Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
ios: make older-device compatibility reach the game host
thehobbit85c9606a142563
diff --git a/frontend-ios/README.md b/frontend-ios/README.mdindex becf8454..33445551 100644--- a/frontend-ios/README.md+++ b/frontend-ios/README.md@@ -55,7 +55,7 @@ The caller returns changed values through `games`. The views keep no second copy| --- | --- | --- || `GameCatalogue` | Scans `Games/<title ID>/`: `game.manifest.json` (schema 1, `GameManifest`), `launcher.json` (`LauncherProfile`, `docs/launcher.schema.json`, also read from `<framework>/<manifest.launcher>`), the manifest's `.framework` folder, optional `banner.<ext>` and `icon.<ext>`. A bundle that cannot be read stays in the list as broken with a readable reason (manifest missing, damaged or of another schema, framework missing, settings list damaged, folder and title ID disagree). | `docs/launcher-c-plan.md`, Manifest and Discovery || `GameCatalogue` (frameworks) | In the shell app the games are the embedded frameworks: `scan(root:)` also reads every `<Name>.framework` folder (pass `Bundle.main.privateFrameworksURL`). A framework without `game.manifest.json` is skipped silently. Otherwise the entry's ID is the manifest's `title_id` (the folder name without `.framework` when the manifest cannot be read), and `directory` and `frameworkURL` are the framework folder. `launcher.json` comes from `<manifest.launcher>`, else the framework's top level, and `banner.<ext>` and `icon.<ext>` from inside the framework. A manifest whose `framework` differs from the folder name is broken (Game files damaged). Of two frameworks with one title ID the first by name is kept and the second is broken, listed under its folder name. `CatalogueEntry.frameworkURL` is a stored property set by both readers. | `docs/launcher-c-plan.md`, Manifest |-| `EngineLaunchPlan` | A pure value from a `LaunchableGame`, the app's `Resources` and `Documents` folders and the text of `Documents/env.txt` (and the game's own `Documents/games/<title ID>/env.txt`, which it reads itself and which wins over the shared one, #557): the environment the real launcher applies with `setenv` (`DM_PROFILE`, `DM_ROMFS`, `DM_SAVE`, `DM_TEMP`, `DM_NVN_SHMAP`, `DM_MSL_DIR`, `DM_PSO_BUNDLE`, `DM_AOC_DIR`, `DM_CHEATS`, `DM_FONT_DIR`, `DM_SAVE_SYNC`, `DM_LAUNCHER=0`, the player's settings, then the keys of the two env files that nothing else set, the game's file first, listed in `DM_ENV_FILE_KEYS`), the `dm_main` arguments (`dmhost`, `<framework>/dm`, the manifest's modules), the framework executable, the image marker, the log URL and the save and temp folders, which only `createFolders()` creates. `parseEnvFile(_:)` reads the `KEY=VALUE` lines. | `boot_env` in `dm/ios/Sources/main.m`, `docs/launcher-c-plan.md`, Environment at game start |+| `EngineLaunchPlan` | A pure value from a `LaunchableGame`, the app's `Resources` and `Documents` folders and the text of `Documents/env.txt` (and the game's own `Documents/games/<title ID>/env.txt`, which it reads itself and which wins over the shared one, #557, followed by build-time defaults in the selected framework's `dm/env.txt`, #719): the environment the real launcher applies with `setenv` (`DM_PROFILE`, `DM_ROMFS`, `DM_SAVE`, `DM_TEMP`, `DM_NVN_SHMAP`, `DM_MSL_DIR`, `DM_PSO_BUNDLE`, `DM_AOC_DIR`, `DM_CHEATS`, `DM_FONT_DIR`, `DM_SAVE_SYNC`, `DM_LAUNCHER=0`, the player's settings, then the keys of the env files that nothing else set, the game's Documents file first and the framework's file last, listed in `DM_ENV_FILE_KEYS`), the `dm_main` arguments (`dmhost`, `<framework>/dm`, the manifest's modules), the framework executable, the image marker, the log URL and the save and temp folders, which only `createFolders()` creates. `parseEnvFile(_:)` reads the `KEY=VALUE` lines. | `boot_env` in `dm/ios/Sources/main.m`, `docs/launcher-c-plan.md`, Environment at game start || `BackupExclusion` | Marks the game data in `Documents/games/<title ID>/` and the single-game names in `Documents` (`romfs*`, `aoc`, `temp`) with `isExcludedFromBackup`, so the backup does not hold many GB (#618). Saves (`save*`) and small text files stay in the backup. Runs when the shell starts, so it also marks what an earlier version left, and `EngineLaunchPlan.createFolders()` marks `temp`. | `boot_env` in `dm/ios/Sources/main.m` || `GameStateResolver` | Broken first, then needs app update (the manifest's `chain` differs from `HostEnvironment.chain`, or `min_os` is above the running OS), then needs game data, else playable. | the plan's playable, needsData, needsFramework and broken || `DataLocator` | The picked location first, then `Documents/games/<title ID>/`, each accepted only with a non-empty `romfs.img` or the manifest's `romfs_marker` (also under `romfs/`). A picked folder that lost its data falls through to the app folder. | `romfs_locate` in `dm/ios/Sources/main.m`, patch 0003's layout |diff --git a/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swift b/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swiftindex 092fcf64..c0878749 100644--- a/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swift+++ b/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swift@@ -24,7 +24,8 @@ public struct EngineLaunchPlan: Equatable, Sendable {/// (#557), read from `game.appFolder` when it is nil. A key in the game's file wins over the shared file, and the launch/// environment (the player's settings, the paths above) wins over both. The game's own `mods/` folder sets/// `DM_ROMFS_OVERLAY` (`GameMods`) when the game's env file does not, and it wins over the shared file. The order is: launch- /// environment, game env.txt, game mods folder, shared env.txt.+ /// environment, game env.txt, game mods folder, shared env.txt, framework dm/env.txt.+ /// The framework file carries build-time defaults such as CPU BC decoding for older GPUs (#719).public static func make(game: LaunchableGame, appResources: URL, documents: URL, envFileText: String?, gameEnvFileText: String? = nil,fileManager fm: FileManager = .default) -> EngineLaunchPlan {let manifest = game.manifest, fw = game.frameworkURL, gdir = game.appFolder@@ -69,6 +70,7 @@ public struct EngineLaunchPlan: Equatable, Sendable {env["DM_ROMFS_OVERLAY"] = overlay}apply(envFileText)+ apply(fm.contents(atPath: fw.appendingPathComponent("dm/env.txt").path).flatMap { String(data: $0, encoding: .utf8) })env["DM_ENV_FILE_KEYS"] = fromFile.joined(separator: " ")return EngineLaunchPlan(diff --git a/frontend-ios/Tests/ShellHostTests/EngineLaunchPlanTests.swift b/frontend-ios/Tests/ShellHostTests/EngineLaunchPlanTests.swiftindex 1123b812..ed2ddfdb 100644--- a/frontend-ios/Tests/ShellHostTests/EngineLaunchPlanTests.swift+++ b/frontend-ios/Tests/ShellHostTests/EngineLaunchPlanTests.swift@@ -26,6 +26,18 @@ import Testing}}+ @Test func frameworkBuildEnvironmentReachesTheHostAndDocumentsCanOverrideIt() throws {+ let rig = try Rig()+ try rig.box.write("DM_PROF_TEX_BC_CPU=1\n", to: rig.fw.appendingPathComponent("dm/env.txt"))+ #expect(rig.plan().environment["DM_PROF_TEX_BC_CPU"] == "1")+ #expect(rig.plan().environment["DM_ENV_FILE_KEYS"] == "DM_PROF_TEX_BC_CPU")+ #expect(rig.plan(envFile: "DM_PROF_TEX_BC_CPU=0\n").environment["DM_PROF_TEX_BC_CPU"] == "0")+ try rig.box.write("DM_PROF_TEX_BC_CPU=0\n", to: rig.gdir.appendingPathComponent("env.txt"))+ #expect(rig.plan().environment["DM_PROF_TEX_BC_CPU"] == "0")+ let another = try Rig()+ #expect(another.plan().environment["DM_PROF_TEX_BC_CPU"] == nil)+ }+@Test func defaultsPointIntoTheFramework() throws {let rig = try Rig()let env = rig.plan().environmentdiff --git a/frontend/Sources/NXModel/BuildStore+Run.swift b/frontend/Sources/NXModel/BuildStore+Run.swiftindex 633cd9aa..2a0dfad8 100644--- a/frontend/Sources/NXModel/BuildStore+Run.swift+++ b/frontend/Sources/NXModel/BuildStore+Run.swift@@ -137,7 +137,7 @@ extension BuildStore {if bcOnCPU && target != BuildTarget.mac {let envPath = NSTemporaryDirectory() + "nspb-env-\(UUID().uuidString.prefix(8)).txt"do {- try "DM_TEX_BC_CPU=1\n".write(toFile: envPath, atomically: true, encoding: .utf8)+ try "DM_PROF_TEX_BC_CPU=1\n".write(toFile: envPath, atomically: true, encoding: .utf8)args += ["--env-file", envPath]say(t("msg.bcOn"))} catch {diff --git a/frontend/Sources/NXModel/BuildStore.swift b/frontend/Sources/NXModel/BuildStore.swiftindex 3248de74..a0b22cfa 100644--- a/frontend/Sources/NXModel/BuildStore.swift+++ b/frontend/Sources/NXModel/BuildStore.swift@@ -123,7 +123,7 @@ func hop(_ body: @escaping @MainActor () -> Void) {}/// Decode BC-compressed textures on the CPU. Only relevant for GPUs without BC support/// (A15/A16 and older): on a device that has it the GPU path is always better, so the switch- /// is a compatibility option and defaults off. Passed as DM_TEX_BC_CPU through --env-file,+ /// is a compatibility option and defaults off. Passed as DM_PROF_TEX_BC_CPU through --env-file,/// which the host reads at start-up — no rebuild of the host needed.@Published package var bcOnCPU: Bool {didSet { defaults.set(bcOnCPU, forKey: Self.bcOnCPUKey) }diff --git a/frontend/Tests/NX2AppleTests/ShellExportTests.swift b/frontend/Tests/NX2AppleTests/ShellExportTests.swiftindex 771f9781..ae724d7b 100644--- a/frontend/Tests/NX2AppleTests/ShellExportTests.swift+++ b/frontend/Tests/NX2AppleTests/ShellExportTests.swift@@ -913,6 +913,7 @@ import NXModellet stores = LauncherStores(xcrun: f.xcrun, defaults: testDefaults); let model = stores.buildstores.repo.path = f.repomodel.target = "ios"+ model.bcOnCPU = truemodel.outDir = path("out")stores.dependencies.pythonPath = "/usr/bin/python3"stores.dependencies.dotnetPath = "/usr/bin/true"@@ -928,6 +929,7 @@ import NXModeltry write(f.repo + "/dm/tools/romfs_image.py", "import sys\nopen(sys.argv[3], 'wb').write(b'image')\n")try write(f.repo + "/scripts/build_ipa_from_nsp.py", """import sys, json, pathlib+ pathlib.Path('\(state)/build-env.txt').write_text(pathlib.Path(sys.argv[sys.argv.index('--env-file') + 1]).read_text())open('\(state)/script.txt', 'w').write(' '.join(sys.argv[1:]))work = pathlib.Path(sys.argv[sys.argv.index('--work-dir') + 1])fw = pathlib.Path(sys.argv[sys.argv.index('--shell-framework') + 1]) / 'DmGame\(titleID).framework'@@ -947,6 +949,7 @@ import NXModelwithExtendedLifetime(token) {}let script = try String(contentsOfFile: state + "/script.txt")+ XCTAssertEqual(try String(contentsOfFile: state + "/build-env.txt"), "DM_PROF_TEX_BC_CPU=1\n")XCTAssertTrue(script.contains("--shell-framework \(temporary.path)/out/\(titleID)_build/shell-framework"), script)XCTAssertFalse(script.contains("--team-id"), script)XCTAssertEqual(model.exportedIPAPath, ShellInstall.ipaPath(root: f.root))diff --git a/patches/0078-ios-carry-cpu-bc-compatibility-through-game-pack.patch b/patches/0078-ios-carry-cpu-bc-compatibility-through-game-pack.patchnew file mode 100644index 00000000..b4feb5dd--- /dev/null+++ b/patches/0078-ios-carry-cpu-bc-compatibility-through-game-pack.patch@@ -0,0 +1,150 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: thehobbit85 <[email protected]>+Date: Wed, 4 Nov 2026 20:45:35 -0800+Subject: [PATCH] ios: carry CPU BC compatibility through game packaging++Keep the build environment in each game framework for the shell to apply. Check the runtime profile before refusing a GPU without native BC formats so a single-game IPA also honors the compatibility override.++Front-ends: the shell must read each framework dm/env.txt after the player environment files.++Upstream-Status: fork-only (declined seedds/nxnative#488, seedds/nxnative#492)+Reason: Repair the fork-only older-device BC decoder and runtime-profile packaging so the launcher compatibility switch reaches the selected game.+Issue: LNPANDY/NX2Apple#719++---+ dm/ios/Sources/main.m | 3 +-+ dm/ios/tests/test_bc_device_check.py | 56 +++++++++++++++++++++++++++++ dm/ios/tests/test_framework_build.py | 21 ++++++++++++ dm/ios/tools/build_ipa.sh | 3 +-+ 4 files changed, 80 insertions(+), 3 deletions(-)+ create mode 100644 dm/ios/tests/test_bc_device_check.py++diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.m+index 69cf022..9824a00 100644+--- a/dm/ios/Sources/main.m++++ b/dm/ios/Sources/main.m+@@ -9,7 +9,6 @@+ #include <sys/stat.h>+ #include <unistd.h>+ #include "hle_profile.h" // the runtime game profile (DM_PROFILE): the RomFS marker path comes from it+-#include "game_profile.h" // DM_GAME_TEX_BC_CPU: a game whose BC textures are decoded on the CPU runs on a GPU without BC+ #include "front.h"+ #include "romfs_image.h"+ #include "DataBookmark.h"+@@ -212,7 +211,7 @@ const char *front_ios_device_check(void) {+ static char msg[320]; static int done;+ if (done++) return msg[0] ? msg : NULL;+ id<MTLDevice> gpu = MTLCreateSystemDefaultDevice(); // the system default device, the one the graphics layers take (mtl_init repeats this check for the other routes)+- if (gpu.supportsBCTextureCompression || DM_GAME_TEX_BC_CPU) return NULL; // tex_bc_cpu: nvn_mtl.m decodes BC on the CPU (nvn_bcdec.c)++ if (gpu.supportsBCTextureCompression || dm_profile()->tex_bc_cpu) return NULL; // tex_bc_cpu: nvn_mtl.m decodes BC on the CPU (nvn_bcdec.c)+ snprintf(msg, sizeof msg, "This device's GPU (%s) cannot read BC-compressed textures, which the games use. It needs an iPhone 15 Pro or newer (A17 Pro chip or later) or an iPad with an M1 chip or later.",+ gpu ? gpu.name.UTF8String : "no Metal device");+ fprintf(stderr, "[RED] boot: %s\n", msg);+diff --git a/dm/ios/tests/test_bc_device_check.py b/dm/ios/tests/test_bc_device_check.py+new file mode 100644+index 0000000..6c443e5+--- /dev/null++++ b/dm/ios/tests/test_bc_device_check.py+@@ -0,0 +1,56 @@++"""Exercise the one-game iOS device check with synthetic GPU capabilities and a runtime profile."""++from pathlib import Path++import subprocess++import sys++import tempfile++import unittest++++REPO = Path(__file__).resolve().parents[3]++++[email protected](sys.platform == 'darwin', 'needs Foundation and Metal')++class BCDeviceCheckTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ cls.temporary = tempfile.TemporaryDirectory()++ cls.addClassCleanup(cls.temporary.cleanup)++ root = Path(cls.temporary.name)++ main = (REPO / 'dm/ios/Sources/main.m').read_text()++ check = main[main.index('const char *front_ios_device_check(void)'):main.index('static void romfs_identity_report')]++ source = root / 'check.m'++ source.write_text('''#import <Foundation/Foundation.h>++#import <Metal/Metal.h>++#include <stdio.h>++#include <stdlib.h>++#define DM_GAME_TEX_BC_CPU 0++static int supports_bc, cpu_decode;++typedef struct { int tex_bc_cpu; } dm_game_profile;++static const dm_game_profile *dm_profile(void) { static dm_game_profile p; p.tex_bc_cpu = cpu_decode; return &p; }++@interface FixtureGPU : NSObject++@property(readonly) BOOL supportsBCTextureCompression;++@property(readonly) NSString *name;++@end++@implementation FixtureGPU++- (BOOL)supportsBCTextureCompression { return supports_bc; }++- (NSString *)name { return @"Fixture GPU"; }++@end++static id<MTLDevice> fixture_device(void) { return (id<MTLDevice>)[FixtureGPU new]; }++#define MTLCreateSystemDefaultDevice fixture_device++''' + check + '''++int main(int argc, char **argv) { @autoreleasepool {++ supports_bc = atoi(argv[1]); cpu_decode = atoi(argv[2]);++ return front_ios_device_check() ? 1 : 0;++} }++''')++ cls.executable = root / 'check'++ subprocess.run(['clang', '-fobjc-arc', '-framework', 'Foundation', '-framework', 'Metal', str(source), '-o', str(cls.executable)], check=True)++++ def test_effective_runtime_profile_allows_cpu_decoding_on_older_gpu(self):++ for supports_bc, cpu_decode, expected in [(0, 0, 1), (0, 1, 0), (1, 0, 0)]:++ with self.subTest(supports_bc=supports_bc, cpu_decode=cpu_decode):++ result = subprocess.run([str(self.executable), str(supports_bc), str(cpu_decode)], capture_output=True, text=True)++ self.assertEqual(result.returncode, expected, result.stderr)++++++if __name__ == '__main__':++ unittest.main()+diff --git a/dm/ios/tests/test_framework_build.py b/dm/ios/tests/test_framework_build.py+index fee9e53..0d20b82 100644+--- a/dm/ios/tests/test_framework_build.py++++ b/dm/ios/tests/test_framework_build.py+@@ -120,6 +120,27 @@ class ProjectTemplateTests(unittest.TestCase):+ self.assertEqual(self.prepare(0), ('name: default\n', False))++++class FrameworkEnvironmentTests(unittest.TestCase):++ def test_build_environment_stays_with_its_framework(self):++ block = SCRIPT[SCRIPT.index('if [ "$FRAMEWORK" = 1 ]; then\n rm -rf Gen/framework'):SCRIPT.index('# A prepared Xcode project is signed')]++ with tempfile.TemporaryDirectory() as temporary:++ root = Path(temporary)++ (root / 'Gen/dm/font').mkdir(parents=True)++ (root / 'patched').mkdir()++ (root / 'dm').symlink_to(REPO / 'dm', target_is_directory=True)++ (root / 'Gen/dm/env.txt').write_text('DM_PROF_TEX_BC_CPU=1\n')++ (root / 'Gen/dm/font/font.ttf').write_text('font')++ (root / 'Gen/dm/launcher.json').write_text('{}')++ (root / 'tools').symlink_to(REPO / 'dm/ios/tools', target_is_directory=True)++ result = run_step(block, root, FRAMEWORK='1', FRAMEWORK_ONLY='out', FW_NAME='DmGame' + GAME,++ PATCHED=str(root / 'patched'), ROMFS=str(root / 'none'), PREPARE_XCODE='NO', DM_COPY_ROMFS='NO',++ DM_DISPLAY_NAME='Fixture', DM_APP_VERSION='1.0', MODS='main', V='fixture', MARKER='marker', F='')++ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)++ self.assertTrue((root / 'Gen/framework/dm/env.txt').is_file(), 'the built framework must carry its environment')++ self.assertEqual((root / 'Gen/framework/dm/env.txt').read_text(), 'DM_PROF_TEX_BC_CPU=1\n')++ self.assertFalse((root / 'Gen/framework/dm/font').exists())+++++ class FrameworkPackagingTests(unittest.TestCase):+ """The signing and pack steps on a stand-in app; no Xcode, no game files."""++diff --git a/dm/ios/tools/build_ipa.sh b/dm/ios/tools/build_ipa.sh+index 97d22d1..e40ed8e 100755+--- a/dm/ios/tools/build_ipa.sh++++ b/dm/ios/tools/build_ipa.sh+@@ -197,7 +197,8 @@ else t "no app icon ($ICON not found): the home-screen icon stays blank"; fi+ if [ "$FRAMEWORK" = 1 ]; then+ rm -rf Gen/framework && mkdir -p Gen/framework/dm || die "mkdir Gen/framework"+ cp -R Gen/dm/. Gen/framework/dm/ || die "copy the framework tables"+- rm -rf Gen/framework/dm/font Gen/framework/dm/env.txt++ rm -rf Gen/framework/dm/font++ # Keep dm/env.txt with this game: the shell applies its build-time defaults after the player's environment files.+ # The one-game app reads its launcher.json from the app's dm/; the shell reads each game's from its framework (manifest key launcher)+ [ -n "$FRAMEWORK_ONLY" ] || rm -f Gen/framework/dm/launcher.json+ python3 "$DM/games/game.py" profile "$GAME" Gen/framework/profile.tsv > /dev/null || die "game profile"diff --git a/patches/series b/patches/seriesindex 8a2fffaf..659ea8c7 100644--- a/patches/series+++ b/patches/series@@ -45,3 +45,4 @@0075-front-mac-hide-the-pointer-before-the-game-takes.patch0076-host-read-embedded-sections-from-the-image-that.patch0077-ios-shell-link-the-host-into-each-game-s-framewo.patch+0078-ios-carry-cpu-bc-compatibility-through-game-pack.patch