// Milestone M0 (docs/d3d12_vulkan.md section 6): a window shows a stable clear colour for 60 frames, through the // Vulkan-backed device behind the Xbox-ABI proxy, with no Vulkan validation errors. Each frame resets the list, // moves the back buffer PRESENT -> RENDER_TARGET, clears it, moves it back, executes, presents and signals a fence. // The window is then resized, which recreates the swapchain and scales the blit. Last, the colour on screen is read // back with GDI when the window is in front and the display is in SDR (skipped otherwise, e.g. in HDR // or on a locked desktop). No shaders or game data. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. #include "vk_test_device.h" #include "../shims/d3d12_com.h" #include "../shims/d3d12_xs_device.h" #include #include #include #include #include #include #define EXPECT(condition) do { \ if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ } while (0) namespace { using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: 8-byte handle in RAX template struct Ref { T* p = nullptr; ~Ref() { reset(); } void reset() { if (p) p->Release(); p = nullptr; } T* operator->() const { return p; } }; // Returns true when the monitor containing the window is running with Windows HDR enabled // (DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020). On an HDR desktop, DWM scales SDR GDI reads // by the user's SDR white level, so fixed-tolerance on-screen colour checks do not hold (TEST-209). bool is_hdr_monitor(HWND window) { const HMONITOR target = MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST); if (!target) return false; Ref factory; if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) return false; for (UINT i = 0;; ++i) { Ref adapter; if (factory->EnumAdapters1(i, &adapter.p) == DXGI_ERROR_NOT_FOUND) break; if (!adapter.p) continue; for (UINT j = 0;; ++j) { Ref output; if (adapter->EnumOutputs(j, &output.p) == DXGI_ERROR_NOT_FOUND) break; if (!output.p) continue; DXGI_OUTPUT_DESC desc{}; if (SUCCEEDED(output->GetDesc(&desc)) && desc.Monitor == target) { Ref output6; if (SUCCEEDED(output->QueryInterface(IID_PPV_ARGS(&output6.p)))) { DXGI_OUTPUT_DESC1 desc1{}; if (SUCCEEDED(output6->GetDesc1(&desc1)) && desc1.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020) return true; } } } } return false; } LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w, LPARAM l) { return DefWindowProcW(window, message, w, l); } void pump() { MSG message; while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&message); DispatchMessageW(&message); } } void set_client_size(HWND window, int width, int height) { RECT rect{0, 0, width, height}; AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE); SetWindowPos(window, HWND_TOP, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOMOVE | SWP_NOZORDER | SWP_SHOWWINDOW); } // A driver double around the real driver: the device and the presenter get their functions through it // (VulkanDeviceInfo::get_instance_proc). It forwards every call, and when armed makes one queue submission fail // without submitting, reports one present that succeeded as another status, or fails one semaphore allocation. It // also counts the presents the real driver reported out of date, and the binary semaphores alive. namespace driver { PFN_vkGetInstanceProcAddr real_get_instance = nullptr; PFN_vkGetDeviceProcAddr real_get_device = nullptr; PFN_vkQueueSubmit real_submit = nullptr; PFN_vkQueuePresentKHR real_present = nullptr; PFN_vkCreateSemaphore real_create_semaphore = nullptr; PFN_vkDestroySemaphore real_destroy_semaphore = nullptr; VkResult fail_next_submit = VK_SUCCESS; // armed: the next vkQueueSubmit returns this and submits nothing VkResult next_present = VK_SUCCESS; // armed: the next present that succeeds reports this instead int fail_semaphore_in = 0; // armed: the n-th vkCreateSemaphore from now fails unsigned out_of_date = 0; // presents the real driver reported out of date std::vector binary; // binary semaphores alive (the device's fences are timeline ones) VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) { if (fail_next_submit != VK_SUCCESS) { const VkResult failure = fail_next_submit; fail_next_submit = VK_SUCCESS; return failure; } return real_submit(queue, count, submits, fence); } VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue queue, const VkPresentInfoKHR* info) { VkResult result = real_present(queue, info); if (result == VK_ERROR_OUT_OF_DATE_KHR) ++out_of_date; if (result == VK_SUCCESS && next_present != VK_SUCCESS) { result = next_present; next_present = VK_SUCCESS; } return result; } VKAPI_ATTR VkResult VKAPI_CALL create_semaphore(VkDevice device, const VkSemaphoreCreateInfo* info, const VkAllocationCallbacks* allocator, VkSemaphore* out) { if (fail_semaphore_in && --fail_semaphore_in == 0) return VK_ERROR_OUT_OF_HOST_MEMORY; const VkResult result = real_create_semaphore(device, info, allocator, out); bool timeline = false; for (auto* next = static_cast(info->pNext); next; next = next->pNext) if (next->sType == VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO) timeline = reinterpret_cast(next)->semaphoreType == VK_SEMAPHORE_TYPE_TIMELINE; if (result == VK_SUCCESS && !timeline) binary.push_back(*out); return result; } VKAPI_ATTR void VKAPI_CALL destroy_semaphore(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks* allocator) { std::erase(binary, semaphore); real_destroy_semaphore(device, semaphore, allocator); } VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { const std::string_view n = name; if (n == "vkQueueSubmit") return reinterpret_cast(queue_submit); if (n == "vkQueuePresentKHR") return reinterpret_cast(queue_present); if (n == "vkCreateSemaphore") return reinterpret_cast(create_semaphore); if (n == "vkDestroySemaphore") return reinterpret_cast(destroy_semaphore); return real_get_device(device, name); } VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance(VkInstance instance, const char* name) { if (std::string_view(name) == "vkGetDeviceProcAddr") return reinterpret_cast(get_device); return real_get_instance(instance, name); } void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDevice device) { real_get_instance = instance_proc; real_get_device = reinterpret_cast(instance_proc(instance, "vkGetDeviceProcAddr")); real_submit = reinterpret_cast(real_get_device(device, "vkQueueSubmit")); real_present = reinterpret_cast(real_get_device(device, "vkQueuePresentKHR")); real_create_semaphore = reinterpret_cast(real_get_device(device, "vkCreateSemaphore")); real_destroy_semaphore = reinterpret_cast(real_get_device(device, "vkDestroySemaphore")); } } // namespace driver } // namespace int main() { vktest::Device d; if (!d.create(true)) { // no Vulkan loader, device or presentation extensions: nothing to test (ctest: skipped) std::fprintf(stderr, "d3d12_present_test: no Vulkan device with presentation, skipped\n"); return 77; } WNDCLASSW window_class{}; window_class.lpfnWndProc = window_proc; window_class.hInstance = GetModuleHandleW(nullptr); window_class.lpszClassName = L"LeonidaPresentTest"; window_class.hCursor = LoadCursorW(nullptr, reinterpret_cast(IDC_ARROW)); EXPECT(RegisterClassW(&window_class)); constexpr int width = 320, height = 240; RECT frame_rect{0, 0, width, height}; AdjustWindowRect(&frame_rect, WS_OVERLAPPEDWINDOW, FALSE); HWND window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida M0: D3D12 clear on Vulkan", WS_OVERLAPPEDWINDOW, 100, 100, frame_rect.right - frame_rect.left, frame_rect.bottom - frame_rect.top, nullptr, nullptr, window_class.hInstance, nullptr); EXPECT(window); ShowWindow(window, SW_SHOWNORMAL); SetForegroundWindow(window); UpdateWindow(window); pump(); const FLOAT colour[4] = {0.2f, 0.6f, 0.9f, 1.0f}; bool screen_checked = false; { driver::install(d.instance_proc, d.instance, d.device); rt::d3d12::VulkanDeviceInfo info{}; info.get_instance_proc = driver::get_instance; info.instance = d.instance; info.physical = d.physical; info.device = d.device; info.queue = d.queue; info.queue_family = d.family; info.presentation = true; ID3D12Device* inner = nullptr; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); auto presenter = rt::d3d12::create_window_presenter(inner, window); EXPECT(presenter); D3D12_COMMAND_QUEUE_DESC queue_desc{}; Ref queue; Ref allocator; Ref list; Ref fence; Ref rtv_heap; Ref back_buffer; EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); EXPECT(SUCCEEDED(list->Close())); EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); const D3D12_CPU_DESCRIPTOR_HANDLE rtv{SIZE_T(reinterpret_cast( (*reinterpret_cast(rtv_heap.p))[9])(rtv_heap.p))}; const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; desc.Width = width; desc.Height = height; desc.DepthOrArraySize = 1; desc.MipLevels = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_PRESENT, nullptr, IID_PPV_ARGS(&back_buffer.p)))); device->CreateRenderTargetView(back_buffer.p, nullptr, rtv); D3D12_RESOURCE_BARRIER barrier{}; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Transition.pResource = back_buffer.p; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; ID3D12CommandList* lists[] = {list.p}; UINT64 signalled = 0; // `arm` runs just before the present, so an injection it sets up hits the presenter, not the list's work. const auto frame = [&](UINT sync_interval, const std::function& arm = {}) -> bool { pump(); if (FAILED(fence->SetEventOnCompletion(signalled, nullptr))) return false; // the list's last run is done if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return false; barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; list->ResourceBarrier(1, &barrier); list->ClearRenderTargetView(rtv, colour, 0, nullptr); barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT; list->ResourceBarrier(1, &barrier); if (FAILED(list->Close())) return false; queue->ExecuteCommandLists(1, lists); if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; if (arm) arm(); const HRESULT presented = presenter->present(back_buffer.p, sync_interval); driver::fail_next_submit = VK_SUCCESS; // whatever the present did not use driver::next_present = VK_SUCCESS; driver::fail_semaphore_in = 0; if (FAILED(presented)) return false; return SUCCEEDED(queue->Signal(fence.p, ++signalled)); }; // Every present is counted unless the surface reported it out of date, which the driver may do around a // resize; the double counts those. for (int i = 0; i < 60; ++i) EXPECT(frame(1)); EXPECT(presenter->presented() == 60 - driver::out_of_date); const VkExtent2D first = presenter->extent(); EXPECT(first.width == width && first.height == height); // A resize recreates the swapchain; the 320x240 back buffer is scaled to the new size. Unsynchronised // presents (sync interval 0) switch the present mode on the way. set_client_size(window, 400, 300); for (int i = 0; i < 10; ++i) EXPECT(frame(i < 5 ? 1 : 0)); EXPECT(presenter->extent().width == 400 && presenter->extent().height == 300); EXPECT(presenter->presented() == 70 - driver::out_of_date); EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr))); const unsigned real_out_of_date = driver::out_of_date; // Failures injected by the driver double (VictorJulianiR's review of the presenter): // 1. Present statuses: OUT_OF_DATE was not shown, so it is not counted; SUBOPTIMAL was, so it is. std::uint64_t before = presenter->presented(); EXPECT(frame(0, [] { driver::next_present = VK_ERROR_OUT_OF_DATE_KHR; })); EXPECT(presenter->presented() == before); EXPECT(frame(0)); // recreates the swapchain the out-of-date present asked for before = presenter->presented(); EXPECT(frame(0, [] { driver::next_present = VK_SUBOPTIMAL_KHR; })); EXPECT(presenter->presented() == before + 1); EXPECT(frame(0)); // 2. A swapchain recreation (here for a vsync change) whose second per-image semaphore cannot be made fails // whole: the half-made semaphores and swapchain go, and a retry at the same vsync makes a complete one // instead of acquiring an image without its semaphore (validation would report a null semaphore). // The device makes only timeline semaphores, so the binary ones are the presenter's: one acquire // semaphore per frame in flight (2) and one per swapchain image. EXPECT(driver::binary.size() > 2); EXPECT(!frame(1, [] { driver::fail_semaphore_in = 2; })); EXPECT(driver::binary.size() == 2); // the old swapchain's went, and nothing of the new set is left before = presenter->presented(); EXPECT(frame(1)); EXPECT(presenter->presented() == before + 1 && driver::binary.size() > 2); // 3. A submit that fails after an image was acquired: present reports it, and the next present neither // waits forever on the frame's fence nor reuses a semaphore that is still pending. before = presenter->presented(); EXPECT(!frame(1, [] { driver::fail_next_submit = VK_ERROR_OUT_OF_HOST_MEMORY; })); EXPECT(presenter->presented() == before); const unsigned out_of_date_before = driver::out_of_date; for (int i = 0; i < 4; ++i) EXPECT(frame(1)); // both frames in flight come round again EXPECT(presenter->presented() == before + 4 - (driver::out_of_date - out_of_date_before)); EXPECT(SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr))); std::printf("injected: out-of-date and suboptimal presents counted apart, a failed swapchain recreation " "released and retried, a failed blit submission recovered (%u real out-of-date presents)\n", real_out_of_date); // What reached the screen: the centre of the client area, if the window is in front. Sleep(200); pump(); if (GetForegroundWindow() == window && !IsIconic(window)) { if (is_hdr_monitor(window)) { std::printf("the monitor is in HDR mode: on-screen colour check skipped\n"); } else { RECT client{}; GetClientRect(window, &client); POINT centre{(client.right - client.left) / 2, (client.bottom - client.top) / 2}; ClientToScreen(window, ¢re); HDC screen = GetDC(nullptr); const COLORREF pixel = GetPixel(screen, centre.x, centre.y); ReleaseDC(nullptr, screen); const int r = GetRValue(pixel), g = GetGValue(pixel), b = GetBValue(pixel); std::printf("screen pixel at the window centre: %d,%d,%d (cleared to 51,153,230)\n", r, g, b); EXPECT(pixel != CLR_INVALID); EXPECT(std::abs(r - 51) <= 3 && std::abs(g - 153) <= 3 && std::abs(b - 230) <= 3); screen_checked = true; } } else { std::printf("the window is not in front: on-screen colour check skipped\n"); } presenter.reset(); // before the device's queue and resources go } DestroyWindow(window); UnregisterClassW(window_class.lpszClassName, window_class.hInstance); if (d.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } std::printf("M0: 70 frames cleared and presented through the Xbox-ABI proxy on Vulkan, swapchain recreated on " "resize%s\n", screen_checked ? ", colour confirmed on screen" : ""); return 0; }