diff --git a/README.md b/README.md
index 635f263..a3caea2 100644
--- a/README.md
+++ b/README.md
@@ -1,58 +1,83 @@
-# KyTx
+# Prospero
-**KyTx** is an experimental PlayStation 5 emulator for **macOS on Apple Silicon**, built on
-[KytyPS5](https://github.com/KytyPS5/KytyPS5) (itself based on [Kyty](https://github.com/InoriRus/Kyty)).
+**Prospero** is a fork of [KyTx](https://github.com/TxCsOffc/KyTx) focused on
+making native Apple Silicon PlayStation 5 emulation easier to build, test and use.
+KyTx builds on [KytyPS5](https://github.com/KytyPS5/KytyPS5) and
+[Kyty](https://github.com/InoriRus/Kyty).
It replaces the upstream x86-64 + Rosetta 2 + MoltenVK setup with a native ARM64 build:
- **Guest CPU:** x86-64 game code runs under [FEX](https://github.com/FEX-Emu/FEX) (FEXCore embedded in-process),
not Rosetta 2.
-- **GPU:** RDNA shaders are translated straight to Metal Shading Language and PM4 command streams are executed on a
- native Metal backend (`src/graphics/host_gpu/metal/`). The product path uses no Vulkan, MoltenVK or SPIRV-Cross; the
- inherited Vulkan renderer is kept only as a diagnostic reference.
+- **GPU:** PM4 command streams execute on a native Metal backend (`src/graphics/host_gpu/metal/`).
+ The shader recompiler emits Metal Shading Language directly for supported stages and uses SPIRV-Cross for mesh translation.
> [!IMPORTANT]
-> KyTx is not affiliated with Sony Interactive Entertainment, PlayStation or any game publisher. The project does not
+> Prospero is not affiliated with Sony Interactive Entertainment, PlayStation or any game publisher. The project does not
> distribute games, game data or copyrighted system software. Use only game files that you have obtained legally.
-## Status
+## Compatibility
-Early and unstable. Only one title has been worked on so far:
-
-| Game | State on an M5 Max |
+| Game | Observed behavior |
|---|---|
-| EA SPORTS FC 27 | Boots to the main menu (30 FPS, the game's own cap there) and into a playable match (30-37 FPS; the game asks for 60). Many rendering errors remain, especially in matches; occasional crashes and GPU hangs. |
+| Is This Seat Taken? | On a Mac mini M4, reaches the title menu, Barcelona map and first level. |
+| Gran Turismo 7 1.71 | On a Mac mini M4, boots to the World Map. The landscape and menu labels still render incorrectly. [GT7 findings](docs/bringup/gt7-metal.md) |
+| EA SPORTS FC 27 | In the original KyTx tests on an M5 Max, reached the main menu and a match with rendering errors and occasional crashes or GPU hangs. |
+
+Prospero is an experimental macOS build for Apple Silicon with Metal 4.
+
+## Build and test
+
+Follow the [macOS ARM64 build guide](docs/bringup/macos-arm64.md) for the pinned
+FEXCore revision, dependencies and game launch command. The
+[GT7 bring-up notes](docs/bringup/gt7-metal.md) list the descriptor and shader
+regression tests and explain how to reproduce the Metal captures.
+
+## Open games
+
+Build the native launcher with `bash tools/build_prospero_launcher.sh /path/to/build/kytx`.
+Open `Prospero.app` beside `kyty_emulator`, then add a game directory, .pkg, or
+.fpkg to the library. You can also use Finder's **Open With** menu for package files.
+
+Prospero starts games in a 1920×1080 window and defaults to 1080p Video Out and
+a 60 Hz virtual refresh rate. **Settings → Video** controls the mode reported to
+the game. Games choose their internal render resolution.
-Nothing else has been tested on this fork, including UFC 5 (the target of the fork this one started from).
+For supported PS5 packages, Prospero streams the original file using a compatible
+`read-fpkg` helper. The launcher looks beside the emulator and in
+`../fpkg-reader/read-fpkg` relative to the emulator directory. Use **Settings →
+Package reader** to select a helper elsewhere. The helper and its dependencies
+are separate from the launcher. A game-specific JSON patch can be selected in
+**Game Options**.
-- **Platforms:** macOS on Apple Silicon only. There are no Windows or Linux builds of KyTx; the upstream code for those
- platforms is still in the tree but is not built or tested here.
-- **Requirements:** an Apple Silicon Mac with a Metal 4 capable GPU (developed on an M5 Max, 48 GB).
+## Development priorities
-## Building
+The following areas are proposed priorities for improving the project:
-The macOS arm64 build links FEXCore from a FEX-darwin source/build tree that is **not part of this repository yet**
-(CMake looks for it in `~/Developer/fex-darwin`, overridable with `KYTY_FEX_DIR` / `KYTY_FEX_BUILD_DIR` /
-`KYTY_FEX_SHIMS_DIR`). With that in place:
+- [ ] Document a reproducible ARM64 build and external FEX dependency setup.
+- [ ] Improve shader translation and rendering correctness.
+- [ ] Investigate GPU hangs and runtime stability.
+- [ ] Establish repeatable compatibility and performance tests.
+- [ ] Expand testing across Apple Silicon hardware and additional titles.
-```bash
-cmake --build _Build/macos-arm64 --target kyty_emulator -j$(sysctl -n hw.logicalcpu)
-```
+Diagnostic environment variables, including `KYTY_PASS_TRACE_*`, `KYTY_GPU_BUSY` and `KYTY_GPU_PASS_TIME`, are documented alongside the implementation. Inherited documentation is available in [`docs/`](docs/).
-Run with the Metal backend:
+## Contributing
-```bash
-KYTY_BACKEND=metal KYTY_MSL_ONLY=1 KYTY_VIDEO_OUT_1080P=1 \
- _Build/macos-arm64/kyty_emulator --game /path/to/your/game
-```
+Contributions to graphics correctness, CPU integration, build reproducibility and documentation are welcome.
-## Development notes
+Before submitting a change, describe the problem, keep the patch focused and include reproduction steps or test results where possible. For a bug report, include the macOS version, Apple Silicon model, memory configuration, commit SHA, relevant logs and expected versus actual behavior.
-Diagnostic switches are environment variables documented next to their code (for example `KYTY_PASS_TRACE_*`,
-`KYTY_GPU_BUSY`, `KYTY_GPU_PASS_TIME` in `src/graphics/host_gpu/metal/`). The upstream KytyPS5 documentation is in
-[`docs/`](docs/).
+- [Report an issue](https://github.com/LuizDusky/Prospero/issues)
+- [Browse pull requests](https://github.com/LuizDusky/Prospero/pulls)
+
+Do not attach copyrighted game files, firmware, keys or other material you are not authorized to distribute.
## Credits
+Prospero builds on the work of the open-source emulation community:
+
+- [KyTx](https://github.com/TxCsOffc/KyTx), the immediate upstream project.
+
- [Kyty](https://github.com/InoriRus/Kyty) by InoriRus and contributors.
- [KytyPS5](https://github.com/KytyPS5/KytyPS5) and its contributors.
- The KytyPS5-UFC5 fork by Reece Ketley.
@@ -60,4 +85,10 @@ Diagnostic switches are environment variables documented next to their code (for
## License
-GPL-2.0, as upstream. See [`LICENSE`](LICENSE) and [`LICENSES/`](LICENSES/).
+GPL-2.0, as upstream. See [LICENSE](LICENSE) and [LICENSES/](LICENSES/) for licensing details.
+
+Prospero is an independent project and is not affiliated with Sony Interactive Entertainment, PlayStation or any game publisher. It does not distribute games, game data or copyrighted system software. Use only game files you have obtained legally.
+
+---
+
+
Prospero · Experimental native PS5 emulation for Apple Silicon
diff --git a/docs/branding/prospero.svg b/docs/branding/prospero.svg
new file mode 100644
index 0000000..0458df6
--- /dev/null
+++ b/docs/branding/prospero.svg
@@ -0,0 +1 @@
+Prospero PROSPERO NATIVE PLAYSTATION 5 EMULATION FOR APPLE SILICON
\ No newline at end of file
diff --git a/docs/bringup/fexcore-optional-snapshot.patch b/docs/bringup/fexcore-optional-snapshot.patch
new file mode 100644
index 0000000..f33b659
--- /dev/null
+++ b/docs/bringup/fexcore-optional-snapshot.patch
@@ -0,0 +1,7 @@
+diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
+index 1d6b5e5..d1e3591 100644
+--- a/FEXCore/Source/Interface/Core/Core.cpp
++++ b/FEXCore/Source/Interface/Core/Core.cpp
+@@ -1165 +1165 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_
+- ::Loader::Fex::KytyRecordKnownBlockSnapshot(reinterpret_cast(Bytes), Bytes, CaptureLen);
++ // The embedding host does not provide the optional snapshot recorder.
diff --git a/docs/bringup/gt7-metal.md b/docs/bringup/gt7-metal.md
new file mode 100644
index 0000000..34913aa
--- /dev/null
+++ b/docs/bringup/gt7-metal.md
@@ -0,0 +1,160 @@
+# Prospero · GT7 on native Metal
+
+Gran Turismo 7 1.71 reaches the World Map on a Mac mini M4. The PS5 reference
+shows the coastline, terrain, water, buildings and readable menu labels. The
+Metal capture preserves the coastline and some icons. The red overlay is gone.
+The landscape is still mostly black, and menu labels are missing.
+
+## What changed since KyTx
+
+| Commit | Change |
+| --- | --- |
+| `859671c` | Adapted the Darwin FEX integration and Unity startup. |
+| `2964105`, `d5a3160` | Read embedded vertex attributes and specialize vertex pulling by layout. |
+| `44e1f49`, `a288f2a` | Pinned FEXCore and documented and scripted the ARM64 build. |
+| `52d074d` | Corrected the Metal presenter's sRGB conversion. |
+| `188c68b` | Added an archive adapter for streaming game packages. |
+| `5f07318` | Fixed GT7 startup on ARM64. |
+| `efc1923` | Added GT7 mesh translation and descriptor tracing. Added support for compute cubemap sampling. |
+| `48b42f6`, `bd29a0b` | Preserved guest compute LDS bounds and backed oversized workgroups with private GPU memory. |
+| `0ccde5e` | Added `.pkg` and `.fpkg` import to the Prospero library, using the existing streaming archive adapter and a local `read-fpkg` helper. |
+| `52fa466` | Applied guest component selectors to Metal storage-image writes and fixed sparse store masks. |
+
+KyTx is based on KytyPS5, a fork of Kyty. The
+[macOS ARM64 build guide](macos-arm64.md) identifies the fork's FEX dependency
+and the referenced toolchain.
+
+## What the World Map trace shows
+
+- With `KYTY_LOG_UNBOUND=1`, a baseline GT7 run reported 26 unique non-null
+ image failures. They pointed at the same 1×1 cubemap. All four component
+ selectors request zero. The native Metal bindings now use a compatible
+ six-slice texture with the guest selectors, with no instances of those 26
+ failures in the repeated scene.
+- The device reports 32,768 bytes of threadgroup memory. For GT7's first mesh
+ pipeline, staging three indices in one word reduced Metal's original
+ 34,000-byte requirement without reducing the guest allocation. The native
+ compute path now runs two kernels with their full 65,536 bytes of LDS per
+ group. It can allocate up to 64 MiB for an oversized dispatch, and reports
+ allocation failures with the shader hash.
+- The display pass with Metal function key `4f4e29ec510fee3b` reads an
+ HDR image containing the coastline and a nearly black landscape, then
+ samples a 3D color table before drawing the interface. The table's ABGR
+ descriptor exposed the alpha written into the physical alpha channel as red.
+ The corrected Metal store puts alpha in the physical red channel. The table
+ now reads as black at the origin and has independent RGB axes. In final map
+ captures, a sampled region went from 44,720 of 73,080 pixels with R ≥ 240 and
+ G/B ≤ 16 to zero. The dark HDR input still needs investigation.
+- Capturing the same scene before and after `4aa7c29794420db2` shows the pink
+ sky and the mountain silhouette in its input at `0x920ec00000`, with most of
+ the terrain already black. Its output at `0x9223690000` (color attachment 1)
+ is darker still. `a6c1f1e9298a6dcd` then writes that same attachment. The trace
+ also shows both passes using the scene depth surface at `0x9210c10000`.
+- With the fixes enabled, the output of `4aa7c29794420db2` shows the terrain and
+ trees before the last composition passes. Its 3D inputs at `0x923dba0000`,
+ `0x923fd60000`, `0x926ef76000` and `0x926f296000` trace back to compute writers
+ `1922aae815846978`, `d2a8505196a1078e` and `e297bb22e6dc4335`. The ordered
+ `[RtVolume]` readback found nonzero packed texels in all four images and
+ zero center texels in the two 240×135×128 images. Their expected PS5 values
+ remain unverified.
+- The dispatch for `ed3ba044f1410a06` writes to a 128×128, six-layer descriptor
+ at `0x9296cd0000`, but the old storage allocation was a single 2D texture.
+ Several World Map pixel shaders sampled a six-face cube decoded from guest
+ backing at the same address. That copy had zero nonzero bytes. The experimental
+ GPU array path retains all six layers and the mip chain for the writer and
+ reuses the texture for compatible array and cube readers. It is enabled by
+ default for `PPSA01317`, `APP_VER=01.710.000`. `KYTY_METAL_GPU_ARRAYS=0`
+ disables it for comparison, `=1` enables it for other titles, and
+ `KYTY_GPU_ARRAY_ADDRESS=9296cd0000` isolates this image.
+ The two compute writers at `ed3ba044f1410a06` and `4269bcac84fccc8c` share
+ the same six-layer allocation in the GT7 trace.
+ An M4 test writes the sixth layer through a view of mip level 1 and verifies
+ the stored channels. In the World Map run, 92 sampled bindings of
+ `0x9296cd0000` reused the six-face GPU texture. Trees, roads and terrain became
+ visible. A fixed 4K terrain region went from 7,548 of 7,548 sampled pixels
+ with all channels ≤3 to 1,490 of 7,548. The sample covers 4–27% of image width
+ and 39–64% of image height at an eight-pixel stride. The game reached the map
+ with the default title profile as well. The scene still lacks the reference
+ brightness and menu text.
+- Follow-up runs intermittently stalled in Metal before reaching the cubemap
+ writer. With `KYTY_MTL_SPLIT_OPS=1` and `KYTY_MTL_GPU_TIME=1`, two runs isolated
+ the stalled command buffer to `5b8c099adc368053`, one group of 512 Metal
+ threads serving a 1024-thread guest group with 64 KiB of device-backed LDS.
+ The generated shader includes a threadgroup barrier inside a wave-vote branch.
+ A separate M4 test with the same group dimensions and LDS size passes
+ cross-wave synchronization and workgroup isolation. An isolated source probe
+ replaced the branch predicate with its statically known value. GT7 still
+ stalled at the same dispatch. The original shader remains the default.
+- `KYTY_TRACE_CS_WORD=5b8c099adc368053,0,288` records the four dwords beginning
+ with this shader's loop bound and correlates them with command completion.
+ With `KYTY_TRACE_CS_WORD_GPU=1`, a Metal blit queued before the dispatch also
+ captures the live input. In a failing run the CPU saw `8` at bind time and
+ the GPU read `0x80000514` from the same address. Successful dispatches often
+ completed in about 0.5–0.8 ms with the bound at `8`. The failure occurred
+ with a six-face texture bound. The PM4 and declared compute-buffer write traces
+ did not identify the writer of the changed word.
+- The renderer now snapshots this shader's 368-byte read-only buffer into a
+ separate retained upload allocation. Sampled cubemaps use the matching
+ six-face texture or the guest cube layout if the newest writer has one layer.
+ In a World Map run with both changes enabled the traced shader completed
+ 364 dispatches, with the bound preserved at `8` and six-face views bound.
+ That run still used the guest-backed cubemaps. Set
+ `KYTY_SNAPSHOT_GT7_LIGHT_CONSTANTS=0` or `KYTY_METAL_STRICT_CUBES=0` to isolate
+ the changes in a diagnostic run.
+- The PS5 reference is a final frame. It identifies the matching shoreline and
+ shows which map elements are missing. Comparing intermediate outputs against
+ PS5 requires a capture of the same render target on that platform.
+
+## Checks in the existing build directory
+
+```sh
+build=/path/to/existing/build/kytx
+cmake --build "$build" --target resource_tracking_tests resource_materialization_tests \
+ scalar_provenance_tests shader_vertex_metadata_tests
+ctest --test-dir "$build" --output-on-failure \
+ -R '^(resource_tracking|resource_materialization|scalar_provenance|shader_vertex_metadata)$'
+bash tools/test_metal_msl.sh "$build"
+```
+
+The MSL tests include cubemap sampling, full and sparse storage-image writes,
+packed D16 writes, local LDS counters, and a dispatch over eight groups that
+verifies the final dword of an oversized LDS
+allocation, synchronization across SIMD groups and isolation between
+workgroups. Replay GT7 and inspect the terrain, water, buildings and menu
+text independently to verify the World Map.
+
+For a bounded render-target trace, set `KYTY_LOG_IMAGE_PRODUCER` to the guest
+image address and `KYTY_DUMP_RT_MIN_FLIP` to the start of the 12-frame window.
+`KYTY_DUMP_RT_DRAW=address,pixel_shader,0,1` dumps the target before the matching
+draw and before the next draw to that target. Set `KYTY_DUMP_RT_DIR` to the
+existing scratch directory for the capture. The draw trace reports the color
+attachment index alongside its shader hash and write masks.
+
+## M4 frame timing
+
+Two World Map runs between guest flips 1525 and 1850 measured a median of 8 fps
+(7.5 to 8.5 fps across 35 samples). The game still uses 3840×2160 targets in the
+scene when Video Out advertises 1080p. In the run with `KYTY_MTL_GPU_TIME=1`,
+completed command buffers above the trace threshold of 20 ms reached 65.8 ms
+in this interval. This measurement covers a command buffer, which may contain
+several passes and need not align with one frame. Set `KYTY_GPU_BUSY=1` to
+measure the proportion of wall time occupied by completed Metal work.
+With the same default title profile, the 60 Hz and 120 Hz virtual VBlank runs
+both used 3840×2160 in the World Map. Over guest flips 1500–1599, the two runs
+measured 8.4 and 8.5 fps, respectively, with six samples in each interval.
+
+## World Map recheck with the Prospero video defaults
+
+Launching GT7 1.71 from Prospero on the M4 initialized a 1920×1080 Metal
+drawable and advertised the 1080p Video Out mode with a 60 Hz virtual refresh
+rate. The game's presented texture remained 3840×2160. The coastline, roads,
+tree silhouettes, and parts of a few buildings were visible. The sky and
+backdrop were black, the bay remained too dark to distinguish from the terrain,
+and the shoreline appeared as a wide pale band. Some header icons rendered,
+while their labels and the pavilion labels were missing in the captures.
+
+The navigation replay used `KYTY_AUTO_INPUT_FILE` for Options (`enter`) and
+directional movement, and `KYTY_DUMP_TRIGGER` for the corresponding Metal
+frames. Left and right input changed which panel was visible. The panels stayed
+unlabeled, and Options did not produce a readable GT Menu. The available PS5
+frame shows the expected scene and menu; it was used as a visual reference.
diff --git a/docs/bringup/macos-arm64.md b/docs/bringup/macos-arm64.md
new file mode 100644
index 0000000..2b98faa
--- /dev/null
+++ b/docs/bringup/macos-arm64.md
@@ -0,0 +1,45 @@
+# macOS ARM64 bring-up
+
+This experimental build uses [alamshafil/fexcore-darwin](https://github.com/alamshafil/fexcore-darwin)
+at revision `eee10cc54a173e79ee16e2169cd4157c7269921b`. The compatibility patch beside this
+document removes a diagnostic callback specific to that FEX port's original embedding project.
+Keep the KyTx and FEXCore checkouts adjacent as `source` and `fexcore`.
+Install native CMake, Ninja and SPIRV-Cross via Homebrew. Xcode is required.
+
+From the parent directory, if the FEXCore checkout is missing, fetch it once:
+
+```sh
+git clone https://github.com/alamshafil/fexcore-darwin.git fexcore
+git -C fexcore checkout --detach eee10cc54a173e79ee16e2169cd4157c7269921b
+```
+
+Configure and build in the existing `build` directory:
+
+```sh
+bash source/tools/build_prospero_macos.sh build
+```
+
+The script checks the FEXCore revision, applies the compatibility patch once,
+and verifies the arm64 executable signature. Set `CMAKE_BUILD_PARALLEL_LEVEL`
+to change the default of four build jobs. The reference toolchain is Xcode
+27.2 (27B52), CMake 4.5.1 and Ninja 1.13.2. The guide reproduces the source and
+build options. Toolchain or SDK changes can yield different binaries.
+
+From `build/kytx`, run with a legally obtained game directory:
+
+```sh
+KYTY_BACKEND=metal KYTY_MSL_ONLY=1 KYTY_MSL_GDS=1 KYTY_VIDEO_OUT_1080P=1 \
+ ./kyty_emulator --game /path/to/game
+```
+
+On a Mac mini M4 with 16 GiB and macOS 27.2.1, *Is This Seat Taken?*
+(PPSA37001) reached the title menu, the Barcelona map and the first level.
+Metal frame captures showed readable text and no recurrence of the reported
+purple rectangle or corruption on the first level's Perfect 6/6 results screen.
+The focused vertex layout cache-key regression passed. The full `shader_cfg`
+suite failed the same SPIR-V repeated-export check before and after the fix.
+Audio quality and regression coverage for other titles remain unverified.
+
+The native attribute path supports unswizzled descriptors within a bounded range
+of argument buffer slots. Cross-thread exception delivery on this Darwin path is
+cooperative at guest waits.
diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt
index c6978a7..cc629e0 100644
--- a/src/common/CMakeLists.txt
+++ b/src/common/CMakeLists.txt
@@ -29,6 +29,10 @@ target_link_libraries(common
ZArchive::zarchive
)
+if(APPLE)
+ target_link_libraries(common PRIVATE nlohmann_json::nlohmann_json)
+endif()
+
get_property(inc_headers TARGET common PROPERTY INCLUDE_DIRECTORIES)
set(check_headers ${CMAKE_CURRENT_SOURCE_DIR})
diff --git a/src/common/archive.cpp b/src/common/archive.cpp
index 4d6f56a..0f9990b 100644
--- a/src/common/archive.cpp
+++ b/src/common/archive.cpp
@@ -4,6 +4,9 @@
#include
#include
+#include
+#include
+#include
#include
#include
#include
@@ -13,6 +16,18 @@
#include
#include
+#if defined(__APPLE__)
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+extern char** environ;
+#endif
+
// POSIX hosts and MinGW's pthread-backed libstdc++ have cancellable condition waits.
// MSVC/ClangCL and MinGW's native Win32 threading backend do not use pthread waits.
#if !defined(_WIN32) || defined(_GLIBCXX_GCC_GTHR_POSIX_H)
@@ -87,12 +102,203 @@ std::shared_ptr OpenZArchive(const std::filesystem::path& path) {
return reader ? std::make_shared(std::move(reader)) : nullptr;
}
+#if defined(__APPLE__)
+// The optional local helper owns the package decoder. The socket carries only
+// the file index and bounded offset reads of the original, read-only package.
+class FpkgArchiveReader final: public ArchiveReader {
+public:
+ FpkgArchiveReader(int socket, pid_t child): m_socket(socket), m_child(child) {}
+ ~FpkgArchiveReader() override {
+ close(m_socket);
+ while (waitpid(m_child, nullptr, 0) < 0 && errno == EINTR) {}
+ }
+
+ bool LoadIndex() {
+ uint32_t size = 0;
+ if (!Receive(&size, sizeof(size)) || size == 0 || size > MaxMessageSize) {
+ kill(m_child, SIGTERM);
+ return false;
+ }
+ std::string data(size, '\0');
+ if (!Receive(data.data(), size)) {
+ kill(m_child, SIGTERM);
+ return false;
+ }
+
+ const auto index = nlohmann::json::parse(data, nullptr, false);
+ if (!index.is_array()) {
+ return false;
+ }
+ m_files.emplace("", Entry {0, 0, false});
+ for (uint32_t i = 0; i < index.size(); ++i) {
+ const auto& member = index[i];
+ if (!member.is_object() || !member.contains("path") || !member.contains("size") ||
+ !member["path"].is_string() || !member["size"].is_number_unsigned()) {
+ return false;
+ }
+ const auto& path = member["path"].get_ref();
+ if (!ValidPath(path) ||
+ !m_files.emplace(path, Entry {i, member["size"].get(), true}).second) {
+ return false;
+ }
+ for (auto parent = path.rfind('/'); parent != std::string::npos;) {
+ const auto [dir, added] = m_files.try_emplace(path.substr(0, parent), Entry {0, 0, false});
+ if (dir->second.is_file) {
+ return false;
+ }
+ if (!added) {
+ break;
+ }
+ parent = path.rfind('/', parent - 1);
+ }
+ }
+ for (const auto& [path, entry]: m_files) {
+ if (path.empty()) {
+ continue;
+ }
+ const auto split = path.rfind('/');
+ m_children[split == std::string::npos ? "" : path.substr(0, split)].push_back(
+ {path.substr(split == std::string::npos ? 0 : split + 1), entry.is_file});
+ }
+ return true;
+ }
+
+ std::optional Find(std::string_view member) override {
+ const auto it = m_files.find(member);
+ return it == m_files.end() ? std::nullopt : std::optional {it->second};
+ }
+
+ std::vector List(std::string_view member) override {
+ const auto it = m_children.find(member);
+ return it == m_children.end() ? std::vector {} : it->second;
+ }
+
+ uint64_t Read(uint64_t id, uint64_t offset, uint32_t size, void* data) override {
+ struct Request {
+ uint32_t file;
+ uint32_t size;
+ uint64_t offset;
+ };
+ static_assert(sizeof(Request) == 16);
+ const Request request {static_cast(id), size, offset};
+ uint32_t received = 0;
+ if (!m_failed && size <= MaxMessageSize && Send(&request, sizeof(request)) &&
+ Receive(&received, sizeof(received)) && received <= size && Receive(data, received)) {
+ return received;
+ }
+ m_failed = true;
+ return 0;
+ }
+
+private:
+ static constexpr uint32_t MaxMessageSize = 8u << 20;
+
+ static bool ValidPath(std::string_view path) {
+ if (path.empty() || path.back() == '/' || path.find('\\') != path.npos ||
+ path.find('\0') != path.npos) {
+ return false;
+ }
+ while (!path.empty()) {
+ const auto separator = path.find('/');
+ const auto component = path.substr(0, separator);
+ if (component.empty() || component == "." || component == "..") {
+ return false;
+ }
+ path.remove_prefix(separator == path.npos ? path.size() : separator + 1);
+ }
+ return true;
+ }
+
+ bool Send(const void* source, size_t size) {
+ auto* bytes = static_cast(source);
+ while (size != 0) {
+ const auto sent = send(m_socket, bytes, size, 0);
+ if (sent < 0 && errno == EINTR) {
+ continue;
+ }
+ if (sent <= 0) {
+ return false;
+ }
+ bytes += sent;
+ size -= static_cast(sent);
+ }
+ return true;
+ }
+
+ bool Receive(void* destination, size_t size) {
+ auto* bytes = static_cast(destination);
+ while (size != 0) {
+ const auto got = recv(m_socket, bytes, size, 0);
+ if (got < 0 && errno == EINTR) {
+ continue;
+ }
+ if (got <= 0) {
+ return false;
+ }
+ bytes += got;
+ size -= static_cast(got);
+ }
+ return true;
+ }
+
+ int m_socket;
+ pid_t m_child;
+ bool m_failed = false; // Reads run on the single archive I/O thread.
+ std::map> m_files;
+ std::map, std::less<>> m_children;
+};
+
+std::shared_ptr OpenFpkg(const std::filesystem::path& path) {
+ const char* helper = std::getenv("KYTY_FPKG_READER");
+ if (helper == nullptr || helper[0] != '/' || access(helper, X_OK) != 0) {
+ std::fprintf(stderr, "Set KYTY_FPKG_READER to the executable path of a local FPKG reader.\n");
+ return {};
+ }
+ int sockets[2];
+ if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) != 0) {
+ return {};
+ }
+ const timeval timeout {30, 0};
+ const int no_sigpipe = 1;
+ int result = fcntl(sockets[0], F_SETFD, FD_CLOEXEC) |
+ fcntl(sockets[1], F_SETFD, FD_CLOEXEC) |
+ setsockopt(sockets[0], SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe, sizeof(no_sigpipe)) |
+ setsockopt(sockets[0], SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) |
+ setsockopt(sockets[0], SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
+ posix_spawn_file_actions_t actions;
+ pid_t child = 0;
+ if (result == 0 && (result = posix_spawn_file_actions_init(&actions)) == 0) {
+ result = posix_spawn_file_actions_adddup2(&actions, sockets[1], STDIN_FILENO) |
+ posix_spawn_file_actions_adddup2(&actions, sockets[1], STDOUT_FILENO);
+ if (result == 0) {
+ char mode[] = "serve";
+ char* const args[] = {const_cast(helper), mode, const_cast(path.c_str()), nullptr};
+ result = posix_spawn(&child, helper, &actions, nullptr, args, environ);
+ }
+ posix_spawn_file_actions_destroy(&actions);
+ }
+ close(sockets[1]);
+ if (result != 0) {
+ close(sockets[0]);
+ return {};
+ }
+ auto reader = std::make_shared(sockets[0], child);
+ return reader->LoadIndex() ? reader : nullptr;
+}
+#endif
+
struct ArchiveFormat {
std::string_view extension;
std::shared_ptr (*open)(const std::filesystem::path&);
};
-constexpr ArchiveFormat Formats[] = {{".zar", OpenZArchive}};
+constexpr ArchiveFormat Formats[] = {
+ {".zar", OpenZArchive},
+#if defined(__APPLE__)
+ {".pkg", OpenFpkg},
+ {".fpkg", OpenFpkg},
+#endif
+};
using NativeView = std::basic_string_view;
const ArchiveFormat* FindFormat(NativeView path) {
diff --git a/src/emulator.h b/src/emulator.h
index cf8f345..c6b7c03 100644
--- a/src/emulator.h
+++ b/src/emulator.h
@@ -5,6 +5,11 @@
#include "common/stringUtils.h"
#include
+#include
+
+namespace Common {
+class ArchiveReader;
+}
namespace Emulator {
@@ -13,6 +18,7 @@ struct RunOptions {
std::filesystem::path app0_dir;
std::filesystem::path elf;
std::filesystem::path game_patch;
+ std::shared_ptr game_archive;
};
void Run(const RunOptions& options);
diff --git a/src/graphics/guest_gpu/gpu_format.cpp b/src/graphics/guest_gpu/gpu_format.cpp
index 4fdaaac..38172b4 100644
--- a/src/graphics/guest_gpu/gpu_format.cpp
+++ b/src/graphics/guest_gpu/gpu_format.cpp
@@ -41,6 +41,7 @@ constexpr FormatInfo kFormatInfo[] = {
{BufferFormat::k16_16Float, 4, 0, 4, true, false},
{BufferFormat::k11_11_10UInt, 4, 0, 4, true, true},
{BufferFormat::k11_11_10Float, 4, 0, 4, true, false},
+ {BufferFormat::k10_11_11Float, 4, 0, 4, true, false},
{BufferFormat::k10_10_10_2UNorm, 4, 0, 4, true, false},
{BufferFormat::k10_10_10_2UInt, 4, 0, 4, true, true},
{BufferFormat::k8_8_8_8UNorm, 4, 0, 4, true, false},
diff --git a/src/graphics/host_gpu/metal/metalAddressSpace.h b/src/graphics/host_gpu/metal/metalAddressSpace.h
index 289c6ca..403f41a 100644
--- a/src/graphics/host_gpu/metal/metalAddressSpace.h
+++ b/src/graphics/host_gpu/metal/metalAddressSpace.h
@@ -2,7 +2,16 @@
#include
+#ifdef __OBJC__
+#import
+#endif
+
namespace Libs::Graphics::Metal {
+inline constexpr uint32_t GuestAddressLeafBits = 10;
+#ifdef __OBJC__
+id BindGuestAddressSpaceBuffer(bool mesh_stage);
+#endif
+
// Native Metal page table for guest scalar/flat addresses. Call while the
// consuming encoder is active; all indirect resources are declared resident.
uint64_t BindGuestAddressSpace();
diff --git a/src/graphics/host_gpu/metal/metalAddressSpace.mm b/src/graphics/host_gpu/metal/metalAddressSpace.mm
index a685e6e..ce2eb7a 100644
--- a/src/graphics/host_gpu/metal/metalAddressSpace.mm
+++ b/src/graphics/host_gpu/metal/metalAddressSpace.mm
@@ -16,7 +16,7 @@
namespace Libs::Graphics::Metal {
namespace {
constexpr uint64_t kPageSize = 1ull << 14;
-constexpr uint64_t kLeafEntries = 1ull << 10;
+constexpr uint64_t kLeafEntries = 1ull << GuestAddressLeafBits;
constexpr uint64_t kLowerSize = 1ull << 40;
constexpr uint64_t kPackedSize = kLowerSize + LibKernel::Memory::kExtendedMemorySize;
constexpr uint64_t kRootEntries = kPackedSize / (kPageSize * kLeafEntries);
@@ -33,7 +33,7 @@ uint64_t PackedAddress(uint64_t address) {
class GuestAddressSpace {
public:
- uint64_t Bind() {
+ id Bind(bool mesh_stage) {
std::vector mappings;
uint64_t generation = m_generation;
if (LibKernel::Memory::GetGuestBackingMappings(generation, mappings)) {
@@ -48,22 +48,22 @@ uint64_t Bind() {
}
if (!ok) {
std::fprintf(stderr, "[MetalBda] could not publish guest mapping generation %llu\n", static_cast(generation));
- return 0;
+ return nil;
}
m_generation = generation;
}
- if (m_root == nil) return 0;
+ if (m_root == nil) return nil;
// The table stores raw GPU addresses, so binding the root alone cannot
// make the leaves or shared physical backing resident. Encoders retain
// this immutable version while newer mappings create a new version.
if (auto encoder = MetalContext::Instance().GetActiveRenderEncoder()) {
- [encoder useResources:m_resources.data() count:m_resources.size() usage:MTLResourceUsageRead
- stages:MTLRenderStageVertex | MTLRenderStageFragment];
+ const auto stages = mesh_stage ? MTLRenderStageMesh : MTLRenderStageVertex | MTLRenderStageFragment;
+ [encoder useResources:m_resources.data() count:m_resources.size() usage:MTLResourceUsageRead stages:stages];
}
if (auto encoder = MetalContext::Instance().GetActiveComputeEncoder()) {
[encoder useResources:m_resources.data() count:m_resources.size() usage:MTLResourceUsageRead];
}
- return m_root.gpuAddress;
+ return m_root;
}
private:
@@ -142,9 +142,13 @@ bool Rebuild(const std::vector& mappings
};
}
-uint64_t BindGuestAddressSpace() {
+id BindGuestAddressSpaceBuffer(bool mesh_stage) {
// Graphics/compute encoding is serialized by MetalRenderer::m_mutex.
static GuestAddressSpace space;
- return space.Bind();
+ return space.Bind(mesh_stage);
+}
+
+uint64_t BindGuestAddressSpace() {
+ return BindGuestAddressSpaceBuffer(false).gpuAddress;
}
}
diff --git a/src/graphics/host_gpu/metal/metalDraw.h b/src/graphics/host_gpu/metal/metalDraw.h
index 5c57b11..1bc1432 100644
--- a/src/graphics/host_gpu/metal/metalDraw.h
+++ b/src/graphics/host_gpu/metal/metalDraw.h
@@ -136,6 +136,8 @@ class MetalDrawExecutor {
// Draw with the arguments read from a GPU buffer (DrawPrimitivesIndirectArguments layout).
// Defer diagnostic pass splitting until the last element of a multi-draw;
// ending its encoder earlier would discard pipeline/resource state for the rest.
+ bool DrawMesh(uint32_t groups, uint32_t instances, uint32_t threads);
+
void DrawIndirect(Prospero::PrimitiveType prim_type, id args_buffer, uint64_t args_offset,
bool last_in_batch = true);
void DrawIndexedIndirect(Prospero::PrimitiveType prim_type, MTLIndexType index_type, id index_buffer,
diff --git a/src/graphics/host_gpu/metal/metalDraw.mm b/src/graphics/host_gpu/metal/metalDraw.mm
index 6f02018..dbf8eb8 100644
--- a/src/graphics/host_gpu/metal/metalDraw.mm
+++ b/src/graphics/host_gpu/metal/metalDraw.mm
@@ -399,7 +399,8 @@ MTLIndexType TranslateIndexType(Prospero::IndexType type) {
}
id encoder = MetalContext::Instance().GetActiveRenderEncoder();
if (encoder) {
- [encoder useResource:resource usage:usage stages:MTLRenderStageVertex | MTLRenderStageFragment];
+ [encoder useResource:resource usage:usage stages:MTLRenderStageVertex |
+ MTLRenderStageFragment | MTLRenderStageMesh];
}
id c_encoder = MetalContext::Instance().GetActiveComputeEncoder();
if (c_encoder) {
@@ -446,6 +447,34 @@ static void SplitAfterDraw() {
}
}
+ if (prim_type == Prospero::PrimitiveType::kTriFan && vertex_count > 3) {
+ // Metal has no triangle fan topology. Index each triangle back to the
+ // first guest vertex while preserving the shader's vertex/instance IDs.
+ const auto index_count = static_cast(vertex_count - 2u) * 3u;
+ const auto indices = MetalBufferManager::Instance().AllocateDynamic(index_count * sizeof(uint32_t),
+ alignof(uint32_t));
+ if (!indices.IsValid() || indices.cpu_addr == nullptr) {
+ return;
+ }
+ auto* data = static_cast(indices.cpu_addr);
+ for (uint32_t i = 1; i < vertex_count - 1u; ++i) {
+ *data++ = 0;
+ *data++ = i;
+ *data++ = i + 1u;
+ }
+ PassTimerItem();
+ [encoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
+ indexCount:index_count
+ indexType:MTLIndexTypeUInt32
+ indexBuffer:indices.buffer
+ indexBufferOffset:indices.offset
+ instanceCount:instance_count
+ baseVertex:first_vertex
+ baseInstance:first_instance];
+ SplitAfterDraw();
+ return;
+ }
+
MTLPrimitiveType mtl_prim = TranslatePrimitiveType(prim_type);
// RECTLIST: three corners define a rectangle; the vertex shader wrapper synthesises vertex 3, so a single
// rectangle is drawn as a four-vertex strip (two triangles).
@@ -462,6 +491,20 @@ static void SplitAfterDraw() {
SplitAfterDraw();
}
+bool MetalDrawExecutor::DrawMesh(uint32_t groups, uint32_t instances, uint32_t threads) {
+ auto encoder = MetalContext::Instance().GetActiveRenderEncoder();
+ if (!encoder || !m_has_render_pipeline || m_scissor_empty || groups == 0 || instances == 0) {
+ return false;
+ }
+ FaultSignpost(encoder);
+ PassTimerItem();
+ [encoder drawMeshThreadgroups:MTLSizeMake(groups, instances, 1)
+ threadsPerObjectThreadgroup:MTLSizeMake(0, 0, 0)
+ threadsPerMeshThreadgroup:MTLSizeMake(threads, 1, 1)];
+ SplitAfterDraw();
+ return true;
+}
+
void MetalDrawExecutor::DrawIndirect(Prospero::PrimitiveType prim_type, id args_buffer,
uint64_t args_offset, bool last_in_batch) {
FaultSignpost(MetalContext::Instance().GetActiveRenderEncoder());
diff --git a/src/graphics/host_gpu/metal/metalPipeline.h b/src/graphics/host_gpu/metal/metalPipeline.h
index c4dff63..bf97ea0 100644
--- a/src/graphics/host_gpu/metal/metalPipeline.h
+++ b/src/graphics/host_gpu/metal/metalPipeline.h
@@ -106,6 +106,7 @@ struct MetalRenderPipelineKey {
MTLPixelFormat stencil_format = static_cast(0);
uint32_t sample_count = 1;
uint32_t primitive_type = 0;
+ uint32_t mesh_threads = 0;
bool operator==(const MetalRenderPipelineKey& other) const noexcept;
};
diff --git a/src/graphics/host_gpu/metal/metalPipeline.mm b/src/graphics/host_gpu/metal/metalPipeline.mm
index f17a9dd..20314a2 100644
--- a/src/graphics/host_gpu/metal/metalPipeline.mm
+++ b/src/graphics/host_gpu/metal/metalPipeline.mm
@@ -70,7 +70,8 @@ void MaskUnwrittenColorAttachments(MetalRenderPipelineKey& key, uint32_t color_e
if (vs_hash != other.vs_hash || fs_hash != other.fs_hash ||
color_target_count != other.color_target_count ||
depth_format != other.depth_format || stencil_format != other.stencil_format ||
- sample_count != other.sample_count || primitive_type != other.primitive_type) {
+ sample_count != other.sample_count || primitive_type != other.primitive_type ||
+ mesh_threads != other.mesh_threads) {
return false;
}
for (uint32_t i = 0; i < color_target_count; ++i) {
@@ -88,6 +89,7 @@ void MaskUnwrittenColorAttachments(MetalRenderPipelineKey& key, uint32_t color_e
size_t MetalRenderPipelineKeyHash::operator()(const MetalRenderPipelineKey& k) const noexcept {
size_t h = k.vs_hash ^ (k.fs_hash << 1);
+ h ^= static_cast(k.mesh_threads) + 0x9e3779b9 + (h << 6) + (h >> 2);
h ^= static_cast(k.depth_format) + 0x9e3779b9 + (h << 6) + (h >> 2);
h ^= static_cast(k.stencil_format) + 0x9e3779b9 + (h << 6) + (h >> 2);
h ^= static_cast(k.color_target_count) + 0x9e3779b9 + (h << 6) + (h >> 2);
@@ -444,7 +446,7 @@ StencilFace ConvertGuestStencilFace(uint8_t compare, uint8_t fail_op, uint8_t zp
// KYTY_DEBUG_PS_ANY=1 widens the gate from RG11B10Float targets to every color target.
static const bool s_debug_ps_any = KYTY_ENV("KYTY_DEBUG_PS_ANY") != nullptr;
const bool debug_ps_active =
- s_debug_ps_enabled && key.color_target_count > 0 &&
+ key.mesh_threads == 0 && s_debug_ps_enabled && key.color_target_count > 0 &&
(s_debug_ps_any || key.color_targets[0].pixel_format == MTLPixelFormatRG11B10Float) &&
MetalDrawSequence() >= s_debug_ps_after;
// Substitute through a distinct cache key: otherwise a pipeline built before the
@@ -485,7 +487,7 @@ StencilFace ConvertGuestStencilFace(uint8_t compare, uint8_t fail_op, uint8_t zp
fragment_function = s_debug_ps_func;
}
}
- if (s_debug_quad) {
+ if (s_debug_quad && key.mesh_threads == 0) {
dispatch_once_t once = 0;
(void)once;
if (s_debug_vs == nil || s_debug_ps == nil) {
@@ -536,12 +538,23 @@ StencilFace ConvertGuestStencilFace(uint8_t compare, uint8_t fail_op, uint8_t zp
desc.vertexFunction = vertex_function;
desc.fragmentFunction = fragment_function;
+ MTLMeshRenderPipelineDescriptor* mesh_desc = nil;
+ if (key.mesh_threads != 0) {
+ mesh_desc = [MTLMeshRenderPipelineDescriptor new];
+ mesh_desc.meshFunction = vertex_function;
+ mesh_desc.fragmentFunction = fragment_function;
+ mesh_desc.maxTotalThreadsPerMeshThreadgroup = key.mesh_threads;
+ mesh_desc.depthAttachmentPixelFormat = key.depth_format;
+ mesh_desc.stencilAttachmentPixelFormat = key.stencil_format;
+ mesh_desc.rasterSampleCount = std::max(key.sample_count, 1u);
+ }
for (uint32_t i = 0; i < key.color_target_count; ++i) {
const auto& color_desc = key.color_targets[i];
if (color_desc.pixel_format == MTLPixelFormatInvalid) {
continue;
}
- MTLRenderPipelineColorAttachmentDescriptor* color_att = desc.colorAttachments[i];
+ MTLRenderPipelineColorAttachmentDescriptor* color_att =
+ mesh_desc != nil ? mesh_desc.colorAttachments[i] : desc.colorAttachments[i];
color_att.pixelFormat = color_desc.pixel_format;
color_att.writeMask = color_desc.write_mask;
color_att.blendingEnabled = color_desc.blending_enabled ? YES : NO;
@@ -581,16 +594,20 @@ StencilFace ConvertGuestStencilFace(uint8_t compare, uint8_t fail_op, uint8_t zp
}
NSError* error = nil;
- id pipeline = [device newRenderPipelineStateWithDescriptor:desc error:&error];
+ id pipeline = mesh_desc != nil
+ ? [device newRenderPipelineStateWithMeshDescriptor:mesh_desc options:MTLPipelineOptionNone
+ reflection:nil error:&error]
+ : [device newRenderPipelineStateWithDescriptor:desc error:&error];
if (!pipeline) {
static std::atomic s_pipeline_failures {0};
const uint32_t count = s_pipeline_failures.fetch_add(1);
if (count < 20) {
std::fprintf(stderr,
- "[MetalPipeline] create failed (%u) vs=0x%016llx ps=0x%016llx fmt=%u: %s\n",
+ "[MetalPipeline] create failed (%u) vs=0x%016llx ps=0x%016llx fmt=%u threadgroup_limit=%lu: %s\n",
count, static_cast(key.vs_hash),
static_cast(key.fs_hash),
static_cast(key.color_targets[0].pixel_format),
+ static_cast(device.maxThreadgroupMemoryLength),
error ? [[error localizedDescription] UTF8String] : "Unknown error");
}
LOGF_COLOR(Log::Color::BrightRed, "Metal: Failed to create render pipeline state: %s\n",
@@ -623,6 +640,10 @@ StencilFace ConvertGuestStencilFace(uint8_t compare, uint8_t fail_op, uint8_t zp
desc.label = [NSString stringWithFormat:@"CS %016llx", (unsigned long long)cs_hash];
id pipeline = [device newComputePipelineStateWithDescriptor:desc options:MTLPipelineOptionNone reflection:nil error:&error];
if (!pipeline) {
+ std::fprintf(stderr, "[MetalPipeline] compute creation failed cs=0x%016llx threadgroup_limit=%lu: %s\n",
+ static_cast(cs_hash),
+ static_cast(device.maxThreadgroupMemoryLength),
+ error ? [[error localizedDescription] UTF8String] : "Unknown error");
LOGF_COLOR(Log::Color::BrightRed, "Metal: Failed to create compute pipeline state: %s\n",
error ? [[error localizedDescription] UTF8String] : "Unknown error");
return nil;
diff --git a/src/graphics/host_gpu/metal/metalPresenter.mm b/src/graphics/host_gpu/metal/metalPresenter.mm
index 663b330..61d8d86 100644
--- a/src/graphics/host_gpu/metal/metalPresenter.mm
+++ b/src/graphics/host_gpu/metal/metalPresenter.mm
@@ -29,8 +29,16 @@
uint32_t pitch;
uint32_t format;
uint32_t is_tiled;
+ uint32_t encode_srgb;
};
+static bool TextureReadNeedsSrgbEncoding(MTLPixelFormat format) {
+ // Metal reads sRGB textures as linear values. The unorm drawable expects
+ // display-encoded values, so restore the transfer curve just like for linear float targets.
+ return format == MTLPixelFormatRGBA8Unorm_sRGB || format == MTLPixelFormatBGRA8Unorm_sRGB ||
+ format == MTLPixelFormatRG11B10Float || format == MTLPixelFormatRGBA16Float;
+}
+
struct MetalPresenter::Impl {
SDL_Window* window = nullptr;
SDL_MetalView metal_view = nullptr;
@@ -64,6 +72,7 @@ bool InitPipeline(id device) {
" uint pitch;\n"
" uint format;\n"
" uint is_tiled;\n"
+ " uint encode_srgb;\n"
"};\n"
"inline float decode_r11(uint val) {\n"
" uint exponent = (val >> 6u) & 0x1Fu;\n"
@@ -104,10 +113,7 @@ bool InitPipeline(id device) {
" }\n"
" float4 c = src.read(uint2(tex_x, tex_y));\n"
" float3 rgb = clamp(c.rgb, 0.0, 1.0);\n"
- " // Display-referred formats (the game's final composite: 8-bit and RGB10A2 flip images) are already\n"
- " // encoded for the display, so they are copied straight; only linear HDR targets (RG11B10F, RGBA16F)\n"
- " // get the sRGB transfer function.\n"
- " if (u.format == 92u || u.format == 115u) {\n"
+ " if (u.encode_srgb != 0u) {\n"
" rgb = select(rgb * 12.92, 1.055 * pow(rgb, float3(1.0 / 2.4)) - 0.055, rgb > 0.0031308);\n"
" }\n"
" return float4(rgb, 1.0);\n"
@@ -336,6 +342,7 @@ bool InitPipeline(id device) {
if (align < 64) align = 64;
u.pitch = static_cast((u.width * 4 + align - 1) & ~(align - 1));
u.format = static_cast(src_tex.pixelFormat);
+ u.encode_srgb = TextureReadNeedsSrgbEncoding(src_tex.pixelFormat);
static int s_env_flip_y = -1;
if (s_env_flip_y == -1) {
const char* env = std::getenv("KYTY_FLIP_Y");
@@ -537,6 +544,7 @@ bool InitPipeline(id device) {
u.height = height;
u.pitch = static_cast(row_bytes);
u.format = static_cast(src.pixelFormat);
+ u.encode_srgb = TextureReadNeedsSrgbEncoding(src.pixelFormat);
u.is_tiled = 0;
id cmd = [queue commandBuffer];
diff --git a/src/graphics/host_gpu/metal/metalRenderer.h b/src/graphics/host_gpu/metal/metalRenderer.h
index 5a4233d..eb8a089 100644
--- a/src/graphics/host_gpu/metal/metalRenderer.h
+++ b/src/graphics/host_gpu/metal/metalRenderer.h
@@ -141,6 +141,7 @@ void RegisterComputeWrittenImage(uint64_t addr, void* texture);
// Check if native Metal backend is enabled (e.g. KYTY_BACKEND=metal or KYTY_USE_METAL=1)
[[nodiscard]] bool UseNativeMetalBackend() noexcept;
+[[nodiscard]] uint32_t NativeMetalThreadgroupLimitDwords();
// Global data share, as seen by compute kernels (ds_append/ds_consume counters). The guest moves counters between GDS and
// memory with DMA_DATA packets; the copies are ordered with the GPU work on the Metal queue.
diff --git a/src/graphics/host_gpu/metal/metalRenderer.mm b/src/graphics/host_gpu/metal/metalRenderer.mm
index 24ffd44..ea98f3f 100644
--- a/src/graphics/host_gpu/metal/metalRenderer.mm
+++ b/src/graphics/host_gpu/metal/metalRenderer.mm
@@ -5,6 +5,7 @@
#include "graphics/presentation/traceWindow.h"
#include "graphics/host_gpu/metal/metalBuffer.h"
#include "graphics/host_gpu/metal/metalIndirect.h"
+#include "graphics/host_gpu/metal/metalOrder.h"
#include "graphics/host_gpu/metal/metalPresenter.h"
#include "graphics/host_gpu/metal/metalSampler.h"
#include "graphics/host_gpu/metal/metalTiling.h"
@@ -18,6 +19,7 @@
#include "graphics/shader/recompiler/backend/msl/MslEmitter.h"
#include "common/logging/log.h"
#include "kernel/memory.h"
+#include "loader/systemContent.h"
#include
#include
@@ -125,6 +127,18 @@ static MetalBufferAllocation SnapshotBytes(const MetalBufferAllocation& src, uin
return dyn.IsValid() ? dyn : src;
}
+static bool SnapshotGt7LightingConstants(uint64_t shader_hash, size_t slot, size_t size,
+ const ShaderRecompiler::IR::BufferResource& resource) {
+ static const bool enabled = [] {
+ const char* value = KYTY_ENV("KYTY_SNAPSHOT_GT7_LIGHT_CONSTANTS");
+ return value == nullptr || std::strcmp(value, "0") != 0;
+ }();
+ // GT7's lighting pass receives 92 dwords of scalar constants in a recycled
+ // guest upload ring. A queued read of dword 72 can see the next upload's data.
+ return enabled && shader_hash == 0x5b8c099adc368053ull && slot == 0 && size == 92 * sizeof(uint32_t) &&
+ resource.read && !resource.written && !resource.atomic;
+}
+
// Sample the range-copy kernel's output in GPU order. CPU reads of the live matrix pool at
// encode time are not evidence of what the later vertex shader consumes. This probe copies
// selected output rows immediately after the dispatch, then checks them only on completion.
@@ -194,11 +208,13 @@ static void ProbeSkinUpload(const std::array& buffers
static bool s_rect_indexed = false;
// Zero-filled stand-in for an image slot whose guest descriptor is empty (a null V# reads as zeros on RDNA). The
// texture type must match the shader's declaration, so it is keyed by dimension, cube, numeric class and storage.
-static id NullImageFor(const ShaderRecompiler::IR::ImageResource& img, bool storage) {
+static id NullImageFor(const ShaderRecompiler::IR::ImageResource& img, bool storage,
+ bool unit_cube = false) {
using Dim = ShaderRecompiler::Decoder::ImageDimension;
static std::unordered_map> s_cache;
const uint32_t key = (static_cast(img.dimension) << 8) | (img.cube ? 0x80u : 0u) |
- (static_cast(img.numeric_class) << 1) | (storage ? 1u : 0u);
+ (static_cast(img.numeric_class) << 1) | (storage ? 1u : 0u) |
+ (unit_cube ? 0x10000u : 0u);
if (const auto it = s_cache.find(key); it != s_cache.end()) {
return it->second;
}
@@ -206,9 +222,9 @@ static void ProbeSkinUpload(const std::array& buffers
switch (img.dimension) {
case Dim::Dim1D: type = MTLTextureType1D; break;
case Dim::Dim1DArray: type = MTLTextureType1DArray; break;
- case Dim::Dim2D: type = img.cube ? MTLTextureTypeCube : MTLTextureType2D; break;
+ case Dim::Dim2D: type = img.cube ? MTLTextureType2DArray : MTLTextureType2D; break;
case Dim::Dim3D: type = MTLTextureType3D; break;
- case Dim::Dim2DArray: type = img.cube ? MTLTextureTypeCubeArray : MTLTextureType2DArray; break;
+ case Dim::Dim2DArray: type = MTLTextureType2DArray; break;
default: s_cache[key] = nil; return nil; // multisampled: no stand-in
}
MTLPixelFormat fmt = MTLPixelFormatRGBA8Unorm;
@@ -217,13 +233,26 @@ static void ProbeSkinUpload(const std::array& buffers
MTLTextureDescriptor* td = [[MTLTextureDescriptor alloc] init];
td.textureType = type;
td.pixelFormat = fmt;
- td.width = 4;
- td.height = (type == MTLTextureType1D || type == MTLTextureType1DArray) ? 1 : 4;
+ td.width = unit_cube ? 1u : 4u;
+ td.height = (type == MTLTextureType1D || type == MTLTextureType1DArray) ? 1u : td.width;
td.depth = type == MTLTextureType3D ? 4 : 1;
- td.arrayLength = (type == MTLTextureType1DArray || type == MTLTextureType2DArray || type == MTLTextureTypeCubeArray) ? 1 : 1;
- td.usage = storage ? (MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite) : MTLTextureUsageShaderRead;
+ td.arrayLength = img.cube ? 6u : 1u;
+ td.usage = MTLTextureUsageShaderRead | MTLTextureUsagePixelFormatView;
+ if (storage) td.usage |= MTLTextureUsageShaderWrite;
td.storageMode = MTLStorageModeShared;
id tex = KytyNewTexture(MetalContext::Instance().GetDevice(), td, __LINE__);
+ if (tex != nil) {
+ // A new Metal texture has undefined contents. Initialize every slice,
+ // including the six array slices sampled by the cube lowering.
+ const std::array zero {};
+ const NSUInteger row_bytes = td.width * BytesPerPixel(fmt);
+ const NSUInteger image_bytes = row_bytes * td.height;
+ const MTLRegion region = MTLRegionMake3D(0, 0, 0, td.width, td.height, td.depth);
+ for (NSUInteger slice = 0; slice < td.arrayLength; ++slice) {
+ [tex replaceRegion:region mipmapLevel:0 slice:slice withBytes:zero.data()
+ bytesPerRow:row_bytes bytesPerImage:image_bytes];
+ }
+ }
s_cache[key] = tex;
return tex;
}
@@ -499,7 +528,7 @@ static void SweepViewCache(Map& cache, uint64_t& last_sweep) {
return it->second.first;
}
id view = [tex newTextureViewWithPixelFormat:tex.pixelFormat textureType:tex.textureType
- levels:NSMakeRange(base, count) slices:NSMakeRange(0, 1)];
+ levels:NSMakeRange(base, count) slices:NSMakeRange(0, tex.arrayLength)];
s_views[key] = {view, ViewCacheNow()};
return view;
}
@@ -513,15 +542,17 @@ static void SweepViewCache(Map& cache, uint64_t& last_sweep) {
uint32_t levels = 1;
uint64_t used_flip = 0; // presented frame of the last request (entries unused for kAliasedEvictFlips frames are dropped)
};
-static std::map, AliasedImage> s_aliased_images;
-static std::map, uint32_t> s_aliased_level_req;
+using AliasedImageKey = std::tuple;
+static std::map s_aliased_images;
+static std::map s_aliased_level_req;
static std::mutex s_aliased_mutex;
// The key holds the size, and dynamic resolution moves the size of the transient targets every few frames (1600x904, 1624x912,
// 1640x920, ...): one mipped full-screen texture per size, never freed, passed 20 GB within 90 s of the 3D menu scene. Entries not
// requested for kAliasedEvictFlips presented frames are dropped (registries that still hold the texture keep it alive meanwhile).
static constexpr uint64_t kAliasedEvictFlips = 120;
static uint64_t s_alloc_cs_hash; // hash of the compute kernel being recorded (defined with the allocation probe)
-static id AliasedImageFor(uint64_t addr, uint32_t w, uint32_t h, MTLPixelFormat fmt, uint32_t levels_wanted) {
+static id AliasedImageFor(uint64_t addr, uint32_t w, uint32_t h, MTLPixelFormat fmt, uint32_t levels_wanted,
+ uint32_t array_layers = 0) {
std::lock_guard lock(s_aliased_mutex);
const uint64_t now = Libs::Graphics::TraceWindow::g_flip.load(std::memory_order_relaxed);
static uint64_t s_aliased_sweep = 0;
@@ -536,7 +567,7 @@ static void SweepViewCache(Map& cache, uint64_t& last_sweep) {
}
}
}
- const auto key = std::make_tuple(addr, w, h, static_cast(fmt));
+ const AliasedImageKey key {addr, w, h, fmt, array_layers};
uint32_t& req = s_aliased_level_req[key];
req = std::max(req, std::max(levels_wanted, 1u));
// A pyramid kernel chain asks for one more level per dispatch (2, 3, ... 11). Growing the texture level by level re-created it
@@ -553,12 +584,16 @@ static void SweepViewCache(Map& cache, uint64_t& last_sweep) {
AliasedImage& img = s_aliased_images[key];
if (img.tex == nil || img.levels < req) {
MTLTextureDescriptor* d = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:fmt width:w height:h mipmapped:req > 1];
+ if (array_layers != 0) {
+ d.textureType = MTLTextureType2DArray;
+ d.arrayLength = array_layers;
+ }
if (req > 1) d.mipmapLevelCount = std::min(req, d.mipmapLevelCount);
d.usage = GuestTextureUsage(fmt) | MTLTextureUsageShaderRead;
d.storageMode = MTLStorageModeShared;
img.tex = KytyNewTexture(MetalContext::Instance().GetDevice(), d, __LINE__);
img.levels = req;
- std::fprintf(stderr, "[AliasImg] addr=0x%llx %ux%u fmt=%lu levels=%u cs=0x%016llx\n", (unsigned long long)addr, w, h, (unsigned long)fmt, req,
+ std::fprintf(stderr, "[AliasImg] addr=0x%llx %ux%u fmt=%lu levels=%u layers=%u cs=0x%016llx\n", (unsigned long long)addr, w, h, (unsigned long)fmt, req, array_layers,
(unsigned long long)s_alloc_cs_hash);
}
img.used_flip = now;
@@ -572,7 +607,15 @@ static void SweepViewCache(Map& cache, uint64_t& last_sweep) {
if (texture == nil) {
return nil;
}
- const uint32_t sel[4] = {tex.DstSelX(), tex.DstSelY(), tex.DstSelZ(), tex.DstSelW()};
+ uint32_t sel[4] = {tex.DstSelX(), tex.DstSelY(), tex.DstSelZ(), tex.DstSelW()};
+ if (tex.Format() == Prospero::BufferFormat::k10_11_11Float) {
+ // Interpret the packed guest channels through Metal's reversed red and blue.
+ for (auto& component: sel) {
+ if (component == 4 || component == 6) {
+ component = 10 - component;
+ }
+ }
+ }
if (sel[0] == 4 && sel[1] == 5 && sel[2] == 6 && sel[3] == 7) {
return texture;
}
@@ -627,15 +670,34 @@ static void SweepViewCache(Map& cache, uint64_t& last_sweep) {
static std::mutex s_cs_storage_mutex;
static std::unordered_map s_cs_storage;
static uint64_t s_cs_storage_serial = 0;
+static bool GpuWritableArraysEnabled() {
+ static const bool enabled = [] {
+ if (const char* value = KYTY_ENV("KYTY_METAL_GPU_ARRAYS")) return std::strcmp(value, "0") != 0;
+ std::string title_id, version;
+ return Loader::SystemContentParamSfoGetString("TITLE_ID", &title_id) && title_id == "PPSA01317" &&
+ Loader::SystemContentParamSfoGetString("APP_VER", &version) && version == "01.710.000";
+ }();
+ return enabled;
+}
+static bool AllocateGpuWritableArray(uint64_t guest_address) {
+ static const uint64_t filter = [] {
+ const char* value = KYTY_ENV("KYTY_GPU_ARRAY_ADDRESS");
+ return value != nullptr ? std::strtoull(value, nullptr, 16) : uint64_t{0};
+ }();
+ return GpuWritableArraysEnabled() && (filter == 0 || filter == guest_address);
+}
// Last GPU writer of a guest address (compute storage image or render target): the surface converter uses it as the source of
// truth when a later pass reads the same memory with another format, size or tile layout.
static void TraceRangeOp(const char* op, uint64_t addr, uint64_t bytes);
// hash_guest (compute storage bindings, not the per-draw render-target calls): also hash the guest bytes behind the image, so a reader
// many frames later can tell whether the CPU has replaced them since (AliasConvert).
static void RecordComputeStorage(uint64_t addr, id tex, Prospero::TileMode tile = Prospero::TileMode::kLinear, bool hash_guest = false) {
- if (addr == 0 || tex == nil || tex.textureType != MTLTextureType2D) return;
- TraceRangeOp("storage_write", addr, static_cast(tex.width) * tex.height * 4);
- const uint64_t bytes = hash_guest && !IsCompressedFormat(tex.pixelFormat) ? static_cast(tex.width) * tex.height * BytesPerPixel(tex.pixelFormat) : 0;
+ if (addr == 0 || tex == nil || (tex.textureType != MTLTextureType2D &&
+ (tex.textureType != MTLTextureType2DArray || !GpuWritableArraysEnabled()))) return;
+ const uint64_t texels = static_cast(tex.width) * tex.height * tex.arrayLength;
+ TraceRangeOp("storage_write", addr, texels * 4);
+ const uint64_t bytes = hash_guest && tex.textureType == MTLTextureType2D && !IsCompressedFormat(tex.pixelFormat) ?
+ texels * BytesPerPixel(tex.pixelFormat) : 0;
const uint64_t hash = bytes != 0 ? GuestTexSourceHash(addr, bytes) : 0;
std::lock_guard lock(s_cs_storage_mutex);
CsStorageEntry& e = s_cs_storage[addr];
@@ -737,6 +799,14 @@ static bool IsDepthStencilPixelFormat(MTLPixelFormat f) {
}
}
+// Depth/stencil storage has an extra stencil plane on Metal. Float reads
+// still address its depth component through a sampled 2D texture.
+static bool CanSampleDepthAsFloat(MTLPixelFormat depth, MTLPixelFormat target) {
+ return (depth == MTLPixelFormatDepth16Unorm && target == MTLPixelFormatR16Unorm) ||
+ ((depth == MTLPixelFormatDepth32Float || depth == MTLPixelFormatDepth32Float_Stencil8) &&
+ target == MTLPixelFormatR32Float);
+}
+
// The registry remembers the last texture bound at an address, whatever its format. A registered texture of another texel size is
// another resource that merely lived at the same address, so it must not be reused for this descriptor.
static bool SameTexelSize(id t, MTLPixelFormat want) {
@@ -941,7 +1011,54 @@ static bool UmaSurfacesEnabled() {
// Last render pass begun by EnsureActiveRenderPass: reused to reopen the pass around a multi-draw clamp, and read by image binding.
static MetalRenderPassDesc s_last_pass_desc;
static bool s_last_pass_valid = false;
+// A 1x1 sampled cubemap with constant component selectors has no texel
+// dependency. Games use such descriptors to disable a material contribution.
+static bool IsConstantUnitCube(const ShaderTextureResource& tex) {
+ return tex.Type() == Prospero::ImageType::kCube && tex.Width5() == 0u &&
+ tex.Height5() == 0u && tex.BaseLevel() == 0u && tex.LastLevel() == 0u &&
+ tex.DstSelX() <= 1u && tex.DstSelY() <= 1u && tex.DstSelZ() <= 1u && tex.DstSelW() <= 1u;
+}
+
+static id ConstantComputeCube(const ShaderRecompiler::IR::CompiledShaderInfo& program,
+ uint32_t slot, const ShaderTextureResource& tex) {
+ if (!program.native_msl || slot >= program.info.images.size()) return nil;
+ const auto& image = program.info.images[slot];
+ if (!image.cube || image.resource_class != ShaderRecompiler::IR::ImageResourceClass::Sampled ||
+ !IsConstantUnitCube(tex)) return nil;
+ return ApplyDstSel(NullImageFor(image, false, true), tex);
+}
+
+static id GpuWrittenArrayFor(const ShaderTextureResource& tex, uint32_t w, uint32_t h) {
+ if ((tex.Type() != Prospero::ImageType::kCube && tex.Type() != Prospero::ImageType::kColor2DArray) ||
+ tex.BaseArray5() != 0 || tex.BaseLevel() > tex.LastLevel()) return nil;
+ std::lock_guard lock(s_cs_storage_mutex);
+ const auto it = s_cs_storage.find(tex.Base40());
+ if (it == s_cs_storage.end() || it->second.tile != tex.TileMode()) return nil;
+ id writer = it->second.tex;
+ if (writer.textureType != MTLTextureType2DArray || writer.width != w || writer.height != h ||
+ writer.arrayLength != uint32_t(tex.Depth()) + 1u || writer.mipmapLevelCount <= tex.LastLevel() ||
+ writer.pixelFormat != MetalFormatFromBufferFormat(tex.Format())) return nil;
+ return writer;
+}
+
+static bool StrictCubeBindings() {
+ static const bool enabled = [] {
+ const char* value = KYTY_ENV("KYTY_METAL_STRICT_CUBES");
+ return value == nullptr || std::strcmp(value, "0") != 0;
+ }();
+ return enabled;
+}
+
static id GraphicsImageFor(const ShaderTextureResource& tex, uint32_t w, uint32_t h, uint64_t addr) {
+ if (id array = GpuWrittenArrayFor(tex, w, h)) {
+ const NSUInteger count = uint32_t(tex.LastLevel()) + 1u - tex.BaseLevel();
+ if (tex.BaseLevel() != 0 || count != array.mipmapLevelCount) {
+ return MipRangeView(array, tex.BaseLevel(), count);
+ }
+ return array;
+ }
+ // A matching 2D view of the allocation can hold only one cubemap face.
+ if (StrictCubeBindings() && tex.Type() == Prospero::ImageType::kCube) return ComputeGuestImage(tex, w, h, addr);
// GPU-produced plain 2D images are read from the same guest-memory views the writers used (see GpuSurfaceFor). A depth surface or a mipped
// image the GPU wrote has no guest-memory form: the lookups below handle those.
if (UmaSurfacesEnabled() && tex.Type() == Prospero::ImageType::kColor2D && tex.BaseLevel() == 0 && tex.LastLevel() == 0) {
@@ -984,13 +1101,15 @@ static bool UmaSurfacesEnabled() {
uint64_t wr_flip = 0;
if (id last = LastGpuWriterTexture(addr, &wr_flip)) {
const uint64_t now_flip = Libs::Graphics::TraceWindow::g_flip.load(std::memory_order_relaxed);
- const bool depth_writer = last.pixelFormat == MTLPixelFormatDepth32Float || last.pixelFormat == MTLPixelFormatDepth16Unorm;
+ const bool depth_writer = IsDepthFormat(last.pixelFormat);
const bool in_current_pass = s_last_pass_valid && s_last_pass_desc.has_depth && s_last_pass_desc.depth_attachment.texture == last;
if (last.width == w && last.height == h && last.mipmapLevelCount == 1 && last.textureType == MTLTextureType2D && !in_current_pass) {
const MTLPixelFormat want_fmt = MetalFormatFromBufferFormat(tex.Format());
if (depth_writer) {
const uint32_t web = last.pixelFormat == MTLPixelFormatDepth16Unorm ? 2u : 4u;
- if (now_flip <= wr_flip + 2 && want_fmt != MTLPixelFormatInvalid && !IsCompressedFormat(want_fmt) && BytesPerPixel(want_fmt) == web) {
+ if (now_flip <= wr_flip + 2 && (CanSampleDepthAsFloat(last.pixelFormat, want_fmt) ||
+ (last.pixelFormat != MTLPixelFormatDepth32Float_Stencil8 && want_fmt != MTLPixelFormatInvalid &&
+ !IsCompressedFormat(want_fmt) && BytesPerPixel(want_fmt) == web))) {
return last;
}
} else if (SameTexelSize(last, want_fmt)) {
@@ -1135,7 +1254,8 @@ static int HostProtectionAt(uint64_t a) {
// 39x18 RGBA32Uint image and sampled for minutes: decoded from guest memory it shows block-shaped letters filled with noise, from
// the old writer it is black (the copy's 64x64 staging source was all zeros when the dispatch was encoded) - neither is right.
const uint64_t now_flip = Libs::Graphics::TraceWindow::g_flip.load(std::memory_order_relaxed);
- if (wr.tex == nil || wr.tile == Prospero::TileMode::kLinear || wr.tex.mipmapLevelCount != 1) return nil;
+ if (wr.tex == nil || wr.tex.textureType != MTLTextureType2D || wr.tile == Prospero::TileMode::kLinear ||
+ wr.tex.mipmapLevelCount != 1) return nil;
if (now_flip > wr.flip + 2) {
static const bool s_old = KYTY_ENV("KYTY_ALIAS_OLD_WRITER") != nullptr;
if (!s_old || wr.guest_hash == 0) return nil;
@@ -1603,6 +1723,10 @@ bool UseNativeMetalBackend() noexcept {
return enabled;
}
+uint32_t NativeMetalThreadgroupLimitDwords() {
+ return static_cast(MetalContext::Instance().GetDevice().maxThreadgroupMemoryLength / sizeof(uint32_t));
+}
+
MetalRenderer& MetalRenderer::Instance() {
static MetalRenderer instance;
return instance;
@@ -1824,6 +1948,62 @@ static bool PassTraceCsBuffers() {
return on && PassTraceCsFilter() && seen++ < limit;
}
+// KYTY_TRACE_CS_WORD=,,. Compare the CPU-visible
+// bytes at bind time with a copy ordered on Metal's queue when GPU mode is set.
+struct ComputeWordTrace {
+ uint64_t id = 0, offset = 0;
+ unsigned slot = 0;
+};
+
+static ComputeWordTrace PrepareComputeWordTrace(uint64_t shader, const ShaderComputeInputInfo& info) {
+ struct Options { unsigned long long shader = 0, offset = 0; unsigned slot = 0; bool gpu = false; };
+ static const Options options = [] {
+ Options out;
+ if (const char* value = KYTY_ENV("KYTY_TRACE_CS_WORD")) {
+ if (std::sscanf(value, "%llx,%u,%llu", &out.shader, &out.slot, &out.offset) != 3 ||
+ out.slot >= 64 || out.offset % 4 != 0) return Options {};
+ out.gpu = KYTY_ENV("KYTY_TRACE_CS_WORD_GPU") != nullptr;
+ }
+ return out;
+ }();
+ if (options.shader == 0 || shader != options.shader || !info.stage.resources ||
+ options.slot >= info.stage.resources->buffers.size()) return {};
+ const auto& desc = info.stage.resources->buffers[options.slot];
+ const uint64_t address = (uint64_t(desc.dwords[1] & 0xffff) << 32) | desc.dwords[0];
+ const uint64_t size = VsharpBytes(desc.dwords);
+ if (address == 0 || options.offset > size || size - options.offset < 16) return {};
+ static uint64_t sequence = 0;
+ if (sequence >= 1024) return {};
+ const uint64_t sequence_id = ++sequence;
+ if (!options.gpu) return {sequence_id, options.offset, options.slot};
+ const auto source = MetalBufferManager::Instance().GetBufferForGuestRange(address, size);
+ if (!source.IsValid() || source.offset > source.buffer.length ||
+ options.offset + 16 > source.buffer.length - source.offset) return {};
+ auto& context = MetalContext::Instance();
+ id copy = KytyNewBuffer(context.GetDevice(), 16, MTLResourceStorageModeShared, __LINE__);
+ if (copy == nil) return {};
+ context.EndCurrentEncoder();
+ id command = context.GetCurrentCommandBuffer();
+ id encoder = [command blitCommandEncoder];
+ if (encoder == nil) return {};
+ OrderBegin(encoder);
+ [encoder copyFromBuffer:source.buffer sourceOffset:source.offset + options.offset
+ toBuffer:copy destinationOffset:0 size:16];
+ OrderEnd(encoder);
+ [encoder endEncoding];
+ const uint64_t gpu_address = source.gpu_addr;
+ [command addCompletedHandler:^(id done) {
+ if (done.status != MTLCommandBufferStatusCompleted) return;
+ uint32_t words[4];
+ std::memcpy(words, copy.contents, sizeof(words));
+ std::fprintf(stderr, "[CsWordGPU] id=%llu guest=%llx gpu=%llx words=%08x,%08x,%08x,%08x\n",
+ (unsigned long long)sequence_id, (unsigned long long)(address + options.offset),
+ (unsigned long long)gpu_address, words[0], words[1], words[2], words[3]);
+ }];
+ context.CommitCommandBuffer(false);
+ return {sequence_id, options.offset, options.slot};
+}
+
// KYTY_PASS_TRACE_CS=[,...]: the first 16 dispatches of each listed kernel are traced the same way at any flip (a LUT
// builder runs once, long before a triggered frame), with the first dwords of its buffers. KYTY_PASS_TRACE_DUMP= also writes the
// 3D volumes such a dispatch reads and writes as raw texels: /cs___r__xx_f.raw.
@@ -3031,11 +3211,24 @@ static void RecordDrawForRT(uint64_t addr) {
return layout;
}
-static void ConfigureNativeColorTargets(MetalRenderPipelineKey& key, const HW::Context& context) {
+static void ConfigureNativeColorTargets(MetalRenderPipelineKey& key, const HW::Context& context,
+ const ShaderPixelInputInfo& pixel) {
const auto layout = NativeColorLayout(context);
for (uint32_t slot = 0; slot < layout.size(); ++slot) {
if (layout[slot].address != 0) ConfigureNativeColorTarget(key, context, slot, layout[slot].format);
}
+ if (pixel.alpha_blend_source_remap && key.color_targets[0].blending_enabled) {
+ auto remap = [](MTLBlendFactor factor) {
+ if (factor == MTLBlendFactorSourceAlpha) return MTLBlendFactorSource1Color;
+ if (factor == MTLBlendFactorOneMinusSourceAlpha) return MTLBlendFactorOneMinusSource1Color;
+ return factor;
+ };
+ auto& color = key.color_targets[0];
+ color.src_rgb = remap(color.src_rgb);
+ color.dst_rgb = remap(color.dst_rgb);
+ color.src_alpha = remap(color.src_alpha);
+ color.dst_alpha = remap(color.dst_alpha);
+ }
}
static void EnsureActiveRenderPass(const HW::Context& context) {
@@ -4693,7 +4886,8 @@ static MetalBufferAllocation GuestGpuAllocation(uint64_t vaddr, size_t size) {
static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
const ShaderPixelInputInfo& ps_info,
- bool pixel_active) {
+ bool pixel_active,
+ std::span mesh_draw = {}) {
s_draw_seq.fetch_add(1, std::memory_order_relaxed);
s_trace_draw_inputs.clear();
s_trace_draw_bufs.clear();
@@ -4796,7 +4990,14 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
dump("ps", ps_info.stage, ps_push_data);
}
}
- MetalDrawExecutor::Instance().SetVertexBytes(&vs_push_data, sizeof(vs_push_data), 1);
+ if (mesh_draw.empty()) {
+ MetalDrawExecutor::Instance().SetVertexBytes(&vs_push_data, sizeof(vs_push_data), 1);
+ } else {
+ std::copy(mesh_draw.begin(), mesh_draw.end(), vs_push_data.dwords.begin());
+ std::copy(mesh_draw.begin(), mesh_draw.end(), ps_push_data.dwords.begin());
+ [MetalContext::Instance().GetActiveRenderEncoder() setMeshBytes:&vs_push_data
+ length:sizeof(vs_push_data) atIndex:1];
+ }
MetalDrawExecutor::Instance().SetFragmentBytes(&ps_push_data, sizeof(ps_push_data), 1);
// 2. Buffer 25: spvBufferSizeConstants (buffer bounds)
@@ -5133,6 +5334,16 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
const size_t vb_bytes = static_cast(vertex_buffers[i].stride) * vertex_buffers[i].num_records;
BindGuestBuffer(static_cast(i), vertex_buffers[i].addr, vb_bytes, vb_bytes);
}
+ if (args == vs_args && stage.program && stage.program->native_msl &&
+ stage.program->info.buffers.size() <= 32) {
+ for (int i = 0; i < vs_info.resources_num && i < 27; ++i) {
+ const auto& resource = vs_info.resources[i];
+ const auto bytes = static_cast(resource.GetSize());
+ const auto slot = 32u + static_cast(i);
+ vs_sizes[slot] = static_cast(std::min(bytes, UINT32_MAX));
+ if (bytes != 0) BindGuestBuffer(slot, resource.Base48(), bytes, bytes);
+ }
+ }
if (stage.resources) {
const auto& snap = *stage.resources;
for (size_t b = 0; b < snap.buffers.size() && b < 64; ++b) {
@@ -5221,7 +5432,13 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
(unsigned long long)Libs::Graphics::TraceWindow::g_flip.load());
}
}
- id base_image = GraphicsImageFor(tex, w, h, addr);
+ const auto* image = stage.program && i < stage.program->info.images.size() ?
+ &stage.program->info.images[i] : nullptr;
+ const bool constant_cube = image && image->cube &&
+ image->resource_class == ShaderRecompiler::IR::ImageResourceClass::Sampled &&
+ IsConstantUnitCube(tex);
+ id base_image = constant_cube ? NullImageFor(*image, false, true) :
+ GraphicsImageFor(tex, w, h, addr);
// KYTY_LOG_TEX_UNIQ=,: every distinct sampled image in that flip range, with the non-zero ratio of the
// bound Metal object (finds images the game samples that nobody filled).
if (const char* uq = KYTY_ENV("KYTY_LOG_TEX_UNIQ"); uq != nullptr && base_image != nil) {
@@ -5303,6 +5520,22 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
std::find(binding.resources.begin(), binding.resources.end(), i) != binding.resources.end()) storage_image = true;
}
if (id texture = storage_image ? base_image : ApplyDstSel(base_image, tex)) {
+ static const char* watch = KYTY_ENV("KYTY_LOG_BOUND_IMAGE");
+ if (watch && args == ps_args && stage.program && addr == std::strtoull(watch, nullptr, 16)) {
+ const uint64_t flip = Libs::Graphics::TraceWindow::g_flip.load();
+ static const uint64_t first = KYTY_ENV("KYTY_DUMP_RT_MIN_FLIP") ?
+ std::strtoull(KYTY_ENV("KYTY_DUMP_RT_MIN_FLIP"), nullptr, 10) : 0;
+ if (flip >= first && flip - first < 4) {
+ const auto swizzle = texture.swizzle;
+ std::fprintf(stderr, "[BoundPS] hash=%016llx slot=%zu addr=%llx fmt=%u tile=%u target=%lu mtl=%lu dim=%lux%lux%lu layers=%lu writer=%d guest=%03x host=%u,%u,%u,%u\n",
+ (unsigned long long)stage.program->shader_hash, i, (unsigned long long)addr,
+ (unsigned)tex.Format(), (unsigned)tex.TileMode(), (unsigned long)texture.textureType,
+ (unsigned long)texture.pixelFormat, (unsigned long)texture.width, (unsigned long)texture.height,
+ (unsigned long)texture.depth, (unsigned long)texture.arrayLength,
+ base_image == GpuWrittenArrayFor(tex, w, h), tex.DstSelXYZW(), (unsigned)swizzle.red, (unsigned)swizzle.green,
+ (unsigned)swizzle.blue, (unsigned)swizzle.alpha);
+ }
+ }
args[64 + i] = [texture gpuResourceID]._impl;
(args == ps_args ? s_ps_caps : s_vs_caps).push_back({static_cast(64 + i), nil, 0, texture, nil});
if (args == ps_args && PassTraceActive() && s_trace_draw_inputs.size() < 64) s_trace_draw_inputs.push_back({texture, static_cast(64 + i), addr, w, h, static_cast(tex.Format()), static_cast(tex.TileMode())});
@@ -5310,29 +5543,39 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
if (storage_image) RecordComputeStorage(addr, base_image, tex.TileMode(), true);
// Presenter lookup by guest address (the flip buffer is bound as an image by its writer). The image
// itself, not its DST_SEL view: compute later binds the registered object as a writable storage image.
- RegisterComputeWrittenImage(addr, (__bridge void*)base_image);
+ if (!constant_cube && (base_image.textureType != MTLTextureType2DArray || !GpuWritableArraysEnabled())) {
+ RegisterComputeWrittenImage(addr, (__bridge void*)base_image);
+ }
}
}
}
for (uint32_t i = 0; i < 64; ++i) {
if (args[64 + i] == 0) {
- // A declared image slot nobody bound is replaced by the white default texture: report it once per shader slot.
+ // Use a compatible zero image for declared slots with no texture.
if (stage.program != nullptr && i < stage.program->info.images.size()) {
- NoteFallback("unbound image slot (white default texture)", static_cast(stage.program->shader_hash),
+ const auto& image = stage.program->info.images[i];
+ if (image.resource_class == ShaderRecompiler::IR::ImageResourceClass::Sampled) {
+ if (auto zero = NullImageFor(image, false)) {
+ args[64 + i] = [zero gpuResourceID]._impl;
+ (args == ps_args ? s_ps_caps : s_vs_caps).push_back({64u + i, nil, 0, zero, nil});
+ MetalDrawExecutor::Instance().UseResource(zero, MTLResourceUsageRead);
+ }
+ }
+ NoteFallback("unbound image slot", static_cast(stage.program->shader_hash),
static_cast(stage.program->shader_hash >> 32), i);
// KYTY_LOG_UNBOUND=1: what the guest descriptor of such a slot holds (null T#, an unsupported type or format, or an
// address with nothing behind it), once per shader slot.
static const bool s_log_unbound = KYTY_ENV("KYTY_LOG_UNBOUND") != nullptr;
if (s_log_unbound) {
static std::mutex s_ub_mutex;
- static std::set> s_ub_seen;
+ static std::set> s_ub_seen;
std::lock_guard ub_lock(s_ub_mutex);
- if (s_ub_seen.insert({stage.program->shader_hash, i}).second) {
- ShaderTextureResource tex {};
- const bool has_desc = stage.resources != nullptr && i < stage.resources->images.size();
- if (has_desc) for (size_t f = 0; f < 8; ++f) tex.fields[f] = stage.resources->images[i].dwords[f];
- std::fprintf(stderr, "[Unbound] %c hash=%016llx slot=%u desc=%d null=%d dim=%d addr=0x%llx %ux%u fmt=%u type=%u tile=%u lvls=%u-%u dst_sel=%u%u%u%u d=%08x %08x %08x %08x\n",
- args == ps_args ? 'P' : 'V', (unsigned long long)stage.program->shader_hash, i, has_desc ? 1 : 0,
+ ShaderTextureResource tex {};
+ const bool has_desc = stage.resources != nullptr && i < stage.resources->images.size();
+ if (has_desc) std::copy_n(stage.resources->images[i].dwords.begin(), 8, tex.fields);
+ if (s_ub_seen.emplace(stage.program->shader_hash, i, has_desc, tex.IsNull()).second) {
+ std::fprintf(stderr, "[Unbound] %c hash=%016llx guest=%016llx slot=%u source=%u pc=0x%x desc=%d null=%d dim=%d addr=0x%llx %ux%u fmt=%u type=%u tile=%u lvls=%u-%u dst_sel=%u%u%u%u d=%08x %08x %08x %08x\n",
+ args == ps_args ? 'P' : 'V', (unsigned long long)stage.program->shader_hash, (unsigned long long)stage.program->guest_hash, i, image.source, image.first_use_pc, has_desc ? 1 : 0,
tex.IsNull() ? 1 : 0,
static_cast(stage.program->info.images[i].dimension), (unsigned long long)tex.Base40(),
static_cast(tex.Width5()) + 1u, static_cast(tex.Height5()) + 1u, (unsigned)tex.Format(),
@@ -5341,7 +5584,7 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
}
}
}
- args[64 + i] = def_tex_id;
+ if (args[64 + i] == 0) args[64 + i] = def_tex_id;
}
}
for (uint32_t i = 0; i < 32; ++i) {
@@ -5383,7 +5626,7 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
continue;
}
static const bool s_spvc_abi_slot = KYTY_ENV("KYTY_SPVC_ABI") != nullptr;
- if (s_spvc_abi_slot) {
+ if (s_spvc_abi_slot || stage.program->stage == ShaderType::Mesh) {
const auto layout = Libs::Graphics::Metal::ComputeSpvcAbiLayout(stage.program->bindings, stage.program->stage);
slot = layout.BaseOf(binding.kind) + static_cast(it - binding.resources.begin());
return true;
@@ -5401,7 +5644,8 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
int vertex_count) {
// KYTY_SPVC_ABI: resource ids come from the per-shader layout, not the legacy offsets.
static const bool s_spvc_abi_bind = KYTY_ENV("KYTY_SPVC_ABI") != nullptr;
- const bool abi_on = s_spvc_abi_bind && stage.program != nullptr;
+ const bool abi_on = stage.program != nullptr &&
+ (s_spvc_abi_bind || stage.program->stage == ShaderType::Mesh);
const auto abi_layout = abi_on ? Libs::Graphics::Metal::ComputeSpvcAbiLayout(stage.program->bindings, stage.program->stage)
: Libs::Graphics::Metal::SpvcAbiLayout {};
using DescKind = ShaderRecompiler::IR::DescriptorBindingKind;
@@ -5413,6 +5657,15 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
const uint32_t abi_buf = abi_on ? AbiBaseOr256(DescKind::Buffers) : base;
const uint32_t abi_srt = abi_on ? AbiBaseOr256(DescKind::FlattenedSrt) : base + 53;
const uint32_t abi_samp = abi_on ? AbiBaseOr256(DescKind::Samplers) : base + 49;
+ const bool mesh_stage = stage.program != nullptr && stage.program->stage == ShaderType::Mesh;
+ if (mesh_stage) {
+ const uint32_t bda_index = AbiBaseOr256(DescKind::BdaPagetable);
+ if (bda_index < 256u) {
+ if (auto root = BindGuestAddressSpaceBuffer(true)) {
+ s_vs_caps.push_back({bda_index, root, 0, nil, nil});
+ }
+ }
+ }
for (int i = 0; vertex_buffers != nullptr && i < vertex_count && i < 5; ++i) {
const auto ga = GuestGpuAllocation(
vertex_buffers[i].addr,
@@ -5476,7 +5729,11 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
}
if (ga.gpu_addr != 0) {
if (abi_buf + b < 256u) args[abi_buf + b] = ga.gpu_addr;
- if (abi_buf + b < 256u) (args == ps_args ? s_ps_caps : s_vs_caps).push_back({static_cast(abi_buf + b), ga.buffer, ga.offset & ~static_cast(255), nil, nil});
+ if (abi_buf + b < 256u) {
+ const auto offset = mesh_stage ? ga.offset : ga.offset & ~static_cast(255);
+ (args == ps_args ? s_ps_caps : s_vs_caps).push_back({static_cast(abi_buf + b), ga.buffer, offset, nil, nil});
+ if (mesh_stage) vs_sizes[b] = static_cast(std::min(ga.size, UINT32_MAX));
+ }
}
}
{
@@ -5671,7 +5928,7 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
for (size_t i = 0; i < 64; ++i) {
if (vs_args[i] == 0) {
vs_args[i] = def_buf_addr;
- vs_sizes[i] = 0;
+ if (mesh_draw.empty()) vs_sizes[i] = 0;
}
if (ps_args[i] == 0) {
ps_args[i] = def_buf_addr;
@@ -5782,7 +6039,15 @@ static void BindMetalShaderResources(const ShaderVertexInputInfo& vs_info,
MetalDrawExecutor::Instance().SetVertexBuffer(s_vsdbg_buf, 0, 27);
}
// Vertex stage through the argument encoder (KYTY_ARGENC_GFX=1), with the same per-index check.
- if (KYTY_ENV("KYTY_ARGENC_GFX") != nullptr && vs_info.stage.program != nullptr) {
+ if (!mesh_draw.empty()) {
+ auto encoder = MetalContext::Instance().GetActiveRenderEncoder();
+ [encoder setMeshBytes:vs_sizes length:sizeof(vs_sizes) atIndex:25];
+ if (ShaderHasArgumentBuffer0(vs_info.stage.program->shader_hash)) {
+ id function = MetalShaderManager::Instance().GetFunction(vs_info.stage.program->shader_hash);
+ id args = build_gfx_argbuf(function, s_vs_caps, false);
+ [encoder setMeshBuffer:args offset:0 atIndex:0];
+ }
+ } else if (KYTY_ENV("KYTY_ARGENC_GFX") != nullptr && vs_info.stage.program != nullptr) {
id vfn = MetalShaderManager::Instance().GetFunction(vs_info.stage.program->shader_hash);
if (vfn != nil && ShaderHasArgumentBuffer0(vs_info.stage.program->shader_hash)) {
if (KYTY_ENV("KYTY_ARGENC_CHECK") != nullptr) {
@@ -5911,8 +6176,14 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
static bool started = false;
static uint32_t count = 0;
static uint64_t flip0 = 0;
- const auto& rt = context.GetRenderTarget(0);
- if (rt.base.addr != want_addr) return false;
+ if (want_addr == 0) return false;
+ const auto mask = context.GetRenderTargetMask();
+ unsigned slot = 0;
+ for (; slot < RENDER_COLOR_ATTACHMENTS_MAX; ++slot) {
+ if (((mask >> (4u * slot)) & 0xfu) != 0 && context.GetRenderTarget(slot).base.addr == want_addr) break;
+ }
+ if (slot == RENDER_COLOR_ATTACHMENTS_MAX) return false;
+ const auto& rt = context.GetRenderTarget(slot);
const auto fmt = MetalFormatFromRenderTarget(rt.info.format, rt.info.channel_type, rt.info.channel_order);
if (const char* filter = KYTY_ENV("KYTY_DUMP_RT_FORMAT");
filter && (uint32_t)fmt != std::strtoul(filter, nullptr, 10)) return false;
@@ -5935,25 +6206,61 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
if (!dir) dir = "/tmp/fix6";
std::snprintf(path, sizeof(path), "%s/rt_%u.ppm", dir, k);
if (texture) MetalPresenter::Instance().DumpTextureToPpm(texture, path);
- const auto& bc = context.GetBlendControl(0);
- std::fprintf(stderr, "[RtDraw] k=%u flip=%llu ps=%016llx fmt=%u mask=%x/%x blend=%d/%u/%u -> %s\n", k,
- (unsigned long long)flip0, (unsigned long long)ps_hash, (unsigned)fmt,
- context.GetRenderTargetMask(), context.GetShaderRegisters().m_cbShaderMask,
+ const auto& bc = context.GetBlendControl(slot);
+ std::fprintf(stderr, "[RtDraw] k=%u flip=%llu ps=%016llx slot=%u fmt=%u mask=%x/%x blend=%d/%u/%u -> %s\n", k,
+ (unsigned long long)flip0, (unsigned long long)ps_hash, slot, (unsigned)fmt,
+ mask, context.GetShaderRegisters().m_cbShaderMask,
bc.enable ? 1 : 0, (unsigned)bc.color_srcblend, (unsigned)bc.color_destblend, path);
if (k == 0 && pixel_info.stage.resources) {
const auto& snap = *pixel_info.stage.resources;
+ if (!snap.buffers.empty()) {
+ const auto& desc = snap.buffers.front().dwords;
+ const uint64_t address = (static_cast(desc[1] & 0xffffu) << 32u) | desc[0];
+ std::array words {};
+ const size_t bytes = std::min(sizeof(words), VsharpBytes(desc));
+ if (address != 0 && bytes != 0 && LibKernel::Memory::TryReadBacking(address, words.data(), bytes)) {
+ std::fprintf(stderr, "[RtConstants] addr=%llx bytes=%zu words:", (unsigned long long)address, bytes);
+ for (size_t i = 0; i < bytes / sizeof(uint32_t); ++i) std::fprintf(stderr, " %08x", words[i]);
+ std::fputc('\n', stderr);
+ }
+ }
for (size_t i = 0; i < snap.images.size(); ++i) {
ShaderTextureResource t {};
std::copy_n(snap.images[i].dwords.begin(), 8, t.fields);
const uint32_t w = t.Width5()+1u, h = t.Height5()+1u;
id image = GraphicsImageFor(t,w,h,t.Base40());
- if (image == nil || image.textureType != MTLTextureType2D) continue;
+ if (image == nil) continue;
+ const bool packed_float = image.pixelFormat == MTLPixelFormatRG11B10Float;
+ if (image.textureType == MTLTextureType3D && image.storageMode == MTLStorageModeShared &&
+ (image.pixelFormat == MTLPixelFormatRGBA16Float || packed_float)) {
+ std::array voxel {};
+ const size_t texel_bytes = packed_float ? sizeof(uint32_t) : sizeof(voxel);
+ std::fprintf(stderr, "[RtVolume] slot=%zu addr=%llx %lux%lux%lu tile=%u mtl=%lu",
+ i, (unsigned long long)t.Base40(), (unsigned long)image.width,
+ (unsigned long)image.height, (unsigned long)image.depth, (unsigned)t.TileMode(),
+ (unsigned long)image.pixelFormat);
+ for (const auto& xyz: std::array, 5> {{
+ {0, 0, 0}, {image.width - 1, 0, 0}, {0, image.height - 1, 0},
+ {0, 0, image.depth - 1}, {image.width / 2, image.height / 2, image.depth / 2},
+ }}) {
+ [image getBytes:voxel.data() bytesPerRow:texel_bytes bytesPerImage:texel_bytes
+ fromRegion:MTLRegionMake3D(xyz[0], xyz[1], xyz[2], 1, 1, 1) mipmapLevel:0 slice:0];
+ if (packed_float) {
+ const uint32_t word = uint32_t(voxel[0]) | (uint32_t(voxel[1]) << 16);
+ std::fprintf(stderr, " %08x", word);
+ } else {
+ std::fprintf(stderr, " (%04x,%04x,%04x,%04x)", voxel[0], voxel[1], voxel[2], voxel[3]);
+ }
+ }
+ std::fputc('\n', stderr);
+ }
+ if (image.textureType != MTLTextureType2D) continue;
MetalRenderer::Instance().WaitIdle();
std::snprintf(path,sizeof(path),"%s/input_%zu.ppm",dir,i);
MetalPresenter::Instance().DumpTextureToPpm((__bridge void*)image,path);
- std::fprintf(stderr,"[RtInput] slot=%zu addr=%llx %ux%u fmt=%u tile=%u mtl=%lu -> %s\n",i,
+ std::fprintf(stderr,"[RtInput] slot=%zu addr=%llx %ux%u fmt=%u tile=%u mtl=%lu swz=%03x -> %s\n",i,
(unsigned long long)t.Base40(),w,h,(unsigned)t.Format(),(unsigned)t.TileMode(),
- (unsigned long)image.pixelFormat,path);
+ (unsigned long)image.pixelFormat,t.DstSelXYZW(),path);
}
}
dumped = true;
@@ -5961,6 +6268,83 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
return dumped;
}
+// Trace all render-target slots. Some lighting passes put the HDR image in
+// MRT1 while color target 0 is disabled.
+static void TraceImageProducer(const HW::Context& context, uint64_t shader_hash,
+ const ShaderPixelInputInfo& pixel) {
+ static const char* address = KYTY_ENV("KYTY_LOG_IMAGE_PRODUCER");
+ if (address == nullptr || shader_hash == 0) return;
+ static const uint64_t target = std::strtoull(address, nullptr, 16);
+ if (target == 0) return;
+ const uint64_t flip = Libs::Graphics::TraceWindow::g_flip.load();
+ static const uint64_t first = KYTY_ENV("KYTY_DUMP_RT_MIN_FLIP") ?
+ std::strtoull(KYTY_ENV("KYTY_DUMP_RT_MIN_FLIP"), nullptr, 10) : 0;
+ if (flip < first || flip - first >= 12) return;
+ const auto mask = context.GetRenderTargetMask();
+ for (unsigned slot = 0; slot < RENDER_COLOR_ATTACHMENTS_MAX; ++slot) {
+ if (((mask >> (4u * slot)) & 0xfu) == 0 || context.GetRenderTarget(slot).base.addr != target) continue;
+ const auto& output = context.GetRenderTarget(slot);
+ std::fprintf(stderr, "[ImageProducer] flip=%llu ps=%016llx addr=%llx slot=%u fmt=%u mask=%x/%x",
+ (unsigned long long)flip, (unsigned long long)shader_hash, (unsigned long long)target,
+ slot, (unsigned)output.info.format, mask,
+ context.GetShaderRegisters().m_cbShaderMask);
+ if (pixel.stage.resources) {
+ for (const auto& image: pixel.stage.resources->images) {
+ ShaderTextureResource desc {};
+ std::copy_n(image.dwords.begin(), 8, desc.fields);
+ std::fprintf(stderr, " R@%llx(%ux%u:%u swz=%03x)", (unsigned long long)desc.Base40(),
+ desc.Width5() + 1u, desc.Height5() + 1u, (unsigned)desc.Format(), desc.DstSelXYZW());
+ }
+ }
+ std::fputc('\n', stderr);
+ }
+}
+
+static bool SkipMeshForDiagnostics(const HW::Context& context) {
+ static const bool skip_mesh = KYTY_ENV("KYTY_METAL_SKIP_MESH") != nullptr;
+ if (!skip_mesh || (context.GetShaderStages() & 0x20u) == 0) {
+ return false;
+ }
+ static std::atomic_bool reported {false};
+ if (!reported.exchange(true, std::memory_order_relaxed)) {
+ std::fprintf(stderr, "[Metal] Diagnostic mode: skipping unsupported mesh draws\n");
+ }
+ return true;
+}
+
+static uint32_t MeshThreadCount(const ShaderMeshInputInfo& mesh) {
+ const auto logical_threads = mesh.threads_num[0] * mesh.threads_num[1] * mesh.threads_num[2];
+ return ((logical_threads + mesh.wave_size - 1u) / mesh.wave_size) *
+ std::min(mesh.host_subgroup_size, mesh.wave_size);
+}
+
+static bool DrawMesh(const ShaderVertexInputInfo& front, const ShaderPixelInputInfo& pixel,
+ bool pixel_active, uint32_t count, uint32_t instance_count, uint32_t first_vertex,
+ uint32_t first_instance, uint32_t element_size, uint64_t index_guest_address) {
+ const auto& mesh = front.mesh;
+ const auto primitives = mesh.InputPrimitiveCount(count);
+ if (primitives == 0 || instance_count == 0) {
+ return false;
+ }
+ const auto groups = (primitives - 1u) / mesh.primitives_per_group + 1u;
+ const uint32_t draw_data[] {
+ count, first_vertex, first_instance, element_size,
+ static_cast(index_guest_address), static_cast(index_guest_address >> 32u),
+ };
+ static_assert(std::size(draw_data) == ShaderRecompiler::IR::PushData::MeshDrawDwordCount);
+ BindMetalShaderResources(front, pixel, pixel_active, draw_data);
+ const auto threads = MeshThreadCount(mesh);
+ if (!MetalDrawExecutor::Instance().DrawMesh(groups, instance_count, threads)) {
+ return false;
+ }
+ static std::atomic_bool reported {false};
+ if (!reported.exchange(true, std::memory_order_relaxed)) {
+ std::fprintf(stderr, "[MetalMesh] first draw: groups=%u instances=%u threads=%u indexed=%u\n",
+ groups, instance_count, threads, element_size != 0);
+ }
+ return true;
+}
+
void MetalRenderer::DrawIndex(uint64_t submit_id, const HW::Context& context, const HW::Shader& sh_ctx,
const HW::UserConfig& ucfg, PipelineCache& pipeline_cache,
Prospero::PrimitiveType prim_type,
@@ -5969,6 +6353,9 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
uint32_t first_instance) {
DrawPassTrace draw_pass_trace;
const PendingIndirectDraw pending_index = TakePendingIndirectDraw();
+ if (SkipMeshForDiagnostics(context)) {
+ return;
+ }
s_trace_submit_id = submit_id;
PassTraceNoteDrawState(context, static_cast(prim_type), index_count);
s_trace_instances = instance_count;
@@ -6040,10 +6427,12 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
sh_ctx.GetVs(), sh_ctx.GetPs(), context.GetShaderRegisters(),
context, ucfg, target_export_mapping, pixel_active, vertex_info, pixel_info);
+ const bool mesh_active = vertex_info[0].logical_stage == ShaderType::Mesh;
uint64_t vs_hash = vertex_info[0].stage.program ? vertex_info[0].stage.program->shader_hash : 0;
uint64_t ps_hash = (pixel_active && pixel_info.stage.program) ? pixel_info.stage.program->shader_hash : 0;
PrepareGraphicsImages(vertex_info[0].stage);
if (pixel_active) PrepareGraphicsImages(pixel_info.stage);
+ TraceImageProducer(context, ps_hash, pixel_info);
if (DumpRtBeforeDraw(context, ps_hash, pixel_info)) EnsureActiveRenderPass(context);
id vs_func = MetalShaderManager::Instance().GetFunction(vs_hash);
@@ -6081,10 +6470,11 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
if (msl_draw_ok) {
MetalRenderPipelineKey pipe_key {};
pipe_key.primitive_type = static_cast(prim_type);
+ if (mesh_active) pipe_key.mesh_threads = MeshThreadCount(vertex_info[0].mesh);
pipe_key.vs_hash = vs_hash;
pipe_key.fs_hash = ps_hash;
TracePsRt(context.GetRenderTarget(0).base.addr, ps_hash);
- ConfigureNativeColorTargets(pipe_key, context);
+ ConfigureNativeColorTargets(pipe_key, context, pixel_info);
const auto& rt0 = context.GetRenderTarget(0);
const auto& dt = context.GetDepthRenderTarget();
if (dt.z_read_base_addr != 0 && dt.z_info.format != Prospero::DepthFormat::kInvalid) {
@@ -6243,8 +6633,16 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
}
}
+ if (mesh_active) {
+ if (pending_index.args_addr != 0 || index_addr == nullptr || vertex_info[0].mesh.fast_launch) {
+ EXIT("Metal mesh draw: unsupported indexed draw arguments\n");
+ }
+ const auto element_size = index_type_and_size == 0 ? 2u : 4u;
+ DrawMesh(vertex_info[0], pixel_info, pixel_active, index_count, instance_count,
+ static_cast(base_vertex), first_instance, element_size,
+ reinterpret_cast(index_addr));
+ } else {
BindMetalShaderResources(vertex_info[0], pixel_info, pixel_active);
-
if (s_rect_indexed) {
MetalDrawExecutor::Instance().UseResource(rect_ib.buffer, MTLResourceUsageRead);
MetalDrawExecutor::Instance().DrawIndexed(prim_type, 6, rect_ib.buffer, rect_ib.offset, MTLIndexTypeUInt32,
@@ -6276,6 +6674,7 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
prim_type, index_count,
index_buffer.GetHandle(), 0, idx_type,
instance_count > 0 ? instance_count : 1, base_vertex, first_instance);
+ }
{
static std::mutex s_exec_mutex;
static std::unordered_map s_exec_counts;
@@ -6323,6 +6722,9 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
}
}
const PendingIndirectDraw pending_indirect = TakePendingIndirectDraw();
+ if (SkipMeshForDiagnostics(context)) {
+ return;
+ }
const uint64_t indirect_args_addr = pending_indirect.args_addr;
s_trace_indirect_addr = indirect_args_addr;
s_trace_instances = instance_count;
@@ -6375,12 +6777,35 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
sh_ctx.GetVs(), sh_ctx.GetPs(), context.GetShaderRegisters(),
context, ucfg, target_export_mapping, pixel_active, vertex_info, pixel_info);
+ const bool mesh_active = vertex_info[0].logical_stage == ShaderType::Mesh;
uint64_t vs_hash = vertex_info[0].stage.program ? vertex_info[0].stage.program->shader_hash : 0;
uint64_t ps_hash = (pixel_active && pixel_info.stage.program) ? pixel_info.stage.program->shader_hash : 0;
PrepareGraphicsImages(vertex_info[0].stage);
if (pixel_active) PrepareGraphicsImages(pixel_info.stage);
+ TraceImageProducer(context, ps_hash, pixel_info);
if (DumpRtBeforeDraw(context, ps_hash, pixel_info)) EnsureActiveRenderPass(context);
+ if (const char* range = KYTY_ENV("KYTY_LOG_DRAWS_FLIP")) {
+ unsigned first = 0, last = 0;
+ const auto flip = TraceWindow::g_flip.load();
+ if (std::sscanf(range, "%u,%u", &first, &last) == 2 && flip >= first && flip <= last) {
+ const auto& target = context.GetRenderTarget(0);
+ std::fprintf(stderr, "[AutoF] flip=%llu rt0=0x%llx vs=%016llx ps=%016llx prim=%u count=%u mesh=%d fmt=%u",
+ (unsigned long long)flip, (unsigned long long)target.base.addr, (unsigned long long)vs_hash,
+ (unsigned long long)ps_hash, (unsigned)prim_type, vertex_count, mesh_active ? 1 : 0,
+ (unsigned)target.info.format);
+ if (pixel_info.stage.resources) {
+ for (const auto& image: pixel_info.stage.resources->images) {
+ ShaderTextureResource desc {};
+ std::copy_n(image.dwords.begin(), 8, desc.fields);
+ std::fprintf(stderr, " R@%llx(%ux%u:%u)", (unsigned long long)desc.Base40(),
+ desc.Width5() + 1u, desc.Height5() + 1u, (unsigned)desc.Format());
+ }
+ }
+ std::fputc('\n', stderr);
+ }
+ }
+
id vs_func = MetalShaderManager::Instance().GetFunction(vs_hash);
id ps_func = ps_hash ? MetalShaderManager::Instance().GetFunction(ps_hash) : nil;
@@ -6446,10 +6871,11 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
if (msl_draw_ok) {
MetalRenderPipelineKey pipe_key {};
pipe_key.primitive_type = static_cast(prim_type);
+ if (mesh_active) pipe_key.mesh_threads = MeshThreadCount(vertex_info[0].mesh);
pipe_key.vs_hash = vs_hash;
pipe_key.fs_hash = ps_hash;
TracePsRt(context.GetRenderTarget(0).base.addr, ps_hash);
- ConfigureNativeColorTargets(pipe_key, context);
+ ConfigureNativeColorTargets(pipe_key, context, pixel_info);
const auto& rt0 = context.GetRenderTarget(0);
const auto& dt = context.GetDepthRenderTarget();
if (dt.z_read_base_addr != 0 && dt.z_info.format != Prospero::DepthFormat::kInvalid) {
@@ -6527,7 +6953,7 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
}
}
- BindMetalShaderResources(vertex_info[0], pixel_info, pixel_active);
+ if (!mesh_active) BindMetalShaderResources(vertex_info[0], pixel_info, pixel_active);
{
char fault_label[288];
std::snprintf(fault_label, sizeof(fault_label), "draw #%llu rt0=0x%llx vs=0x%016llx ps=0x%016llx prim=%u vtx=%u inst=%u tmask=0x%x smask=0x%x blend=%d/%d/%d gfmt=%u mtl=%u",
@@ -6546,7 +6972,13 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
}
MslDrawStatExecuted();
- if (indirect_args_addr != 0) {
+ if (mesh_active) {
+ if (indirect_args_addr != 0) {
+ EXIT("Metal mesh draw: indirect draw arguments are unsupported\n");
+ }
+ DrawMesh(vertex_info[0], pixel_info, pixel_active, vertex_count, std::max(instance_count, 1u),
+ first_vertex, first_instance, 0, 0);
+ } else if (indirect_args_addr != 0) {
if (draw_args != nil) {
MetalDrawExecutor::Instance().UseResource(draw_args, MTLResourceUsageRead);
for (uint32_t k = 0; k < draw_args_count; ++k) {
@@ -6738,25 +7170,27 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
}
}
{
- // KYTY_LOG_CS_WRITES=,: compute dispatches that write a buffer based inside [lo,hi) (who produces vertex streams etc.).
- static uint64_t s_wlo = 0, s_whi = 0;
+ // KYTY_LOG_CS_WRITES=,[,]: compute write descriptors that overlap the guest range.
+ static uint64_t s_wlo = 0, s_whi = 0, s_wfirst = 2000;
static std::once_flag s_w_once;
std::call_once(s_w_once, [] {
if (const char* v = KYTY_ENV("KYTY_LOG_CS_WRITES")) {
char* e = nullptr;
s_wlo = std::strtoull(v, &e, 0);
- if (*e == ',') s_whi = std::strtoull(e + 1, nullptr, 0);
+ if (*e == ',') s_whi = std::strtoull(e + 1, &e, 0);
+ if (*e == ',') s_wfirst = std::strtoull(e + 1, nullptr, 0);
}
});
static std::atomic s_w_n {0};
const uint64_t wf = Libs::Graphics::TraceWindow::g_flip.load(std::memory_order_relaxed);
- if (s_whi > s_wlo && wf >= 2000 && compute_info.stage.program && compute_info.stage.resources && s_w_n.load() < 3000) {
+ if (s_whi > s_wlo && wf >= s_wfirst && compute_info.stage.program && compute_info.stage.resources && s_w_n.load() < 3000) {
const auto& wp = *compute_info.stage.program;
const auto& wr = *compute_info.stage.resources;
for (size_t bi = 0; bi < wp.info.buffers.size() && bi < wr.buffers.size(); ++bi) {
if (!wp.info.buffers[bi].written) continue;
const uint64_t base = (static_cast(wr.buffers[bi].dwords[1] & 0xFFFF) << 32) | wr.buffers[bi].dwords[0];
- if (base >= s_wlo && base < s_whi && s_w_n.fetch_add(1) < 3000) {
+ const uint64_t bytes = VsharpBytes(wr.buffers[bi].dwords);
+ if (base != 0 && bytes != 0 && base < s_whi && s_wlo < base + bytes && s_w_n.fetch_add(1) < 3000) {
for (size_t ob = 0; ob < wp.info.buffers.size() && ob < wr.buffers.size() && ob < 6 && s_w_n.load() < 40; ++ob) {
const uint64_t obase = (static_cast(wr.buffers[ob].dwords[1] & 0xFFFF) << 32) | wr.buffers[ob].dwords[0];
std::fprintf(stderr, "[CsWrite] in-b%zu base=0x%llx nrec=%u stride=%u size=%u read=%d written=%d\n", ob, static_cast(obase),
@@ -6891,6 +7325,31 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
}
if (pstate == nil) { CountDispatchStat(3); return; }
+ uint32_t tg_w = compute_info.threads_num[0] > 0 ? compute_info.threads_num[0] : 64;
+ uint32_t tg_h = compute_info.threads_num[1] > 0 ? compute_info.threads_num[1] : 1;
+ uint32_t tg_d = compute_info.threads_num[2] > 0 ? compute_info.threads_num[2] : 1;
+ // COMPUTE_DISPATCH_INITIATOR.USE_THREAD_DIMENSIONS: the dispatch dimensions are thread counts, not group counts
+ // (the game's memory fill/copy kernels dispatch one thread per dword). The hardware launches ceil(threads / group size)
+ // groups; taking the counts as groups would run group-size times too many threads per dimension.
+ static const bool s_raw_groups = KYTY_ENV("KYTY_CS_RAW_GROUPS") != nullptr; // old behaviour, for A/B runs
+ if (indirect_args_addr == 0 && (mode & (1u << 5u)) != 0 && !s_raw_groups /* COMPUTE_DISPATCH_INITIATOR_USE_THREAD_DIMENSIONS */) {
+ thread_group_x = thread_group_x / tg_w + (thread_group_x % tg_w != 0);
+ thread_group_y = thread_group_y / tg_h + (thread_group_y % tg_h != 0);
+ thread_group_z = thread_group_z / tg_d + (thread_group_z % tg_d != 0);
+ }
+ // Guard: clamp group counts to a sane maximum (log when it happens).
+ // KYTY_MAX_GROUPS=: cap on a dispatch's group count per dimension (default 0xFFFFFF).
+ static const uint32_t kMaxGroups = [] {
+ const char* e = KYTY_ENV("KYTY_MAX_GROUPS");
+ return e != nullptr ? static_cast(std::strtoul(e, nullptr, 0)) : 0x00FFFFFFu;
+ }();
+ if (thread_group_x > kMaxGroups || thread_group_y > kMaxGroups || thread_group_z > kMaxGroups) {
+ std::fprintf(stderr, "[CsClamp] groups %u,%u,%u clamped to %u\n", thread_group_x, thread_group_y,
+ thread_group_z, kMaxGroups);
+ thread_group_x = std::min(thread_group_x, kMaxGroups);
+ thread_group_y = std::min(thread_group_y, kMaxGroups);
+ thread_group_z = std::min(thread_group_z, kMaxGroups);
+ }
// The argument producer can still be queued. Snapshot, convert and clamp on
// the GPU before binding the consumer's pipeline or resources.
id indirect_args = nil;
@@ -6922,20 +7381,66 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
(unsigned long long)indirect_args_addr, cover.c_str());
}
}
+ const auto word_trace = PrepareComputeWordTrace(cs_hash, compute_info);
{
char fault_label[128];
- if (indirect_args_addr != 0)
+ if (word_trace.id != 0)
+ std::snprintf(fault_label, sizeof(fault_label), "cs hash=0x%016llx word_trace=%llu",
+ (unsigned long long)cs_hash, (unsigned long long)word_trace.id);
+ else if (indirect_args_addr != 0)
std::snprintf(fault_label, sizeof(fault_label), "cs hash=0x%016llx indirect args=0x%llx",
(unsigned long long)cs_hash, (unsigned long long)indirect_args_addr);
else std::snprintf(fault_label, sizeof(fault_label), "cs hash=0x%016llx", (unsigned long long)cs_hash);
KytyFaultOpSet(fault_label);
}
+ id device_lds = nil;
+ if (const uint32_t lds_dwords = compute_info.stage.program ? compute_info.stage.program->metal_device_lds_dwords : 0;
+ lds_dwords != 0) {
+ std::array groups {thread_group_x, thread_group_y, thread_group_z};
+ if (indirect_args != nil) {
+ // Size the backing from the GPU-produced, normalized dispatch arguments.
+ MetalContext::Instance().CommitCommandBuffer(true);
+ std::memcpy(groups.data(), indirect_args.contents, sizeof(groups));
+ }
+ if (std::find(groups.begin(), groups.end(), 0u) != groups.end()) {
+ CountDispatchStat(5);
+ return;
+ }
+ const auto device = MetalContext::Instance().GetDevice();
+ const uint64_t limit = std::min(device.maxBufferLength, 64u << 20u);
+ uint64_t bytes = uint64_t(lds_dwords) * sizeof(uint32_t);
+ for (uint32_t dim: groups) {
+ if (bytes > limit / dim) {
+ std::fprintf(stderr, "[MetalLDS] cs=%016llx skipped: %u bytes/group, %ux%ux%u groups exceed backing budget %llu\n",
+ (unsigned long long)cs_hash, lds_dwords * 4u, groups[0], groups[1], groups[2],
+ (unsigned long long)limit);
+ CountDispatchStat(4);
+ return;
+ }
+ bytes *= dim;
+ }
+ device_lds = KytyNewBuffer(device, bytes, MTLResourceStorageModePrivate, __LINE__);
+ if (device_lds == nil) {
+ std::fprintf(stderr, "[MetalLDS] cs=%016llx failed to allocate %llu bytes\n",
+ (unsigned long long)cs_hash, (unsigned long long)bytes);
+ CountDispatchStat(4);
+ return;
+ }
+ static std::unordered_set reported;
+ if (reported.insert(cs_hash).second) {
+ std::fprintf(stderr, "[MetalLDS] cs=%016llx device backing: %u bytes/group, hardware limit %lu\n",
+ (unsigned long long)cs_hash, lds_dwords * 4u, (unsigned long)device.maxThreadgroupMemoryLength);
+ }
+ }
const bool compute_pass_ok = MetalDrawExecutor::Instance().BeginComputePass();
if (!compute_pass_ok) CountDispatchStat(4);
if (compute_pass_ok) {
if (pstate) {
MetalDrawExecutor::Instance().SetComputePipeline(pstate);
}
+ if (device_lds != nil) {
+ MetalDrawExecutor::Instance().SetComputeBuffer(device_lds, 0, ShaderRecompiler::Msl::DeviceLdsBufferIndex);
+ }
if (id cenc = MetalContext::Instance().GetActiveComputeEncoder()) {
for (id r: cs_residency) {
MetalDrawExecutor::Instance().UseResource(r, ResidencyUsage(r));
@@ -7057,6 +7562,7 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
}
auto alloc = MetalBufferManager::Instance().GetBufferForGuestRange(
addr, size != 0 ? size : 4096);
+ bool lighting_snapshot = false;
if (alloc.gpu_addr != 0 && compute_info.stage.program && b < compute_info.stage.program->info.buffers.size() &&
!compute_info.stage.program->info.buffers[b].written) {
// Narrow experiment: FC27's range-copy kernel reads b1 from a recycled 512-KiB CPU
@@ -7087,6 +7593,12 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
const bool skin_upload = (s_skin_snapshot && cs_hash == 0x0cf7218b746c22e4ull && b == 1) || s_staging_snapshot;
const uint64_t live_gpu = alloc.gpu_addr;
alloc = SnapshotBytes(alloc, addr, size != 0 ? size : 4096, skin_upload);
+ if (SnapshotGt7LightingConstants(cs_hash, b, size, compute_info.stage.program->info.buffers[b])) {
+ if (auto copy = MetalBufferManager::Instance().SnapshotReadOnly(alloc, size); copy.IsValid()) {
+ alloc = copy;
+ lighting_snapshot = true;
+ }
+ }
if (skin_upload) {
static uint64_t last_log_flip = UINT64_MAX;
const uint64_t flip = Libs::Graphics::TraceWindow::g_flip.load();
@@ -7107,6 +7619,20 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
const size_t avail = static_cast([alloc.buffer length]) - alloc.offset;
sizes[b] = static_cast(std::min(sizes[b], avail));
}
+ if (word_trace.id != 0 && b == word_trace.slot) {
+ uint32_t words[4] {};
+ bool ok = true;
+ if (lighting_snapshot) {
+ std::memcpy(words, static_cast(alloc.cpu_addr) + word_trace.offset, sizeof(words));
+ } else {
+ ok = Libs::LibKernel::Memory::TryReadBacking(addr + word_trace.offset, words, sizeof(words));
+ }
+ std::fprintf(stderr, "[CsWordBind] id=%llu flip=%llu guest=%llx gpu=%llx size=%u cpu_ok=%d snapshot=%d words=%08x,%08x,%08x,%08x\n",
+ (unsigned long long)word_trace.id,
+ (unsigned long long)Libs::Graphics::TraceWindow::g_flip.load(),
+ (unsigned long long)(addr + word_trace.offset), (unsigned long long)alloc.gpu_addr,
+ sizes[b], ok, lighting_snapshot, words[0], words[1], words[2], words[3]);
+ }
if (KYTY_ENV("KYTY_MTL_FAULT_INFO") != nullptr && alloc.gpu_addr == 0) {
std::fprintf(stderr, "[CsZeroPtr] hash=0x%016llx b=%zu addr=0x%llx size=%zu buffer=%p\n",
(unsigned long long)cs_hash, b, (unsigned long long)addr, size, (__bridge void*)alloc.buffer);
@@ -7185,6 +7711,11 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
for (size_t f = 0; f < 8; ++f) {
tex.fields[f] = desc.dwords[f];
}
+ if (id cube = ConstantComputeCube(cprog, res, tex)) {
+ if (64u + res < std::size(arg_ptrs)) arg_ptrs[64u + res] = [cube gpuResourceID]._impl;
+ cs_residency.push_back(cube);
+ continue;
+ }
const uint64_t addr = tex.Base40();
const uint32_t w = static_cast(tex.Width5()) + 1u;
const uint32_t h = static_cast(tex.Height5()) + 1u;
@@ -7194,6 +7725,32 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
// memory, which would read back as zeros.
id texture = nil;
const char* via = "";
+ const bool declared_array = res < cprog.info.images.size() &&
+ cprog.info.images[res].dimension == ShaderRecompiler::Decoder::ImageDimension::Dim2DArray;
+ const bool cube = res < cprog.info.images.size() && cprog.info.images[res].cube;
+ const bool gpu_arrays = GpuWritableArraysEnabled();
+ if (declared_array && storage && tex.Type() == Prospero::ImageType::kColor2DArray &&
+ tex.BaseArray5() == 0 && tex.BaseLevel() <= tex.LastLevel() && AllocateGpuWritableArray(addr)) {
+ const auto fmt = MetalFormatFromBufferFormat(tex.Format());
+ const uint32_t layers = uint32_t(tex.Depth()) + 1u;
+ const uint32_t levels = std::max(tex.LastLevel(), tex.MaxMip()) + 1u;
+ if ((GuestTextureUsage(fmt) & MTLTextureUsageShaderWrite) != 0 && layers <= 2048 &&
+ levels <= std::bit_width(std::max(w, h)) &&
+ uint64_t(w) * h * layers * BytesPerPixel(fmt) <= (128ull << 20)) {
+ texture = AliasedImageFor(addr, w, h, fmt, levels, layers);
+ via = "array-storage";
+ }
+ } else if (!storage && (declared_array || cube)) {
+ texture = GpuWrittenArrayFor(tex, w, h);
+ if (texture != nil) via = "array-writer";
+ }
+ if (texture == nil && StrictCubeBindings() && cprog.native_msl && cube && !storage &&
+ tex.Type() == Prospero::ImageType::kCube) {
+ texture = ComputeGuestImageFor(cprog, res, tex, w, h, addr);
+ if (texture == nil) texture = NullImageFor(cprog.info.images[res], false);
+ if (texture == nil) continue;
+ via = "cube-layout";
+ }
{
// GPU-produced images are views over the guest memory (see GpuSurfaceFor): writes and later reads meet in the same bytes.
// Opt-in until validated (KYTY_UMA_SURFACES=1): with it on, producer/consumer pairs of GPU-produced images meet in the same
@@ -7238,7 +7795,7 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
cprog.info.images[res].dimension == ShaderRecompiler::Decoder::ImageDimension::Dim2D &&
tex.Type() != Prospero::ImageType::kCube && tex.Type() != Prospero::ImageType::kColor3D &&
tex.BaseLevel() == 0 && tex.LastLevel() == 0;
- if (!s_uma_off && uma_allowed && plain_2d && uma_fmt != MTLPixelFormatInvalid && !IsCompressedFormat(uma_fmt) &&
+ if (texture == nil && !s_uma_off && uma_allowed && plain_2d && uma_fmt != MTLPixelFormatInvalid && !IsCompressedFormat(uma_fmt) &&
(!storage || (GuestTextureUsage(uma_fmt) & MTLTextureUsageShaderWrite) != 0)) {
bool special_writer = false;
if (!storage) {
@@ -7260,8 +7817,8 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
if (id last = LastGpuWriterTexture(addr)) {
const MTLPixelFormat want_fmt = MetalFormatFromBufferFormat(tex.Format());
if (last.width == w && last.height == h && last.mipmapLevelCount == 1 && last.textureType == MTLTextureType2D &&
- SameTexelSize(last, want_fmt)) {
- texture = ReinterpretFormat(last, want_fmt);
+ (CanSampleDepthAsFloat(last.pixelFormat, want_fmt) || SameTexelSize(last, want_fmt))) {
+ texture = CanSampleDepthAsFloat(last.pixelFormat, want_fmt) ? last : ReinterpretFormat(last, want_fmt);
via = "lastwriter";
}
}
@@ -7511,7 +8068,8 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
}
if (!texture) continue;
const auto declared_format = MetalFormatFromBufferFormat(tex.Format());
- if (declared_format != MTLPixelFormatInvalid && texture.pixelFormat != declared_format) {
+ if (declared_format != MTLPixelFormatInvalid && texture.pixelFormat != declared_format &&
+ (storage || !CanSampleDepthAsFloat(texture.pixelFormat, declared_format))) {
// The surface was found under another format of the same texel size (a kernel packs RG11B10 by hand into an R32Uint
// image, another reads the same bytes as RG11B10): bind a view of the declared format over the same bytes. Bound
// as it was, an RG11B10 image read through an R32Uint texture (and back) returned garbage.
@@ -7532,7 +8090,9 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
}
// T# base/last level: bind a view of that level range (the surface keeps one base address for all levels).
bool mip_view_bound = false;
- if (texture.textureType == MTLTextureType2D && (tex.BaseLevel() > 0 || tex.LastLevel() > 0)) {
+ const bool array_texture = gpu_arrays && texture.textureType == MTLTextureType2DArray;
+ if ((texture.textureType == MTLTextureType2D || array_texture) &&
+ (tex.BaseLevel() > 0 || tex.LastLevel() > 0)) {
RequestRtMips(addr, static_cast(tex.LastLevel()) + 1u);
const NSUInteger avail_levels = texture.mipmapLevelCount;
if (avail_levels > 1 && tex.BaseLevel() < avail_levels) {
@@ -7542,7 +8102,7 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
avail_levels - base_l);
cs_residency.push_back(texture);
id full_tex = texture;
- texture = MipRangeView(texture, base_l, cnt_l);
+ if (base_l != 0 || cnt_l != avail_levels) texture = MipRangeView(texture, base_l, cnt_l);
PassTraceRebind(full_tex, texture, storage);
mip_view_bound = true;
}
@@ -7551,7 +8111,7 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
std::fprintf(stderr, "[CsMip] flip=%llu cs=0x%016llx res=%u %s addr=0x%llx T# levels=%u..%u texture=%lux%lu levels=%lu bound_view=%d\n", static_cast(Libs::Graphics::TraceWindow::g_flip.load()),
static_cast(cprog.shader_hash), (unsigned)res, storage ? "STORE" : "load ", static_cast(addr),
(unsigned)tex.BaseLevel(), (unsigned)tex.LastLevel(), (unsigned long)texture.width, (unsigned long)texture.height, (unsigned long)texture.mipmapLevelCount, mip_view_bound ? 1 : 0);
- if (!mip_view_bound && ShaderRecompiler::IR::ImageBindingResourceClass(binding.kind) == ShaderRecompiler::IR::ImageResourceClass::Storage) {
+ if (!array_texture && !mip_view_bound && storage) {
RegisterComputeWrittenImage(addr, (__bridge void*)texture);
}
{
@@ -7577,10 +8137,14 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
const uint32_t slot = cprog.native_msl
? 64u + res
: ShaderRecompiler::IR::NativeBinding(cprog.stage, binding.kind) + static_cast(r);
- const bool declared_array = res < cprog.info.images.size() &&
- (cprog.info.images[res].dimension == ShaderRecompiler::Decoder::ImageDimension::Dim2DArray);
texture = ConformToDeclaredArray(texture, declared_array);
- id bound_tex = (!storage && !mip_view_bound) ? ApplyDstSel(texture, tex) : texture;
+ id bound_tex = (!storage && (!mip_view_bound || array_texture)) ? ApplyDstSel(texture, tex) : texture;
+ if (word_trace.id != 0) {
+ std::fprintf(stderr, "[CsWordImage] id=%llu res=%u guest=%llx guest_type=%u depth=%u cube=%d array=%d via=%s metal_type=%lu layers=%lu\n",
+ (unsigned long long)word_trace.id, res, (unsigned long long)addr, (unsigned)tex.Type(),
+ (unsigned)tex.Depth(), cube, declared_array, via, (unsigned long)bound_tex.textureType,
+ (unsigned long)bound_tex.arrayLength);
+ }
if (slot < 256) {
arg_ptrs[slot] = [bound_tex gpuResourceID]._impl;
}
@@ -7796,23 +8360,23 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
// Buffers: bind by argument index (the buffer index used by the shader's [[id(N)]]).
const auto& bsnap = *compute_info.stage.resources;
for (size_t b = 0; b < bsnap.buffers.size() && b < 64; ++b) {
- const auto& desc = bsnap.buffers[b];
- const uint64_t baddr = (static_cast(desc.dwords[1] & 0xFFFF) << 32) | desc.dwords[0];
- if (baddr == 0) continue;
- const size_t bsize = sizes[b] != 0 ? sizes[b] : 4096;
- auto balloc = MetalBufferManager::Instance().GetBufferForGuestRange(baddr, bsize);
+ const auto& balloc = cs_buffers[b];
+ if (!balloc.IsValid()) continue;
+ const size_t bsize = std::min(sizes[b] != 0 ? sizes[b] : 4096, balloc.size);
if (balloc.gpu_addr != 0 && balloc.buffer != nil) {
[ae setBuffer:balloc.buffer offset:balloc.offset atIndex:static_cast(cs_buf_base + b)];
if (id uenc = MetalContext::Instance().GetActiveComputeEncoder()) {
[uenc useResource:balloc.buffer usage:(MTLResourceUsageRead | MTLResourceUsageWrite)];
}
}
- if (KYTY_ENV("KYTY_CS_PROBE") != nullptr && KYTY_ENV("KYTY_PROBE_HASH") != nullptr &&
+ if (balloc.buffer.contents != nullptr && KYTY_ENV("KYTY_CS_PROBE") != nullptr && KYTY_ENV("KYTY_PROBE_HASH") != nullptr &&
std::strtoull(KYTY_ENV("KYTY_PROBE_HASH"), nullptr, 0) == compute_info.stage.program->shader_hash) {
const uint32_t* w = reinterpret_cast(static_cast([balloc.buffer contents]) + balloc.offset);
size_t nz = 0;
const size_t n = bsize / 4;
for (size_t i = 0; i < n; ++i) nz += w[i] != 0;
+ const auto& desc = bsnap.buffers[b];
+ const uint64_t baddr = (uint64_t(desc.dwords[1] & 0xffff) << 32) | desc.dwords[0];
std::fprintf(stderr, "[CsIn] buf%zu guest=0x%llx size=%zu nonzero_dwords=%zu/%zu first:", b,
(unsigned long long)baddr, bsize, nz, n);
for (size_t i = 0; i < 8 && i < n; ++i) std::fprintf(stderr, " %08x", w[i]);
@@ -7833,7 +8397,9 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
for (size_t f = 0; f < 8; ++f) tx.fields[f] = d.dwords[f];
const uint32_t w = static_cast(tx.Width5()) + 1u;
const uint32_t h = static_cast(tx.Height5()) + 1u;
- id tt = ComputeGuestImageFor(*compute_info.stage.program, res, tx, w, h, tx.Base40());
+ const auto& cprog = *compute_info.stage.program;
+ id tt = ConstantComputeCube(cprog, res, tx);
+ if (tt == nil) tt = ComputeGuestImageFor(cprog, res, tx, w, h, tx.Base40());
if (tt == nil && KYTY_ENV("KYTY_MTL_FAULT_INFO") != nullptr) {
std::fprintf(stderr, "[CsNullImg] hash=0x%016llx res=%u kind=%u addr=0x%llx %ux%u\n",
(unsigned long long)compute_info.stage.program->shader_hash, res,
@@ -7882,32 +8448,7 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
(unsigned long long)arg_ptrs[49], (unsigned long long)arg_ptrs[104]);
}
- uint32_t tg_w = compute_info.threads_num[0] > 0 ? compute_info.threads_num[0] : 64;
- uint32_t tg_h = compute_info.threads_num[1] > 0 ? compute_info.threads_num[1] : 1;
- uint32_t tg_d = compute_info.threads_num[2] > 0 ? compute_info.threads_num[2] : 1;
- // COMPUTE_DISPATCH_INITIATOR.USE_THREAD_DIMENSIONS: the dispatch dimensions are thread counts, not group counts
- // (the game's memory fill/copy kernels dispatch one thread per dword). The hardware launches ceil(threads / group size)
- // groups; taking the counts as groups would run group-size times too many threads per dimension.
- static const bool s_raw_groups = KYTY_ENV("KYTY_CS_RAW_GROUPS") != nullptr; // old behaviour, for A/B runs
- if (indirect_args_addr == 0 && (mode & (1u << 5u)) != 0 && !s_raw_groups /* COMPUTE_DISPATCH_INITIATOR_USE_THREAD_DIMENSIONS */) {
- thread_group_x = thread_group_x / tg_w + (thread_group_x % tg_w != 0);
- thread_group_y = thread_group_y / tg_h + (thread_group_y % tg_h != 0);
- thread_group_z = thread_group_z / tg_d + (thread_group_z % tg_d != 0);
- }
- // Guard: clamp group counts to a sane maximum (log when it happens).
- // KYTY_MAX_GROUPS=: cap on a dispatch's group count per dimension (default 0xFFFFFF).
- static const uint32_t kMaxGroups = [] {
- const char* e = KYTY_ENV("KYTY_MAX_GROUPS");
- return e != nullptr ? static_cast(std::strtoul(e, nullptr, 0)) : 0x00FFFFFFu;
- }();
- if (thread_group_x > kMaxGroups || thread_group_y > kMaxGroups || thread_group_z > kMaxGroups) {
- std::fprintf(stderr, "[CsClamp] groups %u,%u,%u clamped to %u\n", thread_group_x, thread_group_y,
- thread_group_z, kMaxGroups);
- thread_group_x = std::min(thread_group_x, kMaxGroups);
- thread_group_y = std::min(thread_group_y, kMaxGroups);
- thread_group_z = std::min(thread_group_z, kMaxGroups);
- }
- // KYTY_CS_PROBE debug: bind a zeroed counter at buffer 26 and report how many threads ran.
+ // KYTY_CS_PROBE debug: bind a zeroed counter at buffer 26 and report how many threads ran.
const bool cs_probe_here = KYTY_ENV("KYTY_CS_PROBE") != nullptr && compute_info.stage.program != nullptr &&
KYTY_ENV("KYTY_PROBE_HASH") != nullptr &&
std::strtoull(KYTY_ENV("KYTY_PROBE_HASH"), nullptr, 0) ==
@@ -8044,6 +8585,15 @@ static bool DumpRtBeforeDraw(const HW::Context& context, uint64_t ps_hash,
MetalDrawExecutor::Instance().SetComputeBuffer(s_nan_dbg, 0, 28);
nan_dbg = s_nan_dbg;
}
+ if (word_trace.id != 0 && compute_pass_ok) {
+ const uint64_t sequence = word_trace.id;
+ id dispatch_command = MetalContext::Instance().GetCurrentCommandBuffer();
+ [dispatch_command addCompletedHandler:^(id done) {
+ std::fprintf(stderr, "[CsWordDone] id=%llu status=%lu gpu_ms=%.2f\n",
+ (unsigned long long)sequence, (unsigned long)done.status,
+ 1000.0 * (done.GPUEndTime - done.GPUStartTime));
+ }];
+ }
if (indirect_args) {
MetalDrawExecutor::Instance().DispatchIndirect(indirect_args, 0, host_w, host_h, host_d);
} else {
diff --git a/src/graphics/host_gpu/metal/metalShader.mm b/src/graphics/host_gpu/metal/metalShader.mm
index 7c28eac..c677e85 100644
--- a/src/graphics/host_gpu/metal/metalShader.mm
+++ b/src/graphics/host_gpu/metal/metalShader.mm
@@ -567,6 +567,70 @@ static void AddMissingVertexVaryings(std::string& msl) {
}
}
+// SPIRV-Cross stages triangle indices in an array of 16-byte uint3s before
+// exporting the mesh. Each guest index is ten bits, so the staging array can
+// preserve the same values in one dword per triangle.
+static void PackMeshTriangleIndices(std::string& msl) {
+ static const std::regex declaration(
+ R"(threadgroup uint3 gl_PrimitiveTriangleIndicesEXT\[(\d+)\];)");
+ static const std::regex parameter(
+ R"(threadgroup uint3 \(&gl_PrimitiveTriangleIndicesEXT\)\[(\d+)\])");
+ static const std::regex store(
+ R"(gl_PrimitiveTriangleIndicesEXT\[([^\]]+)\] = (uint3\([^;]+\));)");
+ static const std::regex load(
+ R"(gl_PrimitiveTriangleIndicesEXT\[([^\]]+)\]\.([xyz]))");
+ if (!std::regex_search(msl, declaration) || !std::regex_search(msl, store) ||
+ !std::regex_search(msl, load)) {
+ return;
+ }
+
+ auto packed = std::regex_replace(msl, declaration, "threadgroup uint gl_PrimitiveTriangleIndicesEXT[$1];");
+ packed = std::regex_replace(packed, parameter, "threadgroup uint (&gl_PrimitiveTriangleIndicesEXT)[$1]");
+ packed = std::regex_replace(packed, store, "gl_PrimitiveTriangleIndicesEXT[$1] = kyty_pack_triangle($2);");
+ for (uint32_t component = 0; component < 3u; ++component) {
+ const std::string suffix(1, "xyz"[component]);
+ const std::regex component_load(
+ R"(gl_PrimitiveTriangleIndicesEXT\[([^\]]+)\]\.)" + suffix);
+ packed = std::regex_replace(
+ packed, component_load,
+ "extract_bits(gl_PrimitiveTriangleIndicesEXT[$1], " + std::to_string(component * 10u) + "u, 10u)");
+ }
+ const auto metal_std = packed.find("#include ");
+ if (metal_std == std::string::npos) {
+ return;
+ }
+ const auto insert_at = packed.find('\n', metal_std) + 1;
+ packed.insert(insert_at,
+ "static inline uint kyty_pack_triangle(metal::uint3 indices) {\n"
+ " return indices.x | (indices.y << 10u) | (indices.z << 20u);\n"
+ "}\n\n");
+ msl = std::move(packed);
+}
+
+// Write just the selected shader when a hash filter is given.
+static void DumpMslSource(NSString* source_str, uint64_t shader_hash) {
+ const char* dump_hash = KYTY_ENV("KYTY_MSL_DUMP_HASH");
+ if (const char* dump_dir = KYTY_ENV("KYTY_MSL_DUMP_DIR");
+ dump_dir && (!dump_hash || std::strtoull(dump_hash, nullptr, 16) == shader_hash)) {
+ NSString* directory = [NSString stringWithUTF8String:dump_dir];
+ NSError* dump_error = nil;
+ if (directory == nil || directory.length == 0) {
+ std::fprintf(stderr, "[MslDump] invalid or empty KYTY_MSL_DUMP_DIR\n");
+ } else if (![[NSFileManager defaultManager] createDirectoryAtPath:directory
+ withIntermediateDirectories:YES attributes:nil error:&dump_error]) {
+ std::fprintf(stderr, "[MslDump] cannot create %s: %s\n", dump_dir,
+ dump_error.localizedDescription.UTF8String);
+ } else {
+ NSString* filename = [NSString stringWithFormat:@"0x%016llx.metal", static_cast(shader_hash)];
+ NSString* path = [directory stringByAppendingPathComponent:filename];
+ if (![source_str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&dump_error]) {
+ std::fprintf(stderr, "[MslDump] cannot write %s: %s\n", path.UTF8String,
+ dump_error.localizedDescription.UTF8String);
+ }
+ }
+ }
+}
+
MetalShaderCompileResult MetalShaderManager::CompileSpirvToFunction(
std::span spirv,
const char* entry_point,
@@ -607,7 +671,8 @@ static void AddMissingVertexVaryings(std::string& msl) {
// KYTY_SPVC_ABI: pin every descriptor to the id range from ComputeSpvcAbiLayout so arrays
// no longer take consecutive ids that collide with the neighbouring kinds.
static const bool s_spvc_abi = KYTY_ENV("KYTY_SPVC_ABI") != nullptr;
- if (s_spvc_abi && abi != nullptr) {
+ const bool mesh_stage = stage == static_cast(ShaderType::Mesh);
+ if ((s_spvc_abi || mesh_stage) && abi != nullptr) {
const auto model = compiler.get_execution_model();
for (const auto& e: abi->entries) {
spirv_cross::MSLResourceBinding rb {};
@@ -627,11 +692,26 @@ static void AddMissingVertexVaryings(std::string& msl) {
}
}
+ if (mesh_stage) {
+ spirv_cross::MSLResourceBinding push {};
+ push.stage = compiler.get_execution_model();
+ push.desc_set = spirv_cross::kPushConstDescSet;
+ push.binding = spirv_cross::kPushConstBinding;
+ push.msl_buffer = 1;
+ compiler.add_msl_resource_binding(push);
+ }
result.msl_source = SanitizeMslSource(compiler.compile());
+ if (mesh_stage) {
+ PackMeshTriangleIndices(result.msl_source);
+ if (KYTY_ENV("KYTY_METAL_MESH_SINGLE_LAYER") != nullptr) {
+ static const std::regex layer_output(R"(spvP\.gl_Layer = [^;]+;)");
+ result.msl_source = std::regex_replace(result.msl_source, layer_output, "spvP.gl_Layer = 0u;");
+ }
+ }
if (result.msl_source.find("[[buffer(0)]]") != std::string::npos) {
RecordArgBuffer0(shader_hash);
}
- {
+ if (!mesh_stage) {
// Diagnostic: total threadgroup memory declared by this MSL (Metal limit 32768 bytes).
size_t tg_total = 0;
for (size_t pos = 0; (pos = result.msl_source.find("threadgroup ", pos)) != std::string::npos; ++pos) {
@@ -703,6 +783,7 @@ static void AddMissingVertexVaryings(std::string& msl) {
NSError* error = nil;
NSString* source_str = [NSString stringWithUTF8String:result.msl_source.c_str()];
+ DumpMslSource(source_str, shader_hash);
id library =
[device newLibraryWithSource:source_str options:compile_options error:&error];
if (!library) {
@@ -856,25 +937,7 @@ static void AddMissingVertexVaryings(std::string& msl) {
// Pixel shader probes (KYTY_PS_PROBE) rewrite the entry returns of natively emitted MSL as well.
ApplyPsProbe(result.msl_source, shader_hash);
NSString* source_str = [NSString stringWithUTF8String:result.msl_source.c_str()];
- // KYTY_MSL_DUMP_DIR=: write the generated MSL of every directly compiled program as /.metal.
- if (const char* dump_dir = KYTY_ENV("KYTY_MSL_DUMP_DIR")) {
- NSString* directory = [NSString stringWithUTF8String:dump_dir];
- NSError* dump_error = nil;
- if (directory == nil || directory.length == 0) {
- std::fprintf(stderr, "[MslDump] invalid or empty KYTY_MSL_DUMP_DIR\n");
- } else if (![[NSFileManager defaultManager] createDirectoryAtPath:directory
- withIntermediateDirectories:YES attributes:nil error:&dump_error]) {
- std::fprintf(stderr, "[MslDump] cannot create %s: %s\n", dump_dir,
- dump_error.localizedDescription.UTF8String);
- } else {
- NSString* filename = [NSString stringWithFormat:@"0x%016llx.metal", static_cast(shader_hash)];
- NSString* path = [directory stringByAppendingPathComponent:filename];
- if (![source_str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&dump_error]) {
- std::fprintf(stderr, "[MslDump] cannot write %s: %s\n", path.UTF8String,
- dump_error.localizedDescription.UTF8String);
- }
- }
- }
+ DumpMslSource(source_str, shader_hash);
id library =
[device newLibraryWithSource:source_str options:compile_options error:&error];
if (!library) {
diff --git a/src/graphics/host_gpu/metal/metalTexture.mm b/src/graphics/host_gpu/metal/metalTexture.mm
index b290ca9..4ca3b9f 100644
--- a/src/graphics/host_gpu/metal/metalTexture.mm
+++ b/src/graphics/host_gpu/metal/metalTexture.mm
@@ -43,6 +43,7 @@ MTLPixelFormat MetalFormatFromBufferFormat(Prospero::BufferFormat format) {
case Prospero::BufferFormat::k16_16SInt: return MTLPixelFormatRG16Sint;
case Prospero::BufferFormat::k16_16Float: return MTLPixelFormatRG16Float;
+ case Prospero::BufferFormat::k10_11_11Float:
case Prospero::BufferFormat::k11_11_10Float: return MTLPixelFormatRG11B10Float;
case Prospero::BufferFormat::k10_10_10_2UNorm: return MTLPixelFormatRGB10A2Unorm;
case Prospero::BufferFormat::k10_10_10_2SNorm: return MTLPixelFormatRGB10A2Unorm;
diff --git a/src/graphics/host_gpu/renderer/image/textureCommon.cpp b/src/graphics/host_gpu/renderer/image/textureCommon.cpp
index ea90c5c..b0c7eac 100644
--- a/src/graphics/host_gpu/renderer/image/textureCommon.cpp
+++ b/src/graphics/host_gpu/renderer/image/textureCommon.cpp
@@ -35,6 +35,11 @@ struct HostFormatInfo {
HostFormatInfo ResolveHostFormat(Prospero::BufferFormat guest_format,
Prospero::ChannelOrder order) {
+ if (guest_format == Prospero::BufferFormat::k10_11_11Float) {
+ // The host's 10-bit blue stores the guest's 10-bit red. Keep the packed bits
+ // unchanged so aliased guest buffers retain their layout.
+ return {vk::Format::eB10G11R11UfloatPack32, Prospero::ColorMappingBgra};
+ }
if (order == Prospero::ChannelOrder::kAlt) {
switch (guest_format) {
case Prospero::BufferFormat::k8_8_8_8UNorm:
diff --git a/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp b/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
index 782c677..f2f39b5 100644
--- a/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
+++ b/src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
@@ -791,7 +791,12 @@ struct PipelineCache::ProgramCache {
ShaderRecompiler::TranslateResult translated,
ShaderRecompiler::IR::ResourceSpecialization specialization,
uint32_t push_data_start_dword) {
- auto result = ShaderRecompiler::CompileProgram(std::move(translated), options,
+ auto backend_options = options;
+#if defined(__APPLE__)
+ backend_options.metal_guest_address_space =
+ options.stage == ShaderType::Mesh && Metal::UseNativeMetalBackend();
+#endif
+ auto result = ShaderRecompiler::CompileProgram(std::move(translated), backend_options,
specialization, push_data_start_dword);
// KYTY_MSL_DIRECT=<0|1|2>: exercise the direct RDNA->MSL emitter alongside the
@@ -840,7 +845,9 @@ struct PipelineCache::ProgramCache {
#if defined(__APPLE__)
if (Metal::UseNativeMetalBackend()) {
- const uint64_t metal_hash = options.shader_hash ^ MetalFunctionVariant(options);
+ // Compiled mesh shaders use a different guest-address and argument-buffer layout.
+ const uint64_t mesh_revision = options.stage == ShaderType::Mesh ? 0x97470a932deaf19bull : 0;
+ const uint64_t metal_hash = options.shader_hash ^ MetalFunctionVariant(options) ^ mesh_revision;
// KYTY_MSL_BACKEND=1 compiles the direct RDNA->MSL translation. Shaders
// the MSL backend cannot express fall back to the SPIR-V path below.
static const bool s_msl_backend = [] {
@@ -863,7 +870,7 @@ struct PipelineCache::ProgramCache {
const char* value = std::getenv("KYTY_MSL_ONLY");
return value != nullptr && value[0] == '1';
}();
- if (s_msl_only) {
+ if (s_msl_only && options.stage != ShaderType::Mesh) {
auto msl = ShaderRecompiler::Msl::EmitProgram(result.program, options.input_info);
uint64_t msl_hash = Metal::NativeMslFunctionKey(
metal_hash, static_cast(options.stage), msl.source, msl.success);
@@ -928,6 +935,7 @@ struct PipelineCache::ProgramCache {
auto info = std::move(result.program).TakeCompiledInfo();
info.shader_hash = msl_hash;
info.native_msl = true;
+ info.metal_device_lds_dwords = msl.device_lds_dwords;
return {
.specialization = std::move(specialization),
.program = std::move(info),
@@ -949,7 +957,7 @@ struct PipelineCache::ProgramCache {
.handle = {.id = id, .module = nullptr},
};
}
- if (s_msl_backend && msl_stage_allowed) {
+ if (s_msl_backend && msl_stage_allowed && options.stage != ShaderType::Mesh) {
auto msl = ShaderRecompiler::Msl::EmitProgram(result.program, options.input_info);
if (msl.success) {
const uint64_t msl_hash = Metal::NativeMslFunctionKey(
@@ -963,6 +971,7 @@ struct PipelineCache::ProgramCache {
// variant hash, not the raw shader hash.
info.shader_hash = msl_hash;
info.native_msl = true;
+ info.metal_device_lds_dwords = msl.device_lds_dwords;
return {
.specialization = std::move(specialization),
.program = std::move(info),
@@ -974,8 +983,12 @@ struct PipelineCache::ProgramCache {
options.shader_hash, msl.unsupported.size());
}
const auto spvc_abi = Metal::ComputeSpvcAbiLayout(result.program.bindings, options.stage);
- Metal::MetalShaderManager::Instance().CompileSpirvToFunction(
+ const auto compiled = Metal::MetalShaderManager::Instance().CompileSpirvToFunction(
result.spirv, "main0", static_cast