diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 5ee4a366..36878560 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -229,11 +229,6 @@ jobs: token: ${{ secrets.ASSET_REPO_TOKEN }} path: ./private - - name: Setup latest Xcode - uses: maxim-lobanov/setup-xcode@v1 - with: - xcode-version: latest-stable - - name: Setup ccache uses: hendrikmuhs/ccache-action@v1.2 with: diff --git a/.gitmodules b/.gitmodules index b4b2dba8..0976521b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -6,7 +6,7 @@ url = https://github.com/redorav/ddspp.git [submodule "tools/XenosRecomp"] path = tools/XenosRecomp - url = https://github.com/hedge-dev/XenosRecomp.git + url = https://github.com/squidbus/XenosRecomp.git [submodule "UnleashedRecompResources"] path = UnleashedRecompResources url = https://github.com/hedge-dev/UnleashedRecompResources.git @@ -58,3 +58,6 @@ [submodule "thirdparty/plume"] path = thirdparty/plume url = https://github.com/renderbag/plume.git +[submodule "thirdparty/ios-cmake"] + path = thirdparty/ios-cmake + url = https://github.com/leetal/ios-cmake.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 6a06ffb1..f525f1d0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,11 @@ -cmake_minimum_required (VERSION 3.20) +cmake_minimum_required(VERSION 3.20) if(NOT DEFINED ENV{VCPKG_ROOT}) - message(FATAL_ERROR "VCPKG_ROOT is not defined!") + if(EXISTS "${CMAKE_SOURCE_DIR}/thirdparty/vcpkg/scripts/buildsystems/vcpkg.cmake") + set(ENV{VCPKG_ROOT} "${CMAKE_SOURCE_DIR}/thirdparty/vcpkg") + else() + message(FATAL_ERROR "VCPKG_ROOT is not defined!") + endif() endif() set(UNLEASHED_RECOMP_THIRDPARTY_ROOT ${CMAKE_SOURCE_DIR}/thirdparty) @@ -10,36 +14,42 @@ set(CMAKE_CXX_STANDARD 20) set(BUILD_SHARED_LIBS OFF) # Enable Hot Reload for MSVC compilers if supported. -if (POLICY CMP0141) - cmake_policy(SET CMP0141 NEW) - set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$,$>,$<$:EditAndContinue>,$<$:ProgramDatabase>>") +if(POLICY CMP0141) + cmake_policy(SET CMP0141 NEW) + set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$,$>,$<$:EditAndContinue>,$<$:ProgramDatabase>>") endif() set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") project("UnleashedRecomp-ALL") -if (APPLE) +if(APPLE) enable_language(OBJC OBJCXX) endif() -if (CMAKE_OSX_ARCHITECTURES) +if(CMAKE_OSX_ARCHITECTURES) set(UNLEASHED_RECOMP_ARCHITECTURE ${CMAKE_OSX_ARCHITECTURES}) elseif(CMAKE_SYSTEM_PROCESSOR) set(UNLEASHED_RECOMP_ARCHITECTURE ${CMAKE_SYSTEM_PROCESSOR}) else() set(UNLEASHED_RECOMP_ARCHITECTURE ${CMAKE_HOST_SYSTEM_PROCESSOR}) endif() + string(TOLOWER "${UNLEASHED_RECOMP_ARCHITECTURE}" UNLEASHED_RECOMP_ARCHITECTURE) message(STATUS "Detected architecture: ${UNLEASHED_RECOMP_ARCHITECTURE}") -if (UNLEASHED_RECOMP_ARCHITECTURE STREQUAL "x86_64" OR UNLEASHED_RECOMP_ARCHITECTURE STREQUAL "amd64") +if(UNLEASHED_RECOMP_ARCHITECTURE STREQUAL "x86_64" OR UNLEASHED_RECOMP_ARCHITECTURE STREQUAL "amd64") # Target Sandy Bridge for all projects add_compile_options( -march=sandybridge ) endif() +if(CMAKE_BUILD_TYPE STREQUAL "Debug") + # Normally only defined by Visual Studio, added for consistency + add_compile_definitions(_DEBUG) +endif() + add_subdirectory(${UNLEASHED_RECOMP_THIRDPARTY_ROOT}) add_subdirectory(${UNLEASHED_RECOMP_TOOLS_ROOT}) diff --git a/CMakePresets.json b/CMakePresets.json index b64ca36a..6a8c6ed2 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -165,6 +165,66 @@ "CMAKE_BUILD_TYPE": "Release", "CMAKE_INTERPROCEDURAL_OPTIMIZATION": true } + }, + { + "name": "ios-base", + "hidden": true, + "generator": "Ninja", + "binaryDir": "${sourceDir}/out/build/${presetName}", + "installDir": "${sourceDir}/out/install/${presetName}", + "cacheVariables": { + "CMAKE_SYSTEM_NAME": "iOS", + "CMAKE_OSX_SYSROOT": "iphoneos", + "CMAKE_OSX_ARCHITECTURES": "arm64", + "CMAKE_OSX_DEPLOYMENT_TARGET": "16.4", + "DEPLOYMENT_TARGET": "16.4", + "PLATFORM": "OS64", + "CMAKE_TOOLCHAIN_FILE": { + "value": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake", + "type": "FILEPATH" + }, + "VCPKG_CHAINLOAD_TOOLCHAIN_FILE": { + "value": "${sourceDir}/thirdparty/ios-cmake/ios.toolchain.cmake", + "type": "FILEPATH" + }, + "VCPKG_TARGET_TRIPLET": { + "value": "arm64-ios", + "type": "STRING" + } + }, + "environment": { + "VCPKG_ROOT": "${sourceDir}/thirdparty/vcpkg" + }, + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Darwin" + } + }, + { + "name": "ios-device-debug", + "displayName": "iOS Device Debug", + "inherits": "ios-base", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "ios-device-relwithdebinfo", + "displayName": "iOS Device RelWithDebInfo", + "inherits": "ios-base", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "RelWithDebInfo" + } + }, + { + "name": "ios-device-release", + "displayName": "iOS Device Release", + "inherits": "ios-base", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_INTERPROCEDURAL_OPTIMIZATION": true + } } ] } diff --git a/UnleashedRecomp/CMakeLists.txt b/UnleashedRecomp/CMakeLists.txt index 01e040ab..d8513438 100644 --- a/UnleashedRecomp/CMakeLists.txt +++ b/UnleashedRecomp/CMakeLists.txt @@ -1,568 +1,736 @@ -project("UnleashedRecomp") - -if (WIN32) - option(UNLEASHED_RECOMP_D3D12 "Add D3D12 support for rendering" ON) -endif() - -if (CMAKE_SYSTEM_NAME MATCHES "Linux") - option(UNLEASHED_RECOMP_FLATPAK "Configure the build for Flatpak compatibility." OFF) -endif() - -function(BIN2C) - cmake_parse_arguments(BIN2C_ARGS "" "TARGET_OBJ;SOURCE_FILE;DEST_FILE;ARRAY_NAME;COMPRESSION_TYPE" "" ${ARGN}) - - if(NOT BIN2C_ARGS_TARGET_OBJ) - message(FATAL_ERROR "TARGET_OBJ not specified.") - endif() - - if(NOT BIN2C_ARGS_SOURCE_FILE) - message(FATAL_ERROR "SOURCE_FILE not specified.") - endif() - - if(NOT BIN2C_ARGS_DEST_FILE) - set(BIN2C_ARGS_DEST_FILE "${BIN2C_ARGS_SOURCE_FILE}") - endif() - - if(NOT BIN2C_ARGS_COMPRESSION_TYPE) - set(BIN2C_ARGS_COMPRESSION_TYPE "none") - endif() - - add_custom_command(OUTPUT "${BIN2C_ARGS_DEST_FILE}.c" - COMMAND $ "${BIN2C_ARGS_SOURCE_FILE}" "${BIN2C_ARGS_ARRAY_NAME}" "${BIN2C_ARGS_COMPRESSION_TYPE}" "${BIN2C_ARGS_DEST_FILE}.c" "${BIN2C_ARGS_DEST_FILE}.h" - DEPENDS "${BIN2C_ARGS_SOURCE_FILE}" - BYPRODUCTS "${BIN2C_ARGS_DEST_FILE}.h" - COMMENT "Generating binary header for ${BIN2C_ARGS_SOURCE_FILE}..." - ) - - set_source_files_properties(${BIN2C_ARGS_DEST_FILE}.c PROPERTIES SKIP_PRECOMPILE_HEADERS ON) - target_sources(${BIN2C_ARGS_TARGET_OBJ} PRIVATE ${BIN2C_ARGS_DEST_FILE}.c) -endfunction() - -add_compile_options( - -fno-strict-aliasing - -Wno-switch - -Wno-unused-function - -Wno-unused-variable - -Wno-unused-but-set-variable - -Wno-void-pointer-to-int-cast - -Wno-int-to-void-pointer-cast - -Wno-invalid-offsetof - -Wno-null-arithmetic - -Wno-null-conversion - -Wno-tautological-undefined-compare -) - -if (WIN32) - add_compile_options(/fp:strict) -else() - add_compile_options(-ffp-model=strict) -endif() - -add_compile_definitions( - SDL_MAIN_HANDLED - _DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR # Microsoft wtf? - _CRT_SECURE_NO_WARNINGS) - -set(UNLEASHED_RECOMP_PRECOMPILED_HEADERS - "stdafx.h" -) - -set(UNLEASHED_RECOMP_KERNEL_CXX_SOURCES - "kernel/imports.cpp" - "kernel/xdm.cpp" - "kernel/heap.cpp" - "kernel/memory.cpp" - "kernel/xam.cpp" - "kernel/io/file_system.cpp" -) - -set(UNLEASHED_RECOMP_LOCALE_CXX_SOURCES - "locale/config_locale.cpp" - "locale/locale.cpp" -) - -if (WIN32) - set(UNLEASHED_RECOMP_OS_CXX_SOURCES - "os/win32/logger_win32.cpp" - "os/win32/media_win32.cpp" - "os/win32/process_win32.cpp" - "os/win32/user_win32.cpp" - "os/win32/version_win32.cpp" - ) -elseif (CMAKE_SYSTEM_NAME MATCHES "Linux") - set(UNLEASHED_RECOMP_OS_CXX_SOURCES - "os/linux/logger_linux.cpp" - "os/linux/media_linux.cpp" - "os/linux/process_linux.cpp" - "os/linux/user_linux.cpp" - "os/linux/version_linux.cpp" - ) -elseif (APPLE) - set(UNLEASHED_RECOMP_OS_CXX_SOURCES - "os/macos/logger_macos.cpp" - "os/macos/media_macos.cpp" - "os/macos/process_macos.cpp" - "os/macos/user_macos.cpp" - "os/macos/version_macos.cpp" - ) -endif() - -set(UNLEASHED_RECOMP_CPU_CXX_SOURCES - "cpu/guest_thread.cpp" -) - -set(UNLEASHED_RECOMP_GPU_CXX_SOURCES - "gpu/video.cpp" - "gpu/imgui/imgui_common.cpp" - "gpu/imgui/imgui_font_builder.cpp" - "gpu/imgui/imgui_snapshot.cpp" -) - -set(UNLEASHED_RECOMP_APU_CXX_SOURCES - "apu/audio.cpp" - "apu/embedded_player.cpp" - "apu/driver/sdl2_driver.cpp" -) - -set(UNLEASHED_RECOMP_HID_CXX_SOURCES - "hid/hid.cpp" - "hid/driver/sdl_hid.cpp" -) - -set(UNLEASHED_RECOMP_PATCHES_CXX_SOURCES - "patches/aspect_ratio_patches.cpp" - "patches/audio_patches.cpp" - "patches/camera_patches.cpp" - "patches/CGameModeStageTitle_patches.cpp" - "patches/CHudPause_patches.cpp" - "patches/CTitleStateIntro_patches.cpp" - "patches/CTitleStateMenu_patches.cpp" - "patches/fps_patches.cpp" - "patches/frontend_listener.cpp" - "patches/input_patches.cpp" - "patches/inspire_patches.cpp" - "patches/misc_patches.cpp" - "patches/object_patches.cpp" - "patches/player_patches.cpp" - "patches/resident_patches.cpp" - "patches/video_patches.cpp" -) - -set(UNLEASHED_RECOMP_UI_CXX_SOURCES - "ui/achievement_menu.cpp" - "ui/achievement_overlay.cpp" - "ui/black_bar.cpp" - "ui/button_guide.cpp" - "ui/fader.cpp" - "ui/game_window.cpp" - "ui/imgui_utils.cpp" - "ui/installer_wizard.cpp" - "ui/message_window.cpp" - "ui/options_menu.cpp" - "ui/options_menu_thumbnails.cpp" - "ui/tv_static.cpp" -) - -set(UNLEASHED_RECOMP_INSTALL_CXX_SOURCES - "install/installer.cpp" - "install/iso_file_system.cpp" - "install/update_checker.cpp" - "install/xcontent_file_system.cpp" - "install/hashes/apotos_shamar.cpp" - "install/hashes/chunnan.cpp" - "install/hashes/empire_city_adabat.cpp" - "install/hashes/game.cpp" - "install/hashes/holoska.cpp" - "install/hashes/mazuri.cpp" - "install/hashes/spagonia.cpp" - "install/hashes/update.cpp" -) - -set(UNLEASHED_RECOMP_USER_CXX_SOURCES - "user/achievement_data.cpp" - "user/achievement_manager.cpp" - "user/config.cpp" - "user/registry.cpp" - "user/paths.cpp" - "user/persistent_data.cpp" - "user/persistent_storage_manager.cpp" -) - -set(UNLEASHED_RECOMP_MOD_CXX_SOURCES - "mod/mod_loader.cpp" -) - -set(UNLEASHED_RECOMP_THIRDPARTY_SOURCES - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/backends/imgui_impl_sdl2.cpp" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/imgui.cpp" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/imgui_demo.cpp" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/imgui_draw.cpp" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/imgui_tables.cpp" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/imgui_widgets.cpp" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/implot/implot.cpp" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/implot/implot_demo.cpp" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/implot/implot_items.cpp" - "${UNLEASHED_RECOMP_TOOLS_ROOT}/XenosRecomp/thirdparty/smol-v/source/smolv.cpp" -) - -set(UNLEASHED_RECOMP_THIRDPARTY_INCLUDES - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/concurrentqueue" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/ddspp" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/implot" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/json/include" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/magic_enum/include" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/stb" - "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/unordered_dense/include" - "${UNLEASHED_RECOMP_TOOLS_ROOT}/bc_diff" - "${UNLEASHED_RECOMP_TOOLS_ROOT}/XenosRecomp/thirdparty/smol-v/source" -) - -set_source_files_properties(${UNLEASHED_RECOMP_THIRDPARTY_SOURCES} PROPERTIES SKIP_PRECOMPILE_HEADERS ON) - -set(UNLEASHED_RECOMP_CXX_SOURCES - "app.cpp" - "exports.cpp" - "main.cpp" - "misc_impl.cpp" - "preload_executable.cpp" - "sdl_listener.cpp" - "stdafx.cpp" - "version.cpp" - - ${UNLEASHED_RECOMP_KERNEL_CXX_SOURCES} - ${UNLEASHED_RECOMP_LOCALE_CXX_SOURCES} - ${UNLEASHED_RECOMP_OS_CXX_SOURCES} - ${UNLEASHED_RECOMP_CPU_CXX_SOURCES} - ${UNLEASHED_RECOMP_GPU_CXX_SOURCES} - ${UNLEASHED_RECOMP_APU_CXX_SOURCES} - ${UNLEASHED_RECOMP_HID_CXX_SOURCES} - ${UNLEASHED_RECOMP_PATCHES_CXX_SOURCES} - ${UNLEASHED_RECOMP_UI_CXX_SOURCES} - ${UNLEASHED_RECOMP_INSTALL_CXX_SOURCES} - ${UNLEASHED_RECOMP_USER_CXX_SOURCES} - ${UNLEASHED_RECOMP_MOD_CXX_SOURCES} - ${UNLEASHED_RECOMP_THIRDPARTY_SOURCES} -) - -include("version.cmake") - -set(VERSION_TXT "${PROJECT_SOURCE_DIR}/res/version.txt") - -# Only show Git info and build type if not Release. -set(SHOW_GIT_INFO_AND_BUILD_TYPE 0) -if (NOT ${CMAKE_BUILD_TYPE} MATCHES "Release") - set(SHOW_GIT_INFO_AND_BUILD_TYPE 1) -endif() - -GenerateVersionSources( - OUTPUT_DIR ${PROJECT_SOURCE_DIR} - VERSION_TXT ${VERSION_TXT} - H_TEMPLATE "${PROJECT_SOURCE_DIR}/res/version.h.template" - CXX_TEMPLATE "${PROJECT_SOURCE_DIR}/res/version.cpp.template" - BUILD_TYPE ${CMAKE_BUILD_TYPE} - SHOW_GIT_INFO ${SHOW_GIT_INFO_AND_BUILD_TYPE} - SHOW_BUILD_TYPE ${SHOW_GIT_INFO_AND_BUILD_TYPE} -) - -if (WIN32) - # Create binary version number for Win32 integer attributes. - CreateVersionString( - VERSION_TXT ${VERSION_TXT} - OUTPUT_CSV 1 - OUTPUT_VAR WIN32_VERSION_BINARY - ) - - # Create string version number for Win32 detailed attributes. - CreateVersionString( - VERSION_TXT ${VERSION_TXT} - BUILD_TYPE ${CMAKE_BUILD_TYPE} - SHOW_GIT_INFO ${SHOW_GIT_INFO_AND_BUILD_TYPE} - SHOW_BUILD_TYPE ${SHOW_GIT_INFO_AND_BUILD_TYPE} - OUTPUT_VAR WIN32_VERSION_STRING - ) - - # Set Win32 icon path. - set(WIN32_ICON_PATH "${PROJECT_SOURCE_DIR}/../UnleashedRecompResources/images/game_icon.ico") - - configure_file("res/win32/res.rc.template" "${CMAKE_BINARY_DIR}/res.rc" @ONLY) - add_executable(UnleashedRecomp ${UNLEASHED_RECOMP_CXX_SOURCES} "${CMAKE_BINARY_DIR}/res.rc") - - # Hide console for release configurations. - if (${CMAKE_BUILD_TYPE} MATCHES "Release") - target_link_options(UnleashedRecomp PRIVATE "/SUBSYSTEM:WINDOWS" "/ENTRY:mainCRTStartup") - endif() -elseif (APPLE) - # Create version number for app bundle. - CreateVersionString( - VERSION_TXT ${VERSION_TXT} - OUTPUT_VAR MACOS_BUNDLE_VERSION - ) - - add_executable(UnleashedRecomp MACOSX_BUNDLE - ${UNLEASHED_RECOMP_CXX_SOURCES} - res/macos/game_icon.icns - ) - set_source_files_properties(res/macos/game_icon.icns PROPERTIES - MACOSX_PACKAGE_LOCATION Resources) - set_target_properties(UnleashedRecomp PROPERTIES - OUTPUT_NAME "Unleashed Recompiled" - MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/res/macos/MacOSXBundleInfo.plist.in - MACOSX_BUNDLE_GUI_IDENTIFIER hedge-dev.UnleashedRecomp - MACOSX_BUNDLE_BUNDLE_NAME "Unleashed Recompiled" - MACOSX_BUNDLE_BUNDLE_VERSION ${MACOS_BUNDLE_VERSION} - MACOSX_BUNDLE_SHORT_VERSION_STRING ${MACOS_BUNDLE_VERSION} - MACOSX_BUNDLE_ICON_FILE "game_icon.icns" - ) - - # Linking with MoltenVK directly would prevent using the system Vulkan loader to load with debug layers. - # Instead, copy the MoltenVK dylib to the app bundle along with an ICD file for the loader to find it. - # In the event the loader is not installed, the MoltenVK dylib can still be picked up directly in the app bundle. - set(MVK_BUNDLED_PATH "Resources/vulkan/icd.d") - set(MVK_DST "${CMAKE_CURRENT_BINARY_DIR}/Unleashed Recompiled.app/Contents/${MVK_BUNDLED_PATH}") - set_property(TARGET UnleashedRecomp APPEND PROPERTY BUILD_RPATH "@executable_path/../${MVK_BUNDLED_PATH}") - - set(MVK_ICD_SRC "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/MoltenVK/MoltenVK/MoltenVK/icd/MoltenVK_icd.json") - set(MVK_ICD_DST "${MVK_DST}/MoltenVK_icd.json") - set(MVK_DYLIB_SRC "${CMAKE_BINARY_DIR}/thirdparty/MoltenVK/libMoltenVK.dylib") - set(MVK_DYLIB_DST "${MVK_DST}/libMoltenVK.dylib") - - add_custom_command( - OUTPUT ${MVK_DST} - COMMAND ${CMAKE_COMMAND} -E make_directory ${MVK_DST}) - add_custom_command( - OUTPUT ${MVK_ICD_DST} - DEPENDS ${MVK_ICD_SRC} ${MVK_DST} - COMMAND ${CMAKE_COMMAND} -E copy ${MVK_ICD_SRC} ${MVK_ICD_DST}) - add_custom_command( - OUTPUT ${MVK_DYLIB_DST} - DEPENDS ${MVK_DYLIB_SRC} ${MVK_DST} - COMMAND ${CMAKE_COMMAND} -E copy ${MVK_DYLIB_SRC} ${MVK_DYLIB_DST}) - add_custom_target(CopyMoltenVK DEPENDS ${MVK_ICD_DST} ${MVK_DYLIB_DST}) - add_dependencies(CopyMoltenVK MoltenVK) - add_dependencies(UnleashedRecomp CopyMoltenVK) -else() - add_executable(UnleashedRecomp ${UNLEASHED_RECOMP_CXX_SOURCES}) -endif() - -if (UNLEASHED_RECOMP_FLATPAK) - target_compile_definitions(UnleashedRecomp PRIVATE - "UNLEASHED_RECOMP_FLATPAK" - "GAME_INSTALL_DIRECTORY=\"/var/data\"" - ) -endif() - -find_package(CURL REQUIRED) - -if (UNLEASHED_RECOMP_D3D12) - find_package(directx-headers CONFIG REQUIRED) - find_package(directx12-agility CONFIG REQUIRED) - target_compile_definitions(UnleashedRecomp PRIVATE UNLEASHED_RECOMP_D3D12) - - file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/D3D12) - add_custom_command(TARGET UnleashedRecomp POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy $ $/D3D12 - COMMAND ${CMAKE_COMMAND} -E copy $ $/D3D12 - COMMAND ${CMAKE_COMMAND} -E copy $ $ - COMMAND ${CMAKE_COMMAND} -E copy $ $ - COMMAND_EXPAND_LISTS - ) - - target_link_libraries(UnleashedRecomp PRIVATE - Microsoft::DirectXShaderCompiler - Microsoft::DXIL - dxgi - ) -endif() - -if (WIN32) - target_link_libraries(UnleashedRecomp PRIVATE - comctl32 - dwmapi - ntdll - Shcore - Synchronization - winmm - windowsapp - ) -endif() - -target_link_libraries(UnleashedRecomp PRIVATE - fmt::fmt - libzstd_static - msdf-atlas-gen::msdf-atlas-gen - nfd::nfd - o1heap - XenonUtils - SDL2::SDL2-static - SDL2_mixer - tomlplusplus::tomlplusplus - UnleashedRecompLib - xxHash::xxhash - CURL::libcurl - plume -) - -target_include_directories(UnleashedRecomp PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR} - "${CMAKE_CURRENT_SOURCE_DIR}/api" - ${UNLEASHED_RECOMP_THIRDPARTY_INCLUDES} -) - -if (CMAKE_SYSTEM_NAME MATCHES "Linux") - find_package(X11 REQUIRED) - target_include_directories(UnleashedRecomp PRIVATE ${X11_INCLUDE_DIR}) - target_link_libraries(UnleashedRecomp PRIVATE ${X11_LIBRARIES}) -endif() - -target_precompile_headers(UnleashedRecomp PUBLIC ${UNLEASHED_RECOMP_PRECOMPILED_HEADERS}) - -function(compile_shader FILE_PATH TARGET_NAME) - set(FILE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/gpu/shader/${FILE_PATH}.hlsl) - cmake_path(GET FILE_PATH STEM VARIABLE_NAME) - if (UNLEASHED_RECOMP_D3D12) - add_custom_command( - OUTPUT ${FILE_PATH}.dxil.h - COMMAND ${DIRECTX_DXC_TOOL} -T ${TARGET_NAME} -HV 2021 -all-resources-bound -Wno-ignored-attributes -Fh ${FILE_PATH}.dxil.h ${FILE_PATH} -Vn g_${VARIABLE_NAME}_dxil - DEPENDS ${FILE_PATH} - ) - target_sources(UnleashedRecomp PRIVATE ${FILE_PATH}.dxil.h) - endif() - add_custom_command( - OUTPUT ${FILE_PATH}.spirv.h - COMMAND ${DIRECTX_DXC_TOOL} -T ${TARGET_NAME} -HV 2021 -all-resources-bound -spirv -fvk-use-dx-layout ${ARGN} -Fh ${FILE_PATH}.spirv.h ${FILE_PATH} -Vn g_${VARIABLE_NAME}_spirv - DEPENDS ${FILE_PATH} - ) - target_sources(UnleashedRecomp PRIVATE ${FILE_PATH}.spirv.h) -endfunction() - -function(compile_vertex_shader FILE_PATH) - compile_shader(${FILE_PATH} vs_6_0 -fvk-invert-y -DUNLEASHED_RECOMP) -endfunction() - -function(compile_pixel_shader FILE_PATH) - compile_shader(${FILE_PATH} ps_6_0 -DUNLEASHED_RECOMP) -endfunction() - -compile_pixel_shader(blend_color_alpha_ps) -compile_vertex_shader(copy_vs) -compile_pixel_shader(copy_color_ps) -compile_pixel_shader(copy_depth_ps) -compile_pixel_shader(csd_filter_ps) -compile_vertex_shader(csd_no_tex_vs) -compile_vertex_shader(csd_vs) -compile_pixel_shader(enhanced_motion_blur_ps) -compile_pixel_shader(gaussian_blur_3x3) -compile_pixel_shader(gaussian_blur_5x5) -compile_pixel_shader(gaussian_blur_7x7) -compile_pixel_shader(gaussian_blur_9x9) -compile_pixel_shader(gamma_correction_ps) -compile_pixel_shader(imgui_ps) -compile_vertex_shader(imgui_vs) -compile_pixel_shader(movie_ps) -compile_vertex_shader(movie_vs) -compile_pixel_shader(resolve_msaa_color_2x) -compile_pixel_shader(resolve_msaa_color_4x) -compile_pixel_shader(resolve_msaa_color_8x) -compile_pixel_shader(resolve_msaa_depth_2x) -compile_pixel_shader(resolve_msaa_depth_4x) -compile_pixel_shader(resolve_msaa_depth_8x) - -set(RESOURCES_SOURCE_PATH "${PROJECT_SOURCE_DIR}/../UnleashedRecompResources") -set(RESOURCES_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/res") - -## Miscellaneous ## -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/bc_diff/button_bc_diff.bin" DEST_FILE "${RESOURCES_OUTPUT_PATH}/bc_diff/button_bc_diff.bin" ARRAY_NAME "g_button_bc_diff" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/font/im_font_atlas.bin" DEST_FILE "${RESOURCES_OUTPUT_PATH}/font/im_font_atlas.bin" ARRAY_NAME "g_im_font_atlas" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/font/im_font_atlas.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/font/im_font_atlas.dds" ARRAY_NAME "g_im_font_atlas_texture" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/achievements_menu/trophy.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/achievements_menu/trophy.dds" ARRAY_NAME "g_trophy" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/controller.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/controller.dds" ARRAY_NAME "g_controller" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/general_window.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/general_window.dds" ARRAY_NAME "g_general_window" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/hedge-dev.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/hedge-dev.dds" ARRAY_NAME "g_hedgedev" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/kbm.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/kbm.dds" ARRAY_NAME "g_kbm" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/select.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/select.dds" ARRAY_NAME "g_select" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/light.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/light.dds" ARRAY_NAME "g_light" COMPRESSION_TYPE "zstd") - -## Installer ## -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/arrow_circle.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/arrow_circle.dds" ARRAY_NAME "g_arrow_circle" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_001.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_001.dds" ARRAY_NAME "g_install_001" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_002.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_002.dds" ARRAY_NAME "g_install_002" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_003.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_003.dds" ARRAY_NAME "g_install_003" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_004.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_004.dds" ARRAY_NAME "g_install_004" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_005.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_005.dds" ARRAY_NAME "g_install_005" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_006.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_006.dds" ARRAY_NAME "g_install_006" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_007.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_007.dds" ARRAY_NAME "g_install_007" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_008.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_008.dds" ARRAY_NAME "g_install_008" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/miles_electric_icon.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/miles_electric_icon.dds" ARRAY_NAME "g_miles_electric_icon" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/pulse_install.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/pulse_install.dds" ARRAY_NAME "g_pulse_install" COMPRESSION_TYPE "zstd") - -## Options Menu ## -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/achievement_notifications.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/achievement_notifications.dds" ARRAY_NAME "g_achievement_notifications" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/allow_background_input_ps.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/allow_background_input_ps.dds" ARRAY_NAME "g_allow_background_input_ps" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/allow_background_input_xb.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/allow_background_input_xb.dds" ARRAY_NAME "g_allow_background_input_xb" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/antialiasing_none.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/antialiasing_none.dds" ARRAY_NAME "g_antialiasing_none" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/antialiasing_2x.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/antialiasing_2x.dds" ARRAY_NAME "g_antialiasing_2x" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/antialiasing_4x.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/antialiasing_4x.dds" ARRAY_NAME "g_antialiasing_4x" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/antialiasing_8x.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/antialiasing_8x.dds" ARRAY_NAME "g_antialiasing_8x" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/aspect_ratio.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/aspect_ratio.dds" ARRAY_NAME "g_aspect_ratio" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/battle_theme.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/battle_theme.dds" ARRAY_NAME "g_battle_theme" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/brightness.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/brightness.dds" ARRAY_NAME "g_brightness" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/channel_stereo.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/channel_stereo.dds" ARRAY_NAME "g_channel_stereo" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/channel_surround.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/channel_surround.dds" ARRAY_NAME "g_channel_surround" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/control_tutorial_ps.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/control_tutorial_ps.dds" ARRAY_NAME "g_control_tutorial_ps" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/control_tutorial_xb.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/control_tutorial_xb.dds" ARRAY_NAME "g_control_tutorial_xb" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/controller_icons.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/controller_icons.dds" ARRAY_NAME "g_controller_icons" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/default.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/default.dds" ARRAY_NAME "g_default" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/effects_volume.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/effects_volume.dds" ARRAY_NAME "g_effects_volume" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/fps.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/fps.dds" ARRAY_NAME "g_fps" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/fullscreen.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/fullscreen.dds" ARRAY_NAME "g_fullscreen" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/gi_texture_filtering_bilinear.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/gi_texture_filtering_bilinear.dds" ARRAY_NAME "g_gi_texture_filtering_bilinear" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/gi_texture_filtering_bicubic.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/gi_texture_filtering_bicubic.dds" ARRAY_NAME "g_gi_texture_filtering_bicubic" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/hints.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/hints.dds" ARRAY_NAME "g_hints" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/horizontal_camera.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/horizontal_camera.dds" ARRAY_NAME "g_horizontal_camera" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/language.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/language.dds" ARRAY_NAME "g_language" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/master_volume.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/master_volume.dds" ARRAY_NAME "g_master_volume" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/monitor.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/monitor.dds" ARRAY_NAME "g_monitor" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/motion_blur_off.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/motion_blur_off.dds" ARRAY_NAME "g_motion_blur_off" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/motion_blur_original.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/motion_blur_original.dds" ARRAY_NAME "g_motion_blur_original" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/motion_blur_enhanced.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/motion_blur_enhanced.dds" ARRAY_NAME "g_motion_blur_enhanced" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/movie_scale_fit.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/movie_scale_fit.dds" ARRAY_NAME "g_movie_scale_fit" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/movie_scale_fill.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/movie_scale_fill.dds" ARRAY_NAME "g_movie_scale_fill" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/music_attenuation.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/music_attenuation.dds" ARRAY_NAME "g_music_attenuation" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/music_volume.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/music_volume.dds" ARRAY_NAME "g_music_volume" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/shadow_resolution_x512.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/shadow_resolution_x512.dds" ARRAY_NAME "g_shadow_resolution_x512" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/shadow_resolution_x1024.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/shadow_resolution_x1024.dds" ARRAY_NAME "g_shadow_resolution_x1024" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/shadow_resolution_x2048.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/shadow_resolution_x2048.dds" ARRAY_NAME "g_shadow_resolution_x2048" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/shadow_resolution_x4096.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/shadow_resolution_x4096.dds" ARRAY_NAME "g_shadow_resolution_x4096" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/shadow_resolution_x8192.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/shadow_resolution_x8192.dds" ARRAY_NAME "g_shadow_resolution_x8192" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/time_transition_ps.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/time_transition_ps.dds" ARRAY_NAME "g_time_of_day_transition_playstation" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/time_transition_xb.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/time_transition_xb.dds" ARRAY_NAME "g_time_of_day_transition_xbox" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/transparency_antialiasing_false.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/transparency_antialiasing_false.dds" ARRAY_NAME "g_transparency_antialiasing_false" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/transparency_antialiasing_true.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/transparency_antialiasing_true.dds" ARRAY_NAME "g_transparency_antialiasing_true" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/ui_alignment_centre.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/ui_alignment_centre.dds" ARRAY_NAME "g_ui_alignment_centre" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/ui_alignment_edge.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/ui_alignment_edge.dds" ARRAY_NAME "g_ui_alignment_edge" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/vertical_camera.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/vertical_camera.dds" ARRAY_NAME "g_vertical_camera" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/voice_language.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/voice_language.dds" ARRAY_NAME "g_voice_language" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/vibration_ps.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/vibration_ps.dds" ARRAY_NAME "g_vibration_ps" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/vibration_xb.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/vibration_xb.dds" ARRAY_NAME "g_vibration_xb" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/vsync_on.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/vsync_on.dds" ARRAY_NAME "g_vsync_on" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/vsync_off.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/vsync_off.dds" ARRAY_NAME "g_vsync_off" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/window_size.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/window_size.dds" ARRAY_NAME "g_window_size" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/xbox_color_correction.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/xbox_color_correction.dds" ARRAY_NAME "g_xbox_color_correction" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/miles_electric.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/miles_electric.dds" ARRAY_NAME "g_miles_electric" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/options_static.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/options_static.dds" ARRAY_NAME "g_options_static" COMPRESSION_TYPE "zstd") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/options_static_flash.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/options_static_flash.dds" ARRAY_NAME "g_options_static_flash" COMPRESSION_TYPE "zstd") - -## Game Icon ## -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/game_icon.bmp" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/game_icon.bmp" ARRAY_NAME "g_game_icon") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/game_icon_night.bmp" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/game_icon_night.bmp" ARRAY_NAME "g_game_icon_night") - -## Audio ## -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/music/installer.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/music/installer.ogg" ARRAY_NAME "g_installer_music") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_worldmap_cursor.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_worldmap_cursor.ogg" ARRAY_NAME "g_sys_worldmap_cursor") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_worldmap_finaldecide.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_worldmap_finaldecide.ogg" ARRAY_NAME "g_sys_worldmap_finaldecide") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_actstg_pausecansel.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_actstg_pausecansel.ogg" ARRAY_NAME "g_sys_actstg_pausecansel") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_actstg_pausecursor.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_actstg_pausecursor.ogg" ARRAY_NAME "g_sys_actstg_pausecursor") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_actstg_pausedecide.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_actstg_pausedecide.ogg" ARRAY_NAME "g_sys_actstg_pausedecide") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_actstg_pausewinclose.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_actstg_pausewinclose.ogg" ARRAY_NAME "g_sys_actstg_pausewinclose") -BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_actstg_pausewinopen.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_actstg_pausewinopen.ogg" ARRAY_NAME "g_sys_actstg_pausewinopen") +project("UnleashedRecomp") + +if(WIN32) + option(UNLEASHED_RECOMP_D3D12 "Add D3D12 support for rendering" ON) +endif() + +if(APPLE) + option(UNLEASHED_RECOMP_METAL "Add Metal support for rendering" ON) +endif() + +if(CMAKE_SYSTEM_NAME MATCHES "Linux") + option(UNLEASHED_RECOMP_FLATPAK "Configure the build for Flatpak compatibility." OFF) +endif() + +function(BIN2C) + cmake_parse_arguments(BIN2C_ARGS "" "TARGET_OBJ;SOURCE_FILE;DEST_FILE;ARRAY_NAME;COMPRESSION_TYPE" "" ${ARGN}) + + if(NOT BIN2C_ARGS_TARGET_OBJ) + message(FATAL_ERROR "TARGET_OBJ not specified.") + endif() + + if(NOT BIN2C_ARGS_SOURCE_FILE) + message(FATAL_ERROR "SOURCE_FILE not specified.") + endif() + + if(NOT BIN2C_ARGS_DEST_FILE) + set(BIN2C_ARGS_DEST_FILE "${BIN2C_ARGS_SOURCE_FILE}") + endif() + + if(NOT BIN2C_ARGS_COMPRESSION_TYPE) + set(BIN2C_ARGS_COMPRESSION_TYPE "none") + endif() + + if(NOT CMAKE_CROSSCOMPILING) + add_custom_command(OUTPUT "${BIN2C_ARGS_DEST_FILE}.c" + COMMAND $ "${BIN2C_ARGS_SOURCE_FILE}" "${BIN2C_ARGS_ARRAY_NAME}" "${BIN2C_ARGS_COMPRESSION_TYPE}" "${BIN2C_ARGS_DEST_FILE}.c" "${BIN2C_ARGS_DEST_FILE}.h" + DEPENDS "${BIN2C_ARGS_SOURCE_FILE}" + BYPRODUCTS "${BIN2C_ARGS_DEST_FILE}.h" + COMMENT "Generating binary header for ${BIN2C_ARGS_SOURCE_FILE}..." + ) + else() + # When cross-compiling, build a host-native file_to_c out-of-tree and invoke it + set(HOST_FILE_TO_C_BUILD_DIR "${CMAKE_BINARY_DIR}/host-tools/file_to_c") + set(HOST_FILE_TO_C_BIN "${HOST_FILE_TO_C_BUILD_DIR}/file_to_c") + + add_custom_command(OUTPUT "${BIN2C_ARGS_DEST_FILE}.c" + COMMAND ${CMAKE_COMMAND} -S "${CMAKE_SOURCE_DIR}/tools/file_to_c" -B "${HOST_FILE_TO_C_BUILD_DIR}" + -G "${CMAKE_GENERATOR}" + -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/host-tools/install + COMMAND ${CMAKE_COMMAND} --build "${HOST_FILE_TO_C_BUILD_DIR}" --config ${CMAKE_BUILD_TYPE} + COMMAND "${HOST_FILE_TO_C_BIN}" "${BIN2C_ARGS_SOURCE_FILE}" "${BIN2C_ARGS_ARRAY_NAME}" "${BIN2C_ARGS_COMPRESSION_TYPE}" "${BIN2C_ARGS_DEST_FILE}.c" "${BIN2C_ARGS_DEST_FILE}.h" + DEPENDS "${BIN2C_ARGS_SOURCE_FILE}" + BYPRODUCTS "${BIN2C_ARGS_DEST_FILE}.h" + COMMENT "Cross: building host file_to_c and generating binary header for ${BIN2C_ARGS_SOURCE_FILE}..." + USES_TERMINAL + ) + endif() + + set_source_files_properties(${BIN2C_ARGS_DEST_FILE}.c PROPERTIES SKIP_PRECOMPILE_HEADERS ON) + target_sources(${BIN2C_ARGS_TARGET_OBJ} PRIVATE ${BIN2C_ARGS_DEST_FILE}.c) +endfunction() + +add_compile_options( + -fno-strict-aliasing + -Wno-switch + -Wno-unused-function + -Wno-unused-variable + -Wno-unused-but-set-variable + -Wno-void-pointer-to-int-cast + -Wno-int-to-void-pointer-cast + -Wno-invalid-offsetof + -Wno-null-arithmetic + -Wno-null-conversion + -Wno-tautological-undefined-compare +) + +if(WIN32) + add_compile_options(/fp:strict) +else() + add_compile_options(-ffp-model=strict) +endif() + +add_compile_definitions( + _DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR # Microsoft wtf? + _CRT_SECURE_NO_WARNINGS) + +# SDL owns the iOS process entry point and invokes the application's SDL_main. +if(NOT CMAKE_SYSTEM_NAME STREQUAL "iOS") + add_compile_definitions(SDL_MAIN_HANDLED) +endif() + +if(CMAKE_SYSTEM_NAME STREQUAL "iOS") + add_compile_definitions(UNLEASHED_RECOMP_IOS) + set(UNLEASHED_RECOMP_IOS ON) +endif() + +set(UNLEASHED_RECOMP_PRECOMPILED_HEADERS + "stdafx.h" +) + +set(UNLEASHED_RECOMP_KERNEL_CXX_SOURCES + "kernel/imports.cpp" + "kernel/xdm.cpp" + "kernel/heap.cpp" + "kernel/memory.cpp" + "kernel/xam.cpp" + "kernel/io/file_system.cpp" +) + +set(UNLEASHED_RECOMP_LOCALE_CXX_SOURCES + "locale/config_locale.cpp" + "locale/locale.cpp" +) + +if(WIN32) + set(UNLEASHED_RECOMP_OS_CXX_SOURCES + "os/win32/logger_win32.cpp" + "os/win32/media_win32.cpp" + "os/win32/process_win32.cpp" + "os/win32/user_win32.cpp" + "os/win32/version_win32.cpp" + ) +elseif(CMAKE_SYSTEM_NAME MATCHES "Linux") + set(UNLEASHED_RECOMP_OS_CXX_SOURCES + "os/linux/logger_linux.cpp" + "os/linux/media_linux.cpp" + "os/linux/process_linux.cpp" + "os/linux/user_linux.cpp" + "os/linux/version_linux.cpp" + ) +elseif(APPLE) + set(UNLEASHED_RECOMP_OS_CXX_SOURCES + "os/macos/logger_macos.cpp" + "os/macos/media_macos.cpp" + "os/macos/process_macos.cpp" + "os/macos/user_macos.cpp" + "os/macos/version_macos.cpp" + ) +endif() + +set(UNLEASHED_RECOMP_CPU_CXX_SOURCES + "cpu/guest_thread.cpp" +) + +set(UNLEASHED_RECOMP_GPU_CXX_SOURCES + "gpu/video.cpp" + "gpu/imgui/imgui_common.cpp" + "gpu/imgui/imgui_font_builder.cpp" + "gpu/imgui/imgui_snapshot.cpp" +) + +set(UNLEASHED_RECOMP_APU_CXX_SOURCES + "apu/audio.cpp" + "apu/embedded_player.cpp" + "apu/driver/sdl2_driver.cpp" +) + +set(UNLEASHED_RECOMP_HID_CXX_SOURCES + "hid/hid.cpp" + "hid/driver/sdl_hid.cpp" +) + +set(UNLEASHED_RECOMP_PATCHES_CXX_SOURCES + "patches/aspect_ratio_patches.cpp" + "patches/audio_patches.cpp" + "patches/camera_patches.cpp" + "patches/CGameModeStageTitle_patches.cpp" + "patches/CHudPause_patches.cpp" + "patches/CTitleStateIntro_patches.cpp" + "patches/CTitleStateMenu_patches.cpp" + "patches/fps_patches.cpp" + "patches/frontend_listener.cpp" + "patches/input_patches.cpp" + "patches/inspire_patches.cpp" + "patches/misc_patches.cpp" + "patches/object_patches.cpp" + "patches/player_patches.cpp" + "patches/resident_patches.cpp" + "patches/video_patches.cpp" +) + +set(UNLEASHED_RECOMP_UI_CXX_SOURCES + "ui/achievement_menu.cpp" + "ui/achievement_overlay.cpp" + "ui/black_bar.cpp" + "ui/button_guide.cpp" + "ui/fader.cpp" + "ui/game_window.cpp" + "ui/imgui_utils.cpp" + "ui/installer_wizard.cpp" + "ui/message_window.cpp" + "ui/options_menu.cpp" + "ui/options_menu_thumbnails.cpp" + "ui/touch_controls.cpp" + "ui/tv_static.cpp" +) + +if(UNLEASHED_RECOMP_IOS) + list(APPEND UNLEASHED_RECOMP_UI_CXX_SOURCES "ui/file_picker_ios.mm") + list(APPEND UNLEASHED_RECOMP_UI_CXX_SOURCES "ui/touch_haptics_ios.mm") +endif() + +set(UNLEASHED_RECOMP_INSTALL_CXX_SOURCES + "install/installer.cpp" + "install/iso_file_system.cpp" + "install/update_checker.cpp" + "install/xcontent_file_system.cpp" + "install/hashes/apotos_shamar.cpp" + "install/hashes/chunnan.cpp" + "install/hashes/empire_city_adabat.cpp" + "install/hashes/game.cpp" + "install/hashes/holoska.cpp" + "install/hashes/mazuri.cpp" + "install/hashes/spagonia.cpp" + "install/hashes/update.cpp" +) + +set(UNLEASHED_RECOMP_USER_CXX_SOURCES + "user/achievement_data.cpp" + "user/achievement_manager.cpp" + "user/config.cpp" + "user/registry.cpp" + "user/paths.cpp" + "user/persistent_data.cpp" + "user/persistent_storage_manager.cpp" +) + +set(UNLEASHED_RECOMP_MOD_CXX_SOURCES + "mod/mod_loader.cpp" +) + +set(UNLEASHED_RECOMP_THIRDPARTY_SOURCES + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/backends/imgui_impl_sdl2.cpp" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/imgui.cpp" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/imgui_demo.cpp" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/imgui_draw.cpp" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/imgui_tables.cpp" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui/imgui_widgets.cpp" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/implot/implot.cpp" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/implot/implot_demo.cpp" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/implot/implot_items.cpp" + "${UNLEASHED_RECOMP_TOOLS_ROOT}/XenosRecomp/thirdparty/smol-v/source/smolv.cpp" +) + +set(UNLEASHED_RECOMP_THIRDPARTY_INCLUDES + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/concurrentqueue" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/ddspp" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/imgui" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/implot" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/json/include" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/magic_enum/include" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/stb" + "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/unordered_dense/include" + "${UNLEASHED_RECOMP_TOOLS_ROOT}/bc_diff" + "${UNLEASHED_RECOMP_TOOLS_ROOT}/XenosRecomp/thirdparty/smol-v/source" +) + +set_source_files_properties(${UNLEASHED_RECOMP_THIRDPARTY_SOURCES} PROPERTIES SKIP_PRECOMPILE_HEADERS ON) + +set(UNLEASHED_RECOMP_CXX_SOURCES + "app.cpp" + "exports.cpp" + "main.cpp" + "misc_impl.cpp" + "preload_executable.cpp" + "sdl_listener.cpp" + "stdafx.cpp" + "version.cpp" + "apple_utils.mm" + + ${UNLEASHED_RECOMP_KERNEL_CXX_SOURCES} + ${UNLEASHED_RECOMP_LOCALE_CXX_SOURCES} + ${UNLEASHED_RECOMP_OS_CXX_SOURCES} + ${UNLEASHED_RECOMP_CPU_CXX_SOURCES} + ${UNLEASHED_RECOMP_GPU_CXX_SOURCES} + ${UNLEASHED_RECOMP_APU_CXX_SOURCES} + ${UNLEASHED_RECOMP_HID_CXX_SOURCES} + ${UNLEASHED_RECOMP_PATCHES_CXX_SOURCES} + ${UNLEASHED_RECOMP_UI_CXX_SOURCES} + ${UNLEASHED_RECOMP_INSTALL_CXX_SOURCES} + ${UNLEASHED_RECOMP_USER_CXX_SOURCES} + ${UNLEASHED_RECOMP_MOD_CXX_SOURCES} + ${UNLEASHED_RECOMP_THIRDPARTY_SOURCES} +) + +include("version.cmake") + +set(VERSION_TXT "${PROJECT_SOURCE_DIR}/res/version.txt") + +# Only show Git info and build type if not Release. +set(SHOW_GIT_INFO_AND_BUILD_TYPE 0) + +if(NOT ${CMAKE_BUILD_TYPE} MATCHES "Release") + set(SHOW_GIT_INFO_AND_BUILD_TYPE 1) +endif() + +if(UNLEASHED_RECOMP_METAL) + set(XCRUN_TOOL "/usr/bin/xcrun") +endif() + +GenerateVersionSources( + OUTPUT_DIR ${PROJECT_SOURCE_DIR} + VERSION_TXT ${VERSION_TXT} + H_TEMPLATE "${PROJECT_SOURCE_DIR}/res/version.h.template" + CXX_TEMPLATE "${PROJECT_SOURCE_DIR}/res/version.cpp.template" + BUILD_TYPE ${CMAKE_BUILD_TYPE} + SHOW_GIT_INFO ${SHOW_GIT_INFO_AND_BUILD_TYPE} + SHOW_BUILD_TYPE ${SHOW_GIT_INFO_AND_BUILD_TYPE} +) + +if(WIN32) + # Create binary version number for Win32 integer attributes. + CreateVersionString( + VERSION_TXT ${VERSION_TXT} + OUTPUT_CSV 1 + OUTPUT_VAR WIN32_VERSION_BINARY + ) + + # Create string version number for Win32 detailed attributes. + CreateVersionString( + VERSION_TXT ${VERSION_TXT} + BUILD_TYPE ${CMAKE_BUILD_TYPE} + SHOW_GIT_INFO ${SHOW_GIT_INFO_AND_BUILD_TYPE} + SHOW_BUILD_TYPE ${SHOW_GIT_INFO_AND_BUILD_TYPE} + OUTPUT_VAR WIN32_VERSION_STRING + ) + + # Set Win32 icon path. + set(WIN32_ICON_PATH "${PROJECT_SOURCE_DIR}/../UnleashedRecompResources/images/game_icon.ico") + + configure_file("res/win32/res.rc.template" "${CMAKE_BINARY_DIR}/res.rc" @ONLY) + add_executable(UnleashedRecomp ${UNLEASHED_RECOMP_CXX_SOURCES} "${CMAKE_BINARY_DIR}/res.rc") + + # Hide console for release configurations. + if(${CMAKE_BUILD_TYPE} MATCHES "Release") + target_link_options(UnleashedRecomp PRIVATE "/SUBSYSTEM:WINDOWS" "/ENTRY:mainCRTStartup") + endif() +elseif(APPLE) + # Create version number for app bundle. + CreateVersionString( + VERSION_TXT ${VERSION_TXT} + OUTPUT_VAR MACOS_BUNDLE_VERSION + ) + + set(IOS_BUNDLE_VERSION ${MACOS_BUNDLE_VERSION}) + + if(CMAKE_SYSTEM_NAME STREQUAL "iOS") + add_executable(UnleashedRecomp MACOSX_BUNDLE ${UNLEASHED_RECOMP_CXX_SOURCES}) + set_target_properties(UnleashedRecomp PROPERTIES + OUTPUT_NAME "Unleashed Recompiled iOS" + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/res/ios/iOSBundleInfo.plist.in + MACOSX_BUNDLE_GUI_IDENTIFIER hedge-dev.UnleashedRecomp.iOS + MACOSX_BUNDLE_BUNDLE_NAME "Unleashed Recompiled" + MACOSX_BUNDLE_BUNDLE_VERSION ${IOS_BUNDLE_VERSION} + MACOSX_BUNDLE_SHORT_VERSION_STRING ${IOS_BUNDLE_VERSION} + XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1,2" + XCODE_ATTRIBUTE_IPHONEOS_DEPLOYMENT_TARGET "${CMAKE_OSX_DEPLOYMENT_TARGET}" + BUILD_RPATH "@executable_path/Frameworks" + INSTALL_RPATH "@executable_path/Frameworks" + ) + + set(MVK_FRAMEWORK_PATH "Frameworks/MoltenVK.framework") + set(MVK_ICD_PATH "vulkan/icd.d") + + set(MVK_APP_DIR "$") + set(MVK_FRAMEWORK_DST "${MVK_APP_DIR}/${MVK_FRAMEWORK_PATH}") + set(MVK_ICD_DST "${MVK_APP_DIR}/${MVK_ICD_PATH}") + + set(MVK_ICD_SRC "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/MoltenVK/MoltenVK/MoltenVK/icd/MoltenVK_icd.json") + + set(MVK_FRAMEWORK_SRC + "${CMAKE_BINARY_DIR}/thirdparty/MoltenVK/MoltenVK.framework" + ) + + set(ASSETS_CAR_SRC "${CMAKE_CURRENT_SOURCE_DIR}/res/ios/Assets.car") + set(ASSETS_CAR_SRC_DST "${MVK_APP_DIR}/Assets.car") + + add_custom_command( + TARGET UnleashedRecomp POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory "${MVK_FRAMEWORK_DST}" + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${MVK_FRAMEWORK_SRC}" + "${MVK_FRAMEWORK_DST}" + COMMENT "Copying MoltenVK.framework into iOS app bundle" + ) + + add_custom_command( + TARGET UnleashedRecomp POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory "${MVK_APP_DIR}/vulkan/icd.d" + COMMAND ${CMAKE_COMMAND} -E copy + "${MVK_ICD_SRC}" + "${MVK_APP_DIR}/vulkan/icd.d/MoltenVK_icd.json" + COMMENT "Copying MoltenVK ICD" + ) + + add_custom_command( + TARGET UnleashedRecomp POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy + "${ASSETS_CAR_SRC}" + "${ASSETS_CAR_SRC_DST}" + COMMENT "Copying Assets.car into iOS app bundle" + ) + + add_dependencies(UnleashedRecomp MoltenVK) + else() + add_executable(UnleashedRecomp MACOSX_BUNDLE + ${UNLEASHED_RECOMP_CXX_SOURCES} + res/macos/game_icon.icns + ) + set_source_files_properties(res/macos/game_icon.icns PROPERTIES + MACOSX_PACKAGE_LOCATION Resources) + set_target_properties(UnleashedRecomp PROPERTIES + OUTPUT_NAME "Unleashed Recompiled" + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/res/macos/MacOSXBundleInfo.plist.in + MACOSX_BUNDLE_GUI_IDENTIFIER hedge-dev.UnleashedRecomp + MACOSX_BUNDLE_BUNDLE_NAME "Unleashed Recompiled" + MACOSX_BUNDLE_BUNDLE_VERSION ${MACOS_BUNDLE_VERSION} + MACOSX_BUNDLE_SHORT_VERSION_STRING ${MACOS_BUNDLE_VERSION} + MACOSX_BUNDLE_ICON_FILE "game_icon.icns" + MACOSX_DEPLOYMENT_TARGET "${CMAKE_OSX_DEPLOYMENT_TARGET}" + ) + + # Linking with MoltenVK directly would prevent using the system Vulkan loader to load with debug layers. + # Instead, copy the MoltenVK dylib to the app bundle along with an ICD file for the loader to find it. + # In the event the loader is not installed, the MoltenVK dylib can still be picked up directly in the app bundle. + set(MVK_BUNDLED_PATH "Resources/vulkan/icd.d") + set(MVK_DST "${CMAKE_CURRENT_BINARY_DIR}/Unleashed Recompiled.app/Contents/${MVK_BUNDLED_PATH}") + set_property(TARGET UnleashedRecomp APPEND PROPERTY BUILD_RPATH "@executable_path/../${MVK_BUNDLED_PATH}") + + set(MVK_ICD_SRC "${UNLEASHED_RECOMP_THIRDPARTY_ROOT}/MoltenVK/MoltenVK/MoltenVK/icd/MoltenVK_icd.json") + set(MVK_ICD_DST "${MVK_DST}/MoltenVK_icd.json") + set(MVK_DYLIB_SRC "${CMAKE_BINARY_DIR}/thirdparty/MoltenVK/MoltenVK.framework/MoltenVK") + set(MVK_DYLIB_DST "${MVK_DST}/libMoltenVK.dylib") + + add_custom_command(OUTPUT ${MVK_DST} COMMAND ${CMAKE_COMMAND} -E make_directory ${MVK_DST}) + add_custom_command(OUTPUT ${MVK_ICD_DST} DEPENDS ${MVK_ICD_SRC} ${MVK_DST} COMMAND ${CMAKE_COMMAND} -E copy ${MVK_ICD_SRC} ${MVK_ICD_DST}) + add_custom_command(OUTPUT ${MVK_DYLIB_DST} DEPENDS ${MVK_DYLIB_SRC} ${MVK_DST} COMMAND ${CMAKE_COMMAND} -E copy ${MVK_DYLIB_SRC} ${MVK_DYLIB_DST}) + add_custom_target(CopyMoltenVK DEPENDS ${MVK_ICD_DST} ${MVK_DYLIB_DST}) + add_dependencies(CopyMoltenVK MoltenVK) + add_dependencies(UnleashedRecomp CopyMoltenVK) + endif() +else() + add_executable(UnleashedRecomp ${UNLEASHED_RECOMP_CXX_SOURCES}) +endif() + +if(UNLEASHED_RECOMP_FLATPAK) + target_compile_definitions(UnleashedRecomp PRIVATE + "UNLEASHED_RECOMP_FLATPAK" + "GAME_INSTALL_DIRECTORY=\"/var/data\"" + ) +endif() + +find_package(CURL REQUIRED) +find_package(zstd CONFIG REQUIRED) + +if(UNLEASHED_RECOMP_D3D12) + find_package(directx-headers CONFIG REQUIRED) + find_package(directx12-agility CONFIG REQUIRED) + target_compile_definitions(UnleashedRecomp PRIVATE UNLEASHED_RECOMP_D3D12) + + file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/D3D12) + add_custom_command(TARGET UnleashedRecomp POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy $ $/D3D12 + COMMAND ${CMAKE_COMMAND} -E copy $ $/D3D12 + COMMAND ${CMAKE_COMMAND} -E copy $ $ + COMMAND ${CMAKE_COMMAND} -E copy $ $ + COMMAND_EXPAND_LISTS + ) + + target_link_libraries(UnleashedRecomp PRIVATE + Microsoft::DirectXShaderCompiler + Microsoft::DXIL + dxgi + ) +endif() + +if(UNLEASHED_RECOMP_METAL) + target_compile_definitions(UnleashedRecomp PRIVATE UNLEASHED_RECOMP_METAL) +endif() + +if(WIN32) + target_link_libraries(UnleashedRecomp PRIVATE + comctl32 + dwmapi + ntdll + Shcore + Synchronization + winmm + windowsapp + ) +endif() + +set(UNLEASHED_RECOMP_LINK_LIBS + fmt::fmt + zstd::libzstd + msdf-atlas-gen::msdf-atlas-gen + o1heap + XenonUtils + SDL2::SDL2-static + SDL2_mixer + tomlplusplus::tomlplusplus + UnleashedRecompLib + xxHash::xxhash + CURL::libcurl + plume +) + +if(NOT CMAKE_SYSTEM_NAME STREQUAL "iOS") + list(APPEND UNLEASHED_RECOMP_LINK_LIBS nfd::nfd) +endif() + +if(CMAKE_SYSTEM_NAME STREQUAL "iOS") + list(PREPEND UNLEASHED_RECOMP_LINK_LIBS SDL2::SDL2main) + list(APPEND UNLEASHED_RECOMP_LINK_LIBS "-framework UniformTypeIdentifiers") +endif() + +target_link_libraries(UnleashedRecomp PRIVATE ${UNLEASHED_RECOMP_LINK_LIBS}) + +target_include_directories(UnleashedRecomp PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + "${CMAKE_CURRENT_SOURCE_DIR}/api" + ${UNLEASHED_RECOMP_THIRDPARTY_INCLUDES} +) + +if(CMAKE_SYSTEM_NAME MATCHES "Linux") + find_package(X11 REQUIRED) + target_include_directories(UnleashedRecomp PRIVATE ${X11_INCLUDE_DIR}) + target_link_libraries(UnleashedRecomp PRIVATE ${X11_LIBRARIES}) +endif() + +target_precompile_headers(UnleashedRecomp PUBLIC ${UNLEASHED_RECOMP_PRECOMPILED_HEADERS}) + +# If DXC tool not provided, try to pick up vendored host DXC (used for shader compilation) +if(NOT DEFINED DIRECTX_DXC_TOOL) + set(_dxc_vendor_dir "${CMAKE_SOURCE_DIR}/tools/XenosRecomp/thirdparty/dxc-bin") + + if(EXISTS "${_dxc_vendor_dir}") + if(DEFINED CMAKE_HOST_SYSTEM_PROCESSOR) + set(_dxc_arch ${CMAKE_HOST_SYSTEM_PROCESSOR}) + elseif(DEFINED CMAKE_SYSTEM_PROCESSOR) + set(_dxc_arch ${CMAKE_SYSTEM_PROCESSOR}) + else() + set(_dxc_arch "x64") + endif() + + string(TOLOWER "${_dxc_arch}" _dxc_arch) + set(_dxc_bin "${_dxc_vendor_dir}/bin/${_dxc_arch}/dxc-macos") + set(_dxc_libdir "${_dxc_vendor_dir}/lib/${_dxc_arch}") + + if(EXISTS "${_dxc_bin}") + set(DIRECTX_DXC_TOOL "DYLD_LIBRARY_PATH=${_dxc_libdir}" "${_dxc_bin}" CACHE INTERNAL "Location of the dxc tool for shader compilation") + message(STATUS "Using vendored DXC: ${_dxc_bin}") + endif() + endif() +endif() + +function(compile_shader FILE_PATH TARGET_NAME) + set(_shader_target UnleashedRecomp) + + set(HLSL_FILE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/gpu/shader/hlsl/${FILE_PATH}.hlsl) + set(MSL_FILE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/gpu/shader/msl/${FILE_PATH}.metal) + cmake_path(GET HLSL_FILE_PATH STEM HLSL_NAME) + cmake_path(GET MSL_FILE_PATH STEM MSL_NAME) + + if(UNLEASHED_RECOMP_METAL) + # Metal shader libraries are platform-specific. CMAKE_OSX_SYSROOT is + # "iphoneos" for device builds, and defaults to the macOS SDK otherwise. + if(CMAKE_SYSTEM_NAME STREQUAL "iOS") + set(_metal_sdk iphoneos) + set(_metal_sdk_version_arg -mios-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}) + else() + set(_metal_sdk macosx) + set(_metal_sdk_version_arg -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}) + endif() + + add_custom_command( + OUTPUT ${MSL_FILE_PATH}.ir + COMMAND ${XCRUN_TOOL} -sdk ${_metal_sdk} metal ${_metal_sdk_version_arg} -o ${MSL_FILE_PATH}.ir -c ${MSL_FILE_PATH} -D__air__ -frecord-sources -gline-tables-only + DEPENDS ${MSL_FILE_PATH} + ) + add_custom_command( + OUTPUT ${MSL_FILE_PATH}.metallib + COMMAND ${XCRUN_TOOL} -sdk ${_metal_sdk} metallib -o ${MSL_FILE_PATH}.metallib ${MSL_FILE_PATH}.ir + DEPENDS ${MSL_FILE_PATH}.ir + ) + BIN2C(TARGET_OBJ ${_shader_target} SOURCE_FILE "${MSL_FILE_PATH}.metallib" DEST_FILE "${MSL_FILE_PATH}.metallib" ARRAY_NAME "g_${MSL_NAME}_air") + endif() + + if(UNLEASHED_RECOMP_D3D12) + add_custom_command( + OUTPUT ${HLSL_FILE_PATH}.dxil.h + COMMAND ${DIRECTX_DXC_TOOL} -T ${TARGET_NAME} -HV 2021 -all-resources-bound -Wno-ignored-attributes -E shaderMain -Fh ${HLSL_FILE_PATH}.dxil.h ${HLSL_FILE_PATH} -Vn g_${HLSL_NAME}_dxil + DEPENDS ${HLSL_FILE_PATH} + ) + target_sources(UnleashedRecomp PRIVATE ${HLSL_FILE_PATH}.dxil.h) + endif() + + add_custom_command( + OUTPUT ${HLSL_FILE_PATH}.spirv.h + COMMAND ${DIRECTX_DXC_TOOL} -T ${TARGET_NAME} -HV 2021 -all-resources-bound -spirv -fvk-use-dx-layout ${ARGN} -E shaderMain -Fh ${HLSL_FILE_PATH}.spirv.h ${HLSL_FILE_PATH} -Vn g_${HLSL_NAME}_spirv + DEPENDS ${HLSL_FILE_PATH} + ) + target_sources(UnleashedRecomp PRIVATE ${HLSL_FILE_PATH}.spirv.h) +endfunction() + +function(compile_vertex_shader FILE_PATH) + compile_shader(${FILE_PATH} vs_6_0 -fvk-invert-y -DUNLEASHED_RECOMP) +endfunction() + +function(compile_pixel_shader FILE_PATH) + compile_shader(${FILE_PATH} ps_6_0 -DUNLEASHED_RECOMP) +endfunction() + +compile_pixel_shader(blend_color_alpha_ps) +compile_vertex_shader(copy_vs) +compile_pixel_shader(copy_color_ps) +compile_pixel_shader(copy_depth_ps) +compile_pixel_shader(csd_filter_ps) +compile_vertex_shader(csd_no_tex_vs) +compile_vertex_shader(csd_vs) +compile_pixel_shader(enhanced_motion_blur_ps) +compile_pixel_shader(gaussian_blur_3x3) +compile_pixel_shader(gaussian_blur_5x5) +compile_pixel_shader(gaussian_blur_7x7) +compile_pixel_shader(gaussian_blur_9x9) +compile_pixel_shader(gamma_correction_ps) +compile_pixel_shader(imgui_ps) +compile_vertex_shader(imgui_vs) +compile_pixel_shader(movie_ps) +compile_vertex_shader(movie_vs) +compile_pixel_shader(resolve_msaa_color_2x) +compile_pixel_shader(resolve_msaa_color_4x) +compile_pixel_shader(resolve_msaa_color_8x) +compile_pixel_shader(resolve_msaa_depth_2x) +compile_pixel_shader(resolve_msaa_depth_4x) +compile_pixel_shader(resolve_msaa_depth_8x) + +set(RESOURCES_SOURCE_PATH "${PROJECT_SOURCE_DIR}/../UnleashedRecompResources") +set(RESOURCES_OUTPUT_PATH "${PROJECT_SOURCE_DIR}/res") + +# # Miscellaneous ## +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/bc_diff/button_bc_diff.bin" DEST_FILE "${RESOURCES_OUTPUT_PATH}/bc_diff/button_bc_diff.bin" ARRAY_NAME "g_button_bc_diff" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/font/im_font_atlas.bin" DEST_FILE "${RESOURCES_OUTPUT_PATH}/font/im_font_atlas.bin" ARRAY_NAME "g_im_font_atlas" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/font/im_font_atlas.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/font/im_font_atlas.dds" ARRAY_NAME "g_im_font_atlas_texture" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/achievements_menu/trophy.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/achievements_menu/trophy.dds" ARRAY_NAME "g_trophy" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/controller.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/controller.dds" ARRAY_NAME "g_controller" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/general_window.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/general_window.dds" ARRAY_NAME "g_general_window" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/hedge-dev.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/hedge-dev.dds" ARRAY_NAME "g_hedgedev" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/kbm.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/kbm.dds" ARRAY_NAME "g_kbm" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/select.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/select.dds" ARRAY_NAME "g_select" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/common/light.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/common/light.dds" ARRAY_NAME "g_light" COMPRESSION_TYPE "zstd") + +# # Installer ## +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/arrow_circle.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/arrow_circle.dds" ARRAY_NAME "g_arrow_circle" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_001.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_001.dds" ARRAY_NAME "g_install_001" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_002.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_002.dds" ARRAY_NAME "g_install_002" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_003.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_003.dds" ARRAY_NAME "g_install_003" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_004.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_004.dds" ARRAY_NAME "g_install_004" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_005.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_005.dds" ARRAY_NAME "g_install_005" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_006.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_006.dds" ARRAY_NAME "g_install_006" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_007.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_007.dds" ARRAY_NAME "g_install_007" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/install_008.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/install_008.dds" ARRAY_NAME "g_install_008" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/miles_electric_icon.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/miles_electric_icon.dds" ARRAY_NAME "g_miles_electric_icon" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/installer/pulse_install.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/installer/pulse_install.dds" ARRAY_NAME "g_pulse_install" COMPRESSION_TYPE "zstd") + +# # Options Menu ## +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/achievement_notifications.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/achievement_notifications.dds" ARRAY_NAME "g_achievement_notifications" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/allow_background_input_ps.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/allow_background_input_ps.dds" ARRAY_NAME "g_allow_background_input_ps" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/allow_background_input_xb.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/allow_background_input_xb.dds" ARRAY_NAME "g_allow_background_input_xb" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/antialiasing_none.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/antialiasing_none.dds" ARRAY_NAME "g_antialiasing_none" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/antialiasing_2x.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/antialiasing_2x.dds" ARRAY_NAME "g_antialiasing_2x" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/antialiasing_4x.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/antialiasing_4x.dds" ARRAY_NAME "g_antialiasing_4x" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/antialiasing_8x.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/antialiasing_8x.dds" ARRAY_NAME "g_antialiasing_8x" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/aspect_ratio.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/aspect_ratio.dds" ARRAY_NAME "g_aspect_ratio" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/battle_theme.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/battle_theme.dds" ARRAY_NAME "g_battle_theme" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/brightness.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/brightness.dds" ARRAY_NAME "g_brightness" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/channel_stereo.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/channel_stereo.dds" ARRAY_NAME "g_channel_stereo" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/channel_surround.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/channel_surround.dds" ARRAY_NAME "g_channel_surround" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/control_tutorial_ps.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/control_tutorial_ps.dds" ARRAY_NAME "g_control_tutorial_ps" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/control_tutorial_xb.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/control_tutorial_xb.dds" ARRAY_NAME "g_control_tutorial_xb" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/controller_icons.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/controller_icons.dds" ARRAY_NAME "g_controller_icons" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/default.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/default.dds" ARRAY_NAME "g_default" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/effects_volume.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/effects_volume.dds" ARRAY_NAME "g_effects_volume" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/fps.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/fps.dds" ARRAY_NAME "g_fps" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/fullscreen.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/fullscreen.dds" ARRAY_NAME "g_fullscreen" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/gi_texture_filtering_bilinear.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/gi_texture_filtering_bilinear.dds" ARRAY_NAME "g_gi_texture_filtering_bilinear" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/gi_texture_filtering_bicubic.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/gi_texture_filtering_bicubic.dds" ARRAY_NAME "g_gi_texture_filtering_bicubic" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/hints.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/hints.dds" ARRAY_NAME "g_hints" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/horizontal_camera.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/horizontal_camera.dds" ARRAY_NAME "g_horizontal_camera" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/language.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/language.dds" ARRAY_NAME "g_language" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/master_volume.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/master_volume.dds" ARRAY_NAME "g_master_volume" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/monitor.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/monitor.dds" ARRAY_NAME "g_monitor" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/motion_blur_off.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/motion_blur_off.dds" ARRAY_NAME "g_motion_blur_off" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/motion_blur_original.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/motion_blur_original.dds" ARRAY_NAME "g_motion_blur_original" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/motion_blur_enhanced.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/motion_blur_enhanced.dds" ARRAY_NAME "g_motion_blur_enhanced" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/movie_scale_fit.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/movie_scale_fit.dds" ARRAY_NAME "g_movie_scale_fit" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/movie_scale_fill.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/movie_scale_fill.dds" ARRAY_NAME "g_movie_scale_fill" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/music_attenuation.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/music_attenuation.dds" ARRAY_NAME "g_music_attenuation" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/music_volume.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/music_volume.dds" ARRAY_NAME "g_music_volume" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/shadow_resolution_x512.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/shadow_resolution_x512.dds" ARRAY_NAME "g_shadow_resolution_x512" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/shadow_resolution_x1024.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/shadow_resolution_x1024.dds" ARRAY_NAME "g_shadow_resolution_x1024" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/shadow_resolution_x2048.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/shadow_resolution_x2048.dds" ARRAY_NAME "g_shadow_resolution_x2048" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/shadow_resolution_x4096.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/shadow_resolution_x4096.dds" ARRAY_NAME "g_shadow_resolution_x4096" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/shadow_resolution_x8192.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/shadow_resolution_x8192.dds" ARRAY_NAME "g_shadow_resolution_x8192" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/time_transition_ps.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/time_transition_ps.dds" ARRAY_NAME "g_time_of_day_transition_playstation" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/time_transition_xb.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/time_transition_xb.dds" ARRAY_NAME "g_time_of_day_transition_xbox" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/transparency_antialiasing_false.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/transparency_antialiasing_false.dds" ARRAY_NAME "g_transparency_antialiasing_false" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/transparency_antialiasing_true.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/transparency_antialiasing_true.dds" ARRAY_NAME "g_transparency_antialiasing_true" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/ui_alignment_centre.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/ui_alignment_centre.dds" ARRAY_NAME "g_ui_alignment_centre" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/ui_alignment_edge.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/ui_alignment_edge.dds" ARRAY_NAME "g_ui_alignment_edge" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/vertical_camera.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/vertical_camera.dds" ARRAY_NAME "g_vertical_camera" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/voice_language.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/voice_language.dds" ARRAY_NAME "g_voice_language" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/vibration_ps.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/vibration_ps.dds" ARRAY_NAME "g_vibration_ps" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/vibration_xb.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/vibration_xb.dds" ARRAY_NAME "g_vibration_xb" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/vsync_on.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/vsync_on.dds" ARRAY_NAME "g_vsync_on" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/vsync_off.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/vsync_off.dds" ARRAY_NAME "g_vsync_off" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/window_size.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/window_size.dds" ARRAY_NAME "g_window_size" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/thumbnails/xbox_color_correction.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/thumbnails/xbox_color_correction.dds" ARRAY_NAME "g_xbox_color_correction" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/miles_electric.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/miles_electric.dds" ARRAY_NAME "g_miles_electric" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/options_static.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/options_static.dds" ARRAY_NAME "g_options_static" COMPRESSION_TYPE "zstd") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/options_menu/options_static_flash.dds" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/options_menu/options_static_flash.dds" ARRAY_NAME "g_options_static_flash" COMPRESSION_TYPE "zstd") + +# # Game Icon ## +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/game_icon.bmp" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/game_icon.bmp" ARRAY_NAME "g_game_icon") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/images/game_icon_night.bmp" DEST_FILE "${RESOURCES_OUTPUT_PATH}/images/game_icon_night.bmp" ARRAY_NAME "g_game_icon_night") + +# # Audio ## +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/music/installer.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/music/installer.ogg" ARRAY_NAME "g_installer_music") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_worldmap_cursor.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_worldmap_cursor.ogg" ARRAY_NAME "g_sys_worldmap_cursor") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_worldmap_finaldecide.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_worldmap_finaldecide.ogg" ARRAY_NAME "g_sys_worldmap_finaldecide") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_actstg_pausecansel.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_actstg_pausecansel.ogg" ARRAY_NAME "g_sys_actstg_pausecansel") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_actstg_pausecursor.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_actstg_pausecursor.ogg" ARRAY_NAME "g_sys_actstg_pausecursor") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_actstg_pausedecide.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_actstg_pausedecide.ogg" ARRAY_NAME "g_sys_actstg_pausedecide") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_actstg_pausewinclose.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_actstg_pausewinclose.ogg" ARRAY_NAME "g_sys_actstg_pausewinclose") +BIN2C(TARGET_OBJ UnleashedRecomp SOURCE_FILE "${RESOURCES_SOURCE_PATH}/sounds/sys_actstg_pausewinopen.ogg" DEST_FILE "${RESOURCES_OUTPUT_PATH}/sounds/sys_actstg_pausewinopen.ogg" ARRAY_NAME "g_sys_actstg_pausewinopen") diff --git a/UnleashedRecomp/apple_utils.h b/UnleashedRecomp/apple_utils.h new file mode 100644 index 00000000..643786e2 --- /dev/null +++ b/UnleashedRecomp/apple_utils.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +namespace apple { + +/// Get the user data directory (Documents folder on iOS, ~/Documents on macOS) +/// Returns absolute path suitable for user-editable files like saves and mods +std::filesystem::path GetUserDataDirectory(); + +/// Get the application support directory (Library/Application Support) +/// Returns absolute path suitable for app configuration and preferences +std::filesystem::path GetApplicationSupportDirectory(); + +/// Get the caches directory (Library/Caches) +/// Returns absolute path suitable for temporary/cached data +std::filesystem::path GetCachesDirectory(); + +/// Open a URL in the system browser +/// Returns true if the URL was opened successfully, false otherwise +bool OpenBrowser(const char* url); + +/// Check if the current Apple device supports BC texture formats +/// (Apple 9 family and later, select Apple 7/8 family on iPadOS 16.4+) +bool SupportsBCTextures(); + +} // namespace cocoa diff --git a/UnleashedRecomp/apple_utils.mm b/UnleashedRecomp/apple_utils.mm new file mode 100644 index 00000000..e2ec2286 --- /dev/null +++ b/UnleashedRecomp/apple_utils.mm @@ -0,0 +1,127 @@ +#import +#import +#import + +#if TARGET_OS_OSX +#import +#else +#import +#endif + +#include "apple_utils.h" + +namespace apple { + +std::filesystem::path GetUserDataDirectory() { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, + NSUserDomainMask, YES); + + if ([paths count] > 0) { + NSString *documentsPath = [paths objectAtIndex:0]; + return std::filesystem::path([documentsPath UTF8String]); + } + + const char *homeDir = getenv("HOME"); + if (homeDir != nullptr) { + return std::filesystem::path(homeDir) / "Documents"; + } + return std::filesystem::path(); +} + +std::filesystem::path GetApplicationSupportDirectory() { + NSArray *paths = NSSearchPathForDirectoriesInDomains( + NSApplicationSupportDirectory, NSUserDomainMask, YES); + + if ([paths count] > 0) { + NSString *appSupportPath = [paths objectAtIndex:0]; + // Ensure application support directory exists as it is not guaranteed to be + // created by the system + NSFileManager *fileManager = [NSFileManager defaultManager]; + if (![fileManager fileExistsAtPath:appSupportPath]) { + NSError *error = nil; + [fileManager createDirectoryAtPath:appSupportPath + withIntermediateDirectories:YES + attributes:nil + error:&error]; + if (error) { + NSLog(@"Failed to create Application Support directory: %@", error); + return std::filesystem::path(); + } + } + return std::filesystem::path([appSupportPath UTF8String]); + } + + const char *homeDir = getenv("HOME"); + if (homeDir != nullptr) { + return std::filesystem::path(homeDir) / "Library" / "Application Support"; + } + + return std::filesystem::path(); +} + +std::filesystem::path GetCachesDirectory() { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, + NSUserDomainMask, YES); + + if ([paths count] > 0) { + NSString *cachesPath = [paths objectAtIndex:0]; + return std::filesystem::path([cachesPath UTF8String]); + } + + const char *homeDir = getenv("HOME"); + if (homeDir != nullptr) { + return std::filesystem::path(homeDir) / "Library" / "Caches"; + } + + return std::filesystem::path(); +} + +bool OpenBrowser(const char *url) { + @try { + NSString *nsUrl = [NSString stringWithUTF8String:url]; + NSURL *nsUrlObj = [NSURL URLWithString:nsUrl]; + + if (nsUrlObj == nil) { + return false; + } + +#if TARGET_OS_OSX + return [[NSWorkspace sharedWorkspace] openURL:nsUrlObj]; +#else + if (@available(iOS 13.0, *)) { + __block bool success = false; + [[UIApplication sharedApplication] openURL:nsUrlObj + options:@{} + completionHandler:^(BOOL succeeded) { + success = succeeded; + }]; + return success; + } else { + // Fallback for older iOS versions + return [[UIApplication sharedApplication] openURL:nsUrlObj]; + } +#endif + } @catch (NSException *exception) { + return false; + } +} + +bool SupportsBCTextures() { + static bool cachedResult = false; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + @try { + id device = MTLCreateSystemDefaultDevice(); + if (device == nil) { + return; + } + if (@available(iOS 16.4, macOS 13.3, *)) { + cachedResult = [device supportsBCTextureCompression]; + } + } @catch (NSException *exception) { + } + }); + return cachedResult; +} + +} // namespace apple diff --git a/UnleashedRecomp/cpu/guest_thread.cpp b/UnleashedRecomp/cpu/guest_thread.cpp index 3dbe9152..e67e280e 100644 --- a/UnleashedRecomp/cpu/guest_thread.cpp +++ b/UnleashedRecomp/cpu/guest_thread.cpp @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include "ppc_context.h" constexpr size_t PCR_SIZE = 0xAB0; @@ -13,6 +15,29 @@ constexpr size_t TOTAL_SIZE = PCR_SIZE + TLS_SIZE + TEB_SIZE + STACK_SIZE; constexpr size_t TEB_OFFSET = PCR_SIZE + TLS_SIZE; +static std::mutex g_guestThreadRegistryMutex; +static std::unordered_map g_guestThreadRegistry; + +static void RegisterGuestThread(uint32_t guestThreadId) +{ + std::lock_guard lock(g_guestThreadRegistryMutex); + const auto [it, inserted] = g_guestThreadRegistry.emplace( + guestThreadId, GuestThread::GetCurrentThreadId()); + if (!inserted) + { + LOGFN_ERROR( + "SYNC-THREAD-DUPLICATE guestThread=0x{:08X} oldHostThread=0x{:08X} newHostThread=0x{:08X}", + guestThreadId, it->second, GuestThread::GetCurrentThreadId()); + it->second = GuestThread::GetCurrentThreadId(); + } +} + +static void UnregisterGuestThread(uint32_t guestThreadId) +{ + std::lock_guard lock(g_guestThreadRegistryMutex); + g_guestThreadRegistry.erase(guestThreadId); +} + GuestThreadContext::GuestThreadContext(uint32_t cpuNumber) { assert(thread == nullptr); @@ -33,10 +58,13 @@ GuestThreadContext::GuestThreadContext(uint32_t cpuNumber) assert(GetPPCContext() == nullptr); SetPPCContext(ppcContext); + RegisterGuestThread(ppcContext.r13.u32); } GuestThreadContext::~GuestThreadContext() { + UnregisterGuestThread(ppcContext.r13.u32); + ClearPPCContext(); g_userHeap.Free(thread); } @@ -71,7 +99,7 @@ static void* GuestThreadFunc(void* arg) static void GuestThreadFunc(GuestThreadHandle* hThread) { #endif - hThread->suspended.wait(true); + hThread->WaitWhileSuspended(); GuestThread::Start(hThread->params); #ifdef USE_PTHREAD return nullptr; @@ -125,6 +153,35 @@ uint32_t GuestThreadHandle::GetThreadId() const #endif } +void GuestThreadHandle::SetSuspended(bool value) +{ +#if defined(UNLEASHED_RECOMP_IOS) + { + std::lock_guard lock(suspendMutex); + suspended.store(value, std::memory_order_release); + } + if (!value) + suspendCondition.notify_all(); +#else + suspended.store(value, std::memory_order_release); + if (!value) + suspended.notify_all(); +#endif +} + +void GuestThreadHandle::WaitWhileSuspended() +{ +#if defined(UNLEASHED_RECOMP_IOS) + std::unique_lock lock(suspendMutex); + suspendCondition.wait(lock, [&] + { + return !suspended.load(std::memory_order_acquire); + }); +#else + suspended.wait(true, std::memory_order_acquire); +#endif +} + uint32_t GuestThreadHandle::Wait(uint32_t timeout) { assert(timeout == INFINITE); @@ -173,6 +230,13 @@ uint32_t GuestThread::GetCurrentThreadId() #endif } +uint32_t GuestThread::FindHostThreadId(uint32_t guestThreadId) +{ + std::lock_guard lock(g_guestThreadRegistryMutex); + const auto it = g_guestThreadRegistry.find(guestThreadId); + return it != g_guestThreadRegistry.end() ? it->second : 0; +} + void GuestThread::SetLastError(uint32_t error) { auto* thread = (char*)g_memory.Translate(GetPPCContext()->r13.u32); @@ -228,7 +292,7 @@ int GetThreadPriorityImpl(GuestThreadHandle* hThread) { #ifdef _WIN32 return GetThreadPriority(hThread == GetKernelObject(CURRENT_THREAD_HANDLE) ? GetCurrentThread() : hThread->thread.native_handle()); -#else +#else return 0; #endif } diff --git a/UnleashedRecomp/cpu/guest_thread.h b/UnleashedRecomp/cpu/guest_thread.h index e12e91a4..9c4599ca 100644 --- a/UnleashedRecomp/cpu/guest_thread.h +++ b/UnleashedRecomp/cpu/guest_thread.h @@ -1,5 +1,6 @@ #pragma once +#include #include // Use pthreads directly on macOS to be able to increase default stack size. @@ -33,6 +34,10 @@ struct GuestThreadHandle : KernelObject { GuestThreadParams params; std::atomic suspended; +#if defined(UNLEASHED_RECOMP_IOS) + std::mutex suspendMutex; + std::condition_variable suspendCondition; +#endif #ifdef USE_PTHREAD pthread_t thread; #else @@ -43,6 +48,8 @@ struct GuestThreadHandle : KernelObject ~GuestThreadHandle() override; uint32_t GetThreadId() const; + void SetSuspended(bool value); + void WaitWhileSuspended(); uint32_t Wait(uint32_t timeout) override; }; @@ -53,6 +60,7 @@ struct GuestThread static GuestThreadHandle* Start(const GuestThreadParams& params, uint32_t* threadId); static uint32_t GetCurrentThreadId(); + static uint32_t FindHostThreadId(uint32_t guestThreadId); static void SetLastError(uint32_t error); #ifdef _WIN32 diff --git a/UnleashedRecomp/cpu/ppc_context.h b/UnleashedRecomp/cpu/ppc_context.h index c6a67835..e4981d41 100644 --- a/UnleashedRecomp/cpu/ppc_context.h +++ b/UnleashedRecomp/cpu/ppc_context.h @@ -11,3 +11,8 @@ inline void SetPPCContext(PPCContext& ctx) { g_ppcContext = &ctx; } + +inline void ClearPPCContext() +{ + g_ppcContext = nullptr; +} diff --git a/UnleashedRecomp/gpu/imgui/imgui_common.h b/UnleashedRecomp/gpu/imgui/imgui_common.h index 10c5ebbb..c9d0f06e 100644 --- a/UnleashedRecomp/gpu/imgui/imgui_common.h +++ b/UnleashedRecomp/gpu/imgui/imgui_common.h @@ -13,7 +13,7 @@ #define IMGUI_SHADER_MODIFIER_RECTANGLE_BEVEL 10 #define IMGUI_SHADER_MODIFIER_LOW_QUALITY_TEXT 11 -#ifdef __cplusplus +#if defined(__cplusplus) && !defined(__air__) enum class ImGuiCallback : int32_t { diff --git a/UnleashedRecomp/gpu/shader/.gitignore b/UnleashedRecomp/gpu/shader/hlsl/.gitignore similarity index 100% rename from UnleashedRecomp/gpu/shader/.gitignore rename to UnleashedRecomp/gpu/shader/hlsl/.gitignore diff --git a/UnleashedRecomp/gpu/shader/blend_color_alpha_ps.hlsl b/UnleashedRecomp/gpu/shader/hlsl/blend_color_alpha_ps.hlsl similarity index 93% rename from UnleashedRecomp/gpu/shader/blend_color_alpha_ps.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/blend_color_alpha_ps.hlsl index 6c242903..ee16fb4e 100644 --- a/UnleashedRecomp/gpu/shader/blend_color_alpha_ps.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/blend_color_alpha_ps.hlsl @@ -1,4 +1,4 @@ -#include "../../../tools/XenosRecomp/XenosRecomp/shader_common.h" +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" #ifdef __spirv__ @@ -22,7 +22,7 @@ cbuffer SharedConstants : register(b2, space4) #endif -float4 main( +float4 shaderMain( in float4 iPos : SV_Position, in float4 iTexCoord0 : TEXCOORD0) : SV_Target0 { diff --git a/UnleashedRecomp/gpu/shader/copy_color_ps.hlsl b/UnleashedRecomp/gpu/shader/hlsl/copy_color_ps.hlsl similarity index 76% rename from UnleashedRecomp/gpu/shader/copy_color_ps.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/copy_color_ps.hlsl index 0559557a..95bd5c55 100644 --- a/UnleashedRecomp/gpu/shader/copy_color_ps.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/copy_color_ps.hlsl @@ -2,7 +2,7 @@ Texture2D g_Texture2DDescriptorHeap[] : register(t0, space0); -float4 main(in float4 position : SV_Position) : SV_Target +float4 shaderMain(in float4 position : SV_Position) : SV_Target { return g_Texture2DDescriptorHeap[g_PushConstants.ResourceDescriptorIndex].Load(int3(position.xy, 0)); } diff --git a/UnleashedRecomp/gpu/shader/copy_common.hlsli b/UnleashedRecomp/gpu/shader/hlsl/copy_common.hlsli similarity index 100% rename from UnleashedRecomp/gpu/shader/copy_common.hlsli rename to UnleashedRecomp/gpu/shader/hlsl/copy_common.hlsli diff --git a/UnleashedRecomp/gpu/shader/copy_depth_ps.hlsl b/UnleashedRecomp/gpu/shader/hlsl/copy_depth_ps.hlsl similarity index 77% rename from UnleashedRecomp/gpu/shader/copy_depth_ps.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/copy_depth_ps.hlsl index 251f893a..61d8328f 100644 --- a/UnleashedRecomp/gpu/shader/copy_depth_ps.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/copy_depth_ps.hlsl @@ -2,7 +2,7 @@ Texture2D g_Texture2DDescriptorHeap[] : register(t0, space0); -float main(in float4 position : SV_Position) : SV_Depth +float shaderMain(in float4 position : SV_Position) : SV_Depth { return g_Texture2DDescriptorHeap[g_PushConstants.ResourceDescriptorIndex].Load(int3(position.xy, 0)); } diff --git a/UnleashedRecomp/gpu/shader/copy_vs.hlsl b/UnleashedRecomp/gpu/shader/hlsl/copy_vs.hlsl similarity index 55% rename from UnleashedRecomp/gpu/shader/copy_vs.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/copy_vs.hlsl index 5a2576d7..94943765 100644 --- a/UnleashedRecomp/gpu/shader/copy_vs.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/copy_vs.hlsl @@ -1,4 +1,4 @@ -void main(in uint vertexId : SV_VertexID, out float4 position : SV_Position, out float2 texCoord : TEXCOORD) +void shaderMain(in uint vertexId : SV_VertexID, out float4 position : SV_Position, out float2 texCoord : TEXCOORD) { texCoord = float2((vertexId << 1) & 2, vertexId & 2); position = float4(texCoord * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); diff --git a/UnleashedRecomp/gpu/shader/csd_filter_ps.hlsl b/UnleashedRecomp/gpu/shader/hlsl/csd_filter_ps.hlsl similarity index 94% rename from UnleashedRecomp/gpu/shader/csd_filter_ps.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/csd_filter_ps.hlsl index e1ecde39..0e544a3c 100644 --- a/UnleashedRecomp/gpu/shader/csd_filter_ps.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/csd_filter_ps.hlsl @@ -1,4 +1,4 @@ -#include "../../../tools/XenosRecomp/XenosRecomp/shader_common.h" +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" #ifdef __spirv__ @@ -16,7 +16,7 @@ cbuffer SharedConstants : register(b2, space4) #endif -float4 main( +float4 shaderMain( in float4 iPosition : SV_Position, in float4 iTexCoord0 : TEXCOORD0, in float4 iTexCoord1 : TEXCOORD1) : SV_Target diff --git a/UnleashedRecomp/gpu/shader/csd_no_tex_vs.hlsl b/UnleashedRecomp/gpu/shader/hlsl/csd_no_tex_vs.hlsl similarity index 95% rename from UnleashedRecomp/gpu/shader/csd_no_tex_vs.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/csd_no_tex_vs.hlsl index 1654e734..b8163b2e 100644 --- a/UnleashedRecomp/gpu/shader/csd_no_tex_vs.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/csd_no_tex_vs.hlsl @@ -1,4 +1,4 @@ -#include "../../../tools/XenosRecomp/XenosRecomp/shader_common.h" +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" #ifdef __spirv__ @@ -20,7 +20,7 @@ cbuffer SharedConstants : register(b2, space4) #endif -void main( +void shaderMain( [[vk::location(0)]] in float4 iPosition0 : POSITION0, [[vk::location(8)]] in float4 iColor0 : COLOR0, out float4 oPos : SV_Position, diff --git a/UnleashedRecomp/gpu/shader/csd_vs.hlsl b/UnleashedRecomp/gpu/shader/hlsl/csd_vs.hlsl similarity index 95% rename from UnleashedRecomp/gpu/shader/csd_vs.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/csd_vs.hlsl index 90b561f5..0cb28364 100644 --- a/UnleashedRecomp/gpu/shader/csd_vs.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/csd_vs.hlsl @@ -1,4 +1,4 @@ -#include "../../../tools/XenosRecomp/XenosRecomp/shader_common.h" +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" #ifdef __spirv__ @@ -20,7 +20,7 @@ cbuffer SharedConstants : register(b2, space4) #endif -void main( +void shaderMain( [[vk::location(0)]] in float4 iPosition0 : POSITION0, [[vk::location(8)]] in float4 iColor0 : COLOR0, [[vk::location(4)]] in float4 iTexCoord0 : TEXCOORD0, diff --git a/UnleashedRecomp/gpu/shader/enhanced_motion_blur_ps.hlsl b/UnleashedRecomp/gpu/shader/hlsl/enhanced_motion_blur_ps.hlsl similarity index 94% rename from UnleashedRecomp/gpu/shader/enhanced_motion_blur_ps.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/enhanced_motion_blur_ps.hlsl index fd522da7..3535b696 100644 --- a/UnleashedRecomp/gpu/shader/enhanced_motion_blur_ps.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/enhanced_motion_blur_ps.hlsl @@ -1,4 +1,4 @@ -#include "../../../tools/XenosRecomp/XenosRecomp/shader_common.h" +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" #ifdef __spirv__ @@ -38,7 +38,7 @@ cbuffer SharedConstants : register(b2, space4) #endif -float4 main(in float4 position : SV_Position, in float4 texCoord : TEXCOORD0) : SV_Target +float4 shaderMain(in float4 position : SV_Position, in float4 texCoord : TEXCOORD0) : SV_Target { Texture2D sampColor = g_Texture2DDescriptorHeap[sampColor_Texture2DDescriptorIndex]; Texture2D sampVelocityMap = g_Texture2DDescriptorHeap[sampVelocityMap_Texture2DDescriptorIndex]; diff --git a/UnleashedRecomp/gpu/shader/gamma_correction_ps.hlsl b/UnleashedRecomp/gpu/shader/hlsl/gamma_correction_ps.hlsl similarity index 87% rename from UnleashedRecomp/gpu/shader/gamma_correction_ps.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/gamma_correction_ps.hlsl index 2f98b6e6..0c1d9361 100644 --- a/UnleashedRecomp/gpu/shader/gamma_correction_ps.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/gamma_correction_ps.hlsl @@ -1,4 +1,4 @@ -#include "../../../tools/XenosRecomp/XenosRecomp/shader_common.h" +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" #ifdef __spirv__ @@ -20,7 +20,7 @@ cbuffer SharedConstants : register(b2, space4) #endif -float4 main(in float4 position : SV_Position) : SV_Target +float4 shaderMain(in float4 position : SV_Position) : SV_Target { Texture2D texture = g_Texture2DDescriptorHeap[g_TextureDescriptorIndex]; diff --git a/UnleashedRecomp/gpu/shader/gaussian_blur.hlsli b/UnleashedRecomp/gpu/shader/hlsl/gaussian_blur.hlsli similarity index 93% rename from UnleashedRecomp/gpu/shader/gaussian_blur.hlsli rename to UnleashedRecomp/gpu/shader/hlsl/gaussian_blur.hlsli index 10d76cf3..a31c07c2 100644 --- a/UnleashedRecomp/gpu/shader/gaussian_blur.hlsli +++ b/UnleashedRecomp/gpu/shader/hlsl/gaussian_blur.hlsli @@ -1,4 +1,4 @@ -#include "../../../tools/XenosRecomp/XenosRecomp/shader_common.h" +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" #ifdef __spirv__ @@ -40,7 +40,7 @@ float ComputeWeight(float x) return exp(-(x * x) / (2.0 * std * std)) / (std * sqrt(2.0 * PI)); } -float4 main(in float4 iPosition : SV_Position, in float4 iTexCoord0 : TEXCOORD0) : SV_Target +float4 shaderMain(in float4 iPosition : SV_Position, in float4 iTexCoord0 : TEXCOORD0) : SV_Target { Texture2D texture = g_Texture2DDescriptorHeap[s0_Texture2DDescriptorIndex]; SamplerState samplerState = g_SamplerDescriptorHeap[s0_SamplerDescriptorIndex]; diff --git a/UnleashedRecomp/gpu/shader/gaussian_blur_3x3.hlsl b/UnleashedRecomp/gpu/shader/hlsl/gaussian_blur_3x3.hlsl similarity index 100% rename from UnleashedRecomp/gpu/shader/gaussian_blur_3x3.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/gaussian_blur_3x3.hlsl diff --git a/UnleashedRecomp/gpu/shader/gaussian_blur_5x5.hlsl b/UnleashedRecomp/gpu/shader/hlsl/gaussian_blur_5x5.hlsl similarity index 100% rename from UnleashedRecomp/gpu/shader/gaussian_blur_5x5.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/gaussian_blur_5x5.hlsl diff --git a/UnleashedRecomp/gpu/shader/gaussian_blur_7x7.hlsl b/UnleashedRecomp/gpu/shader/hlsl/gaussian_blur_7x7.hlsl similarity index 100% rename from UnleashedRecomp/gpu/shader/gaussian_blur_7x7.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/gaussian_blur_7x7.hlsl diff --git a/UnleashedRecomp/gpu/shader/gaussian_blur_9x9.hlsl b/UnleashedRecomp/gpu/shader/hlsl/gaussian_blur_9x9.hlsl similarity index 100% rename from UnleashedRecomp/gpu/shader/gaussian_blur_9x9.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/gaussian_blur_9x9.hlsl diff --git a/UnleashedRecomp/gpu/shader/imgui_common.hlsli b/UnleashedRecomp/gpu/shader/hlsl/imgui_common.hlsli similarity index 95% rename from UnleashedRecomp/gpu/shader/imgui_common.hlsli rename to UnleashedRecomp/gpu/shader/hlsl/imgui_common.hlsli index f4cbe3cf..42bd94ee 100644 --- a/UnleashedRecomp/gpu/shader/imgui_common.hlsli +++ b/UnleashedRecomp/gpu/shader/hlsl/imgui_common.hlsli @@ -1,6 +1,6 @@ #pragma once -#include "../imgui/imgui_common.h" +#include "../../imgui/imgui_common.h" struct PushConstants { diff --git a/UnleashedRecomp/gpu/shader/imgui_ps.hlsl b/UnleashedRecomp/gpu/shader/hlsl/imgui_ps.hlsl similarity index 99% rename from UnleashedRecomp/gpu/shader/imgui_ps.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/imgui_ps.hlsl index ac0a5983..3ee92099 100644 --- a/UnleashedRecomp/gpu/shader/imgui_ps.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/imgui_ps.hlsl @@ -123,7 +123,7 @@ float4 SampleSdfFont(float4 color, Texture2D texture, float2 uv, float2 return color; } -float4 main(in Interpolators interpolators) : SV_Target +float4 shaderMain(in Interpolators interpolators) : SV_Target { float4 color = interpolators.Color; color *= PixelAntialiasing(interpolators.Position.xy - g_PushConstants.ProceduralOrigin); diff --git a/UnleashedRecomp/gpu/shader/imgui_vs.hlsl b/UnleashedRecomp/gpu/shader/hlsl/imgui_vs.hlsl similarity index 85% rename from UnleashedRecomp/gpu/shader/imgui_vs.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/imgui_vs.hlsl index 50a53f4d..747b41ea 100644 --- a/UnleashedRecomp/gpu/shader/imgui_vs.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/imgui_vs.hlsl @@ -1,6 +1,6 @@ #include "imgui_common.hlsli" -void main(in float2 position : POSITION, in float2 uv : TEXCOORD, in float4 color : COLOR, out Interpolators interpolators) +void shaderMain(in float2 position : POSITION, in float2 uv : TEXCOORD, in float4 color : COLOR, out Interpolators interpolators) { if (g_PushConstants.ShaderModifier == IMGUI_SHADER_MODIFIER_TEXT_SKEW) { diff --git a/UnleashedRecomp/gpu/shader/movie_common.hlsli b/UnleashedRecomp/gpu/shader/hlsl/movie_common.hlsli similarity index 97% rename from UnleashedRecomp/gpu/shader/movie_common.hlsli rename to UnleashedRecomp/gpu/shader/hlsl/movie_common.hlsli index 12942353..61cc3b38 100644 --- a/UnleashedRecomp/gpu/shader/movie_common.hlsli +++ b/UnleashedRecomp/gpu/shader/hlsl/movie_common.hlsli @@ -1,6 +1,6 @@ #pragma once -#include "../../../tools/XenosRecomp/XenosRecomp/shader_common.h" +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" #ifdef __spirv__ diff --git a/UnleashedRecomp/gpu/shader/movie_ps.hlsl b/UnleashedRecomp/gpu/shader/hlsl/movie_ps.hlsl similarity index 98% rename from UnleashedRecomp/gpu/shader/movie_ps.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/movie_ps.hlsl index ec441a1d..fc3c8877 100644 --- a/UnleashedRecomp/gpu/shader/movie_ps.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/movie_ps.hlsl @@ -1,6 +1,6 @@ #include "movie_common.hlsli" -PixelShaderOutput main(in Interpolators In) +PixelShaderOutput shaderMain(in Interpolators In) { Texture2D Tex0 = g_Texture2DDescriptorHeap[Tex0_ResourceDescriptorIndex]; Texture2D Tex1 = g_Texture2DDescriptorHeap[Tex1_ResourceDescriptorIndex]; diff --git a/UnleashedRecomp/gpu/shader/movie_vs.hlsl b/UnleashedRecomp/gpu/shader/hlsl/movie_vs.hlsl similarity index 78% rename from UnleashedRecomp/gpu/shader/movie_vs.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/movie_vs.hlsl index 6d00919e..1ab5a364 100644 --- a/UnleashedRecomp/gpu/shader/movie_vs.hlsl +++ b/UnleashedRecomp/gpu/shader/hlsl/movie_vs.hlsl @@ -1,6 +1,6 @@ #include "movie_common.hlsli" -Interpolators main(in VertexShaderInput In) +Interpolators shaderMain(in VertexShaderInput In) { Interpolators Out; Out.ProjPos = In.ObjPos; diff --git a/UnleashedRecomp/gpu/shader/resolve_msaa_color.hlsli b/UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_color.hlsli similarity index 87% rename from UnleashedRecomp/gpu/shader/resolve_msaa_color.hlsli rename to UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_color.hlsli index f9b029d9..3b09d0cf 100644 --- a/UnleashedRecomp/gpu/shader/resolve_msaa_color.hlsli +++ b/UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_color.hlsli @@ -4,7 +4,7 @@ Texture2DMS g_Texture2DMSDescriptorHeap[] : register(t0, space0); -float4 main(in float4 position : SV_Position) : SV_Target +float4 shaderMain(in float4 position : SV_Position) : SV_Target { float4 result = g_Texture2DMSDescriptorHeap[g_PushConstants.ResourceDescriptorIndex].Load(int2(position.xy), 0); diff --git a/UnleashedRecomp/gpu/shader/resolve_msaa_color_2x.hlsl b/UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_color_2x.hlsl similarity index 100% rename from UnleashedRecomp/gpu/shader/resolve_msaa_color_2x.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_color_2x.hlsl diff --git a/UnleashedRecomp/gpu/shader/resolve_msaa_color_4x.hlsl b/UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_color_4x.hlsl similarity index 100% rename from UnleashedRecomp/gpu/shader/resolve_msaa_color_4x.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_color_4x.hlsl diff --git a/UnleashedRecomp/gpu/shader/resolve_msaa_color_8x.hlsl b/UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_color_8x.hlsl similarity index 100% rename from UnleashedRecomp/gpu/shader/resolve_msaa_color_8x.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_color_8x.hlsl diff --git a/UnleashedRecomp/gpu/shader/resolve_msaa_depth.hlsli b/UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_depth.hlsli similarity index 88% rename from UnleashedRecomp/gpu/shader/resolve_msaa_depth.hlsli rename to UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_depth.hlsli index a06c7bac..0d8f070e 100644 --- a/UnleashedRecomp/gpu/shader/resolve_msaa_depth.hlsli +++ b/UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_depth.hlsli @@ -4,7 +4,7 @@ Texture2DMS g_Texture2DMSDescriptorHeap[] : register(t0, space0); -float main(in float4 position : SV_Position) : SV_Depth +float shaderMain(in float4 position : SV_Position) : SV_Depth { float result = g_Texture2DMSDescriptorHeap[g_PushConstants.ResourceDescriptorIndex].Load(int2(position.xy), 0); diff --git a/UnleashedRecomp/gpu/shader/resolve_msaa_depth_2x.hlsl b/UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_depth_2x.hlsl similarity index 100% rename from UnleashedRecomp/gpu/shader/resolve_msaa_depth_2x.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_depth_2x.hlsl diff --git a/UnleashedRecomp/gpu/shader/resolve_msaa_depth_4x.hlsl b/UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_depth_4x.hlsl similarity index 100% rename from UnleashedRecomp/gpu/shader/resolve_msaa_depth_4x.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_depth_4x.hlsl diff --git a/UnleashedRecomp/gpu/shader/resolve_msaa_depth_8x.hlsl b/UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_depth_8x.hlsl similarity index 100% rename from UnleashedRecomp/gpu/shader/resolve_msaa_depth_8x.hlsl rename to UnleashedRecomp/gpu/shader/hlsl/resolve_msaa_depth_8x.hlsl diff --git a/UnleashedRecomp/gpu/shader/msl/.gitignore b/UnleashedRecomp/gpu/shader/msl/.gitignore new file mode 100644 index 00000000..40d087f0 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/.gitignore @@ -0,0 +1,4 @@ +*.ir +*.metallib +*.metal.*.c +*.metal.*.h \ No newline at end of file diff --git a/UnleashedRecomp/gpu/shader/msl/blend_color_alpha_ps.metal b/UnleashedRecomp/gpu/shader/msl/blend_color_alpha_ps.metal new file mode 100644 index 00000000..461130e7 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/blend_color_alpha_ps.metal @@ -0,0 +1,31 @@ +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" + +#define g_SrcAlpha_DestAlpha (*(reinterpret_cast(g_PushConstants.PixelShaderConstants + 2400))) +#define s0_Texture2DDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 0))) +#define s0_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 192))) + +struct Interpolators +{ + float4 iTexCoord0 [[user(TEXCOORD0)]]; +}; + +[[fragment]] +float4 shaderMain(float4 iPos [[position]], + Interpolators input [[stage_in]], + constant Texture2DDescriptorHeap* g_Texture2DDescriptorHeap [[buffer(0)]], + constant SamplerDescriptorHeap* g_SamplerDescriptorHeap [[buffer(3)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + texture2d texture = g_Texture2DDescriptorHeap[s0_Texture2DDescriptorIndex].tex; + sampler samplerState = g_SamplerDescriptorHeap[s0_SamplerDescriptorIndex].samp; + + float4 color = texture.sample(samplerState, input.iTexCoord0.xy); + + if (any(input.iTexCoord0.xy < 0.0 || input.iTexCoord0.xy > 1.0)) + color = float4(0.0, 0.0, 0.0, 1.0); + + color.rgb *= color.a * g_SrcAlpha_DestAlpha.x; + color.a = g_SrcAlpha_DestAlpha.y + (1.0 - color.a) * g_SrcAlpha_DestAlpha.x; + + return color; +} diff --git a/UnleashedRecomp/gpu/shader/msl/copy_color_ps.metal b/UnleashedRecomp/gpu/shader/msl/copy_color_ps.metal new file mode 100644 index 00000000..1ca6f6bd --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/copy_color_ps.metal @@ -0,0 +1,14 @@ +#include "copy_common.metali" + +struct Texture2DDescriptorHeap +{ + texture2d tex; +}; + +[[fragment]] +float4 shaderMain(float4 position [[position]], + constant Texture2DDescriptorHeap* g_Texture2DDescriptorHeap [[buffer(0)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + return g_Texture2DDescriptorHeap[g_PushConstants.ResourceDescriptorIndex].tex.read(uint2(position.xy), 0); +} diff --git a/UnleashedRecomp/gpu/shader/msl/copy_common.metali b/UnleashedRecomp/gpu/shader/msl/copy_common.metali new file mode 100644 index 00000000..2040a3a8 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/copy_common.metali @@ -0,0 +1,9 @@ +#pragma once +#include + +using namespace metal; + +struct PushConstants +{ + uint ResourceDescriptorIndex; +}; diff --git a/UnleashedRecomp/gpu/shader/msl/copy_depth_ps.metal b/UnleashedRecomp/gpu/shader/msl/copy_depth_ps.metal new file mode 100644 index 00000000..7f9bd37f --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/copy_depth_ps.metal @@ -0,0 +1,23 @@ +#include "copy_common.metali" + +struct Texture2DDescriptorHeap +{ + texture2d tex; +}; + +struct PixelShaderOutput +{ + float oDepth [[depth(any)]]; +}; + +[[fragment]] +PixelShaderOutput shaderMain(float4 position [[position]], + constant Texture2DDescriptorHeap* g_Texture2DDescriptorHeap [[buffer(0)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + PixelShaderOutput output = PixelShaderOutput{}; + + output.oDepth = g_Texture2DDescriptorHeap[g_PushConstants.ResourceDescriptorIndex].tex.read(uint2(position.xy), 0).x; + + return output; +} diff --git a/UnleashedRecomp/gpu/shader/msl/copy_vs.metal b/UnleashedRecomp/gpu/shader/msl/copy_vs.metal new file mode 100644 index 00000000..5703be50 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/copy_vs.metal @@ -0,0 +1,16 @@ +struct Interpolators +{ + float4 position [[position]]; + float2 texCoord [[user(TEXCOORD)]]; +}; + +[[vertex]] +Interpolators shaderMain(uint vertexId [[vertex_id]]) +{ + Interpolators interpolators; + + interpolators.texCoord = float2((vertexId << 1) & 2, vertexId & 2); + interpolators.position = float4(interpolators.texCoord * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); + + return interpolators; +} diff --git a/UnleashedRecomp/gpu/shader/msl/csd_filter_ps.metal b/UnleashedRecomp/gpu/shader/msl/csd_filter_ps.metal new file mode 100644 index 00000000..6dacbb6a --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/csd_filter_ps.metal @@ -0,0 +1,38 @@ +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" + +#define s0_Texture2DDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 0))) +#define s0_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 192))) + +struct Interpolators +{ + float4 iPosition [[position]]; + float4 iTexCoord0 [[user(TEXCOORD0)]]; + float4 iTexCoord1 [[user(TEXCOORD1)]]; +}; + +[[fragment]] +float4 shaderMain(Interpolators input [[stage_in]], + constant Texture2DDescriptorHeap* g_Texture2DDescriptorHeap [[buffer(0)]], + constant SamplerDescriptorHeap* g_SamplerDescriptorHeap [[buffer(3)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + texture2d texture = g_Texture2DDescriptorHeap[s0_Texture2DDescriptorIndex].tex; + sampler samplerState = g_SamplerDescriptorHeap[s0_SamplerDescriptorIndex].samp; + + uint2 dimensions = getTexture2DDimensions(texture); + + // https://www.shadertoy.com/view/csX3RH + float2 uvTexspace = input.iTexCoord1.xy * float2(dimensions); + float2 seam = floor(uvTexspace + 0.5); + uvTexspace = (uvTexspace - seam) / fwidth(uvTexspace) + seam; + uvTexspace = clamp(uvTexspace, seam - 0.5, seam + 0.5); + float2 texCoord = uvTexspace / float2(dimensions); + + float4 color = texture.sample(samplerState, texCoord); + color *= input.iTexCoord0; + + // The game enables alpha test for CSD, but the alpha threshold doesn't seem to be assigned anywhere? Weird. + clip(color.a - g_AlphaThreshold); + + return color; +} diff --git a/UnleashedRecomp/gpu/shader/msl/csd_no_tex_vs.metal b/UnleashedRecomp/gpu/shader/msl/csd_no_tex_vs.metal new file mode 100644 index 00000000..4e25d942 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/csd_no_tex_vs.metal @@ -0,0 +1,64 @@ +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" + +#define g_ViewportSize (*(reinterpret_cast(g_PushConstants.VertexShaderConstants + 2880))) +#define g_Z (*(reinterpret_cast(g_PushConstants.VertexShaderConstants + 3936))) + +struct VertexShaderInput +{ + float4 iPosition0 [[attribute(0)]]; + float4 iColor0 [[attribute(8)]]; +}; + +struct Interpolators +{ + float4 oPos [[position]]; + float4 oTexCoord0 [[user(TEXCOORD0)]]; + float4 oTexCoord1 [[user(TEXCOORD1)]]; + float4 oTexCoord2 [[user(TEXCOORD2)]]; + float4 oTexCoord3 [[user(TEXCOORD3)]]; + float4 oTexCoord4 [[user(TEXCOORD4)]]; + float4 oTexCoord5 [[user(TEXCOORD5)]]; + float4 oTexCoord6 [[user(TEXCOORD6)]]; + float4 oTexCoord7 [[user(TEXCOORD7)]]; + float4 oTexCoord8 [[user(TEXCOORD8)]]; + float4 oTexCoord9 [[user(TEXCOORD9)]]; + float4 oTexCoord10 [[user(TEXCOORD10)]]; + float4 oTexCoord11 [[user(TEXCOORD11)]]; + float4 oTexCoord12 [[user(TEXCOORD12)]]; + float4 oTexCoord13 [[user(TEXCOORD13)]]; + float4 oTexCoord14 [[user(TEXCOORD14)]]; + float4 oTexCoord15 [[user(TEXCOORD15)]]; + float4 oColor0 [[user(COLOR0)]]; + float4 oColor1 [[user(COLOR1)]]; +}; + +[[vertex]] +Interpolators shaderMain(VertexShaderInput input [[stage_in]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + Interpolators output; + + output.oPos.xy = input.iPosition0.xy * g_ViewportSize.zw * float2(2.0, -2.0) + float2(-1.0, 1.0); + output.oPos.z = g_Z.x; + output.oPos.w = 1.0; + output.oTexCoord0 = input.iColor0.wxyz; + output.oTexCoord1 = 0.0; + output.oTexCoord2 = 0.0; + output.oTexCoord3 = 0.0; + output.oTexCoord4 = 0.0; + output.oTexCoord5 = 0.0; + output.oTexCoord6 = 0.0; + output.oTexCoord7 = 0.0; + output.oTexCoord8 = 0.0; + output.oTexCoord9 = 0.0; + output.oTexCoord10 = 0.0; + output.oTexCoord11 = 0.0; + output.oTexCoord12 = 0.0; + output.oTexCoord13 = 0.0; + output.oTexCoord14 = 0.0; + output.oTexCoord15 = 0.0; + output.oColor0 = 0.0; + output.oColor1 = 0.0; + + return output; +} diff --git a/UnleashedRecomp/gpu/shader/msl/csd_vs.metal b/UnleashedRecomp/gpu/shader/msl/csd_vs.metal new file mode 100644 index 00000000..1493f77f --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/csd_vs.metal @@ -0,0 +1,66 @@ +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" + +#define g_ViewportSize (*(reinterpret_cast(g_PushConstants.VertexShaderConstants + 2880))) +#define g_Z (*(reinterpret_cast(g_PushConstants.VertexShaderConstants + 3936))) + +struct VertexShaderInput +{ + float4 iPosition0 [[attribute(0)]]; + float4 iColor0 [[attribute(8)]]; + float4 iTexCoord0 [[attribute(4)]]; +}; + +struct Interpolators +{ + float4 oPos [[position]]; + float4 oTexCoord0 [[user(TEXCOORD0)]]; + float4 oTexCoord1 [[user(TEXCOORD1)]]; + float4 oTexCoord2 [[user(TEXCOORD2)]]; + float4 oTexCoord3 [[user(TEXCOORD3)]]; + float4 oTexCoord4 [[user(TEXCOORD4)]]; + float4 oTexCoord5 [[user(TEXCOORD5)]]; + float4 oTexCoord6 [[user(TEXCOORD6)]]; + float4 oTexCoord7 [[user(TEXCOORD7)]]; + float4 oTexCoord8 [[user(TEXCOORD8)]]; + float4 oTexCoord9 [[user(TEXCOORD9)]]; + float4 oTexCoord10 [[user(TEXCOORD10)]]; + float4 oTexCoord11 [[user(TEXCOORD11)]]; + float4 oTexCoord12 [[user(TEXCOORD12)]]; + float4 oTexCoord13 [[user(TEXCOORD13)]]; + float4 oTexCoord14 [[user(TEXCOORD14)]]; + float4 oTexCoord15 [[user(TEXCOORD15)]]; + float4 oColor0 [[user(COLOR0)]]; + float4 oColor1 [[user(COLOR1)]]; +}; + +[[vertex]] +Interpolators shaderMain(VertexShaderInput input [[stage_in]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + Interpolators output; + + output.oPos.xy = input.iPosition0.xy * g_ViewportSize.zw * float2(2.0, -2.0) + float2(-1.0, 1.0); + output.oPos.z = g_Z.x; + output.oPos.w = 1.0; + output.oTexCoord0 = input.iColor0.wxyz; + output.oTexCoord1.xy = input.iTexCoord0.xy; + output.oTexCoord1.zw = 0.0; + output.oTexCoord2 = 0.0; + output.oTexCoord3 = 0.0; + output.oTexCoord4 = 0.0; + output.oTexCoord5 = 0.0; + output.oTexCoord6 = 0.0; + output.oTexCoord7 = 0.0; + output.oTexCoord8 = 0.0; + output.oTexCoord9 = 0.0; + output.oTexCoord10 = 0.0; + output.oTexCoord11 = 0.0; + output.oTexCoord12 = 0.0; + output.oTexCoord13 = 0.0; + output.oTexCoord14 = 0.0; + output.oTexCoord15 = 0.0; + output.oColor0 = 0.0; + output.oColor1 = 0.0; + + return output; +} diff --git a/UnleashedRecomp/gpu/shader/msl/enhanced_motion_blur_ps.metal b/UnleashedRecomp/gpu/shader/msl/enhanced_motion_blur_ps.metal new file mode 100644 index 00000000..a5205321 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/enhanced_motion_blur_ps.metal @@ -0,0 +1,59 @@ +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" + +#define g_BlurRate (*(reinterpret_cast(g_PushConstants.PixelShaderConstants + 2400))) +#define g_ViewportSize (*(reinterpret_cast(g_PushConstants.PixelShaderConstants + 384))) + +#define sampColor_Texture2DDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 0))) +#define sampColor_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 192))) + +#define sampVelocityMap_Texture2DDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 4))) +#define sampVelocityMap_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 196))) + +#define sampZBuffer_Texture2DDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 8))) +#define sampZBuffer_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 200))) + +struct Interpolators +{ + float4 texCoord [[user(TEXCOORD0)]]; +}; + +[[fragment]] +float4 shaderMain(float4 position [[position]], + Interpolators input [[stage_in]], + constant Texture2DDescriptorHeap* g_Texture2DDescriptorHeap [[buffer(0)]], + constant SamplerDescriptorHeap* g_SamplerDescriptorHeap [[buffer(3)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + texture2d sampColor = g_Texture2DDescriptorHeap[sampColor_Texture2DDescriptorIndex].tex; + texture2d sampVelocityMap = g_Texture2DDescriptorHeap[sampVelocityMap_Texture2DDescriptorIndex].tex; + texture2d sampZBuffer = g_Texture2DDescriptorHeap[sampZBuffer_Texture2DDescriptorIndex].tex; + + sampler sampColor_s = g_SamplerDescriptorHeap[sampColor_SamplerDescriptorIndex].samp; + sampler sampVelocityMap_s = g_SamplerDescriptorHeap[sampVelocityMap_SamplerDescriptorIndex].samp; + sampler sampZBuffer_s = g_SamplerDescriptorHeap[sampZBuffer_SamplerDescriptorIndex].samp; + + float depth = sampZBuffer.sample(sampZBuffer_s, input.texCoord.xy, level(0)).x; + float4 velocityMap = sampVelocityMap.sample(sampVelocityMap_s, input.texCoord.xy, level(0)); + float2 velocity = (velocityMap.xz + velocityMap.yw / 255.0) * 2.0 - 1.0; + + int sampleCount = min(64, int(round(length(velocity * g_ViewportSize.xy)))); + float2 sampleOffset = velocity / (float) sampleCount; + + float3 color = sampColor.sample(sampColor_s, input.texCoord.xy, level(0)).rgb; + int count = 1; + + for (int i = 1; i <= sampleCount; i++) + { + float2 sampleCoord = input.texCoord.xy + sampleOffset * i; + float3 sampleColor = sampColor.sample(sampColor_s, sampleCoord, level(0)).rgb; + float sampleDepth = sampZBuffer.sample(sampZBuffer_s, sampleCoord, 0).x; + + if (sampleDepth - depth < 0.01) + { + color += sampleColor; + count += 1; + } + } + + return float4(color / count, g_BlurRate.x * saturate(dot(abs(velocity), g_ViewportSize.xy) / 8.0) * saturate(float(count - 1))); +} diff --git a/UnleashedRecomp/gpu/shader/msl/gamma_correction_ps.metal b/UnleashedRecomp/gpu/shader/msl/gamma_correction_ps.metal new file mode 100644 index 00000000..6db3b887 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/gamma_correction_ps.metal @@ -0,0 +1,23 @@ +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" + +#define g_Gamma (*(reinterpret_cast(g_PushConstants.SharedConstants + 0))) +#define g_TextureDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 12))) + +#define g_ViewportOffset (*(reinterpret_cast(g_PushConstants.SharedConstants + 16))) +#define g_ViewportSize (*(reinterpret_cast(g_PushConstants.SharedConstants + 24))) + +[[fragment]] +float4 shaderMain(float4 position [[position]], + constant Texture2DDescriptorHeap* g_Texture2DDescriptorHeap [[buffer(0)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + texture2d texture = g_Texture2DDescriptorHeap[g_TextureDescriptorIndex].tex; + + int2 movedPosition = int2(position.xy) - g_ViewportOffset; + bool boxed = any(movedPosition < 0) || any(movedPosition >= g_ViewportSize); + if (boxed) movedPosition = 0; + + float4 color = boxed ? 0.0 : texture.read(uint2(movedPosition), 0); + color.rgb = pow(color.rgb, g_Gamma); + return color; +} diff --git a/UnleashedRecomp/gpu/shader/msl/gaussian_blur.metali b/UnleashedRecomp/gpu/shader/msl/gaussian_blur.metali new file mode 100644 index 00000000..dba59689 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/gaussian_blur.metali @@ -0,0 +1,63 @@ +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" + +#define g_ViewportSize (*(reinterpret_cast(g_PushConstants.PixelShaderConstants + 384))) +#define g_offsets(INDEX) selectWrapper((INDEX) < 74,(*(reinterpret_cast(g_PushConstants.PixelShaderConstants + (150 + min(INDEX, 73)) * 16))), 0.0) +#define g_weights (*(reinterpret_cast(g_PushConstants.PixelShaderConstants + 2656))) + +#define s0_Texture2DDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 0))) +#define s0_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 192))) + +#ifdef __INTELLISENSE__ +#define KERNEL_SIZE 5 +#endif + +#define PI 3.14159265358979323846 + +float ComputeWeight(float x) +{ + float std = 0.952; + return exp(-(x * x) / (2.0 * std * std)) / (std * sqrt(2.0 * PI)); +} + +struct Interpolators +{ + float4 iTexCoord0 [[user(TEXCOORD0)]]; +}; + +[[fragment]] +float4 shaderMain(float4 iPosition [[position]], + Interpolators input [[stage_in]], + constant Texture2DDescriptorHeap* g_Texture2DDescriptorHeap [[buffer(0)]], + constant SamplerDescriptorHeap* g_SamplerDescriptorHeap [[buffer(3)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + texture2d texture = g_Texture2DDescriptorHeap[s0_Texture2DDescriptorIndex].tex; + sampler samplerState = g_SamplerDescriptorHeap[s0_SamplerDescriptorIndex].samp; + + float scale; + if ((g_ViewportSize.x * g_ViewportSize.w) >= (16.0 / 9.0)) + scale = g_ViewportSize.y / 360.0; + else + scale = g_ViewportSize.x / 640.0; + + float2 offsets[3]; + offsets[0] = g_offsets(0).xy * scale; + offsets[1] = g_offsets(0).zw * scale; + offsets[2] = g_offsets(1).xy * scale; + + float4 color = 0.0; + float weightSum = 0.0; + + for (int i = 0; i < KERNEL_SIZE; i++) + { + float step = i / float(KERNEL_SIZE - 1); + float scaled = step * 2; + float2 offset = mix(offsets[int(scaled)], offsets[min(int(scaled) + 1, 2)], frac(scaled)); + float offsetScale = 1.0 / 0.75; + float weight = ComputeWeight(mix(-offsetScale, offsetScale, step)); + color += texture.sample(samplerState, input.iTexCoord0.xy + offset, level(0)) * weight; + weightSum += weight; + } + + return color / weightSum; +} diff --git a/UnleashedRecomp/gpu/shader/msl/gaussian_blur_3x3.metal b/UnleashedRecomp/gpu/shader/msl/gaussian_blur_3x3.metal new file mode 100644 index 00000000..1f8dbf31 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/gaussian_blur_3x3.metal @@ -0,0 +1,2 @@ +#define KERNEL_SIZE 3 +#include "gaussian_blur.metali" diff --git a/UnleashedRecomp/gpu/shader/msl/gaussian_blur_5x5.metal b/UnleashedRecomp/gpu/shader/msl/gaussian_blur_5x5.metal new file mode 100644 index 00000000..5b1a2c2d --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/gaussian_blur_5x5.metal @@ -0,0 +1,2 @@ +#define KERNEL_SIZE 5 +#include "gaussian_blur.metali" diff --git a/UnleashedRecomp/gpu/shader/msl/gaussian_blur_7x7.metal b/UnleashedRecomp/gpu/shader/msl/gaussian_blur_7x7.metal new file mode 100644 index 00000000..ba1bd736 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/gaussian_blur_7x7.metal @@ -0,0 +1,2 @@ +#define KERNEL_SIZE 7 +#include "gaussian_blur.metali" diff --git a/UnleashedRecomp/gpu/shader/msl/gaussian_blur_9x9.metal b/UnleashedRecomp/gpu/shader/msl/gaussian_blur_9x9.metal new file mode 100644 index 00000000..50198a76 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/gaussian_blur_9x9.metal @@ -0,0 +1,2 @@ +#define KERNEL_SIZE 9 +#include "gaussian_blur.metali" diff --git a/UnleashedRecomp/gpu/shader/msl/imgui_common.metali b/UnleashedRecomp/gpu/shader/msl/imgui_common.metali new file mode 100644 index 00000000..35cc10ef --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/imgui_common.metali @@ -0,0 +1,41 @@ +#pragma once +#include + +using namespace metal; + +#include "../../imgui/imgui_common.h" + +struct PushConstants +{ + float2 BoundsMin; + float2 BoundsMax; + uint GradientTopLeft; + uint GradientTopRight; + uint GradientBottomRight; + uint GradientBottomLeft; + uint ShaderModifier; + uint Texture2DDescriptorIndex; + float2 DisplaySize; + float2 InverseDisplaySize; + float2 Origin; + float2 Scale; + float2 ProceduralOrigin; + float Outline; +}; + +struct Interpolators +{ + float4 Position [[position]]; + float2 UV; + float4 Color; +}; + +struct Texture2DDescriptorHeap +{ + texture2d tex; +}; + +struct SamplerDescriptorHeap +{ + sampler samp; +}; \ No newline at end of file diff --git a/UnleashedRecomp/gpu/shader/msl/imgui_ps.metal b/UnleashedRecomp/gpu/shader/msl/imgui_ps.metal new file mode 100644 index 00000000..e00dc36a --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/imgui_ps.metal @@ -0,0 +1,235 @@ +#include "imgui_common.metali" + +float4 DecodeColor(uint color) +{ + return float4(color & 0xFF, (color >> 8) & 0xFF, (color >> 16) & 0xFF, (color >> 24) & 0xFF) / 255.0; +} + +float4 SamplePoint(int2 position, constant PushConstants& g_PushConstants) +{ + switch (g_PushConstants.ShaderModifier) + { + case IMGUI_SHADER_MODIFIER_SCANLINE: + { + if (int(position.y) % 2 == 0) + return float4(1.0, 1.0, 1.0, 0.0); + + break; + } + case IMGUI_SHADER_MODIFIER_CHECKERBOARD: + { + int remnantX = int(position.x) % 9; + int remnantY = int(position.y) % 9; + + float4 color = 1.0; + + if (remnantX == 0 || remnantY == 0) + color.a = 0.0; + + if ((remnantY % 2) == 0) + color.rgb = 0.5; + + return color; + } + case IMGUI_SHADER_MODIFIER_SCANLINE_BUTTON: + { + if (int(position.y) % 2 == 0) + return float4(1.0, 1.0, 1.0, 0.5); + + break; + } + } + + return 1.0; +} + +float4 SampleLinear(float2 uvTexspace, constant PushConstants& g_PushConstants) +{ + int2 integerPart = int2(floor(uvTexspace)); + float2 fracPart = fract(uvTexspace); + + float4 topLeft = SamplePoint(integerPart + int2(0, 0), g_PushConstants); + float4 topRight = SamplePoint(integerPart + int2(1, 0), g_PushConstants); + float4 bottomLeft = SamplePoint(integerPart + int2(0, 1), g_PushConstants); + float4 bottomRight = SamplePoint(integerPart + int2(1, 1), g_PushConstants); + + float4 top = mix(topLeft, topRight, fracPart.x); + float4 bottom = mix(bottomLeft, bottomRight, fracPart.x); + + return mix(top, bottom, fracPart.y); +} + +float4 PixelAntialiasing(float2 uvTexspace, constant PushConstants& g_PushConstants) +{ + if ((g_PushConstants.DisplaySize.x * g_PushConstants.InverseDisplaySize.y) >= (4.0 / 3.0)) + uvTexspace *= g_PushConstants.InverseDisplaySize.y * 720.0; + else + uvTexspace *= g_PushConstants.InverseDisplaySize.x * 960.0; + + float2 seam = floor(uvTexspace + 0.5); + uvTexspace = (uvTexspace - seam) / fwidth(uvTexspace) + seam; + uvTexspace = clamp(uvTexspace, seam - 0.5, seam + 0.5); + + return SampleLinear(uvTexspace - 0.5, g_PushConstants); +} + +float median(float r, float g, float b) +{ + return max(min(r, g), min(max(r, g), b)); +} + +float4 SampleSdfFont(float4 color, texture2d texture, float2 uv, float2 screenTexSize, + constant SamplerDescriptorHeap* g_SamplerDescriptorHeap, + constant PushConstants& g_PushConstants) +{ + float4 textureColor = texture.sample(g_SamplerDescriptorHeap[0].samp, uv); + + uint width = texture.get_width(); + uint height = texture.get_height(); + + float pxRange = 8.0; + float2 unitRange = pxRange / float2(width, height); + float screenPxRange = max(0.5 * dot(unitRange, screenTexSize), 1.0); + + float sd = median(textureColor.r, textureColor.g, textureColor.b) - 0.5; + float screenPxDistance = screenPxRange * (sd + g_PushConstants.Outline / (pxRange * 1.5)); + + if (g_PushConstants.ShaderModifier == IMGUI_SHADER_MODIFIER_TITLE_BEVEL) + { + float2 normal = normalize(float3(dfdx(sd), dfdy(sd), 0.01)).xy; + float3 rimColor = float3(1, 0.8, 0.29); + float3 shadowColor = float3(0.84, 0.57, 0); + + float cosTheta = dot(normal, normalize(float2(1, 1))); + float3 gradient = mix(color.rgb, cosTheta >= 0.0 ? rimColor : shadowColor, abs(cosTheta)); + color.rgb = mix(gradient, color.rgb, pow(saturate(sd + 0.77), 32.0)); + } + else if (g_PushConstants.ShaderModifier == IMGUI_SHADER_MODIFIER_CATEGORY_BEVEL) + { + float2 normal = normalize(float3(dfdx(sd), dfdy(sd), 0.25)).xy; + float cosTheta = dot(normal, normalize(float2(1, 1))); + float gradient = 1.0 + cosTheta * 0.5; + color.rgb = saturate(color.rgb * gradient); + } + else if (g_PushConstants.ShaderModifier == IMGUI_SHADER_MODIFIER_TEXT_SKEW) + { + float2 normal = normalize(float3(dfdx(sd), dfdy(sd), 0.5)).xy; + float cosTheta = dot(normal, normalize(float2(1, 1))); + float gradient = saturate(1.0 + cosTheta); + color.rgb = mix(color.rgb * gradient, color.rgb, pow(saturate(sd + 0.77), 32.0)); + } + + color.a *= saturate(screenPxDistance + 0.5); + color.a *= textureColor.a; + + return color; +} + +[[fragment]] +float4 shaderMain(Interpolators interpolators [[stage_in]], + constant Texture2DDescriptorHeap* g_Texture2DDescriptorHeap [[buffer(0)]], + constant SamplerDescriptorHeap* g_SamplerDescriptorHeap [[buffer(1)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + float4 color = interpolators.Color; + color *= PixelAntialiasing(interpolators.Position.xy - g_PushConstants.ProceduralOrigin, g_PushConstants); + + if (g_PushConstants.Texture2DDescriptorIndex != 0) + { + texture2d texture = g_Texture2DDescriptorHeap[g_PushConstants.Texture2DDescriptorIndex & 0x7FFFFFFF].tex; + + if ((g_PushConstants.Texture2DDescriptorIndex & 0x80000000) != 0) + { + if (g_PushConstants.ShaderModifier == IMGUI_SHADER_MODIFIER_LOW_QUALITY_TEXT) + { + float scale; + float invScale; + + if ((g_PushConstants.DisplaySize.x * g_PushConstants.InverseDisplaySize.y) >= (4.0 / 3.0)) + { + scale = g_PushConstants.InverseDisplaySize.y * 720.0; + invScale = g_PushConstants.DisplaySize.y / 720.0; + } + else + { + scale = g_PushConstants.InverseDisplaySize.x * 960.0; + invScale = g_PushConstants.DisplaySize.x / 960.0; + } + + float2 lowQualityPosition = (interpolators.Position.xy - 0.5) * scale; + float2 fracPart = fract(lowQualityPosition); + + float2 uvStep = fwidth(interpolators.UV) * invScale; + float2 lowQualityUV = interpolators.UV - fracPart * uvStep; + float2 screenTexSize = 1.0 / uvStep; + + float4 topLeft = SampleSdfFont(color, texture, lowQualityUV + float2(0, 0), screenTexSize, g_SamplerDescriptorHeap, g_PushConstants); + float4 topRight = SampleSdfFont(color, texture, lowQualityUV + float2(uvStep.x, 0), screenTexSize, g_SamplerDescriptorHeap, g_PushConstants); + float4 bottomLeft = SampleSdfFont(color, texture, lowQualityUV + float2(0, uvStep.y), screenTexSize, g_SamplerDescriptorHeap, g_PushConstants); + float4 bottomRight = SampleSdfFont(color, texture, lowQualityUV + uvStep.xy, screenTexSize, g_SamplerDescriptorHeap, g_PushConstants); + + float4 top = mix(topLeft, topRight, fracPart.x); + float4 bottom = mix(bottomLeft, bottomRight, fracPart.x); + + color = mix(top, bottom, fracPart.y); + } + else + { + color = SampleSdfFont(color, texture, interpolators.UV, 1.0 / fwidth(interpolators.UV), g_SamplerDescriptorHeap, g_PushConstants); + } + } + else + { + color *= texture.sample(g_SamplerDescriptorHeap[0].samp, interpolators.UV); + } + } + + if (g_PushConstants.ShaderModifier == IMGUI_SHADER_MODIFIER_HORIZONTAL_MARQUEE_FADE) + { + float minAlpha = saturate((interpolators.Position.x - g_PushConstants.BoundsMin.x) / g_PushConstants.Scale.x); + float maxAlpha = saturate((g_PushConstants.BoundsMax.x - interpolators.Position.x) / g_PushConstants.Scale.y); + + color.a *= minAlpha; + color.a *= maxAlpha; + } + else if (g_PushConstants.ShaderModifier == IMGUI_SHADER_MODIFIER_VERTICAL_MARQUEE_FADE) + { + float minAlpha = saturate((interpolators.Position.y - g_PushConstants.BoundsMin.y) / g_PushConstants.Scale.x); + float maxAlpha = saturate((g_PushConstants.BoundsMax.y - interpolators.Position.y) / g_PushConstants.Scale.y); + + color.a *= minAlpha; + color.a *= maxAlpha; + } + else if (any(g_PushConstants.BoundsMin != g_PushConstants.BoundsMax)) + { + float2 factor = saturate((interpolators.Position.xy - g_PushConstants.BoundsMin) / (g_PushConstants.BoundsMax - g_PushConstants.BoundsMin)); + + if (g_PushConstants.ShaderModifier == IMGUI_SHADER_MODIFIER_RECTANGLE_BEVEL) + { + float bevelSize = 0.9; + + float shadow = saturate((factor.x - bevelSize) / (1.0 - bevelSize)); + shadow = max(shadow, saturate((factor.y - bevelSize) / (1.0 - bevelSize))); + + float rim = saturate((1.0 - factor.x - bevelSize) / (1.0 - bevelSize)); + rim = max(rim, saturate((1.0 - factor.y - bevelSize) / (1.0 - bevelSize))); + + float3 rimColor = float3(1, 0.8, 0.29); + float3 shadowColor = float3(0.84, 0.57, 0); + + color.rgb = mix(color.rgb, rimColor, smoothstep(0.0, 1.0, rim)); + color.rgb = mix(color.rgb, shadowColor, smoothstep(0.0, 1.0, shadow)); + } + else + { + float4 top = mix(DecodeColor(g_PushConstants.GradientTopLeft), DecodeColor(g_PushConstants.GradientTopRight), smoothstep(0.0, 1.0, factor.x)); + float4 bottom = mix(DecodeColor(g_PushConstants.GradientBottomLeft), DecodeColor(g_PushConstants.GradientBottomRight), smoothstep(0.0, 1.0, factor.x)); + color *= mix(top, bottom, smoothstep(0.0, 1.0, factor.y)); + } + } + + if (g_PushConstants.ShaderModifier == IMGUI_SHADER_MODIFIER_GRAYSCALE) + color.rgb = dot(color.rgb, float3(0.2126, 0.7152, 0.0722)); + + return color; +} diff --git a/UnleashedRecomp/gpu/shader/msl/imgui_vs.metal b/UnleashedRecomp/gpu/shader/msl/imgui_vs.metal new file mode 100644 index 00000000..8da61c47 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/imgui_vs.metal @@ -0,0 +1,32 @@ +#include "imgui_common.metali" + +struct VertexStageIn +{ + float2 position [[attribute(0)]]; + float2 uv [[attribute(1)]]; + float4 color [[attribute(2)]]; +}; + +[[vertex]] +Interpolators shaderMain(VertexStageIn input [[stage_in]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + Interpolators interpolators = Interpolators{}; + + if (g_PushConstants.ShaderModifier == IMGUI_SHADER_MODIFIER_TEXT_SKEW) + { + if (input.position.y < g_PushConstants.Origin.y) + input.position.x += g_PushConstants.Scale.x; + } + else if (g_PushConstants.ShaderModifier != IMGUI_SHADER_MODIFIER_HORIZONTAL_MARQUEE_FADE && + g_PushConstants.ShaderModifier != IMGUI_SHADER_MODIFIER_VERTICAL_MARQUEE_FADE) + { + input.position.xy = g_PushConstants.Origin + (input.position.xy - g_PushConstants.Origin) * g_PushConstants.Scale; + } + + interpolators.Position = float4(input.position.xy * g_PushConstants.InverseDisplaySize * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); + interpolators.UV = input.uv; + interpolators.Color = input.color; + + return interpolators; +} diff --git a/UnleashedRecomp/gpu/shader/msl/movie_common.metali b/UnleashedRecomp/gpu/shader/msl/movie_common.metali new file mode 100644 index 00000000..9193155a --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/movie_common.metali @@ -0,0 +1,39 @@ +#pragma once + +#include "../../../../tools/XenosRecomp/XenosRecomp/shader_common.h" + +#define fZmin (*(reinterpret_cast(g_PushConstants.PixelShaderConstants + 0))) +#define fZmax (*(reinterpret_cast(g_PushConstants.PixelShaderConstants + 16))) + +#define Tex0_ResourceDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 0))) +#define Tex1_ResourceDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 4))) +#define Tex2_ResourceDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 8))) +#define Tex3_ResourceDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 12))) +#define Tex4_ResourceDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 16))) + +#define Tex0_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 64))) +#define Tex1_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 68))) +#define Tex2_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 72))) +#define Tex3_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 76))) +#define Tex4_SamplerDescriptorIndex (*(reinterpret_cast(g_PushConstants.SharedConstants + 80))) + +#define bCsc (g_Booleans & (1 << (16 + 0))) +#define bAmv (g_Booleans & (1 << (16 + 1))) +#define bZmv (g_Booleans & (1 << (16 + 2))) + +struct VertexShaderInput +{ + float4 ObjPos [[attribute(0)]]; + float2 UV [[attribute(4)]]; +}; + +struct Interpolators +{ + float4 ProjPos [[position]]; + float2 UV; +}; + +struct PixelShaderOutput +{ + float4 Color [[color(0)]]; +}; diff --git a/UnleashedRecomp/gpu/shader/msl/movie_ps.metal b/UnleashedRecomp/gpu/shader/msl/movie_ps.metal new file mode 100644 index 00000000..2b9fb5dc --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/movie_ps.metal @@ -0,0 +1,104 @@ +#include "movie_common.metali" + +[[fragment]] +PixelShaderOutput shaderMain(Interpolators In [[stage_in]], + constant Texture2DDescriptorHeap* g_Texture2DDescriptorHeap [[buffer(0)]], + constant SamplerDescriptorHeap* g_SamplerDescriptorHeap [[buffer(3)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + texture2d Tex0 = g_Texture2DDescriptorHeap[Tex0_ResourceDescriptorIndex].tex; + texture2d Tex1 = g_Texture2DDescriptorHeap[Tex1_ResourceDescriptorIndex].tex; + texture2d Tex2 = g_Texture2DDescriptorHeap[Tex2_ResourceDescriptorIndex].tex; + texture2d Tex3 = g_Texture2DDescriptorHeap[Tex3_ResourceDescriptorIndex].tex; + texture2d Tex4 = g_Texture2DDescriptorHeap[Tex4_ResourceDescriptorIndex].tex; + + sampler Tex0_s = g_SamplerDescriptorHeap[Tex0_SamplerDescriptorIndex].samp; + sampler Tex1_s = g_SamplerDescriptorHeap[Tex1_SamplerDescriptorIndex].samp; + sampler Tex2_s = g_SamplerDescriptorHeap[Tex2_SamplerDescriptorIndex].samp; + sampler Tex3_s = g_SamplerDescriptorHeap[Tex3_SamplerDescriptorIndex].samp; + sampler Tex4_s = g_SamplerDescriptorHeap[Tex4_SamplerDescriptorIndex].samp; + + PixelShaderOutput Out; + float ValY = Tex0.sample(Tex0_s, In.UV).r; + float ValU = Tex1.sample(Tex1_s, In.UV).r - 0.5; + float ValV = Tex2.sample(Tex2_s, In.UV).r - 0.5; + float ValA = 1.0; + float ValD = 0.0; + if (bAmv) + ValA = (Tex3.sample(Tex3_s, In.UV).r - 0.0625) * 1.164; + if (bZmv) + { + ValD = (Tex4.sample(Tex4_s, In.UV).r - 0.0625) * 1.164; + if (ValD < 9.0 / 255.0) + { + ValD = 0.0; + } + else if (ValD < 17.0 / 255.0) + { + ValD = fZmin; + } + else if (ValD < 224.0 / 255.0) + { + ValD = (ValD - 17.0 / 255.0) / (223.0 / 255.0 - 17.0 / 255.0) * (fZmax - fZmin) + fZmin; + } + else if (ValD < 240.0 / 255.0) + { + ValD = fZmax; + } + else + { + ValD = 1.0; + } + } + if (bCsc) + { + if (ValY < 16.0 / 255.0) + { + ValY = ValY * 3.0 / 2.0; + } + else if (ValY < 176.0 / 255.0) + { + ValY = 24.0 / 255.0 + (ValY - 16.0 / 255.0) / 2.0; + } + else if (ValY < 192.0 / 255.0) + { + ValY = 104.0 / 255.0 + (ValY - 176.0 / 255.0) / 1.0; + } + else + { + ValY = 120.0 / 255.0 + (ValY - 192.0 / 255.0) * 2.0; + } + if (abs(ValU) < 24.0 / 255.0) + { + ValU /= 3.0; + } + else + { + ValU = (8.0 / 255.0 + (abs(ValU) - 24.0 / 255.0) * (120.0 / 104.0)) * sign(ValU); + } + if (abs(ValV) < 24.0 / 255.0) + { + ValV /= 3.0; + } + else + { + ValV = (8.0 / 255.0 + (abs(ValV) - 24.0 / 255.0) * (120.0 / 104.0)) * sign(ValV); + } + Out.Color.r = ValY + ValV * 1.402; + Out.Color.g = ValY - ValU * 0.344 - ValV * 0.714; + Out.Color.b = ValY + ValU * 1.772; + } + else + { + ValY = (ValY - 0.0625) * 1.164; + Out.Color.r = ValY + ValV * 1.596; + Out.Color.g = ValY - ValU * 0.392 - ValV * 0.813; + Out.Color.b = ValY + ValU * 2.017; + } + Out.Color.a = ValA; + + if (any(In.UV < 0.0) || any(In.UV > 1.0)) + Out.Color.rgb = 0.0; + + return Out; +} diff --git a/UnleashedRecomp/gpu/shader/msl/movie_vs.metal b/UnleashedRecomp/gpu/shader/msl/movie_vs.metal new file mode 100644 index 00000000..30ad6044 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/movie_vs.metal @@ -0,0 +1,12 @@ +#include "movie_common.metali" + +[[vertex]] +Interpolators shaderMain(VertexShaderInput In [[stage_in]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + Interpolators Out; + Out.ProjPos = In.ObjPos; + Out.ProjPos.xy += g_HalfPixelOffset * Out.ProjPos.w; + Out.UV = In.UV; + return Out; +} diff --git a/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color.metali b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color.metali new file mode 100644 index 00000000..2a3bba5b --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color.metali @@ -0,0 +1,21 @@ +#pragma once + +#include "copy_common.metali" + +struct Texture2DMSDescriptorHeap +{ + texture2d_ms tex; +}; + +[[fragment]] +float4 shaderMain(float4 position [[position]], + constant Texture2DMSDescriptorHeap* g_Texture2DMSDescriptorHeap [[buffer(0)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + float4 result = g_Texture2DMSDescriptorHeap[g_PushConstants.ResourceDescriptorIndex].tex.read(uint2(position.xy), 0); + + for (int i = 1; i < SAMPLE_COUNT; i++) + result += g_Texture2DMSDescriptorHeap[g_PushConstants.ResourceDescriptorIndex].tex.read(uint2(position.xy), i); + + return result / SAMPLE_COUNT; +} diff --git a/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color_2x.metal b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color_2x.metal new file mode 100644 index 00000000..6aa43bb0 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color_2x.metal @@ -0,0 +1,2 @@ +#define SAMPLE_COUNT 2 +#include "resolve_msaa_color.metali" diff --git a/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color_4x.metal b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color_4x.metal new file mode 100644 index 00000000..17878881 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color_4x.metal @@ -0,0 +1,2 @@ +#define SAMPLE_COUNT 4 +#include "resolve_msaa_color.metali" diff --git a/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color_8x.metal b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color_8x.metal new file mode 100644 index 00000000..497f2ed2 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_color_8x.metal @@ -0,0 +1,2 @@ +#define SAMPLE_COUNT 8 +#include "resolve_msaa_color.metali" diff --git a/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth.metali b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth.metali new file mode 100644 index 00000000..bdd4aa92 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth.metali @@ -0,0 +1,30 @@ +#pragma once + +#include "copy_common.metali" + +struct Texture2DMSDescriptorHeap +{ + texture2d_ms tex; +}; + +struct PixelShaderOutput +{ + float oDepth [[depth(any)]]; +}; + +[[fragment]] +PixelShaderOutput shaderMain(float4 position [[position]], + constant Texture2DMSDescriptorHeap* g_Texture2DMSDescriptorHeap [[buffer(0)]], + constant PushConstants& g_PushConstants [[buffer(8)]]) +{ + PixelShaderOutput output = PixelShaderOutput{}; + + float result = g_Texture2DMSDescriptorHeap[g_PushConstants.ResourceDescriptorIndex].tex.read(uint2(position.xy), 0).x; + + for (int i = 1; i < SAMPLE_COUNT; i++) + result = min(result, g_Texture2DMSDescriptorHeap[g_PushConstants.ResourceDescriptorIndex].tex.read(uint2(position.xy), i).x); + + output.oDepth = result; + + return output; +} diff --git a/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth_2x.metal b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth_2x.metal new file mode 100644 index 00000000..cd3be171 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth_2x.metal @@ -0,0 +1,2 @@ +#define SAMPLE_COUNT 2 +#include "resolve_msaa_depth.metali" diff --git a/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth_4x.metal b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth_4x.metal new file mode 100644 index 00000000..e69b2c00 --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth_4x.metal @@ -0,0 +1,2 @@ +#define SAMPLE_COUNT 4 +#include "resolve_msaa_depth.metali" diff --git a/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth_8x.metal b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth_8x.metal new file mode 100644 index 00000000..eaa42e5c --- /dev/null +++ b/UnleashedRecomp/gpu/shader/msl/resolve_msaa_depth_8x.metal @@ -0,0 +1,2 @@ +#define SAMPLE_COUNT 8 +#include "resolve_msaa_depth.metali" diff --git a/UnleashedRecomp/gpu/video.cpp b/UnleashedRecomp/gpu/video.cpp index a9edd0b3..3f061758 100644 --- a/UnleashedRecomp/gpu/video.cpp +++ b/UnleashedRecomp/gpu/video.cpp @@ -3,6 +3,7 @@ #include "imgui/imgui_common.h" #include "imgui/imgui_snapshot.h" #include "imgui/imgui_font_builder.h" +#include "os/logger.h" #include #include @@ -27,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -41,54 +43,80 @@ #include "../../tools/XenosRecomp/XenosRecomp/shader_common.h" #ifdef UNLEASHED_RECOMP_D3D12 -#include "shader/blend_color_alpha_ps.hlsl.dxil.h" -#include "shader/copy_vs.hlsl.dxil.h" -#include "shader/copy_color_ps.hlsl.dxil.h" -#include "shader/copy_depth_ps.hlsl.dxil.h" -#include "shader/csd_filter_ps.hlsl.dxil.h" -#include "shader/csd_no_tex_vs.hlsl.dxil.h" -#include "shader/csd_vs.hlsl.dxil.h" -#include "shader/enhanced_motion_blur_ps.hlsl.dxil.h" -#include "shader/gamma_correction_ps.hlsl.dxil.h" -#include "shader/gaussian_blur_3x3.hlsl.dxil.h" -#include "shader/gaussian_blur_5x5.hlsl.dxil.h" -#include "shader/gaussian_blur_7x7.hlsl.dxil.h" -#include "shader/gaussian_blur_9x9.hlsl.dxil.h" -#include "shader/imgui_ps.hlsl.dxil.h" -#include "shader/imgui_vs.hlsl.dxil.h" -#include "shader/movie_ps.hlsl.dxil.h" -#include "shader/movie_vs.hlsl.dxil.h" -#include "shader/resolve_msaa_color_2x.hlsl.dxil.h" -#include "shader/resolve_msaa_color_4x.hlsl.dxil.h" -#include "shader/resolve_msaa_color_8x.hlsl.dxil.h" -#include "shader/resolve_msaa_depth_2x.hlsl.dxil.h" -#include "shader/resolve_msaa_depth_4x.hlsl.dxil.h" -#include "shader/resolve_msaa_depth_8x.hlsl.dxil.h" +#include "shader/hlsl/blend_color_alpha_ps.hlsl.dxil.h" +#include "shader/hlsl/copy_vs.hlsl.dxil.h" +#include "shader/hlsl/copy_color_ps.hlsl.dxil.h" +#include "shader/hlsl/copy_depth_ps.hlsl.dxil.h" +#include "shader/hlsl/csd_filter_ps.hlsl.dxil.h" +#include "shader/hlsl/csd_no_tex_vs.hlsl.dxil.h" +#include "shader/hlsl/csd_vs.hlsl.dxil.h" +#include "shader/hlsl/enhanced_motion_blur_ps.hlsl.dxil.h" +#include "shader/hlsl/gamma_correction_ps.hlsl.dxil.h" +#include "shader/hlsl/gaussian_blur_3x3.hlsl.dxil.h" +#include "shader/hlsl/gaussian_blur_5x5.hlsl.dxil.h" +#include "shader/hlsl/gaussian_blur_7x7.hlsl.dxil.h" +#include "shader/hlsl/gaussian_blur_9x9.hlsl.dxil.h" +#include "shader/hlsl/imgui_ps.hlsl.dxil.h" +#include "shader/hlsl/imgui_vs.hlsl.dxil.h" +#include "shader/hlsl/movie_ps.hlsl.dxil.h" +#include "shader/hlsl/movie_vs.hlsl.dxil.h" +#include "shader/hlsl/resolve_msaa_color_2x.hlsl.dxil.h" +#include "shader/hlsl/resolve_msaa_color_4x.hlsl.dxil.h" +#include "shader/hlsl/resolve_msaa_color_8x.hlsl.dxil.h" +#include "shader/hlsl/resolve_msaa_depth_2x.hlsl.dxil.h" +#include "shader/hlsl/resolve_msaa_depth_4x.hlsl.dxil.h" +#include "shader/hlsl/resolve_msaa_depth_8x.hlsl.dxil.h" #endif -#include "shader/blend_color_alpha_ps.hlsl.spirv.h" -#include "shader/copy_vs.hlsl.spirv.h" -#include "shader/copy_color_ps.hlsl.spirv.h" -#include "shader/copy_depth_ps.hlsl.spirv.h" -#include "shader/csd_filter_ps.hlsl.spirv.h" -#include "shader/csd_no_tex_vs.hlsl.spirv.h" -#include "shader/csd_vs.hlsl.spirv.h" -#include "shader/enhanced_motion_blur_ps.hlsl.spirv.h" -#include "shader/gamma_correction_ps.hlsl.spirv.h" -#include "shader/gaussian_blur_3x3.hlsl.spirv.h" -#include "shader/gaussian_blur_5x5.hlsl.spirv.h" -#include "shader/gaussian_blur_7x7.hlsl.spirv.h" -#include "shader/gaussian_blur_9x9.hlsl.spirv.h" -#include "shader/imgui_ps.hlsl.spirv.h" -#include "shader/imgui_vs.hlsl.spirv.h" -#include "shader/movie_ps.hlsl.spirv.h" -#include "shader/movie_vs.hlsl.spirv.h" -#include "shader/resolve_msaa_color_2x.hlsl.spirv.h" -#include "shader/resolve_msaa_color_4x.hlsl.spirv.h" -#include "shader/resolve_msaa_color_8x.hlsl.spirv.h" -#include "shader/resolve_msaa_depth_2x.hlsl.spirv.h" -#include "shader/resolve_msaa_depth_4x.hlsl.spirv.h" -#include "shader/resolve_msaa_depth_8x.hlsl.spirv.h" +#ifdef UNLEASHED_RECOMP_METAL +#include "shader/msl/blend_color_alpha_ps.metal.metallib.h" +#include "shader/msl/copy_vs.metal.metallib.h" +#include "shader/msl/copy_color_ps.metal.metallib.h" +#include "shader/msl/copy_depth_ps.metal.metallib.h" +#include "shader/msl/csd_filter_ps.metal.metallib.h" +#include "shader/msl/csd_no_tex_vs.metal.metallib.h" +#include "shader/msl/csd_vs.metal.metallib.h" +#include "shader/msl/enhanced_motion_blur_ps.metal.metallib.h" +#include "shader/msl/gamma_correction_ps.metal.metallib.h" +#include "shader/msl/gaussian_blur_3x3.metal.metallib.h" +#include "shader/msl/gaussian_blur_5x5.metal.metallib.h" +#include "shader/msl/gaussian_blur_7x7.metal.metallib.h" +#include "shader/msl/gaussian_blur_9x9.metal.metallib.h" +#include "shader/msl/imgui_ps.metal.metallib.h" +#include "shader/msl/imgui_vs.metal.metallib.h" +#include "shader/msl/movie_ps.metal.metallib.h" +#include "shader/msl/movie_vs.metal.metallib.h" +#include "shader/msl/resolve_msaa_color_2x.metal.metallib.h" +#include "shader/msl/resolve_msaa_color_4x.metal.metallib.h" +#include "shader/msl/resolve_msaa_color_8x.metal.metallib.h" +#include "shader/msl/resolve_msaa_depth_2x.metal.metallib.h" +#include "shader/msl/resolve_msaa_depth_4x.metal.metallib.h" +#include "shader/msl/resolve_msaa_depth_8x.metal.metallib.h" +#endif + +#include "shader/hlsl/blend_color_alpha_ps.hlsl.spirv.h" +#include "shader/hlsl/copy_vs.hlsl.spirv.h" +#include "shader/hlsl/copy_color_ps.hlsl.spirv.h" +#include "shader/hlsl/copy_depth_ps.hlsl.spirv.h" +#include "shader/hlsl/csd_filter_ps.hlsl.spirv.h" +#include "shader/hlsl/csd_no_tex_vs.hlsl.spirv.h" +#include "shader/hlsl/csd_vs.hlsl.spirv.h" +#include "shader/hlsl/enhanced_motion_blur_ps.hlsl.spirv.h" +#include "shader/hlsl/gamma_correction_ps.hlsl.spirv.h" +#include "shader/hlsl/gaussian_blur_3x3.hlsl.spirv.h" +#include "shader/hlsl/gaussian_blur_5x5.hlsl.spirv.h" +#include "shader/hlsl/gaussian_blur_7x7.hlsl.spirv.h" +#include "shader/hlsl/gaussian_blur_9x9.hlsl.spirv.h" +#include "shader/hlsl/imgui_ps.hlsl.spirv.h" +#include "shader/hlsl/imgui_vs.hlsl.spirv.h" +#include "shader/hlsl/movie_ps.hlsl.spirv.h" +#include "shader/hlsl/movie_vs.hlsl.spirv.h" +#include "shader/hlsl/resolve_msaa_color_2x.hlsl.spirv.h" +#include "shader/hlsl/resolve_msaa_color_4x.hlsl.spirv.h" +#include "shader/hlsl/resolve_msaa_color_8x.hlsl.spirv.h" +#include "shader/hlsl/resolve_msaa_depth_2x.hlsl.spirv.h" +#include "shader/hlsl/resolve_msaa_depth_4x.hlsl.spirv.h" +#include "shader/hlsl/resolve_msaa_depth_8x.hlsl.spirv.h" #ifdef _WIN32 extern "C" @@ -103,6 +131,9 @@ namespace plume #ifdef UNLEASHED_RECOMP_D3D12 extern std::unique_ptr CreateD3D12Interface(); #endif +#ifdef UNLEASHED_RECOMP_METAL + extern std::unique_ptr CreateMetalInterface(); +#endif #ifdef SDL_VULKAN_ENABLED extern std::unique_ptr CreateVulkanInterface(RenderWindow sdlWindow); #else @@ -170,7 +201,7 @@ struct SharedConstants float alphaThreshold{}; }; -// Depth bias values here are only used when the render device has +// Depth bias values here are only used when the render device has // dynamic depth bias capability enabled. Otherwise, they get unused // and the values get assigned in the pipeline state instead. @@ -283,17 +314,14 @@ static Profiler g_swapChainAcquireProfiler; static bool g_profilerVisible; static bool g_profilerWasToggled; -#ifdef UNLEASHED_RECOMP_D3D12 -static bool g_vulkan = false; +#if !defined(UNLEASHED_RECOMP_D3D12) && !defined(UNLEASHED_RECOMP_METAL) +static constexpr Backend g_backend = Backend::VULKAN; #else -static constexpr bool g_vulkan = true; +static Backend g_backend; #endif static bool g_triangleStripWorkaround = false; -static bool g_hardwareResolve = true; -static bool g_hardwareDepthResolve = true; - static std::unique_ptr g_interface; static std::unique_ptr g_device; @@ -311,6 +339,10 @@ static std::unique_ptr g_commandFences[NUM_FRAMES]; static std::unique_ptr g_queryPools[NUM_FRAMES]; static bool g_commandListStates[NUM_FRAMES]; +static Mutex g_waitForGPUMutex; +static std::unique_ptr g_waitForGPUCommandList; +static std::unique_ptr g_waitForGPUCommandFence; + static Mutex g_copyMutex; static std::unique_ptr g_copyQueue; static std::unique_ptr g_copyCommandList; @@ -422,7 +454,7 @@ static std::vector g_pipelineTaskQueue; static void EnqueuePipelineTask(PipelineTaskType type, const boost::shared_ptr& databaseData) { - // Precompiled pipelines deliberately do not increment + // Precompiled pipelines deliberately do not increment // this counter to overlap the compilation with intro logos. if (type != PipelineTaskType::PrecompilePipelines) ++g_compilingPipelineTaskCount; @@ -486,11 +518,11 @@ struct UploadAllocator auto& buffer = buffers[index]; if (buffer.buffer == nullptr) { - buffer.buffer = g_device->createBuffer(RenderBufferDesc::UploadBuffer(UploadBuffer::SIZE, RenderBufferFlag::CONSTANT | RenderBufferFlag::VERTEX | RenderBufferFlag::INDEX)); + buffer.buffer = g_device->createBuffer(RenderBufferDesc::UploadBuffer(UploadBuffer::SIZE, RenderBufferFlag::CONSTANT | RenderBufferFlag::VERTEX | RenderBufferFlag::INDEX | RenderBufferFlag::DEVICE_ADDRESSABLE)); buffer.memory = reinterpret_cast(buffer.buffer->map()); buffer.deviceAddress = buffer.buffer->getDeviceAddress(); } - + auto ref = buffer.buffer->at(offset); offset += size; @@ -596,7 +628,7 @@ struct PrimitiveIndexData { case D3DPT_TRIANGLEFAN: primCount = guestPrimCount - 2; - indexCountPerPrimitive = 3; + indexCountPerPrimitive = 3; break; case D3DPT_QUADLIST: primCount = guestPrimCount / 4; @@ -684,8 +716,8 @@ static void DestructTempResources() g_textureDescriptorAllocator.free(texture->descriptorIndex); if (texture->patchedTexture != nullptr) - g_textureDescriptorAllocator.free(texture->patchedTexture->descriptorIndex); - + g_textureDescriptorAllocator.free(texture->patchedTexture->descriptorIndex); + if (texture->recreatedCubeMapTexture != nullptr) g_textureDescriptorAllocator.free(texture->recreatedCubeMapTexture->descriptorIndex); @@ -738,6 +770,9 @@ static void DestructTempResources() static std::thread::id g_presentThreadId = std::this_thread::get_id(); static std::atomic g_readyForCommands; +static std::atomic g_appSuspended = false; + +static const std::thread::id g_eventThreadId = std::this_thread::get_id(); PPC_FUNC_IMPL(__imp__sub_824ECA00); PPC_FUNC(sub_824ECA00) @@ -780,18 +815,26 @@ static std::unique_ptr g_buttonBcDiff; static void LoadEmbeddedResources() { - if (g_vulkan) + switch (g_backend) { + case Backend::VULKAN: g_shaderCache = std::make_unique(g_spirvCacheDecompressedSize); ZSTD_decompress(g_shaderCache.get(), g_spirvCacheDecompressedSize, g_compressedSpirvCache, g_spirvCacheCompressedSize); - } -#ifdef UNLEASHED_RECOMP_D3D12 - else - { + break; +#if defined(UNLEASHED_RECOMP_D3D12) + case Backend::D3D12: g_shaderCache = std::make_unique(g_dxilCacheDecompressedSize); ZSTD_decompress(g_shaderCache.get(), g_dxilCacheDecompressedSize, g_compressedDxilCache, g_dxilCacheCompressedSize); - } + break; +#elif defined(UNLEASHED_RECOMP_METAL) + case Backend::METAL: + g_shaderCache = std::make_unique(g_airCacheDecompressedSize); + ZSTD_decompress(g_shaderCache.get(), g_airCacheDecompressedSize, g_compressedAirCache, g_airCacheCompressedSize); + break; #endif + default: + assert(false); + } g_buttonBcDiff = decompressZstd(g_button_bc_diff, g_button_bc_diff_uncompressed_size); } @@ -852,7 +895,7 @@ struct RenderCommand uint32_t value; } setRenderState; - struct + struct { GuestResource* resource; } destructResource; @@ -867,31 +910,31 @@ struct RenderCommand GuestBuffer* buffer; } unlockBuffer; - struct + struct { GuestDevice* device; uint32_t flags; GuestTexture* texture; } stretchRect; - struct + struct { GuestSurface* renderTarget; } setRenderTarget; - struct + struct { GuestSurface* depthStencil; } setDepthStencilSurface; - struct + struct { uint32_t flags; float color[4]; float z; } clear; - struct + struct { float x; float y; @@ -901,13 +944,13 @@ struct RenderCommand float maxDepth; } setViewport; - struct + struct { uint32_t index; GuestTexture* texture; } setTexture; - struct + struct { int32_t left; int32_t top; @@ -933,8 +976,8 @@ struct RenderCommand uint8_t* memory; uint32_t index; uint32_t size; - } setVertexShaderConstants; - + } setVertexShaderConstants; + struct { uint8_t* memory; @@ -948,42 +991,42 @@ struct RenderCommand RenderPipeline* pipeline; } addPipeline; - struct + struct { - uint32_t primitiveType; - uint32_t startVertex; + uint32_t primitiveType; + uint32_t startVertex; uint32_t primitiveCount; } drawPrimitive; - struct + struct { uint32_t primitiveType; - int32_t baseVertexIndex; + int32_t baseVertexIndex; uint32_t startIndex; uint32_t primCount; } drawIndexedPrimitive; - struct + struct { uint32_t primitiveType; - uint32_t primitiveCount; + uint32_t primitiveCount; uint8_t* vertexStreamZeroData; uint32_t vertexStreamZeroSize; uint32_t vertexStreamZeroStride; CsdFilterState csdFilterState; } drawPrimitiveUP; - struct + struct { GuestVertexDeclaration* vertexDeclaration; } setVertexDeclaration; - struct + struct { GuestShader* shader; } setVertexShader; - struct + struct { uint32_t index; GuestBuffer* buffer; @@ -991,12 +1034,12 @@ struct RenderCommand uint32_t stride; } setStreamSource; - struct + struct { GuestBuffer* buffer; } setIndices; - struct + struct { GuestShader* shader; } setPixelShader; @@ -1187,7 +1230,7 @@ static void ProcSetRenderState(const RenderCommand& cmd) } case D3DRS_ALPHAREF: { - SetDirtyValue(g_dirtyStates.pipelineState, g_sharedConstants.alphaThreshold, float(value) / 256.0f); + SetDirtyValue(g_dirtyStates.sharedConstants, g_sharedConstants.alphaThreshold, float(value) / 256.0f); break; } case D3DRS_ALPHABLENDENABLE: @@ -1209,7 +1252,7 @@ static void ProcSetRenderState(const RenderCommand& cmd) { if (g_capabilities.dynamicDepthBias) SetDirtyValue(g_dirtyStates.depthBias, g_slopeScaledDepthBias, *reinterpret_cast(&value)); - else + else SetDirtyValue(g_dirtyStates.pipelineState, g_pipelineState.slopeScaledDepthBias, *reinterpret_cast(&value)); break; @@ -1294,19 +1337,28 @@ static GuestShader* g_csdShader; static std::unique_ptr g_enhancedMotionBlurShader; -#ifdef UNLEASHED_RECOMP_D3D12 +#if defined(UNLEASHED_RECOMP_D3D12) #define CREATE_SHADER(NAME) \ g_device->createShader( \ - g_vulkan ? g_##NAME##_spirv : g_##NAME##_dxil, \ - g_vulkan ? sizeof(g_##NAME##_spirv) : sizeof(g_##NAME##_dxil), \ - "main", \ - g_vulkan ? RenderShaderFormat::SPIRV : RenderShaderFormat::DXIL) + (g_backend == Backend::VULKAN) ? g_##NAME##_spirv : g_##NAME##_dxil, \ + (g_backend == Backend::VULKAN) ? sizeof(g_##NAME##_spirv) : sizeof(g_##NAME##_dxil), \ + "shaderMain", \ + (g_backend == Backend::VULKAN) ? RenderShaderFormat::SPIRV : RenderShaderFormat::DXIL) + +#elif defined(UNLEASHED_RECOMP_METAL) + +#define CREATE_SHADER(NAME) \ + g_device->createShader( \ + (g_backend == Backend::VULKAN) ? g_##NAME##_spirv : g_##NAME##_air, \ + (g_backend == Backend::VULKAN) ? sizeof(g_##NAME##_spirv) : sizeof(g_##NAME##_air), \ + "shaderMain", \ + (g_backend == Backend::VULKAN) ? RenderShaderFormat::SPIRV : RenderShaderFormat::METAL) #else #define CREATE_SHADER(NAME) \ - g_device->createShader(g_##NAME##_spirv, sizeof(g_##NAME##_spirv), "main", RenderShaderFormat::SPIRV) + g_device->createShader(g_##NAME##_spirv, sizeof(g_##NAME##_spirv), "shaderMain", RenderShaderFormat::SPIRV) #endif @@ -1384,6 +1436,10 @@ static void CreateImGuiBackend() OptionsMenu::Init(); InstallerWizard::Init(); +#ifdef UNLEASHED_RECOMP_IOS + TouchControls::Init(); +#endif + ImGui_ImplSDL2_InitForOther(GameWindow::s_pWindow); #ifdef ENABLE_IM_FONT_ATLAS_SNAPSHOT @@ -1629,6 +1685,10 @@ static void BeginCommandList() commandList->setGraphicsDescriptorSet(g_textureDescriptorSet.get(), 2); commandList->setGraphicsDescriptorSet(g_samplerDescriptorSet.get(), 3); + if (g_appSuspended.load(std::memory_order_relaxed)) { + g_appSuspended.wait(true, std::memory_order_acquire); + } + g_readyForCommands = true; g_readyForCommands.notify_one(); } @@ -1641,7 +1701,7 @@ static void ApplyLowEndDefault(ConfigDef &configDef, T newDefault, bool &chan configDef = newDefault; changed = true; } - + configDef.DefaultValue = newDefault; } @@ -1654,12 +1714,19 @@ static void ApplyLowEndDefaults() ApplyLowEndDefault(Config::TransparencyAntiAliasing, false, changed); ApplyLowEndDefault(Config::GITextureFiltering, EGITextureFiltering::Bilinear, changed); - if (changed) + if (changed) { Config::Save(); } } +#ifdef __APPLE__ +static void ApplyMetalHUDConfig() +{ + setenv("MTL_HUD_ENABLED", Config::ShowMetalHUD ? "1" : "0", 1); +} +#endif + bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) { for (uint32_t i = 0; i < 16; i++) @@ -1671,8 +1738,14 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) GameWindow::Init(sdlVideoDriver); -#ifdef UNLEASHED_RECOMP_D3D12 - g_vulkan = DetectWine() || Config::GraphicsAPI == EGraphicsAPI::Vulkan; +#if defined(UNLEASHED_RECOMP_D3D12) + g_backend = (DetectWine() || Config::GraphicsAPI == EGraphicsAPI::Vulkan) ? Backend::VULKAN : Backend::D3D12; +#elif defined(UNLEASHED_RECOMP_METAL) + g_backend = Config::GraphicsAPI == EGraphicsAPI::Vulkan ? Backend::VULKAN : Backend::METAL; +#endif + +#ifdef __APPLE__ + ApplyMetalHUDConfig(); #endif // Attempt to create the possible backends using a vector of function pointers. Whichever succeeds first will be the chosen API. @@ -1685,15 +1758,18 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) if (graphicsApiRetry) { // If we are attempting to create again after a reboot due to a crash, swap the order. - g_vulkan = !g_vulkan; + g_backend = (g_backend == Backend::VULKAN) ? Backend::D3D12 : Backend::VULKAN; - // Don't allow redirection to Vulkan if we are retrying after a crash, + // Don't allow redirection to Vulkan if we are retrying after a crash, // so the user can at least boot the game with D3D12 if Vulkan fails to work. allowVulkanRedirection = false; } - interfaceFunctions.push_back(g_vulkan ? CreateVulkanInterfaceWrapper : CreateD3D12Interface); - interfaceFunctions.push_back(g_vulkan ? CreateD3D12Interface : CreateVulkanInterfaceWrapper); + interfaceFunctions.push_back((g_backend == Backend::VULKAN) ? CreateVulkanInterfaceWrapper : CreateD3D12Interface); + interfaceFunctions.push_back((g_backend == Backend::VULKAN) ? CreateD3D12Interface : CreateVulkanInterfaceWrapper); +#elif defined(UNLEASHED_RECOMP_METAL) + interfaceFunctions.push_back((g_backend == Backend::VULKAN) ? CreateVulkanInterfaceWrapper : CreateMetalInterface); + interfaceFunctions.push_back((g_backend == Backend::VULKAN) ? CreateMetalInterface : CreateVulkanInterfaceWrapper); #else interfaceFunctions.push_back(CreateVulkanInterfaceWrapper); #endif @@ -1717,8 +1793,8 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) if (g_device != nullptr) { const RenderDeviceDescription &deviceDescription = g_device->getDescription(); - -#ifdef UNLEASHED_RECOMP_D3D12 + +#if defined(UNLEASHED_RECOMP_D3D12) if (interfaceFunction == CreateD3D12Interface) { if (allowVulkanRedirection) @@ -1747,9 +1823,9 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) g_device.reset(); g_interface.reset(); - // In case Vulkan fails to initialize, we will try D3D12 again afterwards, + // In case Vulkan fails to initialize, we will try D3D12 again afterwards, // just to get the game to boot. This only really happens in very old Intel GPU drivers. - if (!g_vulkan) + if (g_backend != Backend::VULKAN) { interfaceFunctions.push_back(CreateD3D12Interface); allowVulkanRedirection = false; @@ -1758,13 +1834,11 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) continue; } } - - // Hardware resolve seems to be completely bugged on Intel D3D12 drivers. - g_hardwareResolve = (deviceDescription.vendor != RenderDeviceVendor::INTEL); - g_hardwareDepthResolve = (deviceDescription.vendor != RenderDeviceVendor::INTEL); } - g_vulkan = (interfaceFunction == CreateVulkanInterfaceWrapper); + g_backend = (interfaceFunction == CreateVulkanInterfaceWrapper) ? Backend::VULKAN : Backend::D3D12; +#elif defined(UNLEASHED_RECOMP_METAL) + g_backend = (interfaceFunction == CreateVulkanInterfaceWrapper) ? Backend::VULKAN : Backend::METAL; #endif // Enable triangle strip workaround if we are on AMD, as there is a bug where // restart indices cause triangles to be culled incorrectly. Converting them to degenerate triangles fixes it. @@ -1800,7 +1874,7 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) if (graphicsApiRetry) { // If we managed to create a device after retrying it in a reboot, remember the one we picked. - Config::GraphicsAPI = g_vulkan ? EGraphicsAPI::Vulkan : EGraphicsAPI::D3D12; + Config::GraphicsAPI = g_backend == Backend::VULKAN ? EGraphicsAPI::Vulkan : EGraphicsAPI::D3D12; } #endif @@ -1843,6 +1917,9 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) for (auto& commandFence : g_commandFences) commandFence = g_device->createCommandFence(); + g_waitForGPUCommandList = g_queue->createCommandList(); + g_waitForGPUCommandFence = g_device->createCommandFence(); + for (auto& queryPool : g_queryPools) queryPool = g_device->createQueryPool(NUM_QUERIES); @@ -1855,15 +1932,18 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) switch (Config::TripleBuffering) { case ETripleBuffering::Auto: - if (g_vulkan) - { + switch (g_backend) { + case Backend::VULKAN: // Defaulting to 3 is fine if presentWait as supported, as the maximum frame latency allowed is only 1. bufferCount = g_device->getCapabilities().presentWait ? 3 : 2; - } - else - { + break; + case Backend::D3D12: // Defaulting to 3 is fine on D3D12 thanks to flip discard model. bufferCount = 3; + break; + case Backend::METAL: + bufferCount = 2; + break; } break; @@ -1875,26 +1955,33 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) break; } - g_swapChain = g_queue->createSwapChain(GameWindow::s_renderWindow, bufferCount, BACKBUFFER_FORMAT, Config::MaxFrameLatency); + RenderSwapChainDesc swapChainDesc; + swapChainDesc.renderWindow = GameWindow::s_renderWindow; + swapChainDesc.textureCount = bufferCount; + swapChainDesc.format = BACKBUFFER_FORMAT; + swapChainDesc.maxFrameLatency = Config::MaxFrameLatency; + swapChainDesc.enablePresentWait = g_capabilities.presentWait; + + g_swapChain = g_queue->createSwapChain(swapChainDesc); g_swapChain->setVsyncEnabled(Config::VSync); g_swapChainValid = !g_swapChain->needsResize(); for (auto& acquireSemaphore : g_acquireSemaphores) acquireSemaphore = g_device->createCommandSemaphore(); - + for (auto& renderSemaphore : g_renderSemaphores) renderSemaphore = g_device->createCommandSemaphore(); RenderPipelineLayoutBuilder pipelineLayoutBuilder; pipelineLayoutBuilder.begin(false, true); - + RenderDescriptorSetBuilder descriptorSetBuilder; descriptorSetBuilder.begin(); descriptorSetBuilder.addTexture(0, TEXTURE_DESCRIPTOR_SIZE); descriptorSetBuilder.end(true, TEXTURE_DESCRIPTOR_SIZE); - + g_textureDescriptorSet = descriptorSetBuilder.create(g_device.get()); - + for (size_t i = 0; i < TEXTURE_DESCRIPTOR_NULL_COUNT; i++) { auto& texture = g_blankTextures[i]; @@ -1947,11 +2034,11 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) pipelineLayoutBuilder.addDescriptorSet(descriptorSetBuilder); pipelineLayoutBuilder.addDescriptorSet(descriptorSetBuilder); pipelineLayoutBuilder.addDescriptorSet(descriptorSetBuilder); - + descriptorSetBuilder.begin(); descriptorSetBuilder.addSampler(0, SAMPLER_DESCRIPTOR_SIZE); descriptorSetBuilder.end(true, SAMPLER_DESCRIPTOR_SIZE); - + g_samplerDescriptorSet = descriptorSetBuilder.create(g_device.get()); auto& [descriptorIndex, sampler] = g_samplerStates[XXH3_64bits(&g_samplerDescs[0], sizeof(RenderSamplerDesc))]; descriptorIndex = 1; @@ -1960,7 +2047,7 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) pipelineLayoutBuilder.addDescriptorSet(descriptorSetBuilder); - if (g_vulkan) + if (g_backend != Backend::D3D12) { pipelineLayoutBuilder.addPushConstant(0, 4, 24, RenderShaderStageFlag::VERTEX | RenderShaderStageFlag::PIXEL); } @@ -1972,7 +2059,7 @@ bool Video::CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry) pipelineLayoutBuilder.addPushConstant(3, 4, 4, RenderShaderStageFlag::PIXEL); // For copy/resolve shaders. } pipelineLayoutBuilder.end(); - + g_pipelineLayout = pipelineLayoutBuilder.create(g_device.get()); g_copyShader = CREATE_SHADER(copy_vs); @@ -2073,6 +2160,7 @@ static uint32_t g_waitForGPUCount = 0; void Video::WaitForGPU() { + std::lock_guard lock(g_waitForGPUMutex); g_waitForGPUCount++; // Wait for all queued frames to finish. @@ -2086,10 +2174,10 @@ void Video::WaitForGPU() } // Execute an empty command list and wait for it to end to guarantee that any remaining presentation has finished. - g_commandLists[0]->begin(); - g_commandLists[0]->end(); - g_queue->executeCommandLists(g_commandLists[0].get(), g_commandFences[0].get()); - g_queue->waitForCommandFence(g_commandFences[0].get()); + g_waitForGPUCommandList->begin(); + g_waitForGPUCommandList->end(); + g_queue->executeCommandLists(g_waitForGPUCommandList.get(), g_waitForGPUCommandFence.get()); + g_queue->waitForCommandFence(g_waitForGPUCommandFence.get()); } static uint32_t CreateDevice(uint32_t a1, uint32_t a2, uint32_t a3, uint32_t a4, uint32_t a5, be* a6) @@ -2146,7 +2234,7 @@ static uint32_t CreateDevice(uint32_t a1, uint32_t a2, uint32_t a3, uint32_t a4, return 0; } -static void DestructResource(GuestResource* resource) +static void DestructResource(GuestResource* resource) { RenderCommand cmd; cmd.type = RenderCommandType::DestructResource; @@ -2165,7 +2253,7 @@ static uint32_t ComputeTexturePitch(GuestTexture* texture) return (texture->width * RenderFormatSize(texture->format) + PITCH_ALIGNMENT - 1) & ~(PITCH_ALIGNMENT - 1); } -static void LockTextureRect(GuestTexture* texture, uint32_t, GuestLockedRect* lockedRect) +static void LockTextureRect(GuestTexture* texture, uint32_t, GuestLockedRect* lockedRect) { uint32_t pitch = ComputeTexturePitch(texture); uint32_t slicePitch = pitch * texture->height; @@ -2177,7 +2265,7 @@ static void LockTextureRect(GuestTexture* texture, uint32_t, GuestLockedRect* lo lockedRect->bits = g_memory.MapVirtual(texture->mappedMemory); } -static void UnlockTextureRect(GuestTexture* texture) +static void UnlockTextureRect(GuestTexture* texture) { assert(std::this_thread::get_id() == g_presentThreadId); @@ -2304,17 +2392,17 @@ static void UnlockVertexBuffer(GuestBuffer* buffer) UnlockBuffer(buffer); } -static void GetVertexBufferDesc(GuestBuffer* buffer, GuestBufferDesc* desc) +static void GetVertexBufferDesc(GuestBuffer* buffer, GuestBufferDesc* desc) { desc->size = buffer->dataSize; } -static void* LockIndexBuffer(GuestBuffer* buffer, uint32_t, uint32_t, uint32_t flags) +static void* LockIndexBuffer(GuestBuffer* buffer, uint32_t, uint32_t, uint32_t flags) { return LockBuffer(buffer, flags); } -static void UnlockIndexBuffer(GuestBuffer* buffer) +static void UnlockIndexBuffer(GuestBuffer* buffer) { if (buffer->guestFormat == D3DFMT_INDEX32) UnlockBuffer(buffer); @@ -2328,19 +2416,19 @@ static void GetIndexBufferDesc(GuestBuffer* buffer, GuestBufferDesc* desc) desc->size = buffer->dataSize; } -static void GetSurfaceDesc(GuestSurface* surface, GuestSurfaceDesc* desc) +static void GetSurfaceDesc(GuestSurface* surface, GuestSurfaceDesc* desc) { desc->width = surface->width; desc->height = surface->height; } -static void GetVertexDeclaration(GuestVertexDeclaration* vertexDeclaration, GuestVertexElement* vertexElements, be* count) +static void GetVertexDeclaration(GuestVertexDeclaration* vertexDeclaration, GuestVertexElement* vertexElements, be* count) { memcpy(vertexElements, vertexDeclaration->vertexElements.get(), vertexDeclaration->vertexElementCount * sizeof(GuestVertexElement)); *count = vertexDeclaration->vertexElementCount; } -static uint32_t HashVertexDeclaration(uint32_t vertexDeclaration) +static uint32_t HashVertexDeclaration(uint32_t vertexDeclaration) { // Vertex declarations are cached on host side, so the pointer itself can be used. return vertexDeclaration; @@ -2348,7 +2436,7 @@ static uint32_t HashVertexDeclaration(uint32_t vertexDeclaration) static const char *DeviceTypeName(RenderDeviceType type) { - switch (type) + switch (type) { case RenderDeviceType::INTEGRATED: return "Integrated"; @@ -2459,12 +2547,27 @@ static void DrawProfiler() ImGui::Text("Present Wait: %s", g_capabilities.presentWait ? "Supported" : "Unsupported"); ImGui::Text("Triangle Fan: %s", g_capabilities.triangleFan ? "Supported" : "Unsupported"); ImGui::Text("Dynamic Depth Bias: %s", g_capabilities.dynamicDepthBias ? "Supported" : "Unsupported"); + ImGui::Text("Hardware Resolve Modes: %s", g_capabilities.resolveModes ? "Supported" : "Unsupported"); ImGui::Text("Triangle Strip Workaround: %s", g_triangleStripWorkaround ? "Enabled" : "Disabled"); - ImGui::Text("Hardware Resolve: %s", g_hardwareResolve ? "Enabled" : "Disabled"); - ImGui::Text("Hardware Depth Resolve: %s", g_hardwareDepthResolve ? "Enabled" : "Disabled"); ImGui::NewLine(); - ImGui::Text("API: %s", g_vulkan ? "Vulkan" : "D3D12"); + std::string backend; + + switch (g_backend) { + case Backend::VULKAN: + backend = "Vulkan"; + break; + case Backend::D3D12: + backend = "D3D12"; + break; + case Backend::METAL: + backend = "Metal"; + break; + default: + assert(false && "Unknown graphics backend"); + } + + ImGui::Text("API: %s", backend.c_str()); ImGui::Text("Device: %s", g_device->getDescription().name.c_str()); ImGui::Text("Device Type: %s", DeviceTypeName(g_device->getDescription().type)); ImGui::Text("VRAM: %.2f MiB", (double)(g_device->getDescription().dedicatedVideoMemory) / (1024.0 * 1024.0)); @@ -2544,7 +2647,7 @@ static void DrawImGui() io.DisplaySize = { float(Video::s_viewportWidth), float(Video::s_viewportHeight) }; // ImGui doesn't know that we center the screen for specific aspect ratio - // settings, which causes mouse events to not work correctly. To fix this, + // settings, which causes mouse events to not work correctly. To fix this, // we can adjust the mouse events before ImGui processes them. uint32_t width = g_swapChain->getWidth(); uint32_t height = g_swapChain->getHeight(); @@ -2600,6 +2703,10 @@ static void DrawImGui() Fader::Draw(); BlackBar::Draw(); +#ifdef UNLEASHED_RECOMP_IOS + TouchControls::Draw(float(width), float(height), mousePosOffsetX, mousePosOffsetY); +#endif + assert(ImGui::GetBackgroundDrawList()->_ClipRectStack.Size == 1 && "Some clip rects were not removed from the stack!"); DrawFPS(); @@ -2684,7 +2791,7 @@ static void ProcDrawImGui(const RenderCommand& cmd) { case ImGuiCallback::SetGradient: setPushConstants(&pushConstants.boundsMin, &callbackData->setGradient, sizeof(callbackData->setGradient)); - break; + break; case ImGuiCallback::SetShaderModifier: setPushConstants(&pushConstants.shaderModifier, &callbackData->setShaderModifier, sizeof(callbackData->setShaderModifier)); break; @@ -2693,7 +2800,7 @@ static void ProcDrawImGui(const RenderCommand& cmd) break; case ImGuiCallback::SetScale: setPushConstants(&pushConstants.scale, &callbackData->setScale, sizeof(callbackData->setScale)); - break; + break; case ImGuiCallback::SetMarqueeFade: setPushConstants(&pushConstants.boundsMin, &callbackData->setMarqueeFade, sizeof(callbackData->setMarqueeFade)); break; @@ -2770,6 +2877,28 @@ static void ProcDrawImGui(const RenderCommand& cmd) // 5. After the loading thread quits, application also presents. static bool g_pendingWaitOnSwapChain = true; +void Video::HandleApplicationBackgroundState(bool isBackgrounded) +{ + if (g_appSuspended.exchange(isBackgrounded, std::memory_order_acq_rel) != isBackgrounded) + LOGFN("Application {} the background.", isBackgrounded ? "entered" : "left"); +} + +// iOS doesn't allow GPU work in the background, so stop presenting new frames until the app is back. +static void WaitWhileApplicationSuspended() +{ + while (g_appSuspended.load(std::memory_order_acquire)) + { + if (std::this_thread::get_id() == g_eventThreadId) + { + SDL_PumpEvents(); + SDL_FlushEvents(SDL_FIRSTEVENT, SDL_LASTEVENT); + } + + std::this_thread::sleep_for(std::chrono::milliseconds(16)); + } +} + + void Video::WaitOnSwapChain() { if (g_pendingWaitOnSwapChain) @@ -2788,8 +2917,9 @@ void Video::WaitOnSwapChain() static bool g_shouldPrecompilePipelines; static std::atomic g_executedCommandList; -void Video::Present() +void Video::Present() { + WaitWhileApplicationSuspended(); g_readyForCommands = false; RenderCommand cmd; @@ -2888,14 +3018,14 @@ static void SetRootDescriptor(const UploadAllocation& allocation, size_t index) { auto& commandList = g_commandLists[g_frame]; - if (g_vulkan) + if (g_backend != Backend::D3D12) commandList->setGraphicsPushConstants(0, &allocation.deviceAddress, 8 * index, 8); else commandList->setGraphicsRootDescriptor(allocation.buffer->at(allocation.offset), index); } static void ProcExecuteCommandList(const RenderCommand& cmd) -{ +{ if (g_swapChainValid) { auto swapChainTexture = g_swapChain->getTexture(g_backBufferIndex); @@ -3006,7 +3136,7 @@ static void ProcBeginCommandList(const RenderCommand& cmd) BeginCommandList(); } -static GuestSurface* GetBackBuffer() +static GuestSurface* GetBackBuffer() { g_backBuffer->AddRef(); return g_backBuffer; @@ -3092,7 +3222,7 @@ static RenderFormat ConvertFormat(uint32_t format) } } -static GuestTexture* CreateTexture(uint32_t width, uint32_t height, uint32_t depth, uint32_t levels, uint32_t usage, uint32_t format, uint32_t pool, uint32_t type) +static GuestTexture* CreateTexture(uint32_t width, uint32_t height, uint32_t depth, uint32_t levels, uint32_t usage, uint32_t format, uint32_t pool, uint32_t type) { const auto texture = g_userHeap.AllocPhysical(type == 17 ? ResourceType::VolumeTexture : ResourceType::Texture); @@ -3144,8 +3274,8 @@ static GuestTexture* CreateTexture(uint32_t width, uint32_t height, uint32_t dep texture->descriptorIndex = g_textureDescriptorAllocator.allocate(); g_textureDescriptorSet->setTexture(texture->descriptorIndex, texture->texture, RenderTextureLayout::SHADER_READ, texture->textureView.get()); - -#ifdef _DEBUG + +#ifdef _DEBUG texture->texture->setName(fmt::format("Texture {:X}", g_memory.MapVirtual(texture))); #endif @@ -3157,12 +3287,12 @@ static RenderHeapType GetBufferHeapType() return g_capabilities.gpuUploadHeap ? RenderHeapType::GPU_UPLOAD : RenderHeapType::DEFAULT; } -static GuestBuffer* CreateVertexBuffer(uint32_t length) +static GuestBuffer* CreateVertexBuffer(uint32_t length) { auto buffer = g_userHeap.AllocPhysical(ResourceType::VertexBuffer); buffer->buffer = g_device->createBuffer(RenderBufferDesc::VertexBuffer(length, GetBufferHeapType(), RenderBufferFlag::INDEX)); buffer->dataSize = length; -#ifdef _DEBUG +#ifdef _DEBUG buffer->buffer->setName(fmt::format("Vertex Buffer {:X}", g_memory.MapVirtual(buffer))); #endif return buffer; @@ -3175,13 +3305,13 @@ static GuestBuffer* CreateIndexBuffer(uint32_t length, uint32_t, uint32_t format buffer->dataSize = length; buffer->format = ConvertFormat(format); buffer->guestFormat = format; -#ifdef _DEBUG +#ifdef _DEBUG buffer->buffer->setName(fmt::format("Index Buffer {:X}", g_memory.MapVirtual(buffer))); #endif return buffer; } -static GuestSurface* CreateSurface(uint32_t width, uint32_t height, uint32_t format, uint32_t multiSample) +static GuestSurface* CreateSurface(uint32_t width, uint32_t height, uint32_t format, uint32_t multiSample) { RenderTextureDesc desc; desc.dimension = RenderTextureDimension::TEXTURE_2D; @@ -3194,7 +3324,7 @@ static GuestSurface* CreateSurface(uint32_t width, uint32_t height, uint32_t for desc.format = ConvertFormat(format); desc.flags = desc.format == RenderFormat::D32_FLOAT ? RenderTextureFlag::DEPTH_TARGET : RenderTextureFlag::RENDER_TARGET; - auto surface = g_userHeap.AllocPhysical(desc.format == RenderFormat::D32_FLOAT ? + auto surface = g_userHeap.AllocPhysical(desc.format == RenderFormat::D32_FLOAT ? ResourceType::DepthStencil : ResourceType::RenderTarget); surface->textureHolder = g_device->createTexture(desc); @@ -3213,7 +3343,7 @@ static GuestSurface* CreateSurface(uint32_t width, uint32_t height, uint32_t for surface->descriptorIndex = g_textureDescriptorAllocator.allocate(); g_textureDescriptorSet->setTexture(surface->descriptorIndex, surface->textureHolder.get(), RenderTextureLayout::SHADER_READ, surface->textureView.get()); -#ifdef _DEBUG +#ifdef _DEBUG surface->texture->setName(fmt::format("{} {:X}", desc.flags & RenderTextureFlag::RENDER_TARGET ? "Render Target" : "Depth Stencil", g_memory.MapVirtual(surface))); #endif @@ -3321,7 +3451,7 @@ static void SetDefaultViewport(GuestDevice* device, GuestSurface* surface) } } -static void SetRenderTarget(GuestDevice* device, uint32_t index, GuestSurface* renderTarget) +static void SetRenderTarget(GuestDevice* device, uint32_t index, GuestSurface* renderTarget) { RenderCommand cmd; cmd.type = RenderCommandType::SetRenderTarget; @@ -3343,7 +3473,7 @@ static void ProcSetRenderTarget(const RenderCommand& cmd) SetAlphaTestMode((g_pipelineState.specConstants & (SPEC_CONSTANT_ALPHA_TEST | SPEC_CONSTANT_ALPHA_TO_COVERAGE)) != 0); } -static void SetDepthStencilSurface(GuestDevice* device, GuestSurface* depthStencil) +static void SetDepthStencilSurface(GuestDevice* device, GuestSurface* depthStencil) { RenderCommand cmd; cmd.type = RenderCommandType::SetDepthStencilSurface; @@ -3375,19 +3505,16 @@ static bool PopulateBarriersForStretchRect(GuestSurface* renderTarget, GuestSurf RenderTextureLayout dstLayout; bool shaderResolve = true; - if (multiSampling && g_hardwareResolve) + if (multiSampling) { - // Hardware depth resolve is only supported on D3D12 when programmable sample positions are available. - bool hardwareDepthResolveAvailable = g_hardwareDepthResolve && !g_vulkan && g_capabilities.sampleLocations; - - if (surface->format != RenderFormat::D32_FLOAT || hardwareDepthResolveAvailable) + if (surface->format != RenderFormat::D32_FLOAT || g_capabilities.resolveModes) { srcLayout = RenderTextureLayout::RESOLVE_SOURCE; dstLayout = RenderTextureLayout::RESOLVE_DEST; shaderResolve = false; } } - + if (shaderResolve) { srcLayout = RenderTextureLayout::SHADER_READ; @@ -3420,11 +3547,9 @@ static void ExecutePendingStretchRectCommands(GuestSurface* renderTarget, GuestS { bool shaderResolve = true; - if (multiSampling && g_hardwareResolve) + if (multiSampling) { - bool hardwareDepthResolveAvailable = g_hardwareDepthResolve && !g_vulkan && g_capabilities.sampleLocations; - - if (surface->format != RenderFormat::D32_FLOAT || hardwareDepthResolveAvailable) + if (surface->format != RenderFormat::D32_FLOAT || g_capabilities.resolveModes) { if (surface->format == RenderFormat::D32_FLOAT) commandList->resolveTextureRegion(texture->texture, 0, 0, surface->texture, nullptr, RenderResolveMode::MIN); @@ -3540,7 +3665,7 @@ static void ExecutePendingStretchRectCommands(GuestSurface* renderTarget, GuestS g_dirtyStates.pipelineState = true; g_dirtyStates.scissorRect = true; - if (g_vulkan) + if (g_backend != Backend::D3D12) { g_dirtyStates.vertexShaderConstants = true; // The push constant call invalidates vertex shader constants. g_dirtyStates.depthBias = true; // Static depth bias in copy pipeline invalidates dynamic depth bias. @@ -3660,7 +3785,7 @@ static void SetFramebuffer(GuestSurface* renderTarget, GuestSurface* depthStenci } } -static void Clear(GuestDevice* device, uint32_t flags, uint32_t, be* color, double z) +static void Clear(GuestDevice* device, uint32_t flags, uint32_t, be* color, double z) { RenderCommand cmd; cmd.type = RenderCommandType::Clear; @@ -3742,11 +3867,11 @@ static void ProcSetViewport(const RenderCommand& cmd) SetDirtyValue(g_dirtyStates.viewport, g_viewport.height, args.height); SetDirtyValue(g_dirtyStates.viewport, g_viewport.minDepth, args.minDepth); SetDirtyValue(g_dirtyStates.viewport, g_viewport.maxDepth, args.maxDepth); - + uint32_t specConstants = g_pipelineState.specConstants; if (args.minDepth > args.maxDepth) specConstants |= SPEC_CONSTANT_REVERSE_Z; - else + else specConstants &= ~SPEC_CONSTANT_REVERSE_Z; SetDirtyValue(g_dirtyStates.pipelineState, g_pipelineState.specConstants, specConstants); @@ -3754,7 +3879,7 @@ static void ProcSetViewport(const RenderCommand& cmd) g_dirtyStates.scissorRect |= g_dirtyStates.viewport; } -static void SetTexture(GuestDevice* device, uint32_t index, GuestTexture* texture) +static void SetTexture(GuestDevice* device, uint32_t index, GuestTexture* texture) { auto isPlayStation = Config::ControllerIcons == EControllerIcons::PlayStation; @@ -3823,10 +3948,10 @@ static void ProcSetTexture(const RenderCommand& cmd) shouldSetTexture = false; } } - + if (shouldSetTexture) SetTextureInRenderThread(args.index, args.texture); - + g_textures[args.index] = args.texture; } @@ -3853,8 +3978,8 @@ static void ProcSetScissorRect(const RenderCommand& cmd) static RenderShader* GetOrLinkShader(GuestShader* guestShader, uint32_t specConstants) { - if (g_vulkan || - guestShader->shaderCacheEntry == nullptr || + if (g_backend != Backend::D3D12 || + guestShader->shaderCacheEntry == nullptr || guestShader->shaderCacheEntry->specConstantsMask == 0) { std::lock_guard lock(guestShader->mutex); @@ -3863,7 +3988,8 @@ static RenderShader* GetOrLinkShader(GuestShader* guestShader, uint32_t specCons { assert(guestShader->shaderCacheEntry != nullptr); - if (g_vulkan) + switch (g_backend) { + case Backend::VULKAN: { auto compressedSpirvData = g_shaderCache.get() + guestShader->shaderCacheEntry->spirvOffset; @@ -3871,13 +3997,24 @@ static RenderShader* GetOrLinkShader(GuestShader* guestShader, uint32_t specCons bool result = smolv::Decode(compressedSpirvData, guestShader->shaderCacheEntry->spirvSize, decoded.data(), decoded.size()); assert(result); - guestShader->shader = g_device->createShader(decoded.data(), decoded.size(), "main", RenderShaderFormat::SPIRV); + guestShader->shader = g_device->createShader(decoded.data(), decoded.size(), "shaderMain", RenderShaderFormat::SPIRV); + break; } - else + case Backend::D3D12: { - guestShader->shader = g_device->createShader(g_shaderCache.get() + guestShader->shaderCacheEntry->dxilOffset, - guestShader->shaderCacheEntry->dxilSize, "main", RenderShaderFormat::DXIL); + guestShader->shader = g_device->createShader(g_shaderCache.get() + guestShader->shaderCacheEntry->dxilOffset, + guestShader->shaderCacheEntry->dxilSize, "shaderMain", RenderShaderFormat::DXIL); + break; } + case Backend::METAL: + { + guestShader->shader = g_device->createShader(g_shaderCache.get() + guestShader->shaderCacheEntry->airOffset, + guestShader->shaderCacheEntry->airSize, "shaderMain", RenderShaderFormat::METAL); + break; + } + } + + guestShader->shader->setName(fmt::format("{}:{:x}", guestShader->shaderCacheEntry->filename, guestShader->shaderCacheEntry->hash)); } return guestShader->shader.get(); @@ -3981,7 +4118,7 @@ static RenderShader* GetOrLinkShader(GuestShader* guestShader, uint32_t specCons const wchar_t* libraryNames[] = { specConstantsLibName, shaderLibName }; ComPtr result; - HRESULT hr = s_dxcLinker->Link(L"main", guestShader->type == ResourceType::VertexShader ? L"vs_6_0" : L"ps_6_0", + HRESULT hr = s_dxcLinker->Link(L"shaderMain", guestShader->type == ResourceType::VertexShader ? L"vs_6_0" : L"ps_6_0", libraryNames, std::size(libraryNames), nullptr, 0, result.GetAddressOf()); assert(SUCCEEDED(hr) && result != nullptr); @@ -3996,12 +4133,16 @@ static RenderShader* GetOrLinkShader(GuestShader* guestShader, uint32_t specCons auto& linkedShader = guestShader->linkedShaders[specConstants]; if (linkedShader == nullptr) { - linkedShader = g_device->createShader(blob->GetBufferPointer(), blob->GetBufferSize(), "main", RenderShaderFormat::DXIL); + linkedShader = g_device->createShader(blob->GetBufferPointer(), blob->GetBufferSize(), "shaderMain", RenderShaderFormat::DXIL); guestShader->shaderBlobs.push_back(std::move(blob)); } shader = linkedShader.get(); - } + +#ifdef _DEBUG + shader->setName(fmt::format("{}:{:x}", guestShader->shaderCacheEntry->filename, guestShader->shaderCacheEntry->hash)); +#endif + } } #endif @@ -4088,43 +4229,86 @@ static std::unique_ptr CreateGraphicsPipeline(const PipelineStat desc.alphaToCoverageEnabled = pipelineState.enableAlphaToCoverage; desc.inputElements = pipelineState.vertexDeclaration->inputElements.get(); desc.inputElementsCount = pipelineState.vertexDeclaration->inputElementCount; - + RenderSpecConstant specConstant{}; specConstant.value = pipelineState.specConstants; - + if (pipelineState.specConstants != 0) { desc.specConstants = &specConstant; desc.specConstantsCount = 1; } - + RenderInputSlot inputSlots[16]{}; uint32_t inputSlotIndices[16]{}; uint32_t inputSlotCount = 0; - + for (size_t i = 0; i < pipelineState.vertexDeclaration->inputElementCount; i++) { auto& inputElement = pipelineState.vertexDeclaration->inputElements[i]; auto& inputSlotIndex = inputSlotIndices[inputElement.slotIndex]; - + if (inputSlotIndex == NULL) inputSlotIndex = ++inputSlotCount; - + auto& inputSlot = inputSlots[inputSlotIndex - 1]; inputSlot.index = inputElement.slotIndex; inputSlot.stride = pipelineState.vertexStrides[inputElement.slotIndex]; - + if (pipelineState.instancing && inputElement.slotIndex != 0 && inputElement.slotIndex != 15) inputSlot.classification = RenderInputSlotClassification::PER_INSTANCE_DATA; else inputSlot.classification = RenderInputSlotClassification::PER_VERTEX_DATA; } - + desc.inputSlots = inputSlots; desc.inputSlotsCount = inputSlotCount; - + auto pipeline = g_device->createGraphicsPipeline(desc); + // MoltenVK requires the Metal vertex attribute type to agree with the + // SPIR-V input type. D3D12 accepts several conversions that MoltenVK does + // not, so emit the complete declaration once for each failed Vulkan PSO. + if (pipeline == nullptr && g_backend == Backend::VULKAN) + { + static Mutex failureLogMutex; + static ankerl::unordered_dense::set loggedFailures; + const XXH64_hash_t pipelineHash = XXH3_64bits(&pipelineState, sizeof(pipelineState)); + + std::lock_guard lock(failureLogMutex); + if (loggedFailures.emplace(pipelineHash).second) + { + const GuestVertexDeclaration* declaration = pipelineState.vertexDeclaration; + LOGFN_ERROR( + "VK-PIPELINE-FAIL hash=0x{:016X} vs={} ps={} declaration=0x{:08X} inputs={} streams={} spec=0x{:08X}", + pipelineHash, static_cast(pipelineState.vertexShader), + static_cast(pipelineState.pixelShader), + g_memory.MapVirtual(declaration), declaration->inputElementCount, + declaration->vertexElementCount, pipelineState.specConstants); + + for (uint32_t i = 0; i < declaration->inputElementCount; ++i) + { + const RenderInputElement& element = declaration->inputElements[i]; + LOGFN_ERROR( + "VK-PIPELINE-FAIL input[{}] semantic={}:{} location={} format={} slot={} offset={}", + i, element.semanticName, element.semanticIndex, element.location, + static_cast(element.format), element.slotIndex, element.alignedByteOffset); + } + + for (uint32_t i = 0; i < declaration->vertexElementCount; ++i) + { + const GuestVertexElement& element = declaration->vertexElements[i]; + if (element.stream == 0xFF || element.type == D3DDECLTYPE_UNUSED) + break; + + LOGFN_ERROR( + "VK-PIPELINE-FAIL guestInput[{}] usage={}:{} type=0x{:08X} stream={} offset={}", + i, element.usage, element.usageIndex, static_cast(element.type), + static_cast(element.stream), static_cast(element.offset)); + } + } + } + #ifdef ASYNC_PSO_DEBUG --g_pipelinesCurrentlyCompiling; #endif @@ -4152,7 +4336,7 @@ static RenderPipeline* CreateGraphicsPipelineInRenderThread(PipelineState pipeli pipeline->setName(fmt::format("{} {} {} {:X}", loading ? "ASYNC" : "", pipelineState.vertexShader->name, pipelineState.pixelShader != nullptr ? pipelineState.pixelShader->name : "", hash)); - + if (!loading) { std::lock_guard lock(g_debugMutex); @@ -4224,7 +4408,7 @@ static RenderPipeline* CreateGraphicsPipelineInRenderThread(PipelineState pipeli g_pipelineStatesToCache.emplace(hash, pipelineState); #endif } - + return pipeline.get(); } @@ -4494,7 +4678,7 @@ static void FlushRenderStateForRenderThread() // D3D12 resets depth bias values to the pipeline values, even if they are dynamic. // We can reduce unnecessary calls by making common depth bias values part of the pipeline. - if (g_capabilities.dynamicDepthBias && !g_vulkan) + if (g_capabilities.dynamicDepthBias && g_backend == Backend::D3D12) { bool useDepthBias = (g_depthBias != 0) || (g_slopeScaledDepthBias != 0.0f); @@ -4510,7 +4694,7 @@ static void FlushRenderStateForRenderThread() commandList->setPipeline(CreateGraphicsPipelineInRenderThread(g_pipelineState)); // D3D12 resets the depth bias values. Check if they need to be set again. - if (g_capabilities.dynamicDepthBias && !g_vulkan) + if (g_capabilities.dynamicDepthBias && g_backend == Backend::D3D12) g_dirtyStates.depthBias = (g_depthBias != g_pipelineState.depthBias) || (g_slopeScaledDepthBias != g_pipelineState.slopeScaledDepthBias); } @@ -4544,7 +4728,7 @@ static void FlushRenderStateForRenderThread() g_inputSlots + g_dirtyStates.vertexStreamFirst); } - if (g_dirtyStates.indices && (!g_vulkan || g_indexBufferView.buffer.ref != nullptr)) + if (g_dirtyStates.indices && (g_backend == Backend::D3D12 || g_indexBufferView.buffer.ref != nullptr)) commandList->setIndexBuffer(&g_indexBufferView); g_dirtyStates = DirtyStates(false); @@ -4608,7 +4792,7 @@ static void UnsetInstancingStream() } } -static void DrawPrimitive(GuestDevice* device, uint32_t primitiveType, uint32_t startVertex, uint32_t primitiveCount) +static void DrawPrimitive(GuestDevice* device, uint32_t primitiveType, uint32_t startVertex, uint32_t primitiveCount) { LocalRenderCommandQueue queue; FlushRenderStateForMainThread(device, queue); @@ -4692,7 +4876,7 @@ static void DrawPrimitiveUP(GuestDevice* device, uint32_t primitiveType, uint32_ cmd.drawPrimitiveUP.vertexStreamZeroSize = primitiveCount * vertexStreamZeroStride; cmd.drawPrimitiveUP.vertexStreamZeroStride = vertexStreamZeroStride; cmd.drawPrimitiveUP.csdFilterState = g_csdFilterState; - + queue.submit(); } @@ -4822,7 +5006,7 @@ static RenderFormat ConvertDeclType(uint32_t type) } } -static GuestVertexDeclaration* CreateVertexDeclarationWithoutAddRef(GuestVertexElement* vertexElements) +static GuestVertexDeclaration* CreateVertexDeclarationWithoutAddRef(GuestVertexElement* vertexElements) { size_t vertexElementCount = 0; auto vertexElement = vertexElements; @@ -4834,7 +5018,7 @@ static GuestVertexDeclaration* CreateVertexDeclarationWithoutAddRef(GuestVertexE ++vertexElementCount; } - vertexElement->padding = 0; // Clear the padding in D3DDECL_END() + vertexElement->padding = 0; // Clear the padding in D3DDECL_END() std::lock_guard lock(g_vertexDeclarationMutex); @@ -4887,7 +5071,7 @@ static GuestVertexDeclaration* CreateVertexDeclarationWithoutAddRef(GuestVertexE } auto& inputElement = inputElements.emplace_back(); - + inputElement.semanticName = ConvertDeclUsage(vertexElement->usage); inputElement.semanticIndex = vertexElement->usageIndex; inputElement.location = ~0; @@ -5014,7 +5198,7 @@ static GuestVertexDeclaration* CreateVertexDeclaration(GuestVertexElement* verte return vertexDeclaration; } -static void SetVertexDeclaration(GuestDevice* device, GuestVertexDeclaration* vertexDeclaration) +static void SetVertexDeclaration(GuestDevice* device, GuestVertexDeclaration* vertexDeclaration) { RenderCommand cmd; cmd.type = RenderCommandType::SetVertexDeclaration; @@ -5095,7 +5279,7 @@ static GuestShader* CreateShader(const be* function, ResourceType reso return shader; } -static GuestShader* CreateVertexShader(const be* function) +static GuestShader* CreateVertexShader(const be* function) { return CreateShader(function, ResourceType::VertexShader); } @@ -5113,7 +5297,7 @@ static void ProcSetVertexShader(const RenderCommand& cmd) SetDirtyValue(g_dirtyStates.pipelineState, g_pipelineState.vertexShader, cmd.setVertexShader.shader); } -static void SetStreamSource(GuestDevice* device, uint32_t index, GuestBuffer* buffer, uint32_t offset, uint32_t stride) +static void SetStreamSource(GuestDevice* device, uint32_t index, GuestBuffer* buffer, uint32_t offset, uint32_t stride) { RenderCommand cmd; cmd.type = RenderCommandType::SetStreamSource; @@ -5143,7 +5327,7 @@ static void ProcSetStreamSource(const RenderCommand& cmd) } } -static void SetIndices(GuestDevice* device, GuestBuffer* buffer) +static void SetIndices(GuestDevice* device, GuestBuffer* buffer) { RenderCommand cmd; cmd.type = RenderCommandType::SetIndices; @@ -5176,7 +5360,7 @@ static void SetPixelShader(GuestDevice* device, GuestShader* shader) static void ProcSetPixelShader(const RenderCommand& cmd) { GuestShader* shader = cmd.setPixelShader.shader; - if (shader != nullptr && + if (shader != nullptr && shader->shaderCacheEntry != nullptr) { if (shader->shaderCacheEntry->hash == 0x4294510C775F4EE8) @@ -5430,7 +5614,7 @@ struct GuestPictureData static RenderTextureDimension ConvertTextureDimension(ddspp::TextureType type) { - switch (type) + switch (type) { case ddspp::Texture1D: return RenderTextureDimension::TEXTURE_1D; @@ -5463,7 +5647,7 @@ static RenderTextureViewDimension ConvertTextureViewDimension(ddspp::TextureType } } -static RenderFormat ConvertDXGIFormat(ddspp::DXGIFormat format) +static RenderFormat ConvertDXGIFormat(ddspp::DXGIFormat format) { switch (format) { @@ -5516,7 +5700,7 @@ static RenderFormat ConvertDXGIFormat(ddspp::DXGIFormat format) case ddspp::B8G8R8A8_UNORM: return RenderFormat::B8G8R8A8_UNORM; case ddspp::B8G8R8X8_UNORM: - return RenderFormat::B8G8R8A8_UNORM; + return RenderFormat::B8G8R8A8_UNORM; case ddspp::R16G16_TYPELESS: return RenderFormat::R16G16_TYPELESS; case ddspp::R16G16_FLOAT: @@ -5628,7 +5812,7 @@ static bool LoadTexture(GuestTexture& texture, const uint8_t* data, size_t dataS { forceCubeMap &= (ddsDesc.type == ddspp::Texture2D) && (ddsDesc.arraySize == 1); uint32_t arraySize = ddsDesc.type == ddspp::TextureType::Cubemap ? (ddsDesc.arraySize * 6) : ddsDesc.arraySize; - + RenderTextureDesc desc; desc.dimension = ConvertTextureDimension(ddsDesc.type); desc.width = ddsDesc.width; @@ -5827,7 +6011,7 @@ static void DiffPatchTexture(GuestTexture& texture, uint8_t* data, uint32_t data auto header = reinterpret_cast(g_buttonBcDiff.get()); auto entries = reinterpret_cast(g_buttonBcDiff.get() + header->entriesOffset); auto end = entries + header->entryCount; - + auto findResult = std::lower_bound(entries, end, hash, [](BlockCompressionDiffPatchEntry& lhs, XXH64_hash_t rhs) { return lhs.hash < rhs; @@ -5903,7 +6087,7 @@ static void SetResolution(be* device) device[47] = height == 0 ? 720 : height; } -// The game does some weird stuff to render targets if they are above +// The game does some weird stuff to render targets if they are above // 1024x1024 resolution, setting this bool at address 20 seems to avoid all that. PPC_FUNC(sub_82E9F048) { @@ -5974,7 +6158,7 @@ PPC_FUNC(sub_8258CAE0) { if (g_needsResize) { - // Backup job values. These get modified by cutscenes, + // Backup job values. These get modified by cutscenes, // and resizing will cause the values to be forgotten. auto traverseFxJobs = [&](const TCallback& callback) { @@ -6017,7 +6201,7 @@ PPC_FUNC(sub_8258CAE0) if (vfTable == 0x820CA6F8) // SWA::CFxFade { - // NOTE: Intentionally not storing shared pointers here. + // NOTE: Intentionally not storing shared pointers here. // Game sends messages that assign these every frame already. JobValues jobValues{}; @@ -6200,7 +6384,7 @@ enum eDatabaseDataFlags_CompilingPipelines = 0x80 }; -// This is passed to pipeline compilation threads to keep the loading screen busy until +// This is passed to pipeline compilation threads to keep the loading screen busy until // all of them are finished. A shared pointer makes sure the destructor is called only once. struct PipelineTaskToken { @@ -6335,8 +6519,8 @@ struct PipelineTaskTokenPair static xxHashMap g_asyncPipelineStates; static void EnqueueGraphicsPipelineCompilation( - const PipelineState& pipelineState, - PipelineTaskTokenPair& tokenPair, + const PipelineState& pipelineState, + PipelineTaskTokenPair& tokenPair, const char* name, bool isPrecompiledPipeline = false) { @@ -6475,17 +6659,17 @@ static void CompileMeshPipeline(const Mesh& mesh, CompilationArgs& args) pipelineState.vertexDeclaration = mesh.vertexDeclaration; pipelineState.cullMode = mesh.material->m_DoubleSided ? RenderCullMode::NONE : RenderCullMode::BACK; pipelineState.zFunc = RenderComparisonFunction::LESS_EQUAL; - + if (g_capabilities.dynamicDepthBias) { // Put common depth bias values for reducing unnecessary calls. - if (!g_vulkan) + if (g_backend == Backend::D3D12) { pipelineState.depthBias = COMMON_DEPTH_BIAS_VALUE; pipelineState.slopeScaledDepthBias = COMMON_SLOPE_SCALED_DEPTH_BIAS_VALUE; } } - else + else { pipelineState.depthBias = (1 << 24) * (*reinterpret_cast*>(g_memory.Translate(0x83302760))); pipelineState.slopeScaledDepthBias = *reinterpret_cast*>(g_memory.Translate(0x83302764)); @@ -6701,7 +6885,7 @@ static void CompileMeshPipeline(const Mesh& mesh, CompilationArgs& args) createGraphicsPipeline(noMsaaPipeline); } - if (args.objectIcon) + if (args.objectIcon) { // Object icons get rendered to a SDR buffer without MSAA. auto iconPipelineState = noMsaaPipeline; @@ -6826,7 +7010,7 @@ static void CompileParticleMaterialPipeline(const Hedgehog::Sparkle::CParticleMa return; // All the particle models in the game come with the unoptimized format, so we can assume it. - uint8_t unoptimizedVertexElements[144] = + uint8_t unoptimizedVertexElements[144] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x2A, 0x23, 0xB9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x2A, 0x23, 0xB9, 0x00, 0x03, 0x00, 0x00, @@ -6964,7 +7148,7 @@ PPC_FUNC(sub_825369A0) // CModelData::CheckMadeAll PPC_FUNC_IMPL(__imp__sub_82E2EFB0); PPC_FUNC(sub_82E2EFB0) -{ +{ if (reinterpret_cast(base + ctx.r3.u32)->m_Flags & eDatabaseDataFlags_CompilingPipelines) { ctx.r3.u64 = 0; @@ -6978,7 +7162,7 @@ PPC_FUNC(sub_82E2EFB0) // CTerrainModelData::CheckMadeAll PPC_FUNC_IMPL(__imp__sub_82E243D8); PPC_FUNC(sub_82E243D8) -{ +{ if (reinterpret_cast(base + ctx.r3.u32)->m_Flags & eDatabaseDataFlags_CompilingPipelines) { ctx.r3.u64 = 0; @@ -6992,7 +7176,7 @@ PPC_FUNC(sub_82E243D8) // CParticleMaterial::CheckMadeAll PPC_FUNC_IMPL(__imp__sub_82E87598); PPC_FUNC(sub_82E87598) -{ +{ if (reinterpret_cast(base + ctx.r3.u32)->m_Flags & eDatabaseDataFlags_CompilingPipelines) { ctx.r3.u64 = 0; @@ -7071,13 +7255,13 @@ static bool CheckMadeAll(const T& modelData) { if (!CheckMadeAll(mesh.get())) return false; - } + } for (auto& mesh : meshGroup->m_TransparentMeshes) { if (!CheckMadeAll(mesh.get())) return false; - } + } for (auto& mesh : meshGroup->m_PunchThroughMeshes) { @@ -7240,8 +7424,8 @@ static void PipelineTaskConsumerThread() if (!g_capabilities.triangleFan && pipelineState.primitiveTopology == RenderPrimitiveTopology::TRIANGLE_FAN) pipelineState.primitiveTopology = RenderPrimitiveTopology::TRIANGLE_LIST; - // Zero out depth bias for Vulkan, we only store common values for D3D12. - if (g_capabilities.dynamicDepthBias && g_vulkan) + // Zero out depth bias for Vulkan/Metal, we only store common values for D3D12. + if (g_capabilities.dynamicDepthBias && g_backend != Backend::D3D12) { pipelineState.depthBias = 0; pipelineState.slopeScaledDepthBias = 0.0f; @@ -7258,7 +7442,7 @@ static void PipelineTaskConsumerThread() // Compile both MSAA and non MSAA variants to work with reflection maps. The render formats are an assumption but it should hold true. if (Config::AntiAliasing != EAntiAliasing::None && - pipelineState.renderTargetFormat == RenderFormat::R16G16B16A16_FLOAT && + pipelineState.renderTargetFormat == RenderFormat::R16G16B16A16_FLOAT && pipelineState.depthStencilFormat == RenderFormat::D32_FLOAT) { auto msaaPipelineState = pipelineState; @@ -7297,7 +7481,7 @@ static void PipelineTaskConsumerThread() createGraphicsPipeline(newPipelineState, "Precompiled Enhanced Motion Blur Pipeline"); } } - + createGraphicsPipeline(pipelineState, "Precompiled Pipeline"); // Compile the CSD filter shader that we pass to the game when point filtering is used. @@ -7400,7 +7584,7 @@ PPC_FUNC(sub_82E328D8) class SDLEventListenerForPSOCaching : public SDLEventListener { public: - bool OnSDLEvent(SDL_Event* event) override + bool OnSDLEvent(SDL_Event* event) override { if (event->type != SDL_QUIT) return false; @@ -7540,7 +7724,7 @@ void VideoConfigValueChangedCallback(IConfigDef* config) if (g_needsResize) Video::ComputeViewportDimensions(); - + // Config options that require pipeline recompilation bool shouldRecompile = config == &Config::AntiAliasing || @@ -7636,7 +7820,7 @@ static void ConvertToDegenerateTriangles(uint16_t* indices, uint32_t indexCount, stripStart = true; stripSize = 0; } - else + else { if (stripStart && newIndexCount != 0) { @@ -7691,7 +7875,7 @@ PPC_FUNC(sub_82E44AF8) // If index buffers are getting merged, new indices need to survive until the merge happens. g_newIndicesToFree.push_back(newIndices); } - else + else { // Otherwise, we can free it immediately. newIndicesToFree = newIndices; diff --git a/UnleashedRecomp/gpu/video.h b/UnleashedRecomp/gpu/video.h index 6c24d301..80a0b213 100644 --- a/UnleashedRecomp/gpu/video.h +++ b/UnleashedRecomp/gpu/video.h @@ -20,12 +20,19 @@ struct Video static bool CreateHostDevice(const char *sdlVideoDriver, bool graphicsApiRetry); static void WaitOnSwapChain(); + static void HandleApplicationBackgroundState(bool isBackgrounded); static void Present(); static void StartPipelinePrecompilation(); static void WaitForGPU(); static void ComputeViewportDimensions(); }; +enum class Backend { + VULKAN, + D3D12, + METAL +}; + struct GuestSamplerState { be data[6]; diff --git a/UnleashedRecomp/hid/driver/sdl_hid.cpp b/UnleashedRecomp/hid/driver/sdl_hid.cpp index 76235524..60bb31f5 100644 --- a/UnleashedRecomp/hid/driver/sdl_hid.cpp +++ b/UnleashedRecomp/hid/driver/sdl_hid.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -264,6 +265,7 @@ int HID_OnSDLEvent(void*, SDL_Event* event) { SDL_ShowCursor(SDL_DISABLE); SetControllerInputDevice(controller); + TouchControls::OnPhysicalControllerInput(); } controller->PollAxis(); @@ -272,6 +274,7 @@ int HID_OnSDLEvent(void*, SDL_Event* event) { SDL_ShowCursor(SDL_DISABLE); SetControllerInputDevice(controller); + TouchControls::OnPhysicalControllerInput(); controller->Poll(); } @@ -282,17 +285,22 @@ int HID_OnSDLEvent(void*, SDL_Event* event) case SDL_KEYDOWN: case SDL_KEYUP: hid::g_inputDevice = hid::EInputDevice::Keyboard; + TouchControls::OnPhysicalControllerInput(); break; case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { + // Mouse events synthesised from touches shouldn't switch the button prompts to keyboard and mouse. + if (event->motion.which == SDL_TOUCH_MOUSEID) + break; + if (!GameWindow::IsFullscreen() || GameWindow::s_isFullscreenCursorVisible) SDL_ShowCursor(SDL_ENABLE); hid::g_inputDevice = hid::EInputDevice::Mouse; - + TouchControls::OnPhysicalControllerInput(); break; } @@ -332,7 +340,7 @@ void hid::Init() SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_WII, "1"); SDL_SetHint(SDL_HINT_XINPUT_ENABLED, "1"); - + SDL_SetHint(SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS, "0"); // Uses Button Labels. This hint is disabled for Nintendo Controllers. SDL_InitSubSystem(SDL_INIT_EVENTS); @@ -352,10 +360,13 @@ uint32_t hid::GetState(uint32_t dwUserIndex, XAMINPUT_STATE* pState) pState->dwPacketNumber = packet++; - if (!g_activeController) + if (!g_activeController && !TouchControls::IsActive()) return ERROR_DEVICE_NOT_CONNECTED; - pState->Gamepad = g_activeController->state; + if (g_activeController) + pState->Gamepad = g_activeController->state; + + TouchControls::Apply(pState->Gamepad); return ERROR_SUCCESS; } @@ -366,7 +377,7 @@ uint32_t hid::SetState(uint32_t dwUserIndex, XAMINPUT_VIBRATION* pVibration) return ERROR_BAD_ARGUMENTS; if (!g_activeController) - return ERROR_DEVICE_NOT_CONNECTED; + return TouchControls::IsActive() ? ERROR_SUCCESS : ERROR_DEVICE_NOT_CONNECTED; g_activeController->SetVibration(*pVibration); @@ -378,16 +389,20 @@ uint32_t hid::GetCapabilities(uint32_t dwUserIndex, XAMINPUT_CAPABILITIES* pCaps if (!pCaps) return ERROR_BAD_ARGUMENTS; - if (!g_activeController) + if (!g_activeController && !TouchControls::IsActive()) return ERROR_DEVICE_NOT_CONNECTED; memset(pCaps, 0, sizeof(*pCaps)); pCaps->Type = XAMINPUT_DEVTYPE_GAMEPAD; - pCaps->SubType = XAMINPUT_DEVSUBTYPE_GAMEPAD; // TODO: other types? + pCaps->SubType = XAMINPUT_DEVSUBTYPE_GAMEPAD; pCaps->Flags = 0; - pCaps->Gamepad = g_activeController->state; - pCaps->Vibration = g_activeController->vibration; + + if (g_activeController) + { + pCaps->Gamepad = g_activeController->state; + pCaps->Vibration = g_activeController->vibration; + } return ERROR_SUCCESS; } diff --git a/UnleashedRecomp/install/update_checker.cpp b/UnleashedRecomp/install/update_checker.cpp index 2a6f5b1f..6d9a6177 100644 --- a/UnleashedRecomp/install/update_checker.cpp +++ b/UnleashedRecomp/install/update_checker.cpp @@ -9,6 +9,10 @@ #include #endif +#if defined(__APPLE__) +#include "../apple_utils.h" +#endif + #include // UpdateChecker @@ -167,8 +171,7 @@ void UpdateChecker::visitWebsite() std::string command = "xdg-open " + std::string(VISIT_URL) + " &"; std::system(command.c_str()); #elif defined(__APPLE__) - std::string command = "open " + std::string(VISIT_URL) + " &"; - std::system(command.c_str()); + apple::OpenBrowser(VISIT_URL); #else static_assert(false, "Visit website not implemented for this platform."); #endif diff --git a/UnleashedRecomp/kernel/imports.cpp b/UnleashedRecomp/kernel/imports.cpp index 58b33fab..a6e9bb04 100644 --- a/UnleashedRecomp/kernel/imports.cpp +++ b/UnleashedRecomp/kernel/imports.cpp @@ -1,3 +1,7 @@ +#include +#include +#include +#include #include #include #include @@ -10,6 +14,7 @@ #include #include "xam.h" #include "xdm.h" +#include #include #include @@ -21,6 +26,10 @@ struct Event final : KernelObject, HostObject { bool manualReset; std::atomic signaled; +#if defined(UNLEASHED_RECOMP_IOS) + std::mutex waitMutex; + std::condition_variable waitCondition; +#endif Event(XKEVENT* header) : manualReset(!header->Type), signaled(!!header->SignalState) @@ -50,6 +59,25 @@ struct Event final : KernelObject, HostObject } else if (timeout == INFINITE) { +#if defined(UNLEASHED_RECOMP_IOS) + std::unique_lock lock(waitMutex); + if (manualReset) + { + waitCondition.wait(lock, [&] + { + return signaled.load(std::memory_order_acquire); + }); + } + else + { + waitCondition.wait(lock, [&] + { + bool expected = true; + return signaled.compare_exchange_strong( + expected, false, std::memory_order_acquire, std::memory_order_relaxed); + }); + } +#else if (manualReset) { signaled.wait(false); @@ -65,6 +93,7 @@ struct Event final : KernelObject, HostObject signaled.wait(expected); } } +#endif } else { @@ -76,29 +105,79 @@ struct Event final : KernelObject, HostObject bool Set() { - signaled = true; +#if defined(UNLEASHED_RECOMP_IOS) + bool previousState; + { + std::lock_guard lock(waitMutex); + previousState = signaled.exchange(true, std::memory_order_release); + } + + if (manualReset) + waitCondition.notify_all(); + else + waitCondition.notify_one(); +#else + const bool previousState = signaled.exchange(true, std::memory_order_release); if (manualReset) signaled.notify_all(); else signaled.notify_one(); +#endif - return TRUE; + return previousState; } bool Reset() { - signaled = false; - return TRUE; +#if defined(UNLEASHED_RECOMP_IOS) + std::lock_guard lock(waitMutex); +#endif + return signaled.exchange(false, std::memory_order_acq_rel); } }; static std::atomic g_keSetEventGeneration; +#if defined(UNLEASHED_RECOMP_IOS) +static std::mutex g_multipleEventWaitMutex; +static std::condition_variable g_multipleEventWaitCondition; +#endif + +static void NotifyMultipleEventWaiters() +{ + g_keSetEventGeneration.fetch_add(1, std::memory_order_release); +#if defined(UNLEASHED_RECOMP_IOS) + { + // Synchronize with the predicate check performed by condition_variable::wait. + std::lock_guard lock(g_multipleEventWaitMutex); + } + g_multipleEventWaitCondition.notify_all(); +#else + g_keSetEventGeneration.notify_all(); +#endif +} + +static void WaitForMultipleEventGenerationChange(uint32_t generation) +{ +#if defined(UNLEASHED_RECOMP_IOS) + std::unique_lock lock(g_multipleEventWaitMutex); + g_multipleEventWaitCondition.wait(lock, [&] + { + return g_keSetEventGeneration.load(std::memory_order_acquire) != generation; + }); +#else + g_keSetEventGeneration.wait(generation, std::memory_order_relaxed); +#endif +} struct Semaphore final : KernelObject, HostObject { std::atomic count; uint32_t maximumCount; +#if defined(UNLEASHED_RECOMP_IOS) + std::mutex waitMutex; + std::condition_variable waitCondition; +#endif Semaphore(XKSEMAPHORE* semaphore) : count(semaphore->Header.SignalState), maximumCount(semaphore->Limit) @@ -115,7 +194,7 @@ struct Semaphore final : KernelObject, HostObject if (timeout == 0) { uint32_t currentCount = count.load(); - if (currentCount != 0) + while (currentCount != 0) { if (count.compare_exchange_weak(currentCount, currentCount - 1)) return STATUS_SUCCESS; @@ -125,6 +204,9 @@ struct Semaphore final : KernelObject, HostObject } else if (timeout == INFINITE) { +#if defined(UNLEASHED_RECOMP_IOS) + std::unique_lock lock(waitMutex); +#endif uint32_t currentCount; while (true) { @@ -136,7 +218,14 @@ struct Semaphore final : KernelObject, HostObject } else { +#if defined(UNLEASHED_RECOMP_IOS) + waitCondition.wait(lock, [&] + { + return count.load(std::memory_order_relaxed) != 0; + }); +#else count.wait(0); +#endif } } @@ -151,13 +240,30 @@ struct Semaphore final : KernelObject, HostObject void Release(uint32_t releaseCount, uint32_t* previousCount) { - if (previousCount != nullptr) - *previousCount = count; +#if defined(UNLEASHED_RECOMP_IOS) + std::lock_guard lock(waitMutex); +#endif + uint32_t currentCount = count.load(std::memory_order_relaxed); + while (true) + { + assert(currentCount <= maximumCount && releaseCount <= maximumCount - currentCount); + if (releaseCount > maximumCount - currentCount) + return; + + if (count.compare_exchange_weak( + currentCount, currentCount + releaseCount, + std::memory_order_release, std::memory_order_relaxed)) + break; + } - assert(count + releaseCount <= maximumCount); + if (previousCount != nullptr) + *previousCount = currentCount; - count += releaseCount; +#if defined(UNLEASHED_RECOMP_IOS) + waitCondition.notify_all(); +#else count.notify_all(); +#endif } }; @@ -662,8 +768,8 @@ uint32_t NtSuspendThread(GuestThreadHandle* hThread, uint32_t* suspendCount) { assert(hThread != GetKernelObject(CURRENT_THREAD_HANDLE) && hThread->GetThreadId() == GuestThread::GetCurrentThreadId()); - hThread->suspended = true; - hThread->suspended.wait(true); + hThread->SetSuspended(true); + hThread->WaitWhileSuspended(); return S_OK; } @@ -676,36 +782,241 @@ uint32_t KeSetAffinityThread(uint32_t Thread, uint32_t Affinity, be* l return 0; } +#if defined(UNLEASHED_RECOMP_IOS) +// libc++ implements atomic::wait with ulock on iOS. Keep ownership atomic, but +// use a hashed condition-variable wait table so the iOS build can distinguish +// a broken ownership protocol from an atomic-wait/ulock problem. +struct CriticalSectionWaitBucket +{ + std::mutex mutex; + std::condition_variable condition; + uint64_t generation{}; +}; + +struct CriticalSectionOwnerDiagnostic +{ + uint32_t owner{}; + std::chrono::steady_clock::time_point acquiredAt{}; +}; + +static std::mutex g_criticalSectionOwnerDiagnosticMutex; +static std::unordered_map + g_criticalSectionOwnerDiagnostics; + +static void RecordCriticalSectionOwner(XRTL_CRITICAL_SECTION* cs, uint32_t owner) +{ + std::lock_guard lock(g_criticalSectionOwnerDiagnosticMutex); + g_criticalSectionOwnerDiagnostics[cs] = + { + owner, + std::chrono::steady_clock::now() + }; +} + +static CriticalSectionOwnerDiagnostic QueryCriticalSectionOwner(XRTL_CRITICAL_SECTION* cs) +{ + std::lock_guard lock(g_criticalSectionOwnerDiagnosticMutex); + const auto it = g_criticalSectionOwnerDiagnostics.find(cs); + return it != g_criticalSectionOwnerDiagnostics.end() + ? it->second + : CriticalSectionOwnerDiagnostic{}; +} + +static CriticalSectionOwnerDiagnostic RemoveCriticalSectionOwner(XRTL_CRITICAL_SECTION* cs) +{ + std::lock_guard lock(g_criticalSectionOwnerDiagnosticMutex); + const auto it = g_criticalSectionOwnerDiagnostics.find(cs); + if (it == g_criticalSectionOwnerDiagnostics.end()) + return {}; + + const CriticalSectionOwnerDiagnostic result = it->second; + g_criticalSectionOwnerDiagnostics.erase(it); + return result; +} + +static CriticalSectionWaitBucket& GetCriticalSectionWaitBucket(const XRTL_CRITICAL_SECTION* cs) +{ + static std::array buckets; + const size_t index = (reinterpret_cast(cs) >> 2) % buckets.size(); + return buckets[index]; +} + +static bool WaitForCriticalSectionOwnerChange( + XRTL_CRITICAL_SECTION* cs, + std::atomic_ref& owningThread, + uint32_t observedOwner, + uint32_t waitingThread) +{ + using namespace std::chrono_literals; + + auto& bucket = GetCriticalSectionWaitBucket(cs); + std::unique_lock lock(bucket.mutex); + const uint64_t generation = bucket.generation; + + if (owningThread.load(std::memory_order_relaxed) != observedOwner) + return true; + + const bool changed = bucket.condition.wait_for(lock, 2s, [&] + { + return bucket.generation != generation || + owningThread.load(std::memory_order_relaxed) != observedOwner; + }); + + if (!changed) + { + const uint32_t actualOwner = owningThread.load(std::memory_order_relaxed); + const uint32_t ownerHostThread = GuestThread::FindHostThreadId(actualOwner); + const CriticalSectionOwnerDiagnostic ownerDiagnostic = QueryCriticalSectionOwner(cs); + lock.unlock(); + LOGFN_WARNING( + "SYNC-CS-WAIT timeout cs=0x{:08X} waiter=0x{:08X} observedOwner=0x{:08X} actualOwner=0x{:08X} trackedOwner=0x{:08X} waiterHost=0x{:08X} ownerHost=0x{:08X} ownerActive={}", + g_memory.MapVirtual(cs), waitingThread, observedOwner, actualOwner, + ownerDiagnostic.owner, + GuestThread::GetCurrentThreadId(), ownerHostThread, ownerHostThread != 0); + } + + return changed; +} + +static void WakeCriticalSectionWaiters(XRTL_CRITICAL_SECTION* cs) +{ + auto& bucket = GetCriticalSectionWaitBucket(cs); + { + std::lock_guard lock(bucket.mutex); + ++bucket.generation; + } + bucket.condition.notify_all(); +} +#endif + +static bool IsCriticalSectionAtomicStorageValid(const XRTL_CRITICAL_SECTION* cs) +{ +#if defined(UNLEASHED_RECOMP_IOS) + static std::once_flag backendLogFlag; + std::call_once(backendLogFlag, [] + { + LOGN("SYNC-CS-BACKEND condition-variable-ios (libc++ atomic wait bypassed)"); + }); +#endif + + const bool aligned = (reinterpret_cast(&cs->OwningThread) % + std::atomic_ref::required_alignment) == 0; + if (!aligned) + { + LOGFN_ERROR( + "SYNC-CS-MISALIGNED csHost={} ownerHost={} requiredAlignment={}", + static_cast(cs), static_cast(&cs->OwningThread), + std::atomic_ref::required_alignment); + assert(false && "Critical section owner storage is not suitably aligned for atomic_ref."); + } + return aligned; +} + void RtlLeaveCriticalSection(XRTL_CRITICAL_SECTION* cs) { + if (!IsCriticalSectionAtomicStorageValid(cs)) + return; + + uint32_t thisThread = g_ppcContext->r13.u32; + assert(thisThread != NULL); + std::atomic_ref owningThread(cs->OwningThread); + + const uint32_t owner = owningThread.load(std::memory_order_relaxed); + if (owner != thisThread) + { + LOGFN_ERROR( + "SYNC-CS-INVALID-LEAVE cs=0x{:08X} leavingThread=0x{:08X} owner=0x{:08X} recursion={}", + g_memory.MapVirtual(cs), thisThread, owner, cs->RecursionCount); + assert(false && "Critical section left by a thread that does not own it."); + return; + } + + if (cs->RecursionCount <= 0) + { + LOGFN_ERROR( + "SYNC-CS-INVALID-RECURSION cs=0x{:08X} owner=0x{:08X} recursion={}", + g_memory.MapVirtual(cs), thisThread, cs->RecursionCount); + assert(false && "Critical section recursion count underflow."); + return; + } + cs->RecursionCount--; if (cs->RecursionCount != 0) return; - std::atomic_ref owningThread(cs->OwningThread); - owningThread.store(0); +#if defined(UNLEASHED_RECOMP_IOS) + const CriticalSectionOwnerDiagnostic ownerDiagnostic = RemoveCriticalSectionOwner(cs); +#endif + owningThread.store(0, std::memory_order_release); +#if defined(UNLEASHED_RECOMP_IOS) + WakeCriticalSectionWaiters(cs); + + const auto heldFor = std::chrono::steady_clock::now() - ownerDiagnostic.acquiredAt; + if (ownerDiagnostic.owner != 0 && heldFor >= std::chrono::seconds(5)) + { + LOGFN_WARNING( + "SYNC-CS-LONG-HOLD cs=0x{:08X} owner=0x{:08X} heldMs={}", + g_memory.MapVirtual(cs), thisThread, + std::chrono::duration_cast(heldFor).count()); + } +#else owningThread.notify_one(); +#endif } void RtlEnterCriticalSection(XRTL_CRITICAL_SECTION* cs) { + if (!IsCriticalSectionAtomicStorageValid(cs)) + return; + uint32_t thisThread = g_ppcContext->r13.u32; assert(thisThread != NULL); std::atomic_ref owningThread(cs->OwningThread); - - while (true) + uint32_t currentOwner = owningThread.load(std::memory_order_acquire); + const auto contentionStart = std::chrono::steady_clock::now(); + bool contended = false; + while (true) { - uint32_t previousOwner = 0; - - if (owningThread.compare_exchange_weak(previousOwner, thisThread) || previousOwner == thisThread) + if (currentOwner == thisThread) { cs->RecursionCount++; return; } - owningThread.wait(previousOwner); + if (currentOwner == 0) + { + if (owningThread.compare_exchange_weak(currentOwner, thisThread, std::memory_order_acquire, std::memory_order_relaxed)) + { + cs->RecursionCount = 1; +#if defined(UNLEASHED_RECOMP_IOS) + RecordCriticalSectionOwner(cs, thisThread); +#endif + + if (contended) + { + const auto duration = std::chrono::steady_clock::now() - contentionStart; + if (duration >= std::chrono::seconds(2)) + { + LOGFN_WARNING( + "SYNC-CS-ACQUIRED-AFTER-WAIT cs=0x{:08X} thread=0x{:08X} waitedMs={}", + g_memory.MapVirtual(cs), thisThread, + std::chrono::duration_cast(duration).count()); + } + } + return; + } + continue; + } + + contended = true; +#if defined(UNLEASHED_RECOMP_IOS) + WaitForCriticalSectionOwnerChange(cs, owningThread, currentOwner, thisThread); +#else + owningThread.wait(currentOwner, std::memory_order_relaxed); +#endif + currentOwner = owningThread.load(std::memory_order_acquire); } } @@ -741,10 +1052,16 @@ void RtlCompareMemoryUlong() uint32_t RtlInitializeCriticalSection(XRTL_CRITICAL_SECTION* cs) { + if (!IsCriticalSectionAtomicStorageValid(cs)) + return 0xC000000D; + cs->Header.Absolute = 0; cs->LockCount = -1; cs->RecursionCount = 0; cs->OwningThread = 0; +#if defined(UNLEASHED_RECOMP_IOS) + RemoveCriticalSectionOwner(cs); +#endif return 0; } @@ -999,8 +1316,7 @@ bool KeSetEvent(XKEVENT* pEvent, uint32_t Increment, bool Wait) { bool result = QueryKernelObject(*pEvent)->Set(); - ++g_keSetEventGeneration; - g_keSetEventGeneration.notify_all(); + NotifyMultipleEventWaiters(); return result; } @@ -1200,28 +1516,47 @@ void XexGetModuleHandle() bool RtlTryEnterCriticalSection(XRTL_CRITICAL_SECTION* cs) { + if (!IsCriticalSectionAtomicStorageValid(cs)) + return false; + uint32_t thisThread = g_ppcContext->r13.u32; assert(thisThread != NULL); std::atomic_ref owningThread(cs->OwningThread); - uint32_t previousOwner = 0; - - if (owningThread.compare_exchange_weak(previousOwner, thisThread) || previousOwner == thisThread) + uint32_t previousOwner = owningThread.load(std::memory_order_relaxed); + if (previousOwner == thisThread) { cs->RecursionCount++; return true; } + previousOwner = 0; + if (owningThread.compare_exchange_strong( + previousOwner, thisThread, std::memory_order_acquire, std::memory_order_relaxed)) + { + cs->RecursionCount = 1; +#if defined(UNLEASHED_RECOMP_IOS) + RecordCriticalSectionOwner(cs, thisThread); +#endif + return true; + } + return false; } void RtlInitializeCriticalSectionAndSpinCount(XRTL_CRITICAL_SECTION* cs, uint32_t spinCount) { + if (!IsCriticalSectionAtomicStorageValid(cs)) + return; + cs->Header.Absolute = (spinCount + 255) >> 8; cs->LockCount = -1; cs->RecursionCount = 0; cs->OwningThread = 0; +#if defined(UNLEASHED_RECOMP_IOS) + RemoveCriticalSectionOwner(cs); +#endif } void _vswprintf_x() @@ -1317,15 +1652,18 @@ uint32_t NtResumeThread(GuestThreadHandle* hThread, uint32_t* suspendCount) { assert(hThread != GetKernelObject(CURRENT_THREAD_HANDLE)); - hThread->suspended = false; - hThread->suspended.notify_all(); + hThread->SetSuspended(false); return S_OK; } uint32_t NtSetEvent(Event* handle, uint32_t* previousState) { - handle->Set(); + const bool wasSignaled = handle->Set(); + if (previousState != nullptr) + *previousState = ByteSwap(static_cast(wasSignaled)); + + NotifyMultipleEventWaiters(); return 0; } @@ -1508,8 +1846,44 @@ uint32_t KeWaitForMultipleObjects(uint32_t Count, xpointer* if (WaitType == 0) // Wait all { + thread_local std::vector s_events; + thread_local std::vector s_consumedAutoResetEvents; + s_events.resize(Count); + s_consumedAutoResetEvents.reserve(Count); + for (size_t i = 0; i < Count; i++) - QueryKernelObject(*Objects[i])->Wait(timeout); + s_events[i] = QueryKernelObject(*Objects[i]); + + while (true) + { + const uint32_t generation = g_keSetEventGeneration.load(std::memory_order_acquire); + s_consumedAutoResetEvents.clear(); + bool allSignaled = true; + + for (Event* event : s_events) + { + if (event->Wait(0) != STATUS_SUCCESS) + { + allSignaled = false; + break; + } + + if (!event->manualReset) + s_consumedAutoResetEvents.push_back(event); + } + + if (allSignaled) + return STATUS_SUCCESS; + + if (!s_consumedAutoResetEvents.empty()) + { + for (Event* event : s_consumedAutoResetEvents) + event->Set(); + NotifyMultipleEventWaiters(); + } + + WaitForMultipleEventGenerationChange(generation); + } } else { @@ -1521,7 +1895,7 @@ uint32_t KeWaitForMultipleObjects(uint32_t Count, xpointer* while (true) { - uint32_t generation = g_keSetEventGeneration.load(); + uint32_t generation = g_keSetEventGeneration.load(std::memory_order_acquire); for (size_t i = 0; i < Count; i++) { @@ -1531,7 +1905,7 @@ uint32_t KeWaitForMultipleObjects(uint32_t Count, xpointer* } } - g_keSetEventGeneration.wait(generation); + WaitForMultipleEventGenerationChange(generation); } } @@ -1567,8 +1941,7 @@ uint32_t KeResumeThread(GuestThreadHandle* object) { assert(object != GetKernelObject(CURRENT_THREAD_HANDLE)); - object->suspended = false; - object->suspended.notify_all(); + object->SetSuspended(false); return 0; } @@ -1594,7 +1967,7 @@ void XMACreateContext() // uint32_t XAudioRegisterRenderDriverClient(be* callback, be* driver) // { // //printf("XAudioRegisterRenderDriverClient(): %x %x\n"); -// +// // *driver = apu::RegisterClient(callback[0], callback[1]); // return 0; // } @@ -1608,7 +1981,7 @@ void XMACreateContext() // { // // printf("!!! STUB !!! XAudioSubmitRenderDriverFrame\n"); // apu::SubmitFrames(samples); -// +// // return 0; // } diff --git a/UnleashedRecomp/locale/config_locale.cpp b/UnleashedRecomp/locale/config_locale.cpp index 1242e4eb..636024ad 100644 --- a/UnleashedRecomp/locale/config_locale.cpp +++ b/UnleashedRecomp/locale/config_locale.cpp @@ -1012,3 +1012,14 @@ CONFIG_DEFINE_ENUM_LOCALE(EUIAlignmentMode) } } }; + +// TODO: Add localization for the following languages: Japanese, French +CONFIG_DEFINE_LOCALE(ShowMetalHUD) +{ + { ELanguage::English, { "Show Metal HUD", "Toggle the Metal Performance HUD." } }, + // { ELanguage::Japanese, { "", "" } }, + { ELanguage::German, { "Zeige Metal HUD", "Schalte das Metal Performance HUD an oder aus." } }, + // { ELanguage::French, { "", "" } }, + { ELanguage::Spanish, { "Mostrar Metal HUD", "Activa/desactiva el Metal Performance HUD." } }, + { ELanguage::Italian, { "Mostra Metal HUD", "Attiva/disattiva il Metal Performance HUD." } } +}; diff --git a/UnleashedRecomp/locale/locale.cpp b/UnleashedRecomp/locale/locale.cpp index 7544f31c..347e1743 100644 --- a/UnleashedRecomp/locale/locale.cpp +++ b/UnleashedRecomp/locale/locale.cpp @@ -714,6 +714,18 @@ std::unordered_map> { ELanguage::Italian, "Impossibile allocare la memoria per il gioco.\n\nAssicurati che:\n\n- Soddisfi i requisiti minimi di sistema (8 GB).\n- Il tuo file di paging sia configurato con almeno 4 o 8 GB di memoria virtuale." } } }, + { + "System_iOS_UnsupportedGPU_BCTextures", + { + // TODO: Localize the GPU requirements for iOS devices. + { ELanguage::English, "Your device's GPU is not supported.\n\nUnleashed Recompiled requires an iOS device with hardware support for BC texture compression.\n\nMinimum requirement:\n- Apple A17 Pro chip or newer\n- Apple A18 / A18 Pro chip or newer\n- Apple M-series chips (M1, M2, M3, M4 or newer)\n\nSupported devices include:\n- iPhone 15 Pro / 15 Pro Max and newer\n- iPhone 16 / 16 Plus / 16 Pro / 16 Pro Max and newer\n- iPhone 16e and newer\n- iPad mini (A17 Pro) and newer\n- iPad Pro models with M-series chips (M1 / 11-inch 3rd gen / 12.9-inch 5th gen or newer)\n- iPad Air models with M-series chips (M1 / 5th gen or newer)\n\nUnsupported devices include:\n- All iPhones with A16 Bionic chip or earlier (iPhone 15, iPhone 14 Pro, and older)\n- iPads with A-series chips (iPad 10th gen, iPad Air 4th gen, older iPad Pros)\n\nWe aim to support more devices in the future." }, + // { ELanguage::Japanese, ""}, + { ELanguage::German, "Deine Geräte-GPU wird nicht unterstützt.\n\nUnleashed Recompiled benötigt ein iOS-Gerät mit Hardware-Unterstützung für BC-Texturen.\n\nMindestanforderungen:\n- Apple A17 Pro-Chip oder neuer\n- Apple A18 / A18 Pro-Chip oder neuer\n- Apple M-Series-Chips (M1, M2, M3, M4 oder neuer)\n\nUnterstützte Geräte:\n- iPhone 15 Pro / 15 Pro Max und neuer\n- iPhone 16 / 16 Plus / 16 Pro / 16 Pro Max und neuer\n- iPhone 16e und neuer\n- iPad mini (A17 Pro) und neuer\n- iPad Pro-Modelle mit M-Series-Chips (M1 / 11\" 3. Gen / 12,9\" 5. Gen oder neuer)\n- iPad Air-Modelle mit M-Series-Chips (M1 / 5. Gen oder neuer)\n\nNicht unterstützte Geräte:\n- Alle iPhones mit A16 Bionic-Chip oder früher (iPhone 15, iPhone 14 Pro und älter)\n- iPads mit A-Series-Chips (iPad 10. Gen, iPad Air 4. Gen, ältere iPad Pros)\n\nWir bemühen uns, in Zukunft mehr Geräte zu unterstützen." }, + // { ELanguage::French, "" }, + { ELanguage::Spanish, "La GPU en tu dispositivo no es compatible.\n\nUnleashed Recompiled requiere un dispositivo iOS con soporte hardware para texturas BC.\n\nRequisitos mínimos:\n- Chip Apple A17 Pro o superior\n- Chip Apple A18 / A18 Pro o superior\n- Chips Apple M-series (M1, M2, M3, M4 o más recientes)\n\nDispositivos compatibles incluyen:\n- iPhone 15 Pro / 15 Pro Max y más recientes\n- iPhone 16 / 16 Plus / 16 Pro / 16 Pro Max y más recientes\n- iPhone 16e y más recientes\n- iPad mini (A17 Pro) y más recientes\n- Modelos de iPad Pro con chips M-series (M1 / 11 pulgadas 3.ª gen / 12.9 pulgadas 5.ª gen o más recientes)\n- Modelos de iPad Air con chips M-series (M1 / 5.ª gen o más recientes)\n\nDispositivos no compatibles incluyen:\n- Todos los iPhones con chip A16 Bionic o anterior (iPhone 15, iPhone 14 Pro y anteriores)\n- iPads con chips de la serie A (iPad 10.ª gen, iPad Air 4.ª gen, iPad Pro más antiguos)\n\nEsperamos admitir más dispositivos en el futuro." }, + // { ELanguage::Italian, "" } + } + }, { "IntegrityCheck_Success", { @@ -856,7 +868,7 @@ std::unordered_map> { ELanguage::Spanish, "Cambiar" }, { ELanguage::Italian, "Cambia" } } - } + }, }; std::string& Localise(const std::string_view& key) diff --git a/UnleashedRecomp/main.cpp b/UnleashedRecomp/main.cpp index bb241760..e34d7e10 100644 --- a/UnleashedRecomp/main.cpp +++ b/UnleashedRecomp/main.cpp @@ -1,4 +1,7 @@ #include +#if defined(__IPHONEOS__) +#include +#endif #ifdef __x86_64__ #include #endif @@ -32,6 +35,11 @@ #include #endif +#ifdef __APPLE__ +#include "apple_utils.h" +#include +#endif + #if defined(_WIN32) && defined(UNLEASHED_RECOMP_D3D12) static std::array g_D3D12RequiredModules = { @@ -205,6 +213,13 @@ int main(int argc, char *argv[]) os::logger::Init(); +#if TARGET_OS_IOS + if (!apple::SupportsBCTextures()) { + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, GameWindow::GetTitle(), Localise("System_iOS_UnsupportedGPU_BCTextures").c_str(), GameWindow::s_pWindow); + std::_Exit(1); + } +#endif + PreloadContext preloadContext; preloadContext.PreloadExecutable(); @@ -232,11 +247,24 @@ int main(int argc, char *argv[]) } } +#if TARGET_OS_IOS + // iOS: Check if there's a pending DLC installation flag set from a previous attempt + CFStringRef pendingKey = CFSTR("UnleashedRecomp_PendingDLCInstall"); + bool pendingDLC = CFPreferencesGetAppBooleanValue(pendingKey, kCFPreferencesCurrentApplication, nullptr); + if (pendingDLC) + { + CFPreferencesSetAppValue(pendingKey, kCFBooleanFalse, kCFPreferencesCurrentApplication); + forceDLCInstaller = true; + } +#endif + if (!useDefaultWorkingDirectory) { +#if !TARGET_OS_IPHONE // Set the current working directory to the executable's path. std::error_code ec; std::filesystem::current_path(os::process::GetExecutableRoot(), ec); +#endif } Config::Load(); diff --git a/UnleashedRecomp/os/macos/logger_macos.cpp b/UnleashedRecomp/os/macos/logger_macos.cpp index df5708dd..8a284b98 100644 --- a/UnleashedRecomp/os/macos/logger_macos.cpp +++ b/UnleashedRecomp/os/macos/logger_macos.cpp @@ -1,17 +1,30 @@ #include - +#if TARGET_OS_IPHONE +#include +#endif void os::logger::Init() { } void os::logger::Log(const std::string_view str, ELogType type, const char* func) { - if (func) - { - fmt::println("[{}] {}", func, str); - } - else - { - fmt::println("{}", str); - } + #if TARGET_OS_IPHONE + if (func) + { + os_log(OS_LOG_DEFAULT, "%{public}s: %{public}s", func, str.data()); + } + else + { + os_log(OS_LOG_DEFAULT, "%{public}s", str.data()); + } + #else + if (func) + { + fmt::println("[{}] {}", func, str); + } + else + { + fmt::println("{}", str); + } + #endif } diff --git a/UnleashedRecomp/os/macos/process_macos.cpp b/UnleashedRecomp/os/macos/process_macos.cpp index e60ab0b0..35a97eb3 100644 --- a/UnleashedRecomp/os/macos/process_macos.cpp +++ b/UnleashedRecomp/os/macos/process_macos.cpp @@ -41,6 +41,7 @@ std::filesystem::path os::process::GetExecutableRoot() std::filesystem::path os::process::GetWorkingDirectory() { +#if !TARGET_OS_IPHONE char cwd[PATH_MAX] = {}; char *res = getcwd(cwd, sizeof(cwd)); if (res != nullptr) @@ -51,15 +52,26 @@ std::filesystem::path os::process::GetWorkingDirectory() { return std::filesystem::path(); } +#else + // iOS: Working directory is not meaningful in app sandbox + // Return app bundle path as fallback + return GetExecutableRoot(); +#endif } bool os::process::SetWorkingDirectory(const std::filesystem::path& path) { +#if !TARGET_OS_IPHONE return chdir(path.c_str()) == 0; +#else + // iOS: Cannot change working directory in sandbox; return false + return false; +#endif } bool os::process::StartProcess(const std::filesystem::path& path, const std::vector& args, std::filesystem::path work) { +#if !TARGET_OS_IPHONE pid_t pid = fork(); if (pid < 0) return false; @@ -83,6 +95,10 @@ bool os::process::StartProcess(const std::filesystem::path& path, const std::vec } return true; +#else + // iOS: Cannot start other processes in app sandbox + return false; +#endif } void os::process::CheckConsole() diff --git a/UnleashedRecomp/patches/CTitleStateMenu_patches.cpp b/UnleashedRecomp/patches/CTitleStateMenu_patches.cpp index b3ae4580..61ac40d7 100644 --- a/UnleashedRecomp/patches/CTitleStateMenu_patches.cpp +++ b/UnleashedRecomp/patches/CTitleStateMenu_patches.cpp @@ -15,6 +15,16 @@ static bool g_installMessageOpen = false; static bool g_installMessageFaderBegun = false; static int g_installMessageResult = -1; +#if TARGET_OS_IOS +#include + +static void iOS_SetPendingInstallFlag() +{ + CFStringRef pendingKey = CFSTR("UnleashedRecomp_PendingDLCInstall"); + CFPreferencesSetAppValue(pendingKey, kCFBooleanTrue, kCFPreferencesCurrentApplication); +} +#endif + static bool ProcessInstallMessage() { if (!g_installMessageOpen) @@ -34,7 +44,14 @@ static bool ProcessInstallMessage() switch (g_installMessageResult) { case 0: +#if TARGET_OS_IOS + // iOS: Just set a flag to install DLC on next launch + iOS_SetPendingInstallFlag(); + Fader::FadeOut(1, []() { App::Exit(); }); +#else + // Desktop: Restart with installer flag Fader::FadeOut(1, []() { App::Restart({ "--install-dlc" }); }); +#endif g_installMessageFaderBegun = true; break; diff --git a/UnleashedRecomp/res/ios/Assets.car b/UnleashedRecomp/res/ios/Assets.car new file mode 100644 index 00000000..40cc8cda Binary files /dev/null and b/UnleashedRecomp/res/ios/Assets.car differ diff --git a/UnleashedRecomp/res/ios/iOSBundleInfo.plist.in b/UnleashedRecomp/res/ios/iOSBundleInfo.plist.in new file mode 100644 index 00000000..14e48452 --- /dev/null +++ b/UnleashedRecomp/res/ios/iOSBundleInfo.plist.in @@ -0,0 +1,65 @@ + + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + Unleashed Recompiled iOS + CFBundleIdentifier + hedge-dev.UnleashedRecomp + CFBundleName + Unleashed Recompiled + CFBundlePackageType + APPL + CFBundleShortVersionString + @IOS_BUNDLE_VERSION@ + CFBundleVersion + @IOS_BUNDLE_VERSION@ + MinimumOSVersion + @IOS_DEPLOYMENT_TARGET@ + UIDeviceFamily + + 1 + 2 + + CFBundleDisplayName + Unleashed Recompiled + CFBundleIcons + + CFBundlePrimaryIcon + + CFBundleIconName + AppIcon + + + CFBundleIcons~ipad + + CFBundlePrimaryIcon + + CFBundleIconName + AppIcon + + + CADisableMinimumFrameDurationOnPhone + + UIFileSharingEnabled + + LSSupportsOpeningDocumentsInPlace + + NSDocumentsFolderUsageDescription + Allows access to game files and user-provided content. + UIApplicationSupportsIndirectInputEvents + + LSSupportsGameMode + + LSApplicationCategoryType + public.app-category.action-games + UISupportedInterfaceOrientations + + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/UnleashedRecomp/ui/file_picker_ios.h b/UnleashedRecomp/ui/file_picker_ios.h new file mode 100644 index 00000000..fb67151d --- /dev/null +++ b/UnleashedRecomp/ui/file_picker_ios.h @@ -0,0 +1,11 @@ +#pragma once + +#include +#include +#include + +namespace ios +{ + bool PickPaths(bool folderMode, std::list& outPaths, std::string& outError); + void ReleaseAllAccess(); +} diff --git a/UnleashedRecomp/ui/file_picker_ios.mm b/UnleashedRecomp/ui/file_picker_ios.mm new file mode 100644 index 00000000..edfb495c --- /dev/null +++ b/UnleashedRecomp/ui/file_picker_ios.mm @@ -0,0 +1,267 @@ +#include "file_picker_ios.h" + +#import +#import +#import +#include + + +@interface FilePickerDelegate : NSObject +@property(nonatomic, copy) void (^completionHandler)(NSArray *urls, NSError *error, BOOL cancelled); +@end + +@implementation FilePickerDelegate +- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray *)urls { + if (self.completionHandler) { + self.completionHandler(urls, nil, NO); + } +} +- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller { + if (self.completionHandler) { + self.completionHandler(@[], nil, YES); + } +} +@end + +static UIWindow* GetActiveWindow() +{ + UIApplication* app = UIApplication.sharedApplication; + + if (@available(iOS 13.0, *)) + { + for (UIScene* scene in app.connectedScenes) + { + if (![scene isKindOfClass:[UIWindowScene class]]) + continue; + + UIWindowScene* windowScene = (UIWindowScene*)scene; + if (windowScene.activationState != UISceneActivationStateForegroundActive) + continue; + + for (UIWindow* window in windowScene.windows) + { + if (window.isKeyWindow) + return window; + } + + if (windowScene.windows.count > 0) + return windowScene.windows.firstObject; + } + } + + if (app.windows.count > 0) + return app.windows.firstObject; + + return nil; +} + +namespace ios +{ + static std::atomic s_pickerInFlight = false; + static NSMutableArray* s_activeScopedURLs = nil; + + static void ClearActiveScopedURLs() + { + if (s_activeScopedURLs == nil) + return; + + NSArray* urlsToStop = [NSArray arrayWithArray:s_activeScopedURLs]; + for (id scopedObject in urlsToStop) + { + if (![scopedObject isKindOfClass:[NSURL class]]) + continue; + + NSURL* scopedURL = (NSURL*)scopedObject; + [scopedURL stopAccessingSecurityScopedResource]; + } + + [s_activeScopedURLs removeAllObjects]; + } + + static bool IsTrackingScopedURL(NSURL* url) + { + if (url == nil || s_activeScopedURLs == nil) + return false; + + for (id scopedObject in s_activeScopedURLs) + { + if (![scopedObject isKindOfClass:[NSURL class]]) + continue; + + NSURL* scopedURL = (NSURL*)scopedObject; + if ([scopedURL isEqual:url]) + return true; + } + + return false; + } + + bool PickPaths(bool folderMode, std::list& outPaths, std::string& outError) + { + @autoreleasepool + { + bool expected = false; + if (!s_pickerInFlight.compare_exchange_strong(expected, true)) + { + outError = "A file picker request is already active."; + return false; + } + + __block BOOL finished = NO; + __block BOOL cancelled = NO; + __block NSError* pickerError = nil; + __block NSArray* selectedURLs = nil; + dispatch_semaphore_t completionSemaphore = dispatch_semaphore_create(0); + + if (s_activeScopedURLs == nil) + { + s_activeScopedURLs = [[NSMutableArray alloc] init]; + } + + auto presentPicker = ^{ + UIWindow* window = GetActiveWindow(); + UIViewController* presenter = window.rootViewController; + + while (presenter != nil && presenter.presentedViewController != nil) + presenter = presenter.presentedViewController; + + if (presenter == nil) + { + pickerError = [NSError errorWithDomain:@"UnleashedRecomp" code:1 userInfo:@{NSLocalizedDescriptionKey: @"No active presenter for file picker."}]; + finished = YES; + dispatch_semaphore_signal(completionSemaphore); + return; + } + UIDocumentPickerViewController* picker = nil; + if (@available(iOS 14.0, *)) { + NSArray *types = folderMode ? @[UTTypeFolder] : @[UTTypeData]; + picker = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:types asCopy:NO]; + } else { + NSArray* documentTypes = folderMode ? @[@"public.folder"] : @[@"public.data"]; + picker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen]; + } + picker.allowsMultipleSelection = YES; + + FilePickerDelegate* delegate = [FilePickerDelegate new]; + delegate.completionHandler = ^(NSArray* urls, NSError* error, BOOL wasCancelled) + { + selectedURLs = urls != nil ? [urls copy] : @[]; + pickerError = error; + cancelled = wasCancelled; + finished = YES; + dispatch_semaphore_signal(completionSemaphore); + }; + + picker.delegate = delegate; + objc_setAssociatedObject(picker, @selector(PickPaths), delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + [presenter presentViewController:picker animated:YES completion:nil]; + }; + + if ([NSThread isMainThread]) + { + presentPicker(); + while (!finished) + { + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.01]]; + } + } + else + { + dispatch_sync(dispatch_get_main_queue(), presentPicker); + dispatch_semaphore_wait(completionSemaphore, DISPATCH_TIME_FOREVER); + } + + if (pickerError != nil) + { + outError = [[pickerError localizedDescription] UTF8String]; + s_pickerInFlight.store(false); + return false; + } + + if (cancelled) + { + s_pickerInFlight.store(false); + return true; + } + + if (selectedURLs != nil && ![selectedURLs isKindOfClass:[NSArray class]]) + { + outError = "Document picker returned invalid selection data."; + s_pickerInFlight.store(false); + return false; + } + + bool foundValidPath = false; + NSArray* selectedURLArray = selectedURLs != nil ? selectedURLs : @[]; + for (id pickedObject in selectedURLArray) + { + if (![pickedObject isKindOfClass:[NSURL class]]) + continue; + + NSURL* url = (NSURL*)pickedObject; + if (url == nil) + continue; + + BOOL startedScopedAccess = [url startAccessingSecurityScopedResource]; + if (startedScopedAccess && !IsTrackingScopedURL(url)) + [s_activeScopedURLs addObject:url]; + + NSURL* fileURL = url; + if (![fileURL isFileURL]) + { + NSURL* filePathURL = [fileURL filePathURL]; + if (filePathURL != nil) + fileURL = filePathURL; + } + + NSString* path = fileURL.path; + if ((path == nil || path.length == 0) && url.standardizedURL != nil) + path = url.standardizedURL.path; + + if ((path == nil || path.length == 0) && url.absoluteString != nil) + { + NSURL* absoluteURL = [NSURL URLWithString:url.absoluteString]; + if (absoluteURL != nil) + path = absoluteURL.path; + } + + if (path != nil && path.length > 0) + { + outPaths.emplace_back(std::filesystem::path([path UTF8String])); + foundValidPath = true; + } + } + + if (!foundValidPath && selectedURLArray.count > 0) + { + outError = "Document picker returned items without usable local file paths. Try selecting a local file under 'On My iPhone' and ensure the file is fully downloaded."; + s_pickerInFlight.store(false); + return false; + } + + if (!foundValidPath && selectedURLArray.count == 0) + { + s_pickerInFlight.store(false); + return true; + } + + if (outPaths.empty()) + { + outError = "No readable file paths were returned by the picker."; + s_pickerInFlight.store(false); + return false; + } + + s_pickerInFlight.store(false); + return true; + } + } + + void ReleaseAllAccess() + { + @autoreleasepool + { + ClearActiveScopedURLs(); + } + } +} diff --git a/UnleashedRecomp/ui/game_window.cpp b/UnleashedRecomp/ui/game_window.cpp index d15aac63..5f1259a2 100644 --- a/UnleashedRecomp/ui/game_window.cpp +++ b/UnleashedRecomp/ui/game_window.cpp @@ -33,6 +33,17 @@ int Window_OnSDLEvent(void*, SDL_Event* event) switch (event->type) { + case SDL_APP_WILLENTERBACKGROUND: + { + Video::HandleApplicationBackgroundState(true); + break; + } + + case SDL_APP_DIDENTERFOREGROUND: { + Video::HandleApplicationBackgroundState(false); + break; + } + case SDL_QUIT: { if (App::s_isSaving) @@ -218,7 +229,11 @@ void GameWindow::Init(const char* sdlVideoDriver) #elif defined(__linux__) s_renderWindow = { info.info.x11.display, info.info.x11.window }; #elif defined(__APPLE__) +#if defined(SDL_VIDEO_DRIVER_UIKIT) + s_renderWindow.window = info.info.uikit.window; +#else s_renderWindow.window = info.info.cocoa.window; +#endif s_renderWindow.view = SDL_Metal_GetLayer(SDL_Metal_CreateView(s_pWindow)); #else static_assert(false, "Unknown platform."); @@ -346,7 +361,7 @@ bool GameWindow::SetFullscreen(bool isEnabled) return isEnabled; } - + void GameWindow::SetFullscreenCursorVisibility(bool isVisible) { s_isFullscreenCursorVisible = isVisible; diff --git a/UnleashedRecomp/ui/installer_wizard.cpp b/UnleashedRecomp/ui/installer_wizard.cpp index a9d060ed..8a97524a 100644 --- a/UnleashedRecomp/ui/installer_wizard.cpp +++ b/UnleashedRecomp/ui/installer_wizard.cpp @@ -1,6 +1,8 @@ #include "installer_wizard.h" +#ifndef UNLEASHED_RECOMP_IOS #include +#endif #include #include @@ -9,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -17,6 +20,14 @@ #include #include +#if defined(__APPLE__) +#include +#endif + +#if defined(__APPLE__) && TARGET_OS_IPHONE +#include +#endif + #include #include #include @@ -29,6 +40,16 @@ #include #include #include +#if defined(UNLEASHED_RECOMP_IOS_INSTALLER_PNGS) +#include +#include +#include +#include +#include +#include +#include +#include +#endif #include // One Shot Animations Constants @@ -167,6 +188,21 @@ static bool g_currentCursorBack = false; static std::vector> g_currentCursorRects; static std::string g_creditsStr; +static int FindCursorRectIndexAtPoint(const ImVec2 &point) +{ + for (size_t i = 0; i < g_currentCursorRects.size(); i++) + { + const auto ¤tRect = g_currentCursorRects[i]; + if (point.x >= currentRect.first.x && point.x <= currentRect.second.x + && point.y >= currentRect.first.y && point.y <= currentRect.second.y) + { + return int(i); + } + } + + return -1; +} + class SDLEventListenerForInstaller : public SDLEventListener { public: @@ -290,6 +326,27 @@ class SDLEventListenerForInstaller : public SDLEventListener break; } + + case SDL_FINGERDOWN: + case SDL_FINGERMOTION: + { + ImVec2 touchPos = { + event->tfinger.x * ImGui::GetIO().DisplaySize.x, + event->tfinger.y * ImGui::GetIO().DisplaySize.y, + }; + + newCursorIndex = FindCursorRectIndexAtPoint(touchPos); + if (newCursorIndex < 0) + { + g_currentCursorIndex = -1; + } + else if (event->type == SDL_FINGERDOWN) + { + g_currentCursorAccepted = true; + } + + break; + } } if (tapDirection.x != 0.0f || tapDirection.y != 0.0f) @@ -418,12 +475,12 @@ static double ComputeMotionInstaller(double timeAppear, double timeDisappear, do return ComputeMotion(timeAppear, offset, total) * (1.0 - ComputeMotion(timeDisappear, ALL_ANIMATIONS_FULL_DURATION - offset - total, total)); } -static double ComputeMotionInstallerLoop(double timeAppear, double speed, double offset) +static double ComputeMotionInstallerLoop(double timeAppear, double speed, double offset) { return std::clamp(fmodf((ImGui::GetTime() - timeAppear) * speed, 1.0f + offset) - offset, 0.0, 1.0) / 1.0; } -static double ComputeHermiteMotionInstallerLoop(double timeAppear, double speed, double offset) +static double ComputeHermiteMotionInstallerLoop(double timeAppear, double speed, double offset) { return (cosf(M_PI * ComputeMotionInstallerLoop(timeAppear, speed, offset) + M_PI) + 1) / 2; } @@ -482,6 +539,23 @@ static void DrawLeftImage() double imageAlpha = ComputeMotionInstaller(g_appearTime, g_disappearTime, IMAGE_ANIMATION_TIME, IMAGE_ANIMATION_DURATION); int a = std::lround(255.0 * imageAlpha); GuestTexture *guestTexture = g_installTextures[installTextureIndex % g_installTextures.size()].get(); + if (guestTexture == nullptr) + { + for (const auto &texture : g_installTextures) + { + if (texture) + { + guestTexture = texture.get(); + break; + } + } + } + + if (guestTexture == nullptr) + { + return; + } + auto &res = ImGui::GetIO().DisplaySize; auto drawList = ImGui::GetBackgroundDrawList(); ImVec2 min = { g_aspectRatioOffsetX + Scale(IMAGE_X), g_aspectRatioOffsetY + Scale(IMAGE_Y) }; @@ -505,7 +579,7 @@ static void DrawHeaderIconsForInstallPhase(double iconsPosX, double iconsPosY, d // Calculate rotated corners float cosCurrentAngle = cosf(rotation); float sinCurrentAngle = sinf(rotation); - ImVec2 corners[4] = + ImVec2 corners[4] = { ImRotate(ImVec2(arrowCircleMin.x - center.x, arrowCircleMin.y - center.y), cosCurrentAngle, sinCurrentAngle), ImRotate(ImVec2(arrowCircleMax.x - center.x, arrowCircleMin.y - center.y), cosCurrentAngle, sinCurrentAngle), @@ -533,7 +607,7 @@ static void DrawHeaderIconsForInstallPhase(double iconsPosX, double iconsPosY, d // Calculate linear fade-out from high point time - ({PULSE_ANIMATION_LOOP_FADE_HIGH_POINT}, 1) - to loop end - (1, 0) -. float m = -1 / (1 - PULSE_ANIMATION_LOOP_FADE_HIGH_POINT); float b = m * (-PULSE_ANIMATION_LOOP_FADE_HIGH_POINT) + 1; - + pulseFade = m * pulseMotion + b; } @@ -678,11 +752,11 @@ static void DrawScanlineBars() } static void DrawContainer(ImVec2 min, ImVec2 max, bool isTextArea) -{ +{ auto &res = ImGui::GetIO().DisplaySize; auto drawList = ImGui::GetBackgroundDrawList(); - double gridAlpha = ComputeMotionInstaller(g_appearTime, g_disappearTime, + double gridAlpha = ComputeMotionInstaller(g_appearTime, g_disappearTime, isTextArea ? CONTAINER_INNER_TIME : CONTAINER_OUTER_TIME, isTextArea ? CONTAINER_INNER_DURATION : CONTAINER_OUTER_DURATION ); @@ -699,7 +773,7 @@ static void DrawContainer(ImVec2 min, ImVec2 max, bool isTextArea) SetAdditive(false); SetShaderModifier(IMGUI_SHADER_MODIFIER_NONE); - if (isTextArea) + if (isTextArea) { drawList->AddRectFilled(min, max, gridOverlayColor); } @@ -835,7 +909,7 @@ static void DrawDescriptionContainer() ImVec2 imageRegionMin = { containerLeft, textY + descTextSize.y }; ImVec2 imageRegionMax = { containerRight, containerBottom - (marqueeTextMax.y - marqueeTextMin.y) }; - ImVec2 imageMin = + ImVec2 imageMin = { /* X */ imageRegionMin.x + ((imageRegionMax.x - imageRegionMin.x) / 2) - (imageScale / 2) - (hedgeDevTextSize.x / 2) - hedgeDevTextMarginX, /* Y */ imageRegionMin.y + ((imageRegionMax.y - imageRegionMin.y) / 2) - (imageScale / 2) - imageMarginY @@ -1083,6 +1157,7 @@ static void DrawProgressBar(float progressRatio) drawList->AddRectFilledMultiColor(sliderMin, sliderMax, sliderColor0, sliderColor0, sliderColor1, sliderColor1); } +#ifndef UNLEASHED_RECOMP_IOS static bool ConvertPathSet(const nfdpathset_t *pathSet, std::list &filePaths) { nfdpathsetsize_t pathSetCount = 0; @@ -1106,9 +1181,19 @@ static bool ConvertPathSet(const nfdpathset_t *pathSet, std::list &paths) std::list failedPaths; if (g_currentPage == WizardPage::SelectGameAndUpdate) { +#if defined(__APPLE__) && TARGET_OS_IPHONE + auto toLowerString = [](std::string value) + { + std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return value; + }; + + for (const std::filesystem::path &path : paths) + { + std::error_code ec; + bool isDirectory = std::filesystem::is_directory(path, ec); + std::string extension = toLowerString(path.extension().string()); + bool looksLikeGameSource = (extension == ".iso") || isDirectory; + + if (looksLikeGameSource || g_gameSourcePath.empty()) + { + g_gameSourcePath = path; + } + else + { + g_updateSourcePath = path; + } + } +#else for (const std::filesystem::path &path : paths) { if (Installer::parseGame(path)) @@ -1200,6 +1313,7 @@ static bool ParseSourcePaths(std::list &paths) isFailedPathsOverLimit = true; } } +#endif } else if(g_currentPage == WizardPage::SelectDLC) { @@ -1438,9 +1552,17 @@ static void DrawNavigationButton() XexPatcher::Result patcherResult; if (g_currentPage == WizardPage::SelectGameAndUpdate && (patcherResult = Installer::checkGameUpdateCompatibility(g_gameSourcePath, g_updateSourcePath), patcherResult != XexPatcher::Result::Success)) { + std::u8string gameNameU8 = g_gameSourcePath.filename().u8string(); + std::u8string updateNameU8 = g_updateSourcePath.filename().u8string(); + os::logger::Log(fmt::format( + "Installer compatibility check failed (result={}) game='{}' update='{}'", + int(patcherResult), + std::string(gameNameU8.begin(), gameNameU8.end()), + std::string(updateNameU8.begin(), updateNameU8.end()))); g_currentMessagePrompt = Localise("Installer_Message_IncompatibleGameData"); g_currentMessagePromptConfirmation = false; } + else if (g_currentPage == WizardPage::SelectDLC) { // Check if any of the DLC was not specified. @@ -1512,7 +1634,7 @@ static void CheckCancelAction() { return; } - + g_currentCursorBack = false; if (g_currentPage == WizardPage::InstallSucceeded) @@ -1750,6 +1872,23 @@ void InstallerWizard::Init() g_seuratFont = ImFontAtlasSnapshot::GetFont("FOT-SeuratPro-M.otf"); g_dfsogeistdFont = ImFontAtlasSnapshot::GetFont("DFSoGeiStd-W7.otf"); g_newRodinFont = ImFontAtlasSnapshot::GetFont("FOT-NewRodinPro-DB.otf"); +#if defined(UNLEASHED_RECOMP_IOS_INSTALLER_PNGS) +#if defined(UNLEASHED_RECOMP_IOS_LOW_MEM_INSTALLER) + g_installTextures[0] = LOAD_ZSTD_TEXTURE(g_install_001_png); +#else + g_installTextures[0] = LOAD_ZSTD_TEXTURE(g_install_001_png); + g_installTextures[1] = LOAD_ZSTD_TEXTURE(g_install_002_png); + g_installTextures[2] = LOAD_ZSTD_TEXTURE(g_install_003_png); + g_installTextures[3] = LOAD_ZSTD_TEXTURE(g_install_004_png); + g_installTextures[4] = LOAD_ZSTD_TEXTURE(g_install_005_png); + g_installTextures[5] = LOAD_ZSTD_TEXTURE(g_install_006_png); + g_installTextures[6] = LOAD_ZSTD_TEXTURE(g_install_007_png); + g_installTextures[7] = LOAD_ZSTD_TEXTURE(g_install_008_png); +#endif +#else +#if defined(UNLEASHED_RECOMP_IOS_LOW_MEM_INSTALLER) + g_installTextures[0] = LOAD_ZSTD_TEXTURE(g_install_001); +#else g_installTextures[0] = LOAD_ZSTD_TEXTURE(g_install_001); g_installTextures[1] = LOAD_ZSTD_TEXTURE(g_install_002); g_installTextures[2] = LOAD_ZSTD_TEXTURE(g_install_003); @@ -1758,6 +1897,8 @@ void InstallerWizard::Init() g_installTextures[5] = LOAD_ZSTD_TEXTURE(g_install_006); g_installTextures[6] = LOAD_ZSTD_TEXTURE(g_install_007); g_installTextures[7] = LOAD_ZSTD_TEXTURE(g_install_008); +#endif +#endif g_milesElectricIcon = LOAD_ZSTD_TEXTURE(g_miles_electric_icon); g_arrowCircle = LOAD_ZSTD_TEXTURE(g_arrow_circle); g_pulseInstall = LOAD_ZSTD_TEXTURE(g_pulse_install); @@ -1825,11 +1966,15 @@ void InstallerWizard::Shutdown() g_currentPickerThread.reset(); } +#if defined(__APPLE__) && TARGET_OS_IPHONE + ios::ReleaseAllAccess(); +#endif + // Erase the sources. g_installerSources.game.reset(); g_installerSources.update.reset(); g_installerSources.dlc.clear(); - + // Make sure the GPU is not currently active before deleting these textures. Video::WaitForGPU(); @@ -1846,10 +1991,15 @@ void InstallerWizard::Shutdown() bool InstallerWizard::Run(std::filesystem::path installPath, bool skipGame) { + os::logger::Log(fmt::format("InstallerWizard::Run start - installPath: {}, skipGame: {}", (const char*)installPath.u8string().c_str(), skipGame)); g_installPath = installPath; EmbeddedPlayer::Init(); + os::logger::Log("InstallerWizard::Run - EmbeddedPlayer::Init completed"); +#ifndef UNLEASHED_RECOMP_IOS NFD_Init(); + os::logger::Log("InstallerWizard::Run - NFD_Init completed"); +#endif // Guarantee one controller is initialized. We'll rely on SDL's event loop to get the controller events. XAMINPUT_STATE inputState; @@ -1868,19 +2018,35 @@ bool InstallerWizard::Run(std::filesystem::path installPath, bool skipGame) GameWindow::SetFullscreenCursorVisibility(true); s_isVisible = true; + os::logger::Log("InstallerWizard::Run - entering wizard loop"); + + bool firstFrame = true; while (s_isVisible) { + if (firstFrame) + os::logger::Log("InstallerWizard::Run - first frame: WaitOnSwapChain begin"); Video::WaitOnSwapChain(); + if (firstFrame) + os::logger::Log("InstallerWizard::Run - first frame: WaitOnSwapChain end"); ProcessMusic(); + if (firstFrame) + os::logger::Log("InstallerWizard::Run - first frame: ProcessMusic end"); SDL_PumpEvents(); SDL_FlushEvents(SDL_FIRSTEVENT, SDL_LASTEVENT); GameWindow::Update(); Video::Present(); + if (firstFrame) + { + os::logger::Log("InstallerWizard::Run - first frame: Present end"); + firstFrame = false; + } } GameWindow::SetFullscreenCursorVisibility(false); +#ifndef UNLEASHED_RECOMP_IOS NFD_Quit(); +#endif InstallerWizard::Shutdown(); EmbeddedPlayer::Shutdown(); diff --git a/UnleashedRecomp/ui/options_menu.cpp b/UnleashedRecomp/ui/options_menu.cpp index 33ac5c69..10daefeb 100644 --- a/UnleashedRecomp/ui/options_menu.cpp +++ b/UnleashedRecomp/ui/options_menu.cpp @@ -100,6 +100,9 @@ static bool g_canReset = false; static bool g_isLanguageOptionChanged = false; static bool g_titleAnimBegin = true; static EChannelConfiguration g_currentChannelConfig; +#ifdef __APPLE__ +static bool g_currentShowMetalHUD; +#endif static double g_appearTime = 0.0; @@ -199,7 +202,7 @@ static void DrawTitle() rectX += rectSize + (rectSize * 0.25f); isRectFinalAdjustment = true; } - + isRectVisible = !isRectVisible; rectBlinkMotionOffset += squareBlinkDuration; } @@ -331,18 +334,18 @@ static void DrawScanlineBars() drawList->AddRectFilledMultiColor( { 0.0f, y - Scale(2.0f) }, - { res.x, y }, + { res.x, y }, + top ? TOP_COLOR0 : BOTTOM_COLOR1, top ? TOP_COLOR0 : BOTTOM_COLOR1, - top ? TOP_COLOR0 : BOTTOM_COLOR1, top ? TOP_COLOR1 : BOTTOM_COLOR0, top ? TOP_COLOR1 : BOTTOM_COLOR0); drawList->AddRectFilledMultiColor( - { 0.0f, y + Scale(1.0f) }, - { res.x, y + Scale(3.0f) }, - top ? BOTTOM_COLOR0 : TOP_COLOR1, + { 0.0f, y + Scale(1.0f) }, + { res.x, y + Scale(3.0f) }, + top ? BOTTOM_COLOR0 : TOP_COLOR1, top ? BOTTOM_COLOR0 : TOP_COLOR1, - top ? BOTTOM_COLOR1 : TOP_COLOR0, + top ? BOTTOM_COLOR1 : TOP_COLOR0, top ? BOTTOM_COLOR1 : TOP_COLOR0); constexpr uint32_t CENTER_COLOR = IM_COL32(115, 178, 104, 255); @@ -528,7 +531,7 @@ static bool DrawCategories() float animWidth = g_categoryAnimMax.x - g_categoryAnimMin.x; float width = max.x - min.x; float height = max.y - min.y; - + animWidth = Lerp(animWidth, width, 1.0f - exp(-64.0f * ImGui::GetIO().DeltaTime)); auto center = Lerp(min, max, 0.5f); @@ -549,14 +552,14 @@ static bool DrawCategories() g_categoryAnimMin, g_categoryAnimMax, IM_COL32(0, 130, 0, 223 * motion), - IM_COL32(0, 130, 0, 178 * motion), + IM_COL32(0, 130, 0, 178 * motion), IM_COL32(0, 130, 0, 223 * motion), IM_COL32(0, 130, 0, 178 * motion) ); drawList->AddRectFilledMultiColor ( - g_categoryAnimMin, + g_categoryAnimMin, g_categoryAnimMax, IM_COL32(0, 0, 0, 13 * motion), IM_COL32(0, 0, 0, 0), @@ -566,11 +569,11 @@ static bool DrawCategories() drawList->AddRectFilledMultiColor ( - g_categoryAnimMin, + g_categoryAnimMin, g_categoryAnimMax, IM_COL32(0, 130, 0, 13 * motion), IM_COL32(0, 130, 0, 111 * motion), - IM_COL32(0, 130, 0, 0), + IM_COL32(0, 130, 0, 0), IM_COL32(0, 130, 0, 55 * motion) ); @@ -588,7 +591,7 @@ static bool DrawCategories() { auto& pos = textPositions[i]; uint8_t alpha = (i == g_categoryIndex ? 235 : 128) * motion; - + SetOrigin({ pos.x, pos.y }); SetGradient ( @@ -1102,7 +1105,7 @@ static void DrawConfigOption(int32_t rowIndex, float yOffset, ConfigDef* conf bool isConfigValueInBounds = config->Value >= valueMin && config->Value <= valueMax; - if ((increment || decrement) && isConfigValueInBounds && isPlayIncrementSound) + if ((increment || decrement) && isConfigValueInBounds && isPlayIncrementSound) { g_lastIncrementSoundTime = time; Game_PlaySound("sys_actstg_twn_speechbutton"); @@ -1282,6 +1285,7 @@ static void DrawConfigOptions() DrawConfigOption(rowCount++, yOffset, &Config::XboxColorCorrection, true); DrawConfigOption(rowCount++, yOffset, &Config::CutsceneAspectRatio, true); DrawConfigOption(rowCount++, yOffset, &Config::UIAlignmentMode, true); + DrawConfigOption(rowCount++, yOffset, &Config::ShowMetalHUD, true); break; } @@ -1533,7 +1537,7 @@ static void DrawInfoPanel(ImVec2 infoMin, ImVec2 infoMax) clipRectMax.x += annotationFontSize; textY += annotationFontSize; - + // Dirty hack to disallow clipping on Japanese text // whilst allowing annotations to go over the border lineWidth -= annotationFontSize; @@ -1554,7 +1558,7 @@ static void DrawInfoPanel(ImVec2 infoMin, ImVec2 infoMax) if (scrollMax > 0.0f) { auto vert = -g_rightStickY; - + if (fabs(vert) > 0.25f) { isManualScrolling = true; @@ -1567,21 +1571,21 @@ static void DrawInfoPanel(ImVec2 infoMin, ImVec2 infoMax) scrollTimer = 0.0f; scrollDirection = vert > 0.0f ? 1.0f : -1.0f; } - + if (!isManualScrolling) { if (!isScrolling) { scrollTimer += App::s_deltaTime; - + if (scrollTimer >= INFO_TEXT_MARQUEE_DELAY) isScrolling = true; } - + if (isScrolling) { scrollOffset += scrollSpeed * scrollDirection * App::s_deltaTime; - + if (scrollOffset >= scrollMax) { isScrolling = false; @@ -1598,7 +1602,7 @@ static void DrawInfoPanel(ImVec2 infoMin, ImVec2 infoMax) } } } - + scrollOffset = std::clamp(scrollOffset, 0.0f, scrollMax); } else @@ -1670,7 +1674,7 @@ static bool DrawMilesElectric() { if (g_isClosing) SetOptionsMenuVisible(false); - + return true; } @@ -1789,7 +1793,12 @@ void OptionsMenu::Draw() DrawFadeTransition(); } - s_isRestartRequired = Config::Language != App::s_language || Config::ChannelConfiguration != g_currentChannelConfig; + s_isRestartRequired = Config::Language != App::s_language + || Config::ChannelConfiguration != g_currentChannelConfig + #ifdef __APPLE__ + || Config::ShowMetalHUD != g_currentShowMetalHUD + #endif + ; } void OptionsMenu::Open(bool isPause, SWA::EMenuType pauseMenuType) @@ -1798,7 +1807,7 @@ void OptionsMenu::Open(bool isPause, SWA::EMenuType pauseMenuType) s_isPause = isPause; s_pauseMenuType = pauseMenuType; g_isStage = isPause && pauseMenuType != SWA::eMenuType_WorldMap; - + g_appearTime = ImGui::GetTime(); g_categoryIndex = 0; g_categoryAnimMin = { 0.0f, 0.0f }; @@ -1806,6 +1815,9 @@ void OptionsMenu::Open(bool isPause, SWA::EMenuType pauseMenuType) g_selectedItem = nullptr; g_titleAnimBegin = true; g_currentChannelConfig = Config::ChannelConfiguration; +#if defined(__APPLE__) + g_currentShowMetalHUD = Config::ShowMetalHUD; +#endif /* Store button state so we can track it later and prevent the first item being selected. */ @@ -1822,7 +1834,7 @@ void OptionsMenu::Open(bool isPause, SWA::EMenuType pauseMenuType) Button("Common_Select", 115.0f, EButtonIcon::A, &g_isControlsVisible), Button("Common_Back", 65.0f, EButtonIcon::B, &g_isControlsVisible) }; - + ButtonGuide::Open(buttons); ButtonGuide::SetSideMargins(250); diff --git a/UnleashedRecomp/ui/touch_controls.cpp b/UnleashedRecomp/ui/touch_controls.cpp new file mode 100644 index 00000000..8df51bb2 --- /dev/null +++ b/UnleashedRecomp/ui/touch_controls.cpp @@ -0,0 +1,923 @@ +#include "touch_controls.h" +#include "installer_wizard.h" +#include "imgui_utils.h" +#include +#include +#include +#include +#include +#include +#include + +#if defined(__APPLE__) +#include +#endif + +#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE +#include "touch_haptics.h" +#define TOUCH_CONTROLS_SUPPORTED 1 +#else +#define TOUCH_CONTROLS_SUPPORTED 0 +#endif + +// Layout frames and tuning values match the XeniOS defaults (https://github.com/xenios-jp/XeniOS/src/xenia/hid/touch). +static constexpr float STICK_DEADZONE = 0.14f; +static constexpr float STICK_ACTIVATION_RADIUS = 0.48f; +static constexpr float STICK_DPAD_RING_RADIUS = 0.32f; +static constexpr float LOOK_POINTS_PER_FULL_SCALE = 4.0f; +static constexpr float LOOK_VERTICAL_SCALE = 1.2f; +static constexpr double LOOK_HOLD_SECONDS = 0.10; +static constexpr double BUTTON_TAP_HOLD_SECONDS = 0.10; + +// Horizontal margin kept free on wide screens so controls stay clear of the notch and rounded corners. +static constexpr float WIDE_SCREEN_SAFE_MARGIN = 0.055f; + +// Layout editor limits, in layout space. +static constexpr float EDIT_MIN_SIZE = 0.04f; +static constexpr float EDIT_MAX_SIZE = 0.45f; +static constexpr float EDIT_SIZE_STEP = 1.1f; +static constexpr float EDIT_OPACITY_STEP = 0.1f; +static constexpr float EDIT_MIN_OPACITY = 0.1f; + +static constexpr const char* LAYOUT_FILE_NAME = "touch_layout.toml"; + +struct TouchRect +{ + float x, y, width, height; +}; + +enum class TouchControlKind +{ + Stick, + Button +}; + +struct TouchControl +{ + TouchControlKind kind; + const char* id; + const char* label; + TouchRect frame; // Default frame, normalised to the layout space. + uint16_t buttons; + uint8_t leftTrigger; + uint8_t rightTrigger; +}; + +// Default frames come from the XeniOS default layout, with its actions mapped to their gamepad equivalents. +static const TouchControl g_controls[] = +{ + { TouchControlKind::Stick, "stick", nullptr, { 0.055f, 0.560f, 0.190f, 0.315f }, 0, 0, 0 }, + { TouchControlKind::Button, "back", "BACK", { 0.390f, 0.045f, 0.080f, 0.112f }, XAMINPUT_GAMEPAD_BACK, 0, 0 }, + { TouchControlKind::Button, "start", "START", { 0.495f, 0.045f, 0.085f, 0.112f }, XAMINPUT_GAMEPAD_START, 0, 0 }, + { TouchControlKind::Button, "lb", "LB", { 0.660f, 0.050f, 0.085f, 0.112f }, XAMINPUT_GAMEPAD_LEFT_SHOULDER, 0, 0 }, + { TouchControlKind::Button, "rb", "RB", { 0.765f, 0.050f, 0.085f, 0.112f }, XAMINPUT_GAMEPAD_RIGHT_SHOULDER, 0, 0 }, + { TouchControlKind::Button, "lt", "LT", { 0.095f, 0.405f, 0.120f, 0.110f }, 0, 0xFF, 0 }, + { TouchControlKind::Button, "rt", "RT", { 0.860f, 0.405f, 0.120f, 0.110f }, 0, 0, 0xFF }, + { TouchControlKind::Button, "y", "Y", { 0.760f, 0.455f, 0.065f, 0.115f }, XAMINPUT_GAMEPAD_Y, 0, 0 }, + { TouchControlKind::Button, "x", "X", { 0.700f, 0.585f, 0.065f, 0.115f }, XAMINPUT_GAMEPAD_X, 0, 0 }, + { TouchControlKind::Button, "b", "B", { 0.820f, 0.585f, 0.065f, 0.115f }, XAMINPUT_GAMEPAD_B, 0, 0 }, + { TouchControlKind::Button, "a", "A", { 0.760f, 0.715f, 0.065f, 0.115f }, XAMINPUT_GAMEPAD_A, 0, 0 }, +}; + +static constexpr size_t CONTROL_COUNT = std::size(g_controls); + +// The button that opens the layout editor. It isn't part of the editable layout. +static constexpr TouchRect EDIT_BUTTON_FRAME = { 0.290f, 0.045f, 0.075f, 0.112f }; + +struct LayoutEntry +{ + TouchRect frame; + bool hidden; +}; + +static LayoutEntry g_layout[CONTROL_COUNT]; + +enum class EditorAction +{ + Smaller, + Bigger, + ToggleHidden, + LessOpaque, + MoreOpaque, + Reset, + Done +}; + +struct EditorButton +{ + EditorAction action; + const char* label; +}; + +static const EditorButton g_editorButtons[] = +{ + { EditorAction::Smaller, "SIZE -" }, + { EditorAction::Bigger, "SIZE +" }, + { EditorAction::ToggleHidden, "HIDE" }, + { EditorAction::LessOpaque, "ALPHA -" }, + { EditorAction::MoreOpaque, "ALPHA +" }, + { EditorAction::Reset, "RESET" }, + { EditorAction::Done, "DONE" }, +}; + +static constexpr size_t EDITOR_BUTTON_COUNT = std::size(g_editorButtons); + +// Special capture targets besides the layout's controls. +static constexpr int LOOK_ZONE = -1; +static constexpr int EDIT_BUTTON = -2; +static constexpr int EDITOR_TOOLBAR = -3; +static constexpr int EDITOR_EMPTY = -4; + +enum class StickZone +{ + Stick, + DpadUp, + DpadDown, + DpadLeft, + DpadRight +}; + +struct TouchCapture +{ + SDL_FingerID fingerId; + int control; + StickZone stickZone; + ImVec2 anchor; // Window points. + ImVec2 current; // Window points. + TouchRect frameAtAnchor; // Layout space, used when dragging in the editor. +}; + +static std::mutex g_mutex; +static std::vector g_captures; +static double g_buttonPressTimes[CONTROL_COUNT]; +static ImVec2 g_lookVector; +static double g_lookTime = -1.0; +static ImVec2 g_windowSize{ 1.0f, 1.0f }; +static std::atomic g_hiddenByController; +static std::atomic g_isEditing; +static int g_selectedControl = -1; +static ImFont* g_font; + +static double GetTime() +{ + return double(SDL_GetPerformanceCounter()) / double(SDL_GetPerformanceFrequency()); +} + +static bool IsEnabled() +{ +#if TOUCH_CONTROLS_SUPPORTED + return Config::TouchControls && !InstallerWizard::s_isVisible; +#else + return false; +#endif +} + +static std::filesystem::path GetLayoutPath() +{ + return GetUserPath() / LAYOUT_FILE_NAME; +} + +static void ResetLayout() +{ + for (size_t i = 0; i < CONTROL_COUNT; i++) + g_layout[i] = { g_controls[i].frame, false }; +} + +static void LoadLayout() +{ + ResetLayout(); + + std::error_code ec; + if (!std::filesystem::exists(GetLayoutPath(), ec)) + return; + + try + { + std::ifstream stream(GetLayoutPath()); + toml::table table = toml::parse(stream); + + for (size_t i = 0; i < CONTROL_COUNT; i++) + { + auto entry = table[g_controls[i].id]; + if (!entry.is_table()) + continue; + + TouchRect& frame = g_layout[i].frame; + frame.x = std::clamp(entry["x"].value_or(frame.x), 0.0f, 1.0f); + frame.y = std::clamp(entry["y"].value_or(frame.y), 0.0f, 1.0f); + frame.width = std::clamp(entry["width"].value_or(frame.width), EDIT_MIN_SIZE, EDIT_MAX_SIZE); + frame.height = std::clamp(entry["height"].value_or(frame.height), EDIT_MIN_SIZE, EDIT_MAX_SIZE); + g_layout[i].hidden = entry["hidden"].value_or(false); + } + } + catch (toml::parse_error& err) + { + LOGFN_ERROR("Failed to parse touch layout: {}", err.what()); + ResetLayout(); + } +} + +static void SaveLayout() +{ + toml::table table; + + for (size_t i = 0; i < CONTROL_COUNT; i++) + { + const LayoutEntry& entry = g_layout[i]; + + table.insert(g_controls[i].id, toml::table + { + { "x", entry.frame.x }, + { "y", entry.frame.y }, + { "width", entry.frame.width }, + { "height", entry.frame.height }, + { "hidden", entry.hidden } + }); + } + + std::ofstream stream(GetLayoutPath()); + if (stream.is_open()) + stream << table; + else + LOGN_ERROR("Failed to save touch layout."); +} + +static TouchRect GetLayoutSpace(ImVec2 size) +{ + float margin = (size.x / size.y) > 1.9f ? size.x * WIDE_SCREEN_SAFE_MARGIN : 0.0f; + return { margin, 0.0f, size.x - margin * 2.0f, size.y }; +} + +// Resolves a frame in layout space to window points. +static TouchRect ToWindowFrame(const TouchRect& frame, ImVec2 size) +{ + TouchRect space = GetLayoutSpace(size); + + return + { + space.x + frame.x * space.width, + space.y + frame.y * space.height, + frame.width * space.width, + frame.height * space.height + }; +} + +static TouchRect GetControlFrame(size_t index) +{ + return ToWindowFrame(g_layout[index].frame, g_windowSize); +} + +// The editor toolbar runs along the bottom of the screen, in window points. +static TouchRect GetEditorButtonFrame(size_t index) +{ + TouchRect space = GetLayoutSpace(g_windowSize); + float spacing = space.width * 0.01f; + float width = (space.width * 0.9f - spacing * float(EDITOR_BUTTON_COUNT - 1)) / float(EDITOR_BUTTON_COUNT); + float height = g_windowSize.y * 0.11f; + float startX = space.x + space.width * 0.05f; + + return { startX + float(index) * (width + spacing), g_windowSize.y * 0.86f, width, height }; +} + +static ImVec2 GetCentre(const TouchRect& rect) +{ + return { rect.x + rect.width * 0.5f, rect.y + rect.height * 0.5f }; +} + +static float GetRadius(const TouchRect& rect) +{ + return std::min(rect.width, rect.height) * 0.5f; +} + +static bool RectContainsPoint(const TouchRect& rect, ImVec2 point) +{ + return point.x >= rect.x && point.x <= rect.x + rect.width && + point.y >= rect.y && point.y <= rect.y + rect.height; +} + +// Buttons are pills: circles, stretched along their longer side. +static bool PillContainsPoint(const TouchRect& frame, ImVec2 point) +{ + float radius = GetRadius(frame); + ImVec2 centre = GetCentre(frame); + float halfSpanX = std::max(frame.width * 0.5f - radius, 0.0f); + float halfSpanY = std::max(frame.height * 0.5f - radius, 0.0f); + float dx = std::max(std::abs(point.x - centre.x) - halfSpanX, 0.0f); + float dy = std::max(std::abs(point.y - centre.y) - halfSpanY, 0.0f); + return dx * dx + dy * dy <= radius * radius; +} + +static bool ControlContainsPoint(size_t index, ImVec2 point) +{ + TouchRect frame = GetControlFrame(index); + + if (g_controls[index].kind == TouchControlKind::Stick) + return RectContainsPoint(frame, point); + + return PillContainsPoint(frame, point); +} + +static StickZone GetStickZone(const TouchRect& frame, ImVec2 point) +{ + ImVec2 centre = GetCentre(frame); + float stickRadius = std::min(frame.width, frame.height) * STICK_DPAD_RING_RADIUS; + float dx = point.x - centre.x; + float dy = point.y - centre.y; + + if (dx * dx + dy * dy <= stickRadius * stickRadius) + return StickZone::Stick; + + if (std::abs(dx) > std::abs(dy)) + return dx > 0.0f ? StickZone::DpadRight : StickZone::DpadLeft; + + return dy > 0.0f ? StickZone::DpadDown : StickZone::DpadUp; +} + +// Returns the stick deflection for a capture, with Y pointing down. +static ImVec2 GetStickVector(const TouchRect& frame, const TouchCapture& capture) +{ + float outerRadius = std::min(frame.width, frame.height) * STICK_ACTIVATION_RADIUS; + ImVec2 delta = { capture.current.x - capture.anchor.x, capture.current.y - capture.anchor.y }; + float distance = std::hypot(delta.x, delta.y); + + if (distance > outerRadius && distance > 0.0f) + { + delta.x *= outerRadius / distance; + delta.y *= outerRadius / distance; + } + + ImVec2 normalised = { delta.x / outerRadius, delta.y / outerRadius }; + float magnitude = std::hypot(normalised.x, normalised.y); + + if (magnitude < STICK_DEADZONE || magnitude <= 0.0f) + return {}; + + float rescaled = std::clamp((magnitude - STICK_DEADZONE) / (1.0f - STICK_DEADZONE), 0.0f, 1.0f); + return { normalised.x / magnitude * rescaled, normalised.y / magnitude * rescaled }; +} + +static int16_t ToAxis(float value) +{ + return int16_t(std::lround(std::clamp(value, -1.0f, 1.0f) * 32767.0f)); +} + +static void MergeAxis(int16_t& target, int16_t value) +{ + if (std::abs(int(value)) > std::abs(int(target))) + target = value; +} + +static int FindControlAtPoint(ImVec2 point, bool includeHidden) +{ + // Buttons take priority over the stick. + for (int pass = 0; pass < 2; pass++) + { + TouchControlKind kind = pass == 0 ? TouchControlKind::Button : TouchControlKind::Stick; + + for (size_t i = 0; i < CONTROL_COUNT; i++) + { + if (g_controls[i].kind == kind && (includeHidden || !g_layout[i].hidden) && ControlContainsPoint(i, point)) + return int(i); + } + } + + return -1; +} + +static void PlayHaptic(bool light) +{ +#if TOUCH_CONTROLS_SUPPORTED + TouchHaptics::Play(light); +#endif +} + +static void ClampToLayout(TouchRect& frame) +{ + frame.width = std::clamp(frame.width, EDIT_MIN_SIZE, EDIT_MAX_SIZE); + frame.height = std::clamp(frame.height, EDIT_MIN_SIZE, EDIT_MAX_SIZE); + frame.x = std::clamp(frame.x, 0.0f, 1.0f - frame.width); + frame.y = std::clamp(frame.y, 0.0f, 1.0f - frame.height); +} + +static void ApplyEditorAction(EditorAction action) +{ + switch (action) + { + case EditorAction::Smaller: + case EditorAction::Bigger: + { + if (g_selectedControl < 0) + break; + + TouchRect& frame = g_layout[g_selectedControl].frame; + ImVec2 centre = GetCentre(frame); + float scale = action == EditorAction::Bigger ? EDIT_SIZE_STEP : 1.0f / EDIT_SIZE_STEP; + float newWidth = frame.width * scale; + float newHeight = frame.height * scale; + + // Stop at the limits instead of clamping one side, so the control keeps its shape. + if (newWidth < EDIT_MIN_SIZE || newHeight < EDIT_MIN_SIZE || newWidth > EDIT_MAX_SIZE || newHeight > EDIT_MAX_SIZE) + break; + + frame = { centre.x - newWidth * 0.5f, centre.y - newHeight * 0.5f, newWidth, newHeight }; + ClampToLayout(frame); + break; + } + + case EditorAction::ToggleHidden: + { + if (g_selectedControl >= 0) + g_layout[g_selectedControl].hidden = !g_layout[g_selectedControl].hidden; + + break; + } + + case EditorAction::LessOpaque: + case EditorAction::MoreOpaque: + { + float step = action == EditorAction::MoreOpaque ? EDIT_OPACITY_STEP : -EDIT_OPACITY_STEP; + Config::TouchControlsOpacity = std::clamp(Config::TouchControlsOpacity + step, EDIT_MIN_OPACITY, 1.0f); + break; + } + + case EditorAction::Reset: + { + ResetLayout(); + Config::TouchControlsOpacity = 1.0f; + break; + } + + case EditorAction::Done: + { + SaveLayout(); + Config::Save(); + g_isEditing = false; + g_selectedControl = -1; + g_captures.clear(); + break; + } + } +} + +static void OnEditorFingerDown(TouchCapture& capture, ImVec2 point) +{ + for (size_t i = 0; i < EDITOR_BUTTON_COUNT; i++) + { + if (RectContainsPoint(GetEditorButtonFrame(i), point)) + { + capture.control = EDITOR_TOOLBAR; + PlayHaptic(false); + ApplyEditorAction(g_editorButtons[i].action); + return; + } + } + + int control = FindControlAtPoint(point, true); + if (control >= 0) + { + capture.control = control; + capture.frameAtAnchor = g_layout[control].frame; + g_selectedControl = control; + PlayHaptic(true); + } + else + { + capture.control = EDITOR_EMPTY; + g_selectedControl = -1; + } +} + +static void OnEditorFingerMotion(TouchCapture& capture) +{ + if (capture.control < 0) + return; + + TouchRect space = GetLayoutSpace(g_windowSize); + TouchRect& frame = g_layout[capture.control].frame; + + frame.x = capture.frameAtAnchor.x + (capture.current.x - capture.anchor.x) / space.width; + frame.y = capture.frameAtAnchor.y + (capture.current.y - capture.anchor.y) / space.height; + ClampToLayout(frame); +} + +static void OnGameplayFingerDown(TouchCapture& capture, ImVec2 point) +{ + if (RectContainsPoint(ToWindowFrame(EDIT_BUTTON_FRAME, g_windowSize), point)) + { + capture.control = EDIT_BUTTON; + g_isEditing = true; + g_selectedControl = -1; + PlayHaptic(false); + return; + } + + capture.control = FindControlAtPoint(point, false); + + if (capture.control < 0) + { + capture.control = LOOK_ZONE; + return; + } + + const TouchControl& control = g_controls[capture.control]; + + if (control.kind == TouchControlKind::Stick) + { + capture.stickZone = GetStickZone(GetControlFrame(capture.control), point); + PlayHaptic(true); + } + else + { + g_buttonPressTimes[capture.control] = GetTime(); + PlayHaptic(false); + } +} + +static int TouchControls_OnSDLEvent(void*, SDL_Event* event) +{ + if (event->type != SDL_FINGERDOWN && event->type != SDL_FINGERMOTION && event->type != SDL_FINGERUP) + return 0; + + std::lock_guard lock(g_mutex); + + if (!IsEnabled()) + { + g_captures.clear(); + return 0; + } + + int windowWidth = 0; + int windowHeight = 0; + SDL_GetWindowSize(GameWindow::s_pWindow, &windowWidth, &windowHeight); + + if (windowWidth > 0 && windowHeight > 0) + g_windowSize = { float(windowWidth), float(windowHeight) }; + + ImVec2 point = { event->tfinger.x * g_windowSize.x, event->tfinger.y * g_windowSize.y }; + auto capture = std::find_if(g_captures.begin(), g_captures.end(), [&](const TouchCapture& c) { return c.fingerId == event->tfinger.fingerId; }); + + switch (event->type) + { + case SDL_FINGERDOWN: + { + g_hiddenByController = false; + + if (!App::s_isLoading) + { + // Show Xbox button prompts, matching the on-screen labels. + hid::g_inputDevice = hid::EInputDevice::Xbox; + hid::g_inputDeviceController = hid::EInputDevice::Xbox; + } + + if (capture != g_captures.end()) + g_captures.erase(capture); + + TouchCapture newCapture{}; + newCapture.fingerId = event->tfinger.fingerId; + newCapture.anchor = point; + newCapture.current = point; + + if (g_isEditing) + OnEditorFingerDown(newCapture, point); + else + OnGameplayFingerDown(newCapture, point); + + // Pressing DONE clears the captures, so don't track that touch any further. + if (g_isEditing || newCapture.control != EDITOR_TOOLBAR) + g_captures.push_back(newCapture); + + break; + } + + case SDL_FINGERMOTION: + { + if (capture == g_captures.end()) + break; + + capture->current = point; + + if (g_isEditing) + { + OnEditorFingerMotion(*capture); + } + else if (capture->control == LOOK_ZONE) + { + float deltaX = event->tfinger.dx * g_windowSize.x; + float deltaY = event->tfinger.dy * g_windowSize.y; + + g_lookVector = + { + std::clamp(deltaX / LOOK_POINTS_PER_FULL_SCALE, -1.0f, 1.0f), + std::clamp(-deltaY / LOOK_POINTS_PER_FULL_SCALE * LOOK_VERTICAL_SCALE, -1.0f, 1.0f) + }; + + g_lookTime = GetTime(); + } + + break; + } + + case SDL_FINGERUP: + { + if (capture != g_captures.end()) + g_captures.erase(capture); + + break; + } + } + + return 0; +} + +void TouchControls::Init() +{ + g_font = ImFontAtlasSnapshot::GetFont("FOT-NewRodinPro-M.otf"); + +#if TOUCH_CONTROLS_SUPPORTED + { + std::lock_guard lock(g_mutex); + LoadLayout(); + } + + TouchHaptics::Init(); + SDL_AddEventWatch(TouchControls_OnSDLEvent, nullptr); +#endif +} + +bool TouchControls::IsActive() +{ + return IsEnabled() && !g_hiddenByController; +} + +void TouchControls::OnPhysicalControllerInput() +{ + std::lock_guard lock(g_mutex); + + // Keep the overlay up while its layout is being edited. + if (g_isEditing) + return; + + g_hiddenByController = true; + g_captures.clear(); + g_lookTime = -1.0; +} + +void TouchControls::Apply(XAMINPUT_GAMEPAD& pad) +{ + // No game input while the layout is being edited. + if (!IsActive() || g_isEditing) + return; + + std::lock_guard lock(g_mutex); + + double time = GetTime(); + uint16_t buttons = 0; + uint8_t leftTrigger = 0; + uint8_t rightTrigger = 0; + int16_t leftX = 0; + int16_t leftY = 0; + int16_t rightX = 0; + int16_t rightY = 0; + + for (auto& capture : g_captures) + { + if (capture.control < 0) + continue; + + const TouchControl& control = g_controls[capture.control]; + + if (control.kind == TouchControlKind::Stick) + { + switch (capture.stickZone) + { + case StickZone::DpadUp: buttons |= XAMINPUT_GAMEPAD_DPAD_UP; break; + case StickZone::DpadDown: buttons |= XAMINPUT_GAMEPAD_DPAD_DOWN; break; + case StickZone::DpadLeft: buttons |= XAMINPUT_GAMEPAD_DPAD_LEFT; break; + case StickZone::DpadRight: buttons |= XAMINPUT_GAMEPAD_DPAD_RIGHT; break; + + case StickZone::Stick: + { + ImVec2 vector = GetStickVector(GetControlFrame(capture.control), capture); + leftX = ToAxis(vector.x); + leftY = ToAxis(-vector.y); + break; + } + } + } + else if (ControlContainsPoint(capture.control, capture.current)) + { + buttons |= control.buttons; + leftTrigger = std::max(leftTrigger, control.leftTrigger); + rightTrigger = std::max(rightTrigger, control.rightTrigger); + } + } + + // Keep quick taps pressed for long enough that the game sees them even at low frame rates. + for (size_t i = 0; i < CONTROL_COUNT; i++) + { + if (g_controls[i].kind == TouchControlKind::Button && (time - g_buttonPressTimes[i]) < BUTTON_TAP_HOLD_SECONDS) + { + buttons |= g_controls[i].buttons; + leftTrigger = std::max(leftTrigger, g_controls[i].leftTrigger); + rightTrigger = std::max(rightTrigger, g_controls[i].rightTrigger); + } + } + + // Swipes produce a short look impulse that fades out, so the camera stops when the finger does. + if (g_lookTime >= 0.0) + { + double age = time - g_lookTime; + + if (age < LOOK_HOLD_SECONDS) + { + float decay = float(1.0 - age / LOOK_HOLD_SECONDS); + rightX = ToAxis(g_lookVector.x * decay); + rightY = ToAxis(g_lookVector.y * decay); + } + } + + pad.wButtons |= buttons; + pad.bLeftTrigger = std::max(pad.bLeftTrigger, leftTrigger); + pad.bRightTrigger = std::max(pad.bRightTrigger, rightTrigger); + MergeAxis(pad.sThumbLX, leftX); + MergeAxis(pad.sThumbLY, leftY); + MergeAxis(pad.sThumbRX, rightX); + MergeAxis(pad.sThumbRY, rightY); +} + +void TouchControls::Draw(float swapChainWidth, float swapChainHeight, float viewportOffsetX, float viewportOffsetY) +{ + if (!IsActive()) + return; + + std::lock_guard lock(g_mutex); + + auto drawList = ImGui::GetBackgroundDrawList(); + float scale = swapChainWidth / g_windowSize.x; + float opacity = std::clamp(Config::TouchControlsOpacity.Value, 0.0f, 1.0f); + float borderWidth = std::max(1.5f * scale, 1.0f); + bool isEditing = g_isEditing; + + auto toScreen = [&](ImVec2 point) + { + return ImVec2(point.x * scale - viewportOffsetX, point.y * scale - viewportOffsetY); + }; + + // White with the given alpha, scaled by the opacity setting unless told otherwise. + auto white = [&](float alpha, bool applyOpacity = true) + { + float finalAlpha = std::clamp(applyOpacity ? alpha * opacity : alpha, 0.0f, 1.0f); + return IM_COL32(255, 255, 255, int(finalAlpha * 255.0f)); + }; + + auto drawLabel = [&](const char* text, ImVec2 centre, float fontSize, ImU32 colour) + { + if (g_font == nullptr) + return; + + ImVec2 textSize = g_font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, text); + drawList->AddText(g_font, fontSize, { centre.x - textSize.x * 0.5f, centre.y - textSize.y * 0.5f }, colour, text); + }; + + auto drawPill = [&](const TouchRect& frame, ImU32 fill, ImU32 border) + { + ImVec2 min = toScreen({ frame.x, frame.y }); + ImVec2 max = toScreen({ frame.x + frame.width, frame.y + frame.height }); + float rounding = GetRadius(frame) * scale; + + drawList->AddRectFilled(min, max, fill, rounding); + drawList->AddRect(min, max, border, rounding, 0, borderWidth); + }; + + auto isControlHeld = [&](size_t index) + { + return std::any_of(g_captures.begin(), g_captures.end(), [&](const TouchCapture& c) { return c.control == int(index); }); + }; + + if (isEditing) + { + // Dim the game so it's clear the controls are being edited, not played. + drawList->AddRectFilled(toScreen({ 0.0f, 0.0f }), toScreen(g_windowSize), IM_COL32(0, 0, 0, 110)); + drawLabel("Drag controls to move them. Tap one to select it.", toScreen({ g_windowSize.x * 0.5f, g_windowSize.y * 0.79f }), g_windowSize.y * 0.045f * scale, IM_COL32(255, 255, 255, 230)); + } + else + { + TouchRect frame = ToWindowFrame(EDIT_BUTTON_FRAME, g_windowSize); + drawPill(frame, white(0.08f), white(0.32f)); + drawLabel("EDIT", toScreen(GetCentre(frame)), std::min(frame.width, frame.height) * 0.30f * scale, white(0.85f)); + } + + for (size_t i = 0; i < CONTROL_COUNT; i++) + { + const TouchControl& control = g_controls[i]; + const LayoutEntry& entry = g_layout[i]; + + if (entry.hidden && !isEditing) + continue; + + TouchRect frame = GetControlFrame(i); + ImVec2 centre = toScreen(GetCentre(frame)); + bool held = !isEditing && isControlHeld(i); + bool selected = isEditing && int(i) == g_selectedControl; + + // Hidden controls stay faintly visible in the editor so they can be shown again. + float alphaScale = entry.hidden ? 0.35f : 1.0f; + + if (control.kind == TouchControlKind::Stick) + { + float radius = GetRadius(frame) * scale; + float ringRadius = std::min(frame.width, frame.height) * STICK_DPAD_RING_RADIUS * scale; + + drawList->AddCircleFilled(centre, radius, white(0.10f * alphaScale), 48); + drawList->AddCircle(centre, radius, white(0.38f * alphaScale), 48, borderWidth); + drawList->AddCircle(centre, ringRadius, white(0.20f * alphaScale), 48, borderWidth); + + // D-Pad arrows on the outer ring. + float arrowDistance = (radius + ringRadius) * 0.5f; + float arrowSize = (radius - ringRadius) * 0.3f; + const ImVec2 directions[] = { { 0.0f, -1.0f }, { 0.0f, 1.0f }, { -1.0f, 0.0f }, { 1.0f, 0.0f } }; + const StickZone zones[] = { StickZone::DpadUp, StickZone::DpadDown, StickZone::DpadLeft, StickZone::DpadRight }; + + for (size_t d = 0; d < 4; d++) + { + bool pressed = !isEditing && std::any_of(g_captures.begin(), g_captures.end(), [&](const TouchCapture& c) { return c.control == int(i) && c.stickZone == zones[d]; }); + ImVec2 dir = directions[d]; + ImVec2 tip = { centre.x + dir.x * (arrowDistance + arrowSize), centre.y + dir.y * (arrowDistance + arrowSize) }; + ImVec2 base = { centre.x + dir.x * (arrowDistance - arrowSize), centre.y + dir.y * (arrowDistance - arrowSize) }; + ImVec2 side = { -dir.y * arrowSize, dir.x * arrowSize }; + + drawList->AddTriangleFilled(tip, { base.x + side.x, base.y + side.y }, { base.x - side.x, base.y - side.y }, white((pressed ? 0.85f : 0.45f) * alphaScale)); + } + + // Knob follows the finger while the stick is held. + ImVec2 knob = centre; + for (auto& capture : g_captures) + { + if (!isEditing && capture.control == int(i) && capture.stickZone == StickZone::Stick) + { + float outerRadius = std::min(frame.width, frame.height) * STICK_ACTIVATION_RADIUS; + ImVec2 delta = { capture.current.x - capture.anchor.x, capture.current.y - capture.anchor.y }; + float distance = std::hypot(delta.x, delta.y); + + if (distance > outerRadius && distance > 0.0f) + { + delta.x *= outerRadius / distance; + delta.y *= outerRadius / distance; + } + + knob = { centre.x + delta.x * scale, centre.y + delta.y * scale }; + } + } + + float knobRadius = std::min(frame.width, frame.height) * 0.14f * scale; + drawList->AddCircleFilled(knob, knobRadius, white(0.18f * alphaScale), 32); + drawList->AddCircle(knob, knobRadius, white(0.72f * alphaScale), 32, borderWidth); + + if (selected) + drawList->AddCircle(centre, radius + borderWidth * 3.0f, IM_COL32(255, 200, 40, 255), 48, borderWidth * 2.0f); + } + else + { + drawPill(frame, white((held ? 0.35f : 0.08f) * alphaScale), white((held ? 0.80f : 0.32f) * alphaScale)); + + float fontSize = std::min(frame.width, frame.height) * (strlen(control.label) > 2 ? 0.30f : 0.42f) * scale; + drawLabel(control.label, centre, fontSize, white((held ? 1.0f : 0.85f) * alphaScale)); + + if (selected) + { + float outset = borderWidth * 3.0f / scale; + TouchRect outline = { frame.x - outset, frame.y - outset, frame.width + outset * 2.0f, frame.height + outset * 2.0f }; + ImVec2 min = toScreen({ outline.x, outline.y }); + ImVec2 max = toScreen({ outline.x + outline.width, outline.y + outline.height }); + drawList->AddRect(min, max, IM_COL32(255, 200, 40, 255), GetRadius(outline) * scale, 0, borderWidth * 2.0f); + } + } + } + + if (isEditing) + { + // The toolbar ignores the opacity setting so it's always readable. + for (size_t i = 0; i < EDITOR_BUTTON_COUNT; i++) + { + const EditorButton& button = g_editorButtons[i]; + TouchRect frame = GetEditorButtonFrame(i); + bool needsSelection = button.action == EditorAction::Smaller || button.action == EditorAction::Bigger || button.action == EditorAction::ToggleHidden; + bool enabled = !needsSelection || g_selectedControl >= 0; + bool isDone = button.action == EditorAction::Done; + const char* label = button.label; + + if (button.action == EditorAction::ToggleHidden && g_selectedControl >= 0 && g_layout[g_selectedControl].hidden) + label = "SHOW"; + + ImU32 fill = isDone ? IM_COL32(255, 200, 40, 200) : white(enabled ? 0.25f : 0.08f, false); + ImU32 text = isDone ? IM_COL32(0, 0, 0, 255) : white(enabled ? 1.0f : 0.35f, false); + ImVec2 min = toScreen({ frame.x, frame.y }); + ImVec2 max = toScreen({ frame.x + frame.width, frame.y + frame.height }); + float rounding = frame.height * 0.25f * scale; + + drawList->AddRectFilled(min, max, fill, rounding); + drawList->AddRect(min, max, white(0.6f, false), rounding, 0, borderWidth); + drawLabel(label, toScreen(GetCentre(frame)), frame.height * 0.32f * scale, text); + } + } +} diff --git a/UnleashedRecomp/ui/touch_controls.h b/UnleashedRecomp/ui/touch_controls.h new file mode 100644 index 00000000..5c5c4a32 --- /dev/null +++ b/UnleashedRecomp/ui/touch_controls.h @@ -0,0 +1,22 @@ +#pragma once + +// On-screen touch gamepad, modelled after the default XeniOS layout: +// a movement stick with a D-Pad ring on the left, swipe-to-look anywhere on +// the screen that isn't a control, and face/shoulder/trigger buttons on the right. +namespace TouchControls +{ + void Init(); + + // Draws the overlay. Coordinates are mapped from the window to the ImGui + // viewport, which may be letterboxed inside the swap chain. + void Draw(float swapChainWidth, float swapChainHeight, float viewportOffsetX, float viewportOffsetY); + + // Whether the touch gamepad is on screen and should be reported as a connected controller. + bool IsActive(); + + // Merges the touch gamepad state into a controller state. + void Apply(XAMINPUT_GAMEPAD& pad); + + // Hides the overlay once a physical controller is used. Touching the screen shows it again. + void OnPhysicalControllerInput(); +} diff --git a/UnleashedRecomp/ui/touch_haptics.h b/UnleashedRecomp/ui/touch_haptics.h new file mode 100644 index 00000000..01abed6b --- /dev/null +++ b/UnleashedRecomp/ui/touch_haptics.h @@ -0,0 +1,9 @@ +#pragma once + +namespace TouchHaptics +{ + void Init(); + + // Plays a short tap on the Taptic Engine. Light is used for the stick, medium for buttons. + void Play(bool light); +} diff --git a/UnleashedRecomp/ui/touch_haptics_ios.mm b/UnleashedRecomp/ui/touch_haptics_ios.mm new file mode 100644 index 00000000..c06a7d6c --- /dev/null +++ b/UnleashedRecomp/ui/touch_haptics_ios.mm @@ -0,0 +1,29 @@ +#include "touch_haptics.h" + +#import + +static UIImpactFeedbackGenerator* g_lightFeedback; +static UIImpactFeedbackGenerator* g_mediumFeedback; + +namespace TouchHaptics +{ + void Init() + { + dispatch_async(dispatch_get_main_queue(), ^{ + g_lightFeedback = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight]; + g_mediumFeedback = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium]; + [g_lightFeedback prepare]; + [g_mediumFeedback prepare]; + }); + } + + void Play(bool light) + { + // UIKit feedback generators must only be used from the main thread. + dispatch_async(dispatch_get_main_queue(), ^{ + UIImpactFeedbackGenerator* generator = light ? g_lightFeedback : g_mediumFeedback; + [generator impactOccurred]; + [generator prepare]; + }); + } +} diff --git a/UnleashedRecomp/user/config.cpp b/UnleashedRecomp/user/config.cpp index bd622b7f..a5824b6b 100644 --- a/UnleashedRecomp/user/config.cpp +++ b/UnleashedRecomp/user/config.cpp @@ -305,6 +305,9 @@ CONFIG_DEFINE_ENUM_TEMPLATE(EGraphicsAPI) { "Auto", EGraphicsAPI::Auto }, #ifdef UNLEASHED_RECOMP_D3D12 { "D3D12", EGraphicsAPI::D3D12 }, +#endif +#ifdef UNLEASHED_RECOMP_METAL + { "Metal", EGraphicsAPI::Metal }, #endif { "Vulkan", EGraphicsAPI::Vulkan } }; diff --git a/UnleashedRecomp/user/config.h b/UnleashedRecomp/user/config.h index 9e87d12e..36978f95 100644 --- a/UnleashedRecomp/user/config.h +++ b/UnleashedRecomp/user/config.h @@ -70,6 +70,9 @@ enum class EGraphicsAPI : uint32_t Auto, #ifdef UNLEASHED_RECOMP_D3D12 D3D12, +#endif +#ifdef UNLEASHED_RECOMP_METAL + Metal, #endif Vulkan }; diff --git a/UnleashedRecomp/user/config_def.h b/UnleashedRecomp/user/config_def.h index 80eb29c9..8b04693c 100644 --- a/UnleashedRecomp/user/config_def.h +++ b/UnleashedRecomp/user/config_def.h @@ -15,6 +15,8 @@ CONFIG_DEFINE_ENUM_LOCALISED("Input", ECameraRotationMode, VerticalCamera, ECame CONFIG_DEFINE_LOCALISED("Input", bool, Vibration, true); CONFIG_DEFINE_LOCALISED("Input", bool, AllowBackgroundInput, false); CONFIG_DEFINE_ENUM_LOCALISED("Input", EControllerIcons, ControllerIcons, EControllerIcons::Auto); +CONFIG_DEFINE("Input", bool, TouchControls, true); +CONFIG_DEFINE("Input", float, TouchControlsOpacity, 1.0f); CONFIG_DEFINE_ENUM("Bindings", SDL_Scancode, Key_A, SDL_SCANCODE_S); CONFIG_DEFINE_ENUM("Bindings", SDL_Scancode, Key_B, SDL_SCANCODE_D); @@ -74,6 +76,9 @@ CONFIG_DEFINE_ENUM_LOCALISED("Video", EMotionBlur, MotionBlur, EMotionBlur::Orig CONFIG_DEFINE_LOCALISED("Video", bool, XboxColorCorrection, false); CONFIG_DEFINE_ENUM_LOCALISED("Video", ECutsceneAspectRatio, CutsceneAspectRatio, ECutsceneAspectRatio::Original); CONFIG_DEFINE_ENUM_LOCALISED("Video", EUIAlignmentMode, UIAlignmentMode, EUIAlignmentMode::Edge); +#if defined(__APPLE__) +CONFIG_DEFINE_LOCALISED("Video", bool, ShowMetalHUD, false); +#endif CONFIG_DEFINE_HIDDEN("Codes", bool, AllowCancellingUnleash, false); CONFIG_DEFINE_HIDDEN("Codes", bool, DisableAutoSaveWarning, false); diff --git a/UnleashedRecomp/user/paths.cpp b/UnleashedRecomp/user/paths.cpp index e3dbf101..e72b4738 100644 --- a/UnleashedRecomp/user/paths.cpp +++ b/UnleashedRecomp/user/paths.cpp @@ -1,5 +1,8 @@ #include "paths.h" #include +#ifdef TARGET_OS_IPHONE +#include "../apple_utils.h" +#endif std::filesystem::path g_executableRoot = os::process::GetExecutableRoot(); std::filesystem::path g_userPath = BuildUserPath(); @@ -22,6 +25,8 @@ std::filesystem::path BuildUserPath() userPath = std::filesystem::path{ knownPath } / USER_DIRECTORY; CoTaskMemFree(knownPath); +#elif TARGET_OS_IPHONE + userPath = apple::GetUserDataDirectory(); #elif defined(__linux__) || defined(__APPLE__) const char* homeDir = getenv("HOME"); #if defined(__linux__) diff --git a/UnleashedRecompLib/CMakeLists.txt b/UnleashedRecompLib/CMakeLists.txt index 8514bde8..70f6147b 100644 --- a/UnleashedRecompLib/CMakeLists.txt +++ b/UnleashedRecompLib/CMakeLists.txt @@ -4,17 +4,17 @@ add_compile_options( -fno-strict-aliasing ) -if (WIN32) +if(WIN32) add_compile_options(/fp:strict) else() add_compile_options(-ffp-model=strict) endif() -target_compile_definitions(XenonRecomp PRIVATE +target_compile_definitions(XenonRecomp PRIVATE XENON_RECOMP_CONFIG_FILE_PATH=\"${CMAKE_CURRENT_SOURCE_DIR}/config/SWA.toml\" XENON_RECOMP_HEADER_FILE_PATH=\"${UNLEASHED_RECOMP_TOOLS_ROOT}/XenonRecomp/XenonUtils/ppc_context.h\") -set(UNLEASHED_RECOMP_PPC_RECOMPILED_SOURCES +set(UNLEASHED_RECOMP_PPC_RECOMPILED_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/ppc/ppc_config.h" "${CMAKE_CURRENT_SOURCE_DIR}/ppc/ppc_context.h" "${CMAKE_CURRENT_SOURCE_DIR}/ppc/ppc_func_mapping.cpp" @@ -25,57 +25,151 @@ foreach(i RANGE 0 260) list(APPEND UNLEASHED_RECOMP_PPC_RECOMPILED_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/ppc/ppc_recomp.${i}.cpp") endforeach() -add_custom_command( - OUTPUT +if(NOT CMAKE_CROSSCOMPILING) + add_custom_command( + OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/private/default_patched.xex" ${UNLEASHED_RECOMP_PPC_RECOMPILED_SOURCES} - COMMAND + COMMAND $ - DEPENDS + DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/private/default.xex" "${CMAKE_CURRENT_SOURCE_DIR}/private/default.xexp" "${CMAKE_CURRENT_SOURCE_DIR}/config/SWA.toml" - USES_TERMINAL -) + USES_TERMINAL + ) -add_custom_command( - OUTPUT + add_custom_command( + OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/private/shader_decompressed.ar" - COMMAND + COMMAND $ "${CMAKE_CURRENT_SOURCE_DIR}/private/shader.ar" "${CMAKE_CURRENT_SOURCE_DIR}/private/shader_decompressed.ar" - DEPENDS + DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/private/shader.ar" -) + ) -set(XENOS_RECOMP_ROOT "${UNLEASHED_RECOMP_TOOLS_ROOT}/XenosRecomp/XenosRecomp") -set(XENOS_RECOMP_INCLUDE "${XENOS_RECOMP_ROOT}/shader_common.h") + set(XENOS_RECOMP_ROOT "${UNLEASHED_RECOMP_TOOLS_ROOT}/XenosRecomp/XenosRecomp") + set(XENOS_RECOMP_INCLUDE "${XENOS_RECOMP_ROOT}/shader_common.h") -target_compile_definitions(XenosRecomp PRIVATE - XENOS_RECOMP_INPUT=\"${CMAKE_CURRENT_SOURCE_DIR}/private\" - XENOS_RECOMP_OUTPUT=\"${CMAKE_CURRENT_SOURCE_DIR}/shader/shader_cache.cpp\" - XENOS_RECOMP_INCLUDE_INPUT=\"${XENOS_RECOMP_INCLUDE}\" - UNLEASHED_RECOMP -) + target_compile_definitions(XenosRecomp PRIVATE + XENOS_RECOMP_INPUT=\"${CMAKE_CURRENT_SOURCE_DIR}/private\" + XENOS_RECOMP_OUTPUT=\"${CMAKE_CURRENT_SOURCE_DIR}/shader/shader_cache.cpp\" + XENOS_RECOMP_INCLUDE_INPUT=\"${XENOS_RECOMP_INCLUDE}\" + UNLEASHED_RECOMP + ) -file(GLOB XENOS_RECOMP_SOURCES - "${XENOS_RECOMP_ROOT}/*.h" - "${XENOS_RECOMP_ROOT}/*.cpp" -) + file(GLOB XENOS_RECOMP_SOURCES + "${XENOS_RECOMP_ROOT}/*.h" + "${XENOS_RECOMP_ROOT}/*.cpp" + ) -add_custom_command( - OUTPUT + add_custom_command( + OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/shader/shader_cache.cpp" - COMMAND + COMMAND $ - DEPENDS + DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/private/default_patched.xex" - "${CMAKE_CURRENT_SOURCE_DIR}/private/shader_decompressed.ar" - ${XENOS_RECOMP_SOURCES} + "${CMAKE_CURRENT_SOURCE_DIR}/private/shader_decompressed.ar" + ${XENOS_RECOMP_SOURCES} ${XENOS_RECOMP_INCLUDE} - USES_TERMINAL -) + USES_TERMINAL + ) +else() + message(STATUS "Cross-compiling: building host tools for code generation") + + # Build host-native tools out-of-tree + set(HOST_XENONRECOMP_BUILD_DIR "${CMAKE_BINARY_DIR}/host-tools/XenonRecomp") + set(HOST_X_DECOMPRESS_BUILD_DIR "${CMAKE_BINARY_DIR}/host-tools/x_decompress") + set(HOST_XENOSRECOMP_BUILD_DIR "${CMAKE_BINARY_DIR}/host-tools/XenosRecomp") + set(HOST_VCPKG_TRIPLET "${CMAKE_HOST_SYSTEM_PROCESSOR}-osx") + set(HOST_XENONRECOMP_BIN "${HOST_XENONRECOMP_BUILD_DIR}/XenonRecomp/XenonRecomp") + set(HOST_X_DECOMPRESS_BIN "${HOST_X_DECOMPRESS_BUILD_DIR}/x_decompress") + set(HOST_XENOSRECOMP_BIN "${HOST_XENOSRECOMP_BUILD_DIR}/XenosRecomp/XenosRecomp") + + add_custom_command( + OUTPUT + "${CMAKE_CURRENT_SOURCE_DIR}/private/default_patched.xex" + ${UNLEASHED_RECOMP_PPC_RECOMPILED_SOURCES} + + COMMAND + ${CMAKE_COMMAND} -S "${CMAKE_SOURCE_DIR}/tools/XenonRecomp" -B "${HOST_XENONRECOMP_BUILD_DIR}" + -G "${CMAKE_GENERATOR}" + -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/host-tools/install + -DUNLEASHED_RECOMP=ON + COMMAND + ${CMAKE_COMMAND} --build "${HOST_XENONRECOMP_BUILD_DIR}" --config ${CMAKE_BUILD_TYPE} + + COMMAND + "${HOST_XENONRECOMP_BIN}" "${CMAKE_CURRENT_SOURCE_DIR}/config/SWA.toml" "${UNLEASHED_RECOMP_TOOLS_ROOT}/XenonRecomp/XenonUtils/ppc_context.h" + + WORKING_DIRECTORY + "${CMAKE_CURRENT_SOURCE_DIR}" + + DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/private/default.xex" + "${CMAKE_CURRENT_SOURCE_DIR}/private/default.xexp" + "${CMAKE_CURRENT_SOURCE_DIR}/config/SWA.toml" + + COMMENT "Building host XenonRecomp and generating patched XEX + sources" + USES_TERMINAL + ) + + add_custom_command( + OUTPUT + "${CMAKE_CURRENT_SOURCE_DIR}/private/shader_decompressed.ar" + COMMAND + ${CMAKE_COMMAND} -S "${CMAKE_SOURCE_DIR}/tools/x_decompress" -B "${HOST_X_DECOMPRESS_BUILD_DIR}" + -G "${CMAKE_GENERATOR}" + -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + -DUNLEASHED_RECOMP_TOOLS_ROOT=${UNLEASHED_RECOMP_TOOLS_ROOT} + COMMAND + ${CMAKE_COMMAND} --build "${HOST_X_DECOMPRESS_BUILD_DIR}" --config ${CMAKE_BUILD_TYPE} + COMMAND + "${HOST_X_DECOMPRESS_BIN}" "${CMAKE_CURRENT_SOURCE_DIR}/private/shader.ar" "${CMAKE_CURRENT_SOURCE_DIR}/private/shader_decompressed.ar" + DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/private/shader.ar" + COMMENT "Building host x_decompress and decompressing shader archive" + USES_TERMINAL + ) + + set(XENOS_RECOMP_ROOT "${UNLEASHED_RECOMP_TOOLS_ROOT}/XenosRecomp/XenosRecomp") + set(XENOS_RECOMP_INCLUDE "${XENOS_RECOMP_ROOT}/shader_common.h") + + file(GLOB XENOS_RECOMP_SOURCES + "${XENOS_RECOMP_ROOT}/*.h" + "${XENOS_RECOMP_ROOT}/*.cpp" + ) + + add_custom_command( + OUTPUT + "${CMAKE_CURRENT_SOURCE_DIR}/shader/shader_cache.cpp" + COMMAND + ${CMAKE_COMMAND} -S "${CMAKE_SOURCE_DIR}/tools/XenosRecomp" -B "${HOST_XENOSRECOMP_BUILD_DIR}" + -G "${CMAKE_GENERATOR}" + -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/host-tools/install + -DUNLEASHED_RECOMP=ON + -DXENOS_RECOMP_METAL_SDK="iphoneos" + -DXENOS_RECOMP_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET} + + COMMAND + ${CMAKE_COMMAND} --build "${HOST_XENOSRECOMP_BUILD_DIR}" --config ${CMAKE_BUILD_TYPE} + COMMAND + "${HOST_XENOSRECOMP_BIN}" "${CMAKE_CURRENT_SOURCE_DIR}/private" "${CMAKE_CURRENT_SOURCE_DIR}/shader/shader_cache.cpp" "${XENOS_RECOMP_INCLUDE}" + DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/private/default_patched.xex" + "${CMAKE_CURRENT_SOURCE_DIR}/private/shader_decompressed.ar" + ${XENOS_RECOMP_SOURCES} + ${XENOS_RECOMP_INCLUDE} + "${XENOS_RECOMP_ROOT}/CMakeLists.txt" + COMMENT "Building host XenosRecomp and generating shader cache" + USES_TERMINAL + ) +endif() -add_library(UnleashedRecompLib +add_library(UnleashedRecompLib ${UNLEASHED_RECOMP_PPC_RECOMPILED_SOURCES} "shader/shader_cache.h" "shader/shader_cache.cpp" diff --git a/UnleashedRecompLib/shader/shader_cache.h b/UnleashedRecompLib/shader/shader_cache.h index 43439403..8fdbefcf 100644 --- a/UnleashedRecompLib/shader/shader_cache.h +++ b/UnleashedRecompLib/shader/shader_cache.h @@ -7,7 +7,10 @@ struct ShaderCacheEntry const uint32_t dxilSize; const uint32_t spirvOffset; const uint32_t spirvSize; + const uint32_t airOffset; + const uint32_t airSize; const uint32_t specConstantsMask; + char filename[256]; struct GuestShader* guestShader; }; @@ -18,6 +21,10 @@ extern const uint8_t g_compressedDxilCache[]; extern const size_t g_dxilCacheCompressedSize; extern const size_t g_dxilCacheDecompressedSize; +extern const uint8_t g_compressedAirCache[]; +extern const size_t g_airCacheCompressedSize; +extern const size_t g_airCacheDecompressedSize; + extern const uint8_t g_compressedSpirvCache[]; extern const size_t g_spirvCacheCompressedSize; extern const size_t g_spirvCacheDecompressedSize; diff --git a/thirdparty/MoltenVK/CMakeLists.txt b/thirdparty/MoltenVK/CMakeLists.txt index c7ef4f9b..12559325 100644 --- a/thirdparty/MoltenVK/CMakeLists.txt +++ b/thirdparty/MoltenVK/CMakeLists.txt @@ -2,13 +2,15 @@ # Prepare MoltenVK Git revision find_package(Git) + if(GIT_FOUND) execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD - OUTPUT_VARIABLE MVK_GIT_REV - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/MoltenVK - ERROR_QUIET - OUTPUT_STRIP_TRAILING_WHITESPACE) + OUTPUT_VARIABLE MVK_GIT_REV + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/MoltenVK + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) endif() + set(MVK_GENERATED_INCLUDES ${CMAKE_CURRENT_BINARY_DIR}/Generated) file(WRITE ${MVK_GENERATED_INCLUDES}/mvkGitRevDerived.h "static const char* mvkRevString = \"${MVK_GIT_REV}\";") message(STATUS "MoltenVK revision: ${MVK_GIT_REV}") @@ -25,9 +27,15 @@ set(MVK_VERSION "${MVK_VERSION_MAJOR}.${MVK_VERSION_MINOR}.${MVK_VERSION_PATCH}" message(STATUS "MoltenVK version: ${MVK_VERSION}") # Find required system libraries -find_library(APPKIT_LIBRARY AppKit REQUIRED) +if(IOS) + find_library(UIKIT_LIBRARY UIKit REQUIRED) + find_library(COREGRAPHICS_LIBRARY CoreGraphics REQUIRED) +else() + find_library(APPKIT_LIBRARY AppKit REQUIRED) + find_library(IOKIT_LIBRARY IOKit REQUIRED) +endif() + find_library(FOUNDATION_LIBRARY Foundation REQUIRED) -find_library(IOKIT_LIBRARY IOKit REQUIRED) find_library(IOSURFACE_LIBRARY IOSurface REQUIRED) find_library(METAL_LIBRARY Metal REQUIRED) find_library(QUARTZCORE_LIBRARY QuartzCore REQUIRED) @@ -81,6 +89,53 @@ add_library(MoltenVK SHARED ${MVK_SOURCES}) target_include_directories(MoltenVK PRIVATE ${MVK_INCLUDES}) target_compile_options(MoltenVK PRIVATE -w) target_link_libraries(MoltenVK PRIVATE - ${APPKIT_LIBRARY} ${FOUNDATION_LIBRARY} ${IOKIT_LIBRARY} ${IOSURFACE_LIBRARY} ${METAL_LIBRARY} ${QUARTZCORE_LIBRARY} + ${FOUNDATION_LIBRARY} ${IOSURFACE_LIBRARY} ${METAL_LIBRARY} ${QUARTZCORE_LIBRARY} spirv-cross-msl MoltenVKCommon MoltenVKShaderConverter) -target_compile_definitions(MoltenVK PRIVATE MVK_FRAMEWORK_VERSION=${MVK_VERSION} MVK_USE_CEREAL=0) + +if(IOS) + target_link_libraries(MoltenVK PRIVATE ${UIKIT_LIBRARY} ${COREGRAPHICS_LIBRARY}) +else() + target_link_libraries(MoltenVK PRIVATE ${APPKIT_LIBRARY} ${IOKIT_LIBRARY}) +endif() + +target_compile_definitions(MoltenVK PRIVATE + MVK_FRAMEWORK_VERSION=${MVK_VERSION} + MVK_USE_CEREAL=0 + VK_USE_PLATFORM_METAL_EXT=1) + +set_source_files_properties( + ${MVK_SOURCES} + PROPERTIES + COMPILE_FLAGS "-fno-objc-arc" +) + +set_target_properties(MoltenVK PROPERTIES + FRAMEWORK TRUE + + FRAMEWORK_VERSION A + + MACOSX_FRAMEWORK_IDENTIFIER org.moltenvk.MoltenVK + MACOSX_FRAMEWORK_BUNDLE_VERSION ${MVK_VERSION} + MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${MVK_VERSION} + + PUBLIC_HEADER "${MVK_PUBLIC_HEADERS}" + + POSITION_INDEPENDENT_CODE ON + + XCODE_ATTRIBUTE_DEFINES_MODULE YES + XCODE_ATTRIBUTE_DYLIB_INSTALL_NAME_BASE "@rpath" + + BUILD_WITH_INSTALL_RPATH YES + INSTALL_RPATH "@executable_path/Frameworks;@loader_path/Frameworks" +) + +if(IOS) + set_target_properties(MoltenVK PROPERTIES + XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH YES + XCODE_ATTRIBUTE_ENABLE_BITCODE NO + XCODE_ATTRIBUTE_SKIP_INSTALL NO + + XCODE_ATTRIBUTE_IPHONEOS_DEPLOYMENT_TARGET + "${CMAKE_OSX_DEPLOYMENT_TARGET}" + ) +endif() diff --git a/thirdparty/ios-cmake b/thirdparty/ios-cmake new file mode 160000 index 00000000..b055a032 --- /dev/null +++ b/thirdparty/ios-cmake @@ -0,0 +1 @@ +Subproject commit b055a0320feccc168dca13b381ae7097c4771585 diff --git a/thirdparty/plume b/thirdparty/plume index 11926860..e213c40f 160000 --- a/thirdparty/plume +++ b/thirdparty/plume @@ -1 +1 @@ -Subproject commit 11926860e878e68626ea99ec88562ce2b8badc4f +Subproject commit e213c40fa4a9c01ed4fdb1aa683ce1e78d15d970 diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index bdcf384a..fe45cfd6 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -1,6 +1,9 @@ add_subdirectory(${UNLEASHED_RECOMP_TOOLS_ROOT}/bc_diff) -add_subdirectory(${UNLEASHED_RECOMP_TOOLS_ROOT}/file_to_c) add_subdirectory(${UNLEASHED_RECOMP_TOOLS_ROOT}/fshasher) -add_subdirectory(${UNLEASHED_RECOMP_TOOLS_ROOT}/x_decompress) add_subdirectory(${UNLEASHED_RECOMP_TOOLS_ROOT}/XenonRecomp) -add_subdirectory(${UNLEASHED_RECOMP_TOOLS_ROOT}/XenosRecomp) + +if(NOT CMAKE_CROSSCOMPILING) + add_subdirectory(${UNLEASHED_RECOMP_TOOLS_ROOT}/file_to_c) + add_subdirectory(${UNLEASHED_RECOMP_TOOLS_ROOT}/x_decompress) + add_subdirectory(${UNLEASHED_RECOMP_TOOLS_ROOT}/XenosRecomp) +endif() diff --git a/tools/XenosRecomp b/tools/XenosRecomp index 990d03b2..49069920 160000 --- a/tools/XenosRecomp +++ b/tools/XenosRecomp @@ -1 +1 @@ -Subproject commit 990d03b28a27b50277ee5d8d942e1c5f873869d1 +Subproject commit 490699203914fe240b86ccf2401fe1f7d37b1bef diff --git a/tools/file_to_c/CMakeLists.txt b/tools/file_to_c/CMakeLists.txt index 6fbafba6..8f0a9503 100644 --- a/tools/file_to_c/CMakeLists.txt +++ b/tools/file_to_c/CMakeLists.txt @@ -7,4 +7,18 @@ set(CMAKE_CXX_STANDARD 17) add_executable(file_to_c "file_to_c.cpp") -target_link_libraries(file_to_c PRIVATE $,libzstd_static,libzstd_shared>) +find_package(ZSTD) + +if(TARGET ZSTD::ZSTD) + target_link_libraries(file_to_c PRIVATE ZSTD::ZSTD) +else() + find_path(ZSTD_INCLUDE_DIR zstd.h) + find_library(ZSTD_LIBRARY NAMES zstd libzstd libzstd_static) + + if(ZSTD_INCLUDE_DIR AND ZSTD_LIBRARY) + target_include_directories(file_to_c PRIVATE ${ZSTD_INCLUDE_DIR}) + target_link_libraries(file_to_c PRIVATE ${ZSTD_LIBRARY}) + else() + message(FATAL_ERROR "zstd library not found. Install zstd (e.g. via vcpkg) or ensure zstd.h and libzstd are on the include/library path.") + endif() +endif() diff --git a/tools/x_decompress/CMakeLists.txt b/tools/x_decompress/CMakeLists.txt index aecf1f79..88fa6df2 100644 --- a/tools/x_decompress/CMakeLists.txt +++ b/tools/x_decompress/CMakeLists.txt @@ -1,3 +1,4 @@ +cmake_minimum_required(VERSION 3.20) project("x_decompress") set(CMAKE_CXX_STANDARD 17) diff --git a/vcpkg.json b/vcpkg.json index 6b97ca18..07dd123c 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -10,7 +10,8 @@ "platform": "windows" }, "freetype", - "curl" + "curl", + "zstd" ], "vcpkg-configuration": { "overlay-triplets": [