upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorlumenpearson <139921639+lumenpearson@users.noreply.github.com>2026-11-22 23:25:25 +0300
committerlumenpearson <139921639+lumenpearson@users.noreply.github.com>2026-11-22 23:25:25 +0300
commitf324bfbc71f0eabf9515bcd7c8b7c9e4b89448bf (patch)
tree2db4ae6fd5412abbbc3e1894f8bc7ed88c8ae514 /runtime
parent18380c6d2baf1422109b369860a6e8be5e185b05 (diff)
parentf847748cc76bd3777f9c070c4034eb2fc1c04e64 (diff)
Merge upstream main into SHADER-537
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt135
-rw-r--r--runtime/README.md5
-rw-r--r--runtime/cmake/vulkan_headers_missing.cmake21
-rw-r--r--runtime/shims/d3d12_com.cpp15
-rw-r--r--runtime/shims/d3d12_com.h18
-rw-r--r--runtime/shims/d3d12_com_object.h70
-rw-r--r--runtime/shims/d3d12_feature_compat.h18
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp541
-rw-r--r--runtime/shims/dxgi_com.cpp75
-rw-r--r--runtime/shims/gameinput.cpp673
-rw-r--r--runtime/shims/gameinput.h22
-rw-r--r--runtime/shims/gameinput_abi.h215
-rw-r--r--runtime/shims/library_loader.cpp14
-rw-r--r--runtime/shims/startup_trace.h52
-rw-r--r--runtime/shims/winhttp_offline.cpp385
-rw-r--r--runtime/shims/xbox_present.cpp96
-rw-r--r--runtime/shims/xbox_present.h54
-rw-r--r--runtime/shims/xgameruntime.cpp469
-rw-r--r--runtime/src/command_list.h44
-rw-r--r--runtime/src/descriptor_table.h17
-rw-r--r--runtime/src/gfx10_tiling.h158
-rw-r--r--runtime/src/main.cpp2
-rw-r--r--runtime/src/pe_loader.cpp6
-rw-r--r--runtime/src/present_compose.comp130
-rw-r--r--runtime/src/present_compose.inc742
-rw-r--r--runtime/src/present_compose_spv.h11
-rw-r--r--runtime/src/queue_families.h48
-rw-r--r--runtime/src/resource_tiling.h15
-rw-r--r--runtime/src/root_signature.cpp4
-rw-r--r--runtime/src/shader_library.h27
-rw-r--r--runtime/src/spirv_f16_halves.h617
-rw-r--r--runtime/src/spirv_words.h26
-rw-r--r--runtime/src/vulkan_backend.h117
-rw-r--r--runtime/src/vulkan_present.h294
-rw-r--r--runtime/src/vulkan_present_compose.h257
-rw-r--r--runtime/src/vulkan_replay.h221
-rw-r--r--runtime/test/bvh_builder_test.cpp72
-rw-r--r--runtime/test/check_startup_cmdline.cmake20
-rw-r--r--runtime/test/check_vk_pipeline_cli.cmake14
-rw-r--r--runtime/test/d3d12_com_test.cpp5
-rw-r--r--runtime/test/d3d12_compute_test.cpp3
-rw-r--r--runtime/test/d3d12_copy_compare.h40
-rw-r--r--runtime/test/d3d12_debug_markers_test.cpp21
-rw-r--r--runtime/test/d3d12_descriptor_test.cpp3
-rw-r--r--runtime/test/d3d12_draw_test.cpp9
-rw-r--r--runtime/test/d3d12_f16_halves_test.cpp367
-rw-r--r--runtime/test/d3d12_fence_timing_test.cpp23
-rw-r--r--runtime/test/d3d12_fspx_compute_test.cpp7
-rw-r--r--runtime/test/d3d12_geometry_test.cpp267
-rw-r--r--runtime/test/d3d12_msaa_draw_test.cpp7
-rw-r--r--runtime/test/d3d12_pipeline_library_test.cpp7
-rw-r--r--runtime/test/d3d12_present_test.cpp22
-rw-r--r--runtime/test/d3d12_private_data_test.cpp346
-rw-r--r--runtime/test/d3d12_set0_compute_test.cpp3
-rw-r--r--runtime/test/d3d12_state_map_test.cpp120
-rw-r--r--runtime/test/d3d12_subresource_copy_test.cpp366
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp926
-rw-r--r--runtime/test/descriptor_table_test.cpp42
-rw-r--r--runtime/test/dll_thread_calls_test.cpp80
-rw-r--r--runtime/test/dxgi_swapchain_test.cpp128
-rw-r--r--runtime/test/fixtures/dll_thread_calls.cpp15
-rw-r--r--runtime/test/fixtures/tiny_gdk_load.cpp28
-rw-r--r--runtime/test/fixtures/tiny_startup_cmdline.cpp89
-rw-r--r--runtime/test/fsr_dispatch_test.cpp13
-rw-r--r--runtime/test/gameinput_probe.cpp6
-rw-r--r--runtime/test/gameinput_test.cpp349
-rw-r--r--runtime/test/gfx10_tiling_test.cpp155
-rw-r--r--runtime/test/glsl/gs_double.geom22
-rw-r--r--runtime/test/loader_test.cpp37
-rw-r--r--runtime/test/replay_query_edges_test.cpp1043
-rw-r--r--runtime/test/replay_query_predication_test.cpp203
-rw-r--r--runtime/test/resource_tiling_test.cpp45
-rw-r--r--runtime/test/root_signature_test.cpp12
-rw-r--r--runtime/test/shader_fixture_path.h15
-rw-r--r--runtime/test/shader_fixture_path_test.cpp32
-rw-r--r--runtime/test/shader_library_test.cpp27
-rw-r--r--runtime/test/shaders/build.py6
-rw-r--r--runtime/test/shaders/check.py63
-rw-r--r--runtime/test/shaders/compute_fixture.py2
-rw-r--r--runtime/test/shaders/cs_buf_fmt8.asm46
-rw-r--r--runtime/test/shaders/cs_buf_load_sub.asm44
-rw-r--r--runtime/test/shaders/cs_f64_add.asm10
-rw-r--r--runtime/test/shaders/cs_resinfo.asm24
-rw-r--r--runtime/test/shaders/ps_sdwa_dword_hi.asm27
-rw-r--r--runtime/test/shaders/ps_texoff_forms.asm103
-rw-r--r--runtime/test/shaders/ps_vcmp_f16.asm384
-rw-r--r--runtime/test/shaders/ps_vcmp_f16_e64.asm369
-rw-r--r--runtime/test/shaders/ps_vcmpx_f16.asm653
-rw-r--r--runtime/test/shaders/ps_vcmpx_f16_e64.asm639
-rw-r--r--runtime/test/shaders/vs_base_ids.asm24
-rw-r--r--runtime/test/shaders/w64_graphics.py2
-rw-r--r--runtime/test/spirv_f16_halves_test.cpp300
-rw-r--r--runtime/test/startup_trace_test.cpp15
-rw-r--r--runtime/test/vk_bindless_test.cpp39
-rw-r--r--runtime/test/vk_compute_test.cpp48
-rw-r--r--runtime/test/vk_harness.cpp57
-rw-r--r--runtime/test/vk_image_fuzz.cpp19
-rw-r--r--runtime/test/vk_overlapping_occlusion_test.cpp80
-rw-r--r--runtime/test/vk_pc_tail.h125
-rw-r--r--runtime/test/vk_pipeline_check.cpp151
-rw-r--r--runtime/test/vk_queue_test.cpp210
-rw-r--r--runtime/test/vk_sampler_test.cpp26
-rw-r--r--runtime/test/vk_shader_fma.h8
-rw-r--r--runtime/test/vk_store_test.cpp24
-rw-r--r--runtime/test/vk_test_device.h70
-rw-r--r--runtime/test/vk_texture_test.cpp34
-rw-r--r--runtime/test/winhttp_offline_test.cpp296
-rw-r--r--runtime/test/xbox_present_test.cpp521
-rw-r--r--runtime/test/xgameruntime_test.cpp276
-rw-r--r--runtime/test/xmem_test.cpp87
110 files changed, 14615 insertions, 770 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 7104d50cd..8f1dce2ca 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -92,6 +92,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
92 src/pe_loader.cpp 92 src/pe_loader.cpp
93 shims/registry.cpp 93 shims/registry.cpp
94 shims/file_system.cpp 94 shims/file_system.cpp
95 shims/winhttp_offline.cpp
95 shims/xmem.cpp 96 shims/xmem.cpp
96 shims/d3d12_xs.cpp 97 shims/d3d12_xs.cpp
97 shims/d3d12_xs_device.cpp 98 shims/d3d12_xs_device.cpp
@@ -209,6 +210,17 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
209 target_compile_options(file_system_test PRIVATE /W4 /permissive- /utf-8) 210 target_compile_options(file_system_test PRIVATE /W4 /permissive- /utf-8)
210 target_link_options(file_system_test PRIVATE /OPT:NOREF) 211 target_link_options(file_system_test PRIVATE /OPT:NOREF)
211 212
213 # Offline WinHTTP for mapped images (the package's XCurl.dll and libHttpClient.GDK.dll); no network is touched.
214 add_executable(winhttp_offline_test
215 test/winhttp_offline_test.cpp
216 shims/winhttp_offline.cpp
217 shims/registry.cpp
218 )
219 target_include_directories(winhttp_offline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims)
220 target_compile_definitions(winhttp_offline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
221 target_compile_options(winhttp_offline_test PRIVATE /W4 /permissive- /utf-8)
222 target_link_options(winhttp_offline_test PRIVATE /OPT:NOREF)
223
212 # Offline GDK runtime shim (XGameRuntime, XSystem, XTaskQueue, XAsync), driven through the shim registry the way 224 # Offline GDK runtime shim (XGameRuntime, XSystem, XTaskQueue, XAsync), driven through the shim registry the way
213 # a title calls it at boot. Like xmem_test it compiles its own registry.cpp. 225 # a title calls it at boot. Like xmem_test it compiles its own registry.cpp.
214 add_executable(xgameruntime_test 226 add_executable(xgameruntime_test
@@ -284,6 +296,9 @@ endif()
284 296
285include(CTest) 297include(CTest)
286if(BUILD_TESTING) 298if(BUILD_TESTING)
299 add_executable(gfx10_tiling_test test/gfx10_tiling_test.cpp)
300 add_test(NAME gfx10_tiling COMMAND gfx10_tiling_test)
301
287 add_executable(retire_tickets_test test/retire_tickets_test.cpp) 302 add_executable(retire_tickets_test test/retire_tickets_test.cpp)
288 add_test(NAME retire_tickets COMMAND retire_tickets_test) 303 add_test(NAME retire_tickets COMMAND retire_tickets_test)
289 304
@@ -311,7 +326,7 @@ if(BUILD_TESTING)
311 shims/registry.cpp 326 shims/registry.cpp
312 ) 327 )
313 target_compile_definitions(loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) 328 target_compile_definitions(loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
314 target_compile_options(loader_test PRIVATE /W4 /permissive- /utf-8) 329 target_compile_options(loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc)
315 target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) 330 target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE})
316 add_dependencies(loader_test gta6rt_tls_host) 331 add_dependencies(loader_test gta6rt_tls_host)
317 add_test(NAME loader COMMAND loader_test) 332 add_test(NAME loader COMMAND loader_test)
@@ -359,7 +374,7 @@ if(BUILD_TESTING)
359 ${CMAKE_CURRENT_SOURCE_DIR}/shims 374 ${CMAKE_CURRENT_SOURCE_DIR}/shims
360 ) 375 )
361 target_compile_definitions(pe_loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 376 target_compile_definitions(pe_loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
362 target_compile_options(pe_loader_test PRIVATE /W4 /permissive- /utf-8) 377 target_compile_options(pe_loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc)
363 target_link_options(pe_loader_test PRIVATE /OPT:NOREF) 378 target_link_options(pe_loader_test PRIVATE /OPT:NOREF)
364 target_link_libraries(pe_loader_test PRIVATE gta6rt_d3d12_xs_rootsig psapi) 379 target_link_libraries(pe_loader_test PRIVATE gta6rt_d3d12_xs_rootsig psapi)
365 add_dependencies(pe_loader_test tiny_dll tiny_exe gta6rt_tls_host) 380 add_dependencies(pe_loader_test tiny_dll tiny_exe gta6rt_tls_host)
@@ -414,6 +429,18 @@ if(BUILD_TESTING)
414 set_target_properties(tiny_bundled_load PROPERTIES 429 set_target_properties(tiny_bundled_load PROPERTIES
415 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>" 430 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
416 ) 431 )
432 add_library(tiny_startup_cmdline_dll SHARED test/fixtures/tiny_startup_cmdline.cpp)
433 target_compile_definitions(tiny_startup_cmdline_dll PRIVATE STARTUP_CMDLINE_DLL)
434 add_executable(tiny_startup_cmdline test/fixtures/tiny_startup_cmdline.cpp)
435 target_link_libraries(tiny_startup_cmdline PRIVATE tiny_startup_cmdline_dll)
436 foreach(target tiny_startup_cmdline_dll tiny_startup_cmdline)
437 target_compile_definitions(${target} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
438 target_compile_options(${target} PRIVATE /W4 /permissive- /utf-8)
439 set_target_properties(${target} PROPERTIES
440 PREFIX ""
441 RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
442 )
443 endforeach()
417 add_executable(tiny_game test/fixtures/tiny_game.cpp) 444 add_executable(tiny_game test/fixtures/tiny_game.cpp)
418 target_link_libraries(tiny_game PRIVATE xgameruntime_stub) 445 target_link_libraries(tiny_game PRIVATE xgameruntime_stub)
419 target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use 446 target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use
@@ -452,7 +479,7 @@ if(BUILD_TESTING)
452 ${CMAKE_CURRENT_SOURCE_DIR}/shims 479 ${CMAKE_CURRENT_SOURCE_DIR}/shims
453 ) 480 )
454 target_compile_definitions(test_pe_loader_bounds PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 481 target_compile_definitions(test_pe_loader_bounds PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
455 target_compile_options(test_pe_loader_bounds PRIVATE /W4 /permissive- /utf-8) 482 target_compile_options(test_pe_loader_bounds PRIVATE /W4 /permissive- /utf-8 /EHsc)
456 target_link_options(test_pe_loader_bounds PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) 483 target_link_options(test_pe_loader_bounds PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE})
457 target_link_libraries(test_pe_loader_bounds PRIVATE gta6rt_d3d12_xs_rootsig psapi) 484 target_link_libraries(test_pe_loader_bounds PRIVATE gta6rt_d3d12_xs_rootsig psapi)
458 add_dependencies(test_pe_loader_bounds gta6rt_tls_host) 485 add_dependencies(test_pe_loader_bounds gta6rt_tls_host)
@@ -500,6 +527,38 @@ if(BUILD_TESTING)
500 COMMAND loader_tls_test "$<TARGET_FILE:tiny_tls>" 527 COMMAND loader_tls_test "$<TARGET_FILE:tiny_tls>"
501 ) 528 )
502 529
530 # DisableThreadLibraryCalls from a mapped DllMain (shims/library_loader.cpp). The fixture is built without the CRT, so
531 # DllMain's only work is that one call. No game files.
532 add_library(dll_thread_calls SHARED test/fixtures/dll_thread_calls.cpp)
533 target_compile_options(dll_thread_calls PRIVATE /W4 /permissive- /utf-8 /GS-)
534 target_link_options(dll_thread_calls PRIVATE /NODEFAULTLIB /ENTRY:dll_thread_calls_main)
535 target_link_libraries(dll_thread_calls PRIVATE kernel32)
536 set_target_properties(dll_thread_calls PROPERTIES
537 OUTPUT_NAME dll_thread_calls
538 PREFIX ""
539 RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
540 ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
541 )
542 add_executable(dll_thread_calls_test
543 test/dll_thread_calls_test.cpp
544 src/pe_loader.cpp
545 shims/library_loader.cpp
546 shims/registry.cpp
547 shims/xmem.cpp
548 )
549 target_include_directories(dll_thread_calls_test PRIVATE
550 ${CMAKE_CURRENT_SOURCE_DIR}/src
551 ${CMAKE_CURRENT_SOURCE_DIR}/shims
552 )
553 target_compile_definitions(dll_thread_calls_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
554 target_compile_options(dll_thread_calls_test PRIVATE /W4 /permissive- /utf-8 /EHsc)
555 target_link_options(dll_thread_calls_test PRIVATE /OPT:NOREF)
556 target_link_libraries(dll_thread_calls_test PRIVATE psapi)
557 add_dependencies(dll_thread_calls_test dll_thread_calls)
558 add_test(NAME dll_thread_calls
559 COMMAND dll_thread_calls_test "$<TARGET_FILE:dll_thread_calls>"
560 )
561
503 # LEONIDA_UNIMPLEMENTED=log|fail|stop: builds its own image with two imports that bind to nothing, calls them in 562 # LEONIDA_UNIMPLEMENTED=log|fail|stop: builds its own image with two imports that bind to nothing, calls them in
504 # process (log, fail) and in child processes (default/env parsing, stop). No game files, no GPU. 563 # process (log, fail) and in child processes (default/env parsing, stop). No game files, no GPU.
505 add_executable(unimplemented_policy_test 564 add_executable(unimplemented_policy_test
@@ -509,7 +568,10 @@ if(BUILD_TESTING)
509 ) 568 )
510 # The register-preservation check needs a caller that sets rbx/rbp/rdi/rsi/r12-r15 and xmm6-15, which MSVC x64 569 # The register-preservation check needs a caller that sets rbx/rbp/rdi/rsi/r12-r15 and xmm6-15, which MSVC x64
511 # cannot do inline: test/fixtures/abi_probe.asm (MASM). Without ml64 the rest of the test still runs. 570 # cannot do inline: test/fixtures/abi_probe.asm (MASM). Without ml64 the rest of the test still runs.
512 find_program(LEONIDA_ML64 ml64) # CMake would otherwise pick the 32-bit ml with the Ninja generator 571 # Visual Studio locates cl.exe without adding its directory to PATH.
572 # Keep looking for ml64 specifically so Ninja cannot select the 32-bit assembler.
573 get_filename_component(_gta6rt_compiler_bin "${CMAKE_CXX_COMPILER}" DIRECTORY)
574 find_program(LEONIDA_ML64 NAMES ml64 HINTS "${_gta6rt_compiler_bin}")
513 if(LEONIDA_ML64) 575 if(LEONIDA_ML64)
514 set(CMAKE_ASM_MASM_COMPILER "${LEONIDA_ML64}") 576 set(CMAKE_ASM_MASM_COMPILER "${LEONIDA_ML64}")
515 enable_language(ASM_MASM) 577 enable_language(ASM_MASM)
@@ -556,12 +618,16 @@ if(BUILD_TESTING)
556 endif() 618 endif()
557 add_executable(command_list_test test/command_list_test.cpp) 619 add_executable(command_list_test test/command_list_test.cpp)
558 add_test(NAME command_list COMMAND command_list_test) 620 add_test(NAME command_list COMMAND command_list_test)
621 add_executable(shader_fixture_path_test test/shader_fixture_path_test.cpp)
622 add_test(NAME shader_fixture_path COMMAND shader_fixture_path_test)
559 add_executable(resource_tiling_test test/resource_tiling_test.cpp) 623 add_executable(resource_tiling_test test/resource_tiling_test.cpp)
560 add_test(NAME resource_tiling COMMAND resource_tiling_test) 624 add_test(NAME resource_tiling COMMAND resource_tiling_test)
561 add_executable(descriptor_table_test test/descriptor_table_test.cpp) 625 add_executable(descriptor_table_test test/descriptor_table_test.cpp)
562 add_test(NAME descriptor_table COMMAND descriptor_table_test) 626 add_test(NAME descriptor_table COMMAND descriptor_table_test)
563 add_executable(shader_library_test test/shader_library_test.cpp) 627 add_executable(shader_library_test test/shader_library_test.cpp)
564 add_test(NAME shader_library COMMAND shader_library_test) 628 add_test(NAME shader_library COMMAND shader_library_test)
629 add_executable(spirv_f16_halves_test test/spirv_f16_halves_test.cpp)
630 add_test(NAME spirv_f16_halves COMMAND spirv_f16_halves_test)
565 # Optional: skips unless LEONIDA_SHADERS names a translated work folder (<work>/shaders/spirv). 631 # Optional: skips unless LEONIDA_SHADERS names a translated work folder (<work>/shaders/spirv).
566 add_executable(shader_library_corpus_test test/shader_library_corpus_test.cpp) 632 add_executable(shader_library_corpus_test test/shader_library_corpus_test.cpp)
567 add_test(NAME shader_library_corpus COMMAND shader_library_corpus_test) 633 add_test(NAME shader_library_corpus COMMAND shader_library_corpus_test)
@@ -643,6 +709,9 @@ if(BUILD_TESTING)
643 if(WIN32 AND TARGET file_system_test) 709 if(WIN32 AND TARGET file_system_test)
644 add_test(NAME file_system COMMAND file_system_test) 710 add_test(NAME file_system COMMAND file_system_test)
645 endif() 711 endif()
712 if(WIN32 AND TARGET winhttp_offline_test)
713 add_test(NAME winhttp_offline COMMAND winhttp_offline_test)
714 endif()
646 if(WIN32 AND TARGET xgameruntime_test) 715 if(WIN32 AND TARGET xgameruntime_test)
647 add_test(NAME xgameruntime COMMAND xgameruntime_test) 716 add_test(NAME xgameruntime COMMAND xgameruntime_test)
648 endif() 717 endif()
@@ -654,6 +723,9 @@ if(BUILD_TESTING)
654 set_tests_properties(gameinput PROPERTIES DISABLED TRUE) 723 set_tests_properties(gameinput PROPERTIES DISABLED TRUE)
655 endif() 724 endif()
656 if(WIN32 AND TARGET gta6rt AND TARGET tiny_game) 725 if(WIN32 AND TARGET gta6rt AND TARGET tiny_game)
726 add_test(NAME run_startup_cmdline COMMAND ${CMAKE_COMMAND}
727 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_startup_cmdline>"
728 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_startup_cmdline.cmake")
657 add_test(NAME run_tiny_async COMMAND ${CMAKE_COMMAND} 729 add_test(NAME run_tiny_async COMMAND ${CMAKE_COMMAND}
658 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_async>" 730 "-DLOADER=$<TARGET_FILE:gta6rt>" "-DGUEST=$<TARGET_FILE:tiny_async>"
659 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_async.cmake") 731 "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_async.cmake")
@@ -718,6 +790,7 @@ endif()
718# -DLEONIDA_VULKAN_HEADERS_FETCH=ON to download the pinned Khronos Vulkan-Headers release once at configure time 790# -DLEONIDA_VULKAN_HEADERS_FETCH=ON to download the pinned Khronos Vulkan-Headers release once at configure time
719# (hash-checked), or pass -DFETCHCONTENT_SOURCE_DIR_VULKANHEADERS=<path> to use a local copy without downloading. 791# (hash-checked), or pass -DFETCHCONTENT_SOURCE_DIR_VULKANHEADERS=<path> to use a local copy without downloading.
720option(LEONIDA_VULKAN_HEADERS_FETCH "Download the pinned Khronos Vulkan-Headers release if no Vulkan headers are found" OFF) 792option(LEONIDA_VULKAN_HEADERS_FETCH "Download the pinned Khronos Vulkan-Headers release if no Vulkan headers are found" OFF)
793option(LEONIDA_REQUIRE_VULKAN "Fail the configure instead of warning when no Vulkan headers are found" OFF)
721find_package(Vulkan QUIET) 794find_package(Vulkan QUIET)
722if(NOT TARGET Vulkan::Headers) 795if(NOT TARGET Vulkan::Headers)
723 find_path(Vulkan_INCLUDE_DIR 796 find_path(Vulkan_INCLUDE_DIR
@@ -745,7 +818,7 @@ endif()
745if(TARGET Vulkan::Headers) 818if(TARGET Vulkan::Headers)
746 foreach(tool vk_harness vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test 819 foreach(tool vk_harness vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test
747 vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test 820 vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test
748 vk_xdxr_build_test) 821 vk_xdxr_build_test vk_queue_test)
749 add_executable(${tool} test/${tool}.cpp) 822 add_executable(${tool} test/${tool}.cpp)
750 target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) 823 target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
751 if(WIN32) 824 if(WIN32)
@@ -1083,7 +1156,7 @@ if(TARGET Vulkan::Headers)
1083 add_executable(queue_proxy_test test/queue_proxy_test.cpp) 1156 add_executable(queue_proxy_test test/queue_proxy_test.cpp)
1084 target_link_libraries(queue_proxy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) 1157 target_link_libraries(queue_proxy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1085 target_compile_definitions(queue_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 1158 target_compile_definitions(queue_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1086 target_compile_options(queue_proxy_test PRIVATE /W4 /permissive- /utf-8) 1159 target_compile_options(queue_proxy_test PRIVATE /W4 /permissive- /utf-8 /EHsc)
1087 add_test(NAME queue_proxy COMMAND queue_proxy_test) 1160 add_test(NAME queue_proxy COMMAND queue_proxy_test)
1088 set_tests_properties(queue_proxy PROPERTIES SKIP_RETURN_CODE 77) 1161 set_tests_properties(queue_proxy PROPERTIES SKIP_RETURN_CODE 77)
1089 # Xbox-ABI command allocator proxies (device slot 9) on the Vulkan device, and the unwrapped PC allocator on the 1162 # Xbox-ABI command allocator proxies (device slot 9) on the Vulkan device, and the unwrapped PC allocator on the
@@ -1113,6 +1186,14 @@ if(TARGET Vulkan::Headers)
1113 add_test(NAME d3d12_shader_cache COMMAND d3d12_shader_cache_test) 1186 add_test(NAME d3d12_shader_cache COMMAND d3d12_shader_cache_test)
1114 set_tests_properties(d3d12_shader_cache PROPERTIES SKIP_RETURN_CODE 77) 1187 set_tests_properties(d3d12_shader_cache PROPERTIES SKIP_RETURN_CODE 77)
1115 set_tests_properties(d3d12_method_variants PROPERTIES SKIP_RETURN_CODE 77) 1188 set_tests_properties(d3d12_method_variants PROPERTIES SKIP_RETURN_CODE 77)
1189 # ID3D12Object private data (GetPrivateData, SetPrivateData, SetPrivateDataInterface, SetName) compared with
1190 # the host runtime's answers on the device and four child objects.
1191 add_executable(d3d12_private_data_test test/d3d12_private_data_test.cpp)
1192 target_link_libraries(d3d12_private_data_test PRIVATE gta6rt_d3d12_com)
1193 target_compile_definitions(d3d12_private_data_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1194 target_compile_options(d3d12_private_data_test PRIVATE /W4 /permissive- /utf-8)
1195 add_test(NAME d3d12_private_data COMMAND d3d12_private_data_test)
1196 set_tests_properties(d3d12_private_data PROPERTIES SKIP_RETURN_CODE 77)
1116 1197
1117 # CreateSampler2 (D3D-28) against CreateSampler, and its refusals against the host's PC runtime. 1198 # CreateSampler2 (D3D-28) against CreateSampler, and its refusals against the host's PC runtime.
1118 add_executable(d3d12_sampler2_test test/d3d12_sampler2_test.cpp) 1199 add_executable(d3d12_sampler2_test test/d3d12_sampler2_test.cpp)
@@ -1227,6 +1308,14 @@ if(TARGET Vulkan::Headers)
1227 add_test(NAME d3d12_resource_desc COMMAND d3d12_resource_desc_test) 1308 add_test(NAME d3d12_resource_desc COMMAND d3d12_resource_desc_test)
1228 set_tests_properties(d3d12_resource_desc PROPERTIES SKIP_RETURN_CODE 77) 1309 set_tests_properties(d3d12_resource_desc PROPERTIES SKIP_RETURN_CODE 77)
1229 1310
1311 # WriteToSubresource/ReadFromSubresource arguments and bytes, compared with the host runtime.
1312 add_executable(d3d12_subresource_copy_test test/d3d12_subresource_copy_test.cpp)
1313 target_link_libraries(d3d12_subresource_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1314 target_compile_definitions(d3d12_subresource_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1315 target_compile_options(d3d12_subresource_copy_test PRIVATE /W4 /permissive- /utf-8)
1316 add_test(NAME d3d12_subresource_copy COMMAND d3d12_subresource_copy_test)
1317 set_tests_properties(d3d12_subresource_copy PROPERTIES SKIP_RETURN_CODE 77)
1318
1230 # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan. 1319 # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan.
1231 add_executable(d3d12_present_test test/d3d12_present_test.cpp) 1320 add_executable(d3d12_present_test test/d3d12_present_test.cpp)
1232 target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) 1321 target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi)
@@ -1235,6 +1324,14 @@ if(TARGET Vulkan::Headers)
1235 add_test(NAME d3d12_present COMMAND d3d12_present_test) 1324 add_test(NAME d3d12_present COMMAND d3d12_present_test)
1236 set_tests_properties(d3d12_present PROPERTIES SKIP_RETURN_CODE 77) 1325 set_tests_properties(d3d12_present PROPERTIES SKIP_RETURN_CODE 77)
1237 1326
1327 # Per-pipeline --f16-interp-fallback linking (SHADER-378): 16-param VS + colliding PS rendered on Vulkan.
1328 add_executable(d3d12_f16_halves_test test/d3d12_f16_halves_test.cpp shims/d3d12_xs_device.cpp)
1329 target_link_libraries(d3d12_f16_halves_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
1330 target_compile_definitions(d3d12_f16_halves_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1331 target_compile_options(d3d12_f16_halves_test PRIVATE /W4 /permissive- /utf-8)
1332 add_test(NAME d3d12_f16_halves COMMAND d3d12_f16_halves_test)
1333 set_tests_properties(d3d12_f16_halves PROPERTIES SKIP_RETURN_CODE 77)
1334
1238 # PresentX and the frame events on the Vulkan device (shims/xbox_present.h), checked on swapchain pixels. 1335 # PresentX and the frame events on the Vulkan device (shims/xbox_present.h), checked on swapchain pixels.
1239 add_executable(xbox_present_test test/xbox_present_test.cpp) 1336 add_executable(xbox_present_test test/xbox_present_test.cpp)
1240 target_link_libraries(xbox_present_test PRIVATE gta6rt_d3d12_com user32) 1337 target_link_libraries(xbox_present_test PRIVATE gta6rt_d3d12_com user32)
@@ -1567,8 +1664,10 @@ if(TARGET Vulkan::Headers)
1567 set(LEONIDA_TEST_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_draw.spv) 1664 set(LEONIDA_TEST_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_draw.spv)
1568 set(LEONIDA_TEST_VS_FULLSCREEN ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_fullscreen.spv) 1665 set(LEONIDA_TEST_VS_FULLSCREEN ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_fullscreen.spv)
1569 set(LEONIDA_TEST_VS_INT ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_draw_int.spv) 1666 set(LEONIDA_TEST_VS_INT ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_draw_int.spv)
1667 set(LEONIDA_TEST_GS_DOUBLE ${CMAKE_CURRENT_BINARY_DIR}/generated/gs_double.spv)
1570 foreach(pair "vs_draw.vert;${LEONIDA_TEST_VS}" "ps_draw.frag;${LEONIDA_TEST_PS}" 1668 foreach(pair "vs_draw.vert;${LEONIDA_TEST_VS}" "ps_draw.frag;${LEONIDA_TEST_PS}"
1571 "vs_fullscreen.vert;${LEONIDA_TEST_VS_FULLSCREEN}" "vs_draw_int.vert;${LEONIDA_TEST_VS_INT}") 1669 "vs_fullscreen.vert;${LEONIDA_TEST_VS_FULLSCREEN}" "vs_draw_int.vert;${LEONIDA_TEST_VS_INT}"
1670 "gs_double.geom;${LEONIDA_TEST_GS_DOUBLE}")
1572 list(GET pair 0 source) 1671 list(GET pair 0 source)
1573 list(GET pair 1 output) 1672 list(GET pair 1 output)
1574 add_custom_command( 1673 add_custom_command(
@@ -1597,6 +1696,16 @@ if(TARGET Vulkan::Headers)
1597 target_compile_options(d3d12_msaa_draw_test PRIVATE /W4 /permissive- /utf-8) 1696 target_compile_options(d3d12_msaa_draw_test PRIVATE /W4 /permissive- /utf-8)
1598 add_test(NAME d3d12_msaa_draw COMMAND d3d12_msaa_draw_test) 1697 add_test(NAME d3d12_msaa_draw COMMAND d3d12_msaa_draw_test)
1599 set_tests_properties(d3d12_msaa_draw PROPERTIES SKIP_RETURN_CODE 77) 1698 set_tests_properties(d3d12_msaa_draw PROPERTIES SKIP_RETURN_CODE 77)
1699 # Geometry shaders: a VS+GS+PS pipeline whose GS emits each triangle twice.
1700 add_executable(d3d12_geometry_test test/d3d12_geometry_test.cpp shims/d3d12_xs_device.cpp
1701 ${LEONIDA_TEST_VS} ${LEONIDA_TEST_GS_DOUBLE} ${LEONIDA_TEST_PS})
1702 target_link_libraries(d3d12_geometry_test PRIVATE gta6rt_d3d12_com)
1703 target_compile_definitions(d3d12_geometry_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
1704 LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_GS_SPV="${LEONIDA_TEST_GS_DOUBLE}"
1705 LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}")
1706 target_compile_options(d3d12_geometry_test PRIVATE /W4 /permissive- /utf-8)
1707 add_test(NAME d3d12_geometry COMMAND d3d12_geometry_test)
1708 set_tests_properties(d3d12_geometry PROPERTIES SKIP_RETURN_CODE 77)
1600 # Set 0 from the compute bind point: a compute PSO whose shader declares set-0 bindings samples through the 1709 # Set 0 from the compute bind point: a compute PSO whose shader declares set-0 bindings samples through the
1601 # device's bindless set, which nothing but the layer binds. 1710 # device's bindless set, which nothing but the layer binds.
1602 set(LEONIDA_TEST_CS_SET0_SAMPLE ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_set0_sample.spv) 1711 set(LEONIDA_TEST_CS_SET0_SAMPLE ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_set0_sample.spv)
@@ -1787,6 +1896,13 @@ if(TARGET Vulkan::Headers)
1787 target_compile_definitions(replay_query_predication_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 1896 target_compile_definitions(replay_query_predication_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1788 endif() 1897 endif()
1789 add_test(NAME replay_query_predication COMMAND replay_query_predication_test) 1898 add_test(NAME replay_query_predication COMMAND replay_query_predication_test)
1899 # Query edge cases and queue ownership, with CPU mocks (no GPU or game data).
1900 add_executable(replay_query_edges_test test/replay_query_edges_test.cpp)
1901 target_link_libraries(replay_query_edges_test PRIVATE Vulkan::Headers)
1902 if(WIN32)
1903 target_compile_definitions(replay_query_edges_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1904 endif()
1905 add_test(NAME replay_query_edges COMMAND replay_query_edges_test)
1790 # GFX10 T#/S#/V# descriptor encoding and its Vulkan mappings (src/gfx10_descriptors.h). 1906 # GFX10 T#/S#/V# descriptor encoding and its Vulkan mappings (src/gfx10_descriptors.h).
1791 add_executable(gfx10_descriptors_test test/gfx10_descriptors_test.cpp) 1907 add_executable(gfx10_descriptors_test test/gfx10_descriptors_test.cpp)
1792 target_link_libraries(gfx10_descriptors_test PRIVATE Vulkan::Headers) 1908 target_link_libraries(gfx10_descriptors_test PRIVATE Vulkan::Headers)
@@ -1806,7 +1922,6 @@ if(TARGET Vulkan::Headers)
1806 add_test(NAME subgroup_size COMMAND subgroup_size_test) 1922 add_test(NAME subgroup_size COMMAND subgroup_size_test)
1807 endif() 1923 endif()
1808else() 1924else()
1809 message(STATUS "Vulkan headers not found: GPU test tools, vk_pipeline_check, d3d12_state_map_test and " 1925 include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_headers_missing.cmake")
1810 "gfx10_descriptors_test are not built. Set VULKAN_SDK, install Vulkan headers, or pass " 1926 leonida_vulkan_headers_missing()
1811 "-DLEONIDA_VULKAN_HEADERS_FETCH=ON to download the pinned Khronos Vulkan-Headers release")
1812endif() 1927endif()
diff --git a/runtime/README.md b/runtime/README.md
index 532873a6b..b63d536d1 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -164,8 +164,9 @@ Current limits, by design:
164 section 3.2 for what is missing. 164 section 3.2 for what is missing.
165 165
166- `gameinput.dll` / `xgameruntime.dll` — `GameInputCreate`: the v0 GameInput API for gamepads on SDL3 166- `gameinput.dll` / `xgameruntime.dll` — `GameInputCreate`: the v0 GameInput API for gamepads on SDL3
167 (`shims/gameinput.cpp`), so any controller SDL supports works, with rumble, Xbox trigger rumble, and on a 167 (`shims/gameinput.cpp`), so any controller SDL supports works, with rumble, Xbox trigger rumble, force feedback
168 DualSense adaptive-trigger effects and the lightbar. Optional and CMake-only: built when an installed SDL3 is found, 168 and trigger haptics where SDL opens the pad as a haptic device, and on a DualSense adaptive-trigger effects and the
169 lightbar. Optional and CMake-only: built when an installed SDL3 is found,
169 or with `-DLEONIDA_SDL3_FETCH=ON` to download the pinned release; nothing is downloaded otherwise, and the 170 or with `-DLEONIDA_SDL3_FETCH=ON` to download the pinned release; nothing is downloaded otherwise, and the
170 `scripts/build_runtime.ps1` cl.exe fallback never builds it. See [docs/gameinput.md](../docs/gameinput.md) for the mapping, the `LEONIDA_DS_*` settings and what is 171 `scripts/build_runtime.ps1` cl.exe fallback never builds it. See [docs/gameinput.md](../docs/gameinput.md) for the mapping, the `LEONIDA_DS_*` settings and what is
171 unverified. 172 unverified.
diff --git a/runtime/cmake/vulkan_headers_missing.cmake b/runtime/cmake/vulkan_headers_missing.cmake
new file mode 100644
index 000000000..8b4c94dfd
--- /dev/null
+++ b/runtime/cmake/vulkan_headers_missing.cmake
@@ -0,0 +1,21 @@
1# Reports a configure without Vulkan headers. Everything under if(TARGET Vulkan::Headers) in runtime/CMakeLists.txt
2# is then left out: not only the GPU test tools but the D3D12 COM objects and the Vulkan D3D12 device in gta6rt
3# (LEONIDA_D3D12=vulkan), and with them most of ctest. A STATUS line was easy to miss: ctest then reports
4# "100% tests passed" on a fraction of the suite. -DLEONIDA_REQUIRE_VULKAN=ON makes it a configure error (CI sets it).
5# Kept in its own file so tests/test_cmake_vulkan_missing.py can run it with `cmake -P`.
6function(leonida_vulkan_headers_missing)
7 set(text
8 "Vulkan headers not found, so this build leaves out the Vulkan D3D12 device in gta6rt (LEONIDA_D3D12=vulkan "
9 "is unavailable), the D3D12 COM objects and their tests, the D3D12 layer and GPU tests, the GPU test tools "
10 "(run_gpu_tests.py needs them), vk_pipeline_check, d3d12_state_map_test and gfx10_descriptors_test. ctest "
11 "then runs only the CPU tests and can still report 100% passed. Set VULKAN_SDK in the environment that runs "
12 "CMake (then delete CMakeCache.txt, which keeps the failed lookup), install the Vulkan headers, or pass "
13 "-DLEONIDA_VULKAN_HEADERS_FETCH=ON to download the pinned Khronos Vulkan-Headers release. "
14 "-DLEONIDA_REQUIRE_VULKAN=ON turns this warning into an error.")
15 string(CONCAT text ${text})
16 if(LEONIDA_REQUIRE_VULKAN)
17 message(FATAL_ERROR "${text}")
18 else()
19 message(WARNING "${text}")
20 endif()
21endfunction()
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index e1c8deca1..38b21d55f 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -358,7 +358,8 @@ public:
358 void STDMETHODCALLTYPE OMSetRenderTargets(UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* targets, BOOL single_range, 358 void STDMETHODCALLTYPE OMSetRenderTargets(UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* targets, BOOL single_range,
359 const D3D12_CPU_DESCRIPTOR_HANDLE* depth) override { 359 const D3D12_CPU_DESCRIPTOR_HANDLE* depth) override {
360 if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return check(false); 360 if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return check(false);
361 render_targets_.assign(count, {}); 361 render_targets_.fill({});
362 render_target_count_ = count;
362 for (UINT i = 0; i < count && targets; ++i) { 363 for (UINT i = 0; i < count && targets; ++i) {
363 const SIZE_T handle = single_range ? targets[0].ptr + SIZE_T(i) * descriptor_size : targets[i].ptr; 364 const SIZE_T handle = single_range ? targets[0].ptr + SIZE_T(i) * descriptor_size : targets[i].ptr;
364 if (handle) render_targets_[i] = *reinterpret_cast<const leonida::TargetView*>(handle); 365 if (handle) render_targets_[i] = *reinterpret_cast<const leonida::TargetView*>(handle);
@@ -978,7 +979,8 @@ private:
978 leonida::IndexBufferView index_{}; 979 leonida::IndexBufferView index_{};
979 leonida::Viewport viewport_{}; 980 leonida::Viewport viewport_{};
980 leonida::Rect scissor_{}; 981 leonida::Rect scissor_{};
981 std::vector<leonida::TargetView> render_targets_; 982 std::array<leonida::TargetView, D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT> render_targets_{};
983 UINT render_target_count_ = 0;
982 leonida::TargetView depth_{}; 984 leonida::TargetView depth_{};
983 std::array<float, 4> blend_factor_{1, 1, 1, 1}; 985 std::array<float, 4> blend_factor_{1, 1, 1, 1};
984 986
@@ -1041,7 +1043,8 @@ private:
1041 index_ = {}; 1043 index_ = {};
1042 viewport_ = {}; 1044 viewport_ = {};
1043 scissor_ = {}; 1045 scissor_ = {};
1044 render_targets_.clear(); 1046 render_targets_.fill({});
1047 render_target_count_ = 0;
1045 depth_ = {}; 1048 depth_ = {};
1046 blend_factor_ = {1, 1, 1, 1}; 1049 blend_factor_ = {1, 1, 1, 1};
1047 set_pipeline(state); 1050 set_pipeline(state);
@@ -1071,10 +1074,10 @@ private:
1071 // and Vulkan forbids a 0x0 viewport, so the draw is not recorded. 1074 // and Vulkan forbids a 0x0 viewport, so the draw is not recorded.
1072 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; 1075 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return;
1073 leonida::Draw draw{graphics_pipeline_, graphics_.data, render_targets_, depth_, 1076 leonida::Draw draw{graphics_pipeline_, graphics_.data, render_targets_, depth_,
1074 {vertex_buffers_.begin(), vertex_buffers_.end()}, index_, topology_, viewport_, scissor_, 1077 vertex_buffers_, index_, topology_, viewport_, scissor_,
1075 blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first, 1078 blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, first,
1076 base_vertex, first_instance}; 1079 base_vertex, first_instance, render_target_count_};
1077 check(list_.draw(draw)); 1080 check(list_.draw(std::move(draw)));
1078 } 1081 }
1079}; 1082};
1080 1083
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index f0bb0d859..893478ce0 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -29,6 +29,7 @@
29 29
30namespace leonida { 30namespace leonida {
31class VulkanPresenter; 31class VulkanPresenter;
32struct PresentPlanes;
32} 33}
33 34
34namespace rt::d3d12 { 35namespace rt::d3d12 {
@@ -77,6 +78,10 @@ struct VulkanDeviceInfo {
77 // Distinct handles from queue_family, when the creator requested more than one queue. 78 // Distinct handles from queue_family, when the creator requested more than one queue.
78 // Empty for caller-owned devices that only supplied queue above. 79 // Empty for caller-owned devices that only supplied queue above.
79 std::vector<VkQueue> command_queues; 80 std::vector<VkQueue> command_queues;
81 std::uint32_t compute_family = UINT32_MAX;
82 std::uint32_t copy_family = UINT32_MAX;
83 std::vector<VkQueue> compute_queues;
84 std::vector<VkQueue> copy_queues;
80 bool separate_depth_stencil_layouts = true; 85 bool separate_depth_stencil_layouts = true;
81 std::uint32_t max_push_constants_size = 0; 86 std::uint32_t max_push_constants_size = 0;
82 bool push_constants_need_fallback = false; 87 bool push_constants_need_fallback = false;
@@ -120,6 +125,9 @@ struct VulkanDeviceInfo {
120 // instance (only meaningful with `presentation`): a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per 125 // instance (only meaningful with `presentation`): a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per
121 // present, which PresentX's ImmediateThresholdPercent uses. 126 // present, which PresentX's ImmediateThresholdPercent uses.
122 bool swapchain_maintenance1 = false; 127 bool swapchain_maintenance1 = false;
128 // VK_EXT_swapchain_colorspace is enabled on the instance (with `presentation`): the surface can list its HDR10
129 // (ST.2084) formats, which a PresentX plane in HDR10 uses. Without it HDR10 planes are clipped to SDR.
130 bool swapchain_colorspace = false;
123 // VK_EXT_image_view_min_lod and its minLod feature are enabled on the logical device. 131 // VK_EXT_image_view_min_lod and its minLod feature are enabled on the logical device.
124 bool image_view_min_lod = false; 132 bool image_view_min_lod = false;
125 // Pixel-shader extensions translated shaders can declare, each enabled with its feature where the GPU has it: 133 // Pixel-shader extensions translated shaders can declare, each enabled with its feature where the GPU has it:
@@ -263,6 +271,13 @@ public:
263 bool tear = false); 271 bool tear = false);
264 // A black frame, nothing read (PresentX with no planes). 272 // A black frame, nothing read (PresentX with no planes).
265 HRESULT present_blank(UINT sync_interval); 273 HRESULT present_blank(UINT sync_interval);
274 // One or two planes composed (VulkanPresenter::present_planes); `planes` names the textures by ResourceId, so the
275 // caller fills it with resource_id(). DXGI_ERROR_UNSUPPORTED for a source the compose pass cannot read.
276 HRESULT present_planes(const leonida::PresentPlanes& planes, UINT sync_interval, bool tear = false);
277 // The swapchain holds HDR10 (ST.2084) values; and a test hook (VulkanPresenter::force_hdr_encoding).
278 bool hdr_active() const;
279 void force_hdr_encoding(bool on);
280 std::uint64_t composed_presents() const; // presents that went through the compose pass
266 bool tear_supported() const; 281 bool tear_supported() const;
267 bool last_present_tore() const; 282 bool last_present_tore() const;
268 std::uint64_t tear_presents() const; 283 std::uint64_t tear_presents() const;
@@ -279,6 +294,9 @@ private:
279 std::unique_ptr<leonida::VulkanPresenter> presenter_; 294 std::unique_ptr<leonida::VulkanPresenter> presenter_;
280}; 295};
281 296
297// Whether `device` (from create_vulkan_device*) was created with VK_EXT_swapchain_colorspace on its instance.
298bool device_has_swapchain_colorspace(ID3D12Device* device);
299
282// Null when `device` is not a Vulkan device created with presentation, or the window cannot be presented to. 300// Null when `device` is not a Vulkan device created with presentation, or the window cannot be presented to.
283std::unique_ptr<WindowPresenter> create_window_presenter(ID3D12Device* device, HWND window); 301std::unique_ptr<WindowPresenter> create_window_presenter(ID3D12Device* device, HWND window);
284 302
diff --git a/runtime/shims/d3d12_com_object.h b/runtime/shims/d3d12_com_object.h
index 15e666802..e45fcd29f 100644
--- a/runtime/shims/d3d12_com_object.h
+++ b/runtime/shims/d3d12_com_object.h
@@ -11,6 +11,7 @@
11#include <cstring> 11#include <cstring>
12#include <cwchar> 12#include <cwchar>
13#include <mutex> 13#include <mutex>
14#include <string>
14#include <utility> 15#include <utility>
15#include <vector> 16#include <vector>
16 17
@@ -51,24 +52,26 @@ public:
51 52
52 // Private data (ID3D12Object): bytes, or with SetPrivateDataInterface an interface the object holds a reference 53 // Private data (ID3D12Object): bytes, or with SetPrivateDataInterface an interface the object holds a reference
53 // to until the entry is replaced, removed or the object dies. GetPrivateData hands such an interface back with a 54 // to until the entry is replaced, removed or the object dies. GetPrivateData hands such an interface back with a
54 // reference added, as D3D12 does. A buffer too small for the entry gets DXGI_ERROR_MORE_DATA and the size it 55 // reference added, as D3D12 does. The answers are the host runtime's (d3d12_private_data_test, RTX 3060 /
55 // needs, so the caller can retry. SetName stores the name as WKPDID_D3DDebugObjectNameW, which is where D3D12 56 // 610.88, on the device and four child objects): a buffer too small for the entry gets DXGI_ERROR_MORE_DATA and
56 // keeps it, so GetPrivateData reads it back. 57 // the size it needs; SetPrivateData with null data removes the entry whatever the size, S_OK when there was one
58 // and S_FALSE when there wasn't; zero bytes with data keep an empty entry; SetPrivateDataInterface with null
59 // keeps a pointer-sized entry that reads back as null.
57 HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override { 60 HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override {
58 if (!size) return E_INVALIDARG; 61 if (!size) return E_INVALIDARG;
59 std::lock_guard lock(data_mutex_); 62 std::lock_guard lock(data_mutex_);
60 for (const auto& entry : data_) { 63 for (const auto& entry : data_) {
61 if (entry.key != guid) continue; 64 if (entry.key != guid) continue;
62 const UINT bytes = entry.object ? UINT(sizeof(IUnknown*)) : UINT(entry.bytes.size()); 65 const UINT bytes = entry.is_interface ? UINT(sizeof(IUnknown*)) : UINT(entry.bytes.size());
63 if (data && *size < bytes) { 66 if (data && *size < bytes) {
64 *size = bytes; // the size to retry with, as vkd3d-proton does 67 *size = bytes; // the size to retry with
65 return DXGI_ERROR_MORE_DATA; 68 return DXGI_ERROR_MORE_DATA;
66 } 69 }
67 if (data) { 70 if (data) {
68 if (entry.object) { 71 if (entry.is_interface) {
69 entry.object->AddRef(); 72 if (entry.object) entry.object->AddRef();
70 std::memcpy(data, &entry.object, sizeof(IUnknown*)); 73 std::memcpy(data, &entry.object, sizeof(IUnknown*));
71 } else { 74 } else if (bytes) {
72 std::memcpy(data, entry.bytes.data(), bytes); 75 std::memcpy(data, entry.bytes.data(), bytes);
73 } 76 }
74 } 77 }
@@ -80,30 +83,35 @@ public:
80 } 83 }
81 84
82 HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override { 85 HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override {
83 if (size && !data) return E_INVALIDARG; 86 if (!data) return remove(guid) ? S_OK : S_FALSE;
84 PrivateData entry{guid, {}, nullptr}; 87 PrivateData entry{guid, {}, nullptr, false};
85 if (size) { 88 const auto* bytes = static_cast<const std::uint8_t*>(data);
86 const auto* bytes = static_cast<const std::uint8_t*>(data); 89 entry.bytes.assign(bytes, bytes + size);
87 entry.bytes.assign(bytes, bytes + size); 90 store(std::move(entry));
88 }
89 store(std::move(entry), size != 0);
90 return S_OK; 91 return S_OK;
91 } 92 }
92 93
93 HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override { 94 HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override {
94 IUnknown* held = const_cast<IUnknown*>(object); 95 IUnknown* held = const_cast<IUnknown*>(object);
95 if (held) held->AddRef(); 96 if (held) held->AddRef();
96 store(PrivateData{guid, {}, held}, held != nullptr); 97 store(PrivateData{guid, {}, held, true});
97 return S_OK; 98 return S_OK;
98 } 99 }
99 100
101 // The host runtime doesn't keep the name where GetPrivateData can read it (WKPDID_D3DDebugObjectNameW and the
102 // narrow key both stay missing), so the name is kept apart. A null name, which the host runtime faults on,
103 // clears it.
100 HRESULT STDMETHODCALLTYPE SetName(LPCWSTR name) override { 104 HRESULT STDMETHODCALLTYPE SetName(LPCWSTR name) override {
101 if (!name) return SetPrivateData(kDebugObjectNameW, 0, nullptr); 105 std::lock_guard lock(data_mutex_);
102 return SetPrivateData(kDebugObjectNameW, UINT((std::wcslen(name) + 1) * sizeof(wchar_t)), name); 106 name_.assign(name ? name : L"");
107 return S_OK;
103 } 108 }
104 109
105 // WKPDID_D3DDebugObjectNameW (d3dcommon.h), spelled out so nothing needs dxguid.lib. 110 // The name SetName gave the object, or an empty string.
106 static constexpr GUID kDebugObjectNameW{0x4cca5fd8, 0x921f, 0x42c8, {0x85, 0x99, 0xd2, 0x86, 0x6a, 0x3e, 0x5f, 0x7e}}; 111 std::wstring debug_name() {
112 std::lock_guard lock(data_mutex_);
113 return name_;
114 }
107 115
108 // The implementation behind a public interface pointer, or null when it is not a T. No reference is added. 116 // The implementation behind a public interface pointer, or null when it is not a T. No reference is added.
109 template<class T> 117 template<class T>
@@ -125,29 +133,39 @@ private:
125 struct PrivateData { 133 struct PrivateData {
126 GUID key; 134 GUID key;
127 std::vector<std::uint8_t> bytes; 135 std::vector<std::uint8_t> bytes;
128 IUnknown* object; // SetPrivateDataInterface: one reference held 136 IUnknown* object; // SetPrivateDataInterface: one reference held (null for a null interface)
137 bool is_interface; // set by SetPrivateDataInterface, even with null: reads back as a pointer
129 }; 138 };
130 139
131 // Replaces the entry for `entry.key` (or only removes it when `keep` is false). The replaced interface is 140 // Takes the entry for `key` out; true when there was one. The interface it held is released after the lock is
132 // released after the lock is dropped, since its Release may run arbitrary code. 141 // dropped, since its Release may run arbitrary code.
133 void store(PrivateData entry, bool keep) { 142 bool remove(REFGUID key) { return replace(key, nullptr); }
143 void store(PrivateData entry) {
144 const GUID key = entry.key;
145 replace(key, &entry);
146 }
147 bool replace(REFGUID key, PrivateData* entry) {
134 IUnknown* released = nullptr; 148 IUnknown* released = nullptr;
149 bool found = false;
135 { 150 {
136 std::lock_guard lock(data_mutex_); 151 std::lock_guard lock(data_mutex_);
137 for (auto it = data_.begin(); it != data_.end(); ++it) { 152 for (auto it = data_.begin(); it != data_.end(); ++it) {
138 if (it->key != entry.key) continue; 153 if (it->key != key) continue;
139 released = it->object; 154 released = it->object;
140 data_.erase(it); 155 data_.erase(it);
156 found = true;
141 break; 157 break;
142 } 158 }
143 if (keep) data_.push_back(std::move(entry)); 159 if (entry) data_.push_back(std::move(*entry));
144 } 160 }
145 if (released) released->Release(); 161 if (released) released->Release();
162 return found;
146 } 163 }
147 164
148 std::atomic<ULONG> refs_{1}; 165 std::atomic<ULONG> refs_{1};
149 std::mutex data_mutex_; 166 std::mutex data_mutex_;
150 std::vector<PrivateData> data_; 167 std::vector<PrivateData> data_;
168 std::wstring name_;
151}; 169};
152 170
153// An ID3D12DeviceChild: holds a reference to its device, as D3D12 children do, and GetDevice returns it. When the 171// An ID3D12DeviceChild: holds a reference to its device, as D3D12 children do, and GetDevice returns it. When the
diff --git a/runtime/shims/d3d12_feature_compat.h b/runtime/shims/d3d12_feature_compat.h
new file mode 100644
index 000000000..ad14f19cd
--- /dev/null
+++ b/runtime/shims/d3d12_feature_compat.h
@@ -0,0 +1,18 @@
1#pragma once
2
3#include <d3d12.h>
4
5// D3D12_FEATURE values introduced after Windows SDK 10.0.26100.0. Keep their ABI values and payload available to
6// the runtime and its tests without requiring a newer d3d12.h.
7namespace rt::d3d12::compat {
8
9inline constexpr D3D12_FEATURE kFeatureApplicationSpecificDriverState = static_cast<D3D12_FEATURE>(56);
10inline constexpr D3D12_FEATURE kFeatureBytecodeBypassHashSupported = static_cast<D3D12_FEATURE>(57);
11
12struct FeatureSupportFlag {
13 BOOL Supported;
14};
15
16static_assert(sizeof(FeatureSupportFlag) == sizeof(BOOL));
17
18} // namespace rt::d3d12::compat
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index adacb4bf8..3fb36bd4a 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -8,6 +8,7 @@
8#define VK_USE_PLATFORM_WIN32_KHR 8#define VK_USE_PLATFORM_WIN32_KHR
9#endif 9#endif
10#include "d3d12_com.h" 10#include "d3d12_com.h"
11#include "d3d12_feature_compat.h"
11 12
12#include "d3d12_stubs.h" // generated 13#include "d3d12_stubs.h" // generated
13#include "d3d12_com_object.h" 14#include "d3d12_com_object.h"
@@ -21,6 +22,7 @@
21#include "../src/resource_tiling.h" 22#include "../src/resource_tiling.h"
22#include "../src/cached_pso.h" 23#include "../src/cached_pso.h"
23#include "../src/shader_library.h" 24#include "../src/shader_library.h"
25#include "../src/spirv_f16_halves.h"
24#include "../src/vulkan_present.h" 26#include "../src/vulkan_present.h"
25#include "../src/vulkan_device_filter.h" 27#include "../src/vulkan_device_filter.h"
26#include "../src/vulkan13_features.h" 28#include "../src/vulkan13_features.h"
@@ -389,6 +391,15 @@ struct TextureCreateInfo {
389// What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. 391// What a device's children need from it, kept apart from the COM class so children can hold a plain pointer.
390struct DeviceState { 392struct DeviceState {
391 VulkanDeviceInfo info; 393 VulkanDeviceInfo info;
394 std::vector<std::uint32_t> families;
395
396 template<typename CreateInfo>
397 void share(CreateInfo& create) const {
398 if (families.size() < 2) return;
399 create.sharingMode = VK_SHARING_MODE_CONCURRENT;
400 create.queueFamilyIndexCount = std::uint32_t(families.size());
401 create.pQueueFamilyIndices = families.data();
402 }
392 std::unique_ptr<leonida::VulkanContext> context; 403 std::unique_ptr<leonida::VulkanContext> context;
393 VkPhysicalDeviceMemoryProperties memory{}; 404 VkPhysicalDeviceMemoryProperties memory{};
394 // D3D-96: upload-heap buffers prefer DEVICE_LOCAL | HOST_VISIBLE memory, so the GPU reads them from VRAM. Only 405 // D3D-96: upload-heap buffers prefer DEVICE_LOCAL | HOST_VISIBLE memory, so the GPU reads them from VRAM. Only
@@ -715,7 +726,9 @@ struct DeviceState {
715 } 726 }
716 auto& vk = context->vk; // without the query, a throwaway image 727 auto& vk = context->vk; // without the query, a throwaway image
717 VkImage image = VK_NULL_HANDLE; 728 VkImage image = VK_NULL_HANDLE;
718 if (vk.vkCreateImage(info.device, &create, nullptr, &image) != VK_SUCCESS) return false; 729 VkImageCreateInfo shared = create;
730 share(shared);
731 if (vk.vkCreateImage(info.device, &shared, nullptr, &image) != VK_SUCCESS) return false;
719 vk.vkGetImageMemoryRequirements(info.device, image, &out); 732 vk.vkGetImageMemoryRequirements(info.device, image, &out);
720 vk.vkDestroyImage(info.device, image, nullptr); 733 vk.vkDestroyImage(info.device, image, nullptr);
721 return true; 734 return true;
@@ -1046,6 +1059,12 @@ struct DeviceState {
1046 if (context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) == VK_SUCCESS) { 1059 if (context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) == VK_SUCCESS) {
1047 if (chosen) *chosen = memory.memoryTypes[i].propertyFlags; 1060 if (chosen) *chosen = memory.memoryTypes[i].propertyFlags;
1048 if (chosen_type) *chosen_type = i; 1061 if (chosen_type) *chosen_type = i;
1062 if ((preferred & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) &&
1063 !(memory.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) {
1064 const std::string msg = "resource allocation spilled from DEVICE_LOCAL to host memory (heap " +
1065 std::to_string(memory.memoryTypes[i].heapIndex) + "); size in KiB:";
1066 log_once(msg.c_str(), static_cast<int>(requirements.size / 1024));
1067 }
1049 return out; 1068 return out;
1050 } 1069 }
1051 } 1070 }
@@ -1193,9 +1212,59 @@ const char* heap_desc_refusal(const D3D12_HEAP_DESC& desc) {
1193// measured on an RX 9070 XT, an integrated Radeon and WARP, which agree on all of them. Cross-adapter resources 1212// measured on an RX 9070 XT, an integrated Radeon and WARP, which agree on all of them. Cross-adapter resources
1194// (valid there only as a row-major texture on a SHARED | SHARED_CROSS_ADAPTER heap) are refused: this layer has no 1213// (valid there only as a row-major texture on a SHARED | SHARED_CROSS_ADAPTER heap) are refused: this layer has no
1195// cross-adapter sharing. 1214// cross-adapter sharing.
1215// The initial state a committed, placed or reserved resource may start in, as the host runtime answers it
1216// (d3d12_vulkan_device_test's compare_placed_reserved and its "committed: ... state" cases, RTX 3060 / 610.88).
1217// A buffer takes any bits, unknown ones too, except RAYTRACING_ACCELERATION_STRUCTURE without UAV access, or at all
1218// on a device without acceleration structures (the host refuses it where OPTIONS5 reports no ray tracing: an
1219// integrated Radeon, measured by @aguedou-34 on #2462; here, a device with neither the KHR acceleration structures
1220// nor the XDXR builds). A texture
1221// takes exactly GENERIC_READ, or one write state alone (RENDER_TARGET, UNORDERED_ACCESS and DEPTH_WRITE need the
1222// matching resource flag), or any mix of read states (DEPTH_READ needs ALLOW_DEPTH_STENCIL; the shader-resource
1223// states are refused with DENY_SHADER_RESOURCE). The buffer-only bits (vertex/constant, index, indirect, stream
1224// output, acceleration structure) and undefined bits are refused on a texture, also inside a mix.
1225const char* initial_state_refusal(bool buffer, UINT flags, D3D12_RESOURCE_STATES state,
1226 bool acceleration_structures) {
1227 const UINT s = UINT(state);
1228 if (buffer) {
1229 if ((s & D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) && !acceleration_structures)
1230 return "acceleration-structure state on a device without acceleration structures";
1231 if ((s & D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) &&
1232 !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))
1233 return "acceleration-structure state on a buffer without UAV access";
1234 return nullptr;
1235 }
1236 if (s == D3D12_RESOURCE_STATE_GENERIC_READ) return nullptr;
1237 constexpr UINT writes = D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS |
1238 D3D12_RESOURCE_STATE_DEPTH_WRITE | D3D12_RESOURCE_STATE_COPY_DEST |
1239 D3D12_RESOURCE_STATE_RESOLVE_DEST | D3D12_RESOURCE_STATE_VIDEO_DECODE_WRITE |
1240 D3D12_RESOURCE_STATE_VIDEO_PROCESS_WRITE | D3D12_RESOURCE_STATE_VIDEO_ENCODE_WRITE;
1241 constexpr UINT shader_reads =
1242 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
1243 constexpr UINT reads = D3D12_RESOURCE_STATE_DEPTH_READ | shader_reads | D3D12_RESOURCE_STATE_COPY_SOURCE |
1244 D3D12_RESOURCE_STATE_RESOLVE_SOURCE | D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE |
1245 D3D12_RESOURCE_STATE_VIDEO_DECODE_READ | D3D12_RESOURCE_STATE_VIDEO_PROCESS_READ |
1246 D3D12_RESOURCE_STATE_VIDEO_ENCODE_READ;
1247 if (s & ~(writes | reads)) return "initial state of a texture (buffer-only or undefined bits)";
1248 if (s & writes) {
1249 if (s & (s - 1)) return "initial state of a texture (a write state with another state)";
1250 if (s == D3D12_RESOURCE_STATE_RENDER_TARGET && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET))
1251 return "RENDER_TARGET state without ALLOW_RENDER_TARGET";
1252 if (s == D3D12_RESOURCE_STATE_UNORDERED_ACCESS && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))
1253 return "UNORDERED_ACCESS state without ALLOW_UNORDERED_ACCESS";
1254 if (s == D3D12_RESOURCE_STATE_DEPTH_WRITE && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))
1255 return "DEPTH_WRITE state without ALLOW_DEPTH_STENCIL";
1256 return nullptr;
1257 }
1258 if ((s & D3D12_RESOURCE_STATE_DEPTH_READ) && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))
1259 return "DEPTH_READ state without ALLOW_DEPTH_STENCIL";
1260 if ((s & shader_reads) && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE))
1261 return "shader-resource state with DENY_SHADER_RESOURCE";
1262 return nullptr;
1263}
1264
1196const char* committed_resource_refusal(const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags, 1265const char* committed_resource_refusal(const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags,
1197 const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, 1266 const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state,
1198 const D3D12_CLEAR_VALUE* clear) { 1267 const D3D12_CLEAR_VALUE* clear, bool acceleration_structures) {
1199 if (const char* why = heap_properties_refusal(heap)) return why; 1268 if (const char* why = heap_properties_refusal(heap)) return why;
1200 // The DENY flags of a committed resource's heap are the runtime's to choose; most other bits are refused too. 1269 // The DENY flags of a committed resource's heap are the runtime's to choose; most other bits are refused too.
1201 constexpr UINT committed_heap_flags = D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_ALLOW_DISPLAY | 1270 constexpr UINT committed_heap_flags = D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_ALLOW_DISPLAY |
@@ -1222,6 +1291,8 @@ const char* committed_resource_refusal(const D3D12_HEAP_PROPERTIES& heap, D3D12_
1222 if (heap.Type == D3D12_HEAP_TYPE_READBACK && (uav || (UINT(state) & ~UINT(D3D12_RESOURCE_STATE_COPY_DEST)))) 1291 if (heap.Type == D3D12_HEAP_TYPE_READBACK && (uav || (UINT(state) & ~UINT(D3D12_RESOURCE_STATE_COPY_DEST))))
1223 return "readback heap state or UAV"; 1292 return "readback heap state or UAV";
1224 1293
1294 if (const char* why = initial_state_refusal(buffer, flags, state, acceleration_structures)) return why;
1295
1225 if (buffer) { 1296 if (buffer) {
1226 if (!desc.Width || desc.Height != 1 || desc.DepthOrArraySize != 1 || desc.MipLevels != 1 || 1297 if (!desc.Width || desc.Height != 1 || desc.DepthOrArraySize != 1 || desc.MipLevels != 1 ||
1227 desc.Format != DXGI_FORMAT_UNKNOWN || desc.SampleDesc.Count != 1 || desc.SampleDesc.Quality != 0 || 1298 desc.Format != DXGI_FORMAT_UNKNOWN || desc.SampleDesc.Count != 1 || desc.SampleDesc.Quality != 0 ||
@@ -1415,6 +1486,7 @@ public:
1415 info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | 1486 info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR |
1416 VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; 1487 VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR;
1417 } 1488 }
1489 device_.share(info);
1418 if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; 1490 if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY;
1419 VkMemoryRequirements requirements{}; 1491 VkMemoryRequirements requirements{};
1420 vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); 1492 vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements);
@@ -1563,6 +1635,7 @@ public:
1563 support = device_.check_image_support(info); 1635 support = device_.check_image_support(info);
1564 } 1636 }
1565 if (FAILED(support)) return support; 1637 if (FAILED(support)) return support;
1638 device_.share(info);
1566 const VkResult created = vk.vkCreateImage(device_.info.device, &info, nullptr, &image_); 1639 const VkResult created = vk.vkCreateImage(device_.info.device, &info, nullptr, &image_);
1567 if (created != VK_SUCCESS) { 1640 if (created != VK_SUCCESS) {
1568 if (created == VK_ERROR_OUT_OF_HOST_MEMORY || created == VK_ERROR_OUT_OF_DEVICE_MEMORY) 1641 if (created == VK_ERROR_OUT_OF_HOST_MEMORY || created == VK_ERROR_OUT_OF_DEVICE_MEMORY)
@@ -1596,6 +1669,7 @@ public:
1596 binding.volume = volume; 1669 binding.volume = volume;
1597 binding.samples = samples; 1670 binding.samples = samples;
1598 binding.color_attachment = (info.usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) != 0; 1671 binding.color_attachment = (info.usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) != 0;
1672 binding.sampled = (info.usage & VK_IMAGE_USAGE_SAMPLED_BIT) != 0;
1599 binding.simultaneous_access = (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) != 0; 1673 binding.simultaneous_access = (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) != 0;
1600 binding.not_zeroed = (heap_flags_ & D3D12_HEAP_FLAG_CREATE_NOT_ZEROED) != 0; 1674 binding.not_zeroed = (heap_flags_ & D3D12_HEAP_FLAG_CREATE_NOT_ZEROED) != 0;
1601 // With the bindless set, a view's descriptor has one layout for as long as it lives (bind_image). 1675 // With the bindless set, a view's descriptor has one layout for as long as it lives (bind_image).
@@ -1714,8 +1788,10 @@ private:
1714 std::uint32_t slices; 1788 std::uint32_t slices;
1715 }; 1789 };
1716 1790
1717 // The region a copy names, or false when D3D12 would reject it: an unknown subresource, a box outside the 1791 // The region a copy names, or false when D3D12 would reject it: an unknown subresource, a box whose right,
1718 // mip, or one that cuts a compressed block anywhere but at the mip edge. 1792 // bottom or back edge lies past the mip's, or one that cuts a compressed block anywhere but at the mip edge.
1793 // An empty or inverted box that passes those checks is no copy at all: `rows` and `slices` are 0, and the host
1794 // runtime answers S_OK without touching a byte (d3d12_subresource_copy_test, RTX 3060 / 610.88).
1719 bool region(UINT subresource, const D3D12_BOX* box, Region& out) const { 1795 bool region(UINT subresource, const D3D12_BOX* box, Region& out) const {
1720 VkImageSubresourceRange range{}; 1796 VkImageSubresourceRange range{};
1721 if (subresource == leonida::all_subresources || !leonida::image_range(binding_, subresource, range)) return false; 1797 if (subresource == leonida::all_subresources || !leonida::image_range(binding_, subresource, range)) return false;
@@ -1725,15 +1801,19 @@ private:
1725 const std::uint32_t depth = binding_.volume ? std::max(1u, binding_.depth >> mip) : 1; 1801 const std::uint32_t depth = binding_.volume ? std::max(1u, binding_.depth >> mip) : 1;
1726 out.box = box ? *box : D3D12_BOX{0, 0, 0, width, height, depth}; 1802 out.box = box ? *box : D3D12_BOX{0, 0, 0, width, height, depth};
1727 const D3D12_BOX& b = out.box; 1803 const D3D12_BOX& b = out.box;
1728 if (b.left >= b.right || b.top >= b.bottom || b.front >= b.back || b.right > width || b.bottom > height || 1804 if (b.right > width || b.bottom > height || b.back > depth) return false;
1729 b.back > depth)
1730 return false;
1731 out.block = leonida::copy_block_format(binding_, range.aspectMask); 1805 out.block = leonida::copy_block_format(binding_, range.aspectMask);
1732 if (!out.block.bytes) return false; 1806 if (!out.block.bytes) return false;
1733 const std::uint32_t k = out.block.block; 1807 const std::uint32_t k = out.block.block;
1734 if (b.left % k || b.top % k || (b.right % k && b.right != width) || (b.bottom % k && b.bottom != height)) 1808 if (b.left % k || b.top % k || (b.right % k && b.right != width) || (b.bottom % k && b.bottom != height))
1735 return false; 1809 return false;
1736 out.layers = {range.aspectMask, mip, range.baseArrayLayer, 1}; 1810 out.layers = {range.aspectMask, mip, range.baseArrayLayer, 1};
1811 if (b.left >= b.right || b.top >= b.bottom || b.front >= b.back) {
1812 out.rows = 0;
1813 out.row_bytes = 0;
1814 out.slices = 0;
1815 return true;
1816 }
1737 out.rows = (b.bottom - b.top + k - 1) / k; 1817 out.rows = (b.bottom - b.top + k - 1) / k;
1738 out.row_bytes = std::uint64_t((b.right - b.left + k - 1) / k) * out.block.bytes; 1818 out.row_bytes = std::uint64_t((b.right - b.left + k - 1) / k) * out.block.bytes;
1739 out.slices = b.back - b.front; 1819 out.slices = b.back - b.front;
@@ -1745,10 +1825,9 @@ private:
1745 if (!image_ || !data) return E_INVALIDARG; 1825 if (!image_ || !data) return E_INVALIDARG;
1746 Region r{}; 1826 Region r{};
1747 if (!region(subresource, box, r)) return E_INVALIDARG; 1827 if (!region(subresource, box, r)) return E_INVALIDARG;
1748 // The application's rows and slices must not overlap. 1828 if (!r.rows || !r.slices) return S_OK; // an empty box: nothing to copy
1749 if ((r.rows > 1 && row_pitch < r.row_bytes) || 1829 // The pitches are not checked, as on the host runtime: rows or slices that overlap (a pitch smaller than a
1750 (r.slices > 1 && depth_pitch < std::uint64_t(r.rows - 1) * row_pitch + r.row_bytes)) 1830 // row, or 0) are copied in order, row by row and slice by slice, so on a read the last one wins.
1751 return E_INVALIDARG;
1752 if (!cpu_visible()) 1831 if (!cpu_visible())
1753 log_once(write ? "WriteToSubresource on a texture outside a CPU-visible heap; heap type" 1832 log_once(write ? "WriteToSubresource on a texture outside a CPU-visible heap; heap type"
1754 : "ReadFromSubresource on a texture outside a CPU-visible heap; heap type", 1833 : "ReadFromSubresource on a texture outside a CPU-visible heap; heap type",
@@ -1848,6 +1927,7 @@ private:
1848 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 1927 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
1849 info.size = staging.size; 1928 info.size = staging.size;
1850 info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; // storage: D24 depth conversion 1929 info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; // storage: D24 depth conversion
1930 device_.share(info);
1851 if (vk.vkCreateBuffer(dev, &info, nullptr, &staging.buffer) != VK_SUCCESS) return E_OUTOFMEMORY; 1931 if (vk.vkCreateBuffer(dev, &info, nullptr, &staging.buffer) != VK_SUCCESS) return E_OUTOFMEMORY;
1852 VkDeviceMemory memory = VK_NULL_HANDLE; 1932 VkDeviceMemory memory = VK_NULL_HANDLE;
1853 void* mapped = nullptr; 1933 void* mapped = nullptr;
@@ -2408,10 +2488,22 @@ public:
2408 return E_NOTIMPL; 2488 return E_NOTIMPL;
2409 } 2489 }
2410 if (desc.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG; 2490 if (desc.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG;
2411 if (desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.GS.BytecodeLength || desc.StreamOutput.NumEntries) { 2491 if (desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.StreamOutput.NumEntries) {
2412 log_once("graphics pipeline stage not supported yet (hull/domain/geometry/stream output):", 0); 2492 log_once("graphics pipeline stage not supported yet (hull/domain/stream output):", 0);
2493 return E_NOTIMPL;
2494 }
2495 // A geometry shader is the translator's Vulkan geometry stage (docs/design.md, "Geometry shaders"): it takes
2496 // triangles and emits a triangle strip. It needs the geometryShader feature, and the PSO's topology type must
2497 // be its input primitive, as D3D12 requires.
2498 const bool geometry = desc.GS.pShaderBytecode && desc.GS.BytecodeLength;
2499 if (geometry && !device_.info.features.geometryShader) {
2500 log_once("geometry shaders need the Vulkan geometryShader feature; stage", 0);
2413 return E_NOTIMPL; 2501 return E_NOTIMPL;
2414 } 2502 }
2503 if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) {
2504 log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType);
2505 return E_INVALIDARG;
2506 }
2415 const UINT samples = desc.SampleDesc.Count; 2507 const UINT samples = desc.SampleDesc.Count;
2416 if (!samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || (samples & (samples - 1))) { 2508 if (!samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || (samples & (samples - 1))) {
2417 log_once("invalid graphics pipeline sample count:", int(samples)); 2509 log_once("invalid graphics pipeline sample count:", int(samples));
@@ -2422,12 +2514,12 @@ public:
2422 // E_INVALIDARG, as NumQualityLevels is 1). The standard pattern is Vulkan's standard sample positions, so it 2514 // E_INVALIDARG, as NumQualityLevels is 1). The standard pattern is Vulkan's standard sample positions, so it
2423 // is quality 0 here. The centre pattern puts every sample at the pixel centre, which needs custom sample 2515 // is quality 0 here. The centre pattern puts every sample at the pixel centre, which needs custom sample
2424 // locations: refused with a log until those are set. 2516 // locations: refused with a log until those are set.
2425 if (desc.SampleDesc.Quality == UINT(D3D12_CENTER_MULTISAMPLE_PATTERN)) { 2517 if (desc.SampleDesc.Quality == DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) {
2426 log_once("D3D12_CENTER_MULTISAMPLE_PATTERN needs custom sample locations (not set yet); samples", 2518 log_once("D3D12_CENTER_MULTISAMPLE_PATTERN needs custom sample locations (not set yet); samples",
2427 int(samples)); 2519 int(samples));
2428 return E_NOTIMPL; 2520 return E_NOTIMPL;
2429 } 2521 }
2430 if (desc.SampleDesc.Quality != 0 && desc.SampleDesc.Quality != UINT(D3D12_STANDARD_MULTISAMPLE_PATTERN)) { 2522 if (desc.SampleDesc.Quality != 0 && desc.SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN) {
2431 log_once("invalid graphics pipeline sample quality:", int(desc.SampleDesc.Quality)); 2523 log_once("invalid graphics pipeline sample quality:", int(desc.SampleDesc.Quality));
2432 return E_INVALIDARG; 2524 return E_INVALIDARG;
2433 } 2525 }
@@ -2440,8 +2532,14 @@ public:
2440 const D3D12_SHADER_BYTECODE& code; 2532 const D3D12_SHADER_BYTECODE& code;
2441 const leonida::ShaderEntry* entry = nullptr; 2533 const leonida::ShaderEntry* entry = nullptr;
2442 std::vector<std::uint8_t> fssm; 2534 std::vector<std::uint8_t> fssm;
2535 std::vector<std::uint32_t> words;
2443 }; 2536 };
2444 Stage stages[2] = {{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}}; 2537 Stage stages[3] = {{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS},
2538 {"gs", VK_SHADER_STAGE_GEOMETRY_BIT, desc.GS},
2539 {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}};
2540 // stage_infos.size() indexes the recipe's per-stage required-size structs: one for every table entry.
2541 static_assert(std::size(stages) <= std::size(decltype(recipe_.required_sizes){}),
2542 "Recipe::required_sizes needs an entry per graphics stage");
2445 bool uses_bindless = false; // a stage declares set-0 bindings: the layout holds the device's set 0 2543 bool uses_bindless = false; // a stage declares set-0 bindings: the layout holds the device's set 0
2446 std::vector<VkPipelineShaderStageCreateInfo> stage_infos; 2544 std::vector<VkPipelineShaderStageCreateInfo> stage_infos;
2447 // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe. 2545 // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe.
@@ -2481,11 +2579,32 @@ public:
2481 } 2579 }
2482 code_stage = &stage; 2580 code_stage = &stage;
2483 } 2581 }
2484 const std::vector<std::uint32_t> words = library->spirv(*stage.entry); 2582 stage.words = library->spirv(*stage.entry);
2485 if (words.empty()) return E_FAIL; 2583 if (stage.words.empty()) return E_FAIL;
2584 }
2585 // --f16-interp-fallback (SHADER-378): align/synthesize VS decoded f16 halves for this (VS, PS) pair before
2586 // creating the shader modules so colliding PS and high-param producers link within MoltenVK's 30 locations.
2587 // stages[] is {vs, gs, ps} since geometry shaders joined graphics PSOs (#2109): the PS is stages[2], and with a
2588 // GS the PS reads the GS's outputs, not the VS's, so the VS/PS halves link only applies without one.
2589 Stage& vs_stage = stages[0];
2590 Stage& gs_stage = stages[1];
2591 Stage& ps_stage = stages[2];
2592 if (vs_stage.entry && ps_stage.entry && !ps_stage.entry->f16_halves.empty() && gs_stage.entry) {
2593 log_once("--f16-interp-fallback halves are linked VS->PS only; this PSO has a geometry shader", 0);
2594 }
2595 if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && !ps_stage.entry->f16_halves.empty()) {
2596 std::string link_error;
2597 if (!leonida::link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry,
2598 &link_error)) {
2599 std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str());
2600 return E_FAIL;
2601 }
2602 }
2603 for (Stage& stage : stages) {
2604 if (!stage.entry) continue;
2486 VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 2605 VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
2487 module_info.codeSize = words.size() * 4; 2606 module_info.codeSize = stage.words.size() * 4;
2488 module_info.pCode = words.data(); 2607 module_info.pCode = stage.words.data();
2489 VkShaderModule module = VK_NULL_HANDLE; 2608 VkShaderModule module = VK_NULL_HANDLE;
2490 if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; 2609 if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL;
2491 modules_.push_back(module); 2610 modules_.push_back(module);
@@ -2729,7 +2848,10 @@ public:
2729 } 2848 }
2730 // Every stage this path accepts reads the user SGPRs, so the range covers the whole stage table, not only the 2849 // Every stage this path accepts reads the user SGPRs, so the range covers the whole stage table, not only the
2731 // stages present. A stage added to the table (geometry, mesh) is covered without touching this. 2850 // stages present. A stage added to the table (geometry, mesh) is covered without touching this.
2732 for (const Stage& stage : stages) graphics_.push_stages |= stage.bit; 2851 // (The geometry bit only where the device has the stage: a range may not name a stage it cannot run.)
2852 for (const Stage& stage : stages)
2853 if (stage.bit != VK_SHADER_STAGE_GEOMETRY_BIT || device_.info.features.geometryShader)
2854 graphics_.push_stages |= stage.bit;
2733 const VkPushConstantRange push{graphics_.push_stages, 0, sizeof(leonida::ShaderUserData)}; 2855 const VkPushConstantRange push{graphics_.push_stages, 0, sizeof(leonida::ShaderUserData)};
2734 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 2856 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
2735 layout_info.pushConstantRangeCount = 1; 2857 layout_info.pushConstantRangeCount = 1;
@@ -2887,7 +3009,8 @@ private:
2887 // What a graphics pipeline is made from, so variants can be built at draw time. 3009 // What a graphics pipeline is made from, so variants can be built at draw time.
2888 struct Recipe { 3010 struct Recipe {
2889 std::vector<VkPipelineShaderStageCreateInfo> stages; 3011 std::vector<VkPipelineShaderStageCreateInfo> stages;
2890 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_sizes[2]{}; // what `stages` chain 3012 // One per entry of create_graphics's stage table (VS, GS, PS), static_assert there; what `stages` chain.
3013 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_sizes[3]{};
2891 std::vector<VkVertexInputAttributeDescription> attributes; 3014 std::vector<VkVertexInputAttributeDescription> attributes;
2892 std::vector<VkVertexInputBindingDescription> bindings; 3015 std::vector<VkVertexInputBindingDescription> bindings;
2893 VkPipelineInputAssemblyStateCreateInfo assembly{}; 3016 VkPipelineInputAssemblyStateCreateInfo assembly{};
@@ -3694,6 +3817,11 @@ public:
3694 explicit Device(const VulkanDeviceInfo& info) { 3817 explicit Device(const VulkanDeviceInfo& info) {
3695 state_.info = info; 3818 state_.info = info;
3696 queue_busy_.resize(info.command_queues.size(), false); 3819 queue_busy_.resize(info.command_queues.size(), false);
3820 compute_busy_.resize(info.compute_queues.size(), false);
3821 copy_busy_.resize(info.copy_queues.size(), false);
3822 for (std::uint32_t f : {info.queue_family, info.compute_family, info.copy_family})
3823 if (f != UINT32_MAX && std::find(state_.families.begin(), state_.families.end(), f) == state_.families.end())
3824 state_.families.push_back(f);
3697 const auto get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>( 3825 const auto get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(
3698 info.get_instance_proc(info.instance, "vkGetDeviceProcAddr")); 3826 info.get_instance_proc(info.instance, "vkGetDeviceProcAddr"));
3699 state_.format_properties = reinterpret_cast<PFN_vkGetPhysicalDeviceFormatProperties>( 3827 state_.format_properties = reinterpret_cast<PFN_vkGetPhysicalDeviceFormatProperties>(
@@ -3794,6 +3922,8 @@ public:
3794 families(info.physical, &count, nullptr); 3922 families(info.physical, &count, nullptr);
3795 std::vector<VkQueueFamilyProperties> queues(count); 3923 std::vector<VkQueueFamilyProperties> queues(count);
3796 families(info.physical, &count, queues.data()); 3924 families(info.physical, &count, queues.data());
3925 if (info.copy_family < count && !(queues[info.copy_family].queueFlags & VK_QUEUE_COMPUTE_BIT))
3926 state_.context->set_transfer_only_family(info.copy_family);
3797 if (info.queue_family < count && (queues[info.queue_family].queueFlags & VK_QUEUE_COMPUTE_BIT)) { 3927 if (info.queue_family < count && (queues[info.queue_family].queueFlags & VK_QUEUE_COMPUTE_BIT)) {
3798 state_.context->configure_predication(get_device, state_.memory, limits.limits.maxStorageBufferRange, info.queue_family); 3928 state_.context->configure_predication(get_device, state_.memory, limits.limits.maxStorageBufferRange, info.queue_family);
3799 if (info.storage_buffer_8bit) state_.context->configure_predicated_copy(get_device, limits.limits); 3929 if (info.storage_buffer_8bit) state_.context->configure_predicated_copy(get_device, limits.limits);
@@ -3838,6 +3968,21 @@ public:
3838 const auto& family = families[info.queue_family]; 3968 const auto& family = families[info.queue_family];
3839 if (family.timestampValidBits) 3969 if (family.timestampValidBits)
3840 state_.context->set_timestamp_period(properties.limits.timestampPeriod); 3970 state_.context->set_timestamp_period(properties.limits.timestampPeriod);
3971 // MoltenVK (1.4.2 and 1.4.3 measured) resolves a timestamp before the write that precedes it lands, unless
3972 // something orders the two (docs/d3d12_vulkan.md section 4.6).
3973 const auto get_props2 = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
3974 info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2")
3975 : nullptr);
3976 if (family.timestampValidBits && get_props2) {
3977 VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
3978 VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver};
3979 get_props2(info.physical, &props);
3980 if (driver.driverID == VK_DRIVER_ID_MOLTENVK) {
3981 state_.context->set_order_timestamp_copies(true);
3982 log_once("timestamp resolves wait for the timestamps before them (MoltenVK); driver",
3983 int(driver.driverID));
3984 }
3985 }
3841 if (family.queueFlags & VK_QUEUE_COMPUTE_BIT) 3986 if (family.queueFlags & VK_QUEUE_COMPUTE_BIT)
3842 state_.context->set_occlusion_resolve_memory(state_.memory); 3987 state_.context->set_occlusion_resolve_memory(state_.memory);
3843 } 3988 }
@@ -3987,6 +4132,7 @@ public:
3987 if (state_.info.ray_tracing) 4132 if (state_.info.ray_tracing)
3988 info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | 4133 info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR |
3989 VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; 4134 VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR;
4135 state_.share(info);
3990 if (vk.vkCreateBuffer(state_.info.device, &info, nullptr, &arena.buffer) != VK_SUCCESS) { 4136 if (vk.vkCreateBuffer(state_.info.device, &info, nullptr, &arena.buffer) != VK_SUCCESS) {
3991 arena.buffer = VK_NULL_HANDLE; 4137 arena.buffer = VK_NULL_HANDLE;
3992 return false; 4138 return false;
@@ -4049,6 +4195,10 @@ public:
4049 4195
4050 bool ok() const { return state_.context && state_.context->loaded(); } 4196 bool ok() const { return state_.context && state_.context->loaded(); }
4051 const VulkanDeviceInfo& info() const { return state_.info; } 4197 const VulkanDeviceInfo& info() const { return state_.info; }
4198 // Acceleration-structure resources work: KHR builds, or the XDXR records (which need the GPU address arena).
4199 bool acceleration_structures() const {
4200 return state_.info.ray_tracing || (state_.info.xdxr_acceleration_structures && state_.info.buffer_device_address);
4201 }
4052 bool upload_in_vram() const { return state_.upload_in_vram; } 4202 bool upload_in_vram() const { return state_.upload_in_vram; }
4053 leonida::VulkanContext& context() { return *state_.context; } 4203 leonida::VulkanContext& context() { return *state_.context; }
4054 const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } 4204 const leonida::BindlessSet* bindless() const { return state_.bindless.get(); }
@@ -4067,9 +4217,11 @@ public:
4067 // The CUSTOM equivalent of a standard heap type, from the D3D12 documentation's table for a NUMA adapter 4217 // The CUSTOM equivalent of a standard heap type, from the D3D12 documentation's table for a NUMA adapter
4068 // (D3D12_FEATURE_ARCHITECTURE answers UMA = FALSE): DEFAULT is GPU-only memory in L1, UPLOAD write-combined 4218 // (D3D12_FEATURE_ARCHITECTURE answers UMA = FALSE): DEFAULT is GPU-only memory in L1, UPLOAD write-combined
4069 // and READBACK write-back system memory in L0, GPU_UPLOAD write-combined L1. CUSTOM and unknown types have 4219 // and READBACK write-back system memory in L0, GPU_UPLOAD write-combined L1. CUSTOM and unknown types have
4070 // no equivalent and get an all-zero answer (D3D12 reports them through the debug layer). 4220 // no equivalent and get an all-zero answer (D3D12 reports them through the debug layer), with node 0 in both node
4221 // masks as the host runtime gives it (d3d12_fence_timing_test compares CUSTOM, an unknown type and node mask 2).
4071 D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE GetCustomHeapProperties(UINT node_mask, D3D12_HEAP_TYPE type) override { 4222 D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE GetCustomHeapProperties(UINT node_mask, D3D12_HEAP_TYPE type) override {
4072 D3D12_HEAP_PROPERTIES properties{}; 4223 D3D12_HEAP_PROPERTIES properties{};
4224 properties.CreationNodeMask = properties.VisibleNodeMask = 1;
4073 if (node_mask > 1) { 4225 if (node_mask > 1) {
4074 log_once("GetCustomHeapProperties node mask", int(node_mask)); 4226 log_once("GetCustomHeapProperties node mask", int(node_mask));
4075 return properties; 4227 return properties;
@@ -4096,8 +4248,6 @@ public:
4096 return properties; 4248 return properties;
4097 } 4249 }
4098 properties.Type = D3D12_HEAP_TYPE_CUSTOM; 4250 properties.Type = D3D12_HEAP_TYPE_CUSTOM;
4099 properties.CreationNodeMask = 1;
4100 properties.VisibleNodeMask = 1;
4101 return properties; 4251 return properties;
4102 } 4252 }
4103 4253
@@ -4223,8 +4373,32 @@ public:
4223 return d3d12_trace::result(method, create_command_queue(*state_.context, state_.info.queue, 4373 return d3d12_trace::result(method, create_command_queue(*state_.context, state_.info.queue,
4224 state_.info.queue_family, *desc, riid, out, 4374 state_.info.queue_family, *desc, riid, out,
4225 identity(), state_.clock)); 4375 identity(), state_.clock));
4226 // Vulkan only guarantees ordering within a VkQueue. Assign a distinct handle to each live D3D12 queue; 4376 if (desc->Type != D3D12_COMMAND_LIST_TYPE_DIRECT) {
4227 // otherwise a Wait submitted before another queue's Signal can deadlock the shared handle. 4377 const bool compute = desc->Type == D3D12_COMMAND_LIST_TYPE_COMPUTE;
4378 auto& busy = compute ? compute_busy_ : copy_busy_;
4379 const auto& queues = compute ? state_.info.compute_queues : state_.info.copy_queues;
4380 const std::uint32_t family = compute ? state_.info.compute_family : state_.info.copy_family;
4381 std::size_t dedicated = busy.size();
4382 {
4383 std::lock_guard lock(queue_mutex_);
4384 for (std::size_t i = 0; i < busy.size(); ++i) {
4385 if (!busy[i]) {
4386 busy[i] = true;
4387 dedicated = i;
4388 break;
4389 }
4390 }
4391 }
4392 if (dedicated < busy.size()) {
4393 std::shared_ptr<void> lease(nullptr, [this, compute, dedicated](void*) {
4394 std::lock_guard lock(queue_mutex_);
4395 (compute ? compute_busy_ : copy_busy_)[dedicated] = false;
4396 });
4397 return d3d12_trace::result(method, create_command_queue(*state_.context, queues[dedicated], family,
4398 *desc, riid, out, identity(), state_.clock,
4399 std::move(lease)));
4400 }
4401 }
4228 std::size_t slot = queue_busy_.size(); 4402 std::size_t slot = queue_busy_.size();
4229 { 4403 {
4230 std::lock_guard lock(queue_mutex_); 4404 std::lock_guard lock(queue_mutex_);
@@ -4468,30 +4642,41 @@ public:
4468 4642
4469 HRESULT STDMETHODCALLTYPE CreateQueryHeap(const D3D12_QUERY_HEAP_DESC* desc, REFIID riid, void** out) override { 4643 HRESULT STDMETHODCALLTYPE CreateQueryHeap(const D3D12_QUERY_HEAP_DESC* desc, REFIID riid, void** out) override {
4470 if (out) *out = nullptr; 4644 if (out) *out = nullptr;
4471 if (!desc || !desc->Count || desc->NodeMask > 1) return E_INVALIDARG; // one node 4645 // The host runtime's order (compare_invalid_arguments, "query heap:"): the description first, refused with
4646 // E_INVALIDARG for no queries, a node other than node 0 or a type past PIPELINE_STATISTICS1 (7; 6 has no
4647 // name in the SDK but the host takes it), then E_UNEXPECTED for a null output. A known type this layer
4648 // can't create stays E_NOTIMPL.
4649 if (!desc || !desc->Count || desc->NodeMask > 1 ||
4650 UINT(desc->Type) > UINT(D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1))
4651 return E_INVALIDARG;
4652 if (!out) return E_UNEXPECTED;
4472 auto* heap = new QueryHeap(state_); 4653 auto* heap = new QueryHeap(state_);
4473 heap->attach_device(identity()); 4654 heap->attach_device(identity());
4474 if (const HRESULT hr = heap->create(*desc); FAILED(hr)) { 4655 if (const HRESULT hr = heap->create(*desc); FAILED(hr)) {
4475 heap->Release(); 4656 heap->Release();
4476 return hr; 4657 return hr;
4477 } 4658 }
4478 if (!out) { // a capability check: D3D12 allows a null output
4479 heap->Release();
4480 return S_FALSE;
4481 }
4482 return hand_out(heap, riid, out); 4659 return hand_out(heap, riid, out);
4483 } 4660 }
4484 4661
4485 HRESULT STDMETHODCALLTYPE CreateRootSignature(UINT, const void* blob, SIZE_T size, REFIID riid, 4662 HRESULT STDMETHODCALLTYPE CreateRootSignature(UINT node_mask, const void* blob, SIZE_T size, REFIID riid,
4486 void** out) override { 4663 void** out) override {
4487 if (!out) return E_POINTER; 4664 // The host runtime answers a null output with S_FALSE before it looks at the blob or the node mask
4665 // (compare_invalid_arguments, "root signature:"). Otherwise it refuses a node other than node 0, and a DXBC
4666 // container whose own size (the dword at +24) is not the size passed.
4667 if (!out) return S_FALSE;
4488 *out = nullptr; 4668 *out = nullptr;
4489 if (!blob || !size) return E_INVALIDARG; 4669 if (!blob || !size || (node_mask & ~1u)) return E_INVALIDARG;
4670 const auto* bytes = static_cast<const std::uint8_t*>(blob);
4671 if (size >= 28 && std::memcmp(bytes, "DXBC", 4) == 0) {
4672 std::uint32_t container_size = 0;
4673 std::memcpy(&container_size, bytes + 24, sizeof(container_size));
4674 if (container_size != size) return E_INVALIDARG;
4675 }
4490 // The repository's root-signature model (runtime/src/root_signature.h): parse the RTS0 blob, then pack 4676 // The repository's root-signature model (runtime/src/root_signature.h): parse the RTS0 blob, then pack
4491 // the parameters into the 32 user-data dwords. pack() refuses what it cannot place (more than 32 dwords: 4677 // the parameters into the 32 user-data dwords. pack() refuses what it cannot place (more than 32 dwords:
4492 // the console spills those to memory, in a layout that is still open), and so does this. 4678 // the console spills those to memory, in a layout that is still open), and so does this.
4493 const rt::rootsig::DecodeResult parsed = 4679 const rt::rootsig::DecodeResult parsed = rt::rootsig::parse_rts0(bytes, size);
4494 rt::rootsig::parse_rts0(static_cast<const std::uint8_t*>(blob), size);
4495 if (!parsed.ok) { 4680 if (!parsed.ok) {
4496 std::fprintf(stderr, "[rt] d3d12: root signature not understood: %s\n", parsed.error.c_str()); 4681 std::fprintf(stderr, "[rt] d3d12: root signature not understood: %s\n", parsed.error.c_str());
4497 return E_INVALIDARG; 4682 return E_INVALIDARG;
@@ -5154,7 +5339,8 @@ public:
5154 if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); 5339 if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG);
5155 // The host runtime's argument checks (D3D-49). A refusal is logged once per reason and dimension, since a 5340 // The host runtime's argument checks (D3D-49). A refusal is logged once per reason and dimension, since a
5156 // game that trips one (for example with an Xbox-only flag through slot 76) gets no resource. 5341 // game that trips one (for example with an Xbox-only flag through slot 76) gets no resource.
5157 if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear)) { 5342 if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear,
5343 acceleration_structures())) {
5158 log_once((std::string("CreateCommittedResource refused (") + why + "), dimension").c_str(), 5344 log_once((std::string("CreateCommittedResource refused (") + why + "), dimension").c_str(),
5159 desc->Dimension); 5345 desc->Dimension);
5160 return d3d12_trace::result(method, E_INVALIDARG); 5346 return d3d12_trace::result(method, E_INVALIDARG);
@@ -5181,32 +5367,35 @@ public:
5181 // (64KB_STANDARD_SWIZZLE needs StandardSwizzle64KBSupported, which CheckFeatureSupport reports as FALSE). The 5367 // (64KB_STANDARD_SWIZZLE needs StandardSwizzle64KBSupported, which CheckFeatureSupport reports as FALSE). The
5182 // Xbox tiled layout word 0x101 (slot 76, section 4.2) is accepted as 64KB_UNDEFINED_SWIZZLE; that the console 5368 // Xbox tiled layout word 0x101 (slot 76, section 4.2) is accepted as 64KB_UNDEFINED_SWIZZLE; that the console
5183 // uses it for reserved resources too is an assumption. 5369 // uses it for reserved resources too is an assumption.
5184 HRESULT STDMETHODCALLTYPE CreateReservedResource(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES, 5370 HRESULT STDMETHODCALLTYPE CreateReservedResource(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
5185 const D3D12_CLEAR_VALUE*, REFIID riid, void** out) override { 5371 const D3D12_CLEAR_VALUE* clear, REFIID riid,
5372 void** out) override {
5186 constexpr auto method = "ID3D12Device::CreateReservedResource"; 5373 constexpr auto method = "ID3D12Device::CreateReservedResource";
5187 return d3d12_trace::result(method, create_reserved(desc, riid, out)); 5374 return d3d12_trace::result(method, create_reserved(desc, state, clear, riid, out));
5188 } 5375 }
5189 5376
5190 // Device4. Protected sessions are not supported. 5377 // Device4. Protected sessions are not supported.
5191 HRESULT STDMETHODCALLTYPE CreateReservedResource1(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES, 5378 HRESULT STDMETHODCALLTYPE CreateReservedResource1(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
5192 const D3D12_CLEAR_VALUE*, ID3D12ProtectedResourceSession* session, 5379 const D3D12_CLEAR_VALUE* clear,
5193 REFIID riid, void** out) override { 5380 ID3D12ProtectedResourceSession* session, REFIID riid,
5381 void** out) override {
5194 if (session) { 5382 if (session) {
5195 if (out) *out = nullptr; 5383 if (out) *out = nullptr;
5196 log_once("CreateReservedResource1 with a protected session not supported:", 1); 5384 log_once("CreateReservedResource1 with a protected session not supported:", 1);
5197 return E_NOTIMPL; 5385 return E_NOTIMPL;
5198 } 5386 }
5199 return create_reserved(desc, riid, out); 5387 return create_reserved(desc, state, clear, riid, out);
5200 } 5388 }
5201 5389
5202 // Device10: an initial layout instead of a state (resources start in their first use's layout here anyway). 5390 // Device10: an initial layout instead of a state (resources start in their first use's layout here anyway).
5203 // Castable formats are not used: typeless resources are already mutable-format images. 5391 // Castable formats are not used: typeless resources are already mutable-format images.
5204 HRESULT STDMETHODCALLTYPE CreateReservedResource2(const D3D12_RESOURCE_DESC* desc, D3D12_BARRIER_LAYOUT, 5392 HRESULT STDMETHODCALLTYPE CreateReservedResource2(const D3D12_RESOURCE_DESC* desc, D3D12_BARRIER_LAYOUT,
5205 const D3D12_CLEAR_VALUE*, ID3D12ProtectedResourceSession* session, 5393 const D3D12_CLEAR_VALUE* clear,
5394 ID3D12ProtectedResourceSession* session,
5206 UINT32 castable_formats, const DXGI_FORMAT*, REFIID riid, 5395 UINT32 castable_formats, const DXGI_FORMAT*, REFIID riid,
5207 void** out) override { 5396 void** out) override {
5208 if (castable_formats) log_once("CreateReservedResource2: castable formats ignored, count", int(castable_formats)); 5397 if (castable_formats) log_once("CreateReservedResource2: castable formats ignored, count", int(castable_formats));
5209 return CreateReservedResource1(desc, D3D12_RESOURCE_STATE_COMMON, nullptr, session, riid, out); 5398 return CreateReservedResource1(desc, D3D12_RESOURCE_STATE_COMMON, clear, session, riid, out);
5210 } 5399 }
5211 5400
5212 // Tiling of a reserved resource or a tiled (64KB_UNDEFINED_SWIZZLE) texture (src/resource_tiling.h). Anything 5401 // Tiling of a reserved resource or a tiled (64KB_UNDEFINED_SWIZZLE) texture (src/resource_tiling.h). Anything
@@ -5328,21 +5517,21 @@ public:
5328 } 5517 }
5329 5518
5330 HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset, 5519 HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset,
5331 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES, 5520 const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
5332 const D3D12_CLEAR_VALUE*, REFIID riid, void** out) override { 5521 const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override {
5333 return create_placed(heap_interface, heap_offset, desc, 0, nullptr, riid, out); 5522 return create_placed(heap_interface, heap_offset, desc, state, clear, 0, nullptr, riid, out);
5334 } 5523 }
5335 5524
5336 // Device8: the DESC1 placed variant without a castable list. A texture with a mip region gets the failure 5525 // Device8: the DESC1 placed variant without a castable list. A texture with a mip region gets the failure
5337 // answer, as on the PC runtime; a buffer's mip region is ignored. 5526 // answer, as on the PC runtime; a buffer's mip region is ignored.
5338 HRESULT STDMETHODCALLTYPE CreatePlacedResource1(ID3D12Heap* heap_interface, UINT64 heap_offset, 5527 HRESULT STDMETHODCALLTYPE CreatePlacedResource1(ID3D12Heap* heap_interface, UINT64 heap_offset,
5339 const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES, 5528 const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state,
5340 const D3D12_CLEAR_VALUE*, REFIID riid, void** out) override { 5529 const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override {
5341 if (out) *out = nullptr; 5530 if (out) *out = nullptr;
5342 if (!desc) return E_INVALIDARG; 5531 if (!desc) return E_INVALIDARG;
5343 if (texture_mip_region(*desc)) return E_INVALIDARG; 5532 if (texture_mip_region(*desc)) return E_INVALIDARG;
5344 const D3D12_RESOURCE_DESC base = resource_desc(*desc); 5533 const D3D12_RESOURCE_DESC base = resource_desc(*desc);
5345 return create_placed(heap_interface, heap_offset, &base, 0, nullptr, riid, out); 5534 return create_placed(heap_interface, heap_offset, &base, state, clear, 0, nullptr, riid, out);
5346 } 5535 }
5347 5536
5348 // Device10: an initial layout instead of a state, and the castable-format list, which the placed texture's 5537 // Device10: an initial layout instead of a state, and the castable-format list, which the placed texture's
@@ -5350,7 +5539,7 @@ public:
5350 // PC runtime); the layer reports RelaxedFormatCastingSupported, so a real list is passed through. 5539 // PC runtime); the layer reports RelaxedFormatCastingSupported, so a real list is passed through.
5351 HRESULT STDMETHODCALLTYPE CreatePlacedResource2(ID3D12Heap* heap_interface, UINT64 heap_offset, 5540 HRESULT STDMETHODCALLTYPE CreatePlacedResource2(ID3D12Heap* heap_interface, UINT64 heap_offset,
5352 const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, 5541 const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout,
5353 const D3D12_CLEAR_VALUE*, UINT32 castable_count, 5542 const D3D12_CLEAR_VALUE* clear, UINT32 castable_count,
5354 const DXGI_FORMAT* castable, REFIID riid, void** out) override { 5543 const DXGI_FORMAT* castable, REFIID riid, void** out) override {
5355 if (out) *out = nullptr; 5544 if (out) *out = nullptr;
5356 if (!desc) return E_INVALIDARG; 5545 if (!desc) return E_INVALIDARG;
@@ -5359,14 +5548,22 @@ public:
5359 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && layout != D3D12_BARRIER_LAYOUT_UNDEFINED) 5548 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && layout != D3D12_BARRIER_LAYOUT_UNDEFINED)
5360 return E_INVALIDARG; 5549 return E_INVALIDARG;
5361 const D3D12_RESOURCE_DESC base = resource_desc(*desc); 5550 const D3D12_RESOURCE_DESC base = resource_desc(*desc);
5362 return create_placed(heap_interface, heap_offset, &base, castable_count, castable, riid, out); 5551 // An initial layout replaces the state, so the state rules are not this call's.
5552 return create_placed(heap_interface, heap_offset, &base, D3D12_RESOURCE_STATE_COMMON, clear, castable_count,
5553 castable, riid, out);
5363 } 5554 }
5364 5555
5365 // The placed path every CreatePlacedResource variant shares. A castable-format list reaches the placed 5556 // The placed path every CreatePlacedResource variant shares. A castable-format list reaches the placed
5366 // texture's Vulkan image as the committed path's does (create_committed): a buffer with a list is 5557 // texture's Vulkan image as the committed path's does (create_committed): a buffer with a list is
5367 // E_INVALIDARG, and so is a format with no Vulkan mapping. 5558 // E_INVALIDARG, and so is a format with no Vulkan mapping.
5559 // The arguments are answered as the host runtime answers them (d3d12_vulkan_device_test's
5560 // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules
5561 // CreateCommittedResource has, then the placement: a buffer at a 64 KiB-aligned offset, a texture at a
5562 // multiple of its GetResourceAllocationInfo alignment (4 KiB for a small texture), in a heap aligned at least
5563 // as much, and the whole resource inside the heap. Only then is a null output E_UNEXPECTED, with nothing made.
5368 HRESULT create_placed(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC* desc, 5564 HRESULT create_placed(ID3D12Heap* heap_interface, UINT64 heap_offset, const D3D12_RESOURCE_DESC* desc,
5369 UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { 5565 D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, UINT32 castable_count,
5566 const DXGI_FORMAT* castable, REFIID riid, void** out) {
5370 if (out) *out = nullptr; 5567 if (out) *out = nullptr;
5371 auto* heap = Heap::from<Heap>(heap_interface); 5568 auto* heap = Heap::from<Heap>(heap_interface);
5372 if (!heap || !desc) return E_INVALIDARG; 5569 if (!heap || !desc) return E_INVALIDARG;
@@ -5374,15 +5571,29 @@ public:
5374 log_once("castable formats on a placed buffer are invalid; count", int(castable_count)); 5571 log_once("castable formats on a placed buffer are invalid; count", int(castable_count));
5375 return E_INVALIDARG; 5572 return E_INVALIDARG;
5376 } 5573 }
5377 if (heap_offset % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) { 5574 // The description, state and clear value rules of a committed resource, but on a default heap: the heap's
5378 log_once("placed resource offset not 64 KiB aligned:", int(heap_offset)); 5575 // DENY flags are checked against the resource below, and the host takes any initial state for a buffer in
5576 // an upload or readback heap (COPY_DEST in an upload heap, GENERIC_READ in a readback heap), where a
5577 // committed buffer must start in GENERIC_READ or COPY_DEST. UAV access is refused there all the same.
5578 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
5579 const char* why = committed_resource_refusal(default_heap, D3D12_HEAP_FLAG_NONE, *desc, state, clear,
5580 acceleration_structures());
5581 const D3D12_HEAP_TYPE heap_type = heap->properties().Type;
5582 if (!why && (heap_type == D3D12_HEAP_TYPE_UPLOAD || heap_type == D3D12_HEAP_TYPE_READBACK) &&
5583 (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))
5584 why = "UAV access in an upload or readback heap";
5585 if (why) {
5586 log_once((std::string("CreatePlacedResource refused (") + why + "), dimension").c_str(),
5587 desc->Dimension);
5379 return E_INVALIDARG; 5588 return E_INVALIDARG;
5380 } 5589 }
5381 const bool tiled = is_tiled_layout(desc->Layout); 5590 const bool tiled = is_tiled_layout(desc->Layout);
5382 const bool msaa = desc->SampleDesc.Count > 1;
5383 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 5591 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
5384 if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return E_INVALIDARG; 5592 if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return E_INVALIDARG;
5385 if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG; 5593 if (heap_offset % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) {
5594 log_once("placed buffer offset not 64 KiB aligned:", int(heap_offset));
5595 return E_INVALIDARG;
5596 }
5386 if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) return E_INVALIDARG; 5597 if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) return E_INVALIDARG;
5387 } else { 5598 } else {
5388 if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD || 5599 if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD ||
@@ -5392,25 +5603,30 @@ public:
5392 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0; 5603 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0;
5393 if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) return E_INVALIDARG; 5604 if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) return E_INVALIDARG;
5394 if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)) return E_INVALIDARG; 5605 if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)) return E_INVALIDARG;
5395 if (tiled || msaa) { 5606 if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D &&
5396 if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && 5607 desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D)
5397 desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) 5608 return E_INVALIDARG;
5398 return E_INVALIDARG; 5609 if (desc->SampleDesc.Count > 1 && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D)
5399 if (msaa && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return E_INVALIDARG; 5610 return E_INVALIDARG;
5400 const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(*desc); 5611 // Extents, mips, samples, layout and alignment, as GetResourceAllocationInfo answers them (the sample
5401 if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment || 5612 // quality is the description rules' above, as in CreateCommittedResource).
5402 heap_offset % alloc.Alignment || alloc.SizeInBytes > heap->bytes() || 5613 D3D12_RESOURCE_DESC checked = *desc;
5403 heap_offset > heap->bytes() - alloc.SizeInBytes) 5614 checked.SampleDesc.Quality = 0;
5404 return E_INVALIDARG; 5615 const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(checked);
5405 if (tiled && static_cast<UINT>(desc->Layout) == kXboxTiledLayout) { 5616 if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment ||
5406 log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", 5617 heap_offset % alloc.Alignment || alloc.SizeInBytes > heap->bytes() ||
5407 int(desc->Dimension)); 5618 heap_offset > heap->bytes() - alloc.SizeInBytes) {
5408 } 5619 log_once("placed texture refused (size, alignment or room in the heap), dimension",
5409 } else if (heap_offset >= heap->bytes()) { 5620 int(desc->Dimension));
5410 return E_INVALIDARG; 5621 return E_INVALIDARG;
5411 } 5622 }
5623 if (tiled && static_cast<UINT>(desc->Layout) == kXboxTiledLayout) {
5624 log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension",
5625 int(desc->Dimension));
5626 }
5412 } 5627 }
5413 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && !heap->use_as_placed_buffer(out != nullptr)) { 5628 if (!out) return E_UNEXPECTED;
5629 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && !heap->use_as_placed_buffer(true)) {
5414 log_once("placed buffer refused: heap uses a separate allocation for sparse tiles", 1); 5630 log_once("placed buffer refused: heap uses a separate allocation for sparse tiles", 1);
5415 return E_NOTIMPL; 5631 return E_NOTIMPL;
5416 } 5632 }
@@ -5438,10 +5654,6 @@ public:
5438 resource->Release(); 5654 resource->Release();
5439 return hr; 5655 return hr;
5440 } 5656 }
5441 if (!out) {
5442 resource->Release();
5443 return S_FALSE;
5444 }
5445 return hand_out(resource, riid, out); 5657 return hand_out(resource, riid, out);
5446 } 5658 }
5447 5659
@@ -5858,6 +6070,18 @@ public:
5858 auto* fs = static_cast<D3D12_FEATURE_DATA_FORMAT_SUPPORT*>(data); 6070 auto* fs = static_cast<D3D12_FEATURE_DATA_FORMAT_SUPPORT*>(data);
5859 fs->Support1 = D3D12_FORMAT_SUPPORT1_NONE; 6071 fs->Support1 = D3D12_FORMAT_SUPPORT1_NONE;
5860 fs->Support2 = D3D12_FORMAT_SUPPORT2_NONE; 6072 fs->Support2 = D3D12_FORMAT_SUPPORT2_NONE;
6073 // The host runtime's format table (compare_invalid_arguments, "format support:"): a value it has no entry
6074 // for is E_FAIL, not unsupported: past B4G4R4A4_UNORM (115) up to 188, which includes the planar video
6075 // formats P208/V208/V408 (130-132), and from 192 up; 189-191 are the sampler-feedback formats and
6076 // A4B4G4R4. UNKNOWN is a buffer format (raw and structured buffers).
6077 const UINT format_value = static_cast<UINT>(fs->Format);
6078 if (format_value > static_cast<UINT>(DXGI_FORMAT_B4G4R4A4_UNORM) &&
6079 (format_value < 189 || format_value > 191))
6080 return d3d12_trace::result(method, E_FAIL);
6081 if (fs->Format == DXGI_FORMAT_UNKNOWN) {
6082 fs->Support1 = D3D12_FORMAT_SUPPORT1_BUFFER;
6083 return d3d12_trace::result(method, S_OK);
6084 }
5861 const Format fmt = texture_storage_format(fs->Format, false); 6085 const Format fmt = texture_storage_format(fs->Format, false);
5862 const Format depth_fmt = vulkan_format(fs->Format, true); 6086 const Format depth_fmt = vulkan_format(fs->Format, true);
5863 VkFormat vk_fmt = fmt.format != VK_FORMAT_UNDEFINED ? fmt.format : depth_fmt.format; 6087 VkFormat vk_fmt = fmt.format != VK_FORMAT_UNDEFINED ? fmt.format : depth_fmt.format;
@@ -6056,22 +6280,35 @@ public:
6056 case D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS: { 6280 case D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS: {
6057 if (size != sizeof(D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS)) return d3d12_trace::result(method, E_INVALIDARG); 6281 if (size != sizeof(D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS)) return d3d12_trace::result(method, E_INVALIDARG);
6058 auto* levels = static_cast<D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS*>(data); 6282 auto* levels = static_cast<D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS*>(data);
6283 // RTX 5070 / 621.14/621.24: a format outside the runtime's table (and R1_UNORM) fails with the caller's
6284 // output untouched; a known format clears it before the sample count is checked.
6285 const UINT format_id = UINT(levels->Format);
6286 if (levels->Format == DXGI_FORMAT_R1_UNORM ||
6287 !(format_id <= DXGI_FORMAT_B4G4R4A4_UNORM ||
6288 (format_id >= DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE &&
6289 format_id <= DXGI_FORMAT_A4B4G4R4_UNORM)))
6290 return d3d12_trace::result(method, E_FAIL);
6059 levels->NumQualityLevels = 0; 6291 levels->NumQualityLevels = 0;
6060 // TILED_RESOURCE asks about tiled (reserved, 64KB_UNDEFINED_SWIZZLE) textures. Measured natively on an 6292 // TILED_RESOURCE asks about tiled (reserved, 64KB_UNDEFINED_SWIZZLE) textures. Measured natively on an
6061 // RX 7800 XT, a Radeon iGPU and WARP: 1x and 4x keep the plain answer, every other count has none, and a 6293 // RX 7800 XT, a Radeon iGPU and WARP: 1x and 4x keep the plain answer, every other count has none, and a
6062 // format without a tile shape (96-bit) has none at any count. That is GetResourceAllocationInfo's rule 6294 // format without a tile shape (96-bit) has none at any count. That is GetResourceAllocationInfo's rule
6063 // here (tiled MSAA is 4x only). 128-bit formats at 4x: the AMD drivers answer 0, WARP and the RTX 5070 Ti 6295 // here (tiled MSAA is 4x only). 128-bit formats at 4x: the AMD drivers answer 0, WARP and the RTX 5070 Ti
6064 // allocate them; this follows the latter, as the allocation path does. 6296 // allocate them; this follows the latter, as the allocation path does.
6065 const bool tiled = levels->Flags == D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE; 6297 // RTX 5070 / 621.14: undefined flag bits are ignored; bad counts fail, known formats have 1x.
6066 if ((levels->Flags != D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE && !tiled) || 6298 const bool tiled = (levels->Flags & D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE) != 0;
6067 levels->SampleCount == 0 || levels->SampleCount > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || 6299 if (levels->SampleCount == 0 || levels->SampleCount > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT)
6068 (levels->SampleCount & (levels->SampleCount - 1)) != 0) 6300 return d3d12_trace::result(method, E_FAIL);
6069 return d3d12_trace::result(method, E_INVALIDARG); 6301 Format format = texture_storage_format(levels->Format, false);
6302 if (levels->SampleCount == 1) {
6303 levels->NumQualityLevels = tiled && format.rgb96 ? 0 : 1;
6304 return d3d12_trace::result(method, S_OK);
6305 }
6306 if ((levels->SampleCount & (levels->SampleCount - 1)) != 0)
6307 return d3d12_trace::result(method, S_OK);
6070 const bool alpha_only = levels->Format == DXGI_FORMAT_A8_UNORM; 6308 const bool alpha_only = levels->Format == DXGI_FORMAT_A8_UNORM;
6071 if (alpha_only && levels->SampleCount != 1) return d3d12_trace::result(method, S_OK); 6309 if (alpha_only && levels->SampleCount != 1) return d3d12_trace::result(method, S_OK);
6072 if (levels->Format == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM && levels->SampleCount != 1) 6310 if (levels->Format == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM && levels->SampleCount != 1)
6073 return d3d12_trace::result(method, S_OK); // single-sample 2D only; no quality levels 6311 return d3d12_trace::result(method, S_OK); // single-sample 2D only; no quality levels
6074 Format format = texture_storage_format(levels->Format, false);
6075 // A typeless format that is only a texture as depth (R24G8_TYPELESS, R32G8X24_TYPELESS) has no colour 6312 // A typeless format that is only a texture as depth (R24G8_TYPELESS, R32G8X24_TYPELESS) has no colour
6076 // format; creation makes it a depth image, so ask the same. 6313 // format; creation makes it a depth image, so ask the same.
6077 const bool depth_only_typeless = format.format == VK_FORMAT_UNDEFINED && 6314 const bool depth_only_typeless = format.format == VK_FORMAT_UNDEFINED &&
@@ -6083,11 +6320,8 @@ public:
6083 format = state_.texture_format(depth_desc); // includes the D24-to-D32 fallback used by creation 6320 format = state_.texture_format(depth_desc); // includes the D24-to-D32 fallback used by creation
6084 } 6321 }
6085 if (format.format == VK_FORMAT_UNDEFINED || !state_.image_format_properties) 6322 if (format.format == VK_FORMAT_UNDEFINED || !state_.image_format_properties)
6086 return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED);
6087 if (format.rgb96) { // no 96-bit render targets yet, so no multisampled ones; no tile shape either
6088 levels->NumQualityLevels = levels->SampleCount == 1 && !tiled ? 1 : 0;
6089 return d3d12_trace::result(method, S_OK); 6323 return d3d12_trace::result(method, S_OK);
6090 } 6324 if (format.rgb96) return d3d12_trace::result(method, S_OK); // no 96-bit render targets yet
6091 6325
6092 // Vulkan exposes one standard sample pattern per supported count, so each supported count maps to 6326 // Vulkan exposes one standard sample pattern per supported count, so each supported count maps to
6093 // one D3D12 quality level (quality index 0). Query the matching colour or depth/stencil attachment 6327 // one D3D12 quality level (quality index 0). Query the matching colour or depth/stencil attachment
@@ -6117,8 +6351,12 @@ public:
6117 // Measured against the host PC runtime: a request above the supported model is clamped down to it, 5.1 6351 // Measured against the host PC runtime: a request above the supported model is clamped down to it, 5.1
6118 // is echoed because it is D3D12's own baseline (WARP and the RTX 5070 both answer it with S_OK), and a 6352 // is echoed because it is D3D12's own baseline (WARP and the RTX 5070 both answer it with S_OK), and a
6119 // value below it is refused with E_INVALIDARG (0x5f crashed the host, so the test does not probe it). 6353 // value below it is refused with E_INVALIDARG (0x5f crashed the host, so the test does not probe it).
6120 // Refuse the same way instead of echoing an unrepresentable value back. 6354 // Refuse the same way instead of echoing an unrepresentable value back: below 5.1, and between 5.1 and
6121 if (model->HighestShaderModel < D3D_SHADER_MODEL_5_1) return E_INVALIDARG; 6355 // 6.0, where no runtime defines a model (0x52-0x5f; E_INVALIDARG on the host runtime of an RTX 5070).
6356 const UINT requested = static_cast<UINT>(model->HighestShaderModel);
6357 if (requested < D3D_SHADER_MODEL_5_1 ||
6358 (requested > D3D_SHADER_MODEL_5_1 && requested < D3D_SHADER_MODEL_6_0))
6359 return E_INVALIDARG;
6122 if (model->HighestShaderModel > kHighestShaderModel) model->HighestShaderModel = kHighestShaderModel; 6360 if (model->HighestShaderModel > kHighestShaderModel) model->HighestShaderModel = kHighestShaderModel;
6123 return S_OK; 6361 return S_OK;
6124 } 6362 }
@@ -6208,12 +6446,10 @@ public:
6208 case D3D12_FEATURE_PREDICATION: 6446 case D3D12_FEATURE_PREDICATION:
6209 return write_supported_feature<D3D12_FEATURE_DATA_PREDICATION>( 6447 return write_supported_feature<D3D12_FEATURE_DATA_PREDICATION>(
6210 method, data, size, state_.info.conditional_rendering ? TRUE : FALSE); 6448 method, data, size, state_.info.conditional_rendering ? TRUE : FALSE);
6211 case D3D12_FEATURE_APPLICATION_SPECIFIC_DRIVER_STATE: 6449 case compat::kFeatureApplicationSpecificDriverState:
6212 return write_supported_feature<D3D12_FEATURE_DATA_APPLICATION_SPECIFIC_DRIVER_STATE>( 6450 return write_supported_feature<compat::FeatureSupportFlag>(method, data, size, FALSE);
6213 method, data, size, FALSE); 6451 case compat::kFeatureBytecodeBypassHashSupported:
6214 case D3D12_FEATURE_BYTECODE_BYPASS_HASH_SUPPORTED: 6452 return write_supported_feature<compat::FeatureSupportFlag>(method, data, size, FALSE);
6215 return write_supported_feature<D3D12_FEATURE_DATA_BYTECODE_BYPASS_HASH_SUPPORTED>(
6216 method, data, size, FALSE);
6217 default: 6453 default:
6218 // Not answered yet. The log above lists every query; answers are added as the trace asks for them. 6454 // Not answered yet. The log above lists every query; answers are added as the trace asks for them.
6219 return d3d12_trace::result(method, E_INVALIDARG); 6455 return d3d12_trace::result(method, E_INVALIDARG);
@@ -6496,10 +6732,16 @@ private:
6496 } 6732 }
6497 6733
6498 // D3D12's layout rules for reserved resources. Buffers use sparse storage when supported. 6734 // D3D12's layout rules for reserved resources. Buffers use sparse storage when supported.
6499 HRESULT create_reserved(const D3D12_RESOURCE_DESC* desc, REFIID riid, void** out) { 6735 // The arguments are answered as the host runtime answers them (d3d12_vulkan_device_test's
6736 // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules of a
6737 // committed resource on a default heap, the reserved layouts below, and only then E_UNEXPECTED for a null
6738 // output, with nothing made.
6739 HRESULT create_reserved(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
6740 const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) {
6500 if (out) *out = nullptr; 6741 if (out) *out = nullptr;
6501 if (!desc) return E_INVALIDARG; 6742 if (!desc) return E_INVALIDARG;
6502 D3D12_RESOURCE_DESC backing = *desc; 6743 D3D12_RESOURCE_DESC backing = *desc;
6744 const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT};
6503 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 6745 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
6504 if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG; 6746 if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return E_INVALIDARG;
6505 } else { 6747 } else {
@@ -6518,7 +6760,19 @@ private:
6518 } 6760 }
6519 backing.MipLevels = desc->MipLevels; 6761 backing.MipLevels = desc->MipLevels;
6520 } 6762 }
6521 const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; 6763 if (const char* why = committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, backing, state, clear,
6764 acceleration_structures())) {
6765 log_once((std::string("CreateReservedResource refused (") + why + "), dimension").c_str(),
6766 desc->Dimension);
6767 return E_INVALIDARG;
6768 }
6769 if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) {
6770 // Extents, mips and samples, as the committed backing below checks them (GetResourceAllocationInfo).
6771 D3D12_RESOURCE_DESC checked = backing;
6772 checked.SampleDesc.Quality = 0;
6773 if (allocation(checked).SizeInBytes == UINT64_MAX) return E_INVALIDARG;
6774 }
6775 if (!out) return E_UNEXPECTED;
6522 ID3D12Resource* resource = nullptr; 6776 ID3D12Resource* resource = nullptr;
6523 HRESULT hr; 6777 HRESULT hr;
6524 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && state_.sparse_buffer_memory_types) { 6778 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && state_.sparse_buffer_memory_types) {
@@ -6536,10 +6790,6 @@ private:
6536 } 6790 }
6537 if (FAILED(hr)) return hr; 6791 if (FAILED(hr)) return hr;
6538 Resource::from<Resource>(resource)->make_reserved(desc->Layout); 6792 Resource::from<Resource>(resource)->make_reserved(desc->Layout);
6539 if (!out) { // a capability check: D3D12 allows a null output
6540 resource->Release();
6541 return S_FALSE;
6542 }
6543 hr = resource->QueryInterface(riid, out); 6793 hr = resource->QueryInterface(riid, out);
6544 resource->Release(); 6794 resource->Release();
6545 return hr; 6795 return hr;
@@ -6628,6 +6878,8 @@ private:
6628 6878
6629 std::mutex queue_mutex_; 6879 std::mutex queue_mutex_;
6630 std::vector<bool> queue_busy_; 6880 std::vector<bool> queue_busy_;
6881 std::vector<bool> compute_busy_;
6882 std::vector<bool> copy_busy_;
6631 DeviceState state_; 6883 DeviceState state_;
6632 std::atomic<bool> removed_{false}; 6884 std::atomic<bool> removed_{false};
6633 OwnedRuntime owned_; 6885 OwnedRuntime owned_;
@@ -6872,6 +7124,14 @@ HRESULT WindowPresenter::present_blank(UINT sync_interval) {
6872 return present_result(presenter_->present_blank(sync_interval > 0)); 7124 return present_result(presenter_->present_blank(sync_interval > 0));
6873} 7125}
6874 7126
7127HRESULT WindowPresenter::present_planes(const leonida::PresentPlanes& planes, UINT sync_interval, bool tear) {
7128 return present_result(presenter_->present_planes(planes, sync_interval > 0, tear));
7129}
7130
7131bool WindowPresenter::hdr_active() const { return presenter_->hdr_active(); }
7132void WindowPresenter::force_hdr_encoding(bool on) { presenter_->force_hdr_encoding(on); }
7133std::uint64_t WindowPresenter::composed_presents() const { return presenter_->composed_presents(); }
7134
6875bool WindowPresenter::enable_capture() { return presenter_->enable_capture(); } 7135bool WindowPresenter::enable_capture() { return presenter_->enable_capture(); }
6876 7136
6877void WindowPresenter::set_abort(std::function<bool()> abort) { presenter_->set_abort(std::move(abort)); } 7137void WindowPresenter::set_abort(std::function<bool()> abort) { presenter_->set_abort(std::move(abort)); }
@@ -6883,6 +7143,12 @@ bool WindowPresenter::read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* e
6883VkExtent2D WindowPresenter::extent() const { return presenter_->extent(); } 7143VkExtent2D WindowPresenter::extent() const { return presenter_->extent(); }
6884std::uint64_t WindowPresenter::presented() const { return presenter_->presented(); } 7144std::uint64_t WindowPresenter::presented() const { return presenter_->presented(); }
6885 7145
7146bool device_has_swapchain_colorspace(ID3D12Device* device) {
7147 ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device);
7148 Device* d = Device::from<Device>(real ? real : device);
7149 return d && d->state().info.swapchain_colorspace;
7150}
7151
6886std::unique_ptr<WindowPresenter> create_window_presenter(ID3D12Device* device, HWND window) { 7152std::unique_ptr<WindowPresenter> create_window_presenter(ID3D12Device* device, HWND window) {
6887 Device* d = Device::from<Device>(device); 7153 Device* d = Device::from<Device>(device);
6888 if (!d || !window) return nullptr; 7154 if (!d || !window) return nullptr;
@@ -6971,6 +7237,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
6971 get(nullptr, "vkEnumerateInstanceExtensionProperties")); 7237 get(nullptr, "vkEnumerateInstanceExtensionProperties"));
6972 std::vector<const char*> inst_exts; 7238 std::vector<const char*> inst_exts;
6973 bool surface_maintenance1_khr = false, surface_maintenance1_ext = false; // enabled on the instance 7239 bool surface_maintenance1_khr = false, surface_maintenance1_ext = false; // enabled on the instance
7240 bool swapchain_colorspace_enabled = false; // VK_EXT_swapchain_colorspace on the instance
6974 if (enum_inst_exts) { 7241 if (enum_inst_exts) {
6975 std::uint32_t ext_cnt = 0; 7242 std::uint32_t ext_cnt = 0;
6976 enum_inst_exts(nullptr, &ext_cnt, nullptr); 7243 enum_inst_exts(nullptr, &ext_cnt, nullptr);
@@ -6987,6 +7254,14 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
6987 if (has_surface && has_win32) { 7254 if (has_surface && has_win32) {
6988 inst_exts.push_back(VK_KHR_SURFACE_EXTENSION_NAME); 7255 inst_exts.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
6989 inst_exts.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); 7256 inst_exts.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
7257 // Lists the HDR10 (ST.2084) surface formats, which a PresentX plane in HDR10 can use (xbox_present.h); without it
7258 // the surface only offers sRGB-nonlinear ones.
7259 for (const auto& e : available)
7260 if (!std::strcmp(e.extensionName, VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME)) {
7261 inst_exts.push_back(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME);
7262 swapchain_colorspace_enabled = true;
7263 break;
7264 }
6990 // The surface half of VK_*_swapchain_maintenance1 (the present modes a swapchain can switch between). 7265 // The surface half of VK_*_swapchain_maintenance1 (the present modes a swapchain can switch between).
6991 if (has_caps2 && (surface_maintenance1_khr || surface_maintenance1_ext)) { 7266 if (has_caps2 && (surface_maintenance1_khr || surface_maintenance1_ext)) {
6992 inst_exts.push_back(VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME); 7267 inst_exts.push_back(VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME);
@@ -7234,11 +7509,37 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
7234 std::vector<VkQueueFamilyProperties> families(family_count); 7509 std::vector<VkQueueFamilyProperties> families(family_count);
7235 vkGetPhysicalDeviceQueueFamilyProperties(info.physical, &family_count, families.data()); 7510 vkGetPhysicalDeviceQueueFamilyProperties(info.physical, &family_count, families.data());
7236 const std::uint32_t command_queue_count = std::min(16u, families[info.queue_family].queueCount); 7511 const std::uint32_t command_queue_count = std::min(16u, families[info.queue_family].queueCount);
7237 std::vector<float> priorities(command_queue_count, 1.0f); 7512 std::vector<float> priorities(16, 1.0f);
7238 VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; 7513 std::vector<VkDeviceQueueCreateInfo> queue_infos;
7239 queue_info.queueFamilyIndex = info.queue_family; 7514 {
7240 queue_info.queueCount = command_queue_count; 7515 VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
7241 queue_info.pQueuePriorities = priorities.data(); 7516 q.queueFamilyIndex = info.queue_family;
7517 q.queueCount = command_queue_count;
7518 q.pQueuePriorities = priorities.data();
7519 queue_infos.push_back(q);
7520 }
7521 const auto picked = leonida::pick_queue_families(families, info.queue_family);
7522 std::uint32_t compute_count = 0, copy_count = 0;
7523 if (picked.compute != info.queue_family) {
7524 info.compute_family = picked.compute;
7525 compute_count = std::min(16u, families[picked.compute].queueCount);
7526 VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
7527 q.queueFamilyIndex = picked.compute;
7528 q.queueCount = compute_count;
7529 q.pQueuePriorities = priorities.data();
7530 queue_infos.push_back(q);
7531 }
7532 if (picked.copy != info.queue_family) {
7533 info.copy_family = picked.copy;
7534 if (picked.copy != picked.compute) {
7535 copy_count = std::min(16u, families[picked.copy].queueCount);
7536 VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
7537 q.queueFamilyIndex = picked.copy;
7538 q.queueCount = copy_count;
7539 q.pQueuePriorities = priorities.data();
7540 queue_infos.push_back(q);
7541 }
7542 }
7242 VkPhysicalDeviceFeatures enable{}; 7543 VkPhysicalDeviceFeatures enable{};
7243 enable.sparseBinding = chosen_features.sparseBinding; 7544 enable.sparseBinding = chosen_features.sparseBinding;
7244 enable.sparseResidencyBuffer = chosen_features.sparseResidencyBuffer; 7545 enable.sparseResidencyBuffer = chosen_features.sparseResidencyBuffer;
@@ -7359,6 +7660,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
7359 enable.dualSrcBlend = chosen_features.dualSrcBlend; 7660 enable.dualSrcBlend = chosen_features.dualSrcBlend;
7360 enable.logicOp = chosen_features.logicOp; 7661 enable.logicOp = chosen_features.logicOp;
7361 enable.depthClamp = chosen_features.depthClamp; 7662 enable.depthClamp = chosen_features.depthClamp;
7663 enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus)
7362 // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of 7664 // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of
7363 // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, image stores 7665 // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, image stores
7364 // without a format (StorageImageWriteWithoutFormat), gather offsets (ImageGatherExtended) and LOD-clamped samples 7666 // without a format (StorageImageWriteWithoutFormat), gather offsets (ImageGatherExtended) and LOD-clamped samples
@@ -7437,8 +7739,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
7437 } 7739 }
7438 7740
7439 VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; 7741 VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12};
7440 device_info.queueCreateInfoCount = 1; 7742 device_info.queueCreateInfoCount = std::uint32_t(queue_infos.size());
7441 device_info.pQueueCreateInfos = &queue_info; 7743 device_info.pQueueCreateInfos = queue_infos.data();
7442 device_info.pEnabledFeatures = &enable; 7744 device_info.pEnabledFeatures = &enable;
7443 std::vector<const char*> device_extensions; 7745 std::vector<const char*> device_extensions;
7444 v13.add_extensions(device_extensions); 7746 v13.add_extensions(device_extensions);
@@ -7464,6 +7766,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
7464 device_extensions.push_back(VK_KHR_RAY_QUERY_EXTENSION_NAME); 7766 device_extensions.push_back(VK_KHR_RAY_QUERY_EXTENSION_NAME);
7465 } 7767 }
7466 info.presentation = has_swapchain && instance_has_surface; 7768 info.presentation = has_swapchain && instance_has_surface;
7769 info.swapchain_colorspace = info.presentation && swapchain_colorspace_enabled;
7467 if (info.custom_border_color) device_extensions.push_back(custom_border_name); 7770 if (info.custom_border_color) device_extensions.push_back(custom_border_name);
7468 device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); 7771 device_info.enabledExtensionCount = std::uint32_t(device_extensions.size());
7469 device_info.ppEnabledExtensionNames = device_extensions.empty() ? nullptr : device_extensions.data(); 7772 device_info.ppEnabledExtensionNames = device_extensions.empty() ? nullptr : device_extensions.data();
@@ -7475,6 +7778,22 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out) {
7475 const auto get_queue = reinterpret_cast<PFN_vkGetDeviceQueue>(vkGetDeviceProcAddr(owned.device, "vkGetDeviceQueue")); 7778 const auto get_queue = reinterpret_cast<PFN_vkGetDeviceQueue>(vkGetDeviceProcAddr(owned.device, "vkGetDeviceQueue"));
7476 for (std::uint32_t i = 0; i < command_queue_count; ++i) 7779 for (std::uint32_t i = 0; i < command_queue_count; ++i)
7477 get_queue(owned.device, info.queue_family, i, &info.command_queues[i]); 7780 get_queue(owned.device, info.queue_family, i, &info.command_queues[i]);
7781 if (compute_count) {
7782 // Copies on the async-compute family split its queues with the compute queues: one VkQueue per live queue.
7783 const bool split = info.copy_family == info.compute_family && compute_count > 1;
7784 const std::uint32_t for_compute = split ? compute_count / 2 : compute_count;
7785 for (std::uint32_t i = 0; i < compute_count; ++i) {
7786 VkQueue q = VK_NULL_HANDLE;
7787 get_queue(owned.device, info.compute_family, i, &q);
7788 (i < for_compute ? info.compute_queues : info.copy_queues).push_back(q);
7789 }
7790 if (info.copy_family == info.compute_family && !split) info.copy_family = UINT32_MAX;
7791 }
7792 for (std::uint32_t i = 0; i < copy_count; ++i) {
7793 VkQueue q = VK_NULL_HANDLE;
7794 get_queue(owned.device, info.copy_family, i, &q);
7795 info.copy_queues.push_back(q);
7796 }
7478 info.queue = info.command_queues[0]; 7797 info.queue = info.command_queues[0];
7479 info.max_push_constants_size = chosen.limits.maxPushConstantsSize; 7798 info.max_push_constants_size = chosen.limits.maxPushConstantsSize;
7480 info.push_constants_need_fallback = (info.max_push_constants_size < 144); 7799 info.push_constants_need_fallback = (info.max_push_constants_size < 144);
diff --git a/runtime/shims/dxgi_com.cpp b/runtime/shims/dxgi_com.cpp
index 47a53f7a2..55683ea52 100644
--- a/runtime/shims/dxgi_com.cpp
+++ b/runtime/shims/dxgi_com.cpp
@@ -119,6 +119,7 @@ public:
119 119
120 ~SwapChain() { 120 ~SwapChain() {
121 unregister_buffers(); 121 unregister_buffers();
122 if (restrict_to_output_) restrict_to_output_->Release();
122 if (waitable_) CloseHandle(waitable_); 123 if (waitable_) CloseHandle(waitable_);
123 if (device_) device_->Release(); 124 if (device_) device_->Release();
124 if (parent_) parent_->Release(); 125 if (parent_) parent_->Release();
@@ -178,7 +179,15 @@ public:
178 HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** out) override { 179 HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** out) override {
179 if (!out) return E_POINTER; 180 if (!out) return E_POINTER;
180 *out = nullptr; 181 *out = nullptr;
181 return device_ ? device_->QueryInterface(riid, out) : E_NOINTERFACE; 182 if (!device_) return E_NOINTERFACE;
183
184 ID3D12DeviceChild* device_child = nullptr;
185 if (SUCCEEDED(device_->QueryInterface(IID_PPV_ARGS(&device_child)))) {
186 const HRESULT hr = device_child->GetDevice(riid, out);
187 device_child->Release();
188 return hr;
189 }
190 return device_->QueryInterface(riid, out);
182 } 191 }
183 192
184 // IDXGISwapChain 193 // IDXGISwapChain
@@ -300,12 +309,30 @@ public:
300 return S_OK; 309 return S_OK;
301 } 310 }
302 HRESULT STDMETHODCALLTYPE GetHwnd(HWND* out) override { if (!out) return E_INVALIDARG; *out = hwnd_; return S_OK; } 311 HRESULT STDMETHODCALLTYPE GetHwnd(HWND* out) override { if (!out) return E_INVALIDARG; *out = hwnd_; return S_OK; }
303 HRESULT STDMETHODCALLTYPE GetCoreWindow(REFIID, void**) override { return E_NOTIMPL; } 312 HRESULT STDMETHODCALLTYPE GetCoreWindow(REFIID, void** out) override {
313 if (!out) return DXGI_ERROR_INVALID_CALL;
314 *out = nullptr;
315 return DXGI_ERROR_INVALID_CALL;
316 }
304 HRESULT STDMETHODCALLTYPE Present1(UINT sync, UINT flags, const DXGI_PRESENT_PARAMETERS*) override { 317 HRESULT STDMETHODCALLTYPE Present1(UINT sync, UINT flags, const DXGI_PRESENT_PARAMETERS*) override {
305 return Present(sync, flags); 318 return Present(sync, flags);
306 } 319 }
307 BOOL STDMETHODCALLTYPE IsTemporaryMonoSupported() override { return FALSE; } 320 BOOL STDMETHODCALLTYPE IsTemporaryMonoSupported() override { return FALSE; }
308 HRESULT STDMETHODCALLTYPE GetRestrictToOutput(IDXGIOutput**) override { return E_NOTIMPL; } 321 HRESULT STDMETHODCALLTYPE GetRestrictToOutput(IDXGIOutput** out) override {
322 if (!out) return E_INVALIDARG;
323 if (restrict_to_output_) {
324 *out = restrict_to_output_;
325 restrict_to_output_->AddRef();
326 return S_OK;
327 }
328 *out = nullptr;
329 return DXGI_ERROR_NOT_FOUND;
330 }
331 void set_restrict_to_output(IDXGIOutput* out) {
332 if (restrict_to_output_) restrict_to_output_->Release();
333 restrict_to_output_ = out;
334 if (restrict_to_output_) restrict_to_output_->AddRef();
335 }
309 HRESULT STDMETHODCALLTYPE SetBackgroundColor(const DXGI_RGBA* color) override { 336 HRESULT STDMETHODCALLTYPE SetBackgroundColor(const DXGI_RGBA* color) override {
310 if (!color) return E_INVALIDARG; 337 if (!color) return E_INVALIDARG;
311 background_color_ = *color; 338 background_color_ = *color;
@@ -424,6 +451,7 @@ private:
424 leonida::VulkanContext& context_; 451 leonida::VulkanContext& context_;
425 leonida::VulkanSwapchain swapchain_; 452 leonida::VulkanSwapchain swapchain_;
426 HWND hwnd_ = nullptr; 453 HWND hwnd_ = nullptr;
454 IDXGIOutput* restrict_to_output_ = nullptr;
427 UINT flags_ = 0; 455 UINT flags_ = 0;
428 HANDLE waitable_ = nullptr; 456 HANDLE waitable_ = nullptr;
429 std::vector<BackBufferResource*> buffers_; 457 std::vector<BackBufferResource*> buffers_;
@@ -739,7 +767,11 @@ public:
739 HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; } 767 HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; }
740 HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; } 768 HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; }
741 HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; } 769 HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; }
742 HRESULT STDMETHODCALLTYPE GetParent(REFIID, void**) override { return E_NOTIMPL; } 770 HRESULT STDMETHODCALLTYPE GetParent(REFIID, void** out) override {
771 if (!out) return E_POINTER;
772 *out = nullptr;
773 return E_NOINTERFACE;
774 }
743 775
744 // IDXGIFactory 776 // IDXGIFactory
745 HRESULT STDMETHODCALLTYPE EnumAdapters(UINT index, IDXGIAdapter** out) override { 777 HRESULT STDMETHODCALLTYPE EnumAdapters(UINT index, IDXGIAdapter** out) override {
@@ -756,9 +788,35 @@ public:
756 *hwnd = assoc_hwnd_; 788 *hwnd = assoc_hwnd_;
757 return S_OK; 789 return S_OK;
758 } 790 }
759 HRESULT STDMETHODCALLTYPE CreateSwapChain(IUnknown*, DXGI_SWAP_CHAIN_DESC*, IDXGISwapChain**) override { 791 HRESULT STDMETHODCALLTYPE CreateSwapChain(IUnknown* device, DXGI_SWAP_CHAIN_DESC* desc, IDXGISwapChain** out) override {
760 stub("IDXGIFactory::CreateSwapChain"); 792 if (!out || !device || !desc) return DXGI_ERROR_INVALID_CALL;
761 return E_NOTIMPL; 793 *out = nullptr;
794 DXGI_SWAP_CHAIN_DESC1 desc1{};
795 desc1.Width = desc->BufferDesc.Width;
796 desc1.Height = desc->BufferDesc.Height;
797 desc1.Format = desc->BufferDesc.Format;
798 desc1.SampleDesc = desc->SampleDesc;
799 desc1.BufferUsage = desc->BufferUsage;
800 desc1.BufferCount = desc->BufferCount;
801 desc1.Scaling = DXGI_SCALING_STRETCH;
802 desc1.SwapEffect = desc->SwapEffect;
803 desc1.Flags = desc->Flags;
804 DXGI_SWAP_CHAIN_FULLSCREEN_DESC fs_desc{};
805 fs_desc.Windowed = desc->Windowed;
806 fs_desc.RefreshRate = desc->BufferDesc.RefreshRate;
807 fs_desc.Scaling = desc->BufferDesc.Scaling;
808 fs_desc.ScanlineOrdering = desc->BufferDesc.ScanlineOrdering;
809 IDXGISwapChain1* sc1 = nullptr;
810 const HRESULT hr = CreateSwapChainForHwnd(device, desc->OutputWindow, &desc1, &fs_desc, nullptr, &sc1);
811 if (SUCCEEDED(hr) && sc1) {
812 *out = static_cast<IDXGISwapChain*>(sc1);
813 if (!desc->Windowed) {
814 // When exclusive fullscreen is unavailable, native DXGI creates the
815 // windowed chain and returns DXGI_STATUS_OCCLUDED.
816 return DXGI_STATUS_OCCLUDED;
817 }
818 }
819 return hr;
762 } 820 }
763 HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter(HMODULE, IDXGIAdapter**) override { return E_NOTIMPL; } 821 HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter(HMODULE, IDXGIAdapter**) override { return E_NOTIMPL; }
764 822
@@ -776,7 +834,7 @@ public:
776 // IDXGIFactory2 834 // IDXGIFactory2
777 BOOL STDMETHODCALLTYPE IsWindowedStereoEnabled() override { return FALSE; } 835 BOOL STDMETHODCALLTYPE IsWindowedStereoEnabled() override { return FALSE; }
778 HRESULT STDMETHODCALLTYPE CreateSwapChainForHwnd(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc, 836 HRESULT STDMETHODCALLTYPE CreateSwapChainForHwnd(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc,
779 const DXGI_SWAP_CHAIN_FULLSCREEN_DESC*, IDXGIOutput*, 837 const DXGI_SWAP_CHAIN_FULLSCREEN_DESC*, IDXGIOutput* restrict_to_output,
780 IDXGISwapChain1** out) override { 838 IDXGISwapChain1** out) override {
781 if (!out) return E_POINTER; 839 if (!out) return E_POINTER;
782 *out = nullptr; 840 *out = nullptr;
@@ -786,6 +844,7 @@ public:
786 const VkFormat vk_fmt = dxgi_to_vk_format(desc->Format); 844 const VkFormat vk_fmt = dxgi_to_vk_format(desc->Format);
787 if (vk_fmt == VK_FORMAT_UNDEFINED) return DXGI_ERROR_INVALID_CALL; 845 if (vk_fmt == VK_FORMAT_UNDEFINED) return DXGI_ERROR_INVALID_CALL;
788 auto* sc = new SwapChain(this, device, context_, gipa_, instance_, physical_, gdpa_, queue_, queue_family_); 846 auto* sc = new SwapChain(this, device, context_, gipa_, instance_, physical_, gdpa_, queue_, queue_family_);
847 if (restrict_to_output) sc->set_restrict_to_output(restrict_to_output);
789 if (!sc->init(hwnd, *desc, vk_fmt)) { 848 if (!sc->init(hwnd, *desc, vk_fmt)) {
790 sc->Release(); 849 sc->Release();
791 return E_FAIL; 850 return E_FAIL;
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index 21924801c..89b66364d 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -12,6 +12,9 @@
12// effect (SDL_SendGamepadEffect), as set by LEONIDA_DS_TRIGGERS. That is an approximation of the Xbox impulse 12// effect (SDL_SendGamepadEffect), as set by LEONIDA_DS_TRIGGERS. That is an approximation of the Xbox impulse
13// trigger signal, not the PS5 version's authored effects. 13// trigger signal, not the PS5 version's authored effects.
14// - DualSense/DualShock 4 lightbar colour (LEONIDA_DS_LIGHTBAR) and the player LEDs by connection order 14// - DualSense/DualShock 4 lightbar colour (LEONIDA_DS_LIGHTBAR) and the player LEDs by connection order
15// - force-feedback motors, reported from the SDL haptic device SDL opens for the pad's joystick, and played through
16// SDL_CreateHapticEffect/RunHapticEffect (IGameInputForceFeedbackEffect); haptic trigger motors, reported from the
17// trigger motors the pad already has, played as an intensity through the same trigger output as SetRumbleState
15// - the keyboard pad (LEONIDA_KEYBOARD_PAD): one SDL virtual gamepad driven by the keyboard and mouse 18// - the keyboard pad (LEONIDA_KEYBOARD_PAD): one SDL virtual gamepad driven by the keyboard and mouse
16// 19//
17// One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when 20// One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when
@@ -32,6 +35,7 @@
32 35
33#include <algorithm> 36#include <algorithm>
34#include <atomic> 37#include <atomic>
38#include <chrono>
35#include <cmath> 39#include <cmath>
36#include <cstdio> 40#include <cstdio>
37#include <cstdlib> 41#include <cstdlib>
@@ -60,6 +64,9 @@ constexpr Uint32 kRumbleDurationMs = 0xFFFF; // SDL's maximum; refreshed well b
60constexpr uint64_t kRumbleRefreshUs = 20'000'000; 64constexpr uint64_t kRumbleRefreshUs = 20'000'000;
61constexpr uint64_t kBatteryRefreshUs = 1'000'000; 65constexpr uint64_t kBatteryRefreshUs = 1'000'000;
62constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t) 66constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t)
67constexpr uint32_t kForceFeedbackMotors = 1; // one per SDL haptic device: the wheel or stick it belongs to
68constexpr uint32_t kHapticMotors = 2; // the left and right trigger, on a pad that backs them
69constexpr uint32_t kHapticHoldMs = 60'000; // length of an effect GameInput gives no duration; re-run before it ends
63constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old 70constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old
64constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate 71constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate
65// Motion. SDL gives accel in m/s^2 (gravity included) and gyro in rad/s; the state the ABI defines carries signed 72// Motion. SDL gives accel in m/s^2 (gravity included) and gyro in rad/s; the state the ABI defines carries signed
@@ -87,6 +94,37 @@ ULONG release_floor(std::atomic<ULONG>& refs) {
87 94
88bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; } 95bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; }
89 96
97// ---- SDL haptics ------------------------------------------------------------------------------------------------
98//
99// Force feedback and the trigger haptic motors go through SDL's haptic API, opened from the pad's joystick: SDL's
100// gamepad API has no force feedback at all, and a wheel or stick it models as a joystick exposes one only as a haptic
101// device. Every call goes through one table so gameinput_test can stand in for it, because SDL's virtual joysticks
102// report no haptics and a wheel is the only other way to reach this path.
103
104void* sdl_open_haptic(void* js) { return SDL_OpenHapticFromJoystick(static_cast<SDL_Joystick*>(js)); }
105void sdl_close_haptic(void* h) { SDL_CloseHaptic(static_cast<SDL_Haptic*>(h)); }
106uint32_t sdl_haptic_features(void* h) { return SDL_GetHapticFeatures(static_cast<SDL_Haptic*>(h)); }
107int sdl_haptic_max_effects(void* h) { return SDL_GetMaxHapticEffects(static_cast<SDL_Haptic*>(h)); }
108int sdl_haptic_create(void* h, const void* e) {
109 return SDL_CreateHapticEffect(static_cast<SDL_Haptic*>(h), static_cast<const SDL_HapticEffect*>(e));
110}
111bool sdl_haptic_update(void* h, int id, const void* e) {
112 return SDL_UpdateHapticEffect(static_cast<SDL_Haptic*>(h), id, static_cast<const SDL_HapticEffect*>(e));
113}
114bool sdl_haptic_run(void* h, int id, uint32_t iterations) {
115 return SDL_RunHapticEffect(static_cast<SDL_Haptic*>(h), id, iterations);
116}
117bool sdl_haptic_stop(void* h, int id) { return SDL_StopHapticEffect(static_cast<SDL_Haptic*>(h), id); }
118void sdl_haptic_destroy(void* h, int id) { SDL_DestroyHapticEffect(static_cast<SDL_Haptic*>(h), id); }
119bool sdl_haptic_gain(void* h, int gain) { return SDL_SetHapticGain(static_cast<SDL_Haptic*>(h), gain); }
120
121const rt::gameinput::HapticApi kSdlHaptic{sdl_open_haptic, sdl_close_haptic, sdl_haptic_features,
122 sdl_haptic_max_effects, sdl_haptic_create, sdl_haptic_update,
123 sdl_haptic_run, sdl_haptic_stop, sdl_haptic_destroy,
124 sdl_haptic_gain};
125std::atomic<const rt::gameinput::HapticApi*> g_haptic_api{&kSdlHaptic};
126const rt::gameinput::HapticApi& haptics() { return *g_haptic_api.load(); }
127
90// ---- configuration ---------------------------------------------------------------------------------------------- 128// ---- configuration ----------------------------------------------------------------------------------------------
91 129
92std::string env(const char* name) { 130std::string env(const char* name) {
@@ -137,6 +175,7 @@ rt::gameinput::Config read_config() {
137// ---- objects ---------------------------------------------------------------------------------------------------- 175// ---- objects ----------------------------------------------------------------------------------------------------
138 176
139class Device; 177class Device;
178class ForceFeedbackEffect;
140 179
141struct Snapshot { 180struct Snapshot {
142 GameInputGamepadState gamepad{}; 181 GameInputGamepadState gamepad{};
@@ -240,6 +279,149 @@ struct Rumble {
240 float low = 0, high = 0, left = 0, right = 0; 279 float low = 0, high = 0, left = 0, right = 0;
241}; 280};
242 281
282// GameInput -1..1 magnitudes and 0..1 saturations against SDL's levels and saturations.
283Sint16 hlevel(float v) { return static_cast<Sint16>(std::lround(std::clamp(v, -1.0f, 1.0f) * 32767.0f)); }
284Uint16 hsat(float v) { return static_cast<Uint16>(std::lround(std::clamp(v, 0.0f, 1.0f) * 65535.0f)); }
285uint16_t ms_from_us(uint64_t us) { return static_cast<uint16_t>(std::min<uint64_t>((us + 999) / 1000, 65535)); }
286
287// The SDL_HAPTIC_* bit an effect kind needs, for the motor flags and the create-time check.
288uint32_t kind_feature(GameInputForceFeedbackEffectKind kind) {
289 switch (kind) {
290 case GameInputForceFeedbackConstant: return SDL_HAPTIC_CONSTANT;
291 case GameInputForceFeedbackRamp: return SDL_HAPTIC_RAMP;
292 case GameInputForceFeedbackSineWave: return SDL_HAPTIC_SINE;
293 case GameInputForceFeedbackSquareWave: return SDL_HAPTIC_SQUARE;
294 case GameInputForceFeedbackTriangleWave: return SDL_HAPTIC_TRIANGLE;
295 case GameInputForceFeedbackSawtoothUpWave: return SDL_HAPTIC_SAWTOOTHUP;
296 case GameInputForceFeedbackSawtoothDownWave: return SDL_HAPTIC_SAWTOOTHDOWN;
297 case GameInputForceFeedbackSpring: return SDL_HAPTIC_SPRING;
298 case GameInputForceFeedbackFriction: return SDL_HAPTIC_FRICTION;
299 case GameInputForceFeedbackDamper: return SDL_HAPTIC_DAMPER;
300 case GameInputForceFeedbackInertia: return SDL_HAPTIC_INERTIA;
301 }
302 return 0;
303}
304
305bool valid_kind(GameInputForceFeedbackEffectKind kind) {
306 return kind >= GameInputForceFeedbackConstant && kind <= GameInputForceFeedbackInertia;
307}
308
309// An all-zero envelope is how a title that only sets a magnitude leaves it: that means no envelope, not silence.
310bool envelope_used(const GameInputForceFeedbackEnvelope& e) {
311 return e.attackDuration || e.sustainDuration || e.releaseDuration || e.attackGain != 0.0f ||
312 e.sustainGain != 0.0f || e.releaseGain != 0.0f || e.playCount || e.repeatDelay;
313}
314
315uint32_t play_count(const GameInputForceFeedbackParams& p) {
316 return p.kind <= GameInputForceFeedbackSawtoothDownWave ? p.data.constant.envelope.playCount : 0;
317}
318
319// One GameInput effect as SDL's template. GameInput's eleven kinds are SDL's eleven force-feedback effects, so the
320// kind picks the SDL type and the fields are magnitudes; conditions have no envelope in GameInput either. Returns
321// false for a kind the shim does not map. `endless` says the effect has no duration of its own (GameInput left the
322// envelope empty), which is what the poll thread re-runs before the SDL length runs out.
323bool build_effect(const GameInputForceFeedbackParams& p, float gain, bool* endless, uint32_t* length_ms,
324 SDL_HapticEffect* out) {
325 std::memset(out, 0, sizeof *out);
326 if (!valid_kind(p.kind)) return false;
327 const bool envelope_kind = p.kind <= GameInputForceFeedbackSawtoothDownWave;
328 const GameInputForceFeedbackEnvelope env = envelope_kind ? p.data.constant.envelope : GameInputForceFeedbackEnvelope{};
329 const bool used = envelope_kind && envelope_used(env);
330 const float level = gain * (used ? env.sustainGain : 1.0f); // GameInput's sustainGain is the effect's level
331 const uint64_t total_us = used ? env.attackDuration + env.sustainDuration + env.releaseDuration : 0;
332 *endless = total_us == 0;
333 *length_ms = total_us == 0 ? kHapticHoldMs
334 : static_cast<uint32_t>(std::clamp<uint64_t>((total_us + 999) / 1000, 1, 86'400'000));
335 // The envelope's attack and release, when the title gave one. SDL only uses the envelope when attack_length or
336 // fade_level is set, so a zero-gain envelope is left alone rather than muting the effect.
337 auto envelope = [&](SDL_HapticConstant& e) {
338 if (!used || (!env.attackDuration && !env.releaseDuration)) return;
339 e.attack_length = ms_from_us(env.attackDuration);
340 e.attack_level = hsat(env.attackGain);
341 e.fade_length = ms_from_us(env.releaseDuration);
342 e.fade_level = hsat(env.releaseGain);
343 };
344 // Force along +X: the axis a wheel's or a stick's motor acts on, which is the one the motor reports (LinearX).
345 auto direction = [](SDL_HapticDirection& d) {
346 d.type = SDL_HAPTIC_CARTESIAN;
347 d.dir[0] = 1;
348 };
349 switch (p.kind) {
350 case GameInputForceFeedbackConstant: {
351 SDL_HapticConstant& e = out->constant;
352 e.type = SDL_HAPTIC_CONSTANT;
353 direction(e.direction);
354 e.length = *length_ms;
355 e.level = hlevel(p.data.constant.magnitude.linearX * level);
356 envelope(e);
357 break;
358 }
359 case GameInputForceFeedbackRamp: {
360 SDL_HapticRamp& e = out->ramp;
361 e.type = SDL_HAPTIC_RAMP;
362 direction(e.direction);
363 e.length = *length_ms;
364 e.start = hlevel(p.data.ramp.startMagnitude.linearX * level);
365 e.end = hlevel(p.data.ramp.endMagnitude.linearX * level);
366 if (used) {
367 e.attack_length = ms_from_us(env.attackDuration);
368 e.attack_level = hsat(env.attackGain);
369 e.fade_length = ms_from_us(env.releaseDuration);
370 e.fade_level = hsat(env.releaseGain);
371 }
372 break;
373 }
374 case GameInputForceFeedbackSineWave:
375 case GameInputForceFeedbackSquareWave:
376 case GameInputForceFeedbackTriangleWave:
377 case GameInputForceFeedbackSawtoothUpWave:
378 case GameInputForceFeedbackSawtoothDownWave: {
379 SDL_HapticPeriodic& e = out->periodic;
380 e.type = p.kind == GameInputForceFeedbackSineWave ? SDL_HAPTIC_SINE
381 : p.kind == GameInputForceFeedbackSquareWave ? SDL_HAPTIC_SQUARE
382 : p.kind == GameInputForceFeedbackTriangleWave ? SDL_HAPTIC_TRIANGLE
383 : p.kind == GameInputForceFeedbackSawtoothUpWave ? SDL_HAPTIC_SAWTOOTHUP
384 : SDL_HAPTIC_SAWTOOTHDOWN;
385 direction(e.direction);
386 e.length = *length_ms;
387 const GameInputForceFeedbackPeriodicParams& pp = p.data.sineWave;
388 // GameInput gives the wave's frequency in Hz and its phase in degrees; SDL wants a period in ms and a
389 // phase in hundredths of a degree.
390 e.period = pp.frequency > 0.0f ? static_cast<Uint16>(std::clamp(std::lround(1000.0f / pp.frequency), 1L, 65535L)) : 100;
391 e.magnitude = hlevel(pp.magnitude.linearX * level);
392 e.offset = hlevel(pp.bias * level);
393 e.phase = static_cast<Uint16>(std::clamp(std::lround(pp.phase * 100.0f), 0L, 35999L));
394 if (used) {
395 e.attack_length = ms_from_us(env.attackDuration);
396 e.attack_level = hsat(env.attackGain);
397 e.fade_length = ms_from_us(env.releaseDuration);
398 e.fade_level = hsat(env.releaseGain);
399 }
400 break;
401 }
402 default: { // spring, friction, damper, inertia
403 SDL_HapticCondition& e = out->condition;
404 e.type = p.kind == GameInputForceFeedbackSpring ? SDL_HAPTIC_SPRING
405 : p.kind == GameInputForceFeedbackFriction ? SDL_HAPTIC_FRICTION
406 : p.kind == GameInputForceFeedbackDamper ? SDL_HAPTIC_DAMPER
407 : SDL_HAPTIC_INERTIA;
408 e.length = *length_ms;
409 const GameInputForceFeedbackConditionParams& cp = p.data.spring;
410 const float center[3] = {cp.magnitude.linearX, cp.magnitude.linearY, cp.magnitude.linearZ};
411 for (int a = 0; a < 3; ++a) {
412 e.right_sat[a] = hsat(cp.maxPositiveMagnitude);
413 e.left_sat[a] = hsat(cp.maxNegativeMagnitude);
414 e.right_coeff[a] = hlevel(cp.positiveCoefficient * level);
415 e.left_coeff[a] = hlevel(-cp.negativeCoefficient * level);
416 e.deadband[a] = hsat(cp.deadZone);
417 e.center[a] = hlevel(center[a]);
418 }
419 break;
420 }
421 }
422 return true;
423}
424
243class Device final : public IGameInputDevice { 425class Device final : public IGameInputDevice {
244public: 426public:
245 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { 427 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
@@ -260,13 +442,10 @@ public:
260 const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info; } 442 const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info; }
261 uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return status.load(); } 443 uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return status.load(); }
262 void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override; 444 void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override;
263 HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t, const void*, void** effect) override { 445 HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t motorIndex, const void* params, void** effect) override;
264 if (effect) *effect = nullptr; 446 bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t motorIndex) override;
265 return E_INVALIDARG; // forceFeedbackMotorCount is 0 447 void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t motorIndex, float masterGain) override;
266 } 448 HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t motorIndex, const void* params) override;
267 bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t) override { return false; }
268 void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t, float) override {}
269 HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t, const void*) override { return E_INVALIDARG; }
270 void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams* params) override; 449 void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams* params) override;
271 void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {} 450 void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {}
272 void STDMETHODCALLTYPE SendInputSynchronizationHint() override {} 451 void STDMETHODCALLTYPE SendInputSynchronizationHint() override {}
@@ -301,12 +480,20 @@ public:
301 GameInputGamepadInfo gamepad_info{}; 480 GameInputGamepadInfo gamepad_info{};
302 GameInputUiNavigationInfo ui_info{}; 481 GameInputUiNavigationInfo ui_info{};
303 GameInputMotionInfo motion_info{}; // filled only when the pad has sensors; info.motionInfo points at it 482 GameInputMotionInfo motion_info{}; // filled only when the pad has sensors; info.motionInfo points at it
483 GameInputForceFeedbackMotorInfo ff_motor_info{}; // filled when SDL opened the pad as a haptic device
484 GameInputHapticFeedbackMotorInfo haptic_motor_info[kHapticMotors]{}; // the trigger motors, when the pad has them
485 GameInputHapticWaveformInfo haptic_waveform_info[kHapticMotors]{}; // one waveform each, an intensity
304 std::atomic<uint32_t> status{GameInputDeviceNoStatus}; 486 std::atomic<uint32_t> status{GameInputDeviceNoStatus};
305 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading 487 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading
306 uint64_t evicted_order = 0; // order of the newest reading dropped from history 488 uint64_t evicted_order = 0; // order of the newest reading dropped from history
307 Reading* latest() const { return history.empty() ? nullptr : history.back(); } 489 Reading* latest() const { return history.empty() ? nullptr : history.back(); }
308 uint64_t seq = 0; 490 uint64_t seq = 0;
309 Rumble wanted; 491 Rumble wanted;
492 float motor_gain = 1.0f; // SetForceFeedbackMotorGain, 0..1
493 std::vector<ForceFeedbackEffect*> effects; // every live effect, so the poll thread can drive them
494 std::vector<int> retired; // SDL effect ids whose object is gone: destroyed on the poll thread
495 float haptic_intensity[kHapticMotors] = {}; // SetHapticMotorState, 0..1
496 uint64_t haptic_until[kHapticMotors] = {}; // when the request ends, 0 for "until changed"
310 GameInputBatteryState battery{0, 0, 0, 0, GameInputBatteryUnknown}; 497 GameInputBatteryState battery{0, 0, 0, 0, GameInputBatteryUnknown};
311 AppLocalDeviceId base_id{}; // id_bytes of the identity alone: twins share it, info.deviceId tells them apart 498 AppLocalDeviceId base_id{}; // id_bytes of the identity alone: twins share it, info.deviceId tells them apart
312 499
@@ -315,6 +502,11 @@ public:
315 SDL_JoystickID id = 0; 502 SDL_JoystickID id = 0;
316 int player = -1; 503 int player = -1;
317 bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false, has_motion = false; 504 bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false, has_motion = false;
505 bool has_trigger_output = false; // the pad backs trigger motors: rumble, DualSense effects or haptic motors
506 void* haptic = nullptr; // SDL_Haptic behind the joystick, when SDL has one for this pad
507 uint32_t ff_features = 0; // the SDL_HAPTIC_* bits it reports: which effect kinds it can play
508 int sent_gain = -1; // device gain 0..100 last sent, so a steady gain costs one call
509 uint32_t haptic_motors = 0; // trigger haptic motors the pad reports (0 or 2)
318 rt::gameinput::OutputState sent{}; 510 rt::gameinput::OutputState sent{};
319 Snapshot last_snap{}; // what the latest reading holds 511 Snapshot last_snap{}; // what the latest reading holds
320 uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors 512 uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors
@@ -361,6 +553,50 @@ struct Event {
361 GameInputCallbackToken only; // enumeration: deliver to this callback only 553 GameInputCallbackToken only; // enumeration: deliver to this callback only
362}; 554};
363 555
556// One effect a title created, on the device it belongs to. The object and its parameters belong to the title; SDL's
557// effect is created, run and destroyed on the poll thread, so a title call only writes its state and bumps `version_`,
558// which the poll thread compares before it touches SDL. A new effect is Running: CreateForceFeedbackEffect already
559// carried the parameters, and the documented use (create once, SetParams per frame) never reaches SetState.
560class ForceFeedbackEffect final : public IGameInputForceFeedbackEffect {
561public:
562 ForceFeedbackEffect(Device* device, uint32_t motor, const GameInputForceFeedbackParams& params);
563 ~ForceFeedbackEffect();
564
565 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override;
566 ULONG STDMETHODCALLTYPE AddRef() override;
567 ULONG STDMETHODCALLTYPE Release() override;
568 void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override;
569 uint32_t STDMETHODCALLTYPE GetMotorIndex() override;
570 float STDMETHODCALLTYPE GetGain() override;
571 void STDMETHODCALLTYPE SetGain(float gain) override;
572 void STDMETHODCALLTYPE GetParams(GameInputForceFeedbackParams* params) override;
573 bool STDMETHODCALLTYPE SetParams(const GameInputForceFeedbackParams* params) override;
574 GameInputFeedbackEffectState STDMETHODCALLTYPE GetState() override;
575 void STDMETHODCALLTYPE SetState(GameInputFeedbackEffectState state) override;
576
577 // Poll thread: make SDL match the effect's parameters, gain and state. `muted` says every output is off
578 // (LEONIDA_RUMBLE=0); the motor's master gain is SDL's device gain, set once by apply_effects.
579 void sync(Device* device, uint64_t now, bool muted);
580 // Poll thread, on unplug: the SDL device went with the pad, so forget its effect id without touching SDL.
581 void orphan();
582
583private:
584 std::atomic<ULONG> refs_{1};
585 Device* device_;
586 uint32_t motor_;
587 // Written by title calls under g().mu and read by the poll thread.
588 GameInputForceFeedbackParams params_;
589 float gain_ = 1.0f;
590 GameInputFeedbackEffectState state_ = GameInputFeedbackRunning;
591 uint64_t version_ = 1;
592 // Poll thread only.
593 uint64_t applied_ = 0; // the version SDL has
594 int sdl_effect_ = -1;
595 bool sdl_running_ = false;
596 bool endless_ = true; // GameInput gave no duration: re-run before the SDL length runs out
597 uint64_t run_at_ = 0, run_for_ = 0;
598};
599
364class Dispatcher; 600class Dispatcher;
365 601
366struct State { 602struct State {
@@ -425,6 +661,28 @@ void call(const Callback& c, const Event& e) {
425 } 661 }
426} 662}
427 663
664// Runs one queued event's callbacks on the calling thread, without holding the state lock.
665void deliver_event(const Event& e) {
666 State& s = g();
667 std::vector<Callback> targets;
668 {
669 std::lock_guard lock(s.mu);
670 for (const Callback& c : s.callbacks)
671 if (matches(c, e)) targets.push_back(c);
672 }
673 for (const Callback& c : targets) {
674 bool still = false;
675 {
676 std::lock_guard lock(s.mu);
677 for (const Callback& now : s.callbacks)
678 if (now.token == c.token) still = now.active;
679 }
680 if (still) call(c, e);
681 }
682 if (e.device) e.device->Release();
683 if (e.reading) e.reading->Release();
684}
685
428// Runs queued callbacks on the calling thread, without holding the state lock. Returns whether more events arrived 686// Runs queued callbacks on the calling thread, without holding the state lock. Returns whether more events arrived
429// meanwhile. 687// meanwhile.
430bool deliver() { 688bool deliver() {
@@ -435,30 +693,41 @@ bool deliver() {
435 std::lock_guard lock(s.mu); 693 std::lock_guard lock(s.mu);
436 events.swap(s.queue); 694 events.swap(s.queue);
437 } 695 }
438 const DWORD self = GetCurrentThreadId(); 696 s.delivering_thread = GetCurrentThreadId();
439 s.delivering_thread = self; 697 for (const Event& e : events) deliver_event(e);
440 for (const Event& e : events) { 698 s.delivering_thread = 0;
441 std::vector<Callback> targets; 699 std::lock_guard lock(s.mu);
700 return !s.queue.empty();
701}
702
703// IGameInputDispatcher::Dispatch: runs queued events oldest first, at least one even with a quota of 0, and takes no
704// further event once quota_us microseconds have passed (an event already started runs to the end, so the quota is a
705// target, as on Windows). While events remain the wait handle is signalled again, so a title that waits on it before
706// each call comes back for the rest. Returns whether events remain.
707bool deliver_within(uint64_t quota_us) {
708 State& s = g();
709 std::lock_guard dl(s.deliver_mu);
710 const auto start = std::chrono::steady_clock::now();
711 s.delivering_thread = GetCurrentThreadId();
712 for (bool first = true;; first = false) {
713 if (!first) {
714 const auto spent = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start);
715 if (static_cast<uint64_t>(spent.count()) >= quota_us) break;
716 }
717 Event e;
442 { 718 {
443 std::lock_guard lock(s.mu); 719 std::lock_guard lock(s.mu);
444 for (const Callback& c : s.callbacks) 720 if (s.queue.empty()) break;
445 if (matches(c, e)) targets.push_back(c); 721 e = s.queue.front();
722 s.queue.erase(s.queue.begin());
446 } 723 }
447 for (const Callback& c : targets) { 724 deliver_event(e);
448 bool still = false;
449 {
450 std::lock_guard lock(s.mu);
451 for (const Callback& now : s.callbacks)
452 if (now.token == c.token) still = now.active;
453 }
454 if (still) call(c, e);
455 }
456 if (e.device) e.device->Release();
457 if (e.reading) e.reading->Release();
458 } 725 }
459 s.delivering_thread = 0; 726 s.delivering_thread = 0;
460 std::lock_guard lock(s.mu); 727 std::lock_guard lock(s.mu);
461 return !s.queue.empty(); 728 const bool remaining = !s.queue.empty();
729 if (remaining && s.wait_event) SetEvent(s.wait_event);
730 return remaining;
462} 731}
463 732
464// ---- SDL backend (poll thread only) ----------------------------------------------------------------------------- 733// ---- SDL backend (poll thread only) -----------------------------------------------------------------------------
@@ -597,8 +866,7 @@ void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) {
597 // as the per-device one, so only pads with sensors answer a motion query. 866 // as the per-device one, so only pads with sensors answer a motion query.
598 i.supportedInput = kBaseKinds; 867 i.supportedInput = kBaseKinds;
599 if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency; 868 if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency;
600 if (d->has_trigger_rumble || (d->is_dualsense && g().config.ds_triggers != rt::gameinput::DsTriggerMode::Off)) 869 if (d->has_trigger_output) i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger;
601 i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger;
602 if (d->has_motion) { 870 if (d->has_motion) {
603 i.supportedInput |= GameInputKindMotion; 871 i.supportedInput |= GameInputKindMotion;
604 // The maxima GetMotionState's fractions divide by. The magnetometer is not available: SDL's gamepad API has 872 // The maxima GetMotionState's fractions divide by. The magnetometer is not available: SDL's gamepad API has
@@ -606,6 +874,17 @@ void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) {
606 d->motion_info = {kMaxAcceleration, kMaxAngularVelocity, 0.0f}; 874 d->motion_info = {kMaxAcceleration, kMaxAngularVelocity, 0.0f};
607 i.motionInfo = &d->motion_info; 875 i.motionInfo = &d->motion_info;
608 } 876 }
877 // The motors this pad can back. Force feedback is whatever SDL opened a haptic device for with effect kinds of its
878 // own; the haptic motors are the trigger motors the pad already has for rumble, which the shim can drive as an
879 // intensity. A pad with neither keeps the old answers: no motors at all.
880 if (d->haptic) {
881 i.forceFeedbackMotorCount = kForceFeedbackMotors;
882 i.forceFeedbackMotorInfo = &d->ff_motor_info;
883 }
884 if (d->haptic_motors) {
885 i.hapticFeedbackMotorCount = d->haptic_motors;
886 i.hapticFeedbackMotorInfo = d->haptic_motor_info;
887 }
609 i.controllerAxisCount = kAxisCount; 888 i.controllerAxisCount = kAxisCount;
610 i.controllerButtonCount = kButtonCount; 889 i.controllerButtonCount = kButtonCount;
611 for (uint32_t a = 0; a < kAxisCount; ++a) { 890 for (uint32_t a = 0; a < kAxisCount; ++a) {
@@ -703,9 +982,60 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) {
703 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_GYRO, kMotionSensorRate); 982 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_GYRO, kMotionSensorRate);
704 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_ACCEL, kMotionSensorRate); 983 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_ACCEL, kMotionSensorRate);
705 } 984 }
985 d->has_trigger_output = d->has_trigger_rumble ||
986 (d->is_dualsense && s.config.ds_triggers != rt::gameinput::DsTriggerMode::Off);
987 // Force feedback: SDL opens a wheel or a stick as a joystick with a haptic device behind it and never through the
988 // gamepad API, so it is opened from the joystick and closed with the pad. Only what the device really reports is
989 // passed on: no haptic device, no motor, and an effect kind SDL does not list is not offered to a title.
990 d->haptic = haptics().open_joystick(SDL_GetGamepadJoystick(p));
991 d->ff_features = 0;
992 d->ff_motor_info = {};
993 d->sent_gain = -1;
994 if (d->haptic) {
995 const uint32_t features = haptics().features(d->haptic);
996 if (features) {
997 GameInputForceFeedbackMotorInfo& m = d->ff_motor_info;
998 d->ff_features = features;
999 m.supportedAxes = GameInputFeedbackAxisLinearX; // the axis a wheel's or a stick's motor acts on
1000 m.location = GameInputLocationChassis;
1001 m.locationId = 0;
1002 m.maxSimultaneousEffects = static_cast<uint32_t>(std::max(1, haptics().max_effects(d->haptic)));
1003 m.isConstantEffectSupported = (features & SDL_HAPTIC_CONSTANT) != 0;
1004 m.isRampEffectSupported = (features & SDL_HAPTIC_RAMP) != 0;
1005 m.isSineWaveEffectSupported = (features & SDL_HAPTIC_SINE) != 0;
1006 m.isSquareWaveEffectSupported = (features & SDL_HAPTIC_SQUARE) != 0;
1007 m.isTriangleWaveEffectSupported = (features & SDL_HAPTIC_TRIANGLE) != 0;
1008 m.isSawtoothUpWaveEffectSupported = (features & SDL_HAPTIC_SAWTOOTHUP) != 0;
1009 m.isSawtoothDownWaveEffectSupported = (features & SDL_HAPTIC_SAWTOOTHDOWN) != 0;
1010 m.isSpringEffectSupported = (features & SDL_HAPTIC_SPRING) != 0;
1011 m.isFrictionEffectSupported = (features & SDL_HAPTIC_FRICTION) != 0;
1012 m.isDamperEffectSupported = (features & SDL_HAPTIC_DAMPER) != 0;
1013 m.isInertiaEffectSupported = (features & SDL_HAPTIC_INERTIA) != 0;
1014 } else {
1015 haptics().close(d->haptic);
1016 d->haptic = nullptr;
1017 }
1018 }
1019 // Haptic motors: the trigger motors, one waveform each. The waveform identifier is this shim's choice, an
1020 // intensity (HID physical-interface usage 0x0F/0x58), because an intensity is the one thing SDL lets it send.
1021 d->haptic_motors = 0;
1022 if (d->has_trigger_output) {
1023 for (uint32_t m = 0; m < kHapticMotors; ++m) {
1024 d->haptic_waveform_info[m] = {{0x0F, 0x58}, true, true, true, false, 0};
1025 d->haptic_motor_info[m] = {};
1026 d->haptic_motor_info[m].mappedRumbleMotors = m ? GameInputRumbleRightTrigger : GameInputRumbleLeftTrigger;
1027 d->haptic_motor_info[m].location = GameInputLocationChassis;
1028 d->haptic_motor_info[m].locationId = m;
1029 d->haptic_motor_info[m].waveformCount = 1;
1030 d->haptic_motor_info[m].waveformInfo = &d->haptic_waveform_info[m];
1031 }
1032 d->haptic_motors = kHapticMotors;
1033 }
706 d->sent = {}; 1034 d->sent = {};
707 d->sent.is_dualsense = d->is_dualsense; 1035 d->sent.is_dualsense = d->is_dualsense;
708 d->sent.trigger_rumble = d->has_trigger_rumble; 1036 d->sent.trigger_rumble = d->has_trigger_rumble;
1037 d->sent.force_feedback = d->haptic != nullptr;
1038 d->sent.haptic_motors = d->haptic_motors;
709 d->ds_sent_once = false; 1039 d->ds_sent_once = false;
710 d->motors_sent_at = d->triggers_sent_at = d->battery_at = 0; 1040 d->motors_sent_at = d->triggers_sent_at = d->battery_at = 0;
711 d->wanted = {}; 1041 d->wanted = {};
@@ -732,9 +1062,10 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) {
732 d->last_snap = snap; 1062 d->last_snap = snap;
733 push_reading(d, snap, ts); 1063 push_reading(d, snap, ts);
734 queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0}); 1064 queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0});
735 std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s%s)\n", d->name.c_str(), 1065 std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s%s%s)\n", d->name.c_str(),
736 d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "", 1066 d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "",
737 d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : ""); 1067 d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : "",
1068 d->haptic ? ", force feedback" : "");
738} 1069}
739 1070
740void close_pad(Device* d, uint64_t ts) { 1071void close_pad(Device* d, uint64_t ts) {
@@ -744,6 +1075,19 @@ void close_pad(Device* d, uint64_t ts) {
744 SDL_CloseGamepad(d->pad); 1075 SDL_CloseGamepad(d->pad);
745 d->pad = nullptr; 1076 d->pad = nullptr;
746 d->player = -1; 1077 d->player = -1;
1078 // The haptic device belongs to the joystick, which goes with the gamepad. Effects a title still holds stay alive
1079 // and pick up again when the pad comes back.
1080 if (d->haptic) {
1081 haptics().close(d->haptic);
1082 d->haptic = nullptr;
1083 }
1084 d->retired.clear();
1085 d->ff_features = 0;
1086 d->ff_motor_info = {};
1087 d->sent_gain = -1;
1088 d->haptic_motors = 0;
1089 for (ForceFeedbackEffect* e : d->effects) e->orphan();
1090 for (uint32_t m = 0; m < kHapticMotors; ++m) d->haptic_intensity[m] = 0, d->haptic_until[m] = 0;
747 if (!d->history.empty()) d->evicted_order = d->history.back()->order(); // the history ends with the session 1091 if (!d->history.empty()) d->evicted_order = d->history.back()->order(); // the history ends with the session
748 for (Reading* r : d->history) r->Release(); 1092 for (Reading* r : d->history) r->Release();
749 d->history.clear(); 1093 d->history.clear();
@@ -770,14 +1114,55 @@ void ds_effect(float strength, uint8_t out[11]) {
770 } 1114 }
771} 1115}
772 1116
1117// The force-feedback effects and the device gain, on the poll thread: SDL's effects are created, updated, run and
1118// destroyed here and nowhere else, so a title call costs a lock and a copy.
1119void apply_effects(Device* d, uint64_t now) {
1120 State& s = g();
1121 std::vector<ForceFeedbackEffect*> live;
1122 std::vector<int> retire;
1123 float motor_gain;
1124 bool muted;
1125 {
1126 std::lock_guard lock(s.mu);
1127 live.reserve(d->effects.size());
1128 for (ForceFeedbackEffect* e : d->effects) { // referenced: the title may release one while this runs
1129 e->AddRef();
1130 live.push_back(e);
1131 }
1132 retire.swap(d->retired);
1133 motor_gain = d->motor_gain;
1134 muted = !s.config.rumble;
1135 }
1136 if (d->haptic) {
1137 for (int id : retire) haptics().destroy_effect(d->haptic, id);
1138 const int gain = static_cast<int>(std::lround(std::clamp(motor_gain, 0.0f, 1.0f) * 100.0f));
1139 if (gain != d->sent_gain) {
1140 haptics().set_gain(d->haptic, gain);
1141 d->sent_gain = gain;
1142 }
1143 }
1144 for (ForceFeedbackEffect* e : live) {
1145 e->sync(d, now, muted);
1146 e->Release();
1147 }
1148}
1149
773void apply_output(Device* d, uint64_t now) { 1150void apply_output(Device* d, uint64_t now) {
774 State& s = g(); 1151 State& s = g();
775 Rumble want; 1152 Rumble want;
1153 float haptic[kHapticMotors] = {};
776 { 1154 {
777 std::lock_guard lock(s.mu); 1155 std::lock_guard lock(s.mu);
778 want = d->wanted; 1156 want = d->wanted;
779 } 1157 for (uint32_t m = 0; m < d->haptic_motors; ++m)
780 if (!s.config.rumble) want = {}; 1158 if (!d->haptic_until[m] || now < d->haptic_until[m]) haptic[m] = d->haptic_intensity[m];
1159 }
1160 const bool muted = !s.config.rumble;
1161 if (muted) want = {};
1162 // The haptic motors sit on the trigger motors, so their intensity and SetRumbleState's trigger level go out on one
1163 // output: the stronger of the two wins, and a request that has run out is dropped here.
1164 want.left = std::max(want.left, muted ? 0.0f : haptic[0]);
1165 want.right = std::max(want.right, muted ? 0.0f : haptic[1]);
781 rt::gameinput::OutputState& o = d->sent; 1166 rt::gameinput::OutputState& o = d->sent;
782 1167
783 if (d->has_rumble) { 1168 if (d->has_rumble) {
@@ -791,19 +1176,21 @@ void apply_output(Device* d, uint64_t now) {
791 } 1176 }
792 } 1177 }
793 if (d->is_dualsense) { 1178 if (d->is_dualsense) {
794 if (s.config.ds_triggers == rt::gameinput::DsTriggerMode::Off) return; // leave the triggers alone 1179 // LEONIDA_DS_TRIGGERS=off leaves the triggers alone.
795 uint8_t right[11], left[11]; 1180 if (s.config.ds_triggers != rt::gameinput::DsTriggerMode::Off) {
796 ds_effect(want.right, right); 1181 uint8_t right[11], left[11];
797 ds_effect(want.left, left); 1182 ds_effect(want.right, right);
798 if (!d->ds_sent_once || std::memcmp(right, o.ds_right, 11) || std::memcmp(left, o.ds_left, 11)) { 1183 ds_effect(want.left, left);
799 uint8_t block[kDsEffectSize] = {}; 1184 if (!d->ds_sent_once || std::memcmp(right, o.ds_right, 11) || std::memcmp(left, o.ds_left, 11)) {
800 block[0] = 0x04 | 0x08; // valid flags: right and left trigger effect 1185 uint8_t block[kDsEffectSize] = {};
801 std::memcpy(block + 10, right, 11); 1186 block[0] = 0x04 | 0x08; // valid flags: right and left trigger effect
802 std::memcpy(block + 21, left, 11); 1187 std::memcpy(block + 10, right, 11);
803 if (SDL_SendGamepadEffect(d->pad, block, sizeof block)) { 1188 std::memcpy(block + 21, left, 11);
804 std::memcpy(o.ds_right, right, 11); 1189 if (SDL_SendGamepadEffect(d->pad, block, sizeof block)) {
805 std::memcpy(o.ds_left, left, 11); 1190 std::memcpy(o.ds_right, right, 11);
806 d->ds_sent_once = true; 1191 std::memcpy(o.ds_left, left, 11);
1192 d->ds_sent_once = true;
1193 }
807 } 1194 }
808 } 1195 }
809 } else if (d->has_trigger_rumble) { 1196 } else if (d->has_trigger_rumble) {
@@ -816,6 +1203,7 @@ void apply_output(Device* d, uint64_t now) {
816 d->triggers_sent_at = now; 1203 d->triggers_sent_at = now;
817 } 1204 }
818 } 1205 }
1206 apply_effects(d, now);
819} 1207}
820 1208
821void refresh_battery(Device* d, uint64_t now) { 1209void refresh_battery(Device* d, uint64_t now) {
@@ -1226,6 +1614,197 @@ void Device::SetRumbleState(const GameInputRumbleParams* params) {
1226 wanted = params ? Rumble{params->lowFrequency, params->highFrequency, params->leftTrigger, params->rightTrigger} : Rumble{}; 1614 wanted = params ? Rumble{params->lowFrequency, params->highFrequency, params->leftTrigger, params->rightTrigger} : Rumble{};
1227} 1615}
1228 1616
1617HRESULT Device::CreateForceFeedbackEffect(uint32_t motorIndex, const void* params, void** effect) {
1618 if (!effect) return E_POINTER;
1619 *effect = nullptr;
1620 if (!params || motorIndex >= info.forceFeedbackMotorCount) return E_INVALIDARG;
1621 const auto* p = static_cast<const GameInputForceFeedbackParams*>(params);
1622 // Only what the motor reported. SDL is not asked here: this is a title call, so the cached feature mask decides,
1623 // and the poll thread is what finds out if SDL refuses the effect anyway.
1624 if (!valid_kind(p->kind) || !(ff_features & kind_feature(p->kind))) return E_INVALIDARG;
1625 *effect = new ForceFeedbackEffect(this, motorIndex, *p);
1626 return S_OK;
1627}
1628
1629bool Device::IsForceFeedbackMotorPoweredOn(uint32_t motorIndex) {
1630 return motorIndex < info.forceFeedbackMotorCount && haptic != nullptr && status.load() != GameInputDeviceNoStatus;
1631}
1632
1633void Device::SetForceFeedbackMotorGain(uint32_t motorIndex, float masterGain) {
1634 std::lock_guard lock(g().mu);
1635 if (motorIndex < info.forceFeedbackMotorCount) motor_gain = std::clamp(masterGain, 0.0f, 1.0f);
1636}
1637
1638HRESULT Device::SetHapticMotorState(uint32_t motorIndex, const void* params) {
1639 std::lock_guard lock(g().mu);
1640 if (motorIndex >= haptic_motors) return E_INVALIDARG;
1641 if (!params) { // stop the motor
1642 haptic_intensity[motorIndex] = 0.0f;
1643 haptic_until[motorIndex] = 0;
1644 return S_OK;
1645 }
1646 const auto* p = static_cast<const GameInputHapticFeedbackParams*>(params);
1647 if (p->waveformIndex >= haptic_motor_info[motorIndex].waveformCount) return E_INVALIDARG;
1648 haptic_intensity[motorIndex] = std::clamp(p->intensity, 0.0f, 1.0f);
1649 // duration and repeatDelay are microseconds; playCount 0 plays until the state is set again. The poll thread sends
1650 // the level and drops it when the deadline passes.
1651 uint64_t total = p->playCount == 0 ? 0 : p->duration;
1652 if (p->playCount > 1) total = p->duration * p->playCount + p->repeatDelay * (p->playCount - 1);
1653 haptic_until[motorIndex] = total ? now_us() + total : 0;
1654 return S_OK;
1655}
1656
1657// ---- IGameInputForceFeedbackEffect ----------------------------------------------------------------
1658
1659ForceFeedbackEffect::ForceFeedbackEffect(Device* device, uint32_t motor, const GameInputForceFeedbackParams& params)
1660 : device_(device), motor_(motor), params_(params) {
1661 device_->AddRef();
1662 std::lock_guard lock(g().mu);
1663 device_->effects.push_back(this);
1664}
1665
1666ForceFeedbackEffect::~ForceFeedbackEffect() {
1667 std::lock_guard lock(g().mu);
1668 std::vector<ForceFeedbackEffect*>& list = device_->effects;
1669 list.erase(std::remove(list.begin(), list.end(), this), list.end());
1670 if (sdl_effect_ >= 0) { // SDL's effect is destroyed by the poll thread, which is the only thread that may
1671 device_->retired.push_back(sdl_effect_);
1672 sdl_effect_ = -1;
1673 }
1674 device_->Release();
1675}
1676
1677HRESULT STDMETHODCALLTYPE ForceFeedbackEffect::QueryInterface(REFIID riid, void** out) {
1678 if (!out) return E_POINTER;
1679 if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputForceFeedbackEffect)) {
1680 AddRef();
1681 *out = static_cast<IGameInputForceFeedbackEffect*>(this);
1682 return S_OK;
1683 }
1684 *out = nullptr;
1685 return E_NOINTERFACE;
1686}
1687
1688ULONG STDMETHODCALLTYPE ForceFeedbackEffect::AddRef() { return ++refs_; }
1689
1690ULONG STDMETHODCALLTYPE ForceFeedbackEffect::Release() {
1691 const ULONG r = --refs_;
1692 if (r == 0) delete this;
1693 return r;
1694}
1695
1696void STDMETHODCALLTYPE ForceFeedbackEffect::GetDevice(IGameInputDevice** device) {
1697 if (!device) return;
1698 device_->AddRef();
1699 *device = device_;
1700}
1701
1702uint32_t STDMETHODCALLTYPE ForceFeedbackEffect::GetMotorIndex() { return motor_; }
1703
1704float STDMETHODCALLTYPE ForceFeedbackEffect::GetGain() {
1705 std::lock_guard lock(g().mu);
1706 return gain_;
1707}
1708
1709void STDMETHODCALLTYPE ForceFeedbackEffect::SetGain(float gain) {
1710 std::lock_guard lock(g().mu);
1711 gain_ = std::clamp(gain, 0.0f, 1.0f);
1712 ++version_;
1713}
1714
1715void STDMETHODCALLTYPE ForceFeedbackEffect::GetParams(GameInputForceFeedbackParams* params) {
1716 if (!params) return;
1717 std::lock_guard lock(g().mu);
1718 *params = params_;
1719}
1720
1721bool STDMETHODCALLTYPE ForceFeedbackEffect::SetParams(const GameInputForceFeedbackParams* params) {
1722 if (!params || !valid_kind(params->kind)) return false;
1723 std::lock_guard lock(g().mu);
1724 params_ = *params;
1725 ++version_;
1726 return true;
1727}
1728
1729GameInputFeedbackEffectState STDMETHODCALLTYPE ForceFeedbackEffect::GetState() {
1730 std::lock_guard lock(g().mu);
1731 return state_;
1732}
1733
1734void STDMETHODCALLTYPE ForceFeedbackEffect::SetState(GameInputFeedbackEffectState state) {
1735 std::lock_guard lock(g().mu);
1736 state_ = state;
1737 ++version_;
1738}
1739
1740void ForceFeedbackEffect::orphan() {
1741 sdl_effect_ = -1;
1742 sdl_running_ = false;
1743 applied_ = 0;
1744}
1745
1746void ForceFeedbackEffect::sync(Device* d, uint64_t now, bool muted) {
1747 GameInputForceFeedbackParams params;
1748 float gain;
1749 GameInputFeedbackEffectState state;
1750 uint64_t version;
1751 {
1752 std::lock_guard lock(g().mu);
1753 params = params_;
1754 gain = gain_;
1755 state = state_;
1756 version = version_;
1757 }
1758 if (!d->haptic) return;
1759 // A stopped or paused effect is stopped in SDL: GameInput pauses one effect where SDL pauses the device, so a
1760 // pause here is a stop that keeps the parameters. LEONIDA_RUMBLE=0 silences this path like every other.
1761 if (state != GameInputFeedbackRunning || muted) {
1762 if (sdl_running_) {
1763 haptics().stop_effect(d->haptic, sdl_effect_);
1764 sdl_running_ = false;
1765 }
1766 return;
1767 }
1768 // An effect that played the length GameInput gave it is over, as the API says of a finished effect. The run is
1769 // forgotten so that a second SetState(Running) starts it again instead of expiring at once.
1770 if (!endless_ && run_for_ && now >= run_at_ + run_for_) {
1771 if (sdl_running_) {
1772 haptics().stop_effect(d->haptic, sdl_effect_);
1773 sdl_running_ = false;
1774 }
1775 endless_ = true;
1776 run_for_ = 0;
1777 std::lock_guard lock(g().mu);
1778 state_ = GameInputFeedbackStopped;
1779 return;
1780 }
1781 const bool stale = sdl_running_ && endless_ && now - run_at_ > kRumbleRefreshUs;
1782 if (sdl_running_ && version == applied_ && !stale) return;
1783
1784 SDL_HapticEffect fx;
1785 bool endless = true;
1786 uint32_t length_ms = kHapticHoldMs;
1787 if (!build_effect(params, gain, &endless, &length_ms, &fx)) {
1788 if (sdl_running_) haptics().stop_effect(d->haptic, sdl_effect_);
1789 sdl_running_ = false;
1790 return;
1791 }
1792 if (sdl_effect_ < 0) {
1793 sdl_effect_ = haptics().create_effect(d->haptic, &fx); // SDL refused: nothing to drive this effect
1794 if (sdl_effect_ < 0) return;
1795 } else if (!haptics().update_effect(d->haptic, sdl_effect_, &fx)) {
1796 return;
1797 }
1798 // GameInput's playCount 0 means "until stopped", which is what SDL's 0 iterations means.
1799 const uint32_t iterations = endless ? 0 : play_count(params);
1800 if (!haptics().run_effect(d->haptic, sdl_effect_, iterations)) return;
1801 sdl_running_ = true;
1802 applied_ = version;
1803 endless_ = endless;
1804 run_at_ = now;
1805 run_for_ = endless || iterations == 0 ? 0 : static_cast<uint64_t>(length_ms) * 1000ull * iterations;
1806}
1807
1229// ---- IGameInputDispatcher ---- 1808// ---- IGameInputDispatcher ----
1230 1809
1231class Dispatcher final : public IGameInputDispatcher { 1810class Dispatcher final : public IGameInputDispatcher {
@@ -1256,8 +1835,8 @@ public:
1256 } 1835 }
1257 return r; 1836 return r;
1258 } 1837 }
1259 // Runs the queued callbacks on the caller's thread. The quota is not enforced: the queue is short. 1838 // Runs the queued callbacks on the caller's thread within the quota (see deliver_within).
1260 bool STDMETHODCALLTYPE Dispatch(uint64_t) override { return deliver(); } 1839 bool STDMETHODCALLTYPE Dispatch(uint64_t quotaInMicroseconds) override { return deliver_within(quotaInMicroseconds); }
1261 HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override { 1840 HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override {
1262 if (!handle) return E_POINTER; 1841 if (!handle) return E_POINTER;
1263 *handle = nullptr; 1842 *handle = nullptr;
@@ -1607,6 +2186,8 @@ void set_keyboard_source(KeyDownFn key_down, HasFocusFn has_focus) {
1607 2186
1608void set_cursor_source(CursorPosFn cursor_pos) { g_cursor_pos = cursor_pos ? cursor_pos : system_cursor_pos; } 2187void set_cursor_source(CursorPosFn cursor_pos) { g_cursor_pos = cursor_pos ? cursor_pos : system_cursor_pos; }
1609 2188
2189void set_haptic_source(const HapticApi* api) { g_haptic_api = api ? api : &kSdlHaptic; }
2190
1610const KeyBinding* keyboard_bindings(int* count) { 2191const KeyBinding* keyboard_bindings(int* count) {
1611 if (count) *count = static_cast<int>(std::size(kKeyBindings)); 2192 if (count) *count = static_cast<int>(std::size(kKeyBindings));
1612 return kKeyBindings; 2193 return kKeyBindings;
diff --git a/runtime/shims/gameinput.h b/runtime/shims/gameinput.h
index 0aa3cf38d..b3197f58e 100644
--- a/runtime/shims/gameinput.h
+++ b/runtime/shims/gameinput.h
@@ -38,6 +38,26 @@ void poll();
38// Number of gamepads currently open by the backend (tests, gameinput_probe). 38// Number of gamepads currently open by the backend (tests, gameinput_probe).
39int connected_count(); 39int connected_count();
40 40
41// The SDL haptic calls the shim makes, one entry per call, so a test can stand in for them: SDL's virtual joysticks
42// report no haptics, and a pad that does is the only other way to reach this path. `joystick` is the SDL_Joystick the
43// gamepad was opened from, `haptic` what open_joystick returned, `effect` is an SDL_HapticEffect. Returning null from
44// open_joystick says the pad has no force feedback, which is what a pad without it does.
45struct HapticApi {
46 void* (*open_joystick)(void* joystick); // SDL_OpenHapticFromJoystick
47 void (*close)(void* haptic); // SDL_CloseHaptic
48 uint32_t (*features)(void* haptic); // SDL_GetHapticFeatures: the SDL_HAPTIC_* bits the device supports
49 int (*max_effects)(void* haptic); // SDL_GetMaxHapticEffects
50 int (*create_effect)(void* haptic, const void* effect); // SDL_CreateHapticEffect, -1 on failure
51 bool (*update_effect)(void* haptic, int effect, const void* data); // SDL_UpdateHapticEffect
52 bool (*run_effect)(void* haptic, int effect, uint32_t iterations); // SDL_RunHapticEffect
53 bool (*stop_effect)(void* haptic, int effect); // SDL_StopHapticEffect
54 void (*destroy_effect)(void* haptic, int effect); // SDL_DestroyHapticEffect
55 bool (*set_gain)(void* haptic, int gain); // SDL_SetHapticGain, 0..100
56};
57// Where the haptics come from (tests). nullptr restores SDL. Applies to pads opened after the call: a pad keeps the
58// haptic device it was opened with.
59void set_haptic_source(const HapticApi* api);
60
41// What the shim last sent to SDL for the device that is index `i` in connection order. Test seam. 61// What the shim last sent to SDL for the device that is index `i` in connection order. Test seam.
42struct OutputState { 62struct OutputState {
43 uint16_t low = 0, high = 0; // SDL_RumbleGamepad 63 uint16_t low = 0, high = 0; // SDL_RumbleGamepad
@@ -45,6 +65,8 @@ struct OutputState {
45 uint8_t ds_right[11] = {}, ds_left[11] = {}; // last DualSense trigger effects sent 65 uint8_t ds_right[11] = {}, ds_left[11] = {}; // last DualSense trigger effects sent
46 bool is_dualsense = false; 66 bool is_dualsense = false;
47 bool trigger_rumble = false; // the pad takes SDL_RumbleGamepadTriggers 67 bool trigger_rumble = false; // the pad takes SDL_RumbleGamepadTriggers
68 bool force_feedback = false; // SDL opened the pad as a haptic device
69 uint32_t haptic_motors = 0; // haptic motors the pad reports (0 or 2)
48}; 70};
49bool output_state(int i, OutputState* out); 71bool output_state(int i, OutputState* out);
50 72
diff --git a/runtime/shims/gameinput_abi.h b/runtime/shims/gameinput_abi.h
index 053b00cc9..c5c0cd321 100644
--- a/runtime/shims/gameinput_abi.h
+++ b/runtime/shims/gameinput_abi.h
@@ -131,6 +131,50 @@ enum GameInputRumbleMotors : uint32_t {
131 GameInputRumbleRightTrigger = 0x00000008, 131 GameInputRumbleRightTrigger = 0x00000008,
132}; 132};
133 133
134// Where a motor sits on the device. v0 carries it in the motor infos below.
135enum GameInputLocation : int32_t {
136 GameInputLocationUnknown = -1,
137 GameInputLocationChassis = 0,
138 GameInputLocationDisplay = 1,
139 GameInputLocationAxis = 2,
140 GameInputLocationButton = 3,
141 GameInputLocationSwitch = 4,
142 GameInputLocationKey = 5,
143 GameInputLocationTouchPad = 6,
144};
145
146// The axes a force-feedback motor can drive, and the kinds of effect it can play.
147enum GameInputFeedbackAxes : uint32_t {
148 GameInputFeedbackAxisNone = 0x00000000,
149 GameInputFeedbackAxisLinearX = 0x00000001,
150 GameInputFeedbackAxisLinearY = 0x00000002,
151 GameInputFeedbackAxisLinearZ = 0x00000004,
152 GameInputFeedbackAxisAngularX = 0x00000008,
153 GameInputFeedbackAxisAngularY = 0x00000010,
154 GameInputFeedbackAxisAngularZ = 0x00000020,
155 GameInputFeedbackAxisNormal = 0x00000040,
156};
157
158enum GameInputFeedbackEffectState : int32_t {
159 GameInputFeedbackStopped = 0,
160 GameInputFeedbackRunning = 1,
161 GameInputFeedbackPaused = 2,
162};
163
164enum GameInputForceFeedbackEffectKind : int32_t {
165 GameInputForceFeedbackConstant = 0,
166 GameInputForceFeedbackRamp = 1,
167 GameInputForceFeedbackSineWave = 2,
168 GameInputForceFeedbackSquareWave = 3,
169 GameInputForceFeedbackTriangleWave = 4,
170 GameInputForceFeedbackSawtoothUpWave = 5,
171 GameInputForceFeedbackSawtoothDownWave = 6,
172 GameInputForceFeedbackSpring = 7,
173 GameInputForceFeedbackFriction = 8,
174 GameInputForceFeedbackDamper = 9,
175 GameInputForceFeedbackInertia = 10,
176};
177
134enum GameInputSwitchPosition : int32_t { GameInputSwitchCenter = 0 }; 178enum GameInputSwitchPosition : int32_t { GameInputSwitchCenter = 0 };
135enum GameInputFocusPolicy : uint32_t { GameInputDefaultFocusPolicy = 0 }; 179enum GameInputFocusPolicy : uint32_t { GameInputDefaultFocusPolicy = 0 };
136 180
@@ -171,6 +215,11 @@ struct GameInputBatteryState {
171 GameInputBatteryStatus status; 215 GameInputBatteryStatus status;
172}; 216};
173 217
218struct GameInputUsage {
219 uint16_t page;
220 uint16_t id;
221};
222
174struct GameInputRumbleParams { 223struct GameInputRumbleParams {
175 float lowFrequency; 224 float lowFrequency;
176 float highFrequency; 225 float highFrequency;
@@ -178,17 +227,134 @@ struct GameInputRumbleParams {
178 float rightTrigger; 227 float rightTrigger;
179}; 228};
180 229
230// ---- force feedback and haptic motors ------------------------------------------------------------
231// One entry of GameInputDeviceInfo::forceFeedbackMotorInfo per motor.
232struct GameInputForceFeedbackMotorInfo {
233 GameInputFeedbackAxes supportedAxes;
234 GameInputLocation location;
235 uint32_t locationId;
236 uint32_t maxSimultaneousEffects;
237 bool isConstantEffectSupported;
238 bool isRampEffectSupported;
239 bool isSineWaveEffectSupported;
240 bool isSquareWaveEffectSupported;
241 bool isTriangleWaveEffectSupported;
242 bool isSawtoothUpWaveEffectSupported;
243 bool isSawtoothDownWaveEffectSupported;
244 bool isSpringEffectSupported;
245 bool isFrictionEffectSupported;
246 bool isDamperEffectSupported;
247 bool isInertiaEffectSupported;
248};
249
250// One entry of GameInputHapticFeedbackMotorInfo::waveformInfo per waveform the motor can play.
251struct GameInputHapticWaveformInfo {
252 GameInputUsage usage; // the HID usage of the waveform
253 bool isDurationSupported;
254 bool isIntensitySupported;
255 bool isRepeatSupported;
256 bool isRepeatDelaySupported;
257 uint64_t defaultDuration; // microseconds
258};
259
260// One entry of GameInputDeviceInfo::hapticFeedbackMotorInfo per haptic motor.
261struct GameInputHapticFeedbackMotorInfo {
262 GameInputRumbleMotors mappedRumbleMotors; // the rumble motors this haptic motor sits on
263 GameInputLocation location;
264 uint32_t locationId;
265 uint32_t waveformCount;
266 const GameInputHapticWaveformInfo* waveformInfo;
267};
268
269// An effect's duration and gain over time. The durations are microseconds; 0 everywhere means the effect has no
270// envelope and lasts until it is stopped, and playCount 0 means the same.
271struct GameInputForceFeedbackEnvelope {
272 uint64_t attackDuration;
273 uint64_t sustainDuration;
274 uint64_t releaseDuration;
275 float attackGain;
276 float sustainGain;
277 float releaseGain;
278 uint32_t playCount;
279 uint64_t repeatDelay;
280};
281
282// An effect's strength per axis, -1..1 (the axis is chosen by the motor's supportedAxes).
283struct GameInputForceFeedbackMagnitude {
284 float linearX;
285 float linearY;
286 float linearZ;
287 float angularX;
288 float angularY;
289 float angularZ;
290 float normal;
291};
292
293struct GameInputForceFeedbackConditionParams {
294 GameInputForceFeedbackMagnitude magnitude;
295 float positiveCoefficient;
296 float negativeCoefficient;
297 float maxPositiveMagnitude;
298 float maxNegativeMagnitude;
299 float deadZone;
300 float bias;
301};
302
303struct GameInputForceFeedbackConstantParams {
304 GameInputForceFeedbackEnvelope envelope;
305 GameInputForceFeedbackMagnitude magnitude;
306};
307
308// Sine, square, triangle and both sawtooth waves. `frequency` is Hz and `phase` degrees (the shim's reading of the
309// GDK remarks: 0 is no displacement); SDL takes a period in ms and a phase in hundredths of a degree.
310struct GameInputForceFeedbackPeriodicParams {
311 GameInputForceFeedbackEnvelope envelope;
312 GameInputForceFeedbackMagnitude magnitude;
313 float frequency;
314 float phase;
315 float bias;
316};
317
318struct GameInputForceFeedbackRampParams {
319 GameInputForceFeedbackEnvelope envelope;
320 GameInputForceFeedbackMagnitude startMagnitude;
321 GameInputForceFeedbackMagnitude endMagnitude;
322};
323
324// What CreateForceFeedbackEffect and IGameInputForceFeedbackEffect::SetParams take: `kind` chooses the union member.
325struct GameInputForceFeedbackParams {
326 GameInputForceFeedbackEffectKind kind;
327 union {
328 GameInputForceFeedbackConstantParams constant;
329 GameInputForceFeedbackRampParams ramp;
330 GameInputForceFeedbackPeriodicParams sineWave;
331 GameInputForceFeedbackPeriodicParams squareWave;
332 GameInputForceFeedbackPeriodicParams triangleWave;
333 GameInputForceFeedbackPeriodicParams sawtoothUpWave;
334 GameInputForceFeedbackPeriodicParams sawtoothDownWave;
335 GameInputForceFeedbackConditionParams spring;
336 GameInputForceFeedbackConditionParams friction;
337 GameInputForceFeedbackConditionParams damper;
338 GameInputForceFeedbackConditionParams inertia;
339 } data;
340};
341
342// What SetHapticMotorState takes: one waveform of the motor's waveformInfo, played `playCount` times. `duration` and
343// `repeatDelay` are microseconds; playCount 0 plays until the state is set again.
344struct GameInputHapticFeedbackParams {
345 uint32_t waveformIndex;
346 uint64_t duration;
347 float intensity;
348 uint32_t playCount;
349 uint64_t repeatDelay;
350};
351
181struct GameInputString { 352struct GameInputString {
182 uint32_t sizeInBytes; 353 uint32_t sizeInBytes;
183 uint32_t codePointCount; 354 uint32_t codePointCount;
184 const char* data; // UTF-8, zero-terminated 355 const char* data; // UTF-8, zero-terminated
185}; 356};
186 357
187struct GameInputUsage {
188 uint16_t page;
189 uint16_t id;
190};
191
192struct GameInputVersion { 358struct GameInputVersion {
193 uint16_t major, minor, build, revision; 359 uint16_t major, minor, build, revision;
194}; 360};
@@ -332,6 +498,30 @@ static_assert(offsetof(GameInputDeviceInfo, gamepadInfo) == 256);
332static_assert(offsetof(GameInputDeviceInfo, displayName) == 296); 498static_assert(offsetof(GameInputDeviceInfo, displayName) == 296);
333static_assert(sizeof(GameInputDeviceInfo) == 320); 499static_assert(sizeof(GameInputDeviceInfo) == 320);
334 500
501// The force-feedback and haptic layouts, transcribed from the public v0 header (GameInput.h, the same GDK release
502// as the rest of this file). They were not compiled against that header here — it is not in the repository — so
503// the sizes and offsets below are the check: they are what x64 MSVC lays out for those declarations.
504static_assert(sizeof(GameInputForceFeedbackMotorInfo) == 28);
505static_assert(offsetof(GameInputForceFeedbackMotorInfo, location) == 4);
506static_assert(offsetof(GameInputForceFeedbackMotorInfo, maxSimultaneousEffects) == 12);
507static_assert(offsetof(GameInputForceFeedbackMotorInfo, isConstantEffectSupported) == 16);
508static_assert(sizeof(GameInputHapticWaveformInfo) == 16);
509static_assert(offsetof(GameInputHapticWaveformInfo, defaultDuration) == 8);
510static_assert(sizeof(GameInputHapticFeedbackMotorInfo) == 24);
511static_assert(offsetof(GameInputHapticFeedbackMotorInfo, waveformInfo) == 16);
512static_assert(sizeof(GameInputForceFeedbackEnvelope) == 48);
513static_assert(offsetof(GameInputForceFeedbackEnvelope, repeatDelay) == 40);
514static_assert(sizeof(GameInputForceFeedbackMagnitude) == 28);
515static_assert(sizeof(GameInputForceFeedbackConditionParams) == 52);
516static_assert(sizeof(GameInputForceFeedbackConstantParams) == 80); // 76 rounded up to the envelope's 8-byte alignment
517static_assert(offsetof(GameInputForceFeedbackConstantParams, magnitude) == 48);
518static_assert(sizeof(GameInputForceFeedbackPeriodicParams) == 88);
519static_assert(sizeof(GameInputForceFeedbackRampParams) == 104);
520static_assert(sizeof(GameInputForceFeedbackParams) == 112);
521static_assert(offsetof(GameInputForceFeedbackParams, data) == 8);
522static_assert(sizeof(GameInputHapticFeedbackParams) == 32);
523static_assert(offsetof(GameInputHapticFeedbackParams, repeatDelay) == 24);
524
335struct IGameInputDevice; 525struct IGameInputDevice;
336struct IGameInputReading; 526struct IGameInputReading;
337struct IGameInputDispatcher; 527struct IGameInputDispatcher;
@@ -354,6 +544,8 @@ constexpr GUID IID_IGameInputReading = {0x2156947A, 0xE1FA, 0x4DE0, {0xA3, 0x0B,
354constexpr GUID IID_IGameInputDevice = {0x31DD86FB, 0x4C1B, 0x408A, {0x86, 0x8F, 0x43, 0x9B, 0x3C, 0xD4, 0x71, 0x25}}; 544constexpr GUID IID_IGameInputDevice = {0x31DD86FB, 0x4C1B, 0x408A, {0x86, 0x8F, 0x43, 0x9B, 0x3C, 0xD4, 0x71, 0x25}};
355// {415EED2E-98CB-42C2-8F28-B94601074E31} 545// {415EED2E-98CB-42C2-8F28-B94601074E31}
356constexpr GUID IID_IGameInputDispatcher = {0x415EED2E, 0x98CB, 0x42C2, {0x8F, 0x28, 0xB9, 0x46, 0x01, 0x07, 0x4E, 0x31}}; 546constexpr GUID IID_IGameInputDispatcher = {0x415EED2E, 0x98CB, 0x42C2, {0x8F, 0x28, 0xB9, 0x46, 0x01, 0x07, 0x4E, 0x31}};
547// {51BDA05E-F742-45D9-B085-9444AE48381D}
548constexpr GUID IID_IGameInputForceFeedbackEffect = {0x51BDA05E, 0xF742, 0x45D9, {0xB0, 0x85, 0x94, 0x44, 0xAE, 0x48, 0x38, 0x1D}};
357 549
358// Interfaces, methods in vtable order. Pointer types the shim never implements are void*. 550// Interfaces, methods in vtable order. Pointer types the shim never implements are void*.
359struct IGameInput : IUnknown { 551struct IGameInput : IUnknown {
@@ -445,6 +637,19 @@ struct IGameInputDevice : IUnknown {
445 virtual void STDMETHODCALLTYPE ReleaseExclusiveRawDeviceAccess() = 0; 637 virtual void STDMETHODCALLTYPE ReleaseExclusiveRawDeviceAccess() = 0;
446}; 638};
447 639
640// What CreateForceFeedbackEffect returns: the effect's parameters, gain and run state, and one reference on the
641// device it belongs to.
642struct IGameInputForceFeedbackEffect : IUnknown {
643 virtual void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) = 0;
644 virtual uint32_t STDMETHODCALLTYPE GetMotorIndex() = 0;
645 virtual float STDMETHODCALLTYPE GetGain() = 0;
646 virtual void STDMETHODCALLTYPE SetGain(float gain) = 0;
647 virtual void STDMETHODCALLTYPE GetParams(GameInputForceFeedbackParams* params) = 0;
648 virtual bool STDMETHODCALLTYPE SetParams(const GameInputForceFeedbackParams* params) = 0;
649 virtual GameInputFeedbackEffectState STDMETHODCALLTYPE GetState() = 0;
650 virtual void STDMETHODCALLTYPE SetState(GameInputFeedbackEffectState state) = 0;
651};
652
448struct IGameInputDispatcher : IUnknown { 653struct IGameInputDispatcher : IUnknown {
449 virtual bool STDMETHODCALLTYPE Dispatch(uint64_t quotaInMicroseconds) = 0; 654 virtual bool STDMETHODCALLTYPE Dispatch(uint64_t quotaInMicroseconds) = 0;
450 virtual HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* waitHandle) = 0; 655 virtual HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* waitHandle) = 0;
diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp
index 0093e6050..66feefb9b 100644
--- a/runtime/shims/library_loader.cpp
+++ b/runtime/shims/library_loader.cpp
@@ -214,6 +214,17 @@ BOOL WINAPI free_library(HMODULE module) {
214 return FreeLibrary(module); 214 return FreeLibrary(module);
215} 215}
216 216
217// DisableThreadLibraryCalls(hinstance) from a mapped image's DllMain. The real function only accepts a module the
218// Windows loader mapped, so for ours it fails, and a DllMain that returns its result (the MSVC runtime's satellite
219// DLLs do) fails Loader::initialise() with "DllMain returned FALSE". Owned and mapped modules answer TRUE. The loader
220// sends no thread events to a DllMain, so there is nothing further to switch off; every other handle goes to the
221// real function.
222BOOL WINAPI disable_thread_calls(HMODULE module) {
223 if (pseudo(module)) return TRUE;
224 if (owns_bundled_module_handle(module)) return TRUE;
225 return DisableThreadLibraryCalls(module);
226}
227
217#define LOADER(dll) \ 228#define LOADER(dll) \
218 {dll, "LoadLibraryA", reinterpret_cast<void*>(&rt::shims::library_loader::load_library_a)}, \ 229 {dll, "LoadLibraryA", reinterpret_cast<void*>(&rt::shims::library_loader::load_library_a)}, \
219 {dll, "LoadLibraryW", reinterpret_cast<void*>(&rt::shims::library_loader::load_library_w)}, \ 230 {dll, "LoadLibraryW", reinterpret_cast<void*>(&rt::shims::library_loader::load_library_w)}, \
@@ -222,7 +233,8 @@ BOOL WINAPI free_library(HMODULE module) {
222 {dll, "GetModuleHandleA", reinterpret_cast<void*>(&rt::shims::library_loader::get_module_handle_a)}, \ 233 {dll, "GetModuleHandleA", reinterpret_cast<void*>(&rt::shims::library_loader::get_module_handle_a)}, \
223 {dll, "GetModuleHandleW", reinterpret_cast<void*>(&rt::shims::library_loader::get_module_handle_w)}, \ 234 {dll, "GetModuleHandleW", reinterpret_cast<void*>(&rt::shims::library_loader::get_module_handle_w)}, \
224 {dll, "GetProcAddress", reinterpret_cast<void*>(&rt::shims::library_loader::get_proc_address)}, \ 235 {dll, "GetProcAddress", reinterpret_cast<void*>(&rt::shims::library_loader::get_proc_address)}, \
225 {dll, "FreeLibrary", reinterpret_cast<void*>(&rt::shims::library_loader::free_library)} 236 {dll, "FreeLibrary", reinterpret_cast<void*>(&rt::shims::library_loader::free_library)}, \
237 {dll, "DisableThreadLibraryCalls", reinterpret_cast<void*>(&rt::shims::library_loader::disable_thread_calls)}
226 238
227} // namespace 239} // namespace
228} // namespace rt::shims::library_loader 240} // namespace rt::shims::library_loader
diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h
index 392eb39c9..5203837d8 100644
--- a/runtime/shims/startup_trace.h
+++ b/runtime/shims/startup_trace.h
@@ -26,6 +26,7 @@
26#include <chrono> 26#include <chrono>
27#include <cstdint> 27#include <cstdint>
28#include <cstdio> 28#include <cstdio>
29#include <cstdlib>
29#include <mutex> 30#include <mutex>
30#include <string> 31#include <string>
31 32
@@ -35,7 +36,12 @@ namespace rt::startup_trace {
35 36
36namespace detail { 37namespace detail {
37inline std::atomic<bool> on{false}; 38inline std::atomic<bool> on{false};
38inline std::mutex mutex; 39// Intentionally immortal: vectored exception handlers or late teardown paths can still run after normal statics would
40// have been destroyed.
41inline std::mutex& mutex() {
42 static auto* m = new std::mutex;
43 return *m;
44}
39inline FILE* file = nullptr; 45inline FILE* file = nullptr;
40inline unsigned long long seq = 0; 46inline unsigned long long seq = 0;
41inline std::chrono::steady_clock::time_point start; 47inline std::chrono::steady_clock::time_point start;
@@ -65,7 +71,7 @@ inline void append_escaped(std::string& out, const char* s, size_t n) {
65} 71}
66} // namespace detail 72} // namespace detail
67 73
68inline bool enabled() noexcept { return detail::on.load(std::memory_order_relaxed); } 74inline bool enabled() noexcept { return detail::on.load(std::memory_order_acquire); }
69 75
70// A JSON string literal, quotes included. 76// A JSON string literal, quotes included.
71inline std::string quote(const std::string& s) { 77inline std::string quote(const std::string& s) {
@@ -87,7 +93,7 @@ inline std::string where(uint64_t address) { return shims::module_offset(address
87// `fields` is the rest of the object, already JSON: `"module":"a.dll","result":1`. Empty is allowed. 93// `fields` is the rest of the object, already JSON: `"module":"a.dll","result":1`. Empty is allowed.
88inline void event(const char* kind, const std::string& fields = {}) { 94inline void event(const char* kind, const std::string& fields = {}) {
89 if (!enabled()) return; 95 if (!enabled()) return;
90 const std::lock_guard lock(detail::mutex); 96 const std::lock_guard lock(detail::mutex());
91 if (!detail::file) return; 97 if (!detail::file) return;
92 const double t = std::chrono::duration<double>(std::chrono::steady_clock::now() - detail::start).count(); 98 const double t = std::chrono::duration<double>(std::chrono::steady_clock::now() - detail::start).count();
93 std::fprintf(detail::file, "{\"seq\":%llu,\"t\":%.6f,\"kind\":\"%s\"%s%s}\n", ++detail::seq, t, kind, 99 std::fprintf(detail::file, "{\"seq\":%llu,\"t\":%.6f,\"kind\":\"%s\"%s%s}\n", ++detail::seq, t, kind,
@@ -151,10 +157,8 @@ inline std::string debug_text(const EXCEPTION_RECORD& r) {
151 return utf8_from_ansi(a, static_cast<int>(n ? n - 1 : strlen(a))); 157 return utf8_from_ansi(a, static_cast<int>(n ? n - 1 : strlen(a)));
152} 158}
153 159
154inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { 160inline void log_exception(const EXCEPTION_POINTERS& info) {
155 if (!enabled() || in_handler || !info || !info->ExceptionRecord) return EXCEPTION_CONTINUE_SEARCH; 161 const EXCEPTION_RECORD& r = *info.ExceptionRecord;
156 in_handler = true;
157 const EXCEPTION_RECORD& r = *info->ExceptionRecord;
158 try { 162 try {
159 if (r.ExceptionCode == kDbgPrint || r.ExceptionCode == kDbgPrintWide) { 163 if (r.ExceptionCode == kDbgPrint || r.ExceptionCode == kDbgPrintWide) {
160 std::string text = debug_text(r); 164 std::string text = debug_text(r);
@@ -169,23 +173,43 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
169 ",\"address\":" + quote(hex(r.ExceptionInformation[1])); 173 ",\"address\":" + quote(hex(r.ExceptionInformation[1]));
170 } 174 }
171 if (r.ExceptionCode == kCppException) f += ",\"cpp\":true"; 175 if (r.ExceptionCode == kCppException) f += ",\"cpp\":true";
172 if (info->ContextRecord) f += ",\"stack\":" + stack_from(*info->ContextRecord); 176 if (info.ContextRecord) f += ",\"stack\":" + stack_from(*info.ContextRecord);
173 event("exception", f); 177 event("exception", f);
174 } 178 }
175 } catch (...) { 179 } catch (...) {
176 // Out of memory while formatting: drop the event rather than disturb the process. 180 // Out of memory while formatting: drop the event rather than disturb the process.
177 } 181 }
182}
183
184inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
185 if (!enabled() || in_handler || !info || !info->ExceptionRecord) return EXCEPTION_CONTINUE_SEARCH;
186 in_handler = true;
187#ifdef _MSC_VER
188 // Under /EHsc, catch(...) does not catch SEH faults (e.g. a bad DBG_PRINTEXCEPTION_C pointer or corrupt unwind).
189 // Keep the __try frame free of C++ destructors so in_handler is always reset and the exception still propagates.
190 __try {
191 log_exception(*info);
192 } __except (EXCEPTION_EXECUTE_HANDLER) {
193 }
194#else
195 struct Reset {
196 ~Reset() { in_handler = false; }
197 } reset;
198 log_exception(*info);
199#endif
178 in_handler = false; 200 in_handler = false;
179 return EXCEPTION_CONTINUE_SEARCH; 201 return EXCEPTION_CONTINUE_SEARCH;
180} 202}
181} // namespace detail 203} // namespace detail
182 204
205inline void close();
206
183// Creates the trace file and installs the exception handler. The file must not exist yet ("x" mode): the trace is 207// Creates the trace file and installs the exception handler. The file must not exist yet ("x" mode): the trace is
184// opened before the loader reads anything, so overwriting would let `--trace` destroy an input, such as the image 208// opened before the loader reads anything, so overwriting would let `--trace` destroy an input, such as the image
185// itself. Returns false if the file exists or cannot be created; `error`, when given, receives the errno. 209// itself. Returns false if the file exists or cannot be created; `error`, when given, receives the errno.
186inline bool open(const wchar_t* path, int* error = nullptr) { 210inline bool open(const wchar_t* path, int* error = nullptr) {
187 { 211 {
188 const std::lock_guard lock(detail::mutex); 212 const std::lock_guard lock(detail::mutex());
189 if (detail::file) return true; 213 if (detail::file) return true;
190 const errno_t e = _wfopen_s(&detail::file, path, L"wxb"); 214 const errno_t e = _wfopen_s(&detail::file, path, L"wxb");
191 if (e != 0 || !detail::file) { 215 if (e != 0 || !detail::file) {
@@ -195,19 +219,21 @@ inline bool open(const wchar_t* path, int* error = nullptr) {
195 } 219 }
196 detail::start = std::chrono::steady_clock::now(); 220 detail::start = std::chrono::steady_clock::now();
197 detail::seq = 0; 221 detail::seq = 0;
222 static const int atexit_registered = std::atexit(&close);
223 (void)atexit_registered;
198 } 224 }
199 detail::on.store(true, std::memory_order_relaxed);
200 detail::veh = AddVectoredExceptionHandler(1, &detail::handler); 225 detail::veh = AddVectoredExceptionHandler(1, &detail::handler);
226 detail::on.store(true, std::memory_order_release);
201 event("trace_open", "\"pid\":" + std::to_string(GetCurrentProcessId())); 227 event("trace_open", "\"pid\":" + std::to_string(GetCurrentProcessId()));
202 return true; 228 return true;
203} 229}
204 230
205// Removes the handler and closes the file (tests; gta6rt keeps the trace open until the process ends). 231// Removes the handler and closes the file (tests and process exit via atexit).
206inline void close() { 232inline void close() {
207 detail::on.store(false, std::memory_order_relaxed); 233 detail::on.store(false, std::memory_order_release);
208 if (detail::veh) RemoveVectoredExceptionHandler(detail::veh); 234 if (detail::veh) RemoveVectoredExceptionHandler(detail::veh);
209 detail::veh = nullptr; 235 detail::veh = nullptr;
210 const std::lock_guard lock(detail::mutex); 236 const std::lock_guard lock(detail::mutex());
211 if (detail::file) std::fclose(detail::file); 237 if (detail::file) std::fclose(detail::file);
212 detail::file = nullptr; 238 detail::file = nullptr;
213} 239}
diff --git a/runtime/shims/winhttp_offline.cpp b/runtime/shims/winhttp_offline.cpp
new file mode 100644
index 000000000..1cd7d961f
--- /dev/null
+++ b/runtime/shims/winhttp_offline.cpp
@@ -0,0 +1,385 @@
1// winhttp_offline: WinHTTP for a mapped title, with no network.
2//
3// The package's XCurl.dll and libHttpClient.GDK.dll do their HTTP through WinHTTP: between them they import 16
4// functions from winhttp.dll and nothing from Winsock (docs/runtime_imports.md, "WinHTTP offline"). Bound to the host's
5// winhttp.dll a mapped title could reach the network, and nothing here goes online. So winhttp.dll is a module the
6// shims own (a LoadLibrary of it gets a pseudo-handle, library_loader.cpp) and every function a title can reach is
7// answered in-process:
8// - WinHttpOpen, WinHttpConnect and WinHttpOpenRequest return local handles. WinHttpConnect resolves no name and
9// opens no socket.
10// - WinHttpSendRequest fails with ERROR_WINHTTP_CANNOT_CONNECT. On a session opened with WINHTTP_FLAG_ASYNC it
11// returns TRUE and reports the failure the way WinHTTP does, through the status callback:
12// WINHTTP_CALLBACK_STATUS_REQUEST_ERROR with WINHTTP_ASYNC_RESULT { API_SEND_REQUEST, ERROR_WINHTTP_CANNOT_CONNECT },
13// from a thread-pool thread, with the context the request was sent with.
14// - Reading a response (WinHttpReceiveResponse, WinHttpQueryHeaders, WinHttpQueryDataAvailable, WinHttpReadData) and
15// WinHttpWriteData fail with ERROR_WINHTTP_INCORRECT_HANDLE_STATE: no request ever got that far.
16// - Options, timeouts and request headers are accepted. WINHTTP_OPTION_CONTEXT_VALUE is kept per handle and
17// WINHTTP_OPTION_HANDLE_TYPE answered; WinHttpQueryOption reports ERROR_WINHTTP_INVALID_OPTION for the rest.
18// - A status callback set on a handle is inherited by the handles created under it, as in WinHTTP.
19// WINHTTP_CALLBACK_STATUS_HANDLE_CREATED is reported when a child handle is made, and
20// WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING once per handle, last, after WinHttpCloseHandle and any callback still
21// running for it.
22// - WinHttpCrackUrl only parses a string, so it is the host's.
23// Each refused server is logged once ("[rt] winhttp: offline, refused <host>:<port>"), which says what a title tried
24// to reach. Only images mapped by the loader see these: they are bound through the registry, the runtime's own code
25// calls the host directly.
26#include <windows.h>
27#include <winhttp.h>
28
29#include <atomic>
30#include <cstdio>
31#include <cstring>
32#include <mutex>
33#include <set>
34#include <string>
35
36#include "shims.h"
37
38namespace rt::winhttp {
39namespace {
40
41enum class Kind { Session, Connect, Request };
42
43struct Handle {
44 Kind kind = Kind::Session;
45 Handle* parent = nullptr; // holds one reference on the parent
46 bool async = false;
47 std::atomic<long> refs{1}; // the handle's own reference, dropped by WinHttpCloseHandle
48 std::atomic<bool> closed{false};
49
50 std::mutex mutex; // guards the three below
51 WINHTTP_STATUS_CALLBACK callback = nullptr;
52 DWORD notifications = 0;
53 DWORD_PTR context = 0;
54
55 std::wstring server; // Connect: for the log
56 INTERNET_PORT port = 0;
57};
58
59// Intentionally immortal: a mapped DLL can close handles from DLL_PROCESS_DETACH, after normal statics are gone.
60std::mutex& live_mutex() {
61 static auto* m = new std::mutex;
62 return *m;
63}
64std::set<Handle*>& live() {
65 static auto* s = new std::set<Handle*>;
66 return *s;
67}
68
69HINTERNET to_hinternet(Handle* h) { return reinterpret_cast<HINTERNET>(h); }
70
71// Takes a reference on a live handle of an accepted kind. On failure `error` says why: ERROR_INVALID_HANDLE for
72// something that is not an open handle, ERROR_WINHTTP_INCORRECT_HANDLE_TYPE for the wrong kind.
73Handle* acquire(HINTERNET handle, bool session, bool connect, bool request, DWORD& error) {
74 Handle* h = reinterpret_cast<Handle*>(handle);
75 std::lock_guard lock(live_mutex());
76 if (!handle || live().count(h) == 0) {
77 error = ERROR_INVALID_HANDLE;
78 return nullptr;
79 }
80 const bool ok = (h->kind == Kind::Session && session) || (h->kind == Kind::Connect && connect) ||
81 (h->kind == Kind::Request && request);
82 if (!ok) {
83 error = ERROR_WINHTTP_INCORRECT_HANDLE_TYPE;
84 return nullptr;
85 }
86 h->refs.fetch_add(1);
87 return h;
88}
89
90void notify(Handle* h, DWORD status, void* info, DWORD length) {
91 WINHTTP_STATUS_CALLBACK callback;
92 DWORD notifications;
93 DWORD_PTR context;
94 {
95 std::lock_guard lock(h->mutex);
96 callback = h->callback;
97 notifications = h->notifications;
98 context = h->context;
99 }
100 // The WINHTTP_CALLBACK_FLAG_* bits are the status values they select.
101 if (callback && callback != WINHTTP_INVALID_STATUS_CALLBACK && (notifications & status) != 0)
102 callback(to_hinternet(h), context, status, info, length);
103}
104
105void release(Handle* h) {
106 while (h && h->refs.fetch_sub(1) == 1) {
107 HINTERNET self = to_hinternet(h);
108 notify(h, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING, &self, sizeof(self));
109 Handle* parent = h->parent;
110 delete h;
111 h = parent; // the child's reference on its parent
112 }
113}
114
115HINTERNET make_handle(Kind kind, Handle* parent, bool async) {
116 auto* h = new (std::nothrow) Handle;
117 if (!h) {
118 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
119 return nullptr;
120 }
121 h->kind = kind;
122 h->parent = parent;
123 h->async = async;
124 if (parent) {
125 // A callback set on a handle is inherited by the handles created under it.
126 std::lock_guard lock(parent->mutex);
127 h->callback = parent->callback;
128 h->notifications = parent->notifications;
129 }
130 {
131 std::lock_guard lock(live_mutex());
132 live().insert(h);
133 }
134 if (parent) {
135 HINTERNET self = to_hinternet(h);
136 notify(h, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED, &self, sizeof(self));
137 }
138 return to_hinternet(h);
139}
140
141std::wstring server_of(const Handle* request) {
142 const Handle* connect = request ? request->parent : nullptr;
143 if (!connect) return L"?";
144 return connect->server + L":" + std::to_wstring(connect->port);
145}
146
147void log_refused(const Handle* request) {
148 static auto* logged = new std::set<std::wstring>;
149 static auto* mutex = new std::mutex;
150 const std::wstring server = server_of(request);
151 std::lock_guard lock(*mutex);
152 if (logged->insert(server).second) std::fwprintf(stderr, L"[rt] winhttp: offline, refused %ls\n", server.c_str());
153}
154
155void CALLBACK send_failed(PTP_CALLBACK_INSTANCE, void* context) {
156 Handle* h = static_cast<Handle*>(context);
157 if (!h->closed.load()) {
158 WINHTTP_ASYNC_RESULT result{};
159 result.dwResult = API_SEND_REQUEST;
160 result.dwError = ERROR_WINHTTP_CANNOT_CONNECT;
161 notify(h, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result));
162 }
163 release(h); // the reference WinHttpSendRequest took for this callback
164}
165
166BOOL fail(DWORD error) {
167 SetLastError(error);
168 return FALSE;
169}
170
171} // namespace
172
173HINTERNET WINAPI open_session(LPCWSTR, DWORD, LPCWSTR, LPCWSTR, DWORD flags) {
174 static std::once_flag once;
175 std::call_once(once, [] {
176 std::fprintf(stderr, "[rt] winhttp: offline; requests fail with ERROR_WINHTTP_CANNOT_CONNECT\n");
177 });
178 return make_handle(Kind::Session, nullptr, (flags & WINHTTP_FLAG_ASYNC) != 0);
179}
180
181HINTERNET WINAPI open_connection(HINTERNET session, LPCWSTR server, INTERNET_PORT port, DWORD) {
182 DWORD error = 0;
183 Handle* s = acquire(session, true, false, false, error);
184 if (!s) {
185 SetLastError(error);
186 return nullptr;
187 }
188 if (!server || !*server) {
189 release(s);
190 SetLastError(ERROR_INVALID_PARAMETER);
191 return nullptr;
192 }
193 const HINTERNET h = make_handle(Kind::Connect, s, s->async); // keeps the reference on the session
194 if (!h) {
195 release(s);
196 return nullptr;
197 }
198 auto* c = reinterpret_cast<Handle*>(h);
199 c->server = server;
200 c->port = port;
201 return h;
202}
203
204HINTERNET WINAPI open_request(HINTERNET connection, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR*, DWORD) {
205 DWORD error = 0;
206 Handle* c = acquire(connection, false, true, false, error);
207 if (!c) {
208 SetLastError(error);
209 return nullptr;
210 }
211 const HINTERNET h = make_handle(Kind::Request, c, c->async); // keeps the reference on the connection
212 if (!h) release(c);
213 return h;
214}
215
216BOOL WINAPI send_request(HINTERNET request, LPCWSTR, DWORD, LPVOID, DWORD, DWORD, DWORD_PTR context) {
217 DWORD error = 0;
218 Handle* r = acquire(request, false, false, true, error);
219 if (!r) return fail(error);
220 {
221 std::lock_guard lock(r->mutex);
222 r->context = context; // the context this request's callbacks carry
223 }
224 log_refused(r);
225 if (!r->async) {
226 release(r);
227 return fail(ERROR_WINHTTP_CANNOT_CONNECT);
228 }
229 // Asynchronous: the failure arrives through the callback, never on the calling thread, as with WinHTTP. The
230 // reference taken above is the callback's and is dropped there.
231 if (!TrySubmitThreadpoolCallback(&send_failed, r, nullptr)) {
232 const DWORD submit_error = GetLastError();
233 release(r);
234 return fail(submit_error ? submit_error : ERROR_NOT_ENOUGH_MEMORY);
235 }
236 SetLastError(ERROR_SUCCESS);
237 return TRUE;
238}
239
240// No request was ever sent, so there is no response to read and nothing to write to.
241BOOL WINAPI receive_response(HINTERNET request, LPVOID) {
242 DWORD error = 0;
243 Handle* r = acquire(request, false, false, true, error);
244 if (!r) return fail(error);
245 release(r);
246 return fail(ERROR_WINHTTP_INCORRECT_HANDLE_STATE);
247}
248
249BOOL WINAPI query_data_available(HINTERNET request, LPDWORD) { return receive_response(request, nullptr); }
250BOOL WINAPI read_data(HINTERNET request, LPVOID, DWORD, LPDWORD) { return receive_response(request, nullptr); }
251BOOL WINAPI write_data(HINTERNET request, LPCVOID, DWORD, LPDWORD) { return receive_response(request, nullptr); }
252BOOL WINAPI query_headers(HINTERNET request, DWORD, LPCWSTR, LPVOID, LPDWORD, LPDWORD) {
253 return receive_response(request, nullptr);
254}
255
256BOOL WINAPI add_request_headers(HINTERNET request, LPCWSTR, DWORD, DWORD) {
257 DWORD error = 0;
258 Handle* r = acquire(request, false, false, true, error);
259 if (!r) return fail(error);
260 release(r);
261 return TRUE;
262}
263
264BOOL WINAPI set_timeouts(HINTERNET handle, int, int, int, int) {
265 DWORD error = 0;
266 Handle* h = acquire(handle, true, true, true, error);
267 if (!h) return fail(error);
268 release(h);
269 return TRUE;
270}
271
272BOOL WINAPI set_option(HINTERNET handle, DWORD option, LPVOID buffer, DWORD length) {
273 if (!handle) return TRUE; // process-wide options: accepted, nothing to apply
274 DWORD error = 0;
275 Handle* h = acquire(handle, true, true, true, error);
276 if (!h) return fail(error);
277 if (option == WINHTTP_OPTION_CONTEXT_VALUE) {
278 if (!buffer || length < sizeof(DWORD_PTR)) {
279 release(h);
280 return fail(ERROR_INVALID_PARAMETER);
281 }
282 std::lock_guard lock(h->mutex);
283 h->context = *static_cast<const DWORD_PTR*>(buffer);
284 }
285 release(h);
286 return TRUE;
287}
288
289BOOL WINAPI query_option(HINTERNET handle, DWORD option, LPVOID buffer, LPDWORD length) {
290 if (!length) return fail(ERROR_INVALID_PARAMETER);
291 DWORD error = 0;
292 Handle* h = acquire(handle, true, true, true, error);
293 if (!h) return fail(error);
294 DWORD_PTR value_ptr = 0;
295 DWORD value_dword = 0;
296 const void* value = nullptr;
297 DWORD size = 0;
298 if (option == WINHTTP_OPTION_CONTEXT_VALUE) {
299 std::lock_guard lock(h->mutex);
300 value_ptr = h->context;
301 value = &value_ptr;
302 size = sizeof(value_ptr);
303 } else if (option == WINHTTP_OPTION_HANDLE_TYPE) {
304 value_dword = h->kind == Kind::Session ? WINHTTP_HANDLE_TYPE_SESSION
305 : h->kind == Kind::Connect ? WINHTTP_HANDLE_TYPE_CONNECT
306 : WINHTTP_HANDLE_TYPE_REQUEST;
307 value = &value_dword;
308 size = sizeof(value_dword);
309 }
310 release(h);
311 if (!value) return fail(ERROR_WINHTTP_INVALID_OPTION);
312 if (!buffer || *length < size) {
313 *length = size;
314 return fail(ERROR_INSUFFICIENT_BUFFER);
315 }
316 std::memcpy(buffer, value, size);
317 *length = size;
318 return TRUE;
319}
320
321WINHTTP_STATUS_CALLBACK WINAPI set_status_callback(HINTERNET handle, WINHTTP_STATUS_CALLBACK callback,
322 DWORD notifications, DWORD_PTR) {
323 DWORD error = 0;
324 Handle* h = acquire(handle, true, true, true, error);
325 if (!h) {
326 SetLastError(error);
327 return WINHTTP_INVALID_STATUS_CALLBACK;
328 }
329 WINHTTP_STATUS_CALLBACK previous;
330 {
331 std::lock_guard lock(h->mutex);
332 previous = h->callback;
333 h->callback = callback;
334 h->notifications = callback ? notifications : 0;
335 }
336 release(h);
337 return previous;
338}
339
340BOOL WINAPI close_handle(HINTERNET handle) {
341 Handle* h = reinterpret_cast<Handle*>(handle);
342 {
343 std::lock_guard lock(live_mutex());
344 if (!handle || live().erase(h) == 0) return fail(ERROR_INVALID_HANDLE);
345 }
346 h->closed.store(true);
347 release(h); // the handle's own reference; HANDLE_CLOSING follows when nothing else holds it
348 return TRUE;
349}
350
351BOOL WINAPI crack_url(LPCWSTR url, DWORD length, DWORD flags, LPURL_COMPONENTS components) {
352 // Parsing only: the host's, loaded on first use so the runtime does not depend on winhttp.dll otherwise.
353 using CrackUrlFn = BOOL(WINAPI*)(LPCWSTR, DWORD, DWORD, LPURL_COMPONENTS);
354 static CrackUrlFn host = [] {
355 const HMODULE m = LoadLibraryExW(L"winhttp.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
356 return m ? reinterpret_cast<CrackUrlFn>(GetProcAddress(m, "WinHttpCrackUrl")) : nullptr;
357 }();
358 if (!host) return fail(ERROR_PROC_NOT_FOUND);
359 return host(url, length, flags, components);
360}
361
362} // namespace rt::winhttp
363
364namespace {
365using namespace rt::winhttp;
366} // namespace
367
368SHIM_TABLE(winhttp_offline,
369 {"winhttp.dll", "WinHttpOpen", reinterpret_cast<void*>(&open_session)},
370 {"winhttp.dll", "WinHttpConnect", reinterpret_cast<void*>(&open_connection)},
371 {"winhttp.dll", "WinHttpOpenRequest", reinterpret_cast<void*>(&open_request)},
372 {"winhttp.dll", "WinHttpSendRequest", reinterpret_cast<void*>(&send_request)},
373 {"winhttp.dll", "WinHttpReceiveResponse", reinterpret_cast<void*>(&receive_response)},
374 {"winhttp.dll", "WinHttpQueryDataAvailable", reinterpret_cast<void*>(&query_data_available)},
375 {"winhttp.dll", "WinHttpReadData", reinterpret_cast<void*>(&read_data)},
376 {"winhttp.dll", "WinHttpWriteData", reinterpret_cast<void*>(&write_data)},
377 {"winhttp.dll", "WinHttpQueryHeaders", reinterpret_cast<void*>(&query_headers)},
378 {"winhttp.dll", "WinHttpAddRequestHeaders", reinterpret_cast<void*>(&add_request_headers)},
379 {"winhttp.dll", "WinHttpSetTimeouts", reinterpret_cast<void*>(&set_timeouts)},
380 {"winhttp.dll", "WinHttpSetOption", reinterpret_cast<void*>(&set_option)},
381 {"winhttp.dll", "WinHttpQueryOption", reinterpret_cast<void*>(&query_option)},
382 {"winhttp.dll", "WinHttpSetStatusCallback", reinterpret_cast<void*>(&set_status_callback)},
383 {"winhttp.dll", "WinHttpCloseHandle", reinterpret_cast<void*>(&close_handle)},
384 {"winhttp.dll", "WinHttpCrackUrl", reinterpret_cast<void*>(&crack_url)},
385);
diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp
index 0190d029c..54c74b959 100644
--- a/runtime/shims/xbox_present.cpp
+++ b/runtime/shims/xbox_present.cpp
@@ -1,5 +1,7 @@
1#include "xbox_present.h" 1#include "xbox_present.h"
2 2
3#include "../src/vulkan_present.h"
4
3#include <cstdio> 5#include <cstdio>
4 6
5namespace rt::d3d12 { 7namespace rt::d3d12 {
@@ -79,6 +81,13 @@ HRESULT XboxPresentation::PresentX(UINT plane_count, const XboxPresentPlaneParam
79 const XboxPresentPlaneParameters& plane = planes[i]; 81 const XboxPresentPlaneParameters& plane = planes[i];
80 if (plane.Token != token || plane.ResourceCount == 0 || !plane.ppResources || !plane.ppResources[0]) 82 if (plane.Token != token || plane.ResourceCount == 0 || !plane.ppResources || !plane.ppResources[0])
81 return E_INVALIDARG; 83 return E_INVALIDARG;
84 // Both paths read ppResources[0] only: a plane with several resources would silently lose the others and could show
85 // the wrong frame, so it is refused (before anything is presented) until it is modelled. What the console does
86 // with ResourceCount above 1 (views? stereo?) is unmeasured.
87 if (plane.ResourceCount != 1) {
88 log_once(logged_resource_count_, "PresentX plane with ResourceCount other than 1: not implemented, refused");
89 return DXGI_ERROR_UNSUPPORTED;
90 }
82 } 91 }
83 // Only a token that was never handed out is refused. Null, stale and repeated tokens are presented anyway (what the 92 // Only a token that was never handed out is refused. Null, stale and repeated tokens are presented anyway (what the
84 // console does with them is unmeasured, and a title that does it must not freeze); each kind is logged once. 93 // console does with them is unmeasured, and a title that does it must not freeze); each kind is logged once.
@@ -99,6 +108,90 @@ HRESULT XboxPresentation::PresentX(UINT plane_count, const XboxPresentPlaneParam
99 break; 108 break;
100 } 109 }
101 110
111 // What each plane asks for. Colour spaces other than HDR10 are composed as the SDR default (logged once).
112 const auto is_hdr10 = [&](const XboxPresentPlaneParameters& p) {
113 if (p.ColorSpace != xbox_color_space_g22_p709 && p.ColorSpace != xbox_color_space_g2084_p2020)
114 log_once(logged_color_space_, "a present plane's DXGI colour space is neither G22/P709 nor G2084/P2020: composed as SDR G22/P709");
115 return p.ColorSpace == xbox_color_space_g2084_p2020;
116 };
117 // The extra fields are unmeasured, so they are read defensively: a placement that is not a sane sub-rectangle of the output
118 // (also NaN) counts as none, an unknown filter as the default, unknown flag bits are ignored, extended descriptors are
119 // not read; each is logged once and the frame is shown anyway (a title must not freeze on a field we misread).
120 const auto placement = [&](const XboxPresentPlaneParameters& p) -> const XboxViewRect* {
121 const XboxViewRect* r = p.pDestPlacementBase;
122 if (!r) return nullptr;
123 if (!(r->left >= 0.0f && r->left < r->right && r->right <= 1.0f && r->top >= 0.0f && r->top < r->bottom &&
124 r->bottom <= 1.0f)) {
125 log_once(logged_extras_, "a present plane's pDestPlacementBase is not a sub-rectangle of 0..1: ignored (whole output)");
126 return nullptr;
127 }
128 return (r->left == 0.0f && r->top == 0.0f && r->right == 1.0f && r->bottom == 1.0f) ? nullptr : r;
129 };
130 const auto filter_of = [&](const XboxPresentPlaneParameters& p) {
131 if (p.ScaleFilter == xbox_scale_filter_point || p.ScaleFilter == xbox_scale_filter_linear) return p.ScaleFilter;
132 if (p.ScaleFilter != xbox_scale_filter_default)
133 log_once(logged_extras_, "a present plane's ScaleFilter is not a known value: default filter");
134 return int(xbox_scale_filter_default);
135 };
136 for (UINT i = 0; i < plane_count; ++i)
137 if (planes[i].ExtendedDescCount)
138 log_once(logged_extras_, "a present plane has extended descriptors: ignored");
139 const bool hdr0 = is_hdr10(planes[0]);
140 // Plane 1 is composed over plane 0 only when flagged an overlay (hypothesis). Otherwise it is not shown, as before: in
141 // the public HDR sample it is the GameDVR copy of the frame, and blending a plane we cannot tell apart from it risks
142 // drawing the frame twice with an alpha that was never meant to be blended.
143 const bool overlay = plane_count == 2 && (planes[1].Flags & xbox_plane_flag_overlay) != 0;
144 if (plane_count == 2 && !overlay)
145 log_once(logged_planes_, "PresentX with 2 planes and no overlay flag on plane 1: only plane 0 is shown (plane 1 is taken "
146 "as the GameDVR copy of the frame)");
147 const bool compose = hdr0 || placement(planes[0]) || filter_of(planes[0]) != xbox_scale_filter_default || overlay;
148
149 if (compose) {
150 // Every shown plane: a 2D texture, a source rectangle inside it, a placement inside the output.
151 leonida::PresentPlanes composed;
152 composed.count = overlay ? 2 : 1;
153 composed.sdr_white_nits = sdr_white_nits_;
154 for (UINT i = 0; i < composed.count; ++i) {
155 const XboxPresentPlaneParameters& p = planes[i];
156 ID3D12Resource* source = p.ppResources[0];
157 const D3D12_RESOURCE_DESC source_desc = source->GetDesc();
158 if (source_desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return E_INVALIDARG;
159 const D3D12_RECT* source_rect = p.pSrcViewRects;
160 if (source_rect && (source_rect->left < 0 || source_rect->top < 0 || source_rect->left >= source_rect->right ||
161 source_rect->top >= source_rect->bottom || UINT64(source_rect->right) > source_desc.Width ||
162 UINT(source_rect->bottom) > source_desc.Height))
163 return E_INVALIDARG;
164 const XboxViewRect* place = placement(p);
165 leonida::PresentPlane& out = composed.plane[i];
166 out.source = resource_id(source);
167 if (source_rect) {
168 out.source_rect = {source_rect->left, source_rect->top, source_rect->right, source_rect->bottom};
169 out.has_source_rect = true;
170 }
171 if (place) {
172 out.dest[0] = place->left;
173 out.dest[1] = place->top;
174 out.dest[2] = place->right;
175 out.dest[3] = place->bottom;
176 }
177 out.point_filter = filter_of(p) == xbox_scale_filter_point;
178 out.hdr10 = is_hdr10(p);
179 out.straight_alpha = (p.Flags & xbox_plane_flag_straight_alpha) != 0;
180 }
181 bool tear = false;
182 if (wants_tear && sync_interval > 0 && presenter_->tear_supported()) {
183 const FramePacer::PresentTiming timing = pacer_.present_timing(token);
184 tear = leonida::decide_present_sync(timing.late_us, timing.period_us, threshold) == leonida::PresentSync::immediate;
185 }
186 const HRESULT result = presenter_->present_planes(composed, sync_interval, tear);
187 if (FAILED(result)) return pacer_.suspended() ? from_pacer(hr::invalid_state) : result;
188 pacer_.commit_present_token(token, plane_count,
189 tear && presenter_->last_present_tore() ? leonida::PresentSync::immediate
190 : leonida::PresentSync::vblank);
191 ++presents_;
192 return S_OK;
193 }
194
102 const XboxPresentPlaneParameters& plane = planes[0]; 195 const XboxPresentPlaneParameters& plane = planes[0];
103 ID3D12Resource* resource = plane.ppResources[0]; 196 ID3D12Resource* resource = plane.ppResources[0];
104 const D3D12_RESOURCE_DESC desc = resource->GetDesc(); 197 const D3D12_RESOURCE_DESC desc = resource->GetDesc();
@@ -113,9 +206,6 @@ HRESULT XboxPresentation::PresentX(UINT plane_count, const XboxPresentPlaneParam
113 UINT64(rect->right) > desc.Width || UINT(rect->bottom) > desc.Height)) 206 UINT64(rect->right) > desc.Width || UINT(rect->bottom) > desc.Height))
114 return E_INVALIDARG; 207 return E_INVALIDARG;
115 208
116 if (plane_count == 2)
117 log_once(logged_planes_, "PresentX with 2 planes: only plane 0 is shown; HDR/GameDVR plane composition is not implemented");
118
119 // How late the frame is, now that everything that can refuse it has: past the vblank it was due at, by what part of 209 // How late the frame is, now that everything that can refuse it has: past the vblank it was due at, by what part of
120 // the interval the scan has moved on. The presenter says whether it really queued it as a tear. 210 // the interval the scan has moved on. The presenter says whether it really queued it as a tear.
121 FramePacer::PresentTiming timing; 211 FramePacer::PresentTiming timing;
diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h
index 971fa1a6e..8d141f4a7 100644
--- a/runtime/shims/xbox_present.h
+++ b/runtime/shims/xbox_present.h
@@ -37,12 +37,42 @@ inline constexpr std::uint32_t xbox_frame_interval_120hz_us = 8333;
37 37
38// Provisional (ours): D3D12XBOX_PRESENT_PLANE_PARAMETERS. The names are those the samples use; the layout, the 38// Provisional (ours): D3D12XBOX_PRESENT_PLANE_PARAMETERS. The names are those the samples use; the layout, the
39// token width (64 bits here) and the fields the console has beyond these are unmeasured. 39// token width (64 bits here) and the fields the console has beyond these are unmeasured.
40//
41// The fields after pSrcViewRects exist in the console's struct (names and order seen in a public binding, see the struct)
42// but their types, enum values and flag bits are unmeasured: the values of ours below are placeholders that make the
43// composition (section 4.5) testable. Zero everything is the default and means "as before": the whole output,
44// bilinear when scaling, SDR, plane 1 premultiplied and not composed.
45struct XboxViewRect { // D3D12XBOX_VIEW_RECT: four floats; as fractions 0..1 of the output (hypothesis, section 4.5)
46 float left, top, right, bottom;
47};
48// DXGI_COLOR_SPACE_TYPE values (documented DXGI numbers). Only these two are composed; any other is treated as the first.
49inline constexpr int xbox_color_space_g22_p709 = 0; // DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709: SDR
50inline constexpr int xbox_color_space_g2084_p2020 = 12; // DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020: HDR10
51// Provisional (ours): ScaleFilter and Flags.
52inline constexpr int xbox_scale_filter_default = 0; // bilinear (point when not scaled makes no difference)
53inline constexpr int xbox_scale_filter_point = 1;
54inline constexpr int xbox_scale_filter_linear = 2;
55// Plane 1 is composed over plane 0 as an overlay only with this flag (hypothesis: whether the console blends a second plane
56// at all is unmeasured; the public HDR sample's plane 1 is the GameDVR copy of the frame, not shown, so without the flag
57// plane 1 is not composed, as before).
58inline constexpr UINT xbox_plane_flag_overlay = 1;
59inline constexpr UINT xbox_plane_flag_straight_alpha = 2; // plane 1's colour is not premultiplied by its alpha
60
40struct XboxPresentPlaneParameters { 61struct XboxPresentPlaneParameters {
62 // Field ORDER and names: the public Go binding of the GDK header in hajimehoshi/ebiten (Apache-2.0,
63 // internal/graphicsdriver/directx/d3d12_windows.go, _D3D12XBOX_PRESENT_PLANE_PARAMETERS); the HDR10 sample confirms
64 // the first four and ColorSpace. Types, padding and the console's real sizes are unmeasured (ours: 64-bit token, int
65 // enums), so nothing here is the console's ABI.
41 std::uint64_t Token; // from WaitFrameEventX 66 std::uint64_t Token; // from WaitFrameEventX
42 UINT ResourceCount; // 1 in the samples 67 UINT ResourceCount; // 1 in the samples
43 ID3D12Resource* const* ppResources; // ResourceCount committed resources with ALLOW_DISPLAY, in PRESENT 68 ID3D12Resource* const* ppResources; // ResourceCount committed resources with ALLOW_DISPLAY, in PRESENT
44 const D3D12_RECT* pSrcViewRects; // null, or one rectangle per resource (the HDR sample sets it) 69 const D3D12_RECT* pSrcViewRects; // null, or one rectangle per resource (the HDR sample sets it)
45 int ColorSpace; // a DXGI_COLOR_SPACE_TYPE; not used yet 70 const XboxViewRect* pDestPlacementBase; // null: the whole output
71 int ColorSpace; // a DXGI_COLOR_SPACE_TYPE (see above)
72 int ScaleFilter; // xbox_scale_filter_*; anything unknown is the default
73 UINT ExtendedDescCount; // not used (logged once when non-zero)
74 const void* pExtendedDescs;
75 UINT Flags; // xbox_plane_flag_*; unknown bits are ignored
46}; 76};
47 77
48// Provisional (ours): D3D12XBOX_PRESENT_PARAMETERS. The samples show at least this field. 78// Provisional (ours): D3D12XBOX_PRESENT_PARAMETERS. The samples show at least this field.
@@ -81,10 +111,18 @@ public:
81 // 0 planes: a black frame (what a title does before it releases its resources); no token is looked at. 111 // 0 planes: a black frame (what a title does before it releases its resources); no token is looked at.
82 // 1 plane: plane 0's first resource, which must be a single-sample 2D colour texture in the PRESENT state, 112 // 1 plane: plane 0's first resource, which must be a single-sample 2D colour texture in the PRESENT state,
83 // is blitted to the window (format conversion by the blit; an sRGB format gets an sRGB swapchain), 113 // is blitted to the window (format conversion by the blit; an sRGB format gets an sRGB swapchain),
84 // limited to pSrcViewRects[0] when that is set. 114 // limited to pSrcViewRects[0] when that is set. This is the whole behaviour while the plane asks for
85 // 2 planes: the two share one token; plane 0 is presented and plane 1 (the GameDVR/SDR copy) is dropped; the 115 // nothing else (SDR colour space, whole output, default filter).
86 // missing composition (HDR, GameDVR) is logged once. 116 // Composed: a plane with pDestPlacementBase, a point or linear ScaleFilter, or the HDR10 colour space (and any
117 // second plane that is an overlay) is composed by a compute pass (VulkanPresenter::present_planes): plane 0
118 // from its source rectangle to its destination placement, plane 1 alpha-blended over it, colour spaces
119 // converted to the swapchain's (HDR10 when the surface has it, else HDR10 is clipped to SDR). Needs sampled,
120 // single-sample, non-integer sources; others give DXGI_ERROR_UNSUPPORTED.
121 // 2 planes: the two share one token. Plane 1 is composed over plane 0 only when xbox_plane_flag_overlay is set on it
122 // (hypothesis); otherwise it is not shown (the GameDVR copy of the public HDR sample), logged once.
123 // Placement, ScaleFilter and Flags values that are not plausible are ignored and logged once, not refused.
87 // More than 2: E_INVALIDARG (the UMD limit, section 4.5). 124 // More than 2: E_INVALIDARG (the UMD limit, section 4.5).
125 // ResourceCount above 1 on any plane: DXGI_ERROR_UNSUPPORTED (logged once), nothing presented; only resource 0 is read.
88 // Token: the one from WaitFrameEventX. Real behaviour for a null, repeated or out-of-order token is unmeasured and a 126 // Token: the one from WaitFrameEventX. Real behaviour for a null, repeated or out-of-order token is unmeasured and a
89 // title must not freeze on it, so those are presented anyway and logged once per kind; only a token that was never 127 // title must not freeze on it, so those are presented anyway and logged once per kind; only a token that was never
90 // handed out gives E_INVALIDARG (nothing presented). Skipping a token is fine. Sources the GPU cannot blit 128 // handed out gives E_INVALIDARG (nothing presented). Skipping a token is fine. Sources the GPU cannot blit
@@ -99,6 +137,10 @@ public:
99 HRESULT SuspendX(UINT flags); 137 HRESULT SuspendX(UINT flags);
100 HRESULT ResumeX(); 138 HRESULT ResumeX();
101 139
140 // What SDR white is in nits when SDR and HDR10 planes meet (default 203, ITU-R BT.2408's reference white; hypothesis:
141 // the console's value is a user setting). Applies to the next PresentX.
142 void set_sdr_white_nits(float nits) { sdr_white_nits_ = nits > 0.0f ? nits : 203.0f; }
143
102 leonida::FramePacer& pacer() { return pacer_; } 144 leonida::FramePacer& pacer() { return pacer_; }
103 WindowPresenter& presenter() { return *presenter_; } 145 WindowPresenter& presenter() { return *presenter_; }
104 std::uint64_t presents() const { return presents_; } 146 std::uint64_t presents() const { return presents_; }
@@ -111,7 +153,9 @@ private:
111 leonida::FramePacer pacer_; 153 leonida::FramePacer pacer_;
112 std::mutex present_mutex_; // PresentX, SuspendX and ResumeX one at a time 154 std::mutex present_mutex_; // PresentX, SuspendX and ResumeX one at a time
113 std::atomic<std::uint64_t> presents_{0}; 155 std::atomic<std::uint64_t> presents_{0};
114 bool logged_planes_ = false, logged_threshold_ = false, logged_display_ = false; 156 bool logged_planes_ = false, logged_threshold_ = false, logged_display_ = false, logged_color_space_ = false,
157 logged_extras_ = false, logged_resource_count_ = false;
158 float sdr_white_nits_ = 203.0f;
115 bool logged_null_token_ = false, logged_stale_token_ = false, logged_repeated_token_ = false; 159 bool logged_null_token_ = false, logged_stale_token_ = false, logged_repeated_token_ = false;
116}; 160};
117 161
diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp
index 032ca1f4f..7f3599558 100644
--- a/runtime/shims/xgameruntime.cpp
+++ b/runtime/shims/xgameruntime.cpp
@@ -17,6 +17,9 @@
17#include <cstdlib> 17#include <cstdlib>
18#include <cstring> 18#include <cstring>
19#include <iterator> 19#include <iterator>
20#include <mutex>
21#include <string>
22#include <unordered_map>
20 23
21#include <XAsync.h> 24#include <XAsync.h>
22#include <XAsyncProvider.h> 25#include <XAsyncProvider.h>
@@ -36,9 +39,10 @@ std::atomic<int> g_runtime_refs{0};
36// "xgameruntime.dll" and GetProcAddress these five names (measured in the package's libHttpClient.GDK.dll and 39// "xgameruntime.dll" and GetProcAddress these five names (measured in the package's libHttpClient.GDK.dll and
37// XCurl.dll, docs/runtime_imports.md). Signatures, the options struct and the error for an unknown class follow 40// XCurl.dll, docs/runtime_imports.md). Signatures, the options struct and the error for an unknown class follow
38// xodus-gaming/xgameruntime-docs (GPL-3.0; facts only, nothing copied): InitializeApiImplEx2 is the one 41// xodus-gaming/xgameruntime-docs (GPL-3.0; facts only, nothing copied): InitializeApiImplEx2 is the one
39// XGameRuntimeInitialize[WithOptions] calls, and QueryApiImpl hands out the runtime's COM classes. XThreadingImpl and 42// XGameRuntimeInitialize[WithOptions] calls, and QueryApiImpl hands out the runtime's COM classes. XThreadingImpl,
40// XErrorImpl are served (their layouts are measured, below); for any other class QueryApiImpl logs the class and 43// XErrorImpl and XNetworkingImpl are served (their layouts are measured, below); for any other class QueryApiImpl
41// interface id and refuses it, so the first boot with the executable lists the interfaces to implement next. 44// logs the class and interface id and refuses it, so the first boot with the executable lists the interfaces to
45// implement next.
42 46
43struct ApiImplOptions { // InitializeApiImplEx2's fourth argument 47struct ApiImplOptions { // InitializeApiImplEx2's fourth argument
44 uint32_t unknown; // documented as always 1 48 uint32_t unknown; // documented as always 1
@@ -100,7 +104,6 @@ void print_guid(char (&out)[40], const GUID* g) {
100 104
101constexpr GUID kThreadingClass = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}}; 105constexpr GUID kThreadingClass = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}};
102constexpr GUID kErrorClass = {0x8ca467f7, 0x22e8, 0x4096, {0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8}}; 106constexpr GUID kErrorClass = {0x8ca467f7, 0x22e8, 0x4096, {0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8}};
103constexpr GUID kNetworkingClass = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}};
104 107
105// A function's arguments after `this`, forwarded unchanged (x64 has one calling convention). 108// A function's arguments after `this`, forwarded unchanged (x64 has one calling convention).
106// Specialised on the function's exact type, so a noexcept function matches only one form. 109// Specialised on the function's exact type, so a noexcept function matches only one form.
@@ -117,14 +120,18 @@ constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00,
117// The runtime's objects are process-wide singletons: AddRef/Release count but never free. 120// The runtime's objects are process-wide singletons: AddRef/Release count but never free.
118struct RuntimeObject { 121struct RuntimeObject {
119 const void* const* vtable; 122 const void* const* vtable;
120 const GUID* class_id; 123 const GUID* class_id; // the coclass id
124 const GUID* const* interface_ids; // every interface the vtable serves, base first, null-terminated: a derived
125 // interface answers for each one it inherits (IXSystemImpl5 : ... : IXSystemImpl)
121 std::atomic<long> refs{1}; 126 std::atomic<long> refs{1};
122}; 127};
123 128
124HRESULT STDMETHODCALLTYPE object_query_interface(void* self, REFIID iid, void** out) { 129HRESULT STDMETHODCALLTYPE object_query_interface(void* self, REFIID iid, void** out) {
125 if (!out) return E_POINTER; 130 if (!out) return E_POINTER;
126 auto* o = static_cast<RuntimeObject*>(self); 131 auto* o = static_cast<RuntimeObject*>(self);
127 if (iid == kIUnknown || iid == *o->class_id) { 132 bool known = iid == kIUnknown || iid == *o->class_id;
133 for (const GUID* const* i = o->interface_ids; !known && i && *i; ++i) known = iid == **i;
134 if (known) {
128 o->refs.fetch_add(1); 135 o->refs.fetch_add(1);
129 *out = self; 136 *out = self;
130 return S_OK; 137 return S_OK;
@@ -200,18 +207,21 @@ using XErrorCallback = bool(CALLBACK*)(HRESULT hr, const char* message, void* co
200std::atomic<XErrorCallback> g_error_callback{nullptr}; 207std::atomic<XErrorCallback> g_error_callback{nullptr};
201std::atomic<void*> g_error_context{nullptr}; 208std::atomic<void*> g_error_context{nullptr};
202 209
203void STDMETHODCALLTYPE error_report(void*, HRESULT hr, const char* message) { 210// HRESULT XErrorReport(HRESULT, const char*) (xgameruntime-docs' XErrorReport.md): S_OK once reported.
211HRESULT STDMETHODCALLTYPE error_report(void*, HRESULT hr, const char* message) {
204 static std::atomic<int> s_logged{0}; 212 static std::atomic<int> s_logged{0};
205 if (s_logged.fetch_add(1) < 64) 213 if (s_logged.fetch_add(1) < 64)
206 std::fprintf(stderr, "[rt] xgameruntime: XErrorReport(0x%08lx, %s)\n", static_cast<unsigned long>(hr), 214 std::fprintf(stderr, "[rt] xgameruntime: XErrorReport(0x%08lx, %s)\n", static_cast<unsigned long>(hr),
207 message ? message : "(null)"); 215 message ? message : "(null)");
208 if (XErrorCallback cb = g_error_callback.load()) cb(hr, message, g_error_context.load()); 216 if (XErrorCallback cb = g_error_callback.load()) cb(hr, message, g_error_context.load());
217 return S_OK;
209} 218}
210void STDMETHODCALLTYPE error_set_callback(void*, XErrorCallback callback, void* context) { 219void STDMETHODCALLTYPE error_set_callback(void*, XErrorCallback callback, void* context) {
211 g_error_context = context; 220 g_error_context = context;
212 g_error_callback = callback; 221 g_error_callback = callback;
213} 222}
214HRESULT STDMETHODCALLTYPE error_set_options(void*, uint32_t, uint32_t) { return S_OK; } 223// void XErrorSetOptions(XErrorOptions, XErrorOptions), as Microsoft documents it: nothing to configure offline.
224void STDMETHODCALLTYPE error_set_options(void*, uint32_t, uint32_t) {}
215 225
216const void* const kErrorVtable[] = { 226const void* const kErrorVtable[] = {
217 reinterpret_cast<const void*>(&object_query_interface), reinterpret_cast<const void*>(&object_add_ref), 227 reinterpret_cast<const void*>(&object_query_interface), reinterpret_cast<const void*>(&object_add_ref),
@@ -221,130 +231,120 @@ const void* const kErrorVtable[] = {
221 reinterpret_cast<const void*>(&error_set_options), // 5 231 reinterpret_cast<const void*>(&error_set_options), // 5
222}; 232};
223 233
224// IXNetworkingImpl2: 18 methods (slots 3-20). XCurl.dll calls slots 11-17 (docs/runtime_imports.md): 234// ---- XNetworkingImpl (IXNetworkingImpl, IXNetworkingImpl2), offline ----
225// the UTF-16 XNetworkingQuerySecurityInformationForUrl* trio, XNetworkingVerifyServerCertificate, 235//
226// XNetworkingGetConnectivityHint, XNetworkingRegisterConnectivityHintChanged and 236// XCurl.dll asks for the class with IXNetworkingImpl2's interface id and calls slots 11-17 (docs/runtime_imports.md,
227// XNetworkingUnregisterConnectivityHintChanged. Offline, connectivity hints report an initialized 237// "Class layouts, measured"): the UTF-16 security-information query for a URL, the server certificate check, the
228// network with unrestricted internet access, certificate verification succeeds, and registered callbacks 238// connectivity hint and its change registration. Signatures follow Microsoft's public XNetworking documentation.
229// are tracked safely. 239// Offline there is no network: the hint says so (initialized, no connectivity), every query that would need the
230enum class XNetworkingConnectivityLevelHint : uint32_t { 240// network fails with kNoNetwork (asynchronously, through XAsync, for the *Async calls), change registrations hand
231 Unknown = 0, 241// out tokens whose callbacks never fire, and the IXNetworkingImpl2 additions are E_NOTIMPL.
232 None = 1,
233 LocalAccess = 2,
234 InternetAccess = 3,
235 ConstrainedInternetAccess = 4,
236};
237
238enum class XNetworkingConnectivityCostHint : uint32_t {
239 Unknown = 0,
240 Unrestricted = 1,
241 Fixed = 2,
242 Variable = 3,
243};
244 242
245struct XNetworkingConnectivityHint { 243constexpr GUID kNetworkingClass = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}};
246 XNetworkingConnectivityLevelHint connectivityLevelHint; 244constexpr GUID kNetworking2 = {0xbf2346b2, 0x39af, 0x4658, {0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3}};
247 XNetworkingConnectivityCostHint connectivityCostHint; 245constexpr HRESULT kNoNetwork = HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE);
248 uint32_t ianaInterfaceType; 246
249 bool networkInitialized; 247// XNetworkingConnectivityHint: level, cost, IANA interface type (u32 each), then four bools.
250 bool approachingDataLimit; 248struct ConnectivityHint {
251 bool overDataLimit; 249 uint32_t connectivity_level; // XNetworkingConnectivityLevelHint: Unknown 0, None 1, LocalAccess 2, Internet 3
250 uint32_t connectivity_cost; // XNetworkingConnectivityCostHint: Unknown 0, Unrestricted 1, Fixed 2, Variable 3
251 uint32_t iana_interface_type;
252 bool network_initialized;
253 bool approaching_data_limit;
254 bool over_data_limit;
252 bool roaming; 255 bool roaming;
253}; 256};
257static_assert(sizeof(ConnectivityHint) == 16, "XNetworkingConnectivityHint is 16 bytes");
254 258
255using XNetworkingConnectivityHintChangedCallback = void(CALLBACK*)(void* context, const XNetworkingConnectivityHint* hint); 259HRESULT STDMETHODCALLTYPE net_query_port(void*, uint16_t* port) {
256 260 if (!port) return E_POINTER;
257template <int Slot> uint64_t STDMETHODCALLTYPE networking_slot(void*) { 261 *port = 0;
258 static std::atomic<bool> s_logged{false}; 262 return kNoNetwork;
259 if (!s_logged.exchange(true))
260 std::fprintf(stderr, "[rt] xgameruntime: XNetworkingImpl slot %d called; answering 0\n", Slot);
261 return 0;
262} 263}
263 264// Completes `async` with kNoNetwork on its queue, as the GDK does for a query that fails.
264// Slot 11: XNetworkingQuerySecurityInformationForUrlUtf16Async(const wchar_t* url, XAsyncBlock* async) 265HRESULT start_failed_async(XAsyncBlock* async) {
265HRESULT STDMETHODCALLTYPE networking_query_security_info_async(void*, const wchar_t*, XAsyncBlock* async) { 266 if (!async) return E_POINTER;
266 if (async) XAsyncComplete(async, S_OK, 0); 267 return XAsyncRun(async, [](XAsyncBlock*) -> HRESULT { return kNoNetwork; });
267 return S_OK;
268} 268}
269 269HRESULT STDMETHODCALLTYPE net_query_port_async(void*, XAsyncBlock* async) { return start_failed_async(async); }
270// Slot 12: XNetworkingQuerySecurityInformationForUrlUtf16AsyncResultSize(XAsyncBlock* async, size_t* size) 270HRESULT STDMETHODCALLTYPE net_query_port_result(void*, XAsyncBlock* async, uint16_t* port) {
271HRESULT STDMETHODCALLTYPE networking_query_security_info_size(void*, XAsyncBlock*, size_t* size) { 271 if (!async || !port) return E_POINTER;
272 if (size) *size = 0; 272 *port = 0;
273 return XAsyncGetStatus(async, false);
274}
275std::atomic<uint64_t> g_net_tokens{0};
276HRESULT STDMETHODCALLTYPE net_register(void*, XTaskQueueHandle, void*, void*, XTaskQueueRegistrationToken* token) {
277 if (!token) return E_POINTER;
278 token->token = g_net_tokens.fetch_add(1) + 1; // never fires offline: nothing changes
273 return S_OK; 279 return S_OK;
274} 280}
275 281bool STDMETHODCALLTYPE net_unregister(void*, XTaskQueueRegistrationToken, bool) { return true; }
276// Slot 13: XNetworkingQuerySecurityInformationForUrlUtf16AsyncResult(XAsyncBlock*, size_t, size_t*, uint8_t*, void**) 282HRESULT STDMETHODCALLTYPE net_security_async(void*, const void* url, XAsyncBlock* async) {
277HRESULT STDMETHODCALLTYPE networking_query_security_info_result(void*, XAsyncBlock*, size_t, size_t* used, uint8_t*, void** info) { 283 if (!url) return E_INVALIDARG;
284 return start_failed_async(async);
285}
286HRESULT STDMETHODCALLTYPE net_security_result_size(void*, XAsyncBlock* async, size_t* size) {
287 if (!async || !size) return E_POINTER;
288 *size = 0;
289 return XAsyncGetStatus(async, false);
290}
291// XNetworkingQuerySecurityInformationForUrl[Utf16]AsyncResult(XAsyncBlock*, size_t bufferByteCount,
292// size_t* bufferByteCountUsed, uint8_t* buffer, XNetworkingSecurityInformation** securityInformation), in the order
293// of Microsoft's reference pages. The buffer itself is never written: there is no result to copy offline.
294HRESULT STDMETHODCALLTYPE net_security_result(void*, XAsyncBlock* async, size_t, size_t* used, uint8_t*, void** info) {
295 if (!async) return E_POINTER;
278 if (used) *used = 0; 296 if (used) *used = 0;
279 if (info) *info = nullptr; 297 if (info) *info = nullptr;
280 return S_OK; 298 return XAsyncGetStatus(async, false);
281}
282
283// Slot 14: XNetworkingVerifyServerCertificate(void* requestHandle, const void* securityInformation)
284HRESULT STDMETHODCALLTYPE networking_verify_server_cert(void*, void*, const void*) {
285 return S_OK;
286} 299}
287 300HRESULT STDMETHODCALLTYPE net_verify_certificate(void*, void*, const void*) { return kNoNetwork; }
288// Slot 15: XNetworkingGetConnectivityHint(XNetworkingConnectivityHint* hint) 301HRESULT STDMETHODCALLTYPE net_connectivity_hint(void*, ConnectivityHint* hint) {
289HRESULT STDMETHODCALLTYPE networking_get_connectivity_hint(void*, XNetworkingConnectivityHint* hint) {
290 if (!hint) return E_POINTER; 302 if (!hint) return E_POINTER;
291 hint->connectivityLevelHint = XNetworkingConnectivityLevelHint::InternetAccess; 303 *hint = {};
292 hint->connectivityCostHint = XNetworkingConnectivityCostHint::Unrestricted; 304 hint->connectivity_level = 1; // None: the stack is up, nothing is reachable
293 hint->ianaInterfaceType = 6; // MIB_IF_TYPE_ETHERNET 305 hint->network_initialized = true;
294 hint->networkInitialized = true;
295 hint->approachingDataLimit = false;
296 hint->overDataLimit = false;
297 hint->roaming = false;
298 return S_OK;
299}
300
301// Slot 16: XNetworkingRegisterConnectivityHintChanged(XTaskQueueHandle, void*, Callback, XTaskQueueRegistrationToken*)
302std::atomic<uint64_t> g_next_network_token{1};
303HRESULT STDMETHODCALLTYPE networking_register_connectivity_hint_changed(void*, XTaskQueueHandle, void*,
304 XNetworkingConnectivityHintChangedCallback,
305 XTaskQueueRegistrationToken* token) {
306 if (token) token->token = g_next_network_token.fetch_add(1);
307 return S_OK; 306 return S_OK;
308} 307}
308HRESULT STDMETHODCALLTYPE net_not_implemented(void*) { return E_NOTIMPL; }
309 309
310// Slot 17: XNetworkingUnregisterConnectivityHintChanged(XTaskQueueRegistrationToken token, bool wait) 310#define NM(fn) reinterpret_cast<const void*>(&fn)
311bool STDMETHODCALLTYPE networking_unregister_connectivity_hint_changed(void*, XTaskQueueRegistrationToken, bool) {
312 return true;
313}
314
315const void* const kNetworkingVtable[] = { 311const void* const kNetworkingVtable[] = {
316 reinterpret_cast<const void*>(&object_query_interface), 312 NM(object_query_interface), NM(object_add_ref), NM(object_release),
317 reinterpret_cast<const void*>(&object_add_ref), 313 NM(net_query_port), // 3 XNetworkingQueryPreferredLocalUdpMultiplayerPort
318 reinterpret_cast<const void*>(&object_release), 314 NM(net_query_port_async), // 4 ...Async
319 reinterpret_cast<const void*>(&networking_slot<3>), // 3 315 NM(net_query_port_result), // 5 ...AsyncResult
320 reinterpret_cast<const void*>(&networking_slot<4>), // 4 316 NM(net_register), // 6 XNetworkingRegisterPreferredLocalUdpMultiplayerPortChanged
321 reinterpret_cast<const void*>(&networking_slot<5>), // 5 317 NM(net_unregister), // 7 XNetworkingUnregisterPreferredLocalUdpMultiplayerPortChanged
322 reinterpret_cast<const void*>(&networking_slot<6>), // 6 318 NM(net_security_async), // 8 XNetworkingQuerySecurityInformationForUrlAsync
323 reinterpret_cast<const void*>(&networking_slot<7>), // 7 319 NM(net_security_result_size), // 9 ...AsyncResultSize
324 reinterpret_cast<const void*>(&networking_slot<8>), // 8 320 NM(net_security_result), // 10 ...AsyncResult
325 reinterpret_cast<const void*>(&networking_slot<9>), // 9 321 NM(net_security_async), // 11 XNetworkingQuerySecurityInformationForUrlUtf16Async (XCurl)
326 reinterpret_cast<const void*>(&networking_slot<10>), // 10 322 NM(net_security_result_size), // 12 ...Utf16AsyncResultSize (XCurl)
327 reinterpret_cast<const void*>(&networking_query_security_info_async), // 11 323 NM(net_security_result), // 13 ...Utf16AsyncResult (XCurl)
328 reinterpret_cast<const void*>(&networking_query_security_info_size), // 12 324 NM(net_verify_certificate), // 14 XNetworkingVerifyServerCertificate (XCurl)
329 reinterpret_cast<const void*>(&networking_query_security_info_result), // 13 325 NM(net_connectivity_hint), // 15 XNetworkingGetConnectivityHint (XCurl)
330 reinterpret_cast<const void*>(&networking_verify_server_cert), // 14 326 NM(net_register), // 16 XNetworkingRegisterConnectivityHintChanged (XCurl)
331 reinterpret_cast<const void*>(&networking_get_connectivity_hint), // 15 327 NM(net_unregister), // 17 XNetworkingUnregisterConnectivityHintChanged (XCurl)
332 reinterpret_cast<const void*>(&networking_register_connectivity_hint_changed), // 16 328 NM(net_not_implemented), // 18 XNetworkingQueryConfigurationSetting (IXNetworkingImpl2)
333 reinterpret_cast<const void*>(&networking_unregister_connectivity_hint_changed), // 17 329 NM(net_not_implemented), // 19 XNetworkingSetConfigurationSetting
334 reinterpret_cast<const void*>(&networking_slot<18>), // 18 330 NM(net_not_implemented), // 20 XNetworkingQueryStatistics
335 reinterpret_cast<const void*>(&networking_slot<19>), // 19
336 reinterpret_cast<const void*>(&networking_slot<20>), // 20
337}; 331};
338static_assert(std::size(kNetworkingVtable) == 21, "IUnknown + IXNetworkingImpl2's 18 methods"); 332#undef NM
333static_assert(std::size(kNetworkingVtable) == 21, "IUnknown + IXNetworkingImpl's 15 + IXNetworkingImpl2's 3");
339 334
340RuntimeObject g_threading{kThreadingVtable, &kThreadingClass}; 335// The ids xgameruntime-docs and the xgameruntime IDL give: XThreadingImpl's and XErrorImpl's class id is also their
341RuntimeObject g_error{kErrorVtable, &kErrorClass}; 336// one interface's; IXNetworkingImpl's id is the class id, and IXNetworkingImpl2 derives from it.
342RuntimeObject g_networking{kNetworkingVtable, &kNetworkingClass}; 337const GUID* const kNetworkingIids[] = {&kNetworking2, nullptr};
338RuntimeObject g_threading{kThreadingVtable, &kThreadingClass, nullptr};
339RuntimeObject g_error{kErrorVtable, &kErrorClass, nullptr};
340RuntimeObject g_networking{kNetworkingVtable, &kNetworkingClass, kNetworkingIids};
341
342RuntimeObject& system_object(); // XSystemImpl, defined after the XSystem functions it serves
343 343
344HRESULT WINAPI QueryApiImpl(const GUID* class_id, REFIID interface_id, void** out) { 344HRESULT WINAPI QueryApiImpl(const GUID* class_id, REFIID interface_id, void** out) {
345 if (out) *out = nullptr; 345 if (out) *out = nullptr;
346 if (class_id && out) { 346 if (class_id && out) {
347 for (RuntimeObject* o : {&g_threading, &g_error, &g_networking}) 347 for (RuntimeObject* o : {&g_threading, &g_error, &g_networking, &system_object()})
348 if (*class_id == *o->class_id) return object_query_interface(o, interface_id, out); 348 if (*class_id == *o->class_id) return object_query_interface(o, interface_id, out);
349 } 349 }
350 char cls[40], iid[40]; 350 char cls[40], iid[40];
@@ -356,6 +356,19 @@ HRESULT WINAPI QueryApiImpl(const GUID* class_id, REFIID interface_id, void** ou
356 return kClassNotProvided; 356 return kClassNotProvided;
357} 357}
358 358
359// gameplatformservices.dll: XCurl.dll's other way into the runtime (docs/runtime_imports.md). It reads
360// HKLM\Microsoft\GamingServices ServiceRetryTimeout, LoadLibraryExW's this module from System32, calls
361// GetApiVersionImpl through the CFG dispatch with two pointers to 64-bit locals (the result unread), compares them
362// with the pair it saw last and keeps them, and then GetProcAddress'es QueryApiImpl. Served by the shims, so that call
363// never reaches a PC's Gaming Services runtime (which would bypass these offline classes, and could go online) and
364// never fails because the PC has none. The two values only have to be stable: the offline runtime has one version.
365constexpr uint64_t kOfflineApiVersion = 1;
366HRESULT WINAPI GetApiVersionImpl(uint64_t* first, uint64_t* second) {
367 if (first) *first = kOfflineApiVersion;
368 if (second) *second = kOfflineApiVersion;
369 return S_OK;
370}
371
359// HRESULT XGameRuntimeInitialize(). Reference counted, as in the GDK: each call needs an XGameRuntimeUninitialize. 372// HRESULT XGameRuntimeInitialize(). Reference counted, as in the GDK: each call needs an XGameRuntimeUninitialize.
360HRESULT __stdcall XGameRuntimeInitialize() { 373HRESULT __stdcall XGameRuntimeInitialize() {
361 if (g_runtime_refs.fetch_add(1) == 0) std::fprintf(stderr, "[rt] xgameruntime: initialized (offline)\n"); 374 if (g_runtime_refs.fetch_add(1) == 0) std::fprintf(stderr, "[rt] xgameruntime: initialized (offline)\n");
@@ -416,17 +429,83 @@ uint64_t __stdcall XSystemGetAppMemoryUsage() {
416 return 0; 429 return 0;
417} 430}
418 431
432// ---- XSystemImpl (asked for as IXSystemImpl5), offline ----
433//
434// libHttpClient.GDK.dll asks QueryApiImpl for XSystemImpl with IXSystemImpl5's id and calls slots 3-8, each with the
435// argument shape of the function at that position of xgameruntime-docs' IXSystemImpl / IXSystemImpl3 /
436// IXSystemImpl4 lists (IXSystemImpl2 and 5 add nothing known): three (size, buffer, used) id queries, then
437// XSystemHandleTrack (two pointers), XSystemIsHandleValid (a handle) and XSystemAllowFullDownloadBandwidth (a bool).
438// docs/runtime_imports.md has the measurement.
439
440constexpr GUID kSystemClass = {0xe349bd1a, 0xfc20, 0x4e40, {0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f}};
441// IXSystemImpl's id is the class id; IXSystemImpl5 : IXSystemImpl4 : IXSystemImpl3 : IXSystemImpl2 : IXSystemImpl
442// (xgameruntime's include/xsystem.idl). One vtable serves all five.
443constexpr GUID kSystem2 = {0x6fd71f09, 0x7513, 0x49f0, {0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52}};
444constexpr GUID kSystem3 = {0x67ce4bfc, 0xb1d1, 0x4ac7, {0xbc, 0x3a, 0xcb, 0x92, 0x19, 0xa9, 0x7a, 0x85}};
445constexpr GUID kSystem4 = {0xdadc2895, 0x34b0, 0x4ef5, {0xa8, 0x3e, 0x45, 0x11, 0x4d, 0x62, 0x9b, 0x80}};
446constexpr GUID kSystem5 = {0x1861cf2e, 0xe18b, 0x4834, {0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf}};
447const GUID* const kSystemIids[] = {&kSystem2, &kSystem3, &kSystem4, &kSystem5, nullptr};
448
449// A fixed string into a (size, buffer, used) out parameter, as the XSystem id queries take one. `minimum` is the
450// buffer size the API requires (its *Bytes constant), which can be larger than the string.
451HRESULT copy_id(const char* id, size_t bytes, size_t minimum, size_t size, char* out, size_t* used) {
452 if (!out) return E_INVALIDARG;
453 if (size < minimum || size < bytes) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
454 std::memcpy(out, id, bytes);
455 if (used) *used = bytes;
456 return S_OK;
457}
458
459// XSystemXboxLiveSandboxIdMaxBytes is 16, and Microsoft's contract asks for a buffer at least that large (smaller
460// ones get ERROR_INSUFFICIENT_BUFFER, whatever the id's length); an offline title runs in the retail sandbox.
461constexpr size_t kSandboxIdMaxBytes = 16;
462constexpr char kSandboxId[] = "RETAIL";
463static_assert(sizeof(kSandboxId) <= kSandboxIdMaxBytes, "fits XSystemXboxLiveSandboxIdMaxBytes");
464// XSystemAppSpecificDeviceIdBytes is 45 (including the terminator): a fixed placeholder of that length, like the
465// console id.
466constexpr char kAppDeviceId[] = "00000000000000000000000000000000000000000000";
467static_assert(sizeof(kAppDeviceId) == 45, "fills XSystemAppSpecificDeviceIdBytes");
468
469HRESULT STDMETHODCALLTYPE sys_console_id(void*, size_t size, char* out, size_t* used) {
470 return XSystemGetConsoleId(size, out, used);
471}
472HRESULT STDMETHODCALLTYPE sys_sandbox_id(void*, size_t size, char* out, size_t* used) {
473 return copy_id(kSandboxId, sizeof(kSandboxId), kSandboxIdMaxBytes, size, out, used);
474}
475HRESULT STDMETHODCALLTYPE sys_app_device_id(void*, size_t size, char* out, size_t* used) {
476 return copy_id(kAppDeviceId, sizeof(kAppDeviceId), sizeof(kAppDeviceId), size, out, used);
477}
478// XSystemHandleTrack(callback, context): the GDK reports handle creation and destruction to it. Offline nothing is
479// tracked, so the callback is accepted and never called.
480HRESULT STDMETHODCALLTYPE sys_handle_track(void*, void*, void*) { return S_OK; }
481// bool XSystemIsHandleValid(XSystemHandle) and void XSystemAllowFullDownloadBandwidth(bool), as Microsoft documents
482// them: a bool, not an HRESULT (S_OK would read as false).
483bool STDMETHODCALLTYPE sys_is_handle_valid(void*, void* handle) { return handle != nullptr; }
484void STDMETHODCALLTYPE sys_allow_full_download_bandwidth(void*, bool) {}
485
486const void* const kSystemVtable[] = {
487 reinterpret_cast<const void*>(&object_query_interface), reinterpret_cast<const void*>(&object_add_ref),
488 reinterpret_cast<const void*>(&object_release),
489 reinterpret_cast<const void*>(&sys_console_id), // 3 XSystemGetConsoleId
490 reinterpret_cast<const void*>(&sys_sandbox_id), // 4 XSystemGetXboxLiveSandboxId
491 reinterpret_cast<const void*>(&sys_app_device_id), // 5 XSystemGetAppSpecificDeviceId
492 reinterpret_cast<const void*>(&sys_handle_track), // 6 XSystemHandleTrack (IXSystemImpl3)
493 reinterpret_cast<const void*>(&sys_is_handle_valid), // 7 XSystemIsHandleValid
494 reinterpret_cast<const void*>(&sys_allow_full_download_bandwidth), // 8 XSystemAllowFullDownloadBandwidth (4)
495};
496static_assert(std::size(kSystemVtable) == 9, "IUnknown + the six methods IXSystemImpl5 is known to have");
497
498RuntimeObject& system_object() {
499 static RuntimeObject object{kSystemVtable, &kSystemClass, kSystemIids};
500 return object;
501}
502
419// XVersion: 4-part version structure from GDK XGameRuntimeTypes.h (8 bytes) 503// XVersion: 4-part version structure from GDK XGameRuntimeTypes.h (8 bytes)
420struct XVersion { 504struct alignas(8) XVersion {
421 union { 505 uint16_t major;
422 struct { 506 uint16_t minor;
423 uint16_t major; 507 uint16_t build;
424 uint16_t minor; 508 uint16_t revision;
425 uint16_t build;
426 uint16_t revision;
427 };
428 uint64_t Value;
429 };
430}; 509};
431static_assert(sizeof(XVersion) == 8, "XVersion must be 8 bytes"); 510static_assert(sizeof(XVersion) == 8, "XVersion must be 8 bytes");
432 511
@@ -439,25 +518,34 @@ struct XSystemAnalyticsInfo {
439}; 518};
440static_assert(sizeof(XSystemAnalyticsInfo) == 144, "XSystemAnalyticsInfo must be 144 bytes"); 519static_assert(sizeof(XSystemAnalyticsInfo) == 144, "XSystemAnalyticsInfo must be 144 bytes");
441 520
521static void copy_string_padded(char* dst, size_t dst_cap, const char* src) {
522 if (!dst || dst_cap == 0) return;
523 std::memset(dst, 0, dst_cap);
524 if (!src) return;
525 const size_t len = std::strlen(src);
526 const size_t copy_len = len < dst_cap - 1 ? len : dst_cap - 1;
527 std::memcpy(dst, src, copy_len);
528}
529
442// XSystemAnalyticsInfo XSystemGetAnalyticsInfo() 530// XSystemAnalyticsInfo XSystemGetAnalyticsInfo()
443// Returned by value per Microsoft GDK specification. 531// Returned by value per Microsoft GDK specification.
444XSystemAnalyticsInfo __stdcall XSystemGetAnalyticsInfo() { 532XSystemAnalyticsInfo __stdcall XSystemGetAnalyticsInfo() {
445 XSystemAnalyticsInfo info{}; 533 XSystemAnalyticsInfo info{};
446 info.osVersion = {10, 0, 22000, 0}; 534 info.osVersion = {10, 0, 22000, 0};
447 info.hostingOsVersion = {10, 0, 22000, 0}; 535 info.hostingOsVersion = {10, 0, 22000, 0};
448 std::strncpy(info.family, "Xbox", sizeof(info.family) - 1); 536 copy_string_padded(info.family, sizeof(info.family), "Xbox");
449 537
450 const uint32_t dt = XSystemGetDeviceType(); 538 const uint32_t dt = XSystemGetDeviceType();
451 if (dt == static_cast<uint32_t>(XSystemDeviceType::XboxScarlettLockhart)) { 539 if (dt == static_cast<uint32_t>(XSystemDeviceType::XboxScarlettLockhart)) {
452 std::strncpy(info.form, "Xbox Series S", sizeof(info.form) - 1); 540 copy_string_padded(info.form, sizeof(info.form), "Xbox Series S");
453 } else { 541 } else {
454 std::strncpy(info.form, "Xbox Series X", sizeof(info.form) - 1); 542 copy_string_padded(info.form, sizeof(info.form), "Xbox Series X");
455 } 543 }
456 544
457 char form_override[64]; 545 char form_override[64];
458 const DWORD n = GetEnvironmentVariableA("LEONIDA_ANALYTICS_FORM", form_override, sizeof(form_override)); 546 const DWORD n = GetEnvironmentVariableA("LEONIDA_ANALYTICS_FORM", form_override, sizeof(form_override));
459 if (n > 0 && n < sizeof(form_override)) { 547 if (n > 0 && n < sizeof(form_override)) {
460 std::strncpy(info.form, form_override, sizeof(info.form) - 1); 548 copy_string_padded(info.form, sizeof(info.form), form_override);
461 } 549 }
462 return info; 550 return info;
463} 551}
@@ -484,33 +572,116 @@ HRESULT __stdcall XPackageGetCurrentProcessPackageIdentifier(size_t bufferSize,
484 return S_OK; 572 return S_OK;
485} 573}
486 574
487// HRESULT XPackageGetMountPath(XPackageMountHandle mount, size_t pathSize, char* path). 575// XPackageMountHandle: opaque 64-bit mount handle per GDK XPackage.h
488// Retrieves the installed filesystem path for the mounted package. 576struct XPackageMountHandle {
489// Reads LEONIDA_GAME_DIR when set, otherwise falls back to the current module's directory. 577 uint64_t handle;
490HRESULT __stdcall XPackageGetMountPath(void* /*mount*/, size_t pathSize, char* path) { 578};
491 if (!path || pathSize == 0) return E_INVALIDARG;
492 579
493 char buf[MAX_PATH] = {}; 580static std::mutex s_mount_mutex;
494 const DWORD n = GetEnvironmentVariableA("LEONIDA_GAME_DIR", buf, sizeof(buf)); 581static std::atomic<uint64_t> s_next_mount_id{1};
495 if (n == 0 || n >= sizeof(buf)) { 582static std::unordered_map<uint64_t, std::string> s_active_mounts;
496 const DWORD mod_len = GetModuleFileNameA(nullptr, buf, sizeof(buf)); 583
497 if (mod_len > 0 && mod_len < sizeof(buf)) { 584// Resolves the installation path for a specific content package identifier.
498 char* slash = std::strrchr(buf, '\\'); 585// GDK specifies that XPackageMount is only for content packages; mounting the main game returns E_ACCESSDENIED.
499 char* fslash = std::strrchr(buf, '/'); 586// Returns HRESULT_FROM_WIN32(ERROR_NOT_FOUND) if the package identifier is not installed.
500 char* last = slash > fslash ? slash : fslash; 587static HRESULT resolve_package_path(const char* packageIdentifier, char* out, size_t out_cap) {
501 if (last) { 588 if (!packageIdentifier || !out || out_cap == 0) return E_INVALIDARG;
502 *last = '\0'; 589
503 } else { 590 // Check against configured process/game package identifier; mounting the game itself is denied
504 return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); 591 char game_id[XPACKAGE_IDENTIFIER_MAX_LENGTH] = {};
592 const DWORD n = GetEnvironmentVariableA("LEONIDA_PACKAGE_ID", game_id, sizeof(game_id));
593 const char* process_id = (n > 0 && n < sizeof(game_id)) ? game_id : kDefaultPackageIdentifier;
594
595 if (std::strcmp(packageIdentifier, process_id) == 0) {
596 return E_ACCESSDENIED;
597 }
598
599 // Check optional installed content packages mapping: "id1=path1;id2=path2"
600 char mapping[1024] = {};
601 const DWORD map_len = GetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", mapping, sizeof(mapping));
602 if (map_len > 0 && map_len < sizeof(mapping)) {
603 char* token = mapping;
604 while (token && *token) {
605 char* sep = std::strchr(token, ';');
606 if (sep) *sep = '\0';
607 char* eq = std::strchr(token, '=');
608 if (eq) {
609 *eq = '\0';
610 if (std::strcmp(token, packageIdentifier) == 0) {
611 const char* val = eq + 1;
612 const size_t vlen = std::strlen(val);
613 if (vlen + 1 > out_cap) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
614 std::memcpy(out, val, vlen + 1);
615 return S_OK;
616 }
505 } 617 }
506 } else { 618 token = sep ? sep + 1 : nullptr;
507 return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
508 } 619 }
509 } 620 }
510 621
511 const size_t len = std::strlen(buf); 622 return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
512 if (pathSize < len + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); 623}
513 std::memcpy(path, buf, len + 1); 624
625// HRESULT XPackageMount(const char* packageIdentifier, XPackageMountHandle* mount)
626// Mounts an installed content package given its identifier and yields a valid mount handle.
627// Returns ERROR_NOT_FOUND if the package identifier is not recognized/installed.
628HRESULT __stdcall XPackageMount(const char* packageIdentifier, XPackageMountHandle* mount) {
629 if (!packageIdentifier || !mount) return E_INVALIDARG;
630 mount->handle = 0;
631
632 char buf[MAX_PATH] = {};
633 const HRESULT hr = resolve_package_path(packageIdentifier, buf, sizeof(buf));
634 if (FAILED(hr)) return hr;
635
636 const uint64_t id = s_next_mount_id.fetch_add(1);
637 {
638 std::lock_guard lock(s_mount_mutex);
639 s_active_mounts[id] = buf;
640 }
641 mount->handle = id;
642 return S_OK;
643}
644
645// void XPackageCloseMountHandle(XPackageMountHandle mount)
646// Closes a previously mounted package handle.
647void __stdcall XPackageCloseMountHandle(XPackageMountHandle mount) {
648 if (mount.handle == 0) return;
649 std::lock_guard lock(s_mount_mutex);
650 s_active_mounts.erase(mount.handle);
651}
652
653// HRESULT XPackageGetMountPathSize(XPackageMountHandle mount, size_t* pathSize).
654// Retrieves the size of the buffer needed to store the mounted package path, including the null terminator.
655HRESULT __stdcall XPackageGetMountPathSize(XPackageMountHandle mount, size_t* pathSize) {
656 if (mount.handle == 0 || !pathSize) return E_INVALIDARG;
657
658 std::string path;
659 {
660 std::lock_guard lock(s_mount_mutex);
661 auto it = s_active_mounts.find(mount.handle);
662 if (it == s_active_mounts.end()) return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
663 path = it->second;
664 }
665
666 *pathSize = path.size() + 1;
667 return S_OK;
668}
669
670// HRESULT XPackageGetMountPath(XPackageMountHandle mount, size_t pathSize, char* path).
671// Retrieves the installed filesystem path for the mounted package.
672HRESULT __stdcall XPackageGetMountPath(XPackageMountHandle mount, size_t pathSize, char* path) {
673 if (mount.handle == 0 || !path || pathSize == 0) return E_INVALIDARG;
674
675 std::string mount_path;
676 {
677 std::lock_guard lock(s_mount_mutex);
678 auto it = s_active_mounts.find(mount.handle);
679 if (it == s_active_mounts.end()) return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
680 mount_path = it->second;
681 }
682
683 if (pathSize < mount_path.size() + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
684 std::memcpy(path, mount_path.c_str(), mount_path.size() + 1);
514 return S_OK; 685 return S_OK;
515} 686}
516 687
@@ -536,6 +707,9 @@ SHIM_TABLE(xgameruntime,
536 XGR(InitializeApiImplEx2), 707 XGR(InitializeApiImplEx2),
537 XGR(UninitializeApiImpl), 708 XGR(UninitializeApiImpl),
538 XGR(QueryApiImpl), 709 XGR(QueryApiImpl),
710 // the same runtime through gameplatformservices.dll, which XCurl.dll loads from System32 (GetApiVersionImpl above)
711 {"gameplatformservices.dll", "QueryApiImpl", reinterpret_cast<void*>(&QueryApiImpl)},
712 {"gameplatformservices.dll", "GetApiVersionImpl", reinterpret_cast<void*>(&GetApiVersionImpl)},
539 XGR(XGameRuntimeInitialize), 713 XGR(XGameRuntimeInitialize),
540 XGR(XGameRuntimeUninitialize), 714 XGR(XGameRuntimeUninitialize),
541 XGR(XSystemGetDeviceType), 715 XGR(XSystemGetDeviceType),
@@ -544,6 +718,9 @@ SHIM_TABLE(xgameruntime,
544 XGR(XSystemGetAppMemoryUsage), 718 XGR(XSystemGetAppMemoryUsage),
545 XGR(XSystemGetAnalyticsInfo), 719 XGR(XSystemGetAnalyticsInfo),
546 XGR(XPackageGetCurrentProcessPackageIdentifier), 720 XGR(XPackageGetCurrentProcessPackageIdentifier),
721 XGR(XPackageMount),
722 XGR(XPackageCloseMountHandle),
723 XGR(XPackageGetMountPathSize),
547 XGR(XPackageGetMountPath), 724 XGR(XPackageGetMountPath),
548 XGR(XPackageIsPackagedProcess), 725 XGR(XPackageIsPackagedProcess),
549 // XTaskQueue (third_party/xtaskqueue) 726 // XTaskQueue (third_party/xtaskqueue)
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 2b6c03358..fcdc1ca33 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -395,25 +395,28 @@ struct IndexBufferView {
395// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads 395// DrawInstanced / DrawIndexedInstanced, with everything they use captured when they are recorded: D3D12 reads
396// render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at 396// render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the list's state at
397// the draw. resource 0 marks an unbound render-target slot or no depth buffer. 397// the draw. resource 0 marks an unbound render-target slot or no depth buffer.
398// Render targets and vertex buffer views are inlined (8 simultaneous targets, 32 input slots), eliminating heap allocations
399// during command list recording (D3D-289).
398struct Draw { 400struct Draw {
399 std::uintptr_t pipeline; 401 std::uintptr_t pipeline = 0;
400 std::array<std::uint32_t, 32> user_data; 402 std::array<std::uint32_t, 32> user_data{};
401 std::vector<TargetView> render_targets; 403 std::array<TargetView, 8> render_targets{};
402 TargetView depth; 404 TargetView depth{};
403 std::vector<VertexBufferView> vertex_buffers; // by input slot 405 std::array<VertexBufferView, 32> vertex_buffers{}; // by input slot
404 IndexBufferView index; 406 IndexBufferView index{};
405 std::uint32_t topology; // D3D_PRIMITIVE_TOPOLOGY 407 std::uint32_t topology = 0; // D3D_PRIMITIVE_TOPOLOGY
406 Viewport viewport; // the first; more viewports are not modelled yet 408 Viewport viewport{}; // the first; more viewports are not modelled yet
407 Rect scissor; // the first; D3D12 always scissors 409 Rect scissor{}; // the first; D3D12 always scissors
408 std::array<float, 4> blend_factor; 410 std::array<float, 4> blend_factor{1, 1, 1, 1};
409 std::uint32_t stencil_front; 411 std::uint32_t stencil_front = 0;
410 std::uint32_t stencil_back; 412 std::uint32_t stencil_back = 0;
411 bool indexed; 413 bool indexed = false;
412 std::uint32_t count; // vertices or indices per instance 414 std::uint32_t count = 0; // vertices or indices per instance
413 std::uint32_t instances; 415 std::uint32_t instances = 0;
414 std::uint32_t first; // first vertex or first index 416 std::uint32_t first = 0; // first vertex or first index
415 std::int32_t base_vertex; 417 std::int32_t base_vertex = 0;
416 std::uint32_t first_instance; 418 std::uint32_t first_instance = 0;
419 std::uint32_t render_target_count = 8;
417}; 420};
418 421
419// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. 422// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT.
@@ -715,6 +718,11 @@ public:
715 if (!draw.count || !draw.instances) return !closed_; 718 if (!draw.count || !draw.instances) return !closed_;
716 return append(draw); 719 return append(draw);
717 } 720 }
721 bool draw(Draw&& draw) {
722 if (!draw.pipeline) return false;
723 if (!draw.count || !draw.instances) return !closed_;
724 return append(std::move(draw));
725 }
718 726
719 // ClearRenderTargetView; the resource must be in render_target state at execution. No rects: the whole view. 727 // ClearRenderTargetView; the resource must be in render_target state at execution. No rects: the whole view.
720 bool clear_render_target(const TargetView& target, const ClearColor& color, std::span<const Rect> rects = {}) { 728 bool clear_render_target(const TargetView& target, const ClearColor& color, std::span<const Rect> rects = {}) {
diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h
index 2b5b111f7..2b44d32df 100644
--- a/runtime/src/descriptor_table.h
+++ b/runtime/src/descriptor_table.h
@@ -10,6 +10,7 @@
10#include <cstring> 10#include <cstring>
11#include <mutex> 11#include <mutex>
12#include <span> 12#include <span>
13#include <stdexcept>
13#include <vector> 14#include <vector>
14 15
15namespace leonida { 16namespace leonida {
@@ -69,6 +70,8 @@ public:
69 enum class InsertResult { added, unchanged, replaced, added_with_relocation }; 70 enum class InsertResult { added, unchanged, replaced, added_with_relocation };
70 71
71 explicit DescriptorTable(std::uint32_t initial_capacity = 16) { 72 explicit DescriptorTable(std::uint32_t initial_capacity = 16) {
73 // Slots use nonnegative int indices internally. Larger powers also wrap the capacity counter.
74 if (initial_capacity > max_capacity) throw std::length_error("Descriptor table capacity exceeds slot range");
72 std::uint32_t cap = 16; 75 std::uint32_t cap = 16;
73 while (cap < initial_capacity) cap <<= 1; 76 while (cap < initial_capacity) cap <<= 1;
74 mask_ = cap - 1; 77 mask_ = cap - 1;
@@ -291,6 +294,17 @@ private:
291 continue; 294 continue;
292 } 295 }
293 296
297 // Nine distinct keys with the same full hash can never fit the shader's eight probes,
298 // regardless of capacity. Refuse before allocating ever larger tables.
299 if (empty_slot < 0) {
300 std::uint32_t same_hash = 0;
301 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
302 const auto& entry = entries_[(h + k) & mask_];
303 if (hash_descriptor_key(entry.key) == h) ++same_hash;
304 }
305 if (same_hash == kDescriptorProbes)
306 throw std::length_error("Descriptor hash collision exceeds shader probe limit");
307 }
294 const bool relocate = empty_slot < 0; 308 const bool relocate = empty_slot < 0;
295 std::uint32_t moved_to = 0; 309 std::uint32_t moved_to = 0;
296 if (relocate) empty_slot = make_probe_slot(entries_, h, &moved_to); 310 if (relocate) empty_slot = make_probe_slot(entries_, h, &moved_to);
@@ -332,6 +346,7 @@ private:
332 } 346 }
333 347
334 void grow_locked() { 348 void grow_locked() {
349 if (entries_.size() >= max_capacity) throw std::length_error("Descriptor table capacity exhausted");
335 std::uint32_t new_cap = static_cast<std::uint32_t>(entries_.size() * 2); 350 std::uint32_t new_cap = static_cast<std::uint32_t>(entries_.size() * 2);
336 while (true) { 351 while (true) {
337 std::vector<DescriptorEntry> new_entries(new_cap); 352 std::vector<DescriptorEntry> new_entries(new_cap);
@@ -364,10 +379,12 @@ private:
364 changed_slots_.clear(); 379 changed_slots_.clear();
365 break; 380 break;
366 } 381 }
382 if (new_cap >= max_capacity) throw std::length_error("Descriptor probe range exhausted");
367 new_cap *= 2; 383 new_cap *= 2;
368 } 384 }
369 } 385 }
370 386
387 static constexpr std::uint32_t max_capacity = std::uint32_t{1} << 31;
371 mutable std::mutex mutex_; 388 mutable std::mutex mutex_;
372 std::uint32_t mask_ = 15; 389 std::uint32_t mask_ = 15;
373 std::vector<DescriptorEntry> entries_; 390 std::vector<DescriptorEntry> entries_;
diff --git a/runtime/src/gfx10_tiling.h b/runtime/src/gfx10_tiling.h
new file mode 100644
index 000000000..d869d1102
--- /dev/null
+++ b/runtime/src/gfx10_tiling.h
@@ -0,0 +1,158 @@
1#pragma once
2
3#include <bit>
4#include <cstddef>
5#include <cstdint>
6#include <cstring>
7#include <limits>
8#include <span>
9
10namespace leonida::gfx10 {
11
12enum class TileMode { sw_4kb_s, sw_64kb_d };
13
14namespace tiling_detail {
15
16// Mesa addrlib GFX10_SW_4K_S_RBPLUS_PATINFO / GFX10_SW_64K_D_RBPLUS_PATINFO;
17// tools/ttpf_mips.py patterns, corpus validation in docs/textures.md. Zero bits address bytes within an element.
18inline constexpr int patterns_4k[5][12] = {
19 {1, 2, 3, 4, -1, -2, -3, -4, -5, 5, -6, 6},
20 {0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6},
21 {0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5},
22 {0, 0, 0, 1, -1, -2, 2, 3, -3, 4, -4, 5},
23 {0, 0, 0, 0, -1, -2, 1, 2, -3, 3, -4, 4}};
24inline constexpr int patterns_64k[5][16] = {
25 {1, 2, 3, -2, -1, -3, 4, -4, -5, 5, -6, 6, -7, 7, -8, 8},
26 {0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8},
27 {0, 0, 1, 2, -1, -2, 3, -3, -4, 4, -5, 5, -6, 6, -7, 7},
28 {0, 0, 0, 1, -1, 2, 3, -2, -3, 4, -4, 5, -5, 6, -6, 7},
29 {0, 0, 0, 0, 1, -1, 2, -2, -3, 3, -4, 4, -5, 5, -6, 6}};
30
31inline bool overlap(std::span<const std::byte> source, std::span<std::byte> destination) {
32 const auto a = reinterpret_cast<std::uintptr_t>(source.data());
33 const auto b = reinterpret_cast<std::uintptr_t>(destination.data());
34 return a <= b ? b - a < source.size() : a - b < destination.size();
35}
36
37} // namespace tiling_detail
38
39// One standalone 2D level, no mip tail or tile XOR. BC formats use a compressed block as one element.
40class TiledSurface2D {
41public:
42 static bool make(TileMode mode, std::size_t element_bytes, std::size_t width, std::size_t height,
43 TiledSurface2D& out) {
44 if (!width || !height) return false;
45 unsigned index = 0;
46 switch (element_bytes) {
47 case 1: break;
48 case 2: index = 1; break;
49 case 4: index = 2; break;
50 case 8: index = 3; break;
51 case 16: index = 4; break;
52 default: return false;
53 }
54 TiledSurface2D next;
55 switch (mode) {
56 case TileMode::sw_4kb_s:
57 next.pattern_ = tiling_detail::patterns_4k[index];
58 next.bits_ = 12;
59 break;
60 case TileMode::sw_64kb_d:
61 next.pattern_ = tiling_detail::patterns_64k[index];
62 next.bits_ = 16;
63 break;
64 default: return false;
65 }
66 unsigned x_bits = 0, y_bits = 0;
67 for (unsigned bit = 0; bit < next.bits_; ++bit) {
68 x_bits += next.pattern_[bit] > 0;
69 y_bits += next.pattern_[bit] < 0;
70 }
71 next.tile_width_ = std::size_t{1} << x_bits;
72 next.tile_height_ = std::size_t{1} << y_bits;
73 next.tiles_x_ = (width - 1) / next.tile_width_ + 1;
74 const std::size_t tiles_y = (height - 1) / next.tile_height_ + 1;
75 const std::size_t tile_bytes = std::size_t{1} << next.bits_;
76 constexpr auto max = std::numeric_limits<std::size_t>::max();
77 if (next.tiles_x_ > max / tiles_y || next.tiles_x_ * tiles_y > max / tile_bytes) return false;
78 next.size_ = next.tiles_x_ * tiles_y * tile_bytes;
79 next.width_ = width;
80 next.height_ = height;
81 next.element_bytes_ = element_bytes;
82 out = next;
83 return true;
84 }
85
86 std::size_t tiled_size() const { return size_; }
87 std::size_t tile_width() const { return tile_width_; }
88 std::size_t tile_height() const { return tile_height_; }
89
90 bool element_offset(std::size_t x, std::size_t y, std::size_t& offset) const {
91 if (!size_ || x >= width_ || y >= height_) return false;
92 offset = address(x, y);
93 return true;
94 }
95
96 // Buffers must not overlap. Padding in either destination is left untouched; failure writes nothing.
97 bool detile(std::span<const std::byte> tiled, std::span<std::byte> linear, std::size_t row_pitch) const {
98 return copy(tiled, linear, row_pitch, false);
99 }
100
101 bool tile(std::span<const std::byte> linear, std::span<std::byte> tiled, std::size_t row_pitch) const {
102 return copy(linear, tiled, row_pitch, true);
103 }
104
105private:
106 std::size_t address(std::size_t x, std::size_t y) const {
107 std::size_t offset = ((y / tile_height_) * tiles_x_ + x / tile_width_) << bits_;
108 for (unsigned bit = 0; bit < bits_; ++bit) {
109 const int source = pattern_[bit];
110 if (source > 0) offset |= ((x >> (source - 1)) & 1) << bit;
111 else if (source < 0) offset |= ((y >> (-source - 1)) & 1) << bit;
112 }
113 return offset;
114 }
115
116 bool copy(std::span<const std::byte> source, std::span<std::byte> destination, std::size_t pitch,
117 bool to_tiled) const {
118 if (!size_) return false;
119 const std::size_t row_bytes = width_ * element_bytes_;
120 if (pitch < row_bytes || (height_ - 1 &&
121 pitch > (std::numeric_limits<std::size_t>::max() - row_bytes) / (height_ - 1))) return false;
122 const std::size_t linear_size = (height_ - 1) * pitch + row_bytes;
123 if (source.size() < (to_tiled ? linear_size : size_) ||
124 destination.size() < (to_tiled ? size_ : linear_size) ||
125 tiling_detail::overlap(source, destination)) return false;
126 const auto tile_x_bits = std::countr_zero(tile_width_);
127 std::size_t x_offsets[256]{};
128 for (std::size_t x = 0; x < tile_width_; ++x) {
129 for (unsigned bit = 0; bit < bits_; ++bit) {
130 const int source_bit = pattern_[bit];
131 if (source_bit > 0) x_offsets[x] |= ((x >> (source_bit - 1)) & 1) << bit;
132 }
133 }
134 for (std::size_t y = 0; y < height_; ++y) {
135 std::size_t y_offset = 0;
136 for (unsigned bit = 0; bit < bits_; ++bit) {
137 const int source_bit = pattern_[bit];
138 if (source_bit < 0) y_offset |= ((y >> (-source_bit - 1)) & 1) << bit;
139 }
140 const std::size_t tile_row = (y / tile_height_) * tiles_x_;
141 for (std::size_t x = 0; x < width_; ++x) {
142 const std::size_t linear = y * pitch + x * element_bytes_;
143 const std::size_t tiled = ((tile_row + (x >> tile_x_bits)) << bits_) +
144 y_offset + x_offsets[x & (tile_width_ - 1)];
145 std::memcpy(destination.data() + (to_tiled ? tiled : linear),
146 source.data() + (to_tiled ? linear : tiled), element_bytes_);
147 }
148 }
149 return true;
150 }
151
152 const int* pattern_ = nullptr;
153 unsigned bits_ = 0;
154 std::size_t width_ = 0, height_ = 0, element_bytes_ = 0;
155 std::size_t tile_width_ = 0, tile_height_ = 0, tiles_x_ = 0, size_ = 0;
156};
157
158} // namespace leonida::gfx10
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index 06baae387..7bc2d78ab 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -94,6 +94,7 @@ int wmain(int argc, wchar_t** argv) {
94 try { 94 try {
95 rt::Loader loader(game_dir); 95 rt::Loader loader(game_dir);
96 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code 96 rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code
97 if (run) rt::process::set_command_line(image.filename().wstring(), game_args);
97 if (init || run) { 98 if (init || run) {
98 loader.initialise(); // TLS callbacks, then DllMain(DLL_PROCESS_ATTACH) for DLLs 99 loader.initialise(); // TLS callbacks, then DllMain(DLL_PROCESS_ATTACH) for DLLs
99 std::printf("%zu module(s) initialised\n", loader.modules().size()); 100 std::printf("%zu module(s) initialised\n", loader.modules().size());
@@ -128,7 +129,6 @@ int wmain(int argc, wchar_t** argv) {
128 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); 129 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str());
129 return 1; 130 return 1;
130 } 131 }
131 rt::process::set_command_line(image.filename().wstring(), game_args);
132 std::printf("console paths: GAME: -> %ls, writes -> %ls\n", game_dir.c_str(), overlay_dir.c_str()); 132 std::printf("console paths: GAME: -> %ls, writes -> %ls\n", game_dir.c_str(), overlay_dir.c_str());
133 std::printf("running %s\n", main_module.name.c_str()); 133 std::printf("running %s\n", main_module.name.c_str());
134 std::fflush(stdout); 134 std::fflush(stdout);
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index a59f9d0b1..f2c62ec91 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -65,7 +65,8 @@ uint64_t rva_in(const Module& m, uint64_t va, const char* what) {
65 65
66IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { 66IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) {
67 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 67 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
68 const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; 68 // Through directory(), as every other directory: an entry past NumberOfRvaAndSizes is not a TLS directory.
69 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS);
69 if (!dir.Size || !dir.VirtualAddress) return nullptr; 70 if (!dir.Size || !dir.VirtualAddress) return nullptr;
70 require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory"); 71 require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory");
71 return at<IMAGE_TLS_DIRECTORY64>(m.base, dir.VirtualAddress); 72 return at<IMAGE_TLS_DIRECTORY64>(m.base, dir.VirtualAddress);
@@ -696,7 +697,6 @@ void Loader::initialise(Module& m) {
696 // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run. 697 // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run.
697 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew); 698 auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
698 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { 699 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) {
699 if (m.entry_rva >= m.size) throw std::runtime_error(m.name + ": the entry point is outside the image");
700 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva); 700 auto entry = reinterpret_cast<BOOL(NTAPI*)(void*, DWORD, void*)>(m.base + m.entry_rva);
701 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr); 701 const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, nullptr);
702 if (startup_trace::enabled()) 702 if (startup_trace::enabled())
@@ -741,6 +741,8 @@ Module& Loader::map_image(const std::filesystem::path& path) {
741 if (!oh.SizeOfImage || oh.SizeOfHeaders < headers_end || oh.SizeOfHeaders > oh.SizeOfImage || 741 if (!oh.SizeOfImage || oh.SizeOfHeaders < headers_end || oh.SizeOfHeaders > oh.SizeOfImage ||
742 oh.SizeOfHeaders > file.size()) 742 oh.SizeOfHeaders > file.size())
743 throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the headers and file"); 743 throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the headers and file");
744 if (oh.AddressOfEntryPoint && oh.AddressOfEntryPoint >= oh.SizeOfImage)
745 throw std::runtime_error(name + ": the entry point is outside the image");
744 746
745 auto* m = new Module; 747 auto* m = new Module;
746 m->name = name; 748 m->name = name;
diff --git a/runtime/src/present_compose.comp b/runtime/src/present_compose.comp
new file mode 100644
index 000000000..b557a6444
--- /dev/null
+++ b/runtime/src/present_compose.comp
@@ -0,0 +1,130 @@
1// PresentX plane composition (docs/d3d12_vulkan.md section 4.5): one or two planes, each scaled from a source rectangle to
2// a destination rectangle of the output, plane 1 blended over plane 0, written to an RGBA16F image the presenter then
3// copies to the swapchain. present_compose_spv.h is this file compiled with
4// `glslc --target-env=vulkan1.1 -O -mfmt=c` (see the header for the command); keep them together.
5//
6// Every plane is read with texelFetch (no sampler: the filtering is done here, so it works on any sampled format and
7// only reads texels inside the source rectangle). Values are the encoded ones of the plane's colour space: SDR planes
8// hold G2.2 values, HDR10 planes hold ST.2084 (PQ) Rec.2020 values. An sRGB-format source is decoded by the texture unit,
9// so `flag_srgb_source` encodes it again with the sRGB curve and the bytes come out as they went in.
10//
11// Conversions (all provisional, docs section 4.5): SDR -> HDR10: pow 2.2, Rec.709 -> Rec.2020, times the SDR white level
12// in nits, PQ. HDR10 -> SDR: PQ, Rec.2020 -> Rec.709, divided by the white level, clipped to 0..1, pow 1/2.2 (no
13// tone mapping). Same space: untouched. Plane 1 is blended after conversion, in the output's encoded space.
14#version 450
15#extension GL_EXT_samplerless_texture_functions : require
16
17layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
18
19layout(set = 0, binding = 0) uniform texture2D plane0;
20layout(set = 0, binding = 1) uniform texture2D plane1;
21layout(set = 0, binding = 2, rgba16f) uniform writeonly image2D out_image;
22
23const uint flag_point = 1u;
24const uint flag_srgb_source = 2u;
25const uint flag_hdr10 = 4u;
26const uint flag_straight_alpha = 8u;
27
28layout(push_constant) uniform Push {
29 vec4 dest0; // destination rectangle in output pixels: left, top, right, bottom
30 vec4 dest1;
31 vec4 src0; // source rectangle in texels
32 vec4 src1;
33 uint flags0;
34 uint flags1;
35 uint plane_count;
36 uint out_hdr; // 1: the output holds PQ Rec.2020 values
37 float sdr_white; // nits of SDR white, for the conversions
38 uint width, height;
39 uint pad;
40} pc;
41
42vec3 srgb_encode(vec3 c) {
43 c = clamp(c, 0.0, 1.0);
44 return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, greaterThan(c, vec3(0.0031308)));
45}
46
47// `pre`: straight-alpha data is filtered premultiplied (colour * alpha), else a transparent texel would drag the colour of its neighbours down.
48vec4 fetch_texel(texture2D t, ivec2 i, bool pre) {
49 vec4 c = texelFetch(t, i, 0);
50 return pre ? vec4(c.rgb * c.a, c.a) : c;
51}
52
53// The plane's value at output pixel `pixel` (its centre), in the plane's own encoding.
54vec4 fetch_plane(texture2D t, vec4 dest, vec4 src, uint flags, ivec2 pixel) {
55 vec2 p = (vec2(pixel) + 0.5 - dest.xy) / (dest.zw - dest.xy); // 0..1 across the destination rectangle
56 vec2 s = src.xy + p * (src.zw - src.xy); // continuous texel coordinates
57 vec2 lo = src.xy, hi = src.zw - 1.0;
58 bool pre = (flags & flag_straight_alpha) != 0u;
59 vec4 c;
60 if ((flags & flag_point) != 0u) {
61 c = fetch_texel(t, ivec2(clamp(floor(s), lo, hi)), false);
62 } else {
63 vec2 f = clamp(s - 0.5, lo, hi); // the texel whose centre is at or before the sample, clamped inside the rectangle
64 vec2 base = floor(f), w = f - base;
65 ivec2 i0 = ivec2(base), i1 = ivec2(min(base + 1.0, hi));
66 c = mix(mix(fetch_texel(t, ivec2(i0.x, i0.y), pre), fetch_texel(t, ivec2(i1.x, i0.y), pre), w.x),
67 mix(fetch_texel(t, ivec2(i0.x, i1.y), pre), fetch_texel(t, ivec2(i1.x, i1.y), pre), w.x), w.y);
68 if (pre) c.rgb = c.a > 0.0 ? c.rgb / c.a : vec3(0.0); // back to unassociated colour
69 }
70 if ((flags & flag_srgb_source) != 0u) c.rgb = srgb_encode(c.rgb);
71 return c;
72}
73
74const float m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875;
75
76vec3 pq_to_nits(vec3 e) {
77 vec3 ep = pow(clamp(e, 0.0, 1.0), vec3(1.0 / m2));
78 return 10000.0 * pow(max(ep - c1, 0.0) / (c2 - c3 * ep), vec3(1.0 / m1));
79}
80
81vec3 nits_to_pq(vec3 nits) {
82 vec3 y = pow(clamp(nits / 10000.0, 0.0, 1.0), vec3(m1));
83 return pow((c1 + c2 * y) / (1.0 + c3 * y), vec3(m2));
84}
85
86vec3 bt709_to_bt2020(vec3 v) {
87 return vec3(dot(vec3(0.627404, 0.329283, 0.043313), v), dot(vec3(0.069097, 0.919540, 0.011362), v),
88 dot(vec3(0.016391, 0.088013, 0.895595), v));
89}
90
91vec3 bt2020_to_bt709(vec3 v) {
92 return vec3(dot(vec3(1.660491, -0.587641, -0.072850), v), dot(vec3(-0.124550, 1.132900, -0.008349), v),
93 dot(vec3(-0.018151, -0.100579, 1.118730), v));
94}
95
96// `c` in the encoding of the plane (hdr: PQ Rec.2020, else G2.2 Rec.709) to the output's.
97vec3 to_output(vec3 c, bool plane_hdr) {
98 bool out_hdr = pc.out_hdr != 0u;
99 if (plane_hdr == out_hdr) return c;
100 if (!plane_hdr) return nits_to_pq(bt709_to_bt2020(pow(clamp(c, 0.0, 1.0), vec3(2.2))) * pc.sdr_white);
101 return pow(clamp(bt2020_to_bt709(pq_to_nits(c)) / pc.sdr_white, 0.0, 1.0), vec3(1.0 / 2.2));
102}
103
104void main() {
105 ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
106 if (pixel.x >= int(pc.width) || pixel.y >= int(pc.height)) return;
107 vec2 centre = vec2(pixel) + 0.5;
108
109 vec3 base = vec3(0.0); // outside plane 0's rectangle: black
110 if (all(greaterThanEqual(centre, pc.dest0.xy)) && all(lessThan(centre, pc.dest0.zw))) {
111 vec4 c = fetch_plane(plane0, pc.dest0, pc.src0, pc.flags0 & ~flag_straight_alpha, pixel);
112 base = to_output(c.rgb, (pc.flags0 & flag_hdr10) != 0u);
113 }
114 if (pc.plane_count > 1u && all(greaterThanEqual(centre, pc.dest1.xy)) && all(lessThan(centre, pc.dest1.zw))) {
115 vec4 c = fetch_plane(plane1, pc.dest1, pc.src1, pc.flags1, pixel);
116 bool hdr = (pc.flags1 & flag_hdr10) != 0u;
117 float a = clamp(c.a, 0.0, 1.0);
118 bool straight = (pc.flags1 & flag_straight_alpha) != 0u;
119 vec3 over;
120 if (hdr == (pc.out_hdr != 0u)) {
121 over = c.rgb; // already in the output's space: no conversion, so no un-premultiplying either
122 } else {
123 vec3 colour = straight || a <= 0.0 ? c.rgb : c.rgb / a; // convert unassociated colour
124 over = to_output(colour, hdr);
125 if (!straight) over *= a;
126 }
127 base = straight ? mix(base, over, a) : over + (1.0 - a) * base;
128 }
129 imageStore(out_image, pixel, vec4(base, 1.0));
130}
diff --git a/runtime/src/present_compose.inc b/runtime/src/present_compose.inc
new file mode 100644
index 000000000..35cfc3e80
--- /dev/null
+++ b/runtime/src/present_compose.inc
@@ -0,0 +1,742 @@
1{0x07230203,0x00010300,0x000d000b,0x00000632,
20x00000000,0x00020011,0x00000001,0x0006000b,
30x00000001,0x4c534c47,0x6474732e,0x3035342e,
40x00000000,0x0003000e,0x00000000,0x00000001,
50x0006000f,0x00000005,0x00000004,0x6e69616d,
60x00000000,0x000001b3,0x00060010,0x00000004,
70x00000011,0x00000008,0x00000008,0x00000001,
80x00030047,0x0000017b,0x00000002,0x00050048,
90x0000017b,0x00000000,0x00000023,0x00000000,
100x00050048,0x0000017b,0x00000001,0x00000023,
110x00000010,0x00050048,0x0000017b,0x00000002,
120x00000023,0x00000020,0x00050048,0x0000017b,
130x00000003,0x00000023,0x00000030,0x00050048,
140x0000017b,0x00000004,0x00000023,0x00000040,
150x00050048,0x0000017b,0x00000005,0x00000023,
160x00000044,0x00050048,0x0000017b,0x00000006,
170x00000023,0x00000048,0x00050048,0x0000017b,
180x00000007,0x00000023,0x0000004c,0x00050048,
190x0000017b,0x00000008,0x00000023,0x00000050,
200x00050048,0x0000017b,0x00000009,0x00000023,
210x00000054,0x00050048,0x0000017b,0x0000000a,
220x00000023,0x00000058,0x00050048,0x0000017b,
230x0000000b,0x00000023,0x0000005c,0x00040047,
240x000001b3,0x0000000b,0x0000001c,0x00040047,
250x000001e7,0x00000021,0x00000000,0x00040047,
260x000001e7,0x00000022,0x00000000,0x00040047,
270x0000021c,0x00000021,0x00000001,0x00040047,
280x0000021c,0x00000022,0x00000000,0x00030047,
290x00000274,0x00000019,0x00040047,0x00000274,
300x00000021,0x00000002,0x00040047,0x00000274,
310x00000022,0x00000000,0x00040047,0x0000027c,
320x0000000b,0x00000019,0x00020013,0x00000002,
330x00030021,0x00000003,0x00000002,0x00030016,
340x00000006,0x00000020,0x00040017,0x00000007,
350x00000006,0x00000003,0x00090019,0x0000000d,
360x00000006,0x00000001,0x00000000,0x00000000,
370x00000000,0x00000001,0x00000000,0x00040020,
380x0000000e,0x00000000,0x0000000d,0x00040015,
390x0000000f,0x00000020,0x00000001,0x00040017,
400x00000010,0x0000000f,0x00000002,0x00020014,
410x00000012,0x00040017,0x00000014,0x00000006,
420x00000004,0x00040015,0x0000001c,0x00000020,
430x00000000,0x0004002b,0x00000006,0x00000038,
440x00000000,0x0004002b,0x00000006,0x00000039,
450x3f800000,0x0004002b,0x00000006,0x0000003e,
460x414eb852,0x0004002b,0x00000006,0x00000040,
470x3f870a3d,0x0004002b,0x00000006,0x00000042,
480x3ed55555,0x0006002c,0x00000007,0x00000043,
490x00000042,0x00000042,0x00000042,0x0004002b,
500x00000006,0x00000046,0x3d6147ae,0x0004002b,
510x00000006,0x0000004a,0x3b4d2e1c,0x0006002c,
520x00000007,0x0000004b,0x0000004a,0x0000004a,
530x0000004a,0x00040017,0x0000004c,0x00000012,
540x00000003,0x0004002b,0x0000000f,0x00000054,
550x00000000,0x00040017,0x0000006c,0x00000006,
560x00000002,0x0004002b,0x00000006,0x00000071,
570x3f000000,0x0004002b,0x0000001c,0x00000092,
580x00000008,0x0004002b,0x0000001c,0x00000094,
590x00000000,0x0004002b,0x0000001c,0x00000097,
600x00000001,0x0006002c,0x00000007,0x00000101,
610x00000038,0x00000038,0x00000038,0x0004002b,
620x0000001c,0x00000107,0x00000002,0x0004002b,
630x00000006,0x00000121,0x3c4fcdac,0x0006002c,
640x00000007,0x00000122,0x00000121,0x00000121,
650x00000121,0x0004002b,0x00000006,0x00000124,
660x461c4000,0x0004002b,0x00000006,0x00000126,
670x3f560000,0x0004002b,0x00000006,0x0000012b,
680x4196d000,0x0004002b,0x00000006,0x0000012c,
690x41958000,0x0004002b,0x00000006,0x00000132,
700x40c8e06b,0x0006002c,0x00000007,0x00000133,
710x00000132,0x00000132,0x00000132,0x0004002b,
720x00000006,0x0000013f,0x3e232000,0x0006002c,
730x00000007,0x00000140,0x0000013f,0x0000013f,
740x0000013f,0x0004002b,0x00000006,0x0000014b,
750x429db000,0x0006002c,0x00000007,0x0000014c,
760x0000014b,0x0000014b,0x0000014b,0x0004002b,
770x00000006,0x00000150,0x3f209d8c,0x0004002b,
780x00000006,0x00000151,0x3ea897c8,0x0004002b,
790x00000006,0x00000152,0x3d3168f9,0x0006002c,
800x00000007,0x00000153,0x00000150,0x00000151,
810x00000152,0x0004002b,0x00000006,0x00000156,
820x3d8d82ba,0x0004002b,0x00000006,0x00000157,
830x3f6b66f9,0x0004002b,0x00000006,0x00000158,
840x3c3a27af,0x0006002c,0x00000007,0x00000159,
850x00000156,0x00000157,0x00000158,0x0004002b,
860x00000006,0x0000015c,0x3c86466b,0x0004002b,
870x00000006,0x0000015d,0x3db44029,0x0004002b,
880x00000006,0x0000015e,0x3f6545b7,0x0006002c,
890x00000007,0x0000015f,0x0000015c,0x0000015d,
900x0000015e,0x0004002b,0x00000006,0x00000165,
910x3fd48af8,0x0004002b,0x00000006,0x00000166,
920xbf166fa4,0x0004002b,0x00000006,0x00000167,
930xbd953261,0x0006002c,0x00000007,0x00000168,
940x00000165,0x00000166,0x00000167,0x0004002b,
950x00000006,0x0000016b,0xbdff1412,0x0004002b,
960x00000006,0x0000016c,0x3f9102de,0x0004002b,
970x00000006,0x0000016d,0xbc08ca3e,0x0006002c,
980x00000007,0x0000016e,0x0000016b,0x0000016c,
990x0000016d,0x0004002b,0x00000006,0x00000171,
1000xbc94b168,0x0004002b,0x00000006,0x00000172,
1010xbdcdfc5d,0x0004002b,0x00000006,0x00000173,
1020x3f8f328b,0x0006002c,0x00000007,0x00000174,
1030x00000171,0x00000172,0x00000173,0x000e001e,
1040x0000017b,0x00000014,0x00000014,0x00000014,
1050x00000014,0x0000001c,0x0000001c,0x0000001c,
1060x0000001c,0x00000006,0x0000001c,0x0000001c,
1070x0000001c,0x00040020,0x0000017c,0x00000009,
1080x0000017b,0x0004003b,0x0000017c,0x0000017d,
1090x00000009,0x0004002b,0x0000000f,0x0000017e,
1100x00000007,0x00040020,0x0000017f,0x00000009,
1110x0000001c,0x0004002b,0x00000006,0x00000192,
1120x400ccccd,0x0006002c,0x00000007,0x00000193,
1130x00000192,0x00000192,0x00000192,0x0004002b,
1140x0000000f,0x00000197,0x00000008,0x00040020,
1150x00000198,0x00000009,0x00000006,0x0004002b,
1160x00000006,0x000001ab,0x3ee8ba2f,0x0006002c,
1170x00000007,0x000001ac,0x000001ab,0x000001ab,
1180x000001ab,0x00040017,0x000001b1,0x0000001c,
1190x00000003,0x00040020,0x000001b2,0x00000001,
1200x000001b1,0x0004003b,0x000001b2,0x000001b3,
1210x00000001,0x00040017,0x000001b4,0x0000001c,
1220x00000002,0x0004002b,0x0000000f,0x000001ba,
1230x00000009,0x0004002b,0x0000000f,0x000001c4,
1240x0000000a,0x00040020,0x000001d4,0x00000009,
1250x00000014,0x00040017,0x000001d8,0x00000012,
1260x00000002,0x0004003b,0x0000000e,0x000001e7,
1270x00000000,0x0004002b,0x0000000f,0x000001e8,
1280x00000002,0x0004002b,0x0000000f,0x000001e9,
1290x00000004,0x0004002b,0x0000001c,0x000001fa,
1300x00000004,0x0004002b,0x0000000f,0x00000202,
1310x00000006,0x0004002b,0x0000000f,0x00000209,
1320x00000001,0x0004003b,0x0000000e,0x0000021c,
1330x00000000,0x0004002b,0x0000000f,0x0000021d,
1340x00000003,0x0004002b,0x0000000f,0x0000021e,
1350x00000005,0x00090019,0x00000272,0x00000006,
1360x00000001,0x00000000,0x00000000,0x00000000,
1370x00000002,0x00000002,0x00040020,0x00000273,
1380x00000000,0x00000272,0x0004003b,0x00000273,
1390x00000274,0x00000000,0x0006002c,0x000001b1,
1400x0000027c,0x00000092,0x00000092,0x00000097,
1410x0005002c,0x0000006c,0x00000627,0x00000071,
1420x00000071,0x0005002c,0x0000006c,0x00000628,
1430x00000039,0x00000039,0x0006002c,0x00000007,
1440x0000062a,0x00000039,0x00000039,0x00000039,
1450x0006002c,0x00000007,0x0000062b,0x00000046,
1460x00000046,0x00000046,0x0006002c,0x00000007,
1470x0000062d,0x00000126,0x00000126,0x00000126,
1480x0006002c,0x00000007,0x0000062e,0x0000012b,
1490x0000012b,0x0000012b,0x0004002b,0x00000006,
1500x0000062f,0x38d1b717,0x0006002c,0x00000007,
1510x00000630,0x0000062f,0x0000062f,0x0000062f,
1520x00030001,0x00000014,0x00000631,0x00050036,
1530x00000002,0x00000004,0x00000000,0x00000003,
1540x000200f8,0x00000005,0x000300f7,0x0000027d,
1550x00000000,0x000300fb,0x00000094,0x0000027e,
1560x000200f8,0x0000027e,0x0004003d,0x000001b1,
1570x000001b5,0x000001b3,0x0007004f,0x000001b4,
1580x000001b6,0x000001b5,0x000001b5,0x00000000,
1590x00000001,0x0004007c,0x00000010,0x000001b7,
1600x000001b6,0x00050051,0x0000000f,0x000001b9,
1610x000001b7,0x00000000,0x00050041,0x0000017f,
1620x000001bb,0x0000017d,0x000001ba,0x0004003d,
1630x0000001c,0x000001bc,0x000001bb,0x0004007c,
1640x0000000f,0x000001bd,0x000001bc,0x000500af,
1650x00000012,0x000001be,0x000001b9,0x000001bd,
1660x000400a8,0x00000012,0x000001bf,0x000001be,
1670x000300f7,0x000001c1,0x00000000,0x000400fa,
1680x000001bf,0x000001c0,0x000001c1,0x000200f8,
1690x000001c0,0x00050051,0x0000000f,0x000001c3,
1700x000001b7,0x00000001,0x00050041,0x0000017f,
1710x000001c5,0x0000017d,0x000001c4,0x0004003d,
1720x0000001c,0x000001c6,0x000001c5,0x0004007c,
1730x0000000f,0x000001c7,0x000001c6,0x000500af,
1740x00000012,0x000001c8,0x000001c3,0x000001c7,
1750x000200f9,0x000001c1,0x000200f8,0x000001c1,
1760x000700f5,0x00000012,0x000001c9,0x000001be,
1770x0000027e,0x000001c8,0x000001c0,0x000300f7,
1780x000001cb,0x00000000,0x000400fa,0x000001c9,
1790x000001ca,0x000001cb,0x000200f8,0x000001ca,
1800x000200f9,0x0000027d,0x000200f8,0x000001cb,
1810x0004006f,0x0000006c,0x000001cf,0x000001b7,
1820x00050081,0x0000006c,0x000001d1,0x000001cf,
1830x00000627,0x00050041,0x000001d4,0x000001d5,
1840x0000017d,0x00000054,0x0004003d,0x00000014,
1850x000001d6,0x000001d5,0x0007004f,0x0000006c,
1860x000001d7,0x000001d6,0x000001d6,0x00000000,
1870x00000001,0x000500be,0x000001d8,0x000001d9,
1880x000001d1,0x000001d7,0x0004009b,0x00000012,
1890x000001da,0x000001d9,0x000300f7,0x000001dc,
1900x00000000,0x000400fa,0x000001da,0x000001db,
1910x000001dc,0x000200f8,0x000001db,0x0007004f,
1920x0000006c,0x000001e0,0x000001d6,0x000001d6,
1930x00000002,0x00000003,0x000500b8,0x000001d8,
1940x000001e1,0x000001d1,0x000001e0,0x0004009b,
1950x00000012,0x000001e2,0x000001e1,0x000200f9,
1960x000001dc,0x000200f8,0x000001dc,0x000700f5,
1970x00000012,0x000001e3,0x000001da,0x000001cb,
1980x000001e2,0x000001db,0x000300f7,0x000001e5,
1990x00000000,0x000400fa,0x000001e3,0x000001e4,
2000x000001e5,0x000200f8,0x000001e4,0x00050041,
2010x0000017f,0x000001ea,0x0000017d,0x000001e9,
2020x0004003d,0x0000001c,0x000001eb,0x000001ea,
2030x00050041,0x000001d4,0x000001f2,0x0000017d,
2040x000001e8,0x0004003d,0x00000014,0x000001f3,
2050x000001f2,0x00050083,0x0000006c,0x000002a5,
2060x000001d1,0x000001d7,0x0007004f,0x0000006c,
2070x000002a7,0x000001d6,0x000001d6,0x00000002,
2080x00000003,0x00050083,0x0000006c,0x000002aa,
2090x000002a7,0x000001d7,0x00050088,0x0000006c,
2100x000002ab,0x000002a5,0x000002aa,0x0007004f,
2110x0000006c,0x000002ad,0x000001f3,0x000001f3,
2120x00000000,0x00000001,0x0007004f,0x0000006c,
2130x000002b0,0x000001f3,0x000001f3,0x00000002,
2140x00000003,0x00050083,0x0000006c,0x000002b3,
2150x000002b0,0x000002ad,0x00050085,0x0000006c,
2160x000002b4,0x000002ab,0x000002b3,0x00050081,
2170x0000006c,0x000002b5,0x000002ad,0x000002b4,
2180x00050083,0x0000006c,0x000002bb,0x000002b0,
2190x00000628,0x000500c7,0x0000001c,0x000002c0,
2200x000001eb,0x00000097,0x000500ab,0x00000012,
2210x000002c1,0x000002c0,0x00000094,0x000300f7,
2220x0000031c,0x00000000,0x000400fa,0x000002c1,
2230x000002c2,0x000002ca,0x000200f8,0x000002ca,
2240x00050083,0x0000006c,0x000002cd,0x000002b5,
2250x00000627,0x0008000c,0x0000006c,0x000002d0,
2260x00000001,0x0000002b,0x000002cd,0x000002ad,
2270x000002bb,0x0006000c,0x0000006c,0x000002d2,
2280x00000001,0x00000008,0x000002d0,0x00050083,
2290x0000006c,0x000002d5,0x000002d0,0x000002d2,
2300x0004006e,0x00000010,0x000002d7,0x000002d2,
2310x00050081,0x0000006c,0x000002da,0x000002d2,
2320x00000628,0x0007000c,0x0000006c,0x000002dc,
2330x00000001,0x00000025,0x000002da,0x000002bb,
2340x0004006e,0x00000010,0x000002dd,0x000002dc,
2350x00050051,0x0000000f,0x000002df,0x000002d7,
2360x00000000,0x00050051,0x0000000f,0x000002e1,
2370x000002d7,0x00000001,0x0004003d,0x0000000d,
2380x00000348,0x000001e7,0x0007005f,0x00000014,
2390x0000034a,0x00000348,0x000002d7,0x00000002,
2400x00000054,0x00050051,0x0000000f,0x000002e6,
2410x000002dd,0x00000000,0x00050050,0x00000010,
2420x000002e9,0x000002e6,0x000002e1,0x0004003d,
2430x0000000d,0x00000360,0x000001e7,0x0007005f,
2440x00000014,0x00000362,0x00000360,0x000002e9,
2450x00000002,0x00000054,0x00050051,0x00000006,
2460x000002ed,0x000002d5,0x00000000,0x00070050,
2470x00000014,0x000002ee,0x000002ed,0x000002ed,
2480x000002ed,0x000002ed,0x0008000c,0x00000014,
2490x000002ef,0x00000001,0x0000002e,0x0000034a,
2500x00000362,0x000002ee,0x00050051,0x0000000f,
2510x000002f3,0x000002dd,0x00000001,0x00050050,
2520x00000010,0x000002f4,0x000002df,0x000002f3,
2530x0004003d,0x0000000d,0x00000378,0x000001e7,
2540x0007005f,0x00000014,0x0000037a,0x00000378,
2550x000002f4,0x00000002,0x00000054,0x0004003d,
2560x0000000d,0x00000390,0x000001e7,0x0007005f,
2570x00000014,0x00000392,0x00000390,0x000002dd,
2580x00000002,0x00000054,0x0008000c,0x00000014,
2590x00000301,0x00000001,0x0000002e,0x0000037a,
2600x00000392,0x000002ee,0x00050051,0x00000006,
2610x00000303,0x000002d5,0x00000001,0x00070050,
2620x00000014,0x00000304,0x00000303,0x00000303,
2630x00000303,0x00000303,0x0008000c,0x00000014,
2640x00000305,0x00000001,0x0000002e,0x000002ef,
2650x00000301,0x00000304,0x000200f9,0x0000031c,
2660x000200f8,0x000002c2,0x0006000c,0x0000006c,
2670x000002c4,0x00000001,0x00000008,0x000002b5,
2680x0008000c,0x0000006c,0x000002c7,0x00000001,
2690x0000002b,0x000002c4,0x000002ad,0x000002bb,
2700x0004006e,0x00000010,0x000002c8,0x000002c7,
2710x0004003d,0x0000000d,0x00000330,0x000001e7,
2720x0007005f,0x00000014,0x00000332,0x00000330,
2730x000002c8,0x00000002,0x00000054,0x000200f9,
2740x0000031c,0x000200f8,0x0000031c,0x000700f5,
2750x00000014,0x00000602,0x00000332,0x000002c2,
2760x00000305,0x000002ca,0x000500c7,0x0000001c,
2770x0000031e,0x000001eb,0x00000107,0x000500ab,
2780x00000012,0x0000031f,0x0000031e,0x00000094,
2790x000300f7,0x0000032a,0x00000000,0x000400fa,
2800x0000031f,0x00000320,0x0000032a,0x000200f8,
2810x00000320,0x0008004f,0x00000007,0x00000322,
2820x00000602,0x00000602,0x00000000,0x00000001,
2830x00000002,0x0008000c,0x00000007,0x000003a9,
2840x00000001,0x0000002b,0x00000322,0x00000101,
2850x0000062a,0x0005008e,0x00000007,0x000003ab,
2860x000003a9,0x0000003e,0x0007000c,0x00000007,
2870x000003ad,0x00000001,0x0000001a,0x000003a9,
2880x00000043,0x0005008e,0x00000007,0x000003ae,
2890x000003ad,0x00000040,0x00050083,0x00000007,
2900x000003b0,0x000003ae,0x0000062b,0x000500ba,
2910x0000004c,0x000003b2,0x000003a9,0x0000004b,
2920x000600a9,0x00000007,0x000003b3,0x000003b2,
2930x000003b0,0x000003ab,0x00050051,0x00000006,
2940x00000325,0x000003b3,0x00000000,0x00060052,
2950x00000014,0x000005d2,0x00000325,0x00000631,
2960x00000000,0x00050051,0x00000006,0x00000327,
2970x000003b3,0x00000001,0x00060052,0x00000014,
2980x000005d4,0x00000327,0x000005d2,0x00000001,
2990x00050051,0x00000006,0x00000329,0x000003b3,
3000x00000002,0x00060052,0x00000014,0x000005d6,
3010x00000329,0x000005d4,0x00000002,0x000200f9,
3020x0000032a,0x000200f8,0x0000032a,0x000700f5,
3030x00000014,0x00000604,0x00000602,0x0000031c,
3040x000005d6,0x00000320,0x000500c7,0x0000001c,
3050x000001fb,0x000001eb,0x000001fa,0x000500ab,
3060x00000012,0x000001fc,0x000001fb,0x00000094,
3070x0008004f,0x00000007,0x000001ff,0x00000604,
3080x00000604,0x00000000,0x00000001,0x00000002,
3090x000300f7,0x000003e0,0x00000000,0x000300fb,
3100x00000094,0x000003bd,0x000200f8,0x000003bd,
3110x00050041,0x0000017f,0x000003be,0x0000017d,
3120x0000017e,0x0004003d,0x0000001c,0x000003bf,
3130x000003be,0x000500ab,0x00000012,0x000003c0,
3140x000003bf,0x00000094,0x000500a4,0x00000012,
3150x000003c3,0x000001fc,0x000003c0,0x000300f7,
3160x000003c6,0x00000000,0x000400fa,0x000003c3,
3170x000003c4,0x000003c6,0x000200f8,0x000003c4,
3180x000200f9,0x000003e0,0x000200f8,0x000003c6,
3190x000400a8,0x00000012,0x000003c8,0x000001fc,
3200x000300f7,0x000003d4,0x00000000,0x000400fa,
3210x000003c8,0x000003c9,0x000003d4,0x000200f8,
3220x000003c9,0x0008000c,0x00000007,0x000003cd,
3230x00000001,0x0000002b,0x000001ff,0x00000101,
3240x0000062a,0x0007000c,0x00000007,0x000003ce,
3250x00000001,0x0000001a,0x000003cd,0x00000193,
3260x00050094,0x00000006,0x000003e5,0x00000153,
3270x000003ce,0x00050094,0x00000006,0x000003e7,
3280x00000159,0x000003ce,0x00050094,0x00000006,
3290x000003e9,0x0000015f,0x000003ce,0x00060050,
3300x00000007,0x000003ea,0x000003e5,0x000003e7,
3310x000003e9,0x00050041,0x00000198,0x000003d0,
3320x0000017d,0x00000197,0x0004003d,0x00000006,
3330x000003d1,0x000003d0,0x0005008e,0x00000007,
3340x000003d2,0x000003ea,0x000003d1,0x00050085,
3350x00000007,0x000003f0,0x000003d2,0x00000630,
3360x0008000c,0x00000007,0x000003f3,0x00000001,
3370x0000002b,0x000003f0,0x00000101,0x0000062a,
3380x0007000c,0x00000007,0x000003f4,0x00000001,
3390x0000001a,0x000003f3,0x00000140,0x0005008e,
3400x00000007,0x000003f6,0x000003f4,0x0000012b,
3410x00050081,0x00000007,0x000003f8,0x0000062d,
3420x000003f6,0x0005008e,0x00000007,0x000003fa,
3430x000003f4,0x0000012c,0x00050081,0x00000007,
3440x000003fc,0x0000062a,0x000003fa,0x00050088,
3450x00000007,0x000003fd,0x000003f8,0x000003fc,
3460x0007000c,0x00000007,0x000003fe,0x00000001,
3470x0000001a,0x000003fd,0x0000014c,0x000200f9,
3480x000003e0,0x000200f8,0x000003d4,0x0008000c,
3490x00000007,0x00000405,0x00000001,0x0000002b,
3500x000001ff,0x00000101,0x0000062a,0x0007000c,
3510x00000007,0x00000406,0x00000001,0x0000001a,
3520x00000405,0x00000122,0x00050083,0x00000007,
3530x00000409,0x00000406,0x0000062d,0x0007000c,
3540x00000007,0x0000040b,0x00000001,0x00000028,
3550x00000409,0x00000101,0x0005008e,0x00000007,
3560x0000040d,0x00000406,0x0000012c,0x00050083,
3570x00000007,0x0000040f,0x0000062e,0x0000040d,
3580x00050088,0x00000007,0x00000410,0x0000040b,
3590x0000040f,0x0007000c,0x00000007,0x00000411,
3600x00000001,0x0000001a,0x00000410,0x00000133,
3610x0005008e,0x00000007,0x00000412,0x00000411,
3620x00000124,0x00050094,0x00000006,0x00000416,
3630x00000168,0x00000412,0x00050094,0x00000006,
3640x00000418,0x0000016e,0x00000412,0x00050094,
3650x00000006,0x0000041a,0x00000174,0x00000412,
3660x00060050,0x00000007,0x0000041b,0x00000416,
3670x00000418,0x0000041a,0x00050041,0x00000198,
3680x000003d8,0x0000017d,0x00000197,0x0004003d,
3690x00000006,0x000003d9,0x000003d8,0x00060050,
3700x00000007,0x000003da,0x000003d9,0x000003d9,
3710x000003d9,0x00050088,0x00000007,0x000003db,
3720x0000041b,0x000003da,0x0008000c,0x00000007,
3730x000003de,0x00000001,0x0000002b,0x000003db,
3740x00000101,0x0000062a,0x0007000c,0x00000007,
3750x000003df,0x00000001,0x0000001a,0x000003de,
3760x000001ac,0x000200f9,0x000003e0,0x000200f8,
3770x000003e0,0x000900f5,0x00000007,0x00000605,
3780x000001ff,0x000003c4,0x000003fe,0x000003c9,
3790x000003df,0x000003d4,0x000200f9,0x000001e5,
3800x000200f8,0x000001e5,0x000700f5,0x00000007,
3810x0000061a,0x00000101,0x000001dc,0x00000605,
3820x000003e0,0x00050041,0x0000017f,0x00000203,
3830x0000017d,0x00000202,0x0004003d,0x0000001c,
3840x00000204,0x00000203,0x000500ac,0x00000012,
3850x00000205,0x00000204,0x00000097,0x000300f7,
3860x00000207,0x00000000,0x000400fa,0x00000205,
3870x00000206,0x00000207,0x000200f8,0x00000206,
3880x00050041,0x000001d4,0x0000020a,0x0000017d,
3890x00000209,0x0004003d,0x00000014,0x0000020b,
3900x0000020a,0x0007004f,0x0000006c,0x0000020c,
3910x0000020b,0x0000020b,0x00000000,0x00000001,
3920x000500be,0x000001d8,0x0000020d,0x000001d1,
3930x0000020c,0x0004009b,0x00000012,0x0000020e,
3940x0000020d,0x000200f9,0x00000207,0x000200f8,
3950x00000207,0x000700f5,0x00000012,0x0000020f,
3960x00000205,0x000001e5,0x0000020e,0x00000206,
3970x000300f7,0x00000211,0x00000000,0x000400fa,
3980x0000020f,0x00000210,0x00000211,0x000200f8,
3990x00000210,0x00050041,0x000001d4,0x00000213,
4000x0000017d,0x00000209,0x0004003d,0x00000014,
4010x00000214,0x00000213,0x0007004f,0x0000006c,
4020x00000215,0x00000214,0x00000214,0x00000002,
4030x00000003,0x000500b8,0x000001d8,0x00000216,
4040x000001d1,0x00000215,0x0004009b,0x00000012,
4050x00000217,0x00000216,0x000200f9,0x00000211,
4060x000200f8,0x00000211,0x000700f5,0x00000012,
4070x00000218,0x0000020f,0x00000207,0x00000217,
4080x00000210,0x000300f7,0x0000021a,0x00000000,
4090x000400fa,0x00000218,0x00000219,0x0000021a,
4100x000200f8,0x00000219,0x00050041,0x000001d4,
4110x00000220,0x0000017d,0x00000209,0x0004003d,
4120x00000014,0x00000221,0x00000220,0x00050041,
4130x000001d4,0x00000223,0x0000017d,0x0000021d,
4140x0004003d,0x00000014,0x00000224,0x00000223,
4150x00050041,0x0000017f,0x00000226,0x0000017d,
4160x0000021e,0x0004003d,0x0000001c,0x00000227,
4170x00000226,0x0007004f,0x0000006c,0x0000043a,
4180x00000221,0x00000221,0x00000000,0x00000001,
4190x00050083,0x0000006c,0x0000043b,0x000001d1,
4200x0000043a,0x0007004f,0x0000006c,0x0000043d,
4210x00000221,0x00000221,0x00000002,0x00000003,
4220x00050083,0x0000006c,0x00000440,0x0000043d,
4230x0000043a,0x00050088,0x0000006c,0x00000441,
4240x0000043b,0x00000440,0x0007004f,0x0000006c,
4250x00000443,0x00000224,0x00000224,0x00000000,
4260x00000001,0x0007004f,0x0000006c,0x00000446,
4270x00000224,0x00000224,0x00000002,0x00000003,
4280x00050083,0x0000006c,0x00000449,0x00000446,
4290x00000443,0x00050085,0x0000006c,0x0000044a,
4300x00000441,0x00000449,0x00050081,0x0000006c,
4310x0000044b,0x00000443,0x0000044a,0x00050083,
4320x0000006c,0x00000451,0x00000446,0x00000628,
4330x000500c7,0x0000001c,0x00000453,0x00000227,
4340x00000092,0x000500ab,0x00000012,0x00000454,
4350x00000453,0x00000094,0x000500c7,0x0000001c,
4360x00000456,0x00000227,0x00000097,0x000500ab,
4370x00000012,0x00000457,0x00000456,0x00000094,
4380x000300f7,0x000004b2,0x00000000,0x000400fa,
4390x00000457,0x00000458,0x00000460,0x000200f8,
4400x00000460,0x00050083,0x0000006c,0x00000463,
4410x0000044b,0x00000627,0x0008000c,0x0000006c,
4420x00000466,0x00000001,0x0000002b,0x00000463,
4430x00000443,0x00000451,0x0006000c,0x0000006c,
4440x00000468,0x00000001,0x00000008,0x00000466,
4450x00050083,0x0000006c,0x0000046b,0x00000466,
4460x00000468,0x0004006e,0x00000010,0x0000046d,
4470x00000468,0x00050081,0x0000006c,0x00000470,
4480x00000468,0x00000628,0x0007000c,0x0000006c,
4490x00000472,0x00000001,0x00000025,0x00000470,
4500x00000451,0x0004006e,0x00000010,0x00000473,
4510x00000472,0x00050051,0x0000000f,0x00000475,
4520x0000046d,0x00000000,0x00050051,0x0000000f,
4530x00000477,0x0000046d,0x00000001,0x0004003d,
4540x0000000d,0x000004de,0x0000021c,0x0007005f,
4550x00000014,0x000004e0,0x000004de,0x0000046d,
4560x00000002,0x00000054,0x000300f7,0x000004f0,
4570x00000000,0x000400fa,0x00000454,0x000004e2,
4580x000004ee,0x000200f8,0x000004ee,0x000200f9,
4590x000004f0,0x000200f8,0x000004e2,0x0008004f,
4600x00000007,0x000004e4,0x000004e0,0x000004e0,
4610x00000000,0x00000001,0x00000002,0x00050051,
4620x00000006,0x000004e6,0x000004e0,0x00000003,
4630x0005008e,0x00000007,0x000004e7,0x000004e4,
4640x000004e6,0x00050051,0x00000006,0x000004ea,
4650x000004e7,0x00000000,0x00050051,0x00000006,
4660x000004eb,0x000004e7,0x00000001,0x00050051,
4670x00000006,0x000004ec,0x000004e7,0x00000002,
4680x00070050,0x00000014,0x000004ed,0x000004ea,
4690x000004eb,0x000004ec,0x000004e6,0x000200f9,
4700x000004f0,0x000200f8,0x000004f0,0x000700f5,
4710x00000014,0x00000606,0x000004ed,0x000004e2,
4720x000004e0,0x000004ee,0x00050051,0x0000000f,
4730x0000047c,0x00000473,0x00000000,0x00050050,
4740x00000010,0x0000047f,0x0000047c,0x00000477,
4750x0004003d,0x0000000d,0x000004f6,0x0000021c,
4760x0007005f,0x00000014,0x000004f8,0x000004f6,
4770x0000047f,0x00000002,0x00000054,0x000300f7,
4780x00000508,0x00000000,0x000400fa,0x00000454,
4790x000004fa,0x00000506,0x000200f8,0x00000506,
4800x000200f9,0x00000508,0x000200f8,0x000004fa,
4810x0008004f,0x00000007,0x000004fc,0x000004f8,
4820x000004f8,0x00000000,0x00000001,0x00000002,
4830x00050051,0x00000006,0x000004fe,0x000004f8,
4840x00000003,0x0005008e,0x00000007,0x000004ff,
4850x000004fc,0x000004fe,0x00050051,0x00000006,
4860x00000502,0x000004ff,0x00000000,0x00050051,
4870x00000006,0x00000503,0x000004ff,0x00000001,
4880x00050051,0x00000006,0x00000504,0x000004ff,
4890x00000002,0x00070050,0x00000014,0x00000505,
4900x00000502,0x00000503,0x00000504,0x000004fe,
4910x000200f9,0x00000508,0x000200f8,0x00000508,
4920x000700f5,0x00000014,0x00000607,0x00000505,
4930x000004fa,0x000004f8,0x00000506,0x00050051,
4940x00000006,0x00000483,0x0000046b,0x00000000,
4950x00070050,0x00000014,0x00000484,0x00000483,
4960x00000483,0x00000483,0x00000483,0x0008000c,
4970x00000014,0x00000485,0x00000001,0x0000002e,
4980x00000606,0x00000607,0x00000484,0x00050051,
4990x0000000f,0x00000489,0x00000473,0x00000001,
5000x00050050,0x00000010,0x0000048a,0x00000475,
5010x00000489,0x0004003d,0x0000000d,0x0000050e,
5020x0000021c,0x0007005f,0x00000014,0x00000510,
5030x0000050e,0x0000048a,0x00000002,0x00000054,
5040x000300f7,0x00000520,0x00000000,0x000400fa,
5050x00000454,0x00000512,0x0000051e,0x000200f8,
5060x0000051e,0x000200f9,0x00000520,0x000200f8,
5070x00000512,0x0008004f,0x00000007,0x00000514,
5080x00000510,0x00000510,0x00000000,0x00000001,
5090x00000002,0x00050051,0x00000006,0x00000516,
5100x00000510,0x00000003,0x0005008e,0x00000007,
5110x00000517,0x00000514,0x00000516,0x00050051,
5120x00000006,0x0000051a,0x00000517,0x00000000,
5130x00050051,0x00000006,0x0000051b,0x00000517,
5140x00000001,0x00050051,0x00000006,0x0000051c,
5150x00000517,0x00000002,0x00070050,0x00000014,
5160x0000051d,0x0000051a,0x0000051b,0x0000051c,
5170x00000516,0x000200f9,0x00000520,0x000200f8,
5180x00000520,0x000700f5,0x00000014,0x00000608,
5190x0000051d,0x00000512,0x00000510,0x0000051e,
5200x0004003d,0x0000000d,0x00000526,0x0000021c,
5210x0007005f,0x00000014,0x00000528,0x00000526,
5220x00000473,0x00000002,0x00000054,0x000300f7,
5230x00000538,0x00000000,0x000400fa,0x00000454,
5240x0000052a,0x00000536,0x000200f8,0x00000536,
5250x000200f9,0x00000538,0x000200f8,0x0000052a,
5260x0008004f,0x00000007,0x0000052c,0x00000528,
5270x00000528,0x00000000,0x00000001,0x00000002,
5280x00050051,0x00000006,0x0000052e,0x00000528,
5290x00000003,0x0005008e,0x00000007,0x0000052f,
5300x0000052c,0x0000052e,0x00050051,0x00000006,
5310x00000532,0x0000052f,0x00000000,0x00050051,
5320x00000006,0x00000533,0x0000052f,0x00000001,
5330x00050051,0x00000006,0x00000534,0x0000052f,
5340x00000002,0x00070050,0x00000014,0x00000535,
5350x00000532,0x00000533,0x00000534,0x0000052e,
5360x000200f9,0x00000538,0x000200f8,0x00000538,
5370x000700f5,0x00000014,0x00000609,0x00000535,
5380x0000052a,0x00000528,0x00000536,0x0008000c,
5390x00000014,0x00000497,0x00000001,0x0000002e,
5400x00000608,0x00000609,0x00000484,0x00050051,
5410x00000006,0x00000499,0x0000046b,0x00000001,
5420x00070050,0x00000014,0x0000049a,0x00000499,
5430x00000499,0x00000499,0x00000499,0x0008000c,
5440x00000014,0x0000049b,0x00000001,0x0000002e,
5450x00000485,0x00000497,0x0000049a,0x000300f7,
5460x000004b1,0x00000000,0x000400fa,0x00000454,
5470x0000049d,0x000004b1,0x000200f8,0x0000049d,
5480x00050051,0x00000006,0x0000049f,0x0000049b,
5490x00000003,0x000500ba,0x00000012,0x000004a0,
5500x0000049f,0x00000038,0x000300f7,0x000004a9,
5510x00000000,0x000400fa,0x000004a0,0x000004a1,
5520x000004a8,0x000200f8,0x000004a8,0x000200f9,
5530x000004a9,0x000200f8,0x000004a1,0x0008004f,
5540x00000007,0x000004a3,0x0000049b,0x0000049b,
5550x00000000,0x00000001,0x00000002,0x00060050,
5560x00000007,0x000004a6,0x0000049f,0x0000049f,
5570x0000049f,0x00050088,0x00000007,0x000004a7,
5580x000004a3,0x000004a6,0x000200f9,0x000004a9,
5590x000200f8,0x000004a9,0x000700f5,0x00000007,
5600x0000060a,0x000004a7,0x000004a1,0x00000101,
5610x000004a8,0x00050051,0x00000006,0x000004ac,
5620x0000060a,0x00000000,0x00060052,0x00000014,
5630x000005ef,0x000004ac,0x0000049b,0x00000000,
5640x00050051,0x00000006,0x000004ae,0x0000060a,
5650x00000001,0x00060052,0x00000014,0x000005f1,
5660x000004ae,0x000005ef,0x00000001,0x00050051,
5670x00000006,0x000004b0,0x0000060a,0x00000002,
5680x00060052,0x00000014,0x000005f3,0x000004b0,
5690x000005f1,0x00000002,0x000200f9,0x000004b1,
5700x000200f8,0x000004b1,0x000700f5,0x00000014,
5710x0000060e,0x0000049b,0x00000538,0x000005f3,
5720x000004a9,0x000200f9,0x000004b2,0x000200f8,
5730x00000458,0x0006000c,0x0000006c,0x0000045a,
5740x00000001,0x00000008,0x0000044b,0x0008000c,
5750x0000006c,0x0000045d,0x00000001,0x0000002b,
5760x0000045a,0x00000443,0x00000451,0x0004006e,
5770x00000010,0x0000045e,0x0000045d,0x0004003d,
5780x0000000d,0x000004c6,0x0000021c,0x0007005f,
5790x00000014,0x000004c8,0x000004c6,0x0000045e,
5800x00000002,0x00000054,0x000200f9,0x000004b2,
5810x000200f8,0x000004b2,0x000700f5,0x00000014,
5820x0000060d,0x000004c8,0x00000458,0x0000060e,
5830x000004b1,0x000500c7,0x0000001c,0x000004b4,
5840x00000227,0x00000107,0x000500ab,0x00000012,
5850x000004b5,0x000004b4,0x00000094,0x000300f7,
5860x000004c0,0x00000000,0x000400fa,0x000004b5,
5870x000004b6,0x000004c0,0x000200f8,0x000004b6,
5880x0008004f,0x00000007,0x000004b8,0x0000060d,
5890x0000060d,0x00000000,0x00000001,0x00000002,
5900x0008000c,0x00000007,0x0000053f,0x00000001,
5910x0000002b,0x000004b8,0x00000101,0x0000062a,
5920x0005008e,0x00000007,0x00000541,0x0000053f,
5930x0000003e,0x0007000c,0x00000007,0x00000543,
5940x00000001,0x0000001a,0x0000053f,0x00000043,
5950x0005008e,0x00000007,0x00000544,0x00000543,
5960x00000040,0x00050083,0x00000007,0x00000546,
5970x00000544,0x0000062b,0x000500ba,0x0000004c,
5980x00000548,0x0000053f,0x0000004b,0x000600a9,
5990x00000007,0x00000549,0x00000548,0x00000546,
6000x00000541,0x00050051,0x00000006,0x000004bb,
6010x00000549,0x00000000,0x00060052,0x00000014,
6020x000005f5,0x000004bb,0x0000060d,0x00000000,
6030x00050051,0x00000006,0x000004bd,0x00000549,
6040x00000001,0x00060052,0x00000014,0x000005f7,
6050x000004bd,0x000005f5,0x00000001,0x00050051,
6060x00000006,0x000004bf,0x00000549,0x00000002,
6070x00060052,0x00000014,0x000005f9,0x000004bf,
6080x000005f7,0x00000002,0x000200f9,0x000004c0,
6090x000200f8,0x000004c0,0x000700f5,0x00000014,
6100x0000060f,0x0000060d,0x000004b2,0x000005f9,
6110x000004b6,0x000500c7,0x0000001c,0x0000022e,
6120x00000227,0x000001fa,0x000500ab,0x00000012,
6130x0000022f,0x0000022e,0x00000094,0x00050051,
6140x00000006,0x00000232,0x0000060f,0x00000003,
6150x0008000c,0x00000006,0x00000233,0x00000001,
6160x0000002b,0x00000232,0x00000038,0x00000039,
6170x00050041,0x0000017f,0x0000023a,0x0000017d,
6180x0000017e,0x0004003d,0x0000001c,0x0000023b,
6190x0000023a,0x000500ab,0x00000012,0x0000023c,
6200x0000023b,0x00000094,0x000500a4,0x00000012,
6210x0000023d,0x0000022f,0x0000023c,0x000300f7,
6220x0000023f,0x00000000,0x000400fa,0x0000023d,
6230x0000023e,0x00000243,0x000200f8,0x00000243,
6240x000500bc,0x00000012,0x00000247,0x00000233,
6250x00000038,0x000500a6,0x00000012,0x00000248,
6260x00000454,0x00000247,0x000300f7,0x0000024b,
6270x00000000,0x000400fa,0x00000248,0x0000024a,
6280x0000024e,0x000200f8,0x0000024e,0x0008004f,
6290x00000007,0x00000250,0x0000060f,0x0000060f,
6300x00000000,0x00000001,0x00000002,0x00060050,
6310x00000007,0x00000252,0x00000233,0x00000233,
6320x00000233,0x00050088,0x00000007,0x00000253,
6330x00000250,0x00000252,0x000200f9,0x0000024b,
6340x000200f8,0x0000024a,0x0008004f,0x00000007,
6350x0000024d,0x0000060f,0x0000060f,0x00000000,
6360x00000001,0x00000002,0x000200f9,0x0000024b,
6370x000200f8,0x0000024b,0x000700f5,0x00000007,
6380x00000610,0x0000024d,0x0000024a,0x00000253,
6390x0000024e,0x000300f7,0x00000576,0x00000000,
6400x000300fb,0x00000094,0x00000553,0x000200f8,
6410x00000553,0x000300f7,0x0000055c,0x00000000,
6420x000400fa,0x0000023d,0x0000055a,0x0000055c,
6430x000200f8,0x0000055a,0x000200f9,0x00000576,
6440x000200f8,0x0000055c,0x000400a8,0x00000012,
6450x0000055e,0x0000022f,0x000300f7,0x0000056a,
6460x00000000,0x000400fa,0x0000055e,0x0000055f,
6470x0000056a,0x000200f8,0x0000055f,0x0008000c,
6480x00000007,0x00000563,0x00000001,0x0000002b,
6490x00000610,0x00000101,0x0000062a,0x0007000c,
6500x00000007,0x00000564,0x00000001,0x0000001a,
6510x00000563,0x00000193,0x00050094,0x00000006,
6520x0000057b,0x00000153,0x00000564,0x00050094,
6530x00000006,0x0000057d,0x00000159,0x00000564,
6540x00050094,0x00000006,0x0000057f,0x0000015f,
6550x00000564,0x00060050,0x00000007,0x00000580,
6560x0000057b,0x0000057d,0x0000057f,0x00050041,
6570x00000198,0x00000566,0x0000017d,0x00000197,
6580x0004003d,0x00000006,0x00000567,0x00000566,
6590x0005008e,0x00000007,0x00000568,0x00000580,
6600x00000567,0x00050085,0x00000007,0x00000586,
6610x00000568,0x00000630,0x0008000c,0x00000007,
6620x00000589,0x00000001,0x0000002b,0x00000586,
6630x00000101,0x0000062a,0x0007000c,0x00000007,
6640x0000058a,0x00000001,0x0000001a,0x00000589,
6650x00000140,0x0005008e,0x00000007,0x0000058c,
6660x0000058a,0x0000012b,0x00050081,0x00000007,
6670x0000058e,0x0000062d,0x0000058c,0x0005008e,
6680x00000007,0x00000590,0x0000058a,0x0000012c,
6690x00050081,0x00000007,0x00000592,0x0000062a,
6700x00000590,0x00050088,0x00000007,0x00000593,
6710x0000058e,0x00000592,0x0007000c,0x00000007,
6720x00000594,0x00000001,0x0000001a,0x00000593,
6730x0000014c,0x000200f9,0x00000576,0x000200f8,
6740x0000056a,0x0008000c,0x00000007,0x0000059b,
6750x00000001,0x0000002b,0x00000610,0x00000101,
6760x0000062a,0x0007000c,0x00000007,0x0000059c,
6770x00000001,0x0000001a,0x0000059b,0x00000122,
6780x00050083,0x00000007,0x0000059f,0x0000059c,
6790x0000062d,0x0007000c,0x00000007,0x000005a1,
6800x00000001,0x00000028,0x0000059f,0x00000101,
6810x0005008e,0x00000007,0x000005a3,0x0000059c,
6820x0000012c,0x00050083,0x00000007,0x000005a5,
6830x0000062e,0x000005a3,0x00050088,0x00000007,
6840x000005a6,0x000005a1,0x000005a5,0x0007000c,
6850x00000007,0x000005a7,0x00000001,0x0000001a,
6860x000005a6,0x00000133,0x0005008e,0x00000007,
6870x000005a8,0x000005a7,0x00000124,0x00050094,
6880x00000006,0x000005ac,0x00000168,0x000005a8,
6890x00050094,0x00000006,0x000005ae,0x0000016e,
6900x000005a8,0x00050094,0x00000006,0x000005b0,
6910x00000174,0x000005a8,0x00060050,0x00000007,
6920x000005b1,0x000005ac,0x000005ae,0x000005b0,
6930x00050041,0x00000198,0x0000056e,0x0000017d,
6940x00000197,0x0004003d,0x00000006,0x0000056f,
6950x0000056e,0x00060050,0x00000007,0x00000570,
6960x0000056f,0x0000056f,0x0000056f,0x00050088,
6970x00000007,0x00000571,0x000005b1,0x00000570,
6980x0008000c,0x00000007,0x00000574,0x00000001,
6990x0000002b,0x00000571,0x00000101,0x0000062a,
7000x0007000c,0x00000007,0x00000575,0x00000001,
7010x0000001a,0x00000574,0x000001ac,0x000200f9,
7020x00000576,0x000200f8,0x00000576,0x000900f5,
7030x00000007,0x00000611,0x00000610,0x0000055a,
7040x00000594,0x0000055f,0x00000575,0x0000056a,
7050x000400a8,0x00000012,0x0000025b,0x00000454,
7060x000300f7,0x0000025d,0x00000000,0x000400fa,
7070x0000025b,0x0000025c,0x0000025d,0x000200f8,
7080x0000025c,0x0005008e,0x00000007,0x00000260,
7090x00000611,0x00000233,0x000200f9,0x0000025d,
7100x000200f8,0x0000025d,0x000700f5,0x00000007,
7110x00000613,0x00000611,0x00000576,0x00000260,
7120x0000025c,0x000200f9,0x0000023f,0x000200f8,
7130x0000023e,0x0008004f,0x00000007,0x00000242,
7140x0000060f,0x0000060f,0x00000000,0x00000001,
7150x00000002,0x000200f9,0x0000023f,0x000200f8,
7160x0000023f,0x000700f5,0x00000007,0x00000612,
7170x00000242,0x0000023e,0x00000613,0x0000025d,
7180x000300f7,0x00000264,0x00000000,0x000400fa,
7190x00000454,0x00000263,0x0000026a,0x000200f8,
7200x0000026a,0x00050083,0x00000006,0x0000026d,
7210x00000039,0x00000233,0x0005008e,0x00000007,
7220x0000026f,0x0000061a,0x0000026d,0x00050081,
7230x00000007,0x00000270,0x00000612,0x0000026f,
7240x000200f9,0x00000264,0x000200f8,0x00000263,
7250x00060050,0x00000007,0x00000268,0x00000233,
7260x00000233,0x00000233,0x0008000c,0x00000007,
7270x00000269,0x00000001,0x0000002e,0x0000061a,
7280x00000612,0x00000268,0x000200f9,0x00000264,
7290x000200f8,0x00000264,0x000700f5,0x00000007,
7300x00000625,0x00000269,0x00000263,0x00000270,
7310x0000026a,0x000200f9,0x0000021a,0x000200f8,
7320x0000021a,0x000700f5,0x00000007,0x00000626,
7330x0000061a,0x00000211,0x00000625,0x00000264,
7340x0004003d,0x00000272,0x00000275,0x00000274,
7350x00050051,0x00000006,0x00000278,0x00000626,
7360x00000000,0x00050051,0x00000006,0x00000279,
7370x00000626,0x00000001,0x00050051,0x00000006,
7380x0000027a,0x00000626,0x00000002,0x00070050,
7390x00000014,0x0000027b,0x00000278,0x00000279,
7400x0000027a,0x00000039,0x00040063,0x00000275,
7410x000001b7,0x0000027b,0x000200f9,0x0000027d,
7420x000200f8,0x0000027d,0x000100fd,0x00010038}
diff --git a/runtime/src/present_compose_spv.h b/runtime/src/present_compose_spv.h
new file mode 100644
index 000000000..966f31976
--- /dev/null
+++ b/runtime/src/present_compose_spv.h
@@ -0,0 +1,11 @@
1#pragma once
2#include <cstdint>
3
4namespace leonida {
5
6// present_compose.comp compiled with: glslc --target-env=vulkan1.1 -O -mfmt=c present_compose.comp -o present_compose.inc
7inline constexpr std::uint32_t present_compose_spirv[] =
8#include "present_compose.inc"
9;
10
11} // namespace leonida
diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h
new file mode 100644
index 000000000..32ef1eb1d
--- /dev/null
+++ b/runtime/src/queue_families.h
@@ -0,0 +1,48 @@
1#pragma once
2
3// Picking Vulkan queue families for D3D12's direct, compute and copy queues. Header-only and free of the rest of
4// the backend, so test harnesses can use it too.
5
6#include <vulkan/vulkan.h>
7
8#include <cstdint>
9#include <span>
10
11namespace leonida {
12
13// Queue families for D3D12's three queue types. Direct needs graphics. Compute prefers a family with compute and no
14// graphics (async compute), copy one with transfer and neither (a DMA engine); each falls back to a more capable
15// family, ending at the graphics one. A dedicated copy family is only used when its image transfer granularity is
16// 1x1x1, because D3D12 copies any box.
17struct QueueFamilies {
18 std::uint32_t direct = 0;
19 std::uint32_t compute = 0;
20 std::uint32_t copy = 0;
21};
22
23inline QueueFamilies pick_queue_families(std::span<const VkQueueFamilyProperties> families, std::uint32_t graphics) {
24 QueueFamilies out{graphics, graphics, graphics};
25 constexpr VkQueueFlags g = VK_QUEUE_GRAPHICS_BIT, c = VK_QUEUE_COMPUTE_BIT, t = VK_QUEUE_TRANSFER_BIT;
26 const auto fine_grained = [](const VkQueueFamilyProperties& f) {
27 return f.minImageTransferGranularity.width == 1 && f.minImageTransferGranularity.height == 1 &&
28 f.minImageTransferGranularity.depth == 1;
29 };
30 bool have_compute = false, have_copy = false;
31 for (std::uint32_t i = 0; i < families.size(); ++i) {
32 const auto& f = families[i];
33 if (!f.queueCount) continue;
34 if (!have_compute && (f.queueFlags & c) && !(f.queueFlags & g)) {
35 out.compute = i;
36 have_compute = true;
37 }
38 if (!have_copy && (f.queueFlags & t) && !(f.queueFlags & (g | c)) && fine_grained(f)) {
39 out.copy = i;
40 have_copy = true;
41 }
42 }
43 // No DMA family: copies go to the async-compute family, which can transfer too (compute implies transfer).
44 if (!have_copy && have_compute && fine_grained(families[out.compute])) out.copy = out.compute;
45 return out;
46}
47
48} // namespace leonida
diff --git a/runtime/src/resource_tiling.h b/runtime/src/resource_tiling.h
index e63f7ff45..84f77f747 100644
--- a/runtime/src/resource_tiling.h
+++ b/runtime/src/resource_tiling.h
@@ -13,9 +13,11 @@
13// AMD's PC runtime does on RDNA2 and RDNA4 (D3D-65; the console is AMD): 47 measured layouts, see 13// AMD's PC runtime does on RDNA2 and RDNA4 (D3D-65; the console is AMD): 47 measured layouts, see
14// resource_tiling_test. A standard mip may be smaller than a tile and then takes one tile on that axis. An NVIDIA 14// resource_tiling_test. A standard mip may be smaller than a tile and then takes one tile on that axis. An NVIDIA
15// GPU packs from the first mip smaller than a tile on any axis and WARP packs nothing; the test accepts all of 15// GPU packs from the first mip smaller than a tile on any axis and WARP packs nothing; the test accepts all of
16// them. The packed size is their tight 16// them. The packed tail takes one tile per tile-depth slice it spans: ceil(depth of the first packed mip / tile
17// linear size rounded up to whole tiles (at least one); NVIDIA sometimes reports one more. Applications read the 17// depth), so 1 for 2D, as AMD's PC runtime reports on RDNA2 and RDNA4 (83 measured layouts, see
18// numbers rather than assume them, and this layer backs reserved textures fully, so any split is consistent. 18// resource_tiling_test), and never fewer than the tail's tight linear size in whole tiles. NVIDIA sometimes reports
19// one more. Applications read the numbers rather than assume them, and this layer backs reserved textures fully, so
20// any split is consistent.
19 21
20#include <algorithm> 22#include <algorithm>
21#include <cstdint> 23#include <cstdint>
@@ -137,6 +139,7 @@ inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
137 // One array slice: standard mips while wider than half a tile or taller than a tile, then the packed tail. 139 // One array slice: standard mips while wider than half a tile or taller than a tile, then the packed tail.
138 std::vector<SubresourceTiling> slice(desc.mips); 140 std::vector<SubresourceTiling> slice(desc.mips);
139 std::uint64_t standard_tiles = 0, packed_bytes = 0; 141 std::uint64_t standard_tiles = 0, packed_bytes = 0;
142 std::uint32_t tail_depth = 0; // depth of the first packed mip
140 for (std::uint32_t mip = 0; mip < desc.mips; ++mip) { 143 for (std::uint32_t mip = 0; mip < desc.mips; ++mip) {
141 const std::uint64_t w = mip >= 64 ? 1 : std::max<std::uint64_t>(1, desc.width >> mip); 144 const std::uint64_t w = mip >= 64 ? 1 : std::max<std::uint64_t>(1, desc.width >> mip);
142 const std::uint32_t h = mip >= 32 ? 1u : std::max(1u, desc.height >> mip); 145 const std::uint32_t h = mip >= 32 ? 1u : std::max(1u, desc.height >> mip);
@@ -160,11 +163,15 @@ inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) {
160 up(w, desc.block) * up(h, desc.block) * desc.element_bytes * desc.samples; 163 up(w, desc.block) * up(h, desc.block) * desc.element_bytes * desc.samples;
161 if (d > (max_packed_bytes - packed_bytes) / row_slice_bytes) return false; 164 if (d > (max_packed_bytes - packed_bytes) / row_slice_bytes) return false;
162 packed_bytes += row_slice_bytes * d; 165 packed_bytes += row_slice_bytes * d;
166 if (result.packed_mips == 0) tail_depth = d;
163 ++result.packed_mips; 167 ++result.packed_mips;
164 } 168 }
165 } 169 }
170 // One tile per tile-depth slice of the tail (AMD), at least its tight size; 1 for 2D.
166 const std::uint64_t packed_tiles = 171 const std::uint64_t packed_tiles =
167 result.packed_mips ? std::max<std::uint64_t>(1, up(packed_bytes, tile_size_in_bytes)) : 0; 172 result.packed_mips ? std::max<std::uint64_t>({1, up(packed_bytes, tile_size_in_bytes),
173 up(tail_depth, result.shape.depth)})
174 : 0;
168 if (packed_tiles > max_tiles - standard_tiles) return false; 175 if (packed_tiles > max_tiles - standard_tiles) return false;
169 const std::uint64_t per_slice = standard_tiles + packed_tiles; 176 const std::uint64_t per_slice = standard_tiles + packed_tiles;
170 if (per_slice > max_tiles / layers) return false; 177 if (per_slice > max_tiles / layers) return false;
diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp
index 762dd704e..844f1b580 100644
--- a/runtime/src/root_signature.cpp
+++ b/runtime/src/root_signature.cpp
@@ -13,6 +13,10 @@ PackResult pack(const RootSignature& sig) {
13 } 13 }
14 uint64_t cost = 0; // 64-bit: a parameter of 0xFFFFFFFF constants must not wrap past the limits 14 uint64_t cost = 0; // 64-bit: a parameter of 0xFFFFFFFF constants must not wrap past the limits
15 for (const RootParameter& p : sig.params) { 15 for (const RootParameter& p : sig.params) {
16 if (p.type != ParamType::Constants && p.type != ParamType::Descriptor && p.type != ParamType::Table) {
17 out.error = "unknown root parameter type";
18 return out;
19 }
16 if (p.type == ParamType::Constants && p.num_values == 0) { 20 if (p.type == ParamType::Constants && p.num_values == 0) {
17 out.error = "root constant parameter needs at least 1 dword"; 21 out.error = "root constant parameter needs at least 1 dword";
18 return out; 22 return out;
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index c8c994451..5a02ed437 100644
--- a/runtime/src/shader_library.h
+++ b/runtime/src/shader_library.h
@@ -8,6 +8,8 @@
8// writes into `spirv/index.json`, next to `<name>.spv`. This header needs no Windows, Vulkan or third-party code: 8// writes into `spirv/index.json`, next to `<name>.spv`. This header needs no Windows, Vulkan or third-party code:
9// it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader. 9// it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader.
10 10
11#include "spirv_words.h"
12
11#include <algorithm> 13#include <algorithm>
12#include <array> 14#include <array>
13#include <cerrno> 15#include <cerrno>
@@ -636,7 +638,10 @@ struct ShaderEntry {
636 std::string wave64_exchange; 638 std::string wave64_exchange;
637 bool emulated() const { return !wave64_exchange.empty(); } 639 bool emulated() const { return !wave64_exchange.empty(); }
638 std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed 640 std::vector<SignatureElement> input_signature; // vertex shaders: what the input layout must feed
639 std::vector<std::uint32_t> outputs; // pixel shaders: the render-target locations written 641 std::vector<std::uint32_t> inputs; // pixel shaders: input locations declared
642 std::vector<std::uint32_t> outputs; // pixel/vertex shaders: output locations written
643 // --f16-interp-fallback: param/attr index -> {low_half_location, high_half_location} (SHADER-378).
644 std::map<std::uint32_t, std::array<std::uint32_t, 2>> f16_halves;
640}; 645};
641 646
642class ShaderLibrary { 647class ShaderLibrary {
@@ -717,13 +722,8 @@ public:
717 722
718 // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V. 723 // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V.
719 std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const { 724 std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const {
720 std::ifstream file(dir_ + "/" + entry.name + ".spv", std::ios::binary); 725 std::ifstream file(dir_ + "/" + entry.name + ".spv", std::ios::binary | std::ios::ate);
721 if (!file) return {}; 726 return read_spirv_words(file, file.tellg());
722 const std::string bytes((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
723 if (bytes.size() < 20 || bytes.size() % 4) return {};
724 std::vector<std::uint32_t> words(bytes.size() / 4);
725 std::memcpy(words.data(), bytes.data(), bytes.size());
726 return words[0] == 0x07230203 ? words : std::vector<std::uint32_t>{};
727 } 727 }
728 728
729private: 729private:
@@ -796,8 +796,19 @@ private:
796 e.input_signature.push_back(std::move(element)); 796 e.input_signature.push_back(std::move(element));
797 } 797 }
798 } 798 }
799 if (const Json* in = meta.find("inputs"); in && in->kind == Json::Kind::array)
800 for (const Json& item : in->array) e.inputs.push_back(u32(&item));
799 if (const Json* o = meta.find("outputs"); o && o->kind == Json::Kind::array) 801 if (const Json* o = meta.find("outputs"); o && o->kind == Json::Kind::array)
800 for (const Json& item : o->array) e.outputs.push_back(u32(&item)); 802 for (const Json& item : o->array) e.outputs.push_back(u32(&item));
803 if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) {
804 for (const auto& [key, val] : fh->object) {
805 if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue;
806 char* end = nullptr;
807 const unsigned long param = std::strtoul(key.c_str(), &end, 10);
808 if (!end || *end != '\0') continue;
809 e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])};
810 }
811 }
801 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); 812 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e);
802 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); 813 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
803 ++count_; 814 ++count_;
diff --git a/runtime/src/spirv_f16_halves.h b/runtime/src/spirv_f16_halves.h
new file mode 100644
index 000000000..5dffb64ed
--- /dev/null
+++ b/runtime/src/spirv_f16_halves.h
@@ -0,0 +1,617 @@
1#pragma once
2
3// Per-pipeline `--f16-interp-fallback` half placement and SPIR-V specialization (SHADER-378).
4//
5// Under `--f16-interp-fallback` (MoltenVK / devices without PerVertexKHR), a pixel shader reads decoded f16 halves
6// as ordinary smooth vec4 inputs recorded in `index.json` under `f16_halves: {param: [lo_loc, hi_loc]}`. When a
7// producer (VS) exports many params (up to 16) or a PS reads high attributes alongside f16 attributes, no fixed
8// static location map fits all pairs within MoltenVK's 30 locations (0..29, 124 output components counting
9// gl_Position). At graphics PSO creation, once both VS and PS are known, `link_f16_halves`:
10// 1. Fast-paths unchanged when every PS `f16_halves` entry is already exported at the exact same locations by VS.
11// 2. Chooses mutually non-colliding `[lo_loc, hi_loc]` slots in `0..top_location` (keeping PS locations unchanged
12// whenever they do not collide with any raw VS output; otherwise relocating PS `OpDecorate Location` in place).
13// 3. Specializes the VS SPIR-V binary for the pair: reuses matching static `f16_halves` outputs (updating their
14// `Location` decorations), demotes unneeded static `f16_halves` outputs to `Private` (freeing their locations),
15// and synthesizes `UnpackHalf2x16` half exports right before every `OpReturn` in the Vertex entry function for
16// any param the VS did not emit statically.
17//
18// Pure C++20 stdlib, no Vulkan or Windows headers required.
19
20#include "shader_library.h"
21
22#include <algorithm>
23#include <array>
24#include <cstdint>
25#include <map>
26#include <set>
27#include <span>
28#include <string>
29#include <vector>
30
31namespace leonida {
32
33namespace spirv_detail {
34
35constexpr std::uint32_t kSpirvMagic = 0x07230203u;
36constexpr std::uint32_t kSpirvVersion14 = 0x00010400u;
37
38constexpr std::uint16_t kOpSourceContinued = 2;
39constexpr std::uint16_t kOpSource = 3;
40constexpr std::uint16_t kOpSourceExtension = 4;
41constexpr std::uint16_t kOpName = 5;
42constexpr std::uint16_t kOpMemberName = 6;
43constexpr std::uint16_t kOpString = 7;
44constexpr std::uint16_t kOpExtension = 10;
45constexpr std::uint16_t kOpExtInstImport = 11;
46constexpr std::uint16_t kOpExtInst = 12;
47constexpr std::uint16_t kOpMemoryModel = 14;
48constexpr std::uint16_t kOpEntryPoint = 15;
49constexpr std::uint16_t kOpExecutionMode = 16;
50constexpr std::uint16_t kOpCapability = 17;
51constexpr std::uint16_t kOpTypeInt = 21;
52constexpr std::uint16_t kOpTypeFloat = 22;
53constexpr std::uint16_t kOpTypeVector = 23;
54constexpr std::uint16_t kOpTypePointer = 32;
55constexpr std::uint16_t kOpConstantNull = 46;
56constexpr std::uint16_t kOpFunction = 54;
57constexpr std::uint16_t kOpFunctionEnd = 56;
58constexpr std::uint16_t kOpVariable = 59;
59constexpr std::uint16_t kOpLoad = 61;
60constexpr std::uint16_t kOpStore = 62;
61constexpr std::uint16_t kOpAccessChain = 65;
62constexpr std::uint16_t kOpInBoundsAccessChain = 66;
63constexpr std::uint16_t kOpDecorate = 71;
64constexpr std::uint16_t kOpMemberDecorate = 72;
65constexpr std::uint16_t kOpDecorationGroup = 73;
66constexpr std::uint16_t kOpGroupDecorate = 74;
67constexpr std::uint16_t kOpGroupMemberDecorate = 75;
68constexpr std::uint16_t kOpCompositeConstruct = 80;
69constexpr std::uint16_t kOpCompositeExtract = 81;
70constexpr std::uint16_t kOpBitcast = 124;
71constexpr std::uint16_t kOpReturn = 253;
72constexpr std::uint16_t kOpModuleProcessed = 330;
73constexpr std::uint16_t kOpExecutionModeId = 331;
74constexpr std::uint16_t kOpDecorateId = 332;
75constexpr std::uint16_t kOpDecorateString = 5632;
76constexpr std::uint16_t kOpMemberDecorateString = 5633;
77
78constexpr std::uint32_t kExecModelVertex = 0;
79constexpr std::uint32_t kExecModelFragment = 4;
80
81constexpr std::uint32_t kStorageInput = 1;
82constexpr std::uint32_t kStorageOutput = 3;
83constexpr std::uint32_t kStoragePrivate = 6;
84
85constexpr std::uint32_t kDecorationLocation = 30;
86constexpr std::uint32_t kGlslUnpackHalf2x16 = 62;
87
88struct Inst {
89 std::uint16_t opcode = 0;
90 std::vector<std::uint32_t> words;
91};
92
93inline Inst make_inst(std::uint16_t opcode, std::initializer_list<std::uint32_t> operands) {
94 Inst inst;
95 inst.opcode = opcode;
96 inst.words.reserve(1 + operands.size());
97 inst.words.push_back((std::uint32_t(1 + operands.size()) << 16) | opcode);
98 for (std::uint32_t w : operands) inst.words.push_back(w);
99 return inst;
100}
101
102inline Inst make_inst_vec(std::uint16_t opcode, const std::vector<std::uint32_t>& operands) {
103 Inst inst;
104 inst.opcode = opcode;
105 inst.words.reserve(1 + operands.size());
106 inst.words.push_back((std::uint32_t(1 + operands.size()) << 16) | opcode);
107 inst.words.insert(inst.words.end(), operands.begin(), operands.end());
108 return inst;
109}
110
111struct Module {
112 std::array<std::uint32_t, 5> header{};
113 std::vector<Inst> insts;
114
115 bool parse(std::span<const std::uint32_t> words) {
116 if (words.size() < 5 || words[0] != kSpirvMagic || words[3] == 0) return false;
117 for (std::size_t i = 0; i < 5; ++i) header[i] = words[i];
118 insts.clear();
119 std::size_t pos = 5;
120 while (pos < words.size()) {
121 const std::uint32_t head = words[pos];
122 const std::uint32_t wc = head >> 16;
123 const std::uint16_t op = std::uint16_t(head & 0xffffu);
124 if (wc == 0 || pos + wc > words.size()) return false;
125 Inst inst;
126 inst.opcode = op;
127 inst.words.assign(words.begin() + std::ptrdiff_t(pos), words.begin() + std::ptrdiff_t(pos + wc));
128 insts.push_back(std::move(inst));
129 pos += wc;
130 }
131 return true;
132 }
133
134 std::vector<std::uint32_t> serialize() const {
135 std::size_t total = 5;
136 for (const Inst& inst : insts) total += inst.words.size();
137 std::vector<std::uint32_t> out;
138 out.reserve(total);
139 out.insert(out.end(), header.begin(), header.end());
140 for (const Inst& inst : insts) out.insert(out.end(), inst.words.begin(), inst.words.end());
141 return out;
142 }
143
144 std::uint32_t alloc_id() { return header[3]++; }
145};
146
147inline bool is_pre_type_opcode(std::uint16_t op) {
148 switch (op) {
149 case kOpCapability:
150 case kOpExtension:
151 case kOpExtInstImport:
152 case kOpMemoryModel:
153 case kOpEntryPoint:
154 case kOpExecutionMode:
155 case kOpExecutionModeId:
156 case kOpString:
157 case kOpSourceContinued:
158 case kOpSource:
159 case kOpSourceExtension:
160 case kOpName:
161 case kOpMemberName:
162 case kOpModuleProcessed:
163 case kOpDecorate:
164 case kOpMemberDecorate:
165 case kOpDecorationGroup:
166 case kOpGroupDecorate:
167 case kOpGroupMemberDecorate:
168 case kOpDecorateId:
169 case kOpDecorateString:
170 case kOpMemberDecorateString:
171 return true;
172 default:
173 return false;
174 }
175}
176
177inline std::string decode_literal_string(std::span<const std::uint32_t> words) {
178 std::string s;
179 for (std::uint32_t w : words) {
180 for (int b = 0; b < 4; ++b) {
181 const char c = char((w >> (8 * b)) & 0xffu);
182 if (c == '\0') return s;
183 s.push_back(c);
184 }
185 }
186 return s;
187}
188
189inline std::size_t entry_point_interface_start(const Inst& ep) {
190 // OpEntryPoint <ExecModel> <EntryPointId> <Name...> <InterfaceIds...>
191 for (std::size_t i = 3; i < ep.words.size(); ++i) {
192 const std::uint32_t w = ep.words[i];
193 if ((w & 0x000000ffu) == 0 || (w & 0x0000ff00u) == 0 || (w & 0x00ff0000u) == 0 || (w & 0xff000000u) == 0)
194 return i + 1;
195 }
196 return ep.words.size();
197}
198
199// Collects global OpVariables of `storage_class` that carry `OpDecorate <id> Location <loc>`.
200// Returns map: location -> variable_id (first variable found at that location).
201inline std::map<std::uint32_t, std::uint32_t> collect_located_vars(const Module& mod, std::uint32_t storage_class) {
202 std::map<std::uint32_t, std::uint32_t> var_storage;
203 for (const Inst& inst : mod.insts) {
204 if (inst.opcode == kOpFunction) break;
205 if (inst.opcode == kOpVariable && inst.words.size() >= 4) var_storage[inst.words[2]] = inst.words[3];
206 }
207 std::map<std::uint32_t, std::uint32_t> by_loc;
208 for (const Inst& inst : mod.insts) {
209 if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) {
210 const std::uint32_t target = inst.words[1];
211 const auto it = var_storage.find(target);
212 if (it != var_storage.end() && it->second == storage_class) by_loc.emplace(inst.words[3], target);
213 }
214 }
215 return by_loc;
216}
217
218} // namespace spirv_detail
219
220// Specializes/patches `vs_words` and (if needed) `ps_words` so that every entry in `ps_entry.f16_halves` is
221// exported by the VS at the exact smooth location the PS reads, within `0..top_location` (default 29, MoltenVK's
222// 124-component vertex output limit counting gl_Position).
223//
224// Returns true on success (including the no-op fast path when no patching is needed). On failure returns false and
225// writes a concise reason to `*error` if non-null; the caller's word vectors are only replaced on success.
226inline bool link_f16_halves(std::vector<std::uint32_t>& vs_words, const ShaderEntry& vs_entry,
227 std::vector<std::uint32_t>& ps_words, const ShaderEntry& ps_entry,
228 std::string* error = nullptr, std::uint32_t top_location = 29) {
229 const auto fail = [&](const std::string& msg) {
230 if (error) *error = msg;
231 return false;
232 };
233 if (ps_entry.f16_halves.empty()) return true;
234
235 // Fast path: every PS half pair is already exported at the exact same locations by VS.
236 bool already_linked = true;
237 for (const auto& [param, ps_pair] : ps_entry.f16_halves) {
238 const auto it = vs_entry.f16_halves.find(param);
239 if (it == vs_entry.f16_halves.end() || it->second != ps_pair) {
240 already_linked = false;
241 break;
242 }
243 }
244 if (already_linked) return true;
245
246 using namespace spirv_detail;
247 Module vs_mod, ps_mod;
248 if (!vs_mod.parse(vs_words)) return fail("f16_halves: malformed VS SPIR-V");
249 if (!ps_mod.parse(ps_words)) return fail("f16_halves: malformed PS SPIR-V");
250
251 const auto vs_outputs = collect_located_vars(vs_mod, kStorageOutput);
252 const auto ps_inputs = collect_located_vars(ps_mod, kStorageInput);
253
254 std::set<std::uint32_t> vs_static_half_locs;
255 for (const auto& [param, pair] : vs_entry.f16_halves) {
256 vs_static_half_locs.insert(pair[0]);
257 vs_static_half_locs.insert(pair[1]);
258 }
259 std::set<std::uint32_t> ps_static_half_locs;
260 for (const auto& [param, pair] : ps_entry.f16_halves) {
261 ps_static_half_locs.insert(pair[0]);
262 ps_static_half_locs.insert(pair[1]);
263 }
264
265 // Raw outputs of VS (all located Output variables excluding VS's own static f16_halves).
266 std::map<std::uint32_t, std::uint32_t> vs_raw_outputs;
267 std::set<std::uint32_t> vs_raw_locs;
268 for (const auto& [loc, var_id] : vs_outputs) {
269 if (!vs_static_half_locs.count(loc)) {
270 vs_raw_outputs[loc] = var_id;
271 vs_raw_locs.insert(loc);
272 }
273 }
274 std::set<std::uint32_t> ps_raw_locs;
275 for (const auto& [loc, var_id] : ps_inputs) {
276 if (!ps_static_half_locs.count(loc)) ps_raw_locs.insert(loc);
277 }
278
279 // Choose paired [lo, hi] locations for every param in ps_entry.f16_halves.
280 // Keep PS's existing locations unchanged whenever none collides with VS raw outputs or exceeds top_location.
281 bool keep_ps_locs = true;
282 std::set<std::uint32_t> seen_ps_halves;
283 for (const auto& [param, pair] : ps_entry.f16_halves) {
284 for (std::uint32_t loc : pair) {
285 if (loc > top_location || vs_raw_locs.count(loc) || !seen_ps_halves.insert(loc).second) {
286 keep_ps_locs = false;
287 break;
288 }
289 }
290 if (!keep_ps_locs) break;
291 }
292
293 std::map<std::uint32_t, std::array<std::uint32_t, 2>> pair_halves;
294 if (keep_ps_locs) {
295 pair_halves = ps_entry.f16_halves;
296 } else {
297 std::set<std::uint32_t> reserved = vs_raw_locs;
298 reserved.insert(ps_raw_locs.begin(), ps_raw_locs.end());
299 std::vector<std::uint32_t> free_locs;
300 for (std::int64_t loc = top_location; loc >= 0; --loc)
301 if (!reserved.count(std::uint32_t(loc))) free_locs.push_back(std::uint32_t(loc));
302 const std::size_t need = 2 * ps_entry.f16_halves.size();
303 if (free_locs.size() < need)
304 return fail("f16_halves: need " + std::to_string(need) + " free locations in 0.." +
305 std::to_string(top_location) + ", only " + std::to_string(free_locs.size()) + " available");
306 std::size_t k = 0;
307 for (const auto& [param, old_pair] : ps_entry.f16_halves) {
308 const std::uint32_t hi = free_locs[2 * k];
309 const std::uint32_t lo = free_locs[2 * k + 1];
310 pair_halves[param] = {lo, hi};
311 ++k;
312 }
313 }
314
315 // Patch PS OpDecorate Location in place if we relocated any PS half input.
316 bool ps_changed = false;
317 if (!keep_ps_locs) {
318 std::map<std::uint32_t, std::uint32_t> ps_var_new_loc;
319 for (const auto& [param, old_pair] : ps_entry.f16_halves) {
320 const auto& new_pair = pair_halves[param];
321 for (std::size_t h = 0; h < 2; ++h) {
322 const auto it = ps_inputs.find(old_pair[h]);
323 if (it != ps_inputs.end()) ps_var_new_loc[it->second] = new_pair[h];
324 }
325 }
326 for (Inst& inst : ps_mod.insts) {
327 if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) {
328 const auto it = ps_var_new_loc.find(inst.words[1]);
329 if (it != ps_var_new_loc.end() && inst.words[3] != it->second) {
330 inst.words[3] = it->second;
331 ps_changed = true;
332 }
333 }
334 }
335 }
336
337 // Inspect VS types, globals, entry point, and uses of existing static f16_halves variables.
338 std::uint32_t float_ty = 0, uint_ty = 0, v2float_ty = 0, v4float_ty = 0;
339 std::uint32_t ptr_out_v4_ty = 0, ptr_priv_v4_ty = 0, null_v4_id = 0, glsl_id = 0;
340 std::map<std::uint32_t, std::uint32_t> ptr_pointee; // ptr_type_id -> pointee_type_id
341 std::map<std::uint32_t, std::uint32_t> var_ptr_type; // var_id -> ptr_type_id
342 std::uint32_t vs_entry_fn = 0;
343 std::size_t vs_ep_idx = vs_mod.insts.size();
344
345 for (std::size_t idx = 0; idx < vs_mod.insts.size(); ++idx) {
346 const Inst& inst = vs_mod.insts[idx];
347 if (inst.opcode == kOpExtInstImport && inst.words.size() >= 3) {
348 if (decode_literal_string(std::span<const std::uint32_t>(inst.words).subspan(2)) == "GLSL.std.450")
349 glsl_id = inst.words[1];
350 } else if (inst.opcode == kOpEntryPoint && inst.words.size() >= 4 && inst.words[1] == kExecModelVertex) {
351 if (vs_ep_idx == vs_mod.insts.size()) {
352 vs_ep_idx = idx;
353 vs_entry_fn = inst.words[2];
354 }
355 } else if (inst.opcode == kOpTypeFloat && inst.words.size() == 3 && inst.words[2] == 32) {
356 float_ty = inst.words[1];
357 } else if (inst.opcode == kOpTypeInt && inst.words.size() == 4 && inst.words[2] == 32 && inst.words[3] == 0) {
358 uint_ty = inst.words[1];
359 } else if (inst.opcode == kOpTypeVector && inst.words.size() == 4) {
360 if (float_ty && inst.words[2] == float_ty && inst.words[3] == 2) v2float_ty = inst.words[1];
361 if (float_ty && inst.words[2] == float_ty && inst.words[3] == 4) v4float_ty = inst.words[1];
362 } else if (inst.opcode == kOpTypePointer && inst.words.size() == 4) {
363 ptr_pointee[inst.words[1]] = inst.words[3];
364 if (v4float_ty && inst.words[3] == v4float_ty) {
365 if (inst.words[2] == kStorageOutput) ptr_out_v4_ty = inst.words[1];
366 if (inst.words[2] == kStoragePrivate) ptr_priv_v4_ty = inst.words[1];
367 }
368 } else if (inst.opcode == kOpConstantNull && inst.words.size() == 3 && v4float_ty && inst.words[1] == v4float_ty) {
369 null_v4_id = inst.words[2];
370 } else if (inst.opcode == kOpVariable && inst.words.size() >= 4) {
371 var_ptr_type[inst.words[2]] = inst.words[1];
372 } else if (inst.opcode == kOpFunction) {
373 break;
374 }
375 }
376 if (vs_ep_idx == vs_mod.insts.size() || !vs_entry_fn) return fail("f16_halves: VS has no Vertex entry point");
377
378 // Check which existing VS variables are addressed by OpAccessChain (those cannot be trivially demoted to Private).
379 std::set<std::uint32_t> access_chained_vars;
380 for (const Inst& inst : vs_mod.insts) {
381 if ((inst.opcode == kOpAccessChain || inst.opcode == kOpInBoundsAccessChain) && inst.words.size() >= 4)
382 access_chained_vars.insert(inst.words[3]);
383 }
384
385 // Decide per VS static f16_halves entry: reuse (update Location) or demote (Output -> Private, drop Location).
386 std::map<std::uint32_t, std::uint32_t> vs_var_new_loc;
387 std::set<std::uint32_t> demote_vars;
388 std::set<std::uint32_t> satisfied_params;
389 for (const auto& [param, old_pair] : vs_entry.f16_halves) {
390 const auto lo_it = vs_outputs.find(old_pair[0]);
391 const auto hi_it = vs_outputs.find(old_pair[1]);
392 const auto want_it = pair_halves.find(param);
393 if (want_it != pair_halves.end() && lo_it != vs_outputs.end() && hi_it != vs_outputs.end()) {
394 vs_var_new_loc[lo_it->second] = want_it->second[0];
395 vs_var_new_loc[hi_it->second] = want_it->second[1];
396 satisfied_params.insert(param);
397 } else {
398 for (const auto& it : {lo_it, hi_it}) {
399 if (it == vs_outputs.end()) continue;
400 const std::uint32_t vid = it->second;
401 const auto pty = var_ptr_type.find(vid);
402 const bool is_v4 = pty != var_ptr_type.end() && v4float_ty && ptr_pointee[pty->second] == v4float_ty;
403 if (!is_v4 || access_chained_vars.count(vid))
404 return fail("f16_halves: cannot demote non-vec4 or access-chained VS static half output");
405 demote_vars.insert(vid);
406 }
407 }
408 }
409
410 // Params that must be synthesized in the VS epilogue.
411 struct SynthParam {
412 std::uint32_t param = 0;
413 std::uint32_t src_var = 0; // 0 if VS does not export this param (emit null vec4)
414 std::uint32_t lo_loc = 0;
415 std::uint32_t hi_loc = 0;
416 std::uint32_t lo_var = 0;
417 std::uint32_t hi_var = 0;
418 };
419 std::vector<SynthParam> synth;
420 bool need_null_v4 = false;
421 for (const auto& [param, target_pair] : pair_halves) {
422 if (satisfied_params.count(param)) continue;
423 SynthParam sp;
424 sp.param = param;
425 sp.lo_loc = target_pair[0];
426 sp.hi_loc = target_pair[1];
427 const auto raw_it = vs_raw_outputs.find(param);
428 if (raw_it != vs_raw_outputs.end()) {
429 const auto pty = var_ptr_type.find(raw_it->second);
430 if (pty == var_ptr_type.end() || !v4float_ty || ptr_pointee[pty->second] != v4float_ty)
431 return fail("f16_halves: VS param " + std::to_string(param) + " output is not vec4 float");
432 sp.src_var = raw_it->second;
433 } else {
434 need_null_v4 = true;
435 }
436 synth.push_back(sp);
437 }
438
439 // Create any missing types / GLSL.std.450 import needed for demotion or synthesis.
440 std::vector<Inst> new_types;
441 const bool need_glsl = std::any_of(synth.begin(), synth.end(), [](const SynthParam& s) { return s.src_var != 0; });
442 bool insert_glsl = false;
443 if (need_glsl && !glsl_id) {
444 glsl_id = vs_mod.alloc_id();
445 insert_glsl = true;
446 }
447 if ((!synth.empty() || !demote_vars.empty()) && !float_ty) {
448 float_ty = vs_mod.alloc_id();
449 new_types.push_back(make_inst(kOpTypeFloat, {float_ty, 32}));
450 }
451 if (need_glsl && !uint_ty) {
452 uint_ty = vs_mod.alloc_id();
453 new_types.push_back(make_inst(kOpTypeInt, {uint_ty, 32, 0}));
454 }
455 if (need_glsl && !v2float_ty) {
456 v2float_ty = vs_mod.alloc_id();
457 new_types.push_back(make_inst(kOpTypeVector, {v2float_ty, float_ty, 2}));
458 }
459 if ((!synth.empty() || !demote_vars.empty()) && !v4float_ty) {
460 v4float_ty = vs_mod.alloc_id();
461 new_types.push_back(make_inst(kOpTypeVector, {v4float_ty, float_ty, 4}));
462 }
463 if (!synth.empty() && !ptr_out_v4_ty) {
464 ptr_out_v4_ty = vs_mod.alloc_id();
465 new_types.push_back(make_inst(kOpTypePointer, {ptr_out_v4_ty, kStorageOutput, v4float_ty}));
466 }
467 if (!demote_vars.empty() && !ptr_priv_v4_ty) {
468 ptr_priv_v4_ty = vs_mod.alloc_id();
469 new_types.push_back(make_inst(kOpTypePointer, {ptr_priv_v4_ty, kStoragePrivate, v4float_ty}));
470 }
471 if (need_null_v4 && !null_v4_id) {
472 null_v4_id = vs_mod.alloc_id();
473 new_types.push_back(make_inst(kOpConstantNull, {v4float_ty, null_v4_id}));
474 }
475
476 // Allocate Output OpVariables for synthesized params.
477 std::vector<Inst> new_decorates;
478 std::vector<Inst> new_vars;
479 for (SynthParam& sp : synth) {
480 sp.lo_var = vs_mod.alloc_id();
481 sp.hi_var = vs_mod.alloc_id();
482 new_decorates.push_back(make_inst(kOpDecorate, {sp.lo_var, kDecorationLocation, sp.lo_loc}));
483 new_decorates.push_back(make_inst(kOpDecorate, {sp.hi_var, kDecorationLocation, sp.hi_loc}));
484 new_vars.push_back(make_inst(kOpVariable, {ptr_out_v4_ty, sp.lo_var, kStorageOutput}));
485 new_vars.push_back(make_inst(kOpVariable, {ptr_out_v4_ty, sp.hi_var, kStorageOutput}));
486 }
487
488 // Rebuild VS instruction stream in exact SPIR-V logical layout order.
489 // Demoted OpVariables are emitted right after new_types (before the first OpFunction) so ptr_priv_v4_ty is
490 // always defined before every OpVariable that uses it.
491 const bool drop_private_from_ep = vs_mod.header[1] < kSpirvVersion14;
492 std::vector<Inst> demoted_var_insts;
493 std::vector<Inst> out_insts;
494 out_insts.reserve(vs_mod.insts.size() + new_types.size() + new_decorates.size() + new_vars.size() +
495 synth.size() * 32);
496
497 bool glsl_inserted = !insert_glsl;
498 bool decorates_inserted = new_decorates.empty();
499 bool globals_inserted = new_types.empty() && new_vars.empty() && demote_vars.empty();
500 bool in_entry_fn = false;
501 bool found_entry_return = false;
502
503 for (std::size_t idx = 0; idx < vs_mod.insts.size(); ++idx) {
504 Inst inst = vs_mod.insts[idx];
505
506 // Insert OpExtInstImport "GLSL.std.450" right before OpMemoryModel if the module didn't already have it.
507 if (!glsl_inserted && inst.opcode == kOpMemoryModel) {
508 // "GLSL.std.450\0" -> 4 little-endian words: 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000
509 out_insts.push_back(
510 make_inst(kOpExtInstImport, {glsl_id, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u}));
511 glsl_inserted = true;
512 }
513
514 // Insert new OpDecorate instructions at the end of the Annotations section (before the first type/global).
515 if (!decorates_inserted && !is_pre_type_opcode(inst.opcode)) {
516 out_insts.insert(out_insts.end(), new_decorates.begin(), new_decorates.end());
517 decorates_inserted = true;
518 }
519
520 // Insert new Types / Constants, demoted Private OpVariables, and new Output OpVariables before OpFunction.
521 if (!globals_inserted && inst.opcode == kOpFunction) {
522 out_insts.insert(out_insts.end(), new_types.begin(), new_types.end());
523 out_insts.insert(out_insts.end(), demoted_var_insts.begin(), demoted_var_insts.end());
524 out_insts.insert(out_insts.end(), new_vars.begin(), new_vars.end());
525 globals_inserted = true;
526 }
527
528 // Update Vertex OpEntryPoint interface list.
529 if (idx == vs_ep_idx) {
530 const std::size_t if_start = entry_point_interface_start(inst);
531 std::vector<std::uint32_t> operands(inst.words.begin() + 1, inst.words.begin() + std::ptrdiff_t(if_start));
532 for (std::size_t i = if_start; i < inst.words.size(); ++i) {
533 const std::uint32_t id = inst.words[i];
534 if (drop_private_from_ep && demote_vars.count(id)) continue;
535 operands.push_back(id);
536 }
537 for (const SynthParam& sp : synth) {
538 operands.push_back(sp.lo_var);
539 operands.push_back(sp.hi_var);
540 }
541 out_insts.push_back(make_inst_vec(kOpEntryPoint, operands));
542 continue;
543 }
544
545 // Update or remove OpDecorate Location on static VS f16_halves outputs.
546 if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) {
547 const std::uint32_t target = inst.words[1];
548 if (demote_vars.count(target)) continue; // drop Location decoration from demoted Private variable
549 const auto it = vs_var_new_loc.find(target);
550 if (it != vs_var_new_loc.end()) inst.words[3] = it->second;
551 out_insts.push_back(std::move(inst));
552 continue;
553 }
554
555 // Demote unneeded static VS f16_halves OpVariable from Output to Private (emitted after new_types).
556 if (!globals_inserted && inst.opcode == kOpVariable && inst.words.size() >= 4 &&
557 demote_vars.count(inst.words[2])) {
558 inst.words[1] = ptr_priv_v4_ty;
559 inst.words[3] = kStoragePrivate;
560 demoted_var_insts.push_back(std::move(inst));
561 continue;
562 }
563
564 // Track Vertex entry function and inject UnpackHalf2x16 epilogue before every OpReturn inside it.
565 if (inst.opcode == kOpFunction && inst.words.size() >= 3 && inst.words[2] == vs_entry_fn) {
566 in_entry_fn = true;
567 } else if (inst.opcode == kOpFunctionEnd && in_entry_fn) {
568 in_entry_fn = false;
569 } else if (in_entry_fn && inst.opcode == kOpReturn && !synth.empty()) {
570 found_entry_return = true;
571 for (const SynthParam& sp : synth) {
572 if (sp.src_var == 0) {
573 out_insts.push_back(make_inst(kOpStore, {sp.lo_var, null_v4_id}));
574 out_insts.push_back(make_inst(kOpStore, {sp.hi_var, null_v4_id}));
575 continue;
576 }
577 const std::uint32_t raw_id = vs_mod.alloc_id();
578 out_insts.push_back(make_inst(kOpLoad, {v4float_ty, raw_id, sp.src_var}));
579 std::array<std::uint32_t, 4> lo_c{}, hi_c{};
580 for (std::uint32_t c = 0; c < 4; ++c) {
581 const std::uint32_t e_id = vs_mod.alloc_id();
582 const std::uint32_t u_id = vs_mod.alloc_id();
583 const std::uint32_t h2_id = vs_mod.alloc_id();
584 const std::uint32_t a_id = vs_mod.alloc_id();
585 const std::uint32_t b_id = vs_mod.alloc_id();
586 out_insts.push_back(make_inst(kOpCompositeExtract, {float_ty, e_id, raw_id, c}));
587 out_insts.push_back(make_inst(kOpBitcast, {uint_ty, u_id, e_id}));
588 out_insts.push_back(make_inst(kOpExtInst, {v2float_ty, h2_id, glsl_id, kGlslUnpackHalf2x16, u_id}));
589 out_insts.push_back(make_inst(kOpCompositeExtract, {float_ty, a_id, h2_id, 0}));
590 out_insts.push_back(make_inst(kOpCompositeExtract, {float_ty, b_id, h2_id, 1}));
591 lo_c[c] = a_id;
592 hi_c[c] = b_id;
593 }
594 const std::uint32_t lo_vec = vs_mod.alloc_id();
595 const std::uint32_t hi_vec = vs_mod.alloc_id();
596 out_insts.push_back(make_inst(kOpCompositeConstruct, {v4float_ty, lo_vec, lo_c[0], lo_c[1], lo_c[2], lo_c[3]}));
597 out_insts.push_back(make_inst(kOpCompositeConstruct, {v4float_ty, hi_vec, hi_c[0], hi_c[1], hi_c[2], hi_c[3]}));
598 out_insts.push_back(make_inst(kOpStore, {sp.lo_var, lo_vec}));
599 out_insts.push_back(make_inst(kOpStore, {sp.hi_var, hi_vec}));
600 }
601 }
602
603 out_insts.push_back(std::move(inst));
604 }
605
606 if (!synth.empty() && !found_entry_return)
607 return fail("f16_halves: Vertex entry point has no OpReturn to emit decoded halves");
608 if (!glsl_inserted || !decorates_inserted || !globals_inserted)
609 return fail("f16_halves: unexpected VS SPIR-V layout");
610
611 vs_mod.insts = std::move(out_insts);
612 vs_words = vs_mod.serialize();
613 if (ps_changed) ps_words = ps_mod.serialize();
614 return true;
615}
616
617} // namespace leonida
diff --git a/runtime/src/spirv_words.h b/runtime/src/spirv_words.h
new file mode 100644
index 000000000..e7e91fe5d
--- /dev/null
+++ b/runtime/src/spirv_words.h
@@ -0,0 +1,26 @@
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <istream>
6#include <vector>
7
8namespace leonida {
9
10// Checks the binary framing used by the translator and returns words aligned for Vulkan.
11// The caller still relies on the driver or spirv-val for instruction and capability validation.
12inline 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);
14 constexpr std::streamoff header_bytes = 5 * word_bytes;
15 if (byte_count < header_bytes || byte_count % word_bytes || !input.seekg(0)) return {};
16
17 std::uint32_t magic = 0;
18 if (!input.read(reinterpret_cast<char*>(&magic), word_bytes) || magic != 0x07230203) return {};
19
20 std::vector<std::uint32_t> words(static_cast<std::size_t>(byte_count / word_bytes));
21 words.front() = magic;
22 if (!input.read(reinterpret_cast<char*>(words.data() + 1), byte_count - word_bytes)) return {};
23 return words;
24}
25
26} // namespace leonida
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 140d7234b..1be77a0ca 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -17,6 +17,7 @@
17#include "vulkan_depth24.h" 17#include "vulkan_depth24.h"
18#include "vulkan_scratch.h" 18#include "vulkan_scratch.h"
19#include "vulkan_replay.h" 19#include "vulkan_replay.h"
20#include "queue_families.h"
20#include "resource_tiling.h" 21#include "resource_tiling.h"
21#include "xdxr_build.h" 22#include "xdxr_build.h"
22 23
@@ -80,7 +81,8 @@ struct VulkanDeviceFunctions {
80 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ 81 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \
81 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 82 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \
82 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 83 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
83 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) 84 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) \
85 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents)
84#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 86#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
85 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 87 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
86#undef LEONIDA_VK_MEMBER 88#undef LEONIDA_VK_MEMBER
@@ -202,7 +204,11 @@ public:
202 return vk_.vkCreatePipelineLayout(device_, &layout, nullptr, &layout_) == VK_SUCCESS; 204 return vk_.vkCreatePipelineLayout(device_, &layout, nullptr, &layout_) == VK_SUCCESS;
203 } 205 }
204 206
205 bool prepare(bool needs_sum, bool needs_binary, bool needs_statistics_sum = false) { 207 bool prepare(bool needs_sum, bool needs_binary, bool needs_statistics_sum = false,
208 bool needs_sum_binary = false) {
209 // The composite (sum then normalize, D3D-252) uses both pipelines.
210 needs_sum = needs_sum || needs_sum_binary;
211 needs_binary = needs_binary || needs_sum_binary;
206 return (!needs_sum || sum_pipeline_ || create_pipeline(occlusion_sum_spirv, sum_pipeline_)) && 212 return (!needs_sum || sum_pipeline_ || create_pipeline(occlusion_sum_spirv, sum_pipeline_)) &&
207 (!needs_binary || binary_pipeline_ || create_pipeline(binary_occlusion_spirv, binary_pipeline_)) && 213 (!needs_binary || binary_pipeline_ || create_pipeline(binary_occlusion_spirv, binary_pipeline_)) &&
208 (!needs_statistics_sum || statistics_pipeline_ || 214 (!needs_statistics_sum || statistics_pipeline_ ||
@@ -250,6 +256,31 @@ public:
250 copy_result(cb, dst, offset, word_size); 256 copy_result(cb, dst, offset, word_size);
251 } 257 }
252 258
259 // Sums `count` binary-occlusion segments into one value and normalizes that total in place to 0 or 1: the
260 // result of a binary query whose interval spans more than one physical segment (overlapping queries, D3D-252).
261 void sum_binary(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count,
262 VkBuffer dst, VkDeviceSize offset) const {
263 begin_scratch_write(cb);
264 vk_.vkCmdFillBuffer(cb, scratch_, 0, word_size, 0);
265 bind(cb, sum_pipeline_);
266 auto tail = first, left = count;
267 while (left) {
268 const auto chunk = std::min(left, sum_capacity);
269 vk_.vkCmdCopyQueryPoolResults(cb, queries, tail, chunk, scratch_, word_size, word_size,
270 VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
271 barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT,
272 shader_access);
273 dispatch(cb, chunk, 1);
274 tail += chunk;
275 left -= chunk;
276 if (left) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT);
277 }
278 barrier(cb, compute, compute, VK_ACCESS_SHADER_WRITE_BIT, shader_access);
279 bind(cb, binary_pipeline_);
280 dispatch(cb, 1, 1);
281 copy_result(cb, dst, offset, word_size);
282 }
283
253 void normalize(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, 284 void normalize(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count,
254 VkBuffer dst, VkDeviceSize offset) const { 285 VkBuffer dst, VkDeviceSize offset) const {
255 bind(cb, binary_pipeline_); 286 bind(cb, binary_pipeline_);
@@ -1002,6 +1033,10 @@ public:
1002 // (timestampValidBits 0). Set by the device before any queue uses it. 1033 // (timestampValidBits 0). Set by the device before any queue uses it.
1003 double timestamp_period() const { return timestamp_period_; } 1034 double timestamp_period() const { return timestamp_period_; }
1004 void set_timestamp_period(double period) { timestamp_period_ = period; } 1035 void set_timestamp_period(double period) { timestamp_period_ = period; }
1036 // True where a timestamp resolve must be ordered explicitly after the timestamps it copies (MoltenVK on Apple
1037 // GPUs, docs/d3d12_vulkan.md section 4.6). Set by the device before any queue uses it.
1038 bool order_timestamp_copies() const { return order_timestamp_copies_; }
1039 void set_order_timestamp_copies(bool order) { order_timestamp_copies_ = order; }
1005 1040
1006 // The device address of the GPU address arena: console VAs are offsets from it (docs section 3.3). 1041 // The device address of the GPU address arena: console VAs are offsets from it (docs section 3.3).
1007 // execute() copies replay_ under a shared resource_mutex_, so writers hold it uniquely. 1042 // execute() copies replay_ under a shared resource_mutex_, so writers hold it uniquely.
@@ -1115,6 +1150,8 @@ public:
1115 // `prepare` is called at the start of the command buffer of every ExecuteCommandLists, before the lists are 1150 // `prepare` is called at the start of the command buffer of every ExecuteCommandLists, before the lists are
1116 // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) 1151 // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h)
1117 // and records what the set needs first. When it fails, nothing of that call is executed. 1152 // and records what the set needs first. When it fails, nothing of that call is executed.
1153 void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; }
1154
1118 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { 1155 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) {
1119 std::unique_lock lock(resource_mutex_); 1156 std::unique_lock lock(resource_mutex_);
1120 bindless_prepare_ = std::move(prepare); 1157 bindless_prepare_ = std::move(prepare);
@@ -1289,11 +1326,13 @@ private:
1289 std::function<void(bool)> bindless_commit_; 1326 std::function<void(bool)> bindless_commit_;
1290 std::unordered_map<QueryHeapId, QueryPool> query_pools_; // element pointers stay valid across inserts 1327 std::unordered_map<QueryHeapId, QueryPool> query_pools_; // element pointers stay valid across inserts
1291 double timestamp_period_ = 0; 1328 double timestamp_period_ = 0;
1329 bool order_timestamp_copies_ = false;
1292 VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{}; 1330 VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{};
1293 ReplayFunctions replay_; 1331 ReplayFunctions replay_;
1294 std::unique_ptr<PredicateReducer> predicate_reducer_; 1332 std::unique_ptr<PredicateReducer> predicate_reducer_;
1295 std::unique_ptr<PredicatedBufferCopier> predicated_copier_; 1333 std::unique_ptr<PredicatedBufferCopier> predicated_copier_;
1296 std::uint32_t predicate_family_ = UINT32_MAX; 1334 std::uint32_t predicate_family_ = UINT32_MAX;
1335 std::uint32_t transfer_only_family_ = UINT32_MAX;
1297 DebugLabelFunctions labels_; 1336 DebugLabelFunctions labels_;
1298}; 1337};
1299#ifdef _MSC_VER 1338#ifdef _MSC_VER
@@ -1401,6 +1440,8 @@ public:
1401 } 1440 }
1402 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); 1441 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr);
1403 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); 1442 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr);
1443 for (auto& slot : buffers_) free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end());
1444 for (VkEvent event : free_events_) vk.vkDestroyEvent(context_.device(), event, nullptr);
1404 } 1445 }
1405 1446
1406 VulkanQueue(const VulkanQueue&) = delete; 1447 VulkanQueue(const VulkanQueue&) = delete;
@@ -1474,6 +1515,12 @@ public:
1474 // the layout tracker as it was. Pending Wait()s are attached to this submission. 1515 // the layout tracker as it was. Pending Wait()s are attached to this submission.
1475 ReplayResult execute(std::span<const CommandList* const> lists) { 1516 ReplayResult execute(std::span<const CommandList* const> lists) {
1476 if (context_.is_device_lost()) return ReplayResult::unsupported; 1517 if (context_.is_device_lost()) return ReplayResult::unsupported;
1518 if (kind_ != QueueKind::direct)
1519 for (const auto* list : lists)
1520 for (const auto& command : list->commands())
1521 if (std::holds_alternative<ClearRenderTarget>(command) ||
1522 std::holds_alternative<ClearDepthStencil>(command))
1523 return ReplayResult::unsupported;
1477 VkCommandBuffer command_buffer = VK_NULL_HANDLE; 1524 VkCommandBuffer command_buffer = VK_NULL_HANDLE;
1478 std::function<void(bool)> bindless_commit; 1525 std::function<void(bool)> bindless_commit;
1479 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. 1526 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_.
@@ -1500,12 +1547,16 @@ public:
1500 if (active && scratch) scratch->retire(progress, 0); 1547 if (active && scratch) scratch->retire(progress, 0);
1501 } 1548 }
1502 } scratch_guard{context_.scratch_.get(), progress_, false}; 1549 } scratch_guard{context_.scratch_.get(), progress_, false};
1503 bindless_commit = context_.bindless_commit_; 1550 const bool transfer_only = family_ == context_.transfer_only_family_;
1551 if (!transfer_only) bindless_commit = context_.bindless_commit_;
1504 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where 1552 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where
1505 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). 1553 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench).
1506 auto& prepared = prepared_; 1554 auto& prepared = prepared_;
1507 prepared.resize(lists.size()); 1555 prepared.resize(lists.size());
1508 ReplayFunctions replay = context_.replay_; 1556 ReplayFunctions replay = context_.replay_;
1557 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
1558 : kind_ == QueueKind::compute ? detail::queue_stages_compute
1559 : 0;
1509 std::uint64_t captures = 0; 1560 std::uint64_t captures = 0;
1510 for (const auto* list : lists) 1561 for (const auto* list : lists)
1511 for (const auto& command : list->commands()) 1562 for (const auto& command : list->commands())
@@ -1549,7 +1600,7 @@ public:
1549 return context_.scratch_->get(bytes, buffer, offset); 1600 return context_.scratch_->get(bytes, buffer, offset);
1550 }; 1601 };
1551 } 1602 }
1552 if (context_.depth24_) { 1603 if (context_.depth24_ && !transfer_only) {
1553 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, 1604 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
1554 std::vector<Depth24Job>& parts) { 1605 std::vector<Depth24Job>& parts) {
1555 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 1606 if (!tracker_lock.owns_lock()) tracker_lock.lock();
@@ -1575,6 +1626,10 @@ public:
1575 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 1626 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
1576 occlusion_resolve_->sum_statistics(cb, pool, first, count, dst, offset); 1627 occlusion_resolve_->sum_statistics(cb, pool, first, count, dst, offset);
1577 }; 1628 };
1629 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
1630 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
1631 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset);
1632 };
1578 } 1633 }
1579 const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; 1634 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
1580 std::uint32_t segments = 0, statistics_segments = 0; 1635 std::uint32_t segments = 0, statistics_segments = 0;
@@ -1621,19 +1676,38 @@ public:
1621 base += list.segment_count; 1676 base += list.segment_count;
1622 statistics_base += list.statistics_segment_count; 1677 statistics_base += list.statistics_segment_count;
1623 } 1678 }
1624 if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum) { 1679 if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum || queries.needs_sum_binary) {
1625 if (!occlusion_resolve_) { 1680 if (!occlusion_resolve_) {
1626 auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device()); 1681 auto helper = std::make_unique<OcclusionResolve>(context_.vk, context_.device());
1627 if (!helper->initialize(occlusion_memory)) return ReplayResult::unsupported; 1682 if (!helper->initialize(occlusion_memory)) return ReplayResult::unsupported;
1628 occlusion_resolve_ = std::move(helper); 1683 occlusion_resolve_ = std::move(helper);
1629 } 1684 }
1630 if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum)) 1685 if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum,
1686 queries.needs_sum_binary))
1631 return ReplayResult::unsupported; 1687 return ReplayResult::unsupported;
1632 } 1688 }
1633 1689
1634 CommandSlot* slot = acquire(); 1690 CommandSlot* slot = acquire();
1635 if (!slot) return ReplayResult::unsupported; 1691 if (!slot) return ReplayResult::unsupported;
1636 command_buffer = slot->buffer; 1692 command_buffer = slot->buffer;
1693 // MoltenVK writes a timestamp at the end of a Metal encoder and resolves it with a blit that nothing orders
1694 // after that write, so a copy in the same or the next command buffer reads the old value (docs section 4.6).
1695 // An event set and waited for in this command buffer orders it after this submission's timestamps; a wait for
1696 // this queue's previous submission orders it after earlier ones still running.
1697 bool ordered_timestamps = false;
1698 const auto& events = context_.vk;
1699 if (context_.order_timestamp_copies() && events.vkCreateEvent && events.vkDestroyEvent && events.vkResetEvent &&
1700 events.vkCmdSetEvent && events.vkCmdWaitEvents)
1701 replay.order_timestamp_copy = [this, slot, &ordered_timestamps](VkCommandBuffer cb) {
1702 const VkEvent event = take_event();
1703 if (!event) return;
1704 slot->events.push_back(event);
1705 const auto& vk = context_.vk;
1706 vk.vkCmdSetEvent(cb, event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1707 vk.vkCmdWaitEvents(cb, 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
1708 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 0, nullptr);
1709 ordered_timestamps = true;
1710 };
1637 const auto discard = [&] { 1711 const auto discard = [&] {
1638 if (context_.vk.vkResetCommandBuffer(command_buffer, 0) == VK_SUCCESS) slot->ticket = 0; 1712 if (context_.vk.vkResetCommandBuffer(command_buffer, 0) == VK_SUCCESS) slot->ticket = 0;
1639 }; 1713 };
@@ -1644,7 +1718,7 @@ public:
1644 return ReplayResult::unsupported; 1718 return ReplayResult::unsupported;
1645 } 1719 }
1646 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 1720 if (!tracker_lock.owns_lock()) tracker_lock.lock();
1647 if (context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { 1721 if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) {
1648 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 1722 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS;
1649 resource_lock.unlock(); 1723 resource_lock.unlock();
1650 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 1724 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
@@ -1730,6 +1804,11 @@ public:
1730 } 1804 }
1731 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; 1805 const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS;
1732 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 1806 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held
1807 const bool wait_previous = ordered_timestamps && submitted_;
1808 if (wait_previous) {
1809 waits_.push_back(progress_);
1810 wait_values_.push_back(submitted_);
1811 }
1733 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 1812 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
1734 if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission 1813 if (!submitted && !storage_images.empty()) { // not initialized after all: try again with the next submission
1735 std::lock_guard lock(context_.storage_mutex_); 1814 std::lock_guard lock(context_.storage_mutex_);
@@ -1742,6 +1821,10 @@ public:
1742 ++context_.storage_init_version_; 1821 ++context_.storage_init_version_;
1743 storage_init_seen_ = context_.storage_init_version_; 1822 storage_init_seen_ = context_.storage_init_version_;
1744 } 1823 }
1824 if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one
1825 waits_.pop_back();
1826 wait_values_.pop_back();
1827 }
1745 if (submitted) { 1828 if (submitted) {
1746 context_.tracker_ = std::move(next_tracker); 1829 context_.tracker_ = std::move(next_tracker);
1747 slot->predicate = std::move(batch); 1830 slot->predicate = std::move(batch);
@@ -1804,6 +1887,7 @@ private:
1804 VkCommandBuffer buffer; 1887 VkCommandBuffer buffer;
1805 std::uint64_t ticket; 1888 std::uint64_t ticket;
1806 std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments; 1889 std::vector<std::shared_ptr<const OcclusionSegmentPool>> segments;
1890 std::vector<VkEvent> events; // order_timestamp_copy's, reset and reused once the slot completes
1807 std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy; 1891 std::unique_ptr<PredicatedBufferCopier::Batch> predicated_copy;
1808 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes 1892 std::unique_ptr<PredicateReducer::Batch> predicate; // retained until this slot completes
1809 }; 1893 };
@@ -1913,6 +1997,10 @@ private:
1913 for (auto& slot : buffers_) { 1997 for (auto& slot : buffers_) {
1914 if (slot.ticket > done) continue; 1998 if (slot.ticket > done) continue;
1915 slot.segments.clear(); 1999 slot.segments.clear();
2000 for (VkEvent event : slot.events)
2001 if (context_.vk.vkResetEvent(context_.device(), event) == VK_SUCCESS) free_events_.push_back(event);
2002 else context_.vk.vkDestroyEvent(context_.device(), event, nullptr);
2003 slot.events.clear();
1916 if (!reuse) reuse = &slot; 2004 if (!reuse) reuse = &slot;
1917 } 2005 }
1918 if (reuse) { 2006 if (reuse) {
@@ -1933,6 +2021,20 @@ private:
1933 return &buffers_.back(); 2021 return &buffers_.back();
1934 } 2022 }
1935 2023
2024 // An unsignaled event for order_timestamp_copy, or null. MoltenVK decides when the command buffer is submitted
2025 // whether a set or wait does anything, from the event's state then, so each use gets an event of its own.
2026 VkEvent take_event() {
2027 if (!free_events_.empty()) {
2028 const VkEvent event = free_events_.back();
2029 free_events_.pop_back();
2030 return event;
2031 }
2032 VkEventCreateInfo info{VK_STRUCTURE_TYPE_EVENT_CREATE_INFO};
2033 VkEvent event = VK_NULL_HANDLE;
2034 if (context_.vk.vkCreateEvent(context_.device(), &info, nullptr, &event) != VK_SUCCESS) return VK_NULL_HANDLE;
2035 return event;
2036 }
2037
1936 bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { 2038 bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) {
1937 if (context_.is_device_lost()) return false; 2039 if (context_.is_device_lost()) return false;
1938 const std::uint64_t ticket = submitted_ + 1; 2040 const std::uint64_t ticket = submitted_ + 1;
@@ -2002,6 +2104,7 @@ private:
2002 VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done 2104 VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done
2003 std::uint64_t submitted_ = 0; 2105 std::uint64_t submitted_ = 0;
2004 std::vector<CommandSlot> buffers_; 2106 std::vector<CommandSlot> buffers_;
2107 std::vector<VkEvent> free_events_; // unsignaled, for order_timestamp_copy
2005 std::unique_ptr<OcclusionResolve> occlusion_resolve_; 2108 std::unique_ptr<OcclusionResolve> occlusion_resolve_;
2006 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for 2109 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for
2007 std::uint64_t last_sparse_ = 0; 2110 std::uint64_t last_sparse_ = 0;
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index 9a73d2f82..a2874b4b3 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -15,12 +15,18 @@
15// that follows the source (an sRGB source gets an sRGB swapchain, so the blit's decode and encode cancel; every 15// that follows the source (an sRGB source gets an sRGB swapchain, so the blit's decode and encode cancel; every
16// other source gets a UNORM one), and an optional capture that copies each presented frame to host memory. 16// other source gets a UNORM one), and an optional capture that copies each presented frame to host memory.
17// 17//
18// Plane composition (PresentX with placement, a filter, HDR10 or a second plane): present_planes() runs a compute pass
19// (present_compose.comp, vulkan_present_compose.h) over up to two textures into an RGBA16F image and copies that to the
20// swapchain; with an HDR10 plane and a surface that lists an ST.2084 format the swapchain is created in it. The plain
21// blit above is unchanged.
22//
18// Tearing on request (PresentX's ImmediateThresholdPercent): with VK_KHR_swapchain_maintenance1 (or the EXT original) 23// Tearing on request (PresentX's ImmediateThresholdPercent): with VK_KHR_swapchain_maintenance1 (or the EXT original)
19// the vsync swapchain is created with FIFO plus IMMEDIATE (FIFO_RELAXED when the surface cannot switch to IMMEDIATE), 24// the vsync swapchain is created with FIFO plus IMMEDIATE (FIFO_RELAXED when the surface cannot switch to IMMEDIATE),
20// and a present that asks for it is queued in that mode alone. Without the extension, or without either mode, a 25// and a present that asks for it is queued in that mode alone. Without the extension, or without either mode, a
21// request is ignored and the frame waits for the vblank. 26// request is ignored and the frame waits for the vblank.
22 27
23#include "vulkan_backend.h" 28#include "vulkan_backend.h"
29#include "vulkan_present_compose.h"
24 30
25// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. 31// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers.
26#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) 32#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME)
@@ -29,11 +35,13 @@
29 35
30#include <algorithm> 36#include <algorithm>
31#include <array> 37#include <array>
38#include <cmath>
32#include <cstdint> 39#include <cstdint>
33#include <cstdio> 40#include <cstdio>
34#include <cstring> 41#include <cstring>
35#include <functional> 42#include <functional>
36#include <map> 43#include <map>
44#include <memory>
37#include <vector> 45#include <vector>
38 46
39namespace leonida { 47namespace leonida {
@@ -43,6 +51,22 @@ struct PresentRect {
43 std::int32_t left, top, right, bottom; 51 std::int32_t left, top, right, bottom;
44}; 52};
45 53
54// One plane of present_planes(): a colour texture, the part of it shown, and where in the output it goes.
55struct PresentPlane {
56 ResourceId source{};
57 PresentRect source_rect{}; // texels; used when has_source_rect
58 bool has_source_rect = false;
59 float dest[4] = {0, 0, 1, 1}; // left, top, right, bottom as fractions of the output (0..1)
60 bool point_filter = false; // nearest texel; otherwise bilinear inside the source rectangle
61 bool hdr10 = false; // the texture holds ST.2084 (PQ) Rec.2020 values; otherwise G2.2 Rec.709 ones
62 bool straight_alpha = false; // plane 1 only: alpha is not premultiplied into the colour
63};
64struct PresentPlanes {
65 PresentPlane plane[2];
66 std::uint32_t count = 1;
67 float sdr_white_nits = 203.0f; // what SDR white maps to in an HDR10 output, and what HDR10 is divided by for SDR
68};
69
46namespace detail { 70namespace detail {
47inline bool is_srgb_format(VkFormat format) { 71inline bool is_srgb_format(VkFormat format) {
48 switch (format) { 72 switch (format) {
@@ -140,7 +164,9 @@ public:
140 release(swapchain_); 164 release(swapchain_);
141 swapchain_ = VK_NULL_HANDLE; 165 swapchain_ = VK_NULL_HANDLE;
142 release_capture(); 166 release_capture();
167 composer_.reset();
143 for (Frame& frame : frames_) { 168 for (Frame& frame : frames_) {
169 drop_views(frame);
144 if (frame.done) vkDestroyFence_(device, frame.done, nullptr); 170 if (frame.done) vkDestroyFence_(device, frame.done, nullptr);
145 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); 171 if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr);
146 } 172 }
@@ -200,6 +226,47 @@ public:
200 return submit(&binding, source, vsync, source_rect, detail::is_srgb_format(binding.format), tear); 226 return submit(&binding, source, vsync, source_rect, detail::is_srgb_format(binding.format), tear);
201 } 227 }
202 228
229 // PresentX with planes (docs section 4.5): one or two textures, each scaled from its source rectangle to its
230 // destination rectangle of the window, plane 1 blended over plane 0, composed by a compute pass into an RGBA16F image
231 // that is then copied to the swapchain image. Colour spaces are converted to the swapchain's: when a plane is HDR10 and
232 // the surface lists an HDR10 (ST.2084) format the swapchain uses it (hdr_active()), else the HDR10 planes are
233 // converted to SDR by clipping (no tone mapping). The swapchain is always UNORM here; sRGB-format sources are
234 // encoded again by the pass. Sources must be single-sample, sampled (no DENY_SHADER_RESOURCE) float/UNORM/sRGB
235 // colour textures; others are refused (VK_ERROR_FORMAT_NOT_SUPPORTED). Rectangles outside their range give
236 // VK_ERROR_UNKNOWN. vsync and `tear` as for present().
237 VkResult present_planes(const PresentPlanes& planes, bool vsync, bool tear = false) {
238 if (planes.count < 1 || planes.count > 2) return VK_ERROR_UNKNOWN;
239 if (!(planes.sdr_white_nits > 0.0f) || !std::isfinite(planes.sdr_white_nits)) return VK_ERROR_UNKNOWN;
240 for (std::uint32_t i = 0; i < planes.count; ++i) {
241 const PresentPlane& plane = planes.plane[i];
242 ResourceBinding binding;
243 {
244 std::shared_lock lock(context_.resource_mutex_);
245 const ResourceBinding* found = context_.resolve(plane.source);
246 if (!found || !found->image) return VK_ERROR_UNKNOWN;
247 binding = *found;
248 }
249 if (binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT || binding.samples > 1 || !binding.sampled || detail::blit_unsupported_format(binding.format) ||
250 !(format_features(binding.format) & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
251 return VK_ERROR_FORMAT_NOT_SUPPORTED;
252 const PresentRect& r = plane.source_rect;
253 if (plane.has_source_rect && (r.left < 0 || r.top < 0 || r.left >= r.right || r.top >= r.bottom ||
254 std::uint32_t(r.right) > binding.width || std::uint32_t(r.bottom) > binding.height))
255 return VK_ERROR_UNKNOWN;
256 const float* d = plane.dest;
257 if (!(d[0] >= 0.0f && d[0] < d[2] && d[2] <= 1.0f && d[1] >= 0.0f && d[1] < d[3] && d[3] <= 1.0f))
258 return VK_ERROR_UNKNOWN; // (also false for NaN)
259 }
260 return submit(nullptr, ResourceId{}, vsync, nullptr, false, tear, &planes);
261 }
262 // The swapchain holds HDR10 (ST.2084) values: a plane asked for it and the surface has the format.
263 bool hdr_active() const { return hdr_active_; }
264 // Presents that went through the compose pass (present_planes); plain blits and blank frames are not counted.
265 std::uint64_t composed_presents() const { return composed_; }
266 // Tests, on surfaces without HDR10: compose as if the output were HDR10 but write the PQ values into the (8-bit,
267 // UNORM) swapchain, so the encoder can be checked on any GPU. Takes effect with the next present_planes().
268 void force_hdr_encoding(bool on) { force_hdr_encoding_ = on; }
269
203 // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with 270 // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with
204 // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames. 271 // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames.
205 void set_abort(std::function<bool()> abort) { abort_ = std::move(abort); } 272 void set_abort(std::function<bool()> abort) { abort_ = std::move(abort); }
@@ -216,7 +283,7 @@ public:
216 if (!ok_) return false; 283 if (!ok_) return false;
217 capture_ = true; 284 capture_ = true;
218 stale_ = true; 285 stale_ = true;
219 if (!recreate(vsync_, swapchain_srgb_) || (swapchain_ && !capture_buffer_)) { 286 if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) {
220 capture_ = false; 287 capture_ = false;
221 return false; 288 return false;
222 } 289 }
@@ -236,22 +303,32 @@ public:
236 return true; 303 return true;
237 } 304 }
238 305
239 // Shared by present() and present_blank(). `binding` null: clear instead of blit. 306 // Shared by present(), present_blank() and present_planes(). `binding` null and `planes` null: clear instead of blit;
307 // `planes`: compose them (`binding`, `source`, `source_rect` unused).
240 VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, 308 VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect,
241 bool srgb, bool tear = false) { 309 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) {
242 last_tore_ = false; 310 last_tore_ = false;
243 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; 311 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED;
244 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_) { 312 // The swapchain's HDR10 format is only for composed planes that ask for it; a blit of an SDR source or a blank
313 // frame keeps whatever the swapchain has (black is black), except that a blit needs the SDR one.
314 bool want_hdr = swapchain_hdr_req_;
315 if (planes)
316 want_hdr = (planes->plane[0].hdr10) || (planes->count > 1 && planes->plane[1].hdr10);
317 else if (binding)
318 want_hdr = false;
319 if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_ || want_hdr != swapchain_hdr_req_) {
245 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed 320 // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed
246 // recreate is tried again at the next present. 321 // recreate is tried again at the next present.
247 if (!recreate(vsync, srgb)) return VK_ERROR_OUT_OF_DATE_KHR; 322 if (!recreate(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR;
248 } 323 }
249 if (!swapchain_) { // minimised: try again next frame 324 if (!swapchain_) { // minimised: try again next frame
250 stale_ = true; 325 stale_ = true;
251 return VK_SUCCESS; 326 return VK_SUCCESS;
252 } 327 }
253 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it 328 if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it
254 if (binding && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT)) return VK_ERROR_FORMAT_NOT_SUPPORTED; 329 if ((binding || planes) && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT))
330 return VK_ERROR_FORMAT_NOT_SUPPORTED;
331 if (planes && !prepare_compose()) return VK_ERROR_FORMAT_NOT_SUPPORTED;
255 auto& vk = context_.vk; 332 auto& vk = context_.vk;
256 const VkDevice device = context_.device(); 333 const VkDevice device = context_.device();
257 Frame& frame = frames_[frame_index_ % frames_.size()]; 334 Frame& frame = frames_[frame_index_ % frames_.size()];
@@ -261,18 +338,43 @@ public:
261 std::uint32_t image = 0; 338 std::uint32_t image = 0;
262 VkResult acquired = acquire(frame.acquired, &image); 339 VkResult acquired = acquire(frame.acquired, &image);
263 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { 340 if (acquired == VK_ERROR_OUT_OF_DATE_KHR) {
264 if (!recreate(vsync, swapchain_srgb_)) return acquired; 341 if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired;
265 if (!swapchain_) return VK_SUCCESS; 342 if (!swapchain_) return VK_SUCCESS;
266 acquired = acquire(frame.acquired, &image); 343 acquired = acquire(frame.acquired, &image);
267 } 344 }
268 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired 345 if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired
269 if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true; 346 if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true;
347 // An out-of-date retry above may have given the swapchain another extent: the compose target follows it.
348 if (planes && !prepare_compose()) return give_back(frame, VK_ERROR_FORMAT_NOT_SUPPORTED);
270 349
271 bool recorded = false; 350 bool recorded = false;
272 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 351 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
273 bool rollback_source = false; 352 bool rollback_source = false;
274 VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED; 353 VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED;
275 if (binding) { 354 std::array<RollbackPlane, 2> plane_rollbacks{}; // present_planes(): the same, per plane
355 if (planes) {
356 std::array<ResourceBinding, 2> current{};
357 bool found_all = true;
358 {
359 std::shared_lock resource_lock(context_.resource_mutex_);
360 for (std::uint32_t i = 0; i < planes->count; ++i) {
361 const ResourceBinding* found = context_.resolve(planes->plane[i].source);
362 if (found && found->image && found->aspects == VK_IMAGE_ASPECT_COLOR_BIT && found->sampled)
363 current[i] = *found;
364 else
365 found_all = false;
366 }
367 if (found_all) {
368 tracker_lock.lock();
369 for (std::uint32_t i = 0; i < planes->count; ++i) {
370 plane_rollbacks[i].id = planes->plane[i].source;
371 plane_rollbacks[i].tracked = context_.tracker_.tracked(plane_rollbacks[i].id);
372 if (plane_rollbacks[i].tracked) plane_rollbacks[i].layout = context_.tracker_.layout(plane_rollbacks[i].id, 0);
373 }
374 recorded = record_planes(frame, std::uint32_t(frame_index_ % frames_.size()), current, *planes, image);
375 }
376 }
377 } else if (binding) {
276 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h). 378 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h).
277 // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout 379 // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout
278 // rolls back a failed submit in O(1) without copying the entire LayoutTracker map. 380 // rolls back a failed submit in O(1) without copying the entire LayoutTracker map.
@@ -292,6 +394,11 @@ public:
292 const auto rollback = [&] { 394 const auto rollback = [&] {
293 if (rollback_source) 395 if (rollback_source)
294 context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout); 396 context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout);
397 if (planes)
398 for (std::uint32_t i = 0; i < planes->count; ++i)
399 if (plane_rollbacks[i].tracked)
400 context_.tracker_.set(plane_rollbacks[i].id, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
401 plane_rollbacks[i].layout);
295 }; 402 };
296 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable() 403 if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable()
297 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) { 404 if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) {
@@ -342,6 +449,7 @@ public:
342 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. 449 // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted.
343 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { 450 if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) {
344 ++presented_; 451 ++presented_;
452 if (planes) ++composed_;
345 if (tearing) { 453 if (tearing) {
346 last_tore_ = true; 454 last_tore_ = true;
347 ++tear_presents_; 455 ++tear_presents_;
@@ -364,6 +472,7 @@ private:
364 VkCommandBuffer commands = VK_NULL_HANDLE; 472 VkCommandBuffer commands = VK_NULL_HANDLE;
365 VkFence done = VK_NULL_HANDLE; 473 VkFence done = VK_NULL_HANDLE;
366 VkSemaphore acquired = VK_NULL_HANDLE; 474 VkSemaphore acquired = VK_NULL_HANDLE;
475 std::array<VkImageView, 2> views{}; // the plane views of the last composed present, until the frame is reused
367 }; 476 };
368 477
369 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image. 478 // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image.
@@ -462,6 +571,139 @@ private:
462 vk.vkEndCommandBuffer(commands); 571 vk.vkEndCommandBuffer(commands);
463 } 572 }
464 573
574 struct RollbackPlane {
575 ResourceId id{};
576 bool tracked = false;
577 VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED;
578 };
579
580 void drop_views(Frame& frame) {
581 for (VkImageView& view : frame.views)
582 if (view) context_.vk.vkDestroyImageView(context_.device(), view, nullptr);
583 frame.views = {};
584 }
585
586 // The compose pass and its target image, for the swapchain's current size.
587 bool prepare_compose() {
588 if (!composer_) {
589 VkPhysicalDeviceMemoryProperties memory{};
590 if (!vkGetPhysicalDeviceMemoryProperties_) return false;
591 vkGetPhysicalDeviceMemoryProperties_(physical_, &memory);
592 composer_ = std::make_unique<PresentComposer>(context_, memory);
593 }
594 if (!composer_->ready()) return false;
595 if (composer_->target() && composer_->extent().width == extent_.width &&
596 composer_->extent().height == extent_.height)
597 return true;
598 {
599 std::lock_guard lock(context_.submit_mutex());
600 context_.vk.vkQueueWaitIdle(queue_); // the old target may still be in use
601 }
602 bool changed = false;
603 return composer_->ensure_target(extent_, changed);
604 }
605
606 // Records the composition of `planes` and its copy to swapchain image `image`. False, with nothing recorded and the
607 // tracker untouched, when a view cannot be made. The caller holds the resource and tracker locks.
608 bool record_planes(Frame& frame, std::uint32_t slot, const std::array<ResourceBinding, 2>& current,
609 const PresentPlanes& planes, std::uint32_t image) {
610 auto& vk = context_.vk;
611 const ReplayFunctions& fn = context_.replay_;
612 if (composer_->target() == VK_NULL_HANDLE || composer_->extent().width != extent_.width ||
613 composer_->extent().height != extent_.height)
614 return false; // the target does not match the swapchain: nothing recorded
615 drop_views(frame);
616 for (std::uint32_t i = 0; i < planes.count; ++i) {
617 VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
618 view_info.image = current[i].image;
619 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
620 view_info.format = current[i].format;
621 view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
622 if (vk.vkCreateImageView(context_.device(), &view_info, nullptr, &frame.views[i]) != VK_SUCCESS) {
623 drop_views(frame);
624 return false;
625 }
626 }
627 if (planes.count == 1) frame.views[1] = VK_NULL_HANDLE; // the shader never reads it; plane 0's view is bound twice
628
629 VkCommandBuffer commands = frame.commands;
630 vk.vkResetCommandBuffer(commands, 0);
631 VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
632 begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
633 vk.vkBeginCommandBuffer(commands, &begin);
634
635 constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
636 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
637 const bool same = planes.count > 1 && planes.plane[1].source == planes.plane[0].source;
638 std::array<LayoutPieces, 2> pieces;
639 std::array<VkImageLayout, 2> read_layout{};
640 // Each distinct source: its PRESENT (common) layout, then readable by the compute pass. A never-written back buffer
641 // is zero-filled first, as any committed resource is.
642 for (std::uint32_t i = 0; i < planes.count; ++i) {
643 read_layout[i] = image_layout(current[i], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
644 if (i == 1 && same) continue;
645 const VkImageLayout common = image_layout(current[i], VK_IMAGE_LAYOUT_GENERAL);
646 pieces[i] = detail::current(&context_.tracker_, planes.plane[i].source, range, common);
647 detail::initialize(fn, commands, current[i], planes.plane[i].source, pieces[i], common, &context_.tracker_);
648 for (const auto& piece : pieces[i])
649 detail::image_barrier(fn, commands, current[i], piece.range, piece.layout, read_layout[i],
650 VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
651 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
652 }
653
654 // The pass: destinations in output pixels, sources in texels.
655 PresentComposePush push{};
656 const float out_w = float(extent_.width), out_h = float(extent_.height);
657 std::uint32_t* flags[2] = {&push.flags0, &push.flags1};
658 float* dest[2] = {push.dest0, push.dest1};
659 float* src[2] = {push.src0, push.src1};
660 for (std::uint32_t i = 0; i < planes.count; ++i) {
661 const PresentPlane& plane = planes.plane[i];
662 dest[i][0] = plane.dest[0] * out_w;
663 dest[i][1] = plane.dest[1] * out_h;
664 dest[i][2] = plane.dest[2] * out_w;
665 dest[i][3] = plane.dest[3] * out_h;
666 const PresentRect whole{0, 0, std::int32_t(current[i].width), std::int32_t(current[i].height)};
667 const PresentRect& r = plane.has_source_rect ? plane.source_rect : whole;
668 src[i][0] = float(r.left);
669 src[i][1] = float(r.top);
670 src[i][2] = float(r.right);
671 src[i][3] = float(r.bottom);
672 *flags[i] = (plane.point_filter ? compose_flag::point : 0u) |
673 (detail::is_srgb_format(current[i].format) ? compose_flag::srgb_source : 0u) |
674 (plane.hdr10 ? compose_flag::hdr10 : 0u) | (plane.straight_alpha ? compose_flag::straight_alpha : 0u);
675 }
676 push.plane_count = planes.count;
677 push.out_hdr = (hdr_active_ || force_hdr_encoding_) ? 1u : 0u;
678 push.sdr_white = planes.sdr_white_nits;
679 push.width = extent_.width;
680 push.height = extent_.height;
681 composer_->record(commands, slot, frame.views[0], read_layout[0], frame.views[1] ? frame.views[1] : frame.views[0],
682 read_layout[1] ? read_layout[1] : read_layout[0], push);
683
684 // The swapchain image, written by a copy of the composed image (same size: no scaling).
685 ResourceBinding target = target_of(image);
686 detail::image_barrier(fn, commands, target, range, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0,
687 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
688 VkImageBlit blit{};
689 blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
690 blit.srcOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1};
691 blit.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
692 blit.dstOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1};
693 vkCmdBlitImage_(commands, composer_->target(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image],
694 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
695 finish_image(commands, image);
696 for (std::uint32_t i = 0; i < planes.count; ++i) {
697 if (i == 1 && same) continue;
698 for (const auto& piece : pieces[i])
699 detail::image_barrier(fn, commands, current[i], piece.range, read_layout[i], piece.layout,
700 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, any,
701 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
702 }
703 vk.vkEndCommandBuffer(commands);
704 return true;
705 }
706
465 // vkGetPhysicalDeviceFormatProperties, optimal tiling, cached per format. 707 // vkGetPhysicalDeviceFormatProperties, optimal tiling, cached per format.
466 VkFormatFeatureFlags format_features(VkFormat format) { 708 VkFormatFeatureFlags format_features(VkFormat format) {
467 const auto it = features_.find(format); 709 const auto it = features_.find(format);
@@ -595,7 +837,7 @@ private:
595 // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no 837 // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no
596 // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and 838 // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and
597 // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again. 839 // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again.
598 bool recreate(bool vsync, bool srgb) { 840 bool recreate(bool vsync, bool srgb, bool hdr = false) {
599 auto& vk = context_.vk; 841 auto& vk = context_.vk;
600 const VkDevice device = context_.device(); 842 const VkDevice device = context_.device();
601 { 843 {
@@ -625,6 +867,8 @@ private:
625 swapchain_ = VK_NULL_HANDLE; 867 swapchain_ = VK_NULL_HANDLE;
626 vsync_ = vsync; 868 vsync_ = vsync;
627 swapchain_srgb_ = srgb; 869 swapchain_srgb_ = srgb;
870 swapchain_hdr_req_ = hdr;
871 hdr_active_ = false;
628 stale_ = false; 872 stale_ = false;
629 return true; 873 return true;
630 } 874 }
@@ -643,8 +887,28 @@ private:
643 // wants UNORM (the bytes go through as they are). BGRA before RGBA, as the surface lists them. 887 // wants UNORM (the bytes go through as they are). BGRA before RGBA, as the surface lists them.
644 VkSurfaceFormatKHR chosen = formats[0]; 888 VkSurfaceFormatKHR chosen = formats[0];
645 bool found = false; 889 bool found = false;
890 bool chose_hdr = false;
891 if (hdr) {
892 // A plane in HDR10 (PQ, Rec.2020): the surface's ST.2084 format, which needs VK_EXT_swapchain_colorspace on
893 // the instance. Without it the composition converts to SDR.
894 for (const VkFormat wanted : {VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_FORMAT_A2R10G10B10_UNORM_PACK32}) {
895 for (const auto& f : formats)
896 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT) {
897 chosen = f;
898 found = chose_hdr = true;
899 break;
900 }
901 if (found) break;
902 }
903 if (!found && !warned_hdr_) {
904 warned_hdr_ = true;
905 std::fprintf(stderr, "[rt] present: the surface has no HDR10 (ST.2084) format; HDR10 planes are converted to "
906 "SDR by clipping\n");
907 }
908 }
646 for (const VkFormat wanted : srgb ? std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB} 909 for (const VkFormat wanted : srgb ? std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB}
647 : std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}) { 910 : std::array<VkFormat, 2>{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}) {
911 if (chose_hdr) break;
648 for (const auto& f : formats) 912 for (const auto& f : formats)
649 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { 913 if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
650 chosen = f; 914 chosen = f;
@@ -739,14 +1003,18 @@ private:
739 ready_ = std::move(ready); 1003 ready_ = std::move(ready);
740 format_ = chosen.format; 1004 format_ = chosen.format;
741 extent_ = extent; 1005 extent_ = extent;
1006 hdr_active_ = chose_hdr;
742 if (capture_) { 1007 if (capture_) {
743 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. 1008 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set.
744 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || 1009 const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM ||
745 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB; 1010 format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB ||
1011 format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 ||
1012 format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32;
746 if (!four_bytes || !make_capture_buffer()) return false; 1013 if (!four_bytes || !make_capture_buffer()) return false;
747 } 1014 }
748 vsync_ = vsync; 1015 vsync_ = vsync;
749 swapchain_srgb_ = srgb; 1016 swapchain_srgb_ = srgb;
1017 swapchain_hdr_req_ = hdr;
750 stale_ = false; 1018 stale_ = false;
751 return true; 1019 return true;
752 } 1020 }
@@ -836,6 +1104,12 @@ private:
836 bool stale_ = false; 1104 bool stale_ = false;
837 bool ok_ = false; 1105 bool ok_ = false;
838 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists) 1106 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists)
1107 bool swapchain_hdr_req_ = false; // the swapchain was built for an HDR10 request (it has the format only if hdr_active_)
1108 bool hdr_active_ = false;
1109 std::uint64_t composed_ = 0;
1110 bool force_hdr_encoding_ = false;
1111 bool warned_hdr_ = false;
1112 std::unique_ptr<PresentComposer> composer_;
839 std::function<bool()> abort_; 1113 std::function<bool()> abort_;
840 std::function<VkExtent2D()> extent_fn_; 1114 std::function<VkExtent2D()> extent_fn_;
841 std::map<VkFormat, VkFormatFeatureFlags> features_; 1115 std::map<VkFormat, VkFormatFeatureFlags> features_;
diff --git a/runtime/src/vulkan_present_compose.h b/runtime/src/vulkan_present_compose.h
new file mode 100644
index 000000000..3fe834c1c
--- /dev/null
+++ b/runtime/src/vulkan_present_compose.h
@@ -0,0 +1,257 @@
1#pragma once
2
3// The compute pass behind PresentX's plane composition (docs/d3d12_vulkan.md section 4.5), used by VulkanPresenter::
4// present_planes(): up to two sampled planes in, each scaled from a source rectangle to a destination rectangle,
5// plane 1 blended over plane 0, colour spaces converted, the result in an RGBA16F image of the swapchain's size that the
6// presenter copies to the swapchain image. The shader is present_compose.comp (SPIR-V embedded, present_compose_spv.h).
7// Not thread safe: the presenter calls it with its own state locked, one present at a time.
8
9#include "vulkan_backend.h"
10#include "present_compose_spv.h"
11
12#include <array>
13#include <cstdint>
14#include <cstring>
15
16namespace leonida {
17
18// Mirrors the shader's push constants (96 bytes).
19struct PresentComposePush {
20 float dest0[4], dest1[4]; // destination rectangles in output pixels: left, top, right, bottom
21 float src0[4], src1[4]; // source rectangles in texels
22 std::uint32_t flags0, flags1, plane_count, out_hdr;
23 float sdr_white;
24 std::uint32_t width, height, pad;
25};
26static_assert(sizeof(PresentComposePush) == 96);
27
28namespace compose_flag {
29inline constexpr std::uint32_t point = 1, srgb_source = 2, hdr10 = 4, straight_alpha = 8;
30}
31
32class PresentComposer {
33public:
34 static constexpr std::uint32_t frame_slots = 2;
35
36 PresentComposer(VulkanContext& context, const VkPhysicalDeviceMemoryProperties& memory)
37 : context_(context), memory_(memory) {}
38
39 ~PresentComposer() {
40 const VkDevice device = context_.device();
41 auto& vk = context_.vk;
42 release_target();
43 if (pipeline_) vk.vkDestroyPipeline(device, pipeline_, nullptr);
44 if (pipeline_layout_) vk.vkDestroyPipelineLayout(device, pipeline_layout_, nullptr);
45 if (pool_) vk.vkDestroyDescriptorPool(device, pool_, nullptr); // frees its sets
46 if (set_layout_) vk.vkDestroyDescriptorSetLayout(device, set_layout_, nullptr);
47 }
48 PresentComposer(const PresentComposer&) = delete;
49 PresentComposer& operator=(const PresentComposer&) = delete;
50
51 // Builds the pipeline once; false when the device cannot (a function is missing, or creation fails).
52 bool ready() {
53 if (state_ != State::untried) return state_ == State::ready;
54 state_ = State::failed;
55 auto& vk = context_.vk;
56 const VkDevice device = context_.device();
57 if (!vk.vkCreateDescriptorSetLayout || !vk.vkCreateDescriptorPool || !vk.vkAllocateDescriptorSets ||
58 !vk.vkUpdateDescriptorSets || !vk.vkCreatePipelineLayout || !vk.vkCreateShaderModule ||
59 !vk.vkCreateComputePipelines || !vk.vkCmdBindPipeline || !vk.vkCmdBindDescriptorSets ||
60 !vk.vkCmdPushConstants || !vk.vkCmdDispatch || !vk.vkCreateImage || !vk.vkCreateImageView ||
61 !vk.vkAllocateMemory)
62 return false;
63 std::array<VkDescriptorSetLayoutBinding, 3> bindings{};
64 for (std::uint32_t i = 0; i < 3; ++i) {
65 bindings[i].binding = i;
66 bindings[i].descriptorType = i < 2 ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
67 bindings[i].descriptorCount = 1;
68 bindings[i].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
69 }
70 VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
71 set_info.bindingCount = std::uint32_t(bindings.size());
72 set_info.pBindings = bindings.data();
73 if (vk.vkCreateDescriptorSetLayout(device, &set_info, nullptr, &set_layout_) != VK_SUCCESS) return false;
74 const std::array<VkDescriptorPoolSize, 2> sizes{{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2 * frame_slots},
75 {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, frame_slots}}};
76 VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
77 pool_info.maxSets = frame_slots;
78 pool_info.poolSizeCount = std::uint32_t(sizes.size());
79 pool_info.pPoolSizes = sizes.data();
80 if (vk.vkCreateDescriptorPool(device, &pool_info, nullptr, &pool_) != VK_SUCCESS) return false;
81 std::array<VkDescriptorSetLayout, frame_slots> layouts;
82 layouts.fill(set_layout_);
83 VkDescriptorSetAllocateInfo allocate{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
84 allocate.descriptorPool = pool_;
85 allocate.descriptorSetCount = frame_slots;
86 allocate.pSetLayouts = layouts.data();
87 if (vk.vkAllocateDescriptorSets(device, &allocate, sets_.data()) != VK_SUCCESS) return false;
88 const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(PresentComposePush)};
89 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
90 layout_info.setLayoutCount = 1;
91 layout_info.pSetLayouts = &set_layout_;
92 layout_info.pushConstantRangeCount = 1;
93 layout_info.pPushConstantRanges = &push;
94 if (vk.vkCreatePipelineLayout(device, &layout_info, nullptr, &pipeline_layout_) != VK_SUCCESS) return false;
95 VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
96 module_info.codeSize = sizeof(present_compose_spirv);
97 module_info.pCode = present_compose_spirv;
98 VkShaderModule module = VK_NULL_HANDLE;
99 if (vk.vkCreateShaderModule(device, &module_info, nullptr, &module) != VK_SUCCESS) return false;
100 VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
101 pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0,
102 VK_SHADER_STAGE_COMPUTE_BIT, module, "main", nullptr};
103 pipeline_info.layout = pipeline_layout_;
104 const VkResult created =
105 vk.vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline_);
106 vk.vkDestroyShaderModule(device, module, nullptr);
107 if (created != VK_SUCCESS) return false;
108 state_ = State::ready;
109 return true;
110 }
111
112 // The RGBA16F image of `extent` the pass writes (storage + transfer source), made again when the extent changes.
113 // The caller has made the queue idle first when this returns after a change (changed() says so): the old image
114 // may still be in use.
115 bool ensure_target(VkExtent2D extent, bool& changed) {
116 changed = false;
117 if (image_ && extent_.width == extent.width && extent_.height == extent.height) return true;
118 changed = true;
119 release_target();
120 auto& vk = context_.vk;
121 const VkDevice device = context_.device();
122 VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
123 info.imageType = VK_IMAGE_TYPE_2D;
124 info.format = target_format;
125 info.extent = {extent.width, extent.height, 1};
126 info.mipLevels = 1;
127 info.arrayLayers = 1;
128 info.samples = VK_SAMPLE_COUNT_1_BIT;
129 info.tiling = VK_IMAGE_TILING_OPTIMAL;
130 info.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
131 info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
132 info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
133 if (vk.vkCreateImage(device, &info, nullptr, &image_) != VK_SUCCESS) return false;
134 VkMemoryRequirements requirements{};
135 vk.vkGetImageMemoryRequirements(device, image_, &requirements);
136 std::uint32_t type = UINT32_MAX;
137 for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i)
138 if ((requirements.memoryTypeBits & (1u << i)) &&
139 (memory_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) {
140 type = i;
141 break;
142 }
143 VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
144 allocate.allocationSize = requirements.size;
145 allocate.memoryTypeIndex = type;
146 if (type == UINT32_MAX || vk.vkAllocateMemory(device, &allocate, nullptr, &memory_object_) != VK_SUCCESS ||
147 vk.vkBindImageMemory(device, image_, memory_object_, 0) != VK_SUCCESS) {
148 release_target();
149 return false;
150 }
151 VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
152 view_info.image = image_;
153 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
154 view_info.format = target_format;
155 view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
156 if (vk.vkCreateImageView(device, &view_info, nullptr, &view_) != VK_SUCCESS) {
157 release_target();
158 return false;
159 }
160 extent_ = extent;
161 return true;
162 }
163
164 VkImage target() const { return image_; }
165 VkExtent2D extent() const { return extent_; }
166 static constexpr VkFormat target_format = VK_FORMAT_R16G16B16A16_SFLOAT;
167
168 // The binding the image barrier helpers take for the target.
169 ResourceBinding target_binding() const {
170 ResourceBinding binding{};
171 binding.image = image_;
172 binding.format = target_format;
173 binding.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
174 binding.width = extent_.width;
175 binding.height = extent_.height;
176 return binding;
177 }
178
179 // Records the dispatch into `commands`: the planes' views (`plane1` may repeat `plane0` for a single plane) are
180 // bound with the target, the target goes UNDEFINED -> GENERAL for the writes and ends in TRANSFER_SRC_OPTIMAL for
181 // the copy that follows. The planes themselves must be in SHADER_READ_ONLY_OPTIMAL (or GENERAL) already.
182 void record(VkCommandBuffer commands, std::uint32_t slot, VkImageView plane0, VkImageLayout layout0,
183 VkImageView plane1, VkImageLayout layout1,
184 const PresentComposePush& push) {
185 auto& vk = context_.vk;
186 const VkDevice device = context_.device();
187 const VkDescriptorSet set = sets_[slot % frame_slots];
188 std::array<VkDescriptorImageInfo, 3> images{};
189 images[0] = {VK_NULL_HANDLE, plane0, layout0};
190 images[1] = {VK_NULL_HANDLE, plane1, layout1};
191 images[2] = {VK_NULL_HANDLE, view_, VK_IMAGE_LAYOUT_GENERAL};
192 std::array<VkWriteDescriptorSet, 3> writes{};
193 for (std::uint32_t i = 0; i < 3; ++i) {
194 writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
195 writes[i].dstSet = set;
196 writes[i].dstBinding = i;
197 writes[i].descriptorCount = 1;
198 writes[i].descriptorType = i < 2 ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
199 writes[i].pImageInfo = &images[i];
200 }
201 vk.vkUpdateDescriptorSets(device, std::uint32_t(writes.size()), writes.data(), 0, nullptr);
202
203 VkImageMemoryBarrier to_write{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
204 to_write.srcAccessMask = 0; // the previous reader (a copy) only needs the execution dependency
205 to_write.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
206 to_write.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
207 to_write.newLayout = VK_IMAGE_LAYOUT_GENERAL;
208 to_write.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
209 to_write.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
210 to_write.image = image_;
211 to_write.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
212 vk.vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
213 VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &to_write);
214 vk.vkCmdBindPipeline(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
215 vk.vkCmdBindDescriptorSets(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout_, 0, 1, &set, 0, nullptr);
216 vk.vkCmdPushConstants(commands, pipeline_layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push);
217 vk.vkCmdDispatch(commands, (extent_.width + 7) / 8, (extent_.height + 7) / 8, 1);
218 VkImageMemoryBarrier to_read = to_write;
219 to_read.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
220 to_read.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
221 to_read.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
222 to_read.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
223 vk.vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0,
224 nullptr, 0, nullptr, 1, &to_read);
225 }
226
227
228private:
229 enum class State { untried, ready, failed };
230
231 void release_target() {
232 auto& vk = context_.vk;
233 const VkDevice device = context_.device();
234 if (view_) vk.vkDestroyImageView(device, view_, nullptr);
235 if (image_) vk.vkDestroyImage(device, image_, nullptr);
236 if (memory_object_) vk.vkFreeMemory(device, memory_object_, nullptr);
237 view_ = VK_NULL_HANDLE;
238 image_ = VK_NULL_HANDLE;
239 memory_object_ = VK_NULL_HANDLE;
240 extent_ = {};
241 }
242
243 VulkanContext& context_;
244 VkPhysicalDeviceMemoryProperties memory_;
245 State state_ = State::untried;
246 VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE;
247 VkDescriptorPool pool_ = VK_NULL_HANDLE;
248 std::array<VkDescriptorSet, frame_slots> sets_{};
249 VkPipelineLayout pipeline_layout_ = VK_NULL_HANDLE;
250 VkPipeline pipeline_ = VK_NULL_HANDLE;
251 VkImage image_ = VK_NULL_HANDLE;
252 VkDeviceMemory memory_object_ = VK_NULL_HANDLE;
253 VkImageView view_ = VK_NULL_HANDLE;
254 VkExtent2D extent_{};
255};
256
257} // namespace leonida
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index fd69ab91b..6bc59f326 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -87,6 +87,7 @@ struct ResourceBinding {
87 // bytes, and copies between it and a buffer are repacked by the depth24 pass (Depth24Job::rgb96). 87 // bytes, and copies between it and a buffer are repacked by the depth24 pass (Depth24Job::rgb96).
88 bool rgb96 = false; 88 bool rgb96 = false;
89 bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it 89 bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it
90 bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it
90 bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush 91 bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush
91 bool sparse_buffer = false; 92 bool sparse_buffer = false;
92}; 93};
@@ -773,6 +774,7 @@ struct ReplayFunctions {
773 PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; 774 PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr;
774 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. 775 // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported.
775 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers 776 PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers
777 VkPipelineStageFlags2 queue_stages = 0;
776 PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears 778 PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears
777 PFN_vkCmdEndRendering end_rendering = nullptr; 779 PFN_vkCmdEndRendering end_rendering = nullptr;
778 PFN_vkCmdClearAttachments clear_attachments = nullptr; 780 PFN_vkCmdClearAttachments clear_attachments = nullptr;
@@ -792,6 +794,9 @@ struct ReplayFunctions {
792 PFN_vkCmdEndQuery end_query = nullptr; 794 PFN_vkCmdEndQuery end_query = nullptr;
793 PFN_vkCmdWriteTimestamp write_timestamp = nullptr; 795 PFN_vkCmdWriteTimestamp write_timestamp = nullptr;
794 PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr; 796 PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr;
797 // Set only where a copy of timestamp results is not ordered after the timestamps written before it (MoltenVK on
798 // Apple GPUs, docs/d3d12_vulkan.md section 4.6): records what orders them, before each timestamp resolve.
799 std::function<void(VkCommandBuffer)> order_timestamp_copy;
795 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, VkDeviceSize)> 800 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, VkDeviceSize)>
796 sum_occlusion; 801 sum_occlusion;
797 PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches 802 PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches
@@ -826,6 +831,10 @@ struct ReplayFunctions {
826 // rendering: the segments of a statistics query split around resolves (D3D-162). 831 // rendering: the segments of a statistics query split around resolves (D3D-162).
827 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count, 832 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count,
828 VkBuffer dst, VkDeviceSize offset)> sum_statistics; 833 VkBuffer dst, VkDeviceSize offset)> sum_statistics;
834 // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional
835 // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252).
836 std::function<void(VkCommandBuffer, VkQueryPool, std::uint32_t first, std::uint32_t count,
837 VkBuffer dst, VkDeviceSize offset)> sum_binary_occlusion;
829 // VK_EXT_debug_utils, set only when the instance enabled it; debug markers are skipped without them. 838 // VK_EXT_debug_utils, set only when the instance enabled it; debug markers are skipped without them.
830 PFN_vkCmdInsertDebugUtilsLabelEXT insert_label = nullptr; 839 PFN_vkCmdInsertDebugUtilsLabelEXT insert_label = nullptr;
831 PFN_vkCmdBeginDebugUtilsLabelEXT begin_label = nullptr; 840 PFN_vkCmdBeginDebugUtilsLabelEXT begin_label = nullptr;
@@ -1101,6 +1110,36 @@ inline void clip(std::span<const Rect> rects, VkExtent2D extent, std::uint32_t l
1101 } 1110 }
1102} 1111}
1103 1112
1113inline constexpr VkPipelineStageFlags2 queue_stages_copy =
1114 VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT | VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT |
1115 VK_PIPELINE_STAGE_2_HOST_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT | VK_PIPELINE_STAGE_2_COPY_BIT;
1116inline constexpr VkPipelineStageFlags2 queue_stages_compute =
1117 queue_stages_copy | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT |
1118 VK_PIPELINE_STAGE_2_CLEAR_BIT;
1119
1120inline void restrict_to_queue(const ReplayFunctions& vk, VkPipelineStageFlags2& stages, VkAccessFlags2& access) {
1121 if (!vk.queue_stages) return;
1122 VkAccessFlags2 allowed = VK_ACCESS_2_TRANSFER_READ_BIT | VK_ACCESS_2_TRANSFER_WRITE_BIT |
1123 VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT | VK_ACCESS_2_HOST_READ_BIT |
1124 VK_ACCESS_2_HOST_WRITE_BIT;
1125 if (vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT)
1126 allowed |= VK_ACCESS_2_SHADER_READ_BIT | VK_ACCESS_2_SHADER_WRITE_BIT | VK_ACCESS_2_UNIFORM_READ_BIT |
1127 VK_ACCESS_2_SHADER_SAMPLED_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_READ_BIT |
1128 VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT | VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT;
1129 stages &= vk.queue_stages;
1130 if (!stages) stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT;
1131 access &= allowed;
1132}
1133
1134inline void restrict_to_queue(const ReplayFunctions& vk, VkPipelineStageFlags& stages, VkAccessFlags& access) {
1135 if (!vk.queue_stages) return;
1136 VkPipelineStageFlags2 s2 = stages;
1137 VkAccessFlags2 a2 = access;
1138 restrict_to_queue(vk, s2, a2);
1139 stages = static_cast<VkPipelineStageFlags>(s2 & 0xFFFFFFFFull);
1140 access = static_cast<VkAccessFlags>(a2 & 0xFFFFFFFFull);
1141}
1142
1104// A D3D12 barrier on a volume mip covers every W slice, including on devices with maintenance9. 1143// A D3D12 barrier on a volume mip covers every W slice, including on devices with maintenance9.
1105inline VkImageSubresourceRange layout_range(const ResourceBinding& resource, VkImageSubresourceRange range) { 1144inline VkImageSubresourceRange layout_range(const ResourceBinding& resource, VkImageSubresourceRange range) {
1106 if (resource.volume) range.layerCount = VK_REMAINING_ARRAY_LAYERS; 1145 if (resource.volume) range.layerCount = VK_REMAINING_ARRAY_LAYERS;
@@ -1111,6 +1150,8 @@ inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buf
1111 const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout, 1150 const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout,
1112 VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access, 1151 VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access,
1113 VkPipelineStageFlags dst_stages) { 1152 VkPipelineStageFlags dst_stages) {
1153 restrict_to_queue(vk, src_stages, src_access);
1154 restrict_to_queue(vk, dst_stages, dst_access);
1114 VkImageMemoryBarrier barrier{}; 1155 VkImageMemoryBarrier barrier{};
1115 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; 1156 barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1116 barrier.srcAccessMask = src_access; 1157 barrier.srcAccessMask = src_access;
@@ -1126,6 +1167,8 @@ inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buf
1126 1167
1127inline void memory_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkAccessFlags src_access, 1168inline void memory_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkAccessFlags src_access,
1128 VkPipelineStageFlags src_stages, VkAccessFlags dst_access, VkPipelineStageFlags dst_stages) { 1169 VkPipelineStageFlags src_stages, VkAccessFlags dst_access, VkPipelineStageFlags dst_stages) {
1170 restrict_to_queue(vk, src_stages, src_access);
1171 restrict_to_queue(vk, dst_stages, dst_access);
1129 VkMemoryBarrier barrier{}; 1172 VkMemoryBarrier barrier{};
1130 barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; 1173 barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
1131 barrier.srcAccessMask = src_access; 1174 barrier.srcAccessMask = src_access;
@@ -1152,7 +1195,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com
1152 const ResourceBinding& resource, const VkImageSubresourceRange& range, 1195 const ResourceBinding& resource, const VkImageSubresourceRange& range,
1153 VkImageLayout dst_layout) { 1196 VkImageLayout dst_layout) {
1154 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); 1197 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1155 if (fmt.block <= 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false; 1198 if (fmt.block < 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false;
1156 const std::uint32_t mip_begin = range.baseMipLevel; 1199 const std::uint32_t mip_begin = range.baseMipLevel;
1157 const std::uint32_t mip_end = 1200 const std::uint32_t mip_end =
1158 range.levelCount == VK_REMAINING_MIP_LEVELS ? resource.mip_levels 1201 range.levelCount == VK_REMAINING_MIP_LEVELS ? resource.mip_levels
@@ -1296,8 +1339,10 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer
1296 for (auto& piece : pieces) { 1339 for (auto& piece : pieces) {
1297 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; 1340 if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue;
1298 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); 1341 const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT);
1299 const bool compressed = fmt.block > 1; 1342 const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT;
1300 if (resource.not_zeroed) { 1343 const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color);
1344 const bool compressed = fmt.block > 1 || (!can_clear && color);
1345 if (resource.not_zeroed || (!can_clear && !color)) {
1301 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, 1346 image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0,
1302 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); 1347 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1303 } else if (compressed) { 1348 } else if (compressed) {
@@ -1498,21 +1543,46 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
1498 if (block > 1) { 1543 if (block > 1) {
1499 // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip. 1544 // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip.
1500 // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the 1545 // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the
1501 // extent is cut where it reaches an edge, and a copy that cannot satisfy both images is refused. 1546 // extent is cut where it reaches an edge, and a copy that cannot satisfy both images is staged (below).
1502 if ((box.left | box.top | copy.x | copy.y) % block || box.left >= from.width || box.top >= from.height || 1547 if ((box.left | box.top | copy.x | copy.y) % block || box.left >= from.width || box.top >= from.height ||
1503 copy.x >= padded(to.width) || copy.y >= padded(to.height)) 1548 copy.x >= padded(to.width) || copy.y >= padded(to.height))
1504 return ReplayResult::invalid_copy; 1549 return ReplayResult::invalid_copy;
1505 w = padded(w); 1550 w = padded(w);
1506 h = padded(h); 1551 h = padded(h);
1507 if (w > padded(to.width) - copy.x || h > padded(to.height) - copy.y) return ReplayResult::invalid_copy; 1552 if (w > padded(to.width) - copy.x || h > padded(to.height) - copy.y) return ReplayResult::invalid_copy;
1508 w = std::min({w, from.width - box.left, to.width - copy.x}); 1553 // Each image's own extent: the whole blocks, cut where they reach that image's edge.
1509 h = std::min({h, from.height - box.top, to.height - copy.y}); 1554 const std::uint32_t src_w = std::min(w, from.width - box.left), src_h = std::min(h, from.height - box.top);
1555 const std::uint32_t dst_w = std::min(w, to.width - copy.x), dst_h = std::min(h, to.height - copy.y);
1556 const std::uint32_t blocks_w = w, blocks_h = h;
1557 w = std::min(src_w, dst_w);
1558 h = std::min(src_h, dst_h);
1510 const auto fits = [block](std::uint32_t offset, std::uint32_t extent, std::uint32_t size) { 1559 const auto fits = [block](std::uint32_t offset, std::uint32_t extent, std::uint32_t size) {
1511 return extent % block == 0 || offset + extent == size; 1560 return extent % block == 0 || offset + extent == size;
1512 }; 1561 };
1513 if (!fits(box.left, w, from.width) || !fits(copy.x, w, to.width) || !fits(box.top, h, from.height) || 1562 if (!fits(box.left, w, from.width) || !fits(copy.x, w, to.width) || !fits(box.top, h, from.height) ||
1514 !fits(copy.y, h, to.height)) 1563 !fits(copy.y, h, to.height)) {
1515 return ReplayResult::invalid_copy; 1564 // No one extent does for both images: a mip edge inside a block on one side only (a 4x4 box into a
1565 // 3x3 mip, a 6x6 mip into a 12x12 one). The source's blocks go into transfer scratch with its own
1566 // cut extent and from there into the destination with the destination's (`staged_reads` and
1567 // `staged_writes`, offsets from the start of the scratch; prepare allocates it). The box fits the
1568 // source's padded mip, so the scratch holds every block the destination reads.
1569 if (!within(copy.z, d, to_depth)) return ReplayResult::invalid_copy;
1570 VkBufferImageCopy read{};
1571 read.bufferRowLength = blocks_w;
1572 read.bufferImageHeight = blocks_h;
1573 read.imageSubresource = {src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1};
1574 read.imageOffset = {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)};
1575 read.imageExtent = {src_w, src_h, d};
1576 VkBufferImageCopy write = read;
1577 write.imageSubresource = {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1};
1578 write.imageOffset = {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)};
1579 write.imageExtent = {dst_w, dst_h, d};
1580 p.staged_reads.push_back(read);
1581 p.staged_writes.push_back(write);
1582 p.range = dst;
1583 p.source_range = src;
1584 return ReplayResult::success;
1585 }
1516 } 1586 }
1517 if (!within(copy.x, w, to.width) || !within(copy.y, h, to.height) || !within(copy.z, d, to_depth)) 1587 if (!within(copy.x, w, to.width) || !within(copy.y, h, to.height) || !within(copy.z, d, to_depth))
1518 return ReplayResult::invalid_copy; 1588 return ReplayResult::invalid_copy;
@@ -1819,7 +1889,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct
1819 }; 1889 };
1820 1890
1821 p.colors.assign(pipeline->color_formats.size(), {}); 1891 p.colors.assign(pipeline->color_formats.size(), {});
1822 for (std::size_t slot = 0; slot < draw.render_targets.size() && slot < p.colors.size(); ++slot) { 1892 for (std::size_t slot = 0; slot < draw.render_target_count && slot < draw.render_targets.size() && slot < p.colors.size(); ++slot) {
1823 const TargetView& target = draw.render_targets[slot]; 1893 const TargetView& target = draw.render_targets[slot];
1824 if (!target.resource) continue; 1894 if (!target.resource) continue;
1825 const ResourceBinding* binding = resolve(target.resource); 1895 const ResourceBinding* binding = resolve(target.resource);
@@ -1991,6 +2061,9 @@ public:
1991 VkQueryPool statistics_pool = VK_NULL_HANDLE; 2061 VkQueryPool statistics_pool = VK_NULL_HANDLE;
1992 std::uint32_t statistics_base = 0; 2062 std::uint32_t statistics_base = 0;
1993 std::uint32_t statistics_segment_count = 0; 2063 std::uint32_t statistics_segment_count = 0;
2064 // The list's statistics queries overlap (D3D-252): without a statistics pool they cannot run whole, because
2065 // two Vulkan queries of one type may not be active at once; QueryReplay::plan refuses such a list.
2066 bool statistics_overlaps = false;
1994 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them 2067 // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them
1995 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run 2068 // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run
1996 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. 2069 // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it.
@@ -2009,7 +2082,9 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) {
2009 const Command& command = out.list->commands()[query.command]; 2082 const Command& command = out.list->commands()[query.command];
2010 if (std::holds_alternative<ResolveQueries>(command)) continue; 2083 if (std::holds_alternative<ResolveQueries>(command)) continue;
2011 const auto range = query_range(command); 2084 const auto range = query_range(command);
2012 if (range.type != d3d12_query::occlusion) continue; 2085 // Binary occlusion is virtualized alongside the ordinary kind (D3D-252): both are VK_QUERY_TYPE_OCCLUSION,
2086 // so one physical query is open at a time and a binary resolve normalizes the summed counts (0 or 1).
2087 if (range.type != d3d12_query::occlusion && range.type != d3d12_query::binary_occlusion) continue;
2013 const auto key = std::pair{range.heap, range.first}; 2088 const auto key = std::pair{range.heap, range.first};
2014 query.end_segment = current; 2089 query.end_segment = current;
2015 if (std::holds_alternative<BeginQuery>(command)) { 2090 if (std::holds_alternative<BeginQuery>(command)) {
@@ -2071,6 +2146,60 @@ inline void plan_statistics_segments(PreparedList& out) {
2071 } 2146 }
2072} 2147}
2073 2148
2149// Overlapping pipeline-statistics queries (D3D-252): the same physical-segment layout the occlusion planner
2150// builds, in the statistics pool. Each Begin and End of a statistics query — and every non-timestamp resolve
2151// while one runs, because its helper dispatch would be counted — closes the one open physical query and opens
2152// a new one, so each logical query keeps a contiguous slot range and its result is the sum of that range
2153// (statistics_sum.comp). A Begin or End of another query kind leaves the segments alone.
2154inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
2155 std::map<std::pair<QueryHeapId, std::uint32_t>, std::uint32_t> active;
2156 std::uint32_t current = detail::PreparedQuery::no_segment;
2157 std::size_t next_query = 0;
2158 for (std::size_t i = 0; i < out.commands.size(); ++i) {
2159 auto& p = out.commands[i];
2160 detail::PreparedQuery* query = nullptr;
2161 if (next_query != out.queries.size() && out.queries[next_query].command == i)
2162 query = &out.queries[next_query++];
2163 if (!query) {
2164 // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical
2165 // segment before it and open a new one after, the way resolves do.
2166 if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24)) {
2167 p.statistics_end = current;
2168 current = out.statistics_segment_count++;
2169 p.statistics_begin = current;
2170 }
2171 continue;
2172 }
2173 const Command& command = out.list->commands()[i];
2174 const auto range = query_range(command);
2175 if (!std::holds_alternative<ResolveQueries>(command)) {
2176 // A Begin or End of another query kind leaves the shared segment alone.
2177 if (range.type != d3d12_query::pipeline_statistics) continue;
2178 query->statistics_end = current;
2179 const auto key = std::pair{range.heap, range.first};
2180 if (std::holds_alternative<BeginQuery>(command)) {
2181 // A flattened bundle can reuse a slot already active in the parent list.
2182 if (!active.emplace(key, out.statistics_segment_count).second) return ReplayResult::invalid_query;
2183 } else {
2184 const auto start = active.find(key);
2185 if (start == active.end()) return ReplayResult::invalid_query;
2186 query->statistics_first = start->second;
2187 query->statistics_count = out.statistics_segment_count - start->second;
2188 active.erase(start);
2189 }
2190 } else {
2191 if (current == detail::PreparedQuery::no_segment || range.type == d3d12_query::timestamp) continue;
2192 query->statistics_end = current;
2193 current = out.statistics_segment_count++;
2194 query->statistics_begin = current;
2195 continue;
2196 }
2197 current = active.empty() ? detail::PreparedQuery::no_segment : out.statistics_segment_count++;
2198 query->statistics_begin = current;
2199 }
2200 return active.empty() ? ReplayResult::success : ReplayResult::invalid_query;
2201}
2202
2074// detail::initialize zero-clears an image piece the tracker holds in UNDEFINED (D3D12 committed resources start 2203// detail::initialize zero-clears an image piece the tracker holds in UNDEFINED (D3D12 committed resources start
2075// zeroed) the first time a command touches it, with vkCmdClearColorImage or vkCmdClearDepthStencilImage. True when 2204// zeroed) the first time a command touches it, with vkCmdClearColorImage or vkCmdClearDepthStencilImage. True when
2076// a command of the list would need one of those and it is unset; replay() then refuses the list as unsupported, as 2205// a command of the list would need one of those and it is unset; replay() then refuses the list as unsupported, as
@@ -2150,9 +2279,12 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2150 out.unpredicated_copies = 0; 2279 out.unpredicated_copies = 0;
2151 const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp && 2280 const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp &&
2152 vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool; 2281 vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool;
2153 // Vulkan allows one active query per type. Only ordinary occlusion uses virtual segments. 2282 // Vulkan allows one active query per type. Overlapping ordinary and binary occlusion share one physical
2154 std::size_t ordinary_active = 0; 2283 // segment pool, and overlapping statistics split into the statistics pool (D3D-252); a physical query of a
2155 bool overlaps = false, binary_active = false, statistics_active = false; 2284 // type is still open at most once at any point, because each event closes the one open slot and opens a new
2285 // one. The occlusion kinds share their D3D12 heap, statistics have their own, so their states are separate.
2286 std::size_t ordinary_active = 0, binary_active = 0, statistics_active_count = 0;
2287 bool overlaps = false, statistics_overlaps = false, statistics_active = false;
2156 out.wrote_readback = false; 2288 out.wrote_readback = false;
2157 out.readback_src_stages = 0; 2289 out.readback_src_stages = 0;
2158 2290
@@ -2321,6 +2453,20 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2321 } else p.buffer_copies.push_back({src, dst, buffer_copy->size}); 2453 } else p.buffer_copies.push_back({src, dst, buffer_copy->size});
2322 } else if (const auto* texture_copy = std::get_if<CopyTexture>(&command)) { 2454 } else if (const auto* texture_copy = std::get_if<CopyTexture>(&command)) {
2323 result = detail::prepare_texture_copy(*texture_copy, p); 2455 result = detail::prepare_texture_copy(*texture_copy, p);
2456 if (result == ReplayResult::success && !p.staged_reads.empty()) {
2457 // A block-compressed copy staged through transfer scratch (prepare_texture_copy): whole blocks of
2458 // the read's row length and height, one region a copy.
2459 const VkBufferImageCopy& read = p.staged_reads[0];
2460 const BlockFormat f = block_format(p.source.format, read.imageSubresource.aspectMask);
2461 const VkDeviceSize bytes = VkDeviceSize(read.bufferRowLength / f.block) *
2462 (read.bufferImageHeight / f.block) * read.imageExtent.depth * f.bytes;
2463 VkDeviceSize base = 0;
2464 if (!f.bytes || !vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch ||
2465 !vk.copy_scratch(bytes, p.staged, base))
2466 return ReplayResult::invalid_copy; // refused as before this path existed
2467 p.staged_reads[0].bufferOffset += base;
2468 p.staged_writes[0].bufferOffset += base;
2469 }
2324 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. 2470 // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image.
2325 const bool upload = texture_copy->src.footprint; 2471 const bool upload = texture_copy->src.footprint;
2326 const ResourceBinding& image = upload ? p.binding : p.source; 2472 const ResourceBinding& image = upload ? p.binding : p.source;
@@ -2495,15 +2641,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2495 if (range.type != d3d12_query::timestamp && !std::holds_alternative<ResolveQueries>(command)) { 2641 if (range.type != d3d12_query::timestamp && !std::holds_alternative<ResolveQueries>(command)) {
2496 const bool begin = std::holds_alternative<BeginQuery>(command); 2642 const bool begin = std::holds_alternative<BeginQuery>(command);
2497 if (range.type == d3d12_query::occlusion) { 2643 if (range.type == d3d12_query::occlusion) {
2498 if (begin && binary_active) return ReplayResult::unsupported; 2644 overlaps |= begin && (ordinary_active || binary_active);
2499 if (begin) overlaps |= ordinary_active++ != 0; 2645 if (begin) ++ordinary_active; else --ordinary_active;
2500 else --ordinary_active;
2501 } else if (range.type == d3d12_query::binary_occlusion) { 2646 } else if (range.type == d3d12_query::binary_occlusion) {
2502 if (begin && (binary_active || ordinary_active)) return ReplayResult::unsupported; 2647 overlaps |= begin && (ordinary_active || binary_active);
2503 binary_active = begin; 2648 if (begin) ++binary_active; else --binary_active;
2504 } else { 2649 } else {
2505 if (begin && statistics_active) return ReplayResult::unsupported; 2650 statistics_overlaps |= begin && statistics_active_count;
2506 statistics_active = begin; 2651 if (begin) ++statistics_active_count; else --statistics_active_count;
2652 statistics_active = statistics_active_count != 0;
2507 } 2653 }
2508 } 2654 }
2509 if (const auto* resolve_queries = std::get_if<ResolveQueries>(&command)) { 2655 if (const auto* resolve_queries = std::get_if<ResolveQueries>(&command)) {
@@ -2603,8 +2749,14 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
2603 if (const auto r = detail::prepare_draw(*draw, resolve, vk, p); r != ReplayResult::success) return r; 2749 if (const auto r = detail::prepare_draw(*draw, resolve, vk, p); r != ReplayResult::success) return r;
2604 } 2750 }
2605 } 2751 }
2606 if (ordinary_active) return ReplayResult::invalid_query; 2752 if (ordinary_active || binary_active) return ReplayResult::invalid_query;
2607 plan_statistics_segments(out); 2753 out.statistics_overlaps = statistics_overlaps;
2754 if (statistics_overlaps) {
2755 const auto result = plan_overlapping_statistics_segments(out);
2756 if (result != ReplayResult::success) return result;
2757 } else {
2758 plan_statistics_segments(out);
2759 }
2608 if (overlaps) { 2760 if (overlaps) {
2609 if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment) 2761 if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment)
2610 return ReplayResult::unsupported; 2762 return ReplayResult::unsupported;
@@ -2634,6 +2786,9 @@ public:
2634 retain(statistics_pool); 2786 retain(statistics_pool);
2635 list.statistics_pool = statistics_pool->pool; 2787 list.statistics_pool = statistics_pool->pool;
2636 list.statistics_base = statistics_base; 2788 list.statistics_base = statistics_base;
2789 } else if (list.statistics_overlaps) {
2790 // Whole queries on the heap pool would keep two pipeline-statistics queries active at once.
2791 return ReplayResult::unsupported;
2637 } else { 2792 } else {
2638 for (const auto& command : list.commands) 2793 for (const auto& command : list.commands)
2639 if (command.statistics_end != detail::PreparedQuery::no_segment) 2794 if (command.statistics_end != detail::PreparedQuery::no_segment)
@@ -2674,11 +2829,14 @@ public:
2674 detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, 2829 detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE,
2675 index, 1, offset + VkDeviceSize(i) * size}; 2830 index, 1, offset + VkDeviceSize(i) * size};
2676 if (value.occlusion.segments) { 2831 if (value.occlusion.segments) {
2677 if (resolve.type != d3d12_query::occlusion && !statistics) return ReplayResult::invalid_query; 2832 if (resolve.type != d3d12_query::occlusion && !binary && !statistics)
2833 return ReplayResult::invalid_query;
2678 const auto& saved = value.occlusion; 2834 const auto& saved = value.occlusion;
2679 run = {saved.segments->pool, saved.first, saved.count, run.offset, saved.count > 1}; 2835 run = {saved.segments->pool, saved.first, saved.count, run.offset, saved.count > 1};
2680 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; 2836 if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported;
2681 (statistics ? needs_statistics_sum : needs_sum) |= run.sum; 2837 if (statistics) needs_statistics_sum |= run.sum;
2838 else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true;
2839 else needs_sum |= run.sum;
2682 retain(saved.segments); 2840 retain(saved.segments);
2683 } 2841 }
2684 if (!query.resolves.empty() && !run.sum && run.count == 1) { 2842 if (!query.resolves.empty() && !run.sum && run.count == 1) {
@@ -2707,6 +2865,7 @@ public:
2707 bool needs_sum = false; 2865 bool needs_sum = false;
2708 bool needs_binary = false; 2866 bool needs_binary = false;
2709 bool needs_statistics_sum = false; 2867 bool needs_statistics_sum = false;
2868 bool needs_sum_binary = false; // a binary query whose segments must be summed before the 0/1 normalize
2710 std::vector<std::shared_ptr<const OcclusionSegmentPool>> retained; 2869 std::vector<std::shared_ptr<const OcclusionSegmentPool>> retained;
2711 2870
2712private: 2871private:
@@ -2782,11 +2941,16 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
2782 const bool suspend = predicate.buffer && !query.resolves.empty(); 2941 const bool suspend = predicate.buffer && !query.resolves.empty();
2783 end_statistics(); 2942 end_statistics();
2784 if (suspend) vk.end_conditional_rendering(cb); 2943 if (suspend) vk.end_conditional_rendering(cb);
2944 if (resolve.type == d3d12_query::timestamp && vk.order_timestamp_copy &&
2945 std::any_of(query.resolves.begin(), query.resolves.end(), [](const auto& run) { return run.pool; }))
2946 vk.order_timestamp_copy(cb);
2785 for (const auto& run : query.resolves) { 2947 for (const auto& run : query.resolves) {
2786 if (!run.pool) { 2948 if (!run.pool) {
2787 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); 2949 vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0);
2788 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { 2950 } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) {
2789 vk.sum_statistics(cb, run.pool, run.first, run.count, dst, run.offset); 2951 vk.sum_statistics(cb, run.pool, run.first, run.count, dst, run.offset);
2952 } else if (run.sum && binary) {
2953 vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset);
2790 } else if (run.sum || binary) { 2954 } else if (run.sum || binary) {
2791 const auto& resolve_occlusion = run.sum ? vk.sum_occlusion : vk.resolve_binary_occlusion; 2955 const auto& resolve_occlusion = run.sum ? vk.sum_occlusion : vk.resolve_binary_occlusion;
2792 resolve_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); 2956 resolve_occlusion(cb, run.pool, run.first, run.count, dst, run.offset);
@@ -2925,6 +3089,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2925 barrier.dstStageMask = dst.stages; 3089 barrier.dstStageMask = dst.stages;
2926 barrier.srcAccessMask = src.access; 3090 barrier.srcAccessMask = src.access;
2927 barrier.dstAccessMask = dst.access; 3091 barrier.dstAccessMask = dst.access;
3092 if (barrier.srcStageMask) detail::restrict_to_queue(vk, barrier.srcStageMask, barrier.srcAccessMask);
3093 if (barrier.dstStageMask) detail::restrict_to_queue(vk, barrier.dstStageMask, barrier.dstAccessMask);
2928 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; 3094 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO};
2929 dependency.memoryBarrierCount = 1; 3095 dependency.memoryBarrierCount = 1;
2930 dependency.pMemoryBarriers = &barrier; 3096 dependency.pMemoryBarriers = &barrier;
@@ -2959,6 +3125,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
2959 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; 3125 b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
2960 b.image = p.binding.image; 3126 b.image = p.binding.image;
2961 b.subresourceRange = detail::layout_range(p.binding, piece.range); 3127 b.subresourceRange = detail::layout_range(p.binding, piece.range);
3128 if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask);
3129 if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask);
2962 barriers.push_back(b); 3130 barriers.push_back(b);
2963 } 3131 }
2964 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; 3132 VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO};
@@ -3099,7 +3267,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c
3099 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), 3267 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()),
3100 p.buffer_copies.data()); 3268 p.buffer_copies.data());
3101 } else if (p.staged) { 3269 } else if (p.staged) {
3102 // Depth <-> colour: the source into the scratch, then the scratch into the destination. 3270 // Depth <-> colour, or a block-compressed copy no one extent fits: the source into the scratch, then
3271 // the scratch into the destination. The destination's copy_layout comes after the scratch write, so
3272 // its barrier orders every earlier transfer write before the destination's (#860, Vonsek's
3273 // synchronization-validation run).
3103 const VkImageLayout src_layout = detail::copy_layout( 3274 const VkImageLayout src_layout = detail::copy_layout(
3104 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), 3275 vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate),
3105 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); 3276 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker);
diff --git a/runtime/test/bvh_builder_test.cpp b/runtime/test/bvh_builder_test.cpp
index a730f190a..16e5db4d8 100644
--- a/runtime/test/bvh_builder_test.cpp
+++ b/runtime/test/bvh_builder_test.cpp
@@ -154,6 +154,9 @@ int filter(EXCEPTION_POINTERS* e, Call* c) {
154using Ctor = void* (*)(void* self, void* device, bool flag); 154using Ctor = void* (*)(void* self, void* device, bool flag);
155using Dtor = void (*)(void* self); 155using Dtor = void (*)(void* self);
156 156
157// Each guard returns a copy of `c`, not `c` itself: with `return c;` the local becomes the named return value, and
158// clang-cl 19 and 20 crash (exit 139, in recoverAddrOfEscapedLocal) generating the __except filter that writes it,
159// which stops the Linux cross-build (runtime/cmake/clang-cl-xwin.cmake). MSVC is fine either way.
157Call guarded_ctor(Ctor fn, void* self, void* device, bool flag) { 160Call guarded_ctor(Ctor fn, void* self, void* device, bool flag) {
158 Call c; 161 Call c;
159 __try { 162 __try {
@@ -161,7 +164,7 @@ Call guarded_ctor(Ctor fn, void* self, void* device, bool flag) {
161 } __except (filter(GetExceptionInformation(), &c)) { 164 } __except (filter(GetExceptionInformation(), &c)) {
162 c.faulted = true; 165 c.faulted = true;
163 } 166 }
164 return c; 167 return Call(c);
165} 168}
166 169
167Call guarded_dtor(Dtor fn, void* self) { 170Call guarded_dtor(Dtor fn, void* self) {
@@ -171,7 +174,7 @@ Call guarded_dtor(Dtor fn, void* self) {
171 } __except (filter(GetExceptionInformation(), &c)) { 174 } __except (filter(GetExceptionInformation(), &c)) {
172 c.faulted = true; 175 c.faulted = true;
173 } 176 }
174 return c; 177 return Call(c);
175} 178}
176 179
177// main's loader (#95) maps, sets up TLS and runs DllMain, but doesn't register the image's x64 unwind tables yet 180// main's loader (#95) maps, sets up TLS and runs DllMain, but doesn't register the image's x64 unwind tables yet
@@ -342,6 +345,40 @@ std::string container_shape(const void* bytecode, size_t length) {
342 return out; 345 return out;
343} 346}
344 347
348// The module a container belongs to: the file name (without ".pdb") in its ILDN part, a DXIL debug-name record
349// (u16 flags, u16 name length, then the PDB path). Empty when there is no such part. The module names are the ones
350// listed in docs/embedded_shaders.md section 3.
351std::string container_module(const void* bytecode, size_t length) {
352 const auto* b = static_cast<const uint8_t*>(bytecode);
353 auto u32 = [&](size_t o) {
354 uint32_t v = 0;
355 if (o + 4 <= length) std::memcpy(&v, b + o, 4);
356 return v;
357 };
358 if (!b || length < 32 || std::memcmp(b, "DXBC", 4) != 0) return {};
359 const uint32_t parts = u32(28);
360 for (uint32_t i = 0; i < parts && 32 + 4 * size_t(i) + 4 <= length; ++i) {
361 const size_t off = u32(32 + 4 * size_t(i));
362 if (off + 8 > length || std::memcmp(b + off, "ILDN", 4) != 0) continue;
363 const size_t size = u32(off + 4), data = off + 8;
364 if (size < 5 || data + size > length) return {};
365 std::string path(reinterpret_cast<const char*>(b + data + 4), size - 4);
366 path.resize(std::strlen(path.c_str()));
367 const size_t slash = path.find_last_of("\\/");
368 std::string name = slash == std::string::npos ? path : path.substr(slash + 1);
369 if (name.size() > 4 && name.compare(name.size() - 4, 4, ".pdb") == 0) name.resize(name.size() - 4);
370 return name;
371 }
372 return {};
373}
374
375// Every container the constructor has passed to slot 62 so far, to find one that is passed twice (RT-182). The bytes
376// are compared, not a hash, and nothing is printed from them.
377std::vector<std::vector<uint8_t>> g_seen_containers;
378std::vector<std::string> g_seen_modules;
379int g_repeat_first = 0, g_repeat_second = 0; // creation numbers (1-based) of the first repeat found, 0 = none
380int g_repeats = 0;
381
345// LEONIDA_BVH_DXIL=1: what each shader uses, from dxcompiler.dll's disassembly in memory: the distinct dx.op names 382// LEONIDA_BVH_DXIL=1: what each shader uses, from dxcompiler.dll's disassembly in memory: the distinct dx.op names
346// with call counts, and a few type/feature markers. Also dxil.dll's validator verdict. Names and counts only; the 383// with call counts, and a few type/feature markers. Also dxil.dll's validator verdict. Names and counts only; the
347// disassembly is not printed or written. The DLLs come from PATH or the Windows SDK, loaded at run time. 384// disassembly is not printed or written. The DLLs come from PATH or the Windows SDK, loaded at run time.
@@ -459,6 +496,27 @@ uint64_t WINAPI record_slot62(void* self, uint64_t a1, uint64_t a2, uint64_t a3,
459 if (desc) { 496 if (desc) {
460 std::printf(" slot62 #%d container: %s\n", n + 1, 497 std::printf(" slot62 #%d container: %s\n", n + 1,
461 container_shape(desc->CS.pShaderBytecode, desc->CS.BytecodeLength).c_str()); 498 container_shape(desc->CS.pShaderBytecode, desc->CS.BytecodeLength).c_str());
499 const std::string module = container_module(desc->CS.pShaderBytecode, desc->CS.BytecodeLength);
500 std::printf(" slot62 #%d module: %s\n", n + 1, module.empty() ? "(no ILDN part)" : module.c_str());
501 const auto* bytes = static_cast<const uint8_t*>(desc->CS.pShaderBytecode);
502 std::vector<uint8_t> copy(bytes, bytes + desc->CS.BytecodeLength);
503 int same_as = 0;
504 for (size_t i = 0; i < g_seen_containers.size(); ++i)
505 if (g_seen_containers[i] == copy) {
506 same_as = static_cast<int>(i) + 1;
507 break;
508 }
509 if (same_as) {
510 std::printf(" slot62 #%d is byte-identical to #%d (module %s)\n", n + 1, same_as,
511 g_seen_modules[same_as - 1].c_str());
512 if (!g_repeats) {
513 g_repeat_first = same_as;
514 g_repeat_second = n + 1;
515 }
516 ++g_repeats;
517 }
518 g_seen_containers.push_back(std::move(copy));
519 g_seen_modules.push_back(module);
462 if (env("LEONIDA_BVH_DXIL") == "1") 520 if (env("LEONIDA_BVH_DXIL") == "1")
463 std::printf(" slot62 #%d uses: %s\n", n + 1, dxil_usage(desc->CS.pShaderBytecode, desc->CS.BytecodeLength).c_str()); 521 std::printf(" slot62 #%d uses: %s\n", n + 1, dxil_usage(desc->CS.pShaderBytecode, desc->CS.BytecodeLength).c_str());
464 } 522 }
@@ -627,6 +685,16 @@ int main() {
627 note("slot 62 (Xbox CreateComputePipelineState) calls: " + std::to_string(rt::d3d12_xs::device_slot_hits(62)) + 685 note("slot 62 (Xbox CreateComputePipelineState) calls: " + std::to_string(rt::d3d12_xs::device_slot_hits(62)) +
628 (g_slot62_logged ? ", succeeded " + std::to_string(g_slot62_ok) + ", failed " + std::to_string(g_slot62_failed) 686 (g_slot62_logged ? ", succeeded " + std::to_string(g_slot62_ok) + ", failed " + std::to_string(g_slot62_failed)
629 : std::string())); 687 : std::string()));
688 if (g_slot62_logged) {
689 note("slot 62 creations: " + std::to_string(g_slot62_logged) + ", distinct containers: " +
690 std::to_string(g_slot62_logged - g_repeats) + ", repeated creations: " + std::to_string(g_repeats));
691 if (g_repeats) {
692 note("first repeat: creation #" + std::to_string(g_repeat_second) + " passes the same container as #" +
693 std::to_string(g_repeat_first) + ", module " + g_seen_modules[g_repeat_first - 1]);
694 check(g_seen_modules[g_repeat_first - 1] == g_seen_modules[g_repeat_second - 1],
695 "the repeated container names the same module both times");
696 }
697 }
630 note("OutputDebugString calls: " + std::to_string(g_debug_strings) + ", TerminateProcess calls: " + 698 note("OutputDebugString calls: " + std::to_string(g_debug_strings) + ", TerminateProcess calls: " +
631 std::to_string(g_terminate_calls)); 699 std::to_string(g_terminate_calls));
632 check(!c.faulted || c.code == kTerminateCalled, "constructor returns or gives up through TerminateProcess, no fault"); 700 check(!c.faulted || c.code == kTerminateCalled, "constructor returns or gives up through TerminateProcess, no fault");
diff --git a/runtime/test/check_startup_cmdline.cmake b/runtime/test/check_startup_cmdline.cmake
new file mode 100644
index 000000000..7d4d803aa
--- /dev/null
+++ b/runtime/test/check_startup_cmdline.cmake
@@ -0,0 +1,20 @@
1foreach(mode args no_args fail_init)
2 set(args)
3 if(mode STREQUAL "args")
4 set(args hello "two words")
5 elseif(mode STREQUAL "fail_init")
6 set(args fail-init)
7 endif()
8 execute_process(
9 COMMAND ${RUNNER} "${LOADER}" --run "${GUEST}" -- ${args}
10 TIMEOUT 90
11 RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error)
12 if(mode STREQUAL "fail_init")
13 if(NOT code STREQUAL "1" OR NOT error MATCHES "DllMain returned FALSE" OR output MATCHES "running ")
14 message(FATAL_ERROR "Failed attach returned ${code}\n${output}\n${error}")
15 endif()
16 elseif(NOT code STREQUAL "0" OR NOT output MATCHES "tiny_startup_cmdline: PASS"
17 OR NOT output MATCHES "game exited with code 0")
18 message(FATAL_ERROR "Startup command line (${mode}) returned ${code}\n${output}\n${error}")
19 endif()
20endforeach()
diff --git a/runtime/test/check_vk_pipeline_cli.cmake b/runtime/test/check_vk_pipeline_cli.cmake
index 58c3eb8b1..cec400b6d 100644
--- a/runtime/test/check_vk_pipeline_cli.cmake
+++ b/runtime/test/check_vk_pipeline_cli.cmake
@@ -42,4 +42,18 @@ foreach(bytes -1 1.5 4294967296)
42 if(NOT code STREQUAL "2" OR NOT log MATCHES "at byte [0-9]+") 42 if(NOT code STREQUAL "2" OR NOT log MATCHES "at byte [0-9]+")
43 message(FATAL_ERROR "lds_bytes=${bytes}: expected a malformed index, got ${code}\n${log}") 43 message(FATAL_ERROR "lds_bytes=${bytes}: expected a malformed index, got ${code}\n${log}")
44 endif() 44 endif()
45
46 file(WRITE "${TEST_DIR}/index.json" "{\"example\":{\"stage\":\"cs\",\"push_constant_bytes\":${bytes}}}\n")
47 execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}"
48 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5)
49 if(NOT code STREQUAL "2" OR NOT log MATCHES "at byte [0-9]+")
50 message(FATAL_ERROR "push_constant_bytes=${bytes}: expected a malformed index, got ${code}\n${log}")
51 endif()
52
53 file(WRITE "${TEST_DIR}/index.json" "{\"example\":{\"stage\":\"cs\",\"pc_tail\":{\"set\":1,\"binding\":0,\"bytes\":${bytes}}}}\n")
54 execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}"
55 RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5)
56 if(NOT code STREQUAL "2" OR NOT log MATCHES "at byte [0-9]+")
57 message(FATAL_ERROR "pc_tail.bytes=${bytes}: expected a malformed index, got ${code}\n${log}")
58 endif()
45endforeach() 59endforeach()
diff --git a/runtime/test/d3d12_com_test.cpp b/runtime/test/d3d12_com_test.cpp
index 5f30d83b5..caeb70323 100644
--- a/runtime/test/d3d12_com_test.cpp
+++ b/runtime/test/d3d12_com_test.cpp
@@ -29,6 +29,11 @@ struct Ref {
29 29
30} // namespace 30} // namespace
31 31
32static_assert(std::is_move_constructible_v<leonida::Draw>);
33static_assert(std::is_move_assignable_v<leonida::Draw>);
34static_assert(sizeof(leonida::Draw::render_targets) == sizeof(leonida::TargetView) * 8);
35static_assert(sizeof(leonida::Draw::vertex_buffers) == sizeof(leonida::VertexBufferView) * 32);
36
32int main(int argc, char** argv) { 37int main(int argc, char** argv) {
33 if (argc == 2 && std::strcmp(argv[1], "--trace-d3d12") == 0) rt::d3d12_trace::set_enabled(true); 38 if (argc == 2 && std::strcmp(argv[1], "--trace-d3d12") == 0) rt::d3d12_trace::set_enabled(true);
34 else if (argc != 1) return 2; 39 else if (argc != 1) return 2;
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp
index 8aa5611f2..8f22c447b 100644
--- a/runtime/test/d3d12_compute_test.cpp
+++ b/runtime/test/d3d12_compute_test.cpp
@@ -8,6 +8,7 @@
8// arguments they were recorded with, and the results copied to a readback buffer. 8// arguments they were recorded with, and the results copied to a readback buffer.
9// The shader (test/glsl/cs_user_data.comp) is written to the translator's push-constant and address contract. 9// The shader (test/glsl/cs_user_data.comp) is written to the translator's push-constant and address contract.
10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
11#include "shader_fixture_path.h"
11#include "vk_test_device.h" 12#include "vk_test_device.h"
12#include "../shims/d3d12_com.h" 13#include "../shims/d3d12_com.h"
13#include "../src/gfx10_descriptors.h" 14#include "../src/gfx10_descriptors.h"
@@ -269,7 +270,7 @@ int main() {
269 EXPECT(leonida::fssm_program(container) == fssm); 270 EXPECT(leonida::fssm_program(container) == fssm);
270 const auto library = std::filesystem::temp_directory_path() / "leonida_compute_test"; 271 const auto library = std::filesystem::temp_directory_path() / "leonida_compute_test";
271 std::filesystem::create_directories(library); 272 std::filesystem::create_directories(library);
272 std::filesystem::copy_file(LEONIDA_TEST_CS_SPV, library / "cs_user_data.spv", 273 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv",
273 std::filesystem::copy_options::overwrite_existing); 274 std::filesystem::copy_options::overwrite_existing);
274 { 275 {
275 std::ofstream index(library / "index.json", std::ios::binary); 276 std::ofstream index(library / "index.json", std::ios::binary);
diff --git a/runtime/test/d3d12_copy_compare.h b/runtime/test/d3d12_copy_compare.h
index 3d4281a17..49583f1b5 100644
--- a/runtime/test/d3d12_copy_compare.h
+++ b/runtime/test/d3d12_copy_compare.h
@@ -508,7 +508,6 @@ struct MixCase {
508 bool has_box; 508 bool has_box;
509 D3D12_BOX box; 509 D3D12_BOX box;
510 UINT dx, dy; 510 UINT dx, dy;
511 bool bc_gap; // block-compressed: the host copies whole blocks, the layer cannot (known difference)
512}; 511};
513 512
514// Copies one subresource of A into one of D (both prefilled), reads D back. `out.error` is set when the list was 513// Copies one subresource of A into one of D (both prefilled), reads D back. `out.error` is set when the list was
@@ -702,19 +701,24 @@ inline int compare_copies(ID3D12Device* ours, bool bc_supported) {
702 both("buffers", [&](Run& r, Outcome& o) { run_buffers(r, o); }); 701 both("buffers", [&](Run& r, Outcome& o) { run_buffers(r, o); });
703 702
704 // Different mips of one texture. Both sides must refuse what does not fit; what the host copies the layer must 703 // Different mips of one texture. Both sides must refuse what does not fit; what the host copies the layer must
705 // copy the same, except block-compressed copies of sizes that are no block multiple (known difference). 704 // copy the same. A block-compressed copy whose mip edge falls inside a block on one side only is staged through
705 // transfer scratch by the layer (vulkan_replay.h, prepare_texture_copy).
706 constexpr D3D12_BOX no_box{}; 706 constexpr D3D12_BOX no_box{};
707 const MixCase mixes[] = { 707 const MixCase mixes[] = {
708 {"mip 0 box 12x12 into mip 1", 0, 1, true, {0, 0, 0, 12, 12, 1}, 0, 0, false}, 708 {"mip 0 box 12x12 into mip 1", 0, 1, true, {0, 0, 0, 12, 12, 1}, 0, 0},
709 {"mip 1 into mip 0 at 8,8", 1, 0, false, no_box, 8, 8, false}, 709 {"mip 1 into mip 0 at 8,8", 1, 0, false, no_box, 8, 8},
710 {"mip 1 box 4..12 into mip 0", 1, 0, true, {4, 4, 0, 12, 12, 1}, 0, 0, false}, 710 {"mip 1 box 4..12 into mip 0", 1, 0, true, {4, 4, 0, 12, 12, 1}, 0, 0},
711 {"mip 0 box 8x8 into the 6x6 mip 2", 0, 2, true, {0, 0, 0, 8, 8, 1}, 0, 0, true}, 711 {"mip 0 box 8x8 into the 6x6 mip 2", 0, 2, true, {0, 0, 0, 8, 8, 1}, 0, 0},
712 {"mip 2 (6x6) into mip 0 at 4,4", 2, 0, false, no_box, 4, 4, true}, 712 {"mip 2 (6x6) into mip 0 at 4,4", 2, 0, false, no_box, 4, 4},
713 {"mip 2 (6x6) into mip 1", 2, 1, false, no_box, 0, 0, true}, 713 {"mip 2 (6x6) into mip 1", 2, 1, false, no_box, 0, 0},
714 {"mip 0 box 4x4 into the 3x3 mip 3", 0, 3, true, {0, 0, 0, 4, 4, 1}, 0, 0, true}, 714 {"mip 0 box 4x4 into the 3x3 mip 3", 0, 3, true, {0, 0, 0, 4, 4, 1}, 0, 0},
715 {"mip 0 box 16x16 into the 3x3 mip 3 (does not fit)", 0, 3, true, {0, 0, 0, 16, 16, 1}, 0, 0, false}, 715 // The source's mip edge inside the block: the box 4..8 of the 6x6 mip 2 (2x2 texels) into the 3x3 mip 3.
716 {"mip 0 box 16x16 into the 6x6 mip 2 (does not fit)", 0, 2, true, {0, 0, 0, 16, 16, 1}, 0, 0, false}, 716 {"mip 2 (6x6) box 4..8 into the 3x3 mip 3", 2, 3, true, {4, 4, 0, 8, 8, 1}, 0, 0},
717 {"mip 1 into mip 0 at 16,16 (does not fit)", 1, 0, false, no_box, 16, 16, false}, 717 // Both mip edges inside one block, at an offset: the 3x3 mip 3 into the 6x6 mip 2 at 4,4 (2x2 texels land).
718 {"mip 3 (3x3) into mip 2 at 4,4", 3, 2, false, no_box, 4, 4},
719 {"mip 0 box 16x16 into the 3x3 mip 3 (does not fit)", 0, 3, true, {0, 0, 0, 16, 16, 1}, 0, 0},
720 {"mip 0 box 16x16 into the 6x6 mip 2 (does not fit)", 0, 2, true, {0, 0, 0, 16, 16, 1}, 0, 0},
721 {"mip 1 into mip 0 at 16,16 (does not fit)", 1, 0, false, no_box, 16, 16},
718 }; 722 };
719 Run ours_run, host_run; // one queue each for every mixed-mip case 723 Run ours_run, host_run; // one queue each for every mixed-mip case
720 const bool ours_ok = ours_run.init(ours, true), host_ok = host_run.init(host.p, false); 724 const bool ours_ok = ours_run.init(ours, true), host_ok = host_run.init(host.p, false);
@@ -738,14 +742,10 @@ inline int compare_copies(ID3D12Device* ours, bool bc_supported) {
738 std::fprintf(stderr, "copy case %s: the HOST run failed (%s); fix the case\n", name.c_str(), b.error.c_str()); 742 std::fprintf(stderr, "copy case %s: the HOST run failed (%s); fix the case\n", name.c_str(), b.error.c_str());
739 ++bad; 743 ++bad;
740 } else if (host_run.refused != ours_run.refused) { 744 } else if (host_run.refused != ours_run.refused) {
741 if (!host_run.refused && bc && mc.bc_gap) { 745 std::fprintf(stderr, "copy case %s: the host %s the copy, the layer %s it (%s)\n", name.c_str(),
742 std::printf("copy case %s: known difference: the host copies whole blocks, the layer refuses it\n", name.c_str()); 746 host_run.refused ? "refuses" : "does", ours_run.refused ? "refuses" : "does",
743 } else { 747 ours_run.refused ? a.error.c_str() : "accepted");
744 std::fprintf(stderr, "copy case %s: the host %s the copy, the layer %s it (%s)\n", name.c_str(), 748 ++bad;
745 host_run.refused ? "refuses" : "does", ours_run.refused ? "refuses" : "does",
746 ours_run.refused ? a.error.c_str() : "accepted");
747 ++bad;
748 }
749 } else if (!host_run.refused) { 749 } else if (!host_run.refused) {
750 const int r = compare(name.c_str(), a, b); 750 const int r = compare(name.c_str(), a, b);
751 bad += r; 751 bad += r;
diff --git a/runtime/test/d3d12_debug_markers_test.cpp b/runtime/test/d3d12_debug_markers_test.cpp
index 4bc502aca..1be8fffed 100644
--- a/runtime/test/d3d12_debug_markers_test.cpp
+++ b/runtime/test/d3d12_debug_markers_test.cpp
@@ -214,22 +214,29 @@ int check_private_data(ID3D12Object* object, const char* what) {
214 EXPECT(size == sizeof(value)); 214 EXPECT(size == sizeof(value));
215 read = 0; 215 read = 0;
216 EXPECT(object->GetPrivateData(kKey, &size, &read) == S_OK && size == sizeof(value) && read == value); 216 EXPECT(object->GetPrivateData(kKey, &size, &read) == S_OK && size == sizeof(value) && read == value);
217 EXPECT(object->SetPrivateData(kKey, 4, nullptr) == E_INVALIDARG); 217 // Null data removes the entry whatever the size: S_OK, then S_FALSE once there is none (the host runtime's
218 // answers, d3d12_private_data_test).
219 EXPECT(object->SetPrivateData(kKey, 4, nullptr) == S_OK);
220 EXPECT(object->GetPrivateData(kKey, &size, nullptr) == DXGI_ERROR_NOT_FOUND && size == 0);
221 EXPECT(object->SetPrivateData(kKey, 4, nullptr) == S_FALSE);
218 EXPECT(object->SetPrivateDataInterface(kKey, &counted) == S_OK && counted.refs == 2); 222 EXPECT(object->SetPrivateDataInterface(kKey, &counted) == S_OK && counted.refs == 2);
219 EXPECT(object->SetPrivateDataInterface(kKey, &counted) == S_OK && counted.refs == 2); // same one again 223 EXPECT(object->SetPrivateDataInterface(kKey, &counted) == S_OK && counted.refs == 2); // same one again
224 // A null interface releases the one held and stays as a pointer-sized entry that reads back as null.
220 EXPECT(object->SetPrivateDataInterface(kKey, nullptr) == S_OK && counted.refs == 1); 225 EXPECT(object->SetPrivateDataInterface(kKey, nullptr) == S_OK && counted.refs == 1);
221 size = 99; 226 size = 99;
227 EXPECT(object->GetPrivateData(kKey, &size, nullptr) == S_OK && size == sizeof(IUnknown*));
228 got = &counted;
229 EXPECT(object->GetPrivateData(kKey, &size, &got) == S_OK && got == nullptr && counted.refs == 1);
230 EXPECT(object->SetPrivateData(kKey, 0, nullptr) == S_OK);
222 EXPECT(object->GetPrivateData(kKey, &size, nullptr) == DXGI_ERROR_NOT_FOUND && size == 0); 231 EXPECT(object->GetPrivateData(kKey, &size, nullptr) == DXGI_ERROR_NOT_FOUND && size == 0);
223 232
224 // SetName is readable as WKPDID_D3DDebugObjectNameW, terminator included. 233 // SetName is not readable through GetPrivateData, as on the host runtime: WKPDID_D3DDebugObjectNameW stays
234 // missing. A null name (which the host faults on) clears it.
225 const wchar_t name[] = L"leonida object"; 235 const wchar_t name[] = L"leonida object";
226 EXPECT(object->SetName(name) == S_OK); 236 EXPECT(object->SetName(name) == S_OK);
227 wchar_t stored[32] = {}; 237 size = 0;
228 size = sizeof(stored); 238 EXPECT(object->GetPrivateData(kDebugObjectNameW, &size, nullptr) == DXGI_ERROR_NOT_FOUND && size == 0);
229 EXPECT(object->GetPrivateData(kDebugObjectNameW, &size, stored) == S_OK);
230 EXPECT(size == sizeof(name) && std::wcscmp(stored, name) == 0);
231 EXPECT(object->SetName(nullptr) == S_OK); 239 EXPECT(object->SetName(nullptr) == S_OK);
232 EXPECT(object->GetPrivateData(kDebugObjectNameW, &size, nullptr) == DXGI_ERROR_NOT_FOUND);
233 240
234 // Left set: released when the object dies (checked for a fence below). 241 // Left set: released when the object dies (checked for a fence below).
235 EXPECT(object->SetPrivateDataInterface(kOtherKey, nullptr) == S_OK); 242 EXPECT(object->SetPrivateDataInterface(kOtherKey, nullptr) == S_OK);
diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp
index f2a33c4f2..9db94da9a 100644
--- a/runtime/test/d3d12_descriptor_test.cpp
+++ b/runtime/test/d3d12_descriptor_test.cpp
@@ -21,6 +21,7 @@
21// and binds the device's set (rt::d3d12::bindless_set). Without glslangValidator the GPU readbacks are skipped. 21// and binds the device's set (rt::d3d12::bindless_set). Without glslangValidator the GPU readbacks are skipped.
22// No game data. 22// No game data.
23// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 23// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
24#include "shader_fixture_path.h"
24#include "vk_test_device.h" 25#include "vk_test_device.h"
25#include "../shims/d3d12_com.h" 26#include "../shims/d3d12_com.h"
26#include "../shims/d3d12_xs_device.h" 27#include "../shims/d3d12_xs_device.h"
@@ -102,7 +103,7 @@ struct SampleKeys {
102}; 103};
103 104
104VkShaderModule load_shader(vktest::Device& d, const char* path) { 105VkShaderModule load_shader(vktest::Device& d, const char* path) {
105 std::ifstream file(path, std::ios::binary | std::ios::ate); 106 std::ifstream file(vktest::shader_fixture_path(path), std::ios::binary | std::ios::ate);
106 if (!file) return VK_NULL_HANDLE; 107 if (!file) return VK_NULL_HANDLE;
107 std::vector<std::uint32_t> code(std::size_t(file.tellg()) / 4); 108 std::vector<std::uint32_t> code(std::size_t(file.tellg()) / 4);
108 file.seekg(0); 109 file.seekg(0);
diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp
index b108fa8ec..216534cd4 100644
--- a/runtime/test/d3d12_draw_test.cpp
+++ b/runtime/test/d3d12_draw_test.cpp
@@ -12,6 +12,7 @@
12// B8G8R8X8 has no alpha, so destination alpha reads 1 there, as on WARP and AMD's D3D12 driver. 12// B8G8R8X8 has no alpha, so destination alpha reads 1 there, as on WARP and AMD's D3D12 driver.
13// The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data. 13// The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data.
14// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 14// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
15#include "shader_fixture_path.h"
15#include "vk_test_device.h" 16#include "vk_test_device.h"
16#include "d3d12_test_shaders.h" 17#include "d3d12_test_shaders.h"
17#include "../shims/d3d12_com.h" 18#include "../shims/d3d12_com.h"
@@ -69,11 +70,11 @@ int main() {
69 const auto vs_int_container = shader_container(vs_int_program); 70 const auto vs_int_container = shader_container(vs_int_program);
70 const auto library = std::filesystem::temp_directory_path() / "leonida_draw_test"; 71 const auto library = std::filesystem::temp_directory_path() / "leonida_draw_test";
71 std::filesystem::create_directories(library); 72 std::filesystem::create_directories(library);
72 std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing); 73 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing);
73 std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); 74 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing);
74 std::filesystem::copy_file(LEONIDA_TEST_VS_FULLSCREEN_SPV, library / "vs_fullscreen.spv", 75 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_FULLSCREEN_SPV), library / "vs_fullscreen.spv",
75 std::filesystem::copy_options::overwrite_existing); 76 std::filesystem::copy_options::overwrite_existing);
76 std::filesystem::copy_file(LEONIDA_TEST_VS_INT_SPV, library / "vs_draw_int.spv", 77 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_INT_SPV), library / "vs_draw_int.spv",
77 std::filesystem::copy_options::overwrite_existing); 78 std::filesystem::copy_options::overwrite_existing);
78 { 79 {
79 std::ofstream index(library / "index.json", std::ios::binary); 80 std::ofstream index(library / "index.json", std::ios::binary);
diff --git a/runtime/test/d3d12_f16_halves_test.cpp b/runtime/test/d3d12_f16_halves_test.cpp
new file mode 100644
index 000000000..c2f194e31
--- /dev/null
+++ b/runtime/test/d3d12_f16_halves_test.cpp
@@ -0,0 +1,367 @@
1// End-to-end Vulkan GPU test for per-pipeline `--f16-interp-fallback` linking (SHADER-378).
2//
3// Exercises two graphics PSOs through ID3D12Device::CreateGraphicsPipelineState on a real Vulkan 1.3 GPU, without
4// needing glslangValidator, llvm-mc or game files (both SPIR-V 1.5 modules are built directly in memory):
5// 1. A 16-param VS (param0..param15, static f16_halves only for param0..param6) writes packed f16 pairs into
6// param7: .x = packHalf2x16(0.25, 0.75) = 0x3A003400, .y = packHalf2x16(0.5, 1.0) = 0x3C003800.
7// PS #1 reads raw attr0..attr14 plus attr7's decoded f16 halves at Locations 20 & 21 (which collide with VS's
8// static param4 halves at 20 & 21). `link_f16_halves` demotes VS's unneeded static halves to Private,
9// synthesizes UnpackHalf2x16 for param7 at Locations 20 & 21, and the GPU renders RGBA (64, 191, 128, 255).
10// 2. PS #2 reads raw attr0..attr13 plus attr7's decoded f16 halves at Locations 14 & 15 (colliding with VS's raw
11// param14 & param15). `link_f16_halves` relocates BOTH PS and VS halves to Locations 28 & 29 and renders the
12// exact same RGBA (64, 191, 128, 255).
13// Skips (77) when no usable Vulkan 1.3 device is present. No game data.
14#include "vk_test_device.h"
15#include "d3d12_test_shaders.h"
16#include "../shims/d3d12_com.h"
17#include "../shims/d3d12_xs_device.h"
18#include "../src/shader_library.h"
19#include "../src/spirv_f16_halves.h"
20
21#include <cmath>
22#include <cstdint>
23#include <cstdio>
24#include <filesystem>
25#include <fstream>
26#include <map>
27#include <vector>
28
29#define EXPECT(cond) do { \
30 if (!(cond)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #cond); return 1; } \
31} while (0)
32
33using namespace d3d12test;
34using namespace leonida::spirv_detail;
35using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX
36
37namespace {
38
39void put_inst(std::vector<std::uint32_t>& w, std::uint16_t op, std::initializer_list<std::uint32_t> args) {
40 w.push_back((std::uint32_t(1 + args.size()) << 16) | op);
41 for (std::uint32_t a : args) w.push_back(a);
42}
43
44void put_inst_vec(std::vector<std::uint32_t>& w, std::uint16_t op, const std::vector<std::uint32_t>& args) {
45 w.push_back((std::uint32_t(1 + args.size()) << 16) | op);
46 w.insert(w.end(), args.begin(), args.end());
47}
48
49void write_spv(const std::filesystem::path& path, const std::vector<std::uint32_t>& words) {
50 std::ofstream f(path, std::ios::binary | std::ios::trunc);
51 f.write(reinterpret_cast<const char*>(words.data()), std::streamsize(words.size() * 4));
52}
53
54// Fullscreen triangle VS (from VertexIndex 0,1,2) exporting 16 raw params (0..15) + static f16_halves for 0..6.
55// param7 carries packed f16 bits: .x = 0x3A003400 (lo=0.25, hi=0.75), .y = 0x3C003800 (lo=0.5, hi=1.0).
56std::vector<std::uint32_t> make_16param_vs() {
57 // Fixed IDs:
58 // 1=%void, 2=%fn, 3=%float, 4=%v4float, 5=%int, 6=%ptr_in_int, 7=%ptr_out_v4
59 // 8=%vid_var, 9=%pos_var, 10=%null_v4
60 // 11=%f_m1(-1.0), 12=%f_3(3.0), 13=%f_0(0.0), 14=%f_1(1.0)
61 // 15=%c_p0(-1,-1,0,1), 16=%c_p1(3,-1,0,1), 17=%c_p2(-1,3,0,1)
62 // 18=%i_0, 19=%i_1, 20=%bool
63 // 21=%f_pack_x (bitcast 0x3A003400), 22=%f_pack_y (bitcast 0x3C003800), 23=%v_param7
64 // 24=%main, 25=%entry
65 // 26=%vid, 27=%is0, 28=%is1, 29=%p12, 30=%pos
66 // 31..46 = raw param0..param15 Output vars
67 // 47..60 = static f16_halves for param0..param6 (14 Output vars: 28,29, 26,27, ..., 16,17)
68 constexpr std::uint32_t kBound = 61;
69 std::vector<std::uint32_t> w = {kSpirvMagic, 0x00010500u, 0, kBound, 0};
70 put_inst(w, kOpCapability, {1}); // Shader
71 put_inst(w, kOpMemoryModel, {0, 1}); // Logical GLSL450
72 std::vector<std::uint32_t> ep = {kExecModelVertex, 24, 0x6e69616du, 0x00000000u, 8, 9};
73 for (std::uint32_t id = 31; id <= 60; ++id) ep.push_back(id);
74 put_inst_vec(w, kOpEntryPoint, ep);
75
76 put_inst(w, kOpDecorate, {8, 11, 42}); // BuiltIn VertexIndex
77 put_inst(w, kOpDecorate, {9, 11, 0}); // BuiltIn Position
78 for (std::uint32_t p = 0; p < 16; ++p) put_inst(w, kOpDecorate, {31 + p, kDecorationLocation, p});
79 for (std::uint32_t n = 0; n <= 6; ++n) {
80 put_inst(w, kOpDecorate, {47 + 2 * n, kDecorationLocation, 28 - 2 * n});
81 put_inst(w, kOpDecorate, {48 + 2 * n, kDecorationLocation, 29 - 2 * n});
82 }
83
84 put_inst(w, 19, {1}); // OpTypeVoid
85 put_inst(w, 33, {2, 1}); // OpTypeFunction %void
86 put_inst(w, kOpTypeFloat, {3, 32});
87 put_inst(w, kOpTypeVector, {4, 3, 4});
88 put_inst(w, kOpTypeInt, {5, 32, 1}); // %int
89 put_inst(w, kOpTypePointer, {6, kStorageInput, 5});
90 put_inst(w, kOpTypePointer, {7, kStorageOutput, 4});
91 put_inst(w, 20, {20}); // OpTypeBool
92
93 put_inst(w, kOpConstantNull, {4, 10});
94 put_inst(w, 43, {3, 11, 0xbf800000u}); // -1.0f
95 put_inst(w, 43, {3, 12, 0x40400000u}); // 3.0f
96 put_inst(w, 43, {3, 13, 0x00000000u}); // 0.0f
97 put_inst(w, 43, {3, 14, 0x3f800000u}); // 1.0f
98 put_inst(w, 44, {4, 15, 11, 11, 13, 14}); // (-1, -1, 0, 1)
99 put_inst(w, 44, {4, 16, 12, 11, 13, 14}); // ( 3, -1, 0, 1)
100 put_inst(w, 44, {4, 17, 11, 12, 13, 14}); // (-1, 3, 0, 1)
101 put_inst(w, 43, {5, 18, 0u});
102 put_inst(w, 43, {5, 19, 1u});
103 put_inst(w, 43, {3, 21, 0x3a003400u}); // packHalf2x16(0.25, 0.75) as raw f32 bits
104 put_inst(w, 43, {3, 22, 0x3c003800u}); // packHalf2x16(0.50, 1.00) as raw f32 bits
105 put_inst(w, 44, {4, 23, 21, 22, 13, 14});
106
107 put_inst(w, kOpVariable, {6, 8, kStorageInput});
108 put_inst(w, kOpVariable, {7, 9, kStorageOutput});
109 for (std::uint32_t id = 31; id <= 60; ++id) put_inst(w, kOpVariable, {7, id, kStorageOutput});
110
111 put_inst(w, kOpFunction, {1, 24, 0, 2});
112 put_inst(w, 248, {25}); // OpLabel
113 put_inst(w, kOpLoad, {5, 26, 8}); // %vid
114 put_inst(w, 170, {20, 27, 26, 18}); // OpIEqual %vid 0
115 put_inst(w, 170, {20, 28, 26, 19}); // OpIEqual %vid 1
116 put_inst(w, 169, {4, 29, 28, 16, 17}); // OpSelect %is1 %p1 %p2
117 put_inst(w, 169, {4, 30, 27, 15, 29}); // OpSelect %is0 %p0 %p12
118 put_inst(w, kOpStore, {9, 30});
119 for (std::uint32_t p = 0; p < 16; ++p) put_inst(w, kOpStore, {31 + p, p == 7 ? 23u : 10u});
120 for (std::uint32_t id = 47; id <= 60; ++id) put_inst(w, kOpStore, {id, 10});
121 put_inst(w, kOpReturn, {});
122 put_inst(w, kOpFunctionEnd, {});
123 return w;
124}
125
126// Fragment shader reading `num_raw` raw inputs (Location 0..num_raw-1) plus decoded halves of param7 at
127// `lo_loc` and `hi_loc`, writing vec4(lo.x, hi.x, lo.y, hi.y) to MRT 0.
128std::vector<std::uint32_t> make_f16_ps(std::uint32_t num_raw, std::uint32_t lo_loc, std::uint32_t hi_loc) {
129 // 1=%void, 2=%fn, 3=%float, 4=%v4float, 5=%ptr_in_v4, 6=%ptr_out_v4, 7=%out0, 8=%in_lo, 9=%in_hi,
130 // 10=%main, 11=%entry, 12=%vlo, 13=%vhi, 14=%lox, 15=%hix, 16=%loy, 17=%hiy, 18=%rgba,
131 // 19.. = raw inputs 0..num_raw-1
132 const std::uint32_t bound = 19 + num_raw;
133 std::vector<std::uint32_t> w = {kSpirvMagic, 0x00010500u, 0, bound, 0};
134 put_inst(w, kOpCapability, {1});
135 put_inst(w, kOpMemoryModel, {0, 1});
136 std::vector<std::uint32_t> ep = {kExecModelFragment, 10, 0x6e69616du, 0x00000000u, 7, 8, 9};
137 for (std::uint32_t i = 0; i < num_raw; ++i) ep.push_back(19 + i);
138 put_inst_vec(w, kOpEntryPoint, ep);
139 put_inst(w, kOpExecutionMode, {10, 7}); // OriginUpperLeft
140
141 put_inst(w, kOpDecorate, {7, kDecorationLocation, 0});
142 put_inst(w, kOpDecorate, {8, kDecorationLocation, lo_loc});
143 put_inst(w, kOpDecorate, {9, kDecorationLocation, hi_loc});
144 for (std::uint32_t i = 0; i < num_raw; ++i) put_inst(w, kOpDecorate, {19 + i, kDecorationLocation, i});
145
146 put_inst(w, 19, {1});
147 put_inst(w, 33, {2, 1});
148 put_inst(w, kOpTypeFloat, {3, 32});
149 put_inst(w, kOpTypeVector, {4, 3, 4});
150 put_inst(w, kOpTypePointer, {5, kStorageInput, 4});
151 put_inst(w, kOpTypePointer, {6, kStorageOutput, 4});
152
153 put_inst(w, kOpVariable, {6, 7, kStorageOutput});
154 put_inst(w, kOpVariable, {5, 8, kStorageInput});
155 put_inst(w, kOpVariable, {5, 9, kStorageInput});
156 for (std::uint32_t i = 0; i < num_raw; ++i) put_inst(w, kOpVariable, {5, 19 + i, kStorageInput});
157
158 put_inst(w, kOpFunction, {1, 10, 0, 2});
159 put_inst(w, 248, {11});
160 put_inst(w, kOpLoad, {4, 12, 8});
161 put_inst(w, kOpLoad, {4, 13, 9});
162 put_inst(w, kOpCompositeExtract, {3, 14, 12, 0}); // lo.x = 0.25
163 put_inst(w, kOpCompositeExtract, {3, 15, 13, 0}); // hi.x = 0.75
164 put_inst(w, kOpCompositeExtract, {3, 16, 12, 1}); // lo.y = 0.50
165 put_inst(w, kOpCompositeExtract, {3, 17, 13, 1}); // hi.y = 1.00
166 put_inst(w, kOpCompositeConstruct, {4, 18, 14, 15, 16, 17});
167 put_inst(w, kOpStore, {7, 18});
168 put_inst(w, kOpReturn, {});
169 put_inst(w, kOpFunctionEnd, {});
170 return w;
171}
172
173} // namespace
174
175int main() {
176 vktest::Device d;
177 const auto status = d.initialize();
178 if (status == vktest::DeviceStatus::unavailable) {
179 std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n");
180 return 77;
181 }
182 EXPECT(status == vktest::DeviceStatus::ready);
183
184 const auto vs_prog = fssm_program({0x56530378, 0xbf810000});
185 const auto ps1_prog = fssm_program({0x50530378, 0x00000001});
186 const auto ps2_prog = fssm_program({0x50530378, 0x00000002});
187 const auto vs_c = shader_container(vs_prog);
188 const auto ps1_c = shader_container(ps1_prog);
189 const auto ps2_c = shader_container(ps2_prog);
190
191 const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_f16_halves_gpu_test";
192 std::filesystem::create_directories(lib_dir);
193 write_spv(lib_dir / "vs_16p.spv", make_16param_vs());
194 write_spv(lib_dir / "ps_packed.spv", make_f16_ps(15, 20, 21));
195 write_spv(lib_dir / "ps_reloc.spv", make_f16_ps(14, 14, 15));
196 {
197 std::ofstream idx(lib_dir / "index.json", std::ios::binary | std::ios::trunc);
198 idx << "{\"vs_16p\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_prog)
199 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [], "
200 "\"f16_halves\": {\"0\": [28, 29], \"1\": [26, 27], \"2\": [24, 25], \"3\": [22, 23], "
201 "\"4\": [20, 21], \"5\": [18, 19], \"6\": [16, 17]}},\n"
202 " \"ps_packed\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps1_prog)
203 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], "
204 "\"f16_halves\": {\"7\": [20, 21]}},\n"
205 " \"ps_reloc\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps2_prog)
206 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], "
207 "\"f16_halves\": {\"7\": [14, 15]}}}";
208 }
209
210 rt::d3d12::VulkanDeviceInfo info{};
211 info.get_instance_proc = d.instance_proc;
212 info.instance = d.instance;
213 info.physical = d.physical;
214 info.device = d.device;
215 info.queue = d.queue;
216 info.queue_family = d.family;
217 info.buffer_device_address = true;
218 info.subgroup = d.subgroup;
219 info.shader_dir = lib_dir.string();
220
221 ID3D12Device* inner = nullptr;
222 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
223 Ref<ID3D12Device> device;
224 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
225 reinterpret_cast<void**>(&device.p))));
226 rt::d3d12::set_device_outer(inner, device.p);
227
228 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
229 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
230 const auto root_blob = serialize_root_signature(root_desc);
231 EXPECT(!root_blob.empty());
232 Ref<ID3D12RootSignature> root;
233 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
234
235 D3D12_COMMAND_QUEUE_DESC qd{};
236 qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
237 Ref<ID3D12CommandQueue> queue;
238 EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))));
239 Ref<ID3D12CommandAllocator> alloc;
240 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p))));
241 Ref<ID3D12GraphicsCommandList> list;
242 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr,
243 IID_PPV_ARGS(&list.p))));
244 EXPECT(SUCCEEDED(list->Close()));
245
246 Ref<ID3D12Fence> fence;
247 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
248
249 constexpr UINT kSize = 16;
250 D3D12_HEAP_PROPERTIES default_hp{};
251 default_hp.Type = D3D12_HEAP_TYPE_DEFAULT;
252 D3D12_RESOURCE_DESC rt_desc{};
253 rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
254 rt_desc.Width = kSize;
255 rt_desc.Height = kSize;
256 rt_desc.DepthOrArraySize = 1;
257 rt_desc.MipLevels = 1;
258 rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
259 rt_desc.SampleDesc.Count = 1;
260 rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
261 Ref<ID3D12Resource> rt_res;
262 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_hp, D3D12_HEAP_FLAG_NONE, &rt_desc,
263 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
264 IID_PPV_ARGS(&rt_res.p))));
265
266 D3D12_DESCRIPTOR_HEAP_DESC rtv_hd{};
267 rtv_hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
268 rtv_hd.NumDescriptors = 1;
269 Ref<ID3D12DescriptorHeap> rtv_heap;
270 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_hd, IID_PPV_ARGS(&rtv_heap.p))));
271 const D3D12_CPU_DESCRIPTOR_HANDLE rtv_h{
272 SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(rtv_heap.p, 9))(rtv_heap.p))};
273 device->CreateRenderTargetView(rt_res.p, nullptr, rtv_h);
274
275 D3D12_HEAP_PROPERTIES rb_hp{};
276 rb_hp.Type = D3D12_HEAP_TYPE_READBACK;
277 D3D12_RESOURCE_DESC rb_desc{};
278 rb_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
279 rb_desc.Width = kSize * 256;
280 rb_desc.Height = 1;
281 rb_desc.DepthOrArraySize = 1;
282 rb_desc.MipLevels = 1;
283 rb_desc.SampleDesc.Count = 1;
284 rb_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
285 Ref<ID3D12Resource> rb_res;
286 EXPECT(SUCCEEDED(device->CreateCommittedResource(&rb_hp, D3D12_HEAP_FLAG_NONE, &rb_desc,
287 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
288 IID_PPV_ARGS(&rb_res.p))));
289
290 UINT64 fence_val = 0;
291 const auto run_case = [&](const char* label, const std::vector<std::uint8_t>& ps_container) -> bool {
292 D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{};
293 pd.pRootSignature = root.p;
294 pd.VS = {vs_c.data(), vs_c.size()};
295 pd.PS = {ps_container.data(), ps_container.size()};
296 pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
297 pd.SampleMask = 0xffffffffu;
298 pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
299 pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
300 pd.RasterizerState.DepthClipEnable = TRUE;
301 pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
302 pd.NumRenderTargets = 1;
303 pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
304 pd.SampleDesc.Count = 1;
305
306 Ref<ID3D12PipelineState> pso;
307 if (FAILED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p))) || !pso.p) {
308 std::fprintf(stderr, "%s: CreateGraphicsPipelineState failed\n", label);
309 return false;
310 }
311 if (FAILED(alloc->Reset()) || FAILED(list->Reset(alloc.p, pso.p))) return false;
312 const float clear_col[4] = {0.0f, 0.0f, 0.0f, 0.0f};
313 list->ClearRenderTargetView(rtv_h, clear_col, 0, nullptr);
314 list->OMSetRenderTargets(1, &rtv_h, FALSE, nullptr);
315 const D3D12_VIEWPORT vp = {0.0f, 0.0f, float(kSize), float(kSize), 0.0f, 1.0f};
316 const D3D12_RECT sc = {0, 0, LONG(kSize), LONG(kSize)};
317 list->RSSetViewports(1, &vp);
318 list->RSSetScissorRects(1, &sc);
319 list->SetGraphicsRootSignature(root.p);
320 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
321 list->DrawInstanced(3, 1, 0, 0);
322
323 D3D12_RESOURCE_BARRIER to_copy{};
324 to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
325 to_copy.Transition = {rt_res.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
326 D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE};
327 list->ResourceBarrier(1, &to_copy);
328 D3D12_TEXTURE_COPY_LOCATION dst{};
329 dst.pResource = rb_res.p;
330 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
331 dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, 256};
332 D3D12_TEXTURE_COPY_LOCATION src{};
333 src.pResource = rt_res.p;
334 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
335 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
336 D3D12_RESOURCE_BARRIER to_rt = to_copy;
337 to_rt.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE;
338 to_rt.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
339 list->ResourceBarrier(1, &to_rt);
340 if (FAILED(list->Close())) return false;
341
342 ID3D12CommandList* cl = list.p;
343 queue->ExecuteCommandLists(1, &cl);
344 ++fence_val;
345 if (FAILED(queue->Signal(fence.p, fence_val))) return false;
346 if (FAILED(fence->SetEventOnCompletion(fence_val, nullptr))) return false;
347
348 void* mapped = nullptr;
349 const D3D12_RANGE read_range = {0, kSize * 256};
350 if (FAILED(rb_res->Map(0, &read_range, &mapped)) || !mapped) return false;
351 const auto* px = static_cast<const std::uint8_t*>(mapped) + (kSize / 2) * 256 + (kSize / 2) * 4;
352 const int r = px[0], g = px[1], b = px[2], a = px[3];
353 rb_res->Unmap(0, nullptr);
354 // Expected: (0.25, 0.75, 0.50, 1.00) -> (64, 191, 128, 255) within +-1 LSB of UNORM rounding.
355 const bool ok = std::abs(r - 64) <= 1 && std::abs(g - 191) <= 1 && std::abs(b - 128) <= 1 && a == 255;
356 if (!ok) {
357 std::fprintf(stderr, "%s: pixel=(%d,%d,%d,%d), expected~(64,191,128,255)\n", label, r, g, b, a);
358 } else {
359 std::printf("%s: rendered pixel=(%d,%d,%d,%d) OK\n", label, r, g, b, a);
360 }
361 return ok;
362 };
363
364 EXPECT(run_case("ps_packed (synth param7 + demote static halves)", ps1_c));
365 EXPECT(run_case("ps_reloc (relocate colliding PS + VS halves to 28,29)", ps2_c));
366 return 0;
367}
diff --git a/runtime/test/d3d12_fence_timing_test.cpp b/runtime/test/d3d12_fence_timing_test.cpp
index 49eef01df..f5e067dfb 100644
--- a/runtime/test/d3d12_fence_timing_test.cpp
+++ b/runtime/test/d3d12_fence_timing_test.cpp
@@ -16,6 +16,7 @@
16#include <cstdint> 16#include <cstdint>
17#include <cstring> 17#include <cstring>
18#include <thread> 18#include <thread>
19#include <utility>
19#include <vector> 20#include <vector>
20 21
21#define EXPECT(condition) do { \ 22#define EXPECT(condition) do { \
@@ -197,7 +198,9 @@ int check_custom_heap_properties(ID3D12Device* device) {
197 } 198 }
198 } 199 }
199 const D3D12_HEAP_PROPERTIES custom = device->GetCustomHeapProperties(0, D3D12_HEAP_TYPE_CUSTOM); 200 const D3D12_HEAP_PROPERTIES custom = device->GetCustomHeapProperties(0, D3D12_HEAP_TYPE_CUSTOM);
200 EXPECT(custom.Type == D3D12_HEAP_TYPE(0) && custom.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_UNKNOWN); 201 EXPECT(custom.Type == D3D12_HEAP_TYPE(0) && custom.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_UNKNOWN &&
202 custom.MemoryPoolPreference == D3D12_MEMORY_POOL_UNKNOWN && custom.CreationNodeMask == 1 &&
203 custom.VisibleNodeMask == 1);
201 204
202 // The host runtime on a NUMA adapter (the answer the layer gives in D3D12_FEATURE_ARCHITECTURE) must agree. 205 // The host runtime on a NUMA adapter (the answer the layer gives in D3D12_FEATURE_ARCHITECTURE) must agree.
203 Ref<ID3D12Device> host; 206 Ref<ID3D12Device> host;
@@ -221,7 +224,23 @@ int check_custom_heap_properties(ID3D12Device* device) {
221 return 1; 224 return 1;
222 } 225 }
223 } 226 }
224 std::printf("GetCustomHeapProperties: DEFAULT, UPLOAD and READBACK match the host runtime\n"); 227 // What has no custom equivalent: an all-zero description with node 0 in both masks on the host runtime.
228 const std::pair<UINT, D3D12_HEAP_TYPE> invalid[] = {
229 {0, D3D12_HEAP_TYPE_CUSTOM}, {1, D3D12_HEAP_TYPE_CUSTOM}, {0, D3D12_HEAP_TYPE(99)},
230 {2, D3D12_HEAP_TYPE_UPLOAD}};
231 for (const auto& [node_mask, type] : invalid) {
232 const D3D12_HEAP_PROPERTIES ours = device->GetCustomHeapProperties(node_mask, type);
233 const D3D12_HEAP_PROPERTIES theirs = host->GetCustomHeapProperties(node_mask, type);
234 if (std::memcmp(&ours, &theirs, sizeof(ours)) != 0) {
235 std::fprintf(stderr, "node mask %u, heap type %d: ours %d/%d/%d/%u/%u, host %d/%d/%d/%u/%u\n", node_mask,
236 type, ours.Type, ours.CPUPageProperty, ours.MemoryPoolPreference, ours.CreationNodeMask,
237 ours.VisibleNodeMask, theirs.Type, theirs.CPUPageProperty, theirs.MemoryPoolPreference,
238 theirs.CreationNodeMask, theirs.VisibleNodeMask);
239 return 1;
240 }
241 }
242 std::printf("GetCustomHeapProperties: DEFAULT, UPLOAD, READBACK, CUSTOM, an unknown type and node mask 2 match "
243 "the host runtime\n");
225 return 0; 244 return 0;
226} 245}
227 246
diff --git a/runtime/test/d3d12_fspx_compute_test.cpp b/runtime/test/d3d12_fspx_compute_test.cpp
index d919345f5..607af18e4 100644
--- a/runtime/test/d3d12_fspx_compute_test.cpp
+++ b/runtime/test/d3d12_fspx_compute_test.cpp
@@ -9,6 +9,7 @@
9// refused with E_INVALIDARG, as bytecode without a program is today. 9// refused with E_INVALIDARG, as bytecode without a program is today.
10// The shader (test/glsl/cs_user_data.comp) stands in for a translated one. No game data. Set LEONIDA_VK_VALIDATION=1 10// The shader (test/glsl/cs_user_data.comp) stands in for a translated one. No game data. Set LEONIDA_VK_VALIDATION=1
11// to run under VK_LAYER_KHRONOS_validation. 11// to run under VK_LAYER_KHRONOS_validation.
12#include "shader_fixture_path.h"
12#include "vk_test_device.h" 13#include "vk_test_device.h"
13#include "../shims/d3d12_com.h" 14#include "../shims/d3d12_com.h"
14#include "../src/shader_library.h" 15#include "../src/shader_library.h"
@@ -165,12 +166,12 @@ int main() {
165 const auto library = std::filesystem::temp_directory_path() / "leonida_fspx_compute_test"; 166 const auto library = std::filesystem::temp_directory_path() / "leonida_fspx_compute_test";
166 std::filesystem::remove_all(library); 167 std::filesystem::remove_all(library);
167 std::filesystem::create_directories(library / "fspx"); 168 std::filesystem::create_directories(library / "fspx");
168 std::filesystem::copy_file(LEONIDA_TEST_CS_SPV, library / "fspx" / "cs_user_data.spv"); 169 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_user_data.spv");
169 std::filesystem::copy_file(LEONIDA_TEST_CS_SPV, library / "fspx" / "cs_user_data_b.spv"); 170 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_user_data_b.spv");
170 // The review case on #1911: program C in two containers whose kind-0 entries differ, translated to two 171 // The review case on #1911: program C in two containers whose kind-0 entries differ, translated to two
171 // different modules (the second has another generator word in its header, still a valid module). 172 // different modules (the second has another generator word in its header, still a valid module).
172 const auto code_c = kind6(9100); 173 const auto code_c = kind6(9100);
173 std::filesystem::copy_file(LEONIDA_TEST_CS_SPV, library / "fspx" / "cs_c_state1.spv"); 174 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "fspx" / "cs_c_state1.spv");
174 { 175 {
175 std::ifstream in(LEONIDA_TEST_CS_SPV, std::ios::binary); 176 std::ifstream in(LEONIDA_TEST_CS_SPV, std::ios::binary);
176 std::vector<char> words((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); 177 std::vector<char> words((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
diff --git a/runtime/test/d3d12_geometry_test.cpp b/runtime/test/d3d12_geometry_test.cpp
new file mode 100644
index 000000000..dcfb82bc1
--- /dev/null
+++ b/runtime/test/d3d12_geometry_test.cpp
@@ -0,0 +1,267 @@
1// Geometry shaders through the Xbox-ABI proxy over the Vulkan device. A VS+GS+PS pipeline whose GS
2// (test/glsl/gs_double.geom, with a translated GS's interface: triangles in, a triangle strip out) emits every
3// triangle twice, the second copy one clip-space unit to the right. On a 64x64 target cleared blue:
4// - the GS pipeline draws the quad in the top-left quadrant, red: the GS's copy fills the top-right one too;
5// - a pipeline without a GS draws the same quad moved to the bottom-left quadrant, green: no copy, so the
6// bottom-right quadrant stays blue.
7// The PS entry asks for a 32-wide subgroup, so with a GS the third stage's required-size struct is filled too (the
8// recipe keeps one per stage; a two-entry array overflowed here, found by @0xTehuti on #2109).
9// Also refused: a GS pipeline whose topology type is not the GS's input primitive (lines: E_INVALIDARG). Skipped where
10// the GPU lacks geometryShader. Shaders: test/glsl/vs_draw.vert, gs_double.geom, ps_draw.frag. No game data.
11// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
12#include "vk_test_device.h"
13#include "d3d12_test_shaders.h"
14#include "../shims/d3d12_com.h"
15#include "../shims/d3d12_xs_device.h"
16#include "../src/shader_library.h"
17
18#include <array>
19#include <cstring>
20
21#if !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_GS_SPV) || !defined(LEONIDA_TEST_PS_SPV)
22#error "LEONIDA_TEST_VS_SPV, LEONIDA_TEST_GS_SPV and LEONIDA_TEST_PS_SPV must name the compiled test shaders"
23#endif
24
25#define EXPECT(condition) do { \
26 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
27} while (0)
28
29using namespace d3d12test;
30using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX
31
32namespace {
33
34struct Vertex {
35 float x, y;
36 std::uint8_t r, g, b, a;
37};
38
39} // namespace
40
41int main() {
42 vktest::Device d;
43 EXPECT(d.create());
44 if (!d.enabled.geometryShader) {
45 std::printf("SKIP: no geometryShader on this GPU\n");
46 return 77; // ctest's SKIP_RETURN_CODE
47 }
48
49 const auto vs_program = fssm_program({0x56530001, 0xbf810000});
50 const auto gs_program = fssm_program({0x47530001, 0xbf810000});
51 const auto ps_program = fssm_program({0x50530001, 0xbf810000});
52 const auto vs_container = shader_container(vs_program), gs_container = shader_container(gs_program),
53 ps_container = shader_container(ps_program);
54 const auto library = std::filesystem::temp_directory_path() / "leonida_geometry_test";
55 std::filesystem::create_directories(library);
56 std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing);
57 std::filesystem::copy_file(LEONIDA_TEST_GS_SPV, library / "gs_double.spv",
58 std::filesystem::copy_options::overwrite_existing);
59 std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing);
60 {
61 std::ofstream index(library / "index.json", std::ios::binary);
62 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
63 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": ["
64 "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 0, \"mask\": 15, \"rw_mask\": 15, "
65 "\"system_value\": 0, \"component_type\": \"float\"}, "
66 "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 1, \"mask\": 3, \"rw_mask\": 3, "
67 "\"system_value\": 0, \"component_type\": \"float\"}]},\n"
68 " \"gs_double\": {\"stage\": \"gs\", \"fssm_sha256\": \"" << leonida::sha256_hex(gs_program)
69 << "\", \"bindings\": [], \"push_constant_bytes\": 144},\n"
70 " \"ps_draw\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_program)
71 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], \"subgroup_size\": 32}}";
72 }
73
74 constexpr UINT size = 64;
75 std::vector<std::uint8_t> pixels(size * 256);
76 {
77 rt::d3d12::VulkanDeviceInfo info{};
78 info.get_instance_proc = d.instance_proc;
79 info.instance = d.instance;
80 info.physical = d.physical;
81 info.device = d.device;
82 info.queue = d.queue;
83 info.queue_family = d.family;
84 info.buffer_device_address = true;
85 info.features = d.enabled;
86 info.subgroup = d.subgroup;
87 info.shader_dir = library.string();
88 ID3D12Device* inner = nullptr;
89 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner))));
90 Ref<ID3D12Device> device;
91 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device),
92 reinterpret_cast<void**>(&device.p))));
93 rt::d3d12::set_device_outer(inner, device.p);
94
95 D3D12_ROOT_PARAMETER params[2] = {};
96 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
97 params[0].Constants = {0, 0, 2};
98 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
99 params[1].Descriptor = {1, 0};
100 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
101 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
102 root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT};
103 const auto root_blob = serialize_root_signature(root_desc);
104 EXPECT(!root_blob.empty());
105 Ref<ID3D12RootSignature> root;
106 EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p))));
107
108 const D3D12_INPUT_ELEMENT_DESC elements[2] = {
109 {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
110 {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT,
111 D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
112 D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{};
113 pso_desc.pRootSignature = root.p;
114 pso_desc.VS = {vs_container.data(), vs_container.size()};
115 pso_desc.PS = {ps_container.data(), ps_container.size()};
116 pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
117 pso_desc.SampleMask = 0xffffffff;
118 pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
119 pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
120 pso_desc.RasterizerState.DepthClipEnable = TRUE;
121 pso_desc.InputLayout = {elements, 2};
122 pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
123 pso_desc.NumRenderTargets = 1;
124 pso_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
125 pso_desc.SampleDesc.Count = 1;
126 Ref<ID3D12PipelineState> plain, doubled, lines;
127 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&plain.p))));
128 pso_desc.GS = {gs_container.data(), gs_container.size()};
129 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&doubled.p))));
130 pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; // not the GS's input primitive
131 EXPECT(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&lines.p)) == E_INVALIDARG && !lines.p);
132
133 // The d3d12_draw_test quad in the top-left quadrant; root constants move it.
134 const Vertex vertices[4] = {
135 {-1, 1, 255, 0, 0, 255}, {0, 1, 255, 0, 0, 255}, {-1, 0, 255, 0, 0, 255}, {0, 0, 255, 0, 0, 255}};
136 const std::uint16_t indices[6] = {0, 1, 2, 2, 1, 3};
137 const float tints[2][3] = {{1, 0, 1}, {0, 1, 0}}; // red stays red; then green
138
139 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
140 const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
141 const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK};
142 Ref<ID3D12Resource> upload, readback, target;
143 const auto upload_desc = buffer_desc(4096);
144 EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc,
145 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
146 IID_PPV_ARGS(&upload.p))));
147 const auto readback_desc = buffer_desc(size * 256);
148 EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc,
149 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
150 IID_PPV_ARGS(&readback.p))));
151 D3D12_RESOURCE_DESC rt_desc{};
152 rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
153 rt_desc.Width = rt_desc.Height = size;
154 rt_desc.DepthOrArraySize = 1;
155 rt_desc.MipLevels = 1;
156 rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
157 rt_desc.SampleDesc.Count = 1;
158 rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
159 EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc,
160 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
161 IID_PPV_ARGS(&target.p))));
162 std::uint8_t* up = nullptr;
163 EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast<void**>(&up))));
164 std::memcpy(up, vertices, sizeof(vertices));
165 std::memcpy(up + 256, indices, sizeof(indices));
166 std::memcpy(up + 512, tints[0], sizeof(tints[0]));
167 std::memcpy(up + 768, tints[1], sizeof(tints[1]));
168 const D3D12_GPU_VIRTUAL_ADDRESS upload_va = upload->GetGPUVirtualAddress();
169
170 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
171 Ref<ID3D12DescriptorHeap> rtv_heap;
172 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p))));
173 const D3D12_CPU_DESCRIPTOR_HANDLE rtv{
174 SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(rtv_heap.p, 9))(rtv_heap.p))};
175 device->CreateRenderTargetView(target.p, nullptr, rtv);
176
177 D3D12_COMMAND_QUEUE_DESC queue_desc{};
178 Ref<ID3D12CommandQueue> queue;
179 Ref<ID3D12CommandAllocator> allocator;
180 Ref<ID3D12GraphicsCommandList> list;
181 Ref<ID3D12Fence> fence;
182 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
183 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
184 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, doubled.p,
185 IID_PPV_ARGS(&list.p))));
186 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
187
188 const FLOAT blue[4] = {0, 0, 1, 1};
189 list->ClearRenderTargetView(rtv, blue, 0, nullptr);
190 list->SetGraphicsRootSignature(root.p);
191 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
192 const D3D12_VERTEX_BUFFER_VIEW vbv{upload_va, sizeof(vertices), sizeof(Vertex)};
193 list->IASetVertexBuffers(0, 1, &vbv);
194 const D3D12_INDEX_BUFFER_VIEW ibv{upload_va + 256, sizeof(indices), DXGI_FORMAT_R16_UINT};
195 list->IASetIndexBuffer(&ibv);
196 const D3D12_VIEWPORT viewport{0, 0, float(size), float(size), 0, 1};
197 const D3D12_RECT scissor{0, 0, LONG(size), LONG(size)};
198 list->RSSetViewports(1, &viewport);
199 list->RSSetScissorRects(1, &scissor);
200 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
201 const float top_left[2] = {0, 0}, bottom_left[2] = {0, -1};
202 list->SetGraphicsRootConstantBufferView(1, upload_va + 512); // red
203 list->SetGraphicsRoot32BitConstants(0, 2, top_left, 0);
204 list->DrawIndexedInstanced(6, 1, 0, 0, 0); // GS: top-left and its copy top-right
205 list->SetPipelineState(plain.p);
206 list->SetGraphicsRootConstantBufferView(1, upload_va + 768); // green
207 list->SetGraphicsRoot32BitConstants(0, 2, bottom_left, 0);
208 list->DrawIndexedInstanced(6, 1, 0, 0, 0); // no GS: bottom-left only
209
210 D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET,
211 D3D12_RESOURCE_STATE_COPY_SOURCE);
212 list->ResourceBarrier(1, &to_copy);
213 D3D12_TEXTURE_COPY_LOCATION dst{};
214 dst.pResource = readback.p;
215 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
216 dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, size, size, 1, 256}};
217 D3D12_TEXTURE_COPY_LOCATION src{};
218 src.pResource = target.p;
219 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
220 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
221 EXPECT(list->Close() == S_OK);
222 ID3D12CommandList* lists[] = {list.p};
223 queue->ExecuteCommandLists(1, lists);
224 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
225 EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)));
226 EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
227 void* mapped = nullptr;
228 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
229 std::memcpy(pixels.data(), mapped, pixels.size());
230
231 for (auto* r : {&upload, &readback, &target}) r->reset();
232 plain.reset();
233 doubled.reset();
234 root.reset();
235 rtv_heap.reset();
236 list.reset();
237 allocator.reset();
238 queue.reset();
239 fence.reset();
240 EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1);
241 }
242 std::filesystem::remove_all(library);
243
244 unsigned mismatches = 0;
245 for (UINT row = 0; row < size; ++row) {
246 for (UINT col = 0; col < size; ++col) {
247 const bool top = row < size / 2, left = col < size / 2;
248 const std::array<std::uint8_t, 4> want = top ? std::array<std::uint8_t, 4>{255, 0, 0, 255}
249 : left ? std::array<std::uint8_t, 4>{0, 255, 0, 255}
250 : std::array<std::uint8_t, 4>{0, 0, 255, 255};
251 const std::uint8_t* got = pixels.data() + row * 256 + col * 4;
252 if (std::equal(want.begin(), want.end(), got)) continue;
253 if (mismatches++ < 6)
254 std::fprintf(stderr, "pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col, row, got[0], got[1],
255 got[2], got[3], want[0], want[1], want[2], want[3]);
256 }
257 }
258 EXPECT(!mismatches);
259 if (d.validation_errors()) {
260 std::fprintf(stderr, "%u validation errors\n", d.validation_errors());
261 return 1;
262 }
263 std::printf("geometry: a VS+GS+PS pipeline drew its quad and the GS's copy (top half red), a pipeline without a "
264 "GS only the quad (bottom-left green), all %u pixels matched; a GS with a line topology refused\n",
265 size * size);
266 return 0;
267}
diff --git a/runtime/test/d3d12_msaa_draw_test.cpp b/runtime/test/d3d12_msaa_draw_test.cpp
index 8b8aa06e1..2c87e880c 100644
--- a/runtime/test/d3d12_msaa_draw_test.cpp
+++ b/runtime/test/d3d12_msaa_draw_test.cpp
@@ -10,6 +10,7 @@
10// and 3 samples are E_INVALIDARG. A 4x PSO drawing into a single-sampled target fails the list at execute 10// and 3 samples are E_INVALIDARG. A 4x PSO drawing into a single-sampled target fails the list at execute
11// (invalid_subresource) instead of reaching the driver. Shaders: test/glsl/vs_draw.vert, ps_draw.frag. No game data. 11// (invalid_subresource) instead of reaching the driver. Shaders: test/glsl/vs_draw.vert, ps_draw.frag. No game data.
12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
13#include "shader_fixture_path.h"
13#include "vk_test_device.h" 14#include "vk_test_device.h"
14#include "d3d12_test_shaders.h" 15#include "d3d12_test_shaders.h"
15#include "../shims/d3d12_com.h" 16#include "../shims/d3d12_com.h"
@@ -53,8 +54,8 @@ int main() {
53 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); 54 const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program);
54 const auto library = std::filesystem::temp_directory_path() / "leonida_msaa_draw_test"; 55 const auto library = std::filesystem::temp_directory_path() / "leonida_msaa_draw_test";
55 std::filesystem::create_directories(library); 56 std::filesystem::create_directories(library);
56 std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing); 57 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), library / "vs_draw.spv", std::filesystem::copy_options::overwrite_existing);
57 std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing); 58 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_draw.spv", std::filesystem::copy_options::overwrite_existing);
58 { 59 {
59 std::ofstream index(library / "index.json", std::ios::binary); 60 std::ofstream index(library / "index.json", std::ios::binary);
60 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) 61 index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program)
@@ -131,7 +132,7 @@ int main() {
131 EXPECT(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&three.p)) == E_INVALIDARG && !three.p); 132 EXPECT(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&three.p)) == E_INVALIDARG && !three.p);
132 pso_desc.SampleDesc = {samples, 1}; // past NumQualityLevels (1): D3D12 returns E_INVALIDARG 133 pso_desc.SampleDesc = {samples, 1}; // past NumQualityLevels (1): D3D12 returns E_INVALIDARG
133 EXPECT(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&three.p)) == E_INVALIDARG && !three.p); 134 EXPECT(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&three.p)) == E_INVALIDARG && !three.p);
134 pso_desc.SampleDesc = {samples, UINT(D3D12_STANDARD_MULTISAMPLE_PATTERN)}; // accepted natively 135 pso_desc.SampleDesc = {samples, UINT(DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN)}; // accepted natively
135 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&three.p)))); 136 EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&three.p))));
136 three.reset(); 137 three.reset();
137 138
diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp
index cd7b411e5..5643c0d73 100644
--- a/runtime/test/d3d12_pipeline_library_test.cpp
+++ b/runtime/test/d3d12_pipeline_library_test.cpp
@@ -8,6 +8,7 @@
8// - GetSerializedSize + Serialize round-trip into a second CreatePipelineLibrary; 8// - GetSerializedSize + Serialize round-trip into a second CreatePipelineLibrary;
9// - GPU execution of both loaded compute and loaded graphics PSOs under LEONIDA_VK_VALIDATION=1. 9// - GPU execution of both loaded compute and loaded graphics PSOs under LEONIDA_VK_VALIDATION=1.
10// No game data. 10// No game data.
11#include "shader_fixture_path.h"
11#include "vk_test_device.h" 12#include "vk_test_device.h"
12#include "d3d12_test_shaders.h" 13#include "d3d12_test_shaders.h"
13#include "../shims/d3d12_com.h" 14#include "../shims/d3d12_com.h"
@@ -69,11 +70,11 @@ int main() {
69 70
70 const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_pipeline_library_test"; 71 const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_pipeline_library_test";
71 std::filesystem::create_directories(lib_dir); 72 std::filesystem::create_directories(lib_dir);
72 std::filesystem::copy_file(LEONIDA_TEST_CS_SPV, lib_dir / "cs.spv", 73 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), lib_dir / "cs.spv",
73 std::filesystem::copy_options::overwrite_existing); 74 std::filesystem::copy_options::overwrite_existing);
74 std::filesystem::copy_file(LEONIDA_TEST_VS_SPV, lib_dir / "vs.spv", 75 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_SPV), lib_dir / "vs.spv",
75 std::filesystem::copy_options::overwrite_existing); 76 std::filesystem::copy_options::overwrite_existing);
76 std::filesystem::copy_file(LEONIDA_TEST_PS_SPV, lib_dir / "ps.spv", 77 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), lib_dir / "ps.spv",
77 std::filesystem::copy_options::overwrite_existing); 78 std::filesystem::copy_options::overwrite_existing);
78 { 79 {
79 std::ofstream idx(lib_dir / "index.json", std::ios::binary); 80 std::ofstream idx(lib_dir / "index.json", std::ios::binary);
diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp
index 44c7f4624..c3a0f4d39 100644
--- a/runtime/test/d3d12_present_test.cpp
+++ b/runtime/test/d3d12_present_test.cpp
@@ -3,8 +3,9 @@
3// moves the back buffer PRESENT -> RENDER_TARGET, clears it, moves it back, executes, presents and signals a fence. 3// moves the back buffer PRESENT -> RENDER_TARGET, clears it, moves it back, executes, presents and signals a fence.
4// The window is then resized, which recreates the swapchain and scales the blit. The presented images are copied 4// The window is then resized, which recreates the swapchain and scales the blit. The presented images are copied
5// back (the presenter's capture) and must hold the clear colour at the swapchain's size. Last, the colour on screen 5// back (the presenter's capture) and must hold the clear colour at the swapchain's size. Last, the colour on screen
6// is read back with GDI when the window is in front, the display is in SDR and GDI can read the screen (skipped 6// is read back with GDI on native Windows when the window is in front, the display is in SDR and GDI can read the
7// otherwise, e.g. in HDR, on a locked desktop or under Wine's macOS driver). No shaders or game data. 7// screen. Under Wine, rootless XWayland can return black for desktop reads, so the swapchain checks confirm the
8// colour there. No shaders or game data.
8// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. 9// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test.
9#include "vk_test_device.h" 10#include "vk_test_device.h"
10#include "../shims/d3d12_com.h" 11#include "../shims/d3d12_com.h"
@@ -461,13 +462,16 @@ int main() {
461 "(%u real out-of-date presents)\n", 462 "(%u real out-of-date presents)\n",
462 real_out_of_date); 463 real_out_of_date);
463 464
464 // What reached the screen: the centre of the client area, if the window is in front. This needs GDI to read 465 // Wine's desktop GDI read can return black even when the compositor presents the right colour.
465 // the screen, which not every window system gives it: under Wine's macOS driver the screen DC reads nothing 466 // The swapchain checks above also cover Wine drivers that cannot read the desktop at all.
466 // (GetPixel returns CLR_INVALID even for a pixel GDI itself painted), so there the swapchain checks above are 467 const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr;
467 // what confirms the colour. 468 if (!wine) {
468 Sleep(200); 469 Sleep(200);
469 pump(); 470 pump();
470 if (GetForegroundWindow() == window && !IsIconic(window)) { 471 }
472 if (wine) {
473 std::printf("Wine: on-screen colour check skipped after swapchain readback\n");
474 } else if (GetForegroundWindow() == window && !IsIconic(window)) {
471 if (is_hdr_monitor(window)) { 475 if (is_hdr_monitor(window)) {
472 std::printf("the monitor is in HDR mode: on-screen colour check skipped\n"); 476 std::printf("the monitor is in HDR mode: on-screen colour check skipped\n");
473 } else { 477 } else {
diff --git a/runtime/test/d3d12_private_data_test.cpp b/runtime/test/d3d12_private_data_test.cpp
new file mode 100644
index 000000000..4c1848a9c
--- /dev/null
+++ b/runtime/test/d3d12_private_data_test.cpp
@@ -0,0 +1,346 @@
1// ID3D12Object private data on the Vulkan-backed device, compared with the host PC runtime: GetPrivateData,
2// SetPrivateData, SetPrivateDataInterface and SetName (runtime/shims/d3d12_com_object.h, D3D-24). The same script
3// runs on the device and on a fence, a committed buffer, a command allocator and a descriptor heap of each device,
4// and records every HRESULT, every size the call writes back, the bytes it reads and the reference count of an
5// interface the object holds. The two records must be the same, step by step. No shaders or game data. Skips (77)
6// without a Vulkan GPU; without a host D3D12 device only the layer's own record is printed. Set
7// LEONIDA_D3D49_VERBOSE=1 to print every step.
8#include "vk_test_device.h"
9#include "../shims/d3d12_com.h"
10
11#include <cstdint>
12#include <cstdio>
13#include <cstring>
14#include <string>
15#include <vector>
16
17#define EXPECT(condition) do { \
18 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
19} while (0)
20
21namespace {
22
23template<class T>
24struct Ref {
25 T* p = nullptr;
26 ~Ref() { reset(); }
27 void reset() {
28 if (p) p->Release();
29 p = nullptr;
30 }
31 T* operator->() const { return p; }
32};
33
34// An interface for SetPrivateDataInterface that counts its references, the same object type on both devices.
35class Counted final : public IUnknown {
36public:
37 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
38 if (!out) return E_POINTER;
39 if (riid == __uuidof(IUnknown)) {
40 *out = this;
41 AddRef();
42 return S_OK;
43 }
44 *out = nullptr;
45 return E_NOINTERFACE;
46 }
47 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; }
48 ULONG STDMETHODCALLTYPE Release() override { return --refs; } // lives on the stack; never deleted
49 ULONG refs = 1;
50};
51
52// WKPDID_D3DDebugObjectName / ...NameW (d3dcommon.h), spelled out so nothing needs dxguid.lib.
53constexpr GUID kName{0x429b8c22, 0x9188, 0x4b0c, {0x87, 0x42, 0xac, 0xb0, 0xbf, 0x85, 0xc2, 0x00}};
54constexpr GUID kNameW{0x4cca5fd8, 0x921f, 0x42c8, {0x85, 0x99, 0xd2, 0x86, 0x6a, 0x3e, 0x5f, 0x7e}};
55
56// A key of its own for each step, so no step sees another's entry.
57GUID key(unsigned step) { return GUID{0x5eed0000u + step, 0x1d3d, 0x4c12, {0x9a, 0x41, 0x77, 0x10, 0x2b, 0x6c, 0x00, 0x01}}; }
58
59struct Record {
60 std::vector<std::string> names;
61 std::vector<std::uint64_t> values;
62 void add(const std::string& name, std::uint64_t value) {
63 names.push_back(name);
64 values.push_back(value);
65 }
66};
67
68// A call the host may fault on is recorded as this value instead of crashing the test.
69constexpr std::uint64_t kFaulted = 0xC0000005;
70
71HRESULT get_guarded(ID3D12Object* o, REFGUID guid, UINT* size, void* data) {
72 __try {
73 return o->GetPrivateData(guid, size, data);
74 } __except (EXCEPTION_EXECUTE_HANDLER) {
75 return HRESULT(kFaulted);
76 }
77}
78
79HRESULT set_guarded(ID3D12Object* o, REFGUID guid, UINT size, const void* data) {
80 __try {
81 return o->SetPrivateData(guid, size, data);
82 } __except (EXCEPTION_EXECUTE_HANDLER) {
83 return HRESULT(kFaulted);
84 }
85}
86
87HRESULT name_guarded(ID3D12Object* o, LPCWSTR name) {
88 __try {
89 return o->SetName(name);
90 } __except (EXCEPTION_EXECUTE_HANDLER) {
91 return HRESULT(kFaulted);
92 }
93}
94
95// GetPrivateData with a buffer of `capacity` bytes (null when `with_buffer` is false), starting the size at
96// `capacity`. Records the HRESULT, the size written back and the first 8 bytes of the buffer (filled with 0xCD).
97void get(Record& r, const std::string& what, ID3D12Object* o, REFGUID guid, UINT capacity, bool with_buffer = true) {
98 std::uint8_t buffer[64];
99 std::memset(buffer, 0xCD, sizeof(buffer));
100 UINT size = capacity;
101 const HRESULT hr = get_guarded(o, guid, &size, with_buffer ? buffer : nullptr);
102 r.add(what + ": hr", std::uint32_t(hr));
103 r.add(what + ": size", size);
104 std::uint64_t head = 0;
105 std::memcpy(&head, buffer, sizeof(head));
106 if (with_buffer) r.add(what + ": bytes", head);
107}
108
109void script(Record& r, ID3D12Object* o) {
110 const std::uint8_t eight[8] = {1, 2, 3, 4, 5, 6, 7, 8};
111 const std::uint8_t four[4] = {9, 10, 11, 12};
112 unsigned step = 0;
113
114 // A key that was never set.
115 {
116 const GUID g = key(++step);
117 get(r, "missing, 16-byte buffer", o, g, 16);
118 get(r, "missing, size query", o, g, 16, false);
119 get(r, "missing, size 0", o, g, 0);
120 r.add("missing, null size: hr", std::uint32_t(get_guarded(o, g, nullptr, nullptr)));
121 }
122 // Eight bytes, read back with buffers of every size around them.
123 {
124 const GUID g = key(++step);
125 r.add("set 8 bytes: hr", std::uint32_t(set_guarded(o, g, 8, eight)));
126 get(r, "8 bytes, size query", o, g, 0, false);
127 get(r, "8 bytes, size query from 100", o, g, 100, false);
128 get(r, "8 bytes, 4-byte buffer", o, g, 4);
129 get(r, "8 bytes, 0-byte buffer", o, g, 0);
130 get(r, "8 bytes, 8-byte buffer", o, g, 8);
131 get(r, "8 bytes, 64-byte buffer", o, g, 64);
132 r.add("8 bytes, null size: hr", std::uint32_t(get_guarded(o, g, nullptr, nullptr)));
133 r.add("overwrite with 4 bytes: hr", std::uint32_t(set_guarded(o, g, 4, four)));
134 get(r, "after overwrite", o, g, 64);
135 }
136 // Removal: size 0, null data, or both.
137 {
138 const GUID g = key(++step);
139 set_guarded(o, g, 8, eight);
140 r.add("set 8 with null data: hr", std::uint32_t(set_guarded(o, g, 8, nullptr)));
141 get(r, "after 8 with null data", o, g, 64);
142 }
143 {
144 const GUID g = key(++step);
145 set_guarded(o, g, 8, eight);
146 r.add("set 0 bytes with data: hr", std::uint32_t(set_guarded(o, g, 0, eight)));
147 get(r, "after 0 bytes with data", o, g, 64);
148 }
149 {
150 const GUID g = key(++step);
151 set_guarded(o, g, 8, eight);
152 r.add("set 0 bytes, null data: hr", std::uint32_t(set_guarded(o, g, 0, nullptr)));
153 get(r, "after 0 bytes, null data", o, g, 64);
154 }
155 {
156 const GUID g = key(++step);
157 r.add("set 8 with null data on a missing key: hr", std::uint32_t(set_guarded(o, g, 8, nullptr)));
158 r.add("set 0 bytes on a missing key: hr", std::uint32_t(set_guarded(o, g, 0, nullptr)));
159 get(r, "missing key after removals", o, g, 64);
160 }
161 {
162 const GUID g = key(++step);
163 r.add("set 0 bytes with data on a missing key: hr", std::uint32_t(set_guarded(o, g, 0, eight)));
164 get(r, "after 0 bytes with data on a missing key", o, g, 64);
165 get(r, "after 0 bytes with data on a missing key, size query", o, g, 64, false);
166 r.add("then 0 bytes, null data: hr", std::uint32_t(set_guarded(o, g, 0, nullptr)));
167 get(r, "after removing the empty entry", o, g, 64);
168 }
169 {
170 const GUID g = key(++step);
171 r.add("null interface on a missing key: hr", std::uint32_t(o->SetPrivateDataInterface(g, nullptr)));
172 get(r, "after a null interface, 4-byte buffer", o, g, 4);
173 get(r, "after a null interface, 64-byte buffer", o, g, 64);
174 r.add("null interface again: hr", std::uint32_t(o->SetPrivateDataInterface(g, nullptr)));
175 r.add("remove the null interface: hr", std::uint32_t(set_guarded(o, g, 0, nullptr)));
176 get(r, "after removing the null interface", o, g, 64);
177 }
178 // An interface entry: the object's references to it, and what reading it gives.
179 {
180 const GUID g = key(++step);
181 Counted payload;
182 r.add("interface: set hr", std::uint32_t(o->SetPrivateDataInterface(g, &payload)));
183 r.add("interface: refs after set", payload.refs);
184 get(r, "interface, size query", o, g, 0, false);
185 r.add("interface, size query: refs", payload.refs);
186 get(r, "interface, 4-byte buffer", o, g, 4);
187 r.add("interface, 4-byte buffer: refs", payload.refs);
188 {
189 IUnknown* read = nullptr;
190 UINT size = sizeof(read);
191 const HRESULT hr = get_guarded(o, g, &size, &read);
192 r.add("interface, pointer-size buffer: hr", std::uint32_t(hr));
193 r.add("interface, pointer-size buffer: size", size);
194 r.add("interface, pointer-size buffer: same object", read == &payload);
195 r.add("interface, pointer-size buffer: refs", payload.refs);
196 if (read == &payload) read->Release();
197 }
198 r.add("interface: set again hr", std::uint32_t(o->SetPrivateDataInterface(g, &payload)));
199 r.add("interface: refs after setting again", payload.refs);
200 r.add("interface: bytes over it hr", std::uint32_t(set_guarded(o, g, 4, four)));
201 r.add("interface: refs after bytes over it", payload.refs);
202 get(r, "interface, then bytes", o, g, 64);
203 r.add("interface: set over bytes hr", std::uint32_t(o->SetPrivateDataInterface(g, &payload)));
204 r.add("interface: refs after set over bytes", payload.refs);
205 r.add("interface: null hr", std::uint32_t(o->SetPrivateDataInterface(g, nullptr)));
206 r.add("interface: refs after null", payload.refs);
207 get(r, "interface, after null", o, g, 64);
208 // Removed with SetPrivateData(0, null) instead.
209 o->SetPrivateDataInterface(g, &payload);
210 r.add("interface: removed with bytes hr", std::uint32_t(set_guarded(o, g, 0, nullptr)));
211 r.add("interface: refs after removal with bytes", payload.refs);
212 get(r, "interface, after removal with bytes", o, g, 64);
213 o->SetPrivateDataInterface(g, nullptr);
214 }
215 // SetName: where the name goes, and what an empty or null name does.
216 {
217 r.add("SetName abc: hr", std::uint32_t(name_guarded(o, L"abc")));
218 get(r, "name W after abc", o, kNameW, 64);
219 get(r, "name A after abc", o, kName, 64);
220 r.add("SetName empty: hr", std::uint32_t(name_guarded(o, L"")));
221 get(r, "name W after empty", o, kNameW, 64);
222 get(r, "name A after empty", o, kName, 64);
223 r.add("SetName null: hr", std::uint32_t(name_guarded(o, nullptr)));
224 get(r, "name W after null", o, kNameW, 64);
225 get(r, "name A after null", o, kName, 64);
226 // A name set through the narrow key, and SetName after it.
227 const char narrow[] = "xyz";
228 r.add("set narrow name: hr", std::uint32_t(set_guarded(o, kName, sizeof(narrow), narrow)));
229 get(r, "name W after narrow", o, kNameW, 64);
230 r.add("SetName def after narrow: hr", std::uint32_t(name_guarded(o, L"def")));
231 get(r, "name A after def", o, kName, 64);
232 get(r, "name W after def", o, kNameW, 64);
233 set_guarded(o, kName, 0, nullptr);
234 name_guarded(o, nullptr);
235 }
236}
237
238// The objects the script runs on, made on `device`: the device itself and four children.
239struct Objects {
240 Ref<ID3D12Fence> fence;
241 Ref<ID3D12Resource> buffer;
242 Ref<ID3D12CommandAllocator> allocator;
243 Ref<ID3D12DescriptorHeap> heap;
244};
245
246bool make(ID3D12Device* device, Objects& o) {
247 D3D12_RESOURCE_DESC desc{};
248 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
249 desc.Width = 256;
250 desc.Height = 1;
251 desc.DepthOrArraySize = 1;
252 desc.MipLevels = 1;
253 desc.SampleDesc.Count = 1;
254 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
255 const D3D12_HEAP_PROPERTIES upload{D3D12_HEAP_TYPE_UPLOAD};
256 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4};
257 return SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&o.fence.p))) &&
258 SUCCEEDED(device->CreateCommittedResource(&upload, D3D12_HEAP_FLAG_NONE, &desc,
259 D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
260 IID_PPV_ARGS(&o.buffer.p))) &&
261 SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&o.allocator.p))) &&
262 SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&o.heap.p)));
263}
264
265// The records of every object of `device`, in a fixed order, each name prefixed with the object's kind.
266bool record(ID3D12Device* device, Record& r) {
267 Objects o;
268 if (!make(device, o)) return false;
269 const struct {
270 const char* kind;
271 ID3D12Object* object;
272 } objects[] = {{"device", device}, {"fence", o.fence.p}, {"buffer", o.buffer.p},
273 {"allocator", o.allocator.p}, {"descriptor heap", o.heap.p}};
274 for (const auto& entry : objects) {
275 Record one;
276 script(one, entry.object);
277 for (std::size_t i = 0; i < one.names.size(); ++i) r.add(std::string(entry.kind) + ": " + one.names[i], one.values[i]);
278 }
279 // An object that dies holding an interface releases it.
280 Counted payload;
281 {
282 Ref<ID3D12Fence> fence;
283 if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) return false;
284 fence->SetPrivateDataInterface(key(100), &payload);
285 r.add("dying fence: refs while held", payload.refs);
286 }
287 r.add("dying fence: refs after release", payload.refs);
288 return true;
289}
290
291} // namespace
292
293int main() {
294 vktest::Device d;
295 const auto device_status = d.initialize();
296 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
297 if (device_status != vktest::DeviceStatus::ready) return 1;
298 const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0;
299 {
300 rt::d3d12::VulkanDeviceInfo info{};
301 info.get_instance_proc = d.instance_proc;
302 info.instance = d.instance;
303 info.physical = d.physical;
304 info.device = d.device;
305 info.queue = d.queue;
306 info.queue_family = d.family;
307 Ref<ID3D12Device> device;
308 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
309 Record ours;
310 EXPECT(record(device.p, ours));
311
312 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
313 const auto create_host = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(
314 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")))
315 : nullptr;
316 Ref<ID3D12Device> host;
317 if (!create_host || FAILED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) {
318 std::printf("private data: no host D3D12 device to compare with; %zu steps recorded, not compared\n",
319 ours.values.size());
320 } else {
321 Record theirs;
322 EXPECT(record(host.p, theirs));
323 EXPECT(theirs.names == ours.names);
324 int mismatches = 0, faulted = 0;
325 for (std::size_t i = 0; i < ours.values.size(); ++i) {
326 if (theirs.values[i] == kFaulted) { // SetName(nullptr): the host faults; the layer clears the name
327 std::printf("private data %s: the host faults, not compared (ours 0x%llx)\n",
328 ours.names[i].c_str(), static_cast<unsigned long long>(ours.values[i]));
329 ++faulted;
330 continue;
331 }
332 const bool same = ours.values[i] == theirs.values[i];
333 if (verbose || !same)
334 std::printf("private data %s: ours 0x%llx host 0x%llx%s\n", ours.names[i].c_str(),
335 static_cast<unsigned long long>(ours.values[i]),
336 static_cast<unsigned long long>(theirs.values[i]), same ? "" : " MISMATCH");
337 mismatches += !same;
338 }
339 std::printf("private data: %zu steps compared with the host (%d more the host faults on), %d mismatches\n",
340 ours.values.size() - faulted, faulted, mismatches);
341 EXPECT(mismatches == 0);
342 }
343 }
344 std::printf("d3d12_private_data_test: OK\n");
345 return 0;
346}
diff --git a/runtime/test/d3d12_set0_compute_test.cpp b/runtime/test/d3d12_set0_compute_test.cpp
index 69663d764..0b0646593 100644
--- a/runtime/test/d3d12_set0_compute_test.cpp
+++ b/runtime/test/d3d12_set0_compute_test.cpp
@@ -15,6 +15,7 @@
15// A device without the bindless set refuses the PSO. No game data: the program is two marker words and the module is 15// A device without the bindless set refuses the PSO. No game data: the program is two marker words and the module is
16// GLSL written to the translator's contract. 16// GLSL written to the translator's contract.
17// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). 17// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required).
18#include "shader_fixture_path.h"
18#include "vk_test_device.h" 19#include "vk_test_device.h"
19#include "d3d12_test_shaders.h" 20#include "d3d12_test_shaders.h"
20#include "../shims/d3d12_com.h" 21#include "../shims/d3d12_com.h"
@@ -69,7 +70,7 @@ int main() {
69 const auto container = shader_container(program); 70 const auto container = shader_container(program);
70 const auto library = std::filesystem::temp_directory_path() / "leonida_set0_compute_test"; 71 const auto library = std::filesystem::temp_directory_path() / "leonida_set0_compute_test";
71 std::filesystem::create_directories(library); 72 std::filesystem::create_directories(library);
72 std::filesystem::copy_file(LEONIDA_TEST_CS_SET0_SAMPLE_SPV, library / "cs_set0_sample.spv", 73 std::filesystem::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SET0_SAMPLE_SPV), library / "cs_set0_sample.spv",
73 std::filesystem::copy_options::overwrite_existing); 74 std::filesystem::copy_options::overwrite_existing);
74 { 75 {
75 std::ofstream index(library / "index.json", std::ios::binary); 76 std::ofstream index(library / "index.json", std::ios::binary);
diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp
index 77ef6222d..58a649437 100644
--- a/runtime/test/d3d12_state_map_test.cpp
+++ b/runtime/test/d3d12_state_map_test.cpp
@@ -227,6 +227,48 @@ int main() {
227 CHECK(!(vulkan_access(s::predication, false).access & VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT)); 227 CHECK(!(vulkan_access(s::predication, false).access & VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT));
228 CHECK(!(vulkan_access(s::copy_dest, false, true).stages & VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT)); 228 CHECK(!(vulkan_access(s::copy_dest, false, true).stages & VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT));
229 229
230 // Primitive topology: a D3D12_PRIMITIVE_TOPOLOGY value maps to a VkPrimitiveTopology, and strip topologies are
231 // the ones a primitive-restart index cuts. A wrong map draws the wrong primitive; a wrong strip classification
232 // restarts (or fails to restart) an indexed strip. The D3D12 values are the public D3D_PRIMITIVE_TOPOLOGY enum.
233 {
234 using detail::strip_topology;
235 using detail::vulkan_topology;
236#ifdef _WIN32
237 static_assert(D3D_PRIMITIVE_TOPOLOGY_POINTLIST == 1 && D3D_PRIMITIVE_TOPOLOGY_LINELIST == 2 &&
238 D3D_PRIMITIVE_TOPOLOGY_LINESTRIP == 3 && D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST == 4 &&
239 D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP == 5 && D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ == 10 &&
240 D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ == 11 && D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ == 12 &&
241 D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ == 13,
242 "D3D_PRIMITIVE_TOPOLOGY values the topology map is keyed on");
243#endif
244 struct TopoCase {
245 std::uint32_t d3d;
246 VkPrimitiveTopology vk;
247 bool strip;
248 };
249 static constexpr TopoCase topos[] = {
250 {1, VK_PRIMITIVE_TOPOLOGY_POINT_LIST, false}, // POINTLIST
251 {2, VK_PRIMITIVE_TOPOLOGY_LINE_LIST, false}, // LINELIST
252 {3, VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, true}, // LINESTRIP
253 {5, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, true}, // TRIANGLESTRIP
254 {10, VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY, false}, // LINELIST_ADJ
255 {11, VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY, true}, // LINESTRIP_ADJ
256 {12, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY, false}, // TRIANGLELIST_ADJ
257 {13, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY, true}, // TRIANGLESTRIP_ADJ
258 };
259 for (const auto& t : topos) {
260 CHECK(vulkan_topology(t.d3d) == t.vk);
261 CHECK(strip_topology(t.vk) == t.strip);
262 }
263 // TRIANGLELIST (4), UNDEFINED (0) and any unmapped value fall back to the triangle list, which is not a strip.
264 CHECK(vulkan_topology(4) == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
265 CHECK(vulkan_topology(0) == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
266 CHECK(vulkan_topology(99) == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
267 CHECK(!strip_topology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST));
268 CHECK(!strip_topology(VK_PRIMITIVE_TOPOLOGY_LINE_LIST));
269 CHECK(!strip_topology(VK_PRIMITIVE_TOPOLOGY_POINT_LIST));
270 }
271
230 // Subresource indices: mip + layer * mips + plane * mips * layers. 272 // Subresource indices: mip + layer * mips + plane * mips * layers.
231 VkImageSubresourceRange range{}; 273 VkImageSubresourceRange range{};
232 ResourceBinding color{}; 274 ResourceBinding color{};
@@ -274,6 +316,62 @@ int main() {
274 CHECK(detail::prepare_texture_copy(copy, upload) == ReplayResult::invalid_copy); 316 CHECK(detail::prepare_texture_copy(copy, upload) == ReplayResult::invalid_copy);
275 CHECK(upload.buffer_image_copies.size() == 1); 317 CHECK(upload.buffer_image_copies.size() == 1);
276 318
319 // Block-compressed texture to texture between mips of a 24x24 BC1 texture (mips 24, 12, 6, 3, 1). The host
320 // copies whole blocks; where one vkCmdCopyImage extent cannot reach the edge of both mips, the copy is described
321 // as a read into transfer scratch and a write from it (offsets from the scratch's start; prepare allocates it).
322 {
323 ResourceBinding bc1 = color;
324 bc1.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
325 bc1.width = bc1.height = 24;
326 bc1.depth = 1;
327 bc1.mip_levels = 5;
328 bc1.array_layers = 1;
329 const auto bc_copy = [&](std::uint32_t dst_mip, std::uint32_t x, std::uint32_t y, std::uint32_t src_mip,
330 bool has_box, CopyBox box, detail::Prepared& p) {
331 p = {};
332 p.binding = p.source = bc1;
333 CopyTexture c{};
334 c.dst = {1, false, dst_mip, 0, 0, 0, 0, 0};
335 c.src = {1, false, src_mip, 0, 0, 0, 0, 0};
336 c.x = x;
337 c.y = y;
338 c.has_box = has_box;
339 c.box = box;
340 return detail::prepare_texture_copy(c, p);
341 };
342 const auto extent_is = [](const VkExtent3D& e, std::uint32_t w, std::uint32_t h) {
343 return e.width == w && e.height == h && e.depth == 1;
344 };
345 const auto staged = [](const detail::Prepared& p) {
346 return p.image_copies.empty() && p.staged_reads.size() == 1 && p.staged_writes.size() == 1;
347 };
348 detail::Prepared p{};
349 // Both edges reachable with one extent: a direct copy, nothing staged.
350 CHECK(bc_copy(1, 0, 0, 0, true, {0, 0, 0, 12, 12, 1}, p) == ReplayResult::success);
351 CHECK(p.image_copies.size() == 1 && p.staged_reads.empty() && extent_is(p.image_copies[0].extent, 12, 12));
352 // A 4x4 box into the 3x3 mip 3: one block read 4x4 from mip 0 and written 3x3.
353 CHECK(bc_copy(3, 0, 0, 0, true, {0, 0, 0, 4, 4, 1}, p) == ReplayResult::success && staged(p));
354 CHECK(p.staged_reads[0].bufferRowLength == 4 && p.staged_reads[0].bufferImageHeight == 4);
355 CHECK(p.staged_reads[0].imageSubresource.mipLevel == 0 && extent_is(p.staged_reads[0].imageExtent, 4, 4));
356 CHECK(p.staged_writes[0].imageSubresource.mipLevel == 3 && extent_is(p.staged_writes[0].imageExtent, 3, 3));
357 CHECK(p.staged_writes[0].bufferOffset == 0 && p.staged_writes[0].bufferRowLength == 4);
358 // The 6x6 mip 2 into the 12x12 mip 1: 2x2 blocks, read to the 6x6 edge, written as 8x8.
359 CHECK(bc_copy(1, 0, 0, 2, false, {}, p) == ReplayResult::success && staged(p));
360 CHECK(p.staged_reads[0].bufferRowLength == 8 && extent_is(p.staged_reads[0].imageExtent, 6, 6) &&
361 extent_is(p.staged_writes[0].imageExtent, 8, 8));
362 // The 3x3 mip 3 into the 6x6 mip 2 at 4,4: read 3x3, written 2x2 at (4, 4).
363 CHECK(bc_copy(2, 4, 4, 3, false, {}, p) == ReplayResult::success && staged(p));
364 CHECK(extent_is(p.staged_reads[0].imageExtent, 3, 3) && extent_is(p.staged_writes[0].imageExtent, 2, 2));
365 CHECK(p.staged_writes[0].imageOffset.x == 4 && p.staged_writes[0].imageOffset.y == 4);
366 // The box 4..8 of the 6x6 mip 2 (its edge inside the block) into the 3x3 mip 3: read 2x2 at (4, 4).
367 CHECK(bc_copy(3, 0, 0, 2, true, {4, 4, 0, 8, 8, 1}, p) == ReplayResult::success && staged(p));
368 CHECK(p.staged_reads[0].imageOffset.x == 4 && extent_is(p.staged_reads[0].imageExtent, 2, 2) &&
369 extent_is(p.staged_writes[0].imageExtent, 3, 3));
370 // What does not fit the destination's padded mip is refused, staged or not.
371 CHECK(bc_copy(3, 0, 0, 0, true, {0, 0, 0, 16, 16, 1}, p) == ReplayResult::invalid_copy);
372 CHECK(bc_copy(0, 16, 16, 1, false, {}, p) == ReplayResult::invalid_copy);
373 }
374
277 ResourceBinding depth_stencil = color; 375 ResourceBinding depth_stencil = color;
278 depth_stencil.aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; 376 depth_stencil.aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
279 depth_stencil.mip_levels = 2; 377 depth_stencil.mip_levels = 2;
@@ -584,6 +682,10 @@ int main() {
584 CHECK(memory_type_order(memory, 0xF, host, local, 224395264) == (order{3, 1, 2})); // exactly fits 682 CHECK(memory_type_order(memory, 0xF, host, local, 224395264) == (order{3, 1, 2})); // exactly fits
585 CHECK(memory_type_order(memory, 0x7, host, local, 128 * mib) == (order{1, 2})); // type 3 not allowed 683 CHECK(memory_type_order(memory, 0x7, host, local, 128 * mib) == (order{1, 2})); // type 3 not allowed
586 CHECK(memory_type_order(memory, 0xF, 0, local, 1 * mib) == (order{0, 3, 1, 2})); 684 CHECK(memory_type_order(memory, 0xF, 0, local, 1 * mib) == (order{0, 3, 1, 2}));
685 // D3D-299: types 1 and 2 lack DEVICE_LOCAL; when preferred local fails, allocations fall back to them (host spill).
686 const order spill_order = memory_type_order(memory, 0xF, 0, local, 1 * mib);
687 CHECK((memory.memoryTypes[spill_order[2]].propertyFlags & local) == 0);
688 CHECK((memory.memoryTypes[spill_order[3]].propertyFlags & local) == 0);
587 CHECK(memory_type_order(memory, 0xF, host, local, 64ull << 30).empty()); // nothing that large 689 CHECK(memory_type_order(memory, 0xF, host, local, 64ull << 30).empty()); // nothing that large
588 memory.memoryHeaps[2].size = 24ull << 30; // Resizable BAR on 690 memory.memoryHeaps[2].size = 24ull << 30; // Resizable BAR on
589 CHECK(memory_type_order(memory, 0xF, host, local, 256 * mib) == (order{3, 1, 2})); 691 CHECK(memory_type_order(memory, 0xF, host, local, 256 * mib) == (order{3, 1, 2}));
@@ -610,6 +712,24 @@ int main() {
610 {VK_FORMAT_R32_UINT, 4, 1}, {VK_FORMAT_R8G8_UNORM, 2, 1}, 712 {VK_FORMAT_R32_UINT, 4, 1}, {VK_FORMAT_R8G8_UNORM, 2, 1},
611 {VK_FORMAT_R16_SFLOAT, 2, 1}, {VK_FORMAT_R16_UNORM, 2, 1}, 713 {VK_FORMAT_R16_SFLOAT, 2, 1}, {VK_FORMAT_R16_UNORM, 2, 1},
612 {VK_FORMAT_R8_UNORM, 1, 1}, 714 {VK_FORMAT_R8_UNORM, 1, 1},
715 // Integer and additional packed formats the DXGI map also produces: each SINT/SNORM/UINT variant is the
716 // size of its UNORM/SFLOAT sibling, and the PACK16/PACK32 formats are 2 and 4 bytes.
717 {VK_FORMAT_R32G32B32A32_SINT, 16, 1},
718 {VK_FORMAT_R16G16B16A16_SNORM, 8, 1}, {VK_FORMAT_R16G16B16A16_UINT, 8, 1},
719 {VK_FORMAT_R16G16B16A16_SINT, 8, 1}, {VK_FORMAT_R32G32_UINT, 8, 1},
720 {VK_FORMAT_R32G32_SINT, 8, 1},
721 {VK_FORMAT_A2B10G10R10_UINT_PACK32, 4, 1}, {VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, 4, 1},
722 {VK_FORMAT_R8G8B8A8_SNORM, 4, 1}, {VK_FORMAT_R8G8B8A8_SINT, 4, 1},
723 {VK_FORMAT_R16G16_UNORM, 4, 1}, {VK_FORMAT_R16G16_SNORM, 4, 1},
724 {VK_FORMAT_R16G16_UINT, 4, 1}, {VK_FORMAT_R16G16_SINT, 4, 1},
725 {VK_FORMAT_R32_SINT, 4, 1},
726 {VK_FORMAT_R5G6B5_UNORM_PACK16, 2, 1}, {VK_FORMAT_A1R5G5B5_UNORM_PACK16, 2, 1},
727 {VK_FORMAT_A4R4G4B4_UNORM_PACK16, 2, 1}, {VK_FORMAT_R4G4B4A4_UNORM_PACK16, 2, 1},
728 {VK_FORMAT_R8G8_SNORM, 2, 1}, {VK_FORMAT_R8G8_UINT, 2, 1},
729 {VK_FORMAT_R8G8_SINT, 2, 1}, {VK_FORMAT_R16_SNORM, 2, 1},
730 {VK_FORMAT_R16_UINT, 2, 1}, {VK_FORMAT_R16_SINT, 2, 1},
731 {VK_FORMAT_R8_SNORM, 1, 1}, {VK_FORMAT_R8_UINT, 1, 1},
732 {VK_FORMAT_R8_SINT, 1, 1},
613 // Block-compressed: one 4x4 block is 8 bytes (BC1, BC4) or 16 bytes (BC2, BC3, BC5, BC6H, BC7). 733 // Block-compressed: one 4x4 block is 8 bytes (BC1, BC4) or 16 bytes (BC2, BC3, BC5, BC6H, BC7).
614 {VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 8, 4}, {VK_FORMAT_BC1_RGBA_SRGB_BLOCK, 8, 4}, 734 {VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 8, 4}, {VK_FORMAT_BC1_RGBA_SRGB_BLOCK, 8, 4},
615 {VK_FORMAT_BC4_UNORM_BLOCK, 8, 4}, {VK_FORMAT_BC4_SNORM_BLOCK, 8, 4}, 735 {VK_FORMAT_BC4_UNORM_BLOCK, 8, 4}, {VK_FORMAT_BC4_SNORM_BLOCK, 8, 4},
diff --git a/runtime/test/d3d12_subresource_copy_test.cpp b/runtime/test/d3d12_subresource_copy_test.cpp
new file mode 100644
index 000000000..17b6e179e
--- /dev/null
+++ b/runtime/test/d3d12_subresource_copy_test.cpp
@@ -0,0 +1,366 @@
1// ID3D12Resource::WriteToSubresource / ReadFromSubresource on the Vulkan-backed device, compared with the host PC
2// runtime. The same script runs on both devices: textures in CPU-visible custom heaps (write-back and
3// write-combine), a volume, an array, BC1 blocks, a buffer, an upload-heap buffer, a default-heap texture and a
4// multisampled one, with whole and boxed copies, pitches too small or zero, boxes outside or empty or cutting a
5// block, subresources past the last, and null pointers. Every HRESULT is recorded, and every read records a hash of
6// its whole destination buffer (so bytes written outside the region count too). The two records must be the same,
7// step by step. A step the host runtime faults on is reported and not compared. No shaders or game data. Skips (77)
8// without a Vulkan GPU; without a host D3D12 device only the layer's own record is printed. Set
9// LEONIDA_D3D49_VERBOSE=1 to print every step.
10#include "vk_test_device.h"
11#include "../shims/d3d12_com.h"
12
13#include <cstdint>
14#include <cstdio>
15#include <cstring>
16#include <string>
17#include <vector>
18
19#define EXPECT(condition) do { \
20 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
21} while (0)
22
23namespace {
24
25template<class T>
26struct Ref {
27 T* p = nullptr;
28 ~Ref() { reset(); }
29 void reset() {
30 if (p) p->Release();
31 p = nullptr;
32 }
33 T* operator->() const { return p; }
34};
35
36constexpr std::uint64_t kFaulted = 0xFA017EDull; // the call raised an exception
37constexpr std::uint64_t kMissing = 0x5C1F1Dull; // the resource couldn't be created on this device
38constexpr std::size_t kBytes = 4096;
39
40struct Resources {
41 ID3D12Resource* tex = nullptr; // 8x8 RGBA8, 2 mips, custom heap write-back L0
42 ID3D12Resource* vol = nullptr; // 4x4x4 RGBA8 volume, same heap
43 ID3D12Resource* arr = nullptr; // 4x4 RGBA8, 2 layers
44 ID3D12Resource* bc1 = nullptr; // 8x8 BC1
45 ID3D12Resource* wc = nullptr; // 4x4 RGBA8, custom heap write-combine L0
46 ID3D12Resource* buffer = nullptr; // 4096-byte buffer, custom heap write-back L0
47 ID3D12Resource* upload = nullptr; // 4096-byte buffer, upload heap
48 ID3D12Resource* gpu = nullptr; // 4x4 RGBA8, default heap
49 ID3D12Resource* msaa = nullptr; // 4x4 RGBA8 render target, 4 samples, default heap
50 std::uint8_t src[kBytes];
51 std::uint8_t dst[kBytes];
52};
53
54using Call = HRESULT (*)(Resources&);
55
56struct Step {
57 const char* name;
58 ID3D12Resource* Resources::*resource;
59 Call call;
60 bool read; // also record a hash of r.dst
61};
62
63HRESULT guarded(Call call, Resources* r) {
64 __try {
65 return call(*r);
66 } __except (EXCEPTION_EXECUTE_HANDLER) {
67 return HRESULT(kFaulted);
68 }
69}
70
71D3D12_BOX box(UINT left, UINT top, UINT front, UINT right, UINT bottom, UINT back) {
72 return D3D12_BOX{left, top, front, right, bottom, back};
73}
74
75HRESULT write(ID3D12Resource* t, UINT sub, const D3D12_BOX* b, Resources& r, UINT row, UINT depth) {
76 return t->WriteToSubresource(sub, b, r.src, row, depth);
77}
78HRESULT read(ID3D12Resource* t, UINT sub, const D3D12_BOX* b, Resources& r, UINT row, UINT depth) {
79 std::memset(r.dst, 0xcd, kBytes);
80 return t->ReadFromSubresource(r.dst, row, depth, sub, b);
81}
82
83#define W(res, sub, B, row, depth) [](Resources& r) -> HRESULT { const D3D12_BOX b = B; return write(r.res, sub, &b, r, row, depth); }
84#define WN(res, sub, row, depth) [](Resources& r) -> HRESULT { return write(r.res, sub, nullptr, r, row, depth); }
85#define R(res, sub, B, row, depth) [](Resources& r) -> HRESULT { const D3D12_BOX b = B; return read(r.res, sub, &b, r, row, depth); }
86#define RN(res, sub, row, depth) [](Resources& r) -> HRESULT { return read(r.res, sub, nullptr, r, row, depth); }
87
88const Step kSteps[] = {
89 // Before any Map: D3D12 asks for the subresource to be mapped (with a null pointer) first.
90 {"tex: write before Map", &Resources::tex, WN(tex, 0, 32, 0), false},
91 {"tex: read before Map", &Resources::tex, RN(tex, 0, 32, 0), true},
92 {"buffer: write before Map", &Resources::buffer, WN(buffer, 0, 64, 0), false},
93 // Map(sub, nullptr) on every texture subresource the script uses comes next (in run()).
94 {"tex: write mip 0 whole", &Resources::tex, WN(tex, 0, 32, 0), false},
95 {"tex: write mip 1 whole", &Resources::tex, WN(tex, 1, 16, 0), false},
96 {"tex: write subresource 2 (past the last)", &Resources::tex, WN(tex, 2, 32, 0), false},
97 {"tex: write subresource 0xffffffff", &Resources::tex, WN(tex, 0xffffffffu, 32, 0), false},
98 {"tex: write a 5x4 box at a 100-byte pitch", &Resources::tex, W(tex, 0, box(2, 1, 0, 7, 5, 1), 100, 0), false},
99 {"tex: write a box past the right edge", &Resources::tex, W(tex, 0, box(0, 0, 0, 9, 1, 1), 100, 0), false},
100 {"tex: write a box past the bottom edge", &Resources::tex, W(tex, 0, box(0, 0, 0, 1, 9, 1), 100, 0), false},
101 {"tex: write a box with back 2", &Resources::tex, W(tex, 0, box(0, 0, 0, 1, 1, 2), 100, 0), false},
102 {"tex: write a box with front 1, back 2", &Resources::tex, W(tex, 0, box(0, 0, 1, 1, 1, 2), 100, 0), false},
103 {"tex: write an empty box (left == right)", &Resources::tex, W(tex, 0, box(2, 2, 0, 2, 3, 1), 100, 0), false},
104 {"tex: write an empty box (top == bottom)", &Resources::tex, W(tex, 0, box(2, 2, 0, 3, 2, 1), 100, 0), false},
105 {"tex: write an empty box (front == back)", &Resources::tex, W(tex, 0, box(2, 2, 0, 3, 3, 0), 100, 0), false},
106 {"tex: write an inverted box", &Resources::tex, W(tex, 0, box(5, 0, 0, 3, 1, 1), 100, 0), false},
107 {"tex: write an inverted box starting past the right edge", &Resources::tex,
108 W(tex, 0, box(9, 0, 0, 3, 1, 1), 100, 0), false},
109 {"tex: write an empty box at the right edge", &Resources::tex, W(tex, 0, box(8, 0, 0, 8, 1, 1), 100, 0), false},
110 {"tex: write an empty box past the right edge", &Resources::tex, W(tex, 0, box(9, 0, 0, 9, 1, 1), 100, 0), false},
111 {"tex: write an empty box past the bottom edge", &Resources::tex, W(tex, 0, box(0, 9, 0, 1, 9, 1), 100, 0), false},
112 {"tex: write an empty box in subresource 2", &Resources::tex, W(tex, 2, box(0, 0, 0, 0, 1, 1), 100, 0), false},
113 {"tex: read mip 0 after the empty and inverted boxes", &Resources::tex, RN(tex, 0, 32, 0), true},
114 {"tex: write a box of mip 1 past its edge", &Resources::tex, W(tex, 1, box(0, 0, 0, 5, 1, 1), 100, 0), false},
115 {"tex: write null data", &Resources::tex, [](Resources& r) -> HRESULT {
116 return r.tex->WriteToSubresource(0, nullptr, nullptr, 32, 0);
117 }, false},
118 {"tex: write rows 16 apart (32-byte rows)", &Resources::tex, WN(tex, 0, 16, 0), false},
119 {"tex: write rows 31 apart", &Resources::tex, WN(tex, 0, 31, 0), false},
120 {"tex: write rows 0 apart", &Resources::tex, WN(tex, 0, 0, 0), false},
121 {"tex: write one row, pitch 0", &Resources::tex, W(tex, 0, box(0, 3, 0, 8, 4, 1), 0, 0), false},
122 {"tex: write one row, pitch 4", &Resources::tex, W(tex, 0, box(0, 3, 0, 8, 4, 1), 4, 0), false},
123 {"tex: write one texel, pitch 0", &Resources::tex, W(tex, 0, box(7, 7, 0, 8, 8, 1), 0, 0), false},
124 {"tex: write mip 0, depth pitch 1", &Resources::tex, WN(tex, 0, 32, 1), false},
125 {"tex: write mip 0 at a 48-byte pitch", &Resources::tex, WN(tex, 0, 48, 0), false},
126 {"tex: read null data", &Resources::tex, [](Resources& r) -> HRESULT {
127 return r.tex->ReadFromSubresource(nullptr, 32, 0, 0, nullptr);
128 }, false},
129 {"tex: read subresource 2", &Resources::tex, RN(tex, 2, 32, 0), true},
130 {"tex: read a box past the right edge", &Resources::tex, R(tex, 0, box(0, 0, 0, 9, 1, 1), 64, 0), true},
131 {"tex: read an empty box", &Resources::tex, R(tex, 0, box(2, 2, 0, 2, 3, 1), 64, 0), true},
132 {"tex: read rows 16 apart [overlap]", &Resources::tex, RN(tex, 0, 16, 0), true},
133 {"tex: read rows 0 apart [overlap]", &Resources::tex, RN(tex, 0, 0, 0), true},
134 {"tex: read mip 0 whole at a 40-byte pitch", &Resources::tex, RN(tex, 0, 40, 0), true},
135 {"tex: read mip 1 whole", &Resources::tex, RN(tex, 1, 16, 0), true},
136 {"tex: read a 2x3 box of mip 1", &Resources::tex, R(tex, 1, box(1, 1, 0, 3, 4, 1), 8, 0), true},
137 {"tex: read one row, pitch 0", &Resources::tex, R(tex, 0, box(0, 5, 0, 8, 6, 1), 0, 0), true},
138
139 {"vol: write whole, rows 16 and slices 64 apart", &Resources::vol, WN(vol, 0, 16, 64), false},
140 {"vol: write a 3x4x3 box, rows 12 and slices 64 apart", &Resources::vol,
141 W(vol, 0, box(1, 0, 1, 4, 4, 4), 12, 64), false},
142 {"vol: write slices 32 apart (64-byte slices)", &Resources::vol, WN(vol, 0, 16, 32), false},
143 {"vol: write slices 0 apart", &Resources::vol, WN(vol, 0, 16, 0), false},
144 {"vol: write one slice, depth pitch 0", &Resources::vol, W(vol, 0, box(0, 0, 2, 4, 4, 3), 16, 0), false},
145 {"vol: write a box with back 5", &Resources::vol, W(vol, 0, box(0, 0, 0, 4, 4, 5), 16, 64), false},
146 {"vol: read whole, rows 20 and slices 96 apart", &Resources::vol, RN(vol, 0, 20, 96), true},
147 {"vol: read slices 0 apart [overlap]", &Resources::vol, RN(vol, 0, 16, 0), true},
148
149 {"arr: write layer 1", &Resources::arr, WN(arr, 1, 16, 0), false},
150 {"arr: write subresource 2 (past the last)", &Resources::arr, WN(arr, 2, 16, 0), false},
151 {"arr: write layer 0 with back 2", &Resources::arr, W(arr, 0, box(0, 0, 0, 4, 4, 2), 16, 64), false},
152 {"arr: read layer 1", &Resources::arr, RN(arr, 1, 16, 0), true},
153 {"arr: read layer 0", &Resources::arr, RN(arr, 0, 16, 0), true},
154
155 {"bc1: write whole (2x2 blocks, rows 16 apart)", &Resources::bc1, WN(bc1, 0, 16, 0), false},
156 {"bc1: write the bottom-right block", &Resources::bc1, W(bc1, 0, box(4, 4, 0, 8, 8, 1), 8, 0), false},
157 {"bc1: write a box starting inside a block", &Resources::bc1, W(bc1, 0, box(2, 0, 0, 8, 4, 1), 16, 0), false},
158 {"bc1: write a box ending inside a block", &Resources::bc1, W(bc1, 0, box(0, 0, 0, 6, 4, 1), 16, 0), false},
159 {"bc1: write a box ending inside a block row", &Resources::bc1, W(bc1, 0, box(0, 0, 0, 4, 2, 1), 16, 0), false},
160 {"bc1: write an empty box inside a block", &Resources::bc1, W(bc1, 0, box(2, 0, 0, 2, 4, 1), 16, 0), false},
161 {"bc1: write an inverted box cutting blocks", &Resources::bc1, W(bc1, 0, box(6, 0, 0, 2, 4, 1), 16, 0), false},
162 {"bc1: read whole after the empty boxes", &Resources::bc1, RN(bc1, 0, 32, 0), true},
163 {"bc1: write rows 8 apart (16-byte block rows)", &Resources::bc1, WN(bc1, 0, 8, 0), false},
164 {"bc1: write a block row, pitch 0", &Resources::bc1, W(bc1, 0, box(0, 4, 0, 8, 8, 1), 0, 0), false},
165 {"bc1: read whole, rows 32 apart", &Resources::bc1, RN(bc1, 0, 32, 0), true},
166
167 {"wc: write whole", &Resources::wc, WN(wc, 0, 16, 0), false},
168 {"wc: read whole", &Resources::wc, RN(wc, 0, 16, 0), true},
169
170 {"buffer: write", &Resources::buffer, WN(buffer, 0, 64, 0), false},
171 {"buffer: write a 16-byte box", &Resources::buffer, W(buffer, 0, box(0, 0, 0, 16, 1, 1), 16, 0), false},
172 {"buffer: read", &Resources::buffer, RN(buffer, 0, 64, 0), true},
173 {"upload: write", &Resources::upload, WN(upload, 0, 64, 0), false},
174 {"upload: read", &Resources::upload, RN(upload, 0, 64, 0), true},
175
176 {"gpu: write (default heap)", &Resources::gpu, WN(gpu, 0, 16, 0), false},
177 {"gpu: read (default heap)", &Resources::gpu, RN(gpu, 0, 16, 0), true},
178 {"msaa: write (4 samples)", &Resources::msaa, WN(msaa, 0, 16, 0), false},
179 {"msaa: read (4 samples)", &Resources::msaa, RN(msaa, 0, 16, 0), true},
180};
181constexpr std::size_t kBeforeMap = 3; // the first steps run before Map
182
183#undef W
184#undef WN
185#undef R
186#undef RN
187
188std::uint64_t fnv(const std::uint8_t* p, std::size_t n) {
189 std::uint64_t h = 1469598103934665603ull;
190 for (std::size_t i = 0; i < n; ++i) h = (h ^ p[i]) * 1099511628211ull;
191 return h;
192}
193
194D3D12_RESOURCE_DESC texture(UINT width, UINT height, UINT16 depth, UINT16 mips, DXGI_FORMAT format,
195 D3D12_RESOURCE_DIMENSION dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D) {
196 D3D12_RESOURCE_DESC d{};
197 d.Dimension = dimension;
198 d.Width = width;
199 d.Height = height;
200 d.DepthOrArraySize = depth;
201 d.MipLevels = mips;
202 d.Format = format;
203 d.SampleDesc.Count = 1;
204 return d;
205}
206
207D3D12_RESOURCE_DESC buffer(UINT64 bytes) {
208 D3D12_RESOURCE_DESC d{};
209 d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
210 d.Width = bytes;
211 d.Height = 1;
212 d.DepthOrArraySize = 1;
213 d.MipLevels = 1;
214 d.SampleDesc.Count = 1;
215 d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
216 return d;
217}
218
219struct Record {
220 std::vector<std::string> names;
221 std::vector<std::uint64_t> values;
222 void add(const std::string& name, std::uint64_t value) {
223 names.push_back(name);
224 values.push_back(value);
225 }
226};
227
228// Creates the resources on `device`, runs the script and records it. A resource the device refuses is recorded
229// as missing, and its steps too.
230bool run(ID3D12Device* device, bool bc, Record& out) {
231 const D3D12_HEAP_PROPERTIES write_back{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
232 D3D12_MEMORY_POOL_L0};
233 const D3D12_HEAP_PROPERTIES write_combine{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
234 D3D12_MEMORY_POOL_L0};
235 const D3D12_HEAP_PROPERTIES upload{D3D12_HEAP_TYPE_UPLOAD};
236 const D3D12_HEAP_PROPERTIES gpu{D3D12_HEAP_TYPE_DEFAULT};
237 static Resources r; // too big for the stack frame __try lives next to
238 std::memset(&r, 0, sizeof(r));
239 for (std::size_t i = 0; i < kBytes; ++i) r.src[i] = std::uint8_t(i * 7 + (i >> 8) * 13 + 1);
240 const auto create = [&](const char* what, const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC& desc,
241 D3D12_RESOURCE_STATES state, ID3D12Resource*& to) {
242 const HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
243 IID_PPV_ARGS(&to));
244 out.add(std::string("create ") + what, std::uint64_t(std::uint32_t(hr)));
245 if (FAILED(hr)) to = nullptr;
246 };
247 create("tex", write_back, texture(8, 8, 1, 2, DXGI_FORMAT_R8G8B8A8_UNORM), D3D12_RESOURCE_STATE_COMMON, r.tex);
248 create("vol", write_back, texture(4, 4, 4, 1, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_DIMENSION_TEXTURE3D),
249 D3D12_RESOURCE_STATE_COMMON, r.vol);
250 create("arr", write_back, texture(4, 4, 2, 1, DXGI_FORMAT_R8G8B8A8_UNORM), D3D12_RESOURCE_STATE_COMMON, r.arr);
251 if (bc) create("bc1", write_back, texture(8, 8, 1, 1, DXGI_FORMAT_BC1_UNORM), D3D12_RESOURCE_STATE_COMMON, r.bc1);
252 create("wc", write_combine, texture(4, 4, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM), D3D12_RESOURCE_STATE_COMMON, r.wc);
253 create("buffer", write_back, buffer(kBytes), D3D12_RESOURCE_STATE_COMMON, r.buffer);
254 create("upload", upload, buffer(kBytes), D3D12_RESOURCE_STATE_GENERIC_READ, r.upload);
255 create("gpu", gpu, texture(4, 4, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM), D3D12_RESOURCE_STATE_COMMON, r.gpu);
256 auto ms = texture(4, 4, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM);
257 ms.SampleDesc.Count = 4;
258 ms.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
259 create("msaa", gpu, ms, D3D12_RESOURCE_STATE_RENDER_TARGET, r.msaa);
260
261 const auto step = [&](const Step& s) {
262 if (!(r.*s.resource)) {
263 out.add(s.name, kMissing);
264 if (s.read) out.add(std::string(s.name) + " (bytes)", kMissing);
265 return;
266 }
267 const HRESULT hr = guarded(s.call, &r);
268 out.add(s.name, std::uint64_t(std::uint32_t(hr)));
269 if (s.read) out.add(std::string(s.name) + " (bytes)", hr == HRESULT(kFaulted) ? kFaulted : fnv(r.dst, kBytes));
270 };
271 for (std::size_t i = 0; i < kBeforeMap; ++i) step(kSteps[i]);
272 // Map with a null pointer, as D3D12 asks before a CPU copy: every texture subresource in a CPU-visible heap.
273 const struct { ID3D12Resource* res; UINT subs; } maps[] = {{r.tex, 2}, {r.vol, 1}, {r.arr, 2}, {r.bc1, 1},
274 {r.wc, 1}, {r.buffer, 1}, {r.upload, 1}};
275 for (const auto& m : maps)
276 for (UINT s = 0; m.res && s < m.subs; ++s) out.add("Map", std::uint64_t(std::uint32_t(m.res->Map(s, nullptr, nullptr))));
277 for (std::size_t i = kBeforeMap; i < sizeof(kSteps) / sizeof(kSteps[0]); ++i) step(kSteps[i]);
278 for (const auto& m : maps)
279 for (UINT s = 0; m.res && s < m.subs; ++s) m.res->Unmap(s, nullptr);
280 for (ID3D12Resource* res : {r.tex, r.vol, r.arr, r.bc1, r.wc, r.buffer, r.upload, r.gpu, r.msaa})
281 if (res) res->Release();
282 return true;
283}
284
285} // namespace
286
287int main() {
288 vktest::Device d;
289 const auto device_status = d.initialize();
290 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
291 if (device_status != vktest::DeviceStatus::ready) return 1;
292 const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0;
293
294 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
295 const auto create_host = d3d12 ? reinterpret_cast<PFN_D3D12_CREATE_DEVICE>(
296 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12CreateDevice")))
297 : nullptr;
298 Ref<ID3D12Device> host;
299 Record theirs;
300 if (create_host && SUCCEEDED(create_host(nullptr, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p))))
301 EXPECT(run(host.p, d.bc, theirs));
302
303 // Once per copy path: on the host with VK_EXT_host_image_copy where the GPU has it, and through a staging submit
304 // (a second D3D12 device on the same Vulkan device, told the extension is off).
305 for (const bool host_copy : {true, false}) {
306 const char* path = host_copy ? "host image copy" : "staging copy";
307 if (host_copy && !d.host_image_copy) {
308 std::printf("CPU copies (%s): no VK_EXT_host_image_copy, skipped\n", path);
309 continue;
310 }
311 rt::d3d12::VulkanDeviceInfo info{};
312 info.get_instance_proc = d.instance_proc;
313 info.instance = d.instance;
314 info.physical = d.physical;
315 info.device = d.device;
316 info.queue = d.queue;
317 info.queue_family = d.family;
318 info.texture_compression_bc = d.bc;
319 info.host_image_copy = host_copy;
320 Ref<ID3D12Device> device;
321 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
322 Record ours;
323 EXPECT(run(device.p, d.bc, ours));
324 if (!host.p) {
325 std::printf("CPU copies (%s): no host D3D12 device to compare with; %zu steps recorded, not compared\n",
326 path, ours.values.size());
327 continue;
328 }
329 EXPECT(theirs.names == ours.names);
330 int mismatches = 0, skipped = 0;
331 const auto show = [&](std::size_t i, const char* note) {
332 std::printf("CPU copies (%s) %s: ours 0x%llx host 0x%llx%s\n", path, ours.names[i].c_str(),
333 static_cast<unsigned long long>(ours.values[i]),
334 static_cast<unsigned long long>(theirs.values[i]), note);
335 };
336 for (std::size_t i = 0; i < ours.values.size(); ++i) {
337 if (theirs.values[i] == kFaulted) { // null data: the host faults
338 show(i, " (the host faults; not compared)");
339 ++skipped;
340 continue;
341 }
342 // A default-heap texture: the host refuses CPU copies there, the layer makes them and logs it
343 // (docs/d3d12_vulkan.md), on purpose.
344 if (ours.names[i].find("(default heap)") != std::string::npos) {
345 show(i, " (the layer copies on purpose; not compared)");
346 ++skipped;
347 continue;
348 }
349 // A read whose rows or slices overlap in the destination: which bytes win is the order the driver
350 // copies texels in (tiled on an RTX 3060, not row by row), so only its HRESULT is compared.
351 if (ours.names[i].find("[overlap] (bytes)") != std::string::npos) {
352 if (verbose) show(i, " (the driver's copy order; not compared)");
353 ++skipped;
354 continue;
355 }
356 const bool same = ours.values[i] == theirs.values[i];
357 if (verbose || !same) show(i, same ? "" : " MISMATCH");
358 mismatches += !same;
359 }
360 std::printf("CPU copies (%s): %zu steps compared with the host (%d more not compared), %d mismatches\n", path,
361 ours.values.size() - skipped, skipped, mismatches);
362 EXPECT(mismatches == 0);
363 }
364 std::printf("d3d12_subresource_copy_test: OK\n");
365 return 0;
366}
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index 6b7a399bf..ad98eca7b 100644
--- a/runtime/test/d3d12_vulkan_device_test.cpp
+++ b/runtime/test/d3d12_vulkan_device_test.cpp
@@ -10,6 +10,7 @@
10// under VK_LAYER_KHRONOS_validation; any validation error fails the test. 10// under VK_LAYER_KHRONOS_validation; any validation error fails the test.
11#include "vk_test_device.h" 11#include "vk_test_device.h"
12#include "../shims/d3d12_com.h" 12#include "../shims/d3d12_com.h"
13#include "../shims/d3d12_feature_compat.h"
13#include "../shims/d3d12_xs_device.h" 14#include "../shims/d3d12_xs_device.h"
14#include "d3d12_copy_compare.h" // D3D-46: copies compared with the host runtime 15#include "d3d12_copy_compare.h" // D3D-46: copies compared with the host runtime
15#include "d3d12_depth24_compare.h" // D24 clears compared with the host runtime 16#include "d3d12_depth24_compare.h" // D24 clears compared with the host runtime
@@ -252,15 +253,15 @@ int cpu_copies(ID3D12Device* device, bool bc, const char* path) {
252 EXPECT(bc1->WriteToSubresource(0, &cut, blocks, 16, 0) == E_INVALIDARG); 253 EXPECT(bc1->WriteToSubresource(0, &cut, blocks, 16, 0) == E_INVALIDARG);
253 } 254 }
254 255
255 // Calls D3D12 rejects. 256 // Calls D3D12 rejects, and two it doesn't: an empty box copies nothing, and pitches aren't checked (the host's
257 // answers, d3d12_subresource_copy_test).
256 const D3D12_BOX outside{0, 0, 0, 9, 1, 1}, empty{2, 2, 0, 2, 3, 1}; 258 const D3D12_BOX outside{0, 0, 0, 9, 1, 1}, empty{2, 2, 0, 2, 3, 1};
257 EXPECT(tex->WriteToSubresource(0, &outside, src.data(), 100, 0) == E_INVALIDARG); 259 EXPECT(tex->WriteToSubresource(0, &outside, src.data(), 100, 0) == E_INVALIDARG);
258 EXPECT(tex->WriteToSubresource(0, &empty, src.data(), 100, 0) == E_INVALIDARG); 260 EXPECT(tex->WriteToSubresource(0, &empty, src.data(), 100, 0) == S_OK);
259 EXPECT(tex->WriteToSubresource(2, nullptr, src.data(), 100, 0) == E_INVALIDARG); // 2 mips, 1 layer 261 EXPECT(tex->WriteToSubresource(2, nullptr, src.data(), 100, 0) == E_INVALIDARG); // 2 mips, 1 layer
260 EXPECT(tex->WriteToSubresource(0, nullptr, nullptr, 32, 0) == E_INVALIDARG); 262 EXPECT(tex->WriteToSubresource(0, nullptr, nullptr, 32, 0) == E_INVALIDARG);
261 EXPECT(tex->ReadFromSubresource(nullptr, 32, 0, 0, nullptr) == E_INVALIDARG); 263 EXPECT(tex->ReadFromSubresource(nullptr, 32, 0, 0, nullptr) == E_INVALIDARG);
262 EXPECT(tex->WriteToSubresource(0, nullptr, src.data(), 16, 0) == E_INVALIDARG); // 32-byte rows 16 apart 264 EXPECT(vol->WriteToSubresource(0, nullptr, src.data(), 16, 32) == S_OK); // 64-byte slices 32 apart
263 EXPECT(vol->WriteToSubresource(0, nullptr, src.data(), 16, 32) == E_INVALIDARG); // 64-byte slices 32 apart
264 EXPECT(buffer->WriteToSubresource(0, nullptr, src.data(), 16, 0) == E_INVALIDARG); 265 EXPECT(buffer->WriteToSubresource(0, nullptr, src.data(), 16, 0) == E_INVALIDARG);
265 266
266 // A default-heap texture: D3D12 wants a CPU-visible heap, but the copy still works (and is logged). 267 // A default-heap texture: D3D12 wants a CPU-visible heap, but the copy still works (and is logged).
@@ -2034,11 +2035,24 @@ int new_format_round_trips(ID3D12Device* device, const rt::d3d12::VulkanDeviceIn
2034 continue; 2035 continue;
2035 } 2036 }
2036 if (host.p) { 2037 if (host.p) {
2037 Ref<ID3D12Resource> native; 2038 // A host runtime older than the format has nothing to match: A4B4G4R4_UNORM is not in Windows 10's D3D12,
2038 if (FAILED(host->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, 2039 // which reports no 2D texture support for it and refuses it. Compare only where the host itself says it
2039 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, 2040 // has the format, so a host that reports it and still refuses the texture fails as before.
2040 IID_PPV_ARGS(&native.p)))) 2041 D3D12_FEATURE_DATA_FORMAT_SUPPORT host_support{format};
2041 fail(format, "the host refuses a texture the layer creates"); 2042 const bool host_has_format =
2043 SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &host_support,
2044 sizeof(host_support))) &&
2045 (host_support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D);
2046 if (!host_has_format) {
2047 std::printf("new format %d: the host runtime has no such 2D texture (e.g. Windows 10), "
2048 "host comparison skipped\n", int(format));
2049 } else {
2050 Ref<ID3D12Resource> native;
2051 if (FAILED(host->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc,
2052 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
2053 IID_PPV_ARGS(&native.p))))
2054 fail(format, "the host refuses a texture the layer creates");
2055 }
2042 } 2056 }
2043 D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed{}; 2057 D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed{};
2044 UINT rows = 0; 2058 UINT rows = 0;
@@ -2241,8 +2255,8 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2241 D3D12_FEATURE_DATA_CROSS_NODE cross_node{}; 2255 D3D12_FEATURE_DATA_CROSS_NODE cross_node{};
2242 D3D12_FEATURE_DATA_DISPLAYABLE displayable{}; 2256 D3D12_FEATURE_DATA_DISPLAYABLE displayable{};
2243 D3D12_FEATURE_DATA_PREDICATION predication{}; 2257 D3D12_FEATURE_DATA_PREDICATION predication{};
2244 D3D12_FEATURE_DATA_APPLICATION_SPECIFIC_DRIVER_STATE driver_state{}; 2258 rt::d3d12::compat::FeatureSupportFlag driver_state{};
2245 D3D12_FEATURE_DATA_BYTECODE_BYPASS_HASH_SUPPORTED bypass_hash{}; 2259 rt::d3d12::compat::FeatureSupportFlag bypass_hash{};
2246 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT prot_support{}; 2260 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT prot_support{};
2247 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPE_COUNT prot_count{}; 2261 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPE_COUNT prot_count{};
2248 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPES prot_types{}; 2262 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPES prot_types{};
@@ -2254,9 +2268,12 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2254 query_ours(std::pair{"CROSS_NODE", D3D12_FEATURE_CROSS_NODE}, cross_node); 2268 query_ours(std::pair{"CROSS_NODE", D3D12_FEATURE_CROSS_NODE}, cross_node);
2255 query_ours(std::pair{"DISPLAYABLE", D3D12_FEATURE_DISPLAYABLE}, displayable); 2269 query_ours(std::pair{"DISPLAYABLE", D3D12_FEATURE_DISPLAYABLE}, displayable);
2256 query_ours(std::pair{"PREDICATION", D3D12_FEATURE_PREDICATION}, predication); 2270 query_ours(std::pair{"PREDICATION", D3D12_FEATURE_PREDICATION}, predication);
2257 query_ours(std::pair{"APPLICATION_SPECIFIC_DRIVER_STATE", D3D12_FEATURE_APPLICATION_SPECIFIC_DRIVER_STATE}, 2271 query_ours(std::pair{"APPLICATION_SPECIFIC_DRIVER_STATE",
2272 rt::d3d12::compat::kFeatureApplicationSpecificDriverState},
2258 driver_state); 2273 driver_state);
2259 query_ours(std::pair{"BYTECODE_BYPASS_HASH_SUPPORTED", D3D12_FEATURE_BYTECODE_BYPASS_HASH_SUPPORTED}, bypass_hash); 2274 query_ours(std::pair{"BYTECODE_BYPASS_HASH_SUPPORTED",
2275 rt::d3d12::compat::kFeatureBytecodeBypassHashSupported},
2276 bypass_hash);
2260 query_ours_input(std::pair{"PROTECTED_RESOURCE_SESSION_SUPPORT", D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT}, 2277 query_ours_input(std::pair{"PROTECTED_RESOURCE_SESSION_SUPPORT", D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT},
2261 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT{0, {}}, prot_support); 2278 D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT{0, {}}, prot_support);
2262 query_ours_input( 2279 query_ours_input(
@@ -2648,11 +2665,13 @@ int compare_feature_options(ID3D12Device* ours, const rt::d3d12::VulkanDeviceInf
2648 [&](const char* n, const auto& a, const auto& b) { 2665 [&](const char* n, const auto& a, const auto& b) {
2649 check_bool(n, "Supported", a.Supported, b.Supported); 2666 check_bool(n, "Supported", a.Supported, b.Supported);
2650 }); 2667 });
2651 compare_host("APPLICATION_SPECIFIC_DRIVER_STATE", D3D12_FEATURE_APPLICATION_SPECIFIC_DRIVER_STATE, driver_state, 2668 compare_host("APPLICATION_SPECIFIC_DRIVER_STATE", rt::d3d12::compat::kFeatureApplicationSpecificDriverState,
2669 driver_state,
2652 [&](const char* n, const auto& a, const auto& b) { 2670 [&](const char* n, const auto& a, const auto& b) {
2653 check_bool(n, "Supported", a.Supported, b.Supported); 2671 check_bool(n, "Supported", a.Supported, b.Supported);
2654 }); 2672 });
2655 compare_host("BYTECODE_BYPASS_HASH_SUPPORTED", D3D12_FEATURE_BYTECODE_BYPASS_HASH_SUPPORTED, bypass_hash, 2673 compare_host("BYTECODE_BYPASS_HASH_SUPPORTED", rt::d3d12::compat::kFeatureBytecodeBypassHashSupported,
2674 bypass_hash,
2656 [&](const char* n, const auto& a, const auto& b) { 2675 [&](const char* n, const auto& a, const auto& b) {
2657 check_bool(n, "Supported", a.Supported, b.Supported); 2676 check_bool(n, "Supported", a.Supported, b.Supported);
2658 }); 2677 });
@@ -2781,6 +2800,56 @@ HRESULT command_queue(ID3D12Device* device, D3D12_COMMAND_QUEUE_DESC desc) {
2781 return released(device->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), &out), &out); 2800 return released(device->CreateCommandQueue(&desc, __uuidof(ID3D12CommandQueue), &out), &out);
2782} 2801}
2783 2802
2803HRESULT query_heap(ID3D12Device* device, D3D12_QUERY_HEAP_TYPE type, UINT count, UINT node_mask = 0,
2804 bool output = true) {
2805 const D3D12_QUERY_HEAP_DESC desc{type, count, node_mask};
2806 void* out = nullptr;
2807 return released(device->CreateQueryHeap(&desc, __uuidof(ID3D12QueryHeap), output ? &out : nullptr), &out);
2808}
2809
2810// A root signature blob from the host's own serializer (version 1.0): empty, or one root CBV at b0, or one table of
2811// unbounded SRVs from t0. Empty when d3d12.dll has no serializer, and both devices then get the same refusal.
2812std::vector<std::uint8_t> root_signature_blob(int parameters) {
2813 using Serialize = HRESULT(WINAPI*)(const D3D12_ROOT_SIGNATURE_DESC*, D3D_ROOT_SIGNATURE_VERSION, ID3DBlob**,
2814 ID3DBlob**);
2815 static const auto serialize = reinterpret_cast<Serialize>(reinterpret_cast<void*>(GetProcAddress(
2816 LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32), "D3D12SerializeRootSignature")));
2817 D3D12_ROOT_PARAMETER parameter{};
2818 parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
2819 const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, UINT_MAX, 0, 0,
2820 D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND};
2821 if (parameters == 1) {
2822 parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
2823 } else if (parameters == 2) {
2824 parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
2825 parameter.DescriptorTable = {1, &range};
2826 }
2827 const D3D12_ROOT_SIGNATURE_DESC desc{parameters ? 1u : 0u, parameters ? &parameter : nullptr, 0, nullptr,
2828 D3D12_ROOT_SIGNATURE_FLAG_NONE};
2829 ID3DBlob* blob = nullptr;
2830 ID3DBlob* error = nullptr;
2831 std::vector<std::uint8_t> bytes;
2832 if (serialize && SUCCEEDED(serialize(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &error)) && blob) {
2833 const auto* first = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
2834 bytes.assign(first, first + blob->GetBufferSize());
2835 }
2836 if (blob) blob->Release();
2837 if (error) error->Release();
2838 return bytes;
2839}
2840
2841// CreateRootSignature with `blob`, passed as `size` bytes (the blob's own size when 0; the vector is padded with
2842// zeros when `size` is larger).
2843HRESULT root_signature(ID3D12Device* device, std::vector<std::uint8_t> blob, SIZE_T size = 0, UINT node_mask = 0,
2844 bool output = true, REFIID riid = __uuidof(ID3D12RootSignature)) {
2845 if (!size) size = blob.size();
2846 if (blob.size() < size) blob.resize(size);
2847 void* out = nullptr;
2848 return released(device->CreateRootSignature(node_mask, blob.empty() ? nullptr : blob.data(), size, riid,
2849 output ? &out : nullptr),
2850 &out);
2851}
2852
2784// CreateCommandSignature without a root signature. Each argument is only its type; a CONSTANT one sets one value. 2853// CreateCommandSignature without a root signature. Each argument is only its type; a CONSTANT one sets one value.
2785HRESULT command_signature(ID3D12Device* device, UINT stride, std::initializer_list<D3D12_INDIRECT_ARGUMENT_TYPE> types, 2854HRESULT command_signature(ID3D12Device* device, UINT stride, std::initializer_list<D3D12_INDIRECT_ARGUMENT_TYPE> types,
2786 UINT node_mask = 0) { 2855 UINT node_mask = 0) {
@@ -2796,6 +2865,14 @@ HRESULT command_signature(ID3D12Device* device, UINT stride, std::initializer_li
2796 return released(device->CreateCommandSignature(&desc, nullptr, __uuidof(ID3D12CommandSignature), &out), &out); 2865 return released(device->CreateCommandSignature(&desc, nullptr, __uuidof(ID3D12CommandSignature), &out), &out);
2797} 2866}
2798 2867
2868// CheckFeatureSupport(FORMAT_SUPPORT) for `value`: the HRESULT, or Support1 when it succeeds (Support2 holds what the
2869// GPU can do, such as TILED, which the layer doesn't offer, so it isn't compared).
2870HRESULT format_support1(ID3D12Device* device, UINT value) {
2871 D3D12_FEATURE_DATA_FORMAT_SUPPORT support{static_cast<DXGI_FORMAT>(value)};
2872 const HRESULT hr = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support));
2873 return SUCCEEDED(hr) ? static_cast<HRESULT>(support.Support1) : hr;
2874}
2875
2799HRESULT fence(ID3D12Device* device, D3D12_FENCE_FLAGS flags, REFIID riid = __uuidof(ID3D12Fence)) { 2876HRESULT fence(ID3D12Device* device, D3D12_FENCE_FLAGS flags, REFIID riid = __uuidof(ID3D12Fence)) {
2800 void* out = nullptr; 2877 void* out = nullptr;
2801 return released(device->CreateFence(0, flags, riid, &out), &out); 2878 return released(device->CreateFence(0, flags, riid, &out), &out);
@@ -2817,6 +2894,49 @@ HRESULT heap_create(ID3D12Device* device, D3D12_HEAP_DESC desc) {
2817 return released(device->CreateHeap(&desc, __uuidof(ID3D12Heap), &out), &out); 2894 return released(device->CreateHeap(&desc, __uuidof(ID3D12Heap), &out), &out);
2818} 2895}
2819 2896
2897// CreatePlacedResource in a fresh heap of `heap` made on the same device. A heap the device refuses makes the case
2898// itself wrong, so it answers E_UNEXPECTED on either side.
2899struct PlacedArgs {
2900 D3D12_HEAP_DESC heap = heap_desc_of(0, {D3D12_HEAP_TYPE_DEFAULT}, D3D12_HEAP_FLAG_NONE, 1024 * 1024);
2901 UINT64 offset = 0;
2902 D3D12_RESOURCE_STATES state = D3D12_RESOURCE_STATE_COMMON;
2903 const D3D12_CLEAR_VALUE* clear = nullptr;
2904 bool output = true;
2905 const IID* riid = &__uuidof(ID3D12Resource);
2906};
2907
2908HRESULT placed(ID3D12Device* device, const D3D12_RESOURCE_DESC* desc, const PlacedArgs& args = {}) {
2909 ID3D12Heap* heap = nullptr;
2910 if (FAILED(device->CreateHeap(&args.heap, IID_PPV_ARGS(&heap)))) return E_UNEXPECTED;
2911 void* out = nullptr;
2912 const HRESULT hr = device->CreatePlacedResource(heap, args.offset, desc, args.state, args.clear, *args.riid,
2913 args.output ? &out : nullptr);
2914 released(hr, &out);
2915 heap->Release();
2916 return hr;
2917}
2918
2919HRESULT placed(ID3D12Device* device, D3D12_RESOURCE_DESC desc, const PlacedArgs& args = {}) {
2920 return placed(device, &desc, args);
2921}
2922
2923HRESULT reserved(ID3D12Device* device, const D3D12_RESOURCE_DESC* desc,
2924 D3D12_RESOURCE_STATES state = D3D12_RESOURCE_STATE_COMMON, const D3D12_CLEAR_VALUE* clear = nullptr,
2925 bool output = true, REFIID riid = __uuidof(ID3D12Resource)) {
2926 void* out = nullptr;
2927 return released(device->CreateReservedResource(desc, state, clear, riid, output ? &out : nullptr), &out);
2928}
2929
2930HRESULT reserved(ID3D12Device* device, D3D12_RESOURCE_DESC desc,
2931 D3D12_RESOURCE_STATES state = D3D12_RESOURCE_STATE_COMMON, const D3D12_CLEAR_VALUE* clear = nullptr) {
2932 return reserved(device, &desc, state, clear);
2933}
2934
2935D3D12_RESOURCE_DESC tiled(D3D12_RESOURCE_DESC desc) {
2936 desc.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
2937 return desc;
2938}
2939
2820// Map on a fresh committed resource; `range` is the read range, or null. 2940// Map on a fresh committed resource; `range` is the read range, or null.
2821HRESULT map(ID3D12Device* device, D3D12_HEAP_PROPERTIES heap, D3D12_RESOURCE_DESC desc, D3D12_RESOURCE_STATES state, 2941HRESULT map(ID3D12Device* device, D3D12_HEAP_PROPERTIES heap, D3D12_RESOURCE_DESC desc, D3D12_RESOURCE_STATES state,
2822 UINT subresource, const D3D12_RANGE* range, bool want_pointer = true) { 2942 UINT subresource, const D3D12_RANGE* range, bool want_pointer = true) {
@@ -2843,6 +2963,15 @@ HRESULT call_guarded(InvalidCase call, ID3D12Device* device) {
2843 } 2963 }
2844} 2964}
2845 2965
2966// The host accepts a UAV buffer in RAYTRACING_ACCELERATION_STRUCTURE state only where OPTIONS5 reports ray tracing
2967// (an RTX does, an integrated Radeon without DXR refuses it: @aguedou-34 on #2462). The layer accepts it where it
2968// has acceleration structures: the standalone device (XDXR or KHR), not the device main builds without them.
2969bool host_ray_tracing(ID3D12Device* host) {
2970 D3D12_FEATURE_DATA_D3D12_OPTIONS5 o5{};
2971 return SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &o5, sizeof(o5))) &&
2972 o5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED;
2973}
2974
2846int compare_invalid_arguments(ID3D12Device* ours) { 2975int compare_invalid_arguments(ID3D12Device* ours) {
2847 Ref<ID3D12Device> host; 2976 Ref<ID3D12Device> host;
2848 if (!create_host_device(host)) return -1; 2977 if (!create_host_device(host)) return -1;
@@ -2880,6 +3009,104 @@ int compare_invalid_arguments(ID3D12Device* ours) {
2880 D3D12_RESOURCE_STATE_COMMON, nullptr, 3009 D3D12_RESOURCE_STATE_COMMON, nullptr,
2881 __uuidof(ID3D12Fence), &out), &out); 3010 __uuidof(ID3D12Fence), &out), &out);
2882 }}, 3011 }},
3012 // CreateCommittedResource: the initial state. A buffer takes any bits but the acceleration-structure state
3013 // without UAV access; a texture takes GENERIC_READ, one write state alone (RENDER_TARGET, UNORDERED_ACCESS,
3014 // DEPTH_WRITE with their flag), or a mix of read states (DEPTH_READ with ALLOW_DEPTH_STENCIL, the shader
3015 // resource states without DENY_SHADER_RESOURCE), and never a buffer-only or undefined bit.
3016 {"committed: plain texture in RENDER_TARGET state", [](ID3D12Device* d) {
3017 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_RENDER_TARGET);
3018 }},
3019 {"committed: render target in RENDER_TARGET state", [](ID3D12Device* d) {
3020 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET),
3021 D3D12_RESOURCE_STATE_RENDER_TARGET);
3022 }},
3023 {"committed: plain texture in UNORDERED_ACCESS state", [](ID3D12Device* d) {
3024 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
3025 }},
3026 {"committed: UAV texture in UNORDERED_ACCESS state", [](ID3D12Device* d) {
3027 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
3028 D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
3029 }},
3030 {"committed: plain texture in DEPTH_WRITE state", [](ID3D12Device* d) {
3031 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_DEPTH_WRITE);
3032 }},
3033 {"committed: plain texture in DEPTH_READ state", [](ID3D12Device* d) {
3034 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_DEPTH_READ);
3035 }},
3036 {"committed: depth texture in DEPTH_READ | PIXEL_SHADER_RESOURCE state", [](ID3D12Device* d) {
3037 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
3038 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
3039 D3D12_RESOURCE_STATE_DEPTH_READ | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
3040 }},
3041 {"committed: depth texture in DEPTH_WRITE | DEPTH_READ state", [](ID3D12Device* d) {
3042 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
3043 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
3044 D3D12_RESOURCE_STATE_DEPTH_WRITE | D3D12_RESOURCE_STATE_DEPTH_READ);
3045 }},
3046 {"committed: depth texture without shader resource in PIXEL_SHADER_RESOURCE state", [](ID3D12Device* d) {
3047 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
3048 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT,
3049 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
3050 D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE),
3051 D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
3052 }},
3053 {"committed: depth texture without shader resource in GENERIC_READ state", [](ID3D12Device* d) {
3054 return committed(d, {D3D12_HEAP_TYPE_DEFAULT},
3055 texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT,
3056 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
3057 D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE),
3058 D3D12_RESOURCE_STATE_GENERIC_READ);
3059 }},
3060 {"committed: texture in GENERIC_READ state", [](ID3D12Device* d) {
3061 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_GENERIC_READ);
3062 }},
3063 {"committed: texture in GENERIC_READ | COPY_DEST state", [](ID3D12Device* d) {
3064 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(),
3065 D3D12_RESOURCE_STATE_GENERIC_READ | D3D12_RESOURCE_STATE_COPY_DEST);
3066 }},
3067 {"committed: texture in COPY_DEST | PIXEL_SHADER_RESOURCE state", [](ID3D12Device* d) {
3068 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(),
3069 D3D12_RESOURCE_STATE_COPY_DEST | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
3070 }},
3071 {"committed: texture in the three shader-read and copy-source states", [](ID3D12Device* d) {
3072 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(),
3073 D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_COPY_SOURCE);
3074 }},
3075 {"committed: render target in RENDER_TARGET | PIXEL_SHADER_RESOURCE state", [](ID3D12Device* d) {
3076 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET),
3077 D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
3078 }},
3079 {"committed: texture in VERTEX_AND_CONSTANT_BUFFER state", [](ID3D12Device* d) {
3080 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
3081 }},
3082 {"committed: texture in INDEX_BUFFER | PIXEL_SHADER_RESOURCE state", [](ID3D12Device* d) {
3083 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(),
3084 D3D12_RESOURCE_STATE_INDEX_BUFFER | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
3085 }},
3086 {"committed: texture in state 0x80000000", [](ID3D12Device* d) {
3087 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATES(0x80000000u));
3088 }},
3089 {"committed: texture in RESOLVE_DEST state", [](ID3D12Device* d) {
3090 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, rgba8(), D3D12_RESOURCE_STATE_RESOLVE_DEST);
3091 }},
3092 {"committed: buffer in state 0x80000000", [](ID3D12Device* d) {
3093 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256), D3D12_RESOURCE_STATES(0x80000000u));
3094 }},
3095 {"committed: buffer in RENDER_TARGET | UNORDERED_ACCESS state", [](ID3D12Device* d) {
3096 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256),
3097 D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
3098 }},
3099 {"committed: buffer in RAYTRACING_ACCELERATION_STRUCTURE state", [](ID3D12Device* d) {
3100 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(256),
3101 D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE);
3102 }},
3103 // This device has no acceleration structures and refuses it, as a host without ray tracing does.
3104 {"committed: UAV buffer in RAYTRACING_ACCELERATION_STRUCTURE state", [](ID3D12Device* d) {
3105 auto desc = buffer_desc(256);
3106 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
3107 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc,
3108 D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE);
3109 }, [](ID3D12Device* host) { return !host_ray_tracing(host); }},
2883 // CreateCommittedResource: buffer descriptions. 3110 // CreateCommittedResource: buffer descriptions.
2884 {"committed: buffer width 0", [](ID3D12Device* d) { 3111 {"committed: buffer width 0", [](ID3D12Device* d) {
2885 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(0)); 3112 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, buffer_desc(0));
@@ -3512,6 +3739,94 @@ int compare_invalid_arguments(ID3D12Device* ours) {
3512 }}, 3739 }},
3513 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }}, 3740 {"command queue: compute", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COMPUTE}); }},
3514 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }}, 3741 {"command queue: copy", [](ID3D12Device* d) { return command_queue(d, {D3D12_COMMAND_LIST_TYPE_COPY}); }},
3742 // CreateQueryHeap: the description is checked first (types past PIPELINE_STATISTICS1 are refused), then a
3743 // null output is E_UNEXPECTED. Known types this layer has no path for (stream output, video decode, mesh
3744 // statistics) are E_NOTIMPL here and not compared.
3745 {"query heap: occlusion", [](ID3D12Device* d) { return query_heap(d, D3D12_QUERY_HEAP_TYPE_OCCLUSION, 4); }},
3746 {"query heap: timestamps", [](ID3D12Device* d) { return query_heap(d, D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 4); }},
3747 {"query heap: no queries", [](ID3D12Device* d) { return query_heap(d, D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0); }},
3748 {"query heap: type 8", [](ID3D12Device* d) { return query_heap(d, D3D12_QUERY_HEAP_TYPE(8), 1); }},
3749 {"query heap: type 99", [](ID3D12Device* d) { return query_heap(d, D3D12_QUERY_HEAP_TYPE(99), 1); }},
3750 {"query heap: type -1", [](ID3D12Device* d) { return query_heap(d, D3D12_QUERY_HEAP_TYPE(-1), 1); }},
3751 {"query heap: node mask 1", [](ID3D12Device* d) {
3752 return query_heap(d, D3D12_QUERY_HEAP_TYPE_OCCLUSION, 1, 1);
3753 }},
3754 {"query heap: node mask 2", [](ID3D12Device* d) {
3755 return query_heap(d, D3D12_QUERY_HEAP_TYPE_OCCLUSION, 1, 2);
3756 }},
3757 {"query heap: null output", [](ID3D12Device* d) {
3758 return query_heap(d, D3D12_QUERY_HEAP_TYPE_OCCLUSION, 4, 0, false);
3759 }},
3760 {"query heap: null output, no queries", [](ID3D12Device* d) {
3761 return query_heap(d, D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0, false);
3762 }},
3763 {"query heap: null output, type 99", [](ID3D12Device* d) {
3764 return query_heap(d, D3D12_QUERY_HEAP_TYPE(99), 1, 0, false);
3765 }},
3766 {"query heap: null output, node mask 2", [](ID3D12Device* d) {
3767 return query_heap(d, D3D12_QUERY_HEAP_TYPE_OCCLUSION, 1, 2, false);
3768 }},
3769 {"query heap: wrong interface", [](ID3D12Device* d) {
3770 const D3D12_QUERY_HEAP_DESC desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 1, 0};
3771 void* out = nullptr;
3772 return released(d->CreateQueryHeap(&desc, __uuidof(ID3D12Fence), &out), &out);
3773 }},
3774 // CreateRootSignature: a null output is S_FALSE whatever the blob; otherwise node 0 only, and the blob's
3775 // DXBC size must be the size passed.
3776 {"root signature: empty", [](ID3D12Device* d) { return root_signature(d, root_signature_blob(0)); }},
3777 {"root signature: root CBV", [](ID3D12Device* d) { return root_signature(d, root_signature_blob(1)); }},
3778 {"root signature: unbounded SRV table", [](ID3D12Device* d) {
3779 return root_signature(d, root_signature_blob(2));
3780 }},
3781 {"root signature: size 0", [](ID3D12Device* d) {
3782 void* out = nullptr;
3783 const auto blob = root_signature_blob(0);
3784 return released(d->CreateRootSignature(0, blob.data(), 0, __uuidof(ID3D12RootSignature), &out), &out);
3785 }},
3786 {"root signature: one byte short", [](ID3D12Device* d) {
3787 const auto blob = root_signature_blob(0);
3788 return root_signature(d, blob, blob.size() - 1);
3789 }},
3790 {"root signature: 4 bytes over", [](ID3D12Device* d) {
3791 const auto blob = root_signature_blob(1);
3792 return root_signature(d, blob, blob.size() + 4);
3793 }},
3794 {"root signature: 16 bytes over", [](ID3D12Device* d) {
3795 const auto blob = root_signature_blob(0);
3796 return root_signature(d, blob, blob.size() + 16);
3797 }},
3798 {"root signature: 64 zero bytes", [](ID3D12Device* d) {
3799 return root_signature(d, std::vector<std::uint8_t>(64, 0));
3800 }},
3801 {"root signature: null blob", [](ID3D12Device* d) {
3802 void* out = nullptr;
3803 return released(d->CreateRootSignature(0, nullptr, 64, __uuidof(ID3D12RootSignature), &out), &out);
3804 }},
3805 {"root signature: node mask 1", [](ID3D12Device* d) {
3806 return root_signature(d, root_signature_blob(0), 0, 1);
3807 }},
3808 {"root signature: node mask 2", [](ID3D12Device* d) {
3809 return root_signature(d, root_signature_blob(0), 0, 2);
3810 }},
3811 {"root signature: node mask 0x80000000", [](ID3D12Device* d) {
3812 return root_signature(d, root_signature_blob(0), 0, 0x80000000u);
3813 }},
3814 {"root signature: wrong interface", [](ID3D12Device* d) {
3815 return root_signature(d, root_signature_blob(0), 0, 0, true, __uuidof(ID3D12Fence));
3816 }},
3817 {"root signature: null output", [](ID3D12Device* d) {
3818 return root_signature(d, root_signature_blob(1), 0, 0, false);
3819 }},
3820 {"root signature: null output, 64 zero bytes", [](ID3D12Device* d) {
3821 return root_signature(d, std::vector<std::uint8_t>(64, 0), 0, 0, false);
3822 }},
3823 {"root signature: null output, node mask 2", [](ID3D12Device* d) {
3824 return root_signature(d, root_signature_blob(0), 0, 2, false);
3825 }},
3826 {"root signature: null output, 16 bytes over", [](ID3D12Device* d) {
3827 const auto blob = root_signature_blob(0);
3828 return root_signature(d, blob, blob.size() + 16, 0, false);
3829 }},
3515 {"command queue: high priority", [](ID3D12Device* d) { 3830 {"command queue: high priority", [](ID3D12Device* d) {
3516 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_HIGH}); 3831 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_QUEUE_PRIORITY_HIGH});
3517 }}, 3832 }},
@@ -3594,6 +3909,19 @@ int compare_invalid_arguments(ID3D12Device* ours) {
3594 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 1}); 3909 return command_queue(d, {D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 1});
3595 }}, 3910 }},
3596 // CreateFence. 3911 // CreateFence.
3912 // FORMAT_SUPPORT for values the runtime's format table has no entry for (E_FAIL), and for UNKNOWN (a buffer
3913 // format: Support1 is compared, not Support2).
3914 {"format support: UNKNOWN", [](ID3D12Device* d) { return format_support1(d, DXGI_FORMAT_UNKNOWN); }},
3915 {"format support: 116, the first unused value", [](ID3D12Device* d) { return format_support1(d, 0x74u); }},
3916 {"format support: 129", [](ID3D12Device* d) { return format_support1(d, 0x81u); }},
3917 {"format support: 130, P208", [](ID3D12Device* d) { return format_support1(d, 0x82u); }},
3918 {"format support: 131, V208", [](ID3D12Device* d) { return format_support1(d, 0x83u); }},
3919 {"format support: 132, V408", [](ID3D12Device* d) { return format_support1(d, 0x84u); }},
3920 {"format support: 133", [](ID3D12Device* d) { return format_support1(d, 0x85u); }},
3921 {"format support: 188", [](ID3D12Device* d) { return format_support1(d, 0xbcu); }},
3922 {"format support: 192, past A4B4G4R4", [](ID3D12Device* d) { return format_support1(d, 0xc0u); }},
3923 {"format support: 1000", [](ID3D12Device* d) { return format_support1(d, 0x3e8u); }},
3924 {"format support: -1", [](ID3D12Device* d) { return format_support1(d, 0xffffffffu); }},
3597 {"fence: null output", [](ID3D12Device* d) { 3925 {"fence: null output", [](ID3D12Device* d) {
3598 return d->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), nullptr); 3926 return d->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), nullptr);
3599 }}, 3927 }},
@@ -3782,6 +4110,446 @@ int compare_heap_neighbours(ID3D12Device* ours) {
3782 return mismatches; 4110 return mismatches;
3783} 4111}
3784 4112
4113// CreatePlacedResource and CreateReservedResource answer their arguments as the host runtime does: the placement
4114// (offset, alignment, room in the heap), the heap's type and DENY flags against the resource, the description and
4115// initial state rules CreateCommittedResource shares, and the output and interface. Run on a device with the GPU
4116// address arena (without it every heap is E_NOTIMPL). Returns the number of mismatches, or -1 without a host.
4117int compare_placed_reserved(ID3D12Device* ours) {
4118 Ref<ID3D12Device> host;
4119 if (!create_host_device(host)) return -1;
4120 struct Case {
4121 const char* name;
4122 InvalidCase call;
4123 bool (*comparable)(ID3D12Device*) = nullptr;
4124 };
4125 static const Case cases[] = {
4126 // The standalone device has acceleration structures (XDXR, or KHR with LEONIDA_RT_AS=khr) and accepts a UAV
4127 // buffer in their state, as a host with ray tracing does.
4128 {"committed (standalone): UAV buffer in RAYTRACING_ACCELERATION_STRUCTURE state", [](ID3D12Device* d) {
4129 auto desc = buffer_desc(256);
4130 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
4131 return committed(d, {D3D12_HEAP_TYPE_DEFAULT}, desc,
4132 D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE);
4133 }, host_ray_tracing},
4134 {"placed: UAV buffer in RAYTRACING_ACCELERATION_STRUCTURE state", [](ID3D12Device* d) {
4135 PlacedArgs a;
4136 a.state = D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE;
4137 auto desc = buffer_desc(64 * 1024);
4138 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
4139 return placed(d, desc, a);
4140 }, host_ray_tracing},
4141 // CreatePlacedResource: arguments.
4142 {"placed: buffer at 0", [](ID3D12Device* d) { return placed(d, buffer_desc(64 * 1024)); }},
4143 {"placed: null description", [](ID3D12Device* d) { return placed(d, nullptr); }},
4144 {"placed: null heap", [](ID3D12Device* d) {
4145 const D3D12_RESOURCE_DESC desc = buffer_desc(64 * 1024);
4146 void* out = nullptr;
4147 return released(d->CreatePlacedResource(nullptr, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
4148 __uuidof(ID3D12Resource), &out), &out);
4149 }},
4150 {"placed: null output (capability check)", [](ID3D12Device* d) {
4151 PlacedArgs a;
4152 a.output = false;
4153 return placed(d, buffer_desc(64 * 1024), a);
4154 }},
4155 {"placed: null output, offset 4096", [](ID3D12Device* d) {
4156 PlacedArgs a;
4157 a.output = false;
4158 a.offset = 4096;
4159 return placed(d, buffer_desc(64 * 1024), a);
4160 }},
4161 {"placed: null output, buffer height 2", [](ID3D12Device* d) {
4162 auto desc = buffer_desc(256);
4163 desc.Height = 2;
4164 PlacedArgs a;
4165 a.output = false;
4166 return placed(d, desc, a);
4167 }},
4168 {"placed: null output, texture past the heap's end", [](ID3D12Device* d) {
4169 PlacedArgs a;
4170 a.output = false;
4171 a.offset = 1024 * 1024 - 64 * 1024;
4172 return placed(d, texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), a);
4173 }},
4174 {"placed: wrong interface", [](ID3D12Device* d) {
4175 PlacedArgs a;
4176 a.riid = &__uuidof(ID3D12Fence);
4177 return placed(d, buffer_desc(64 * 1024), a);
4178 }},
4179 // CreatePlacedResource: where the resource goes.
4180 {"placed: buffer at 64 KiB", [](ID3D12Device* d) {
4181 PlacedArgs a;
4182 a.offset = 64 * 1024;
4183 return placed(d, buffer_desc(64 * 1024), a);
4184 }},
4185 {"placed: buffer at 4096", [](ID3D12Device* d) {
4186 PlacedArgs a;
4187 a.offset = 4096;
4188 return placed(d, buffer_desc(256), a);
4189 }},
4190 {"placed: buffer filling the heap", [](ID3D12Device* d) { return placed(d, buffer_desc(1024 * 1024)); }},
4191 {"placed: buffer one byte larger than the heap", [](ID3D12Device* d) {
4192 return placed(d, buffer_desc(1024 * 1024 + 1));
4193 }},
4194 {"placed: buffer past the heap's end", [](ID3D12Device* d) {
4195 PlacedArgs a;
4196 a.offset = 1024 * 1024 - 64 * 1024;
4197 return placed(d, buffer_desc(128 * 1024), a);
4198 }},
4199 {"placed: buffer at the heap's end", [](ID3D12Device* d) {
4200 PlacedArgs a;
4201 a.offset = 1024 * 1024;
4202 return placed(d, buffer_desc(256), a);
4203 }},
4204 {"placed: small texture at 4096 (4 KiB alignment)", [](ID3D12Device* d) {
4205 auto desc = texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
4206 desc.Alignment = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT;
4207 PlacedArgs a;
4208 a.offset = 4096;
4209 return placed(d, desc, a);
4210 }},
4211 {"placed: texture at 4096 (default alignment)", [](ID3D12Device* d) {
4212 PlacedArgs a;
4213 a.offset = 4096;
4214 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), a);
4215 }},
4216 {"placed: texture at 64 KiB", [](ID3D12Device* d) {
4217 PlacedArgs a;
4218 a.offset = 64 * 1024;
4219 return placed(d, texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), a);
4220 }},
4221 {"placed: texture larger than the heap", [](ID3D12Device* d) {
4222 return placed(d, texture_desc(1024, 1024, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
4223 }},
4224 {"placed: texture past the heap's end", [](ID3D12Device* d) {
4225 PlacedArgs a;
4226 a.offset = 1024 * 1024 - 64 * 1024;
4227 return placed(d, texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), a);
4228 }},
4229 {"placed: MSAA texture at 64 KiB (4 MiB alignment)", [](ID3D12Device* d) {
4230 auto desc = texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
4231 desc.SampleDesc.Count = 4;
4232 PlacedArgs a;
4233 a.heap = heap_desc_of(D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, {D3D12_HEAP_TYPE_DEFAULT},
4234 D3D12_HEAP_FLAG_NONE, 8 * 1024 * 1024);
4235 a.offset = 64 * 1024;
4236 return placed(d, desc, a);
4237 }},
4238 {"placed: MSAA texture in a 64 KiB-aligned heap", [](ID3D12Device* d) {
4239 auto desc = texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
4240 desc.SampleDesc.Count = 4;
4241 return placed(d, desc);
4242 }},
4243 // CreatePlacedResource: the heap's type and DENY flags against the resource.
4244 {"placed: buffer in an ALLOW_ONLY_NON_RT_DS_TEXTURES heap", [](ID3D12Device* d) {
4245 PlacedArgs a;
4246 a.heap.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
4247 return placed(d, buffer_desc(256), a);
4248 }},
4249 {"placed: texture in an ALLOW_ONLY_BUFFERS heap", [](ID3D12Device* d) {
4250 PlacedArgs a;
4251 a.heap.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
4252 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), a);
4253 }},
4254 {"placed: render target in an ALLOW_ONLY_NON_RT_DS_TEXTURES heap", [](ID3D12Device* d) {
4255 PlacedArgs a;
4256 a.heap.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES;
4257 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM,
4258 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), a);
4259 }},
4260 {"placed: plain texture in an ALLOW_ONLY_RT_DS_TEXTURES heap", [](ID3D12Device* d) {
4261 PlacedArgs a;
4262 a.heap.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;
4263 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), a);
4264 }},
4265 {"placed: render target in an ALLOW_ONLY_RT_DS_TEXTURES heap", [](ID3D12Device* d) {
4266 PlacedArgs a;
4267 a.heap.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;
4268 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM,
4269 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), a);
4270 }},
4271 {"placed: texture in an upload heap", [](ID3D12Device* d) {
4272 PlacedArgs a;
4273 a.heap.Properties.Type = D3D12_HEAP_TYPE_UPLOAD;
4274 a.state = D3D12_RESOURCE_STATE_GENERIC_READ;
4275 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), a);
4276 }},
4277 // CreatePlacedResource: the description rules CreateCommittedResource has.
4278 {"placed: buffer width 0", [](ID3D12Device* d) { return placed(d, buffer_desc(0)); }},
4279 {"placed: buffer height 2", [](ID3D12Device* d) {
4280 auto desc = buffer_desc(256);
4281 desc.Height = 2;
4282 return placed(d, desc);
4283 }},
4284 {"placed: buffer with 2 mips", [](ID3D12Device* d) {
4285 auto desc = buffer_desc(256);
4286 desc.MipLevels = 2;
4287 return placed(d, desc);
4288 }},
4289 {"placed: buffer with a format", [](ID3D12Device* d) {
4290 auto desc = buffer_desc(256);
4291 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
4292 return placed(d, desc);
4293 }},
4294 {"placed: buffer with layout UNKNOWN", [](ID3D12Device* d) {
4295 auto desc = buffer_desc(256);
4296 desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
4297 return placed(d, desc);
4298 }},
4299 {"placed: buffer with 4 KiB alignment", [](ID3D12Device* d) {
4300 auto desc = buffer_desc(256);
4301 desc.Alignment = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT;
4302 return placed(d, desc);
4303 }},
4304 {"placed: buffer with ALLOW_DEPTH_STENCIL", [](ID3D12Device* d) {
4305 auto desc = buffer_desc(256);
4306 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
4307 return placed(d, desc);
4308 }},
4309 {"placed: texture width 0", [](ID3D12Device* d) {
4310 return placed(d, texture_desc(0, 16, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
4311 }},
4312 {"placed: texture with format UNKNOWN", [](ID3D12Device* d) {
4313 return placed(d, texture_desc(16, 16, DXGI_FORMAT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE));
4314 }},
4315 {"placed: texture with layout ROW_MAJOR", [](ID3D12Device* d) {
4316 auto desc = texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
4317 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
4318 return placed(d, desc);
4319 }},
4320 {"placed: depth texture with ALLOW_UNORDERED_ACCESS", [](ID3D12Device* d) {
4321 return placed(d, texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT,
4322 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
4323 D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS));
4324 }},
4325 // CreatePlacedResource: the initial state and the clear value.
4326 {"placed: upload buffer in GENERIC_READ", [](ID3D12Device* d) {
4327 PlacedArgs a;
4328 a.heap.Properties.Type = D3D12_HEAP_TYPE_UPLOAD;
4329 a.state = D3D12_RESOURCE_STATE_GENERIC_READ;
4330 return placed(d, buffer_desc(256), a);
4331 }},
4332 {"placed: upload buffer in COPY_DEST", [](ID3D12Device* d) {
4333 PlacedArgs a;
4334 a.heap.Properties.Type = D3D12_HEAP_TYPE_UPLOAD;
4335 a.state = D3D12_RESOURCE_STATE_COPY_DEST;
4336 return placed(d, buffer_desc(256), a);
4337 }},
4338 {"placed: upload buffer with ALLOW_UNORDERED_ACCESS", [](ID3D12Device* d) {
4339 auto desc = buffer_desc(256);
4340 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
4341 PlacedArgs a;
4342 a.heap.Properties.Type = D3D12_HEAP_TYPE_UPLOAD;
4343 a.state = D3D12_RESOURCE_STATE_GENERIC_READ;
4344 return placed(d, desc, a);
4345 }},
4346 {"placed: readback buffer in COPY_DEST", [](ID3D12Device* d) {
4347 PlacedArgs a;
4348 a.heap.Properties.Type = D3D12_HEAP_TYPE_READBACK;
4349 a.state = D3D12_RESOURCE_STATE_COPY_DEST;
4350 return placed(d, buffer_desc(256), a);
4351 }},
4352 {"placed: readback buffer in GENERIC_READ", [](ID3D12Device* d) {
4353 PlacedArgs a;
4354 a.heap.Properties.Type = D3D12_HEAP_TYPE_READBACK;
4355 a.state = D3D12_RESOURCE_STATE_GENERIC_READ;
4356 return placed(d, buffer_desc(256), a);
4357 }},
4358 {"placed: default buffer in state 0x80000000", [](ID3D12Device* d) {
4359 PlacedArgs a;
4360 a.state = D3D12_RESOURCE_STATES(0x80000000u);
4361 return placed(d, buffer_desc(256), a);
4362 }},
4363 {"placed: depth texture in DEPTH_WRITE", [](ID3D12Device* d) {
4364 PlacedArgs a;
4365 a.state = D3D12_RESOURCE_STATE_DEPTH_WRITE;
4366 return placed(d, texture_desc(16, 16, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
4367 a);
4368 }},
4369 {"placed: plain texture in UNORDERED_ACCESS", [](ID3D12Device* d) {
4370 PlacedArgs a;
4371 a.state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
4372 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), a);
4373 }},
4374 {"placed: render target in RENDER_TARGET", [](ID3D12Device* d) {
4375 PlacedArgs a;
4376 a.state = D3D12_RESOURCE_STATE_RENDER_TARGET;
4377 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM,
4378 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), a);
4379 }},
4380 {"placed: plain texture in RENDER_TARGET", [](ID3D12Device* d) {
4381 PlacedArgs a;
4382 a.state = D3D12_RESOURCE_STATE_RENDER_TARGET;
4383 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), a);
4384 }},
4385 {"placed: render target with a clear value", [](ID3D12Device* d) {
4386 static const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.f, 0.f, 0.f, 1.f}};
4387 PlacedArgs a;
4388 a.clear = &clear;
4389 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM,
4390 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), a);
4391 }},
4392 {"placed: plain texture with a clear value", [](ID3D12Device* d) {
4393 static const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.f, 0.f, 0.f, 1.f}};
4394 PlacedArgs a;
4395 a.clear = &clear;
4396 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), a);
4397 }},
4398 {"placed: buffer with a clear value", [](ID3D12Device* d) {
4399 static const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.f, 0.f, 0.f, 1.f}};
4400 PlacedArgs a;
4401 a.clear = &clear;
4402 return placed(d, buffer_desc(256), a);
4403 }},
4404 {"placed: render target, clear value of another format", [](ID3D12Device* d) {
4405 static const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R16G16B16A16_FLOAT, {0.f, 0.f, 0.f, 1.f}};
4406 PlacedArgs a;
4407 a.clear = &clear;
4408 return placed(d, texture_desc(16, 16, DXGI_FORMAT_R8G8B8A8_UNORM,
4409 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), a);
4410 }},
4411 // CreateReservedResource.
4412 {"reserved: buffer", [](ID3D12Device* d) { return reserved(d, buffer_desc(64 * 1024)); }},
4413 {"reserved: null description", [](ID3D12Device* d) { return reserved(d, nullptr); }},
4414 {"reserved: null output (capability check)", [](ID3D12Device* d) {
4415 const auto desc = buffer_desc(64 * 1024);
4416 return reserved(d, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, false);
4417 }},
4418 {"reserved: null output, buffer height 2", [](ID3D12Device* d) {
4419 auto desc = buffer_desc(64 * 1024);
4420 desc.Height = 2;
4421 return reserved(d, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, false);
4422 }},
4423 {"reserved: null output, plain texture in RENDER_TARGET", [](ID3D12Device* d) {
4424 const auto desc =
4425 tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
4426 return reserved(d, &desc, D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, false);
4427 }},
4428 {"reserved: wrong interface", [](ID3D12Device* d) {
4429 const auto desc = buffer_desc(64 * 1024);
4430 return reserved(d, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, true, __uuidof(ID3D12Fence));
4431 }},
4432 {"reserved: buffer with layout UNKNOWN", [](ID3D12Device* d) {
4433 auto desc = buffer_desc(64 * 1024);
4434 desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
4435 return reserved(d, desc);
4436 }},
4437 {"reserved: buffer width 0", [](ID3D12Device* d) { return reserved(d, buffer_desc(0)); }},
4438 {"reserved: buffer height 2", [](ID3D12Device* d) {
4439 auto desc = buffer_desc(64 * 1024);
4440 desc.Height = 2;
4441 return reserved(d, desc);
4442 }},
4443 {"reserved: buffer with a format", [](ID3D12Device* d) {
4444 auto desc = buffer_desc(64 * 1024);
4445 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
4446 return reserved(d, desc);
4447 }},
4448 {"reserved: buffer with 4 KiB alignment", [](ID3D12Device* d) {
4449 auto desc = buffer_desc(64 * 1024);
4450 desc.Alignment = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT;
4451 return reserved(d, desc);
4452 }},
4453 {"reserved: buffer in COPY_DEST", [](ID3D12Device* d) {
4454 return reserved(d, buffer_desc(64 * 1024), D3D12_RESOURCE_STATE_COPY_DEST);
4455 }},
4456 {"reserved: buffer in state 0x80000000", [](ID3D12Device* d) {
4457 return reserved(d, buffer_desc(64 * 1024), D3D12_RESOURCE_STATES(0x80000000u));
4458 }},
4459 {"reserved: texture", [](ID3D12Device* d) {
4460 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)));
4461 }},
4462 {"reserved: texture with layout UNKNOWN", [](ID3D12Device* d) {
4463 return reserved(d, texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
4464 }},
4465 {"reserved: texture with layout ROW_MAJOR", [](ID3D12Device* d) {
4466 auto desc = texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
4467 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
4468 return reserved(d, desc);
4469 }},
4470 {"reserved: texture with 64KB_STANDARD_SWIZZLE", [](ID3D12Device* d) {
4471 auto desc = texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
4472 desc.Layout = D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE;
4473 return reserved(d, desc);
4474 }},
4475 {"reserved: texture width 0", [](ID3D12Device* d) {
4476 return reserved(d, tiled(texture_desc(0, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)));
4477 }},
4478 {"reserved: full mip chain", [](ID3D12Device* d) {
4479 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE,
4480 0)));
4481 }},
4482 {"reserved: BC1 texture", [](ID3D12Device* d) {
4483 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE)));
4484 }},
4485 {"reserved: 1D texture", [](ID3D12Device* d) {
4486 auto desc = tiled(texture_desc(256, 1, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE));
4487 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D;
4488 return reserved(d, desc);
4489 }},
4490 {"reserved: D24S8 depth texture", [](ID3D12Device* d) {
4491 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_D24_UNORM_S8_UINT,
4492 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)));
4493 }},
4494 {"reserved: D32 depth texture", [](ID3D12Device* d) {
4495 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_D32_FLOAT,
4496 D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)));
4497 }},
4498 {"reserved: R32G32B32 texture", [](ID3D12Device* d) {
4499 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R32G32B32_FLOAT, D3D12_RESOURCE_FLAG_NONE)));
4500 }},
4501 {"reserved: texture with ALLOW_SIMULTANEOUS_ACCESS", [](ID3D12Device* d) {
4502 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM,
4503 D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS)));
4504 }},
4505 {"reserved: render target with a clear value", [](ID3D12Device* d) {
4506 static const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.f, 0.f, 0.f, 1.f}};
4507 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM,
4508 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)),
4509 D3D12_RESOURCE_STATE_COMMON, &clear);
4510 }},
4511 {"reserved: plain texture with a clear value", [](ID3D12Device* d) {
4512 static const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.f, 0.f, 0.f, 1.f}};
4513 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)),
4514 D3D12_RESOURCE_STATE_COMMON, &clear);
4515 }},
4516 {"reserved: plain texture in RENDER_TARGET", [](ID3D12Device* d) {
4517 return reserved(d, tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)),
4518 D3D12_RESOURCE_STATE_RENDER_TARGET);
4519 }},
4520 {"reserved: 3D texture", [](ID3D12Device* d) {
4521 auto desc = tiled(texture_desc(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 1, 16));
4522 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
4523 return reserved(d, desc);
4524 }},
4525 {"reserved: 4x MSAA render target", [](ID3D12Device* d) {
4526 auto desc = tiled(texture_desc(256, 256, DXGI_FORMAT_R8G8B8A8_UNORM,
4527 D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET));
4528 desc.SampleDesc.Count = 4;
4529 return reserved(d, desc);
4530 }},
4531 };
4532 const bool verbose = GetEnvironmentVariableA("LEONIDA_D3D49_VERBOSE", nullptr, 0) > 0;
4533 int mismatches = 0;
4534 for (const Case& c : cases) {
4535 if (verbose) {
4536 std::printf("invalid arguments %s:", c.name);
4537 std::fflush(stdout);
4538 }
4539 const HRESULT a = call_guarded(c.call, ours), b = call_guarded(c.call, host.p);
4540 if (verbose) std::printf(" ours 0x%08lx host 0x%08lx\n", a, b);
4541 if (a == b) continue;
4542 if (c.comparable && !c.comparable(host.p)) {
4543 std::printf("invalid arguments %s: not comparable on this host (ours 0x%08lx, host 0x%08lx)\n", c.name,
4544 a, b);
4545 continue;
4546 }
4547 ++mismatches;
4548 std::fprintf(stderr, "invalid arguments %s: ours 0x%08lx, host 0x%08lx\n", c.name, a, b);
4549 }
4550 return mismatches;
4551}
4552
3785// CheckFeatureSupport's error paths must match the host runtime's exactly: games and middleware branch on these 4553// CheckFeatureSupport's error paths must match the host runtime's exactly: games and middleware branch on these
3786// HRESULTs at startup, and a wrong success or a wrong error sends them down the wrong path. A null data pointer, a 4554// HRESULTs at startup, and a wrong success or a wrong error sends them down the wrong path. A null data pointer, a
3787// structure smaller than the feature requires, or a feature value no runtime defines must all return the same HRESULT 4555// structure smaller than the feature requires, or a feature value no runtime defines must all return the same HRESULT
@@ -3990,15 +4758,62 @@ int main() {
3990 EXPECT(format_support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET); 4758 EXPECT(format_support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET);
3991 EXPECT(format_support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE); 4759 EXPECT(format_support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE);
3992 4760
3993 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS invalid_sample_count{}; 4761 // RTX 5070 / 621.14 host answers, without requiring a host device for this regression.
3994 invalid_sample_count.Format = DXGI_FORMAT_R8G8B8A8_UNORM; 4762 for (const UINT samples : {0u, 33u, 64u, UINT_MAX}) {
3995 invalid_sample_count.SampleCount = D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT * 2; 4763 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS quality{DXGI_FORMAT_R8G8B8A8_UNORM, samples,
3996 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &invalid_sample_count, 4764 D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE, 99};
3997 sizeof(invalid_sample_count)) == E_INVALIDARG); 4765 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &quality,
3998 EXPECT(invalid_sample_count.NumQualityLevels == 0); 4766 sizeof(quality)) == E_FAIL);
3999 invalid_sample_count.SampleCount = 0; 4767 EXPECT(quality.NumQualityLevels == 0);
4000 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &invalid_sample_count, 4768 }
4001 sizeof(invalid_sample_count)) == E_INVALIDARG); 4769 for (UINT format = 0; format <= 192; ++format) {
4770 const bool known = format != UINT(DXGI_FORMAT_R1_UNORM) &&
4771 (format <= 115 || (format >= 189 && format <= 191));
4772 for (const UINT samples : {1u, 3u, 31u}) {
4773 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS quality{DXGI_FORMAT(format), samples,
4774 D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE, 99};
4775 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &quality,
4776 sizeof(quality)) == (known ? S_OK : E_FAIL));
4777 EXPECT(quality.NumQualityLevels == (known ? UINT(samples == 1) : 99u));
4778 }
4779 }
4780 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS invalid_format_levels{DXGI_FORMAT_FORCE_UINT, 1,
4781 D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE, 99};
4782 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &invalid_format_levels,
4783 sizeof(invalid_format_levels)) == E_FAIL);
4784 EXPECT(invalid_format_levels.NumQualityLevels == 99);
4785 // Native (RTX 5070 / 621.24): an unknown format keeps the output even with an invalid count.
4786 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS unknown_zero{DXGI_FORMAT(192), 0,
4787 D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE, 99};
4788 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &unknown_zero,
4789 sizeof(unknown_zero)) == E_FAIL);
4790 EXPECT(unknown_zero.NumQualityLevels == 99);
4791 for (const auto format : {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_R32G32B32_FLOAT}) {
4792 for (const UINT samples : {1u, 3u, 4u, 32u}) {
4793 for (const UINT flags : {0u, 1u}) {
4794 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS plain{format, samples,
4795 D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS(flags)};
4796 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &plain,
4797 sizeof(plain)) == S_OK);
4798 if (flags && format == DXGI_FORMAT_R32G32B32_FLOAT) EXPECT(plain.NumQualityLevels == 0);
4799 for (const UINT extra : {2u, 0xfeu}) {
4800 auto undefined_flags = plain;
4801 undefined_flags.Flags = D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS(flags | extra);
4802 undefined_flags.NumQualityLevels = 99;
4803 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &undefined_flags,
4804 sizeof(undefined_flags)) == S_OK);
4805 EXPECT(undefined_flags.NumQualityLevels == plain.NumQualityLevels);
4806 }
4807 }
4808 }
4809 }
4810 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS wrong_size[2]{{DXGI_FORMAT_R8G8B8A8_UNORM, 1,
4811 D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE, 99}};
4812 for (const UINT bytes : {UINT(sizeof(wrong_size[0]) - 1), UINT(sizeof(wrong_size))}) {
4813 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, wrong_size,
4814 bytes) == E_INVALIDARG);
4815 EXPECT(wrong_size[0].NumQualityLevels == 99);
4816 }
4002 4817
4003 D3D12_RESOURCE_DESC unsupported_quality = 4818 D3D12_RESOURCE_DESC unsupported_quality =
4004 texture_desc(size, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); 4819 texture_desc(size, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET);
@@ -4006,8 +4821,20 @@ int main() {
4006 unsupported_quality.SampleDesc.Quality = 1; 4821 unsupported_quality.SampleDesc.Quality = 1;
4007 EXPECT(device->GetResourceAllocationInfo(0, 1, &unsupported_quality).SizeInBytes == UINT64_MAX); 4822 EXPECT(device->GetResourceAllocationInfo(0, 1, &unsupported_quality).SizeInBytes == UINT64_MAX);
4008 4823
4009 D3D12_FEATURE_DATA_FORMAT_SUPPORT invalid_format{DXGI_FORMAT_UNKNOWN}; 4824 // UNKNOWN is a buffer format to the host runtime (S_OK, Support1 BUFFER; "format support: UNKNOWN" compares
4010 EXPECT(FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &invalid_format, sizeof(invalid_format)))); 4825 // it), and a value past its format table is E_FAIL.
4826 D3D12_FEATURE_DATA_FORMAT_SUPPORT unknown_format{DXGI_FORMAT_UNKNOWN};
4827 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &unknown_format, sizeof(unknown_format)) ==
4828 S_OK &&
4829 unknown_format.Support1 == D3D12_FORMAT_SUPPORT1_BUFFER);
4830 D3D12_FEATURE_DATA_FORMAT_SUPPORT invalid_format{static_cast<DXGI_FORMAT>(116)};
4831 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &invalid_format, sizeof(invalid_format)) ==
4832 E_FAIL);
4833 // The table's last entries before and after the gap are formats, whatever this GPU supports of them.
4834 for (const UINT edge : {115u, 189u, 191u}) { // B4G4R4A4_UNORM, SAMPLER_FEEDBACK_MIN_MIP_OPAQUE, A4B4G4R4_UNORM
4835 D3D12_FEATURE_DATA_FORMAT_SUPPORT known{static_cast<DXGI_FORMAT>(edge)};
4836 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &known, sizeof(known)) != E_FAIL);
4837 }
4011 4838
4012 // D3D-61: XR_BIAS is a display-only format with the R10G10B10A2 bit layout. The layer can create and 4839 // D3D-61: XR_BIAS is a display-only format with the R10G10B10A2 bit layout. The layer can create and
4013 // copy it, and its views can cast to the ordinary 10:10:10:2 format, but it does not claim display or 4840 // copy it, and its views can cast to the ordinary 10:10:10:2 format, but it does not claim display or
@@ -4220,6 +5047,11 @@ int main() {
4220 EXPECT(above.HighestShaderModel == D3D_SHADER_MODEL_6_0); // clamped to what the layer accepts 5047 EXPECT(above.HighestShaderModel == D3D_SHADER_MODEL_6_0); // clamped to what the layer accepts
4221 D3D12_FEATURE_DATA_SHADER_MODEL below{static_cast<D3D_SHADER_MODEL>(0)}; 5048 D3D12_FEATURE_DATA_SHADER_MODEL below{static_cast<D3D_SHADER_MODEL>(0)};
4222 EXPECT(FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &below, sizeof(below)))); 5049 EXPECT(FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &below, sizeof(below))));
5050 // Between 5.1 and 6.0 no runtime names a model: refused (the host's E_INVALIDARG), not echoed back.
5051 for (const UINT undefined : {0x52u, 0x5au, 0x5fu}) {
5052 D3D12_FEATURE_DATA_SHADER_MODEL gap{static_cast<D3D_SHADER_MODEL>(undefined)};
5053 EXPECT(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &gap, sizeof(gap)) == E_INVALIDARG);
5054 }
4223 5055
4224 D3D12_FEATURE_DATA_ROOT_SIGNATURE signature{D3D_ROOT_SIGNATURE_VERSION_1_1}; 5056 D3D12_FEATURE_DATA_ROOT_SIGNATURE signature{D3D_ROOT_SIGNATURE_VERSION_1_1};
4225 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &signature, sizeof(signature)))); 5057 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &signature, sizeof(signature))));
@@ -5238,8 +6070,9 @@ int main() {
5238 EXPECT(tiled->GetDesc().Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE); 6070 EXPECT(tiled->GetDesc().Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE);
5239 D3D12_HEAP_PROPERTIES reserved_heap{}; 6071 D3D12_HEAP_PROPERTIES reserved_heap{};
5240 EXPECT(tiled->GetHeapProperties(&reserved_heap, nullptr) == E_INVALIDARG); // no heap of its own 6072 EXPECT(tiled->GetHeapProperties(&reserved_heap, nullptr) == E_INVALIDARG); // no heap of its own
6073 // A null output is E_UNEXPECTED, as on the host runtime (compare_placed_reserved, "reserved:").
5241 EXPECT(device->CreateReservedResource(&tiled_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, 6074 EXPECT(device->CreateReservedResource(&tiled_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
5242 __uuidof(ID3D12Resource), nullptr) == S_FALSE); 6075 __uuidof(ID3D12Resource), nullptr) == E_UNEXPECTED);
5243 const auto refuses = [&](D3D12_RESOURCE_DESC desc) { 6076 const auto refuses = [&](D3D12_RESOURCE_DESC desc) {
5244 const HRESULT hr = device->CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, nullptr, 6077 const HRESULT hr = device->CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
5245 IID_PPV_ARGS(&refused.p)); 6078 IID_PPV_ARGS(&refused.p));
@@ -5411,7 +6244,8 @@ int main() {
5411 Ref<ID3D12QueryHeap> occlusion, timestamps, statistics, refused; 6244 Ref<ID3D12QueryHeap> occlusion, timestamps, statistics, refused;
5412 D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 4, 0}; 6245 D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 4, 0};
5413 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&occlusion.p)))); 6246 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&occlusion.p))));
5414 EXPECT(device->CreateQueryHeap(&query_desc, __uuidof(ID3D12QueryHeap), nullptr) == S_FALSE); 6247 // A null output is E_UNEXPECTED, as on the host runtime (compare_invalid_arguments, "query heap:").
6248 EXPECT(device->CreateQueryHeap(&query_desc, __uuidof(ID3D12QueryHeap), nullptr) == E_UNEXPECTED);
5415 { 6249 {
5416 Ref<ID3D12Device> parent; 6250 Ref<ID3D12Device> parent;
5417 EXPECT(SUCCEEDED(occlusion->GetDevice(IID_PPV_ARGS(&parent.p))) && parent.p == device.p); 6251 EXPECT(SUCCEEDED(occlusion->GetDevice(IID_PPV_ARGS(&parent.p))) && parent.p == device.p);
@@ -5482,6 +6316,33 @@ int main() {
5482 EXPECT(submit_and_wait()); 6316 EXPECT(submit_and_wait());
5483 EXPECT(u64(again_at) >= t1 && u64(again_at + 8) == t1); 6317 EXPECT(u64(again_at) >= t1 && u64(again_at + 8) == t1);
5484 6318
6319 // A timestamp written by one execution and resolved by the next, with nothing waited for in between, as
6320 // a game resolves last frame's timestamps. The resolve reads the new value (on MoltenVK only because the
6321 // queue orders the two; docs/d3d12_vulkan.md section 4.6).
6322 {
6323 constexpr UINT64 later_at = 2048;
6324 Ref<ID3D12CommandAllocator> writer_allocator;
6325 Ref<ID3D12GraphicsCommandList> writer;
6326 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
6327 IID_PPV_ARGS(&writer_allocator.p))));
6328 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, writer_allocator.p,
6329 nullptr, IID_PPV_ARGS(&writer.p))));
6330 writer->CopyBufferRegion(readback.p, 8192, upload.p, 0, 32768);
6331 writer->EndQuery(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 2);
6332 EXPECT(writer->Close() == S_OK);
6333 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)));
6334 list->ResolveQueryData(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0, 3, readback.p, later_at);
6335 EXPECT(list->Close() == S_OK);
6336 ID3D12CommandList* const writers[] = {writer.p};
6337 queue->ExecuteCommandLists(1, writers);
6338 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
6339 queue->ExecuteCommandLists(1, lists);
6340 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
6341 EXPECT(submit_and_wait());
6342 EXPECT(u64(later_at) == u64(again_at) && u64(later_at + 8) == t1);
6343 EXPECT(u64(later_at + 16) >= u64(again_at) && u64(later_at + 16) != 0xcdcdcdcdcdcdcdcdull);
6344 }
6345
5485 // Lists that break the rules. Close reports what it can see; the rest is refused at execution, and 6346 // Lists that break the rules. Close reports what it can see; the rest is refused at execution, and
5486 // nothing is submitted. 6347 // nothing is submitted.
5487 const auto refuse = [&](HRESULT close, leonida::ReplayResult result, auto&& record) { 6348 const auto refuse = [&](HRESULT close, leonida::ReplayResult result, auto&& record) {
@@ -5506,11 +6367,13 @@ int main() {
5506 [&] { list->ResolveQueryData(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0, 1, rt_resource.p, 0); })); 6367 [&] { list->ResolveQueryData(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0, 1, rt_resource.p, 0); }));
5507 EXPECT(refuse(S_OK, R::invalid_query, // past the end of the buffer 6368 EXPECT(refuse(S_OK, R::invalid_query, // past the end of the buffer
5508 [&] { list->ResolveQueryData(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, readback.p, 65528); })); 6369 [&] { list->ResolveQueryData(timestamps.p, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, readback.p, 65528); }));
5509 EXPECT(refuse(S_OK, R::unsupported, [&] { // valid D3D12, but Vulkan runs one occlusion query at a time 6370 EXPECT(refuse(S_OK, R::success, [&] { // overlapping occlusion kinds share physical segments (D3D-252)
5510 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); 6371 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0);
5511 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1); 6372 list->BeginQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1);
5512 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1); 6373 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1);
5513 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); 6374 list->EndQuery(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0);
6375 list->ResolveQueryData(occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0, 1, readback.p, 0);
6376 list->ResolveQueryData(occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 1, 1, readback.p, 8);
5514 })); 6377 }));
5515 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr))); 6378 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)));
5516 EXPECT(SUCCEEDED(list->Close())); 6379 EXPECT(SUCCEEDED(list->Close()));
@@ -5894,6 +6757,11 @@ int main() {
5894 if (heap_mismatches < 0) 6757 if (heap_mismatches < 0)
5895 std::printf("CreateHeap valid neighbours: no host D3D12 device to compare with, skipped\n"); 6758 std::printf("CreateHeap valid neighbours: no host D3D12 device to compare with, skipped\n");
5896 EXPECT(heap_mismatches <= 0); 6759 EXPECT(heap_mismatches <= 0);
6760 const int placed_mismatches = compare_placed_reserved(standalone.p);
6761 if (placed_mismatches < 0)
6762 std::printf("CreatePlacedResource/CreateReservedResource arguments: no host D3D12 device to compare "
6763 "with, skipped\n");
6764 EXPECT(placed_mismatches <= 0);
5897 } 6765 }
5898 6766
5899 auto tiled_2d = [&](UINT w, UINT h, DXGI_FORMAT fmt, UINT16 mips, D3D12_RESOURCE_FLAGS flags, 6767 auto tiled_2d = [&](UINT w, UINT h, DXGI_FORMAT fmt, UINT16 mips, D3D12_RESOURCE_FLAGS flags,
diff --git a/runtime/test/descriptor_table_test.cpp b/runtime/test/descriptor_table_test.cpp
index 26fb39083..7a24117e3 100644
--- a/runtime/test/descriptor_table_test.cpp
+++ b/runtime/test/descriptor_table_test.cpp
@@ -408,7 +408,49 @@ int test_erase_moves_no_other_entry() {
408 return 0; 408 return 0;
409} 409}
410 410
411int test_unresolvable_hash_collision() {
412 DescriptorTable table(32);
413 std::array<DescriptorKey, 9> keys{};
414 for (std::uint32_t i = 0; i < keys.size(); ++i) {
415 keys[i][0] = i;
416 // Invert the final FNV multiplication to make every complete hash zero.
417 std::uint32_t prefix = kFnvOffsetBasis;
418 for (int word = 0; word < 7; ++word) prefix = (prefix ^ keys[i][word]) * kFnvPrime;
419 keys[i][7] = prefix;
420 EXPECT(hash_descriptor_key(keys[i]) == 0);
421 }
422 for (std::uint32_t i = 0; i < 8; ++i) table.insert(keys[i], i + 1);
423 const auto before = table.build_gpu_buffer();
424 bool rejected = false;
425 try { table.insert(keys[8], 9); }
426 catch (const std::length_error&) { rejected = true; }
427 EXPECT(rejected && table.size() == 8 && table.capacity() == 32);
428 EXPECT(table.build_gpu_buffer() == before);
429 for (std::uint32_t i = 0; i < 8; ++i) EXPECT(table.lookup(keys[i]) == i + 1);
430 EXPECT(table.insert_or_update(keys[0].data(), 99) == DescriptorTable::InsertResult::replaced);
431 EXPECT(table.lookup(keys[0]) == 99);
432 EXPECT(table.erase(keys[0]));
433 EXPECT(table.insert(keys[8], 9) && table.lookup(keys[8]) == 9);
434 return 0;
435}
436
437int test_capacity_overflow() {
438 for (std::uint32_t requested : {0x80000001u, 0xffffffffu}) {
439 bool rejected = false;
440 try { DescriptorTable table(requested); }
441 catch (const std::length_error&) { rejected = true; }
442 EXPECT(rejected);
443 }
444 for (std::uint32_t requested : {0u, 1u, 16u, 17u, 31u, 32u}) {
445 DescriptorTable table(requested);
446 EXPECT(table.capacity() == (requested <= 16 ? 16 : 32));
447 }
448 return 0;
449}
450
411int main() { 451int main() {
452 EXPECT(test_unresolvable_hash_collision() == 0);
453 EXPECT(test_capacity_overflow() == 0);
412 EXPECT(test_fnv1a_hash_matches_contract() == 0); 454 EXPECT(test_fnv1a_hash_matches_contract() == 0);
413 EXPECT(test_ssharp_key_padding() == 0); 455 EXPECT(test_ssharp_key_padding() == 0);
414 EXPECT(test_basic_insertion_and_lookup() == 0); 456 EXPECT(test_basic_insertion_and_lookup() == 0);
diff --git a/runtime/test/dll_thread_calls_test.cpp b/runtime/test/dll_thread_calls_test.cpp
new file mode 100644
index 000000000..1cc6928ca
--- /dev/null
+++ b/runtime/test/dll_thread_calls_test.cpp
@@ -0,0 +1,80 @@
1// DisableThreadLibraryCalls from a mapped image's DllMain (shims/library_loader.cpp).
2//
3// The real function only accepts a module the Windows loader knows, so for a manually mapped image it returned FALSE
4// and a DllMain that returns its result made Loader::initialise() throw "DllMain returned FALSE". The shim answers
5// TRUE for a mapped module and for a module the shims own (a pseudo-handle), and leaves every other handle to the
6// real function.
7//
8// Maps dll_thread_calls.dll (test/fixtures/dll_thread_calls.cpp). xmem.cpp is linked only so the shims own a module
9// (xmem.dll) to hand out a pseudo-handle for. No game files.
10#include <windows.h>
11
12#include <cstdio>
13#include <filesystem>
14#include <stdexcept>
15#include <string>
16
17#include "pe_loader.h"
18#include "shims.h"
19
20namespace {
21
22int g_failures = 0;
23
24void check(bool ok, const std::string& what) {
25 std::printf("%s %s\n", ok ? "PASS" : "FAIL", what.c_str());
26 std::fflush(stdout);
27 if (!ok) ++g_failures;
28}
29
30} // namespace
31
32int main(int argc, char** argv) {
33 if (argc != 2) {
34 std::fprintf(stderr, "usage: dll_thread_calls_test <dll_thread_calls.dll>\n");
35 return 2;
36 }
37 const std::filesystem::path dll = argv[1];
38 try {
39 rt::Loader loader(dll.parent_path());
40 rt::Module& m = loader.load(dll);
41
42 bool shimmed = false;
43 for (const auto& r : m.imports)
44 if (r.name == "DisableThreadLibraryCalls") shimmed = r.binding == rt::Binding::Shim;
45 check(shimmed, "the DisableThreadLibraryCalls import is bound to the shim");
46
47 bool initialised = true;
48 try {
49 loader.initialise();
50 } catch (const std::exception& e) {
51 initialised = false;
52 std::printf(" initialise() threw: %s\n", e.what());
53 }
54 check(initialised, "initialise() succeeds when DllMain returns DisableThreadLibraryCalls(hinstance)");
55
56 const auto bogus =
57 reinterpret_cast<BOOL(__cdecl*)()>(m.exports.at("dll_thread_calls_bogus_handle"));
58 SetLastError(0);
59 check(bogus() == FALSE, "a handle that names no module still gets the real answer (FALSE)");
60
61 // A shim pseudo-handle is no module the Windows loader knows, so the real function would fail on it.
62 using GetModuleHandleAFn = HMODULE(WINAPI*)(LPCSTR);
63 using DisableFn = BOOL(WINAPI*)(HMODULE);
64 const auto get_module =
65 reinterpret_cast<GetModuleHandleAFn>(rt::shims::find("kernel32.dll", "GetModuleHandleA"));
66 const auto disable =
67 reinterpret_cast<DisableFn>(rt::shims::find("kernel32.dll", "DisableThreadLibraryCalls"));
68 check(get_module != nullptr && disable != nullptr,
69 "the registry serves GetModuleHandleA and DisableThreadLibraryCalls");
70 const HMODULE owned = get_module ? get_module("xmem.dll") : nullptr;
71 check(owned != nullptr, "the shims hand out a pseudo-handle for the module they own (xmem.dll)");
72 check(disable != nullptr && owned != nullptr && disable(owned) == TRUE,
73 "DisableThreadLibraryCalls on a shim pseudo-handle answers TRUE");
74 } catch (const std::exception& e) {
75 std::printf("FAIL unexpected exception: %s\n", e.what());
76 ++g_failures;
77 }
78 std::printf("dll_thread_calls_test: %s (%d failures)\n", g_failures ? "FAILED" : "OK", g_failures);
79 return g_failures ? 1 : 0;
80}
diff --git a/runtime/test/dxgi_swapchain_test.cpp b/runtime/test/dxgi_swapchain_test.cpp
index bc1b99486..95bf9bb06 100644
--- a/runtime/test/dxgi_swapchain_test.cpp
+++ b/runtime/test/dxgi_swapchain_test.cpp
@@ -318,18 +318,63 @@ int main() {
318 318
319 if (!check_statistics_disjoint(sc)) return fail("initial frame-statistics disjoint notification"); 319 if (!check_statistics_disjoint(sc)) return fail("initial frame-statistics disjoint notification");
320 320
321 ID3D12CommandQueue* got_queue = nullptr; 321 ID3D12Device* got_device = nullptr;
322 if (FAILED(sc->GetDevice(IID_PPV_ARGS(&got_queue))) || got_queue != queue) { 322 if (FAILED(sc->GetDevice(IID_PPV_ARGS(&got_device))) || got_device != dev) {
323 if (got_queue) got_queue->Release(); 323 if (got_device) got_device->Release();
324 return fail("GetDevice"); 324 return fail("GetDevice did not return the command queue's parent device");
325 } 325 }
326 got_queue->Release(); 326 got_device->Release();
327
328 IUnknown* got_unknown = nullptr;
329 IUnknown* expected_device_unknown = nullptr;
330 IUnknown* queue_unknown = nullptr;
331 const HRESULT got_unknown_hr = sc->GetDevice(IID_PPV_ARGS(&got_unknown));
332 if (FAILED(got_unknown_hr) || !got_unknown) {
333 if (got_unknown) got_unknown->Release();
334 return fail("GetDevice(IUnknown) failed");
335 }
336 if (FAILED(dev->QueryInterface(IID_PPV_ARGS(&expected_device_unknown))) || !expected_device_unknown) {
337 got_unknown->Release();
338 return fail("QueryInterface(IUnknown) on device failed");
339 }
340 if (FAILED(queue->QueryInterface(IID_PPV_ARGS(&queue_unknown))) || !queue_unknown) {
341 expected_device_unknown->Release();
342 got_unknown->Release();
343 return fail("QueryInterface(IUnknown) on queue failed");
344 }
345 const bool has_device_identity = got_unknown == expected_device_unknown && got_unknown != queue_unknown;
346 queue_unknown->Release();
347 expected_device_unknown->Release();
348 got_unknown->Release();
349 if (!has_device_identity)
350 return fail("GetDevice(IUnknown) returned the queue identity instead of its parent device");
327 DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullscreen{}; 351 DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullscreen{};
328 if (FAILED(sc->GetFullscreenDesc(&fullscreen)) || !fullscreen.Windowed || 352 if (FAILED(sc->GetFullscreenDesc(&fullscreen)) || !fullscreen.Windowed ||
329 fullscreen.Scaling != DXGI_MODE_SCALING_UNSPECIFIED || 353 fullscreen.Scaling != DXGI_MODE_SCALING_UNSPECIFIED ||
330 fullscreen.ScanlineOrdering != DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED) 354 fullscreen.ScanlineOrdering != DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED)
331 return fail("GetFullscreenDesc"); 355 return fail("GetFullscreenDesc");
332 356
357 // Factory::GetParent: root DXGI object has no parent; native DXGI returns E_NOINTERFACE
358 void* parent_out = reinterpret_cast<void*>(1);
359 if (factory->GetParent(IID_IUnknown, nullptr) != E_POINTER)
360 return fail("Factory::GetParent with null out should return E_POINTER");
361 if (factory->GetParent(IID_IUnknown, &parent_out) != E_NOINTERFACE || parent_out != nullptr)
362 return fail("Factory::GetParent should return E_NOINTERFACE and set null out");
363
364 // SwapChain::GetCoreWindow: HWND swapchain is not associated with a CoreWindow
365 void* cw_out = reinterpret_cast<void*>(1);
366 if (sc->GetCoreWindow(IID_IUnknown, nullptr) != DXGI_ERROR_INVALID_CALL)
367 return fail("GetCoreWindow with null out should return DXGI_ERROR_INVALID_CALL");
368 if (sc->GetCoreWindow(IID_IUnknown, &cw_out) != DXGI_ERROR_INVALID_CALL || cw_out != nullptr)
369 return fail("GetCoreWindow on HWND swapchain should return DXGI_ERROR_INVALID_CALL and set null out");
370
371 // SwapChain::GetRestrictToOutput: unrestricted swapchain returns DXGI_ERROR_NOT_FOUND
372 IDXGIOutput* restrict_out = reinterpret_cast<IDXGIOutput*>(1);
373 if (sc->GetRestrictToOutput(nullptr) != E_INVALIDARG)
374 return fail("GetRestrictToOutput with null out should return E_INVALIDARG");
375 if (sc->GetRestrictToOutput(&restrict_out) != DXGI_ERROR_NOT_FOUND || restrict_out != nullptr)
376 return fail("GetRestrictToOutput on unrestricted swapchain should return DXGI_ERROR_NOT_FOUND and set null out");
377
333 D3D12_DESCRIPTOR_HEAP_DESC rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; 378 D3D12_DESCRIPTOR_HEAP_DESC rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
334 ID3D12DescriptorHeap* rtv_heap = nullptr; 379 ID3D12DescriptorHeap* rtv_heap = nullptr;
335 if (FAILED(dev->CreateDescriptorHeap(&rtv_hd, IID_PPV_ARGS(&rtv_heap)))) return fail("CreateDescriptorHeap"); 380 if (FAILED(dev->CreateDescriptorHeap(&rtv_hd, IID_PPV_ARGS(&rtv_heap)))) return fail("CreateDescriptorHeap");
@@ -1088,6 +1133,77 @@ int main() {
1088 CloseHandle(ev); 1133 CloseHandle(ev);
1089 } 1134 }
1090 1135
1136 // Classic IDXGIFactory::CreateSwapChain delegation
1137 {
1138 if (factory->CreateSwapChain(nullptr, nullptr, nullptr) != DXGI_ERROR_INVALID_CALL)
1139 return fail("CreateSwapChain(null out) should return DXGI_ERROR_INVALID_CALL");
1140 IDXGISwapChain* legacy_sc = nullptr;
1141 if (factory->CreateSwapChain(nullptr, nullptr, &legacy_sc) != DXGI_ERROR_INVALID_CALL)
1142 return fail("CreateSwapChain(null device, null desc) should return DXGI_ERROR_INVALID_CALL");
1143 if (factory->CreateSwapChain(queue, nullptr, &legacy_sc) != DXGI_ERROR_INVALID_CALL)
1144 return fail("CreateSwapChain(valid device, null desc) should return DXGI_ERROR_INVALID_CALL");
1145
1146 HWND hwnd_legacy = create_test_window(160, 120);
1147 if (!hwnd_legacy) return fail("CreateWindowExW (legacy)");
1148
1149 DXGI_SWAP_CHAIN_DESC leg_desc{};
1150 leg_desc.BufferDesc.Width = 160;
1151 leg_desc.BufferDesc.Height = 120;
1152 leg_desc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
1153 leg_desc.SampleDesc.Count = 1;
1154 leg_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
1155 leg_desc.BufferCount = 2;
1156 leg_desc.OutputWindow = hwnd_legacy;
1157 leg_desc.Windowed = TRUE;
1158 leg_desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
1159
1160 if (FAILED(factory->CreateSwapChain(queue, &leg_desc, &legacy_sc)) || !legacy_sc) {
1161 DestroyWindow(hwnd_legacy);
1162 return fail("CreateSwapChain failed");
1163 }
1164
1165 DXGI_SWAP_CHAIN_DESC got_leg_desc{};
1166 if (FAILED(legacy_sc->GetDesc(&got_leg_desc)) || got_leg_desc.BufferDesc.Width != 160 ||
1167 got_leg_desc.BufferDesc.Height != 120) {
1168 legacy_sc->Release();
1169 DestroyWindow(hwnd_legacy);
1170 return fail("GetDesc on legacy swapchain mismatch");
1171 }
1172
1173 // Fullscreen request fallback: when exclusive fullscreen is unavailable,
1174 // CreateSwapChain falls back to windowed chain and returns DXGI_STATUS_OCCLUDED.
1175 HWND hwnd_fs = create_test_window(160, 120);
1176 if (!hwnd_fs) return fail("CreateWindowExW (fullscreen fallback)");
1177 DXGI_SWAP_CHAIN_DESC fs_req_desc = leg_desc;
1178 fs_req_desc.OutputWindow = hwnd_fs;
1179 fs_req_desc.Windowed = FALSE;
1180 IDXGISwapChain* fs_sc = nullptr;
1181 const HRESULT fs_hr = factory->CreateSwapChain(queue, &fs_req_desc, &fs_sc);
1182 if (fs_hr != DXGI_STATUS_OCCLUDED || !fs_sc) {
1183 if (fs_sc) fs_sc->Release();
1184 DestroyWindow(hwnd_fs);
1185 return fail("CreateSwapChain(Windowed == FALSE) should return DXGI_STATUS_OCCLUDED fallback");
1186 }
1187 BOOL is_fs = TRUE;
1188 fs_sc->GetFullscreenState(&is_fs, nullptr);
1189 if (is_fs != FALSE) {
1190 fs_sc->Release();
1191 DestroyWindow(hwnd_fs);
1192 return fail("GetFullscreenState should remain FALSE on fallback windowed swapchain");
1193 }
1194 fs_sc->Release();
1195 DestroyWindow(hwnd_fs);
1196
1197 if (FAILED(legacy_sc->Present(0, 0))) {
1198 legacy_sc->Release();
1199 DestroyWindow(hwnd_legacy);
1200 return fail("Present on legacy swapchain failed");
1201 }
1202
1203 legacy_sc->Release();
1204 DestroyWindow(hwnd_legacy);
1205 }
1206
1091 rtv_heap->Release(); 1207 rtv_heap->Release();
1092 sc->Release(); 1208 sc->Release();
1093 fence->Release(); 1209 fence->Release();
@@ -1107,7 +1223,7 @@ int main() {
1107 return 1; 1223 return 1;
1108 } 1224 }
1109 std::printf("device: %s (validation %s)\n", chosen.deviceName, val_active ? "on" : "off"); 1225 std::printf("device: %s (validation %s)\n", chosen.deviceName, val_active ? "on" : "off");
1110 std::printf("dxgi_swapchain_test: PASS (CreateSwapChainForHwnd, CreateSwapChainForCoreWindow, occlusion status, " 1226 std::printf("dxgi_swapchain_test: PASS (CreateSwapChain, CreateSwapChainForHwnd, CreateSwapChainForCoreWindow, occlusion status, "
1111 "GetBuffer+GetDesc, clear+readback, Present, ResizeBuffers; 0 validation errors)\n"); 1227 "GetBuffer+GetDesc, clear+readback, Present, ResizeBuffers; 0 validation errors)\n");
1112 return 0; 1228 return 0;
1113} 1229}
diff --git a/runtime/test/fixtures/dll_thread_calls.cpp b/runtime/test/fixtures/dll_thread_calls.cpp
new file mode 100644
index 000000000..4f4d73eb8
--- /dev/null
+++ b/runtime/test/fixtures/dll_thread_calls.cpp
@@ -0,0 +1,15 @@
1// A DLL whose DllMain returns the result of DisableThreadLibraryCalls(hinstance), the way the MSVC runtime's satellite
2// DLLs do (msvcp140_1.dll, msvcp140_2.dll, msvcp140_atomic_wait.dll, msvcp140_codecvt_ids.dll). Built without the
3// CRT, so nothing but this one call runs at DLL_PROCESS_ATTACH. dll_thread_calls_test maps it with the loader. No game
4// data.
5#include <windows.h>
6
7extern "C" BOOL WINAPI dll_thread_calls_main(HINSTANCE instance, DWORD reason, LPVOID) {
8 if (reason == DLL_PROCESS_ATTACH) return DisableThreadLibraryCalls(instance);
9 return TRUE;
10}
11
12// The same call on a handle that names no module: the answer must stay the Windows one (FALSE).
13extern "C" __declspec(dllexport) BOOL dll_thread_calls_bogus_handle() {
14 return DisableThreadLibraryCalls(reinterpret_cast<HMODULE>(static_cast<uintptr_t>(0x10000)));
15}
diff --git a/runtime/test/fixtures/tiny_gdk_load.cpp b/runtime/test/fixtures/tiny_gdk_load.cpp
index f4c6a163c..99a5c8c2b 100644
--- a/runtime/test/fixtures/tiny_gdk_load.cpp
+++ b/runtime/test/fixtures/tiny_gdk_load.cpp
@@ -68,32 +68,10 @@ int main() {
68 reinterpret_cast<Close>(vtable[17])(obj, queue); 68 reinterpret_cast<Close>(vtable[17])(obj, queue);
69 reinterpret_cast<Release>(vtable[2])(obj); 69 reinterpret_cast<Release>(vtable[2])(obj);
70 70
71 // XNetworkingImpl is served through QueryApiImpl (slot 15: XNetworkingGetConnectivityHint). 71 // A class not served (an id no runtime class has) is refused, with the out pointer cleared.
72 const GUID networking = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}}; 72 const GUID unserved = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}};
73 void* net_obj = nullptr;
74 hr = query(&networking, networking, &net_obj);
75 if (hr != S_OK || !net_obj)
76 return fail("QueryApiImpl hands out XNetworkingImpl", static_cast<unsigned long>(hr));
77 void* const* net_vtable = *static_cast<void* const* const*>(net_obj);
78 struct Hint {
79 UINT32 level;
80 UINT32 cost;
81 UINT32 iana;
82 bool init;
83 bool appr;
84 bool over;
85 bool roam;
86 } hint{};
87 using GetHint = HRESULT(STDMETHODCALLTYPE*)(void*, Hint*);
88 hr = reinterpret_cast<GetHint>(net_vtable[15])(net_obj, &hint);
89 if (hr != S_OK || !hint.init)
90 return fail("XNetworkingImpl slot 15 (XNetworkingGetConnectivityHint)", static_cast<unsigned long>(hr));
91 reinterpret_cast<Release>(net_vtable[2])(net_obj);
92
93 // A class not served yet (an unprovided class id) is refused, with the out pointer cleared.
94 const GUID unprovided = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}};
95 void* out = reinterpret_cast<void*>(1); 73 void* out = reinterpret_cast<void*>(1);
96 hr = query(&unprovided, unprovided, &out); 74 hr = query(&unserved, unserved, &out);
97 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr) 75 if (hr != static_cast<HRESULT>(0x80070032) || out != nullptr)
98 return fail("QueryApiImpl refuses an unprovided class and clears its out pointer", static_cast<unsigned long>(hr)); 76 return fail("QueryApiImpl refuses an unprovided class and clears its out pointer", static_cast<unsigned long>(hr));
99 hr = uninit(); 77 hr = uninit();
diff --git a/runtime/test/fixtures/tiny_startup_cmdline.cpp b/runtime/test/fixtures/tiny_startup_cmdline.cpp
new file mode 100644
index 000000000..ac0de4364
--- /dev/null
+++ b/runtime/test/fixtures/tiny_startup_cmdline.cpp
@@ -0,0 +1,89 @@
1// Synthetic startup fixture: process-attach callbacks must see the entry point's command line.
2#include <windows.h>
3
4#include <cstdio>
5#include <cstdlib>
6#include <cstring>
7#include <cwchar>
8
9namespace {
10
11struct Snapshot {
12 int argc;
13 char argv[8][256];
14 wchar_t wargv[8][256];
15 char line[2048];
16 wchar_t wline[2048];
17};
18
19Snapshot g_startup{};
20bool g_captured = false;
21
22template <typename C, size_t N>
23bool copy(C (&to)[N], const C* from) {
24 if (!from) return false;
25 size_t i = 0;
26 for (; i + 1 < N && from[i]; ++i) to[i] = from[i];
27 to[i] = 0;
28 return from[i] == 0;
29}
30
31bool capture(Snapshot& s) {
32 s.argc = *__p___argc();
33 char** args = *__p___argv();
34 wchar_t** wargs = *__p___wargv();
35 if (s.argc < 1 || s.argc > 8 || !args || !wargs) return false;
36 for (int i = 0; i < s.argc; ++i)
37 if (!copy(s.argv[i], args[i]) || !copy(s.wargv[i], wargs[i])) return false;
38 return !args[s.argc] && !wargs[s.argc] && copy(s.line, GetCommandLineA()) &&
39 copy(s.wline, GetCommandLineW());
40}
41
42bool matches(const Snapshot& a, const Snapshot& b) {
43 if (a.argc != b.argc || std::strcmp(a.line, b.line) || std::wcscmp(a.wline, b.wline)) return false;
44 for (int i = 0; i < a.argc; ++i)
45 if (std::strcmp(a.argv[i], b.argv[i]) || std::wcscmp(a.wargv[i], b.wargv[i])) return false;
46 return true;
47}
48
49} // namespace
50
51#ifdef STARTUP_CMDLINE_DLL
52
53extern "C" __declspec(dllexport) bool __cdecl startup_cmdline_matches(const Snapshot* entry) {
54 return g_captured && matches(g_startup, *entry);
55}
56
57BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
58 if (reason == DLL_PROCESS_ATTACH) {
59 g_captured = capture(g_startup);
60 if (std::strstr(GetCommandLineA(), "fail-init")) return FALSE;
61 }
62 return TRUE;
63}
64
65#else
66
67extern "C" __declspec(dllimport) bool __cdecl startup_cmdline_matches(const Snapshot* entry);
68
69namespace {
70void NTAPI startup_callback(PVOID, DWORD reason, PVOID) {
71 if (reason == DLL_PROCESS_ATTACH) g_captured = capture(g_startup);
72}
73} // namespace
74
75#pragma section(".CRT$XLB", read)
76extern "C" __declspec(allocate(".CRT$XLB")) PIMAGE_TLS_CALLBACK g_startup_callback = startup_callback;
77#pragma comment(linker, "/INCLUDE:_tls_used")
78#pragma comment(linker, "/INCLUDE:g_startup_callback")
79
80int main(int argc, char** argv) {
81 Snapshot entry{};
82 bool ok = capture(entry) && g_captured && matches(g_startup, entry) && startup_cmdline_matches(&entry);
83 ok = ok && argc == entry.argc;
84 for (int i = 0; ok && i < argc; ++i) ok = std::strcmp(argv[i], entry.argv[i]) == 0;
85 std::printf("tiny_startup_cmdline: %s\n", ok ? "PASS" : "FAIL");
86 return ok ? 0 : 1;
87}
88
89#endif
diff --git a/runtime/test/fsr_dispatch_test.cpp b/runtime/test/fsr_dispatch_test.cpp
index 9a66071ac..ee30460b8 100644
--- a/runtime/test/fsr_dispatch_test.cpp
+++ b/runtime/test/fsr_dispatch_test.cpp
@@ -161,6 +161,9 @@ int capture_fault(const EXCEPTION_POINTERS* ep, Call& c) {
161 return EXCEPTION_EXECUTE_HANDLER; 161 return EXCEPTION_EXECUTE_HANDLER;
162} 162}
163 163
164// Each guard returns a copy of `c`, not `c` itself: with `return c;` the local becomes the named return value, and
165// clang-cl 19 and 20 crash (exit 139, in recoverAddrOfEscapedLocal) generating the __except filter that writes it,
166// which stops the Linux cross-build (runtime/cmake/clang-cl-xwin.cmake). MSVC is fine either way.
164Call guarded_configure(ffx::PfnConfigure fn, ffx::Context* ctx, const ffx::Header* desc) { 167Call guarded_configure(ffx::PfnConfigure fn, ffx::Context* ctx, const ffx::Header* desc) {
165 Call c; 168 Call c;
166 __try { 169 __try {
@@ -168,7 +171,7 @@ Call guarded_configure(ffx::PfnConfigure fn, ffx::Context* ctx, const ffx::Heade
168 } __except (capture_fault(GetExceptionInformation(), c)) { 171 } __except (capture_fault(GetExceptionInformation(), c)) {
169 c.faulted = true; 172 c.faulted = true;
170 } 173 }
171 return c; 174 return Call(c);
172} 175}
173 176
174Call guarded_query(ffx::PfnQuery fn, ffx::Context* ctx, ffx::Header* desc) { 177Call guarded_query(ffx::PfnQuery fn, ffx::Context* ctx, ffx::Header* desc) {
@@ -178,7 +181,7 @@ Call guarded_query(ffx::PfnQuery fn, ffx::Context* ctx, ffx::Header* desc) {
178 } __except (capture_fault(GetExceptionInformation(), c)) { 181 } __except (capture_fault(GetExceptionInformation(), c)) {
179 c.faulted = true; 182 c.faulted = true;
180 } 183 }
181 return c; 184 return Call(c);
182} 185}
183 186
184Call guarded_create(ffx::PfnCreateContext fn, ffx::Context* ctx, ffx::Header* desc) { 187Call guarded_create(ffx::PfnCreateContext fn, ffx::Context* ctx, ffx::Header* desc) {
@@ -188,7 +191,7 @@ Call guarded_create(ffx::PfnCreateContext fn, ffx::Context* ctx, ffx::Header* de
188 } __except (capture_fault(GetExceptionInformation(), c)) { 191 } __except (capture_fault(GetExceptionInformation(), c)) {
189 c.faulted = true; 192 c.faulted = true;
190 } 193 }
191 return c; 194 return Call(c);
192} 195}
193 196
194Call guarded_destroy(ffx::PfnDestroyContext fn, ffx::Context* ctx) { 197Call guarded_destroy(ffx::PfnDestroyContext fn, ffx::Context* ctx) {
@@ -198,7 +201,7 @@ Call guarded_destroy(ffx::PfnDestroyContext fn, ffx::Context* ctx) {
198 } __except (capture_fault(GetExceptionInformation(), c)) { 201 } __except (capture_fault(GetExceptionInformation(), c)) {
199 c.faulted = true; 202 c.faulted = true;
200 } 203 }
201 return c; 204 return Call(c);
202} 205}
203 206
204Call guarded_dispatch(ffx::PfnDispatch fn, ffx::Context* ctx, const ffx::Header* desc) { 207Call guarded_dispatch(ffx::PfnDispatch fn, ffx::Context* ctx, const ffx::Header* desc) {
@@ -208,7 +211,7 @@ Call guarded_dispatch(ffx::PfnDispatch fn, ffx::Context* ctx, const ffx::Header*
208 } __except (capture_fault(GetExceptionInformation(), c)) { 211 } __except (capture_fault(GetExceptionInformation(), c)) {
209 c.faulted = true; 212 c.faulted = true;
210 } 213 }
211 return c; 214 return Call(c);
212} 215}
213 216
214// PC stand-in for one console capability. The console build creates a DXGI_FORMAT_R9G9B9E5_SHAREDEXP texture with 217// PC stand-in for one console capability. The console build creates a DXGI_FORMAT_R9G9B9E5_SHAREDEXP texture with
diff --git a/runtime/test/gameinput_probe.cpp b/runtime/test/gameinput_probe.cpp
index 32ddf5d91..a56132ed5 100644
--- a/runtime/test/gameinput_probe.cpp
+++ b/runtime/test/gameinput_probe.cpp
@@ -26,8 +26,10 @@ std::vector<IGameInputDevice*> g_devices;
26 26
27void CALLBACK on_device(GameInputCallbackToken, void*, IGameInputDevice* device, uint64_t, uint32_t current, uint32_t previous) { 27void CALLBACK on_device(GameInputCallbackToken, void*, IGameInputDevice* device, uint64_t, uint32_t current, uint32_t previous) {
28 const GameInputDeviceInfo* i = device->GetDeviceInfo(); 28 const GameInputDeviceInfo* i = device->GetDeviceInfo();
29 std::printf("\n%s %s (%04x:%04x) motors=0x%x\n", (current & GameInputDeviceConnected) ? "connected " : "disconnected", 29 std::printf("\n%s %s (%04x:%04x) motors=0x%x forcefeedback=%u haptic=%u\n",
30 i->displayName ? i->displayName->data : "?", i->vendorId, i->productId, i->supportedRumbleMotors); 30 (current & GameInputDeviceConnected) ? "connected " : "disconnected",
31 i->displayName ? i->displayName->data : "?", i->vendorId, i->productId, i->supportedRumbleMotors,
32 i->forceFeedbackMotorCount, i->hapticFeedbackMotorCount);
31 if ((current & GameInputDeviceConnected) && !(previous & GameInputDeviceConnected)) { 33 if ((current & GameInputDeviceConnected) && !(previous & GameInputDeviceConnected)) {
32 device->AddRef(); 34 device->AddRef();
33 g_devices.push_back(device); 35 g_devices.push_back(device);
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp
index a65b444a1..99e74a082 100644
--- a/runtime/test/gameinput_test.cpp
+++ b/runtime/test/gameinput_test.cpp
@@ -130,8 +130,11 @@ void CALLBACK on_device(GameInputCallbackToken token, void*, IGameInputDevice* d
130 uint32_t previous) { 130 uint32_t previous) {
131 g_device_events.push_back({device, current, previous, token}); 131 g_device_events.push_back({device, current, previous, token});
132} 132}
133DWORD g_reading_sleep_ms = 0; // makes on_reading slow, for the Dispatch quota checks
134
133void CALLBACK on_reading(GameInputCallbackToken, void*, IGameInputReading* reading, bool) { 135void CALLBACK on_reading(GameInputCallbackToken, void*, IGameInputReading* reading, bool) {
134 if (reading) ++g_reading_events; 136 if (reading) ++g_reading_events;
137 if (g_reading_sleep_ms) Sleep(g_reading_sleep_ms);
135} 138}
136void CALLBACK on_guide(GameInputCallbackToken, void*, IGameInputDevice*, uint64_t, bool pressed) { 139void CALLBACK on_guide(GameInputCallbackToken, void*, IGameInputDevice*, uint64_t, bool pressed) {
137 g_guide_events.push_back(pressed); 140 g_guide_events.push_back(pressed);
@@ -763,6 +766,324 @@ void test_twins(IGameInput* input) {
763 check(rt::gameinput::connected_count() == 0, "twins: removed at the end"); 766 check(rt::gameinput::connected_count() == 0, "twins: removed at the end");
764} 767}
765 768
769// ---- force feedback and haptic motors: a fake SDL haptic backend ----
770// SDL's virtual joysticks report no haptics, so the shim's haptic calls go through this table instead. It records what
771// the shim asked SDL to do and reports the capabilities a force-feedback wheel has.
772struct FakeHaptic {
773 uint32_t features = SDL_HAPTIC_CONSTANT | SDL_HAPTIC_SINE | SDL_HAPTIC_SQUARE | SDL_HAPTIC_TRIANGLE |
774 SDL_HAPTIC_SAWTOOTHUP | SDL_HAPTIC_SAWTOOTHDOWN | SDL_HAPTIC_RAMP | SDL_HAPTIC_SPRING |
775 SDL_HAPTIC_FRICTION | SDL_HAPTIC_DAMPER | SDL_HAPTIC_INERTIA;
776 int max_effects = 8;
777 int opens = 0, closes = 0, creates = 0, updates = 0, runs = 0, stops = 0, destroys = 0;
778 int gain_calls = 0, last_gain = -1;
779 uint32_t last_iterations = 0;
780 SDL_HapticEffect last{};
781};
782FakeHaptic g_fake;
783bool g_fake_open = false; // pads attached while this is set are opened as haptic devices
784
785void* fake_open(void*) {
786 if (!g_fake_open) return nullptr;
787 ++g_fake.opens;
788 return &g_fake;
789}
790void fake_close(void*) { ++g_fake.closes; }
791uint32_t fake_features(void* h) { return static_cast<FakeHaptic*>(h)->features; }
792int fake_max_effects(void* h) { return static_cast<FakeHaptic*>(h)->max_effects; }
793int fake_create(void* h, const void* e) {
794 FakeHaptic* f = static_cast<FakeHaptic*>(h);
795 ++f->creates;
796 f->last = *static_cast<const SDL_HapticEffect*>(e);
797 return 1;
798}
799bool fake_update(void* h, int, const void* e) {
800 FakeHaptic* f = static_cast<FakeHaptic*>(h);
801 ++f->updates;
802 f->last = *static_cast<const SDL_HapticEffect*>(e);
803 return true;
804}
805bool fake_run(void* h, int, uint32_t iterations) {
806 FakeHaptic* f = static_cast<FakeHaptic*>(h);
807 ++f->runs;
808 f->last_iterations = iterations;
809 return true;
810}
811bool fake_stop(void* h, int) {
812 ++static_cast<FakeHaptic*>(h)->stops;
813 return true;
814}
815void fake_destroy(void* h, int) { ++static_cast<FakeHaptic*>(h)->destroys; }
816bool fake_gain(void* h, int gain) {
817 FakeHaptic* f = static_cast<FakeHaptic*>(h);
818 ++f->gain_calls;
819 f->last_gain = gain;
820 return true;
821}
822const rt::gameinput::HapticApi kFakeHaptic{fake_open, fake_close, fake_features, fake_max_effects, fake_create,
823 fake_update, fake_run, fake_stop, fake_destroy, fake_gain};
824
825// The motors of one device, and the effect object its force-feedback motor hands out. Runs with no other pad.
826void test_force_feedback(IGameInput* input) {
827 rt::gameinput::set_haptic_source(&kFakeHaptic);
828 g_fake = {};
829 g_fake_open = true;
830 Pad wheel;
831 attach(wheel, "Leonida virtual wheel", 0x046D, 0xC24F, false);
832 const size_t before = g_device_events.size();
833 rt::gameinput::poll();
834 IGameInputDevice* dev = g_device_events.size() > before ? g_device_events.back().device : nullptr;
835 check(dev && rt::gameinput::connected_count() == 1 && g_fake.opens == 1,
836 "force feedback: the pad's joystick is opened as an SDL haptic device");
837 if (!dev) return;
838 dev->AddRef();
839 rt::gameinput::OutputState out{};
840 check(rt::gameinput::output_state(0, &out) && out.force_feedback, "force feedback: the output state says so");
841 IGameInputReading* r = current(input, dev);
842 check(r != nullptr, "force feedback: the pad still reads normally with a haptic device open");
843 if (r) r->Release();
844
845 const GameInputDeviceInfo* info = dev->GetDeviceInfo();
846 check(info->forceFeedbackMotorCount == 1 && info->forceFeedbackMotorInfo != nullptr,
847 "force feedback: the device reports one force-feedback motor");
848 const GameInputForceFeedbackMotorInfo* motor =
849 static_cast<const GameInputForceFeedbackMotorInfo*>(info->forceFeedbackMotorInfo);
850 check(motor->supportedAxes == GameInputFeedbackAxisLinearX && motor->location == GameInputLocationChassis &&
851 motor->maxSimultaneousEffects == 8,
852 "force feedback: motorInfo carries the axis, the location and the effect limit");
853 check(motor->isConstantEffectSupported && motor->isRampEffectSupported && motor->isSpringEffectSupported &&
854 motor->isSawtoothDownWaveEffectSupported,
855 "force feedback: the effect kinds come from SDL's feature bits");
856 check(info->hapticFeedbackMotorCount == 0, "force feedback: a wheel without trigger motors reports no haptics");
857 check(dev->IsForceFeedbackMotorPoweredOn(0) && !dev->IsForceFeedbackMotorPoweredOn(1),
858 "force feedback: motor 0 is powered on, and motor 1 does not exist");
859
860 IGameInputForceFeedbackEffect* effect = nullptr;
861 GameInputForceFeedbackParams params{};
862 params.kind = GameInputForceFeedbackConstant;
863 params.data.constant.magnitude.linearX = 0.5f;
864 check(dev->CreateForceFeedbackEffect(1, &params, reinterpret_cast<void**>(&effect)) == E_INVALIDARG && !effect,
865 "force feedback: motor 1 does not exist");
866 check(dev->CreateForceFeedbackEffect(0, &params, nullptr) == E_POINTER, "force feedback: a null effect is E_POINTER");
867 check(dev->CreateForceFeedbackEffect(0, nullptr, reinterpret_cast<void**>(&effect)) == E_INVALIDARG,
868 "force feedback: null parameters are E_INVALIDARG");
869 GameInputForceFeedbackParams unknown{};
870 unknown.kind = static_cast<GameInputForceFeedbackEffectKind>(11);
871 check(dev->CreateForceFeedbackEffect(0, &unknown, reinterpret_cast<void**>(&effect)) == E_INVALIDARG,
872 "force feedback: an effect kind outside the enum is E_INVALIDARG");
873 check(dev->CreateForceFeedbackEffect(0, &params, reinterpret_cast<void**>(&effect)) == S_OK && effect,
874 "force feedback: CreateForceFeedbackEffect");
875 if (!effect) { // leave nothing behind for the next test
876 detach(wheel);
877 dev->Release();
878 rt::gameinput::poll();
879 rt::gameinput::set_haptic_source(nullptr);
880 return;
881 }
882 check(effect->GetMotorIndex() == 0 && approx(effect->GetGain(), 1.0f) && effect->GetState() == GameInputFeedbackRunning,
883 "force feedback: a new effect is on motor 0, at full gain, running");
884 IGameInputDevice* owner = nullptr;
885 effect->GetDevice(&owner);
886 check(owner == dev, "force feedback: the effect names its device");
887 if (owner) owner->Release();
888
889 // Nothing is asked of SDL before the poll thread runs: the title only wrote the parameters.
890 const int runs0 = g_fake.runs;
891 rt::gameinput::poll();
892 check(g_fake.creates == 1 && g_fake.runs == runs0 + 1, "force feedback: the poll thread creates and runs the effect");
893 check(g_fake.last.type == SDL_HAPTIC_CONSTANT && g_fake.last.constant.level == 16384,
894 "force feedback: a constant 0.5 becomes SDL_HAPTIC_CONSTANT level 16384");
895 check(g_fake.last.constant.length == 60000 && g_fake.last_iterations == 0,
896 "force feedback: no duration in GameInput is SDL's 60 s hold, run until stopped");
897 rt::gameinput::poll();
898 check(g_fake.runs == runs0 + 1, "force feedback: an unchanged effect is not re-sent every poll");
899
900 params.data.constant.magnitude.linearX = -1.0f;
901 check(effect->SetParams(&params), "force feedback: SetParams");
902 rt::gameinput::poll();
903 check(g_fake.updates == 1 && g_fake.runs == runs0 + 2 && g_fake.last.constant.level == -32767,
904 "force feedback: changed parameters update the SDL effect once");
905 GameInputForceFeedbackParams read{};
906 effect->GetParams(&read);
907 check(read.kind == GameInputForceFeedbackConstant && read.data.constant.magnitude.linearX == -1.0f,
908 "force feedback: GetParams returns what was set");
909
910 effect->SetGain(0.5f);
911 rt::gameinput::poll();
912 check(approx(effect->GetGain(), 0.5f) && g_fake.last.constant.level == -16384,
913 "force feedback: the effect's gain scales the SDL level");
914 // The device gain is SDL's, sent once when the pad is opened (100) and once per change.
915 check(g_fake.last_gain == 100 && g_fake.gain_calls == 1, "force feedback: the device gain starts at SDL's full 100");
916 dev->SetForceFeedbackMotorGain(0, 0.5f);
917 rt::gameinput::poll();
918 check(g_fake.last_gain == 50 && g_fake.gain_calls == 2,
919 "force feedback: SetForceFeedbackMotorGain sets SDL's device gain once");
920 dev->SetForceFeedbackMotorGain(0, 1.0f);
921 effect->SetGain(1.0f);
922 rt::gameinput::poll();
923 check(g_fake.last_gain == 100, "force feedback: the master gain follows the request");
924
925 // A wave with GameInput's envelope: 50 Hz for 90 degrees over 100 ms, played once.
926 GameInputForceFeedbackParams wave{};
927 wave.kind = GameInputForceFeedbackSineWave;
928 wave.data.sineWave.envelope.sustainDuration = 100'000; // microseconds
929 wave.data.sineWave.envelope.sustainGain = 1.0f;
930 wave.data.sineWave.envelope.playCount = 1;
931 wave.data.sineWave.magnitude.linearX = 1.0f;
932 wave.data.sineWave.frequency = 50.0f;
933 wave.data.sineWave.phase = 90.0f;
934 check(effect->SetParams(&wave), "force feedback: SetParams for a sine wave");
935 rt::gameinput::poll();
936 check(g_fake.last.type == SDL_HAPTIC_SINE && g_fake.last.periodic.period == 20 &&
937 g_fake.last.periodic.magnitude == 32767 && g_fake.last.periodic.phase == 9000,
938 "force feedback: a 50 Hz sine with a 90 degree phase becomes SDL's period and hundredths of a degree");
939 check(g_fake.last.periodic.length == 100 && g_fake.last_iterations == 1,
940 "force feedback: the envelope's 100 ms is SDL's length and its playCount the iteration count");
941 Sleep(130);
942 rt::gameinput::poll();
943 check(effect->GetState() == GameInputFeedbackStopped && g_fake.stops >= 1,
944 "force feedback: an effect that ran its duration reports stopped");
945
946 // A condition effect: coefficients, saturations, dead zone and centre.
947 GameInputForceFeedbackParams spring{};
948 spring.kind = GameInputForceFeedbackSpring;
949 spring.data.spring.magnitude.linearX = 0.5f;
950 spring.data.spring.positiveCoefficient = 0.5f;
951 spring.data.spring.negativeCoefficient = 0.25f;
952 spring.data.spring.maxPositiveMagnitude = 1.0f;
953 spring.data.spring.maxNegativeMagnitude = 0.5f;
954 spring.data.spring.deadZone = 0.1f;
955 check(effect->SetParams(&spring), "force feedback: SetParams for a spring");
956 effect->SetState(GameInputFeedbackRunning);
957 rt::gameinput::poll();
958 check(g_fake.last.type == SDL_HAPTIC_SPRING && g_fake.last.condition.right_coeff[0] == 16384 &&
959 g_fake.last.condition.left_coeff[0] == -8192 && g_fake.last.condition.right_sat[0] == 65535 &&
960 g_fake.last.condition.left_sat[0] == 32768 && g_fake.last.condition.deadband[0] == 6554 &&
961 g_fake.last.condition.center[0] == 16384,
962 "force feedback: a spring maps its coefficients, saturations, dead zone and centre");
963
964 effect->SetState(GameInputFeedbackPaused);
965 const int stops0 = g_fake.stops;
966 rt::gameinput::poll();
967 check(g_fake.stops == stops0 + 1 && effect->GetState() == GameInputFeedbackPaused,
968 "force feedback: a paused effect is stopped in SDL");
969
970 // LEONIDA_RUMBLE=0 silences this path too: a running effect is stopped, and it runs again when the mute lifts.
971 effect->SetState(GameInputFeedbackRunning);
972 rt::gameinput::poll();
973 const int runs1 = g_fake.runs, stops1 = g_fake.stops;
974 check(g_fake.runs == runs1, "force feedback: the effect is running before the mute");
975 set_env("LEONIDA_RUMBLE", "0");
976 rt::gameinput::reload_config();
977 rt::gameinput::poll();
978 check(g_fake.runs == runs1 && g_fake.stops == stops1 + 1, "force feedback: LEONIDA_RUMBLE=0 stops the effect");
979 set_env("LEONIDA_RUMBLE", nullptr);
980 rt::gameinput::reload_config();
981 rt::gameinput::poll();
982 check(g_fake.runs == runs1 + 1, "force feedback: and it runs again once the mute is lifted");
983
984 check(effect->Release() == 0, "force feedback: the effect is freed once the title releases it");
985 rt::gameinput::poll();
986 check(g_fake.destroys == 1, "force feedback: its SDL effect is destroyed on the poll thread");
987
988 detach(wheel);
989 rt::gameinput::poll();
990 check(g_fake.closes == 1 && !dev->IsForceFeedbackMotorPoweredOn(0),
991 "force feedback: unplugging closes the haptic device");
992 dev->Release();
993
994 // A pad SDL opens no haptic device for keeps the old answer: no motor, and no effect.
995 g_fake_open = false;
996 Pad plain;
997 attach(plain, "Leonida virtual plain pad", 0x045E, 0x02FF, false);
998 const size_t plain_before = g_device_events.size();
999 rt::gameinput::poll();
1000 IGameInputDevice* plaindev = g_device_events.size() > plain_before ? g_device_events.back().device : nullptr;
1001 check(plaindev && plaindev->GetDeviceInfo()->forceFeedbackMotorCount == 0 &&
1002 plaindev->GetDeviceInfo()->forceFeedbackMotorInfo == nullptr,
1003 "force feedback: a pad without SDL haptics reports no motor");
1004 if (plaindev) {
1005 effect = nullptr;
1006 check(plaindev->CreateForceFeedbackEffect(0, &params, reinterpret_cast<void**>(&effect)) == E_INVALIDARG && !effect,
1007 "force feedback: so CreateForceFeedbackEffect is E_INVALIDARG");
1008 check(!plaindev->IsForceFeedbackMotorPoweredOn(0), "force feedback: and no motor is powered on");
1009 }
1010 detach(plain);
1011 rt::gameinput::poll();
1012 rt::gameinput::set_haptic_source(nullptr);
1013}
1014
1015// The trigger haptic motors of a pad that has them. Runs with no other pad.
1016void test_haptic_motors(IGameInput* input) {
1017 set_env("LEONIDA_DS_TRIGGERS", nullptr);
1018 rt::gameinput::reload_config();
1019 Pad xbox;
1020 attach(xbox, "Leonida virtual Xbox pad", 0x045E, 0x0B12, true);
1021 const size_t before = g_device_events.size();
1022 rt::gameinput::poll();
1023 IGameInputDevice* dev = g_device_events.size() > before ? g_device_events.back().device : nullptr;
1024 check(dev && rt::gameinput::connected_count() == 1, "haptics: the pad with trigger motors is connected");
1025 if (!dev) return;
1026 dev->AddRef();
1027 const GameInputDeviceInfo* info = dev->GetDeviceInfo();
1028 check(info->hapticFeedbackMotorCount == 2 && info->hapticFeedbackMotorInfo != nullptr,
1029 "haptics: the pad reports two haptic motors");
1030 const GameInputHapticFeedbackMotorInfo* motors =
1031 static_cast<const GameInputHapticFeedbackMotorInfo*>(info->hapticFeedbackMotorInfo);
1032 check(motors[0].mappedRumbleMotors == GameInputRumbleLeftTrigger &&
1033 motors[1].mappedRumbleMotors == GameInputRumbleRightTrigger && motors[0].waveformCount == 1 &&
1034 motors[0].waveformInfo != nullptr && motors[0].waveformInfo->isIntensitySupported,
1035 "haptics: they are the left and right trigger, one waveform each, an intensity");
1036 check(sticks_at_rest(pad_state(input, dev)), "haptics: the pad still reads normally");
1037
1038 GameInputHapticFeedbackParams p{};
1039 p.intensity = 0.5f;
1040 p.duration = 100'000; // microseconds
1041 p.playCount = 1;
1042 check(dev->SetHapticMotorState(2, &p) == E_INVALIDARG, "haptics: motor 2 does not exist");
1043 GameInputHapticFeedbackParams other_wave = p;
1044 other_wave.waveformIndex = 1;
1045 check(dev->SetHapticMotorState(0, &other_wave) == E_INVALIDARG, "haptics: waveform 1 does not exist");
1046 check(dev->SetHapticMotorState(0, &p) == S_OK, "haptics: SetHapticMotorState on the left trigger");
1047 rt::gameinput::poll();
1048 check(xbox.left == 32768 && xbox.right == 0, "haptics: the intensity reaches the trigger motor");
1049 Sleep(130);
1050 rt::gameinput::poll();
1051 check(xbox.left == 0, "haptics: the request ends with its duration");
1052
1053 p.intensity = 1.0f;
1054 p.playCount = 0; // until changed
1055 check(dev->SetHapticMotorState(1, &p) == S_OK, "haptics: playCount 0 plays until changed");
1056 rt::gameinput::poll();
1057 check(xbox.right == 65535 && xbox.left == 0, "haptics: the right trigger takes its own motor");
1058 Sleep(130);
1059 rt::gameinput::poll();
1060 check(xbox.right == 65535, "haptics: and keeps playing past the duration");
1061 check(dev->SetHapticMotorState(1, nullptr) == S_OK, "haptics: a null state stops the motor");
1062 rt::gameinput::poll();
1063 check(xbox.right == 0 && xbox.left == 0, "haptics: both triggers are silent again");
1064
1065 // SetRumbleState still works on the same pad, and the two share the trigger output.
1066 GameInputRumbleParams rumble{0, 0, 0.25f, 0};
1067 dev->SetRumbleState(&rumble);
1068 rt::gameinput::poll();
1069 check(xbox.left == 16384, "haptics: SetRumbleState still drives the trigger motor");
1070 p.intensity = 1.0f;
1071 p.playCount = 1;
1072 p.duration = 0; // no deadline at playCount 1 either: the level holds until it is set again
1073 dev->SetHapticMotorState(0, &p);
1074 rt::gameinput::poll();
1075 check(xbox.left == 65535, "haptics: the stronger of the two wins on one trigger");
1076 dev->SetRumbleState(nullptr);
1077 dev->SetHapticMotorState(0, nullptr);
1078 rt::gameinput::poll();
1079 check(xbox.left == 0, "haptics: releasing both leaves the trigger silent");
1080
1081 detach(xbox);
1082 rt::gameinput::poll();
1083 check(rt::gameinput::connected_count() == 0, "haptics: detached");
1084 dev->Release();
1085}
1086
766} // namespace 1087} // namespace
767 1088
768int main() { 1089int main() {
@@ -1024,6 +1345,32 @@ int main() {
1024 check(wait && WaitForSingleObject(wait, 0) == WAIT_OBJECT_0, "the wait handle is signalled"); 1345 check(wait && WaitForSingleObject(wait, 0) == WAIT_OBJECT_0, "the wait handle is signalled");
1025 if (dispatcher) dispatcher->Dispatch(1000); 1346 if (dispatcher) dispatcher->Dispatch(1000);
1026 check(g_reading_events > before_dispatch, "Dispatch runs them"); 1347 check(g_reading_events > before_dispatch, "Dispatch runs them");
1348
1349 // The quota: Dispatch runs at least one queued event, takes no more once the quota has passed, and returns whether
1350 // events remain (re-signalling the wait handle). Four button changes queue four reading events.
1351 auto queue_changes = [&](int n) {
1352 for (int i = 0; i < n; ++i) {
1353 SDL_SetJoystickVirtualButton(xbox.js, SDL_GAMEPAD_BUTTON_NORTH, i % 2 == 1); // NORTH is down now: up, down, up, down
1354 rt::gameinput::poll();
1355 }
1356 };
1357 if (dispatcher) {
1358 while (dispatcher->Dispatch(UINT64_MAX)) {}
1359 queue_changes(4);
1360 int before_quota = g_reading_events;
1361 if (wait) WaitForSingleObject(wait, 0); // consume the signal from queueing
1362 check(dispatcher->Dispatch(0) && g_reading_events == before_quota + 1, "Dispatch(0) runs exactly one event and reports more");
1363 check(wait && WaitForSingleObject(wait, 0) == WAIT_OBJECT_0, "the wait handle is signalled again while events remain");
1364 g_reading_sleep_ms = 5;
1365 before_quota = g_reading_events;
1366 check(dispatcher->Dispatch(1000) && g_reading_events == before_quota + 1,
1367 "a 1 ms quota stops after a 5 ms callback and reports more");
1368 g_reading_sleep_ms = 0;
1369 before_quota = g_reading_events;
1370 check(!dispatcher->Dispatch(1'000'000) && g_reading_events >= before_quota + 2,
1371 "a large quota drains the queue and returns false");
1372 check(!dispatcher->Dispatch(0), "Dispatch on an empty queue returns false");
1373 }
1027 if (wait) CloseHandle(wait); 1374 if (wait) CloseHandle(wait);
1028 if (dispatcher) dispatcher->Release(); 1375 if (dispatcher) dispatcher->Release();
1029 1376
@@ -1226,6 +1573,8 @@ int main() {
1226 test_keyboard_pad(input); 1573 test_keyboard_pad(input);
1227 test_motion(input); 1574 test_motion(input);
1228 test_aggregate_device(input); 1575 test_aggregate_device(input);
1576 test_force_feedback(input);
1577 test_haptic_motors(input);
1229 input->Release(); 1578 input->Release();
1230 1579
1231 std::printf("%d checks, %d failures\n", g_checks, g_failures); 1580 std::printf("%d checks, %d failures\n", g_checks, g_failures);
diff --git a/runtime/test/gfx10_tiling_test.cpp b/runtime/test/gfx10_tiling_test.cpp
new file mode 100644
index 000000000..fd0d14779
--- /dev/null
+++ b/runtime/test/gfx10_tiling_test.cpp
@@ -0,0 +1,155 @@
1#include "../src/gfx10_tiling.h"
2
3#include <algorithm>
4#include <array>
5#include <cstdio>
6#include <limits>
7#include <vector>
8
9#define CHECK(condition) do { \
10 if (!(condition)) { \
11 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
12 return 1; \
13 } \
14} while (0)
15
16using leonida::gfx10::TileMode;
17using leonida::gfx10::TiledSurface2D;
18
19int check_surface(TileMode mode, std::size_t bpe, std::size_t width, std::size_t height) {
20 TiledSurface2D surface;
21 CHECK(TiledSurface2D::make(mode, bpe, width, height, surface));
22 const auto bw = surface.tile_width(), bh = surface.tile_height();
23 const auto pw = (width + bw - 1) / bw * bw, ph = (height + bh - 1) / bh * bh;
24 CHECK(surface.tiled_size() == pw * ph * bpe);
25 TiledSurface2D padded;
26 CHECK(TiledSurface2D::make(mode, bpe, pw, ph, padded));
27 std::vector<bool> seen(surface.tiled_size());
28 for (std::size_t y = 0; y < ph; ++y) {
29 for (std::size_t x = 0; x < pw; ++x) {
30 std::size_t offset;
31 CHECK(padded.element_offset(x, y, offset));
32 CHECK(offset % bpe == 0 && offset <= seen.size() - bpe);
33 for (std::size_t byte = 0; byte < bpe; ++byte) {
34 CHECK(!seen[offset + byte]);
35 seen[offset + byte] = true;
36 }
37 }
38 }
39 CHECK(std::all_of(seen.begin(), seen.end(), [](bool value) { return value; }));
40
41 const std::size_t row_bytes = width * bpe;
42 for (const auto pitch : {row_bytes, row_bytes + 13}) {
43 const std::size_t linear_size = (height - 1) * pitch + row_bytes;
44 std::vector<std::byte> linear(linear_size), tiled(surface.tiled_size(), std::byte{0xcc});
45 for (std::size_t i = 0; i < linear.size(); ++i) linear[i] = std::byte((i * 37 + i / 251) & 255);
46 std::vector<std::byte> decoded(linear_size, std::byte{0xab});
47 CHECK(surface.tile(linear, tiled, pitch));
48 CHECK(surface.detile(tiled, decoded, pitch));
49 std::vector<std::byte> expected(linear_size, std::byte{0xab});
50 for (std::size_t y = 0; y < height; ++y)
51 std::copy_n(linear.begin() + y * pitch, row_bytes, expected.begin() + y * pitch);
52 CHECK(decoded == expected);
53 std::vector<std::byte> reference(linear_size, std::byte{0xab});
54 for (std::size_t y = 0; y < height; ++y) {
55 for (std::size_t x = 0; x < width; ++x) {
56 std::size_t offset;
57 CHECK(surface.element_offset(x, y, offset));
58 std::copy_n(tiled.begin() + offset, bpe, reference.begin() + y * pitch + x * bpe);
59 }
60 }
61 CHECK(decoded == reference);
62 std::vector<std::byte> encoded(tiled.size(), std::byte{0xcc});
63 CHECK(surface.tile(decoded, encoded, pitch));
64 CHECK(encoded == tiled);
65 std::vector<bool> active(tiled.size());
66 for (std::size_t y = 0; y < height; ++y) {
67 for (std::size_t x = 0; x < width; ++x) {
68 std::size_t offset;
69 CHECK(surface.element_offset(x, y, offset));
70 for (std::size_t byte = 0; byte < bpe; ++byte) {
71 CHECK(tiled[offset + byte] == linear[y * pitch + x * bpe + byte]);
72 active[offset + byte] = true;
73 }
74 }
75 }
76 for (std::size_t i = 0; i < tiled.size(); ++i) CHECK(active[i] || tiled[i] == std::byte{0xcc});
77
78 const auto before_tiled = tiled, before_decoded = decoded;
79 CHECK(!surface.tile(std::span(linear).first(linear_size - 1), tiled, pitch));
80 CHECK(!surface.tile(linear, std::span(tiled).first(tiled.size() - 1), pitch));
81 CHECK(!surface.detile(std::span(tiled).first(tiled.size() - 1), decoded, pitch));
82 CHECK(!surface.detile(tiled, std::span(decoded).first(linear_size - 1), pitch));
83 CHECK(!surface.tile(linear, tiled, row_bytes - 1));
84 CHECK(!surface.detile(tiled, decoded, row_bytes - 1));
85 CHECK(!surface.tile({}, tiled, pitch));
86 CHECK(!surface.detile(tiled, {}, pitch));
87 CHECK(tiled == before_tiled && decoded == before_decoded);
88 }
89 std::size_t offset = 123;
90 CHECK(!surface.element_offset(width, 0, offset));
91 CHECK(!surface.element_offset(0, height, offset));
92 CHECK(offset == 123);
93 std::vector<std::byte> shared(std::max(surface.tiled_size(), width * height * bpe) + 1);
94 const auto before = shared;
95 CHECK(!surface.tile(shared, shared, row_bytes));
96 CHECK(!surface.detile(shared, shared, row_bytes));
97 CHECK(!surface.tile(std::span(shared).subspan(1), std::span(shared).first(shared.size() - 1), row_bytes));
98 CHECK(!surface.detile(std::span(shared).first(shared.size() - 1), std::span(shared).subspan(1), row_bytes));
99 CHECK(shared == before);
100 return 0;
101}
102
103int main() {
104 // Source byte offsets reconstructed by calling ttpf_mips.detile on synthetic address-labelled bytes,
105 // three passes (address >> 0/8/16). Extent 300x130; points (4,4), (32,16), (299,129).
106 constexpr std::size_t answers[2][5][3] = {
107 {{68, 2304, 59419}, {72, 3072, 100502}, {192, 5120, 201244},
108 {384, 45056, 365144}, {768, 86016, 698576}},
109 {{36, 2304, 84051}, {72, 3072, 198806}, {192, 9216, 336412},
110 {320, 12288, 533048}, {768, 36864, 952432}}};
111 constexpr std::array<std::array<std::size_t, 2>, 3> points{{{4, 4}, {32, 16}, {299, 129}}};
112 unsigned mode_index = 0;
113 for (const auto mode : {TileMode::sw_4kb_s, TileMode::sw_64kb_d}) {
114 unsigned bpe_index = 0;
115 for (const std::size_t bpe : {1, 2, 4, 8, 16}) {
116 TiledSurface2D surface;
117 CHECK(TiledSurface2D::make(mode, bpe, 300, 130, surface));
118 for (unsigned i = 0; i < points.size(); ++i) {
119 std::size_t offset;
120 CHECK(surface.element_offset(points[i][0], points[i][1], offset));
121 CHECK(offset == answers[mode_index][bpe_index][i]);
122 }
123 CHECK(check_surface(mode, bpe, 1, 1) == 0);
124 CHECK(check_surface(mode, bpe, 33, 17) == 0);
125 CHECK(check_surface(mode, bpe, 300, 130) == 0);
126 CHECK(check_surface(mode, bpe, surface.tile_width() * 2, surface.tile_height() * 2) == 0);
127 ++bpe_index;
128 }
129 ++mode_index;
130 }
131 TiledSurface2D invalid;
132 for (const std::size_t bpe : {0, 3, 12, 32})
133 CHECK(!TiledSurface2D::make(TileMode::sw_4kb_s, bpe, 1, 1, invalid));
134 CHECK(!TiledSurface2D::make(TileMode(99), 4, 1, 1, invalid));
135 CHECK(!TiledSurface2D::make(TileMode::sw_4kb_s, 4, 0, 1, invalid));
136 CHECK(!TiledSurface2D::make(TileMode::sw_4kb_s, 4, 1, 0, invalid));
137 constexpr auto max = std::numeric_limits<std::size_t>::max();
138 for (const auto mode : {TileMode::sw_4kb_s, TileMode::sw_64kb_d}) {
139 CHECK(!TiledSurface2D::make(mode, 16, max, 1, invalid));
140 CHECK(!TiledSurface2D::make(mode, 1, max, max, invalid));
141 CHECK(!TiledSurface2D::make(mode, 1, 1, max, invalid));
142 }
143 CHECK(invalid.tiled_size() == 0);
144 std::size_t offset;
145 CHECK(!invalid.element_offset(0, 0, offset));
146 CHECK(!invalid.tile({}, {}, 0));
147 CHECK(!invalid.detile({}, {}, 0));
148 TiledSurface2D surface;
149 CHECK(TiledSurface2D::make(TileMode::sw_4kb_s, 4, 1, 3, surface));
150 std::vector<std::byte> tiled(surface.tiled_size()), linear(12);
151 CHECK(!surface.tile(linear, tiled, max));
152 CHECK(!surface.detile(tiled, linear, max));
153 std::puts("gfx10_tiling: 40 surface round trips, padded bijections, 30 Python offsets and invalid arguments passed");
154 return 0;
155}
diff --git a/runtime/test/glsl/gs_double.geom b/runtime/test/glsl/gs_double.geom
new file mode 100644
index 000000000..4181b4f9d
--- /dev/null
+++ b/runtime/test/glsl/gs_double.geom
@@ -0,0 +1,22 @@
1#version 460
2// A geometry shader with the interface of a translated one (docs/design.md, "Geometry shaders": triangles in, a
3// triangle strip out, inputs and outputs at the signature's locations), for d3d12_geometry_test. It emits every
4// input triangle twice: as it is, and moved right by one in clip space, so a quad drawn in the top-left quadrant
5// also covers the top-right one. The colour at location 0 (vs_draw.vert's output) passes through.
6
7layout(triangles) in;
8layout(triangle_strip, max_vertices = 6) out;
9
10layout(location = 0) in vec4 in_color[];
11layout(location = 0) out vec4 out_color;
12
13void main() {
14 for (int copy = 0; copy < 2; ++copy) {
15 for (int i = 0; i < 3; ++i) {
16 gl_Position = gl_in[i].gl_Position + vec4(float(copy), 0.0, 0.0, 0.0);
17 out_color = in_color[i];
18 EmitVertex();
19 }
20 EndPrimitive();
21 }
22}
diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp
index 194174b00..73bc49206 100644
--- a/runtime/test/loader_test.cpp
+++ b/runtime/test/loader_test.cpp
@@ -184,6 +184,28 @@ void expect_rejects(const char* what, const std::vector<uint8_t>& bytes) {
184 184
185void test_valid_image() { expect_loads("a valid image maps with its section intact", make_image()); } 185void test_valid_image() { expect_loads("a valid image maps with its section intact", make_image()); }
186 186
187void test_entry_bounds() {
188 for (bool is_dll : {false, true}) {
189 for (uint32_t entry : {0u, 0x1000u, 0x1FFFu, 0x2000u, 0x2001u}) {
190 auto img = make_image();
191 if (is_dll) nt_of(img)->FileHeader.Characteristics |= IMAGE_FILE_DLL;
192 nt_of(img)->OptionalHeader.AddressOfEntryPoint = entry;
193 const std::string what = std::string(is_dll ? "DLL" : "EXE") + " entry RVA " + std::to_string(entry);
194 if (entry < nt_of(img)->OptionalHeader.SizeOfImage) {
195 expect_loads(what.c_str(), img);
196 } else {
197 std::string error;
198 if (load(write_image(img), error) == 0)
199 failed(what.c_str(), "the image loaded");
200 else if (error.find("the entry point is outside the image") == std::string::npos)
201 failed(what.c_str(), "unexpected error: " + error);
202 else
203 pass(what.c_str());
204 }
205 }
206 }
207}
208
187void test_header_bounds() { 209void test_header_bounds() {
188 { 210 {
189 auto img = make_image(); 211 auto img = make_image();
@@ -941,6 +963,19 @@ std::vector<uint8_t> make_unwind_image(const std::vector<RUNTIME_FUNCTION>& entr
941 return img; 963 return img;
942} 964}
943 965
966// PE/COFF: NumberOfRvaAndSizes counts the data directories; the slots past it are not directories whatever they hold.
967// With 9 directories the TLS slot (index 9) is not one, so bytes left in it must not make the image fail to load.
968void test_tls_directory_count() {
969 auto img = make_image();
970 auto& tls = nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
971 tls.VirtualAddress = 0xFFFF0000; // would run past the image if it were read as a TLS directory
972 tls.Size = sizeof(IMAGE_TLS_DIRECTORY64);
973 nt_of(img)->OptionalHeader.NumberOfRvaAndSizes = IMAGE_DIRECTORY_ENTRY_TLS;
974 expect_loads("a TLS slot past NumberOfRvaAndSizes is not read as a TLS directory", img);
975 nt_of(img)->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
976 expect_rejects("the same TLS slot within NumberOfRvaAndSizes is checked and refused", img);
977}
978
944void test_unwind_registration() { 979void test_unwind_registration() {
945 const std::vector<RUNTIME_FUNCTION> entries = {{0x1000, 0x1010, kUnwindRva}, {0x1010, 0x1020, kUnwindRva}}; 980 const std::vector<RUNTIME_FUNCTION> entries = {{0x1000, 0x1010, kUnwindRva}, {0x1010, 0x1020, kUnwindRva}};
946 uintptr_t pc = 0; 981 uintptr_t pc = 0;
@@ -1093,6 +1128,7 @@ int main() {
1093 return 1; 1128 return 1;
1094 } 1129 }
1095 test_valid_image(); 1130 test_valid_image();
1131 test_entry_bounds();
1096 test_header_bounds(); 1132 test_header_bounds();
1097 test_section_bounds(); 1133 test_section_bounds();
1098 test_truncation(); 1134 test_truncation();
@@ -1109,6 +1145,7 @@ int main() {
1109 test_delay_descriptor_fields(); 1145 test_delay_descriptor_fields();
1110 test_forwarded_exports(); 1146 test_forwarded_exports();
1111 test_export_bounds(); 1147 test_export_bounds();
1148 test_tls_directory_count();
1112 test_unwind_registration(); 1149 test_unwind_registration();
1113 } catch (const std::exception& e) { 1150 } catch (const std::exception& e) {
1114 // A write that fails (write_image throws) ends the run with the reason, instead of terminating the process. 1151 // A write that fails (write_image throws) ends the run with the reason, instead of terminating the process.
diff --git a/runtime/test/replay_query_edges_test.cpp b/runtime/test/replay_query_edges_test.cpp
new file mode 100644
index 000000000..1bd55d237
--- /dev/null
+++ b/runtime/test/replay_query_edges_test.cpp
@@ -0,0 +1,1043 @@
1// Query heap boundaries, resolve helper chunking, arena offsets, query reuse across lists/submissions, and
2// predication around copies. These edge cases are only reached by GPU tests today; this CPU mock lets CI
3// without a GPU check replay planning, emitted commands, destination guards, and pool ownership on submit failure.
4// Shader arithmetic and Vulkan entry points are mocked; no driver is loaded. No GPU or game data.
5#include "../src/vulkan_backend.h"
6
7#include <algorithm>
8#include <array>
9#include <cstdint>
10#include <cstdio>
11#include <cstring>
12#include <map>
13#include <memory>
14#include <set>
15#include <stdexcept>
16#include <string>
17#include <string_view>
18#include <utility>
19#include <vector>
20
21namespace {
22
23using namespace leonida;
24
25// OcclusionResolve keeps these capacities private (runtime/src/vulkan_backend.h). Pin the expected boundaries
26// here so a change to its chunking still has an independent oracle; derive public result sizes from the IR.
27constexpr unsigned sum_capacity = 256;
28constexpr unsigned binary_capacity = 1024;
29constexpr unsigned statistics_capacity = 64;
30constexpr unsigned binary_group_size = 64;
31constexpr VkDeviceSize word_size = sizeof(std::uint64_t);
32constexpr unsigned statistics_size = query_result_size(d3d12_query::pipeline_statistics);
33constexpr unsigned statistics_counters = statistics_size / word_size;
34constexpr VkDeviceSize scratch_size = std::max({sum_capacity + 1, binary_capacity,
35 (statistics_capacity + 1) * statistics_counters}) * word_size;
36constexpr unsigned char guard_byte = 0xa5;
37
38template<class T>
39T handle(std::uintptr_t n) {
40 return reinterpret_cast<T>(n);
41}
42
43// Stop the current case on failure so a failed mock bounds check cannot turn into an out-of-bounds access.
44void expect(bool ok, const char* what) {
45 if (!ok) {
46 throw std::runtime_error(what);
47 }
48}
49struct Call {
50 VkQueryPool pool;
51 unsigned first;
52 unsigned count;
53 VkDeviceSize offset;
54 VkDeviceSize stride;
55};
56
57struct MockReplay {
58 static inline MockReplay* current;
59 std::map<VkBuffer, std::vector<unsigned char>> buffers;
60 std::map<VkQueryPool, std::vector<std::array<std::uint64_t, statistics_counters>>> values;
61 std::vector<Call> copies;
62 std::vector<std::pair<VkQueryPool, unsigned>> resets;
63 std::set<VkQueryPool> statistics_pools;
64 std::vector<unsigned> chunks;
65 std::vector<unsigned> groups;
66 std::vector<VkBufferCopy> transfers;
67 std::vector<std::string> events;
68 std::map<VkQueryPool, std::set<unsigned>> active;
69 bool conditional = false;
70 bool execute = true;
71 unsigned captures = 0;
72 unsigned pred_copies = 0;
73 unsigned native_copies = 0;
74 std::uint64_t snapshot = 0;
75 std::uint64_t serial = 10;
76 enum Mode {
77 none,
78 sum,
79 binary,
80 statistics
81 };
82 Mode mode = none;
83 MockReplay() {
84 current = this;
85 // OcclusionResolve is exercised without initialize(); the null buffer stands in for its scratch storage.
86 buffers[VK_NULL_HANDLE].resize(scratch_size);
87 }
88
89 auto& bytes(VkBuffer b, VkDeviceSize offset, VkDeviceSize size) {
90 auto& v = buffers.at(b);
91 expect(offset <= v.size() && size <= v.size() - offset, "mock buffer access out of bounds");
92 return v;
93 }
94
95 std::uint64_t word(VkBuffer b, VkDeviceSize off) {
96 std::uint64_t v;
97 auto&a = bytes(b, off, word_size);
98 std::memcpy(&v, a.data() + off, word_size);
99 return v;
100 }
101
102 void word(VkBuffer b, VkDeviceSize off, std::uint64_t v) {
103 auto&a = bytes(b, off, word_size);
104 std::memcpy(a.data() + off, &v, word_size);
105 }
106
107 void query(VkQueryPool p, unsigned first, unsigned count, VkBuffer b, VkDeviceSize off, VkDeviceSize stride,
108 VkQueryResultFlags flags) {
109 constexpr auto result_flags = VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT;
110 expect((flags & result_flags) == result_flags, "query result flags");
111 copies.push_back({p, first, count, off, stride});
112 auto& q = values.at(p);
113 expect(first <= q.size() && count <= q.size() - first, "mock query access out of bounds");
114 for (unsigned i = 0; i < count; ++i) {
115 for (unsigned j = 0; j < (stride == statistics_size ? statistics_counters : 1u); ++j) {
116 word(b, off + i * stride + word_size * j, q[first + i][j]);
117 }
118 }
119 events.push_back("query_copy");
120 }
121
122 void fill(VkBuffer b, VkDeviceSize off, VkDeviceSize n, unsigned value) {
123 auto& v = bytes(b, off, n);
124 for (VkDeviceSize i = 0; i < n; i += sizeof(value)) {
125 std::memcpy(v.data() + off + i, &value, sizeof(value));
126 }
127 events.push_back("fill");
128 }
129
130 void copy(VkBuffer a, VkBuffer b, const VkBufferCopy& c) {
131 auto& av = bytes(a, c.srcOffset, c.size);
132 auto& bv = bytes(b, c.dstOffset, c.size);
133 std::memmove(bv.data() + c.dstOffset, av.data() + c.srcOffset, c.size);
134 transfers.push_back(c);
135 }
136
137 ReplayFunctions replay_functions() {
138 ReplayFunctions v{};
139 v.reset_query_pool = +[](VkCommandBuffer, VkQueryPool p, unsigned first, unsigned count) {
140 auto& c = *current;
141 expect(first <= c.values.at(p).size() && count <= c.values.at(p).size() - first, "reset query bounds");
142 for (unsigned i = 0; i < count; ++i) {
143 expect(!c.active[p].count(first + i), "reset active query");
144 c.values[p][first + i] = {};
145 c.resets.emplace_back(p, first + i);
146 }
147 };
148 v.begin_query = +[](VkCommandBuffer, VkQueryPool p, unsigned i, VkQueryControlFlags) {
149 expect(current->active[p].empty(), "overlapping physical query");
150 current->active[p].insert(i);
151 current->events.push_back("begin_query");
152 };
153 v.end_query = +[](VkCommandBuffer, VkQueryPool p, unsigned i) {
154 expect(current->active[p].erase(i) == 1, "end inactive query");
155 for (unsigned j = 0; j < statistics_counters; ++j) {
156 current->values.at(p).at(i)[j] = ++current->serial + j;
157 }
158 current->events.push_back("end_query");
159 };
160 v.write_timestamp = +[](VkCommandBuffer, VkPipelineStageFlagBits, VkQueryPool p, unsigned i) {
161 current->values.at(p).at(i)[0] = ++current->serial;
162 };
163 v.copy_query_pool_results = +[](VkCommandBuffer, VkQueryPool p, unsigned first, unsigned count, VkBuffer b,
164 VkDeviceSize off, VkDeviceSize stride, VkQueryResultFlags flags) {
165 current->query(p, first, count, b, off, stride, flags);
166 };
167 v.fill_buffer = +[](VkCommandBuffer, VkBuffer b, VkDeviceSize off, VkDeviceSize n, unsigned value) {
168 expect(!current->conditional, "resolve fill inside predicate");
169 current->fill(b, off, n, value);
170 };
171 v.copy_buffer = +[](VkCommandBuffer, VkBuffer a, VkBuffer b, unsigned n, const VkBufferCopy* copies) {
172 ++current->native_copies;
173 for (unsigned i = 0; i < n; ++i) {
174 current->copy(a, b, copies[i]);
175 }
176 current->events.push_back("native_copy");
177 };
178 // Capability entries are never called in buffer-only tests.
179 v.copy_buffer_to_image = +[](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout, unsigned,
180 const VkBufferImageCopy*) {
181 expect(false, "unexpected image copy");
182 };
183 v.copy_image_to_buffer = +[](VkCommandBuffer, VkImage, VkImageLayout, VkBuffer, unsigned,
184 const VkBufferImageCopy*) {
185 expect(false, "unexpected image copy");
186 };
187 v.copy_image = +[](VkCommandBuffer, VkImage, VkImageLayout, VkImage, VkImageLayout, unsigned,
188 const VkImageCopy*) {
189 expect(false, "unexpected image copy");
190 };
191 v.begin_conditional_rendering = +[](VkCommandBuffer, const VkConditionalRenderingBeginInfoEXT* info) {
192 auto& c = *current;
193 expect(!c.conditional, "nested predicate");
194 c.conditional = true;
195 c.execute = (c.snapshot != 0);
196 if (info->flags & VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT) {
197 c.execute = !c.execute;
198 }
199 c.events.push_back("begin_cond");
200 };
201 v.end_conditional_rendering = +[](VkCommandBuffer) {
202 expect(current->conditional, "end missing predicate");
203 current->conditional = false;
204 current->events.push_back("end_cond");
205 };
206 v.prepare_predicate = [](VkBuffer b, VkDeviceSize off, PredicateCapture& out) {
207 out = {b, off, handle<VkBuffer>(99), 0, handle<VkDescriptorSet>(99)};
208 return true;
209 };
210 v.capture_predicate = [](VkCommandBuffer, const PredicateCapture& p) {
211 expect(!current->conditional, "predicated capture");
212 current->snapshot = current->word(p.source, p.source_offset);
213 ++current->captures;
214 current->events.push_back("capture");
215 };
216 auto helper = [](bool stats, bool binary, VkQueryPool p, unsigned first, unsigned count, VkBuffer dst,
217 VkDeviceSize off) {
218 auto& c = *current;
219 expect(!c.conditional, "predicated resolve helper");
220 c.events.push_back("helper");
221 for (auto pool : c.statistics_pools) {
222 expect(c.active[pool].empty(), "resolve helper pollutes active pipeline-statistics query");
223 }
224 if (binary) {
225 for (unsigned i = 0; i < count; ++i) {
226 c.word(dst, off + word_size * i, c.values.at(p).at(first + i)[0] != 0);
227 }
228 } else {
229 for (unsigned j = 0; j < (stats ? statistics_counters : 1u); ++j) {
230 std::uint64_t total = 0;
231 for (unsigned i = 0; i < count; ++i) {
232 total += c.values.at(p).at(first + i)[j];
233 }
234 c.word(dst, off + word_size * j, total);
235 }
236 }
237 };
238 v.sum_occlusion = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b,
239 VkDeviceSize off) {
240 helper(false, false, p, f, n, b, off);
241 };
242 v.sum_statistics = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b,
243 VkDeviceSize off) {
244 helper(true, false, p, f, n, b, off);
245 };
246 v.resolve_binary_occlusion = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b,
247 VkDeviceSize off) {
248 helper(false, true, p, f, n, b, off);
249 };
250 return v;
251 }
252};
253
254inline std::shared_ptr<OcclusionSegmentPool> make_segment_pool(unsigned id) {
255 auto p = std::make_shared<OcclusionSegmentPool>();
256 p->pool = handle<VkQueryPool>(id);
257 p->destroy = +[](VkDevice, VkQueryPool, const VkAllocationCallbacks*) {};
258 return p;
259}
260
261void test_helper_chunks() {
262 constexpr unsigned first_query = 7;
263 constexpr VkDeviceSize arena_offset = 40;
264 constexpr VkDeviceSize resolve_offset = 24;
265 constexpr VkDeviceSize output_offset = arena_offset + resolve_offset;
266 constexpr unsigned buffer_bytes = 10000;
267 constexpr std::uint64_t reset_sum = 3;
268 constexpr std::uint64_t reset_counter = 9;
269
270 MockReplay c;
271 VulkanDeviceFunctions vk{};
272 vk.vkCmdFillBuffer = +[](VkCommandBuffer, VkBuffer b, VkDeviceSize off, VkDeviceSize n, unsigned value) {
273 MockReplay::current->fill(b, off, n, value);
274 };
275 vk.vkCmdCopyQueryPoolResults = +[](VkCommandBuffer, VkQueryPool p, unsigned first, unsigned count, VkBuffer b,
276 VkDeviceSize off, VkDeviceSize stride, VkQueryResultFlags flags) {
277 MockReplay::current->query(p, first, count, b, off, stride, flags);
278 };
279 vk.vkCmdCopyBuffer = +[](VkCommandBuffer, VkBuffer a, VkBuffer b, unsigned n, const VkBufferCopy* copies) {
280 for (unsigned i = 0; i < n; ++i) {
281 MockReplay::current->copy(a, b, copies[i]);
282 }
283 };
284 vk.vkCmdBindPipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {};
285 vk.vkCmdBindDescriptorSets = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipelineLayout, unsigned, unsigned,
286 const VkDescriptorSet*, unsigned, const unsigned*) {};
287 vk.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, unsigned off, unsigned size,
288 const void*p) {
289 expect(off == 0 && size == sizeof(unsigned), "chunk push constants");
290 MockReplay::current->chunks.push_back(*static_cast<const unsigned *>(p));
291 };
292 vk.vkCmdDispatch = +[](VkCommandBuffer, unsigned x, unsigned y, unsigned z) {
293 auto& c = *MockReplay::current;
294 c.groups.push_back(x);
295 expect(y == 1 && z == 1, "dispatch dimensions");
296 auto n = c.chunks.back();
297 if (c.mode == MockReplay::binary) {
298 for (unsigned i = 0; i < n; ++i) {
299 c.word(VK_NULL_HANDLE, word_size * i, c.word(VK_NULL_HANDLE, word_size * i) != 0);
300 }
301 } else {
302 for (unsigned j = 0; j < (c.mode == MockReplay::statistics ? statistics_counters : 1u); ++j) {
303 unsigned width = c.mode == MockReplay::statistics ? statistics_counters : 1;
304 auto total = c.word(VK_NULL_HANDLE, word_size * j);
305 for (unsigned i = 0; i < n; ++i) {
306 total += c.word(VK_NULL_HANDLE, word_size * (width * (i + 1) + j));
307 }
308 c.word(VK_NULL_HANDLE, word_size * j, total);
309 }
310 }
311 };
312 vk.vkCmdPipelineBarrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags,
313 unsigned, const VkMemoryBarrier*, unsigned n, const VkBufferMemoryBarrier* b, unsigned,
314 const VkImageMemoryBarrier*) {
315 expect(n == 1 && b->offset == 0 && b->size == scratch_size, "scratch barrier covers the shared scratch buffer");
316 };
317 OcclusionResolve helper(vk, VK_NULL_HANDLE);
318 auto qp = handle<VkQueryPool>(1);
319 auto dst = handle<VkBuffer>(2);
320 for (auto mode : {MockReplay::sum, MockReplay::binary, MockReplay::statistics}) {
321 for (unsigned extra : {0u, 1u}) {
322 c.mode = mode;
323 const unsigned capacity = mode == MockReplay::sum ? sum_capacity
324 : mode == MockReplay::binary ? binary_capacity
325 : statistics_capacity;
326 const unsigned n = capacity + extra;
327 const unsigned first = first_query;
328 const unsigned width = mode == MockReplay::statistics ? statistics_counters : 1;
329 c.values[qp].resize(first + n);
330 for (unsigned i = 0; i < first + n; ++i) {
331 for (unsigned j = 0; j < statistics_counters; ++j) {
332 c.values[qp][i][j] = i % 3 == 0 ? 0 : (UINT64_C(1) << 32) + i * 17 + j;
333 }
334 }
335 c.buffers[dst].assign(buffer_bytes, guard_byte);
336 auto expected = c.buffers[dst];
337 c.copies.clear();
338 c.chunks.clear();
339 c.groups.clear();
340 c.transfers.clear();
341 if (mode == MockReplay::binary) {
342 helper.normalize({}, qp, first, n, dst, output_offset);
343 for (unsigned i = 0; i < n; ++i) {
344 std::uint64_t v = c.values[qp][first + i][0] != 0;
345 std::memcpy(expected.data() + output_offset + word_size * i, &v, word_size);
346 }
347 } else {
348 if (mode == MockReplay::statistics) {
349 helper.sum_statistics({}, qp, first, n, dst, output_offset);
350 } else {
351 helper.sum({}, qp, first, n, dst, output_offset);
352 }
353 for (unsigned j = 0; j < width; ++j) {
354 std::uint64_t v = 0;
355 for (unsigned i = 0; i < n; ++i) {
356 v += c.values[qp][first + i][j];
357 }
358 std::memcpy(expected.data() + output_offset + word_size * j, &v, word_size);
359 }
360 }
361 expect(c.buffers[dst] == expected, "numeric helper result and destination guard bytes");
362 expect(c.chunks == (extra ? std::vector<unsigned>{capacity, 1}
363 : std::vector<unsigned>{capacity}), "exact chunk sizes");
364 expect(c.copies.size() == 1 + extra && c.copies[0].first == first && (!extra
365 || c.copies[1].first == first + capacity), "chunk query indices end exactly at heap boundary");
366 std::vector<unsigned> expected_groups(1 + extra, 1);
367 if (mode == MockReplay::binary) {
368 expected_groups[0] = binary_capacity / binary_group_size;
369 }
370 expect(c.groups == expected_groups, "dispatch workgroup counts");
371 if (mode == MockReplay::binary) {
372 expect(c.transfers.size() == 1 + extra && (!extra
373 || c.transfers[1].dstOffset == output_offset + word_size * capacity),
374 "binary second output chunk offset");
375 } else {
376 expect(c.transfers.size() == 1 && c.transfers[0].size == word_size * width,
377 "sum copies only the final accumulator");
378 }
379 }
380 }
381
382 // A previous call must not leave stale accumulator state in the next call.
383 c.mode = MockReplay::sum;
384 c.values[qp][first_query][0] = reset_sum;
385 helper.sum({}, qp, first_query, 1, dst, output_offset);
386 expect(c.word(dst, output_offset) == reset_sum, "sum accumulator reset between calls");
387 c.mode = MockReplay::statistics;
388 c.values[qp][first_query].fill(reset_counter);
389 helper.sum_statistics({}, qp, first_query, 1, dst, output_offset);
390 for (unsigned j = 0; j < statistics_counters; ++j) {
391 expect(c.word(dst, output_offset + word_size * j) == reset_counter, "statistics accumulator reset");
392 }
393}
394
395void test_query_state() {
396 constexpr unsigned heap_count = 4;
397 constexpr unsigned overlap_segments = 3;
398 constexpr unsigned split_statistics_segments = 5;
399 constexpr unsigned mixed_statistics_segments = 4;
400 constexpr VkDeviceSize arena_offset = 40;
401 constexpr VkDeviceSize boundary_offset = 24;
402 constexpr VkDeviceSize buffer_bytes = 4200;
403 constexpr VkDeviceSize resource_bytes = 4096;
404 constexpr VkDeviceSize reused_offset = 16;
405 constexpr VkDeviceSize repeated_offset = 128;
406 constexpr VkDeviceSize overwrite_offset = 144;
407 constexpr VkDeviceSize zero_offset = 200;
408 constexpr VkDeviceSize statistics_offset = 256;
409 constexpr VkDeviceSize later_statistics_offset = 512;
410 constexpr VkDeviceSize inner_statistics_offset = 768;
411 constexpr VkDeviceSize binary_offset = 864;
412 constexpr VkDeviceSize timestamp_offset = 880;
413 constexpr VkDeviceSize sum_offset = 896;
414 constexpr VkDeviceSize mixed_statistics_offset = 1024;
415 constexpr std::uint64_t first_saved_count = 17;
416 constexpr std::uint64_t second_saved_count = 23;
417
418 MockReplay c;
419 auto vk = c.replay_functions();
420 ResourceBinding dst{};
421 dst.buffer = handle<VkBuffer>(1);
422 dst.buffer_offset = arena_offset;
423 dst.size = resource_bytes;
424 dst.host_readable = true;
425 c.buffers[dst.buffer].assign(buffer_bytes, guard_byte);
426 auto resource = [&](ResourceId id) -> const ResourceBinding* {
427 return id == 1 ? &dst : nullptr;
428 };
429 QueryPool heap{handle<VkQueryPool>(2), d3d12_query_heap::occlusion, heap_count, true,
430 std::vector<bool>(heap_count), {}};
431 QueryPool stat{handle<VkQueryPool>(3), d3d12_query_heap::pipeline_statistics, heap_count, false,
432 std::vector<bool>(heap_count), {}};
433 QueryPool time{handle<VkQueryPool>(4), d3d12_query_heap::timestamp, heap_count, false,
434 std::vector<bool>(heap_count), {}};
435 for (auto p : {heap.pool, stat.pool, time.pool}) {
436 c.values[p].resize(heap_count);
437 }
438 vk.query_pool = [&](QueryHeapId id) -> QueryPool* {
439 return id == 1 ? &heap : id == 2 ? &stat : id == 3 ? &time : nullptr;
440 };
441 auto prep = [&](CommandList& list, PreparedList& out) {
442 expect(list.close(), "close query list");
443 expect(prepare(list, resource, vk, out) == ReplayResult::success, "prepare query list");
444 };
445
446 // Inclusive final slot / exclusive heap end, for every supported resolve result width.
447 for (auto type : {d3d12_query::occlusion, d3d12_query::binary_occlusion, d3d12_query::timestamp,
448 d3d12_query::pipeline_statistics}) {
449 unsigned id = type == d3d12_query::timestamp ? 3 : type == d3d12_query::pipeline_statistics ? 2 : 1;
450 auto* hp = vk.query_pool(id);
451 hp->ended = {false, false, true, true};
452 for (unsigned i = 2; i < heap_count; ++i) {
453 for (unsigned j = 0; j < statistics_counters; ++j) {
454 c.values[hp->pool][i][j] = (UINT64_C(1) << 32) + 100 * i + j;
455 }
456 }
457 auto size = query_result_size(type);
458 for (unsigned count : {1u, 2u}) {
459 CommandList list;
460 expect(list.resolve_queries({id, type, heap_count - count, count, 1, boundary_offset}),
461 "record boundary resolve");
462 PreparedList out;
463 dst.size = boundary_offset + size * count;
464 c.buffers[dst.buffer].assign(buffer_bytes, guard_byte);
465 auto expected = c.buffers[dst.buffer];
466 prep(list, out);
467 QueryReplay q;
468 expect(q.plan(out, {}, 0, true) == ReplayResult::success, "plan boundary");
469 emit(out, {}, vk);
470 for (unsigned i = 0; i < count; ++i) {
471 for (unsigned j = 0; j < size / word_size; ++j) {
472 const auto v = type == d3d12_query::binary_occlusion
473 ? UINT64_C(1)
474 : c.values[hp->pool][heap_count - count + i][j];
475 std::memcpy(expected.data() + arena_offset + boundary_offset + size * i + word_size * j, &v,
476 word_size);
477 }
478 }
479 expect(c.buffers[dst.buffer] == expected, "heap-end resolve numeric values, arena offset and guards");
480 expect(out.wrote_readback, "query resolve readback visibility");
481 }
482 CommandList bad;
483 expect(bad.resolve_queries({id, type, heap_count - 1, 2, 1, 0}) && bad.close(), "record one-past heap end");
484 PreparedList invalid;
485 expect(prepare(bad, resource, vk, invalid) == ReplayResult::invalid_query, "reject one-past heap range");
486 CommandList short_dst;
487 expect(short_dst.resolve_queries({id, type, heap_count - 1, 1, 1, boundary_offset}) && short_dst.close(),
488 "record short destination");
489 dst.size = boundary_offset + size - 1;
490 expect(prepare(short_dst, resource, vk, invalid) == ReplayResult::invalid_query,
491 "reject destination one byte short");
492 }
493 dst.size = resource_bytes;
494 heap.ended.assign(heap_count, false);
495 heap.occlusion.clear();
496
497 // Plan three lists as VulkanQueue::execute does, before any emission or commit.
498 CommandList a, b, d;
499 PreparedList pa, pb, pd;
500 expect(a.begin_query({1, d3d12_query::occlusion, 0}) && a.begin_query({1, d3d12_query::occlusion, 1})
501 && a.end_query({1, d3d12_query::occlusion, 0}) && a.end_query({1, d3d12_query::occlusion, 1}),
502 "record overlap");
503 expect(b.resolve_queries({1, d3d12_query::occlusion, 0, 2, 1, 0}) && b.begin_query({1, d3d12_query::occlusion,
504 0}) && b.end_query({1, d3d12_query::occlusion, 0}) && b.resolve_queries({1, d3d12_query::occlusion, 0, 1,
505 1, reused_offset}), "record reuse after resolve");
506 expect(d.resolve_queries({1, d3d12_query::occlusion, 0, 2, 1, boundary_offset}), "record third list resolve");
507 prep(a, pa);
508 prep(b, pb);
509 prep(d, pd);
510 expect(pa.segment_count == overlap_segments && pb.segment_count == 0 && pd.segment_count == 0,
511 "queue needs exactly three physical occlusion slots");
512 auto physical = make_segment_pool(10);
513 c.values[physical->pool].resize(overlap_segments);
514 std::weak_ptr<const OcclusionSegmentPool> alive = physical;
515 QueryReplay batch;
516 unsigned base = 0;
517 for (auto* p : {&pa, &pb, &pd}) {
518 expect(batch.plan(*p, physical, base, true) == ReplayResult::success, "plan multi-list batch");
519 base += p->segment_count;
520 }
521 expect(heap.occlusion.empty() && !heap.ended[0] && !heap.ended[1],
522 "planning does not publish results before commit");
523 emit(pa, {}, vk);
524 auto old0 = c.values[physical->pool][0][0] + c.values[physical->pool][1][0];
525 auto old1 = c.values[physical->pool][1][0] + c.values[physical->pool][2][0];
526 emit(pb, {}, vk);
527 auto new0 = c.values[heap.pool][0][0];
528 emit(pd, {}, vk);
529 expect(c.word(dst.buffer, arena_offset) == old0 && c.word(dst.buffer, arena_offset + word_size) == old1
530 && c.word(dst.buffer, arena_offset + reused_offset) == new0 && c.word(dst.buffer,
531 arena_offset + boundary_offset) == new0 && c.word(dst.buffer,
532 arena_offset + boundary_offset + word_size) == old1,
533 "pending results, resolve preservation and slot reuse across three lists");
534 batch.commit();
535 expect(heap.ended[0] && heap.ended[1] && !heap.occlusion.count(0) && heap.occlusion.at(1).count == 2,
536 "commit replaces reused slot metadata only");
537 physical.reset();
538 batch.retained.clear();
539 expect(!alive.expired(), "heap retains segment pool after submission owner releases it");
540 for (unsigned submission = 0; submission < 3; ++submission) {
541 CommandList list;
542 PreparedList p;
543 expect(list.resolve_queries({1, d3d12_query::occlusion, 0, 2, 1, repeated_offset}), "record later resolve");
544 prep(list, p);
545 QueryReplay q;
546 expect(q.plan(p, {}, 0, true) == ReplayResult::success, "plan later submission");
547 emit(p, {}, vk);
548 q.commit();
549 expect(c.word(dst.buffer, arena_offset + repeated_offset) == new0 && c.word(dst.buffer,
550 arena_offset + repeated_offset + word_size) == old1, "repeat resolve across submissions");
551 }
552 CommandList overwrite;
553 PreparedList po;
554 expect(overwrite.begin_query({1, d3d12_query::occlusion, 1}) && overwrite.end_query({1, d3d12_query::occlusion,
555 1}) && overwrite.resolve_queries({1, d3d12_query::occlusion, 1, 1, 1, overwrite_offset}),
556 "record last segment overwrite");
557 prep(overwrite, po);
558 {
559 QueryReplay q;
560 expect(q.plan(po, {}, 0, true) == ReplayResult::success, "plan native replacement");
561 emit(po, {}, vk);
562 q.commit();
563 expect(!heap.occlusion.count(1) && c.word(dst.buffer,
564 arena_offset + overwrite_offset) == c.values[heap.pool][1][0],
565 "native result replaces last virtual result");
566 }
567 expect(alive.expired(), "last heap overwrite releases old segment pool");
568
569 // Statistics pool size/base accumulation across two split lists; resolve during statistics must not count helpers.
570 heap.ended[3] = false;
571 CommandList s0, s1;
572 PreparedList ps0, ps1;
573 for (unsigned index = 0; index < 2; ++index) {
574 auto& list = index ? s1 : s0;
575 expect(list.begin_query({2, d3d12_query::pipeline_statistics, index}), "statistics begin");
576 for (unsigned i = 0; i <= index; ++i) {
577 expect(list.resolve_queries({1, d3d12_query::occlusion, 3, 1, 1, zero_offset}), "inner zero-fill resolve");
578 }
579 expect(list.resolve_queries({1, d3d12_query::occlusion, heap_count, 0, 1, 0}), "zero-count resolve at heap end");
580 expect(list.end_query({2, d3d12_query::pipeline_statistics, index}) && list.resolve_queries({2,
581 d3d12_query::pipeline_statistics, index, 1, 1, statistics_offset + statistics_size * index}),
582 "statistics end and resolve");
583 }
584 prep(s0, ps0);
585 prep(s1, ps1);
586 expect(ps0.statistics_segment_count == 2 && ps1.statistics_segment_count == 3,
587 "zero-count resolves allocate no statistics segment");
588 auto sp = make_segment_pool(11);
589 c.values[sp->pool].resize(split_statistics_segments);
590 c.statistics_pools.insert(sp->pool);
591 QueryReplay stats;
592 unsigned sb = 0;
593 for (auto* p : {&ps0, &ps1}) {
594 expect(stats.plan(*p, {}, 0, true, sp, sb) == ReplayResult::success, "plan split statistics lists");
595 sb += p->statistics_segment_count;
596 }
597 emit(ps0, {}, vk);
598 emit(ps1, {}, vk);
599 stats.commit();
600 expect(stat.occlusion.at(0).first == 0 && stat.occlusion.at(1).first == 2 && sb == split_statistics_segments,
601 "queue statistics pool sizing and disjoint bases");
602 for (unsigned i = 0; i < 2; ++i) {
603 for (unsigned j = 0; j < statistics_counters; ++j) {
604 std::uint64_t total = 0;
605 auto r = stat.occlusion.at(i);
606 for (unsigned k = 0; k < r.count; ++k) {
607 total += c.values[sp->pool][r.first + k][j];
608 }
609 expect(c.word(dst.buffer,
610 arena_offset + statistics_offset + statistics_size * i + word_size * j) == total,
611 "all 11 split statistics counters");
612 }
613 }
614
615 // No segment ownership is needed on the next submission: heap metadata carries it.
616 CommandList later;
617 PreparedList pl;
618 expect(later.resolve_queries({2, d3d12_query::pipeline_statistics, 0, 2, 1, later_statistics_offset}),
619 "later statistics resolve");
620 prep(later, pl);
621 QueryReplay later_batch;
622 expect(later_batch.plan(pl, {}, 0, true) == ReplayResult::success && later_batch.needs_statistics_sum,
623 "later statistics helper selection");
624 emit(pl, {}, vk);
625 for (unsigned i = 0; i < (2 * statistics_size); i += word_size) {
626 expect(c.word(dst.buffer, arena_offset + later_statistics_offset + i) == c.word(dst.buffer,
627 arena_offset + statistics_offset + i), "statistics persist after commit");
628 }
629
630 // Mixed helper types inside one statistics scope, including a timestamp copy that must not split it.
631 auto saved = make_segment_pool(12);
632 c.values[saved->pool].resize(2);
633 c.values[saved->pool][0][0] = 17;
634 c.values[saved->pool][1][0] = 23;
635 heap.occlusion[2] = {saved, 0, 2};
636 heap.ended[2] = true;
637 CommandList mixed;
638 PreparedList pm;
639 expect(mixed.begin_query({2, d3d12_query::pipeline_statistics, 2}) && mixed.resolve_queries({2,
640 d3d12_query::pipeline_statistics, 0, 1, 1, inner_statistics_offset}) && mixed.resolve_queries({1,
641 d3d12_query::binary_occlusion, 0, 1, 1, binary_offset}) && mixed.resolve_queries({3,
642 d3d12_query::timestamp, 3, 1, 1, timestamp_offset}) && mixed.resolve_queries({1, d3d12_query::occlusion,
643 2, 1, 1, sum_offset}) && mixed.end_query({2, d3d12_query::pipeline_statistics, 2})
644 && mixed.resolve_queries({2, d3d12_query::pipeline_statistics, 2, 1, 1, mixed_statistics_offset}),
645 "mixed helpers inside statistics");
646 prep(mixed, pm);
647 expect(pm.statistics_segment_count == mixed_statistics_segments, "only three non-timestamp resolves split statistics");
648 auto mixed_pool = make_segment_pool(13);
649 c.values[mixed_pool->pool].resize(mixed_statistics_segments);
650 c.statistics_pools.insert(mixed_pool->pool);
651 QueryReplay mixed_batch;
652 expect(mixed_batch.plan(pm, {}, 0, true, mixed_pool) == ReplayResult::success && mixed_batch.needs_sum
653 && mixed_batch.needs_binary && mixed_batch.needs_statistics_sum, "mixed helper selection");
654 emit(pm, {}, vk);
655 mixed_batch.commit();
656 expect(c.word(dst.buffer, arena_offset + sum_offset) == first_saved_count + second_saved_count
657 && c.word(dst.buffer, arena_offset + binary_offset) == 1,
658 "ordinary sum and binary results inside statistics");
659 for (unsigned j = 0; j < statistics_counters; ++j) {
660 std::uint64_t total = 0;
661 for (unsigned k = 0; k < mixed_statistics_segments; ++k) {
662 total += c.values[mixed_pool->pool][k][j];
663 }
664 expect(c.word(dst.buffer, arena_offset + mixed_statistics_offset + word_size * j) == total,
665 "mixed statistics sum");
666 expect(c.word(dst.buffer, arena_offset + inner_statistics_offset + word_size * j) == c.word(dst.buffer,
667 arena_offset + statistics_offset + word_size * j), "previous statistics sum inside a new scope");
668 }
669}
670
671void test_predicated_copies() {
672 constexpr VkDeviceSize source_arena = 32;
673 constexpr VkDeviceSize destination_arena = 40;
674 constexpr VkDeviceSize predicate_arena = 24;
675 constexpr VkDeviceSize predicate_offset = word_size;
676 constexpr VkDeviceSize predicate_address = predicate_arena + predicate_offset;
677 constexpr unsigned resource_bytes = 128;
678 constexpr unsigned backing_bytes = 200;
679 constexpr unsigned predicate_backing_bytes = 64;
680 constexpr unsigned copy_source = 9;
681 constexpr unsigned copy_bytes = 7;
682 constexpr unsigned cleared_offset = 8;
683 constexpr unsigned resolved_offset = 16;
684 constexpr unsigned snapshot_offset = 24;
685 constexpr unsigned skipped_offset = 32;
686 constexpr unsigned inverted_offset = 40;
687 constexpr unsigned second_cleared_offset = 48;
688 constexpr unsigned next_list_offset = 56;
689 constexpr unsigned high_word_offset = 65;
690 constexpr unsigned high_word_source = 11;
691 constexpr std::uint32_t invalid_operation = 999;
692
693 MockReplay c;
694 auto vk = c.replay_functions();
695 ResourceBinding src{}, dst{}, pred{};
696 src.buffer = handle<VkBuffer>(1);
697 src.buffer_offset = source_arena;
698 src.size = resource_bytes;
699 dst.buffer = handle<VkBuffer>(2);
700 dst.buffer_offset = destination_arena;
701 dst.size = resource_bytes;
702 dst.host_readable = true;
703 pred.buffer = handle<VkBuffer>(3);
704 pred.buffer_offset = predicate_arena;
705 pred.size = 2 * word_size;
706 c.buffers[src.buffer].resize(backing_bytes);
707 for (unsigned i = 0; i < backing_bytes; ++i) {
708 c.buffers[src.buffer][i] = static_cast<unsigned char>(i);
709 }
710 c.word(src.buffer, source_arena, 0);
711 c.buffers[dst.buffer].assign(backing_bytes, guard_byte);
712 auto expected = c.buffers[dst.buffer];
713 c.buffers[pred.buffer].assign(predicate_backing_bytes, guard_byte);
714 c.word(pred.buffer, predicate_address, 0);
715 QueryPool heap{handle<VkQueryPool>(4), d3d12_query_heap::occlusion, 1, false, {true}, {}};
716 c.values[heap.pool].resize(1);
717 c.values[heap.pool][0][0] = UINT64_C(1) << 40;
718 vk.query_pool = [&](QueryHeapId id) -> QueryPool* {
719 return id == 1 ? &heap : nullptr;
720 };
721 auto resources = [&](ResourceId id) -> const ResourceBinding* {
722 return id == 1 ? &src : id == 2 ? &dst : id == 3 ? &pred : nullptr;
723 };
724 struct Job {
725 VkBuffer a, b;
726 VkBufferCopy copy;
727 };
728 std::vector<Job> jobs;
729 vk.prepare_predicated_copy = [&](VkBuffer a, VkBuffer b, VkDeviceSize so, VkDeviceSize d, VkDeviceSize n,
730 std::vector<PredicatedCopyDispatch>& out) {
731 jobs.push_back({a, b, {so, d, n}});
732 out.push_back({handle<VkDescriptorSet>(jobs.size()), 0, 0, static_cast<unsigned>(n)});
733 return true;
734 };
735 vk.emit_predicated_copy = [&](VkCommandBuffer, const std::vector<PredicatedCopyDispatch>& out) {
736 expect(c.conditional, "predicated copy outside scope");
737 ++c.pred_copies;
738 c.events.push_back("pred_copy");
739 for (auto& p : out) {
740 auto& job = jobs.at(reinterpret_cast<std::uintptr_t>(p.set) - 1);
741 if (c.execute) {
742 c.copy(job.a, job.b, job.copy);
743 }
744 }
745 };
746 auto expect_copy = [&](unsigned dest, unsigned source, unsigned n) {
747 std::memcpy(expected.data() + destination_arena + dest,
748 c.buffers[src.buffer].data() + source_arena + source, n);
749 };
750 CommandList list;
751 expect(list.set_predication({3, predicate_offset, d3d12_predication::equal_zero}) && list.copy_buffer({2, 0, 1,
752 copy_source, copy_bytes}), "record skipped copy");
753 expect(list.resolve_queries({1, d3d12_query::binary_occlusion, 0, 1, 3, predicate_offset})
754 && list.copy_buffer({2, 0, 1, copy_source, copy_bytes}),
755 "resolve into active predicate then copy without recapture");
756 expect(list.set_predication({0, UINT64_MAX, UINT32_MAX}) && list.copy_buffer({2, cleared_offset, 1, copy_source,
757 copy_bytes}), "clear predicate ignores invalid offset/op");
758 expect_copy(cleared_offset, copy_source, copy_bytes);
759 expect(list.set_predication({3, predicate_offset, d3d12_predication::equal_zero}) && list.copy_buffer({2,
760 resolved_offset, 1, copy_source, copy_bytes}), "recapture resolved nonzero");
761 expect_copy(resolved_offset, copy_source, copy_bytes);
762 expect(list.copy_buffer({3, predicate_offset, 1, 0, word_size}) && list.copy_buffer({2, snapshot_offset, 1,
763 copy_source, copy_bytes}), "overwrite predicate without recapture");
764 expect_copy(snapshot_offset, copy_source, copy_bytes);
765 expect(list.set_predication({3, predicate_offset, d3d12_predication::equal_zero}) && list.copy_buffer({2,
766 skipped_offset, 1, copy_source, copy_bytes}), "recapture zero skips");
767 expect(list.set_predication({3, predicate_offset, d3d12_predication::not_equal_zero}) && list.copy_buffer({2,
768 inverted_offset, 1, copy_source, copy_bytes}), "inverted zero executes");
769 expect_copy(inverted_offset, copy_source, copy_bytes);
770 expect(list.set_predication({0, 7, invalid_operation}) && list.copy_buffer({2, second_cleared_offset, 1,
771 copy_source, copy_bytes}), "clear then native copy");
772 expect_copy(second_cleared_offset, copy_source, copy_bytes);
773 expect(list.set_predication({3, predicate_offset, d3d12_predication::equal_zero}) && list.copy_buffer({2,
774 resource_bytes, 1, resource_bytes, 0}) && list.close(), "zero-length copy at buffer end while predicated");
775 PreparedList p;
776 expect(prepare(list, resources, vk, p) == ReplayResult::success, "prepare mixed list");
777 expect(p.unpredicated_copies == 0, "buffer copies never counted as unsupported predication fallback");
778 expect(p.readback_src_stages == (VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_2_COPY_BIT),
779 "mixed readback producers");
780 QueryReplay q;
781 expect(q.plan(p, {}, 0, true) == ReplayResult::success, "plan resolve into predicate");
782 emit(p, {}, vk);
783 q.commit();
784 expect(c.buffers[dst.buffer] == expected, "all copied/skipped bytes and guards match independent oracle");
785 expect(c.word(pred.buffer, predicate_address) == 0, "predicate overwrite executes");
786 expect(c.captures == 5 && c.pred_copies == 7 && c.native_copies == 2 && !c.conditional,
787 "capture/copy counts; no zero-byte dispatch; final scope balanced");
788 auto expected_pred = std::vector<unsigned char>(predicate_backing_bytes, guard_byte);
789 std::uint64_t zero = 0;
790 std::memcpy(expected_pred.data() + predicate_address, &zero, word_size);
791 expect(c.buffers[pred.buffer] == expected_pred, "predicate-buffer arena guards");
792 CommandList next;
793 expect(next.copy_buffer({2, next_list_offset, 1, copy_source, copy_bytes}) && next.close(),
794 "next list starts unpredicated");
795 expect(replay(next, {}, resources, vk) == ReplayResult::success, "replay next list");
796 expect_copy(next_list_offset, copy_source, copy_bytes);
797 expect(c.buffers[dst.buffer] == expected && c.native_copies == 3, "predication does not leak to next list");
798 c.word(pred.buffer, predicate_address, UINT64_C(1) << 40);
799 CommandList high;
800 expect(high.set_predication({3, predicate_offset, d3d12_predication::equal_zero}) && high.copy_buffer({2,
801 high_word_offset, 1, high_word_source, copy_bytes}) && high.close(), "high-word-only predicate");
802 expect(replay(high, {}, resources, vk) == ReplayResult::success, "replay high-word predicate");
803 expect_copy(high_word_offset, high_word_source, copy_bytes);
804 expect(c.buffers[dst.buffer] == expected, "full 64-bit predicate and unaligned copy offsets");
805
806 // Recording-time controls; false returns must not mutate active query state.
807 CommandList validation;
808 expect(!validation.begin_query({1, d3d12_query::timestamp, 0}), "timestamp begin rejected");
809 expect(validation.begin_query({1, d3d12_query::occlusion, 0}), "ordinary begin");
810 expect(!validation.begin_query({1, d3d12_query::occlusion, 0}), "duplicate active slot rejected");
811 expect(!validation.end_query({1, d3d12_query::binary_occlusion, 0}), "mismatched end type rejected");
812 expect(!validation.resolve_queries({1, d3d12_query::occlusion, 0, 1, 2, 0}), "active slot resolve rejected");
813 expect(validation.end_query({1, d3d12_query::occlusion, 0}), "rejected operations preserve matching end");
814 expect(validation.begin_query({1, d3d12_query::occlusion, 0}) && validation.end_query({1,
815 d3d12_query::occlusion, 0}), "same-list slot reuse");
816 expect(!validation.resolve_queries({1, d3d12_query::occlusion, UINT32_MAX, 2, 2, 0}),
817 "overflowing query range rejected");
818 expect(!validation.resolve_queries({1, d3d12_query::occlusion, 0, 1, 2, 1}), "unaligned resolve offset rejected");
819 expect(!validation.set_predication({3, 1, 0}) && !validation.set_predication({3, 0, invalid_operation}),
820 "invalid nonnull predicate rejected");
821 auto n = validation.commands().size();
822 expect(validation.resolve_queries({1, d3d12_query::occlusion, 1, 0, 2, 0}) && validation.copy_buffer({2,
823 UINT64_MAX, 1, UINT64_MAX, 0}) && validation.commands().size() == n, "zero-count commands record no IR");
824 expect(validation.close() && !validation.copy_buffer({2, 0, 1, 0, 0}), "closed list rejects even zero-byte copies");
825 CommandList open;
826 expect(open.begin_query({1, d3d12_query::occlusion, 0}) && open.close(), "close synthetic IR with active query");
827 PreparedList invalid;
828 expect(prepare(open, resources, vk, invalid) == ReplayResult::invalid_query, "replay rejects unended query");
829 pred.size = predicate_offset + word_size - 1;
830 CommandList short_pred;
831 expect(short_pred.set_predication({3, predicate_offset, 0}) && short_pred.close(), "record short predicate");
832 expect(prepare(short_pred, resources, vk, invalid) == ReplayResult::invalid_predication,
833 "all eight predicate bytes required");
834}
835
836VulkanDeviceFunctions driver;
837std::vector<std::pair<VkQueryType, unsigned>> allocations;
838std::set<VkQueryPool> destroyed;
839constexpr unsigned first_pool_id = 100;
840unsigned next_pool = first_pool_id;
841bool fail_submit = false;
842PFN_vkVoidFunction VKAPI_CALL get(VkDevice, const char* name) {
843#define MOCK_DEVICE_FUNCTION(n) \
844 if (std::string_view(name) == #n) { \
845 return reinterpret_cast<PFN_vkVoidFunction>(driver.n); \
846 }
847 LEONIDA_VK_DEVICE_FUNCTIONS(MOCK_DEVICE_FUNCTION)
848#undef MOCK_DEVICE_FUNCTION
849 return nullptr;
850}
851
852void test_queue_segments() {
853 constexpr unsigned list_count = 2;
854 constexpr unsigned overlap_segments = 3;
855 constexpr unsigned occlusion_slots_needed = list_count * overlap_segments;
856 constexpr unsigned statistics_slots_needed = 2 + 3;
857 constexpr unsigned successful_occlusion_pool = first_pool_id + 2;
858 constexpr unsigned successful_statistics_pool = first_pool_id + 3;
859 constexpr VkQueryPipelineStatisticFlags statistics_mask = (1u << statistics_counters) - 1;
860 constexpr VkDeviceSize arena_offset = 24;
861 constexpr VkDeviceSize probe_occlusion_offset = 16;
862 constexpr VkDeviceSize probe_statistics_offset = 32;
863 constexpr unsigned resource_bytes = 128;
864 constexpr unsigned backing_bytes = 160;
865
866 MockReplay c;
867 auto r = c.replay_functions();
868 // Only the entry points used by a query-only queue are supplied. No Vulkan loader is involved.
869 driver.vkCmdResetQueryPool = r.reset_query_pool;
870 driver.vkCmdBeginQuery = r.begin_query;
871 driver.vkCmdEndQuery = r.end_query;
872 driver.vkCmdWriteTimestamp = r.write_timestamp;
873 driver.vkCmdCopyQueryPoolResults = r.copy_query_pool_results;
874 driver.vkCmdFillBuffer = r.fill_buffer;
875 driver.vkCreateCommandPool = +[](VkDevice, const VkCommandPoolCreateInfo*, const VkAllocationCallbacks*,
876 VkCommandPool* p) {
877 *p = handle<VkCommandPool>(1);
878 return VK_SUCCESS;
879 };
880 driver.vkDestroyCommandPool = +[](VkDevice, VkCommandPool, const VkAllocationCallbacks*) {};
881 driver.vkCreateSemaphore = +[](VkDevice, const VkSemaphoreCreateInfo*, const VkAllocationCallbacks*,
882 VkSemaphore* s) {
883 *s = handle<VkSemaphore>(1);
884 return VK_SUCCESS;
885 };
886 driver.vkDestroySemaphore = +[](VkDevice, VkSemaphore, const VkAllocationCallbacks*) {};
887 driver.vkGetSemaphoreCounterValue = +[](VkDevice, VkSemaphore, std::uint64_t* v) {
888 *v = UINT64_MAX;
889 return VK_SUCCESS;
890 };
891 driver.vkQueueWaitIdle = +[](VkQueue) {
892 return VK_SUCCESS;
893 };
894 driver.vkAllocateCommandBuffers = +[](VkDevice, const VkCommandBufferAllocateInfo* info, VkCommandBuffer* b) {
895 expect(info->commandBufferCount == 1, "one command buffer");
896 *b = handle<VkCommandBuffer>(1);
897 return VK_SUCCESS;
898 };
899 driver.vkResetCommandBuffer = +[](VkCommandBuffer, VkCommandBufferResetFlags) {
900 return VK_SUCCESS;
901 };
902 driver.vkBeginCommandBuffer = +[](VkCommandBuffer, const VkCommandBufferBeginInfo*) {
903 return VK_SUCCESS;
904 };
905 driver.vkEndCommandBuffer = +[](VkCommandBuffer) {
906 return VK_SUCCESS;
907 };
908 driver.vkQueueSubmit = +[](VkQueue, unsigned, const VkSubmitInfo*, VkFence) {
909 return fail_submit ? VK_ERROR_OUT_OF_HOST_MEMORY : VK_SUCCESS;
910 };
911 driver.vkCreateQueryPool = +[](VkDevice, const VkQueryPoolCreateInfo* info, const VkAllocationCallbacks*,
912 VkQueryPool* out) {
913 expect(info->queryCount > 0, "no empty pool allocation");
914 if (info->queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS) {
915 expect(info->pipelineStatistics == statistics_mask, "all 11 counters selected");
916 }
917 allocations.emplace_back(info->queryType, info->queryCount);
918 *out = handle<VkQueryPool>(next_pool++);
919 MockReplay::current->values[*out].resize(info->queryCount);
920 return VK_SUCCESS;
921 };
922 driver.vkDestroyQueryPool = +[](VkDevice, VkQueryPool p, const VkAllocationCallbacks*) {
923 expect(destroyed.insert(p).second, "pool destroyed twice");
924 };
925 VulkanContext context(get, handle<VkDevice>(1), true);
926 VkPhysicalDeviceMemoryProperties memory{};
927 memory.memoryTypeCount = 1;
928 context.set_occlusion_resolve_memory(memory);
929 QueryPool heap{handle<VkQueryPool>(2), d3d12_query_heap::occlusion, 4, false, std::vector<bool>(4), {}};
930 QueryPool stat{handle<VkQueryPool>(3), d3d12_query_heap::pipeline_statistics, 2, false, std::vector<bool>(2), {}};
931 c.values[heap.pool].resize(4);
932 c.values[stat.pool].resize(2);
933 context.add_query_pool(1, heap);
934 context.add_query_pool(2, stat);
935 ResourceBinding dst{};
936 dst.buffer = handle<VkBuffer>(1);
937 dst.size = resource_bytes;
938 dst.buffer_offset = arena_offset;
939 context.add_resource(1, dst);
940 c.buffers[dst.buffer].assign(backing_bytes, guard_byte);
941 {
942 VulkanQueue queue(context, handle<VkQueue>(1), 0);
943 expect(queue.ok(), "mock queue initialized");
944 CommandList a, b;
945 for (unsigned i = 0; i < list_count; ++i) {
946 auto& list = i ? b : a;
947 expect(list.begin_query({1, d3d12_query::occlusion, 0}) && list.begin_query({1, d3d12_query::occlusion,
948 1}) && list.end_query({1, d3d12_query::occlusion, 0}) && list.end_query({1,
949 d3d12_query::occlusion, 1}), "overlap scope");
950 expect(list.begin_query({2, d3d12_query::pipeline_statistics, i}), "statistics begin");
951 for (unsigned k = 0; k <= i; ++k) {
952 expect(list.resolve_queries({1, d3d12_query::occlusion, 3, 1, 1, 0}), "split statistics on zero fill");
953 }
954 expect(list.end_query({2, d3d12_query::pipeline_statistics, i}) && list.close(), "statistics end");
955 }
956 const CommandList* lists[]{&a, &b};
957 fail_submit = true;
958 expect(queue.execute(lists) == ReplayResult::unsupported, "injected transient submit failure");
959 fail_submit = false;
960 const std::vector<std::pair<VkQueryType, unsigned>> want{{VK_QUERY_TYPE_OCCLUSION, occlusion_slots_needed},
961 {VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_slots_needed}};
962 expect(allocations == want && destroyed.size() == 2, "failed submission frees exact six/five-slot pools");
963 // Published query state must still say 'never ended'. If commit ran on failure this would need a sum helper.
964 CommandList probe;
965 expect(probe.resolve_queries({1, d3d12_query::occlusion, 0, 2, 1, probe_occlusion_offset})
966 && probe.resolve_queries({2, d3d12_query::pipeline_statistics, 0, 1, 1, probe_statistics_offset})
967 && probe.close(), "failure-state probe");
968 const CommandList* pp = &probe;
969 expect(queue.execute({&pp, 1}) == ReplayResult::success, "failed query results were not published");
970 expect(c.word(dst.buffer, arena_offset + probe_occlusion_offset) == 0 && c.word(dst.buffer,
971 arena_offset + probe_occlusion_offset + word_size) == 0, "ordinary failure state zero-filled");
972 for (unsigned j = 0; j < statistics_counters; ++j) {
973 expect(c.word(dst.buffer, arena_offset + probe_statistics_offset + word_size * j) == 0,
974 "statistics failure state zero-filled");
975 }
976 expect(allocations == want, "resolve-only batch allocates no segment pools");
977 allocations.clear();
978 c.resets.clear();
979 expect(queue.execute(lists) == ReplayResult::success, "retry multi-list submission");
980 expect(allocations == want, "actual queue sums all list segment counts");
981 std::vector<unsigned> occlusion_slots, statistics_slots;
982 for (auto [p, i] : c.resets) {
983 if (p == handle<VkQueryPool>(successful_occlusion_pool)) {
984 occlusion_slots.push_back(i);
985 }
986 if (p == handle<VkQueryPool>(successful_statistics_pool)) {
987 statistics_slots.push_back(i);
988 }
989 }
990 expect(occlusion_slots == std::vector<unsigned>({0, 1, 2, 3, 4, 5})
991 && statistics_slots == std::vector<unsigned>({0, 1, 2, 3, 4}),
992 "second-list bases use every allocated slot exactly once");
993 // Mock reset/end entry points bounds-check every index against the actual allocations. Nonzero bases in the
994 // second list must cover occlusion slots 3..5 and statistics slots 2..4, without overlap or overflow.
995 for (unsigned i = first_pool_id; i <= successful_statistics_pool; ++i) {
996 expect(c.active[handle<VkQueryPool>(i)].empty(), "all physical queries ended");
997 }
998 expect(!destroyed.count(handle<VkQueryPool>(successful_occlusion_pool))
999 && !destroyed.count(handle<VkQueryPool>(successful_statistics_pool)), "successful pools remain alive");
1000 context.remove_query_pool(1);
1001 context.remove_query_pool(2);
1002 expect(!destroyed.count(handle<VkQueryPool>(successful_occlusion_pool))
1003 && !destroyed.count(handle<VkQueryPool>(successful_statistics_pool)),
1004 "in-flight command slot retains pools after heap removal");
1005 CommandList empty;
1006 expect(empty.close(), "empty list");
1007 const CommandList* ep = &empty;
1008 expect(queue.execute({&ep, 1}) == ReplayResult::success, "reuse completed command slot");
1009 expect(destroyed.count(handle<VkQueryPool>(successful_occlusion_pool))
1010 && destroyed.count(handle<VkQueryPool>(successful_statistics_pool)),
1011 "completed slot releases pools after final owner disappears");
1012 }
1013}
1014
1015} // namespace
1016
1017int main() {
1018 struct TestCase {
1019 const char* name;
1020 void (*run)();
1021 };
1022 const TestCase cases[] = {
1023 {"helper chunk boundaries", test_helper_chunks},
1024 {"query boundaries and persistent state", test_query_state},
1025 {"predication and recording checks", test_predicated_copies},
1026 {"queue segment allocation and failed submit", test_queue_segments},
1027 };
1028 unsigned failures = 0;
1029 for (const auto& test : cases) {
1030 try {
1031 test.run();
1032 } catch (const std::exception& error) {
1033 std::fprintf(stderr, "FAIL: %s: %s\n", test.name, error.what());
1034 ++failures;
1035 }
1036 }
1037 if (failures) {
1038 return 1;
1039 }
1040 std::puts("replay_query_edges_test: heap boundaries, chunking, persistent queries, "
1041 "predicated copies and queue ownership passed");
1042 return 0;
1043}
diff --git a/runtime/test/replay_query_predication_test.cpp b/runtime/test/replay_query_predication_test.cpp
index 621fb4eee..df4e22718 100644
--- a/runtime/test/replay_query_predication_test.cpp
+++ b/runtime/test/replay_query_predication_test.cpp
@@ -3,7 +3,9 @@
3// an active conditional rendering scope (D3D-148). Check that emit() suspends conditional rendering for the 3// an active conditional rendering scope (D3D-148). Check that emit() suspends conditional rendering for the
4// entire ResolveQueryData loop (not only before helper dispatches) and restores it afterward. Cases 5 and 6 check 4// entire ResolveQueryData loop (not only before helper dispatches) and restores it afterward. Cases 5 and 6 check
5// how resolves inside a pipeline-statistics query are replayed; cases 7 and 8 cover the other helper dispatches 5// how resolves inside a pipeline-statistics query are replayed; cases 7 and 8 cover the other helper dispatches
6// and their no-pool fallback (D3D-162). No GPU or game data. 6// and their no-pool fallback (D3D-162). Cases 9 to 13 check overlapping queries: statistics over statistics, binary
7// inside ordinary, the composite sum-and-normalize binary resolve, helper dispatches inside overlapping statistics
8// queries, and the single-list refusal (D3D-252). No GPU or game data.
7#include "../src/vulkan_replay.h" 9#include "../src/vulkan_replay.h"
8#include <cstdint> 10#include <cstdint>
9#include <cstdio> 11#include <cstdio>
@@ -133,6 +135,14 @@ int main() {
133 if (g_trace->cond_active) ++g_trace->binary_while_cond; 135 if (g_trace->cond_active) ++g_trace->binary_while_cond;
134 g_trace->events.push_back("binary"); 136 g_trace->events.push_back("binary");
135 }; 137 };
138 vk.sum_occlusion = [](VkCommandBuffer, VkQueryPool pool, std::uint32_t first, std::uint32_t count, VkBuffer,
139 VkDeviceSize) {
140 g_trace->events.push_back(query_event("sum_occlusion", pool, first) + "+" + std::to_string(count));
141 };
142 vk.sum_binary_occlusion = [](VkCommandBuffer, VkQueryPool pool, std::uint32_t first, std::uint32_t count,
143 VkBuffer, VkDeviceSize) {
144 g_trace->events.push_back(query_event("sum_binary_occlusion", pool, first) + "+" + std::to_string(count));
145 };
136 146
137 // 1. Binary occlusion resolve with leading and trailing un-ended queries under a predicate: 147 // 1. Binary occlusion resolve with leading and trailing un-ended queries under a predicate:
138 // conditional rendering must end before the leading fill_buffer and resume after the trailing fill_buffer. 148 // conditional rendering must end before the leading fill_buffer and resume after the trailing fill_buffer.
@@ -370,6 +380,197 @@ int main() {
370 } 380 }
371 } 381 }
372 382
383 // 9. D3D-252, overlapping pipeline-statistics queries: the segments follow every Begin and End, so each logical
384 // query keeps a contiguous range — the intersection interval is shared — and each resolve sums its range.
385 // A resolve may only name an ended query, so the second resolve follows the second End.
386 {
387 Trace trace;
388 g_trace = &trace;
389 CommandList list;
390 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 0}), "record overlap begin 0");
391 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 1}), "record overlap begin 1");
392 expect(list.end_query({6, d3d12_query::pipeline_statistics, 0}), "record overlap end 0");
393 expect(list.resolve_queries({6, d3d12_query::pipeline_statistics, 0, 1, 1, 0}), "record overlap resolve 0");
394 expect(list.end_query({6, d3d12_query::pipeline_statistics, 1}), "record overlap end 1");
395 expect(list.resolve_queries({6, d3d12_query::pipeline_statistics, 1, 1, 1, 0}), "record overlap resolve 1");
396 expect(list.close(), "close overlap statistics list");
397 PreparedList prepared;
398 expect(prepare(list, resolve, vk, prepared) == ReplayResult::success, "prepare overlap statistics list");
399 expect(prepared.statistics_segment_count == 4, "overlap statistics: four physical segments");
400 auto segments = std::make_shared<OcclusionSegmentPool>();
401 segments->pool = handle<VkQueryPool>(9);
402 segments->destroy = mock_destroy_pool;
403 QueryReplay queries;
404 expect(queries.plan(prepared, {}, 0, true, segments, 4) == ReplayResult::success,
405 "plan overlap statistics list");
406 expect(queries.needs_statistics_sum, "overlap statistics: the sum helper is needed");
407 emit(prepared, VK_NULL_HANDLE, vk);
408 queries.commit();
409 const std::vector<std::string> want{"begin_query 9:4", "end_query 9:4", "begin_query 9:5",
410 "end_query 9:5", "begin_query 9:6", "end_query 9:6",
411 "sum_statistics 9:4+2", "begin_query 9:7", "end_query 9:7",
412 "sum_statistics 9:5+3"};
413 expect(trace.events == want, "overlap statistics: one open segment per event, resolves sum the ranges");
414 expect(statistics_heap.occlusion.count(0) && statistics_heap.occlusion[0].count == 2 &&
415 statistics_heap.occlusion.count(1) && statistics_heap.occlusion[1].count == 3,
416 "overlap statistics: both heaps keep their segment ranges");
417 }
418
419 // 10. D3D-252, a binary occlusion query open inside an ordinary one: both are virtualized into the same physical
420 // pool. The ordinary resolve sums three segments; the binary resolve normalizes its one segment to 0/1.
421 {
422 Trace trace;
423 g_trace = &trace;
424 CommandList list;
425 expect(list.begin_query({1, d3d12_query::occlusion, 0}), "record kind overlap begin ordinary");
426 expect(list.begin_query({1, d3d12_query::binary_occlusion, 1}), "record kind overlap begin binary");
427 expect(list.end_query({1, d3d12_query::binary_occlusion, 1}), "record kind overlap end binary");
428 expect(list.end_query({1, d3d12_query::occlusion, 0}), "record kind overlap end ordinary");
429 expect(list.resolve_queries({1, d3d12_query::occlusion, 0, 1, 1, 0}), "record kind overlap resolve ordinary");
430 expect(list.resolve_queries({1, d3d12_query::binary_occlusion, 1, 1, 1, 16}), "record kind overlap resolve binary");
431 expect(list.close(), "close kind overlap list");
432 PreparedList prepared;
433 expect(prepare(list, resolve, vk, prepared) == ReplayResult::success, "prepare kind overlap list");
434 expect(prepared.segment_count == 3, "kind overlap: three physical segments");
435 auto segments = std::make_shared<OcclusionSegmentPool>();
436 segments->pool = handle<VkQueryPool>(9);
437 segments->destroy = mock_destroy_pool;
438 QueryReplay queries;
439 expect(queries.plan(prepared, segments, 0, true, {}, 0) == ReplayResult::success,
440 "plan kind overlap list");
441 expect(queries.needs_sum && queries.needs_binary && !queries.needs_sum_binary,
442 "kind overlap: sum for the ordinary resolve, normalize for the single-segment binary");
443 emit(prepared, VK_NULL_HANDLE, vk);
444 queries.commit();
445 const std::vector<std::string> want{"begin_query 9:0", "end_query 9:0", "begin_query 9:1",
446 "end_query 9:1", "begin_query 9:2", "end_query 9:2",
447 "sum_occlusion 9:0+3", "binary"};
448 expect(trace.events == want, "kind overlap: shared physical segments, sum and normalize resolves");
449 expect(heap.occlusion.count(0) && heap.occlusion[0].count == 3 && heap.occlusion.count(1) &&
450 heap.occlusion[1].count == 1,
451 "kind overlap: both kinds keep their segment ranges in the heap");
452 }
453
454 // 11. D3D-252, a binary query overlapping the ordinary one with two segments: the resolve sums the segments and
455 // then normalizes the total (the composite helper), not one 0/1 per segment.
456 {
457 Trace trace;
458 g_trace = &trace;
459 CommandList list;
460 expect(list.begin_query({1, d3d12_query::occlusion, 0}), "record composite begin ordinary");
461 expect(list.begin_query({1, d3d12_query::binary_occlusion, 1}), "record composite begin binary");
462 expect(list.end_query({1, d3d12_query::occlusion, 0}), "record composite end ordinary");
463 expect(list.end_query({1, d3d12_query::binary_occlusion, 1}), "record composite end binary");
464 expect(list.resolve_queries({1, d3d12_query::binary_occlusion, 1, 1, 1, 16}), "record composite resolve binary");
465 expect(list.close(), "close composite list");
466 PreparedList prepared;
467 expect(prepare(list, resolve, vk, prepared) == ReplayResult::success, "prepare composite list");
468 expect(prepared.segment_count == 3, "composite: three physical segments");
469 auto segments = std::make_shared<OcclusionSegmentPool>();
470 segments->pool = handle<VkQueryPool>(9);
471 segments->destroy = mock_destroy_pool;
472 QueryReplay queries;
473 expect(queries.plan(prepared, segments, 0, true, {}, 0) == ReplayResult::success, "plan composite list");
474 expect(queries.needs_sum_binary, "composite: the sum-and-normalize helper is needed");
475 emit(prepared, VK_NULL_HANDLE, vk);
476 queries.commit();
477 const std::vector<std::string> want{"begin_query 9:0", "end_query 9:0", "begin_query 9:1",
478 "end_query 9:1", "begin_query 9:2", "end_query 9:2",
479 "sum_binary_occlusion 9:1+2"};
480 expect(trace.events == want, "composite: the binary resolve sums its segments and normalizes once");
481 }
482
483 // 12. D3D-252, helper dispatches inside overlapping statistics queries: the helpers share the segment numbering
484 // here too — the shared physical segment closes before the dispatches and a new one opens after them, so a
485 // footprint conversion stays out of every query still running (D3D-162).
486 {
487 Trace trace;
488 g_trace = &trace;
489 auto helpers = vk;
490 helpers.depth24_prepare = [&](Depth24Job& job, std::vector<Depth24Job>& parts) {
491 job.scratch = handle<VkBuffer>(10);
492 parts.assign(2, job);
493 return true;
494 };
495 helpers.depth24_run = [](VkCommandBuffer, const Depth24Job&) {
496 expect(!g_trace->cond_active, "footprint helper is unconditional");
497 g_trace->events.push_back("footprint");
498 };
499 helpers.pipeline_barrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags,
500 VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*, std::uint32_t,
501 const VkBufferMemoryBarrier*, std::uint32_t, const VkImageMemoryBarrier*) {};
502 helpers.copy_buffer = +[](VkCommandBuffer, VkBuffer, VkBuffer, std::uint32_t, const VkBufferCopy*) {};
503 helpers.copy_buffer_to_image = +[](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout,
504 std::uint32_t, const VkBufferImageCopy*) {};
505 helpers.copy_image = +[](VkCommandBuffer, VkImage, VkImageLayout, VkImage, VkImageLayout,
506 std::uint32_t, const VkImageCopy*) {};
507 helpers.copy_image_to_buffer = +[](VkCommandBuffer, VkImage, VkImageLayout, VkBuffer,
508 std::uint32_t, const VkBufferImageCopy*) {
509 g_trace->events.push_back("readback");
510 };
511 ResourceBinding buffer = dst;
512 buffer.buffer_offset = 0;
513 buffer.size = 512;
514 ResourceBinding image{};
515 image.image = handle<VkImage>(11);
516 image.format = VK_FORMAT_D32_SFLOAT_S8_UINT;
517 image.aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
518 image.width = image.height = image.depth = image.mip_levels = image.array_layers = image.samples = 1;
519 image.rgb96 = false;
520 image.depth24 = image.depth24_as_float = true;
521 const auto resources = [&](ResourceId id) -> const ResourceBinding* {
522 return id == 1 ? &buffer : id == 3 ? &image : nullptr;
523 };
524 const CopyLocation texture{3, false, 0, 0, 0, 0, 0, 0};
525 const CopyLocation footprint{1, true, 0, 0, 1, 1, 1, 256};
526 CommandList list;
527 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 0}), "overlap helper begin 0");
528 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 1}), "overlap helper begin 1");
529 expect(list.end_query({6, d3d12_query::pipeline_statistics, 0}), "overlap helper end 0");
530 expect(list.copy_texture({footprint, 0, 0, 0, texture, false, {}}), "overlap helper footprint copy");
531 expect(list.end_query({6, d3d12_query::pipeline_statistics, 1}), "overlap helper end 1");
532 expect(list.resolve_queries({6, d3d12_query::pipeline_statistics, 0, 1, 1, 0}), "overlap helper resolve 0");
533 expect(list.resolve_queries({6, d3d12_query::pipeline_statistics, 1, 1, 1, 0}), "overlap helper resolve 1");
534 expect(list.close(), "close overlap helper list");
535 PreparedList prepared;
536 expect(prepare(list, resources, helpers, prepared, true) == ReplayResult::success,
537 "prepare overlap helper list");
538 expect(prepared.statistics_segment_count == 4, "the helper adds its two segments to the overlap");
539 auto segments = std::make_shared<OcclusionSegmentPool>();
540 segments->pool = handle<VkQueryPool>(9);
541 segments->destroy = mock_destroy_pool;
542 QueryReplay queries;
543 expect(queries.plan(prepared, {}, 0, true, segments, 4) == ReplayResult::success,
544 "plan overlap helper list");
545 expect(queries.needs_statistics_sum, "overlap helpers need the statistics sum");
546 emit(prepared, VK_NULL_HANDLE, helpers);
547 queries.commit();
548 const std::vector<std::string> want{
549 "begin_query 9:4", "end_query 9:4", "begin_query 9:5", "end_query 9:5", "begin_query 9:6",
550 "readback", "end_query 9:6", "footprint", "footprint", "begin_query 9:7",
551 "end_query 9:7", "sum_statistics 9:4+2", "sum_statistics 9:5+3"};
552 expect(trace.events == want, "overlap helpers: the dispatches run outside every open segment");
553 expect(statistics_heap.occlusion.count(0) && statistics_heap.occlusion[0].count == 2 &&
554 statistics_heap.occlusion.count(1) && statistics_heap.occlusion[1].count == 3,
555 "overlap helpers: the queries keep their segment ranges");
556 }
557
558 // 13. D3D-252, the single-list replay() helper: it has no segment pool, and running overlapping statistics
559 // queries whole would keep two Vulkan queries of one type active, so the list is refused outright.
560 {
561 Trace trace;
562 g_trace = &trace;
563 CommandList list;
564 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 0}), "record helper begin 0");
565 expect(list.begin_query({6, d3d12_query::pipeline_statistics, 1}), "record helper begin 1");
566 expect(list.end_query({6, d3d12_query::pipeline_statistics, 0}), "record helper end 0");
567 expect(list.end_query({6, d3d12_query::pipeline_statistics, 1}), "record helper end 1");
568 expect(list.close(), "close helper list");
569 expect(replay(list, VK_NULL_HANDLE, resolve, vk) == ReplayResult::unsupported,
570 "no segment pool: overlapping statistics queries are refused instead of run whole");
571 expect(trace.events.empty(), "no segment pool: nothing was emitted for the refused list");
572 }
573
373 if (failures) return 1; 574 if (failures) return 1;
374 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); 575 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches");
375 return 0; 576 return 0;
diff --git a/runtime/test/resource_tiling_test.cpp b/runtime/test/resource_tiling_test.cpp
index 848e2f57c..9bbcfbf3a 100644
--- a/runtime/test/resource_tiling_test.cpp
+++ b/runtime/test/resource_tiling_test.cpp
@@ -111,8 +111,8 @@ int main() {
111 // AMD's split (D3D-65). Every layout below was measured on the AMD PC runtime and is identical on an RX 9070 XT 111 // AMD's split (D3D-65). Every layout below was measured on the AMD PC runtime and is identical on an RX 9070 XT
112 // (RDNA4, driver 32.0.31041.1004) and a Ryzen 7 9800X3D iGPU (RDNA2, 32.0.21045.5002): compare_tiling's 17 texture 112 // (RDNA4, driver 32.0.31041.1004) and a Ryzen 7 9800X3D iGPU (RDNA2, 32.0.21045.5002): compare_tiling's 17 texture
113 // layouts, then 30 edge cases (a mip exactly at or just past half a tile, thin and tall textures, non-square 2D and 113 // layouts, then 30 edge cases (a mip exactly at or just past half a tile, thin and tall textures, non-square 2D and
114 // volume tiles). The standard and packed mip counts and the packed start are AMD's. The packed tiles are this 114 // volume tiles), then 36 volumes whose packed tail is deeper than a tile. Every field is AMD's: the standard and
115 // layer's tight count, which is AMD's except for the two deep volumes packed from mip 0, where AMD reserves 2. 115 // packed mip counts, the packed start, and the packed tiles, one per tile-depth slice the tail spans.
116 struct AmdCase { 116 struct AmdCase {
117 const char* name; 117 const char* name;
118 TilingDesc desc; 118 TilingDesc desc;
@@ -159,13 +159,50 @@ int main() {
159 {"132x4 BC7", {TiledKind::texture2d, 132, 4, 1, 8, 16, 4}, 1, 7, 1, 1}, 159 {"132x4 BC7", {TiledKind::texture2d, 132, 4, 1, 8, 16, 4}, 1, 7, 1, 1},
160 {"32^3 R8 vol", {TiledKind::texture3d, 32, 32, 32, 6, 1, 1}, 0, 6, 1, 0}, 160 {"32^3 R8 vol", {TiledKind::texture3d, 32, 32, 32, 6, 1, 1}, 0, 6, 1, 0},
161 {"33x4x4 R8 vol", {TiledKind::texture3d, 33, 4, 4, 6, 1, 1}, 1, 5, 1, 1}, 161 {"33x4x4 R8 vol", {TiledKind::texture3d, 33, 4, 4, 6, 1, 1}, 1, 5, 1, 1},
162 {"8x8x64 R8 vol", {TiledKind::texture3d, 8, 8, 64, 7, 1, 1}, 0, 7, 1, 0}, // AMD reserves 2 162 {"8x8x64 R8 vol", {TiledKind::texture3d, 8, 8, 64, 7, 1, 1}, 0, 7, 2, 0},
163 {"32x17x17 R8 vol", {TiledKind::texture3d, 32, 17, 17, 6, 1, 1}, 0, 6, 1, 0}, 163 {"32x17x17 R8 vol", {TiledKind::texture3d, 32, 17, 17, 6, 1, 1}, 0, 6, 1, 0},
164 {"16^3 RGBA8 vol", {TiledKind::texture3d, 16, 16, 16, 5, 4, 1}, 0, 5, 1, 0}, 164 {"16^3 RGBA8 vol", {TiledKind::texture3d, 16, 16, 16, 5, 4, 1}, 0, 5, 1, 0},
165 {"16x16x17 RGBA8 vol", {TiledKind::texture3d, 16, 16, 17, 5, 4, 1}, 0, 5, 1, 0}, // AMD reserves 2 165 {"16x16x17 RGBA8 vol", {TiledKind::texture3d, 16, 16, 17, 5, 4, 1}, 0, 5, 2, 0},
166 {"16x9x9 RGBA8 vol", {TiledKind::texture3d, 16, 9, 9, 5, 4, 1}, 0, 5, 1, 0}, 166 {"16x9x9 RGBA8 vol", {TiledKind::texture3d, 16, 9, 9, 5, 4, 1}, 0, 5, 1, 0},
167 {"8^3 RGBA32F vol", {TiledKind::texture3d, 8, 8, 8, 4, 16, 1}, 0, 4, 1, 0}, 167 {"8^3 RGBA32F vol", {TiledKind::texture3d, 8, 8, 8, 4, 16, 1}, 0, 4, 1, 0},
168 {"9x1x1 RGBA32F vol", {TiledKind::texture3d, 9, 1, 1, 4, 16, 1}, 1, 3, 1, 1}, 168 {"9x1x1 RGBA32F vol", {TiledKind::texture3d, 9, 1, 1, 4, 16, 1}, 1, 3, 1, 1},
169 // Packed tails deeper than one tile: one packed tile per tile-depth slice.
170 {"8x8x16 R8 vol", {TiledKind::texture3d, 8, 8, 16, 5, 1, 1}, 0, 5, 1, 0},
171 {"8x8x32 R8 vol", {TiledKind::texture3d, 8, 8, 32, 6, 1, 1}, 0, 6, 1, 0},
172 {"8x8x33 R8 vol", {TiledKind::texture3d, 8, 8, 33, 6, 1, 1}, 0, 6, 2, 0},
173 {"8x8x48 R8 vol", {TiledKind::texture3d, 8, 8, 48, 6, 1, 1}, 0, 6, 2, 0},
174 {"8x8x64 R8 vol", {TiledKind::texture3d, 8, 8, 64, 7, 1, 1}, 0, 7, 2, 0},
175 {"8x8x65 R8 vol", {TiledKind::texture3d, 8, 8, 65, 7, 1, 1}, 0, 7, 3, 0},
176 {"8x8x96 R8 vol", {TiledKind::texture3d, 8, 8, 96, 7, 1, 1}, 0, 7, 3, 0},
177 {"8x8x128 R8 vol", {TiledKind::texture3d, 8, 8, 128, 8, 1, 1}, 0, 8, 4, 0},
178 {"8x8x129 R8 vol", {TiledKind::texture3d, 8, 8, 129, 8, 1, 1}, 0, 8, 5, 0},
179 {"8x8x256 R8 vol", {TiledKind::texture3d, 8, 8, 256, 9, 1, 1}, 0, 9, 8, 0},
180 {"16x16x16 RGBA8 vol", {TiledKind::texture3d, 16, 16, 16, 5, 4, 1}, 0, 5, 1, 0},
181 {"16x16x17 RGBA8 vol", {TiledKind::texture3d, 16, 16, 17, 5, 4, 1}, 0, 5, 2, 0},
182 {"16x16x32 RGBA8 vol", {TiledKind::texture3d, 16, 16, 32, 6, 4, 1}, 0, 6, 2, 0},
183 {"16x16x33 RGBA8 vol", {TiledKind::texture3d, 16, 16, 33, 6, 4, 1}, 0, 6, 3, 0},
184 {"16x16x48 RGBA8 vol", {TiledKind::texture3d, 16, 16, 48, 6, 4, 1}, 0, 6, 3, 0},
185 {"16x16x64 RGBA8 vol", {TiledKind::texture3d, 16, 16, 64, 7, 4, 1}, 0, 7, 4, 0},
186 {"16x16x128 RGBA8 vol", {TiledKind::texture3d, 16, 16, 128, 8, 4, 1}, 0, 8, 8, 0},
187 {"16x16x32 R16F vol", {TiledKind::texture3d, 16, 16, 32, 6, 2, 1}, 0, 6, 1, 0},
188 {"16x16x33 R16F vol", {TiledKind::texture3d, 16, 16, 33, 6, 2, 1}, 0, 6, 2, 0},
189 {"16x16x64 R16F vol", {TiledKind::texture3d, 16, 16, 64, 7, 2, 1}, 0, 7, 2, 0},
190 {"16x16x100 R16F vol", {TiledKind::texture3d, 16, 16, 100, 7, 2, 1}, 0, 7, 4, 0},
191 {"16x16x16 RGBA16F vol", {TiledKind::texture3d, 16, 16, 16, 5, 8, 1}, 0, 5, 1, 0},
192 {"16x16x17 RGBA16F vol", {TiledKind::texture3d, 16, 16, 17, 5, 8, 1}, 0, 5, 2, 0},
193 {"16x16x64 RGBA16F vol", {TiledKind::texture3d, 16, 16, 64, 7, 8, 1}, 0, 7, 4, 0},
194 {"8x8x8 RGBA32F vol", {TiledKind::texture3d, 8, 8, 8, 4, 16, 1}, 0, 4, 1, 0},
195 {"8x8x16 RGBA32F vol", {TiledKind::texture3d, 8, 8, 16, 5, 16, 1}, 0, 5, 1, 0},
196 {"8x8x17 RGBA32F vol", {TiledKind::texture3d, 8, 8, 17, 5, 16, 1}, 0, 5, 2, 0},
197 {"8x8x64 RGBA32F vol", {TiledKind::texture3d, 8, 8, 64, 7, 16, 1}, 0, 7, 4, 0},
198 {"32x32x64 R8 vol", {TiledKind::texture3d, 32, 32, 64, 7, 1, 1}, 0, 7, 2, 0},
199 {"1x1x256 R8 vol", {TiledKind::texture3d, 1, 1, 256, 9, 1, 1}, 0, 9, 8, 0},
200 {"16x4x100 RGBA8 vol", {TiledKind::texture3d, 16, 4, 100, 7, 4, 1}, 0, 7, 7, 0},
201 {"64x8x256 R8 vol", {TiledKind::texture3d, 64, 8, 256, 9, 1, 1}, 1, 8, 4, 8},
202 {"32x8x64 RGBA8 vol", {TiledKind::texture3d, 32, 8, 64, 7, 4, 1}, 1, 6, 2, 4},
203 {"128x16x128 RGBA8 vol", {TiledKind::texture3d, 128, 16, 128, 8, 4, 1}, 3, 5, 1, 42},
204 {"64x64x256 R8 vol", {TiledKind::texture3d, 64, 64, 256, 9, 1, 1}, 1, 8, 4, 16},
205 {"32x16x64 RGBA16F vol", {TiledKind::texture3d, 32, 16, 64, 7, 8, 1}, 1, 6, 2, 4},
169 }; 206 };
170 for (const AmdCase& c : amd) { 207 for (const AmdCase& c : amd) {
171 if (!resource_tiling(c.desc, t) || t.standard_mips != c.standard || t.packed_mips != c.packed || 208 if (!resource_tiling(c.desc, t) || t.standard_mips != c.standard || t.packed_mips != c.packed ||
diff --git a/runtime/test/root_signature_test.cpp b/runtime/test/root_signature_test.cpp
index f11302874..3952db5b8 100644
--- a/runtime/test/root_signature_test.cpp
+++ b/runtime/test/root_signature_test.cpp
@@ -76,6 +76,18 @@ std::vector<uint8_t> build_payload() {
76int main() { 76int main() {
77 using namespace rt::rootsig; 77 using namespace rt::rootsig;
78 78
79 // The public packer also validates callers that construct the model directly.
80 {
81 RootSignature sig;
82 RootParameter invalid;
83 invalid.type = static_cast<ParamType>(0xffffffffu);
84 invalid.num_values = 1;
85 sig.params = {invalid};
86 const auto result = pack(sig);
87 check(!result.ok && result.error.find("unknown") != std::string::npos,
88 "invalid parameter enum cannot produce a successful zero-cost layout");
89 }
90
79 // Mixed signature: 4 constants + CBV + table + 1 static sampler. 91 // Mixed signature: 4 constants + CBV + table + 1 static sampler.
80 { 92 {
81 RootSignature sig; 93 RootSignature sig;
diff --git a/runtime/test/shader_fixture_path.h b/runtime/test/shader_fixture_path.h
new file mode 100644
index 000000000..fdfd4aa59
--- /dev/null
+++ b/runtime/test/shader_fixture_path.h
@@ -0,0 +1,15 @@
1// Synthetic GPU test shaders are packaged under generated/ in runtime-windows artifacts.
2// Run downloaded tests from the artifact directory, as CTest does for a local build.
3#pragma once
4
5#include <filesystem>
6
7namespace vktest {
8inline std::filesystem::path shader_fixture_path(const std::filesystem::path& compiled_path) {
9 if (std::filesystem::is_regular_file(compiled_path)) return compiled_path;
10 const auto packaged = std::filesystem::path("generated") / compiled_path.filename();
11 if (std::filesystem::is_regular_file(packaged)) return packaged;
12 // Preserve the original path in the caller's missing-file diagnostic.
13 return compiled_path;
14}
15} // namespace vktest
diff --git a/runtime/test/shader_fixture_path_test.cpp b/runtime/test/shader_fixture_path_test.cpp
new file mode 100644
index 000000000..557986157
--- /dev/null
+++ b/runtime/test/shader_fixture_path_test.cpp
@@ -0,0 +1,32 @@
1#include "shader_fixture_path.h"
2#include <cstdio>
3#include <chrono>
4#include <fstream>
5
6int main() {
7 namespace fs = std::filesystem;
8 const auto root = fs::temp_directory_path() / ("leonida_fixture_path_" +
9 std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
10 fs::create_directories(root / "generated");
11 const auto previous = fs::current_path();
12 int result = 0;
13 try {
14 fs::current_path(root);
15 std::ofstream("generated/test.spv") << "packaged";
16 const auto original = root / "build" / "test.spv";
17 if (vktest::shader_fixture_path(original) != fs::path("generated/test.spv")) result = 1;
18 fs::create_directory("build");
19 std::ofstream(original) << "local";
20 if (vktest::shader_fixture_path(original) != original) result = 1;
21 const auto missing = root / "build" / "missing.spv";
22 if (vktest::shader_fixture_path(missing) != missing) result = 1;
23 fs::remove(original);
24 fs::remove("generated/test.spv");
25 fs::create_directory("generated/test.spv");
26 if (vktest::shader_fixture_path(original) != original) result = 1;
27 } catch (...) { result = 1; }
28 fs::current_path(previous);
29 fs::remove_all(root);
30 std::puts(result ? "shader fixture lookup failed" : "shader fixture lookup passed");
31 return result;
32}
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index 8a57d7bae..3a37018d6 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -7,6 +7,7 @@
7#include <filesystem> 7#include <filesystem>
8#include <fstream> 8#include <fstream>
9#include <initializer_list> 9#include <initializer_list>
10#include <sstream>
10#include <string> 11#include <string>
11#include <vector> 12#include <vector>
12 13
@@ -251,6 +252,26 @@ int fspx_checks() {
251int main() { 252int main() {
252 using namespace leonida; 253 using namespace leonida;
253 254
255 // Test the shared file reader without passing malformed bytes to a driver.
256 const std::vector<std::uint32_t> header = {0x07230203, 0x00010300, 0, 1, 0};
257 const std::string header_bytes(reinterpret_cast<const char*>(header.data()), header.size() * sizeof(header.front()));
258 {
259 std::istringstream input(header_bytes);
260 input.seekg(0, std::ios::end);
261 CHECK(read_spirv_words(input, input.tellg()) == header);
262 }
263 for (const auto& bad : {std::string{}, header_bytes.substr(0, 16), header_bytes + 'x',
264 std::string("bad!") + header_bytes.substr(4)}) {
265 std::istringstream input(bad);
266 input.seekg(0, std::ios::end);
267 CHECK(read_spirv_words(input, input.tellg()).empty());
268 }
269 {
270 std::istringstream input(header_bytes);
271 input.seekg(0, std::ios::end);
272 CHECK(read_spirv_words(input, static_cast<std::streamoff>(header_bytes.size() + 4)).empty());
273 }
274
254 CHECK(sha256_hex({}) == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); 275 CHECK(sha256_hex({}) == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
255 CHECK(sha256_hex(bytes("abc")) == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); 276 CHECK(sha256_hex(bytes("abc")) == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
256 CHECK(sha256_hex(bytes("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")) == 277 CHECK(sha256_hex(bytes("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")) ==
@@ -339,7 +360,8 @@ int main() {
339 " \"vs_same_program\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << hash << "\", \"input_signature\": [" 360 " \"vs_same_program\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << hash << "\", \"input_signature\": ["
340 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, " 361 "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, "
341 "\"component_type\": \"float\"}]},\n" 362 "\"component_type\": \"float\"}]},\n"
342 " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"outputs\": [0, 2]},\n" 363 " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"inputs\": [0, 1, 28, 29], "
364 "\"outputs\": [0, 2], \"f16_halves\": {\"0\": [28, 29], \"bad\": [1], \"7\": [20, 21]}},\n"
343 " \"ps_native\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " 365 " \"ps_native\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, "
344 "\"subgroup_size\": 64},\n" 366 "\"subgroup_size\": 64},\n"
345 " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " 367 " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, "
@@ -364,6 +386,9 @@ int main() {
364 vs_all[1]->input_signature[0].register_index == 0); 386 vs_all[1]->input_signature[0].register_index == 0);
365 const ShaderEntry* ps = library.find("ps", hash); 387 const ShaderEntry* ps = library.find("ps", hash);
366 CHECK(ps && ps->outputs.size() == 2 && ps->outputs[1] == 2); 388 CHECK(ps && ps->outputs.size() == 2 && ps->outputs[1] == 2);
389 CHECK(ps->inputs.size() == 4 && ps->inputs[0] == 0 && ps->inputs[3] == 29);
390 CHECK(ps->f16_halves.size() == 2 && ps->f16_halves.at(0)[0] == 28 && ps->f16_halves.at(0)[1] == 29 &&
391 ps->f16_halves.at(7)[0] == 20 && ps->f16_halves.at(7)[1] == 21);
367 const ShaderEntry* entry = library.find("cs", sha256_hex(fssm_program(shader))); 392 const ShaderEntry* entry = library.find("cs", sha256_hex(fssm_program(shader)));
368 CHECK(entry && entry->name == "cs_test" && entry->binding_count == 1 && entry->push_constant_bytes == 144); 393 CHECK(entry && entry->name == "cs_test" && entry->binding_count == 1 && entry->push_constant_bytes == 144);
369 CHECK(entry->local_size[0] == 64 && entry->uses_code_base && !entry->wave64); 394 CHECK(entry->local_size[0] == 64 && entry->uses_code_base && !entry->wave64);
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index 412dc2b8f..4dd01f8e4 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -22,6 +22,9 @@ With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are trans
22each gets a pass-through geometry shader, <name>.bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). 22each gets a pass-through geometry shader, <name>.bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py).
23Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR 23Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR
24inputs, and check.py reports it as SKIP. 24inputs, and check.py reports it as SKIP.
25With LEONIDA_PC_TAIL_UBO=1, every shader is translated with --pc-tail-ubo (s0..s31 in 128 push-constant bytes, the
26heap base and code base in a uniform block at set 1), for devices whose maxPushConstantsSize is 128; set it for
27check.py too, whose test programs then bind that block (runtime/test/vk_pc_tail.h).
25""" 28"""
26import json 29import json
27import os 30import os
@@ -165,6 +168,9 @@ def translate_tests(work, names):
165 cmd.append("--f16-interp-fallback") 168 cmd.append("--f16-interp-fallback")
166 if os.environ.get("LEONIDA_TEXOFF_FALLBACK") == "1": # texel offsets without VK_KHR_maintenance8 169 if os.environ.get("LEONIDA_TEXOFF_FALLBACK") == "1": # texel offsets without VK_KHR_maintenance8
167 cmd.append("--texel-offset-fallback") 170 cmd.append("--texel-offset-fallback")
171 # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h).
172 if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"):
173 cmd.append("--pc-tail-ubo")
168 return subprocess.run(cmd).returncode 174 return subprocess.run(cmd).returncode
169 175
170 176
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index bec6947e7..9771f17b1 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -296,6 +296,8 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
296 "ps_ops8": (0x80000000, 0xbfffffff, 0x000f100e, 0x0f0f0f1f), 296 "ps_ops8": (0x80000000, 0xbfffffff, 0x000f100e, 0x0f0f0f1f),
297 "ps_f32_mods": (0xc0256a01, 0x3f800000, 0x41e00000, 0x3fc00000), 297 "ps_f32_mods": (0xc0256a01, 0x3f800000, 0x41e00000, 0x3fc00000),
298 "ps_scc": (1, 1, 3, 0x80000000), "ps_sdwa": (0x000000f1, 0xbffefff2, 0x3c003344, 0xbff70000), 298 "ps_scc": (1, 1, 3, 0x80000000), "ps_sdwa": (0x000000f1, 0xbffefff2, 0x3c003344, 0xbff70000),
299 # 16-bit SDWA results with dst_sel:DWORD zero the high half (.asm header, measured on gfx1036)
300 "ps_sdwa_dword_hi": (0x00004000, 0x00000003, 0x00004700, 0x0000c000),
299 "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), 301 "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0),
300 # v_cmpx_{eq,gt,le,lt,ngt,nle}_f32, f_i32, t_u32, {eq,gt,le}_i64, {ge,lt,ne}_u64 (.asm header) 302 # v_cmpx_{eq,gt,le,lt,ngt,nle}_f32, f_i32, t_u32, {eq,gt,le}_i64, {ge,lt,ne}_u64 (.asm header)
301 "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000), 303 "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000),
@@ -325,6 +327,12 @@ PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
325 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000), 327 "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000),
326 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) 328 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers)
327 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3f800000), 329 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3f800000),
330 # 16-bit float v_cmp, all 16 predicates, e32 and e64 with swapped operands (.asm headers)
331 "ps_vcmp_f16": (0x48a12080, 0x4ce9b1a2, 0x4ba72c98, 0x4fefbdba),
332 "ps_vcmp_f16_e64": (0x44c11100, 0x4cf171c1, 0x47c71d18, 0x4ff77dd9),
333 # 16-bit float v_cmpx, all 16 predicates, EXEC result with VCC kept (.asm headers)
334 "ps_vcmpx_f16": (0x68a12080, 0x6ce9b1a2, 0x6ba72c98, 0x6fefbdba),
335 "ps_vcmpx_f16_e64": (0x64c11100, 0x6cf171c1, 0x67c71d18, 0x6ff77dd9),
328 "ps_cvt_off": (0xbf000000, 0x3ee00000, 0xbe800000, 0x3f800000), 336 "ps_cvt_off": (0xbf000000, 0x3ee00000, 0xbe800000, 0x3f800000),
329 "ps_fmac_f16_mods": (0xaaaa3c00, 0xaaaa3e00, 0xaaaa0000, 0xaaaa4000), 337 "ps_fmac_f16_mods": (0xaaaa3c00, 0xaaaa3e00, 0xaaaa0000, 0xaaaa4000),
330 "ps_vop3_const_mods": (0xc0000000, 0xbf800000, 0x3f800000, 0xaaaabc00), 338 "ps_vop3_const_mods": (0xc0000000, 0xbf800000, 0x3f800000, 0xaaaabc00),
@@ -367,6 +375,7 @@ CLIP_TESTS = ("vs_clip", "vs_clip_param4", "vs_clip_undeclared")
367# One definition: a later assignment used to drop ps_texoff (and any entry added by an earlier assignment) from 375# One definition: a later assignment used to drop ps_texoff (and any entry added by an earlier assignment) from
368# the standalone run. Keep every pixel fixture in this tuple. 376# the standalone run. Keep every pixel fixture in this tuple.
369PIXEL_TESTS = sorted((*PIXEL_BITS, "ps_bary", "ps_flat", "ps_bitmask_perm", "ps_texoff", "ps_texoff_implicit", 377PIXEL_TESTS = sorted((*PIXEL_BITS, "ps_bary", "ps_flat", "ps_bitmask_perm", "ps_texoff", "ps_texoff_implicit",
378 "ps_texoff_forms",
370 "ps_uniform_branch", "ps_wqm", "ps_scc_mask32", "ps_interp_f16_high", "ps_ij_computed", 379 "ps_uniform_branch", "ps_wqm", "ps_scc_mask32", "ps_interp_f16_high", "ps_ij_computed",
371 "ps_mandelbrot")) 380 "ps_mandelbrot"))
372# Pixel fixtures drawn with another vertex shader than vs_ids. 381# Pixel fixtures drawn with another vertex shader than vs_ids.
@@ -400,8 +409,10 @@ STORE_WORDS = {
400 "cs_imgatomic3d": ({}, dict(enumerate([0x101, 0xDB, 0xF4, 0xCE, 0xE6, 0xFF])), 409 "cs_imgatomic3d": ({}, dict(enumerate([0x101, 0xDB, 0xF4, 0xCE, 0xE6, 0xFF])),
401 {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}), 410 {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}),
402 # image_get_resinfo on a 16x4 image with five levels: (width, height, depth, levels) of levels 0, 1 and 3, then 411 # image_get_resinfo on a 16x4 image with five levels: (width, height, depth, levels) of levels 0, 1 and 3, then
403 # width and height of level 2 and an untouched register, height and levels of level 1, the levels alone 412 # width and height of level 2 and an untouched register, height and levels of level 1, the levels alone, and
404 "cs_resinfo": ({**dict(enumerate([16, 4, 1, 5, 8, 2, 1, 5, 2, 1, 1, 5, 4, 1, 0xABCD])), 16: 2, 17: 5, 18: 5}, 413 # level 5, past the last (2D depth 0 and the past-the-end zeros measured on RDNA2, SHADER-388)
414 "cs_resinfo": ({**dict(enumerate([16, 4, 0, 5, 8, 2, 0, 5, 2, 1, 0, 5, 4, 1, 0xABCD])), 16: 2, 17: 5, 18: 5,
415 20: 0, 21: 0, 22: 0, 23: 5},
405 {}, {}), 416 {}, {}),
406} 417}
407# TEST-184: image_get_lod on vk_texture_test's textures. Per fixture, its draws: S# word 1 (MIN_LOD [11:0], MAX_LOD 418# TEST-184: image_get_lod on vk_texture_test's textures. Per fixture, its draws: S# word 1 (MIN_LOD [11:0], MAX_LOD
@@ -903,7 +914,7 @@ def sampler_mismatch(data, words, view):
903 for i, got in enumerate(struct.iter_unpack("<4f", data)): 914 for i, got in enumerate(struct.iter_unpack("<4f", data)):
904 y, x = divmod(i, SAMPLER_SIZE) 915 y, x = divmod(i, SAMPLER_SIZE)
905 want = sampler_texel(explicit, x, y) + sampler_texel(implicit, x, y) 916 want = sampler_texel(explicit, x, y) + sampler_texel(implicit, x, y)
906 if any(abs(g - w) > 1e-6 for g, w in zip(got, want)): 917 if any(not math.isclose(g, w, rel_tol=0, abs_tol=1e-6) for g, w in zip(got, want)):
907 return f"({x},{y}): {tuple(round(g, 4) for g in got)} != {tuple(round(w, 4) for w in want)}" 918 return f"({x},{y}): {tuple(round(g, 4) for g in got)} != {tuple(round(w, 4) for w in want)}"
908 return "" 919 return ""
909 920
@@ -973,11 +984,15 @@ def texture_constant_test(tools, spirv, name):
973 return "" if not wrong else f"{wrong} of 4096 pixels differ from {expected}" 984 return "" if not wrong else f"{wrong} of 4096 pixels differ from {expected}"
974 985
975 986
976def texoff_words(px, py): 987def texoff_words(px, py, name="ps_texoff"):
977 """ps_texoff's mrt0 words at pixel (px, py), from the rule in docs/design.md (derivation in ps_texoff.asm).""" 988 """ps_texoff's mrt0 words at pixel (px, py), from the rule in docs/design.md (derivation in ps_texoff.asm).
989 ps_texoff_forms (image_sample_o, image_sample_b_o, image_gather4_l_o) puts the per-pixel sample in .x and .y and
990 the same two gathers in .z and .w (derivation in ps_texoff_forms.asm)."""
978 bx, by = px >> 3, py >> 3 # per-pixel offset (bx - 4, by - 4) from texel (4, 4) 991 bx, by = px >> 3, py >> 3 # per-pixel offset (bx - 4, by - 4) from texel (4, 4)
979 x0, y0 = max(bx - 1, 0), max(by - 1, 0) # gather footprint 3..4 moved by the offset, clamped at 0 992 x0, y0 = max(bx - 1, 0), max(by - 1, 0) # gather footprint 3..4 moved by the offset, clamped at 0
980 return (bx | by << 4, 0x0761, x0 | bx << 4 | bx << 8 | x0 << 12, by | by << 4 | y0 << 8 | y0 << 12) 993 sample = bx | by << 4
994 return (sample, sample if name == "ps_texoff_forms" else 0x0761, x0 | bx << 4 | bx << 8 | x0 << 12,
995 by | by << 4 | y0 << 8 | y0 << 12)
981 996
982 997
983# LEONIDA_TEXOFF_FALLBACK=1 (set for build.py too): image_sample*_o was translated with --texel-offset-fallback, so 998# LEONIDA_TEXOFF_FALLBACK=1 (set for build.py too): image_sample*_o was translated with --texel-offset-fallback, so
@@ -985,7 +1000,7 @@ def texoff_words(px, py):
985TEXOFF_FALLBACK = os.environ.get("LEONIDA_TEXOFF_FALLBACK") == "1" 1000TEXOFF_FALLBACK = os.environ.get("LEONIDA_TEXOFF_FALLBACK") == "1"
986 1001
987 1002
988def texoff_problem(data, output, all_offsets=None): 1003def texoff_problem(data, output, all_offsets=None, name="ps_texoff"):
989 """Judge ps_texoff's 64x64 RGBA32 dump: (failure text or "", what was covered). The +16 / -32 sample (bits 8-15 1004 """Judge ps_texoff's 64x64 RGBA32 dump: (failure text or "", what was covered). The +16 / -32 sample (bits 8-15
990 of .y) is only defined, and so only judged, where vk_texture_test printed texel offset limits that cover it.""" 1005 of .y) is only defined, and so only judged, where vk_texture_test printed texel offset limits that cover it."""
991 m = re.search(r"texel offset limits: (-?\d+)\.\.(-?\d+)", output) 1006 m = re.search(r"texel offset limits: (-?\d+)\.\.(-?\d+)", output)
@@ -994,18 +1009,22 @@ def texoff_problem(data, output, all_offsets=None):
994 wide = True # the offset is a coordinate shift: no device limit applies 1009 wide = True # the offset is a coordinate shift: no device limit applies
995 if len(data) != 64 * 64 * 16: 1010 if len(data) != 64 * 64 * 16:
996 return "vk_texture_test returned an unexpected pixel count", "" 1011 return "vk_texture_test returned an unexpected pixel count", ""
1012 if name == "ps_texoff_forms":
1013 wide = True # every offset there is in -4..3, inside Vulkan's guaranteed -8..7
997 keep = (0xFFFFFFFF, 0xFFFFFFFF if wide else 0xFFFF00FF, 0xFFFFFFFF, 0xFFFFFFFF) 1014 keep = (0xFFFFFFFF, 0xFFFFFFFF if wide else 0xFFFF00FF, 0xFFFFFFFF, 0xFFFFFFFF)
998 px = list(struct.iter_unpack("<4I", data)) 1015 px = list(struct.iter_unpack("<4I", data))
999 bad = [(i, got) for i, got in enumerate(px) 1016 bad = [(i, got) for i, got in enumerate(px)
1000 if any((g ^ w) & k for g, w, k in zip(got, texoff_words(i % 64, i // 64), keep))] 1017 if any((g ^ w) & k for g, w, k in zip(got, texoff_words(i % 64, i // 64, name), keep))]
1001 limits = f"{m.group(1)}..{m.group(2)}" if m else "unknown" 1018 limits = f"{m.group(1)}..{m.group(2)}" if m else "unknown"
1002 covered = ("offsets +16/-32 judged" + (" (texel offset fallback)" if wide and not ( 1019 covered = ("offsets +16/-32 judged" + (" (texel offset fallback)" if wide and not (
1003 bool(m) and int(m.group(1)) <= -32 and int(m.group(2)) >= 16) else "")) if wide else f"offsets +16/-32 not judged (device texel offset limits {limits})" 1020 bool(m) and int(m.group(1)) <= -32 and int(m.group(2)) >= 16) else "")) if wide else f"offsets +16/-32 not judged (device texel offset limits {limits})"
1021 if name == "ps_texoff_forms":
1022 covered = "offsets -4..3 on image_sample_o, image_sample_b_o and image_gather4_l_o"
1004 if not bad: 1023 if not bad:
1005 return "", covered 1024 return "", covered
1006 i, got = bad[0] 1025 i, got = bad[0]
1007 return (f"{len(bad)} of {len(px)} pixels differ; first at ({i % 64},{i // 64}): got {[hex(x) for x in got]}, " 1026 return (f"{len(bad)} of {len(px)} pixels differ; first at ({i % 64},{i // 64}): got {[hex(x) for x in got]}, "
1008 f"want {[hex(x) for x in texoff_words(i % 64, i // 64)]} ({covered})"), covered 1027 f"want {[hex(x) for x in texoff_words(i % 64, i // 64, name)]} ({covered})"), covered
1009 1028
1010 1029
1011def texoff_env(base=None): 1030def texoff_env(base=None):
@@ -1028,7 +1047,7 @@ def texoff_test(tools, spirv, name):
1028 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") 1047 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})")
1029 if code or not raw.is_file(): 1048 if code or not raw.is_file():
1030 return failure(code, out, 2) 1049 return failure(code, out, 2)
1031 return texoff_problem(raw.read_bytes(), out)[0] 1050 return texoff_problem(raw.read_bytes(), out, name=name)[0]
1032 1051
1033 1052
1034def store_words(name): 1053def store_words(name):
@@ -1178,6 +1197,27 @@ def interp_f16_high_problem(px):
1178 return "" if err < 2e-3 else f"f16 halves off by {err:.3g}" 1197 return "" if err < 2e-3 else f"f16 halves off by {err:.3g}"
1179 1198
1180 1199
1200def base_ids_test(tools, spirv):
1201 """vs_base_ids with ps_flat, drawn with firstVertex 16 and firstInstance 7: the VS input VGPRs are zero-based on
1202 the hardware, so every pixel must still see vertex 0 of instance 0 (0x101, 0x102), not 0x7111."""
1203 for n in ("vs_base_ids", "ps_flat"):
1204 if not os.path.isfile(os.path.join(spirv, n + ".spv")):
1205 return f"missing {n}.spv"
1206 env = dict(os.environ, VKH_DRAW="16,7")
1207 with tempfile.TemporaryDirectory(prefix="leonida-pixels-") as tmp:
1208 raw = Path(tmp) / "pixels.raw"
1209 code, out = run(os.path.join(tools, "vk_harness" + EXE), os.path.join(spirv, "vs_base_ids.spv"),
1210 os.path.join(spirv, "ps_flat.spv"), raw, env=env)
1211 if code == UNSUPPORTED:
1212 m = re.search(r"unsupported: .*", out)
1213 return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})")
1214 if code or not raw.is_file():
1215 return out if out.startswith("could not start") else "vk_harness failed or returned no pixels"
1216 px = list(struct.iter_unpack("<2I2f", raw.read_bytes()))
1217 wrong = [p for p in px if (p[0], p[1]) != (0x101, 0x102)]
1218 return "" if px and not wrong else f"{len(wrong)} of {len(px)} pixels differ, e.g. {hex(wrong[0][0]) if wrong else '-'}"
1219
1220
1181def wide_pixel_skip(name, out): 1221def wide_pixel_skip(name, out):
1182 """A Skip when `name` needs a 64-wide pixel stage (WIDE_PIXEL_TESTS) and vk_harness's output does not say that size 1222 """A Skip when `name` needs a 64-wide pixel stage (WIDE_PIXEL_TESTS) and vk_harness's output does not say that size
1183 was required of the fragment stage, else None.""" 1223 was required of the fragment stage, else None."""
@@ -1236,7 +1276,7 @@ def pixel_test(tools, spirv, name):
1236 return Skip("SKIP (computed I/J pairs need PerVertexKHR inputs: no --bary-fallback / --f16-interp-fallback)") 1276 return Skip("SKIP (computed I/J pairs need PerVertexKHR inputs: no --bary-fallback / --f16-interp-fallback)")
1237 if not os.path.isfile(path): 1277 if not os.path.isfile(path):
1238 return f"missing {name}.spv" 1278 return f"missing {name}.spv"
1239 if name in ("ps_texoff", "ps_texoff_implicit"): 1279 if name in ("ps_texoff", "ps_texoff_implicit", "ps_texoff_forms"):
1240 return texoff_test(tools, spirv, name) 1280 return texoff_test(tools, spirv, name)
1241 if name == "ps_interp_f16_high" and BARY_FALLBACK and not F16_HALVES: # with F16_HALVES it reads decoded halves 1281 if name == "ps_interp_f16_high" and BARY_FALLBACK and not F16_HALVES: # with F16_HALVES it reads decoded halves
1242 return Skip("SKIP (per-vertex interpolants need VK_KHR_fragment_shader_barycentric)") 1282 return Skip("SKIP (per-vertex interpolants need VK_KHR_fragment_shader_barycentric)")
@@ -1389,6 +1429,7 @@ def main():
1389 results.append((name, pixel_test(tools, spirv, name))) 1429 results.append((name, pixel_test(tools, spirv, name)))
1390 for name in TEXTURE_CONSTANTS: 1430 for name in TEXTURE_CONSTANTS:
1391 results.append((name, texture_constant_test(tools, spirv, name))) 1431 results.append((name, texture_constant_test(tools, spirv, name)))
1432 results.append(("vs_base_ids", base_ids_test(tools, spirv)))
1392 results.append(("ps_tex", bindless_test(tools, spirv))) 1433 results.append(("ps_tex", bindless_test(tools, spirv)))
1393 results.append(("ps_ssharp", sampler_test(tools, spirv))) 1434 results.append(("ps_ssharp", sampler_test(tools, spirv)))
1394 results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic"))) 1435 results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic")))
diff --git a/runtime/test/shaders/compute_fixture.py b/runtime/test/shaders/compute_fixture.py
index c5cdb438f..ec8dad37a 100644
--- a/runtime/test/shaders/compute_fixture.py
+++ b/runtime/test/shaders/compute_fixture.py
@@ -14,7 +14,7 @@ def compute_header(asm_path):
14 continue 14 continue
15 if not line.startswith(";"): 15 if not line.startswith(";"):
16 break 16 break
17 size = re.match(r";\s*group:\s*(\d+),(\d+),(\d+)", line) 17 size = re.match(r";\s*group:\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)", line)
18 if size: 18 if size:
19 group = tuple(map(int, size.groups())) 19 group = tuple(map(int, size.groups()))
20 elif line[1:].lstrip().startswith("rsrc2:"): 20 elif line[1:].lstrip().startswith("rsrc2:"):
diff --git a/runtime/test/shaders/cs_buf_fmt8.asm b/runtime/test/shaders/cs_buf_fmt8.asm
new file mode 100644
index 000000000..120eba435
--- /dev/null
+++ b/runtime/test/shaders/cs_buf_fmt8.asm
@@ -0,0 +1,46 @@
1; TEST-510: GFX10_FORMAT_8_UINT (code 5) loads on the GPU (docs/design.md, "Sub-dword MUBUF loads and
2; GFX10_FORMAT_8_UINT"; CPU-checked by tests/semantic/test_buffer_load_sub.py). Thread 0 seeds heap bytes 0x40..0x43
3; with 7f 80 ff 01. Every V# has base 0x40, stride 0, NUM_RECORDS 4 and OOB_SELECT 3 (RAW). Words, in out[0..7]:
4; 0..3 tbuffer_load_format_x format:[BUF_FMT_8_UINT] at 0..3, V# format 20 (32_UINT): the instruction's own format
5; is used, one byte zero-extended: 0x7f 0x80 0xff 0x01
6; 4 the same at 4: 4 + 1 > 4 -> 0
7; 5 the same at 1 with V# format 0 (INVALID): an MTBUF load of an invalid V# reads 0 even in range
8; 6, 7 buffer_load_format_xyzw at 2 with V# format 5 (8_UINT) and DST_SEL (X, 0, 1, 1): x = 0xff and w = integer 1
9; (not 1.0f, 0x3f800000)
10; One thread, no wave64 requirement.
11; Run: vk_compute_test cs_buf_fmt8.spv 1 dump -> out[0..7] = 0x0000007f 0x00000080 0x000000ff 0x00000001 0x00000000
12; 0x00000000 0x000000ff 0x00000001 (127 128 255 1 0 0 255 1).
13v_cmpx_eq_u32_e32 0, v0
14v_mov_b32 v1, 0x01ff807f
15buffer_store_dword v1, off, s[0:3], 0 offset:64
16s_waitcnt vmcnt(0)
17s_mov_b32 s4, 0x40
18s_mov_b32 s5, 0
19s_mov_b32 s6, 4
20s_mov_b32 s7, 0x31014fac
21s_mov_b32 s8, 0x40
22s_mov_b32 s9, 0
23s_mov_b32 s10, 4
24s_mov_b32 s11, 0x31000fac
25s_mov_b32 s12, 0x40
26s_mov_b32 s13, 0
27s_mov_b32 s14, 4
28s_mov_b32 s15, 0x31005244
29v_mov_b32 v20, 0
30v_mov_b32 v21, 1
31v_mov_b32 v22, 2
32v_mov_b32 v23, 3
33v_mov_b32 v24, 4
34tbuffer_load_format_x v10, v20, s[4:7], 0 format:[BUF_FMT_8_UINT] offen
35tbuffer_load_format_x v11, v21, s[4:7], 0 format:[BUF_FMT_8_UINT] offen
36tbuffer_load_format_x v12, v22, s[4:7], 0 format:[BUF_FMT_8_UINT] offen
37tbuffer_load_format_x v13, v23, s[4:7], 0 format:[BUF_FMT_8_UINT] offen
38tbuffer_load_format_x v14, v24, s[4:7], 0 format:[BUF_FMT_8_UINT] offen
39tbuffer_load_format_x v15, v21, s[8:11], 0 format:[BUF_FMT_8_UINT] offen
40buffer_load_format_xyzw v[30:33], v22, s[12:15], 0 offen
41s_waitcnt vmcnt(0)
42v_mov_b32 v16, v30
43v_mov_b32 v17, v33
44buffer_store_dwordx4 v[10:13], off, s[0:3], 0
45buffer_store_dwordx4 v[14:17], off, s[0:3], 0 offset:16
46s_endpgm
diff --git a/runtime/test/shaders/cs_buf_load_sub.asm b/runtime/test/shaders/cs_buf_load_sub.asm
new file mode 100644
index 000000000..48ffd4e47
--- /dev/null
+++ b/runtime/test/shaders/cs_buf_load_sub.asm
@@ -0,0 +1,44 @@
1; TEST-510: sub-dword MUBUF loads on the GPU (docs/design.md, "Sub-dword MUBUF loads and GFX10_FORMAT_8_UINT";
2; CPU-checked by tests/semantic/test_buffer_load_sub.py). Thread 0 seeds heap bytes 0x40..0x47 with 7f 80 ff 01 ab cd
3; 00 fe; the heap is 0xee-filled past them. The V# has base 0x40, stride 0, NUM_RECORDS 8 and OOB_SELECT 3 (RAW: an
4; element is in range when offset + size <= NUM_RECORDS; out of range reads 0 without touching memory). Words, in
5; out[0..7]:
6; 0 buffer_load_ubyte at 1: 0x80 zero-extended
7; 1 buffer_load_sbyte at 1: 0x80 -> 0xffffff80 sign-extended
8; 2 buffer_load_ushort at 2: ff 01 -> 0x01ff
9; 3 buffer_load_sshort at 0: 7f 80 -> 0xffff807f
10; 4 buffer_load_ushort at 3: 01 ab -> 0xab01 crosses into the next dword (3 + 2 <= 8)
11; 5 buffer_load_sshort at 5: cd 00 -> 0x000000cd positive, no sign bits
12; 6 buffer_load_ubyte at 8: 8 + 1 > 8 -> 0
13; 7 buffer_load_ushort at 7: 7 + 2 > 8 -> 0 a start-only check would read fe ee -> 0xeefe
14; One thread, no wave64 requirement.
15; Run: vk_compute_test cs_buf_load_sub.spv 1 dump -> out[0..7] = 0x00000080 0xffffff80 0x000001ff 0xffff807f
16; 0x0000ab01 0x000000cd 0x00000000 0x00000000 (128 4294967168 511 4294934655 43777 205 0 0).
17v_cmpx_eq_u32_e32 0, v0
18v_mov_b32 v1, 0x01ff807f
19v_mov_b32 v2, 0xfe00cdab
20buffer_store_dwordx2 v[1:2], off, s[0:3], 0 offset:64
21s_waitcnt vmcnt(0)
22s_mov_b32 s4, 0x40
23s_mov_b32 s5, 0
24s_mov_b32 s6, 8
25s_mov_b32 s7, 0x31016fac
26v_mov_b32 v20, 1
27v_mov_b32 v21, 2
28v_mov_b32 v22, 0
29v_mov_b32 v23, 3
30v_mov_b32 v24, 5
31v_mov_b32 v25, 8
32v_mov_b32 v26, 7
33buffer_load_ubyte v10, v20, s[4:7], 0 offen
34buffer_load_sbyte v11, v20, s[4:7], 0 offen
35buffer_load_ushort v12, v21, s[4:7], 0 offen
36buffer_load_sshort v13, v22, s[4:7], 0 offen
37buffer_load_ushort v14, v23, s[4:7], 0 offen
38buffer_load_sshort v15, v24, s[4:7], 0 offen
39buffer_load_ubyte v16, v25, s[4:7], 0 offen
40buffer_load_ushort v17, v26, s[4:7], 0 offen
41s_waitcnt vmcnt(0)
42buffer_store_dwordx4 v[10:13], off, s[0:3], 0
43buffer_store_dwordx4 v[14:17], off, s[0:3], 0 offset:16
44s_endpgm
diff --git a/runtime/test/shaders/cs_f64_add.asm b/runtime/test/shaders/cs_f64_add.asm
new file mode 100644
index 000000000..4dbba4123
--- /dev/null
+++ b/runtime/test/shaders/cs_f64_add.asm
@@ -0,0 +1,10 @@
1; group: 1,1,1
2; Store binary64 (0.75 + 0.5) * 2 = 2.5 as low/high words: 0x00000000, 0x40040000.
3v_mov_b32 v0, 0
4v_mov_b32 v1, 0x3fe80000
5v_mov_b32 v2, 0
6v_mov_b32 v3, 0x3fe00000
7v_add_f64 v[4:5], v[0:1], v[2:3] mul:2
8v_mov_b32 v6, 0
9buffer_store_dwordx2 v[4:5], v6, s[0:3], 0 offen
10s_endpgm
diff --git a/runtime/test/shaders/cs_resinfo.asm b/runtime/test/shaders/cs_resinfo.asm
index 41ecaf7f7..88be15028 100644
--- a/runtime/test/shaders/cs_resinfo.asm
+++ b/runtime/test/shaders/cs_resinfo.asm
@@ -1,8 +1,9 @@
1; image_get_resinfo on a 16x4 image with five mip levels. RDNA2 ISA (MIMG): the address register holds a mip level, 1; image_get_resinfo on a 16x4 image with five mip levels. RDNA2 ISA (MIMG): the address register holds a mip level,
2; there is no sampler, and the result is four integers, {num_mip_levels, depth, height, width} in VGPRs 3..0, of 2; there is no sampler, and the result is four integers, {num_mip_levels, depth, height, width} in VGPRs 3..0, of
3; which dmask keeps some and packs them into consecutive registers. Width and height are those of the level asked 3; which dmask keeps some and packs them into consecutive registers. Width and height are those of the level asked
4; for (halved per level, never below 1), depth is 1 for an image that is neither 3D nor an array, and the level 4; for (halved per level, never below 1), the depth word is 0 for a 2D image (not the T#'s DEPTH field + 1), and the
5; count is that of the view. 5; level count is that of the view; past the last level width, height and depth are 0 (both measured on RDNA2 gfx1036
6; with tools/image_query_probe.py, SHADER-388).
6; Run: vk_store_test cs_resinfo.spv words 7; Run: vk_store_test cs_resinfo.spv words
7; The T# in s[8:15] is the one of that image, as Mesa's gfx10 register database lays it out (and as 8; The T# in s[8:15] is the one of that image, as Mesa's gfx10 register database lays it out (and as
8; runtime/src/gfx10_descriptors.h writes it): word 1 = FORMAT 56 (rgba8 unorm) << 20 | (width - 1 = 15) low two bits 9; runtime/src/gfx10_descriptors.h writes it): word 1 = FORMAT 56 (rgba8 unorm) << 20 | (width - 1 = 15) low two bits
@@ -10,13 +11,14 @@
10; TYPE 9 (2D) << 28, word 5 = MAX_MIP 4 << 4. vk_store_test binds a 16x4 rgba8 image with five levels behind exactly 11; TYPE 9 (2D) << 28, word 5 = MAX_MIP 4 << 4. vk_store_test binds a 16x4 rgba8 image with five levels behind exactly
11; these eight words. Thread 0 stores each result word into its own texel of the uint image (T# 0x2000...), texel 12; these eight words. Thread 0 stores each result word into its own texel of the uint image (T# 0x2000...), texel
12; i = 8y + x: 13; i = 8y + x:
13; level 0, dmask 0xf -> words 0..3 = 16 4 1 5 14; level 0, dmask 0xf -> words 0..3 = 16 4 0 5
14; level 1, dmask 0xf -> words 4..7 = 8 2 1 5 15; level 1, dmask 0xf -> words 4..7 = 8 2 0 5
15; level 3, dmask 0xf -> words 8..11 = 2 1 1 5 (4 >> 3 would be 0: the height stays 1) 16; level 3, dmask 0xf -> words 8..11 = 2 1 0 5 (4 >> 3 would be 0: the height stays 1)
16; level 2, dmask 0x3 -> words 12..13 = 4 1 width and height 17; level 2, dmask 0x3 -> words 12..13 = 4 1 width and height
17; word 14 = 0xabcd the register after them is not written 18; word 14 = 0xabcd the register after them is not written
18; level 1, dmask 0xa -> words 16..17 = 2 5 height and level count, packed into two registers 19; level 1, dmask 0xa -> words 16..17 = 2 5 height and level count, packed into two registers
19; level 4, dmask 0x8 -> word 18 = 5 the level count alone 20; level 4, dmask 0x8 -> word 18 = 5 the level count alone
21; level 5, dmask 0xf -> words 20..23 = 0 0 0 5 past the last level
20; Every other word keeps the tool's fill, 100 + i, and the sint image its -2i. 22; Every other word keeps the tool's fill, 100 + i, and the sint image its -2i.
21v_cmpx_eq_u32_e32 0, v0 23v_cmpx_eq_u32_e32 0, v0
22s_mov_b32 s8, 0x4000 24s_mov_b32 s8, 0x4000
@@ -93,4 +95,16 @@ image_get_resinfo v13, v3, s[8:15] dmask:0x8 dim:SQ_RSRC_IMG_2D
93s_waitcnt vmcnt(0) 95s_waitcnt vmcnt(0)
94v_mov_b32_e32 v1, 2 96v_mov_b32_e32 v1, 2
95image_store v13, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm 97image_store v13, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
98v_mov_b32_e32 v3, 5
99image_get_resinfo v[4:7], v3, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D
100s_waitcnt vmcnt(0)
101v_mov_b32_e32 v2, 2
102v_mov_b32_e32 v1, 4
103image_store v4, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
104v_mov_b32_e32 v1, 5
105image_store v5, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
106v_mov_b32_e32 v1, 6
107image_store v6, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
108v_mov_b32_e32 v1, 7
109image_store v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm
96s_endpgm 110s_endpgm
diff --git a/runtime/test/shaders/ps_sdwa_dword_hi.asm b/runtime/test/shaders/ps_sdwa_dword_hi.asm
new file mode 100644
index 000000000..09f3740b7
--- /dev/null
+++ b/runtime/test/shaders/ps_sdwa_dword_hi.asm
@@ -0,0 +1,27 @@
1; 16-bit SDWA results written with dst_sel:DWORD. The non-SDWA f16 VOP1/VOP2 forms keep the destination's high
2; half (docs/design.md, 16-bit results), but an SDWA destination with dst_sel:DWORD takes the whole dword: the
3; 16-bit result zero-extended, whatever dst_unused says. Measured natively on an AMD Radeon iGPU (gfx1036, RDNA2,
4; Windows driver 26.10.1) through tools/hw_oracle with this exact program: 0x00004000, 0x00000003, 0x00004700,
5; 0x0000c000; the same four ops with dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE gave 0xdead4000, 0xdead0003,
6; 0xdead4700, 0xdeadc000 (the high half kept), so the zero comes from dst_sel:DWORD.
7; Every destination starts as 0xdeadbeef. Sources: v2 = 0x12343c00 (WORD_0 = 1.0), v4 = 0xc0004200 (WORD_0 = 3.0,
8; WORD_1 = -2.0), v6 = 0x00070000 (WORD_1 = 7).
9; x: v_add_f16 1.0 + 1.0 = 2.0 = 0x4000, UNUSED_PRESERVE -> 0x00004000
10; y: v_cvt_u16_f16 of 3.0 = 3 = 0x0003, UNUSED_PAD -> 0x00000003
11; z: v_cvt_f16_u16 of 7 = 7.0 = 0x4700 (exact), UNUSED_PRESERVE -> 0x00004700
12; w: v_mul_f16 1.0 * -2.0 = -2.0 = 0xc000, UNUSED_SEXT -> 0x0000c000 (no sign copies above it)
13; All four are small positive denormal floats, kept bit-exact by the RGBA32F target (as 0x000000f1 in ps_sdwa).
14; Expected mrt0 bits: 0x00004000, 0x00000003, 0x00004700, 0x0000c000
15v_mov_b32 v1, 0xdeadbeef
16v_mov_b32 v2, 0x12343c00
17v_mov_b32 v3, 0xdeadbeef
18v_mov_b32 v4, 0xc0004200
19v_mov_b32 v5, 0xdeadbeef
20v_mov_b32 v6, 0x70000
21v_mov_b32 v7, 0xdeadbeef
22v_add_f16_sdwa v1, v2, v2 dst_sel:DWORD dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_0
23v_cvt_u16_f16_sdwa v3, v4 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0
24v_cvt_f16_u16_sdwa v5, v6 dst_sel:DWORD dst_unused:UNUSED_PRESERVE src0_sel:WORD_1
25v_mul_f16_sdwa v7, v2, v4 dst_sel:DWORD dst_unused:UNUSED_SEXT src0_sel:WORD_0 src1_sel:WORD_1
26exp mrt0 v1, v3, v5, v7 done vm
27s_endpgm
diff --git a/runtime/test/shaders/ps_texoff_forms.asm b/runtime/test/shaders/ps_texoff_forms.asm
new file mode 100644
index 000000000..9076e4a01
--- /dev/null
+++ b/runtime/test/shaders/ps_texoff_forms.asm
@@ -0,0 +1,103 @@
1; Texel offsets on the image_sample*_o forms ps_texoff does not run (SHADER-337): image_sample_o (implicit LOD),
2; image_sample_b_o (LOD bias) and image_gather4_l_o (explicit LOD). docs/design.md, "Texel offsets": the first address
3; dword packs signed 6-bit offsets, x = [5:0], y = [13:8]; the bias (_b) or the LOD (_l) follows the coordinates as
4; the MIMG address order puts them: _b_o = {offset, bias, s, t}, _l_o = {offset, s, t, lod}.
5; Run: vk_texture_test <vs> ps_texoff_forms.spv out.raw 2 92 0 0 0 (VKT_NEED_MAINTENANCE8=1: exit 77 without it)
6; Same set-up as ps_texoff.asm: an 8x8 RGBA8 texture whose texel (x, y) is r = 32x/255, g = 32y/255, one mip, a
7; point sampler that clamps to the edge (S# 0x92), 64x64 pixels with attr0.xy = ((px + 0.5) / 64, (py + 0.5) / 64).
8; Each sampled channel c reads back as its texel coordinate through rndne(c * 255/32).
9;
10; Every sample uses the per-pixel offset of ps_texoff's .x: ox = bx - 4, oy = by - 4 (bx = px >> 3, by = py >> 3),
11; all 64 pairs in -4..3, none clamped by the sample. Expected mrt0 words, derived from the rule and the texture:
12; .x image_sample_o at the centre of texel (4, 4); the coordinates are the same in every pixel, so the implicit
13; derivatives are 0 and the one mip is sampled: texel (bx, by), word = bx | by << 4.
14; .y image_sample_b_o with bias 0.0 at the same point: word = bx | by << 4.
15; .z image_gather4_l_o of red (dmask 1, LOD 0.0) at uv (0.5, 0.5), the corner of texels 3..4: X0 = max(bx - 1, 0),
16; X1 = bx; gather order (i0, j1), (i1, j1), (i1, j0), (i0, j0): word = X0 | X1 << 4 | X1 << 8 | X0 << 12.
17; .w the same gather of green: word = Y1 | Y1 << 4 | Y0 << 8 | Y0 << 12 (Y0 = max(by - 1, 0), Y1 = by).
18; .z and .w are ps_texoff's gather words (check.py texoff_words). Dropping the offset gives 0x44 in .x and .y; x and y
19; swapped give by | bx << 4.
20s_load_dwordx8 s[8:15], s[2:3], 0
21s_mov_b32 s16, 0x92
22s_mov_b32 s17, 0
23s_mov_b32 s18, 0
24s_mov_b32 s19, 0
25v_interp_p1_f32_e32 v2, v0, attr0.x
26v_interp_p2_f32_e32 v2, v1, attr0.x
27v_interp_p1_f32_e32 v3, v0, attr0.y
28v_interp_p2_f32_e32 v3, v1, attr0.y
29v_mul_f32_e32 v2, 0x41000000, v2
30v_mul_f32_e32 v3, 0x41000000, v3
31v_cvt_u32_f32_e32 v2, v2
32v_cvt_u32_f32_e32 v3, v3
33v_add_nc_u32_e32 v2, -4, v2
34v_add_nc_u32_e32 v3, -4, v3
35v_and_b32_e32 v2, 63, v2
36v_and_b32_e32 v3, 63, v3
37v_lshl_or_b32 v10, v3, 8, v2
38v_mov_b32_e32 v11, 0x3f100000
39v_mov_b32_e32 v12, 0x3f100000
40s_waitcnt lgkmcnt(0)
41image_sample_o v[4:5], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D
42v_mov_b32_e32 v24, v10
43v_mov_b32_e32 v25, 0
44v_mov_b32_e32 v26, 0x3f100000
45v_mov_b32_e32 v27, 0x3f100000
46image_sample_b_o v[6:7], v[24:27], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D
47v_mov_b32_e32 v13, v10
48v_mov_b32_e32 v14, 0.5
49v_mov_b32_e32 v15, 0.5
50v_mov_b32_e32 v28, 0
51v_mov_b32_e32 v29, v10
52v_mov_b32_e32 v30, 0.5
53v_mov_b32_e32 v31, 0.5
54v_mov_b32_e32 v32, 0
55image_gather4_l_o v[16:19], v[29:32], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D
56image_gather4_l_o v[20:23], v[29:32], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D
57s_waitcnt vmcnt(0)
58v_mul_f32_e32 v4, 0x40ff0000, v4
59v_rndne_f32_e32 v4, v4
60v_cvt_u32_f32_e32 v4, v4
61v_mul_f32_e32 v5, 0x40ff0000, v5
62v_rndne_f32_e32 v5, v5
63v_cvt_u32_f32_e32 v5, v5
64v_mul_f32_e32 v6, 0x40ff0000, v6
65v_rndne_f32_e32 v6, v6
66v_cvt_u32_f32_e32 v6, v6
67v_mul_f32_e32 v7, 0x40ff0000, v7
68v_rndne_f32_e32 v7, v7
69v_cvt_u32_f32_e32 v7, v7
70v_mul_f32_e32 v16, 0x40ff0000, v16
71v_rndne_f32_e32 v16, v16
72v_cvt_u32_f32_e32 v16, v16
73v_mul_f32_e32 v17, 0x40ff0000, v17
74v_rndne_f32_e32 v17, v17
75v_cvt_u32_f32_e32 v17, v17
76v_mul_f32_e32 v18, 0x40ff0000, v18
77v_rndne_f32_e32 v18, v18
78v_cvt_u32_f32_e32 v18, v18
79v_mul_f32_e32 v19, 0x40ff0000, v19
80v_rndne_f32_e32 v19, v19
81v_cvt_u32_f32_e32 v19, v19
82v_mul_f32_e32 v20, 0x40ff0000, v20
83v_rndne_f32_e32 v20, v20
84v_cvt_u32_f32_e32 v20, v20
85v_mul_f32_e32 v21, 0x40ff0000, v21
86v_rndne_f32_e32 v21, v21
87v_cvt_u32_f32_e32 v21, v21
88v_mul_f32_e32 v22, 0x40ff0000, v22
89v_rndne_f32_e32 v22, v22
90v_cvt_u32_f32_e32 v22, v22
91v_mul_f32_e32 v23, 0x40ff0000, v23
92v_rndne_f32_e32 v23, v23
93v_cvt_u32_f32_e32 v23, v23
94v_lshl_or_b32 v40, v5, 4, v4
95v_lshl_or_b32 v41, v7, 4, v6
96v_lshl_or_b32 v42, v17, 4, v16
97v_lshl_or_b32 v42, v18, 8, v42
98v_lshl_or_b32 v42, v19, 12, v42
99v_lshl_or_b32 v43, v21, 4, v20
100v_lshl_or_b32 v43, v22, 8, v43
101v_lshl_or_b32 v43, v23, 12, v43
102exp mrt0 v40, v41, v42, v43 done vm
103s_endpgm
diff --git a/runtime/test/shaders/ps_vcmp_f16.asm b/runtime/test/shaders/ps_vcmp_f16.asm
new file mode 100644
index 000000000..0c1a17733
--- /dev/null
+++ b/runtime/test/shaders/ps_vcmp_f16.asm
@@ -0,0 +1,384 @@
1; 16-bit float VOPC compares, e32 form (VCC destination): v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16
2; (all 16 IEEE predicates) on seven operand pairs covering the four relations less, greater, equal and unordered, with
3; +-0, +-inf, quiet and signalling NaN and f16 denormals, and junk in the high halves of the register operands.
4; RDNA2 ISA (VOPC, _F16): the compare reads S0.f16 and S1.f16 (bits 15:0 of the operands only) and writes one bit per lane
5; to VCC. Per the ISA pseudocode, for the relation of S0 to S1:
6; F = 0, TRU = 1; LT: S0 < S1; EQ: S0 == S1; LE: S0 <= S1; GT: S0 > S1; LG: S0 <> S1 (less or greater);
7; GE: S0 >= S1; O: !isNAN(S0) && !isNAN(S1); U: isNAN(S0) || isNAN(S1); NGE = !(S0 >= S1); NLG = !(S0 <> S1);
8; NGT = !(S0 > S1); NLE = !(S0 <= S1); NEQ = !(S0 == S1); NLT = !(S0 < S1).
9; Every ordered compare with a NaN operand is false, so the N* forms (negations) are true for an unordered pair; +0 == -0;
10; the f16 denormals 0x0001 and 0x0002 are kept (they are different numbers, 0x0001 < 0x0002). Cases (A = src0, B = src1,
11; the VGPR operand is shown as junk:value, junk = high half that must be ignored):
12; k0: A = inline 1.0 (0x3c00), B = 0x1234:0x4000 (2.0) less
13; k1: A = inline 2.0 (0x4000), B = 0xabcd:0x3c00 (1.0) greater
14; k2: A = inline 0 (+0), B = 0xffff:0x8000 (-0) equal
15; k3: A = 0xffff:0x7e00 (qNaN), B = 0x0001:0x3c00 (1.0) unordered
16; k4: A = 0x5555:0x3c00 (1.0), B = 0x7c00:0x7c01 (sNaN) unordered
17; k5: A = 0x0001:0x7c00 (+inf), B = 0xbeef:0xfc00 (-inf) greater
18; k6: A = 0xdead:0x0001 (denormal), B = 0x8000:0x0002 (denormal) less
19; Relation sets: LESS = {k0,k6} = 0x41, GREATER = {k1,k5} = 0x22, EQUAL = {k2} = 0x04, UNORDERED = {k3,k4} = 0x18.
20; Mask of an op (bit k = result on case k) is the union of the sets it is true for:
21; f 0x00 lt 0x41 eq 0x04 le 0x45 gt 0x22 lg 0x63 ge 0x26 o 0x67
22; u 0x18 nge 0x59 nlg 0x1c ngt 0x5d nle 0x3a neq 0x7b nlt 0x3e tru 0x7f
23; Word w holds ops 4w..4w+3 (the order above), op j of the word at bit 7*j + k, plus bit 30 so the float export never
24; sees a denormal or NaN pattern:
25; word 0 = 0x40000000 | 0x00 | 0x41<<7 | 0x04<<14 | 0x45<<21 = 0x40000000 + 0x2080 + 0x10000 + 0x8a00000 = 0x48a12080
26; word 1 = 0x40000000 | 0x22 | 0x63<<7 | 0x26<<14 | 0x67<<21 = 0x40000000 + 0x31a2 + 0x98000 + 0xce00000 = 0x4ce9b1a2
27; word 2 = 0x40000000 | 0x18 | 0x59<<7 | 0x1c<<14 | 0x5d<<21 = 0x40000000 + 0x2c98 + 0x70000 + 0xba00000 = 0x4ba72c98
28; word 3 = 0x40000000 | 0x3a | 0x7b<<7 | 0x3e<<14 | 0x7f<<21 = 0x40000000 + 0x3dba + 0xf8000 + 0xfe00000 = 0x4fefbdba
29; A translation that compared the whole 32-bit registers, flushed the denormals (k6 would become equal), ordered a NaN
30; (k3, k4 true for lt/gt/le/ge...), or took -0 below +0 (k2) moves bits in the words.
31; Expected mrt0 bits: 0x48a12080, 0x4ce9b1a2, 0x4ba72c98, 0x4fefbdba
32v_mov_b32_e32 v8, 0x12344000
33v_mov_b32_e32 v9, 0xabcd3c00
34v_mov_b32_e32 v10, 0xffff8000
35v_mov_b32_e32 v4, 0xffff7e00
36v_mov_b32_e32 v11, 0x00013c00
37v_mov_b32_e32 v5, 0x55553c00
38v_mov_b32_e32 v12, 0x7c007c01
39v_mov_b32_e32 v6, 0x00017c00
40v_mov_b32_e32 v13, 0xbeeffc00
41v_mov_b32_e32 v7, 0xdead0001
42v_mov_b32_e32 v14, 0x80000002
43v_mov_b32_e32 v40, 0x40000000
44v_cmp_f_f16_e32 vcc_lo, 1.0, v8
45v_cndmask_b32_e64 v20, 0, 1, vcc_lo
46v_lshl_or_b32 v40, v20, 0, v40
47v_cmp_f_f16_e32 vcc_lo, 2.0, v9
48v_cndmask_b32_e64 v20, 0, 1, vcc_lo
49v_lshl_or_b32 v40, v20, 1, v40
50v_cmp_f_f16_e32 vcc_lo, 0, v10
51v_cndmask_b32_e64 v20, 0, 1, vcc_lo
52v_lshl_or_b32 v40, v20, 2, v40
53v_cmp_f_f16_e32 vcc_lo, v4, v11
54v_cndmask_b32_e64 v20, 0, 1, vcc_lo
55v_lshl_or_b32 v40, v20, 3, v40
56v_cmp_f_f16_e32 vcc_lo, v5, v12
57v_cndmask_b32_e64 v20, 0, 1, vcc_lo
58v_lshl_or_b32 v40, v20, 4, v40
59v_cmp_f_f16_e32 vcc_lo, v6, v13
60v_cndmask_b32_e64 v20, 0, 1, vcc_lo
61v_lshl_or_b32 v40, v20, 5, v40
62v_cmp_f_f16_e32 vcc_lo, v7, v14
63v_cndmask_b32_e64 v20, 0, 1, vcc_lo
64v_lshl_or_b32 v40, v20, 6, v40
65v_cmp_lt_f16_e32 vcc_lo, 1.0, v8
66v_cndmask_b32_e64 v20, 0, 1, vcc_lo
67v_lshl_or_b32 v40, v20, 7, v40
68v_cmp_lt_f16_e32 vcc_lo, 2.0, v9
69v_cndmask_b32_e64 v20, 0, 1, vcc_lo
70v_lshl_or_b32 v40, v20, 8, v40
71v_cmp_lt_f16_e32 vcc_lo, 0, v10
72v_cndmask_b32_e64 v20, 0, 1, vcc_lo
73v_lshl_or_b32 v40, v20, 9, v40
74v_cmp_lt_f16_e32 vcc_lo, v4, v11
75v_cndmask_b32_e64 v20, 0, 1, vcc_lo
76v_lshl_or_b32 v40, v20, 10, v40
77v_cmp_lt_f16_e32 vcc_lo, v5, v12
78v_cndmask_b32_e64 v20, 0, 1, vcc_lo
79v_lshl_or_b32 v40, v20, 11, v40
80v_cmp_lt_f16_e32 vcc_lo, v6, v13
81v_cndmask_b32_e64 v20, 0, 1, vcc_lo
82v_lshl_or_b32 v40, v20, 12, v40
83v_cmp_lt_f16_e32 vcc_lo, v7, v14
84v_cndmask_b32_e64 v20, 0, 1, vcc_lo
85v_lshl_or_b32 v40, v20, 13, v40
86v_cmp_eq_f16_e32 vcc_lo, 1.0, v8
87v_cndmask_b32_e64 v20, 0, 1, vcc_lo
88v_lshl_or_b32 v40, v20, 14, v40
89v_cmp_eq_f16_e32 vcc_lo, 2.0, v9
90v_cndmask_b32_e64 v20, 0, 1, vcc_lo
91v_lshl_or_b32 v40, v20, 15, v40
92v_cmp_eq_f16_e32 vcc_lo, 0, v10
93v_cndmask_b32_e64 v20, 0, 1, vcc_lo
94v_lshl_or_b32 v40, v20, 16, v40
95v_cmp_eq_f16_e32 vcc_lo, v4, v11
96v_cndmask_b32_e64 v20, 0, 1, vcc_lo
97v_lshl_or_b32 v40, v20, 17, v40
98v_cmp_eq_f16_e32 vcc_lo, v5, v12
99v_cndmask_b32_e64 v20, 0, 1, vcc_lo
100v_lshl_or_b32 v40, v20, 18, v40
101v_cmp_eq_f16_e32 vcc_lo, v6, v13
102v_cndmask_b32_e64 v20, 0, 1, vcc_lo
103v_lshl_or_b32 v40, v20, 19, v40
104v_cmp_eq_f16_e32 vcc_lo, v7, v14
105v_cndmask_b32_e64 v20, 0, 1, vcc_lo
106v_lshl_or_b32 v40, v20, 20, v40
107v_cmp_le_f16_e32 vcc_lo, 1.0, v8
108v_cndmask_b32_e64 v20, 0, 1, vcc_lo
109v_lshl_or_b32 v40, v20, 21, v40
110v_cmp_le_f16_e32 vcc_lo, 2.0, v9
111v_cndmask_b32_e64 v20, 0, 1, vcc_lo
112v_lshl_or_b32 v40, v20, 22, v40
113v_cmp_le_f16_e32 vcc_lo, 0, v10
114v_cndmask_b32_e64 v20, 0, 1, vcc_lo
115v_lshl_or_b32 v40, v20, 23, v40
116v_cmp_le_f16_e32 vcc_lo, v4, v11
117v_cndmask_b32_e64 v20, 0, 1, vcc_lo
118v_lshl_or_b32 v40, v20, 24, v40
119v_cmp_le_f16_e32 vcc_lo, v5, v12
120v_cndmask_b32_e64 v20, 0, 1, vcc_lo
121v_lshl_or_b32 v40, v20, 25, v40
122v_cmp_le_f16_e32 vcc_lo, v6, v13
123v_cndmask_b32_e64 v20, 0, 1, vcc_lo
124v_lshl_or_b32 v40, v20, 26, v40
125v_cmp_le_f16_e32 vcc_lo, v7, v14
126v_cndmask_b32_e64 v20, 0, 1, vcc_lo
127v_lshl_or_b32 v40, v20, 27, v40
128v_mov_b32_e32 v41, 0x40000000
129v_cmp_gt_f16_e32 vcc_lo, 1.0, v8
130v_cndmask_b32_e64 v20, 0, 1, vcc_lo
131v_lshl_or_b32 v41, v20, 0, v41
132v_cmp_gt_f16_e32 vcc_lo, 2.0, v9
133v_cndmask_b32_e64 v20, 0, 1, vcc_lo
134v_lshl_or_b32 v41, v20, 1, v41
135v_cmp_gt_f16_e32 vcc_lo, 0, v10
136v_cndmask_b32_e64 v20, 0, 1, vcc_lo
137v_lshl_or_b32 v41, v20, 2, v41
138v_cmp_gt_f16_e32 vcc_lo, v4, v11
139v_cndmask_b32_e64 v20, 0, 1, vcc_lo
140v_lshl_or_b32 v41, v20, 3, v41
141v_cmp_gt_f16_e32 vcc_lo, v5, v12
142v_cndmask_b32_e64 v20, 0, 1, vcc_lo
143v_lshl_or_b32 v41, v20, 4, v41
144v_cmp_gt_f16_e32 vcc_lo, v6, v13
145v_cndmask_b32_e64 v20, 0, 1, vcc_lo
146v_lshl_or_b32 v41, v20, 5, v41
147v_cmp_gt_f16_e32 vcc_lo, v7, v14
148v_cndmask_b32_e64 v20, 0, 1, vcc_lo
149v_lshl_or_b32 v41, v20, 6, v41
150v_cmp_lg_f16_e32 vcc_lo, 1.0, v8
151v_cndmask_b32_e64 v20, 0, 1, vcc_lo
152v_lshl_or_b32 v41, v20, 7, v41
153v_cmp_lg_f16_e32 vcc_lo, 2.0, v9
154v_cndmask_b32_e64 v20, 0, 1, vcc_lo
155v_lshl_or_b32 v41, v20, 8, v41
156v_cmp_lg_f16_e32 vcc_lo, 0, v10
157v_cndmask_b32_e64 v20, 0, 1, vcc_lo
158v_lshl_or_b32 v41, v20, 9, v41
159v_cmp_lg_f16_e32 vcc_lo, v4, v11
160v_cndmask_b32_e64 v20, 0, 1, vcc_lo
161v_lshl_or_b32 v41, v20, 10, v41
162v_cmp_lg_f16_e32 vcc_lo, v5, v12
163v_cndmask_b32_e64 v20, 0, 1, vcc_lo
164v_lshl_or_b32 v41, v20, 11, v41
165v_cmp_lg_f16_e32 vcc_lo, v6, v13
166v_cndmask_b32_e64 v20, 0, 1, vcc_lo
167v_lshl_or_b32 v41, v20, 12, v41
168v_cmp_lg_f16_e32 vcc_lo, v7, v14
169v_cndmask_b32_e64 v20, 0, 1, vcc_lo
170v_lshl_or_b32 v41, v20, 13, v41
171v_cmp_ge_f16_e32 vcc_lo, 1.0, v8
172v_cndmask_b32_e64 v20, 0, 1, vcc_lo
173v_lshl_or_b32 v41, v20, 14, v41
174v_cmp_ge_f16_e32 vcc_lo, 2.0, v9
175v_cndmask_b32_e64 v20, 0, 1, vcc_lo
176v_lshl_or_b32 v41, v20, 15, v41
177v_cmp_ge_f16_e32 vcc_lo, 0, v10
178v_cndmask_b32_e64 v20, 0, 1, vcc_lo
179v_lshl_or_b32 v41, v20, 16, v41
180v_cmp_ge_f16_e32 vcc_lo, v4, v11
181v_cndmask_b32_e64 v20, 0, 1, vcc_lo
182v_lshl_or_b32 v41, v20, 17, v41
183v_cmp_ge_f16_e32 vcc_lo, v5, v12
184v_cndmask_b32_e64 v20, 0, 1, vcc_lo
185v_lshl_or_b32 v41, v20, 18, v41
186v_cmp_ge_f16_e32 vcc_lo, v6, v13
187v_cndmask_b32_e64 v20, 0, 1, vcc_lo
188v_lshl_or_b32 v41, v20, 19, v41
189v_cmp_ge_f16_e32 vcc_lo, v7, v14
190v_cndmask_b32_e64 v20, 0, 1, vcc_lo
191v_lshl_or_b32 v41, v20, 20, v41
192v_cmp_o_f16_e32 vcc_lo, 1.0, v8
193v_cndmask_b32_e64 v20, 0, 1, vcc_lo
194v_lshl_or_b32 v41, v20, 21, v41
195v_cmp_o_f16_e32 vcc_lo, 2.0, v9
196v_cndmask_b32_e64 v20, 0, 1, vcc_lo
197v_lshl_or_b32 v41, v20, 22, v41
198v_cmp_o_f16_e32 vcc_lo, 0, v10
199v_cndmask_b32_e64 v20, 0, 1, vcc_lo
200v_lshl_or_b32 v41, v20, 23, v41
201v_cmp_o_f16_e32 vcc_lo, v4, v11
202v_cndmask_b32_e64 v20, 0, 1, vcc_lo
203v_lshl_or_b32 v41, v20, 24, v41
204v_cmp_o_f16_e32 vcc_lo, v5, v12
205v_cndmask_b32_e64 v20, 0, 1, vcc_lo
206v_lshl_or_b32 v41, v20, 25, v41
207v_cmp_o_f16_e32 vcc_lo, v6, v13
208v_cndmask_b32_e64 v20, 0, 1, vcc_lo
209v_lshl_or_b32 v41, v20, 26, v41
210v_cmp_o_f16_e32 vcc_lo, v7, v14
211v_cndmask_b32_e64 v20, 0, 1, vcc_lo
212v_lshl_or_b32 v41, v20, 27, v41
213v_mov_b32_e32 v42, 0x40000000
214v_cmp_u_f16_e32 vcc_lo, 1.0, v8
215v_cndmask_b32_e64 v20, 0, 1, vcc_lo
216v_lshl_or_b32 v42, v20, 0, v42
217v_cmp_u_f16_e32 vcc_lo, 2.0, v9
218v_cndmask_b32_e64 v20, 0, 1, vcc_lo
219v_lshl_or_b32 v42, v20, 1, v42
220v_cmp_u_f16_e32 vcc_lo, 0, v10
221v_cndmask_b32_e64 v20, 0, 1, vcc_lo
222v_lshl_or_b32 v42, v20, 2, v42
223v_cmp_u_f16_e32 vcc_lo, v4, v11
224v_cndmask_b32_e64 v20, 0, 1, vcc_lo
225v_lshl_or_b32 v42, v20, 3, v42
226v_cmp_u_f16_e32 vcc_lo, v5, v12
227v_cndmask_b32_e64 v20, 0, 1, vcc_lo
228v_lshl_or_b32 v42, v20, 4, v42
229v_cmp_u_f16_e32 vcc_lo, v6, v13
230v_cndmask_b32_e64 v20, 0, 1, vcc_lo
231v_lshl_or_b32 v42, v20, 5, v42
232v_cmp_u_f16_e32 vcc_lo, v7, v14
233v_cndmask_b32_e64 v20, 0, 1, vcc_lo
234v_lshl_or_b32 v42, v20, 6, v42
235v_cmp_nge_f16_e32 vcc_lo, 1.0, v8
236v_cndmask_b32_e64 v20, 0, 1, vcc_lo
237v_lshl_or_b32 v42, v20, 7, v42
238v_cmp_nge_f16_e32 vcc_lo, 2.0, v9
239v_cndmask_b32_e64 v20, 0, 1, vcc_lo
240v_lshl_or_b32 v42, v20, 8, v42
241v_cmp_nge_f16_e32 vcc_lo, 0, v10
242v_cndmask_b32_e64 v20, 0, 1, vcc_lo
243v_lshl_or_b32 v42, v20, 9, v42
244v_cmp_nge_f16_e32 vcc_lo, v4, v11
245v_cndmask_b32_e64 v20, 0, 1, vcc_lo
246v_lshl_or_b32 v42, v20, 10, v42
247v_cmp_nge_f16_e32 vcc_lo, v5, v12
248v_cndmask_b32_e64 v20, 0, 1, vcc_lo
249v_lshl_or_b32 v42, v20, 11, v42
250v_cmp_nge_f16_e32 vcc_lo, v6, v13
251v_cndmask_b32_e64 v20, 0, 1, vcc_lo
252v_lshl_or_b32 v42, v20, 12, v42
253v_cmp_nge_f16_e32 vcc_lo, v7, v14
254v_cndmask_b32_e64 v20, 0, 1, vcc_lo
255v_lshl_or_b32 v42, v20, 13, v42
256v_cmp_nlg_f16_e32 vcc_lo, 1.0, v8
257v_cndmask_b32_e64 v20, 0, 1, vcc_lo
258v_lshl_or_b32 v42, v20, 14, v42
259v_cmp_nlg_f16_e32 vcc_lo, 2.0, v9
260v_cndmask_b32_e64 v20, 0, 1, vcc_lo
261v_lshl_or_b32 v42, v20, 15, v42
262v_cmp_nlg_f16_e32 vcc_lo, 0, v10
263v_cndmask_b32_e64 v20, 0, 1, vcc_lo
264v_lshl_or_b32 v42, v20, 16, v42
265v_cmp_nlg_f16_e32 vcc_lo, v4, v11
266v_cndmask_b32_e64 v20, 0, 1, vcc_lo
267v_lshl_or_b32 v42, v20, 17, v42
268v_cmp_nlg_f16_e32 vcc_lo, v5, v12
269v_cndmask_b32_e64 v20, 0, 1, vcc_lo
270v_lshl_or_b32 v42, v20, 18, v42
271v_cmp_nlg_f16_e32 vcc_lo, v6, v13
272v_cndmask_b32_e64 v20, 0, 1, vcc_lo
273v_lshl_or_b32 v42, v20, 19, v42
274v_cmp_nlg_f16_e32 vcc_lo, v7, v14
275v_cndmask_b32_e64 v20, 0, 1, vcc_lo
276v_lshl_or_b32 v42, v20, 20, v42
277v_cmp_ngt_f16_e32 vcc_lo, 1.0, v8
278v_cndmask_b32_e64 v20, 0, 1, vcc_lo
279v_lshl_or_b32 v42, v20, 21, v42
280v_cmp_ngt_f16_e32 vcc_lo, 2.0, v9
281v_cndmask_b32_e64 v20, 0, 1, vcc_lo
282v_lshl_or_b32 v42, v20, 22, v42
283v_cmp_ngt_f16_e32 vcc_lo, 0, v10
284v_cndmask_b32_e64 v20, 0, 1, vcc_lo
285v_lshl_or_b32 v42, v20, 23, v42
286v_cmp_ngt_f16_e32 vcc_lo, v4, v11
287v_cndmask_b32_e64 v20, 0, 1, vcc_lo
288v_lshl_or_b32 v42, v20, 24, v42
289v_cmp_ngt_f16_e32 vcc_lo, v5, v12
290v_cndmask_b32_e64 v20, 0, 1, vcc_lo
291v_lshl_or_b32 v42, v20, 25, v42
292v_cmp_ngt_f16_e32 vcc_lo, v6, v13
293v_cndmask_b32_e64 v20, 0, 1, vcc_lo
294v_lshl_or_b32 v42, v20, 26, v42
295v_cmp_ngt_f16_e32 vcc_lo, v7, v14
296v_cndmask_b32_e64 v20, 0, 1, vcc_lo
297v_lshl_or_b32 v42, v20, 27, v42
298v_mov_b32_e32 v43, 0x40000000
299v_cmp_nle_f16_e32 vcc_lo, 1.0, v8
300v_cndmask_b32_e64 v20, 0, 1, vcc_lo
301v_lshl_or_b32 v43, v20, 0, v43
302v_cmp_nle_f16_e32 vcc_lo, 2.0, v9
303v_cndmask_b32_e64 v20, 0, 1, vcc_lo
304v_lshl_or_b32 v43, v20, 1, v43
305v_cmp_nle_f16_e32 vcc_lo, 0, v10
306v_cndmask_b32_e64 v20, 0, 1, vcc_lo
307v_lshl_or_b32 v43, v20, 2, v43
308v_cmp_nle_f16_e32 vcc_lo, v4, v11
309v_cndmask_b32_e64 v20, 0, 1, vcc_lo
310v_lshl_or_b32 v43, v20, 3, v43
311v_cmp_nle_f16_e32 vcc_lo, v5, v12
312v_cndmask_b32_e64 v20, 0, 1, vcc_lo
313v_lshl_or_b32 v43, v20, 4, v43
314v_cmp_nle_f16_e32 vcc_lo, v6, v13
315v_cndmask_b32_e64 v20, 0, 1, vcc_lo
316v_lshl_or_b32 v43, v20, 5, v43
317v_cmp_nle_f16_e32 vcc_lo, v7, v14
318v_cndmask_b32_e64 v20, 0, 1, vcc_lo
319v_lshl_or_b32 v43, v20, 6, v43
320v_cmp_neq_f16_e32 vcc_lo, 1.0, v8
321v_cndmask_b32_e64 v20, 0, 1, vcc_lo
322v_lshl_or_b32 v43, v20, 7, v43
323v_cmp_neq_f16_e32 vcc_lo, 2.0, v9
324v_cndmask_b32_e64 v20, 0, 1, vcc_lo
325v_lshl_or_b32 v43, v20, 8, v43
326v_cmp_neq_f16_e32 vcc_lo, 0, v10
327v_cndmask_b32_e64 v20, 0, 1, vcc_lo
328v_lshl_or_b32 v43, v20, 9, v43
329v_cmp_neq_f16_e32 vcc_lo, v4, v11
330v_cndmask_b32_e64 v20, 0, 1, vcc_lo
331v_lshl_or_b32 v43, v20, 10, v43
332v_cmp_neq_f16_e32 vcc_lo, v5, v12
333v_cndmask_b32_e64 v20, 0, 1, vcc_lo
334v_lshl_or_b32 v43, v20, 11, v43
335v_cmp_neq_f16_e32 vcc_lo, v6, v13
336v_cndmask_b32_e64 v20, 0, 1, vcc_lo
337v_lshl_or_b32 v43, v20, 12, v43
338v_cmp_neq_f16_e32 vcc_lo, v7, v14
339v_cndmask_b32_e64 v20, 0, 1, vcc_lo
340v_lshl_or_b32 v43, v20, 13, v43
341v_cmp_nlt_f16_e32 vcc_lo, 1.0, v8
342v_cndmask_b32_e64 v20, 0, 1, vcc_lo
343v_lshl_or_b32 v43, v20, 14, v43
344v_cmp_nlt_f16_e32 vcc_lo, 2.0, v9
345v_cndmask_b32_e64 v20, 0, 1, vcc_lo
346v_lshl_or_b32 v43, v20, 15, v43
347v_cmp_nlt_f16_e32 vcc_lo, 0, v10
348v_cndmask_b32_e64 v20, 0, 1, vcc_lo
349v_lshl_or_b32 v43, v20, 16, v43
350v_cmp_nlt_f16_e32 vcc_lo, v4, v11
351v_cndmask_b32_e64 v20, 0, 1, vcc_lo
352v_lshl_or_b32 v43, v20, 17, v43
353v_cmp_nlt_f16_e32 vcc_lo, v5, v12
354v_cndmask_b32_e64 v20, 0, 1, vcc_lo
355v_lshl_or_b32 v43, v20, 18, v43
356v_cmp_nlt_f16_e32 vcc_lo, v6, v13
357v_cndmask_b32_e64 v20, 0, 1, vcc_lo
358v_lshl_or_b32 v43, v20, 19, v43
359v_cmp_nlt_f16_e32 vcc_lo, v7, v14
360v_cndmask_b32_e64 v20, 0, 1, vcc_lo
361v_lshl_or_b32 v43, v20, 20, v43
362v_cmp_tru_f16_e32 vcc_lo, 1.0, v8
363v_cndmask_b32_e64 v20, 0, 1, vcc_lo
364v_lshl_or_b32 v43, v20, 21, v43
365v_cmp_tru_f16_e32 vcc_lo, 2.0, v9
366v_cndmask_b32_e64 v20, 0, 1, vcc_lo
367v_lshl_or_b32 v43, v20, 22, v43
368v_cmp_tru_f16_e32 vcc_lo, 0, v10
369v_cndmask_b32_e64 v20, 0, 1, vcc_lo
370v_lshl_or_b32 v43, v20, 23, v43
371v_cmp_tru_f16_e32 vcc_lo, v4, v11
372v_cndmask_b32_e64 v20, 0, 1, vcc_lo
373v_lshl_or_b32 v43, v20, 24, v43
374v_cmp_tru_f16_e32 vcc_lo, v5, v12
375v_cndmask_b32_e64 v20, 0, 1, vcc_lo
376v_lshl_or_b32 v43, v20, 25, v43
377v_cmp_tru_f16_e32 vcc_lo, v6, v13
378v_cndmask_b32_e64 v20, 0, 1, vcc_lo
379v_lshl_or_b32 v43, v20, 26, v43
380v_cmp_tru_f16_e32 vcc_lo, v7, v14
381v_cndmask_b32_e64 v20, 0, 1, vcc_lo
382v_lshl_or_b32 v43, v20, 27, v43
383exp mrt0 v40, v41, v42, v43 done vm
384s_endpgm
diff --git a/runtime/test/shaders/ps_vcmp_f16_e64.asm b/runtime/test/shaders/ps_vcmp_f16_e64.asm
new file mode 100644
index 000000000..4bad79619
--- /dev/null
+++ b/runtime/test/shaders/ps_vcmp_f16_e64.asm
@@ -0,0 +1,369 @@
1; 16-bit float VOPC compares, e64 form (SGPR destination) with swapped operands: v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,
2; ngt,nle,neq,nlt,tru}_f16_e64 s4, B, A. Same seven operand pairs as ps_vcmp_f16 (see its header for the ISA rules and
3; the case list), but src0 is the VGPR B and src1 is A (the inline constant for k0..k2, the VGPR otherwise), so each
4; op sees the mirrored relation: less <-> greater, equal and unordered unchanged.
5; Cases (A to B as in ps_vcmp_f16): k0 1.0/2.0, k1 2.0/1.0, k2 +0/-0, k3 qNaN/1.0, k4 1.0/sNaN,
6; k5 +inf/-inf, k6 denormal 0x0001/0x0002; the high halves of the VGPR operands hold junk.
7; Relation of B (src0) to A (src1): LESS = {k1,k5} = 0x22, GREATER = {k0,k6} = 0x41,
8; EQUAL = {k2} = 0x04, UNORDERED = {k3,k4} = 0x18. Masks (bit k = result on case k):
9; f 0x00 lt 0x22 eq 0x04 le 0x26 gt 0x41 lg 0x63 ge 0x45 o 0x67
10; u 0x18 nge 0x3a nlg 0x1c ngt 0x3e nle 0x59 neq 0x7b nlt 0x5d tru 0x7f
11; Word w holds ops 4w..4w+3, op j at bit 7*j + k, plus bit 30 (no denormal or NaN export pattern):
12; word 0 = 0x40000000 | 0x00 | 0x22<<7 | 0x04<<14 | 0x26<<21 = 0x40000000 + 0x1100 + 0x10000 + 0x4c00000 = 0x44c11100
13; word 1 = 0x40000000 | 0x41 | 0x63<<7 | 0x45<<14 | 0x67<<21 = 0x40000000 + 0x31c1 + 0x114000 + 0xce00000 = 0x4cf171c1
14; word 2 = 0x40000000 | 0x18 | 0x3a<<7 | 0x1c<<14 | 0x3e<<21 = 0x40000000 + 0x1d18 + 0x70000 + 0x7c00000 = 0x47c71d18
15; word 3 = 0x40000000 | 0x59 | 0x7b<<7 | 0x5d<<14 | 0x7f<<21 = 0x40000000 + 0x3dd9 + 0x174000 + 0xfe00000 = 0x4ff77dd9
16; Expected mrt0 bits: 0x44c11100, 0x4cf171c1, 0x47c71d18, 0x4ff77dd9
17v_mov_b32_e32 v8, 0x12344000
18v_mov_b32_e32 v9, 0xabcd3c00
19v_mov_b32_e32 v10, 0xffff8000
20v_mov_b32_e32 v4, 0xffff7e00
21v_mov_b32_e32 v11, 0x00013c00
22v_mov_b32_e32 v5, 0x55553c00
23v_mov_b32_e32 v12, 0x7c007c01
24v_mov_b32_e32 v6, 0x00017c00
25v_mov_b32_e32 v13, 0xbeeffc00
26v_mov_b32_e32 v7, 0xdead0001
27v_mov_b32_e32 v14, 0x80000002
28v_mov_b32_e32 v40, 0x40000000
29v_cmp_f_f16_e64 s4, v8, 1.0
30v_cndmask_b32_e64 v20, 0, 1, s4
31v_lshl_or_b32 v40, v20, 0, v40
32v_cmp_f_f16_e64 s4, v9, 2.0
33v_cndmask_b32_e64 v20, 0, 1, s4
34v_lshl_or_b32 v40, v20, 1, v40
35v_cmp_f_f16_e64 s4, v10, 0
36v_cndmask_b32_e64 v20, 0, 1, s4
37v_lshl_or_b32 v40, v20, 2, v40
38v_cmp_f_f16_e64 s4, v11, v4
39v_cndmask_b32_e64 v20, 0, 1, s4
40v_lshl_or_b32 v40, v20, 3, v40
41v_cmp_f_f16_e64 s4, v12, v5
42v_cndmask_b32_e64 v20, 0, 1, s4
43v_lshl_or_b32 v40, v20, 4, v40
44v_cmp_f_f16_e64 s4, v13, v6
45v_cndmask_b32_e64 v20, 0, 1, s4
46v_lshl_or_b32 v40, v20, 5, v40
47v_cmp_f_f16_e64 s4, v14, v7
48v_cndmask_b32_e64 v20, 0, 1, s4
49v_lshl_or_b32 v40, v20, 6, v40
50v_cmp_lt_f16_e64 s4, v8, 1.0
51v_cndmask_b32_e64 v20, 0, 1, s4
52v_lshl_or_b32 v40, v20, 7, v40
53v_cmp_lt_f16_e64 s4, v9, 2.0
54v_cndmask_b32_e64 v20, 0, 1, s4
55v_lshl_or_b32 v40, v20, 8, v40
56v_cmp_lt_f16_e64 s4, v10, 0
57v_cndmask_b32_e64 v20, 0, 1, s4
58v_lshl_or_b32 v40, v20, 9, v40
59v_cmp_lt_f16_e64 s4, v11, v4
60v_cndmask_b32_e64 v20, 0, 1, s4
61v_lshl_or_b32 v40, v20, 10, v40
62v_cmp_lt_f16_e64 s4, v12, v5
63v_cndmask_b32_e64 v20, 0, 1, s4
64v_lshl_or_b32 v40, v20, 11, v40
65v_cmp_lt_f16_e64 s4, v13, v6
66v_cndmask_b32_e64 v20, 0, 1, s4
67v_lshl_or_b32 v40, v20, 12, v40
68v_cmp_lt_f16_e64 s4, v14, v7
69v_cndmask_b32_e64 v20, 0, 1, s4
70v_lshl_or_b32 v40, v20, 13, v40
71v_cmp_eq_f16_e64 s4, v8, 1.0
72v_cndmask_b32_e64 v20, 0, 1, s4
73v_lshl_or_b32 v40, v20, 14, v40
74v_cmp_eq_f16_e64 s4, v9, 2.0
75v_cndmask_b32_e64 v20, 0, 1, s4
76v_lshl_or_b32 v40, v20, 15, v40
77v_cmp_eq_f16_e64 s4, v10, 0
78v_cndmask_b32_e64 v20, 0, 1, s4
79v_lshl_or_b32 v40, v20, 16, v40
80v_cmp_eq_f16_e64 s4, v11, v4
81v_cndmask_b32_e64 v20, 0, 1, s4
82v_lshl_or_b32 v40, v20, 17, v40
83v_cmp_eq_f16_e64 s4, v12, v5
84v_cndmask_b32_e64 v20, 0, 1, s4
85v_lshl_or_b32 v40, v20, 18, v40
86v_cmp_eq_f16_e64 s4, v13, v6
87v_cndmask_b32_e64 v20, 0, 1, s4
88v_lshl_or_b32 v40, v20, 19, v40
89v_cmp_eq_f16_e64 s4, v14, v7
90v_cndmask_b32_e64 v20, 0, 1, s4
91v_lshl_or_b32 v40, v20, 20, v40
92v_cmp_le_f16_e64 s4, v8, 1.0
93v_cndmask_b32_e64 v20, 0, 1, s4
94v_lshl_or_b32 v40, v20, 21, v40
95v_cmp_le_f16_e64 s4, v9, 2.0
96v_cndmask_b32_e64 v20, 0, 1, s4
97v_lshl_or_b32 v40, v20, 22, v40
98v_cmp_le_f16_e64 s4, v10, 0
99v_cndmask_b32_e64 v20, 0, 1, s4
100v_lshl_or_b32 v40, v20, 23, v40
101v_cmp_le_f16_e64 s4, v11, v4
102v_cndmask_b32_e64 v20, 0, 1, s4
103v_lshl_or_b32 v40, v20, 24, v40
104v_cmp_le_f16_e64 s4, v12, v5
105v_cndmask_b32_e64 v20, 0, 1, s4
106v_lshl_or_b32 v40, v20, 25, v40
107v_cmp_le_f16_e64 s4, v13, v6
108v_cndmask_b32_e64 v20, 0, 1, s4
109v_lshl_or_b32 v40, v20, 26, v40
110v_cmp_le_f16_e64 s4, v14, v7
111v_cndmask_b32_e64 v20, 0, 1, s4
112v_lshl_or_b32 v40, v20, 27, v40
113v_mov_b32_e32 v41, 0x40000000
114v_cmp_gt_f16_e64 s4, v8, 1.0
115v_cndmask_b32_e64 v20, 0, 1, s4
116v_lshl_or_b32 v41, v20, 0, v41
117v_cmp_gt_f16_e64 s4, v9, 2.0
118v_cndmask_b32_e64 v20, 0, 1, s4
119v_lshl_or_b32 v41, v20, 1, v41
120v_cmp_gt_f16_e64 s4, v10, 0
121v_cndmask_b32_e64 v20, 0, 1, s4
122v_lshl_or_b32 v41, v20, 2, v41
123v_cmp_gt_f16_e64 s4, v11, v4
124v_cndmask_b32_e64 v20, 0, 1, s4
125v_lshl_or_b32 v41, v20, 3, v41
126v_cmp_gt_f16_e64 s4, v12, v5
127v_cndmask_b32_e64 v20, 0, 1, s4
128v_lshl_or_b32 v41, v20, 4, v41
129v_cmp_gt_f16_e64 s4, v13, v6
130v_cndmask_b32_e64 v20, 0, 1, s4
131v_lshl_or_b32 v41, v20, 5, v41
132v_cmp_gt_f16_e64 s4, v14, v7
133v_cndmask_b32_e64 v20, 0, 1, s4
134v_lshl_or_b32 v41, v20, 6, v41
135v_cmp_lg_f16_e64 s4, v8, 1.0
136v_cndmask_b32_e64 v20, 0, 1, s4
137v_lshl_or_b32 v41, v20, 7, v41
138v_cmp_lg_f16_e64 s4, v9, 2.0
139v_cndmask_b32_e64 v20, 0, 1, s4
140v_lshl_or_b32 v41, v20, 8, v41
141v_cmp_lg_f16_e64 s4, v10, 0
142v_cndmask_b32_e64 v20, 0, 1, s4
143v_lshl_or_b32 v41, v20, 9, v41
144v_cmp_lg_f16_e64 s4, v11, v4
145v_cndmask_b32_e64 v20, 0, 1, s4
146v_lshl_or_b32 v41, v20, 10, v41
147v_cmp_lg_f16_e64 s4, v12, v5
148v_cndmask_b32_e64 v20, 0, 1, s4
149v_lshl_or_b32 v41, v20, 11, v41
150v_cmp_lg_f16_e64 s4, v13, v6
151v_cndmask_b32_e64 v20, 0, 1, s4
152v_lshl_or_b32 v41, v20, 12, v41
153v_cmp_lg_f16_e64 s4, v14, v7
154v_cndmask_b32_e64 v20, 0, 1, s4
155v_lshl_or_b32 v41, v20, 13, v41
156v_cmp_ge_f16_e64 s4, v8, 1.0
157v_cndmask_b32_e64 v20, 0, 1, s4
158v_lshl_or_b32 v41, v20, 14, v41
159v_cmp_ge_f16_e64 s4, v9, 2.0
160v_cndmask_b32_e64 v20, 0, 1, s4
161v_lshl_or_b32 v41, v20, 15, v41
162v_cmp_ge_f16_e64 s4, v10, 0
163v_cndmask_b32_e64 v20, 0, 1, s4
164v_lshl_or_b32 v41, v20, 16, v41
165v_cmp_ge_f16_e64 s4, v11, v4
166v_cndmask_b32_e64 v20, 0, 1, s4
167v_lshl_or_b32 v41, v20, 17, v41
168v_cmp_ge_f16_e64 s4, v12, v5
169v_cndmask_b32_e64 v20, 0, 1, s4
170v_lshl_or_b32 v41, v20, 18, v41
171v_cmp_ge_f16_e64 s4, v13, v6
172v_cndmask_b32_e64 v20, 0, 1, s4
173v_lshl_or_b32 v41, v20, 19, v41
174v_cmp_ge_f16_e64 s4, v14, v7
175v_cndmask_b32_e64 v20, 0, 1, s4
176v_lshl_or_b32 v41, v20, 20, v41
177v_cmp_o_f16_e64 s4, v8, 1.0
178v_cndmask_b32_e64 v20, 0, 1, s4
179v_lshl_or_b32 v41, v20, 21, v41
180v_cmp_o_f16_e64 s4, v9, 2.0
181v_cndmask_b32_e64 v20, 0, 1, s4
182v_lshl_or_b32 v41, v20, 22, v41
183v_cmp_o_f16_e64 s4, v10, 0
184v_cndmask_b32_e64 v20, 0, 1, s4
185v_lshl_or_b32 v41, v20, 23, v41
186v_cmp_o_f16_e64 s4, v11, v4
187v_cndmask_b32_e64 v20, 0, 1, s4
188v_lshl_or_b32 v41, v20, 24, v41
189v_cmp_o_f16_e64 s4, v12, v5
190v_cndmask_b32_e64 v20, 0, 1, s4
191v_lshl_or_b32 v41, v20, 25, v41
192v_cmp_o_f16_e64 s4, v13, v6
193v_cndmask_b32_e64 v20, 0, 1, s4
194v_lshl_or_b32 v41, v20, 26, v41
195v_cmp_o_f16_e64 s4, v14, v7
196v_cndmask_b32_e64 v20, 0, 1, s4
197v_lshl_or_b32 v41, v20, 27, v41
198v_mov_b32_e32 v42, 0x40000000
199v_cmp_u_f16_e64 s4, v8, 1.0
200v_cndmask_b32_e64 v20, 0, 1, s4
201v_lshl_or_b32 v42, v20, 0, v42
202v_cmp_u_f16_e64 s4, v9, 2.0
203v_cndmask_b32_e64 v20, 0, 1, s4
204v_lshl_or_b32 v42, v20, 1, v42
205v_cmp_u_f16_e64 s4, v10, 0
206v_cndmask_b32_e64 v20, 0, 1, s4
207v_lshl_or_b32 v42, v20, 2, v42
208v_cmp_u_f16_e64 s4, v11, v4
209v_cndmask_b32_e64 v20, 0, 1, s4
210v_lshl_or_b32 v42, v20, 3, v42
211v_cmp_u_f16_e64 s4, v12, v5
212v_cndmask_b32_e64 v20, 0, 1, s4
213v_lshl_or_b32 v42, v20, 4, v42
214v_cmp_u_f16_e64 s4, v13, v6
215v_cndmask_b32_e64 v20, 0, 1, s4
216v_lshl_or_b32 v42, v20, 5, v42
217v_cmp_u_f16_e64 s4, v14, v7
218v_cndmask_b32_e64 v20, 0, 1, s4
219v_lshl_or_b32 v42, v20, 6, v42
220v_cmp_nge_f16_e64 s4, v8, 1.0
221v_cndmask_b32_e64 v20, 0, 1, s4
222v_lshl_or_b32 v42, v20, 7, v42
223v_cmp_nge_f16_e64 s4, v9, 2.0
224v_cndmask_b32_e64 v20, 0, 1, s4
225v_lshl_or_b32 v42, v20, 8, v42
226v_cmp_nge_f16_e64 s4, v10, 0
227v_cndmask_b32_e64 v20, 0, 1, s4
228v_lshl_or_b32 v42, v20, 9, v42
229v_cmp_nge_f16_e64 s4, v11, v4
230v_cndmask_b32_e64 v20, 0, 1, s4
231v_lshl_or_b32 v42, v20, 10, v42
232v_cmp_nge_f16_e64 s4, v12, v5
233v_cndmask_b32_e64 v20, 0, 1, s4
234v_lshl_or_b32 v42, v20, 11, v42
235v_cmp_nge_f16_e64 s4, v13, v6
236v_cndmask_b32_e64 v20, 0, 1, s4
237v_lshl_or_b32 v42, v20, 12, v42
238v_cmp_nge_f16_e64 s4, v14, v7
239v_cndmask_b32_e64 v20, 0, 1, s4
240v_lshl_or_b32 v42, v20, 13, v42
241v_cmp_nlg_f16_e64 s4, v8, 1.0
242v_cndmask_b32_e64 v20, 0, 1, s4
243v_lshl_or_b32 v42, v20, 14, v42
244v_cmp_nlg_f16_e64 s4, v9, 2.0
245v_cndmask_b32_e64 v20, 0, 1, s4
246v_lshl_or_b32 v42, v20, 15, v42
247v_cmp_nlg_f16_e64 s4, v10, 0
248v_cndmask_b32_e64 v20, 0, 1, s4
249v_lshl_or_b32 v42, v20, 16, v42
250v_cmp_nlg_f16_e64 s4, v11, v4
251v_cndmask_b32_e64 v20, 0, 1, s4
252v_lshl_or_b32 v42, v20, 17, v42
253v_cmp_nlg_f16_e64 s4, v12, v5
254v_cndmask_b32_e64 v20, 0, 1, s4
255v_lshl_or_b32 v42, v20, 18, v42
256v_cmp_nlg_f16_e64 s4, v13, v6
257v_cndmask_b32_e64 v20, 0, 1, s4
258v_lshl_or_b32 v42, v20, 19, v42
259v_cmp_nlg_f16_e64 s4, v14, v7
260v_cndmask_b32_e64 v20, 0, 1, s4
261v_lshl_or_b32 v42, v20, 20, v42
262v_cmp_ngt_f16_e64 s4, v8, 1.0
263v_cndmask_b32_e64 v20, 0, 1, s4
264v_lshl_or_b32 v42, v20, 21, v42
265v_cmp_ngt_f16_e64 s4, v9, 2.0
266v_cndmask_b32_e64 v20, 0, 1, s4
267v_lshl_or_b32 v42, v20, 22, v42
268v_cmp_ngt_f16_e64 s4, v10, 0
269v_cndmask_b32_e64 v20, 0, 1, s4
270v_lshl_or_b32 v42, v20, 23, v42
271v_cmp_ngt_f16_e64 s4, v11, v4
272v_cndmask_b32_e64 v20, 0, 1, s4
273v_lshl_or_b32 v42, v20, 24, v42
274v_cmp_ngt_f16_e64 s4, v12, v5
275v_cndmask_b32_e64 v20, 0, 1, s4
276v_lshl_or_b32 v42, v20, 25, v42
277v_cmp_ngt_f16_e64 s4, v13, v6
278v_cndmask_b32_e64 v20, 0, 1, s4
279v_lshl_or_b32 v42, v20, 26, v42
280v_cmp_ngt_f16_e64 s4, v14, v7
281v_cndmask_b32_e64 v20, 0, 1, s4
282v_lshl_or_b32 v42, v20, 27, v42
283v_mov_b32_e32 v43, 0x40000000
284v_cmp_nle_f16_e64 s4, v8, 1.0
285v_cndmask_b32_e64 v20, 0, 1, s4
286v_lshl_or_b32 v43, v20, 0, v43
287v_cmp_nle_f16_e64 s4, v9, 2.0
288v_cndmask_b32_e64 v20, 0, 1, s4
289v_lshl_or_b32 v43, v20, 1, v43
290v_cmp_nle_f16_e64 s4, v10, 0
291v_cndmask_b32_e64 v20, 0, 1, s4
292v_lshl_or_b32 v43, v20, 2, v43
293v_cmp_nle_f16_e64 s4, v11, v4
294v_cndmask_b32_e64 v20, 0, 1, s4
295v_lshl_or_b32 v43, v20, 3, v43
296v_cmp_nle_f16_e64 s4, v12, v5
297v_cndmask_b32_e64 v20, 0, 1, s4
298v_lshl_or_b32 v43, v20, 4, v43
299v_cmp_nle_f16_e64 s4, v13, v6
300v_cndmask_b32_e64 v20, 0, 1, s4
301v_lshl_or_b32 v43, v20, 5, v43
302v_cmp_nle_f16_e64 s4, v14, v7
303v_cndmask_b32_e64 v20, 0, 1, s4
304v_lshl_or_b32 v43, v20, 6, v43
305v_cmp_neq_f16_e64 s4, v8, 1.0
306v_cndmask_b32_e64 v20, 0, 1, s4
307v_lshl_or_b32 v43, v20, 7, v43
308v_cmp_neq_f16_e64 s4, v9, 2.0
309v_cndmask_b32_e64 v20, 0, 1, s4
310v_lshl_or_b32 v43, v20, 8, v43
311v_cmp_neq_f16_e64 s4, v10, 0
312v_cndmask_b32_e64 v20, 0, 1, s4
313v_lshl_or_b32 v43, v20, 9, v43
314v_cmp_neq_f16_e64 s4, v11, v4
315v_cndmask_b32_e64 v20, 0, 1, s4
316v_lshl_or_b32 v43, v20, 10, v43
317v_cmp_neq_f16_e64 s4, v12, v5
318v_cndmask_b32_e64 v20, 0, 1, s4
319v_lshl_or_b32 v43, v20, 11, v43
320v_cmp_neq_f16_e64 s4, v13, v6
321v_cndmask_b32_e64 v20, 0, 1, s4
322v_lshl_or_b32 v43, v20, 12, v43
323v_cmp_neq_f16_e64 s4, v14, v7
324v_cndmask_b32_e64 v20, 0, 1, s4
325v_lshl_or_b32 v43, v20, 13, v43
326v_cmp_nlt_f16_e64 s4, v8, 1.0
327v_cndmask_b32_e64 v20, 0, 1, s4
328v_lshl_or_b32 v43, v20, 14, v43
329v_cmp_nlt_f16_e64 s4, v9, 2.0
330v_cndmask_b32_e64 v20, 0, 1, s4
331v_lshl_or_b32 v43, v20, 15, v43
332v_cmp_nlt_f16_e64 s4, v10, 0
333v_cndmask_b32_e64 v20, 0, 1, s4
334v_lshl_or_b32 v43, v20, 16, v43
335v_cmp_nlt_f16_e64 s4, v11, v4
336v_cndmask_b32_e64 v20, 0, 1, s4
337v_lshl_or_b32 v43, v20, 17, v43
338v_cmp_nlt_f16_e64 s4, v12, v5
339v_cndmask_b32_e64 v20, 0, 1, s4
340v_lshl_or_b32 v43, v20, 18, v43
341v_cmp_nlt_f16_e64 s4, v13, v6
342v_cndmask_b32_e64 v20, 0, 1, s4
343v_lshl_or_b32 v43, v20, 19, v43
344v_cmp_nlt_f16_e64 s4, v14, v7
345v_cndmask_b32_e64 v20, 0, 1, s4
346v_lshl_or_b32 v43, v20, 20, v43
347v_cmp_tru_f16_e64 s4, v8, 1.0
348v_cndmask_b32_e64 v20, 0, 1, s4
349v_lshl_or_b32 v43, v20, 21, v43
350v_cmp_tru_f16_e64 s4, v9, 2.0
351v_cndmask_b32_e64 v20, 0, 1, s4
352v_lshl_or_b32 v43, v20, 22, v43
353v_cmp_tru_f16_e64 s4, v10, 0
354v_cndmask_b32_e64 v20, 0, 1, s4
355v_lshl_or_b32 v43, v20, 23, v43
356v_cmp_tru_f16_e64 s4, v11, v4
357v_cndmask_b32_e64 v20, 0, 1, s4
358v_lshl_or_b32 v43, v20, 24, v43
359v_cmp_tru_f16_e64 s4, v12, v5
360v_cndmask_b32_e64 v20, 0, 1, s4
361v_lshl_or_b32 v43, v20, 25, v43
362v_cmp_tru_f16_e64 s4, v13, v6
363v_cndmask_b32_e64 v20, 0, 1, s4
364v_lshl_or_b32 v43, v20, 26, v43
365v_cmp_tru_f16_e64 s4, v14, v7
366v_cndmask_b32_e64 v20, 0, 1, s4
367v_lshl_or_b32 v43, v20, 27, v43
368exp mrt0 v40, v41, v42, v43 done vm
369s_endpgm
diff --git a/runtime/test/shaders/ps_vcmpx_f16.asm b/runtime/test/shaders/ps_vcmpx_f16.asm
new file mode 100644
index 000000000..3a7cd338d
--- /dev/null
+++ b/runtime/test/shaders/ps_vcmpx_f16.asm
@@ -0,0 +1,653 @@
1; 16-bit float v_cmpx, e32 form: v_cmpx_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16 on the seven operand
2; pairs of ps_vcmp_f16 (see that header for the case list and the ISA rules of the 16 predicates: bits 15:0 of the
3; operands only, ordered compares false for a NaN, +0 == -0, denormals kept). A v_cmpx writes the result to EXEC
4; (EXEC = EXEC & compare, per lane) and to nothing else, so VCC is kept. Each compare runs alone: EXEC is copied out
5; and put back after it (s20 holds the EXEC the shader started with, s21 the copy), so a lane that was true shows as 1
6; and every lane has the same operands. Cases (A = src0, B = src1; the junk is the high half that must be ignored):
7; k0: A = inline 1.0, B = 0x1234:2.0 less k4: A = 0x5555:1.0, B = 0x7c00:sNaN 0x7c01 unordered
8; k1: A = inline 2.0, B = 0xabcd:1.0 greater k5: A = 0x0001:+inf, B = 0xbeef:-inf greater
9; k2: A = inline 0, B = 0xffff:-0 equal k6: A = 0xdead:0x0001, B = 0x8000:0x0002 less (denormals)
10; k3: A = 0xffff:qNaN 0x7e00, B = 0x0001:1.0 unordered
11; Relation sets: LESS = {k0,k6} = 0x41, GREATER = {k1,k5} = 0x22, EQUAL = {k2} = 0x04, UNORDERED = {k3,k4} = 0x18; the
12; mask of an op (bit k = result on case k) is the union of the sets it is true for:
13; f 0x00 lt 0x41 eq 0x04 le 0x45 gt 0x22 lg 0x63 ge 0x26 o 0x67
14; u 0x18 nge 0x59 nlg 0x1c ngt 0x5d nle 0x3a neq 0x7b nlt 0x3e tru 0x7f
15; Word w holds ops 4w..4w+3 (the order above), op j at bit 7*j + k. Three more bits per word, from one op of the form:
16; bit 30: always 1 (keeps the float export away from denormal and NaN patterns).
17; bit 29: VCC = 1 in every lane (v_cmp_tru_f16 v8, v8), then v_cmpx_f_f16 empties EXEC; after EXEC is restored VCC
18; must still be 1, because a v_cmpx writes EXEC only: the bit is 1.
19; bit 28: v_cmpx_f_f16 empties EXEC, the v_cmpx_tru_f16 after it is true in every lane, but v_cmpx only ANDs into
20; EXEC, so no lane comes back: the bit is 0.
21; word 0 = 0x60000000 | 0x00 | 0x41<<7 | 0x04<<14 | 0x45<<21 = 0x60000000 + 0x2080 + 0x10000 + 0x8a00000 = 0x68a12080
22; word 1 = 0x60000000 | 0x22 | 0x63<<7 | 0x26<<14 | 0x67<<21 = 0x60000000 + 0x31a2 + 0x98000 + 0xce00000 = 0x6ce9b1a2
23; word 2 = 0x60000000 | 0x18 | 0x59<<7 | 0x1c<<14 | 0x5d<<21 = 0x60000000 + 0x2c98 + 0x70000 + 0xba00000 = 0x6ba72c98
24; word 3 = 0x60000000 | 0x3a | 0x7b<<7 | 0x3e<<14 | 0x7f<<21 = 0x60000000 + 0x3dba + 0xf8000 + 0xfe00000 = 0x6fefbdba
25; A v_cmpx that wrote VCC, or did not AND with the old EXEC, flips bit 29 or bit 28; one that ordered a NaN, flushed a
26; denormal, took -0 below +0 or read the high halves moves bits in the words.
27; Expected mrt0 bits: 0x68a12080, 0x6ce9b1a2, 0x6ba72c98, 0x6fefbdba
28v_mov_b32_e32 v8, 0x12344000
29v_mov_b32_e32 v9, 0xabcd3c00
30v_mov_b32_e32 v10, 0xffff8000
31v_mov_b32_e32 v4, 0xffff7e00
32v_mov_b32_e32 v11, 0x00013c00
33v_mov_b32_e32 v5, 0x55553c00
34v_mov_b32_e32 v12, 0x7c007c01
35v_mov_b32_e32 v6, 0x00017c00
36v_mov_b32_e32 v13, 0xbeeffc00
37v_mov_b32_e32 v7, 0xdead0001
38v_mov_b32_e32 v14, 0x80000002
39s_mov_b32 s20, exec_lo
40v_mov_b32_e32 v40, 0x40000000
41v_cmp_tru_f16_e32 vcc_lo, v8, v8
42v_cmpx_f_f16_e32 v8, v8
43s_mov_b32 s21, exec_lo
44s_mov_b32 exec_lo, s20
45v_cndmask_b32_e64 v30, 0, 1, vcc_lo
46v_lshl_or_b32 v40, v30, 29, v40
47v_cmpx_f_f16_e32 v8, v8
48v_cmpx_tru_f16_e32 v8, v8
49s_mov_b32 s21, exec_lo
50s_mov_b32 exec_lo, s20
51v_cndmask_b32_e64 v30, 0, 1, s21
52v_lshl_or_b32 v40, v30, 28, v40
53v_cmpx_f_f16_e32 1.0, v8
54s_mov_b32 s21, exec_lo
55s_mov_b32 exec_lo, s20
56v_cndmask_b32_e64 v30, 0, 1, s21
57v_lshl_or_b32 v40, v30, 0, v40
58v_cmpx_f_f16_e32 2.0, v9
59s_mov_b32 s21, exec_lo
60s_mov_b32 exec_lo, s20
61v_cndmask_b32_e64 v30, 0, 1, s21
62v_lshl_or_b32 v40, v30, 1, v40
63v_cmpx_f_f16_e32 0, v10
64s_mov_b32 s21, exec_lo
65s_mov_b32 exec_lo, s20
66v_cndmask_b32_e64 v30, 0, 1, s21
67v_lshl_or_b32 v40, v30, 2, v40
68v_cmpx_f_f16_e32 v4, v11
69s_mov_b32 s21, exec_lo
70s_mov_b32 exec_lo, s20
71v_cndmask_b32_e64 v30, 0, 1, s21
72v_lshl_or_b32 v40, v30, 3, v40
73v_cmpx_f_f16_e32 v5, v12
74s_mov_b32 s21, exec_lo
75s_mov_b32 exec_lo, s20
76v_cndmask_b32_e64 v30, 0, 1, s21
77v_lshl_or_b32 v40, v30, 4, v40
78v_cmpx_f_f16_e32 v6, v13
79s_mov_b32 s21, exec_lo
80s_mov_b32 exec_lo, s20
81v_cndmask_b32_e64 v30, 0, 1, s21
82v_lshl_or_b32 v40, v30, 5, v40
83v_cmpx_f_f16_e32 v7, v14
84s_mov_b32 s21, exec_lo
85s_mov_b32 exec_lo, s20
86v_cndmask_b32_e64 v30, 0, 1, s21
87v_lshl_or_b32 v40, v30, 6, v40
88v_cmpx_lt_f16_e32 1.0, v8
89s_mov_b32 s21, exec_lo
90s_mov_b32 exec_lo, s20
91v_cndmask_b32_e64 v30, 0, 1, s21
92v_lshl_or_b32 v40, v30, 7, v40
93v_cmpx_lt_f16_e32 2.0, v9
94s_mov_b32 s21, exec_lo
95s_mov_b32 exec_lo, s20
96v_cndmask_b32_e64 v30, 0, 1, s21
97v_lshl_or_b32 v40, v30, 8, v40
98v_cmpx_lt_f16_e32 0, v10
99s_mov_b32 s21, exec_lo
100s_mov_b32 exec_lo, s20
101v_cndmask_b32_e64 v30, 0, 1, s21
102v_lshl_or_b32 v40, v30, 9, v40
103v_cmpx_lt_f16_e32 v4, v11
104s_mov_b32 s21, exec_lo
105s_mov_b32 exec_lo, s20
106v_cndmask_b32_e64 v30, 0, 1, s21
107v_lshl_or_b32 v40, v30, 10, v40
108v_cmpx_lt_f16_e32 v5, v12
109s_mov_b32 s21, exec_lo
110s_mov_b32 exec_lo, s20
111v_cndmask_b32_e64 v30, 0, 1, s21
112v_lshl_or_b32 v40, v30, 11, v40
113v_cmpx_lt_f16_e32 v6, v13
114s_mov_b32 s21, exec_lo
115s_mov_b32 exec_lo, s20
116v_cndmask_b32_e64 v30, 0, 1, s21
117v_lshl_or_b32 v40, v30, 12, v40
118v_cmpx_lt_f16_e32 v7, v14
119s_mov_b32 s21, exec_lo
120s_mov_b32 exec_lo, s20
121v_cndmask_b32_e64 v30, 0, 1, s21
122v_lshl_or_b32 v40, v30, 13, v40
123v_cmpx_eq_f16_e32 1.0, v8
124s_mov_b32 s21, exec_lo
125s_mov_b32 exec_lo, s20
126v_cndmask_b32_e64 v30, 0, 1, s21
127v_lshl_or_b32 v40, v30, 14, v40
128v_cmpx_eq_f16_e32 2.0, v9
129s_mov_b32 s21, exec_lo
130s_mov_b32 exec_lo, s20
131v_cndmask_b32_e64 v30, 0, 1, s21
132v_lshl_or_b32 v40, v30, 15, v40
133v_cmpx_eq_f16_e32 0, v10
134s_mov_b32 s21, exec_lo
135s_mov_b32 exec_lo, s20
136v_cndmask_b32_e64 v30, 0, 1, s21
137v_lshl_or_b32 v40, v30, 16, v40
138v_cmpx_eq_f16_e32 v4, v11
139s_mov_b32 s21, exec_lo
140s_mov_b32 exec_lo, s20
141v_cndmask_b32_e64 v30, 0, 1, s21
142v_lshl_or_b32 v40, v30, 17, v40
143v_cmpx_eq_f16_e32 v5, v12
144s_mov_b32 s21, exec_lo
145s_mov_b32 exec_lo, s20
146v_cndmask_b32_e64 v30, 0, 1, s21
147v_lshl_or_b32 v40, v30, 18, v40
148v_cmpx_eq_f16_e32 v6, v13
149s_mov_b32 s21, exec_lo
150s_mov_b32 exec_lo, s20
151v_cndmask_b32_e64 v30, 0, 1, s21
152v_lshl_or_b32 v40, v30, 19, v40
153v_cmpx_eq_f16_e32 v7, v14
154s_mov_b32 s21, exec_lo
155s_mov_b32 exec_lo, s20
156v_cndmask_b32_e64 v30, 0, 1, s21
157v_lshl_or_b32 v40, v30, 20, v40
158v_cmpx_le_f16_e32 1.0, v8
159s_mov_b32 s21, exec_lo
160s_mov_b32 exec_lo, s20
161v_cndmask_b32_e64 v30, 0, 1, s21
162v_lshl_or_b32 v40, v30, 21, v40
163v_cmpx_le_f16_e32 2.0, v9
164s_mov_b32 s21, exec_lo
165s_mov_b32 exec_lo, s20
166v_cndmask_b32_e64 v30, 0, 1, s21
167v_lshl_or_b32 v40, v30, 22, v40
168v_cmpx_le_f16_e32 0, v10
169s_mov_b32 s21, exec_lo
170s_mov_b32 exec_lo, s20
171v_cndmask_b32_e64 v30, 0, 1, s21
172v_lshl_or_b32 v40, v30, 23, v40
173v_cmpx_le_f16_e32 v4, v11
174s_mov_b32 s21, exec_lo
175s_mov_b32 exec_lo, s20
176v_cndmask_b32_e64 v30, 0, 1, s21
177v_lshl_or_b32 v40, v30, 24, v40
178v_cmpx_le_f16_e32 v5, v12
179s_mov_b32 s21, exec_lo
180s_mov_b32 exec_lo, s20
181v_cndmask_b32_e64 v30, 0, 1, s21
182v_lshl_or_b32 v40, v30, 25, v40
183v_cmpx_le_f16_e32 v6, v13
184s_mov_b32 s21, exec_lo
185s_mov_b32 exec_lo, s20
186v_cndmask_b32_e64 v30, 0, 1, s21
187v_lshl_or_b32 v40, v30, 26, v40
188v_cmpx_le_f16_e32 v7, v14
189s_mov_b32 s21, exec_lo
190s_mov_b32 exec_lo, s20
191v_cndmask_b32_e64 v30, 0, 1, s21
192v_lshl_or_b32 v40, v30, 27, v40
193v_mov_b32_e32 v41, 0x40000000
194v_cmp_tru_f16_e32 vcc_lo, v8, v8
195v_cmpx_f_f16_e32 v8, v8
196s_mov_b32 s21, exec_lo
197s_mov_b32 exec_lo, s20
198v_cndmask_b32_e64 v30, 0, 1, vcc_lo
199v_lshl_or_b32 v41, v30, 29, v41
200v_cmpx_f_f16_e32 v8, v8
201v_cmpx_tru_f16_e32 v8, v8
202s_mov_b32 s21, exec_lo
203s_mov_b32 exec_lo, s20
204v_cndmask_b32_e64 v30, 0, 1, s21
205v_lshl_or_b32 v41, v30, 28, v41
206v_cmpx_gt_f16_e32 1.0, v8
207s_mov_b32 s21, exec_lo
208s_mov_b32 exec_lo, s20
209v_cndmask_b32_e64 v30, 0, 1, s21
210v_lshl_or_b32 v41, v30, 0, v41
211v_cmpx_gt_f16_e32 2.0, v9
212s_mov_b32 s21, exec_lo
213s_mov_b32 exec_lo, s20
214v_cndmask_b32_e64 v30, 0, 1, s21
215v_lshl_or_b32 v41, v30, 1, v41
216v_cmpx_gt_f16_e32 0, v10
217s_mov_b32 s21, exec_lo
218s_mov_b32 exec_lo, s20
219v_cndmask_b32_e64 v30, 0, 1, s21
220v_lshl_or_b32 v41, v30, 2, v41
221v_cmpx_gt_f16_e32 v4, v11
222s_mov_b32 s21, exec_lo
223s_mov_b32 exec_lo, s20
224v_cndmask_b32_e64 v30, 0, 1, s21
225v_lshl_or_b32 v41, v30, 3, v41
226v_cmpx_gt_f16_e32 v5, v12
227s_mov_b32 s21, exec_lo
228s_mov_b32 exec_lo, s20
229v_cndmask_b32_e64 v30, 0, 1, s21
230v_lshl_or_b32 v41, v30, 4, v41
231v_cmpx_gt_f16_e32 v6, v13
232s_mov_b32 s21, exec_lo
233s_mov_b32 exec_lo, s20
234v_cndmask_b32_e64 v30, 0, 1, s21
235v_lshl_or_b32 v41, v30, 5, v41
236v_cmpx_gt_f16_e32 v7, v14
237s_mov_b32 s21, exec_lo
238s_mov_b32 exec_lo, s20
239v_cndmask_b32_e64 v30, 0, 1, s21
240v_lshl_or_b32 v41, v30, 6, v41
241v_cmpx_lg_f16_e32 1.0, v8
242s_mov_b32 s21, exec_lo
243s_mov_b32 exec_lo, s20
244v_cndmask_b32_e64 v30, 0, 1, s21
245v_lshl_or_b32 v41, v30, 7, v41
246v_cmpx_lg_f16_e32 2.0, v9
247s_mov_b32 s21, exec_lo
248s_mov_b32 exec_lo, s20
249v_cndmask_b32_e64 v30, 0, 1, s21
250v_lshl_or_b32 v41, v30, 8, v41
251v_cmpx_lg_f16_e32 0, v10
252s_mov_b32 s21, exec_lo
253s_mov_b32 exec_lo, s20
254v_cndmask_b32_e64 v30, 0, 1, s21
255v_lshl_or_b32 v41, v30, 9, v41
256v_cmpx_lg_f16_e32 v4, v11
257s_mov_b32 s21, exec_lo
258s_mov_b32 exec_lo, s20
259v_cndmask_b32_e64 v30, 0, 1, s21
260v_lshl_or_b32 v41, v30, 10, v41
261v_cmpx_lg_f16_e32 v5, v12
262s_mov_b32 s21, exec_lo
263s_mov_b32 exec_lo, s20
264v_cndmask_b32_e64 v30, 0, 1, s21
265v_lshl_or_b32 v41, v30, 11, v41
266v_cmpx_lg_f16_e32 v6, v13
267s_mov_b32 s21, exec_lo
268s_mov_b32 exec_lo, s20
269v_cndmask_b32_e64 v30, 0, 1, s21
270v_lshl_or_b32 v41, v30, 12, v41
271v_cmpx_lg_f16_e32 v7, v14
272s_mov_b32 s21, exec_lo
273s_mov_b32 exec_lo, s20
274v_cndmask_b32_e64 v30, 0, 1, s21
275v_lshl_or_b32 v41, v30, 13, v41
276v_cmpx_ge_f16_e32 1.0, v8
277s_mov_b32 s21, exec_lo
278s_mov_b32 exec_lo, s20
279v_cndmask_b32_e64 v30, 0, 1, s21
280v_lshl_or_b32 v41, v30, 14, v41
281v_cmpx_ge_f16_e32 2.0, v9
282s_mov_b32 s21, exec_lo
283s_mov_b32 exec_lo, s20
284v_cndmask_b32_e64 v30, 0, 1, s21
285v_lshl_or_b32 v41, v30, 15, v41
286v_cmpx_ge_f16_e32 0, v10
287s_mov_b32 s21, exec_lo
288s_mov_b32 exec_lo, s20
289v_cndmask_b32_e64 v30, 0, 1, s21
290v_lshl_or_b32 v41, v30, 16, v41
291v_cmpx_ge_f16_e32 v4, v11
292s_mov_b32 s21, exec_lo
293s_mov_b32 exec_lo, s20
294v_cndmask_b32_e64 v30, 0, 1, s21
295v_lshl_or_b32 v41, v30, 17, v41
296v_cmpx_ge_f16_e32 v5, v12
297s_mov_b32 s21, exec_lo
298s_mov_b32 exec_lo, s20
299v_cndmask_b32_e64 v30, 0, 1, s21
300v_lshl_or_b32 v41, v30, 18, v41
301v_cmpx_ge_f16_e32 v6, v13
302s_mov_b32 s21, exec_lo
303s_mov_b32 exec_lo, s20
304v_cndmask_b32_e64 v30, 0, 1, s21
305v_lshl_or_b32 v41, v30, 19, v41
306v_cmpx_ge_f16_e32 v7, v14
307s_mov_b32 s21, exec_lo
308s_mov_b32 exec_lo, s20
309v_cndmask_b32_e64 v30, 0, 1, s21
310v_lshl_or_b32 v41, v30, 20, v41
311v_cmpx_o_f16_e32 1.0, v8
312s_mov_b32 s21, exec_lo
313s_mov_b32 exec_lo, s20
314v_cndmask_b32_e64 v30, 0, 1, s21
315v_lshl_or_b32 v41, v30, 21, v41
316v_cmpx_o_f16_e32 2.0, v9
317s_mov_b32 s21, exec_lo
318s_mov_b32 exec_lo, s20
319v_cndmask_b32_e64 v30, 0, 1, s21
320v_lshl_or_b32 v41, v30, 22, v41
321v_cmpx_o_f16_e32 0, v10
322s_mov_b32 s21, exec_lo
323s_mov_b32 exec_lo, s20
324v_cndmask_b32_e64 v30, 0, 1, s21
325v_lshl_or_b32 v41, v30, 23, v41
326v_cmpx_o_f16_e32 v4, v11
327s_mov_b32 s21, exec_lo
328s_mov_b32 exec_lo, s20
329v_cndmask_b32_e64 v30, 0, 1, s21
330v_lshl_or_b32 v41, v30, 24, v41
331v_cmpx_o_f16_e32 v5, v12
332s_mov_b32 s21, exec_lo
333s_mov_b32 exec_lo, s20
334v_cndmask_b32_e64 v30, 0, 1, s21
335v_lshl_or_b32 v41, v30, 25, v41
336v_cmpx_o_f16_e32 v6, v13
337s_mov_b32 s21, exec_lo
338s_mov_b32 exec_lo, s20
339v_cndmask_b32_e64 v30, 0, 1, s21
340v_lshl_or_b32 v41, v30, 26, v41
341v_cmpx_o_f16_e32 v7, v14
342s_mov_b32 s21, exec_lo
343s_mov_b32 exec_lo, s20
344v_cndmask_b32_e64 v30, 0, 1, s21
345v_lshl_or_b32 v41, v30, 27, v41
346v_mov_b32_e32 v42, 0x40000000
347v_cmp_tru_f16_e32 vcc_lo, v8, v8
348v_cmpx_f_f16_e32 v8, v8
349s_mov_b32 s21, exec_lo
350s_mov_b32 exec_lo, s20
351v_cndmask_b32_e64 v30, 0, 1, vcc_lo
352v_lshl_or_b32 v42, v30, 29, v42
353v_cmpx_f_f16_e32 v8, v8
354v_cmpx_tru_f16_e32 v8, v8
355s_mov_b32 s21, exec_lo
356s_mov_b32 exec_lo, s20
357v_cndmask_b32_e64 v30, 0, 1, s21
358v_lshl_or_b32 v42, v30, 28, v42
359v_cmpx_u_f16_e32 1.0, v8
360s_mov_b32 s21, exec_lo
361s_mov_b32 exec_lo, s20
362v_cndmask_b32_e64 v30, 0, 1, s21
363v_lshl_or_b32 v42, v30, 0, v42
364v_cmpx_u_f16_e32 2.0, v9
365s_mov_b32 s21, exec_lo
366s_mov_b32 exec_lo, s20
367v_cndmask_b32_e64 v30, 0, 1, s21
368v_lshl_or_b32 v42, v30, 1, v42
369v_cmpx_u_f16_e32 0, v10
370s_mov_b32 s21, exec_lo
371s_mov_b32 exec_lo, s20
372v_cndmask_b32_e64 v30, 0, 1, s21
373v_lshl_or_b32 v42, v30, 2, v42
374v_cmpx_u_f16_e32 v4, v11
375s_mov_b32 s21, exec_lo
376s_mov_b32 exec_lo, s20
377v_cndmask_b32_e64 v30, 0, 1, s21
378v_lshl_or_b32 v42, v30, 3, v42
379v_cmpx_u_f16_e32 v5, v12
380s_mov_b32 s21, exec_lo
381s_mov_b32 exec_lo, s20
382v_cndmask_b32_e64 v30, 0, 1, s21
383v_lshl_or_b32 v42, v30, 4, v42
384v_cmpx_u_f16_e32 v6, v13
385s_mov_b32 s21, exec_lo
386s_mov_b32 exec_lo, s20
387v_cndmask_b32_e64 v30, 0, 1, s21
388v_lshl_or_b32 v42, v30, 5, v42
389v_cmpx_u_f16_e32 v7, v14
390s_mov_b32 s21, exec_lo
391s_mov_b32 exec_lo, s20
392v_cndmask_b32_e64 v30, 0, 1, s21
393v_lshl_or_b32 v42, v30, 6, v42
394v_cmpx_nge_f16_e32 1.0, v8
395s_mov_b32 s21, exec_lo
396s_mov_b32 exec_lo, s20
397v_cndmask_b32_e64 v30, 0, 1, s21
398v_lshl_or_b32 v42, v30, 7, v42
399v_cmpx_nge_f16_e32 2.0, v9
400s_mov_b32 s21, exec_lo
401s_mov_b32 exec_lo, s20
402v_cndmask_b32_e64 v30, 0, 1, s21
403v_lshl_or_b32 v42, v30, 8, v42
404v_cmpx_nge_f16_e32 0, v10
405s_mov_b32 s21, exec_lo
406s_mov_b32 exec_lo, s20
407v_cndmask_b32_e64 v30, 0, 1, s21
408v_lshl_or_b32 v42, v30, 9, v42
409v_cmpx_nge_f16_e32 v4, v11
410s_mov_b32 s21, exec_lo
411s_mov_b32 exec_lo, s20
412v_cndmask_b32_e64 v30, 0, 1, s21
413v_lshl_or_b32 v42, v30, 10, v42
414v_cmpx_nge_f16_e32 v5, v12
415s_mov_b32 s21, exec_lo
416s_mov_b32 exec_lo, s20
417v_cndmask_b32_e64 v30, 0, 1, s21
418v_lshl_or_b32 v42, v30, 11, v42
419v_cmpx_nge_f16_e32 v6, v13
420s_mov_b32 s21, exec_lo
421s_mov_b32 exec_lo, s20
422v_cndmask_b32_e64 v30, 0, 1, s21
423v_lshl_or_b32 v42, v30, 12, v42
424v_cmpx_nge_f16_e32 v7, v14
425s_mov_b32 s21, exec_lo
426s_mov_b32 exec_lo, s20
427v_cndmask_b32_e64 v30, 0, 1, s21
428v_lshl_or_b32 v42, v30, 13, v42
429v_cmpx_nlg_f16_e32 1.0, v8
430s_mov_b32 s21, exec_lo
431s_mov_b32 exec_lo, s20
432v_cndmask_b32_e64 v30, 0, 1, s21
433v_lshl_or_b32 v42, v30, 14, v42
434v_cmpx_nlg_f16_e32 2.0, v9
435s_mov_b32 s21, exec_lo
436s_mov_b32 exec_lo, s20
437v_cndmask_b32_e64 v30, 0, 1, s21
438v_lshl_or_b32 v42, v30, 15, v42
439v_cmpx_nlg_f16_e32 0, v10
440s_mov_b32 s21, exec_lo
441s_mov_b32 exec_lo, s20
442v_cndmask_b32_e64 v30, 0, 1, s21
443v_lshl_or_b32 v42, v30, 16, v42
444v_cmpx_nlg_f16_e32 v4, v11
445s_mov_b32 s21, exec_lo
446s_mov_b32 exec_lo, s20
447v_cndmask_b32_e64 v30, 0, 1, s21
448v_lshl_or_b32 v42, v30, 17, v42
449v_cmpx_nlg_f16_e32 v5, v12
450s_mov_b32 s21, exec_lo
451s_mov_b32 exec_lo, s20
452v_cndmask_b32_e64 v30, 0, 1, s21
453v_lshl_or_b32 v42, v30, 18, v42
454v_cmpx_nlg_f16_e32 v6, v13
455s_mov_b32 s21, exec_lo
456s_mov_b32 exec_lo, s20
457v_cndmask_b32_e64 v30, 0, 1, s21
458v_lshl_or_b32 v42, v30, 19, v42
459v_cmpx_nlg_f16_e32 v7, v14
460s_mov_b32 s21, exec_lo
461s_mov_b32 exec_lo, s20
462v_cndmask_b32_e64 v30, 0, 1, s21
463v_lshl_or_b32 v42, v30, 20, v42
464v_cmpx_ngt_f16_e32 1.0, v8
465s_mov_b32 s21, exec_lo
466s_mov_b32 exec_lo, s20
467v_cndmask_b32_e64 v30, 0, 1, s21
468v_lshl_or_b32 v42, v30, 21, v42
469v_cmpx_ngt_f16_e32 2.0, v9
470s_mov_b32 s21, exec_lo
471s_mov_b32 exec_lo, s20
472v_cndmask_b32_e64 v30, 0, 1, s21
473v_lshl_or_b32 v42, v30, 22, v42
474v_cmpx_ngt_f16_e32 0, v10
475s_mov_b32 s21, exec_lo
476s_mov_b32 exec_lo, s20
477v_cndmask_b32_e64 v30, 0, 1, s21
478v_lshl_or_b32 v42, v30, 23, v42
479v_cmpx_ngt_f16_e32 v4, v11
480s_mov_b32 s21, exec_lo
481s_mov_b32 exec_lo, s20
482v_cndmask_b32_e64 v30, 0, 1, s21
483v_lshl_or_b32 v42, v30, 24, v42
484v_cmpx_ngt_f16_e32 v5, v12
485s_mov_b32 s21, exec_lo
486s_mov_b32 exec_lo, s20
487v_cndmask_b32_e64 v30, 0, 1, s21
488v_lshl_or_b32 v42, v30, 25, v42
489v_cmpx_ngt_f16_e32 v6, v13
490s_mov_b32 s21, exec_lo
491s_mov_b32 exec_lo, s20
492v_cndmask_b32_e64 v30, 0, 1, s21
493v_lshl_or_b32 v42, v30, 26, v42
494v_cmpx_ngt_f16_e32 v7, v14
495s_mov_b32 s21, exec_lo
496s_mov_b32 exec_lo, s20
497v_cndmask_b32_e64 v30, 0, 1, s21
498v_lshl_or_b32 v42, v30, 27, v42
499v_mov_b32_e32 v43, 0x40000000
500v_cmp_tru_f16_e32 vcc_lo, v8, v8
501v_cmpx_f_f16_e32 v8, v8
502s_mov_b32 s21, exec_lo
503s_mov_b32 exec_lo, s20
504v_cndmask_b32_e64 v30, 0, 1, vcc_lo
505v_lshl_or_b32 v43, v30, 29, v43
506v_cmpx_f_f16_e32 v8, v8
507v_cmpx_tru_f16_e32 v8, v8
508s_mov_b32 s21, exec_lo
509s_mov_b32 exec_lo, s20
510v_cndmask_b32_e64 v30, 0, 1, s21
511v_lshl_or_b32 v43, v30, 28, v43
512v_cmpx_nle_f16_e32 1.0, v8
513s_mov_b32 s21, exec_lo
514s_mov_b32 exec_lo, s20
515v_cndmask_b32_e64 v30, 0, 1, s21
516v_lshl_or_b32 v43, v30, 0, v43
517v_cmpx_nle_f16_e32 2.0, v9
518s_mov_b32 s21, exec_lo
519s_mov_b32 exec_lo, s20
520v_cndmask_b32_e64 v30, 0, 1, s21
521v_lshl_or_b32 v43, v30, 1, v43
522v_cmpx_nle_f16_e32 0, v10
523s_mov_b32 s21, exec_lo
524s_mov_b32 exec_lo, s20
525v_cndmask_b32_e64 v30, 0, 1, s21
526v_lshl_or_b32 v43, v30, 2, v43
527v_cmpx_nle_f16_e32 v4, v11
528s_mov_b32 s21, exec_lo
529s_mov_b32 exec_lo, s20
530v_cndmask_b32_e64 v30, 0, 1, s21
531v_lshl_or_b32 v43, v30, 3, v43
532v_cmpx_nle_f16_e32 v5, v12
533s_mov_b32 s21, exec_lo
534s_mov_b32 exec_lo, s20
535v_cndmask_b32_e64 v30, 0, 1, s21
536v_lshl_or_b32 v43, v30, 4, v43
537v_cmpx_nle_f16_e32 v6, v13
538s_mov_b32 s21, exec_lo
539s_mov_b32 exec_lo, s20
540v_cndmask_b32_e64 v30, 0, 1, s21
541v_lshl_or_b32 v43, v30, 5, v43
542v_cmpx_nle_f16_e32 v7, v14
543s_mov_b32 s21, exec_lo
544s_mov_b32 exec_lo, s20
545v_cndmask_b32_e64 v30, 0, 1, s21
546v_lshl_or_b32 v43, v30, 6, v43
547v_cmpx_neq_f16_e32 1.0, v8
548s_mov_b32 s21, exec_lo
549s_mov_b32 exec_lo, s20
550v_cndmask_b32_e64 v30, 0, 1, s21
551v_lshl_or_b32 v43, v30, 7, v43
552v_cmpx_neq_f16_e32 2.0, v9
553s_mov_b32 s21, exec_lo
554s_mov_b32 exec_lo, s20
555v_cndmask_b32_e64 v30, 0, 1, s21
556v_lshl_or_b32 v43, v30, 8, v43
557v_cmpx_neq_f16_e32 0, v10
558s_mov_b32 s21, exec_lo
559s_mov_b32 exec_lo, s20
560v_cndmask_b32_e64 v30, 0, 1, s21
561v_lshl_or_b32 v43, v30, 9, v43
562v_cmpx_neq_f16_e32 v4, v11
563s_mov_b32 s21, exec_lo
564s_mov_b32 exec_lo, s20
565v_cndmask_b32_e64 v30, 0, 1, s21
566v_lshl_or_b32 v43, v30, 10, v43
567v_cmpx_neq_f16_e32 v5, v12
568s_mov_b32 s21, exec_lo
569s_mov_b32 exec_lo, s20
570v_cndmask_b32_e64 v30, 0, 1, s21
571v_lshl_or_b32 v43, v30, 11, v43
572v_cmpx_neq_f16_e32 v6, v13
573s_mov_b32 s21, exec_lo
574s_mov_b32 exec_lo, s20
575v_cndmask_b32_e64 v30, 0, 1, s21
576v_lshl_or_b32 v43, v30, 12, v43
577v_cmpx_neq_f16_e32 v7, v14
578s_mov_b32 s21, exec_lo
579s_mov_b32 exec_lo, s20
580v_cndmask_b32_e64 v30, 0, 1, s21
581v_lshl_or_b32 v43, v30, 13, v43
582v_cmpx_nlt_f16_e32 1.0, v8
583s_mov_b32 s21, exec_lo
584s_mov_b32 exec_lo, s20
585v_cndmask_b32_e64 v30, 0, 1, s21
586v_lshl_or_b32 v43, v30, 14, v43
587v_cmpx_nlt_f16_e32 2.0, v9
588s_mov_b32 s21, exec_lo
589s_mov_b32 exec_lo, s20
590v_cndmask_b32_e64 v30, 0, 1, s21
591v_lshl_or_b32 v43, v30, 15, v43
592v_cmpx_nlt_f16_e32 0, v10
593s_mov_b32 s21, exec_lo
594s_mov_b32 exec_lo, s20
595v_cndmask_b32_e64 v30, 0, 1, s21
596v_lshl_or_b32 v43, v30, 16, v43
597v_cmpx_nlt_f16_e32 v4, v11
598s_mov_b32 s21, exec_lo
599s_mov_b32 exec_lo, s20
600v_cndmask_b32_e64 v30, 0, 1, s21
601v_lshl_or_b32 v43, v30, 17, v43
602v_cmpx_nlt_f16_e32 v5, v12
603s_mov_b32 s21, exec_lo
604s_mov_b32 exec_lo, s20
605v_cndmask_b32_e64 v30, 0, 1, s21
606v_lshl_or_b32 v43, v30, 18, v43
607v_cmpx_nlt_f16_e32 v6, v13
608s_mov_b32 s21, exec_lo
609s_mov_b32 exec_lo, s20
610v_cndmask_b32_e64 v30, 0, 1, s21
611v_lshl_or_b32 v43, v30, 19, v43
612v_cmpx_nlt_f16_e32 v7, v14
613s_mov_b32 s21, exec_lo
614s_mov_b32 exec_lo, s20
615v_cndmask_b32_e64 v30, 0, 1, s21
616v_lshl_or_b32 v43, v30, 20, v43
617v_cmpx_tru_f16_e32 1.0, v8
618s_mov_b32 s21, exec_lo
619s_mov_b32 exec_lo, s20
620v_cndmask_b32_e64 v30, 0, 1, s21
621v_lshl_or_b32 v43, v30, 21, v43
622v_cmpx_tru_f16_e32 2.0, v9
623s_mov_b32 s21, exec_lo
624s_mov_b32 exec_lo, s20
625v_cndmask_b32_e64 v30, 0, 1, s21
626v_lshl_or_b32 v43, v30, 22, v43
627v_cmpx_tru_f16_e32 0, v10
628s_mov_b32 s21, exec_lo
629s_mov_b32 exec_lo, s20
630v_cndmask_b32_e64 v30, 0, 1, s21
631v_lshl_or_b32 v43, v30, 23, v43
632v_cmpx_tru_f16_e32 v4, v11
633s_mov_b32 s21, exec_lo
634s_mov_b32 exec_lo, s20
635v_cndmask_b32_e64 v30, 0, 1, s21
636v_lshl_or_b32 v43, v30, 24, v43
637v_cmpx_tru_f16_e32 v5, v12
638s_mov_b32 s21, exec_lo
639s_mov_b32 exec_lo, s20
640v_cndmask_b32_e64 v30, 0, 1, s21
641v_lshl_or_b32 v43, v30, 25, v43
642v_cmpx_tru_f16_e32 v6, v13
643s_mov_b32 s21, exec_lo
644s_mov_b32 exec_lo, s20
645v_cndmask_b32_e64 v30, 0, 1, s21
646v_lshl_or_b32 v43, v30, 26, v43
647v_cmpx_tru_f16_e32 v7, v14
648s_mov_b32 s21, exec_lo
649s_mov_b32 exec_lo, s20
650v_cndmask_b32_e64 v30, 0, 1, s21
651v_lshl_or_b32 v43, v30, 27, v43
652exp mrt0 v40, v41, v42, v43 done vm
653s_endpgm
diff --git a/runtime/test/shaders/ps_vcmpx_f16_e64.asm b/runtime/test/shaders/ps_vcmpx_f16_e64.asm
new file mode 100644
index 000000000..62250f738
--- /dev/null
+++ b/runtime/test/shaders/ps_vcmpx_f16_e64.asm
@@ -0,0 +1,639 @@
1; 16-bit float v_cmpx, e64 form with swapped operands: v_cmpx_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16_e64
2; B, A (no SDST: the VOP3 form of v_cmpx writes EXEC). Same seven operand pairs, EXEC copy-out/restore and VCC/AND bits
3; as ps_vcmpx_f16 (see its header), but src0 is the VGPR B and src1 is A (the inline constant for k0..k2), so each op
4; sees the mirrored relation: LESS = {k1,k5} = 0x22, GREATER = {k0,k6} = 0x41, EQUAL = {k2} = 0x04,
5; UNORDERED = {k3,k4} = 0x18. Masks (bit k = result on case k):
6; f 0x00 lt 0x22 eq 0x04 le 0x26 gt 0x41 lg 0x63 ge 0x45 o 0x67
7; u 0x18 nge 0x3a nlg 0x1c ngt 0x3e nle 0x59 neq 0x7b nlt 0x5d tru 0x7f
8; Word w holds ops 4w..4w+3, op j at bit 7*j + k; bit 30 = 1, bit 29 = 1 (VCC kept), bit 28 = 0 (AND into EXEC):
9; word 0 = 0x60000000 | 0x00 | 0x22<<7 | 0x04<<14 | 0x26<<21 = 0x60000000 + 0x1100 + 0x10000 + 0x4c00000 = 0x64c11100
10; word 1 = 0x60000000 | 0x41 | 0x63<<7 | 0x45<<14 | 0x67<<21 = 0x60000000 + 0x31c1 + 0x114000 + 0xce00000 = 0x6cf171c1
11; word 2 = 0x60000000 | 0x18 | 0x3a<<7 | 0x1c<<14 | 0x3e<<21 = 0x60000000 + 0x1d18 + 0x70000 + 0x7c00000 = 0x67c71d18
12; word 3 = 0x60000000 | 0x59 | 0x7b<<7 | 0x5d<<14 | 0x7f<<21 = 0x60000000 + 0x3dd9 + 0x174000 + 0xfe00000 = 0x6ff77dd9
13; Expected mrt0 bits: 0x64c11100, 0x6cf171c1, 0x67c71d18, 0x6ff77dd9
14v_mov_b32_e32 v8, 0x12344000
15v_mov_b32_e32 v9, 0xabcd3c00
16v_mov_b32_e32 v10, 0xffff8000
17v_mov_b32_e32 v4, 0xffff7e00
18v_mov_b32_e32 v11, 0x00013c00
19v_mov_b32_e32 v5, 0x55553c00
20v_mov_b32_e32 v12, 0x7c007c01
21v_mov_b32_e32 v6, 0x00017c00
22v_mov_b32_e32 v13, 0xbeeffc00
23v_mov_b32_e32 v7, 0xdead0001
24v_mov_b32_e32 v14, 0x80000002
25s_mov_b32 s20, exec_lo
26v_mov_b32_e32 v40, 0x40000000
27v_cmp_tru_f16_e32 vcc_lo, v8, v8
28v_cmpx_f_f16_e64 v8, v8
29s_mov_b32 s21, exec_lo
30s_mov_b32 exec_lo, s20
31v_cndmask_b32_e64 v30, 0, 1, vcc_lo
32v_lshl_or_b32 v40, v30, 29, v40
33v_cmpx_f_f16_e64 v8, v8
34v_cmpx_tru_f16_e64 v8, v8
35s_mov_b32 s21, exec_lo
36s_mov_b32 exec_lo, s20
37v_cndmask_b32_e64 v30, 0, 1, s21
38v_lshl_or_b32 v40, v30, 28, v40
39v_cmpx_f_f16_e64 v8, 1.0
40s_mov_b32 s21, exec_lo
41s_mov_b32 exec_lo, s20
42v_cndmask_b32_e64 v30, 0, 1, s21
43v_lshl_or_b32 v40, v30, 0, v40
44v_cmpx_f_f16_e64 v9, 2.0
45s_mov_b32 s21, exec_lo
46s_mov_b32 exec_lo, s20
47v_cndmask_b32_e64 v30, 0, 1, s21
48v_lshl_or_b32 v40, v30, 1, v40
49v_cmpx_f_f16_e64 v10, 0
50s_mov_b32 s21, exec_lo
51s_mov_b32 exec_lo, s20
52v_cndmask_b32_e64 v30, 0, 1, s21
53v_lshl_or_b32 v40, v30, 2, v40
54v_cmpx_f_f16_e64 v11, v4
55s_mov_b32 s21, exec_lo
56s_mov_b32 exec_lo, s20
57v_cndmask_b32_e64 v30, 0, 1, s21
58v_lshl_or_b32 v40, v30, 3, v40
59v_cmpx_f_f16_e64 v12, v5
60s_mov_b32 s21, exec_lo
61s_mov_b32 exec_lo, s20
62v_cndmask_b32_e64 v30, 0, 1, s21
63v_lshl_or_b32 v40, v30, 4, v40
64v_cmpx_f_f16_e64 v13, v6
65s_mov_b32 s21, exec_lo
66s_mov_b32 exec_lo, s20
67v_cndmask_b32_e64 v30, 0, 1, s21
68v_lshl_or_b32 v40, v30, 5, v40
69v_cmpx_f_f16_e64 v14, v7
70s_mov_b32 s21, exec_lo
71s_mov_b32 exec_lo, s20
72v_cndmask_b32_e64 v30, 0, 1, s21
73v_lshl_or_b32 v40, v30, 6, v40
74v_cmpx_lt_f16_e64 v8, 1.0
75s_mov_b32 s21, exec_lo
76s_mov_b32 exec_lo, s20
77v_cndmask_b32_e64 v30, 0, 1, s21
78v_lshl_or_b32 v40, v30, 7, v40
79v_cmpx_lt_f16_e64 v9, 2.0
80s_mov_b32 s21, exec_lo
81s_mov_b32 exec_lo, s20
82v_cndmask_b32_e64 v30, 0, 1, s21
83v_lshl_or_b32 v40, v30, 8, v40
84v_cmpx_lt_f16_e64 v10, 0
85s_mov_b32 s21, exec_lo
86s_mov_b32 exec_lo, s20
87v_cndmask_b32_e64 v30, 0, 1, s21
88v_lshl_or_b32 v40, v30, 9, v40
89v_cmpx_lt_f16_e64 v11, v4
90s_mov_b32 s21, exec_lo
91s_mov_b32 exec_lo, s20
92v_cndmask_b32_e64 v30, 0, 1, s21
93v_lshl_or_b32 v40, v30, 10, v40
94v_cmpx_lt_f16_e64 v12, v5
95s_mov_b32 s21, exec_lo
96s_mov_b32 exec_lo, s20
97v_cndmask_b32_e64 v30, 0, 1, s21
98v_lshl_or_b32 v40, v30, 11, v40
99v_cmpx_lt_f16_e64 v13, v6
100s_mov_b32 s21, exec_lo
101s_mov_b32 exec_lo, s20
102v_cndmask_b32_e64 v30, 0, 1, s21
103v_lshl_or_b32 v40, v30, 12, v40
104v_cmpx_lt_f16_e64 v14, v7
105s_mov_b32 s21, exec_lo
106s_mov_b32 exec_lo, s20
107v_cndmask_b32_e64 v30, 0, 1, s21
108v_lshl_or_b32 v40, v30, 13, v40
109v_cmpx_eq_f16_e64 v8, 1.0
110s_mov_b32 s21, exec_lo
111s_mov_b32 exec_lo, s20
112v_cndmask_b32_e64 v30, 0, 1, s21
113v_lshl_or_b32 v40, v30, 14, v40
114v_cmpx_eq_f16_e64 v9, 2.0
115s_mov_b32 s21, exec_lo
116s_mov_b32 exec_lo, s20
117v_cndmask_b32_e64 v30, 0, 1, s21
118v_lshl_or_b32 v40, v30, 15, v40
119v_cmpx_eq_f16_e64 v10, 0
120s_mov_b32 s21, exec_lo
121s_mov_b32 exec_lo, s20
122v_cndmask_b32_e64 v30, 0, 1, s21
123v_lshl_or_b32 v40, v30, 16, v40
124v_cmpx_eq_f16_e64 v11, v4
125s_mov_b32 s21, exec_lo
126s_mov_b32 exec_lo, s20
127v_cndmask_b32_e64 v30, 0, 1, s21
128v_lshl_or_b32 v40, v30, 17, v40
129v_cmpx_eq_f16_e64 v12, v5
130s_mov_b32 s21, exec_lo
131s_mov_b32 exec_lo, s20
132v_cndmask_b32_e64 v30, 0, 1, s21
133v_lshl_or_b32 v40, v30, 18, v40
134v_cmpx_eq_f16_e64 v13, v6
135s_mov_b32 s21, exec_lo
136s_mov_b32 exec_lo, s20
137v_cndmask_b32_e64 v30, 0, 1, s21
138v_lshl_or_b32 v40, v30, 19, v40
139v_cmpx_eq_f16_e64 v14, v7
140s_mov_b32 s21, exec_lo
141s_mov_b32 exec_lo, s20
142v_cndmask_b32_e64 v30, 0, 1, s21
143v_lshl_or_b32 v40, v30, 20, v40
144v_cmpx_le_f16_e64 v8, 1.0
145s_mov_b32 s21, exec_lo
146s_mov_b32 exec_lo, s20
147v_cndmask_b32_e64 v30, 0, 1, s21
148v_lshl_or_b32 v40, v30, 21, v40
149v_cmpx_le_f16_e64 v9, 2.0
150s_mov_b32 s21, exec_lo
151s_mov_b32 exec_lo, s20
152v_cndmask_b32_e64 v30, 0, 1, s21
153v_lshl_or_b32 v40, v30, 22, v40
154v_cmpx_le_f16_e64 v10, 0
155s_mov_b32 s21, exec_lo
156s_mov_b32 exec_lo, s20
157v_cndmask_b32_e64 v30, 0, 1, s21
158v_lshl_or_b32 v40, v30, 23, v40
159v_cmpx_le_f16_e64 v11, v4
160s_mov_b32 s21, exec_lo
161s_mov_b32 exec_lo, s20
162v_cndmask_b32_e64 v30, 0, 1, s21
163v_lshl_or_b32 v40, v30, 24, v40
164v_cmpx_le_f16_e64 v12, v5
165s_mov_b32 s21, exec_lo
166s_mov_b32 exec_lo, s20
167v_cndmask_b32_e64 v30, 0, 1, s21
168v_lshl_or_b32 v40, v30, 25, v40
169v_cmpx_le_f16_e64 v13, v6
170s_mov_b32 s21, exec_lo
171s_mov_b32 exec_lo, s20
172v_cndmask_b32_e64 v30, 0, 1, s21
173v_lshl_or_b32 v40, v30, 26, v40
174v_cmpx_le_f16_e64 v14, v7
175s_mov_b32 s21, exec_lo
176s_mov_b32 exec_lo, s20
177v_cndmask_b32_e64 v30, 0, 1, s21
178v_lshl_or_b32 v40, v30, 27, v40
179v_mov_b32_e32 v41, 0x40000000
180v_cmp_tru_f16_e32 vcc_lo, v8, v8
181v_cmpx_f_f16_e64 v8, v8
182s_mov_b32 s21, exec_lo
183s_mov_b32 exec_lo, s20
184v_cndmask_b32_e64 v30, 0, 1, vcc_lo
185v_lshl_or_b32 v41, v30, 29, v41
186v_cmpx_f_f16_e64 v8, v8
187v_cmpx_tru_f16_e64 v8, v8
188s_mov_b32 s21, exec_lo
189s_mov_b32 exec_lo, s20
190v_cndmask_b32_e64 v30, 0, 1, s21
191v_lshl_or_b32 v41, v30, 28, v41
192v_cmpx_gt_f16_e64 v8, 1.0
193s_mov_b32 s21, exec_lo
194s_mov_b32 exec_lo, s20
195v_cndmask_b32_e64 v30, 0, 1, s21
196v_lshl_or_b32 v41, v30, 0, v41
197v_cmpx_gt_f16_e64 v9, 2.0
198s_mov_b32 s21, exec_lo
199s_mov_b32 exec_lo, s20
200v_cndmask_b32_e64 v30, 0, 1, s21
201v_lshl_or_b32 v41, v30, 1, v41
202v_cmpx_gt_f16_e64 v10, 0
203s_mov_b32 s21, exec_lo
204s_mov_b32 exec_lo, s20
205v_cndmask_b32_e64 v30, 0, 1, s21
206v_lshl_or_b32 v41, v30, 2, v41
207v_cmpx_gt_f16_e64 v11, v4
208s_mov_b32 s21, exec_lo
209s_mov_b32 exec_lo, s20
210v_cndmask_b32_e64 v30, 0, 1, s21
211v_lshl_or_b32 v41, v30, 3, v41
212v_cmpx_gt_f16_e64 v12, v5
213s_mov_b32 s21, exec_lo
214s_mov_b32 exec_lo, s20
215v_cndmask_b32_e64 v30, 0, 1, s21
216v_lshl_or_b32 v41, v30, 4, v41
217v_cmpx_gt_f16_e64 v13, v6
218s_mov_b32 s21, exec_lo
219s_mov_b32 exec_lo, s20
220v_cndmask_b32_e64 v30, 0, 1, s21
221v_lshl_or_b32 v41, v30, 5, v41
222v_cmpx_gt_f16_e64 v14, v7
223s_mov_b32 s21, exec_lo
224s_mov_b32 exec_lo, s20
225v_cndmask_b32_e64 v30, 0, 1, s21
226v_lshl_or_b32 v41, v30, 6, v41
227v_cmpx_lg_f16_e64 v8, 1.0
228s_mov_b32 s21, exec_lo
229s_mov_b32 exec_lo, s20
230v_cndmask_b32_e64 v30, 0, 1, s21
231v_lshl_or_b32 v41, v30, 7, v41
232v_cmpx_lg_f16_e64 v9, 2.0
233s_mov_b32 s21, exec_lo
234s_mov_b32 exec_lo, s20
235v_cndmask_b32_e64 v30, 0, 1, s21
236v_lshl_or_b32 v41, v30, 8, v41
237v_cmpx_lg_f16_e64 v10, 0
238s_mov_b32 s21, exec_lo
239s_mov_b32 exec_lo, s20
240v_cndmask_b32_e64 v30, 0, 1, s21
241v_lshl_or_b32 v41, v30, 9, v41
242v_cmpx_lg_f16_e64 v11, v4
243s_mov_b32 s21, exec_lo
244s_mov_b32 exec_lo, s20
245v_cndmask_b32_e64 v30, 0, 1, s21
246v_lshl_or_b32 v41, v30, 10, v41
247v_cmpx_lg_f16_e64 v12, v5
248s_mov_b32 s21, exec_lo
249s_mov_b32 exec_lo, s20
250v_cndmask_b32_e64 v30, 0, 1, s21
251v_lshl_or_b32 v41, v30, 11, v41
252v_cmpx_lg_f16_e64 v13, v6
253s_mov_b32 s21, exec_lo
254s_mov_b32 exec_lo, s20
255v_cndmask_b32_e64 v30, 0, 1, s21
256v_lshl_or_b32 v41, v30, 12, v41
257v_cmpx_lg_f16_e64 v14, v7
258s_mov_b32 s21, exec_lo
259s_mov_b32 exec_lo, s20
260v_cndmask_b32_e64 v30, 0, 1, s21
261v_lshl_or_b32 v41, v30, 13, v41
262v_cmpx_ge_f16_e64 v8, 1.0
263s_mov_b32 s21, exec_lo
264s_mov_b32 exec_lo, s20
265v_cndmask_b32_e64 v30, 0, 1, s21
266v_lshl_or_b32 v41, v30, 14, v41
267v_cmpx_ge_f16_e64 v9, 2.0
268s_mov_b32 s21, exec_lo
269s_mov_b32 exec_lo, s20
270v_cndmask_b32_e64 v30, 0, 1, s21
271v_lshl_or_b32 v41, v30, 15, v41
272v_cmpx_ge_f16_e64 v10, 0
273s_mov_b32 s21, exec_lo
274s_mov_b32 exec_lo, s20
275v_cndmask_b32_e64 v30, 0, 1, s21
276v_lshl_or_b32 v41, v30, 16, v41
277v_cmpx_ge_f16_e64 v11, v4
278s_mov_b32 s21, exec_lo
279s_mov_b32 exec_lo, s20
280v_cndmask_b32_e64 v30, 0, 1, s21
281v_lshl_or_b32 v41, v30, 17, v41
282v_cmpx_ge_f16_e64 v12, v5
283s_mov_b32 s21, exec_lo
284s_mov_b32 exec_lo, s20
285v_cndmask_b32_e64 v30, 0, 1, s21
286v_lshl_or_b32 v41, v30, 18, v41
287v_cmpx_ge_f16_e64 v13, v6
288s_mov_b32 s21, exec_lo
289s_mov_b32 exec_lo, s20
290v_cndmask_b32_e64 v30, 0, 1, s21
291v_lshl_or_b32 v41, v30, 19, v41
292v_cmpx_ge_f16_e64 v14, v7
293s_mov_b32 s21, exec_lo
294s_mov_b32 exec_lo, s20
295v_cndmask_b32_e64 v30, 0, 1, s21
296v_lshl_or_b32 v41, v30, 20, v41
297v_cmpx_o_f16_e64 v8, 1.0
298s_mov_b32 s21, exec_lo
299s_mov_b32 exec_lo, s20
300v_cndmask_b32_e64 v30, 0, 1, s21
301v_lshl_or_b32 v41, v30, 21, v41
302v_cmpx_o_f16_e64 v9, 2.0
303s_mov_b32 s21, exec_lo
304s_mov_b32 exec_lo, s20
305v_cndmask_b32_e64 v30, 0, 1, s21
306v_lshl_or_b32 v41, v30, 22, v41
307v_cmpx_o_f16_e64 v10, 0
308s_mov_b32 s21, exec_lo
309s_mov_b32 exec_lo, s20
310v_cndmask_b32_e64 v30, 0, 1, s21
311v_lshl_or_b32 v41, v30, 23, v41
312v_cmpx_o_f16_e64 v11, v4
313s_mov_b32 s21, exec_lo
314s_mov_b32 exec_lo, s20
315v_cndmask_b32_e64 v30, 0, 1, s21
316v_lshl_or_b32 v41, v30, 24, v41
317v_cmpx_o_f16_e64 v12, v5
318s_mov_b32 s21, exec_lo
319s_mov_b32 exec_lo, s20
320v_cndmask_b32_e64 v30, 0, 1, s21
321v_lshl_or_b32 v41, v30, 25, v41
322v_cmpx_o_f16_e64 v13, v6
323s_mov_b32 s21, exec_lo
324s_mov_b32 exec_lo, s20
325v_cndmask_b32_e64 v30, 0, 1, s21
326v_lshl_or_b32 v41, v30, 26, v41
327v_cmpx_o_f16_e64 v14, v7
328s_mov_b32 s21, exec_lo
329s_mov_b32 exec_lo, s20
330v_cndmask_b32_e64 v30, 0, 1, s21
331v_lshl_or_b32 v41, v30, 27, v41
332v_mov_b32_e32 v42, 0x40000000
333v_cmp_tru_f16_e32 vcc_lo, v8, v8
334v_cmpx_f_f16_e64 v8, v8
335s_mov_b32 s21, exec_lo
336s_mov_b32 exec_lo, s20
337v_cndmask_b32_e64 v30, 0, 1, vcc_lo
338v_lshl_or_b32 v42, v30, 29, v42
339v_cmpx_f_f16_e64 v8, v8
340v_cmpx_tru_f16_e64 v8, v8
341s_mov_b32 s21, exec_lo
342s_mov_b32 exec_lo, s20
343v_cndmask_b32_e64 v30, 0, 1, s21
344v_lshl_or_b32 v42, v30, 28, v42
345v_cmpx_u_f16_e64 v8, 1.0
346s_mov_b32 s21, exec_lo
347s_mov_b32 exec_lo, s20
348v_cndmask_b32_e64 v30, 0, 1, s21
349v_lshl_or_b32 v42, v30, 0, v42
350v_cmpx_u_f16_e64 v9, 2.0
351s_mov_b32 s21, exec_lo
352s_mov_b32 exec_lo, s20
353v_cndmask_b32_e64 v30, 0, 1, s21
354v_lshl_or_b32 v42, v30, 1, v42
355v_cmpx_u_f16_e64 v10, 0
356s_mov_b32 s21, exec_lo
357s_mov_b32 exec_lo, s20
358v_cndmask_b32_e64 v30, 0, 1, s21
359v_lshl_or_b32 v42, v30, 2, v42
360v_cmpx_u_f16_e64 v11, v4
361s_mov_b32 s21, exec_lo
362s_mov_b32 exec_lo, s20
363v_cndmask_b32_e64 v30, 0, 1, s21
364v_lshl_or_b32 v42, v30, 3, v42
365v_cmpx_u_f16_e64 v12, v5
366s_mov_b32 s21, exec_lo
367s_mov_b32 exec_lo, s20
368v_cndmask_b32_e64 v30, 0, 1, s21
369v_lshl_or_b32 v42, v30, 4, v42
370v_cmpx_u_f16_e64 v13, v6
371s_mov_b32 s21, exec_lo
372s_mov_b32 exec_lo, s20
373v_cndmask_b32_e64 v30, 0, 1, s21
374v_lshl_or_b32 v42, v30, 5, v42
375v_cmpx_u_f16_e64 v14, v7
376s_mov_b32 s21, exec_lo
377s_mov_b32 exec_lo, s20
378v_cndmask_b32_e64 v30, 0, 1, s21
379v_lshl_or_b32 v42, v30, 6, v42
380v_cmpx_nge_f16_e64 v8, 1.0
381s_mov_b32 s21, exec_lo
382s_mov_b32 exec_lo, s20
383v_cndmask_b32_e64 v30, 0, 1, s21
384v_lshl_or_b32 v42, v30, 7, v42
385v_cmpx_nge_f16_e64 v9, 2.0
386s_mov_b32 s21, exec_lo
387s_mov_b32 exec_lo, s20
388v_cndmask_b32_e64 v30, 0, 1, s21
389v_lshl_or_b32 v42, v30, 8, v42
390v_cmpx_nge_f16_e64 v10, 0
391s_mov_b32 s21, exec_lo
392s_mov_b32 exec_lo, s20
393v_cndmask_b32_e64 v30, 0, 1, s21
394v_lshl_or_b32 v42, v30, 9, v42
395v_cmpx_nge_f16_e64 v11, v4
396s_mov_b32 s21, exec_lo
397s_mov_b32 exec_lo, s20
398v_cndmask_b32_e64 v30, 0, 1, s21
399v_lshl_or_b32 v42, v30, 10, v42
400v_cmpx_nge_f16_e64 v12, v5
401s_mov_b32 s21, exec_lo
402s_mov_b32 exec_lo, s20
403v_cndmask_b32_e64 v30, 0, 1, s21
404v_lshl_or_b32 v42, v30, 11, v42
405v_cmpx_nge_f16_e64 v13, v6
406s_mov_b32 s21, exec_lo
407s_mov_b32 exec_lo, s20
408v_cndmask_b32_e64 v30, 0, 1, s21
409v_lshl_or_b32 v42, v30, 12, v42
410v_cmpx_nge_f16_e64 v14, v7
411s_mov_b32 s21, exec_lo
412s_mov_b32 exec_lo, s20
413v_cndmask_b32_e64 v30, 0, 1, s21
414v_lshl_or_b32 v42, v30, 13, v42
415v_cmpx_nlg_f16_e64 v8, 1.0
416s_mov_b32 s21, exec_lo
417s_mov_b32 exec_lo, s20
418v_cndmask_b32_e64 v30, 0, 1, s21
419v_lshl_or_b32 v42, v30, 14, v42
420v_cmpx_nlg_f16_e64 v9, 2.0
421s_mov_b32 s21, exec_lo
422s_mov_b32 exec_lo, s20
423v_cndmask_b32_e64 v30, 0, 1, s21
424v_lshl_or_b32 v42, v30, 15, v42
425v_cmpx_nlg_f16_e64 v10, 0
426s_mov_b32 s21, exec_lo
427s_mov_b32 exec_lo, s20
428v_cndmask_b32_e64 v30, 0, 1, s21
429v_lshl_or_b32 v42, v30, 16, v42
430v_cmpx_nlg_f16_e64 v11, v4
431s_mov_b32 s21, exec_lo
432s_mov_b32 exec_lo, s20
433v_cndmask_b32_e64 v30, 0, 1, s21
434v_lshl_or_b32 v42, v30, 17, v42
435v_cmpx_nlg_f16_e64 v12, v5
436s_mov_b32 s21, exec_lo
437s_mov_b32 exec_lo, s20
438v_cndmask_b32_e64 v30, 0, 1, s21
439v_lshl_or_b32 v42, v30, 18, v42
440v_cmpx_nlg_f16_e64 v13, v6
441s_mov_b32 s21, exec_lo
442s_mov_b32 exec_lo, s20
443v_cndmask_b32_e64 v30, 0, 1, s21
444v_lshl_or_b32 v42, v30, 19, v42
445v_cmpx_nlg_f16_e64 v14, v7
446s_mov_b32 s21, exec_lo
447s_mov_b32 exec_lo, s20
448v_cndmask_b32_e64 v30, 0, 1, s21
449v_lshl_or_b32 v42, v30, 20, v42
450v_cmpx_ngt_f16_e64 v8, 1.0
451s_mov_b32 s21, exec_lo
452s_mov_b32 exec_lo, s20
453v_cndmask_b32_e64 v30, 0, 1, s21
454v_lshl_or_b32 v42, v30, 21, v42
455v_cmpx_ngt_f16_e64 v9, 2.0
456s_mov_b32 s21, exec_lo
457s_mov_b32 exec_lo, s20
458v_cndmask_b32_e64 v30, 0, 1, s21
459v_lshl_or_b32 v42, v30, 22, v42
460v_cmpx_ngt_f16_e64 v10, 0
461s_mov_b32 s21, exec_lo
462s_mov_b32 exec_lo, s20
463v_cndmask_b32_e64 v30, 0, 1, s21
464v_lshl_or_b32 v42, v30, 23, v42
465v_cmpx_ngt_f16_e64 v11, v4
466s_mov_b32 s21, exec_lo
467s_mov_b32 exec_lo, s20
468v_cndmask_b32_e64 v30, 0, 1, s21
469v_lshl_or_b32 v42, v30, 24, v42
470v_cmpx_ngt_f16_e64 v12, v5
471s_mov_b32 s21, exec_lo
472s_mov_b32 exec_lo, s20
473v_cndmask_b32_e64 v30, 0, 1, s21
474v_lshl_or_b32 v42, v30, 25, v42
475v_cmpx_ngt_f16_e64 v13, v6
476s_mov_b32 s21, exec_lo
477s_mov_b32 exec_lo, s20
478v_cndmask_b32_e64 v30, 0, 1, s21
479v_lshl_or_b32 v42, v30, 26, v42
480v_cmpx_ngt_f16_e64 v14, v7
481s_mov_b32 s21, exec_lo
482s_mov_b32 exec_lo, s20
483v_cndmask_b32_e64 v30, 0, 1, s21
484v_lshl_or_b32 v42, v30, 27, v42
485v_mov_b32_e32 v43, 0x40000000
486v_cmp_tru_f16_e32 vcc_lo, v8, v8
487v_cmpx_f_f16_e64 v8, v8
488s_mov_b32 s21, exec_lo
489s_mov_b32 exec_lo, s20
490v_cndmask_b32_e64 v30, 0, 1, vcc_lo
491v_lshl_or_b32 v43, v30, 29, v43
492v_cmpx_f_f16_e64 v8, v8
493v_cmpx_tru_f16_e64 v8, v8
494s_mov_b32 s21, exec_lo
495s_mov_b32 exec_lo, s20
496v_cndmask_b32_e64 v30, 0, 1, s21
497v_lshl_or_b32 v43, v30, 28, v43
498v_cmpx_nle_f16_e64 v8, 1.0
499s_mov_b32 s21, exec_lo
500s_mov_b32 exec_lo, s20
501v_cndmask_b32_e64 v30, 0, 1, s21
502v_lshl_or_b32 v43, v30, 0, v43
503v_cmpx_nle_f16_e64 v9, 2.0
504s_mov_b32 s21, exec_lo
505s_mov_b32 exec_lo, s20
506v_cndmask_b32_e64 v30, 0, 1, s21
507v_lshl_or_b32 v43, v30, 1, v43
508v_cmpx_nle_f16_e64 v10, 0
509s_mov_b32 s21, exec_lo
510s_mov_b32 exec_lo, s20
511v_cndmask_b32_e64 v30, 0, 1, s21
512v_lshl_or_b32 v43, v30, 2, v43
513v_cmpx_nle_f16_e64 v11, v4
514s_mov_b32 s21, exec_lo
515s_mov_b32 exec_lo, s20
516v_cndmask_b32_e64 v30, 0, 1, s21
517v_lshl_or_b32 v43, v30, 3, v43
518v_cmpx_nle_f16_e64 v12, v5
519s_mov_b32 s21, exec_lo
520s_mov_b32 exec_lo, s20
521v_cndmask_b32_e64 v30, 0, 1, s21
522v_lshl_or_b32 v43, v30, 4, v43
523v_cmpx_nle_f16_e64 v13, v6
524s_mov_b32 s21, exec_lo
525s_mov_b32 exec_lo, s20
526v_cndmask_b32_e64 v30, 0, 1, s21
527v_lshl_or_b32 v43, v30, 5, v43
528v_cmpx_nle_f16_e64 v14, v7
529s_mov_b32 s21, exec_lo
530s_mov_b32 exec_lo, s20
531v_cndmask_b32_e64 v30, 0, 1, s21
532v_lshl_or_b32 v43, v30, 6, v43
533v_cmpx_neq_f16_e64 v8, 1.0
534s_mov_b32 s21, exec_lo
535s_mov_b32 exec_lo, s20
536v_cndmask_b32_e64 v30, 0, 1, s21
537v_lshl_or_b32 v43, v30, 7, v43
538v_cmpx_neq_f16_e64 v9, 2.0
539s_mov_b32 s21, exec_lo
540s_mov_b32 exec_lo, s20
541v_cndmask_b32_e64 v30, 0, 1, s21
542v_lshl_or_b32 v43, v30, 8, v43
543v_cmpx_neq_f16_e64 v10, 0
544s_mov_b32 s21, exec_lo
545s_mov_b32 exec_lo, s20
546v_cndmask_b32_e64 v30, 0, 1, s21
547v_lshl_or_b32 v43, v30, 9, v43
548v_cmpx_neq_f16_e64 v11, v4
549s_mov_b32 s21, exec_lo
550s_mov_b32 exec_lo, s20
551v_cndmask_b32_e64 v30, 0, 1, s21
552v_lshl_or_b32 v43, v30, 10, v43
553v_cmpx_neq_f16_e64 v12, v5
554s_mov_b32 s21, exec_lo
555s_mov_b32 exec_lo, s20
556v_cndmask_b32_e64 v30, 0, 1, s21
557v_lshl_or_b32 v43, v30, 11, v43
558v_cmpx_neq_f16_e64 v13, v6
559s_mov_b32 s21, exec_lo
560s_mov_b32 exec_lo, s20
561v_cndmask_b32_e64 v30, 0, 1, s21
562v_lshl_or_b32 v43, v30, 12, v43
563v_cmpx_neq_f16_e64 v14, v7
564s_mov_b32 s21, exec_lo
565s_mov_b32 exec_lo, s20
566v_cndmask_b32_e64 v30, 0, 1, s21
567v_lshl_or_b32 v43, v30, 13, v43
568v_cmpx_nlt_f16_e64 v8, 1.0
569s_mov_b32 s21, exec_lo
570s_mov_b32 exec_lo, s20
571v_cndmask_b32_e64 v30, 0, 1, s21
572v_lshl_or_b32 v43, v30, 14, v43
573v_cmpx_nlt_f16_e64 v9, 2.0
574s_mov_b32 s21, exec_lo
575s_mov_b32 exec_lo, s20
576v_cndmask_b32_e64 v30, 0, 1, s21
577v_lshl_or_b32 v43, v30, 15, v43
578v_cmpx_nlt_f16_e64 v10, 0
579s_mov_b32 s21, exec_lo
580s_mov_b32 exec_lo, s20
581v_cndmask_b32_e64 v30, 0, 1, s21
582v_lshl_or_b32 v43, v30, 16, v43
583v_cmpx_nlt_f16_e64 v11, v4
584s_mov_b32 s21, exec_lo
585s_mov_b32 exec_lo, s20
586v_cndmask_b32_e64 v30, 0, 1, s21
587v_lshl_or_b32 v43, v30, 17, v43
588v_cmpx_nlt_f16_e64 v12, v5
589s_mov_b32 s21, exec_lo
590s_mov_b32 exec_lo, s20
591v_cndmask_b32_e64 v30, 0, 1, s21
592v_lshl_or_b32 v43, v30, 18, v43
593v_cmpx_nlt_f16_e64 v13, v6
594s_mov_b32 s21, exec_lo
595s_mov_b32 exec_lo, s20
596v_cndmask_b32_e64 v30, 0, 1, s21
597v_lshl_or_b32 v43, v30, 19, v43
598v_cmpx_nlt_f16_e64 v14, v7
599s_mov_b32 s21, exec_lo
600s_mov_b32 exec_lo, s20
601v_cndmask_b32_e64 v30, 0, 1, s21
602v_lshl_or_b32 v43, v30, 20, v43
603v_cmpx_tru_f16_e64 v8, 1.0
604s_mov_b32 s21, exec_lo
605s_mov_b32 exec_lo, s20
606v_cndmask_b32_e64 v30, 0, 1, s21
607v_lshl_or_b32 v43, v30, 21, v43
608v_cmpx_tru_f16_e64 v9, 2.0
609s_mov_b32 s21, exec_lo
610s_mov_b32 exec_lo, s20
611v_cndmask_b32_e64 v30, 0, 1, s21
612v_lshl_or_b32 v43, v30, 22, v43
613v_cmpx_tru_f16_e64 v10, 0
614s_mov_b32 s21, exec_lo
615s_mov_b32 exec_lo, s20
616v_cndmask_b32_e64 v30, 0, 1, s21
617v_lshl_or_b32 v43, v30, 23, v43
618v_cmpx_tru_f16_e64 v11, v4
619s_mov_b32 s21, exec_lo
620s_mov_b32 exec_lo, s20
621v_cndmask_b32_e64 v30, 0, 1, s21
622v_lshl_or_b32 v43, v30, 24, v43
623v_cmpx_tru_f16_e64 v12, v5
624s_mov_b32 s21, exec_lo
625s_mov_b32 exec_lo, s20
626v_cndmask_b32_e64 v30, 0, 1, s21
627v_lshl_or_b32 v43, v30, 25, v43
628v_cmpx_tru_f16_e64 v13, v6
629s_mov_b32 s21, exec_lo
630s_mov_b32 exec_lo, s20
631v_cndmask_b32_e64 v30, 0, 1, s21
632v_lshl_or_b32 v43, v30, 26, v43
633v_cmpx_tru_f16_e64 v14, v7
634s_mov_b32 s21, exec_lo
635s_mov_b32 exec_lo, s20
636v_cndmask_b32_e64 v30, 0, 1, s21
637v_lshl_or_b32 v43, v30, 27, v43
638exp mrt0 v40, v41, v42, v43 done vm
639s_endpgm
diff --git a/runtime/test/shaders/vs_base_ids.asm b/runtime/test/shaders/vs_base_ids.asm
new file mode 100644
index 000000000..27e905aea
--- /dev/null
+++ b/runtime/test/shaders/vs_base_ids.asm
@@ -0,0 +1,24 @@
1; Vertex shader for the base-vertex / base-instance test. On AMD hardware the VS input VGPRs are zero-based: v0 is
2; the vertex id without the draw's first vertex (Mesa: ac.vertex_id = load_vertex_id_zero_base, the base comes in
3; the base_vertex SGPR), and v3 the instance id without its first instance (ac.instance_id = load_instance_id, the
4; base in start_instance). Vulkan's VertexIndex / InstanceIndex include firstVertex / firstInstance.
5; Same full-screen triangle as vs_ids (from v0's low bits), param0 = (u, v, 0, 1), and param1.x =
6; 0x101 + v0 + 0x1000 * v3 as raw bits, so ps_flat (attr1.x from the provoking vertex) shows both ids.
7; Run: VKH_DRAW=16,7 vk_harness vs_base_ids.spv ps_flat.spv out.raw
8; -> mrt0 bits = 0x101, 0x102 on every pixel (vertex 0 of instance 0); 0x7111 means firstVertex/firstInstance
9; leaked into v0 / v3. With VKH_DRAW unset (0,0) both read 0x101, as vs_ids.
10v_lshlrev_b32_e32 v8, 12, v3
11v_lshlrev_b32_e32 v1, 1, v0
12v_and_b32_e32 v1, 2, v1
13v_and_b32_e32 v2, 2, v0
14v_cvt_f32_u32_e32 v1, v1
15v_cvt_f32_u32_e32 v2, v2
16v_fma_f32 v3, v1, 2.0, -1.0
17v_fma_f32 v4, v2, 2.0, -1.0
18v_mov_b32_e32 v5, 0
19v_mov_b32_e32 v6, 1.0
20exp pos0 v3, v4, v5, v6 done
21exp param0 v1, v2, v5, v6
22v_add3_u32 v7, v0, v8, 0x101
23exp param1 v7, v7, v7, v7
24s_endpgm
diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py
index efa21c752..988fa4a43 100644
--- a/runtime/test/shaders/w64_graphics.py
+++ b/runtime/test/shaders/w64_graphics.py
@@ -355,6 +355,8 @@ def check(tools, spirv, name):
355 if size == 64: 355 if size == 64:
356 continue 356 continue
357 if tier == "C": 357 if tier == "C":
358 if comparable(name, ref_words, None) != comparable(name, words, None):
359 return "a word that must not depend on the partition differs from the 64-lane reference"
358 if not partition_dependent(name, ref_words, words): 360 if not partition_dependent(name, ref_words, words):
359 return "tier C but the run equals the 64-lane reference: the detector is wrong" 361 return "tier C but the run equals the 64-lane reference: the detector is wrong"
360 compared = True 362 compared = True
diff --git a/runtime/test/spirv_f16_halves_test.cpp b/runtime/test/spirv_f16_halves_test.cpp
new file mode 100644
index 000000000..29bb37113
--- /dev/null
+++ b/runtime/test/spirv_f16_halves_test.cpp
@@ -0,0 +1,300 @@
1// Pure-CPU tests for runtime/src/spirv_f16_halves.h (SHADER-378):
2// - fast path when PS has no f16_halves or VS already matches all PS half locations;
3// - in-place relocation when VS already emits the requested params at different locations;
4// - 16-param VS (param0..param15, static halves only for 0..6) paired with a corpus-style PS (raw 0..14,
5// f16 on 0, 4, 5, 6, 7): unused static halves demoted to Private, reused halves relocated, missing param 7
6// synthesized with OpLoad + 4x UnpackHalf2x16 + OpStore before OpReturn;
7// - PS relocation when a PS half location collides with an unread raw VS output;
8// - SPIR-V 1.3 vs 1.4+ OpEntryPoint interface rules for demoted Private variables;
9// - clean failure on genuine >30 location budget overflow (leaving input buffers untouched).
10// No GPU or game files required.
11#include "../src/spirv_f16_halves.h"
12
13#include <cstdint>
14#include <cstdio>
15#include <map>
16#include <set>
17#include <string>
18#include <vector>
19
20#define CHECK(cond) do { \
21 if (!(cond)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #cond); return 1; } \
22} while (0)
23
24namespace {
25
26using namespace leonida::spirv_detail;
27
28void append_inst(std::vector<std::uint32_t>& w, std::uint16_t op, std::initializer_list<std::uint32_t> args) {
29 w.push_back((std::uint32_t(1 + args.size()) << 16) | op);
30 for (std::uint32_t a : args) w.push_back(a);
31}
32
33void append_inst_vec(std::vector<std::uint32_t>& w, std::uint16_t op, const std::vector<std::uint32_t>& args) {
34 w.push_back((std::uint32_t(1 + args.size()) << 16) | op);
35 w.insert(w.end(), args.begin(), args.end());
36}
37
38// Build a minimal valid Vertex SPIR-V module with `num_raw_params` Output vec4 params (Location 0..num_raw_params-1)
39// and optional static f16_halves Output vec4 vars at the given locations.
40std::vector<std::uint32_t> build_vs(std::uint32_t version, std::uint32_t num_raw_params,
41 const std::map<std::uint32_t, std::array<std::uint32_t, 2>>& static_halves) {
42 // IDs:
43 // 1 = %void, 2 = %fn, 3 = %float, 4 = %v4float, 5 = %ptr_out_v4, 6 = %null_v4, 7 = %main, 8 = %entry
44 // 9 = %out_pos (BuiltIn Position)
45 // 10.. = raw param vars, then static half vars (lo, hi)
46 std::uint32_t next_id = 10;
47 std::vector<std::uint32_t> raw_vars;
48 for (std::uint32_t p = 0; p < num_raw_params; ++p) raw_vars.push_back(next_id++);
49 std::vector<std::pair<std::uint32_t, std::uint32_t>> half_vars; // (var_id, loc)
50 for (const auto& [param, pair] : static_halves) {
51 half_vars.push_back({next_id++, pair[0]});
52 half_vars.push_back({next_id++, pair[1]});
53 }
54
55 std::vector<std::uint32_t> w = {kSpirvMagic, version, 0, next_id, 0};
56 append_inst(w, kOpCapability, {1}); // Shader
57 append_inst(w, kOpMemoryModel, {0, 1}); // Logical GLSL450
58 std::vector<std::uint32_t> ep = {kExecModelVertex, 7, 0x6e69616du, 0x00000000u, 9}; // "main\0"
59 for (std::uint32_t v : raw_vars) ep.push_back(v);
60 for (const auto& [v, loc] : half_vars) ep.push_back(v);
61 append_inst_vec(w, kOpEntryPoint, ep);
62
63 append_inst(w, kOpDecorate, {9, 11, 0}); // BuiltIn Position
64 for (std::uint32_t p = 0; p < num_raw_params; ++p) append_inst(w, kOpDecorate, {raw_vars[p], kDecorationLocation, p});
65 for (const auto& [v, loc] : half_vars) append_inst(w, kOpDecorate, {v, kDecorationLocation, loc});
66
67 append_inst(w, 19, {1}); // OpTypeVoid
68 append_inst(w, 33, {2, 1}); // OpTypeFunction %void
69 append_inst(w, kOpTypeFloat, {3, 32});
70 append_inst(w, kOpTypeVector, {4, 3, 4});
71 append_inst(w, kOpTypePointer, {5, kStorageOutput, 4});
72 append_inst(w, kOpConstantNull, {4, 6});
73 append_inst(w, kOpVariable, {5, 9, kStorageOutput});
74 for (std::uint32_t v : raw_vars) append_inst(w, kOpVariable, {5, v, kStorageOutput});
75 for (const auto& [v, loc] : half_vars) append_inst(w, kOpVariable, {5, v, kStorageOutput});
76
77 append_inst(w, kOpFunction, {1, 7, 0, 2});
78 append_inst(w, 248, {8}); // OpLabel
79 append_inst(w, kOpStore, {9, 6});
80 for (std::uint32_t v : raw_vars) append_inst(w, kOpStore, {v, 6});
81 for (const auto& [v, loc] : half_vars) append_inst(w, kOpStore, {v, 6});
82 append_inst(w, kOpReturn, {});
83 append_inst(w, kOpFunctionEnd, {});
84 return w;
85}
86
87// Build a minimal valid Fragment SPIR-V module with `raw_in_locs` and `half_in_locs` Input vec4 variables.
88std::vector<std::uint32_t> build_ps(std::uint32_t version, const std::vector<std::uint32_t>& raw_in_locs,
89 const std::map<std::uint32_t, std::array<std::uint32_t, 2>>& f16_halves) {
90 // 1 = %void, 2 = %fn, 3 = %float, 4 = %v4float, 5 = %ptr_in_v4, 6 = %ptr_out_v4, 7 = %null_v4, 8 = %out0,
91 // 9 = %main, 10 = %entry
92 std::uint32_t next_id = 11;
93 std::vector<std::pair<std::uint32_t, std::uint32_t>> in_vars; // (var_id, loc)
94 for (std::uint32_t loc : raw_in_locs) in_vars.push_back({next_id++, loc});
95 for (const auto& [param, pair] : f16_halves) {
96 in_vars.push_back({next_id++, pair[0]});
97 in_vars.push_back({next_id++, pair[1]});
98 }
99
100 std::vector<std::uint32_t> w = {kSpirvMagic, version, 0, next_id, 0};
101 append_inst(w, kOpCapability, {1});
102 append_inst(w, kOpMemoryModel, {0, 1});
103 std::vector<std::uint32_t> ep = {kExecModelFragment, 9, 0x6e69616du, 0x00000000u, 8};
104 for (const auto& [v, loc] : in_vars) ep.push_back(v);
105 append_inst_vec(w, kOpEntryPoint, ep);
106 append_inst(w, kOpExecutionMode, {9, 7}); // OriginUpperLeft
107
108 append_inst(w, kOpDecorate, {8, kDecorationLocation, 0});
109 for (const auto& [v, loc] : in_vars) append_inst(w, kOpDecorate, {v, kDecorationLocation, loc});
110
111 append_inst(w, 19, {1});
112 append_inst(w, 33, {2, 1});
113 append_inst(w, kOpTypeFloat, {3, 32});
114 append_inst(w, kOpTypeVector, {4, 3, 4});
115 append_inst(w, kOpTypePointer, {5, kStorageInput, 4});
116 append_inst(w, kOpTypePointer, {6, kStorageOutput, 4});
117 append_inst(w, kOpConstantNull, {4, 7});
118 append_inst(w, kOpVariable, {6, 8, kStorageOutput});
119 for (const auto& [v, loc] : in_vars) append_inst(w, kOpVariable, {5, v, kStorageInput});
120
121 append_inst(w, kOpFunction, {1, 9, 0, 2});
122 append_inst(w, 248, {10});
123 append_inst(w, kOpStore, {8, 7});
124 append_inst(w, kOpReturn, {});
125 append_inst(w, kOpFunctionEnd, {});
126 return w;
127}
128
129// Verify basic SPIR-V structural invariants: valid section ordering, all IDs < bound, unique Locations per storage.
130bool verify_spirv_structure(const std::vector<std::uint32_t>& words, std::uint32_t storage_class,
131 std::map<std::uint32_t, std::uint32_t>& out_loc_to_var, int& out_unpack_count,
132 int& out_private_vars, std::set<std::uint32_t>& out_ep_iface) {
133 Module mod;
134 if (!mod.parse(words)) return false;
135 out_loc_to_var.clear();
136 out_unpack_count = 0;
137 out_private_vars = 0;
138 out_ep_iface.clear();
139
140 // Check section order: pre-type -> types/globals -> functions, and every defined type appears before its use.
141 int section = 0; // 0 = pre-type, 1 = types/globals, 2 = functions
142 std::set<std::uint32_t> defined_types;
143 std::map<std::uint32_t, std::uint32_t> var_storage;
144 std::uint32_t glsl_id = 0;
145 for (const Inst& inst : mod.insts) {
146 if (inst.opcode == kOpExtInstImport && inst.words.size() >= 3 &&
147 decode_literal_string(std::span<const std::uint32_t>(inst.words).subspan(2)) == "GLSL.std.450") {
148 glsl_id = inst.words[1];
149 }
150 if (inst.opcode == kOpEntryPoint) {
151 const std::size_t s = entry_point_interface_start(inst);
152 for (std::size_t i = s; i < inst.words.size(); ++i) out_ep_iface.insert(inst.words[i]);
153 }
154 if (inst.opcode == kOpFunction) {
155 section = 2;
156 } else if (section == 0 && !is_pre_type_opcode(inst.opcode)) {
157 section = 1;
158 } else if (section == 1 && is_pre_type_opcode(inst.opcode)) {
159 return false; // annotation/header appeared after types started
160 }
161 if (section == 1) {
162 if (inst.opcode == 19 || inst.opcode == 33 || inst.opcode == kOpTypeInt || inst.opcode == kOpTypeFloat ||
163 inst.opcode == kOpTypeVector || inst.opcode == kOpTypePointer) {
164 defined_types.insert(inst.words[1]);
165 if (inst.words[1] >= mod.header[3]) return false;
166 }
167 if (inst.opcode == kOpVariable) {
168 if (!defined_types.count(inst.words[1])) return false; // pointer type must precede OpVariable
169 if (inst.words[2] >= mod.header[3]) return false;
170 var_storage[inst.words[2]] = inst.words[3];
171 if (inst.words[3] == kStoragePrivate) ++out_private_vars;
172 }
173 }
174 if (inst.opcode == kOpExtInst && inst.words.size() >= 6 && inst.words[3] == glsl_id &&
175 inst.words[4] == kGlslUnpackHalf2x16) {
176 ++out_unpack_count;
177 if (inst.words[2] >= mod.header[3]) return false;
178 }
179 }
180 for (const Inst& inst : mod.insts) {
181 if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) {
182 const auto it = var_storage.find(inst.words[1]);
183 if (it != var_storage.end() && it->second == storage_class) {
184 if (!out_loc_to_var.emplace(inst.words[3], inst.words[1]).second) return false; // duplicate Location
185 }
186 if (it != var_storage.end() && it->second == kStoragePrivate) return false; // Private cannot have Location
187 }
188 }
189 return true;
190}
191
192} // namespace
193
194int main() {
195 using namespace leonida;
196
197 // 1. Fast path: already matching static f16_halves -> both modules untouched.
198 {
199 ShaderEntry vs_e, ps_e;
200 vs_e.f16_halves = {{0, {28, 29}}, {1, {26, 27}}};
201 ps_e.f16_halves = {{0, {28, 29}}};
202 auto vs_w = build_vs(0x00010500u, 2, vs_e.f16_halves);
203 auto ps_w = build_ps(0x00010500u, {0, 1}, ps_e.f16_halves);
204 const auto vs_orig = vs_w, ps_orig = ps_w;
205 std::string err;
206 CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err));
207 CHECK(vs_w == vs_orig && ps_w == ps_orig);
208 }
209
210 // 2. Corpus pattern (SHADER-378): 16-param VS (param0..param15, static halves only for 0..6) paired with a PS
211 // reading raw attrs 0..14 and f16 attrs {0, 4, 5, 6, 7} packed at 20..29.
212 // Expected: params 1,2,3 demoted to Private (6 Private vars), params 0,4,5,6 relocated, param 7 synthesized
213 // with 4 UnpackHalf2x16 ops at Locations 20 & 21; PS unchanged.
214 {
215 ShaderEntry vs_e, ps_e;
216 for (std::uint32_t n = 0; n <= 6; ++n) vs_e.f16_halves[n] = {28 - 2 * n, 29 - 2 * n};
217 ps_e.f16_halves = {{0, {28, 29}}, {4, {26, 27}}, {5, {24, 25}}, {6, {22, 23}}, {7, {20, 21}}};
218 std::vector<std::uint32_t> ps_raw;
219 for (std::uint32_t a = 0; a < 15; ++a) ps_raw.push_back(a);
220
221 auto vs_w = build_vs(0x00010500u, 16, vs_e.f16_halves);
222 auto ps_w = build_ps(0x00010500u, ps_raw, ps_e.f16_halves);
223 const auto ps_orig = ps_w;
224 std::string err;
225 CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err));
226 CHECK(ps_w == ps_orig); // PS locations 20..29 do not collide with VS raw 0..15
227
228 std::map<std::uint32_t, std::uint32_t> vs_locs;
229 int unpacks = 0, privs = 0;
230 std::set<std::uint32_t> ep_iface;
231 CHECK(verify_spirv_structure(vs_w, kStorageOutput, vs_locs, unpacks, privs, ep_iface));
232 CHECK(privs == 6); // 3 unneeded static half pairs (params 1, 2, 3) demoted to Private
233 CHECK(unpacks == 4); // 1 missing param (param 7) * 4 vec4 channels
234 for (std::uint32_t loc = 0; loc < 16; ++loc) CHECK(vs_locs.count(loc) == 1);
235 for (std::uint32_t loc = 20; loc <= 29; ++loc) {
236 CHECK(vs_locs.count(loc) == 1);
237 CHECK(ep_iface.count(vs_locs[loc]) == 1);
238 }
239 CHECK(vs_locs.size() == 26); // 16 raw + 10 decoded halves; all <= 29
240 CHECK(vs_locs.rbegin()->first == 29);
241 }
242
243 // 3. PS relocation: VS exports raw param0..param15, PS only read raw attr0..13 so PS placed attr7 at [14, 15]
244 // (colliding with VS's raw param14/param15). Both VS and PS must relocate attr7 to [28, 29].
245 {
246 ShaderEntry vs_e, ps_e;
247 ps_e.f16_halves = {{7, {14, 15}}};
248 std::vector<std::uint32_t> ps_raw;
249 for (std::uint32_t a = 0; a < 14; ++a) ps_raw.push_back(a);
250
251 auto vs_w = build_vs(0x00010500u, 16, {});
252 auto ps_w = build_ps(0x00010500u, ps_raw, ps_e.f16_halves);
253 std::string err;
254 CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err));
255
256 std::map<std::uint32_t, std::uint32_t> vs_locs, ps_locs;
257 int vs_unpacks = 0, vs_privs = 0, ps_unpacks = 0, ps_privs = 0;
258 std::set<std::uint32_t> vs_ep, ps_ep;
259 CHECK(verify_spirv_structure(vs_w, kStorageOutput, vs_locs, vs_unpacks, vs_privs, vs_ep));
260 CHECK(verify_spirv_structure(ps_w, kStorageInput, ps_locs, ps_unpacks, ps_privs, ps_ep));
261 CHECK(vs_unpacks == 4);
262 CHECK(vs_locs.count(28) == 1 && vs_locs.count(29) == 1);
263 CHECK(ps_locs.count(28) == 1 && ps_locs.count(29) == 1);
264 CHECK(!ps_locs.count(14) && !ps_locs.count(15));
265 }
266
267 // 4. SPIR-V 1.3 OpEntryPoint drops demoted Private variables from interface list (SPIR-V 1.4+ keeps them).
268 {
269 ShaderEntry vs_e, ps_e;
270 vs_e.f16_halves = {{0, {28, 29}}, {1, {26, 27}}};
271 ps_e.f16_halves = {{0, {26, 27}}}; // force patching; param 1 is demoted
272 auto vs_13 = build_vs(0x00010300u, 2, vs_e.f16_halves);
273 auto ps_13 = build_ps(0x00010300u, {0, 1}, ps_e.f16_halves);
274 std::string err;
275 CHECK(link_f16_halves(vs_13, vs_e, ps_13, ps_e, &err));
276 std::map<std::uint32_t, std::uint32_t> locs;
277 int unpacks = 0, privs = 0;
278 std::set<std::uint32_t> ep_iface;
279 CHECK(verify_spirv_structure(vs_13, kStorageOutput, locs, unpacks, privs, ep_iface));
280 CHECK(privs == 2);
281 // Position (9) + 2 raw (10,11) + 2 reused halves (12,13) = 5 interface vars; demoted 14,15 dropped in v1.3.
282 CHECK(ep_iface.size() == 5);
283 }
284
285 // 5. Genuine budget overflow (>30 locations needed): returns false, leaves modules unchanged.
286 {
287 ShaderEntry vs_e, ps_e;
288 ps_e.f16_halves = {{0, {28, 29}}};
289 auto vs_w = build_vs(0x00010500u, 29, {}); // 29 raw outputs (0..28) -> only location 29 is free (< 2 needed)
290 auto ps_w = build_ps(0x00010500u, {0}, ps_e.f16_halves);
291 const auto vs_orig = vs_w, ps_orig = ps_w;
292 std::string err;
293 CHECK(!link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err));
294 CHECK(!err.empty());
295 CHECK(vs_w == vs_orig && ps_w == ps_orig);
296 }
297
298 std::printf("spirv_f16_halves_test: all checks passed\n");
299 return 0;
300}
diff --git a/runtime/test/startup_trace_test.cpp b/runtime/test/startup_trace_test.cpp
index 8df64680f..ca085a4cf 100644
--- a/runtime/test/startup_trace_test.cpp
+++ b/runtime/test/startup_trace_test.cpp
@@ -139,6 +139,14 @@ bool call_faulting(void* fn) {
139 return false; 139 return false;
140} 140}
141 141
142void raise_bad_dbg_print() {
143 __try {
144 ULONG_PTR args[2] = {5, 0x1000}; // invalid string pointer in DBG_PRINTEXCEPTION_C
145 RaiseException(0x40010006, 0, 2, args);
146 } __except (EXCEPTION_EXECUTE_HANDLER) {
147 }
148}
149
142std::string hex_rva(uint32_t rva) { 150std::string hex_rva(uint32_t rva) {
143 char b[16]; 151 char b[16];
144 std::snprintf(b, sizeof b, "+0x%x", rva); 152 std::snprintf(b, sizeof b, "+0x%x", rva);
@@ -211,6 +219,8 @@ void test_trace(const fs::path& dir) {
211 reinterpret_cast<VoidFn>(m.base + caller_rva(0))(nullptr); // second call: no second event 219 reinterpret_cast<VoidFn>(m.base + caller_rva(0))(nullptr); // second call: no second event
212 reinterpret_cast<VoidFn>(m.base + caller_rva(1))(kDebugText); 220 reinterpret_cast<VoidFn>(m.base + caller_rva(1))(kDebugText);
213 reinterpret_cast<VoidFn>(m.base + caller_rva(1))(kAnsiText); 221 reinterpret_cast<VoidFn>(m.base + caller_rva(1))(kAnsiText);
222 raise_bad_dbg_print();
223 OutputDebugStringA("after_bad_dbg_print");
214 check(call_faulting(m.base + kFaultRva), "the access violation reached the test's handler"); 224 check(call_faulting(m.base + kFaultRva), "the access violation reached the test's handler");
215 rt::startup_trace::event("exit", "\"code\":0"); 225 rt::startup_trace::event("exit", "\"code\":0");
216 } 226 }
@@ -240,6 +250,11 @@ void test_trace(const fs::path& dir) {
240 bool ansi_found = false; 250 bool ansi_found = false;
241 for (auto& l : lines) ansi_found |= l.find("\"kind\":\"debug_string\"") != std::string::npos && l.find(ansi) != std::string::npos; 251 for (auto& l : lines) ansi_found |= l.find("\"kind\":\"debug_string\"") != std::string::npos && l.find(ansi) != std::string::npos;
242 check(ansi_found, "an ANSI debug string with a byte above 0x7f is written as UTF-8"); 252 check(ansi_found, "an ANSI debug string with a byte above 0x7f is written as UTF-8");
253 bool after_bad_found = false;
254 for (auto& l : lines)
255 after_bad_found |=
256 l.find("\"kind\":\"debug_string\"") != std::string::npos && l.find("after_bad_dbg_print") != std::string::npos;
257 check(after_bad_found, "an SEH fault inside the VEH does not leave in_handler stuck true");
243 check(valid_utf8(trace), "the whole trace is valid UTF-8"); 258 check(valid_utf8(trace), "the whole trace is valid UTF-8");
244 259
245 const std::string* e = find_line(lines, "exception"); 260 const std::string* e = find_line(lines, "exception");
diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp
index 91f954cf3..6b72034e5 100644
--- a/runtime/test/vk_bindless_test.cpp
+++ b/runtime/test/vk_bindless_test.cpp
@@ -22,6 +22,7 @@
22#include "vulkan_loader.h" 22#include "vulkan_loader.h"
23#include "vk_device_pick.h" 23#include "vk_device_pick.h"
24#include "vk_shader_fma.h" 24#include "vk_shader_fma.h"
25#include "vk_pc_tail.h"
25#include "../src/vulkan_bindless.h" 26#include "../src/vulkan_bindless.h"
26 27
27#include <algorithm> 28#include <algorithm>
@@ -192,7 +193,10 @@ int main(int argc, char** argv) {
192 std::printf("device: %s%s\n", props.properties.deviceName, validation ? " (validation on)" : ""); 193 std::printf("device: %s%s\n", props.properties.deviceName, validation ? " (validation on)" : "");
193 // The pipeline layout pushes the 144-byte translated user-data block. A device with fewer push constant bytes 194 // The pipeline layout pushes the 144-byte translated user-data block. A device with fewer push constant bytes
194 // (128 on Intel Arc and some AMD drivers) can't create it: a device limit, not a wrong result (TEST-149). 195 // (128 on Intel Arc and some AMD drivers) can't create it: a device limit, not a wrong result (TEST-149).
195 constexpr std::uint32_t push_bytes = 144; 196 // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only, 128 bytes; the heap base, if a stage reads
197 // it, is in a uniform block at set 1 (vk_pc_tail.h).
198 const bool pc_tail = leonida::vk_test::pc_tail_requested();
199 const std::uint32_t push_bytes = pc_tail ? 128u : 144u;
196 if (props.properties.limits.maxPushConstantsSize < push_bytes) { 200 if (props.properties.limits.maxPushConstantsSize < push_bytes) {
197 std::printf("unsupported: need %u push constant bytes, device has %u\n", push_bytes, 201 std::printf("unsupported: need %u push constant bytes, device has %u\n", push_bytes,
198 props.properties.limits.maxPushConstantsSize); 202 props.properties.limits.maxPushConstantsSize);
@@ -201,7 +205,8 @@ int main(int argc, char** argv) {
201 205
202 // The features ps_tex's metadata names (bufferDeviceAddress, runtimeDescriptorArray, shaderInt64), dynamic 206 // The features ps_tex's metadata names (bufferDeviceAddress, runtimeDescriptorArray, shaderInt64), dynamic
203 // indexing of the image array, and whichever descriptor-indexing flags the set can use. 207 // indexing of the image array, and whichever descriptor-indexing flags the set can use.
204 VkPhysicalDeviceVulkan12Features have12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 208 VkPhysicalDeviceVulkan11Features have11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
209 VkPhysicalDeviceVulkan12Features have12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &have11};
205 VkPhysicalDeviceFeatures2 have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &have12}; 210 VkPhysicalDeviceFeatures2 have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &have12};
206 vkGetPhysicalDeviceFeatures2(pd, &have); 211 vkGetPhysicalDeviceFeatures2(pd, &have);
207 if (!have12.bufferDeviceAddress || !have12.runtimeDescriptorArray || !have.features.shaderInt64 || 212 if (!have12.bufferDeviceAddress || !have12.runtimeDescriptorArray || !have.features.shaderInt64 ||
@@ -215,7 +220,10 @@ int main(int argc, char** argv) {
215 have12.descriptorBindingStorageImageUpdateAfterBind && 220 have12.descriptorBindingStorageImageUpdateAfterBind &&
216 have12.descriptorBindingStorageBufferUpdateAfterBind; 221 have12.descriptorBindingStorageBufferUpdateAfterBind;
217 device_flags.partially_bound = have12.descriptorBindingPartiallyBound == VK_TRUE; 222 device_flags.partially_bound = have12.descriptorBindingPartiallyBound == VK_TRUE;
218 VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 223 // Translated vertex shaders read BaseVertex / BaseInstance (DrawParameters) for the zero-based v0 / v3.
224 VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
225 enable11.shaderDrawParameters = have11.shaderDrawParameters;
226 VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11};
219 enable12.bufferDeviceAddress = VK_TRUE; 227 enable12.bufferDeviceAddress = VK_TRUE;
220 enable12.runtimeDescriptorArray = VK_TRUE; 228 enable12.runtimeDescriptorArray = VK_TRUE;
221 enable12.descriptorIndexing = have12.descriptorIndexing; 229 enable12.descriptorIndexing = have12.descriptorIndexing;
@@ -419,17 +427,34 @@ int main(int argc, char** argv) {
419 CHECK(make_buffer(VkDeviceSize(W) * H * 16, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback, &readback_map)); 427 CHECK(make_buffer(VkDeviceSize(W) * H * 16, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback, &readback_map));
420 428
421 VkShaderModule vs, fs; 429 VkShaderModule vs, fs;
430 bool tail_block = false;
422 for (int stage = 0; stage < 2; ++stage) { 431 for (int stage = 0; stage < 2; ++stage) {
423 const auto code = read_spv(argv[1 + stage]); 432 const auto code = read_spv(argv[1 + stage]);
424 if (code.empty()) { 433 if (code.empty()) {
425 std::fprintf(stderr, "cannot read %s\n", argv[1 + stage]); 434 std::fprintf(stderr, "cannot read %s\n", argv[1 + stage]);
426 return 1; 435 return 1;
427 } 436 }
437 if (pc_tail && leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set))
438 tail_block = true;
428 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 439 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
429 smi.codeSize = code.size() * 4; 440 smi.codeSize = code.size() * 4;
430 smi.pCode = code.data(); 441 smi.pCode = code.data();
431 CHECK(vkCreateShaderModule(dev, &smi, nullptr, stage ? &fs : &vs)); 442 CHECK(vkCreateShaderModule(dev, &smi, nullptr, stage ? &fs : &vs));
432 } 443 }
444 // One tail block for every variant below: each draw's tail is the same heap base.
445 leonida::vk_test::PcTail tail;
446 if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, props.properties.limits.minUniformBufferOffsetAlignment,
447 VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 1)) {
448 std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n");
449 return 1;
450 }
451 auto bind_tail = [&](VkCommandBuffer cb, VkPipelineLayout layout, const std::uint32_t* block) {
452 if (!tail_block) return;
453 tail.write(0, block, 4);
454 const std::uint32_t offset = tail.offset(0);
455 vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, leonida::vk_test::pc_tail_set, 1, &tail.set,
456 1, &offset);
457 };
433 VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; 458 VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};
434 cpi.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; 459 cpi.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
435 cpi.queueFamilyIndex = qi; 460 cpi.queueFamilyIndex = qi;
@@ -566,6 +591,8 @@ int main(int argc, char** argv) {
566 pli.pSetLayouts = &set_layout; 591 pli.pSetLayouts = &set_layout;
567 pli.pushConstantRangeCount = 1; 592 pli.pushConstantRangeCount = 1;
568 pli.pPushConstantRanges = &push; 593 pli.pPushConstantRanges = &push;
594 const VkDescriptorSetLayout set_layouts[] = {set_layout, tail.set_layout};
595 if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = set_layouts; }
569 VkPipelineLayout pipeline_layout; 596 VkPipelineLayout pipeline_layout;
570 CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pipeline_layout)); 597 CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pipeline_layout));
571 VkPipelineShaderStageCreateInfo stages[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, 598 VkPipelineShaderStageCreateInfo stages[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO},
@@ -632,7 +659,8 @@ int main(int argc, char** argv) {
632 block[2] = table_va; // s2:s3 = console VA of the descriptor table 659 block[2] = table_va; // s2:s3 = console VA of the descriptor table
633 block[32] = std::uint32_t(heap_base); 660 block[32] = std::uint32_t(heap_base);
634 block[33] = std::uint32_t(heap_base >> 32); 661 block[33] = std::uint32_t(heap_base >> 32);
635 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(block), block); 662 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes, block);
663 bind_tail(cmd, pipeline_layout, block);
636 vkCmdDraw(cmd, 3, 1, 0, 0); 664 vkCmdDraw(cmd, 3, 1, 0, 0);
637 vkCmdEndRenderPass(cmd); 665 vkCmdEndRenderPass(cmd);
638 VkBufferImageCopy rc{}; 666 VkBufferImageCopy rc{};
@@ -780,7 +808,8 @@ int main(int argc, char** argv) {
780 block[32] = std::uint32_t(heap_base); 808 block[32] = std::uint32_t(heap_base);
781 block[33] = std::uint32_t(heap_base >> 32); 809 block[33] = std::uint32_t(heap_base >> 32);
782 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, 810 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0,
783 sizeof(block), block); 811 push_bytes, block);
812 bind_tail(cmd, pipeline_layout, block);
784 vkCmdDraw(cmd, 3, 1, 0, 0); 813 vkCmdDraw(cmd, 3, 1, 0, 0);
785 vkCmdEndRenderPass(cmd); 814 vkCmdEndRenderPass(cmd);
786 VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; 815 VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp
index bcc6683ef..f0f7c4605 100644
--- a/runtime/test/vk_compute_test.cpp
+++ b/runtime/test/vk_compute_test.cpp
@@ -11,10 +11,12 @@
11// VKC_SGPRS=w4,w5,... (env): set s4, s5, ... (decimal or 0x hex, up to s31), the user SGPRs after the output V#, 11// VKC_SGPRS=w4,w5,... (env): set s4, s5, ... (decimal or 0x hex, up to s31), the user SGPRs after the output V#,
12// so a test can take input words (cs_user_sgprs.asm). They are zero otherwise. Same syntax as vk_harness's VKH_SGPRS. 12// so a test can take input words (cs_user_sgprs.asm). They are zero otherwise. Same syntax as vk_harness's VKH_SGPRS.
13// Contract (docs/design.md): push constants = s0..s31 (128 bytes), heap base lo/hi, code base lo/hi (144 bytes). 13// Contract (docs/design.md): push constants = s0..s31 (128 bytes), heap base lo/hi, code base lo/hi (144 bytes).
14// LEONIDA_PC_TAIL_UBO=1 (modules from rdna2spirv.py --pc-tail-ubo): s0..s31 only, the rest at set 1 (vk_pc_tail.h).
14// The output buffer is the "heap": Xbox VA 0 maps to its device address, and s[0:3] hold a V# with base 0. 15// The output buffer is the "heap": Xbox VA 0 maps to its device address, and s[0:3] hold a V# with base 0.
15#include "vulkan_loader.h" 16#include "vulkan_loader.h"
16#include "vk_device_pick.h" 17#include "vk_device_pick.h"
17#include "vk_shader_fma.h" 18#include "vk_shader_fma.h"
19#include "vk_pc_tail.h"
18 20
19#include <cctype> 21#include <cctype>
20#include <cmath> 22#include <cmath>
@@ -151,6 +153,13 @@ int main(int argc, char** argv) {
151 std::fprintf(stderr, "full 64-wide compute subgroups unavailable\n"); 153 std::fprintf(stderr, "full 64-wide compute subgroups unavailable\n");
152 return 77; 154 return 77;
153 } 155 }
156 std::ifstream f(argv[1], std::ios::binary);
157 std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
158 const bool needs_float64 = leonida::vk_test::spirv_declares_capability(code.data(), code.size(), 10); // Float64
159 if (needs_float64 && !f2q.features.shaderFloat64) {
160 std::fprintf(stderr, "unsupported: %s uses Float64 and the device has no shaderFloat64\n", argv[1]);
161 return 77;
162 }
154 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 163 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
155 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 164 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
156 f12.bufferDeviceAddress = VK_TRUE; 165 f12.bufferDeviceAddress = VK_TRUE;
@@ -161,6 +170,7 @@ int main(int argc, char** argv) {
161 } 170 }
162 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; 171 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
163 f2.features.shaderInt64 = VK_TRUE; 172 f2.features.shaderInt64 = VK_TRUE;
173 f2.features.shaderFloat64 = needs_float64;
164 f2.pNext = &f12; 174 f2.pNext = &f12;
165 // OpFmaKHR (rdna2spirv.py --fma khr): VK_KHR_shader_fma, when the device has it. 175 // OpFmaKHR (rdna2spirv.py --fma khr): VK_KHR_shader_fma, when the device has it.
166 leonida::vk_test::ShaderFma fma; 176 leonida::vk_test::ShaderFma fma;
@@ -178,7 +188,7 @@ int main(int argc, char** argv) {
178 LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); LOADD(vkCreateCommandPool); 188 LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); LOADD(vkCreateCommandPool);
179 LOADD(vkAllocateCommandBuffers); LOADD(vkBeginCommandBuffer); LOADD(vkCmdBindPipeline); 189 LOADD(vkAllocateCommandBuffers); LOADD(vkBeginCommandBuffer); LOADD(vkCmdBindPipeline);
180 LOADD(vkCmdPushConstants); LOADD(vkCmdDispatch); LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit); 190 LOADD(vkCmdPushConstants); LOADD(vkCmdDispatch); LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit);
181 LOADD(vkQueueWaitIdle); LOADD(vkCmdPipelineBarrier); LOADD(vkCmdDispatchBase); 191 LOADD(vkQueueWaitIdle); LOADD(vkCmdPipelineBarrier); LOADD(vkCmdDispatchBase); LOADD(vkCmdBindDescriptorSets);
182 VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); 192 VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q);
183 193
184 // Output buffer = heap. Host-visible so the result can be read back directly. 194 // Output buffer = heap. Host-visible so the result can be read back directly.
@@ -227,15 +237,28 @@ int main(int argc, char** argv) {
227 bai.buffer = buf; 237 bai.buffer = buf;
228 const uint64_t heap = vkGetBufferDeviceAddress(dev, &bai); 238 const uint64_t heap = vkGetBufferDeviceAddress(dev, &bai);
229 239
230 std::ifstream f(argv[1], std::ios::binary);
231 std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
232 if (!fma.accepts(code.data(), code.size(), argv[1])) return 77; 240 if (!fma.accepts(code.data(), code.size(), argv[1])) return 77;
233 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 241 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
234 smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data()); 242 smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data());
235 VkShaderModule sm; CHECK(vkCreateShaderModule(dev, &smi, nullptr, &sm)); 243 VkShaderModule sm; CHECK(vkCreateShaderModule(dev, &smi, nullptr, &sm));
236 VkPushConstantRange pcr{VK_SHADER_STAGE_COMPUTE_BIT, 0, 144}; 244 // 144 push-constant bytes: s0..s31, heap base, code base. With LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py
245 // --pc-tail-ubo) only s0..s31; the tail, if the module reads it, is a uniform block at set 1 (vk_pc_tail.h), one
246 // slot for the dispatch and one per workgroup_yz origin.
247 const bool pc_tail = leonida::vk_test::pc_tail_requested();
248 const uint32_t pc_bytes = pc_tail ? 128u : 144u;
249 leonida::vk_test::PcTail tail;
250 const bool tail_block = pc_tail &&
251 leonida::vk_test::spirv_declares_set(code.data(), code.size(), leonida::vk_test::pc_tail_set);
252 if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, props.limits.minUniformBufferOffsetAlignment,
253 VK_SHADER_STAGE_COMPUTE_BIT, 1 + origins)) {
254 std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n");
255 return 1;
256 }
257 VkPushConstantRange pcr{VK_SHADER_STAGE_COMPUTE_BIT, 0, pc_bytes};
237 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 258 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
238 pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; 259 pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
260 const VkDescriptorSetLayout tail_layouts[] = {tail.empty_layout, tail.set_layout};
261 if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = tail_layouts; }
239 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); 262 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl));
240 VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; 263 VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
241 if (workgroup_yz) cpi.flags |= VK_PIPELINE_CREATE_DISPATCH_BASE_BIT; 264 if (workgroup_yz) cpi.flags |= VK_PIPELINE_CREATE_DISPATCH_BASE_BIT;
@@ -270,14 +293,27 @@ int main(int argc, char** argv) {
270 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; 293 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
271 CHECK(vkBeginCommandBuffer(cmd, &cbi)); 294 CHECK(vkBeginCommandBuffer(cmd, &cbi));
272 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); 295 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe);
273 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, 144, pc); 296 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, pc_bytes, pc);
297 auto bind_tail = [&](uint32_t slot) {
298 if (!tail_block) return;
299 tail.write(slot, pc, 4);
300 const uint32_t offset = tail.offset(slot);
301 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, leonida::vk_test::pc_tail_set, 1, &tail.set,
302 1, &offset);
303 };
304 bind_tail(0);
274 vkCmdDispatch(cmd, groups, groups_y, groups_z); 305 vkCmdDispatch(cmd, groups, groups_y, groups_z);
275 // A permutation within one axis can leave the full-grid histogram unchanged. Dispatch one group at 306 // A permutation within one axis can leave the full-grid histogram unchanged. Dispatch one group at
276 // each known origin into its own histogram, selected by the host independently of the shader's SGPRs. 307 // each known origin into its own histogram, selected by the host independently of the shader's SGPRs.
277 for (uint32_t g = 0; g < origins; ++g) { 308 for (uint32_t g = 0; g < origins; ++g) {
278 const uint64_t base = heap + (g + 1) * yz_bins * sizeof(uint32_t); 309 const uint64_t base = heap + (g + 1) * yz_bins * sizeof(uint32_t);
279 const uint32_t address[] = {uint32_t(base), uint32_t(base >> 32)}; 310 const uint32_t address[] = {uint32_t(base), uint32_t(base >> 32)};
280 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 32 * sizeof(uint32_t), sizeof(address), address); 311 if (pc_tail) {
312 pc[32] = address[0]; pc[33] = address[1]; // the heap base is the tail's dwords 0..1
313 bind_tail(g + 1);
314 } else {
315 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 32 * sizeof(uint32_t), sizeof(address), address);
316 }
281 vkCmdDispatchBase(cmd, g % groups, (g / groups) % groups_y, g / (groups * groups_y), 1, 1, 1); 317 vkCmdDispatchBase(cmd, g % groups, (g / groups) % groups_y, g / (groups * groups_y), 1, 1, 1);
282 } 318 }
283 VkMemoryBarrier readback{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; 319 VkMemoryBarrier readback{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp
index fe9ae194a..abaacb348 100644
--- a/runtime/test/vk_harness.cpp
+++ b/runtime/test/vk_harness.cpp
@@ -23,6 +23,7 @@
23#include "vulkan_loader.h" 23#include "vulkan_loader.h"
24#include "vk_device_pick.h" 24#include "vk_device_pick.h"
25#include "vk_shader_fma.h" 25#include "vk_shader_fma.h"
26#include "vk_pc_tail.h"
26 27
27#include <cctype> 28#include <cctype>
28#include <cstddef> 29#include <cstddef>
@@ -296,7 +297,16 @@ int main(int argc, char** argv) {
296 // fewer bytes (128, the Vulkan minimum, as on some Intel Arc drivers and AMD's Windows driver for RDNA2 iGPUs) 297 // fewer bytes (128, the Vulkan minimum, as on some Intel Arc drivers and AMD's Windows driver for RDNA2 iGPUs)
297 // cannot take that range: declaring it anyway is invalid, and there a shader reading past the limit crashed or 298 // cannot take that range: declaring it anyway is invalid, and there a shader reading past the limit crashed or
298 // hung the device. 77, as vk_texture_test and vk_bindless_test: a device limit, not a wrong result (D3D-14). 299 // hung the device. 77, as vk_texture_test and vk_bindless_test: a device limit, not a wrong result (D3D-14).
299 const uint32_t pc_bytes = mesh_compute ? 152u : 144u; 300 // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only, 128 bytes, which every device has; the
301 // tail is a uniform block at set 1 (vk_pc_tail.h). tools/mesh_compute_vs.py's vertex shader still reads the
302 // --mesh-compute output address from push constants, so that combination isn't run.
303 const bool pc_tail = leonida::vk_test::pc_tail_requested();
304 if (pc_tail && mesh_compute) {
305 std::fprintf(stderr, "unsupported: --mesh-compute's vertex shader reads the output address from push "
306 "constants, not from the --pc-tail-ubo block\n");
307 return 77;
308 }
309 const uint32_t pc_bytes = pc_tail ? 128u : mesh_compute ? 152u : 144u;
300 if (props.limits.maxPushConstantsSize < pc_bytes) { 310 if (props.limits.maxPushConstantsSize < pc_bytes) {
301 std::fprintf(stderr, "unsupported: need %u push constant bytes, device has %u\n", pc_bytes, 311 std::fprintf(stderr, "unsupported: need %u push constant bytes, device has %u\n", pc_bytes,
302 props.limits.maxPushConstantsSize); 312 props.limits.maxPushConstantsSize);
@@ -326,12 +336,22 @@ int main(int argc, char** argv) {
326 m8.maintenance8 = VK_TRUE; m8.pNext = chain; chain = &m8; 336 m8.maintenance8 = VK_TRUE; m8.pNext = chain; chain = &m8;
327 } 337 }
328#endif 338#endif
339 VkPhysicalDeviceVulkan11Features f11q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
329 VkPhysicalDeviceVulkan12Features f12q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 340 VkPhysicalDeviceVulkan12Features f12q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
341 f12q.pNext = &f11q;
330 VkPhysicalDeviceVulkan13Features f13q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 342 VkPhysicalDeviceVulkan13Features f13q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
331 f13q.pNext = &f12q; 343 f13q.pNext = &f12q;
332 VkPhysicalDeviceFeatures2 f2q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; 344 VkPhysicalDeviceFeatures2 f2q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
333 f2q.pNext = &f13q; 345 f2q.pNext = &f13q;
334 vkGetPhysicalDeviceFeatures2(pd, &f2q); 346 vkGetPhysicalDeviceFeatures2(pd, &f2q);
347 // Translated vertex shaders read BaseVertex / BaseInstance (DrawParameters) to give v0 / v3 the hardware's
348 // zero-based ids.
349 VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
350 if (f11q.shaderDrawParameters) {
351 f11.shaderDrawParameters = VK_TRUE;
352 f11.pNext = chain;
353 chain = &f11;
354 }
335 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 355 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
336 if (f13q.subgroupSizeControl) { 356 if (f13q.subgroupSizeControl) {
337 f13.subgroupSizeControl = VK_TRUE; 357 f13.subgroupSizeControl = VK_TRUE;
@@ -390,6 +410,7 @@ int main(int argc, char** argv) {
390 LOADD(vkCreateCommandPool); LOADD(vkAllocateCommandBuffers); LOADD(vkBeginCommandBuffer); 410 LOADD(vkCreateCommandPool); LOADD(vkAllocateCommandBuffers); LOADD(vkBeginCommandBuffer);
391 LOADD(vkCmdBeginRenderPass); LOADD(vkCmdBindPipeline); LOADD(vkCmdDraw); LOADD(vkCmdEndRenderPass); 411 LOADD(vkCmdBeginRenderPass); LOADD(vkCmdBindPipeline); LOADD(vkCmdDraw); LOADD(vkCmdEndRenderPass);
392 LOADD(vkCmdBindVertexBuffers); LOADD(vkCmdBindIndexBuffer); LOADD(vkCmdDrawIndexed); 412 LOADD(vkCmdBindVertexBuffers); LOADD(vkCmdBindIndexBuffer); LOADD(vkCmdDrawIndexed);
413 LOADD(vkCmdPipelineBarrier);
393 LOADD(vkCmdCopyImageToBuffer); LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit); LOADD(vkQueueWaitIdle); 414 LOADD(vkCmdCopyImageToBuffer); LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit); LOADD(vkQueueWaitIdle);
394 LOADD(vkCreateBuffer); LOADD(vkGetBufferMemoryRequirements); LOADD(vkBindBufferMemory); LOADD(vkMapMemory); 415 LOADD(vkCreateBuffer); LOADD(vkGetBufferMemoryRequirements); LOADD(vkBindBufferMemory); LOADD(vkMapMemory);
395 VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); 416 VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q);
@@ -462,8 +483,11 @@ int main(int argc, char** argv) {
462 VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; 483 VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
463 fbi.renderPass = rp; fbi.attachmentCount = rpi.attachmentCount; fbi.pAttachments = views; fbi.width = W; fbi.height = H; fbi.layers = 1; 484 fbi.renderPass = rp; fbi.attachmentCount = rpi.attachmentCount; fbi.pAttachments = views; fbi.width = W; fbi.height = H; fbi.layers = 1;
464 VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb)); 485 VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb));
486 bool tail_block = false; // some stage reads the --pc-tail-ubo block (declares set 1)
465 auto module = [&](const char* p, VkShaderModule* m) { 487 auto module = [&](const char* p, VkShaderModule* m) {
466 auto code = read_spv(p); 488 auto code = read_spv(p);
489 if (pc_tail && leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set))
490 tail_block = true;
467 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 491 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
468 smi.codeSize = code.size() * 4; smi.pCode = code.data(); 492 smi.codeSize = code.size() * 4; smi.pCode = code.data();
469 return vkCreateShaderModule(dev, &smi, nullptr, m); 493 return vkCreateShaderModule(dev, &smi, nullptr, m);
@@ -537,6 +561,14 @@ int main(int argc, char** argv) {
537 VkPushConstantRange pcr{pcs, 0, pc_bytes}; 561 VkPushConstantRange pcr{pcs, 0, pc_bytes};
538 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 562 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
539 pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; 563 pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
564 // --pc-tail-ubo: the tail block at set 1 (set 0 stays empty here), one slot for the one draw.
565 leonida::vk_test::PcTail tail;
566 if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, props.limits.minUniformBufferOffsetAlignment, pcs, 1)) {
567 std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n");
568 return 1;
569 }
570 const VkDescriptorSetLayout tail_layouts[] = {tail.empty_layout, tail.set_layout};
571 if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = tail_layouts; }
540 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); 572 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl));
541 VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; 573 VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
542 gpi.stageCount = nstages; gpi.pStages = stages; 574 gpi.stageCount = nstages; gpi.pStages = stages;
@@ -674,7 +706,7 @@ int main(int argc, char** argv) {
674 auto push = reinterpret_cast<PFN_vkCmdPushConstants>(vkGetDeviceProcAddr(dev, "vkCmdPushConstants")); 706 auto push = reinterpret_cast<PFN_vkCmdPushConstants>(vkGetDeviceProcAddr(dev, "vkCmdPushConstants"));
675 if (mesh_compute) { 707 if (mesh_compute) {
676 // The mesh shader as compute, then make its stores visible to the vertex shader's reads. 708 // The mesh shader as compute, then make its stores visible to the vertex shader's reads.
677 LOADD(vkCmdDispatch); LOADD(vkCmdPipelineBarrier); 709 LOADD(vkCmdDispatch);
678 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, cpipe); 710 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, cpipe);
679 push(cmd, pl, pcs, 0, pc_bytes, pc); 711 push(cmd, pl, pcs, 0, pc_bytes, pc);
680 vkCmdDispatch(cmd, groups[0], groups[1], groups[2]); 712 vkCmdDispatch(cmd, groups[0], groups[1], groups[2]);
@@ -698,6 +730,13 @@ int main(int argc, char** argv) {
698 } 730 }
699 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); 731 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);
700 push(cmd, pl, pcs, 0, pc_bytes, pc); 732 push(cmd, pl, pcs, 0, pc_bytes, pc);
733 if (tail_block) {
734 LOADD(vkCmdBindDescriptorSets);
735 tail.write(0, pc, 4); // heap base (VKH_HEAP) and code base, as pc[32..35] are without the flag
736 const uint32_t offset = tail.offset(0);
737 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, leonida::vk_test::pc_tail_set, 1, &tail.set,
738 1, &offset);
739 }
701 // VKH_VERTICES=<n>: draw n vertices instead of one triangle, so a vertex shader fills whole waves (TEST-251). 740 // VKH_VERTICES=<n>: draw n vertices instead of one triangle, so a vertex shader fills whole waves (TEST-251).
702 const char* vertices_env = std::getenv("VKH_VERTICES"); 741 const char* vertices_env = std::getenv("VKH_VERTICES");
703 if (draw_mesh_path) { 742 if (draw_mesh_path) {
@@ -712,11 +751,21 @@ int main(int argc, char** argv) {
712 vkCmdDraw(cmd, uint32_t(mesh_groups * mesh_prims * 3), 1, 0, 0); 751 vkCmdDraw(cmd, uint32_t(mesh_groups * mesh_prims * 3), 1, 0, 0);
713 else if (mesh) 752 else if (mesh)
714 reinterpret_cast<PFN_vkCmdDrawMeshTasksEXT>(vkGetDeviceProcAddr(dev, "vkCmdDrawMeshTasksEXT"))(cmd, groups[0], groups[1], groups[2]); 753 reinterpret_cast<PFN_vkCmdDrawMeshTasksEXT>(vkGetDeviceProcAddr(dev, "vkCmdDrawMeshTasksEXT"))(cmd, groups[0], groups[1], groups[2]);
715 else 754 else {
716 vkCmdDraw(cmd, 3, 1, 0, 0); 755 // VKH_DRAW=<firstVertex>,<firstInstance>: draw the triangle with non-zero bases (vs_base_ids).
756 unsigned first_vertex = 0, first_instance = 0;
757 if (const char* d = std::getenv("VKH_DRAW")) std::sscanf(d, "%u,%u", &first_vertex, &first_instance);
758 vkCmdDraw(cmd, 3, 1, first_vertex, first_instance);
759 }
717 vkCmdEndRenderPass(cmd); 760 vkCmdEndRenderPass(cmd);
718 VkBufferImageCopy reg{}; reg.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; reg.imageExtent = {W, H, 1}; 761 VkBufferImageCopy reg{}; reg.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; reg.imageExtent = {W, H, 1};
719 vkCmdCopyImageToBuffer(cmd, img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buf, 1, &reg); 762 vkCmdCopyImageToBuffer(cmd, img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buf, 1, &reg);
763 // Make the image copy and any shader writes to the heap visible to the host after the queue wait.
764 VkMemoryBarrier readback{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
765 readback.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT;
766 readback.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
767 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0,
768 1, &readback, 0, nullptr, 0, nullptr);
720 CHECK(vkEndCommandBuffer(cmd)); 769 CHECK(vkEndCommandBuffer(cmd));
721 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; 770 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd;
722 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); 771 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE));
diff --git a/runtime/test/vk_image_fuzz.cpp b/runtime/test/vk_image_fuzz.cpp
index b38188b22..52b59d6e0 100644
--- a/runtime/test/vk_image_fuzz.cpp
+++ b/runtime/test/vk_image_fuzz.cpp
@@ -9,6 +9,7 @@
9#include "../src/vulkan_device_filter.h" 9#include "../src/vulkan_device_filter.h"
10#include "../src/vulkan_bindless.h" 10#include "../src/vulkan_bindless.h"
11 11
12#include <cctype>
12#include <cstdint> 13#include <cstdint>
13#include <cstdio> 14#include <cstdio>
14#include <cstdlib> 15#include <cstdlib>
@@ -51,6 +52,14 @@ std::string trim(const std::string& s) {
51 std::size_t b = s.find_first_not_of(" \t\r\n"), e = s.find_last_not_of(" \t\r\n"); 52 std::size_t b = s.find_first_not_of(" \t\r\n"), e = s.find_last_not_of(" \t\r\n");
52 return b == std::string::npos ? "" : s.substr(b, e - b + 1); 53 return b == std::string::npos ? "" : s.substr(b, e - b + 1);
53} 54}
55// LEONIDA_PC_TAIL_UBO=1: shaders were translated with --pc-tail-ubo (128-byte push constants for s0..s31; the
56// image_load fuzz shaders read neither heap base nor code base, so they declare no set-1 block).
57bool pc_tail_requested() {
58 const char* v = std::getenv("LEONIDA_PC_TAIL_UBO");
59 std::string s = trim(v ? v : "");
60 for (char& c : s) c = char(std::tolower(static_cast<unsigned char>(c)));
61 return s == "1" || s == "true" || s == "yes" || s == "on";
62}
54// Decimal or 0x-prefixed hex, whole string, no exceptions (strtoul with base 0 handles both). 63// Decimal or 0x-prefixed hex, whole string, no exceptions (strtoul with base 0 handles both).
55bool parse_u32(const std::string& text, std::uint32_t& out) { 64bool parse_u32(const std::string& text, std::uint32_t& out) {
56 if (text.empty() || text.find_first_of(" \t\r\n") != std::string::npos) return false; 65 if (text.empty() || text.find_first_of(" \t\r\n") != std::string::npos) return false;
@@ -223,9 +232,11 @@ int main(int argc, char** argv) {
223 std::printf("unsupported: %s lacks the required image feature\n", spec.format_name.c_str()); 232 std::printf("unsupported: %s lacks the required image feature\n", spec.format_name.c_str());
224 return unsupported; 233 return unsupported;
225 } 234 }
226 // The pipeline layout pushes the 144-byte translated user-data block. A device with fewer push constant bytes 235 // The pipeline layout pushes the translated user-data block (144 bytes by default, or 128 bytes under
227 // (128 on Intel Arc and some AMD drivers) can't create it: a device limit, not a wrong result (TEST-149). 236 // LEONIDA_PC_TAIL_UBO=1 for rdna2spirv.py --pc-tail-ubo). A device with fewer push constant bytes (128 on
228 constexpr std::uint32_t push_bytes = 144; 237 // Intel Arc and AMD's Windows driver for RDNA2 iGPUs) can't take 144: a device limit, not a wrong result (TEST-149).
238 const bool pc_tail = pc_tail_requested();
239 const std::uint32_t push_bytes = pc_tail ? 128u : 144u;
229 if (props.properties.limits.maxPushConstantsSize < push_bytes) { 240 if (props.properties.limits.maxPushConstantsSize < push_bytes) {
230 std::printf("unsupported: need %u push constant bytes, device has %u\n", push_bytes, 241 std::printf("unsupported: need %u push constant bytes, device has %u\n", push_bytes,
231 props.properties.limits.maxPushConstantsSize); 242 props.properties.limits.maxPushConstantsSize);
@@ -561,7 +572,7 @@ int main(int argc, char** argv) {
561 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &bound, 0, nullptr); 572 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &bound, 0, nullptr);
562 std::uint32_t block[36] = {}; 573 std::uint32_t block[36] = {};
563 std::memcpy(block + 8, spec.tsharp, sizeof(spec.tsharp)); // s[8:15]: the T# the fragment shader loads 574 std::memcpy(block + 8, spec.tsharp, sizeof(spec.tsharp)); // s[8:15]: the T# the fragment shader loads
564 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(block), block); 575 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes, block);
565 vkCmdDraw(cmd, 3, 1, 0, 0); 576 vkCmdDraw(cmd, 3, 1, 0, 0);
566 vkCmdEndRenderPass(cmd); 577 vkCmdEndRenderPass(cmd);
567 VkBufferImageCopy rc{.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .imageExtent = {W, H, 1}}; 578 VkBufferImageCopy rc{.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .imageExtent = {W, H, 1}};
diff --git a/runtime/test/vk_overlapping_occlusion_test.cpp b/runtime/test/vk_overlapping_occlusion_test.cpp
index 2a510d33a..43ffd5002 100644
--- a/runtime/test/vk_overlapping_occlusion_test.cpp
+++ b/runtime/test/vk_overlapping_occlusion_test.cpp
@@ -16,8 +16,8 @@ namespace {
16 16
17using namespace leonida; 17using namespace leonida;
18constexpr std::uint32_t side = 8; 18constexpr std::uint32_t side = 8;
19constexpr std::uint32_t query_count = 4; 19constexpr std::uint32_t query_count = 10;
20constexpr std::uint32_t statistics_count = 4; 20constexpr std::uint32_t statistics_count = 9;
21constexpr std::uint32_t statistics_words = 11; // D3D12_QUERY_DATA_PIPELINE_STATISTICS 21constexpr std::uint32_t statistics_words = 11; // D3D12_QUERY_DATA_PIPELINE_STATISTICS
22 22
23VkShaderModule load_shader(vktest::Device& d, const char* path) { 23VkShaderModule load_shader(vktest::Device& d, const char* path) {
@@ -190,6 +190,10 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
190 // The statistics lists below: a split query (two segments), two unsplit references and a second split query. 190 // The statistics lists below: a split query (two segments), two unsplit references and a second split query.
191 if (d.pipeline_statistics_query) schedule.extents.insert(schedule.extents.end(), {3, 5, 3, 5, 3, 5}); 191 if (d.pipeline_statistics_query) schedule.extents.insert(schedule.extents.end(), {3, 5, 3, 5, 3, 5});
192 schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0, 1}); 192 schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0, 1});
193 // The D3D-252 lists: three crossing statistics segment ends, three statistics references with the same draws,
194 // then the kind overlap's three segment ends and three occlusion references carrying the same draws.
195 if (d.pipeline_statistics_query) schedule.extents.insert(schedule.extents.end(), {7, 9, 11, 7, 9, 11});
196 schedule.extents.insert(schedule.extents.end(), {19, 21, 23, 19, 21, 23});
193 schedule.every = bisect.enabled; 197 schedule.every = bisect.enabled;
194 schedule.no_draw = bisect.no_draw; 198 schedule.no_draw = bisect.no_draw;
195 draws = &schedule; 199 draws = &schedule;
@@ -216,7 +220,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
216 std::vector<bool>(query_count, false)}); 220 std::vector<bool>(query_count, false)});
217 221
218 constexpr ResourceId dst_id = 4, predicate_id = 5; 222 constexpr ResourceId dst_id = 4, predicate_id = 5;
219 constexpr VkDeviceSize binding_offset = 24, size = 160; 223 constexpr VkDeviceSize binding_offset = 24, size = 256;
220 void* mapping = nullptr; 224 void* mapping = nullptr;
221 ResourceBinding dst{}; 225 ResourceBinding dst{};
222 dst.buffer = d.buffer(size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapping); 226 dst.buffer = d.buffer(size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapping);
@@ -388,7 +392,7 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
388 // gets one native draw before it ends (extents 3 and 5); two unsplit queries with the same draws are the 392 // gets one native draw before it ends (extents 3 and 5); two unsplit queries with the same draws are the
389 // reference, and CSInvocations stays 0 because no application compute runs. 393 // reference, and CSInvocations stays 0 because no application compute runs.
390 constexpr ResourceId stats_dst_id = 6; 394 constexpr ResourceId stats_dst_id = 6;
391 constexpr VkDeviceSize stats_result = statistics_words * sizeof(std::uint64_t), stats_slots = 5; 395 constexpr VkDeviceSize stats_result = statistics_words * sizeof(std::uint64_t), stats_slots = 10;
392 void* stats_mapping = nullptr; 396 void* stats_mapping = nullptr;
393 ResourceBinding stats_dst{}; 397 ResourceBinding stats_dst{};
394 if (fixture.statistics) { 398 if (fixture.statistics) {
@@ -446,6 +450,43 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
446 EXPECT(single.close()); 450 EXPECT(single.close());
447 const CommandList* fifth[] = {&single}; 451 const CommandList* fifth[] = {&single};
448 EXPECT(queue.execute(fifth) == ReplayResult::success); 452 EXPECT(queue.execute(fifth) == ReplayResult::success);
453 // D3D-252: overlapping pipeline-statistics queries and overlapping occlusion kinds. The hook's draw lands in
454 // the segment that is about to close, so each crossing query's sum covers its own intervals plus the shared
455 // intersection; the reference queries carry the same draws unsplit, and the sums must match them.
456 CommandList crossing_stats, stats_references, kind_overlap, kind_references;
457 if (d.pipeline_statistics_query) {
458 EXPECT(crossing_stats.begin_query({stats, d3d12_query::pipeline_statistics, 4}));
459 EXPECT(crossing_stats.begin_query({stats, d3d12_query::pipeline_statistics, 5}));
460 EXPECT(crossing_stats.end_query({stats, d3d12_query::pipeline_statistics, 4}));
461 EXPECT(crossing_stats.end_query({stats, d3d12_query::pipeline_statistics, 5}));
462 EXPECT(crossing_stats.resolve_queries({stats, d3d12_query::pipeline_statistics, 4, 1, stats_dst_id,
463 5 * stats_result}));
464 EXPECT(crossing_stats.resolve_queries({stats, d3d12_query::pipeline_statistics, 5, 1, stats_dst_id,
465 6 * stats_result}));
466 EXPECT(crossing_stats.close());
467 for (std::uint32_t index : {6u, 7u, 8u}) {
468 EXPECT(stats_references.begin_query({stats, d3d12_query::pipeline_statistics, index}));
469 EXPECT(stats_references.end_query({stats, d3d12_query::pipeline_statistics, index}));
470 }
471 EXPECT(stats_references.resolve_queries({stats, d3d12_query::pipeline_statistics, 6, 3, stats_dst_id,
472 7 * stats_result}));
473 EXPECT(stats_references.close());
474 }
475 EXPECT(kind_overlap.begin_query({a, occ, 4}));
476 EXPECT(kind_overlap.begin_query({a, binary, 5}));
477 EXPECT(kind_overlap.end_query({a, binary, 5}));
478 EXPECT(kind_overlap.end_query({a, occ, 4}));
479 EXPECT(kind_overlap.resolve_queries({a, occ, 4, 1, dst_id, 168}));
480 EXPECT(kind_overlap.resolve_queries({a, binary, 5, 1, dst_id, 176}));
481 EXPECT(kind_overlap.close());
482 for (std::uint32_t index : {6u, 7u, 8u}) {
483 EXPECT(kind_references.begin_query({b, occ, index}));
484 EXPECT(kind_references.end_query({b, occ, index}));
485 }
486 EXPECT(kind_references.resolve_queries({b, occ, 6, 3, dst_id, 184}));
487 EXPECT(kind_references.close());
488 const CommandList* overlap_lists[] = {&crossing_stats, &stats_references, &kind_overlap, &kind_references};
489 EXPECT(queue.execute(overlap_lists) == ReplayResult::success);
449 EXPECT(!schedule.overflow && schedule.next == schedule.extents.size()); 490 EXPECT(!schedule.overflow && schedule.next == schedule.extents.size());
450 EXPECT(gate.signal(1)); 491 EXPECT(gate.signal(1));
451 EXPECT(queue.idle()); 492 EXPECT(queue.idle());
@@ -455,6 +496,21 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
455 {88, 2 * bursts + 1}, {96, 1}, {112, 4}, {120, 0}, {128, 4}, 496 {88, 2 * bursts + 1}, {96, 1}, {112, 4}, {120, 0}, {128, 4},
456 }; 497 };
457 if (fixture.statistics) expected[0] = 2 * bursts + 1; // the sum resolved inside the statistics query 498 if (fixture.statistics) expected[0] = 2 * bursts + 1; // the sum resolved inside the statistics query
499 { // D3D-252: the ordinary result covers three segments (draws 19, 21 and 23); the binary result is the
500 // shared segment's count normalized to 1. The reference queries carry the same draws unsplit, and their
501 // own results at 184, 192 and 200 are the expectation for the sums.
502 const auto word_at = [&](VkDeviceSize at) {
503 std::uint64_t value = 0;
504 std::memcpy(&value, static_cast<const char*>(mapping) + binding_offset + at, sizeof(value));
505 return value;
506 };
507 const std::uint64_t first = word_at(184), shared = word_at(192), last = word_at(200);
508 expected[168] = first + shared + last;
509 expected[176] = 1;
510 expected[184] = first;
511 expected[192] = shared;
512 expected[200] = last;
513 }
458 for (VkDeviceSize offset = 0; offset < size; offset += 8) { 514 for (VkDeviceSize offset = 0; offset < size; offset += 8) {
459 const auto it = expected.find(offset - binding_offset); 515 const auto it = expected.find(offset - binding_offset);
460 const auto want = it == expected.end() ? 0xcdcdcdcdcdcdcdcdULL : it->second; 516 const auto want = it == expected.end() ? 0xcdcdcdcdcdcdcdcdULL : it->second;
@@ -487,9 +543,25 @@ int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisec
487 } 543 }
488 } 544 }
489 EXPECT(word(0, cs_invocations) == 0 && word(1, 0) != 0 && word(2, 0) != 0); 545 EXPECT(word(0, cs_invocations) == 0 && word(1, 0) != 0 && word(2, 0) != 0);
546 // D3D-252: the crossing statistics queries (slots 5 and 6) each cover one private interval plus the shared
547 // intersection; slots 7 to 9 are the references with the same draws unsplit.
548 for (std::uint32_t counter = 0; counter < statistics_words; ++counter) {
549 if (word(5, counter) != word(7, counter) + word(8, counter) ||
550 word(6, counter) != word(8, counter) + word(9, counter)) {
551 std::fprintf(stderr, "crossing statistics counter %u: got %llu/%llu, wanted %llu/%llu\n", counter,
552 static_cast<unsigned long long>(word(5, counter)),
553 static_cast<unsigned long long>(word(6, counter)),
554 static_cast<unsigned long long>(word(7, counter) + word(8, counter)),
555 static_cast<unsigned long long>(word(8, counter) + word(9, counter)));
556 return 1;
557 }
558 }
559 EXPECT(word(5, cs_invocations) == 0 && word(6, cs_invocations) == 0);
490 std::printf("statistics split around a sum: IA vertices %llu, PS invocations %llu, CS invocations 0, " 560 std::printf("statistics split around a sum: IA vertices %llu, PS invocations %llu, CS invocations 0, "
491 "equal to two unsplit queries\n", 561 "equal to two unsplit queries\n",
492 static_cast<unsigned long long>(word(0, 0)), static_cast<unsigned long long>(word(0, 7))); 562 static_cast<unsigned long long>(word(0, 0)), static_cast<unsigned long long>(word(0, 7)));
563 std::printf("crossing statistics: IA vertices %llu/%llu, CS invocations 0, equal to the unsplit references\n",
564 static_cast<unsigned long long>(word(5, 0)), static_cast<unsigned long long>(word(6, 0)));
493 } 565 }
494 std::printf("crossing 80/20; nested 84/16; %u segments summed; alternating binary results 1/1; " 566 std::printf("crossing 80/20; nested 84/16; %u segments summed; alternating binary results 1/1; "
495 "resolve inside an active query 4; offsets and gated overwrites exact\n", 567 "resolve inside an active query 4; offsets and gated overwrites exact\n",
diff --git a/runtime/test/vk_pc_tail.h b/runtime/test/vk_pc_tail.h
new file mode 100644
index 000000000..fa0509e68
--- /dev/null
+++ b/runtime/test/vk_pc_tail.h
@@ -0,0 +1,125 @@
1// --pc-tail-ubo for the test programs: shaders translated with `rdna2spirv.py --pc-tail-ubo` keep s0..s31 (128 bytes)
2// in push constants and read the tail (heap base, code base; the --mesh-compute output address) from a uniform block
3// at set 1, binding 0 (docs/design.md, "Push-constant tail as a uniform block"). LEONIDA_PC_TAIL_UBO=1 says the
4// shaders were translated that way (build.py and run_gpu_tests.py pass the flag then). A test program then declares
5// 128 push-constant bytes and, when the module declares set 1, binds a PcTail: a host-visible buffer of one slot per
6// dispatch or draw, bound as a dynamic uniform buffer so each one can select its own tail.
7#pragma once
8
9#include <vulkan/vulkan.h>
10
11#include <cctype>
12#include <cstddef>
13#include <cstdint>
14#include <cstdlib>
15#include <cstring>
16#include <string>
17#include <vector>
18
19namespace leonida::vk_test {
20
21inline constexpr std::uint32_t pc_tail_set = 1;
22inline constexpr std::uint32_t pc_tail_binding = 0;
23
24// LEONIDA_PC_TAIL_UBO=1: the shaders were translated with --pc-tail-ubo. The values run_gpu_tests.py accepts:
25// 1/true/yes/on, any case, with the trailing space cmd.exe's `set VAR=1 &` leaves.
26inline bool pc_tail_requested() {
27 const char* v = std::getenv("LEONIDA_PC_TAIL_UBO");
28 std::string s = v ? v : "";
29 while (!s.empty() && std::isspace(static_cast<unsigned char>(s.back()))) s.pop_back();
30 while (!s.empty() && std::isspace(static_cast<unsigned char>(s.front()))) s.erase(s.begin());
31 for (char& c : s) c = char(std::tolower(static_cast<unsigned char>(c)));
32 return s == "1" || s == "true" || s == "yes" || s == "on";
33}
34
35// OpDecorate (71) <id> DescriptorSet (34) <set>: a --pc-tail-ubo module declares set 1 only when it reads the tail.
36inline bool spirv_declares_set(const void* data, std::size_t bytes, std::uint32_t set) {
37 if (bytes < 20 || bytes % 4) return false;
38 std::vector<std::uint32_t> words(bytes / 4);
39 std::memcpy(words.data(), data, bytes);
40 for (std::size_t i = 5; i < words.size() && (words[i] >> 16);) {
41 const std::uint32_t op = words[i] & 0xffff, count = words[i] >> 16;
42 if (op == 71 && count == 4 && i + 3 < words.size() && words[i + 2] == 34 && words[i + 3] == set) return true;
43 i += count;
44 }
45 return false;
46}
47
48// The tail block, `slots` slots of up to 6 dwords each (the 24-byte --mesh-compute tail), each at a multiple of the
49// device's minUniformBufferOffsetAlignment. create() returns false (and leaves what it made to the device's
50// destruction, as the test programs do) if any call fails. set_layout goes at index pc_tail_set of the pipeline
51// layout; a program with no set 0 of its own puts empty_layout at index 0.
52struct PcTail {
53 static constexpr VkDeviceSize slot_bytes = 6 * sizeof(std::uint32_t);
54 VkDescriptorSetLayout set_layout = VK_NULL_HANDLE;
55 VkDescriptorSetLayout empty_layout = VK_NULL_HANDLE;
56 VkDescriptorSet set = VK_NULL_HANDLE;
57 VkDeviceSize stride = 0;
58 std::uint32_t slots = 0;
59 std::uint8_t* map = nullptr;
60
61 bool create(PFN_vkGetDeviceProcAddr gdpa, VkDevice dev, const VkPhysicalDeviceMemoryProperties& memory,
62 VkDeviceSize min_offset_alignment, VkShaderStageFlags stages, std::uint32_t slot_count) {
63#define PC_TAIL_LOAD(f) auto f = reinterpret_cast<PFN_##f>(gdpa(dev, #f)); if (!f) return false
64 PC_TAIL_LOAD(vkCreateDescriptorSetLayout); PC_TAIL_LOAD(vkCreateDescriptorPool);
65 PC_TAIL_LOAD(vkAllocateDescriptorSets); PC_TAIL_LOAD(vkUpdateDescriptorSets); PC_TAIL_LOAD(vkCreateBuffer);
66 PC_TAIL_LOAD(vkGetBufferMemoryRequirements); PC_TAIL_LOAD(vkAllocateMemory); PC_TAIL_LOAD(vkBindBufferMemory);
67 PC_TAIL_LOAD(vkMapMemory);
68#undef PC_TAIL_LOAD
69 const VkDeviceSize align = min_offset_alignment ? min_offset_alignment : 1;
70 stride = (slot_bytes + align - 1) / align * align;
71 slots = slot_count ? slot_count : 1;
72
73 VkDescriptorSetLayoutBinding b{pc_tail_binding, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, stages, nullptr};
74 VkDescriptorSetLayoutCreateInfo li{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
75 li.bindingCount = 1; li.pBindings = &b;
76 if (vkCreateDescriptorSetLayout(dev, &li, nullptr, &set_layout) != VK_SUCCESS) return false;
77 VkDescriptorSetLayoutCreateInfo ei{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
78 if (vkCreateDescriptorSetLayout(dev, &ei, nullptr, &empty_layout) != VK_SUCCESS) return false;
79 VkDescriptorPoolSize ps{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1};
80 VkDescriptorPoolCreateInfo pi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
81 pi.maxSets = 1; pi.poolSizeCount = 1; pi.pPoolSizes = &ps;
82 VkDescriptorPool pool;
83 if (vkCreateDescriptorPool(dev, &pi, nullptr, &pool) != VK_SUCCESS) return false;
84 VkDescriptorSetAllocateInfo ai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
85 ai.descriptorPool = pool; ai.descriptorSetCount = 1; ai.pSetLayouts = &set_layout;
86 if (vkAllocateDescriptorSets(dev, &ai, &set) != VK_SUCCESS) return false;
87
88 VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
89 bi.size = stride * slots; bi.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
90 VkBuffer buffer;
91 if (vkCreateBuffer(dev, &bi, nullptr, &buffer) != VK_SUCCESS) return false;
92 VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, buffer, &mr);
93 constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
94 std::uint32_t type = 0;
95 while (type < memory.memoryTypeCount &&
96 !((mr.memoryTypeBits >> type & 1) && (memory.memoryTypes[type].propertyFlags & host) == host)) ++type;
97 if (type == memory.memoryTypeCount) return false;
98 VkMemoryAllocateInfo mi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
99 mi.allocationSize = mr.size; mi.memoryTypeIndex = type;
100 VkDeviceMemory mem;
101 if (vkAllocateMemory(dev, &mi, nullptr, &mem) != VK_SUCCESS) return false;
102 if (vkBindBufferMemory(dev, buffer, mem, 0) != VK_SUCCESS) return false;
103 void* p;
104 if (vkMapMemory(dev, mem, 0, VK_WHOLE_SIZE, 0, &p) != VK_SUCCESS) return false;
105 map = static_cast<std::uint8_t*>(p);
106 std::memset(map, 0, std::size_t(stride * slots));
107
108 VkDescriptorBufferInfo di{buffer, 0, slot_bytes};
109 VkWriteDescriptorSet w{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
110 w.dstSet = set; w.dstBinding = pc_tail_binding; w.descriptorCount = 1;
111 w.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; w.pBufferInfo = &di;
112 vkUpdateDescriptorSets(dev, 1, &w, 0, nullptr);
113 return true;
114 }
115
116 // The tail of slot `slot` from a push-constant array laid out as without the flag: words 32.. of `pc`, `words`
117 // of them (4, or 6 with --mesh-compute).
118 void write(std::uint32_t slot, const std::uint32_t* pc, std::uint32_t words) {
119 std::memcpy(map + stride * slot, pc + 32, words * sizeof(std::uint32_t));
120 }
121
122 std::uint32_t offset(std::uint32_t slot) const { return std::uint32_t(stride * slot); }
123};
124
125} // namespace leonida::vk_test
diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp
index 6e1e63eb8..65a53a5f3 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -1,7 +1,8 @@
1// Driver-level check of the translated corpus: vk_pipeline_check <spirv dir> [pipeline_cache.bin] 1// Driver-level check of the translated corpus: vk_pipeline_check <spirv dir> [pipeline_cache.bin]
2// Reads <spirv dir>/index.json (written by tools/rdna2spirv.py), creates a VkShaderModule for every entry and a real 2// Reads <spirv dir>/index.json (written by tools/rdna2spirv.py), creates a VkShaderModule for every entry and a real
3// pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash 3// pipeline with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash
4// table 2; storage images 4, 7 and 8..19; push constants 144 bytes): 4// table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants
5// sized from push_constant_bytes, default 144 or 128 with pc_tail):
5// - cs: compute pipeline via vkCreateComputePipelines 6// - cs: compute pipeline via vkCreateComputePipelines
6// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) 7// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass)
7// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py) 8// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py)
@@ -41,6 +42,7 @@
41#include "vk_device_pick.h" 42#include "vk_device_pick.h"
42#include "pipeline_cache_file.h" 43#include "pipeline_cache_file.h"
43#include "pipeline_cache_snapshot.h" 44#include "pipeline_cache_snapshot.h"
45#include "../src/spirv_words.h"
44 46
45#include <algorithm> 47#include <algorithm>
46#include <atomic> 48#include <atomic>
@@ -84,6 +86,8 @@ struct ShaderMeta {
84 std::string stage; 86 std::string stage;
85 uint32_t subgroup_size = 0; 87 uint32_t subgroup_size = 0;
86 uint32_t lds_bytes = 0; 88 uint32_t lds_bytes = 0;
89 uint32_t push_constant_bytes = 0; // 0 = absent in index (128 with pc_tail, else 144)
90 uint32_t pc_tail_bytes = 0; // >0 = --pc-tail-ubo uniform block at set 1, binding 0
87 bool writes_depth = false; 91 bool writes_depth = false;
88 bool needs_maintenance8 = false; 92 bool needs_maintenance8 = false;
89 std::vector<std::string> features; 93 std::vector<std::string> features;
@@ -263,6 +267,35 @@ struct JsonParser {
263 if (!error) fail("unterminated vertex_inputs array"); 267 if (!error) fail("unterminated vertex_inputs array");
264 return out; 268 return out;
265 } 269 }
270 uint32_t parse_strict_u32(const char* what) {
271 ws();
272 uint32_t v = 0;
273 const auto [end, ec] = std::from_chars(s.data() + i, s.data() + s.size(), v);
274 if (ec != std::errc{}) { fail(what); return 0u; }
275 i = static_cast<size_t>(end - s.data());
276 if (i < s.size() && (s[i] == '.' || s[i] == 'e' || s[i] == 'E')) { fail(what); return 0u; }
277 return v;
278 }
279 uint32_t parse_pc_tail_bytes() {
280 ws();
281 if (s.compare(i, 4, "null") == 0) { i += 4; return 0u; }
282 if (!consume('{')) { fail("expected object for pc_tail"); return 0u; }
283 uint32_t bytes = 0;
284 while (!error && i < s.size()) {
285 if (consume('}')) return bytes;
286 const size_t before = i;
287 std::string k = parse_string();
288 if (error) return bytes;
289 if (!consume(':')) { fail("expected ':' in pc_tail"); return bytes; }
290 if (k == "bytes") bytes = parse_strict_u32("expected unsigned 32-bit pc_tail.bytes");
291 else skip_value();
292 if (error) return bytes;
293 if (consume('}')) return bytes;
294 if (!consume(',') || i == before) { fail("expected ',' or '}' in pc_tail"); return bytes; }
295 }
296 if (!error) fail("unterminated pc_tail object");
297 return bytes;
298 }
266 ShaderMeta parse_meta() { 299 ShaderMeta parse_meta() {
267 ShaderMeta m; 300 ShaderMeta m;
268 if (!consume('{')) { skip_value(); return m; } 301 if (!consume('{')) { skip_value(); return m; }
@@ -279,12 +312,10 @@ struct JsonParser {
279 if (s.compare(i, 4, "null") == 0) { i += 4; m.subgroup_size = 0; } 312 if (s.compare(i, 4, "null") == 0) { i += 4; m.subgroup_size = 0; }
280 else m.subgroup_size = parse_u32(); 313 else m.subgroup_size = parse_u32();
281 } 314 }
282 else if (k == "lds_bytes") { 315 else if (k == "lds_bytes") m.lds_bytes = parse_strict_u32("expected unsigned 32-bit lds_bytes");
283 ws(); 316 else if (k == "push_constant_bytes")
284 const auto [end, ec] = std::from_chars(s.data() + i, s.data() + s.size(), m.lds_bytes); 317 m.push_constant_bytes = parse_strict_u32("expected unsigned 32-bit push_constant_bytes");
285 if (ec != std::errc{}) fail("expected unsigned 32-bit lds_bytes"); 318 else if (k == "pc_tail") m.pc_tail_bytes = parse_pc_tail_bytes();
286 else i = static_cast<size_t>(end - s.data());
287 }
288 else if (k == "writes_depth") m.writes_depth = parse_bool(); 319 else if (k == "writes_depth") m.writes_depth = parse_bool();
289 else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool(); 320 else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool();
290 else if (k == "features") m.features = parse_str_array(); 321 else if (k == "features") m.features = parse_str_array();
@@ -411,6 +442,21 @@ static_assert(shader_slice(7, 2, 0) == std::pair<size_t, size_t>{2, 7});
411static_assert(shader_slice(7, 8, 3) == std::pair<size_t, size_t>{7, 7}); 442static_assert(shader_slice(7, 8, 3) == std::pair<size_t, size_t>{7, 7});
412static_assert(shader_slice(7, 2, std::numeric_limits<size_t>::max()) == std::pair<size_t, size_t>{2, 7}); 443static_assert(shader_slice(7, 2, std::numeric_limits<size_t>::max()) == std::pair<size_t, size_t>{2, 7});
413 444
445// Push-constant range size a shader needs: its index push_constant_bytes when recorded (128 with --pc-tail-ubo,
446// 144 by default, 152 with --mesh-compute), or 128 when pc_tail is present, else 144. Rounded up to 4 bytes
447// (Vulkan requires VkPushConstantRange::size to be a positive multiple of 4).
448constexpr uint32_t required_push_bytes(uint32_t push_constant_bytes, uint32_t pc_tail_bytes) {
449 const uint32_t raw = push_constant_bytes ? push_constant_bytes : (pc_tail_bytes ? 128u : 144u);
450 return raw > (std::numeric_limits<uint32_t>::max() - 3u) ? raw : ((raw + 3u) & ~3u);
451}
452
453static_assert(required_push_bytes(0, 0) == 144);
454static_assert(required_push_bytes(0, 16) == 128);
455static_assert(required_push_bytes(128, 0) == 128);
456static_assert(required_push_bytes(128, 16) == 128);
457static_assert(required_push_bytes(144, 0) == 144);
458static_assert(required_push_bytes(152, 0) == 152);
459
414// --cache-feedback class of a successful pipeline: 0 hit, 1 no hit reported, 2 unavailable. A hit counts only with 460// --cache-feedback class of a successful pipeline: 0 hit, 1 no hit reported, 2 unavailable. A hit counts only with
415// VALID; the duration and base-pipeline bits are not classified. 461// VALID; the duration and base-pipeline bits are not classified.
416constexpr int feedback_outcome(VkPipelineCreationFeedbackFlags f) { 462constexpr int feedback_outcome(VkPipelineCreationFeedbackFlags f) {
@@ -547,6 +593,7 @@ int main(int argc, char** argv) {
547 } 593 }
548 std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen 594 std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen
549 std::string dir = argv[1], cache_path, stats_path, inflight_path, skip_path; 595 std::string dir = argv[1], cache_path, stats_path, inflight_path, skip_path;
596 bool cache_given = false; // an empty cache_path alone can't tell "not given" from an empty argument
550 uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2); 597 uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2);
551 size_t start = 0, count = 0, max_bytes = 0; 598 size_t start = 0, count = 0, max_bytes = 0;
552 size_t large_module_bytes = 4 * 1024 * 1024; 599 size_t large_module_bytes = 4 * 1024 * 1024;
@@ -592,9 +639,11 @@ int main(int argc, char** argv) {
592 else if (a.starts_with("--")) { // not a cache path: an option this build doesn't know 639 else if (a.starts_with("--")) { // not a cache path: an option this build doesn't know
593 std::fprintf(stderr, "unknown option %s\n", a.c_str()); 640 std::fprintf(stderr, "unknown option %s\n", a.c_str());
594 return 2; 641 return 2;
595 } else if (cache_path.empty()) cache_path = a; 642 } else if (!cache_given) {
596 else { 643 cache_path = a;
597 std::fprintf(stderr, "unexpected argument %s (the cache path is already %s)\n", a.c_str(), 644 cache_given = true;
645 } else {
646 std::fprintf(stderr, "unexpected argument '%s' (a cache path was already given: '%s')\n", a.c_str(),
598 cache_path.c_str()); 647 cache_path.c_str());
599 return 2; 648 return 2;
600 } 649 }
@@ -827,6 +876,7 @@ int main(int argc, char** argv) {
827#endif 876#endif
828 VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR exe{ 877 VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR exe{
829 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR}; 878 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR};
879 VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
830 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 880 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
831 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 881 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
832 void* chain = nullptr; 882 void* chain = nullptr;
@@ -837,6 +887,7 @@ int main(int argc, char** argv) {
837 b->pNext = static_cast<VkBaseOutStructure*>(chain); chain = s; 887 b->pNext = static_cast<VkBaseOutStructure*>(chain); chain = s;
838 return true; 888 return true;
839 }; 889 };
890 link(&f11, reinterpret_cast<VkBaseOutStructure*>(&f11), nullptr, true); // shaderDrawParameters (VS v0/v3)
840 link(&f12, reinterpret_cast<VkBaseOutStructure*>(&f12), nullptr, true); 891 link(&f12, reinterpret_cast<VkBaseOutStructure*>(&f12), nullptr, true);
841 link(&f13, reinterpret_cast<VkBaseOutStructure*>(&f13), nullptr, true); 892 link(&f13, reinterpret_cast<VkBaseOutStructure*>(&f13), nullptr, true);
842 const bool ext_mesh = link(&mesh, reinterpret_cast<VkBaseOutStructure*>(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, want_mesh); 893 const bool ext_mesh = link(&mesh, reinterpret_cast<VkBaseOutStructure*>(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, want_mesh);
@@ -872,6 +923,12 @@ int main(int argc, char** argv) {
872 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; 923 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
873 f2.pNext = chain; 924 f2.pNext = chain;
874 vkGetPhysicalDeviceFeatures2(pd, &f2); // fills every linked struct with what's supported 925 vkGetPhysicalDeviceFeatures2(pd, &f2); // fills every linked struct with what's supported
926 VkPhysicalDeviceMeshShaderPropertiesEXT mesh_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT};
927 if (ext_mesh && mesh.meshShader) {
928 VkPhysicalDeviceProperties2 mesh_device_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
929 mesh_device_props.pNext = &mesh_props;
930 vkGetPhysicalDeviceProperties2(pd, &mesh_device_props);
931 }
875 if (ext_mesh) { 932 if (ext_mesh) {
876 mesh.multiviewMeshShader = mesh.primitiveFragmentShadingRateMeshShader = mesh.meshShaderQueries = VK_FALSE; 933 mesh.multiviewMeshShader = mesh.primitiveFragmentShadingRateMeshShader = mesh.meshShaderQueries = VK_FALSE;
877 mesh.taskShader = VK_FALSE; 934 mesh.taskShader = VK_FALSE;
@@ -918,6 +975,12 @@ int main(int argc, char** argv) {
918 975
919 // Map enabled device features for per-shader compatibility checks. 976 // Map enabled device features for per-shader compatibility checks.
920 auto check_missing_feature = [&](const ShaderMeta& meta) -> std::string { 977 auto check_missing_feature = [&](const ShaderMeta& meta) -> std::string {
978 const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes);
979 if (need_pc > props.limits.maxPushConstantsSize) {
980 return "needs " + std::to_string(need_pc) + " push-constant bytes, device has " +
981 std::to_string(props.limits.maxPushConstantsSize) +
982 (need_pc > 128 ? " (translate with --pc-tail-ubo)" : "");
983 }
921 if (is_graphics_stage(meta.stage) && !f13.dynamicRendering) return "no dynamicRendering"; 984 if (is_graphics_stage(meta.stage) && !f13.dynamicRendering) return "no dynamicRendering";
922 if (meta.stage == "ms" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader"; 985 if (meta.stage == "ms" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader";
923 if (meta.stage == "gs" && !f2.features.geometryShader) return "no geometryShader"; 986 if (meta.stage == "gs" && !f2.features.geometryShader) return "no geometryShader";
@@ -950,6 +1013,7 @@ int main(int argc, char** argv) {
950 } 1013 }
951 if (feat == "shaderFloat64" && !f2.features.shaderFloat64) return "no shaderFloat64"; 1014 if (feat == "shaderFloat64" && !f2.features.shaderFloat64) return "no shaderFloat64";
952 if (feat == "shaderInt64" && !f2.features.shaderInt64) return "no shaderInt64"; 1015 if (feat == "shaderInt64" && !f2.features.shaderInt64) return "no shaderInt64";
1016 if (feat == "shaderDrawParameters" && !f11.shaderDrawParameters) return "no shaderDrawParameters";
953 if (feat == "bufferDeviceAddress" && !f12.bufferDeviceAddress) return "no bufferDeviceAddress"; 1017 if (feat == "bufferDeviceAddress" && !f12.bufferDeviceAddress) return "no bufferDeviceAddress";
954 if (feat == "runtimeDescriptorArray" && !f12.runtimeDescriptorArray) return "no runtimeDescriptorArray"; 1018 if (feat == "runtimeDescriptorArray" && !f12.runtimeDescriptorArray) return "no runtimeDescriptorArray";
955 if (feat == "shaderImageGatherExtended" && !f2.features.shaderImageGatherExtended) return "no shaderImageGatherExtended"; 1019 if (feat == "shaderImageGatherExtended" && !f2.features.shaderImageGatherExtended) return "no shaderImageGatherExtended";
@@ -976,10 +1040,41 @@ int main(int argc, char** argv) {
976 dli.bindingCount = uint32_t(b.size()); dli.pBindings = b.data(); 1040 dli.bindingCount = uint32_t(b.size()); dli.pBindings = b.data();
977 VkDescriptorSetLayout dsl; 1041 VkDescriptorSetLayout dsl;
978 if (VkResult r = vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)) { std::fprintf(stderr, "layout %d\n", r); return 1; } 1042 if (VkResult r = vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)) { std::fprintf(stderr, "layout %d\n", r); return 1; }
979 VkPushConstantRange pcr{VK_SHADER_STAGE_ALL, 0, 144}; 1043 // Set 1 of --pc-tail-ubo shaders (docs/design.md): dynamic uniform block at binding 0 holding heap/code base.
980 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 1044 const VkDescriptorSetLayoutBinding tail_binding{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1,
981 pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; 1045 VK_SHADER_STAGE_ALL, nullptr};
982 VkPipelineLayout pl; vkCreatePipelineLayout(dev, &pli, nullptr, &pl); 1046 VkDescriptorSetLayoutCreateInfo tail_dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
1047 tail_dli.bindingCount = 1; tail_dli.pBindings = &tail_binding;
1048 VkDescriptorSetLayout dsl_tail = VK_NULL_HANDLE;
1049 if (VkResult r = vkCreateDescriptorSetLayout(dev, &tail_dli, nullptr, &dsl_tail)) {
1050 std::fprintf(stderr, "tail layout %d\n", r); return 1;
1051 }
1052 // One VkPipelineLayout per (push_constant_bytes, has_pc_tail) needed by the selected shaders that fits
1053 // maxPushConstantsSize; never declares a range above the device limit (VUID-VkPushConstantRange-size-00298).
1054 std::map<std::pair<uint32_t, bool>, VkPipelineLayout> layouts;
1055 for (const auto& [_, meta] : work) {
1056 const uint32_t need_pc = required_push_bytes(meta->push_constant_bytes, meta->pc_tail_bytes);
1057 if (need_pc > props.limits.maxPushConstantsSize) continue;
1058 const std::pair<uint32_t, bool> key{need_pc, meta->pc_tail_bytes != 0};
1059 if (layouts.count(key)) continue;
1060 VkPushConstantRange pcr{VK_SHADER_STAGE_ALL, 0, need_pc};
1061 VkDescriptorSetLayout sets[2] = {dsl, dsl_tail};
1062 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
1063 pli.setLayoutCount = key.second ? 2u : 1u;
1064 pli.pSetLayouts = sets;
1065 pli.pushConstantRangeCount = 1;
1066 pli.pPushConstantRanges = &pcr;
1067 VkPipelineLayout pl = VK_NULL_HANDLE;
1068 if (VkResult r = vkCreatePipelineLayout(dev, &pli, nullptr, &pl)) {
1069 std::fprintf(stderr, "pipeline layout (%u bytes%s) %d\n", need_pc, key.second ? ", set 1" : "", r);
1070 return 1;
1071 }
1072 layouts.emplace(key, pl);
1073 }
1074 auto layout_for = [&](const ShaderMeta& meta) -> VkPipelineLayout {
1075 const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes);
1076 return layouts.at({need_pc, meta.pc_tail_bytes != 0});
1077 };
983 VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; 1078 VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO};
984 std::vector<char> seed; 1079 std::vector<char> seed;
985 if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly 1080 if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly
@@ -1050,13 +1145,13 @@ int main(int argc, char** argv) {
1050 auto it = stub_cache.find(fname); 1145 auto it = stub_cache.find(fname);
1051 if (it != stub_cache.end()) return it->second; 1146 if (it != stub_cache.end()) return it->second;
1052 } 1147 }
1053 std::ifstream f(dir + "/stubs/" + fname, std::ios::binary); 1148 std::ifstream f(dir + "/stubs/" + fname, std::ios::binary | std::ios::ate);
1054 std::vector<char> code((std::istreambuf_iterator<char>(f)), {}); 1149 const auto code = leonida::read_spirv_words(f, f.tellg());
1055 VkShaderModule mod = VK_NULL_HANDLE; 1150 VkShaderModule mod = VK_NULL_HANDLE;
1056 if (!code.empty()) { 1151 if (!code.empty()) {
1057 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 1152 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
1058 smi.codeSize = code.size(); 1153 smi.codeSize = code.size() * sizeof(code.front());
1059 smi.pCode = reinterpret_cast<const uint32_t*>(code.data()); 1154 smi.pCode = code.data();
1060 if (vkCreateShaderModule(dev, &smi, nullptr, &mod) != VK_SUCCESS) mod = VK_NULL_HANDLE; 1155 if (vkCreateShaderModule(dev, &smi, nullptr, &mod) != VK_SUCCESS) mod = VK_NULL_HANDLE;
1061 } 1156 }
1062 std::lock_guard<std::mutex> g(mu); 1157 std::lock_guard<std::mutex> g(mu);
@@ -1169,11 +1264,15 @@ int main(int argc, char** argv) {
1169 ++done; 1264 ++done;
1170 continue; 1265 continue;
1171 } 1266 }
1172 if (stage == "cs" && meta.lds_bytes > props.limits.maxComputeSharedMemorySize) { 1267 uint32_t shared_memory_limit = 0;
1268 if (stage == "cs") shared_memory_limit = props.limits.maxComputeSharedMemorySize;
1269 else if (stage == "ms") shared_memory_limit = mesh_props.maxMeshSharedMemorySize;
1270 if (shared_memory_limit && meta.lds_bytes > shared_memory_limit) {
1271 const char* limit_name = stage == "cs" ? "maxComputeSharedMemorySize" : "maxMeshSharedMemorySize";
1173 std::lock_guard<std::mutex> g(mu); 1272 std::lock_guard<std::mutex> g(mu);
1174 modules_bad[stage]++; 1273 modules_bad[stage]++;
1175 std::printf("MODULE FAIL %s (workgroup memory %u bytes exceeds maxComputeSharedMemorySize %u)\n", 1274 std::printf("MODULE FAIL %s (workgroup memory %u bytes exceeds %s %u)\n",
1176 name.c_str(), meta.lds_bytes, props.limits.maxComputeSharedMemorySize); 1275 name.c_str(), meta.lds_bytes, limit_name, shared_memory_limit);
1177 ++done; 1276 ++done;
1178 continue; 1277 continue;
1179 } 1278 }
@@ -1190,13 +1289,13 @@ int main(int argc, char** argv) {
1190 if (isolated) write_inflight(); // alone in flight: the file names exactly this module 1289 if (isolated) write_inflight(); // alone in flight: the file names exactly this module
1191 } 1290 }
1192 1291
1193 f.seekg(0); 1292 const auto code = leonida::read_spirv_words(f, file_size);
1194 std::vector<char> code((std::istreambuf_iterator<char>(f)), {});
1195 VkShaderModule sm = VK_NULL_HANDLE; 1293 VkShaderModule sm = VK_NULL_HANDLE;
1196 bool mod_ok = false; 1294 bool mod_ok = false;
1197 if (!code.empty()) { 1295 if (!code.empty()) {
1198 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 1296 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
1199 smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data()); 1297 smi.codeSize = code.size() * sizeof(code.front());
1298 smi.pCode = code.data();
1200 mod_ok = vkCreateShaderModule(dev, &smi, nullptr, &sm) == VK_SUCCESS; 1299 mod_ok = vkCreateShaderModule(dev, &smi, nullptr, &sm) == VK_SUCCESS;
1201 } 1300 }
1202 { 1301 {
@@ -1218,7 +1317,7 @@ int main(int argc, char** argv) {
1218 cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main"; 1317 cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main";
1219 const bool sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT); 1318 const bool sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT);
1220 if (sg_forced) cpi.stage.pNext = &reqSg; 1319 if (sg_forced) cpi.stage.pNext = &reqSg;
1221 cpi.layout = pl; 1320 cpi.layout = layout_for(meta);
1222 cpi.flags = capture; 1321 cpi.flags = capture;
1223 // Only whole-pipeline feedback is reported. 1322 // Only whole-pipeline feedback is reported.
1224 VkPipelineCreationFeedback fb{}; 1323 VkPipelineCreationFeedback fb{};
@@ -1390,7 +1489,7 @@ int main(int argc, char** argv) {
1390 gpci.pDepthStencilState = &ds; 1489 gpci.pDepthStencilState = &ds;
1391 gpci.pColorBlendState = &blend; 1490 gpci.pColorBlendState = &blend;
1392 gpci.pDynamicState = &dyn_state; 1491 gpci.pDynamicState = &dyn_state;
1393 gpci.layout = pl; 1492 gpci.layout = layout_for(meta);
1394 gpci.renderPass = VK_NULL_HANDLE; 1493 gpci.renderPass = VK_NULL_HANDLE;
1395 gpci.flags = capture; 1494 gpci.flags = capture;
1396 // Zeroed per call and read after it returns; per-stage entries are required but not reported. 1495 // Zeroed per call and read after it returns; per-stage entries are required but not reported.
diff --git a/runtime/test/vk_queue_test.cpp b/runtime/test/vk_queue_test.cpp
new file mode 100644
index 000000000..84289198c
--- /dev/null
+++ b/runtime/test/vk_queue_test.cpp
@@ -0,0 +1,210 @@
1// D3D12 copy and compute queues on their own Vulkan queues, with cross-queue fences. No shaders or game data.
2//
3// The device gets a queue per D3D12 type (dedicated families when the GPU has them). A copy queue uploads a buffer
4// and a texture, the way asset streaming does, signals a fence, and the direct queue waits on that fence on the GPU
5// before reading both back. The compute queue does the same handoff the other way. A copy queue must refuse a
6// render-target clear. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error
7// fails the test.
8#include "vk_test_device.h"
9#include "../src/vulkan_backend.h"
10
11#include <array>
12#include <cstdint>
13#include <cstring>
14#include <vector>
15
16#define EXPECT(condition) do { \
17 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
18} while (0)
19
20namespace {
21
22using namespace leonida;
23using Kind = VulkanQueue::QueueKind;
24
25const char* flags_text(VkQueueFlags f) {
26 static char buf[32];
27 std::snprintf(buf, sizeof buf, "%s%s%s", f & VK_QUEUE_GRAPHICS_BIT ? "G" : "", f & VK_QUEUE_COMPUTE_BIT ? "C" : "",
28 f & VK_QUEUE_TRANSFER_BIT ? "T" : "");
29 return buf;
30}
31
32int check_picker() {
33 // Synthetic family layouts: the picker's choices don't depend on the GPU running the test.
34 auto fam = [](VkQueueFlags flags, std::uint32_t granularity = 1) {
35 VkQueueFamilyProperties p{};
36 p.queueFlags = flags;
37 p.queueCount = 1;
38 p.minImageTransferGranularity = {granularity, granularity, granularity};
39 return p;
40 };
41 constexpr VkQueueFlags G = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT;
42 constexpr VkQueueFlags C = VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT;
43 constexpr VkQueueFlags T = VK_QUEUE_TRANSFER_BIT;
44 {
45 const std::array f{fam(G), fam(T), fam(C)}; // the common NVIDIA layout
46 const auto q = pick_queue_families(f, 0);
47 EXPECT(q.direct == 0 && q.compute == 2 && q.copy == 1);
48 }
49 {
50 const std::array f{fam(G)}; // one family for everything (integrated GPUs, llvmpipe)
51 const auto q = pick_queue_families(f, 0);
52 EXPECT(q.direct == 0 && q.compute == 0 && q.copy == 0);
53 }
54 {
55 const std::array f{fam(G), fam(C)}; // no DMA family: copies go to async compute
56 const auto q = pick_queue_families(f, 0);
57 EXPECT(q.compute == 1 && q.copy == 1);
58 }
59 {
60 const std::array f{fam(G), fam(T, 8), fam(C)}; // a coarse DMA family is skipped
61 const auto q = pick_queue_families(f, 0);
62 EXPECT(q.copy == 2);
63 }
64 std::printf("queue family picker: 4 layouts ok\n");
65 return 0;
66}
67
68constexpr std::uint32_t kSize = 64 * 1024;
69constexpr std::uint32_t kTex = 64; // 64x64 RGBA8: row pitch 256, already aligned
70
71std::uint8_t pattern(std::uint32_t i, std::uint8_t seed) { return std::uint8_t(i * 31 + seed); }
72
73} // namespace
74
75int main() {
76 if (check_picker()) return 1;
77
78 vktest::Device d;
79 d.all_queue_types = true;
80 if (!d.create()) {
81 std::printf("SKIP: no usable Vulkan device\n");
82 return 77;
83 }
84 std::printf("families: direct %u (%s)", d.family, flags_text(d.families[d.family].queueFlags));
85 std::printf(", compute %u (%s)", d.compute_family, flags_text(d.families[d.compute_family].queueFlags));
86 std::printf(", copy %u (%s)\n", d.copy_family, flags_text(d.families[d.copy_family].queueFlags));
87
88 VulkanContext context(d.device_proc, d.device, true);
89 EXPECT(context.loaded());
90 VulkanQueue direct(context, d.queue, d.family, Kind::direct);
91 VulkanQueue compute(context, d.compute_queue, d.compute_family, Kind::compute);
92 VulkanQueue copy(context, d.copy_queue, d.copy_family, Kind::copy);
93 EXPECT(direct.ok() && compute.ok() && copy.ok());
94
95 // Buffers: an upload source, a GPU-side destination and a readback, all host-visible for the test.
96 void *upload_map = nullptr, *mid_map = nullptr, *readback_map = nullptr, *tex_readback_map = nullptr;
97 const VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
98 VkBuffer upload = d.buffer(kSize, usage, &upload_map);
99 VkBuffer mid = d.buffer(kSize, usage, &mid_map);
100 VkBuffer readback = d.buffer(kSize, usage, &readback_map);
101 VkBuffer tex_readback = d.buffer(kTex * kTex * 4, usage, &tex_readback_map);
102 VkImage texture = d.image(VK_FORMAT_R8G8B8A8_UNORM, kTex, kTex, 1, VK_IMAGE_USAGE_SAMPLED_BIT);
103 EXPECT(upload && mid && readback && tex_readback && texture);
104 auto* up = static_cast<std::uint8_t*>(upload_map);
105 for (std::uint32_t i = 0; i < kSize; ++i) up[i] = pattern(i, 7);
106
107 const ResourceId upload_id = 1, mid_id = 2, readback_id = 3, tex_id = 4, tex_readback_id = 5;
108 auto add_buffer = [&](ResourceId id, VkBuffer b, VkDeviceSize size) {
109 ResourceBinding r;
110 r.buffer = b;
111 r.size = size;
112 context.add_resource(id, r);
113 };
114 add_buffer(upload_id, upload, kSize);
115 add_buffer(mid_id, mid, kSize);
116 add_buffer(readback_id, readback, kSize);
117 add_buffer(tex_readback_id, tex_readback, kTex * kTex * 4);
118 ResourceBinding tex;
119 tex.image = texture;
120 tex.format = VK_FORMAT_R8G8B8A8_UNORM;
121 tex.width = kTex;
122 tex.height = kTex;
123 // As the device registers a texture: tracked, still undefined, in D3D12's common state. Its first use is the
124 // copy-queue upload, which can't zero-fill it first.
125 context.add_resource(tex_id, tex, VK_IMAGE_LAYOUT_UNDEFINED);
126
127 VulkanFence fence(context, 0);
128 EXPECT(fence.semaphore());
129
130 // 1. Copy queue: buffer upload and a texture upload from the same staging buffer (footprint copy), then signal.
131 CommandList on_copy;
132 EXPECT(on_copy.copy_buffer({mid_id, 0, upload_id, 0, kSize}));
133 CopyTexture upload_tex{};
134 upload_tex.dst = {tex_id, false, 0, 0, 0, 0, 0, 0};
135 upload_tex.src = {upload_id, true, 0, 0, kTex, kTex, 1, kTex * 4};
136 EXPECT(on_copy.copy_texture(upload_tex));
137 EXPECT(on_copy.close());
138 const CommandList* copy_lists[] = {&on_copy};
139 EXPECT(copy.execute(copy_lists) == ReplayResult::success);
140 EXPECT(copy.signal(fence.semaphore(), 1));
141
142 // 2. Direct queue: wait for the copy queue on the GPU, then read both back.
143 direct.wait(fence.semaphore(), 1);
144 CommandList on_direct;
145 EXPECT(on_direct.copy_buffer({readback_id, 0, mid_id, 0, kSize}));
146 CopyTexture read_tex{};
147 read_tex.dst = {tex_readback_id, true, 0, 0, kTex, kTex, 1, kTex * 4};
148 read_tex.src = {tex_id, false, 0, 0, 0, 0, 0, 0};
149 EXPECT(on_direct.copy_texture(read_tex));
150 EXPECT(on_direct.close());
151 const CommandList* direct_lists[] = {&on_direct};
152 EXPECT(direct.execute(direct_lists) == ReplayResult::success);
153 EXPECT(direct.signal(fence.semaphore(), 2));
154 EXPECT(fence.wait(2, 5'000'000'000ull));
155
156 std::uint32_t bad = 0;
157 auto* rb = static_cast<std::uint8_t*>(readback_map);
158 for (std::uint32_t i = 0; i < kSize; ++i) bad += rb[i] != pattern(i, 7);
159 auto* tr = static_cast<std::uint8_t*>(tex_readback_map);
160 for (std::uint32_t i = 0; i < kTex * kTex * 4; ++i) bad += tr[i] != pattern(i, 7);
161 std::printf("copy -> direct: buffer and texture upload read back, %u bad bytes\n", bad);
162 EXPECT(bad == 0);
163
164 // 3. Compute queue the other way: wait for the direct queue, copy, signal; the host waits on the fence.
165 for (std::uint32_t i = 0; i < kSize; ++i) up[i] = pattern(i, 99);
166 CommandList on_direct2;
167 EXPECT(on_direct2.copy_buffer({mid_id, 0, upload_id, 0, kSize}));
168 EXPECT(on_direct2.close());
169 const CommandList* direct_lists2[] = {&on_direct2};
170 EXPECT(direct.execute(direct_lists2) == ReplayResult::success);
171 EXPECT(direct.signal(fence.semaphore(), 3));
172 compute.wait(fence.semaphore(), 3);
173 CommandList on_compute;
174 EXPECT(on_compute.copy_buffer({readback_id, 0, mid_id, 0, kSize}));
175 EXPECT(on_compute.close());
176 const CommandList* compute_lists[] = {&on_compute};
177 EXPECT(compute.execute(compute_lists) == ReplayResult::success);
178 EXPECT(compute.signal(fence.semaphore(), 4));
179 EXPECT(fence.wait(4, 5'000'000'000ull));
180 bad = 0;
181 for (std::uint32_t i = 0; i < kSize; ++i) bad += rb[i] != pattern(i, 99);
182 std::printf("direct -> compute: %u bad bytes\n", bad);
183 EXPECT(bad == 0);
184
185 // 4. A copy queue refuses a render-target clear and submits nothing.
186 VkImage rt_image = d.image(VK_FORMAT_R8G8B8A8_UNORM, 8, 8, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
187 ResourceBinding rt;
188 rt.image = rt_image;
189 rt.format = VK_FORMAT_R8G8B8A8_UNORM;
190 rt.width = rt.height = 8;
191 context.add_resource(6, rt, VK_IMAGE_LAYOUT_UNDEFINED);
192 CommandList clear;
193 TargetView view{};
194 view.resource = 6;
195 view.layer_count = 1;
196 EXPECT(clear.clear_render_target(view, ClearColor{}));
197 EXPECT(clear.close());
198 const CommandList* clear_lists[] = {&clear};
199 EXPECT(copy.execute(clear_lists) == ReplayResult::unsupported);
200 EXPECT(compute.execute(clear_lists) == ReplayResult::unsupported);
201 std::printf("copy and compute queues refuse a render-target clear\n");
202
203 EXPECT(direct.idle() && compute.idle() && copy.idle());
204 if (d.validation) {
205 std::printf("validation errors: %u\n", d.validation_errors());
206 EXPECT(d.validation_errors() == 0);
207 }
208 std::printf("vk_queue_test: OK\n");
209 return 0;
210}
diff --git a/runtime/test/vk_sampler_test.cpp b/runtime/test/vk_sampler_test.cpp
index c1bc4b7e1..2adf4d629 100644
--- a/runtime/test/vk_sampler_test.cpp
+++ b/runtime/test/vk_sampler_test.cpp
@@ -13,6 +13,7 @@
13#define VK_NO_PROTOTYPES 13#define VK_NO_PROTOTYPES
14#include "vulkan_loader.h" 14#include "vulkan_loader.h"
15#include "../src/vulkan_device_filter.h" 15#include "../src/vulkan_device_filter.h"
16#include "vk_pc_tail.h"
16 17
17#include "../src/descriptor_table.h" 18#include "../src/descriptor_table.h"
18#include "../src/gfx10_descriptors.h" 19#include "../src/gfx10_descriptors.h"
@@ -355,12 +356,19 @@ int main(int argc, char** argv) {
355 356
356 // Pipeline. 357 // Pipeline.
357 VkShaderModule modules[2]; 358 VkShaderModule modules[2];
359 // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 in 128 push-constant bytes; the heap base, if a
360 // stage reads it, in a uniform block at set 1 (vk_pc_tail.h).
361 const bool pc_tail = leonida::vk_test::pc_tail_requested();
362 const std::uint32_t push_bytes = pc_tail ? 128u : 144u;
363 bool tail_block = false;
358 for (int stage = 0; stage < 2; ++stage) { 364 for (int stage = 0; stage < 2; ++stage) {
359 const auto code = read_spv(argv[1 + stage]); 365 const auto code = read_spv(argv[1 + stage]);
360 if (code.empty()) { 366 if (code.empty()) {
361 std::fprintf(stderr, "cannot read %s\n", argv[1 + stage]); 367 std::fprintf(stderr, "cannot read %s\n", argv[1 + stage]);
362 return 1; 368 return 1;
363 } 369 }
370 if (pc_tail && leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set))
371 tail_block = true;
364 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 372 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
365 smi.codeSize = code.size() * 4; 373 smi.codeSize = code.size() * 4;
366 smi.pCode = code.data(); 374 smi.pCode = code.data();
@@ -374,12 +382,20 @@ int main(int argc, char** argv) {
374 stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; 382 stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
375 stages[1].module = modules[1]; 383 stages[1].module = modules[1];
376 stages[1].pName = "main"; 384 stages[1].pName = "main";
377 const VkPushConstantRange push{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, 144}; 385 const VkPushConstantRange push{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes};
378 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 386 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
379 pli.setLayoutCount = 1; 387 pli.setLayoutCount = 1;
380 pli.pSetLayouts = &dsl; 388 pli.pSetLayouts = &dsl;
381 pli.pushConstantRangeCount = 1; 389 pli.pushConstantRangeCount = 1;
382 pli.pPushConstantRanges = &push; 390 pli.pPushConstantRanges = &push;
391 leonida::vk_test::PcTail tail;
392 if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, props.limits.minUniformBufferOffsetAlignment,
393 VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 1)) {
394 std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n");
395 return 1;
396 }
397 const VkDescriptorSetLayout set_layouts[] = {dsl, tail.set_layout};
398 if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = set_layouts; }
383 VkPipelineLayout pipeline_layout; 399 VkPipelineLayout pipeline_layout;
384 CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pipeline_layout)); 400 CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pipeline_layout));
385 const VkPipelineVertexInputStateCreateInfo vertex_input{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; 401 const VkPipelineVertexInputStateCreateInfo vertex_input{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
@@ -472,7 +488,13 @@ int main(int argc, char** argv) {
472 block[0] = table_va; // s0:s1 = console VA of the T# (the shader's s1 stays 0) 488 block[0] = table_va; // s0:s1 = console VA of the T# (the shader's s1 stays 0)
473 block[32] = std::uint32_t(heap_base); 489 block[32] = std::uint32_t(heap_base);
474 block[33] = std::uint32_t(heap_base >> 32); 490 block[33] = std::uint32_t(heap_base >> 32);
475 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(block), block); 491 vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes, block);
492 if (tail_block) {
493 tail.write(0, block, 4);
494 const std::uint32_t offset = tail.offset(0);
495 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, leonida::vk_test::pc_tail_set, 1,
496 &tail.set, 1, &offset);
497 }
476 vkCmdDraw(cmd, 3, 1, 0, 0); 498 vkCmdDraw(cmd, 3, 1, 0, 0);
477 vkCmdEndRenderPass(cmd); 499 vkCmdEndRenderPass(cmd);
478 VkBufferImageCopy rc{}; 500 VkBufferImageCopy rc{};
diff --git a/runtime/test/vk_shader_fma.h b/runtime/test/vk_shader_fma.h
index e66884f97..a740859dc 100644
--- a/runtime/test/vk_shader_fma.h
+++ b/runtime/test/vk_shader_fma.h
@@ -21,14 +21,14 @@ inline constexpr bool shader_fma_in_headers = true;
21inline constexpr bool shader_fma_in_headers = false; 21inline constexpr bool shader_fma_in_headers = false;
22#endif 22#endif
23 23
24// OpCapability (17) FMAKHR (6030; spirv/unified1/spirv.h). 24// Find OpCapability (17) in a binary module.
25inline bool spirv_needs_fma(const void* data, std::size_t bytes) { 25inline bool spirv_declares_capability(const void* data, std::size_t bytes, std::uint32_t capability) {
26 if (bytes < 20 || bytes % 4) return false; 26 if (bytes < 20 || bytes % 4) return false;
27 std::vector<std::uint32_t> words(bytes / 4); 27 std::vector<std::uint32_t> words(bytes / 4);
28 std::memcpy(words.data(), data, bytes); 28 std::memcpy(words.data(), data, bytes);
29 for (std::size_t i = 5; i < words.size() && (words[i] >> 16);) { 29 for (std::size_t i = 5; i < words.size() && (words[i] >> 16);) {
30 const std::uint32_t op = words[i] & 0xffff, count = words[i] >> 16; 30 const std::uint32_t op = words[i] & 0xffff, count = words[i] >> 16;
31 if (op == 17 && count == 2 && i + 1 < words.size() && words[i + 1] == 6030) return true; 31 if (op == 17 && count == 2 && i + 1 < words.size() && words[i + 1] == capability) return true;
32 i += count; 32 i += count;
33 } 33 }
34 return false; 34 return false;
@@ -93,7 +93,7 @@ struct ShaderFma {
93 // True when the module can be used: it does not need FMAKHR, or the device enables shaderFmaFloat32. 93 // True when the module can be used: it does not need FMAKHR, or the device enables shaderFmaFloat32.
94 // Otherwise says so and the caller returns 77. 94 // Otherwise says so and the caller returns 77.
95 bool accepts(const void* code, std::size_t bytes, const char* name) const { 95 bool accepts(const void* code, std::size_t bytes, const char* name) const {
96 if (float32 || !spirv_needs_fma(code, bytes)) return true; 96 if (float32 || !spirv_declares_capability(code, bytes, 6030)) return true; // FMAKHR
97 std::fprintf(stderr, "unsupported: %s needs OpFmaKHR (VK_KHR_shader_fma, shaderFmaFloat32) and the device " 97 std::fprintf(stderr, "unsupported: %s needs OpFmaKHR (VK_KHR_shader_fma, shaderFmaFloat32) and the device "
98 "lacks it; translate with --fma glsl\n", name); 98 "lacks it; translate with --fma glsl\n", name);
99 return false; 99 return false;
diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp
index 964266d1b..e6b76d363 100644
--- a/runtime/test/vk_store_test.cpp
+++ b/runtime/test/vk_store_test.cpp
@@ -18,6 +18,7 @@
18#include "vulkan_loader.h" 18#include "vulkan_loader.h"
19#include "vk_device_pick.h" 19#include "vk_device_pick.h"
20#include "vk_shader_fma.h" 20#include "vk_shader_fma.h"
21#include "vk_pc_tail.h"
21#include "../src/gfx10_descriptors.h" 22#include "../src/gfx10_descriptors.h"
22 23
23#include <cmath> 24#include <cmath>
@@ -321,9 +322,23 @@ int main(int argc, char** argv) {
321 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 322 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
322 smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data()); 323 smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data());
323 VkShaderModule sm; CHECK(vkCreateShaderModule(dev, &smi, nullptr, &sm)); 324 VkShaderModule sm; CHECK(vkCreateShaderModule(dev, &smi, nullptr, &sm));
324 VkPushConstantRange pcr{VK_SHADER_STAGE_COMPUTE_BIT, 0, 144}; 325 // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only, 128 bytes; a module that reads the tail
326 // gets it, all zero as without the flag, from a uniform block at set 1 (vk_pc_tail.h).
327 const bool pc_tail = leonida::vk_test::pc_tail_requested();
328 const uint32_t pc_bytes = pc_tail ? 128u : 144u;
329 const bool tail_block = pc_tail &&
330 leonida::vk_test::spirv_declares_set(code.data(), code.size(), leonida::vk_test::pc_tail_set);
331 leonida::vk_test::PcTail tail;
332 if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, props.limits.minUniformBufferOffsetAlignment,
333 VK_SHADER_STAGE_COMPUTE_BIT, 1)) {
334 std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n");
335 return 1;
336 }
337 VkPushConstantRange pcr{VK_SHADER_STAGE_COMPUTE_BIT, 0, pc_bytes};
325 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 338 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
326 pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; 339 pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
340 const VkDescriptorSetLayout set_layouts[] = {dsl, tail.set_layout};
341 if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = set_layouts; }
327 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); 342 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl));
328 VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; 343 VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
329 cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; 344 cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
@@ -420,7 +435,12 @@ int main(int argc, char** argv) {
420 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); 435 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe);
421 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr); 436 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr);
422 uint32_t pc[36] = {}; 437 uint32_t pc[36] = {};
423 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, 144, pc); 438 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, pc_bytes, pc);
439 if (tail_block) {
440 const uint32_t offset = tail.offset(0); // PcTail starts zeroed: the tail stays all zero, as pushed before
441 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, leonida::vk_test::pc_tail_set, 1, &tail.set,
442 1, &offset);
443 }
424 vkCmdDispatch(cmd, 1, 1, 1); 444 vkCmdDispatch(cmd, 1, 1, 1);
425 for (int k = 0; k < 3; k++) { 445 for (int k = 0; k < 3; k++) {
426 ib[k].oldLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; 446 ib[k].oldLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index 84d9e7a7d..b1d5f8f73 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -5,6 +5,7 @@
5#pragma once 5#pragma once
6 6
7#include "vulkan_loader.h" 7#include "vulkan_loader.h"
8#include "../src/queue_families.h"
8#include "../src/vulkan_device_filter.h" 9#include "../src/vulkan_device_filter.h"
9#include "../src/vulkan13_features.h" 10#include "../src/vulkan13_features.h"
10#include "vk_device_pick.h" 11#include "vk_device_pick.h"
@@ -92,6 +93,10 @@ public:
92 std::vector<VkQueue> queues; 93 std::vector<VkQueue> queues;
93 bool validation = false; 94 bool validation = false;
94 bool bc = false; // textureCompressionBC enabled 95 bool bc = false; // textureCompressionBC enabled
96 bool all_queue_types = false;
97 VkQueue compute_queue = VK_NULL_HANDLE, copy_queue = VK_NULL_HANDLE;
98 std::uint32_t compute_family = 0, copy_family = 0;
99 std::vector<VkQueueFamilyProperties> families;
95 VkPhysicalDeviceFeatures enabled{}; // the core features enabled on `device` 100 VkPhysicalDeviceFeatures enabled{}; // the core features enabled on `device`
96 bool bindless = false; // the features the bindless set 0 needs are enabled 101 bool bindless = false; // the features the bindless set 0 needs are enabled
97 bool partially_bound = false; // and its slots can stay empty 102 bool partially_bound = false; // and its slots can stay empty
@@ -211,6 +216,9 @@ public:
211 std::vector<VkExtensionProperties> available(count); 216 std::vector<VkExtensionProperties> available(count);
212 enumerate_instance(nullptr, &count, available.data()); 217 enumerate_instance(nullptr, &count, available.data());
213 bool caps2 = false; 218 bool caps2 = false;
219 for (const auto& e : available) // lists the HDR10 (ST.2084) surface formats, when the display has them
220 if (std::strcmp(e.extensionName, "VK_EXT_swapchain_colorspace") == 0)
221 instance_extensions.push_back("VK_EXT_swapchain_colorspace");
214 for (const auto& e : available) { 222 for (const auto& e : available) {
215 caps2 = caps2 || std::strcmp(e.extensionName, "VK_KHR_get_surface_capabilities2") == 0; 223 caps2 = caps2 || std::strcmp(e.extensionName, "VK_KHR_get_surface_capabilities2") == 0;
216 surface_m1_khr = surface_m1_khr || std::strcmp(e.extensionName, "VK_KHR_surface_maintenance1") == 0; 224 surface_m1_khr = surface_m1_khr || std::strcmp(e.extensionName, "VK_KHR_surface_maintenance1") == 0;
@@ -286,15 +294,15 @@ public:
286 if (!candidate13.usable()) continue; 294 if (!candidate13.usable()) continue;
287 std::uint32_t family_count = 0; 295 std::uint32_t family_count = 0;
288 families_of(candidate, &family_count, nullptr); 296 families_of(candidate, &family_count, nullptr);
289 std::vector<VkQueueFamilyProperties> families(family_count); 297 std::vector<VkQueueFamilyProperties> candidate_families(family_count);
290 families_of(candidate, &family_count, families.data()); 298 families_of(candidate, &family_count, candidate_families.data());
291 for (std::uint32_t i = 0; i < family_count; ++i) { 299 for (std::uint32_t i = 0; i < family_count; ++i) {
292 if (!(families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) continue; 300 if (!(candidate_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) continue;
293 if (const int rank = leonida::vk_test::device_rank(props.deviceType, props.vendorID); 301 if (const int rank = leonida::vk_test::device_rank(props.deviceType, props.vendorID);
294 rank > best_rank) { 302 rank > best_rank) {
295 physical = candidate; 303 physical = candidate;
296 family = i; 304 family = i;
297 family_queue_count = families[i].queueCount; 305 family_queue_count = candidate_families[i].queueCount;
298 chosen = props; 306 chosen = props;
299 best_rank = rank; 307 best_rank = rank;
300 v13_.choose(candidate13); 308 v13_.choose(candidate13);
@@ -386,11 +394,32 @@ public:
386 enable12.samplerFilterMinmax = sampler_filter_minmax; 394 enable12.samplerFilterMinmax = sampler_filter_minmax;
387 enable12.bufferDeviceAddress = VK_TRUE; 395 enable12.bufferDeviceAddress = VK_TRUE;
388 396
389 const std::vector<float> priority(std::max(1u, std::min(queue_count_wanted, family_queue_count)), 1.0f); 397 const std::uint32_t graphics_count = std::max(1u, std::min(queue_count_wanted, family_queue_count));
390 VkDeviceQueueCreateInfo queue_info{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; 398 const std::vector<float> priority(graphics_count, 1.0f);
391 queue_info.queueFamilyIndex = family; 399 {
392 queue_info.queueCount = std::max(1u, std::min(queue_count_wanted, family_queue_count)); 400 std::uint32_t family_count = 0;
393 queue_info.pQueuePriorities = priority.data(); 401 families_of(physical, &family_count, nullptr);
402 families.resize(family_count);
403 families_of(physical, &family_count, families.data());
404 }
405 compute_family = copy_family = family;
406 if (all_queue_types) {
407 const auto picked = leonida::pick_queue_families(families, family);
408 compute_family = picked.compute;
409 copy_family = picked.copy;
410 }
411 std::vector<VkDeviceQueueCreateInfo> queue_infos;
412 for (std::uint32_t f : {family, compute_family, copy_family}) {
413 bool seen = false;
414 for (const auto& q : queue_infos) seen = seen || q.queueFamilyIndex == f;
415 if (seen) continue;
416 VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
417 q.queueFamilyIndex = f;
418 q.queueCount = f == family ? graphics_count : 1;
419 q.pQueuePriorities = priority.data();
420 queue_infos.push_back(q);
421 sharing_.push_back(f);
422 }
394 VkPhysicalDeviceFeatures enable{}; 423 VkPhysicalDeviceFeatures enable{};
395 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available 424 enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available
396 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features) 425 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features)
@@ -398,6 +427,7 @@ public:
398 enable.shaderSampledImageArrayDynamicIndexing = bindless; 427 enable.shaderSampledImageArrayDynamicIndexing = bindless;
399 enable.shaderStorageImageArrayDynamicIndexing = bindless; 428 enable.shaderStorageImageArrayDynamicIndexing = bindless;
400 enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available 429 enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available
430 enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available
401 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses 431 enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses
402 const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; 432 const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME;
403 433
@@ -471,8 +501,8 @@ public:
471 } 501 }
472 502
473 VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; 503 VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12};
474 device_info.queueCreateInfoCount = 1; 504 device_info.queueCreateInfoCount = std::uint32_t(queue_infos.size());
475 device_info.pQueueCreateInfos = &queue_info; 505 device_info.pQueueCreateInfos = queue_infos.data();
476 device_info.pEnabledFeatures = &enable; 506 device_info.pEnabledFeatures = &enable;
477 enabled = enable; 507 enabled = enable;
478 std::vector<const char*> device_extensions; 508 std::vector<const char*> device_extensions;
@@ -514,10 +544,12 @@ public:
514 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device); 544 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device);
515 if (result != VK_SUCCESS) return failure("vkCreateDevice", result); 545 if (result != VK_SUCCESS) return failure("vkCreateDevice", result);
516 device_proc = instance_fn<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr"); 546 device_proc = instance_fn<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr");
517 queues.resize(queue_info.queueCount); 547 queues.resize(graphics_count);
518 for (std::uint32_t i = 0; i < queue_info.queueCount; ++i) 548 for (std::uint32_t i = 0; i < graphics_count; ++i)
519 fn<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(device, family, i, &queues[i]); 549 fn<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(device, family, i, &queues[i]);
520 queue = queues[0]; 550 queue = queues[0];
551 fn<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(device, compute_family, 0, &compute_queue);
552 fn<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(device, copy_family, 0, &copy_queue);
521 instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(physical, 553 instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(physical,
522 &memory_); 554 &memory_);
523 VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; 555 VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};
@@ -547,6 +579,7 @@ public:
547 info.arrayLayers = layers; 579 info.arrayLayers = layers;
548 info.samples = VkSampleCountFlagBits(samples); 580 info.samples = VkSampleCountFlagBits(samples);
549 info.usage = usage | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; 581 info.usage = usage | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
582 share(info);
550 VkImage image = VK_NULL_HANDLE; 583 VkImage image = VK_NULL_HANDLE;
551 if (fn<PFN_vkCreateImage>("vkCreateImage")(device, &info, nullptr, &image) != VK_SUCCESS) return VK_NULL_HANDLE; 584 if (fn<PFN_vkCreateImage>("vkCreateImage")(device, &info, nullptr, &image) != VK_SUCCESS) return VK_NULL_HANDLE;
552 VkMemoryRequirements requirements{}; 585 VkMemoryRequirements requirements{};
@@ -563,6 +596,7 @@ public:
563 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 596 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
564 info.size = size; 597 info.size = size;
565 info.usage = usage | (buffer_device_address ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u); 598 info.usage = usage | (buffer_device_address ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u);
599 share(info);
566 VkBuffer buffer = VK_NULL_HANDLE; 600 VkBuffer buffer = VK_NULL_HANDLE;
567 if (fn<PFN_vkCreateBuffer>("vkCreateBuffer")(device, &info, nullptr, &buffer) != VK_SUCCESS) 601 if (fn<PFN_vkCreateBuffer>("vkCreateBuffer")(device, &info, nullptr, &buffer) != VK_SUCCESS)
568 return VK_NULL_HANDLE; 602 return VK_NULL_HANDLE;
@@ -646,6 +680,16 @@ public:
646 } 680 }
647 681
648private: 682private:
683 std::vector<std::uint32_t> sharing_;
684
685 template<typename Info>
686 void share(Info& info) const {
687 if (sharing_.size() < 2) return;
688 info.sharingMode = VK_SHARING_MODE_CONCURRENT;
689 info.queueFamilyIndexCount = std::uint32_t(sharing_.size());
690 info.pQueueFamilyIndices = sharing_.data();
691 }
692
649 VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags flags) { 693 VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags flags) {
650 for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) { 694 for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) {
651 if (!(requirements.memoryTypeBits & (1u << i))) continue; 695 if (!(requirements.memoryTypeBits & (1u << i))) continue;
diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp
index 69f4b5675..2deb3f812 100644
--- a/runtime/test/vk_texture_test.cpp
+++ b/runtime/test/vk_texture_test.cpp
@@ -23,6 +23,7 @@
23#include "vulkan_loader.h" 23#include "vulkan_loader.h"
24#include "vk_device_pick.h" 24#include "vk_device_pick.h"
25#include "vk_shader_fma.h" 25#include "vk_shader_fma.h"
26#include "vk_pc_tail.h"
26 27
27#include <algorithm> 28#include <algorithm>
28#include <cmath> 29#include <cmath>
@@ -112,10 +113,11 @@ int main(int argc, char** argv) {
112 std::fprintf(stderr, "usage: vk_texture_test [cube|dref|dref_a16] [out] | vs fs out ptr_sgpr s0 s1 s2 s3 [--two-mip|--two-mip-sint]\n"); 113 std::fprintf(stderr, "usage: vk_texture_test [cube|dref|dref_a16] [out] | vs fs out ptr_sgpr s0 s1 s2 s3 [--two-mip|--two-mip-sint]\n");
113 return 2; 114 return 2;
114 } 115 }
115 // Word 1 also selects the numeric type when the shader fetches through this key. 116 // Word 1 also selects the numeric type when the shader fetches through this key. Word 3 keeps BASE_LEVEL [15:12]
117 // at 0, as the views here start at level 0: image_get_resinfo minifies a 2D array's layers from BASE_LEVEL.
116 const VkFormat sampled_format = dref ? VK_FORMAT_D32_SFLOAT : 118 const VkFormat sampled_format = dref ? VK_FORMAT_D32_SFLOAT :
117 signed_mips ? VK_FORMAT_R8G8B8A8_SINT : VK_FORMAT_R8G8B8A8_UNORM; 119 signed_mips ? VK_FORMAT_R8G8B8A8_SINT : VK_FORMAT_R8G8B8A8_UNORM;
118 uint32_t tsharp[8] = {0x11111111, leonida::gfx10::format_from_vulkan(sampled_format) << 20, 0x33333333, 0x44444444, 120 uint32_t tsharp[8] = {0x11111111, leonida::gfx10::format_from_vulkan(sampled_format) << 20, 0x33333333, 0x44440444,
119 0x55555555, 0x66666666, 0x77777777, 0x88888888}; 121 0x55555555, 0x66666666, 0x77777777, 0x88888888};
120 const uint32_t tsharp_va = 256; 122 const uint32_t tsharp_va = 256;
121 123
@@ -155,7 +157,10 @@ int main(int argc, char** argv) {
155 } 157 }
156 } 158 }
157 constexpr uint32_t push_words = 36; 159 constexpr uint32_t push_words = 36;
158 constexpr uint32_t push_bytes = push_words * sizeof(uint32_t); 160 // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only; the heap base is in a uniform block at set 1
161 // (vk_pc_tail.h), so a 128-byte device runs these tests too.
162 const bool pc_tail = leonida::vk_test::pc_tail_requested();
163 const uint32_t push_bytes = pc_tail ? 128u : push_words * uint32_t(sizeof(uint32_t));
159 if (properties.limits.maxPushConstantsSize < push_bytes) { 164 if (properties.limits.maxPushConstantsSize < push_bytes) {
160 std::fprintf(stderr, "unsupported: need %u push constant bytes, device has %u\n", 165 std::fprintf(stderr, "unsupported: need %u push constant bytes, device has %u\n",
161 push_bytes, properties.limits.maxPushConstantsSize); 166 push_bytes, properties.limits.maxPushConstantsSize);
@@ -172,7 +177,11 @@ int main(int argc, char** argv) {
172 float prio = 1; 177 float prio = 1;
173 VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; 178 VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
174 qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; 179 qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio;
180 // Translated vertex shaders read BaseVertex / BaseInstance (DrawParameters) for the zero-based v0 / v3.
181 VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES};
182 f11.shaderDrawParameters = VK_TRUE;
175 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; 183 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
184 f12.pNext = &f11;
176 f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE; 185 f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE;
177 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12; 186 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12;
178 f2.features.shaderInt64 = VK_TRUE; 187 f2.features.shaderInt64 = VK_TRUE;
@@ -413,12 +422,15 @@ int main(int argc, char** argv) {
413 wr[3].dstBinding = 3; wr[3].descriptorCount = 2; wr[3].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[3].pImageInfo = ai2; 422 wr[3].dstBinding = 3; wr[3].descriptorCount = 2; wr[3].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[3].pImageInfo = ai2;
414 vkUpdateDescriptorSets(dev, 4, wr, 0, nullptr); 423 vkUpdateDescriptorSets(dev, 4, wr, 0, nullptr);
415 // Pipeline. 424 // Pipeline.
425 bool tail_block = false; // a stage reads the --pc-tail-ubo block (declares set 1)
416 auto module = [&](const char* p, VkShaderModule* m) { 426 auto module = [&](const char* p, VkShaderModule* m) {
417 auto code = read_spv(p); 427 auto code = read_spv(p);
418 if (code.empty()) { 428 if (code.empty()) {
419 std::fprintf(stderr, "failed to read shader module: %s\n", p); 429 std::fprintf(stderr, "failed to read shader module: %s\n", p);
420 return VK_ERROR_INITIALIZATION_FAILED; 430 return VK_ERROR_INITIALIZATION_FAILED;
421 } 431 }
432 if (pc_tail && leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set))
433 tail_block = true;
422 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; smi.codeSize = code.size() * 4; smi.pCode = code.data(); 434 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; smi.codeSize = code.size() * 4; smi.pCode = code.data();
423 return vkCreateShaderModule(dev, &smi, nullptr, m); 435 return vkCreateShaderModule(dev, &smi, nullptr, m);
424 }; 436 };
@@ -429,6 +441,14 @@ int main(int argc, char** argv) {
429 VkPushConstantRange pcr{VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes}; 441 VkPushConstantRange pcr{VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes};
430 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; 442 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
431 pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; 443 pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
444 leonida::vk_test::PcTail tail;
445 if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, properties.limits.minUniformBufferOffsetAlignment,
446 VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 1)) {
447 std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n");
448 return 1;
449 }
450 const VkDescriptorSetLayout set_layouts[] = {dsl, tail.set_layout};
451 if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = set_layouts; }
432 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); 452 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl));
433 VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; 453 VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
434 VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; 454 VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
@@ -481,7 +501,13 @@ int main(int argc, char** argv) {
481 uint32_t pc[push_words] = {}; 501 uint32_t pc[push_words] = {};
482 pc[ptr_sgpr] = tsharp_va; // pointer to the T# (low dword; the shader forces the high dword to 0) 502 pc[ptr_sgpr] = tsharp_va; // pointer to the T# (low dword; the shader forces the high dword to 0)
483 pc[32] = uint32_t(heap_base); pc[33] = uint32_t(heap_base >> 32); 503 pc[32] = uint32_t(heap_base); pc[33] = uint32_t(heap_base >> 32);
484 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(pc), pc); 504 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes, pc);
505 if (tail_block) {
506 tail.write(0, pc, 4);
507 const uint32_t offset = tail.offset(0);
508 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, leonida::vk_test::pc_tail_set, 1, &tail.set,
509 1, &offset);
510 }
485 vkCmdDraw(cmd, 3, 1, 0, 0); 511 vkCmdDraw(cmd, 3, 1, 0, 0);
486 vkCmdEndRenderPass(cmd); 512 vkCmdEndRenderPass(cmd);
487 VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1}; 513 VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1};
diff --git a/runtime/test/winhttp_offline_test.cpp b/runtime/test/winhttp_offline_test.cpp
new file mode 100644
index 000000000..3d80c7f02
--- /dev/null
+++ b/runtime/test/winhttp_offline_test.cpp
@@ -0,0 +1,296 @@
1// Checks the offline WinHTTP the shims give a mapped title (runtime/shims/winhttp_offline.cpp).
2//
3// Every function is resolved through rt::shims::find under winhttp.dll, so the test runs against the table the
4// runtime installs. Nothing here touches the network: the server names use the reserved .invalid top-level domain, and
5// the only host WinHTTP call the shims make is WinHttpCrackUrl, which parses a string.
6#include <windows.h>
7#include <winhttp.h>
8
9#include <atomic>
10#include <chrono>
11#include <cstdio>
12#include <cstring>
13
14#include "shims.h"
15
16namespace {
17
18using OpenFn = HINTERNET(WINAPI*)(LPCWSTR, DWORD, LPCWSTR, LPCWSTR, DWORD);
19using ConnectFn = HINTERNET(WINAPI*)(HINTERNET, LPCWSTR, INTERNET_PORT, DWORD);
20using OpenRequestFn = HINTERNET(WINAPI*)(HINTERNET, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR*, DWORD);
21using SendRequestFn = BOOL(WINAPI*)(HINTERNET, LPCWSTR, DWORD, LPVOID, DWORD, DWORD, DWORD_PTR);
22using ReceiveResponseFn = BOOL(WINAPI*)(HINTERNET, LPVOID);
23using ReadDataFn = BOOL(WINAPI*)(HINTERNET, LPVOID, DWORD, LPDWORD);
24using QueryHeadersFn = BOOL(WINAPI*)(HINTERNET, DWORD, LPCWSTR, LPVOID, LPDWORD, LPDWORD);
25using AddRequestHeadersFn = BOOL(WINAPI*)(HINTERNET, LPCWSTR, DWORD, DWORD);
26using SetTimeoutsFn = BOOL(WINAPI*)(HINTERNET, int, int, int, int);
27using SetOptionFn = BOOL(WINAPI*)(HINTERNET, DWORD, LPVOID, DWORD);
28using QueryOptionFn = BOOL(WINAPI*)(HINTERNET, DWORD, LPVOID, LPDWORD);
29using SetStatusCallbackFn = WINHTTP_STATUS_CALLBACK(WINAPI*)(HINTERNET, WINHTTP_STATUS_CALLBACK, DWORD, DWORD_PTR);
30using CloseHandleFn = BOOL(WINAPI*)(HINTERNET);
31using CrackUrlFn = BOOL(WINAPI*)(LPCWSTR, DWORD, DWORD, LPURL_COMPONENTS);
32
33int g_checks = 0;
34int g_failures = 0;
35
36void check(bool condition, const char* what) {
37 ++g_checks;
38 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
39 if (!condition) ++g_failures;
40}
41
42template <typename Fn>
43Fn resolve(const char* name) {
44 return reinterpret_cast<Fn>(rt::shims::find("winhttp.dll", name));
45}
46
47// What the status callback saw, for the asynchronous checks.
48struct Seen {
49 std::atomic<int> request_errors{0};
50 std::atomic<int> closing{0};
51 std::atomic<int> created{0};
52 std::atomic<DWORD> api{0};
53 std::atomic<DWORD> error{0};
54 std::atomic<DWORD_PTR> context{0};
55 std::atomic<DWORD> thread{0};
56 std::atomic<bool> closing_after_error{true};
57 HANDLE error_event = nullptr;
58 HANDLE closing_event = nullptr;
59 CloseHandleFn close_in_callback = nullptr; // when set, the error callback closes the request itself
60};
61Seen* g_seen = nullptr;
62
63void CALLBACK on_status(HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID info, DWORD length) {
64 Seen& s = *g_seen;
65 if (status == WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) {
66 ++s.created;
67 } else if (status == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR && info && length == sizeof(WINHTTP_ASYNC_RESULT)) {
68 const auto* result = static_cast<const WINHTTP_ASYNC_RESULT*>(info);
69 s.api = static_cast<DWORD>(result->dwResult);
70 s.error = result->dwError;
71 s.context = context;
72 s.thread = GetCurrentThreadId();
73 ++s.request_errors;
74 if (s.close_in_callback) s.close_in_callback(handle);
75 SetEvent(s.error_event);
76 } else if (status == WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) {
77 if (s.request_errors.load() == 0) s.closing_after_error = false;
78 if (info && length == sizeof(HINTERNET) && *static_cast<HINTERNET*>(info) == handle) ++s.closing;
79 SetEvent(s.closing_event);
80 }
81}
82
83double ms_since(std::chrono::steady_clock::time_point start) {
84 return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
85}
86
87} // namespace
88
89int main() {
90 const auto open = resolve<OpenFn>("WinHttpOpen");
91 const auto connect = resolve<ConnectFn>("WinHttpConnect");
92 const auto open_request = resolve<OpenRequestFn>("WinHttpOpenRequest");
93 const auto send = resolve<SendRequestFn>("WinHttpSendRequest");
94 const auto receive = resolve<ReceiveResponseFn>("WinHttpReceiveResponse");
95 const auto read = resolve<ReadDataFn>("WinHttpReadData");
96 const auto query_headers = resolve<QueryHeadersFn>("WinHttpQueryHeaders");
97 const auto add_headers = resolve<AddRequestHeadersFn>("WinHttpAddRequestHeaders");
98 const auto set_timeouts = resolve<SetTimeoutsFn>("WinHttpSetTimeouts");
99 const auto set_option = resolve<SetOptionFn>("WinHttpSetOption");
100 const auto query_option = resolve<QueryOptionFn>("WinHttpQueryOption");
101 const auto set_callback = resolve<SetStatusCallbackFn>("WinHttpSetStatusCallback");
102 const auto close = resolve<CloseHandleFn>("WinHttpCloseHandle");
103 const auto crack = resolve<CrackUrlFn>("WinHttpCrackUrl");
104 check(open && connect && open_request && send && receive && read && query_headers && add_headers &&
105 set_timeouts && set_option && query_option && set_callback && close && crack &&
106 rt::shims::find("winhttp.dll", "WinHttpQueryDataAvailable") &&
107 rt::shims::find("winhttp.dll", "WinHttpWriteData"),
108 "all 16 WinHTTP imports of the package resolve through the registry");
109 check(rt::shims::owns_dll("winhttp.dll"), "winhttp.dll is a module the shims own (LoadLibrary gets a pseudo-handle)");
110 if (!(open && connect && open_request && send && close && set_callback)) {
111 std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures + 1);
112 return 1;
113 }
114
115 // Synchronous: the send fails at once, nothing is resolved or connected.
116 {
117 const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, 0);
118 check(session != nullptr, "WinHttpOpen returns a session");
119 const HINTERNET connection = connect(session, L"example.invalid", INTERNET_DEFAULT_HTTPS_PORT, 0);
120 check(connection != nullptr, "WinHttpConnect returns a connection without resolving the name");
121 const HINTERNET request =
122 open_request(connection, L"GET", L"/x", nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
123 WINHTTP_FLAG_SECURE);
124 check(request != nullptr, "WinHttpOpenRequest returns a request");
125 check(add_headers(request, L"X-Test: 1", static_cast<DWORD>(-1), WINHTTP_ADDREQ_FLAG_ADD) != FALSE,
126 "request headers are accepted");
127 check(set_timeouts(request, 1000, 1000, 1000, 1000) != FALSE, "timeouts are accepted");
128
129 SetLastError(0);
130 const auto start = std::chrono::steady_clock::now();
131 const BOOL sent = send(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
132 const DWORD error = GetLastError();
133 const double elapsed = ms_since(start);
134 check(sent == FALSE && error == ERROR_WINHTTP_CANNOT_CONNECT,
135 "WinHttpSendRequest fails with ERROR_WINHTTP_CANNOT_CONNECT");
136 check(elapsed < 50.0, "and fails at once (under 50 ms)");
137 SetLastError(0);
138 check(receive(request, nullptr) == FALSE && GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_STATE,
139 "there is no response to receive");
140 char buffer[16];
141 DWORD got = 0;
142 SetLastError(0);
143 check(read(request, buffer, sizeof(buffer), &got) == FALSE &&
144 GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_STATE,
145 "and nothing to read");
146 DWORD status = 0, size = sizeof(status);
147 SetLastError(0);
148 check(query_headers(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX,
149 &status, &size, WINHTTP_NO_HEADER_INDEX) == FALSE &&
150 GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_STATE,
151 "and no status code");
152
153 // Options: the context value round-trips, the handle type is answered, the rest is refused when queried.
154 DWORD_PTR value = 0x1234;
155 check(set_option(request, WINHTTP_OPTION_CONTEXT_VALUE, &value, sizeof(value)) != FALSE,
156 "WINHTTP_OPTION_CONTEXT_VALUE can be set");
157 DWORD_PTR back = 0;
158 DWORD back_size = sizeof(back);
159 check(query_option(request, WINHTTP_OPTION_CONTEXT_VALUE, &back, &back_size) != FALSE && back == 0x1234,
160 "and queried back");
161 DWORD type = 0, type_size = sizeof(type);
162 check(query_option(connection, WINHTTP_OPTION_HANDLE_TYPE, &type, &type_size) != FALSE &&
163 type == WINHTTP_HANDLE_TYPE_CONNECT,
164 "WINHTTP_OPTION_HANDLE_TYPE names a connection");
165 DWORD needed = 0;
166 SetLastError(0);
167 check(query_option(request, WINHTTP_OPTION_CONTEXT_VALUE, nullptr, &needed) == FALSE &&
168 GetLastError() == ERROR_INSUFFICIENT_BUFFER && needed == sizeof(DWORD_PTR),
169 "a query without a buffer reports the size it needs");
170 DWORD flags = 0, flags_size = sizeof(flags);
171 SetLastError(0);
172 check(query_option(request, WINHTTP_OPTION_SECURITY_FLAGS, &flags, &flags_size) == FALSE &&
173 GetLastError() == ERROR_WINHTTP_INVALID_OPTION,
174 "other options are not answered");
175 DWORD protocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
176 check(set_option(session, WINHTTP_OPTION_SECURE_PROTOCOLS, &protocols, sizeof(protocols)) != FALSE,
177 "but setting them is accepted");
178
179 // Wrong handles.
180 SetLastError(0);
181 check(connect(request, L"example.invalid", 80, 0) == nullptr &&
182 GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_TYPE,
183 "a request is not a session");
184 SetLastError(0);
185 check(send(connection, nullptr, 0, nullptr, 0, 0, 0) == FALSE &&
186 GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_TYPE,
187 "a connection is not a request");
188 SetLastError(0);
189 check(connect(session, nullptr, 80, 0) == nullptr && GetLastError() == ERROR_INVALID_PARAMETER,
190 "a connection needs a server name");
191
192 check(close(request) != FALSE && close(connection) != FALSE && close(session) != FALSE,
193 "the handles close, children first");
194 SetLastError(0);
195 check(close(request) == FALSE && GetLastError() == ERROR_INVALID_HANDLE, "a closed handle is gone");
196 SetLastError(0);
197 check(send(request, nullptr, 0, nullptr, 0, 0, 0) == FALSE && GetLastError() == ERROR_INVALID_HANDLE,
198 "and cannot be used");
199 }
200
201 // Asynchronous: the send returns TRUE, the failure arrives through the inherited callback on another thread with
202 // the request's context, and HANDLE_CLOSING comes last.
203 Seen seen;
204 seen.error_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
205 seen.closing_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
206 g_seen = &seen;
207 {
208 const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, WINHTTP_FLAG_ASYNC);
209 check(set_callback(session, &on_status, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0) == nullptr,
210 "WinHttpSetStatusCallback returns the previous callback (none)");
211 const HINTERNET connection = connect(session, L"example.invalid", 443, 0);
212 const HINTERNET request = open_request(connection, L"POST", L"/y", nullptr, WINHTTP_NO_REFERER,
213 WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
214 check(connection && request && seen.created.load() == 2,
215 "the callback is inherited and reports both new handles as created");
216
217 const auto start = std::chrono::steady_clock::now();
218 const BOOL sent = send(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0xC0FFEE);
219 check(sent != FALSE, "an asynchronous WinHttpSendRequest returns TRUE");
220 const bool fired = WaitForSingleObject(seen.error_event, 2000) == WAIT_OBJECT_0;
221 const double elapsed = ms_since(start);
222 check(fired && seen.request_errors.load() == 1, "WINHTTP_CALLBACK_STATUS_REQUEST_ERROR arrives once");
223 check(seen.api.load() == API_SEND_REQUEST && seen.error.load() == ERROR_WINHTTP_CANNOT_CONNECT,
224 "for API_SEND_REQUEST with ERROR_WINHTTP_CANNOT_CONNECT");
225 check(seen.context.load() == 0xC0FFEE, "with the context the request was sent with");
226 check(seen.thread.load() != GetCurrentThreadId(), "on another thread");
227 check(elapsed < 500.0, "within 500 ms");
228
229 check(close(request) != FALSE, "the request closes");
230 check(WaitForSingleObject(seen.closing_event, 2000) == WAIT_OBJECT_0 && seen.closing.load() == 1 &&
231 seen.closing_after_error.load(),
232 "and HANDLE_CLOSING follows once, after the error");
233 close(connection);
234 close(session);
235 check(seen.closing.load() == 3, "every handle reports HANDLE_CLOSING once");
236 }
237
238 // A callback that closes its request while handling the error, as libHttpClient-style code does.
239 {
240 seen.request_errors = 0;
241 seen.closing = 0;
242 seen.close_in_callback = close;
243 ResetEvent(seen.closing_event);
244 const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, WINHTTP_FLAG_ASYNC);
245 set_callback(session, &on_status, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0);
246 const HINTERNET connection = connect(session, L"example.invalid", 443, 0);
247 const HINTERNET request = open_request(connection, L"GET", L"/z", nullptr, WINHTTP_NO_REFERER,
248 WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
249 check(send(request, nullptr, 0, nullptr, 0, 0, 7) != FALSE, "a second asynchronous send is queued");
250 check(WaitForSingleObject(seen.error_event, 2000) == WAIT_OBJECT_0, "its error arrives");
251 check(WaitForSingleObject(seen.closing_event, 2000) == WAIT_OBJECT_0 && seen.closing.load() == 1,
252 "closing the request inside the callback reports HANDLE_CLOSING once");
253 seen.close_in_callback = nullptr;
254 close(connection);
255 close(session);
256 }
257
258 // A request closed before its queued failure is delivered gets no error callback, only HANDLE_CLOSING.
259 {
260 seen.request_errors = 0;
261 seen.closing = 0;
262 const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, WINHTTP_FLAG_ASYNC);
263 set_callback(session, &on_status, WINHTTP_CALLBACK_FLAG_HANDLES, 0); // closing only
264 const HINTERNET connection = connect(session, L"example.invalid", 443, 0);
265 const HINTERNET request = open_request(connection, L"GET", L"/w", nullptr, WINHTTP_NO_REFERER,
266 WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
267 send(request, nullptr, 0, nullptr, 0, 0, 0);
268 close(request);
269 close(connection);
270 close(session);
271 for (int i = 0; i < 100 && seen.closing.load() < 3; ++i) Sleep(10);
272 check(seen.request_errors.load() == 0 && seen.closing.load() == 3,
273 "notifications not asked for are not sent, and each handle still closes once");
274 }
275 g_seen = nullptr;
276 CloseHandle(seen.error_event);
277 CloseHandle(seen.closing_event);
278
279 // WinHttpCrackUrl is parsing only and stays the host's.
280 {
281 wchar_t host[64] = {}, path[64] = {};
282 URL_COMPONENTS parts{};
283 parts.dwStructSize = sizeof(parts);
284 parts.lpszHostName = host;
285 parts.dwHostNameLength = 64;
286 parts.lpszUrlPath = path;
287 parts.dwUrlPathLength = 64;
288 check(crack(L"https://example.invalid:8443/a/b", 0, 0, &parts) != FALSE && parts.nPort == 8443 &&
289 parts.nScheme == INTERNET_SCHEME_HTTPS && std::wcscmp(host, L"example.invalid") == 0 &&
290 std::wcscmp(path, L"/a/b") == 0,
291 "WinHttpCrackUrl parses a URL");
292 }
293
294 std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures);
295 return g_failures == 0 ? 0 : 1;
296}
diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp
index 2e3afcaea..6d8860c99 100644
--- a/runtime/test/xbox_present_test.cpp
+++ b/runtime/test/xbox_present_test.cpp
@@ -3,8 +3,11 @@
3// fake clock, so the test is fast and the order of tokens and presents is exact. 3// fake clock, so the test is fast and the order of tokens and presents is exact.
4// 4//
5// Cases: 0 planes (blank), 1 plane (solid colour, two colours side by side, a source rectangle, an RGBA and a BGRA 5// Cases: 0 planes (blank), 1 plane (solid colour, two colours side by side, a source rectangle, an RGBA and a BGRA
6// source, an sRGB source), 2 planes (plane 0 shown), token errors (null, unknown, stale, repeated), suspend/resume 6// source, an sRGB source), 2 planes (SDR overlay), plane composition (placement, point/bilinear, premultiplied and
7// with re-registration, statistics, and a real-time loop at 60 Hz. Needs a window and a Vulkan GPU with presentation. 7// straight alpha, HDR10 and PQ conversions, refusals) against a CPU model with the tolerances stated at each case, token
8// errors (null, unknown, stale, repeated), suspend/resume with re-registration, statistics, and a real-time loop at
9// 60 Hz. An HDR10 swapchain is only checked where the surface lists an ST.2084 format (else logged as skipped).
10// Needs a window and a Vulkan GPU with presentation.
8// Set LEONIDA_VK_VALIDATION=1 for VK_LAYER_KHRONOS_validation; any validation error fails the test, except that 11// Set LEONIDA_VK_VALIDATION=1 for VK_LAYER_KHRONOS_validation; any validation error fails the test, except that
9// the NVIDIA layer's known sRGB-swapchain STORAGE check makes the run skip rather than pass or fail. 12// the NVIDIA layer's known sRGB-swapchain STORAGE check makes the run skip rather than pass or fail.
10#include "vk_test_device.h" 13#include "vk_test_device.h"
@@ -12,10 +15,15 @@
12#include "../shims/d3d12_xs_device.h" 15#include "../shims/d3d12_xs_device.h"
13#include "../shims/xbox_present.h" 16#include "../shims/xbox_present.h"
14 17
18#include <algorithm>
15#include <chrono> 19#include <chrono>
16#include <cmath> 20#include <cmath>
21#include <cstring>
22#include <limits>
17#include <cstdint> 23#include <cstdint>
18#include <cstdlib> 24#include <cstdlib>
25#include <array>
26#include <vector>
19 27
20#define EXPECT(condition) do { \ 28#define EXPECT(condition) do { \
21 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ 29 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
@@ -85,6 +93,126 @@ bool region_is(const Frame& frame, UINT x0, UINT y0, UINT x1, UINT y1, Px want,
85 return true; 93 return true;
86} 94}
87 95
96// A CPU model of runtime/src/present_compose.comp, in double precision, written from the documented behaviour
97// (docs/d3d12_vulkan.md section 4.5), not from the shader's code: planes scaled from a source rectangle to a
98// destination rectangle (point: the texel containing the sample; bilinear: four texels clamped inside the source
99// rectangle), SDR = G2.2 Rec.709, HDR10 = PQ Rec.2020, conversions through linear light and `white` nits, plane 1 blended
100// over plane 0 in the output's encoded space, premultiplied or straight.
101namespace xbox_present_ref {
102
103struct Tex {
104 UINT w = 0, h = 0;
105 std::vector<std::array<double, 4>> px; // 0..1, as stored
106};
107struct Ref_plane {
108 const Tex* tex = nullptr;
109 double src[4]{}, dest[4]{}; // texels; output pixels
110 bool point = false, hdr = false, straight = false;
111};
112using V3 = std::array<double, 3>;
113
114double pq_encode(double nits) {
115 const double m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875;
116 const double y = std::pow(std::clamp(nits / 10000.0, 0.0, 1.0), m1);
117 return std::pow((c1 + c2 * y) / (1.0 + c3 * y), m2);
118}
119double pq_decode(double e) {
120 const double m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875;
121 const double ep = std::pow(std::clamp(e, 0.0, 1.0), 1.0 / m2);
122 return 10000.0 * std::pow(std::max(ep - c1, 0.0) / (c2 - c3 * ep), 1.0 / m1);
123}
124V3 convert(V3 c, bool plane_hdr, bool out_hdr, double white) {
125 if (plane_hdr == out_hdr) return c;
126 if (!plane_hdr) { // SDR -> PQ
127 const double r = std::pow(std::clamp(c[0], 0.0, 1.0), 2.2), g = std::pow(std::clamp(c[1], 0.0, 1.0), 2.2),
128 b = std::pow(std::clamp(c[2], 0.0, 1.0), 2.2);
129 return {pq_encode((0.627404 * r + 0.329283 * g + 0.043313 * b) * white),
130 pq_encode((0.069097 * r + 0.919540 * g + 0.011362 * b) * white),
131 pq_encode((0.016391 * r + 0.088013 * g + 0.895595 * b) * white)};
132 }
133 const double r = pq_decode(c[0]), g = pq_decode(c[1]), b = pq_decode(c[2]);
134 const auto sdr = [&](double v) { return std::pow(std::clamp(v / white, 0.0, 1.0), 1.0 / 2.2); };
135 return {sdr(1.660491 * r - 0.587641 * g - 0.072850 * b), sdr(-0.124550 * r + 1.132900 * g - 0.008349 * b),
136 sdr(-0.018151 * r - 0.100579 * g + 1.118730 * b)};
137}
138std::array<double, 4> sample(const Ref_plane& p, int x, int y) {
139 const Tex& t = *p.tex;
140 const double u = (x + 0.5 - p.dest[0]) / (p.dest[2] - p.dest[0]), v = (y + 0.5 - p.dest[1]) / (p.dest[3] - p.dest[1]);
141 const double sx = p.src[0] + u * (p.src[2] - p.src[0]), sy = p.src[1] + v * (p.src[3] - p.src[1]);
142 const auto at = [&](int ix, int iy) { return t.px[std::size_t(iy) * t.w + ix]; };
143 if (p.point)
144 return at(int(std::clamp(std::floor(sx), p.src[0], p.src[2] - 1)), int(std::clamp(std::floor(sy), p.src[1], p.src[3] - 1)));
145 const double fx = std::clamp(sx - 0.5, p.src[0], p.src[2] - 1), fy = std::clamp(sy - 0.5, p.src[1], p.src[3] - 1);
146 const int x0 = int(std::floor(fx)), y0 = int(std::floor(fy));
147 const int x1 = int(std::min(double(x0) + 1, p.src[2] - 1)), y1 = int(std::min(double(y0) + 1, p.src[3] - 1));
148 const double wx = fx - x0, wy = fy - y0;
149 // Four texels with their bilinear weights. Straight-alpha colour is weighted by its alpha (filtering associated colour),
150 // then divided by the filtered alpha: a transparent texel contributes no colour of its own.
151 const double weight[4] = {(1 - wx) * (1 - wy), wx * (1 - wy), (1 - wx) * wy, wx * wy};
152 const std::array<double, 4> texel[4] = {at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1)};
153 std::array<double, 4> out{};
154 for (int i = 0; i < 4; ++i) {
155 const double colour_weight = p.straight ? weight[i] * texel[i][3] : weight[i];
156 for (int c = 0; c < 3; ++c) out[c] += texel[i][c] * colour_weight;
157 out[3] += texel[i][3] * weight[i];
158 }
159 if (p.straight)
160 for (int c = 0; c < 3; ++c) out[c] = out[3] > 0.0 ? out[c] / out[3] : 0.0;
161 return out;
162}
163V3 compose(const Ref_plane* planes, int count, bool out_hdr, double white, int x, int y) {
164 const auto inside = [&](const Ref_plane& p) {
165 return x + 0.5 >= p.dest[0] && x + 0.5 < p.dest[2] && y + 0.5 >= p.dest[1] && y + 0.5 < p.dest[3];
166 };
167 V3 base{0, 0, 0};
168 if (inside(planes[0])) {
169 const auto c = sample(planes[0], x, y);
170 base = convert({c[0], c[1], c[2]}, planes[0].hdr, out_hdr, white);
171 }
172 if (count > 1 && inside(planes[1])) {
173 const Ref_plane& p = planes[1];
174 const auto c = sample(p, x, y);
175 const double a = std::clamp(c[3], 0.0, 1.0);
176 V3 over{c[0], c[1], c[2]};
177 if (p.hdr != out_hdr) { // converted as unassociated colour, premultiplied again afterwards
178 if (!p.straight && a > 0.0) over = {c[0] / a, c[1] / a, c[2] / a};
179 over = convert(over, p.hdr, out_hdr, white);
180 if (!p.straight) over = {over[0] * a, over[1] * a, over[2] * a};
181 }
182 for (int i = 0; i < 3; ++i) base[i] = p.straight ? base[i] * (1 - a) + over[i] * a : over[i] + (1 - a) * base[i];
183 }
184 return base;
185}
186
187// The whole swapchain frame against the model; prints the first pixel that is off by more than `tolerance` levels.
188bool frame_matches(const Frame& frame, const Ref_plane* planes, int count, bool out_hdr, double white, int tolerance) {
189 int worst = 0;
190 UINT bad = 0, first_x = 0, first_y = 0;
191 Px first_got{}, first_want{};
192 for (UINT y = 0; y < frame.extent.height; ++y)
193 for (UINT x = 0; x < frame.extent.width; ++x) {
194 const V3 v = compose(planes, count, out_hdr, white, int(x), int(y));
195 const Px want{int(std::lround(std::clamp(v[0], 0.0, 1.0) * 255)), int(std::lround(std::clamp(v[1], 0.0, 1.0) * 255)),
196 int(std::lround(std::clamp(v[2], 0.0, 1.0) * 255))};
197 const Px got = frame.at(x, y);
198 const int err = std::max({std::abs(got.r - want.r), std::abs(got.g - want.g), std::abs(got.b - want.b)});
199 worst = std::max(worst, err);
200 if (err > tolerance && bad++ == 0) {
201 first_x = x;
202 first_y = y;
203 first_got = got;
204 first_want = want;
205 }
206 }
207 if (bad)
208 std::fprintf(stderr, "%u pixels differ from the model by more than %d (worst %d); first at %u,%u is %d,%d,%d, model %d,%d,%d\n", bad,
209 tolerance, worst, first_x, first_y, first_got.r, first_got.g, first_got.b, first_want.r, first_want.g,
210 first_want.b);
211 return bad == 0;
212}
213
214} // namespace xbox_present_ref
215
88} // namespace 216} // namespace
89 217
90int main() { 218int main() {
@@ -123,6 +251,33 @@ int main() {
123 pump(); 251 pump();
124 252
125 { 253 {
254 // The real runtime's instance path (create_vulkan_device_standalone, not the test device): it must enable
255 // VK_EXT_swapchain_colorspace when the loader has it, or the HDR10 surface formats can never be listed.
256 Ref<ID3D12Device> standalone;
257 if (SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&standalone.p)))) {
258 const auto enumerate = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>(
259 d.instance_proc(nullptr, "vkEnumerateInstanceExtensionProperties"));
260 std::uint32_t count = 0;
261 enumerate(nullptr, &count, nullptr);
262 std::vector<VkExtensionProperties> available(count);
263 enumerate(nullptr, &count, available.data());
264 bool loader_has = false;
265 for (const auto& e : available) loader_has = loader_has || !std::strcmp(e.extensionName, "VK_EXT_swapchain_colorspace");
266 auto standalone_presenter = rt::d3d12::create_window_presenter(standalone.p, window);
267 if (standalone_presenter) {
268 EXPECT(rt::d3d12::device_has_swapchain_colorspace(standalone.p) == loader_has);
269 EXPECT(standalone_presenter->enable_capture());
270 EXPECT(SUCCEEDED(standalone_presenter->present_blank(1)));
271 std::printf("standalone device (real instance path): VK_EXT_swapchain_colorspace %s on the instance (loader has it: %s)\n",
272 rt::d3d12::device_has_swapchain_colorspace(standalone.p) ? "enabled" : "not enabled",
273 loader_has ? "yes" : "no");
274 } else {
275 std::printf("standalone device: no window presenter (skipped the instance-extension check)\n");
276 }
277 }
278 }
279
280 {
126 rt::d3d12::VulkanDeviceInfo info{}; 281 rt::d3d12::VulkanDeviceInfo info{};
127 info.get_instance_proc = d.instance_proc; 282 info.get_instance_proc = d.instance_proc;
128 info.instance = d.instance; 283 info.instance = d.instance;
@@ -158,7 +313,7 @@ int main() {
158 IID_PPV_ARGS(&list.p)))); 313 IID_PPV_ARGS(&list.p))));
159 EXPECT(SUCCEEDED(list->Close())); 314 EXPECT(SUCCEEDED(list->Close()));
160 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); 315 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
161 constexpr UINT rtv_slots = 8; 316 constexpr UINT rtv_slots = 24;
162 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, rtv_slots, 317 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, rtv_slots,
163 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; 318 D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0};
164 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); 319 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p))));
@@ -172,12 +327,12 @@ int main() {
172 Ref<ID3D12Resource> resource; 327 Ref<ID3D12Resource> resource;
173 D3D12_CPU_DESCRIPTOR_HANDLE rtv{}; 328 D3D12_CPU_DESCRIPTOR_HANDLE rtv{};
174 }; 329 };
175 const auto make_source = [&](DXGI_FORMAT format, Source& out) -> bool { 330 const auto make_source = [&](DXGI_FORMAT format, Source& out, UINT w = width, UINT h = height) -> bool {
176 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; 331 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
177 D3D12_RESOURCE_DESC desc{}; 332 D3D12_RESOURCE_DESC desc{};
178 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; 333 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
179 desc.Width = width; 334 desc.Width = w;
180 desc.Height = height; 335 desc.Height = h;
181 desc.DepthOrArraySize = 1; 336 desc.DepthOrArraySize = 1;
182 desc.MipLevels = 1; 337 desc.MipLevels = 1;
183 desc.Format = format; 338 desc.Format = format;
@@ -223,9 +378,10 @@ int main() {
223 clock.advance_us(period); 378 clock.advance_us(period);
224 return xbox.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0, &token) == S_OK; 379 return xbox.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0, &token) == S_OK;
225 }; 380 };
381 UINT want_w = width, want_h = height; // the client size the frames are expected at (the resize case changes it)
226 const auto grab = [&](Frame& frame) -> bool { 382 const auto grab = [&](Frame& frame) -> bool {
227 return xbox.presenter().read_back(frame.bytes, &frame.extent, &frame.format) && 383 return xbox.presenter().read_back(frame.bytes, &frame.extent, &frame.format) &&
228 frame.extent.width == width && frame.extent.height == height; 384 (want_w == 0 || (frame.extent.width == want_w && frame.extent.height == want_h));
229 }; 385 };
230 386
231 const FLOAT blue_ish[4] = {0.2f, 0.6f, 0.9f, 1.0f}; // 51, 153, 230 387 const FLOAT blue_ish[4] = {0.2f, 0.6f, 0.9f, 1.0f}; // 51, 153, 230
@@ -331,15 +487,18 @@ int main() {
331 EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); 487 EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230}));
332 std::printf("1 plane, sRGB source (swapchain follows): ok\n"); 488 std::printf("1 plane, sRGB source (swapchain follows): ok\n");
333 489
334 // 2 planes sharing a token: plane 0 is shown. 490 // 2 planes sharing a token, both SDR: plane 1 is an overlay (section 4.5), and an opaque one covers plane 0.
491 // (The plane composition has its own checks further down.)
335 Source second; 492 Source second;
336 EXPECT(make_source(DXGI_FORMAT_R8G8B8A8_UNORM, second)); 493 EXPECT(make_source(DXGI_FORMAT_R8G8B8A8_UNORM, second));
337 EXPECT(fill(second, green)); 494 EXPECT(fill(second, green));
338 EXPECT(next_token(token)); 495 EXPECT(next_token(token));
339 rt::d3d12::XboxPresentPlaneParameters two[2] = {plane_of(rgba, token), plane_of(second, token)}; 496 rt::d3d12::XboxPresentPlaneParameters two[2] = {plane_of(rgba, token), plane_of(second, token)};
497 const std::uint64_t composed_before = xbox.presenter().composed_presents();
340 EXPECT(xbox.PresentX(2, two, nullptr) == S_OK); 498 EXPECT(xbox.PresentX(2, two, nullptr) == S_OK);
499 EXPECT(xbox.presenter().composed_presents() == composed_before); // plane 1 without the overlay flag: not composed
341 EXPECT(grab(frame)); 500 EXPECT(grab(frame));
342 EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); 501 EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); // plane 0 only, by the plain blit
343 // Planes with different tokens, or more than two planes, are refused. 502 // Planes with different tokens, or more than two planes, are refused.
344 EXPECT(next_token(token)); 503 EXPECT(next_token(token));
345 two[0] = plane_of(rgba, token); 504 two[0] = plane_of(rgba, token);
@@ -348,7 +507,25 @@ int main() {
348 rt::d3d12::XboxPresentPlaneParameters three[3] = {plane_of(rgba, token), plane_of(second, token), plane_of(second, token)}; 507 rt::d3d12::XboxPresentPlaneParameters three[3] = {plane_of(rgba, token), plane_of(second, token), plane_of(second, token)};
349 EXPECT(xbox.PresentX(3, three, nullptr) == E_INVALIDARG); 508 EXPECT(xbox.PresentX(3, three, nullptr) == E_INVALIDARG);
350 EXPECT(xbox.PresentX(1, nullptr, nullptr) == E_INVALIDARG); 509 EXPECT(xbox.PresentX(1, nullptr, nullptr) == E_INVALIDARG);
351 std::printf("2 planes (plane 0 shown) and refused plane sets: ok\n"); 510 { // ResourceCount above 1 (either plane, either path) is refused, nothing presented, the frame stays
511 ID3D12Resource* both[2] = {rgba.resource.p, second.resource.p};
512 const std::uint64_t presents_before_count = xbox.presents();
513 const auto count_two = [&](int color_space, UINT flags) {
514 rt::d3d12::XboxPresentPlaneParameters p{token, 2, both, nullptr, 0};
515 p.ColorSpace = color_space;
516 p.Flags = flags;
517 return p;
518 };
519 auto one_count = count_two(0, 0);
520 EXPECT(xbox.PresentX(1, &one_count, nullptr) == DXGI_ERROR_UNSUPPORTED); // plain blit path
521 one_count = count_two(rt::d3d12::xbox_color_space_g2084_p2020, 0);
522 EXPECT(xbox.PresentX(1, &one_count, nullptr) == DXGI_ERROR_UNSUPPORTED); // compose path
523 rt::d3d12::XboxPresentPlaneParameters pair_count[2] = {plane_of(rgba, token), count_two(0, rt::d3d12::xbox_plane_flag_overlay)};
524 EXPECT(xbox.PresentX(2, pair_count, nullptr) == DXGI_ERROR_UNSUPPORTED); // plane 1
525 EXPECT(xbox.presents() == presents_before_count);
526 std::printf("ResourceCount above 1 refused (plain, compose, plane 1): ok\n");
527 }
528 std::printf("2 planes (SDR overlay over plane 0) and refused plane sets: ok\n");
352 529
353 // The parameters struct is accepted (ImmediateThresholdPercent is ignored). 530 // The parameters struct is accepted (ImmediateThresholdPercent is ignored).
354 const rt::d3d12::XboxPresentParameters params{50.0f}; 531 const rt::d3d12::XboxPresentParameters params{50.0f};
@@ -421,6 +598,330 @@ int main() {
421 std::printf("unsupported sources (MSAA, integer, BC) refused: ok\n"); 598 std::printf("unsupported sources (MSAA, integer, BC) refused: ok\n");
422 } 599 }
423 600
601 // ---- Plane composition (docs section 4.5), against a CPU model of the compose pass (xbox_present_ref below). ----
602 // Exact (tolerance 0) for point filtering between SDR planes without alpha; 1 level for bilinear filtering and
603 // alpha blending (the pass works in float, stores RGBA16F and the copy rounds to 8 bits); 2 levels where PQ and
604 // gamma conversions are involved (GPU pow is not correctly rounded).
605 {
606 using namespace xbox_present_ref;
607 using rt::d3d12::XboxViewRect;
608 struct Painted {
609 Source source;
610 Tex tex;
611 };
612 const auto make_painted = [&](Painted& p, UINT w, UINT h, DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM) {
613 p.tex = Tex{w, h, std::vector<std::array<double, 4>>(std::size_t(w) * h, {0, 0, 0, 0})};
614 const FLOAT zero[4] = {0, 0, 0, 0};
615 return make_source(format, p.source, w, h) && fill(p.source, zero);
616 };
617 // Paints a rectangle with 8-bit values (R8G8B8A8) in the texture and in the model.
618 const auto paint = [&](Painted& p, D3D12_RECT r, int R, int G, int B, int A) {
619 const FLOAT c[4] = {R / 255.0f, G / 255.0f, B / 255.0f, A / 255.0f};
620 if (!fill(p.source, c, 1, &r)) return false;
621 for (LONG y = r.top; y < r.bottom; ++y)
622 for (LONG x = r.left; x < r.right; ++x)
623 p.tex.px[std::size_t(y) * p.tex.w + x] = {R / 255.0, G / 255.0, B / 255.0, A / 255.0};
624 return true;
625 };
626 // The same for R10G10B10A2 (10-bit codes; alpha 2 bits): the model keeps the quantised value.
627 const auto paint10 = [&](Painted& p, D3D12_RECT r, int R, int G, int B) {
628 const FLOAT c[4] = {R / 1023.0f, G / 1023.0f, B / 1023.0f, 1.0f};
629 if (!fill(p.source, c, 1, &r)) return false;
630 for (LONG y = r.top; y < r.bottom; ++y)
631 for (LONG x = r.left; x < r.right; ++x)
632 p.tex.px[std::size_t(y) * p.tex.w + x] = {R / 1023.0, G / 1023.0, B / 1023.0, 1.0};
633 return true;
634 };
635 // One PresentX of `count` planes, a fresh token for all; the swapchain frame is read back into `frame`.
636 const auto present_planes = [&](rt::d3d12::XboxPresentPlaneParameters* planes_, UINT count_, HRESULT want = S_OK) {
637 clock.advance_us(4 * period);
638 if (!next_token(token)) return false;
639 for (UINT i = 0; i < count_; ++i) planes_[i].Token = token;
640 if (xbox.PresentX(count_, planes_, nullptr) != want) return false;
641 return want != S_OK || grab(frame);
642 };
643 const auto parameters = [&](Source& s, const XboxViewRect* place, int filter, int color_space = 0,
644 UINT flags = 0, const D3D12_RECT* rect = nullptr) {
645 rt::d3d12::XboxPresentPlaneParameters p = plane_of(s, 0, rect);
646 p.ColorSpace = color_space;
647 p.pDestPlacementBase = place;
648 p.ScaleFilter = filter;
649 p.Flags = flags;
650 return p;
651 };
652 const auto model = [&](const Painted& p, const XboxViewRect* place, bool point, const D3D12_RECT* rect = nullptr,
653 bool hdr = false, bool straight = false) {
654 Ref_plane r;
655 r.tex = &p.tex;
656 r.src[0] = rect ? rect->left : 0;
657 r.src[1] = rect ? rect->top : 0;
658 r.src[2] = rect ? rect->right : double(p.tex.w);
659 r.src[3] = rect ? rect->bottom : double(p.tex.h);
660 const XboxViewRect whole{0, 0, 1, 1};
661 const XboxViewRect& v = place ? *place : whole;
662 r.dest[0] = v.left * width;
663 r.dest[1] = v.top * height;
664 r.dest[2] = v.right * width;
665 r.dest[3] = v.bottom * height;
666 r.point = point;
667 r.hdr = hdr;
668 r.straight = straight;
669 return r;
670 };
671 using rt::d3d12::xbox_scale_filter_linear;
672 using rt::d3d12::xbox_scale_filter_point;
673 const std::uint64_t composed_start = xbox.presenter().composed_presents();
674 std::uint64_t composed_expected = composed_start;
675 const auto composed_ok = [&] { return xbox.presenter().composed_presents() == ++composed_expected; };
676
677 // A: one plane, scaled 2x to the middle of the output, point and linear; the rest of the output is black.
678 Painted quad;
679 EXPECT(make_painted(quad, 80, 60));
680 EXPECT(paint(quad, {0, 0, 40, 30}, 255, 0, 0, 255) && paint(quad, {40, 0, 80, 30}, 0, 255, 0, 255));
681 EXPECT(paint(quad, {0, 30, 40, 60}, 0, 0, 255, 255) && paint(quad, {40, 30, 80, 60}, 255, 255, 255, 255));
682 const XboxViewRect middle_half{0.25f, 0.25f, 0.75f, 0.75f};
683 auto one = parameters(quad.source, &middle_half, xbox_scale_filter_point);
684 EXPECT(present_planes(&one, 1) && composed_ok());
685 EXPECT(frame.format == VK_FORMAT_B8G8R8A8_UNORM || frame.format == VK_FORMAT_R8G8B8A8_UNORM);
686 Ref_plane ref0 = model(quad, &middle_half, true);
687 EXPECT(frame_matches(frame, &ref0, 1, false, 203.0, 0));
688 std::printf("compose: 1 plane, 80x60 -> dest placement 160x120, point: exact\n");
689 one = parameters(quad.source, &middle_half, xbox_scale_filter_linear);
690 EXPECT(present_planes(&one, 1) && composed_ok());
691 ref0 = model(quad, &middle_half, false);
692 EXPECT(frame_matches(frame, &ref0, 1, false, 203.0, 1));
693 std::printf("compose: same, bilinear: within 1 level of the model\n");
694 // A source rectangle (the right half) onto the whole output, point: no placement.
695 const D3D12_RECT right_half_of_quad{40, 0, 80, 60};
696 one = parameters(quad.source, nullptr, xbox_scale_filter_point, 0, 0, &right_half_of_quad);
697 EXPECT(present_planes(&one, 1) && composed_ok());
698 ref0 = model(quad, nullptr, true, &right_half_of_quad);
699 EXPECT(frame_matches(frame, &ref0, 1, false, 203.0, 0));
700 // Bilinear with a source rectangle must not read outside it: the right half shows only green over white.
701 one = parameters(quad.source, nullptr, xbox_scale_filter_linear, 0, 0, &right_half_of_quad);
702 EXPECT(present_planes(&one, 1) && composed_ok());
703 ref0 = model(quad, nullptr, false, &right_half_of_quad);
704 EXPECT(frame_matches(frame, &ref0, 1, false, 203.0, 1));
705 std::printf("compose: source rectangle, point and bilinear (clamped inside it): ok\n");
706
707 // The compose pass with point filtering at 1:1 gives the very bytes of the plain blit.
708 plane = plane_of(split, 0);
709 clock.advance_us(4 * period);
710 EXPECT(next_token(token));
711 plane.Token = token;
712 const std::uint64_t blits = xbox.presenter().composed_presents();
713 EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK && xbox.presenter().composed_presents() == blits);
714 Frame blit_frame;
715 EXPECT(grab(blit_frame));
716 one = parameters(split, nullptr, xbox_scale_filter_point);
717 EXPECT(present_planes(&one, 1) && composed_ok());
718 EXPECT(frame.bytes == blit_frame.bytes);
719 std::printf("compose at 1:1 equals the plain blit byte for byte: ok\n");
720
721 // An sRGB source (0.5 linear is byte 188): the pass encodes it again, so the bytes come out as stored.
722 one = parameters(srgb, nullptr, xbox_scale_filter_point);
723 EXPECT(present_planes(&one, 1) && composed_ok());
724 EXPECT(!frame.srgb());
725 EXPECT(region_is(frame, 0, 0, width, height, {188, 188, 188}, 1));
726 std::printf("compose: sRGB source, UNORM swapchain: ok\n");
727
728 // B: plane 1 over plane 0. Plane 0 is a solid; plane 1 (80x60, scaled 2x into the middle) has a half
729 // transparent red (premultiplied: 128,0,0 alpha 128), nothing, opaque green and 25% blue (0,0,64, alpha 64).
730 Painted solid;
731 EXPECT(make_painted(solid, width, height));
732 EXPECT(paint(solid, {0, 0, LONG(width), LONG(height)}, 51, 153, 230, 255));
733 Painted ui;
734 EXPECT(make_painted(ui, 80, 60));
735 EXPECT(paint(ui, {0, 0, 40, 30}, 128, 0, 0, 128) && paint(ui, {0, 30, 40, 60}, 0, 255, 0, 255));
736 EXPECT(paint(ui, {40, 30, 80, 60}, 0, 0, 64, 64));
737 rt::d3d12::XboxPresentPlaneParameters pair[2];
738 pair[0] = parameters(solid.source, nullptr, xbox_scale_filter_point);
739 pair[1] = parameters(ui.source, &middle_half, xbox_scale_filter_point, 0, rt::d3d12::xbox_plane_flag_overlay);
740 EXPECT(present_planes(pair, 2) && composed_ok());
741 Ref_plane refs[2] = {model(solid, nullptr, true), model(ui, &middle_half, true)};
742 EXPECT(frame_matches(frame, refs, 2, false, 203.0, 1));
743 std::printf("compose: 2 planes, premultiplied alpha overlay, point: within 1 level of the model\n");
744 pair[1] = parameters(ui.source, &middle_half, xbox_scale_filter_point, 0, rt::d3d12::xbox_plane_flag_overlay | rt::d3d12::xbox_plane_flag_straight_alpha);
745 EXPECT(present_planes(pair, 2) && composed_ok());
746 refs[1] = model(ui, &middle_half, true, nullptr, false, true);
747 EXPECT(frame_matches(frame, refs, 2, false, 203.0, 1));
748 std::printf("compose: 2 planes, straight alpha overlay: within 1 level of the model\n");
749 pair[1] = parameters(ui.source, &middle_half, xbox_scale_filter_linear, 0, rt::d3d12::xbox_plane_flag_overlay);
750 EXPECT(present_planes(pair, 2) && composed_ok());
751 refs[1] = model(ui, &middle_half, false);
752 EXPECT(frame_matches(frame, refs, 2, false, 203.0, 1));
753 std::printf("compose: 2 planes, bilinear overlay: within 1 level of the model\n");
754 // Straight alpha with bilinear filtering across a transparent edge: opaque white on the left, transparent black on the
755 // right. Colour is filtered premultiplied, so the edge is white at partial alpha, not grey (filtering the
756 // unassociated colour would also quarter the colour and quarter it again by the alpha). At output x=160 the sample
757 // is 0.75 of the way from the white texel to the transparent one: alpha 0.25, colour white:
758 // base 51 + 0.25 * (255 - 51) = 102.
759 Painted edge;
760 EXPECT(make_painted(edge, 80, 60));
761 EXPECT(paint(edge, {0, 0, 40, 60}, 255, 255, 255, 255) && paint(edge, {40, 0, 80, 60}, 0, 0, 0, 0));
762 pair[1] = parameters(edge.source, &middle_half, xbox_scale_filter_linear, 0,
763 rt::d3d12::xbox_plane_flag_overlay | rt::d3d12::xbox_plane_flag_straight_alpha);
764 EXPECT(present_planes(pair, 2) && composed_ok());
765 refs[1] = model(edge, &middle_half, false, nullptr, false, true);
766 EXPECT(frame_matches(frame, refs, 2, false, 203.0, 1));
767 {
768 const Px edge_px = frame.at(160, 120);
769 // red: 51 + 0.25 * 204 = 102 (blue: 230 + 0.25 * 25 = 236); the unfiltered-colour result would be near 54
770 EXPECT(std::abs(edge_px.r - 102) <= 1 && std::abs(edge_px.b - 236) <= 1);
771 }
772 std::printf("compose: straight alpha, bilinear across a transparent edge (premultiplied filtering): ok\n");
773
774 // C: HDR10 (PQ, Rec.2020) planes. Plane 0 is 80x60 R10G10B10A2 (three bands: SDR white level, a bright
775 // colour above it, and a dim colour), shown 4x on the whole output.
776 Painted hdr;
777 EXPECT(make_painted(hdr, 80, 60, DXGI_FORMAT_R10G10B10A2_UNORM));
778 const auto code = [](double nits) { return int(std::lround(pq_encode(nits) * 1023.0)); };
779 EXPECT(paint10(hdr, {0, 0, 27, 60}, code(203), code(203), code(203)));
780 EXPECT(paint10(hdr, {27, 0, 54, 60}, code(600), code(150), code(20)));
781 EXPECT(paint10(hdr, {54, 0, 80, 60}, code(40), code(80), code(120)));
782 one = parameters(hdr.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020);
783 EXPECT(present_planes(&one, 1) && composed_ok());
784 Ref_plane href = model(hdr, nullptr, true, nullptr, true);
785 const bool surface_hdr = xbox.presenter().hdr_active();
786 if (!surface_hdr) {
787 EXPECT(frame_matches(frame, &href, 1, false, 203.0, 2));
788 std::printf("compose: HDR10 plane to an SDR swapchain (clipped to SDR, white = 203 nits): within 2 levels of the model\n");
789 } else {
790 // A real HDR10 swapchain: the 10-bit codes come out as they went in (plane 0, point, 1:1 PQ).
791 EXPECT(frame.format == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || frame.format == VK_FORMAT_A2R10G10B10_UNORM_PACK32);
792 bool ok = true;
793 for (UINT y = 0; y < height && ok; y += 7)
794 for (UINT x = 0; x < width && ok; x += 5) {
795 std::uint32_t word;
796 std::memcpy(&word, &frame.bytes[(std::size_t(y) * frame.extent.width + x) * 4], 4);
797 const bool abgr = frame.format == VK_FORMAT_A2B10G10R10_UNORM_PACK32;
798 const int r = int(abgr ? (word & 1023) : ((word >> 20) & 1023));
799 const auto want = hdr.tex.px[std::size_t(y / 4) * 80 + x / 4];
800 ok = std::abs(r - int(std::lround(want[0] * 1023.0))) <= 1;
801 }
802 EXPECT(ok);
803 std::printf("compose: HDR10 plane to an HDR10 (ST.2084) swapchain: codes within 1 of the source: ok\n");
804 }
805 // Same plane, conversions to the PQ encoding of an 8-bit swapchain (test hook): an SDR overlay over it.
806 xbox.presenter().force_hdr_encoding(true);
807 pair[0] = parameters(hdr.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020);
808 pair[1] = parameters(ui.source, &middle_half, xbox_scale_filter_point, 0, rt::d3d12::xbox_plane_flag_overlay);
809 EXPECT(present_planes(pair, 2) && composed_ok());
810 Ref_plane hrefs[2] = {model(hdr, nullptr, true, nullptr, true), model(ui, &middle_half, true)};
811 if (!surface_hdr) {
812 EXPECT(frame_matches(frame, hrefs, 2, true, 203.0, 2));
813 std::printf("compose: HDR10 plane + SDR overlay in PQ encoding (8-bit, forced): within 2 levels of the model\n");
814 }
815 // SDR planes into PQ: the SDR white of the quad's white corner goes to 203 nits.
816 pair[0] = parameters(quad.source, nullptr, xbox_scale_filter_point);
817 pair[1] = parameters(ui.source, &middle_half, xbox_scale_filter_point, 0, rt::d3d12::xbox_plane_flag_overlay);
818 EXPECT(present_planes(pair, 2) && composed_ok());
819 Ref_plane srefs[2] = {model(quad, nullptr, true), model(ui, &middle_half, true)};
820 if (!surface_hdr) {
821 EXPECT(frame_matches(frame, srefs, 2, true, 203.0, 2));
822 std::printf("compose: SDR planes converted to PQ (forced): within 2 levels of the model\n");
823 }
824 xbox.presenter().force_hdr_encoding(false);
825 // The HDR plane reaches the SDR swapchain again after an HDR request on a surface that has none.
826 if (!surface_hdr) {
827 xbox.set_sdr_white_nits(100.0f);
828 one = parameters(hdr.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020);
829 EXPECT(present_planes(&one, 1) && composed_ok());
830 EXPECT(frame_matches(frame, &href, 1, false, 100.0, 2));
831 xbox.set_sdr_white_nits(203.0f);
832 std::printf("compose: SDR white level 100 nits applies: ok\n");
833 } else {
834 std::printf("compose: the surface has HDR10: the forced-encoding checks are skipped on it\n");
835 }
836 if (!surface_hdr)
837 std::printf("compose: HDR10 swapchain: this surface/display lists no ST.2084 format, so only the SDR clip and "
838 "the PQ encoder were run (HDR10 swapchain case skipped)\n");
839
840 // D: an SDR plane 1 next to an HDR10 plane 0 that is not flagged an overlay is the GameDVR copy: not shown.
841 pair[0] = parameters(hdr.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020);
842 pair[1] = parameters(second, nullptr, xbox_scale_filter_point, 0);
843 EXPECT(present_planes(pair, 2) && composed_ok());
844 if (!surface_hdr) EXPECT(frame_matches(frame, &href, 1, false, 203.0, 2));
845 std::printf("compose: HDR10 plane 0 + unflagged SDR plane 1 (GameDVR copy) shows plane 0 only: ok\n");
846
847 // E: a placement that is not a sub-rectangle of the output (empty, inverted, outside, NaN), an unknown filter and
848 // extended descriptors are ignored (logged once): the plane is shown over the whole output, point filtered.
849 const float nan = std::numeric_limits<float>::quiet_NaN();
850 const XboxViewRect bad_places[] = {{0.5f, 0, 0.5f, 1}, {-0.1f, 0, 1, 1}, {0, 0, 1.5f, 1}, {0, 0.75f, 1, 0.25f}, {nan, 0, 1, 1}};
851 for (const XboxViewRect& bad : bad_places) {
852 one = parameters(quad.source, &bad, xbox_scale_filter_point);
853 EXPECT(present_planes(&one, 1) && composed_ok());
854 Ref_plane whole = model(quad, nullptr, true);
855 EXPECT(frame_matches(frame, &whole, 1, false, 203.0, 0));
856 }
857 one = parameters(quad.source, nullptr, 77); // unknown filter: default (bilinear), plain blit path
858 one.ExtendedDescCount = 2;
859 EXPECT(present_planes(&one, 1));
860 std::printf("compose: implausible placement, unknown filter, extended descriptors ignored (shown, not refused): ok\n");
861 // Sources the pass cannot read (depth, multisampled) are refused: nothing is presented, the token still works.
862 const std::uint64_t presents_before = xbox.presents();
863 {
864 const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT};
865 const auto make_special = [&](DXGI_FORMAT format, UINT samples, D3D12_RESOURCE_FLAGS flags, Ref<ID3D12Resource>& out) {
866 D3D12_RESOURCE_DESC desc{};
867 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
868 desc.Width = width;
869 desc.Height = height;
870 desc.DepthOrArraySize = 1;
871 desc.MipLevels = 1;
872 desc.Format = format;
873 desc.SampleDesc.Count = samples;
874 desc.Flags = flags;
875 return SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_ALLOW_DISPLAY, &desc,
876 D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&out.p)));
877 };
878 Ref<ID3D12Resource> depth_plane, msaa_plane;
879 EXPECT(make_special(DXGI_FORMAT_D32_FLOAT, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE, depth_plane));
880 EXPECT(make_special(DXGI_FORMAT_R8G8B8A8_UNORM, 4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, msaa_plane));
881 ID3D12Resource* cannot[2] = {depth_plane.p, msaa_plane.p};
882 for (ID3D12Resource* resource : cannot) {
883 rt::d3d12::XboxPresentPlaneParameters p{0, 1, &resource, nullptr, 0};
884 p.ScaleFilter = xbox_scale_filter_point;
885 EXPECT(present_planes(&p, 1, DXGI_ERROR_UNSUPPORTED));
886 }
887 }
888 EXPECT(xbox.presents() == presents_before);
889 EXPECT(xbox.presenter().composed_presents() == composed_expected);
890 one = parameters(quad.source, &middle_half, xbox_scale_filter_point);
891 EXPECT(present_planes(&one, 1) && composed_ok()); // still working after the refusals
892 std::printf("compose: bad placements, depth and multisampled sources refused: ok\n");
893
894 // F: the window changes size between composed presents (the swapchain is recreated, possibly in the middle of a
895 // present after an out-of-date acquire): the compose target follows, pixels match the model at the new size.
896 const UINT sizes[][2] = {{400, 300}, {200, 150}, {width, height}};
897 for (const auto& size : sizes) {
898 RECT outer{0, 0, LONG(size[0]), LONG(size[1])};
899 AdjustWindowRect(&outer, WS_OVERLAPPEDWINDOW, FALSE);
900 SetWindowPos(window, nullptr, 0, 0, outer.right - outer.left, outer.bottom - outer.top,
901 SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
902 pump();
903 want_w = want_h = 0; // the first present after a resize may still be at the old size (suboptimal swapchain)
904 for (int round = 0; round < 3; ++round) {
905 one = parameters(quad.source, &middle_half, xbox_scale_filter_point);
906 // (A present the driver reports out of date right after the resize is not counted as shown, so the counter
907 // is not checked here; the frame is still composed and read back.)
908 EXPECT(present_planes(&one, 1));
909 // Whatever size the frame has, it must be the composition at that size (no stale or mis-sized target).
910 Ref_plane resized = model(quad, &middle_half, true);
911 resized.dest[0] = middle_half.left * double(frame.extent.width);
912 resized.dest[1] = middle_half.top * double(frame.extent.height);
913 resized.dest[2] = middle_half.right * double(frame.extent.width);
914 resized.dest[3] = middle_half.bottom * double(frame.extent.height);
915 EXPECT(frame_matches(frame, &resized, 1, false, 203.0, 0));
916 if (round == 2) EXPECT(frame.extent.width == size[0] && frame.extent.height == size[1]);
917 }
918 }
919 want_w = width;
920 want_h = height;
921 composed_expected = xbox.presenter().composed_presents();
922 std::printf("compose: window resized 320x240 -> 400x300 -> 200x150 -> 320x240 between composed presents: ok\n");
923 }
924
424 // Skipping a frame (waiting twice, presenting the second token) is fine. 925 // Skipping a frame (waiting twice, presenting the second token) is fine.
425 std::uint64_t skipped = 0; 926 std::uint64_t skipped = 0;
426 clock.advance_us(4 * period); 927 clock.advance_us(4 * period);
diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp
index 504f0f74d..c5a0e988e 100644
--- a/runtime/test/xgameruntime_test.cpp
+++ b/runtime/test/xgameruntime_test.cpp
@@ -51,16 +51,11 @@ using AsyncCompleteFn = void(__stdcall*)(XAsyncBlock*, HRESULT, size_t);
51using AsyncResultSizeFn = HRESULT(__stdcall*)(XAsyncBlock*, size_t*); 51using AsyncResultSizeFn = HRESULT(__stdcall*)(XAsyncBlock*, size_t*);
52using AsyncResultFn = HRESULT(__stdcall*)(XAsyncBlock*, const void*, size_t, void*, size_t*); 52using AsyncResultFn = HRESULT(__stdcall*)(XAsyncBlock*, const void*, size_t, void*, size_t*);
53 53
54struct XVersion { 54struct alignas(8) XVersion {
55 union { 55 uint16_t major;
56 struct { 56 uint16_t minor;
57 uint16_t major; 57 uint16_t build;
58 uint16_t minor; 58 uint16_t revision;
59 uint16_t build;
60 uint16_t revision;
61 };
62 uint64_t Value;
63 };
64}; 59};
65static_assert(sizeof(XVersion) == 8, "XVersion must be 8 bytes per GDK spec"); 60static_assert(sizeof(XVersion) == 8, "XVersion must be 8 bytes per GDK spec");
66 61
@@ -72,14 +67,22 @@ struct XSystemAnalyticsInfo {
72}; 67};
73static_assert(sizeof(XSystemAnalyticsInfo) == 144, "XSystemAnalyticsInfo must be 144 bytes per GDK spec"); 68static_assert(sizeof(XSystemAnalyticsInfo) == 144, "XSystemAnalyticsInfo must be 144 bytes per GDK spec");
74 69
70struct XPackageMountHandle {
71 uint64_t handle;
72};
73
75using AnalyticsInfoFn = XSystemAnalyticsInfo(__stdcall*)(); 74using AnalyticsInfoFn = XSystemAnalyticsInfo(__stdcall*)();
76using PackageIdentifierFn = HRESULT(__stdcall*)(size_t, char*); 75using PackageIdentifierFn = HRESULT(__stdcall*)(size_t, char*);
77using PackageMountPathFn = HRESULT(__stdcall*)(void*, size_t, char*); 76using PackageMountFn = HRESULT(__stdcall*)(const char*, XPackageMountHandle*);
77using PackageCloseMountHandleFn = void(__stdcall*)(XPackageMountHandle);
78using PackageMountPathSizeFn = HRESULT(__stdcall*)(XPackageMountHandle, size_t*);
79using PackageMountPathFn = HRESULT(__stdcall*)(XPackageMountHandle, size_t, char*);
78using PackagedProcessFn = bool(__stdcall*)(); 80using PackagedProcessFn = bool(__stdcall*)();
79 81
80const char* const kNames[] = { 82const char* const kNames[] = {
81 "XGameRuntimeInitialize", "XGameRuntimeUninitialize", "XSystemGetDeviceType", "XSystemGetConsoleId", 83 "XGameRuntimeInitialize", "XGameRuntimeUninitialize", "XSystemGetDeviceType", "XSystemGetConsoleId",
82 "XSystemGetAnalyticsInfo", "XPackageGetCurrentProcessPackageIdentifier", "XPackageGetMountPath", 84 "XSystemGetAnalyticsInfo", "XPackageGetCurrentProcessPackageIdentifier", "XPackageMount",
85 "XPackageCloseMountHandle", "XPackageGetMountPathSize", "XPackageGetMountPath",
83 "XPackageIsPackagedProcess", 86 "XPackageIsPackagedProcess",
84 "XTaskQueueCreate", "XTaskQueueCreateComposite", "XTaskQueueGetPort", "XTaskQueueDuplicateHandle", 87 "XTaskQueueCreate", "XTaskQueueCreateComposite", "XTaskQueueGetPort", "XTaskQueueDuplicateHandle",
85 "XTaskQueueCloseHandle", "XTaskQueueTerminate", "XTaskQueueDispatch", "XTaskQueueSubmitCallback", 88 "XTaskQueueCloseHandle", "XTaskQueueTerminate", "XTaskQueueDispatch", "XTaskQueueSubmitCallback",
@@ -194,6 +197,23 @@ void check_run_time_load() {
194 check(get_proc(rt_mod, nullptr) == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND, 197 check(get_proc(rt_mod, nullptr) == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND,
195 "a null proc name is NULL with ERROR_PROC_NOT_FOUND"); 198 "a null proc name is NULL with ERROR_PROC_NOT_FOUND");
196 199
200 // XCurl.dll's other way in: LoadLibraryExW(L"gameplatformservices.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32),
201 // then GetApiVersionImpl(uint64_t*, uint64_t*) and QueryApiImpl. Served by the shims, never the PC's own.
202 using LoadExW = HMODULE(WINAPI*)(LPCWSTR, HANDLE, DWORD);
203 auto load_ex_w = reinterpret_cast<LoadExW>(rt::shims::find(set, "LoadLibraryExW"));
204 HMODULE gps = load_ex_w ? load_ex_w(L"gameplatformservices.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32) : nullptr;
205 check(rt::shims::owns_dll("gameplatformservices.dll") && gps != nullptr && gps != rt_mod,
206 "LoadLibraryExW(gameplatformservices.dll, SEARCH_SYSTEM32) is served by the shims");
207 using ApiVersion = HRESULT(WINAPI*)(uint64_t*, uint64_t*);
208 auto api_version = gps ? reinterpret_cast<ApiVersion>(get_proc(gps, "GetApiVersionImpl")) : nullptr;
209 uint64_t v1 = 0, v2 = 0, w1 = 0, w2 = 0;
210 check(api_version && api_version(&v1, &v2) == S_OK && api_version(&w1, &w2) == S_OK && v1 && v2 && v1 == w1 &&
211 v2 == w2,
212 "GetApiVersionImpl writes the same two non-zero versions on every call");
213 check(gps && reinterpret_cast<void*>(get_proc(gps, "QueryApiImpl")) ==
214 rt::shims::find("xgameruntime.dll", "QueryApiImpl"),
215 "its QueryApiImpl is the offline runtime's");
216
197 struct Options { 217 struct Options {
198 uint32_t unknown; 218 uint32_t unknown;
199 BOOL is_inline; 219 BOOL is_inline;
@@ -283,76 +303,123 @@ void check_run_time_load() {
283 return true; 303 return true;
284 }; 304 };
285 using SetCallback = void(STDMETHODCALLTYPE*)(void*, Callback, void*); 305 using SetCallback = void(STDMETHODCALLTYPE*)(void*, Callback, void*);
286 using Report = void(STDMETHODCALLTYPE*)(void*, HRESULT, const char*); 306 using Report = HRESULT(STDMETHODCALLTYPE*)(void*, HRESULT, const char*);
287 reinterpret_cast<SetCallback>(slot(e, 4))(e, on_error, &seen); 307 reinterpret_cast<SetCallback>(slot(e, 4))(e, on_error, &seen);
288 reinterpret_cast<Report>(slot(e, 3))(e, E_FAIL, "offline test"); 308 const HRESULT reported = reinterpret_cast<Report>(slot(e, 3))(e, E_FAIL, "offline test");
289 check(seen.hr == E_FAIL && std::strcmp(seen.msg, "offline test") == 0, 309 check(reported == S_OK && seen.hr == E_FAIL && std::strcmp(seen.msg, "offline test") == 0,
290 "slot 3 is XErrorReport and reaches the callback slot 4 (XErrorSetCallback) set"); 310 "slot 3 is XErrorReport and reaches the callback slot 4 (XErrorSetCallback) set");
291 reinterpret_cast<SetCallback>(slot(e, 4))(e, nullptr, nullptr); 311 reinterpret_cast<SetCallback>(slot(e, 4))(e, nullptr, nullptr);
292 using SetOptions = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t, uint32_t); 312 using SetOptions = void(STDMETHODCALLTYPE*)(void*, uint32_t, uint32_t); // void, per Microsoft's page
293 check(reinterpret_cast<SetOptions>(slot(e, 5))(e, 0, 0) == S_OK, "slot 5 is XErrorSetOptions"); 313 reinterpret_cast<SetOptions>(slot(e, 5))(e, 0x01, 0x00); // OutputDebugStringOnError / None
294 release(e); 314 release(e);
295 } 315 }
296 316
297 const GUID networking_cls = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}}; 317 // XNetworkingImpl, asked for as XCurl.dll does: the class id with IXNetworkingImpl2's interface id.
298 void* n = get(networking_cls); 318 const GUID networking = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}};
299 check(n != nullptr, "QueryApiImpl hands out XNetworkingImpl for its class id"); 319 const GUID networking2 = {0xbf2346b2, 0x39af, 0x4658, {0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3}};
320 const HRESULT no_network = HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE);
321 void* n = nullptr;
322 check(query(&networking, networking2, &n) == S_OK && n, "QueryApiImpl hands out XNetworkingImpl for IXNetworkingImpl2");
323 void* n1 = nullptr;
324 check(query(&networking, networking, &n1) == S_OK && n1 == n, "and the same object for IXNetworkingImpl");
325 if (n1) release(n1);
300 if (n) { 326 if (n) {
301 void* again = get(networking_cls); 327 struct Hint {
302 check(again == n, "XNetworkingImpl is one process-wide object"); 328 uint32_t level, cost, iana;
303 release(again); 329 bool initialized, approaching, over, roaming;
304 330 } hint{9, 9, 9, false, true, true, true};
305 // Slot 15: XNetworkingGetConnectivityHint 331 using GetHint = HRESULT(STDMETHODCALLTYPE*)(void*, Hint*);
306 struct ConnectivityHint { 332 check(reinterpret_cast<GetHint>(slot(n, 15))(n, &hint) == S_OK && hint.level == 1 && hint.cost == 0 &&
307 uint32_t level; 333 hint.initialized && !hint.approaching && !hint.over && !hint.roaming,
308 uint32_t cost; 334 "slot 15 (XNetworkingGetConnectivityHint): initialized, no connectivity");
309 uint32_t iana_type; 335 XAsyncBlock block{};
310 bool network_initialized; 336 using SecurityAsync = HRESULT(STDMETHODCALLTYPE*)(void*, const wchar_t*, XAsyncBlock*);
311 bool approaching_limit; 337 using ResultSize = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, size_t*);
312 bool over_limit; 338 size_t size = 99;
313 bool roaming; 339 check(reinterpret_cast<SecurityAsync>(slot(n, 11))(n, L"https://example.invalid/", &block) == S_OK &&
314 } hint{}; 340 XAsyncGetStatus(&block, true) == no_network &&
315 using GetHint = HRESULT(STDMETHODCALLTYPE*)(void*, ConnectivityHint*); 341 reinterpret_cast<ResultSize>(slot(n, 12))(n, &block, &size) == no_network && size == 0,
316 check(reinterpret_cast<GetHint>(slot(n, 15))(n, nullptr) == E_POINTER, 342 "slots 11/12 (UTF-16 URL security info): the async call completes with no network");
317 "slot 15 rejects null pointer with E_POINTER"); 343 // Slots 10/13 in Microsoft's order: (async, bufferByteCount, bufferByteCountUsed*, buffer*, information**).
318 check(reinterpret_cast<GetHint>(slot(n, 15))(n, &hint) == S_OK && hint.network_initialized && 344 // A sentinel buffer must stay untouched; the two outputs are written where they are, not into the buffer.
319 hint.level == 3 && hint.cost == 1, 345 using SecurityResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, size_t, size_t*, uint8_t*, void**);
320 "slot 15 is XNetworkingGetConnectivityHint reporting initialized network and internet access"); 346 for (int s : {10, 13}) {
321 347 uint8_t buffer[32];
322 // Slot 14: XNetworkingVerifyServerCertificate 348 std::memset(buffer, 0xA5, sizeof(buffer));
323 using VerifyCert = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const void*); 349 size_t used = 77;
324 check(reinterpret_cast<VerifyCert>(slot(n, 14))(n, nullptr, nullptr) == S_OK, 350 void* info = &used;
325 "slot 14 is XNetworkingVerifyServerCertificate returning S_OK offline"); 351 const HRESULT hr = reinterpret_cast<SecurityResult>(slot(n, s))(n, &block, sizeof(buffer), &used, buffer, &info);
326 352 bool untouched = true;
327 // Slot 16 & 17: XNetworkingRegisterConnectivityHintChanged and Unregister 353 for (uint8_t byte : buffer) untouched = untouched && byte == 0xA5;
328 using RegisterHint = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, void*, void*, XTaskQueueRegistrationToken*); 354 check(hr == no_network && used == 0 && info == nullptr && untouched,
329 using UnregisterHint = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool); 355 s == 10 ? "slot 10 (ANSI result): outputs zeroed in place, the caller's buffer untouched"
330 XTaskQueueRegistrationToken tok1{0}, tok2{0}; 356 : "slot 13 (UTF-16 result): outputs zeroed in place, the caller's buffer untouched");
331 check(reinterpret_cast<RegisterHint>(slot(n, 16))(n, nullptr, nullptr, nullptr, &tok1) == S_OK && 357 }
332 reinterpret_cast<RegisterHint>(slot(n, 16))(n, nullptr, nullptr, nullptr, &tok2) == S_OK && 358 using Verify = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const void*);
333 tok1.token != tok2.token && tok1.token > 0, 359 check(reinterpret_cast<Verify>(slot(n, 14))(n, nullptr, nullptr) == no_network,
334 "slot 16 registers connectivity hint callbacks and hands out tokens"); 360 "slot 14 (XNetworkingVerifyServerCertificate) fails offline");
335 check(reinterpret_cast<UnregisterHint>(slot(n, 17))(n, tok1, false) == true && 361 XTaskQueueRegistrationToken token{};
336 reinterpret_cast<UnregisterHint>(slot(n, 17))(n, tok2, true) == true, 362 using Register = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, void*, void*, XTaskQueueRegistrationToken*);
337 "slot 17 unregisters connectivity hint callbacks"); 363 using Unregister = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool);
338 364 check(reinterpret_cast<Register>(slot(n, 16))(n, nullptr, nullptr, nullptr, &token) == S_OK && token.token &&
339 // Slots 11-13: Async security info query 365 reinterpret_cast<Unregister>(slot(n, 17))(n, token, true),
340 using QuerySecAsync = HRESULT(STDMETHODCALLTYPE*)(void*, const wchar_t*, XAsyncBlock*); 366 "slots 16/17 register and unregister a connectivity-hint callback");
341 using QuerySecSize = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, size_t*); 367 uint16_t port = 7;
342 using QuerySecResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, size_t, size_t*, uint8_t*, void**); 368 using QueryPort = HRESULT(STDMETHODCALLTYPE*)(void*, uint16_t*);
343 check(reinterpret_cast<QuerySecAsync>(slot(n, 11))(n, L"https://example.com", nullptr) == S_OK, 369 using NotImpl = HRESULT(STDMETHODCALLTYPE*)(void*);
344 "slot 11 is XNetworkingQuerySecurityInformationForUrlUtf16Async"); 370 check(reinterpret_cast<QueryPort>(slot(n, 3))(n, &port) == no_network && port == 0 &&
345 size_t sec_size = 42; 371 reinterpret_cast<NotImpl>(slot(n, 20))(n) == E_NOTIMPL,
346 check(reinterpret_cast<QuerySecSize>(slot(n, 12))(n, nullptr, &sec_size) == S_OK && sec_size == 0, 372 "slot 3 (preferred UDP port) has no answer offline; slot 20 (IXNetworkingImpl2) is E_NOTIMPL");
347 "slot 12 is XNetworkingQuerySecurityInformationForUrlUtf16AsyncResultSize returning 0 bytes");
348 size_t used = 42;
349 void* sec_info = reinterpret_cast<void*>(1);
350 check(reinterpret_cast<QuerySecResult>(slot(n, 13))(n, nullptr, 0, &used, nullptr, &sec_info) == S_OK &&
351 used == 0 && sec_info == nullptr,
352 "slot 13 is XNetworkingQuerySecurityInformationForUrlUtf16AsyncResult returning S_OK with null result");
353
354 release(n); 373 release(n);
355 } 374 }
375
376 // XSystemImpl, asked for as libHttpClient.GDK.dll does: the class id with IXSystemImpl5's interface id.
377 const GUID system_cls = {0xe349bd1a, 0xfc20, 0x4e40, {0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f}};
378 const GUID system5 = {0x1861cf2e, 0xe18b, 0x4834, {0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf}};
379 void* sy = nullptr;
380 check(query(&system_cls, system5, &sy) == S_OK && sy, "QueryApiImpl hands out XSystemImpl for IXSystemImpl5");
381 if (sy) {
382 using IdQuery = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*, size_t*);
383 char buf[64] = {};
384 size_t used = 0;
385 check(reinterpret_cast<IdQuery>(slot(sy, 3))(sy, sizeof(buf), buf, &used) == S_OK && used == 39 &&
386 std::strlen(buf) == 38,
387 "slot 3 (XSystemGetConsoleId): the 39-byte placeholder");
388 check(reinterpret_cast<IdQuery>(slot(sy, 4))(sy, sizeof(buf), buf, &used) == S_OK &&
389 std::strcmp(buf, "RETAIL") == 0 && used == 7,
390 "slot 4 (XSystemGetXboxLiveSandboxId): RETAIL");
391 check(reinterpret_cast<IdQuery>(slot(sy, 4))(sy, 15, buf, &used) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) &&
392 reinterpret_cast<IdQuery>(slot(sy, 4))(sy, 16, buf, &used) == S_OK,
393 "slot 4 needs XSystemXboxLiveSandboxIdMaxBytes (16), not just the id's 7 bytes");
394 const GUID chain[] = {
395 system_cls,
396 {0x6fd71f09, 0x7513, 0x49f0, {0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52}},
397 {0x67ce4bfc, 0xb1d1, 0x4ac7, {0xbc, 0x3a, 0xcb, 0x92, 0x19, 0xa9, 0x7a, 0x85}},
398 {0xdadc2895, 0x34b0, 0x4ef5, {0xa8, 0x3e, 0x45, 0x11, 0x4d, 0x62, 0x9b, 0x80}},
399 system5};
400 bool all = true;
401 for (const GUID& iid : chain) {
402 void* same = nullptr;
403 all = all && query(&system_cls, iid, &same) == S_OK && same == sy;
404 if (same) release(same);
405 }
406 check(all, "IXSystemImpl5 answers for every interface it inherits (IXSystemImpl .. IXSystemImpl4)");
407 check(reinterpret_cast<IdQuery>(slot(sy, 5))(sy, sizeof(buf), buf, &used) == S_OK && used == 45 &&
408 reinterpret_cast<IdQuery>(slot(sy, 5))(sy, 44, buf, &used) ==
409 HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) &&
410 reinterpret_cast<IdQuery>(slot(sy, 5))(sy, 45, nullptr, &used) == E_INVALIDARG,
411 "slot 5 (XSystemGetAppSpecificDeviceId): 45 bytes; a short or null buffer is refused");
412 using Track = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*);
413 using IsValid = bool(STDMETHODCALLTYPE*)(void*, void*); // bool, per Microsoft's reference page
414 using Bandwidth = void(STDMETHODCALLTYPE*)(void*, bool);
415 int ctx = 0;
416 reinterpret_cast<Bandwidth>(slot(sy, 8))(sy, true);
417 check(reinterpret_cast<Track>(slot(sy, 6))(sy, &ctx, &ctx) == S_OK &&
418 reinterpret_cast<IsValid>(slot(sy, 7))(sy, &ctx) &&
419 !reinterpret_cast<IsValid>(slot(sy, 7))(sy, nullptr),
420 "slots 6-8 (handle tracking, handle check, download bandwidth) answer offline");
421 release(sy);
422 }
356 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds"); 423 check(uninit_api() == S_OK, "UninitializeApiImpl succeeds");
357 424
358 HMODULE k32 = load_w(L"kernel32.dll"); 425 HMODULE k32 = load_w(L"kernel32.dll");
@@ -426,20 +493,63 @@ int main() {
426 std::strcmp(pkg_id, "CustomTestPackageId_123456789012") == 0, 493 std::strcmp(pkg_id, "CustomTestPackageId_123456789012") == 0,
427 "XPackageGetCurrentProcessPackageIdentifier respects LEONIDA_PACKAGE_ID override"); 494 "XPackageGetCurrentProcessPackageIdentifier respects LEONIDA_PACKAGE_ID override");
428 SetEnvironmentVariableA("LEONIDA_PACKAGE_ID", nullptr); 495 SetEnvironmentVariableA("LEONIDA_PACKAGE_ID", nullptr);
496 // pkg_id still holds the override; the mount checks below need the game's own identifier again.
497 check(package_id(sizeof(pkg_id), pkg_id) == S_OK && std::strlen(pkg_id) == 32,
498 "XPackageGetCurrentProcessPackageIdentifier returns the default again once the override is cleared");
429 499
500 auto mount_pkg = get<PackageMountFn>("XPackageMount");
501 auto close_mount = get<PackageCloseMountHandleFn>("XPackageCloseMountHandle");
502 auto mount_path_size = get<PackageMountPathSizeFn>("XPackageGetMountPathSize");
430 auto mount_path = get<PackageMountPathFn>("XPackageGetMountPath"); 503 auto mount_path = get<PackageMountPathFn>("XPackageGetMountPath");
431 check(mount_path(nullptr, 0, nullptr) == E_INVALIDARG, "XPackageGetMountPath rejects null buffer and size 0");
432 char mnt_path[MAX_PATH] = {};
433 check(mount_path(nullptr, 0, mnt_path) == E_INVALIDARG, "XPackageGetMountPath rejects size 0 with buffer");
434 check(mount_path(nullptr, 10, nullptr) == E_INVALIDARG, "XPackageGetMountPath rejects null pointer with size");
435 504
436 SetEnvironmentVariableA("LEONIDA_GAME_DIR", "C:\\LeonidaGameDir"); 505 const XPackageMountHandle kInvalidMount{0};
437 check(mount_path(nullptr, 5, mnt_path) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER), 506 const XPackageMountHandle kStaleMount{999};
507
508 XPackageMountHandle test_out{0};
509 check(mount_pkg(nullptr, nullptr) == E_INVALIDARG, "XPackageMount rejects null identifier and null out pointer");
510 check(mount_pkg(pkg_id, nullptr) == E_INVALIDARG, "XPackageMount rejects null out pointer with identifier");
511 check(mount_pkg(nullptr, &test_out) == E_INVALIDARG, "XPackageMount rejects null identifier with out pointer");
512 check(mount_pkg(pkg_id, &test_out) == E_ACCESSDENIED,
513 "XPackageMount rejects game package identifier with E_ACCESSDENIED");
514 check(mount_pkg("UninstalledPackage_0000000000000", &test_out) == HRESULT_FROM_WIN32(ERROR_NOT_FOUND),
515 "XPackageMount rejects uninstalled package identifier with ERROR_NOT_FOUND");
516
517 size_t req_size = 0;
518 check(mount_path_size(kInvalidMount, &req_size) == E_INVALIDARG,
519 "XPackageGetMountPathSize rejects invalid mount handle 0");
520 check(mount_path_size(kStaleMount, &req_size) == HRESULT_FROM_WIN32(ERROR_NOT_FOUND),
521 "XPackageGetMountPathSize rejects unknown mount handle");
522
523 char mnt_path[MAX_PATH] = {};
524 check(mount_path(kInvalidMount, 0, nullptr) == E_INVALIDARG,
525 "XPackageGetMountPath rejects invalid mount handle 0");
526 check(mount_path(kStaleMount, sizeof(mnt_path), mnt_path) == HRESULT_FROM_WIN32(ERROR_NOT_FOUND),
527 "XPackageGetMountPath rejects unknown mount handle");
528
529 SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", "DLC1_123456789012345678901234567=C:\\LeonidaDLC1");
530 XPackageMountHandle dlc_mount{0};
531 check(mount_pkg("DLC1_123456789012345678901234567", &dlc_mount) == S_OK && dlc_mount.handle != 0,
532 "XPackageMount mounts content package from LEONIDA_CONTENT_PACKAGES");
533 check(mount_path_size(dlc_mount, nullptr) == E_INVALIDARG,
534 "XPackageGetMountPathSize rejects null size pointer");
535 check(mount_path_size(dlc_mount, &req_size) == S_OK && req_size == std::strlen("C:\\LeonidaDLC1") + 1,
536 "XPackageGetMountPathSize returns required buffer size including null terminator for mounted handle");
537 check(mount_path(dlc_mount, 0, mnt_path) == E_INVALIDARG,
538 "XPackageGetMountPath rejects size 0 with buffer");
539 check(mount_path(dlc_mount, 10, nullptr) == E_INVALIDARG,
540 "XPackageGetMountPath rejects null pointer with size");
541 check(mount_path(dlc_mount, 5, mnt_path) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER),
438 "XPackageGetMountPath rejects insufficient buffer"); 542 "XPackageGetMountPath rejects insufficient buffer");
439 check(mount_path(nullptr, sizeof(mnt_path), mnt_path) == S_OK && 543 check(mount_path(dlc_mount, sizeof(mnt_path), mnt_path) == S_OK &&
440 std::strcmp(mnt_path, "C:\\LeonidaGameDir") == 0, 544 std::strcmp(mnt_path, "C:\\LeonidaDLC1") == 0,
441 "XPackageGetMountPath returns configured game directory"); 545 "XPackageGetMountPath returns configured content directory for mounted handle");
442 SetEnvironmentVariableA("LEONIDA_GAME_DIR", nullptr); 546
547 close_mount(dlc_mount);
548 check(mount_path_size(dlc_mount, &req_size) == HRESULT_FROM_WIN32(ERROR_NOT_FOUND),
549 "XPackageGetMountPathSize rejects closed/stale mount handle");
550 check(mount_path(dlc_mount, sizeof(mnt_path), mnt_path) == HRESULT_FROM_WIN32(ERROR_NOT_FOUND),
551 "XPackageGetMountPath rejects closed/stale mount handle");
552 SetEnvironmentVariableA("LEONIDA_CONTENT_PACKAGES", nullptr);
443 553
444 auto is_packaged = get<PackagedProcessFn>("XPackageIsPackagedProcess"); 554 auto is_packaged = get<PackagedProcessFn>("XPackageIsPackagedProcess");
445 check(is_packaged() == true, "XPackageIsPackagedProcess returns true by default"); 555 check(is_packaged() == true, "XPackageIsPackagedProcess returns true by default");
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index 4087df4d7..7e4948f1f 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -20,6 +20,9 @@ using XMemFreeFn = void(__stdcall*)(void*, uint64_t);
20using XMemVirtualQueryFn = SIZE_T(__stdcall*)(HANDLE, const void*, void*); 20using XMemVirtualQueryFn = SIZE_T(__stdcall*)(HANDLE, const void*, void*);
21// BOOL XMemGetWorkingSetStatistics(UINT32 kind, stats*): the FSR DLL passes kind 0x20000001 at every call site. 21// BOOL XMemGetWorkingSetStatistics(UINT32 kind, stats*): the FSR DLL passes kind 0x20000001 at every call site.
22using XMemGetWorkingSetStatisticsFn = BOOL(__stdcall*)(uint32_t, void*); 22using XMemGetWorkingSetStatisticsFn = BOOL(__stdcall*)(uint32_t, void*);
23using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD);
24using XMemGetWriteWatchFn = UINT(WINAPI*)(DWORD, void*, SIZE_T, void**, ULONG_PTR*, ULONG*);
25using XMemResetWriteWatchFn = UINT(WINAPI*)(void*, SIZE_T);
23constexpr uint32_t kMeasuredKind = 0x20000001; 26constexpr uint32_t kMeasuredKind = 0x20000001;
24 27
25int g_checks = 0; 28int g_checks = 0;
@@ -129,6 +132,78 @@ void test_virtual_query(XMemVirtualQueryFn query) {
129 check(bad == 0, "XMemVirtualQuery on an invalid address returns 0 without crashing"); 132 check(bad == 0, "XMemVirtualQuery on an invalid address returns 0 without crashing");
130} 133}
131 134
135void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn get_write_watch,
136 XMemResetWriteWatchFn reset_write_watch) {
137 SYSTEM_INFO system_info{};
138 GetSystemInfo(&system_info);
139 const SIZE_T page_size = system_info.dwPageSize;
140 check(page_size != 0, "GetSystemInfo reports a non-zero page size");
141 if (page_size == 0) return;
142
143 const SIZE_T region_size = page_size * 3;
144 void* const base = virtual_alloc(nullptr, region_size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, 0,
145 PAGE_READWRITE);
146 check(base != nullptr, "XMemVirtualAlloc creates a synthetic write-watch region");
147 if (!base) return;
148
149 void* watched[4]{};
150 ULONG_PTR count = 4;
151 ULONG granularity = 0;
152 UINT status = get_write_watch(0, base, region_size, watched, &count, &granularity);
153 check(status == NO_ERROR && count == 0, "new write-watch region starts with no dirty pages");
154 check(status == NO_ERROR && granularity == page_size, "write-watch reports the host page granularity");
155
156 auto* const bytes = static_cast<volatile uint8_t*>(base);
157 bytes[0] = 0xa1;
158 bytes[page_size * 2] = 0xb2;
159
160 count = 4;
161 status = get_write_watch(0, base, region_size, watched, &count, &granularity);
162 bool saw_first_page = false;
163 bool saw_third_page = false;
164 bool all_addresses_are_page_aligned = count <= 4;
165 for (ULONG_PTR i = 0; i < count && i < 4; ++i) {
166 const uintptr_t address = reinterpret_cast<uintptr_t>(watched[i]);
167 const uintptr_t start = reinterpret_cast<uintptr_t>(base);
168 all_addresses_are_page_aligned &= address >= start && (address - start) % page_size == 0;
169 saw_first_page |= address == start;
170 saw_third_page |= address == start + page_size * 2;
171 }
172 check(status == NO_ERROR && count == 2 && saw_first_page && saw_third_page,
173 "write-watch reports each written page by its relative address");
174 check(all_addresses_are_page_aligned, "write-watch addresses are page aligned and within the region");
175
176 count = 4;
177 status = get_write_watch(0, base, region_size, watched, &count, &granularity);
178 check(status == NO_ERROR && count == 2, "query-only write-watch leaves dirty pages recorded");
179
180 status = reset_write_watch(base, region_size);
181 check(status == NO_ERROR, "XMemResetWriteWatch clears the synthetic region");
182 count = 4;
183 status = get_write_watch(0, base, region_size, watched, &count, &granularity);
184 check(status == NO_ERROR && count == 0, "reset write-watch query returns no dirty pages");
185
186 bytes[page_size] = 0xc3;
187 count = 4;
188 status = get_write_watch(0, base, region_size, watched, &count, &granularity);
189 check(status == NO_ERROR && count == 1 &&
190 reinterpret_cast<uintptr_t>(watched[0]) == reinterpret_cast<uintptr_t>(base) + page_size,
191 "write-watch records writes again after reset");
192
193 check(VirtualFree(base, 0, MEM_RELEASE), "release the synthetic write-watch region");
194
195 SetLastError(ERROR_SUCCESS);
196 void* const large_page = virtual_alloc(nullptr, page_size, MEM_RESERVE | MEM_COMMIT | 0x20000000, 0,
197 PAGE_READWRITE);
198 check(large_page == nullptr && GetLastError() == ERROR_NOT_SUPPORTED,
199 "unsupported large-page allocation is rejected before host allocation");
200
201 SetLastError(ERROR_SUCCESS);
202 void* const attributed = virtual_alloc(nullptr, page_size, MEM_RESERVE | MEM_COMMIT, 1, PAGE_READWRITE);
203 check(attributed == nullptr && GetLastError() == ERROR_NOT_SUPPORTED,
204 "nonzero XMem allocation attributes are rejected before host allocation");
205}
206
132void print_result() { 207void print_result() {
133 if (g_failures == 0) { 208 if (g_failures == 0) {
134 std::printf("xmem_test: OK (%d checks)\n", g_checks); 209 std::printf("xmem_test: OK (%d checks)\n", g_checks);
@@ -148,11 +223,20 @@ int main() {
148 const auto query = reinterpret_cast<XMemVirtualQueryFn>(rt::shims::find("xmem.dll", "XMemVirtualQuery")); 223 const auto query = reinterpret_cast<XMemVirtualQueryFn>(rt::shims::find("xmem.dll", "XMemVirtualQuery"));
149 const auto get_stats = 224 const auto get_stats =
150 reinterpret_cast<XMemGetWorkingSetStatisticsFn>(rt::shims::find("xmem.dll", "XMemGetWorkingSetStatistics")); 225 reinterpret_cast<XMemGetWorkingSetStatisticsFn>(rt::shims::find("xmem.dll", "XMemGetWorkingSetStatistics"));
226 const auto virtual_alloc =
227 reinterpret_cast<XMemVirtualAllocFn>(rt::shims::find("xmem.dll", "XMemVirtualAlloc"));
228 const auto get_write_watch =
229 reinterpret_cast<XMemGetWriteWatchFn>(rt::shims::find("xmem.dll", "XMemGetWriteWatch"));
230 const auto reset_write_watch =
231 reinterpret_cast<XMemResetWriteWatchFn>(rt::shims::find("xmem.dll", "XMemResetWriteWatch"));
151 232
152 check(alloc != nullptr, "registry exposes xmem.dll!XMemAlloc"); 233 check(alloc != nullptr, "registry exposes xmem.dll!XMemAlloc");
153 check(free_mem != nullptr, "registry exposes xmem.dll!XMemFree"); 234 check(free_mem != nullptr, "registry exposes xmem.dll!XMemFree");
154 check(query != nullptr, "registry exposes xmem.dll!XMemVirtualQuery"); 235 check(query != nullptr, "registry exposes xmem.dll!XMemVirtualQuery");
155 check(get_stats != nullptr, "registry exposes xmem.dll!XMemGetWorkingSetStatistics"); 236 check(get_stats != nullptr, "registry exposes xmem.dll!XMemGetWorkingSetStatistics");
237 check(virtual_alloc != nullptr, "registry exposes xmem.dll!XMemVirtualAlloc");
238 check(get_write_watch != nullptr, "registry exposes xmem.dll!XMemGetWriteWatch");
239 check(reset_write_watch != nullptr, "registry exposes xmem.dll!XMemResetWriteWatch");
156 240
157 if (!alloc || !free_mem || !query || !get_stats) { 241 if (!alloc || !free_mem || !query || !get_stats) {
158 print_result(); 242 print_result();
@@ -162,6 +246,9 @@ int main() {
162 test_alloc(alloc, free_mem); 246 test_alloc(alloc, free_mem);
163 test_working_set(get_stats); 247 test_working_set(get_stats);
164 test_virtual_query(query); 248 test_virtual_query(query);
249 if (virtual_alloc && get_write_watch && reset_write_watch) {
250 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch);
251 }
165 252
166 print_result(); 253 print_result();
167 return g_failures ? 1 : 0; 254 return g_failures ? 1 : 0;