diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml new file mode 100644 index 00000000..7998228e --- /dev/null +++ b/.github/workflows/android.yml @@ -0,0 +1,141 @@ +# Android APK (docs/ANDROID.md). Builds on every push to android-port, on pull requests to it and +# by hand (Actions > Android > Run workflow). The APK is attached to the run as an artifact; a +# pushed tag "android-*" also publishes it as a GitHub release (pre-release). +# +# The bundled compiler (libllvm.so, clang + lld for Android) takes about two hours to build, so it +# is built once and kept in the Actions cache (key: LLVM version, script and NDK). +# +# Signing: set the repository secret ANDROID_KEYSTORE_BASE64 (base64 of a keystore whose key is +# "lmport", password in ANDROID_KEYSTORE_PASS or "android") so every build can be installed over +# the previous one. Without it a key is generated once and kept in the cache. +name: Android + +on: + push: + branches: [android-port] + tags: ["android-*"] + pull_request: + branches: [android-port] + workflow_dispatch: + +permissions: + contents: read + +env: + NDK_VERSION: 29.0.14206865 + BUILD_TOOLS: 37.0.0 + LLVM_VERSION: 21.1.8 + +jobs: + compiler: + name: Compiler (libllvm.so) + runs-on: ubuntu-24.04 + timeout-minutes: 340 + outputs: + key: ${{ steps.key.outputs.key }} + steps: + - uses: actions/checkout@v4 + - id: key + run: echo "key=libllvm-${{ env.LLVM_VERSION }}-ndk${{ env.NDK_VERSION }}-${{ hashFiles('tools/android/build_llvm.sh') }}" >> "$GITHUB_OUTPUT" + - id: cache + uses: actions/cache@v4 + with: + path: build/android-llvm/libllvm.so + key: ${{ steps.key.outputs.key }} + lookup-only: true + - name: Install the NDK + if: steps.cache.outputs.cache-hit != 'true' + run: | + yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --install "ndk;$NDK_VERSION" >/dev/null + sudo apt-get update -q && sudo apt-get install -y -q ninja-build clang + - name: Build clang + lld for Android + if: steps.cache.outputs.cache-hit != 'true' + env: + LM_LLVM_VERSION: ${{ env.LLVM_VERSION }} + run: | + export ANDROID_NDK="$ANDROID_HOME/ndk/$NDK_VERSION" + tools/android/build_llvm.sh + rm -rf build/android-llvm/build build/android-llvm/llvm-project + - name: Save the compiler + if: steps.cache.outputs.cache-hit != 'true' + uses: actions/cache/save@v4 + with: + path: build/android-llvm/libllvm.so + key: ${{ steps.key.outputs.key }} + + apk: + name: APK + needs: compiler + runs-on: ubuntu-24.04 + timeout-minutes: 120 + permissions: + contents: write # releases for android-* tags + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 17 + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-linux-android + - name: Install the Android SDK parts + run: | + yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --install \ + "ndk;$NDK_VERSION" "build-tools;$BUILD_TOOLS" "platforms;android-35" >/dev/null + sudo apt-get update -q && sudo apt-get install -y -q ninja-build zip + echo "ANDROID_NDK=$ANDROID_HOME/ndk/$NDK_VERSION" >> "$GITHUB_ENV" + - name: Restore the compiler + uses: actions/cache/restore@v4 + with: + path: build/android-llvm/libllvm.so + key: ${{ needs.compiler.outputs.key }} + fail-on-cache-miss: true + - name: Cache nod + uses: actions/cache@v4 + with: + path: build/android-nod/libnod-android-aarch64.tar.gz + key: nod-android-${{ env.NDK_VERSION }}-${{ hashFiles('tools/android/build_nod.sh', 'extern/aurora/cmake/AuroraDependencyVersions.cmake') }} + - name: Build nod + run: | + [ -f build/android-nod/libnod-android-aarch64.tar.gz ] || tools/android/build_nod.sh + - name: Signing key + env: + KEYSTORE_B64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + run: | + if [ -n "$KEYSTORE_B64" ]; then + echo "$KEYSTORE_B64" | base64 -d > "$RUNNER_TEMP/release.keystore" + echo "LM_KEYSTORE=$RUNNER_TEMP/release.keystore" >> "$GITHUB_ENV" + else + echo "::warning::No ANDROID_KEYSTORE_BASE64 secret: signing with a key kept in the Actions cache (an APK signed with another key cannot be installed over this one)." + fi + - name: Cached fallback key + if: env.LM_KEYSTORE == '' + uses: actions/cache@v4 + with: + path: build/android-debug.keystore + key: android-fallback-keystore + - name: Build libmain.so + run: tools/android/build.sh + - name: Build the APK + env: + LM_KEYSTORE_PASS: ${{ secrets.ANDROID_KEYSTORE_PASS || 'android' }} + run: | + name="LuigisMansionRecompiled-android-arm64-${GITHUB_REF_NAME//\//-}-${GITHUB_SHA::7}.apk" + tools/android/build_apk.sh "build/$name" + echo "APK_NAME=$name" >> "$GITHUB_ENV" + - uses: actions/upload-artifact@v4 + with: + name: ${{ env.APK_NAME }} + path: build/${{ env.APK_NAME }} + compression-level: 0 + - name: Release (android-* tags) + if: startsWith(github.ref, 'refs/tags/android-') + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "$GITHUB_REF_NAME" "build/$APK_NAME" --prerelease \ + --title "Android $GITHUB_REF_NAME" \ + --notes "Android (arm64) build from $GITHUB_SHA. Needs your own disc image; the first start compiles the game on the phone. See docs/ANDROID.md and docs/TEXTURE_PACKS.md." diff --git a/CMakeLists.txt b/CMakeLists.txt index db019565..525fb9a8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,7 +50,17 @@ if (NOT _stamped STREQUAL _patch_ids) endforeach () file(WRITE ${_stamp} "${_patch_ids}") endif () +if (CMAKE_CROSSCOMPILING) + # The build machine's pkg-config must not offer its libraries (sqlite3, freetype, libpng...) to + # a cross build; re-configures from `cmake --build` do not get the preset's environment. + set(ENV{PKG_CONFIG_LIBDIR} "/nonexistent-cross-pkgconfig") + set(ENV{PKG_CONFIG_PATH} "") +endif () add_subdirectory(extern/aurora EXCLUDE_FROM_ALL) +if (ANDROID) + # Plain char is unsigned on ARM; the port was written and tested where it is signed (x86). + add_compile_options(-fsigned-char) +endif () # ---- Shared game/library compile environment ------------------------------- @@ -85,7 +95,11 @@ endforeach () # each unit is made to compile against Aurora (see docs/ROADMAP.md, Phase 1). file(GLOB PORT_SOURCES CONFIGURE_DEPENDS src/port/*.cpp src/port/os/*.cpp src/helpers/*.cpp) file(GLOB_RECURSE GAME_SOURCES CONFIGURE_DEPENDS src/game/*.cpp) -add_executable(lmport ${PORT_SOURCES} ${GAME_SOURCES}) +if (ANDROID) + # The old hand-port prototype is desktop-only (not built on Android, like on Linux it is optional). + set(_lmport_exclude EXCLUDE_FROM_ALL) +endif () +add_executable(lmport ${_lmport_exclude} ${PORT_SOURCES} ${GAME_SOURCES}) target_include_directories(lmport PRIVATE src) target_link_libraries(lmport PRIVATE aurora::main ${GAME_LIBS} ${JSYSTEM_LIBRARIES}) if (WIN32) @@ -112,8 +126,10 @@ endif () # dev build uses. Nothing generated is ever committed. add_library(lm_recompiler STATIC src/recompiler/recompiler.cpp src/recompiler/recompiler.h) target_include_directories(lm_recompiler PUBLIC src) -add_executable(lmrecompile tools/recomp/lmrecompile.cpp) -target_link_libraries(lmrecompile PRIVATE lm_recompiler) +if (NOT ANDROID) + add_executable(lmrecompile tools/recomp/lmrecompile.cpp) + target_link_libraries(lmrecompile PRIVATE lm_recompiler) +endif () # Runtime shared by both executables: memory/CPU helpers, scheduler, HLE SDK, frame # driver, audio, menu. module_rt.cpp belongs to the game module, not the runtime. @@ -125,6 +141,9 @@ list(APPEND RECOMP_RUNTIME_SOURCES src/port/crash_handler.cpp src/port/options.c # game module's cache key; docs/SETUP.md "Updates"). Only this file sees it, so a version bump # rebuilds one file. set_source_files_properties(src/port/update.cpp PROPERTIES COMPILE_DEFINITIONS "LM_VERSION=\"${PROJECT_VERSION}\"") +if (ANDROID) + list(APPEND RECOMP_RUNTIME_SOURCES src/port/android.cpp) # docs/ANDROID.md +endif () function(lm_runtime_target tgt) target_include_directories(${tgt} PRIVATE src @@ -151,6 +170,9 @@ function(lm_runtime_target tgt) # (src/setup/module_builder.cpp): no fused multiply-adds the PowerPC would not do, in # the HLE math (PSMTX/PSVEC) and in lmrecomp's generated code. target_compile_options(${tgt} PRIVATE -ffp-contract=off) + elseif (ANDROID) + # Android arm64 (docs/ANDROID.md): the same fused multiply-add rule as macOS above. + target_compile_options(${tgt} PRIVATE -ffp-contract=off) elseif (CMAKE_SYSTEM_NAME STREQUAL "Linux") # Portable Linux binary (docs/LINUX.md): SDL3, Dawn and nod are linked statically by # Aurora; the C++ runtime is too, and src/port/glibc_compat.c covers the few symbols @@ -161,6 +183,8 @@ function(lm_runtime_target tgt) # libgcc_s stays shared: the static unwinder of a newer GCC needs _dl_find_object (glibc 2.35). target_link_options(${tgt} PRIVATE -static-libstdc++) target_link_libraries(${tgt} PRIVATE ${CMAKE_DL_LIBS}) + elseif (ANDROID) + target_link_libraries(${tgt} PRIVATE ${CMAKE_DL_LIBS} log android) endif () endfunction() @@ -168,7 +192,17 @@ endfunction() # the setup UI; the game itself is a module DLL that setup compiles from the user's disc # with the bundled clang + lld (docs/SETUP.md). file(GLOB SETUP_SOURCES CONFIGURE_DEPENDS src/setup/*.cpp src/setup/*.h) -add_executable(LuigisMansionRecomp ${RECOMP_RUNTIME_SOURCES} ${SETUP_SOURCES}) +if (ANDROID) + # Android (docs/ANDROID.md): the program is libmain.so, loaded by SDL's Java activity + # (packaging/android), which calls SDL_main (aurora::main renames main to it). + add_library(LuigisMansionRecomp SHARED ${RECOMP_RUNTIME_SOURCES} ${SETUP_SOURCES}) + set_target_properties(LuigisMansionRecomp PROPERTIES OUTPUT_NAME main) + # Nothing in the program calls SDL_main (SDL's Java side looks it up with dlsym), so pull + # aurora::main's definition out of its static library explicitly. + target_link_options(LuigisMansionRecomp PRIVATE -Wl,-u,SDL_main) +else () + add_executable(LuigisMansionRecomp ${RECOMP_RUNTIME_SOURCES} ${SETUP_SOURCES}) +endif () lm_runtime_target(LuigisMansionRecomp) target_link_libraries(LuigisMansionRecomp PRIVATE lm_recompiler) # nod comes with aurora::dvd if (WIN32) @@ -178,8 +212,19 @@ if (WIN32) target_link_options(LuigisMansionRecomp PRIVATE "LINKER:/ENTRY:mainCRTStartup") endif () # Setup's inputs are embedded in the executable (src/setup/embedded.cpp): symbol maps, -# hooks, and the game module's freestanding sources. -add_executable(lmembed tools/recomp/lmembed.cpp) +# hooks, and the game module's freestanding sources. lmembed runs at build time, so a +# cross build (Android) takes one built for the build machine: LM_HOST_LMEMBED. +if (CMAKE_CROSSCOMPILING) + set(LM_HOST_LMEMBED "" CACHE FILEPATH "lmembed built for the build machine (cross builds)") + if (NOT LM_HOST_LMEMBED) + message(FATAL_ERROR "Cross build: set LM_HOST_LMEMBED to a host build of tools/recomp/lmembed.cpp " + "(e.g. c++ -std=c++20 -O2 tools/recomp/lmembed.cpp -o lmembed; tools/android/build.sh does this)") + endif () + add_executable(lmembed IMPORTED) + set_target_properties(lmembed PROPERTIES IMPORTED_LOCATION ${LM_HOST_LMEMBED}) +else () + add_executable(lmembed tools/recomp/lmembed.cpp) +endif () set(LM_EMBEDDED_FILES kSymbolsUs=decomp/config/GLME01/symbols.txt kSplitsUs=decomp/config/GLME01/splits.txt kSymbolsPal=decomp/config/GLMP01_00/symbols.txt kVersionMapPal=tools/recomp/GLMP01_map.txt @@ -207,7 +252,7 @@ else () set(LM_MODULE_LINKER ld.lld) endif () get_filename_component(_cxx_dir ${CMAKE_CXX_COMPILER} DIRECTORY) -if (EXISTS ${_cxx_dir}/clang${CMAKE_EXECUTABLE_SUFFIX} AND EXISTS ${_cxx_dir}/${LM_MODULE_LINKER}${CMAKE_EXECUTABLE_SUFFIX}) +if (NOT CMAKE_CROSSCOMPILING AND EXISTS ${_cxx_dir}/clang${CMAKE_EXECUTABLE_SUFFIX} AND EXISTS ${_cxx_dir}/${LM_MODULE_LINKER}${CMAKE_EXECUTABLE_SUFFIX}) target_compile_definitions(LuigisMansionRecomp PRIVATE "LM_DEV_LLVM_DIR=\"${_cxx_dir}\"") elseif (APPLE) # macOS: Apple's clang comes without lld. Homebrew's llvm and lld (separate kegs) build the @@ -240,6 +285,8 @@ if (WIN32) file(INSTALL \${_dlls} DESTINATION \"\${CMAKE_INSTALL_PREFIX}\")") install(PROGRAMS ${LM_LLVM_DIR}/clang${CMAKE_EXECUTABLE_SUFFIX} ${LM_LLVM_DIR}/lld-link${CMAKE_EXECUTABLE_SUFFIX} DESTINATION llvm/bin OPTIONAL) +elseif (ANDROID) + # Android packaging is an APK, built by tools/android/build_apk.sh (docs/ANDROID.md). else () # Linux (docs/LINUX.md): clang and ld.lld are usually symlinks (clang -> clang-21, # ld.lld -> lld); copy the real binaries under the names the setup looks for (lld picks diff --git a/CMakePresets.json b/CMakePresets.json index 8f3f59d1..9c13cee0 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -55,6 +55,26 @@ "lhs": "${hostSystemName}", "rhs": "Darwin" } + }, + { + "name": "android-arm64", + "displayName": "Android arm64-v8a (NDK clang, Ninja; docs/ANDROID.md)", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build/${presetName}", + "toolchainFile": "$env{ANDROID_NDK}/build/cmake/android.toolchain.cmake", + "environment": { + "PKG_CONFIG_LIBDIR": "/nonexistent-android-pkgconfig", + "PKG_CONFIG_PATH": "" + }, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "RelWithDebInfo", + "ANDROID_ABI": "arm64-v8a", + "ANDROID_PLATFORM": "android-28", + "ANDROID_STL": "c++_static", + "AURORA_SDL3_PROVIDER": "vendor", + "AURORA_NOD_PROVIDER": "package", + "AURORA_NOD_LINKAGE": "static" + } } ], "buildPresets": [ @@ -69,6 +89,10 @@ { "name": "macos-clang", "configurePreset": "macos-clang" + }, + { + "name": "android-arm64", + "configurePreset": "android-arm64" } ] } diff --git a/docs/ANDROID.md b/docs/ANDROID.md new file mode 100644 index 00000000..87f0abf5 --- /dev/null +++ b/docs/ANDROID.md @@ -0,0 +1,157 @@ +# Android port + +The port builds for Android phones and tablets (arm64-v8a, Android 9 / API 28 or newer): +the same runtime, recompiler and first-run setup as on Windows and Linux, Aurora on Dawn's +Vulkan backend (OpenGL ES fallback), SDL3 for the window, input and audio. The game module +that setup compiles from the player's disc is built **on the device**, with a clang + lld +that the APK carries. Everything Android-specific is behind `__ANDROID__` / `if (ANDROID)`, +the `android-arm64` CMake preset, `packaging/android/` and `tools/android/`; desktop builds +are unchanged. + +**Status (October 2026):** builds and packages; not yet run on a device. See +"Not verified yet" at the end. + +## For players + +- Needs: a 64-bit ARM device with Android 9+, a Vulkan-capable GPU (most phones from 2018 + on), 4 GB of RAM or more recommended, about 1 GB of free storage, and your own disc image + (ISO, RVZ, ...) of the USA (GLME01) and/or European (GLMP01) release, copied to the device. +- Install the APK (allow "install unknown apps" for your file manager or browser). +- First start: tap **Browse...**, pick the disc image in the system file picker, then + **Install and play**. The game is translated and compiled on the phone once; that takes + several minutes (keep the app open, ideally plugged in). Then the shaders are prepared. + Later starts go straight to the game. +- Controls: a Bluetooth or USB controller works like on PC (F1 > Controls). Without one, + touch controls are shown: the left side of the screen is the stick (it appears where you + put your thumb), the yellow circle is the C-stick, A/B/X/Y on the right, L/R/Z at the top + corners, START and MENU at the top. **MENU** (or the **Back** button) opens the options + menu, which is the F1 menu of the PC version. F1 > Controls > Touch sets when the touch + controls show, their size and opacity. +- Logs for bug reports: the app writes `last_run.log` (and `previous_run.log`) in its + private files folder; with a USB cable and `adb`: `adb logcat -s LuigisMansion` while it + runs, or `adb shell run-as dev.lmport.luigismansion cat files/last_run.log` for a + debuggable build. + +## Building + +On a Linux (or WSL) machine: + +``` +# Once: the disc image library (nod has no Android release) and the on-device compiler. +export ANDROID_NDK=~/android-ndk-r29 # NDK r29 or newer (C++20 std::jthread) +rustup target add aarch64-linux-android # for nod (Rust) +tools/android/build_nod.sh # -> build/android-nod/libnod-android-aarch64.tar.gz +tools/android/build_llvm.sh # -> build/android-llvm/libllvm.so (hours) + +# The program (libmain.so) and the APK. +tools/android/build.sh # cmake --preset android-arm64 + build +export ANDROID_HOME=~/android-sdk # build-tools 37 (34's d8 crashed here) + platforms;android-35 +LM_ANDROID_LLVM=build/android-llvm/libllvm.so tools/android/build_apk.sh +# -> build/LuigisMansionPort-android-arm64.apk +adb install -r build/LuigisMansionPort-android-arm64.apk +``` + +Requirements: CMake 3.25+, Ninja, a host C++ compiler (clang), JDK 17+ (javac, keytool), +Python 3 (icon script only), git, curl, zip. No Gradle: `build_apk.sh` runs aapt2, javac, +d8, zipalign and apksigner from the SDK. It signs with `$LM_KEYSTORE` / `$LM_KEYSTORE_PASS`, +or with a local key it creates in `build/android-debug.keystore` (keep it: an update has +to be signed with the same key, otherwise Android asks to uninstall first, which deletes the +app's files: saves, settings, built game). + +`build_llvm.sh` builds LLVM's clang and lld (release 21.1.8 by default, `LM_LLVM_VERSION`) +for Android with only the AArch64 target, as one multi-call binary. That build is long but +only needs redoing for a new LLVM. Without `LM_ANDROID_LLVM` the APK is built without a +compiler and setup reports it missing. + +## How it works + +| Area | Desktop | Android | +|------|---------|---------| +| Program | `LuigisMansionRecomp(.exe)` | `libmain.so`, loaded by SDL's Java activity (`dev.lmport.LMActivity`), entry `SDL_main` (aurora::main; linked with `-u SDL_main`) | +| Game module | `module.dll` / `module.so` (x86-64) | `module.so` for `aarch64-linux-android28`, same freestanding flags plus `-mno-outline-atomics` (no libgcc for the `__aarch64_*` helpers) and `-fsigned-char`; made read-only after the build (Android 14+ refuses writable code) | +| Bundled compiler | `llvm/bin/clang` + `ld.lld` / `lld-link` | `lib/arm64-v8a/libllvm.so` in the APK: the `llvm-driver` multi-call binary, run as `libllvm.so clang ...` / `libllvm.so ld.lld ...` | +| Compile jobs | one per hardware thread | also at most one per 2.5 GB of RAM (a large generated file can take over 1 GB; Android kills the app when memory runs out); `LM_COMPILE_JOBS` overrides | +| Settings, install.ini, modules, overlays, memory cards | `%APPDATA%` / XDG folders | `Context.getFilesDir()` (`LM_ANDROID_FILES`) | +| GPU caches | `%APPDATA%` / `$XDG_CACHE_HOME` | `Context.getCacheDir()` (`LM_ANDROID_CACHE`) | +| `pipelines.bin` | next to the executable | APK asset, copied to `files/res` on the first start of each app version (`LM_ANDROID_RES`) | +| Disc images | file paths | `content://` URIs from the system file picker (SDL's `ACTION_OPEN_DOCUMENT`); opened through the ContentResolver with a persistent read permission, read by nod and Aurora through SDL streams (`SDL_IOFromFile` opens content URIs; `port::discOpenPath`) | +| Restart (setup changes) | exec of the executable | `LMRestartActivity` in its own process (`:restart`) starts the game again once the old process has exited | +| Logging | console / launcher script | stdout + stderr to logcat (tag `LuigisMansion`) and `files/last_run.log` (`port::android::redirectOutput`) | +| Crashes | own signal/SEH handler | Android's debuggerd (tombstone + logcat backtrace) | +| Input | keyboard, controllers | controllers (SDL), touch controls (`src/recomp/touch.cpp`) merged into port 1 in PADRead, Back button = F1 (`SDL_HINT_ANDROID_TRAP_BACK_BUTTON`) | +| Window | windowed / fullscreen | always fullscreen (immersive), landscape | +| Default render resolution | window size | 2 x 480p (F1 > Visuals), for heat and battery | + +Why the compiler is a "library": Android only lets an app run programs from its native +library folder (files in its data folder cannot be executed since Android 10), and the +installer only unpacks `lib*.so` files there (`android:extractNativeLibs="true"`). The game +module itself is loaded with `dlopen`, which is allowed from the data folder. + +The JNI calls from native code (`src/port/android.cpp`) go to static methods of +`LMActivity` through the class of `SDL_GetAndroidActivity()`, which works on any thread. + +The menus use the port's menu size (F1 > Visuals > General > Menu size, `ui_scale.cpp`): its +Auto measures the window in ImGui units, which SDL already scales by the screen density on +phones. The updater (`update.cpp`) is off: new versions come as a new APK. + +Plain `char` is signed on x86 but unsigned on ARM, so the runtime and the module are built +with `-fsigned-char` to behave as the port does on PC. + +### Adreno: OpenGL ES + +On Qualcomm Adreno GPUs the port uses Dawn's OpenGL ES backend, not Vulkan (`main.cpp`, +`ro.hardware.egl` / `ro.hardware.vulkan` = `adreno`; `LM_BACKEND=vulkan` overrides for tests). +Adreno's Vulkan driver miscompiles the 16-bit unpacking in Aurora's vertex fetch (storage +buffer reads): on an Adreno 740 (Nubia NX729J, driver 512.863.1) the title backdrop and the +file-select pictures were drawn as vertical stripes (every pixel sampled the texture's first +row) and the file-select text was missing, while the 3D world looked right. Checked on the +device: the texture data, the texcoords the game sends (U16, frac 15) and the texcoord scales +are correct; the raw interpolated texcoord t was constant in the title draw. Rewriting the +unpacking (shift and mask instead of `extractBits`, byte loads) did not help (byte loads broke +positions too), as Aurora's author found on Adreno 7xx/8xx (Dusklight issue #750). GLES draws +all of it correctly. + +### Depth copies on OpenGL ES (Luigi's shadow) + +OpenGL ES runs Dawn in compatibility mode, where Aurora skipped EFB depth copies, so the game's +Z16 copy (Luigi's self-shadow map, `fn_8005D8CC`) was never made and Luigi cast no shadow. +Compatibility mode forbids `textureLoad` on depth textures and sampling them with a +non-comparison sampler (both confirmed with `AURORA_DAWN_VALIDATION=1`), so Aurora patch 0251 +reads each texel's 24-bit depth by a binary search of 24 comparison samples +(`textureSampleCompareLevel`, nearest, LessEqual): the same 24-bit value as the core path's +`textureLoad`. Only compatibility devices use it; core devices keep the original shaders. The +24 steps are unrolled: the Adreno GLES compiler hung for over 100 s on the loop form (start-up +"stopped responding"). Verified on the Adreno 740: shadow back, 1186 Z16 copies with validation +on and no errors. + +### GitHub Actions + +`.github/workflows/android.yml` builds the APK on every push to `android-port` (and by hand: +Actions > Android > Run workflow); the APK is attached to the run. A tag `android-*` also +publishes it as a pre-release. The compiler (`libllvm.so`) is built only when its script, the +LLVM version or the NDK changes (about two hours) and kept in the Actions cache. For APKs that +install over each other, add the signing keystore as the secret `ANDROID_KEYSTORE_BASE64` +(base64 of the file; key alias `lmport`, password in `ANDROID_KEYSTORE_PASS` or `android`). + +### Building on a restricted network + +The build downloads Dawn, SDL3 and other dependencies at configure time like on desktop. +Where GitHub archive downloads are blocked but `git clone` works, a CMake dependency +provider (`-DCMAKE_PROJECT_TOP_LEVEL_INCLUDES=`) can point FetchContent at +local git checkouts; `tools/android/build.sh` passes extra arguments through to CMake. + +## Not verified yet + +Built and packaged in a cloud workspace without an Android device or a game disc, so: + +- Nothing has run on a device yet: rendering on mobile GPUs (Aurora's accuracy features: + EFB copies to RAM, 6-bit blending, shadows, enhanced lighting), performance, audio, the + touch controls' feel, controller hot-plug. +- The on-device setup (recompiling the DOL, compiling 33 files with the bundled clang, + linking, `dlopen`) has only been tried with a synthetic module (compile, link, symbol + checks); memory use and time on a real phone are unknown. +- Large disc images from cloud-backed file providers (Google Drive + and similar) may be slow or not seekable; a copy in the device's own storage + (Downloads) is the safe choice. +- First things to check on a device: setup to the title screen, then F1 > Visuals > + Rendering toggles if anything renders wrong or slowly. diff --git a/docs/TEXTURE_PACKS.md b/docs/TEXTURE_PACKS.md new file mode 100644 index 00000000..f57ade27 --- /dev/null +++ b/docs/TEXTURE_PACKS.md @@ -0,0 +1,32 @@ +# Texture packs + +The port loads replacement textures made for Dolphin's "Load Custom Textures": files named +`tex1_x[_m]_[_]_.png` (or `.dds`), for +example Henriko Magnifico's Luigi's Mansion 4K pack. Download packs from their authors; none are +included. + +## Installing + +- **Windows / Linux:** copy the pack's texture folder (for Luigi's Mansion usually `GLM`, found in + Dolphin packs under `Load/Textures/`) into the `textures` folder of the game's data folder. + F1 > Visuals > Texture pack shows the folder and opens it ("Open textures folder"). Any layout + works: files are found in subfolders too. "Reload textures" picks up changes without a restart. +- **Android:** F1 > Visuals > Texture pack > "Import .zip" (the pack's archive) or "Import + folder" (an unpacked pack). Only the texture files are copied into the app. A `.7z`/`.rar` + must be unpacked first (e.g. with a file manager app), then imported as a folder. Use a pack's + 1080p version on phones: 4K textures take several GB of storage and much more memory. + +"Use custom textures" switches the pack off and on at once. + +## How it works + +Aurora (`extern/aurora`, `lib/gfx/texture_replacement.cpp`) hashes each texture the game loads +the way Dolphin names them: xxHash64 (seed 0) of the GX texture data and, for palette formats, of +the palette range the texture uses. A matching file replaces the texture (mipmaps from the file +or its `_mipN` sidecars). `src/recomp/texture_pack.cpp` points it at `/textures` +(`port::dataDir()`), keeps the registrations so the setting can unload them, and draws the menu. +On Android, `LMActivity` copies `tex1_*.png/.dds` files from the picked `.zip` or folder into +`files/textures//` (flat: only file names are used, never archive paths). + +Packs made from the US game mostly match the European game too (most textures are the same +data); textures with region-specific content (text) stay the original ones. diff --git a/packaging/android/AndroidManifest.xml b/packaging/android/AndroidManifest.xml new file mode 100644 index 00000000..d42e6819 --- /dev/null +++ b/packaging/android/AndroidManifest.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/android/java/dev/lmport/LMActivity.java b/packaging/android/java/dev/lmport/LMActivity.java new file mode 100644 index 00000000..1dd2fe60 --- /dev/null +++ b/packaging/android/java/dev/lmport/LMActivity.java @@ -0,0 +1,377 @@ +package dev.lmport; + +import android.content.ContentResolver; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageInfo; +import android.content.res.AssetManager; +import android.database.Cursor; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.ParcelFileDescriptor; +import android.provider.OpenableColumns; +import android.system.Os; +import android.util.Log; +import android.view.WindowManager; + +import org.libsdl.app.SDLActivity; +import org.libsdl.app.SDLSurface; + +import dev.encounter.aurora.AuroraSurface; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * The game's activity (docs/ANDROID.md): SDL's activity running libmain.so (the port's + * runtime, SDL3, Aurora). Before the native side starts it exports the app's folders as + * environment variables (src/port/android.cpp reads them) and copies the APK assets the + * runtime reads by path. The static methods are called from native code through JNI. + */ +public class LMActivity extends SDLActivity { + private static final String TAG = "LuigisMansion"; + private static LMActivity sSelf; + + @Override + protected void onCreate(Bundle savedInstanceState) { + sSelf = this; + try { + final String files = getFilesDir().getAbsolutePath(); + Os.setenv("LM_ANDROID_FILES", files, true); + Os.setenv("LM_ANDROID_CACHE", getCacheDir().getAbsolutePath(), true); + Os.setenv("LM_ANDROID_LIBDIR", getApplicationInfo().nativeLibraryDir, true); + Os.setenv("HOME", files, true); + Os.setenv("TMPDIR", getCacheDir().getAbsolutePath(), true); + final File res = new File(getFilesDir(), "res"); + copyAssets(res); + saveCrashLog(); + Os.setenv("LM_ANDROID_RES", res.getAbsolutePath(), true); + } catch (Exception e) { + Log.e(TAG, "setup of the native environment failed", e); + } + super.onCreate(savedInstanceState); + // The game runs with the screen on (also while the first-run setup compiles). + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + } + + // SDL3 is linked into libmain.so (static), so there is only one library to load. + @Override + protected String[] getLibraries() { + return new String[] {"main"}; + } + + @Override + protected String[] getArguments() { + final Intent i = getIntent(); + if (i != null && i.getBooleanExtra("setup", false)) return new String[] {"--setup"}; + return new String[0]; + } + + // Aurora tracks surface readiness through its own SDLSurface subclass. + @Override + protected SDLSurface createSDLSurface(Context context) { + return new AuroraSurface(context); + } + + // Copies the assets (pipelines.bin, ...) to `dir` once per app version. + private void copyAssets(File dir) throws Exception { + long version; + final PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0); + version = Build.VERSION.SDK_INT >= 28 ? pi.getLongVersionCode() : pi.versionCode; + final File stamp = new File(dir, ".version"); + final String want = version + " " + pi.lastUpdateTime; + if (stamp.exists() && want.equals(readSmall(stamp))) return; + dir.mkdirs(); + final AssetManager am = getAssets(); + final String[] names = am.list(""); + if (names != null) { + byte[] buf = new byte[1 << 16]; + for (String name : names) { + InputStream in; + try { + in = am.open(name); + } catch (Exception e) { + continue; // a folder + } + try (InputStream is = in; OutputStream os = new FileOutputStream(new File(dir, name))) { + for (int n; (n = is.read(buf)) > 0;) os.write(buf, 0, n); + } + } + } + try (OutputStream os = new FileOutputStream(stamp)) { + os.write(want.getBytes("UTF-8")); + } + } + + /** + * Copies the previous run's log (files/last_run.log, before the native side renames it) to + * Download/LuigisMansionPort/previous_run.log on every start, replacing the last copy, so a + * player can send the log of a run that crashed or froze without any extra tools. + */ + private void saveCrashLog() { + final File log = new File(getFilesDir(), "last_run.log"); + if (!log.exists() || log.length() == 0 || Build.VERSION.SDK_INT < 29) return; + final android.content.ContentResolver cr = getContentResolver(); + final Uri downloads = android.provider.MediaStore.Downloads.EXTERNAL_CONTENT_URI; + final String dir = "Download/LuigisMansionPort/"; + final String name = "previous_run.log"; + try { + // Our earlier copy (an app may delete the files it created). + cr.delete(downloads, + android.provider.MediaStore.Downloads.DISPLAY_NAME + "=? AND " + + android.provider.MediaStore.Downloads.RELATIVE_PATH + "=?", + new String[] {name, dir}); + } catch (Exception e) { + Log.w(TAG, "could not remove the old log copy", e); + } + try { + final android.content.ContentValues v = new android.content.ContentValues(); + v.put(android.provider.MediaStore.Downloads.DISPLAY_NAME, name); + v.put(android.provider.MediaStore.Downloads.MIME_TYPE, "text/plain"); + v.put(android.provider.MediaStore.Downloads.RELATIVE_PATH, dir); + final Uri uri = cr.insert(downloads, v); + if (uri == null) { + Log.w(TAG, "MediaStore refused the log copy"); + return; + } + try (InputStream in = new java.io.FileInputStream(log); OutputStream out = cr.openOutputStream(uri)) { + byte[] buf = new byte[1 << 16]; + for (int n; (n = in.read(buf)) > 0;) out.write(buf, 0, n); + } + Log.i(TAG, "previous run's log saved to " + dir + name); + } catch (Exception e) { + Log.w(TAG, "could not save the previous run's log", e); + } + } + + private static String readSmall(File f) { + try (InputStream in = new java.io.FileInputStream(f)) { + byte[] b = new byte[256]; + int n = in.read(b); + return n > 0 ? new String(b, 0, n, "UTF-8") : ""; + } catch (Exception e) { + return ""; + } + } + + // ---- Called from native code (src/port/android.cpp) ---- + + /** + * Opens a disc image the user picked with the system file picker (a content:// URI) and + * returns a file descriptor the native side reads through /proc/self/fd, or -1. The read + * permission is made persistent so the next start can open it again without asking. + */ + public static int openContentFd(String uriString) { + if (sSelf == null) return -1; + try { + final Uri uri = Uri.parse(uriString); + final ContentResolver cr = sSelf.getContentResolver(); + try { + cr.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION); + } catch (Exception e) { + // Not persistable (some providers): works for this run only. + } + final ParcelFileDescriptor pfd = cr.openFileDescriptor(uri, "r"); + return pfd != null ? pfd.detachFd() : -1; + } catch (Exception e) { + Log.w(TAG, "could not open " + uriString, e); + return -1; + } + } + + /** The file name of a content:// URI (for the setup screen), or null. */ + public static String contentDisplayName(String uriString) { + if (sSelf == null) return null; + try (Cursor c = sSelf.getContentResolver().query(Uri.parse(uriString), + new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null)) { + if (c != null && c.moveToFirst()) return c.getString(0); + } catch (Exception e) { + Log.w(TAG, "no name for " + uriString, e); + } + return null; + } + + /** PowerManager thermal status (0 none ... 6 shutdown), -1 if unknown. */ + public static int thermalStatus() { + if (sSelf == null || Build.VERSION.SDK_INT < 29) return -1; + final android.os.PowerManager pm = (android.os.PowerManager) sSelf.getSystemService(Context.POWER_SERVICE); + return pm != null ? pm.getCurrentThermalStatus() : -1; + } + + /** Opens the system share sheet with the game's log (LogProvider). */ + public static void shareLog() { + if (sSelf == null) return; + sSelf.runOnUiThread(new Runnable() { @Override public void run() { + final Intent send = new Intent(Intent.ACTION_SEND); + send.setType("text/plain"); + send.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://" + LogProvider.AUTHORITY + "/last_run.log")); + send.putExtra(Intent.EXTRA_SUBJECT, "Luigi's Mansion Port log"); + send.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + sSelf.startActivity(Intent.createChooser(send, "Share log")); + }}); + } + + // ---- Texture packs (src/recomp/texture_pack.cpp) ---- + + private static final int REQ_TEXTURE_ZIP = 7101; + private static final int REQ_TEXTURE_DIR = 7102; + private static String sTextureDest; + // 0 idle, 1 running, 2 done, 3 failed (port::android::ImportState) + private static volatile int sTexState = 0; + private static volatile int sTexCount = 0; + private static volatile String sTexMessage = ""; + + /** Opens the system picker for a texture pack .zip or folder; the copy starts when one is chosen. */ + public static void pickTexturePack(final boolean folder, final String destDir) { + if (sSelf == null) return; + sTextureDest = destDir; + sSelf.runOnUiThread(new Runnable() { @Override public void run() { + final Intent i; + if (folder) { + i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); + } else { + i = new Intent(Intent.ACTION_OPEN_DOCUMENT); + i.addCategory(Intent.CATEGORY_OPENABLE); + i.setType("*/*"); + i.putExtra(Intent.EXTRA_MIME_TYPES, new String[] {"application/zip", "application/x-zip-compressed", "application/octet-stream"}); + } + try { + sSelf.startActivityForResult(i, folder ? REQ_TEXTURE_DIR : REQ_TEXTURE_ZIP); + } catch (Exception e) { + sTexState = 3; + sTexMessage = "No file picker available: " + e; + } + }}); + } + + /** "||" for the native side. */ + public static String texturePackStatus() { + return sTexState + "|" + sTexCount + "|" + sTexMessage; + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (requestCode != REQ_TEXTURE_ZIP && requestCode != REQ_TEXTURE_DIR) { + super.onActivityResult(requestCode, resultCode, data); + return; + } + final Uri uri = data != null ? data.getData() : null; + if (resultCode != RESULT_OK || uri == null || sTextureDest == null) { + sTexState = 0; + return; + } + final boolean folder = requestCode == REQ_TEXTURE_DIR; + sTexState = 1; + sTexCount = 0; + sTexMessage = ""; + new Thread(new Runnable() { @Override public void run() { + try { + final int n = folder ? importTextureFolder(uri) : importTextureZip(uri); + sTexMessage = n > 0 ? "Imported " + n + " texture files." + : "No texture files (tex1_*.png / .dds) found in what you picked."; + sTexState = n > 0 ? 2 : 3; + } catch (Throwable t) { + Log.e(TAG, "texture pack import failed", t); + sTexMessage = "Import failed: " + t.getMessage(); + sTexState = 3; + } + }}, "texture-import").start(); + } + + // Texture files only: tex1_*.png / tex1_*.dds (Dolphin's naming; mip sidecars included). + private static boolean isTextureName(String name) { + final String n = name.toLowerCase(java.util.Locale.ROOT); + return n.startsWith("tex1_") && (n.endsWith(".png") || n.endsWith(".dds")); + } + + // A folder name for the pack from what the player picked (no path separators). + private static File packDir(String label) { + String name = label == null ? "" : label.replaceAll("\\.(zip|ZIP)$", "").replaceAll("[^A-Za-z0-9 ._()-]", "_").trim(); + if (name.isEmpty() || name.startsWith(".")) name = "pack"; + final File dir = new File(sTextureDest, name); + deleteTree(dir); // importing the same pack again replaces it + dir.mkdirs(); + return dir; + } + + private static void deleteTree(File f) { + final File[] kids = f.listFiles(); + if (kids != null) for (File k : kids) deleteTree(k); + f.delete(); + } + + // Writes one texture by its bare file name (flat: names are unique by content hash, and no + // path from the archive is used, so nothing can land outside the pack folder). + private static void writeTexture(File dir, String name, InputStream in, byte[] buf) throws Exception { + final File tmp = new File(dir, name + ".part"); + try (OutputStream os = new FileOutputStream(tmp)) { + for (int n; (n = in.read(buf)) > 0;) os.write(buf, 0, n); + } + if (!tmp.renameTo(new File(dir, name))) throw new java.io.IOException("could not write " + name); + sTexCount++; + } + + private static int importTextureZip(Uri uri) throws Exception { + final File dir = packDir(contentDisplayName(uri.toString())); + final byte[] buf = new byte[1 << 16]; + try (InputStream raw = sSelf.getContentResolver().openInputStream(uri); + java.util.zip.ZipInputStream zip = new java.util.zip.ZipInputStream(new java.io.BufferedInputStream(raw, 1 << 16))) { + for (java.util.zip.ZipEntry e; (e = zip.getNextEntry()) != null;) { + if (e.isDirectory()) continue; + String name = e.getName(); + name = name.substring(Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')) + 1); + if (isTextureName(name)) writeTexture(dir, name, zip, buf); + } + } + return sTexCount; + } + + private static int importTextureFolder(Uri tree) throws Exception { + final ContentResolver cr = sSelf.getContentResolver(); + final String rootId = android.provider.DocumentsContract.getTreeDocumentId(tree); + String label = rootId.substring(rootId.lastIndexOf(':') + 1); + label = label.substring(label.lastIndexOf('/') + 1); + final File dir = packDir(label); + final byte[] buf = new byte[1 << 16]; + final java.util.ArrayDeque pending = new java.util.ArrayDeque<>(); + pending.add(rootId); + while (!pending.isEmpty()) { + final String id = pending.poll(); + final Uri children = android.provider.DocumentsContract.buildChildDocumentsUriUsingTree(tree, id); + try (Cursor c = cr.query(children, new String[] { + android.provider.DocumentsContract.Document.COLUMN_DOCUMENT_ID, + android.provider.DocumentsContract.Document.COLUMN_DISPLAY_NAME, + android.provider.DocumentsContract.Document.COLUMN_MIME_TYPE}, null, null, null)) { + if (c == null) continue; + while (c.moveToNext()) { + final String childId = c.getString(0), name = c.getString(1), mime = c.getString(2); + if (android.provider.DocumentsContract.Document.MIME_TYPE_DIR.equals(mime)) { + pending.add(childId); + } else if (name != null && isTextureName(name) && name.indexOf('/') < 0) { + final Uri doc = android.provider.DocumentsContract.buildDocumentUriUsingTree(tree, childId); + try (InputStream in = cr.openInputStream(doc)) { + writeTexture(dir, name, in, buf); + } + } + } + } + } + return sTexCount; + } + + /** + * Restarts the game in a new process (after setup changes; F1 > Game). A small activity + * in its own process (LMRestartActivity) starts the game again once this process is gone. + */ + public static void relaunch(boolean setup) { + if (sSelf == null) return; + final Intent i = new Intent(sSelf, LMRestartActivity.class); + i.putExtra("setup", setup); + i.putExtra("pid", android.os.Process.myPid()); + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + sSelf.startActivity(i); + } +} diff --git a/packaging/android/java/dev/lmport/LMRestartActivity.java b/packaging/android/java/dev/lmport/LMRestartActivity.java new file mode 100644 index 00000000..afd5ab6d --- /dev/null +++ b/packaging/android/java/dev/lmport/LMRestartActivity.java @@ -0,0 +1,39 @@ +package dev.lmport; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; + +/** + * Runs in its own process (":restart", AndroidManifest.xml): waits for the game's process to + * exit, then starts LMActivity again in a fresh one. Native code cannot restart itself on + * Android (no fork/exec), see port::relaunch. + */ +public class LMRestartActivity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + final int pid = getIntent().getIntExtra("pid", -1); + final boolean setup = getIntent().getBooleanExtra("setup", false); + final Handler h = new Handler(Looper.getMainLooper()); + h.postDelayed(new Runnable() { + int tries = 0; + + @Override + public void run() { + if (pid > 0 && new java.io.File("/proc/" + pid).exists() && tries++ < 40) { + h.postDelayed(this, 50); // the old process is still shutting down + return; + } + final Intent i = new Intent(LMRestartActivity.this, LMActivity.class); + i.putExtra("setup", setup); + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + startActivity(i); + finish(); + Runtime.getRuntime().exit(0); + } + }, 100); + } +} diff --git a/packaging/android/java/dev/lmport/LogProvider.java b/packaging/android/java/dev/lmport/LogProvider.java new file mode 100644 index 00000000..8b2d002c --- /dev/null +++ b/packaging/android/java/dev/lmport/LogProvider.java @@ -0,0 +1,71 @@ +package dev.lmport; + +import android.content.ContentProvider; +import android.content.ContentValues; +import android.database.Cursor; +import android.database.MatrixCursor; +import android.net.Uri; +import android.os.ParcelFileDescriptor; +import android.provider.OpenableColumns; + +import java.io.File; +import java.io.FileNotFoundException; + +/** + * Hands the game's log files (files/last_run.log, previous_run.log) to the app the player + * shares them with (F1 > Enhancements > Debug > Share log; LMActivity.shareLog). Read-only, + * only those two files, and only to apps the share grants access to. + */ +public class LogProvider extends ContentProvider { + static final String AUTHORITY = "dev.lmport.luigismansion.logs"; + + private File fileFor(Uri uri) throws FileNotFoundException { + final String name = uri.getLastPathSegment(); + if (!"last_run.log".equals(name) && !"previous_run.log".equals(name)) throw new FileNotFoundException(name); + final File f = new File(getContext().getFilesDir(), name); + if (!f.exists()) throw new FileNotFoundException(name); + return f; + } + + @Override + public boolean onCreate() { + return true; + } + + @Override + public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { + return ParcelFileDescriptor.open(fileFor(uri), ParcelFileDescriptor.MODE_READ_ONLY); + } + + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] args, String sort) { + try { + final File f = fileFor(uri); + final MatrixCursor c = new MatrixCursor(new String[] {OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE}); + c.addRow(new Object[] {f.getName(), f.length()}); + return c; + } catch (FileNotFoundException e) { + return null; + } + } + + @Override + public String getType(Uri uri) { + return "text/plain"; + } + + @Override + public Uri insert(Uri uri, ContentValues values) { + return null; + } + + @Override + public int delete(Uri uri, String selection, String[] args) { + return 0; + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] args) { + return 0; + } +} diff --git a/packaging/android/res/mipmap-hdpi/ic_launcher.png b/packaging/android/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000..43ca0898 Binary files /dev/null and b/packaging/android/res/mipmap-hdpi/ic_launcher.png differ diff --git a/packaging/android/res/mipmap-mdpi/ic_launcher.png b/packaging/android/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000..f91fc63a Binary files /dev/null and b/packaging/android/res/mipmap-mdpi/ic_launcher.png differ diff --git a/packaging/android/res/mipmap-xhdpi/ic_launcher.png b/packaging/android/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000..0cfca04d Binary files /dev/null and b/packaging/android/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/packaging/android/res/mipmap-xxhdpi/ic_launcher.png b/packaging/android/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000..358b856c Binary files /dev/null and b/packaging/android/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/packaging/android/res/mipmap-xxxhdpi/ic_launcher.png b/packaging/android/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..a65275fe Binary files /dev/null and b/packaging/android/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/packaging/android/res/values/strings.xml b/packaging/android/res/values/strings.xml new file mode 100644 index 00000000..1be83717 --- /dev/null +++ b/packaging/android/res/values/strings.xml @@ -0,0 +1,4 @@ + + + Luigi\'s Mansion Port + diff --git a/patches/aurora/0251-compat-depth-copies.patch b/patches/aurora/0251-compat-depth-copies.patch new file mode 100644 index 00000000..4d330ee7 --- /dev/null +++ b/patches/aurora/0251-compat-depth-copies.patch @@ -0,0 +1,171 @@ +--- a/lib/gfx/tex_copy_conv.cpp ++++ b/lib/gfx/tex_copy_conv.cpp +@@ -409,8 +409,13 @@ + // Depth copies from a multisampled EFB (MSAA enhancement): the same conversions reading sample 0. + static wgpu::BindGroupLayout g_depthBindGroupLayoutMS; + static absl::flat_hash_map g_depthPipelinesMS; ++// 0251: compatibility mode (OpenGL ES) forbids textureLoad on depth textures and sampling them with ++// non-comparison samplers; the depth copies there find each texel's 24-bit depth by a binary search ++// of comparison samples (binding 2: nearest, LessEqual). ++static wgpu::BindGroupLayout g_depthBindGroupLayoutCompat; + static wgpu::Sampler g_nearestSampler; + static wgpu::Sampler g_linearSampler; ++static wgpu::Sampler g_depthCompareSampler; // 0251 + static absl::flat_hash_map g_pipelines; + static wgpu::RenderPipeline g_blitPipeline; + static wgpu::BindGroupLayout g_depthSnapshotBindGroupLayout; +@@ -633,7 +638,7 @@ + Log.fatal("Output format mismatch for {}", conv.fmt); + } + } +- // Skip depth copies in compatibility mode ++ // Depth copies: textureLoad on core devices; compatibility mode below (0251). + if (webgpu::g_hasCoreFeatures) { + for (const auto& conv : DepthConvPipelines) { + g_pipelines[conv.fmt] = create_pipeline(conv, DepthShaderPreamble, g_depthBindGroupLayout); +@@ -651,6 +656,93 @@ + create_depth_snapshot_pipeline(DepthSnapshotShader, g_depthSnapshotBindGroupLayout, "Depth Snapshot"); + g_depthSnapshotPipelineMS = + create_depth_snapshot_pipeline(DepthSnapshotShaderMS, g_depthSnapshotBindGroupLayoutMS, "Depth Snapshot MS"); ++ } else { ++ // 0251: depth copies in compatibility mode (no MSAA there, so single-sampled only). ++ static constexpr std::array depthBindGroupLayoutEntriesCompat{ ++ wgpu::BindGroupLayoutEntry{ ++ .binding = 0, ++ .visibility = wgpu::ShaderStage::Fragment, ++ .texture = ++ wgpu::TextureBindingLayout{ ++ .sampleType = wgpu::TextureSampleType::Depth, ++ .viewDimension = wgpu::TextureViewDimension::e2D, ++ }, ++ }, ++ wgpu::BindGroupLayoutEntry{ ++ .binding = 1, ++ .visibility = wgpu::ShaderStage::Vertex, ++ .buffer = ++ wgpu::BufferBindingLayout{ ++ .type = wgpu::BufferBindingType::Uniform, ++ }, ++ }, ++ wgpu::BindGroupLayoutEntry{ ++ .binding = 2, ++ .visibility = wgpu::ShaderStage::Fragment, ++ .sampler = ++ wgpu::SamplerBindingLayout{ ++ .type = wgpu::SamplerBindingType::Comparison, ++ }, ++ }, ++ }; ++ static constexpr wgpu::BindGroupLayoutDescriptor depthBindGroupLayoutDescriptorCompat{ ++ .label = "TexCopyConv Depth Compat Bind Group Layout", ++ .entryCount = depthBindGroupLayoutEntriesCompat.size(), ++ .entries = depthBindGroupLayoutEntriesCompat.data(), ++ }; ++ g_depthBindGroupLayoutCompat = g_device.CreateBindGroupLayout(&depthBindGroupLayoutDescriptorCompat); ++ std::string preamble = DepthShaderPreamble; ++ const auto replace = [&preamble](std::string_view from, std::string_view to) { ++ const auto pos = preamble.find(from); ++ CHECK(pos != std::string::npos, "tex_copy_conv: compat depth preamble: '{}' not found", from); ++ preamble.replace(pos, from.size(), to); ++ }; ++ // depth >= ref is one comparison sample; 24 of them give the depth's 24 bits (floor(depth * (2^24 - 1)), ++ // the value the core path rounds to, exact for 24-bit depth formats). ++ replace("var src: texture_depth_2d;", R"(var src: texture_depth_2d; ++@group(0) @binding(2) var src_samp: sampler_comparison; ++ ++fn compat_depth(coord: vec2i, texSize: vec2i) -> f32 { ++ let uv = (vec2f(coord) + vec2f(0.5)) / vec2f(texSize); ++ // Unrolled: the Adreno GLES compiler hung (> 100 s) on the loop form. ++ var lo = 0u; ++ lo = select(lo, lo | 8388608u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 8388608u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 4194304u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 4194304u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 2097152u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 2097152u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 1048576u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 1048576u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 524288u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 524288u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 262144u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 262144u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 131072u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 131072u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 65536u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 65536u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 32768u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 32768u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 16384u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 16384u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 8192u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 8192u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 4096u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 4096u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 2048u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 2048u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 1024u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 1024u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 512u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 512u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 256u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 256u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 128u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 128u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 64u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 64u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 32u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 32u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 16u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 16u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 8u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 8u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 4u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 4u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 2u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 2u) / 16777215.0) > 0.5); ++ lo = select(lo, lo | 1u, textureSampleCompareLevel(src, src_samp, uv, f32(lo | 1u) / 16777215.0) > 0.5); ++ return f32(lo) / 16777215.0; ++})"); ++ replace("let depth = textureLoad(src, coord, 0);", "let depth = compat_depth(coord, texSize);"); ++ static constexpr wgpu::SamplerDescriptor compareSamplerDescriptor{ ++ .label = "TexCopyConv Depth Compare Sampler", ++ .magFilter = wgpu::FilterMode::Nearest, ++ .minFilter = wgpu::FilterMode::Nearest, ++ .compare = wgpu::CompareFunction::LessEqual, ++ }; ++ g_depthCompareSampler = g_device.CreateSampler(&compareSamplerDescriptor); ++ for (const auto& conv : DepthConvPipelines) { ++ g_pipelines[conv.fmt] = create_pipeline(conv, preamble, g_depthBindGroupLayoutCompat); ++ } + } + + static constexpr wgpu::SamplerDescriptor nearestSamplerDescriptor{ +@@ -675,6 +767,8 @@ + g_depthBindGroupLayout = {}; + g_depthBindGroupLayoutMS = {}; + g_depthPipelinesMS.clear(); ++ g_depthBindGroupLayoutCompat = {}; ++ g_depthCompareSampler = {}; + g_nearestSampler = {}; + g_linearSampler = {}; + g_depthSnapshotBindGroupLayout = {}; +@@ -689,10 +783,31 @@ + } + wgpu::BindGroup bindGroup; + if (gx::is_depth_format(req.fmt)) { +- // Skip depth copies in compatibility mode + if (!webgpu::g_hasCoreFeatures) { +- return; +- } ++ // 0251: compatibility mode: the same conversion, depth read through comparison samples. ++ const std::array bindGroupEntries{ ++ wgpu::BindGroupEntry{ ++ .binding = 0, ++ .textureView = req.srcView, ++ }, ++ wgpu::BindGroupEntry{ ++ .binding = 1, ++ .buffer = detail::resources().uniformBuffer, ++ .offset = req.uniformRange.offset, ++ .size = req.uniformRange.size, ++ }, ++ wgpu::BindGroupEntry{ ++ .binding = 2, ++ .sampler = g_depthCompareSampler, ++ }, ++ }; ++ const wgpu::BindGroupDescriptor bindGroupDescriptor{ ++ .layout = g_depthBindGroupLayoutCompat, ++ .entryCount = bindGroupEntries.size(), ++ .entries = bindGroupEntries.data(), ++ }; ++ bindGroup = g_device.CreateBindGroup(&bindGroupDescriptor); ++ } else { + const std::array bindGroupEntries{ + wgpu::BindGroupEntry{ + .binding = 0, +@@ -711,6 +826,7 @@ + .entries = bindGroupEntries.data(), + }; + bindGroup = g_device.CreateBindGroup(&bindGroupDescriptor); ++ } + } else { + const auto& sampler = req.sampleFilter == SampleFilter::Linear ? g_linearSampler : g_nearestSampler; + const std::array bindGroupEntries{ diff --git a/src/port/android.cpp b/src/port/android.cpp new file mode 100644 index 00000000..a3d64a31 --- /dev/null +++ b/src/port/android.cpp @@ -0,0 +1,279 @@ +// Android platform helpers (docs/ANDROID.md, port/android.h). +#ifdef __ANDROID__ +#include "port/android.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace port::android { +namespace { + +// LMActivity exports its folders as environment variables before libmain.so starts +// (android.system.Os.setenv in onCreate); SDL's own paths are the fallback. +std::filesystem::path envDir(const char* var, const char* fallback) { + std::filesystem::path p; + if (const char* v = std::getenv(var); v && v[0] == '/') p = v; + else if (fallback) p = fallback; + else p = "."; + std::error_code ec; + std::filesystem::create_directories(p, ec); + return p; +} + +// Calls a static method of the running activity's class (LMActivity). SDL hands out the +// activity as a local reference; using its class avoids FindClass, which only sees system +// classes on threads that were not started from Java. +template +auto withActivity(F&& f) -> decltype(f(static_cast(nullptr), jclass{})) { + auto* env = static_cast(SDL_GetAndroidJNIEnv()); + auto activity = static_cast(SDL_GetAndroidActivity()); + if (!env || !activity) return decltype(f(env, jclass{})){}; + jclass cls = env->GetObjectClass(activity); + auto r = f(env, cls); + if (env->ExceptionCheck()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + } + env->DeleteLocalRef(cls); + env->DeleteLocalRef(activity); + return r; +} + + +} // namespace + +void redirectOutput() { + static bool sDone = false; + if (sDone) return; + sDone = true; + int fds[2]; + if (pipe(fds) != 0) return; + const auto dir = filesDir(); + std::error_code ec; + std::filesystem::rename(dir / "last_run.log", dir / "previous_run.log", ec); + // Removed by sessionEnded() on a normal exit; still there after a crash, so LMActivity copies + // the log to Downloads on the next start. + std::fclose(std::fopen((dir / "session_active").c_str(), "w")); + FILE* file = std::fopen((dir / "last_run.log").c_str(), "w"); + dup2(fds[1], STDOUT_FILENO); + dup2(fds[1], STDERR_FILENO); + close(fds[1]); + std::setvbuf(stdout, nullptr, _IOLBF, 0); + std::setvbuf(stderr, nullptr, _IONBF, 0); + std::thread([rd = fds[0], file] { + std::string line; + char buf[4096]; + for (;;) { + const ssize_t n = read(rd, buf, sizeof(buf)); + if (n <= 0) { + if (n < 0 && errno == EINTR) continue; + break; + } + if (file) { + std::fwrite(buf, 1, size_t(n), file); + std::fflush(file); + } + line.append(buf, size_t(n)); + for (size_t nl; (nl = line.find('\n')) != std::string::npos;) { + __android_log_write(ANDROID_LOG_INFO, "LuigisMansion", line.substr(0, nl).c_str()); + line.erase(0, nl + 1); + } + } + }).detach(); +} + +std::filesystem::path filesDir() { return envDir("LM_ANDROID_FILES", SDL_GetAndroidInternalStoragePath()); } +std::filesystem::path cacheDir() { return envDir("LM_ANDROID_CACHE", SDL_GetAndroidCachePath()); } +std::filesystem::path resourceDir() { return envDir("LM_ANDROID_RES", SDL_GetAndroidInternalStoragePath()); } +std::filesystem::path nativeLibDir() { return envDir("LM_ANDROID_LIBDIR", nullptr); } + +std::string openDiscPath(const std::string& stored, std::string* error) { + if (stored.rfind("content://", 0) != 0) return stored; + // Opening once through LMActivity checks the file is still there and makes the read + // permission persistent. The URI itself is then what gets opened: SDL_IOFromFile opens + // content:// URIs through the ContentResolver and reads that descriptor directly + // (re-opening /proc/self/fd/ fails for files the app can't see by path). + const int fd = withActivity([&](JNIEnv* env, jclass cls) -> int { + jmethodID m = env->GetStaticMethodID(cls, "openContentFd", "(Ljava/lang/String;)I"); + if (!m) return -1; + jstring s = env->NewStringUTF(stored.c_str()); + const int r = env->CallStaticIntMethod(cls, m, s); + env->DeleteLocalRef(s); + return r; + }); + if (fd < 0) { + if (error) *error = "The disc image can no longer be opened (was it moved or deleted?). Choose it again."; + return {}; + } + close(fd); + return stored; +} + +std::string displayName(const std::string& stored) { + if (stored.rfind("content://", 0) != 0) return stored; + std::string name = withActivity([&](JNIEnv* env, jclass cls) -> std::string { + jmethodID m = env->GetStaticMethodID(cls, "contentDisplayName", "(Ljava/lang/String;)Ljava/lang/String;"); + if (!m) return {}; + jstring s = env->NewStringUTF(stored.c_str()); + auto r = static_cast(env->CallStaticObjectMethod(cls, m, s)); + env->DeleteLocalRef(s); + if (!r) return {}; + const char* c = env->GetStringUTFChars(r, nullptr); + std::string out = c ? c : ""; + env->ReleaseStringUTFChars(r, c); + env->DeleteLocalRef(r); + return out; + }); + return name.empty() ? stored : name; +} + +namespace { +struct ThreadTimes { + std::string name; + unsigned long long ticks = 0; +}; + +// utime + stime (clock ticks) and comm of a /proc/.../stat file. +bool readStat(const std::string& path, ThreadTimes& out) { + FILE* f = std::fopen(path.c_str(), "r"); + if (!f) return false; + char buf[1024]; + const size_t n = std::fread(buf, 1, sizeof(buf) - 1, f); + std::fclose(f); + buf[n] = 0; + const char* open = std::strchr(buf, '('); + const char* close = std::strrchr(buf, ')'); + if (!open || !close) return false; + out.name.assign(open + 1, close); + // Fields after ")": state(3) ... utime(14) stime(15). + const char* p = close + 2; + unsigned long long v[13] = {}; + char state = 0; + if (std::sscanf(p, "%c %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu", &state, &v[0], &v[1], &v[2], + &v[3], &v[4], &v[5], &v[6], &v[7], &v[8], &v[9], &v[10], &v[11]) < 13) + return false; + out.ticks = v[10] + v[11]; + return true; +} +} // namespace + +void startPerfLog() { + std::thread([] { + const double hz = double(sysconf(_SC_CLK_TCK)); + std::map last; // tid -> ticks + unsigned long long lastProc = 0; + for (;;) { + std::this_thread::sleep_for(std::chrono::seconds(10)); + ThreadTimes proc; + if (!readStat("/proc/self/stat", proc)) continue; + std::vector> busy; + std::map now; + if (DIR* d = opendir("/proc/self/task")) { + while (dirent* e = readdir(d)) { + if (e->d_name[0] == '.') continue; + ThreadTimes t; + if (!readStat(std::string("/proc/self/task/") + e->d_name + "/stat", t)) continue; + now[e->d_name] = t.ticks; + if (auto it = last.find(e->d_name); it != last.end() && t.ticks > it->second) + busy.emplace_back(double(t.ticks - it->second) / hz / 10.0 * 100.0, t.name); + } + closedir(d); + } + last = std::move(now); + std::sort(busy.begin(), busy.end(), [](auto& a, auto& b) { return a.first > b.first; }); + const int thermal = withActivity([](JNIEnv* env, jclass cls) -> int { + jmethodID m = env->GetStaticMethodID(cls, "thermalStatus", "()I"); + return m ? env->CallStaticIntMethod(cls, m) : -1; + }); + static const char* kThermal[] = {"none", "light", "moderate", "severe", "critical", "emergency", "shutdown"}; + std::string top; + for (size_t i = 0; i < busy.size() && i < 5; i++) { + char b[96]; + std::snprintf(b, sizeof(b), "%s%s %.0f%%", i ? ", " : "", busy[i].second.c_str(), busy[i].first); + top += b; + } + if (lastProc) + std::printf("[perf] cpu %.0f%% (100%% = one core); busiest threads: %s; thermal %s\n", + double(proc.ticks - lastProc) / hz / 10.0 * 100.0, top.c_str(), + thermal >= 0 && thermal <= 6 ? kThermal[thermal] : "unknown"); + std::fflush(stdout); + lastProc = proc.ticks; + } + }).detach(); +} + +void sessionEnded() { + std::fflush(nullptr); + std::error_code ec; + std::filesystem::remove(filesDir() / "session_active", ec); +} + +void shareLog() { + std::fflush(stdout); + withActivity([&](JNIEnv* env, jclass cls) -> int { + if (jmethodID m = env->GetStaticMethodID(cls, "shareLog", "()V")) env->CallStaticVoidMethod(cls, m); + return 0; + }); +} + +void pickTexturePack(bool folder, const std::string& destDir) { + withActivity([&](JNIEnv* env, jclass cls) -> int { + jmethodID m = env->GetStaticMethodID(cls, "pickTexturePack", "(ZLjava/lang/String;)V"); + if (!m) return 0; + jstring s = env->NewStringUTF(destDir.c_str()); + env->CallStaticVoidMethod(cls, m, jboolean(folder), s); + env->DeleteLocalRef(s); + return 0; + }); +} + +ImportStatus texturePackImportStatus() { + ImportStatus st; + const std::string s = withActivity([](JNIEnv* env, jclass cls) -> std::string { + jmethodID m = env->GetStaticMethodID(cls, "texturePackStatus", "()Ljava/lang/String;"); + if (!m) return {}; + auto r = static_cast(env->CallStaticObjectMethod(cls, m)); + if (!r) return {}; + const char* c = env->GetStringUTFChars(r, nullptr); + std::string out = c ? c : ""; + env->ReleaseStringUTFChars(r, c); + env->DeleteLocalRef(r); + return out; + }); + // "||" + const auto a = s.find('|'), b = a == std::string::npos ? a : s.find('|', a + 1); + if (b == std::string::npos) return st; + st.state = ImportState(std::atoi(s.substr(0, a).c_str())); + st.count = std::atoi(s.substr(a + 1, b - a - 1).c_str()); + st.message = s.substr(b + 1); + return st; +} + +void relaunch(bool setup) { + sessionEnded(); + withActivity([&](JNIEnv* env, jclass cls) -> int { + if (jmethodID m = env->GetStaticMethodID(cls, "relaunch", "(Z)V")) + env->CallStaticVoidMethod(cls, m, jboolean(setup)); + return 0; + }); + std::fflush(nullptr); + std::_Exit(0); +} + +} // namespace port::android +#endif diff --git a/src/port/android.h b/src/port/android.h new file mode 100644 index 00000000..613d74ef --- /dev/null +++ b/src/port/android.h @@ -0,0 +1,62 @@ +#pragma once +// Android platform helpers (docs/ANDROID.md). Only built for Android; the Java side is +// packaging/android/java/dev/lmport/LMActivity.java. +#ifdef __ANDROID__ +#include +#include + +namespace port::android { + +// Sends stdout/stderr (all of the runtime's logging) to logcat (tag "LuigisMansion") and to +// last_run.log in filesDir() (the previous run's log is kept as previous_run.log). Android +// discards both streams otherwise. Call first thing in main. +void redirectOutput(); + +// App-private folders (Context.getFilesDir / getCacheDir). +std::filesystem::path filesDir(); +std::filesystem::path cacheDir(); + +// Folder with files shipped in the APK's assets that the runtime reads by path +// (pipelines.bin), copied there by LMActivity on the first start of each app version. +std::filesystem::path resourceDir(); + +// Folder with the bundled compiler (the APK's native library folder: libllvm.so). +std::filesystem::path nativeLibDir(); + +// A path nod can open for a disc image the user picked: the system file picker returns +// content:// URIs; they are opened through the ContentResolver (keeping the permission +// across restarts); the URI is returned and opened with SDL_IOFromFile (which reads it through +// the ContentResolver). Other paths are returned as is. +// Empty (and `error` set) when the URI can no longer be opened (file moved or deleted). +std::string openDiscPath(const std::string& stored, std::string* error = nullptr); + +// A short name for a stored disc path, for the setup screen (content URIs are long). +std::string displayName(const std::string& stored); + +// Every 10 s, logs the process' CPU use, its busiest threads and the device's thermal state +// ("[perf]" lines), to tell a slow phone, a hot one and a stalled game apart in shared logs. +void startPerfLog(); + +// A normal exit: the log need not be saved to Downloads on the next start (redirectOutput). +void sessionEnded(); + +// Opens the system share sheet with last_run.log (to send it to someone). +void shareLog(); + +// Texture packs (src/recomp/texture_pack.cpp): opens the system picker for a .zip (folder=false) +// or a folder (folder=true); LMActivity then copies the texture files (tex1_*.png/.dds) into +// destDir/ on its own thread. Progress through texturePackImportStatus(). +void pickTexturePack(bool folder, const std::string& destDir); +enum class ImportState { Idle = 0, Running = 1, Done = 2, Failed = 3 }; +struct ImportStatus { + ImportState state = ImportState::Idle; + int count = 0; // texture files copied so far + std::string message; // result or error for the player +}; +ImportStatus texturePackImportStatus(); + +// Restarts the app (optionally on the setup screen); does not return. +[[noreturn]] void relaunch(bool setup); + +} // namespace port::android +#endif diff --git a/src/port/crash_handler.cpp b/src/port/crash_handler.cpp index 4e1b06cb..0a0ce262 100644 --- a/src/port/crash_handler.cpp +++ b/src/port/crash_handler.cpp @@ -22,6 +22,10 @@ #include #include #include +#elif defined(__ANDROID__) +// Android: the system's crash reporter (debuggerd) writes a symbolized tombstone and logcat +// backtrace for fatal signals; this file only adds the reason line (docs/ANDROID.md). +#include #else #include #include @@ -82,6 +86,8 @@ void printStackTo(std::FILE* out, const char* reason) { } std::fputc('\n', out); } +#elif defined(__ANDROID__) + std::fflush(stderr); // the system crash report (logcat / tombstone) has the stack #else // backtrace_symbols_fd writes "binary(symbol+off) [addr]" lines without allocating; the // executable's own functions are named only for exported symbols, so the offsets are @@ -140,7 +146,7 @@ LONG WINAPI onException(EXCEPTION_POINTERS* info) { printStack(reason); return EXCEPTION_EXECUTE_HANDLER; } -#else +#elif !defined(__ANDROID__) // Fatal signals (Linux): report the signal, the faulting address, the instruction and the // binary it is in (e.g. the game module .so), then the stack. Runs on an alternate stack on // the main thread so a stack overflow there can still be reported. Afterwards the default @@ -274,6 +280,9 @@ void dumpAllThreads(const char* reason) { std::fprintf(stderr, "=== end of thread stacks ===\n"); std::fflush(stderr); } +#elif defined(__ANDROID__) +// Android: no thread dump of our own (debuggerd's tombstone has every thread's stack). +void dumpAllThreads(const char*) {} #else // Linux (issue #11: a Steam Deck log said nothing about where the game stopped): each thread is // sent a signal whose handler writes its own backtrace ("binary(symbol+off) [addr]" lines, without @@ -474,6 +483,14 @@ void startHangWatchdog() { } void installCrashHandler() { +#ifdef __ANDROID__ + // Leave SIGABRT and fatal signals to debuggerd (it symbolizes the stack); only name the reason. + std::set_terminate([] { + printStack("std::terminate"); + std::abort(); + }); + return; +#endif std::signal(SIGABRT, onAbort); std::set_terminate([] { aurora_pipeline_cache_note_crash(); @@ -486,7 +503,7 @@ void installCrashHandler() { AddVectoredExceptionHandler(1, onVectored); // Route CRT abort() through SIGABRT instead of an immediate fast-fail. _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); -#else +#elif !defined(__ANDROID__) installSignalHandlers(); #endif } diff --git a/src/port/install.cpp b/src/port/install.cpp index 5e40415d..8d99c4f0 100644 --- a/src/port/install.cpp +++ b/src/port/install.cpp @@ -25,6 +25,9 @@ #include #include #endif +#ifdef __ANDROID__ +#include "port/android.h" +#endif namespace port { namespace { @@ -673,20 +676,46 @@ std::string requestDataMove(bool toPortable) { } std::filesystem::path configDir() { +#ifdef __ANDROID__ + return android::filesDir(); // settings, install.ini (docs/ANDROID.md) +#endif const auto& l = dataLocation(); return l.portable ? l.root : sysDir(Kind::Config, true); } std::filesystem::path dataDir() { +#ifdef __ANDROID__ + return android::filesDir(); // game modules, overlays, memory cards +#endif const auto& l = dataLocation(); return l.portable ? l.root : sysDir(Kind::Data, true); } std::filesystem::path cacheDir() { +#ifdef __ANDROID__ + return android::cacheDir(); // GPU pipeline caches (the system may clear them) +#endif const auto& l = dataLocation(); return l.portable ? l.root : sysDir(Kind::Cache, true); } +std::string discOpenPath(const std::string& stored, std::string* error) { +#ifdef __ANDROID__ + return android::openDiscPath(stored, error); +#else + (void)error; + return stored; +#endif +} + +std::string discDisplayName(const std::string& stored) { +#ifdef __ANDROID__ + return android::displayName(stored); +#else + return stored; +#endif +} + std::filesystem::path envPath(const char* name) { #ifdef _WIN32 const std::wstring wname(name, name + std::strlen(name)); @@ -909,6 +938,9 @@ void relaunch(bool setup, const std::filesystem::path& exePath) { } else if (!exePath.empty()) { return; // the updater reports it } +#elif defined(__ANDROID__) + (void)exePath; + android::relaunch(setup); // a new activity instance; this process exits #else std::vector argv; for (auto& a : sArgs) argv.push_back(a.data()); diff --git a/src/port/install.h b/src/port/install.h index 033d14d2..ab01bc4a 100644 --- a/src/port/install.h +++ b/src/port/install.h @@ -121,6 +121,12 @@ std::string installPathProblem(); // "" when the program's folder is short enou // A message for the player when long paths are off and the data folder is too deep for the // parts that use plain paths (Aurora's memory cards, caches, imgui.ini); "" when all is well. std::string dataPathProblem(); +// The path to open a stored disc image path with (nod / aurora_dvd_open). The same path on +// desktops; on Android the file picker gives content:// URIs, opened here through the +// ContentResolver (port/android.h). Empty, with `error` set, if it can't be opened. +std::string discOpenPath(const std::string& stored, std::string* error = nullptr); +// How to show a stored disc path to the player (Android: the file's name instead of the URI). +std::string discDisplayName(const std::string& stored); void loadInstall(); void saveInstall(); diff --git a/src/port/settings.cpp b/src/port/settings.cpp index e2aed74d..36122900 100644 --- a/src/port/settings.cpp +++ b/src/port/settings.cpp @@ -99,6 +99,7 @@ std::vector fields() { flag("rendering", "shadow_render_resolution", r.shadowRenderResolution), flag("rendering", "shadow_widescreen", r.shadowWidescreen), flag("rendering", "shadow_any_distance", r.shadowAnyDistance), + flag("rendering", "custom_textures", r.customTextures), // Enhanced lighting > Ghost lights flag("ghost_lights", "enabled", sSettings.ghostLights.enabled), num("ghost_lights", "intensity", sSettings.ghostLights.intensity), @@ -212,6 +213,9 @@ std::vector fields() { flag("audio", "voice_filters", a.voiceFilters), flag("audio", "sinc_resampler", a.sincResampler), flag("enhancements", "show_fps", e.showFps), + num("enhancements", "touch_controls", e.touchControls), + num("enhancements", "touch_scale", e.touchScale), + num("enhancements", "touch_opacity", e.touchOpacity), flag("enhancements", "pause_on_focus_loss", e.pauseOnFocusLoss), flag("enhancements", "hidden_mansion_pal", e.hiddenMansionPal), num("enhancements", "pal_language", e.palLanguage), @@ -300,6 +304,7 @@ std::vector fields() { } void writeSettings(std::ostream& out); +void logSettings(const char* when); template void clampTo(T& v, T lo, T hi) { @@ -458,6 +463,31 @@ void loadSettings() { } std::ifstream in(settingsFile()); if (!in) return; + struct LogAfter { + ~LogAfter() { +#ifdef __ANDROID__ + // Once per install: settings saved by earlier Android builds had the PC's accuracy + // defaults; switch the costly ones to the phone defaults (kPcDefault) one time. + const auto marker = std::filesystem::path(settingsPath()).parent_path() / "phone_defaults_v1"; + std::error_code ec; + if (!std::filesystem::exists(marker, ec)) { + auto& r = sSettings.rendering; + const RenderingSettings d{}; + r.integerTev = d.integerTev; + r.efbColorDepth = d.efbColorDepth; + r.efbBlend6 = d.efbBlend6; + r.earlyZAlphaDepth = d.earlyZAlphaDepth; + r.efbCopyToRam = d.efbCopyToRam; + r.gpuKeepWarm = d.gpuKeepWarm; + r.shadowRenderResolution = d.shadowRenderResolution; + r.shadowAnyDistance = d.shadowAnyDistance; + std::ofstream(marker) << "1\n"; + saveSettings(); + } +#endif + logSettings("loaded"); + } + } logAfter; auto table = fields(); std::string line, section; while (std::getline(in, line)) { @@ -496,7 +526,30 @@ void resetSettingsToDefaults() { saveSettings(); } +namespace { +// Shared logs (Android "Share log") should say which settings a run used: the video and +// rendering sections and the enhanced-lighting master switch, as written to settings.ini. +void logSettings(const char* when) { + std::ostringstream all; + writeSettings(all); + std::istringstream in(all.str()); + std::string line, section, out; + while (std::getline(in, line)) { + if (!line.empty() && line[0] == '[') { + section = line; + continue; + } + if (section == "[video]" || section == "[rendering]" || + (section == "[enhanced_lighting]" && line.rfind("enabled=", 0) == 0)) + out += " " + section.substr(1, section.size() - 2) + "." + line; + } + std::printf("[settings] %s:%s\n", when, out.c_str()); + std::fflush(stdout); +} +} // namespace + void saveSettings() { + logSettings("saved"); // Written to a temporary file and renamed over settings.ini, so a crash or power loss while // saving never leaves a truncated file (which would reset every setting on the next launch). const std::filesystem::path path = settingsFile(), tmp = std::filesystem::path(path) += ".tmp"; diff --git a/src/port/settings.h b/src/port/settings.h index 6c2d9fbd..33933a19 100644 --- a/src/port/settings.h +++ b/src/port/settings.h @@ -24,7 +24,11 @@ struct VideoSettings { bool unlimitedFps = false; // interpolated, as fast as the PC can (no frame-rate cap or schedule) bool matchDisplay = false; AspectMode aspect = AspectMode::Auto; +#ifdef __ANDROID__ + int resolutionScale = 2; // phones: 2 x 480p by default (a phone's full resolution costs battery and heat) +#else int resolutionScale = 0; // internal render resolution: 0 = match window, N = N x 480p (aspect-widened) +#endif float fovScale = 1.0f; // multiplies the game's vertical field of view bool fullscreen = false; bool vsync = true; // applied at next launch @@ -91,6 +95,9 @@ struct AudioSettings { struct EnhancementSettings { bool showFps = false; + int touchControls = 1; // Android on-screen pad: 0 off, 1 auto (hidden with a controller), 2 always + float touchScale = 1.0f; // its size, 0.6..1.6 + float touchOpacity = 0.5f; // 0.1..1 bool pauseOnFocusLoss = true; bool hiddenMansionPal = true; // default Hidden Mansion rules for saves that have not chosen in E. Gadd's lab int palLanguage = 1; // PAL game only: 1 English, 2 German, 3 French, 4 Spanish, 5 Italian (next launch) @@ -143,17 +150,24 @@ struct GameplaySettings { // Hardware-accuracy rendering features (F1 > Visuals > Rendering). Every costly accuracy // feature gets a flag here, ON by default (best quality); weaker PCs can turn them off. +// Costly accuracy features are on by default on PC and off on phones (docs/ANDROID.md: on a +// phone GPU they cost tens of milliseconds per frame); F1 > Visuals > Rendering turns them on. +#ifdef __ANDROID__ +constexpr bool kPcDefault = false; +#else +constexpr bool kPcDefault = true; +#endif struct RenderingSettings { // Integer TEV: the color combiner computes with the hardware's 8-bit inputs, signed 11-bit // registers and per-stage rounding instead of floats (Aurora GX_AURORA_ACCURACY_INT_TEV). - bool integerTev = true; + bool integerTev = kPcDefault; // EFB color depth: pixels are stored the way the game's RGBA6 framebuffer stores them, // 6 bits per channel with the ordered dither the game enables (GX_AURORA_ACCURACY_EFB_DEPTH). - bool efbColorDepth = true; + bool efbColorDepth = kPcDefault; // 6-bit blending: with efbColorDepth, blended draws (the flashlight beam, glows, HUD edges) // are stored like the console's RGBA6 framebuffer stores them, the blend result dithered and // truncated to 6 bits (GX_AURORA_ACCURACY_EFB_BLEND, Aurora 0176). - bool efbBlend6 = true; + bool efbBlend6 = kPcDefault; // Smooth color banding (enhancement, OFF = vanilla-accurate): with efbColorDepth, the 6-bit // framebuffer and the game's RGB565 screen copy store the local average of the console's // 6/5-bit result instead of its steps, so gradients keep the same brightness and tint without @@ -164,7 +178,7 @@ struct RenderingSettings { // Early Z writes depth for alpha-tested pixels: draws that compare Z before texturing // (GXSetZCompLoc(GX_TRUE)) update Z even where the alpha test then rejects the pixel, as the // hardware does (GX_AURORA_ACCURACY_EARLY_Z, Aurora 0170/0179: depth-only pass + colour pass). - bool earlyZAlphaDepth = true; + bool earlyZAlphaDepth = kPcDefault; // Display copy filter: the vertical filter (and gamma) GXCopyDisp applies on the way to the TV. bool displayCopyFilter = true; // Texture copy filter: the same vertical filter applied to the game's GXCopyTex copies (the @@ -174,7 +188,7 @@ struct RenderingSettings { // GXCopyTex results also exist as GX-format bytes in main memory, so textures that read a // copy with another format/size (the shadow depth map) and CPU reads see what the // console sees (docs/RENDERING.md). Off: copies stay GPU-only textures. - bool efbCopyToRam = true; + bool efbCopyToRam = kPcDefault; // Vertex data each draw indexes is copied when the game issues the draw (as the console's GPU // reads it then), not when Aurora's FIFO thread gets to it; fixes Luigi's rare mouth/hose // flicker (CPU/GPU timing race; docs/RENDERING.md "Vertex snapshots"). Interpolated frame @@ -182,17 +196,19 @@ struct RenderingSettings { bool vtxSnapshot = true; // Keep the GPU clocks up when a frame is much lighter than play (menus over a still picture): // filler GPU work so the first frames after it are not 5-7x slower (pacing.cpp, Aurora 0215). - bool gpuKeepWarm = true; + bool gpuKeepWarm = kPcDefault; // Shadows (docs/RENDERING.md, "Shadows"). The game's shadow map (light's-view depth, copied // as Z16 and compared in the TEV) at the internal render resolution instead of 640x480. - bool shadowRenderResolution = true; + bool shadowRenderResolution = kPcDefault; // Widescreen: the shadow light's frustum is widened by the same factor as the view, so // shadows reach the extra side areas (the game only covers what a 4:3 screen shows). bool shadowWidescreen = true; // The game's shadow light only covers a depth band around Luigi (e.g. 619..2322 units from the // room light), so shadows vanish on things farther away. On: the band is extended to what the // player's view shows (enhancement). Off: the original range. - bool shadowAnyDistance = true; + bool shadowAnyDistance = kPcDefault; + // Custom texture packs (Dolphin tex1_ names) from /textures (src/recomp/texture_pack.cpp). + bool customTextures = true; }; // ---- Enhanced lighting > Ghost lights (src/recomp/ghost_lights.cpp; docs/RENDERING.md) ---- diff --git a/src/port/update.cpp b/src/port/update.cpp index 4b9418a7..42214a40 100644 --- a/src/port/update.cpp +++ b/src/port/update.cpp @@ -1514,6 +1514,10 @@ State state() { } void startupCheck() { +#ifdef __ANDROID__ + ulog("Android: no updater (new versions come as a new APK; docs/ANDROID.md)"); + return; +#endif if (!port::settings().updates.checkAtStartup) { ulog("startup check off (F1 > Game)"); return; diff --git a/src/recomp/controls.cpp b/src/recomp/controls.cpp index 765dce5d..17d2717e 100644 --- a/src/recomp/controls.cpp +++ b/src/recomp/controls.cpp @@ -17,6 +17,7 @@ #include "recomp/controls.h" #include "recomp/dsu.h" #include "recomp/ui_scale.h" +#include "recomp/touch.h" #include "port/settings.h" @@ -1469,6 +1470,10 @@ bool drawTab() { local |= dsu::drawTab(); ImGui::EndTabItem(); } + if (touch::supported() && ImGui::BeginTabItem("Touch", nullptr, subTabFlags("Touch"))) { + local |= touch::drawSettings(); // a plain setting (settings.ini [enhancements]) + ImGui::EndTabItem(); + } ImGui::EndTabBar(); } sEnvSubTab = nullptr; diff --git a/src/recomp/frame.cpp b/src/recomp/frame.cpp index 053203fa..9057940c 100644 --- a/src/recomp/frame.cpp +++ b/src/recomp/frame.cpp @@ -1,3 +1,6 @@ +#ifdef __ANDROID__ +#include +#endif #include "recomp/frame.h" #include "port/recovery.h" @@ -77,6 +80,9 @@ bool interpolationWanted() { void start(Entry boot) { sched::startHostThread([boot] { cpu::setCurrent(cpu::Role::Guest); +#ifdef __ANDROID__ + pthread_setname_np(pthread_self(), "guest-main"); +#endif { std::unique_lock lk(sM); sCv.wait(lk, [] { return sTurn == Turn::Guest || sStopping; }); diff --git a/src/recomp/hle_os.cpp b/src/recomp/hle_os.cpp index 2765c918..fc600829 100644 --- a/src/recomp/hle_os.cpp +++ b/src/recomp/hle_os.cpp @@ -114,11 +114,17 @@ std::unordered_map sAlarmGen; // alarm -> generation of its pending e using AlarmClock = std::chrono::steady_clock; std::unordered_map sAlarmFired; // alarm -> when it last expired -void armAlarm(u32 alarm, u64 ticks, u32 handler, u64 period) { +void armAlarm(u32 alarm, s64 ticks, u32 handler, u64 period) { + // OSTime is signed: an alarm set for a time already past (the European frame pacer after a + // long frame, e.g. a room load) fires at once on the console. As an unsigned delay it was + // ~2^64 ticks, a double the duration_cast below cannot hold: x86 converts it to INT64_MIN + // (fires at once, by luck), ARM saturates to INT64_MAX, and the game stayed at ~7 fps from + // then on (Android, docs/ANDROID.md). + if (ticks < 0) ticks = 0; // Fast-forward (skip.h) speeds alarms up like it speeds up retraces. const double speed = std::max(1.0, skip::retraceSpeed()); const auto delay = std::chrono::duration_cast( - std::chrono::duration(double(ticks) / kTimerClock / speed)); + std::chrono::duration(std::min(double(ticks) / kTimerClock / speed, 86400.0))); // no overflow const auto now = AlarmClock::now(); auto when = now + delay; u32 gen; @@ -144,7 +150,7 @@ void armAlarm(u32 alarm, u64 ticks, u32 handler, u64 period) { if (sAlarmGen[alarm] != gen) return; // cancelled or re-armed sAlarmFired[alarm] = when; } - if (period) armAlarm(alarm, period, handler, period); + if (period) armAlarm(alarm, s64(period), handler, period); guestCall(c, handler, alarm, 0); }); } @@ -156,11 +162,12 @@ HLE(OSCreateAlarm) { ++sAlarmGen[c.r[3]]; sAlarmFired.erase(c.r[3]); } -HLE(OSSetAlarm) { armAlarm(c.r[3], u64(c.r[5]) << 32 | c.r[6], c.r[7], 0); } +HLE(OSSetAlarm) { armAlarm(c.r[3], s64(u64(c.r[5]) << 32 | c.r[6]), c.r[7], 0); } HLE(OSSetPeriodicAlarm) { - // (alarm, u64 start r5:r6, u64 period r7:r8, handler r9); start is absolute time. - const u64 now = timeBase(), start = u64(c.r[5]) << 32 | c.r[6], period = u64(c.r[7]) << 32 | c.r[8]; - armAlarm(c.r[3], start > now ? start - now : 0, c.r[9], period ? period : 1); + // (alarm, s64 start r5:r6, s64 period r7:r8, handler r9); start is absolute time. + const s64 now = s64(timeBase()), start = s64(u64(c.r[5]) << 32 | c.r[6]); + const s64 period = s64(u64(c.r[7]) << 32 | c.r[8]); + armAlarm(c.r[3], start > now ? start - now : 0, c.r[9], period > 0 ? u64(period) : 1); } HLE(OSCancelAlarm) { std::lock_guard lk(sAlarmM); diff --git a/src/recomp/hle_pad.cpp b/src/recomp/hle_pad.cpp index c551fd42..dca1aff7 100644 --- a/src/recomp/hle_pad.cpp +++ b/src/recomp/hle_pad.cpp @@ -9,6 +9,7 @@ #include "recomp/coop_test.h" #include "recomp/menu.h" #include "recomp/skip.h" +#include "recomp/touch.h" #include "recomp/unused2.h" #include @@ -175,6 +176,7 @@ HLE(PADRead) { controls::beforeRead(); // port devices (hot-plug) and bindings from F1 > Controls const u32 motor = PADRead(st); controls::afterRead(st); // dead zones, sensitivity; input test values + touch::apply(st); // Android on-screen pad on port 1 (touch.h) logPad(st); if (menu::isOpen()) { // the overlay menu owns input while open for (auto& s : st) { diff --git a/src/recomp/main.cpp b/src/recomp/main.cpp index 8c3ad430..db672d85 100644 --- a/src/recomp/main.cpp +++ b/src/recomp/main.cpp @@ -17,6 +17,7 @@ #include "port/recovery.h" #include "port/settings.h" #include "port/update.h" +#include "recomp/texture_pack.h" #include "recomp/audio.h" #include "recomp/cpu_qos.h" #include "recomp/mem_report.h" @@ -30,10 +31,16 @@ #include "recomp/precache.h" #include "recomp/runtime.h" #include "recomp/sched.h" +#include "recomp/skip.h" +#include "recomp/touch.h" #include "recomp/widescreen.h" #ifndef LM_STATIC_MODULE #include "setup/setup.h" #endif +#ifdef __ANDROID__ +#include "port/android.h" +#include +#endif #include #include @@ -49,6 +56,7 @@ u32 copyDispCount(); // hle_gx.cpp #ifdef __APPLE__ void hideWindowMacos(SDL_Window* w); // macos_window.cpp #endif +u32 viRetraceCount(); // hle_vi.cpp #ifdef LM_STATIC_MODULE extern const GameModule kGameModule; // generated func_table.cpp, linked in (lmrecomp) #endif @@ -188,6 +196,10 @@ void hangDetail(char* out, size_t size, bool stallBegins) { int main(int argc, char* argv[]) { using namespace recomp; +#ifdef __ANDROID__ + port::android::redirectOutput(); // logcat + last_run.log (docs/ANDROID.md) + port::android::startPerfLog(); // "[perf]" CPU / thermal lines +#endif // Windows: no console window for players; output to a terminal, a redirect or last_run.log. port::recovery::setupConsole(argc, argv); port::installCrashHandler(); @@ -245,7 +257,24 @@ int main(int argc, char* argv[]) { std::printf("[video] Gamescope: VSync on (FIFO presentation; the VSync setting is ignored under Gamescope)\n"); } } - // LM_BACKEND=d3d12|d3d11|vulkan (testing): graphics backend instead of Aurora's choice. +#ifdef __ANDROID__ + // Qualcomm's Adreno Vulkan driver miscompiles the 16-bit masking in Aurora's vertex fetch + // (Adreno 740 here: the title backdrop and file-select pictures sampled only their first row; + // Aurora's author hit the same on Adreno 7xx/8xx, Dusklight #750). The OpenGL ES backend draws + // them correctly, so Adreno devices default to it (docs/ANDROID.md "Adreno: OpenGL ES"). + { + char egl[PROP_VALUE_MAX] = {}; + char vk[PROP_VALUE_MAX] = {}; + __system_property_get("ro.hardware.egl", egl); + __system_property_get("ro.hardware.vulkan", vk); + if (std::strstr(egl, "adreno") || std::strstr(vk, "adreno")) { + config.desiredBackend = BACKEND_OPENGLES; + std::printf("[video] Adreno GPU: OpenGL ES backend (its Vulkan driver breaks 16-bit vertex data; " + "LM_BACKEND=vulkan overrides)\n"); + } + } +#endif + // LM_BACKEND=d3d12|d3d11|vulkan|opengl|gles (testing): graphics backend instead of Aurora's choice. if (const char* b = std::getenv("LM_BACKEND")) { const std::string s = b; config.desiredBackend = s == "d3d12" ? BACKEND_D3D12 @@ -283,6 +312,9 @@ int main(int argc, char* argv[]) { if (!sCacheOverride.empty()) config.cachePath = sCacheOverride.c_str(); const port::Options& opts = port::options(); config.startFullscreen = opts.fullscreen || port::settings().video.fullscreen; +#ifdef __ANDROID__ + config.startFullscreen = true; // immersive: no status or navigation bar over the game +#endif config.windowWidth = opts.windowWidth; config.windowHeight = opts.windowHeight; if (!config.windowWidth && opts.aspectRatio > 0.0f) { // fixed aspect: open a window of that shape @@ -296,6 +328,10 @@ int main(int argc, char* argv[]) { const bool topmost = std::getenv("LM_TOPMOST") != nullptr; if (topmost) SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); cpu::init(); // thread policy + Aurora thread hooks (issue #18), before Aurora starts its threads +#ifdef __ANDROID__ + // The Back button opens/closes the F1 menu (menu.cpp) instead of closing the app. + SDL_SetHint(SDL_HINT_ANDROID_TRAP_BACK_BUTTON, "1"); +#endif aurora_initialize(argc, argv, &config); mem::trackInit(); // LM_MEM_TRACK (test aid, docs/RENDERING.md "Memory use over time") if (topmost) @@ -316,6 +352,7 @@ int main(int argc, char* argv[]) { // LM_MAXIMIZE=1 (testing): open the window maximized, as players often run it. if (std::getenv("LM_MAXIMIZE")) if (SDL_Window* w = aurora_get_window()) SDL_MaximizeWindow(w); + texture_pack::init(); // custom textures from /textures (before any game texture is used) precache::init(); ws::init(); port::setPhase("loading the game"); @@ -345,14 +382,25 @@ int main(int argc, char* argv[]) { if (!setup::run(so, launch)) { port::recovery::onExit(); aurora_shutdown(); +#ifdef __ANDROID__ + port::android::sessionEnded(); +#endif std::_Exit(0); } const std::string disc = launch.disc; const char* wantId = port::gameId(launch.version); #endif port::setPhase("loading the game"); - if (disc.empty() || !aurora_dvd_open(disc.c_str())) { + const std::string discOpen = port::discOpenPath(disc); // Android: content:// URI -> descriptor + if (discOpen.empty() || !aurora_dvd_open(discOpen.c_str())) { std::fprintf(stderr, "Could not open a Luigi's Mansion disc image. Pass --disc .\n"); +#ifdef __ANDROID__ // no console to read: say it on screen + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Luigi's Mansion", + "The disc image could not be opened (was it moved or deleted?). " + "Start the app again and choose it on the setup screen.", + nullptr); + port::relaunch(true); +#endif aurora_shutdown(); return 1; } @@ -383,6 +431,10 @@ int main(int argc, char* argv[]) { #ifndef LM_STATIC_MODULE if (std::string err; !loadGameModule(launch.module, err)) { std::fprintf(stderr, "%s\n", err.c_str()); +#ifdef __ANDROID__ // no console to read: say it on screen + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Luigi's Mansion", + ("The game module could not be loaded:\n" + err).c_str(), nullptr); +#endif aurora_shutdown(); return 1; } @@ -390,6 +442,25 @@ int main(int argc, char* argv[]) { std::printf("Opened %s (%s)\n", disc.c_str(), discId); frame::start(&boot); +#ifdef __ANDROID__ + // Diagnostics for shared logs (docs/ANDROID.md): when the game itself runs below 10 frames + // a second for 10 s (not paused), dump where every guest thread waits, a few times per run. + std::thread([] { + u32 last = skip::guestFrames(); + int dumps = 0; + for (;;) { + std::this_thread::sleep_for(std::chrono::seconds(10)); + const u32 now = skip::guestFrames(); + const u32 frames = now - last; + last = now; + if (frames > 0 && frames < 100 && dumps < 4) { + dumps++; + log("[slow] %u game frames in 10 s, retrace %u: guest threads", frames, viRetraceCount()); + sched::dumpThreads(); + } + } + }).detach(); +#endif if (std::getenv("LM_WATCHDOG")) { std::thread([] { for (;;) { @@ -438,7 +509,10 @@ int main(int argc, char* argv[]) { if (quitAfter > 0 && std::chrono::duration(std::chrono::steady_clock::now() - runStart).count() > quitAfter) break; for (const AuroraEvent* ev = aurora_update(); ev && ev->type != AURORA_NONE; ++ev) { - if (ev->type == AURORA_SDL_EVENT) menu::handleEvent(ev->sdl); + if (ev->type == AURORA_SDL_EVENT && !touch::handleEvent(ev->sdl)) { + touch::feedImGui(ev->sdl); // taps on the F1 menu (Android; touch.h) + menu::handleEvent(ev->sdl); + } if (ev->type == AURORA_EXIT) exiting = true; else if (ev->type == AURORA_PAUSED) { paused = true; @@ -502,6 +576,7 @@ int main(int argc, char* argv[]) { lastPresented = SteadyClock::now(); presentStallReported = false; menu::draw(); // applies settings changes (they may change what is being compiled) + touch::draw(); precache::drawHold(); precache::frame(); aurora_end_frame(); @@ -530,6 +605,7 @@ int main(int argc, char* argv[]) { interp::hostMark(2); port::setPhase("game loop: F1 menu / overlays"); menu::draw(); + touch::draw(); // Android on-screen pad (touch.h) precache::frame(); port::setPhase("game loop: present hold"); pacing::beforeEnd(); @@ -550,5 +626,8 @@ int main(int argc, char* argv[]) { audio::outShutdown(); aurora_shutdown(); port::recovery::onExit(); +#ifdef __ANDROID__ + port::android::sessionEnded(); +#endif std::_Exit(0); } diff --git a/src/recomp/menu.cpp b/src/recomp/menu.cpp index fd375882..913aded3 100644 --- a/src/recomp/menu.cpp +++ b/src/recomp/menu.cpp @@ -1,6 +1,10 @@ // In-game overlay menu (F1 toggles, Esc closes): Visuals / Sound / Controls / Enhancements / Game. // Drawn with Aurora's Dear ImGui on the host thread between the guest's present // and aurora_end_frame. While it is open the game receives neutral pad input. +#ifdef __ANDROID__ +#include "port/android.h" +#endif +#include "recomp/texture_pack.h" #include "recomp/menu.h" #include "recomp/gx_bridge.h" @@ -349,12 +353,33 @@ bool tab(const char* name) { return ImGui::BeginTabItem(name, nullptr, select ? ImGuiTabItemFlags_SetSelected : 0); } -void applyResolution() { VISetFrameBufferScale(float(port::settings().video.resolutionScale)); } +#ifdef __ANDROID__ +// Phones: at most 3x (1440 lines, above any phone screen's height). "Match window" (0) is +// replaced by 2x: higher internal resolutions cost a phone GPU tens of milliseconds per frame. +constexpr int kMaxResolutionScale = 3; +#else +constexpr int kMaxResolutionScale = 8; +#endif + +void applyResolution() { + int& rs = port::settings().video.resolutionScale; +#ifdef __ANDROID__ + if (rs <= 0) rs = 2; +#endif + rs = std::min(rs, kMaxResolutionScale); + VISetFrameBufferScale(float(rs)); + std::printf("[settings] render resolution %dx\n", rs); +} void applyWindowSettings() { const auto& v = port::settings().video; applyResolution(); +#ifdef __ANDROID__ + // Phones: always fullscreen (immersive: no status or navigation bar over the game). + if (SDL_Window* w = aurora_get_window()) SDL_SetWindowFullscreen(w, true); +#else if (SDL_Window* w = aurora_get_window()) SDL_SetWindowFullscreen(w, v.fullscreen); +#endif // Automated runs (scripted --input, or LM_BACKGROUND=1) never pause when another window // takes focus, so several test instances can run side by side. static const bool sBackground = !port::options().inputScript.empty() || std::getenv("LM_BACKGROUND") != nullptr; @@ -1517,7 +1542,12 @@ void visualsTab() { const int w = int(float(h) * std::max(aspect, 4.0f / 3.0f) + 0.5f); std::snprintf(label, sizeof(label), "%dx (%d x %d)", rs, w, h); } - if (recomp::menu::SliderInt("Render resolution", &rs, 0, 8, label, ImGuiSliderFlags_AlwaysClamp)) { +#ifdef __ANDROID__ + const int minScale = 1; // no "Match window" on phones (applyResolution) +#else + const int minScale = 0; +#endif + if (recomp::menu::SliderInt("Render resolution", &rs, minScale, kMaxResolutionScale, label, ImGuiSliderFlags_AlwaysClamp)) { sDirty = true; applyResolution(); } @@ -1585,6 +1615,8 @@ void visualsTab() { ImGui::SeparatorText("CRT filter"); sDirty |= recomp::crt::drawMenu(); + + sDirty |= recomp::texture_pack::drawMenu(); } // Volume slider shown in percent (the setting is 0..1). @@ -1869,6 +1901,10 @@ void gameplayTab() { gameplaySection(); } // Debug features left in the game, warps and viewers. void debugTab() { +#ifdef __ANDROID__ + if (ImGui::Button("Share log")) port::android::shareLog(); + ImGui::SetItemTooltip("Sends this session's log (last_run.log) through Android's share menu, e.g. for a bug report."); +#endif recomp::dev::debugSection(); recomp::unused2::debugSection(); } @@ -1950,6 +1986,14 @@ void openTreesForCheck() { } bool isOpen() { return sOpen || recomp::dev::capturesInput(); } + +void toggle() { + sOpen = !sOpen; + if (!sOpen && sDirty) { + port::saveSettings(); + sDirty = false; + } +} bool quitRequested() { return sQuit; } void shutdown() { @@ -1967,6 +2011,7 @@ void handleEvent(const SDL_Event& ev) { if (ev.type != SDL_EVENT_KEY_DOWN || ev.key.repeat) return; if (ev.key.key == SDLK_F1) sOpen = !sOpen; else if (ev.key.key == SDLK_ESCAPE && sOpen) sOpen = false; + else if (ev.key.key == SDLK_AC_BACK) sOpen = !sOpen; // Android Back button (SDL_HINT_ANDROID_TRAP_BACK_BUTTON) if (!sOpen && sDirty) { port::saveSettings(); sDirty = false; diff --git a/src/recomp/menu.h b/src/recomp/menu.h index caa1511c..0aab31af 100644 --- a/src/recomp/menu.h +++ b/src/recomp/menu.h @@ -7,6 +7,7 @@ void init(); // loads settings, applies window opti void handleEvent(const SDL_Event& ev); // host event loop void draw(); // host thread, inside an Aurora frame bool isOpen(); // game input is suppressed while open +void toggle(); // opens or closes it (F1; Android: the touch MENU button / Back) bool quitRequested(); // "Quit game" chosen in the menu void shutdown(); // saves changes not yet written (window closed with the menu open) // LM_MENU_ID_CHECK sweep: tree nodes and collapsible sections in the menu call this right diff --git a/src/recomp/precache.cpp b/src/recomp/precache.cpp index 3ddc3009..60ef1be3 100644 --- a/src/recomp/precache.cpp +++ b/src/recomp/precache.cpp @@ -24,6 +24,9 @@ #define NOMINMAX #include #endif +#ifdef __ANDROID__ +#include "port/android.h" +#endif namespace recomp::precache { namespace { @@ -33,7 +36,9 @@ using Clock = std::chrono::steady_clock; bool sLog = false; std::filesystem::path exeDir() { -#ifdef _WIN32 +#ifdef __ANDROID__ + return port::android::resourceDir(); // APK assets copied out by LMActivity (docs/ANDROID.md) +#elif defined(_WIN32) wchar_t buf[MAX_PATH * 4]; const DWORD n = GetModuleFileNameW(nullptr, buf, DWORD(std::size(buf))); return std::filesystem::path(std::wstring(buf, n)).parent_path(); diff --git a/src/recomp/sched.cpp b/src/recomp/sched.cpp index cb69fbcc..205fe5d5 100644 --- a/src/recomp/sched.cpp +++ b/src/recomp/sched.cpp @@ -1,3 +1,6 @@ +#ifdef __ANDROID__ +#include +#endif #include "recomp/sched.h" #include "recomp/cpu_qos.h" @@ -176,6 +179,9 @@ void finishThread(GuestThread* t, u32 val) { void threadMain(GuestThread* t) { tSelf = t; cpu::setCurrent(cpu::Role::Guest); +#ifdef __ANDROID__ + pthread_setname_np(pthread_self(), "guest"); // named in the [perf] log lines +#endif u32 val = 0; try { { diff --git a/src/recomp/texture_pack.cpp b/src/recomp/texture_pack.cpp new file mode 100644 index 00000000..5a3e0fcd --- /dev/null +++ b/src/recomp/texture_pack.cpp @@ -0,0 +1,185 @@ +// Custom texture packs (texture_pack.h, docs/TEXTURE_PACKS.md). +// +// Aurora already replaces textures by the Dolphin naming convention: the name of each file is the +// texture's size, an xxHash64 of its GX data (and of the palette range it uses) and its GX +// format, so a pack made for Dolphin's "Load Custom Textures" works unchanged. This file only +// points Aurora at /textures, keeps the registrations so the pack can be switched off or +// reloaded, and on Android imports a pack from a .zip or a folder the player picks (the app +// cannot read shared storage by path; LMActivity copies the texture files into its own folder). +#include "recomp/texture_pack.h" + +#include "port/install.h" +#include "port/settings.h" +#include "recomp/menu.h" +#ifdef __ANDROID__ +#include "port/android.h" +#endif + +#include +#include +#include +#include + +#include +#include +#include + +namespace recomp::texture_pack { +namespace { + +std::mutex sM; +aurora::texture::ReplacementGroup sGroup; +bool sLoaded = false; + +// Number of texture files below the folder (shown before they are loaded). +size_t countFiles(const std::filesystem::path& dir) { + size_t n = 0; + std::error_code ec; + for (auto it = std::filesystem::recursive_directory_iterator( + dir, std::filesystem::directory_options::skip_permission_denied, ec); + !ec && it != std::filesystem::recursive_directory_iterator(); it.increment(ec)) { + std::error_code e; + if (!it->is_regular_file(e)) continue; + const auto name = it->path().filename().string(); + if (name.rfind("tex1_", 0) == 0) n++; + } + return n; +} + +void unloadLocked() { + if (!sLoaded) return; + aurora::texture::unregister_replacements(sGroup); + sGroup = {}; + sLoaded = false; +} + +void loadLocked() { + unloadLocked(); + if (!port::settings().rendering.customTextures) return; + const auto dir = folder(); + sGroup = aurora::texture::load_replacement_directory(dir); + sLoaded = true; + std::printf("[textures] %zu replacement textures from %s\n", sGroup.registrations.size(), + port::displayPath(dir).c_str()); + std::fflush(stdout); +} + +#ifdef __ANDROID__ +// Import state, polled from the menu (LMActivity copies on its own thread). +bool sImportWatching = false; +#endif + +} // namespace + +std::filesystem::path folder() { return port::dataDir() / "textures"; } + +void init() { + std::error_code ec; + std::filesystem::create_directories(folder(), ec); + std::lock_guard lk(sM); + loadLocked(); +} + +void reload() { + std::lock_guard lk(sM); + loadLocked(); +} + +size_t loadedCount() { + std::lock_guard lk(sM); + return sLoaded ? sGroup.registrations.size() : 0; +} + +bool drawMenu() { + bool changed = false; + auto& r = port::settings().rendering; + ImGui::SeparatorText("Texture pack"); + if (recomp::menu::Checkbox("Use custom textures", &r.customTextures)) { + changed = true; + reload(); + } + ImGui::SetItemTooltip( + "Replacement textures made for Dolphin's \"Load Custom Textures\" (files named\n" + "tex1___.png or .dds, e.g. a 4K texture pack) are used instead of the\n" + "game's own. Put the pack's texture folder (for Luigi's Mansion usually \"GLM\") into the\n" + "textures folder below; any folder layout works. Packs made from the US version mostly\n" + "match the European one too."); + static size_t sFiles = size_t(-1); + if (sFiles == size_t(-1)) sFiles = countFiles(folder()); + const size_t loaded = loadedCount(); + if (!r.customTextures) + ImGui::TextDisabled("Off (%zu texture files in the folder)", sFiles); + else if (sFiles == 0) + ImGui::TextDisabled("No texture pack installed"); + else + ImGui::Text("%zu replacement textures loaded", loaded); +#ifdef __ANDROID__ + // Phones: the pack is copied into the app (it cannot read a folder in shared storage). + if (recomp::menu::Button("Import .zip")) { + port::android::pickTexturePack(false, folder().string()); + sImportWatching = true; + } + ImGui::SetItemTooltip("Choose the texture pack's .zip. Its texture files are copied into the app (the rest of\n" + "the archive is skipped). Use the pack's 1080p version on a phone: the 4K one needs\n" + "several GB of storage and much more memory. A .7z or .rar must be unpacked first\n" + "(e.g. with a file manager app); then use Import folder."); + ImGui::SameLine(); + if (recomp::menu::Button("Import folder")) { + port::android::pickTexturePack(true, folder().string()); + sImportWatching = true; + } + ImGui::SetItemTooltip("Choose an unpacked texture pack folder (e.g. \"GLM\"). Its texture files, also in\n" + "subfolders, are copied into the app."); + if (sImportWatching) { + const auto st = port::android::texturePackImportStatus(); + if (st.state == port::android::ImportState::Running) { + ImGui::Text("Importing... %d files", st.count); + } else if (st.state == port::android::ImportState::Done) { + sImportWatching = false; + sFiles = countFiles(folder()); + reload(); + std::printf("[textures] imported %d files\n", st.count); + } else if (st.state == port::android::ImportState::Failed) { + sImportWatching = false; + sFiles = countFiles(folder()); + std::printf("[textures] import failed: %s\n", st.message.c_str()); + } + } + if (const auto st = port::android::texturePackImportStatus(); + !sImportWatching && !st.message.empty() && st.state != port::android::ImportState::Running) + ImGui::TextWrapped("%s", st.message.c_str()); + if (sFiles > 0) { + if (recomp::menu::Button("Remove texture packs")) { + { + std::lock_guard lk(sM); + unloadLocked(); + } + std::error_code ec; + std::filesystem::remove_all(folder(), ec); + std::filesystem::create_directories(folder(), ec); + sFiles = 0; + std::printf("[textures] removed the imported texture packs\n"); + } + ImGui::SetItemTooltip("Deletes the imported texture files from the app."); + } +#else + ImGui::TextDisabled("Folder: %s", port::displayPath(folder()).c_str()); + if (recomp::menu::Button("Open textures folder")) { + std::error_code ec; + std::filesystem::create_directories(folder(), ec); + const auto url = "file:///" + port::displayPath(folder()); + SDL_OpenURL(url.c_str()); + } + ImGui::SameLine(); +#endif +#ifndef __ANDROID__ + if (recomp::menu::Button("Reload textures")) { + sFiles = countFiles(folder()); + reload(); + } + ImGui::SetItemTooltip("Picks up texture files added, changed or removed since the game started."); +#endif + return changed; +} + +} // namespace recomp::texture_pack diff --git a/src/recomp/texture_pack.h b/src/recomp/texture_pack.h new file mode 100644 index 00000000..38fb9e6f --- /dev/null +++ b/src/recomp/texture_pack.h @@ -0,0 +1,23 @@ +#pragma once +// Custom texture packs (docs/TEXTURE_PACKS.md): Dolphin-style replacement textures +// (tex1_x[_m]_[_]_.png/.dds) loaded from /textures through +// Aurora's texture replacement (aurora/texture.hpp). F1 > Visuals > Texture pack. +#include +#include + +namespace recomp::texture_pack { + +// Folder the packs live in (any layout below it: the files are found recursively). +std::filesystem::path folder(); + +// Loads the folder's textures if the setting is on (after aurora_initialize). +void init(); +// Applies the setting / picks up changed files: unloads, then loads again if enabled. +void reload(); +// Textures registered now. +size_t loadedCount(); + +// The F1 menu section (Visuals tab). Returns true when a setting changed. +bool drawMenu(); + +} // namespace recomp::texture_pack diff --git a/src/recomp/touch.cpp b/src/recomp/touch.cpp new file mode 100644 index 00000000..23776741 --- /dev/null +++ b/src/recomp/touch.cpp @@ -0,0 +1,378 @@ +// On-screen touch controls (touch.h, docs/ANDROID.md). +#include "recomp/touch.h" + +#include "port/settings.h" +#include "recomp/menu.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace recomp::touch { +namespace { + +#ifdef __ANDROID__ +constexpr bool kSupported = true; +#else +constexpr bool kSupported = false; // desktops: keyboard/controller (could be enabled for touchscreens) +#endif + +enum class Ctl { None, Stick, CStick, A, B, X, Y, L, R, Z, Start, DUp, DDown, DLeft, DRight, Menu }; + +struct Circle { + Ctl ctl; + float x, y, r; + const char* label; +}; + +struct Layout { + float w = 0, h = 0, u = 0; + float stickX = 0, stickY = 0, stickR = 0; // main stick resting place + float cX = 0, cY = 0, cR = 0; // C-stick + float dX = 0, dY = 0, dS = 0; // D-pad centre, arm size + Circle buttons[9]; + int nButtons = 0; +}; + +struct Finger { + Ctl ctl = Ctl::None; + float ox = 0, oy = 0; // stick origin (where the finger landed, or the C-stick centre) + float x = 0, y = 0; // current position +}; + +std::mutex sM; +std::map sFingers; +Layout sLayout; +bool sMenuButtonDown = false; + +bool enabledSetting() { return port::settings().enhancements.touchControls != 0; } + +// Shown: "Always", or "Auto" while no gamepad is connected (a Bluetooth/USB controller takes over). +bool visible() { + if (!kSupported || !enabledSetting()) return false; + if (port::settings().enhancements.touchControls == 2) return true; + return !SDL_HasGamepad(); +} + +Layout makeLayout(float w, float h) { + Layout l; + l.w = w; + l.h = h; + const float scale = std::clamp(port::settings().enhancements.touchScale, 0.6f, 1.6f); + const float u = std::min(w, h) / 10.0f * scale; + l.u = u; + l.stickX = 2.4f * u; + l.stickY = h - 2.6f * u; + l.stickR = 1.5f * u; + l.cX = w - 6.4f * u; + l.cY = h - 3.0f * u; + l.cR = 0.95f * u; + l.dX = 1.7f * u; + l.dY = h - 6.1f * u; + l.dS = 0.62f * u; + auto add = [&](Ctl c, float x, float y, float r, const char* label) { l.buttons[l.nButtons++] = {c, x, y, r, label}; }; + // GameCube face-button arrangement: big A, B low-left of it, X to the right, Y above. + add(Ctl::A, w - 2.7f * u, h - 2.4f * u, 1.0f * u, "A"); + add(Ctl::B, w - 4.5f * u, h - 1.3f * u, 0.68f * u, "B"); + add(Ctl::X, w - 1.0f * u, h - 3.9f * u, 0.66f * u, "X"); + add(Ctl::Y, w - 3.1f * u, h - 4.7f * u, 0.62f * u, "Y"); + add(Ctl::L, 1.5f * u, 1.1f * u, 0.85f * u, "L"); + add(Ctl::R, w - 1.5f * u, 1.1f * u, 0.85f * u, "R"); + add(Ctl::Z, w - 1.5f * u, 2.85f * u, 0.6f * u, "Z"); + add(Ctl::Start, w * 0.5f + 1.0f * u, 0.8f * u, 0.5f * u, "START"); + add(Ctl::Menu, w * 0.5f - 1.0f * u, 0.8f * u, 0.5f * u, "MENU"); + return l; +} + +Ctl dpadAt(const Layout& l, float x, float y) { + const float dx = x - l.dX, dy = y - l.dY; + const float reach = l.dS * 2.2f; + if (std::fabs(dx) > reach || std::fabs(dy) > reach) return Ctl::None; + if (std::fabs(dx) < l.dS * 0.35f && std::fabs(dy) < l.dS * 0.35f) return Ctl::None; // dead centre + if (std::fabs(dx) > std::fabs(dy)) return dx < 0 ? Ctl::DLeft : Ctl::DRight; + return dy < 0 ? Ctl::DUp : Ctl::DDown; +} + +Ctl hit(const Layout& l, float x, float y, bool menuOpen) { + for (int i = 0; i < l.nButtons; i++) { + const Circle& c = l.buttons[i]; + if (menuOpen && c.ctl != Ctl::Menu) continue; + const float dx = x - c.x, dy = y - c.y; + if (dx * dx + dy * dy <= (c.r * 1.2f) * (c.r * 1.2f)) return c.ctl; + } + if (menuOpen) return Ctl::None; + { + const float dx = x - l.cX, dy = y - l.cY; + if (dx * dx + dy * dy <= (l.cR * 1.4f) * (l.cR * 1.4f)) return Ctl::CStick; + } + if (Ctl d = dpadAt(l, x, y); d != Ctl::None) return d; + if (x < l.w * 0.42f && y > l.h * 0.3f) return Ctl::Stick; // floating stick: anywhere lower-left + return Ctl::None; +} + +// Unit vector-ish stick value from a finger: -1..1 each axis, magnitude clamped to 1. +void stickValue(const Finger& f, float radius, float& vx, float& vy) { + vx = (f.x - f.ox) / radius; + vy = (f.y - f.oy) / radius; + const float m = std::sqrt(vx * vx + vy * vy); + if (m > 1.0f) { + vx /= m; + vy /= m; + } +} + +s8 axis(float v) { return s8(std::lround(std::clamp(v, -1.0f, 1.0f) * 105.0f)); } // GameCube stick range ~±100 + +} // namespace + +bool supported() { return kSupported; } + +namespace { +SDL_FingerID sUiFinger = 0; // the finger driving ImGui's mouse (0: none) +bool sUiFingerDown = false; +} // namespace + +bool feedImGui(const SDL_Event& ev) { + if (!kSupported || !ImGui::GetCurrentContext()) return false; + if (ev.type != SDL_EVENT_FINGER_DOWN && ev.type != SDL_EVENT_FINGER_MOTION && ev.type != SDL_EVENT_FINGER_UP && + ev.type != SDL_EVENT_FINGER_CANCELED) + return false; + ImGuiIO& io = ImGui::GetIO(); + float w = io.DisplaySize.x, h = io.DisplaySize.y; + if (w <= 0 || h <= 0) { + int iw = 0, ih = 0; + if (SDL_Window* win = SDL_GetWindowFromID(ev.tfinger.windowID)) SDL_GetWindowSize(win, &iw, &ih); + w = float(iw); + h = float(ih); + } + const float x = ev.tfinger.x * w, y = ev.tfinger.y * h; + if (ev.type == SDL_EVENT_FINGER_DOWN) { + if (sUiFingerDown) return false; // a second finger: ignored by the menus + sUiFinger = ev.tfinger.fingerID; + sUiFingerDown = true; + io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen); + io.AddMousePosEvent(x, y); + io.AddMouseButtonEvent(ImGuiMouseButton_Left, true); + return true; + } + if (!sUiFingerDown || ev.tfinger.fingerID != sUiFinger) return false; + io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen); + io.AddMousePosEvent(x, y); + if (ev.type == SDL_EVENT_FINGER_MOTION) { + // Dragging scrolls lists like a phone does: ImGui's touch source drags windows' scroll + // only with the wheel, so turn vertical movement into wheel steps. + const float dy = ev.tfinger.dy * h; + if (dy != 0.0f) io.AddMouseWheelEvent(0.0f, dy / (ImGui::GetFontSize() * 3.0f)); + return true; + } + io.AddMouseButtonEvent(ImGuiMouseButton_Left, false); + // Lift the pointer off the screen, so nothing stays "hovered" under the last tap. + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); + sUiFingerDown = false; + return true; +} + +bool handleEvent(const SDL_Event& ev) { + if (!kSupported) return false; + if (ev.type != SDL_EVENT_FINGER_DOWN && ev.type != SDL_EVENT_FINGER_MOTION && ev.type != SDL_EVENT_FINGER_UP && + ev.type != SDL_EVENT_FINGER_CANCELED) + return false; + std::lock_guard lk(sM); + if (!visible() && ev.type == SDL_EVENT_FINGER_DOWN) return false; + Layout& l = sLayout; + if (l.w <= 0) return false; // not drawn yet + const float x = ev.tfinger.x * l.w, y = ev.tfinger.y * l.h; + const SDL_FingerID id = ev.tfinger.fingerID; + if (ev.type == SDL_EVENT_FINGER_DOWN) { + const Ctl c = hit(l, x, y, menu::isOpen()); + if (c == Ctl::None) return false; + Finger f; + f.ctl = c; + f.x = x; + f.y = y; + if (c == Ctl::CStick) { + f.ox = l.cX; + f.oy = l.cY; + } else { + f.ox = x; + f.oy = y; + } + if (c == Ctl::Menu) sMenuButtonDown = true; + sFingers[id] = f; + return true; + } + auto it = sFingers.find(id); + if (it == sFingers.end()) return false; + Finger& f = it->second; + f.x = x; + f.y = y; + // The D-pad follows a sliding finger between its arms. + if (f.ctl == Ctl::DUp || f.ctl == Ctl::DDown || f.ctl == Ctl::DLeft || f.ctl == Ctl::DRight) + if (Ctl d = dpadAt(l, x, y); d != Ctl::None) f.ctl = d; + if (ev.type == SDL_EVENT_FINGER_UP || ev.type == SDL_EVENT_FINGER_CANCELED) { + if (f.ctl == Ctl::Menu) { + sMenuButtonDown = false; + // Released on the button: open or close the F1 menu (Android has no F1 key). + const float dx = x - l.buttons[8].x, dy = y - l.buttons[8].y; + if (ev.type == SDL_EVENT_FINGER_UP && dx * dx + dy * dy <= l.buttons[8].r * l.buttons[8].r * 2.0f) + menu::toggle(); + } + sFingers.erase(it); + } + return true; +} + +void apply(PADStatus* status) { + if (!kSupported) return; + std::lock_guard lk(sM); + if (!visible()) return; + PADStatus& s = status[0]; + // The touch pad is a controller in port 1 even while idle (no "connect a controller"). + if (s.err != PAD_ERR_NONE) { + s = PADStatus{}; + s.err = PAD_ERR_NONE; + } + const Layout& l = sLayout; + for (const auto& [id, f] : sFingers) { + float vx, vy; + switch (f.ctl) { + case Ctl::Stick: + stickValue(f, l.stickR, vx, vy); + if (std::abs(axis(vx)) + std::abs(axis(-vy)) > std::abs(s.stickX) + std::abs(s.stickY)) { + s.stickX = axis(vx); + s.stickY = axis(-vy); + } + break; + case Ctl::CStick: + stickValue(f, l.cR, vx, vy); + s.substickX = axis(vx); + s.substickY = axis(-vy); + break; + case Ctl::A: s.button |= PAD_BUTTON_A; s.analogA = 255; break; + case Ctl::B: s.button |= PAD_BUTTON_B; s.analogB = 255; break; + case Ctl::X: s.button |= PAD_BUTTON_X; break; + case Ctl::Y: s.button |= PAD_BUTTON_Y; break; + case Ctl::L: s.button |= PAD_TRIGGER_L; s.triggerLeft = 255; break; + case Ctl::R: s.button |= PAD_TRIGGER_R; s.triggerRight = 255; break; + case Ctl::Z: s.button |= PAD_TRIGGER_Z; break; + case Ctl::Start: s.button |= PAD_BUTTON_START; break; + case Ctl::DUp: s.button |= PAD_BUTTON_UP; break; + case Ctl::DDown: s.button |= PAD_BUTTON_DOWN; break; + case Ctl::DLeft: s.button |= PAD_BUTTON_LEFT; break; + case Ctl::DRight: s.button |= PAD_BUTTON_RIGHT; break; + default: break; + } + } +} + +void draw() { + if (!kSupported) return; + std::lock_guard lk(sM); + const ImVec2 size = ImGui::GetIO().DisplaySize; + sLayout = makeLayout(size.x, size.y); + if (!visible()) { + sFingers.clear(); + return; + } + const Layout& l = sLayout; + const bool menuOpen = menu::isOpen(); + const float alpha = std::clamp(port::settings().enhancements.touchOpacity, 0.1f, 1.0f); + auto col = [&](int r, int g, int b, float a) { return IM_COL32(r, g, b, int(255.0f * a * alpha)); }; + auto pressed = [&](Ctl c) { + for (const auto& [id, f] : sFingers) + if (f.ctl == c) return true; + return false; + }; + ImDrawList* dl = ImGui::GetForegroundDrawList(); + ImFont* font = ImGui::GetFont(); + auto label = [&](const char* text, float cx, float cy, float px) { + const ImVec2 ts = font->CalcTextSizeA(px, FLT_MAX, 0.0f, text); + dl->AddText(font, px, ImVec2(cx - ts.x * 0.5f, cy - ts.y * 0.5f), col(255, 255, 255, 0.95f), text); + }; + for (int i = 0; i < l.nButtons; i++) { + const Circle& c = l.buttons[i]; + if (menuOpen && c.ctl != Ctl::Menu) continue; + const bool down = pressed(c.ctl); + ImU32 fill = col(30, 30, 40, down ? 0.75f : 0.4f); + if (c.ctl == Ctl::A) fill = col(40, 150, 120, down ? 0.85f : 0.5f); // GameCube green A + if (c.ctl == Ctl::B) fill = col(200, 50, 50, down ? 0.85f : 0.5f); // red B + dl->AddCircleFilled(ImVec2(c.x, c.y), c.r, fill, 40); + dl->AddCircle(ImVec2(c.x, c.y), c.r, col(255, 255, 255, 0.6f), 40, std::max(1.5f, l.u * 0.04f)); + const float px = c.r * (std::strlen(c.label) > 2 ? 0.5f : 0.95f); + label(c.label, c.x, c.y, px); + } + if (menuOpen) return; + // Main stick: base where the finger landed (or its resting place), knob under the finger. + { + float bx = l.stickX, by = l.stickY, kx = bx, ky = by; + for (const auto& [id, f] : sFingers) + if (f.ctl == Ctl::Stick) { + float vx, vy; + stickValue(f, l.stickR, vx, vy); + bx = f.ox; + by = f.oy; + kx = bx + vx * l.stickR; + ky = by + vy * l.stickR; + } + dl->AddCircleFilled(ImVec2(bx, by), l.stickR, col(30, 30, 40, 0.3f), 48); + dl->AddCircle(ImVec2(bx, by), l.stickR, col(255, 255, 255, 0.5f), 48, std::max(1.5f, l.u * 0.04f)); + dl->AddCircleFilled(ImVec2(kx, ky), l.stickR * 0.45f, col(200, 200, 210, 0.6f), 36); + } + // C-stick (yellow on the GameCube pad). + { + float kx = l.cX, ky = l.cY; + for (const auto& [id, f] : sFingers) + if (f.ctl == Ctl::CStick) { + float vx, vy; + stickValue(f, l.cR, vx, vy); + kx = l.cX + vx * l.cR; + ky = l.cY + vy * l.cR; + } + dl->AddCircleFilled(ImVec2(l.cX, l.cY), l.cR, col(30, 30, 40, 0.3f), 40); + dl->AddCircle(ImVec2(l.cX, l.cY), l.cR, col(240, 200, 40, 0.7f), 40, std::max(1.5f, l.u * 0.04f)); + dl->AddCircleFilled(ImVec2(kx, ky), l.cR * 0.5f, col(240, 200, 40, 0.6f), 32); + label("C", kx, ky, l.cR * 0.6f); + } + // D-pad: four arms. + { + const struct { + Ctl c; + float dx, dy; + } arms[] = {{Ctl::DUp, 0, -1}, {Ctl::DDown, 0, 1}, {Ctl::DLeft, -1, 0}, {Ctl::DRight, 1, 0}}; + const float s = l.dS; + for (const auto& a : arms) { + const float cx = l.dX + a.dx * s * 1.05f, cy = l.dY + a.dy * s * 1.05f; + dl->AddRectFilled(ImVec2(cx - s * 0.5f, cy - s * 0.5f), ImVec2(cx + s * 0.5f, cy + s * 0.5f), + col(30, 30, 40, pressed(a.c) ? 0.8f : 0.4f), s * 0.15f); + dl->AddRect(ImVec2(cx - s * 0.5f, cy - s * 0.5f), ImVec2(cx + s * 0.5f, cy + s * 0.5f), + col(255, 255, 255, 0.5f), s * 0.15f, 0, std::max(1.0f, l.u * 0.03f)); + } + } +} + +bool drawSettings() { + if (!kSupported) return false; + auto& e = port::settings().enhancements; + bool changed = false; + ImGui::SeparatorText("Touch controls"); + const char* modes[] = {"Off", "Auto (hidden while a controller is connected)", "Always"}; + int mode = std::clamp(e.touchControls, 0, 2); + if (ImGui::Combo("Show##touch", &mode, modes, 3)) { + e.touchControls = mode; + changed = true; + } + changed |= ImGui::SliderFloat("Size##touch", &e.touchScale, 0.6f, 1.6f, "%.2f"); + changed |= ImGui::SliderFloat("Opacity##touch", &e.touchOpacity, 0.1f, 1.0f, "%.2f"); + ImGui::TextDisabled("Left side: move (the stick appears where you touch). Yellow circle: C-stick.\n" + "MENU opens this menu; the Back button does too."); + return changed; +} + +} // namespace recomp::touch diff --git a/src/recomp/touch.h b/src/recomp/touch.h new file mode 100644 index 00000000..fd0bcb30 --- /dev/null +++ b/src/recomp/touch.h @@ -0,0 +1,25 @@ +#pragma once +// On-screen touch controls (Android; docs/ANDROID.md): a GameCube pad drawn over the game +// (floating main stick, C-stick, A/B/X/Y, L/R/Z, START, D-pad) and a menu button, since a +// phone has no F1 key. Their input is merged into controller port 1 in PADRead. Shown while +// no physical controller is in use ("Auto"), always, or never (F1 > Controls > Touch). +union SDL_Event; +struct PADStatus; + +namespace recomp::touch { + +// Host event loop: finger events. True when the event was used by the touch controls. +bool handleEvent(const SDL_Event& ev); +// Host thread, inside an Aurora frame, after the menu: draws the controls. +void draw(); +// PADRead (guest thread): adds the touch pad to port 1. +void apply(PADStatus* status); +// Taps and drags for the menus (setup screen, F1 menu): Aurora turns off SDL's touch-to-mouse +// events, so one finger is fed to ImGui as a touchscreen mouse here. True when used. +bool feedImGui(const SDL_Event& ev); +// F1 > Controls > Touch. +bool drawSettings(); +// Built for a touch platform (Android) at all. +bool supported(); + +} // namespace recomp::touch diff --git a/src/setup/disc.cpp b/src/setup/disc.cpp index 320ed95b..d2f5b90b 100644 --- a/src/setup/disc.cpp +++ b/src/setup/disc.cpp @@ -1,9 +1,17 @@ #include "setup/disc.h" #include "port/dol.h" +#include "port/install.h" #include +#include +#include +#ifdef __ANDROID__ +#include +#include +#endif + namespace setup { std::string hex(const std::uint8_t* data, size_t n) { @@ -22,7 +30,55 @@ Disc::~Disc() { } bool Disc::open(const std::string& utf8Path, std::string& error) { - if (nod_disc_open(utf8Path.c_str(), nullptr, &disc_) != NOD_RESULT_OK) { + { + // Archives are not disc images: say so instead of nod's "unknown format". + std::string name = port::discDisplayName(utf8Path); + for (auto& ch : name) ch = char(std::tolower(static_cast(ch))); + for (const char* ext : {".7z", ".zip", ".rar", ".gz", ".xz"}) + if (name.size() > std::strlen(ext) && name.compare(name.size() - std::strlen(ext), std::string::npos, ext) == 0) { + error = "This is a compressed archive, not a disc image. Extract it first (to an .iso, .ciso, .rvz, ...) " + "and choose the extracted file."; + return false; + } + } + const std::string openPath = port::discOpenPath(utf8Path, &error); // Android: content:// URIs + if (openPath.empty()) return false; +#ifdef __ANDROID__ + // Picked files are content:// URIs, which only SDL_IOFromFile can open (through the + // ContentResolver), so nod reads through an SDL stream, like Aurora's DVD code does. + { + SDL_IOStream* io = SDL_IOFromFile(openPath.c_str(), "rb"); + if (!io) { + error = std::string("Could not read the disc image: ") + SDL_GetError(); + return false; + } + const NodDiscStream stream{ + .user_data = io, + .read_at = [](void* ud, uint64_t off, void* out, size_t len) -> int64_t { + auto* s = static_cast(ud); + if (SDL_SeekIO(s, Sint64(off), SDL_IO_SEEK_SET) < 0) return -1; + size_t done = 0; + while (done < len) { + const size_t n = SDL_ReadIO(s, static_cast(out) + done, len - done); + if (n == 0) break; + done += n; + } + return int64_t(done); + }, + .stream_len = [](void* ud) -> int64_t { return SDL_GetIOSize(static_cast(ud)); }, + .close = [](void* ud) { SDL_CloseIO(static_cast(ud)); }, + }; + const NodDiscOptions options{.preloader_threads = 1}; + if (nod_disc_open_stream(&stream, &options, &disc_) != NOD_RESULT_OK) { + const char* msg = nod_error_message(); + error = std::string("Could not read the disc image") + (msg ? std::string(": ") + msg : "."); + return false; + } + } + if (false) { +#else + if (nod_disc_open(openPath.c_str(), nullptr, &disc_) != NOD_RESULT_OK) { +#endif const char* msg = nod_error_message(); error = std::string("Could not read the disc image") + (msg ? std::string(": ") + msg : "."); return false; diff --git a/src/setup/module_builder.cpp b/src/setup/module_builder.cpp index 92275743..5cf97855 100644 --- a/src/setup/module_builder.cpp +++ b/src/setup/module_builder.cpp @@ -6,8 +6,12 @@ #include "recomp/ctx.h" #include "recompiler/recompiler.h" #include "setup/embedded.h" +#ifdef __ANDROID__ +#include "port/android.h" +#endif #include +#include #include #include #include @@ -78,6 +82,23 @@ constexpr const char* kModuleFile = "module.dylib"; constexpr const char* kObjExt = ".o"; constexpr const char* kExeSuffix = ""; constexpr const char* kLinkerName = "ld64.lld"; +#elif defined(__ANDROID__) +// Android (docs/ANDROID.md): the Linux flags for arm64. -mno-outline-atomics: the module has +// no libgcc/compiler-rt to provide the __aarch64_* atomic helpers. -fsigned-char: like the +// runtime (CMakeLists.txt) and x86, where the port was written. -ffp-contract=off: no fused +// multiply-adds the PowerPC would not do (as on macOS, docs/MACOS.md "Floating point on arm64"). +const std::vector kCompileFlags = { + "--target=aarch64-linux-android28", "-std=c++20", "-O2", "-fPIC", "-fvisibility=hidden", "-ffreestanding", + "-nostdinc", "-fno-exceptions", "-fno-rtti", "-fno-threadsafe-statics", "-fno-math-errno", + "-fno-stack-protector", "-ffp-contract=off", "-funwind-tables", "-mno-outline-atomics", "-fsigned-char", + "-Wno-unused-label", "-Wno-unused-variable"}; +const std::vector kLinkFlags = {"-shared", "-nostdlib", "--eh-frame-hdr", "-Bsymbolic", + "-z", "defs", "-z", "noexecstack", "-z", "now", "-O1", + "--hash-style=both", "-soname", "lm_game_module.so"}; +constexpr const char* kModuleFile = "module.so"; +constexpr const char* kObjExt = ".o"; +constexpr const char* kExeSuffix = ""; +constexpr const char* kLinkerName = "ld.lld"; #else // Linux: a position-independent shared object. Everything is hidden and bound locally // (-fvisibility=hidden, -Bsymbolic) except lm_module_init, so the module's g_mem, memcpy, ... @@ -101,6 +122,13 @@ constexpr const char* kLinkerName = "ld.lld"; // itself handles plain paths past MAX_PATH). Our own file calls go through port::longPath, so a // deep %APPDATA% works without Windows' long path policy (docs/SETUP.md "Long paths"). using port::longPath; +// Leading arguments for the tools: on Android one multi-call LLVM binary (libllvm.so, the +// clang and lld "llvm-driver" build) is both, selected by its first argument. +std::vector sClangPrefix, sLldPrefix; +#ifdef __ANDROID__ +std::mutex sSerialM; // held by each compile once memory ran out +std::atomic sLowMemory{false}; // the system killed a compile during this build +#endif bool writeText(const std::filesystem::path& p, std::string_view text) { std::ofstream o(longPath(p), std::ios::binary); @@ -270,6 +298,26 @@ bool moduleUpToDate(const Disc& disc) { } bool findToolchain(std::filesystem::path& clang, std::filesystem::path& lld, std::string& error) { +#ifdef __ANDROID__ + // The APK carries the compiler as lib/arm64-v8a/libllvm.so, which the installer unpacks + // into the app's native library folder: the one place an app may run programs from + // (docs/ANDROID.md). LM_LLVM_DIR (testing) may name another folder with it. + std::vector androidDirs; + if (const char* env = std::getenv("LM_LLVM_DIR")) androidDirs.emplace_back(env); + androidDirs.push_back(port::android::nativeLibDir()); + for (const auto& d : androidDirs) { + std::error_code ec; + const auto drv = d / "libllvm.so"; + if (std::filesystem::exists(drv, ec)) { + clang = lld = drv; + sClangPrefix = {"clang"}; + sLldPrefix = {"ld.lld"}; + return true; + } + } + error = "The bundled compiler (libllvm.so) is missing from the app. Reinstall the app (docs/ANDROID.md)."; + return false; +#endif const char* exe = kExeSuffix; std::vector dirs{exeDir() / "llvm" / "bin"}; if (const char* env = std::getenv("LM_LLVM_DIR")) dirs.emplace_back(env); @@ -398,7 +446,19 @@ bool buildModule(const Disc& disc, const Progress& progress, std::string& error) std::error_code e; return std::filesystem::file_size(longPath(a), e) > std::filesystem::file_size(longPath(b), e); }); - const unsigned jobs = std::max(1u, std::min(unsigned(sources.size()), std::thread::hardware_concurrency())); + unsigned maxJobs = std::thread::hardware_concurrency(); +#ifdef __ANDROID__ + // Phones: one compile of a large generated file can take over a gigabyte, and the system + // kills the app when memory runs out, so allow one job per 2.5 GB of RAM (the system and other + // apps keep a good part of it; docs/ANDROID.md). + { + const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGESIZE); + const double gb = pages > 0 && page > 0 ? double(pages) * double(page) / (1024.0 * 1024.0 * 1024.0) : 4.0; + maxJobs = std::min(maxJobs, std::max(1u, unsigned(gb / 2.5))); + } +#endif + if (const char* j = std::getenv("LM_COMPILE_JOBS"); j && std::atoi(j) > 0) maxJobs = unsigned(std::atoi(j)); + const unsigned jobs = std::max(1u, std::min(unsigned(sources.size()), maxJobs)); std::mutex m; size_t next = 0, done = 0; std::string failure; @@ -416,13 +476,33 @@ bool buildModule(const Disc& disc, const Progress& progress, std::string& error) obj += kObjExt; auto log = work / "obj" / src.stem(); log += ".log"; - std::vector args(kCompileFlags.begin(), kCompileFlags.end()); + std::vector args(sClangPrefix); + args.insert(args.end(), kCompileFlags.begin(), kCompileFlags.end()); args.push_back("-I" + utf8(work / "include")); args.push_back("-c"); args.push_back(utf8(src)); args.push_back("-o"); args.push_back(utf8(obj)); +#ifdef __ANDROID__ + // After the system killed a compile (128 + signal, most likely for memory), the rest + // run one at a time, and the killed one again. + int rc; + if (sLowMemory) { + std::lock_guard serial(sSerialM); + rc = run(clang, args, log); + } else { + rc = run(clang, args, log); + } + if (rc > 128) { + sLowMemory = true; + std::printf("[setup] a compile was killed (exit %d): continuing one file at a time\n", rc); + std::fflush(stdout); + std::lock_guard serial(sSerialM); + rc = run(clang, args, log); + } +#else const int rc = run(clang, args, log); +#endif std::lock_guard lk(m); if (rc != 0 && failure.empty()) failure = "Compiling " + src.filename().string() + " failed (exit " + std::to_string(rc) + "):\n" + @@ -447,7 +527,8 @@ bool buildModule(const Disc& disc, const Progress& progress, std::string& error) // 3. Link. report("Linking the game module", 0.96f); const auto tmpDll = work / kModuleFile; - std::vector args(kLinkFlags.begin(), kLinkFlags.end()); + std::vector args(sLldPrefix); + args.insert(args.end(), kLinkFlags.begin(), kLinkFlags.end()); #ifdef _WIN32 args.push_back("/out:" + utf8(tmpDll)); args.push_back("/implib:" + utf8(work / "module.lib")); @@ -470,6 +551,13 @@ bool buildModule(const Disc& disc, const Progress& progress, std::string& error) error = "Could not install the game module: " + ec.message(); return false; } +#ifdef __ANDROID__ + // Code an app loads at run time must not be writable (Android 14+ checks this). + std::filesystem::permissions(dir / kModuleFile, + std::filesystem::perms::owner_read | std::filesystem::perms::owner_exec | + std::filesystem::perms::group_read | std::filesystem::perms::others_read, + ec); +#endif writeText(dir / "module.key", moduleKey(disc)); writeText(dir / "recompiler.log", out.summary + "\n"); // Generated code is derived from the user's game; keep it only while building. diff --git a/src/setup/setup.cpp b/src/setup/setup.cpp index b3de64a8..f36da128 100644 --- a/src/setup/setup.cpp +++ b/src/setup/setup.cpp @@ -5,6 +5,7 @@ #include "port/dol.h" #include "recomp/precache.h" #include "recomp/ui_scale.h" +#include "recomp/touch.h" #include "setup/disc.h" #include "setup/hm_overlay.h" #include "setup/module_builder.h" @@ -237,6 +238,7 @@ bool run(const Options& opts, LaunchInfo& launch) { if (ev->type == AURORA_EXIT) return false; if (ev->type == AURORA_PAUSED) port::setPhase(nullptr); // waits for the window: not a hang if (ev->type == AURORA_UNPAUSED) port::setPhase("setup"); + if (ev->type == AURORA_SDL_EVENT) recomp::touch::feedImGui(ev->sdl); // Android taps (touch.h) } { std::lock_guard lk(sPickM); @@ -277,8 +279,14 @@ bool run(const Options& opts, LaunchInfo& launch) { ImGui::Text("Luigi's Mansion Recompiled"); ImGui::Separator(); if (screen == Screen::Pick) { +#ifdef __ANDROID__ + ImGui::TextWrapped("This port runs your own copy of Luigi's Mansion. Choose your disc image (ISO or RVZ). " + "The game is translated and compiled on this device once; on a phone that takes " + "several minutes. Keep the app open and the device plugged in."); +#else ImGui::TextWrapped("This port runs your own copy of Luigi's Mansion. Choose your disc image (ISO or RVZ). " "The game is translated and compiled for this PC once; that takes a minute or two."); +#endif // Portable mode (docs/SETUP.md): where everything goes, or why it was not possible. if (const auto& loc = port::dataLocation(); loc.portable) { const auto s = loc.root.u8string(); @@ -296,11 +304,11 @@ bool run(const Options& opts, LaunchInfo& launch) { ImGui::Text("%s", labels[i]); ImGui::SameLine(); if (*notes[i]) ImGui::TextDisabled("%s", notes[i]); - ImGui::TextWrapped("%s", slots[i].path.empty() ? "(none)" : slots[i].path.c_str()); + ImGui::TextWrapped("%s", slots[i].path.empty() ? "(none)" : port::discDisplayName(slots[i].path).c_str()); if (ImGui::Button("Browse...")) browse(i, slots[i].path); -#ifndef _WIN32 +#if !defined(_WIN32) && !defined(__ANDROID__) // Linux: the file dialog needs xdg-desktop-portal (or zenity/kdialog); a typed or - // pasted path always works (docs/LINUX.md). + // pasted path always works (docs/LINUX.md). (Android always has the system picker.) { static char typed[2][1024]; ImGui::SameLine(); diff --git a/tools/android/build.sh b/tools/android/build.sh new file mode 100755 index 00000000..dcf183ea --- /dev/null +++ b/tools/android/build.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Builds the Android program (libmain.so) for arm64-v8a. docs/ANDROID.md. +# +# ANDROID_NDK= tools/android/build.sh [extra cmake args...] +# +# Needs: CMake 3.25+, Ninja, a host C++ compiler (for lmembed), and a nod package for +# android-aarch64 (tools/android/build_nod.sh makes one; pass its path in LM_NOD_PACKAGE). +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../.." && pwd)" +: "${ANDROID_NDK:?set ANDROID_NDK to an Android NDK (r29 or newer)}" +build="$root/build/android-arm64" +host="$root/build/android-host" + +# lmembed runs at build time, so it is built for this machine. +mkdir -p "$host" +if [ ! -x "$host/lmembed" ] || [ "$root/tools/recomp/lmembed.cpp" -nt "$host/lmembed" ]; then + "${CXX:-c++}" -std=c++20 -O2 "$root/tools/recomp/lmembed.cpp" -o "$host/lmembed" +fi + +nod_pkg="${LM_NOD_PACKAGE:-$root/build/android-nod/libnod-android-aarch64.tar.gz}" +if [ ! -f "$nod_pkg" ]; then + echo "No nod package at $nod_pkg: run tools/android/build_nod.sh first (or set LM_NOD_PACKAGE)." >&2 + exit 1 +fi + +cmake --preset android-arm64 \ + -DLM_HOST_LMEMBED="$host/lmembed" \ + -DAURORA_NOD_PACKAGE_URL="file://$nod_pkg" \ + "$@" +cmake --build "$build" --target LuigisMansionRecomp +echo "Built $build/libmain.so" diff --git a/tools/android/build_apk.sh b/tools/android/build_apk.sh new file mode 100755 index 00000000..21dab3a3 --- /dev/null +++ b/tools/android/build_apk.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Packages build/android-arm64/libmain.so into an installable APK (docs/ANDROID.md). +# +# ANDROID_HOME= \ +# [LM_ANDROID_LLVM=] \ +# tools/android/build_apk.sh [out.apk] +# +# No Gradle: aapt2, javac, d8, zipalign and apksigner from the SDK. Signs with +# $LM_KEYSTORE (password $LM_KEYSTORE_PASS), or a local debug key made on first use. +# The APK holds no game data: players pick their own disc image on first start. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../.." && pwd)" +build="$root/build/android-arm64" +work="$root/build/android-apk" +out="${1:-$root/build/LuigisMansionPort-android-arm64.apk}" +: "${ANDROID_HOME:?set ANDROID_HOME to an Android SDK}" + +bt="$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)" +platform="$ANDROID_HOME/platforms/android-35/android.jar" +[ -f "$platform" ] || { echo "Need $platform (SDK platform 35)" >&2; exit 1; } +[ -f "$build/libmain.so" ] || { echo "Build libmain.so first (tools/android/build.sh)" >&2; exit 1; } + +sdl_java="$(sed -n 's/^AURORA_SDL3_JAVA_SOURCE_DIR:INTERNAL=//p' "$build/CMakeCache.txt")" +aurora_java="$(sed -n 's/^AURORA_ANDROID_JAVA_SOURCE_DIR:INTERNAL=//p' "$build/CMakeCache.txt")" +[ -d "$sdl_java/org/libsdl/app" ] || { echo "SDL's Java sources not found ($sdl_java)" >&2; exit 1; } + +version="$(sed -n 's/^CMAKE_PROJECT_VERSION:STATIC=//p' "$build/CMakeCache.txt")" +version="${version:-1.0.0}" +IFS=. read -r vmaj vmin vpat <<< "$version" +version_code=$(( ${vmaj:-1} * 10000 + ${vmin:-0} * 100 + ${vpat:-0} )) + +rm -rf "$work" +mkdir -p "$work"/{res,classes,dex,apk/lib/arm64-v8a,assets} + +# Manifest with the version filled in. +sed -e "s/@LM_VERSION_CODE@/$version_code/" -e "s/@LM_VERSION_NAME@/$version/" \ + "$root/packaging/android/AndroidManifest.xml" > "$work/AndroidManifest.xml" + +# Resources and assets. +"$bt/aapt2" compile --dir "$root/packaging/android/res" -o "$work/res/res.zip" +cp "$root/data/pipelines.bin" "$work/assets/" +cp "$root/NOTICE.md" "$work/assets/NOTICE.md" +cp "$root/packaging/LLVM-LICENSE.TXT" "$work/assets/LLVM-LICENSE.TXT" +"$bt/aapt2" link -o "$work/base.apk" -I "$platform" --manifest "$work/AndroidManifest.xml" \ + -A "$work/assets" --min-sdk-version 28 --target-sdk-version 35 "$work/res/res.zip" + +# Java: SDL's activity, Aurora's surface, the port's activity. +find "$sdl_java/org/libsdl/app" "$aurora_java" "$root/packaging/android/java" -name '*.java' > "$work/sources.txt" +javac -nowarn -source 8 -target 8 -encoding UTF-8 -bootclasspath "$platform" -classpath "$platform" \ + -d "$work/classes" @"$work/sources.txt" 2>&1 | grep -v -E "^warning: \[options\]|^[0-9]+ warnings?$|^Note: " || true +[ -n "$(find "$work/classes" -name LMActivity.class)" ] || { echo "javac failed" >&2; exit 1; } +"$bt/d8" --release --min-api 28 --lib "$platform" --output "$work/dex" $(find "$work/classes" -name '*.class') + +# Native code: the program and, if given, the bundled compiler for the first-run setup. +cp "$build/libmain.so" "$work/apk/lib/arm64-v8a/libmain.so" +"${ANDROID_NDK:-$ANDROID_HOME/ndk-bundle}"/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-strip \ + "$work/apk/lib/arm64-v8a/libmain.so" 2>/dev/null || strip "$work/apk/lib/arm64-v8a/libmain.so" 2>/dev/null || true +# Default: tools/android/build_llvm.sh's output. LM_ANDROID_LLVM=none builds an APK without it +# (setup then cannot build the game on the device). +llvm="${LM_ANDROID_LLVM:-$root/build/android-llvm/libllvm.so}" +if [ "$llvm" = none ]; then + echo "warning: no compiler in the APK: setup cannot build the game on the device" >&2 +elif [ -f "$llvm" ]; then + cp "$llvm" "$work/apk/lib/arm64-v8a/libllvm.so" +else + echo "No compiler at $llvm: run tools/android/build_llvm.sh, set LM_ANDROID_LLVM, or LM_ANDROID_LLVM=none" >&2 + exit 1 +fi + +cp "$work/base.apk" "$work/unsigned.apk" +(cd "$work/dex" && zip -q -X "$work/unsigned.apk" classes.dex) +(cd "$work/apk" && zip -q -X -r "$work/unsigned.apk" lib) +"$bt/zipalign" -f -P 16 4 "$work/unsigned.apk" "$work/aligned.apk" + +ks="${LM_KEYSTORE:-$root/build/android-debug.keystore}" +pass="${LM_KEYSTORE_PASS:-android}" +if [ ! -f "$ks" ]; then + keytool -genkeypair -keystore "$ks" -storepass "$pass" -keypass "$pass" -alias lmport \ + -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Luigi's Mansion Port (local build)" >/dev/null 2>&1 +fi +"$bt/apksigner" sign --ks "$ks" --ks-pass "pass:$pass" --key-pass "pass:$pass" --out "$out" "$work/aligned.apk" +"$bt/apksigner" verify "$out" +echo "Built $out ($(du -h "$out" | cut -f1))" diff --git a/tools/android/build_llvm.sh b/tools/android/build_llvm.sh new file mode 100755 index 00000000..c2912ae8 --- /dev/null +++ b/tools/android/build_llvm.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Builds the compiler the APK carries for the first-run setup (docs/ANDROID.md): clang and +# lld from the LLVM release, cross-compiled to run on Android arm64, as one multi-call +# binary (LLVM_TOOL_LLVM_DRIVER_BUILD: "llvm clang ..." / "llvm ld.lld ..."), AArch64 +# target only. The result is shipped as lib/arm64-v8a/libllvm.so. +# +# ANDROID_NDK= tools/android/build_llvm.sh [llvm-project checkout] +# +# Takes a few hours on a laptop (most of it is clang). Needs a host clang (for LLVM's +# build-time tablegen tools), CMake and Ninja. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../.." && pwd)" +: "${ANDROID_NDK:?set ANDROID_NDK to an Android NDK (r29 or newer)}" +llvm_version="${LM_LLVM_VERSION:-21.1.8}" +out="$root/build/android-llvm" +src="${1:-$out/llvm-project}" +mkdir -p "$out" +if [ ! -d "$src/llvm" ]; then + git clone -q --depth 1 --branch "llvmorg-$llvm_version" https://github.com/llvm/llvm-project.git "$src" +fi +cmake -G Ninja -S "$src/llvm" -B "$out/build" \ + -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK/build/cmake/android.toolchain.cmake" \ + -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-28 -DANDROID_STL=c++_static \ + -DCMAKE_BUILD_TYPE=Release \ + -DLLVM_ENABLE_PROJECTS="clang;lld" -DLLVM_TARGETS_TO_BUILD=AArch64 \ + -DLLVM_HOST_TRIPLE=aarch64-unknown-linux-android28 -DLLVM_DEFAULT_TARGET_TRIPLE=aarch64-unknown-linux-android28 \ + -DLLVM_TOOL_LLVM_DRIVER_BUILD=ON \ + -DLLVM_ENABLE_ZLIB=OFF -DLLVM_ENABLE_ZSTD=OFF -DLLVM_ENABLE_LIBXML2=OFF -DLLVM_ENABLE_TERMINFO=OFF \ + -DLLVM_ENABLE_LIBEDIT=OFF -DLLVM_ENABLE_BINDINGS=OFF -DLLVM_ENABLE_PIC=ON \ + -DLLVM_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_EXAMPLES=OFF -DLLVM_INCLUDE_BENCHMARKS=OFF -DLLVM_INCLUDE_DOCS=OFF \ + -DLLVM_INCLUDE_UTILS=OFF -DLLVM_BUILD_TOOLS=OFF \ + -DCLANG_ENABLE_STATIC_ANALYZER=OFF -DCLANG_ENABLE_ARCMT=OFF -DCLANG_PLUGIN_SUPPORT=OFF \ + -DCLANG_INCLUDE_TESTS=OFF -DCLANG_INCLUDE_DOCS=OFF \ + -DCROSS_TOOLCHAIN_FLAGS_NATIVE="-DCMAKE_C_COMPILER=${HOST_CC:-clang};-DCMAKE_CXX_COMPILER=${HOST_CXX:-clang++}" +cmake --build "$out/build" --target llvm-driver +"$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-strip" -o "$out/libllvm.so" "$out/build/bin/llvm" +echo "Built $out/libllvm.so (pass it to tools/android/build_apk.sh as LM_ANDROID_LLVM)" diff --git a/tools/android/build_nod.sh b/tools/android/build_nod.sh new file mode 100755 index 00000000..02e40715 --- /dev/null +++ b/tools/android/build_nod.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Builds nod (disc image reader, Rust) for Android arm64 and packages it like nod's own +# release packages, for AURORA_NOD_PACKAGE_URL (nod publishes no Android build; docs/ANDROID.md). +# +# ANDROID_NDK= tools/android/build_nod.sh +# +# Needs git, cargo and the aarch64-linux-android Rust target (rustup target add +# aarch64-linux-android). Without that target, LM_RUST_BUILD_STD=1 builds the standard +# library from rust-src instead (needs the rust-src component). +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../.." && pwd)" +: "${ANDROID_NDK:?set ANDROID_NDK to an Android NDK (r29 or newer)}" +version="$(sed -n 's/.*AURORA_NOD_VERSION "\([^"]*\)".*/\1/p' "$root/extern/aurora/cmake/AuroraDependencyVersions.cmake")" +out="$root/build/android-nod" +src="$out/nod-src" +mkdir -p "$out" +if [ ! -d "$src" ]; then + git clone -q --depth 1 --branch "$version" https://github.com/encounter/nod.git "$src" +fi +tc="$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/bin" +export CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER="$tc/aarch64-linux-android28-clang" +export CC_aarch64_linux_android="$tc/aarch64-linux-android28-clang" +export AR_aarch64_linux_android="$tc/llvm-ar" +extra=() +if [ "${LM_RUST_BUILD_STD:-0}" = 1 ]; then + export RUSTC_BOOTSTRAP=1 + extra=(-Zbuild-std=std,panic_abort) +fi +(cd "$src" && cargo build --release -p nod-ffi --no-default-features \ + --features compress-bzip2-static,compress-lzma-static,compress-zlib-static,compress-zstd-static,threading \ + --target aarch64-linux-android "${extra[@]}") + +# Same layout as nod's release packages (libnod-.tar.gz): its CMake package files +# and header are platform-independent, so they are taken from the Linux package of the same +# version, with the libraries replaced by the Android ones. +pkg="$out/pkg" +rm -rf "$pkg" +mkdir -p "$pkg" +curl -fsSL "https://github.com/encounter/nod/releases/download/$version/libnod-linux-x86_64.tar.gz" | tar xz -C "$pkg" +rm -f "$pkg"/lib/libnod.* +cp "$src/target/aarch64-linux-android/release/libnod.a" "$src/target/aarch64-linux-android/release/libnod.so" "$pkg/lib/" +cp "$src/nod-ffi/include/nod.h" "$pkg/include/nod.h" +tar czf "$out/libnod-android-aarch64.tar.gz" -C "$pkg" . +echo "Built $out/libnod-android-aarch64.tar.gz" diff --git a/tools/android/make_icon.py b/tools/android/make_icon.py new file mode 100644 index 00000000..0e2ae33c --- /dev/null +++ b/tools/android/make_icon.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Draws the Android launcher icon (an original design: a flashlight beam in a dark +hallway) into packaging/android/res/mipmap-*/ic_launcher.png. Needs Pillow.""" +import os +from PIL import Image, ImageDraw, ImageFilter + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +SIZES = {"mdpi": 48, "hdpi": 72, "xhdpi": 96, "xxhdpi": 144, "xxxhdpi": 192} + + +def draw(size: int) -> Image.Image: + s = 4 * size # supersample + img = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + bg = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + d = ImageDraw.Draw(bg) + d.rounded_rectangle([0, 0, s - 1, s - 1], radius=s // 5, fill=(24, 20, 48, 255)) + # floor glow + d.ellipse([s * 0.15, s * 0.70, s * 0.95, s * 0.98], fill=(60, 50, 90, 255)) + img = Image.alpha_composite(img, bg) + # beam: a soft yellow wedge from the lower left + beam = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + b = ImageDraw.Draw(beam) + b.polygon([(s * 0.22, s * 0.74), (s * 0.95, s * 0.28), (s * 0.95, s * 0.86)], fill=(255, 226, 120, 170)) + beam = beam.filter(ImageFilter.GaussianBlur(s * 0.02)) + img = Image.alpha_composite(img, beam) + # flashlight body + f = ImageDraw.Draw(img) + f.rounded_rectangle([s * 0.08, s * 0.70, s * 0.26, s * 0.80], radius=s * 0.03, fill=(70, 160, 90, 255)) + f.polygon([(s * 0.24, s * 0.68), (s * 0.30, s * 0.66), (s * 0.30, s * 0.84), (s * 0.24, s * 0.82)], fill=(200, 200, 210, 255)) + # two little eyes in the dark + for cx in (0.62, 0.72): + f.ellipse([s * (cx - 0.03), s * 0.40, s * (cx + 0.03), s * 0.48], fill=(255, 255, 255, 235)) + # clip to the rounded square + mask = Image.new("L", (s, s), 0) + ImageDraw.Draw(mask).rounded_rectangle([0, 0, s - 1, s - 1], radius=s // 5, fill=255) + img.putalpha(Image.composite(img.getchannel("A"), mask, mask)) + return img.resize((size, size), Image.LANCZOS) + + +def main(): + for name, px in SIZES.items(): + out = os.path.join(ROOT, "packaging", "android", "res", f"mipmap-{name}") + os.makedirs(out, exist_ok=True) + draw(px).save(os.path.join(out, "ic_launcher.png")) + print("icons written") + + +if __name__ == "__main__": + main()