diff options
| author | Claude <noreply@anthropic.com> | 2026-11-29 19:18:03 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-29 19:18:03 +0000 |
| commit | f61e5e89333aa18a1ca894e54da38d5460f7cee2 (patch) | |
| tree | ba590eaad8b20cefbfd0a6ebdc782cdba2ba5bf3 /runtime/src | |
| parent | ee27e871966c01d59c0cbc36468fa7f7cf51f33f (diff) | |
| parent | dd87aa405a0d48cbce4269c9d20e50c3ec8b5dbc (diff) | |
Merge ProjectLeonida/mandy main into port/nv-vram-target-reserve-settle
# Conflicts:
# d3d12/README.md
Diffstat (limited to 'runtime/src')
| -rw-r--r-- | runtime/src/address_binding.h | 303 | ||||
| -rw-r--r-- | runtime/src/assert_skip.h | 151 | ||||
| -rw-r--r-- | runtime/src/command_list.h | 18 | ||||
| -rw-r--r-- | runtime/src/descriptor_table.h | 36 | ||||
| -rw-r--r-- | runtime/src/dev_status.h | 4 | ||||
| -rw-r--r-- | runtime/src/gfx10_descriptors.h | 32 | ||||
| -rw-r--r-- | runtime/src/indirect_draw_stats.h | 7 | ||||
| -rw-r--r-- | runtime/src/main.cpp | 12 | ||||
| -rw-r--r-- | runtime/src/pe_loader.cpp | 9 | ||||
| -rw-r--r-- | runtime/src/pipeline_wait.h | 5 | ||||
| -rw-r--r-- | runtime/src/quad_index_expand.h | 74 | ||||
| -rw-r--r-- | runtime/src/queue_families.h | 19 | ||||
| -rw-r--r-- | runtime/src/shader_library.h | 39 | ||||
| -rw-r--r-- | runtime/src/spirv_words.h | 16 | ||||
| -rw-r--r-- | runtime/src/uav_clear.h | 118 | ||||
| -rw-r--r-- | runtime/src/vulkan_backend.h | 5 | ||||
| -rw-r--r-- | runtime/src/vulkan_device_fault.h | 21 | ||||
| -rw-r--r-- | runtime/src/vulkan_indirect_dispatch_count.h | 141 | ||||
| -rw-r--r-- | runtime/src/vulkan_memory.h | 24 | ||||
| -rw-r--r-- | runtime/src/vulkan_predicate.h | 173 | ||||
| -rw-r--r-- | runtime/src/vulkan_predicated_copy.h | 97 | ||||
| -rw-r--r-- | runtime/src/vulkan_replay.h | 210 |
22 files changed, 1241 insertions, 273 deletions
diff --git a/runtime/src/address_binding.h b/runtime/src/address_binding.h new file mode 100644 index 000000000..b8c54e18b --- /dev/null +++ b/runtime/src/address_binding.h | |||
| @@ -0,0 +1,303 @@ | |||
| 1 | #pragma once | ||
| 2 | // LEONIDA_ADDRESS_BINDINGS=1, with LEONIDA_DEVICE_FAULT=1: names what the driver had bound at a device-fault address | ||
| 3 | // (RT-FAULT-ADDRESS-OWNER). VK_EXT_device_address_binding_report has the driver report the GPU virtual address range | ||
| 4 | // of every buffer, image and allocation as it is bound and unbound, to the instance's debug messengers. This keeps | ||
| 5 | // the live ranges and the most recent unbound ones, so the device-fault report (vulkan_device_fault.h) can say which | ||
| 6 | // object contains a faulting address, which objects end right below it and start right above it, and which objects | ||
| 7 | // held it before. An address that none of them covers is a GPU address no object of this device was ever given. | ||
| 8 | // | ||
| 9 | // The record and the report are pure (record_binding, report); the Vulkan side is install_messenger before | ||
| 10 | // vkCreateDevice's bindings start and enable_device on the device's create chain. | ||
| 11 | |||
| 12 | #include <vulkan/vulkan.h> | ||
| 13 | |||
| 14 | #include <algorithm> | ||
| 15 | #include <atomic> | ||
| 16 | #include <chrono> | ||
| 17 | #include <cinttypes> | ||
| 18 | #include <cstdint> | ||
| 19 | #include <cstdio> | ||
| 20 | #include <cstdlib> | ||
| 21 | #include <cstring> | ||
| 22 | #include <deque> | ||
| 23 | #include <map> | ||
| 24 | #include <mutex> | ||
| 25 | #include <span> | ||
| 26 | #include <string> | ||
| 27 | #include <vector> | ||
| 28 | |||
| 29 | namespace leonida::address_binding { | ||
| 30 | |||
| 31 | struct Entry { | ||
| 32 | std::uint64_t base = 0, size = 0; | ||
| 33 | VkObjectType type = VK_OBJECT_TYPE_UNKNOWN; | ||
| 34 | std::uint64_t handle = 0; | ||
| 35 | bool internal = false; // VK_DEVICE_ADDRESS_BINDING_INTERNAL_OBJECT_BIT_EXT | ||
| 36 | double bound_at = 0, unbound_at = 0; // seconds since the record started; unbound_at 0 while live | ||
| 37 | }; | ||
| 38 | |||
| 39 | class Record { | ||
| 40 | public: | ||
| 41 | static constexpr std::size_t kept_unbound = 16384; | ||
| 42 | |||
| 43 | // One report: bound, or unbound (matched to its live entry by base, handle and size). | ||
| 44 | void record(Entry e, bool bind, double now) { | ||
| 45 | std::lock_guard lock(mutex_); | ||
| 46 | if (bind) { | ||
| 47 | e.bound_at = now; | ||
| 48 | live_.emplace(e.base, e); | ||
| 49 | ++binds_; | ||
| 50 | return; | ||
| 51 | } | ||
| 52 | ++unbinds_; | ||
| 53 | auto [first, last] = live_.equal_range(e.base); | ||
| 54 | for (auto it = first; it != last; ++it) { | ||
| 55 | if (it->second.handle != e.handle || it->second.size != e.size) continue; | ||
| 56 | e = it->second; | ||
| 57 | live_.erase(it); | ||
| 58 | break; | ||
| 59 | } | ||
| 60 | e.unbound_at = now; | ||
| 61 | unbound_.push_back(e); | ||
| 62 | if (unbound_.size() > kept_unbound) unbound_.pop_front(); | ||
| 63 | } | ||
| 64 | |||
| 65 | // What was bound at and around the `precision`-sized page of `address`, one line per finding. | ||
| 66 | std::string report(std::uint64_t address, std::uint64_t precision) const { | ||
| 67 | std::lock_guard lock(mutex_); | ||
| 68 | std::string out; | ||
| 69 | char line[160]; | ||
| 70 | std::snprintf(line, sizeof line, "0x%" PRIx64 " (precision 0x%" PRIx64 "): %" PRIu64 " binds, %" PRIu64 | ||
| 71 | " unbinds, %zu live\n", | ||
| 72 | address, precision, binds_, unbinds_, live_.size()); | ||
| 73 | out += line; | ||
| 74 | const std::uint64_t lo = precision > 1 ? address & ~(precision - 1) : address; | ||
| 75 | const std::uint64_t hi = lo + (precision > 1 ? precision : 1); | ||
| 76 | const auto overlaps = [&](const Entry& e) { return e.base < hi && e.base + e.size > lo; }; | ||
| 77 | int containing = 0; | ||
| 78 | const Entry* below = nullptr; | ||
| 79 | const Entry* above = nullptr; | ||
| 80 | // "containing" only for an object the address itself is in; one that shares only the reported page with it is | ||
| 81 | // "on the page", since the driver gives the fault address no closer than `precision`. | ||
| 82 | const auto inside = [&](const Entry& e) { return address >= e.base && address - e.base < e.size; }; | ||
| 83 | for (const auto& [base, e] : live_) { | ||
| 84 | if (overlaps(e)) { | ||
| 85 | if (containing++ < 16) out += describe(inside(e) ? "live, containing" : "live, on the page", e, address); | ||
| 86 | continue; | ||
| 87 | } | ||
| 88 | if (base + e.size <= lo && (!below || base + e.size > below->base + below->size)) below = &e; | ||
| 89 | if (base >= hi && (!above || base < above->base)) above = &e; | ||
| 90 | } | ||
| 91 | if (below) out += describe("live, nearest below", *below, address); | ||
| 92 | if (above) out += describe("live, nearest above", *above, address); | ||
| 93 | int held = 0; | ||
| 94 | for (auto it = unbound_.rbegin(); it != unbound_.rend() && held < 16; ++it) | ||
| 95 | if (overlaps(*it)) { | ||
| 96 | out += describe(inside(*it) ? "unbound, held it" : "unbound, held the page", *it, address); | ||
| 97 | ++held; | ||
| 98 | } | ||
| 99 | if (!containing && !held) out += " nothing live or recently unbound there\n"; | ||
| 100 | return out; | ||
| 101 | } | ||
| 102 | |||
| 103 | private: | ||
| 104 | static const char* type_name(VkObjectType t) { | ||
| 105 | switch (t) { | ||
| 106 | case VK_OBJECT_TYPE_BUFFER: return "buffer"; | ||
| 107 | case VK_OBJECT_TYPE_IMAGE: return "image"; | ||
| 108 | case VK_OBJECT_TYPE_DEVICE_MEMORY: return "memory"; | ||
| 109 | case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_KHR: return "acceleration structure"; | ||
| 110 | case VK_OBJECT_TYPE_COMMAND_BUFFER: return "command buffer"; | ||
| 111 | case VK_OBJECT_TYPE_PIPELINE: return "pipeline"; | ||
| 112 | case VK_OBJECT_TYPE_QUERY_POOL: return "query pool"; | ||
| 113 | case VK_OBJECT_TYPE_DESCRIPTOR_POOL: return "descriptor pool"; | ||
| 114 | default: return "object"; | ||
| 115 | } | ||
| 116 | } | ||
| 117 | |||
| 118 | static std::string describe(const char* what, const Entry& e, std::uint64_t address) { | ||
| 119 | const std::uint64_t end = e.base + e.size; | ||
| 120 | const char* relation; | ||
| 121 | std::uint64_t distance; | ||
| 122 | if (address >= e.base && address < end) { | ||
| 123 | relation = "into"; | ||
| 124 | distance = address - e.base; | ||
| 125 | } else if (address >= end) { | ||
| 126 | relation = "past the end of"; | ||
| 127 | distance = address - end; | ||
| 128 | } else { | ||
| 129 | relation = "before"; | ||
| 130 | distance = e.base - address; | ||
| 131 | } | ||
| 132 | char line[320]; | ||
| 133 | std::snprintf(line, sizeof line, | ||
| 134 | " %s: %s%s 0x%" PRIx64 "..0x%" PRIx64 " (%" PRIu64 " KiB) handle 0x%" PRIx64 | ||
| 135 | " bound at %.1f s%s; the address is 0x%" PRIx64 " %s it\n", | ||
| 136 | what, type_name(e.type), e.internal ? " (driver-internal)" : "", e.base, end, e.size >> 10, | ||
| 137 | e.handle, e.bound_at, e.unbound_at ? (", unbound at " + std::to_string(e.unbound_at) + " s").c_str() : "", | ||
| 138 | distance, relation); | ||
| 139 | return line; | ||
| 140 | } | ||
| 141 | |||
| 142 | mutable std::mutex mutex_; | ||
| 143 | std::multimap<std::uint64_t, Entry> live_; // by base address | ||
| 144 | std::deque<Entry> unbound_; // the most recent last | ||
| 145 | std::uint64_t binds_ = 0, unbinds_ = 0; | ||
| 146 | }; | ||
| 147 | |||
| 148 | struct State { | ||
| 149 | std::mutex install; // the messenger fields below; the record has a lock of its own | ||
| 150 | Record record; | ||
| 151 | std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); | ||
| 152 | VkPhysicalDeviceAddressBindingReportFeaturesEXT feature{ | ||
| 153 | VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ADDRESS_BINDING_REPORT_FEATURES_EXT}; | ||
| 154 | VkDebugUtilsMessengerEXT messenger = VK_NULL_HANDLE; | ||
| 155 | VkInstance messenger_instance = VK_NULL_HANDLE; | ||
| 156 | PFN_vkDestroyDebugUtilsMessengerEXT destroy_messenger = nullptr; | ||
| 157 | // A device enabled the report and this process's messenger records it. Read at a device fault on whatever thread | ||
| 158 | // notices it, so atomic. | ||
| 159 | std::atomic<bool> on{false}; | ||
| 160 | }; | ||
| 161 | |||
| 162 | inline State& state() { | ||
| 163 | static State s; | ||
| 164 | return s; | ||
| 165 | } | ||
| 166 | |||
| 167 | inline bool requested() { | ||
| 168 | const char* v = std::getenv("LEONIDA_ADDRESS_BINDINGS"); | ||
| 169 | return v && v[0] == '1' && !v[1]; | ||
| 170 | } | ||
| 171 | |||
| 172 | inline VKAPI_ATTR VkBool32 VKAPI_CALL on_message(VkDebugUtilsMessageSeverityFlagBitsEXT, | ||
| 173 | VkDebugUtilsMessageTypeFlagsEXT types, | ||
| 174 | const VkDebugUtilsMessengerCallbackDataEXT* data, void*) { | ||
| 175 | if (!(types & VK_DEBUG_UTILS_MESSAGE_TYPE_DEVICE_ADDRESS_BINDING_BIT_EXT) || !data) return VK_FALSE; | ||
| 176 | const VkDeviceAddressBindingCallbackDataEXT* binding = nullptr; | ||
| 177 | for (auto* p = static_cast<const VkBaseInStructure*>(data->pNext); p; p = p->pNext) | ||
| 178 | if (p->sType == VK_STRUCTURE_TYPE_DEVICE_ADDRESS_BINDING_CALLBACK_DATA_EXT) | ||
| 179 | binding = reinterpret_cast<const VkDeviceAddressBindingCallbackDataEXT*>(p); | ||
| 180 | if (!binding) return VK_FALSE; | ||
| 181 | State& s = state(); | ||
| 182 | Entry e; | ||
| 183 | e.base = binding->baseAddress; | ||
| 184 | e.size = binding->size; | ||
| 185 | e.internal = (binding->flags & VK_DEVICE_ADDRESS_BINDING_INTERNAL_OBJECT_BIT_EXT) != 0; | ||
| 186 | if (data->objectCount && data->pObjects) { | ||
| 187 | e.type = data->pObjects[0].objectType; | ||
| 188 | e.handle = data->pObjects[0].objectHandle; | ||
| 189 | } | ||
| 190 | const double now = std::chrono::duration<double>(std::chrono::steady_clock::now() - s.start).count(); | ||
| 191 | s.record.record(e, binding->bindingType == VK_DEVICE_ADDRESS_BINDING_TYPE_BIND_EXT, now); | ||
| 192 | return VK_FALSE; | ||
| 193 | } | ||
| 194 | |||
| 195 | // Before vkCreateDevice: adds the extension and its feature to `device`'s chain when the device has them and | ||
| 196 | // `instance` has this process's messenger. Without the messenger nothing would record the reports, so the device is | ||
| 197 | // left as it is and a fault report says the bindings were not recorded. | ||
| 198 | inline bool enable_device(VkInstance instance, VkPhysicalDevice physical, PFN_vkGetPhysicalDeviceFeatures2 query, | ||
| 199 | std::span<const VkExtensionProperties> advertised, std::vector<const char*>& extensions, | ||
| 200 | VkDeviceCreateInfo& device) { | ||
| 201 | if (!requested() || !query) return false; | ||
| 202 | { | ||
| 203 | State& s = state(); | ||
| 204 | std::lock_guard lock(s.install); | ||
| 205 | if (!s.messenger || s.messenger_instance != instance) { | ||
| 206 | std::fprintf(stderr, "[rt] address-binding: no messenger on this device's instance; bindings are not " | ||
| 207 | "recorded\n"); | ||
| 208 | return false; | ||
| 209 | } | ||
| 210 | } | ||
| 211 | const bool has = std::any_of(advertised.begin(), advertised.end(), [](const auto& e) { | ||
| 212 | return std::strcmp(e.extensionName, VK_EXT_DEVICE_ADDRESS_BINDING_REPORT_EXTENSION_NAME) == 0; | ||
| 213 | }); | ||
| 214 | State& s = state(); | ||
| 215 | if (!has) { | ||
| 216 | std::fprintf(stderr, "[rt] address-binding: the device has no VK_EXT_device_address_binding_report\n"); | ||
| 217 | return false; | ||
| 218 | } | ||
| 219 | s.feature.pNext = nullptr; | ||
| 220 | VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &s.feature}; | ||
| 221 | query(physical, &features); | ||
| 222 | if (!s.feature.reportAddressBinding) { | ||
| 223 | std::fprintf(stderr, "[rt] address-binding: reportAddressBinding is not supported\n"); | ||
| 224 | return false; | ||
| 225 | } | ||
| 226 | extensions.push_back(VK_EXT_DEVICE_ADDRESS_BINDING_REPORT_EXTENSION_NAME); | ||
| 227 | s.feature.pNext = const_cast<void*>(device.pNext); | ||
| 228 | device.pNext = &s.feature; | ||
| 229 | s.on = true; | ||
| 230 | return true; | ||
| 231 | } | ||
| 232 | |||
| 233 | // After vkCreateInstance with VK_EXT_debug_utils and before vkCreateDevice: bindings reach the instance's messengers | ||
| 234 | // as they happen. | ||
| 235 | inline void install_messenger(VkInstance instance, PFN_vkGetInstanceProcAddr get) { | ||
| 236 | if (!requested() || !instance || !get) return; | ||
| 237 | const auto create = | ||
| 238 | reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(get(instance, "vkCreateDebugUtilsMessengerEXT")); | ||
| 239 | if (!create) { | ||
| 240 | std::fprintf(stderr, "[rt] address-binding: no vkCreateDebugUtilsMessengerEXT\n"); | ||
| 241 | return; | ||
| 242 | } | ||
| 243 | VkDebugUtilsMessengerCreateInfoEXT info{VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; | ||
| 244 | info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | | ||
| 245 | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; | ||
| 246 | info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_DEVICE_ADDRESS_BINDING_BIT_EXT; | ||
| 247 | info.pfnUserCallback = &on_message; | ||
| 248 | State& s = state(); | ||
| 249 | std::lock_guard lock(s.install); | ||
| 250 | // One record per process: a second instance (a second device in one process) would mix its GPU addresses with | ||
| 251 | // the first's, and overwriting the handle would leave the first messenger alive past its instance. So the | ||
| 252 | // second one is refused, and its device is not enabled. | ||
| 253 | if (s.messenger) { | ||
| 254 | std::fprintf(stderr, "[rt] address-binding: a messenger is already installed for another instance; this " | ||
| 255 | "instance's bindings are not recorded\n"); | ||
| 256 | return; | ||
| 257 | } | ||
| 258 | VkDebugUtilsMessengerEXT messenger = VK_NULL_HANDLE; | ||
| 259 | const VkResult r = create(instance, &info, nullptr, &messenger); | ||
| 260 | if (r == VK_SUCCESS) { | ||
| 261 | s.messenger = messenger; | ||
| 262 | s.messenger_instance = instance; | ||
| 263 | s.destroy_messenger = reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT>( | ||
| 264 | get(instance, "vkDestroyDebugUtilsMessengerEXT")); | ||
| 265 | } | ||
| 266 | std::fprintf(stderr, "[rt] address-binding: messenger %s\n", r == VK_SUCCESS ? "installed" : "failed"); | ||
| 267 | } | ||
| 268 | |||
| 269 | // Before vkDestroyInstance: a messenger may not outlive its instance. What it recorded stays. | ||
| 270 | inline void uninstall_messenger(VkInstance instance) { | ||
| 271 | State& s = state(); | ||
| 272 | std::lock_guard lock(s.install); | ||
| 273 | if (!s.messenger || s.messenger_instance != instance) return; | ||
| 274 | if (s.destroy_messenger) s.destroy_messenger(instance, s.messenger, nullptr); | ||
| 275 | s.messenger = VK_NULL_HANDLE; | ||
| 276 | s.messenger_instance = VK_NULL_HANDLE; | ||
| 277 | s.destroy_messenger = nullptr; | ||
| 278 | s.on = false; | ||
| 279 | } | ||
| 280 | |||
| 281 | // At a device fault: what the driver had bound at and around `address`, on stderr. | ||
| 282 | inline void describe(std::uint64_t address, std::uint64_t precision) { | ||
| 283 | State& s = state(); | ||
| 284 | if (!s.on) { | ||
| 285 | // Asked for but not recording: say so, rather than leave a report that reads as "no object there". | ||
| 286 | if (requested()) | ||
| 287 | std::fprintf(stderr, "[rt] address-binding: 0x%" PRIx64 ": bindings were not recorded for this device (no " | ||
| 288 | "messenger or no VK_EXT_device_address_binding_report; see the address-binding " | ||
| 289 | "lines at startup)\n", address); | ||
| 290 | return; | ||
| 291 | } | ||
| 292 | const std::string text = s.record.report(address, precision); | ||
| 293 | std::size_t at = 0; | ||
| 294 | while (at < text.size()) { | ||
| 295 | const std::size_t end = text.find('\n', at); | ||
| 296 | std::fprintf(stderr, "[rt] address-binding: %.*s\n", int((end == std::string::npos ? text.size() : end) - at), | ||
| 297 | text.c_str() + at); | ||
| 298 | if (end == std::string::npos) break; | ||
| 299 | at = end + 1; | ||
| 300 | } | ||
| 301 | } | ||
| 302 | |||
| 303 | } // namespace leonida::address_binding | ||
diff --git a/runtime/src/assert_skip.h b/runtime/src/assert_skip.h new file mode 100644 index 000000000..9565d8dbd --- /dev/null +++ b/runtime/src/assert_skip.h | |||
| @@ -0,0 +1,151 @@ | |||
| 1 | #pragma once | ||
| 2 | |||
| 3 | // LEONIDA_SKIP_ASSERTS=N (diagnostic, off by default): step over up to N int3 breakpoints in guest code. | ||
| 4 | // | ||
| 5 | // A title's assert ends in an int3 (0xCC). With a debugger attached that is a stop to look at; without one it is an | ||
| 6 | // unhandled EXCEPTION_BREAKPOINT and the run ends there. gta6rt installs this vectored handler when the variable is a | ||
| 7 | // number above 0 (main.cpp, before any image code runs). For an EXCEPTION_BREAKPOINT whose address is in no host | ||
| 8 | // module (the Windows loader knows none at that address: the mapped game images, or code a title wrote itself) and | ||
| 9 | // whose byte there is 0xCC, it logs one line, moves RIP past the int3 and continues; after N of them it stops doing so, | ||
| 10 | // says so once, and the next int3 ends the run as before. An int3 in a host module (gta6rt, its shims, a system DLL, | ||
| 11 | // DbgBreakPoint) is never stepped over. | ||
| 12 | // | ||
| 13 | // RIP: on Windows x64 an int3's ExceptionAddress and the context's RIP both name the 0xCC (the kernel backs RIP up | ||
| 14 | // over it), and Wine reports the same; the handler also takes a RIP one past the 0xCC, which it leaves as it is. | ||
| 15 | // Any other RIP is not this int3's, and the exception is passed on. | ||
| 16 | // | ||
| 17 | // Unlike LEONIDA_SKIP_INT3 (startup_trace.h), it needs no --trace, counts every int3 rather than each address once, | ||
| 18 | // and stops after N, so a loop of asserts can't spin forever. With --trace each skip is also an `int3_skipped` event, | ||
| 19 | // and the trace's own handler, which runs first, records the exception and its stack. The handler is added last, so | ||
| 20 | // every other vectored handler sees the breakpoint first. Each skipped address is a finding, not a fix: a correct run | ||
| 21 | // reaches none. | ||
| 22 | // | ||
| 23 | // The log lines quote addresses as module+RVA only; they stay on the player's machine like the startup trace does. | ||
| 24 | |||
| 25 | #include <windows.h> | ||
| 26 | |||
| 27 | #include <atomic> | ||
| 28 | #include <cerrno> | ||
| 29 | #include <cstdint> | ||
| 30 | #include <cstdio> | ||
| 31 | #include <cwchar> | ||
| 32 | #include <string> | ||
| 33 | |||
| 34 | #include "../shims/shims.h" | ||
| 35 | #include "../shims/startup_trace.h" | ||
| 36 | |||
| 37 | namespace rt::assert_skip { | ||
| 38 | |||
| 39 | inline constexpr wchar_t kVariable[] = L"LEONIDA_SKIP_ASSERTS"; | ||
| 40 | // Far above any useful count; it only keeps the number in an unsigned. | ||
| 41 | inline constexpr unsigned long kMaxLimit = 1000000; | ||
| 42 | |||
| 43 | // The limit LEONIDA_SKIP_ASSERTS asks for: 0 when the text is null or empty, "0", or not a decimal number in | ||
| 44 | // 0..kMaxLimit (then `*valid`, when given, is false). | ||
| 45 | inline unsigned parse_limit(const wchar_t* text, bool* valid = nullptr) { | ||
| 46 | if (valid) *valid = true; | ||
| 47 | if (!text || !*text) return 0; | ||
| 48 | if (*text < L'0' || *text > L'9') { // no sign, no leading space: wcstoul would take "-1" as ULONG_MAX | ||
| 49 | if (valid) *valid = false; | ||
| 50 | return 0; | ||
| 51 | } | ||
| 52 | errno = 0; | ||
| 53 | wchar_t* end = nullptr; | ||
| 54 | const unsigned long n = std::wcstoul(text, &end, 10); | ||
| 55 | if (errno != 0 || !end || *end != L'\0' || n > kMaxLimit) { | ||
| 56 | if (valid) *valid = false; | ||
| 57 | return 0; | ||
| 58 | } | ||
| 59 | return static_cast<unsigned>(n); | ||
| 60 | } | ||
| 61 | |||
| 62 | // LEONIDA_SKIP_ASSERTS as a limit; a value that is not one is reported on stderr and counts as 0 (off). | ||
| 63 | inline unsigned limit_from_environment() { | ||
| 64 | wchar_t value[32] = {}; | ||
| 65 | const DWORD length = GetEnvironmentVariableW(kVariable, value, 32); | ||
| 66 | if (length == 0) return 0; | ||
| 67 | bool valid = false; | ||
| 68 | const unsigned limit = length < 32 ? parse_limit(value, &valid) : 0; | ||
| 69 | if (length >= 32 || !valid) | ||
| 70 | std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: expected a number of int3 to step over (0..%lu); off\n", | ||
| 71 | kMaxLimit); | ||
| 72 | return limit; | ||
| 73 | } | ||
| 74 | |||
| 75 | namespace detail { | ||
| 76 | inline std::atomic<unsigned> limit{0}; | ||
| 77 | inline std::atomic<unsigned> claimed{0}; // skips handed out, may pass `limit` by the declined ones | ||
| 78 | inline std::atomic<bool> exhausted_logged{false}; | ||
| 79 | inline void* veh = nullptr; | ||
| 80 | |||
| 81 | // True when the Windows loader knows a module at `address`: gta6rt, its DLLs, system DLLs. The Loader's mapped | ||
| 82 | // images are not among them. | ||
| 83 | inline bool in_host_module(const void* address) { | ||
| 84 | HMODULE module = nullptr; | ||
| 85 | return GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, | ||
| 86 | static_cast<LPCWSTR>(address), &module) && module; | ||
| 87 | } | ||
| 88 | |||
| 89 | // The byte at `address`, read only when the page is committed and readable. | ||
| 90 | inline bool read_byte(const void* address, unsigned char& byte) { | ||
| 91 | MEMORY_BASIC_INFORMATION mbi{}; | ||
| 92 | if (!address || !VirtualQuery(address, &mbi, sizeof mbi) || mbi.State != MEM_COMMIT) return false; | ||
| 93 | if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return false; | ||
| 94 | const DWORD readable = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | | ||
| 95 | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; | ||
| 96 | if (!(mbi.Protect & readable)) return false; | ||
| 97 | byte = *static_cast<const unsigned char*>(address); | ||
| 98 | return true; | ||
| 99 | } | ||
| 100 | |||
| 101 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | ||
| 102 | if (!info || !info->ExceptionRecord || !info->ContextRecord) return EXCEPTION_CONTINUE_SEARCH; | ||
| 103 | const EXCEPTION_RECORD& r = *info->ExceptionRecord; | ||
| 104 | if (r.ExceptionCode != EXCEPTION_BREAKPOINT) return EXCEPTION_CONTINUE_SEARCH; | ||
| 105 | const unsigned max = limit.load(std::memory_order_relaxed); | ||
| 106 | if (max == 0) return EXCEPTION_CONTINUE_SEARCH; | ||
| 107 | const void* at = r.ExceptionAddress; | ||
| 108 | const auto at_word = reinterpret_cast<DWORD64>(at); | ||
| 109 | CONTEXT& c = *info->ContextRecord; | ||
| 110 | if (c.Rip != at_word && c.Rip != at_word + 1) return EXCEPTION_CONTINUE_SEARCH; // not this int3's RIP | ||
| 111 | unsigned char byte = 0; | ||
| 112 | if (in_host_module(at) || !read_byte(at, byte) || byte != 0xCC) return EXCEPTION_CONTINUE_SEARCH; | ||
| 113 | const unsigned n = claimed.fetch_add(1, std::memory_order_relaxed) + 1; | ||
| 114 | if (n > max) { | ||
| 115 | if (!exhausted_logged.exchange(true, std::memory_order_relaxed)) | ||
| 116 | std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: %u int3 stepped over; the one at %s is not\n", max, | ||
| 117 | shims::module_offset(at_word).c_str()); | ||
| 118 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 119 | } | ||
| 120 | const std::string where = shims::module_offset(at_word); | ||
| 121 | std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: int3 at %s stepped over (%u of %u)\n", where.c_str(), n, max); | ||
| 122 | std::fflush(stderr); | ||
| 123 | startup_trace::event("int3_skipped", "\"at\":" + startup_trace::quote(where) + ",\"skip\":" + std::to_string(n)); | ||
| 124 | if (c.Rip == at_word) c.Rip = at_word + 1; | ||
| 125 | return EXCEPTION_CONTINUE_EXECUTION; | ||
| 126 | } | ||
| 127 | } // namespace detail | ||
| 128 | |||
| 129 | // Steps over up to `limit` guest int3 from now on (0 removes the handler). Returns false only when the handler could | ||
| 130 | // not be added. Called once, from main.cpp; tests call it again to start over. | ||
| 131 | inline bool install(unsigned limit) { | ||
| 132 | detail::limit.store(0, std::memory_order_relaxed); | ||
| 133 | if (detail::veh) RemoveVectoredExceptionHandler(detail::veh); | ||
| 134 | detail::veh = nullptr; | ||
| 135 | detail::claimed.store(0, std::memory_order_relaxed); | ||
| 136 | detail::exhausted_logged.store(false, std::memory_order_relaxed); | ||
| 137 | if (limit == 0) return true; | ||
| 138 | detail::limit.store(limit, std::memory_order_relaxed); | ||
| 139 | detail::veh = AddVectoredExceptionHandler(0, &detail::handler); // last: the other handlers see it first | ||
| 140 | if (!detail::veh) detail::limit.store(0, std::memory_order_relaxed); | ||
| 141 | return detail::veh != nullptr; | ||
| 142 | } | ||
| 143 | |||
| 144 | // int3 stepped over since install. | ||
| 145 | inline unsigned skipped() { | ||
| 146 | const unsigned claimed = detail::claimed.load(std::memory_order_relaxed); | ||
| 147 | const unsigned max = detail::limit.load(std::memory_order_relaxed); | ||
| 148 | return claimed < max ? claimed : max; | ||
| 149 | } | ||
| 150 | |||
| 151 | } // namespace rt::assert_skip | ||
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 8b79c987e..48c443c18 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h | |||
| @@ -579,6 +579,20 @@ struct Predication { | |||
| 579 | std::uint32_t op; // d3d12_predication | 579 | std::uint32_t op; // d3d12_predication |
| 580 | }; | 580 | }; |
| 581 | 581 | ||
| 582 | struct SamplePosition { | ||
| 583 | std::int8_t x, y; | ||
| 584 | }; | ||
| 585 | |||
| 586 | struct SamplePositions { | ||
| 587 | std::uint32_t samples = 0; | ||
| 588 | std::uint32_t pixels = 0; | ||
| 589 | std::array<SamplePosition, 16> positions{}; | ||
| 590 | |||
| 591 | static constexpr bool valid_grid(std::uint32_t samples, std::uint32_t pixels) { | ||
| 592 | return (pixels == 1 || pixels == 4) && samples && !(samples & (samples - 1)) && samples <= 16 / pixels; | ||
| 593 | } | ||
| 594 | }; | ||
| 595 | |||
| 582 | // Query heaps are identified like resources, by the COM object's pointer value. A heap's type and size are checked | 596 | // Query heaps are identified like resources, by the COM object's pointer value. A heap's type and size are checked |
| 583 | // at replay, when the heap is known. | 597 | // at replay, when the heap is known. |
| 584 | using QueryHeapId = std::uintptr_t; | 598 | using QueryHeapId = std::uintptr_t; |
| @@ -706,7 +720,7 @@ struct AccelerationStructurePostbuild { | |||
| 706 | 720 | ||
| 707 | using Command = std::variant<TransitionBarrier, UavBarrier, AliasingBarrier, GlobalBarrier, BufferBarrier, | 721 | using Command = std::variant<TransitionBarrier, UavBarrier, AliasingBarrier, GlobalBarrier, BufferBarrier, |
| 708 | TextureBarrier, ClearRenderTarget, ClearDepthStencil, CopyBuffer, CopyTexture, | 722 | TextureBarrier, ClearRenderTarget, ClearDepthStencil, CopyBuffer, CopyTexture, |
| 709 | CopyResource, ResolveSubresource, Predication, ClearUnorderedAccess, DiscardResource, | 723 | CopyResource, ResolveSubresource, Predication, SamplePositions, ClearUnorderedAccess, DiscardResource, |
| 710 | WriteImmediate, label::Write, AtomicCopyBuffer, BeginQuery, EndQuery, ResolveQueries, DebugMarker, | 724 | WriteImmediate, label::Write, AtomicCopyBuffer, BeginQuery, EndQuery, ResolveQueries, DebugMarker, |
| 711 | ExecuteIndirect, BuildAccelerationStructure, Dispatch, Draw, CopyAccelerationStructure, | 725 | ExecuteIndirect, BuildAccelerationStructure, Dispatch, Draw, CopyAccelerationStructure, |
| 712 | AccelerationStructurePostbuild, IndirectRasterDraw>; | 726 | AccelerationStructurePostbuild, IndirectRasterDraw>; |
| @@ -901,6 +915,8 @@ public: | |||
| 901 | return true; | 915 | return true; |
| 902 | } | 916 | } |
| 903 | 917 | ||
| 918 | bool set_sample_positions(const SamplePositions& pattern) { return append(pattern); } | ||
| 919 | |||
| 904 | // SetPredication. Turning it off ignores the offset and op, as D3D12 does. | 920 | // SetPredication. Turning it off ignores the offset and op, as D3D12 does. |
| 905 | bool set_predication(const Predication& predication) { | 921 | bool set_predication(const Predication& predication) { |
| 906 | if (!predication.buffer) return append(Predication{0, 0, 0}); | 922 | if (!predication.buffer) return append(Predication{0, 0, 0}); |
diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h index 82fa19dbf..62e2c3c58 100644 --- a/runtime/src/descriptor_table.h +++ b/runtime/src/descriptor_table.h | |||
| @@ -282,10 +282,11 @@ public: | |||
| 282 | std::lock_guard lock(mutex_); | 282 | std::lock_guard lock(mutex_); |
| 283 | if (first > entries_.size() || count > entries_.size() - first) return false; | 283 | if (first > entries_.size() || count > entries_.size() - first) return false; |
| 284 | for (std::uint32_t i = 0; i < count; ++i) { | 284 | for (std::uint32_t i = 0; i < count; ++i) { |
| 285 | const DescriptorEntry& entry = entries_[first + i]; | 285 | const DescriptorEntry& entry = entries_[std::size_t(first) + i]; |
| 286 | std::memcpy(dest + i * 10, entry.key, sizeof(entry.key)); | 286 | const std::size_t base = std::size_t(i) * 10; |
| 287 | dest[i * 10 + 8] = entry.index; | 287 | std::memcpy(dest + base, entry.key, sizeof(entry.key)); |
| 288 | dest[i * 10 + 9] = entry.kind; | 288 | dest[base + 8] = entry.index; |
| 289 | dest[base + 9] = entry.kind; | ||
| 289 | } | 290 | } |
| 290 | return true; | 291 | return true; |
| 291 | } | 292 | } |
| @@ -308,7 +309,14 @@ public: | |||
| 308 | } | 309 | } |
| 309 | 310 | ||
| 310 | private: | 311 | private: |
| 311 | void mark(std::uint32_t slot) { changed_slots_.push_back(slot); } | 312 | // Reserve dirty-slot storage before mutating entries_ so OOM cannot leave CPU/GPU tables desynchronized. |
| 313 | // Once all_changed_ is set, the next upload sends the full table and per-slot tracking is skipped. | ||
| 314 | void reserve_marks(std::size_t count) { | ||
| 315 | if (!all_changed_) changed_slots_.reserve(changed_slots_.size() + count); | ||
| 316 | } | ||
| 317 | void mark(std::uint32_t slot) { | ||
| 318 | if (!all_changed_) changed_slots_.push_back(slot); | ||
| 319 | } | ||
| 312 | 320 | ||
| 313 | // All eight slots for the incoming key are occupied. Try moving one resident | 321 | // All eight slots for the incoming key are occupied. Try moving one resident |
| 314 | // to the first empty slot beyond that window, within its own eight probes. | 322 | // to the first empty slot beyond that window, within its own eight probes. |
| @@ -346,6 +354,7 @@ private: | |||
| 346 | if (std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { | 354 | if (std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { |
| 347 | if (entry.index == index && slot_kind(entry) == kind) return InsertResult::unchanged; | 355 | if (entry.index == index && slot_kind(entry) == kind) return InsertResult::unchanged; |
| 348 | // A new index or a new kind: either way the slot's copy of the entry must reach the GPU. | 356 | // A new index or a new kind: either way the slot's copy of the entry must reach the GPU. |
| 357 | reserve_marks(1); | ||
| 349 | entry.index = index; | 358 | entry.index = index; |
| 350 | entry.kind = kSlotOccupiedMarker | (kind & kKindMask); | 359 | entry.kind = kSlotOccupiedMarker | (kind & kKindMask); |
| 351 | mark(slot); | 360 | mark(slot); |
| @@ -356,13 +365,8 @@ private: | |||
| 356 | } | 365 | } |
| 357 | } | 366 | } |
| 358 | 367 | ||
| 359 | if ((occupied_count_ + 1) * 2 > entries_.size()) { | ||
| 360 | grow_locked(); | ||
| 361 | continue; | ||
| 362 | } | ||
| 363 | |||
| 364 | // Nine distinct keys with the same full hash can never fit the shader's eight probes, | 368 | // Nine distinct keys with the same full hash can never fit the shader's eight probes, |
| 365 | // regardless of capacity. Refuse before allocating ever larger tables. | 369 | // regardless of capacity. Refuse before growing or allocating ever larger tables. |
| 366 | if (empty_slot < 0) { | 370 | if (empty_slot < 0) { |
| 367 | std::uint32_t same_hash = 0; | 371 | std::uint32_t same_hash = 0; |
| 368 | for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { | 372 | for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { |
| @@ -372,7 +376,14 @@ private: | |||
| 372 | if (same_hash == kDescriptorProbes) | 376 | if (same_hash == kDescriptorProbes) |
| 373 | throw std::length_error("Descriptor hash collision exceeds shader probe limit"); | 377 | throw std::length_error("Descriptor hash collision exceeds shader probe limit"); |
| 374 | } | 378 | } |
| 379 | |||
| 380 | if ((occupied_count_ + 1) * 2 > entries_.size()) { | ||
| 381 | grow_locked(); | ||
| 382 | continue; | ||
| 383 | } | ||
| 384 | |||
| 375 | const bool relocate = empty_slot < 0; | 385 | const bool relocate = empty_slot < 0; |
| 386 | reserve_marks(relocate ? 2 : 1); | ||
| 376 | std::uint32_t moved_to = 0; | 387 | std::uint32_t moved_to = 0; |
| 377 | if (relocate) empty_slot = make_probe_slot(entries_, h, hash_kind_, &moved_to); | 388 | if (relocate) empty_slot = make_probe_slot(entries_, h, hash_kind_, &moved_to); |
| 378 | if (empty_slot >= 0) { | 389 | if (empty_slot >= 0) { |
| @@ -405,10 +416,11 @@ private: | |||
| 405 | } | 416 | } |
| 406 | if (!found) return false; | 417 | if (!found) return false; |
| 407 | 418 | ||
| 419 | reserve_marks(1); | ||
| 408 | // No backward shift: see erase(). | 420 | // No backward shift: see erase(). |
| 409 | entries_[found_slot] = DescriptorEntry{}; | 421 | entries_[found_slot] = DescriptorEntry{}; |
| 410 | mark(found_slot); | ||
| 411 | --occupied_count_; | 422 | --occupied_count_; |
| 423 | mark(found_slot); | ||
| 412 | return true; | 424 | return true; |
| 413 | } | 425 | } |
| 414 | 426 | ||
diff --git a/runtime/src/dev_status.h b/runtime/src/dev_status.h index 3efc9bf4f..ec1c5a5d9 100644 --- a/runtime/src/dev_status.h +++ b/runtime/src/dev_status.h | |||
| @@ -20,6 +20,10 @@ struct Builds { | |||
| 20 | } | 20 | } |
| 21 | void name(const char* text) { | 21 | void name(const char* text) { |
| 22 | std::lock_guard lock(mutex_); | 22 | std::lock_guard lock(mutex_); |
| 23 | if (!text) { | ||
| 24 | name_[0] = 0; | ||
| 25 | return; | ||
| 26 | } | ||
| 23 | const std::size_t n = std::min(std::strlen(text), sizeof name_ - 1); | 27 | const std::size_t n = std::min(std::strlen(text), sizeof name_ - 1); |
| 24 | std::memcpy(name_, text, n); | 28 | std::memcpy(name_, text, n); |
| 25 | name_[n] = 0; | 29 | name_[n] = 0; |
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index acfa590f8..9cbc49b75 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h | |||
| @@ -11,7 +11,7 @@ | |||
| 11 | // SQ_IMG_SAMP_WORD0..3 and SQ_BUF_RSRC_WORD0..3 types with their gfx103 variants (RDNA2). The comments below | 11 | // SQ_IMG_SAMP_WORD0..3 and SQ_BUF_RSRC_WORD0..3 types with their gfx103 variants (RDNA2). The comments below |
| 12 | // name those fields. | 12 | // name those fields. |
| 13 | // - Enum values in the fields: Mesa's gfx6.json (SQ_RSRC_IMG_TYPE, SQ_SEL_XYZW01, SQ_TEX_CLAMP, SQ_TEX_XY_FILTER, | 13 | // - Enum values in the fields: Mesa's gfx6.json (SQ_RSRC_IMG_TYPE, SQ_SEL_XYZW01, SQ_TEX_CLAMP, SQ_TEX_XY_FILTER, |
| 14 | // SQ_TEX_MIP_FILTER, SQ_TEX_DEPTH_COMPARE, SQ_TEX_BORDER_COLOR, SQ_IMG_FILTER_TYPE). | 14 | // SQ_TEX_Z_FILTER, SQ_TEX_MIP_FILTER, SQ_TEX_DEPTH_COMPARE, SQ_TEX_BORDER_COLOR, SQ_IMG_FILTER_TYPE). |
| 15 | // - Which value goes into which field: Mesa's src/amd/common/ac_descriptors.c (ac_build_gfx10_texture_descriptor, | 15 | // - Which value goes into which field: Mesa's src/amd/common/ac_descriptors.c (ac_build_gfx10_texture_descriptor, |
| 16 | // ac_build_sampler_descriptor, ac_build_buffer_descriptor) and radv's radv_image_view.c and radv_sampler.c. | 16 | // ac_build_sampler_descriptor, ac_build_buffer_descriptor) and radv's radv_image_view.c and radv_sampler.c. |
| 17 | // - Formats: the GFX10_FORMAT enum, which tools/gfx10_formats.json holds too. A format names its channel sizes | 17 | // - Formats: the GFX10_FORMAT enum, which tools/gfx10_formats.json holds too. A format names its channel sizes |
| @@ -31,6 +31,7 @@ | |||
| 31 | #include <algorithm> | 31 | #include <algorithm> |
| 32 | #include <array> | 32 | #include <array> |
| 33 | #include <bit> | 33 | #include <bit> |
| 34 | #include <cmath> | ||
| 34 | #include <cstdint> | 35 | #include <cstdint> |
| 35 | 36 | ||
| 36 | namespace leonida::gfx10 { | 37 | namespace leonida::gfx10 { |
| @@ -488,6 +489,12 @@ enum class MipFilter : std::uint32_t { // SQ_TEX_MIP_FILTER | |||
| 488 | linear = 2, | 489 | linear = 2, |
| 489 | }; | 490 | }; |
| 490 | 491 | ||
| 492 | enum class VolumeFilter : std::uint32_t { // SQ_TEX_Z_FILTER | ||
| 493 | none = 0, | ||
| 494 | point = 1, | ||
| 495 | linear = 2, | ||
| 496 | }; | ||
| 497 | |||
| 491 | enum class CompareFunction : std::uint32_t { // SQ_TEX_DEPTH_COMPARE; the same values as VkCompareOp | 498 | enum class CompareFunction : std::uint32_t { // SQ_TEX_DEPTH_COMPARE; the same values as VkCompareOp |
| 492 | never = 0, | 499 | never = 0, |
| 493 | less = 1, | 500 | less = 1, |
| @@ -534,6 +541,7 @@ struct Sampler { | |||
| 534 | // layer keeps it in the S# words, which are the sampler's key: see kIntegerBorderPtr. | 541 | // layer keeps it in the S# words, which are the sampler's key: see kIntegerBorderPtr. |
| 535 | bool integer_border = false; | 542 | bool integer_border = false; |
| 536 | bool compare_never = false; // D3D12 comparison filter with DEPTH_COMPARE_FUNC = NEVER | 543 | bool compare_never = false; // D3D12 comparison filter with DEPTH_COMPARE_FUNC = NEVER |
| 544 | VolumeFilter volume_filter = VolumeFilter::none; | ||
| 537 | bool operator==(const Sampler&) const = default; | 545 | bool operator==(const Sampler&) const = default; |
| 538 | }; | 546 | }; |
| 539 | 547 | ||
| @@ -552,7 +560,7 @@ inline constexpr std::uint32_t kCompareNever = 1u << 12; | |||
| 552 | // DEPTH_COMPARE_FUNC [14:12], FORCE_UNNORMALIZED [15], FILTER_MODE [30:29] | 560 | // DEPTH_COMPARE_FUNC [14:12], FORCE_UNNORMALIZED [15], FILTER_MODE [30:29] |
| 553 | // WORD1 MIN_LOD [11:0], MAX_LOD [23:12] (4.8 fixed, clamped to 0..15) | 561 | // WORD1 MIN_LOD [11:0], MAX_LOD [23:12] (4.8 fixed, clamped to 0..15) |
| 554 | // WORD2 LOD_BIAS [13:0] (signed 5.8 fixed, clamped to -32..31), XY_MAG_FILTER [21:20], XY_MIN_FILTER [23:22], | 562 | // WORD2 LOD_BIAS [13:0] (signed 5.8 fixed, clamped to -32..31), XY_MAG_FILTER [21:20], XY_MIN_FILTER [23:22], |
| 555 | // MIP_FILTER [27:26] | 563 | // Z_FILTER [25:24], MIP_FILTER [27:26] |
| 556 | // WORD3 BORDER_COLOR_PTR [11:0], BORDER_COLOR_TYPE [31:30] | 564 | // WORD3 BORDER_COLOR_PTR [11:0], BORDER_COLOR_TYPE [31:30] |
| 557 | // Mesa also sets tuning fields from the anisotropy (ANISO_THRESHOLD, ANISO_BIAS, PERF_MIP, ANISO_OVERRIDE) and | 565 | // Mesa also sets tuning fields from the anisotropy (ANISO_THRESHOLD, ANISO_BIAS, PERF_MIP, ANISO_OVERRIDE) and |
| 558 | // TRUNC_COORD for point filters. They are not written here, and decode() ignores them. | 566 | // TRUNC_COORD for point filters. They are not written here, and decode() ignores them. |
| @@ -569,7 +577,7 @@ inline SamplerWords encode(const Sampler& sampler) { | |||
| 569 | field(detail::unsigned_fixed(sampler.max_lod, 0, 15), 12, 12); | 577 | field(detail::unsigned_fixed(sampler.max_lod, 0, 15), 12, 12); |
| 570 | words[2] = field(detail::signed_fixed(sampler.lod_bias, -32, 31), 0, 14) | | 578 | words[2] = field(detail::signed_fixed(sampler.lod_bias, -32, 31), 0, 14) | |
| 571 | field(std::uint32_t(sampler.mag_filter), 20, 2) | field(std::uint32_t(sampler.min_filter), 22, 2) | | 579 | field(std::uint32_t(sampler.mag_filter), 20, 2) | field(std::uint32_t(sampler.min_filter), 22, 2) | |
| 572 | field(std::uint32_t(sampler.mip_filter), 26, 2); | 580 | field(std::uint32_t(sampler.volume_filter), 24, 2) | field(std::uint32_t(sampler.mip_filter), 26, 2); |
| 573 | const bool marked = sampler.integer_border && sampler.border_color != BorderColor::table; | 581 | const bool marked = sampler.integer_border && sampler.border_color != BorderColor::table; |
| 574 | words[3] = field(marked ? kIntegerBorderPtr : sampler.border_color_index, 0, 12) | | 582 | words[3] = field(marked ? kIntegerBorderPtr : sampler.border_color_index, 0, 12) | |
| 575 | field(std::uint32_t(sampler.border_color), 30, 2); | 583 | field(std::uint32_t(sampler.border_color), 30, 2); |
| @@ -598,10 +606,12 @@ inline Sampler decode(const SamplerWords& words) { | |||
| 598 | sampler.lod_bias = float(std::int32_t(bias ^ 0x2000u) - 0x2000) / 256.0f; // sign-extend 14 bits | 606 | sampler.lod_bias = float(std::int32_t(bias ^ 0x2000u) - 0x2000) / 256.0f; // sign-extend 14 bits |
| 599 | sampler.mag_filter = Filter(get(words[2], 20, 2)); | 607 | sampler.mag_filter = Filter(get(words[2], 20, 2)); |
| 600 | sampler.min_filter = Filter(get(words[2], 22, 2)); | 608 | sampler.min_filter = Filter(get(words[2], 22, 2)); |
| 609 | sampler.volume_filter = VolumeFilter(get(words[2], 24, 2)); | ||
| 601 | sampler.mip_filter = MipFilter(get(words[2], 26, 2)); | 610 | sampler.mip_filter = MipFilter(get(words[2], 26, 2)); |
| 602 | sampler.border_color_index = get(words[3], 0, 12); | 611 | sampler.border_color_index = get(words[3], 0, 12); |
| 603 | sampler.border_color = BorderColor(get(words[3], 30, 2)); | 612 | sampler.border_color = BorderColor(get(words[3], 30, 2)); |
| 604 | if (sampler.border_color != BorderColor::table && sampler.border_color_index == kIntegerBorderPtr) { | 613 | if (!deriv_adjust && sampler.border_color != BorderColor::table && |
| 614 | sampler.border_color_index == kIntegerBorderPtr) { | ||
| 605 | sampler.integer_border = true; | 615 | sampler.integer_border = true; |
| 606 | sampler.border_color_index = 0; | 616 | sampler.border_color_index = 0; |
| 607 | } | 617 | } |
| @@ -634,6 +644,7 @@ inline constexpr VkSamplerReductionMode vulkan_reduction_mode(FilterMode mode) { | |||
| 634 | // the S# only indexes (VK_EXT_custom_border_color); | 644 | // the S# only indexes (VK_EXT_custom_border_color); |
| 635 | // - filter_mode != blend: chain a VkSamplerReductionModeCreateInfo with vulkan_reduction_mode(); | 645 | // - filter_mode != blend: chain a VkSamplerReductionModeCreateInfo with vulkan_reduction_mode(); |
| 636 | // - mirror-once modes need samplerMirrorClampToEdge, anisotropy needs samplerAnisotropy. | 646 | // - mirror-once modes need samplerMirrorClampToEdge, anisotropy needs samplerAnisotropy. |
| 647 | // Vulkan applies minFilter and magFilter to all three spatial axes; the S# can specify a separate Z filter. | ||
| 637 | // MIP_FILTER_NONE samples the base level only, which Vulkan expresses as nearest mip filtering with the LOD held | 648 | // MIP_FILTER_NONE samples the base level only, which Vulkan expresses as nearest mip filtering with the LOD held |
| 638 | // in [0, 0.25] (the Vulkan specification's note on samplers without mipmapping). An unnormalised sampler gets | 649 | // in [0, 0.25] (the Vulkan specification's note on samplers without mipmapping). An unnormalised sampler gets |
| 639 | // what Vulkan requires of one: no mips, no anisotropy, no comparison. | 650 | // what Vulkan requires of one: no mips, no anisotropy, no comparison. |
| @@ -658,13 +669,20 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_ | |||
| 658 | info.addressModeU = vulkan_address_mode(sampler.address_u); | 669 | info.addressModeU = vulkan_address_mode(sampler.address_u); |
| 659 | info.addressModeV = vulkan_address_mode(sampler.address_v); | 670 | info.addressModeV = vulkan_address_mode(sampler.address_v); |
| 660 | info.addressModeW = vulkan_address_mode(sampler.address_w); | 671 | info.addressModeW = vulkan_address_mode(sampler.address_w); |
| 661 | info.mipLodBias = std::clamp(sampler.lod_bias, -max_lod_bias, max_lod_bias); | 672 | // VUID-VkSamplerCreateInfo-mipLodBias-01069: |mipLodBias| <= maxSamplerLodBias; keep non-finite inputs and |
| 673 | // non-positive limits finite without tripping std::clamp's precondition. | ||
| 674 | const float lod_bias_limit = max_lod_bias > 0.0f ? max_lod_bias : 0.0f; | ||
| 675 | const float lod_bias = std::isnan(sampler.lod_bias) ? 0.0f : sampler.lod_bias; | ||
| 676 | info.mipLodBias = lod_bias_limit == 0.0f ? 0.0f : detail::clamped(lod_bias, -lod_bias_limit, lod_bias_limit); | ||
| 662 | info.anisotropyEnable = sampler.max_anisotropy > 1 ? VK_TRUE : VK_FALSE; | 677 | info.anisotropyEnable = sampler.max_anisotropy > 1 ? VK_TRUE : VK_FALSE; |
| 663 | info.maxAnisotropy = float(std::max(sampler.max_anisotropy, 1u)); | 678 | info.maxAnisotropy = float(std::max(sampler.max_anisotropy, 1u)); |
| 664 | info.compareEnable = (sampler.compare_never || sampler.compare != CompareFunction::never) ? VK_TRUE : VK_FALSE; | 679 | info.compareEnable = (sampler.compare_never || sampler.compare != CompareFunction::never) ? VK_TRUE : VK_FALSE; |
| 665 | info.compareOp = VkCompareOp(sampler.compare); | 680 | info.compareOp = VkCompareOp(sampler.compare); |
| 666 | info.minLod = sampler.min_lod; | 681 | // VUID-VkSamplerCreateInfo-maxLod-01973: maxLod must be >= minLod. An S# (or D3D12_SAMPLER_DESC) can carry |
| 667 | info.maxLod = sampler.max_lod; | 682 | // MIN_LOD > MAX_LOD (or NaN); raise maxLod to minLod so vkCreateSampler never sees an inverted or NaN range. |
| 683 | info.minLod = std::isnan(sampler.min_lod) ? 0.0f : sampler.min_lod; | ||
| 684 | info.maxLod = std::isnan(sampler.max_lod) ? info.minLod : sampler.max_lod; | ||
| 685 | if (info.maxLod < info.minLod) info.maxLod = info.minLod; | ||
| 668 | if (sampler.mip_filter == MipFilter::none) { | 686 | if (sampler.mip_filter == MipFilter::none) { |
| 669 | info.minLod = 0.0f; | 687 | info.minLod = 0.0f; |
| 670 | info.maxLod = 0.25f; | 688 | info.maxLod = 0.25f; |
diff --git a/runtime/src/indirect_draw_stats.h b/runtime/src/indirect_draw_stats.h index 0413ae5d8..9d612459b 100644 --- a/runtime/src/indirect_draw_stats.h +++ b/runtime/src/indirect_draw_stats.h | |||
| @@ -42,6 +42,7 @@ struct Counts { | |||
| 42 | std::atomic<unsigned long long> values[4]{}; | 42 | std::atomic<unsigned long long> values[4]{}; |
| 43 | std::atomic<unsigned long long> by_reason[reason_count]{}; | 43 | std::atomic<unsigned long long> by_reason[reason_count]{}; |
| 44 | void report(std::FILE* out = stderr) const { | 44 | void report(std::FILE* out = stderr) const { |
| 45 | if (!out) return; | ||
| 45 | char line[1280]; | 46 | char line[1280]; |
| 46 | int pos = std::snprintf( | 47 | int pos = std::snprintf( |
| 47 | line, sizeof(line), | 48 | line, sizeof(line), |
| @@ -88,13 +89,15 @@ inline unsigned long long reason_skips(Reason reason) { | |||
| 88 | } | 89 | } |
| 89 | 90 | ||
| 90 | inline void note(Event event) { | 91 | inline void note(Event event) { |
| 92 | const unsigned index = static_cast<unsigned>(event); | ||
| 93 | if (index >= 4u) return; | ||
| 91 | auto& c = counts(); | 94 | auto& c = counts(); |
| 92 | const auto n = 1 + c.values[static_cast<unsigned>(event)].fetch_add(1, std::memory_order_relaxed); | 95 | const auto n = 1 + c.values[index].fetch_add(1, std::memory_order_relaxed); |
| 93 | if ((n & (n - 1)) == 0) c.report(); | 96 | if ((n & (n - 1)) == 0) c.report(); |
| 94 | } | 97 | } |
| 95 | 98 | ||
| 96 | inline void skip(Event event, Reason reason) { | 99 | inline void skip(Event event, Reason reason) { |
| 97 | if (static_cast<unsigned>(reason) >= reason_count) return; | 100 | if (static_cast<unsigned>(event) >= 4u || static_cast<unsigned>(reason) >= reason_count) return; |
| 98 | static std::atomic_flag shown[reason_count]{}; | 101 | static std::atomic_flag shown[reason_count]{}; |
| 99 | if (!shown[reason].test_and_set(std::memory_order_relaxed)) | 102 | if (!shown[reason].test_and_set(std::memory_order_relaxed)) |
| 100 | std::fprintf(stderr, "[rt] indirect graphics skipped: %s\n", reason_name(reason)); | 103 | std::fprintf(stderr, "[rt] indirect graphics skipped: %s\n", reason_name(reason)); |
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index f44eb2535..ad17dd3b0 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp | |||
| @@ -176,6 +176,7 @@ void start_title_peek(std::uint8_t* base) { | |||
| 176 | 176 | ||
| 177 | } // namespace | 177 | } // namespace |
| 178 | 178 | ||
| 179 | #include "assert_skip.h" | ||
| 179 | #include "avx2_emulation.h" | 180 | #include "avx2_emulation.h" |
| 180 | #include "base_reservation.h" | 181 | #include "base_reservation.h" |
| 181 | #include "compile_gate_policy.h" | 182 | #include "compile_gate_policy.h" |
| @@ -576,6 +577,17 @@ int wmain(int argc, wchar_t** argv) { | |||
| 576 | if (!rt::avx2_emulation::install()) | 577 | if (!rt::avx2_emulation::install()) |
| 577 | std::fprintf(stderr, "[rt] cpu: AddVectoredExceptionHandler (AVX2) failed (error %lu); instructions this CPU " | 578 | std::fprintf(stderr, "[rt] cpu: AddVectoredExceptionHandler (AVX2) failed (error %lu); instructions this CPU " |
| 578 | "lacks will stop the game\n", GetLastError()); | 579 | "lacks will stop the game\n", GetLastError()); |
| 580 | // LEONIDA_SKIP_ASSERTS=N (src/assert_skip.h): up to N int3 in guest code are logged and stepped over. Off unless | ||
| 581 | // set; installed before the first TLS callback, the first image code that runs. | ||
| 582 | if (init || run) | ||
| 583 | if (const unsigned skip_asserts = rt::assert_skip::limit_from_environment()) { | ||
| 584 | if (rt::assert_skip::install(skip_asserts)) | ||
| 585 | std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS=%u: up to %u int3 in guest code are stepped over " | ||
| 586 | "(diagnostic)\n", skip_asserts, skip_asserts); | ||
| 587 | else | ||
| 588 | std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: AddVectoredExceptionHandler failed (error %lu); off\n", | ||
| 589 | GetLastError()); | ||
| 590 | } | ||
| 579 | 591 | ||
| 580 | try { | 592 | try { |
| 581 | rt::Loader loader(game_dir); | 593 | rt::Loader loader(game_dir); |
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 303469b06..49588b424 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp | |||
| @@ -188,6 +188,15 @@ std::filesystem::path tls_host_base_path() { | |||
| 188 | } | 188 | } |
| 189 | 189 | ||
| 190 | std::filesystem::path tls_host_clone_dir() { | 190 | std::filesystem::path tls_host_clone_dir() { |
| 191 | if (const char* dir = std::getenv("LEONIDA_TEST_DIR"); dir && *dir) return std::filesystem::path(dir); | ||
| 192 | const char* tmp = std::getenv("TMP"); | ||
| 193 | const char* temp = std::getenv("TEMP"); | ||
| 194 | const char* profile = std::getenv("USERPROFILE"); | ||
| 195 | if ((!tmp || !*tmp) && (!temp || !*temp) && (!profile || !*profile)) { | ||
| 196 | std::error_code ec; | ||
| 197 | auto cwd = std::filesystem::current_path(ec); | ||
| 198 | if (!ec) return cwd; | ||
| 199 | } | ||
| 191 | wchar_t buf[MAX_PATH]; | 200 | wchar_t buf[MAX_PATH]; |
| 192 | DWORD n = GetTempPathW(MAX_PATH, buf); | 201 | DWORD n = GetTempPathW(MAX_PATH, buf); |
| 193 | if (n > 0 && n < MAX_PATH) return std::filesystem::path(buf); | 202 | if (n > 0 && n < MAX_PATH) return std::filesystem::path(buf); |
diff --git a/runtime/src/pipeline_wait.h b/runtime/src/pipeline_wait.h index 2d74d8581..d809e8ad3 100644 --- a/runtime/src/pipeline_wait.h +++ b/runtime/src/pipeline_wait.h | |||
| @@ -22,8 +22,11 @@ inline std::atomic<std::int64_t>& last_submission() { | |||
| 22 | } | 22 | } |
| 23 | inline void note_submission() { last_submission().store(now_ns(), std::memory_order_relaxed); } | 23 | inline void note_submission() { last_submission().store(now_ns(), std::memory_order_relaxed); } |
| 24 | inline bool title_submitting(std::int64_t within_ns = 1000000000) { | 24 | inline bool title_submitting(std::int64_t within_ns = 1000000000) { |
| 25 | if (within_ns <= 0) return false; | ||
| 25 | const std::int64_t last = last_submission().load(std::memory_order_relaxed); | 26 | const std::int64_t last = last_submission().load(std::memory_order_relaxed); |
| 26 | return last && now_ns() - last < within_ns; | 27 | if (last <= 0) return false; |
| 28 | const std::int64_t now = now_ns(); | ||
| 29 | return now < last || now - last < within_ns; | ||
| 27 | } | 30 | } |
| 28 | 31 | ||
| 29 | // Big warm-ups left to their first use while the title submits. | 32 | // Big warm-ups left to their first use while the title submits. |
diff --git a/runtime/src/quad_index_expand.h b/runtime/src/quad_index_expand.h index 3c539a540..1883e4a43 100644 --- a/runtime/src/quad_index_expand.h +++ b/runtime/src/quad_index_expand.h | |||
| @@ -56,8 +56,8 @@ public: | |||
| 56 | QuadIndexExpander(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits) | 56 | QuadIndexExpander(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits) |
| 57 | : get_(get), device_(device), limits_(limits) {} | 57 | : get_(get), device_(device), limits_(limits) {} |
| 58 | ~QuadIndexExpander() { | 58 | ~QuadIndexExpander() { |
| 59 | if (pipeline_) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline_, nullptr); | 59 | if (pipeline_) vk_.destroy_pipeline(device_, pipeline_, nullptr); |
| 60 | if (layout_) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout_, nullptr); | 60 | if (layout_) vk_.destroy_layout(device_, layout_, nullptr); |
| 61 | } | 61 | } |
| 62 | QuadIndexExpander(const QuadIndexExpander&) = delete; | 62 | QuadIndexExpander(const QuadIndexExpander&) = delete; |
| 63 | QuadIndexExpander& operator=(const QuadIndexExpander&) = delete; | 63 | QuadIndexExpander& operator=(const QuadIndexExpander&) = delete; |
| @@ -72,12 +72,11 @@ public: | |||
| 72 | if (!indices || !scratch || !index_bytes || !quads || quads > max_quads || index_offset % index_bytes || | 72 | if (!indices || !scratch || !index_bytes || !quads || quads > max_quads || index_offset % index_bytes || |
| 73 | scratch_offset % sizeof(std::uint32_t) || !limits_.maxComputeWorkGroupCount[0] || !make_pipeline()) | 73 | scratch_offset % sizeof(std::uint32_t) || !limits_.maxComputeWorkGroupCount[0] || !make_pipeline()) |
| 74 | return false; | 74 | return false; |
| 75 | const auto address = fn<PFN_vkGetBufferDeviceAddress>("vkGetBufferDeviceAddress"); | ||
| 76 | VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; | 75 | VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; |
| 77 | info.buffer = indices; | 76 | info.buffer = indices; |
| 78 | const VkDeviceAddress source = address(device_, &info); | 77 | const VkDeviceAddress source = vk_.get_address(device_, &info); |
| 79 | info.buffer = scratch; | 78 | info.buffer = scratch; |
| 80 | const VkDeviceAddress target = address(device_, &info); | 79 | const VkDeviceAddress target = vk_.get_address(device_, &info); |
| 81 | if (!source || !target || index_offset > UINT64_MAX - source || scratch_offset > UINT64_MAX - target || | 80 | if (!source || !target || index_offset > UINT64_MAX - source || scratch_offset > UINT64_MAX - target || |
| 82 | (source % sizeof(std::uint32_t)) || (target % sizeof(std::uint32_t))) | 81 | (source % sizeof(std::uint32_t)) || (target % sizeof(std::uint32_t))) |
| 83 | return false; | 82 | return false; |
| @@ -95,14 +94,13 @@ public: | |||
| 95 | 94 | ||
| 96 | // Records the pass: outside a render pass, before the draw that binds job.buffer as its index buffer. | 95 | // Records the pass: outside a render pass, before the draw that binds job.buffer as its index buffer. |
| 97 | void emit(VkCommandBuffer cb, const QuadIndexExpansion& job) const { | 96 | void emit(VkCommandBuffer cb, const QuadIndexExpansion& job) const { |
| 98 | const auto barrier = fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier"); | ||
| 99 | // Whatever wrote the application's indices earlier in the command buffer (a copy, a shader) is visible. | 97 | // Whatever wrote the application's indices earlier in the command buffer (a copy, a shader) is visible. |
| 100 | VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 98 | VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 101 | before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; | 99 | before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; |
| 102 | before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; | 100 | before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; |
| 103 | barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, | 101 | vk_.cmd_barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, |
| 104 | 0, 1, &before, 0, nullptr, 0, nullptr); | 102 | 0, 1, &before, 0, nullptr, 0, nullptr); |
| 105 | fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); | 103 | vk_.cmd_bind_pipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); |
| 106 | struct Push { | 104 | struct Push { |
| 107 | VkDeviceAddress source, triangles; | 105 | VkDeviceAddress source, triangles; |
| 108 | std::uint32_t first_half, index_bits, limit, quads; | 106 | std::uint32_t first_half, index_bits, limit, quads; |
| @@ -121,54 +119,77 @@ public: | |||
| 121 | const Push push{job.source + source_bytes, job.triangles + first * indices_per_quad * 4, | 119 | const Push push{job.source + source_bytes, job.triangles + first * indices_per_quad * 4, |
| 122 | job.first_half, job.index_bits, std::uint32_t(std::min<std::uint64_t>(left, UINT32_MAX)), | 120 | job.first_half, job.index_bits, std::uint32_t(std::min<std::uint64_t>(left, UINT32_MAX)), |
| 123 | quads}; | 121 | quads}; |
| 124 | fn<PFN_vkCmdPushConstants>("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, | 122 | vk_.cmd_push_constants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); |
| 125 | sizeof(push), &push); | 123 | vk_.cmd_dispatch(cb, (quads - 1u) / group_size + 1u, 1, 1); |
| 126 | fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb, (quads - 1u) / group_size + 1u, 1, 1); | ||
| 127 | first += quads; | 124 | first += quads; |
| 128 | } | 125 | } |
| 129 | VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 126 | VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 130 | after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; | 127 | after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; |
| 131 | after.dstAccessMask = VK_ACCESS_INDEX_READ_BIT; | 128 | after.dstAccessMask = VK_ACCESS_INDEX_READ_BIT; |
| 132 | barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, | 129 | vk_.cmd_barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, |
| 133 | 0, 1, &after, 0, nullptr, 0, nullptr); | 130 | 0, 1, &after, 0, nullptr, 0, nullptr); |
| 134 | } | 131 | } |
| 135 | 132 | ||
| 136 | private: | 133 | private: |
| 137 | static constexpr std::uint32_t group_size = 64; // local_size_x of quad_index_expand.comp | 134 | static constexpr std::uint32_t group_size = 64; // local_size_x of quad_index_expand.comp |
| 138 | static constexpr std::uint32_t push_bytes = 32; | 135 | static constexpr std::uint32_t push_bytes = 32; |
| 139 | template<typename T> T fn(const char* name) const { return reinterpret_cast<T>(get_(device_, name)); } | 136 | struct Functions { |
| 137 | PFN_vkGetBufferDeviceAddress get_address = nullptr; | ||
| 138 | PFN_vkCreateShaderModule create_shader = nullptr; | ||
| 139 | PFN_vkDestroyShaderModule destroy_shader = nullptr; | ||
| 140 | PFN_vkCreatePipelineLayout create_layout = nullptr; | ||
| 141 | PFN_vkDestroyPipelineLayout destroy_layout = nullptr; | ||
| 142 | PFN_vkCreateComputePipelines create_pipelines = nullptr; | ||
| 143 | PFN_vkDestroyPipeline destroy_pipeline = nullptr; | ||
| 144 | PFN_vkCmdPipelineBarrier cmd_barrier = nullptr; | ||
| 145 | PFN_vkCmdBindPipeline cmd_bind_pipeline = nullptr; | ||
| 146 | PFN_vkCmdPushConstants cmd_push_constants = nullptr; | ||
| 147 | PFN_vkCmdDispatch cmd_dispatch = nullptr; | ||
| 148 | }; | ||
| 149 | template<typename T> bool load_fn(T& out, const char* name) const { | ||
| 150 | out = reinterpret_cast<T>(get_(device_, name)); | ||
| 151 | return out != nullptr; | ||
| 152 | } | ||
| 140 | bool make_pipeline() { | 153 | bool make_pipeline() { |
| 141 | if (pipeline_) return true; | 154 | if (pipeline_) return true; |
| 142 | for (const char* name : {"vkGetBufferDeviceAddress", "vkCreateShaderModule", "vkDestroyShaderModule", | 155 | Functions f{}; |
| 143 | "vkCreatePipelineLayout", "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", | 156 | if (!load_fn(f.get_address, "vkGetBufferDeviceAddress") || |
| 144 | "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"}) | 157 | !load_fn(f.create_shader, "vkCreateShaderModule") || |
| 145 | if (!get_(device_, name)) return false; | 158 | !load_fn(f.destroy_shader, "vkDestroyShaderModule") || |
| 159 | !load_fn(f.create_layout, "vkCreatePipelineLayout") || | ||
| 160 | !load_fn(f.destroy_layout, "vkDestroyPipelineLayout") || | ||
| 161 | !load_fn(f.create_pipelines, "vkCreateComputePipelines") || | ||
| 162 | !load_fn(f.destroy_pipeline, "vkDestroyPipeline") || | ||
| 163 | !load_fn(f.cmd_barrier, "vkCmdPipelineBarrier") || | ||
| 164 | !load_fn(f.cmd_bind_pipeline, "vkCmdBindPipeline") || | ||
| 165 | !load_fn(f.cmd_push_constants, "vkCmdPushConstants") || !load_fn(f.cmd_dispatch, "vkCmdDispatch")) | ||
| 166 | return false; | ||
| 146 | VkShaderModule module = VK_NULL_HANDLE; | 167 | VkShaderModule module = VK_NULL_HANDLE; |
| 147 | VkPipelineLayout layout = VK_NULL_HANDLE; | 168 | VkPipelineLayout layout = VK_NULL_HANDLE; |
| 148 | VkPipeline pipeline = VK_NULL_HANDLE; | 169 | VkPipeline pipeline = VK_NULL_HANDLE; |
| 149 | VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | 170 | VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; |
| 150 | shader.codeSize = sizeof(quad_index_expand_spirv); | 171 | shader.codeSize = sizeof(quad_index_expand_spirv); |
| 151 | shader.pCode = quad_index_expand_spirv; | 172 | shader.pCode = quad_index_expand_spirv; |
| 152 | bool ok = fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS; | 173 | bool ok = f.create_shader(device_, &shader, nullptr, &module) == VK_SUCCESS; |
| 153 | const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, push_bytes}; | 174 | const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, push_bytes}; |
| 154 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | 175 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; |
| 155 | layout_info.pushConstantRangeCount = 1; | 176 | layout_info.pushConstantRangeCount = 1; |
| 156 | layout_info.pPushConstantRanges = ⦥ | 177 | layout_info.pPushConstantRanges = ⦥ |
| 157 | ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; | 178 | ok = ok && f.create_layout(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; |
| 158 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | 179 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; |
| 159 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | 180 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; |
| 160 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; | 181 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; |
| 161 | info.stage.module = module; | 182 | info.stage.module = module; |
| 162 | info.stage.pName = "main"; | 183 | info.stage.pName = "main"; |
| 163 | info.layout = layout; | 184 | info.layout = layout; |
| 164 | ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")( | 185 | ok = ok && f.create_pipelines(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; |
| 165 | device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; | 186 | if (module) f.destroy_shader(device_, module, nullptr); |
| 166 | if (module) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, module, nullptr); | ||
| 167 | if (!ok) { | 187 | if (!ok) { |
| 168 | if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr); | 188 | if (pipeline) f.destroy_pipeline(device_, pipeline, nullptr); |
| 169 | if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr); | 189 | if (layout) f.destroy_layout(device_, layout, nullptr); |
| 170 | return false; | 190 | return false; |
| 171 | } | 191 | } |
| 192 | vk_ = f; | ||
| 172 | layout_ = layout; | 193 | layout_ = layout; |
| 173 | pipeline_ = pipeline; | 194 | pipeline_ = pipeline; |
| 174 | return true; | 195 | return true; |
| @@ -176,6 +197,7 @@ private: | |||
| 176 | PFN_vkGetDeviceProcAddr get_; | 197 | PFN_vkGetDeviceProcAddr get_; |
| 177 | VkDevice device_; | 198 | VkDevice device_; |
| 178 | VkPhysicalDeviceLimits limits_; | 199 | VkPhysicalDeviceLimits limits_; |
| 200 | Functions vk_{}; | ||
| 179 | VkPipelineLayout layout_ = VK_NULL_HANDLE; | 201 | VkPipelineLayout layout_ = VK_NULL_HANDLE; |
| 180 | VkPipeline pipeline_ = VK_NULL_HANDLE; | 202 | VkPipeline pipeline_ = VK_NULL_HANDLE; |
| 181 | }; | 203 | }; |
diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h index 5682d9e54..c88696483 100644 --- a/runtime/src/queue_families.h +++ b/runtime/src/queue_families.h | |||
| @@ -70,15 +70,16 @@ inline QueueFamilies pick_queue_families(std::span<const VkQueueFamilyProperties | |||
| 70 | return out; | 70 | return out; |
| 71 | } | 71 | } |
| 72 | 72 | ||
| 73 | // A D3D12 COPY/COMPUTE queue may call UpdateTileMappings at any time. Vulkan binds sparse | 73 | inline bool supports_sparse_tile_aliasing(const VkPhysicalDeviceFeatures& features, |
| 74 | // pages on the VkQueue itself, so a family without SPARSE_BINDING cannot back that D3D12 | 74 | const VkPhysicalDeviceSparseProperties& properties) { |
| 75 | // queue when reserved buffers are offered. Use the graphics family (already checked for | 75 | return features.sparseBinding && features.sparseResidencyAliased && properties.residencyNonResidentStrict; |
| 76 | // sparse support by the device) rather than submitting an invalid vkQueueBindSparse. | 76 | } |
| 77 | // Kept separate from the preference-only picker so devices without sparse resources keep | 77 | |
| 78 | // their dedicated async families unchanged. | ||
| 79 | inline QueueFamilies sparse_capable_queue_families(std::span<const VkQueueFamilyProperties> families, | 78 | inline QueueFamilies sparse_capable_queue_families(std::span<const VkQueueFamilyProperties> families, |
| 80 | QueueFamilies chosen, bool sparse_buffers) { | 79 | QueueFamilies chosen, const VkPhysicalDeviceFeatures& features, |
| 81 | if (!sparse_buffers || chosen.direct >= families.size() || | 80 | const VkPhysicalDeviceSparseProperties& properties) { |
| 81 | if (!supports_sparse_tile_aliasing(features, properties) || | ||
| 82 | !(features.sparseResidencyBuffer || features.sparseResidencyImage2D) || chosen.direct >= families.size() || | ||
| 82 | !(families[chosen.direct].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT)) | 83 | !(families[chosen.direct].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT)) |
| 83 | return chosen; | 84 | return chosen; |
| 84 | if (chosen.compute >= families.size() || | 85 | if (chosen.compute >= families.size() || |
| @@ -107,7 +108,7 @@ inline QueueSlot pick_queue_slot(std::initializer_list<std::span<const std::uint | |||
| 107 | std::size_t p = 0; | 108 | std::size_t p = 0; |
| 108 | for (const auto users : pools) { | 109 | for (const auto users : pools) { |
| 109 | for (std::size_t i = 0; i < users.size(); ++i) | 110 | for (std::size_t i = 0; i < users.size(); ++i) |
| 110 | if (users[i] < fewest) { | 111 | if (chosen.pool == SIZE_MAX || users[i] < fewest) { |
| 111 | fewest = users[i]; | 112 | fewest = users[i]; |
| 112 | chosen = {p, i}; | 113 | chosen = {p, i}; |
| 113 | } | 114 | } |
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index f19e56d71..c483d60dd 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h | |||
| @@ -26,6 +26,7 @@ | |||
| 26 | #include <span> | 26 | #include <span> |
| 27 | #include <string> | 27 | #include <string> |
| 28 | #include <string_view> | 28 | #include <string_view> |
| 29 | #include <system_error> | ||
| 29 | #include <tuple> | 30 | #include <tuple> |
| 30 | #include <utility> | 31 | #include <utility> |
| 31 | #include <vector> | 32 | #include <vector> |
| @@ -858,6 +859,9 @@ struct ShaderEntry { | |||
| 858 | std::uint32_t lds_bytes = 0; | 859 | std::uint32_t lds_bytes = 0; |
| 859 | bool uses_code_base = false; | 860 | bool uses_code_base = false; |
| 860 | bool code_base_known = false; | 861 | bool code_base_known = false; |
| 862 | // The index's needs_maintenance8: an image sample takes a texel offset outside a gather (the SPIR-V Offset image | ||
| 863 | // operand), valid only with VK_KHR_maintenance8; a pipeline on a device without it is refused. | ||
| 864 | bool needs_maintenance8 = false; | ||
| 861 | bool wave64 = false; | 865 | bool wave64 = false; |
| 862 | // The subgroup size the translator assumed (64 for a wave64 shader, 32 otherwise); 0 when the entry says null, | 866 | // The subgroup size the translator assumed (64 for a wave64 shader, 32 otherwise); 0 when the entry says null, |
| 863 | // as one translated with --wave64-emulate does, or has none. | 867 | // as one translated with --wave64-emulate does, or has none. |
| @@ -1139,14 +1143,8 @@ public: | |||
| 1139 | // The size of the module's file in bytes, or 0 when it is missing: what spirv() would read, without reading it. | 1143 | // The size of the module's file in bytes, or 0 when it is missing: what spirv() would read, without reading it. |
| 1140 | std::size_t spirv_bytes(const ShaderEntry& entry) const { | 1144 | std::size_t spirv_bytes(const ShaderEntry& entry) const { |
| 1141 | std::error_code ec; | 1145 | std::error_code ec; |
| 1142 | auto path = dir_; | 1146 | auto size = std::filesystem::file_size(module_path(entry.name + ".spv"), ec); |
| 1143 | path += "/" + entry.name + ".spv"; | 1147 | if (ec && !entry.spv_file.empty()) size = std::filesystem::file_size(module_path(entry.spv_file), ec); |
| 1144 | auto size = std::filesystem::file_size(path, ec); | ||
| 1145 | if (ec && !entry.spv_file.empty()) { | ||
| 1146 | auto alt = dir_; | ||
| 1147 | alt += "/" + entry.spv_file; | ||
| 1148 | size = std::filesystem::file_size(alt, ec); | ||
| 1149 | } | ||
| 1150 | return ec ? 0 : static_cast<std::size_t>(size); | 1148 | return ec ? 0 : static_cast<std::size_t>(size); |
| 1151 | } | 1149 | } |
| 1152 | 1150 | ||
| @@ -1166,18 +1164,25 @@ public: | |||
| 1166 | 1164 | ||
| 1167 | // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V. | 1165 | // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V. |
| 1168 | std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const { | 1166 | std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const { |
| 1169 | auto path = dir_; | 1167 | std::ifstream file(module_path(entry.name + ".spv"), std::ios::binary | std::ios::ate); |
| 1170 | path += "/" + entry.name + ".spv"; | 1168 | if (!file && !entry.spv_file.empty()) file.open(module_path(entry.spv_file), std::ios::binary | std::ios::ate); |
| 1171 | std::ifstream file(path, std::ios::binary | std::ios::ate); | ||
| 1172 | if (!file && !entry.spv_file.empty()) { | ||
| 1173 | auto alt = dir_; | ||
| 1174 | alt += "/" + entry.spv_file; | ||
| 1175 | file.open(alt, std::ios::binary | std::ios::ate); | ||
| 1176 | } | ||
| 1177 | return read_spirv_words(file, file.tellg()); | 1169 | return read_spirv_words(file, file.tellg()); |
| 1178 | } | 1170 | } |
| 1179 | 1171 | ||
| 1180 | private: | 1172 | private: |
| 1173 | std::filesystem::path module_path(std::string_view filename) const { | ||
| 1174 | // Index strings are UTF-8, including the optional explicit SPIR-V filename. | ||
| 1175 | try { | ||
| 1176 | std::u8string suffix = u8"/"; | ||
| 1177 | suffix.append(filename.begin(), filename.end()); | ||
| 1178 | auto path = dir_; | ||
| 1179 | path += suffix; | ||
| 1180 | return path; | ||
| 1181 | } catch (const std::system_error&) { | ||
| 1182 | return {}; // a filename the host cannot decode is an unavailable module | ||
| 1183 | } | ||
| 1184 | } | ||
| 1185 | |||
| 1181 | // A non-negative integer field, or 0 when it is missing, not a number or out of range. | 1186 | // A non-negative integer field, or 0 when it is missing, not a number or out of range. |
| 1182 | static std::uint32_t u32(const Json* value) { | 1187 | static std::uint32_t u32(const Json* value) { |
| 1183 | if (!value || value->kind != Json::Kind::number) return 0; | 1188 | if (!value || value->kind != Json::Kind::number) return 0; |
| @@ -1267,6 +1272,8 @@ private: | |||
| 1267 | e.uses_code_base = c->boolean; | 1272 | e.uses_code_base = c->boolean; |
| 1268 | e.code_base_known = true; | 1273 | e.code_base_known = true; |
| 1269 | } | 1274 | } |
| 1275 | if (const Json* m = meta.find("needs_maintenance8"); m && m->kind == Json::Kind::boolean) | ||
| 1276 | e.needs_maintenance8 = m->boolean; | ||
| 1270 | if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; | 1277 | if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; |
| 1271 | if (const Json* g = meta.find("subgroup_size"); g && g->kind == Json::Kind::number) | 1278 | if (const Json* g = meta.find("subgroup_size"); g && g->kind == Json::Kind::number) |
| 1272 | e.subgroup_size = u32(g); | 1279 | e.subgroup_size = u32(g); |
diff --git a/runtime/src/spirv_words.h b/runtime/src/spirv_words.h index e7e91fe5d..2f0770ba4 100644 --- a/runtime/src/spirv_words.h +++ b/runtime/src/spirv_words.h | |||
| @@ -7,19 +7,29 @@ | |||
| 7 | 7 | ||
| 8 | namespace leonida { | 8 | namespace leonida { |
| 9 | 9 | ||
| 10 | // Checks the binary framing used by the translator and returns words aligned for Vulkan. | 10 | // Checks the binary framing and returns aligned words in host byte order for Vulkan. |
| 11 | // The caller still relies on the driver or spirv-val for instruction and capability validation. | 11 | // The caller still relies on the driver or spirv-val for instruction and capability validation. |
| 12 | inline std::vector<std::uint32_t> read_spirv_words(std::istream& input, std::streamoff byte_count) { | 12 | inline std::vector<std::uint32_t> read_spirv_words(std::istream& input, std::streamoff byte_count) { |
| 13 | constexpr std::streamoff word_bytes = sizeof(std::uint32_t); | 13 | constexpr std::streamoff word_bytes = sizeof(std::uint32_t); |
| 14 | constexpr std::streamoff header_bytes = 5 * word_bytes; | 14 | constexpr std::streamoff header_bytes = 5 * word_bytes; |
| 15 | constexpr std::uint32_t native_magic = 0x07230203u; | ||
| 16 | constexpr std::uint32_t reversed_magic = 0x03022307u; | ||
| 15 | if (byte_count < header_bytes || byte_count % word_bytes || !input.seekg(0)) return {}; | 17 | if (byte_count < header_bytes || byte_count % word_bytes || !input.seekg(0)) return {}; |
| 16 | 18 | ||
| 17 | std::uint32_t magic = 0; | 19 | std::uint32_t magic = 0; |
| 18 | if (!input.read(reinterpret_cast<char*>(&magic), word_bytes) || magic != 0x07230203) return {}; | 20 | if (!input.read(reinterpret_cast<char*>(&magic), word_bytes) || |
| 21 | (magic != native_magic && magic != reversed_magic)) return {}; | ||
| 19 | 22 | ||
| 20 | std::vector<std::uint32_t> words(static_cast<std::size_t>(byte_count / word_bytes)); | 23 | std::vector<std::uint32_t> words(static_cast<std::size_t>(byte_count / word_bytes)); |
| 21 | words.front() = magic; | 24 | words.front() = native_magic; |
| 22 | if (!input.read(reinterpret_cast<char*>(words.data() + 1), byte_count - word_bytes)) return {}; | 25 | if (!input.read(reinterpret_cast<char*>(words.data() + 1), byte_count - word_bytes)) return {}; |
| 26 | if (magic == reversed_magic) { | ||
| 27 | for (std::size_t i = 1; i < words.size(); ++i) { | ||
| 28 | const auto word = words[i]; | ||
| 29 | words[i] = (word << 24) | ((word & 0x0000ff00u) << 8) | | ||
| 30 | ((word & 0x00ff0000u) >> 8) | (word >> 24); | ||
| 31 | } | ||
| 32 | } | ||
| 23 | return words; | 33 | return words; |
| 24 | } | 34 | } |
| 25 | 35 | ||
diff --git a/runtime/src/uav_clear.h b/runtime/src/uav_clear.h index 385d55950..4b265c258 100644 --- a/runtime/src/uav_clear.h +++ b/runtime/src/uav_clear.h | |||
| @@ -105,11 +105,62 @@ inline constexpr Layout layouts[] = { | |||
| 105 | }; | 105 | }; |
| 106 | 106 | ||
| 107 | inline constexpr const Layout* layout(VkFormat format) { | 107 | inline constexpr const Layout* layout(VkFormat format) { |
| 108 | for (const Layout& l : layouts) | 108 | switch (format) { |
| 109 | if (l.format == format) return &l; | 109 | case VK_FORMAT_R32G32B32A32_SFLOAT: return &layouts[0]; |
| 110 | return nullptr; | 110 | case VK_FORMAT_R32G32B32A32_UINT: return &layouts[1]; |
| 111 | case VK_FORMAT_R32G32B32A32_SINT: return &layouts[2]; | ||
| 112 | case VK_FORMAT_R16G16B16A16_SFLOAT: return &layouts[3]; | ||
| 113 | case VK_FORMAT_R16G16B16A16_UNORM: return &layouts[4]; | ||
| 114 | case VK_FORMAT_R16G16B16A16_SNORM: return &layouts[5]; | ||
| 115 | case VK_FORMAT_R16G16B16A16_UINT: return &layouts[6]; | ||
| 116 | case VK_FORMAT_R16G16B16A16_SINT: return &layouts[7]; | ||
| 117 | case VK_FORMAT_R32G32_SFLOAT: return &layouts[8]; | ||
| 118 | case VK_FORMAT_R32G32_UINT: return &layouts[9]; | ||
| 119 | case VK_FORMAT_R32G32_SINT: return &layouts[10]; | ||
| 120 | case VK_FORMAT_A2B10G10R10_UNORM_PACK32: return &layouts[11]; | ||
| 121 | case VK_FORMAT_A2B10G10R10_UINT_PACK32: return &layouts[12]; | ||
| 122 | case VK_FORMAT_B10G11R11_UFLOAT_PACK32: return &layouts[13]; | ||
| 123 | case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: return &layouts[14]; | ||
| 124 | case VK_FORMAT_R8G8B8A8_UNORM: return &layouts[15]; | ||
| 125 | case VK_FORMAT_R8G8B8A8_SNORM: return &layouts[16]; | ||
| 126 | case VK_FORMAT_R8G8B8A8_UINT: return &layouts[17]; | ||
| 127 | case VK_FORMAT_R8G8B8A8_SINT: return &layouts[18]; | ||
| 128 | case VK_FORMAT_B8G8R8A8_UNORM: return &layouts[19]; | ||
| 129 | case VK_FORMAT_R16G16_SFLOAT: return &layouts[20]; | ||
| 130 | case VK_FORMAT_R16G16_UNORM: return &layouts[21]; | ||
| 131 | case VK_FORMAT_R16G16_SNORM: return &layouts[22]; | ||
| 132 | case VK_FORMAT_R16G16_UINT: return &layouts[23]; | ||
| 133 | case VK_FORMAT_R16G16_SINT: return &layouts[24]; | ||
| 134 | case VK_FORMAT_R32_SFLOAT: return &layouts[25]; | ||
| 135 | case VK_FORMAT_R32_UINT: return &layouts[26]; | ||
| 136 | case VK_FORMAT_R32_SINT: return &layouts[27]; | ||
| 137 | case VK_FORMAT_R8G8_UNORM: return &layouts[28]; | ||
| 138 | case VK_FORMAT_R8G8_SNORM: return &layouts[29]; | ||
| 139 | case VK_FORMAT_R8G8_UINT: return &layouts[30]; | ||
| 140 | case VK_FORMAT_R8G8_SINT: return &layouts[31]; | ||
| 141 | case VK_FORMAT_R16_SFLOAT: return &layouts[32]; | ||
| 142 | case VK_FORMAT_R16_UNORM: return &layouts[33]; | ||
| 143 | case VK_FORMAT_R4G4B4A4_UNORM_PACK16: return &layouts[34]; | ||
| 144 | case VK_FORMAT_R5G6B5_UNORM_PACK16: return &layouts[35]; | ||
| 145 | case VK_FORMAT_A1R5G5B5_UNORM_PACK16: return &layouts[36]; | ||
| 146 | case VK_FORMAT_A4R4G4B4_UNORM_PACK16: return &layouts[37]; | ||
| 147 | case VK_FORMAT_R16_SNORM: return &layouts[38]; | ||
| 148 | case VK_FORMAT_R16_UINT: return &layouts[39]; | ||
| 149 | case VK_FORMAT_R16_SINT: return &layouts[40]; | ||
| 150 | case VK_FORMAT_R8_UNORM: return &layouts[41]; | ||
| 151 | case VK_FORMAT_R8_SNORM: return &layouts[42]; | ||
| 152 | case VK_FORMAT_R8_UINT: return &layouts[43]; | ||
| 153 | case VK_FORMAT_R8_SINT: return &layouts[44]; | ||
| 154 | default: return nullptr; | ||
| 155 | } | ||
| 111 | } | 156 | } |
| 112 | 157 | ||
| 158 | static_assert([] { | ||
| 159 | for (const Layout& l : layouts) | ||
| 160 | if (layout(l.format) != &l) return false; | ||
| 161 | return true; | ||
| 162 | }(), "layout() switch must match layouts[] table"); | ||
| 163 | |||
| 113 | // Up to one element of the largest format. | 164 | // Up to one element of the largest format. |
| 114 | struct Element { | 165 | struct Element { |
| 115 | std::array<std::uint8_t, 16> bytes{}; | 166 | std::array<std::uint8_t, 16> bytes{}; |
| @@ -118,19 +169,63 @@ struct Element { | |||
| 118 | 169 | ||
| 119 | namespace detail { | 170 | namespace detail { |
| 120 | 171 | ||
| 172 | static_assert(std::endian::native == std::endian::little, "uav_clear assumes little-endian byte order"); | ||
| 173 | |||
| 121 | inline constexpr std::uint32_t mask(unsigned bits) { return bits >= 32 ? 0xffffffffu : (1u << bits) - 1; } | 174 | inline constexpr std::uint32_t mask(unsigned bits) { return bits >= 32 ? 0xffffffffu : (1u << bits) - 1; } |
| 122 | 175 | ||
| 123 | inline void put(Element& e, Channel c, std::uint32_t value) { | 176 | inline void put(Element& e, Channel c, std::uint32_t value) { |
| 177 | if (!c.bits || c.bits > 32u || c.offset > 128u - c.bits) return; | ||
| 124 | value &= mask(c.bits); | 178 | value &= mask(c.bits); |
| 125 | for (unsigned i = 0; i < c.bits; ++i) | 179 | const unsigned byte = c.offset >> 3; |
| 126 | if (value >> i & 1) e.bytes[(c.offset + i) / 8] |= std::uint8_t(1u << ((c.offset + i) % 8)); | 180 | const unsigned bit = c.offset & 7u; |
| 181 | if (bit == 0u) { | ||
| 182 | if (c.bits == 8u) { | ||
| 183 | e.bytes[byte] |= static_cast<std::uint8_t>(value); | ||
| 184 | return; | ||
| 185 | } | ||
| 186 | if (c.bits == 16u) { | ||
| 187 | std::uint16_t cur = 0; | ||
| 188 | std::memcpy(&cur, e.bytes.data() + byte, 2); | ||
| 189 | cur = static_cast<std::uint16_t>(cur | static_cast<std::uint16_t>(value)); | ||
| 190 | std::memcpy(e.bytes.data() + byte, &cur, 2); | ||
| 191 | return; | ||
| 192 | } | ||
| 193 | if (c.bits == 32u) { | ||
| 194 | std::uint32_t cur = 0; | ||
| 195 | std::memcpy(&cur, e.bytes.data() + byte, 4); | ||
| 196 | cur |= value; | ||
| 197 | std::memcpy(e.bytes.data() + byte, &cur, 4); | ||
| 198 | return; | ||
| 199 | } | ||
| 200 | } | ||
| 201 | const unsigned span = (bit + c.bits + 7u) >> 3; | ||
| 202 | std::uint64_t word = 0; | ||
| 203 | std::memcpy(&word, e.bytes.data() + byte, span); | ||
| 204 | word |= std::uint64_t{value} << bit; | ||
| 205 | std::memcpy(e.bytes.data() + byte, &word, span); | ||
| 127 | } | 206 | } |
| 128 | 207 | ||
| 129 | inline std::uint32_t get(const Element& e, Channel c) { | 208 | inline std::uint32_t get(const Element& e, Channel c) { |
| 130 | std::uint32_t value = 0; | 209 | if (!c.bits || c.bits > 32u || c.offset > 128u - c.bits) return 0u; |
| 131 | for (unsigned i = 0; i < c.bits; ++i) | 210 | const unsigned byte = c.offset >> 3; |
| 132 | value |= std::uint32_t(e.bytes[(c.offset + i) / 8] >> ((c.offset + i) % 8) & 1) << i; | 211 | const unsigned bit = c.offset & 7u; |
| 133 | return value; | 212 | if (bit == 0u) { |
| 213 | if (c.bits == 8u) return e.bytes[byte]; | ||
| 214 | if (c.bits == 16u) { | ||
| 215 | std::uint16_t v = 0; | ||
| 216 | std::memcpy(&v, e.bytes.data() + byte, 2); | ||
| 217 | return v; | ||
| 218 | } | ||
| 219 | if (c.bits == 32u) { | ||
| 220 | std::uint32_t v = 0; | ||
| 221 | std::memcpy(&v, e.bytes.data() + byte, 4); | ||
| 222 | return v; | ||
| 223 | } | ||
| 224 | } | ||
| 225 | const unsigned span = (bit + c.bits + 7u) >> 3; | ||
| 226 | std::uint64_t word = 0; | ||
| 227 | std::memcpy(&word, e.bytes.data() + byte, span); | ||
| 228 | return static_cast<std::uint32_t>(word >> bit) & mask(c.bits); | ||
| 134 | } | 229 | } |
| 135 | 230 | ||
| 136 | // A float32 as a float with `mantissa` fraction bits, `exponent` exponent bits and an optional sign bit (IEEE | 231 | // A float32 as a float with `mantissa` fraction bits, `exponent` exponent bits and an optional sign bit (IEEE |
| @@ -246,11 +341,12 @@ inline bool encode(VkFormat format, bool is_float, const std::array<std::uint32_ | |||
| 246 | continue; | 341 | continue; |
| 247 | } | 342 | } |
| 248 | const float v = std::bit_cast<float>(values[i]); | 343 | const float v = std::bit_cast<float>(values[i]); |
| 249 | const double scale = double(detail::mask(c.bits)); | ||
| 250 | switch (l->kind) { | 344 | switch (l->kind) { |
| 251 | case Kind::unorm: | 345 | case Kind::unorm: { |
| 346 | const double scale = double(detail::mask(c.bits)); | ||
| 252 | detail::put(out, c, std::isnan(v) ? 0 : std::uint32_t(std::lround(std::clamp(double(v), 0.0, 1.0) * scale))); | 347 | detail::put(out, c, std::isnan(v) ? 0 : std::uint32_t(std::lround(std::clamp(double(v), 0.0, 1.0) * scale))); |
| 253 | break; | 348 | break; |
| 349 | } | ||
| 254 | case Kind::snorm: { | 350 | case Kind::snorm: { |
| 255 | const double max = double(detail::mask(c.bits - 1)); | 351 | const double max = double(detail::mask(c.bits - 1)); |
| 256 | detail::put(out, c, std::isnan(v) ? 0 : std::uint32_t(std::lround(std::clamp(double(v), -1.0, 1.0) * max))); | 352 | detail::put(out, c, std::isnan(v) ? 0 : std::uint32_t(std::lround(std::clamp(double(v), -1.0, 1.0) * max))); |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 556022fb2..f5902252d 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -125,8 +125,8 @@ struct VulkanDeviceFunctions { | |||
| 125 | X(vkCmdPushConstants) X(vkCmdDispatch) \ | 125 | X(vkCmdPushConstants) X(vkCmdDispatch) \ |
| 126 | X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ | 126 | X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ |
| 127 | X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \ | 127 | X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \ |
| 128 | X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) X(vkCmdSetDepthBounds) \ | 128 | X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ |
| 129 | X(vkCmdSetBlendConstants) X(vkCmdDraw) \ | 129 | X(vkCmdSetDepthBounds) X(vkCmdSetBlendConstants) X(vkCmdDraw) X(vkCmdSetSampleLocationsEXT) \ |
| 130 | X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ | 130 | X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ |
| 131 | X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ | 131 | X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ |
| 132 | X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) X(vkCmdDrawMeshTasksIndirectEXT) X(vkCmdDrawMeshTasksIndirectCountEXT) \ | 132 | X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) X(vkCmdDrawMeshTasksIndirectEXT) X(vkCmdDrawMeshTasksIndirectCountEXT) \ |
| @@ -1191,6 +1191,7 @@ public: | |||
| 1191 | replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; | 1191 | replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; |
| 1192 | replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; | 1192 | replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; |
| 1193 | replay_.set_stencil_reference = vk.vkCmdSetStencilReference; | 1193 | replay_.set_stencil_reference = vk.vkCmdSetStencilReference; |
| 1194 | replay_.set_sample_locations = vk.vkCmdSetSampleLocationsEXT; | ||
| 1194 | replay_.set_blend_constants = vk.vkCmdSetBlendConstants; | 1195 | replay_.set_blend_constants = vk.vkCmdSetBlendConstants; |
| 1195 | replay_.set_depth_bounds = vk.vkCmdSetDepthBounds; | 1196 | replay_.set_depth_bounds = vk.vkCmdSetDepthBounds; |
| 1196 | replay_.draw = vk.vkCmdDraw; | 1197 | replay_.draw = vk.vkCmdDraw; |
diff --git a/runtime/src/vulkan_device_fault.h b/runtime/src/vulkan_device_fault.h index 3c49fce8d..9b55ef268 100644 --- a/runtime/src/vulkan_device_fault.h +++ b/runtime/src/vulkan_device_fault.h | |||
| @@ -1,6 +1,14 @@ | |||
| 1 | #pragma once | 1 | #pragma once |
| 2 | 2 | ||
| 3 | #include <vulkan/vulkan.h> | 3 | #include <vulkan/vulkan.h> |
| 4 | #ifdef _WIN32 | ||
| 5 | #ifndef NOMINMAX | ||
| 6 | #define NOMINMAX | ||
| 7 | #endif | ||
| 8 | #include <windows.h> // VirtualQuery: what the process has at a fault address | ||
| 9 | #endif | ||
| 10 | |||
| 11 | #include "address_binding.h" // LEONIDA_ADDRESS_BINDINGS: the bound object at a fault address | ||
| 4 | 12 | ||
| 5 | #include "compile_gate_policy.h" | 13 | #include "compile_gate_policy.h" |
| 6 | #include "vulkan_device_markers.h" | 14 | #include "vulkan_device_markers.h" |
| @@ -1578,6 +1586,19 @@ private: | |||
| 1578 | std::fprintf(stderr, "[rt] device-fault: address[%zu] type=%d address=0x%" PRIx64 | 1586 | std::fprintf(stderr, "[rt] device-fault: address[%zu] type=%d address=0x%" PRIx64 |
| 1579 | " precision=%" PRIu64 "\n", | 1587 | " precision=%" PRIu64 "\n", |
| 1580 | i, int(address.addressType), address.reportedAddress, address.addressPrecision); | 1588 | i, int(address.addressType), address.reportedAddress, address.addressPrecision); |
| 1589 | #ifdef _WIN32 | ||
| 1590 | // The page in this process at the same number. A GPU address is not a CPU one, but a host import, a title | ||
| 1591 | // range or a raw CPU pointer that reached the GPU shares it, so the region says which of those it can be. | ||
| 1592 | MEMORY_BASIC_INFORMATION page{}; | ||
| 1593 | if (VirtualQuery(reinterpret_cast<const void*>(static_cast<std::uintptr_t>(address.reportedAddress)), &page, | ||
| 1594 | sizeof page)) | ||
| 1595 | std::fprintf(stderr, "[rt] device-fault: address[%zu] in this process: base %p allocation %p size 0x%zx " | ||
| 1596 | "state 0x%lx protect 0x%lx type 0x%lx\n", | ||
| 1597 | i, page.BaseAddress, page.AllocationBase, page.RegionSize, | ||
| 1598 | static_cast<unsigned long>(page.State), static_cast<unsigned long>(page.Protect), | ||
| 1599 | static_cast<unsigned long>(page.Type)); | ||
| 1600 | #endif | ||
| 1601 | leonida::address_binding::describe(address.reportedAddress, address.addressPrecision); | ||
| 1581 | } | 1602 | } |
| 1582 | for (std::size_t i = 0; i < counts.vendorInfoCount; ++i) { | 1603 | for (std::size_t i = 0; i < counts.vendorInfoCount; ++i) { |
| 1583 | const auto& vendor = vendors[i]; | 1604 | const auto& vendor = vendors[i]; |
diff --git a/runtime/src/vulkan_indirect_dispatch_count.h b/runtime/src/vulkan_indirect_dispatch_count.h index 8e0f7d4aa..e8eb35174 100644 --- a/runtime/src/vulkan_indirect_dispatch_count.h +++ b/runtime/src/vulkan_indirect_dispatch_count.h | |||
| @@ -51,8 +51,8 @@ public: | |||
| 51 | const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceLimits& limits) | 51 | const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceLimits& limits) |
| 52 | : get_(get), device_(device), memory_(memory), limits_(limits) {} | 52 | : get_(get), device_(device), memory_(memory), limits_(limits) {} |
| 53 | ~IndirectDispatchCounter() { | 53 | ~IndirectDispatchCounter() { |
| 54 | if (pipeline_) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline_, nullptr); | 54 | if (pipeline_) vk_.destroy_pipeline(device_, pipeline_, nullptr); |
| 55 | if (layout_) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout_, nullptr); | 55 | if (layout_) vk_.destroy_layout(device_, layout_, nullptr); |
| 56 | } | 56 | } |
| 57 | IndirectDispatchCounter(const IndirectDispatchCounter&) = delete; | 57 | IndirectDispatchCounter(const IndirectDispatchCounter&) = delete; |
| 58 | IndirectDispatchCounter& operator=(const IndirectDispatchCounter&) = delete; | 58 | IndirectDispatchCounter& operator=(const IndirectDispatchCounter&) = delete; |
| @@ -68,8 +68,8 @@ public: | |||
| 68 | explicit Batch(IndirectDispatchCounter& value) : owner(value) {} | 68 | explicit Batch(IndirectDispatchCounter& value) : owner(value) {} |
| 69 | ~Batch() { | 69 | ~Batch() { |
| 70 | for (auto& a : allocations) { | 70 | for (auto& a : allocations) { |
| 71 | if (a.buffer) owner.fn<PFN_vkDestroyBuffer>("vkDestroyBuffer")(owner.device_, a.buffer, nullptr); | 71 | if (a.buffer) owner.vk_.destroy_buffer(owner.device_, a.buffer, nullptr); |
| 72 | if (a.memory) owner.fn<PFN_vkFreeMemory>("vkFreeMemory")(owner.device_, a.memory, nullptr); | 72 | if (a.memory) owner.vk_.free_memory(owner.device_, a.memory, nullptr); |
| 73 | } | 73 | } |
| 74 | } | 74 | } |
| 75 | Batch(const Batch&) = delete; | 75 | Batch(const Batch&) = delete; |
| @@ -80,8 +80,8 @@ public: | |||
| 80 | CountedDispatch& out) { | 80 | CountedDispatch& out) { |
| 81 | out = {}; | 81 | out = {}; |
| 82 | constexpr VkDeviceSize record_bytes = 3 * sizeof(std::uint32_t); | 82 | constexpr VkDeviceSize record_bytes = 3 * sizeof(std::uint32_t); |
| 83 | if (!arguments || (!count && !indirect_group_budget()) || stride < record_bytes || stride % 4 || | 83 | if (!arguments || (!count && (count_offset || !indirect_group_budget())) || stride < record_bytes || |
| 84 | (argument_offset % 4) != 0 || (count_offset % 4) != 0 || !max_count || | 84 | stride % 4 || (argument_offset % 4) != 0 || (count_offset % 4) != 0 || !max_count || |
| 85 | !owner.limits_.maxComputeWorkGroupCount[0] || !owner.make_pipeline()) return false; | 85 | !owner.limits_.maxComputeWorkGroupCount[0] || !owner.make_pipeline()) return false; |
| 86 | if (VkDeviceSize(max_count) > std::numeric_limits<VkDeviceSize>::max() / record_bytes) | 86 | if (VkDeviceSize(max_count) > std::numeric_limits<VkDeviceSize>::max() / record_bytes) |
| 87 | return false; | 87 | return false; |
| @@ -90,42 +90,50 @@ public: | |||
| 90 | info.size = bytes; | 90 | info.size = bytes; |
| 91 | info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | | 91 | info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | |
| 92 | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; | 92 | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; |
| 93 | Allocation scratch{}; | 93 | Allocation a{}; |
| 94 | if (owner.fn<PFN_vkCreateBuffer>("vkCreateBuffer")(owner.device_, &info, nullptr, &scratch.buffer) != VK_SUCCESS) | 94 | const auto cleanup = [&] { |
| 95 | if (a.buffer) owner.vk_.destroy_buffer(owner.device_, a.buffer, nullptr); | ||
| 96 | if (a.memory) owner.vk_.free_memory(owner.device_, a.memory, nullptr); | ||
| 95 | return false; | 97 | return false; |
| 96 | allocations.push_back(scratch); // all failure paths free it with the batch | 98 | }; |
| 97 | auto& a = allocations.back(); | 99 | if (owner.vk_.create_buffer(owner.device_, &info, nullptr, &a.buffer) != VK_SUCCESS) { |
| 100 | a.buffer = VK_NULL_HANDLE; | ||
| 101 | return false; | ||
| 102 | } | ||
| 98 | VkMemoryRequirements requirements{}; | 103 | VkMemoryRequirements requirements{}; |
| 99 | owner.fn<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")( | 104 | owner.vk_.get_reqs(owner.device_, a.buffer, &requirements); |
| 100 | owner.device_, a.buffer, &requirements); | 105 | auto order = memory_type_order(owner.memory_, requirements.memoryTypeBits, 0, |
| 101 | const auto order = memory_type_order(owner.memory_, requirements.memoryTypeBits, 0, | 106 | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, requirements.size); |
| 102 | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, requirements.size); | 107 | if (!resizable_bar(owner.memory_)) { |
| 103 | if (order.empty()) return false; | 108 | std::stable_partition(order.begin(), order.end(), [&](std::uint32_t t) { |
| 109 | const auto f = owner.memory_.memoryTypes[t].propertyFlags; | ||
| 110 | return (f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && !(f & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); | ||
| 111 | }); | ||
| 112 | } | ||
| 113 | if (order.empty()) return cleanup(); | ||
| 104 | VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; | 114 | VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; |
| 105 | flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; | 115 | flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; |
| 106 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; | 116 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; |
| 107 | allocation.allocationSize = requirements.size; | 117 | allocation.allocationSize = requirements.size; |
| 108 | const auto alloc_memory = owner.fn<PFN_vkAllocateMemory>("vkAllocateMemory"); | ||
| 109 | for (const std::uint32_t memory_type : order) { | 118 | for (const std::uint32_t memory_type : order) { |
| 110 | allocation.memoryTypeIndex = memory_type; | 119 | allocation.memoryTypeIndex = memory_type; |
| 111 | if (alloc_memory(owner.device_, &allocation, nullptr, &a.memory) == VK_SUCCESS) break; | 120 | if (owner.vk_.allocate_memory(owner.device_, &allocation, nullptr, &a.memory) == VK_SUCCESS) break; |
| 112 | a.memory = VK_NULL_HANDLE; | 121 | a.memory = VK_NULL_HANDLE; |
| 113 | } | 122 | } |
| 114 | if (!a.memory || | 123 | if (!a.memory || owner.vk_.bind_buffer(owner.device_, a.buffer, a.memory, 0) != VK_SUCCESS) |
| 115 | owner.fn<PFN_vkBindBufferMemory>("vkBindBufferMemory")(owner.device_, a.buffer, a.memory, 0) != VK_SUCCESS) | 124 | return cleanup(); |
| 116 | return false; | ||
| 117 | const auto address = owner.fn<PFN_vkGetBufferDeviceAddress>("vkGetBufferDeviceAddress"); | ||
| 118 | VkBufferDeviceAddressInfo addr{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; | 125 | VkBufferDeviceAddressInfo addr{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; |
| 119 | addr.buffer = arguments; | 126 | addr.buffer = arguments; |
| 120 | const VkDeviceAddress args_va = address(owner.device_, &addr); | 127 | const VkDeviceAddress args_va = owner.vk_.get_address(owner.device_, &addr); |
| 121 | addr.buffer = count; | 128 | addr.buffer = count; |
| 122 | const VkDeviceAddress count_va = count ? address(owner.device_, &addr) : 0; | 129 | const VkDeviceAddress count_va = count ? owner.vk_.get_address(owner.device_, &addr) : 0; |
| 123 | addr.buffer = a.buffer; | 130 | addr.buffer = a.buffer; |
| 124 | const VkDeviceAddress output_va = address(owner.device_, &addr); | 131 | const VkDeviceAddress output_va = owner.vk_.get_address(owner.device_, &addr); |
| 125 | if (!args_va || (count && !count_va) || !output_va || | 132 | if (!args_va || (count && !count_va) || !output_va || |
| 126 | argument_offset > UINT64_MAX - args_va || count_offset > UINT64_MAX - count_va) | 133 | argument_offset > UINT64_MAX - args_va || (count && count_offset > UINT64_MAX - count_va)) |
| 127 | return false; | 134 | return cleanup(); |
| 128 | out = {a.buffer, 0, args_va + argument_offset, count_va + count_offset, | 135 | allocations.push_back(a); |
| 136 | out = {a.buffer, 0, args_va + argument_offset, count ? count_va + count_offset : 0, | ||
| 129 | output_va, stride, max_count}; | 137 | output_va, stride, max_count}; |
| 130 | return true; | 138 | return true; |
| 131 | } | 139 | } |
| @@ -134,13 +142,12 @@ public: | |||
| 134 | std::unique_ptr<Batch> batch() { return std::make_unique<Batch>(*this); } | 142 | std::unique_ptr<Batch> batch() { return std::make_unique<Batch>(*this); } |
| 135 | 143 | ||
| 136 | void emit(VkCommandBuffer cb, const CountedDispatch& job) const { | 144 | void emit(VkCommandBuffer cb, const CountedDispatch& job) const { |
| 137 | const auto barrier = fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier"); | ||
| 138 | VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 145 | VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 139 | before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; | 146 | before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; |
| 140 | before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; | 147 | before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; |
| 141 | barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, | 148 | vk_.cmd_barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, |
| 142 | 0, 1, &before, 0, nullptr, 0, nullptr); | 149 | 0, 1, &before, 0, nullptr, 0, nullptr); |
| 143 | fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); | 150 | vk_.cmd_bind_pipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); |
| 144 | struct Push { | 151 | struct Push { |
| 145 | VkDeviceAddress arguments, count, output; | 152 | VkDeviceAddress arguments, count, output; |
| 146 | std::uint32_t stride_words, first_record, records, budget, has_count; | 153 | std::uint32_t stride_words, first_record, records, budget, has_count; |
| @@ -156,29 +163,62 @@ public: | |||
| 156 | const std::uint32_t count = std::uint32_t(std::min<VkDeviceSize>(chunk_limit, job.max_count - first)); | 163 | const std::uint32_t count = std::uint32_t(std::min<VkDeviceSize>(chunk_limit, job.max_count - first)); |
| 157 | const Push push{job.arguments + first * job.stride, job.count, job.output + first * 12, | 164 | const Push push{job.arguments + first * job.stride, job.count, job.output + first * 12, |
| 158 | job.stride / 4, std::uint32_t(first), count, indirect_group_budget(), job.count != 0}; | 165 | job.stride / 4, std::uint32_t(first), count, indirect_group_budget(), job.count != 0}; |
| 159 | fn<PFN_vkCmdPushConstants>("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, | 166 | vk_.cmd_push_constants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); |
| 160 | 0, sizeof(push), &push); | 167 | vk_.cmd_dispatch(cb, (count - 1u) / 64u + 1u, 1, 1); |
| 161 | fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb, (count - 1u) / 64u + 1u, 1, 1); | ||
| 162 | first += count; | 168 | first += count; |
| 163 | } | 169 | } |
| 164 | VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 170 | VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 165 | after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT; | 171 | after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT; |
| 166 | after.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_MEMORY_READ_BIT | | 172 | after.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_MEMORY_READ_BIT | |
| 167 | VK_ACCESS_MEMORY_WRITE_BIT; | 173 | VK_ACCESS_MEMORY_WRITE_BIT; |
| 168 | barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, | 174 | vk_.cmd_barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, |
| 169 | 0, 1, &after, 0, nullptr, 0, nullptr); | 175 | 0, 1, &after, 0, nullptr, 0, nullptr); |
| 170 | } | 176 | } |
| 171 | 177 | ||
| 172 | private: | 178 | private: |
| 173 | template<typename T> T fn(const char* name) const { return reinterpret_cast<T>(get_(device_, name)); } | 179 | struct Functions { |
| 180 | PFN_vkCreateBuffer create_buffer = nullptr; | ||
| 181 | PFN_vkDestroyBuffer destroy_buffer = nullptr; | ||
| 182 | PFN_vkGetBufferMemoryRequirements get_reqs = nullptr; | ||
| 183 | PFN_vkAllocateMemory allocate_memory = nullptr; | ||
| 184 | PFN_vkFreeMemory free_memory = nullptr; | ||
| 185 | PFN_vkBindBufferMemory bind_buffer = nullptr; | ||
| 186 | PFN_vkGetBufferDeviceAddress get_address = nullptr; | ||
| 187 | PFN_vkCreateShaderModule create_shader = nullptr; | ||
| 188 | PFN_vkDestroyShaderModule destroy_shader = nullptr; | ||
| 189 | PFN_vkCreatePipelineLayout create_layout = nullptr; | ||
| 190 | PFN_vkDestroyPipelineLayout destroy_layout = nullptr; | ||
| 191 | PFN_vkCreateComputePipelines create_pipelines = nullptr; | ||
| 192 | PFN_vkDestroyPipeline destroy_pipeline = nullptr; | ||
| 193 | PFN_vkCmdPipelineBarrier cmd_barrier = nullptr; | ||
| 194 | PFN_vkCmdBindPipeline cmd_bind_pipeline = nullptr; | ||
| 195 | PFN_vkCmdPushConstants cmd_push_constants = nullptr; | ||
| 196 | PFN_vkCmdDispatch cmd_dispatch = nullptr; | ||
| 197 | }; | ||
| 198 | |||
| 199 | template<typename T> bool load_fn(T& out, const char* name) const { | ||
| 200 | out = reinterpret_cast<T>(get_(device_, name)); | ||
| 201 | return out != nullptr; | ||
| 202 | } | ||
| 203 | |||
| 174 | bool make_pipeline() { | 204 | bool make_pipeline() { |
| 175 | if (pipeline_) return true; | 205 | if (pipeline_) return true; |
| 176 | for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", | 206 | Functions f{}; |
| 177 | "vkAllocateMemory", "vkFreeMemory", "vkBindBufferMemory", "vkGetBufferDeviceAddress", | 207 | if (!load_fn(f.create_buffer, "vkCreateBuffer") || !load_fn(f.destroy_buffer, "vkDestroyBuffer") || |
| 178 | "vkCreateShaderModule", "vkDestroyShaderModule", "vkCreatePipelineLayout", | 208 | !load_fn(f.get_reqs, "vkGetBufferMemoryRequirements") || |
| 179 | "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", | 209 | !load_fn(f.allocate_memory, "vkAllocateMemory") || !load_fn(f.free_memory, "vkFreeMemory") || |
| 180 | "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"}) | 210 | !load_fn(f.bind_buffer, "vkBindBufferMemory") || |
| 181 | if (!get_(device_, name)) return false; | 211 | !load_fn(f.get_address, "vkGetBufferDeviceAddress") || |
| 212 | !load_fn(f.create_shader, "vkCreateShaderModule") || | ||
| 213 | !load_fn(f.destroy_shader, "vkDestroyShaderModule") || | ||
| 214 | !load_fn(f.create_layout, "vkCreatePipelineLayout") || | ||
| 215 | !load_fn(f.destroy_layout, "vkDestroyPipelineLayout") || | ||
| 216 | !load_fn(f.create_pipelines, "vkCreateComputePipelines") || | ||
| 217 | !load_fn(f.destroy_pipeline, "vkDestroyPipeline") || | ||
| 218 | !load_fn(f.cmd_barrier, "vkCmdPipelineBarrier") || | ||
| 219 | !load_fn(f.cmd_bind_pipeline, "vkCmdBindPipeline") || | ||
| 220 | !load_fn(f.cmd_push_constants, "vkCmdPushConstants") || !load_fn(f.cmd_dispatch, "vkCmdDispatch")) | ||
| 221 | return false; | ||
| 182 | VkShaderModule module = VK_NULL_HANDLE; | 222 | VkShaderModule module = VK_NULL_HANDLE; |
| 183 | VkPipelineLayout layout = VK_NULL_HANDLE; | 223 | VkPipelineLayout layout = VK_NULL_HANDLE; |
| 184 | VkPipeline pipeline = VK_NULL_HANDLE; | 224 | VkPipeline pipeline = VK_NULL_HANDLE; |
| @@ -186,26 +226,26 @@ private: | |||
| 186 | shader.codeSize = sizeof(indirect_dispatch_count_spirv); | 226 | shader.codeSize = sizeof(indirect_dispatch_count_spirv); |
| 187 | shader.pCode = indirect_dispatch_count_spirv; | 227 | shader.pCode = indirect_dispatch_count_spirv; |
| 188 | const aftermath::ShaderName aftermath_name("(runtime) indirect_dispatch_count"); | 228 | const aftermath::ShaderName aftermath_name("(runtime) indirect_dispatch_count"); |
| 189 | bool ok = fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS; | 229 | bool ok = f.create_shader(device_, &shader, nullptr, &module) == VK_SUCCESS; |
| 190 | const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, 48}; | 230 | const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, 48}; |
| 191 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | 231 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; |
| 192 | layout_info.pushConstantRangeCount = 1; | 232 | layout_info.pushConstantRangeCount = 1; |
| 193 | layout_info.pPushConstantRanges = ⦥ | 233 | layout_info.pPushConstantRanges = ⦥ |
| 194 | ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; | 234 | ok = ok && f.create_layout(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; |
| 195 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | 235 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; |
| 196 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | 236 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; |
| 197 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; | 237 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; |
| 198 | info.stage.module = module; | 238 | info.stage.module = module; |
| 199 | info.stage.pName = "main"; | 239 | info.stage.pName = "main"; |
| 200 | info.layout = layout; | 240 | info.layout = layout; |
| 201 | ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")( | 241 | ok = ok && f.create_pipelines(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; |
| 202 | device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; | 242 | if (module) f.destroy_shader(device_, module, nullptr); |
| 203 | if (module) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, module, nullptr); | ||
| 204 | if (!ok) { | 243 | if (!ok) { |
| 205 | if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr); | 244 | if (pipeline) f.destroy_pipeline(device_, pipeline, nullptr); |
| 206 | if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr); | 245 | if (layout) f.destroy_layout(device_, layout, nullptr); |
| 207 | return false; | 246 | return false; |
| 208 | } | 247 | } |
| 248 | vk_ = f; | ||
| 209 | layout_ = layout; | 249 | layout_ = layout; |
| 210 | pipeline_ = pipeline; | 250 | pipeline_ = pipeline; |
| 211 | return true; | 251 | return true; |
| @@ -214,6 +254,7 @@ private: | |||
| 214 | VkDevice device_; | 254 | VkDevice device_; |
| 215 | VkPhysicalDeviceMemoryProperties memory_; | 255 | VkPhysicalDeviceMemoryProperties memory_; |
| 216 | VkPhysicalDeviceLimits limits_; | 256 | VkPhysicalDeviceLimits limits_; |
| 257 | Functions vk_{}; | ||
| 217 | VkPipelineLayout layout_ = VK_NULL_HANDLE; | 258 | VkPipelineLayout layout_ = VK_NULL_HANDLE; |
| 218 | VkPipeline pipeline_ = VK_NULL_HANDLE; | 259 | VkPipeline pipeline_ = VK_NULL_HANDLE; |
| 219 | }; | 260 | }; |
diff --git a/runtime/src/vulkan_memory.h b/runtime/src/vulkan_memory.h index a818ce205..6c5e14840 100644 --- a/runtime/src/vulkan_memory.h +++ b/runtime/src/vulkan_memory.h | |||
| @@ -35,24 +35,44 @@ inline bool resizable_bar(const VkPhysicalDeviceMemoryProperties& memory) { | |||
| 35 | return false; | 35 | return false; |
| 36 | } | 36 | } |
| 37 | 37 | ||
| 38 | // True for a DEVICE_LOCAL | HOST_VISIBLE type in a device-local heap no larger than the BAR window. Without | ||
| 39 | // Resizable BAR that heap is the only VRAM the CPU can write, shared by every host-visible allocation that prefers | ||
| 40 | // VRAM (the arena, upload buffers). Once it is full the NVIDIA driver answers VK_ERROR_OUT_OF_HOST_MEMORY there. | ||
| 41 | inline bool bar_window_type(const VkPhysicalDeviceMemoryProperties& memory, std::uint32_t index) { | ||
| 42 | constexpr VkMemoryPropertyFlags wanted = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; | ||
| 43 | if (index >= memory.memoryTypeCount || index >= VK_MAX_MEMORY_TYPES) return false; | ||
| 44 | const VkMemoryType& type = memory.memoryTypes[index]; | ||
| 45 | if ((type.propertyFlags & wanted) != wanted || type.heapIndex >= memory.memoryHeapCount) return false; | ||
| 46 | const VkMemoryHeap& heap = memory.memoryHeaps[type.heapIndex]; | ||
| 47 | return (heap.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) && heap.size <= kBarWindowBytes; | ||
| 48 | } | ||
| 49 | |||
| 38 | // The memory types to try for an allocation of `size` bytes, best first: those with `required | preferred`, then | 50 | // The memory types to try for an allocation of `size` bytes, best first: those with `required | preferred`, then |
| 39 | // those with only `required`. A type whose heap is smaller than the allocation is left out, as the allocation would | 51 | // those with only `required`. A type whose heap is smaller than the allocation is left out, as the allocation would |
| 40 | // break VUID-vkAllocateMemory-pAllocateInfo-01713 (some drivers still return VK_SUCCESS). Without Resizable BAR the | 52 | // break VUID-vkAllocateMemory-pAllocateInfo-01713 (some drivers still return VK_SUCCESS). Without Resizable BAR the |
| 41 | // heap of DEVICE_LOCAL | HOST_VISIBLE memory is typically 256 MiB or less, so a larger host-visible allocation falls | 53 | // heap of DEVICE_LOCAL | HOST_VISIBLE memory is typically 256 MiB or less, so a larger host-visible allocation falls |
| 42 | // through to system memory. A heap that is big enough but already partly used is left to the driver: a failed | 54 | // through to system memory. A heap that is big enough but already partly used is left to the driver: a failed |
| 43 | // vkAllocateMemory moves on to the next type. | 55 | // vkAllocateMemory moves on to the next type. Only an allocation that asks for both DEVICE_LOCAL and HOST_VISIBLE |
| 56 | // (the arena, upload buffers with Resizable BAR) tries a BAR-window type (bar_window_type) in its place; the others | ||
| 57 | // try it last. A texture or a staging buffer there takes the window from the arena, and once VRAM is full the window | ||
| 58 | // is too, so trying it early costs a failed call on every allocation before system memory. | ||
| 44 | inline std::vector<std::uint32_t> memory_type_order(const VkPhysicalDeviceMemoryProperties& memory, | 59 | inline std::vector<std::uint32_t> memory_type_order(const VkPhysicalDeviceMemoryProperties& memory, |
| 45 | std::uint32_t type_bits, VkMemoryPropertyFlags required, | 60 | std::uint32_t type_bits, VkMemoryPropertyFlags required, |
| 46 | VkMemoryPropertyFlags preferred, VkDeviceSize size) { | 61 | VkMemoryPropertyFlags preferred, VkDeviceSize size) { |
| 47 | std::vector<std::uint32_t> order; | 62 | std::vector<std::uint32_t> order; |
| 63 | std::vector<std::uint32_t> window; | ||
| 64 | constexpr VkMemoryPropertyFlags both = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; | ||
| 65 | const bool wants_window = ((required | preferred) & both) == both; | ||
| 48 | for (const VkMemoryPropertyFlags flags : {required | preferred, required}) { | 66 | for (const VkMemoryPropertyFlags flags : {required | preferred, required}) { |
| 49 | for (std::uint32_t i = 0; i < memory.memoryTypeCount && i < VK_MAX_MEMORY_TYPES; ++i) { | 67 | for (std::uint32_t i = 0; i < memory.memoryTypeCount && i < VK_MAX_MEMORY_TYPES; ++i) { |
| 50 | const VkMemoryType& type = memory.memoryTypes[i]; | 68 | const VkMemoryType& type = memory.memoryTypes[i]; |
| 51 | if (!(type_bits & (1u << i)) || (type.propertyFlags & flags) != flags) continue; | 69 | if (!(type_bits & (1u << i)) || (type.propertyFlags & flags) != flags) continue; |
| 52 | if (type.heapIndex >= memory.memoryHeapCount || memory.memoryHeaps[type.heapIndex].size < size) continue; | 70 | if (type.heapIndex >= memory.memoryHeapCount || memory.memoryHeaps[type.heapIndex].size < size) continue; |
| 53 | if (std::find(order.begin(), order.end(), i) == order.end()) order.push_back(i); | 71 | std::vector<std::uint32_t>& list = !wants_window && bar_window_type(memory, i) ? window : order; |
| 72 | if (std::find(list.begin(), list.end(), i) == list.end()) list.push_back(i); | ||
| 54 | } | 73 | } |
| 55 | } | 74 | } |
| 75 | order.insert(order.end(), window.begin(), window.end()); | ||
| 56 | return order; | 76 | return order; |
| 57 | } | 77 | } |
| 58 | 78 | ||
diff --git a/runtime/src/vulkan_predicate.h b/runtime/src/vulkan_predicate.h index 87d58b546..de8ed3aa0 100644 --- a/runtime/src/vulkan_predicate.h +++ b/runtime/src/vulkan_predicate.h | |||
| @@ -4,11 +4,14 @@ | |||
| 4 | #define VK_NO_PROTOTYPES | 4 | #define VK_NO_PROTOTYPES |
| 5 | #endif | 5 | #endif |
| 6 | #include <vulkan/vulkan.h> | 6 | #include <vulkan/vulkan.h> |
| 7 | #include <algorithm> | ||
| 7 | #include <cstdint> | 8 | #include <cstdint> |
| 8 | #include <memory> | 9 | #include <memory> |
| 9 | #include <initializer_list> | 10 | #include <initializer_list> |
| 11 | #include <vector> | ||
| 10 | #include "predicate_reduce_spv.h" | 12 | #include "predicate_reduce_spv.h" |
| 11 | #include "vulkan_aftermath.h" | 13 | #include "vulkan_aftermath.h" |
| 14 | #include "vulkan_memory.h" | ||
| 12 | 15 | ||
| 13 | namespace leonida { | 16 | namespace leonida { |
| 14 | struct PredicateCapture { | 17 | struct PredicateCapture { |
| @@ -24,9 +27,9 @@ public: | |||
| 24 | PredicateReducer(PFN_vkGetDeviceProcAddr get, VkDevice device, VkPhysicalDeviceMemoryProperties memory, | 27 | PredicateReducer(PFN_vkGetDeviceProcAddr get, VkDevice device, VkPhysicalDeviceMemoryProperties memory, |
| 25 | VkDeviceSize max_range) : get_(get), device_(device), memory_(memory), max_range_(max_range) {} | 28 | VkDeviceSize max_range) : get_(get), device_(device), memory_(memory), max_range_(max_range) {} |
| 26 | ~PredicateReducer() { | 29 | ~PredicateReducer() { |
| 27 | if (pipeline_) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline_, nullptr); | 30 | if (pipeline_) vk_.destroy_pipeline(device_, pipeline_, nullptr); |
| 28 | if (layout_) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout_, nullptr); | 31 | if (layout_) vk_.destroy_layout(device_, layout_, nullptr); |
| 29 | if (set_layout_) fn<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(device_, set_layout_, nullptr); | 32 | if (set_layout_) vk_.destroy_set_layout(device_, set_layout_, nullptr); |
| 30 | } | 33 | } |
| 31 | PredicateReducer(const PredicateReducer&) = delete; | 34 | PredicateReducer(const PredicateReducer&) = delete; |
| 32 | PredicateReducer& operator=(const PredicateReducer&) = delete; | 35 | PredicateReducer& operator=(const PredicateReducer&) = delete; |
| @@ -42,9 +45,9 @@ public: | |||
| 42 | std::uint32_t count = 0, next = 0; | 45 | std::uint32_t count = 0, next = 0; |
| 43 | explicit Batch(PredicateReducer& r) : owner(r) {} | 46 | explicit Batch(PredicateReducer& r) : owner(r) {} |
| 44 | ~Batch() { | 47 | ~Batch() { |
| 45 | if (pool) owner.fn<PFN_vkDestroyDescriptorPool>("vkDestroyDescriptorPool")(owner.device_, pool, nullptr); | 48 | if (pool) owner.vk_.destroy_pool(owner.device_, pool, nullptr); |
| 46 | if (buffer) owner.fn<PFN_vkDestroyBuffer>("vkDestroyBuffer")(owner.device_, buffer, nullptr); | 49 | if (buffer) owner.vk_.destroy_buffer(owner.device_, buffer, nullptr); |
| 47 | if (memory) owner.fn<PFN_vkFreeMemory>("vkFreeMemory")(owner.device_, memory, nullptr); | 50 | if (memory) owner.vk_.free_memory(owner.device_, memory, nullptr); |
| 48 | } | 51 | } |
| 49 | Batch(const Batch&) = delete; | 52 | Batch(const Batch&) = delete; |
| 50 | Batch& operator=(const Batch&) = delete; | 53 | Batch& operator=(const Batch&) = delete; |
| @@ -65,33 +68,57 @@ public: | |||
| 65 | buffer.size = b->bytes; | 68 | buffer.size = b->bytes; |
| 66 | buffer.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | | 69 | buffer.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | |
| 67 | VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; | 70 | VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; |
| 68 | if (fn<PFN_vkCreateBuffer>("vkCreateBuffer")(device_, &buffer, nullptr, &b->buffer) != VK_SUCCESS) return {}; | 71 | if (vk_.create_buffer(device_, &buffer, nullptr, &b->buffer) != VK_SUCCESS) { |
| 72 | b->buffer = VK_NULL_HANDLE; | ||
| 73 | return {}; | ||
| 74 | } | ||
| 69 | VkMemoryRequirements requirements{}; | 75 | VkMemoryRequirements requirements{}; |
| 70 | fn<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(device_, b->buffer, &requirements); | 76 | vk_.get_reqs(device_, b->buffer, &requirements); |
| 71 | std::uint32_t type = UINT32_MAX; | 77 | std::vector<std::uint32_t> order; |
| 72 | for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) { | 78 | if (memory_.memoryHeapCount) { |
| 73 | if (!(requirements.memoryTypeBits & (1u << i))) continue; | 79 | order = memory_type_order(memory_, requirements.memoryTypeBits, 0, |
| 74 | if (type == UINT32_MAX) type = i; | 80 | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, requirements.size); |
| 75 | if (memory_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { type = i; break; } | 81 | } else { |
| 82 | for (const VkMemoryPropertyFlags flags : | ||
| 83 | {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT), VkMemoryPropertyFlags(0)}) { | ||
| 84 | for (std::uint32_t i = 0; i < memory_.memoryTypeCount && i < VK_MAX_MEMORY_TYPES; ++i) { | ||
| 85 | if (!(requirements.memoryTypeBits & (1u << i)) || | ||
| 86 | (memory_.memoryTypes[i].propertyFlags & flags) != flags) | ||
| 87 | continue; | ||
| 88 | if (std::find(order.begin(), order.end(), i) == order.end()) order.push_back(i); | ||
| 89 | } | ||
| 90 | } | ||
| 91 | } | ||
| 92 | if (!resizable_bar(memory_)) { | ||
| 93 | std::stable_partition(order.begin(), order.end(), [&](std::uint32_t t) { | ||
| 94 | const auto f = memory_.memoryTypes[t].propertyFlags; | ||
| 95 | return (f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && !(f & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); | ||
| 96 | }); | ||
| 76 | } | 97 | } |
| 77 | if (type == UINT32_MAX) return {}; | 98 | if (order.empty()) return {}; |
| 78 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | 99 | VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; |
| 79 | allocation.allocationSize = requirements.size; | 100 | allocation.allocationSize = requirements.size; |
| 80 | allocation.memoryTypeIndex = type; | 101 | for (const std::uint32_t type : order) { |
| 81 | if (fn<PFN_vkAllocateMemory>("vkAllocateMemory")(device_, &allocation, nullptr, &b->memory) != VK_SUCCESS || | 102 | allocation.memoryTypeIndex = type; |
| 82 | fn<PFN_vkBindBufferMemory>("vkBindBufferMemory")(device_, b->buffer, b->memory, 0) != VK_SUCCESS) return {}; | 103 | if (vk_.allocate_memory(device_, &allocation, nullptr, &b->memory) == VK_SUCCESS) break; |
| 104 | b->memory = VK_NULL_HANDLE; | ||
| 105 | } | ||
| 106 | if (!b->memory || vk_.bind_buffer(device_, b->buffer, b->memory, 0) != VK_SUCCESS) return {}; | ||
| 83 | const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; | 107 | const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; |
| 84 | VkDescriptorPoolCreateInfo pool{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; | 108 | VkDescriptorPoolCreateInfo pool{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; |
| 85 | pool.maxSets = 1; pool.poolSizeCount = 1; pool.pPoolSizes = &size; | 109 | pool.maxSets = 1; pool.poolSizeCount = 1; pool.pPoolSizes = &size; |
| 86 | if (fn<PFN_vkCreateDescriptorPool>("vkCreateDescriptorPool")(device_, &pool, nullptr, &b->pool) != VK_SUCCESS) return {}; | 110 | if (vk_.create_pool(device_, &pool, nullptr, &b->pool) != VK_SUCCESS) { |
| 111 | b->pool = VK_NULL_HANDLE; | ||
| 112 | return {}; | ||
| 113 | } | ||
| 87 | VkDescriptorSetAllocateInfo sets{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; | 114 | VkDescriptorSetAllocateInfo sets{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; |
| 88 | sets.descriptorPool = b->pool; sets.descriptorSetCount = 1; sets.pSetLayouts = &set_layout_; | 115 | sets.descriptorPool = b->pool; sets.descriptorSetCount = 1; sets.pSetLayouts = &set_layout_; |
| 89 | if (fn<PFN_vkAllocateDescriptorSets>("vkAllocateDescriptorSets")(device_, &sets, &b->set) != VK_SUCCESS) return {}; | 116 | if (vk_.allocate_sets(device_, &sets, &b->set) != VK_SUCCESS) return {}; |
| 90 | const VkDescriptorBufferInfo info{b->buffer, 0, b->bytes}; | 117 | const VkDescriptorBufferInfo info{b->buffer, 0, b->bytes}; |
| 91 | VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; | 118 | VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; |
| 92 | write.dstSet = b->set; write.dstBinding = 0; write.descriptorCount = 1; | 119 | write.dstSet = b->set; write.dstBinding = 0; write.descriptorCount = 1; |
| 93 | write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &info; | 120 | write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &info; |
| 94 | fn<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(device_, 1, &write, 0, nullptr); | 121 | vk_.update_sets(device_, 1, &write, 0, nullptr); |
| 95 | return b; | 122 | return b; |
| 96 | } | 123 | } |
| 97 | 124 | ||
| @@ -101,10 +128,10 @@ public: | |||
| 101 | VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 128 | VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 102 | before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_MEMORY_READ_BIT; | 129 | before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_MEMORY_READ_BIT; |
| 103 | before.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; | 130 | before.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; |
| 104 | const auto barrier = fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier"); | 131 | vk_.cmd_barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 105 | barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr); | 132 | 0, 1, &before, 0, nullptr, 0, nullptr); |
| 106 | const VkBufferCopy copy{p.source_offset, p.offset, 8}; | 133 | const VkBufferCopy copy{p.source_offset, p.offset, 8}; |
| 107 | fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer")(cb, p.source, p.scratch, 1, ©); | 134 | vk_.cmd_copy_buffer(cb, p.source, p.scratch, 1, ©); |
| 108 | // The application's PREDICATION state does not describe this internal transfer read. Preserve snapshot | 135 | // The application's PREDICATION state does not describe this internal transfer read. Preserve snapshot |
| 109 | // semantics when it subsequently transitions and overwrites the source in the same command list. | 136 | // semantics when it subsequently transitions and overwrites the source in the same command list. |
| 110 | VkBufferMemoryBarrier source_done{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; | 137 | VkBufferMemoryBarrier source_done{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; |
| @@ -112,36 +139,84 @@ public: | |||
| 112 | source_done.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; | 139 | source_done.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; |
| 113 | source_done.srcQueueFamilyIndex = source_done.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 140 | source_done.srcQueueFamilyIndex = source_done.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; |
| 114 | source_done.buffer = p.source; source_done.offset = p.source_offset; source_done.size = 8; | 141 | source_done.buffer = p.source; source_done.offset = p.source_offset; source_done.size = 8; |
| 115 | barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, | 142 | vk_.cmd_barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, |
| 116 | 0, 0, nullptr, 1, &source_done, 0, nullptr); | 143 | 0, 0, nullptr, 1, &source_done, 0, nullptr); |
| 117 | VkMemoryBarrier compute{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 144 | VkMemoryBarrier compute{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 118 | compute.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; | 145 | compute.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; |
| 119 | compute.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; | 146 | compute.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; |
| 120 | barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &compute, 0, nullptr, 0, nullptr); | 147 | vk_.cmd_barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, |
| 121 | fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); | 148 | 0, 1, &compute, 0, nullptr, 0, nullptr); |
| 122 | fn<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &p.set, 0, nullptr); | 149 | vk_.cmd_bind_pipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); |
| 150 | vk_.cmd_bind_sets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &p.set, 0, nullptr); | ||
| 123 | const std::uint32_t index = static_cast<std::uint32_t>(p.offset / 4); | 151 | const std::uint32_t index = static_cast<std::uint32_t>(p.offset / 4); |
| 124 | fn<PFN_vkCmdPushConstants>("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, 4, &index); | 152 | vk_.cmd_push_constants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, 4, &index); |
| 125 | fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb, 1, 1, 1); | 153 | vk_.cmd_dispatch(cb, 1, 1, 1); |
| 126 | VkMemoryBarrier condition{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 154 | VkMemoryBarrier condition{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 127 | condition.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; | 155 | condition.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; |
| 128 | condition.dstAccessMask = VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT; | 156 | condition.dstAccessMask = VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT; |
| 129 | barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT, | 157 | vk_.cmd_barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT, |
| 130 | 0, 1, &condition, 0, nullptr, 0, nullptr); | 158 | 0, 1, &condition, 0, nullptr, 0, nullptr); |
| 131 | } | 159 | } |
| 132 | 160 | ||
| 133 | private: | 161 | private: |
| 134 | template<class T> T fn(const char* name) const { return reinterpret_cast<T>(get_(device_, name)); } | 162 | struct Functions { |
| 163 | PFN_vkCreateBuffer create_buffer = nullptr; | ||
| 164 | PFN_vkDestroyBuffer destroy_buffer = nullptr; | ||
| 165 | PFN_vkGetBufferMemoryRequirements get_reqs = nullptr; | ||
| 166 | PFN_vkAllocateMemory allocate_memory = nullptr; | ||
| 167 | PFN_vkFreeMemory free_memory = nullptr; | ||
| 168 | PFN_vkBindBufferMemory bind_buffer = nullptr; | ||
| 169 | PFN_vkCreateDescriptorPool create_pool = nullptr; | ||
| 170 | PFN_vkDestroyDescriptorPool destroy_pool = nullptr; | ||
| 171 | PFN_vkAllocateDescriptorSets allocate_sets = nullptr; | ||
| 172 | PFN_vkUpdateDescriptorSets update_sets = nullptr; | ||
| 173 | PFN_vkCreateShaderModule create_shader = nullptr; | ||
| 174 | PFN_vkDestroyShaderModule destroy_shader = nullptr; | ||
| 175 | PFN_vkCreateDescriptorSetLayout create_set_layout = nullptr; | ||
| 176 | PFN_vkDestroyDescriptorSetLayout destroy_set_layout = nullptr; | ||
| 177 | PFN_vkCreatePipelineLayout create_layout = nullptr; | ||
| 178 | PFN_vkDestroyPipelineLayout destroy_layout = nullptr; | ||
| 179 | PFN_vkCreateComputePipelines create_pipelines = nullptr; | ||
| 180 | PFN_vkDestroyPipeline destroy_pipeline = nullptr; | ||
| 181 | PFN_vkCmdCopyBuffer cmd_copy_buffer = nullptr; | ||
| 182 | PFN_vkCmdPipelineBarrier cmd_barrier = nullptr; | ||
| 183 | PFN_vkCmdBindPipeline cmd_bind_pipeline = nullptr; | ||
| 184 | PFN_vkCmdBindDescriptorSets cmd_bind_sets = nullptr; | ||
| 185 | PFN_vkCmdPushConstants cmd_push_constants = nullptr; | ||
| 186 | PFN_vkCmdDispatch cmd_dispatch = nullptr; | ||
| 187 | }; | ||
| 188 | |||
| 189 | template<class T> bool load_fn(T& out, const char* name) const { | ||
| 190 | out = reinterpret_cast<T>(get_(device_, name)); | ||
| 191 | return out != nullptr; | ||
| 192 | } | ||
| 193 | |||
| 135 | bool make_pipeline() { | 194 | bool make_pipeline() { |
| 136 | if (pipeline_) return true; | 195 | if (pipeline_) return true; |
| 137 | // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything. | 196 | // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything. |
| 138 | for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", "vkAllocateMemory", | 197 | Functions f{}; |
| 139 | "vkFreeMemory", "vkBindBufferMemory", "vkCreateDescriptorPool", "vkDestroyDescriptorPool", | 198 | if (!load_fn(f.create_buffer, "vkCreateBuffer") || !load_fn(f.destroy_buffer, "vkDestroyBuffer") || |
| 140 | "vkAllocateDescriptorSets", "vkUpdateDescriptorSets", "vkCreateShaderModule", "vkDestroyShaderModule", | 199 | !load_fn(f.get_reqs, "vkGetBufferMemoryRequirements") || |
| 141 | "vkCreateDescriptorSetLayout", "vkDestroyDescriptorSetLayout", "vkCreatePipelineLayout", | 200 | !load_fn(f.allocate_memory, "vkAllocateMemory") || !load_fn(f.free_memory, "vkFreeMemory") || |
| 142 | "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", "vkCmdCopyBuffer", | 201 | !load_fn(f.bind_buffer, "vkBindBufferMemory") || |
| 143 | "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdBindDescriptorSets", "vkCmdPushConstants", "vkCmdDispatch"}) | 202 | !load_fn(f.create_pool, "vkCreateDescriptorPool") || |
| 144 | if (!get_(device_, name)) return false; | 203 | !load_fn(f.destroy_pool, "vkDestroyDescriptorPool") || |
| 204 | !load_fn(f.allocate_sets, "vkAllocateDescriptorSets") || | ||
| 205 | !load_fn(f.update_sets, "vkUpdateDescriptorSets") || | ||
| 206 | !load_fn(f.create_shader, "vkCreateShaderModule") || | ||
| 207 | !load_fn(f.destroy_shader, "vkDestroyShaderModule") || | ||
| 208 | !load_fn(f.create_set_layout, "vkCreateDescriptorSetLayout") || | ||
| 209 | !load_fn(f.destroy_set_layout, "vkDestroyDescriptorSetLayout") || | ||
| 210 | !load_fn(f.create_layout, "vkCreatePipelineLayout") || | ||
| 211 | !load_fn(f.destroy_layout, "vkDestroyPipelineLayout") || | ||
| 212 | !load_fn(f.create_pipelines, "vkCreateComputePipelines") || | ||
| 213 | !load_fn(f.destroy_pipeline, "vkDestroyPipeline") || | ||
| 214 | !load_fn(f.cmd_copy_buffer, "vkCmdCopyBuffer") || | ||
| 215 | !load_fn(f.cmd_barrier, "vkCmdPipelineBarrier") || | ||
| 216 | !load_fn(f.cmd_bind_pipeline, "vkCmdBindPipeline") || | ||
| 217 | !load_fn(f.cmd_bind_sets, "vkCmdBindDescriptorSets") || | ||
| 218 | !load_fn(f.cmd_push_constants, "vkCmdPushConstants") || !load_fn(f.cmd_dispatch, "vkCmdDispatch")) | ||
| 219 | return false; | ||
| 145 | VkDescriptorSetLayout set = VK_NULL_HANDLE; | 220 | VkDescriptorSetLayout set = VK_NULL_HANDLE; |
| 146 | VkPipelineLayout layout = VK_NULL_HANDLE; | 221 | VkPipelineLayout layout = VK_NULL_HANDLE; |
| 147 | VkShaderModule shader = VK_NULL_HANDLE; | 222 | VkShaderModule shader = VK_NULL_HANDLE; |
| @@ -149,28 +224,29 @@ private: | |||
| 149 | const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; | 224 | const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; |
| 150 | VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; | 225 | VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; |
| 151 | set_info.bindingCount = 1; set_info.pBindings = &binding; | 226 | set_info.bindingCount = 1; set_info.pBindings = &binding; |
| 152 | bool ok = fn<PFN_vkCreateDescriptorSetLayout>("vkCreateDescriptorSetLayout")(device_, &set_info, nullptr, &set) == VK_SUCCESS; | 227 | bool ok = f.create_set_layout(device_, &set_info, nullptr, &set) == VK_SUCCESS; |
| 153 | const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 4}; | 228 | const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 4}; |
| 154 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | 229 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; |
| 155 | layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set; | 230 | layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set; |
| 156 | layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; | 231 | layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; |
| 157 | ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; | 232 | ok = ok && f.create_layout(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; |
| 158 | VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | 233 | VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; |
| 159 | module.codeSize = sizeof(predicate_reduce_spirv); module.pCode = predicate_reduce_spirv; | 234 | module.codeSize = sizeof(predicate_reduce_spirv); module.pCode = predicate_reduce_spirv; |
| 160 | const aftermath::ShaderName aftermath_name("(runtime) predicate_reduce"); | 235 | const aftermath::ShaderName aftermath_name("(runtime) predicate_reduce"); |
| 161 | ok = ok && fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &module, nullptr, &shader) == VK_SUCCESS; | 236 | ok = ok && f.create_shader(device_, &module, nullptr, &shader) == VK_SUCCESS; |
| 162 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | 237 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; |
| 163 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | 238 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; |
| 164 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main"; | 239 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main"; |
| 165 | info.layout = layout; | 240 | info.layout = layout; |
| 166 | ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; | 241 | ok = ok && f.create_pipelines(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; |
| 167 | if (shader) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, shader, nullptr); | 242 | if (shader) f.destroy_shader(device_, shader, nullptr); |
| 168 | if (!ok) { | 243 | if (!ok) { |
| 169 | if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr); | 244 | if (pipeline) f.destroy_pipeline(device_, pipeline, nullptr); |
| 170 | if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr); | 245 | if (layout) f.destroy_layout(device_, layout, nullptr); |
| 171 | if (set) fn<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(device_, set, nullptr); | 246 | if (set) f.destroy_set_layout(device_, set, nullptr); |
| 172 | return false; | 247 | return false; |
| 173 | } | 248 | } |
| 249 | vk_ = f; | ||
| 174 | set_layout_ = set; layout_ = layout; pipeline_ = pipeline; | 250 | set_layout_ = set; layout_ = layout; pipeline_ = pipeline; |
| 175 | return true; | 251 | return true; |
| 176 | } | 252 | } |
| @@ -178,6 +254,7 @@ private: | |||
| 178 | VkDevice device_; | 254 | VkDevice device_; |
| 179 | VkPhysicalDeviceMemoryProperties memory_; | 255 | VkPhysicalDeviceMemoryProperties memory_; |
| 180 | VkDeviceSize max_range_; | 256 | VkDeviceSize max_range_; |
| 257 | Functions vk_{}; | ||
| 181 | VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE; | 258 | VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE; |
| 182 | VkPipelineLayout layout_ = VK_NULL_HANDLE; | 259 | VkPipelineLayout layout_ = VK_NULL_HANDLE; |
| 183 | VkPipeline pipeline_ = VK_NULL_HANDLE; | 260 | VkPipeline pipeline_ = VK_NULL_HANDLE; |
diff --git a/runtime/src/vulkan_predicated_copy.h b/runtime/src/vulkan_predicated_copy.h index 1da4f8f6a..2cc0e38fd 100644 --- a/runtime/src/vulkan_predicated_copy.h +++ b/runtime/src/vulkan_predicated_copy.h | |||
| @@ -21,9 +21,9 @@ public: | |||
| 21 | PredicatedBufferCopier(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits) | 21 | PredicatedBufferCopier(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits) |
| 22 | : get_(get), device_(device), limits_(limits) {} | 22 | : get_(get), device_(device), limits_(limits) {} |
| 23 | ~PredicatedBufferCopier() { | 23 | ~PredicatedBufferCopier() { |
| 24 | if(pipeline_)fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_,pipeline_,nullptr); | 24 | if (pipeline_) vk_.destroy_pipeline(device_, pipeline_, nullptr); |
| 25 | if(layout_)fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_,layout_,nullptr); | 25 | if (layout_) vk_.destroy_layout(device_, layout_, nullptr); |
| 26 | if(set_layout_)fn<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(device_,set_layout_,nullptr); | 26 | if (set_layout_) vk_.destroy_set_layout(device_, set_layout_, nullptr); |
| 27 | } | 27 | } |
| 28 | PredicatedBufferCopier(const PredicatedBufferCopier&)=delete; | 28 | PredicatedBufferCopier(const PredicatedBufferCopier&)=delete; |
| 29 | PredicatedBufferCopier& operator=(const PredicatedBufferCopier&)=delete; | 29 | PredicatedBufferCopier& operator=(const PredicatedBufferCopier&)=delete; |
| @@ -31,7 +31,7 @@ public: | |||
| 31 | PredicatedBufferCopier& owner; | 31 | PredicatedBufferCopier& owner; |
| 32 | std::vector<VkDescriptorPool> pools; | 32 | std::vector<VkDescriptorPool> pools; |
| 33 | explicit Batch(PredicatedBufferCopier& value):owner(value){} | 33 | explicit Batch(PredicatedBufferCopier& value):owner(value){} |
| 34 | ~Batch(){for(auto pool:pools)owner.fn<PFN_vkDestroyDescriptorPool>("vkDestroyDescriptorPool")(owner.device_,pool,nullptr);} | 34 | ~Batch(){for(auto pool:pools)owner.vk_.destroy_pool(owner.device_,pool,nullptr);} |
| 35 | bool prepare(VkBuffer source,VkBuffer destination,VkDeviceSize src,VkDeviceSize dst,VkDeviceSize bytes, | 35 | bool prepare(VkBuffer source,VkBuffer destination,VkDeviceSize src,VkDeviceSize dst,VkDeviceSize bytes, |
| 36 | std::vector<PredicatedCopyDispatch>& out) { | 36 | std::vector<PredicatedCopyDispatch>& out) { |
| 37 | out.clear(); | 37 | out.clear(); |
| @@ -61,14 +61,17 @@ public: | |||
| 61 | VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; | 61 | VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; |
| 62 | pool_info.maxSets=count;pool_info.poolSizeCount=1;pool_info.pPoolSizes=&size; | 62 | pool_info.maxSets=count;pool_info.poolSizeCount=1;pool_info.pPoolSizes=&size; |
| 63 | VkDescriptorPool pool=VK_NULL_HANDLE; | 63 | VkDescriptorPool pool=VK_NULL_HANDLE; |
| 64 | if(owner.fn<PFN_vkCreateDescriptorPool>("vkCreateDescriptorPool")(owner.device_,&pool_info,nullptr,&pool)!=VK_SUCCESS)return false; | 64 | if(owner.vk_.create_pool(owner.device_,&pool_info,nullptr,&pool)!=VK_SUCCESS)return false; |
| 65 | // The batch is retained with the command buffer until its timeline ticket completes. | ||
| 66 | pools.push_back(pool); | ||
| 67 | const std::vector<VkDescriptorSetLayout> layouts(count,owner.set_layout_); | 65 | const std::vector<VkDescriptorSetLayout> layouts(count,owner.set_layout_); |
| 68 | std::vector<VkDescriptorSet> sets(count); | 66 | std::vector<VkDescriptorSet> sets(count); |
| 69 | VkDescriptorSetAllocateInfo allocate{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; | 67 | VkDescriptorSetAllocateInfo allocate{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; |
| 70 | allocate.descriptorPool=pool;allocate.descriptorSetCount=count;allocate.pSetLayouts=layouts.data(); | 68 | allocate.descriptorPool=pool;allocate.descriptorSetCount=count;allocate.pSetLayouts=layouts.data(); |
| 71 | if(owner.fn<PFN_vkAllocateDescriptorSets>("vkAllocateDescriptorSets")(owner.device_,&allocate,sets.data())!=VK_SUCCESS)return false; | 69 | if(owner.vk_.allocate_sets(owner.device_,&allocate,sets.data())!=VK_SUCCESS){ |
| 70 | owner.vk_.destroy_pool(owner.device_,pool,nullptr); | ||
| 71 | return false; | ||
| 72 | } | ||
| 73 | // The batch is retained with the command buffer until its timeline ticket completes. | ||
| 74 | pools.push_back(pool); | ||
| 72 | for(std::uint32_t i=0;i<count;++i){ | 75 | for(std::uint32_t i=0;i<count;++i){ |
| 73 | VkWriteDescriptorSet writes[2]{}; | 76 | VkWriteDescriptorSet writes[2]{}; |
| 74 | const VkDescriptorBufferInfo* infos[]={&windows[i].source,&windows[i].destination}; | 77 | const VkDescriptorBufferInfo* infos[]={&windows[i].source,&windows[i].destination}; |
| @@ -76,7 +79,7 @@ public: | |||
| 76 | auto& w=writes[binding];w.sType=VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;w.dstSet=sets[i]; | 79 | auto& w=writes[binding];w.sType=VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;w.dstSet=sets[i]; |
| 77 | w.dstBinding=binding;w.descriptorCount=1;w.descriptorType=VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;w.pBufferInfo=infos[binding]; | 80 | w.dstBinding=binding;w.descriptorCount=1;w.descriptorType=VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;w.pBufferInfo=infos[binding]; |
| 78 | } | 81 | } |
| 79 | owner.fn<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(owner.device_,2,writes,0,nullptr); | 82 | owner.vk_.update_sets(owner.device_,2,writes,0,nullptr); |
| 80 | out.push_back({sets[i],windows[i].src,windows[i].dst,windows[i].bytes}); | 83 | out.push_back({sets[i],windows[i].src,windows[i].dst,windows[i].bytes}); |
| 81 | } | 84 | } |
| 82 | return true; | 85 | return true; |
| @@ -84,36 +87,66 @@ public: | |||
| 84 | }; | 87 | }; |
| 85 | std::unique_ptr<Batch> batch(){return std::make_unique<Batch>(*this);} | 88 | std::unique_ptr<Batch> batch(){return std::make_unique<Batch>(*this);} |
| 86 | void emit(VkCommandBuffer cb,const std::vector<PredicatedCopyDispatch>& jobs)const{ | 89 | void emit(VkCommandBuffer cb,const std::vector<PredicatedCopyDispatch>& jobs)const{ |
| 87 | const auto barrier=fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier"); | ||
| 88 | // Barriers are unconditional even when the dispatch is skipped by conditional rendering. They order | 90 | // Barriers are unconditional even when the dispatch is skipped by conditional rendering. They order |
| 89 | // transfer producers, dependent copies, and adjacent windows whose aligned descriptors may overlap. | 91 | // transfer producers, dependent copies, and adjacent windows whose aligned descriptors may overlap. |
| 90 | for(const auto& job:jobs){ | 92 | for(const auto& job:jobs){ |
| 91 | VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 93 | VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 92 | before.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT; | 94 | before.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT; |
| 93 | before.dstAccessMask=VK_ACCESS_SHADER_READ_BIT|VK_ACCESS_SHADER_WRITE_BIT; | 95 | before.dstAccessMask=VK_ACCESS_SHADER_READ_BIT|VK_ACCESS_SHADER_WRITE_BIT; |
| 94 | barrier(cb,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,0,1,&before,0,nullptr,0,nullptr); | 96 | vk_.cmd_barrier(cb,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,0,1,&before,0,nullptr,0,nullptr); |
| 95 | fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb,VK_PIPELINE_BIND_POINT_COMPUTE,pipeline_); | 97 | vk_.cmd_bind_pipeline(cb,VK_PIPELINE_BIND_POINT_COMPUTE,pipeline_); |
| 96 | fn<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(cb,VK_PIPELINE_BIND_POINT_COMPUTE,layout_,0,1,&job.set,0,nullptr); | 98 | vk_.cmd_bind_sets(cb,VK_PIPELINE_BIND_POINT_COMPUTE,layout_,0,1,&job.set,0,nullptr); |
| 97 | const std::uint32_t push[]={job.source,job.destination,job.bytes}; | 99 | const std::uint32_t push[]={job.source,job.destination,job.bytes}; |
| 98 | fn<PFN_vkCmdPushConstants>("vkCmdPushConstants")(cb,layout_,VK_SHADER_STAGE_COMPUTE_BIT,0,sizeof(push),push); | 100 | vk_.cmd_push_constants(cb,layout_,VK_SHADER_STAGE_COMPUTE_BIT,0,sizeof(push),push); |
| 99 | fn<PFN_vkCmdDispatch>("vkCmdDispatch")(cb,(job.bytes-1u)/64u+1u,1,1); | 101 | vk_.cmd_dispatch(cb,(job.bytes-1u)/64u+1u,1,1); |
| 100 | VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 102 | VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 101 | after.srcAccessMask=VK_ACCESS_SHADER_WRITE_BIT|VK_ACCESS_SHADER_READ_BIT; | 103 | after.srcAccessMask=VK_ACCESS_SHADER_WRITE_BIT|VK_ACCESS_SHADER_READ_BIT; |
| 102 | after.dstAccessMask=VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT; | 104 | after.dstAccessMask=VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT; |
| 103 | barrier(cb,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,1,&after,0,nullptr,0,nullptr); | 105 | vk_.cmd_barrier(cb,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,1,&after,0,nullptr,0,nullptr); |
| 104 | } | 106 | } |
| 105 | } | 107 | } |
| 106 | private: | 108 | private: |
| 107 | template<class T>T fn(const char* name)const{return reinterpret_cast<T>(get_(device_,name));} | 109 | struct Functions { |
| 110 | PFN_vkCreateDescriptorPool create_pool = nullptr; | ||
| 111 | PFN_vkDestroyDescriptorPool destroy_pool = nullptr; | ||
| 112 | PFN_vkAllocateDescriptorSets allocate_sets = nullptr; | ||
| 113 | PFN_vkUpdateDescriptorSets update_sets = nullptr; | ||
| 114 | PFN_vkCreateShaderModule create_shader = nullptr; | ||
| 115 | PFN_vkDestroyShaderModule destroy_shader = nullptr; | ||
| 116 | PFN_vkCreateDescriptorSetLayout create_set_layout = nullptr; | ||
| 117 | PFN_vkDestroyDescriptorSetLayout destroy_set_layout = nullptr; | ||
| 118 | PFN_vkCreatePipelineLayout create_layout = nullptr; | ||
| 119 | PFN_vkDestroyPipelineLayout destroy_layout = nullptr; | ||
| 120 | PFN_vkCreateComputePipelines create_pipelines = nullptr; | ||
| 121 | PFN_vkDestroyPipeline destroy_pipeline = nullptr; | ||
| 122 | PFN_vkCmdPipelineBarrier cmd_barrier = nullptr; | ||
| 123 | PFN_vkCmdBindPipeline cmd_bind_pipeline = nullptr; | ||
| 124 | PFN_vkCmdBindDescriptorSets cmd_bind_sets = nullptr; | ||
| 125 | PFN_vkCmdPushConstants cmd_push_constants = nullptr; | ||
| 126 | PFN_vkCmdDispatch cmd_dispatch = nullptr; | ||
| 127 | }; | ||
| 128 | template<class T> bool load_fn(T& out, const char* name) const { | ||
| 129 | out = reinterpret_cast<T>(get_(device_, name)); | ||
| 130 | return out != nullptr; | ||
| 131 | } | ||
| 108 | bool make_pipeline() { | 132 | bool make_pipeline() { |
| 109 | if (pipeline_) return true; | 133 | if (pipeline_) return true; |
| 110 | // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything. | 134 | // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything. |
| 111 | for (const char* name : {"vkCreateDescriptorPool", "vkDestroyDescriptorPool", | 135 | Functions f{}; |
| 112 | "vkAllocateDescriptorSets", "vkUpdateDescriptorSets", "vkCreateShaderModule", "vkDestroyShaderModule", | 136 | if (!load_fn(f.create_pool, "vkCreateDescriptorPool") || !load_fn(f.destroy_pool, "vkDestroyDescriptorPool") || |
| 113 | "vkCreateDescriptorSetLayout", "vkDestroyDescriptorSetLayout", "vkCreatePipelineLayout", | 137 | !load_fn(f.allocate_sets, "vkAllocateDescriptorSets") || !load_fn(f.update_sets, "vkUpdateDescriptorSets") || |
| 114 | "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", | 138 | !load_fn(f.create_shader, "vkCreateShaderModule") || !load_fn(f.destroy_shader, "vkDestroyShaderModule") || |
| 115 | "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdBindDescriptorSets", "vkCmdPushConstants", "vkCmdDispatch"}) | 139 | !load_fn(f.create_set_layout, "vkCreateDescriptorSetLayout") || |
| 116 | if (!get_(device_, name)) return false; | 140 | !load_fn(f.destroy_set_layout, "vkDestroyDescriptorSetLayout") || |
| 141 | !load_fn(f.create_layout, "vkCreatePipelineLayout") || | ||
| 142 | !load_fn(f.destroy_layout, "vkDestroyPipelineLayout") || | ||
| 143 | !load_fn(f.create_pipelines, "vkCreateComputePipelines") || | ||
| 144 | !load_fn(f.destroy_pipeline, "vkDestroyPipeline") || | ||
| 145 | !load_fn(f.cmd_barrier, "vkCmdPipelineBarrier") || | ||
| 146 | !load_fn(f.cmd_bind_pipeline, "vkCmdBindPipeline") || | ||
| 147 | !load_fn(f.cmd_bind_sets, "vkCmdBindDescriptorSets") || | ||
| 148 | !load_fn(f.cmd_push_constants, "vkCmdPushConstants") || !load_fn(f.cmd_dispatch, "vkCmdDispatch")) | ||
| 149 | return false; | ||
| 117 | VkDescriptorSetLayout set = VK_NULL_HANDLE; | 150 | VkDescriptorSetLayout set = VK_NULL_HANDLE; |
| 118 | VkPipelineLayout layout = VK_NULL_HANDLE; | 151 | VkPipelineLayout layout = VK_NULL_HANDLE; |
| 119 | VkShaderModule shader = VK_NULL_HANDLE; | 152 | VkShaderModule shader = VK_NULL_HANDLE; |
| @@ -121,34 +154,36 @@ private: | |||
| 121 | const VkDescriptorSetLayoutBinding bindings[]={{0,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr},{1,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr}}; | 154 | const VkDescriptorSetLayoutBinding bindings[]={{0,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr},{1,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr}}; |
| 122 | VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; | 155 | VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; |
| 123 | set_info.bindingCount = 2; set_info.pBindings = bindings; | 156 | set_info.bindingCount = 2; set_info.pBindings = bindings; |
| 124 | bool ok = fn<PFN_vkCreateDescriptorSetLayout>("vkCreateDescriptorSetLayout")(device_, &set_info, nullptr, &set) == VK_SUCCESS; | 157 | bool ok = f.create_set_layout(device_, &set_info, nullptr, &set) == VK_SUCCESS; |
| 125 | const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 12}; | 158 | const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 12}; |
| 126 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; | 159 | VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; |
| 127 | layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set; | 160 | layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set; |
| 128 | layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; | 161 | layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; |
| 129 | ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; | 162 | ok = ok && f.create_layout(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; |
| 130 | VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | 163 | VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; |
| 131 | module.codeSize = sizeof(predicated_copy_spirv); module.pCode = predicated_copy_spirv; | 164 | module.codeSize = sizeof(predicated_copy_spirv); module.pCode = predicated_copy_spirv; |
| 132 | const aftermath::ShaderName aftermath_name("(runtime) predicated_copy"); | 165 | const aftermath::ShaderName aftermath_name("(runtime) predicated_copy"); |
| 133 | ok = ok && fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &module, nullptr, &shader) == VK_SUCCESS; | 166 | ok = ok && f.create_shader(device_, &module, nullptr, &shader) == VK_SUCCESS; |
| 134 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; | 167 | VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; |
| 135 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; | 168 | info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; |
| 136 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main"; | 169 | info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main"; |
| 137 | info.layout = layout; | 170 | info.layout = layout; |
| 138 | ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; | 171 | ok = ok && f.create_pipelines(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; |
| 139 | if (shader) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, shader, nullptr); | 172 | if (shader) f.destroy_shader(device_, shader, nullptr); |
| 140 | if (!ok) { | 173 | if (!ok) { |
| 141 | if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr); | 174 | if (pipeline) f.destroy_pipeline(device_, pipeline, nullptr); |
| 142 | if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr); | 175 | if (layout) f.destroy_layout(device_, layout, nullptr); |
| 143 | if (set) fn<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(device_, set, nullptr); | 176 | if (set) f.destroy_set_layout(device_, set, nullptr); |
| 144 | return false; | 177 | return false; |
| 145 | } | 178 | } |
| 179 | vk_ = f; | ||
| 146 | set_layout_ = set; layout_ = layout; pipeline_ = pipeline; | 180 | set_layout_ = set; layout_ = layout; pipeline_ = pipeline; |
| 147 | return true; | 181 | return true; |
| 148 | } | 182 | } |
| 149 | PFN_vkGetDeviceProcAddr get_; | 183 | PFN_vkGetDeviceProcAddr get_; |
| 150 | VkDevice device_; | 184 | VkDevice device_; |
| 151 | VkPhysicalDeviceLimits limits_; | 185 | VkPhysicalDeviceLimits limits_; |
| 186 | Functions vk_{}; | ||
| 152 | VkDescriptorSetLayout set_layout_=VK_NULL_HANDLE; | 187 | VkDescriptorSetLayout set_layout_=VK_NULL_HANDLE; |
| 153 | VkPipelineLayout layout_=VK_NULL_HANDLE; | 188 | VkPipelineLayout layout_=VK_NULL_HANDLE; |
| 154 | VkPipeline pipeline_=VK_NULL_HANDLE; | 189 | VkPipeline pipeline_=VK_NULL_HANDLE; |
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 39c63851a..c4f76e194 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h | |||
| @@ -106,6 +106,7 @@ struct ResourceBinding { | |||
| 106 | // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (the GPU has no D24): footprint copies of the depth plane convert | 106 | // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (the GPU has no D24): footprint copies of the depth plane convert |
| 107 | // (depth24.h) and clears quantise to 24 bits. | 107 | // (depth24.h) and clears quantise to 24 bits. |
| 108 | bool depth24_as_float = false; | 108 | bool depth24_as_float = false; |
| 109 | bool sample_locations_depth = false; | ||
| 109 | bool depth24 = false; // a D24 family format, native or not: depth clears are quantised to 24 bits first | 110 | bool depth24 = false; // a D24 family format, native or not: depth clears are quantised to 24 bits first |
| 110 | // A D3D12 R32G32B32 texture (12 bytes a texel) held in an R32G32B32A32 image (16): footprints keep D3D12's 12 | 111 | // A D3D12 R32G32B32 texture (12 bytes a texel) held in an R32G32B32A32 image (16): footprints keep D3D12's 12 |
| 111 | // bytes, and copies between it and a buffer are repacked by the depth24 pass (Depth24Job::rgb96). | 112 | // bytes, and copies between it and a buffer are repacked by the depth24 pass (Depth24Job::rgb96). |
| @@ -908,6 +909,7 @@ struct GraphicsPipeline { | |||
| 908 | // and stencil. Null when it cannot be built. | 909 | // and stencil. Null when it cannot be built. |
| 909 | static constexpr std::uint32_t unbound_depth = 1u << 8; | 910 | static constexpr std::uint32_t unbound_depth = 1u << 8; |
| 910 | static constexpr std::uint32_t rectangle_stage = 1u << 9; | 911 | static constexpr std::uint32_t rectangle_stage = 1u << 9; |
| 912 | static constexpr std::uint32_t custom_samples = 1u << 10; // programmable sample positions are dynamic state | ||
| 911 | // IA topology requiring a fourth-corner geometry stage. Zero when the PSO already contains the stage. | 913 | // IA topology requiring a fourth-corner geometry stage. Zero when the PSO already contains the stage. |
| 912 | std::uint32_t rectangle_variant_topology = 0; | 914 | std::uint32_t rectangle_variant_topology = 0; |
| 913 | std::function<VkPipeline(std::uint32_t flags)> variant; | 915 | std::function<VkPipeline(std::uint32_t flags)> variant; |
| @@ -919,6 +921,7 @@ struct GraphicsPipeline { | |||
| 919 | void* request_context = nullptr; | 921 | void* request_context = nullptr; |
| 920 | bool large = false; // as ComputePipeline::large | 922 | bool large = false; // as ComputePipeline::large |
| 921 | std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count | 923 | std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count |
| 924 | VkSampleCountFlags sample_grid_1 = 0, sample_grid_4 = 0; | ||
| 922 | bool async_build = false; | 925 | bool async_build = false; |
| 923 | bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation | 926 | bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation |
| 924 | std::uint64_t estimate = 0; // as ComputePipeline::estimate | 927 | std::uint64_t estimate = 0; // as ComputePipeline::estimate |
| @@ -1223,6 +1226,7 @@ struct ReplayFunctions { | |||
| 1223 | PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; | 1226 | PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; |
| 1224 | PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; | 1227 | PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; |
| 1225 | PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; | 1228 | PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; |
| 1229 | PFN_vkCmdSetSampleLocationsEXT set_sample_locations = nullptr; | ||
| 1226 | PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; | 1230 | PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; |
| 1227 | PFN_vkCmdSetDepthBounds set_depth_bounds = nullptr; // for depth-bounds pipelines only | 1231 | PFN_vkCmdSetDepthBounds set_depth_bounds = nullptr; // for depth-bounds pipelines only |
| 1228 | PFN_vkCmdDraw draw = nullptr; | 1232 | PFN_vkCmdDraw draw = nullptr; |
| @@ -1583,17 +1587,55 @@ inline float quantize_snorm(float value, double maximum) { | |||
| 1583 | return static_cast<float>(round_half_even(double(value) * maximum) / maximum); | 1587 | return static_cast<float>(round_half_even(double(value) * maximum) / maximum); |
| 1584 | } | 1588 | } |
| 1585 | 1589 | ||
| 1590 | // An sRGB format takes a linear value and stores its encoding. D3D lets an implementation place the 255 steps of | ||
| 1591 | // that encoding within 0.6 of a step of the ideal curve, and each one measured places them elsewhere: of 60 000 | ||
| 1592 | // random values, an Intel Iris Xe (driver 32.0.101.7092) stores another byte than WARP for 6 649 and an NVIDIA RTX | ||
| 1593 | // 4060 (616.92) for 3 648, in vkCmdClearColorImage and vkCmdClearAttachments alike (0.5 is 187 on the Intel GPU and | ||
| 1594 | // 188 on the other two). So the value is encoded here, the way WARP does it, and Vulkan gets the linear value in the | ||
| 1595 | // middle of that code's range (srgb8_linear), which both drivers store as that code for all 256. A GPU's own D3D12 | ||
| 1596 | // driver encodes as its Vulkan driver does, so where that differs from WARP the layer now differs from that driver: | ||
| 1597 | // WARP is the reference here, as it is for the ties of quantize_unorm and for D24. | ||
| 1598 | // | ||
| 1599 | // WARP (10.0.26100.5074) takes the value to 12 bits first - x * 4095 in single precision, rounded half up - and | ||
| 1600 | // encodes that with the curve of IEC 61966-2-1, rounded to nearest. Bisecting where its result changes gives 255 | ||
| 1601 | // floats, and this function changes at the same 255; it also agrees on 84 582 other values (docs/d3d12_vulkan.md). | ||
| 1602 | // NaN and values below 0 are 0, values above 1 are 255. | ||
| 1603 | inline unsigned srgb8_from_linear(float value) { | ||
| 1604 | if (!(value > 0.0f)) return 0; | ||
| 1605 | if (value >= 1.0f) return 255; | ||
| 1606 | // The single-precision product, rounded to nearest even whatever the thread's rounding mode (see | ||
| 1607 | // round_half_even): a double holds the product exactly (24 bits times 12), and a float keeps 24 bits of it. | ||
| 1608 | const double product = double(value) * 4095.0; | ||
| 1609 | if (product < 0.25) return 0; // rounds to the 12-bit value 0, and keeps denormals away from frexp | ||
| 1610 | int exponent = 0; | ||
| 1611 | std::frexp(product, &exponent); | ||
| 1612 | const double ulp = std::ldexp(1.0, exponent - 24); | ||
| 1613 | const double single = round_half_even(product / ulp) * ulp; | ||
| 1614 | const double linear = std::floor(single + 0.5) / 4095.0; | ||
| 1615 | const double encoded = linear < 0.0031308 ? 12.92 * linear : 1.055 * std::pow(linear, 1.0 / 2.4) - 0.055; | ||
| 1616 | return static_cast<unsigned>(std::floor(encoded * 255.0 + 0.5)); | ||
| 1617 | } | ||
| 1618 | |||
| 1619 | // The linear value an 8-bit sRGB code stands for, which is the one farthest from the values a GPU may encode as a | ||
| 1620 | // neighbouring code. | ||
| 1621 | inline float srgb8_linear(unsigned code) { | ||
| 1622 | if (code >= 255) return 1.0f; | ||
| 1623 | const double encoded = code / 255.0; | ||
| 1624 | return static_cast<float>(encoded <= 0.04045 ? encoded / 12.92 : std::pow((encoded + 0.055) / 1.055, 2.4)); | ||
| 1625 | } | ||
| 1626 | |||
| 1586 | // ClearRenderTargetView takes FLOATs even for integer RTVs. Windows D3D12 (WARP and AMD) clamps to the | 1627 | // ClearRenderTargetView takes FLOATs even for integer RTVs. Windows D3D12 (WARP and AMD) clamps to the |
| 1587 | // component range and truncates fractions. Vulkan instead interprets the matching union member as an integer | 1628 | // component range and truncates fractions. Vulkan instead interprets the matching union member as an integer |
| 1588 | // already; copying float bits changes the value without a validation error. The normalised formats are rounded like | 1629 | // already; copying float bits changes the value without a validation error. The normalised formats are rounded like |
| 1589 | // D3D (quantize_unorm, quantize_snorm). | 1630 | // D3D (quantize_unorm, quantize_snorm), and the colour channels of the sRGB formats are encoded like WARP |
| 1631 | // (srgb8_from_linear). | ||
| 1590 | inline VkClearColorValue render_target_clear_color(VkFormat format, const ClearColor& input) { | 1632 | inline VkClearColorValue render_target_clear_color(VkFormat format, const ClearColor& input) { |
| 1591 | // Integer formats convert the float numerically: NaN maps to zero, values below the range clamp to the low | 1633 | // Integer formats convert the float numerically: NaN maps to zero, values below the range clamp to the low |
| 1592 | // end, positive overflow (and +infinity) to the high end, and fractions truncate toward zero. Unsigned uses | 1634 | // end, positive overflow (and +infinity) to the high end, and fractions truncate toward zero. Unsigned uses |
| 1593 | // uint32, signed int32. A2B10G10R10 clamps RGB to 10 bits and alpha (channel 3) to 2 bits. | 1635 | // uint32, signed int32. A2B10G10R10 clamps RGB to 10 bits and alpha (channel 3) to 2 bits. |
| 1594 | constexpr double u32_max = 4294967295.0, s32_min = -2147483648.0, s32_max = 2147483647.0; | 1636 | constexpr double u32_max = 4294967295.0, s32_min = -2147483648.0, s32_max = 2147483647.0; |
| 1595 | double low = 0, high = 0, alpha_high = 0; | 1637 | double low = 0, high = 0, alpha_high = 0; |
| 1596 | bool is_integer = true, is_signed = false; | 1638 | bool is_integer = true, is_signed = false, srgb = false; |
| 1597 | std::array<double, 4> unorm{}; // the largest value of each normalised channel; 0 leaves the channel to the GPU | 1639 | std::array<double, 4> unorm{}; // the largest value of each normalised channel; 0 leaves the channel to the GPU |
| 1598 | double snorm = 0; // the largest value of a signed normalised format | 1640 | double snorm = 0; // the largest value of a signed normalised format |
| 1599 | switch (format) { | 1641 | switch (format) { |
| @@ -1630,8 +1672,9 @@ inline VkClearColorValue render_target_clear_color(VkFormat format, const ClearC | |||
| 1630 | case VK_FORMAT_A8_UNORM_KHR: is_integer = false; unorm = {0, 0, 0, 255}; break; // alpha only | 1672 | case VK_FORMAT_A8_UNORM_KHR: is_integer = false; unorm = {0, 0, 0, 255}; break; // alpha only |
| 1631 | #endif | 1673 | #endif |
| 1632 | case VK_FORMAT_R8G8B8A8_SRGB: | 1674 | case VK_FORMAT_R8G8B8A8_SRGB: |
| 1633 | case VK_FORMAT_B8G8R8A8_SRGB: // the colour channels go through the sRGB curve on the GPU | 1675 | case VK_FORMAT_B8G8R8A8_SRGB: // the colour channels are encoded below; alpha is linear |
| 1634 | is_integer = false; | 1676 | is_integer = false; |
| 1677 | srgb = true; | ||
| 1635 | unorm = {0, 0, 0, 255}; | 1678 | unorm = {0, 0, 0, 255}; |
| 1636 | break; | 1679 | break; |
| 1637 | case VK_FORMAT_A2B10G10R10_UNORM_PACK32: is_integer = false; unorm = {1023, 1023, 1023, 3}; break; | 1680 | case VK_FORMAT_A2B10G10R10_UNORM_PACK32: is_integer = false; unorm = {1023, 1023, 1023, 3}; break; |
| @@ -1645,6 +1688,7 @@ inline VkClearColorValue render_target_clear_color(VkFormat format, const ClearC | |||
| 1645 | for (std::size_t i = 0; i < input.size(); ++i) { | 1688 | for (std::size_t i = 0; i < input.size(); ++i) { |
| 1646 | if (!is_integer) { | 1689 | if (!is_integer) { |
| 1647 | if (snorm != 0) value.float32[i] = quantize_snorm(input[i], snorm); | 1690 | if (snorm != 0) value.float32[i] = quantize_snorm(input[i], snorm); |
| 1691 | else if (srgb && i < 3) value.float32[i] = srgb8_linear(srgb8_from_linear(input[i])); | ||
| 1648 | else value.float32[i] = unorm[i] != 0.0 ? quantize_unorm(input[i], unorm[i]) : input[i]; | 1692 | else value.float32[i] = unorm[i] != 0.0 ? quantize_unorm(input[i], unorm[i]) : input[i]; |
| 1649 | continue; | 1693 | continue; |
| 1650 | } | 1694 | } |
| @@ -1793,14 +1837,53 @@ inline VkImageSubresourceRange layout_range(const ResourceBinding& resource, VkI | |||
| 1793 | return range; | 1837 | return range; |
| 1794 | } | 1838 | } |
| 1795 | 1839 | ||
| 1840 | // Vulkan's Standard Sample Locations table, expressed relative to the pixel centre in sixteenths. | ||
| 1841 | inline const SamplePosition* standard_sample_positions(unsigned samples) { | ||
| 1842 | static constexpr SamplePosition one[] = {{0, 0}}; | ||
| 1843 | static constexpr SamplePosition two[] = {{4, 4}, {-4, -4}}; | ||
| 1844 | static constexpr SamplePosition four[] = {{-2, -6}, {6, -2}, {-6, 2}, {2, 6}}; | ||
| 1845 | static constexpr SamplePosition eight[] = {{1, -3}, {-1, 3}, {5, 1}, {-3, -5}, {-5, 5}, {-7, -1}, {3, 7}, {7, -7}}; | ||
| 1846 | static constexpr SamplePosition sixteen[] = {{1, 1}, {-1, -3}, {-3, 2}, {4, -1}, {-5, -2}, {2, 5}, {5, 3}, {3, -5}, | ||
| 1847 | {-2, 6}, {0, -7}, {-4, -6}, {-6, 4}, {-8, 0}, {7, -4}, {6, 7}, {-7, -8}}; | ||
| 1848 | switch (samples) { | ||
| 1849 | case 1: return one; | ||
| 1850 | case 2: return two; | ||
| 1851 | case 4: return four; | ||
| 1852 | case 8: return eight; | ||
| 1853 | case 16: return sixteen; | ||
| 1854 | default: return nullptr; | ||
| 1855 | } | ||
| 1856 | } | ||
| 1857 | |||
| 1858 | struct VulkanSampleLocations { | ||
| 1859 | std::array<VkSampleLocationEXT, 16> positions; | ||
| 1860 | VkSampleLocationsInfoEXT info; | ||
| 1861 | |||
| 1862 | const VkSampleLocationsInfoEXT* set(unsigned samples, const SamplePositions* pattern) { | ||
| 1863 | const bool custom = pattern && pattern->samples == samples && SamplePositions::valid_grid(samples, pattern->pixels); | ||
| 1864 | const auto* source = custom ? pattern->positions.data() : standard_sample_positions(samples); | ||
| 1865 | if (!source) return nullptr; | ||
| 1866 | const unsigned side = custom && pattern->pixels == 4 ? 2 : 1; | ||
| 1867 | const unsigned count = samples * side * side; | ||
| 1868 | for (unsigned i = 0; i < count; ++i) | ||
| 1869 | positions[i] = {(source[i].x + 8) / 16.f, (source[i].y + 8) / 16.f}; | ||
| 1870 | info = {VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT, nullptr, VkSampleCountFlagBits(samples), {side, side}, | ||
| 1871 | count, positions.data()}; | ||
| 1872 | return &info; | ||
| 1873 | } | ||
| 1874 | }; | ||
| 1875 | |||
| 1796 | inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, | 1876 | inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, |
| 1797 | const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout, | 1877 | const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout, |
| 1798 | VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access, | 1878 | VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access, |
| 1799 | VkPipelineStageFlags dst_stages) { | 1879 | VkPipelineStageFlags dst_stages, const SamplePositions* active_samples = nullptr) { |
| 1800 | restrict_to_queue(vk, src_stages, src_access); | 1880 | restrict_to_queue(vk, src_stages, src_access); |
| 1801 | restrict_to_queue(vk, dst_stages, dst_access); | 1881 | restrict_to_queue(vk, dst_stages, dst_access); |
| 1802 | VkImageMemoryBarrier barrier{}; | 1882 | VkImageMemoryBarrier barrier{}; |
| 1803 | barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; | 1883 | barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; |
| 1884 | VulkanSampleLocations locations; | ||
| 1885 | if (resource.sample_locations_depth && old_layout != VK_IMAGE_LAYOUT_UNDEFINED && old_layout != new_layout) | ||
| 1886 | barrier.pNext = locations.set(resource.samples, active_samples); | ||
| 1804 | barrier.srcAccessMask = src_access; | 1887 | barrier.srcAccessMask = src_access; |
| 1805 | barrier.dstAccessMask = dst_access; | 1888 | barrier.dstAccessMask = dst_access; |
| 1806 | barrier.oldLayout = old_layout; | 1889 | barrier.oldLayout = old_layout; |
| @@ -1990,7 +2073,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com | |||
| 1990 | // when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run | 2073 | // when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run |
| 1991 | // expects; with not_zeroed, it is only moved. The tracker records it. | 2074 | // expects; with not_zeroed, it is only moved. The tracker records it. |
| 1992 | inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, | 2075 | inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, |
| 1993 | ResourceId id, LayoutPieces& pieces, VkImageLayout layout, LayoutTracker* tracker) { | 2076 | ResourceId id, LayoutPieces& pieces, VkImageLayout layout, LayoutTracker* tracker, const SamplePositions* active_samples = nullptr) { |
| 1994 | constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; | 2077 | constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; |
| 1995 | for (auto& piece : pieces) { | 2078 | for (auto& piece : pieces) { |
| 1996 | if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; | 2079 | if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; |
| @@ -2003,7 +2086,7 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer | |||
| 2003 | (vk.compute_copy_aspects(resource.format) & piece.range.aspectMask) == piece.range.aspectMask; | 2086 | (vk.compute_copy_aspects(resource.format) & piece.range.aspectMask) == piece.range.aspectMask; |
| 2004 | if (resource.not_zeroed || (!can_clear && !color && !compute_depth)) { | 2087 | if (resource.not_zeroed || (!can_clear && !color && !compute_depth)) { |
| 2005 | image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, | 2088 | image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, |
| 2006 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); | 2089 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); |
| 2007 | } else if (fmt.block > 1 || !can_clear) { | 2090 | } else if (fmt.block > 1 || !can_clear) { |
| 2008 | const bool can_zero = | 2091 | const bool can_zero = |
| 2009 | vk.copy_buffer_to_image && | 2092 | vk.copy_buffer_to_image && |
| @@ -2012,7 +2095,7 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer | |||
| 2012 | const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); | 2095 | const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); |
| 2013 | image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, | 2096 | image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, |
| 2014 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, | 2097 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, |
| 2015 | VK_PIPELINE_STAGE_TRANSFER_BIT); | 2098 | VK_PIPELINE_STAGE_TRANSFER_BIT, active_samples); |
| 2016 | bool zeroed = true; | 2099 | bool zeroed = true; |
| 2017 | for (auto aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) | 2100 | for (auto aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) |
| 2018 | if (piece.range.aspectMask & aspect) | 2101 | if (piece.range.aspectMask & aspect) |
| @@ -2020,16 +2103,16 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer | |||
| 2020 | image_barrier(vk, command_buffer, resource, piece.range, dst, layout, | 2103 | image_barrier(vk, command_buffer, resource, piece.range, dst, layout, |
| 2021 | zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0, | 2104 | zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0, |
| 2022 | zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, | 2105 | zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, |
| 2023 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); | 2106 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); |
| 2024 | } else { | 2107 | } else { |
| 2025 | image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, | 2108 | image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, |
| 2026 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); | 2109 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); |
| 2027 | } | 2110 | } |
| 2028 | } else { | 2111 | } else { |
| 2029 | const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); | 2112 | const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); |
| 2030 | image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, | 2113 | image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, |
| 2031 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, | 2114 | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, |
| 2032 | VK_PIPELINE_STAGE_TRANSFER_BIT); | 2115 | VK_PIPELINE_STAGE_TRANSFER_BIT, active_samples); |
| 2033 | if (piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) { | 2116 | if (piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) { |
| 2034 | const VkClearColorValue zero{}; | 2117 | const VkClearColorValue zero{}; |
| 2035 | vk.clear_color_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); | 2118 | vk.clear_color_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); |
| @@ -2038,7 +2121,7 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer | |||
| 2038 | vk.clear_depth_stencil_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); | 2121 | vk.clear_depth_stencil_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); |
| 2039 | } | 2122 | } |
| 2040 | image_barrier(vk, command_buffer, resource, piece.range, dst, layout, VK_ACCESS_TRANSFER_WRITE_BIT, | 2123 | image_barrier(vk, command_buffer, resource, piece.range, dst, layout, VK_ACCESS_TRANSFER_WRITE_BIT, |
| 2041 | VK_PIPELINE_STAGE_TRANSFER_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); | 2124 | VK_PIPELINE_STAGE_TRANSFER_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); |
| 2042 | } | 2125 | } |
| 2043 | piece.layout = layout; | 2126 | piece.layout = layout; |
| 2044 | if (tracker) tracker->set(id, piece.range, layout); | 2127 | if (tracker) tracker->set(id, piece.range, layout); |
| @@ -2548,10 +2631,10 @@ inline ReplayResult keep_around_resolve(const ReplayFunctions& vk, Prepared& p) | |||
| 2548 | // promotion lets the copy run in place. Anything else is moved to `wanted` and tracked. | 2631 | // promotion lets the copy run in place. Anything else is moved to `wanted` and tracked. |
| 2549 | inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer command_buffer, | 2632 | inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer command_buffer, |
| 2550 | const ResourceBinding& resource, ResourceId id, const VkImageSubresourceRange& range, | 2633 | const ResourceBinding& resource, ResourceId id, const VkImageSubresourceRange& range, |
| 2551 | VkImageLayout wanted, VkAccessFlags access, LayoutTracker* tracker) { | 2634 | VkImageLayout wanted, VkAccessFlags access, LayoutTracker* tracker, const SamplePositions* active_samples = nullptr) { |
| 2552 | const VkImageLayout target = image_layout(resource, wanted); | 2635 | const VkImageLayout target = image_layout(resource, wanted); |
| 2553 | auto pieces = current(tracker, id, range, target); | 2636 | auto pieces = current(tracker, id, range, target); |
| 2554 | initialize(vk, command_buffer, resource, id, pieces, target, tracker); | 2637 | initialize(vk, command_buffer, resource, id, pieces, target, tracker, active_samples); |
| 2555 | // D3D12 orders back-to-back copies and resolves on a resource that stays in COPY_DEST or COPY_SOURCE without a | 2638 | // D3D12 orders back-to-back copies and resolves on a resource that stays in COPY_DEST or COPY_SOURCE without a |
| 2556 | // barrier from the application; Vulkan does not. A piece already in the transfer layout gets no layout | 2639 | // barrier from the application; Vulkan does not. A piece already in the transfer layout gets no layout |
| 2557 | // transition, so an earlier transfer write to it is ordered here instead (write-after-write and read-after-write, | 2640 | // transition, so an earlier transfer write to it is ordered here instead (write-after-write and read-after-write, |
| @@ -2573,7 +2656,7 @@ inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer comm | |||
| 2573 | } | 2656 | } |
| 2574 | image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, | 2657 | image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, |
| 2575 | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, | 2658 | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, |
| 2576 | VK_PIPELINE_STAGE_TRANSFER_BIT); | 2659 | VK_PIPELINE_STAGE_TRANSFER_BIT, active_samples); |
| 2577 | } | 2660 | } |
| 2578 | if (tracker) tracker->set(id, range, target); | 2661 | if (tracker) tracker->set(id, range, target); |
| 2579 | return target; | 2662 | return target; |
| @@ -2584,14 +2667,14 @@ inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer comm | |||
| 2584 | template<typename Body> | 2667 | template<typename Body> |
| 2585 | void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, | 2668 | void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, |
| 2586 | const LayoutPieces& pieces, VkImageLayout target, const VulkanAccess& state, | 2669 | const LayoutPieces& pieces, VkImageLayout target, const VulkanAccess& state, |
| 2587 | VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body) { | 2670 | VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body, const SamplePositions* active_samples = nullptr) { |
| 2588 | for (const auto& piece : pieces) { | 2671 | for (const auto& piece : pieces) { |
| 2589 | if (piece.layout == target) { | 2672 | if (piece.layout == target) { |
| 2590 | memory_barrier(vk, command_buffer, state.access, state.stages, target_access, target_stages); | 2673 | memory_barrier(vk, command_buffer, state.access, state.stages, target_access, target_stages); |
| 2591 | continue; | 2674 | continue; |
| 2592 | } | 2675 | } |
| 2593 | image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, state.access, state.stages, | 2676 | image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, state.access, state.stages, |
| 2594 | target_access, target_stages); | 2677 | target_access, target_stages, active_samples); |
| 2595 | } | 2678 | } |
| 2596 | body(); | 2679 | body(); |
| 2597 | for (const auto& piece : pieces) { | 2680 | for (const auto& piece : pieces) { |
| @@ -2600,7 +2683,7 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const | |||
| 2600 | continue; | 2683 | continue; |
| 2601 | } | 2684 | } |
| 2602 | image_barrier(vk, command_buffer, resource, piece.range, target, piece.layout, target_access, target_stages, | 2685 | image_barrier(vk, command_buffer, resource, piece.range, target, piece.layout, target_access, target_stages, |
| 2603 | state.access, state.stages); | 2686 | state.access, state.stages, active_samples); |
| 2604 | } | 2687 | } |
| 2605 | } | 2688 | } |
| 2606 | 2689 | ||
| @@ -2714,7 +2797,7 @@ namespace detail { | |||
| 2714 | // typeless texture is viewed as the format the pipeline renders. | 2797 | // typeless texture is viewed as the format the pipeline renders. |
| 2715 | template<typename Resolve> | 2798 | template<typename Resolve> |
| 2716 | ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, Resolve&& resolve, | 2799 | ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, Resolve&& resolve, |
| 2717 | const ReplayFunctions& vk, PreparedDraw& p) { | 2800 | const ReplayFunctions& vk, PreparedDraw& p, const SamplePositions* pattern) { |
| 2718 | if (arguments) { | 2801 | if (arguments) { |
| 2719 | const IndirectDrawArgs& arg = *arguments; | 2802 | const IndirectDrawArgs& arg = *arguments; |
| 2720 | const VkDeviceSize record_size = draw.mesh ? sizeof(VkDrawMeshTasksIndirectCommandEXT) | 2803 | const VkDeviceSize record_size = draw.mesh ? sizeof(VkDrawMeshTasksIndirectCommandEXT) |
| @@ -2859,6 +2942,12 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R | |||
| 2859 | for (std::size_t slot = 0; slot < p.colors.size(); ++slot) | 2942 | for (std::size_t slot = 0; slot < p.colors.size(); ++slot) |
| 2860 | if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; | 2943 | if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; |
| 2861 | if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; | 2944 | if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; |
| 2945 | if (pattern) { | ||
| 2946 | const auto counts = pattern->pixels == 1 ? pipeline->sample_grid_1 : pipeline->sample_grid_4; | ||
| 2947 | if (!vk.set_sample_locations || !SamplePositions::valid_grid(pattern->samples, pattern->pixels) || | ||
| 2948 | pattern->samples != pipeline->samples || !(counts & pattern->samples)) return unsupported_at(__LINE__); | ||
| 2949 | unbound |= GraphicsPipeline::custom_samples; | ||
| 2950 | } | ||
| 2862 | if (pipeline->requested) pipeline->requested(pipeline->request_context, unbound); | 2951 | if (pipeline->requested) pipeline->requested(pipeline->request_context, unbound); |
| 2863 | if (unbound || !p.pipeline) { | 2952 | if (unbound || !p.pipeline) { |
| 2864 | const bool indirect_rect_variant = arguments && (unbound & GraphicsPipeline::rectangle_stage); | 2953 | const bool indirect_rect_variant = arguments && (unbound & GraphicsPipeline::rectangle_stage); |
| @@ -3026,10 +3115,10 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { | |||
| 3026 | // Moves an attachment's tracked pieces to `layout` before rendering (first use zero-fills, as everywhere). | 3115 | // Moves an attachment's tracked pieces to `layout` before rendering (first use zero-fills, as everywhere). |
| 3027 | inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const PreparedDraw::Attachment& a, | 3116 | inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const PreparedDraw::Attachment& a, |
| 3028 | VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stages, | 3117 | VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stages, |
| 3029 | LayoutTracker* tracker, bool separate) { | 3118 | LayoutTracker* tracker, bool separate, const SamplePositions* active_samples = nullptr) { |
| 3030 | const VkImageSubresourceRange range = planes_for_layout(a.binding, a.range, separate); | 3119 | const VkImageSubresourceRange range = planes_for_layout(a.binding, a.range, separate); |
| 3031 | auto pieces = current(tracker, a.id, range, layout); | 3120 | auto pieces = current(tracker, a.id, range, layout); |
| 3032 | initialize(vk, command_buffer, a.binding, a.id, pieces, layout, tracker); | 3121 | initialize(vk, command_buffer, a.binding, a.id, pieces, layout, tracker, active_samples); |
| 3033 | for (const auto& piece : pieces) { | 3122 | for (const auto& piece : pieces) { |
| 3034 | if (piece.layout == layout) { | 3123 | if (piece.layout == layout) { |
| 3035 | // Attachment writes of an earlier rendering scope are not ordered with this one without a barrier. | 3124 | // Attachment writes of an earlier rendering scope are not ordered with this one without a barrier. |
| @@ -3037,7 +3126,7 @@ inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buf | |||
| 3037 | continue; | 3126 | continue; |
| 3038 | } | 3127 | } |
| 3039 | image_barrier(vk, command_buffer, a.binding, piece.range, piece.layout, layout, | 3128 | image_barrier(vk, command_buffer, a.binding, piece.range, piece.layout, layout, |
| 3040 | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, stages); | 3129 | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, stages, active_samples); |
| 3041 | } | 3130 | } |
| 3042 | if (tracker) tracker->set(a.id, range, layout); | 3131 | if (tracker) tracker->set(a.id, range, layout); |
| 3043 | } | 3132 | } |
| @@ -3489,6 +3578,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 3489 | std::uint32_t so_active = 0; | 3578 | std::uint32_t so_active = 0; |
| 3490 | out.wrote_readback = false; | 3579 | out.wrote_readback = false; |
| 3491 | out.readback_src_stages = 0; | 3580 | out.readback_src_stages = 0; |
| 3581 | const SamplePositions* sample_positions = nullptr; | ||
| 3492 | 3582 | ||
| 3493 | // Successive plane transfers use the same transient range and order their buffer accesses in emit(). | 3583 | // Successive plane transfers use the same transient range and order their buffer accesses in emit(). |
| 3494 | VkBuffer plane_scratch = VK_NULL_HANDLE; | 3584 | VkBuffer plane_scratch = VK_NULL_HANDLE; |
| @@ -4022,6 +4112,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 4022 | out.wrote_readback = true; | 4112 | out.wrote_readback = true; |
| 4023 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; | 4113 | out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; |
| 4024 | } | 4114 | } |
| 4115 | } else if (const auto* pattern = std::get_if<SamplePositions>(&command)) { | ||
| 4116 | sample_positions = pattern->samples ? pattern : nullptr; | ||
| 4025 | } else if (const auto* predication = std::get_if<Predication>(&command)) { | 4117 | } else if (const auto* predication = std::get_if<Predication>(&command)) { |
| 4026 | predicated = predication->buffer != 0; | 4118 | predicated = predication->buffer != 0; |
| 4027 | if (!predicated) continue; | 4119 | if (!predicated) continue; |
| @@ -4309,7 +4401,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 4309 | auto& prepared_draw = out.draws[out.draw_count]; | 4401 | auto& prepared_draw = out.draws[out.draw_count]; |
| 4310 | prepared_draw.reset(); | 4402 | prepared_draw.reset(); |
| 4311 | p.draw = std::uint32_t(out.draw_count++); | 4403 | p.draw = std::uint32_t(out.draw_count++); |
| 4312 | if (const auto r = detail::prepare_draw(*draw.state, draw.arguments, resolve, vk, prepared_draw); | 4404 | if (const auto r = detail::prepare_draw(*draw.state, draw.arguments, resolve, vk, prepared_draw, |
| 4405 | sample_positions); | ||
| 4313 | r != ReplayResult::success) { | 4406 | r != ReplayResult::success) { |
| 4314 | const bool strict = strict_replay(); | 4407 | const bool strict = strict_replay(); |
| 4315 | if (r != ReplayResult::unresolved_resource || strict) return r; | 4408 | if (r != ReplayResult::unresolved_resource || strict) return r; |
| @@ -4658,6 +4751,7 @@ inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions& | |||
| 4658 | template<bool Checkpoints> | 4751 | template<bool Checkpoints> |
| 4659 | inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, | 4752 | inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, |
| 4660 | LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints) { | 4753 | LayoutTracker* tracker, std::uint32_t* open_labels, const CheckpointRecorder* checkpoints) { |
| 4754 | const SamplePositions* active_samples = nullptr; | ||
| 4661 | std::uint32_t own_labels = 0; | 4755 | std::uint32_t own_labels = 0; |
| 4662 | std::uint32_t& labels = open_labels ? *open_labels : own_labels; | 4756 | std::uint32_t& labels = open_labels ? *open_labels : own_labels; |
| 4663 | const auto commands = prepared.list->commands(); | 4757 | const auto commands = prepared.list->commands(); |
| @@ -4715,6 +4809,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4715 | vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices); | 4809 | vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices); |
| 4716 | begin_statistics(); | 4810 | begin_statistics(); |
| 4717 | } | 4811 | } |
| 4812 | if (const auto* pattern = std::get_if<SamplePositions>(&command)) { | ||
| 4813 | active_samples = pattern->samples ? pattern : nullptr; | ||
| 4814 | continue; | ||
| 4815 | } | ||
| 4718 | if (const auto* predication = std::get_if<Predication>(&command)) { | 4816 | if (const auto* predication = std::get_if<Predication>(&command)) { |
| 4719 | // Conditional rendering cannot nest, so a new predicate ends the previous one first. | 4817 | // Conditional rendering cannot nest, so a new predicate ends the previous one first. |
| 4720 | if (predicate.buffer) vk.end_conditional_rendering(command_buffer); | 4818 | if (predicate.buffer) vk.end_conditional_rendering(command_buffer); |
| @@ -4756,10 +4854,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4756 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); | 4854 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); |
| 4757 | const VkImageLayout new_layout = image_layout(p.binding, to.layout); | 4855 | const VkImageLayout new_layout = image_layout(p.binding, to.layout); |
| 4758 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, from.layout)); | 4856 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, from.layout)); |
| 4759 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, from.layout), tracker); | 4857 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, from.layout), tracker, active_samples); |
| 4760 | for (const auto& piece : pieces) | 4858 | for (const auto& piece : pieces) |
| 4761 | detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, | 4859 | detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, |
| 4762 | from.access, from.stages, to.access, to.stages); | 4860 | from.access, from.stages, to.access, to.stages, active_samples); |
| 4763 | if (tracker) tracker->set(id, range, new_layout); | 4861 | if (tracker) tracker->set(id, range, new_layout); |
| 4764 | finish_depth_uav_barrier(p, new_layout, end_statistics, begin_statistics); | 4862 | finish_depth_uav_barrier(p, new_layout, end_statistics, begin_statistics); |
| 4765 | } else if (std::holds_alternative<UavBarrier>(command)) { | 4863 | } else if (std::holds_alternative<UavBarrier>(command)) { |
| @@ -4826,7 +4924,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4826 | texture->layout_before == d3d12_layout::undefined ? VK_IMAGE_LAYOUT_GENERAL : | 4924 | texture->layout_before == d3d12_layout::undefined ? VK_IMAGE_LAYOUT_GENERAL : |
| 4827 | image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); | 4925 | image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); |
| 4828 | pieces = detail::current(tracker, id, range, before); | 4926 | pieces = detail::current(tracker, id, range, before); |
| 4829 | if (!release) detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); | 4927 | if (!release) detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker, active_samples); |
| 4830 | } | 4928 | } |
| 4831 | const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); | 4929 | const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); |
| 4832 | const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); | 4930 | const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); |
| @@ -4836,6 +4934,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4836 | if (pieces.size() > few.size()) many.resize(pieces.size()); | 4934 | if (pieces.size() > few.size()) many.resize(pieces.size()); |
| 4837 | VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); | 4935 | VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); |
| 4838 | std::uint32_t barrier_count = 0; | 4936 | std::uint32_t barrier_count = 0; |
| 4937 | detail::VulkanSampleLocations locations; | ||
| 4938 | const auto* depth_locations = p.binding.sample_locations_depth ? locations.set(p.binding.samples, active_samples) : nullptr; | ||
| 4839 | for (const auto& piece : pieces) { | 4939 | for (const auto& piece : pieces) { |
| 4840 | // Released before it was ever used (the tracker still has it in UNDEFINED): nothing to order. | 4940 | // Released before it was ever used (the tracker still has it in UNDEFINED): nothing to order. |
| 4841 | if (release && piece.layout == VK_IMAGE_LAYOUT_UNDEFINED) continue; | 4941 | if (release && piece.layout == VK_IMAGE_LAYOUT_UNDEFINED) continue; |
| @@ -4846,7 +4946,9 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4846 | b.srcAccessMask = src.access; | 4946 | b.srcAccessMask = src.access; |
| 4847 | b.dstAccessMask = dst.access; | 4947 | b.dstAccessMask = dst.access; |
| 4848 | b.oldLayout = piece.layout; | 4948 | b.oldLayout = piece.layout; |
| 4849 | b.newLayout = release ? piece.layout : new_layout; | 4949 | const VkImageLayout to = release ? piece.layout : new_layout; |
| 4950 | if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED && piece.layout != to) b.pNext = depth_locations; | ||
| 4951 | b.newLayout = to; | ||
| 4850 | b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 4952 | b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; |
| 4851 | b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; | 4953 | b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; |
| 4852 | b.image = p.binding.image; | 4954 | b.image = p.binding.image; |
| @@ -4867,7 +4969,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4867 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); | 4969 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); |
| 4868 | const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); | 4970 | const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); |
| 4869 | auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); | 4971 | auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); |
| 4870 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); | 4972 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker, active_samples); |
| 4871 | auto clear_value=color_clear->color; | 4973 | auto clear_value=color_clear->color; |
| 4872 | if(p.binding.rgba4_render_fallback)for(auto& channel:clear_value) | 4974 | if(p.binding.rgba4_render_fallback)for(auto& channel:clear_value) |
| 4873 | channel=std::nearbyint(std::clamp(channel,0.0f,1.0f)*15.0f)/15.0f; | 4975 | channel=std::nearbyint(std::clamp(channel,0.0f,1.0f)*15.0f)/15.0f; |
| @@ -4877,7 +4979,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4877 | state, transfer_dst.access, transfer_dst.stages, [&] { | 4979 | state, transfer_dst.access, transfer_dst.stages, [&] { |
| 4878 | vk.clear_color_image(command_buffer, p.binding.image, image_layout(p.binding, transfer_dst.layout), | 4980 | vk.clear_color_image(command_buffer, p.binding.image, image_layout(p.binding, transfer_dst.layout), |
| 4879 | &color, 1, &p.range); | 4981 | &color, 1, &p.range); |
| 4880 | }); | 4982 | }, active_samples); |
| 4881 | continue; | 4983 | continue; |
| 4882 | } | 4984 | } |
| 4883 | const VkImageLayout attachment = image_layout(p.binding, state.layout); | 4985 | const VkImageLayout attachment = image_layout(p.binding, state.layout); |
| @@ -4898,7 +5000,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4898 | attachment_clear.clearValue.color = color; | 5000 | attachment_clear.clearValue.color = color; |
| 4899 | vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); | 5001 | vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); |
| 4900 | vk.end_rendering(command_buffer); | 5002 | vk.end_rendering(command_buffer); |
| 4901 | }); | 5003 | }, active_samples); |
| 4902 | } else if (const auto* depth_clear = std::get_if<ClearDepthStencil>(&command)) { | 5004 | } else if (const auto* depth_clear = std::get_if<ClearDepthStencil>(&command)) { |
| 4903 | if (p.skip) continue; | 5005 | if (p.skip) continue; |
| 4904 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); | 5006 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); |
| @@ -4906,7 +5008,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4906 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); | 5008 | const auto range = detail::planes_for_layout(p.binding, p.range, separate); |
| 4907 | const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); | 5009 | const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); |
| 4908 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); | 5010 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); |
| 4909 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); | 5011 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker, active_samples); |
| 4910 | float depth = p.binding.xbox_depth16_stencil8 ? detail::quantize_depth16(depth_clear->depth) | 5012 | float depth = p.binding.xbox_depth16_stencil8 ? detail::quantize_depth16(depth_clear->depth) |
| 4911 | : p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h | 5013 | : p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h |
| 4912 | : p.binding.format == VK_FORMAT_D16_UNORM | 5014 | : p.binding.format == VK_FORMAT_D16_UNORM |
| @@ -4921,7 +5023,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4921 | state, transfer_dst.access, transfer_dst.stages, [&] { | 5023 | state, transfer_dst.access, transfer_dst.stages, [&] { |
| 4922 | vk.clear_depth_stencil_image(command_buffer, p.binding.image, | 5024 | vk.clear_depth_stencil_image(command_buffer, p.binding.image, |
| 4923 | image_layout(p.binding, transfer_dst.layout), &value, 1, &p.range); | 5025 | image_layout(p.binding, transfer_dst.layout), &value, 1, &p.range); |
| 4924 | }); | 5026 | }, active_samples); |
| 4925 | continue; | 5027 | continue; |
| 4926 | } | 5028 | } |
| 4927 | const VkImageLayout attachment = image_layout(p.binding, state.layout); | 5029 | const VkImageLayout attachment = image_layout(p.binding, state.layout); |
| @@ -4942,7 +5044,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4942 | attachment_clear.clearValue.depthStencil = value; | 5044 | attachment_clear.clearValue.depthStencil = value; |
| 4943 | vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); | 5045 | vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); |
| 4944 | vk.end_rendering(command_buffer); | 5046 | vk.end_rendering(command_buffer); |
| 4945 | }); | 5047 | }, active_samples); |
| 4946 | } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) { | 5048 | } else if (const auto* uav = std::get_if<ClearUnorderedAccess>(&command)) { |
| 4947 | if (p.skip) continue; | 5049 | if (p.skip) continue; |
| 4948 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); | 5050 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); |
| @@ -4969,7 +5071,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 4969 | // Cleared in place in GENERAL, the UAV layout, which transfer clears and attachments both accept. | 5071 | // Cleared in place in GENERAL, the UAV layout, which transfer clears and attachments both accept. |
| 4970 | const VkImageLayout layout = image_layout(p.binding, state.layout); | 5072 | const VkImageLayout layout = image_layout(p.binding, state.layout); |
| 4971 | auto pieces = detail::current(tracker, id, p.range, layout); | 5073 | auto pieces = detail::current(tracker, id, p.range, layout); |
| 4972 | detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker); | 5074 | detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker, active_samples); |
| 4973 | if (p.clear_pattern_bytes) { | 5075 | if (p.clear_pattern_bytes) { |
| 4974 | detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, VK_ACCESS_TRANSFER_WRITE_BIT, | 5076 | detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, VK_ACCESS_TRANSFER_WRITE_BIT, |
| 4975 | VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { | 5077 | VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { |
| @@ -5002,14 +5104,14 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5002 | } | 5104 | } |
| 5003 | } | 5105 | } |
| 5004 | } | 5106 | } |
| 5005 | }); | 5107 | }, active_samples); |
| 5006 | continue; | 5108 | continue; |
| 5007 | } | 5109 | } |
| 5008 | if (p.rects.empty()) { | 5110 | if (p.rects.empty()) { |
| 5009 | detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, | 5111 | detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, |
| 5010 | VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { | 5112 | VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { |
| 5011 | vk.clear_color_image(command_buffer, p.binding.image, layout, &p.clear_color, 1, &p.range); | 5113 | vk.clear_color_image(command_buffer, p.binding.image, layout, &p.clear_color, 1, &p.range); |
| 5012 | }); | 5114 | }, active_samples); |
| 5013 | continue; | 5115 | continue; |
| 5014 | } | 5116 | } |
| 5015 | detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, | 5117 | detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, |
| @@ -5030,7 +5132,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5030 | attachment_clear.clearValue.color = p.clear_color; | 5132 | attachment_clear.clearValue.color = p.clear_color; |
| 5031 | vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); | 5133 | vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); |
| 5032 | vk.end_rendering(command_buffer); | 5134 | vk.end_rendering(command_buffer); |
| 5033 | }); | 5135 | }, active_samples); |
| 5034 | } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || | 5136 | } else if (std::holds_alternative<CopyBuffer>(command) || std::holds_alternative<CopyTexture>(command) || |
| 5035 | std::holds_alternative<CopyResource>(command)) { | 5137 | std::holds_alternative<CopyResource>(command)) { |
| 5036 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy); | 5138 | if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::copy); |
| @@ -5057,14 +5159,14 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5057 | // synchronization-validation run). | 5159 | // synchronization-validation run). |
| 5058 | const VkImageLayout src_layout = detail::copy_layout( | 5160 | const VkImageLayout src_layout = detail::copy_layout( |
| 5059 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), | 5161 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), |
| 5060 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); | 5162 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker, active_samples); |
| 5061 | vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, p.staged, | 5163 | vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, p.staged, |
| 5062 | std::uint32_t(p.staged_reads.size()), p.staged_reads.data()); | 5164 | std::uint32_t(p.staged_reads.size()), p.staged_reads.data()); |
| 5063 | detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, | 5165 | detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, |
| 5064 | VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); | 5166 | VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); |
| 5065 | const VkImageLayout dst_layout = detail::copy_layout( | 5167 | const VkImageLayout dst_layout = detail::copy_layout( |
| 5066 | vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), | 5168 | vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), |
| 5067 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); | 5169 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); |
| 5068 | vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout, | 5170 | vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout, |
| 5069 | std::uint32_t(p.staged_writes.size()), p.staged_writes.data()); | 5171 | std::uint32_t(p.staged_writes.size()), p.staged_writes.data()); |
| 5070 | } else if (!p.image_copies.empty()) { | 5172 | } else if (!p.image_copies.empty()) { |
| @@ -5074,10 +5176,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5074 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), | 5176 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), |
| 5075 | self ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, | 5177 | self ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, |
| 5076 | self ? VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT, | 5178 | self ? VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT, |
| 5077 | tracker); | 5179 | tracker, active_samples); |
| 5078 | const VkImageLayout dst_layout = self ? src_layout : detail::copy_layout( | 5180 | const VkImageLayout dst_layout = self ? src_layout : detail::copy_layout( |
| 5079 | vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), | 5181 | vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), |
| 5080 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); | 5182 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); |
| 5081 | const auto count = std::uint32_t(p.image_copies.size()); | 5183 | const auto count = std::uint32_t(p.image_copies.size()); |
| 5082 | const auto depth_stencil = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; | 5184 | const auto depth_stencil = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; |
| 5083 | if (std::holds_alternative<CopyResource>(command) && | 5185 | if (std::holds_alternative<CopyResource>(command) && |
| @@ -5128,13 +5230,13 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5128 | } | 5230 | } |
| 5129 | const VkImageLayout dst_layout = detail::copy_layout( | 5231 | const VkImageLayout dst_layout = detail::copy_layout( |
| 5130 | vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), | 5232 | vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), |
| 5131 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); | 5233 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); |
| 5132 | vk.copy_buffer_to_image(command_buffer, source, p.binding.image, dst_layout, | 5234 | vk.copy_buffer_to_image(command_buffer, source, p.binding.image, dst_layout, |
| 5133 | std::uint32_t(regions->size()), regions->data()); | 5235 | std::uint32_t(regions->size()), regions->data()); |
| 5134 | } else { | 5236 | } else { |
| 5135 | const VkImageLayout src_layout = detail::copy_layout( | 5237 | const VkImageLayout src_layout = detail::copy_layout( |
| 5136 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), | 5238 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), |
| 5137 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); | 5239 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker, active_samples); |
| 5138 | if (!p.has_depth24) { | 5240 | if (!p.has_depth24) { |
| 5139 | const auto target = p.tile_scratch ? p.tile_scratch : p.binding.buffer; | 5241 | const auto target = p.tile_scratch ? p.tile_scratch : p.binding.buffer; |
| 5140 | vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, target, | 5242 | vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, target, |
| @@ -5184,15 +5286,15 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5184 | const VkImageLayout dest_layout = image_layout(p.binding, dest_state.layout); | 5286 | const VkImageLayout dest_layout = image_layout(p.binding, dest_state.layout); |
| 5185 | auto source_pieces = detail::current( | 5287 | auto source_pieces = detail::current( |
| 5186 | tracker, src_id, detail::planes_for_layout(p.source, p.source_range, separate), source_layout); | 5288 | tracker, src_id, detail::planes_for_layout(p.source, p.source_range, separate), source_layout); |
| 5187 | detail::initialize(vk, command_buffer, p.source, src_id, source_pieces, source_layout, tracker); | 5289 | detail::initialize(vk, command_buffer, p.source, src_id, source_pieces, source_layout, tracker, active_samples); |
| 5188 | auto dest_pieces = detail::current( | 5290 | auto dest_pieces = detail::current( |
| 5189 | tracker, dst_id, detail::planes_for_layout(p.binding, p.range, separate), dest_layout); | 5291 | tracker, dst_id, detail::planes_for_layout(p.binding, p.range, separate), dest_layout); |
| 5190 | detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker); | 5292 | detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker, active_samples); |
| 5191 | // The texels around the rectangle, kept in `staged` across the resolve (keep_around_resolve). | 5293 | // The texels around the rectangle, kept in `staged` across the resolve (keep_around_resolve). |
| 5192 | const auto keep = [&](VkImageLayout wanted, VkAccessFlags access, auto&& copy) { | 5294 | const auto keep = [&](VkImageLayout wanted, VkAccessFlags access, auto&& copy) { |
| 5193 | const VkImageLayout layout = image_layout(p.binding, wanted); | 5295 | const VkImageLayout layout = image_layout(p.binding, wanted); |
| 5194 | detail::round_trip(vk, command_buffer, p.binding, dest_pieces, layout, dest_state, access, | 5296 | detail::round_trip(vk, command_buffer, p.binding, dest_pieces, layout, dest_state, access, |
| 5195 | VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { copy(layout); }); | 5297 | VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { copy(layout); }, active_samples); |
| 5196 | }; | 5298 | }; |
| 5197 | const auto bands = std::uint32_t(p.staged_reads.size()); | 5299 | const auto bands = std::uint32_t(p.staged_reads.size()); |
| 5198 | if (p.staged) { | 5300 | if (p.staged) { |
| @@ -5239,8 +5341,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5239 | else rendering.pStencilAttachment = &info; | 5341 | else rendering.pStencilAttachment = &info; |
| 5240 | vk.begin_rendering(command_buffer, &rendering); | 5342 | vk.begin_rendering(command_buffer, &rendering); |
| 5241 | vk.end_rendering(command_buffer); | 5343 | vk.end_rendering(command_buffer); |
| 5242 | }); | 5344 | }, active_samples); |
| 5243 | }); | 5345 | }, active_samples); |
| 5244 | if (p.staged) { | 5346 | if (p.staged) { |
| 5245 | keep(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, [&](VkImageLayout layout) { | 5347 | keep(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, [&](VkImageLayout layout) { |
| 5246 | vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, bands, | 5348 | vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, bands, |
| @@ -5251,10 +5353,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5251 | } | 5353 | } |
| 5252 | const VkImageLayout src_layout = detail::copy_layout( | 5354 | const VkImageLayout src_layout = detail::copy_layout( |
| 5253 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), | 5355 | vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), |
| 5254 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); | 5356 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker, active_samples); |
| 5255 | const VkImageLayout dst_layout = detail::copy_layout( | 5357 | const VkImageLayout dst_layout = detail::copy_layout( |
| 5256 | vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), | 5358 | vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), |
| 5257 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); | 5359 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker, active_samples); |
| 5258 | vk.resolve_image(command_buffer, p.source.image, src_layout, p.binding.image, dst_layout, 1, &p.resolve); | 5360 | vk.resolve_image(command_buffer, p.source.image, src_layout, p.binding.image, dst_layout, 1, &p.resolve); |
| 5259 | } else if (const auto* marker = std::get_if<DebugMarker>(&command)) { | 5361 | } else if (const auto* marker = std::get_if<DebugMarker>(&command)) { |
| 5260 | if (!vk.insert_label || !vk.begin_label || !vk.end_label) continue; | 5362 | if (!vk.insert_label || !vk.begin_label || !vk.end_label) continue; |
| @@ -5284,7 +5386,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5284 | if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) | 5386 | if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) |
| 5285 | detail::image_barrier(vk, command_buffer, p.binding, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, | 5387 | detail::image_barrier(vk, command_buffer, p.binding, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, |
| 5286 | piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, | 5388 | piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, |
| 5287 | any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); | 5389 | any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, active_samples); |
| 5288 | } | 5390 | } |
| 5289 | } else if (const auto* label_write=std::get_if<label::Write>(&command)) { | 5391 | } else if (const auto* label_write=std::get_if<label::Write>(&command)) { |
| 5290 | vk.gpu_label(command_buffer, *label_write); | 5392 | vk.gpu_label(command_buffer, *label_write); |
| @@ -5543,7 +5645,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5543 | if (!a.id) continue; // an unbound slot: no image view, writes are dropped | 5645 | if (!a.id) continue; // an unbound slot: no image view, writes are dropped |
| 5544 | const VkImageLayout layout = image_layout(a.binding, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); | 5646 | const VkImageLayout layout = image_layout(a.binding, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); |
| 5545 | detail::to_attachment(vk, command_buffer, a, layout, color_access, | 5647 | detail::to_attachment(vk, command_buffer, a, layout, color_access, |
| 5546 | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate); | 5648 | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate, active_samples); |
| 5547 | colors[slot].imageView = a.view; | 5649 | colors[slot].imageView = a.view; |
| 5548 | colors[slot].imageLayout = layout; | 5650 | colors[slot].imageLayout = layout; |
| 5549 | colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; | 5651 | colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; |
| @@ -5553,7 +5655,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5553 | if (d.depth.id) { | 5655 | if (d.depth.id) { |
| 5554 | const VkImageLayout layout = image_layout(d.depth.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); | 5656 | const VkImageLayout layout = image_layout(d.depth.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); |
| 5555 | detail::to_attachment(vk, command_buffer, d.depth, layout, depth_access, depth_stages, tracker, | 5657 | detail::to_attachment(vk, command_buffer, d.depth, layout, depth_access, depth_stages, tracker, |
| 5556 | separate); | 5658 | separate, active_samples); |
| 5557 | depth.imageView = d.depth.view; | 5659 | depth.imageView = d.depth.view; |
| 5558 | depth.imageLayout = layout; | 5660 | depth.imageLayout = layout; |
| 5559 | depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; | 5661 | depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; |
| @@ -5633,6 +5735,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ | |||
| 5633 | (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); | 5735 | (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); |
| 5634 | vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE); | 5736 | vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE); |
| 5635 | } | 5737 | } |
| 5738 | if (active_samples) { | ||
| 5739 | detail::VulkanSampleLocations locations; | ||
| 5740 | vk.set_sample_locations(command_buffer, locations.set(active_samples->samples, active_samples)); | ||
| 5741 | } | ||
| 5636 | vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); | 5742 | vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); |
| 5637 | vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); | 5743 | vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); |
| 5638 | vk.set_blend_constants(command_buffer, draw->blend_factor.data()); | 5744 | vk.set_blend_constants(command_buffer, draw->blend_factor.data()); |