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(ios): an export is an Xcode project you can open
esengine09ca27ee4829
diff --git a/build-tools/cli.js b/build-tools/cli.jsindex 4760648da..b11a63e32 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -168,7 +168,7 @@ program.option('--platform <platform>', 'Android platform', 'android-33').option('--ios-min <version>', 'iOS deployment target', '17.0').option('--simulator', 'iOS: build the simulator slice (needs a simulator Dawn)', false)- .option('--package', 'Android: also package a signed APK (aapt2 + zipalign + apksigner)', false)+ .option('--package', 'Assemble the app around --content: Android a signed APK, iOS a self-contained Xcode project', false).option('--keystore <path>', 'Android --package: signing keystore (default: the debug one)').option('--jdk <dir>', 'JDK home for the APK step (else JAVA_HOME, or the JDK Android Studio bundles)').option('--content <dir>', 'Ship an exported project (Package Project -> Android / iOS) as the app content')diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.jsindex 6fe7e09f1..f1a64ace1 100644--- a/build-tools/tasks/native.js+++ b/build-tools/tasks/native.js@@ -10,13 +10,14 @@import path from 'path';import { existsSync, readFileSync, writeFileSync } from 'fs';-import { mkdir, rm, cp } from 'fs/promises';+import { mkdir, rm, cp, readdir } from 'fs/promises';import config from '../build.config.js';import * as logger from '../utils/logger.js';import { runCommand, getCpuCount, resolvePython } from '../utils/emscripten.js';import { requireSdk, requireNdk, sdkCmake } from '../utils/android.js';import { packageNativeApk } from './nativePackage.js';import { readAppConfig, iosInterfaceOrientations, fillTemplate } from '../utils/nativeApp.js';+import { renderPbxproj, renderScheme } from '../utils/xcodeProject.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@@ -334,6 +335,76 @@ async function writeIosAppIdentity(rootDir, contentDir) {logger.info(`App: ${app.name} (${app.id}) v${app.version} — ${app.orientation}`);}+/** A target/product name Xcode and the shell can both carry unquoted. */+function xcodeTargetName(appName) {+ const cleaned = appName.replace(/[^A-Za-z0-9]+/g, '');+ return cleaned || 'EstellaGame';+}++/**+ * Turn an export into a self-contained Xcode project, in place — the iOS+ * counterpart of `--package`'s APK.+ *+ * The export directory BECOMES the project: its cooked files stay where they are+ * and join the resources phase directly (they land at the bundle root, which is+ * where the host looks), with the app shell, the engine xcframework and the+ * .xcodeproj written alongside. So "Build" in the editor hands back something to+ * double-click — no xcodegen, no shared project in the engine checkout that a+ * second game would overwrite.+ */+async function emitIosXcodeProject(rootDir, contentDir, deploymentTarget) {+ const app = readAppConfig(contentDir, (m) => logger.warn(m));+ const name = xcodeTargetName(app.name);+ const frameworkName = 'Estella.xcframework';+ const projectDir = path.join(contentDir, `${name}.xcodeproj`);+ const appDir = path.join(contentDir, 'App');+ const frameworkDest = path.join(contentDir, frameworkName);++ // Rewritten wholesale so a re-export never inherits the last one's stale+ // slices, plist or object graph.+ await rm(projectDir, { recursive: true, force: true });+ await rm(appDir, { recursive: true, force: true });+ await rm(frameworkDest, { recursive: true, force: true });++ await cp(path.join(rootDir, XCFRAMEWORK), frameworkDest, { recursive: true });++ await mkdir(appDir, { recursive: true });+ const iosDir = path.join(rootDir, 'native', 'ios');+ await cp(path.join(iosDir, 'App', 'main.m'), path.join(appDir, 'main.m'));+ const orientations = iosInterfaceOrientations(app.orientation)+ .map((o) => `\t\t<string>${o}</string>`).join('\n');+ writeFileSync(path.join(appDir, 'Info.plist'), fillTemplate(+ readFileSync(path.join(iosDir, 'App', 'Info.plist.in'), 'utf8'),+ { APP_NAME: app.name, VERSION_NAME: app.version, VERSION_CODE: app.versionCode, ORIENTATIONS: orientations },+ ), 'utf8');++ // Everything the export wrote, minus what this function just added. Dotfiles+ // stay out: .DS_Store in a resources phase is a code-signing failure.+ const skip = new Set([`${name}.xcodeproj`, 'App', frameworkName]);+ const resources = (await readdir(contentDir, { withFileTypes: true }))+ .filter((e) => !skip.has(e.name) && !e.name.startsWith('.'))+ .map((e) => ({ name: e.name, isDir: e.isDirectory() }))+ .sort((a, b) => a.name.localeCompare(b.name));++ await mkdir(path.join(projectDir, 'xcshareddata', 'xcschemes'), { recursive: true });+ writeFileSync(path.join(projectDir, 'project.pbxproj'), renderPbxproj({+ name,+ bundleId: app.id,+ version: app.version,+ versionCode: app.versionCode,+ deploymentTarget,+ frameworkName,+ resources,+ }), 'utf8');+ writeFileSync(+ path.join(projectDir, 'xcshareddata', 'xcschemes', `${name}.xcscheme`),+ renderScheme(name), 'utf8');++ logger.success(`iOS project: ${path.join(contentDir, `${name}.xcodeproj`)}`);+ logger.info(`App: ${app.name} (${app.id}) v${app.version} — ${app.orientation}`);+ return { name, projectDir };+}+async function buildIosHost(options) {if (process.platform !== 'darwin') throw new Error('The iOS host builds on macOS only.');const rootDir = config.paths.root;@@ -378,6 +449,23 @@ async function buildIosHost(options) {logger.success(`iOS host: ${path.join(slice.dir, 'libestella_ios.a')}`);await assembleXcframework(rootDir, env);++ // --package: the export becomes a project of its own. Without it the engine's+ // own native/ios shell is staged instead — that one is for working ON the+ // host, where the Xcode project is checked in and the content is scratch.+ if (options.package) {+ if (!options.content) {+ throw new Error('--package needs the game to package: pass --content <dir> from '+ + 'the editor\'s iOS export.');+ }+ const contentDir = path.isAbsolute(options.content)+ ? options.content : path.join(rootDir, options.content);+ if (!existsSync(contentDir)) throw new Error(`--content dir not found: ${contentDir}`);+ const { projectDir } = await emitIosXcodeProject(rootDir, contentDir, deploymentTarget);+ logger.info(`Next: open ${projectDir} — pick your Team under Signing & Capabilities, then Run.`);+ return;+ }+const staged = options.content ? await stageIosContent(rootDir, options.content) : null;await writeIosAppIdentity(rootDir, staged);logger.info('Next: cd native/ios && xcodegen && open EstellaiOS.xcodeproj — pick your Team, then Run.');diff --git a/build-tools/utils/xcodeProject.js b/build-tools/utils/xcodeProject.jsnew file mode 100644index 000000000..11445519a--- /dev/null+++ b/build-tools/utils/xcodeProject.js@@ -0,0 +1,401 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// The .xcodeproj an iOS export ships, written directly.+//+// An export has to be something a user can double-click, the way Unity and Godot+// hand back a complete Xcode project — not a content folder plus instructions to+// install xcodegen and run it. The project's shape is fixed (one app target, one+// xcframework, the export's own files as resources), so generating the pbxproj is+// a template, and templating it here is what removes the external tool from the+// path between "Build" and "Run".+//+// Object ids are derived from their role, so re-exporting a project rewrites the+// same file byte-for-byte instead of churning a diff.++import { createHash } from 'crypto';++/** A pbxproj object id: 24 uppercase hex chars, stable for a given role. */+function oid(role) {+ return createHash('md5').update(role).digest('hex').slice(0, 24).toUpperCase();+}++// pbxproj is OpenStep plist. A bare word may only be alphanumerics, `_`, `.` and+// `/` — notably NOT `$` or parentheses, so build-setting references like+// `$(inherited)` have to be quoted or the whole file fails to parse.+function q(value) {+ const s = String(value);+ return s !== '' && /^[A-Za-z0-9_./]+$/.test(s)+ ? s+ : `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;+}++function settingsBlock(settings, indent) {+ const pad = '\t'.repeat(indent);+ return Object.entries(settings)+ .map(([k, v]) => (Array.isArray(v)+ ? `${pad}${k} = (\n${v.map((i) => `${pad}\t${q(i)},`).join('\n')}\n${pad});`+ : `${pad}${k} = ${q(v)};`))+ .join('\n');+}++// The system frameworks the host links. Passed as linker flags rather than as file+// references: they add nothing a reader of the project navigator wants to see, and+// each one would otherwise cost a PBXFileReference + PBXBuildFile pair.+const SYSTEM_FRAMEWORKS = [+ 'UIKit', 'Metal', 'QuartzCore', 'IOSurface', 'CoreGraphics',+ // Core Text names the font file the glyph rasterizer parses.+ 'CoreText', 'Foundation',+ // miniaudio's CoreAudio backend, linked at build time (MA_NO_RUNTIME_LINKING).+ 'AVFoundation', 'CoreAudio', 'AudioToolbox',+];++/** Xcode's file type for an export resource, by extension. `folder` ships a+ * directory as-is, keeping the cooked tree's shape inside the bundle. */+function fileType(name, isDir) {+ if (isDir) return 'folder';+ if (name.endsWith('.json')) return 'text.json';+ if (name.endsWith('.js')) return 'sourcecode.javascript';+ return 'file';+}++/**+ * Render the project.pbxproj for an exported game.+ *+ * @param {object} o+ * @param {string} o.name Target + product name (the app's display name, sanitized).+ * @param {string} o.bundleId PRODUCT_BUNDLE_IDENTIFIER.+ * @param {string} o.version MARKETING_VERSION.+ * @param {number|string} o.versionCode CURRENT_PROJECT_VERSION.+ * @param {string} o.deploymentTarget IPHONEOS_DEPLOYMENT_TARGET.+ * @param {string} o.frameworkName The xcframework's filename, at the project root.+ * @param {Array<{name: string, isDir: boolean}>} o.resources+ * The export's own files, copied into the bundle root — where the host looks+ * for them (it reads the bundle root, so no Content/ indirection).+ * @returns {string} project.pbxproj contents+ */+export function renderPbxproj(o) {+ const deploymentTarget = o.deploymentTarget ?? '17.0';+ const ids = {+ project: oid('project'),+ target: oid('target'),+ mainGroup: oid('group.main'),+ appGroup: oid('group.app'),+ productsGroup: oid('group.products'),+ product: oid('file.product'),+ mainSource: oid('file.main.m'),+ infoPlist: oid('file.Info.plist'),+ framework: oid(`file.${o.frameworkName}`),+ sourcesPhase: oid('phase.sources'),+ frameworksPhase: oid('phase.frameworks'),+ resourcesPhase: oid('phase.resources'),+ buildMain: oid('build.main.m'),+ buildFramework: oid(`build.${o.frameworkName}`),+ projectConfigList: oid('configlist.project'),+ targetConfigList: oid('configlist.target'),+ projectDebug: oid('config.project.Debug'),+ projectRelease: oid('config.project.Release'),+ targetDebug: oid('config.target.Debug'),+ targetRelease: oid('config.target.Release'),+ };+ const resources = o.resources.map((r) => ({+ ...r,+ fileId: oid(`file.res.${r.name}`),+ buildId: oid(`build.res.${r.name}`),+ }));++ const projectCommon = {+ ALWAYS_SEARCH_USER_PATHS: 'NO',+ CLANG_ENABLE_OBJC_ARC: 'YES',+ CLANG_ENABLE_MODULES: 'YES',+ COPY_PHASE_STRIP: 'NO',+ ENABLE_STRICT_OBJC_MSGSEND: 'YES',+ GCC_NO_COMMON_BLOCKS: 'YES',+ IPHONEOS_DEPLOYMENT_TARGET: deploymentTarget,+ SDKROOT: 'iphoneos',+ // arm64 only, device and simulator alike: the engine and Dawn are both+ // built arm64, so no x86_64 slice exists for a simulator to link against.+ ARCHS: 'arm64',+ ENABLE_BITCODE: 'NO',+ TARGETED_DEVICE_FAMILY: '1,2',+ };+ const targetCommon = {+ PRODUCT_NAME: '$(TARGET_NAME)',+ PRODUCT_BUNDLE_IDENTIFIER: o.bundleId,+ MARKETING_VERSION: o.version,+ CURRENT_PROJECT_VERSION: String(o.versionCode),+ INFOPLIST_FILE: 'App/Info.plist',+ GENERATE_INFOPLIST_FILE: 'NO',+ CODE_SIGN_STYLE: 'Automatic',+ // The xcframework sits at the project root, next to the export's files.+ FRAMEWORK_SEARCH_PATHS: ['$(inherited)', '$(PROJECT_DIR)'],+ // -ObjC keeps the app delegate / view controller alive: they live in the+ // static library and nothing in main.m references them, so the linker+ // would otherwise drop those translation units.+ OTHER_LDFLAGS: ['$(inherited)', '-ObjC', '-lc++',+ ...SYSTEM_FRAMEWORKS.flatMap((f) => ['-framework', f])],+ };++ const out = [];+ const w = (line) => out.push(line);++ w('// !$*UTF8*$!');+ w('{');+ w('\tarchiveVersion = 1;');+ w('\tclasses = {');+ w('\t};');+ w('\tobjectVersion = 56;');+ w(`\trootObject = ${ids.project} /* Project object */;`);+ w('\tobjects = {');++ w('\n/* Begin PBXBuildFile section */');+ w(`\t\t${ids.buildMain} = {isa = PBXBuildFile; fileRef = ${ids.mainSource}; };`);+ w(`\t\t${ids.buildFramework} = {isa = PBXBuildFile; fileRef = ${ids.framework}; };`);+ for (const r of resources) {+ w(`\t\t${r.buildId} = {isa = PBXBuildFile; fileRef = ${r.fileId}; };`);+ }+ w('/* End PBXBuildFile section */');++ w('\n/* Begin PBXFileReference section */');+ w(`\t\t${ids.product} = {isa = PBXFileReference; explicitFileType = wrapper.application; `+ + `includeInIndex = 0; path = ${q(`${o.name}.app`)}; sourceTree = BUILT_PRODUCTS_DIR; };`);+ w(`\t\t${ids.mainSource} = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; `+ + 'path = main.m; sourceTree = "<group>"; };');+ w(`\t\t${ids.infoPlist} = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; `+ + 'path = Info.plist; sourceTree = "<group>"; };');+ w(`\t\t${ids.framework} = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; `+ + `path = ${q(o.frameworkName)}; sourceTree = "<group>"; };`);+ for (const r of resources) {+ w(`\t\t${r.fileId} = {isa = PBXFileReference; lastKnownFileType = ${fileType(r.name, r.isDir)}; `+ + `path = ${q(r.name)}; sourceTree = "<group>"; };`);+ }+ w('/* End PBXFileReference section */');++ w('\n/* Begin PBXFrameworksBuildPhase section */');+ w(`\t\t${ids.frameworksPhase} = {`);+ w('\t\t\tisa = PBXFrameworksBuildPhase;');+ w('\t\t\tbuildActionMask = 2147483647;');+ w('\t\t\tfiles = (');+ w(`\t\t\t\t${ids.buildFramework},`);+ w('\t\t\t);');+ w('\t\t\trunOnlyForDeploymentPostprocessing = 0;');+ w('\t\t};');+ w('/* End PBXFrameworksBuildPhase section */');++ w('\n/* Begin PBXGroup section */');+ w(`\t\t${ids.mainGroup} = {`);+ w('\t\t\tisa = PBXGroup;');+ w('\t\t\tchildren = (');+ w(`\t\t\t\t${ids.appGroup} /* App */,`);+ w(`\t\t\t\t${ids.framework} /* ${o.frameworkName} */,`);+ for (const r of resources) w(`\t\t\t\t${r.fileId} /* ${r.name} */,`);+ w(`\t\t\t\t${ids.productsGroup} /* Products */,`);+ w('\t\t\t);');+ w('\t\t\tsourceTree = "<group>";');+ w('\t\t};');+ w(`\t\t${ids.appGroup} = {`);+ w('\t\t\tisa = PBXGroup;');+ w('\t\t\tchildren = (');+ w(`\t\t\t\t${ids.mainSource} /* main.m */,`);+ w(`\t\t\t\t${ids.infoPlist} /* Info.plist */,`);+ w('\t\t\t);');+ w('\t\t\tpath = App;');+ w('\t\t\tsourceTree = "<group>";');+ w('\t\t};');+ w(`\t\t${ids.productsGroup} = {`);+ w('\t\t\tisa = PBXGroup;');+ w('\t\t\tchildren = (');+ w(`\t\t\t\t${ids.product} /* ${o.name}.app */,`);+ w('\t\t\t);');+ w('\t\t\tname = Products;');+ w('\t\t\tsourceTree = "<group>";');+ w('\t\t};');+ w('/* End PBXGroup section */');++ w('\n/* Begin PBXNativeTarget section */');+ w(`\t\t${ids.target} = {`);+ w('\t\t\tisa = PBXNativeTarget;');+ w(`\t\t\tbuildConfigurationList = ${ids.targetConfigList};`);+ w('\t\t\tbuildPhases = (');+ w(`\t\t\t\t${ids.sourcesPhase},`);+ w(`\t\t\t\t${ids.frameworksPhase},`);+ w(`\t\t\t\t${ids.resourcesPhase},`);+ w('\t\t\t);');+ w('\t\t\tbuildRules = (');+ w('\t\t\t);');+ w('\t\t\tdependencies = (');+ w('\t\t\t);');+ w(`\t\t\tname = ${q(o.name)};`);+ w(`\t\t\tproductName = ${q(o.name)};`);+ w(`\t\t\tproductReference = ${ids.product};`);+ w('\t\t\tproductType = "com.apple.product-type.application";');+ w('\t\t};');+ w('/* End PBXNativeTarget section */');++ w('\n/* Begin PBXProject section */');+ w(`\t\t${ids.project} = {`);+ w('\t\t\tisa = PBXProject;');+ w('\t\t\tattributes = {');+ w('\t\t\t\tBuildIndependentTargetsInParallel = 1;');+ w('\t\t\t\tLastUpgradeCheck = 1600;');+ w('\t\t\t\tTargetAttributes = {');+ w(`\t\t\t\t\t${ids.target} = {`);+ w('\t\t\t\t\t\tCreatedOnToolsVersion = 16.0;');+ w('\t\t\t\t\t};');+ w('\t\t\t\t};');+ w('\t\t\t};');+ w(`\t\t\tbuildConfigurationList = ${ids.projectConfigList};`);+ w('\t\t\tcompatibilityVersion = "Xcode 14.0";');+ w('\t\t\tdevelopmentRegion = en;');+ w('\t\t\thasScannedForEncodings = 0;');+ w('\t\t\tknownRegions = (');+ w('\t\t\t\ten,');+ w('\t\t\t\tBase,');+ w('\t\t\t);');+ w(`\t\t\tmainGroup = ${ids.mainGroup};`);+ w(`\t\t\tproductRefGroup = ${ids.productsGroup};`);+ w('\t\t\tprojectDirPath = "";');+ w('\t\t\tprojectRoot = "";');+ w('\t\t\ttargets = (');+ w(`\t\t\t\t${ids.target},`);+ w('\t\t\t);');+ w('\t\t};');+ w('/* End PBXProject section */');++ w('\n/* Begin PBXResourcesBuildPhase section */');+ w(`\t\t${ids.resourcesPhase} = {`);+ w('\t\t\tisa = PBXResourcesBuildPhase;');+ w('\t\t\tbuildActionMask = 2147483647;');+ w('\t\t\tfiles = (');+ for (const r of resources) w(`\t\t\t\t${r.buildId} /* ${r.name} */,`);+ w('\t\t\t);');+ w('\t\t\trunOnlyForDeploymentPostprocessing = 0;');+ w('\t\t};');+ w('/* End PBXResourcesBuildPhase section */');++ w('\n/* Begin PBXSourcesBuildPhase section */');+ w(`\t\t${ids.sourcesPhase} = {`);+ w('\t\t\tisa = PBXSourcesBuildPhase;');+ w('\t\t\tbuildActionMask = 2147483647;');+ w('\t\t\tfiles = (');+ w(`\t\t\t\t${ids.buildMain},`);+ w('\t\t\t);');+ w('\t\t\trunOnlyForDeploymentPostprocessing = 0;');+ w('\t\t};');+ w('/* End PBXSourcesBuildPhase section */');++ w('\n/* Begin XCBuildConfiguration section */');+ const config = (id, name, settings) => {+ w(`\t\t${id} = {`);+ w('\t\t\tisa = XCBuildConfiguration;');+ w('\t\t\tbuildSettings = {');+ w(settingsBlock(settings, 4));+ w('\t\t\t};');+ w(`\t\t\tname = ${name};`);+ w('\t\t};');+ };+ config(ids.projectDebug, 'Debug', {+ ...projectCommon,+ DEBUG_INFORMATION_FORMAT: 'dwarf',+ ENABLE_TESTABILITY: 'YES',+ GCC_OPTIMIZATION_LEVEL: '0',+ GCC_PREPROCESSOR_DEFINITIONS: ['DEBUG=1', '$(inherited)'],+ MTL_ENABLE_DEBUG_INFO: 'INCLUDE_SOURCE',+ ONLY_ACTIVE_ARCH: 'YES',+ });+ config(ids.projectRelease, 'Release', {+ ...projectCommon,+ DEBUG_INFORMATION_FORMAT: 'dwarf-with-dsym',+ ENABLE_NS_ASSERTIONS: 'NO',+ MTL_ENABLE_DEBUG_INFO: 'NO',+ ONLY_ACTIVE_ARCH: 'NO',+ VALIDATE_PRODUCT: 'YES',+ });+ config(ids.targetDebug, 'Debug', targetCommon);+ config(ids.targetRelease, 'Release', targetCommon);+ w('/* End XCBuildConfiguration section */');++ w('\n/* Begin XCConfigurationList section */');+ const configList = (id, label, debug, release) => {+ w(`\t\t${id} /* Build configuration list for ${label} */ = {`);+ w('\t\t\tisa = XCConfigurationList;');+ w('\t\t\tbuildConfigurations = (');+ w(`\t\t\t\t${debug} /* Debug */,`);+ w(`\t\t\t\t${release} /* Release */,`);+ w('\t\t\t);');+ w('\t\t\tdefaultConfigurationIsVisible = 0;');+ w('\t\t\tdefaultConfigurationName = Release;');+ w('\t\t};');+ };+ configList(ids.projectConfigList, 'PBXProject', ids.projectDebug, ids.projectRelease);+ configList(ids.targetConfigList, 'PBXNativeTarget', ids.targetDebug, ids.targetRelease);+ w('/* End XCConfigurationList section */');++ w('\t};');+ w('}');+ return `${out.join('\n')}\n`;+}++/**+ * The shared scheme that makes the target runnable straight from a fresh open —+ * without one Xcode has to autocreate it, and `xcodebuild -scheme` finds nothing.+ *+ * Metal API Validation is off (`enableGPUValidationMode = "1"` — Xcode writes that+ * to mean DISABLED; enabled is the absent default). Dawn's Metal backend calls+ * `setDepthClipMode` unconditionally, and the iOS simulator's Metal does not+ * support depth clip mode at all, so the validation layer asserts on the first+ * frame — on a device it is fine, and with validation off the simulator renders+ * correctly too. A game developer writes no Metal, so the first Run should not+ * abort on a backend limitation they cannot act on. Re-enable it per project in+ * Edit Scheme → Run → Diagnostics.+ */+export function renderScheme(name) {+ const id = oid('target');+ return `<?xml version="1.0" encoding="UTF-8"?>+<Scheme LastUpgradeVersion = "1600" version = "1.7">+ <BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES">+ <BuildActionEntries>+ <BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "${id}"+ BuildableName = "${name}.app"+ BlueprintName = "${name}"+ ReferencedContainer = "container:${name}.xcodeproj">+ </BuildableReference>+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES">+ <Testables>+ </Testables>+ </TestAction>+ <LaunchAction buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" debugServiceExtension = "internal" enableGPUValidationMode = "1" allowLocationSimulation = "YES">+ <BuildableProductRunnable runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "${id}"+ BuildableName = "${name}.app"+ BlueprintName = "${name}"+ ReferencedContainer = "container:${name}.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </LaunchAction>+ <ProfileAction buildConfiguration = "Release" shouldUseLaunchSchemeArgsEnv = "YES" savedToolIdentifier = "" useCustomWorkingDirectory = "NO" debugDocumentVersioning = "YES">+ <BuildableProductRunnable runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "${id}"+ BuildableName = "${name}.app"+ BlueprintName = "${name}"+ ReferencedContainer = "container:${name}.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction buildConfiguration = "Debug">+ </AnalyzeAction>+ <ArchiveAction buildConfiguration = "Release" revealArchiveInOrganizer = "YES">+ </ArchiveAction>+</Scheme>+`;+}diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex 5d007a543..2c3c118d6 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -37,6 +37,7 @@ import type { OnExportProgress } from './exportProgress';import { ESENGINE_EXTERNAL } from './esengineResolve';import { orientationCss, orientationOverlayHtml, orientationLockScript, type ScreenOrientation } from './orientationHtml';+import { emitIosXcodeProject, type IosProjectSources } from './iosProject';import { isNativePlatform, type ExportPlatform } from '../src/project/platforms';import { collectSubsystems, subsystemGapWarnings, targetGaps, type Subsystem } from '../src/project/targetSupport';export type { ExportPlatform };@@ -150,6 +151,9 @@ export interface ExportGameResult {included: number;warnings: string[];errors: string[];+ /** iOS: the generated `.xcodeproj`, for the editor to open. Absent when the+ * engine is not built for iOS here (the export still carries its content). */+ xcodeProject?: string;}/** The web host page. `orientation` pins the canvas to a screen orientation (rotate-@@ -400,6 +404,9 @@ export async function exportGame(opts: {* assets resolve against + the storage key an applied update persists under.* The addressable `asset-manifest.json` this export always emits enables it. */hotUpdate?: { remoteRoot?: string; persistUpdateKey?: string };+ /** iOS: where the prebuilt engine + app shell live, so the export can wrap+ * itself in an Xcode project. Omitted (or null) exports content only. */+ iosSources?: IosProjectSources | null;}): Promise<ExportGameResult> {const platform = opts.platform ?? 'web';const title = opts.title ?? 'Game';@@ -501,6 +508,8 @@ export async function exportGame(opts: {const nativeContent = isNativePlatform(platform);const warnings: string[] = [];const errors: string[] = [];+ /** iOS: set once the project is written around the content (see below). */+ let xcodeProject: string | undefined;await mkdir(payloadDir, { recursive: true });const common: BuildOptions = {bundle: true,@@ -623,10 +632,30 @@ export async function exportGame(opts: {orientation,};await writeFile(path.join(payloadDir, 'app.config.json'), JSON.stringify(appConfig, null, 2) + '\n');++ // iOS: wrap the content in a project the user can open. Needs no compiler —+ // the engine is a prebuilt xcframework — so it belongs here rather than behind+ // a command the user has to find and type. An install that never built the+ // engine for iOS still exports its content, and says what is missing.+ if (platform === 'ios') {+ progress({ phase: 'Writing Xcode project' });+ const sources = opts.iosSources ?? null;+ if (sources) {+ const projectDir = await emitIosXcodeProject(absOut, appConfig, sources);+ xcodeProject = projectDir;+ } else {+ warnings.push('The engine is not built for iOS on this machine, so no Xcode project was '+ + 'written — the content is here. Build it once with `node build-tools/cli.js '+ + '--target ios`, then export again.');+ }+ }}// 6. Desktop: wrap the payload in a runnable Electron app.if (platform === 'desktop') { progress({ phase: 'Staging Electron app' }); await stageDesktopApp(absOut, title, orientation, opts.desktopAppId, opts.desktopProductName); }- return { ok: errors.length === 0, platform, outDir: absOut, included: cook.included.length, warnings, errors };+ return {+ ok: errors.length === 0, platform, outDir: absOut, included: cook.included.length,+ warnings, errors, ...(xcodeProject ? { xcodeProject } : {}),+ };}diff --git a/desktop/electron/iosProject.ts b/desktop/electron/iosProject.tsnew file mode 100644index 000000000..ad770d222--- /dev/null+++ b/desktop/electron/iosProject.ts@@ -0,0 +1,143 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file iosProject.ts+ * @brief Turn an iOS export into a project the user can open.+ *+ * @details An export that hands back a content folder plus two commands to type is+ * not a build — Unity and Godot both give you an Xcode project you can+ * double-click, and so should this. Generating one needs no compiler: the+ * engine is a prebuilt xcframework and the app shell is a `main.m` plus a+ * plist, so the whole step is copy + write, which is why it belongs in the+ * export rather than behind a separate "assemble" action.+ *+ * The pbxproj writer is shared with `cli native --target ios --package`+ * (build-tools/utils/xcodeProject.js) so the two paths cannot drift.+ */++import path from 'node:path';+import { existsSync } from 'node:fs';+import { cp, mkdir, readdir, rm, readFile, writeFile } from 'node:fs/promises';+// @ts-expect-error — plain ESM JS, shared with the CLI; bundled in by vite.+import { renderPbxproj, renderScheme } from '../../build-tools/utils/xcodeProject.js';++export interface IosProjectSources {+ /** The engine, built for device + simulator (`cli native --target ios`). */+ xcframework: string;+ /** Holds `main.m` and `Info.plist.in` — the signing/packaging shell. */+ appShell: string;+}++export interface IosAppIdentity {+ id: string;+ name: string;+ version: string;+ versionCode: number;+ orientation: 'landscape' | 'portrait';+}++/**+ * Where the pieces live, or null when this install cannot finish an iOS export.+ *+ * A dev checkout builds the xcframework into `build-native-ios/`; a shipped editor+ * carries it as a resource. Absent means the engine was never built for iOS here —+ * the export still writes its content, it just cannot wrap a project around it.+ */+export function iosProjectSources(candidates: {+ resourcesPath?: string;+ repoRoot?: string;+}): IosProjectSources | null {+ const roots = [+ ...(candidates.resourcesPath ? [path.join(candidates.resourcesPath, 'ios')] : []),+ ...(candidates.repoRoot ? [candidates.repoRoot] : []),+ ];+ for (const root of roots) {+ const xcframework = path.join(root, 'build-native-ios', 'Estella.xcframework');+ const appShell = path.join(root, 'native', 'ios', 'App');+ if (existsSync(xcframework) && existsSync(path.join(appShell, 'main.m'))) {+ return { xcframework, appShell };+ }+ // A shipped editor stages them flat, without the checkout's directory shape.+ const flatFramework = path.join(root, 'Estella.xcframework');+ const flatShell = path.join(root, 'App');+ if (existsSync(flatFramework) && existsSync(path.join(flatShell, 'main.m'))) {+ return { xcframework: flatFramework, appShell: flatShell };+ }+ }+ return null;+}++/** A target/product name Xcode and the shell can both carry unquoted. */+function targetName(appName: string): string {+ return appName.replace(/[^A-Za-z0-9]+/g, '') || 'EstellaGame';+}++/** The orientations the OS may rotate among; mirrors nativeApp.js's iOS mapping. */+function interfaceOrientations(orientation: 'landscape' | 'portrait'): string[] {+ return orientation === 'portrait'+ ? ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown']+ : ['UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];+}++/**+ * Write the Xcode project into an export, in place: the export directory BECOMES+ * the project. Its cooked files stay where they are and join the resources phase+ * directly — they land at the bundle root, which is where the host reads them.+ *+ * @returns The `.xcodeproj` path, for the editor to reveal or open.+ */+export async function emitIosXcodeProject(+ contentDir: string,+ app: IosAppIdentity,+ sources: IosProjectSources,+ deploymentTarget = '17.0',+): Promise<string> {+ const name = targetName(app.name);+ const frameworkName = 'Estella.xcframework';+ const projectDir = path.join(contentDir, `${name}.xcodeproj`);+ const appDir = path.join(contentDir, 'App');+ const frameworkDest = path.join(contentDir, frameworkName);++ // Rewritten wholesale so a re-export never inherits the last one's stale+ // slices, plist or object graph.+ await rm(projectDir, { recursive: true, force: true });+ await rm(appDir, { recursive: true, force: true });+ await rm(frameworkDest, { recursive: true, force: true });++ await cp(sources.xcframework, frameworkDest, { recursive: true });+ await mkdir(appDir, { recursive: true });+ await cp(path.join(sources.appShell, 'main.m'), path.join(appDir, 'main.m'));++ const template = await readFile(path.join(sources.appShell, 'Info.plist.in'), 'utf8');+ const orientations = interfaceOrientations(app.orientation)+ .map((o) => `\t\t<string>${o}</string>`).join('\n');+ await writeFile(path.join(appDir, 'Info.plist'), template+ .replace(/@APP_NAME@/g, app.name)+ .replace(/@VERSION_NAME@/g, app.version)+ .replace(/@VERSION_CODE@/g, String(app.versionCode))+ .replace(/@ORIENTATIONS@/g, orientations));++ // Everything the export wrote, minus what this function just added. Dotfiles+ // stay out: a .DS_Store in a resources phase is a code-signing failure.+ const skip = new Set([`${name}.xcodeproj`, 'App', frameworkName]);+ const resources = (await readdir(contentDir, { withFileTypes: true }))+ .filter((e) => !skip.has(e.name) && !e.name.startsWith('.'))+ .map((e) => ({ name: e.name, isDir: e.isDirectory() }))+ .sort((a, b) => a.name.localeCompare(b.name));++ await mkdir(path.join(projectDir, 'xcshareddata', 'xcschemes'), { recursive: true });+ await writeFile(path.join(projectDir, 'project.pbxproj'), renderPbxproj({+ name,+ bundleId: app.id,+ version: app.version,+ versionCode: app.versionCode,+ deploymentTarget,+ frameworkName,+ resources,+ }));+ await writeFile(+ path.join(projectDir, 'xcshareddata', 'xcschemes', `${name}.xcscheme`),+ renderScheme(name));++ return projectDir;+}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 65dfed331..1c9d4d9b3 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -31,6 +31,7 @@ import { cookAssets } from './cookAssets';import { startProjectWatch, stopProjectWatch } from './projectWatcher';import { importAssets, createAsset, IMPORT_EXTENSIONS } from './importAssets';import { exportGame } from './exportGame';+import { iosProjectSources } from './iosProject';import { loopbackServer, closeAllLoopbackServers } from './loopbackServer';import { httpContentType } from './mimeTypes';import { buildPlayRealm } from './buildPlayRealm';@@ -861,6 +862,12 @@ ipcMain.handle(compressTextures: opts?.compressTextures,compressAudio: opts?.compressAudio,atlasTextures: opts?.atlasTextures,+ // iOS wraps its content in an Xcode project; these are the prebuilt pieces+ // it needs. Null on an install where the engine was never built for iOS —+ // the export then says so instead of writing a project that cannot link.+ iosSources: opts?.platform === 'ios'+ ? iosProjectSources({ resourcesPath: app.isPackaged ? process.resourcesPath : undefined, repoRoot: REPO_ROOT })+ : null,onProgress: (p) => e.sender.send('project:exportProgress', p),});},diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsxindex 7b98768d1..d5bb7219a 100644--- a/desktop/src/components/BuildDialog.tsx+++ b/desktop/src/components/BuildDialog.tsx@@ -49,6 +49,8 @@ interface Result {bytes?: number;warnings: string[];errors: string[];+ /** iOS: the .xcodeproj the export wrote around its content. */+ xcodeProject?: string;}/** Nav groupings. Order here is the order they appear. */@@ -692,7 +694,9 @@ export function BuildDialog() {<span className="build__status-line selectable"><CheckCircle2 size={14} /> {t('build.packagedSummary', { count: result.included, size: result.bytes ? ` · ${mb(result.bytes)}` : '', out: result.outDir })}</span>- <div className="build__next selectable">{def.next(result.outDir)}</div>+ <div className="build__next selectable">+ {result.xcodeProject ? t('build.next.iosProject') : def.next(result.outDir)}+ </div>{result.ok && (<div className="build__actions">{def.httpPreview && (@@ -700,6 +704,11 @@ export function BuildDialog() {<ExternalLink size={13} /> {t('build.previewHttp')}</Button>)}+ {result.xcodeProject && (+ <Button variant="primary" onClick={() => void window.estella.shell?.openPath?.(result.xcodeProject!)}>+ <ExternalLink size={13} /> {t('build.openXcode')}+ </Button>+ )}<Button onClick={() => void window.estella.shell?.openPath?.(result.outDir)}><FolderOpen size={13} /> {t('build.openFolder')}</Button>diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex 5f792d862..fa56fe74c 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -129,9 +129,14 @@ export const projectMessages = defineMessages({zh: '据此构建签名 APK:node build-tools/cli.js native --package --content {out}(一次性的 Dawn + QuickJS 准备见 native/README.md)。',},'build.next.ios': {- en: 'On a Mac: node build-tools/cli.js native --target ios --content {out}, then cd native/ios && xcodegen — pick your Team in Xcode and Run.',- zh: '在 Mac 上运行:node build-tools/cli.js native --target ios --content {out},然后 cd native/ios && xcodegen —— 在 Xcode 中选择你的 Team 并运行。',+ en: 'On a Mac: node build-tools/cli.js native --target ios --package --content {out} — that writes the Xcode project around this content.',+ zh: '在 Mac 上运行:node build-tools/cli.js native --target ios --package --content {out} —— 它会围绕这份内容写出 Xcode 工程。',},+ 'build.next.iosProject': {+ en: 'The Xcode project is written — open it, pick your Team under Signing & Capabilities, then Run.',+ zh: 'Xcode 工程已写好——打开它,在 Signing & Capabilities 下选择你的 Team,然后运行。',+ },+ 'build.openXcode': { en: 'Open in Xcode', zh: '在 Xcode 中打开' },// — Options —'build.configuration': { en: 'Configuration', zh: '配置' },diff --git a/native/ios/project.yml b/native/ios/project.ymlindex 31e1f09c3..db86aa58d 100644--- a/native/ios/project.yml+++ b/native/ios/project.yml@@ -68,3 +68,11 @@ targets:- sdk: AVFoundation.framework- sdk: CoreAudio.framework- sdk: AudioToolbox.framework++# No `schemes:` here on purpose. Without one Xcode autocreates the scheme under+# xcuserdata, which xcodegen never overwrites — so a developer's Diagnostics+# choices survive a regenerate. A shared scheme would be rewritten every time.+# (Metal API Validation has to be turned off once: Dawn calls setDepthClipMode+# unconditionally and the simulator's Metal lacks it. An EXPORTED project ships+# its scheme as a build artifact, so that one has the setting baked in — see+# build-tools/utils/xcodeProject.js.)