summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/CMakeLists.txt5
-rw-r--r--src/audio_core/CMakeLists.txt11
-rw-r--r--src/audio_core/audio_event.cpp1
-rw-r--r--src/audio_core/audio_manager.h2
-rw-r--r--src/audio_core/audio_render_manager.h2
-rw-r--r--src/audio_core/common/feature_support.h1
-rw-r--r--src/audio_core/precompiled_headers.h6
-rw-r--r--src/audio_core/renderer/command/command_buffer.cpp14
-rw-r--r--src/audio_core/renderer/command/effect/i3dl2_reverb.cpp1
-rw-r--r--src/audio_core/renderer/command/effect/reverb.cpp1
-rw-r--r--src/audio_core/renderer/mix/mix_context.cpp1
-rw-r--r--src/audio_core/renderer/performance/performance_manager.cpp1
-rw-r--r--src/audio_core/renderer/voice/voice_context.cpp1
-rw-r--r--src/audio_core/sink/sink_stream.cpp19
-rw-r--r--src/audio_core/sink/sink_stream.h5
-rw-r--r--src/common/CMakeLists.txt8
-rw-r--r--src/common/atomic_helpers.h1
-rw-r--r--src/common/cache_management.cpp59
-rw-r--r--src/common/cache_management.h27
-rw-r--r--src/common/common_precompiled_headers.h14
-rw-r--r--src/common/fs/file.cpp2
-rw-r--r--src/common/fs/fs_util.cpp1
-rw-r--r--src/common/fs/path_util.cpp1
-rw-r--r--src/common/input.h41
-rw-r--r--src/common/logging/backend.cpp2
-rw-r--r--src/common/polyfill_ranges.h530
-rw-r--r--src/common/polyfill_thread.h323
-rw-r--r--src/common/precompiled_headers.h6
-rw-r--r--src/common/settings.cpp2
-rw-r--r--src/common/settings.h6
-rw-r--r--src/common/string_util.cpp4
-rw-r--r--src/common/thread_worker.h5
-rw-r--r--src/common/threadsafe_queue.h4
-rw-r--r--src/core/CMakeLists.txt14
-rw-r--r--src/core/arm/dynarmic/arm_dynarmic_64.cpp1
-rw-r--r--src/core/core.cpp11
-rw-r--r--src/core/cpu_manager.h1
-rw-r--r--src/core/crypto/key_manager.cpp8
-rw-r--r--src/core/debugger/debugger.cpp1
-rw-r--r--src/core/file_sys/content_archive.cpp1
-rw-r--r--src/core/frontend/applets/cabinet.cpp20
-rw-r--r--src/core/frontend/applets/cabinet.h37
-rw-r--r--src/core/frontend/applets/controller.h1
-rw-r--r--src/core/frontend/emu_window.h2
-rw-r--r--src/core/hid/emulated_console.cpp98
-rw-r--r--src/core/hid/emulated_console.h15
-rw-r--r--src/core/hid/emulated_controller.cpp39
-rw-r--r--src/core/hid/emulated_controller.h1
-rw-r--r--src/core/hid/emulated_devices.cpp15
-rw-r--r--src/core/hid/emulated_devices.h1
-rw-r--r--src/core/hid/input_converter.cpp3
-rw-r--r--src/core/hle/kernel/hle_ipc.h62
-rw-r--r--src/core/hle/kernel/init/init_slab_setup.cpp1
-rw-r--r--src/core/hle/kernel/k_handle_table.cpp17
-rw-r--r--src/core/hle/kernel/k_handle_table.h16
-rw-r--r--src/core/hle/kernel/k_memory_manager.cpp4
-rw-r--r--src/core/hle/kernel/k_page_table.cpp3
-rw-r--r--src/core/hle/kernel/k_process.cpp1
-rw-r--r--src/core/hle/kernel/k_slab_heap.h6
-rw-r--r--src/core/hle/kernel/k_thread_local_page.h1
-rw-r--r--src/core/hle/kernel/service_thread.cpp1
-rw-r--r--src/core/hle/kernel/svc.cpp26
-rw-r--r--src/core/hle/kernel/svc_wrap.h12
-rw-r--r--src/core/hle/service/acc/acc.cpp1
-rw-r--r--src/core/hle/service/acc/profile_manager.cpp1
-rw-r--r--src/core/hle/service/am/am.cpp4
-rw-r--r--src/core/hle/service/am/applets/applet_cabinet.cpp177
-rw-r--r--src/core/hle/service/am/applets/applet_cabinet.h104
-rw-r--r--src/core/hle/service/am/applets/applet_error.cpp1
-rw-r--r--src/core/hle/service/am/applets/applet_general_backend.cpp2
-rw-r--r--src/core/hle/service/am/applets/applets.cpp20
-rw-r--r--src/core/hle/service/am/applets/applets.h12
-rw-r--r--src/core/hle/service/audio/audin_u.cpp10
-rw-r--r--src/core/hle/service/audio/audout_u.cpp10
-rw-r--r--src/core/hle/service/audio/audren_u.cpp7
-rw-r--r--src/core/hle/service/audio/hwopus.cpp2
-rw-r--r--src/core/hle/service/bcat/bcat_module.cpp4
-rw-r--r--src/core/hle/service/es/es.cpp27
-rw-r--r--src/core/hle/service/filesystem/fsp_srv.cpp4
-rw-r--r--src/core/hle/service/hid/hid.cpp32
-rw-r--r--src/core/hle/service/hid/hid.h4
-rw-r--r--src/core/hle/service/ldn/ldn.cpp4
-rw-r--r--src/core/hle/service/nfc/nfc.cpp71
-rw-r--r--src/core/hle/service/nfc/nfc_device.cpp197
-rw-r--r--src/core/hle/service/nfc/nfc_device.h70
-rw-r--r--src/core/hle/service/nfc/nfc_result.h17
-rw-r--r--src/core/hle/service/nfc/nfc_user.cpp365
-rw-r--r--src/core/hle/service/nfc/nfc_user.h52
-rw-r--r--src/core/hle/service/nfp/amiibo_crypto.cpp1
-rw-r--r--src/core/hle/service/nfp/nfp_device.cpp41
-rw-r--r--src/core/hle/service/nfp/nfp_device.h9
-rw-r--r--src/core/hle/service/nfp/nfp_types.h17
-rw-r--r--src/core/hle/service/nfp/nfp_user.cpp23
-rw-r--r--src/core/hle/service/nfp/nfp_user.h5
-rw-r--r--src/core/hle/service/nifm/nifm.cpp41
-rw-r--r--src/core/hle/service/ns/iplatform_service_manager.cpp11
-rw-r--r--src/core/hle/service/nvdrv/core/syncpoint_manager.cpp46
-rw-r--r--src/core/hle/service/nvdrv/core/syncpoint_manager.h2
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp5
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_gpu.cpp5
-rw-r--r--src/core/hle/service/nvdrv/nvdrv.cpp44
-rw-r--r--src/core/hle/service/nvflinger/buffer_item_consumer.cpp2
-rw-r--r--src/core/hle/service/nvflinger/buffer_item_consumer.h2
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue_consumer.cpp2
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue_core.cpp6
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue_core.h5
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue_producer.cpp14
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue_producer.h3
-rw-r--r--src/core/hle/service/nvflinger/consumer_base.cpp6
-rw-r--r--src/core/hle/service/nvflinger/consumer_base.h16
-rw-r--r--src/core/hle/service/nvflinger/nvflinger.cpp3
-rw-r--r--src/core/hle/service/nvflinger/nvflinger.h1
-rw-r--r--src/core/hle/service/nvflinger/producer_listener.h1
-rw-r--r--src/core/hle/service/service.cpp1
-rw-r--r--src/core/hle/service/set/set.cpp2
-rw-r--r--src/core/hle/service/time/time_zone_manager.cpp1
-rw-r--r--src/core/internal_network/network_interface.cpp1
-rw-r--r--src/core/memory.cpp65
-rw-r--r--src/core/memory.h34
-rw-r--r--src/core/memory/dmnt_cheat_vm.cpp2
-rw-r--r--src/core/precompiled_headers.h11
-rw-r--r--src/core/telemetry_session.cpp2
-rw-r--r--src/dedicated_room/CMakeLists.txt5
-rw-r--r--src/dedicated_room/precompiled_headers.h6
-rw-r--r--src/input_common/CMakeLists.txt11
-rw-r--r--src/input_common/drivers/gc_adapter.h2
-rw-r--r--src/input_common/drivers/mouse.cpp1
-rw-r--r--src/input_common/drivers/mouse.h2
-rw-r--r--src/input_common/drivers/sdl_driver.cpp15
-rw-r--r--src/input_common/drivers/sdl_driver.h3
-rw-r--r--src/input_common/drivers/tas_input.cpp1
-rw-r--r--src/input_common/drivers/virtual_amiibo.cpp15
-rw-r--r--src/input_common/drivers/virtual_amiibo.h3
-rw-r--r--src/input_common/helpers/stick_from_buttons.cpp25
-rw-r--r--src/input_common/helpers/touch_from_buttons.cpp22
-rw-r--r--src/input_common/input_engine.h2
-rw-r--r--src/input_common/input_poller.cpp18
-rw-r--r--src/input_common/main.cpp110
-rw-r--r--src/input_common/main.h3
-rw-r--r--src/input_common/precompiled_headers.h6
-rw-r--r--src/network/CMakeLists.txt5
-rw-r--r--src/network/precompiled_headers.h6
-rw-r--r--src/shader_recompiler/CMakeLists.txt7
-rw-r--r--src/shader_recompiler/backend/glasm/emit_glasm.cpp1
-rw-r--r--src/shader_recompiler/backend/glasm/emit_glasm_context_get_set.cpp3
-rw-r--r--src/shader_recompiler/backend/glsl/emit_glsl_context_get_set.cpp3
-rw-r--r--src/shader_recompiler/backend/spirv/emit_spirv.cpp13
-rw-r--r--src/shader_recompiler/backend/spirv/emit_spirv_context_get_set.cpp2
-rw-r--r--src/shader_recompiler/backend/spirv/emit_spirv_control_flow.cpp2
-rw-r--r--src/shader_recompiler/backend/spirv/emit_spirv_warp.cpp35
-rw-r--r--src/shader_recompiler/backend/spirv/spirv_emit_context.cpp5
-rw-r--r--src/shader_recompiler/frontend/ir/opcodes.h1
-rw-r--r--src/shader_recompiler/frontend/ir/value.h1
-rw-r--r--src/shader_recompiler/frontend/maxwell/control_flow.cpp1
-rw-r--r--src/shader_recompiler/frontend/maxwell/decode.cpp1
-rw-r--r--src/shader_recompiler/frontend/maxwell/structured_control_flow.cpp1
-rw-r--r--src/shader_recompiler/frontend/maxwell/translate/impl/floating_point_conversion_integer.cpp7
-rw-r--r--src/shader_recompiler/frontend/maxwell/translate_program.cpp81
-rw-r--r--src/shader_recompiler/frontend/maxwell/translate_program.h9
-rw-r--r--src/shader_recompiler/host_translate_info.h3
-rw-r--r--src/shader_recompiler/ir_opt/layer_pass.cpp68
-rw-r--r--src/shader_recompiler/ir_opt/passes.h1
-rw-r--r--src/shader_recompiler/precompiled_headers.h7
-rw-r--r--src/shader_recompiler/shader_info.h3
-rw-r--r--src/tests/CMakeLists.txt5
-rw-r--r--src/tests/precompiled_headers.h6
-rw-r--r--src/video_core/CMakeLists.txt23
-rw-r--r--src/video_core/buffer_cache/buffer_base.h2
-rw-r--r--src/video_core/buffer_cache/buffer_cache.h38
-rw-r--r--src/video_core/control/channel_state.cpp2
-rw-r--r--src/video_core/control/channel_state_cache.h2
-rw-r--r--src/video_core/engines/engine_upload.cpp11
-rw-r--r--src/video_core/engines/engine_upload.h2
-rw-r--r--src/video_core/engines/fermi_2d.cpp26
-rw-r--r--src/video_core/engines/fermi_2d.h11
-rw-r--r--src/video_core/engines/kepler_compute.cpp6
-rw-r--r--src/video_core/engines/kepler_compute.h14
-rw-r--r--src/video_core/engines/kepler_memory.cpp6
-rw-r--r--src/video_core/engines/maxwell_3d.cpp166
-rw-r--r--src/video_core/engines/maxwell_3d.h94
-rw-r--r--src/video_core/engines/maxwell_dma.cpp82
-rw-r--r--src/video_core/engines/maxwell_dma.h3
-rw-r--r--src/video_core/engines/puller.cpp14
-rw-r--r--src/video_core/engines/sw_blitter/blitter.cpp238
-rw-r--r--src/video_core/engines/sw_blitter/blitter.h27
-rw-r--r--src/video_core/engines/sw_blitter/converter.cpp1234
-rw-r--r--src/video_core/engines/sw_blitter/converter.h36
-rw-r--r--src/video_core/engines/sw_blitter/generate_converters.py136
-rw-r--r--src/video_core/gpu.h18
-rw-r--r--src/video_core/gpu_thread.cpp2
-rw-r--r--src/video_core/gpu_thread.h1
-rw-r--r--src/video_core/host1x/syncpoint_manager.cpp6
-rw-r--r--src/video_core/host1x/syncpoint_manager.h12
-rw-r--r--src/video_core/macro/macro_hle.cpp16
-rw-r--r--src/video_core/macro/macro_interpreter.cpp2
-rw-r--r--src/video_core/macro/macro_jit_x64.cpp1
-rw-r--r--src/video_core/precompiled_headers.h6
-rw-r--r--src/video_core/rasterizer_interface.h4
-rw-r--r--src/video_core/renderer_null/null_rasterizer.cpp90
-rw-r--r--src/video_core/renderer_null/null_rasterizer.h78
-rw-r--r--src/video_core/renderer_null/renderer_null.cpp24
-rw-r--r--src/video_core/renderer_null/renderer_null.h36
-rw-r--r--src/video_core/renderer_opengl/gl_device.cpp1
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.cpp17
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.h4
-rw-r--r--src/video_core/renderer_opengl/gl_shader_cache.cpp37
-rw-r--r--src/video_core/renderer_opengl/gl_shader_cache.h1
-rw-r--r--src/video_core/renderer_opengl/gl_texture_cache.cpp2
-rw-r--r--src/video_core/renderer_opengl/maxwell_to_gl.h1
-rw-r--r--src/video_core/renderer_opengl/renderer_opengl.cpp1
-rw-r--r--src/video_core/renderer_vulkan/fixed_pipeline_state.cpp1
-rw-r--r--src/video_core/renderer_vulkan/maxwell_to_vk.cpp9
-rw-r--r--src/video_core/renderer_vulkan/pipeline_helper.h14
-rw-r--r--src/video_core/renderer_vulkan/renderer_vulkan.cpp8
-rw-r--r--src/video_core/renderer_vulkan/vk_blit_screen.cpp1
-rw-r--r--src/video_core/renderer_vulkan/vk_compute_pass.cpp12
-rw-r--r--src/video_core/renderer_vulkan/vk_compute_pass.h4
-rw-r--r--src/video_core/renderer_vulkan/vk_compute_pipeline.cpp2
-rw-r--r--src/video_core/renderer_vulkan/vk_compute_pipeline.h2
-rw-r--r--src/video_core/renderer_vulkan/vk_descriptor_pool.cpp1
-rw-r--r--src/video_core/renderer_vulkan/vk_fsr.cpp6
-rw-r--r--src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp2
-rw-r--r--src/video_core/renderer_vulkan/vk_graphics_pipeline.h2
-rw-r--r--src/video_core/renderer_vulkan/vk_master_semaphore.cpp8
-rw-r--r--src/video_core/renderer_vulkan/vk_master_semaphore.h1
-rw-r--r--src/video_core/renderer_vulkan/vk_pipeline_cache.cpp55
-rw-r--r--src/video_core/renderer_vulkan/vk_query_cache.cpp2
-rw-r--r--src/video_core/renderer_vulkan/vk_rasterizer.cpp22
-rw-r--r--src/video_core/renderer_vulkan/vk_rasterizer.h4
-rw-r--r--src/video_core/renderer_vulkan/vk_render_pass_cache.h2
-rw-r--r--src/video_core/renderer_vulkan/vk_scheduler.cpp7
-rw-r--r--src/video_core/renderer_vulkan/vk_scheduler.h1
-rw-r--r--src/video_core/renderer_vulkan/vk_swapchain.cpp1
-rw-r--r--src/video_core/renderer_vulkan/vk_texture_cache.cpp1
-rw-r--r--src/video_core/shader_cache.h1
-rw-r--r--src/video_core/shader_environment.cpp1
-rw-r--r--src/video_core/shader_environment.h2
-rw-r--r--src/video_core/surface.cpp27
-rw-r--r--src/video_core/surface.h4
-rw-r--r--src/video_core/texture_cache/formatter.cpp1
-rw-r--r--src/video_core/texture_cache/formatter.h2
-rw-r--r--src/video_core/texture_cache/render_targets.h2
-rw-r--r--src/video_core/texture_cache/slot_vector.h1
-rw-r--r--src/video_core/texture_cache/texture_cache.h29
-rw-r--r--src/video_core/texture_cache/texture_cache_base.h11
-rw-r--r--src/video_core/textures/astc.cpp1
-rw-r--r--src/video_core/textures/decoders.cpp3
-rw-r--r--src/video_core/transform_feedback.cpp1
-rw-r--r--src/video_core/video_core.cpp4
-rw-r--r--src/video_core/vulkan_common/vulkan_device.cpp288
-rw-r--r--src/video_core/vulkan_common/vulkan_device.h18
-rw-r--r--src/video_core/vulkan_common/vulkan_instance.cpp28
-rw-r--r--src/video_core/vulkan_common/vulkan_memory_allocator.cpp1
-rw-r--r--src/video_core/vulkan_common/vulkan_surface.cpp38
-rw-r--r--src/video_core/vulkan_common/vulkan_wrapper.cpp68
-rw-r--r--src/video_core/vulkan_common/vulkan_wrapper.h49
-rw-r--r--src/web_service/CMakeLists.txt5
-rw-r--r--src/web_service/precompiled_headers.h6
-rw-r--r--src/yuzu/CMakeLists.txt40
-rw-r--r--src/yuzu/applets/qt_amiibo_settings.cpp264
-rw-r--r--src/yuzu/applets/qt_amiibo_settings.h83
-rw-r--r--src/yuzu/applets/qt_amiibo_settings.ui494
-rw-r--r--src/yuzu/bootmanager.cpp32
-rw-r--r--src/yuzu/bootmanager.h4
-rw-r--r--src/yuzu/compatdb.cpp1
-rw-r--r--src/yuzu/configuration/config.cpp5
-rw-r--r--src/yuzu/configuration/configure_camera.cpp7
-rw-r--r--src/yuzu/configuration/configure_camera.h2
-rw-r--r--src/yuzu/configuration/configure_graphics.cpp45
-rw-r--r--src/yuzu/configuration/configure_graphics.h2
-rw-r--r--src/yuzu/configuration/configure_graphics.ui151
-rw-r--r--src/yuzu/configuration/configure_input_advanced.cpp4
-rw-r--r--src/yuzu/main.cpp102
-rw-r--r--src/yuzu/main.h13
-rw-r--r--src/yuzu/main.ui9
-rw-r--r--src/yuzu/multiplayer/chat_room.h1
-rw-r--r--src/yuzu/multiplayer/direct_connect.cpp2
-rw-r--r--src/yuzu/multiplayer/validation.h16
-rw-r--r--src/yuzu/precompiled_headers.h6
-rw-r--r--src/yuzu/startup_checks.cpp84
-rw-r--r--src/yuzu/startup_checks.h4
-rw-r--r--src/yuzu_cmd/CMakeLists.txt14
-rw-r--r--src/yuzu_cmd/config.cpp7
-rw-r--r--src/yuzu_cmd/default_ini.h29
-rw-r--r--src/yuzu_cmd/emu_window/emu_window_sdl2.cpp2
-rw-r--r--src/yuzu_cmd/emu_window/emu_window_sdl2.h2
-rw-r--r--src/yuzu_cmd/emu_window/emu_window_sdl2_null.cpp51
-rw-r--r--src/yuzu_cmd/emu_window/emu_window_sdl2_null.h26
-rw-r--r--src/yuzu_cmd/emu_window/emu_window_sdl2_vk.cpp34
-rw-r--r--src/yuzu_cmd/emu_window/emu_window_sdl2_vk.h2
-rw-r--r--src/yuzu_cmd/precompiled_headers.h6
-rw-r--r--src/yuzu_cmd/yuzu.cpp5
292 files changed, 7386 insertions, 1136 deletions
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 0ac3d254e..140415474 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -82,8 +82,9 @@ if (MSVC)
/wd4324 # 'struct_name': structure was padded due to __declspec(align())
)
- if (USE_CCACHE)
+ if (USE_CCACHE OR YUZU_USE_PRECOMPILED_HEADERS)
# when caching, we need to use /Z7 to downgrade debug info to use an older but more cachable format
+ # Precompiled headers are deleted if not using /Z7. See https://github.com/nanoant/CMakePCHCompiler/issues/21
add_compile_options(/Z7)
else()
add_compile_options(/Zi)
@@ -112,6 +113,8 @@ else()
$<$<CXX_COMPILER_ID:Clang>:-Wno-braced-scalar-init>
$<$<CXX_COMPILER_ID:Clang>:-Wno-unused-private-field>
+ $<$<CXX_COMPILER_ID:AppleClang>:-Wno-braced-scalar-init>
+ $<$<CXX_COMPILER_ID:AppleClang>:-Wno-unused-private-field>
)
if (ARCHITECTURE_x86_64)
diff --git a/src/audio_core/CMakeLists.txt b/src/audio_core/CMakeLists.txt
index 8e3a8f5a8..0a9d9ec29 100644
--- a/src/audio_core/CMakeLists.txt
+++ b/src/audio_core/CMakeLists.txt
@@ -31,6 +31,7 @@ add_library(audio_core STATIC
out/audio_out.h
out/audio_out_system.cpp
out/audio_out_system.h
+ precompiled_headers.h
renderer/adsp/adsp.cpp
renderer/adsp/adsp.h
renderer/adsp/audio_renderer.cpp
@@ -226,6 +227,14 @@ if(ENABLE_CUBEB)
target_compile_definitions(audio_core PRIVATE -DHAVE_CUBEB=1)
endif()
if(ENABLE_SDL2)
- target_link_libraries(audio_core PRIVATE SDL2)
+ if (YUZU_USE_EXTERNAL_SDL2)
+ target_link_libraries(audio_core PRIVATE SDL2-static)
+ else()
+ target_link_libraries(audio_core PRIVATE SDL2)
+ endif()
target_compile_definitions(audio_core PRIVATE HAVE_SDL2)
endif()
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(audio_core PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/audio_core/audio_event.cpp b/src/audio_core/audio_event.cpp
index 424049c7a..d15568e1f 100644
--- a/src/audio_core/audio_event.cpp
+++ b/src/audio_core/audio_event.cpp
@@ -3,6 +3,7 @@
#include "audio_core/audio_event.h"
#include "common/assert.h"
+#include "common/polyfill_ranges.h"
namespace AudioCore {
diff --git a/src/audio_core/audio_manager.h b/src/audio_core/audio_manager.h
index abf077de4..02270242a 100644
--- a/src/audio_core/audio_manager.h
+++ b/src/audio_core/audio_manager.h
@@ -9,6 +9,8 @@
#include <mutex>
#include <thread>
+#include "common/polyfill_thread.h"
+
#include "audio_core/audio_event.h"
union Result;
diff --git a/src/audio_core/audio_render_manager.h b/src/audio_core/audio_render_manager.h
index bf4837190..fffa5944d 100644
--- a/src/audio_core/audio_render_manager.h
+++ b/src/audio_core/audio_render_manager.h
@@ -7,6 +7,8 @@
#include <memory>
#include <mutex>
+#include "common/polyfill_thread.h"
+
#include "audio_core/common/common.h"
#include "audio_core/renderer/system_manager.h"
#include "core/hle/service/audio/errors.h"
diff --git a/src/audio_core/common/feature_support.h b/src/audio_core/common/feature_support.h
index 55c9e690d..e71905ae8 100644
--- a/src/audio_core/common/feature_support.h
+++ b/src/audio_core/common/feature_support.h
@@ -10,6 +10,7 @@
#include "common/assert.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
+#include "common/polyfill_ranges.h"
namespace AudioCore {
constexpr u32 CurrentRevision = 11;
diff --git a/src/audio_core/precompiled_headers.h b/src/audio_core/precompiled_headers.h
new file mode 100644
index 000000000..aabae730b
--- /dev/null
+++ b/src/audio_core/precompiled_headers.h
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
diff --git a/src/audio_core/renderer/command/command_buffer.cpp b/src/audio_core/renderer/command/command_buffer.cpp
index 2ef879ee1..8c6fe97e7 100644
--- a/src/audio_core/renderer/command/command_buffer.cpp
+++ b/src/audio_core/renderer/command/command_buffer.cpp
@@ -460,21 +460,23 @@ void CommandBuffer::GenerateDeviceSinkCommand(const s32 node_id, const s16 buffe
cmd.session_id = session_id;
+ cmd.input_count = parameter.input_count;
+ s16 max_input{0};
+ for (u32 i = 0; i < parameter.input_count; i++) {
+ cmd.inputs[i] = buffer_offset + parameter.inputs[i];
+ max_input = std::max(max_input, cmd.inputs[i]);
+ }
+
if (state.upsampler_info != nullptr) {
const auto size_{state.upsampler_info->sample_count * parameter.input_count};
const auto size_bytes{size_ * sizeof(s32)};
const auto addr{memory_pool->Translate(state.upsampler_info->samples_pos, size_bytes)};
cmd.sample_buffer = {reinterpret_cast<s32*>(addr),
- parameter.input_count * state.upsampler_info->sample_count};
+ (max_input + 1) * state.upsampler_info->sample_count};
} else {
cmd.sample_buffer = samples_buffer;
}
- cmd.input_count = parameter.input_count;
- for (u32 i = 0; i < parameter.input_count; i++) {
- cmd.inputs[i] = buffer_offset + parameter.inputs[i];
- }
-
GenerateEnd<DeviceSinkCommand>(cmd);
}
diff --git a/src/audio_core/renderer/command/effect/i3dl2_reverb.cpp b/src/audio_core/renderer/command/effect/i3dl2_reverb.cpp
index c4bf3943a..2187d8a65 100644
--- a/src/audio_core/renderer/command/effect/i3dl2_reverb.cpp
+++ b/src/audio_core/renderer/command/effect/i3dl2_reverb.cpp
@@ -5,6 +5,7 @@
#include "audio_core/renderer/adsp/command_list_processor.h"
#include "audio_core/renderer/command/effect/i3dl2_reverb.h"
+#include "common/polyfill_ranges.h"
namespace AudioCore::AudioRenderer {
diff --git a/src/audio_core/renderer/command/effect/reverb.cpp b/src/audio_core/renderer/command/effect/reverb.cpp
index fe2b1eb43..427489214 100644
--- a/src/audio_core/renderer/command/effect/reverb.cpp
+++ b/src/audio_core/renderer/command/effect/reverb.cpp
@@ -6,6 +6,7 @@
#include "audio_core/renderer/adsp/command_list_processor.h"
#include "audio_core/renderer/command/effect/reverb.h"
+#include "common/polyfill_ranges.h"
namespace AudioCore::AudioRenderer {
diff --git a/src/audio_core/renderer/mix/mix_context.cpp b/src/audio_core/renderer/mix/mix_context.cpp
index 2427c83ed..35b748ede 100644
--- a/src/audio_core/renderer/mix/mix_context.cpp
+++ b/src/audio_core/renderer/mix/mix_context.cpp
@@ -5,6 +5,7 @@
#include "audio_core/renderer/mix/mix_context.h"
#include "audio_core/renderer/splitter/splitter_context.h"
+#include "common/polyfill_ranges.h"
namespace AudioCore::AudioRenderer {
diff --git a/src/audio_core/renderer/performance/performance_manager.cpp b/src/audio_core/renderer/performance/performance_manager.cpp
index fd5873e1e..8aa0f5ed0 100644
--- a/src/audio_core/renderer/performance/performance_manager.cpp
+++ b/src/audio_core/renderer/performance/performance_manager.cpp
@@ -26,6 +26,7 @@ void PerformanceManager::CreateImpl(const size_t version) {
impl = std::make_unique<
PerformanceManagerImpl<PerformanceVersion::Version1, PerformanceFrameHeaderVersion1,
PerformanceEntryVersion1, PerformanceDetailVersion1>>();
+ break;
}
}
diff --git a/src/audio_core/renderer/voice/voice_context.cpp b/src/audio_core/renderer/voice/voice_context.cpp
index a501a677d..16a3e839d 100644
--- a/src/audio_core/renderer/voice/voice_context.cpp
+++ b/src/audio_core/renderer/voice/voice_context.cpp
@@ -4,6 +4,7 @@
#include <ranges>
#include "audio_core/renderer/voice/voice_context.h"
+#include "common/polyfill_ranges.h"
namespace AudioCore::AudioRenderer {
diff --git a/src/audio_core/sink/sink_stream.cpp b/src/audio_core/sink/sink_stream.cpp
index 849f862b0..06c2a876e 100644
--- a/src/audio_core/sink/sink_stream.cpp
+++ b/src/audio_core/sink/sink_stream.cpp
@@ -170,8 +170,8 @@ void SinkStream::ProcessAudioIn(std::span<const s16> input_buffer, std::size_t n
// Get the minimum frames available between the currently playing buffer, and the
// amount we have left to fill
- size_t frames_available{std::min(playing_buffer.frames - playing_buffer.frames_played,
- num_frames - frames_written)};
+ size_t frames_available{std::min<u64>(playing_buffer.frames - playing_buffer.frames_played,
+ num_frames - frames_written)};
samples_buffer.Push(&input_buffer[frames_written * frame_size],
frames_available * frame_size);
@@ -241,8 +241,8 @@ void SinkStream::ProcessAudioOutAndRender(std::span<s16> output_buffer, std::siz
// Get the minimum frames available between the currently playing buffer, and the
// amount we have left to fill
- size_t frames_available{std::min(playing_buffer.frames - playing_buffer.frames_played,
- num_frames - frames_written)};
+ size_t frames_available{std::min<u64>(playing_buffer.frames - playing_buffer.frames_played,
+ num_frames - frames_written)};
samples_buffer.Pop(&output_buffer[frames_written * frame_size],
frames_available * frame_size);
@@ -266,19 +266,20 @@ void SinkStream::ProcessAudioOutAndRender(std::span<s16> output_buffer, std::siz
}
void SinkStream::Stall() {
- if (stalled) {
+ std::scoped_lock lk{stall_guard};
+ if (stalled_lock) {
return;
}
- stalled = true;
- system.StallProcesses();
+ stalled_lock = system.StallProcesses();
}
void SinkStream::Unstall() {
- if (!stalled) {
+ std::scoped_lock lk{stall_guard};
+ if (!stalled_lock) {
return;
}
system.UnstallProcesses();
- stalled = false;
+ stalled_lock.unlock();
}
} // namespace AudioCore::Sink
diff --git a/src/audio_core/sink/sink_stream.h b/src/audio_core/sink/sink_stream.h
index 38a4b2f51..5fea72ab7 100644
--- a/src/audio_core/sink/sink_stream.h
+++ b/src/audio_core/sink/sink_stream.h
@@ -6,6 +6,7 @@
#include <array>
#include <atomic>
#include <memory>
+#include <mutex>
#include <span>
#include <vector>
@@ -240,8 +241,8 @@ private:
f32 system_volume{1.0f};
/// Set via IAudioDevice service calls
f32 device_volume{1.0f};
- /// True if coretiming has been stalled
- bool stalled{false};
+ std::mutex stall_guard;
+ std::unique_lock<std::mutex> stalled_lock;
};
using SinkStreamPtr = std::unique_ptr<SinkStream>;
diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt
index c0555f840..a12edc584 100644
--- a/src/common/CMakeLists.txt
+++ b/src/common/CMakeLists.txt
@@ -34,7 +34,10 @@ add_library(common STATIC
bit_util.h
cityhash.cpp
cityhash.h
+ cache_management.cpp
+ cache_management.h
common_funcs.h
+ common_precompiled_headers.h
common_types.h
concepts.h
div_ceil.h
@@ -93,6 +96,7 @@ add_library(common STATIC
param_package.h
parent_of_member.h
point.h
+ precompiled_headers.h
quaternion.h
reader_writer_queue.h
ring_buffer.h
@@ -181,3 +185,7 @@ else()
target_link_libraries(common PRIVATE
$<IF:$<TARGET_EXISTS:zstd::libzstd_shared>,zstd::libzstd_shared,zstd::libzstd_static>)
endif()
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(common PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/common/atomic_helpers.h b/src/common/atomic_helpers.h
index bef5015c1..aef3b66a4 100644
--- a/src/common/atomic_helpers.h
+++ b/src/common/atomic_helpers.h
@@ -156,6 +156,7 @@ AE_FORCEINLINE void compiler_fence(memory_order order) AE_NO_TSAN {
break;
default:
assert(false);
+ break;
}
}
diff --git a/src/common/cache_management.cpp b/src/common/cache_management.cpp
new file mode 100644
index 000000000..ed353828a
--- /dev/null
+++ b/src/common/cache_management.cpp
@@ -0,0 +1,59 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include <cstdint>
+#include <cstring>
+
+#include "common/cache_management.h"
+
+namespace Common {
+
+#if defined(ARCHITECTURE_x86_64)
+
+// Most cache operations are no-ops on x86
+
+void DataCacheLineCleanByVAToPoU(void* start, size_t size) {}
+void DataCacheLineCleanAndInvalidateByVAToPoC(void* start, size_t size) {}
+void DataCacheLineCleanByVAToPoC(void* start, size_t size) {}
+void DataCacheZeroByVA(void* start, size_t size) {
+ std::memset(start, 0, size);
+}
+
+#elif defined(ARCHITECTURE_arm64)
+
+// BS/DminLine is log2(cache size in words), we want size in bytes
+#define EXTRACT_DMINLINE(ctr_el0) (1 << ((((ctr_el0) >> 16) & 0xf) + 2))
+#define EXTRACT_BS(dczid_el0) (1 << (((dczid_el0)&0xf) + 2))
+
+#define DEFINE_DC_OP(op_name, function_name) \
+ void function_name(void* start, size_t size) { \
+ size_t ctr_el0; \
+ asm volatile("mrs %[ctr_el0], ctr_el0\n\t" : [ctr_el0] "=r"(ctr_el0)); \
+ size_t cacheline_size = EXTRACT_DMINLINE(ctr_el0); \
+ uintptr_t va_start = reinterpret_cast<uintptr_t>(start); \
+ uintptr_t va_end = va_start + size; \
+ for (uintptr_t va = va_start; va < va_end; va += cacheline_size) { \
+ asm volatile("dc " #op_name ", %[va]\n\t" : : [va] "r"(va) : "memory"); \
+ } \
+ }
+
+#define DEFINE_DC_OP_DCZID(op_name, function_name) \
+ void function_name(void* start, size_t size) { \
+ size_t dczid_el0; \
+ asm volatile("mrs %[dczid_el0], dczid_el0\n\t" : [dczid_el0] "=r"(dczid_el0)); \
+ size_t cacheline_size = EXTRACT_BS(dczid_el0); \
+ uintptr_t va_start = reinterpret_cast<uintptr_t>(start); \
+ uintptr_t va_end = va_start + size; \
+ for (uintptr_t va = va_start; va < va_end; va += cacheline_size) { \
+ asm volatile("dc " #op_name ", %[va]\n\t" : : [va] "r"(va) : "memory"); \
+ } \
+ }
+
+DEFINE_DC_OP(cvau, DataCacheLineCleanByVAToPoU);
+DEFINE_DC_OP(civac, DataCacheLineCleanAndInvalidateByVAToPoC);
+DEFINE_DC_OP(cvac, DataCacheLineCleanByVAToPoC);
+DEFINE_DC_OP_DCZID(zva, DataCacheZeroByVA);
+
+#endif
+
+} // namespace Common
diff --git a/src/common/cache_management.h b/src/common/cache_management.h
new file mode 100644
index 000000000..038323e95
--- /dev/null
+++ b/src/common/cache_management.h
@@ -0,0 +1,27 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include <cstddef>
+
+namespace Common {
+
+// Data cache instructions enabled at EL0 by SCTLR_EL1.UCI.
+// VA = virtual address
+// PoC = point of coherency
+// PoU = point of unification
+
+// dc cvau
+void DataCacheLineCleanByVAToPoU(void* start, size_t size);
+
+// dc civac
+void DataCacheLineCleanAndInvalidateByVAToPoC(void* start, size_t size);
+
+// dc cvac
+void DataCacheLineCleanByVAToPoC(void* start, size_t size);
+
+// dc zva
+void DataCacheZeroByVA(void* start, size_t size);
+
+} // namespace Common
diff --git a/src/common/common_precompiled_headers.h b/src/common/common_precompiled_headers.h
new file mode 100644
index 000000000..be7e5b5f9
--- /dev/null
+++ b/src/common/common_precompiled_headers.h
@@ -0,0 +1,14 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <chrono>
+#include <memory>
+
+#include <fmt/format.h>
+
+#include "common/assert.h"
+#include "common/common_types.h"
diff --git a/src/common/fs/file.cpp b/src/common/fs/file.cpp
index fa8422c41..656b03cc5 100644
--- a/src/common/fs/file.cpp
+++ b/src/common/fs/file.cpp
@@ -1,6 +1,8 @@
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
+#include <vector>
+
#include "common/fs/file.h"
#include "common/fs/fs.h"
#include "common/logging/log.h"
diff --git a/src/common/fs/fs_util.cpp b/src/common/fs/fs_util.cpp
index eb4ac1deb..813a713c3 100644
--- a/src/common/fs/fs_util.cpp
+++ b/src/common/fs/fs_util.cpp
@@ -4,6 +4,7 @@
#include <algorithm>
#include "common/fs/fs_util.h"
+#include "common/polyfill_ranges.h"
namespace Common::FS {
diff --git a/src/common/fs/path_util.cpp b/src/common/fs/path_util.cpp
index 1074f2421..defa3e918 100644
--- a/src/common/fs/path_util.cpp
+++ b/src/common/fs/path_util.cpp
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-2.0-or-later
#include <algorithm>
+#include <sstream>
#include <unordered_map>
#include "common/fs/fs.h"
diff --git a/src/common/input.h b/src/common/input.h
index cb30b7254..fc14fd7bf 100644
--- a/src/common/input.h
+++ b/src/common/input.h
@@ -8,6 +8,7 @@
#include <string>
#include <unordered_map>
#include <utility>
+#include <vector>
#include "common/logging/log.h"
#include "common/param_package.h"
#include "common/uuid.h"
@@ -383,6 +384,16 @@ void RegisterFactory(const std::string& name, std::shared_ptr<Factory<InputDevic
}
}
+inline void RegisterInputFactory(const std::string& name,
+ std::shared_ptr<Factory<InputDevice>> factory) {
+ RegisterFactory<InputDevice>(name, std::move(factory));
+}
+
+inline void RegisterOutputFactory(const std::string& name,
+ std::shared_ptr<Factory<OutputDevice>> factory) {
+ RegisterFactory<OutputDevice>(name, std::move(factory));
+}
+
/**
* Unregisters an input device factory.
* @tparam InputDeviceType the type of input devices the factory can create
@@ -395,6 +406,14 @@ void UnregisterFactory(const std::string& name) {
}
}
+inline void UnregisterInputFactory(const std::string& name) {
+ UnregisterFactory<InputDevice>(name);
+}
+
+inline void UnregisterOutputFactory(const std::string& name) {
+ UnregisterFactory<OutputDevice>(name);
+}
+
/**
* Create an input device from given paramters.
* @tparam InputDeviceType the type of input devices to create
@@ -416,13 +435,21 @@ std::unique_ptr<InputDeviceType> CreateDeviceFromString(const std::string& param
return pair->second->Create(package);
}
+inline std::unique_ptr<InputDevice> CreateInputDeviceFromString(const std::string& params) {
+ return CreateDeviceFromString<InputDevice>(params);
+}
+
+inline std::unique_ptr<OutputDevice> CreateOutputDeviceFromString(const std::string& params) {
+ return CreateDeviceFromString<OutputDevice>(params);
+}
+
/**
- * Create an input device from given paramters.
+ * Create an input device from given parameters.
* @tparam InputDeviceType the type of input devices to create
- * @param A ParamPackage that contains all parameters for creating the device
+ * @param package A ParamPackage that contains all parameters for creating the device
*/
template <typename InputDeviceType>
-std::unique_ptr<InputDeviceType> CreateDevice(const Common::ParamPackage package) {
+std::unique_ptr<InputDeviceType> CreateDevice(const ParamPackage& package) {
const std::string engine = package.Get("engine", "null");
const auto& factory_list = Impl::FactoryList<InputDeviceType>::list;
const auto pair = factory_list.find(engine);
@@ -435,4 +462,12 @@ std::unique_ptr<InputDeviceType> CreateDevice(const Common::ParamPackage package
return pair->second->Create(package);
}
+inline std::unique_ptr<InputDevice> CreateInputDevice(const ParamPackage& package) {
+ return CreateDevice<InputDevice>(package);
+}
+
+inline std::unique_ptr<OutputDevice> CreateOutputDevice(const ParamPackage& package) {
+ return CreateDevice<OutputDevice>(package);
+}
+
} // namespace Common::Input
diff --git a/src/common/logging/backend.cpp b/src/common/logging/backend.cpp
index 15d92505e..2a3bded40 100644
--- a/src/common/logging/backend.cpp
+++ b/src/common/logging/backend.cpp
@@ -4,7 +4,6 @@
#include <atomic>
#include <chrono>
#include <climits>
-#include <stop_token>
#include <thread>
#include <fmt/format.h>
@@ -18,6 +17,7 @@
#include "common/fs/fs_paths.h"
#include "common/fs/path_util.h"
#include "common/literals.h"
+#include "common/polyfill_thread.h"
#include "common/thread.h"
#include "common/logging/backend.h"
diff --git a/src/common/polyfill_ranges.h b/src/common/polyfill_ranges.h
new file mode 100644
index 000000000..ca44bfaef
--- /dev/null
+++ b/src/common/polyfill_ranges.h
@@ -0,0 +1,530 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+//
+// TODO: remove this file when ranges are supported by all compilation targets
+//
+
+#pragma once
+
+#include <algorithm>
+#include <utility>
+#include <version>
+
+#ifndef __cpp_lib_ranges
+
+namespace std {
+namespace ranges {
+
+template <typename T>
+concept range = requires(T& t) {
+ begin(t);
+ end(t);
+};
+
+template <typename T>
+concept input_range = range<T>;
+
+template <typename T>
+concept output_range = range<T>;
+
+template <range R>
+using range_difference_t = ptrdiff_t;
+
+//
+// find, find_if, find_if_not
+//
+
+struct find_fn {
+ template <typename Iterator, typename T, typename Proj = std::identity>
+ constexpr Iterator operator()(Iterator first, Iterator last, const T& value,
+ Proj proj = {}) const {
+ for (; first != last; ++first) {
+ if (std::invoke(proj, *first) == value) {
+ return first;
+ }
+ }
+ return first;
+ }
+
+ template <ranges::input_range R, typename T, typename Proj = std::identity>
+ constexpr ranges::iterator_t<R> operator()(R&& r, const T& value, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), value, std::ref(proj));
+ }
+};
+
+struct find_if_fn {
+ template <typename Iterator, typename Proj = std::identity, typename Pred>
+ constexpr Iterator operator()(Iterator first, Iterator last, Pred pred, Proj proj = {}) const {
+ for (; first != last; ++first) {
+ if (std::invoke(pred, std::invoke(proj, *first))) {
+ return first;
+ }
+ }
+ return first;
+ }
+
+ template <ranges::input_range R, typename Proj = std::identity, typename Pred>
+ constexpr ranges::iterator_t<R> operator()(R&& r, Pred pred, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
+ }
+};
+
+struct find_if_not_fn {
+ template <typename Iterator, typename Proj = std::identity, typename Pred>
+ constexpr Iterator operator()(Iterator first, Iterator last, Pred pred, Proj proj = {}) const {
+ for (; first != last; ++first) {
+ if (!std::invoke(pred, std::invoke(proj, *first))) {
+ return first;
+ }
+ }
+ return first;
+ }
+
+ template <ranges::input_range R, typename Proj = std::identity, typename Pred>
+ constexpr ranges::iterator_t<R> operator()(R&& r, Pred pred, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
+ }
+};
+
+inline constexpr find_fn find;
+inline constexpr find_if_fn find_if;
+inline constexpr find_if_not_fn find_if_not;
+
+//
+// any_of, all_of, none_of
+//
+
+struct all_of_fn {
+ template <typename Iterator, typename Proj = std::identity, typename Pred>
+ constexpr bool operator()(Iterator first, Iterator last, Pred pred, Proj proj = {}) const {
+ return ranges::find_if_not(first, last, std::ref(pred), std::ref(proj)) == last;
+ }
+
+ template <ranges::input_range R, typename Proj = std::identity, typename Pred>
+ constexpr bool operator()(R&& r, Pred pred, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
+ }
+};
+
+struct any_of_fn {
+ template <typename Iterator, typename Proj = std::identity, typename Pred>
+ constexpr bool operator()(Iterator first, Iterator last, Pred pred, Proj proj = {}) const {
+ return ranges::find_if(first, last, std::ref(pred), std::ref(proj)) != last;
+ }
+
+ template <ranges::input_range R, typename Proj = std::identity, typename Pred>
+ constexpr bool operator()(R&& r, Pred pred, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
+ }
+};
+
+struct none_of_fn {
+ template <typename Iterator, typename Proj = std::identity, typename Pred>
+ constexpr bool operator()(Iterator first, Iterator last, Pred pred, Proj proj = {}) const {
+ return ranges::find_if(first, last, std::ref(pred), std::ref(proj)) == last;
+ }
+
+ template <ranges::input_range R, typename Proj = std::identity, typename Pred>
+ constexpr bool operator()(R&& r, Pred pred, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
+ }
+};
+
+inline constexpr any_of_fn any_of;
+inline constexpr all_of_fn all_of;
+inline constexpr none_of_fn none_of;
+
+//
+// count, count_if
+//
+
+struct count_fn {
+ template <typename Iterator, typename T, typename Proj = std::identity>
+ constexpr ptrdiff_t operator()(Iterator first, Iterator last, const T& value,
+ Proj proj = {}) const {
+ ptrdiff_t counter = 0;
+ for (; first != last; ++first)
+ if (std::invoke(proj, *first) == value)
+ ++counter;
+ return counter;
+ }
+
+ template <ranges::input_range R, typename T, typename Proj = std::identity>
+ constexpr ptrdiff_t operator()(R&& r, const T& value, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), value, std::ref(proj));
+ }
+};
+
+struct count_if_fn {
+ template <typename Iterator, typename Proj = std::identity, typename Pred>
+ constexpr ptrdiff_t operator()(Iterator first, Iterator last, Pred pred, Proj proj = {}) const {
+ ptrdiff_t counter = 0;
+ for (; first != last; ++first)
+ if (std::invoke(pred, std::invoke(proj, *first)))
+ ++counter;
+ return counter;
+ }
+
+ template <ranges::input_range R, typename Proj = std::identity, typename Pred>
+ constexpr ptrdiff_t operator()(R&& r, Pred pred, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
+ }
+};
+
+inline constexpr count_fn count;
+inline constexpr count_if_fn count_if;
+
+//
+// transform
+//
+
+struct transform_fn {
+ template <typename InputIterator, typename OutputIterator, typename F,
+ typename Proj = std::identity>
+ constexpr void operator()(InputIterator first1, InputIterator last1, OutputIterator result,
+ F op, Proj proj = {}) const {
+ for (; first1 != last1; ++first1, (void)++result) {
+ *result = std::invoke(op, std::invoke(proj, *first1));
+ }
+ }
+
+ template <ranges::input_range R, typename OutputIterator, typename F,
+ typename Proj = std::identity>
+ constexpr void operator()(R&& r, OutputIterator result, F op, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), result, std::ref(op), std::ref(proj));
+ }
+};
+
+inline constexpr transform_fn transform;
+
+//
+// sort
+//
+
+struct sort_fn {
+ template <typename Iterator, typename Comp = ranges::less, typename Proj = std::identity>
+ constexpr void operator()(Iterator first, Iterator last, Comp comp = {}, Proj proj = {}) const {
+ if (first == last)
+ return;
+
+ Iterator last_iter = ranges::next(first, last);
+ std::sort(first, last_iter,
+ [&](auto& lhs, auto& rhs) { return comp(proj(lhs), proj(rhs)); });
+ }
+
+ template <ranges::input_range R, typename Comp = ranges::less, typename Proj = std::identity>
+ constexpr void operator()(R&& r, Comp comp = {}, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj));
+ }
+};
+
+inline constexpr sort_fn sort;
+
+//
+// fill
+//
+
+struct fill_fn {
+ template <typename T, typename OutputIterator>
+ constexpr OutputIterator operator()(OutputIterator first, OutputIterator last,
+ const T& value) const {
+ while (first != last) {
+ *first++ = value;
+ }
+
+ return first;
+ }
+
+ template <typename T, ranges::output_range R>
+ constexpr ranges::iterator_t<R> operator()(R&& r, const T& value) const {
+ return operator()(ranges::begin(r), ranges::end(r), value);
+ }
+};
+
+inline constexpr fill_fn fill;
+
+//
+// for_each
+//
+
+struct for_each_fn {
+ template <typename Iterator, typename Proj = std::identity, typename Fun>
+ constexpr void operator()(Iterator first, Iterator last, Fun f, Proj proj = {}) const {
+ for (; first != last; ++first) {
+ std::invoke(f, std::invoke(proj, *first));
+ }
+ }
+
+ template <ranges::input_range R, typename Proj = std::identity, typename Fun>
+ constexpr void operator()(R&& r, Fun f, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::move(f), std::ref(proj));
+ }
+};
+
+inline constexpr for_each_fn for_each;
+
+//
+// min_element, max_element
+//
+
+struct min_element_fn {
+ template <typename Iterator, typename Proj = std::identity, typename Comp = ranges::less>
+ constexpr Iterator operator()(Iterator first, Iterator last, Comp comp = {},
+ Proj proj = {}) const {
+ if (first == last) {
+ return last;
+ }
+
+ auto smallest = first;
+ ++first;
+ for (; first != last; ++first) {
+ if (!std::invoke(comp, std::invoke(proj, *smallest), std::invoke(proj, *first))) {
+ smallest = first;
+ }
+ }
+ return smallest;
+ }
+
+ template <ranges::input_range R, typename Proj = std::identity, typename Comp = ranges::less>
+ constexpr ranges::iterator_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj));
+ }
+};
+
+struct max_element_fn {
+ template <typename Iterator, typename Proj = std::identity, typename Comp = ranges::less>
+ constexpr Iterator operator()(Iterator first, Iterator last, Comp comp = {},
+ Proj proj = {}) const {
+ if (first == last) {
+ return last;
+ }
+
+ auto largest = first;
+ ++first;
+ for (; first != last; ++first) {
+ if (std::invoke(comp, std::invoke(proj, *largest), std::invoke(proj, *first))) {
+ largest = first;
+ }
+ }
+ return largest;
+ }
+
+ template <ranges::input_range R, typename Proj = std::identity, typename Comp = ranges::less>
+ constexpr ranges::iterator_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj));
+ }
+};
+
+inline constexpr min_element_fn min_element;
+inline constexpr max_element_fn max_element;
+
+//
+// replace, replace_if
+//
+
+struct replace_fn {
+ template <typename Iterator, typename T1, typename T2, typename Proj = std::identity>
+ constexpr Iterator operator()(Iterator first, Iterator last, const T1& old_value,
+ const T2& new_value, Proj proj = {}) const {
+ for (; first != last; ++first) {
+ if (old_value == std::invoke(proj, *first)) {
+ *first = new_value;
+ }
+ }
+ return first;
+ }
+
+ template <ranges::input_range R, typename T1, typename T2, typename Proj = std::identity>
+ constexpr ranges::iterator_t<R> operator()(R&& r, const T1& old_value, const T2& new_value,
+ Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), old_value, new_value, std::move(proj));
+ }
+};
+
+struct replace_if_fn {
+ template <typename Iterator, typename T, typename Proj = std::identity, typename Pred>
+ constexpr Iterator operator()(Iterator first, Iterator last, Pred pred, const T& new_value,
+ Proj proj = {}) const {
+ for (; first != last; ++first) {
+ if (!!std::invoke(pred, std::invoke(proj, *first))) {
+ *first = new_value;
+ }
+ }
+ return std::move(first);
+ }
+
+ template <ranges::input_range R, typename T, typename Proj = std::identity, typename Pred>
+ constexpr ranges::iterator_t<R> operator()(R&& r, Pred pred, const T& new_value,
+ Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::move(pred), new_value,
+ std::move(proj));
+ }
+};
+
+inline constexpr replace_fn replace;
+inline constexpr replace_if_fn replace_if;
+
+//
+// copy, copy_if
+//
+
+struct copy_fn {
+ template <typename InputIterator, typename OutputIterator>
+ constexpr void operator()(InputIterator first, InputIterator last,
+ OutputIterator result) const {
+ for (; first != last; ++first, (void)++result) {
+ *result = *first;
+ }
+ }
+
+ template <ranges::input_range R, typename OutputIterator>
+ constexpr void operator()(R&& r, OutputIterator result) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::move(result));
+ }
+};
+
+struct copy_if_fn {
+ template <typename InputIterator, typename OutputIterator, typename Proj = std::identity,
+ typename Pred>
+ constexpr void operator()(InputIterator first, InputIterator last, OutputIterator result,
+ Pred pred, Proj proj = {}) const {
+ for (; first != last; ++first) {
+ if (std::invoke(pred, std::invoke(proj, *first))) {
+ *result = *first;
+ ++result;
+ }
+ }
+ }
+
+ template <ranges::input_range R, typename OutputIterator, typename Proj = std::identity,
+ typename Pred>
+ constexpr void operator()(R&& r, OutputIterator result, Pred pred, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::move(result), std::ref(pred),
+ std::ref(proj));
+ }
+};
+
+inline constexpr copy_fn copy;
+inline constexpr copy_if_fn copy_if;
+
+//
+// generate
+//
+
+struct generate_fn {
+ template <typename Iterator, typename F>
+ constexpr Iterator operator()(Iterator first, Iterator last, F gen) const {
+ for (; first != last; *first = std::invoke(gen), ++first)
+ ;
+ return first;
+ }
+
+ template <typename R, std::copy_constructible F>
+ requires std::invocable<F&> && ranges::output_range<R>
+ constexpr ranges::iterator_t<R> operator()(R&& r, F gen) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::move(gen));
+ }
+};
+
+inline constexpr generate_fn generate;
+
+//
+// lower_bound, upper_bound
+//
+
+struct lower_bound_fn {
+ template <typename Iterator, typename T, typename Proj = std::identity,
+ typename Comp = ranges::less>
+ constexpr Iterator operator()(Iterator first, Iterator last, const T& value, Comp comp = {},
+ Proj proj = {}) const {
+ Iterator it;
+ std::ptrdiff_t _count, _step;
+ _count = std::distance(first, last);
+
+ while (_count > 0) {
+ it = first;
+ _step = _count / 2;
+ ranges::advance(it, _step, last);
+ if (comp(std::invoke(proj, *it), value)) {
+ first = ++it;
+ _count -= _step + 1;
+ } else {
+ _count = _step;
+ }
+ }
+ return first;
+ }
+
+ template <ranges::input_range R, typename T, typename Proj = std::identity,
+ typename Comp = ranges::less>
+ constexpr ranges::iterator_t<R> operator()(R&& r, const T& value, Comp comp = {},
+ Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), value, std::ref(comp), std::ref(proj));
+ }
+};
+
+struct upper_bound_fn {
+ template <typename Iterator, typename T, typename Proj = std::identity,
+ typename Comp = ranges::less>
+ constexpr Iterator operator()(Iterator first, Iterator last, const T& value, Comp comp = {},
+ Proj proj = {}) const {
+ Iterator it;
+ std::ptrdiff_t _count, _step;
+ _count = std::distance(first, last);
+
+ while (_count > 0) {
+ it = first;
+ _step = _count / 2;
+ ranges::advance(it, _step, last);
+ if (!comp(value, std::invoke(proj, *it))) {
+ first = ++it;
+ _count -= _step + 1;
+ } else {
+ _count = _step;
+ }
+ }
+ return first;
+ }
+
+ template <ranges::input_range R, typename T, typename Proj = std::identity,
+ typename Comp = ranges::less>
+ constexpr ranges::iterator_t<R> operator()(R&& r, const T& value, Comp comp = {},
+ Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), value, std::ref(comp), std::ref(proj));
+ }
+};
+
+inline constexpr lower_bound_fn lower_bound;
+inline constexpr upper_bound_fn upper_bound;
+
+//
+// adjacent_find
+//
+
+struct adjacent_find_fn {
+ template <typename Iterator, typename Proj = std::identity, typename Pred = ranges::equal_to>
+ constexpr Iterator operator()(Iterator first, Iterator last, Pred pred = {},
+ Proj proj = {}) const {
+ if (first == last)
+ return first;
+ auto _next = ranges::next(first);
+ for (; _next != last; ++_next, ++first)
+ if (std::invoke(pred, std::invoke(proj, *first), std::invoke(proj, *_next)))
+ return first;
+ return _next;
+ }
+
+ template <ranges::input_range R, typename Proj = std::identity,
+ typename Pred = ranges::equal_to>
+ constexpr ranges::iterator_t<R> operator()(R&& r, Pred pred = {}, Proj proj = {}) const {
+ return operator()(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
+ }
+};
+
+inline constexpr adjacent_find_fn adjacent_find;
+
+} // namespace ranges
+} // namespace std
+
+#endif
diff --git a/src/common/polyfill_thread.h b/src/common/polyfill_thread.h
new file mode 100644
index 000000000..5a8d1ce08
--- /dev/null
+++ b/src/common/polyfill_thread.h
@@ -0,0 +1,323 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+//
+// TODO: remove this file when jthread is supported by all compilation targets
+//
+
+#pragma once
+
+#include <version>
+
+#ifdef __cpp_lib_jthread
+
+#include <stop_token>
+#include <thread>
+
+namespace Common {
+
+template <typename Condvar, typename Lock, typename Pred>
+void CondvarWait(Condvar& cv, Lock& lock, std::stop_token token, Pred&& pred) {
+ cv.wait(lock, token, std::move(pred));
+}
+
+} // namespace Common
+
+#else
+
+#include <atomic>
+#include <functional>
+#include <list>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <thread>
+#include <type_traits>
+
+namespace std {
+namespace polyfill {
+
+using stop_state_callbacks = list<function<void()>>;
+
+class stop_state {
+public:
+ stop_state() = default;
+ ~stop_state() = default;
+
+ bool request_stop() {
+ stop_state_callbacks callbacks;
+
+ {
+ scoped_lock lk{m_lock};
+
+ if (m_stop_requested.load()) {
+ // Already set, nothing to do
+ return false;
+ }
+
+ // Set as requested
+ m_stop_requested = true;
+
+ // Copy callback list
+ callbacks = m_callbacks;
+ }
+
+ for (auto callback : callbacks) {
+ callback();
+ }
+
+ return true;
+ }
+
+ bool stop_requested() const {
+ return m_stop_requested.load();
+ }
+
+ stop_state_callbacks::const_iterator insert_callback(function<void()> f) {
+ stop_state_callbacks::const_iterator ret{};
+ bool should_run{};
+
+ {
+ scoped_lock lk{m_lock};
+ should_run = m_stop_requested.load();
+ m_callbacks.push_front(f);
+ ret = m_callbacks.begin();
+ }
+
+ if (should_run) {
+ f();
+ }
+
+ return ret;
+ }
+
+ void remove_callback(stop_state_callbacks::const_iterator it) {
+ scoped_lock lk{m_lock};
+ m_callbacks.erase(it);
+ }
+
+private:
+ mutex m_lock;
+ atomic<bool> m_stop_requested;
+ stop_state_callbacks m_callbacks;
+};
+
+} // namespace polyfill
+
+class stop_token;
+class stop_source;
+struct nostopstate_t {
+ explicit nostopstate_t() = default;
+};
+inline constexpr nostopstate_t nostopstate{};
+
+template <class Callback>
+class stop_callback;
+
+class stop_token {
+public:
+ stop_token() noexcept = default;
+
+ stop_token(const stop_token&) noexcept = default;
+ stop_token(stop_token&&) noexcept = default;
+ stop_token& operator=(const stop_token&) noexcept = default;
+ stop_token& operator=(stop_token&&) noexcept = default;
+ ~stop_token() = default;
+
+ void swap(stop_token& other) noexcept {
+ m_stop_state.swap(other.m_stop_state);
+ }
+
+ [[nodiscard]] bool stop_requested() const noexcept {
+ return m_stop_state && m_stop_state->stop_requested();
+ }
+ [[nodiscard]] bool stop_possible() const noexcept {
+ return m_stop_state != nullptr;
+ }
+
+private:
+ friend class stop_source;
+ template <typename Callback>
+ friend class stop_callback;
+ stop_token(shared_ptr<polyfill::stop_state> stop_state) : m_stop_state(move(stop_state)) {}
+
+private:
+ shared_ptr<polyfill::stop_state> m_stop_state;
+};
+
+class stop_source {
+public:
+ stop_source() : m_stop_state(make_shared<polyfill::stop_state>()) {}
+ explicit stop_source(nostopstate_t) noexcept {}
+
+ stop_source(const stop_source&) noexcept = default;
+ stop_source(stop_source&&) noexcept = default;
+ stop_source& operator=(const stop_source&) noexcept = default;
+ stop_source& operator=(stop_source&&) noexcept = default;
+ ~stop_source() = default;
+ void swap(stop_source& other) noexcept {
+ m_stop_state.swap(other.m_stop_state);
+ }
+
+ [[nodiscard]] stop_token get_token() const noexcept {
+ return stop_token(m_stop_state);
+ }
+ [[nodiscard]] bool stop_possible() const noexcept {
+ return m_stop_state != nullptr;
+ }
+ [[nodiscard]] bool stop_requested() const noexcept {
+ return m_stop_state && m_stop_state->stop_requested();
+ }
+ bool request_stop() noexcept {
+ return m_stop_state && m_stop_state->request_stop();
+ }
+
+private:
+ friend class jthread;
+ explicit stop_source(shared_ptr<polyfill::stop_state> stop_state)
+ : m_stop_state(move(stop_state)) {}
+
+private:
+ shared_ptr<polyfill::stop_state> m_stop_state;
+};
+
+template <typename Callback>
+class stop_callback {
+ static_assert(is_nothrow_destructible_v<Callback>);
+ static_assert(is_invocable_v<Callback>);
+
+public:
+ using callback_type = Callback;
+
+ template <typename C>
+ requires constructible_from<Callback, C>
+ explicit stop_callback(const stop_token& st,
+ C&& cb) noexcept(is_nothrow_constructible_v<Callback, C>)
+ : m_stop_state(st.m_stop_state) {
+ if (m_stop_state) {
+ m_callback = m_stop_state->insert_callback(move(cb));
+ }
+ }
+ template <typename C>
+ requires constructible_from<Callback, C>
+ explicit stop_callback(stop_token&& st,
+ C&& cb) noexcept(is_nothrow_constructible_v<Callback, C>)
+ : m_stop_state(move(st.m_stop_state)) {
+ if (m_stop_state) {
+ m_callback = m_stop_state->insert_callback(move(cb));
+ }
+ }
+ ~stop_callback() {
+ if (m_stop_state && m_callback) {
+ m_stop_state->remove_callback(*m_callback);
+ }
+ }
+
+ stop_callback(const stop_callback&) = delete;
+ stop_callback(stop_callback&&) = delete;
+ stop_callback& operator=(const stop_callback&) = delete;
+ stop_callback& operator=(stop_callback&&) = delete;
+
+private:
+ shared_ptr<polyfill::stop_state> m_stop_state;
+ optional<polyfill::stop_state_callbacks::const_iterator> m_callback;
+};
+
+template <typename Callback>
+stop_callback(stop_token, Callback) -> stop_callback<Callback>;
+
+class jthread {
+public:
+ using id = thread::id;
+ using native_handle_type = thread::native_handle_type;
+
+ jthread() noexcept = default;
+
+ template <typename F, typename... Args,
+ typename = enable_if_t<!is_same_v<remove_cvref_t<F>, jthread>>>
+ explicit jthread(F&& f, Args&&... args)
+ : m_stop_state(make_shared<polyfill::stop_state>()),
+ m_thread(make_thread(move(f), move(args)...)) {}
+
+ ~jthread() {
+ if (joinable()) {
+ request_stop();
+ join();
+ }
+ }
+
+ jthread(const jthread&) = delete;
+ jthread(jthread&&) noexcept = default;
+ jthread& operator=(const jthread&) = delete;
+
+ jthread& operator=(jthread&& other) noexcept {
+ m_thread.swap(other.m_thread);
+ m_stop_state.swap(other.m_stop_state);
+ return *this;
+ }
+
+ void swap(jthread& other) noexcept {
+ m_thread.swap(other.m_thread);
+ m_stop_state.swap(other.m_stop_state);
+ }
+ [[nodiscard]] bool joinable() const noexcept {
+ return m_thread.joinable();
+ }
+ void join() {
+ m_thread.join();
+ }
+ void detach() {
+ m_thread.detach();
+ m_stop_state.reset();
+ }
+
+ [[nodiscard]] id get_id() const noexcept {
+ return m_thread.get_id();
+ }
+ [[nodiscard]] native_handle_type native_handle() {
+ return m_thread.native_handle();
+ }
+ [[nodiscard]] stop_source get_stop_source() noexcept {
+ return stop_source(m_stop_state);
+ }
+ [[nodiscard]] stop_token get_stop_token() const noexcept {
+ return stop_source(m_stop_state).get_token();
+ }
+ bool request_stop() noexcept {
+ return get_stop_source().request_stop();
+ }
+ [[nodiscard]] static unsigned int hardware_concurrency() noexcept {
+ return thread::hardware_concurrency();
+ }
+
+private:
+ template <typename F, typename... Args>
+ thread make_thread(F&& f, Args&&... args) {
+ if constexpr (is_invocable_v<decay_t<F>, stop_token, decay_t<Args>...>) {
+ return thread(move(f), get_stop_token(), move(args)...);
+ } else {
+ return thread(move(f), move(args)...);
+ }
+ }
+
+ shared_ptr<polyfill::stop_state> m_stop_state;
+ thread m_thread;
+};
+
+} // namespace std
+
+namespace Common {
+
+template <typename Condvar, typename Lock, typename Pred>
+void CondvarWait(Condvar& cv, Lock& lock, std::stop_token token, Pred pred) {
+ if (token.stop_requested()) {
+ return;
+ }
+
+ std::stop_callback callback(token, [&] { cv.notify_all(); });
+ cv.wait(lock, [&] { return pred() || token.stop_requested(); });
+}
+
+} // namespace Common
+
+#endif
diff --git a/src/common/precompiled_headers.h b/src/common/precompiled_headers.h
new file mode 100644
index 000000000..aabae730b
--- /dev/null
+++ b/src/common/precompiled_headers.h
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
diff --git a/src/common/settings.cpp b/src/common/settings.cpp
index 8173462cb..d8ffe34c3 100644
--- a/src/common/settings.cpp
+++ b/src/common/settings.cpp
@@ -48,6 +48,7 @@ void LogSettings() {
log_setting("CPU_Accuracy", values.cpu_accuracy.GetValue());
log_setting("Renderer_UseResolutionScaling", values.resolution_setup.GetValue());
log_setting("Renderer_ScalingFilter", values.scaling_filter.GetValue());
+ log_setting("Renderer_FSRSlider", values.fsr_sharpening_slider.GetValue());
log_setting("Renderer_AntiAliasing", values.anti_aliasing.GetValue());
log_setting("Renderer_UseSpeedLimit", values.use_speed_limit.GetValue());
log_setting("Renderer_SpeedLimit", values.speed_limit.GetValue());
@@ -181,6 +182,7 @@ void RestoreGlobalState(bool is_powered_on) {
values.cpuopt_unsafe_ignore_global_monitor.SetGlobal(true);
// Renderer
+ values.fsr_sharpening_slider.SetGlobal(true);
values.renderer_backend.SetGlobal(true);
values.vulkan_device.SetGlobal(true);
values.aspect_ratio.SetGlobal(true);
diff --git a/src/common/settings.h b/src/common/settings.h
index 0eb98939c..c0620066c 100644
--- a/src/common/settings.h
+++ b/src/common/settings.h
@@ -19,6 +19,7 @@ namespace Settings {
enum class RendererBackend : u32 {
OpenGL = 0,
Vulkan = 1,
+ Null = 2,
};
enum class ShaderBackend : u32 {
@@ -411,7 +412,7 @@ struct Values {
// Renderer
SwitchableSetting<RendererBackend, true> renderer_backend{
- RendererBackend::Vulkan, RendererBackend::OpenGL, RendererBackend::Vulkan, "backend"};
+ RendererBackend::Vulkan, RendererBackend::OpenGL, RendererBackend::Null, "backend"};
Setting<bool> renderer_debug{false, "debug"};
Setting<bool> renderer_shader_feedback{false, "shader_feedback"};
Setting<bool> enable_nsight_aftermath{false, "nsight_aftermath"};
@@ -421,6 +422,7 @@ struct Values {
ResolutionScalingInfo resolution_info{};
SwitchableSetting<ResolutionSetup> resolution_setup{ResolutionSetup::Res1X, "resolution_setup"};
SwitchableSetting<ScalingFilter> scaling_filter{ScalingFilter::Bilinear, "scaling_filter"};
+ SwitchableSetting<int, true> fsr_sharpening_slider{25, 0, 200, "fsr_sharpening_slider"};
SwitchableSetting<AntiAliasing> anti_aliasing{AntiAliasing::None, "anti_aliasing"};
// *nix platforms may have issues with the borderless windowed fullscreen mode.
// Default to exclusive fullscreen on these platforms for now.
@@ -442,7 +444,7 @@ struct Values {
SwitchableSetting<NvdecEmulation> nvdec_emulation{NvdecEmulation::GPU, "nvdec_emulation"};
SwitchableSetting<bool> accelerate_astc{true, "accelerate_astc"};
SwitchableSetting<bool> use_vsync{true, "use_vsync"};
- SwitchableSetting<ShaderBackend, true> shader_backend{ShaderBackend::GLASM, ShaderBackend::GLSL,
+ SwitchableSetting<ShaderBackend, true> shader_backend{ShaderBackend::GLSL, ShaderBackend::GLSL,
ShaderBackend::SPIRV, "shader_backend"};
SwitchableSetting<bool> use_asynchronous_shaders{false, "use_asynchronous_shaders"};
SwitchableSetting<bool> use_fast_gpu_time{true, "use_fast_gpu_time"};
diff --git a/src/common/string_util.cpp b/src/common/string_util.cpp
index 7a495bc79..b26db4796 100644
--- a/src/common/string_util.cpp
+++ b/src/common/string_util.cpp
@@ -141,7 +141,7 @@ static std::wstring CPToUTF16(u32 code_page, const std::string& input) {
MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()), nullptr, 0);
if (size == 0) {
- return L"";
+ return {};
}
std::wstring output(size, L'\0');
@@ -158,7 +158,7 @@ std::string UTF16ToUTF8(const std::wstring& input) {
const auto size = WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast<int>(input.size()),
nullptr, 0, nullptr, nullptr);
if (size == 0) {
- return "";
+ return {};
}
std::string output(size, '\0');
diff --git a/src/common/thread_worker.h b/src/common/thread_worker.h
index 62c60f724..260ad44e4 100644
--- a/src/common/thread_worker.h
+++ b/src/common/thread_worker.h
@@ -7,13 +7,13 @@
#include <condition_variable>
#include <functional>
#include <mutex>
-#include <stop_token>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
#include <queue>
+#include "common/polyfill_thread.h"
#include "common/thread.h"
#include "common/unique_function.h"
@@ -47,7 +47,8 @@ public:
if (requests.empty()) {
wait_condition.notify_all();
}
- condition.wait(lock, stop_token, [this] { return !requests.empty(); });
+ Common::CondvarWait(condition, lock, stop_token,
+ [this] { return !requests.empty(); });
if (stop_token.stop_requested()) {
break;
}
diff --git a/src/common/threadsafe_queue.h b/src/common/threadsafe_queue.h
index 053798e79..2ef1da064 100644
--- a/src/common/threadsafe_queue.h
+++ b/src/common/threadsafe_queue.h
@@ -12,6 +12,8 @@
#include <mutex>
#include <utility>
+#include "common/polyfill_thread.h"
+
namespace Common {
template <typename T, bool with_stop_token = false>
class SPSCQueue {
@@ -97,7 +99,7 @@ public:
T PopWait(std::stop_token stop_token) {
if (Empty()) {
std::unique_lock lock{cv_mutex};
- cv.wait(lock, stop_token, [this] { return !Empty(); });
+ Common::CondvarWait(cv, lock, stop_token, [this] { return !Empty(); });
}
if (stop_token.stop_requested()) {
return T{};
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index f67f1ce92..6530d3c60 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -120,6 +120,8 @@ add_library(core STATIC
file_sys/vfs_vector.h
file_sys/xts_archive.cpp
file_sys/xts_archive.h
+ frontend/applets/cabinet.cpp
+ frontend/applets/cabinet.h
frontend/applets/controller.cpp
frontend/applets/controller.h
frontend/applets/error.cpp
@@ -312,6 +314,8 @@ add_library(core STATIC
hle/service/am/applet_ae.h
hle/service/am/applet_oe.cpp
hle/service/am/applet_oe.h
+ hle/service/am/applets/applet_cabinet.cpp
+ hle/service/am/applets/applet_cabinet.h
hle/service/am/applets/applet_controller.cpp
hle/service/am/applets/applet_controller.h
hle/service/am/applets/applet_error.cpp
@@ -526,6 +530,11 @@ add_library(core STATIC
hle/service/ncm/ncm.h
hle/service/nfc/nfc.cpp
hle/service/nfc/nfc.h
+ hle/service/nfc/nfc_device.cpp
+ hle/service/nfc/nfc_device.h
+ hle/service/nfc/nfc_result.h
+ hle/service/nfc/nfc_user.cpp
+ hle/service/nfc/nfc_user.h
hle/service/nfp/amiibo_crypto.cpp
hle/service/nfp/amiibo_crypto.h
hle/service/nfp/nfp.cpp
@@ -762,6 +771,7 @@ add_library(core STATIC
memory.h
perf_stats.cpp
perf_stats.h
+ precompiled_headers.h
reporter.cpp
reporter.h
telemetry_session.cpp
@@ -816,3 +826,7 @@ if (ARCHITECTURE_x86_64 OR ARCHITECTURE_arm64)
)
target_link_libraries(core PRIVATE dynarmic)
endif()
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(core PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/core/arm/dynarmic/arm_dynarmic_64.cpp b/src/core/arm/dynarmic/arm_dynarmic_64.cpp
index afb7fb3a0..cb53d64ba 100644
--- a/src/core/arm/dynarmic/arm_dynarmic_64.cpp
+++ b/src/core/arm/dynarmic/arm_dynarmic_64.cpp
@@ -348,7 +348,6 @@ std::shared_ptr<Dynarmic::A64::Jit> ARM_Dynarmic_64::MakeJit(Common::PageTable*
if (Settings::values.cpu_accuracy.GetValue() == Settings::CPUAccuracy::Auto) {
config.unsafe_optimizations = true;
config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_UnfuseFMA;
- config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_InaccurateNaN;
config.fastmem_address_space_bits = 64;
config.optimizations |= Dynarmic::OptimizationFlag::Unsafe_IgnoreGlobalMonitor;
}
diff --git a/src/core/core.cpp b/src/core/core.cpp
index d8934be52..94d4e2212 100644
--- a/src/core/core.cpp
+++ b/src/core/core.cpp
@@ -189,7 +189,7 @@ struct System::Impl {
kernel.Suspend(false);
core_timing.SyncPause(false);
- is_paused = false;
+ is_paused.store(false, std::memory_order_relaxed);
return status;
}
@@ -200,14 +200,13 @@ struct System::Impl {
core_timing.SyncPause(true);
kernel.Suspend(true);
- is_paused = true;
+ is_paused.store(true, std::memory_order_relaxed);
return status;
}
bool IsPaused() const {
- std::unique_lock lk(suspend_guard);
- return is_paused;
+ return is_paused.load(std::memory_order_relaxed);
}
std::unique_lock<std::mutex> StallProcesses() {
@@ -218,7 +217,7 @@ struct System::Impl {
}
void UnstallProcesses() {
- if (!is_paused) {
+ if (!IsPaused()) {
core_timing.SyncPause(false);
kernel.Suspend(false);
}
@@ -465,7 +464,7 @@ struct System::Impl {
}
mutable std::mutex suspend_guard;
- bool is_paused{};
+ std::atomic_bool is_paused{};
std::atomic<bool> is_shutting_down{};
Timing::CoreTiming core_timing;
diff --git a/src/core/cpu_manager.h b/src/core/cpu_manager.h
index 95ea3ef39..374367468 100644
--- a/src/core/cpu_manager.h
+++ b/src/core/cpu_manager.h
@@ -10,6 +10,7 @@
#include <thread>
#include "common/fiber.h"
+#include "common/polyfill_thread.h"
#include "common/thread.h"
#include "core/hardware_properties.h"
diff --git a/src/core/crypto/key_manager.cpp b/src/core/crypto/key_manager.cpp
index 443323390..65a9fe802 100644
--- a/src/core/crypto/key_manager.cpp
+++ b/src/core/crypto/key_manager.cpp
@@ -578,18 +578,18 @@ KeyManager::KeyManager() {
if (Settings::values.use_dev_keys) {
dev_mode = true;
- LoadFromFile(yuzu_keys_dir / "dev.keys", false);
LoadFromFile(yuzu_keys_dir / "dev.keys_autogenerated", false);
+ LoadFromFile(yuzu_keys_dir / "dev.keys", false);
} else {
dev_mode = false;
- LoadFromFile(yuzu_keys_dir / "prod.keys", false);
LoadFromFile(yuzu_keys_dir / "prod.keys_autogenerated", false);
+ LoadFromFile(yuzu_keys_dir / "prod.keys", false);
}
- LoadFromFile(yuzu_keys_dir / "title.keys", true);
LoadFromFile(yuzu_keys_dir / "title.keys_autogenerated", true);
- LoadFromFile(yuzu_keys_dir / "console.keys", false);
+ LoadFromFile(yuzu_keys_dir / "title.keys", true);
LoadFromFile(yuzu_keys_dir / "console.keys_autogenerated", false);
+ LoadFromFile(yuzu_keys_dir / "console.keys", false);
}
static bool ValidCryptoRevisionString(std::string_view base, size_t begin, size_t length) {
diff --git a/src/core/debugger/debugger.cpp b/src/core/debugger/debugger.cpp
index 1a8e02e6a..a9675df76 100644
--- a/src/core/debugger/debugger.cpp
+++ b/src/core/debugger/debugger.cpp
@@ -9,6 +9,7 @@
#include <boost/process/async_pipe.hpp>
#include "common/logging/log.h"
+#include "common/polyfill_thread.h"
#include "common/thread.h"
#include "core/core.h"
#include "core/debugger/debugger.h"
diff --git a/src/core/file_sys/content_archive.cpp b/src/core/file_sys/content_archive.cpp
index 78e56bbbd..50303fe42 100644
--- a/src/core/file_sys/content_archive.cpp
+++ b/src/core/file_sys/content_archive.cpp
@@ -7,6 +7,7 @@
#include <utility>
#include "common/logging/log.h"
+#include "common/polyfill_ranges.h"
#include "core/crypto/aes_util.h"
#include "core/crypto/ctr_encryption_layer.h"
#include "core/crypto/key_manager.h"
diff --git a/src/core/frontend/applets/cabinet.cpp b/src/core/frontend/applets/cabinet.cpp
new file mode 100644
index 000000000..26c7fefe3
--- /dev/null
+++ b/src/core/frontend/applets/cabinet.cpp
@@ -0,0 +1,20 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include "common/logging/log.h"
+#include "core/frontend/applets/cabinet.h"
+
+#include <thread>
+
+namespace Core::Frontend {
+
+CabinetApplet::~CabinetApplet() = default;
+
+void DefaultCabinetApplet::ShowCabinetApplet(
+ const CabinetCallback& callback, const CabinetParameters& parameters,
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const {
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+ callback(false, {});
+}
+
+} // namespace Core::Frontend
diff --git a/src/core/frontend/applets/cabinet.h b/src/core/frontend/applets/cabinet.h
new file mode 100644
index 000000000..c28a235c1
--- /dev/null
+++ b/src/core/frontend/applets/cabinet.h
@@ -0,0 +1,37 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include <functional>
+#include "core/hle/service/nfp/nfp_types.h"
+
+namespace Service::NFP {
+class NfpDevice;
+} // namespace Service::NFP
+
+namespace Core::Frontend {
+
+struct CabinetParameters {
+ Service::NFP::TagInfo tag_info;
+ Service::NFP::RegisterInfo register_info;
+ Service::NFP::CabinetMode mode;
+};
+
+using CabinetCallback = std::function<void(bool, const std::string&)>;
+
+class CabinetApplet {
+public:
+ virtual ~CabinetApplet();
+ virtual void ShowCabinetApplet(const CabinetCallback& callback,
+ const CabinetParameters& parameters,
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const = 0;
+};
+
+class DefaultCabinetApplet final : public CabinetApplet {
+public:
+ void ShowCabinetApplet(const CabinetCallback& callback, const CabinetParameters& parameters,
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const override;
+};
+
+} // namespace Core::Frontend
diff --git a/src/core/frontend/applets/controller.h b/src/core/frontend/applets/controller.h
index 1d2850ad5..71698df74 100644
--- a/src/core/frontend/applets/controller.h
+++ b/src/core/frontend/applets/controller.h
@@ -4,6 +4,7 @@
#pragma once
#include <functional>
+#include <vector>
#include "common/common_types.h"
diff --git a/src/core/frontend/emu_window.h b/src/core/frontend/emu_window.h
index ac1906d5e..95363b645 100644
--- a/src/core/frontend/emu_window.h
+++ b/src/core/frontend/emu_window.h
@@ -17,6 +17,8 @@ enum class WindowSystemType {
Windows,
X11,
Wayland,
+ Cocoa,
+ Android,
};
/**
diff --git a/src/core/hid/emulated_console.cpp b/src/core/hid/emulated_console.cpp
index aac45907d..b6c8cc58d 100644
--- a/src/core/hid/emulated_console.cpp
+++ b/src/core/hid/emulated_console.cpp
@@ -19,27 +19,26 @@ void EmulatedConsole::ReloadFromSettings() {
}
void EmulatedConsole::SetTouchParams() {
- // TODO(german77): Support any number of fingers
std::size_t index = 0;
- // Hardcode mouse, touchscreen and cemuhook parameters
+ // We can't use mouse as touch if native mouse is enabled
if (!Settings::values.mouse_enabled) {
- // We can't use mouse as touch if native mouse is enabled
touch_params[index++] = Common::ParamPackage{"engine:mouse,axis_x:10,axis_y:11,button:0"};
}
touch_params[index++] =
- Common::ParamPackage{"engine:touch,axis_x:0,axis_y:1,button:0,touch_id:0"};
+ Common::ParamPackage{"engine:cemuhookudp,axis_x:17,axis_y:18,button:65536"};
touch_params[index++] =
- Common::ParamPackage{"engine:touch,axis_x:2,axis_y:3,button:1,touch_id:1"};
- touch_params[index++] =
- Common::ParamPackage{"engine:touch,axis_x:4,axis_y:5,button:2,touch_id:2"};
- touch_params[index++] =
- Common::ParamPackage{"engine:touch,axis_x:6,axis_y:7,button:3,touch_id:3"};
- touch_params[index++] =
- Common::ParamPackage{"engine:cemuhookudp,axis_x:17,axis_y:18,button:65536,touch_id:0"};
- touch_params[index++] =
- Common::ParamPackage{"engine:cemuhookudp,axis_x:19,axis_y:20,button:131072,touch_id:1"};
+ Common::ParamPackage{"engine:cemuhookudp,axis_x:19,axis_y:20,button:131072"};
+
+ for (int i = 0; i < static_cast<int>(MaxActiveTouchInputs); i++) {
+ Common::ParamPackage touchscreen_param{};
+ touchscreen_param.Set("engine", "touch");
+ touchscreen_param.Set("axis_x", i * 2);
+ touchscreen_param.Set("axis_y", (i * 2) + 1);
+ touchscreen_param.Set("button", i);
+ touch_params[index++] = touchscreen_param;
+ }
const auto button_index =
static_cast<u64>(Settings::values.touch_from_button_map_index.GetValue());
@@ -47,7 +46,7 @@ void EmulatedConsole::SetTouchParams() {
// Map the rest of the fingers from touch from button configuration
for (const auto& config_entry : touch_buttons) {
- if (index >= touch_params.size()) {
+ if (index >= MaxTouchDevices) {
continue;
}
Common::ParamPackage params{config_entry};
@@ -60,7 +59,6 @@ void EmulatedConsole::SetTouchParams() {
touch_button_params.Set("button", params.Serialize());
touch_button_params.Set("x", x);
touch_button_params.Set("y", y);
- touch_button_params.Set("touch_id", static_cast<int>(index));
touch_params[index] = touch_button_params;
index++;
}
@@ -70,7 +68,7 @@ void EmulatedConsole::ReloadInput() {
// If you load any device here add the equivalent to the UnloadInput() function
SetTouchParams();
- motion_devices = Common::Input::CreateDevice<Common::Input::InputDevice>(motion_params);
+ motion_devices = Common::Input::CreateInputDevice(motion_params);
if (motion_devices) {
motion_devices->SetCallback({
.on_change =
@@ -81,7 +79,7 @@ void EmulatedConsole::ReloadInput() {
// Unique index for identifying touch device source
std::size_t index = 0;
for (auto& touch_device : touch_devices) {
- touch_device = Common::Input::CreateDevice<Common::Input::InputDevice>(touch_params[index]);
+ touch_device = Common::Input::CreateInputDevice(touch_params[index]);
if (!touch_device) {
continue;
}
@@ -178,12 +176,38 @@ void EmulatedConsole::SetMotion(const Common::Input::CallbackStatus& callback) {
}
void EmulatedConsole::SetTouch(const Common::Input::CallbackStatus& callback, std::size_t index) {
- if (index >= console.touch_values.size()) {
+ if (index >= MaxTouchDevices) {
return;
}
std::unique_lock lock{mutex};
- console.touch_values[index] = TransformToTouch(callback);
+ const auto touch_input = TransformToTouch(callback);
+ auto touch_index = GetIndexFromFingerId(index);
+ bool is_new_input = false;
+
+ if (!touch_index.has_value() && touch_input.pressed.value) {
+ touch_index = GetNextFreeIndex();
+ is_new_input = true;
+ }
+
+ // No free entries or invalid state. Ignore input
+ if (!touch_index.has_value()) {
+ return;
+ }
+
+ auto& touch_value = console.touch_values[touch_index.value()];
+
+ if (is_new_input) {
+ touch_value.pressed.value = true;
+ touch_value.id = static_cast<u32>(index);
+ }
+
+ touch_value.x = touch_input.x;
+ touch_value.y = touch_input.y;
+
+ if (!touch_input.pressed.value) {
+ touch_value.pressed.value = false;
+ }
if (is_configuring) {
lock.unlock();
@@ -191,11 +215,15 @@ void EmulatedConsole::SetTouch(const Common::Input::CallbackStatus& callback, st
return;
}
- // TODO(german77): Remap touch id in sequential order
- console.touch_state[index] = {
- .position = {console.touch_values[index].x.value, console.touch_values[index].y.value},
- .id = static_cast<u32>(console.touch_values[index].id),
- .pressed = console.touch_values[index].pressed.value,
+ // Touch outside allowed range. Ignore input
+ if (touch_index.value() >= MaxActiveTouchInputs) {
+ return;
+ }
+
+ console.touch_state[touch_index.value()] = {
+ .position = {touch_value.x.value, touch_value.y.value},
+ .id = static_cast<u32>(touch_index.value()),
+ .pressed = touch_input.pressed.value,
};
lock.unlock();
@@ -222,6 +250,28 @@ TouchFingerState EmulatedConsole::GetTouch() const {
return console.touch_state;
}
+std::optional<std::size_t> EmulatedConsole::GetIndexFromFingerId(std::size_t finger_id) const {
+ for (std::size_t index = 0; index < MaxTouchDevices; ++index) {
+ const auto& finger = console.touch_values[index];
+ if (!finger.pressed.value) {
+ continue;
+ }
+ if (finger.id == static_cast<int>(finger_id)) {
+ return index;
+ }
+ }
+ return std::nullopt;
+}
+
+std::optional<std::size_t> EmulatedConsole::GetNextFreeIndex() const {
+ for (std::size_t index = 0; index < MaxTouchDevices; ++index) {
+ if (!console.touch_values[index].pressed.value) {
+ return index;
+ }
+ }
+ return std::nullopt;
+}
+
void EmulatedConsole::TriggerOnChange(ConsoleTriggerType type) {
std::scoped_lock lock{callback_mutex};
for (const auto& poller_pair : callback_list) {
diff --git a/src/core/hid/emulated_console.h b/src/core/hid/emulated_console.h
index 1c510cd19..697ecd2d6 100644
--- a/src/core/hid/emulated_console.h
+++ b/src/core/hid/emulated_console.h
@@ -7,6 +7,7 @@
#include <functional>
#include <memory>
#include <mutex>
+#include <optional>
#include <unordered_map>
#include "common/common_funcs.h"
@@ -20,6 +21,8 @@
#include "core/hid/motion_input.h"
namespace Core::HID {
+static constexpr std::size_t MaxTouchDevices = 32;
+static constexpr std::size_t MaxActiveTouchInputs = 16;
struct ConsoleMotionInfo {
Common::Input::MotionStatus raw_status{};
@@ -27,13 +30,13 @@ struct ConsoleMotionInfo {
};
using ConsoleMotionDevices = std::unique_ptr<Common::Input::InputDevice>;
-using TouchDevices = std::array<std::unique_ptr<Common::Input::InputDevice>, 16>;
+using TouchDevices = std::array<std::unique_ptr<Common::Input::InputDevice>, MaxTouchDevices>;
using ConsoleMotionParams = Common::ParamPackage;
-using TouchParams = std::array<Common::ParamPackage, 16>;
+using TouchParams = std::array<Common::ParamPackage, MaxTouchDevices>;
using ConsoleMotionValues = ConsoleMotionInfo;
-using TouchValues = std::array<Common::Input::TouchStatus, 16>;
+using TouchValues = std::array<Common::Input::TouchStatus, MaxTouchDevices>;
struct TouchFinger {
u64 last_touch{};
@@ -55,7 +58,7 @@ struct ConsoleMotion {
bool is_at_rest{};
};
-using TouchFingerState = std::array<TouchFinger, 16>;
+using TouchFingerState = std::array<TouchFinger, MaxActiveTouchInputs>;
struct ConsoleStatus {
// Data from input_common
@@ -166,6 +169,10 @@ private:
*/
void SetTouch(const Common::Input::CallbackStatus& callback, std::size_t index);
+ std::optional<std::size_t> GetIndexFromFingerId(std::size_t finger_id) const;
+
+ std::optional<std::size_t> GetNextFreeIndex() const;
+
/**
* Triggers a callback that something has changed on the console status
* @param type Input type of the event to trigger
diff --git a/src/core/hid/emulated_controller.cpp b/src/core/hid/emulated_controller.cpp
index a2d106245..74c877728 100644
--- a/src/core/hid/emulated_controller.cpp
+++ b/src/core/hid/emulated_controller.cpp
@@ -1,6 +1,9 @@
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
+#include <algorithm>
+
+#include "common/polyfill_ranges.h"
#include "common/thread.h"
#include "core/hid/emulated_controller.h"
#include "core/hid/input_converter.h"
@@ -143,29 +146,23 @@ void EmulatedController::LoadDevices() {
LoadTASParams();
- std::transform(button_params.begin() + Settings::NativeButton::BUTTON_HID_BEGIN,
- button_params.begin() + Settings::NativeButton::BUTTON_NS_END,
- button_devices.begin(), Common::Input::CreateDevice<Common::Input::InputDevice>);
- std::transform(stick_params.begin() + Settings::NativeAnalog::STICK_HID_BEGIN,
- stick_params.begin() + Settings::NativeAnalog::STICK_HID_END,
- stick_devices.begin(), Common::Input::CreateDevice<Common::Input::InputDevice>);
- std::transform(motion_params.begin() + Settings::NativeMotion::MOTION_HID_BEGIN,
- motion_params.begin() + Settings::NativeMotion::MOTION_HID_END,
- motion_devices.begin(), Common::Input::CreateDevice<Common::Input::InputDevice>);
- std::transform(trigger_params.begin(), trigger_params.end(), trigger_devices.begin(),
- Common::Input::CreateDevice<Common::Input::InputDevice>);
- std::transform(battery_params.begin(), battery_params.end(), battery_devices.begin(),
- Common::Input::CreateDevice<Common::Input::InputDevice>);
- camera_devices = Common::Input::CreateDevice<Common::Input::InputDevice>(camera_params);
- nfc_devices = Common::Input::CreateDevice<Common::Input::InputDevice>(nfc_params);
- std::transform(output_params.begin(), output_params.end(), output_devices.begin(),
- Common::Input::CreateDevice<Common::Input::OutputDevice>);
+ std::ranges::transform(button_params, button_devices.begin(), Common::Input::CreateInputDevice);
+ std::ranges::transform(stick_params, stick_devices.begin(), Common::Input::CreateInputDevice);
+ std::ranges::transform(motion_params, motion_devices.begin(), Common::Input::CreateInputDevice);
+ std::ranges::transform(trigger_params, trigger_devices.begin(),
+ Common::Input::CreateInputDevice);
+ std::ranges::transform(battery_params, battery_devices.begin(),
+ Common::Input::CreateInputDevice);
+ camera_devices = Common::Input::CreateInputDevice(camera_params);
+ nfc_devices = Common::Input::CreateInputDevice(nfc_params);
+ std::ranges::transform(output_params, output_devices.begin(),
+ Common::Input::CreateOutputDevice);
// Initialize TAS devices
- std::transform(tas_button_params.begin(), tas_button_params.end(), tas_button_devices.begin(),
- Common::Input::CreateDevice<Common::Input::InputDevice>);
- std::transform(tas_stick_params.begin(), tas_stick_params.end(), tas_stick_devices.begin(),
- Common::Input::CreateDevice<Common::Input::InputDevice>);
+ std::ranges::transform(tas_button_params, tas_button_devices.begin(),
+ Common::Input::CreateInputDevice);
+ std::ranges::transform(tas_stick_params, tas_stick_devices.begin(),
+ Common::Input::CreateInputDevice);
}
void EmulatedController::LoadTASParams() {
diff --git a/src/core/hid/emulated_controller.h b/src/core/hid/emulated_controller.h
index d004ca56a..3f83108d3 100644
--- a/src/core/hid/emulated_controller.h
+++ b/src/core/hid/emulated_controller.h
@@ -8,6 +8,7 @@
#include <memory>
#include <mutex>
#include <unordered_map>
+#include <vector>
#include "common/common_types.h"
#include "common/input.h"
diff --git a/src/core/hid/emulated_devices.cpp b/src/core/hid/emulated_devices.cpp
index 8d367b546..e421828d2 100644
--- a/src/core/hid/emulated_devices.cpp
+++ b/src/core/hid/emulated_devices.cpp
@@ -25,12 +25,12 @@ void EmulatedDevices::ReloadInput() {
Common::ParamPackage mouse_params;
mouse_params.Set("engine", "mouse");
mouse_params.Set("button", static_cast<int>(key_index));
- mouse_device = Common::Input::CreateDevice<Common::Input::InputDevice>(mouse_params);
+ mouse_device = Common::Input::CreateInputDevice(mouse_params);
key_index++;
}
- mouse_stick_device = Common::Input::CreateDeviceFromString<Common::Input::InputDevice>(
- "engine:mouse,axis_x:0,axis_y:1");
+ mouse_stick_device =
+ Common::Input::CreateInputDeviceFromString("engine:mouse,axis_x:0,axis_y:1");
// First two axis are reserved for mouse position
key_index = 2;
@@ -38,7 +38,7 @@ void EmulatedDevices::ReloadInput() {
Common::ParamPackage mouse_params;
mouse_params.Set("engine", "mouse");
mouse_params.Set("axis", static_cast<int>(key_index));
- mouse_device = Common::Input::CreateDevice<Common::Input::InputDevice>(mouse_params);
+ mouse_device = Common::Input::CreateInputDevice(mouse_params);
key_index++;
}
@@ -50,7 +50,7 @@ void EmulatedDevices::ReloadInput() {
keyboard_params.Set("button", static_cast<int>(key_index));
keyboard_params.Set("port", 1);
keyboard_params.Set("pad", 0);
- keyboard_device = Common::Input::CreateDevice<Common::Input::InputDevice>(keyboard_params);
+ keyboard_device = Common::Input::CreateInputDevice(keyboard_params);
key_index++;
}
@@ -62,11 +62,11 @@ void EmulatedDevices::ReloadInput() {
keyboard_params.Set("button", static_cast<int>(key_index));
keyboard_params.Set("port", 1);
keyboard_params.Set("pad", 1);
- keyboard_device = Common::Input::CreateDevice<Common::Input::InputDevice>(keyboard_params);
+ keyboard_device = Common::Input::CreateInputDevice(keyboard_params);
key_index++;
}
- ring_analog_device = Common::Input::CreateDevice<Common::Input::InputDevice>(ring_params);
+ ring_analog_device = Common::Input::CreateInputDevice(ring_params);
for (std::size_t index = 0; index < mouse_button_devices.size(); ++index) {
if (!mouse_button_devices[index]) {
@@ -145,6 +145,7 @@ void EmulatedDevices::UnloadInput() {
for (auto& button : keyboard_modifier_devices) {
button.reset();
}
+ ring_analog_device.reset();
}
void EmulatedDevices::EnableConfiguration() {
diff --git a/src/core/hid/emulated_devices.h b/src/core/hid/emulated_devices.h
index 4149eeced..4cdbf9dc6 100644
--- a/src/core/hid/emulated_devices.h
+++ b/src/core/hid/emulated_devices.h
@@ -8,6 +8,7 @@
#include <memory>
#include <mutex>
#include <unordered_map>
+#include <vector>
#include "common/common_types.h"
#include "common/input.h"
diff --git a/src/core/hid/input_converter.cpp b/src/core/hid/input_converter.cpp
index 5d8b75b50..502692875 100644
--- a/src/core/hid/input_converter.cpp
+++ b/src/core/hid/input_converter.cpp
@@ -200,9 +200,6 @@ Common::Input::TouchStatus TransformToTouch(const Common::Input::CallbackStatus&
x = std::clamp(x, 0.0f, 1.0f);
y = std::clamp(y, 0.0f, 1.0f);
- // Limit id to maximum number of fingers
- status.id = std::clamp(status.id, 0, 16);
-
if (status.pressed.inverted) {
status.pressed.value = !status.pressed.value;
}
diff --git a/src/core/hle/kernel/hle_ipc.h b/src/core/hle/kernel/hle_ipc.h
index d87be72d6..e252b5f4b 100644
--- a/src/core/hle/kernel/hle_ipc.h
+++ b/src/core/hle/kernel/hle_ipc.h
@@ -199,7 +199,7 @@ public:
~HLERequestContext();
/// Returns a pointer to the IPC command buffer for this request.
- u32* CommandBuffer() {
+ [[nodiscard]] u32* CommandBuffer() {
return cmd_buf.data();
}
@@ -207,7 +207,7 @@ public:
* Returns the session through which this request was made. This can be used as a map key to
* access per-client data on services.
*/
- Kernel::KServerSession* Session() {
+ [[nodiscard]] Kernel::KServerSession* Session() {
return server_session;
}
@@ -217,61 +217,61 @@ public:
/// Writes data from this context back to the requesting process/thread.
Result WriteToOutgoingCommandBuffer(KThread& requesting_thread);
- u32_le GetHipcCommand() const {
+ [[nodiscard]] u32_le GetHipcCommand() const {
return command;
}
- u32_le GetTipcCommand() const {
+ [[nodiscard]] u32_le GetTipcCommand() const {
return static_cast<u32_le>(command_header->type.Value()) -
static_cast<u32_le>(IPC::CommandType::TIPC_CommandRegion);
}
- u32_le GetCommand() const {
+ [[nodiscard]] u32_le GetCommand() const {
return command_header->IsTipc() ? GetTipcCommand() : GetHipcCommand();
}
- bool IsTipc() const {
+ [[nodiscard]] bool IsTipc() const {
return command_header->IsTipc();
}
- IPC::CommandType GetCommandType() const {
+ [[nodiscard]] IPC::CommandType GetCommandType() const {
return command_header->type;
}
- u64 GetPID() const {
+ [[nodiscard]] u64 GetPID() const {
return pid;
}
- u32 GetDataPayloadOffset() const {
+ [[nodiscard]] u32 GetDataPayloadOffset() const {
return data_payload_offset;
}
- const std::vector<IPC::BufferDescriptorX>& BufferDescriptorX() const {
+ [[nodiscard]] const std::vector<IPC::BufferDescriptorX>& BufferDescriptorX() const {
return buffer_x_desciptors;
}
- const std::vector<IPC::BufferDescriptorABW>& BufferDescriptorA() const {
+ [[nodiscard]] const std::vector<IPC::BufferDescriptorABW>& BufferDescriptorA() const {
return buffer_a_desciptors;
}
- const std::vector<IPC::BufferDescriptorABW>& BufferDescriptorB() const {
+ [[nodiscard]] const std::vector<IPC::BufferDescriptorABW>& BufferDescriptorB() const {
return buffer_b_desciptors;
}
- const std::vector<IPC::BufferDescriptorC>& BufferDescriptorC() const {
+ [[nodiscard]] const std::vector<IPC::BufferDescriptorC>& BufferDescriptorC() const {
return buffer_c_desciptors;
}
- const IPC::DomainMessageHeader& GetDomainMessageHeader() const {
+ [[nodiscard]] const IPC::DomainMessageHeader& GetDomainMessageHeader() const {
return domain_message_header.value();
}
- bool HasDomainMessageHeader() const {
+ [[nodiscard]] bool HasDomainMessageHeader() const {
return domain_message_header.has_value();
}
/// Helper function to read a buffer using the appropriate buffer descriptor
- std::vector<u8> ReadBuffer(std::size_t buffer_index = 0) const;
+ [[nodiscard]] std::vector<u8> ReadBuffer(std::size_t buffer_index = 0) const;
/// Helper function to write a buffer using the appropriate buffer descriptor
std::size_t WriteBuffer(const void* buffer, std::size_t size,
@@ -308,22 +308,34 @@ public:
}
/// Helper function to get the size of the input buffer
- std::size_t GetReadBufferSize(std::size_t buffer_index = 0) const;
+ [[nodiscard]] std::size_t GetReadBufferSize(std::size_t buffer_index = 0) const;
/// Helper function to get the size of the output buffer
- std::size_t GetWriteBufferSize(std::size_t buffer_index = 0) const;
+ [[nodiscard]] std::size_t GetWriteBufferSize(std::size_t buffer_index = 0) const;
+
+ /// Helper function to derive the number of elements able to be contained in the read buffer
+ template <typename T>
+ [[nodiscard]] std::size_t GetReadBufferNumElements(std::size_t buffer_index = 0) const {
+ return GetReadBufferSize(buffer_index) / sizeof(T);
+ }
+
+ /// Helper function to derive the number of elements able to be contained in the write buffer
+ template <typename T>
+ [[nodiscard]] std::size_t GetWriteBufferNumElements(std::size_t buffer_index = 0) const {
+ return GetWriteBufferSize(buffer_index) / sizeof(T);
+ }
/// Helper function to test whether the input buffer at buffer_index can be read
- bool CanReadBuffer(std::size_t buffer_index = 0) const;
+ [[nodiscard]] bool CanReadBuffer(std::size_t buffer_index = 0) const;
/// Helper function to test whether the output buffer at buffer_index can be written
- bool CanWriteBuffer(std::size_t buffer_index = 0) const;
+ [[nodiscard]] bool CanWriteBuffer(std::size_t buffer_index = 0) const;
- Handle GetCopyHandle(std::size_t index) const {
+ [[nodiscard]] Handle GetCopyHandle(std::size_t index) const {
return incoming_copy_handles.at(index);
}
- Handle GetMoveHandle(std::size_t index) const {
+ [[nodiscard]] Handle GetMoveHandle(std::size_t index) const {
return incoming_move_handles.at(index);
}
@@ -348,13 +360,13 @@ public:
manager = manager_;
}
- std::string Description() const;
+ [[nodiscard]] std::string Description() const;
- KThread& GetThread() {
+ [[nodiscard]] KThread& GetThread() {
return *thread;
}
- std::shared_ptr<SessionRequestManager> GetManager() const {
+ [[nodiscard]] std::shared_ptr<SessionRequestManager> GetManager() const {
return manager.lock();
}
diff --git a/src/core/hle/kernel/init/init_slab_setup.cpp b/src/core/hle/kernel/init/init_slab_setup.cpp
index bda098511..7b363eb1e 100644
--- a/src/core/hle/kernel/init/init_slab_setup.cpp
+++ b/src/core/hle/kernel/init/init_slab_setup.cpp
@@ -243,6 +243,7 @@ void InitializeSlabHeaps(Core::System& system, KMemoryLayout& memory_layout) {
// If we somehow get an invalid type, abort.
default:
ASSERT_MSG(false, "Unknown slab type: {}", slab_types[i]);
+ break;
}
// If we've hit the end of a gap, free it.
diff --git a/src/core/hle/kernel/k_handle_table.cpp b/src/core/hle/kernel/k_handle_table.cpp
index 1c7a766c8..3535ddc0c 100644
--- a/src/core/hle/kernel/k_handle_table.cpp
+++ b/src/core/hle/kernel/k_handle_table.cpp
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/hle/kernel/k_handle_table.h"
+#include "core/hle/kernel/k_process.h"
namespace Kernel {
@@ -82,6 +83,22 @@ Result KHandleTable::Add(Handle* out_handle, KAutoObject* obj) {
R_SUCCEED();
}
+KScopedAutoObject<KAutoObject> KHandleTable::GetObjectForIpc(Handle handle,
+ KThread* cur_thread) const {
+ // Handle pseudo-handles.
+ ASSERT(cur_thread != nullptr);
+ if (handle == Svc::PseudoHandle::CurrentProcess) {
+ auto* const cur_process = cur_thread->GetOwnerProcess();
+ ASSERT(cur_process != nullptr);
+ return cur_process;
+ }
+ if (handle == Svc::PseudoHandle::CurrentThread) {
+ return cur_thread;
+ }
+
+ return GetObjectForIpcWithoutPseudoHandle(handle);
+}
+
Result KHandleTable::Reserve(Handle* out_handle) {
KScopedDisableDispatch dd{m_kernel};
KScopedSpinLock lk(m_lock);
diff --git a/src/core/hle/kernel/k_handle_table.h b/src/core/hle/kernel/k_handle_table.h
index 65cae3b27..37a24e7d9 100644
--- a/src/core/hle/kernel/k_handle_table.h
+++ b/src/core/hle/kernel/k_handle_table.h
@@ -113,21 +113,7 @@ public:
return this->GetObjectImpl(handle);
}
- KScopedAutoObject<KAutoObject> GetObjectForIpc(Handle handle, KThread* cur_thread) const {
- // Handle pseudo-handles.
- ASSERT(cur_thread != nullptr);
- if (handle == Svc::PseudoHandle::CurrentProcess) {
- auto* const cur_process =
- static_cast<KAutoObject*>(static_cast<void*>(cur_thread->GetOwnerProcess()));
- ASSERT(cur_process != nullptr);
- return cur_process;
- }
- if (handle == Svc::PseudoHandle::CurrentThread) {
- return static_cast<KAutoObject*>(cur_thread);
- }
-
- return GetObjectForIpcWithoutPseudoHandle(handle);
- }
+ KScopedAutoObject<KAutoObject> GetObjectForIpc(Handle handle, KThread* cur_thread) const;
KScopedAutoObject<KAutoObject> GetObjectByIndex(Handle* out_handle, size_t index) const {
KScopedDisableDispatch dd{m_kernel};
diff --git a/src/core/hle/kernel/k_memory_manager.cpp b/src/core/hle/kernel/k_memory_manager.cpp
index c4bf306e8..bd33571da 100644
--- a/src/core/hle/kernel/k_memory_manager.cpp
+++ b/src/core/hle/kernel/k_memory_manager.cpp
@@ -225,8 +225,8 @@ Result KMemoryManager::AllocatePageGroupImpl(KPageGroup* out, size_t num_pages,
ON_RESULT_FAILURE {
for (const auto& it : out->Nodes()) {
auto& manager = this->GetManager(it.GetAddress());
- const size_t node_num_pages =
- std::min(it.GetNumPages(), (manager.GetEndAddress() - it.GetAddress()) / PageSize);
+ const size_t node_num_pages = std::min<u64>(
+ it.GetNumPages(), (manager.GetEndAddress() - it.GetAddress()) / PageSize);
manager.Free(it.GetAddress(), node_num_pages);
}
out->Finalize();
diff --git a/src/core/hle/kernel/k_page_table.cpp b/src/core/hle/kernel/k_page_table.cpp
index 5387bf5fe..612fc76fa 100644
--- a/src/core/hle/kernel/k_page_table.cpp
+++ b/src/core/hle/kernel/k_page_table.cpp
@@ -2301,6 +2301,7 @@ Result KPageTable::SetProcessMemoryPermission(VAddr addr, size_t size,
break;
default:
ASSERT(false);
+ break;
}
}
@@ -2803,6 +2804,7 @@ Result KPageTable::Operate(VAddr addr, size_t num_pages, const KPageGroup& page_
break;
default:
ASSERT(false);
+ break;
}
addr += size;
@@ -2838,6 +2840,7 @@ Result KPageTable::Operate(VAddr addr, size_t num_pages, KMemoryPermission perm,
break;
default:
ASSERT(false);
+ break;
}
R_SUCCEED();
}
diff --git a/src/core/hle/kernel/k_process.cpp b/src/core/hle/kernel/k_process.cpp
index 55a9c5fae..d1dc62401 100644
--- a/src/core/hle/kernel/k_process.cpp
+++ b/src/core/hle/kernel/k_process.cpp
@@ -395,6 +395,7 @@ Result KProcess::LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std:
default:
ASSERT(false);
+ break;
}
// Create TLS region
diff --git a/src/core/hle/kernel/k_slab_heap.h b/src/core/hle/kernel/k_slab_heap.h
index a8c77a7d4..68469b041 100644
--- a/src/core/hle/kernel/k_slab_heap.h
+++ b/src/core/hle/kernel/k_slab_heap.h
@@ -6,6 +6,7 @@
#include <atomic>
#include "common/assert.h"
+#include "common/atomic_ops.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/spin_lock.h"
@@ -82,16 +83,13 @@ private:
private:
void UpdatePeakImpl(uintptr_t obj) {
- static_assert(std::atomic_ref<uintptr_t>::is_always_lock_free);
- std::atomic_ref<uintptr_t> peak_ref(m_peak);
-
const uintptr_t alloc_peak = obj + this->GetObjectSize();
uintptr_t cur_peak = m_peak;
do {
if (alloc_peak <= cur_peak) {
break;
}
- } while (!peak_ref.compare_exchange_strong(cur_peak, alloc_peak));
+ } while (!Common::AtomicCompareAndSwap(&m_peak, alloc_peak, cur_peak, cur_peak));
}
public:
diff --git a/src/core/hle/kernel/k_thread_local_page.h b/src/core/hle/kernel/k_thread_local_page.h
index 5d466ace7..fe0cff084 100644
--- a/src/core/hle/kernel/k_thread_local_page.h
+++ b/src/core/hle/kernel/k_thread_local_page.h
@@ -10,6 +10,7 @@
#include "common/assert.h"
#include "common/common_types.h"
#include "common/intrusive_red_black_tree.h"
+#include "common/polyfill_ranges.h"
#include "core/hle/kernel/memory_types.h"
#include "core/hle/kernel/slab_helpers.h"
#include "core/hle/result.h"
diff --git a/src/core/hle/kernel/service_thread.cpp b/src/core/hle/kernel/service_thread.cpp
index e6e41ac34..0690f9a1c 100644
--- a/src/core/hle/kernel/service_thread.cpp
+++ b/src/core/hle/kernel/service_thread.cpp
@@ -7,6 +7,7 @@
#include <thread>
#include <vector>
+#include "common/polyfill_thread.h"
#include "common/scope_exit.h"
#include "common/thread.h"
#include "core/hle/ipc_helpers.h"
diff --git a/src/core/hle/kernel/svc.cpp b/src/core/hle/kernel/svc.cpp
index 9962ad171..e520cab47 100644
--- a/src/core/hle/kernel/svc.cpp
+++ b/src/core/hle/kernel/svc.cpp
@@ -2701,14 +2701,24 @@ static Result GetThreadList(Core::System& system, u32* out_num_threads, VAddr ou
return ResultSuccess;
}
-static Result FlushProcessDataCache32([[maybe_unused]] Core::System& system,
- [[maybe_unused]] Handle handle, [[maybe_unused]] u32 address,
- [[maybe_unused]] u32 size) {
- // Note(Blinkhawk): For emulation purposes of the data cache this is mostly a no-op,
- // as all emulation is done in the same cache level in host architecture, thus data cache
- // does not need flushing.
- LOG_DEBUG(Kernel_SVC, "called");
- return ResultSuccess;
+static Result FlushProcessDataCache32(Core::System& system, Handle process_handle, u64 address,
+ u64 size) {
+ // Validate address/size.
+ R_UNLESS(size > 0, ResultInvalidSize);
+ R_UNLESS(address == static_cast<uintptr_t>(address), ResultInvalidCurrentMemory);
+ R_UNLESS(size == static_cast<size_t>(size), ResultInvalidCurrentMemory);
+
+ // Get the process from its handle.
+ KScopedAutoObject process =
+ system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KProcess>(process_handle);
+ R_UNLESS(process.IsNotNull(), ResultInvalidHandle);
+
+ // Verify the region is within range.
+ auto& page_table = process->PageTable();
+ R_UNLESS(page_table.Contains(address, size), ResultInvalidCurrentMemory);
+
+ // Perform the operation.
+ R_RETURN(system.Memory().FlushDataCache(*process, address, size));
}
namespace {
diff --git a/src/core/hle/kernel/svc_wrap.h b/src/core/hle/kernel/svc_wrap.h
index 272c54cf7..1ea8c7fbc 100644
--- a/src/core/hle/kernel/svc_wrap.h
+++ b/src/core/hle/kernel/svc_wrap.h
@@ -82,7 +82,7 @@ void SvcWrap64(Core::System& system) {
}
// Used by ControlCodeMemory
-template <Result func(Core::System&, Handle, u32, u64, u64, Svc::MemoryPermission)>
+template <Result func(Core::System&, Handle, u32, VAddr, size_t, Svc::MemoryPermission)>
void SvcWrap64(Core::System& system) {
FuncReturn(system, func(system, static_cast<Handle>(Param(system, 0)),
static_cast<u32>(Param(system, 1)), Param(system, 2), Param(system, 3),
@@ -327,7 +327,7 @@ void SvcWrap64(Core::System& system) {
}
// Used by CreateCodeMemory
-template <Result func(Core::System&, Handle*, u64, u64)>
+template <Result func(Core::System&, Handle*, VAddr, size_t)>
void SvcWrap64(Core::System& system) {
u32 param_1 = 0;
const u32 retval = func(system, &param_1, Param(system, 1), Param(system, 2)).raw;
@@ -722,4 +722,12 @@ void SvcWrap32(Core::System& system) {
FuncReturn(system, retval);
}
+// Used by Invalidate/Store/FlushProcessDataCache32
+template <Result func(Core::System&, Handle, u64, u64)>
+void SvcWrap32(Core::System& system) {
+ const u64 address = (Param(system, 3) << 32) | Param(system, 2);
+ const u64 size = (Param(system, 4) << 32) | Param(system, 1);
+ FuncReturn32(system, func(system, Param32(system, 0), address, size).raw);
+}
+
} // namespace Kernel
diff --git a/src/core/hle/service/acc/acc.cpp b/src/core/hle/service/acc/acc.cpp
index 85a3f0802..6d1084fd1 100644
--- a/src/core/hle/service/acc/acc.cpp
+++ b/src/core/hle/service/acc/acc.cpp
@@ -7,6 +7,7 @@
#include "common/fs/file.h"
#include "common/fs/path_util.h"
#include "common/logging/log.h"
+#include "common/polyfill_ranges.h"
#include "common/string_util.h"
#include "common/swap.h"
#include "core/constants.h"
diff --git a/src/core/hle/service/acc/profile_manager.cpp b/src/core/hle/service/acc/profile_manager.cpp
index 481e0d141..97f7c6688 100644
--- a/src/core/hle/service/acc/profile_manager.cpp
+++ b/src/core/hle/service/acc/profile_manager.cpp
@@ -9,6 +9,7 @@
#include "common/fs/file.h"
#include "common/fs/fs.h"
#include "common/fs/path_util.h"
+#include "common/polyfill_ranges.h"
#include "common/settings.h"
#include "core/hle/service/acc/profile_manager.h"
diff --git a/src/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp
index 8ea7fd760..22999c942 100644
--- a/src/core/hle/service/am/am.cpp
+++ b/src/core/hle/service/am/am.cpp
@@ -1125,7 +1125,7 @@ void IStorageAccessor::Write(Kernel::HLERequestContext& ctx) {
const u64 offset{rp.Pop<u64>()};
const std::vector<u8> data{ctx.ReadBuffer()};
- const std::size_t size{std::min(data.size(), backing.GetSize() - offset)};
+ const std::size_t size{std::min<u64>(data.size(), backing.GetSize() - offset)};
LOG_DEBUG(Service_AM, "called, offset={}, size={}", offset, size);
@@ -1149,7 +1149,7 @@ void IStorageAccessor::Read(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u64 offset{rp.Pop<u64>()};
- const std::size_t size{std::min(ctx.GetWriteBufferSize(), backing.GetSize() - offset)};
+ const std::size_t size{std::min<u64>(ctx.GetWriteBufferSize(), backing.GetSize() - offset)};
LOG_DEBUG(Service_AM, "called, offset={}, size={}", offset, size);
diff --git a/src/core/hle/service/am/applets/applet_cabinet.cpp b/src/core/hle/service/am/applets/applet_cabinet.cpp
new file mode 100644
index 000000000..d0969b0f1
--- /dev/null
+++ b/src/core/hle/service/am/applets/applet_cabinet.cpp
@@ -0,0 +1,177 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include "common/assert.h"
+#include "common/logging/log.h"
+#include "core/core.h"
+#include "core/frontend/applets/cabinet.h"
+#include "core/hid/hid_core.h"
+#include "core/hle/kernel/k_event.h"
+#include "core/hle/kernel/k_readable_event.h"
+#include "core/hle/service/am/am.h"
+#include "core/hle/service/am/applets/applet_cabinet.h"
+#include "core/hle/service/mii/mii_manager.h"
+#include "core/hle/service/nfp/nfp_device.h"
+
+namespace Service::AM::Applets {
+
+Cabinet::Cabinet(Core::System& system_, LibraryAppletMode applet_mode_,
+ const Core::Frontend::CabinetApplet& frontend_)
+ : Applet{system_, applet_mode_}, frontend{frontend_}, system{system_}, service_context{
+ system_,
+ "CabinetApplet"} {
+
+ availability_change_event =
+ service_context.CreateEvent("CabinetApplet:AvailabilityChangeEvent");
+}
+
+Cabinet::~Cabinet() = default;
+
+void Cabinet::Initialize() {
+ Applet::Initialize();
+
+ LOG_INFO(Service_HID, "Initializing Cabinet Applet.");
+
+ LOG_DEBUG(Service_HID,
+ "Initializing Applet with common_args: arg_version={}, lib_version={}, "
+ "play_startup_sound={}, size={}, system_tick={}, theme_color={}",
+ common_args.arguments_version, common_args.library_version,
+ common_args.play_startup_sound, common_args.size, common_args.system_tick,
+ common_args.theme_color);
+
+ const auto storage = broker.PopNormalDataToApplet();
+ ASSERT(storage != nullptr);
+
+ const auto applet_input_data = storage->GetData();
+ ASSERT(applet_input_data.size() >= sizeof(StartParamForAmiiboSettings));
+
+ std::memcpy(&applet_input_common, applet_input_data.data(),
+ sizeof(StartParamForAmiiboSettings));
+}
+
+bool Cabinet::TransactionComplete() const {
+ return is_complete;
+}
+
+Result Cabinet::GetStatus() const {
+ return ResultSuccess;
+}
+
+void Cabinet::ExecuteInteractive() {
+ ASSERT_MSG(false, "Attempted to call interactive execution on non-interactive applet.");
+}
+
+void Cabinet::Execute() {
+ if (is_complete) {
+ return;
+ }
+
+ const auto callback = [this](bool apply_changes, const std::string& amiibo_name) {
+ DisplayCompleted(apply_changes, amiibo_name);
+ };
+
+ // TODO: listen on all controllers
+ if (nfp_device == nullptr) {
+ nfp_device = std::make_shared<Service::NFP::NfpDevice>(
+ system.HIDCore().GetFirstNpadId(), system, service_context, availability_change_event);
+ nfp_device->Initialize();
+ nfp_device->StartDetection(Service::NFP::TagProtocol::All);
+ }
+
+ const Core::Frontend::CabinetParameters parameters{
+ .tag_info = applet_input_common.tag_info,
+ .register_info = applet_input_common.register_info,
+ .mode = applet_input_common.applet_mode,
+ };
+
+ switch (applet_input_common.applet_mode) {
+ case Service::NFP::CabinetMode::StartNicknameAndOwnerSettings:
+ case Service::NFP::CabinetMode::StartGameDataEraser:
+ case Service::NFP::CabinetMode::StartRestorer:
+ case Service::NFP::CabinetMode::StartFormatter:
+ frontend.ShowCabinetApplet(callback, parameters, nfp_device);
+ break;
+ default:
+ UNIMPLEMENTED_MSG("Unknown CabinetMode={}", applet_input_common.applet_mode);
+ DisplayCompleted(false, {});
+ break;
+ }
+}
+
+void Cabinet::DisplayCompleted(bool apply_changes, std::string_view amiibo_name) {
+ Service::Mii::MiiManager manager;
+ ReturnValueForAmiiboSettings applet_output{};
+
+ if (!apply_changes) {
+ Cancel();
+ }
+
+ if (nfp_device->GetCurrentState() != Service::NFP::DeviceState::TagFound &&
+ nfp_device->GetCurrentState() != Service::NFP::DeviceState::TagMounted) {
+ Cancel();
+ }
+
+ if (nfp_device->GetCurrentState() == Service::NFP::DeviceState::TagFound) {
+ nfp_device->Mount(Service::NFP::MountTarget::All);
+ }
+
+ switch (applet_input_common.applet_mode) {
+ case Service::NFP::CabinetMode::StartNicknameAndOwnerSettings: {
+ Service::NFP::AmiiboName name{};
+ std::memcpy(name.data(), amiibo_name.data(), std::min(amiibo_name.size(), name.size() - 1));
+ nfp_device->SetNicknameAndOwner(name);
+ break;
+ }
+ case Service::NFP::CabinetMode::StartGameDataEraser:
+ nfp_device->DeleteApplicationArea();
+ break;
+ case Service::NFP::CabinetMode::StartRestorer:
+ nfp_device->RestoreAmiibo();
+ break;
+ case Service::NFP::CabinetMode::StartFormatter:
+ nfp_device->DeleteAllData();
+ break;
+ default:
+ UNIMPLEMENTED_MSG("Unknown CabinetMode={}", applet_input_common.applet_mode);
+ break;
+ }
+
+ applet_output.device_handle = applet_input_common.device_handle;
+ applet_output.result = CabinetResult::Cancel;
+ const auto reg_result = nfp_device->GetRegisterInfo(applet_output.register_info);
+ const auto tag_result = nfp_device->GetTagInfo(applet_output.tag_info);
+ nfp_device->Finalize();
+
+ if (reg_result.IsSuccess()) {
+ applet_output.result |= CabinetResult::RegisterInfo;
+ }
+
+ if (tag_result.IsSuccess()) {
+ applet_output.result |= CabinetResult::TagInfo;
+ }
+
+ std::vector<u8> out_data(sizeof(ReturnValueForAmiiboSettings));
+ std::memcpy(out_data.data(), &applet_output, sizeof(ReturnValueForAmiiboSettings));
+
+ is_complete = true;
+
+ broker.PushNormalDataFromApplet(std::make_shared<IStorage>(system, std::move(out_data)));
+ broker.SignalStateChanged();
+}
+
+void Cabinet::Cancel() {
+ ReturnValueForAmiiboSettings applet_output{};
+ applet_output.device_handle = applet_input_common.device_handle;
+ applet_output.result = CabinetResult::Cancel;
+ nfp_device->Finalize();
+
+ std::vector<u8> out_data(sizeof(ReturnValueForAmiiboSettings));
+ std::memcpy(out_data.data(), &applet_output, sizeof(ReturnValueForAmiiboSettings));
+
+ is_complete = true;
+
+ broker.PushNormalDataFromApplet(std::make_shared<IStorage>(system, std::move(out_data)));
+ broker.SignalStateChanged();
+}
+
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/am/applets/applet_cabinet.h b/src/core/hle/service/am/applets/applet_cabinet.h
new file mode 100644
index 000000000..84197a807
--- /dev/null
+++ b/src/core/hle/service/am/applets/applet_cabinet.h
@@ -0,0 +1,104 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include <array>
+
+#include "core/hle/result.h"
+#include "core/hle/service/am/applets/applets.h"
+#include "core/hle/service/kernel_helpers.h"
+#include "core/hle/service/nfp/nfp_types.h"
+
+namespace Kernel {
+class KEvent;
+class KReadableEvent;
+} // namespace Kernel
+
+namespace Core {
+class System;
+} // namespace Core
+
+namespace Service::NFP {
+class NfpDevice;
+}
+
+namespace Service::AM::Applets {
+
+enum class CabinetAppletVersion : u32 {
+ Version1 = 0x1,
+};
+
+enum class CabinetResult : u8 {
+ Cancel = 0,
+ TagInfo = 1 << 1,
+ RegisterInfo = 1 << 2,
+ All = TagInfo | RegisterInfo,
+};
+DECLARE_ENUM_FLAG_OPERATORS(CabinetResult)
+
+// This is nn::nfp::AmiiboSettingsStartParam
+struct AmiiboSettingsStartParam {
+ u64 device_handle;
+ std::array<u8, 0x20> param_1;
+ u8 param_2;
+};
+static_assert(sizeof(AmiiboSettingsStartParam) == 0x30,
+ "AmiiboSettingsStartParam is an invalid size");
+
+#pragma pack(push, 1)
+// This is nn::nfp::StartParamForAmiiboSettings
+struct StartParamForAmiiboSettings {
+ u8 param_1;
+ Service::NFP::CabinetMode applet_mode;
+ u8 flags;
+ u8 amiibo_settings_1;
+ u64 device_handle;
+ Service::NFP::TagInfo tag_info;
+ Service::NFP::RegisterInfo register_info;
+ std::array<u8, 0x20> amiibo_settings_3;
+ INSERT_PADDING_BYTES(0x24);
+};
+static_assert(sizeof(StartParamForAmiiboSettings) == 0x1A8,
+ "StartParamForAmiiboSettings is an invalid size");
+
+// This is nn::nfp::ReturnValueForAmiiboSettings
+struct ReturnValueForAmiiboSettings {
+ CabinetResult result;
+ INSERT_PADDING_BYTES(0x3);
+ u64 device_handle;
+ Service::NFP::TagInfo tag_info;
+ Service::NFP::RegisterInfo register_info;
+ INSERT_PADDING_BYTES(0x24);
+};
+static_assert(sizeof(ReturnValueForAmiiboSettings) == 0x188,
+ "ReturnValueForAmiiboSettings is an invalid size");
+#pragma pack(pop)
+
+class Cabinet final : public Applet {
+public:
+ explicit Cabinet(Core::System& system_, LibraryAppletMode applet_mode_,
+ const Core::Frontend::CabinetApplet& frontend_);
+ ~Cabinet() override;
+
+ void Initialize() override;
+
+ bool TransactionComplete() const override;
+ Result GetStatus() const override;
+ void ExecuteInteractive() override;
+ void Execute() override;
+ void DisplayCompleted(bool apply_changes, std::string_view amiibo_name);
+ void Cancel();
+
+private:
+ const Core::Frontend::CabinetApplet& frontend;
+ Core::System& system;
+
+ bool is_complete{false};
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device;
+ Kernel::KEvent* availability_change_event;
+ KernelHelpers::ServiceContext service_context;
+ StartParamForAmiiboSettings applet_input_common{};
+};
+
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/am/applets/applet_error.cpp b/src/core/hle/service/am/applets/applet_error.cpp
index fcf34bf7e..bae0d99a6 100644
--- a/src/core/hle/service/am/applets/applet_error.cpp
+++ b/src/core/hle/service/am/applets/applet_error.cpp
@@ -144,6 +144,7 @@ void Error::Initialize() {
break;
default:
UNIMPLEMENTED_MSG("Unimplemented LibAppletError mode={:02X}!", mode);
+ break;
}
}
diff --git a/src/core/hle/service/am/applets/applet_general_backend.cpp b/src/core/hle/service/am/applets/applet_general_backend.cpp
index c34ef08b3..e50acdaf6 100644
--- a/src/core/hle/service/am/applets/applet_general_backend.cpp
+++ b/src/core/hle/service/am/applets/applet_general_backend.cpp
@@ -129,6 +129,7 @@ void Auth::Execute() {
}
default:
unimplemented_log();
+ break;
}
}
@@ -192,6 +193,7 @@ void PhotoViewer::Execute() {
break;
default:
UNIMPLEMENTED_MSG("Unimplemented PhotoViewer applet mode={:02X}!", mode);
+ break;
}
}
diff --git a/src/core/hle/service/am/applets/applets.cpp b/src/core/hle/service/am/applets/applets.cpp
index 7062df21c..10afbc2da 100644
--- a/src/core/hle/service/am/applets/applets.cpp
+++ b/src/core/hle/service/am/applets/applets.cpp
@@ -5,6 +5,7 @@
#include "common/assert.h"
#include "core/core.h"
+#include "core/frontend/applets/cabinet.h"
#include "core/frontend/applets/controller.h"
#include "core/frontend/applets/error.h"
#include "core/frontend/applets/general_frontend.h"
@@ -16,6 +17,7 @@
#include "core/hle/service/am/am.h"
#include "core/hle/service/am/applet_ae.h"
#include "core/hle/service/am/applet_oe.h"
+#include "core/hle/service/am/applets/applet_cabinet.h"
#include "core/hle/service/am/applets/applet_controller.h"
#include "core/hle/service/am/applets/applet_error.h"
#include "core/hle/service/am/applets/applet_general_backend.h"
@@ -171,13 +173,15 @@ void Applet::Initialize() {
AppletFrontendSet::AppletFrontendSet() = default;
-AppletFrontendSet::AppletFrontendSet(ControllerApplet controller_applet, ErrorApplet error_applet,
+AppletFrontendSet::AppletFrontendSet(CabinetApplet cabinet_applet,
+ ControllerApplet controller_applet, ErrorApplet error_applet,
MiiEdit mii_edit_,
ParentalControlsApplet parental_controls_applet,
PhotoViewer photo_viewer_, ProfileSelect profile_select_,
SoftwareKeyboard software_keyboard_, WebBrowser web_browser_)
- : controller{std::move(controller_applet)}, error{std::move(error_applet)},
- mii_edit{std::move(mii_edit_)}, parental_controls{std::move(parental_controls_applet)},
+ : cabinet{std::move(cabinet_applet)}, controller{std::move(controller_applet)},
+ error{std::move(error_applet)}, mii_edit{std::move(mii_edit_)},
+ parental_controls{std::move(parental_controls_applet)},
photo_viewer{std::move(photo_viewer_)}, profile_select{std::move(profile_select_)},
software_keyboard{std::move(software_keyboard_)}, web_browser{std::move(web_browser_)} {}
@@ -196,6 +200,10 @@ const AppletFrontendSet& AppletManager::GetAppletFrontendSet() const {
}
void AppletManager::SetAppletFrontendSet(AppletFrontendSet set) {
+ if (set.cabinet != nullptr) {
+ frontend.cabinet = std::move(set.cabinet);
+ }
+
if (set.controller != nullptr) {
frontend.controller = std::move(set.controller);
}
@@ -235,6 +243,10 @@ void AppletManager::SetDefaultAppletFrontendSet() {
}
void AppletManager::SetDefaultAppletsIfMissing() {
+ if (frontend.cabinet == nullptr) {
+ frontend.cabinet = std::make_unique<Core::Frontend::DefaultCabinetApplet>();
+ }
+
if (frontend.controller == nullptr) {
frontend.controller =
std::make_unique<Core::Frontend::DefaultControllerApplet>(system.HIDCore());
@@ -279,6 +291,8 @@ std::shared_ptr<Applet> AppletManager::GetApplet(AppletId id, LibraryAppletMode
switch (id) {
case AppletId::Auth:
return std::make_shared<Auth>(system, mode, *frontend.parental_controls);
+ case AppletId::Cabinet:
+ return std::make_shared<Cabinet>(system, mode, *frontend.cabinet);
case AppletId::Controller:
return std::make_shared<Controller>(system, mode, *frontend.controller);
case AppletId::Error:
diff --git a/src/core/hle/service/am/applets/applets.h b/src/core/hle/service/am/applets/applets.h
index 12c6a5b1a..a22eb62a8 100644
--- a/src/core/hle/service/am/applets/applets.h
+++ b/src/core/hle/service/am/applets/applets.h
@@ -16,6 +16,7 @@ class System;
}
namespace Core::Frontend {
+class CabinetApplet;
class ControllerApplet;
class ECommerceApplet;
class ErrorApplet;
@@ -176,6 +177,7 @@ protected:
};
struct AppletFrontendSet {
+ using CabinetApplet = std::unique_ptr<Core::Frontend::CabinetApplet>;
using ControllerApplet = std::unique_ptr<Core::Frontend::ControllerApplet>;
using ErrorApplet = std::unique_ptr<Core::Frontend::ErrorApplet>;
using MiiEdit = std::unique_ptr<Core::Frontend::MiiEditApplet>;
@@ -186,10 +188,11 @@ struct AppletFrontendSet {
using WebBrowser = std::unique_ptr<Core::Frontend::WebBrowserApplet>;
AppletFrontendSet();
- AppletFrontendSet(ControllerApplet controller_applet, ErrorApplet error_applet,
- MiiEdit mii_edit_, ParentalControlsApplet parental_controls_applet,
- PhotoViewer photo_viewer_, ProfileSelect profile_select_,
- SoftwareKeyboard software_keyboard_, WebBrowser web_browser_);
+ AppletFrontendSet(CabinetApplet cabinet_applet, ControllerApplet controller_applet,
+ ErrorApplet error_applet, MiiEdit mii_edit_,
+ ParentalControlsApplet parental_controls_applet, PhotoViewer photo_viewer_,
+ ProfileSelect profile_select_, SoftwareKeyboard software_keyboard_,
+ WebBrowser web_browser_);
~AppletFrontendSet();
AppletFrontendSet(const AppletFrontendSet&) = delete;
@@ -198,6 +201,7 @@ struct AppletFrontendSet {
AppletFrontendSet(AppletFrontendSet&&) noexcept;
AppletFrontendSet& operator=(AppletFrontendSet&&) noexcept;
+ CabinetApplet cabinet;
ControllerApplet controller;
ErrorApplet error;
MiiEdit mii_edit;
diff --git a/src/core/hle/service/audio/audin_u.cpp b/src/core/hle/service/audio/audin_u.cpp
index 608925dfc..053e8f9dd 100644
--- a/src/core/hle/service/audio/audin_u.cpp
+++ b/src/core/hle/service/audio/audin_u.cpp
@@ -122,10 +122,10 @@ private:
}
void GetReleasedAudioInBuffer(Kernel::HLERequestContext& ctx) {
- auto write_buffer_size = ctx.GetWriteBufferSize() / sizeof(u64);
- std::vector<u64> released_buffers(write_buffer_size, 0);
+ const auto write_buffer_size = ctx.GetWriteBufferNumElements<u64>();
+ std::vector<u64> released_buffers(write_buffer_size);
- auto count = impl->GetReleasedBuffers(released_buffers);
+ const auto count = impl->GetReleasedBuffers(released_buffers);
[[maybe_unused]] std::string tags{};
for (u32 i = 0; i < count; i++) {
@@ -228,7 +228,7 @@ void AudInU::ListAudioIns(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "called");
const auto write_count =
- static_cast<u32>(ctx.GetWriteBufferSize() / sizeof(AudioDevice::AudioDeviceName));
+ static_cast<u32>(ctx.GetWriteBufferNumElements<AudioDevice::AudioDeviceName>());
std::vector<AudioDevice::AudioDeviceName> device_names{};
u32 out_count{0};
@@ -248,7 +248,7 @@ void AudInU::ListAudioInsAutoFiltered(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "called");
const auto write_count =
- static_cast<u32>(ctx.GetWriteBufferSize() / sizeof(AudioDevice::AudioDeviceName));
+ static_cast<u32>(ctx.GetWriteBufferNumElements<AudioDevice::AudioDeviceName>());
std::vector<AudioDevice::AudioDeviceName> device_names{};
u32 out_count{0};
diff --git a/src/core/hle/service/audio/audout_u.cpp b/src/core/hle/service/audio/audout_u.cpp
index 122290c6a..29751f075 100644
--- a/src/core/hle/service/audio/audout_u.cpp
+++ b/src/core/hle/service/audio/audout_u.cpp
@@ -129,16 +129,16 @@ private:
}
void GetReleasedAudioOutBuffers(Kernel::HLERequestContext& ctx) {
- auto write_buffer_size = ctx.GetWriteBufferSize() / sizeof(u64);
- std::vector<u64> released_buffers(write_buffer_size, 0);
+ const auto write_buffer_size = ctx.GetWriteBufferNumElements<u64>();
+ std::vector<u64> released_buffers(write_buffer_size);
- auto count = impl->GetReleasedBuffers(released_buffers);
+ const auto count = impl->GetReleasedBuffers(released_buffers);
[[maybe_unused]] std::string tags{};
for (u32 i = 0; i < count; i++) {
tags += fmt::format("{:08X}, ", released_buffers[i]);
}
- [[maybe_unused]] auto sessionid{impl->GetSystem().GetSessionId()};
+ [[maybe_unused]] const auto sessionid{impl->GetSystem().GetSessionId()};
LOG_TRACE(Service_Audio, "called. Session {} released {} buffers: {}", sessionid, count,
tags);
@@ -244,7 +244,7 @@ void AudOutU::ListAudioOuts(Kernel::HLERequestContext& ctx) {
std::scoped_lock l{impl->mutex};
const auto write_count =
- static_cast<u32>(ctx.GetWriteBufferSize() / sizeof(AudioDevice::AudioDeviceName));
+ static_cast<u32>(ctx.GetWriteBufferNumElements<AudioDevice::AudioDeviceName>());
std::vector<AudioDevice::AudioDeviceName> device_names{};
if (write_count > 0) {
device_names.emplace_back("DeviceOut");
diff --git a/src/core/hle/service/audio/audren_u.cpp b/src/core/hle/service/audio/audren_u.cpp
index 13423dca6..3a1c231b6 100644
--- a/src/core/hle/service/audio/audren_u.cpp
+++ b/src/core/hle/service/audio/audren_u.cpp
@@ -14,6 +14,7 @@
#include "common/bit_util.h"
#include "common/common_funcs.h"
#include "common/logging/log.h"
+#include "common/polyfill_ranges.h"
#include "common/string_util.h"
#include "core/core.h"
#include "core/hle/ipc_helpers.h"
@@ -274,7 +275,7 @@ public:
private:
void ListAudioDeviceName(Kernel::HLERequestContext& ctx) {
- const size_t in_count = ctx.GetWriteBufferSize() / sizeof(AudioDevice::AudioDeviceName);
+ const size_t in_count = ctx.GetWriteBufferNumElements<AudioDevice::AudioDeviceName>();
std::vector<AudioDevice::AudioDeviceName> out_names{};
@@ -335,7 +336,7 @@ private:
}
void GetActiveAudioDeviceName(Kernel::HLERequestContext& ctx) {
- const auto write_size = ctx.GetWriteBufferSize() / sizeof(char);
+ const auto write_size = ctx.GetWriteBufferSize();
std::string out_name{"AudioTvOutput"};
LOG_DEBUG(Service_Audio, "(STUBBED) called. Name={}", out_name);
@@ -387,7 +388,7 @@ private:
}
void ListAudioOutputDeviceName(Kernel::HLERequestContext& ctx) {
- const size_t in_count = ctx.GetWriteBufferSize() / sizeof(AudioDevice::AudioDeviceName);
+ const size_t in_count = ctx.GetWriteBufferNumElements<AudioDevice::AudioDeviceName>();
std::vector<AudioDevice::AudioDeviceName> out_names{};
diff --git a/src/core/hle/service/audio/hwopus.cpp b/src/core/hle/service/audio/hwopus.cpp
index 8bafc3a98..825fb8bcc 100644
--- a/src/core/hle/service/audio/hwopus.cpp
+++ b/src/core/hle/service/audio/hwopus.cpp
@@ -68,7 +68,7 @@ private:
ExtraBehavior extra_behavior) {
u32 consumed = 0;
u32 sample_count = 0;
- std::vector<opus_int16> samples(ctx.GetWriteBufferSize() / sizeof(opus_int16));
+ std::vector<opus_int16> samples(ctx.GetWriteBufferNumElements<opus_int16>());
if (extra_behavior == ExtraBehavior::ResetContext) {
ResetDecoderContext();
diff --git a/src/core/hle/service/bcat/bcat_module.cpp b/src/core/hle/service/bcat/bcat_module.cpp
index bc08ac487..cbe690a5d 100644
--- a/src/core/hle/service/bcat/bcat_module.cpp
+++ b/src/core/hle/service/bcat/bcat_module.cpp
@@ -443,7 +443,7 @@ private:
}
void Read(Kernel::HLERequestContext& ctx) {
- auto write_size = ctx.GetWriteBufferSize() / sizeof(DeliveryCacheDirectoryEntry);
+ auto write_size = ctx.GetWriteBufferNumElements<DeliveryCacheDirectoryEntry>();
LOG_DEBUG(Service_BCAT, "called, write_size={:016X}", write_size);
@@ -533,7 +533,7 @@ private:
}
void EnumerateDeliveryCacheDirectory(Kernel::HLERequestContext& ctx) {
- auto size = ctx.GetWriteBufferSize() / sizeof(DirectoryName);
+ auto size = ctx.GetWriteBufferNumElements<DirectoryName>();
LOG_DEBUG(Service_BCAT, "called, size={:016X}", size);
diff --git a/src/core/hle/service/es/es.cpp b/src/core/hle/service/es/es.cpp
index ff9b0427c..d183e5829 100644
--- a/src/core/hle/service/es/es.cpp
+++ b/src/core/hle/service/es/es.cpp
@@ -192,12 +192,10 @@ private:
}
void ListCommonTicketRightsIds(Kernel::HLERequestContext& ctx) {
- u32 out_entries;
- if (keys.GetCommonTickets().empty())
- out_entries = 0;
- else
- out_entries = static_cast<u32>(ctx.GetWriteBufferSize() / sizeof(u128));
-
+ size_t out_entries = 0;
+ if (!keys.GetCommonTickets().empty()) {
+ out_entries = ctx.GetWriteBufferNumElements<u128>();
+ }
LOG_DEBUG(Service_ETicket, "called, entries={:016X}", out_entries);
keys.PopulateTickets();
@@ -206,20 +204,19 @@ private:
std::transform(tickets.begin(), tickets.end(), std::back_inserter(ids),
[](const auto& pair) { return pair.first; });
- out_entries = static_cast<u32>(std::min<std::size_t>(ids.size(), out_entries));
+ out_entries = std::min(ids.size(), out_entries);
ctx.WriteBuffer(ids.data(), out_entries * sizeof(u128));
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(ResultSuccess);
- rb.Push<u32>(out_entries);
+ rb.Push<u32>(static_cast<u32>(out_entries));
}
void ListPersonalizedTicketRightsIds(Kernel::HLERequestContext& ctx) {
- u32 out_entries;
- if (keys.GetPersonalizedTickets().empty())
- out_entries = 0;
- else
- out_entries = static_cast<u32>(ctx.GetWriteBufferSize() / sizeof(u128));
+ size_t out_entries = 0;
+ if (!keys.GetPersonalizedTickets().empty()) {
+ out_entries = ctx.GetWriteBufferNumElements<u128>();
+ }
LOG_DEBUG(Service_ETicket, "called, entries={:016X}", out_entries);
@@ -229,12 +226,12 @@ private:
std::transform(tickets.begin(), tickets.end(), std::back_inserter(ids),
[](const auto& pair) { return pair.first; });
- out_entries = static_cast<u32>(std::min<std::size_t>(ids.size(), out_entries));
+ out_entries = std::min(ids.size(), out_entries);
ctx.WriteBuffer(ids.data(), out_entries * sizeof(u128));
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(ResultSuccess);
- rb.Push<u32>(out_entries);
+ rb.Push<u32>(static_cast<u32>(out_entries));
}
void GetCommonTicketSize(Kernel::HLERequestContext& ctx) {
diff --git a/src/core/hle/service/filesystem/fsp_srv.cpp b/src/core/hle/service/filesystem/fsp_srv.cpp
index c08274ef9..fbb16a7da 100644
--- a/src/core/hle/service/filesystem/fsp_srv.cpp
+++ b/src/core/hle/service/filesystem/fsp_srv.cpp
@@ -277,7 +277,7 @@ private:
LOG_DEBUG(Service_FS, "called.");
// Calculate how many entries we can fit in the output buffer
- const u64 count_entries = ctx.GetWriteBufferSize() / sizeof(FileSys::Entry);
+ const u64 count_entries = ctx.GetWriteBufferNumElements<FileSys::Entry>();
// Cap at total number of entries.
const u64 actual_entries = std::min(count_entries, entries.size() - next_entry_index);
@@ -543,7 +543,7 @@ public:
LOG_DEBUG(Service_FS, "called");
// Calculate how many entries we can fit in the output buffer
- const u64 count_entries = ctx.GetWriteBufferSize() / sizeof(SaveDataInfo);
+ const u64 count_entries = ctx.GetWriteBufferNumElements<SaveDataInfo>();
// Cap at total number of entries.
const u64 actual_entries = std::min(count_entries, info.size() - next_entry_index);
diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp
index 79375bd2f..bf28440c6 100644
--- a/src/core/hle/service/hid/hid.cpp
+++ b/src/core/hle/service/hid/hid.cpp
@@ -36,8 +36,9 @@ namespace Service::HID {
// Updating period for each HID device.
// Period time is obtained by measuring the number of samples in a second on HW using a homebrew
-// Correct pad_update_ns is 4ms this is overclocked to lower input lag
-constexpr auto pad_update_ns = std::chrono::nanoseconds{1 * 1000 * 1000}; // (1ms, 1000Hz)
+// Correct npad_update_ns is 4ms this is overclocked to lower input lag
+constexpr auto npad_update_ns = std::chrono::nanoseconds{1 * 1000 * 1000}; // (1ms, 1000Hz)
+constexpr auto default_update_ns = std::chrono::nanoseconds{4 * 1000 * 1000}; // (4ms, 1000Hz)
constexpr auto mouse_keyboard_update_ns = std::chrono::nanoseconds{8 * 1000 * 1000}; // (8ms, 125Hz)
constexpr auto motion_update_ns = std::chrono::nanoseconds{5 * 1000 * 1000}; // (5ms, 200Hz)
@@ -75,11 +76,19 @@ IAppletResource::IAppletResource(Core::System& system_,
GetController<Controller_Stubbed>(HidController::UniquePad).SetCommonHeaderOffset(0x5A00);
// Register update callbacks
- pad_update_event = Core::Timing::CreateEvent(
+ npad_update_event = Core::Timing::CreateEvent(
"HID::UpdatePadCallback",
[this](std::uintptr_t user_data, s64 time,
std::chrono::nanoseconds ns_late) -> std::optional<std::chrono::nanoseconds> {
const auto guard = LockService();
+ UpdateNpad(user_data, ns_late);
+ return std::nullopt;
+ });
+ default_update_event = Core::Timing::CreateEvent(
+ "HID::UpdateDefaultCallback",
+ [this](std::uintptr_t user_data, s64 time,
+ std::chrono::nanoseconds ns_late) -> std::optional<std::chrono::nanoseconds> {
+ const auto guard = LockService();
UpdateControllers(user_data, ns_late);
return std::nullopt;
});
@@ -100,7 +109,9 @@ IAppletResource::IAppletResource(Core::System& system_,
return std::nullopt;
});
- system.CoreTiming().ScheduleLoopingEvent(pad_update_ns, pad_update_ns, pad_update_event);
+ system.CoreTiming().ScheduleLoopingEvent(npad_update_ns, npad_update_ns, npad_update_event);
+ system.CoreTiming().ScheduleLoopingEvent(default_update_ns, default_update_ns,
+ default_update_event);
system.CoreTiming().ScheduleLoopingEvent(mouse_keyboard_update_ns, mouse_keyboard_update_ns,
mouse_keyboard_update_event);
system.CoreTiming().ScheduleLoopingEvent(motion_update_ns, motion_update_ns,
@@ -118,7 +129,8 @@ void IAppletResource::DeactivateController(HidController controller) {
}
IAppletResource::~IAppletResource() {
- system.CoreTiming().UnscheduleEvent(pad_update_event, 0);
+ system.CoreTiming().UnscheduleEvent(npad_update_event, 0);
+ system.CoreTiming().UnscheduleEvent(default_update_event, 0);
system.CoreTiming().UnscheduleEvent(mouse_keyboard_update_event, 0);
system.CoreTiming().UnscheduleEvent(motion_update_event, 0);
}
@@ -144,10 +156,20 @@ void IAppletResource::UpdateControllers(std::uintptr_t user_data,
if (controller == controllers[static_cast<size_t>(HidController::Mouse)]) {
continue;
}
+ // Npad has it's own update event
+ if (controller == controllers[static_cast<size_t>(HidController::NPad)]) {
+ continue;
+ }
controller->OnUpdate(core_timing);
}
}
+void IAppletResource::UpdateNpad(std::uintptr_t user_data, std::chrono::nanoseconds ns_late) {
+ auto& core_timing = system.CoreTiming();
+
+ controllers[static_cast<size_t>(HidController::NPad)]->OnUpdate(core_timing);
+}
+
void IAppletResource::UpdateMouseKeyboard(std::uintptr_t user_data,
std::chrono::nanoseconds ns_late) {
auto& core_timing = system.CoreTiming();
diff --git a/src/core/hle/service/hid/hid.h b/src/core/hle/service/hid/hid.h
index 340d26fdc..b7c2a23ef 100644
--- a/src/core/hle/service/hid/hid.h
+++ b/src/core/hle/service/hid/hid.h
@@ -71,12 +71,14 @@ private:
void GetSharedMemoryHandle(Kernel::HLERequestContext& ctx);
void UpdateControllers(std::uintptr_t user_data, std::chrono::nanoseconds ns_late);
+ void UpdateNpad(std::uintptr_t user_data, std::chrono::nanoseconds ns_late);
void UpdateMouseKeyboard(std::uintptr_t user_data, std::chrono::nanoseconds ns_late);
void UpdateMotion(std::uintptr_t user_data, std::chrono::nanoseconds ns_late);
KernelHelpers::ServiceContext& service_context;
- std::shared_ptr<Core::Timing::EventType> pad_update_event;
+ std::shared_ptr<Core::Timing::EventType> npad_update_event;
+ std::shared_ptr<Core::Timing::EventType> default_update_event;
std::shared_ptr<Core::Timing::EventType> mouse_keyboard_update_event;
std::shared_ptr<Core::Timing::EventType> motion_update_event;
diff --git a/src/core/hle/service/ldn/ldn.cpp b/src/core/hle/service/ldn/ldn.cpp
index 6df563136..c49c61cff 100644
--- a/src/core/hle/service/ldn/ldn.cpp
+++ b/src/core/hle/service/ldn/ldn.cpp
@@ -292,7 +292,7 @@ public:
void GetNetworkInfoLatestUpdate(Kernel::HLERequestContext& ctx) {
const std::size_t network_buffer_size = ctx.GetWriteBufferSize(0);
- const std::size_t node_buffer_count = ctx.GetWriteBufferSize(1) / sizeof(NodeLatestUpdate);
+ const std::size_t node_buffer_count = ctx.GetWriteBufferNumElements<NodeLatestUpdate>(1);
if (node_buffer_count == 0 || network_buffer_size != sizeof(NetworkInfo)) {
LOG_ERROR(Service_LDN, "Invalid buffer, size = {}, count = {}", network_buffer_size,
@@ -333,7 +333,7 @@ public:
const auto channel{rp.PopEnum<WifiChannel>()};
const auto scan_filter{rp.PopRaw<ScanFilter>()};
- const std::size_t network_info_size = ctx.GetWriteBufferSize() / sizeof(NetworkInfo);
+ const std::size_t network_info_size = ctx.GetWriteBufferNumElements<NetworkInfo>();
if (network_info_size == 0) {
LOG_ERROR(Service_LDN, "Invalid buffer size {}", network_info_size);
diff --git a/src/core/hle/service/nfc/nfc.cpp b/src/core/hle/service/nfc/nfc.cpp
index 046c5f18f..2f4bacb3b 100644
--- a/src/core/hle/service/nfc/nfc.cpp
+++ b/src/core/hle/service/nfc/nfc.cpp
@@ -7,6 +7,7 @@
#include "common/settings.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/service/nfc/nfc.h"
+#include "core/hle/service/nfc/nfc_user.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sm/sm.h"
@@ -97,76 +98,6 @@ private:
}
};
-class IUser final : public ServiceFramework<IUser> {
-public:
- explicit IUser(Core::System& system_) : ServiceFramework{system_, "NFC::IUser"} {
- // clang-format off
- static const FunctionInfo functions[] = {
- {0, &IUser::InitializeOld, "InitializeOld"},
- {1, &IUser::FinalizeOld, "FinalizeOld"},
- {2, &IUser::GetStateOld, "GetStateOld"},
- {3, &IUser::IsNfcEnabledOld, "IsNfcEnabledOld"},
- {400, &IUser::InitializeOld, "Initialize"},
- {401, &IUser::FinalizeOld, "Finalize"},
- {402, &IUser::GetStateOld, "GetState"},
- {403, &IUser::IsNfcEnabledOld, "IsNfcEnabled"},
- {404, nullptr, "ListDevices"},
- {405, nullptr, "GetDeviceState"},
- {406, nullptr, "GetNpadId"},
- {407, nullptr, "AttachAvailabilityChangeEvent"},
- {408, nullptr, "StartDetection"},
- {409, nullptr, "StopDetection"},
- {410, nullptr, "GetTagInfo"},
- {411, nullptr, "AttachActivateEvent"},
- {412, nullptr, "AttachDeactivateEvent"},
- {1000, nullptr, "ReadMifare"},
- {1001, nullptr, "WriteMifare"},
- {1300, nullptr, "SendCommandByPassThrough"},
- {1301, nullptr, "KeepPassThroughSession"},
- {1302, nullptr, "ReleasePassThroughSession"},
- };
- // clang-format on
-
- RegisterHandlers(functions);
- }
-
-private:
- enum class NfcStates : u32 {
- Finalized = 6,
- };
-
- void InitializeOld(Kernel::HLERequestContext& ctx) {
- LOG_DEBUG(Service_NFC, "called");
-
- IPC::ResponseBuilder rb{ctx, 2, 0};
- rb.Push(ResultSuccess);
- // We don't deal with hardware initialization so we can just stub this.
- }
-
- void IsNfcEnabledOld(Kernel::HLERequestContext& ctx) {
- LOG_DEBUG(Service_NFC, "IsNfcEnabledOld");
-
- IPC::ResponseBuilder rb{ctx, 3};
- rb.Push(ResultSuccess);
- rb.PushRaw<u8>(true);
- }
-
- void GetStateOld(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_NFC, "(STUBBED) called");
-
- IPC::ResponseBuilder rb{ctx, 3};
- rb.Push(ResultSuccess);
- rb.PushEnum(NfcStates::Finalized); // TODO(ogniK): Figure out if this matches nfp
- }
-
- void FinalizeOld(Kernel::HLERequestContext& ctx) {
- LOG_WARNING(Service_NFC, "(STUBBED) called");
-
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(ResultSuccess);
- }
-};
-
class NFC_U final : public ServiceFramework<NFC_U> {
public:
explicit NFC_U(Core::System& system_) : ServiceFramework{system_, "nfc:user"} {
diff --git a/src/core/hle/service/nfc/nfc_device.cpp b/src/core/hle/service/nfc/nfc_device.cpp
new file mode 100644
index 000000000..4d514cf5f
--- /dev/null
+++ b/src/core/hle/service/nfc/nfc_device.cpp
@@ -0,0 +1,197 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include "common/input.h"
+#include "common/logging/log.h"
+#include "core/core.h"
+#include "core/hid/emulated_controller.h"
+#include "core/hid/hid_core.h"
+#include "core/hid/hid_types.h"
+#include "core/hle/ipc_helpers.h"
+#include "core/hle/kernel/k_event.h"
+#include "core/hle/service/nfc/nfc_device.h"
+#include "core/hle/service/nfc/nfc_result.h"
+#include "core/hle/service/nfc/nfc_user.h"
+
+namespace Service::NFC {
+NfcDevice::NfcDevice(Core::HID::NpadIdType npad_id_, Core::System& system_,
+ KernelHelpers::ServiceContext& service_context_,
+ Kernel::KEvent* availability_change_event_)
+ : npad_id{npad_id_}, system{system_}, service_context{service_context_},
+ availability_change_event{availability_change_event_} {
+ activate_event = service_context.CreateEvent("IUser:NFCActivateEvent");
+ deactivate_event = service_context.CreateEvent("IUser:NFCDeactivateEvent");
+ npad_device = system.HIDCore().GetEmulatedController(npad_id);
+
+ Core::HID::ControllerUpdateCallback engine_callback{
+ .on_change = [this](Core::HID::ControllerTriggerType type) { NpadUpdate(type); },
+ .is_npad_service = false,
+ };
+ is_controller_set = true;
+ callback_key = npad_device->SetCallback(engine_callback);
+}
+
+NfcDevice::~NfcDevice() {
+ activate_event->Close();
+ deactivate_event->Close();
+ if (!is_controller_set) {
+ return;
+ }
+ npad_device->DeleteCallback(callback_key);
+ is_controller_set = false;
+};
+
+void NfcDevice::NpadUpdate(Core::HID::ControllerTriggerType type) {
+ if (type == Core::HID::ControllerTriggerType::Connected ||
+ type == Core::HID::ControllerTriggerType::Disconnected) {
+ availability_change_event->Signal();
+ return;
+ }
+
+ if (type != Core::HID::ControllerTriggerType::Nfc) {
+ return;
+ }
+
+ if (!npad_device->IsConnected()) {
+ return;
+ }
+
+ const auto nfc_status = npad_device->GetNfc();
+ switch (nfc_status.state) {
+ case Common::Input::NfcState::NewAmiibo:
+ LoadNfcTag(nfc_status.data);
+ break;
+ case Common::Input::NfcState::AmiiboRemoved:
+ if (device_state != NFP::DeviceState::SearchingForTag) {
+ CloseNfcTag();
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+bool NfcDevice::LoadNfcTag(std::span<const u8> data) {
+ if (device_state != NFP::DeviceState::SearchingForTag) {
+ LOG_ERROR(Service_NFC, "Game is not looking for nfc tag, current state {}", device_state);
+ return false;
+ }
+
+ if (data.size() != sizeof(NFP::EncryptedNTAG215File)) {
+ LOG_ERROR(Service_NFC, "Not an amiibo, size={}", data.size());
+ return false;
+ }
+
+ memcpy(&encrypted_tag_data, data.data(), sizeof(NFP::EncryptedNTAG215File));
+
+ device_state = NFP::DeviceState::TagFound;
+ deactivate_event->GetReadableEvent().Clear();
+ activate_event->Signal();
+ return true;
+}
+
+void NfcDevice::CloseNfcTag() {
+ LOG_INFO(Service_NFC, "Remove nfc tag");
+
+ device_state = NFP::DeviceState::TagRemoved;
+ encrypted_tag_data = {};
+ activate_event->GetReadableEvent().Clear();
+ deactivate_event->Signal();
+}
+
+Kernel::KReadableEvent& NfcDevice::GetActivateEvent() const {
+ return activate_event->GetReadableEvent();
+}
+
+Kernel::KReadableEvent& NfcDevice::GetDeactivateEvent() const {
+ return deactivate_event->GetReadableEvent();
+}
+
+void NfcDevice::Initialize() {
+ device_state =
+ npad_device->HasNfc() ? NFP::DeviceState::Initialized : NFP::DeviceState::Unavailable;
+ encrypted_tag_data = {};
+}
+
+void NfcDevice::Finalize() {
+ if (device_state == NFP::DeviceState::SearchingForTag ||
+ device_state == NFP::DeviceState::TagRemoved) {
+ StopDetection();
+ }
+ device_state = NFP::DeviceState::Unavailable;
+}
+
+Result NfcDevice::StartDetection(s32 protocol_) {
+ if (device_state != NFP::DeviceState::Initialized &&
+ device_state != NFP::DeviceState::TagRemoved) {
+ LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
+ return WrongDeviceState;
+ }
+
+ if (!npad_device->SetPollingMode(Common::Input::PollingMode::NFC)) {
+ LOG_ERROR(Service_NFC, "Nfc not supported");
+ return NfcDisabled;
+ }
+
+ device_state = NFP::DeviceState::SearchingForTag;
+ protocol = protocol_;
+ return ResultSuccess;
+}
+
+Result NfcDevice::StopDetection() {
+ npad_device->SetPollingMode(Common::Input::PollingMode::Active);
+
+ if (device_state == NFP::DeviceState::Initialized) {
+ return ResultSuccess;
+ }
+
+ if (device_state == NFP::DeviceState::TagFound ||
+ device_state == NFP::DeviceState::TagMounted) {
+ CloseNfcTag();
+ return ResultSuccess;
+ }
+ if (device_state == NFP::DeviceState::SearchingForTag ||
+ device_state == NFP::DeviceState::TagRemoved) {
+ device_state = NFP::DeviceState::Initialized;
+ return ResultSuccess;
+ }
+
+ LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
+ return WrongDeviceState;
+}
+
+Result NfcDevice::GetTagInfo(NFP::TagInfo& tag_info) const {
+ if (device_state != NFP::DeviceState::TagFound &&
+ device_state != NFP::DeviceState::TagMounted) {
+ LOG_ERROR(Service_NFC, "Wrong device state {}", device_state);
+ if (device_state == NFP::DeviceState::TagRemoved) {
+ return TagRemoved;
+ }
+ return WrongDeviceState;
+ }
+
+ // Protocol and tag type may change here
+ tag_info = {
+ .uuid = encrypted_tag_data.uuid.uid,
+ .uuid_length = static_cast<u8>(encrypted_tag_data.uuid.uid.size()),
+ .protocol = NFP::TagProtocol::TypeA,
+ .tag_type = NFP::TagType::Type2,
+ };
+
+ return ResultSuccess;
+}
+
+u64 NfcDevice::GetHandle() const {
+ // Generate a handle based of the npad id
+ return static_cast<u64>(npad_id);
+}
+
+NFP::DeviceState NfcDevice::GetCurrentState() const {
+ return device_state;
+}
+
+Core::HID::NpadIdType NfcDevice::GetNpadId() const {
+ return npad_id;
+}
+
+} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc_device.h b/src/core/hle/service/nfc/nfc_device.h
new file mode 100644
index 000000000..fa1348f1a
--- /dev/null
+++ b/src/core/hle/service/nfc/nfc_device.h
@@ -0,0 +1,70 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_types.h"
+#include "core/hle/service/kernel_helpers.h"
+#include "core/hle/service/nfp/nfp_types.h"
+#include "core/hle/service/service.h"
+
+namespace Kernel {
+class KEvent;
+class KReadableEvent;
+} // namespace Kernel
+
+namespace Core {
+class System;
+} // namespace Core
+
+namespace Core::HID {
+class EmulatedController;
+enum class ControllerTriggerType;
+enum class NpadIdType : u32;
+} // namespace Core::HID
+
+namespace Service::NFC {
+class NfcDevice {
+public:
+ NfcDevice(Core::HID::NpadIdType npad_id_, Core::System& system_,
+ KernelHelpers::ServiceContext& service_context_,
+ Kernel::KEvent* availability_change_event_);
+ ~NfcDevice();
+
+ void Initialize();
+ void Finalize();
+
+ Result StartDetection(s32 protocol_);
+ Result StopDetection();
+
+ Result GetTagInfo(NFP::TagInfo& tag_info) const;
+
+ u64 GetHandle() const;
+ NFP::DeviceState GetCurrentState() const;
+ Core::HID::NpadIdType GetNpadId() const;
+
+ Kernel::KReadableEvent& GetActivateEvent() const;
+ Kernel::KReadableEvent& GetDeactivateEvent() const;
+
+private:
+ void NpadUpdate(Core::HID::ControllerTriggerType type);
+ bool LoadNfcTag(std::span<const u8> data);
+ void CloseNfcTag();
+
+ bool is_controller_set{};
+ int callback_key;
+ const Core::HID::NpadIdType npad_id;
+ Core::System& system;
+ Core::HID::EmulatedController* npad_device = nullptr;
+ KernelHelpers::ServiceContext& service_context;
+ Kernel::KEvent* activate_event = nullptr;
+ Kernel::KEvent* deactivate_event = nullptr;
+ Kernel::KEvent* availability_change_event = nullptr;
+
+ s32 protocol{};
+ NFP::DeviceState device_state{NFP::DeviceState::Unavailable};
+
+ NFP::EncryptedNTAG215File encrypted_tag_data{};
+};
+
+} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc_result.h b/src/core/hle/service/nfc/nfc_result.h
new file mode 100644
index 000000000..537dc15f4
--- /dev/null
+++ b/src/core/hle/service/nfc/nfc_result.h
@@ -0,0 +1,17 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "core/hle/result.h"
+
+namespace Service::NFC {
+
+constexpr Result DeviceNotFound(ErrorModule::NFC, 64);
+constexpr Result InvalidArgument(ErrorModule::NFC, 65);
+constexpr Result WrongDeviceState(ErrorModule::NFC, 73);
+constexpr Result NfcDisabled(ErrorModule::NFC, 80);
+constexpr Result TagRemoved(ErrorModule::NFC, 97);
+constexpr Result CorruptedData(ErrorModule::NFC, 144);
+
+} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc_user.cpp b/src/core/hle/service/nfc/nfc_user.cpp
new file mode 100644
index 000000000..ced2d560b
--- /dev/null
+++ b/src/core/hle/service/nfc/nfc_user.cpp
@@ -0,0 +1,365 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include "common/logging/log.h"
+#include "core/core.h"
+#include "core/hid/hid_types.h"
+#include "core/hle/ipc_helpers.h"
+#include "core/hle/kernel/k_event.h"
+#include "core/hle/service/nfc/nfc_device.h"
+#include "core/hle/service/nfc/nfc_result.h"
+#include "core/hle/service/nfc/nfc_user.h"
+#include "core/hle/service/time/clock_types.h"
+
+namespace Service::NFC {
+
+IUser::IUser(Core::System& system_)
+ : ServiceFramework{system_, "NFC::IUser"}, service_context{system_, service_name} {
+ static const FunctionInfo functions[] = {
+ {0, &IUser::Initialize, "InitializeOld"},
+ {1, &IUser::Finalize, "FinalizeOld"},
+ {2, &IUser::GetState, "GetStateOld"},
+ {3, &IUser::IsNfcEnabled, "IsNfcEnabledOld"},
+ {400, &IUser::Initialize, "Initialize"},
+ {401, &IUser::Finalize, "Finalize"},
+ {402, &IUser::GetState, "GetState"},
+ {403, &IUser::IsNfcEnabled, "IsNfcEnabled"},
+ {404, &IUser::ListDevices, "ListDevices"},
+ {405, &IUser::GetDeviceState, "GetDeviceState"},
+ {406, &IUser::GetNpadId, "GetNpadId"},
+ {407, &IUser::AttachAvailabilityChangeEvent, "AttachAvailabilityChangeEvent"},
+ {408, &IUser::StartDetection, "StartDetection"},
+ {409, &IUser::StopDetection, "StopDetection"},
+ {410, &IUser::GetTagInfo, "GetTagInfo"},
+ {411, &IUser::AttachActivateEvent, "AttachActivateEvent"},
+ {412, &IUser::AttachDeactivateEvent, "AttachDeactivateEvent"},
+ {1000, nullptr, "ReadMifare"},
+ {1001, nullptr, "WriteMifare"},
+ {1300, &IUser::SendCommandByPassThrough, "SendCommandByPassThrough"},
+ {1301, nullptr, "KeepPassThroughSession"},
+ {1302, nullptr, "ReleasePassThroughSession"},
+ };
+ RegisterHandlers(functions);
+
+ availability_change_event = service_context.CreateEvent("IUser:AvailabilityChangeEvent");
+
+ for (u32 device_index = 0; device_index < 10; device_index++) {
+ devices[device_index] =
+ std::make_shared<NfcDevice>(Core::HID::IndexToNpadIdType(device_index), system,
+ service_context, availability_change_event);
+ }
+}
+
+IUser ::~IUser() {
+ availability_change_event->Close();
+}
+
+void IUser::Initialize(Kernel::HLERequestContext& ctx) {
+ LOG_INFO(Service_NFC, "called");
+
+ state = State::Initialized;
+
+ for (auto& device : devices) {
+ device->Initialize();
+ }
+
+ IPC::ResponseBuilder rb{ctx, 2, 0};
+ rb.Push(ResultSuccess);
+}
+
+void IUser::Finalize(Kernel::HLERequestContext& ctx) {
+ LOG_INFO(Service_NFC, "called");
+
+ state = State::NonInitialized;
+
+ for (auto& device : devices) {
+ device->Finalize();
+ }
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ResultSuccess);
+}
+
+void IUser::GetState(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NFC, "called");
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(ResultSuccess);
+ rb.PushEnum(state);
+}
+
+void IUser::IsNfcEnabled(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_NFC, "called");
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(ResultSuccess);
+ rb.Push(state != State::NonInitialized);
+}
+
+void IUser::ListDevices(Kernel::HLERequestContext& ctx) {
+ LOG_INFO(Service_NFC, "called");
+
+ if (state == State::NonInitialized) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(NfcDisabled);
+ return;
+ }
+
+ if (!ctx.CanWriteBuffer()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(InvalidArgument);
+ return;
+ }
+
+ if (ctx.GetWriteBufferSize() == 0) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(InvalidArgument);
+ return;
+ }
+
+ std::vector<u64> nfp_devices;
+ const std::size_t max_allowed_devices = ctx.GetWriteBufferNumElements<u64>();
+
+ for (auto& device : devices) {
+ if (nfp_devices.size() >= max_allowed_devices) {
+ continue;
+ }
+ if (device->GetCurrentState() != NFP::DeviceState::Unavailable) {
+ nfp_devices.push_back(device->GetHandle());
+ }
+ }
+
+ if (nfp_devices.empty()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(DeviceNotFound);
+ return;
+ }
+
+ ctx.WriteBuffer(nfp_devices);
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(ResultSuccess);
+ rb.Push(static_cast<s32>(nfp_devices.size()));
+}
+
+void IUser::GetDeviceState(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto device_handle{rp.Pop<u64>()};
+ LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
+
+ auto device = GetNfcDevice(device_handle);
+
+ if (!device.has_value()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(DeviceNotFound);
+ return;
+ }
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(ResultSuccess);
+ rb.PushEnum(device.value()->GetCurrentState());
+}
+
+void IUser::GetNpadId(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto device_handle{rp.Pop<u64>()};
+ LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
+
+ if (state == State::NonInitialized) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(NfcDisabled);
+ return;
+ }
+
+ auto device = GetNfcDevice(device_handle);
+
+ if (!device.has_value()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(DeviceNotFound);
+ return;
+ }
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(ResultSuccess);
+ rb.PushEnum(device.value()->GetNpadId());
+}
+
+void IUser::AttachAvailabilityChangeEvent(Kernel::HLERequestContext& ctx) {
+ LOG_INFO(Service_NFC, "called");
+
+ if (state == State::NonInitialized) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(NfcDisabled);
+ return;
+ }
+
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(ResultSuccess);
+ rb.PushCopyObjects(availability_change_event->GetReadableEvent());
+}
+
+void IUser::StartDetection(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto device_handle{rp.Pop<u64>()};
+ const auto nfp_protocol{rp.Pop<s32>()};
+ LOG_INFO(Service_NFC, "called, device_handle={}, nfp_protocol={}", device_handle, nfp_protocol);
+
+ if (state == State::NonInitialized) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(NfcDisabled);
+ return;
+ }
+
+ auto device = GetNfcDevice(device_handle);
+
+ if (!device.has_value()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(DeviceNotFound);
+ return;
+ }
+
+ const auto result = device.value()->StartDetection(nfp_protocol);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(result);
+}
+
+void IUser::StopDetection(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto device_handle{rp.Pop<u64>()};
+ LOG_INFO(Service_NFC, "called, device_handle={}", device_handle);
+
+ if (state == State::NonInitialized) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(NfcDisabled);
+ return;
+ }
+
+ auto device = GetNfcDevice(device_handle);
+
+ if (!device.has_value()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(DeviceNotFound);
+ return;
+ }
+
+ const auto result = device.value()->StopDetection();
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(result);
+}
+
+void IUser::GetTagInfo(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto device_handle{rp.Pop<u64>()};
+ LOG_INFO(Service_NFC, "called, device_handle={}", device_handle);
+
+ if (state == State::NonInitialized) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(NfcDisabled);
+ return;
+ }
+
+ auto device = GetNfcDevice(device_handle);
+
+ if (!device.has_value()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(DeviceNotFound);
+ return;
+ }
+
+ NFP::TagInfo tag_info{};
+ const auto result = device.value()->GetTagInfo(tag_info);
+ ctx.WriteBuffer(tag_info);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(result);
+}
+
+void IUser::AttachActivateEvent(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto device_handle{rp.Pop<u64>()};
+ LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
+
+ if (state == State::NonInitialized) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(NfcDisabled);
+ return;
+ }
+
+ auto device = GetNfcDevice(device_handle);
+
+ if (!device.has_value()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(DeviceNotFound);
+ return;
+ }
+
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(ResultSuccess);
+ rb.PushCopyObjects(device.value()->GetActivateEvent());
+}
+
+void IUser::AttachDeactivateEvent(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto device_handle{rp.Pop<u64>()};
+ LOG_DEBUG(Service_NFC, "called, device_handle={}", device_handle);
+
+ if (state == State::NonInitialized) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(NfcDisabled);
+ return;
+ }
+
+ auto device = GetNfcDevice(device_handle);
+
+ if (!device.has_value()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(DeviceNotFound);
+ return;
+ }
+
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(ResultSuccess);
+ rb.PushCopyObjects(device.value()->GetDeactivateEvent());
+}
+
+void IUser::SendCommandByPassThrough(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto device_handle{rp.Pop<u64>()};
+ const auto timeout{rp.PopRaw<Time::Clock::TimeSpanType>()};
+ const auto command_data{ctx.ReadBuffer()};
+
+ LOG_INFO(Service_NFC, "(STUBBED) called, device_handle={}, timeout={}, data_size={}",
+ device_handle, timeout.ToSeconds(), command_data.size());
+
+ if (state == State::NonInitialized) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(NfcDisabled);
+ return;
+ }
+
+ auto device = GetNfcDevice(device_handle);
+
+ if (!device.has_value()) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(DeviceNotFound);
+ return;
+ }
+
+ std::vector<u8> out_data(1);
+ // TODO: Request data from nfc device
+ ctx.WriteBuffer(out_data);
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(ResultSuccess);
+ rb.Push(static_cast<u32>(out_data.size()));
+}
+
+std::optional<std::shared_ptr<NfcDevice>> IUser::GetNfcDevice(u64 handle) {
+ for (auto& device : devices) {
+ if (device->GetHandle() == handle) {
+ return device;
+ }
+ }
+ return std::nullopt;
+}
+
+} // namespace Service::NFC
diff --git a/src/core/hle/service/nfc/nfc_user.h b/src/core/hle/service/nfc/nfc_user.h
new file mode 100644
index 000000000..a5a4f12f9
--- /dev/null
+++ b/src/core/hle/service/nfc/nfc_user.h
@@ -0,0 +1,52 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include <array>
+#include <memory>
+#include <optional>
+
+#include "core/hle/service/kernel_helpers.h"
+#include "core/hle/service/service.h"
+
+namespace Service::NFC {
+class NfcDevice;
+
+class IUser final : public ServiceFramework<IUser> {
+public:
+ explicit IUser(Core::System& system_);
+ ~IUser();
+
+private:
+ enum class State : u32 {
+ NonInitialized,
+ Initialized,
+ };
+
+ void Initialize(Kernel::HLERequestContext& ctx);
+ void Finalize(Kernel::HLERequestContext& ctx);
+ void GetState(Kernel::HLERequestContext& ctx);
+ void IsNfcEnabled(Kernel::HLERequestContext& ctx);
+ void ListDevices(Kernel::HLERequestContext& ctx);
+ void GetDeviceState(Kernel::HLERequestContext& ctx);
+ void GetNpadId(Kernel::HLERequestContext& ctx);
+ void AttachAvailabilityChangeEvent(Kernel::HLERequestContext& ctx);
+ void StartDetection(Kernel::HLERequestContext& ctx);
+ void StopDetection(Kernel::HLERequestContext& ctx);
+ void GetTagInfo(Kernel::HLERequestContext& ctx);
+ void AttachActivateEvent(Kernel::HLERequestContext& ctx);
+ void AttachDeactivateEvent(Kernel::HLERequestContext& ctx);
+ void SendCommandByPassThrough(Kernel::HLERequestContext& ctx);
+
+ std::optional<std::shared_ptr<NfcDevice>> GetNfcDevice(u64 handle);
+
+ KernelHelpers::ServiceContext service_context;
+
+ std::array<std::shared_ptr<NfcDevice>, 10> devices{};
+
+ State state{State::NonInitialized};
+ Kernel::KEvent* availability_change_event;
+};
+
+} // namespace Service::NFC
diff --git a/src/core/hle/service/nfp/amiibo_crypto.cpp b/src/core/hle/service/nfp/amiibo_crypto.cpp
index 167e29572..ffb2f959c 100644
--- a/src/core/hle/service/nfp/amiibo_crypto.cpp
+++ b/src/core/hle/service/nfp/amiibo_crypto.cpp
@@ -12,7 +12,6 @@
#include "common/fs/fs.h"
#include "common/fs/path_util.h"
#include "common/logging/log.h"
-#include "core/hle/service/mii/mii_manager.h"
#include "core/hle/service/nfp/amiibo_crypto.h"
namespace Service::NFP::AmiiboCrypto {
diff --git a/src/core/hle/service/nfp/nfp_device.cpp b/src/core/hle/service/nfp/nfp_device.cpp
index b19672560..c860fd1a1 100644
--- a/src/core/hle/service/nfp/nfp_device.cpp
+++ b/src/core/hle/service/nfp/nfp_device.cpp
@@ -2,10 +2,7 @@
// SPDX-License-Identifier: GPL-2.0-or-later
#include <array>
-#include <atomic>
-#include "common/fs/file.h"
-#include "common/fs/path_util.h"
#include "common/input.h"
#include "common/logging/log.h"
#include "common/string_util.h"
@@ -19,7 +16,6 @@
#include "core/hle/service/mii/mii_manager.h"
#include "core/hle/service/mii/types.h"
#include "core/hle/service/nfp/amiibo_crypto.h"
-#include "core/hle/service/nfp/nfp.h"
#include "core/hle/service/nfp/nfp_device.h"
#include "core/hle/service/nfp/nfp_result.h"
#include "core/hle/service/nfp/nfp_user.h"
@@ -49,6 +45,8 @@ NfpDevice::NfpDevice(Core::HID::NpadIdType npad_id_, Core::System& system_,
}
NfpDevice::~NfpDevice() {
+ activate_event->Close();
+ deactivate_event->Close();
if (!is_controller_set) {
return;
}
@@ -77,6 +75,9 @@ void NfpDevice::NpadUpdate(Core::HID::ControllerTriggerType type) {
LoadAmiibo(nfc_status.data);
break;
case Common::Input::NfcState::AmiiboRemoved:
+ if (device_state == DeviceState::Initialized || device_state == DeviceState::TagRemoved) {
+ break;
+ }
if (device_state != DeviceState::SearchingForTag) {
CloseAmiibo();
}
@@ -97,6 +98,8 @@ bool NfpDevice::LoadAmiibo(std::span<const u8> data) {
return false;
}
+ // TODO: Filter by allowed_protocols here
+
memcpy(&encrypted_tag_data, data.data(), sizeof(EncryptedNTAG215File));
device_state = DeviceState::TagFound;
@@ -143,7 +146,7 @@ void NfpDevice::Finalize() {
device_state = DeviceState::Unavailable;
}
-Result NfpDevice::StartDetection(s32 protocol_) {
+Result NfpDevice::StartDetection(TagProtocol allowed_protocol) {
if (device_state != DeviceState::Initialized && device_state != DeviceState::TagRemoved) {
LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
return WrongDeviceState;
@@ -155,7 +158,7 @@ Result NfpDevice::StartDetection(s32 protocol_) {
}
device_state = DeviceState::SearchingForTag;
- protocol = protocol_;
+ allowed_protocols = allowed_protocol;
return ResultSuccess;
}
@@ -469,6 +472,32 @@ Result NfpDevice::OpenApplicationArea(u32 access_id) {
return ResultSuccess;
}
+Result NfpDevice::GetApplicationAreaId(u32& application_area_id) const {
+ application_area_id = {};
+
+ if (device_state != DeviceState::TagMounted) {
+ LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
+ if (device_state == DeviceState::TagRemoved) {
+ return TagRemoved;
+ }
+ return WrongDeviceState;
+ }
+
+ if (mount_target == MountTarget::None || mount_target == MountTarget::Rom) {
+ LOG_ERROR(Service_NFP, "Amiibo is read only", device_state);
+ return WrongDeviceState;
+ }
+
+ if (tag_data.settings.settings.appdata_initialized.Value() == 0) {
+ LOG_WARNING(Service_NFP, "Application area is not initialized");
+ return ApplicationAreaIsNotInitialized;
+ }
+
+ application_area_id = tag_data.application_area_id;
+
+ return ResultSuccess;
+}
+
Result NfpDevice::GetApplicationArea(std::vector<u8>& data) const {
if (device_state != DeviceState::TagMounted) {
LOG_ERROR(Service_NFP, "Wrong device state {}", device_state);
diff --git a/src/core/hle/service/nfp/nfp_device.h b/src/core/hle/service/nfp/nfp_device.h
index 76d0e9ae4..b6a46f2ac 100644
--- a/src/core/hle/service/nfp/nfp_device.h
+++ b/src/core/hle/service/nfp/nfp_device.h
@@ -3,10 +3,10 @@
#pragma once
-#include <array>
+#include <span>
#include <vector>
-#include "common/common_funcs.h"
+#include "common/common_types.h"
#include "core/hle/service/kernel_helpers.h"
#include "core/hle/service/nfp/nfp_types.h"
#include "core/hle/service/service.h"
@@ -37,7 +37,7 @@ public:
void Initialize();
void Finalize();
- Result StartDetection(s32 protocol_);
+ Result StartDetection(TagProtocol allowed_protocol);
Result StopDetection();
Result Mount(MountTarget mount_target);
Result Unmount();
@@ -53,6 +53,7 @@ public:
Result DeleteAllData();
Result OpenApplicationArea(u32 access_id);
+ Result GetApplicationAreaId(u32& application_area_id) const;
Result GetApplicationArea(std::vector<u8>& data) const;
Result SetApplicationArea(std::span<const u8> data);
Result CreateApplicationArea(u32 access_id, std::span<const u8> data);
@@ -88,7 +89,7 @@ private:
bool is_data_moddified{};
bool is_app_area_open{};
- s32 protocol{};
+ TagProtocol allowed_protocols{};
s64 current_posix_time{};
MountTarget mount_target{MountTarget::None};
DeviceState device_state{DeviceState::Unavailable};
diff --git a/src/core/hle/service/nfp/nfp_types.h b/src/core/hle/service/nfp/nfp_types.h
index 63d5917cb..69858096a 100644
--- a/src/core/hle/service/nfp/nfp_types.h
+++ b/src/core/hle/service/nfp/nfp_types.h
@@ -88,11 +88,22 @@ enum class PackedTagType : u8 {
Type5, // ISO15693 RW/RO 540 bytes 106kbit/s
};
+// Verify this enum. It might be completely wrong default protocol is 0x48
enum class TagProtocol : u32 {
None,
- TypeA, // ISO14443A
- TypeB, // ISO14443B
- TypeF, // Sony Felica
+ TypeA = 1U << 0, // ISO14443A
+ TypeB = 1U << 1, // ISO14443B
+ TypeF = 1U << 2, // Sony Felica
+ Unknown1 = 1U << 3,
+ Unknown2 = 1U << 5,
+ All = 0xFFFFFFFFU,
+};
+
+enum class CabinetMode : u8 {
+ StartNicknameAndOwnerSettings,
+ StartGameDataEraser,
+ StartRestorer,
+ StartFormatter,
};
using UniqueSerialNumber = std::array<u8, 7>;
diff --git a/src/core/hle/service/nfp/nfp_user.cpp b/src/core/hle/service/nfp/nfp_user.cpp
index 33e2ef518..49816b4c7 100644
--- a/src/core/hle/service/nfp/nfp_user.cpp
+++ b/src/core/hle/service/nfp/nfp_user.cpp
@@ -1,9 +1,6 @@
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
-#include <array>
-#include <atomic>
-
#include "common/logging/log.h"
#include "core/core.h"
#include "core/hid/hid_types.h"
@@ -55,8 +52,12 @@ IUser::IUser(Core::System& system_)
}
}
+IUser ::~IUser() {
+ availability_change_event->Close();
+}
+
void IUser::Initialize(Kernel::HLERequestContext& ctx) {
- LOG_INFO(Service_NFC, "called");
+ LOG_INFO(Service_NFP, "called");
state = State::Initialized;
@@ -64,7 +65,7 @@ void IUser::Initialize(Kernel::HLERequestContext& ctx) {
device->Initialize();
}
- IPC::ResponseBuilder rb{ctx, 2, 0};
+ IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
@@ -103,9 +104,9 @@ void IUser::ListDevices(Kernel::HLERequestContext& ctx) {
}
std::vector<u64> nfp_devices;
- const std::size_t max_allowed_devices = ctx.GetWriteBufferSize() / sizeof(u64);
+ const std::size_t max_allowed_devices = ctx.GetWriteBufferNumElements<u64>();
- for (auto& device : devices) {
+ for (const auto& device : devices) {
if (nfp_devices.size() >= max_allowed_devices) {
continue;
}
@@ -114,7 +115,7 @@ void IUser::ListDevices(Kernel::HLERequestContext& ctx) {
}
}
- if (nfp_devices.size() == 0) {
+ if (nfp_devices.empty()) {
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(DeviceNotFound);
return;
@@ -130,7 +131,7 @@ void IUser::ListDevices(Kernel::HLERequestContext& ctx) {
void IUser::StartDetection(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const auto device_handle{rp.Pop<u64>()};
- const auto nfp_protocol{rp.Pop<s32>()};
+ const auto nfp_protocol{rp.PopEnum<TagProtocol>()};
LOG_INFO(Service_NFP, "called, device_handle={}, nfp_protocol={}", device_handle, nfp_protocol);
if (state == State::NonInitialized) {
@@ -551,9 +552,9 @@ void IUser::AttachDeactivateEvent(Kernel::HLERequestContext& ctx) {
}
void IUser::GetState(Kernel::HLERequestContext& ctx) {
- LOG_DEBUG(Service_NFC, "called");
+ LOG_DEBUG(Service_NFP, "called");
- IPC::ResponseBuilder rb{ctx, 3, 0};
+ IPC::ResponseBuilder rb{ctx, 3};
rb.Push(ResultSuccess);
rb.PushEnum(state);
}
diff --git a/src/core/hle/service/nfp/nfp_user.h b/src/core/hle/service/nfp/nfp_user.h
index 47aff3695..7e9a90af8 100644
--- a/src/core/hle/service/nfp/nfp_user.h
+++ b/src/core/hle/service/nfp/nfp_user.h
@@ -3,6 +3,10 @@
#pragma once
+#include <array>
+#include <memory>
+#include <optional>
+
#include "core/hle/service/kernel_helpers.h"
#include "core/hle/service/service.h"
@@ -12,6 +16,7 @@ class NfpDevice;
class IUser final : public ServiceFramework<IUser> {
public:
explicit IUser(Core::System& system_);
+ ~IUser();
private:
enum class State : u32 {
diff --git a/src/core/hle/service/nifm/nifm.cpp b/src/core/hle/service/nifm/nifm.cpp
index e3ef06481..4fa9f51a6 100644
--- a/src/core/hle/service/nifm/nifm.cpp
+++ b/src/core/hle/service/nifm/nifm.cpp
@@ -129,6 +129,9 @@ static_assert(sizeof(NifmNetworkProfileData) == 0x18E,
"NifmNetworkProfileData has incorrect size.");
#pragma pack(pop)
+constexpr Result ResultPendingConnection{ErrorModule::NIFM, 111};
+constexpr Result ResultNetworkCommunicationDisabled{ErrorModule::NIFM, 1111};
+
class IScanRequest final : public ServiceFramework<IScanRequest> {
public:
explicit IScanRequest(Core::System& system_) : ServiceFramework{system_, "IScanRequest"} {
@@ -192,6 +195,10 @@ private:
void Submit(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+ if (state == RequestState::NotSubmitted) {
+ UpdateState(RequestState::Pending);
+ }
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
@@ -201,19 +208,32 @@ private:
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(ResultSuccess);
-
- if (Network::GetHostIPv4Address().has_value()) {
- rb.PushEnum(RequestState::Connected);
- } else {
- rb.PushEnum(RequestState::NotSubmitted);
- }
+ rb.PushEnum(state);
}
void GetResult(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
+ const auto result = [this] {
+ const auto has_connection = Network::GetHostIPv4Address().has_value();
+ switch (state) {
+ case RequestState::NotSubmitted:
+ return has_connection ? ResultSuccess : ResultNetworkCommunicationDisabled;
+ case RequestState::Pending:
+ if (has_connection) {
+ UpdateState(RequestState::Connected);
+ } else {
+ UpdateState(RequestState::Error);
+ }
+ return ResultPendingConnection;
+ case RequestState::Connected:
+ default:
+ return ResultSuccess;
+ }
+ }();
+
IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(ResultSuccess);
+ rb.Push(result);
}
void GetSystemEventReadableHandles(Kernel::HLERequestContext& ctx) {
@@ -252,8 +272,15 @@ private:
rb.Push<u32>(0);
}
+ void UpdateState(RequestState new_state) {
+ state = new_state;
+ event1->Signal();
+ }
+
KernelHelpers::ServiceContext service_context;
+ RequestState state;
+
Kernel::KEvent* event1;
Kernel::KEvent* event2;
};
diff --git a/src/core/hle/service/ns/iplatform_service_manager.cpp b/src/core/hle/service/ns/iplatform_service_manager.cpp
index fd047ff26..1fab2f0dd 100644
--- a/src/core/hle/service/ns/iplatform_service_manager.cpp
+++ b/src/core/hle/service/ns/iplatform_service_manager.cpp
@@ -279,13 +279,10 @@ void IPlatformServiceManager::GetSharedFontInOrderOfPriority(Kernel::HLERequestC
font_sizes.push_back(region.size);
}
- // Resize buffers if game requests smaller size output.
- font_codes.resize(
- std::min<std::size_t>(font_codes.size(), ctx.GetWriteBufferSize(0) / sizeof(u32)));
- font_offsets.resize(
- std::min<std::size_t>(font_offsets.size(), ctx.GetWriteBufferSize(1) / sizeof(u32)));
- font_sizes.resize(
- std::min<std::size_t>(font_sizes.size(), ctx.GetWriteBufferSize(2) / sizeof(u32)));
+ // Resize buffers if game requests smaller size output
+ font_codes.resize(std::min(font_codes.size(), ctx.GetWriteBufferNumElements<u32>(0)));
+ font_offsets.resize(std::min(font_offsets.size(), ctx.GetWriteBufferNumElements<u32>(1)));
+ font_sizes.resize(std::min(font_sizes.size(), ctx.GetWriteBufferNumElements<u32>(2)));
ctx.WriteBuffer(font_codes, 0);
ctx.WriteBuffer(font_offsets, 1);
diff --git a/src/core/hle/service/nvdrv/core/syncpoint_manager.cpp b/src/core/hle/service/nvdrv/core/syncpoint_manager.cpp
index eda2041a0..aba51d280 100644
--- a/src/core/hle/service/nvdrv/core/syncpoint_manager.cpp
+++ b/src/core/hle/service/nvdrv/core/syncpoint_manager.cpp
@@ -28,13 +28,15 @@ SyncpointManager::SyncpointManager(Tegra::Host1x::Host1x& host1x_) : host1x{host
SyncpointManager::~SyncpointManager() = default;
u32 SyncpointManager::ReserveSyncpoint(u32 id, bool client_managed) {
- if (syncpoints.at(id).reserved) {
+ auto& syncpoint = syncpoints.at(id);
+
+ if (syncpoint.reserved) {
ASSERT_MSG(false, "Requested syncpoint is in use");
return 0;
}
- syncpoints.at(id).reserved = true;
- syncpoints.at(id).interface_managed = client_managed;
+ syncpoint.reserved = true;
+ syncpoint.interface_managed = client_managed;
return id;
}
@@ -56,11 +58,12 @@ u32 SyncpointManager::AllocateSyncpoint(bool client_managed) {
void SyncpointManager::FreeSyncpoint(u32 id) {
std::lock_guard lock(reservation_lock);
- ASSERT(syncpoints.at(id).reserved);
- syncpoints.at(id).reserved = false;
+ auto& syncpoint = syncpoints.at(id);
+ ASSERT(syncpoint.reserved);
+ syncpoint.reserved = false;
}
-bool SyncpointManager::IsSyncpointAllocated(u32 id) {
+bool SyncpointManager::IsSyncpointAllocated(u32 id) const {
return (id <= SyncpointCount) && syncpoints[id].reserved;
}
@@ -69,7 +72,7 @@ bool SyncpointManager::HasSyncpointExpired(u32 id, u32 threshold) const {
if (!syncpoint.reserved) {
ASSERT(false);
- return 0;
+ return false;
}
// If the interface manages counters then we don't keep track of the maximum value as it handles
@@ -82,40 +85,51 @@ bool SyncpointManager::HasSyncpointExpired(u32 id, u32 threshold) const {
}
u32 SyncpointManager::IncrementSyncpointMaxExt(u32 id, u32 amount) {
- if (!syncpoints.at(id).reserved) {
+ auto& syncpoint = syncpoints.at(id);
+
+ if (!syncpoint.reserved) {
ASSERT(false);
return 0;
}
- return syncpoints.at(id).counter_max += amount;
+ return syncpoint.counter_max += amount;
}
u32 SyncpointManager::ReadSyncpointMinValue(u32 id) {
- if (!syncpoints.at(id).reserved) {
+ auto& syncpoint = syncpoints.at(id);
+
+ if (!syncpoint.reserved) {
ASSERT(false);
return 0;
}
- return syncpoints.at(id).counter_min;
+ return syncpoint.counter_min;
}
u32 SyncpointManager::UpdateMin(u32 id) {
- if (!syncpoints.at(id).reserved) {
+ auto& syncpoint = syncpoints.at(id);
+
+ if (!syncpoint.reserved) {
ASSERT(false);
return 0;
}
- syncpoints.at(id).counter_min = host1x.GetSyncpointManager().GetHostSyncpointValue(id);
- return syncpoints.at(id).counter_min;
+ syncpoint.counter_min = host1x.GetSyncpointManager().GetHostSyncpointValue(id);
+ return syncpoint.counter_min;
}
NvFence SyncpointManager::GetSyncpointFence(u32 id) {
- if (!syncpoints.at(id).reserved) {
+ auto& syncpoint = syncpoints.at(id);
+
+ if (!syncpoint.reserved) {
ASSERT(false);
return NvFence{};
}
- return {.id = static_cast<s32>(id), .value = syncpoints.at(id).counter_max};
+ return {
+ .id = static_cast<s32>(id),
+ .value = syncpoint.counter_max,
+ };
}
} // namespace Service::Nvidia::NvCore
diff --git a/src/core/hle/service/nvdrv/core/syncpoint_manager.h b/src/core/hle/service/nvdrv/core/syncpoint_manager.h
index b76ef9032..4f2cefae5 100644
--- a/src/core/hle/service/nvdrv/core/syncpoint_manager.h
+++ b/src/core/hle/service/nvdrv/core/syncpoint_manager.h
@@ -44,7 +44,7 @@ public:
/**
* @brief Checks if the given syncpoint is both allocated and below the number of HW syncpoints
*/
- bool IsSyncpointAllocated(u32 id);
+ bool IsSyncpointAllocated(u32 id) const;
/**
* @brief Finds a free syncpoint and reserves it
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp b/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp
index ced57dfe6..b97813fbc 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp
@@ -300,11 +300,10 @@ Kernel::KEvent* nvhost_ctrl_gpu::QueryEvent(u32 event_id) {
return error_notifier_event;
case 2:
return unknown_event;
- default: {
+ default:
LOG_CRITICAL(Service_NVDRV, "Unknown Ctrl GPU Event {}", event_id);
+ return nullptr;
}
- }
- return nullptr;
}
} // namespace Service::Nvidia::Devices
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_gpu.cpp b/src/core/hle/service/nvdrv/devices/nvhost_gpu.cpp
index 45a759fa8..e123564c6 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_gpu.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_gpu.cpp
@@ -364,11 +364,10 @@ Kernel::KEvent* nvhost_gpu::QueryEvent(u32 event_id) {
return sm_exception_breakpoint_pause_report_event;
case 3:
return error_notifier_event;
- default: {
+ default:
LOG_CRITICAL(Service_NVDRV, "Unknown Ctrl GPU Event {}", event_id);
+ return nullptr;
}
- }
- return nullptr;
}
} // namespace Service::Nvidia::Devices
diff --git a/src/core/hle/service/nvdrv/nvdrv.cpp b/src/core/hle/service/nvdrv/nvdrv.cpp
index 9f4c7c99a..6fc8565c0 100644
--- a/src/core/hle/service/nvdrv/nvdrv.cpp
+++ b/src/core/hle/service/nvdrv/nvdrv.cpp
@@ -55,48 +55,40 @@ void InstallInterfaces(SM::ServiceManager& service_manager, NVFlinger::NVFlinger
Module::Module(Core::System& system)
: container{system.Host1x()}, service_context{system, "nvdrv"}, events_interface{*this} {
builders["/dev/nvhost-as-gpu"] = [this, &system](DeviceFD fd) {
- std::shared_ptr<Devices::nvdevice> device =
- std::make_shared<Devices::nvhost_as_gpu>(system, *this, container);
- return open_files.emplace(fd, device).first;
+ auto device = std::make_shared<Devices::nvhost_as_gpu>(system, *this, container);
+ return open_files.emplace(fd, std::move(device)).first;
};
builders["/dev/nvhost-gpu"] = [this, &system](DeviceFD fd) {
- std::shared_ptr<Devices::nvdevice> device =
- std::make_shared<Devices::nvhost_gpu>(system, events_interface, container);
- return open_files.emplace(fd, device).first;
+ auto device = std::make_shared<Devices::nvhost_gpu>(system, events_interface, container);
+ return open_files.emplace(fd, std::move(device)).first;
};
builders["/dev/nvhost-ctrl-gpu"] = [this, &system](DeviceFD fd) {
- std::shared_ptr<Devices::nvdevice> device =
- std::make_shared<Devices::nvhost_ctrl_gpu>(system, events_interface);
- return open_files.emplace(fd, device).first;
+ auto device = std::make_shared<Devices::nvhost_ctrl_gpu>(system, events_interface);
+ return open_files.emplace(fd, std::move(device)).first;
};
builders["/dev/nvmap"] = [this, &system](DeviceFD fd) {
- std::shared_ptr<Devices::nvdevice> device =
- std::make_shared<Devices::nvmap>(system, container);
- return open_files.emplace(fd, device).first;
+ auto device = std::make_shared<Devices::nvmap>(system, container);
+ return open_files.emplace(fd, std::move(device)).first;
};
builders["/dev/nvdisp_disp0"] = [this, &system](DeviceFD fd) {
- std::shared_ptr<Devices::nvdevice> device =
- std::make_shared<Devices::nvdisp_disp0>(system, container);
- return open_files.emplace(fd, device).first;
+ auto device = std::make_shared<Devices::nvdisp_disp0>(system, container);
+ return open_files.emplace(fd, std::move(device)).first;
};
builders["/dev/nvhost-ctrl"] = [this, &system](DeviceFD fd) {
- std::shared_ptr<Devices::nvdevice> device =
- std::make_shared<Devices::nvhost_ctrl>(system, events_interface, container);
- return open_files.emplace(fd, device).first;
+ auto device = std::make_shared<Devices::nvhost_ctrl>(system, events_interface, container);
+ return open_files.emplace(fd, std::move(device)).first;
};
builders["/dev/nvhost-nvdec"] = [this, &system](DeviceFD fd) {
- std::shared_ptr<Devices::nvdevice> device =
- std::make_shared<Devices::nvhost_nvdec>(system, container);
- return open_files.emplace(fd, device).first;
+ auto device = std::make_shared<Devices::nvhost_nvdec>(system, container);
+ return open_files.emplace(fd, std::move(device)).first;
};
builders["/dev/nvhost-nvjpg"] = [this, &system](DeviceFD fd) {
- std::shared_ptr<Devices::nvdevice> device = std::make_shared<Devices::nvhost_nvjpg>(system);
- return open_files.emplace(fd, device).first;
+ auto device = std::make_shared<Devices::nvhost_nvjpg>(system);
+ return open_files.emplace(fd, std::move(device)).first;
};
builders["/dev/nvhost-vic"] = [this, &system](DeviceFD fd) {
- std::shared_ptr<Devices::nvdevice> device =
- std::make_shared<Devices::nvhost_vic>(system, container);
- return open_files.emplace(fd, device).first;
+ auto device = std::make_shared<Devices::nvhost_vic>(system, container);
+ return open_files.emplace(fd, std::move(device)).first;
};
}
diff --git a/src/core/hle/service/nvflinger/buffer_item_consumer.cpp b/src/core/hle/service/nvflinger/buffer_item_consumer.cpp
index 6d2c92a2c..152bb5bdf 100644
--- a/src/core/hle/service/nvflinger/buffer_item_consumer.cpp
+++ b/src/core/hle/service/nvflinger/buffer_item_consumer.cpp
@@ -39,7 +39,7 @@ Status BufferItemConsumer::AcquireBuffer(BufferItem* item, std::chrono::nanoseco
return Status::NoError;
}
-Status BufferItemConsumer::ReleaseBuffer(const BufferItem& item, Fence& release_fence) {
+Status BufferItemConsumer::ReleaseBuffer(const BufferItem& item, const Fence& release_fence) {
std::scoped_lock lock{mutex};
if (const auto status = AddReleaseFenceLocked(item.buf, item.graphic_buffer, release_fence);
diff --git a/src/core/hle/service/nvflinger/buffer_item_consumer.h b/src/core/hle/service/nvflinger/buffer_item_consumer.h
index 69046233d..a5c655d9e 100644
--- a/src/core/hle/service/nvflinger/buffer_item_consumer.h
+++ b/src/core/hle/service/nvflinger/buffer_item_consumer.h
@@ -22,7 +22,7 @@ public:
explicit BufferItemConsumer(std::unique_ptr<BufferQueueConsumer> consumer);
Status AcquireBuffer(BufferItem* item, std::chrono::nanoseconds present_when,
bool wait_for_fence = true);
- Status ReleaseBuffer(const BufferItem& item, Fence& release_fence);
+ Status ReleaseBuffer(const BufferItem& item, const Fence& release_fence);
};
} // namespace Service::android
diff --git a/src/core/hle/service/nvflinger/buffer_queue_consumer.cpp b/src/core/hle/service/nvflinger/buffer_queue_consumer.cpp
index 1ce67c771..0767e548d 100644
--- a/src/core/hle/service/nvflinger/buffer_queue_consumer.cpp
+++ b/src/core/hle/service/nvflinger/buffer_queue_consumer.cpp
@@ -169,7 +169,7 @@ Status BufferQueueConsumer::Connect(std::shared_ptr<IConsumerListener> consumer_
return Status::NoInit;
}
- core->consumer_listener = consumer_listener;
+ core->consumer_listener = std::move(consumer_listener);
core->consumer_controlled_by_app = controlled_by_app;
return Status::NoError;
diff --git a/src/core/hle/service/nvflinger/buffer_queue_core.cpp b/src/core/hle/service/nvflinger/buffer_queue_core.cpp
index ea4a14ea4..3d1338e66 100644
--- a/src/core/hle/service/nvflinger/buffer_queue_core.cpp
+++ b/src/core/hle/service/nvflinger/buffer_queue_core.cpp
@@ -23,15 +23,17 @@ void BufferQueueCore::NotifyShutdown() {
}
void BufferQueueCore::SignalDequeueCondition() {
+ dequeue_possible.store(true);
dequeue_condition.notify_all();
}
-bool BufferQueueCore::WaitForDequeueCondition() {
+bool BufferQueueCore::WaitForDequeueCondition(std::unique_lock<std::mutex>& lk) {
if (is_shutting_down) {
return false;
}
- dequeue_condition.wait(mutex);
+ dequeue_condition.wait(lk, [&] { return dequeue_possible.load(); });
+ dequeue_possible.store(false);
return true;
}
diff --git a/src/core/hle/service/nvflinger/buffer_queue_core.h b/src/core/hle/service/nvflinger/buffer_queue_core.h
index ca6baefaf..85b3bc4c1 100644
--- a/src/core/hle/service/nvflinger/buffer_queue_core.h
+++ b/src/core/hle/service/nvflinger/buffer_queue_core.h
@@ -38,7 +38,7 @@ public:
private:
void SignalDequeueCondition();
- bool WaitForDequeueCondition();
+ bool WaitForDequeueCondition(std::unique_lock<std::mutex>& lk);
s32 GetMinUndequeuedBufferCountLocked(bool async) const;
s32 GetMinMaxBufferCountLocked(bool async) const;
@@ -60,7 +60,8 @@ private:
BufferQueueDefs::SlotsType slots{};
std::vector<BufferItem> queue;
s32 override_max_buffer_count{};
- mutable std::condition_variable_any dequeue_condition;
+ std::condition_variable dequeue_condition;
+ std::atomic<bool> dequeue_possible{};
const bool use_async_buffer{}; // This is always disabled on HOS
bool dequeue_buffer_cannot_block{};
PixelFormat default_buffer_format{PixelFormat::Rgba8888};
diff --git a/src/core/hle/service/nvflinger/buffer_queue_producer.cpp b/src/core/hle/service/nvflinger/buffer_queue_producer.cpp
index 41ba44b21..e601b5da1 100644
--- a/src/core/hle/service/nvflinger/buffer_queue_producer.cpp
+++ b/src/core/hle/service/nvflinger/buffer_queue_producer.cpp
@@ -121,8 +121,8 @@ Status BufferQueueProducer::SetBufferCount(s32 buffer_count) {
return Status::NoError;
}
-Status BufferQueueProducer::WaitForFreeSlotThenRelock(bool async, s32* found,
- Status* return_flags) const {
+Status BufferQueueProducer::WaitForFreeSlotThenRelock(bool async, s32* found, Status* return_flags,
+ std::unique_lock<std::mutex>& lk) const {
bool try_again = true;
while (try_again) {
@@ -214,7 +214,7 @@ Status BufferQueueProducer::WaitForFreeSlotThenRelock(bool async, s32* found,
return Status::WouldBlock;
}
- if (!core->WaitForDequeueCondition()) {
+ if (!core->WaitForDequeueCondition(lk)) {
// We are no longer running
return Status::NoError;
}
@@ -237,7 +237,7 @@ Status BufferQueueProducer::DequeueBuffer(s32* out_slot, Fence* out_fence, bool
Status return_flags = Status::NoError;
bool attached_by_consumer = false;
{
- std::scoped_lock lock{core->mutex};
+ std::unique_lock lock{core->mutex};
core->WaitWhileAllocatingLocked();
if (format == PixelFormat::NoFormat) {
@@ -248,7 +248,7 @@ Status BufferQueueProducer::DequeueBuffer(s32* out_slot, Fence* out_fence, bool
usage |= core->consumer_usage_bit;
s32 found{};
- Status status = WaitForFreeSlotThenRelock(async, &found, &return_flags);
+ Status status = WaitForFreeSlotThenRelock(async, &found, &return_flags, lock);
if (status != Status::NoError) {
return status;
}
@@ -400,13 +400,13 @@ Status BufferQueueProducer::AttachBuffer(s32* out_slot,
return Status::BadValue;
}
- std::scoped_lock lock{core->mutex};
+ std::unique_lock lock{core->mutex};
core->WaitWhileAllocatingLocked();
Status return_flags = Status::NoError;
s32 found{};
- const auto status = WaitForFreeSlotThenRelock(false, &found, &return_flags);
+ const auto status = WaitForFreeSlotThenRelock(false, &found, &return_flags, lock);
if (status != Status::NoError) {
return status;
}
diff --git a/src/core/hle/service/nvflinger/buffer_queue_producer.h b/src/core/hle/service/nvflinger/buffer_queue_producer.h
index 7526bf8ec..1d380480f 100644
--- a/src/core/hle/service/nvflinger/buffer_queue_producer.h
+++ b/src/core/hle/service/nvflinger/buffer_queue_producer.h
@@ -70,7 +70,8 @@ public:
private:
BufferQueueProducer(const BufferQueueProducer&) = delete;
- Status WaitForFreeSlotThenRelock(bool async, s32* found, Status* return_flags) const;
+ Status WaitForFreeSlotThenRelock(bool async, s32* found, Status* return_flags,
+ std::unique_lock<std::mutex>& lk) const;
Kernel::KEvent* buffer_wait_event{};
Service::KernelHelpers::ServiceContext& service_context;
diff --git a/src/core/hle/service/nvflinger/consumer_base.cpp b/src/core/hle/service/nvflinger/consumer_base.cpp
index 5b9995854..982531e2d 100644
--- a/src/core/hle/service/nvflinger/consumer_base.cpp
+++ b/src/core/hle/service/nvflinger/consumer_base.cpp
@@ -83,7 +83,7 @@ Status ConsumerBase::AcquireBufferLocked(BufferItem* item, std::chrono::nanoseco
}
Status ConsumerBase::AddReleaseFenceLocked(s32 slot,
- const std::shared_ptr<GraphicBuffer> graphic_buffer,
+ const std::shared_ptr<GraphicBuffer>& graphic_buffer,
const Fence& fence) {
LOG_DEBUG(Service_NVFlinger, "slot={}", slot);
@@ -100,7 +100,7 @@ Status ConsumerBase::AddReleaseFenceLocked(s32 slot,
}
Status ConsumerBase::ReleaseBufferLocked(s32 slot,
- const std::shared_ptr<GraphicBuffer> graphic_buffer) {
+ const std::shared_ptr<GraphicBuffer>& graphic_buffer) {
// If consumer no longer tracks this graphic_buffer (we received a new
// buffer on the same slot), the buffer producer is definitely no longer
// tracking it.
@@ -121,7 +121,7 @@ Status ConsumerBase::ReleaseBufferLocked(s32 slot,
}
bool ConsumerBase::StillTracking(s32 slot,
- const std::shared_ptr<GraphicBuffer> graphic_buffer) const {
+ const std::shared_ptr<GraphicBuffer>& graphic_buffer) const {
if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
return false;
}
diff --git a/src/core/hle/service/nvflinger/consumer_base.h b/src/core/hle/service/nvflinger/consumer_base.h
index 90ba07f45..9a8a5f6bb 100644
--- a/src/core/hle/service/nvflinger/consumer_base.h
+++ b/src/core/hle/service/nvflinger/consumer_base.h
@@ -27,18 +27,18 @@ public:
protected:
explicit ConsumerBase(std::unique_ptr<BufferQueueConsumer> consumer_);
- virtual ~ConsumerBase();
+ ~ConsumerBase() override;
- virtual void OnFrameAvailable(const BufferItem& item) override;
- virtual void OnFrameReplaced(const BufferItem& item) override;
- virtual void OnBuffersReleased() override;
- virtual void OnSidebandStreamChanged() override;
+ void OnFrameAvailable(const BufferItem& item) override;
+ void OnFrameReplaced(const BufferItem& item) override;
+ void OnBuffersReleased() override;
+ void OnSidebandStreamChanged() override;
void FreeBufferLocked(s32 slot_index);
Status AcquireBufferLocked(BufferItem* item, std::chrono::nanoseconds present_when);
- Status ReleaseBufferLocked(s32 slot, const std::shared_ptr<GraphicBuffer> graphic_buffer);
- bool StillTracking(s32 slot, const std::shared_ptr<GraphicBuffer> graphic_buffer) const;
- Status AddReleaseFenceLocked(s32 slot, const std::shared_ptr<GraphicBuffer> graphic_buffer,
+ Status ReleaseBufferLocked(s32 slot, const std::shared_ptr<GraphicBuffer>& graphic_buffer);
+ bool StillTracking(s32 slot, const std::shared_ptr<GraphicBuffer>& graphic_buffer) const;
+ Status AddReleaseFenceLocked(s32 slot, const std::shared_ptr<GraphicBuffer>& graphic_buffer,
const Fence& fence);
struct Slot final {
diff --git a/src/core/hle/service/nvflinger/nvflinger.cpp b/src/core/hle/service/nvflinger/nvflinger.cpp
index c3af12c90..d1cbadde4 100644
--- a/src/core/hle/service/nvflinger/nvflinger.cpp
+++ b/src/core/hle/service/nvflinger/nvflinger.cpp
@@ -307,8 +307,7 @@ void NVFlinger::Compose() {
swap_interval = buffer.swap_interval;
- auto fence = android::Fence::NoFence();
- layer.GetConsumer().ReleaseBuffer(buffer, fence);
+ layer.GetConsumer().ReleaseBuffer(buffer, android::Fence::NoFence());
}
}
diff --git a/src/core/hle/service/nvflinger/nvflinger.h b/src/core/hle/service/nvflinger/nvflinger.h
index 460bef976..9b22397db 100644
--- a/src/core/hle/service/nvflinger/nvflinger.h
+++ b/src/core/hle/service/nvflinger/nvflinger.h
@@ -11,6 +11,7 @@
#include <vector>
#include "common/common_types.h"
+#include "common/polyfill_thread.h"
#include "core/hle/result.h"
#include "core/hle/service/kernel_helpers.h"
diff --git a/src/core/hle/service/nvflinger/producer_listener.h b/src/core/hle/service/nvflinger/producer_listener.h
index 1c4d5db0e..6bf8aaf1e 100644
--- a/src/core/hle/service/nvflinger/producer_listener.h
+++ b/src/core/hle/service/nvflinger/producer_listener.h
@@ -10,6 +10,7 @@ namespace Service::android {
class IProducerListener {
public:
+ virtual ~IProducerListener() = default;
virtual void OnBufferReleased() = 0;
};
diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp
index 5ab41c0c4..0de67f1e1 100644
--- a/src/core/hle/service/service.cpp
+++ b/src/core/hle/service/service.cpp
@@ -228,6 +228,7 @@ Result ServiceFrameworkBase::HandleSyncRequest(Kernel::KServerSession& session,
}
UNIMPLEMENTED_MSG("command_type={}", ctx.GetCommandType());
+ break;
}
// If emulation was shutdown, we are closing service threads, do not write the response back to
diff --git a/src/core/hle/service/set/set.cpp b/src/core/hle/service/set/set.cpp
index f761c2da4..4f1a8d6b7 100644
--- a/src/core/hle/service/set/set.cpp
+++ b/src/core/hle/service/set/set.cpp
@@ -83,7 +83,7 @@ void PushResponseLanguageCode(Kernel::HLERequestContext& ctx, std::size_t num_la
}
void GetAvailableLanguageCodesImpl(Kernel::HLERequestContext& ctx, std::size_t max_entries) {
- const std::size_t requested_amount = ctx.GetWriteBufferSize() / sizeof(LanguageCode);
+ const std::size_t requested_amount = ctx.GetWriteBufferNumElements<LanguageCode>();
const std::size_t max_amount = std::min(requested_amount, max_entries);
const std::size_t copy_amount = std::min(available_language_codes.size(), max_amount);
const std::size_t copy_size = copy_amount * sizeof(LanguageCode);
diff --git a/src/core/hle/service/time/time_zone_manager.cpp b/src/core/hle/service/time/time_zone_manager.cpp
index 2aa675df9..f9ada7c93 100644
--- a/src/core/hle/service/time/time_zone_manager.cpp
+++ b/src/core/hle/service/time/time_zone_manager.cpp
@@ -280,6 +280,7 @@ static constexpr int TransitionTime(int year, Rule rule, int offset) {
}
default:
ASSERT(false);
+ break;
}
return value + rule.transition_time + offset;
}
diff --git a/src/core/internal_network/network_interface.cpp b/src/core/internal_network/network_interface.cpp
index 057fd3661..7b8e510a2 100644
--- a/src/core/internal_network/network_interface.cpp
+++ b/src/core/internal_network/network_interface.cpp
@@ -9,6 +9,7 @@
#include "common/bit_cast.h"
#include "common/common_types.h"
#include "common/logging/log.h"
+#include "common/polyfill_ranges.h"
#include "common/settings.h"
#include "common/string_util.h"
#include "core/internal_network/network_interface.h"
diff --git a/src/core/memory.cpp b/src/core/memory.cpp
index 3ca80c8ff..3141122f1 100644
--- a/src/core/memory.cpp
+++ b/src/core/memory.cpp
@@ -6,6 +6,7 @@
#include "common/assert.h"
#include "common/atomic_ops.h"
+#include "common/cache_management.h"
#include "common/common_types.h"
#include "common/logging/log.h"
#include "common/page_table.h"
@@ -329,6 +330,55 @@ struct Memory::Impl {
});
}
+ template <typename Callback>
+ Result PerformCacheOperation(const Kernel::KProcess& process, VAddr dest_addr, std::size_t size,
+ Callback&& cb) {
+ class InvalidMemoryException : public std::exception {};
+
+ try {
+ WalkBlock(
+ process, dest_addr, size,
+ [&](const std::size_t block_size, const VAddr current_vaddr) {
+ LOG_ERROR(HW_Memory, "Unmapped cache maintenance @ {:#018X}", current_vaddr);
+ throw InvalidMemoryException();
+ },
+ [&](const std::size_t block_size, u8* const host_ptr) { cb(block_size, host_ptr); },
+ [&](const VAddr current_vaddr, const std::size_t block_size, u8* const host_ptr) {
+ system.GPU().FlushRegion(current_vaddr, block_size);
+ cb(block_size, host_ptr);
+ },
+ [](const std::size_t block_size) {});
+ } catch (InvalidMemoryException&) {
+ return Kernel::ResultInvalidCurrentMemory;
+ }
+
+ return ResultSuccess;
+ }
+
+ Result InvalidateDataCache(const Kernel::KProcess& process, VAddr dest_addr, std::size_t size) {
+ auto perform = [&](const std::size_t block_size, u8* const host_ptr) {
+ // Do nothing; this operation (dc ivac) cannot be supported
+ // from EL0
+ };
+ return PerformCacheOperation(process, dest_addr, size, perform);
+ }
+
+ Result StoreDataCache(const Kernel::KProcess& process, VAddr dest_addr, std::size_t size) {
+ auto perform = [&](const std::size_t block_size, u8* const host_ptr) {
+ // dc cvac: Store to point of coherency
+ Common::DataCacheLineCleanByVAToPoC(host_ptr, block_size);
+ };
+ return PerformCacheOperation(process, dest_addr, size, perform);
+ }
+
+ Result FlushDataCache(const Kernel::KProcess& process, VAddr dest_addr, std::size_t size) {
+ auto perform = [&](const std::size_t block_size, u8* const host_ptr) {
+ // dc civac: Store to point of coherency, and invalidate from cache
+ Common::DataCacheLineCleanAndInvalidateByVAToPoC(host_ptr, block_size);
+ };
+ return PerformCacheOperation(process, dest_addr, size, perform);
+ }
+
void MarkRegionDebug(VAddr vaddr, u64 size, bool debug) {
if (vaddr == 0) {
return;
@@ -786,6 +836,21 @@ void Memory::ZeroBlock(const Kernel::KProcess& process, VAddr dest_addr, const s
impl->ZeroBlock(process, dest_addr, size);
}
+Result Memory::InvalidateDataCache(const Kernel::KProcess& process, VAddr dest_addr,
+ const std::size_t size) {
+ return impl->InvalidateDataCache(process, dest_addr, size);
+}
+
+Result Memory::StoreDataCache(const Kernel::KProcess& process, VAddr dest_addr,
+ const std::size_t size) {
+ return impl->StoreDataCache(process, dest_addr, size);
+}
+
+Result Memory::FlushDataCache(const Kernel::KProcess& process, VAddr dest_addr,
+ const std::size_t size) {
+ return impl->FlushDataCache(process, dest_addr, size);
+}
+
void Memory::RasterizerMarkRegionCached(VAddr vaddr, u64 size, bool cached) {
impl->RasterizerMarkRegionCached(vaddr, size, cached);
}
diff --git a/src/core/memory.h b/src/core/memory.h
index 81eac448b..31fe699d8 100644
--- a/src/core/memory.h
+++ b/src/core/memory.h
@@ -7,6 +7,7 @@
#include <memory>
#include <string>
#include "common/common_types.h"
+#include "core/hle/result.h"
namespace Common {
struct PageTable;
@@ -450,6 +451,39 @@ public:
void ZeroBlock(const Kernel::KProcess& process, VAddr dest_addr, std::size_t size);
/**
+ * Invalidates a range of bytes within the current process' address space at the specified
+ * virtual address.
+ *
+ * @param process The process that will have data invalidated within its address space.
+ * @param dest_addr The destination virtual address to invalidate the data from.
+ * @param size The size of the range to invalidate, in bytes.
+ *
+ */
+ Result InvalidateDataCache(const Kernel::KProcess& process, VAddr dest_addr, std::size_t size);
+
+ /**
+ * Stores a range of bytes within the current process' address space at the specified
+ * virtual address.
+ *
+ * @param process The process that will have data stored within its address space.
+ * @param dest_addr The destination virtual address to store the data from.
+ * @param size The size of the range to store, in bytes.
+ *
+ */
+ Result StoreDataCache(const Kernel::KProcess& process, VAddr dest_addr, std::size_t size);
+
+ /**
+ * Flushes a range of bytes within the current process' address space at the specified
+ * virtual address.
+ *
+ * @param process The process that will have data flushed within its address space.
+ * @param dest_addr The destination virtual address to flush the data from.
+ * @param size The size of the range to flush, in bytes.
+ *
+ */
+ Result FlushDataCache(const Kernel::KProcess& process, VAddr dest_addr, std::size_t size);
+
+ /**
* Marks each page within the specified address range as cached or uncached.
*
* @param vaddr The virtual address indicating the start of the address range.
diff --git a/src/core/memory/dmnt_cheat_vm.cpp b/src/core/memory/dmnt_cheat_vm.cpp
index de96fcb8e..31ffc4fbb 100644
--- a/src/core/memory/dmnt_cheat_vm.cpp
+++ b/src/core/memory/dmnt_cheat_vm.cpp
@@ -761,7 +761,7 @@ void DmntCheatVm::Execute(const CheatProcessMetadata& metadata) {
u64 src_address =
GetCheatProcessAddress(metadata, begin_cond->mem_type, begin_cond->rel_address);
u64 src_value = 0;
- switch (store_static->bit_width) {
+ switch (begin_cond->bit_width) {
case 1:
case 2:
case 4:
diff --git a/src/core/precompiled_headers.h b/src/core/precompiled_headers.h
new file mode 100644
index 000000000..30a31001d
--- /dev/null
+++ b/src/core/precompiled_headers.h
@@ -0,0 +1,11 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include <boost/container/flat_map.hpp> // used by service.h which is heavily included
+#include <boost/intrusive/rbtree.hpp> // used by k_auto_object.h which is heavily included
+
+#include "common/common_precompiled_headers.h"
+
+#include "core/hle/kernel/k_process.h"
diff --git a/src/core/telemetry_session.cpp b/src/core/telemetry_session.cpp
index abcf6eb11..8d5f2be2f 100644
--- a/src/core/telemetry_session.cpp
+++ b/src/core/telemetry_session.cpp
@@ -55,6 +55,8 @@ static const char* TranslateRenderer(Settings::RendererBackend backend) {
return "OpenGL";
case Settings::RendererBackend::Vulkan:
return "Vulkan";
+ case Settings::RendererBackend::Null:
+ return "Null";
}
return "Unknown";
}
diff --git a/src/dedicated_room/CMakeLists.txt b/src/dedicated_room/CMakeLists.txt
index 2d9731f19..5bbe1d4b5 100644
--- a/src/dedicated_room/CMakeLists.txt
+++ b/src/dedicated_room/CMakeLists.txt
@@ -4,6 +4,7 @@
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${PROJECT_SOURCE_DIR}/CMakeModules)
add_executable(yuzu-room
+ precompiled_headers.h
yuzu_room.cpp
yuzu_room.rc
)
@@ -25,3 +26,7 @@ target_link_libraries(yuzu-room PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads)
if(UNIX AND NOT APPLE)
install(TARGETS yuzu-room)
endif()
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(yuzu-room PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/dedicated_room/precompiled_headers.h b/src/dedicated_room/precompiled_headers.h
new file mode 100644
index 000000000..aabae730b
--- /dev/null
+++ b/src/dedicated_room/precompiled_headers.h
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
diff --git a/src/input_common/CMakeLists.txt b/src/input_common/CMakeLists.txt
index cc6f0ffc0..e41da2726 100644
--- a/src/input_common/CMakeLists.txt
+++ b/src/input_common/CMakeLists.txt
@@ -34,6 +34,7 @@ add_library(input_common STATIC
input_poller.h
main.cpp
main.h
+ precompiled_headers.h
)
if (MSVC)
@@ -55,7 +56,11 @@ if (ENABLE_SDL2)
drivers/sdl_driver.cpp
drivers/sdl_driver.h
)
- target_link_libraries(input_common PRIVATE SDL2)
+ if (YUZU_USE_EXTERNAL_SDL2)
+ target_link_libraries(input_common PRIVATE SDL2-static)
+ else()
+ target_link_libraries(input_common PRIVATE SDL2)
+ endif()
target_compile_definitions(input_common PRIVATE HAVE_SDL2)
endif()
@@ -63,3 +68,7 @@ target_link_libraries(input_common PRIVATE usb)
create_target_directory_groups(input_common)
target_link_libraries(input_common PUBLIC core PRIVATE common Boost::boost)
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(input_common PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/input_common/drivers/gc_adapter.h b/src/input_common/drivers/gc_adapter.h
index 7f81767f7..b5270fd0b 100644
--- a/src/input_common/drivers/gc_adapter.h
+++ b/src/input_common/drivers/gc_adapter.h
@@ -5,10 +5,10 @@
#include <array>
#include <memory>
-#include <stop_token>
#include <string>
#include <thread>
+#include "common/polyfill_thread.h"
#include "input_common/input_engine.h"
struct libusb_context;
diff --git a/src/input_common/drivers/mouse.cpp b/src/input_common/drivers/mouse.cpp
index 98c3157a8..faf9cbdc3 100644
--- a/src/input_common/drivers/mouse.cpp
+++ b/src/input_common/drivers/mouse.cpp
@@ -1,7 +1,6 @@
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
-#include <stop_token>
#include <thread>
#include <fmt/format.h>
diff --git a/src/input_common/drivers/mouse.h b/src/input_common/drivers/mouse.h
index 286ce1cf6..72073cc23 100644
--- a/src/input_common/drivers/mouse.h
+++ b/src/input_common/drivers/mouse.h
@@ -3,9 +3,9 @@
#pragma once
-#include <stop_token>
#include <thread>
+#include "common/polyfill_thread.h"
#include "common/vector_math.h"
#include "input_common/input_engine.h"
diff --git a/src/input_common/drivers/sdl_driver.cpp b/src/input_common/drivers/sdl_driver.cpp
index 45ce588f0..8de86b61e 100644
--- a/src/input_common/drivers/sdl_driver.cpp
+++ b/src/input_common/drivers/sdl_driver.cpp
@@ -361,6 +361,12 @@ void SDLDriver::CloseJoystick(SDL_Joystick* sdl_joystick) {
}
}
+void SDLDriver::PumpEvents() const {
+ if (initialized) {
+ SDL_PumpEvents();
+ }
+}
+
void SDLDriver::HandleGameControllerEvent(const SDL_Event& event) {
switch (event.type) {
case SDL_JOYBUTTONUP: {
@@ -451,14 +457,6 @@ SDLDriver::SDLDriver(std::string input_engine_) : InputEngine(std::move(input_en
initialized = true;
if (start_thread) {
- poll_thread = std::thread([this] {
- Common::SetCurrentThreadName("SDL_MainLoop");
- using namespace std::chrono_literals;
- while (initialized) {
- SDL_PumpEvents();
- std::this_thread::sleep_for(1ms);
- }
- });
vibration_thread = std::thread([this] {
Common::SetCurrentThreadName("SDL_Vibration");
using namespace std::chrono_literals;
@@ -481,7 +479,6 @@ SDLDriver::~SDLDriver() {
initialized = false;
if (start_thread) {
- poll_thread.join();
vibration_thread.join();
SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER);
}
diff --git a/src/input_common/drivers/sdl_driver.h b/src/input_common/drivers/sdl_driver.h
index d1b4471cf..366bcc496 100644
--- a/src/input_common/drivers/sdl_driver.h
+++ b/src/input_common/drivers/sdl_driver.h
@@ -36,6 +36,8 @@ public:
/// Unregisters SDL device factories and shut them down.
~SDLDriver() override;
+ void PumpEvents() const;
+
/// Handle SDL_Events for joysticks from SDL_PollEvent
void HandleGameControllerEvent(const SDL_Event& event);
@@ -128,7 +130,6 @@ private:
bool start_thread = false;
std::atomic<bool> initialized = false;
- std::thread poll_thread;
std::thread vibration_thread;
};
} // namespace InputCommon
diff --git a/src/input_common/drivers/tas_input.cpp b/src/input_common/drivers/tas_input.cpp
index 21c6ed405..f3ade90da 100644
--- a/src/input_common/drivers/tas_input.cpp
+++ b/src/input_common/drivers/tas_input.cpp
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-2.0-or-later
#include <cstring>
+#include <sstream>
#include <fmt/format.h>
#include "common/fs/file.h"
diff --git a/src/input_common/drivers/virtual_amiibo.cpp b/src/input_common/drivers/virtual_amiibo.cpp
index 0cd5129da..564a188e5 100644
--- a/src/input_common/drivers/virtual_amiibo.cpp
+++ b/src/input_common/drivers/virtual_amiibo.cpp
@@ -60,6 +60,8 @@ Common::Input::NfcState VirtualAmiibo::WriteNfcData(
return Common::Input::NfcState::WriteFailed;
}
+ amiibo_data = data;
+
return Common::Input::NfcState::Success;
}
@@ -91,6 +93,15 @@ VirtualAmiibo::Info VirtualAmiibo::LoadAmiibo(const std::string& filename) {
return Info::Success;
}
+VirtualAmiibo::Info VirtualAmiibo::ReloadAmiibo() {
+ if (state == State::AmiiboIsOpen) {
+ SetNfc(identifier, {Common::Input::NfcState::NewAmiibo, amiibo_data});
+ return Info::Success;
+ }
+
+ return LoadAmiibo(file_path);
+}
+
VirtualAmiibo::Info VirtualAmiibo::CloseAmiibo() {
state = polling_mode == Common::Input::PollingMode::NFC ? State::WaitingForAmiibo
: State::Initialized;
@@ -98,4 +109,8 @@ VirtualAmiibo::Info VirtualAmiibo::CloseAmiibo() {
return Info::Success;
}
+std::string VirtualAmiibo::GetLastFilePath() const {
+ return file_path;
+}
+
} // namespace InputCommon
diff --git a/src/input_common/drivers/virtual_amiibo.h b/src/input_common/drivers/virtual_amiibo.h
index 9eac07544..9baeb3997 100644
--- a/src/input_common/drivers/virtual_amiibo.h
+++ b/src/input_common/drivers/virtual_amiibo.h
@@ -47,8 +47,11 @@ public:
State GetCurrentState() const;
Info LoadAmiibo(const std::string& amiibo_file);
+ Info ReloadAmiibo();
Info CloseAmiibo();
+ std::string GetLastFilePath() const;
+
private:
static constexpr std::size_t amiibo_size = 0x21C;
static constexpr std::size_t amiibo_size_without_password = amiibo_size - 0x8;
diff --git a/src/input_common/helpers/stick_from_buttons.cpp b/src/input_common/helpers/stick_from_buttons.cpp
index 536d413a5..82aa6ac2f 100644
--- a/src/input_common/helpers/stick_from_buttons.cpp
+++ b/src/input_common/helpers/stick_from_buttons.cpp
@@ -294,6 +294,15 @@ public:
}
private:
+ static constexpr Common::Input::AnalogProperties properties{
+ .deadzone = 0.0f,
+ .range = 1.0f,
+ .threshold = 0.5f,
+ .offset = 0.0f,
+ .inverted = false,
+ .toggle = false,
+ };
+
Button up;
Button down;
Button left;
@@ -311,23 +320,17 @@ private:
float last_x_axis_value{};
float last_y_axis_value{};
Common::Input::ButtonStatus modifier_status{};
- const Common::Input::AnalogProperties properties{0.0f, 1.0f, 0.5f, 0.0f, false};
std::chrono::time_point<std::chrono::steady_clock> last_update;
};
std::unique_ptr<Common::Input::InputDevice> StickFromButton::Create(
const Common::ParamPackage& params) {
const std::string null_engine = Common::ParamPackage{{"engine", "null"}}.Serialize();
- auto up = Common::Input::CreateDeviceFromString<Common::Input::InputDevice>(
- params.Get("up", null_engine));
- auto down = Common::Input::CreateDeviceFromString<Common::Input::InputDevice>(
- params.Get("down", null_engine));
- auto left = Common::Input::CreateDeviceFromString<Common::Input::InputDevice>(
- params.Get("left", null_engine));
- auto right = Common::Input::CreateDeviceFromString<Common::Input::InputDevice>(
- params.Get("right", null_engine));
- auto modifier = Common::Input::CreateDeviceFromString<Common::Input::InputDevice>(
- params.Get("modifier", null_engine));
+ auto up = Common::Input::CreateInputDeviceFromString(params.Get("up", null_engine));
+ auto down = Common::Input::CreateInputDeviceFromString(params.Get("down", null_engine));
+ auto left = Common::Input::CreateInputDeviceFromString(params.Get("left", null_engine));
+ auto right = Common::Input::CreateInputDeviceFromString(params.Get("right", null_engine));
+ auto modifier = Common::Input::CreateInputDeviceFromString(params.Get("modifier", null_engine));
auto modifier_scale = params.Get("modifier_scale", 0.5f);
auto modifier_angle = params.Get("modifier_angle", 5.5f);
return std::make_unique<Stick>(std::move(up), std::move(down), std::move(left),
diff --git a/src/input_common/helpers/touch_from_buttons.cpp b/src/input_common/helpers/touch_from_buttons.cpp
index da4a3dca5..e064b13d9 100644
--- a/src/input_common/helpers/touch_from_buttons.cpp
+++ b/src/input_common/helpers/touch_from_buttons.cpp
@@ -10,8 +10,8 @@ namespace InputCommon {
class TouchFromButtonDevice final : public Common::Input::InputDevice {
public:
using Button = std::unique_ptr<Common::Input::InputDevice>;
- TouchFromButtonDevice(Button button_, int touch_id_, float x_, float y_)
- : button(std::move(button_)), touch_id(touch_id_), x(x_), y(y_) {
+ TouchFromButtonDevice(Button button_, float x_, float y_)
+ : button(std::move(button_)), x(x_), y(y_) {
last_button_value = false;
button->SetCallback({
.on_change =
@@ -34,7 +34,6 @@ public:
.pressed = button_status,
.x = {},
.y = {},
- .id = touch_id,
};
status.x.properties = properties;
status.y.properties = properties;
@@ -60,23 +59,28 @@ public:
}
private:
+ static constexpr Common::Input::AnalogProperties properties{
+ .deadzone = 0.0f,
+ .range = 1.0f,
+ .threshold = 0.5f,
+ .offset = 0.0f,
+ .inverted = false,
+ .toggle = false,
+ };
+
Button button;
bool last_button_value;
- const int touch_id;
const float x;
const float y;
- const Common::Input::AnalogProperties properties{0.0f, 1.0f, 0.5f, 0.0f, false};
};
std::unique_ptr<Common::Input::InputDevice> TouchFromButton::Create(
const Common::ParamPackage& params) {
const std::string null_engine = Common::ParamPackage{{"engine", "null"}}.Serialize();
- auto button = Common::Input::CreateDeviceFromString<Common::Input::InputDevice>(
- params.Get("button", null_engine));
- const auto touch_id = params.Get("touch_id", 0);
+ auto button = Common::Input::CreateInputDeviceFromString(params.Get("button", null_engine));
const float x = params.Get("x", 0.0f) / 1280.0f;
const float y = params.Get("y", 0.0f) / 720.0f;
- return std::make_unique<TouchFromButtonDevice>(std::move(button), touch_id, x, y);
+ return std::make_unique<TouchFromButtonDevice>(std::move(button), x, y);
}
} // namespace InputCommon
diff --git a/src/input_common/input_engine.h b/src/input_common/input_engine.h
index d4c264a8e..6cbcf5207 100644
--- a/src/input_common/input_engine.h
+++ b/src/input_common/input_engine.h
@@ -133,7 +133,7 @@ public:
return Common::Input::CameraError::NotSupported;
}
- // Request nfc data from a controller
+ // Returns success if nfc is supported
virtual Common::Input::NfcState SupportsNfc(
[[maybe_unused]] const PadIdentifier& identifier) const {
return Common::Input::NfcState::NotSupported;
diff --git a/src/input_common/input_poller.cpp b/src/input_common/input_poller.cpp
index 4ac182147..fb8be42e2 100644
--- a/src/input_common/input_poller.cpp
+++ b/src/input_common/input_poller.cpp
@@ -229,13 +229,12 @@ private:
class InputFromTouch final : public Common::Input::InputDevice {
public:
- explicit InputFromTouch(PadIdentifier identifier_, int touch_id_, int button_, bool toggle_,
- bool inverted_, int axis_x_, int axis_y_,
- Common::Input::AnalogProperties properties_x_,
+ explicit InputFromTouch(PadIdentifier identifier_, int button_, bool toggle_, bool inverted_,
+ int axis_x_, int axis_y_, Common::Input::AnalogProperties properties_x_,
Common::Input::AnalogProperties properties_y_,
InputEngine* input_engine_)
- : identifier(identifier_), touch_id(touch_id_), button(button_), toggle(toggle_),
- inverted(inverted_), axis_x(axis_x_), axis_y(axis_y_), properties_x(properties_x_),
+ : identifier(identifier_), button(button_), toggle(toggle_), inverted(inverted_),
+ axis_x(axis_x_), axis_y(axis_y_), properties_x(properties_x_),
properties_y(properties_y_), input_engine(input_engine_) {
UpdateCallback engine_callback{[this]() { OnChange(); }};
const InputIdentifier button_input_identifier{
@@ -271,8 +270,7 @@ public:
}
Common::Input::TouchStatus GetStatus() const {
- Common::Input::TouchStatus status;
- status.id = touch_id;
+ Common::Input::TouchStatus status{};
status.pressed = {
.value = input_engine->GetButton(identifier, button),
.inverted = inverted,
@@ -307,7 +305,6 @@ public:
private:
const PadIdentifier identifier;
- const int touch_id;
const int button;
const bool toggle;
const bool inverted;
@@ -919,7 +916,6 @@ std::unique_ptr<Common::Input::InputDevice> InputFactory::CreateTriggerDevice(
std::unique_ptr<Common::Input::InputDevice> InputFactory::CreateTouchDevice(
const Common::ParamPackage& params) {
- const auto touch_id = params.Get("touch_id", 0);
const auto deadzone = std::clamp(params.Get("deadzone", 0.0f), 0.0f, 1.0f);
const auto range = std::clamp(params.Get("range", 1.0f), 0.25f, 1.50f);
const auto threshold = std::clamp(params.Get("threshold", 0.5f), 0.0f, 1.0f);
@@ -954,8 +950,8 @@ std::unique_ptr<Common::Input::InputDevice> InputFactory::CreateTouchDevice(
input_engine->PreSetAxis(identifier, axis_x);
input_engine->PreSetAxis(identifier, axis_y);
input_engine->PreSetButton(identifier, button);
- return std::make_unique<InputFromTouch>(identifier, touch_id, button, toggle, inverted, axis_x,
- axis_y, properties_x, properties_y, input_engine.get());
+ return std::make_unique<InputFromTouch>(identifier, button, toggle, inverted, axis_x, axis_y,
+ properties_x, properties_y, input_engine.get());
}
std::unique_ptr<Common::Input::InputDevice> InputFactory::CreateBatteryDevice(
diff --git a/src/input_common/main.cpp b/src/input_common/main.cpp
index b2064ef95..942a13535 100644
--- a/src/input_common/main.cpp
+++ b/src/input_common/main.cpp
@@ -33,119 +33,113 @@ struct InputSubsystem::Impl {
keyboard->SetMappingCallback(mapping_callback);
keyboard_factory = std::make_shared<InputFactory>(keyboard);
keyboard_output_factory = std::make_shared<OutputFactory>(keyboard);
- Common::Input::RegisterFactory<Common::Input::InputDevice>(keyboard->GetEngineName(),
- keyboard_factory);
- Common::Input::RegisterFactory<Common::Input::OutputDevice>(keyboard->GetEngineName(),
- keyboard_output_factory);
+ Common::Input::RegisterInputFactory(keyboard->GetEngineName(), keyboard_factory);
+ Common::Input::RegisterOutputFactory(keyboard->GetEngineName(), keyboard_output_factory);
mouse = std::make_shared<Mouse>("mouse");
mouse->SetMappingCallback(mapping_callback);
mouse_factory = std::make_shared<InputFactory>(mouse);
mouse_output_factory = std::make_shared<OutputFactory>(mouse);
- Common::Input::RegisterFactory<Common::Input::InputDevice>(mouse->GetEngineName(),
- mouse_factory);
- Common::Input::RegisterFactory<Common::Input::OutputDevice>(mouse->GetEngineName(),
- mouse_output_factory);
+ Common::Input::RegisterInputFactory(mouse->GetEngineName(), mouse_factory);
+ Common::Input::RegisterOutputFactory(mouse->GetEngineName(), mouse_output_factory);
touch_screen = std::make_shared<TouchScreen>("touch");
touch_screen_factory = std::make_shared<InputFactory>(touch_screen);
- Common::Input::RegisterFactory<Common::Input::InputDevice>(touch_screen->GetEngineName(),
- touch_screen_factory);
+ Common::Input::RegisterInputFactory(touch_screen->GetEngineName(), touch_screen_factory);
gcadapter = std::make_shared<GCAdapter>("gcpad");
gcadapter->SetMappingCallback(mapping_callback);
gcadapter_input_factory = std::make_shared<InputFactory>(gcadapter);
gcadapter_output_factory = std::make_shared<OutputFactory>(gcadapter);
- Common::Input::RegisterFactory<Common::Input::InputDevice>(gcadapter->GetEngineName(),
- gcadapter_input_factory);
- Common::Input::RegisterFactory<Common::Input::OutputDevice>(gcadapter->GetEngineName(),
- gcadapter_output_factory);
+ Common::Input::RegisterInputFactory(gcadapter->GetEngineName(), gcadapter_input_factory);
+ Common::Input::RegisterOutputFactory(gcadapter->GetEngineName(), gcadapter_output_factory);
udp_client = std::make_shared<CemuhookUDP::UDPClient>("cemuhookudp");
udp_client->SetMappingCallback(mapping_callback);
udp_client_input_factory = std::make_shared<InputFactory>(udp_client);
udp_client_output_factory = std::make_shared<OutputFactory>(udp_client);
- Common::Input::RegisterFactory<Common::Input::InputDevice>(udp_client->GetEngineName(),
- udp_client_input_factory);
- Common::Input::RegisterFactory<Common::Input::OutputDevice>(udp_client->GetEngineName(),
- udp_client_output_factory);
+ Common::Input::RegisterInputFactory(udp_client->GetEngineName(), udp_client_input_factory);
+ Common::Input::RegisterOutputFactory(udp_client->GetEngineName(),
+ udp_client_output_factory);
tas_input = std::make_shared<TasInput::Tas>("tas");
tas_input->SetMappingCallback(mapping_callback);
tas_input_factory = std::make_shared<InputFactory>(tas_input);
tas_output_factory = std::make_shared<OutputFactory>(tas_input);
- Common::Input::RegisterFactory<Common::Input::InputDevice>(tas_input->GetEngineName(),
- tas_input_factory);
- Common::Input::RegisterFactory<Common::Input::OutputDevice>(tas_input->GetEngineName(),
- tas_output_factory);
+ Common::Input::RegisterInputFactory(tas_input->GetEngineName(), tas_input_factory);
+ Common::Input::RegisterOutputFactory(tas_input->GetEngineName(), tas_output_factory);
camera = std::make_shared<Camera>("camera");
camera->SetMappingCallback(mapping_callback);
camera_input_factory = std::make_shared<InputFactory>(camera);
camera_output_factory = std::make_shared<OutputFactory>(camera);
- Common::Input::RegisterFactory<Common::Input::InputDevice>(camera->GetEngineName(),
- camera_input_factory);
- Common::Input::RegisterFactory<Common::Input::OutputDevice>(camera->GetEngineName(),
- camera_output_factory);
+ Common::Input::RegisterInputFactory(camera->GetEngineName(), camera_input_factory);
+ Common::Input::RegisterOutputFactory(camera->GetEngineName(), camera_output_factory);
virtual_amiibo = std::make_shared<VirtualAmiibo>("virtual_amiibo");
virtual_amiibo->SetMappingCallback(mapping_callback);
virtual_amiibo_input_factory = std::make_shared<InputFactory>(virtual_amiibo);
virtual_amiibo_output_factory = std::make_shared<OutputFactory>(virtual_amiibo);
- Common::Input::RegisterFactory<Common::Input::InputDevice>(virtual_amiibo->GetEngineName(),
- virtual_amiibo_input_factory);
- Common::Input::RegisterFactory<Common::Input::OutputDevice>(virtual_amiibo->GetEngineName(),
- virtual_amiibo_output_factory);
+ Common::Input::RegisterInputFactory(virtual_amiibo->GetEngineName(),
+ virtual_amiibo_input_factory);
+ Common::Input::RegisterOutputFactory(virtual_amiibo->GetEngineName(),
+ virtual_amiibo_output_factory);
#ifdef HAVE_SDL2
sdl = std::make_shared<SDLDriver>("sdl");
sdl->SetMappingCallback(mapping_callback);
sdl_input_factory = std::make_shared<InputFactory>(sdl);
sdl_output_factory = std::make_shared<OutputFactory>(sdl);
- Common::Input::RegisterFactory<Common::Input::InputDevice>(sdl->GetEngineName(),
- sdl_input_factory);
- Common::Input::RegisterFactory<Common::Input::OutputDevice>(sdl->GetEngineName(),
- sdl_output_factory);
+ Common::Input::RegisterInputFactory(sdl->GetEngineName(), sdl_input_factory);
+ Common::Input::RegisterOutputFactory(sdl->GetEngineName(), sdl_output_factory);
#endif
- Common::Input::RegisterFactory<Common::Input::InputDevice>(
- "touch_from_button", std::make_shared<TouchFromButton>());
- Common::Input::RegisterFactory<Common::Input::InputDevice>(
- "analog_from_button", std::make_shared<StickFromButton>());
+ Common::Input::RegisterInputFactory("touch_from_button",
+ std::make_shared<TouchFromButton>());
+ Common::Input::RegisterInputFactory("analog_from_button",
+ std::make_shared<StickFromButton>());
}
void Shutdown() {
- Common::Input::UnregisterFactory<Common::Input::InputDevice>(keyboard->GetEngineName());
- Common::Input::UnregisterFactory<Common::Input::OutputDevice>(keyboard->GetEngineName());
+ Common::Input::UnregisterInputFactory(keyboard->GetEngineName());
+ Common::Input::UnregisterOutputFactory(keyboard->GetEngineName());
keyboard.reset();
- Common::Input::UnregisterFactory<Common::Input::InputDevice>(mouse->GetEngineName());
- Common::Input::UnregisterFactory<Common::Input::OutputDevice>(mouse->GetEngineName());
+ Common::Input::UnregisterInputFactory(mouse->GetEngineName());
+ Common::Input::UnregisterOutputFactory(mouse->GetEngineName());
mouse.reset();
- Common::Input::UnregisterFactory<Common::Input::InputDevice>(touch_screen->GetEngineName());
+ Common::Input::UnregisterInputFactory(touch_screen->GetEngineName());
touch_screen.reset();
- Common::Input::UnregisterFactory<Common::Input::InputDevice>(gcadapter->GetEngineName());
- Common::Input::UnregisterFactory<Common::Input::OutputDevice>(gcadapter->GetEngineName());
+ Common::Input::UnregisterInputFactory(gcadapter->GetEngineName());
+ Common::Input::UnregisterOutputFactory(gcadapter->GetEngineName());
gcadapter.reset();
- Common::Input::UnregisterFactory<Common::Input::InputDevice>(udp_client->GetEngineName());
- Common::Input::UnregisterFactory<Common::Input::OutputDevice>(udp_client->GetEngineName());
+ Common::Input::UnregisterInputFactory(udp_client->GetEngineName());
+ Common::Input::UnregisterOutputFactory(udp_client->GetEngineName());
udp_client.reset();
- Common::Input::UnregisterFactory<Common::Input::InputDevice>(tas_input->GetEngineName());
- Common::Input::UnregisterFactory<Common::Input::OutputDevice>(tas_input->GetEngineName());
+ Common::Input::UnregisterInputFactory(tas_input->GetEngineName());
+ Common::Input::UnregisterOutputFactory(tas_input->GetEngineName());
tas_input.reset();
+ Common::Input::UnregisterInputFactory(camera->GetEngineName());
+ Common::Input::UnregisterOutputFactory(camera->GetEngineName());
+ camera.reset();
+
+ Common::Input::UnregisterInputFactory(virtual_amiibo->GetEngineName());
+ Common::Input::UnregisterOutputFactory(virtual_amiibo->GetEngineName());
+ virtual_amiibo.reset();
+
#ifdef HAVE_SDL2
- Common::Input::UnregisterFactory<Common::Input::InputDevice>(sdl->GetEngineName());
- Common::Input::UnregisterFactory<Common::Input::OutputDevice>(sdl->GetEngineName());
+ Common::Input::UnregisterInputFactory(sdl->GetEngineName());
+ Common::Input::UnregisterOutputFactory(sdl->GetEngineName());
sdl.reset();
#endif
- Common::Input::UnregisterFactory<Common::Input::InputDevice>("touch_from_button");
- Common::Input::UnregisterFactory<Common::Input::InputDevice>("analog_from_button");
+ Common::Input::UnregisterInputFactory("touch_from_button");
+ Common::Input::UnregisterInputFactory("analog_from_button");
}
[[nodiscard]] std::vector<Common::ParamPackage> GetInputDevices() const {
@@ -324,6 +318,12 @@ struct InputSubsystem::Impl {
#endif
}
+ void PumpEvents() const {
+#ifdef HAVE_SDL2
+ sdl->PumpEvents();
+#endif
+ }
+
void RegisterInput(const MappingData& data) {
mapping_factory->RegisterInput(data);
}
@@ -472,6 +472,10 @@ void InputSubsystem::StopMapping() const {
impl->mapping_factory->StopMapping();
}
+void InputSubsystem::PumpEvents() const {
+ impl->PumpEvents();
+}
+
std::string GenerateKeyboardParam(int key_code) {
Common::ParamPackage param;
param.Set("engine", "keyboard");
diff --git a/src/input_common/main.h b/src/input_common/main.h
index ced252383..6218c37f6 100644
--- a/src/input_common/main.h
+++ b/src/input_common/main.h
@@ -147,6 +147,9 @@ public:
/// Stop polling from all backends.
void StopMapping() const;
+ /// Signals SDL driver for new input events
+ void PumpEvents() const;
+
private:
struct Impl;
std::unique_ptr<Impl> impl;
diff --git a/src/input_common/precompiled_headers.h b/src/input_common/precompiled_headers.h
new file mode 100644
index 000000000..aabae730b
--- /dev/null
+++ b/src/input_common/precompiled_headers.h
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
diff --git a/src/network/CMakeLists.txt b/src/network/CMakeLists.txt
index 6f8ca4b90..c85c308de 100644
--- a/src/network/CMakeLists.txt
+++ b/src/network/CMakeLists.txt
@@ -8,6 +8,7 @@ add_library(network STATIC
network.h
packet.cpp
packet.h
+ precompiled_headers.h
room.cpp
room.h
room_member.cpp
@@ -23,3 +24,7 @@ if (ENABLE_WEB_SERVICE)
target_compile_definitions(network PRIVATE -DENABLE_WEB_SERVICE)
target_link_libraries(network PRIVATE web_service)
endif()
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(network PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/network/precompiled_headers.h b/src/network/precompiled_headers.h
new file mode 100644
index 000000000..aabae730b
--- /dev/null
+++ b/src/network/precompiled_headers.h
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
diff --git a/src/shader_recompiler/CMakeLists.txt b/src/shader_recompiler/CMakeLists.txt
index 545d69c7e..525b2363c 100644
--- a/src/shader_recompiler/CMakeLists.txt
+++ b/src/shader_recompiler/CMakeLists.txt
@@ -221,6 +221,7 @@ add_library(shader_recompiler STATIC
ir_opt/dual_vertex_pass.cpp
ir_opt/global_memory_to_storage_buffer_pass.cpp
ir_opt/identity_removal_pass.cpp
+ ir_opt/layer_pass.cpp
ir_opt/lower_fp16_to_fp32.cpp
ir_opt/lower_int64_to_int32.cpp
ir_opt/passes.h
@@ -230,6 +231,7 @@ add_library(shader_recompiler STATIC
ir_opt/texture_pass.cpp
ir_opt/verification_pass.cpp
object_pool.h
+ precompiled_headers.h
profile.h
program_header.h
runtime_info.h
@@ -254,7 +256,12 @@ else()
# Bracket depth determines maximum size of a fold expression in Clang since 9c9974c3ccb6.
# And this in turns limits the size of a std::array.
$<$<CXX_COMPILER_ID:Clang>:-fbracket-depth=1024>
+ $<$<CXX_COMPILER_ID:AppleClang>:-fbracket-depth=1024>
)
endif()
create_target_directory_groups(shader_recompiler)
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(shader_recompiler PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/shader_recompiler/backend/glasm/emit_glasm.cpp b/src/shader_recompiler/backend/glasm/emit_glasm.cpp
index 3b0176bf6..0cb1e193e 100644
--- a/src/shader_recompiler/backend/glasm/emit_glasm.cpp
+++ b/src/shader_recompiler/backend/glasm/emit_glasm.cpp
@@ -320,6 +320,7 @@ void SetupOptions(const IR::Program& program, const Profile& profile,
}
if (stage == Stage::Fragment) {
header += "OPTION ARB_draw_buffers;";
+ header += "OPTION ARB_fragment_layer_viewport;";
}
}
diff --git a/src/shader_recompiler/backend/glasm/emit_glasm_context_get_set.cpp b/src/shader_recompiler/backend/glasm/emit_glasm_context_get_set.cpp
index d6562c842..f0bd84ab2 100644
--- a/src/shader_recompiler/backend/glasm/emit_glasm_context_get_set.cpp
+++ b/src/shader_recompiler/backend/glasm/emit_glasm_context_get_set.cpp
@@ -104,6 +104,9 @@ void EmitGetAttribute(EmitContext& ctx, IR::Inst& inst, IR::Attribute attr, Scal
case IR::Attribute::PrimitiveId:
ctx.Add("MOV.F {}.x,primitive.id;", inst);
break;
+ case IR::Attribute::Layer:
+ ctx.Add("MOV.F {}.x,fragment.layer;", inst);
+ break;
case IR::Attribute::PositionX:
case IR::Attribute::PositionY:
case IR::Attribute::PositionZ:
diff --git a/src/shader_recompiler/backend/glsl/emit_glsl_context_get_set.cpp b/src/shader_recompiler/backend/glsl/emit_glsl_context_get_set.cpp
index c1671c37b..39579cf5d 100644
--- a/src/shader_recompiler/backend/glsl/emit_glsl_context_get_set.cpp
+++ b/src/shader_recompiler/backend/glsl/emit_glsl_context_get_set.cpp
@@ -205,6 +205,9 @@ void EmitGetAttribute(EmitContext& ctx, IR::Inst& inst, IR::Attribute attr,
case IR::Attribute::PrimitiveId:
ctx.AddF32("{}=itof(gl_PrimitiveID);", inst);
break;
+ case IR::Attribute::Layer:
+ ctx.AddF32("{}=itof(gl_Layer);", inst);
+ break;
case IR::Attribute::PositionX:
case IR::Attribute::PositionY:
case IR::Attribute::PositionZ:
diff --git a/src/shader_recompiler/backend/spirv/emit_spirv.cpp b/src/shader_recompiler/backend/spirv/emit_spirv.cpp
index 265ac9c85..0f86a8004 100644
--- a/src/shader_recompiler/backend/spirv/emit_spirv.cpp
+++ b/src/shader_recompiler/backend/spirv/emit_spirv.cpp
@@ -402,8 +402,10 @@ void SetupCapabilities(const Profile& profile, const Info& info, EmitContext& ct
ctx.AddCapability(spv::Capability::SparseResidency);
}
if (info.uses_demote_to_helper_invocation && profile.support_demote_to_helper_invocation) {
- ctx.AddExtension("SPV_EXT_demote_to_helper_invocation");
- ctx.AddCapability(spv::Capability::DemoteToHelperInvocationEXT);
+ if (profile.supported_spirv < 0x00010600) {
+ ctx.AddExtension("SPV_EXT_demote_to_helper_invocation");
+ }
+ ctx.AddCapability(spv::Capability::DemoteToHelperInvocation);
}
if (info.stores[IR::Attribute::ViewportIndex]) {
ctx.AddCapability(spv::Capability::MultiViewport);
@@ -426,12 +428,11 @@ void SetupCapabilities(const Profile& profile, const Info& info, EmitContext& ct
if ((info.uses_subgroup_vote || info.uses_subgroup_invocation_id ||
info.uses_subgroup_shuffles) &&
profile.support_vote) {
- ctx.AddExtension("SPV_KHR_shader_ballot");
- ctx.AddCapability(spv::Capability::SubgroupBallotKHR);
+ ctx.AddCapability(spv::Capability::GroupNonUniformBallot);
+ ctx.AddCapability(spv::Capability::GroupNonUniformShuffle);
if (!profile.warp_size_potentially_larger_than_guest) {
// vote ops are only used when not taking the long path
- ctx.AddExtension("SPV_KHR_subgroup_vote");
- ctx.AddCapability(spv::Capability::SubgroupVoteKHR);
+ ctx.AddCapability(spv::Capability::GroupNonUniformVote);
}
}
if (info.uses_int64_bit_atomics && profile.support_int64_atomics) {
diff --git a/src/shader_recompiler/backend/spirv/emit_spirv_context_get_set.cpp b/src/shader_recompiler/backend/spirv/emit_spirv_context_get_set.cpp
index 5b3b5d1f3..01f6ec9b5 100644
--- a/src/shader_recompiler/backend/spirv/emit_spirv_context_get_set.cpp
+++ b/src/shader_recompiler/backend/spirv/emit_spirv_context_get_set.cpp
@@ -315,6 +315,8 @@ Id EmitGetAttribute(EmitContext& ctx, IR::Attribute attr, Id vertex) {
switch (attr) {
case IR::Attribute::PrimitiveId:
return ctx.OpBitcast(ctx.F32[1], ctx.OpLoad(ctx.U32[1], ctx.primitive_id));
+ case IR::Attribute::Layer:
+ return ctx.OpBitcast(ctx.F32[1], ctx.OpLoad(ctx.U32[1], ctx.layer));
case IR::Attribute::PositionX:
case IR::Attribute::PositionY:
case IR::Attribute::PositionZ:
diff --git a/src/shader_recompiler/backend/spirv/emit_spirv_control_flow.cpp b/src/shader_recompiler/backend/spirv/emit_spirv_control_flow.cpp
index 7ad0b08ac..fb2c792c1 100644
--- a/src/shader_recompiler/backend/spirv/emit_spirv_control_flow.cpp
+++ b/src/shader_recompiler/backend/spirv/emit_spirv_control_flow.cpp
@@ -12,7 +12,7 @@ void EmitJoin(EmitContext&) {
void EmitDemoteToHelperInvocation(EmitContext& ctx) {
if (ctx.profile.support_demote_to_helper_invocation) {
- ctx.OpDemoteToHelperInvocationEXT();
+ ctx.OpDemoteToHelperInvocation();
} else {
const Id kill_label{ctx.OpLabel()};
const Id impossible_label{ctx.OpLabel()};
diff --git a/src/shader_recompiler/backend/spirv/emit_spirv_warp.cpp b/src/shader_recompiler/backend/spirv/emit_spirv_warp.cpp
index 7cbbbfaa6..2c90f2368 100644
--- a/src/shader_recompiler/backend/spirv/emit_spirv_warp.cpp
+++ b/src/shader_recompiler/backend/spirv/emit_spirv_warp.cpp
@@ -6,6 +6,10 @@
namespace Shader::Backend::SPIRV {
namespace {
+Id SubgroupScope(EmitContext& ctx) {
+ return ctx.Const(static_cast<u32>(spv::Scope::Subgroup));
+}
+
Id GetThreadId(EmitContext& ctx) {
return ctx.OpLoad(ctx.U32[1], ctx.subgroup_local_invocation_id);
}
@@ -49,8 +53,9 @@ Id GetMaxThreadId(EmitContext& ctx, Id thread_id, Id clamp, Id segmentation_mask
}
Id SelectValue(EmitContext& ctx, Id in_range, Id value, Id src_thread_id) {
- return ctx.OpSelect(ctx.U32[1], in_range,
- ctx.OpSubgroupReadInvocationKHR(ctx.U32[1], value, src_thread_id), value);
+ return ctx.OpSelect(
+ ctx.U32[1], in_range,
+ ctx.OpGroupNonUniformShuffle(ctx.U32[1], SubgroupScope(ctx), value, src_thread_id), value);
}
Id GetUpperClamp(EmitContext& ctx, Id invocation_id, Id clamp) {
@@ -71,40 +76,46 @@ Id EmitLaneId(EmitContext& ctx) {
Id EmitVoteAll(EmitContext& ctx, Id pred) {
if (!ctx.profile.warp_size_potentially_larger_than_guest) {
- return ctx.OpSubgroupAllKHR(ctx.U1, pred);
+ return ctx.OpGroupNonUniformAll(ctx.U1, SubgroupScope(ctx), pred);
}
- const Id mask_ballot{ctx.OpSubgroupBallotKHR(ctx.U32[4], ctx.true_value)};
+ const Id mask_ballot{
+ ctx.OpGroupNonUniformBallot(ctx.U32[4], SubgroupScope(ctx), ctx.true_value)};
const Id active_mask{WarpExtract(ctx, mask_ballot)};
- const Id ballot{WarpExtract(ctx, ctx.OpSubgroupBallotKHR(ctx.U32[4], pred))};
+ const Id ballot{
+ WarpExtract(ctx, ctx.OpGroupNonUniformBallot(ctx.U32[4], SubgroupScope(ctx), pred))};
const Id lhs{ctx.OpBitwiseAnd(ctx.U32[1], ballot, active_mask)};
return ctx.OpIEqual(ctx.U1, lhs, active_mask);
}
Id EmitVoteAny(EmitContext& ctx, Id pred) {
if (!ctx.profile.warp_size_potentially_larger_than_guest) {
- return ctx.OpSubgroupAnyKHR(ctx.U1, pred);
+ return ctx.OpGroupNonUniformAny(ctx.U1, SubgroupScope(ctx), pred);
}
- const Id mask_ballot{ctx.OpSubgroupBallotKHR(ctx.U32[4], ctx.true_value)};
+ const Id mask_ballot{
+ ctx.OpGroupNonUniformBallot(ctx.U32[4], SubgroupScope(ctx), ctx.true_value)};
const Id active_mask{WarpExtract(ctx, mask_ballot)};
- const Id ballot{WarpExtract(ctx, ctx.OpSubgroupBallotKHR(ctx.U32[4], pred))};
+ const Id ballot{
+ WarpExtract(ctx, ctx.OpGroupNonUniformBallot(ctx.U32[4], SubgroupScope(ctx), pred))};
const Id lhs{ctx.OpBitwiseAnd(ctx.U32[1], ballot, active_mask)};
return ctx.OpINotEqual(ctx.U1, lhs, ctx.u32_zero_value);
}
Id EmitVoteEqual(EmitContext& ctx, Id pred) {
if (!ctx.profile.warp_size_potentially_larger_than_guest) {
- return ctx.OpSubgroupAllEqualKHR(ctx.U1, pred);
+ return ctx.OpGroupNonUniformAllEqual(ctx.U1, SubgroupScope(ctx), pred);
}
- const Id mask_ballot{ctx.OpSubgroupBallotKHR(ctx.U32[4], ctx.true_value)};
+ const Id mask_ballot{
+ ctx.OpGroupNonUniformBallot(ctx.U32[4], SubgroupScope(ctx), ctx.true_value)};
const Id active_mask{WarpExtract(ctx, mask_ballot)};
- const Id ballot{WarpExtract(ctx, ctx.OpSubgroupBallotKHR(ctx.U32[4], pred))};
+ const Id ballot{
+ WarpExtract(ctx, ctx.OpGroupNonUniformBallot(ctx.U32[4], SubgroupScope(ctx), pred))};
const Id lhs{ctx.OpBitwiseXor(ctx.U32[1], ballot, active_mask)};
return ctx.OpLogicalOr(ctx.U1, ctx.OpIEqual(ctx.U1, lhs, ctx.u32_zero_value),
ctx.OpIEqual(ctx.U1, lhs, active_mask));
}
Id EmitSubgroupBallot(EmitContext& ctx, Id pred) {
- const Id ballot{ctx.OpSubgroupBallotKHR(ctx.U32[4], pred)};
+ const Id ballot{ctx.OpGroupNonUniformBallot(ctx.U32[4], SubgroupScope(ctx), pred)};
if (!ctx.profile.warp_size_potentially_larger_than_guest) {
return ctx.OpCompositeExtract(ctx.U32[1], ballot, 0U);
}
diff --git a/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp b/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp
index 0bfc2dd89..8e3e40cd5 100644
--- a/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp
+++ b/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp
@@ -1359,6 +1359,11 @@ void EmitContext::DefineInputs(const IR::Program& program) {
if (loads[IR::Attribute::PrimitiveId]) {
primitive_id = DefineInput(*this, U32[1], false, spv::BuiltIn::PrimitiveId);
}
+ if (loads[IR::Attribute::Layer]) {
+ AddCapability(spv::Capability::Geometry);
+ layer = DefineInput(*this, U32[1], false, spv::BuiltIn::Layer);
+ Decorate(layer, spv::Decoration::Flat);
+ }
if (loads.AnyComponent(IR::Attribute::PositionX)) {
const bool is_fragment{stage != Stage::Fragment};
const spv::BuiltIn built_in{is_fragment ? spv::BuiltIn::Position : spv::BuiltIn::FragCoord};
diff --git a/src/shader_recompiler/frontend/ir/opcodes.h b/src/shader_recompiler/frontend/ir/opcodes.h
index e70d7745c..d155afd0f 100644
--- a/src/shader_recompiler/frontend/ir/opcodes.h
+++ b/src/shader_recompiler/frontend/ir/opcodes.h
@@ -8,6 +8,7 @@
#include <fmt/format.h>
+#include "common/polyfill_ranges.h"
#include "shader_recompiler/frontend/ir/type.h"
namespace Shader::IR {
diff --git a/src/shader_recompiler/frontend/ir/value.h b/src/shader_recompiler/frontend/ir/value.h
index e8bbb93a5..8b34356fd 100644
--- a/src/shader_recompiler/frontend/ir/value.h
+++ b/src/shader_recompiler/frontend/ir/value.h
@@ -23,7 +23,6 @@
#include "shader_recompiler/frontend/ir/pred.h"
#include "shader_recompiler/frontend/ir/reg.h"
#include "shader_recompiler/frontend/ir/type.h"
-#include "shader_recompiler/frontend/ir/value.h"
namespace Shader::IR {
diff --git a/src/shader_recompiler/frontend/maxwell/control_flow.cpp b/src/shader_recompiler/frontend/maxwell/control_flow.cpp
index 6939692cd..dce414cb4 100644
--- a/src/shader_recompiler/frontend/maxwell/control_flow.cpp
+++ b/src/shader_recompiler/frontend/maxwell/control_flow.cpp
@@ -9,6 +9,7 @@
#include <fmt/format.h>
+#include "common/polyfill_ranges.h"
#include "shader_recompiler/exception.h"
#include "shader_recompiler/frontend/maxwell/control_flow.h"
#include "shader_recompiler/frontend/maxwell/decode.h"
diff --git a/src/shader_recompiler/frontend/maxwell/decode.cpp b/src/shader_recompiler/frontend/maxwell/decode.cpp
index 455c91470..774f65bc5 100644
--- a/src/shader_recompiler/frontend/maxwell/decode.cpp
+++ b/src/shader_recompiler/frontend/maxwell/decode.cpp
@@ -7,6 +7,7 @@
#include <memory>
#include "common/common_types.h"
+#include "common/polyfill_ranges.h"
#include "shader_recompiler/exception.h"
#include "shader_recompiler/frontend/maxwell/decode.h"
#include "shader_recompiler/frontend/maxwell/opcodes.h"
diff --git a/src/shader_recompiler/frontend/maxwell/structured_control_flow.cpp b/src/shader_recompiler/frontend/maxwell/structured_control_flow.cpp
index ce42475d4..80c90fe6a 100644
--- a/src/shader_recompiler/frontend/maxwell/structured_control_flow.cpp
+++ b/src/shader_recompiler/frontend/maxwell/structured_control_flow.cpp
@@ -12,6 +12,7 @@
#include <boost/intrusive/list.hpp>
+#include "common/polyfill_ranges.h"
#include "shader_recompiler/environment.h"
#include "shader_recompiler/frontend/ir/basic_block.h"
#include "shader_recompiler/frontend/ir/ir_emitter.h"
diff --git a/src/shader_recompiler/frontend/maxwell/translate/impl/floating_point_conversion_integer.cpp b/src/shader_recompiler/frontend/maxwell/translate/impl/floating_point_conversion_integer.cpp
index 4942878b9..85c18d942 100644
--- a/src/shader_recompiler/frontend/maxwell/translate/impl/floating_point_conversion_integer.cpp
+++ b/src/shader_recompiler/frontend/maxwell/translate/impl/floating_point_conversion_integer.cpp
@@ -176,12 +176,13 @@ void TranslateF2I(TranslatorVisitor& v, u64 insn, const IR::F16F32F64& src_a) {
(f2i.src_format == SrcFormat::F64) != (f2i.dest_format == DestFormat::I64);
if (special_nan_cases) {
if (f2i.dest_format == DestFormat::I32) {
+ constexpr u32 nan_value = 0x8000'0000U;
handled_special_case = true;
- result = IR::U32{v.ir.Select(v.ir.FPIsNan(op_a), v.ir.Imm32(0x8000'0000U), result)};
+ result = IR::U32{v.ir.Select(v.ir.FPIsNan(op_a), v.ir.Imm32(nan_value), result)};
} else if (f2i.dest_format == DestFormat::I64) {
+ constexpr u64 nan_value = 0x8000'0000'0000'0000ULL;
handled_special_case = true;
- result = IR::U64{
- v.ir.Select(v.ir.FPIsNan(op_a), v.ir.Imm64(0x8000'0000'0000'0000UL), result)};
+ result = IR::U64{v.ir.Select(v.ir.FPIsNan(op_a), v.ir.Imm64(nan_value), result)};
}
}
if (!handled_special_case && is_signed) {
diff --git a/src/shader_recompiler/frontend/maxwell/translate_program.cpp b/src/shader_recompiler/frontend/maxwell/translate_program.cpp
index 376aae0ea..3adbd2b16 100644
--- a/src/shader_recompiler/frontend/maxwell/translate_program.cpp
+++ b/src/shader_recompiler/frontend/maxwell/translate_program.cpp
@@ -9,6 +9,7 @@
#include "common/settings.h"
#include "shader_recompiler/exception.h"
#include "shader_recompiler/frontend/ir/basic_block.h"
+#include "shader_recompiler/frontend/ir/ir_emitter.h"
#include "shader_recompiler/frontend/ir/post_order.h"
#include "shader_recompiler/frontend/maxwell/structured_control_flow.h"
#include "shader_recompiler/frontend/maxwell/translate/translate.h"
@@ -233,6 +234,8 @@ IR::Program TranslateProgram(ObjectPool<IR::Inst>& inst_pool, ObjectPool<IR::Blo
Optimization::VerificationPass(program);
}
Optimization::CollectShaderInfoPass(env, program);
+ Optimization::LayerPass(program, host_info);
+
CollectInterpolationInfo(env, program);
AddNVNStorageBuffers(program);
return program;
@@ -331,4 +334,82 @@ void ConvertLegacyToGeneric(IR::Program& program, const Shader::RuntimeInfo& run
}
}
+IR::Program GenerateGeometryPassthrough(ObjectPool<IR::Inst>& inst_pool,
+ ObjectPool<IR::Block>& block_pool,
+ const HostTranslateInfo& host_info,
+ IR::Program& source_program,
+ Shader::OutputTopology output_topology) {
+ IR::Program program;
+ program.stage = Stage::Geometry;
+ program.output_topology = output_topology;
+ switch (output_topology) {
+ case OutputTopology::PointList:
+ program.output_vertices = 1;
+ break;
+ case OutputTopology::LineStrip:
+ program.output_vertices = 2;
+ break;
+ default:
+ program.output_vertices = 3;
+ break;
+ }
+
+ program.is_geometry_passthrough = false;
+ program.info.loads.mask = source_program.info.stores.mask;
+ program.info.stores.mask = source_program.info.stores.mask;
+ program.info.stores.Set(IR::Attribute::Layer, true);
+ program.info.stores.Set(source_program.info.emulated_layer, false);
+
+ IR::Block* current_block = block_pool.Create(inst_pool);
+ auto& node{program.syntax_list.emplace_back()};
+ node.type = IR::AbstractSyntaxNode::Type::Block;
+ node.data.block = current_block;
+
+ IR::IREmitter ir{*current_block};
+ for (u32 i = 0; i < program.output_vertices; i++) {
+ // Assign generics from input
+ for (u32 j = 0; j < 32; j++) {
+ if (!program.info.stores.Generic(j)) {
+ continue;
+ }
+
+ const IR::Attribute attr = IR::Attribute::Generic0X + (j * 4);
+ ir.SetAttribute(attr + 0, ir.GetAttribute(attr + 0, ir.Imm32(i)), ir.Imm32(0));
+ ir.SetAttribute(attr + 1, ir.GetAttribute(attr + 1, ir.Imm32(i)), ir.Imm32(0));
+ ir.SetAttribute(attr + 2, ir.GetAttribute(attr + 2, ir.Imm32(i)), ir.Imm32(0));
+ ir.SetAttribute(attr + 3, ir.GetAttribute(attr + 3, ir.Imm32(i)), ir.Imm32(0));
+ }
+
+ // Assign position from input
+ const IR::Attribute attr = IR::Attribute::PositionX;
+ ir.SetAttribute(attr + 0, ir.GetAttribute(attr + 0, ir.Imm32(i)), ir.Imm32(0));
+ ir.SetAttribute(attr + 1, ir.GetAttribute(attr + 1, ir.Imm32(i)), ir.Imm32(0));
+ ir.SetAttribute(attr + 2, ir.GetAttribute(attr + 2, ir.Imm32(i)), ir.Imm32(0));
+ ir.SetAttribute(attr + 3, ir.GetAttribute(attr + 3, ir.Imm32(i)), ir.Imm32(0));
+
+ // Assign layer
+ ir.SetAttribute(IR::Attribute::Layer, ir.GetAttribute(source_program.info.emulated_layer),
+ ir.Imm32(0));
+
+ // Emit vertex
+ ir.EmitVertex(ir.Imm32(0));
+ }
+ ir.EndPrimitive(ir.Imm32(0));
+
+ IR::Block* return_block{block_pool.Create(inst_pool)};
+ IR::IREmitter{*return_block}.Epilogue();
+ current_block->AddBranch(return_block);
+
+ auto& merge{program.syntax_list.emplace_back()};
+ merge.type = IR::AbstractSyntaxNode::Type::Block;
+ merge.data.block = return_block;
+ program.syntax_list.emplace_back().type = IR::AbstractSyntaxNode::Type::Return;
+
+ program.blocks = GenerateBlocks(program.syntax_list);
+ program.post_order_blocks = PostOrder(program.syntax_list.front());
+ Optimization::SsaRewritePass(program);
+
+ return program;
+}
+
} // namespace Shader::Maxwell
diff --git a/src/shader_recompiler/frontend/maxwell/translate_program.h b/src/shader_recompiler/frontend/maxwell/translate_program.h
index 02ede8c9c..497afe7cb 100644
--- a/src/shader_recompiler/frontend/maxwell/translate_program.h
+++ b/src/shader_recompiler/frontend/maxwell/translate_program.h
@@ -25,4 +25,13 @@ namespace Shader::Maxwell {
void ConvertLegacyToGeneric(IR::Program& program, const RuntimeInfo& runtime_info);
+// Maxwell v1 and older Nvidia cards don't support setting gl_Layer from non-geometry stages.
+// This creates a workaround by setting the layer as a generic output and creating a
+// passthrough geometry shader that reads the generic and sets the layer.
+[[nodiscard]] IR::Program GenerateGeometryPassthrough(ObjectPool<IR::Inst>& inst_pool,
+ ObjectPool<IR::Block>& block_pool,
+ const HostTranslateInfo& host_info,
+ IR::Program& source_program,
+ Shader::OutputTopology output_topology);
+
} // namespace Shader::Maxwell
diff --git a/src/shader_recompiler/host_translate_info.h b/src/shader_recompiler/host_translate_info.h
index cc1500690..d5d279554 100644
--- a/src/shader_recompiler/host_translate_info.h
+++ b/src/shader_recompiler/host_translate_info.h
@@ -13,7 +13,8 @@ struct HostTranslateInfo {
bool support_float16{}; ///< True when the device supports 16-bit floats
bool support_int64{}; ///< True when the device supports 64-bit integers
bool needs_demote_reorder{}; ///< True when the device needs DemoteToHelperInvocation reordered
- bool support_snorm_render_buffer{}; ///< True when the device supports SNORM render buffers
+ bool support_snorm_render_buffer{}; ///< True when the device supports SNORM render buffers
+ bool support_viewport_index_layer{}; ///< True when the device supports gl_Layer in VS
};
} // namespace Shader
diff --git a/src/shader_recompiler/ir_opt/layer_pass.cpp b/src/shader_recompiler/ir_opt/layer_pass.cpp
new file mode 100644
index 000000000..4574f7cf2
--- /dev/null
+++ b/src/shader_recompiler/ir_opt/layer_pass.cpp
@@ -0,0 +1,68 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include <algorithm>
+#include <bit>
+#include <optional>
+
+#include <boost/container/small_vector.hpp>
+
+#include "shader_recompiler/environment.h"
+#include "shader_recompiler/frontend/ir/basic_block.h"
+#include "shader_recompiler/frontend/ir/breadth_first_search.h"
+#include "shader_recompiler/frontend/ir/ir_emitter.h"
+#include "shader_recompiler/host_translate_info.h"
+#include "shader_recompiler/ir_opt/passes.h"
+#include "shader_recompiler/shader_info.h"
+
+namespace Shader::Optimization {
+
+static IR::Attribute EmulatedLayerAttribute(VaryingState& stores) {
+ for (u32 i = 0; i < 32; i++) {
+ if (!stores.Generic(i)) {
+ return IR::Attribute::Generic0X + (i * 4);
+ }
+ }
+ return IR::Attribute::Layer;
+}
+
+static bool PermittedProgramStage(Stage stage) {
+ switch (stage) {
+ case Stage::VertexA:
+ case Stage::VertexB:
+ case Stage::TessellationControl:
+ case Stage::TessellationEval:
+ return true;
+ default:
+ return false;
+ }
+}
+
+void LayerPass(IR::Program& program, const HostTranslateInfo& host_info) {
+ if (host_info.support_viewport_index_layer || !PermittedProgramStage(program.stage)) {
+ return;
+ }
+
+ const auto end{program.post_order_blocks.end()};
+ const auto layer_attribute = EmulatedLayerAttribute(program.info.stores);
+ bool requires_layer_emulation = false;
+
+ for (auto block = program.post_order_blocks.begin(); block != end; ++block) {
+ for (IR::Inst& inst : (*block)->Instructions()) {
+ if (inst.GetOpcode() == IR::Opcode::SetAttribute &&
+ inst.Arg(0).Attribute() == IR::Attribute::Layer) {
+ requires_layer_emulation = true;
+ inst.SetArg(0, IR::Value{layer_attribute});
+ }
+ }
+ }
+
+ if (requires_layer_emulation) {
+ program.info.requires_layer_emulation = true;
+ program.info.emulated_layer = layer_attribute;
+ program.info.stores.Set(IR::Attribute::Layer, false);
+ program.info.stores.Set(layer_attribute, true);
+ }
+}
+
+} // namespace Shader::Optimization
diff --git a/src/shader_recompiler/ir_opt/passes.h b/src/shader_recompiler/ir_opt/passes.h
index 586a0668f..11bfe801a 100644
--- a/src/shader_recompiler/ir_opt/passes.h
+++ b/src/shader_recompiler/ir_opt/passes.h
@@ -23,6 +23,7 @@ void RescalingPass(IR::Program& program);
void SsaRewritePass(IR::Program& program);
void PositionPass(Environment& env, IR::Program& program);
void TexturePass(Environment& env, IR::Program& program, const HostTranslateInfo& host_info);
+void LayerPass(IR::Program& program, const HostTranslateInfo& host_info);
void VerificationPass(const IR::Program& program);
// Dual Vertex
diff --git a/src/shader_recompiler/precompiled_headers.h b/src/shader_recompiler/precompiled_headers.h
new file mode 100644
index 000000000..5dd6b7eca
--- /dev/null
+++ b/src/shader_recompiler/precompiled_headers.h
@@ -0,0 +1,7 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
+#include "frontend/maxwell/translate/impl/impl.h"
diff --git a/src/shader_recompiler/shader_info.h b/src/shader_recompiler/shader_info.h
index ee6252bb5..d9c6e92db 100644
--- a/src/shader_recompiler/shader_info.h
+++ b/src/shader_recompiler/shader_info.h
@@ -204,6 +204,9 @@ struct Info {
u32 nvn_buffer_base{};
std::bitset<16> nvn_buffer_used{};
+ bool requires_layer_emulation{};
+ IR::Attribute emulated_layer{};
+
boost::container::static_vector<ConstantBufferDescriptor, MAX_CBUFS>
constant_buffer_descriptors;
boost::container::static_vector<StorageBufferDescriptor, MAX_SSBOS> storage_buffers_descriptors;
diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt
index 43ad2c7ff..348d1edf4 100644
--- a/src/tests/CMakeLists.txt
+++ b/src/tests/CMakeLists.txt
@@ -11,6 +11,7 @@ add_executable(tests
common/unique_function.cpp
core/core_timing.cpp
core/internal_network/network.cpp
+ precompiled_headers.h
tests.cpp
video_core/buffer_base.cpp
input_common/calibration_configuration_job.cpp
@@ -22,3 +23,7 @@ target_link_libraries(tests PRIVATE common core input_common)
target_link_libraries(tests PRIVATE ${PLATFORM_LIBRARIES} Catch2::Catch2 Threads::Threads)
add_test(NAME tests COMMAND tests)
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(tests PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/tests/precompiled_headers.h b/src/tests/precompiled_headers.h
new file mode 100644
index 000000000..aabae730b
--- /dev/null
+++ b/src/tests/precompiled_headers.h
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
diff --git a/src/video_core/CMakeLists.txt b/src/video_core/CMakeLists.txt
index d7f7d336c..b9bad63ac 100644
--- a/src/video_core/CMakeLists.txt
+++ b/src/video_core/CMakeLists.txt
@@ -28,6 +28,10 @@ add_library(video_core STATIC
dirty_flags.h
dma_pusher.cpp
dma_pusher.h
+ engines/sw_blitter/blitter.cpp
+ engines/sw_blitter/blitter.h
+ engines/sw_blitter/converter.cpp
+ engines/sw_blitter/converter.h
engines/const_buffer_info.h
engines/engine_interface.h
engines/engine_upload.cpp
@@ -80,6 +84,7 @@ add_library(video_core STATIC
gpu_thread.h
memory_manager.cpp
memory_manager.h
+ precompiled_headers.h
pte_kind.h
query_cache.h
rasterizer_accelerated.cpp
@@ -87,6 +92,10 @@ add_library(video_core STATIC
rasterizer_interface.h
renderer_base.cpp
renderer_base.h
+ renderer_null/null_rasterizer.cpp
+ renderer_null/null_rasterizer.h
+ renderer_null/renderer_null.cpp
+ renderer_null/renderer_null.h
renderer_opengl/gl_buffer_cache.cpp
renderer_opengl/gl_buffer_cache.h
renderer_opengl/gl_compute_pipeline.cpp
@@ -275,9 +284,15 @@ if (MSVC)
/we4244 # 'conversion': conversion from 'type1' to 'type2', possible loss of data
)
else()
- target_compile_options(video_core PRIVATE
- -Werror=conversion
+ if (APPLE)
+ # error: declaration shadows a typedef in 'interval_base_set<SubType, DomainT, Compare, Interval, Alloc>'
+ # error: implicit conversion loses integer precision: 'int' to 'boost::icl::bound_type' (aka 'unsigned char')
+ target_compile_options(video_core PRIVATE -Wno-shadow -Wno-unused-local-typedef)
+ else()
+ target_compile_options(video_core PRIVATE -Werror=conversion)
+ endif()
+ target_compile_options(video_core PRIVATE
-Wno-sign-conversion
)
@@ -296,3 +311,7 @@ endif()
if (ARCHITECTURE_x86_64 OR ARCHITECTURE_arm64)
target_link_libraries(video_core PRIVATE dynarmic)
endif()
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(video_core PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/video_core/buffer_cache/buffer_base.h b/src/video_core/buffer_cache/buffer_base.h
index f9a6472cf..92d77eef2 100644
--- a/src/video_core/buffer_cache/buffer_base.h
+++ b/src/video_core/buffer_cache/buffer_base.h
@@ -535,7 +535,7 @@ private:
const u64* const state_words = Array<type>();
const u64 num_query_words = size / BYTES_PER_WORD + 1;
const u64 word_begin = offset / BYTES_PER_WORD;
- const u64 word_end = std::min(word_begin + num_query_words, NumWords());
+ const u64 word_end = std::min<u64>(word_begin + num_query_words, NumWords());
const u64 page_limit = Common::DivCeil(offset + size, BYTES_PER_PAGE);
u64 page_index = (offset / BYTES_PER_PAGE) % PAGES_PER_WORD;
for (u64 word_index = word_begin; word_index < word_end; ++word_index, page_index = 0) {
diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h
index 2ba33543c..6881b34c4 100644
--- a/src/video_core/buffer_cache/buffer_cache.h
+++ b/src/video_core/buffer_cache/buffer_cache.h
@@ -19,6 +19,7 @@
#include "common/literals.h"
#include "common/lru_cache.h"
#include "common/microprofile.h"
+#include "common/polyfill_ranges.h"
#include "common/settings.h"
#include "core/memory.h"
#include "video_core/buffer_cache/buffer_base.h"
@@ -992,7 +993,20 @@ void BufferCache<P>::BindHostIndexBuffer() {
TouchBuffer(buffer, index_buffer.buffer_id);
const u32 offset = buffer.Offset(index_buffer.cpu_addr);
const u32 size = index_buffer.size;
- SynchronizeBuffer(buffer, index_buffer.cpu_addr, size);
+ if (maxwell3d->inline_index_draw_indexes.size()) {
+ if constexpr (USE_MEMORY_MAPS) {
+ auto upload_staging = runtime.UploadStagingBuffer(size);
+ std::array<BufferCopy, 1> copies{
+ {BufferCopy{.src_offset = upload_staging.offset, .dst_offset = 0, .size = size}}};
+ std::memcpy(upload_staging.mapped_span.data(),
+ maxwell3d->inline_index_draw_indexes.data(), size);
+ runtime.CopyBuffer(buffer, upload_staging.buffer, copies);
+ } else {
+ buffer.ImmediateUpload(0, maxwell3d->inline_index_draw_indexes);
+ }
+ } else {
+ SynchronizeBuffer(buffer, index_buffer.cpu_addr, size);
+ }
if constexpr (HAS_FULL_INDEX_AND_PRIMITIVE_SUPPORT) {
const u32 new_offset = offset + maxwell3d->regs.index_buffer.first *
maxwell3d->regs.index_buffer.FormatSizeInBytes();
@@ -1275,7 +1289,15 @@ void BufferCache<P>::UpdateIndexBuffer() {
}
flags[Dirty::IndexBuffer] = false;
last_index_count = index_array.count;
-
+ if (maxwell3d->inline_index_draw_indexes.size()) {
+ auto inline_index_size = static_cast<u32>(maxwell3d->inline_index_draw_indexes.size());
+ index_buffer = Binding{
+ .cpu_addr = 0,
+ .size = inline_index_size,
+ .buffer_id = CreateBuffer(0, inline_index_size),
+ };
+ return;
+ }
const GPUVAddr gpu_addr_begin = index_array.StartAddress();
const GPUVAddr gpu_addr_end = index_array.EndAddress();
const std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin);
@@ -1491,6 +1513,14 @@ typename BufferCache<P>::OverlapResult BufferCache<P>::ResolveOverlaps(VAddr cpu
VAddr end = cpu_addr + wanted_size;
int stream_score = 0;
bool has_stream_leap = false;
+ if (begin == 0) {
+ return OverlapResult{
+ .ids = std::move(overlap_ids),
+ .begin = begin,
+ .end = end,
+ .has_stream_leap = has_stream_leap,
+ };
+ }
for (; cpu_addr >> YUZU_PAGEBITS < Common::DivCeil(end, YUZU_PAGESIZE);
cpu_addr += YUZU_PAGESIZE) {
const BufferId overlap_id = page_table[cpu_addr >> YUZU_PAGEBITS];
@@ -1713,12 +1743,12 @@ bool BufferCache<P>::InlineMemory(VAddr dest_address, size_t copy_size,
SynchronizeBuffer(buffer, dest_address, static_cast<u32>(copy_size));
if constexpr (USE_MEMORY_MAPS) {
+ auto upload_staging = runtime.UploadStagingBuffer(copy_size);
std::array copies{BufferCopy{
- .src_offset = 0,
+ .src_offset = upload_staging.offset,
.dst_offset = buffer.Offset(dest_address),
.size = copy_size,
}};
- auto upload_staging = runtime.UploadStagingBuffer(copy_size);
u8* const src_pointer = upload_staging.mapped_span.data();
std::memcpy(src_pointer, inlined_buffer.data(), copy_size);
runtime.CopyBuffer(buffer, upload_staging.buffer, copies);
diff --git a/src/video_core/control/channel_state.cpp b/src/video_core/control/channel_state.cpp
index cdecc3a91..832025d75 100644
--- a/src/video_core/control/channel_state.cpp
+++ b/src/video_core/control/channel_state.cpp
@@ -20,7 +20,7 @@ void ChannelState::Init(Core::System& system, GPU& gpu) {
ASSERT(memory_manager);
dma_pusher = std::make_unique<Tegra::DmaPusher>(system, gpu, *memory_manager, *this);
maxwell_3d = std::make_unique<Engines::Maxwell3D>(system, *memory_manager);
- fermi_2d = std::make_unique<Engines::Fermi2D>();
+ fermi_2d = std::make_unique<Engines::Fermi2D>(*memory_manager);
kepler_compute = std::make_unique<Engines::KeplerCompute>(system, *memory_manager);
maxwell_dma = std::make_unique<Engines::MaxwellDMA>(system, *memory_manager);
kepler_memory = std::make_unique<Engines::KeplerMemory>(system, *memory_manager);
diff --git a/src/video_core/control/channel_state_cache.h b/src/video_core/control/channel_state_cache.h
index 584a0c26c..cdaf4f8d5 100644
--- a/src/video_core/control/channel_state_cache.h
+++ b/src/video_core/control/channel_state_cache.h
@@ -35,8 +35,6 @@ public:
explicit ChannelInfo(Tegra::Control::ChannelState& state);
ChannelInfo(const ChannelInfo& state) = delete;
ChannelInfo& operator=(const ChannelInfo&) = delete;
- ChannelInfo(ChannelInfo&& other) = default;
- ChannelInfo& operator=(ChannelInfo&& other) = default;
Tegra::Engines::Maxwell3D& maxwell3d;
Tegra::Engines::KeplerCompute& kepler_compute;
diff --git a/src/video_core/engines/engine_upload.cpp b/src/video_core/engines/engine_upload.cpp
index a34819234..e4f8331ab 100644
--- a/src/video_core/engines/engine_upload.cpp
+++ b/src/video_core/engines/engine_upload.cpp
@@ -49,13 +49,12 @@ void State::ProcessData(std::span<const u8> read_buffer) {
if (regs.line_count == 1) {
rasterizer->AccelerateInlineToMemory(address, copy_size, read_buffer);
} else {
- for (u32 line = 0; line < regs.line_count; ++line) {
- const GPUVAddr dest_line = address + static_cast<size_t>(line) * regs.dest.pitch;
- memory_manager.WriteBlockUnsafe(
- dest_line, read_buffer.data() + static_cast<size_t>(line) * regs.line_length_in,
- regs.line_length_in);
+ for (size_t line = 0; line < regs.line_count; ++line) {
+ const GPUVAddr dest_line = address + line * regs.dest.pitch;
+ std::span<const u8> buffer(read_buffer.data() + line * regs.line_length_in,
+ regs.line_length_in);
+ rasterizer->AccelerateInlineToMemory(dest_line, regs.line_length_in, buffer);
}
- memory_manager.InvalidateRegion(address, regs.dest.pitch * regs.line_count);
}
} else {
u32 width = regs.dest.width;
diff --git a/src/video_core/engines/engine_upload.h b/src/video_core/engines/engine_upload.h
index f08f6e36a..94fafd9dc 100644
--- a/src/video_core/engines/engine_upload.h
+++ b/src/video_core/engines/engine_upload.h
@@ -39,7 +39,7 @@ struct Registers {
u32 y;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) | address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
u32 BlockWidth() const {
diff --git a/src/video_core/engines/fermi_2d.cpp b/src/video_core/engines/fermi_2d.cpp
index 453e0fb01..c6478ae85 100644
--- a/src/video_core/engines/fermi_2d.cpp
+++ b/src/video_core/engines/fermi_2d.cpp
@@ -3,17 +3,25 @@
#include "common/assert.h"
#include "common/logging/log.h"
+#include "common/microprofile.h"
#include "video_core/engines/fermi_2d.h"
-#include "video_core/memory_manager.h"
+#include "video_core/engines/sw_blitter/blitter.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/surface.h"
+#include "video_core/textures/decoders.h"
+
+MICROPROFILE_DECLARE(GPU_BlitEngine);
+MICROPROFILE_DEFINE(GPU_BlitEngine, "GPU", "Blit Engine", MP_RGB(224, 224, 128));
using VideoCore::Surface::BytesPerBlock;
using VideoCore::Surface::PixelFormatFromRenderTargetFormat;
namespace Tegra::Engines {
-Fermi2D::Fermi2D() {
+using namespace Texture;
+
+Fermi2D::Fermi2D(MemoryManager& memory_manager_) {
+ sw_blitter = std::make_unique<Blitter::SoftwareBlitEngine>(memory_manager_);
// Nvidia's OpenGL driver seems to assume these values
regs.src.depth = 1;
regs.dst.depth = 1;
@@ -42,6 +50,7 @@ void Fermi2D::CallMultiMethod(u32 method, const u32* base_start, u32 amount, u32
}
void Fermi2D::Blit() {
+ MICROPROFILE_SCOPE(GPU_BlitEngine);
LOG_DEBUG(HW_GPU, "called. source address=0x{:x}, destination address=0x{:x}",
regs.src.Address(), regs.dst.Address());
@@ -52,9 +61,16 @@ void Fermi2D::Blit() {
UNIMPLEMENTED_IF_MSG(regs.clip_enable != 0, "Clipped blit enabled");
const auto& args = regs.pixels_from_memory;
+ constexpr s64 null_derivate = 1ULL << 32;
+ Surface src = regs.src;
+ const auto bytes_per_pixel = BytesPerBlock(PixelFormatFromRenderTargetFormat(src.format));
+ const bool delegate_to_gpu = src.width > 512 && src.height > 512 && bytes_per_pixel <= 8 &&
+ src.format != regs.dst.format;
Config config{
.operation = regs.operation,
.filter = args.sample_mode.filter,
+ .must_accelerate =
+ args.du_dx != null_derivate || args.dv_dy != null_derivate || delegate_to_gpu,
.dst_x0 = args.dst_x0,
.dst_y0 = args.dst_y0,
.dst_x1 = args.dst_x0 + args.dst_width,
@@ -64,8 +80,7 @@ void Fermi2D::Blit() {
.src_x1 = static_cast<s32>((args.du_dx * args.dst_width + args.src_x0) >> 32),
.src_y1 = static_cast<s32>((args.dv_dy * args.dst_height + args.src_y0) >> 32),
};
- Surface src = regs.src;
- const auto bytes_per_pixel = BytesPerBlock(PixelFormatFromRenderTargetFormat(src.format));
+
const auto need_align_to_pitch =
src.linear == Tegra::Engines::Fermi2D::MemoryLayout::Pitch &&
static_cast<s32>(src.width) == config.src_x1 &&
@@ -78,8 +93,9 @@ void Fermi2D::Blit() {
config.src_x1 -= config.src_x0;
config.src_x0 = 0;
}
+
if (!rasterizer->AccelerateSurfaceCopy(src, regs.dst, config)) {
- UNIMPLEMENTED();
+ sw_blitter->Blit(src, regs.dst, config);
}
}
diff --git a/src/video_core/engines/fermi_2d.h b/src/video_core/engines/fermi_2d.h
index 1229aa35b..100b21bac 100644
--- a/src/video_core/engines/fermi_2d.h
+++ b/src/video_core/engines/fermi_2d.h
@@ -5,6 +5,7 @@
#include <array>
#include <cstddef>
+#include <memory>
#include "common/bit_field.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
@@ -21,6 +22,10 @@ class RasterizerInterface;
namespace Tegra::Engines {
+namespace Blitter {
+class SoftwareBlitEngine;
+}
+
/**
* This Engine is known as G80_2D. Documentation can be found in:
* https://github.com/envytools/envytools/blob/master/rnndb/graph/g80_2d.xml
@@ -32,7 +37,7 @@ namespace Tegra::Engines {
class Fermi2D final : public EngineInterface {
public:
- explicit Fermi2D();
+ explicit Fermi2D(MemoryManager& memory_manager_);
~Fermi2D() override;
/// Binds a rasterizer to this engine.
@@ -92,7 +97,7 @@ public:
u32 addr_lower;
[[nodiscard]] constexpr GPUVAddr Address() const noexcept {
- return (static_cast<GPUVAddr>(addr_upper) << 32) | static_cast<GPUVAddr>(addr_lower);
+ return (GPUVAddr{addr_upper} << 32) | GPUVAddr{addr_lower};
}
};
static_assert(sizeof(Surface) == 0x28, "Surface has incorrect size");
@@ -286,6 +291,7 @@ public:
struct Config {
Operation operation;
Filter filter;
+ bool must_accelerate;
s32 dst_x0;
s32 dst_y0;
s32 dst_x1;
@@ -298,6 +304,7 @@ public:
private:
VideoCore::RasterizerInterface* rasterizer = nullptr;
+ std::unique_ptr<Blitter::SoftwareBlitEngine> sw_blitter;
/// Performs the copy from the source surface to the destination surface as configured in the
/// registers.
diff --git a/src/video_core/engines/kepler_compute.cpp b/src/video_core/engines/kepler_compute.cpp
index 7c50bdbe0..e5c622155 100644
--- a/src/video_core/engines/kepler_compute.cpp
+++ b/src/video_core/engines/kepler_compute.cpp
@@ -50,11 +50,11 @@ void KeplerCompute::CallMultiMethod(u32 method, const u32* base_start, u32 amoun
u32 methods_pending) {
switch (method) {
case KEPLER_COMPUTE_REG_INDEX(data_upload):
- upload_state.ProcessData(base_start, static_cast<size_t>(amount));
+ upload_state.ProcessData(base_start, amount);
return;
default:
- for (std::size_t i = 0; i < amount; i++) {
- CallMethod(method, base_start[i], methods_pending - static_cast<u32>(i) <= 1);
+ for (u32 i = 0; i < amount; i++) {
+ CallMethod(method, base_start[i], methods_pending - i <= 1);
}
break;
}
diff --git a/src/video_core/engines/kepler_compute.h b/src/video_core/engines/kepler_compute.h
index aab309ecc..e154e3f06 100644
--- a/src/video_core/engines/kepler_compute.h
+++ b/src/video_core/engines/kepler_compute.h
@@ -68,7 +68,7 @@ public:
struct {
u32 address;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address) << 8));
+ return GPUVAddr{address} << 8;
}
} launch_desc_loc;
@@ -83,8 +83,7 @@ public:
u32 address_low;
u32 limit;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
} tsc;
@@ -95,8 +94,7 @@ public:
u32 address_low;
u32 limit;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
} tic;
@@ -106,8 +104,7 @@ public:
u32 address_high;
u32 address_low;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
} code_loc;
@@ -162,8 +159,7 @@ public:
BitField<15, 17, u32> size;
};
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high.Value()) << 32) |
- address_low);
+ return (GPUVAddr{address_high.Value()} << 32) | GPUVAddr{address_low};
}
};
std::array<ConstBufferConfig, NumConstBuffers> const_buffer_config;
diff --git a/src/video_core/engines/kepler_memory.cpp b/src/video_core/engines/kepler_memory.cpp
index a3fbab1e5..08045d1cf 100644
--- a/src/video_core/engines/kepler_memory.cpp
+++ b/src/video_core/engines/kepler_memory.cpp
@@ -42,11 +42,11 @@ void KeplerMemory::CallMultiMethod(u32 method, const u32* base_start, u32 amount
u32 methods_pending) {
switch (method) {
case KEPLERMEMORY_REG_INDEX(data):
- upload_state.ProcessData(base_start, static_cast<size_t>(amount));
+ upload_state.ProcessData(base_start, amount);
return;
default:
- for (std::size_t i = 0; i < amount; i++) {
- CallMethod(method, base_start[i], methods_pending - static_cast<u32>(i) <= 1);
+ for (u32 i = 0; i < amount; i++) {
+ CallMethod(method, base_start[i], methods_pending - i <= 1);
}
break;
}
diff --git a/src/video_core/engines/maxwell_3d.cpp b/src/video_core/engines/maxwell_3d.cpp
index d502d181c..34bbc72cf 100644
--- a/src/video_core/engines/maxwell_3d.cpp
+++ b/src/video_core/engines/maxwell_3d.cpp
@@ -217,22 +217,25 @@ void Maxwell3D::ProcessMethodCall(u32 method, u32 argument, u32 nonshadow_argume
regs.index_buffer.count = regs.index_buffer32_first.count;
regs.index_buffer.first = regs.index_buffer32_first.first;
dirty.flags[VideoCommon::Dirty::IndexBuffer] = true;
+ draw_indexed = true;
return ProcessDraw();
case MAXWELL3D_REG_INDEX(index_buffer16_first):
regs.index_buffer.count = regs.index_buffer16_first.count;
regs.index_buffer.first = regs.index_buffer16_first.first;
dirty.flags[VideoCommon::Dirty::IndexBuffer] = true;
+ draw_indexed = true;
return ProcessDraw();
case MAXWELL3D_REG_INDEX(index_buffer8_first):
regs.index_buffer.count = regs.index_buffer8_first.count;
regs.index_buffer.first = regs.index_buffer8_first.first;
dirty.flags[VideoCommon::Dirty::IndexBuffer] = true;
+ draw_indexed = true;
return ProcessDraw();
case MAXWELL3D_REG_INDEX(topology_override):
use_topology_override = true;
return;
case MAXWELL3D_REG_INDEX(clear_surface):
- return ProcessClearBuffers();
+ return ProcessClearBuffers(1);
case MAXWELL3D_REG_INDEX(report_semaphore.query):
return ProcessQueryGet();
case MAXWELL3D_REG_INDEX(render_enable.mode):
@@ -249,9 +252,6 @@ void Maxwell3D::ProcessMethodCall(u32 method, u32 argument, u32 nonshadow_argume
return;
case MAXWELL3D_REG_INDEX(fragment_barrier):
return rasterizer->FragmentBarrier();
- case MAXWELL3D_REG_INDEX(invalidate_texture_data_cache):
- rasterizer->InvalidateGPUCache();
- return rasterizer->WaitForIdle();
case MAXWELL3D_REG_INDEX(tiled_cache_barrier):
return rasterizer->TiledCacheBarrier();
}
@@ -288,31 +288,63 @@ void Maxwell3D::CallMethod(u32 method, u32 method_argument, bool is_last_call) {
ASSERT_MSG(method < Regs::NUM_REGS,
"Invalid Maxwell3D register, increase the size of the Regs structure");
+ const u32 argument = ProcessShadowRam(method, method_argument);
+ ProcessDirtyRegisters(method, argument);
+
if (draw_command[method]) {
regs.reg_array[method] = method_argument;
deferred_draw_method.push_back(method);
- auto u32_to_u8 = [&](const u32 argument) {
- inline_index_draw_indexes.push_back(static_cast<u8>(argument & 0x000000ff));
- inline_index_draw_indexes.push_back(static_cast<u8>((argument & 0x0000ff00) >> 8));
- inline_index_draw_indexes.push_back(static_cast<u8>((argument & 0x00ff0000) >> 16));
- inline_index_draw_indexes.push_back(static_cast<u8>((argument & 0xff000000) >> 24));
+ auto update_inline_index = [&](const u32 index) {
+ inline_index_draw_indexes.push_back(static_cast<u8>(index & 0x000000ff));
+ inline_index_draw_indexes.push_back(static_cast<u8>((index & 0x0000ff00) >> 8));
+ inline_index_draw_indexes.push_back(static_cast<u8>((index & 0x00ff0000) >> 16));
+ inline_index_draw_indexes.push_back(static_cast<u8>((index & 0xff000000) >> 24));
+ draw_mode = DrawMode::InlineIndex;
};
- if (MAXWELL3D_REG_INDEX(draw_inline_index) == method) {
- u32_to_u8(method_argument);
- } else if (MAXWELL3D_REG_INDEX(inline_index_2x16.even) == method) {
- u32_to_u8(regs.inline_index_2x16.even);
- u32_to_u8(regs.inline_index_2x16.odd);
- } else if (MAXWELL3D_REG_INDEX(inline_index_4x8.index0) == method) {
- u32_to_u8(regs.inline_index_4x8.index0);
- u32_to_u8(regs.inline_index_4x8.index1);
- u32_to_u8(regs.inline_index_4x8.index2);
- u32_to_u8(regs.inline_index_4x8.index3);
+ switch (method) {
+ case MAXWELL3D_REG_INDEX(draw.begin): {
+ draw_mode =
+ (regs.draw.instance_id == Maxwell3D::Regs::Draw::InstanceId::Subsequent) ||
+ (regs.draw.instance_id == Maxwell3D::Regs::Draw::InstanceId::Unchanged)
+ ? DrawMode::Instance
+ : DrawMode::General;
+ break;
+ }
+ case MAXWELL3D_REG_INDEX(draw.end):
+ switch (draw_mode) {
+ case DrawMode::General:
+ ProcessDraw();
+ break;
+ case DrawMode::InlineIndex:
+ regs.index_buffer.count = static_cast<u32>(inline_index_draw_indexes.size() / 4);
+ regs.index_buffer.format = Regs::IndexFormat::UnsignedInt;
+ draw_indexed = true;
+ ProcessDraw();
+ inline_index_draw_indexes.clear();
+ break;
+ case DrawMode::Instance:
+ break;
+ }
+ break;
+ case MAXWELL3D_REG_INDEX(index_buffer.count):
+ draw_indexed = true;
+ break;
+ case MAXWELL3D_REG_INDEX(draw_inline_index):
+ update_inline_index(method_argument);
+ break;
+ case MAXWELL3D_REG_INDEX(inline_index_2x16.even):
+ update_inline_index(regs.inline_index_2x16.even);
+ update_inline_index(regs.inline_index_2x16.odd);
+ break;
+ case MAXWELL3D_REG_INDEX(inline_index_4x8.index0):
+ update_inline_index(regs.inline_index_4x8.index0);
+ update_inline_index(regs.inline_index_4x8.index1);
+ update_inline_index(regs.inline_index_4x8.index2);
+ update_inline_index(regs.inline_index_4x8.index3);
+ break;
}
} else {
ProcessDeferredDraw();
-
- const u32 argument = ProcessShadowRam(method, method_argument);
- ProcessDirtyRegisters(method, argument);
ProcessMethodCall(method, argument, method_argument, is_last_call);
}
}
@@ -345,11 +377,11 @@ void Maxwell3D::CallMultiMethod(u32 method, const u32* base_start, u32 amount,
ProcessCBMultiData(base_start, amount);
break;
case MAXWELL3D_REG_INDEX(inline_data):
- upload_state.ProcessData(base_start, static_cast<size_t>(amount));
+ upload_state.ProcessData(base_start, amount);
return;
default:
- for (std::size_t i = 0; i < amount; i++) {
- CallMethod(method, base_start[i], methods_pending - static_cast<u32>(i) <= 1);
+ for (u32 i = 0; i < amount; i++) {
+ CallMethod(method, base_start[i], methods_pending - i <= 1);
}
break;
}
@@ -511,10 +543,7 @@ void Maxwell3D::ProcessCounterReset() {
void Maxwell3D::ProcessSyncPoint() {
const u32 sync_point = regs.sync_info.sync_point.Value();
- const u32 cache_flush = regs.sync_info.clean_l2.Value();
- if (cache_flush != 0) {
- rasterizer->InvalidateGPUCache();
- }
+ [[maybe_unused]] const u32 cache_flush = regs.sync_info.clean_l2.Value();
rasterizer->SignalSyncPoint(sync_point);
}
@@ -596,87 +625,44 @@ u32 Maxwell3D::GetRegisterValue(u32 method) const {
return regs.reg_array[method];
}
-void Maxwell3D::ProcessClearBuffers() {
- rasterizer->Clear();
+void Maxwell3D::ProcessClearBuffers(u32 layer_count) {
+ rasterizer->Clear(layer_count);
}
void Maxwell3D::ProcessDraw(u32 instance_count) {
LOG_TRACE(HW_GPU, "called, topology={}, count={}", regs.draw.topology.Value(),
- regs.vertex_buffer.count);
-
- ASSERT_MSG(!(regs.index_buffer.count && regs.vertex_buffer.count), "Both indexed and direct?");
-
- // Both instance configuration registers can not be set at the same time.
- ASSERT_MSG(regs.draw.instance_id == Maxwell3D::Regs::Draw::InstanceId::First ||
- regs.draw.instance_id != Maxwell3D::Regs::Draw::InstanceId::Unchanged,
- "Illegal combination of instancing parameters");
+ draw_indexed ? regs.index_buffer.count : regs.vertex_buffer.count);
ProcessTopologyOverride();
- const bool is_indexed = regs.index_buffer.count && !regs.vertex_buffer.count;
if (ShouldExecute()) {
- rasterizer->Draw(is_indexed, instance_count);
+ rasterizer->Draw(draw_indexed, instance_count);
}
- if (is_indexed) {
- regs.index_buffer.count = 0;
- } else {
- regs.vertex_buffer.count = 0;
- }
+ draw_indexed = false;
+ deferred_draw_method.clear();
}
void Maxwell3D::ProcessDeferredDraw() {
- if (deferred_draw_method.empty()) {
+ if (draw_mode != DrawMode::Instance || deferred_draw_method.empty()) {
return;
}
- enum class DrawMode {
- Undefined,
- General,
- Instance,
- };
- DrawMode draw_mode{DrawMode::Undefined};
- u32 method_count = static_cast<u32>(deferred_draw_method.size());
- u32 method = deferred_draw_method[method_count - 1];
- if (MAXWELL3D_REG_INDEX(draw.end) != method) {
- return;
- }
- draw_mode = (regs.draw.instance_id == Maxwell3D::Regs::Draw::InstanceId::Subsequent) ||
- (regs.draw.instance_id == Maxwell3D::Regs::Draw::InstanceId::Unchanged)
- ? DrawMode::Instance
- : DrawMode::General;
- u32 instance_count = 0;
- if (draw_mode == DrawMode::Instance) {
- u32 vertex_buffer_count = 0;
- u32 index_buffer_count = 0;
- for (u32 index = 0; index < method_count; ++index) {
- method = deferred_draw_method[index];
- if (method == MAXWELL3D_REG_INDEX(vertex_buffer.count)) {
- instance_count = ++vertex_buffer_count;
- } else if (method == MAXWELL3D_REG_INDEX(index_buffer.count)) {
- instance_count = ++index_buffer_count;
- }
- }
- ASSERT_MSG(!(vertex_buffer_count && index_buffer_count),
- "Instance both indexed and direct?");
- } else {
- instance_count = 1;
- for (u32 index = 0; index < method_count; ++index) {
- method = deferred_draw_method[index];
- if (MAXWELL3D_REG_INDEX(draw_inline_index) == method ||
- MAXWELL3D_REG_INDEX(inline_index_2x16.even) == method ||
- MAXWELL3D_REG_INDEX(inline_index_4x8.index0) == method) {
- regs.index_buffer.count = static_cast<u32>(inline_index_draw_indexes.size() / 4);
- regs.index_buffer.format = Regs::IndexFormat::UnsignedInt;
- break;
- }
+ const auto method_count = deferred_draw_method.size();
+ u32 instance_count = 1;
+ u32 vertex_buffer_count = 0;
+ u32 index_buffer_count = 0;
+ for (size_t index = 0; index < method_count; ++index) {
+ const u32 method = deferred_draw_method[index];
+ if (method == MAXWELL3D_REG_INDEX(vertex_buffer.count)) {
+ instance_count = ++vertex_buffer_count;
+ } else if (method == MAXWELL3D_REG_INDEX(index_buffer.count)) {
+ instance_count = ++index_buffer_count;
}
}
+ ASSERT_MSG(!(vertex_buffer_count && index_buffer_count), "Instance both indexed and direct?");
ProcessDraw(instance_count);
-
- deferred_draw_method.clear();
- inline_index_draw_indexes.clear();
}
} // namespace Tegra::Engines
diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h
index 34b085388..a541cd95f 100644
--- a/src/video_core/engines/maxwell_3d.h
+++ b/src/video_core/engines/maxwell_3d.h
@@ -96,8 +96,7 @@ public:
u32 type;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -106,8 +105,7 @@ public:
u32 address_low;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -124,8 +122,7 @@ public:
Mode mode;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(offset_high) << 32) |
- offset_low);
+ return (GPUVAddr{offset_high} << 32) | GPUVAddr{offset_low};
}
};
@@ -187,7 +184,7 @@ public:
default:
// Thresholds begin at 0x10 (1 << 4)
// Threshold is in the range 0x1 to 0x13
- return 1 << (4 + threshold.Value() - 1);
+ return 1U << (4 + threshold.Value() - 1);
}
}
};
@@ -468,8 +465,7 @@ public:
INSERT_PADDING_BYTES_NOINIT(0xC);
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
static_assert(sizeof(Buffer) == 0x20);
@@ -511,12 +507,11 @@ public:
u32 default_size_per_warp;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
u64 Size() const {
- return (static_cast<u64>(size_high) << 32) | size_low;
+ return (u64{size_high} << 32) | u64{size_low};
}
};
@@ -538,13 +533,11 @@ public:
u32 storage_limit_address_low;
GPUVAddr StorageAddress() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(storage_address_high) << 32) |
- storage_address_low);
+ return (GPUVAddr{storage_address_high} << 32) | GPUVAddr{storage_address_low};
}
GPUVAddr StorageLimitAddress() const {
- return static_cast<GPUVAddr>(
- (static_cast<GPUVAddr>(storage_limit_address_high) << 32) |
- storage_limit_address_low);
+ return (GPUVAddr{storage_limit_address_high} << 32) |
+ GPUVAddr{storage_limit_address_low};
}
};
@@ -829,11 +822,11 @@ public:
struct CompressionThresholdSamples {
u32 samples;
- u32 Samples() {
+ u32 Samples() const {
if (samples == 0) {
return 0;
}
- return 1 << (samples - 1);
+ return 1U << (samples - 1);
}
};
@@ -1138,8 +1131,7 @@ public:
INSERT_PADDING_BYTES_NOINIT(0x18);
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
static_assert(sizeof(RenderTargetConfig) == 0x40);
@@ -1482,8 +1474,7 @@ public:
u32 address_low;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -1533,8 +1524,7 @@ public:
u32 address_low;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -1561,8 +1551,7 @@ public:
u32 array_pitch;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -1910,8 +1899,7 @@ public:
Mode mode;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -1921,8 +1909,7 @@ public:
u32 limit;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -1932,8 +1919,7 @@ public:
u32 limit;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -1981,8 +1967,7 @@ public:
u32 address_low;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -2027,8 +2012,7 @@ public:
u32 address_low;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -2224,19 +2208,16 @@ public:
}
GPUVAddr StartAddress() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(start_addr_high) << 32) |
- start_addr_low);
+ return (GPUVAddr{start_addr_high} << 32) | GPUVAddr{start_addr_low};
}
GPUVAddr EndAddress() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(limit_addr_high) << 32) |
- limit_addr_low);
+ return (GPUVAddr{limit_addr_high} << 32) | GPUVAddr{limit_addr_low};
}
/// Adjust the index buffer offset so it points to the first desired index.
GPUVAddr IndexStart() const {
- return StartAddress() +
- static_cast<size_t>(first) * static_cast<size_t>(FormatSizeInBytes());
+ return StartAddress() + size_t{first} * size_t{FormatSizeInBytes()};
}
};
@@ -2464,8 +2445,7 @@ public:
} query;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -2479,8 +2459,7 @@ public:
u32 frequency;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
bool IsEnabled() const {
@@ -2494,8 +2473,7 @@ public:
u32 address_low;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
static_assert(sizeof(VertexStreamLimit) == 0x8);
@@ -2543,8 +2521,7 @@ public:
std::array<u32, NumCBData> buffer;
GPUVAddr Address() const {
- return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) |
- address_low);
+ return (GPUVAddr{address_high} << 32) | GPUVAddr{address_low};
}
};
@@ -3086,6 +3063,9 @@ public:
std::vector<u8> inline_index_draw_indexes;
+ /// Handles a write to the CLEAR_BUFFERS register.
+ void ProcessClearBuffers(u32 layer_count);
+
private:
void InitializeRegisterDefaults();
@@ -3120,9 +3100,6 @@ private:
/// Handles firmware blob 4
void ProcessFirmwareCall4();
- /// Handles a write to the CLEAR_BUFFERS register.
- void ProcessClearBuffers();
-
/// Handles a write to the QUERY_GET register.
void ProcessQueryGet();
@@ -3148,10 +3125,12 @@ private:
/// Handles use of topology overrides (e.g., to avoid using a topology assigned from a macro)
void ProcessTopologyOverride();
- void ProcessDraw(u32 instance_count = 1);
-
+ /// Handles deferred draw(e.g., instance draw).
void ProcessDeferredDraw();
+ /// Handles a draw.
+ void ProcessDraw(u32 instance_count = 1);
+
/// Returns a query's value or an empty object if the value will be deferred through a cache.
std::optional<u64> GetQueryResult();
@@ -3178,6 +3157,9 @@ private:
std::array<bool, Regs::NUM_REGS> draw_command{};
std::vector<u32> deferred_draw_method;
+ enum class DrawMode : u32 { General = 0, Instance, InlineIndex };
+ DrawMode draw_mode{DrawMode::General};
+ bool draw_indexed{};
};
#define ASSERT_REG_POSITION(field_name, position) \
diff --git a/src/video_core/engines/maxwell_dma.cpp b/src/video_core/engines/maxwell_dma.cpp
index 54523a4b2..a189e60ae 100644
--- a/src/video_core/engines/maxwell_dma.cpp
+++ b/src/video_core/engines/maxwell_dma.cpp
@@ -41,8 +41,8 @@ void MaxwellDMA::CallMethod(u32 method, u32 method_argument, bool is_last_call)
void MaxwellDMA::CallMultiMethod(u32 method, const u32* base_start, u32 amount,
u32 methods_pending) {
- for (size_t i = 0; i < amount; ++i) {
- CallMethod(method, base_start[i], methods_pending - static_cast<u32>(i) <= 1);
+ for (u32 i = 0; i < amount; ++i) {
+ CallMethod(method, base_start[i], methods_pending - i <= 1);
}
}
@@ -62,7 +62,8 @@ void MaxwellDMA::Launch() {
if (!is_src_pitch && !is_dst_pitch) {
// If both the source and the destination are in block layout, assert.
- UNIMPLEMENTED_MSG("Tiled->Tiled DMA transfers are not yet implemented");
+ CopyBlockLinearToBlockLinear();
+ ReleaseSemaphore();
return;
}
@@ -93,14 +94,14 @@ void MaxwellDMA::Launch() {
reinterpret_cast<u8*>(tmp_buffer.data()),
regs.line_length_in * sizeof(u32));
} else {
- auto convert_linear_2_blocklinear_addr = [](u64 address) {
+ const auto convert_linear_2_blocklinear_addr = [](u64 address) {
return (address & ~0x1f0ULL) | ((address & 0x40) >> 2) | ((address & 0x10) << 1) |
((address & 0x180) >> 1) | ((address & 0x20) << 3);
};
- auto src_kind = memory_manager.GetPageKind(regs.offset_in);
- auto dst_kind = memory_manager.GetPageKind(regs.offset_out);
- const bool is_src_pitch = IsPitchKind(static_cast<PTEKind>(src_kind));
- const bool is_dst_pitch = IsPitchKind(static_cast<PTEKind>(dst_kind));
+ const auto src_kind = memory_manager.GetPageKind(regs.offset_in);
+ const auto dst_kind = memory_manager.GetPageKind(regs.offset_out);
+ const bool is_src_pitch = IsPitchKind(src_kind);
+ const bool is_dst_pitch = IsPitchKind(dst_kind);
if (!is_src_pitch && is_dst_pitch) {
UNIMPLEMENTED_IF(regs.line_length_in % 16 != 0);
UNIMPLEMENTED_IF(regs.offset_in % 16 != 0);
@@ -291,6 +292,70 @@ void MaxwellDMA::FastCopyBlockLinearToPitch() {
memory_manager.WriteBlock(regs.offset_out, write_buffer.data(), dst_size);
}
+void MaxwellDMA::CopyBlockLinearToBlockLinear() {
+ UNIMPLEMENTED_IF(regs.src_params.block_size.width != 0);
+
+ const bool is_remapping = regs.launch_dma.remap_enable != 0;
+
+ // Deswizzle the input and copy it over.
+ const Parameters& src = regs.src_params;
+ const Parameters& dst = regs.dst_params;
+
+ const u32 num_remap_components = regs.remap_const.num_dst_components_minus_one + 1;
+ const u32 remap_components_size = regs.remap_const.component_size_minus_one + 1;
+
+ const u32 base_bpp = !is_remapping ? 1U : num_remap_components * remap_components_size;
+
+ u32 src_width = src.width;
+ u32 dst_width = dst.width;
+ u32 x_elements = regs.line_length_in;
+ u32 src_x_offset = src.origin.x;
+ u32 dst_x_offset = dst.origin.x;
+ u32 bpp_shift = 0U;
+ if (!is_remapping) {
+ bpp_shift = Common::FoldRight(
+ 4U, [](u32 x, u32 y) { return std::min(x, static_cast<u32>(std::countr_zero(y))); },
+ src_width, dst_width, x_elements, src_x_offset, dst_x_offset,
+ static_cast<u32>(regs.offset_in), static_cast<u32>(regs.offset_out));
+ src_width >>= bpp_shift;
+ dst_width >>= bpp_shift;
+ x_elements >>= bpp_shift;
+ src_x_offset >>= bpp_shift;
+ dst_x_offset >>= bpp_shift;
+ }
+
+ const u32 bytes_per_pixel = base_bpp << bpp_shift;
+ const size_t src_size = CalculateSize(true, bytes_per_pixel, src_width, src.height, src.depth,
+ src.block_size.height, src.block_size.depth);
+ const size_t dst_size = CalculateSize(true, bytes_per_pixel, dst_width, dst.height, dst.depth,
+ dst.block_size.height, dst.block_size.depth);
+
+ const u32 pitch = x_elements * bytes_per_pixel;
+ const size_t mid_buffer_size = pitch * regs.line_count;
+
+ if (read_buffer.size() < src_size) {
+ read_buffer.resize(src_size);
+ }
+ if (write_buffer.size() < dst_size) {
+ write_buffer.resize(dst_size);
+ }
+
+ intermediate_buffer.resize(mid_buffer_size);
+
+ memory_manager.ReadBlock(regs.offset_in, read_buffer.data(), src_size);
+ memory_manager.ReadBlock(regs.offset_out, write_buffer.data(), dst_size);
+
+ UnswizzleSubrect(intermediate_buffer, read_buffer, bytes_per_pixel, src_width, src.height,
+ src.depth, src_x_offset, src.origin.y, x_elements, regs.line_count,
+ src.block_size.height, src.block_size.depth, pitch);
+
+ SwizzleSubrect(write_buffer, intermediate_buffer, bytes_per_pixel, dst_width, dst.height,
+ dst.depth, dst_x_offset, dst.origin.y, x_elements, regs.line_count,
+ dst.block_size.height, dst.block_size.depth, pitch);
+
+ memory_manager.WriteBlock(regs.offset_out, write_buffer.data(), dst_size);
+}
+
void MaxwellDMA::ReleaseSemaphore() {
const auto type = regs.launch_dma.semaphore_type;
const GPUVAddr address = regs.semaphore.address;
@@ -314,6 +379,7 @@ void MaxwellDMA::ReleaseSemaphore() {
}
default:
ASSERT_MSG(false, "Unknown semaphore type: {}", static_cast<u32>(type.Value()));
+ break;
}
}
diff --git a/src/video_core/engines/maxwell_dma.h b/src/video_core/engines/maxwell_dma.h
index 953e34adc..d40d3d302 100644
--- a/src/video_core/engines/maxwell_dma.h
+++ b/src/video_core/engines/maxwell_dma.h
@@ -223,6 +223,8 @@ private:
void CopyPitchToBlockLinear();
+ void CopyBlockLinearToBlockLinear();
+
void FastCopyBlockLinearToPitch();
void ReleaseSemaphore();
@@ -234,6 +236,7 @@ private:
std::vector<u8> read_buffer;
std::vector<u8> write_buffer;
+ std::vector<u8> intermediate_buffer;
static constexpr std::size_t NUM_REGS = 0x800;
struct Regs {
diff --git a/src/video_core/engines/puller.cpp b/src/video_core/engines/puller.cpp
index 3977bb0fb..7718a09b3 100644
--- a/src/video_core/engines/puller.cpp
+++ b/src/video_core/engines/puller.cpp
@@ -31,7 +31,7 @@ void Puller::ProcessBindMethod(const MethodCall& method_call) {
LOG_DEBUG(HW_GPU, "Binding subchannel {} to engine {}", method_call.subchannel,
method_call.argument);
const auto engine_id = static_cast<EngineID>(method_call.argument);
- bound_engines[method_call.subchannel] = static_cast<EngineID>(engine_id);
+ bound_engines[method_call.subchannel] = engine_id;
switch (engine_id) {
case EngineID::FERMI_TWOD_A:
dma_pusher.BindSubchannel(channel_state.fermi_2d.get(), method_call.subchannel);
@@ -50,6 +50,7 @@ void Puller::ProcessBindMethod(const MethodCall& method_call) {
break;
default:
UNIMPLEMENTED_MSG("Unimplemented engine {:04X}", engine_id);
+ break;
}
}
@@ -65,6 +66,7 @@ void Puller::ProcessFenceActionMethod() {
break;
default:
UNIMPLEMENTED_MSG("Unimplemented operation {}", regs.fence_action.op.Value());
+ break;
}
}
@@ -116,7 +118,7 @@ void Puller::ProcessSemaphoreRelease() {
std::function<void()> operation([this, sequence_address, payload] {
memory_manager.Write<u32>(sequence_address, payload);
});
- rasterizer->SyncOperation(std::move(operation));
+ rasterizer->SignalFence(std::move(operation));
}
void Puller::ProcessSemaphoreAcquire() {
@@ -149,8 +151,8 @@ void Puller::CallPullerMethod(const MethodCall& method_call) {
case BufferMethods::SemaphoreAddressLow:
case BufferMethods::SemaphoreSequencePayload:
case BufferMethods::SyncpointPayload:
- break;
case BufferMethods::WrcacheFlush:
+ break;
case BufferMethods::RefCnt:
rasterizer->SignalReference();
break;
@@ -228,6 +230,7 @@ void Puller::CallEngineMethod(const MethodCall& method_call) {
break;
default:
UNIMPLEMENTED_MSG("Unimplemented engine");
+ break;
}
}
@@ -254,6 +257,7 @@ void Puller::CallEngineMultiMethod(u32 method, u32 subchannel, const u32* base_s
break;
default:
UNIMPLEMENTED_MSG("Unimplemented engine");
+ break;
}
}
@@ -281,12 +285,12 @@ void Puller::CallMultiMethod(u32 method, u32 subchannel, const u32* base_start,
if (ExecuteMethodOnEngine(method)) {
CallEngineMultiMethod(method, subchannel, base_start, amount, methods_pending);
} else {
- for (std::size_t i = 0; i < amount; i++) {
+ for (u32 i = 0; i < amount; i++) {
CallPullerMethod(MethodCall{
method,
base_start[i],
subchannel,
- methods_pending - static_cast<u32>(i),
+ methods_pending - i,
});
}
}
diff --git a/src/video_core/engines/sw_blitter/blitter.cpp b/src/video_core/engines/sw_blitter/blitter.cpp
new file mode 100644
index 000000000..2f1ea4626
--- /dev/null
+++ b/src/video_core/engines/sw_blitter/blitter.cpp
@@ -0,0 +1,238 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+#include <algorithm>
+#include <cmath>
+#include <vector>
+
+#include "video_core/engines/sw_blitter/blitter.h"
+#include "video_core/engines/sw_blitter/converter.h"
+#include "video_core/memory_manager.h"
+#include "video_core/surface.h"
+#include "video_core/textures/decoders.h"
+
+namespace Tegra {
+class MemoryManager;
+}
+
+using VideoCore::Surface::BytesPerBlock;
+using VideoCore::Surface::PixelFormatFromRenderTargetFormat;
+
+namespace Tegra::Engines::Blitter {
+
+using namespace Texture;
+
+namespace {
+
+constexpr size_t ir_components = 4;
+
+void NearestNeighbor(std::span<const u8> input, std::span<u8> output, u32 src_width, u32 src_height,
+ u32 dst_width, u32 dst_height, size_t bpp) {
+ const size_t dx_du = std::llround((static_cast<f64>(src_width) / dst_width) * (1ULL << 32));
+ const size_t dy_dv = std::llround((static_cast<f64>(src_height) / dst_height) * (1ULL << 32));
+ size_t src_y = 0;
+ for (u32 y = 0; y < dst_height; y++) {
+ size_t src_x = 0;
+ for (u32 x = 0; x < dst_width; x++) {
+ const size_t read_from = ((src_y * src_width + src_x) >> 32) * bpp;
+ const size_t write_to = (y * dst_width + x) * bpp;
+
+ std::memcpy(&output[write_to], &input[read_from], bpp);
+ src_x += dx_du;
+ }
+ src_y += dy_dv;
+ }
+}
+
+void NearestNeighborFast(std::span<const f32> input, std::span<f32> output, u32 src_width,
+ u32 src_height, u32 dst_width, u32 dst_height) {
+ const size_t dx_du = std::llround((static_cast<f64>(src_width) / dst_width) * (1ULL << 32));
+ const size_t dy_dv = std::llround((static_cast<f64>(src_height) / dst_height) * (1ULL << 32));
+ size_t src_y = 0;
+ for (u32 y = 0; y < dst_height; y++) {
+ size_t src_x = 0;
+ for (u32 x = 0; x < dst_width; x++) {
+ const size_t read_from = ((src_y * src_width + src_x) >> 32) * ir_components;
+ const size_t write_to = (y * dst_width + x) * ir_components;
+
+ std::memcpy(&output[write_to], &input[read_from], sizeof(f32) * ir_components);
+ src_x += dx_du;
+ }
+ src_y += dy_dv;
+ }
+}
+
+void Bilinear(std::span<const f32> input, std::span<f32> output, size_t src_width,
+ size_t src_height, size_t dst_width, size_t dst_height) {
+ const auto bilinear_sample = [](std::span<const f32> x0_y0, std::span<const f32> x1_y0,
+ std::span<const f32> x0_y1, std::span<const f32> x1_y1,
+ f32 weight_x, f32 weight_y) {
+ std::array<f32, ir_components> result{};
+ for (size_t i = 0; i < ir_components; i++) {
+ const f32 a = std::lerp(x0_y0[i], x1_y0[i], weight_x);
+ const f32 b = std::lerp(x0_y1[i], x1_y1[i], weight_x);
+ result[i] = std::lerp(a, b, weight_y);
+ }
+ return result;
+ };
+ const f32 dx_du =
+ dst_width > 1 ? static_cast<f32>(src_width - 1) / static_cast<f32>(dst_width - 1) : 0.f;
+ const f32 dy_dv =
+ dst_height > 1 ? static_cast<f32>(src_height - 1) / static_cast<f32>(dst_height - 1) : 0.f;
+ for (u32 y = 0; y < dst_height; y++) {
+ for (u32 x = 0; x < dst_width; x++) {
+ const f32 x_low = std::floor(static_cast<f32>(x) * dx_du);
+ const f32 y_low = std::floor(static_cast<f32>(y) * dy_dv);
+ const f32 x_high = std::ceil(static_cast<f32>(x) * dx_du);
+ const f32 y_high = std::ceil(static_cast<f32>(y) * dy_dv);
+ const f32 weight_x = (static_cast<f32>(x) * dx_du) - x_low;
+ const f32 weight_y = (static_cast<f32>(y) * dy_dv) - y_low;
+
+ const auto read_src = [&](f32 in_x, f32 in_y) {
+ const size_t read_from =
+ ((static_cast<size_t>(in_x) * src_width + static_cast<size_t>(in_y)) >> 32) *
+ ir_components;
+ return std::span<const f32>(&input[read_from], ir_components);
+ };
+
+ auto x0_y0 = read_src(x_low, y_low);
+ auto x1_y0 = read_src(x_high, y_low);
+ auto x0_y1 = read_src(x_low, y_high);
+ auto x1_y1 = read_src(x_high, y_high);
+
+ const auto result = bilinear_sample(x0_y0, x1_y0, x0_y1, x1_y1, weight_x, weight_y);
+
+ const size_t write_to = (y * dst_width + x) * ir_components;
+
+ std::memcpy(&output[write_to], &result, sizeof(f32) * ir_components);
+ }
+ }
+}
+
+} // namespace
+
+struct SoftwareBlitEngine::BlitEngineImpl {
+ std::vector<u8> tmp_buffer;
+ std::vector<u8> src_buffer;
+ std::vector<u8> dst_buffer;
+ std::vector<f32> intermediate_src;
+ std::vector<f32> intermediate_dst;
+ ConverterFactory converter_factory;
+};
+
+SoftwareBlitEngine::SoftwareBlitEngine(MemoryManager& memory_manager_)
+ : memory_manager{memory_manager_} {
+ impl = std::make_unique<BlitEngineImpl>();
+}
+
+SoftwareBlitEngine::~SoftwareBlitEngine() = default;
+
+bool SoftwareBlitEngine::Blit(Fermi2D::Surface& src, Fermi2D::Surface& dst,
+ Fermi2D::Config& config) {
+ const auto get_surface_size = [](Fermi2D::Surface& surface, u32 bytes_per_pixel) {
+ if (surface.linear == Fermi2D::MemoryLayout::BlockLinear) {
+ return CalculateSize(true, bytes_per_pixel, surface.width, surface.height,
+ surface.depth, surface.block_height, surface.block_depth);
+ }
+ return static_cast<size_t>(surface.pitch * surface.height);
+ };
+ const auto process_pitch_linear = [](bool unpack, std::span<const u8> input,
+ std::span<u8> output, u32 extent_x, u32 extent_y,
+ u32 pitch, u32 x0, u32 y0, size_t bpp) {
+ const size_t base_offset = x0 * bpp;
+ const size_t copy_size = extent_x * bpp;
+ for (u32 y = y0; y < extent_y; y++) {
+ const size_t first_offset = y * pitch + base_offset;
+ const size_t second_offset = y * extent_x * bpp;
+ u8* write_to = unpack ? &output[first_offset] : &output[second_offset];
+ const u8* read_from = unpack ? &input[second_offset] : &input[first_offset];
+ std::memcpy(write_to, read_from, copy_size);
+ }
+ };
+
+ const u32 src_extent_x = config.src_x1 - config.src_x0;
+ const u32 src_extent_y = config.src_y1 - config.src_y0;
+
+ const u32 dst_extent_x = config.dst_x1 - config.dst_x0;
+ const u32 dst_extent_y = config.dst_y1 - config.dst_y0;
+ const auto src_bytes_per_pixel = BytesPerBlock(PixelFormatFromRenderTargetFormat(src.format));
+ const auto dst_bytes_per_pixel = BytesPerBlock(PixelFormatFromRenderTargetFormat(dst.format));
+ const size_t src_size = get_surface_size(src, src_bytes_per_pixel);
+ impl->tmp_buffer.resize(src_size);
+ memory_manager.ReadBlock(src.Address(), impl->tmp_buffer.data(), src_size);
+
+ const size_t src_copy_size = src_extent_x * src_extent_y * src_bytes_per_pixel;
+
+ const size_t dst_copy_size = dst_extent_x * dst_extent_y * dst_bytes_per_pixel;
+
+ impl->src_buffer.resize(src_copy_size);
+
+ const bool no_passthrough =
+ src.format != dst.format || src_extent_x != dst_extent_x || src_extent_y != dst_extent_y;
+
+ const auto convertion_phase_same_format = [&]() {
+ NearestNeighbor(impl->src_buffer, impl->dst_buffer, src_extent_x, src_extent_y,
+ dst_extent_x, dst_extent_y, dst_bytes_per_pixel);
+ };
+
+ const auto convertion_phase_ir = [&]() {
+ auto* input_converter = impl->converter_factory.GetFormatConverter(src.format);
+ impl->intermediate_src.resize((src_copy_size / src_bytes_per_pixel) * ir_components);
+ impl->intermediate_dst.resize((dst_copy_size / dst_bytes_per_pixel) * ir_components);
+ input_converter->ConvertTo(impl->src_buffer, impl->intermediate_src);
+
+ if (config.filter != Fermi2D::Filter::Bilinear) {
+ NearestNeighborFast(impl->intermediate_src, impl->intermediate_dst, src_extent_x,
+ src_extent_y, dst_extent_x, dst_extent_y);
+ } else {
+ Bilinear(impl->intermediate_src, impl->intermediate_dst, src_extent_x, src_extent_y,
+ dst_extent_x, dst_extent_y);
+ }
+
+ auto* output_converter = impl->converter_factory.GetFormatConverter(dst.format);
+ output_converter->ConvertFrom(impl->intermediate_dst, impl->dst_buffer);
+ };
+
+ // Do actuall Blit
+
+ impl->dst_buffer.resize(dst_copy_size);
+ if (src.linear == Fermi2D::MemoryLayout::BlockLinear) {
+ UnswizzleSubrect(impl->src_buffer, impl->tmp_buffer, src_bytes_per_pixel, src.width,
+ src.height, src.depth, config.src_x0, config.src_y0, src_extent_x,
+ src_extent_y, src.block_height, src.block_depth,
+ src_extent_x * src_bytes_per_pixel);
+ } else {
+ process_pitch_linear(false, impl->tmp_buffer, impl->src_buffer, src_extent_x, src_extent_y,
+ src.pitch, config.src_x0, config.src_y0, src_bytes_per_pixel);
+ }
+
+ // Conversion Phase
+ if (no_passthrough) {
+ if (src.format != dst.format || config.filter == Fermi2D::Filter::Bilinear) {
+ convertion_phase_ir();
+ } else {
+ convertion_phase_same_format();
+ }
+ } else {
+ impl->dst_buffer.swap(impl->src_buffer);
+ }
+
+ const size_t dst_size = get_surface_size(dst, dst_bytes_per_pixel);
+ impl->tmp_buffer.resize(dst_size);
+ memory_manager.ReadBlock(dst.Address(), impl->tmp_buffer.data(), dst_size);
+
+ if (dst.linear == Fermi2D::MemoryLayout::BlockLinear) {
+ SwizzleSubrect(impl->tmp_buffer, impl->dst_buffer, dst_bytes_per_pixel, dst.width,
+ dst.height, dst.depth, config.dst_x0, config.dst_y0, dst_extent_x,
+ dst_extent_y, dst.block_height, dst.block_depth,
+ dst_extent_x * dst_bytes_per_pixel);
+ } else {
+ process_pitch_linear(true, impl->dst_buffer, impl->tmp_buffer, dst_extent_x, dst_extent_y,
+ dst.pitch, config.dst_x0, config.dst_y0,
+ static_cast<size_t>(dst_bytes_per_pixel));
+ }
+ memory_manager.WriteBlock(dst.Address(), impl->tmp_buffer.data(), dst_size);
+ return true;
+}
+
+} // namespace Tegra::Engines::Blitter
diff --git a/src/video_core/engines/sw_blitter/blitter.h b/src/video_core/engines/sw_blitter/blitter.h
new file mode 100644
index 000000000..85b55c836
--- /dev/null
+++ b/src/video_core/engines/sw_blitter/blitter.h
@@ -0,0 +1,27 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+#pragma once
+
+#include "video_core/engines/fermi_2d.h"
+
+namespace Tegra {
+class MemoryManager;
+}
+
+namespace Tegra::Engines::Blitter {
+
+class SoftwareBlitEngine {
+public:
+ explicit SoftwareBlitEngine(MemoryManager& memory_manager_);
+ ~SoftwareBlitEngine();
+
+ bool Blit(Fermi2D::Surface& src, Fermi2D::Surface& dst, Fermi2D::Config& copy_config);
+
+private:
+ MemoryManager& memory_manager;
+ struct BlitEngineImpl;
+ std::unique_ptr<BlitEngineImpl> impl;
+};
+
+} // namespace Tegra::Engines::Blitter
diff --git a/src/video_core/engines/sw_blitter/converter.cpp b/src/video_core/engines/sw_blitter/converter.cpp
new file mode 100644
index 000000000..2419b5632
--- /dev/null
+++ b/src/video_core/engines/sw_blitter/converter.cpp
@@ -0,0 +1,1234 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+#include <array>
+#include <cmath>
+#include <span>
+#include <unordered_map>
+
+#include "common/assert.h"
+#include "common/bit_cast.h"
+#include "video_core/engines/sw_blitter/converter.h"
+#include "video_core/surface.h"
+#include "video_core/textures/decoders.h"
+
+#ifdef _MSC_VER
+#define FORCE_INLINE __forceinline
+#else
+#define FORCE_INLINE inline __attribute__((always_inline))
+#endif
+
+namespace Tegra::Engines::Blitter {
+
+enum class Swizzle : size_t {
+ R = 0,
+ G = 1,
+ B = 2,
+ A = 3,
+ None,
+};
+
+enum class ComponentType : u32 {
+ SNORM = 1,
+ UNORM = 2,
+ SINT = 3,
+ UINT = 4,
+ SNORM_FORCE_FP16 = 5,
+ UNORM_FORCE_FP16 = 6,
+ FLOAT = 7,
+ SRGB = 8,
+};
+
+namespace {
+
+/*
+ * Note: Use generate_converters.py to generate the structs and searches for new render target
+ * formats and copy paste them to this file in order to update. just call "python
+ * generate_converters.py" and get the code from the output. modify the file to add new formats.
+ */
+
+constexpr std::array<f32, 256> SRGB_TO_RGB_LUT = {
+ 0.000000e+00f, 3.035270e-04f, 6.070540e-04f, 9.105810e-04f, 1.214108e-03f, 1.517635e-03f,
+ 1.821162e-03f, 2.124689e-03f, 2.428216e-03f, 2.731743e-03f, 3.035270e-03f, 3.346536e-03f,
+ 3.676507e-03f, 4.024717e-03f, 4.391442e-03f, 4.776953e-03f, 5.181517e-03f, 5.605392e-03f,
+ 6.048833e-03f, 6.512091e-03f, 6.995410e-03f, 7.499032e-03f, 8.023193e-03f, 8.568126e-03f,
+ 9.134059e-03f, 9.721218e-03f, 1.032982e-02f, 1.096009e-02f, 1.161224e-02f, 1.228649e-02f,
+ 1.298303e-02f, 1.370208e-02f, 1.444384e-02f, 1.520851e-02f, 1.599629e-02f, 1.680738e-02f,
+ 1.764195e-02f, 1.850022e-02f, 1.938236e-02f, 2.028856e-02f, 2.121901e-02f, 2.217389e-02f,
+ 2.315337e-02f, 2.415763e-02f, 2.518686e-02f, 2.624122e-02f, 2.732089e-02f, 2.842604e-02f,
+ 2.955684e-02f, 3.071344e-02f, 3.189603e-02f, 3.310477e-02f, 3.433981e-02f, 3.560131e-02f,
+ 3.688945e-02f, 3.820437e-02f, 3.954624e-02f, 4.091520e-02f, 4.231141e-02f, 4.373503e-02f,
+ 4.518620e-02f, 4.666509e-02f, 4.817183e-02f, 4.970657e-02f, 5.126946e-02f, 5.286065e-02f,
+ 5.448028e-02f, 5.612849e-02f, 5.780543e-02f, 5.951124e-02f, 6.124605e-02f, 6.301001e-02f,
+ 6.480327e-02f, 6.662594e-02f, 6.847817e-02f, 7.036009e-02f, 7.227185e-02f, 7.421357e-02f,
+ 7.618538e-02f, 7.818742e-02f, 8.021982e-02f, 8.228271e-02f, 8.437621e-02f, 8.650046e-02f,
+ 8.865558e-02f, 9.084171e-02f, 9.305897e-02f, 9.530747e-02f, 9.758735e-02f, 9.989873e-02f,
+ 1.022417e-01f, 1.046165e-01f, 1.070231e-01f, 1.094617e-01f, 1.119324e-01f, 1.144354e-01f,
+ 1.169707e-01f, 1.195384e-01f, 1.221388e-01f, 1.247718e-01f, 1.274377e-01f, 1.301365e-01f,
+ 1.328683e-01f, 1.356333e-01f, 1.384316e-01f, 1.412633e-01f, 1.441285e-01f, 1.470273e-01f,
+ 1.499598e-01f, 1.529261e-01f, 1.559265e-01f, 1.589608e-01f, 1.620294e-01f, 1.651322e-01f,
+ 1.682694e-01f, 1.714411e-01f, 1.746474e-01f, 1.778884e-01f, 1.811642e-01f, 1.844750e-01f,
+ 1.878208e-01f, 1.912017e-01f, 1.946178e-01f, 1.980693e-01f, 2.015563e-01f, 2.050787e-01f,
+ 2.086369e-01f, 2.122308e-01f, 2.158605e-01f, 2.195262e-01f, 2.232280e-01f, 2.269659e-01f,
+ 2.307401e-01f, 2.345506e-01f, 2.383976e-01f, 2.422811e-01f, 2.462013e-01f, 2.501583e-01f,
+ 2.541521e-01f, 2.581829e-01f, 2.622507e-01f, 2.663556e-01f, 2.704978e-01f, 2.746773e-01f,
+ 2.788943e-01f, 2.831487e-01f, 2.874408e-01f, 2.917706e-01f, 2.961383e-01f, 3.005438e-01f,
+ 3.049873e-01f, 3.094689e-01f, 3.139887e-01f, 3.185468e-01f, 3.231432e-01f, 3.277781e-01f,
+ 3.324515e-01f, 3.371636e-01f, 3.419144e-01f, 3.467041e-01f, 3.515326e-01f, 3.564001e-01f,
+ 3.613068e-01f, 3.662526e-01f, 3.712377e-01f, 3.762621e-01f, 3.813260e-01f, 3.864294e-01f,
+ 3.915725e-01f, 3.967552e-01f, 4.019778e-01f, 4.072402e-01f, 4.125426e-01f, 4.178851e-01f,
+ 4.232677e-01f, 4.286905e-01f, 4.341536e-01f, 4.396572e-01f, 4.452012e-01f, 4.507858e-01f,
+ 4.564110e-01f, 4.620770e-01f, 4.677838e-01f, 4.735315e-01f, 4.793202e-01f, 4.851499e-01f,
+ 4.910209e-01f, 4.969330e-01f, 5.028865e-01f, 5.088813e-01f, 5.149177e-01f, 5.209956e-01f,
+ 5.271151e-01f, 5.332764e-01f, 5.394795e-01f, 5.457245e-01f, 5.520114e-01f, 5.583404e-01f,
+ 5.647115e-01f, 5.711249e-01f, 5.775805e-01f, 5.840784e-01f, 5.906188e-01f, 5.972018e-01f,
+ 6.038274e-01f, 6.104956e-01f, 6.172066e-01f, 6.239604e-01f, 6.307572e-01f, 6.375968e-01f,
+ 6.444797e-01f, 6.514056e-01f, 6.583748e-01f, 6.653873e-01f, 6.724432e-01f, 6.795425e-01f,
+ 6.866853e-01f, 6.938717e-01f, 7.011019e-01f, 7.083758e-01f, 7.156935e-01f, 7.230551e-01f,
+ 7.304608e-01f, 7.379104e-01f, 7.454042e-01f, 7.529422e-01f, 7.605245e-01f, 7.681512e-01f,
+ 7.758222e-01f, 7.835378e-01f, 7.912979e-01f, 7.991027e-01f, 8.069522e-01f, 8.148466e-01f,
+ 8.227857e-01f, 8.307699e-01f, 8.387990e-01f, 8.468732e-01f, 8.549926e-01f, 8.631572e-01f,
+ 8.713671e-01f, 8.796224e-01f, 8.879231e-01f, 8.962694e-01f, 9.046612e-01f, 9.130986e-01f,
+ 9.215819e-01f, 9.301109e-01f, 9.386857e-01f, 9.473065e-01f, 9.559733e-01f, 9.646863e-01f,
+ 9.734453e-01f, 9.822506e-01f, 9.911021e-01f, 1.000000e+00f};
+
+constexpr std::array<f32, 256> RGB_TO_SRGB_LUT = {
+ 0.000000e+00f, 4.984009e-02f, 8.494473e-02f, 1.107021e-01f, 1.318038e-01f, 1.500052e-01f,
+ 1.661857e-01f, 1.808585e-01f, 1.943532e-01f, 2.068957e-01f, 2.186491e-01f, 2.297351e-01f,
+ 2.402475e-01f, 2.502604e-01f, 2.598334e-01f, 2.690152e-01f, 2.778465e-01f, 2.863614e-01f,
+ 2.945889e-01f, 3.025538e-01f, 3.102778e-01f, 3.177796e-01f, 3.250757e-01f, 3.321809e-01f,
+ 3.391081e-01f, 3.458689e-01f, 3.524737e-01f, 3.589320e-01f, 3.652521e-01f, 3.714419e-01f,
+ 3.775084e-01f, 3.834581e-01f, 3.892968e-01f, 3.950301e-01f, 4.006628e-01f, 4.061998e-01f,
+ 4.116451e-01f, 4.170030e-01f, 4.222770e-01f, 4.274707e-01f, 4.325873e-01f, 4.376298e-01f,
+ 4.426010e-01f, 4.475037e-01f, 4.523403e-01f, 4.571131e-01f, 4.618246e-01f, 4.664766e-01f,
+ 4.710712e-01f, 4.756104e-01f, 4.800958e-01f, 4.845292e-01f, 4.889122e-01f, 4.932462e-01f,
+ 4.975329e-01f, 5.017734e-01f, 5.059693e-01f, 5.101216e-01f, 5.142317e-01f, 5.183006e-01f,
+ 5.223295e-01f, 5.263194e-01f, 5.302714e-01f, 5.341862e-01f, 5.380651e-01f, 5.419087e-01f,
+ 5.457181e-01f, 5.494938e-01f, 5.532369e-01f, 5.569480e-01f, 5.606278e-01f, 5.642771e-01f,
+ 5.678965e-01f, 5.714868e-01f, 5.750484e-01f, 5.785821e-01f, 5.820884e-01f, 5.855680e-01f,
+ 5.890211e-01f, 5.924487e-01f, 5.958509e-01f, 5.992285e-01f, 6.025819e-01f, 6.059114e-01f,
+ 6.092176e-01f, 6.125010e-01f, 6.157619e-01f, 6.190008e-01f, 6.222180e-01f, 6.254140e-01f,
+ 6.285890e-01f, 6.317436e-01f, 6.348780e-01f, 6.379926e-01f, 6.410878e-01f, 6.441637e-01f,
+ 6.472208e-01f, 6.502595e-01f, 6.532799e-01f, 6.562824e-01f, 6.592672e-01f, 6.622347e-01f,
+ 6.651851e-01f, 6.681187e-01f, 6.710356e-01f, 6.739363e-01f, 6.768209e-01f, 6.796897e-01f,
+ 6.825429e-01f, 6.853807e-01f, 6.882034e-01f, 6.910111e-01f, 6.938041e-01f, 6.965826e-01f,
+ 6.993468e-01f, 7.020969e-01f, 7.048331e-01f, 7.075556e-01f, 7.102645e-01f, 7.129600e-01f,
+ 7.156424e-01f, 7.183118e-01f, 7.209683e-01f, 7.236121e-01f, 7.262435e-01f, 7.288625e-01f,
+ 7.314693e-01f, 7.340640e-01f, 7.366470e-01f, 7.392181e-01f, 7.417776e-01f, 7.443256e-01f,
+ 7.468624e-01f, 7.493880e-01f, 7.519025e-01f, 7.544061e-01f, 7.568989e-01f, 7.593810e-01f,
+ 7.618526e-01f, 7.643137e-01f, 7.667645e-01f, 7.692052e-01f, 7.716358e-01f, 7.740564e-01f,
+ 7.764671e-01f, 7.788681e-01f, 7.812595e-01f, 7.836413e-01f, 7.860138e-01f, 7.883768e-01f,
+ 7.907307e-01f, 7.930754e-01f, 7.954110e-01f, 7.977377e-01f, 8.000556e-01f, 8.023647e-01f,
+ 8.046651e-01f, 8.069569e-01f, 8.092403e-01f, 8.115152e-01f, 8.137818e-01f, 8.160402e-01f,
+ 8.182903e-01f, 8.205324e-01f, 8.227665e-01f, 8.249926e-01f, 8.272109e-01f, 8.294214e-01f,
+ 8.316242e-01f, 8.338194e-01f, 8.360070e-01f, 8.381871e-01f, 8.403597e-01f, 8.425251e-01f,
+ 8.446831e-01f, 8.468339e-01f, 8.489776e-01f, 8.511142e-01f, 8.532437e-01f, 8.553662e-01f,
+ 8.574819e-01f, 8.595907e-01f, 8.616927e-01f, 8.637881e-01f, 8.658767e-01f, 8.679587e-01f,
+ 8.700342e-01f, 8.721032e-01f, 8.741657e-01f, 8.762218e-01f, 8.782716e-01f, 8.803151e-01f,
+ 8.823524e-01f, 8.843835e-01f, 8.864085e-01f, 8.884274e-01f, 8.904402e-01f, 8.924471e-01f,
+ 8.944480e-01f, 8.964431e-01f, 8.984324e-01f, 9.004158e-01f, 9.023935e-01f, 9.043654e-01f,
+ 9.063318e-01f, 9.082925e-01f, 9.102476e-01f, 9.121972e-01f, 9.141413e-01f, 9.160800e-01f,
+ 9.180133e-01f, 9.199412e-01f, 9.218637e-01f, 9.237810e-01f, 9.256931e-01f, 9.276000e-01f,
+ 9.295017e-01f, 9.313982e-01f, 9.332896e-01f, 9.351761e-01f, 9.370575e-01f, 9.389339e-01f,
+ 9.408054e-01f, 9.426719e-01f, 9.445336e-01f, 9.463905e-01f, 9.482424e-01f, 9.500897e-01f,
+ 9.519322e-01f, 9.537700e-01f, 9.556032e-01f, 9.574316e-01f, 9.592555e-01f, 9.610748e-01f,
+ 9.628896e-01f, 9.646998e-01f, 9.665055e-01f, 9.683068e-01f, 9.701037e-01f, 9.718961e-01f,
+ 9.736842e-01f, 9.754679e-01f, 9.772474e-01f, 9.790225e-01f, 9.807934e-01f, 9.825601e-01f,
+ 9.843225e-01f, 9.860808e-01f, 9.878350e-01f, 9.895850e-01f, 9.913309e-01f, 9.930727e-01f,
+ 9.948106e-01f, 9.965444e-01f, 9.982741e-01f, 1.000000e+00f};
+
+} // namespace
+
+struct R32G32B32A32_FLOATTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::FLOAT, ComponentType::FLOAT, ComponentType::FLOAT, ComponentType::FLOAT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32, 32, 32, 32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::A};
+};
+
+struct R32G32B32A32_SINTTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SINT, ComponentType::SINT, ComponentType::SINT, ComponentType::SINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32, 32, 32, 32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::A};
+};
+
+struct R32G32B32A32_UINTTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT, ComponentType::UINT, ComponentType::UINT, ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32, 32, 32, 32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::A};
+};
+
+struct R32G32B32X32_FLOATTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::FLOAT, ComponentType::FLOAT, ComponentType::FLOAT, ComponentType::FLOAT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32, 32, 32, 32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::None};
+};
+
+struct R32G32B32X32_SINTTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SINT, ComponentType::SINT, ComponentType::SINT, ComponentType::SINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32, 32, 32, 32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::None};
+};
+
+struct R32G32B32X32_UINTTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT, ComponentType::UINT, ComponentType::UINT, ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32, 32, 32, 32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::None};
+};
+
+struct R16G16B16A16_UNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16, 16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::A};
+};
+
+struct R16G16B16A16_SNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SNORM, ComponentType::SNORM, ComponentType::SNORM, ComponentType::SNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16, 16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::A};
+};
+
+struct R16G16B16A16_SINTTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SINT, ComponentType::SINT, ComponentType::SINT, ComponentType::SINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16, 16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::A};
+};
+
+struct R16G16B16A16_UINTTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT, ComponentType::UINT, ComponentType::UINT, ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16, 16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::A};
+};
+
+struct R16G16B16A16_FLOATTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::FLOAT, ComponentType::FLOAT, ComponentType::FLOAT, ComponentType::FLOAT};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16, 16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::A};
+};
+
+struct R32G32_FLOATTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::FLOAT, ComponentType::FLOAT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32, 32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R32G32_SINTTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SINT, ComponentType::SINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32, 32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R32G32_UINTTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT, ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32, 32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R16G16B16X16_FLOATTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::FLOAT, ComponentType::FLOAT, ComponentType::FLOAT, ComponentType::FLOAT};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16, 16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B, Swizzle::None};
+};
+
+struct A8R8G8B8_UNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::R, Swizzle::G, Swizzle::B};
+};
+
+struct A8R8G8B8_SRGBTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SRGB, ComponentType::SRGB, ComponentType::SRGB, ComponentType::SRGB};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::R, Swizzle::G, Swizzle::B};
+};
+
+struct A2B10G10R10_UNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {2, 10, 10, 10};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::B, Swizzle::G, Swizzle::R};
+};
+
+struct A2B10G10R10_UINTTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT, ComponentType::UINT, ComponentType::UINT, ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {2, 10, 10, 10};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::B, Swizzle::G, Swizzle::R};
+};
+
+struct A2R10G10B10_UNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {2, 10, 10, 10};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::R, Swizzle::G, Swizzle::B};
+};
+
+struct A8B8G8R8_UNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::B, Swizzle::G, Swizzle::R};
+};
+
+struct A8B8G8R8_SRGBTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SRGB, ComponentType::SRGB, ComponentType::SRGB, ComponentType::SRGB};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::B, Swizzle::G, Swizzle::R};
+};
+
+struct A8B8G8R8_SNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SNORM, ComponentType::SNORM, ComponentType::SNORM, ComponentType::SNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::B, Swizzle::G, Swizzle::R};
+};
+
+struct A8B8G8R8_SINTTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SINT, ComponentType::SINT, ComponentType::SINT, ComponentType::SINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::B, Swizzle::G, Swizzle::R};
+};
+
+struct A8B8G8R8_UINTTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT, ComponentType::UINT, ComponentType::UINT, ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::B, Swizzle::G, Swizzle::R};
+};
+
+struct R16G16_UNORMTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R16G16_SNORMTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SNORM, ComponentType::SNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R16G16_SINTTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SINT, ComponentType::SINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R16G16_UINTTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT, ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R16G16_FLOATTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::FLOAT, ComponentType::FLOAT};
+ static constexpr std::array<size_t, num_components> component_sizes = {16, 16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct B10G11R11_FLOATTraits {
+ static constexpr size_t num_components = 3;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::FLOAT, ComponentType::FLOAT, ComponentType::FLOAT};
+ static constexpr std::array<size_t, num_components> component_sizes = {10, 11, 11};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::B, Swizzle::G, Swizzle::R};
+};
+
+struct R32_SINTTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct R32_UINTTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct R32_FLOATTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::FLOAT};
+ static constexpr std::array<size_t, num_components> component_sizes = {32};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct X8R8G8B8_UNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::None, Swizzle::R, Swizzle::G, Swizzle::B};
+};
+
+struct X8R8G8B8_SRGBTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SRGB, ComponentType::SRGB, ComponentType::SRGB, ComponentType::SRGB};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::None, Swizzle::R, Swizzle::G, Swizzle::B};
+};
+
+struct R5G6B5_UNORMTraits {
+ static constexpr size_t num_components = 3;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {5, 6, 5};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::R, Swizzle::G, Swizzle::B};
+};
+
+struct A1R5G5B5_UNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {1, 5, 5, 5};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::A, Swizzle::R, Swizzle::G, Swizzle::B};
+};
+
+struct R8G8_UNORMTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R8G8_SNORMTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SNORM, ComponentType::SNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R8G8_SINTTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SINT, ComponentType::SINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R8G8_UINTTraits {
+ static constexpr size_t num_components = 2;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT, ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R,
+ Swizzle::G};
+};
+
+struct R16_UNORMTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct R16_SNORMTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct R16_SINTTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct R16_UINTTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct R16_FLOATTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::FLOAT};
+ static constexpr std::array<size_t, num_components> component_sizes = {16};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct R8_UNORMTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct R8_SNORMTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct R8_SINTTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct R8_UINTTraits {
+ static constexpr size_t num_components = 1;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UINT};
+ static constexpr std::array<size_t, num_components> component_sizes = {8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {Swizzle::R};
+};
+
+struct X1R5G5B5_UNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {1, 5, 5, 5};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::None, Swizzle::R, Swizzle::G, Swizzle::B};
+};
+
+struct X8B8G8R8_UNORMTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM, ComponentType::UNORM};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::None, Swizzle::B, Swizzle::G, Swizzle::R};
+};
+
+struct X8B8G8R8_SRGBTraits {
+ static constexpr size_t num_components = 4;
+ static constexpr std::array<ComponentType, num_components> component_types = {
+ ComponentType::SRGB, ComponentType::SRGB, ComponentType::SRGB, ComponentType::SRGB};
+ static constexpr std::array<size_t, num_components> component_sizes = {8, 8, 8, 8};
+ static constexpr std::array<Swizzle, num_components> component_swizzle = {
+ Swizzle::None, Swizzle::B, Swizzle::G, Swizzle::R};
+};
+
+template <class ConverterTraits>
+class ConverterImpl : public Converter {
+private:
+ static constexpr size_t num_components = ConverterTraits::num_components;
+ static constexpr std::array<ComponentType, num_components> component_types =
+ ConverterTraits::component_types;
+ static constexpr std::array<size_t, num_components> component_sizes =
+ ConverterTraits::component_sizes;
+ static constexpr std::array<Swizzle, num_components> component_swizzle =
+ ConverterTraits::component_swizzle;
+
+ static constexpr size_t CalculateByteSize() {
+ size_t size = 0;
+ for (const size_t component_size : component_sizes) {
+ size += component_size;
+ }
+ const size_t power = (sizeof(size_t) * 8) - std::countl_zero(size) - 1ULL;
+ const size_t base_size = 1ULL << power;
+ const size_t mask = base_size - 1ULL;
+ return ((size & mask) != 0 ? base_size << 1ULL : base_size) / 8;
+ }
+
+ static constexpr size_t total_bytes_per_pixel = CalculateByteSize();
+ static constexpr size_t total_words_per_pixel =
+ (total_bytes_per_pixel + sizeof(u32) - 1U) / sizeof(u32);
+ static constexpr size_t components_per_ir_rep = 4;
+
+ template <bool get_offsets>
+ static constexpr std::array<size_t, num_components> GetBoundWordsOffsets() {
+ std::array<size_t, num_components> result;
+ result.fill(0);
+ constexpr size_t total_bits_per_word = sizeof(u32) * 8;
+ size_t accumulated_size = 0;
+ size_t count = 0;
+ for (size_t i = 0; i < num_components; i++) {
+ if constexpr (get_offsets) {
+ result[i] = accumulated_size;
+ } else {
+ result[i] = count;
+ }
+ accumulated_size += component_sizes[i];
+ if (accumulated_size > total_bits_per_word) {
+ if constexpr (get_offsets) {
+ result[i] = 0;
+ } else {
+ result[i]++;
+ }
+ count++;
+ accumulated_size = component_sizes[i];
+ }
+ }
+ return result;
+ }
+
+ static constexpr std::array<size_t, num_components> bound_words = GetBoundWordsOffsets<false>();
+ static constexpr std::array<size_t, num_components> bound_offsets =
+ GetBoundWordsOffsets<true>();
+
+ static constexpr std::array<u32, num_components> GetComponentsMask() {
+ std::array<u32, num_components> result;
+ for (size_t i = 0; i < num_components; i++) {
+ result[i] = (((u32)~0) >> (8 * sizeof(u32) - component_sizes[i])) << bound_offsets[i];
+ }
+ return result;
+ }
+
+ static constexpr std::array<u32, num_components> component_mask = GetComponentsMask();
+
+ // We are forcing inline so the compiler can SIMD the conversations, since it may do 4 function
+ // calls, it may fail to detect the benefit of inlining.
+ template <size_t which_component>
+ FORCE_INLINE void ConvertToComponent(u32 which_word, f32& out_component) {
+ const u32 value = (which_word >> bound_offsets[which_component]) &
+ static_cast<u32>((1ULL << component_sizes[which_component]) - 1ULL);
+ const auto sign_extend = [](u32 base_value, size_t bits) {
+ const size_t shift_amount = sizeof(u32) * 8 - bits;
+ s32 shifted_value = static_cast<s32>(base_value << shift_amount);
+ return shifted_value >> shift_amount;
+ };
+ const auto force_to_fp16 = [](f32 base_value) {
+ u32 tmp = Common::BitCast<u32>(base_value);
+ constexpr size_t fp32_mantissa_bits = 23;
+ constexpr size_t fp16_mantissa_bits = 10;
+ constexpr size_t mantissa_mask =
+ ~((1ULL << (fp32_mantissa_bits - fp16_mantissa_bits)) - 1ULL);
+ tmp = tmp & static_cast<u32>(mantissa_mask);
+ // TODO: force the exponent within the range of half float. Not needed in UNORM / SNORM
+ return Common::BitCast<f32>(tmp);
+ };
+ const auto from_fp_n = [&sign_extend](u32 base_value, size_t bits, size_t mantissa) {
+ constexpr size_t fp32_mantissa_bits = 23;
+ size_t shift_towards = fp32_mantissa_bits - mantissa;
+ const u32 new_value =
+ static_cast<u32>(sign_extend(base_value, bits) << shift_towards) & (~(1U << 31));
+ return Common::BitCast<f32>(new_value);
+ };
+ const auto calculate_snorm = [&]() {
+ return static_cast<f32>(
+ static_cast<f32>(sign_extend(value, component_sizes[which_component])) /
+ static_cast<f32>((1ULL << (component_sizes[which_component] - 1ULL)) - 1ULL));
+ };
+ const auto calculate_unorm = [&]() {
+ return static_cast<f32>(
+ static_cast<f32>(value) /
+ static_cast<f32>((1ULL << (component_sizes[which_component])) - 1ULL));
+ };
+ if constexpr (component_types[which_component] == ComponentType::SNORM) {
+ out_component = calculate_snorm();
+ } else if constexpr (component_types[which_component] == ComponentType::UNORM) {
+ out_component = calculate_unorm();
+ } else if constexpr (component_types[which_component] == ComponentType::SINT) {
+ out_component = static_cast<f32>(
+ static_cast<s32>(sign_extend(value, component_sizes[which_component])));
+ } else if constexpr (component_types[which_component] == ComponentType::UINT) {
+ out_component = static_cast<f32>(
+ static_cast<s32>(sign_extend(value, component_sizes[which_component])));
+ } else if constexpr (component_types[which_component] == ComponentType::SNORM_FORCE_FP16) {
+ out_component = calculate_snorm();
+ out_component = force_to_fp16(out_component);
+ } else if constexpr (component_types[which_component] == ComponentType::UNORM_FORCE_FP16) {
+ out_component = calculate_unorm();
+ out_component = force_to_fp16(out_component);
+ } else if constexpr (component_types[which_component] == ComponentType::FLOAT) {
+ if constexpr (component_sizes[which_component] == 32) {
+ out_component = Common::BitCast<f32>(value);
+ } else if constexpr (component_sizes[which_component] == 16) {
+ static constexpr u32 sign_mask = 0x8000;
+ static constexpr u32 mantissa_mask = 0x8000;
+ out_component = Common::BitCast<f32>(((value & sign_mask) << 16) |
+ (((value & 0x7c00) + 0x1C000) << 13) |
+ ((value & mantissa_mask) << 13));
+ } else {
+ out_component = from_fp_n(value, component_sizes[which_component],
+ component_sizes[which_component] - 5);
+ }
+ } else if constexpr (component_types[which_component] == ComponentType::SRGB) {
+ if constexpr (component_swizzle[which_component] == Swizzle::A) {
+ out_component = calculate_unorm();
+ } else if constexpr (component_sizes[which_component] == 8) {
+ out_component = SRGB_TO_RGB_LUT[value];
+ } else {
+ out_component = calculate_unorm();
+ UNIMPLEMENTED_MSG("SRGB Conversion with component sizes of {} is unimplemented",
+ component_sizes[which_component]);
+ }
+ }
+ }
+
+ // We are forcing inline so the compiler can SIMD the conversations, since it may do 4 function
+ // calls, it may fail to detect the benefit of inlining.
+ template <size_t which_component>
+ FORCE_INLINE void ConvertFromComponent(u32& which_word, f32 in_component) {
+ const auto insert_to_word = [&]<typename T>(T new_word) {
+ which_word |= (static_cast<u32>(new_word) << bound_offsets[which_component]) &
+ component_mask[which_component];
+ };
+ const auto to_fp_n = [](f32 base_value, size_t bits, size_t mantissa) {
+ constexpr size_t fp32_mantissa_bits = 23;
+ u32 tmp_value = Common::BitCast<u32>(std::max(base_value, 0.0f));
+ size_t shift_towards = fp32_mantissa_bits - mantissa;
+ return tmp_value >> shift_towards;
+ };
+ const auto calculate_unorm = [&]() {
+ return static_cast<u32>(
+ static_cast<f32>(in_component) *
+ static_cast<f32>((1ULL << (component_sizes[which_component])) - 1ULL));
+ };
+ if constexpr (component_types[which_component] == ComponentType::SNORM ||
+ component_types[which_component] == ComponentType::SNORM_FORCE_FP16) {
+ s32 tmp_word = static_cast<s32>(
+ static_cast<f32>(in_component) *
+ static_cast<f32>((1ULL << (component_sizes[which_component] - 1ULL)) - 1ULL));
+ insert_to_word(tmp_word);
+
+ } else if constexpr (component_types[which_component] == ComponentType::UNORM ||
+ component_types[which_component] == ComponentType::UNORM_FORCE_FP16) {
+ u32 tmp_word = calculate_unorm();
+ insert_to_word(tmp_word);
+ } else if constexpr (component_types[which_component] == ComponentType::SINT) {
+ s32 tmp_word = static_cast<s32>(in_component);
+ insert_to_word(tmp_word);
+ } else if constexpr (component_types[which_component] == ComponentType::UINT) {
+ u32 tmp_word = static_cast<u32>(in_component);
+ insert_to_word(tmp_word);
+ } else if constexpr (component_types[which_component] == ComponentType::FLOAT) {
+ if constexpr (component_sizes[which_component] == 32) {
+ u32 tmp_word = Common::BitCast<u32>(in_component);
+ insert_to_word(tmp_word);
+ } else if constexpr (component_sizes[which_component] == 16) {
+ static constexpr u32 sign_mask = 0x8000;
+ static constexpr u32 mantissa_mask = 0x03ff;
+ static constexpr u32 exponent_mask = 0x7c00;
+ const u32 tmp_word = Common::BitCast<u32>(in_component);
+ const u32 half = ((tmp_word >> 16) & sign_mask) |
+ ((((tmp_word & 0x7f800000) - 0x38000000) >> 13) & exponent_mask) |
+ ((tmp_word >> 13) & mantissa_mask);
+ insert_to_word(half);
+ } else {
+ insert_to_word(to_fp_n(in_component, component_sizes[which_component],
+ component_sizes[which_component] - 5));
+ }
+ } else if constexpr (component_types[which_component] == ComponentType::SRGB) {
+ if constexpr (component_swizzle[which_component] != Swizzle::A) {
+ if constexpr (component_sizes[which_component] == 8) {
+ const u32 index = calculate_unorm();
+ in_component = RGB_TO_SRGB_LUT[index];
+ } else {
+ UNIMPLEMENTED_MSG("SRGB Conversion with component sizes of {} is unimplemented",
+ component_sizes[which_component]);
+ }
+ }
+ const u32 tmp_word = calculate_unorm();
+ insert_to_word(tmp_word);
+ }
+ }
+
+public:
+ void ConvertTo(std::span<const u8> input, std::span<f32> output) override {
+ const size_t num_pixels = output.size() / components_per_ir_rep;
+ for (size_t pixel = 0; pixel < num_pixels; pixel++) {
+ std::array<u32, total_words_per_pixel> words{};
+
+ std::memcpy(words.data(), &input[pixel * total_bytes_per_pixel], total_bytes_per_pixel);
+ std::span<f32> new_components(&output[pixel * components_per_ir_rep],
+ components_per_ir_rep);
+ if constexpr (component_swizzle[0] != Swizzle::None) {
+ ConvertToComponent<0>(words[bound_words[0]],
+ new_components[static_cast<size_t>(component_swizzle[0])]);
+ } else {
+ new_components[0] = 0.0f;
+ }
+ if constexpr (num_components >= 2) {
+ if constexpr (component_swizzle[1] != Swizzle::None) {
+ ConvertToComponent<1>(
+ words[bound_words[1]],
+ new_components[static_cast<size_t>(component_swizzle[1])]);
+ } else {
+ new_components[1] = 0.0f;
+ }
+ } else {
+ new_components[1] = 0.0f;
+ }
+ if constexpr (num_components >= 3) {
+ if constexpr (component_swizzle[2] != Swizzle::None) {
+ ConvertToComponent<2>(
+ words[bound_words[2]],
+ new_components[static_cast<size_t>(component_swizzle[2])]);
+ } else {
+ new_components[2] = 0.0f;
+ }
+ } else {
+ new_components[2] = 0.0f;
+ }
+ if constexpr (num_components >= 4) {
+ if constexpr (component_swizzle[3] != Swizzle::None) {
+ ConvertToComponent<3>(
+ words[bound_words[3]],
+ new_components[static_cast<size_t>(component_swizzle[3])]);
+ } else {
+ new_components[3] = 0.0f;
+ }
+ } else {
+ new_components[3] = 0.0f;
+ }
+ }
+ }
+
+ void ConvertFrom(std::span<const f32> input, std::span<u8> output) override {
+ const size_t num_pixels = output.size() / total_bytes_per_pixel;
+ for (size_t pixel = 0; pixel < num_pixels; pixel++) {
+ std::span<const f32> old_components(&input[pixel * components_per_ir_rep],
+ components_per_ir_rep);
+ std::array<u32, total_words_per_pixel> words{};
+ if constexpr (component_swizzle[0] != Swizzle::None) {
+ ConvertFromComponent<0>(words[bound_words[0]],
+ old_components[static_cast<size_t>(component_swizzle[0])]);
+ }
+ if constexpr (num_components >= 2) {
+ if constexpr (component_swizzle[1] != Swizzle::None) {
+ ConvertFromComponent<1>(
+ words[bound_words[1]],
+ old_components[static_cast<size_t>(component_swizzle[1])]);
+ }
+ }
+ if constexpr (num_components >= 3) {
+ if constexpr (component_swizzle[2] != Swizzle::None) {
+ ConvertFromComponent<2>(
+ words[bound_words[2]],
+ old_components[static_cast<size_t>(component_swizzle[2])]);
+ }
+ }
+ if constexpr (num_components >= 4) {
+ if constexpr (component_swizzle[3] != Swizzle::None) {
+ ConvertFromComponent<3>(
+ words[bound_words[3]],
+ old_components[static_cast<size_t>(component_swizzle[3])]);
+ }
+ }
+ std::memcpy(&output[pixel * total_bytes_per_pixel], words.data(),
+ total_bytes_per_pixel);
+ }
+ }
+
+ ConverterImpl() = default;
+ ~ConverterImpl() override = default;
+};
+
+struct ConverterFactory::ConverterFactoryImpl {
+ std::unordered_map<RenderTargetFormat, std::unique_ptr<Converter>> converters_cache;
+};
+
+ConverterFactory::ConverterFactory() {
+ impl = std::make_unique<ConverterFactoryImpl>();
+}
+
+ConverterFactory::~ConverterFactory() = default;
+
+Converter* ConverterFactory::GetFormatConverter(RenderTargetFormat format) {
+ auto it = impl->converters_cache.find(format);
+ if (it == impl->converters_cache.end()) [[unlikely]] {
+ return BuildConverter(format);
+ }
+ return it->second.get();
+}
+
+class NullConverter : public Converter {
+public:
+ void ConvertTo([[maybe_unused]] std::span<const u8> input, std::span<f32> output) override {
+ std::fill(output.begin(), output.end(), 0.0f);
+ }
+ void ConvertFrom([[maybe_unused]] std::span<const f32> input, std::span<u8> output) override {
+ const u8 fill_value = 0U;
+ std::fill(output.begin(), output.end(), fill_value);
+ }
+ NullConverter() = default;
+ ~NullConverter() = default;
+};
+
+Converter* ConverterFactory::BuildConverter(RenderTargetFormat format) {
+ switch (format) {
+ case RenderTargetFormat::R32G32B32A32_FLOAT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32G32B32A32_FLOATTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32G32B32A32_SINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32G32B32A32_SINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32G32B32A32_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32G32B32A32_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32G32B32X32_FLOAT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32G32B32X32_FLOATTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32G32B32X32_SINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32G32B32X32_SINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32G32B32X32_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32G32B32X32_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16B16A16_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16B16A16_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16B16A16_SNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16B16A16_SNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16B16A16_SINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16B16A16_SINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16B16A16_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16B16A16_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16B16A16_FLOAT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16B16A16_FLOATTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32G32_FLOAT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32G32_FLOATTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32G32_SINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32G32_SINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32G32_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32G32_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16B16X16_FLOAT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16B16X16_FLOATTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A8R8G8B8_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A8R8G8B8_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A8R8G8B8_SRGB:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A8R8G8B8_SRGBTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A2B10G10R10_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A2B10G10R10_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A2B10G10R10_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A2B10G10R10_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A2R10G10B10_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A2R10G10B10_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A8B8G8R8_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A8B8G8R8_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A8B8G8R8_SRGB:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A8B8G8R8_SRGBTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A8B8G8R8_SNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A8B8G8R8_SNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A8B8G8R8_SINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A8B8G8R8_SINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A8B8G8R8_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A8B8G8R8_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16_SNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16_SNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16_SINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16_SINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16G16_FLOAT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16G16_FLOATTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::B10G11R11_FLOAT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<B10G11R11_FLOATTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32_SINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32_SINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R32_FLOAT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R32_FLOATTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::X8R8G8B8_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<X8R8G8B8_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::X8R8G8B8_SRGB:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<X8R8G8B8_SRGBTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R5G6B5_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R5G6B5_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::A1R5G5B5_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<A1R5G5B5_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R8G8_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R8G8_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R8G8_SNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R8G8_SNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R8G8_SINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R8G8_SINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R8G8_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R8G8_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16_SNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16_SNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16_SINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16_SINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R16_FLOAT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R16_FLOATTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R8_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R8_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R8_SNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R8_SNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R8_SINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R8_SINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::R8_UINT:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<R8_UINTTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::X1R5G5B5_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<X1R5G5B5_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::X8B8G8R8_UNORM:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<X8B8G8R8_UNORMTraits>>())
+ .first->second.get();
+ break;
+ case RenderTargetFormat::X8B8G8R8_SRGB:
+ return impl->converters_cache
+ .emplace(format, std::make_unique<ConverterImpl<X8B8G8R8_SRGBTraits>>())
+ .first->second.get();
+ break;
+ default: {
+ UNIMPLEMENTED_MSG("This format {} converter is not implemented", format);
+ return impl->converters_cache.emplace(format, std::make_unique<NullConverter>())
+ .first->second.get();
+ }
+ }
+}
+
+} // namespace Tegra::Engines::Blitter
diff --git a/src/video_core/engines/sw_blitter/converter.h b/src/video_core/engines/sw_blitter/converter.h
new file mode 100644
index 000000000..f9bdc516e
--- /dev/null
+++ b/src/video_core/engines/sw_blitter/converter.h
@@ -0,0 +1,36 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+#pragma once
+
+#include <memory>
+#include <span>
+
+#include "common/common_types.h"
+
+#include "video_core/gpu.h"
+
+namespace Tegra::Engines::Blitter {
+
+class Converter {
+public:
+ virtual void ConvertTo(std::span<const u8> input, std::span<f32> output) = 0;
+ virtual void ConvertFrom(std::span<const f32> input, std::span<u8> output) = 0;
+ virtual ~Converter() = default;
+};
+
+class ConverterFactory {
+public:
+ ConverterFactory();
+ ~ConverterFactory();
+
+ Converter* GetFormatConverter(RenderTargetFormat format);
+
+private:
+ Converter* BuildConverter(RenderTargetFormat format);
+
+ struct ConverterFactoryImpl;
+ std::unique_ptr<ConverterFactoryImpl> impl;
+};
+
+} // namespace Tegra::Engines::Blitter
diff --git a/src/video_core/engines/sw_blitter/generate_converters.py b/src/video_core/engines/sw_blitter/generate_converters.py
new file mode 100644
index 000000000..f641564f7
--- /dev/null
+++ b/src/video_core/engines/sw_blitter/generate_converters.py
@@ -0,0 +1,136 @@
+# SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import re
+
+class Format:
+ def __init__(self, string_value):
+ self.name = string_value
+ tmp = string_value.split('_')
+ self.component_type = tmp[1]
+ component_data = re.findall(r"\w\d+", tmp[0])
+ self.num_components = len(component_data)
+ sizes = []
+ swizzle = []
+ for data in component_data:
+ swizzle.append(data[0])
+ sizes.append(int(data[1:]))
+ self.sizes = sizes
+ self.swizzle = swizzle
+
+ def build_component_type_array(self):
+ result = "{ "
+ b = False
+ for i in range(0, self.num_components):
+ if b:
+ result += ", "
+ b = True
+ result += "ComponentType::" + self.component_type
+ result += " }"
+ return result
+
+ def build_component_sizes_array(self):
+ result = "{ "
+ b = False
+ for i in range(0, self.num_components):
+ if b:
+ result += ", "
+ b = True
+ result += str(self.sizes[i])
+ result += " }"
+ return result
+
+ def build_component_swizzle_array(self):
+ result = "{ "
+ b = False
+ for i in range(0, self.num_components):
+ if b:
+ result += ", "
+ b = True
+ swizzle = self.swizzle[i]
+ if swizzle == "X":
+ swizzle = "None"
+ result += "Swizzle::" + swizzle
+ result += " }"
+ return result
+
+ def print_declaration(self):
+ print("struct " + self.name + "Traits {")
+ print(" static constexpr size_t num_components = " + str(self.num_components) + ";")
+ print(" static constexpr std::array<ComponentType, num_components> component_types = " + self.build_component_type_array() + ";")
+ print(" static constexpr std::array<size_t, num_components> component_sizes = " + self.build_component_sizes_array() + ";")
+ print(" static constexpr std::array<Swizzle, num_components> component_swizzle = " + self.build_component_swizzle_array() + ";")
+ print("};\n")
+
+ def print_case(self):
+ print("case RenderTargetFormat::" + self.name + ":")
+ print(" return impl->converters_cache")
+ print(" .emplace(format, std::make_unique<ConverterImpl<" + self.name + "Traits>>())")
+ print(" .first->second.get();")
+ print(" break;")
+
+txt = """
+R32G32B32A32_FLOAT
+R32G32B32A32_SINT
+R32G32B32A32_UINT
+R32G32B32X32_FLOAT
+R32G32B32X32_SINT
+R32G32B32X32_UINT
+R16G16B16A16_UNORM
+R16G16B16A16_SNORM
+R16G16B16A16_SINT
+R16G16B16A16_UINT
+R16G16B16A16_FLOAT
+R32G32_FLOAT
+R32G32_SINT
+R32G32_UINT
+R16G16B16X16_FLOAT
+A8R8G8B8_UNORM
+A8R8G8B8_SRGB
+A2B10G10R10_UNORM
+A2B10G10R10_UINT
+A2R10G10B10_UNORM
+A8B8G8R8_UNORM
+A8B8G8R8_SRGB
+A8B8G8R8_SNORM
+A8B8G8R8_SINT
+A8B8G8R8_UINT
+R16G16_UNORM
+R16G16_SNORM
+R16G16_SINT
+R16G16_UINT
+R16G16_FLOAT
+B10G11R11_FLOAT
+R32_SINT
+R32_UINT
+R32_FLOAT
+X8R8G8B8_UNORM
+X8R8G8B8_SRGB
+R5G6B5_UNORM
+A1R5G5B5_UNORM
+R8G8_UNORM
+R8G8_SNORM
+R8G8_SINT
+R8G8_UINT
+R16_UNORM
+R16_SNORM
+R16_SINT
+R16_UINT
+R16_FLOAT
+R8_UNORM
+R8_SNORM
+R8_SINT
+R8_UINT
+X1R5G5B5_UNORM
+X8B8G8R8_UNORM
+X8B8G8R8_SRGB
+"""
+
+x = txt.split()
+y = list(map(lambda a: Format(a), x))
+formats = list(y)
+for format in formats:
+ format.print_declaration()
+
+for format in formats:
+ format.print_case()
diff --git a/src/video_core/gpu.h b/src/video_core/gpu.h
index d0709dc69..8a871593a 100644
--- a/src/video_core/gpu.h
+++ b/src/video_core/gpu.h
@@ -27,12 +27,12 @@ struct CommandList;
// TODO: Implement the commented ones
enum class RenderTargetFormat : u32 {
NONE = 0x0,
- R32B32G32A32_FLOAT = 0xC0,
+ R32G32B32A32_FLOAT = 0xC0,
R32G32B32A32_SINT = 0xC1,
R32G32B32A32_UINT = 0xC2,
- // R32G32B32X32_FLOAT = 0xC3,
- // R32G32B32X32_SINT = 0xC4,
- // R32G32B32X32_UINT = 0xC5,
+ R32G32B32X32_FLOAT = 0xC3,
+ R32G32B32X32_SINT = 0xC4,
+ R32G32B32X32_UINT = 0xC5,
R16G16B16A16_UNORM = 0xC6,
R16G16B16A16_SNORM = 0xC7,
R16G16B16A16_SINT = 0xC8,
@@ -56,13 +56,13 @@ enum class RenderTargetFormat : u32 {
R16G16_SINT = 0xDC,
R16G16_UINT = 0xDD,
R16G16_FLOAT = 0xDE,
- // A2R10G10B10_UNORM = 0xDF,
+ A2R10G10B10_UNORM = 0xDF,
B10G11R11_FLOAT = 0xE0,
R32_SINT = 0xE3,
R32_UINT = 0xE4,
R32_FLOAT = 0xE5,
- // X8R8G8B8_UNORM = 0xE6,
- // X8R8G8B8_SRGB = 0xE7,
+ X8R8G8B8_UNORM = 0xE6,
+ X8R8G8B8_SRGB = 0xE7,
R5G6B5_UNORM = 0xE8,
A1R5G5B5_UNORM = 0xE9,
R8G8_UNORM = 0xEA,
@@ -79,11 +79,11 @@ enum class RenderTargetFormat : u32 {
R8_SINT = 0xF5,
R8_UINT = 0xF6,
- /*
- A8_UNORM = 0xF7,
+ // A8_UNORM = 0xF7,
X1R5G5B5_UNORM = 0xF8,
X8B8G8R8_UNORM = 0xF9,
X8B8G8R8_SRGB = 0xFA,
+ /*
Z1R5G5B5_UNORM = 0xFB,
O1R5G5B5_UNORM = 0xFC,
Z8R8G8B8_UNORM = 0xFD,
diff --git a/src/video_core/gpu_thread.cpp b/src/video_core/gpu_thread.cpp
index 1bd477011..164a5252a 100644
--- a/src/video_core/gpu_thread.cpp
+++ b/src/video_core/gpu_thread.cpp
@@ -125,7 +125,7 @@ u64 ThreadManager::PushCommand(CommandData&& command_data, bool block) {
state.queue.Push(CommandDataContainer(std::move(command_data), fence, block));
if (block) {
- state.cv.wait(lk, thread.get_stop_token(), [this, fence] {
+ Common::CondvarWait(state.cv, lk, thread.get_stop_token(), [this, fence] {
return fence <= state.signaled_fence.load(std::memory_order_relaxed);
});
}
diff --git a/src/video_core/gpu_thread.h b/src/video_core/gpu_thread.h
index 64628d3e3..c71a419c7 100644
--- a/src/video_core/gpu_thread.h
+++ b/src/video_core/gpu_thread.h
@@ -10,6 +10,7 @@
#include <thread>
#include <variant>
+#include "common/polyfill_thread.h"
#include "common/threadsafe_queue.h"
#include "video_core/framebuffer_config.h"
diff --git a/src/video_core/host1x/syncpoint_manager.cpp b/src/video_core/host1x/syncpoint_manager.cpp
index a44fc83d3..8f23ce527 100644
--- a/src/video_core/host1x/syncpoint_manager.cpp
+++ b/src/video_core/host1x/syncpoint_manager.cpp
@@ -34,7 +34,7 @@ SyncpointManager::ActionHandle SyncpointManager::RegisterAction(
}
void SyncpointManager::DeregisterAction(std::list<RegisteredAction>& action_storage,
- ActionHandle& handle) {
+ const ActionHandle& handle) {
std::unique_lock lk(guard);
// We want to ensure the iterator still exists prior to erasing it
@@ -49,11 +49,11 @@ void SyncpointManager::DeregisterAction(std::list<RegisteredAction>& action_stor
}
}
-void SyncpointManager::DeregisterGuestAction(u32 syncpoint_id, ActionHandle& handle) {
+void SyncpointManager::DeregisterGuestAction(u32 syncpoint_id, const ActionHandle& handle) {
DeregisterAction(guest_action_storage[syncpoint_id], handle);
}
-void SyncpointManager::DeregisterHostAction(u32 syncpoint_id, ActionHandle& handle) {
+void SyncpointManager::DeregisterHostAction(u32 syncpoint_id, const ActionHandle& handle) {
DeregisterAction(host_action_storage[syncpoint_id], handle);
}
diff --git a/src/video_core/host1x/syncpoint_manager.h b/src/video_core/host1x/syncpoint_manager.h
index 50a264e23..847ed20c8 100644
--- a/src/video_core/host1x/syncpoint_manager.h
+++ b/src/video_core/host1x/syncpoint_manager.h
@@ -36,21 +36,19 @@ public:
template <typename Func>
ActionHandle RegisterGuestAction(u32 syncpoint_id, u32 expected_value, Func&& action) {
- std::function<void()> func(action);
return RegisterAction(syncpoints_guest[syncpoint_id], guest_action_storage[syncpoint_id],
- expected_value, std::move(func));
+ expected_value, std::move(action));
}
template <typename Func>
ActionHandle RegisterHostAction(u32 syncpoint_id, u32 expected_value, Func&& action) {
- std::function<void()> func(action);
return RegisterAction(syncpoints_host[syncpoint_id], host_action_storage[syncpoint_id],
- expected_value, std::move(func));
+ expected_value, std::move(action));
}
- void DeregisterGuestAction(u32 syncpoint_id, ActionHandle& handle);
+ void DeregisterGuestAction(u32 syncpoint_id, const ActionHandle& handle);
- void DeregisterHostAction(u32 syncpoint_id, ActionHandle& handle);
+ void DeregisterHostAction(u32 syncpoint_id, const ActionHandle& handle);
void IncrementGuest(u32 syncpoint_id);
@@ -76,7 +74,7 @@ private:
std::list<RegisteredAction>& action_storage, u32 expected_value,
std::function<void()>&& action);
- void DeregisterAction(std::list<RegisteredAction>& action_storage, ActionHandle& handle);
+ void DeregisterAction(std::list<RegisteredAction>& action_storage, const ActionHandle& handle);
void Wait(std::atomic<u32>& syncpoint, std::condition_variable& wait_cv, u32 expected_value);
diff --git a/src/video_core/macro/macro_hle.cpp b/src/video_core/macro/macro_hle.cpp
index f896591bf..0f3262edb 100644
--- a/src/video_core/macro/macro_hle.cpp
+++ b/src/video_core/macro/macro_hle.cpp
@@ -126,11 +126,25 @@ void HLE_3F5E74B9C9A50164(Engines::Maxwell3D& maxwell3d, const std::vector<u32>&
}
}
-constexpr std::array<std::pair<u64, HLEFunction>, 4> hle_funcs{{
+// Multi-layer Clear
+void HLE_EAD26C3E2109B06B(Engines::Maxwell3D& maxwell3d, const std::vector<u32>& parameters) {
+ ASSERT(parameters.size() == 1);
+
+ const Engines::Maxwell3D::Regs::ClearSurface clear_params{parameters[0]};
+ const u32 rt_index = clear_params.RT;
+ const u32 num_layers = maxwell3d.regs.rt[rt_index].depth;
+ ASSERT(clear_params.layer == 0);
+
+ maxwell3d.regs.clear_surface.raw = clear_params.raw;
+ maxwell3d.ProcessClearBuffers(num_layers);
+}
+
+constexpr std::array<std::pair<u64, HLEFunction>, 5> hle_funcs{{
{0x771BB18C62444DA0, &HLE_771BB18C62444DA0},
{0x0D61FC9FAAC9FCAD, &HLE_0D61FC9FAAC9FCAD},
{0x0217920100488FF7, &HLE_0217920100488FF7},
{0x3F5E74B9C9A50164, &HLE_3F5E74B9C9A50164},
+ {0xEAD26C3E2109B06B, &HLE_EAD26C3E2109B06B},
}};
class HLEMacroImpl final : public CachedMacro {
diff --git a/src/video_core/macro/macro_interpreter.cpp b/src/video_core/macro/macro_interpreter.cpp
index c0d32c112..0d63495a9 100644
--- a/src/video_core/macro/macro_interpreter.cpp
+++ b/src/video_core/macro/macro_interpreter.cpp
@@ -201,6 +201,7 @@ bool MacroInterpreterImpl::Step(bool is_delay_slot) {
}
default:
UNIMPLEMENTED_MSG("Unimplemented macro operation {}", opcode.operation.Value());
+ break;
}
// An instruction with the Exit flag will not actually
@@ -297,6 +298,7 @@ void MacroInterpreterImpl::ProcessResult(Macro::ResultOperation operation, u32 r
break;
default:
UNIMPLEMENTED_MSG("Unimplemented result operation {}", operation);
+ break;
}
}
diff --git a/src/video_core/macro/macro_jit_x64.cpp b/src/video_core/macro/macro_jit_x64.cpp
index 25c1ce798..7347cbd88 100644
--- a/src/video_core/macro/macro_jit_x64.cpp
+++ b/src/video_core/macro/macro_jit_x64.cpp
@@ -652,6 +652,7 @@ void MacroJITx64Impl::Compile_ProcessResult(Macro::ResultOperation operation, u3
break;
default:
UNIMPLEMENTED_MSG("Unimplemented macro operation {}", operation);
+ break;
}
}
diff --git a/src/video_core/precompiled_headers.h b/src/video_core/precompiled_headers.h
new file mode 100644
index 000000000..aabae730b
--- /dev/null
+++ b/src/video_core/precompiled_headers.h
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
diff --git a/src/video_core/rasterizer_interface.h b/src/video_core/rasterizer_interface.h
index 1cbfef090..b6907463c 100644
--- a/src/video_core/rasterizer_interface.h
+++ b/src/video_core/rasterizer_interface.h
@@ -6,8 +6,8 @@
#include <functional>
#include <optional>
#include <span>
-#include <stop_token>
#include "common/common_types.h"
+#include "common/polyfill_thread.h"
#include "video_core/engines/fermi_2d.h"
#include "video_core/gpu.h"
@@ -43,7 +43,7 @@ public:
virtual void Draw(bool is_indexed, u32 instance_count) = 0;
/// Clear the current framebuffer
- virtual void Clear() = 0;
+ virtual void Clear(u32 layer_count) = 0;
/// Dispatches a compute shader invocation
virtual void DispatchCompute() = 0;
diff --git a/src/video_core/renderer_null/null_rasterizer.cpp b/src/video_core/renderer_null/null_rasterizer.cpp
new file mode 100644
index 000000000..9734d84bc
--- /dev/null
+++ b/src/video_core/renderer_null/null_rasterizer.cpp
@@ -0,0 +1,90 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include "video_core/host1x/host1x.h"
+#include "video_core/memory_manager.h"
+#include "video_core/renderer_null/null_rasterizer.h"
+
+namespace Null {
+
+AccelerateDMA::AccelerateDMA() = default;
+
+bool AccelerateDMA::BufferCopy(GPUVAddr start_address, GPUVAddr end_address, u64 amount) {
+ return true;
+}
+bool AccelerateDMA::BufferClear(GPUVAddr src_address, u64 amount, u32 value) {
+ return true;
+}
+
+RasterizerNull::RasterizerNull(Core::Memory::Memory& cpu_memory_, Tegra::GPU& gpu)
+ : RasterizerAccelerated(cpu_memory_), m_gpu{gpu} {}
+RasterizerNull::~RasterizerNull() = default;
+
+void RasterizerNull::Draw(bool is_indexed, u32 instance_count) {}
+void RasterizerNull::Clear(u32 layer_count) {}
+void RasterizerNull::DispatchCompute() {}
+void RasterizerNull::ResetCounter(VideoCore::QueryType type) {}
+void RasterizerNull::Query(GPUVAddr gpu_addr, VideoCore::QueryType type,
+ std::optional<u64> timestamp) {
+ if (!gpu_memory) {
+ return;
+ }
+
+ gpu_memory->Write(gpu_addr, u64{0});
+ if (timestamp) {
+ gpu_memory->Write(gpu_addr + 8, *timestamp);
+ }
+}
+void RasterizerNull::BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr,
+ u32 size) {}
+void RasterizerNull::DisableGraphicsUniformBuffer(size_t stage, u32 index) {}
+void RasterizerNull::FlushAll() {}
+void RasterizerNull::FlushRegion(VAddr addr, u64 size) {}
+bool RasterizerNull::MustFlushRegion(VAddr addr, u64 size) {
+ return false;
+}
+void RasterizerNull::InvalidateRegion(VAddr addr, u64 size) {}
+void RasterizerNull::OnCPUWrite(VAddr addr, u64 size) {}
+void RasterizerNull::InvalidateGPUCache() {}
+void RasterizerNull::UnmapMemory(VAddr addr, u64 size) {}
+void RasterizerNull::ModifyGPUMemory(size_t as_id, GPUVAddr addr, u64 size) {}
+void RasterizerNull::SignalFence(std::function<void()>&& func) {
+ func();
+}
+void RasterizerNull::SyncOperation(std::function<void()>&& func) {
+ func();
+}
+void RasterizerNull::SignalSyncPoint(u32 value) {
+ auto& syncpoint_manager = m_gpu.Host1x().GetSyncpointManager();
+ syncpoint_manager.IncrementGuest(value);
+ syncpoint_manager.IncrementHost(value);
+}
+void RasterizerNull::SignalReference() {}
+void RasterizerNull::ReleaseFences() {}
+void RasterizerNull::FlushAndInvalidateRegion(VAddr addr, u64 size) {}
+void RasterizerNull::WaitForIdle() {}
+void RasterizerNull::FragmentBarrier() {}
+void RasterizerNull::TiledCacheBarrier() {}
+void RasterizerNull::FlushCommands() {}
+void RasterizerNull::TickFrame() {}
+Tegra::Engines::AccelerateDMAInterface& RasterizerNull::AccessAccelerateDMA() {
+ return m_accelerate_dma;
+}
+bool RasterizerNull::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Surface& src,
+ const Tegra::Engines::Fermi2D::Surface& dst,
+ const Tegra::Engines::Fermi2D::Config& copy_config) {
+ return true;
+}
+void RasterizerNull::AccelerateInlineToMemory(GPUVAddr address, size_t copy_size,
+ std::span<const u8> memory) {}
+bool RasterizerNull::AccelerateDisplay(const Tegra::FramebufferConfig& config,
+ VAddr framebuffer_addr, u32 pixel_stride) {
+ return true;
+}
+void RasterizerNull::LoadDiskResources(u64 title_id, std::stop_token stop_loading,
+ const VideoCore::DiskResourceLoadCallback& callback) {}
+void RasterizerNull::InitializeChannel(Tegra::Control::ChannelState& channel) {}
+void RasterizerNull::BindChannel(Tegra::Control::ChannelState& channel) {}
+void RasterizerNull::ReleaseChannel(s32 channel_id) {}
+
+} // namespace Null
diff --git a/src/video_core/renderer_null/null_rasterizer.h b/src/video_core/renderer_null/null_rasterizer.h
new file mode 100644
index 000000000..ecf77ba42
--- /dev/null
+++ b/src/video_core/renderer_null/null_rasterizer.h
@@ -0,0 +1,78 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_types.h"
+#include "video_core/control/channel_state_cache.h"
+#include "video_core/engines/maxwell_dma.h"
+#include "video_core/rasterizer_accelerated.h"
+#include "video_core/rasterizer_interface.h"
+
+namespace Core {
+class System;
+}
+
+namespace Null {
+
+class RasterizerNull;
+
+class AccelerateDMA : public Tegra::Engines::AccelerateDMAInterface {
+public:
+ explicit AccelerateDMA();
+ bool BufferCopy(GPUVAddr start_address, GPUVAddr end_address, u64 amount) override;
+ bool BufferClear(GPUVAddr src_address, u64 amount, u32 value) override;
+};
+
+class RasterizerNull final : public VideoCore::RasterizerAccelerated,
+ protected VideoCommon::ChannelSetupCaches<VideoCommon::ChannelInfo> {
+public:
+ explicit RasterizerNull(Core::Memory::Memory& cpu_memory, Tegra::GPU& gpu);
+ ~RasterizerNull() override;
+
+ void Draw(bool is_indexed, u32 instance_count) override;
+ void Clear(u32 layer_count) override;
+ void DispatchCompute() override;
+ void ResetCounter(VideoCore::QueryType type) override;
+ void Query(GPUVAddr gpu_addr, VideoCore::QueryType type, std::optional<u64> timestamp) override;
+ void BindGraphicsUniformBuffer(size_t stage, u32 index, GPUVAddr gpu_addr, u32 size) override;
+ void DisableGraphicsUniformBuffer(size_t stage, u32 index) override;
+ void FlushAll() override;
+ void FlushRegion(VAddr addr, u64 size) override;
+ bool MustFlushRegion(VAddr addr, u64 size) override;
+ void InvalidateRegion(VAddr addr, u64 size) override;
+ void OnCPUWrite(VAddr addr, u64 size) override;
+ void InvalidateGPUCache() override;
+ void UnmapMemory(VAddr addr, u64 size) override;
+ void ModifyGPUMemory(size_t as_id, GPUVAddr addr, u64 size) override;
+ void SignalFence(std::function<void()>&& func) override;
+ void SyncOperation(std::function<void()>&& func) override;
+ void SignalSyncPoint(u32 value) override;
+ void SignalReference() override;
+ void ReleaseFences() override;
+ void FlushAndInvalidateRegion(VAddr addr, u64 size) override;
+ void WaitForIdle() override;
+ void FragmentBarrier() override;
+ void TiledCacheBarrier() override;
+ void FlushCommands() override;
+ void TickFrame() override;
+ bool AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Surface& src,
+ const Tegra::Engines::Fermi2D::Surface& dst,
+ const Tegra::Engines::Fermi2D::Config& copy_config) override;
+ Tegra::Engines::AccelerateDMAInterface& AccessAccelerateDMA() override;
+ void AccelerateInlineToMemory(GPUVAddr address, size_t copy_size,
+ std::span<const u8> memory) override;
+ bool AccelerateDisplay(const Tegra::FramebufferConfig& config, VAddr framebuffer_addr,
+ u32 pixel_stride) override;
+ void LoadDiskResources(u64 title_id, std::stop_token stop_loading,
+ const VideoCore::DiskResourceLoadCallback& callback) override;
+ void InitializeChannel(Tegra::Control::ChannelState& channel) override;
+ void BindChannel(Tegra::Control::ChannelState& channel) override;
+ void ReleaseChannel(s32 channel_id) override;
+
+private:
+ Tegra::GPU& m_gpu;
+ AccelerateDMA m_accelerate_dma;
+};
+
+} // namespace Null
diff --git a/src/video_core/renderer_null/renderer_null.cpp b/src/video_core/renderer_null/renderer_null.cpp
new file mode 100644
index 000000000..e2a189b63
--- /dev/null
+++ b/src/video_core/renderer_null/renderer_null.cpp
@@ -0,0 +1,24 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include "video_core/renderer_null/renderer_null.h"
+
+namespace Null {
+
+RendererNull::RendererNull(Core::Frontend::EmuWindow& emu_window, Core::Memory::Memory& cpu_memory,
+ Tegra::GPU& gpu,
+ std::unique_ptr<Core::Frontend::GraphicsContext> context_)
+ : RendererBase(emu_window, std::move(context_)), m_gpu(gpu), m_rasterizer(cpu_memory, gpu) {}
+
+RendererNull::~RendererNull() = default;
+
+void RendererNull::SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
+ if (!framebuffer) {
+ return;
+ }
+
+ m_gpu.RendererFrameEndNotify();
+ render_window.OnFrameDisplayed();
+}
+
+} // namespace Null
diff --git a/src/video_core/renderer_null/renderer_null.h b/src/video_core/renderer_null/renderer_null.h
new file mode 100644
index 000000000..967ff5645
--- /dev/null
+++ b/src/video_core/renderer_null/renderer_null.h
@@ -0,0 +1,36 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include <memory>
+#include <string>
+
+#include "video_core/renderer_base.h"
+#include "video_core/renderer_null/null_rasterizer.h"
+
+namespace Null {
+
+class RendererNull final : public VideoCore::RendererBase {
+public:
+ explicit RendererNull(Core::Frontend::EmuWindow& emu_window, Core::Memory::Memory& cpu_memory,
+ Tegra::GPU& gpu,
+ std::unique_ptr<Core::Frontend::GraphicsContext> context);
+ ~RendererNull() override;
+
+ void SwapBuffers(const Tegra::FramebufferConfig* framebuffer) override;
+
+ VideoCore::RasterizerInterface* ReadRasterizer() override {
+ return &m_rasterizer;
+ }
+
+ [[nodiscard]] std::string GetDeviceVendor() const override {
+ return "NULL";
+ }
+
+private:
+ Tegra::GPU& m_gpu;
+ RasterizerNull m_rasterizer;
+};
+
+} // namespace Null
diff --git a/src/video_core/renderer_opengl/gl_device.cpp b/src/video_core/renderer_opengl/gl_device.cpp
index 1663e277d..e2e3dac34 100644
--- a/src/video_core/renderer_opengl/gl_device.cpp
+++ b/src/video_core/renderer_opengl/gl_device.cpp
@@ -14,6 +14,7 @@
#include "common/literals.h"
#include "common/logging/log.h"
+#include "common/polyfill_ranges.h"
#include "common/settings.h"
#include "shader_recompiler/stage.h"
#include "video_core/renderer_opengl/gl_device.h"
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index d05a5f60b..f71a316b6 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -136,7 +136,7 @@ void RasterizerOpenGL::LoadDiskResources(u64 title_id, std::stop_token stop_load
shader_cache.LoadDiskResources(title_id, stop_loading, callback);
}
-void RasterizerOpenGL::Clear() {
+void RasterizerOpenGL::Clear(u32 layer_count) {
MICROPROFILE_SCOPE(OpenGL_Clears);
if (!maxwell3d->ShouldExecute()) {
return;
@@ -222,8 +222,6 @@ void RasterizerOpenGL::Draw(bool is_indexed, u32 instance_count) {
pipeline->SetEngine(maxwell3d, gpu_memory);
pipeline->Configure(is_indexed);
- BindInlineIndexBuffer();
-
SyncState();
const GLenum primitive_mode = MaxwellToGL::PrimitiveTopology(maxwell3d->regs.draw.topology);
@@ -468,8 +466,7 @@ bool RasterizerOpenGL::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Surf
const Tegra::Engines::Fermi2D::Config& copy_config) {
MICROPROFILE_SCOPE(OpenGL_Blits);
std::scoped_lock lock{texture_cache.mutex};
- texture_cache.BlitImage(dst, src, copy_config);
- return true;
+ return texture_cache.BlitImage(dst, src, copy_config);
}
Tegra::Engines::AccelerateDMAInterface& RasterizerOpenGL::AccessAccelerateDMA() {
@@ -1140,16 +1137,6 @@ void RasterizerOpenGL::ReleaseChannel(s32 channel_id) {
query_cache.EraseChannel(channel_id);
}
-void RasterizerOpenGL::BindInlineIndexBuffer() {
- if (maxwell3d->inline_index_draw_indexes.empty()) {
- return;
- }
- const auto data_count = static_cast<u32>(maxwell3d->inline_index_draw_indexes.size());
- auto buffer = Buffer(buffer_cache_runtime, *this, 0, data_count);
- buffer.ImmediateUpload(0, maxwell3d->inline_index_draw_indexes);
- buffer_cache_runtime.BindIndexBuffer(buffer, 0, data_count);
-}
-
AccelerateDMA::AccelerateDMA(BufferCache& buffer_cache_) : buffer_cache{buffer_cache_} {}
bool AccelerateDMA::BufferCopy(GPUVAddr src_address, GPUVAddr dest_address, u64 amount) {
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index 793e0d608..fc183c3ca 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer.h
@@ -69,7 +69,7 @@ public:
~RasterizerOpenGL() override;
void Draw(bool is_indexed, u32 instance_count) override;
- void Clear() override;
+ void Clear(u32 layer_count) override;
void DispatchCompute() override;
void ResetCounter(VideoCore::QueryType type) override;
void Query(GPUVAddr gpu_addr, VideoCore::QueryType type, std::optional<u64> timestamp) override;
@@ -199,8 +199,6 @@ private:
/// End a transform feedback
void EndTransformFeedback();
- void BindInlineIndexBuffer();
-
Tegra::GPU& gpu;
const Device& device;
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.cpp b/src/video_core/renderer_opengl/gl_shader_cache.cpp
index 3fe04a115..a38060100 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_cache.cpp
@@ -39,6 +39,7 @@ using Shader::Backend::GLASM::EmitGLASM;
using Shader::Backend::GLSL::EmitGLSL;
using Shader::Backend::SPIRV::EmitSPIRV;
using Shader::Maxwell::ConvertLegacyToGeneric;
+using Shader::Maxwell::GenerateGeometryPassthrough;
using Shader::Maxwell::MergeDualVertexPrograms;
using Shader::Maxwell::TranslateProgram;
using VideoCommon::ComputeEnvironment;
@@ -56,6 +57,17 @@ auto MakeSpan(Container& container) {
return std::span(container.data(), container.size());
}
+Shader::OutputTopology MaxwellToOutputTopology(Maxwell::PrimitiveTopology topology) {
+ switch (topology) {
+ case Maxwell::PrimitiveTopology::Points:
+ return Shader::OutputTopology::PointList;
+ case Maxwell::PrimitiveTopology::LineStrip:
+ return Shader::OutputTopology::LineStrip;
+ default:
+ return Shader::OutputTopology::TriangleStrip;
+ }
+}
+
Shader::RuntimeInfo MakeRuntimeInfo(const GraphicsPipelineKey& key,
const Shader::IR::Program& program,
const Shader::IR::Program* previous_program,
@@ -220,6 +232,7 @@ ShaderCache::ShaderCache(RasterizerOpenGL& rasterizer_, Core::Frontend::EmuWindo
.support_int64 = device.HasShaderInt64(),
.needs_demote_reorder = device.IsAmd(),
.support_snorm_render_buffer = false,
+ .support_viewport_index_layer = device.HasVertexViewportLayer(),
} {
if (use_asynchronous_shaders) {
workers = CreateWorkers();
@@ -314,9 +327,7 @@ GraphicsPipeline* ShaderCache::CurrentGraphicsPipeline() {
const auto& regs{maxwell3d->regs};
graphics_key.raw = 0;
graphics_key.early_z.Assign(regs.mandated_early_z != 0 ? 1 : 0);
- graphics_key.gs_input_topology.Assign(graphics_key.unique_hashes[4] != 0
- ? regs.draw.topology.Value()
- : Maxwell::PrimitiveTopology{});
+ graphics_key.gs_input_topology.Assign(regs.draw.topology.Value());
graphics_key.tessellation_primitive.Assign(regs.tessellation.params.domain_type.Value());
graphics_key.tessellation_spacing.Assign(regs.tessellation.params.spacing.Value());
graphics_key.tessellation_clockwise.Assign(
@@ -415,7 +426,19 @@ std::unique_ptr<GraphicsPipeline> ShaderCache::CreateGraphicsPipeline(
std::array<Shader::IR::Program, Maxwell::MaxShaderProgram> programs;
const bool uses_vertex_a{key.unique_hashes[0] != 0};
const bool uses_vertex_b{key.unique_hashes[1] != 0};
+
+ // Layer passthrough generation for devices without GL_ARB_shader_viewport_layer_array
+ Shader::IR::Program* layer_source_program{};
+
for (size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
+ const bool is_emulated_stage = layer_source_program != nullptr &&
+ index == static_cast<u32>(Maxwell::ShaderType::Geometry);
+ if (key.unique_hashes[index] == 0 && is_emulated_stage) {
+ auto topology = MaxwellToOutputTopology(key.gs_input_topology);
+ programs[index] = GenerateGeometryPassthrough(pools.inst, pools.block, host_info,
+ *layer_source_program, topology);
+ continue;
+ }
if (key.unique_hashes[index] == 0) {
continue;
}
@@ -443,6 +466,10 @@ std::unique_ptr<GraphicsPipeline> ShaderCache::CreateGraphicsPipeline(
Shader::NumDescriptors(program_vb.info.storage_buffers_descriptors);
programs[index] = MergeDualVertexPrograms(program_va, program_vb, env);
}
+
+ if (programs[index].info.requires_layer_emulation) {
+ layer_source_program = &programs[index];
+ }
}
const u32 glasm_storage_buffer_limit{device.GetMaxGLASMStorageBufferBlocks()};
const bool glasm_use_storage_buffers{total_storage_buffers <= glasm_storage_buffer_limit};
@@ -456,7 +483,9 @@ std::unique_ptr<GraphicsPipeline> ShaderCache::CreateGraphicsPipeline(
const bool use_glasm{device.UseAssemblyShaders()};
const size_t first_index = uses_vertex_a && uses_vertex_b ? 1 : 0;
for (size_t index = first_index; index < Maxwell::MaxShaderProgram; ++index) {
- if (key.unique_hashes[index] == 0) {
+ const bool is_emulated_stage = layer_source_program != nullptr &&
+ index == static_cast<u32>(Maxwell::ShaderType::Geometry);
+ if (key.unique_hashes[index] == 0 && !is_emulated_stage) {
continue;
}
UNIMPLEMENTED_IF(index == 0);
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.h b/src/video_core/renderer_opengl/gl_shader_cache.h
index 89f181fe3..53ffea904 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.h
+++ b/src/video_core/renderer_opengl/gl_shader_cache.h
@@ -4,7 +4,6 @@
#pragma once
#include <filesystem>
-#include <stop_token>
#include <unordered_map>
#include "common/common_types.h"
diff --git a/src/video_core/renderer_opengl/gl_texture_cache.cpp b/src/video_core/renderer_opengl/gl_texture_cache.cpp
index 99cd11d1e..9f7ce7414 100644
--- a/src/video_core/renderer_opengl/gl_texture_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_texture_cache.cpp
@@ -891,6 +891,7 @@ void Image::CopyBufferToImage(const VideoCommon::BufferImageCopy& copy, size_t b
break;
default:
ASSERT(false);
+ break;
}
}
@@ -927,6 +928,7 @@ void Image::CopyImageToBuffer(const VideoCommon::BufferImageCopy& copy, size_t b
break;
default:
ASSERT(false);
+ break;
}
// Compressed formats don't have a pixel format or type
const bool is_compressed = gl_format == GL_NONE;
diff --git a/src/video_core/renderer_opengl/maxwell_to_gl.h b/src/video_core/renderer_opengl/maxwell_to_gl.h
index e14f9b2db..ef1190e1f 100644
--- a/src/video_core/renderer_opengl/maxwell_to_gl.h
+++ b/src/video_core/renderer_opengl/maxwell_to_gl.h
@@ -28,6 +28,7 @@ constexpr std::array<FormatTuple, VideoCore::Surface::MaxPixelFormat> FORMAT_TAB
{GL_RGB5_A1, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV}, // A1R5G5B5_UNORM
{GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV}, // A2B10G10R10_UNORM
{GL_RGB10_A2UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV}, // A2B10G10R10_UINT
+ {GL_RGB10_A2, GL_BGRA, GL_UNSIGNED_INT_2_10_10_10_REV}, // A2R10G10B10_UNORM
{GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV}, // A1B5G5R5_UNORM
{GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1}, // A5B5G5R1_UNORM
{GL_R8, GL_RED, GL_UNSIGNED_BYTE}, // R8_UNORM
diff --git a/src/video_core/renderer_opengl/renderer_opengl.cpp b/src/video_core/renderer_opengl/renderer_opengl.cpp
index 8bd5eba7e..f29462f7c 100644
--- a/src/video_core/renderer_opengl/renderer_opengl.cpp
+++ b/src/video_core/renderer_opengl/renderer_opengl.cpp
@@ -340,6 +340,7 @@ void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
texture.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
// UNIMPLEMENTED_MSG("Unknown framebuffer pixel format: {}",
// static_cast<u32>(framebuffer.pixel_format));
+ break;
}
texture.resource.Release();
diff --git a/src/video_core/renderer_vulkan/fixed_pipeline_state.cpp b/src/video_core/renderer_vulkan/fixed_pipeline_state.cpp
index 98cc26679..f3f08b42c 100644
--- a/src/video_core/renderer_vulkan/fixed_pipeline_state.cpp
+++ b/src/video_core/renderer_vulkan/fixed_pipeline_state.cpp
@@ -7,6 +7,7 @@
#include "common/bit_cast.h"
#include "common/cityhash.h"
#include "common/common_types.h"
+#include "common/polyfill_ranges.h"
#include "video_core/renderer_vulkan/fixed_pipeline_state.h"
#include "video_core/renderer_vulkan/vk_state_tracker.h"
diff --git a/src/video_core/renderer_vulkan/maxwell_to_vk.cpp b/src/video_core/renderer_vulkan/maxwell_to_vk.cpp
index 5c156087b..3e03c5cd6 100644
--- a/src/video_core/renderer_vulkan/maxwell_to_vk.cpp
+++ b/src/video_core/renderer_vulkan/maxwell_to_vk.cpp
@@ -58,7 +58,7 @@ VkSamplerAddressMode WrapMode(const Device& device, Tegra::Texture::WrapMode wra
case Tegra::Texture::WrapMode::Border:
return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
case Tegra::Texture::WrapMode::Clamp:
- if (device.GetDriverID() == VK_DRIVER_ID_NVIDIA_PROPRIETARY_KHR) {
+ if (device.GetDriverID() == VK_DRIVER_ID_NVIDIA_PROPRIETARY) {
// Nvidia's Vulkan driver defaults to GL_CLAMP on invalid enumerations, we can hack this
// by sending an invalid enumeration.
return static_cast<VkSamplerAddressMode>(0xcafe);
@@ -125,6 +125,7 @@ struct FormatTuple {
{VK_FORMAT_A1R5G5B5_UNORM_PACK16, Attachable}, // A1R5G5B5_UNORM
{VK_FORMAT_A2B10G10R10_UNORM_PACK32, Attachable | Storage}, // A2B10G10R10_UNORM
{VK_FORMAT_A2B10G10R10_UINT_PACK32, Attachable | Storage}, // A2B10G10R10_UINT
+ {VK_FORMAT_A2R10G10B10_UNORM_PACK32, Attachable | Storage}, // A2R10G10B10_UNORM
{VK_FORMAT_A1R5G5B5_UNORM_PACK16, Attachable}, // A1B5G5R5_UNORM (flipped with swizzle)
{VK_FORMAT_R5G5B5A1_UNORM_PACK16}, // A5B5G5R1_UNORM (specially swizzled)
{VK_FORMAT_R8_UNORM, Attachable | Storage}, // R8_UNORM
@@ -149,7 +150,7 @@ struct FormatTuple {
{VK_FORMAT_BC6H_UFLOAT_BLOCK}, // BC6H_UFLOAT
{VK_FORMAT_BC6H_SFLOAT_BLOCK}, // BC6H_SFLOAT
{VK_FORMAT_ASTC_4x4_UNORM_BLOCK}, // ASTC_2D_4X4_UNORM
- {VK_FORMAT_B8G8R8A8_UNORM, Attachable}, // B8G8R8A8_UNORM
+ {VK_FORMAT_B8G8R8A8_UNORM, Attachable | Storage}, // B8G8R8A8_UNORM
{VK_FORMAT_R32G32B32A32_SFLOAT, Attachable | Storage}, // R32G32B32A32_FLOAT
{VK_FORMAT_R32G32B32A32_SINT, Attachable | Storage}, // R32G32B32A32_SINT
{VK_FORMAT_R32G32_SFLOAT, Attachable | Storage}, // R32G32_FLOAT
@@ -159,7 +160,7 @@ struct FormatTuple {
{VK_FORMAT_R16_UNORM, Attachable | Storage}, // R16_UNORM
{VK_FORMAT_R16_SNORM, Attachable | Storage}, // R16_SNORM
{VK_FORMAT_R16_UINT, Attachable | Storage}, // R16_UINT
- {VK_FORMAT_UNDEFINED}, // R16_SINT
+ {VK_FORMAT_R16_SINT, Attachable | Storage}, // R16_SINT
{VK_FORMAT_R16G16_UNORM, Attachable | Storage}, // R16G16_UNORM
{VK_FORMAT_R16G16_SFLOAT, Attachable | Storage}, // R16G16_FLOAT
{VK_FORMAT_R16G16_UINT, Attachable | Storage}, // R16G16_UINT
@@ -183,7 +184,7 @@ struct FormatTuple {
{VK_FORMAT_BC2_SRGB_BLOCK}, // BC2_SRGB
{VK_FORMAT_BC3_SRGB_BLOCK}, // BC3_SRGB
{VK_FORMAT_BC7_SRGB_BLOCK}, // BC7_SRGB
- {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Attachable}, // A4B4G4R4_UNORM
+ {VK_FORMAT_R4G4B4A4_UNORM_PACK16}, // A4B4G4R4_UNORM
{VK_FORMAT_R4G4_UNORM_PACK8}, // G4R4_UNORM
{VK_FORMAT_ASTC_4x4_SRGB_BLOCK}, // ASTC_2D_4X4_SRGB
{VK_FORMAT_ASTC_8x8_SRGB_BLOCK}, // ASTC_2D_8X8_SRGB
diff --git a/src/video_core/renderer_vulkan/pipeline_helper.h b/src/video_core/renderer_vulkan/pipeline_helper.h
index b7843e995..28b893e25 100644
--- a/src/video_core/renderer_vulkan/pipeline_helper.h
+++ b/src/video_core/renderer_vulkan/pipeline_helper.h
@@ -44,17 +44,17 @@ public:
});
}
- vk::DescriptorUpdateTemplateKHR CreateTemplate(VkDescriptorSetLayout descriptor_set_layout,
- VkPipelineLayout pipeline_layout,
- bool use_push_descriptor) const {
+ vk::DescriptorUpdateTemplate CreateTemplate(VkDescriptorSetLayout descriptor_set_layout,
+ VkPipelineLayout pipeline_layout,
+ bool use_push_descriptor) const {
if (entries.empty()) {
return nullptr;
}
const VkDescriptorUpdateTemplateType type =
use_push_descriptor ? VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR
- : VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET_KHR;
- return device->GetLogical().CreateDescriptorUpdateTemplateKHR({
- .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO_KHR,
+ : VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET;
+ return device->GetLogical().CreateDescriptorUpdateTemplate({
+ .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.descriptorUpdateEntryCount = static_cast<u32>(entries.size()),
@@ -129,7 +129,7 @@ private:
const Device* device{};
bool is_compute{};
boost::container::small_vector<VkDescriptorSetLayoutBinding, 32> bindings;
- boost::container::small_vector<VkDescriptorUpdateTemplateEntryKHR, 32> entries;
+ boost::container::small_vector<VkDescriptorUpdateTemplateEntry, 32> entries;
u32 binding{};
u32 num_descriptors{};
size_t offset{};
diff --git a/src/video_core/renderer_vulkan/renderer_vulkan.cpp b/src/video_core/renderer_vulkan/renderer_vulkan.cpp
index d8131232a..18be54729 100644
--- a/src/video_core/renderer_vulkan/renderer_vulkan.cpp
+++ b/src/video_core/renderer_vulkan/renderer_vulkan.cpp
@@ -45,14 +45,14 @@ std::string GetDriverVersion(const Device& device) {
// https://github.com/SaschaWillems/vulkan.gpuinfo.org/blob/5dddea46ea1120b0df14eef8f15ff8e318e35462/functions.php#L308-L314
const u32 version = device.GetDriverVersion();
- if (device.GetDriverID() == VK_DRIVER_ID_NVIDIA_PROPRIETARY_KHR) {
+ if (device.GetDriverID() == VK_DRIVER_ID_NVIDIA_PROPRIETARY) {
const u32 major = (version >> 22) & 0x3ff;
const u32 minor = (version >> 14) & 0x0ff;
const u32 secondary = (version >> 6) & 0x0ff;
const u32 tertiary = version & 0x003f;
return fmt::format("{}.{}.{}.{}", major, minor, secondary, tertiary);
}
- if (device.GetDriverID() == VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS_KHR) {
+ if (device.GetDriverID() == VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS) {
const u32 major = version >> 14;
const u32 minor = version & 0x3fff;
return fmt::format("{}.{}", major, minor);
@@ -172,6 +172,7 @@ void RendererVulkan::SwapBuffers(const Tegra::FramebufferConfig* framebuffer) {
}
void RendererVulkan::Report() const {
+ using namespace Common::Literals;
const std::string vendor_name{device.GetVendorName()};
const std::string model_name{device.GetModelName()};
const std::string driver_version = GetDriverVersion(device);
@@ -181,9 +182,12 @@ void RendererVulkan::Report() const {
const std::string extensions = BuildCommaSeparatedExtensions(device.GetAvailableExtensions());
+ const auto available_vram = static_cast<f64>(device.GetDeviceLocalMemory()) / f64{1_GiB};
+
LOG_INFO(Render_Vulkan, "Driver: {}", driver_name);
LOG_INFO(Render_Vulkan, "Device: {}", model_name);
LOG_INFO(Render_Vulkan, "Vulkan: {}", api_version);
+ LOG_INFO(Render_Vulkan, "Available VRAM: {:.2f} GiB", available_vram);
static constexpr auto field = Common::Telemetry::FieldType::UserSystem;
telemetry_session.AddField(field, "GPU_Vendor", vendor_name);
diff --git a/src/video_core/renderer_vulkan/vk_blit_screen.cpp b/src/video_core/renderer_vulkan/vk_blit_screen.cpp
index 89426121f..6e5abade4 100644
--- a/src/video_core/renderer_vulkan/vk_blit_screen.cpp
+++ b/src/video_core/renderer_vulkan/vk_blit_screen.cpp
@@ -10,6 +10,7 @@
#include "common/assert.h"
#include "common/common_types.h"
#include "common/math_util.h"
+#include "common/polyfill_ranges.h"
#include "common/settings.h"
#include "core/core.h"
#include "core/frontend/emu_window.h"
diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.cpp b/src/video_core/renderer_vulkan/vk_compute_pass.cpp
index 241d7573e..2c00979d7 100644
--- a/src/video_core/renderer_vulkan/vk_compute_pass.cpp
+++ b/src/video_core/renderer_vulkan/vk_compute_pass.cpp
@@ -93,7 +93,7 @@ constexpr DescriptorBankInfo ASTC_BANK_INFO{
.score = 2,
};
-constexpr VkDescriptorUpdateTemplateEntryKHR INPUT_OUTPUT_DESCRIPTOR_UPDATE_TEMPLATE{
+constexpr VkDescriptorUpdateTemplateEntry INPUT_OUTPUT_DESCRIPTOR_UPDATE_TEMPLATE{
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = 2,
@@ -102,7 +102,7 @@ constexpr VkDescriptorUpdateTemplateEntryKHR INPUT_OUTPUT_DESCRIPTOR_UPDATE_TEMP
.stride = sizeof(DescriptorUpdateEntry),
};
-constexpr std::array<VkDescriptorUpdateTemplateEntryKHR, ASTC_NUM_BINDINGS>
+constexpr std::array<VkDescriptorUpdateTemplateEntry, ASTC_NUM_BINDINGS>
ASTC_PASS_DESCRIPTOR_UPDATE_TEMPLATE_ENTRY{{
{
.dstBinding = ASTC_BINDING_INPUT_BUFFER,
@@ -134,7 +134,7 @@ struct AstcPushConstants {
ComputePass::ComputePass(const Device& device_, DescriptorPool& descriptor_pool,
vk::Span<VkDescriptorSetLayoutBinding> bindings,
- vk::Span<VkDescriptorUpdateTemplateEntryKHR> templates,
+ vk::Span<VkDescriptorUpdateTemplateEntry> templates,
const DescriptorBankInfo& bank_info,
vk::Span<VkPushConstantRange> push_constants, std::span<const u32> code)
: device{device_} {
@@ -155,13 +155,13 @@ ComputePass::ComputePass(const Device& device_, DescriptorPool& descriptor_pool,
.pPushConstantRanges = push_constants.data(),
});
if (!templates.empty()) {
- descriptor_template = device.GetLogical().CreateDescriptorUpdateTemplateKHR({
- .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO_KHR,
+ descriptor_template = device.GetLogical().CreateDescriptorUpdateTemplate({
+ .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.descriptorUpdateEntryCount = templates.size(),
.pDescriptorUpdateEntries = templates.data(),
- .templateType = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET_KHR,
+ .templateType = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET,
.descriptorSetLayout = *descriptor_set_layout,
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
.pipelineLayout = *layout,
diff --git a/src/video_core/renderer_vulkan/vk_compute_pass.h b/src/video_core/renderer_vulkan/vk_compute_pass.h
index dcc691a8e..5d32e3caf 100644
--- a/src/video_core/renderer_vulkan/vk_compute_pass.h
+++ b/src/video_core/renderer_vulkan/vk_compute_pass.h
@@ -29,14 +29,14 @@ class ComputePass {
public:
explicit ComputePass(const Device& device, DescriptorPool& descriptor_pool,
vk::Span<VkDescriptorSetLayoutBinding> bindings,
- vk::Span<VkDescriptorUpdateTemplateEntryKHR> templates,
+ vk::Span<VkDescriptorUpdateTemplateEntry> templates,
const DescriptorBankInfo& bank_info,
vk::Span<VkPushConstantRange> push_constants, std::span<const u32> code);
~ComputePass();
protected:
const Device& device;
- vk::DescriptorUpdateTemplateKHR descriptor_template;
+ vk::DescriptorUpdateTemplate descriptor_template;
vk::PipelineLayout layout;
vk::Pipeline pipeline;
vk::DescriptorSetLayout descriptor_set_layout;
diff --git a/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp b/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp
index 7906e11a8..04a3a861e 100644
--- a/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp
+++ b/src/video_core/renderer_vulkan/vk_compute_pipeline.cpp
@@ -53,7 +53,7 @@ ComputePipeline::ComputePipeline(const Device& device_, DescriptorPool& descript
.requiredSubgroupSize = GuestWarpSize,
};
VkPipelineCreateFlags flags{};
- if (device.IsKhrPipelineEexecutablePropertiesEnabled()) {
+ if (device.IsKhrPipelineExecutablePropertiesEnabled()) {
flags |= VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR;
}
pipeline = device.GetLogical().CreateComputePipeline({
diff --git a/src/video_core/renderer_vulkan/vk_compute_pipeline.h b/src/video_core/renderer_vulkan/vk_compute_pipeline.h
index 9879735fe..d70837fc5 100644
--- a/src/video_core/renderer_vulkan/vk_compute_pipeline.h
+++ b/src/video_core/renderer_vulkan/vk_compute_pipeline.h
@@ -55,7 +55,7 @@ private:
vk::DescriptorSetLayout descriptor_set_layout;
DescriptorAllocator descriptor_allocator;
vk::PipelineLayout pipeline_layout;
- vk::DescriptorUpdateTemplateKHR descriptor_update_template;
+ vk::DescriptorUpdateTemplate descriptor_update_template;
vk::Pipeline pipeline;
std::condition_variable build_condvar;
diff --git a/src/video_core/renderer_vulkan/vk_descriptor_pool.cpp b/src/video_core/renderer_vulkan/vk_descriptor_pool.cpp
index c7196b64e..b5ae6443c 100644
--- a/src/video_core/renderer_vulkan/vk_descriptor_pool.cpp
+++ b/src/video_core/renderer_vulkan/vk_descriptor_pool.cpp
@@ -7,6 +7,7 @@
#include <vector>
#include "common/common_types.h"
+#include "common/polyfill_ranges.h"
#include "video_core/renderer_vulkan/vk_descriptor_pool.h"
#include "video_core/renderer_vulkan/vk_resource_pool.h"
#include "video_core/renderer_vulkan/vk_scheduler.h"
diff --git a/src/video_core/renderer_vulkan/vk_fsr.cpp b/src/video_core/renderer_vulkan/vk_fsr.cpp
index dd450169e..33daa8c1c 100644
--- a/src/video_core/renderer_vulkan/vk_fsr.cpp
+++ b/src/video_core/renderer_vulkan/vk_fsr.cpp
@@ -5,6 +5,7 @@
#include "common/bit_cast.h"
#include "common/common_types.h"
#include "common/div_ceil.h"
+#include "common/settings.h"
#include "video_core/host_shaders/vulkan_fidelityfx_fsr_easu_fp16_comp_spv.h"
#include "video_core/host_shaders/vulkan_fidelityfx_fsr_easu_fp32_comp_spv.h"
@@ -227,7 +228,10 @@ VkImageView FSR::Draw(Scheduler& scheduler, size_t image_index, VkImageView imag
cmdbuf.BindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, *rcas_pipeline);
- FsrRcasCon(push_constants.data(), 0.25f);
+ const float sharpening =
+ static_cast<float>(Settings::values.fsr_sharpening_slider.GetValue()) / 100.0f;
+
+ FsrRcasCon(push_constants.data(), sharpening);
cmdbuf.PushConstants(*pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, push_constants);
{
diff --git a/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp b/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp
index ef75c126c..e77a57a4a 100644
--- a/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp
+++ b/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp
@@ -830,7 +830,7 @@ void GraphicsPipeline::MakePipeline(VkRenderPass render_pass) {
*/
}
VkPipelineCreateFlags flags{};
- if (device.IsKhrPipelineEexecutablePropertiesEnabled()) {
+ if (device.IsKhrPipelineExecutablePropertiesEnabled()) {
flags |= VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR;
}
pipeline = device.GetLogical().CreateGraphicsPipeline({
diff --git a/src/video_core/renderer_vulkan/vk_graphics_pipeline.h b/src/video_core/renderer_vulkan/vk_graphics_pipeline.h
index 6bf577d25..1ed2967be 100644
--- a/src/video_core/renderer_vulkan/vk_graphics_pipeline.h
+++ b/src/video_core/renderer_vulkan/vk_graphics_pipeline.h
@@ -151,7 +151,7 @@ private:
vk::DescriptorSetLayout descriptor_set_layout;
DescriptorAllocator descriptor_allocator;
vk::PipelineLayout pipeline_layout;
- vk::DescriptorUpdateTemplateKHR descriptor_update_template;
+ vk::DescriptorUpdateTemplate descriptor_update_template;
vk::Pipeline pipeline;
std::condition_variable build_condvar;
diff --git a/src/video_core/renderer_vulkan/vk_master_semaphore.cpp b/src/video_core/renderer_vulkan/vk_master_semaphore.cpp
index 4e81d3d28..8aa07ef9d 100644
--- a/src/video_core/renderer_vulkan/vk_master_semaphore.cpp
+++ b/src/video_core/renderer_vulkan/vk_master_semaphore.cpp
@@ -11,10 +11,10 @@
namespace Vulkan {
MasterSemaphore::MasterSemaphore(const Device& device) {
- static constexpr VkSemaphoreTypeCreateInfoKHR semaphore_type_ci{
- .sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR,
+ static constexpr VkSemaphoreTypeCreateInfo semaphore_type_ci{
+ .sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO,
.pNext = nullptr,
- .semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR,
+ .semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE,
.initialValue = 0,
};
static constexpr VkSemaphoreCreateInfo semaphore_ci{
@@ -28,7 +28,7 @@ MasterSemaphore::MasterSemaphore(const Device& device) {
return;
}
// Validation layers have a bug where they fail to track resource usage when using timeline
- // semaphores and synchronizing with GetSemaphoreCounterValueKHR. To workaround this issue, have
+ // semaphores and synchronizing with GetSemaphoreCounterValue. To workaround this issue, have
// a separate thread waiting for each timeline semaphore value.
debug_thread = std::jthread([this](std::stop_token stop_token) {
u64 counter = 0;
diff --git a/src/video_core/renderer_vulkan/vk_master_semaphore.h b/src/video_core/renderer_vulkan/vk_master_semaphore.h
index 362ed579a..689f02ea5 100644
--- a/src/video_core/renderer_vulkan/vk_master_semaphore.h
+++ b/src/video_core/renderer_vulkan/vk_master_semaphore.h
@@ -7,6 +7,7 @@
#include <thread>
#include "common/common_types.h"
+#include "common/polyfill_thread.h"
#include "video_core/vulkan_common/vulkan_wrapper.h"
namespace Vulkan {
diff --git a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
index d4b0a542a..38a6b7488 100644
--- a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
@@ -46,6 +46,7 @@ MICROPROFILE_DECLARE(Vulkan_PipelineCache);
namespace {
using Shader::Backend::SPIRV::EmitSPIRV;
using Shader::Maxwell::ConvertLegacyToGeneric;
+using Shader::Maxwell::GenerateGeometryPassthrough;
using Shader::Maxwell::MergeDualVertexPrograms;
using Shader::Maxwell::TranslateProgram;
using VideoCommon::ComputeEnvironment;
@@ -53,13 +54,24 @@ using VideoCommon::FileEnvironment;
using VideoCommon::GenericEnvironment;
using VideoCommon::GraphicsEnvironment;
-constexpr u32 CACHE_VERSION = 7;
+constexpr u32 CACHE_VERSION = 8;
template <typename Container>
auto MakeSpan(Container& container) {
return std::span(container.data(), container.size());
}
+Shader::OutputTopology MaxwellToOutputTopology(Maxwell::PrimitiveTopology topology) {
+ switch (topology) {
+ case Maxwell::PrimitiveTopology::Points:
+ return Shader::OutputTopology::PointList;
+ case Maxwell::PrimitiveTopology::LineStrip:
+ return Shader::OutputTopology::LineStrip;
+ default:
+ return Shader::OutputTopology::TriangleStrip;
+ }
+}
+
Shader::CompareFunction MaxwellToCompareFunction(Maxwell::ComparisonOp comparison) {
switch (comparison) {
case Maxwell::ComparisonOp::Never_D3D:
@@ -275,9 +287,9 @@ PipelineCache::PipelineCache(RasterizerVulkan& rasterizer_, const Device& device
workers(std::max(std::thread::hardware_concurrency(), 2U) - 1, "VkPipelineBuilder"),
serialization_thread(1, "VkPipelineSerialization") {
const auto& float_control{device.FloatControlProperties()};
- const VkDriverIdKHR driver_id{device.GetDriverID()};
+ const VkDriverId driver_id{device.GetDriverID()};
profile = Shader::Profile{
- .supported_spirv = device.IsKhrSpirv1_4Supported() ? 0x00010400U : 0x00010000U,
+ .supported_spirv = device.SupportedSpirvVersion(),
.unified_descriptor_binding = true,
.support_descriptor_aliasing = true,
.support_int8 = device.IsInt8Supported(),
@@ -285,10 +297,10 @@ PipelineCache::PipelineCache(RasterizerVulkan& rasterizer_, const Device& device
.support_int64 = device.IsShaderInt64Supported(),
.support_vertex_instance_id = false,
.support_float_controls = true,
- .support_separate_denorm_behavior = float_control.denormBehaviorIndependence ==
- VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR,
+ .support_separate_denorm_behavior =
+ float_control.denormBehaviorIndependence == VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL,
.support_separate_rounding_mode =
- float_control.roundingModeIndependence == VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR,
+ float_control.roundingModeIndependence == VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL,
.support_fp16_denorm_preserve = float_control.shaderDenormPreserveFloat16 != VK_FALSE,
.support_fp32_denorm_preserve = float_control.shaderDenormPreserveFloat32 != VK_FALSE,
.support_fp16_denorm_flush = float_control.shaderDenormFlushToZeroFloat16 != VK_FALSE,
@@ -315,18 +327,19 @@ PipelineCache::PipelineCache(RasterizerVulkan& rasterizer_, const Device& device
.lower_left_origin_mode = false,
.need_declared_frag_colors = false,
- .has_broken_spirv_clamp = driver_id == VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS_KHR,
+ .has_broken_spirv_clamp = driver_id == VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS,
.has_broken_unsigned_image_offsets = false,
.has_broken_signed_operations = false,
- .has_broken_fp16_float_controls = driver_id == VK_DRIVER_ID_NVIDIA_PROPRIETARY_KHR,
+ .has_broken_fp16_float_controls = driver_id == VK_DRIVER_ID_NVIDIA_PROPRIETARY,
.ignore_nan_fp_comparisons = false,
};
host_info = Shader::HostTranslateInfo{
.support_float16 = device.IsFloat16Supported(),
.support_int64 = device.IsShaderInt64Supported(),
- .needs_demote_reorder = driver_id == VK_DRIVER_ID_AMD_PROPRIETARY_KHR ||
- driver_id == VK_DRIVER_ID_AMD_OPEN_SOURCE_KHR,
+ .needs_demote_reorder =
+ driver_id == VK_DRIVER_ID_AMD_PROPRIETARY || driver_id == VK_DRIVER_ID_AMD_OPEN_SOURCE,
.support_snorm_render_buffer = true,
+ .support_viewport_index_layer = device.IsExtShaderViewportIndexLayerSupported(),
};
}
@@ -395,7 +408,7 @@ void PipelineCache::LoadDiskResources(u64 title_id, std::stop_token stop_loading
std::unique_ptr<PipelineStatistics> statistics;
} state;
- if (device.IsKhrPipelineEexecutablePropertiesEnabled()) {
+ if (device.IsKhrPipelineExecutablePropertiesEnabled()) {
state.statistics = std::make_unique<PipelineStatistics>(device);
}
const auto load_compute{[&](std::ifstream& file, FileEnvironment env) {
@@ -509,7 +522,19 @@ std::unique_ptr<GraphicsPipeline> PipelineCache::CreateGraphicsPipeline(
std::array<Shader::IR::Program, Maxwell::MaxShaderProgram> programs;
const bool uses_vertex_a{key.unique_hashes[0] != 0};
const bool uses_vertex_b{key.unique_hashes[1] != 0};
+
+ // Layer passthrough generation for devices without VK_EXT_shader_viewport_index_layer
+ Shader::IR::Program* layer_source_program{};
+
for (size_t index = 0; index < Maxwell::MaxShaderProgram; ++index) {
+ const bool is_emulated_stage = layer_source_program != nullptr &&
+ index == static_cast<u32>(Maxwell::ShaderType::Geometry);
+ if (key.unique_hashes[index] == 0 && is_emulated_stage) {
+ auto topology = MaxwellToOutputTopology(key.state.topology);
+ programs[index] = GenerateGeometryPassthrough(pools.inst, pools.block, host_info,
+ *layer_source_program, topology);
+ continue;
+ }
if (key.unique_hashes[index] == 0) {
continue;
}
@@ -530,6 +555,10 @@ std::unique_ptr<GraphicsPipeline> PipelineCache::CreateGraphicsPipeline(
auto program_vb{TranslateProgram(pools.inst, pools.block, env, cfg, host_info)};
programs[index] = MergeDualVertexPrograms(program_va, program_vb, env);
}
+
+ if (programs[index].info.requires_layer_emulation) {
+ layer_source_program = &programs[index];
+ }
}
std::array<const Shader::Info*, Maxwell::MaxShaderStage> infos{};
std::array<vk::ShaderModule, Maxwell::MaxShaderStage> modules;
@@ -538,7 +567,9 @@ std::unique_ptr<GraphicsPipeline> PipelineCache::CreateGraphicsPipeline(
Shader::Backend::Bindings binding;
for (size_t index = uses_vertex_a && uses_vertex_b ? 1 : 0; index < Maxwell::MaxShaderProgram;
++index) {
- if (key.unique_hashes[index] == 0) {
+ const bool is_emulated_stage = layer_source_program != nullptr &&
+ index == static_cast<u32>(Maxwell::ShaderType::Geometry);
+ if (key.unique_hashes[index] == 0 && !is_emulated_stage) {
continue;
}
UNIMPLEMENTED_IF(index == 0);
diff --git a/src/video_core/renderer_vulkan/vk_query_cache.cpp b/src/video_core/renderer_vulkan/vk_query_cache.cpp
index 4b15c0f85..929c8ece6 100644
--- a/src/video_core/renderer_vulkan/vk_query_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_query_cache.cpp
@@ -98,7 +98,7 @@ HostCounter::HostCounter(QueryCache& cache_, std::shared_ptr<HostCounter> depend
query{cache_.AllocateQuery(type_)}, tick{cache_.GetScheduler().CurrentTick()} {
const vk::Device* logical = &cache.GetDevice().GetLogical();
cache.GetScheduler().Record([logical, query = query](vk::CommandBuffer cmdbuf) {
- logical->ResetQueryPoolEXT(query.first, query.second, 1);
+ logical->ResetQueryPool(query.first, query.second, 1);
cmdbuf.BeginQuery(query.first, query.second, VK_QUERY_CONTROL_PRECISE_BIT);
});
}
diff --git a/src/video_core/renderer_vulkan/vk_rasterizer.cpp b/src/video_core/renderer_vulkan/vk_rasterizer.cpp
index f69c0c50f..d8ad8815c 100644
--- a/src/video_core/renderer_vulkan/vk_rasterizer.cpp
+++ b/src/video_core/renderer_vulkan/vk_rasterizer.cpp
@@ -191,8 +191,6 @@ void RasterizerVulkan::Draw(bool is_indexed, u32 instance_count) {
pipeline->SetEngine(maxwell3d, gpu_memory);
pipeline->Configure(is_indexed);
- BindInlineIndexBuffer();
-
BeginTransformFeedback();
UpdateDynamicStates();
@@ -213,7 +211,7 @@ void RasterizerVulkan::Draw(bool is_indexed, u32 instance_count) {
EndTransformFeedback();
}
-void RasterizerVulkan::Clear() {
+void RasterizerVulkan::Clear(u32 layer_count) {
MICROPROFILE_SCOPE(Vulkan_Clearing);
if (!maxwell3d->ShouldExecute()) {
@@ -256,7 +254,7 @@ void RasterizerVulkan::Clear() {
.rect = regs.clear_control.use_scissor ? GetScissorState(regs, 0, up_scale, down_shift)
: default_scissor,
.baseArrayLayer = regs.clear_surface.layer,
- .layerCount = 1,
+ .layerCount = layer_count,
};
if (clear_rect.rect.extent.width == 0 || clear_rect.rect.extent.height == 0) {
return;
@@ -544,8 +542,7 @@ bool RasterizerVulkan::AccelerateSurfaceCopy(const Tegra::Engines::Fermi2D::Surf
const Tegra::Engines::Fermi2D::Surface& dst,
const Tegra::Engines::Fermi2D::Config& copy_config) {
std::scoped_lock lock{texture_cache.mutex};
- texture_cache.BlitImage(dst, src, copy_config);
- return true;
+ return texture_cache.BlitImage(dst, src, copy_config);
}
Tegra::Engines::AccelerateDMAInterface& RasterizerVulkan::AccessAccelerateDMA() {
@@ -1029,17 +1026,4 @@ void RasterizerVulkan::ReleaseChannel(s32 channel_id) {
query_cache.EraseChannel(channel_id);
}
-void RasterizerVulkan::BindInlineIndexBuffer() {
- if (maxwell3d->inline_index_draw_indexes.empty()) {
- return;
- }
- const auto data_count = static_cast<u32>(maxwell3d->inline_index_draw_indexes.size());
- auto buffer = buffer_cache_runtime.UploadStagingBuffer(data_count);
- std::memcpy(buffer.mapped_span.data(), maxwell3d->inline_index_draw_indexes.data(), data_count);
- buffer_cache_runtime.BindIndexBuffer(
- maxwell3d->regs.draw.topology, maxwell3d->regs.index_buffer.format,
- maxwell3d->regs.index_buffer.first, maxwell3d->regs.index_buffer.count, buffer.buffer,
- static_cast<u32>(buffer.offset), data_count);
-}
-
} // namespace Vulkan
diff --git a/src/video_core/renderer_vulkan/vk_rasterizer.h b/src/video_core/renderer_vulkan/vk_rasterizer.h
index b0bc306f5..ee483cfd9 100644
--- a/src/video_core/renderer_vulkan/vk_rasterizer.h
+++ b/src/video_core/renderer_vulkan/vk_rasterizer.h
@@ -65,7 +65,7 @@ public:
~RasterizerVulkan() override;
void Draw(bool is_indexed, u32 instance_count) override;
- void Clear() override;
+ void Clear(u32 layer_count) override;
void DispatchCompute() override;
void ResetCounter(VideoCore::QueryType type) override;
void Query(GPUVAddr gpu_addr, VideoCore::QueryType type, std::optional<u64> timestamp) override;
@@ -141,8 +141,6 @@ private:
void UpdateVertexInput(Tegra::Engines::Maxwell3D::Regs& regs);
- void BindInlineIndexBuffer();
-
Tegra::GPU& gpu;
ScreenInfo& screen_info;
diff --git a/src/video_core/renderer_vulkan/vk_render_pass_cache.h b/src/video_core/renderer_vulkan/vk_render_pass_cache.h
index dc21b7e69..91ad4bf57 100644
--- a/src/video_core/renderer_vulkan/vk_render_pass_cache.h
+++ b/src/video_core/renderer_vulkan/vk_render_pass_cache.h
@@ -12,7 +12,7 @@
namespace Vulkan {
struct RenderPassKey {
- auto operator<=>(const RenderPassKey&) const noexcept = default;
+ bool operator==(const RenderPassKey&) const noexcept = default;
std::array<VideoCore::Surface::PixelFormat, 8> color_formats;
VideoCore::Surface::PixelFormat depth_format;
diff --git a/src/video_core/renderer_vulkan/vk_scheduler.cpp b/src/video_core/renderer_vulkan/vk_scheduler.cpp
index 7934f2a51..c2e53a5d5 100644
--- a/src/video_core/renderer_vulkan/vk_scheduler.cpp
+++ b/src/video_core/renderer_vulkan/vk_scheduler.cpp
@@ -145,7 +145,7 @@ void Scheduler::WorkerThread(std::stop_token stop_token) {
if (work_queue.empty()) {
wait_cv.notify_all();
}
- work_cv.wait(lock, stop_token, [this] { return !work_queue.empty(); });
+ Common::CondvarWait(work_cv, lock, stop_token, [&] { return !work_queue.empty(); });
if (stop_token.stop_requested()) {
continue;
}
@@ -194,8 +194,8 @@ void Scheduler::SubmitExecution(VkSemaphore signal_semaphore, VkSemaphore wait_s
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
};
- const VkTimelineSemaphoreSubmitInfoKHR timeline_si{
- .sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR,
+ const VkTimelineSemaphoreSubmitInfo timeline_si{
+ .sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO,
.pNext = nullptr,
.waitSemaphoreValueCount = num_wait_semaphores,
.pWaitSemaphoreValues = wait_values.data(),
@@ -221,6 +221,7 @@ void Scheduler::SubmitExecution(VkSemaphore signal_semaphore, VkSemaphore wait_s
[[fallthrough]];
default:
vk::Check(result);
+ break;
}
});
chunk->MarkSubmit();
diff --git a/src/video_core/renderer_vulkan/vk_scheduler.h b/src/video_core/renderer_vulkan/vk_scheduler.h
index 929216749..3858c506c 100644
--- a/src/video_core/renderer_vulkan/vk_scheduler.h
+++ b/src/video_core/renderer_vulkan/vk_scheduler.h
@@ -12,6 +12,7 @@
#include "common/alignment.h"
#include "common/common_types.h"
+#include "common/polyfill_thread.h"
#include "video_core/renderer_vulkan/vk_master_semaphore.h"
#include "video_core/vulkan_common/vulkan_wrapper.h"
diff --git a/src/video_core/renderer_vulkan/vk_swapchain.cpp b/src/video_core/renderer_vulkan/vk_swapchain.cpp
index 706d9ba74..d7be417f5 100644
--- a/src/video_core/renderer_vulkan/vk_swapchain.cpp
+++ b/src/video_core/renderer_vulkan/vk_swapchain.cpp
@@ -7,6 +7,7 @@
#include <vector>
#include "common/logging/log.h"
+#include "common/polyfill_ranges.h"
#include "common/settings.h"
#include "core/core.h"
#include "video_core/renderer_vulkan/vk_scheduler.h"
diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp
index 853b80d8a..a65bbeb1c 100644
--- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp
@@ -108,6 +108,7 @@ constexpr VkBorderColor ConvertBorderColor(const std::array<float, 4>& color) {
break;
default:
ASSERT_MSG(false, "Invalid surface type");
+ break;
}
}
if (info.storage) {
diff --git a/src/video_core/shader_cache.h b/src/video_core/shader_cache.h
index a4391202d..f3cc4c70b 100644
--- a/src/video_core/shader_cache.h
+++ b/src/video_core/shader_cache.h
@@ -12,6 +12,7 @@
#include <vector>
#include "common/common_types.h"
+#include "common/polyfill_ranges.h"
#include "video_core/control/channel_state_cache.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/shader_environment.h"
diff --git a/src/video_core/shader_environment.cpp b/src/video_core/shader_environment.cpp
index f24f320b6..958810747 100644
--- a/src/video_core/shader_environment.cpp
+++ b/src/video_core/shader_environment.cpp
@@ -15,6 +15,7 @@
#include "common/fs/fs.h"
#include "common/fs/path_util.h"
#include "common/logging/log.h"
+#include "common/polyfill_ranges.h"
#include "shader_recompiler/environment.h"
#include "video_core/engines/kepler_compute.h"
#include "video_core/memory_manager.h"
diff --git a/src/video_core/shader_environment.h b/src/video_core/shader_environment.h
index bb55b029f..1342fab1e 100644
--- a/src/video_core/shader_environment.h
+++ b/src/video_core/shader_environment.h
@@ -10,12 +10,12 @@
#include <memory>
#include <optional>
#include <span>
-#include <stop_token>
#include <type_traits>
#include <unordered_map>
#include <vector>
#include "common/common_types.h"
+#include "common/polyfill_thread.h"
#include "common/unique_function.h"
#include "shader_recompiler/environment.h"
#include "video_core/engines/maxwell_3d.h"
diff --git a/src/video_core/surface.cpp b/src/video_core/surface.cpp
index 6bd133d10..1a76d4178 100644
--- a/src/video_core/surface.cpp
+++ b/src/video_core/surface.cpp
@@ -93,11 +93,14 @@ PixelFormat PixelFormatFromDepthFormat(Tegra::DepthFormat format) {
PixelFormat PixelFormatFromRenderTargetFormat(Tegra::RenderTargetFormat format) {
switch (format) {
- case Tegra::RenderTargetFormat::R32B32G32A32_FLOAT:
+ case Tegra::RenderTargetFormat::R32G32B32A32_FLOAT:
+ case Tegra::RenderTargetFormat::R32G32B32X32_FLOAT:
return PixelFormat::R32G32B32A32_FLOAT;
case Tegra::RenderTargetFormat::R32G32B32A32_SINT:
+ case Tegra::RenderTargetFormat::R32G32B32X32_SINT:
return PixelFormat::R32G32B32A32_SINT;
case Tegra::RenderTargetFormat::R32G32B32A32_UINT:
+ case Tegra::RenderTargetFormat::R32G32B32X32_UINT:
return PixelFormat::R32G32B32A32_UINT;
case Tegra::RenderTargetFormat::R16G16B16A16_UNORM:
return PixelFormat::R16G16B16A16_UNORM;
@@ -118,16 +121,22 @@ PixelFormat PixelFormatFromRenderTargetFormat(Tegra::RenderTargetFormat format)
case Tegra::RenderTargetFormat::R16G16B16X16_FLOAT:
return PixelFormat::R16G16B16X16_FLOAT;
case Tegra::RenderTargetFormat::A8R8G8B8_UNORM:
+ case Tegra::RenderTargetFormat::X8R8G8B8_UNORM:
return PixelFormat::B8G8R8A8_UNORM;
case Tegra::RenderTargetFormat::A8R8G8B8_SRGB:
+ case Tegra::RenderTargetFormat::X8R8G8B8_SRGB:
return PixelFormat::B8G8R8A8_SRGB;
case Tegra::RenderTargetFormat::A2B10G10R10_UNORM:
return PixelFormat::A2B10G10R10_UNORM;
case Tegra::RenderTargetFormat::A2B10G10R10_UINT:
return PixelFormat::A2B10G10R10_UINT;
+ case Tegra::RenderTargetFormat::A2R10G10B10_UNORM:
+ return PixelFormat::A2R10G10B10_UNORM;
case Tegra::RenderTargetFormat::A8B8G8R8_UNORM:
+ case Tegra::RenderTargetFormat::X8B8G8R8_UNORM:
return PixelFormat::A8B8G8R8_UNORM;
case Tegra::RenderTargetFormat::A8B8G8R8_SRGB:
+ case Tegra::RenderTargetFormat::X8B8G8R8_SRGB:
return PixelFormat::A8B8G8R8_SRGB;
case Tegra::RenderTargetFormat::A8B8G8R8_SNORM:
return PixelFormat::A8B8G8R8_SNORM;
@@ -156,6 +165,7 @@ PixelFormat PixelFormatFromRenderTargetFormat(Tegra::RenderTargetFormat format)
case Tegra::RenderTargetFormat::R5G6B5_UNORM:
return PixelFormat::R5G6B5_UNORM;
case Tegra::RenderTargetFormat::A1R5G5B5_UNORM:
+ case Tegra::RenderTargetFormat::X1R5G5B5_UNORM:
return PixelFormat::A1R5G5B5_UNORM;
case Tegra::RenderTargetFormat::R8G8_UNORM:
return PixelFormat::R8G8_UNORM;
@@ -204,23 +214,16 @@ PixelFormat PixelFormatFromGPUPixelFormat(Service::android::PixelFormat format)
}
SurfaceType GetFormatType(PixelFormat pixel_format) {
- if (static_cast<std::size_t>(pixel_format) <
- static_cast<std::size_t>(PixelFormat::MaxColorFormat)) {
+ if (pixel_format < PixelFormat::MaxColorFormat) {
return SurfaceType::ColorTexture;
}
-
- if (static_cast<std::size_t>(pixel_format) <
- static_cast<std::size_t>(PixelFormat::MaxDepthFormat)) {
+ if (pixel_format < PixelFormat::MaxDepthFormat) {
return SurfaceType::Depth;
}
-
- if (static_cast<std::size_t>(pixel_format) <
- static_cast<std::size_t>(PixelFormat::MaxStencilFormat)) {
+ if (pixel_format < PixelFormat::MaxStencilFormat) {
return SurfaceType::Stencil;
}
-
- if (static_cast<std::size_t>(pixel_format) <
- static_cast<std::size_t>(PixelFormat::MaxDepthStencilFormat)) {
+ if (pixel_format < PixelFormat::MaxDepthStencilFormat) {
return SurfaceType::DepthStencil;
}
diff --git a/src/video_core/surface.h b/src/video_core/surface.h
index 57ca7f597..44b79af20 100644
--- a/src/video_core/surface.h
+++ b/src/video_core/surface.h
@@ -23,6 +23,7 @@ enum class PixelFormat {
A1R5G5B5_UNORM,
A2B10G10R10_UNORM,
A2B10G10R10_UINT,
+ A2R10G10B10_UNORM,
A1B5G5R5_UNORM,
A5B5G5R1_UNORM,
R8_UNORM,
@@ -159,6 +160,7 @@ constexpr std::array<u8, MaxPixelFormat> BLOCK_WIDTH_TABLE = {{
1, // A1R5G5B5_UNORM
1, // A2B10G10R10_UNORM
1, // A2B10G10R10_UINT
+ 1, // A2R10G10B10_UNORM
1, // A1B5G5R5_UNORM
1, // A5B5G5R1_UNORM
1, // R8_UNORM
@@ -264,6 +266,7 @@ constexpr std::array<u8, MaxPixelFormat> BLOCK_HEIGHT_TABLE = {{
1, // A1R5G5B5_UNORM
1, // A2B10G10R10_UNORM
1, // A2B10G10R10_UINT
+ 1, // A2R10G10B10_UNORM
1, // A1B5G5R5_UNORM
1, // A5B5G5R1_UNORM
1, // R8_UNORM
@@ -369,6 +372,7 @@ constexpr std::array<u8, MaxPixelFormat> BITS_PER_BLOCK_TABLE = {{
16, // A1R5G5B5_UNORM
32, // A2B10G10R10_UNORM
32, // A2B10G10R10_UINT
+ 32, // A2R10G10B10_UNORM
16, // A1B5G5R5_UNORM
16, // A5B5G5R1_UNORM
8, // R8_UNORM
diff --git a/src/video_core/texture_cache/formatter.cpp b/src/video_core/texture_cache/formatter.cpp
index ee4f2d406..418890126 100644
--- a/src/video_core/texture_cache/formatter.cpp
+++ b/src/video_core/texture_cache/formatter.cpp
@@ -4,6 +4,7 @@
#include <algorithm>
#include <string>
+#include "common/polyfill_ranges.h"
#include "video_core/texture_cache/formatter.h"
#include "video_core/texture_cache/image_base.h"
#include "video_core/texture_cache/image_info.h"
diff --git a/src/video_core/texture_cache/formatter.h b/src/video_core/texture_cache/formatter.h
index acc854715..f1f0a057b 100644
--- a/src/video_core/texture_cache/formatter.h
+++ b/src/video_core/texture_cache/formatter.h
@@ -35,6 +35,8 @@ struct fmt::formatter<VideoCore::Surface::PixelFormat> : fmt::formatter<fmt::str
return "A2B10G10R10_UNORM";
case PixelFormat::A2B10G10R10_UINT:
return "A2B10G10R10_UINT";
+ case PixelFormat::A2R10G10B10_UNORM:
+ return "A2R10G10B10_UNORM";
case PixelFormat::A1B5G5R5_UNORM:
return "A1B5G5R5_UNORM";
case PixelFormat::A5B5G5R1_UNORM:
diff --git a/src/video_core/texture_cache/render_targets.h b/src/video_core/texture_cache/render_targets.h
index 1efbd6507..0829d773a 100644
--- a/src/video_core/texture_cache/render_targets.h
+++ b/src/video_core/texture_cache/render_targets.h
@@ -13,7 +13,7 @@ namespace VideoCommon {
/// Framebuffer properties used to lookup a framebuffer
struct RenderTargets {
- constexpr auto operator<=>(const RenderTargets&) const noexcept = default;
+ constexpr bool operator==(const RenderTargets&) const noexcept = default;
constexpr bool Contains(std::span<const ImageViewId> elements) const noexcept {
const auto contains = [elements](ImageViewId item) {
diff --git a/src/video_core/texture_cache/slot_vector.h b/src/video_core/texture_cache/slot_vector.h
index 46e8a86e6..1e2aad76a 100644
--- a/src/video_core/texture_cache/slot_vector.h
+++ b/src/video_core/texture_cache/slot_vector.h
@@ -12,6 +12,7 @@
#include "common/assert.h"
#include "common/common_types.h"
+#include "common/polyfill_ranges.h"
namespace VideoCommon {
diff --git a/src/video_core/texture_cache/texture_cache.h b/src/video_core/texture_cache/texture_cache.h
index 8ef75fe73..8e68a2e53 100644
--- a/src/video_core/texture_cache/texture_cache.h
+++ b/src/video_core/texture_cache/texture_cache.h
@@ -506,10 +506,14 @@ void TextureCache<P>::UnmapGPUMemory(size_t as_id, GPUVAddr gpu_addr, size_t siz
}
template <class P>
-void TextureCache<P>::BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
+bool TextureCache<P>::BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
const Tegra::Engines::Fermi2D::Surface& src,
const Tegra::Engines::Fermi2D::Config& copy) {
- const BlitImages images = GetBlitImages(dst, src, copy);
+ const auto result = GetBlitImages(dst, src, copy);
+ if (!result) {
+ return false;
+ }
+ const BlitImages images = *result;
const ImageId dst_id = images.dst_id;
const ImageId src_id = images.src_id;
@@ -596,6 +600,7 @@ void TextureCache<P>::BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
runtime.BlitImage(dst_framebuffer, dst_view, src_view, dst_region, src_region, copy.filter,
copy.operation);
}
+ return true;
}
template <class P>
@@ -1133,7 +1138,7 @@ ImageId TextureCache<P>::JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, VA
}
template <class P>
-typename TextureCache<P>::BlitImages TextureCache<P>::GetBlitImages(
+std::optional<typename TextureCache<P>::BlitImages> TextureCache<P>::GetBlitImages(
const Tegra::Engines::Fermi2D::Surface& dst, const Tegra::Engines::Fermi2D::Surface& src,
const Tegra::Engines::Fermi2D::Config& copy) {
@@ -1154,6 +1159,20 @@ typename TextureCache<P>::BlitImages TextureCache<P>::GetBlitImages(
has_deleted_images = false;
src_id = FindImage(src_info, src_addr, try_options);
dst_id = FindImage(dst_info, dst_addr, try_options);
+ if (!copy.must_accelerate) {
+ do {
+ if (!src_id && !dst_id) {
+ return std::nullopt;
+ }
+ if (src_id && True(slot_images[src_id].flags & ImageFlagBits::GpuModified)) {
+ break;
+ }
+ if (dst_id && True(slot_images[dst_id].flags & ImageFlagBits::GpuModified)) {
+ break;
+ }
+ return std::nullopt;
+ } while (false);
+ }
const ImageBase* const src_image = src_id ? &slot_images[src_id] : nullptr;
if (src_image && src_image->info.num_samples > 1) {
RelaxedOptions find_options{FIND_OPTIONS | RelaxedOptions::ForceBrokenViews};
@@ -1194,12 +1213,12 @@ typename TextureCache<P>::BlitImages TextureCache<P>::GetBlitImages(
dst_id = FindOrInsertImage(dst_info, dst_addr, RelaxedOptions{});
} while (has_deleted_images);
}
- return BlitImages{
+ return {BlitImages{
.dst_id = dst_id,
.src_id = src_id,
.dst_format = dst_info.format,
.src_format = src_info.format,
- };
+ }};
}
template <class P>
diff --git a/src/video_core/texture_cache/texture_cache_base.h b/src/video_core/texture_cache/texture_cache_base.h
index 2fa8445eb..587339a31 100644
--- a/src/video_core/texture_cache/texture_cache_base.h
+++ b/src/video_core/texture_cache/texture_cache_base.h
@@ -16,6 +16,7 @@
#include "common/hash.h"
#include "common/literals.h"
#include "common/lru_cache.h"
+#include "common/polyfill_ranges.h"
#include "video_core/compatible_formats.h"
#include "video_core/control/channel_state_cache.h"
#include "video_core/delayed_destruction_ring.h"
@@ -60,8 +61,6 @@ public:
TextureCacheChannelInfo(Tegra::Control::ChannelState& state) noexcept;
TextureCacheChannelInfo(const TextureCacheChannelInfo& state) = delete;
TextureCacheChannelInfo& operator=(const TextureCacheChannelInfo&) = delete;
- TextureCacheChannelInfo(TextureCacheChannelInfo&& other) noexcept = default;
- TextureCacheChannelInfo& operator=(TextureCacheChannelInfo&& other) noexcept = default;
DescriptorTable<TICEntry> graphics_image_table{gpu_memory};
DescriptorTable<TSCEntry> graphics_sampler_table{gpu_memory};
@@ -174,7 +173,7 @@ public:
void UnmapGPUMemory(size_t as_id, GPUVAddr gpu_addr, size_t size);
/// Blit an image with the given parameters
- void BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
+ bool BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
const Tegra::Engines::Fermi2D::Surface& src,
const Tegra::Engines::Fermi2D::Config& copy);
@@ -285,9 +284,9 @@ private:
[[nodiscard]] ImageId JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, VAddr cpu_addr);
/// Return a blit image pair from the given guest blit parameters
- [[nodiscard]] BlitImages GetBlitImages(const Tegra::Engines::Fermi2D::Surface& dst,
- const Tegra::Engines::Fermi2D::Surface& src,
- const Tegra::Engines::Fermi2D::Config& copy);
+ [[nodiscard]] std::optional<BlitImages> GetBlitImages(
+ const Tegra::Engines::Fermi2D::Surface& dst, const Tegra::Engines::Fermi2D::Surface& src,
+ const Tegra::Engines::Fermi2D::Config& copy);
/// Find or create a sampler from a guest descriptor sampler
[[nodiscard]] SamplerId FindSampler(const TSCEntry& config);
diff --git a/src/video_core/textures/astc.cpp b/src/video_core/textures/astc.cpp
index 69a32819a..e8d7c7863 100644
--- a/src/video_core/textures/astc.cpp
+++ b/src/video_core/textures/astc.cpp
@@ -15,6 +15,7 @@
#include "common/alignment.h"
#include "common/common_types.h"
+#include "common/polyfill_ranges.h"
#include "common/thread_worker.h"
#include "video_core/textures/astc.h"
diff --git a/src/video_core/textures/decoders.cpp b/src/video_core/textures/decoders.cpp
index fd1a4b987..59120cd09 100644
--- a/src/video_core/textures/decoders.cpp
+++ b/src/video_core/textures/decoders.cpp
@@ -170,6 +170,7 @@ void Swizzle(std::span<u8> output, std::span<const u8> input, u32 bytes_per_pixe
#undef BPP_CASE
default:
ASSERT_MSG(false, "Invalid bytes_per_pixel={}", bytes_per_pixel);
+ break;
}
}
@@ -217,6 +218,7 @@ void SwizzleSubrect(std::span<u8> output, std::span<const u8> input, u32 bytes_p
#undef BPP_CASE
default:
ASSERT_MSG(false, "Invalid bytes_per_pixel={}", bytes_per_pixel);
+ break;
}
}
@@ -240,6 +242,7 @@ void UnswizzleSubrect(std::span<u8> output, std::span<const u8> input, u32 bytes
#undef BPP_CASE
default:
ASSERT_MSG(false, "Invalid bytes_per_pixel={}", bytes_per_pixel);
+ break;
}
}
diff --git a/src/video_core/transform_feedback.cpp b/src/video_core/transform_feedback.cpp
index 45071185a..155599316 100644
--- a/src/video_core/transform_feedback.cpp
+++ b/src/video_core/transform_feedback.cpp
@@ -7,6 +7,7 @@
#include "common/alignment.h"
#include "common/assert.h"
+#include "common/polyfill_ranges.h"
#include "shader_recompiler/shader_info.h"
#include "video_core/transform_feedback.h"
diff --git a/src/video_core/video_core.cpp b/src/video_core/video_core.cpp
index 04ac4af11..fedb4a7bb 100644
--- a/src/video_core/video_core.cpp
+++ b/src/video_core/video_core.cpp
@@ -7,6 +7,7 @@
#include "common/settings.h"
#include "core/core.h"
#include "video_core/renderer_base.h"
+#include "video_core/renderer_null/renderer_null.h"
#include "video_core/renderer_opengl/renderer_opengl.h"
#include "video_core/renderer_vulkan/renderer_vulkan.h"
#include "video_core/video_core.h"
@@ -26,6 +27,9 @@ std::unique_ptr<VideoCore::RendererBase> CreateRenderer(
case Settings::RendererBackend::Vulkan:
return std::make_unique<Vulkan::RendererVulkan>(telemetry_session, emu_window, cpu_memory,
gpu, std::move(context));
+ case Settings::RendererBackend::Null:
+ return std::make_unique<Null::RendererNull>(emu_window, cpu_memory, gpu,
+ std::move(context));
default:
return nullptr;
}
diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp
index ddecfca13..33856fe59 100644
--- a/src/video_core/vulkan_common/vulkan_device.cpp
+++ b/src/video_core/vulkan_common/vulkan_device.cpp
@@ -12,6 +12,7 @@
#include "common/assert.h"
#include "common/literals.h"
+#include "common/polyfill_ranges.h"
#include "common/settings.h"
#include "video_core/vulkan_common/nsight_aftermath_tracker.h"
#include "video_core/vulkan_common/vulkan_device.h"
@@ -74,23 +75,8 @@ enum class NvidiaArchitecture {
};
constexpr std::array REQUIRED_EXTENSIONS{
- VK_KHR_MAINTENANCE1_EXTENSION_NAME,
- VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME,
- VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME,
- VK_KHR_16BIT_STORAGE_EXTENSION_NAME,
- VK_KHR_8BIT_STORAGE_EXTENSION_NAME,
- VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME,
- VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME,
- VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME,
- VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME,
- VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME,
- VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME,
VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME,
- VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME,
- VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME,
VK_EXT_ROBUSTNESS_2_EXTENSION_NAME,
- VK_EXT_HOST_QUERY_RESET_EXTENSION_NAME,
- VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME,
#ifdef _WIN32
VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME,
#endif
@@ -99,6 +85,17 @@ constexpr std::array REQUIRED_EXTENSIONS{
#endif
};
+constexpr std::array REQUIRED_EXTENSIONS_BEFORE_1_2{
+ VK_KHR_8BIT_STORAGE_EXTENSION_NAME,
+ VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME,
+ VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME,
+ VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME,
+};
+
+constexpr std::array REQUIRED_EXTENSIONS_BEFORE_1_3{
+ VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME,
+};
+
template <typename T>
void SetNext(void**& next, T& data) {
*next = &data;
@@ -308,10 +305,10 @@ NvidiaArchitecture GetNvidiaArchitecture(vk::PhysicalDevice physical,
VkPhysicalDeviceFragmentShadingRatePropertiesKHR shading_rate_props{};
shading_rate_props.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_PROPERTIES_KHR;
- VkPhysicalDeviceProperties2KHR physical_properties{};
- physical_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR;
+ VkPhysicalDeviceProperties2 physical_properties{};
+ physical_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
physical_properties.pNext = &shading_rate_props;
- physical.GetProperties2KHR(physical_properties);
+ physical.GetProperties2(physical_properties);
if (shading_rate_props.primitiveFragmentShadingRateWithMultipleViewports) {
// Only Ampere and newer support this feature
return NvidiaArchitecture::AmpereOrNewer;
@@ -327,7 +324,8 @@ NvidiaArchitecture GetNvidiaArchitecture(vk::PhysicalDevice physical,
Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR surface,
const vk::InstanceDispatch& dld_)
: instance{instance_}, dld{dld_}, physical{physical_}, properties{physical.GetProperties()},
- supported_extensions{GetSupportedExtensions(physical)},
+ instance_version{properties.apiVersion}, supported_extensions{GetSupportedExtensions(
+ physical)},
format_properties(GetFormatProperties(physical)) {
CheckSuitability(surface != nullptr);
SetupFamilies(surface);
@@ -401,15 +399,15 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR
const void* first_next = &features2;
void** next = &features2.pNext;
- VkPhysicalDeviceTimelineSemaphoreFeaturesKHR timeline_semaphore{
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES_KHR,
+ VkPhysicalDeviceTimelineSemaphoreFeatures timeline_semaphore{
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES,
.pNext = nullptr,
.timelineSemaphore = true,
};
SetNext(next, timeline_semaphore);
- VkPhysicalDevice16BitStorageFeaturesKHR bit16_storage{
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR,
+ VkPhysicalDevice16BitStorageFeatures bit16_storage{
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES,
.pNext = nullptr,
.storageBuffer16BitAccess = true,
.uniformAndStorageBuffer16BitAccess = true,
@@ -418,8 +416,8 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR
};
SetNext(next, bit16_storage);
- VkPhysicalDevice8BitStorageFeaturesKHR bit8_storage{
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR,
+ VkPhysicalDevice8BitStorageFeatures bit8_storage{
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES,
.pNext = nullptr,
.storageBuffer8BitAccess = false,
.uniformAndStorageBuffer8BitAccess = true,
@@ -436,32 +434,39 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR
};
SetNext(next, robustness2);
- VkPhysicalDeviceHostQueryResetFeaturesEXT host_query_reset{
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT,
+ VkPhysicalDeviceHostQueryResetFeatures host_query_reset{
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES,
.pNext = nullptr,
.hostQueryReset = true,
};
SetNext(next, host_query_reset);
- VkPhysicalDeviceVariablePointerFeaturesKHR variable_pointers{
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES_KHR,
+ VkPhysicalDeviceVariablePointerFeatures variable_pointers{
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES,
.pNext = nullptr,
.variablePointersStorageBuffer = VK_TRUE,
.variablePointers = VK_TRUE,
};
SetNext(next, variable_pointers);
- VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT demote{
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT,
+ VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures demote{
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES,
.pNext = nullptr,
.shaderDemoteToHelperInvocation = true,
};
SetNext(next, demote);
- VkPhysicalDeviceFloat16Int8FeaturesKHR float16_int8;
+ VkPhysicalDeviceShaderDrawParametersFeatures draw_parameters{
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES,
+ .pNext = nullptr,
+ .shaderDrawParameters = true,
+ };
+ SetNext(next, draw_parameters);
+
+ VkPhysicalDeviceShaderFloat16Int8Features float16_int8;
if (is_int8_supported || is_float16_supported) {
float16_int8 = {
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR,
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES,
.pNext = nullptr,
.shaderFloat16 = is_float16_supported,
.shaderInt8 = is_int8_supported,
@@ -487,10 +492,10 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR
LOG_INFO(Render_Vulkan, "Device doesn't support passthrough geometry shaders");
}
- VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR std430_layout;
+ VkPhysicalDeviceUniformBufferStandardLayoutFeatures std430_layout;
if (khr_uniform_buffer_standard_layout) {
std430_layout = {
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR,
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES,
.pNext = nullptr,
.uniformBufferStandardLayout = true,
};
@@ -608,10 +613,10 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR
LOG_INFO(Render_Vulkan, "Device doesn't support vertex input dynamic state");
}
- VkPhysicalDeviceShaderAtomicInt64FeaturesKHR atomic_int64;
+ VkPhysicalDeviceShaderAtomicInt64Features atomic_int64;
if (ext_shader_atomic_int64) {
atomic_int64 = {
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES_KHR,
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES,
.pNext = nullptr,
.shaderBufferInt64Atomics = VK_TRUE,
.shaderSharedInt64Atomics = VK_TRUE,
@@ -896,28 +901,51 @@ std::string Device::GetDriverName() const {
}
}
+static std::vector<const char*> ExtensionsRequiredForInstanceVersion(u32 available_version) {
+ std::vector<const char*> extensions{REQUIRED_EXTENSIONS.begin(), REQUIRED_EXTENSIONS.end()};
+
+ if (available_version < VK_API_VERSION_1_2) {
+ extensions.insert(extensions.end(), REQUIRED_EXTENSIONS_BEFORE_1_2.begin(),
+ REQUIRED_EXTENSIONS_BEFORE_1_2.end());
+ }
+
+ if (available_version < VK_API_VERSION_1_3) {
+ extensions.insert(extensions.end(), REQUIRED_EXTENSIONS_BEFORE_1_3.begin(),
+ REQUIRED_EXTENSIONS_BEFORE_1_3.end());
+ }
+
+ return extensions;
+}
+
void Device::CheckSuitability(bool requires_swapchain) const {
- std::bitset<REQUIRED_EXTENSIONS.size()> available_extensions;
- bool has_swapchain = false;
- for (const VkExtensionProperties& property : physical.EnumerateDeviceExtensionProperties()) {
- const std::string_view name{property.extensionName};
- for (size_t i = 0; i < REQUIRED_EXTENSIONS.size(); ++i) {
- if (available_extensions[i]) {
- continue;
- }
- available_extensions[i] = name == REQUIRED_EXTENSIONS[i];
- }
- has_swapchain = has_swapchain || name == VK_KHR_SWAPCHAIN_EXTENSION_NAME;
+ std::vector<const char*> required_extensions =
+ ExtensionsRequiredForInstanceVersion(instance_version);
+ std::vector<const char*> available_extensions;
+
+ if (requires_swapchain) {
+ required_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
}
- for (size_t i = 0; i < REQUIRED_EXTENSIONS.size(); ++i) {
- if (available_extensions[i]) {
- continue;
+
+ auto extension_properties = physical.EnumerateDeviceExtensionProperties();
+
+ for (const VkExtensionProperties& property : extension_properties) {
+ available_extensions.push_back(property.extensionName);
+ }
+
+ bool has_all_required_extensions = true;
+ for (const char* requirement_name : required_extensions) {
+ const bool found =
+ std::ranges::any_of(available_extensions, [&](const char* extension_name) {
+ return std::strcmp(requirement_name, extension_name) == 0;
+ });
+
+ if (!found) {
+ LOG_ERROR(Render_Vulkan, "Missing required extension: {}", requirement_name);
+ has_all_required_extensions = false;
}
- LOG_ERROR(Render_Vulkan, "Missing required extension: {}", REQUIRED_EXTENSIONS[i]);
- throw vk::Exception(VK_ERROR_EXTENSION_NOT_PRESENT);
}
- if (requires_swapchain && !has_swapchain) {
- LOG_ERROR(Render_Vulkan, "Missing required extension: VK_KHR_swapchain");
+
+ if (!has_all_required_extensions) {
throw vk::Exception(VK_ERROR_EXTENSION_NOT_PRESENT);
}
@@ -940,27 +968,46 @@ void Device::CheckSuitability(bool requires_swapchain) const {
throw vk::Exception(VK_ERROR_FEATURE_NOT_PRESENT);
}
}
- VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT demote{};
- demote.sType =
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT;
+ VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures demote{};
+ demote.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES;
demote.pNext = nullptr;
- VkPhysicalDeviceVariablePointerFeaturesKHR variable_pointers{};
- variable_pointers.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES_KHR;
+ VkPhysicalDeviceVariablePointerFeatures variable_pointers{};
+ variable_pointers.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES;
variable_pointers.pNext = &demote;
VkPhysicalDeviceRobustness2FeaturesEXT robustness2{};
robustness2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT;
robustness2.pNext = &variable_pointers;
- VkPhysicalDeviceFeatures2KHR features2{};
+ VkPhysicalDeviceTimelineSemaphoreFeatures timeline_semaphore{};
+ timeline_semaphore.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES;
+ timeline_semaphore.pNext = &robustness2;
+
+ VkPhysicalDevice16BitStorageFeatures bit16_storage{};
+ bit16_storage.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES;
+ bit16_storage.pNext = &timeline_semaphore;
+
+ VkPhysicalDevice8BitStorageFeatures bit8_storage{};
+ bit8_storage.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES;
+ bit8_storage.pNext = &bit16_storage;
+
+ VkPhysicalDeviceHostQueryResetFeatures host_query_reset{};
+ host_query_reset.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES;
+ host_query_reset.pNext = &bit8_storage;
+
+ VkPhysicalDeviceShaderDrawParametersFeatures draw_parameters{};
+ draw_parameters.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES;
+ draw_parameters.pNext = &host_query_reset;
+
+ VkPhysicalDeviceFeatures2 features2{};
features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
- features2.pNext = &robustness2;
+ features2.pNext = &draw_parameters;
- physical.GetFeatures2KHR(features2);
+ physical.GetFeatures2(features2);
const VkPhysicalDeviceFeatures& features{features2.features};
- const std::array feature_report{
+ std::array feature_report{
std::make_pair(features.robustBufferAccess, "robustBufferAccess"),
std::make_pair(features.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics"),
std::make_pair(features.imageCubeArray, "imageCubeArray"),
@@ -976,6 +1023,7 @@ void Device::CheckSuitability(bool requires_swapchain) const {
std::make_pair(features.tessellationShader, "tessellationShader"),
std::make_pair(features.sampleRateShading, "sampleRateShading"),
std::make_pair(features.dualSrcBlend, "dualSrcBlend"),
+ std::make_pair(features.logicOp, "logicOp"),
std::make_pair(features.occlusionQueryPrecise, "occlusionQueryPrecise"),
std::make_pair(features.fragmentStoresAndAtomics, "fragmentStoresAndAtomics"),
std::make_pair(features.shaderImageGatherExtended, "shaderImageGatherExtended"),
@@ -983,27 +1031,38 @@ void Device::CheckSuitability(bool requires_swapchain) const {
"shaderStorageImageWriteWithoutFormat"),
std::make_pair(features.shaderClipDistance, "shaderClipDistance"),
std::make_pair(features.shaderCullDistance, "shaderCullDistance"),
- std::make_pair(demote.shaderDemoteToHelperInvocation, "shaderDemoteToHelperInvocation"),
std::make_pair(variable_pointers.variablePointers, "variablePointers"),
std::make_pair(variable_pointers.variablePointersStorageBuffer,
"variablePointersStorageBuffer"),
std::make_pair(robustness2.robustBufferAccess2, "robustBufferAccess2"),
std::make_pair(robustness2.robustImageAccess2, "robustImageAccess2"),
std::make_pair(robustness2.nullDescriptor, "nullDescriptor"),
+ std::make_pair(demote.shaderDemoteToHelperInvocation, "shaderDemoteToHelperInvocation"),
+ std::make_pair(timeline_semaphore.timelineSemaphore, "timelineSemaphore"),
+ std::make_pair(bit16_storage.storageBuffer16BitAccess, "storageBuffer16BitAccess"),
+ std::make_pair(bit16_storage.uniformAndStorageBuffer16BitAccess,
+ "uniformAndStorageBuffer16BitAccess"),
+ std::make_pair(bit8_storage.uniformAndStorageBuffer8BitAccess,
+ "uniformAndStorageBuffer8BitAccess"),
+ std::make_pair(host_query_reset.hostQueryReset, "hostQueryReset"),
+ std::make_pair(draw_parameters.shaderDrawParameters, "shaderDrawParameters"),
};
+
+ bool has_all_required_features = true;
for (const auto& [is_supported, name] : feature_report) {
- if (is_supported) {
- continue;
+ if (!is_supported) {
+ LOG_ERROR(Render_Vulkan, "Missing required feature: {}", name);
+ has_all_required_features = false;
}
- LOG_ERROR(Render_Vulkan, "Missing required feature: {}", name);
+ }
+
+ if (!has_all_required_features) {
throw vk::Exception(VK_ERROR_FEATURE_NOT_PRESENT);
}
}
std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
- std::vector<const char*> extensions;
- extensions.reserve(8 + REQUIRED_EXTENSIONS.size());
- extensions.insert(extensions.begin(), REQUIRED_EXTENSIONS.begin(), REQUIRED_EXTENSIONS.end());
+ std::vector<const char*> extensions = ExtensionsRequiredForInstanceVersion(instance_version);
if (requires_surface) {
extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
}
@@ -1079,37 +1138,37 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, false);
}
}
- VkPhysicalDeviceFeatures2KHR features{};
- features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR;
+ VkPhysicalDeviceFeatures2 features{};
+ features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
- VkPhysicalDeviceProperties2KHR physical_properties{};
- physical_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR;
+ VkPhysicalDeviceProperties2 physical_properties{};
+ physical_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
if (has_khr_shader_float16_int8) {
- VkPhysicalDeviceFloat16Int8FeaturesKHR float16_int8_features;
- float16_int8_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR;
+ VkPhysicalDeviceShaderFloat16Int8Features float16_int8_features;
+ float16_int8_features.sType =
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES;
float16_int8_features.pNext = nullptr;
features.pNext = &float16_int8_features;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
is_float16_supported = float16_int8_features.shaderFloat16;
is_int8_supported = float16_int8_features.shaderInt8;
extensions.push_back(VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME);
}
if (has_ext_subgroup_size_control) {
- VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_features;
- subgroup_features.sType =
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
+ VkPhysicalDeviceSubgroupSizeControlFeatures subgroup_features;
+ subgroup_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES;
subgroup_features.pNext = nullptr;
features.pNext = &subgroup_features;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
- VkPhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_properties;
+ VkPhysicalDeviceSubgroupSizeControlProperties subgroup_properties;
subgroup_properties.sType =
- VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES_EXT;
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES;
subgroup_properties.pNext = nullptr;
physical_properties.pNext = &subgroup_properties;
- physical.GetProperties2KHR(physical_properties);
+ physical.GetProperties2(physical_properties);
is_warp_potentially_bigger = subgroup_properties.maxSubgroupSize > GuestWarpSize;
@@ -1128,7 +1187,7 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
provoking_vertex.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_FEATURES_EXT;
provoking_vertex.pNext = nullptr;
features.pNext = &provoking_vertex;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
if (provoking_vertex.provokingVertexLast &&
provoking_vertex.transformFeedbackPreservesProvokingVertex) {
@@ -1142,7 +1201,7 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_INPUT_DYNAMIC_STATE_FEATURES_EXT;
vertex_input.pNext = nullptr;
features.pNext = &vertex_input;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
if (vertex_input.vertexInputDynamicState) {
extensions.push_back(VK_EXT_VERTEX_INPUT_DYNAMIC_STATE_EXTENSION_NAME);
@@ -1154,7 +1213,7 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
atomic_int64.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES;
atomic_int64.pNext = nullptr;
features.pNext = &atomic_int64;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
if (atomic_int64.shaderBufferInt64Atomics && atomic_int64.shaderSharedInt64Atomics) {
extensions.push_back(VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME);
@@ -1166,13 +1225,13 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
tfb_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT;
tfb_features.pNext = nullptr;
features.pNext = &tfb_features;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
VkPhysicalDeviceTransformFeedbackPropertiesEXT tfb_properties;
tfb_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT;
tfb_properties.pNext = nullptr;
physical_properties.pNext = &tfb_properties;
- physical.GetProperties2KHR(physical_properties);
+ physical.GetProperties2(physical_properties);
if (tfb_features.transformFeedback && tfb_features.geometryStreams &&
tfb_properties.maxTransformFeedbackStreams >= 4 &&
@@ -1187,7 +1246,7 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
border_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT;
border_features.pNext = nullptr;
features.pNext = &border_features;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
if (border_features.customBorderColors && border_features.customBorderColorWithoutFormat) {
extensions.push_back(VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME);
@@ -1200,7 +1259,7 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT;
extended_dynamic_state.pNext = nullptr;
features.pNext = &extended_dynamic_state;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
if (extended_dynamic_state.extendedDynamicState) {
extensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME);
@@ -1212,7 +1271,7 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
line_raster.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINE_RASTERIZATION_FEATURES_EXT;
line_raster.pNext = nullptr;
features.pNext = &line_raster;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
if (line_raster.rectangularLines && line_raster.smoothLines) {
extensions.push_back(VK_EXT_LINE_RASTERIZATION_EXTENSION_NAME);
ext_line_rasterization = true;
@@ -1224,7 +1283,7 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_WORKGROUP_MEMORY_EXPLICIT_LAYOUT_FEATURES_KHR;
layout.pNext = nullptr;
features.pNext = &layout;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
if (layout.workgroupMemoryExplicitLayout &&
layout.workgroupMemoryExplicitLayout8BitAccess &&
@@ -1240,7 +1299,7 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
executable_properties.pNext = nullptr;
features.pNext = &executable_properties;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
if (executable_properties.pipelineExecutableInfo) {
extensions.push_back(VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME);
@@ -1253,7 +1312,7 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIMITIVE_TOPOLOGY_LIST_RESTART_FEATURES_EXT;
primitive_topology_list_restart.pNext = nullptr;
features.pNext = &primitive_topology_list_restart;
- physical.GetFeatures2KHR(features);
+ physical.GetFeatures2(features);
is_topology_list_restart_supported =
primitive_topology_list_restart.primitiveTopologyListRestart;
@@ -1271,7 +1330,7 @@ std::vector<const char*> Device::LoadExtensions(bool requires_surface) {
push_descriptor.pNext = nullptr;
physical_properties.pNext = &push_descriptor;
- physical.GetProperties2KHR(physical_properties);
+ physical.GetProperties2(physical_properties);
max_push_descriptors = push_descriptor.maxPushDescriptors;
}
@@ -1322,18 +1381,18 @@ void Device::SetupFeatures() {
}
void Device::SetupProperties() {
- float_controls.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES_KHR;
+ float_controls.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES;
VkPhysicalDeviceProperties2KHR properties2{};
- properties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR;
+ properties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
properties2.pNext = &float_controls;
- physical.GetProperties2KHR(properties2);
+ physical.GetProperties2(properties2);
}
void Device::CollectTelemetryParameters() {
- VkPhysicalDeviceDriverPropertiesKHR driver{
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR,
+ VkPhysicalDeviceDriverProperties driver{
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES,
.pNext = nullptr,
.driverID = {},
.driverName = {},
@@ -1341,12 +1400,12 @@ void Device::CollectTelemetryParameters() {
.conformanceVersion = {},
};
- VkPhysicalDeviceProperties2KHR device_properties{
- .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR,
+ VkPhysicalDeviceProperties2 device_properties{
+ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,
.pNext = &driver,
.properties = {},
};
- physical.GetProperties2KHR(device_properties);
+ physical.GetProperties2(device_properties);
driver_id = driver.driverID;
vendor_name = driver.driverName;
@@ -1402,23 +1461,10 @@ void Device::CollectToolingInfo() {
if (!ext_tooling_info) {
return;
}
- const auto vkGetPhysicalDeviceToolPropertiesEXT =
- reinterpret_cast<PFN_vkGetPhysicalDeviceToolPropertiesEXT>(
- dld.vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceToolPropertiesEXT"));
- if (!vkGetPhysicalDeviceToolPropertiesEXT) {
- return;
- }
- u32 tool_count = 0;
- if (vkGetPhysicalDeviceToolPropertiesEXT(physical, &tool_count, nullptr) != VK_SUCCESS) {
- return;
- }
- std::vector<VkPhysicalDeviceToolPropertiesEXT> tools(tool_count);
- if (vkGetPhysicalDeviceToolPropertiesEXT(physical, &tool_count, tools.data()) != VK_SUCCESS) {
- return;
- }
- for (const VkPhysicalDeviceToolPropertiesEXT& tool : tools) {
+ auto tools{physical.GetPhysicalDeviceToolProperties()};
+ for (const VkPhysicalDeviceToolProperties& tool : tools) {
const std::string_view name = tool.name;
- LOG_INFO(Render_Vulkan, "{}", name);
+ LOG_INFO(Render_Vulkan, "Attached debugging tool: {}", name);
has_renderdoc = has_renderdoc || name == "RenderDoc";
has_nsight_graphics = has_nsight_graphics || name == "NVIDIA Nsight Graphics";
}
diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h
index d7cc6c593..db802437c 100644
--- a/src/video_core/vulkan_common/vulkan_device.h
+++ b/src/video_core/vulkan_common/vulkan_device.h
@@ -211,18 +211,13 @@ public:
return khr_uniform_buffer_standard_layout;
}
- /// Returns true if the device supports VK_KHR_spirv_1_4.
- bool IsKhrSpirv1_4Supported() const {
- return khr_spirv_1_4;
- }
-
/// Returns true if the device supports VK_KHR_push_descriptor.
bool IsKhrPushDescriptorSupported() const {
return khr_push_descriptor;
}
/// Returns true if VK_KHR_pipeline_executable_properties is enabled.
- bool IsKhrPipelineEexecutablePropertiesEnabled() const {
+ bool IsKhrPipelineExecutablePropertiesEnabled() const {
return khr_pipeline_executable_properties;
}
@@ -316,6 +311,17 @@ public:
return ext_shader_atomic_int64;
}
+ /// Returns the minimum supported version of SPIR-V.
+ u32 SupportedSpirvVersion() const {
+ if (instance_version >= VK_API_VERSION_1_3) {
+ return 0x00010600U;
+ }
+ if (khr_spirv_1_4) {
+ return 0x00010400U;
+ }
+ return 0x00010000U;
+ }
+
/// Returns true when a known debugging tool is attached.
bool HasDebuggingToolAttached() const {
return has_renderdoc || has_nsight_graphics;
diff --git a/src/video_core/vulkan_common/vulkan_instance.cpp b/src/video_core/vulkan_common/vulkan_instance.cpp
index a082e3059..562039b56 100644
--- a/src/video_core/vulkan_common/vulkan_instance.cpp
+++ b/src/video_core/vulkan_common/vulkan_instance.cpp
@@ -9,18 +9,21 @@
#include "common/common_types.h"
#include "common/dynamic_library.h"
#include "common/logging/log.h"
+#include "common/polyfill_ranges.h"
#include "core/frontend/emu_window.h"
#include "video_core/vulkan_common/vulkan_instance.h"
#include "video_core/vulkan_common/vulkan_wrapper.h"
// Include these late to avoid polluting previous headers
-#ifdef _WIN32
+#if defined(_WIN32)
#include <windows.h>
// ensure include order
#include <vulkan/vulkan_win32.h>
-#endif
-
-#if !defined(_WIN32) && !defined(__APPLE__)
+#elif defined(__APPLE__)
+#include <vulkan/vulkan_macos.h>
+#elif defined(__ANDROID__)
+#include <vulkan/vulkan_android.h>
+#else
#include <X11/Xlib.h>
#include <vulkan/vulkan_wayland.h>
#include <vulkan/vulkan_xlib.h>
@@ -39,8 +42,15 @@ namespace {
case Core::Frontend::WindowSystemType::Windows:
extensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
break;
-#endif
-#if !defined(_WIN32) && !defined(__APPLE__)
+#elif defined(__APPLE__)
+ case Core::Frontend::WindowSystemType::Cocoa:
+ extensions.push_back(VK_MVK_MACOS_SURFACE_EXTENSION_NAME);
+ break;
+#elif defined(__ANDROID__)
+ case Core::Frontend::WindowSystemType::Android:
+ extensions.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME);
+ break;
+#else
case Core::Frontend::WindowSystemType::X11:
extensions.push_back(VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
break;
@@ -59,6 +69,10 @@ namespace {
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
+
+#ifdef __APPLE__
+ extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
+#endif
return extensions;
}
@@ -140,7 +154,7 @@ vk::Instance CreateInstance(const Common::DynamicLibrary& library, vk::InstanceD
}
vk::Instance instance =
std::async([&] {
- return vk::Instance::Create(required_version, layers, extensions, dld);
+ return vk::Instance::Create(available_version, layers, extensions, dld);
}).get();
if (!vk::Load(*instance, dld)) {
LOG_ERROR(Render_Vulkan, "Failed to load Vulkan instance function pointers");
diff --git a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp
index 6442898bd..1732866e0 100644
--- a/src/video_core/vulkan_common/vulkan_memory_allocator.cpp
+++ b/src/video_core/vulkan_common/vulkan_memory_allocator.cpp
@@ -12,6 +12,7 @@
#include "common/assert.h"
#include "common/common_types.h"
#include "common/logging/log.h"
+#include "common/polyfill_ranges.h"
#include "video_core/vulkan_common/vulkan_device.h"
#include "video_core/vulkan_common/vulkan_memory_allocator.h"
#include "video_core/vulkan_common/vulkan_wrapper.h"
diff --git a/src/video_core/vulkan_common/vulkan_surface.cpp b/src/video_core/vulkan_common/vulkan_surface.cpp
index 69f9c494b..fa9bafa20 100644
--- a/src/video_core/vulkan_common/vulkan_surface.cpp
+++ b/src/video_core/vulkan_common/vulkan_surface.cpp
@@ -11,9 +11,11 @@
#include <windows.h>
// ensure include order
#include <vulkan/vulkan_win32.h>
-#endif
-
-#if !defined(_WIN32) && !defined(__APPLE__)
+#elif defined(__APPLE__)
+#include <vulkan/vulkan_macos.h>
+#elif defined(__ANDROID__)
+#include <vulkan/vulkan_android.h>
+#else
#include <X11/Xlib.h>
#include <vulkan/vulkan_wayland.h>
#include <vulkan/vulkan_xlib.h>
@@ -40,8 +42,33 @@ vk::SurfaceKHR CreateSurface(const vk::Instance& instance,
throw vk::Exception(VK_ERROR_INITIALIZATION_FAILED);
}
}
-#endif
-#if !defined(_WIN32) && !defined(__APPLE__)
+#elif defined(__APPLE__)
+ if (window_info.type == Core::Frontend::WindowSystemType::Cocoa) {
+ const VkMacOSSurfaceCreateInfoMVK mvk_ci{VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK,
+ nullptr, 0, window_info.render_surface};
+ const auto vkCreateMacOSSurfaceMVK = reinterpret_cast<PFN_vkCreateMacOSSurfaceMVK>(
+ dld.vkGetInstanceProcAddr(*instance, "vkCreateMacOSSurfaceMVK"));
+ if (!vkCreateMacOSSurfaceMVK ||
+ vkCreateMacOSSurfaceMVK(*instance, &mvk_ci, nullptr, &unsafe_surface) != VK_SUCCESS) {
+ LOG_ERROR(Render_Vulkan, "Failed to initialize Metal surface");
+ throw vk::Exception(VK_ERROR_INITIALIZATION_FAILED);
+ }
+ }
+#elif defined(__ANDROID__)
+ if (window_info.type == Core::Frontend::WindowSystemType::Android) {
+ const VkAndroidSurfaceCreateInfoKHR android_ci{
+ VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR, nullptr, 0,
+ reinterpret_cast<ANativeWindow*>(window_info.render_surface)};
+ const auto vkCreateAndroidSurfaceKHR = reinterpret_cast<PFN_vkCreateAndroidSurfaceKHR>(
+ dld.vkGetInstanceProcAddr(*instance, "vkCreateAndroidSurfaceKHR"));
+ if (!vkCreateAndroidSurfaceKHR ||
+ vkCreateAndroidSurfaceKHR(*instance, &android_ci, nullptr, &unsafe_surface) !=
+ VK_SUCCESS) {
+ LOG_ERROR(Render_Vulkan, "Failed to initialize Android surface");
+ throw vk::Exception(VK_ERROR_INITIALIZATION_FAILED);
+ }
+ }
+#else
if (window_info.type == Core::Frontend::WindowSystemType::X11) {
const VkXlibSurfaceCreateInfoKHR xlib_ci{
VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR, nullptr, 0,
@@ -70,6 +97,7 @@ vk::SurfaceKHR CreateSurface(const vk::Instance& instance,
}
}
#endif
+
if (!unsafe_surface) {
LOG_ERROR(Render_Vulkan, "Presentation not supported on this platform");
throw vk::Exception(VK_ERROR_INITIALIZATION_FAILED);
diff --git a/src/video_core/vulkan_common/vulkan_wrapper.cpp b/src/video_core/vulkan_common/vulkan_wrapper.cpp
index 2ad98dcfe..e4a07813f 100644
--- a/src/video_core/vulkan_common/vulkan_wrapper.cpp
+++ b/src/video_core/vulkan_common/vulkan_wrapper.cpp
@@ -130,7 +130,7 @@ void Load(VkDevice device, DeviceDispatch& dld) noexcept {
X(vkCreateComputePipelines);
X(vkCreateDescriptorPool);
X(vkCreateDescriptorSetLayout);
- X(vkCreateDescriptorUpdateTemplateKHR);
+ X(vkCreateDescriptorUpdateTemplate);
X(vkCreateEvent);
X(vkCreateFence);
X(vkCreateFramebuffer);
@@ -149,7 +149,7 @@ void Load(VkDevice device, DeviceDispatch& dld) noexcept {
X(vkDestroyCommandPool);
X(vkDestroyDescriptorPool);
X(vkDestroyDescriptorSetLayout);
- X(vkDestroyDescriptorUpdateTemplateKHR);
+ X(vkDestroyDescriptorUpdateTemplate);
X(vkDestroyEvent);
X(vkDestroyFence);
X(vkDestroyFramebuffer);
@@ -180,18 +180,29 @@ void Load(VkDevice device, DeviceDispatch& dld) noexcept {
X(vkGetQueryPoolResults);
X(vkGetPipelineExecutablePropertiesKHR);
X(vkGetPipelineExecutableStatisticsKHR);
- X(vkGetSemaphoreCounterValueKHR);
+ X(vkGetSemaphoreCounterValue);
X(vkMapMemory);
X(vkQueueSubmit);
X(vkResetFences);
- X(vkResetQueryPoolEXT);
+ X(vkResetQueryPool);
X(vkSetDebugUtilsObjectNameEXT);
X(vkSetDebugUtilsObjectTagEXT);
X(vkUnmapMemory);
- X(vkUpdateDescriptorSetWithTemplateKHR);
+ X(vkUpdateDescriptorSetWithTemplate);
X(vkUpdateDescriptorSets);
X(vkWaitForFences);
- X(vkWaitSemaphoresKHR);
+ X(vkWaitSemaphores);
+
+ // Support for timeline semaphores is mandatory in Vulkan 1.2
+ if (!dld.vkGetSemaphoreCounterValue) {
+ Proc(dld.vkGetSemaphoreCounterValue, dld, "vkGetSemaphoreCounterValueKHR", device);
+ Proc(dld.vkWaitSemaphores, dld, "vkWaitSemaphoresKHR", device);
+ }
+
+ // Support for host query reset is mandatory in Vulkan 1.2
+ if (!dld.vkResetQueryPool) {
+ Proc(dld.vkResetQueryPool, dld, "vkResetQueryPoolEXT", device);
+ }
#undef X
}
@@ -224,12 +235,13 @@ bool Load(VkInstance instance, InstanceDispatch& dld) noexcept {
X(vkCreateDebugUtilsMessengerEXT);
X(vkDestroyDebugUtilsMessengerEXT);
X(vkDestroySurfaceKHR);
- X(vkGetPhysicalDeviceFeatures2KHR);
- X(vkGetPhysicalDeviceProperties2KHR);
+ X(vkGetPhysicalDeviceFeatures2);
+ X(vkGetPhysicalDeviceProperties2);
X(vkGetPhysicalDeviceSurfaceCapabilitiesKHR);
X(vkGetPhysicalDeviceSurfaceFormatsKHR);
X(vkGetPhysicalDeviceSurfacePresentModesKHR);
X(vkGetPhysicalDeviceSurfaceSupportKHR);
+ X(vkGetPhysicalDeviceToolProperties);
X(vkGetSwapchainImagesKHR);
X(vkQueuePresentKHR);
@@ -359,9 +371,9 @@ void Destroy(VkDevice device, VkDescriptorSetLayout handle, const DeviceDispatch
dld.vkDestroyDescriptorSetLayout(device, handle, nullptr);
}
-void Destroy(VkDevice device, VkDescriptorUpdateTemplateKHR handle,
+void Destroy(VkDevice device, VkDescriptorUpdateTemplate handle,
const DeviceDispatch& dld) noexcept {
- dld.vkDestroyDescriptorUpdateTemplateKHR(device, handle, nullptr);
+ dld.vkDestroyDescriptorUpdateTemplate(device, handle, nullptr);
}
void Destroy(VkDevice device, VkDeviceMemory handle, const DeviceDispatch& dld) noexcept {
@@ -737,11 +749,11 @@ CommandPool Device::CreateCommandPool(const VkCommandPoolCreateInfo& ci) const {
return CommandPool(object, handle, *dld);
}
-DescriptorUpdateTemplateKHR Device::CreateDescriptorUpdateTemplateKHR(
- const VkDescriptorUpdateTemplateCreateInfoKHR& ci) const {
- VkDescriptorUpdateTemplateKHR object;
- Check(dld->vkCreateDescriptorUpdateTemplateKHR(handle, &ci, nullptr, &object));
- return DescriptorUpdateTemplateKHR(object, handle, *dld);
+DescriptorUpdateTemplate Device::CreateDescriptorUpdateTemplate(
+ const VkDescriptorUpdateTemplateCreateInfo& ci) const {
+ VkDescriptorUpdateTemplate object;
+ Check(dld->vkCreateDescriptorUpdateTemplate(handle, &ci, nullptr, &object));
+ return DescriptorUpdateTemplate(object, handle, *dld);
}
QueryPool Device::CreateQueryPool(const VkQueryPoolCreateInfo& ci) const {
@@ -857,20 +869,20 @@ VkPhysicalDeviceProperties PhysicalDevice::GetProperties() const noexcept {
return properties;
}
-void PhysicalDevice::GetProperties2KHR(VkPhysicalDeviceProperties2KHR& properties) const noexcept {
- dld->vkGetPhysicalDeviceProperties2KHR(physical_device, &properties);
+void PhysicalDevice::GetProperties2(VkPhysicalDeviceProperties2& properties) const noexcept {
+ dld->vkGetPhysicalDeviceProperties2(physical_device, &properties);
}
VkPhysicalDeviceFeatures PhysicalDevice::GetFeatures() const noexcept {
- VkPhysicalDeviceFeatures2KHR features2;
- features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR;
+ VkPhysicalDeviceFeatures2 features2;
+ features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
features2.pNext = nullptr;
- dld->vkGetPhysicalDeviceFeatures2KHR(physical_device, &features2);
+ dld->vkGetPhysicalDeviceFeatures2(physical_device, &features2);
return features2.features;
}
-void PhysicalDevice::GetFeatures2KHR(VkPhysicalDeviceFeatures2KHR& features) const noexcept {
- dld->vkGetPhysicalDeviceFeatures2KHR(physical_device, &features);
+void PhysicalDevice::GetFeatures2(VkPhysicalDeviceFeatures2& features) const noexcept {
+ dld->vkGetPhysicalDeviceFeatures2(physical_device, &features);
}
VkFormatProperties PhysicalDevice::GetFormatProperties(VkFormat format) const noexcept {
@@ -895,6 +907,18 @@ std::vector<VkQueueFamilyProperties> PhysicalDevice::GetQueueFamilyProperties()
return properties;
}
+std::vector<VkPhysicalDeviceToolProperties> PhysicalDevice::GetPhysicalDeviceToolProperties()
+ const {
+ u32 num = 0;
+ if (!dld->vkGetPhysicalDeviceToolProperties) {
+ return {};
+ }
+ dld->vkGetPhysicalDeviceToolProperties(physical_device, &num, nullptr);
+ std::vector<VkPhysicalDeviceToolProperties> properties(num);
+ dld->vkGetPhysicalDeviceToolProperties(physical_device, &num, properties.data());
+ return properties;
+}
+
bool PhysicalDevice::GetSurfaceSupportKHR(u32 queue_family_index, VkSurfaceKHR surface) const {
VkBool32 supported;
Check(dld->vkGetPhysicalDeviceSurfaceSupportKHR(physical_device, queue_family_index, surface,
diff --git a/src/video_core/vulkan_common/vulkan_wrapper.h b/src/video_core/vulkan_common/vulkan_wrapper.h
index 1b3f493bd..8395ff2cb 100644
--- a/src/video_core/vulkan_common/vulkan_wrapper.h
+++ b/src/video_core/vulkan_common/vulkan_wrapper.h
@@ -168,12 +168,13 @@ struct InstanceDispatch {
PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties{};
PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices{};
PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr{};
- PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR{};
+ PFN_vkGetPhysicalDeviceFeatures2 vkGetPhysicalDeviceFeatures2{};
PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties{};
PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties{};
PFN_vkGetPhysicalDeviceMemoryProperties2 vkGetPhysicalDeviceMemoryProperties2{};
PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties{};
- PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR{};
+ PFN_vkGetPhysicalDeviceProperties2 vkGetPhysicalDeviceProperties2{};
+ PFN_vkGetPhysicalDeviceToolProperties vkGetPhysicalDeviceToolProperties{};
PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties{};
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR{};
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR{};
@@ -247,7 +248,7 @@ struct DeviceDispatch : InstanceDispatch {
PFN_vkCreateComputePipelines vkCreateComputePipelines{};
PFN_vkCreateDescriptorPool vkCreateDescriptorPool{};
PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout{};
- PFN_vkCreateDescriptorUpdateTemplateKHR vkCreateDescriptorUpdateTemplateKHR{};
+ PFN_vkCreateDescriptorUpdateTemplate vkCreateDescriptorUpdateTemplate{};
PFN_vkCreateEvent vkCreateEvent{};
PFN_vkCreateFence vkCreateFence{};
PFN_vkCreateFramebuffer vkCreateFramebuffer{};
@@ -266,7 +267,7 @@ struct DeviceDispatch : InstanceDispatch {
PFN_vkDestroyCommandPool vkDestroyCommandPool{};
PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool{};
PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout{};
- PFN_vkDestroyDescriptorUpdateTemplateKHR vkDestroyDescriptorUpdateTemplateKHR{};
+ PFN_vkDestroyDescriptorUpdateTemplate vkDestroyDescriptorUpdateTemplate{};
PFN_vkDestroyEvent vkDestroyEvent{};
PFN_vkDestroyFence vkDestroyFence{};
PFN_vkDestroyFramebuffer vkDestroyFramebuffer{};
@@ -297,18 +298,18 @@ struct DeviceDispatch : InstanceDispatch {
PFN_vkGetPipelineExecutablePropertiesKHR vkGetPipelineExecutablePropertiesKHR{};
PFN_vkGetPipelineExecutableStatisticsKHR vkGetPipelineExecutableStatisticsKHR{};
PFN_vkGetQueryPoolResults vkGetQueryPoolResults{};
- PFN_vkGetSemaphoreCounterValueKHR vkGetSemaphoreCounterValueKHR{};
+ PFN_vkGetSemaphoreCounterValue vkGetSemaphoreCounterValue{};
PFN_vkMapMemory vkMapMemory{};
PFN_vkQueueSubmit vkQueueSubmit{};
PFN_vkResetFences vkResetFences{};
- PFN_vkResetQueryPoolEXT vkResetQueryPoolEXT{};
+ PFN_vkResetQueryPool vkResetQueryPool{};
PFN_vkSetDebugUtilsObjectNameEXT vkSetDebugUtilsObjectNameEXT{};
PFN_vkSetDebugUtilsObjectTagEXT vkSetDebugUtilsObjectTagEXT{};
PFN_vkUnmapMemory vkUnmapMemory{};
- PFN_vkUpdateDescriptorSetWithTemplateKHR vkUpdateDescriptorSetWithTemplateKHR{};
+ PFN_vkUpdateDescriptorSetWithTemplate vkUpdateDescriptorSetWithTemplate{};
PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets{};
PFN_vkWaitForFences vkWaitForFences{};
- PFN_vkWaitSemaphoresKHR vkWaitSemaphoresKHR{};
+ PFN_vkWaitSemaphores vkWaitSemaphores{};
};
/// Loads instance agnostic function pointers.
@@ -327,7 +328,7 @@ void Destroy(VkDevice, VkBufferView, const DeviceDispatch&) noexcept;
void Destroy(VkDevice, VkCommandPool, const DeviceDispatch&) noexcept;
void Destroy(VkDevice, VkDescriptorPool, const DeviceDispatch&) noexcept;
void Destroy(VkDevice, VkDescriptorSetLayout, const DeviceDispatch&) noexcept;
-void Destroy(VkDevice, VkDescriptorUpdateTemplateKHR, const DeviceDispatch&) noexcept;
+void Destroy(VkDevice, VkDescriptorUpdateTemplate, const DeviceDispatch&) noexcept;
void Destroy(VkDevice, VkDeviceMemory, const DeviceDispatch&) noexcept;
void Destroy(VkDevice, VkEvent, const DeviceDispatch&) noexcept;
void Destroy(VkDevice, VkFence, const DeviceDispatch&) noexcept;
@@ -559,7 +560,7 @@ private:
using DebugUtilsMessenger = Handle<VkDebugUtilsMessengerEXT, VkInstance, InstanceDispatch>;
using DescriptorSetLayout = Handle<VkDescriptorSetLayout, VkDevice, DeviceDispatch>;
-using DescriptorUpdateTemplateKHR = Handle<VkDescriptorUpdateTemplateKHR, VkDevice, DeviceDispatch>;
+using DescriptorUpdateTemplate = Handle<VkDescriptorUpdateTemplate, VkDevice, DeviceDispatch>;
using Pipeline = Handle<VkPipeline, VkDevice, DeviceDispatch>;
using PipelineLayout = Handle<VkPipelineLayout, VkDevice, DeviceDispatch>;
using QueryPool = Handle<VkQueryPool, VkDevice, DeviceDispatch>;
@@ -766,7 +767,7 @@ public:
[[nodiscard]] u64 GetCounter() const {
u64 value;
- Check(dld->vkGetSemaphoreCounterValueKHR(owner, handle, &value));
+ Check(dld->vkGetSemaphoreCounterValue(owner, handle, &value));
return value;
}
@@ -778,15 +779,15 @@ public:
* @return True on successful wait, false on timeout
*/
bool Wait(u64 value, u64 timeout = std::numeric_limits<u64>::max()) const {
- const VkSemaphoreWaitInfoKHR wait_info{
- .sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO_KHR,
+ const VkSemaphoreWaitInfo wait_info{
+ .sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO,
.pNext = nullptr,
.flags = 0,
.semaphoreCount = 1,
.pSemaphores = &handle,
.pValues = &value,
};
- const VkResult result = dld->vkWaitSemaphoresKHR(owner, &wait_info, timeout);
+ const VkResult result = dld->vkWaitSemaphores(owner, &wait_info, timeout);
switch (result) {
case VK_SUCCESS:
return true;
@@ -840,8 +841,8 @@ public:
CommandPool CreateCommandPool(const VkCommandPoolCreateInfo& ci) const;
- DescriptorUpdateTemplateKHR CreateDescriptorUpdateTemplateKHR(
- const VkDescriptorUpdateTemplateCreateInfoKHR& ci) const;
+ DescriptorUpdateTemplate CreateDescriptorUpdateTemplate(
+ const VkDescriptorUpdateTemplateCreateInfo& ci) const;
QueryPool CreateQueryPool(const VkQueryPoolCreateInfo& ci) const;
@@ -869,9 +870,9 @@ public:
void UpdateDescriptorSets(Span<VkWriteDescriptorSet> writes,
Span<VkCopyDescriptorSet> copies) const noexcept;
- void UpdateDescriptorSet(VkDescriptorSet set, VkDescriptorUpdateTemplateKHR update_template,
+ void UpdateDescriptorSet(VkDescriptorSet set, VkDescriptorUpdateTemplate update_template,
const void* data) const noexcept {
- dld->vkUpdateDescriptorSetWithTemplateKHR(handle, set, update_template, data);
+ dld->vkUpdateDescriptorSetWithTemplate(handle, set, update_template, data);
}
VkResult AcquireNextImageKHR(VkSwapchainKHR swapchain, u64 timeout, VkSemaphore semaphore,
@@ -884,8 +885,8 @@ public:
return dld->vkDeviceWaitIdle(handle);
}
- void ResetQueryPoolEXT(VkQueryPool query_pool, u32 first, u32 count) const noexcept {
- dld->vkResetQueryPoolEXT(handle, query_pool, first, count);
+ void ResetQueryPool(VkQueryPool query_pool, u32 first, u32 count) const noexcept {
+ dld->vkResetQueryPool(handle, query_pool, first, count);
}
VkResult GetQueryResults(VkQueryPool query_pool, u32 first, u32 count, std::size_t data_size,
@@ -910,11 +911,11 @@ public:
VkPhysicalDeviceProperties GetProperties() const noexcept;
- void GetProperties2KHR(VkPhysicalDeviceProperties2KHR&) const noexcept;
+ void GetProperties2(VkPhysicalDeviceProperties2&) const noexcept;
VkPhysicalDeviceFeatures GetFeatures() const noexcept;
- void GetFeatures2KHR(VkPhysicalDeviceFeatures2KHR&) const noexcept;
+ void GetFeatures2(VkPhysicalDeviceFeatures2&) const noexcept;
VkFormatProperties GetFormatProperties(VkFormat) const noexcept;
@@ -922,6 +923,8 @@ public:
std::vector<VkQueueFamilyProperties> GetQueueFamilyProperties() const;
+ std::vector<VkPhysicalDeviceToolProperties> GetPhysicalDeviceToolProperties() const;
+
bool GetSurfaceSupportKHR(u32 queue_family_index, VkSurfaceKHR) const;
VkSurfaceCapabilitiesKHR GetSurfaceCapabilitiesKHR(VkSurfaceKHR) const;
@@ -980,7 +983,7 @@ public:
dynamic_offsets.size(), dynamic_offsets.data());
}
- void PushDescriptorSetWithTemplateKHR(VkDescriptorUpdateTemplateKHR update_template,
+ void PushDescriptorSetWithTemplateKHR(VkDescriptorUpdateTemplate update_template,
VkPipelineLayout layout, u32 set,
const void* data) const noexcept {
dld->vkCmdPushDescriptorSetWithTemplateKHR(handle, update_template, layout, set, data);
diff --git a/src/web_service/CMakeLists.txt b/src/web_service/CMakeLists.txt
index 3f75d97d1..19534b9e4 100644
--- a/src/web_service/CMakeLists.txt
+++ b/src/web_service/CMakeLists.txt
@@ -4,6 +4,7 @@
add_library(web_service STATIC
announce_room_json.cpp
announce_room_json.h
+ precompiled_headers.h
telemetry_json.cpp
telemetry_json.h
verify_login.cpp
@@ -17,3 +18,7 @@ add_library(web_service STATIC
create_target_directory_groups(web_service)
target_link_libraries(web_service PRIVATE common network nlohmann_json::nlohmann_json httplib cpp-jwt)
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(web_service PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/web_service/precompiled_headers.h b/src/web_service/precompiled_headers.h
new file mode 100644
index 000000000..aabae730b
--- /dev/null
+++ b/src/web_service/precompiled_headers.h
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
diff --git a/src/yuzu/CMakeLists.txt b/src/yuzu/CMakeLists.txt
index 8a252bd5d..f192d6329 100644
--- a/src/yuzu/CMakeLists.txt
+++ b/src/yuzu/CMakeLists.txt
@@ -18,6 +18,9 @@ add_executable(yuzu
about_dialog.cpp
about_dialog.h
aboutdialog.ui
+ applets/qt_amiibo_settings.cpp
+ applets/qt_amiibo_settings.h
+ applets/qt_amiibo_settings.ui
applets/qt_controller.cpp
applets/qt_controller.h
applets/qt_controller.ui
@@ -186,6 +189,7 @@ add_executable(yuzu
multiplayer/state.cpp
multiplayer/state.h
multiplayer/validation.h
+ precompiled_headers.h
startup_checks.cpp
startup_checks.h
uisettings.cpp
@@ -295,7 +299,7 @@ if (APPLE)
set_target_properties(yuzu PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist)
elseif(WIN32)
# compile as a win32 gui application instead of a console application
- if (QT_VERSION VERSION_GREATER 6)
+ if (QT_VERSION VERSION_GREATER_EQUAL 6)
target_link_libraries(yuzu PRIVATE Qt6::EntryPointPrivate)
else()
target_link_libraries(yuzu PRIVATE Qt5::WinMain)
@@ -311,15 +315,15 @@ endif()
create_target_directory_groups(yuzu)
target_link_libraries(yuzu PRIVATE common core input_common network video_core)
-target_link_libraries(yuzu PRIVATE Boost::boost glad Qt::Widgets Qt::Multimedia)
+target_link_libraries(yuzu PRIVATE Boost::boost glad Qt${QT_MAJOR_VERSION}::Widgets)
target_link_libraries(yuzu PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads)
target_include_directories(yuzu PRIVATE ../../externals/Vulkan-Headers/include)
if (NOT WIN32)
- target_include_directories(yuzu PRIVATE ${Qt5Gui_PRIVATE_INCLUDE_DIRS})
+ target_include_directories(yuzu PRIVATE ${Qt${QT_MAJOR_VERSION}Gui_PRIVATE_INCLUDE_DIRS})
endif()
if (UNIX AND NOT APPLE)
- target_link_libraries(yuzu PRIVATE Qt::DBus)
+ target_link_libraries(yuzu PRIVATE Qt${QT_MAJOR_VERSION}::DBus)
endif()
target_compile_definitions(yuzu PRIVATE
@@ -358,8 +362,13 @@ if (ENABLE_WEB_SERVICE)
target_compile_definitions(yuzu PRIVATE -DENABLE_WEB_SERVICE)
endif()
+if (YUZU_USE_QT_MULTIMEDIA)
+ target_link_libraries(yuzu PRIVATE Qt${QT_MAJOR_VERSION}::Multimedia)
+ target_compile_definitions(yuzu PRIVATE -DYUZU_USE_QT_MULTIMEDIA)
+endif ()
+
if (YUZU_USE_QT_WEB_ENGINE)
- target_link_libraries(yuzu PRIVATE Qt::WebEngineCore Qt::WebEngineWidgets)
+ target_link_libraries(yuzu PRIVATE Qt${QT_MAJOR_VERSION}::WebEngineCore Qt${QT_MAJOR_VERSION}::WebEngineWidgets)
target_compile_definitions(yuzu PRIVATE -DYUZU_USE_QT_WEB_ENGINE)
endif ()
@@ -367,13 +376,26 @@ if(UNIX AND NOT APPLE)
install(TARGETS yuzu)
endif()
-if (YUZU_USE_BUNDLED_QT)
+if (WIN32 AND QT_VERSION VERSION_GREATER_EQUAL 6)
+ if (MSVC AND NOT ${CMAKE_GENERATOR} STREQUAL "Ninja")
+ set(YUZU_EXE_DIR "${CMAKE_BINARY_DIR}/bin/$<CONFIG>")
+ else()
+ set(YUZU_EXE_DIR "${CMAKE_BINARY_DIR}/bin")
+ endif()
+ add_custom_command(TARGET yuzu POST_BUILD COMMAND ${WINDEPLOYQT_EXECUTABLE} "${YUZU_EXE_DIR}/yuzu.exe" --dir "${YUZU_EXE_DIR}" --libdir "${YUZU_EXE_DIR}" --plugindir "${YUZU_EXE_DIR}/plugins" --no-compiler-runtime --no-opengl-sw --no-system-d3d-compiler --no-translations --verbose 0)
+endif()
+
+if (YUZU_USE_BUNDLED_QT AND QT_VERSION VERSION_LESS 6)
include(CopyYuzuQt5Deps)
copy_yuzu_Qt5_deps(yuzu)
endif()
if (ENABLE_SDL2)
- target_link_libraries(yuzu PRIVATE SDL2)
+ if (YUZU_USE_EXTERNAL_SDL2)
+ target_link_libraries(yuzu PRIVATE SDL2-static)
+ else()
+ target_link_libraries(yuzu PRIVATE SDL2)
+ endif()
target_compile_definitions(yuzu PRIVATE HAVE_SDL2)
endif()
@@ -391,3 +413,7 @@ endif()
if (ARCHITECTURE_x86_64 OR ARCHITECTURE_arm64)
target_link_libraries(yuzu PRIVATE dynarmic)
endif()
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(yuzu PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/yuzu/applets/qt_amiibo_settings.cpp b/src/yuzu/applets/qt_amiibo_settings.cpp
new file mode 100644
index 000000000..93ad4b4f9
--- /dev/null
+++ b/src/yuzu/applets/qt_amiibo_settings.cpp
@@ -0,0 +1,264 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include <algorithm>
+#include <thread>
+#include <fmt/format.h>
+#include <nlohmann/json.hpp>
+
+#include "common/assert.h"
+#include "common/string_util.h"
+#include "core/hle/service/nfp/nfp_device.h"
+#include "core/hle/service/nfp/nfp_result.h"
+#include "input_common/drivers/virtual_amiibo.h"
+#include "input_common/main.h"
+#include "ui_qt_amiibo_settings.h"
+#ifdef ENABLE_WEB_SERVICE
+#include "web_service/web_backend.h"
+#endif
+#include "yuzu/applets/qt_amiibo_settings.h"
+#include "yuzu/main.h"
+
+QtAmiiboSettingsDialog::QtAmiiboSettingsDialog(QWidget* parent,
+ Core::Frontend::CabinetParameters parameters_,
+ InputCommon::InputSubsystem* input_subsystem_,
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device_)
+ : QDialog(parent), ui(std::make_unique<Ui::QtAmiiboSettingsDialog>()),
+ input_subsystem{input_subsystem_}, nfp_device{std::move(nfp_device_)},
+ parameters(std::move(parameters_)) {
+ ui->setupUi(this);
+
+ LoadInfo();
+
+ resize(0, 0);
+}
+
+QtAmiiboSettingsDialog::~QtAmiiboSettingsDialog() = default;
+
+int QtAmiiboSettingsDialog::exec() {
+ if (!is_initalized) {
+ return QDialog::Rejected;
+ }
+ return QDialog::exec();
+}
+
+std::string QtAmiiboSettingsDialog::GetName() const {
+ return ui->amiiboCustomNameValue->text().toStdString();
+}
+
+void QtAmiiboSettingsDialog::LoadInfo() {
+ if (input_subsystem->GetVirtualAmiibo()->ReloadAmiibo() !=
+ InputCommon::VirtualAmiibo::Info::Success) {
+ return;
+ }
+
+ if (nfp_device->GetCurrentState() != Service::NFP::DeviceState::TagFound &&
+ nfp_device->GetCurrentState() != Service::NFP::DeviceState::TagMounted) {
+ return;
+ }
+ nfp_device->Mount(Service::NFP::MountTarget::All);
+
+ LoadAmiiboInfo();
+ LoadAmiiboData();
+ LoadAmiiboGameInfo();
+
+ ui->amiiboDirectoryValue->setText(
+ QString::fromStdString(input_subsystem->GetVirtualAmiibo()->GetLastFilePath()));
+
+ SetSettingsDescription();
+ is_initalized = true;
+}
+
+void QtAmiiboSettingsDialog::LoadAmiiboInfo() {
+ Service::NFP::ModelInfo model_info{};
+ const auto model_result = nfp_device->GetModelInfo(model_info);
+
+ if (model_result.IsFailure()) {
+ ui->amiiboImageLabel->setVisible(false);
+ ui->amiiboInfoGroup->setVisible(false);
+ return;
+ }
+
+ const auto amiibo_id =
+ fmt::format("{:04x}{:02x}{:02x}{:04x}{:02x}02", Common::swap16(model_info.character_id),
+ model_info.character_variant, model_info.amiibo_type, model_info.model_number,
+ model_info.series);
+
+ LOG_DEBUG(Frontend, "Loading amiibo id {}", amiibo_id);
+ // Note: This function is not being used until we host the images on our server
+ // LoadAmiiboApiInfo(amiibo_id);
+ ui->amiiboImageLabel->setVisible(false);
+ ui->amiiboInfoGroup->setVisible(false);
+}
+
+void QtAmiiboSettingsDialog::LoadAmiiboApiInfo(std::string_view amiibo_id) {
+#ifdef ENABLE_WEB_SERVICE
+ // TODO: Host this data on our website
+ WebService::Client client{"https://amiiboapi.com", {}, {}};
+ WebService::Client image_client{"https://raw.githubusercontent.com", {}, {}};
+ const auto url_path = fmt::format("/api/amiibo/?id={}", amiibo_id);
+
+ const auto amiibo_json = client.GetJson(url_path, true).returned_data;
+ if (amiibo_json.empty()) {
+ ui->amiiboImageLabel->setVisible(false);
+ ui->amiiboInfoGroup->setVisible(false);
+ return;
+ }
+
+ std::string amiibo_series{};
+ std::string amiibo_name{};
+ std::string amiibo_image_url{};
+ std::string amiibo_type{};
+
+ const auto parsed_amiibo_json_json = nlohmann::json::parse(amiibo_json).at("amiibo");
+ parsed_amiibo_json_json.at("amiiboSeries").get_to(amiibo_series);
+ parsed_amiibo_json_json.at("name").get_to(amiibo_name);
+ parsed_amiibo_json_json.at("image").get_to(amiibo_image_url);
+ parsed_amiibo_json_json.at("type").get_to(amiibo_type);
+
+ ui->amiiboSeriesValue->setText(QString::fromStdString(amiibo_series));
+ ui->amiiboNameValue->setText(QString::fromStdString(amiibo_name));
+ ui->amiiboTypeValue->setText(QString::fromStdString(amiibo_type));
+
+ if (amiibo_image_url.size() < 34) {
+ ui->amiiboImageLabel->setVisible(false);
+ }
+
+ const auto image_url_path = amiibo_image_url.substr(34, amiibo_image_url.size() - 34);
+ const auto image_data = image_client.GetImage(image_url_path, true).returned_data;
+
+ if (image_data.empty()) {
+ ui->amiiboImageLabel->setVisible(false);
+ }
+
+ QPixmap pixmap;
+ pixmap.loadFromData(reinterpret_cast<const u8*>(image_data.data()),
+ static_cast<uint>(image_data.size()));
+ pixmap = pixmap.scaled(250, 350, Qt::AspectRatioMode::KeepAspectRatio,
+ Qt::TransformationMode::SmoothTransformation);
+ ui->amiiboImageLabel->setPixmap(pixmap);
+#endif
+}
+
+void QtAmiiboSettingsDialog::LoadAmiiboData() {
+ Service::NFP::RegisterInfo register_info{};
+ Service::NFP::CommonInfo common_info{};
+ const auto register_result = nfp_device->GetRegisterInfo(register_info);
+ const auto common_result = nfp_device->GetCommonInfo(common_info);
+
+ if (register_result.IsFailure()) {
+ ui->creationDateValue->setDisabled(true);
+ ui->modificationDateValue->setDisabled(true);
+ ui->amiiboCustomNameValue->setReadOnly(false);
+ ui->amiiboOwnerValue->setReadOnly(false);
+ return;
+ }
+
+ if (parameters.mode == Service::NFP::CabinetMode::StartNicknameAndOwnerSettings) {
+ ui->creationDateValue->setDisabled(true);
+ ui->modificationDateValue->setDisabled(true);
+ }
+
+ const auto amiibo_name = std::string(register_info.amiibo_name.data());
+ const auto owner_name = Common::UTF16ToUTF8(register_info.mii_char_info.name.data());
+ const auto creation_date =
+ QDate(register_info.creation_date.year, register_info.creation_date.month,
+ register_info.creation_date.day);
+
+ ui->amiiboCustomNameValue->setText(QString::fromStdString(amiibo_name));
+ ui->amiiboOwnerValue->setText(QString::fromStdString(owner_name));
+ ui->amiiboCustomNameValue->setReadOnly(true);
+ ui->amiiboOwnerValue->setReadOnly(true);
+ ui->creationDateValue->setDate(creation_date);
+
+ if (common_result.IsFailure()) {
+ ui->modificationDateValue->setDisabled(true);
+ return;
+ }
+
+ const auto modification_date =
+ QDate(common_info.last_write_date.year, common_info.last_write_date.month,
+ common_info.last_write_date.day);
+ ui->modificationDateValue->setDate(modification_date);
+}
+
+void QtAmiiboSettingsDialog::LoadAmiiboGameInfo() {
+ u32 application_area_id{};
+ const auto application_result = nfp_device->GetApplicationAreaId(application_area_id);
+
+ if (application_result.IsFailure()) {
+ ui->gameIdValue->setVisible(false);
+ ui->gameIdLabel->setText(tr("No game data present"));
+ return;
+ }
+
+ SetGameDataName(application_area_id);
+}
+
+void QtAmiiboSettingsDialog::SetGameDataName(u32 application_area_id) {
+ static constexpr std::array<std::pair<u32, const char*>, 12> game_name_list = {
+ // 3ds, wii u
+ std::pair<u32, const char*>{0x10110E00, "Super Smash Bros (3DS/WiiU)"},
+ {0x00132600, "Mario & Luigi: Paper Jam"},
+ {0x0014F000, "Animal Crossing: Happy Home Designer"},
+ {0x00152600, "Chibi-Robo!: Zip Lash"},
+ {0x10161f00, "Mario Party 10"},
+ {0x1019C800, "The Legend of Zelda: Twilight Princess HD"},
+ // switch
+ {0x10162B00, "Splatoon 2"},
+ {0x1016e100, "Shovel Knight: Treasure Trove"},
+ {0x1019C800, "The Legend of Zelda: Breath of the Wild"},
+ {0x34F80200, "Super Smash Bros. Ultimate"},
+ {0x38600500, "Splatoon 3"},
+ {0x3B440400, "The Legend of Zelda: Link's Awakening"},
+ };
+
+ for (const auto& [game_id, game_name] : game_name_list) {
+ if (application_area_id == game_id) {
+ ui->gameIdValue->setText(QString::fromStdString(game_name));
+ return;
+ }
+ }
+
+ const auto application_area_string = fmt::format("{:016x}", application_area_id);
+ ui->gameIdValue->setText(QString::fromStdString(application_area_string));
+}
+
+void QtAmiiboSettingsDialog::SetSettingsDescription() {
+ switch (parameters.mode) {
+ case Service::NFP::CabinetMode::StartFormatter:
+ ui->cabinetActionDescriptionLabel->setText(
+ tr("The following amiibo data will be formatted:"));
+ break;
+ case Service::NFP::CabinetMode::StartGameDataEraser:
+ ui->cabinetActionDescriptionLabel->setText(tr("The following game data will removed:"));
+ break;
+ case Service::NFP::CabinetMode::StartNicknameAndOwnerSettings:
+ ui->cabinetActionDescriptionLabel->setText(tr("Set nickname and owner:"));
+ break;
+ case Service::NFP::CabinetMode::StartRestorer:
+ ui->cabinetActionDescriptionLabel->setText(tr("Do you wish to restore this amiibo?"));
+ break;
+ }
+}
+
+QtAmiiboSettings::QtAmiiboSettings(GMainWindow& parent) {
+ connect(this, &QtAmiiboSettings::MainWindowShowAmiiboSettings, &parent,
+ &GMainWindow::AmiiboSettingsShowDialog, Qt::QueuedConnection);
+ connect(&parent, &GMainWindow::AmiiboSettingsFinished, this,
+ &QtAmiiboSettings::MainWindowFinished, Qt::QueuedConnection);
+}
+
+QtAmiiboSettings::~QtAmiiboSettings() = default;
+
+void QtAmiiboSettings::ShowCabinetApplet(
+ const Core::Frontend::CabinetCallback& callback_,
+ const Core::Frontend::CabinetParameters& parameters,
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const {
+ callback = std::move(callback_);
+ emit MainWindowShowAmiiboSettings(parameters, nfp_device);
+}
+
+void QtAmiiboSettings::MainWindowFinished(bool is_success, const std::string& name) {
+ callback(is_success, name);
+}
diff --git a/src/yuzu/applets/qt_amiibo_settings.h b/src/yuzu/applets/qt_amiibo_settings.h
new file mode 100644
index 000000000..930c96739
--- /dev/null
+++ b/src/yuzu/applets/qt_amiibo_settings.h
@@ -0,0 +1,83 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include <array>
+#include <memory>
+#include <QDialog>
+#include "core/frontend/applets/cabinet.h"
+
+class GMainWindow;
+class QCheckBox;
+class QComboBox;
+class QDialogButtonBox;
+class QGroupBox;
+class QLabel;
+
+namespace InputCommon {
+class InputSubsystem;
+}
+
+namespace Ui {
+class QtAmiiboSettingsDialog;
+}
+
+namespace Service::NFP {
+class NfpDevice;
+} // namespace Service::NFP
+
+class QtAmiiboSettingsDialog final : public QDialog {
+ Q_OBJECT
+
+public:
+ explicit QtAmiiboSettingsDialog(QWidget* parent, Core::Frontend::CabinetParameters parameters_,
+ InputCommon::InputSubsystem* input_subsystem_,
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device_);
+ ~QtAmiiboSettingsDialog() override;
+
+ int exec() override;
+
+ std::string GetName() const;
+
+private:
+ void LoadInfo();
+ void LoadAmiiboInfo();
+ void LoadAmiiboApiInfo(std::string_view amiibo_id);
+ void LoadAmiiboData();
+ void LoadAmiiboGameInfo();
+ void SetGameDataName(u32 application_area_id);
+ void SetSettingsDescription();
+
+ std::unique_ptr<Ui::QtAmiiboSettingsDialog> ui;
+
+ InputCommon::InputSubsystem* input_subsystem;
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device;
+
+ // Parameters sent in from the backend HLE applet.
+ Core::Frontend::CabinetParameters parameters;
+
+ // If false amiibo settings failed to load
+ bool is_initalized{};
+};
+
+class QtAmiiboSettings final : public QObject, public Core::Frontend::CabinetApplet {
+ Q_OBJECT
+
+public:
+ explicit QtAmiiboSettings(GMainWindow& parent);
+ ~QtAmiiboSettings() override;
+
+ void ShowCabinetApplet(const Core::Frontend::CabinetCallback& callback_,
+ const Core::Frontend::CabinetParameters& parameters,
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const override;
+
+signals:
+ void MainWindowShowAmiiboSettings(const Core::Frontend::CabinetParameters& parameters,
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device) const;
+
+private:
+ void MainWindowFinished(bool is_success, const std::string& name);
+
+ mutable Core::Frontend::CabinetCallback callback;
+};
diff --git a/src/yuzu/applets/qt_amiibo_settings.ui b/src/yuzu/applets/qt_amiibo_settings.ui
new file mode 100644
index 000000000..f377a6e61
--- /dev/null
+++ b/src/yuzu/applets/qt_amiibo_settings.ui
@@ -0,0 +1,494 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>QtAmiiboSettingsDialog</class>
+ <widget class="QDialog" name="QtAmiiboSettingsDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>839</width>
+ <height>500</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Amiibo Settings</string>
+ </property>
+ <property name="styleSheet">
+ <string notr="true"/>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout" stretch="0">
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QWidget" name="mainControllerApplet" native="true">
+ <layout class="QVBoxLayout" name="verticalLayout_1" stretch="0,3,0">
+ <property name="spacing">
+ <number>0</number>
+ </property>
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QWidget" name="topControllerApplet" native="true">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <property name="spacing">
+ <number>10</number>
+ </property>
+ <property name="leftMargin">
+ <number>20</number>
+ </property>
+ <property name="topMargin">
+ <number>15</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>15</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="cabinetActionDescriptionLabel">
+ <property name="font">
+ <font>
+ <pointsize>12</pointsize>
+ <weight>75</weight>
+ <bold>true</bold>
+ </font>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+ </property>
+ <property name="wordWrap">
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QWidget" name="middleControllerApplet" native="true">
+ <layout class="QVBoxLayout" name="verticalLayout_3">
+ <property name="spacing">
+ <number>0</number>
+ </property>
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>0</number>
+ </property>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <property name="spacing">
+ <number>20</number>
+ </property>
+ <property name="leftMargin">
+ <number>15</number>
+ </property>
+ <property name="rightMargin">
+ <number>15</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="amiiboImageLabel">
+ <property name="minimumSize">
+ <size>
+ <width>250</width>
+ <height>350</height>
+ </size>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>236</width>
+ <height>350</height>
+ </size>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout_4">
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>8</number>
+ </property>
+ <property name="bottomMargin">
+ <number>15</number>
+ </property>
+ <item>
+ <widget class="QGroupBox" name="amiiboInfoGroup">
+ <property name="title">
+ <string>Amiibo Info</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_5">
+ <item>
+ <layout class="QGridLayout" name="gridLayout_1">
+ <item row="0" column="0">
+ <widget class="QLabel" name="amiiboSeriesLabel">
+ <property name="text">
+ <string>Series</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="amiiboSeriesValue">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="amiiboTypeLabel">
+ <property name="text">
+ <string>Type</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLineEdit" name="amiiboTypeValue">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="amiiboNameLabel">
+ <property name="text">
+ <string>Name</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QLineEdit" name="amiiboNameValue">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="amiiboDataGroup">
+ <property name="title">
+ <string>Amiibo Data</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_6">
+ <item>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <item row="0" column="0">
+ <widget class="QLabel" name="amiiboCustomNameLabel">
+ <property name="text">
+ <string>Custom Name</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="amiiboCustomNameValue">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="maxLength">
+ <number>10</number>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="amiiboOwnerLabel">
+ <property name="text">
+ <string>Owner</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLineEdit" name="amiiboOwnerValue">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="maxLength">
+ <number>10</number>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="creationDateLabel">
+ <property name="text">
+ <string>Creation Date</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QDateTimeEdit" name="creationDateValue">
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ <property name="minimumDate">
+ <date>
+ <year>1970</year>
+ <month>1</month>
+ <day>1</day>
+ </date>
+ </property>
+ <property name="displayFormat">
+ <string>dd/MM/yyyy</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="modificationDateLabel">
+ <property name="text">
+ <string>Modification Date</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QDateTimeEdit" name="modificationDateValue">
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ <property name="minimumDate">
+ <date>
+ <year>1970</year>
+ <month>1</month>
+ <day>1</day>
+ </date>
+ </property>
+ <property name="displayFormat">
+ <string>dd/MM/yyyy </string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="gameDataGroup">
+ <property name="minimumSize">
+ <size>
+ <width>500</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="title">
+ <string>Game Data</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_3">
+ <item row="0" column="0">
+ <widget class="QLabel" name="gameIdLabel">
+ <property name="text">
+ <string>Game Id</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="gameIdValue">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="MountAmiiboGroup">
+ <property name="minimumSize">
+ <size>
+ <width>500</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="title">
+ <string>Mount Amiibo</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_4">
+ <item row="0" column="3">
+ <widget class="QToolButton" name="amiiboDirectoryButton">
+ <property name="text">
+ <string>...</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Maximum</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>60</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="0" column="0">
+ <widget class="QLabel" name="amiiboDirectoryLabel">
+ <property name="text">
+ <string>File Path</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="2">
+ <widget class="QLineEdit" name="amiiboDirectoryValue"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QWidget" name="bottomControllerApplet" native="true">
+ <layout class="QHBoxLayout" name="horizontalLayout_6">
+ <property name="spacing">
+ <number>15</number>
+ </property>
+ <property name="leftMargin">
+ <number>15</number>
+ </property>
+ <property name="topMargin">
+ <number>8</number>
+ </property>
+ <property name="rightMargin">
+ <number>20</number>
+ </property>
+ <property name="bottomMargin">
+ <number>8</number>
+ </property>
+ <item alignment="Qt::AlignBottom">
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>QtAmiiboSettingsDialog</receiver>
+ <slot>accept()</slot>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>QtAmiiboSettingsDialog</receiver>
+ <slot>reject()</slot>
+ </connection>
+ </connections>
+</ui>
diff --git a/src/yuzu/bootmanager.cpp b/src/yuzu/bootmanager.cpp
index d88efacd7..5b5b6fed8 100644
--- a/src/yuzu/bootmanager.cpp
+++ b/src/yuzu/bootmanager.cpp
@@ -4,8 +4,10 @@
#include <glad/glad.h>
#include <QApplication>
+#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
#include <QCameraImageCapture>
#include <QCameraInfo>
+#endif
#include <QHBoxLayout>
#include <QMessageBox>
#include <QPainter>
@@ -116,7 +118,7 @@ void EmuThread::run() {
}
} else {
std::unique_lock lock{running_mutex};
- running_cv.wait(lock, stop_token, [this] { return IsRunning(); });
+ Common::CondvarWait(running_cv, lock, stop_token, [&] { return IsRunning(); });
}
}
@@ -235,8 +237,7 @@ private:
GRenderWindow* render_window;
};
-class OpenGLRenderWidget : public RenderWidget {
-public:
+struct OpenGLRenderWidget : public RenderWidget {
explicit OpenGLRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {
windowHandle()->setSurfaceType(QWindow::OpenGLSurface);
}
@@ -249,13 +250,16 @@ private:
std::unique_ptr<Core::Frontend::GraphicsContext> context;
};
-class VulkanRenderWidget : public RenderWidget {
-public:
+struct VulkanRenderWidget : public RenderWidget {
explicit VulkanRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {
windowHandle()->setSurfaceType(QWindow::VulkanSurface);
}
};
+struct NullRenderWidget : public RenderWidget {
+ explicit NullRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {}
+};
+
static Core::Frontend::WindowSystemType GetWindowSystemType() {
// Determine WSI type based on Qt platform.
QString platform_name = QGuiApplication::platformName();
@@ -265,6 +269,10 @@ static Core::Frontend::WindowSystemType GetWindowSystemType() {
return Core::Frontend::WindowSystemType::X11;
else if (platform_name == QStringLiteral("wayland"))
return Core::Frontend::WindowSystemType::Wayland;
+ else if (platform_name == QStringLiteral("cocoa"))
+ return Core::Frontend::WindowSystemType::Cocoa;
+ else if (platform_name == QStringLiteral("android"))
+ return Core::Frontend::WindowSystemType::Android;
LOG_CRITICAL(Frontend, "Unknown Qt platform!");
return Core::Frontend::WindowSystemType::Windows;
@@ -707,6 +715,7 @@ void GRenderWindow::TouchEndEvent() {
}
void GRenderWindow::InitializeCamera() {
+#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
constexpr auto camera_update_ms = std::chrono::milliseconds{50}; // (50ms, 20Hz)
if (!Settings::values.enable_ir_sensor) {
return;
@@ -760,18 +769,22 @@ void GRenderWindow::InitializeCamera() {
connect(camera_timer.get(), &QTimer::timeout, [this] { RequestCameraCapture(); });
// This timer should be dependent of camera resolution 5ms for every 100 pixels
camera_timer->start(camera_update_ms);
+#endif
}
void GRenderWindow::FinalizeCamera() {
+#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
if (camera_timer) {
camera_timer->stop();
}
if (camera) {
camera->unload();
}
+#endif
}
void GRenderWindow::RequestCameraCapture() {
+#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
if (!Settings::values.enable_ir_sensor) {
return;
}
@@ -788,6 +801,7 @@ void GRenderWindow::RequestCameraCapture() {
pending_camera_snapshots++;
camera_capture->capture();
+#endif
}
void GRenderWindow::OnCameraCapture(int requestId, const QImage& img) {
@@ -866,6 +880,9 @@ bool GRenderWindow::InitRenderTarget() {
return false;
}
break;
+ case Settings::RendererBackend::Null:
+ InitializeNull();
+ break;
}
// Update the Window System information with the new render target
@@ -962,6 +979,11 @@ bool GRenderWindow::InitializeVulkan() {
return true;
}
+void GRenderWindow::InitializeNull() {
+ child_widget = new NullRenderWidget(this);
+ main_context = std::make_unique<DummyContext>();
+}
+
bool GRenderWindow::LoadOpenGL() {
auto context = CreateSharedContext();
auto scope = context->Acquire();
diff --git a/src/yuzu/bootmanager.h b/src/yuzu/bootmanager.h
index c45ebf1a2..f4deae4ee 100644
--- a/src/yuzu/bootmanager.h
+++ b/src/yuzu/bootmanager.h
@@ -14,6 +14,7 @@
#include <QTouchEvent>
#include <QWidget>
+#include "common/polyfill_thread.h"
#include "common/thread.h"
#include "core/frontend/emu_window.h"
@@ -218,6 +219,7 @@ private:
bool InitializeOpenGL();
bool InitializeVulkan();
+ void InitializeNull();
bool LoadOpenGL();
QStringList GetUnsupportedGLExtensions() const;
@@ -241,8 +243,10 @@ private:
bool is_virtual_camera;
int pending_camera_snapshots;
+#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
std::unique_ptr<QCamera> camera;
std::unique_ptr<QCameraImageCapture> camera_capture;
+#endif
std::unique_ptr<QTimer> camera_timer;
Core::System& system;
diff --git a/src/yuzu/compatdb.cpp b/src/yuzu/compatdb.cpp
index b03e71248..05f49c0d2 100644
--- a/src/yuzu/compatdb.cpp
+++ b/src/yuzu/compatdb.cpp
@@ -126,6 +126,7 @@ void CompatDB::Submit() {
break;
default:
LOG_ERROR(Frontend, "Unexpected page: {}", currentId());
+ break;
}
}
diff --git a/src/yuzu/configuration/config.cpp b/src/yuzu/configuration/config.cpp
index cc1ba9f70..c11d1c8b3 100644
--- a/src/yuzu/configuration/config.cpp
+++ b/src/yuzu/configuration/config.cpp
@@ -693,6 +693,7 @@ void Config::ReadRendererValues() {
ReadGlobalSetting(Settings::values.aspect_ratio);
ReadGlobalSetting(Settings::values.resolution_setup);
ReadGlobalSetting(Settings::values.scaling_filter);
+ ReadGlobalSetting(Settings::values.fsr_sharpening_slider);
ReadGlobalSetting(Settings::values.anti_aliasing);
ReadGlobalSetting(Settings::values.max_anisotropy);
ReadGlobalSetting(Settings::values.use_speed_limit);
@@ -1316,6 +1317,10 @@ void Config::SaveRendererValues() {
static_cast<u32>(Settings::values.scaling_filter.GetValue(global)),
static_cast<u32>(Settings::values.scaling_filter.GetDefault()),
Settings::values.scaling_filter.UsingGlobal());
+ WriteSetting(QString::fromStdString(Settings::values.fsr_sharpening_slider.GetLabel()),
+ static_cast<u32>(Settings::values.fsr_sharpening_slider.GetValue(global)),
+ static_cast<u32>(Settings::values.fsr_sharpening_slider.GetDefault()),
+ Settings::values.fsr_sharpening_slider.UsingGlobal());
WriteSetting(QString::fromStdString(Settings::values.anti_aliasing.GetLabel()),
static_cast<u32>(Settings::values.anti_aliasing.GetValue(global)),
static_cast<u32>(Settings::values.anti_aliasing.GetDefault()),
diff --git a/src/yuzu/configuration/configure_camera.cpp b/src/yuzu/configuration/configure_camera.cpp
index 2a61de2a1..d95e96696 100644
--- a/src/yuzu/configuration/configure_camera.cpp
+++ b/src/yuzu/configuration/configure_camera.cpp
@@ -2,8 +2,11 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include <memory>
+#include <QtCore>
+#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
#include <QCameraImageCapture>
#include <QCameraInfo>
+#endif
#include <QStandardItemModel>
#include <QTimer>
@@ -33,6 +36,7 @@ ConfigureCamera::ConfigureCamera(QWidget* parent, InputCommon::InputSubsystem* i
ConfigureCamera::~ConfigureCamera() = default;
void ConfigureCamera::PreviewCamera() {
+#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
const auto index = ui->ir_sensor_combo_box->currentIndex();
bool camera_found = false;
const QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
@@ -101,6 +105,7 @@ void ConfigureCamera::PreviewCamera() {
});
camera_timer->start(250);
+#endif
}
void ConfigureCamera::DisplayCapturedFrame(int requestId, const QImage& img) {
@@ -133,11 +138,13 @@ void ConfigureCamera::LoadConfiguration() {
ui->ir_sensor_combo_box->clear();
input_devices.push_back("Auto");
ui->ir_sensor_combo_box->addItem(tr("Auto"));
+#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
const auto cameras = QCameraInfo::availableCameras();
for (const QCameraInfo& cameraInfo : cameras) {
input_devices.push_back(cameraInfo.deviceName().toStdString());
ui->ir_sensor_combo_box->addItem(cameraInfo.description());
}
+#endif
const auto current_device = Settings::values.ir_sensor_device.GetValue();
diff --git a/src/yuzu/configuration/configure_camera.h b/src/yuzu/configuration/configure_camera.h
index db9833b5c..9a90512b3 100644
--- a/src/yuzu/configuration/configure_camera.h
+++ b/src/yuzu/configuration/configure_camera.h
@@ -46,8 +46,10 @@ private:
bool is_virtual_camera;
int pending_snapshots;
+#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && YUZU_USE_QT_MULTIMEDIA
std::unique_ptr<QCamera> camera;
std::unique_ptr<QCameraImageCapture> camera_capture;
+#endif
std::unique_ptr<QTimer> camera_timer;
std::vector<std::string> input_devices;
std::unique_ptr<Ui::ConfigureCamera> ui;
diff --git a/src/yuzu/configuration/configure_graphics.cpp b/src/yuzu/configuration/configure_graphics.cpp
index bd69d04a6..8ca683966 100644
--- a/src/yuzu/configuration/configure_graphics.cpp
+++ b/src/yuzu/configuration/configure_graphics.cpp
@@ -63,6 +63,11 @@ ConfigureGraphics::ConfigureGraphics(const Core::System& system_, QWidget* paren
ui->api_widget->isEnabled());
ui->bg_label->setVisible(Settings::IsConfiguringGlobal());
ui->bg_combobox->setVisible(!Settings::IsConfiguringGlobal());
+
+ connect(ui->fsr_sharpening_slider, &QSlider::valueChanged, this,
+ &ConfigureGraphics::SetFSRIndicatorText);
+ ui->fsr_sharpening_combobox->setVisible(!Settings::IsConfiguringGlobal());
+ ui->fsr_sharpening_label->setVisible(Settings::IsConfiguringGlobal());
}
void ConfigureGraphics::UpdateDeviceSelection(int device) {
@@ -110,6 +115,7 @@ void ConfigureGraphics::SetConfiguration() {
static_cast<int>(Settings::values.resolution_setup.GetValue()));
ui->scaling_filter_combobox->setCurrentIndex(
static_cast<int>(Settings::values.scaling_filter.GetValue()));
+ ui->fsr_sharpening_slider->setValue(Settings::values.fsr_sharpening_slider.GetValue());
ui->anti_aliasing_combobox->setCurrentIndex(
static_cast<int>(Settings::values.anti_aliasing.GetValue()));
} else {
@@ -147,6 +153,15 @@ void ConfigureGraphics::SetConfiguration() {
ConfigurationShared::SetHighlight(ui->anti_aliasing_label,
!Settings::values.anti_aliasing.UsingGlobal());
+ ui->fsr_sharpening_combobox->setCurrentIndex(
+ Settings::values.fsr_sharpening_slider.UsingGlobal() ? 0 : 1);
+ ui->fsr_sharpening_slider->setEnabled(
+ !Settings::values.fsr_sharpening_slider.UsingGlobal());
+ ui->fsr_sharpening_value->setEnabled(!Settings::values.fsr_sharpening_slider.UsingGlobal());
+ ConfigurationShared::SetHighlight(ui->fsr_sharpening_layout,
+ !Settings::values.fsr_sharpening_slider.UsingGlobal());
+ ui->fsr_sharpening_slider->setValue(Settings::values.fsr_sharpening_slider.GetValue());
+
ui->bg_combobox->setCurrentIndex(Settings::values.bg_red.UsingGlobal() ? 0 : 1);
ui->bg_button->setEnabled(!Settings::values.bg_red.UsingGlobal());
ConfigurationShared::SetHighlight(ui->bg_layout, !Settings::values.bg_red.UsingGlobal());
@@ -155,6 +170,12 @@ void ConfigureGraphics::SetConfiguration() {
Settings::values.bg_green.GetValue(),
Settings::values.bg_blue.GetValue()));
UpdateAPILayout();
+ SetFSRIndicatorText(ui->fsr_sharpening_slider->sliderPosition());
+}
+
+void ConfigureGraphics::SetFSRIndicatorText(int percentage) {
+ ui->fsr_sharpening_value->setText(
+ tr("%1%", "FSR sharpening percentage (e.g. 50%)").arg(100 - (percentage / 2)));
}
void ConfigureGraphics::ApplyConfiguration() {
@@ -210,6 +231,7 @@ void ConfigureGraphics::ApplyConfiguration() {
if (Settings::values.anti_aliasing.UsingGlobal()) {
Settings::values.anti_aliasing.SetValue(anti_aliasing);
}
+ Settings::values.fsr_sharpening_slider.SetValue(ui->fsr_sharpening_slider->value());
} else {
if (ui->resolution_combobox->currentIndex() == ConfigurationShared::USE_GLOBAL_INDEX) {
Settings::values.resolution_setup.SetGlobal(true);
@@ -238,6 +260,7 @@ void ConfigureGraphics::ApplyConfiguration() {
Settings::values.renderer_backend.SetValue(GetCurrentGraphicsBackend());
switch (GetCurrentGraphicsBackend()) {
case Settings::RendererBackend::OpenGL:
+ case Settings::RendererBackend::Null:
Settings::values.shader_backend.SetGlobal(false);
Settings::values.vulkan_device.SetGlobal(true);
Settings::values.shader_backend.SetValue(shader_backend);
@@ -269,6 +292,13 @@ void ConfigureGraphics::ApplyConfiguration() {
Settings::values.bg_green.SetValue(static_cast<u8>(bg_color.green()));
Settings::values.bg_blue.SetValue(static_cast<u8>(bg_color.blue()));
}
+
+ if (ui->fsr_sharpening_combobox->currentIndex() == ConfigurationShared::USE_GLOBAL_INDEX) {
+ Settings::values.fsr_sharpening_slider.SetGlobal(true);
+ } else {
+ Settings::values.fsr_sharpening_slider.SetGlobal(false);
+ Settings::values.fsr_sharpening_slider.SetValue(ui->fsr_sharpening_slider->value());
+ }
}
}
@@ -319,6 +349,10 @@ void ConfigureGraphics::UpdateAPILayout() {
ui->device_widget->setVisible(true);
ui->backend_widget->setVisible(false);
break;
+ case Settings::RendererBackend::Null:
+ ui->device_widget->setVisible(false);
+ ui->backend_widget->setVisible(false);
+ break;
}
}
@@ -331,7 +365,7 @@ void ConfigureGraphics::RetrieveVulkanDevices() try {
vk::InstanceDispatch dld;
const Common::DynamicLibrary library = OpenLibrary();
- const vk::Instance instance = CreateInstance(library, dld, VK_API_VERSION_1_0);
+ const vk::Instance instance = CreateInstance(library, dld, VK_API_VERSION_1_1);
const std::vector<VkPhysicalDevice> physical_devices = instance.EnumeratePhysicalDevices();
vulkan_devices.clear();
@@ -380,6 +414,7 @@ void ConfigureGraphics::SetupPerGameUI() {
ui->aspect_ratio_combobox->setEnabled(Settings::values.aspect_ratio.UsingGlobal());
ui->resolution_combobox->setEnabled(Settings::values.resolution_setup.UsingGlobal());
ui->scaling_filter_combobox->setEnabled(Settings::values.scaling_filter.UsingGlobal());
+ ui->fsr_sharpening_slider->setEnabled(Settings::values.fsr_sharpening_slider.UsingGlobal());
ui->anti_aliasing_combobox->setEnabled(Settings::values.anti_aliasing.UsingGlobal());
ui->use_asynchronous_gpu_emulation->setEnabled(
Settings::values.use_asynchronous_gpu_emulation.UsingGlobal());
@@ -387,6 +422,7 @@ void ConfigureGraphics::SetupPerGameUI() {
ui->accelerate_astc->setEnabled(Settings::values.accelerate_astc.UsingGlobal());
ui->use_disk_shader_cache->setEnabled(Settings::values.use_disk_shader_cache.UsingGlobal());
ui->bg_button->setEnabled(Settings::values.bg_red.UsingGlobal());
+ ui->fsr_slider_layout->setEnabled(Settings::values.fsr_sharpening_slider.UsingGlobal());
return;
}
@@ -396,6 +432,13 @@ void ConfigureGraphics::SetupPerGameUI() {
ConfigurationShared::SetHighlight(ui->bg_layout, index == 1);
});
+ connect(ui->fsr_sharpening_combobox, qOverload<int>(&QComboBox::activated), this,
+ [this](int index) {
+ ui->fsr_sharpening_slider->setEnabled(index == 1);
+ ui->fsr_sharpening_value->setEnabled(index == 1);
+ ConfigurationShared::SetHighlight(ui->fsr_sharpening_layout, index == 1);
+ });
+
ConfigurationShared::SetColoredTristate(
ui->use_disk_shader_cache, Settings::values.use_disk_shader_cache, use_disk_shader_cache);
ConfigurationShared::SetColoredTristate(ui->accelerate_astc, Settings::values.accelerate_astc,
diff --git a/src/yuzu/configuration/configure_graphics.h b/src/yuzu/configuration/configure_graphics.h
index 70034eb1b..d98d6624e 100644
--- a/src/yuzu/configuration/configure_graphics.h
+++ b/src/yuzu/configuration/configure_graphics.h
@@ -42,6 +42,8 @@ private:
void RetrieveVulkanDevices();
+ void SetFSRIndicatorText(int percentage);
+
void SetupPerGameUI();
Settings::RendererBackend GetCurrentGraphicsBackend() const;
diff --git a/src/yuzu/configuration/configure_graphics.ui b/src/yuzu/configuration/configure_graphics.ui
index fdbb33372..f78396690 100644
--- a/src/yuzu/configuration/configure_graphics.ui
+++ b/src/yuzu/configuration/configure_graphics.ui
@@ -139,6 +139,11 @@
<string notr="true">Vulkan</string>
</property>
</item>
+ <item>
+ <property name="text">
+ <string>None</string>
+ </property>
+ </item>
</widget>
</item>
</layout>
@@ -152,6 +157,12 @@
</item>
<item>
<widget class="QGroupBox" name="groupBox">
+ <property name="maximumSize">
+ <size>
+ <width>16777215</width>
+ <height>16777215</height>
+ </size>
+ </property>
<property name="title">
<string>Graphics Settings</string>
</property>
@@ -482,6 +493,146 @@
</widget>
</item>
<item>
+ <widget class="QWidget" name="fsr_sharpening_layout" native="true">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <property name="spacing">
+ <number>6</number>
+ </property>
+ <property name="sizeConstraint">
+ <enum>QLayout::SetDefaultConstraint</enum>
+ </property>
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>0</number>
+ </property>
+ <item>
+ <layout class="QHBoxLayout" name="fsr_sharpening_label_group">
+ <item>
+ <widget class="QComboBox" name="fsr_sharpening_combobox">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Maximum" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <item>
+ <property name="text">
+ <string>Use global FSR Sharpness</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Set FSR Sharpness</string>
+ </property>
+ </item>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="fsr_sharpening_label">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>FSR Sharpness:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="fsr_slider_layout">
+ <property name="spacing">
+ <number>6</number>
+ </property>
+ <item>
+ <widget class="QSlider" name="fsr_sharpening_slider">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="baseSize">
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="maximum">
+ <number>200</number>
+ </property>
+ <property name="sliderPosition">
+ <number>25</number>
+ </property>
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="invertedAppearance">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="fsr_sharpening_value">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Maximum" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>32</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>100%</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignCenter</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
<widget class="QWidget" name="bg_layout" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
diff --git a/src/yuzu/configuration/configure_input_advanced.cpp b/src/yuzu/configuration/configure_input_advanced.cpp
index 10f841b98..235b813d9 100644
--- a/src/yuzu/configuration/configure_input_advanced.cpp
+++ b/src/yuzu/configuration/configure_input_advanced.cpp
@@ -194,4 +194,8 @@ void ConfigureInputAdvanced::UpdateUIEnabled() {
ui->mouse_panning->setEnabled(!ui->mouse_enabled->isChecked());
ui->mouse_panning_sensitivity->setEnabled(!ui->mouse_enabled->isChecked());
ui->ring_controller_configure->setEnabled(ui->enable_ring_controller->isChecked());
+#if QT_VERSION > QT_VERSION_CHECK(6, 0, 0) || !defined(YUZU_USE_QT_MULTIMEDIA)
+ ui->enable_ir_sensor->setEnabled(false);
+ ui->camera_configure->setEnabled(false);
+#endif
}
diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp
index 21983a799..c0afb2e5f 100644
--- a/src/yuzu/main.cpp
+++ b/src/yuzu/main.cpp
@@ -15,6 +15,7 @@
#endif
// VFS includes must be before glad as they will conflict with Windows file api, which uses defines.
+#include "applets/qt_amiibo_settings.h"
#include "applets/qt_controller.h"
#include "applets/qt_error.h"
#include "applets/qt_profile_select.h"
@@ -26,6 +27,7 @@
#include "configuration/configure_tas.h"
#include "core/file_sys/vfs.h"
#include "core/file_sys/vfs_real.h"
+#include "core/frontend/applets/cabinet.h"
#include "core/frontend/applets/controller.h"
#include "core/frontend/applets/general_frontend.h"
#include "core/frontend/applets/mii_edit.h"
@@ -166,6 +168,7 @@ __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
constexpr int default_mouse_hide_timeout = 2500;
constexpr int default_mouse_center_timeout = 10;
+constexpr int default_input_update_timeout = 1;
/**
* "Callouts" are one-time instructional messages shown to the user. In the config settings, there
@@ -236,6 +239,7 @@ static void LogRuntimes() {
LOG_INFO(Frontend, "Unable to inspect {}", runtime_dll_name);
}
#endif
+ LOG_INFO(Frontend, "Qt Compile: {} Runtime: {}", QT_VERSION_STR, qVersion());
}
static QString PrettyProductName() {
@@ -403,6 +407,10 @@ GMainWindow::GMainWindow(std::unique_ptr<Config> config_, bool has_broken_vulkan
mouse_center_timer.setInterval(default_mouse_center_timeout);
connect(&mouse_center_timer, &QTimer::timeout, this, &GMainWindow::CenterMouseCursor);
+ update_input_timer.setInterval(default_input_update_timeout);
+ connect(&update_input_timer, &QTimer::timeout, this, &GMainWindow::UpdateInputDrivers);
+ update_input_timer.start();
+
MigrateConfigFiles();
if (has_broken_vulkan) {
@@ -549,6 +557,11 @@ void GMainWindow::RegisterMetaTypes() {
// Register applet types
+ // Cabinet Applet
+ qRegisterMetaType<Core::Frontend::CabinetParameters>("Core::Frontend::CabinetParameters");
+ qRegisterMetaType<std::shared_ptr<Service::NFP::NfpDevice>>(
+ "std::shared_ptr<Service::NFP::NfpDevice>");
+
// Controller Applet
qRegisterMetaType<Core::Frontend::ControllerParameters>("Core::Frontend::ControllerParameters");
@@ -570,6 +583,21 @@ void GMainWindow::RegisterMetaTypes() {
qRegisterMetaType<Core::SystemResultStatus>("Core::SystemResultStatus");
}
+void GMainWindow::AmiiboSettingsShowDialog(const Core::Frontend::CabinetParameters& parameters,
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device) {
+ QtAmiiboSettingsDialog dialog(this, parameters, input_subsystem.get(), nfp_device);
+
+ dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint |
+ Qt::WindowTitleHint | Qt::WindowSystemMenuHint);
+ dialog.setWindowModality(Qt::WindowModal);
+ if (dialog.exec() == QDialog::Rejected) {
+ emit AmiiboSettingsFinished(false, {});
+ return;
+ }
+
+ emit AmiiboSettingsFinished(true, dialog.GetName());
+}
+
void GMainWindow::ControllerSelectorReconfigureControllers(
const Core::Frontend::ControllerParameters& parameters) {
QtControllerSelectorDialog dialog(this, parameters, input_subsystem.get(), *system);
@@ -985,29 +1013,11 @@ void GMainWindow::InitializeWidgets() {
renderer_status_button->setObjectName(QStringLiteral("RendererStatusBarButton"));
renderer_status_button->setCheckable(true);
renderer_status_button->setFocusPolicy(Qt::NoFocus);
- connect(renderer_status_button, &QPushButton::toggled, [this](bool checked) {
- renderer_status_button->setText(checked ? tr("VULKAN") : tr("OPENGL"));
- });
- renderer_status_button->toggle();
-
+ connect(renderer_status_button, &QPushButton::clicked, this, &GMainWindow::OnToggleGraphicsAPI);
+ UpdateAPIText();
+ renderer_status_button->setCheckable(true);
renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
Settings::RendererBackend::Vulkan);
- connect(renderer_status_button, &QPushButton::clicked, [this] {
- if (emulation_running) {
- return;
- }
- if (renderer_status_button->isChecked()) {
- Settings::values.renderer_backend.SetValue(Settings::RendererBackend::Vulkan);
- } else {
- Settings::values.renderer_backend.SetValue(Settings::RendererBackend::OpenGL);
- if (Settings::values.scaling_filter.GetValue() == Settings::ScalingFilter::Fsr) {
- Settings::values.scaling_filter.SetValue(Settings::ScalingFilter::NearestNeighbor);
- UpdateFilterText();
- }
- }
-
- system->ApplySettings();
- });
statusBar()->insertPermanentWidget(0, renderer_status_button);
statusBar()->setVisible(true);
@@ -1547,6 +1557,7 @@ bool GMainWindow::LoadROM(const QString& filename, u64 program_id, std::size_t p
system->SetFilesystem(vfs);
system->SetAppletFrontendSet({
+ std::make_unique<QtAmiiboSettings>(*this), // Amiibo Settings
std::make_unique<QtControllerSelector>(*this), // Controller Selector
std::make_unique<QtErrorDisplay>(*this), // Error Display
nullptr, // Mii Editor
@@ -1958,6 +1969,7 @@ void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target
}
default:
UNIMPLEMENTED();
+ break;
}
const QString qpath = QString::fromStdString(Common::FS::PathToUTF8String(path));
@@ -2823,6 +2835,7 @@ void GMainWindow::ErrorDisplayDisplayError(QString error_code, QString error_tex
}
void GMainWindow::OnMenuReportCompatibility() {
+#if defined(ARCHITECTURE_x86_64) && !defined(__APPLE__)
const auto& caps = Common::GetCPUCaps();
const bool has_fma = caps.fma || caps.fma4;
const auto processor_count = std::thread::hardware_concurrency();
@@ -2849,6 +2862,11 @@ void GMainWindow::OnMenuReportCompatibility() {
"&gt; "
"Web."));
}
+#else
+ QMessageBox::critical(this, tr("Hardware requirements not met"),
+ tr("Your system does not meet the recommended hardware requirements. "
+ "Compatibility reporting has been disabled."));
+#endif
}
void GMainWindow::OpenURL(const QUrl& url) {
@@ -3202,6 +3220,7 @@ void GMainWindow::OnToggleGpuAccuracy() {
case Settings::GPUAccuracy::Extreme:
default: {
Settings::values.gpu_accuracy.SetValue(Settings::GPUAccuracy::High);
+ break;
}
}
@@ -3225,6 +3244,18 @@ void GMainWindow::OnToggleAdaptingFilter() {
UpdateFilterText();
}
+void GMainWindow::OnToggleGraphicsAPI() {
+ auto api = Settings::values.renderer_backend.GetValue();
+ if (api == Settings::RendererBackend::OpenGL) {
+ api = Settings::RendererBackend::Vulkan;
+ } else {
+ api = Settings::RendererBackend::OpenGL;
+ }
+ Settings::values.renderer_backend.SetValue(api);
+ renderer_status_button->setChecked(api == Settings::RendererBackend::Vulkan);
+ UpdateAPIText();
+}
+
void GMainWindow::OnConfigurePerGame() {
const u64 title_id = system->GetCurrentProcessProgramID();
OpenPerGameConfiguration(title_id, current_game_path.toStdString());
@@ -3535,6 +3566,7 @@ void GMainWindow::UpdateGPUAccuracyButton() {
default: {
gpu_accuracy_button->setText(tr("GPU ERROR"));
gpu_accuracy_button->setChecked(true);
+ break;
}
}
}
@@ -3545,6 +3577,21 @@ void GMainWindow::UpdateDockedButton() {
dock_status_button->setText(is_docked ? tr("DOCKED") : tr("HANDHELD"));
}
+void GMainWindow::UpdateAPIText() {
+ const auto api = Settings::values.renderer_backend.GetValue();
+ switch (api) {
+ case Settings::RendererBackend::OpenGL:
+ renderer_status_button->setText(tr("OPENGL"));
+ break;
+ case Settings::RendererBackend::Vulkan:
+ renderer_status_button->setText(tr("VULKAN"));
+ break;
+ case Settings::RendererBackend::Null:
+ renderer_status_button->setText(tr("NULL"));
+ break;
+ }
+}
+
void GMainWindow::UpdateFilterText() {
const auto filter = Settings::values.scaling_filter.GetValue();
switch (filter) {
@@ -3590,6 +3637,7 @@ void GMainWindow::UpdateAAText() {
void GMainWindow::UpdateStatusButtons() {
renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
Settings::RendererBackend::Vulkan);
+ UpdateAPIText();
UpdateGPUAccuracyButton();
UpdateDockedButton();
UpdateFilterText();
@@ -3614,6 +3662,13 @@ void GMainWindow::UpdateUISettings() {
UISettings::values.first_start = false;
}
+void GMainWindow::UpdateInputDrivers() {
+ if (!input_subsystem) {
+ return;
+ }
+ input_subsystem->PumpEvents();
+}
+
void GMainWindow::HideMouseCursor() {
if (emu_thread == nullptr && UISettings::values.hide_mouse) {
mouse_hide_timer.stop();
@@ -4016,7 +4071,6 @@ void GMainWindow::UpdateUITheme() {
const QString default_theme =
QString::fromUtf8(UISettings::themes[static_cast<size_t>(Config::default_theme)].second);
QString current_theme = UISettings::values.theme;
- QStringList theme_paths(default_theme_paths);
if (current_theme.isEmpty()) {
current_theme = default_theme;
@@ -4029,7 +4083,7 @@ void GMainWindow::UpdateUITheme() {
if (current_theme == QStringLiteral("default") || current_theme == QStringLiteral("colorful")) {
QIcon::setThemeName(current_theme == QStringLiteral("colorful") ? current_theme
: startup_icon_theme);
- QIcon::setThemeSearchPaths(theme_paths);
+ QIcon::setThemeSearchPaths(QStringList(default_theme_paths));
if (CheckDarkMode()) {
current_theme = QStringLiteral("default_dark");
}
@@ -4197,10 +4251,12 @@ int main(int argc, char* argv[]) {
// so we can see if we get \u3008 instead
// TL;DR all other number formats are consecutive in unicode code points
// This bug is fixed in Qt6, specifically 6.0.0-alpha1
+#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
const QLocale locale = QLocale::system();
if (QStringLiteral("\u3008") == locale.toString(1)) {
QLocale::setDefault(QLocale::system().name());
}
+#endif
// Qt changes the locale and causes issues in float conversion using std::to_string() when
// generating shaders
diff --git a/src/yuzu/main.h b/src/yuzu/main.h
index b73f550dd..62d629973 100644
--- a/src/yuzu/main.h
+++ b/src/yuzu/main.h
@@ -55,6 +55,7 @@ class System;
} // namespace Core
namespace Core::Frontend {
+struct CabinetParameters;
struct ControllerParameters;
struct InlineAppearParameters;
struct InlineTextParameters;
@@ -82,6 +83,10 @@ enum class SwkbdReplyType : u32;
enum class WebExitReason : u32;
} // namespace Service::AM::Applets
+namespace Service::NFP {
+class NfpDevice;
+} // namespace Service::NFP
+
namespace Ui {
class MainWindow;
}
@@ -149,6 +154,8 @@ signals:
void UpdateInstallProgress();
+ void AmiiboSettingsFinished(bool is_success, const std::string& name);
+
void ControllerSelectorReconfigureFinished();
void ErrorDisplayFinished();
@@ -170,6 +177,8 @@ public slots:
void OnExecuteProgram(std::size_t program_index);
void OnExit();
void OnSaveConfig();
+ void AmiiboSettingsShowDialog(const Core::Frontend::CabinetParameters& parameters,
+ std::shared_ptr<Service::NFP::NfpDevice> nfp_device);
void ControllerSelectorReconfigureControllers(
const Core::Frontend::ControllerParameters& parameters);
void SoftwareKeyboardInitialize(
@@ -298,6 +307,7 @@ private slots:
void OnTasStartStop();
void OnTasRecord();
void OnTasReset();
+ void OnToggleGraphicsAPI();
void OnToggleDockedMode();
void OnToggleGpuAccuracy();
void OnToggleAdaptingFilter();
@@ -338,12 +348,14 @@ private:
void UpdateWindowTitle(std::string_view title_name = {}, std::string_view title_version = {},
std::string_view gpu_vendor = {});
void UpdateDockedButton();
+ void UpdateAPIText();
void UpdateFilterText();
void UpdateAAText();
void UpdateStatusBar();
void UpdateGPUAccuracyButton();
void UpdateStatusButtons();
void UpdateUISettings();
+ void UpdateInputDrivers();
void HideMouseCursor();
void ShowMouseCursor();
void CenterMouseCursor();
@@ -395,6 +407,7 @@ private:
bool auto_muted = false;
QTimer mouse_hide_timer;
QTimer mouse_center_timer;
+ QTimer update_input_timer;
QString startup_icon_theme;
bool os_dark_mode = false;
diff --git a/src/yuzu/main.ui b/src/yuzu/main.ui
index e670acc30..013ba0ceb 100644
--- a/src/yuzu/main.ui
+++ b/src/yuzu/main.ui
@@ -231,6 +231,9 @@
<property name="text">
<string>Con&amp;figure...</string>
</property>
+ <property name="menuRole">
+ <enum>QAction::PreferencesRole</enum>
+ </property>
</action>
<action name="action_Display_Dock_Widget_Headers">
<property name="checkable">
@@ -363,6 +366,9 @@
<property name="text">
<string>&amp;Configure TAS...</string>
</property>
+ <property name="menuRole">
+ <enum>QAction::NoRole</enum>
+ </property>
</action>
<action name="action_Configure_Current_Game">
<property name="enabled">
@@ -371,6 +377,9 @@
<property name="text">
<string>Configure C&amp;urrent Game...</string>
</property>
+ <property name="menuRole">
+ <enum>QAction::NoRole</enum>
+ </property>
</action>
<action name="action_TAS_Start">
<property name="enabled">
diff --git a/src/yuzu/multiplayer/chat_room.h b/src/yuzu/multiplayer/chat_room.h
index 01c70fad0..dd71ea4cd 100644
--- a/src/yuzu/multiplayer/chat_room.h
+++ b/src/yuzu/multiplayer/chat_room.h
@@ -4,6 +4,7 @@
#pragma once
#include <memory>
+#include <unordered_map>
#include <unordered_set>
#include <QDialog>
#include <QSortFilterProxyModel>
diff --git a/src/yuzu/multiplayer/direct_connect.cpp b/src/yuzu/multiplayer/direct_connect.cpp
index 10bf0a4fb..cbd52da85 100644
--- a/src/yuzu/multiplayer/direct_connect.cpp
+++ b/src/yuzu/multiplayer/direct_connect.cpp
@@ -4,7 +4,7 @@
#include <QComboBox>
#include <QFuture>
#include <QIntValidator>
-#include <QRegExpValidator>
+#include <QRegularExpressionValidator>
#include <QString>
#include <QtConcurrent/QtConcurrentRun>
#include "common/settings.h"
diff --git a/src/yuzu/multiplayer/validation.h b/src/yuzu/multiplayer/validation.h
index dabf860be..dd25af280 100644
--- a/src/yuzu/multiplayer/validation.h
+++ b/src/yuzu/multiplayer/validation.h
@@ -3,7 +3,7 @@
#pragma once
-#include <QRegExp>
+#include <QRegularExpression>
#include <QString>
#include <QValidator>
@@ -29,19 +29,21 @@ public:
private:
/// room name can be alphanumeric and " " "_" "." and "-" and must have a size of 4-20
- QRegExp room_name_regex = QRegExp(QStringLiteral("^[a-zA-Z0-9._- ]{4,20}$"));
- QRegExpValidator room_name;
+ QRegularExpression room_name_regex =
+ QRegularExpression(QStringLiteral("^[a-zA-Z0-9._ -]{4,20}"));
+ QRegularExpressionValidator room_name;
/// nickname can be alphanumeric and " " "_" "." and "-" and must have a size of 4-20
- QRegExp nickname_regex = QRegExp(QStringLiteral("^[a-zA-Z0-9._- ]{4,20}$"));
- QRegExpValidator nickname;
+ const QRegularExpression nickname_regex =
+ QRegularExpression(QStringLiteral("^[a-zA-Z0-9._ -]{4,20}"));
+ QRegularExpressionValidator nickname;
/// ipv4 address only
// TODO remove this when we support hostnames in direct connect
- QRegExp ip_regex = QRegExp(QStringLiteral(
+ QRegularExpression ip_regex = QRegularExpression(QStringLiteral(
"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|"
"2[0-4][0-9]|25[0-5])"));
- QRegExpValidator ip;
+ QRegularExpressionValidator ip;
/// port must be between 0 and 65535
QIntValidator port;
diff --git a/src/yuzu/precompiled_headers.h b/src/yuzu/precompiled_headers.h
new file mode 100644
index 000000000..aabae730b
--- /dev/null
+++ b/src/yuzu/precompiled_headers.h
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
diff --git a/src/yuzu/startup_checks.cpp b/src/yuzu/startup_checks.cpp
index 6a91212e2..563818362 100644
--- a/src/yuzu/startup_checks.cpp
+++ b/src/yuzu/startup_checks.cpp
@@ -4,16 +4,19 @@
#include "video_core/vulkan_common/vulkan_wrapper.h"
#ifdef _WIN32
-#include <cstring> // for memset, strncpy
+#include <cstring>
#include <processthreadsapi.h>
#include <windows.h>
#elif defined(YUZU_UNIX)
+#include <cstring>
#include <errno.h>
+#include <spawn.h>
+#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
-#include <cstdio>
+#include <fmt/core.h>
#include "video_core/vulkan_common/vulkan_instance.h"
#include "video_core/vulkan_common/vulkan_library.h"
#include "yuzu/startup_checks.h"
@@ -24,10 +27,10 @@ void CheckVulkan() {
Vulkan::vk::InstanceDispatch dld;
const Common::DynamicLibrary library = Vulkan::OpenLibrary();
const Vulkan::vk::Instance instance =
- Vulkan::CreateInstance(library, dld, VK_API_VERSION_1_0);
+ Vulkan::CreateInstance(library, dld, VK_API_VERSION_1_1);
} catch (const Vulkan::vk::Exception& exception) {
- std::fprintf(stderr, "Failed to initialize Vulkan: %s\n", exception.what());
+ fmt::print(stderr, "Failed to initialize Vulkan: {}\n", exception.what());
}
}
@@ -49,8 +52,15 @@ bool CheckEnvVars(bool* is_child) {
*is_child = true;
return false;
} else if (!SetEnvironmentVariableA(IS_CHILD_ENV_VAR, ENV_VAR_ENABLED_TEXT)) {
- std::fprintf(stderr, "SetEnvironmentVariableA failed to set %s with error %lu\n",
- IS_CHILD_ENV_VAR, GetLastError());
+ fmt::print(stderr, "SetEnvironmentVariableA failed to set {} with error {}\n",
+ IS_CHILD_ENV_VAR, GetLastError());
+ return true;
+ }
+#elif defined(YUZU_UNIX)
+ const char* startup_check_var = getenv(STARTUP_CHECK_ENV_VAR);
+ if (startup_check_var != nullptr &&
+ std::strncmp(startup_check_var, ENV_VAR_ENABLED_TEXT, 8) == 0) {
+ CheckVulkan();
return true;
}
#endif
@@ -62,8 +72,8 @@ bool StartupChecks(const char* arg0, bool* has_broken_vulkan, bool perform_vulka
// Set the startup variable for child processes
const bool env_var_set = SetEnvironmentVariableA(STARTUP_CHECK_ENV_VAR, ENV_VAR_ENABLED_TEXT);
if (!env_var_set) {
- std::fprintf(stderr, "SetEnvironmentVariableA failed to set %s with error %lu\n",
- STARTUP_CHECK_ENV_VAR, GetLastError());
+ fmt::print(stderr, "SetEnvironmentVariableA failed to set {} with error {}\n",
+ STARTUP_CHECK_ENV_VAR, GetLastError());
return false;
}
@@ -81,48 +91,57 @@ bool StartupChecks(const char* arg0, bool* has_broken_vulkan, bool perform_vulka
DWORD exit_code = STILL_ACTIVE;
const int err = GetExitCodeProcess(process_info.hProcess, &exit_code);
if (err == 0) {
- std::fprintf(stderr, "GetExitCodeProcess failed with error %lu\n", GetLastError());
+ fmt::print(stderr, "GetExitCodeProcess failed with error {}\n", GetLastError());
}
// Vulkan is broken if the child crashed (return value is not zero)
*has_broken_vulkan = (exit_code != 0);
if (CloseHandle(process_info.hProcess) == 0) {
- std::fprintf(stderr, "CloseHandle failed with error %lu\n", GetLastError());
+ fmt::print(stderr, "CloseHandle failed with error {}\n", GetLastError());
}
if (CloseHandle(process_info.hThread) == 0) {
- std::fprintf(stderr, "CloseHandle failed with error %lu\n", GetLastError());
+ fmt::print(stderr, "CloseHandle failed with error {}\n", GetLastError());
}
}
if (!SetEnvironmentVariableA(STARTUP_CHECK_ENV_VAR, nullptr)) {
- std::fprintf(stderr, "SetEnvironmentVariableA failed to clear %s with error %lu\n",
- STARTUP_CHECK_ENV_VAR, GetLastError());
+ fmt::print(stderr, "SetEnvironmentVariableA failed to clear {} with error {}\n",
+ STARTUP_CHECK_ENV_VAR, GetLastError());
}
#elif defined(YUZU_UNIX)
+ const int env_var_set = setenv(STARTUP_CHECK_ENV_VAR, ENV_VAR_ENABLED_TEXT, 1);
+ if (env_var_set == -1) {
+ const int err = errno;
+ fmt::print(stderr, "setenv failed to set {} with error {}\n", STARTUP_CHECK_ENV_VAR, err);
+ return false;
+ }
+
if (perform_vulkan_check) {
- const pid_t pid = fork();
- if (pid == 0) {
- CheckVulkan();
- return true;
- } else if (pid == -1) {
- const int err = errno;
- std::fprintf(stderr, "fork failed with error %d\n", err);
+ const pid_t pid = SpawnChild(arg0);
+ if (pid == -1) {
return false;
}
// Get exit code from child process
int status;
- const int r_val = wait(&status);
+ const int r_val = waitpid(pid, &status, 0);
if (r_val == -1) {
const int err = errno;
- std::fprintf(stderr, "wait failed with error %d\n", err);
+ fmt::print(stderr, "wait failed with error {}\n", err);
return false;
}
// Vulkan is broken if the child crashed (return value is not zero)
*has_broken_vulkan = (status != 0);
}
+
+ const int env_var_cleared = unsetenv(STARTUP_CHECK_ENV_VAR);
+ if (env_var_cleared == -1) {
+ const int err = errno;
+ fmt::print(stderr, "unsetenv failed to clear {} with error {}\n", STARTUP_CHECK_ENV_VAR,
+ err);
+ }
#endif
return false;
}
@@ -150,10 +169,29 @@ bool SpawnChild(const char* arg0, PROCESS_INFORMATION* pi, int flags) {
pi // lpProcessInformation
);
if (!process_created) {
- std::fprintf(stderr, "CreateProcessA failed with error %lu\n", GetLastError());
+ fmt::print(stderr, "CreateProcessA failed with error {}\n", GetLastError());
return false;
}
return true;
}
+#elif defined(YUZU_UNIX)
+pid_t SpawnChild(const char* arg0) {
+ const pid_t pid = fork();
+
+ if (pid == -1) {
+ // error
+ const int err = errno;
+ fmt::print(stderr, "fork failed with error {}\n", err);
+ return pid;
+ } else if (pid == 0) {
+ // child
+ execl(arg0, arg0, nullptr);
+ const int err = errno;
+ fmt::print(stderr, "execl failed with error {}\n", err);
+ _exit(0);
+ }
+
+ return pid;
+}
#endif
diff --git a/src/yuzu/startup_checks.h b/src/yuzu/startup_checks.h
index d8e563be6..2f86fb843 100644
--- a/src/yuzu/startup_checks.h
+++ b/src/yuzu/startup_checks.h
@@ -5,6 +5,8 @@
#ifdef _WIN32
#include <windows.h>
+#elif defined(YUZU_UNIX)
+#include <sys/types.h>
#endif
constexpr char IS_CHILD_ENV_VAR[] = "YUZU_IS_CHILD";
@@ -17,4 +19,6 @@ bool StartupChecks(const char* arg0, bool* has_broken_vulkan, bool perform_vulka
#ifdef _WIN32
bool SpawnChild(const char* arg0, PROCESS_INFORMATION* pi, int flags);
+#elif defined(YUZU_UNIX)
+pid_t SpawnChild(const char* arg0);
#endif
diff --git a/src/yuzu_cmd/CMakeLists.txt b/src/yuzu_cmd/CMakeLists.txt
index 7d8ca3d8a..1c0c1a9fe 100644
--- a/src/yuzu_cmd/CMakeLists.txt
+++ b/src/yuzu_cmd/CMakeLists.txt
@@ -22,8 +22,11 @@ add_executable(yuzu-cmd
emu_window/emu_window_sdl2.h
emu_window/emu_window_sdl2_gl.cpp
emu_window/emu_window_sdl2_gl.h
+ emu_window/emu_window_sdl2_null.cpp
+ emu_window/emu_window_sdl2_null.h
emu_window/emu_window_sdl2_vk.cpp
emu_window/emu_window_sdl2_vk.h
+ precompiled_headers.h
yuzu.cpp
yuzu.rc
)
@@ -35,7 +38,7 @@ target_link_libraries(yuzu-cmd PRIVATE inih glad)
if (MSVC)
target_link_libraries(yuzu-cmd PRIVATE getopt)
endif()
-target_link_libraries(yuzu-cmd PRIVATE ${PLATFORM_LIBRARIES} SDL2 Threads::Threads)
+target_link_libraries(yuzu-cmd PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads)
create_resource("../../dist/yuzu.bmp" "yuzu_cmd/yuzu_icon.h" "yuzu_icon")
target_include_directories(yuzu-cmd PRIVATE ${RESOURCES_DIR})
@@ -43,8 +46,9 @@ target_include_directories(yuzu-cmd PRIVATE ${RESOURCES_DIR})
target_include_directories(yuzu-cmd PRIVATE ../../externals/Vulkan-Headers/include)
if (YUZU_USE_EXTERNAL_SDL2)
- target_compile_definitions(yuzu-cmd PRIVATE -DYUZU_USE_EXTERNAL_SDL2)
- target_include_directories(yuzu-cmd PRIVATE ${PROJECT_BINARY_DIR}/externals/SDL/include)
+ target_link_libraries(yuzu-cmd PRIVATE SDL2-static)
+else()
+ target_link_libraries(yuzu-cmd PRIVATE SDL2)
endif()
if(UNIX AND NOT APPLE)
@@ -55,3 +59,7 @@ if (MSVC)
include(CopyYuzuSDLDeps)
copy_yuzu_SDL_deps(yuzu-cmd)
endif()
+
+if (YUZU_USE_PRECOMPILED_HEADERS)
+ target_precompile_headers(yuzu-cmd PRIVATE precompiled_headers.h)
+endif()
diff --git a/src/yuzu_cmd/config.cpp b/src/yuzu_cmd/config.cpp
index 66dd0dc15..59f9c8e09 100644
--- a/src/yuzu_cmd/config.cpp
+++ b/src/yuzu_cmd/config.cpp
@@ -90,7 +90,11 @@ static const std::array<std::array<int, 5>, Settings::NativeAnalog::NumAnalogs>
template <>
void Config::ReadSetting(const std::string& group, Settings::Setting<std::string>& setting) {
- setting = sdl2_config->Get(group, setting.GetLabel(), setting.GetDefault());
+ std::string setting_value = sdl2_config->Get(group, setting.GetLabel(), setting.GetDefault());
+ if (setting_value.empty()) {
+ setting_value = setting.GetDefault();
+ }
+ setting = std::move(setting_value);
}
template <>
@@ -299,6 +303,7 @@ void Config::ReadValues() {
ReadSetting("Renderer", Settings::values.resolution_setup);
ReadSetting("Renderer", Settings::values.scaling_filter);
+ ReadSetting("Renderer", Settings::values.fsr_sharpening_slider);
ReadSetting("Renderer", Settings::values.anti_aliasing);
ReadSetting("Renderer", Settings::values.fullscreen_mode);
ReadSetting("Renderer", Settings::values.aspect_ratio);
diff --git a/src/yuzu_cmd/default_ini.h b/src/yuzu_cmd/default_ini.h
index d214771b0..5bbc3f532 100644
--- a/src/yuzu_cmd/default_ini.h
+++ b/src/yuzu_cmd/default_ini.h
@@ -6,16 +6,22 @@
namespace DefaultINI {
const char* sdl2_config_file = R"(
-[ControlsGeneral]
+
+[ControlsP0]
# The input devices and parameters for each Switch native input
+# The config section determines the player number where the config will be applied on. For example "ControlsP0", "ControlsP1", ...
# It should be in the format of "engine:[engine_name],[param1]:[value1],[param2]:[value2]..."
# Escape characters $0 (for ':'), $1 (for ',') and $2 (for '$') can be used in values
+# Indicates if this player should be connected at boot
+connected=
+
# for button input, the following devices are available:
# - "keyboard" (default) for keyboard input. Required parameters:
# - "code": the code of the key to bind
# - "sdl" for joystick input using SDL. Required parameters:
-# - "joystick": the index of the joystick to bind
+# - "guid": SDL identification GUID of the joystick
+# - "port": the index of the joystick to bind
# - "button"(optional): the index of the button to bind
# - "hat"(optional): the index of the hat to bind as direction buttons
# - "axis"(optional): the index of the axis to bind
@@ -58,12 +64,29 @@ button_screenshot=
# - "modifier_scale": a float number representing the applied modifier scale to the analog input.
# Must be in range of 0.0-1.0. Defaults to 0.5
# - "sdl" for joystick input using SDL. Required parameters:
-# - "joystick": the index of the joystick to bind
+# - "guid": SDL identification GUID of the joystick
+# - "port": the index of the joystick to bind
# - "axis_x": the index of the axis to bind as x-axis (default to 0)
# - "axis_y": the index of the axis to bind as y-axis (default to 1)
lstick=
rstick=
+# for motion input, the following devices are available:
+# - "keyboard" (default) for emulating random motion input from buttons. Required parameters:
+# - "code": the code of the key to bind
+# - "sdl" for motion input using SDL. Required parameters:
+# - "guid": SDL identification GUID of the joystick
+# - "port": the index of the joystick to bind
+# - "motion": the index of the motion sensor to bind
+# - "cemuhookudp" for motion input using Cemu Hook protocol. Required parameters:
+# - "guid": the IP address of the cemu hook server encoded to a hex string. for example 192.168.0.1 = "c0a80001"
+# - "port": the port of the cemu hook server
+# - "pad": the index of the joystick
+# - "motion": the index of the motion sensor of the joystick to bind
+motionleft=
+motionright=
+
+[ControlsGeneral]
# To use the debug_pad, prepend `debug_pad_` before each button setting above.
# i.e. debug_pad_button_a=
diff --git a/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp b/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
index 4ac72c2f6..37dd1747c 100644
--- a/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
+++ b/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
@@ -7,6 +7,7 @@
#include "common/scm_rev.h"
#include "common/settings.h"
#include "core/core.h"
+#include "core/hid/hid_core.h"
#include "core/perf_stats.h"
#include "input_common/drivers/keyboard.h"
#include "input_common/drivers/mouse.h"
@@ -26,6 +27,7 @@ EmuWindow_SDL2::EmuWindow_SDL2(InputCommon::InputSubsystem* input_subsystem_, Co
}
EmuWindow_SDL2::~EmuWindow_SDL2() {
+ system.HIDCore().UnloadInputDevices();
input_subsystem->Shutdown();
SDL_Quit();
}
diff --git a/src/yuzu_cmd/emu_window/emu_window_sdl2.h b/src/yuzu_cmd/emu_window/emu_window_sdl2.h
index 90bb0b415..25c23e2a5 100644
--- a/src/yuzu_cmd/emu_window/emu_window_sdl2.h
+++ b/src/yuzu_cmd/emu_window/emu_window_sdl2.h
@@ -89,3 +89,5 @@ protected:
/// yuzu core instance
Core::System& system;
};
+
+class DummyContext : public Core::Frontend::GraphicsContext {};
diff --git a/src/yuzu_cmd/emu_window/emu_window_sdl2_null.cpp b/src/yuzu_cmd/emu_window/emu_window_sdl2_null.cpp
new file mode 100644
index 000000000..259192f3c
--- /dev/null
+++ b/src/yuzu_cmd/emu_window/emu_window_sdl2_null.cpp
@@ -0,0 +1,51 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include <cstdlib>
+#include <memory>
+#include <string>
+
+#include <fmt/format.h>
+
+#include "common/logging/log.h"
+#include "common/scm_rev.h"
+#include "video_core/renderer_null/renderer_null.h"
+#include "yuzu_cmd/emu_window/emu_window_sdl2_null.h"
+
+#ifdef YUZU_USE_EXTERNAL_SDL2
+// Include this before SDL.h to prevent the external from including a dummy
+#define USING_GENERATED_CONFIG_H
+#include <SDL_config.h>
+#endif
+
+#include <SDL.h>
+
+EmuWindow_SDL2_Null::EmuWindow_SDL2_Null(InputCommon::InputSubsystem* input_subsystem_,
+ Core::System& system_, bool fullscreen)
+ : EmuWindow_SDL2{input_subsystem_, system_} {
+ const std::string window_title = fmt::format("yuzu {} | {}-{} (Vulkan)", Common::g_build_name,
+ Common::g_scm_branch, Common::g_scm_desc);
+ render_window =
+ SDL_CreateWindow(window_title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
+ Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height,
+ SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
+
+ SetWindowIcon();
+
+ if (fullscreen) {
+ Fullscreen();
+ ShowCursor(false);
+ }
+
+ OnResize();
+ OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
+ SDL_PumpEvents();
+ LOG_INFO(Frontend, "yuzu Version: {} | {}-{} (Null)", Common::g_build_name,
+ Common::g_scm_branch, Common::g_scm_desc);
+}
+
+EmuWindow_SDL2_Null::~EmuWindow_SDL2_Null() = default;
+
+std::unique_ptr<Core::Frontend::GraphicsContext> EmuWindow_SDL2_Null::CreateSharedContext() const {
+ return std::make_unique<DummyContext>();
+}
diff --git a/src/yuzu_cmd/emu_window/emu_window_sdl2_null.h b/src/yuzu_cmd/emu_window/emu_window_sdl2_null.h
new file mode 100644
index 000000000..35aee286d
--- /dev/null
+++ b/src/yuzu_cmd/emu_window/emu_window_sdl2_null.h
@@ -0,0 +1,26 @@
+// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include <memory>
+
+#include "core/frontend/emu_window.h"
+#include "yuzu_cmd/emu_window/emu_window_sdl2.h"
+
+namespace Core {
+class System;
+}
+
+namespace InputCommon {
+class InputSubsystem;
+}
+
+class EmuWindow_SDL2_Null final : public EmuWindow_SDL2 {
+public:
+ explicit EmuWindow_SDL2_Null(InputCommon::InputSubsystem* input_subsystem_,
+ Core::System& system, bool fullscreen);
+ ~EmuWindow_SDL2_Null() override;
+
+ std::unique_ptr<Core::Frontend::GraphicsContext> CreateSharedContext() const override;
+};
diff --git a/src/yuzu_cmd/emu_window/emu_window_sdl2_vk.cpp b/src/yuzu_cmd/emu_window/emu_window_sdl2_vk.cpp
index 65455c86e..9ed47d453 100644
--- a/src/yuzu_cmd/emu_window/emu_window_sdl2_vk.cpp
+++ b/src/yuzu_cmd/emu_window/emu_window_sdl2_vk.cpp
@@ -12,12 +12,6 @@
#include "video_core/renderer_vulkan/renderer_vulkan.h"
#include "yuzu_cmd/emu_window/emu_window_sdl2_vk.h"
-#ifdef YUZU_USE_EXTERNAL_SDL2
-// Include this before SDL.h to prevent the external from including a dummy
-#define USING_GENERATED_CONFIG_H
-#include <SDL_config.h>
-#endif
-
#include <SDL.h>
#include <SDL_syswm.h>
@@ -51,11 +45,6 @@ EmuWindow_SDL2_VK::EmuWindow_SDL2_VK(InputCommon::InputSubsystem* input_subsyste
window_info.type = Core::Frontend::WindowSystemType::Windows;
window_info.render_surface = reinterpret_cast<void*>(wm.info.win.window);
break;
-#else
- case SDL_SYSWM_TYPE::SDL_SYSWM_WINDOWS:
- LOG_CRITICAL(Frontend, "Window manager subsystem Windows not compiled");
- std::exit(EXIT_FAILURE);
- break;
#endif
#ifdef SDL_VIDEO_DRIVER_X11
case SDL_SYSWM_TYPE::SDL_SYSWM_X11:
@@ -63,11 +52,6 @@ EmuWindow_SDL2_VK::EmuWindow_SDL2_VK(InputCommon::InputSubsystem* input_subsyste
window_info.display_connection = wm.info.x11.display;
window_info.render_surface = reinterpret_cast<void*>(wm.info.x11.window);
break;
-#else
- case SDL_SYSWM_TYPE::SDL_SYSWM_X11:
- LOG_CRITICAL(Frontend, "Window manager subsystem X11 not compiled");
- std::exit(EXIT_FAILURE);
- break;
#endif
#ifdef SDL_VIDEO_DRIVER_WAYLAND
case SDL_SYSWM_TYPE::SDL_SYSWM_WAYLAND:
@@ -75,15 +59,23 @@ EmuWindow_SDL2_VK::EmuWindow_SDL2_VK(InputCommon::InputSubsystem* input_subsyste
window_info.display_connection = wm.info.wl.display;
window_info.render_surface = wm.info.wl.surface;
break;
-#else
- case SDL_SYSWM_TYPE::SDL_SYSWM_WAYLAND:
- LOG_CRITICAL(Frontend, "Window manager subsystem Wayland not compiled");
- std::exit(EXIT_FAILURE);
+#endif
+#ifdef SDL_VIDEO_DRIVER_COCOA
+ case SDL_SYSWM_TYPE::SDL_SYSWM_COCOA:
+ window_info.type = Core::Frontend::WindowSystemType::Cocoa;
+ window_info.render_surface = SDL_Metal_CreateView(render_window);
+ break;
+#endif
+#ifdef SDL_VIDEO_DRIVER_ANDROID
+ case SDL_SYSWM_TYPE::SDL_SYSWM_ANDROID:
+ window_info.type = Core::Frontend::WindowSystemType::Android;
+ window_info.render_surface = reinterpret_cast<void*>(wm.info.android.window);
break;
#endif
default:
- LOG_CRITICAL(Frontend, "Window manager subsystem not implemented");
+ LOG_CRITICAL(Frontend, "Window manager subsystem {} not implemented", wm.subsystem);
std::exit(EXIT_FAILURE);
+ break;
}
OnResize();
diff --git a/src/yuzu_cmd/emu_window/emu_window_sdl2_vk.h b/src/yuzu_cmd/emu_window/emu_window_sdl2_vk.h
index e39ad754d..9467d164a 100644
--- a/src/yuzu_cmd/emu_window/emu_window_sdl2_vk.h
+++ b/src/yuzu_cmd/emu_window/emu_window_sdl2_vk.h
@@ -24,5 +24,3 @@ public:
std::unique_ptr<Core::Frontend::GraphicsContext> CreateSharedContext() const override;
};
-
-class DummyContext : public Core::Frontend::GraphicsContext {};
diff --git a/src/yuzu_cmd/precompiled_headers.h b/src/yuzu_cmd/precompiled_headers.h
new file mode 100644
index 000000000..aabae730b
--- /dev/null
+++ b/src/yuzu_cmd/precompiled_headers.h
@@ -0,0 +1,6 @@
+// SPDX-FileCopyrightText: 2022 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#pragma once
+
+#include "common/common_precompiled_headers.h"
diff --git a/src/yuzu_cmd/yuzu.cpp b/src/yuzu_cmd/yuzu.cpp
index e16f79eb4..a80649703 100644
--- a/src/yuzu_cmd/yuzu.cpp
+++ b/src/yuzu_cmd/yuzu.cpp
@@ -34,6 +34,7 @@
#include "yuzu_cmd/config.h"
#include "yuzu_cmd/emu_window/emu_window_sdl2.h"
#include "yuzu_cmd/emu_window/emu_window_sdl2_gl.h"
+#include "yuzu_cmd/emu_window/emu_window_sdl2_null.h"
#include "yuzu_cmd/emu_window/emu_window_sdl2_vk.h"
#ifdef _WIN32
@@ -317,6 +318,9 @@ int main(int argc, char** argv) {
case Settings::RendererBackend::Vulkan:
emu_window = std::make_unique<EmuWindow_SDL2_VK>(&input_subsystem, system, fullscreen);
break;
+ case Settings::RendererBackend::Null:
+ emu_window = std::make_unique<EmuWindow_SDL2_Null>(&input_subsystem, system, fullscreen);
+ break;
}
system.SetContentProvider(std::make_unique<FileSys::ContentProviderUnion>());
@@ -351,6 +355,7 @@ int main(int argc, char** argv) {
"additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}",
loader_id, error_id, static_cast<Loader::ResultStatus>(error_id));
}
+ break;
}
system.TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "SDL");