A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(native): package the Android APK through the same task, not by hand
esengine9e95e5850457
diff --git a/build-tools/cli.js b/build-tools/cli.jsindex 649f3b55d..6fd3cb87a 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -167,6 +167,9 @@ program.option('--abi <abi>', 'Android ABI', 'arm64-v8a').option('--platform <platform>', 'Android platform', 'android-33').option('--ios-min <version>', 'iOS deployment target', '17.0')+ .option('--package', 'Android: also package a signed APK (aapt2 + zipalign + apksigner)', false)+ .option('--host <host>', 'Android --package: js (QuickJS host) or cpp (smoke test)')+ .option('--keystore <path>', 'Android --package: signing keystore (default: the debug one)').option('-v, --verbose', 'Verbose output', false).action(async (options) => {logger.setVerbose(options.verbose);@@ -179,6 +182,9 @@ programabi: options.abi,platform: options.platform,iosMin: options.iosMin,+ package: options.package,+ host: options.host,+ keystore: options.keystore,});} catch (err) {logger.error(err.message);diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.jsindex eaee39f68..741f77e64 100644--- a/build-tools/tasks/native.js+++ b/build-tools/tasks/native.js@@ -9,35 +9,13 @@// --dawn / --dawn-build or ESTELLA_DAWN_DIR / ESTELLA_DAWN_BUILD.import path from 'path';-import { existsSync, readdirSync, readFileSync, writeFileSync } from 'fs';+import { existsSync, readFileSync, writeFileSync } from 'fs';import { mkdir } from 'fs/promises';import config from '../build.config.js';import * as logger from '../utils/logger.js';import { runCommand, getCpuCount, resolvePython } from '../utils/emscripten.js';--function androidSdk() {- const sdk = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT;- if (sdk && existsSync(sdk)) return sdk;- // Android Studio's default install location.- const dflt = path.join(process.env.LOCALAPPDATA || process.env.HOME || '', 'Android', 'Sdk');- return existsSync(dflt) ? dflt : null;-}--function newest(dir) {- if (!existsSync(dir)) return null;- const entries = readdirSync(dir).sort();- return entries.length ? path.join(dir, entries[entries.length - 1]) : null;-}--// Prefer the NDK-bundled CMake (>= 3.22, ships ninja) over whatever is on PATH —-// CMake 4.x rejects the pre-3.5 minimums in some transitive deps.-function sdkCmake(sdk) {- const cmakeRoot = newest(path.join(sdk, 'cmake'));- if (!cmakeRoot) return { cmake: 'cmake', ninja: null };- const bin = path.join(cmakeRoot, 'bin');- const exe = process.platform === 'win32' ? '.exe' : '';- return { cmake: path.join(bin, 'cmake' + exe), ninja: path.join(bin, 'ninja' + exe) };-}+import { requireSdk, requireNdk, sdkCmake } from '../utils/android.js';+import { packageNativeApk } from './nativePackage.js';// Generate the native (QuickJS) ECS bindings from the SAME reflection source EHT// uses for the web embind bindings — so the two surfaces can never drift. Written@@ -114,10 +92,8 @@ async function buildAndroidHost(options) {const { abi = 'arm64-v8a', platform = 'android-33' } = options;const rootDir = config.paths.root;- const sdk = androidSdk();- if (!sdk) throw new Error('Android SDK not found. Set ANDROID_HOME (install via Android Studio).');- const ndk = newest(path.join(sdk, 'ndk'));- if (!ndk) throw new Error(`No NDK under ${sdk}/ndk. Install one via Android Studio's SDK Manager.`);+ const sdk = requireSdk();+ const ndk = requireNdk(sdk);const toolchain = path.join(ndk, 'build', 'cmake', 'android.toolchain.cmake');const { dawnDir, dawnBuild } = dawnPaths(options);@@ -162,6 +138,13 @@ async function buildAndroidHost(options) {if (quickjs) {logger.success(`JS host: ${path.join('build-native', 'libestella_js_host.so')}`);}++ if (options.package) {+ await packageNativeApk({+ host: options.host || (quickjs ? 'js' : 'cpp'),+ dawnBuild, abi, platform, keystore: options.keystore,+ });+ }}// Xcode ships the iPhoneOS SDK; the Command Line Tools alone do not. Point thediff --git a/build-tools/tasks/nativePackage.js b/build-tools/tasks/nativePackage.jsnew file mode 100644index 000000000..63973a84b--- /dev/null+++ b/build-tools/tasks/nativePackage.js@@ -0,0 +1,128 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// APK packaging for the native host — the Android counterpart of what Xcode does+// for native/ios. No gradle: the host is a NativeActivity with no Java, so the+// APK is just aapt2 link, the .so payload, zipalign and apksigner. The game and+// its content go in as assets/, which is where the host's readAsset() looks.++import path from 'path';+import { existsSync } from 'fs';+import { mkdir, copyFile, rm } from 'fs/promises';+import config from '../build.config.js';+import * as logger from '../utils/logger.js';+import { runCommand } from '../utils/emscripten.js';+import { requireSdk, requireNdk, buildTool, platformJar, ndkTool, ndkLibcxxShared } from '../utils/android.js';++const HOSTS = {+ // The product-shaped runtime: the QuickJS host + the SDK + a game asset.+ js: {+ manifest: 'js',+ library: 'libestella_js_host.so',+ assets: ['game.js', 'logo.png'],+ apk: 'estella-js-host.apk',+ },+ // The pure-C++ smoke test: one ECS scene, no JS, no assets.+ cpp: {+ manifest: 'host',+ library: 'libestella_host.so',+ assets: [],+ apk: 'estella-host.apk',+ },+};++// A debug keystore is enough to sideload; Android Studio uses the same one. Create+// it on first use so packaging never stops to ask for credentials.+async function debugKeystore() {+ const home = process.env.HOME || process.env.USERPROFILE || '';+ const keystore = path.join(home, '.android', 'debug.keystore');+ if (existsSync(keystore)) return keystore;+ logger.step('Creating the Android debug keystore...');+ await mkdir(path.dirname(keystore), { recursive: true });+ await runCommand('keytool', [+ '-genkeypair', '-keystore', keystore, '-storepass', 'android', '-keypass', 'android',+ '-alias', 'androiddebugkey', '-keyalg', 'RSA', '-keysize', '2048', '-validity', '10000',+ '-dname', 'CN=Android Debug,O=Android,C=US',+ ]);+ return keystore;+}++// APKs are zips; `jar` ships with the JDK that apksigner already requires, so it+// is the one archiver we can count on wherever packaging runs.+async function addToApk(apk, stagingDir) {+ await runCommand('jar', ['ufM', apk, '-C', stagingDir, 'lib']);+}++export async function packageNativeApk(options = {}) {+ const hostKey = (options.host || 'js').toLowerCase();+ const host = HOSTS[hostKey];+ if (!host) throw new Error(`Unknown --host ${hostKey} (expected js or cpp).`);++ const rootDir = config.paths.root;+ const buildDir = path.join(rootDir, 'build-native');+ const library = path.join(buildDir, host.library);+ if (!existsSync(library)) {+ throw new Error(`${host.library} not found in build-native/. Build it first: `+ + `node build-tools/cli.js native${hostKey === 'js' ? ' --quickjs <dir>' : ''} --dawn <src> --dawn-build <build>.`);+ }++ const dawnBuild = options.dawnBuild || process.env.ESTELLA_DAWN_BUILD;+ if (!dawnBuild) throw new Error('Pass --dawn-build <dir> (or set ESTELLA_DAWN_BUILD) — the APK ships libwebgpu_dawn.so.');+ const dawnLib = path.join(dawnBuild, 'src', 'dawn', 'native', 'libwebgpu_dawn.so');+ if (!existsSync(dawnLib)) throw new Error(`Dawn library not found: ${dawnLib}.`);++ const sdk = requireSdk();+ const ndk = requireNdk(sdk);+ const abi = options.abi || 'arm64-v8a';+ const platform = options.platform || 'android-33';++ const staging = path.join(buildDir, `apk-${hostKey}`);+ const libDir = path.join(staging, 'lib', abi);+ await rm(staging, { recursive: true, force: true });+ await mkdir(libDir, { recursive: true });++ logger.step('Staging the native libraries...');+ await copyFile(library, path.join(libDir, host.library));+ await copyFile(ndkLibcxxShared(ndk), path.join(libDir, 'libc++_shared.so'));+ // Dawn carries debug info an APK does not need — it dominates the payload.+ await runCommand(ndkTool(ndk, 'llvm-strip'), [+ '--strip-all', '-o', path.join(libDir, 'libwebgpu_dawn.so'), dawnLib,+ ]);++ let assetsDir = null;+ if (host.assets.length) {+ assetsDir = path.join(staging, 'assets');+ await mkdir(assetsDir, { recursive: true });+ for (const asset of host.assets) {+ await copyFile(path.join(rootDir, 'native', 'js', asset), path.join(assetsDir, asset));+ }+ }++ const unsigned = path.join(staging, 'unsigned.apk');+ const aligned = path.join(buildDir, host.apk);+ logger.step('Linking resources (aapt2)...');+ await runCommand(buildTool(sdk, 'aapt2'), [+ 'link',+ '--manifest', path.join(rootDir, 'native', 'android', host.manifest, 'AndroidManifest.xml'),+ '-I', platformJar(sdk, platform),+ ...(assetsDir ? ['-A', assetsDir] : []),+ '-o', unsigned,+ ]);++ logger.step('Adding the native libraries...');+ await addToApk(unsigned, staging);++ logger.step('Aligning + signing...');+ await rm(aligned, { force: true });+ await runCommand(buildTool(sdk, 'zipalign'), ['-f', '4', unsigned, aligned]);+ const keystore = options.keystore || await debugKeystore();+ await runCommand(buildTool(sdk, 'apksigner'), [+ 'sign', '--ks', keystore,+ ...(options.keystore ? [] : ['--ks-pass', 'pass:android', '--key-pass', 'pass:android',+ '--ks-key-alias', 'androiddebugkey']),+ aligned,+ ]);++ logger.success(`APK: ${path.relative(rootDir, aligned)}`);+ logger.info('Install it with: adb install -r ' + path.relative(rootDir, aligned));+}diff --git a/build-tools/utils/android.js b/build-tools/utils/android.jsnew file mode 100644index 000000000..8e1ecd35d--- /dev/null+++ b/build-tools/utils/android.js@@ -0,0 +1,90 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// Locating the Android toolchain — the SDK, its build-tools, a platform jar and+// the NDK bits the native host build and the APK packaging both need. Nothing is+// hardcoded per machine: everything hangs off ANDROID_HOME or Android Studio's+// default install.++import path from 'path';+import { existsSync, readdirSync } from 'fs';++export function androidSdk() {+ const sdk = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT;+ if (sdk && existsSync(sdk)) return sdk;+ // Android Studio's default install location.+ const dflt = path.join(process.env.LOCALAPPDATA || process.env.HOME || '', 'Android', 'Sdk');+ return existsSync(dflt) ? dflt : null;+}++/** The lexicographically newest entry in @p dir — SDK components are versioned by name. */+export function newest(dir) {+ if (!existsSync(dir)) return null;+ const entries = readdirSync(dir).sort();+ return entries.length ? path.join(dir, entries[entries.length - 1]) : null;+}++export function requireSdk() {+ const sdk = androidSdk();+ if (!sdk) throw new Error('Android SDK not found. Set ANDROID_HOME (install via Android Studio).');+ return sdk;+}++export function requireNdk(sdk) {+ const ndk = newest(path.join(sdk, 'ndk'));+ if (!ndk) throw new Error(`No NDK under ${sdk}/ndk. Install one via Android Studio's SDK Manager.`);+ return ndk;+}++const exe = process.platform === 'win32' ? '.exe' : '';++/** aapt2 / zipalign / apksigner, from the newest installed build-tools. */+export function buildTool(sdk, name) {+ const dir = newest(path.join(sdk, 'build-tools'));+ if (!dir) throw new Error(`No build-tools under ${sdk}/build-tools. Install them via the SDK Manager.`);+ // apksigner is a script (.bat on Windows), the rest are native binaries.+ const suffix = name === 'apksigner' ? (process.platform === 'win32' ? '.bat' : '') : exe;+ const tool = path.join(dir, name + suffix);+ if (!existsSync(tool)) throw new Error(`${name} not found at ${tool}.`);+ return tool;+}++/** The android.jar aapt2 links against; falls back to the newest installed platform. */+export function platformJar(sdk, platform) {+ const wanted = path.join(sdk, 'platforms', platform, 'android.jar');+ if (existsSync(wanted)) return wanted;+ const newestPlatform = newest(path.join(sdk, 'platforms'));+ const jar = newestPlatform && path.join(newestPlatform, 'android.jar');+ if (!jar || !existsSync(jar)) {+ throw new Error(`No android.jar for ${platform} under ${sdk}/platforms. Install it via the SDK Manager.`);+ }+ return jar;+}++/** The NDK's LLVM toolchain dir — its host tag is the only entry under prebuilt/. */+function llvmPrebuilt(ndk) {+ const prebuilt = path.join(ndk, 'toolchains', 'llvm', 'prebuilt');+ const host = newest(prebuilt);+ if (!host) throw new Error(`No LLVM toolchain under ${prebuilt}.`);+ return host;+}++export function ndkTool(ndk, name) {+ return path.join(llvmPrebuilt(ndk), 'bin', name + exe);+}++/** The shared libc++ an ANDROID_STL=c++_shared build expects inside the APK. */+export function ndkLibcxxShared(ndk, triple = 'aarch64-linux-android') {+ const lib = path.join(llvmPrebuilt(ndk), 'sysroot', 'usr', 'lib', triple, 'libc++_shared.so');+ if (!existsSync(lib)) throw new Error(`libc++_shared.so not found at ${lib}.`);+ return lib;+}++/** Prefer the NDK-bundled CMake (>= 3.22, ships ninja) over whatever is on PATH —+ * CMake 4.x rejects the pre-3.5 minimums in some transitive deps. */+export function sdkCmake(sdk) {+ const cmakeRoot = newest(path.join(sdk, 'cmake'));+ if (!cmakeRoot) return { cmake: 'cmake', ninja: null };+ const bin = path.join(cmakeRoot, 'bin');+ return { cmake: path.join(bin, 'cmake' + exe), ninja: path.join(bin, 'ninja' + exe) };+}diff --git a/native/README.md b/native/README.mdindex 529598b4d..0c5d55d94 100644--- a/native/README.md+++ b/native/README.md@@ -22,6 +22,7 @@ This directory holds two reference hosts + the build recipe:`eshost::Platform`.- `js/main_android.cpp` — NativeActivity, APK assets, Vulkan, the ALooper loop.- `js/main_ios.mm` — a CAMetalLayer view, bundle assets, Metal, CADisplayLink.+- **`android/`** — the APK manifests (`host/`, `js/`), packaged by `--package`.- **`ios/`** — the Xcode app shell (xcodegen) that signs and packages the iOSbuild. It is only an entry point; the app lives in the static library.@@ -87,10 +88,21 @@ Paths may also come from `ESTELLA_DAWN_DIR` / `ESTELLA_DAWN_BUILD` /`ESTELLA_QUICKJS_DIR`. Outputs: `build-native/libestella_host.so`, and with`--quickjs`, `build-native/libestella_js_host.so`.-Package the APK by hand (no gradle): `aapt2 link` the matching manifest-(`host/` or `js/AndroidManifest.xml`), inject-`lib/arm64-v8a/{libestella*_host.so,libwebgpu_dawn.so,libc++_shared.so}` (strip-Dawn with `llvm-strip`), `zipalign -f 4`, `apksigner sign`.+**Package a signed APK** by adding `--package` — the Android counterpart of what+Xcode does for `native/ios`, and still no gradle (a NativeActivity has no Java):++```sh+node build-tools/cli.js native --dawn "$DAWN" --dawn-build "$DAWN/out-android" \+ --quickjs "$QJS" --package # --host cpp for the smoke-test APK+adb install -r build-native/estella-js-host.apk+```++It runs `aapt2 link` over `native/android/<host>/AndroidManifest.xml`, stages+`lib/arm64-v8a/{libestella*_host.so,libwebgpu_dawn.so,libc++_shared.so}` (Dawn+stripped with the NDK's `llvm-strip`), packs the game and its content into+`assets/` where the host's `readAsset()` looks, then `zipalign -f 4` and+`apksigner sign`. Signing uses the Android debug keystore — created on first use —+unless you pass `--keystore`.## Build (iOS arm64)diff --git a/native/host/AndroidManifest.xml b/native/android/host/AndroidManifest.xmlsimilarity index 100%rename from native/host/AndroidManifest.xmlrename to native/android/host/AndroidManifest.xmldiff --git a/native/js/AndroidManifest.xml b/native/android/js/AndroidManifest.xmlsimilarity index 100%rename from native/js/AndroidManifest.xmlrename to native/android/js/AndroidManifest.xml