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 @@ +ProsperoPROSPERONATIVE 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(options.stage), metal_hash, &spvc_abi); + if (options.stage == ShaderType::Mesh && !compiled.success) { + std::fprintf(stderr, "[MetalMesh] compiler failed for 0x%016" PRIx64 ": %s\n", + options.shader_hash, compiled.error_log.c_str()); + } const auto id = ++next_shader_id; auto info = std::move(result.program).TakeCompiledInfo(); info.shader_hash = metal_hash; @@ -1025,8 +1038,18 @@ struct PipelineCache::ProgramCache { lookup_key.hash = params.hash; lookup_key.user_data_count = params.user_data_count; lookup_key.code_size = static_cast(params.code.size()); - { ProfileDetailScope key_profile("cpu_program_static_key", params.hash); - BuildStageStaticKey(input_info, lookup_key.static_state); } + { + ProfileDetailScope key_profile("cpu_program_static_key", params.hash); +#if defined(__APPLE__) + if constexpr (std::is_same_v) { + const bool pulls_vertices = stage == ShaderType::Vertex && Metal::UseNativeMetalBackend(); + BuildStageStaticKey(input_info, lookup_key.static_state, pulls_vertices); + } else +#endif + { + BuildStageStaticKey(input_info, lookup_key.static_state); + } + } uint64_t profile_key = params.hash; if (profile.Active()) { ProfileCpuScope fingerprint(*ProfileThread().scheduler, "profile_fingerprint_cpu"); @@ -1449,21 +1472,28 @@ PipelineCache::GraphicsPrograms PipelineCache::GetGraphicsPrograms( } const bool mesh_active = vertex_info[0].logical_stage == ShaderType::Mesh; if (mesh_active) { - EXIT_NOT_IMPLEMENTED(!m_graphics.mesh_shader_enabled); - auto& mesh = vertex_info[0].mesh; - mesh.host_subgroup_size = m_graphics.subgroup_size; - const auto& limits = m_graphics.mesh_shader_properties; - const auto logical_threads = - mesh.threads_num[0] * mesh.threads_num[1] * mesh.threads_num[2]; - const auto host_threads = ((logical_threads + mesh.wave_size - 1u) / mesh.wave_size) * - std::min(mesh.host_subgroup_size, mesh.wave_size); - if (host_threads > limits.maxMeshWorkGroupInvocations || - host_threads > limits.maxMeshWorkGroupSize[0] || - mesh.max_vertices > limits.maxMeshOutputVertices || - mesh.max_primitives > limits.maxMeshOutputPrimitives || - mesh.lds_size_dwords * sizeof(uint32_t) > limits.maxMeshSharedMemorySize) { - EXIT("mesh shader exceeds host limits: threads=%u vertices=%u primitives=%u LDS=%u\n", - host_threads, mesh.max_vertices, mesh.max_primitives, mesh.lds_size_dwords); +#if defined(__APPLE__) + if (Metal::UseNativeMetalBackend()) { + vertex_info[0].mesh.host_subgroup_size = 32; + } else +#endif + { + EXIT_NOT_IMPLEMENTED(!m_graphics.mesh_shader_enabled); + auto& mesh = vertex_info[0].mesh; + mesh.host_subgroup_size = m_graphics.subgroup_size; + const auto& limits = m_graphics.mesh_shader_properties; + const auto logical_threads = + mesh.threads_num[0] * mesh.threads_num[1] * mesh.threads_num[2]; + const auto host_threads = ((logical_threads + mesh.wave_size - 1u) / mesh.wave_size) * + std::min(mesh.host_subgroup_size, mesh.wave_size); + if (host_threads > limits.maxMeshWorkGroupInvocations || + host_threads > limits.maxMeshWorkGroupSize[0] || + mesh.max_vertices > limits.maxMeshOutputVertices || + mesh.max_primitives > limits.maxMeshOutputPrimitives || + mesh.lds_size_dwords * sizeof(uint32_t) > limits.maxMeshSharedMemorySize) { + EXIT("mesh shader exceeds host limits: threads=%u vertices=%u primitives=%u LDS=%u\n", + host_threads, mesh.max_vertices, mesh.max_primitives, mesh.lds_size_dwords); + } } } ShaderParams pixel_params; @@ -1541,30 +1571,30 @@ ShaderProgram PipelineCache::GetComputeProgram(const HW::ComputeShaderInfo& regs ShaderComputeInputInfo& input_info) { input_info.host_subgroup_size = m_graphics.SupportsComputeWave64() ? 64u : 32u; const auto params = PrepareProgram(regs, sh, input_info); + // Metal's native emitter can back an oversized LDS with a private buffer. + // Keep the guest declaration intact through resource and shader compilation. + bool native_metal = false; #if defined(__APPLE__) - const auto max_lds_dwords = Metal::UseNativeMetalBackend() ? 8192u : - m_graphics.GetPhysicalDeviceProperties().limits.maxComputeSharedMemorySize / 4u; -#else - const auto max_lds_dwords = - m_graphics.GetPhysicalDeviceProperties().limits.maxComputeSharedMemorySize / 4u; + native_metal = Metal::UseNativeMetalBackend(); + if (native_metal) input_info.metal_threadgroup_limit_dwords = Metal::NativeMetalThreadgroupLimitDwords(); #endif - if (input_info.lds_size_dwords > max_lds_dwords) { - static std::atomic_bool warned = false; - if (!warned.exchange(true, std::memory_order_relaxed)) { - PipelineCacheLog("GPU warning: game compute shader requests {} bytes of LDS, but " - "the Vulkan device limit is {} bytes. Clamping LDS; rendering may " - "be incorrect.", - input_info.lds_size_dwords * 4u, max_lds_dwords * 4u); - } - } - input_info.lds_size_dwords = std::min(input_info.lds_size_dwords, max_lds_dwords); - // KYTY_CS_LDS_MIN=: raise the LDS declaration of every compute shader (diagnosis). + // KYTY_CS_LDS_MIN=: raise the LDS declaration (diagnosis). static const uint32_t lds_min = [] { const char* value = std::getenv("KYTY_CS_LDS_MIN"); return value != nullptr ? static_cast(std::strtoul(value, nullptr, 0)) : 0u; }(); - if (lds_min != 0 && input_info.lds_size_dwords < lds_min) { - input_info.lds_size_dwords = std::min(lds_min, max_lds_dwords); + input_info.lds_size_dwords = std::max(input_info.lds_size_dwords, lds_min); + if (!native_metal) { + const auto max_lds_dwords = m_graphics.GetPhysicalDeviceProperties().limits.maxComputeSharedMemorySize / 4u; + if (input_info.lds_size_dwords > max_lds_dwords) { + static std::atomic_bool warned = false; + if (!warned.exchange(true, std::memory_order_relaxed)) { + PipelineCacheLog("GPU warning: game compute shader requests {} bytes of LDS, but " + "the Vulkan device limit is {} bytes. Clamping LDS; rendering may " + "be incorrect.", input_info.lds_size_dwords * 4u, max_lds_dwords * 4u); + } + input_info.lds_size_dwords = max_lds_dwords; + } } uint32_t push_data_cursor = 0; auto program = m_program_cache->Get(params, input_info, push_data_cursor); diff --git a/src/graphics/shader/recompiler/ShaderRecompiler.cpp b/src/graphics/shader/recompiler/ShaderRecompiler.cpp index e5aec78..64dde0d 100644 --- a/src/graphics/shader/recompiler/ShaderRecompiler.cpp +++ b/src/graphics/shader/recompiler/ShaderRecompiler.cpp @@ -679,7 +679,7 @@ CompileResult CompileProgram(TranslateResult translated, const CompileOptions& o LOGF("%s phase begin: stage=%s hash=0x%016" PRIx64 " SPIR-V EmitProgram\n", GetDumpLabel(options), StageName(ir.stage), ir.shader_hash); - auto spirv = Spirv::EmitProgram(ir, options.input_info); + auto spirv = Spirv::EmitProgram(ir, options.input_info, options.metal_guest_address_space); LOGF("%s phase end: stage=%s hash=0x%016" PRIx64 " SPIR-V EmitProgram words=%" PRIu64 " elapsed_ms=%" PRIu64 "\n", GetDumpLabel(options), StageName(ir.stage), ir.shader_hash, diff --git a/src/graphics/shader/recompiler/ShaderRecompiler.h b/src/graphics/shader/recompiler/ShaderRecompiler.h index e243de7..8d8dc55 100644 --- a/src/graphics/shader/recompiler/ShaderRecompiler.h +++ b/src/graphics/shader/recompiler/ShaderRecompiler.h @@ -20,6 +20,7 @@ struct CompileOptions { uint64_t shader_hash = 0; bool dump_ir = true; bool early_dump = false; + bool metal_guest_address_space = false; const char* dump_label = nullptr; std::span user_data; std::span back_code; diff --git a/src/graphics/shader/recompiler/backend/msl/MslEmitter.cpp b/src/graphics/shader/recompiler/backend/msl/MslEmitter.cpp index a7dedb9..ebf5dfc 100644 --- a/src/graphics/shader/recompiler/backend/msl/MslEmitter.cpp +++ b/src/graphics/shader/recompiler/backend/msl/MslEmitter.cpp @@ -96,7 +96,7 @@ const char* MslType(IR::Type type) { case IR::Type::F16: return "half"; case IR::Type::F32: return "float"; case IR::Type::U64: return "ulong"; - case IR::Type::F64: return "double"; + case IR::Type::F64: return "ulong"; // Metal has no native double type. case IR::Type::U32x2: return "uint2"; case IR::Type::U32x3: return "uint3"; case IR::Type::U32x4: return "uint4"; @@ -283,7 +283,11 @@ struct Emitter { } break; case IR::StageInputKind::Layer: - case IR::StageInputKind::SampleId: unsupported.push_back("pixel input builtin"); break; + in_fields.push_back({"layer", "uint", "[[render_target_array_index]]"}); + break; + case IR::StageInputKind::SampleId: + in_fields.push_back({"sample_id", "uint", "[[sample_id]]"}); + break; default: break; } } @@ -313,6 +317,10 @@ struct Emitter { default: break; } } + if (input_info.pixel && input_info.pixel->alpha_blend_source_remap && !mrt_field.contains(1)) { + mrt_field[1] = "color1"; + out_fields.push_back({"color1", "float4", "[[color(0), index(1)]]"}); + } pixel_location_count = static_cast(in_fields.size()); } } @@ -662,13 +670,18 @@ struct Emitter { return bits; } - std::string TexelValue(const IR::ImageResource& image, const std::string& bits_in, - const IR::MemoryInfo* mem = nullptr) { - std::string bits = bits_in; - if (mem != nullptr && mem->data_bits == 16u) { - bits = "kyty_d16_unpack(" + bits_in + ", " + std::to_string(mem->dmask != 0u ? mem->dmask : 1u) + "u, " + - (ImageIsFloatClass(image) ? "true" : "false") + ")"; + std::string TexelValue(const IR::ImageResource& image, const std::string& logical, + uint32_t mask) { + // Metal writes the physical RGBA components. Reverse the descriptor's + // channel selection so a later sampled view sees the original logical values. + std::string bits = "uint4("; + for (uint32_t physical = 0; physical < 4u; ++physical) { + if (physical != 0) bits += ", "; + const uint32_t source = IR::ImageStoreSourceChannel(image.shader_swizzle, physical); + bits += source < 4u && ((mask >> source) & 1u) != 0 ? + logical + "." + std::string(1, "xyzw"[source]) : "0u"; } + bits += ")"; switch (image.numeric_class) { case Prospero::TextureNumericClass::Uint: return bits; case Prospero::TextureNumericClass::Sint: return "as_type(" + bits + ")"; @@ -875,12 +888,21 @@ struct Emitter { [[nodiscard]] uint32_t LdsDwords() const { if (program.stage != ShaderType::Compute) return 2048u; const uint32_t declared = input_info.compute ? input_info.compute->lds_size_dwords : 0u; - return declared != 0 ? std::min(declared, 8192u) : 8192u; + // Preserve the guest bounds. Metal validates the complete pipeline's + // threadgroup allocation against the selected device. + return declared != 0 ? declared : 8192u; + } + + [[nodiscard]] bool UsesDeviceLds() const { + const auto* cs = input_info.compute; + return program.stage == ShaderType::Compute && cs != nullptr && + cs->metal_threadgroup_limit_dwords != 0 && + LdsDwords() > cs->metal_threadgroup_limit_dwords && UsesLds(); } [[nodiscard]] bool UsesLds() const { for (const auto& info: program.memory_info) { - if (info.kind == IR::ResourceKind::Lds) { + if (info.kind == IR::ResourceKind::Lds || (info.kind == IR::ResourceKind::Gds && !GdsMem(info))) { return true; } } @@ -961,6 +983,8 @@ struct Emitter { unsupported.push_back("barycentric builtin without interface"); } return; + case IR::StageInputKind::Layer: EmitAssignment(inst, "in.layer"); return; + case IR::StageInputKind::SampleId: EmitAssignment(inst, "in.sample_id"); return; case IR::StageInputKind::WorkgroupId: EmitAssignment(inst, std::string("tgid.") + ComponentName(comp)); return; @@ -1006,6 +1030,39 @@ struct Emitter { } const auto attr = *attr_value; const auto chan = *chan_value; + if (program.stage == ShaderType::Vertex && input_info.vertex != nullptr && + attr < 27u && attr < static_cast(input_info.vertex->resources_num) && + program.info.buffers.size() <= 32u) { + const auto& vertex = *input_info.vertex; + const auto& resource = vertex.resources[attr]; + const auto format = Format::GetFormatInfo(resource.Format()); + const auto binding = vertex.resources_dst[attr].buffer_index; + if (!resource.SwizzleEnabled() && binding >= 0 && binding < vertex.buffers_num && + chan < format.component_count && format.component_bits[chan] > 0 && + format.component_bits[chan] <= 32 && format.type != Format::ComponentType::Unknown) { + const auto slot = std::to_string(32u + attr); + const auto bits = format.component_bits[chan]; + const auto offset = format.packed_bitfield ? 0u : Format::GetFormatComponentByteOffset(format, chan); + const auto bytes = format.packed_bitfield ? 4u : (bits + 7u) / 8u; + const auto id = vertex.buffers[binding].fetch_index != 0 ? "iid" : "vid"; + const auto stride = std::to_string(vertex.buffers[binding].stride); + const auto pos = "(ulong(" + std::string(id) + ") * " + stride + "u + " + std::to_string(offset) + "u)"; + const auto ptr = "((device uchar*)ab.buffers[" + slot + "])"; + std::string raw = "("; + for (uint32_t b = 0; b < bytes; ++b) { + if (b != 0) raw += " | "; + raw += "(uint(" + ptr + "[" + pos + " + " + std::to_string(b) + "u]) << " + std::to_string(b * 8) + "u)"; + } + raw += ")"; + if (format.packed_bitfield && bits < 32) { + raw = "((" + raw + " >> " + std::to_string(format.component_bit_offset[chan]) + + "u) & " + U32Literal((1u << bits) - 1u) + ")"; + } + EmitAssignment(inst, "(" + pos + " + " + std::to_string(bytes) + "u <= sizes[" + slot + + "] ? " + NormalizeFormatComponent(format, chan, raw) + " : 0u)"); + return; + } + } if (program.stage != ShaderType::Pixel) { Unsupported(inst, "vertex-stage attribute fetch"); EmitAssignment(inst, "0u"); @@ -1021,8 +1078,21 @@ struct Emitter { ComponentName(chan) + ")"); } + // Match the SPIR-V backend: a VM export updates whether this pixel survives. + bool TracksPixelValidMask() const { + return program.stage == ShaderType::Pixel && + std::ranges::any_of(program.export_info, [](const auto& exp) { return exp.vm; }); + } + + void EmitPixelDiscard() { + if (TracksPixelValidMask()) body << "\t\tif (!kyty_pixel_valid) discard_fragment();\n"; + } + void EmitSetAttribute(const Inst& inst) { const auto& exp = program.export_info.at(inst.Flags().index); + if (program.stage == ShaderType::Pixel && exp.vm) { + body << "\t\tkyty_pixel_valid = " << Expr(inst.Arg(1)) << ";\n"; + } if (exp.kind == IR::ExportTargetKind::Null || exp.en == 0u) { return; } @@ -1092,6 +1162,10 @@ struct Emitter { } } + const bool pixel_color = program.stage == ShaderType::Pixel && + exp.kind == IR::ExportTargetKind::Mrt && input_info.pixel != nullptr; + const bool alpha_remap = pixel_color && input_info.pixel->alpha_blend_source_remap; + if (alpha_remap && exp.index != 0) return; body << "\t\tif (" << exec << ") {\n"; for (uint32_t component = 0; component < 4; ++component) { const bool component_written = @@ -1138,6 +1212,17 @@ struct Emitter { } body << ";\n"; } + if (alpha_remap && integer == 0) { + body << "\t\t\tout.color1 = float4(out." << field << ".w);\n"; + } + if (pixel_color && exp.index < input_info.pixel->target_export_mapping.size()) { + const auto mapping = input_info.pixel->target_export_mapping[exp.index]; + if (!mapping.IsIdentity()) { + body << "\t\t\tout." << field << " = out." << field << "."; + for (uint32_t i = 0; i < 4; ++i) body << ComponentName(mapping.Map(i)); + body << ";\n"; + } + } body << "\t\t}\n"; } @@ -1352,11 +1437,50 @@ struct Emitter { } void EmitImage(const Inst& inst) { + const auto& image = program.info.images.at(Mem(inst).resource); + if (image.indirect_root != Mem(inst).resource) { + EmitImageForResource(inst, Mem(inst).resource); + return; + } + + const auto* handle = inst.Arg(0).Resolve().TryInstruction(); + if (inst.GetOpcode() != ValueOpcode::ImageSampleRaw || handle == nullptr || + handle->NumArgs() == 0u || image.indirect_resources.empty() || + !HasDescriptor(IR::DescriptorBindingKind::FlattenedSrt)) { + Unsupported(inst, "indirect image without a sampled descriptor map"); + return; + } + + // The resource planner writes sorted key-to-descriptor pairs into SRT. + // A miss uses candidate zero, the same default as the SPIR-V backend. + body << "\t\t{\n" + << "\t\t\tconst device uint* mapping = ab.flattened_srt + " + << image.indirect_mapping_offset << "u;\n" + << "\t\t\tconst uint key = " << Expr(handle->Arg(0)) << ";\n" + << "\t\t\tuint lo = 0u, hi = mapping[0], selected = 0u;\n" + << "\t\t\tfor (uint step = 0u; lo < hi && step < " + << image.indirect_search_iterations << "u; ++step) {\n" + << "\t\t\t\tconst uint mid = lo + (hi - lo) / 2u;\n" + << "\t\t\t\tconst uint entry = 1u + mid * 2u;\n" + << "\t\t\t\tconst uint mapped_key = mapping[entry];\n" + << "\t\t\t\tif (mapped_key == key) { selected = mapping[entry + 1u]; break; }\n" + << "\t\t\t\tif (mapped_key < key) lo = mid + 1u; else hi = mid;\n" + << "\t\t\t}\n\t\t\tswitch (selected) {\n"; + for (size_t index = 0; index < image.indirect_resources.size(); ++index) { + if (index == 0) body << "\t\t\tdefault: {\n"; + else body << "\t\t\tcase " << index << "u: {\n"; + EmitImageForResource(inst, image.indirect_resources[index]); + body << "\t\t\tbreak; }\n"; + } + body << "\t\t\t}\n\t\t}\n"; + } + + void EmitImageForResource(const Inst& inst, uint32_t resource) { const auto op = inst.GetOpcode(); const auto info = IR::ImageOpcodeInfoOf(op); const auto& mem = Mem(inst); - const auto& image = program.info.images.at(mem.resource); - const auto slot = ImageSlotOf(mem.resource); + const auto& image = program.info.images.at(resource); + const auto slot = ImageSlotOf(resource); const auto fail = [&](const char* reason) { Unsupported(inst, reason); if (inst.GetType() != IR::Type::Void) { @@ -1367,21 +1491,19 @@ struct Emitter { fail("image resource is not bound"); return; } - // NoIndirectImage (UINT32_MAX) is the common direct case; only an image whose - // indirect_root points at itself needs the runtime SRT mapping. - if (!ImageSupported(image) || image.indirect_root == mem.resource) { + if (!ImageSupported(image) || resource >= kMslSamplerBase - kMslImageBase) { char reason[128]; std::snprintf(reason, sizeof(reason), "image: r128=%d format=%u convert=%u depth=%d atomic=%d indirect=%u/%u", image.r128 ? 1 : 0, static_cast(image.numeric_class), static_cast(image.conversion_format), image.depth_compare ? 1 : 0, image.atomic ? 1 : 0, - image.indirect_root, mem.resource); + image.indirect_root, resource); fail(reason); return; } - const bool storage = static_cast(slot->kind) >= IR::FirstStorageImageBinding; - const std::string tex = "ab.image_" + std::to_string(mem.resource); + const bool storage = image.resource_class == IR::ImageResourceClass::Storage; + const std::string tex = "ab.image_" + std::to_string(resource); const auto dim = DimensionInfo(image.dimension); const Inst* address = inst.Arg(info.needs_sampler ? 2 : 1).TryInstruction(); if (address == nullptr) { @@ -1393,13 +1515,6 @@ struct Emitter { case IR::ValueOpcode::ImageSampleRaw: { const auto layout = LayoutOf(mem); if (image.cube) { - // Experimental (KYTY_MSL_CUBE=1): the kernels that sample cubes (reflection filtering) run for seconds per frame - // with the state-machine codegen and the cube faces are not uploaded yet, so they stay skipped by default. - // Graphics stages sample cubes by default (a skipped pixel shader drops its draw); compute kernels stay off. - if (program.stage == ShaderType::Compute && std::getenv("KYTY_MSL_CUBE") == nullptr) { - fail("cube sample in compute (enable with KYTY_MSL_CUBE=1)"); - return; - } if (dim.components < 2u || dim.components > 3u || dim.spatial != 2u || (mem.image_sample_flags & Decoder::ImageSampleFlagDerivative) != 0u || layout.dref >= 0) { char why[160]; @@ -1558,29 +1673,46 @@ struct Emitter { const std::string lod = image.mip_mode == IR::ImageMipMode::Dynamic ? AddressU32(*address, mem, static_cast(dim.components)) : "0u"; - const std::string value = TexelValue(image, Expr(inst.Arg(2)), &mem); - body << "\t\tif (" << Expr(inst.Arg(3)) << ") {\n\t\t\t" << tex << ".write(" << value + const uint32_t mask = mem.dmask != 0u ? mem.dmask : 1u; + const auto bits = Expr(inst.Arg(2)); + body << "\t\tif (" << Expr(inst.Arg(3)) << ") {\n"; + if (mem.data_bits == 16u) { + body << "\t\t\tconst uint4 kyty_store = kyty_d16_unpack(" << bits << ", " << mask << "u, " + << (ImageIsFloatClass(image) ? "true" : "false") << ");\n"; + } else { + std::array channels {"0u", "0u", "0u", "0u"}; + uint32_t packed = 0; + for (uint32_t logical = 0; logical < 4u; ++logical) { + if ((mask & (1u << logical)) != 0) { + channels[logical] = "(" + bits + ")." + std::string(1, "xyzw"[packed++]); + } + } + body << "\t\t\tconst uint4 kyty_store = uint4(" << channels[0] << ", " << channels[1] + << ", " << channels[2] << ", " << channels[3] << ");\n"; + } + body << "\t\t\t" << tex << ".write(" << TexelValue(image, "kyty_store", mask) << ", " << coord << array_arg << ", " << lod << ");\n\t\t}\n"; return; } case IR::ValueOpcode::ImageQueryDimensions: { - // image_get_resinfo: (width, height, depth/layers, mip count) at the requested level. - if (dim.msaa || image.cube) { - fail("resinfo of a multisampled or cube image"); - return; - } - const std::string lod = "min(" + AddressU32(*address, mem, 0) + ", (uint)" + tex + ".get_num_mip_levels() - 1u)"; - std::string h = "1u", d = "1u"; - if (dim.spatial >= 2u) h = "(uint)" + tex + ".get_height(" + lod + ")"; + // Multisample views have no mip argument or mip count. Cube views on + // Metal have one array slice per face. Follow the guest resource's + // coordinate count for the components exposed to the shader. + const std::string mip_levels = dim.msaa ? "0u" : "(uint)" + tex + ".get_num_mip_levels()"; + const std::string lod = dim.msaa ? "" : + "min(" + AddressU32(*address, mem, 0) + ", " + mip_levels + " - 1u)"; + const std::string width = "(uint)" + tex + ".get_width(" + lod + ")"; + const std::string height = dim.spatial >= 2u ? "(uint)" + tex + ".get_height(" + lod + ")" : "0u"; + std::string depth_or_layers = "0u"; if (image.dimension == Decoder::ImageDimension::Dim3D) { - d = "(uint)" + tex + ".get_depth(" + lod + ")"; + depth_or_layers = "(uint)" + tex + ".get_depth(" + lod + ")"; } else if (dim.components > dim.spatial) { - d = "(uint)" + tex + ".get_array_size()"; + depth_or_layers = "(uint)" + tex + ".get_array_size()"; } - EmitAssignment(inst, "uint4((uint)" + tex + ".get_width(" + lod + "), " + h + ", " + d + ", (uint)" + - tex + ".get_num_mip_levels())"); + EmitAssignment(inst, "uint4(" + width + ", " + height + ", " + depth_or_layers + ", " + mip_levels + ")"); return; } + default: fail("image operation"); return; } } @@ -1683,6 +1815,7 @@ struct Emitter { if (inst.GetOpcode() != ValueOpcode::Phi && !IsResourceType(inst.GetType())) EmitWaveInstruction(inst); } if (term.kind == CFG::TerminatorKind::Return) { + EmitPixelDiscard(); body << "\t\treturn" << (HasOutInterface() ? " out" : "") << ";\n"; return true; } @@ -2086,7 +2219,9 @@ struct Emitter { case IR::ValueOpcode::BufferAtomicUMin32: case IR::ValueOpcode::BufferAtomicUMax32: case IR::ValueOpcode::BufferAtomicSMin32: - case IR::ValueOpcode::BufferAtomicSMax32: { + case IR::ValueOpcode::BufferAtomicSMax32: + case IR::ValueOpcode::BufferAtomicFMin32: + case IR::ValueOpcode::BufferAtomicFMax32: { // 32-bit device atomics on a storage buffer: the result is the old value. Lanes whose // condition is false or whose index is past the buffer end contribute 0 and do not write. // Operands follow the SPIR-V EmitAtomicOperation convention: value at NumArgs-2 (CmpSwap: @@ -2113,6 +2248,22 @@ struct Emitter { << "\t\t\t\tatomic_compare_exchange_weak_explicit((device atomic_uint*)" << elem << ", &kyty_exp, " << desired << ", memory_order_relaxed, memory_order_relaxed);\n" << "\t\t\t\t" << Name(inst) << " = kyty_exp;\n\t\t\t}\n"; + } else if (op == IR::ValueOpcode::BufferAtomicFMin32 || op == IR::ValueOpcode::BufferAtomicFMax32) { + // Compare float encodings as integers to preserve NaNs and signed zero + // with Metal fast math enabled. Like the SPIR-V path, unordered or + // equal operands keep the existing value. + const char comparison = op == IR::ValueOpcode::BufferAtomicFMax32 ? '>' : '<'; + body << "\t\t\tdevice atomic_uint* atomic_word = (device atomic_uint*)" << elem << ";\n" + << "\t\t\tconst uint operand = " << Expr(inst.Arg(inst.NumArgs() - 2)) << ";\n" + << "\t\t\tconst uint operand_key = operand ^ ((operand >> 31u) != 0u ? 0xffffffffu : 0x80000000u);\n" + << "\t\t\tuint old = atomic_load_explicit(atomic_word, memory_order_relaxed);\n" + << "\t\t\tdo {\n" + << "\t\t\t\tconst uint old_key = old ^ ((old >> 31u) != 0u ? 0xffffffffu : 0x80000000u);\n" + << "\t\t\t\tconst bool ordered = (operand & 0x7fffffffu) <= 0x7f800000u && (old & 0x7fffffffu) <= 0x7f800000u;\n" + << "\t\t\t\tconst bool both_zero = ((operand | old) & 0x7fffffffu) == 0u;\n" + << "\t\t\t\tif (!ordered || both_zero || !(operand_key " << comparison << " old_key)) break;\n" + << "\t\t\t} while (!atomic_compare_exchange_weak_explicit(atomic_word, &old, operand, memory_order_relaxed, memory_order_relaxed));\n" + << "\t\t\t" << Name(inst) << " = old;\n"; } else { const std::string value = Expr(inst.Arg(inst.NumArgs() - 2)); const char* fn = "atomic_fetch_add_explicit"; @@ -2204,7 +2355,7 @@ struct Emitter { const std::string d = "(" + LdsByte(inst, mem) + " >> 2)"; const std::string value = Expr(inst.Arg(inst.NumArgs() - 2)); const std::string cond = Expr(inst.Arg(inst.NumArgs() - 1)); - const std::string space = gds ? "device" : "threadgroup"; + const std::string space = gds || UsesDeviceLds() ? "device" : "threadgroup"; const std::string slot = gds ? "ab.gds[" + d + "]" : "kyty_lds[" + d + "]"; body << "\t\t" << Name(inst) << " = 0u;\n"; body << "\t\tif (" << cond << " && " << d << " < " << limit << ") {\n"; @@ -2288,7 +2439,9 @@ struct Emitter { << "\t\t\tuint kyty_old = 0u;\n" << "\t\t\tif ((lane & 31u) == (kyty_first & 31u) && kyty_cnt != 0u && kyty_ok) {\n" << "\t\t\t\tkyty_old = atomic_fetch_" << (append ? "add" : "sub") << "_explicit(" - << (gds ? "&ab.gds[kyty_idx]" : "(threadgroup atomic_uint*)&kyty_lds[kyty_idx]") + << (gds ? "&ab.gds[kyty_idx]" : UsesDeviceLds() ? + "(device atomic_uint*)&kyty_lds[kyty_idx]" : + "(threadgroup atomic_uint*)&kyty_lds[kyty_idx]") << ", kyty_cnt, memory_order_relaxed);\n" << "\t\t\t}\n" << "\t\t\t" << Name(inst) << " = simd_shuffle(kyty_old, kyty_first & 31u);\n"; @@ -2321,7 +2474,8 @@ struct Emitter { if (count>1) result+=")"; // KYTY_LDS_SYNC=1 (experiment): a wave64 workgroup is two 32-wide host simdgroups that do not run in lockstep, so LDS // handed from one half to the other needs a barrier the RDNA code (one wave, no s_barrier) never had. - if (LdsSyncEnabled() && program.stage == ShaderType::Compute) body << "\t\tthreadgroup_barrier(mem_flags::mem_threadgroup);\n"; + if (LdsSyncEnabled() && program.stage == ShaderType::Compute) body << (UsesDeviceLds() ? "\t\tthreadgroup_barrier(mem_flags::mem_device);\n" : + "\t\tthreadgroup_barrier(mem_flags::mem_threadgroup);\n"); EmitAssignment(inst,result); return; } @@ -2373,7 +2527,8 @@ struct Emitter { } } body << "\t\t}\n"; - if (LdsSyncEnabled() && program.stage == ShaderType::Compute) body << "\t\tthreadgroup_barrier(mem_flags::mem_threadgroup);\n"; + if (LdsSyncEnabled() && program.stage == ShaderType::Compute) body << (UsesDeviceLds() ? "\t\tthreadgroup_barrier(mem_flags::mem_device);\n" : + "\t\tthreadgroup_barrier(mem_flags::mem_threadgroup);\n"); return; } default: EmitAlu(inst); return; @@ -2580,6 +2735,27 @@ void Emitter::EmitAlu(const Inst& inst) { // (EmitF32ToU32). A plain C cast is undefined in MSL for exactly those inputs. EmitAssignment(inst, (RdnaFloatMask() & 2u) != 0 ? "kyty_f2u(" + Expr(inst.Arg(0)) + ")" : "(uint)(" + Expr(inst.Arg(0)) + ")"); return; + case IR::ValueOpcode::BitCastU64F64: + case IR::ValueOpcode::BitCastF64U64: + EmitAssignment(inst, Expr(inst.Arg(0))); + return; + case IR::ValueOpcode::ConvertF64F32: + EmitAssignment(inst, "kyty_widen_float(as_type(" + Expr(inst.Arg(0)) + "))"); + return; + case IR::ValueOpcode::ConvertF32F64: + EmitAssignment(inst, "as_type(kyty_narrow_double(" + Expr(inst.Arg(0)) + "))"); + return; + case IR::ValueOpcode::FPMin64: + case IR::ValueOpcode::FPMax64: + EmitAssignment(inst, "kyty_double_minmax(" + Expr(inst.Arg(0)) + ", " + Expr(inst.Arg(1)) + + (inst.GetOpcode() == IR::ValueOpcode::FPMax64 ? ", true)" : ", false)")); + return; + case IR::ValueOpcode::FPAdd64: + EmitAssignment(inst, "kyty_double_add(" + Expr(inst.Arg(0)) + ", " + Expr(inst.Arg(1)) + ")"); + return; + case IR::ValueOpcode::FPMul64: + EmitAssignment(inst, "kyty_double_multiply(" + Expr(inst.Arg(0)) + ", " + Expr(inst.Arg(1)) + ")"); + return; case IR::ValueOpcode::BitCastU32F32: EmitAssignment(inst, "as_type(" + Expr(inst.Arg(0)) + ")"); return; @@ -2701,6 +2877,162 @@ std::string Emitter::Emit() { out << "#include \n"; out << "#include \n"; out << "using namespace metal;\n\n"; + if (std::ranges::any_of(program.blocks, [](const IR::Block* block) { + return std::ranges::any_of(*block, [](const Inst& inst) { + switch (inst.GetOpcode()) { + case IR::ValueOpcode::ConvertF64F32: + case IR::ValueOpcode::ConvertF32F64: + case IR::ValueOpcode::FPMin64: + case IR::ValueOpcode::FPMax64: + case IR::ValueOpcode::FPAdd64: + case IR::ValueOpcode::FPMul64: return true; + default: return false; + } + }); + })) { + out << R"( +inline ulong kyty_widen_float(uint bits) { + const ulong sign = ulong(bits & 0x80000000u) << 32u; + const uint exponent = (bits >> 23u) & 0xffu; + const uint fraction = bits & 0x007fffffu; + if (exponent == 0xffu) { + const ulong quiet = fraction != 0u ? (1ul << 51u) : 0ul; + return sign | 0x7ff0000000000000ul | quiet | (ulong(fraction) << 29u); + } + // The guest conversion flushes single-precision denormals to signed zero. + if (exponent == 0u) return sign; + return sign | (ulong(exponent + 896u) << 52u) | (ulong(fraction) << 29u); +} +constant ulong kyty_f64_sign = 0x8000000000000000ul; +constant ulong kyty_f64_inf = 0x7ff0000000000000ul; +constant ulong kyty_f64_fraction = 0x000ffffffffffffful; +constant ulong kyty_f64_quiet = 0x0008000000000000ul; + +inline ulong kyty_shift_right_sticky(ulong value, uint shift) { + if (shift == 0u) return value; + if (shift >= 64u) return ulong(value != 0ul); + return (value >> shift) | ulong((value << (64u - shift)) != 0ul); +} + +inline uint kyty_narrow_double(ulong bits) { + const uint sign = uint(bits >> 32u) & 0x80000000u; + const uint exponent = uint((bits >> 52u) & 0x7fful); + const ulong fraction = bits & kyty_f64_fraction; + if (exponent == 0x7ffu) { + return sign | 0x7f800000u | + (fraction != 0ul ? 0x00400000u | uint(fraction >> 29u) : 0u); + } + // Mirror the SPIR-V conversion: clamp overflows and flush float denormals. + if (exponent > 1150u) return sign | 0x7f7fffffu; + if (exponent < 896u) return sign; + const uint shift = exponent == 896u ? 30u : 29u; + const ulong significand = (1ul << 52u) | fraction; + const uint integral = uint(significand >> shift); + const ulong halfway = 1ul << (shift - 1u); + const ulong dropped = significand & ((halfway << 1u) - 1ul); + const uint rounded = integral + uint(dropped > halfway || (dropped == halfway && (integral & 1u))); + if (exponent == 896u) return sign | (rounded & 0x00800000u); + return sign | (((exponent - 897u) << 23u) + rounded); +} + +inline ulong kyty_double_minmax(ulong a, ulong b, bool maximum) { + if ((a & ~kyty_f64_sign) > kyty_f64_inf) return b; + if ((b & ~kyty_f64_sign) > kyty_f64_inf) return a; + const ulong a_key = a ^ ((a & kyty_f64_sign) ? ~0ul : kyty_f64_sign); + const ulong b_key = b ^ ((b & kyty_f64_sign) ? ~0ul : kyty_f64_sign); + return (maximum ? (a_key > b_key) : (a_key < b_key)) ? a : b; +} + +// Round a 53-bit significand with three additional guard/round/sticky bits. +inline ulong kyty_double_round(ulong sign, int exponent, ulong extended) { + if (exponent < 1) { + extended = kyty_shift_right_sticky(extended, uint(1 - exponent)); + exponent = 1; + } + ulong significant = extended >> 3u; + const ulong remainder = extended & 7ul; + significant += ulong(remainder > 4ul || (remainder == 4ul && (significant & 1ul))); + if (significant >= (1ul << 53u)) { + significant >>= 1u; + ++exponent; + } + if (exponent >= 0x7ff) return sign | kyty_f64_inf; + if (significant < (1ul << 52u)) exponent = 0; + return sign | (ulong(exponent) << 52u) | (significant & kyty_f64_fraction); +} + +inline ulong kyty_double_add(ulong a, ulong b) { + ulong a_abs = a & ~kyty_f64_sign, b_abs = b & ~kyty_f64_sign; + if (a_abs > kyty_f64_inf) return a | kyty_f64_quiet; + if (b_abs > kyty_f64_inf) return b | kyty_f64_quiet; + if (a_abs == kyty_f64_inf || b_abs == kyty_f64_inf) { + if (a_abs == b_abs && a != b) return kyty_f64_inf | kyty_f64_quiet; + return a_abs == kyty_f64_inf ? a : b; + } + if ((a_abs | b_abs) == 0ul) return a & b; + if (a_abs < b_abs) { + const ulong swap = a; + a = b; + b = swap; + const ulong swap_abs = a_abs; + a_abs = b_abs; + b_abs = swap_abs; + } + int exponent = max(int(a_abs >> 52u), 1); + const int b_exponent = max(int(b_abs >> 52u), 1); + const ulong a_sig = (a_abs & kyty_f64_fraction) | ((a_abs >> 52u) ? 1ul << 52u : 0ul); + const ulong b_sig = (b_abs & kyty_f64_fraction) | ((b_abs >> 52u) ? 1ul << 52u : 0ul); + const ulong b_aligned = kyty_shift_right_sticky(b_sig << 3u, uint(exponent - b_exponent)); + ulong extended = ((a ^ b) & kyty_f64_sign) ? (a_sig << 3u) - b_aligned : (a_sig << 3u) + b_aligned; + if (extended == 0ul) return 0ul; + if (extended & (1ul << 56u)) { + extended = kyty_shift_right_sticky(extended, 1u); + ++exponent; + } else if (extended < (1ul << 55u)) { + const int shift = min(int(clz(extended)) - 8, exponent - 1); + extended <<= uint(shift); + exponent -= shift; + } + return kyty_double_round(a & kyty_f64_sign, exponent, extended); +} + +inline ulong kyty_double_multiply(ulong a, ulong b) { + const ulong sign = (a ^ b) & kyty_f64_sign; + const ulong a_abs = a & ~kyty_f64_sign, b_abs = b & ~kyty_f64_sign; + if (a_abs > kyty_f64_inf) return a | kyty_f64_quiet; + if (b_abs > kyty_f64_inf) return b | kyty_f64_quiet; + if (a_abs == kyty_f64_inf || b_abs == kyty_f64_inf) { + return (a_abs == 0ul || b_abs == 0ul) ? kyty_f64_inf | kyty_f64_quiet : sign | kyty_f64_inf; + } + if (a_abs == 0ul || b_abs == 0ul) return sign; + int a_exponent = int(a_abs >> 52u), b_exponent = int(b_abs >> 52u); + ulong a_sig = a_abs & kyty_f64_fraction, b_sig = b_abs & kyty_f64_fraction; + if (a_exponent != 0) a_sig |= 1ul << 52u; + else { + const uint shift = clz(a_sig) - 11u; + a_sig <<= shift; + a_exponent = 1 - int(shift); + } + if (b_exponent != 0) b_sig |= 1ul << 52u; + else { + const uint shift = clz(b_sig) - 11u; + b_sig <<= shift; + b_exponent = 1 - int(shift); + } + + // The two 53-bit significands produce a 106-bit product. + const ulong low_product = ulong(uint(a_sig)) * uint(b_sig); + const ulong middle = (low_product >> 32u) + (a_sig >> 32u) * uint(b_sig) + (b_sig >> 32u) * uint(a_sig); + const ulong low = (middle << 32u) | uint(low_product); + const ulong high = (a_sig >> 32u) * (b_sig >> 32u) + (middle >> 32u); + const bool leading = (high & (1ul << 41u)) != 0ul; + const uint shift = leading ? 50u : 49u; + const ulong extended = (high << (64u - shift)) | kyty_shift_right_sticky(low, shift); + return kyty_double_round(sign, a_exponent + b_exponent - 1023 + int(leading), extended); +} + +)"; + } if (HasDescriptor(IR::DescriptorBindingKind::BdaPagetable)) { out << R"( // Two-level native Metal page table: 16 KiB pages, 1024 entries per leaf. @@ -2833,13 +3165,16 @@ inline float kyty_med3f(float a, float b, float c) { // NativeBinding layout overlaps as soon as a descriptor group has more than one // element (Buffers at 0..N-1 vs images starting at 1). out << "struct KytyArgumentBuffer {\n"; - if (program.bindings.descriptors.empty()) { + if (program.bindings.descriptors.empty() && program.stage != ShaderType::Vertex) { // A struct with no members cannot be bound as an argument buffer. out << "\tdevice uint *kyty_padding [[id(0)]];\n"; } { // (first id, number of ids the member occupies, declaration) std::vector> members; + if (program.stage == ShaderType::Vertex && !HasDescriptor(IR::DescriptorBindingKind::Buffers)) { + members.emplace_back(kMslBufferBase, 64u, "device uint *buffers [[id(0)]][64];"); + } for (const auto& binding: program.bindings.descriptors) { switch (binding.kind) { case IR::DescriptorBindingKind::Buffers: @@ -2867,27 +3202,19 @@ inline float kyty_med3f(float a, float b, float c) { "device const uint *flattened_srt [[id(" + std::to_string(kMslSrtBinding) + ")]];"); break; - default: - if (IsImageBinding(binding.kind)) { - const bool storage = static_cast(binding.kind) >= - IR::FirstStorageImageBinding; - for (const uint32_t resource: binding.resources) { - if (resource >= program.info.images.size()) { - continue; - } - const auto slot = ImageSlotOf(resource); - if (!slot) { - continue; - } - const auto& image = program.info.images[resource]; - members.emplace_back( - slot->id, 1u, TextureType(image, storage) + " image_" + - std::to_string(resource) + " [[id(" + - std::to_string(slot->id) + ")]];"); - } - } - break; + default: break; + } + } + // An image can appear repeatedly in a descriptor array (for example one + // entry per mip). Direct MSL uses one argument per IR image resource. + for (const auto& [resource, slot]: image_slots_) { + if (resource >= program.info.images.size()) { + continue; } + const auto& image = program.info.images[resource]; + const bool storage = image.resource_class == IR::ImageResourceClass::Storage; + members.emplace_back(slot.id, 1u, TextureType(image, storage) + " image_" + + std::to_string(resource) + " [[id(" + std::to_string(slot.id) + ")]];"); } std::sort(members.begin(), members.end(), [](const auto& lhs, const auto& rhs) { return std::get<0>(lhs) < std::get<0>(rhs); }); @@ -2955,6 +3282,10 @@ inline float kyty_med3f(float a, float b, float c) { << "uint3 tid [[thread_position_in_threadgroup]], " << "uint3 tgid [[threadgroup_position_in_grid]], " << "uint liid [[thread_index_in_threadgroup]]"; + if (UsesDeviceLds()) { + out << ", uint3 grid_groups [[threadgroups_per_grid]], device uint* lds_backing [[buffer(" + << DeviceLdsBufferIndex << ")]]"; + } if (nan_trace_) out << ", device atomic_uint* kyty_nan_dbg [[buffer(28)]]"; } out << ") {\n"; @@ -2963,8 +3294,12 @@ inline float kyty_med3f(float a, float b, float c) { out << "\tKytyStageOut out = {};\n"; } out << "\t(void)ab; (void)pc_data; (void)sizes;\n"; + if (TracksPixelValidMask()) out << "\tbool kyty_pixel_valid = true;\n"; if (UsesLds()) { - if (program.stage == ShaderType::Compute) { + if (UsesDeviceLds()) { + out << "\tconst ulong lds_group = (ulong(tgid.z) * grid_groups.y + tgid.y) * grid_groups.x + tgid.x;\n" + << "\tdevice uint* kyty_lds = lds_backing + lds_group * " << LdsDwords() << "u;\n"; + } else if (program.stage == ShaderType::Compute) { out << "\tthreadgroup uint kyty_lds[" << LdsDwords() << "];\n"; } else { // Non-kernel stages cannot use the threadgroup address space; per-thread @@ -3048,7 +3383,10 @@ inline float kyty_med3f(float a, float b, float c) { body << "\t\t\tpc = " << BlockIndex(term.false_block) << "u;\n\t\t}\n\t\tbreak;\n"; } break; - default: body << "\t\treturn" << (has_out ? " out" : "") << ";\n"; break; + default: + EmitPixelDiscard(); + body << "\t\treturn" << (has_out ? " out" : "") << ";\n"; + break; } body << "\t}\n"; } @@ -3207,6 +3545,7 @@ EmitResult EmitProgram(const IR::Program& program, ShaderStageInputInfo input_in EmitResult result; result.source = emitter.Emit(); result.wave64_pair = emitter.pair_; + result.device_lds_dwords = emitter.UsesDeviceLds() ? emitter.LdsDwords() : 0u; if (program.stage == ShaderType::Compute) { const auto* cs = ShaderWorkgroupInput(program.stage, emitter.input_info); std::lock_guard lock(s_pair_mutex); diff --git a/src/graphics/shader/recompiler/backend/msl/MslEmitter.h b/src/graphics/shader/recompiler/backend/msl/MslEmitter.h index d23befa..a9c599e 100644 --- a/src/graphics/shader/recompiler/backend/msl/MslEmitter.h +++ b/src/graphics/shader/recompiler/backend/msl/MslEmitter.h @@ -10,6 +10,8 @@ namespace Libs::Graphics::ShaderRecompiler::Msl { +inline constexpr uint32_t DeviceLdsBufferIndex = 29; + // Direct RDNA (IR) -> Metal Shading Language translation. Bypasses SPIR-V and // SPIRV-Cross: the IR already carries typed memory, image and export semantics. struct EmitResult { @@ -20,6 +22,7 @@ struct EmitResult { // The kernel runs each wave64 as 32 host lanes that each carry two guest lanes (see Wave64Pair): the dispatch must launch // half as many host threads per group, in one dimension. bool wave64_pair = false; + uint32_t device_lds_dwords = 0; }; [[nodiscard]] EmitResult EmitProgram(const IR::Program& program, diff --git a/src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp b/src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp index a13cb12..ad07c49 100644 --- a/src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp +++ b/src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp @@ -539,7 +539,7 @@ Emitter::SpirvRequirements Emitter::AnalyzeProgramRequirements(const IR::Program } std::vector EmitProgram(const IR::Program& program, - ShaderStageInputInfo input_info) { + ShaderStageInputInfo input_info, bool metal_guest_address_space) { using namespace Emitter; if (program.stage != ShaderType::Compute && program.stage != ShaderType::Vertex && @@ -555,6 +555,7 @@ std::vector EmitProgram(const IR::Program& program, ValidateNativeProgram(program); IR::ValidateProgram(program, true); EmitterState state(program, input_info); + state.metal_guest_address_space = metal_guest_address_space; const auto* workgroup = ShaderWorkgroupInput(program.stage, input_info); state.lane_count = workgroup != nullptr && program.wave_size == 64u && workgroup->host_subgroup_size == 32u diff --git a/src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h b/src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h index ee7dfd8..3dd4c7f 100644 --- a/src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h +++ b/src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h @@ -10,7 +10,8 @@ namespace Libs::Graphics::ShaderRecompiler::Spirv { std::vector EmitProgram(const IR::Program& program, - ShaderStageInputInfo input_info); + ShaderStageInputInfo input_info, + bool metal_guest_address_space = false); } // namespace Libs::Graphics::ShaderRecompiler::Spirv diff --git a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp index 6cb0911..8b8a90b 100644 --- a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp +++ b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp @@ -379,13 +379,6 @@ uint32_t HorizontalOffsets(EmitterState& state, ImageDimension dimension) { offsets[2], offsets[3]); } -uint32_t InverseSwizzle(uint32_t swizzle, uint32_t component) { - for (uint32_t source = 0; source < 4u; source++) { - if (((swizzle >> (source * 3u)) & 7u) == 4u + component) return source; - } - return UINT32_MAX; -} - Format::BufferFormatInfo ImageConversionFormat(const EmitterState& state, const IR::MemoryInfo& mem) { const auto format = state.program.info.images[mem.resource].conversion_format; @@ -549,7 +542,7 @@ uint32_t StoreTexel(ValueEmitContext& ctx, const IR::MemoryInfo& mem, uint32_t d uint32_t values[4] {}; const auto dmask = mem.dmask != 0u ? mem.dmask : 1u; for (uint32_t component = 0; component < 4u; component++) { - const auto source = InverseSwizzle(swizzle, component); + const auto source = IR::ImageStoreSourceChannel(swizzle, component); uint32_t raw = ConstantU32(ctx.state, 0); if (source < 4u && ((dmask >> source) & 1u) != 0u) { const auto packed_index = DmaskComponentIndex(dmask, source); diff --git a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h index c6f3a4d..cd0590f 100644 --- a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h +++ b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h @@ -157,6 +157,10 @@ EMIT_NATIVE(FPSub32, OpFSub, F32, uint32_t, uint32_t) EMIT_NATIVE(FPMul32, OpFMul, F32, uint32_t, uint32_t) EMIT_NATIVE(FPAdd64, OpFAdd, F64, uint32_t, uint32_t) EMIT_NATIVE(FPMul64, OpFMul, F64, uint32_t, uint32_t) +inline constexpr auto EmitFPMin64 = + EmitGlsl; +inline constexpr auto EmitFPMax64 = + EmitGlsl; inline constexpr auto EmitFPFma64 = EmitGlsl; uint32_t EmitFPRecip64(EmitterState& state, uint32_t arg0); diff --git a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h index 425845f..2c89515 100644 --- a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h +++ b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h @@ -85,6 +85,7 @@ struct EmitterState { Builder builder; const IR::Program& program; ShaderStageInputInfo input_info; + bool metal_guest_address_space = false; uint32_t void_type = 0; uint32_t bool_type = 0; uint32_t u32_type = 0; diff --git a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp index d0a18e3..68ca234 100644 --- a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp +++ b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp @@ -1,3 +1,4 @@ +#include "graphics/host_gpu/metal/metalAddressSpace.h" #include "graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h" #include "graphics/host_gpu/renderer/cache/bufferCache.h" @@ -1067,11 +1068,23 @@ void DefineGetBdaPointer(EmitterState& state) { address); const auto page64 = Binary(state, spv::OpShiftRightLogical, type, packed, ConstantDeviceAddress(state, BufferCache::CACHING_PAGEBITS)); - const auto page = Unary(state, spv::OpUConvert, TypeU32(state), page64); + auto page = Unary(state, spv::OpUConvert, TypeU32(state), page64); + uint32_t valid_address = 0; + if (state.metal_guest_address_space) { + const auto low = Binary(state, spv::OpULessThan, TypeBool(state), address, + ConstantDeviceAddress(state, LOWER_ADDRESS_SIZE)); + const auto high = Binary(state, spv::OpULessThan, TypeBool(state), address, + ConstantDeviceAddress(state, LibKernel::Memory::kExtendedMemoryBase + + LibKernel::Memory::kExtendedMemorySize)); + valid_address = EmitLogicalOrBool(state, low, EmitLogicalAndBool(state, extended, high)); + page = Select(state, TypeU32(state), valid_address, page, ConstantU32(state, 0)); + } uint32_t base; - if (BufferCache::SparseBdaEnabled()) { + if (state.metal_guest_address_space || BufferCache::SparseBdaEnabled()) { + const uint32_t leaf_bits = state.metal_guest_address_space + ? Metal::GuestAddressLeafBits : BufferCache::BDA_LEAF_BITS; const auto root_index = Binary(state, spv::OpShiftRightLogical, TypeU32(state), page, - ConstantU32(state, BufferCache::BDA_LEAF_BITS)); + ConstantU32(state, leaf_bits)); const auto root_pointer = state.builder.AllocateId(); state.builder.AddFunction(spv::OpAccessChain, TypeStorageBufferU64ElementPointer(state), root_pointer, state.bda_pagetable_variable, @@ -1091,7 +1104,7 @@ void DefineGetBdaPointer(EmitterState& state) { const auto leaf_offset = Binary(state, spv::OpShiftLeftLogical, type, Unary(state, spv::OpUConvert, type, Binary(state, spv::OpBitwiseAnd, TypeU32(state), page, - ConstantU32(state, BufferCache::BDA_LEAF_ENTRIES - 1))), + ConstantU32(state, (1u << leaf_bits) - 1u))), ConstantDeviceAddress(state, 3)); const auto leaf_address = Binary(state, spv::OpIAdd, type, leaf_base, leaf_offset); const auto leaf_pointer = Unary(state, spv::OpConvertUToPtr, @@ -1114,6 +1127,9 @@ void DefineGetBdaPointer(EmitterState& state) { base = state.builder.AllocateId(); state.builder.AddFunction(spv::OpLoad, type, base, entry_pointer); } + if (state.metal_guest_address_space) { + base = Select(state, type, valid_address, base, ConstantDeviceAddress(state, 0)); + } const auto missing = Binary(state, spv::OpIEqual, TypeBool(state), base, ConstantDeviceAddress(state, 0)); const auto fault_label = state.builder.AllocateId(); @@ -1123,7 +1139,7 @@ void DefineGetBdaPointer(EmitterState& state) { state.builder.AddFunction(spv::OpBranchConditional, missing, fault_label, available_label); EmitLabel(state, fault_label); - RecordBdaFault(state, page); + if (!state.metal_guest_address_space) RecordBdaFault(state, page); state.builder.AddFunction(spv::OpBranch, merge_label); EmitLabel(state, available_label); diff --git a/src/graphics/shader/recompiler/frontend/decode/ScalarAluOps.cpp b/src/graphics/shader/recompiler/frontend/decode/ScalarAluOps.cpp index 6c8b7bb..ae4ae64 100644 --- a/src/graphics/shader/recompiler/frontend/decode/ScalarAluOps.cpp +++ b/src/graphics/shader/recompiler/frontend/decode/ScalarAluOps.cpp @@ -59,6 +59,7 @@ constexpr OpcodeMap SOP1_OPCODE_LIST[] = { {0x1eu, Opcode::S_BITSET1_B64}, {0x1fu, Opcode::S_GETPC_B64}, {0x20u, Opcode::S_SETPC_B64}, + {0x21u, Opcode::S_OR_SAVEEXEC_B64}, {0x24u, Opcode::S_AND_SAVEEXEC_B64}, {0x28u, Opcode::S_ORN2_SAVEEXEC_B64}, {0x2du, Opcode::S_QUADMASK_B64}, diff --git a/src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h b/src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h index 43b6552..7cb3f16 100644 --- a/src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h +++ b/src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h @@ -61,9 +61,11 @@ enum class Opcode { S_SUBVECTOR_LOOP_BEGIN, S_SUBVECTOR_LOOP_END, S_AND_SAVEEXEC_B32, + S_OR_SAVEEXEC_B32, S_ORN2_SAVEEXEC_B32, S_ANDN1_SAVEEXEC_B32, S_AND_SAVEEXEC_B64, + S_OR_SAVEEXEC_B64, S_ORN2_SAVEEXEC_B64, S_ANDN1_SAVEEXEC_B64, S_NOT_B32, @@ -247,6 +249,8 @@ enum class Opcode { V_FMA_F64, V_ADD_F64, V_MUL_F64, + V_MIN_F64, + V_MAX_F64, V_FMA_F32, V_FMA_F16, V_PACK_B32_F16, diff --git a/src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp b/src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp index 9bcdf75..a617dc4 100644 --- a/src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp +++ b/src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp @@ -289,6 +289,8 @@ constexpr OpcodeMap VOP3_OPCODE_LIST[] = { {0x14cu, Opcode::V_FMA_F64}, {0x164u, Opcode::V_ADD_F64}, {0x165u, Opcode::V_MUL_F64}, + {0x166u, Opcode::V_MIN_F64}, + {0x167u, Opcode::V_MAX_F64}, {0x148u, Opcode::V_BFE_U32}, {0x149u, Opcode::V_BFE_I32}, {0x14au, Opcode::V_BFI_B32}, @@ -1221,6 +1223,8 @@ uint32_t NativeVop3SourceCount(Opcode opcode) { switch (opcode) { case Opcode::V_ADD_F64: case Opcode::V_MUL_F64: + case Opcode::V_MIN_F64: + case Opcode::V_MAX_F64: case Opcode::V_MUL_LO_U32: case Opcode::V_MUL_HI_U32: case Opcode::V_MUL_LO_I32: @@ -1373,6 +1377,8 @@ bool SupportsNativeVop3SourceModifiers(Opcode opcode) { case Opcode::V_MAD_F32: case Opcode::V_ADD_F64: case Opcode::V_MUL_F64: + case Opcode::V_MIN_F64: + case Opcode::V_MAX_F64: case Opcode::V_FMA_F64: case Opcode::V_FMA_F32: case Opcode::V_PACK_B32_F16: diff --git a/src/graphics/shader/recompiler/frontend/translate/Scalar.cpp b/src/graphics/shader/recompiler/frontend/translate/Scalar.cpp index ecd3838..1c3c1bf 100644 --- a/src/graphics/shader/recompiler/frontend/translate/Scalar.cpp +++ b/src/graphics/shader/recompiler/frontend/translate/Scalar.cpp @@ -23,6 +23,9 @@ void Translator::EmitScalar(const Decoder::Instruction& inst) { case O::S_AND_SAVEEXEC_B32: S_SAVEEXEC(inst, IR::ValueOpcode::LogicalAnd, false, false, false); return; + case O::S_OR_SAVEEXEC_B32: + S_SAVEEXEC(inst, IR::ValueOpcode::LogicalOr, false, false, false); + return; case O::S_ANDN1_SAVEEXEC_B32: S_SAVEEXEC(inst, IR::ValueOpcode::LogicalAnd, false, true, false); return; @@ -32,6 +35,9 @@ void Translator::EmitScalar(const Decoder::Instruction& inst) { case O::S_AND_SAVEEXEC_B64: S_SAVEEXEC(inst, IR::ValueOpcode::LogicalAnd, false, false, true); return; + case O::S_OR_SAVEEXEC_B64: + S_SAVEEXEC(inst, IR::ValueOpcode::LogicalOr, false, false, true); + return; case O::S_ANDN1_SAVEEXEC_B64: S_SAVEEXEC(inst, IR::ValueOpcode::LogicalAnd, false, true, true); return; diff --git a/src/graphics/shader/recompiler/frontend/translate/Translate.cpp b/src/graphics/shader/recompiler/frontend/translate/Translate.cpp index b06c3a6..ee0b48c 100644 --- a/src/graphics/shader/recompiler/frontend/translate/Translate.cpp +++ b/src/graphics/shader/recompiler/frontend/translate/Translate.cpp @@ -895,7 +895,9 @@ void IncludeInstructionVectorRegisters(const Decoder::Instruction& inst, uint32_ case Decoder::Opcode::V_CVT_F64_U32: include_vector(inst.dst, 2u); break; case Decoder::Opcode::V_FMA_F64: include_vector(inst.src2, 2u); [[fallthrough]]; case Decoder::Opcode::V_ADD_F64: - case Decoder::Opcode::V_MUL_F64: include_vector(inst.src1, 2u); [[fallthrough]]; + case Decoder::Opcode::V_MUL_F64: + case Decoder::Opcode::V_MIN_F64: + case Decoder::Opcode::V_MAX_F64: include_vector(inst.src1, 2u); [[fallthrough]]; case Decoder::Opcode::V_RCP_F64: include_vector(inst.dst, 2u); [[fallthrough]]; case Decoder::Opcode::V_CVT_F32_F64: include_vector(inst.src0, 2u); break; case Decoder::Opcode::V_CMP_EQ_F64: diff --git a/src/graphics/shader/recompiler/frontend/translate/Vector.cpp b/src/graphics/shader/recompiler/frontend/translate/Vector.cpp index 344861b..ca77aae 100644 --- a/src/graphics/shader/recompiler/frontend/translate/Vector.cpp +++ b/src/graphics/shader/recompiler/frontend/translate/Vector.cpp @@ -469,6 +469,8 @@ void Translator::EmitVector(const Decoder::Instruction& inst) { case O::V_MUL_F32: return FloatBinary(inst, IR::ValueOpcode::FPMul32, false); case O::V_ADD_F64: return FloatBinary(inst, IR::ValueOpcode::FPAdd64, false); case O::V_MUL_F64: return FloatBinary(inst, IR::ValueOpcode::FPMul64, false); + case O::V_MIN_F64: return FloatBinary(inst, IR::ValueOpcode::FPMin64, false); + case O::V_MAX_F64: return FloatBinary(inst, IR::ValueOpcode::FPMax64, false); case O::V_MIN_F32: return FloatBinary(inst, IR::ValueOpcode::FPMin32, false); case O::V_MAX_F32: return FloatBinary(inst, IR::ValueOpcode::FPMax32, false); case O::V_LDEXP_F32: return FloatBinary(inst, IR::ValueOpcode::FPLdexp, false); diff --git a/src/graphics/shader/recompiler/ir/ShaderIR.h b/src/graphics/shader/recompiler/ir/ShaderIR.h index f37818c..7dcf1a9 100644 --- a/src/graphics/shader/recompiler/ir/ShaderIR.h +++ b/src/graphics/shader/recompiler/ir/ShaderIR.h @@ -119,6 +119,14 @@ enum class ImageMipMode { None, Dynamic }; constexpr uint32_t ShaderImageIdentitySwizzle = 0x00000facu; +// Storage writes carry enabled logical channels in ascending DMASK order. +constexpr uint32_t ImageStoreSourceChannel(uint32_t swizzle, uint32_t physical) { + for (uint32_t logical = 0; logical < 4u; ++logical) { + if (((swizzle >> (logical * 3u)) & 7u) == 4u + physical) return logical; + } + return UINT32_MAX; +} + struct ImageResource { static constexpr uint32_t NoIndirectImage = UINT32_MAX; @@ -528,6 +536,7 @@ struct CompiledShaderInfo { // renderer must then fill the flat MSL argument-buffer layout instead of the // historical SPIRV-Cross layout. bool native_msl = false; + uint32_t metal_device_lds_dwords = 0; ShaderInfo info; BindingLayout bindings; }; diff --git a/src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc b/src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc index 986f8c9..2c1c9f1 100644 --- a/src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc +++ b/src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc @@ -181,6 +181,8 @@ VALUE_OPCODE(FPFma32, F32, F32, F32, F32) VALUE_OPCODE(FPMul32, F32, F32, F32) VALUE_OPCODE(FPAdd64, F64, F64, F64) VALUE_OPCODE(FPMul64, F64, F64, F64) +VALUE_OPCODE(FPMin64, F64, F64, F64) +VALUE_OPCODE(FPMax64, F64, F64, F64) VALUE_OPCODE(FPFma64, F64, F64, F64, F64) VALUE_OPCODE(FPRecip64, F64, F64) VALUE_OPCODE(FPMin32, F32, F32, F32) diff --git a/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp b/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp index 33913c2..f47a1c7 100644 --- a/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp +++ b/src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp @@ -36,9 +36,13 @@ uint32_t PossibleU32Bits(Value value) { return PossibleU32Bits(inst->Arg(0)) | PossibleU32Bits(inst->Arg(1)); case ValueOpcode::ShiftLeftLogical32: { const auto shift = inst->Arg(1).Resolve(); - return shift.IsImmediate() && shift.GetType() == Type::U32 - ? PossibleU32Bits(inst->Arg(0)) << (shift.U32() & 31u) - : UINT32_MAX; + if (shift.IsImmediate() && shift.GetType() == Type::U32) { + const uint32_t s = shift.U32() & 31u; + // Low s bits are always zero; upper bits depend on the input. + const uint32_t lo_zero = (1u << s) - 1u; + return (PossibleU32Bits(inst->Arg(0)) << s) & ~lo_zero; + } + return UINT32_MAX; } default: return UINT32_MAX; } @@ -563,10 +567,14 @@ class Tracker { descriptor.dwords[3] = CanonicalizeSampleAdjustDword3(descriptor.dwords[3]); } const auto dword0 = descriptor.dwords[0].Resolve(); - if (sampler && dword0.IsImmediate() && dword0.GetType() == Type::U32 && - (dword0.U32() & SamplerBorderClampMask) == 0) { - // Border color and its table index are unused unless a clamp axis selects border mode. - descriptor.dwords[3] = Value(0u); + if (sampler) { + const bool ignores_border = (PossibleU32Bits(dword0) & SamplerBorderClampMask) == 0; + const bool only_reserved = + (PossibleU32Bits(descriptor.dwords[3]) & ~SamplerDword3ReservedMask) == 0; + if (ignores_border || only_reserved) { + // GPU expressions in reserved bits do not affect the sampler fields. + descriptor.dwords[3] = Value(0u); + } } m_resolved_handles.push_back({&handle, pc, descriptor, {}}); } @@ -1673,8 +1681,11 @@ class Tracker { [](Value word) { return word.Resolve().GetType() == Type::U32; })) { return false; } - Fail(pc, fmt::format("{} dword {} is not a valid runtime value", - ValueOpcodeName(expected), bad_dword)); + const auto word = descriptor.dwords[bad_dword].Resolve(); + const auto* def = word.TryInstruction(); + Fail(pc, fmt::format("{} dword {} is not a valid runtime value ({})", + ValueOpcodeName(expected), bad_dword, + def != nullptr ? ValueOpcodeName(def->GetOpcode()) : "immediate")); } source = InternSource(descriptor); return true; diff --git a/src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp b/src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp index ec2b950..805e766 100644 --- a/src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp +++ b/src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp @@ -71,6 +71,14 @@ bool IsRuntimeSelect(ValueOpcode op) { op == ValueOpcode::SelectF32; } +uint32_t ReverseDescriptorBits(uint32_t word) { + word = ((word & 0x55555555u) << 1u) | ((word >> 1u) & 0x55555555u); + word = ((word & 0x33333333u) << 2u) | ((word >> 2u) & 0x33333333u); + word = ((word & 0x0f0f0f0fu) << 4u) | ((word >> 4u) & 0x0f0f0f0fu); + return ((word & 0x000000ffu) << 24u) | ((word & 0x0000ff00u) << 8u) | + ((word & 0x00ff0000u) >> 8u) | (word >> 24u); +} + bool IsRuntimeUniformOp(ValueOpcode op) { switch (op) { case ValueOpcode::ConditionRef: @@ -104,6 +112,7 @@ bool IsRuntimeUniformOp(ValueOpcode op) { case ValueOpcode::BitwiseOr32: case ValueOpcode::BitwiseXor32: case ValueOpcode::BitwiseNot32: + case ValueOpcode::BitReverse32: case ValueOpcode::SelectU1: case ValueOpcode::SelectU32: case ValueOpcode::SelectF32: @@ -811,6 +820,10 @@ bool SrtWalker::EvaluateInst(const Inst& inst, uint64_t& result) { return true; } return false; + case ValueOpcode::BitReverse32: + if (!Arg(inst, 0, a)) return false; + result = ReverseDescriptorBits(static_cast(a)); + return true; case ValueOpcode::ShiftLeftLogical32: if (binary()) { result = static_cast(a) << (b & 31u); @@ -1384,6 +1397,7 @@ class SrtPlanCompiler { case ValueOpcode::FPRecipIFlag32: case ValueOpcode::FPIsNan32: case ValueOpcode::BitwiseNot32: + case ValueOpcode::BitReverse32: case ValueOpcode::ConditionRef: case ValueOpcode::LogicalNot: Operands(inst, node, 1); break; case ValueOpcode::CompositeConstructU64: @@ -1822,6 +1836,10 @@ bool CompiledSrtWalker::EvaluateInst(uint32_t id, uint64_t& result) { if (!EvaluateNode(node.args[0], a)) return false; result = ~static_cast(a); return true; + case ValueOpcode::BitReverse32: + if (!EvaluateNode(node.args[0], a)) return false; + result = ReverseDescriptorBits(static_cast(a)); + return true; case ValueOpcode::ShiftLeftLogical32: if (!binary()) return false; result = static_cast(a) << (b & 31u); diff --git a/src/graphics/shader/shader.cpp b/src/graphics/shader/shader.cpp index 9d9aadc..d83a277 100644 --- a/src/graphics/shader/shader.cpp +++ b/src/graphics/shader/shader.cpp @@ -594,7 +594,8 @@ static void ShaderGetStaticInputInfoCS(const HW::ComputeShaderInfo& regs, info.workgroup_register = regs.cs_regs.user_sgpr; } -void BuildStageStaticKey(const ShaderVertexInputInfo& info, std::vector& key) { +void BuildStageStaticKey(const ShaderVertexInputInfo& info, std::vector& key, + bool specialize_vertex_pulling) { EXIT_IF(info.resources_num < 0 || info.resources_num > ShaderVertexInputInfo::RES_MAX); key.clear(); key.push_back(static_cast(info.fetch_embedded)); @@ -640,6 +641,13 @@ void BuildStageStaticKey(const ShaderVertexInputInfo& info, std::vector(destination.attr_id)); key.push_back(resource.fields[3] & 0x7ffffu); // Channels and format used by embedded fetch. + if (specialize_vertex_pulling && i < 27) { + // Native MSL pulls from each attribute's buffer and bakes its stride and index source. + const auto binding = destination.buffer_index; + const bool pulls = !resource.SwizzleEnabled() && binding >= 0 && binding < info.buffers_num; + key.push_back(pulls ? info.buffers[binding].stride : 0u); + key.push_back(pulls ? (info.buffers[binding].fetch_index != 0 ? 2u : 1u) : 0u); + } } } @@ -687,6 +695,7 @@ void BuildStageStaticKey(const ShaderComputeInputInfo& info, std::vector(info.dispatch_thread_dimensions)); for (int i = 0; i < 3; i++) { diff --git a/src/graphics/shader/shader.h b/src/graphics/shader/shader.h index 04022b4..64100ea 100644 --- a/src/graphics/shader/shader.h +++ b/src/graphics/shader/shader.h @@ -147,6 +147,7 @@ struct ShaderVertexInputInfo { }; struct ShaderComputeInputInfo: ShaderWorkgroupInputInfo { + uint32_t metal_threadgroup_limit_dwords = 0; uint8_t float_mode = 0xc0; uint32_t dispatch_threads_num[3] = {0, 0, 0}; bool group_id[3] = {false, false, false}; diff --git a/src/graphics/shader/shaderCompiler.h b/src/graphics/shader/shaderCompiler.h index d4b05f5..c1e2738 100644 --- a/src/graphics/shader/shaderCompiler.h +++ b/src/graphics/shader/shaderCompiler.h @@ -26,7 +26,8 @@ struct ShaderParams { } }; -void BuildStageStaticKey(const ShaderVertexInputInfo& input_info, std::vector& key); +void BuildStageStaticKey(const ShaderVertexInputInfo& input_info, std::vector& key, + bool specialize_vertex_pulling = false); void BuildStageStaticKey(const ShaderPixelInputInfo& input_info, std::vector& key); void BuildStageStaticKey(const ShaderComputeInputInfo& input_info, std::vector& key); diff --git a/src/kernel/eventQueue.cpp b/src/kernel/eventQueue.cpp index 010a1f0..afb8472 100644 --- a/src/kernel/eventQueue.cpp +++ b/src/kernel/eventQueue.cpp @@ -564,7 +564,7 @@ int KYTY_SYSV_ABI KernelAddAmprEvent(KernelEqueue eq, int id, void* udata) { if (eq != KERNEL_EQUEUE_INVALID) { KernelEqueueEvent event {}; event.event.ident = static_cast(id); - event.event.filter = KERNEL_EVFILT_USER; + event.event.filter = KERNEL_EVFILT_AMPR; event.event.flags = EV_ADD | EV_CLEAR; event.event.fflags = 0; event.event.data = 0; @@ -592,7 +592,7 @@ int KYTY_SYSV_ABI KernelDeleteAmprEvent(KernelEqueue eq, int id) { LOGF("\t AMPR event delete: eq = 0x%016" PRIx64 ", id = %d\n", static_cast(eq), id); if (eq != KERNEL_EQUEUE_INVALID) { - (void)KernelDeleteEvent(eq, static_cast(id), KERNEL_EVFILT_USER); + (void)KernelDeleteEvent(eq, static_cast(id), KERNEL_EVFILT_AMPR); } return OK; diff --git a/src/kernel/eventQueue.h b/src/kernel/eventQueue.h index ca724cd..911d6ea 100644 --- a/src/kernel/eventQueue.h +++ b/src/kernel/eventQueue.h @@ -18,6 +18,7 @@ constexpr int16_t KERNEL_EVFILT_FILE = -4; constexpr int16_t KERNEL_EVFILT_GRAPHICS = -14; constexpr int16_t KERNEL_EVFILT_VIDEO_OUT = -13; constexpr int16_t KERNEL_EVFILT_HRTIMER = -15; +constexpr int16_t KERNEL_EVFILT_AMPR = -25; class KernelEqueuePrivate; struct KernelEqueueEvent; diff --git a/src/kernel/pthread.cpp b/src/kernel/pthread.cpp index ba95bdf..3bb1fe0 100644 --- a/src/kernel/pthread.cpp +++ b/src/kernel/pthread.cpp @@ -1993,7 +1993,8 @@ int KYTY_SYSV_ABI PthreadAttrGetschedparam(const PthreadAttr* attr, KernelSchedP return KERNEL_ERROR_EINVAL; } - int result = pthread_attr_getschedparam(&(*attr)->p, param); + sched_param native_param {}; + int result = pthread_attr_getschedparam(&(*attr)->p, &native_param); // Host priority mapping is lossy; return the exact guest value. param->sched_priority = (*attr)->guest_priority; @@ -2161,7 +2162,7 @@ int KYTY_SYSV_ABI PthreadAttrSetschedparam(PthreadAttr* attr, const KernelSchedP } #if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS - KernelSchedParam pparam {}; + sched_param pparam {}; if (param->sched_priority <= 478) { pparam.sched_priority = +2; } else if (param->sched_priority >= 733) { diff --git a/src/kernel/pthread.h b/src/kernel/pthread.h index 6819410..ca3d626 100644 --- a/src/kernel/pthread.h +++ b/src/kernel/pthread.h @@ -60,7 +60,7 @@ using Pthread = PthreadPrivate*; using KernelCpumask = uint64_t; using PthreadMutex = PthreadMutexPrivate*; using PthreadMutexattr = PthreadMutexattrPrivate*; -using KernelSchedParam = struct sched_param; +struct KernelSchedParam { int sched_priority; }; using PthreadRwlock = PthreadRwlockPrivate*; using PthreadRwlockattr = PthreadRwlockattrPrivate*; using KernelUseconds = unsigned int; diff --git a/src/libs/libAmpr.cpp b/src/libs/libAmpr.cpp index 471fff4..ce74660 100644 --- a/src/libs/libAmpr.cpp +++ b/src/libs/libAmpr.cpp @@ -1201,8 +1201,9 @@ static int ExecuteCommand(const CommandBufferState::Command& entry) { std::get_if(&entry.data)) { const auto& command = *payload; const auto eq = static_cast(command.eq); - auto result = LibKernel::EventQueue::KernelTriggerUserEvent( - eq, command.id, reinterpret_cast(command.data)); + auto result = LibKernel::EventQueue::KernelTriggerEvent( + eq, static_cast(command.id), LibKernel::EventQueue::KERNEL_EVFILT_AMPR, + reinterpret_cast(command.data)); if (result != OK) { LOGF("\tAPR submit event failed: eq=0x%016" PRIx64 ", id=%" PRId32 ", result=0x%08" PRIx32 "\n", diff --git a/src/libs/libKernel.cpp b/src/libs/libKernel.cpp index 0facc76..09393d9 100644 --- a/src/libs/libKernel.cpp +++ b/src/libs/libKernel.cpp @@ -267,7 +267,8 @@ int KYTY_SYSV_ABI KernelDlsym(KernelModule handle, const char* symbol, void** ad } if (handle == 0 && std::strcmp(symbol, "scriptingGetMem") == 0) { - *addr = reinterpret_cast(&KernelApplicationHeapGetMem); + *addr = reinterpret_cast(Loader::GuestCpu::GetHostFunctionStub( + reinterpret_cast(&KernelApplicationHeapGetMem), "KernelApplicationHeapGetMem")); if (index < 32 || (index % 600) == 0) { LOGF("\t resolved = 0x%016" PRIx64 " (application heap scriptingGetMem)\n", reinterpret_cast(*addr)); @@ -1250,8 +1251,16 @@ static int KYTY_SYSV_ABI KernelRaiseException(Pthread thread, int signum) { WaitForSignalDispatch(thread, signum); return OK; #else - auto ctx = CreateSignalUcontext(); - handler(signum, &ctx); + if (thread == PthreadSelfOrNull()) { + SignalDispatchScope scope; + auto ctx = CreateSignalUcontext(); + SanitizeNonGuestSignalUcontext(&ctx, thread); + handler(signum, &ctx); + } else { + // The target dispatches the handler when it wakes from a guest wait. + PthreadQueuePendingSignal(thread, signum); + PthreadWakeForSignal(thread); + } #endif } @@ -2443,6 +2452,9 @@ struct FiberOptParam { uint32_t magic; }; +#if KYTY_GUEST_CPU_EMULATED +using FiberCpuContext = Loader::GuestCpu::GuestContinuation; +#else struct FiberCpuContext { uint64_t rbx; uint64_t rbp; @@ -2457,6 +2469,7 @@ struct FiberCpuContext { }; static_assert(sizeof(FiberCpuContext) == 80); +#endif struct FiberObject { uint32_t magic_start; @@ -2474,6 +2487,9 @@ struct FiberObject { FiberCpuContext saved_context; uint64_t arg_on_run; uint64_t arg_on_return; +#if KYTY_GUEST_CPU_EMULATED + uint64_t* arg_on_resume; +#endif bool context_valid; uint32_t magic_end; }; @@ -2503,6 +2519,9 @@ struct FiberThreadContext { FiberObject* returned_fiber; FiberObject* pending_idle_fiber; FiberCpuContext cpu_context; +#if KYTY_GUEST_CPU_EMULATED + uint64_t* arg_on_return; +#endif }; static const auto g_fiber_context_key = [] { @@ -2570,6 +2589,52 @@ static void FiberSetContextValid(FiberObject* fiber, bool valid) { fiber->context = valid ? &fiber->saved_context : nullptr; } +#if KYTY_GUEST_CPU_EMULATED +static thread_local FiberThreadContext g_emulated_fiber_thread; + +static void FiberResumeThread(FiberThreadContext* context, uint64_t value, int32_t result) { + if (context->arg_on_return != nullptr) { + *context->arg_on_return = value; + } + Loader::GuestCpu::ResumeContinuation(context->cpu_context, static_cast(result)); + FiberCompleteSwitch(nullptr); + FiberSetThreadContext(nullptr); +} + +static void FiberFinishEmulated() { + auto* context = FiberGetThreadContext(); + auto* fiber = context->current_fiber; + FiberSetContextValid(fiber, false); + FiberStoreState(fiber, FIBER_STATE_TERMINATED); + FiberResumeThread(context, 0, FIBER_ERROR_STATE); +} + +static void FiberEnterEmulated(FiberObject* fiber) { + if (fiber->context_valid) { + if (fiber->arg_on_resume != nullptr) { + *fiber->arg_on_resume = fiber->arg_on_run; + fiber->arg_on_resume = nullptr; + } + Loader::GuestCpu::ResumeContinuation(fiber->saved_context, OK); + } else { + static const auto finish = Loader::GuestCpu::GetHostFunctionStub( + reinterpret_cast(&FiberFinishEmulated), "Fiber::FinishEmulated"); + const auto stack_top = reinterpret_cast(fiber->context_end) & ~uint64_t {15}; + // The finish stub also enters HLE, so leave a readable frame below the stack end. + auto* stack = reinterpret_cast(stack_top - 3 * sizeof(uint64_t)); + stack[0] = finish; + stack[1] = 0; + stack[2] = 0; + FiberCpuContext initial {}; + initial.rsp = reinterpret_cast(stack); + initial.rip = reinterpret_cast(fiber->entry); + initial.rdi = fiber->arg_on_initialize; + initial.rsi = fiber->arg_on_run; + Loader::GuestCpu::ResumeContinuation(initial, OK); + } + FiberCompleteSwitch(fiber); +} +#else #if defined(__x86_64__) || defined(_M_X64) [[gnu::naked, gnu::returns_twice]] static KYTY_SYSV_ABI int FiberSaveContext(FiberCpuContext* /*ctx*/) { @@ -2652,6 +2717,7 @@ static int FiberSaveContext(FiberCpuContext* ctx) { FiberRestoreContext(&context->cpu_context, 1); } +#endif int32_t KYTY_SYSV_ABI FiberInitialize(FiberObject* fiber, const char* name, FiberEntry entry, uint64_t arg_on_initialize, void* addr_context, @@ -2693,7 +2759,7 @@ int32_t KYTY_SYSV_ABI FiberInitialize(FiberObject* fiber, const char* name, Fibe fiber->context_start = addr_context; fiber->context_end = (addr_context != nullptr ? static_cast(addr_context) + size_context : nullptr); - std::memset(&fiber->saved_context, 0, sizeof(fiber->saved_context)); + fiber->saved_context = {}; FiberSetContextValid(fiber, false); fiber->magic_end = FIBER_MAGIC_END; @@ -2763,12 +2829,27 @@ int32_t KYTY_SYSV_ABI FiberRun(FiberObject* fiber, uint64_t arg_on_run, uint64_t if (FiberGetThreadContext() != nullptr) { return FIBER_ERROR_PERMISSION; } +#if KYTY_GUEST_CPU_EMULATED + FiberCpuContext caller {}; + if (fiber->addr_context == nullptr || !Loader::GuestCpu::CaptureContinuation(&caller)) { + return FIBER_ERROR_INVALID; + } +#endif if (!FiberCompareExchangeState(fiber, FIBER_STATE_IDLE, FIBER_STATE_RUNNING)) { return FIBER_ERROR_STATE; } fiber->arg_on_run = arg_on_run; fiber->arg_on_return = 0; +#if KYTY_GUEST_CPU_EMULATED + auto& context = g_emulated_fiber_thread; + context = {}; + context.cpu_context = caller; + context.arg_on_return = arg_on_return; + FiberSetThreadContext(&context); + FiberEnterEmulated(fiber); + return OK; +#else // Register on the host stack; switching fibers only reads the native TLS slot. FiberThreadContext context {}; FiberSetThreadContext(&context); @@ -2793,6 +2874,7 @@ int32_t KYTY_SYSV_ABI FiberRun(FiberObject* fiber, uint64_t arg_on_run, uint64_t } return return_code; +#endif } int32_t KYTY_SYSV_ABI FiberSwitch(FiberObject* fiber, uint64_t arg_on_run, @@ -2807,15 +2889,27 @@ int32_t KYTY_SYSV_ABI FiberSwitch(FiberObject* fiber, uint64_t arg_on_run, return FIBER_ERROR_PERMISSION; } + auto* caller = context->current_fiber; +#if KYTY_GUEST_CPU_EMULATED + FiberCpuContext saved_context {}; + if (fiber->addr_context == nullptr || !Loader::GuestCpu::CaptureContinuation(&saved_context)) { + return FIBER_ERROR_INVALID; + } +#endif if (!FiberCompareExchangeState(fiber, FIBER_STATE_IDLE, FIBER_STATE_RUNNING)) { return FIBER_ERROR_STATE; } - auto* caller = context->current_fiber; - fiber->arg_on_run = arg_on_run; fiber->arg_on_return = 0; +#if KYTY_GUEST_CPU_EMULATED + caller->saved_context = saved_context; + caller->arg_on_resume = arg_on_return; + FiberSetContextValid(caller, true); + context->pending_idle_fiber = caller; + FiberEnterEmulated(fiber); +#else if (FiberSaveContext(&caller->saved_context) == 0) { FiberSetContextValid(caller, true); context->pending_idle_fiber = caller; @@ -2830,6 +2924,7 @@ int32_t KYTY_SYSV_ABI FiberSwitch(FiberObject* fiber, uint64_t arg_on_run, if (arg_on_return != nullptr) { *arg_on_return = caller->arg_on_run; } +#endif return OK; } @@ -2858,6 +2953,15 @@ int32_t KYTY_SYSV_ABI FiberReturnToThread(uint64_t arg_on_return, uint64_t* arg_ auto* fiber = context->current_fiber; fiber->arg_on_return = arg_on_return; +#if KYTY_GUEST_CPU_EMULATED + if (!Loader::GuestCpu::CaptureContinuation(&fiber->saved_context)) { + return FIBER_ERROR_PERMISSION; + } + fiber->arg_on_resume = arg_on_run; + FiberSetContextValid(fiber, true); + context->pending_idle_fiber = fiber; + FiberResumeThread(context, arg_on_return, OK); +#else if (FiberSaveContext(&fiber->saved_context) == 0) { FiberSetContextValid(fiber, true); context->returned_fiber = fiber; @@ -2869,6 +2973,7 @@ int32_t KYTY_SYSV_ABI FiberReturnToThread(uint64_t arg_on_return, uint64_t* arg_ if (arg_on_run != nullptr) { *arg_on_run = fiber->arg_on_run; } +#endif return OK; } @@ -3460,7 +3565,7 @@ static void AddLibkernelUnityFunc(Loader::SymbolDatabase* s, const char* nid, ui sr.module_version_major = 1; sr.module_version_minor = 1; sr.type = Loader::SymbolType::Func; - s->Add(sr, func, dbg_name); + s->Add(sr, Loader::GuestCpu::GetHostFunctionStub(func, dbg_name.c_str()), dbg_name); } LIB_DEFINE(InitLibKernel_1) { diff --git a/src/loader/guest_cpu/fex_guest_cpu.cpp b/src/loader/guest_cpu/fex_guest_cpu.cpp index f519f83..6f66bbf 100644 --- a/src/loader/guest_cpu/fex_guest_cpu.cpp +++ b/src/loader/guest_cpu/fex_guest_cpu.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -31,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -231,7 +233,8 @@ FEXCore::HostFeatures MakeHostFeatures() { if (sysctlbyname("hw.cachelinesize", &line, &size, nullptr, 0) != 0 || line == 0) { line = 64; } - f.DCacheLineLog2 = static_cast(std::log2(static_cast(line) / 4.0)); + f.DCacheLineSize = static_cast(line); + f.ICacheLineSize = static_cast(line); f.SupportsCacheMaintenanceOps = 0; f.SupportsAES = SysctlFlag("hw.optional.arm.FEAT_AES"); f.SupportsCRC = SysctlFlag("hw.optional.arm.FEAT_CRC32"); @@ -305,6 +308,9 @@ struct ThreadState { static constexpr int kMaxHleRegsDepth = 16; GuestRegs hle_regs[kMaxHleRegsDepth] {}; int hle_regs_depth = 0; + GuestContinuation continuation {}; + uint64_t continuation_result = 0; + int continuation_depth = 0; HostCallFrame bridge[kMaxBridgeDepth] {}; int bridge_depth = 0; uint64_t callret_alloc = 0; // call-ret stack incl. guard pages @@ -346,7 +352,7 @@ ThreadState* GetThreadState() { st.cs_cached = FEXCore::Core::CPUState::CalculateGDTBase(*cs); st.mxcsr = 0x1F80; - ts->thread = g->ctx->CreateThread(&st); + ts->thread = g->ctx->CreateThread(st.rip, st.gregs[X86::REG_RSP], &st); if (ts->thread == nullptr) { std::fprintf(stderr, "[fex] CreateThread failed\n"); std::abort(); @@ -469,6 +475,8 @@ GuestCallResult RunGuest(uint64_t entry, const GuestCallArgs& a, uint64_t stack_ st.gregs[X86::REG_RAX] = 8; // AL = vector registers used, for variadic callees ts->depth++; + // FEX may leave this thread in write mode after allocating its JIT buffer. + pthread_jit_write_protect_np(1); g->ctx->HandleCallback(ts->thread, entry); ts->depth--; @@ -550,6 +558,7 @@ void DispatchHle(FEXCore::Core::CpuStateFrame* frame, uint64_t index) { *reinterpret_cast<__uint128_t*>(&f.v[i]) = *reinterpret_cast(st.xmm.sse.data[i]); } + const auto n = g->hle_calls.fetch_add(1, std::memory_order_relaxed); // Restrict a diagnostic HLE trace to one guest module without spending its // quota on unrelated rendering/thread calls (begin:end, end exclusive). @@ -587,9 +596,33 @@ void DispatchHle(FEXCore::Core::CpuStateFrame* frame, uint64_t index) { static_cast(tid)); } + const auto dispatch_depth = ts->hle_regs_depth; if (__builtin_expect(ts->hle_regs_depth > 0, 1)) { --ts->hle_regs_depth; } + if (ts->continuation_depth != 0 && ts->continuation_depth == dispatch_depth) { + const auto& resume = ts->continuation; + st.gregs[X86::REG_RBX] = resume.rbx; + st.gregs[X86::REG_RBP] = resume.rbp; + st.gregs[X86::REG_RDI] = resume.rdi; + st.gregs[X86::REG_RSI] = resume.rsi; + st.gregs[X86::REG_R12] = resume.r12; + st.gregs[X86::REG_R13] = resume.r13; + st.gregs[X86::REG_R14] = resume.r14; + st.gregs[X86::REG_R15] = resume.r15; + // FEX can translate syscall and the stub's ret in the same block. Put the + // continuation on the destination stack so that ret restores both RIP and RSP. + st.gregs[X86::REG_RSP] = resume.rsp - sizeof(uint64_t); + *reinterpret_cast(st.gregs[X86::REG_RSP]) = resume.rip; + st.gregs[X86::REG_RAX] = ts->continuation_result; + st.rip = rip + 2; + st.mxcsr = resume.mxcsr; + st.FCW = resume.fcw; + // Predicted native return addresses belong to the previous guest stack. + st.callret_sp = CallRetDefault(ts->callret_alloc); + ts->continuation_depth = 0; + return; + } st.gregs[X86::REG_RAX] = f.ret_x0; st.gregs[X86::REG_RDX] = f.ret_x1; *reinterpret_cast<__uint128_t*>(st.xmm.sse.data[0]) = *reinterpret_cast(&f.ret_v0); @@ -599,14 +632,16 @@ void DispatchHle(FEXCore::Core::CpuStateFrame* frame, uint64_t index) { class KytySyscallHandler final : public FEXCore::HLE::SyscallHandler { public: - void HandleSyscall(FEXCore::Core::CpuStateFrame* frame) override { + KytySyscallHandler() { OSABI = FEXCore::HLE::SyscallOSABI::OS_GENERIC; } + + uint64_t HandleSyscall(FEXCore::Core::CpuStateFrame* frame, FEXCore::HLE::SyscallArguments*) override { auto& st = frame->State; const uint64_t rip = st.rip; if (__builtin_expect(InStubRegion(rip), 1)) { const uint64_t index = (rip - reinterpret_cast(g->stub_base)) / kStubSlotSize; if (__builtin_expect(index < g->stub_count.load(std::memory_order_acquire), 1)) { DispatchHle(frame, index); - return; + return st.gregs[X86::REG_RAX]; } } // A raw `syscall` in guest code. PS5 games reach the kernel through libkernel (HLE), so @@ -619,6 +654,7 @@ class KytySyscallHandler final : public FEXCore::HLE::SyscallHandler { } st.gregs[X86::REG_RAX] = static_cast(-38); st.rip = rip + 2; + return st.gregs[X86::REG_RAX]; } FEXCore::HLE::ExecutableRangeInfo QueryGuestExecutableRange(FEXCore::Core::InternalThreadState* /*thread*/, @@ -811,6 +847,32 @@ bool GetCurrentGuestRegs(GuestRegs* out) { return true; } +bool CaptureContinuation(GuestContinuation* continuation) { + GuestRegs regs {}; + if (!GetCurrentGuestRegs(®s)) { + return false; + } + const auto& state = State(t_state); + *continuation = { + regs.gpr[X86::REG_RBX], regs.gpr[X86::REG_RBP], + regs.gpr[X86::REG_RDI], regs.gpr[X86::REG_RSI], + regs.gpr[X86::REG_R12], regs.gpr[X86::REG_R13], + regs.gpr[X86::REG_R14], regs.gpr[X86::REG_R15], + regs.gpr[X86::REG_RSP] + sizeof(uint64_t), regs.rip, + state.mxcsr, state.FCW, + }; + return true; +} + +void ResumeContinuation(const GuestContinuation& continuation, uint64_t result) { + if (t_state == nullptr || t_state->hle_regs_depth == 0 || t_state->continuation_depth != 0) { + std::abort(); + } + t_state->continuation = continuation; + t_state->continuation_result = result; + t_state->continuation_depth = t_state->hle_regs_depth; +} + bool GetFaultGuestLocation(uint64_t host_pc, GuestFaultLocation* out) { // No new thread state, loader locks, or mutation of the faulting CPU context. if (out == nullptr || g == nullptr || !g->ctx || t_state == nullptr || t_state->thread == nullptr || @@ -888,6 +950,7 @@ bool HandleHostFault(int /*sig*/, void* siginfo, void* ucontext) { const uint64_t pc_now = mc->__ss.__pc; if (align && ts != nullptr && ts->thread != nullptr && g->ctx->IsAddressInCodeBuffer(ts->thread, pc_now)) { // __x[0..28], __fp, __lr are contiguous: the 31-entry GPR array FEX expects. + const FEXCore::Allocator::ScopedJITWriteProtect allow_backpatch; const auto result = FEXCore::ArchHelpers::Arm64::HandleUnalignedAccess( ts->thread, FEXCore::ArchHelpers::Arm64::UnalignedHandlerType::HalfBarrier, pc_now, &mc->__ss.__x[0]); if (result.has_value()) { diff --git a/src/loader/guest_cpu/guest_cpu.h b/src/loader/guest_cpu/guest_cpu.h index e9cf3a3..b10e398 100644 --- a/src/loader/guest_cpu/guest_cpu.h +++ b/src/loader/guest_cpu/guest_cpu.h @@ -70,6 +70,27 @@ struct GuestRegs { }; bool GetCurrentGuestRegs(GuestRegs* out); +// The SysV register context needed to suspend a guest call and return on a different guest stack. +struct GuestContinuation { + uint64_t rbx = 0; + uint64_t rbp = 0; + uint64_t rdi = 0; + uint64_t rsi = 0; + uint64_t r12 = 0; + uint64_t r13 = 0; + uint64_t r14 = 0; + uint64_t r15 = 0; + uint64_t rsp = 0; + uint64_t rip = 0; + uint32_t mxcsr = 0x1f80; + uint16_t fcw = 0x37f; +}; + +// Valid within HLE. A queued continuation replaces that HLE call's ordinary guest return. +bool CaptureContinuation(GuestContinuation* continuation); +void ResumeContinuation(const GuestContinuation& continuation, uint64_t result); + + // Diagnostic only: FEX's best RIP reconstruction for a fault inside its JIT cache. // FEX can fall back to a saved RIP; this is a location hint, not a reconstructed register file. struct GuestFaultLocation { diff --git a/src/loader/runtimeLinker.cpp b/src/loader/runtimeLinker.cpp index 012e08a..36a9dc0 100644 --- a/src/loader/runtimeLinker.cpp +++ b/src/loader/runtimeLinker.cpp @@ -1432,7 +1432,7 @@ RuntimeLinker::~RuntimeLinker() { Clear(); } -Program* RuntimeLinker::LoadProgram(const std::filesystem::path& elf_name) { +Program* RuntimeLinker::LoadProgram(const std::filesystem::path& elf_name, bool optional) { KYTY_PROFILER_FUNCTION(); Common::LockGuard lock(m_mutex); @@ -1455,6 +1455,10 @@ Program* RuntimeLinker::LoadProgram(const std::filesystem::path& elf_name) { LoadProgramToMemory(program); ParseProgramDynamicInfo(program); CreateSymbolDatabase(program); + } else if (optional) { + std::fprintf(stderr, "[Loader] Ignoring non-executable adjacent module: %s\n", + Common::PathToString(elf_name.filename()).c_str()); + return nullptr; } else { EXIT("elf is not valid: %s\n", Common::PathToString(elf_name).c_str()); } @@ -1935,9 +1939,12 @@ void RuntimeLinker::PreloadAdjacentPrograms() { add_dir(root / "sce_module"); add_dir(root / "sce_modules"); + // Adjacent .prx files can contain data for hardware modules. Only an + // explicitly requested executable must pass validation. for (const auto& path: module_paths) { - auto* program = LoadProgram(path); - program->fail_if_global_not_resolved = false; + if (auto* program = LoadProgram(path, true)) { + program->fail_if_global_not_resolved = false; + } } } diff --git a/src/loader/runtimeLinker.h b/src/loader/runtimeLinker.h index 7be2aae..721841a 100644 --- a/src/loader/runtimeLinker.h +++ b/src/loader/runtimeLinker.h @@ -143,7 +143,7 @@ class RuntimeLinker { void DbgDump(const std::string& folder); - Program* LoadProgram(const std::filesystem::path& elf_name); + Program* LoadProgram(const std::filesystem::path& elf_name, bool optional = false); void SaveMainProgram(const std::filesystem::path& elf_name); void SaveProgram(Program* program, const std::filesystem::path& elf_name); void UnloadProgram(Program* program); diff --git a/src/main.cpp b/src/main.cpp index b1bc22b..968a311 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -45,9 +45,12 @@ static std::string GetBuildString() { static void PrintUsage() { ::printf("KyTx PS5 Emulator [ARM64 + Metal RDNA->MSL]\n"); ::printf("%s\n", GetBuildString().c_str()); - ::printf("kytx_emulator --game [options]\n\n"); + ::printf("kytx_emulator --game [options]\n\n"); ::printf("Options:\n"); - ::printf(" --game Game directory, ELF, or ZArchive to load.\n"); + ::printf(" --game Game directory, executable, or archive to load.\n"); +#if defined(__APPLE__) + ::printf(" .pkg and .fpkg require the external KYTY_FPKG_READER helper.\n"); +#endif ::printf(" --game-patch ETAHen cheat file.\n"); ::printf(" --screen-width Window width. Default: 1920.\n"); ::printf(" --screen-height Window height. Default: 1080.\n"); @@ -270,6 +273,11 @@ static bool ParseArgs(int argc, char* argv[], RunOptions& options, bool& show_he options.app0_dir = path; options.elf = "/app0/eboot.bin"; } else if (Common::IsSupportedArchive(path) && Common::File::IsFileExisting(path)) { + options.game_archive = Common::OpenArchive(path); + if (!options.game_archive) { + ::printf("Could not open game archive: %s\n", value.c_str()); + return false; + } const auto root = Common::MakeArchivePath(path); if (!Common::File::IsFileExisting(root / "eboot.bin")) { ::printf("Archive does not contain eboot.bin: %s\n", value.c_str()); diff --git a/src/prospero/Prospero.swift b/src/prospero/Prospero.swift new file mode 100644 index 0000000..cb42238 --- /dev/null +++ b/src/prospero/Prospero.swift @@ -0,0 +1,364 @@ +import AppKit +import SwiftUI +import UniformTypeIdentifiers + +private enum VirtualRefreshRate: Int { + case hz60 = 60 + case hz120 = 120 + + static let standard = Self.hz60 +} + +struct LibraryGame: Codable, Identifiable, Hashable { + let path: String + let title: String + var patch: String? + var id: String { path } + + init(url: URL) { + let folder = url.lastPathComponent == "eboot.bin" ? url.deletingLastPathComponent() : url + path = folder.standardizedFileURL.path + let manifest = folder.appendingPathComponent("sce_sys/param.json") + if let data = try? Data(contentsOf: manifest), + let fields = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let localization = fields["localizedParameters"] as? [String: Any], + let locale = localization["defaultLanguage"] as? String, + let entry = localization[locale] as? [String: Any], + let name = entry["titleName"] as? String, !name.isEmpty { + title = name + } else { + title = folder.deletingPathExtension().lastPathComponent + } + } + + var isPackage: Bool { + ["pkg", "fpkg"].contains(URL(fileURLWithPath: path).pathExtension.lowercased()) + } + var artwork: NSImage? { + NSImage(contentsOfFile: URL(fileURLWithPath: path).appendingPathComponent("sce_sys/icon0.png").path) + } +} + +@MainActor +final class Library: ObservableObject { + @Published var games: [LibraryGame] = [] + @Published var selection: String? + @Published var running: String? + @Published var error: String? + private var emulatorProcess: Process? + + init() { + UserDefaults.standard.register(defaults: [ + "tessellation": true, + "window1080": true, + "virtualRefreshRate": VirtualRefreshRate.standard.rawValue + ]) + if let data = UserDefaults.standard.data(forKey: "games"), + let decoded = try? JSONDecoder().decode([LibraryGame].self, from: data) { + games = decoded + } + } + + func showAddGames() { + let panel = NSOpenPanel() + panel.message = "Choose a game folder, eboot.bin, or a supported game package." + panel.canChooseDirectories = true + panel.canChooseFiles = true + panel.allowsMultipleSelection = true + if panel.runModal() == .OK { addGames(panel.urls) } + } + + func addGames(_ urls: [URL]) { + var rejected: [String] = [] + var firstAdded: String? + for url in urls { + let game = LibraryGame(url: url) + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: game.path, isDirectory: &isDirectory), + (game.isPackage && !isDirectory.boolValue) || (isDirectory.boolValue && + FileManager.default.fileExists(atPath: game.path + "/eboot.bin")) else { + rejected.append(url.lastPathComponent) + continue + } + if !games.contains(where: { $0.id == game.id }) { games.append(game) } + if firstAdded == nil { firstAdded = game.id } + } + if let firstAdded { selection = firstAdded } + save() + if !rejected.isEmpty { + error = "Choose a .pkg or .fpkg file or a game folder containing eboot.bin. Could not add " + + rejected.joined(separator: ", ") + "." + } + } + + func choosePatch(for game: LibraryGame) { + let panel = NSOpenPanel() + panel.allowedContentTypes = [.json] + guard panel.runModal() == .OK, let url = panel.url else { return } + setPatch(url.path, for: game) + } + + func setPatch(_ path: String?, for game: LibraryGame) { + guard let index = games.firstIndex(where: { $0.id == game.id }) else { return } + games[index].patch = path + save() + } + + func remove(_ game: LibraryGame) { + games.removeAll { $0.id == game.id } + save() + } + + private func save() { + games.sort { $0.title.localizedStandardCompare($1.title) == .orderedAscending } + if let data = try? JSONEncoder().encode(games) { + UserDefaults.standard.set(data, forKey: "games") + } + } + + static func packageReader(override: String, emulator: URL) -> String? { + if !override.isEmpty { + return FileManager.default.isExecutableFile(atPath: override) ? override : nil + } + let coreFolder = emulator.deletingLastPathComponent() + let candidates = [ + Bundle.main.url(forResource: "read-fpkg", withExtension: nil), + coreFolder.appendingPathComponent("read-fpkg"), + coreFolder.deletingLastPathComponent().appendingPathComponent("fpkg-reader/read-fpkg") + ] + return candidates.compactMap { $0?.path }.first { + FileManager.default.isExecutableFile(atPath: $0) + } + } + + func launch(_ game: LibraryGame) { + guard emulatorProcess == nil else { return } + guard FileManager.default.fileExists(atPath: game.path) else { + error = "The game is unavailable. Connect its drive and try again." + return + } + let defaults = UserDefaults.standard + let core = defaults.string(forKey: "core") ?? "" + let reader = defaults.string(forKey: "reader") ?? "" + let refreshRate = VirtualRefreshRate(rawValue: defaults.integer(forKey: "virtualRefreshRate")) + ?? .standard + let corePath = core.isEmpty ? Bundle.main.bundleURL.deletingLastPathComponent() + .appendingPathComponent("kyty_emulator").path : core + guard FileManager.default.isExecutableFile(atPath: corePath) else { + error = "Select the kyty_emulator executable in Prospero Settings." + return + } + let executable = URL(fileURLWithPath: corePath) + let resolvedReader = game.isPackage ? Self.packageReader(override: reader, emulator: executable) : nil + if game.isPackage && resolvedReader == nil { + error = "Select a compatible package reader in Prospero Settings." + return + } + if let patch = game.patch, !FileManager.default.isReadableFile(atPath: patch) { + error = "The selected game patch is unavailable." + return + } + let process = Process() + process.executableURL = executable + process.currentDirectoryURL = executable.deletingLastPathComponent() + var environment = ProcessInfo.processInfo.environment + environment["KYTY_BACKEND"] = "metal" + environment["KYTY_MSL_ONLY"] = "1" + environment["KYTY_MSL_GDS"] = "1" + environment["KYTY_VIDEO_OUT_1080P"] = defaults.bool(forKey: "window1080") ? "1" : nil + environment["KYTY_FPKG_READER"] = resolvedReader + process.environment = environment + var arguments = ["--game", game.path, "--screen-width", "1920", "--screen-height", "1080", + "--vblank-frequency", String(refreshRate.rawValue)] + if defaults.bool(forKey: "tessellation") { arguments += ["--tessellation"] } + if let patch = game.patch { arguments += ["--game-patch", patch] } + process.arguments = arguments + process.terminationHandler = { [weak self] ended in + let status = ended.terminationStatus + let reason = ended.terminationReason + Task { @MainActor in + self?.emulatorProcess = nil + self?.running = nil + if reason == .exit && status != 0 { + self?.error = "The emulator exited with status \(status)." + } + } + } + do { + try process.run() + emulatorProcess = process + running = game.id + } catch { + self.error = error.localizedDescription + } + } +} + +struct LibraryView: View { + @ObservedObject var library: Library + + var body: some View { + NavigationSplitView { + List(selection: $library.selection) { + ForEach(library.games) { game in + Label(game.title, systemImage: "gamecontroller") + .tag(game.id) + .contextMenu { + Button("Remove from Library") { library.remove(game) } + } + } + } + .dropDestination(for: URL.self) { urls, _ in + library.addGames(urls) + return true + } + .navigationTitle("Library") + .navigationSplitViewColumnWidth(min: 190, ideal: 240) + .toolbar { + Button("Add Games", systemImage: "plus") { library.showAddGames() } + SettingsLink { Label("Settings", systemImage: "gearshape") } + } + } detail: { + if let game = library.games.first(where: { $0.id == library.selection }) { + VStack(alignment: .leading, spacing: 20) { + if let artwork = game.artwork { + Image(nsImage: artwork).resizable().aspectRatio(contentMode: .fit) + .frame(maxHeight: 220).clipShape(.rect(cornerRadius: 12)) + } else { + Image(systemName: "gamecontroller.fill").font(.system(size: 58)) + .foregroundStyle(.tint).accessibilityHidden(true) + } + Text(game.title).font(.largeTitle.bold()) + Text(game.path).font(.callout).foregroundStyle(.secondary) + .textSelection(.enabled) + if let patch = game.patch { + Text(URL(fileURLWithPath: patch).lastPathComponent) + .font(.caption).foregroundStyle(.secondary) + } + Button(library.running == game.id ? "Running" : "Play", systemImage: "play.fill") { + library.launch(game) + } + .buttonStyle(.borderedProminent) + .disabled(library.running != nil) + Menu("Game Options") { + Button("Choose Patch…") { library.choosePatch(for: game) } + if game.patch != nil { + Button("Clear Patch") { library.setPatch(nil, for: game) } + } + } + .fixedSize() + } + .padding(36) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center) + } else { + ContentUnavailableView { + Label(library.games.isEmpty ? "Your Library Is Empty" : "Select a Game", + systemImage: "gamecontroller") + } actions: { + if library.games.isEmpty { + Button("Add Games") { library.showAddGames() }.buttonStyle(.borderedProminent) + } + } + } + } + .frame(minWidth: 720, minHeight: 430) + .alert("Prospero", isPresented: Binding(get: { library.error != nil }, + set: { if !$0 { library.error = nil } })) { + Button("OK", role: .cancel) {} + } message: { Text(library.error ?? "") } + } +} + +struct ProsperoSettings: View { + @AppStorage("core") private var core = "" + @AppStorage("reader") private var reader = "" + @AppStorage("tessellation") private var tessellation = true + @AppStorage("window1080") private var window1080 = true + @AppStorage("virtualRefreshRate") private var virtualRefreshRate = VirtualRefreshRate.standard + @AppStorage("appearance") private var appearance = "system" + + var body: some View { + Form { + Section("Emulator") { + FileSetting(title: "Executable", path: $core, defaultLabel: "Use adjacent emulator") + FileSetting(title: "Package reader", path: $reader, defaultLabel: "Find adjacent reader") + Toggle("Enable tessellation", isOn: $tessellation) + } + Section("Video") { + Toggle("Report 1080p to games", isOn: $window1080) + Picker("Virtual refresh rate", selection: $virtualRefreshRate) { + Text("60 Hz").tag(VirtualRefreshRate.hz60) + Text("120 Hz").tag(VirtualRefreshRate.hz120) + } + Text("Games choose their internal render resolution.") + .foregroundStyle(.secondary) + } + Picker("Appearance", selection: $appearance) { + Text("System").tag("system") + Text("Light").tag("light") + Text("Dark").tag("dark") + } + } + .formStyle(.grouped) + .frame(minWidth: 510, minHeight: 330) + } +} + +struct FileSetting: View { + var title: String + @Binding var path: String + var defaultLabel = "None" + + var body: some View { + LabeledContent(title) { + Text(path.isEmpty ? defaultLabel : URL(fileURLWithPath: path).lastPathComponent) + .lineLimit(1).help(path) + Button("Choose…") { + let panel = NSOpenPanel() + if panel.runModal() == .OK, let file = panel.url { path = file.path } + } + if !path.isEmpty { + Button("Clear") { path = "" } + .accessibilityLabel("Clear \(title)") + } + } + } +} + +@MainActor +final class ProsperoAppDelegate: NSObject, NSApplicationDelegate { + let library = Library() + + func application(_ application: NSApplication, open urls: [URL]) { + library.addGames(urls) + } + + func applicationDidFinishLaunching(_ notification: Notification) { + let arguments = CommandLine.arguments + guard let play = arguments.firstIndex(of: "--play"), play + 1 < arguments.count else { return } + let url = URL(fileURLWithPath: arguments[play + 1]) + library.addGames([url]) + let identifier = LibraryGame(url: url).id + guard var game = library.games.first(where: { $0.id == identifier }) else { return } + if let patch = arguments.firstIndex(of: "--game-patch"), patch + 1 < arguments.count { + let patchPath = URL(fileURLWithPath: arguments[patch + 1]).standardizedFileURL.path + library.setPatch(patchPath, for: game) + game.patch = patchPath + } + library.launch(game) + } +} + +@main +struct ProsperoApp: App { + @NSApplicationDelegateAdaptor(ProsperoAppDelegate.self) private var delegate + @AppStorage("appearance") private var appearance = "system" + + var body: some Scene { + WindowGroup("Prospero") { + LibraryView(library: delegate.library) + .preferredColorScheme(appearance == "light" ? .light : appearance == "dark" ? .dark : nil) + } + Settings { ProsperoSettings() } + } +} diff --git a/tests/EventQueueLifetimeTests.cpp b/tests/EventQueueLifetimeTests.cpp index 430333d..023be62 100644 --- a/tests/EventQueueLifetimeTests.cpp +++ b/tests/EventQueueLifetimeTests.cpp @@ -91,6 +91,32 @@ void TestPeriodicTimerEvents() { Check(EventQueue::KernelDeleteEqueue(queue) == OK, "delete timer queue"); } +void TestAmprAndUserEventsShareAnId() { + EventQueue::KernelEqueue queue = EventQueue::KERNEL_EQUEUE_INVALID; + constexpr int id = 5; + auto* userdata = reinterpret_cast(0x1234); + auto* completion = reinterpret_cast(0x5678); + Check(EventQueue::KernelCreateEqueue(&queue, "apr-test") == OK, "create AMPR queue"); + Check(EventQueue::KernelAddUserEventEdge(queue, id) == OK, "add user event"); + Check(EventQueue::KernelAddAmprEvent(queue, id, userdata) == OK, "add AMPR event"); + Check(EventQueue::KernelTriggerEvent(queue, id, EventQueue::KERNEL_EVFILT_AMPR, + completion) == OK, + "trigger AMPR completion"); + + EventQueue::KernelEvent event {}; + int count = 0; + Libs::LibKernel::KernelUseconds timeout = 0; + Check(EventQueue::KernelWaitEqueue(queue, &event, 1, &count, &timeout) == OK && count == 1, + "receive AMPR completion"); + Check(event.ident == id && event.filter == EventQueue::KERNEL_EVFILT_AMPR && + event.udata == userdata && event.data == reinterpret_cast(completion), + "AMPR completion reports its own filter and payload"); + Check(EventQueue::KernelDeleteAmprEvent(queue, id) == OK, "delete AMPR event"); + Check(EventQueue::KernelTriggerUserEvent(queue, id, userdata) == OK, + "user event survives deletion of AMPR event sharing the id"); + Check(EventQueue::KernelDeleteEqueue(queue) == OK, "delete AMPR queue"); +} + void CountDeletedEvent(EventQueue::KernelEqueue, EventQueue::KernelEqueueEvent* event) { auto* count = static_cast(event->filter.data); count->fetch_add(1, std::memory_order_relaxed); @@ -496,6 +522,7 @@ void TestConcurrentDelete() { int main() { TestPeriodicTimerEvents(); + TestAmprAndUserEventsShareAnId(); TestDuplicateAddPreservesEventState(); TestCallbackStateOutlivesPort(); TestCallbackOwnsPayload(); diff --git a/tests/ResourceTrackingTests.cpp b/tests/ResourceTrackingTests.cpp index d6f9a1a..c9e333e 100644 --- a/tests/ResourceTrackingTests.cpp +++ b/tests/ResourceTrackingTests.cpp @@ -1942,6 +1942,37 @@ void TestSampleAdjustSamplerScratch() { "SampleAdjust canonicalization discarded border-mode bits"); } +void TestSamplerDescriptorWords() { + for (bool reserved_only : {false, true}) { + Fixture fixture(ShaderType::Pixel); + const auto word3 = reserved_only + ? fixture.Emit(ValueOpcode::ShiftLeftLogical32, + {fixture.Emit(ValueOpcode::BitwiseAnd32, + {fixture.Emit(ValueOpcode::LaneId), Value(0xffu)}), + Value(12u)}) + : fixture.Emit(ValueOpcode::BitReverse32, {fixture.UserData(3)}); + const auto image = fixture.Image({Value(0u), Value(0u), Value(0u), Value(0u), + Value(0u), Value(0u), Value(0u), Value(0u)}); + const auto sampler = fixture.Sampler({Value(4u), Value(0u), Value(0u), word3}); + MemoryInfo memory; + memory.kind = ResourceKind::Image; + memory.image_dimension = Decoder::ImageDimension::Dim2D; + fixture.Emit(ValueOpcode::ImageSampleRaw, + {image, sampler, fixture.ImageAddress()}, + fixture.AddMemory(memory, 0x204)); + fixture.PlanAndTrack(); + + const auto source = fixture.program.info.samplers[0].source; + const std::array user_data{0u, 0u, 0u, 0x12345601u}; + SrtRuntime runtime{.user_data = user_data}; + DescriptorValue descriptor; + Check(SrtWalker(fixture.program, runtime).EvaluateDescriptor(source, descriptor), + "sampler descriptor evaluation failed"); + Check(descriptor.dwords[3] == (reserved_only ? 0u : 0x806a2c48u), + "sampler descriptor lost active border fields"); + } +} + void TestFmaskLoadSpecialization() { namespace Prospero = Libs::Graphics::Prospero; Fixture fixture; @@ -3463,6 +3494,7 @@ int main() { Run("runtime unsigned min", TestRuntimeUnsignedMinDescriptor); Run("images and samplers", TestImagesSamplersAndAliases); Run("SampleAdjust sampler scratch", TestSampleAdjustSamplerScratch); + Run("sampler descriptor words", TestSamplerDescriptorWords); Run("FMASK load specialization", TestFmaskLoadSpecialization); Run("gather LOD sampler validation", TestGatherLodSamplerValidation); Run("dynamic storage mips", TestDynamicStorageMipTracking); diff --git a/tests/metalMslTests.mm b/tests/metalMslTests.mm index 0b2db3e..dd9cbe0 100644 --- a/tests/metalMslTests.mm +++ b/tests/metalMslTests.mm @@ -24,6 +24,7 @@ static void Check(bool value, const char* message) { struct Fixture { IR::Program program; uint32_t lds_dwords = 0; + uint32_t metal_lds_limit_dwords = 0; Fixture(uint32_t buffers = 1) { program.stage = ShaderType::Compute; program.wave_size = 32; @@ -57,9 +58,11 @@ void Store(uint32_t block, Value handle, uint32_t offset, Value value, uint64_t static id device; -static id Compile(Fixture& fixture, const ShaderPixelInputInfo* pixel_options = nullptr) { - ShaderComputeInputInfo compute {}; +static id Compile(Fixture& fixture, const ShaderPixelInputInfo* pixel_options = nullptr, + const ShaderComputeInputInfo* compute_options = nullptr) { + ShaderComputeInputInfo compute = compute_options != nullptr ? *compute_options : ShaderComputeInputInfo {}; compute.lds_size_dwords = fixture.lds_dwords; + compute.metal_threadgroup_limit_dwords = fixture.metal_lds_limit_dwords; ShaderPixelInputInfo pixel {}; pixel.dual_source_blending = true; ShaderStageInputInfo input {}; @@ -154,6 +157,7 @@ static void ImageSampling() { bool derivative; int gather_component; // -1 = sample uint32_t expected_layer; + bool cube = false; }; const Case cases[] = { {"2D explicit LOD", Dimension::Dim2D, 0, false, -1, 0}, @@ -169,6 +173,7 @@ static void ImageSampling() { {"gather green", Dimension::Dim2D, 0, false, 1, 0}, {"array gather blue", Dimension::Dim2DArray, 1, false, 2, 1}, {"array gather alpha", Dimension::Dim2DArray, 0.51f, false, 3, 1}, + {"compute cube face", Dimension::Dim2DArray, 2, false, -1, 2, true}, }; unsigned failures = 0; for (const auto& test: cases) { @@ -185,6 +190,7 @@ static void ImageSampling() { image.mip_mode = IR::ImageMipMode::Dynamic; image.mip_count = 5; image.read = true; + image.cube = test.cube; f.program.info.images.push_back(image); f.program.info.samplers.emplace_back(); f.program.bindings.descriptors.push_back({*IR::DescriptorBindingForImage(image), {0}}); @@ -233,7 +239,7 @@ static void ImageSampling() { MTLTextureDescriptor* descriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:16 height:16 mipmapped:YES]; descriptor.textureType = arrayed ? MTLTextureType2DArray : volume ? MTLTextureType3D : MTLTextureType2D; - descriptor.arrayLength = arrayed ? 3 : 1; + descriptor.arrayLength = test.cube ? 6 : arrayed ? 3 : 1; descriptor.depth = volume ? 16 : 1; descriptor.storageMode = MTLStorageModeShared; descriptor.usage = MTLTextureUsageShaderRead; @@ -344,6 +350,74 @@ static void RawBufferBounds() { } } +static void StorageImageChannelMapping() { + constexpr uint32_t reverse = 7u | (6u << 3u) | (5u << 6u) | (4u << 9u); + const uint32_t texture_formats[] = {32, 32, 16}; + for (size_t check = 0; check < std::size(texture_formats); ++check) { + const bool sparse = check != 0; + const bool packed_16 = texture_formats[check] == 16; + Fixture f(0); + IR::ImageResource image {}; + image.resource_class = IR::ImageResourceClass::Storage; + image.numeric_class = Prospero::TextureNumericClass::Float; + image.dimension = ShaderRecompiler::Decoder::ImageDimension::Dim3D; + image.shader_swizzle = reverse; + image.written = true; + f.program.info.images.push_back(image); + f.program.bindings.descriptors.push_back({*IR::DescriptorBindingForImage(image), {0}}); + const auto handle = f.Emit(0, ValueOpcode::GetImageResource, + {Value(0u),Value(0u),Value(0u),Value(0u),Value(0u),Value(0u),Value(0u),Value(0u)}); + const auto address = f.Emit(0, ValueOpcode::MakeImageAddress, + {Value(0u),Value(0u),Value(0u),Value(0u),Value(0u),Value(0u),Value(0u), + Value(0u),Value(0u),Value(0u),Value(0u),Value(0u),Value(0u)}); + IR::MemoryInfo memory {}; + memory.kind = IR::ResourceKind::Image; + memory.dmask = sparse ? 0x5u : 0xfu; + memory.data_bits = texture_formats[check]; + memory.data_dwords = packed_16 ? 1 : sparse ? 2 : 4; + memory.image_dimension = image.dimension; + memory.image_address_components = 3; + f.program.memory_info.push_back(memory); + const auto value = f.Emit(0, ValueOpcode::CompositeConstructU32x4, { + Value(packed_16 ? 0x38003400u : std::bit_cast(0.25f)), + Value(std::bit_cast(sparse ? 0.5f : 0.375f)), + Value(std::bit_cast(0.5f)), + Value(std::bit_cast(1.0f)), + }); + f.Emit(0, ValueOpcode::ImageWrite, {handle, address, value, Value(true)}); + id function = Compile(f); + NSError* error = nil; + id pipeline = [device newComputePipelineStateWithFunction:function error:&error]; + Check(pipeline != nil, "storage image mapping pipeline failed"); + MTLTextureDescriptor* desc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float + width:1 height:1 mipmapped:NO]; + desc.textureType = MTLTextureType3D; + desc.storageMode = MTLStorageModeShared; + desc.usage = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite; + id texture = [device newTextureWithDescriptor:desc]; + id args = [function newArgumentEncoderWithBufferIndex:0]; + id argbuf = [device newBufferWithLength:args.encodedLength options:MTLResourceStorageModeShared]; + [args setArgumentBuffer:argbuf offset:0]; + [args setTexture:texture atIndex:64]; + const uint32_t push[32] {}, sizes[64] {}; + id command = [[device newCommandQueue] commandBuffer]; + id encoder = [command computeCommandEncoder]; + [encoder setComputePipelineState:pipeline]; [encoder setBuffer:argbuf offset:0 atIndex:0]; + [encoder setBytes:push length:sizeof(push) atIndex:1]; [encoder setBytes:sizes length:sizeof(sizes) atIndex:25]; + [encoder useResource:texture usage:MTLResourceUsageWrite]; + [encoder dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(1,1,1)]; + [encoder endEncoding]; [command commit]; [command waitUntilCompleted]; + Check(command.status == MTLCommandBufferStatusCompleted, "storage image mapping dispatch failed"); + float result[4] {}; + [texture getBytes:result bytesPerRow:16 bytesPerImage:16 fromRegion:MTLRegionMake3D(0,0,0,1,1,1) + mipmapLevel:0 slice:0]; + const float expected[] = {sparse ? 0.0f : 1.0f, 0.5f, sparse ? 0.0f : 0.375f, 0.25f}; + Check(std::equal(std::begin(result), std::end(result), expected), + "storage image ignored inverse DST_SEL or compacted DMASK"); + } + std::puts("Storage image channel mapping: 3 GPU cases passed"); +} + static void DeclaredLds() { Fixture f; f.lds_dwords = 384; @@ -367,6 +441,95 @@ static void DeclaredLds() { std::memcpy(&actual,output.data()+8,4); Check(actual==0,"inactive LDS read did not return zero"); } +static void LargeLdsEmission() { + Fixture f; + ShaderComputeInputInfo compute {}; + compute.lds_size_dwords = 9000; + ShaderStageInputInfo input {}; + input.compute = &compute; + f.program.memory_info.push_back({.kind = IR::ResourceKind::Lds}); + f.Emit(0, ValueOpcode::WriteSharedU32, + {Value(8999u * 4), Value(0x12345678u), Value(true)}, 0); + const auto result = ShaderRecompiler::Msl::EmitProgram(f.program, input); + Check(result.success && result.source.find("kyty_lds[9000]") != std::string::npos, + "MSL silently shortened guest LDS"); + std::printf("Large LDS emission: 36000 guest bytes retained (device limit %lu)\n", + static_cast(device.maxThreadgroupMemoryLength)); +} + +static void DeviceBackedLds(bool paired = false) { + Fixture f; + f.metal_lds_limit_dwords = static_cast(device.maxThreadgroupMemoryLength / sizeof(uint32_t)); + f.lds_dwords = paired ? 16384u : f.metal_lds_limit_dwords + 1u; + f.program.wave_size = paired ? 64u : 32u; + ShaderComputeInputInfo workgroup {}; + workgroup.host_subgroup_size = 32; + workgroup.threads_num[0] = paired ? 8 : 64; + workgroup.threads_num[1] = paired ? 8 : 1; + workgroup.threads_num[2] = paired ? 16 : 1; + const uint32_t guest_threads = paired ? 1024 : 64; + const auto input = [&](IR::StageInputKind kind, uint32_t component) { + return f.Emit(0, ValueOpcode::GetBuiltin, {Value(uint32_t(kind)), Value(component)}); + }; + const auto group_x = input(IR::StageInputKind::WorkgroupId, 0); + const auto group_y = input(IR::StageInputKind::WorkgroupId, 1); + const auto group_z = input(IR::StageInputKind::WorkgroupId, 2); + const auto y = f.Emit(0, ValueOpcode::IMul32, {group_y, Value(2u)}); + const auto z = f.Emit(0, ValueOpcode::IMul32, {group_z, Value(4u)}); + const auto yz = f.Emit(0, ValueOpcode::IAdd32, {y, z}); + const auto index = f.Emit(0, ValueOpcode::IAdd32, {group_x, yz}); + const auto value = f.Emit(0, ValueOpcode::IAdd32, {index, Value(100u)}); + const auto tid = input(IR::StageInputKind::LocalInvocationIndex, 0); + const auto writer = f.Emit(0, ValueOpcode::IEqual32, {tid, Value(0u)}); + const auto reader = f.Emit(0, ValueOpcode::IEqual32, {tid, Value(guest_threads - 1u)}); + const auto word = Value((f.lds_dwords - 1u) * 4u); + const uint64_t lds = f.program.memory_info.size(); + f.program.memory_info.push_back({.kind = IR::ResourceKind::Lds}); + f.Emit(0, ValueOpcode::WriteSharedU32, {word, value, writer}, lds); + f.Emit(0, ValueOpcode::Barrier, {}); + const auto read = f.Emit(0, ValueOpcode::LoadSharedU32, {word, reader}, lds); + const auto output_offset = f.Emit(0, ValueOpcode::IMul32, {index, Value(4u)}); + const auto handle = f.Buffer(0); + f.Emit(0, ValueOpcode::StoreBufferU32, + {handle, Value(0u), output_offset, Value(0u), read, reader}, f.Memory(0)); + + id fn = Compile(f, nullptr, &workgroup); + NSError* error = nil; + id pipeline = [device newComputePipelineStateWithFunction:fn error:&error]; + if (!pipeline) std::fprintf(stderr, "%s\n", error.localizedDescription.UTF8String); + Check(pipeline != nil, "device-backed LDS pipeline failed"); + id scratch = [device newBufferWithLength:8u * f.lds_dwords * sizeof(uint32_t) + options:MTLResourceStorageModePrivate]; + id output = [device newBufferWithLength:32 options:MTLResourceStorageModeShared]; + id args = [fn newArgumentEncoderWithBufferIndex:0]; + id argbuf = [device newBufferWithLength:args.encodedLength options:MTLResourceStorageModeShared]; + [args setArgumentBuffer:argbuf offset:0]; + [args setBuffer:output offset:0 atIndex:0]; + uint32_t push[32] {}; + uint32_t sizes[64] {32}; + id queue = [device newCommandQueue]; + id command = [queue commandBuffer]; + id encoder = [command computeCommandEncoder]; + [encoder setComputePipelineState:pipeline]; + [encoder setBuffer:argbuf offset:0 atIndex:0]; + [encoder setBytes:push length:sizeof(push) atIndex:1]; + [encoder setBytes:sizes length:sizeof(sizes) atIndex:25]; + [encoder setBuffer:scratch offset:0 atIndex:ShaderRecompiler::Msl::DeviceLdsBufferIndex]; + [encoder useResource:output usage:MTLResourceUsageWrite]; + const uint32_t metal_threads = paired ? guest_threads / 2u : guest_threads; + Check(pipeline.maxTotalThreadsPerThreadgroup >= metal_threads, "device-backed LDS workgroup unsupported"); + [encoder dispatchThreadgroups:MTLSizeMake(2, 2, 2) threadsPerThreadgroup:MTLSizeMake(metal_threads, 1, 1)]; + [encoder endEncoding]; + [command commit]; + [command waitUntilCompleted]; + Check(command.status == MTLCommandBufferStatusCompleted, "device-backed LDS command failed"); + const auto* values = static_cast(output.contents); + for (uint32_t i = 0; i < 8; ++i) { + Check(values[i] == 100u + i, "device-backed LDS barrier or group isolation failed"); + } + std::printf("Device-backed LDS: final dword shared across SIMD groups in eight isolated %u-thread workgroups\n", metal_threads); +} + static void SubwordLoads() { Fixture f(2); const auto buffer = f.Buffer(0); @@ -859,7 +1022,7 @@ int main() { @autoreleasepool { try { device = MTLCreateSystemDefaultDevice(); Check(device != nil, "Metal device unavailable"); - ImageSampling(); PixelInterpolation(); LocalAppendConsume(); FloatClasses(); PackFloat2x16Rtz(); Shifts64(); FormattedStores(); RawBufferBounds(); DeclaredLds(); SubwordLoads(); GuestAddressLoads(); DualSourceOutput(); VertexReadFirstLane(); + ImageSampling(); StorageImageChannelMapping(); PixelInterpolation(); LocalAppendConsume(); FloatClasses(); PackFloat2x16Rtz(); Shifts64(); FormattedStores(); RawBufferBounds(); DeclaredLds(); SubwordLoads(); GuestAddressLoads(); DualSourceOutput(); VertexReadFirstLane(); IndirectRectList(); LoopPhiSwap(); DiamondPhi(true); DiamondPhi(false); NestedLoops(); setenv("KYTY_MSL_DISPATCHER", "1", 1); LoopPhiSwap(); DiamondPhi(true); DiamondPhi(false); NestedLoops(); diff --git a/tests/shaderCfgTests.cpp b/tests/shaderCfgTests.cpp index fae2815..4eee02e 100644 --- a/tests/shaderCfgTests.cpp +++ b/tests/shaderCfgTests.cpp @@ -10255,6 +10255,28 @@ void TestEmbeddedFetchPreservesSharedScalarLoad() { Check(MakeStageStaticKey(layout) == key, "pipeline-only vertex layout fragmented the shader module cache key"); + const auto metal_key = [](const ShaderVertexInputInfo &vertex) { + std::vector key; + BuildStageStaticKey(vertex, key, true); + return key; + }; + auto pulled = layout; + pulled.resources_dst[0].buffer_index = 0; + pulled.buffers[0].stride = 76; + auto different_stride = pulled; + different_stride.buffers[0].stride = 108; + Check(metal_key(pulled) != metal_key(different_stride), + "Metal vertex pulling reused a shader with a different stride"); + auto different_index = pulled; + different_index.buffers[0].fetch_index = 0; + Check(metal_key(pulled) != metal_key(different_index), + "Metal vertex pulling reused a shader with a different index source"); + auto moved_buffer = pulled; + moved_buffer.resources[0].UpdateAddress48(0x12340000u); + moved_buffer.buffers[0].addr = 0x12340000u; + Check(metal_key(pulled) == metal_key(moved_buffer), + "Metal vertex pulling specialized on a dynamic buffer address"); + auto formatted = input; formatted.resources[0].fields[3] = (static_cast(Prospero::BufferFormat::k32_32_32UInt) << 12u) | diff --git a/tools/build_prospero_launcher.sh b/tools/build_prospero_launcher.sh new file mode 100644 index 0000000..cc88cc3 --- /dev/null +++ b/tools/build_prospero_launcher.sh @@ -0,0 +1,32 @@ +#!/bin/bash +set -euo pipefail +root=$(cd "$(dirname "$0")/.." && pwd) +out=${1:-"$(dirname "$root")/build/kytx"} +bundle="$out/Prospero.app" +mkdir -p "$bundle/Contents/MacOS" +cat > "$bundle/Contents/Info.plist" <<'PLIST' + + + + + CFBundleExecutableProspero + CFBundleIdentifierio.github.luizdusky.prospero + CFBundleNameProspero + CFBundlePackageTypeAPPL + CFBundleShortVersionString0.1.0 + LSMinimumSystemVersion15.0 + CFBundleDocumentTypes + + CFBundleTypeNamePlayStation game package + CFBundleTypeRoleViewer + LSHandlerRankAlternate + CFBundleTypeExtensionspkgfpkg + + + +PLIST +xcrun swiftc -parse-as-library -O -target arm64-apple-macos15.0 \ + "$root/src/prospero/Prospero.swift" -o "$bundle/Contents/MacOS/Prospero" +plutil -lint "$bundle/Contents/Info.plist" +codesign --force --sign - "$bundle" +codesign --verify --strict "$bundle" diff --git a/tools/build_prospero_macos.sh b/tools/build_prospero_macos.sh new file mode 100644 index 0000000..ff4ff43 --- /dev/null +++ b/tools/build_prospero_macos.sh @@ -0,0 +1,46 @@ +#!/bin/bash +set -euo pipefail + +source_dir=$(cd "$(dirname "$0")/.." && pwd) +fex_dir=${KYTY_FEX_DIR:-"$(dirname "$source_dir")/fexcore"} +build_root=${1:-"$(dirname "$source_dir")/build"} +jobs=${CMAKE_BUILD_PARALLEL_LEVEL:-4} +fex_revision=eee10cc54a173e79ee16e2169cd4157c7269921b +fex_patch="$source_dir/docs/bringup/fexcore-optional-snapshot.patch" + +if [[ $(uname -s) != Darwin || $(uname -m) != arm64 ]]; then + echo "Use a native arm64 shell on macOS." >&2 + exit 1 +fi +if [[ $(git -C "$fex_dir" rev-parse HEAD 2>/dev/null) != "$fex_revision" ]]; then + echo "The build requires FEXCore $fex_revision at $fex_dir." >&2 + exit 1 +fi +if ! git -C "$fex_dir" apply --reverse --check --unidiff-zero "$fex_patch" 2>/dev/null; then + git -C "$fex_dir" apply --check --unidiff-zero "$fex_patch" + git -C "$fex_dir" apply --unidiff-zero "$fex_patch" +fi + +xcodebuild -version +cmake --version +ninja --version +git -C "$source_dir" rev-parse HEAD +git -C "$source_dir" submodule update --init +mkdir -p "$build_root" +build_root=$(cd "$build_root" && pwd) +fex_dir=$(cd "$fex_dir" && pwd) + +cmake -S "$fex_dir" -B "$build_root/fex" -G Ninja \ + -DBUILD_FEXCORE_ONLY=ON -DBUILD_FEXCORE_SMOKE=OFF -DBUILD_TESTING=OFF \ + -DTUNE_CPU=none -DENABLE_LTO=OFF -DENABLE_JEMALLOC_GLIBC_ALLOC=OFF \ + -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON +cmake --build "$build_root/fex" --parallel "$jobs" + +cmake -S "$source_dir" -B "$build_root/kytx" -G Ninja \ + -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_BUILD_TYPE=Release \ + -DKYTY_BUILD_LAUNCHER=OFF -DKYTY_FEX_DIR="$fex_dir" \ + -DKYTY_FEX_BUILD_DIR="$build_root/fex" -DKYTY_FEX_SHIMS_DIR="$fex_dir" +cmake --build "$build_root/kytx" --target kyty_emulator --parallel "$jobs" +file "$build_root/kytx/kyty_emulator" +codesign --verify "$build_root/kytx/kyty_emulator" diff --git a/tools/test_metal_msl.sh b/tools/test_metal_msl.sh index f44def8..03f4928 100644 --- a/tools/test_metal_msl.sh +++ b/tools/test_metal_msl.sh @@ -1,10 +1,11 @@ #!/bin/bash set -euo pipefail repo_dir=$(cd "$(dirname "$0")/.." && pwd) -test_dir=$(mktemp -d "${TMPDIR:-/tmp}/kytx-msl-test.XXXXXX") +build_dir=$(cd "${1:-$repo_dir/_Build/macos-arm64}" && pwd) +test_dir=$(mktemp -d "$build_dir/.metal-msl-test.XXXXXX") trap 'rm -rf "$test_dir"' EXIT ir_dir="$repo_dir/src/graphics/shader/recompiler/ir" -xcrun clang++ -std=c++20 -fobjc-arc -I"$repo_dir/src" -I"$repo_dir/_Build/macos-arm64" \ +xcrun clang++ -std=c++20 -fobjc-arc -I"$repo_dir/src" -I"$build_dir" \ -I"$repo_dir/3rdparty/fmt/include" -I"$repo_dir/3rdparty/magic_enum/include/magic_enum" \ "$repo_dir/tests/metalMslTests.mm" \ "$repo_dir/src/graphics/shader/recompiler/backend/msl/MslEmitter.cpp" \ @@ -13,6 +14,6 @@ xcrun clang++ -std=c++20 -fobjc-arc -I"$repo_dir/src" -I"$repo_dir/_Build/macos- "$repo_dir/src/graphics/shader/shaderPixelParameter.cpp" \ "$ir_dir/Block.cpp" "$ir_dir/Program.cpp" "$ir_dir/Type.cpp" "$ir_dir/Value.cpp" \ "$ir_dir/opcodes/ValueOpcodes.cpp" "$ir_dir/passes/BindingLayout.cpp" \ - "$repo_dir/_Build/macos-arm64/3rdparty/fmt/libfmt.a" \ + "$build_dir/3rdparty/fmt/libfmt.a" \ -Wl,-dead_strip -framework Metal -framework Foundation -o "$test_dir/metalMslTests" "$test_dir/metalMslTests"