diff --git a/.gitignore b/.gitignore index d6013931e..24c195817 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,16 @@ compile_commands.json *~ *.log memcards/ + +# Android/Gradle +.gradle/ +local.properties +**/build/ +**/.cxx/ +*.apk +*.aar +.navigation/ +captures/ +*.keystore +!debug.keystore + diff --git a/CMakeLists.txt b/CMakeLists.txt index 7ce4ec210..c2f8dc37a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.20) -project(CTR-Native C) +project(CTR-Native C CXX) include(CheckCCompilerFlag) set(CMAKE_C_STANDARD 99) @@ -7,9 +7,11 @@ set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_C_EXTENSIONS ON) set(CTR_NATIVE_VERSION "0.1.0-beta.7.1") -if(NOT CMAKE_C_COMPILER_TARGET MATCHES "i.86" AND NOT CMAKE_SYSTEM_PROCESSOR MATCHES "i.86") - set(CMAKE_C_FLAGS "-m32 ${CMAKE_C_FLAGS}") - set(CMAKE_EXE_LINKER_FLAGS "-m32 ${CMAKE_EXE_LINKER_FLAGS}") +if(NOT ANDROID) + if(NOT CMAKE_C_COMPILER_TARGET MATCHES "i.86" AND NOT CMAKE_SYSTEM_PROCESSOR MATCHES "i.86") + set(CMAKE_C_FLAGS "-m32 ${CMAKE_C_FLAGS}") + set(CMAKE_EXE_LINKER_FLAGS "-m32 ${CMAKE_EXE_LINKER_FLAGS}") + endif() endif() set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE NEVER) @@ -40,7 +42,10 @@ else() set(CTR_NATIVE_BUILD_ID "${CTR_NATIVE_GIT_HASH}-dirty-${CTR_NATIVE_BUILD_TIMESTAMP}") endif() -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -msse -Wno-error -g") +if(NOT ANDROID) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -msse") +endif() +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error -g") function(ctr_native_add_label_warning_if_supported target warning flag_check) set(saved_required_flags "${CMAKE_REQUIRED_FLAGS}") @@ -57,21 +62,25 @@ function(ctr_native_add_label_warning_if_supported target warning flag_check) endfunction() # SDL3 -set(SDL_SHARED OFF CACHE BOOL "" FORCE) -set(SDL_STATIC ON CACHE BOOL "" FORCE) +set(SDL_SHARED ON CACHE BOOL "" FORCE) +set(SDL_STATIC OFF CACHE BOOL "" FORCE) set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE) set(SDL_TESTS OFF CACHE BOOL "" FORCE) set(SDL_EXAMPLES OFF CACHE BOOL "" FORCE) set(SDL_INSTALL OFF CACHE BOOL "" FORCE) set(SDL_GPU OFF CACHE BOOL "" FORCE) -set(SDL_RENDER OFF CACHE BOOL "" FORCE) +set(SDL_RENDER ON CACHE BOOL "" FORCE) set(SDL_CAMERA OFF CACHE BOOL "" FORCE) -set(SDL_SENSOR OFF CACHE BOOL "" FORCE) +set(SDL_SENSOR ON CACHE BOOL "" FORCE) set(SDL_DIALOG OFF CACHE BOOL "" FORCE) set(SDL_TRAY OFF CACHE BOOL "" FORCE) -set(SDL_POWER OFF CACHE BOOL "" FORCE) +set(SDL_POWER ON CACHE BOOL "" FORCE) set(SDL_VULKAN OFF CACHE BOOL "" FORCE) -set(SDL_OPENGLES OFF CACHE BOOL "" FORCE) +if(ANDROID) + set(SDL_OPENGLES ON CACHE BOOL "" FORCE) +else() + set(SDL_OPENGLES OFF CACHE BOOL "" FORCE) +endif() set(SDL_OFFSCREEN OFF CACHE BOOL "" FORCE) set(SDL_SNDIO OFF CACHE BOOL "" FORCE) set(SDL_SNDIO_SHARED OFF CACHE BOOL "" FORCE) @@ -80,7 +89,12 @@ set(SDL_X11_XTEST OFF CACHE BOOL "" FORCE) add_subdirectory(externals/SDL) # CTR Native -add_executable(ctr_native main.c) +if(ANDROID) + add_library(ctr_native SHARED main.c) +else() + add_executable(ctr_native main.c) +endif() +set_target_properties(ctr_native PROPERTIES LINKER_LANGUAGE CXX) target_include_directories(ctr_native PRIVATE ${CMAKE_SOURCE_DIR}/include) target_compile_definitions(ctr_native PRIVATE CTR_NATIVE @@ -100,6 +114,9 @@ elseif(CMAKE_C_COMPILER_ID MATCHES "Clang") ctr_native_add_label_warning_if_supported(ctr_native -Wc23-extensions CTR_HAS_WC23_EXTENSIONS) endif() target_link_libraries(ctr_native SDL3::SDL3) +if(ANDROID) + target_link_libraries(ctr_native log GLESv2 android) +endif() target_link_options(ctr_native PRIVATE -static-libgcc) if(WIN32) target_link_options(ctr_native PRIVATE -static) diff --git a/README_ANDROID.md b/README_ANDROID.md new file mode 100644 index 000000000..320f2bd99 --- /dev/null +++ b/README_ANDROID.md @@ -0,0 +1,32 @@ +# CTR Native Android Port + +This project has been ported to Android using SDL3. + +## Building + +1. Open the `android` folder in Android Studio. +2. Sync Gradle. +3. Build and run. + +The build targets `armeabi-v7a` to maintain 32-bit compatibility with the game's memory model. + +## Assets Setup (S21+ / Modern Android) + +Due to Android security restrictions, the game looks for assets in its private external storage. + +1. Install the app on your phone. +2. Create the following directory on your phone: + `/storage/emulated/0/Android/data/com.ctrnative/files/assets/` +3. Place your `ctr-u.bin` (NTSC-U retail disc image) into that `assets` folder. + The path should be: + `.../Android/data/com.ctrnative/files/assets/ctr-u.bin` +4. Alternatively, you can place extracted assets (BIGFILE.BIG, etc.) in the same `assets` folder. + +## Controls + +- The port supports the **Backbone One** and other standard Android gamepads via SDL3's Gamepad API. +- Touch controls are currently not implemented (keyboard/gamepad only). + +## Troubleshooting + +Check Logcat with tag `CTR-Native` for any initialization errors. diff --git a/android/.DS_Store b/android/.DS_Store new file mode 100644 index 000000000..29f68c767 Binary files /dev/null and b/android/.DS_Store differ diff --git a/android/app/.DS_Store b/android/app/.DS_Store new file mode 100644 index 000000000..dede17299 Binary files /dev/null and b/android/app/.DS_Store differ diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 000000000..1e83b3cee --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,52 @@ +apply plugin: 'com.android.application' + +android { + namespace 'com.ctrnative' + compileSdk 34 + + defaultConfig { + applicationId "com.ctrnative" + minSdk 21 + targetSdk 34 + versionCode 1 + versionName "1.0" + + externalNativeBuild { + cmake { + arguments "-DANDROID_STL=c++_static", "-DCTR_NATIVE=ON" + abiFilters 'armeabi-v7a' + } + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + + externalNativeBuild { + cmake { + path "../../CMakeLists.txt" + version "3.22.1" + } + } + + sourceSets { + main { + java.srcDirs = [ + 'src/main/java', + '../../externals/SDL/android-project/app/src/main/java' + ] + res.srcDirs = [ + 'src/main/res', + '../../externals/SDL/android-project/app/src/main/res' + ] + } + } +} + +dependencies { + implementation 'androidx.appcompat:appcompat:1.6.1' +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..a75126aa2 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/com/ctrnative/CTRNativeActivity.java b/android/app/src/main/java/com/ctrnative/CTRNativeActivity.java new file mode 100644 index 000000000..c080329ed --- /dev/null +++ b/android/app/src/main/java/com/ctrnative/CTRNativeActivity.java @@ -0,0 +1,13 @@ +package com.ctrnative; + +import org.libsdl.app.SDLActivity; + +public class CTRNativeActivity extends SDLActivity { + @Override + protected String[] getLibraries() { + return new String[] { + "SDL3", + "ctr_native" + }; + } +} diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 000000000..df4514e3f --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,20 @@ +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.2.2' + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 000000000..646c51b97 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,2 @@ +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..61285a659 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..b82aa23a4 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 000000000..adff685a0 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 000000000..e509b2dd8 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 000000000..e7b4def49 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1 @@ +include ':app' diff --git a/game/223.c b/game/223.c index 5e7674384..23206b1c4 100644 --- a/game/223.c +++ b/game/223.c @@ -334,7 +334,7 @@ void RR_EndEvent_DrawMenu(void) if (elapsedFrames >= RR_COUNTDOWN_START_FRAME) { char *str = countdownText; - sprintf(str, s_countdownStartFormat223); + sprintf(str, "%s", s_countdownStartFormat223); drawCountdown = 0; diff --git a/game/UI/UI_RenderFrame.c b/game/UI/UI_RenderFrame.c index a41a13b7e..2e137db5c 100644 --- a/game/UI/UI_RenderFrame.c +++ b/game/UI/UI_RenderFrame.c @@ -683,7 +683,7 @@ void UI_RenderFrame_Racing() // "999" <-- ascii string, not 2-u8 value // Cap the on-screen counter at 999 - sprintf((char *)&string[0], &sdata->s_999[0]); + sprintf((char *)&string[0], "%s", &sdata->s_999[0]); } i = DecalFont_GetLineWidth(sdata->lngStrings[LNG_TURBOS], 1); diff --git a/main.c b/main.c index b6182ce9c..951f211f2 100644 --- a/main.c +++ b/main.c @@ -1,5 +1,7 @@ #define _CRT_SECURE_NO_WARNINGS +#ifndef __ANDROID__ #define SDL_MAIN_HANDLED +#endif #include #include @@ -118,6 +120,7 @@ static int NativeConsole_ShouldPauseOnError(void) static s32 NativeConsole_Return(const u32 result) { +#ifndef __ANDROID__ if ((result != 0) && NativeConsole_ShouldPauseOnError()) { fflush(stdout); @@ -129,6 +132,7 @@ static s32 NativeConsole_Return(const u32 result) { } } +#endif return (s32)result; } @@ -154,7 +158,15 @@ int main(int argc, char *argv[]) printf("[CTR Native] Starting...\n"); fflush(stdout); - const char *sdlBasePath = SDL_GetBasePath(); + const char *sdlBasePath = NULL; +#ifdef __ANDROID__ + // On Android, we search for assets in the app's external files directory + sdlBasePath = SDL_GetPrefPath("CTR-Native", "assets"); + // The above usually returns /data/user/0/com.ctrnative/files/assets/ + // We might want to look at the external files dir too. +#else + sdlBasePath = SDL_GetBasePath(); +#endif printf("[CTR Native] SDL base path: %s\n", sdlBasePath ? sdlBasePath : "(null)"); fflush(stdout); diff --git a/platform/native_audio.c b/platform/native_audio.c index db1123f7a..c8ad51a8a 100644 --- a/platform/native_audio.c +++ b/platform/native_audio.c @@ -1891,7 +1891,7 @@ internal int NativeAudio_RenderFramesNoLock(s16 *out, int frameCount); internal void NativeAudio_SelectDriverHint(void) { -#if defined(__linux__) +#if defined(__linux__) && !defined(__ANDROID__) if (SDL_GetHint(SDL_HINT_AUDIO_DRIVER) == NULL) { // NOTE(aalhendi): Keep native Linux playback on the SDL3 drivers that @@ -3170,7 +3170,7 @@ void NativeAudio_StepVBlank(void) #ifdef CTR_INTERNAL if (shouldReportStats) { - printf("[CTR Native] Audio output stats: underrunFrames=%d overflowFrames=%d queuedFrames=%d callbackMaxRequestFrames=%d\n", underrunFrames, + Platform_Log("[CTR Native] Audio output stats: underrunFrames=%d overflowFrames=%d queuedFrames=%d callbackMaxRequestFrames=%d\n", underrunFrames, overflowFrames, queuedFrames, s_audio.output.callbackMaxRequestFrames); } #endif @@ -3207,7 +3207,7 @@ internal int NativeAudio_OpenDevice(void) s_audio.output.stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &want, NativeAudio_StreamCallback, NULL); if (s_audio.output.stream == NULL) { - fprintf(stderr, "[CTR Native] SDL audio unavailable: %s\n", SDL_GetError()); + Platform_LogError("[CTR Native] SDL audio unavailable: %s\n", SDL_GetError()); return 0; } @@ -3218,7 +3218,7 @@ internal int NativeAudio_OpenDevice(void) } if (!SDL_GetAudioStreamFormat(s_audio.output.stream, &srcSpec, &dstSpec)) { - fprintf(stderr, "[CTR Native] SDL audio stream format unavailable: %s\n", SDL_GetError()); + Platform_LogError("[CTR Native] SDL audio stream format unavailable: %s\n", SDL_GetError()); SDL_DestroyAudioStream(s_audio.output.stream); s_audio.output.stream = NULL; s_audio.output.device = 0; @@ -3227,7 +3227,7 @@ internal int NativeAudio_OpenDevice(void) if ((srcSpec.freq != want.freq) || (srcSpec.format != want.format) || (srcSpec.channels != want.channels)) { - fprintf(stderr, "[CTR Native] SDL audio rejected fixed PCM contract: got %d Hz format 0x%x channels %d\n", srcSpec.freq, srcSpec.format, + Platform_LogError("[CTR Native] SDL audio rejected fixed PCM contract: got %d Hz format 0x%x channels %d\n", srcSpec.freq, srcSpec.format, srcSpec.channels); SDL_DestroyAudioStream(s_audio.output.stream); s_audio.output.stream = NULL; @@ -3235,12 +3235,12 @@ internal int NativeAudio_OpenDevice(void) return 0; } - printf("[CTR Native] SDL audio stream opened: driver=%s src=%d Hz/%d ch dst=%d Hz/%d ch device=%d Hz/%d ch sampleFrames=%d\n", SDL_GetCurrentAudioDriver(), + Platform_Log("[CTR Native] SDL audio stream opened: driver=%s src=%d Hz/%d ch dst=%d Hz/%d ch device=%d Hz/%d ch sampleFrames=%d\n", SDL_GetCurrentAudioDriver(), srcSpec.freq, srcSpec.channels, dstSpec.freq, dstSpec.channels, deviceSpec.freq, deviceSpec.channels, deviceSampleFrames); NativeAudio_ClearOutputQueueNoLock(); if (!SDL_ResumeAudioStreamDevice(s_audio.output.stream)) { - fprintf(stderr, "[CTR Native] SDL audio stream resume failed: %s\n", SDL_GetError()); + Platform_LogError("[CTR Native] SDL audio stream resume failed: %s\n", SDL_GetError()); SDL_DestroyAudioStream(s_audio.output.stream); s_audio.output.stream = NULL; s_audio.output.device = 0; diff --git a/platform/native_log.c b/platform/native_log.c index e04862126..bee91aa98 100644 --- a/platform/native_log.c +++ b/platform/native_log.c @@ -10,6 +10,11 @@ #include "platform/native_win32.h" #endif +#ifdef __ANDROID__ +#include +#define LOG_TAG "CTR-Native" +#endif + global_variable FILE *s_logStream = NULL; global_variable char s_logPath[512]; // TODO(aalhendi): yeah this is an issue waiting to happen. w/e @@ -21,6 +26,10 @@ internal void Platform_LogWrite(FILE *consoleStream, const char *text) OutputDebugStringA(text); #endif +#ifdef __ANDROID__ + __android_log_write(ANDROID_LOG_INFO, LOG_TAG, text); +#endif + fputs(text, stream); if (s_logStream != NULL) diff --git a/platform/native_renderer.c b/platform/native_renderer.c index 9182d7b92..33654e26e 100644 --- a/platform/native_renderer.c +++ b/platform/native_renderer.c @@ -26,6 +26,10 @@ __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; #endif // def WIN32 +#ifdef __ANDROID__ +#define VRAM_FORMAT GL_RG +#define VRAM_INTERNAL_FORMAT GL_RG8 +#else #define VRAM_FORMAT GL_RG // NOTE(penta3): VRAM holds packed 16-bit PSX pixels as two bytes (R=low, // G=high), uploaded as GL_RG + GL_UNSIGNED_BYTE. RG8 is the faithful storage: @@ -148,9 +152,15 @@ internal int NativeRenderer_InitialiseGLContext(char *windowName, int fullscreen return 0; } +#ifdef __ANDROID__ + int major_version = 3; + int minor_version = 0; + int profile = SDL_GL_CONTEXT_PROFILE_ES; +#else int major_version = 3; int minor_version = 3; int profile = SDL_GL_CONTEXT_PROFILE_CORE; +#endif // find best OpenGL version do @@ -170,7 +180,11 @@ internal int NativeRenderer_InitialiseGLContext(char *windowName, int fullscreen if (minor_version == -1) { +#ifdef __ANDROID__ + NATIVE_RENDERER_ERROR("Failed to initialise - OpenGL ES 3.x is not supported. Please update video drivers.\n"); +#else NATIVE_RENDERER_ERROR("Failed to initialise - OpenGL 3.x is not supported. Please update video drivers.\n"); +#endif return 0; } @@ -179,9 +193,14 @@ internal int NativeRenderer_InitialiseGLContext(char *windowName, int fullscreen internal int NativeRenderer_InitialiseGLExt(void) { - GLenum err = gladLoadGL(); +#ifdef __ANDROID__ + // On Android, use SDL to load the GL functions as it's already linked to GLES. + int status = gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress); +#else + int status = gladLoadGL(); +#endif - if (err == 0) + if (status == 0) { return 0; } @@ -677,6 +696,21 @@ internal int NativeRenderer_Shader_CheckProgramStatus(GLuint program) internal ShaderID NativeRenderer_Shader_Compile(const char *source, bool isPsxShader) { +#ifdef __ANDROID__ + const char *GLSL_HEADER_VERT = " #version 300 es\n" + " precision mediump int;\n" + " precision highp float;\n" + " #define varying out\n" + " #define attribute in\n" + " #define texture2D texture\n"; + + const char *GLSL_HEADER_FRAG = " #version 300 es\n" + " precision mediump int;\n" + " precision highp float;\n" + " #define varying in\n" + " #define texture2D texture\n" + " out vec4 fragColor;\n"; +#else const char *GLSL_HEADER_VERT = " #version 140\n" " precision lowp int;\n" " precision highp float;\n" @@ -690,6 +724,7 @@ internal ShaderID NativeRenderer_Shader_Compile(const char *source, bool isPsxSh " #define varying in\n" " #define texture2D texture\n" " out vec4 fragColor;\n"; +#endif char extra_vs_defines[1024]; char extra_fs_defines[1024]; @@ -1623,6 +1658,11 @@ void NativeRenderer_ReadFramebufferDataToVRAM(void) pixels = NativeRenderer_GetReadbackScratch(w * h); if (pixels != NULL) { +#ifdef __ANDROID__ + glBindFramebuffer(GL_FRAMEBUFFER, s_glBlitFramebuffer); + glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + glBindFramebuffer(GL_FRAMEBUFFER, 0); +#else glBindTexture(GL_TEXTURE_2D, s_framebufferTexture); // NOTE(aalhendi): DrawSync can be called immediately before screen-copy // effects sample PS1 VRAM. A delayed readback replays an older frame @@ -1630,6 +1670,7 @@ void NativeRenderer_ReadFramebufferDataToVRAM(void) // framebuffer texture here. glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glBindTexture(GL_TEXTURE_2D, 0); +#endif // NOTE(aalhendi): Keep the CPU-side VRAM mirror packed like PS1 VRAM. // Host texture bindings are invalid after this direct GL texture read. NativeRenderer_CopyRGBAFramebufferToVRAM(pixels, x, y, w, h, 1, 0); @@ -1679,8 +1720,14 @@ internal void NativeRenderer_FlushOffscreenToVRAM(void) return; } +#ifdef __ANDROID__ + glBindFramebuffer(GL_FRAMEBUFFER, s_glOffscreenFramebuffer); + glReadPixels(0, 0, s_previousOffscreen.w, s_previousOffscreen.h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + glBindFramebuffer(GL_FRAMEBUFFER, 0); +#else glBindTexture(GL_TEXTURE_2D, s_offscreenRenderTexture); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); +#endif glBindTexture(GL_TEXTURE_2D, s_lastBoundTexture != (TextureID)-1 ? s_lastBoundTexture : 0); NativeRenderer_CopyRGBAFramebufferToVRAM(pixels, s_previousOffscreen.x, s_previousOffscreen.y, s_previousOffscreen.w, s_previousOffscreen.h, 0, 1); @@ -2205,7 +2252,9 @@ internal void NativeRenderer_SetViewPort(int x, int y, int width, int height) internal void NativeRenderer_SetWireframe(int enable) { +#ifndef __ANDROID__ glPolygonMode(GL_FRONT_AND_BACK, enable ? GL_LINE : GL_FILL); +#endif } internal void NativeRenderer_BindVertexBuffer(void)