Skip to content

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.

feat(android): export the project, not only the package

yhhdc2455825b10
diff --git a/build-tools/utils/gradleProject.d.ts b/build-tools/utils/gradleProject.d.ts
new file mode 100644
index 000000000..f13f178ae
--- /dev/null
+++ b/build-tools/utils/gradleProject.d.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Types for gradleProject.js — the module is plain ESM so the CLI can run it
+// unbuilt, and this is how the editor's TypeScript sees it. The Android side of
+// iosProject.d.ts, down to the shape.
+
+/**
+ * The prebuilt pieces a project is wrapped around, named directory by directory:
+ * they come from a runtime template, whose layout table is the only thing that
+ * knows where they sit inside it (see nativeTemplate.js).
+ */
+export interface AndroidProjectSources {
+ /** The engine's shared libraries, one directory per ABI. */
+ libs: string;
+ /** The host's Java shim, as source — what the project compiles. */
+ java: string;
+ /** The manifest template the app's identity is substituted into. */
+ manifestIn: string;
+ /** The template's default launcher icon, used when the project sets none. */
+ icon: string;
+ /** Precompiled SDK bytecode, if the template carries it. */
+ bytecode?: string;
+}
+
+export interface AndroidAppIdentity {
+ id: string;
+ name: string;
+ version: string;
+ versionCode: number;
+ orientation: 'landscape' | 'portrait';
+}
+
+/** The manifest a Gradle build wants, plus the SDK levels it took out of it. */
+export function gradleManifest(
+ templateXml: string,
+ app: AndroidAppIdentity,
+): { xml: string; minSdk: number; targetSdk: number };
+
+export function renderSettingsGradle(name: string): string;
+export function renderRootGradle(): string;
+export function renderAppGradle(o: {
+ appId: string;
+ version: string;
+ versionCode: number;
+ minSdk: number;
+ targetSdk: number;
+ abis: string[];
+}): string;
+export function renderGradleProperties(): string;
+export function renderProjectReadme(o: { name: string; abis: string[] }): string;
+export function renderGitignore(): string;
+
+export function emitAndroidGradleProject(
+ contentDir: string,
+ app: AndroidAppIdentity,
+ sources: AndroidProjectSources,
+ icon?: Buffer,
+): Promise<string>;
diff --git a/build-tools/utils/gradleProject.js b/build-tools/utils/gradleProject.js
new file mode 100644
index 000000000..6c0a84135
--- /dev/null
+++ b/build-tools/utils/gradleProject.js
@@ -0,0 +1,299 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The Android Studio project an Android export ships, written directly — the
+// Android side of iosProject.js, and the same bargain: the runtime template
+// carries the engine's compiled half, the export carries the game, and what the
+// user opens is an ordinary project of their platform's own kind.
+//
+// It exists because an APK is a dead end for anyone who needs to add an SDK, a
+// permission, a service or their own Activity. The one-click package stays for
+// everyone who does not.
+
+import { cp, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { fillTemplate, androidScreenOrientation } from './nativeApp.js';
+
+/** Android Gradle Plugin the emitted project asks for. */
+const AGP_VERSION = '8.7.3';
+/** compileSdk. min/target come from the manifest template, which owns them. */
+const COMPILE_SDK = 34;
+
+/** The Gradle project's own files, which are never mistaken for game content. */
+const PROJECT_ENTRIES = [
+ 'app', 'settings.gradle.kts', 'build.gradle.kts', 'gradle.properties',
+ 'gradle', 'gradlew', 'gradlew.bat', 'README.md', '.gitignore',
+];
+
+/** A Gradle project name (and Android Studio window title) that needs no quoting. */
+function projectName(appName) {
+ return appName.replace(/[^A-Za-z0-9]+/g, '') || 'EstellaGame';
+}
+
+/**
+ * Turn the packaging manifest template into the one a Gradle build wants.
+ *
+ * Same file, same substitutions, so the manifest an APK carries and the manifest
+ * a project builds are the same document. What differs is where identity lives:
+ * AGP 8 rejects `package` and the version attributes in a manifest and reads them
+ * from the build script, and it ignores `<uses-sdk>` in favour of the same. So
+ * those move out — and their values move INTO the build script rather than being
+ * restated, which is why they are returned here.
+ *
+ * @returns {{xml: string, minSdk: number, targetSdk: number}}
+ */
+export function gradleManifest(templateXml, app) {
+ const filled = fillTemplate(templateXml, {
+ APP_ID: app.id,
+ APP_NAME: app.name,
+ VERSION_NAME: app.version,
+ VERSION_CODE: app.versionCode,
+ SCREEN_ORIENTATION: androidScreenOrientation(app.orientation),
+ // A project compiles the Java shim from source, so there is always code.
+ HAS_CODE: 'true',
+ });
+
+ const minSdk = Number(/android:minSdkVersion="(\d+)"/.exec(filled)?.[1] ?? 26);
+ const targetSdk = Number(/android:targetSdkVersion="(\d+)"/.exec(filled)?.[1] ?? 33);
+
+ const xml = filled
+ // Horizontal whitespace only: `\s*` also eats the next line's indent, which
+ // pulls the element after it onto the manifest tag's own line.
+ .replace(/^[^\S\n]*<uses-sdk[^>]*\/>[^\S\n]*\r?\n/m, '')
+ // The line ending goes with the line: a template with CRLF would otherwise
+ // leave its `\r` behind on the tag these were removed from.
+ .replace(/\r?\n[^\S\n]*package="[^"]*"/, '')
+ .replace(/\r?\n[^\S\n]*android:versionCode="[^"]*"/, '')
+ .replace(/\r?\n[^\S\n]*android:versionName="[^"]*"/, '');
+
+ return { xml, minSdk, targetSdk };
+}
+
+/** `settings.gradle.kts` — where the plugin and its dependencies come from. */
+export function renderSettingsGradle(name) {
+ return `pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+rootProject.name = "${name}"
+include(":app")
+`;
+}
+
+/** The root build script: declares the plugin, applies it in :app. */
+export function renderRootGradle() {
+ return `plugins {
+ id("com.android.application") version "${AGP_VERSION}" apply false
+}
+`;
+}
+
+/**
+ * `app/build.gradle.kts` — the file a game edits.
+ *
+ * Identity, SDK levels and the ABI filter live here because AGP owns them; the
+ * engine's prebuilt libraries are picked up from jniLibs by convention, so
+ * nothing here has to name them.
+ */
+export function renderAppGradle(o) {
+ const abis = o.abis.map((abi) => `"${abi}"`).join(', ');
+ return `plugins {
+ id("com.android.application")
+}
+
+android {
+ namespace = "${o.appId}"
+ compileSdk = ${COMPILE_SDK}
+
+ defaultConfig {
+ applicationId = "${o.appId}"
+ minSdk = ${o.minSdk}
+ targetSdk = ${o.targetSdk}
+ versionCode = ${o.versionCode}
+ versionName = "${o.version}"
+
+ // The engine ships as prebuilt libraries under src/main/jniLibs; this is
+ // the set of architectures they were built for.
+ ndk {
+ abiFilters += listOf(${abis})
+ }
+ }
+
+ // The host maps its libraries out of the installed package, which is also what
+ // lets an App Bundle split them per device.
+ packaging {
+ jniLibs {
+ useLegacyPackaging = false
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = false
+ // Add a signingConfig here to build an upload-ready release. Until then
+ // \`assembleRelease\` produces an unsigned APK and \`assembleDebug\` a
+ // debug-signed one that installs on a device.
+ }
+ }
+}
+
+dependencies {
+ // Your SDKs go here — this project is an ordinary Android application.
+}
+`;
+}
+
+export function renderGradleProperties() {
+ return `org.gradle.jvmargs=-Xmx2048m
+android.useAndroidX=true
+android.nonTransitiveRClass=true
+`;
+}
+
+export function renderProjectReadme(o) {
+ return `# ${o.name}
+
+An Android Studio project exported from Estella. Open this folder in Android
+Studio (or run \`gradle :app:assembleDebug\`) — no Android SDK setup beyond the
+one Studio installs, and no Estella toolchain.
+
+## What is here
+
+ app/src/main/assets/ the exported game: cooked content + its configs
+ app/src/main/jniLibs/ the engine, prebuilt for ${o.abis.join(' and ')}
+ app/src/main/java/ the host's Java shim (the IME side of a text field)
+ app/src/main/res/ the launcher icon
+ app/src/main/AndroidManifest.xml
+ app/build.gradle.kts identity, SDK levels, and where your SDKs go
+
+## Adding an SDK
+
+Add the dependency in \`app/build.gradle.kts\` and whatever the SDK asks of the
+manifest. The game itself is native and starts from \`NativeActivity\`; a Java SDK
+that needs an entry point can subclass it and name the subclass in the manifest.
+
+## Re-exporting
+
+Exporting again from Estella rewrites \`app/src/main/assets\`, the manifest, the
+libraries and the icon — the content, in other words. \`app/build.gradle.kts\` and
+anything else you edit is left alone.
+`;
+}
+
+export function renderGitignore() {
+ return `.gradle/
+build/
+local.properties
+.idea/
+*.iml
+`;
+}
+
+/**
+ * Write the Android Studio project into an export, in place: the export directory
+ * BECOMES the project. The cooked content moves once, into the module's assets —
+ * where Gradle expects it and where the host reads it from the installed package,
+ * so the layout inside an APK is byte-for-byte what the one-click path produces.
+ *
+ * Re-exporting overwrites what the export owns and leaves the build scripts alone,
+ * so a project that has grown an SDK survives its game being rebuilt.
+ *
+ * @param {string} contentDir The export (cooked content + the two configs).
+ * @param {{id: string, name: string, version: string, versionCode: number,
+ * orientation: 'landscape'|'portrait'}} app From `app.config.json`.
+ * @param {{libs: string, java: string, manifestIn: string, icon: string,
+ * bytecode?: string}} sources Out of the installed runtime template.
+ * @param {Buffer} [icon] The launcher icon; the template's default when absent.
+ * @returns {Promise<string>} The project directory, to reveal or open.
+ */
+export async function emitAndroidGradleProject(contentDir, app, sources, icon) {
+ const name = projectName(app.name);
+ const appDir = path.join(contentDir, 'app');
+ const mainDir = path.join(appDir, 'src', 'main');
+ const assetsDir = path.join(mainDir, 'assets');
+
+ const abis = (await readdir(sources.libs, { withFileTypes: true }))
+ .filter((e) => e.isDirectory())
+ .map((e) => e.name)
+ .sort();
+ if (abis.length === 0) {
+ throw new Error(`The runtime template at ${sources.libs} carries no native libraries.`);
+ }
+
+ // Everything the export wrote, before this function adds anything that could be
+ // mistaken for it.
+ const exported = (await readdir(contentDir, { withFileTypes: true }))
+ .filter((e) => !PROJECT_ENTRIES.includes(e.name))
+ .map((e) => e.name);
+
+ // The generated half is rewritten wholesale so a re-export cannot inherit the
+ // last one's assets, libraries or manifest. The build scripts are not in here:
+ // they are the half the user owns.
+ await rm(path.join(mainDir, 'assets'), { recursive: true, force: true });
+ await rm(path.join(mainDir, 'jniLibs'), { recursive: true, force: true });
+ await rm(path.join(mainDir, 'java'), { recursive: true, force: true });
+ await rm(path.join(mainDir, 'res'), { recursive: true, force: true });
+
+ await mkdir(assetsDir, { recursive: true });
+ for (const entry of exported) {
+ await rename(path.join(contentDir, entry), path.join(assetsDir, entry));
+ }
+
+ // The SDK bytecode rides along as an asset, where the host's reader finds it —
+ // without it the first launch after an install spends seconds compiling.
+ if (sources.bytecode && existsSync(sources.bytecode)) {
+ await cp(sources.bytecode, path.join(assetsDir, path.basename(sources.bytecode)));
+ }
+
+ await cp(sources.libs, path.join(mainDir, 'jniLibs'), { recursive: true });
+ if (existsSync(sources.java)) {
+ await cp(sources.java, path.join(mainDir, 'java'), { recursive: true });
+ }
+
+ const manifest = gradleManifest(await readFile(sources.manifestIn, 'utf8'), app);
+ await writeFile(path.join(mainDir, 'AndroidManifest.xml'), manifest.xml);
+
+ const iconDir = path.join(mainDir, 'res', 'mipmap-xxxhdpi');
+ await mkdir(iconDir, { recursive: true });
+ await writeFile(path.join(iconDir, 'ic_launcher.png'), icon ?? await readFile(sources.icon));
+
+ await writeIfAbsent(path.join(appDir, 'build.gradle.kts'), renderAppGradle({
+ appId: app.id,
+ version: app.version,
+ versionCode: app.versionCode,
+ minSdk: manifest.minSdk,
+ targetSdk: manifest.targetSdk,
+ abis,
+ }));
+ await writeIfAbsent(path.join(contentDir, 'settings.gradle.kts'), renderSettingsGradle(name));
+ await writeIfAbsent(path.join(contentDir, 'build.gradle.kts'), renderRootGradle());
+ await writeIfAbsent(path.join(contentDir, 'gradle.properties'), renderGradleProperties());
+ await writeIfAbsent(path.join(contentDir, '.gitignore'), renderGitignore());
+ await writeIfAbsent(path.join(contentDir, 'README.md'), renderProjectReadme({ name, abis }));
+
+ return contentDir;
+}
+
+/** Write a file the user is expected to edit — once, and never over their copy. */
+async function writeIfAbsent(file, contents) {
+ if (existsSync(file)) return;
+ await writeFile(file, contents);
+}
diff --git a/build-tools/utils/nativeTemplate.d.ts b/build-tools/utils/nativeTemplate.d.ts
index 35153fab0..b6ce17ca2 100644
--- a/build-tools/utils/nativeTemplate.d.ts
+++ b/build-tools/utils/nativeTemplate.d.ts
@@ -77,6 +77,21 @@ export const TEMPLATE_INDEX: string;
export function releaseAssetBase(engineVersion: string): string;
export function parseTemplateIndex(doc: unknown, engineVersion?: string): PublishedTemplate[] | null;
export const DEFAULT_ICON: string;
+/** The pieces an exported Android Studio project is assembled from. */
+export function androidTemplateSources(dir: string): {
+ /** The engine's shared libraries, one directory per ABI. */
+ libs: string;
+ /** The host's Java shim, as source. */
+ java: string;
+ /** The same shim precompiled, for the package path that needs no JDK. */
+ dex: string;
+ manifestIn: string;
+ /** The default launcher icon, used when the project sets none. */
+ icon: string;
+ /** Precompiled SDK bytecode, when the template's build machine could produce it. */
+ bytecode: string;
+};
+
export function iosTemplateSources(dir: string): {
xcframework: string;
mainM: string;
diff --git a/build-tools/utils/nativeTemplate.js b/build-tools/utils/nativeTemplate.js
index 0f2f3ebef..5b4a05173 100644
--- a/build-tools/utils/nativeTemplate.js
+++ b/build-tools/utils/nativeTemplate.js
@@ -118,6 +118,14 @@ export function templateLayout(platform, options = {}) {
// of an editable field has to be Java, and a template exists so that no
// user needs a JDK to package.
{ rel: 'classes.dex', produced: true },
+ // The same Java, as source. The dex above is what the one-click package
+ // needs (no JDK on the user's machine); these are what an exported
+ // Android Studio project compiles, and what a game adding its own SDK
+ // extends. One template carries both because both are the same shim.
+ {
+ rel: 'java', kind: 'dir',
+ from: (ctx) => path.join(ctx.root, 'native', 'android', 'java'),
+ },
// Absent is valid — the host falls back to compiling the bundle, at the
// cost of a ~14 s black screen on first launch.
{
@@ -145,6 +153,21 @@ export function requiredTemplateFiles(platform, options) {
* Read off the files rather than the manifest: a template is usable if its files
* are there, and asking the directory is what makes that true by construction.
*/
+/**
+ * The pieces an exported Android Studio project is assembled from, out of an
+ * installed template — the Android side of {@link iosTemplateSources}.
+ */
+export function androidTemplateSources(dir) {
+ return {
+ libs: path.join(dir, 'lib'),
+ java: path.join(dir, 'java'),
+ dex: path.join(dir, 'classes.dex'),
+ manifestIn: path.join(dir, 'AndroidManifest.xml.in'),
+ icon: path.join(dir, DEFAULT_ICON),
+ bytecode: path.join(dir, 'assets', BYTECODE_FILE),
+ };
+}
+
export function templateAbis(dir) {
return ANDROID_ABIS.filter((abi) => existsSync(path.join(dir, 'lib', abi, 'libestella_js_host.so')));
}
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index 453c21028..f55fafc91 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -38,6 +38,8 @@ import type { OnExportProgress } from './exportProgress';
import { ESENGINE_EXTERNAL } from './esengineResolve';
import { orientationCss, orientationOverlayHtml, orientationLockScript, orientationLockCspHash, type ScreenOrientation } from './orientationHtml';
import { emitIosXcodeProject, type IosProjectSources } from '../../build-tools/utils/iosProject.js';
+import { emitAndroidGradleProject } from '../../build-tools/utils/gradleProject.js';
+import { androidTemplateSources } from '../../build-tools/utils/nativeTemplate.js';
import { assembleApk, apkFileName } from '../../build-tools/utils/apk.js';
import { assembleAab, aabFileName } from '../../build-tools/utils/aab.js';
import { debugSigningKey, type SigningKey } from '../../build-tools/utils/androidKeystore.js';
@@ -154,6 +156,9 @@ export interface ExportGameResult {
included: number;
warnings: string[];
errors: string[];
+ /** Android: the generated Gradle project, for the editor to reveal. Absent
+ * unless the export asked for a project (and a template was installed). */
+ androidProject?: string;
/** iOS: the generated `.xcodeproj`, for the editor to open. Absent when no iOS
* runtime template is installed (the export still carries its content). */
xcodeProject?: string;
@@ -432,6 +437,13 @@ export async function exportGame(opts: {
* which carries every architecture it will ship. Omitted (or null) exports
* content only. */
androidTemplate?: string | null;
+ /**
+ * What an Android export produces. 'package' assembles the APK (and the App
+ * Bundle beside it when asked); 'project' writes an Android Studio project the
+ * game is built from instead — the same trade the iOS export has always made,
+ * and the only route for a game that has to add an SDK of its own.
+ */
+ androidOutput?: 'package' | 'project';
/** Android: the identity to sign with. Omitted uses the development key, which
* installs on a device and is refused by every store. */
androidKey?: SigningKey;
@@ -541,6 +553,7 @@ export async function exportGame(opts: {
const errors: string[] = [];
/** iOS: set once the project is written around the content (see below). */
let xcodeProject: string | undefined;
+ let androidProject: string | undefined;
let apkFile: string | undefined;
let aabFile: string | undefined;
await mkdir(payloadDir, { recursive: true });
@@ -694,9 +707,18 @@ export async function exportGame(opts: {
}
if (platform === 'android') {
- progress({ phase: 'Assembling the APK' });
const template = opts.androidTemplate ?? null;
- if (template) {
+ const wantsProject = opts.androidOutput === 'project';
+ if (!template) {
+ warnings.push(`No Android runtime template is installed for this editor version, so no ${
+ wantsProject ? 'project was written' : 'APK was assembled'} — the content is here. `
+ + 'Install one from the Android row in Package Project, then export again.');
+ } else if (wantsProject) {
+ progress({ phase: 'Writing Android Studio project' });
+ androidProject = await emitAndroidGradleProject(
+ absOut, appConfig, androidTemplateSources(template), icon);
+ } else {
+ progress({ phase: 'Assembling the APK' });
const key = opts.androidKey ?? debugSigningKey();
const assembly = { templateDir: template, contentDir: absOut, app: appConfig, key, icon };
apkFile = path.join(absOut, apkFileName(appConfig.id));
@@ -706,10 +728,6 @@ export async function exportGame(opts: {
aabFile = path.join(absOut, aabFileName(appConfig.id));
await writeFile(aabFile, assembleAab(assembly));
}
- } else {
- warnings.push('No Android runtime template is installed for this editor version, so no APK '
- + 'was assembled — the content is here. Install one from the Android row in Package '
- + 'Project, then export again.');
}
}
}
@@ -719,6 +737,7 @@ export async function exportGame(opts: {
return {
ok: errors.length === 0, platform, outDir: absOut, included: cook.included.length,
- warnings, errors, ...(xcodeProject ? { xcodeProject } : {}), ...(apkFile ? { apkFile } : {}), ...(aabFile ? { aabFile } : {}),
+ warnings, errors, ...(xcodeProject ? { xcodeProject } : {}), ...(androidProject ? { androidProject } : {}),
+ ...(apkFile ? { apkFile } : {}), ...(aabFile ? { aabFile } : {}),
};
}
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 49adaa6ed..446b6efbe 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -898,10 +898,12 @@ ipcMain.handle(
// writing a project that cannot link.
iosSources: opts?.platform === 'ios' ? iosSourcesFromTemplate(app.getVersion()) : null,
// Android assembles the APK outright — the template carries everything the
- // package needs, and signing is ours to do.
+ // package needs, and signing is ours to do — or writes a Gradle project from
+ // the same template when the game needs to build it itself.
androidTemplate: opts?.platform === 'android'
? (resolveNativeTemplate('android', app.getVersion())?.dir ?? null)
: null,
+ androidOutput: plat?.android?.output,
onProgress: (p) => e.sender.send('project:exportProgress', p),
});
},
diff --git a/desktop/scripts/export-project.mjs b/desktop/scripts/export-project.mjs
index b01cb383a..509e2928c 100644
--- a/desktop/scripts/export-project.mjs
+++ b/desktop/scripts/export-project.mjs
@@ -23,6 +23,7 @@ import path from 'node:path';
import { existsSync, readFileSync, mkdtempSync, rmSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
+import { installedTemplateDir } from '../../build-tools/utils/nativeTemplate.js';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const DESKTOP = path.join(HERE, '..');
@@ -31,7 +32,8 @@ const REPO = path.join(DESKTOP, '..');
function parseArgs(argv) {
const [projectDir, ...rest] = argv;
if (!projectDir) {
- console.error('usage: node desktop/scripts/export-project.mjs <projectDir> [--platform android] [--out dir]');
+ console.error('usage: node desktop/scripts/export-project.mjs <projectDir> '
+ + '[--platform android] [--out dir] [--output package|project] [--template dir]');
process.exit(2);
}
const opts = { projectDir: path.resolve(projectDir), platform: 'android' };
@@ -109,6 +111,16 @@ const scriptsEntry = opts.scripts ?? (existsSync(path.join(opts.projectDir, 'src
? 'src/main.ts' : undefined);
const outDir = path.resolve(opts.out ?? path.join(opts.projectDir, `dist-${platform}`));
+
+// The native half the editor resolves through the installed-template store. Named
+// explicitly with --template, else looked up the way the editor does, so a headless
+// export assembles the same package the dialog would rather than content alone.
+const engineVersion = JSON.parse(readFileSync(path.join(DESKTOP, 'package.json'), 'utf8')).version;
+const androidTemplate = platform === 'android'
+ ? (opts.template
+ ? path.resolve(opts.template)
+ : firstExisting([installedTemplateDir(engineVersion, 'android')]) ?? null)
+ : null;
const { exportGame, cleanup } = await loadExportGame();
let code = 1;
try {
@@ -123,6 +135,8 @@ try {
platform,
title: opts.title ?? project.name ?? path.basename(opts.projectDir),
orientation: project.orientation ?? 'landscape',
+ androidTemplate,
+ androidOutput: opts.output === 'project' ? 'project' : undefined,
});
console.log(JSON.stringify({ ...result, outDir }, null, 2));
code = result.ok ? 0 : 1;
diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsx
index bd00ecc67..67fbcab94 100644
--- a/desktop/src/components/BuildDialog.tsx
+++ b/desktop/src/components/BuildDialog.tsx
@@ -55,6 +55,8 @@ interface Result {
errors: string[];
/** iOS: the .xcodeproj the export wrote around its content. */
xcodeProject?: string;
+ /** Android: the Gradle project the export wrote around its content. */
+ androidProject?: string;
/** Android: the signed APK the export assembled. */
apkFile?: string;
/** Android: the App Bundle, when the project asked for one. */
@@ -220,6 +222,8 @@ export function BuildDialog() {
// The Play upload format, beside the installable APK. A per-build decision that
// the project remembers, like the ad network above.
const [appBundle, setAppBundle] = useState(saved.platforms?.android?.appBundle ?? false);
+ const [androidOutput, setAndroidOutput] = useState<'package' | 'project'>(
+ saved.platforms?.android?.output ?? 'package');
const [adNetworks, setAdNetworks] = useState<PlayableNetworkOption[]>([]);
const [advOpen, setAdvOpen] = useState(false);
const [copiedFix, setCopiedFix] = useState(false);
@@ -478,7 +482,7 @@ export function BuildDialog() {
// manifest, so a race here would package for the previous one.
if (platform === 'playable') await ProjectStore.setPlatformPackaging('playable', { network: adNetwork });
// Same reason: the export reads the bundle choice from the manifest.
- if (platform === 'android') await ProjectStore.setPlatformPackaging('android', { appBundle });
+ if (platform === 'android') await ProjectStore.setPlatformPackaging('android', { appBundle, output: androidOutput });
// 'auto' → honor each asset's Import Settings (the cook then reads per-asset
// texture/audio compression + Max Size); 'skip' → ship everything raw.
const compress = assetCompression === 'auto';
@@ -734,10 +738,28 @@ export function BuildDialog() {
<Group title={t('build.secBuild')}>
{platform === 'android' && (
- <label className="build__opt" title={t('build.appBundleTip')}>
- <input type="checkbox" checked={appBundle} onChange={(e) => setAppBundle(e.target.checked)} />
- {t('build.appBundle')}
- </label>
+ <>
+ <div className="build__row">
+ <span className="build__label" title={t('build.androidOutputTip')}>{t('build.androidOutput')}</span>
+ <Select
+ ariaLabel={t('build.androidOutput')}
+ value={androidOutput}
+ options={[
+ { value: 'package', label: t('build.androidOutput.package') },
+ { value: 'project', label: t('build.androidOutput.project') },
+ ]}
+ onChange={(v) => setAndroidOutput(v as 'package' | 'project')}
+ />
+ </div>
+ {/* An App Bundle is a second FORMAT of the package; a project builds
+ whichever format its own Gradle build is asked for. */}
+ {androidOutput === 'package' && (
+ <label className="build__opt" title={t('build.appBundleTip')}>
+ <input type="checkbox" checked={appBundle} onChange={(e) => setAppBundle(e.target.checked)} />
+ {t('build.appBundle')}
+ </label>
+ )}
+ </>
)}
{platform === 'playable' && (
<>
@@ -920,6 +942,8 @@ export function BuildDialog() {
<div className="build__next selectable">
{result.xcodeProject
? t('build.next.iosProject')
+ : result.androidProject
+ ? t('build.next.androidProject')
: result.apkFile
? (result.aabFile
? t('build.next.apkAab', { apk: result.apkFile, aab: result.aabFile })
@@ -940,6 +964,11 @@ export function BuildDialog() {
<ExternalLink size={13} /> {t('build.openXcode')}
</Button>
)}
+ {result.androidProject && (
+ <Button variant="primary" onClick={() => void window.estella.shell?.openPath?.(result.androidProject!)}>
+ <FolderOpen size={13} /> {t('build.openAndroidProject')}
+ </Button>
+ )}
{result.apkFile && (
<Button variant="primary" onClick={() => void window.estella.shell?.showItem?.(result.apkFile!)}>
<FolderOpen size={13} /> {t('build.showApk')}
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index e786e868c..513d9d528 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -171,6 +171,18 @@ export const projectMessages = defineMessages({
en: 'Also write the upload format Google Play requires for new apps, beside the installable APK. A bundle cannot be installed on a device — Play builds the APKs from it.',
zh: '在可安装的 APK 之外,另写一份 Google Play 对新应用强制要求的上传格式。bundle 无法直接装到设备上——Play 会用它生成各机型的 APK。',
},
+ 'build.androidOutput': { en: 'Package as', zh: '打包为' },
+ 'build.androidOutputTip': {
+ en: 'A package installs on a device with nothing else installed. A project is an ordinary Android Studio project — the route for a game that has to add an SDK, a permission or an Activity of its own, and build and sign the package itself.',
+ zh: '「安装包」什么都不用装就能直接装到设备上。「工程」是一个普通的 Android Studio 工程——需要接自己的 SDK、加权限或加 Activity、自己构建和签名的游戏走这条路。',
+ },
+ 'build.androidOutput.package': { en: 'Installable package (.apk)', zh: '安装包(.apk)' },
+ 'build.androidOutput.project': { en: 'Android Studio project', zh: 'Android Studio 工程' },
+ 'build.next.androidProject': {
+ en: 'The Android Studio project is written — open the folder in Android Studio and Run. Your SDKs go in app/build.gradle.kts; re-exporting rewrites the game and leaves that file alone.',
+ zh: 'Android Studio 工程已写好——用 Android Studio 打开该文件夹后直接运行。你的 SDK 加在 app/build.gradle.kts 里;重新导出只会覆盖游戏内容,不动这个文件。',
+ },
+ 'build.openAndroidProject': { en: 'Open project folder', zh: '打开工程文件夹' },
'build.next.ios': {
en: 'The content is in {out}. Install the iOS runtime template to get an Xcode project written around it.',
zh: '内容已写入 {out}。安装 iOS 运行时模板后,导出会围绕它写出 Xcode 工程。',
diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.ts
index 601d7111b..5903de4ea 100644
--- a/desktop/src/project/format.ts
+++ b/desktop/src/project/format.ts
@@ -130,6 +130,16 @@ export interface DesktopPackaging { appId?: string; productName?: string; }
export interface AndroidPackaging {
appId?: string;
versionCode?: number;
+ /**
+ * What the export produces: the installable package, or an Android Studio
+ * project the game is built from.
+ *
+ * A package is the shorter path and needs nothing installed; a project is the
+ * only one that can carry an SDK, a permission or an Activity of the game's own
+ * — the same choice the iOS export makes for you, made explicit here because
+ * Android can do both.
+ */
+ output?: 'package' | 'project';
/**
* Also write the Google Play upload format (`.aab`) beside the `.apk`.
*
diff --git a/desktop/tests/android-project.test.ts b/desktop/tests/android-project.test.ts
new file mode 100644
index 000000000..9a591a5e7
--- /dev/null
+++ b/desktop/tests/android-project.test.ts
@@ -0,0 +1,169 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The Android Studio project an export writes, checked as the two things it has to
+// be: a project Gradle can build (identity where AGP reads it, libraries and assets
+// where the conventions put them), and a project a game can OWN — re-exporting
+// refreshes the game and leaves the build script the game edited alone.
+//
+// The APK path is covered next door; what is unique here is that this output is
+// source, so it is read as text rather than validated by a packaging tool.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { emitAndroidGradleProject, gradleManifest } from '../../build-tools/utils/gradleProject.js';
+import { androidTemplateSources } from '../../build-tools/utils/nativeTemplate.js';
+
+const REPO = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
+const MANIFEST_TEMPLATE = path.join(REPO, 'native', 'android', 'host', 'AndroidManifest.xml.in');
+const DEFAULT_ICON_SOURCE = path.join(REPO, 'native', 'icon.png');
+
+const APP = {
+ id: 'com.example.demo', name: 'My Game', version: '1.2', versionCode: 7,
+ orientation: 'portrait' as const,
+};
+
+let scratch: string;
+let templateDir: string;
+let contentDir: string;
+
+beforeEach(() => {
+ scratch = mkdtempSync(path.join(tmpdir(), 'es-agp-'));
+
+ templateDir = path.join(scratch, 'template');
+ mkdirSync(path.join(templateDir, 'lib', 'arm64-v8a'), { recursive: true });
+ mkdirSync(path.join(templateDir, 'lib', 'x86_64'), { recursive: true });
+ mkdirSync(path.join(templateDir, 'java', 'com', 'estella', 'host'), { recursive: true });
+ mkdirSync(path.join(templateDir, 'assets'), { recursive: true });
+ writeFileSync(path.join(templateDir, 'AndroidManifest.xml.in'), readFileSync(MANIFEST_TEMPLATE));
+ writeFileSync(path.join(templateDir, 'icon.png'), readFileSync(DEFAULT_ICON_SOURCE));
+ writeFileSync(path.join(templateDir, 'classes.dex'), Buffer.from('dex\n035\0stand-in'));
+ for (const abi of ['arm64-v8a', 'x86_64']) {
+ writeFileSync(path.join(templateDir, 'lib', abi, 'libestella_js_host.so'), Buffer.alloc(1024, 7));
+ writeFileSync(path.join(templateDir, 'lib', abi, 'libwebgpu_dawn.so'), Buffer.alloc(1024, 9));
+ }
+ writeFileSync(path.join(templateDir, 'java', 'com', 'estella', 'host', 'TextEditor.java'),
+ 'package com.estella.host;\npublic class TextEditor {}\n');
+ writeFileSync(path.join(templateDir, 'assets', 'esengine.native.qjsbc'), Buffer.alloc(64, 3));
+
+ contentDir = path.join(scratch, 'dist-android');
+ mkdirSync(path.join(contentDir, 'assets', 'scenes'), { recursive: true });
+ writeFileSync(path.join(contentDir, 'game.config.json'), '{"entryScene":"main"}');
+ writeFileSync(path.join(contentDir, 'app.config.json'), '{"id":"com.example.demo"}');
+ writeFileSync(path.join(contentDir, 'assets/scenes/main.esscene'), '{"entities":[]}');
+});
+
+afterEach(() => rmSync(scratch, { recursive: true, force: true }));
+
+const emit = () => emitAndroidGradleProject(contentDir, APP, androidTemplateSources(templateDir));
+const read = (...rel: string[]) => readFileSync(path.join(contentDir, ...rel), 'utf8');
+const has = (...rel: string[]) => existsSync(path.join(contentDir, ...rel));
+
+describe('the Android Studio project an export writes', () => {
+ it('puts the game where Gradle and the host both look: src/main/assets', async () => {
+ await emit();
+
+ expect(has('app', 'src', 'main', 'assets', 'game.config.json')).toBe(true);
+ expect(has('app', 'src', 'main', 'assets', 'assets', 'scenes', 'main.esscene')).toBe(true);
+ // Moved, not copied — the export directory IS the project, and a second copy
+ // of the content would ship in the APK twice.
+ expect(has('game.config.json')).toBe(false);
+ });
+
+ it('carries the engine, the Java shim and the icon out of the template', async () => {
+ await emit();
+
+ for (const abi of ['arm64-v8a', 'x86_64']) {
+ expect(has('app', 'src', 'main', 'jniLibs', abi, 'libestella_js_host.so')).toBe(true);
+ expect(has('app', 'src', 'main', 'jniLibs', abi, 'libwebgpu_dawn.so')).toBe(true);
+ }
+ expect(has('app', 'src', 'main', 'java', 'com', 'estella', 'host', 'TextEditor.java')).toBe(true);
+ expect(has('app', 'src', 'main', 'res', 'mipmap-xxxhdpi', 'ic_launcher.png')).toBe(true);
+ // The precompiled bundle rides along as an asset, or the first launch after
+ // an install spends seconds compiling it.
+ expect(has('app', 'src', 'main', 'assets', 'esengine.native.qjsbc')).toBe(true);
+ });
+
+ it('moves identity out of the manifest, which AGP 8 requires, and into Gradle', async () => {
+ await emit();
+ const manifest = read('app', 'src', 'main', 'AndroidManifest.xml');
+ const gradle = read('app', 'build.gradle.kts');
+
+ // AGP rejects a manifest that declares these, and ignores <uses-sdk>.
+ expect(manifest).not.toMatch(/\bpackage=/);
+ expect(manifest).not.toMatch(/android:versionCode=/);
+ expect(manifest).not.toMatch(/android:versionName=/);
+ expect(manifest).not.toContain('<uses-sdk');
+ // Removing a line must not pull the next element onto the one before it.
+ expect(manifest).toMatch(/<manifest xmlns:android="[^"]+">\r?\n\s+<uses-feature/);
+
+ // What stays is the host: label, orientation, the Vulkan requirement, and
+ // hasCode — true here, because a project compiles the shim from source.
+ expect(manifest).toContain('android:label="My Game"');
+ expect(manifest).toContain('android:screenOrientation="sensorPortrait"');
+ expect(manifest).toContain('android:hasCode="true"');
+
+ expect(gradle).toContain('applicationId = "com.example.demo"');
+ expect(gradle).toContain('namespace = "com.example.demo"');
+ expect(gradle).toContain('versionCode = 7');
+ expect(gradle).toContain('versionName = "1.2"');
+ // Taken from the manifest template rather than restated, so the two agree.
+ expect(gradle).toContain('minSdk = 26');
+ expect(gradle).toContain('targetSdk = 33');
+ });
+
+ it('filters to the architectures the template actually carries', async () => {
+ rmSync(path.join(templateDir, 'lib', 'x86_64'), { recursive: true, force: true });
+ await emit();
+
+ const gradle = read('app', 'build.gradle.kts');
+ expect(gradle).toContain('abiFilters += listOf("arm64-v8a")');
+ expect(gradle).not.toContain('x86_64');
+ });
+
+ it('is a Gradle project: settings, root script, properties', async () => {
+ await emit();
+
+ expect(read('settings.gradle.kts')).toContain('include(":app")');
+ expect(read('settings.gradle.kts')).toContain('rootProject.name = "MyGame"');
+ expect(read('build.gradle.kts')).toContain('com.android.application');
+ expect(read('gradle.properties')).toContain('org.gradle.jvmargs');
+ expect(has('README.md')).toBe(true);
+ expect(has('.gitignore')).toBe(true);
+ });
+
+ it('re-exporting refreshes the game and keeps what the game owns', async () => {
+ await emit();
+
+ // What a game does the moment it needs an SDK.
+ const buildScript = path.join(contentDir, 'app', 'build.gradle.kts');
+ writeFileSync(buildScript, `${readFileSync(buildScript, 'utf8')}\n// implementation("com.ads:sdk:1.0")\n`);
+ // A stale asset from the previous export, and a fresh one to replace it.
+ writeFileSync(path.join(contentDir, 'app', 'src', 'main', 'assets', 'gone.json'), '{}');
+ mkdirSync(path.join(contentDir, 'assets'), { recursive: true });
+ writeFileSync(path.join(contentDir, 'game.config.json'), '{"entryScene":"second"}');
+
+ await emit();
+
+ expect(read('app', 'build.gradle.kts')).toContain('com.ads:sdk:1.0');
+ expect(read('app', 'src', 'main', 'assets', 'game.config.json')).toContain('second');
+ expect(has('app', 'src', 'main', 'assets', 'gone.json')).toBe(false);
+ });
+
+ it('refuses a template with no native libraries rather than writing a project that cannot run', async () => {
+ rmSync(path.join(templateDir, 'lib'), { recursive: true, force: true });
+ mkdirSync(path.join(templateDir, 'lib'), { recursive: true });
+
+ await expect(emit()).rejects.toThrow(/no native libraries/);
+ });
+});
+
+describe('gradleManifest', () => {
+ it('reads the SDK levels it strips, so the build script can state them', () => {
+ const { minSdk, targetSdk } = gradleManifest(readFileSync(MANIFEST_TEMPLATE, 'utf8'), APP);
+ expect(minSdk).toBe(26);
+ expect(targetSdk).toBe(33);
+ });
+});
diff --git a/docs/astro/src/content/docs/guides/mobile.mdx b/docs/astro/src/content/docs/guides/mobile.mdx
index 796d99473..a757bb1c4 100644
--- a/docs/astro/src/content/docs/guides/mobile.mdx
+++ b/docs/astro/src/content/docs/guides/mobile.mdx
@@ -41,7 +41,13 @@ package the way `dist-web/` is.
| Export output | `dist-android/` | `dist-ios/` |
| Assembled by | the editor (no Android SDK) | the editor, then Xcode |
| Assembly host OS | any desktop OS | **macOS only** |
-| Result | a signed `.apk` | an Xcode project you open, sign and run |
+| Result | a signed `.apk`, **or** an Android Studio project | an Xcode project you open, sign and run |
+
+Android offers both because it can: the editor assembles a package outright, and it
+can also write the Gradle project that package would have been built from. Pick the
+project under **Output** in the Android section when the game needs to add an SDK, a
+permission or an Activity of its own — that is the same shape iOS has always had,
+where Xcode does the assembling.
## Prerequisites
@@ -106,6 +112,13 @@ folder holds the finished app:
the export writes one beside the APK. Play has required a bundle rather than an
APK for new apps since 2021 — it is the upload format, and cannot be installed on
a device, which is why the APK is still what you test with.
+- **Android, with *Output* set to *Android Studio project*** — an ordinary Gradle
+ project instead of a package: your content under `app/src/main/assets`, the engine
+ under `app/src/main/jniLibs`, the host's Java shim as source, and an
+ `app/build.gradle.kts` carrying the app's identity. Open the folder in Android
+ Studio and Run; add your SDKs to `build.gradle.kts` as you would in any Android
+ app. Exporting again rewrites the game and leaves the build script alone, so a
+ project that has grown an SDK survives its game being rebuilt.
- **iOS** — an Xcode project: the `.xcframework`, the app shell and a generated
`.pbxproj`, written around your content. Open it, pick your signing team under
*Signing & Capabilities*, and Run.
diff --git a/docs/astro/src/content/docs/zh-cn/guides/mobile.mdx b/docs/astro/src/content/docs/zh-cn/guides/mobile.mdx
index 209b1d0b8..b1f4d2344 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/mobile.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/mobile.mdx
@@ -36,7 +36,11 @@ Android 和 iOS 是**两个目标而不是一个"Mobile"**,因为它们被组装
| 导出产物 | `dist-android/` | `dist-ios/` |
| 组装方 | 编辑器(不需要 Android SDK) | 编辑器,然后 Xcode |
| 组装所需系统 | 任意桌面系统 | **仅 macOS** |
-| 结果 | 一个已签名的 `.apk` | 一个可打开、签名并运行的 Xcode 工程 |
+| 结果 | 一个已签名的 `.apk`,**或**一个 Android Studio 工程 | 一个可打开、签名并运行的 Xcode 工程 |
+
+Android 两者都给,是因为它两者都做得到:编辑器既能直接装配出安装包,也能写出这个安装包
+本该由之构建的那个 Gradle 工程。游戏需要接自己的 SDK、加权限或加 Activity 时,在 Android
+分区的**输出**里选「Android Studio 工程」——这正是 iOS 一直以来的形状,那边由 Xcode 收尾。
## 前置条件
@@ -89,6 +93,12 @@ Android 和 iOS 是**两个目标而不是一个"Mobile"**,因为它们被组装
要发 **Google Play**,在 Android 分区勾上 *Google Play App Bundle(.aab)*:导出会在
APK 旁边再写一份。Play 自 2021 年起对新应用强制要求 bundle 而非 APK——它是上传格式,
无法直接装到设备上,所以你测试用的仍然是那个 APK。
+- **Android,且**输出**选了「Android Studio 工程」** —— 给的不是安装包,而是一个普通的
+ Gradle 工程:内容在 `app/src/main/assets`,引擎在 `app/src/main/jniLibs`,宿主的 Java
+ shim 以源码形式在 `app/src/main/java`,应用身份写在 `app/build.gradle.kts` 里。用
+ Android Studio 打开该文件夹直接 Run;要接 SDK 就像在任何 Android 应用里那样加进
+ `build.gradle.kts`。再次导出只会重写游戏内容,不动这个构建脚本——已经长出 SDK 的工程
+ 不会因为重新打包游戏而被抹掉。
- **iOS** —— 一个 Xcode 工程:`.xcframework`、应用外壳和生成好的 `.pbxproj` 都已围绕你的
内容写出。打开它,在 *Signing & Capabilities* 下选好签名 Team,Run。