Building for Android

A game made with Acron can be built as an Android app that runs on phones and tablets with a 64-bit ARM processor (arm64-v8a) and Android 7.0 (API level 24) or later. It renders with OpenGL ES 3, plays sound through OpenAL Soft, and is played with the fingers, a connected gamepad, or a keyboard and mouse.

A Python game is packed with build_apps into an Android App Bundle (.aab), the format the Play Store takes, and an APK made from it, which installs on a device; see Building a Python game below.

Building a Python game

A Python game is frozen with build_apps for the platform android. The engine wheel for it (android_arm64) comes from the Acron archive like the desktop wheels; it carries CPython for Android, so nothing is compiled. You need the Android SDK (a platform and the build-tools, from Android Studio or the command-line tools) and a JDK.

With acronmanager, in the project directory:

acronmanager dist --android

runs build_apps with the project’s options ([tool.acron.build_apps], the application id and icons of [tool.acron.app]), which makes an app bundle, dist/<name>-<version>_android.aab, and turns the bundle into one signed APK, dist/<name>-<version>.apk, with bundletool (fetched once when it is not installed). acronmanager run --android installs the APK on the connected device or emulator and starts it; build --android only builds it. [tool.acron.android] sets the ABI and the minimum Android version, the signing key (see Signing) and more:

[tool.acron.android]
abi = "arm64-v8a"                    # the default
min_sdk = 24                         # the default
# keystore = "release.jks"           # default: the debug key
# keystore_alias = "upload"
# keystore_password = "env:KS_PASS"  # pass:..., env:VAR or file:path
# prepare = ["python", "tools/data.py"]  # run from the project root first
# command = ["tools/package-android.sh"]  # your own packaging script

By hand, name the platform and the Android options in setup.py:

from setuptools import setup

setup(
    name="mygame",
    version="1.2.0",
    options={
        "build_apps": {
            "gui_apps": {"mygame": "main.py"},
            "platforms": ["android"],
            "android_abis": ["arm64-v8a"],
            "application_id": "com.example.mygame",
            "android_version_code": 3,
            "android_min_sdk_version": 24,
            "plugins": ["acrongles2", "p3openal_audio"],
            "include_patterns": ["models/**", "textures/**", "data/**"],
        },
    },
)

The launcher icon is the app’s icons, and on Android 8 and later its adaptive_icons (see App Icons and Store Art, which acronmanager makes from one picture); without them the app has Android’s default icon.

python setup.py bdist_apps writes dist/mygame-1.2.0_android.aab (it needs protobuf installed beside setuptools). To install the bundle on a device, turn it into one APK with bundletool, signed with your key (or the debug key for testing):

bundletool build-apks --mode=universal --bundle=dist/mygame-1.2.0_android.aab \
    --output=mygame.apks --ks=$HOME/.android/debug.keystore \
    --ks-key-alias=androiddebugkey --ks-pass=pass:android
unzip -p mygame.apks universal.apk > mygame.apk
adb install -r mygame.apk

A Python game on Android differs from the desktop in a few ways:

  • The included files stay inside the app, where the engine reads them at /android_asset (models, textures, sounds and fonts load as on the desktop). Python’s own open() cannot see them: read such files with the engine’s VirtualFileSystem, or copy them out to Filename.get_user_appdata_directory() on the first start.

  • Files the game writes belong in Filename.get_user_appdata_directory(), the app’s private storage (platformdirs cannot find it in a frozen app).

  • sys.platform is "android".

  • With acronmanager installed, build_apps ships the converted assets (.built_assets/) under the asset directory’s name (assets/), as on the desktop: look files up there in a frozen app.

  • A program the game runs (a chess engine, for example) must ship as a native library, lib/arm64-v8a/lib<name>.so, with the app’s native libraries extracted at install (android:extractNativeLibs="true" in the manifest): Android executes programs from nowhere else. sys.platlibdir is that directory at run time. Such a game packages itself with a script of its own ([tool.acron.android] command, which gets the app assets in ACRON_APP_ASSETS).

  • print() output goes to Android’s log under the tags python.stdout and python.stderr:

    adb logcat -s python.stdout python.stderr Acron
    

The rest of this page describes C++ games, but what it says about the Back button, the screen and touch screens applies to Python games as well.

Building a C++ game

The Android SDK

A C++ game is compiled against the Acron Android SDK: the engine cross-compiled as static libraries, with a CMake package and the tools that turn the game into an APK. It contains:

include/acron/          the engine's headers
lib/                    the static libraries
lib/cmake/Acron/        the CMake package, with AcronAndroid.cmake
share/acron/android/    the activity's Java sources and the APK packager
etc/                    the default configuration (.prc files)
starter/                a first game: a spinning cube, text, a tap counter
examples/rmlui-menu/    an RmlUi (HTML/CSS) menu: tap, drag to scroll, or gamepad
ANDROID_NDK_VERSION     the NDK the SDK was built with

The SDK records the version of the Android NDK it was built with in ANDROID_NDK_VERSION. Build your game with that NDK: static libraries only link reliably with the NDK that compiled them.

Prerequisites

  • The Android SDK, from Android Studio or the command-line tools, with a platform, the build-tools and the NDK the Acron SDK names:

    sdkmanager "platforms;android-35" "build-tools;35.0.0" "ndk;<version>"
    export ANDROID_HOME=~/Library/Android/sdk    # wherever it is installed
    

    ANDROID_HOME (or ANDROID_SDK_ROOT) tells the build where it is.

  • A JDK 17 or later, for javac and keytool.

  • Python 3.8 or later, which runs the APK packager.

  • CMake 3.21 or later; Ninja is recommended.

  • To run the game: a device with USB debugging enabled, or an emulator with an arm64-v8a system image (on an Apple silicon Mac it runs natively).

With acronmanager

Declare the game’s CMake build in pyproject.toml (see Building C++ Games for the Desktop), and the Android build in [tool.acron.android]:

[tool.acron.cmake]
target = "mygame"

[tool.acron.app]
name = "My Game"
id = "com.example.mygame"           # the PACKAGE (below)
icon = "art/icon.png"

[tool.acron.android]
# sdk = "acron-android-sdk-....tar.gz"  # default: the archive's latest
build_dir = "build/android"         # the default
configure_args = ["-DMYGAME_RELEASE=ON"]
# prepare = ["python", "tools/data.py"]  # run from the project root first
abi = "arm64-v8a"                   # the default
min_sdk = 24                        # the default
# keystore = "release.jks"          # default: the debug key
# keystore_alias = "upload"
# keystore_password = "env:KS_PASS" # pass:..., env:VAR or file:path

acronmanager build --android fetches the Android SDK (once, into the shared cache) and installs the NDK it names with sdkmanager when the Android SDK does not have it, configures the project with the NDK’s toolchain file in build/android, and builds the APK; dist --android copies it to dist/<name>-<version>.apk, and run --android installs it on the connected device or emulator and starts it. The application id (-DACRON_ANDROID_PACKAGE) and the launcher icons (-DACRON_ANDROID_ICON) come from [tool.acron.app]. You need the Android SDK (with a platform and the build-tools) and a JDK; ANDROID_HOME or ANDROID_SDK_ROOT tells acronmanager where the Android SDK is, else it looks where Android Studio installs it.

A first build

By hand, the starter in the SDK builds as it is:

cd starter
NDK=$ANDROID_HOME/ndk/$(cat ../ANDROID_NDK_VERSION)
cmake -S . -B build -G Ninja \
    -DCMAKE_TOOLCHAIN_FILE=$NDK/build/cmake/android.toolchain.cmake \
    -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-24 \
    -DAcron_DIR=$PWD/../lib/cmake/Acron
cmake --build build

This leaves build/starter.apk. Install and start it with adb:

adb install -r build/starter.apk
adb shell am start -n org.acron.starter/com.acronengine.android.AcronActivity

Building your game

On Android a game is one shared library, which the engine’s activity loads when the app starts; elsewhere it is an executable. Its main() runs as it does on the desktop and returns when the app is closed. acron_android_executable() links the engine into it and packages it as a signed APK after every build:

find_package(Acron REQUIRED COMPONENTS Framework)

if(ANDROID)
  add_library(mygame SHARED main.cxx)
  acron_android_executable(mygame
    LABEL "My Game"
    PACKAGE com.example.mygame
    VERSION_CODE 3
    VERSION_NAME 1.2
    DATA models textures etc)
else()
  add_executable(mygame main.cxx)
endif()

It links the framework, the OpenGL ES renderer, OpenAL audio and the egg loader, and registers the plugins that a static program cannot load by name. Link other components (Bullet, for example) with target_link_libraries as usual. The options are:

LABEL <name>

The app’s name on the launcher (default: the target’s name).

PACKAGE <id>

The application id, which identifies the app on the device and in a store (default: ACRON_ANDROID_PACKAGE if that is set, which acronmanager sets from [tool.acron.app] id, else org.acron.<target>). It is usually your domain reversed followed by the game’s name; once an app is published it cannot change.

VERSION_CODE <n>

An integer that grows with every release (default 1). Android installs an update only over a lower version code.

VERSION_NAME <text>

The version shown to players (default 1.0).

DATA <path>...

Files and directories copied into the APK’s assets. A directory keeps its name. The game finds them on its model path, so models/ship.bam loads as on the desktop, and the .prc files of an etc directory are read at startup. assets/assets.index in the APK lists every asset, for a game that needs to know what is there (to copy files out, for example).

ICON <png|dir>

The launcher icon: a PNG of 192 × 192 pixels or more, or an Android res directory with mipmap-*/ic_launcher.png, a round icon (ic_launcher_round.png) and an adaptive icon (mipmap-anydpi-v26/ic_launcher.xml and its layers), as acronmanager assets makes them from one picture (see App Icons and Store Art). Without it, ACRON_ANDROID_ICON if that is set, else Android’s default icon.

ORIENTATION <o>

landscape (the default), portrait, or any value of Android’s screenOrientation. With sensor or fullSensor the game turns with the device (see Turning the device).

KEYSTORE <file>, KEYSTORE_ALIAS <alias>, KEYSTORE_PASSWORD <pw>

The key the APK is signed with (see Signing). Without them it is signed with the debug key. The password can be given as env:VAR (from an environment variable) or file:path (the first line of a file), so that it does not have to be written into the build.

OUTPUT <file.apk>

Where the APK goes (default <build dir>/<target>.apk).

Unless CMAKE_BUILD_TYPE is Debug, the library is stripped of its debug information before it is packaged.

Signing

Every Android app is signed, and Android installs an update only when it is signed with the same key as the installed app. The builds sign with the debug key, ~/.android/debug.keystore (made if it is missing), unless they are given yours: fine for testing, but a debug-signed app cannot be published, and the debug key of another machine is another key.

Make a release key once with keytool and keep it, and its password, safe – without it, the app can never be updated:

keytool -genkeypair -keystore release.keystore -alias mygame \
    -keyalg RSA -keysize 2048 -validity 10000

Then name it to the build:

  • acronmanager (Python and C++): keystore, keystore_alias and keystore_password in [tool.acron.android], or the environment variables ACRON_ANDROID_KEYSTORE, ACRON_ANDROID_KEYSTORE_ALIAS and ACRON_ANDROID_KEYSTORE_PASSWORD, which take precedence (CI sets them from the repository’s secrets; see Continuous Integration for Games). The password is pass:<password>, env:<variable> or file:<path>.

  • CMake (C++): the KEYSTORE, KEYSTORE_ALIAS and KEYSTORE_PASSWORD options of acron_android_executable():

    acron_android_executable(mygame LABEL "My Game" PACKAGE com.example.mygame
        KEYSTORE ${CMAKE_SOURCE_DIR}/release.keystore
        KEYSTORE_ALIAS mygame
        KEYSTORE_PASSWORD env:MYGAME_KEY_PASSWORD
        DATA models textures)
    
  • bundletool (a Python game’s APK, made by hand): --ks, --ks-key-alias and --ks-pass.

Google Play takes app bundles, which only Python games have: upload the .aab of bdist_apps (acronmanager signs the APK it makes from it, not the bundle), signed with your upload key – with jarsigner from the JDK, or by bdist_apps itself, given the key and its certificate as PEM files (signing_certificate, signing_private_key; see List of Build Options). A C++ game’s APK can be published outside Google Play (on itch.io, or for side-loading).

What a game does differently

Most of a game needs no changes. The differences are:

Files

The game’s data is read-only, inside the APK: load it from the model path rather than from a path next to the program. Files the game writes – saved games, settings – belong in Filename::get_user_appdata_directory(), which is the app’s private storage on Android.

The Back button

Android’s Back button and the back gesture arrive as the escape key, so the game’s existing “pause” or “back to the menu” handling works. On the main menu, quitting the game is the expected answer to it.

The screen

The game draws under the system bars, which are hidden until the player swipes from the edge of the screen.

In the background

When the player switches to another app, the game’s window goes away until the player comes back, but the game keeps its state and the graphics context, with the textures and buffers loaded into it. The window’s minimized and foreground properties tell when this happens, for a game that pauses itself then.

The log

The engine’s log, and everything the game prints to std::cout and std::cerr, goes to Android’s log, under the tags Acron, stdout and stderr:

adb logcat -s Acron stdout stderr

Turning the device

A game built with ORIENTATION sensor or fullSensor (or user, sensorPortrait and the like) turns with the device and keeps running: it is not restarted. The window changes size, as a desktop window does when the player resizes it: the game receives a window-event, and the framework adjusts the lenses’ aspect ratio. A game that lays out its screen for the window’s shape does so again on that event. The size can also change in Android’s split-screen and free-form window modes.

The default, landscape, keeps the game the right way up whichever way the device is held in landscape, without these changes of size.

Touch screens

Asking for touch controls

GraphicsWindow::has_touch_screen() tells whether the window is on a touch screen that is the device’s main input – a phone or a tablet. When it is, show touch controls, size buttons for fingers, and say “tap” rather than “press a key”. It is false on the desktop and the web, and on an Android device without a touch screen; a keyboard, mouse or gamepad may be connected either way.

GraphicsWindow *win = window->get_graphics_window();
bool touch = win != nullptr && win->has_touch_screen();

The fingers as the mouse

Without any work on the game’s side, the finger that touches the screen first stands in for the mouse:

  • It presses the left mouse button (mouse1) where it lands, and lifting it releases the button there. A tap therefore clicks what is under the finger, as GUI buttons expect.

  • Dragging it moves the mouse pointer.

  • A frame after it lifts, the pointer leaves the window, so nothing stays under a hover highlight.

  • Other fingers that touch the screen meanwhile do not move the mouse, and when the first finger lifts they do not take over: the mouse waits for the next finger to touch an empty screen.

  • While the window’s mouse mode is M_relative (a game’s mouse look), no finger stands in for the mouse: they are only touches, for the game or a touch gamepad to read.

Several fingers in the GUI

The GUI follows every finger by itself: each presses the button (or slider, entry, scroll frame) it lands on, and lifting it there clicks that button, whatever the other fingers do. Two fingers press two buttons at once; one finger drags a slider while another taps a button. The first finger does so as the mouse (mouse1); the others with the button MouseButton::touch(). A PGButton clicks with both by default (add_click_button() and remove_click_button() change that), so its click event is click-mouse1-<id> for the first finger and click-touch-<id> for the others. The MouseWatcherParameter of an event tells which finger it was: get_pointer_id(), which is 0 for the mouse itself.

A finger dragged across a PGScrollFrame (that is active) scrolls it, as on any phone; the mouse does not.

Every finger on its own

For the game itself, several ways to follow the fingers:

  • touch is a button that is down while any finger touches the screen (an event like mouse1, but for all the fingers).

  • GraphicsWindow::get_num_touches() and get_touch_info() give the position and id of each finger that is down.

  • Each finger is a pointer of the window’s input device, of type PointerType::FINGER, its id one more than the finger’s; the first finger’s is primary (PointerData::is_primary()), as it is the mouse.

  • A PointerThrower attached to the window’s MouseAndKeyboard throws pointer-down, pointer-move and pointer-up for every finger, with the finger’s id and its position in window pixels:

    #include "pointerThrower.h"
    
    // The MouseAndKeyboard of the window (window->get_mouse() is the
    // MouseWatcher below it, which does not pass the fingers on).
    NodePath mouse = framework.get_mouse(window->get_graphics_output());
    mouse.attach_new_node(new PointerThrower("pointers"));
    framework.define_key("pointer-down", "finger", &on_finger_down, nullptr);
    

    ShowBase attaches one for each window.

The touch gamepad

TouchGamepad is a gamepad drawn on the screen and played with the fingers: a stick that appears where a finger lands on the left of the screen, a look area on the right, and buttons. It is an InputDevice of the gamepad class, registered with the InputDeviceManager, so a game that already supports gamepads plays on a phone without further work:

#include "touchGamepad.h"

PT(TouchGamepad) pad = new TouchGamepad;
pad->set_default_layout();   // face buttons, shoulders, start, back, D-pad
pad->setup_window(window->get_graphics_window());

setup_window() draws it over the window in a display region of its own. By default it is shown while the window’s mouse mode is relative – during play, when the fingers stop acting as the mouse – and hidden otherwise, so menus are tapped and play has the pad. set_visibility(TouchGamepad::V_shown) or V_hidden overrides that. A finger that is already down when the gamepad appears (the tap that started or resumed the game) is ignored until it lifts.

Instead of the default layout, add_button(button, label, x, y, radius) places a GamepadButton where you want it: x and y as fractions of the window’s width and height, radius as a fraction of its shorter side.

Looking around. A stick turns the view at a rate, which is not how a camera should follow a finger. A game with mouse look sets set_look_mode(TouchGamepad::LM_delta) and adds get_look_delta() – how far the look finger moved since the last frame – to its mouse motion, so the view follows the finger. The default, LM_stick, moves the right stick instead, for games that only read gamepads. set_look_sensitivity() scales either.

Theming. Without art of its own the gamepad is translucent white discs with white labels. A game gives it its own look with:

  • set_button_images(button, image, pressed): a square image, the button’s diameter wide, and optionally another while it is pressed;

  • set_stick_images(base, knob): the stick’s base and knob;

  • set_font(font), set_label_color(color) and set_label_shadow(color) for the labels (an empty label draws none);

  • set_opacity(opacity) for the whole of it.