From 366d6052af5f1a39bbe9064d6c5eb3b93e7027f8 Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:20:33 +0100 Subject: [PATCH 01/13] Add nix devshell and stop hardcoding the LLVM path Resolve LLVM from LLVM_BIN, then PATH, then Homebrew; provide LLVM, .NET 10, SPIRV-Cross and Python 3.12 through flake.nix; build the venv with uv. Default the launch profiles to enUS because zh-Hans needs the separate zhCN DLC pack. --- .gitignore | 1 + Makefile | 10 +++-- docs/BUILD.md | 2 +- flake.lock | 27 ++++++++++++++ flake.nix | 54 +++++++++++++++++++++++++++ tests/test_mobile_graphics_profile.py | 2 +- tools/dr3.py | 24 +++++++++--- tools/mac_launcher.m | 3 +- tools/mobile_graphics_profile.py | 13 ++++++- tools/smoke_mac.py | 4 +- 10 files changed, 126 insertions(+), 14 deletions(-) create mode 100644 flake.lock create mode 100644 flake.nix diff --git a/.gitignore b/.gitignore index dc3b828..2f91082 100644 --- a/.gitignore +++ b/.gitignore @@ -80,3 +80,4 @@ third_party/nxnative/ *.ttf *.heic *.mov +.serena/* diff --git a/Makefile b/Makefile index 86bfb45..c09bf73 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,12 @@ PY := .venv/bin/python -.PHONY: setup bootstrap rewrite verify shaders mac app run test +.PHONY: setup bootstrap rewrite verify shaders mac app run test env +# --no-config: this machine's global uv config pins exclude-newer=7 days, +# which rejects the pinned versions in requirements.txt. setup: - python3 -m venv .venv - $(PY) -m pip install -r requirements.txt + uv venv --python 3.12 .venv + uv pip install --no-config --python .venv/bin/python -r requirements.txt +env: + nix develop bootstrap: $(PY) tools/dr3.py bootstrap rewrite: diff --git a/docs/BUILD.md b/docs/BUILD.md index 3a188d2..75ebd85 100644 --- a/docs/BUILD.md +++ b/docs/BUILD.md @@ -4,7 +4,7 @@ Read [GAME_FILES.md](GAME_FILES.md) first. 本教程从你已经合法准备的 ## Prerequisites / 环境 -Apple silicon Mac; macOS 26+; full Xcode with Metal tools (tested Xcode 27); Python 3.12+; LLVM; .NET 10; SPIRV-Cross; XcodeGen for iOS. Install and select your own Xcode/toolchains. The verifier currently expects Homebrew LLVM at `/opt/homebrew/opt/llvm/bin`. Prepare substantial free disk space: the tested base/language resource set alone is about 22.75 GB, with additional extraction, shader and build caches. +Apple silicon Mac; macOS 26+; full Xcode with Metal tools (tested Xcode 27); Python 3.12+; LLVM; .NET 10; SPIRV-Cross; XcodeGen for iOS. Install and select your own Xcode/toolchains. LLVM is resolved from `LLVM_BIN`, then `llvm-mc` on `PATH`, and only then from Homebrew's `/opt/homebrew/opt/llvm/bin`. On a nix machine `nix develop` (see `flake.nix`) provides LLVM, .NET 10, SPIRV-Cross and Python 3.12 — it deliberately drops nix's `xcrun`/`clang` wrappers so Xcode's toolchain and the separately installed Metal compiler (`xcodebuild -downloadComponent MetalToolchain`) stay in charge. Prepare substantial free disk space: the tested base/language resource set alone is about 22.75 GB, with additional extraction, shader and build caches. ```sh git clone https://github.com/enginefuture/dr3-mobile.git diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..1c688af --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1792210252, + "narHash": "sha256-Mh0PUaIv4nFY+8wAGonaEh8iBzwsmdNlwjVHmFg1Biw=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "09063bd1f2b36fd9fd793c36dfade7bd40a93dfc", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..f0acc6f --- /dev/null +++ b/flake.nix @@ -0,0 +1,54 @@ +{ + description = "D3 mobile native toolchain"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + outputs = { self, nixpkgs }: + let + system = "aarch64-darwin"; + pkgs = nixpkgs.legacyPackages.${system}; + in + { + devShells.${system}.default = pkgs.mkShell { + packages = with pkgs; [ + llvm + dotnet-sdk_10 + spirv-cross + python312 + uv + git + gnumake + gnused + gnugrep + ]; + + # The verifier shells out to llvm-mc/llvm-objdump; bind them to this + # shell's LLVM so results cannot drift with a host toolchain. + LLVM_BIN = "${pkgs.llvm}/bin"; + # dotnet resolves its runtime relative to DOTNET_ROOT, and the nix + # package keeps the payload in share/dotnet rather than bin. + DOTNET_ROOT = "${pkgs.dotnet-sdk_10}/share/dotnet"; + + shellHook = '' + # Keep dotnet/NuGet state inside the workspace: the CLI refuses to run + # when its home sentinels cannot be created (observed EPERM on ~/.dotnet). + export DOTNET_CLI_HOME="$PWD/work/.dotnet" + export NUGET_PACKAGES="$PWD/work/.nuget/packages" + export DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1 + # Xcode must provide the C/ObjC toolchain and xcrun: the Metal compiler + # is an Xcode component, and nix's xcbuild xcrun shim plus the nix + # apple-sdk (SDK 14.4) hide it. llvm-mc stays available via LLVM_BIN. + unset SDKROOT DEVELOPER_DIR NIX_APPLE_SDK_VERSION + PATH=$(printf '%s' "$PATH" | tr ':' '\n' | grep -vE -- '/nix/store/[^/]*(clang|llvm|xcbuild)[^/]*/bin' | paste -sd: -) + export PATH + # The nix compiler env would otherwise supply the nix apple-sdk and + # libc++ headers to whatever clang wins; the host links Xcode frameworks. + unset NIX_CFLAGS_COMPILE NIX_LDFLAGS NIX_CC NIX_BINTOOLS + echo "llvm-mc: $("$LLVM_BIN/llvm-mc" --version | head -1)" + echo "clang: $(clang --version | head -1)" + echo "dotnet: $(dotnet --version)" + echo "spirv-cross: $(spirv-cross --help 2>&1 | head -1)" + ''; + }; + }; +} diff --git a/tests/test_mobile_graphics_profile.py b/tests/test_mobile_graphics_profile.py index 5173a44..f452404 100644 --- a/tests/test_mobile_graphics_profile.py +++ b/tests/test_mobile_graphics_profile.py @@ -51,7 +51,7 @@ def test_bounds_do_not_allow_unknown_dimensions(self): with self.assertRaises(ValueError):m.parameters(w,h) def test_independent_guest_math(self): - llvm=Path('/opt/homebrew/opt/llvm/bin/llvm-mc') + llvm=m.llvm_mc() if not llvm.exists():self.skipTest('LLVM unavailable') for width in (1280,1568,1920): report=m.verify(self.source(),llvm,width,720) diff --git a/tools/dr3.py b/tools/dr3.py index f359ca7..9ff95c4 100644 --- a/tools/dr3.py +++ b/tools/dr3.py @@ -17,6 +17,8 @@ TITLE = '01001B300B9BE000' COMMIT = '9579030e5b1f0443c12b7376559560915b6d4c4b' PROFILE = ROOT / 'config/diablo3-2.7.7.json' +# zh-Hans needs the separate zhCN language DLC; only enUS ships in the pinned base set. +LANG = 'enUS' SUFFIXES = ('patched.bin', 'fixups.tsv', 'gates.tsv', 'sites.tsv', 'cuts.tsv', 'obs.tsv', 'params.tsv') @@ -35,12 +37,23 @@ def save(path, value): def env(): result = {k: v for k, v in os.environ.items() if not k.startswith('DM_')} result.update(DM_ROOT=str(WORK), DM_GAME=TITLE, DM_RULESET='native', DM_PRIVATE_GATES='0') - dotnet = shutil.which('dotnet') - if dotnet: - result['DOTNET_ROOT'] = str(Path(dotnet).resolve().parent) + if 'DOTNET_ROOT' not in result: + dotnet = shutil.which('dotnet') + if dotnet: + result['DOTNET_ROOT'] = str(Path(dotnet).resolve().parent) return result +def llvm_bin(): + configured = os.environ.get('LLVM_BIN') + if configured: + return Path(configured) + tool = shutil.which('llvm-mc') + if tool: + return Path(tool).resolve().parent + return Path('/opt/homebrew/opt/llvm/bin') + + def run(command, log, extra=None, cwd=None, timeout=None): log.parent.mkdir(parents=True, exist_ok=True) print(f'{log.relative_to(ROOT)}', flush=True) @@ -148,7 +161,7 @@ def verify(_): for script, options in [('structck.py', []), ('equiv.py', ['--jobs', '4', '--seed', '1', '--mutate', '100'])]: log = WORK / 'logs' / f'verify-{name}-{script}.log' run([sys.executable, UPSTREAM / 'dm/verify' / script, WORK / 'rewrite', name, - WORK / 'game/ExeFS' / name, *options], log, {'LLVM_BIN': '/opt/homebrew/opt/llvm/bin'}) + WORK / 'game/ExeFS' / name, *options], log, {'LLVM_BIN': str(llvm_bin())}) results[f'{name}/{script}'] = log.read_text().splitlines()[-1] save(WORK / 'verification.json', {'passed': True, 'artifacts': fingerprints(), 'results': results, 'profile_sha256': sha(PROFILE), 'limitations': ['Exclusives replaced in both Unicorn inputs; concurrency unproven.', @@ -218,7 +231,7 @@ def launch(args): (WORK / 'run' / name).mkdir(exist_ok=True) settings = dict(DM_ROMFS=str(WORK / 'game/RomFS'), DM_SAVE=str(WORK / 'run/save'), DM_TEMP=str(WORK / 'run/temp'), DM_WINDOW='1', DM_DBG='1', DM_AUDIO='1', - DM_LANG='zh-Hans', DM_AOC_DIR=str(WORK / 'aoc'), MTL_HUD_ENABLED='1', + DM_LANG=args.lang, DM_AOC_DIR=str(WORK / 'aoc'), MTL_HUD_ENABLED='1', DM_NVN_SHMAP=str(UPSTREAM / 'dm/games' / TITLE / 'shader_map.tsv'), DM_MSL_DIR=str(WORK / 'build/cache/metal_shader_cache'), DM_PSO_MANIFEST='off', DM_NVN_TBDR='0', DM_NVN_UNIFORM_FORWARD='1', @@ -272,6 +285,7 @@ def main(): prep.add_argument('--keys', type=Path, required=True, help='Your own local keyset; never uploaded or required at runtime') start = commands.add_parser('run') start.add_argument('--seconds', type=int, default=30) + start.add_argument('--lang', default=LANG, help='Game UI language; zh-Hans requires the zhCN DLC pack') start.add_argument('--capture-shaders', action='store_true', help='Diagnostic only: missing stages may omit draws') start.add_argument('--keys', help='Timed diagnostic gamepad input using the upstream DM_KEYS syntax') start.add_argument('--inspect-frame', type=int, help='Dump actual pass bindings and render targets') diff --git a/tools/mac_launcher.m b/tools/mac_launcher.m index 30045b5..3a28cad 100644 --- a/tools/mac_launcher.m +++ b/tools/mac_launcher.m @@ -113,7 +113,8 @@ - (void)start:(id)sender { path_env("DM_SAVE",g_runRoot,@"save");path_env("DM_TEMP",g_runRoot,@"temp");path_env("DM_HID_RECEIPT_LOG",g_runRoot,@"controller.jsonl"); path_env("DM_PAD_EVENT_LOG",g_runRoot,@"controller-events.jsonl");path_env("DM_NVN_TSV",g_runRoot,@"performance.tsv"); path_env("DM_NVN_SHMAP",g_resources,@"game/shader_map.tsv");path_env("DM_MSL_DIR",g_resources,@"shaders"); - setenv("DM_WINDOW","1",1);setenv("DM_AUDIO","1",1);setenv("DM_LANG","zh-Hans",1);setenv("DM_OPMODE","0",1); + // zh-Hans needs the separate zhCN DLC pack; the shipped base set is enUS. + setenv("DM_WINDOW","1",1);setenv("DM_AUDIO","1",1);setenv("DM_LANG","enUS",1);setenv("DM_OPMODE","0",1); setenv("DM_HID_RECEIPT_LIMIT","65536",1);setenv("DM_NVN_TSV_CALLS","0",1);setenv("DM_NVN_UNIFORM_FORWARD","1",1); setenv("DM_NVN_TBDR","0",1);setenv("DM_PSO_MANIFEST","off",1); setenv("MTL_HUD_ENABLED",self.hud.state==NSControlStateValueOn?"1":"0",1); diff --git a/tools/mobile_graphics_profile.py b/tools/mobile_graphics_profile.py index 4e2af8f..cdc960e 100644 --- a/tools/mobile_graphics_profile.py +++ b/tools/mobile_graphics_profile.py @@ -9,8 +9,10 @@ import argparse import hashlib import json +import os from pathlib import Path import random +import shutil import struct import subprocess @@ -145,7 +147,16 @@ def launch_directory(work,destination,width=DEFAULT_WIDTH,height=DEFAULT_HEIGHT) return destination -def verify(original,llvm=Path('/opt/homebrew/opt/llvm/bin/llvm-mc'),width=DEFAULT_WIDTH,height=DEFAULT_HEIGHT): +def llvm_mc(): + configured=os.environ.get('LLVM_BIN') + if configured:return Path(configured)/'llvm-mc' + found=shutil.which('llvm-mc') + if found:return Path(found) + return Path('/opt/homebrew/opt/llvm/bin/llvm-mc') + + +def verify(original,llvm=None,width=DEFAULT_WIDTH,height=DEFAULT_HEIGHT): + llvm=llvm or llvm_mc() from unicorn import Uc,UC_ARCH_ARM64,UC_MODE_ARM from unicorn.arm64_const import (UC_ARM64_REG_X0,UC_ARM64_REG_X30,UC_ARM64_REG_SP,UC_ARM64_REG_CPACR_EL1, UC_ARM64_REG_S0) diff --git a/tools/smoke_mac.py b/tools/smoke_mac.py index bbefa7e..3c2bdbb 100644 --- a/tools/smoke_mac.py +++ b/tools/smoke_mac.py @@ -7,7 +7,7 @@ import statistics import subprocess import time -from dr3 import WORK, env, check_modules, profile, sha, save +from dr3 import WORK, LANG, env, check_modules, profile, sha, save def save_files(directory): @@ -31,7 +31,7 @@ def main(): directory.mkdir();shutil.copytree(original,directory/'save');(directory/'temp').mkdir() control=directory/'control.txt';control.write_text('1 1\n') settings=dict(DM_ROMFS=str(WORK/'game/RomFS'),DM_SAVE=str(directory/'save'),DM_TEMP=str(directory/'temp'), - DM_AOC_DIR=str(WORK/'aoc'),DM_LANG='zh-Hans',DM_OPMODE=args.opmode,DM_NVN_TBDR='0',DM_PSO_MANIFEST='off', + DM_AOC_DIR=str(WORK/'aoc'),DM_LANG=LANG,DM_OPMODE=args.opmode,DM_NVN_TBDR='0',DM_PSO_MANIFEST='off', DM_NVN_SHMAP=str(resources/'game/shader_map.tsv'),DM_MSL_DIR=str(resources/'shaders'), DM_NVN_UNIFORM_FORWARD='1',DM_NVN_UNIFORM_FORWARD_CONTROL=str(control), DM_NVN_TSV=str(directory/'performance.tsv'),DM_NVN_TSV_CALLS='0',DM_KEYS=args.keys, From e7a4ddc3773dd025b3aed3f3955275c11e07d001 Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:54:25 +0100 Subject: [PATCH 02/13] Localize the launcher and add a game language control MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add en/zh-Hans Localizable.strings, select the launcher language from the system locale, and let the launcher pick the game language (System, English, 简体中文) instead of hardcoding one tag. --- patches/nxnative.patch | 38 ++++++++++--- tests/test_launcher_i18n.py | 51 +++++++++++++++++ tools/dr3.py | 19 ++++++- tools/mac-i18n/en.lproj/Localizable.strings | 28 ++++++++++ .../zh-Hans.lproj/Localizable.strings | 28 ++++++++++ tools/mac_app.py | 37 ++++++++++++ tools/mac_launcher.m | 56 ++++++++++++------- tools/smoke_mac.py | 4 +- 8 files changed, 228 insertions(+), 33 deletions(-) create mode 100644 tests/test_launcher_i18n.py create mode 100644 tools/mac-i18n/en.lproj/Localizable.strings create mode 100644 tools/mac-i18n/zh-Hans.lproj/Localizable.strings diff --git a/patches/nxnative.patch b/patches/nxnative.patch index 91b9c5e..a46af46 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -1578,7 +1578,7 @@ index d21874c..926334d 100644 printf("== %d 项,失败 %d ==\n", g_n, g_fail); return g_fail != 0; diff --git a/dm/gfx/tools/dmsh_chain.lock b/dm/gfx/tools/dmsh_chain.lock -index c925370..05aa879 100644 +index c925370..4dc5154 100644 --- a/dm/gfx/tools/dmsh_chain.lock +++ b/dm/gfx/tools/dmsh_chain.lock @@ -3,6 +3,6 @@ dmsh_xlate.dll 6dd3441c31b57475 @@ -1586,7 +1586,7 @@ index c925370..05aa879 100644 Ryujinx.Common.dll 74f785bc3a81386e xlate_source 23b85cb2e58b9c36 -spirv-cross d9dc197f061b42a5 -+spirv-cross 242d2c694be3ec91 ++spirv-cross 00f1a6a7e06b5523 metal_macosx Apple metal version 32023.921 (metalfe-32023.921.6) metal_iphoneos Apple metal version 32023.921 (metalfe-32023.921.6) diff --git a/dm/host/Makefile b/dm/host/Makefile @@ -1672,7 +1672,7 @@ index 933c85b..6dfad7a 100644 +void dm_pad_clear(void); +void dm_input_clear(void); diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m -index c7559ca..1cbe064 100644 +index c7559ca..cb5a160 100644 --- a/dm/host/front_mac.m +++ b/dm/host/front_mac.m @@ -3,6 +3,7 @@ @@ -1683,7 +1683,7 @@ index c7559ca..1cbe064 100644 #import #include "dm.h" #include "dm_input.h" -@@ -13,14 +14,45 @@ __attribute__((constructor)) static void ui_shift_reg(void) { mtl_set_ui_rect_fn +@@ -13,14 +14,58 @@ __attribute__((constructor)) static void ui_shift_reg(void) { mtl_set_ui_rect_fn #include "front.h" #include "hle.h" #include @@ -1692,8 +1692,21 @@ index c7559ca..1cbe064 100644 +void dm_gamepad_start(void (*on_present)(int)); +void dm_gamepad_set_active(int active); +static __weak NSWindow *g_window; ++static int lang_zh(void) { const char *e = getenv("DM_LANG"); return e && (e[0] | 0x20) == 'z' && (e[1] | 0x20) == 'h'; } +static void pad_status(int present) { -+ g_window.title = [NSString stringWithFormat:@"%s · %@", DM_GAME_NAME, present ? @"手柄已连接" : @"等待手柄(键盘可用)"]; ++ g_window.title = [NSString stringWithFormat:@"%s · %@", DM_GAME_NAME, lang_zh() ? (present ? @"手柄已连接" : @"等待手柄(键盘可用)") ++ : (present ? @"Controller connected" : @"Waiting for controller (keyboard works)")]; ++} ++static void install_main_menu(void) { ++ NSString *name = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleName"]; ++ if (!name.length) name = NSProcessInfo.processInfo.processName; ++ NSMenu *main = [NSMenu new], *app = [[NSMenu alloc] initWithTitle:name]; ++ NSMenuItem *item = [[NSMenuItem alloc] init]; ++ item.title = name; item.submenu = app; [main addItem:item]; ++ [app addItemWithTitle:[NSString stringWithFormat:@"Hide %@", name] action:@selector(hide:) keyEquivalent:@"h"]; ++ [app addItem:NSMenuItem.separatorItem]; ++ [app addItemWithTitle:[NSString stringWithFormat:@"Quit %@", name] action:@selector(terminate:) keyEquivalent:@"q"]; ++ NSApp.mainMenu = main; +} static CAMetalLayer *g_layer; static uint64_t g_btn; @@ -1729,7 +1742,7 @@ index c7559ca..1cbe064 100644 unsigned w, h; const char *e = getenv("DM_GAME_RES"); if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4; return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280; -@@ -60,18 +92,27 @@ void front_run(void (*guest)(void)) { +@@ -60,23 +105,33 @@ void front_run(void (*guest)(void)) { @autoreleasepool { [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; @@ -1760,7 +1773,13 @@ index c7559ca..1cbe064 100644 [win center]; [win makeKeyAndOrderFront:nil]; [NSApp activateIgnoringOtherApps:YES]; -@@ -93,10 +134,10 @@ void front_run(void (*guest)(void)) { + [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown | NSEventMaskKeyUp handler:^NSEvent *(NSEvent *e) { + if (e.window != win) return e; // Only swallow keys for the game window; other windows such as the software keyboard input box receive typing as usual ++ if (e.modifierFlags & NSEventModifierFlagCommand) return e; // Let Command key equivalents reach the menu (Cmd+Q / Cmd+W); the game key map has no Command bindings + if (!e.isARepeat) on_key(e, e.type == NSEventTypeKeyDown); + return nil; // Swallow it to avoid the system beep + }]; +@@ -93,14 +148,15 @@ void front_run(void (*guest)(void)) { usingBlock:^(NSNotification *n) { (void)n; exit(0); }]; // Lifecycle (hle.h / dm.h): focus lost → 2, focus regained → 1; minimized → 3 + audio paused + GPU suspended, restored → resume (followed by focus regained → 1) NSNotificationCenter *nc = NSNotificationCenter.defaultCenter; @@ -1775,6 +1794,11 @@ index c7559ca..1cbe064 100644 // Guest thread: 64 MiB stack (the Switch main thread stack is specified by npdm; the host gives plenty) static guest_arg ga; ga.fn = guest; pthread_attr_t a; pthread_attr_init(&a); pthread_attr_setstacksize(&a, 64u << 20); + pthread_t th; if (pthread_create(&th, &a, guest_tramp, &ga)) die("pthread_create guest"); ++ install_main_menu(); + [NSApp run]; + } + } diff --git a/dm/host/hle.c b/dm/host/hle.c index 1a63bd7..9fcffec 100644 --- a/dm/host/hle.c diff --git a/tests/test_launcher_i18n.py b/tests/test_launcher_i18n.py new file mode 100644 index 0000000..95064e3 --- /dev/null +++ b/tests/test_launcher_i18n.py @@ -0,0 +1,51 @@ +import re +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +STRINGS = ROOT / 'tools/mac-i18n' +LAUNCHER = ROOT / 'tools/mac_launcher.m' +LANGUAGES = ('en', 'zh-Hans') + + +def strings_keys(path): + keys = {} + for number, line in enumerate(path.read_text(encoding='utf-8-sig').splitlines(), 1): + text = line.strip() + if not text or text.startswith('/*') or text.startswith('//'): + continue + match = re.fullmatch(r'"((?:[^"\\]|\\.)*)"\s*=\s*"((?:[^"\\]|\\.)*)"\s*;', text) + if not match: + raise AssertionError(f'{path}:{number}: malformed localization entry') + key, value = match.groups() + if key in keys: + raise AssertionError(f'{path}:{number}: duplicate key {key!r}') + keys[key] = value + return keys + + +class LauncherI18N(unittest.TestCase): + def setUp(self): + self.strings = {language: strings_keys(STRINGS / f'{language}.lproj' / 'Localizable.strings') + for language in LANGUAGES} + + def test_localizations_share_one_key_set(self): + english, chinese = self.strings['en'], self.strings['zh-Hans'] + self.assertEqual(sorted(english), sorted(chinese)) + + def test_localizations_have_values(self): + for language, entries in self.strings.items(): + for key, value in entries.items(): + self.assertTrue(value.strip(), f'{language}: empty value for {key!r}') + + def test_launcher_keys_exist_and_are_all_used(self): + source = LAUNCHER.read_text(encoding='utf-8') + used = set(re.findall(r'NSLocalizedString\(\s*@"((?:[^"\\]|\\.)*)"', source)) + self.assertTrue(used) + for language, entries in self.strings.items(): + self.assertEqual(used - entries.keys(), set(), f'{language}: missing launcher keys') + self.assertEqual(entries.keys() - used, set(), f'{language}: unused localization keys') + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/dr3.py b/tools/dr3.py index 9ff95c4..42a71a9 100644 --- a/tools/dr3.py +++ b/tools/dr3.py @@ -18,7 +18,8 @@ COMMIT = '9579030e5b1f0443c12b7376559560915b6d4c4b' PROFILE = ROOT / 'config/diablo3-2.7.7.json' # zh-Hans needs the separate zhCN language DLC; only enUS ships in the pinned base set. -LANG = 'enUS' +LANG = 'system' +LANG_TAGS = ('system', 'en-US', 'zh-Hans') SUFFIXES = ('patched.bin', 'fixups.tsv', 'gates.tsv', 'sites.tsv', 'cuts.tsv', 'obs.tsv', 'params.tsv') @@ -34,6 +35,18 @@ def save(path, value): tmp.replace(path) +def resolve_lang(value): + if value == 'system': + try: + output = subprocess.check_output(['defaults', 'read', '-g', 'AppleLanguages'], + text=True, stderr=subprocess.DEVNULL, timeout=5) + match = re.search(r'^\s*\(?\s*"?([A-Za-z0-9_-]+)"?', output) + value = match.group(1) if match else 'en-US' + except (OSError, subprocess.SubprocessError): + value = 'en-US' + return 'zh-Hans' if value.lower().startswith('zh') else 'en-US' + + def env(): result = {k: v for k, v in os.environ.items() if not k.startswith('DM_')} result.update(DM_ROOT=str(WORK), DM_GAME=TITLE, DM_RULESET='native', DM_PRIVATE_GATES='0') @@ -231,7 +244,7 @@ def launch(args): (WORK / 'run' / name).mkdir(exist_ok=True) settings = dict(DM_ROMFS=str(WORK / 'game/RomFS'), DM_SAVE=str(WORK / 'run/save'), DM_TEMP=str(WORK / 'run/temp'), DM_WINDOW='1', DM_DBG='1', DM_AUDIO='1', - DM_LANG=args.lang, DM_AOC_DIR=str(WORK / 'aoc'), MTL_HUD_ENABLED='1', + DM_LANG=resolve_lang(args.lang), DM_AOC_DIR=str(WORK / 'aoc'), MTL_HUD_ENABLED='1', DM_NVN_SHMAP=str(UPSTREAM / 'dm/games' / TITLE / 'shader_map.tsv'), DM_MSL_DIR=str(WORK / 'build/cache/metal_shader_cache'), DM_PSO_MANIFEST='off', DM_NVN_TBDR='0', DM_NVN_UNIFORM_FORWARD='1', @@ -285,7 +298,7 @@ def main(): prep.add_argument('--keys', type=Path, required=True, help='Your own local keyset; never uploaded or required at runtime') start = commands.add_parser('run') start.add_argument('--seconds', type=int, default=30) - start.add_argument('--lang', default=LANG, help='Game UI language; zh-Hans requires the zhCN DLC pack') + start.add_argument('--lang', choices=LANG_TAGS, default=LANG, help='Game UI language: system, en-US, or zh-Hans; zh-Hans requires the zhCN DLC pack') start.add_argument('--capture-shaders', action='store_true', help='Diagnostic only: missing stages may omit draws') start.add_argument('--keys', help='Timed diagnostic gamepad input using the upstream DM_KEYS syntax') start.add_argument('--inspect-frame', type=int, help='Dump actual pass bindings and render targets') diff --git a/tools/mac-i18n/en.lproj/Localizable.strings b/tools/mac-i18n/en.lproj/Localizable.strings new file mode 100644 index 0000000..962d0c4 --- /dev/null +++ b/tools/mac-i18n/en.lproj/Localizable.strings @@ -0,0 +1,28 @@ +/* DR3 Mobile launcher — English */ +"window.title" = "DR3 Mobile · Launch Settings"; +"menu.quit" = "Quit DR3 Mobile"; +"button.play" = "Play"; +"subtitle" = "Diablo III: Eternal Collection"; +"note.autosave" = "Settings are saved automatically and can be changed next time."; +"save.local" = "Save: local game progress"; +"save.test" = "Save: LAN test copy"; +"section.display" = "Display Mode"; +"mode.normal" = "Normal 16:9"; +"mode.wide" = "Wide"; +"note.display.normal" = "1280×720, original 16:9 field of view."; +"note.display.wide" = "1568×720, wider field of view; the window keeps the image ratio."; +"section.graphics" = "Graphics"; +"toggle.hud" = "Metal HUD"; +"toggle.metalfx" = "MetalFX Upscaling"; +"note.graphics.fx" = "Render at 720p, upscale to 2K with MetalFX; the HUD shows frame rate and GPU data."; +"note.graphics.direct" = "Render at 720p directly to the window; the HUD shows frame rate and GPU data."; +"section.lan" = "Local Network"; +"toggle.lan" = "Local Wi-Fi Multiplayer"; +"note.lan" = "Connect both devices to the same Wi-Fi, then create or join a local game in-game."; +"section.language" = "Game Language"; +"lang.system" = "System"; +"lang.en" = "English"; +"lang.zh" = "简体中文"; +"note.language" = "Sets the default language for new profiles. An existing save's Settings.json language takes precedence."; +"alert.failed.title" = "Game failed to launch"; +"alert.failed.body" = "Check the local game files and try again."; diff --git a/tools/mac-i18n/zh-Hans.lproj/Localizable.strings b/tools/mac-i18n/zh-Hans.lproj/Localizable.strings new file mode 100644 index 0000000..e692ced --- /dev/null +++ b/tools/mac-i18n/zh-Hans.lproj/Localizable.strings @@ -0,0 +1,28 @@ +/* DR3 Mobile 启动器 — 简体中文 */ +"window.title" = "DR3 Mobile · 启动设置"; +"menu.quit" = "退出 DR3 Mobile"; +"button.play" = "开始游戏"; +"subtitle" = "暗黑破坏神 III · 永恒之战版"; +"note.autosave" = "设置会自动保存,下次打开可重新选择。"; +"save.local" = "存档:本机游戏进度"; +"save.test" = "存档:联机测试副本"; +"section.display" = "画面模式"; +"mode.normal" = "正常 16:9"; +"mode.wide" = "宽屏"; +"note.display.normal" = "1280×720,保留原版 16:9 视野。"; +"note.display.wide" = "1568×720,扩大左右视野;窗口保持画面比例。"; +"section.graphics" = "图形选项"; +"toggle.hud" = "Metal HUD"; +"toggle.metalfx" = "MetalFX 超分"; +"note.graphics.fx" = "720p 渲染,MetalFX 超分至 2K;HUD 显示帧率与 GPU 数据。"; +"note.graphics.direct" = "720p 渲染,直接适配窗口;HUD 显示帧率与 GPU 数据。"; +"section.lan" = "局域网"; +"toggle.lan" = "本地 Wi-Fi 联机"; +"note.lan" = "两台设备连接同一 Wi-Fi,在游戏内创建或加入本地游戏。"; +"section.language" = "游戏语言"; +"lang.system" = "跟随系统"; +"lang.en" = "English"; +"lang.zh" = "简体中文"; +"note.language" = "设置新存档的默认语言;已有存档的 Settings.json 语言设置优先。"; +"alert.failed.title" = "游戏未能启动"; +"alert.failed.body" = "请检查本机游戏资源后重试。"; diff --git a/tools/mac_app.py b/tools/mac_app.py index 781907a..7a6cdb6 100644 --- a/tools/mac_app.py +++ b/tools/mac_app.py @@ -4,6 +4,7 @@ import json from pathlib import Path import plistlib +import re import shutil import subprocess import time @@ -11,6 +12,38 @@ from app_icons import mac_icns from mobile_graphics_profile import launch_directory, verify +LANGUAGES = ('en', 'zh-Hans') + + +def strings_keys(path): + keys = {} + for number, line in enumerate(path.read_text(encoding='utf-8-sig').splitlines(), 1): + text = line.strip() + if not text or text.startswith('/*') or text.startswith('//'): + continue + match = re.fullmatch(r'"((?:[^"\\]|\\.)*)"\s*=\s*"((?:[^"\\]|\\.)*)"\s*;', text) + if not match: + raise ValueError(f'{path}:{number}: malformed localization entry') + key, value = match.groups() + if not value: + raise ValueError(f'{path}:{number}: empty value for {key!r}') + keys[key] = value + return keys + + +def check_localizations(): + files = {} + for language in LANGUAGES: + path = ROOT / 'tools/mac-i18n' / f'{language}.lproj' / 'Localizable.strings' + if not path.is_file(): + raise ValueError(f'Missing localization file: {path}') + files[language] = strings_keys(path) + if files['en'].keys() != files['zh-Hans'].keys(): + missing = sorted(files['en'].keys() - files['zh-Hans'].keys()) + extra = sorted(files['zh-Hans'].keys() - files['en'].keys()) + raise ValueError(f'Localization key sets differ; absent from zh-Hans: {missing}; absent from en: {extra}') + return files + def main(): parser = argparse.ArgumentParser(description=__doc__) @@ -20,6 +53,7 @@ def main(): if args.test_session: args.test_session=args.test_session.resolve(strict=True) if not (args.test_session/'save/account.dat').is_file():raise ValueError('Test session requires an existing save copy') + localizations = check_localizations() check_modules() verification = json.loads((WORK / 'verification.json').read_text()) if not verification['passed'] or verification['artifacts'] != fingerprints() or verification['profile_sha256'] != sha(PROFILE): @@ -43,6 +77,8 @@ def main(): resources = stage / 'Contents/Resources' mac.mkdir(parents=True) resources.mkdir() + for language in localizations: + shutil.copytree(ROOT / 'tools/mac-i18n' / f'{language}.lproj', resources / f'{language}.lproj') mac_icns(WORK/'game/icon.jpg',resources/'AppIcon.icns',WORK/'build/app-icons') shutil.copy2(host, mac / 'dmhost') shutil.copytree(WORK / 'rewrite', resources / 'rewrite', ignore=shutil.ignore_patterns('*.log', '*.orig.bin')) @@ -57,6 +93,7 @@ def main(): ignore=shutil.ignore_patterns('*.metal', '*.air', '*.spv')) info = {'CFBundleName': 'DR3 Mobile', 'CFBundleDisplayName': 'DR3 Mobile', 'CFBundleIdentifier': 'com.enginefuture.dr3-mobile', 'CFBundleExecutable': 'DR3Mobile', + 'CFBundleDevelopmentRegion': 'en', 'CFBundleLocalizations': ['en', 'zh-Hans'], 'CFBundlePackageType': 'APPL', 'CFBundleShortVersionString': '0.1.0', 'CFBundleIconFile': 'AppIcon.icns', 'CFBundleVersion': '3', 'NSLocalNetworkUsageDescription': '用于发现并加入同一 Wi-Fi 内的暗黑破坏神 III 游戏。', 'NSBonjourServices': ['_dr3lan._udp'], 'LSMinimumSystemVersion': '26.0', 'NSHighResolutionCapable': True} diff --git a/tools/mac_launcher.m b/tools/mac_launcher.m index 3a28cad..a13d3cf 100644 --- a/tools/mac_launcher.m +++ b/tools/mac_launcher.m @@ -38,6 +38,7 @@ @interface DR3Launcher : NSObject @property(strong) NSWindow *window; @property(strong) NSSegmentedControl *mode; @property(strong) NSButton *hud,*fx,*lan,*play; +@property(strong) NSPopUpButton *language; @property(strong) NSTextField *displayNote,*graphicsNote; @property BOOL starting; @end @@ -51,33 +52,42 @@ - (void)applicationDidFinishLaunching:(NSNotification *)note { (void)note; NSMenu *menu=[NSMenu new];NSMenuItem *applicationItem=[NSMenuItem new];[menu addItem:applicationItem]; NSMenu *applicationMenu=[[NSMenu alloc] initWithTitle:@"DR3 Mobile"]; - NSMenuItem *quit=[[NSMenuItem alloc] initWithTitle:@"退出 DR3 Mobile" action:@selector(terminate:) keyEquivalent:@"q"]; + NSMenuItem *quit=[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"menu.quit",nil) action:@selector(terminate:) keyEquivalent:@"q"]; quit.target=NSApp;[applicationMenu addItem:quit];applicationItem.submenu=applicationMenu;NSApp.mainMenu=menu; - [NSUserDefaults.standardUserDefaults registerDefaults:@{@"LaunchWide":@NO,@"LaunchMetalHUD":@YES,@"LaunchMetalFX":@YES,@"LaunchLocalLAN":@YES}]; - self.window=[[NSWindow alloc] initWithContentRect:NSMakeRect(0,0,760,470) + [NSUserDefaults.standardUserDefaults registerDefaults:@{@"LaunchWide":@NO,@"LaunchMetalHUD":@YES,@"LaunchMetalFX":@YES,@"LaunchLocalLAN":@YES,@"LaunchLanguage":@"system"}]; + self.window=[[NSWindow alloc] initWithContentRect:NSMakeRect(0,0,760,610) styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; - self.window.title=@"DR3 Mobile · 启动设置";self.window.delegate=self;self.window.contentMinSize=NSMakeSize(700,450); + self.window.title=NSLocalizedString(@"window.title",nil);self.window.delegate=self;self.window.contentMinSize=NSMakeSize(700,580); NSImageView *icon=[NSImageView imageViewWithImage:[[NSImage alloc] initWithContentsOfFile:[g_resources stringByAppendingPathComponent:@"AppIcon.icns"]]]; [icon.widthAnchor constraintEqualToConstant:96].active=YES;[icon.heightAnchor constraintEqualToConstant:96].active=YES; NSTextField *title=label(@"DR3 Mobile",28,NO);title.font=[NSFont systemFontOfSize:28 weight:NSFontWeightSemibold]; - self.play=[NSButton buttonWithTitle:@"开始游戏" target:self action:@selector(start:)];self.play.bezelStyle=NSBezelStyleRounded; + self.play=[NSButton buttonWithTitle:NSLocalizedString(@"button.play",nil) target:self action:@selector(start:)];self.play.bezelStyle=NSBezelStyleRounded; self.play.controlSize=NSControlSizeLarge;self.play.keyEquivalent=@"\r";self.play.identifier=@"start-game"; [self.play.widthAnchor constraintGreaterThanOrEqualToConstant:190].active=YES; - NSStackView *left=column(@[icon,title,label(@"暗黑破坏神 III · 永恒之战版",12,YES),self.play, - label(@"设置会自动保存,下次打开可重新选择。",12,YES), - label(g_testSession?@"存档:联机测试副本":@"存档:本机游戏进度",12,YES)],16); - self.mode=[NSSegmentedControl segmentedControlWithLabels:@[@"正常 16:9",@"宽屏"] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(changed:)]; + NSStackView *left=column(@[icon,title,label(NSLocalizedString(@"subtitle",nil),12,YES),self.play, + label(NSLocalizedString(@"note.autosave",nil),12,YES), + label(g_testSession?NSLocalizedString(@"save.test",nil):NSLocalizedString(@"save.local",nil),12,YES)],16); + self.mode=[NSSegmentedControl segmentedControlWithLabels:@[NSLocalizedString(@"mode.normal",nil),NSLocalizedString(@"mode.wide",nil)] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(changed:)]; self.mode.selectedSegment=[NSUserDefaults.standardUserDefaults boolForKey:@"LaunchWide"]?1:0;self.mode.identifier=@"display-mode"; [self.mode setEnabled:[NSFileManager.defaultManager fileExistsAtPath:[g_resources stringByAppendingPathComponent:@"rewrite-wide/main.patched.bin"]] forSegment:1]; if(![self.mode isEnabledForSegment:1])self.mode.selectedSegment=0; self.displayNote=label(@"",12,YES);self.graphicsNote=label(@"",12,YES); - self.hud=[self toggle:@"Metal HUD" key:@"LaunchMetalHUD"]; - self.fx=[self toggle:@"MetalFX 超分" key:@"LaunchMetalFX"]; - self.lan=[self toggle:@"本地 Wi-Fi 联机" key:@"LaunchLocalLAN"]; - NSStackView *right=column(@[section(@"画面模式",@[self.mode,self.displayNote]), - section(@"图形选项",@[self.hud,self.fx,self.graphicsNote]), - section(@"局域网",@[self.lan,label(@"两台设备连接同一 Wi-Fi,在游戏内创建或加入本地游戏。",12,YES)])],14); + self.hud=[self toggle:NSLocalizedString(@"toggle.hud",nil) key:@"LaunchMetalHUD"]; + self.fx=[self toggle:NSLocalizedString(@"toggle.metalfx",nil) key:@"LaunchMetalFX"]; + self.lan=[self toggle:NSLocalizedString(@"toggle.lan",nil) key:@"LaunchLocalLAN"]; + self.language=[NSPopUpButton new]; + // NSMenuItem tags are integers, so each Switch language tag lives in representedObject. + [self.language addItemWithTitle:NSLocalizedString(@"lang.system",nil)];self.language.lastItem.representedObject=@"system"; + [self.language addItemWithTitle:NSLocalizedString(@"lang.en",nil)];self.language.lastItem.representedObject=@"en-US"; + [self.language addItemWithTitle:NSLocalizedString(@"lang.zh",nil)];self.language.lastItem.representedObject=@"zh-Hans"; + self.language.identifier=@"LaunchLanguage";self.language.target=self;self.language.action=@selector(changed:); + NSString *language=[NSUserDefaults.standardUserDefaults stringForKey:@"LaunchLanguage"]; + for(NSMenuItem *item in self.language.itemArray)if([item.representedObject isEqual:language])[self.language selectItem:item]; + NSStackView *right=column(@[section(NSLocalizedString(@"section.display",nil),@[self.mode,self.displayNote]), + section(NSLocalizedString(@"section.graphics",nil),@[self.hud,self.fx,self.graphicsNote]), + section(NSLocalizedString(@"section.lan",nil),@[self.lan,label(NSLocalizedString(@"note.lan",nil),12,YES)]), + section(NSLocalizedString(@"section.language",nil),@[self.language,label(NSLocalizedString(@"note.language",nil),12,YES)])],14); for(NSView *v in right.arrangedSubviews)[v.widthAnchor constraintEqualToAnchor:right.widthAnchor].active=YES; NSStackView *content=[NSStackView stackViewWithViews:@[left,right]];content.orientation=NSUserInterfaceLayoutOrientationHorizontal; content.alignment=NSLayoutAttributeTop;content.distribution=NSStackViewDistributionFill;content.spacing=30;content.translatesAutoresizingMaskIntoConstraints=NO; @@ -94,8 +104,9 @@ - (void)changed:(id)sender { (void)sender;NSUserDefaults *d=NSUserDefaults.standardUserDefaults; [d setBool:self.mode.selectedSegment==1 forKey:@"LaunchWide"]; for(NSButton *b in @[self.hud,self.fx,self.lan])[d setBool:b.state==NSControlStateValueOn forKey:b.identifier]; - self.displayNote.stringValue=self.mode.selectedSegment==1?@"1568×720,扩大左右视野;窗口保持画面比例。":@"1280×720,保留原版 16:9 视野。"; - self.graphicsNote.stringValue=self.fx.state==NSControlStateValueOn?@"720p 渲染,MetalFX 超分至 2K;HUD 显示帧率与 GPU 数据。":@"720p 渲染,直接适配窗口;HUD 显示帧率与 GPU 数据。"; + [d setObject:self.language.selectedItem.representedObject forKey:@"LaunchLanguage"]; + self.displayNote.stringValue=self.mode.selectedSegment==1?NSLocalizedString(@"note.display.wide",nil):NSLocalizedString(@"note.display.normal",nil); + self.graphicsNote.stringValue=self.fx.state==NSControlStateValueOn?NSLocalizedString(@"note.graphics.fx",nil):NSLocalizedString(@"note.graphics.direct",nil); } - (void)start:(id)sender { (void)sender;if(self.starting)return;self.starting=YES;self.play.enabled=NO; @@ -113,19 +124,22 @@ - (void)start:(id)sender { path_env("DM_SAVE",g_runRoot,@"save");path_env("DM_TEMP",g_runRoot,@"temp");path_env("DM_HID_RECEIPT_LOG",g_runRoot,@"controller.jsonl"); path_env("DM_PAD_EVENT_LOG",g_runRoot,@"controller-events.jsonl");path_env("DM_NVN_TSV",g_runRoot,@"performance.tsv"); path_env("DM_NVN_SHMAP",g_resources,@"game/shader_map.tsv");path_env("DM_MSL_DIR",g_resources,@"shaders"); - // zh-Hans needs the separate zhCN DLC pack; the shipped base set is enUS. - setenv("DM_WINDOW","1",1);setenv("DM_AUDIO","1",1);setenv("DM_LANG","enUS",1);setenv("DM_OPMODE","0",1); + // DM_LANG seeds new profiles; an existing save's Settings.json Language wins. + NSString *language=self.language.selectedItem.representedObject; + if([language isEqualToString:@"system"])language=NSLocale.preferredLanguages.firstObject?:@"en-US"; + language=[language.lowercaseString hasPrefix:@"zh"]?@"zh-Hans":@"en-US"; + setenv("DM_WINDOW","1",1);setenv("DM_AUDIO","1",1);setenv("DM_LANG",language.UTF8String,1);setenv("DM_OPMODE","0",1); setenv("DM_HID_RECEIPT_LIMIT","65536",1);setenv("DM_NVN_TSV_CALLS","0",1);setenv("DM_NVN_UNIFORM_FORWARD","1",1); setenv("DM_NVN_TBDR","0",1);setenv("DM_PSO_MANIFEST","off",1); setenv("MTL_HUD_ENABLED",self.hud.state==NSControlStateValueOn?"1":"0",1); setenv("DM_METALFX",fx?"spatial":"off",1);setenv("DM_MAC_DISPLAY_MODE",wide?"wide":"normal",1); setenv("DM_DR3_LAN",self.lan.state==NSControlStateValueOn?"1":"0",1); [NSUserDefaults.standardUserDefaults synchronize]; - fprintf(stderr,"launch: mode=%s HUD=%s MetalFX=%s LAN=%s save=%s\n",wide?"wide":"normal",getenv("MTL_HUD_ENABLED"),getenv("DM_METALFX"),getenv("DM_DR3_LAN"),g_testSession?"test-copy":"local"); + fprintf(stderr,"launch: mode=%s HUD=%s MetalFX=%s LAN=%s lang=%s save=%s\n",wide?"wide":"normal",getenv("MTL_HUD_ENABLED"),getenv("DM_METALFX"),getenv("DM_DR3_LAN"),getenv("DM_LANG"),g_testSession?"test-copy":"local"); char *args[]={(char *)binary.fileSystemRepresentation,(char *)rewrite.fileSystemRepresentation,"main","sdk",NULL}; execv(args[0],args);[NSException raise:@"Launch failed" format:@"%s",strerror(errno)]; } @catch(NSException *e) { - NSAlert *alert=[NSAlert new];alert.messageText=@"游戏未能启动";alert.informativeText=e.reason?:@"请检查本机游戏资源后重试。";[alert runModal]; + NSAlert *alert=[NSAlert new];alert.messageText=NSLocalizedString(@"alert.failed.title",nil);alert.informativeText=e.reason?:NSLocalizedString(@"alert.failed.body",nil);[alert runModal]; self.starting=NO;self.play.enabled=YES; } } diff --git a/tools/smoke_mac.py b/tools/smoke_mac.py index 3c2bdbb..84636b1 100644 --- a/tools/smoke_mac.py +++ b/tools/smoke_mac.py @@ -7,7 +7,7 @@ import statistics import subprocess import time -from dr3 import WORK, LANG, env, check_modules, profile, sha, save +from dr3 import WORK, LANG, resolve_lang, env, check_modules, profile, sha, save def save_files(directory): @@ -31,7 +31,7 @@ def main(): directory.mkdir();shutil.copytree(original,directory/'save');(directory/'temp').mkdir() control=directory/'control.txt';control.write_text('1 1\n') settings=dict(DM_ROMFS=str(WORK/'game/RomFS'),DM_SAVE=str(directory/'save'),DM_TEMP=str(directory/'temp'), - DM_AOC_DIR=str(WORK/'aoc'),DM_LANG=LANG,DM_OPMODE=args.opmode,DM_NVN_TBDR='0',DM_PSO_MANIFEST='off', + DM_AOC_DIR=str(WORK/'aoc'),DM_LANG=resolve_lang(LANG),DM_OPMODE=args.opmode,DM_NVN_TBDR='0',DM_PSO_MANIFEST='off', DM_NVN_SHMAP=str(resources/'game/shader_map.tsv'),DM_MSL_DIR=str(resources/'shaders'), DM_NVN_UNIFORM_FORWARD='1',DM_NVN_UNIFORM_FORWARD_CONTROL=str(control), DM_NVN_TSV=str(directory/'performance.tsv'),DM_NVN_TSV_CALLS='0',DM_KEYS=args.keys, From 1b106281ae8a41d5a87f5a34417cc28c2473f297 Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:15:37 +0100 Subject: [PATCH 03/13] Enable offline seasonal heroes on 2.7.7 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Retarget d3hack v3.1's always-on dynamic-seasonal set from 2.7.6.90885 to 2.7.7.92380 with dm/tools/nso_fnmap.py plus per-site disassembly: five equal-length patches, originals asserted by the rewriter. d3hack's spawn gate (site 10) is deliberately excluded — arming it unconditionally made every hero hang on world entry — and its XVar writes cannot be done statically (0x72eea0's x1 is a pointer, not the value). Also adds two env-gated diagnostic switches used while chasing that hang: DM_DR3_NSA (fake network service account) and DM_DR3_PCTL (grant free-communication permission). Both are D3-only and inert without the environment variable. --- patches/nxnative.patch | 103 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 96 insertions(+), 7 deletions(-) diff --git a/patches/nxnative.patch b/patches/nxnative.patch index a46af46..f15da5a 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -1829,9 +1829,17 @@ index 1a63bd7..9fcffec 100644 // ---------- Host gate dispatch ---------- diff --git a/dm/host/hle_account.c b/dm/host/hle_account.c -index 362a6c2..61dbe98 100644 +index 362a6c2..b32be1e 100644 --- a/dm/host/hle_account.c +++ b/dm/host/hle_account.c +@@ -1,6 +1,6 @@ + // nn::account: the real device manages users via the acc:u0 service; the host has one fixed local user. + // Online accounts (network service account / Nintendo Account authorization / tokens) are out of scope and uniformly return RES_FAIL; the async context's completion event fires immediately. +-// Environment switch: DM_NICK=nickname (default Player). ++// Environment switch: DM_NICK=nickname (default Player); DM_DR3_NSA=1 spoofs a network service account (D3 only, for diagnosing the online-session bootstrap). + #include "hle.h" + + typedef struct { uint64_t v[2]; } Uid; // nn::account::Uid, 16 bytes @@ -30,6 +30,13 @@ HLE_FORCE("_ZN2nn7account12PopOpenUsersEPiPNS0_10UserHandleEi", "系统代开的 HLE_FORCE("_ZN2nn7account22TryOpenPreselectedUserEPNS0_10UserHandleE", "启动时预选用户;恒为本地用户(返回 bool)", unsigned, h_acc_TryOpenPre, UserHandle *h) { h->v[0] = k_uid.v[0]; h->v[1] = k_uid.v[1]; h->v[2] = HANDLE_MAGIC; return 1; @@ -1846,6 +1854,51 @@ index 362a6c2..61dbe98 100644 HLE_FORCE("_ZN2nn7account8OpenUserEPNS0_10UserHandleERKNS0_3UidE", "打开用户;句柄内直接存 Uid", Result, h_acc_OpenUser, UserHandle *h, const Uid *uid) { h->v[0] = uid->v[0]; h->v[1] = uid->v[1]; h->v[2] = HANDLE_MAGIC; return RES_OK; } +@@ -46,16 +53,30 @@ HLE_FORCE("_ZN2nn7account11GetNicknameEPNS0_8NicknameERKNS0_3UidE", "用户昵 + } + + // ---------- Online accounts: cut ---------- +-HLE_FORCE("_ZN2nn7account36EnsureNetworkServiceAccountAvailableERKNS0_10UserHandleE", "网络服务账号,排除范围;剪口:恒不可用", Result, h_acc_EnsureNsa, const UserHandle *h) { (void)h; return RES_FAIL; } +-HLE_FORCE("_ZN2nn7account26GetNetworkServiceAccountIdEPNS0_23NetworkServiceAccountIdERKNS0_10UserHandleE", "网络服务账号,排除范围;剪口", Result, h_acc_GetNsaId, void *id, const UserHandle *h) { (void)id; (void)h; return RES_FAIL; } +-HLE_FORCE("_ZN2nn7account37LoadNetworkServiceAccountIdTokenCacheEPmPcmRKNS0_10UserHandleE", "网络服务账号令牌,排除范围;剪口", Result, h_acc_LoadTok, uint64_t *n, char *buf, uint64_t sz, const UserHandle *h) { +- (void)buf; (void)sz; (void)h; if (n) *n = 0; return RES_FAIL; ++// D3-only experiment: the world-load hang may be the online-session bootstrap, so this switch fakes a network service account; every other build stays fail-closed. ++#if DM_GAME_PROGRAM_ID == 0x01001B300B9BE000ull ++static int d3_nsa(void) { const char *e = getenv("DM_DR3_NSA"); return e && atoi(e) != 0; } ++#else ++static int d3_nsa(void) { return 0; } ++#endif ++HLE_FORCE("_ZN2nn7account36EnsureNetworkServiceAccountAvailableERKNS0_10UserHandleE", "网络服务账号,排除范围;剪口:恒不可用(DM_DR3_NSA=1 时伪造成可用)", Result, h_acc_EnsureNsa, const UserHandle *h) { (void)h; return d3_nsa() ? RES_OK : RES_FAIL; } ++HLE_FORCE("_ZN2nn7account26GetNetworkServiceAccountIdEPNS0_23NetworkServiceAccountIdERKNS0_10UserHandleE", "网络服务账号,排除范围;剪口(DM_DR3_NSA=1 时给固定非零 id)", Result, h_acc_GetNsaId, void *id, const UserHandle *h) { ++ (void)h; ++ if (!d3_nsa()) { (void)id; return RES_FAIL; } ++ // Fixed non-zero id: the guest only checks that an account exists, it never compares it with a server value. ++ memset(id, 0, 16); *(uint8_t *)id = 1; return RES_OK; ++} ++HLE_FORCE("_ZN2nn7account37LoadNetworkServiceAccountIdTokenCacheEPmPcmRKNS0_10UserHandleE", "网络服务账号令牌,排除范围;剪口(DM_DR3_NSA=1 时为空令牌)", Result, h_acc_LoadTok, uint64_t *n, char *buf, uint64_t sz, const UserHandle *h) { ++ (void)h; if (n) *n = 0; ++ // Empty token, never a fabricated JWT: the host cannot mint or verify one. ++ if (!d3_nsa()) { (void)buf; (void)sz; return RES_FAIL; } ++ if (buf && sz) buf[0] = 0; return RES_OK; + } + HLE_FORCE("_ZN2nn7account40ShowLicenseRequirementsForNetworkServiceERKNS0_10UserHandleE", "联网会员提示小程序,排除范围;剪口", Result, h_acc_ShowLic, const UserHandle *h) { (void)h; return RES_FAIL; } + + // AsyncContext / NintendoAccountAuthorizationRequestContext: object contents are read and written only by the interfaces below; construction writes no memory, the completion event fires immediately, and the result is always failure + HLE_FORCE("_ZN2nn7account12AsyncContextC1Ev", "异步上下文构造;宿主不建 IPC 对象", void, h_acc_AcCtor, void *self) { (void)self; } +-HLE_FORCE("_ZN2nn7account44EnsureNetworkServiceAccountIdTokenCacheAsyncEPNS0_12AsyncContextERKNS0_10UserHandleE", "网络服务账号令牌,排除范围;剪口", Result, h_acc_EnsureTokAsync, void *ctx, const UserHandle *h) { (void)ctx; (void)h; return RES_FAIL; } ++HLE_FORCE("_ZN2nn7account44EnsureNetworkServiceAccountIdTokenCacheAsyncEPNS0_12AsyncContextERKNS0_10UserHandleE", "网络服务账号令牌,排除范围;剪口(DM_DR3_NSA=1 时直接成功,完成事件已立即触发)", Result, h_acc_EnsureTokAsync, void *ctx, const UserHandle *h) { (void)ctx; (void)h; return d3_nsa() ? RES_OK : RES_FAIL; } + HLE_FORCE("_ZN2nn7account12AsyncContext14GetSystemEventEPNS_2os11SystemEventE", "异步完成事件;立即触发", Result, h_acc_AcGetEv, void *self, void *ev) { (void)self; hle_signal_system_event(ev); return RES_OK; } + HLE_FORCE("_ZN2nn7account12AsyncContext9GetResultEv", "异步结果;联网已剪,恒失败", Result, h_acc_AcGetRes, void *self) { (void)self; return RES_FAIL; } + HLE_FORCE("_ZN2nn7account42NintendoAccountAuthorizationRequestContextC1Ev", "任天堂账号授权,排除范围;构造不写内存", void, h_acc_NaCtor, void *self) { (void)self; } +@@ -82,7 +103,7 @@ HLE_FORCE("_ZN2nn7account15ShowUserCreatorEv", "新建用户小程序;宿主 + HLE_FORCE("_ZN2nn7account16LoadProfileImageEPmPvmRKNS0_3UidE", "用户头像;宿主没有(失败)", Result, h_acc_LoadImage, uint64_t *n, void *buf, uint64_t sz, const Uid *uid) { + (void)buf; (void)sz; (void)uid; if (n) *n = 0; return RES_FAIL; + } +-HLE_FORCE("_ZN2nn7account32IsNetworkServiceAccountAvailableEPbRKNS0_10UserHandleE", "网络服务账号,排除范围;恒不可用", Result, h_acc_NsaAvail, uint8_t *out, const UserHandle *h) { (void)h; *out = 0; return RES_OK; } ++HLE_FORCE("_ZN2nn7account32IsNetworkServiceAccountAvailableEPbRKNS0_10UserHandleE", "网络服务账号,排除范围;恒不可用(DM_DR3_NSA=1 时为真)", Result, h_acc_NsaAvail, uint8_t *out, const UserHandle *h) { (void)h; *out = (uint8_t)d3_nsa(); return RES_OK; } + HLE_FORCE("_ZN2nn7account9CloseUserERKNS0_10UserHandleE", "关闭用户;句柄里没有会话", void, h_acc_CloseUser, const UserHandle *h) { (void)h; } + HLE_FORCE("_ZN2nn7account12AsyncContext6CancelEv", "异步上下文取消;无请求", Result, h_acc_AcCancel, void *self) { (void)self; return RES_OK; } + HLE_FORCE("_ZN2nn7account12AsyncContext7HasDoneEPb", "异步上下文:恒已完成", Result, h_acc_AcHasDone, void *self, uint8_t *done) { (void)self; *done = 1; return RES_OK; } diff --git a/dm/host/hle_audio.c b/dm/host/hle_audio.c index 3d309a1..ec44a2c 100644 --- a/dm/host/hle_audio.c @@ -2791,19 +2844,35 @@ index 0000000..d90be06 +void dm_lan_freeaddrinfo(void*value){guest_ai*a=value;while(a){guest_ai*next=a->next;free(a);a=next;}} +void*dm_lan_gethostbyname(const char*host){static __thread struct {char*name;char**aliases;int type,length;char**addresses;} entry;static __thread char name[64],*aliases[1],*addresses[2];static __thread struct in_addr ip;if(!host)return NULL;if(!strcmp(host,"localhost"))ip.s_addr=htonl(INADDR_LOOPBACK);else if(inet_pton(AF_INET,host,&ip)!=1){socket_error=guest_errno(ENOENT);return NULL;}if(!dm_lan_peer_allowed(ip.s_addr,0)){socket_error=guest_errno(EACCES);return NULL;}snprintf(name,sizeof(name),"%s",host);aliases[0]=NULL;addresses[0]=(char*)&ip;addresses[1]=NULL;entry.name=name;entry.aliases=aliases;entry.type=AF_INET;entry.length=4;entry.addresses=addresses;return &entry;} diff --git a/dm/host/hle_misc.c b/dm/host/hle_misc.c -index 5f86515..ea4cf72 100644 +index 5f86515..b837763 100644 --- a/dm/host/hle_misc.c +++ b/dm/host/hle_misc.c -@@ -91,6 +91,9 @@ HLE_FORCE("_ZN2nn3ngc15ProfanityFilter19CheckProfanityWordsEPjjPPKcm", "敏感 +@@ -88,13 +88,23 @@ HLE_FORCE("_ZN2nn3ngc15ProfanityFilter19CheckProfanityWordsEPjjPPKcm", "敏感 + } + + // ---------- nsd server name resolution / pctl free communication: networking, out of scope ---------- ++// D3-only experiment: the world-load hang may be the online bootstrap; DM_DR3_PCTL=1 reports the parental-control free-communication permission as granted. ++// Every other build keeps the offline policy (0) at compile time. ++#if DM_GAME_PROGRAM_ID == 0x01001B300B9BE000ull ++static int d3_pctl(void) { const char *e = getenv("DM_DR3_PCTL"); return e && atoi(e) != 0; } ++#else ++static int d3_pctl(void) { return 0; } ++#endif HLE_FORCE("_ZN2nn3nsd7ResolveEPNS0_4FqdnERKS1_", "服务器名解析,联网排除;剪口", Result, h_nsd_Resolve, void *out, const void *in) { (void)out; (void)in; return RES_FAIL; } HLE_FORCE("_ZN2nn3nsd9ResolveExEPNS0_4FqdnERKS1_", "服务器名解析,联网排除;剪口", Result, h_nsd_ResolveEx, void *out, const void *in) { (void)out; (void)in; return RES_FAIL; } // bool arguments only look at the low 8 bits; returns bool +-HLE_FORCE("_ZN2nn4pctl25TryBeginFreeCommunicationEb", "家长控制·与他人通信,联网排除;恒不允许", unsigned, h_pctl_TryBegin, unsigned show_ui) { (void)show_ui; return 0; } +// SDK 8 / D3 calls this query before its network startup (sdk+0x33a620). +// Match the host's existing offline communication policy; the result is bool. -+HLE_FORCE("_ZN2nn4pctl32CheckFreeCommunicationPermissionEb", "Offline communication permission query", unsigned, h_pctl_CheckFree, unsigned show_ui) { (void)show_ui; return 0; } - HLE_FORCE("_ZN2nn4pctl25TryBeginFreeCommunicationEb", "家长控制·与他人通信,联网排除;恒不允许", unsigned, h_pctl_TryBegin, unsigned show_ui) { (void)show_ui; return 0; } ++HLE_FORCE("_ZN2nn4pctl32CheckFreeCommunicationPermissionEb", "Offline communication permission query", unsigned, h_pctl_CheckFree, unsigned show_ui) { (void)show_ui; return d3_pctl() ? 1u : 0u; } ++HLE_FORCE("_ZN2nn4pctl25TryBeginFreeCommunicationEb", "家长控制·与他人通信,联网排除;恒不允许", unsigned, h_pctl_TryBegin, unsigned show_ui) { (void)show_ui; return d3_pctl() ? 1u : 0u; } HLE_FORCE("_ZN2nn4pctl20EndFreeCommunicationEv", "家长控制·与他人通信", void, h_pctl_End, void) {} // Engage asks on entering a battle map (no UI); without this the SDK connects to the pctl service through sm, which the host does not have, and aborts +-HLE_FORCE("_ZN2nn4pctl28IsFreeCommunicationAvailableEv", "家长控制·与他人通信可用否,联网排除;恒否", unsigned, h_pctl_IsFree, void) { return 0; } ++HLE_FORCE("_ZN2nn4pctl28IsFreeCommunicationAvailableEv", "家长控制·与他人通信可用否,联网排除;恒否", unsigned, h_pctl_IsFree, void) { return d3_pctl() ? 1u : 0u; } + // The Legend of Zelda: Breath of the Wild: checks the parental-control permission for stereoscopic 3D before VR-related screens (returns bool; the argument = whether to show UI, the game passes 0). The host has no parental controls: permitted + HLE_FORCE("_ZN2nn4pctl27CheckStereoVisionPermissionEb", "家长控制·3D 立体显示许可;宿主无家长控制,允许", unsigned, h_pctl_Stereo, unsigned show_ui) { (void)show_ui; return 1; } + diff --git a/dm/host/hle_net.c b/dm/host/hle_net.c index 234d762..672dfa6 100644 --- a/dm/host/hle_net.c @@ -3092,10 +3161,30 @@ index e237a24..2fe8d62 100644 int front = m->patch_off < 0; if (z0 + zw != (front ? m->file_image_len : (uint64_t)m->patch_off) || (z0 & 0x3FFF) || (zw & 0x3FFF) || (z1 & 0x3FFF) || ((uintptr_t)x0 & 0x3FFF) || ((uintptr_t)w & 0x3FFF) || ((uintptr_t)x1 & 0x3FFF)) diff --git a/dm/tools/patch_nso.py b/dm/tools/patch_nso.py -index 837700c..4cb657c 100644 +index 837700c..bdc2849 100644 --- a/dm/tools/patch_nso.py +++ b/dm/tools/patch_nso.py -@@ -680,7 +680,12 @@ for a in sorted(kinds): +@@ -46,6 +46,19 @@ else: + # Networking cuts (excluded scope: Battle.net / online play): taken from a community offline fix (LFS Mod Offline Fix for v2228224, which differs from the official 94012 main in only these 7 words). + # Measured: the system service layer (nifm offline / DNS black hole / account service) cannot get around it: the game itself sends Battle.net requests directly and allows offline play according to the "last online" time. + CUTS = { ++ # Diablo III 2.7.7 (main 2607a74f): the always-on part of d3hack v3.1's dynamic-seasonal set (its table is ++ # pinned to 2.7.6.90885). Offsets carried over with dm/tools/nso_fnmap.py and each site re-checked against ++ # 2.7.7. Season number 37 = the account's last online season. ++ # Sites 01/02 (XVar season number/state) are NOT patchable this way: at 0x72eea0 x1 is a pointer, not the ++ # value (patching it crashed at 0xa272f4 dereferencing 37+0x18); the game already passes 37 there. d3hack site 10 ++ # (the spawn gate) is deliberately NOT applied: arming it unconditionally made non-seasonal heroes hang. ++ '2607a74f5df7754cc0357b5df7e49693': [ ++ (0x351ccc, '81010054', '21008052', 'd3hack dynamic_seasonal_03:bSeasonConfirmedAvailable 的 b.ne → movz w1,#1,函数体总是带「已确认」执行'), ++ (0x5ff0c, '00010012', '20008052', 'd3hack dynamic_seasonal_04:IsSeasonsInitialized 的 and w0,w8,#1 → movz w0,#1,恒为真'), ++ (0x1bd140, '159140b9', 'b5048052', 'd3hack dynamic_seasonal_05:season_created 的 ldr w21,[x8,#0x90] → movz w21,#37'), ++ (0x1bf5f0, 'ff0304d1', '00008052', 'd3hack dynamic_seasonal_08:ValidateHeroForPartyMember 的 sub sp,sp,#0x100 → movz w0,#0,返回 error_none'), ++ (0x1bf5f4, 'f76300f9', 'c0035fd6', 'd3hack dynamic_seasonal_09:紧随其后的 str x23,[sp,#0xc0] → ret,跳过函数体'), ++ ], + # Super Mario Bros. Wonder v0 main + 'cd6e42aee7934f4d8393cd43893ae25e': [ + # Resource heap slack: each resource unit's ExpHeap is created with the resource size table value + 0x1008 (main+0x1e603c → ExpHeap::create main+0x4aac38); the table holds Nintendo's measured peaks with almost no margin +@@ -680,7 +693,12 @@ for a in sorted(kinds): elif k in ('cntpct', 'cntvct'): st = site_gate(ins, k, arg); stat(k) elif k == 'ctr': # replaced in place by a constant: DminLine = 4 (64-byte lines); movz xN, #4, lsl #16 assert arg != 18, f'{a:x} mrs x18, ctr_el0' From 3987304a241dfa3895dde5cddcc535c1c3bdcf0b Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:31:25 +0100 Subject: [PATCH 04/13] Default the pad mapping to the user's Eden profile Cross=A, Circle=B, Square=X, Triangle=Y and a 0.15 stick deadzone, matching the player_0 block in Eden's qt-config.ini for the DualSense. The Switch physical layout is still available with DM_PAD_FACE=position, and the gamepad test now asserts both. --- native/gamepad_mac.m | 12 +++++++----- tests/test_gamepad.m | 8 ++++++-- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/native/gamepad_mac.m b/native/gamepad_mac.m index e6f7ab9..100ad9f 100644 --- a/native/gamepad_mac.m +++ b/native/gamepad_mac.m @@ -47,9 +47,9 @@ static void apply(void) { dm_pad_set(b, ax[0], ax[1], ax[2], ax[3]); trace(b, ax); } -// Stick: radial dead zone, then rescale to full range +// Stick: radial dead zone (default 0.15, as in the Eden profile), then rescale to full range static void stick(float x, float y, int32_t *ox, int32_t *oy) { - if (g_dead < 0) { const char *e = getenv("DM_PAD_DEADZONE"); g_dead = e ? (float)atof(e) : 0.12f; if (!isfinite(g_dead) || g_dead < 0 || g_dead > 0.9f) g_dead = 0.12f; } + if (g_dead < 0) { const char *e = getenv("DM_PAD_DEADZONE"); g_dead = e ? (float)atof(e) : 0.15f; if (!isfinite(g_dead) || g_dead < 0 || g_dead > 0.9f) g_dead = 0.15f; } if (!isfinite(x) || !isfinite(y)) { *ox = *oy = 0; return; } float m = hypotf(x, y); if (m <= g_dead) { *ox = *oy = 0; return; } @@ -57,7 +57,9 @@ static void stick(float x, float y, int32_t *ox, int32_t *oy) { *ox = (int32_t)lroundf(x * k * DM_STICK_MAX); *oy = (int32_t)lroundf(y * k * DM_STICK_MAX); } static void publish(GCController *c, GCExtendedGamepad *g) { - if (g_face_letter < 0) { const char *e = getenv("DM_PAD_FACE"); g_face_letter = e && !strcmp(e, "letter"); } + // Default follows the Eden profile this port was configured against (Cross=A, Circle=B, Square=X, Triangle=Y); + // DM_PAD_FACE=position restores the Switch physical layout (right=A, bottom=B, top=X, left=Y). + if (g_face_letter < 0) { const char *e = getenv("DM_PAD_FACE"); g_face_letter = !e || strcmp(e, "position"); } if (!g_active) return; uint64_t b = 0; int bot = g.buttonA.pressed, rgt = g.buttonB.pressed, lft = g.buttonX.pressed, top = g.buttonY.pressed; @@ -83,7 +85,7 @@ static void attach(GCController *c) { g_count++; c.handlerQueue = dispatch_get_main_queue(); LOG("Gamepad connected: %s (%s), count=%d, face=%s, deadzone=%s", c.vendorName.UTF8String ?: "?", - c.productCategory.UTF8String ?: "?", g_count, getenv("DM_PAD_FACE") ?: "position", getenv("DM_PAD_DEADZONE") ?: "0.12"); + c.productCategory.UTF8String ?: "?", g_count, g_face_letter ? "letter" : "position", getenv("DM_PAD_DEADZONE") ?: "0.15"); __weak GCController *wc = c; g.valueChangedHandler = ^(GCExtendedGamepad *gp, GCControllerElement *el) { (void)el; GCController *sc = wc; if (sc) publish(sc, gp); }; publish(c, g); @@ -114,7 +116,7 @@ void dm_gamepad_start(void (*on_present)(int present)) { [nc addObserverForName:GCControllerDidDisconnectNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *n) { detach(n.object); }]; NSArray *cs = GCController.controllers; LOG("GameController started: system controllers=%lu, face=%s, deadzone=%s", (unsigned long)cs.count, - getenv("DM_PAD_FACE") ?: "position", getenv("DM_PAD_DEADZONE") ?: "0.12"); + g_face_letter ? "letter" : "position", getenv("DM_PAD_DEADZONE") ?: "0.15"); for (GCController *c in cs) attach(c); // attaching one calls back on_present(1) if (!g_count) present_changed(); // none: call back once with 0 for the current count } diff --git a/tests/test_gamepad.m b/tests/test_gamepad.m index 864017c..2e45861 100644 --- a/tests/test_gamepad.m +++ b/tests/test_gamepad.m @@ -26,15 +26,19 @@ int main(void) { @autoreleasepool { [[NSNotificationCenter defaultCenter] postNotificationName:GCControllerDidConnectNotification object:c]; drain(); assert(dm_gamepad_count() == 1); GCExtendedGamepad *g = c.extendedGamepad; - [g.buttonB setValue:1]; publish(c,g); assert(sample().buttons & DM_BTN_A); + // Default is the Eden profile: Circle (GC buttonB) is the Switch B button. + [g.buttonB setValue:1]; publish(c,g); assert(sample().buttons & DM_BTN_B); [g.buttonB setValue:0]; publish(c,g); assert(sample().buttons == 0); + g_face_letter = 0; // DM_PAD_FACE=position restores the Switch physical layout + [g.buttonB setValue:1]; publish(c,g); assert(sample().buttons & DM_BTN_A); + [g.buttonB setValue:0]; publish(c,g); assert(sample().buttons == 0); g_face_letter = 1; [g.buttonA setValue:1]; [g.buttonY setValue:1]; [g.buttonX setValue:1]; [g.leftShoulder setValue:1]; [g.rightShoulder setValue:1]; [g.leftTrigger setValue:1]; [g.rightTrigger setValue:1]; [g.leftThumbstickButton setValue:1]; [g.rightThumbstickButton setValue:1]; [g.buttonMenu setValue:1]; [g.buttonOptions setValue:1]; [g.dpad setValueForXAxis:-1 yAxis:1]; publish(c,g); - uint64_t expected = DM_BTN_B|DM_BTN_X|DM_BTN_Y|DM_BTN_L|DM_BTN_R|DM_BTN_ZL|DM_BTN_ZR|DM_BTN_LS|DM_BTN_RS|DM_BTN_PLUS|DM_BTN_MINUS|DM_BTN_LEFT|DM_BTN_UP; + uint64_t expected = DM_BTN_A|DM_BTN_X|DM_BTN_Y|DM_BTN_L|DM_BTN_R|DM_BTN_ZL|DM_BTN_ZR|DM_BTN_LS|DM_BTN_RS|DM_BTN_PLUS|DM_BTN_MINUS|DM_BTN_LEFT|DM_BTN_UP; assert(sample().buttons == expected); [g.leftThumbstick setValueForXAxis:0.05 yAxis:0.04]; [g.rightThumbstick setValueForXAxis:1 yAxis:-1]; publish(c,g); From 6112a41d43b212274367b0546f1e17a07382299d Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:44:58 +0100 Subject: [PATCH 05/13] Swap shoulder buttons and add full-screen L1 now sends Switch R and R1 sends Switch L (D4 muscle memory, potion on LB). The game window gets FullScreenPrimary collection behaviour and a View menu with Enter Full Screen (Ctrl-Cmd-F), so it no longer needs to be dragged to another space. --- native/gamepad_mac.m | 3 ++- patches/nxnative.patch | 15 +++++++++++---- tests/test_gamepad.m | 4 +++- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/native/gamepad_mac.m b/native/gamepad_mac.m index 100ad9f..ea99d3e 100644 --- a/native/gamepad_mac.m +++ b/native/gamepad_mac.m @@ -65,7 +65,8 @@ static void publish(GCController *c, GCExtendedGamepad *g) { int bot = g.buttonA.pressed, rgt = g.buttonB.pressed, lft = g.buttonX.pressed, top = g.buttonY.pressed; if (g_face_letter) { if (bot) b |= DM_BTN_A; if (rgt) b |= DM_BTN_B; if (lft) b |= DM_BTN_X; if (top) b |= DM_BTN_Y; } else { if (rgt) b |= DM_BTN_A; if (bot) b |= DM_BTN_B; if (top) b |= DM_BTN_X; if (lft) b |= DM_BTN_Y; } // Switch positions - if (g.leftShoulder.pressed) b |= DM_BTN_L; if (g.rightShoulder.pressed) b |= DM_BTN_R; + // Shoulders swapped by request: R1=L, L1=R (muscle memory from D4, where the potion sits on LB). + if (g.leftShoulder.pressed) b |= DM_BTN_R; if (g.rightShoulder.pressed) b |= DM_BTN_L; if (g.leftTrigger.pressed) b |= DM_BTN_ZL; if (g.rightTrigger.pressed) b |= DM_BTN_ZR; if (g.leftThumbstickButton.pressed) b |= DM_BTN_LS; if (g.rightThumbstickButton.pressed) b |= DM_BTN_RS; if (g.buttonMenu.pressed) b |= DM_BTN_PLUS; if (g.buttonOptions.pressed) b |= DM_BTN_MINUS; diff --git a/patches/nxnative.patch b/patches/nxnative.patch index f15da5a..6517d96 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -1672,7 +1672,7 @@ index 933c85b..6dfad7a 100644 +void dm_pad_clear(void); +void dm_input_clear(void); diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m -index c7559ca..cb5a160 100644 +index c7559ca..1d426e1 100644 --- a/dm/host/front_mac.m +++ b/dm/host/front_mac.m @@ -3,6 +3,7 @@ @@ -1683,7 +1683,7 @@ index c7559ca..cb5a160 100644 #import #include "dm.h" #include "dm_input.h" -@@ -13,14 +14,58 @@ __attribute__((constructor)) static void ui_shift_reg(void) { mtl_set_ui_rect_fn +@@ -13,14 +14,64 @@ __attribute__((constructor)) static void ui_shift_reg(void) { mtl_set_ui_rect_fn #include "front.h" #include "hle.h" #include @@ -1706,6 +1706,12 @@ index c7559ca..cb5a160 100644 + [app addItemWithTitle:[NSString stringWithFormat:@"Hide %@", name] action:@selector(hide:) keyEquivalent:@"h"]; + [app addItem:NSMenuItem.separatorItem]; + [app addItemWithTitle:[NSString stringWithFormat:@"Quit %@", name] action:@selector(terminate:) keyEquivalent:@"q"]; ++ NSMenu *view = [[NSMenu alloc] initWithTitle:@"View"]; ++ NSMenuItem *viewItem = [[NSMenuItem alloc] init]; ++ viewItem.title = @"View"; viewItem.submenu = view; [main addItem:viewItem]; ++ // Target nil: toggleFullScreen: is resolved along the responder chain to the key window. ++ NSMenuItem *full = [view addItemWithTitle:@"Enter Full Screen" action:@selector(toggleFullScreen:) keyEquivalent:@"f"]; ++ full.keyEquivalentModifierMask = NSEventModifierFlagControl | NSEventModifierFlagCommand; + NSApp.mainMenu = main; +} static CAMetalLayer *g_layer; @@ -1742,7 +1748,7 @@ index c7559ca..cb5a160 100644 unsigned w, h; const char *e = getenv("DM_GAME_RES"); if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4; return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280; -@@ -60,23 +105,33 @@ void front_run(void (*guest)(void)) { +@@ -60,23 +111,34 @@ void front_run(void (*guest)(void)) { @autoreleasepool { [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; @@ -1753,6 +1759,7 @@ index c7559ca..cb5a160 100644 backing:NSBackingStoreBuffered defer:NO]; - win.title = @DM_GAME_NAME; // the game profile's name (game name label) + g_window = win; ++ win.collectionBehavior |= NSWindowCollectionBehaviorFullScreenPrimary; // green button / ⌃⌘F; the layer letterboxes via update_game_layer + dm_gamepad_start(pad_status); NSView *v = win.contentView; v.wantsLayer = YES; @@ -1779,7 +1786,7 @@ index c7559ca..cb5a160 100644 if (!e.isARepeat) on_key(e, e.type == NSEventTypeKeyDown); return nil; // Swallow it to avoid the system beep }]; -@@ -93,14 +148,15 @@ void front_run(void (*guest)(void)) { +@@ -93,14 +155,15 @@ void front_run(void (*guest)(void)) { usingBlock:^(NSNotification *n) { (void)n; exit(0); }]; // Lifecycle (hle.h / dm.h): focus lost → 2, focus regained → 1; minimized → 3 + audio paused + GPU suspended, restored → resume (followed by focus regained → 1) NSNotificationCenter *nc = NSNotificationCenter.defaultCenter; diff --git a/tests/test_gamepad.m b/tests/test_gamepad.m index 2e45861..2fd86d5 100644 --- a/tests/test_gamepad.m +++ b/tests/test_gamepad.m @@ -33,7 +33,9 @@ int main(void) { @autoreleasepool { [g.buttonB setValue:1]; publish(c,g); assert(sample().buttons & DM_BTN_A); [g.buttonB setValue:0]; publish(c,g); assert(sample().buttons == 0); g_face_letter = 1; [g.buttonA setValue:1]; [g.buttonY setValue:1]; [g.buttonX setValue:1]; - [g.leftShoulder setValue:1]; [g.rightShoulder setValue:1]; + [g.leftShoulder setValue:1]; publish(c,g); assert(sample().buttons == (DM_BTN_A|DM_BTN_X|DM_BTN_Y|DM_BTN_R)); // R1 = Switch R + [g.leftShoulder setValue:0]; [g.rightShoulder setValue:1]; publish(c,g); assert(sample().buttons == (DM_BTN_A|DM_BTN_X|DM_BTN_Y|DM_BTN_L)); // L1 = Switch L + [g.leftShoulder setValue:1]; [g.leftTrigger setValue:1]; [g.rightTrigger setValue:1]; [g.leftThumbstickButton setValue:1]; [g.rightThumbstickButton setValue:1]; [g.buttonMenu setValue:1]; [g.buttonOptions setValue:1]; From c4cfa21130ee002418939dbf732d357430f62f78 Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:13:45 +0000 Subject: [PATCH 06/13] Add D3 publisher-file branch gates, observe only Installs branch gates at the three lobby retrieval result tests (OnConfigFileRetrieved 0x64268, OnSeasonsFileRetrieved 0x6527c, OnBlacklistFileRetrieved 0x6581c) with host calls 0x8f-0x91. The host handler only logs the blz::string it is handed and always forces x8=0, so guest behaviour is unchanged. The branch-copy verifier now accepts a cbz/cbnz copy re-encoded to the original target (directly or through a checked local b trampoline), since a verbatim copy in the patch area would branch by the wrong pc. --- patches/nxnative.patch | 108 ++++++++++++++++++++++++++++- third_party/d2r-verify/structck.py | 21 +++++- 2 files changed, 127 insertions(+), 2 deletions(-) diff --git a/patches/nxnative.patch b/patches/nxnative.patch index 6517d96..aaf13b8 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -1835,6 +1835,19 @@ index 1a63bd7..9fcffec 100644 void stubs_report(void) { LOG("stubs=%u", g_nstub); } // ---------- Host gate dispatch ---------- +diff --git a/dm/host/hle.h b/dm/host/hle.h +index 79fda3d..bb8a80f 100644 +--- a/dm/host/hle.h ++++ b/dm/host/hle.h +@@ -77,4 +77,7 @@ uint64_t dm_audio_render_calls(void); // Cumulative sound card callback count + // 0x8c Current act saved while in a rift (when the character is in a rift map w9 is replaced with 4 = Act V, writes x9; x8 always 0) dm_rift.c 0x6fa9d0 (branch gate: x8≠0 jumps to 0x6fa9d4, otherwise executes the original instruction and returns to 0x6fa9d4) + // 0x8d Extra mercenary equipment slots (mercenary + rift level ≥10 + belt / boots / gloves / ring / amulet: w0 is replaced with 1, writes x0; x8 always 0) dm_rift.c 0x64a34c (branch gate: x8≠0 jumps to 0x64a350, otherwise executes the original instruction and returns to 0x64a350) + // 0x8e Client-side check for the extra mercenary equipment slots (rift level ≥10 + the item is a belt / boots / gloves / ring / amulet: w1 is replaced with the item's own type number, writes x1; x8 always 0) dm_rift.c 0x3beb58 (branch gate: x8≠0 jumps to 0x3beb5c, otherwise executes the original instruction and returns to 0x3beb5c) +-enum { SVC_HOST_TACT_ZLIB = 0x80, SVC_HOST_C2S_DELIVER = 0x81, SVC_HOST_C2S_SYS = 0x82, SVC_HOST_GRANNY_A = 0x83, SVC_HOST_GRANNY_B = 0x84, SVC_HOST_PRIVATE_SKILL_RENDER = 0x85, SVC_HOST_PRIVATE_SKILL_AIM = 0x86, SVC_HOST_GROUND_ASSET = 0x87, SVC_HOST_DROP_SOUND = 0x88, SVC_HOST_RIFT_EXIT = 0x89, SVC_HOST_JOIN_SPAWN = 0x8a, SVC_HOST_JOIN_CORPSE = 0x8b, SVC_HOST_SAVE_ACT = 0x8c, SVC_HOST_MERC_SLOT = 0x8d, SVC_HOST_MERC_SLOT_CL = 0x8e }; // 0x87: fetch the model path for ground items (dm_dropfilter.c drop light) // 0x83/0x84: Granny per-block decode call sites (hle_granny.c) ++// 0x8f Diablo III publisher file Config.txt result test, observe only (OnConfigFileRetrieved) host_stubs.c 0x64268(分支门:x8≠0 跳 0x6426c,否则执行原指令回 0x6426c;svc8f 仅宿主观测,x8 恒 0,不写 guest 内存) ++// 0x90 Diablo III publisher file Seasons.txt result test, observe only (OnSeasonsFileRetrieved) host_stubs.c 0x6527c(分支门:x8≠0 跳 0x6529c,否则执行原指令回 0x65280;svc90 仅宿主观测,x8 恒 0,不写 guest 内存) ++// 0x91 Diablo III publisher file Blacklist.txt result test, observe only (OnBlacklistFileRetrieved) host_stubs.c 0x6581c(分支门:x8≠0 跳 0x6583c,否则执行原指令回 0x65820;svc91 仅宿主观测,x8 恒 0,不写 guest 内存) ++enum { SVC_HOST_TACT_ZLIB = 0x80, SVC_HOST_C2S_DELIVER = 0x81, SVC_HOST_C2S_SYS = 0x82, SVC_HOST_GRANNY_A = 0x83, SVC_HOST_GRANNY_B = 0x84, SVC_HOST_PRIVATE_SKILL_RENDER = 0x85, SVC_HOST_PRIVATE_SKILL_AIM = 0x86, SVC_HOST_GROUND_ASSET = 0x87, SVC_HOST_DROP_SOUND = 0x88, SVC_HOST_RIFT_EXIT = 0x89, SVC_HOST_JOIN_SPAWN = 0x8a, SVC_HOST_JOIN_CORPSE = 0x8b, SVC_HOST_SAVE_ACT = 0x8c, SVC_HOST_MERC_SLOT = 0x8d, SVC_HOST_MERC_SLOT_CL = 0x8e, SVC_HOST_D3_CONFIG_FILE = 0x8f, SVC_HOST_D3_SEASONS_FILE = 0x90, SVC_HOST_D3_BLACKLIST_FILE = 0x91 }; // 0x87: fetch the model path for ground items (dm_dropfilter.c drop light) // 0x83/0x84: Granny per-block decode call sites (hle_granny.c) diff --git a/dm/host/hle_account.c b/dm/host/hle_account.c index 362a6c2..b32be1e 100644 --- a/dm/host/hle_account.c @@ -3019,6 +3032,48 @@ index 96d2674..579e8ae 100644 void hle_signal_system_event(void *ev) { // An unbound one is bound on the spot as manual-clear (can only happen on a guest thread) pthread_mutex_lock(&g_se_lock); uint32_t wh = se_find(ev); pthread_mutex_unlock(&g_se_lock); if (!wh) { hle_bind_system_event(ev, 0); pthread_mutex_lock(&g_se_lock); wh = se_find(ev); pthread_mutex_unlock(&g_se_lock); } +diff --git a/dm/host/host_stubs.c b/dm/host/host_stubs.c +index ef7f336..15d7e41 100644 +--- a/dm/host/host_stubs.c ++++ b/dm/host/host_stubs.c +@@ -2,6 +2,7 @@ + // the generic host still calls them, and they get empty implementations here. When a feature is redone for this game, replace the matching stub with the real thing. + #include "dm.h" + #include "front.h" ++#include "hle.h" + + void crash_sample_self(void) {} + void inflate_bench_maybe(void) {} +@@ -24,4 +25,29 @@ uint64_t dm_game_res(int docked) { return front_game_res(docked); } + int dm_screen_real(int *w, int *h) { *w = *h = 0; return 0; } + void dm_ui_rect(int *x, int *y, int *w, int *h) { *x = *y = *w = *h = 0; } + // svc #0x80.. host gates: only D2R's rewrite rules create them; they should not appear in this game's build output ++#if DM_GAME_PROGRAM_ID == 0x01001B300B9BE000ull ++// Diablo III publisher-file gates (0x8f Config / 0x90 Seasons / 0x91 Blacklist), observation only: read the three blz::string ++// fields the lobby handed back and report them once per number. x8 is forced to 0 so the branch gate always executes the ++// original result test; diverting would have to splice a substituted string into the guest, which needs the guest allocator. ++uint64_t svc_host_call(int num, uint64_t *regs) { ++ if (num < SVC_HOST_D3_CONFIG_FILE || num > SVC_HOST_D3_BLACKLIST_FILE) die("svc_host_call:未登记的宿主门 svc #%#x", num); ++ static uint8_t logged[3]; ++ unsigned k = (unsigned)num - SVC_HOST_D3_CONFIG_FILE; ++ int ptr_reg = num == SVC_HOST_D3_CONFIG_FILE ? 20 : 2; // Config moved its shared_ptr x2→x20, the other two keep x2 ++ int res_reg = num == SVC_HOST_D3_CONFIG_FILE ? 21 : 1; ++ if (!logged[k]) { ++ logged[k] = 1; ++ uint64_t psz = regs[ptr_reg]; ++ if (!psz) LOG("d3 pubfile svc#%#x shared_ptr x%d is null (observe only, x8 forced 0)", num, ptr_reg); ++ else { ++ uint64_t so = *(const uint64_t *)psz; ++ LOG("d3 pubfile svc#%#x result=%u str=%#llx elems=%#llx size=%llu capraw=%#llx", num, (unsigned)regs[res_reg], so, ++ so ? *(const uint64_t *)so : 0, so ? *(const uint64_t *)(so + 8) : 0, so ? *(const uint64_t *)(so + 0x10) : 0); ++ } ++ } ++ regs[8] = 0; ++ return 1; ++} ++#else + uint64_t svc_host_call(int num, uint64_t *regs) { (void)regs; die("svc_host_call:本作没有宿主门 svc #%#x", num); } ++#endif diff --git a/dm/host/lan_native.h b/dm/host/lan_native.h new file mode 100644 index 0000000..00d42c8 @@ -3168,7 +3223,7 @@ index e237a24..2fe8d62 100644 int front = m->patch_off < 0; if (z0 + zw != (front ? m->file_image_len : (uint64_t)m->patch_off) || (z0 & 0x3FFF) || (zw & 0x3FFF) || (z1 & 0x3FFF) || ((uintptr_t)x0 & 0x3FFF) || ((uintptr_t)w & 0x3FFF) || ((uintptr_t)x1 & 0x3FFF)) diff --git a/dm/tools/patch_nso.py b/dm/tools/patch_nso.py -index 837700c..bdc2849 100644 +index 837700c..911c355 100644 --- a/dm/tools/patch_nso.py +++ b/dm/tools/patch_nso.py @@ -46,6 +46,19 @@ else: @@ -3205,3 +3260,54 @@ index 837700c..bdc2849 100644 put_branch(a, st) # Private visual branch; not OBS, 0x85 is a read-only query. Only this experimental build explicitly opts in; the original Qty/children and Update are unchanged. +@@ -819,6 +837,50 @@ if RULE_RUN and PRIVATE_GATES: + cuts.append((off, struct.pack(' host swaps w1 to the item\'s own type for ring/amulet/boots/gloves/belt (rift best >= 10); x8 stays 0, original insn runs ->0x3beb5c; svc8e', '仅宿主')) + ++# ---- Publisher-file branch gates: {NSO build ID: [(site, original branch word, divert target, svc number, reason, normal continuation)]}. ---- ++# Each row replaces the result test of one lobby retrieval callback with a branch gate of the 0x85 / 0x89 shape: x8≠0 jumps ++# to the divert target (the callback body), otherwise the original branch runs and control continues at the normal ++# continuation. These are not private gates: RULE_RUN is the touch-only flag (it asserts the touch build ID), while the D3 ++# host has no touch build and the observation is wanted in the ground-truth domains too, so the switch is RULE_RUN's ++# build check replaced by NAME == 'main' and the row's own build ID -- not DM_PRIVATE_GATES. ++BRANCH_GATES = { ++ # Diablo III 2.7.7: OnConfigFileRetrieved / OnSeasonsFileRetrieved / OnBlacklistFileRetrieved. The host only observes in ++ # this iteration (host_stubs.c svc_host_call), so x8 stays 0 and both paths below collapse onto the original branch. ++ '2607a74f5df7754cc0357b5df7e49693': [ ++ (0x64268, '35003a75', 0x6426c, 0x8f, ++ '发布文件 Config.txt:OnConfigFileRetrieved 结果判断 0x64268 的 cbnz w21,#0x649b4 → 分支门(x8≠0 跳 0x6426c,否则执行原 cbnz 回 0x6426c);svc8f 仅宿主观测,不跳转', 0x6426c), ++ (0x6527c, '34000101', 0x6529c, 0x90, ++ '发布文件 Seasons.txt:OnSeasonsFileRetrieved 结果判断 0x6527c 的 cbz w1,#0x6529c → 分支门(x8≠0 跳 0x6529c,否则执行原 cbz 回 0x65280);svc90 仅宿主观测,不跳转', 0x65280), ++ (0x6581c, '34000101', 0x6583c, 0x91, ++ '发布文件 Blacklist.txt:OnBlacklistFileRetrieved 结果判断 0x6581c 的 cbz w1,#0x6583c → 分支门(x8≠0 跳 0x6583c,否则执行原 cbz 回 0x65820);svc91 仅宿主观测,不跳转', 0x65820), ++ ], ++} ++if NAME == 'main' and BUILD_ID in BRANCH_GATES: ++ for site, word, tgt, svc, why, cont in BRANCH_GATES[BUILD_ID]: ++ ow = struct.unpack_from('` trampoline. ++ oi = dis(ow, site) ++ assert oi.mnemonic in ('cbz', 'cbnz'), f'分支门原指令必须是 cbz/cbnz {site:#x} {oi.mnemonic}' ++ t = oi.operands[-1].imm; pc = here(); tramp = pc + 8 ++ cw = (ow & 0xFF00001F) | (((tramp - pc) >> 2 & 0x7FFFF) << 5) ++ di = dis(cw, pc); assert di.mnemonic == oi.mnemonic and di.operands[-1].imm == tramp, f'分支门原指令重编失败 {site:#x}' ++ emit(cw); emit(B(here(), cont)); emit(B(here(), t)) ++ gates.append((ret, 'svc', svc, site)) ++ put_branch(site, start); stat('pubfile') ++ cuts.append((site, struct.pack('> 2) & 0x3FFFFFF) # ⑪ 剪口引入的分支门(hle.h 登记表形态「分支门:x8≠0 跳 0x目标,否则执行原指令回 0x原处+4」):原处换成 B 进补丁区,块逐字 = # stp x8,xzr,[sp,#-16]! ; stp x29,x30,[sp,#-16]! ; 键页取 KGATE ; ldr x30,[x30] ; ldr x29,[sp] ; blr x30 ; ldp x29,x30 ; cbz w8,+12 ; # ldp x8,xzr ; b 目标 ; ldp x8,xzr ; 原指令 ; b 原处+4 —— x8 两路都恢复为原值,宿主结果只用于选路;gates.tsv 记 (svc, 号, 原处) +# 原指令是 PC 相对条件分支(cbz/cbnz,暗黑发布文件门)时逐字复制会在补丁区按新 pc 算偏移:副本重编到原目标, +# 超出 ±1 MB 时经跟随的一个字 `b 原目标` 跳板(补丁区离 text 约 27 MB) # ⑪ Branch gates introduced by cuts (hle.h registry form 「分支门:x8≠0 跳 0x目标,否则执行原指令回 0x原处+4」(branch gate: x8≠0 jumps to 0x, otherwise executes the original instruction and returns to 0x+4)): the original site is replaced with a B into the patch area, and the block equals word for word # stp x8,xzr,[sp,#-16]! ; stp x29,x30,[sp,#-16]! ; fetch KGATE via key page ; ldr x30,[x30] ; ldr x29,[sp] ; blr x30 ; ldp x29,x30 ; cbz w8,+12 ; # ldp x8,xzr ; b target ; ldp x8,xzr ; original instruction ; b original site+4 - x8 is restored to its original value on both paths, the host result is only used to pick the path; gates.tsv records (svc, number, original site) +# When the original instruction is a PC-relative conditional branch (cbz/cbnz, the Diablo III publisher-file gates), a verbatim copy +# would compute its offset from the new pc in the patch area: the copy keeps the test and registers and is re-encoded to the +# original target, through a one-word `b original target` trampoline when that is beyond the ±1 MB reach (the patch area sits ~27 MB away) +def _condt(w, o): + imm = (w >> 5) & 0x7FFFF; imm -= (imm & 0x40000) << 1 + return o + 4 * imm +def branch_copy_ok(ow, cw, at, roff): + """Copy of the original instruction in the gate block: verbatim, or for a PC-relative cbz/cbnz the same test and + registers with the target preserved - either encoded directly, or (the patch area is beyond the ±1 MB reach of a + conditional branch) pointing one word ahead at a local `b ` trampoline.""" + if cw == ow: return True + if not (ow & 0x7E000000 == 0x34000000 and cw & 0x7E000000 == 0x34000000 + and cw & 0xFF00001F == ow & 0xFF00001F): return False + to, tc = _condt(ow, roff), _condt(cw, at) + if to == tc: return True + return PO <= tc and tc + 4 <= len(pat) and W(pat, tc) == B(tc, to) nbranch = 0 for n, (roff, form) in _hreg.items(): if not form.startswith('分支门'): continue @@ -328,7 +346,8 @@ def B(frm, to): return 0x14000000 | (((to - frm) >> 2) & 0x3FFFFFF) if s_ is None or not (PO <= s_ < len(pat)) or W(pat, s_) != 0xA9BF7FE8 or W(pat, s_ + 4) != 0xA9BF7BFD or not ks or ks[1] != KEY.get('KGATE') \ or W(pat, ks[0]) & 0xFFC00000 != 0xF9400000 or W(pat, ks[0] + 4) != LDR_X29_SP or W(pat, ks[0] + 8) != 0xD63F03C0 or W(pat, ks[0] + 12) != 0xA8C17BFD \ or W(pat, ks[0] + 16) != 0x34000068 or W(pat, ks[0] + 20) != 0xA8C17FE8 or W(pat, ks[0] + 24) != B(ks[0] + 24, tgt) \ - or W(pat, ks[0] + 28) != 0xA8C17FE8 or W(pat, ks[0] + 32) != W(orig, roff) or W(pat, ks[0] + 36) != B(ks[0] + 36, roff + 4): + or W(pat, ks[0] + 28) != 0xA8C17FE8 or not branch_copy_ok(W(orig, roff), W(pat, ks[0] + 32), ks[0] + 32, roff) \ + or W(pat, ks[0] + 36) != B(ks[0] + 36, roff + 4): bad(f'分支门 svc #{n:#x} {roff:#x}:块不符模板'); continue if gates.get(ks[0] + 12) != ('svc', n, roff): bad(f'分支门 svc #{n:#x} gates.tsv 行不符:{gates.get(ks[0] + 12)}') seen.add(ks[0] + 12); nbranch += 1 From fe78b8fbc4cc0da56f0f3544ae969917215210a4 Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:45:31 +0000 Subject: [PATCH 07/13] Inject D3 season and blacklist publisher files from the host The offline lobby never issues the publisher fetch, so the callbacks d3hack hooks are never entered. Call them ourselves instead: seeds two blz::string payloads as embedded-capacity buffers and invokes OnBlacklistFileRetrieved and OnSeasonsFileRetrieved with result 0 from a weak per-frame hook in the OE message poll, 600 frames after boot, re-arming if the game resets the season vector. Verified in a 90 s run: vector size 1, season 37, seasons/blacklist flags 1. Config.txt is not injected because that callback dereferences self. --- patches/nxnative.patch | 192 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) diff --git a/patches/nxnative.patch b/patches/nxnative.patch index aaf13b8..cbdcd70 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -1933,6 +1933,186 @@ index 3d309a1..ec44a2c 100644 +HLE_FORCE("_ZN2nn5audio12ListAudioInsEPNS0_11AudioInInfoEi", "No capture devices in this host", int, h_audio_ListIns, void *infos, int capacity) { + (void)infos; (void)capacity; return 0; +} +diff --git a/dm/host/hle_d3_pubfile.c b/dm/host/hle_d3_pubfile.c +new file mode 100644 +index 0000000..23023f3 +--- /dev/null ++++ b/dm/host/hle_d3_pubfile.c +@@ -0,0 +1,174 @@ ++/* Diablo III offline publisher files: hand Seasons.txt / Blacklist.txt to the game's own lobby callbacks. ++ * ++ * The game fetches both files from the online service; with no service the season calendar stays empty and the ++ * Journey never appears. Instead of patching the lobby state, this substitutes the two downloaded documents: the ++ * retrieval callbacks parse them exactly as if the service had answered. ++ * ++ * Driven from oe::TryPopNotificationMessage (hle_oe.c) rather than the NVN present path: the render thread can ++ * hold graphics locks in present, and calling into the lobby from there risks a lock-order deadlock. ++ */ ++#include "dm.h" ++#include "dm_d3_graphics.h" ++#include "hle.h" ++#include ++#include ++ ++#if DM_GAME_PROGRAM_ID == 0x01001B300B9BE000ull ++ ++// Payloads carry no season data of their own: the game only needs the calendar and the (empty) item blacklist. ++// Byte-for-byte the strings d3hack synthesises (god-jester/d3hack, source/program/d3/hooks/season_events.hpp); ++// the trailing blank line belongs to the seasons document format. ++static const char k_seasons_text[] = ++ "# Format for dates MUST be: \" ? ? ? , DD MMM YYYY hh : mm:ss UTC\"\n" ++ "# The Day of Month(DD) MUST be 2 - digit; use either preceding zero or trailing space\n" ++ "[Season 37]\n" ++ "Start \"Sat, 09 Feb 2025 00:00:00 GMT\"\n" ++ "End \"Tue, 09 Feb 2036 01:00:00 GMT\"\n\n"; ++static const char k_blacklist_text[] = ++ "# Blacklist overridden by d3hack\n" ++ "[GBID]\n\n" ++ "[SNO]\n"; ++#define SEASONS_BYTES 239u ++#define BLACKLIST_BYTES 47u ++ ++// blz::string is 0x28 bytes: text, size, capacity-with-flags, then inline SSO scratch. The engine reads these ++// fields directly (no accessor on the retrieval path), so the layout is reproduced here. ++// bit63 of the capacity marks embedded storage: the guest then never calls the allocator on the text pointer, ++// which matters because the text below lives in host memory. ++typedef struct { const char *data; uint64_t size; uint64_t capacity; uint64_t sso[2]; } blz_string; ++typedef struct { void *pointer; void *manager; } blz_shared_ptr; ++_Static_assert(sizeof(blz_string) == 0x28, "blz::string layout"); ++_Static_assert(offsetof(blz_string, data) == 0x00 && offsetof(blz_string, size) == 0x08 && offsetof(blz_string, capacity) == 0x10, "blz::string fields"); ++_Static_assert(sizeof(blz_shared_ptr) == 0x10, "blz::shared_ptr layout"); ++ ++// main 2.7.7 (build 2607a74f…) globals reached by the retrieval callbacks. ++enum { ++ OFF_SEASONS_PARSED = 0x114ac48, // uint8_t **: "seasons.txt was parsed" flag ++ OFF_SEASONS_VEC = 0x114ac58, // vector object { data, size, capacity }: season calendar ++ OFF_SEASONS_XVAR = 0x114ac60, // seasons-override xvar, read by the callback ++ OFF_ONLINE_XVAR = 0x114ac68, // online-service xvar, read by the callback ++ OFF_BLACKLIST_FLAG = 0x114ae58, // uint8_t **: "blacklist applied" flag ++ OFF_LOBBY_A = 0x114b0a0, // lobby objects the callbacks reach through ++ OFF_LOBBY_B = 0x114b128, ++ OFF_BLACKLIST_CB = 0x657f0, // OnBlacklistFileRetrieved(self, eResult, shared_ptr *) ++ OFF_SEASONS_CB = 0x65270, // OnSeasonsFileRetrieved(self, eResult, shared_ptr *) ++}; ++enum { MAX_INJECTIONS = 8 }; ++ ++static blz_string *s_seasons, *s_blacklist; ++static blz_shared_ptr *s_sp_seasons, *s_sp_blacklist; ++static int s_off = 1; // stays set until pubfile_init decides to run ++static uint64_t s_delay = 600; // the lobby is not up before the front end; injecting earlier just hits null globals ++static unsigned s_injections; ++static pthread_once_t s_once = PTHREAD_ONCE_INIT; ++ ++static void pubfile_init(void) { ++ const char *on = getenv("DM_D3_PUBFILE"); ++ if (on && !strcmp(on, "0")) { LOG("d3 pubfile: INFO disabled by DM_D3_PUBFILE=0"); return; } ++ const char *d = getenv("DM_D3_PUBFILE_DELAY"); ++ if (d && *d) { ++ char *end; unsigned long long v = strtoull(d, &end, 10); ++ if (end == d || *end) die("DM_D3_PUBFILE_DELAY 非法:%s", d); ++ s_delay = v; ++ } ++ // The offsets and callback entries below belong to one signed image; the svc gates prove this build output ++ // actually carries the two branch gates the substitution was surveyed against. ++ if (strcmp(dm_main_build(), DM_D3_MAIN_BUILD_ID) || !gate_svc_present(SVC_HOST_D3_SEASONS_FILE) || !gate_svc_present(SVC_HOST_D3_BLACKLIST_FILE)) { ++ LOG("d3 pubfile: INFO disabled (main build %s, svc 0x90=%d 0x91=%d)", dm_main_build()[0] ? dm_main_build() : "(none)", ++ gate_svc_present(SVC_HOST_D3_SEASONS_FILE), gate_svc_present(SVC_HOST_D3_BLACKLIST_FILE)); ++ return; ++ } ++ size_t sl = strlen(k_seasons_text), bl = strlen(k_blacklist_text); ++ if (sl != SEASONS_BYTES || bl != BLACKLIST_BYTES) { ++ LOG("d3 pubfile: payload size mismatch seasons=%zu (want %u) blacklist=%zu (want %u), disabled", sl, SEASONS_BYTES, bl, BLACKLIST_BYTES); ++ return; ++ } ++ // One block, never freed: the guest may keep pointers into it for the rest of the process. ++ size_t cap = sl + bl + 3 * 15 + 2 * sizeof(blz_string) + 2 * sizeof(blz_shared_ptr); ++ uint8_t *buf = malloc(cap); ++ if (!buf) { LOG("d3 pubfile: INFO out of memory, disabled"); return; } ++ memcpy(buf, k_seasons_text, sl); ++ memcpy(buf + sl, k_blacklist_text, bl); ++ uint8_t *p = buf + sl + bl; ++ // The engine reads the headers with 8-byte loads but the shared_ptr pair is copied whole; keep both aligned. ++ p = (uint8_t *)(((uintptr_t)p + 15) & ~(uintptr_t)15); ++ s_seasons = (blz_string *)p; p += sizeof *s_seasons; ++ p = (uint8_t *)(((uintptr_t)p + 15) & ~(uintptr_t)15); ++ s_blacklist = (blz_string *)p; p += sizeof *s_blacklist; ++ p = (uint8_t *)(((uintptr_t)p + 15) & ~(uintptr_t)15); ++ s_sp_seasons = (blz_shared_ptr *)p; p += sizeof *s_sp_seasons; ++ s_sp_blacklist = (blz_shared_ptr *)p; ++ const uint64_t embedded = 1ull << 63; ++ *s_seasons = (blz_string){(const char *)buf, sl, (uint64_t)sl | embedded, {0, 0}}; ++ *s_blacklist = (blz_string){(const char *)buf + sl, bl, (uint64_t)bl | embedded, {0, 0}}; ++ s_sp_seasons->pointer = s_seasons; s_sp_seasons->manager = NULL; ++ s_sp_blacklist->pointer = s_blacklist; s_sp_blacklist->manager = NULL; ++ s_off = 0; ++ LOG("d3 pubfile: INFO enabled (main %s, %.0f frames delay, seasons %zu B, blacklist %zu B)", dm_main_build(), (double)s_delay, sl, bl); ++} ++ ++static module_t *main_module(void) { ++ for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) return &g_mod[i]; ++ return NULL; ++} ++ ++static void *grab(uint8_t *base, unsigned off) { return *(void **)(base + off); } ++ ++// The callbacks dereference all of these; calling before the lobby/XVar objects exist would fault in guest code. ++static int lobby_ready(uint8_t *base) { ++ return grab(base, OFF_SEASONS_VEC) && grab(base, OFF_SEASONS_XVAR) && grab(base, OFF_ONLINE_XVAR) && ++ grab(base, OFF_LOBBY_A) && grab(base, OFF_LOBBY_B); ++} ++ ++static uint64_t seasons_size(uint8_t *base) { ++ void *vec = grab(base, OFF_SEASONS_VEC); ++ return vec ? *(uint64_t *)((uint8_t *)vec + 8) : 0; ++} ++ ++static void inject(uint8_t *base) { ++ // The callback may have replaced the pair on an earlier pass; reset it before every call. ++ s_sp_blacklist->pointer = s_blacklist; s_sp_blacklist->manager = NULL; ++ s_sp_seasons->pointer = s_seasons; s_sp_seasons->manager = NULL; ++ // eResult must be 0: the retrieval body is only entered on success (the season callback tests it with ++ // cbz before its prologue; 3 is the network failure result and would return without parsing). ++ ((void (*)(void *, int, void *))(base + OFF_BLACKLIST_CB))(NULL, 0, s_sp_blacklist); ++ ((void (*)(void *, int, void *))(base + OFF_SEASONS_CB))(NULL, 0, s_sp_seasons); ++ s_injections++; ++} ++ ++static void report(uint8_t *base) { ++ void *vec = grab(base, OFF_SEASONS_VEC); ++ uint64_t n = vec ? *(uint64_t *)((uint8_t *)vec + 8) : 0; ++ void *data = n ? *(void **)vec : NULL; ++ uint64_t season = data ? *(uint32_t *)data : 0; ++ uint64_t start = data ? *(uint64_t *)((uint8_t *)data + 0x10) : 0; ++ uint64_t end = data ? *(uint64_t *)((uint8_t *)data + 0x18) : 0; ++ uint8_t *fs = *(uint8_t **)(base + OFF_SEASONS_PARSED); ++ uint8_t *fb = *(uint8_t **)(base + OFF_BLACKLIST_FLAG); ++ LOG("d3 pubfile: seasons vec=%p n=%llu season=%u start=%llu end=%llu flags seasons=%u blacklist=%u", vec, ++ (unsigned long long)n, (unsigned)season, (unsigned long long)start, (unsigned long long)end, ++ fs ? (unsigned)*fs : 0u, fb ? (unsigned)*fb : 0u); ++} ++ ++void dm_d3_pubfile_tick(void) { ++ pthread_once(&s_once, pubfile_init); ++ if (s_off || dm_guest_frame() < s_delay) return; ++ static _Atomic int busy; ++ if (atomic_exchange(&busy, 1)) return; ++ module_t *m = main_module(); ++ if (!m || !lobby_ready(m->base)) { atomic_store(&busy, 0); return; } ++ if (!s_injections) { ++ inject(m->base); ++ report(m->base); ++ } else if (!seasons_size(m->base) && s_injections < MAX_INJECTIONS) { ++ // The lobby is torn down and rebuilt on reconnect / character switch (main+0x72f7c clears the calendar). ++ // Without re-arming, the Journey disappears for the rest of the session; the cap keeps a pathological ++ // reset loop from calling the lobby on every frame. ++ LOG("d3 pubfile: seasons cleared by the lobby reset, re-arm %u/%u", s_injections + 1, MAX_INJECTIONS); ++ inject(m->base); ++ report(m->base); ++ } ++ atomic_store(&busy, 0); ++} ++ ++#endif diff --git a/dm/host/hle_hid.c b/dm/host/hle_hid.c index 561a3c8..e126dcf 100644 --- a/dm/host/hle_hid.c @@ -2929,6 +3109,18 @@ index 234d762..672dfa6 100644 // ---------- ssl: offline, Initialize succeeds (the network library's global initialization depends on it), everything else that contacts the service fails ---------- // Not cut: Context / Connection construction and destruction, Context::GetContextId (only read and write game objects). #define SSF(m, cname, ...) HLE_FORCE(m, "ssl 服务(剪):失败", Result, cname, __VA_ARGS__) +diff --git a/dm/host/hle_oe.c b/dm/host/hle_oe.c +index 180c62c..1120abc 100644 +--- a/dm/host/hle_oe.c ++++ b/dm/host/hle_oe.c +@@ -221,6 +221,7 @@ static void scale3d_tick(void) { + *(uint32_t *)(renderer + 0xee88), *(uint32_t *)(renderer + 0xee8c), (unsigned long long)dm_nvn_frame_count()); + } + HLE_FORCE("_ZN2nn2oe25TryPopNotificationMessageEPj", "系统通知队列;前端状态变化入队", unsigned, h_oe_TryPopMsg, uint32_t *msg) { ++ { extern void dm_d3_pubfile_tick(void) __attribute__((weak)); if (dm_d3_pubfile_tick) dm_d3_pubfile_tick(); } // D3 publisher files (hle_d3_pubfile.c): the main loop pumps notifications every frame, unlike present (which can run with graphics locks held) + scale3d_tick(); + pthread_once(&g_oe_once, oe_script_start); + pthread_mutex_lock(&g_mq_lock); diff --git a/dm/host/hle_offline.c b/dm/host/hle_offline.c index 367779a..9eccbc0 100644 --- a/dm/host/hle_offline.c From dc08aa744f4b30dc5b7d0d3879bca2a5d1f3d172 Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:04:58 +0000 Subject: [PATCH 08/13] Set D3 season XVars and show build state in the title XVarUint32_Set is 0xA273C0 in 2.7.7; the season objects are pointed to by 0x114ac60/0x114ac68 and the injector now writes season 37 / state 1 with dirty flags 3, matching d3hack's pair. The window title carries the host build stamp, the rewrite build id and the injector's status line, so a stale bundle is visible at a glance. --- patches/nxnative.patch | 122 ++++++++++++++++++++++++++++++++++------- 1 file changed, 103 insertions(+), 19 deletions(-) diff --git a/patches/nxnative.patch b/patches/nxnative.patch index cbdcd70..cf6d656 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -1590,7 +1590,7 @@ index c925370..4dc5154 100644 metal_macosx Apple metal version 32023.921 (metalfe-32023.921.6) metal_iphoneos Apple metal version 32023.921 (metalfe-32023.921.6) diff --git a/dm/host/Makefile b/dm/host/Makefile -index 31b4420..51cec58 100644 +index 31b4420..6c2626e 100644 --- a/dm/host/Makefile +++ b/dm/host/Makefile @@ -10,7 +10,7 @@ GAME_DIR = ../games/$(GAME) @@ -1602,14 +1602,15 @@ index 31b4420..51cec58 100644 # NVN null device + nn::vi (dm/gfx/) # Sources under dm/gfx and dm/gfx/nvn are included by wildcard (tests/ and metal/ do not go into the host): adding a file does not touch this line GFX=$(sort $(wildcard ../gfx/*.c ../gfx/nvn/*.c ../gfx/nvn/*.m ../gfx/nvn/*.S ../gfx/tex/*.c ../gfx/tex/*.m)) -@@ -51,5 +51,5 @@ $(GAME_STAMP): FORCE +@@ -51,5 +51,6 @@ $(GAME_STAMP): FORCE @mkdir -p gen; echo $(GAME) | cmp -s - $@ || echo $(GAME) > $@ .PHONY: FORCE FORCE: -dmhost: $(SRC) $(GFX) dm.h hle.h dm_input.h front.h touch_mac.h ../ios/Sources/dm_touch_controls.[ch] $(GFX_H) $(GAME_H) $(GAME_DIR)/dmsh_chain.h $(GAME_STAMP) $(VPX_LIB) - clang $(CFLAGS) -I../gfx/nvn/include -I$(dir $(GAME_H)) -I$(GAME_DIR) -I$(VPX) -I../third_party/stb_vorbis -fobjc-arc -o $@ $(SRC) $(GFX) $(VPX_LIB) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers +dmhost: $(SRC) $(GFX) dm.h hle.h dm_input.h front.h touch_mac.h ../ios/Sources/dm_touch_controls.[ch] $(GFX_H) controller_effects.h lan_native.h dm_d3_graphics.h $(GAME_H) $(GAME_DIR)/dmsh_chain.h $(GAME_STAMP) $(VPX_LIB) -+ clang $(CFLAGS) -I../gfx/nvn/include -I$(dir $(GAME_H)) -I$(GAME_DIR) -I$(VPX) -I../third_party/stb_vorbis -fobjc-arc -o $@ $(SRC) $(GFX) $(VPX_LIB) -framework Cocoa -framework GameController -framework CoreHaptics -framework QuartzCore -framework Metal -framework MetalFX -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers ++ # env -u SOURCE_DATE_EPOCH: the nix devshell exports a pinned epoch, which would freeze dm_host_build_stamp (__DATE__/__TIME__) at 1980 and hide a stale dmhost ++ env -u SOURCE_DATE_EPOCH clang $(CFLAGS) -I../gfx/nvn/include -I$(dir $(GAME_H)) -I$(GAME_DIR) -I$(VPX) -I../third_party/stb_vorbis -fobjc-arc -o $@ $(SRC) $(GFX) $(VPX_LIB) -framework Cocoa -framework GameController -framework CoreHaptics -framework QuartzCore -framework Metal -framework MetalFX -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers diff --git a/dm/host/dm_d3_graphics.h b/dm/host/dm_d3_graphics.h new file mode 100644 index 0000000..c6da2da @@ -1672,18 +1673,20 @@ index 933c85b..6dfad7a 100644 +void dm_pad_clear(void); +void dm_input_clear(void); diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m -index c7559ca..1d426e1 100644 +index c7559ca..d71b581 100644 --- a/dm/host/front_mac.m +++ b/dm/host/front_mac.m -@@ -3,6 +3,7 @@ +@@ -3,7 +3,9 @@ // Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−. #import #import +#import #import ++#import #include "dm.h" #include "dm_input.h" -@@ -13,14 +14,64 @@ __attribute__((constructor)) static void ui_shift_reg(void) { mtl_set_ui_rect_fn + #include "dm_uiscreen.h" +@@ -13,14 +15,77 @@ __attribute__((constructor)) static void ui_shift_reg(void) { mtl_set_ui_rect_fn #include "front.h" #include "hle.h" #include @@ -1692,11 +1695,24 @@ index c7559ca..1d426e1 100644 +void dm_gamepad_start(void (*on_present)(int)); +void dm_gamepad_set_active(int active); +static __weak NSWindow *g_window; ++static int g_pad_present; // last controller state reported by the gamepad layer (main thread), replayed by dm_front_title_refresh +static int lang_zh(void) { const char *e = getenv("DM_LANG"); return e && (e[0] | 0x20) == 'z' && (e[1] | 0x20) == 'h'; } ++// Only D3 builds the injector (hle_d3_pubfile.c); elsewhere the symbol is absent and the field is omitted. ++extern int dm_d3_pubfile_status(char *buf, size_t n) __attribute__((weak)); +static void pad_status(int present) { -+ g_window.title = [NSString stringWithFormat:@"%s · %@", DM_GAME_NAME, lang_zh() ? (present ? @"手柄已连接" : @"等待手柄(键盘可用)") -+ : (present ? @"Controller connected" : @"Waiting for controller (keyboard works)")]; -+} ++ g_pad_present = present; ++ const char *wait = lang_zh() ? (present ? "手柄已连接" : "等待手柄(键盘可用)") ++ : (present ? "Controller connected" : "Waiting for controller (keyboard works)"); ++ const char *build = dm_main_build(); ++ char rewrite[9] = "", injector[96] = "", title[256]; ++ if (build) for (size_t i = 0; i < 8 && build[i]; i++) { rewrite[i] = build[i]; rewrite[i + 1] = 0; } ++ if (dm_d3_pubfile_status) dm_d3_pubfile_status(injector, sizeof injector); ++ snprintf(title, sizeof title, "%s · %s · %s%s%s%s%s", DM_GAME_NAME, wait, dm_host_build_stamp(), ++ rewrite[0] ? " · " : "", rewrite, injector[0] ? " · " : "", injector); ++ g_window.title = [NSString stringWithUTF8String:title]; ++} ++// The injector learns its result only after the first guest tick, long after the title is set: replay it on the main thread. ++void dm_front_title_refresh(void) { dispatch_async(dispatch_get_main_queue(), ^{ if (g_window) pad_status(g_pad_present); }); } +static void install_main_menu(void) { + NSString *name = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleName"]; + if (!name.length) name = NSProcessInfo.processInfo.processName; @@ -1748,7 +1764,7 @@ index c7559ca..1d426e1 100644 unsigned w, h; const char *e = getenv("DM_GAME_RES"); if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4; return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280; -@@ -60,23 +111,34 @@ void front_run(void (*guest)(void)) { +@@ -60,23 +125,34 @@ void front_run(void (*guest)(void)) { @autoreleasepool { [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; @@ -1786,7 +1802,7 @@ index c7559ca..1d426e1 100644 if (!e.isARepeat) on_key(e, e.type == NSEventTypeKeyDown); return nil; // Swallow it to avoid the system beep }]; -@@ -93,14 +155,15 @@ void front_run(void (*guest)(void)) { +@@ -93,14 +169,15 @@ void front_run(void (*guest)(void)) { usingBlock:^(NSNotification *n) { (void)n; exit(0); }]; // Lifecycle (hle.h / dm.h): focus lost → 2, focus regained → 1; minimized → 3 + audio paused + GPU suspended, restored → resume (followed by focus regained → 1) NSNotificationCenter *nc = NSNotificationCenter.defaultCenter; @@ -1807,7 +1823,7 @@ index c7559ca..1d426e1 100644 } } diff --git a/dm/host/hle.c b/dm/host/hle.c -index 1a63bd7..9fcffec 100644 +index 1a63bd7..266bad2 100644 --- a/dm/host/hle.c +++ b/dm/host/hle.c @@ -17,6 +17,7 @@ extern uint64_t unimpl_stubs[MAX_STUB]; // 8 bytes per stub @@ -1818,7 +1834,7 @@ index 1a63bd7..9fcffec 100644 return 0; } -@@ -42,6 +43,16 @@ uint64_t resolve_import(module_t *m, const char *name) { +@@ -42,8 +43,21 @@ uint64_t resolve_import(module_t *m, const char *name) { return (uint64_t)hlecount_wrap("STUB", name, (void *)&unimpl_stubs[k]); } @@ -1834,12 +1850,25 @@ index 1a63bd7..9fcffec 100644 + void stubs_report(void) { LOG("stubs=%u", g_nstub); } ++// Compile-time stamp of this host binary (the window title in front_mac.m shows it so a stale dmhost is visible). ++const char *dm_host_build_stamp(void) { return __DATE__ " " __TIME__; } ++ // ---------- Host gate dispatch ---------- + // The rewriter replaces every svc #n / mrs cntpct with a call to dm_gate; here we remember, by gate block return point (absolute address), what it originally was. + // Lookup: open-addressing hash, one hit (it used to do module_of + a linear compare over 110 entries on every gate call, keyed by in-module offset, which would collide across modules). diff --git a/dm/host/hle.h b/dm/host/hle.h -index 79fda3d..bb8a80f 100644 +index 79fda3d..4f4f319 100644 --- a/dm/host/hle.h +++ b/dm/host/hle.h -@@ -77,4 +77,7 @@ uint64_t dm_audio_render_calls(void); // Cumulative sound card callback count +@@ -18,6 +18,7 @@ void *objmap_get(const void *guest); + void objmap_put(const void *guest, void *host); + void *objmap_del(const void *guest); + uint64_t now_ns(void); ++const char *dm_host_build_stamp(void); // __DATE__ " " __TIME__ of this host build (title bar) + // This thread is doing the host's own heavy work (NVN submit / present: encoding Metal commands; on hardware that is the GPU's business and does not occupy a guest core). The same-core preemption approximation (hle_thread.c) does not count it as "running" + extern __thread _Atomic int dm_host_work; + uint64_t guest_ns(void); // Guest clock (hle_os.c; does not advance while DM_TICK_HOLD is frozen) +@@ -77,4 +78,7 @@ uint64_t dm_audio_render_calls(void); // Cumulative sound card callback count // 0x8c Current act saved while in a rift (when the character is in a rift map w9 is replaced with 4 = Act V, writes x9; x8 always 0) dm_rift.c 0x6fa9d0 (branch gate: x8≠0 jumps to 0x6fa9d4, otherwise executes the original instruction and returns to 0x6fa9d4) // 0x8d Extra mercenary equipment slots (mercenary + rift level ≥10 + belt / boots / gloves / ring / amulet: w0 is replaced with 1, writes x0; x8 always 0) dm_rift.c 0x64a34c (branch gate: x8≠0 jumps to 0x64a350, otherwise executes the original instruction and returns to 0x64a350) // 0x8e Client-side check for the extra mercenary equipment slots (rift level ≥10 + the item is a belt / boots / gloves / ring / amulet: w1 is replaced with the item's own type number, writes x1; x8 always 0) dm_rift.c 0x3beb58 (branch gate: x8≠0 jumps to 0x3beb5c, otherwise executes the original instruction and returns to 0x3beb5c) @@ -1935,10 +1964,10 @@ index 3d309a1..ec44a2c 100644 +} diff --git a/dm/host/hle_d3_pubfile.c b/dm/host/hle_d3_pubfile.c new file mode 100644 -index 0000000..23023f3 +index 0000000..31a3a81 --- /dev/null +++ b/dm/host/hle_d3_pubfile.c -@@ -0,0 +1,174 @@ +@@ -0,0 +1,229 @@ +/* Diablo III offline publisher files: hand Seasons.txt / Blacklist.txt to the game's own lobby callbacks. + * + * The game fetches both files from the online service; with no service the season calendar stays empty and the @@ -1959,18 +1988,26 @@ index 0000000..23023f3 +// Payloads carry no season data of their own: the game only needs the calendar and the (empty) item blacklist. +// Byte-for-byte the strings d3hack synthesises (god-jester/d3hack, source/program/d3/hooks/season_events.hpp); +// the trailing blank line belongs to the seasons document format. ++// The guest parses these dates into its own epoch, which is 946,684,800 s (30 years) behind the text: ++// measured, text 2025-02-09 00:00 is stored as 1995-02-10 00:00, text 2036-02-09 01:00 as 2006-02-09 01:00. ++// The years below are therefore written +30 so the season window lands on 2025-02-09 .. 2036-02-09 once the ++// guest has re-based them; without the offset the UI sees a season that ended in 2006. ++// A time of exactly 00:00:00 also loses a day in the round trip (see the 1995-02-10 above), which is why the end ++// keeps 01:00:00 instead of midnight. +static const char k_seasons_text[] = + "# Format for dates MUST be: \" ? ? ? , DD MMM YYYY hh : mm:ss UTC\"\n" + "# The Day of Month(DD) MUST be 2 - digit; use either preceding zero or trailing space\n" + "[Season 37]\n" -+ "Start \"Sat, 09 Feb 2025 00:00:00 GMT\"\n" -+ "End \"Tue, 09 Feb 2036 01:00:00 GMT\"\n\n"; ++ "Start \"Sat, 09 Feb 2055 00:00:00 GMT\"\n" ++ "End \"Tue, 09 Feb 2066 01:00:00 GMT\"\n\n"; +static const char k_blacklist_text[] = + "# Blacklist overridden by d3hack\n" + "[GBID]\n\n" + "[SNO]\n"; +#define SEASONS_BYTES 239u +#define BLACKLIST_BYTES 47u ++_Static_assert(sizeof(k_seasons_text) - 1 == SEASONS_BYTES, "k_seasons_text length vs SEASONS_BYTES"); ++_Static_assert(sizeof(k_blacklist_text) - 1 == BLACKLIST_BYTES, "k_blacklist_text length vs BLACKLIST_BYTES"); + +// blz::string is 0x28 bytes: text, size, capacity-with-flags, then inline SSO scratch. The engine reads these +// fields directly (no accessor on the retrieval path), so the layout is reproduced here. @@ -1993,8 +2030,16 @@ index 0000000..23023f3 + OFF_LOBBY_B = 0x114b128, + OFF_BLACKLIST_CB = 0x657f0, // OnBlacklistFileRetrieved(self, eResult, shared_ptr *) + OFF_SEASONS_CB = 0x65270, // OnSeasonsFileRetrieved(self, eResult, shared_ptr *) ++ // bool XVarUint32_Set(XVarUint32 *this, uint32 value, uint32 dirty_flags). 2.7.6 0xa272c0 → 2.7.7 by ++ // nso_fnmap.py (containing function identical after address masking, +0x100 like the rest of the region). ++ // 2.7.7 0xa273c0 stores value inline at this+0xb0 (ldaxr/stlxr) and notifies observers at this+0xa8. ++ OFF_XVAR_SET = 0xa273c0, +}; +enum { MAX_INJECTIONS = 8 }; ++// Season values d3hack writes (patches.cpp: XVarUint32_Set(&g_varSeasonNum, 37, 3) / &g_varSeasonState, 1, 3). ++enum { SEASON_NUM = 37, SEASON_STATE = 1, XVAR_DIRTY = 3 }; ++ ++typedef int (*xvar_uint32_set_fn)(void *xvar, uint32_t value, uint32_t dirty_flags); + +static blz_string *s_seasons, *s_blacklist; +static blz_shared_ptr *s_sp_seasons, *s_sp_blacklist; @@ -2002,8 +2047,15 @@ index 0000000..23023f3 +static uint64_t s_delay = 600; // the lobby is not up before the front end; injecting earlier just hits null globals +static unsigned s_injections; +static pthread_once_t s_once = PTHREAD_ONCE_INIT; ++// Title-bar status (dm_d3_pubfile_status): written by the guest thread, read by the AppKit main thread. ++enum { PUBFILE_PENDING, PUBFILE_OFF, PUBFILE_ON }; ++static _Atomic int s_state = PUBFILE_PENDING; // PENDING until pubfile_init has decided ++static _Atomic int s_vec_seasons; // seasons vector non-empty as of the last report ++static _Atomic unsigned s_injected; // mirror of s_injections for the reader ++static _Atomic int s_set_num = -1, s_set_state = -1; // XVar setter return values (-1 = not called) + +static void pubfile_init(void) { ++ atomic_store(&s_state, PUBFILE_OFF); + const char *on = getenv("DM_D3_PUBFILE"); + if (on && !strcmp(on, "0")) { LOG("d3 pubfile: INFO disabled by DM_D3_PUBFILE=0"); return; } + const char *d = getenv("DM_D3_PUBFILE_DELAY"); @@ -2046,6 +2098,7 @@ index 0000000..23023f3 + s_sp_blacklist->pointer = s_blacklist; s_sp_blacklist->manager = NULL; + s_off = 0; + LOG("d3 pubfile: INFO enabled (main %s, %.0f frames delay, seasons %zu B, blacklist %zu B)", dm_main_build(), (double)s_delay, sl, bl); ++ atomic_store(&s_state, PUBFILE_ON); +} + +static module_t *main_module(void) { @@ -2074,7 +2127,20 @@ index 0000000..23023f3 + // cbz before its prologue; 3 is the network failure result and would return without parsing). + ((void (*)(void *, int, void *))(base + OFF_BLACKLIST_CB))(NULL, 0, s_sp_blacklist); + ((void (*)(void *, int, void *))(base + OFF_SEASONS_CB))(NULL, 0, s_sp_seasons); ++ // The retrieval tail (0x5ff20) recomputes the active-season state and pushes it through these same XVars, ++ // so the override has to land after it. The globals hold the XVar objects themselves: the getters ++ // 0x72e090/0x72e0a0 load them and tail-call XVarUint32_Get 0xa27470 (ldar [x0+0xb0]), and the tail at ++ // 0x600ac calls this setter with the loaded pointer in x0 and dirty flags 3. s_off only clears after the ++ // build-id/svc-gate checks in pubfile_init, so this runs on the surveyed image only. ++ void *num = grab(base, OFF_SEASONS_XVAR), *state = grab(base, OFF_ONLINE_XVAR); ++ xvar_uint32_set_fn set = (xvar_uint32_set_fn)(base + OFF_XVAR_SET); ++ int rn = num ? set(num, SEASON_NUM, XVAR_DIRTY) : -1; ++ int rs = state ? set(state, SEASON_STATE, XVAR_DIRTY) : -1; ++ atomic_store(&s_set_num, rn); ++ atomic_store(&s_set_state, rs); ++ LOG("d3 pubfile: xvar num=%p state=%p set(num)=%d set(state)=%d", num, state, rn, rs); + s_injections++; ++ atomic_store(&s_injected, s_injections); +} + +static void report(uint8_t *base) { @@ -2086,11 +2152,27 @@ index 0000000..23023f3 + uint64_t end = data ? *(uint64_t *)((uint8_t *)data + 0x18) : 0; + uint8_t *fs = *(uint8_t **)(base + OFF_SEASONS_PARSED); + uint8_t *fb = *(uint8_t **)(base + OFF_BLACKLIST_FLAG); ++ atomic_store(&s_vec_seasons, n ? 1 : 0); + LOG("d3 pubfile: seasons vec=%p n=%llu season=%u start=%llu end=%llu flags seasons=%u blacklist=%u", vec, + (unsigned long long)n, (unsigned)season, (unsigned long long)start, (unsigned long long)end, + fs ? (unsigned)*fs : 0u, fb ? (unsigned)*fb : 0u); +} + ++// Title-bar text (front_mac.m weak-calls this). Allocation-free and safe on any thread: it only reads the ++// numbers stored above. Returns 0 when the injector is off for this build (the caller then omits the field). ++int dm_d3_pubfile_status(char *buf, size_t n) { ++ if (!buf || n < 32) return 0; ++ int state = atomic_load(&s_state); ++ if (state == PUBFILE_OFF) return 0; ++ if (state == PUBFILE_PENDING || !atomic_load(&s_injected)) { ++ snprintf(buf, n, "injector idle"); ++ return 1; ++ } ++ snprintf(buf, n, "season %d injected (vec=%d, xvar=%d/%d)", SEASON_NUM, atomic_load(&s_vec_seasons), ++ atomic_load(&s_set_num) == 1, atomic_load(&s_set_state) == 1); ++ return 1; ++} ++ +void dm_d3_pubfile_tick(void) { + pthread_once(&s_once, pubfile_init); + if (s_off || dm_guest_frame() < s_delay) return; @@ -2101,6 +2183,8 @@ index 0000000..23023f3 + if (!s_injections) { + inject(m->base); + report(m->base); ++ // The title was set before the first tick; re-render it once the injector has a result. ++ { extern void dm_front_title_refresh(void) __attribute__((weak)); if (dm_front_title_refresh) dm_front_title_refresh(); } + } else if (!seasons_size(m->base) && s_injections < MAX_INJECTIONS) { + // The lobby is torn down and rebuilt on reconnect / character switch (main+0x72f7c clears the calendar). + // Without re-arming, the Journey disappears for the rest of the session; the cap keeps a pathological From 5bc04fe5383626d644fa079f3e0bba74830917da Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:22:54 +0000 Subject: [PATCH 09/13] Inject offline challenge rift data from captured weeklies OnGetChallengeRiftData (main+0x185f70) is not reachable offline: the service only registers it in the connected branch. The host calls it directly with the two parsed publisher documents and clears the gate byte on the resolved service instance, so the guest publishes the weekly data itself (measured valid=1, challenge_number 346). Payloads are the captured protobufs from vendor/d3hack read at runtime from work/rift_data; a missing directory disables the path instead of failing. Game Settings -> Mode Select now shows the Challenge Rifts row; it stays locked until a Greater Rift is cleared, so rift entry is not yet verified in game. --- docs/UPSTREAM_CHANGES.md | 1 + patches/nxnative.patch | 233 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 232 insertions(+), 2 deletions(-) diff --git a/docs/UPSTREAM_CHANGES.md b/docs/UPSTREAM_CHANGES.md index 0fe2cc9..3d72498 100644 --- a/docs/UPSTREAM_CHANGES.md +++ b/docs/UPSTREAM_CHANGES.md @@ -8,6 +8,7 @@ Base: seedds/nxnative `9579030e5b1f0443c12b7376559560915b6d4c4b` (MIT, includes - `patch_nso.py`: record the four in-place CTR_EL0 adaptations as explicit cuts, including original and new bytes. These set the host cache-line policy (DminLine=4); they are intentional adaptations, not claimed register-value equivalence. - `hle_account.c`: SDK 8 `OpenPreselectedUser(UserHandle*)` returns Result, unlike `TryOpenPreselectedUser`'s bool. Return the existing local user's complete 24-byte handle. The SDK public implementation requires a platform-populated UID and otherwise aborts; D3 calls it at `main+0x4c51cc`. A synthetic C test checks output canaries and GetUserId roundtrip. - `hle_misc.c`: adapt SDK 8 `CheckFreeCommunicationPermission(bool)` to the host's existing offline policy, returning false. Its SDK implementation tries to connect to `sm:` for the missing pctl service (`sdk+0x33a620`; observed guest backtrace). +- `hle_d3_pubfile.c`: offline publisher documents. The lobby never issues its own fetch offline, so the host hands the game's own callbacks the documents it would have downloaded: Seasons and Blacklist (season 37 calendar, `0x65270`/`0x657f0`), then the weekly challenge-rift protobufs (`0x185f70`, payloads read from `work/rift_data`, GPL sample weeklies in `vendor/d3hack`). Measured: the season calendar, season XVars and the challenge `valid` flag all land. The challenge mode row is visible in Game Settings → Mode Select but stays locked until a Greater Rift is cleared, so rift entry is unverified. The D3 profile uses exact full NSO Build IDs and SHA-256 in `config/diablo3-2.7.7.json`. The Mac address-space profile was increased after observing nninitStartup's 768 MiB allocation fail against the initial 256 MiB alias candidate. This is a virtual reservation policy, not an iPhone memory validation. diff --git a/patches/nxnative.patch b/patches/nxnative.patch index cf6d656..737e4fc 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -1964,10 +1964,10 @@ index 3d309a1..ec44a2c 100644 +} diff --git a/dm/host/hle_d3_pubfile.c b/dm/host/hle_d3_pubfile.c new file mode 100644 -index 0000000..31a3a81 +index 0000000..d9da2dc --- /dev/null +++ b/dm/host/hle_d3_pubfile.c -@@ -0,0 +1,229 @@ +@@ -0,0 +1,458 @@ +/* Diablo III offline publisher files: hand Seasons.txt / Blacklist.txt to the game's own lobby callbacks. + * + * The game fetches both files from the online service; with no service the season calendar stays empty and the @@ -1976,6 +1976,10 @@ index 0000000..31a3a81 + * + * Driven from oe::TryPopNotificationMessage (hle_oe.c) rather than the NVN present path: the render thread can + * hold graphics locks in present, and calling into the lobby from there risks a lock-order deadlock. ++ * ++ * The same path also feeds challengerift_config.dat + challengerift_NN.dat to OnGetChallengeRiftData and reports ++ * under its own "d3 pubfile: challenge" prefix; measured, the callback is called once per session after the seasons ++ * pair and publishes valid=1, so it is on by default and DM_D3_CHALLENGE=0 turns it off. + */ +#include "dm.h" +#include "dm_d3_graphics.h" @@ -2028,18 +2032,41 @@ index 0000000..31a3a81 + OFF_BLACKLIST_FLAG = 0x114ae58, // uint8_t **: "blacklist applied" flag + OFF_LOBBY_A = 0x114b0a0, // lobby objects the callbacks reach through + OFF_LOBBY_B = 0x114b128, ++ // Challenge-rift survey (cr_probe below): nothing in this file calls into these. ++ OFF_CR_SERVICE = 0x114d940, // service singleton, read as *(void **)(base + off) ++ OFF_CR_READY = 0x114d998, // registry object; *(uint8_t *)(obj + 0x18) & 4 gates the callback ++ OFF_CR_XVAR = 0x1158fd8, // challenge-rift-enabled XVar object pointer ++ // Challenge-rift injection call sites: the guest builds both messages from the payloads, the host owns the text. ++ OFF_CR_CONFIG_CTOR = 0x564d00, // void ChallengeData_ctor(ChallengeData *), 0x40-byte protobuf message ++ OFF_CR_WEEKLY_CTOR = 0x62abe0, // void WeeklyChallengeData_ctor(WeeklyChallengeData *), 0x40-byte message ++ OFF_CR_PARSE = 0xbb2c50, // bool ParsePartialFromString(Message *, const blz::string *data) ++ OFF_CR_CALLBACK = 0x185f70, // OnGetChallengeRiftData(bind, int *result, ChallengeData *, WeeklyChallengeData *) ++ OFF_XVAR_BOOL_SET = 0xa26fc0, // bool XVarBool_Set(XVarBool *this, bool value, uint32 dirty_flags) + OFF_BLACKLIST_CB = 0x657f0, // OnBlacklistFileRetrieved(self, eResult, shared_ptr *) + OFF_SEASONS_CB = 0x65270, // OnSeasonsFileRetrieved(self, eResult, shared_ptr *) + // bool XVarUint32_Set(XVarUint32 *this, uint32 value, uint32 dirty_flags). 2.7.6 0xa272c0 → 2.7.7 by + // nso_fnmap.py (containing function identical after address masking, +0x100 like the rest of the region). + // 2.7.7 0xa273c0 stores value inline at this+0xb0 (ldaxr/stlxr) and notifies observers at this+0xa8. + OFF_XVAR_SET = 0xa273c0, ++ // Gate/clock survey (challenge_once): only called, never inspected by the injector. ++ OFF_CR_RESOLVE = 0x327b50, // void *resolve_ns(void *handle, uint32_t one): hash-map lookup of the registry handle ++ OFF_CLOCK_NOW = 0x5fcb0, // uint64_t now_ns(void), epoch 2000 ++ OFF_CLOCK_UNIX = 0xa430, // int64_t ns_to_unix(uint64_t ns) ++ OFF_CLOCK_OFFSET = 0x114a0c38, // clock-offset object: { uint64_t value; uint32_t valid; ... } ++ // Challenge-unlock survey (challenge_once): the predicate behind the ModeSelect Challenge Rifts row, read-only. ++ // The row's caller (0x184804) enables it on (0x528320() == 0). ++ OFF_CR_UNLOCK = 0x528320, // int (void): *(uint8_t *)(inner + 0x64), or the fallback byte when inner is null ++ OFF_CR_UNLOCK_OBJ = 0x574e0, // void *(void): factory for the singleton whose +0x18 is `inner` ++ OFF_CR_UNLOCK_FALLBACK = 0x114a9c0, // void **: object the predicate falls back to when inner is null ++ OFF_CR_GAMESTATE = 0x4cafe0, // int (void): the == 6 test reached from 0x4c65b0 ++ OFF_CR_GAMESTATE_RAW = 0x114a8d0, // void **: the same value read straight off the global chain (+0x10 of the inner) +}; +enum { MAX_INJECTIONS = 8 }; +// Season values d3hack writes (patches.cpp: XVarUint32_Set(&g_varSeasonNum, 37, 3) / &g_varSeasonState, 1, 3). +enum { SEASON_NUM = 37, SEASON_STATE = 1, XVAR_DIRTY = 3 }; + +typedef int (*xvar_uint32_set_fn)(void *xvar, uint32_t value, uint32_t dirty_flags); ++typedef int (*parse_partial_fn)(void *msg, const blz_string *data); + +static blz_string *s_seasons, *s_blacklist; +static blz_shared_ptr *s_sp_seasons, *s_sp_blacklist; @@ -2053,6 +2080,73 @@ index 0000000..31a3a81 +static _Atomic int s_vec_seasons; // seasons vector non-empty as of the last report +static _Atomic unsigned s_injected; // mirror of s_injections for the reader +static _Atomic int s_set_num = -1, s_set_state = -1; // XVar setter return values (-1 = not called) ++static int s_cr_late; // the fixed post-report challenge-rift sample has been logged ++// Challenge-rift injection payload bytes plus the two blz::string headers over them (DM_D3_CHALLENGE=0 disables). ++static blz_string s_cr_config_str, s_cr_rift_str; ++static int s_cr_off = 1; // no payloads (flag absent, files missing) → nothing to do ++static int s_cr_attempted; // one attempt per session, no retry ++ ++// {DM_D3_RIFT_DIR} or {DM_ROOT}/rift_data. Kept separate from the payload readers so the log can name the file only. ++static int rift_dir(char *out, size_t n) { ++ const char *dir = getenv("DM_D3_RIFT_DIR"); ++ if (dir && *dir) { int r = snprintf(out, n, "%s", dir); return r > 0 && (size_t)r < n; } ++ const char *root = getenv("DM_ROOT"); ++ if (!root || !*root) return 0; ++ int r = snprintf(out, n, "%s/rift_data", root); ++ return r > 0 && (size_t)r < n; ++} ++ ++// Reads one publisher document whole (31 B config, 3-8 KB weekly). Returns NULL and sets *why on any problem, so ++// the caller can log a reason instead of failing the whole injector. ++static uint8_t *read_payload(const char *dir, const char *name, size_t *len, const char **why) { ++ char path[1024]; ++ *why = "path too long"; ++ int r = snprintf(path, sizeof path, "%s/%s", dir, name); ++ if (r <= 0 || (size_t)r >= sizeof path) return NULL; ++ FILE *f = fopen(path, "rb"); ++ if (!f) { *why = "missing"; return NULL; } ++ if (fseek(f, 0, SEEK_END)) { *why = "unreadable"; fclose(f); return NULL; } ++ long size = ftell(f); ++ if (size <= 0) { *why = "empty"; fclose(f); return NULL; } ++ if (size > (1 << 20)) { *why = "too large"; fclose(f); return NULL; } ++ if (fseek(f, 0, SEEK_SET)) { *why = "unreadable"; fclose(f); return NULL; } ++ uint8_t *buf = malloc((size_t)size); ++ if (!buf) { *why = "out of memory"; fclose(f); return NULL; } ++ if (fread(buf, 1, (size_t)size, f) != (size_t)size) { *why = "short read"; free(buf); fclose(f); return NULL; } ++ fclose(f); ++ *len = (size_t)size; ++ return buf; ++} ++ ++static void challenge_init(void) { ++ const char *on = getenv("DM_D3_CHALLENGE"); ++ if (on && !strcmp(on, "0")) { LOG("d3 pubfile: challenge INFO disabled by DM_D3_CHALLENGE=0"); return; } ++ unsigned num = 0; ++ const char *snum = getenv("DM_D3_RIFT_NUM"); ++ if (snum && *snum) { ++ char *end; unsigned long v = strtoul(snum, &end, 10); ++ if (end == snum || *end || v > 99) die("DM_D3_RIFT_NUM 非法:%s", snum); ++ num = (unsigned)v; ++ } ++ char dir[900]; ++ if (!rift_dir(dir, sizeof dir)) { LOG("d3 pubfile: challenge INFO disabled (no rift_data directory)"); return; } ++ char weekly[32]; ++ snprintf(weekly, sizeof weekly, "challengerift_%02u.dat", num); ++ size_t clen = 0, rlen = 0; ++ const char *why = NULL; ++ uint8_t *config = read_payload(dir, "challengerift_config.dat", &clen, &why); ++ if (!config) { LOG("d3 pubfile: challenge INFO disabled (challengerift_config.dat %s)", why); return; } ++ uint8_t *rift = read_payload(dir, weekly, &rlen, &why); ++ if (!rift) { free(config); LOG("d3 pubfile: challenge INFO disabled (%s %s)", weekly, why); return; } ++ // Neither block is ever freed: the guest parser keeps the text pointer for as long as it holds the message, the ++ // same contract as the seasons/blacklist payloads above. Embedded capacity (bit63) tells the guest it must not ++ // hand the pointer to the allocator, which is what makes host memory legal here. ++ const uint64_t embedded = 1ull << 63; ++ s_cr_config_str = (blz_string){(const char *)config, clen, (uint64_t)clen | embedded, {0, 0}}; ++ s_cr_rift_str = (blz_string){(const char *)rift, rlen, (uint64_t)rlen | embedded, {0, 0}}; ++ s_cr_off = 0; ++ LOG("d3 pubfile: challenge INFO enabled (%s, config %zu B, weekly %s %zu B)", dir, clen, weekly, rlen); ++} + +static void pubfile_init(void) { + atomic_store(&s_state, PUBFILE_OFF); @@ -2099,6 +2193,7 @@ index 0000000..31a3a81 + s_off = 0; + LOG("d3 pubfile: INFO enabled (main %s, %.0f frames delay, seasons %zu B, blacklist %zu B)", dm_main_build(), (double)s_delay, sl, bl); + atomic_store(&s_state, PUBFILE_ON); ++ challenge_init(); +} + +static module_t *main_module(void) { @@ -2119,6 +2214,25 @@ index 0000000..31a3a81 + return vec ? *(uint64_t *)((uint8_t *)vec + 8) : 0; +} + ++// Offline challenge-rift survey: the publisher path for challengerift_*.dat reads these three main-image ++// globals. Read-only and null-checked at every level, because the registry is torn down on reconnect. ++// The tuple (service, ready, ready & 4) only moves at lobby transitions, so the tick samples it by change ++// and report() forces one line per injection. ++static void cr_probe(uint8_t *base, int force) { ++ static int last_service = -1, last_ready = -1, last_armed = -1; ++ void *service = grab(base, OFF_CR_SERVICE); ++ void *ready = grab(base, OFF_CR_READY); ++ void *xvar = grab(base, OFF_CR_XVAR); ++ unsigned flags = ready ? *(uint8_t *)((uint8_t *)ready + 0x18) & 0xffu : 0u; ++ int has_service = service != NULL, has_ready = ready != NULL, armed = (flags & 4u) != 0; ++ if (!force && has_service == last_service && has_ready == last_ready && armed == last_armed) return; ++ if (ready) ++ LOG("d3 pubfile: cr globals service=%p ready=%p flags=%#x xvar=%p", service, ready, flags, xvar); ++ else ++ LOG("d3 pubfile: cr globals service=%p ready=%p flags=(null) xvar=%p", service, ready, xvar); ++ last_service = has_service; last_ready = has_ready; last_armed = armed; ++} ++ +static void inject(uint8_t *base) { + // The callback may have replaced the pair on an earlier pass; reset it before every call. + s_sp_blacklist->pointer = s_blacklist; s_sp_blacklist->manager = NULL; @@ -2143,6 +2257,112 @@ index 0000000..31a3a81 + atomic_store(&s_injected, s_injections); +} + ++typedef int (*xvar_bool_set_fn)(void *xvar, uint32_t value, uint32_t dirty_flags); ++ ++enum { CR_MESSAGE_BYTES = 0x40 }; ++ ++// One-shot probe of the offline challenge-rift tail. Each stage logs before it can fault, so a crash is attributable ++// to the stage after the last printed line. No destructor is ever called on the two messages: the callback may keep ++// them, and the host-visible payload text must stay alive with them. ++static void challenge_once(uint8_t *base) { ++ if (s_cr_off || s_cr_attempted) return; ++ s_cr_attempted = 1; ++ // The registry ready byte (OFF_CR_READY + 0x18) is measured 0xc6 offline but 0xc1 in a live session, so bit 0x4 is ++ // not set there and has to be written (on the resolved object, below); the XVar above is turned on for the same ++ // reason, the callback wants rifts enabled on both. ++ void *xvar = grab(base, OFF_CR_XVAR); ++ int set = xvar ? ((xvar_bool_set_fn)(base + OFF_XVAR_BOOL_SET))(xvar, 1, XVAR_DIRTY) : -1; ++ LOG("d3 pubfile: challenge xvar=%p set(1)=%d", xvar, set); ++ void *service = grab(base, OFF_CR_SERVICE); ++ uint8_t *config = calloc(1, CR_MESSAGE_BYTES), *weekly = calloc(1, CR_MESSAGE_BYTES); ++ if (!config || !weekly) { ++ LOG("d3 pubfile: challenge out of memory, giving up"); ++ free(config); free(weekly); ++ return; ++ } ++ ((void (*)(void *))(base + OFF_CR_CONFIG_CTOR))(config); ++ ((void (*)(void *))(base + OFF_CR_WEEKLY_CTOR))(weekly); ++ LOG("d3 pubfile: challenge ctor config vptr=%p weekly vptr=%p", *(void **)config, *(void **)weekly); ++ parse_partial_fn parse = (parse_partial_fn)(base + OFF_CR_PARSE); ++ int pc = parse(config, &s_cr_config_str), pw = parse(weekly, &s_cr_rift_str); ++ LOG("d3 pubfile: challenge parse config=%d weekly=%d", pc, pw); ++ // The callback errors out unless start <= now < end, and the documents carry fixed dates; widen the window to the ++ // whole epoch like d3hack does instead of trusting their timestamps. challenge_number_ is kept as parsed; the ++ // window overrides also need ChallengeData._has_bits_ bit 3 at +0x10, because the callback tests that bit before ++ // it converts end from seconds to ns and silently ignores a host-written +0x30 without it. ++ *(uint8_t *)(config + 0x10) |= 0x8; ++ *(uint64_t *)(config + 0x18) = 0; ++ *(uint64_t *)(config + 0x30) = 0x7fffffff; ++ LOG("d3 pubfile: challenge number=%u orb_multiplier=%g", *(uint32_t *)(config + 0x28), (double)*(float *)(config + 0x2c)); ++ uint32_t bind = 0, result = 0; ++ // Gate survey: every path that reaches the callback writes valid=1 unconditionally, so valid=0 in the result line ++ // means one of the two silent early exits was taken. The first one tests a byte on the object the registry handle ++ // *resolves to* (0x327b50 is a hash-map lookup, w1=1), not on *(0x114d998) itself, which is what cr_probe samples. ++ { ++ typedef void *(*resolve_ns_fn)(void *handle, uint32_t one); ++ typedef uint64_t (*now_ns_fn)(void); ++ typedef int64_t (*ns_to_unix_fn)(uint64_t ns); ++ void *handle = grab(base, OFF_CR_READY); ++ void *resolved = handle ? ((resolve_ns_fn)(base + OFF_CR_RESOLVE))(handle, 1) : NULL; ++ unsigned flags = resolved ? *(uint8_t *)((uint8_t *)resolved + 0x18) & 0xffu : 0u; ++ // The early exit at 0x185fd0 (tbz w8,#2) tests this byte on the resolved object, so the write has to land on ++ // that same pointer; setting it on the registry handle (what cr_probe samples) would not be seen. ++ unsigned flags_after = flags; ++ if (resolved) { ++ ((uint8_t *)resolved)[0x18] |= 0x4; ++ flags_after = *(uint8_t *)((uint8_t *)resolved + 0x18) & 0xffu; ++ } ++ if (handle) ++ LOG("d3 pubfile: challenge gate handle=%p resolved=%p same=%d flags=%#x -> %#x", handle, resolved, ++ resolved == handle, flags, flags_after); ++ else ++ LOG("d3 pubfile: challenge gate handle=%p resolved=(skipped) same=%d flags=%#x", handle, 0, flags); ++ uint64_t now = ((now_ns_fn)(base + OFF_CLOCK_NOW))(); ++ int64_t unix_ns = ((ns_to_unix_fn)(base + OFF_CLOCK_UNIX))(now); ++ LOG("d3 pubfile: challenge clock now_ns=%llu now_unix=%lld (%#llx)", (unsigned long long)now, (long long)unix_ns, ++ (unsigned long long)unix_ns); ++ void *offset = grab(base, OFF_CLOCK_OFFSET); ++ if (offset) ++ LOG("d3 pubfile: challenge clock offset=%p value=%llu valid=%u", offset, (unsigned long long)*(uint64_t *)offset, ++ *(uint32_t *)((uint8_t *)offset + 8)); ++ else ++ LOG("d3 pubfile: challenge clock offset=%p value=(null) valid=(null)", offset); ++ } ++ // ModeSelect Challenge Rifts row survey, all reads: the predicate chain evaluated by hand so the byte that keeps ++ // the row locked is visible before anything writes it. Null-checked at every step, because these singletons are ++ // rebuilt at lobby transitions and the setter writes above must stay attributable if the chain has moved. ++ { ++ int unlock = ((int (*)(void))(base + OFF_CR_UNLOCK))(); ++ LOG("d3 pubfile: challenge unlock fn=%d", unlock); ++ void *obj = ((void *(*)(void))(base + OFF_CR_UNLOCK_OBJ))(); ++ void *inner = obj ? *(void **)((uint8_t *)obj + 0x18) : NULL; ++ if (inner) ++ LOG("d3 pubfile: challenge unlock obj=%p inner=%p byte=%#x", obj, inner, *(uint8_t *)((uint8_t *)inner + 0x64)); ++ else ++ LOG("d3 pubfile: challenge unlock obj=%p inner=%p byte=(null)", obj, inner); ++ void *fallback = grab(base, OFF_CR_UNLOCK_FALLBACK); ++ void *fallback_inner = fallback ? *(void **)((uint8_t *)fallback + 0x18) : NULL; ++ if (fallback_inner) ++ LOG("d3 pubfile: challenge unlock fallback=%p byte=%#x", fallback_inner, *(uint8_t *)((uint8_t *)fallback_inner + 0x64)); ++ else ++ LOG("d3 pubfile: challenge unlock fallback=%p byte=(null)", fallback_inner); ++ int gamestate = ((int (*)(void))(base + OFF_CR_GAMESTATE))(); ++ void *raw = grab(base, OFF_CR_GAMESTATE_RAW); ++ void *raw_inner = raw ? *(void **)raw : NULL; ++ if (raw_inner) ++ LOG("d3 pubfile: challenge gamestate value=%#x raw=%#x", (unsigned)gamestate, *(uint32_t *)((uint8_t *)raw_inner + 0x10)); ++ else ++ LOG("d3 pubfile: challenge gamestate value=%#x raw=(null)", (unsigned)gamestate); ++ } ++ LOG("d3 pubfile: challenge calling callback service=%p", service); ++ ((void (*)(void *, int *, void *, void *))(base + OFF_CR_CALLBACK))(&bind, (int *)&result, config, weekly); ++ uint32_t number = *(uint32_t *)(config + 0x28); ++ if (service) ++ LOG("d3 pubfile: challenge result=%d number=%u valid=%#x", (int)result, number, *(uint32_t *)((uint8_t *)service + 0x2e0)); ++ else ++ LOG("d3 pubfile: challenge result=%d number=%u valid=(no service)", (int)result, number); ++} ++ +static void report(uint8_t *base) { + void *vec = grab(base, OFF_SEASONS_VEC); + uint64_t n = vec ? *(uint64_t *)((uint8_t *)vec + 8) : 0; @@ -2156,6 +2376,7 @@ index 0000000..31a3a81 + LOG("d3 pubfile: seasons vec=%p n=%llu season=%u start=%llu end=%llu flags seasons=%u blacklist=%u", vec, + (unsigned long long)n, (unsigned)season, (unsigned long long)start, (unsigned long long)end, + fs ? (unsigned)*fs : 0u, fb ? (unsigned)*fb : 0u); ++ cr_probe(base, 1); +} + +// Title-bar text (front_mac.m weak-calls this). Allocation-free and safe on any thread: it only reads the @@ -2193,6 +2414,14 @@ index 0000000..31a3a81 + inject(m->base); + report(m->base); + } ++ // Probe of the untraced challenge-rift tail: only after the seasons/blacklist pair has been handed over, and only ++ // once per session (challenge_once self-guards), because a fault here must not repeat every frame. ++ if (s_injections) challenge_once(m->base); ++ // One sample on top of the change-driven ones: state that only settles after the lobby has been up for a ++ // while would otherwise never be recorded, since the injector reports just once per injection. ++ int late = !s_cr_late && dm_guest_frame() >= s_delay + 600; ++ s_cr_late |= late; ++ cr_probe(m->base, late); + atomic_store(&busy, 0); +} + From aae696abd7ba474e9166c1f5b85d022f08c9cabe Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:39:06 +0000 Subject: [PATCH 10/13] Log the guest's requested MSAA level One summary line per run from the texture-initialization counters, plus the swapchain sample count in WindowInitialize. Measured on 2.7.7: the guest never calls nvnTextureBuilderSetSamples, so every texture and the swapchain is single-sample. d3hack's MSAA clamp rule and its dead extra.msaal_level override therefore have no target here. --- patches/nxnative.patch | 99 +++++++++++++++++++++++++++++++++++------- 1 file changed, 84 insertions(+), 15 deletions(-) diff --git a/patches/nxnative.patch b/patches/nxnative.patch index 737e4fc..221df7f 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -1,5 +1,5 @@ diff --git a/dm/gfx/nvn/hle_nvn.c b/dm/gfx/nvn/hle_nvn.c -index d4c3531..de5f4f5 100644 +index d4c3531..ebe0d0f 100644 --- a/dm/gfx/nvn/hle_nvn.c +++ b/dm/gfx/nvn/hle_nvn.c @@ -52,6 +52,7 @@ static uint8_t g_unimpl_seen[NVN_NFUNC]; @@ -28,7 +28,31 @@ index d4c3531..de5f4f5 100644 // ---------- Memory pools ---------- NVN(nvnMemoryPoolBuilderSetDefaults, void, NVNmemoryPoolBuilder *b) { memset(b, 0, sizeof(pool_builder_t)); } -@@ -205,6 +208,8 @@ NVN(nvnTextureBuilderSetSize1D, void, NVNtextureBuilder *b, int w) { TB(b)->d.wi +@@ -189,6 +192,23 @@ NVN(nvnSamplerPoolInitialize, NVNboolean, NVNsamplerPool *sp, const NVNmemoryPoo + NVN(nvnSamplerPoolFinalize, void, NVNsamplerPool *sp) { (void)sp; } + NVN(nvnSamplerPoolRegisterSampler, void, const NVNsamplerPool *sp, int id, const NVNsampler *s) { (void)sp; mtl_reg_samp(id, &((const samp_t *)s)->p); } + ++// ---------- MSAA 统计(只读埋点:游戏实际请求多少样本、按贴图种类分)---------- ++// 记在贴图初始化而不是 BuilderSetSamples:同一个 builder 可能被多次初始化,按初始化计数才等于每张贴图一次 ++static _Atomic uint64_t g_msaa_hist[9]; // 下标 = 请求样本数,8 含更高 ++static _Atomic uint64_t g_msaa_ntex, g_msaa_nms, g_msaa_ndepth_ms; ++static _Atomic int g_msaa_done; // 汇总行只出一行,出过之后不再计数 ++static void msaa_report(void); ++// 深度目标:NVN 的贴图 builder 没有 usage 字段,只能看格式(STENCIL8 到 DEPTH32F_STENCIL8 连续一段) ++static int msaa_is_depth(int fmt) { return fmt >= NVN_FORMAT_STENCIL8 && fmt <= NVN_FORMAT_DEPTH32F_STENCIL8; } ++static void msaa_note(const nvn_texdesc *d) { ++ if (atomic_load(&g_msaa_done)) return; ++ unsigned b = d->samples < 0 ? 0u : (unsigned)d->samples > 8 ? 8u : (unsigned)d->samples; // 0 和 1 都是单采样,分开列 ++ atomic_fetch_add(&g_msaa_hist[b], 1); ++ uint64_t n = atomic_fetch_add(&g_msaa_ntex, 1) + 1; ++ if (d->samples > 1) { atomic_fetch_add(&g_msaa_nms, 1); if (msaa_is_depth(d->format)) atomic_fetch_add(&g_msaa_ndepth_ms, 1); } ++ if (n >= 96) msaa_report(); ++} ++ + // ---------- Textures ---------- + #define TB(b) ((tex_builder_t *)(b)) + NVN(nvnTextureBuilderSetDefaults, void, NVNtextureBuilder *b) { +@@ -205,6 +225,8 @@ NVN(nvnTextureBuilderSetSize1D, void, NVNtextureBuilder *b, int w) { TB(b)->d.wi NVN(nvnTextureBuilderSetLevels, void, NVNtextureBuilder *b, int v) { TB(b)->d.levels = v; } NVN(nvnTextureBuilderSetFormat, void, NVNtextureBuilder *b, NVNformat f) { TB(b)->d.format = f; } NVN(nvnTextureBuilderSetSamples, void, NVNtextureBuilder *b, int s) { TB(b)->d.samples = s; } @@ -37,7 +61,15 @@ index d4c3531..de5f4f5 100644 NVN(nvnTextureBuilderSetStride, void, NVNtextureBuilder *b, ptrdiff_t s) { TB(b)->d.stride = (uint32_t)s; } NVN(nvnTextureBuilderSetStorage, void, NVNtextureBuilder *b, NVNmemoryPool *p, ptrdiff_t off) { TB(b)->pool = (pool_t *)p; TB(b)->off = off; } NVN(nvnTextureBuilderSetPackagedTextureLayout, void, NVNtextureBuilder *b, const NVNpackagedTextureLayout *l) { -@@ -371,9 +376,16 @@ static int keys_hash(const NVNshaderData *sd, int mapped, uint8_t out[8]) { +@@ -249,6 +271,7 @@ NVN(nvnTextureInitialize, NVNboolean, NVNtexture *t, const NVNtextureBuilder *b) + } + OLOG("Texture %p %ux%ux%u lv%u fmt=%#x tgt=%d flags=%#x size=%#llx", (void *)t, o->d.width, o->d.height, o->d.depth, + o->d.levels, o->d.format, o->d.target, o->d.flags, o->L.size); ++ msaa_note(&o->d); // 放在最后:计数只看已写好的描述,不影响上面任何一步 + return 1; + } + NVN(nvnTextureFinalize, void, NVNtexture *t) { mtl_tex_release(TX(t)); TX(t)->magic = 0; } +@@ -371,9 +394,16 @@ static int keys_hash(const NVNshaderData *sd, int mapped, uint8_t out[8]) { return 1; } int prog_key(const prog_t *p, unsigned st, uint8_t key[8]) { @@ -56,7 +88,7 @@ index d4c3531..de5f4f5 100644 memcpy(key, k->key[st], 8); return 1; } -@@ -395,21 +407,53 @@ NVN(nvnProgramSetShaders, NVNboolean, NVNprogram *p, int n, const NVNshaderData +@@ -395,21 +425,53 @@ NVN(nvnProgramSetShaders, NVNboolean, NVNprogram *p, int n, const NVNshaderData } // ---------- Sync / events ---------- @@ -122,7 +154,7 @@ index d4c3531..de5f4f5 100644 } NVN(nvnEventBuilderSetDefaults, void, NVNeventBuilder *b) { memset(b, 0, sizeof(ev_builder_t)); } NVN(nvnEventBuilderSetStorage, void, NVNeventBuilder *b, const NVNmemoryPool *p, int64_t off) { *(ev_builder_t *)b = (ev_builder_t){(const pool_t *)p, off}; } -@@ -456,6 +500,41 @@ NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; mtl_finish(); } +@@ -456,6 +518,41 @@ NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; mtl_finish(); } #define CB(c) ((cmd_t *)(c)) #define OP_RESERVE 24 // Always keep enough room at the segment end for one JUMP / END @@ -164,7 +196,7 @@ index d4c3531..de5f4f5 100644 NVN(nvnCommandBufferInitialize, NVNboolean, NVNcommandBuffer *c, NVNdevice *d) { memset(c, 0, sizeof(cmd_t)); CB(c)->magic = MAGIC('C', 'M', 'D', 'B'); CB(c)->dev = d; return 1; } -@@ -485,6 +564,7 @@ static void cmd_new_segment(cmd_t *o, uint8_t *mem, size_t n) { +@@ -485,6 +582,7 @@ static void cmd_new_segment(cmd_t *o, uint8_t *mem, size_t n) { uint8_t *start = align8(mem), *end = mem + n; if (o->recording && o->cur) { if (cs_on() && o->end > o->cur) { pthread_mutex_lock(&g_cs_mu); g_cs.waste += (uint64_t)(o->end - o->cur); pthread_mutex_unlock(&g_cs_mu); } put_hdr(o->cur, OP_JUMP, 16); memcpy(o->cur + 8, &start, 8); o->used += 16; } // the JUMP also occupies guest memory of this recording: count it in used, so the game packing the next recording right behind by used does not overwrite it @@ -172,7 +204,7 @@ index d4c3531..de5f4f5 100644 o->cur = start; o->end = end; } // Host-supplied segment when the game's own command memory runs out: when the game's out-of-memory callback cannot allocate from its command memory pool, it calls AddCommandMemory with an empty pool (p = NULL, n = 0) -@@ -559,19 +639,36 @@ static uint8_t *cmd_alloc(cmd_t *o, uint32_t size) { +@@ -559,19 +657,36 @@ static uint8_t *cmd_alloc(cmd_t *o, uint32_t size) { } NVN(nvnCommandBufferBeginRecording, void, NVNcommandBuffer *c) { cmd_t *o = CB(c); @@ -213,7 +245,7 @@ index d4c3531..de5f4f5 100644 } NVN(nvnCommandBufferSignalEvent, void, NVNcommandBuffer *c, const NVNevent *e, NVNeventSignalMode m, NVNeventSignalLocation loc, int flags, uint32_t v) { (void)loc; (void)flags; -@@ -652,7 +749,12 @@ NVN(nvnCommandBufferSetViewports, void, NVNcommandBuffer *c, int first, int n, c +@@ -652,7 +767,12 @@ NVN(nvnCommandBufferSetViewports, void, NVNcommandBuffer *c, int first, int n, c NVN(nvnCommandBufferSetScissor, void, NVNcommandBuffer *c, int x, int y, int w, int h) { *REC(c, OP_SCISSOR, p_scissor) = (p_scissor){x, y, w, h}; } NVN(nvnCommandBufferSetDepthRange, void, NVNcommandBuffer *c, float n, float f) { *REC(c, OP_DEPTH_RANGE, p_depth_range) = (p_depth_range){n, f}; } NVN(nvnCommandBufferBindProgram, void, NVNcommandBuffer *c, const NVNprogram *p, int stages) { @@ -227,7 +259,7 @@ index d4c3531..de5f4f5 100644 } static void bind_state(NVNcommandBuffer *c, int kind, const void *st, size_t n) { p_bind_state *r = REC(c, OP_BIND_STATE, p_bind_state); r->kind = kind; memcpy(r->bytes, st, n); } NVN(nvnCommandBufferBindBlendState, void, NVNcommandBuffer *c, const NVNblendState *st) { bind_state(c, 0, st, sizeof(blend_st)); } -@@ -743,6 +845,12 @@ NVN(nvnCommandBufferCopyTextureToTexture, void, NVNcommandBuffer *c, const NVNte +@@ -743,6 +863,12 @@ NVN(nvnCommandBufferCopyTextureToTexture, void, NVNcommandBuffer *c, const NVNte p_copy_t2t *o = REC_SNAP(c, OP_COPY_T2T, p_copy_t2t, 2); o->src = tex_snap(o, SNAP_OFF(p_copy_t2t), 0, s, (uint64_t)__builtin_return_address(0)); o->dst = tex_snap(o, SNAP_OFF(p_copy_t2t), 1, d, (uint64_t)__builtin_return_address(0)); copy_view(&o->sv, &o->has_sv, sv); copy_view(&o->dv, &o->has_dv, dv); o->sr = *sr; o->dr = *dr; o->flags = flags; } @@ -240,7 +272,7 @@ index d4c3531..de5f4f5 100644 NVN(nvnCommandBufferSetCopyRowStride, void, NVNcommandBuffer *c, ptrdiff_t st) { p_copy_stride *o = REC(c, OP_COPY_STRIDE, p_copy_stride); o->stride = st; o->image = 0; } NVN(nvnCommandBufferSetCopyImageStride, void, NVNcommandBuffer *c, ptrdiff_t st) { p_copy_stride *o = REC(c, OP_COPY_STRIDE, p_copy_stride); o->stride = st; o->image = 1; } // Link's Awakening NVN(nvnCommandBufferSetBlendColor, void, NVNcommandBuffer *c, const float *v) { memcpy(REC(c, OP_BLEND_COLOR, p_blend_color)->rgba, v, 16); } -@@ -838,7 +946,10 @@ void dm_gfx_suspend(int on) { +@@ -838,7 +964,10 @@ void dm_gfx_suspend(int on) { if (on) { mtl_drain(); LOG("[nvn] 图形挂起:在途 GPU 工作已清空"); } else LOG("[nvn] 图形恢复"); } NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) { @@ -251,7 +283,7 @@ index d4c3531..de5f4f5 100644 uint64_t t0 = now_ns(), c0 = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID), i0, y0, s0 = thr_sys_ns(); thr_counts(&i0, &y0); ((queue_t *)q)->submits++; mtl_sub_begin(); -@@ -852,6 +963,7 @@ NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) +@@ -852,6 +981,7 @@ NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) atomic_fetch_add(&g_cum_sub_cyc, y1 - y0); atomic_fetch_add(&g_cum_sub_sys_ns, thr_sys_ns() - s0); atomic_fetch_add(&g_cum_sub_wall_ns, dw); atomic_fetch_add(&g_sub_cpu_ns, dc); atomic_fetch_add(&g_cum_sub_cpu_ns, dc); atomic_fetch_add(&g_sub_instr, di); atomic_fetch_add(&g_cum_sub_instr, di); @@ -259,7 +291,7 @@ index d4c3531..de5f4f5 100644 gfx_leave(); } -@@ -863,7 +975,6 @@ static const char *const g_nops[] = { +@@ -863,7 +993,6 @@ static const char *const g_nops[] = { "nvnCommandBufferMultiDrawElementsIndirectCount", "nvnCommandBufferDispatchComputeIndirect", "nvnCommandBufferSetDepthBounds", @@ -267,7 +299,43 @@ index d4c3531..de5f4f5 100644 "nvnCommandBufferSetShaderScratchMemory", "nvnCommandBufferPushDebugGroupDynamic", "nvnCommandBufferPopDebugGroup", -@@ -1218,6 +1329,9 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) { +@@ -916,8 +1045,9 @@ NVN(nvnWindowInitialize, NVNboolean, NVNwindow *w, const NVNwindowBuilder *b) { + memset(o, 0, sizeof *o); o->magic = MAGIC('W', 'I', 'N', 'D'); o->native = s->native; o->ntex = s->ntex; o->interval = s->interval; + memcpy(o->tex, s->tex, sizeof o->tex); + for (int i = 0; i < o->ntex; i++) if (o->tex[i]) mtl_xv_window_tex(CTX(o->tex[i])->serial); +- LOG("[nvn] WindowInitialize 交换链 %d 张 间隔 %d 首张 %dx%d 格式 %#x", o->ntex, o->interval, +- o->ntex ? (int)CTX(o->tex[0])->d.width : 0, o->ntex ? (int)CTX(o->tex[0])->d.height : 0, o->ntex ? CTX(o->tex[0])->d.format : 0); ++ LOG("[nvn] WindowInitialize 交换链 %d 张 间隔 %d 首张 %dx%d 格式 %#x 样本 %d", o->ntex, o->interval, ++ o->ntex ? (int)CTX(o->tex[0])->d.width : 0, o->ntex ? (int)CTX(o->tex[0])->d.height : 0, o->ntex ? CTX(o->tex[0])->d.format : 0, ++ o->ntex ? CTX(o->tex[0])->d.samples : 0); + return 1; + } + NVN(nvnWindowGetPresentInterval, int, const NVNwindow *w) { return ((const win_t *)w)->interval; } // Link's Awakening reads it back every frame +@@ -938,6 +1068,15 @@ __attribute__((weak)) void dm_main_yield_stats(uint64_t *n, uint64_t *ns) { *n = + __attribute__((weak)) uint32_t dm_guest_work_qos(unsigned *count) { if (count) *count = 0; return QOS_CLASS_UNSPECIFIED; } + extern uint32_t mtl_present_qos(void); + static uint64_t g_frame; ++// MSAA 汇总行:帧数只在 present 路径上推进,帧 900 这个触发条件只能放在这里(贴图数满 96 时已由 msaa_note 提前触发) ++static void msaa_report(void) { ++ if (atomic_exchange(&g_msaa_done, 1)) return; ++ unsigned long long h[9]; ++ for (int i = 0; i < 9; i++) h[i] = atomic_load(&g_msaa_hist[i]); ++ LOG("nvn MSAA 统计:纹理 %llu 张,samples>1 %llu 张(深度 %llu),分布 0:%llu 1:%llu 2:%llu 4:%llu 8:%llu", ++ (unsigned long long)atomic_load(&g_msaa_ntex), (unsigned long long)atomic_load(&g_msaa_nms), ++ (unsigned long long)atomic_load(&g_msaa_ndepth_ms), h[0], h[1], h[2], h[4], h[8]); ++} + static uint64_t g_acq_wait_ns, g_pq_wait_ns; // Accumulated display-link wait / wait for the present queue to return inside acquire, recorded per frame at present (there can be several acquires within one frame) + uint64_t dm_nvn_frame_count(void) { return g_frame; } + extern uint64_t g_t0_ns; // Host process start point (main.c; same base as the UIMSG timestamps) +@@ -974,6 +1113,7 @@ NVN(nvnQueueAcquireTexture, NVNqueueAcquireTextureResult, NVNqueue *q, NVNwindow + static uint64_t g_prev[NVN_NFUNC]; + static FILE *g_tsv; + static void dump_frame(void) { ++ if (g_frame >= 900) msaa_report(); // 第二个触发条件(帧计数的自增在函数末尾,这里 g_frame 就是本帧序号) + static int inited, nframes = 3, calls = 1; + if (!inited) { + inited = 1; +@@ -1218,6 +1358,9 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) { if (pproc) trow(f, "@proc_cpu_ms", (pc - pproc) / 1e6); pproc = pc; trow(f, "@call_ms", (t0 - g_t0_ns) / 1e6); } @@ -277,7 +345,7 @@ index d4c3531..de5f4f5 100644 trow(f, "@passes", (double)(ps - prev_pass)); trow(f, "@draws", (double)(dr - prev_draw)); static uint64_t pl, pst, pf, pudc; uint64_t l, st, fu; mtl_bw(&l, &st, &fu); trow(f, "@rt_load_mb", (l - pl) / 1048576.0); trow(f, "@rt_store_mb", (st - pst) / 1048576.0); trow(f, "@pass_full_rw", (double)(fu - pf)); -@@ -1435,7 +1549,14 @@ NVN_NOPROTO(nvnProgramSetShadersExt, NVNboolean, NVNprogram *p, int n, const sha +@@ -1435,7 +1578,14 @@ NVN_NOPROTO(nvnProgramSetShadersExt, NVNboolean, NVNprogram *p, int n, const sha // Singular / combined forms → plural / separate forms; state the replay layer does not have yet (conditional render, depth bounds, ...) is logged once and drawing continues (better to over-draw than to drop). #include "../tex/nvn_deswizzle.h" @@ -293,7 +361,7 @@ index d4c3531..de5f4f5 100644 // Combined texture handle (texture id | sampler id << 20) is recorded into the texture slot as is: the replay layer takes the texture from the low 20 bits and the sampler from the high bits (nvn_mtl.m NVN_RB_SAMPT) NVN(nvnCommandBufferBindTexture, void, NVNcommandBuffer *c, NVNshaderStage st, int i, NVNtextureHandle h) { uint64_t v = (uint64_t)h; bind_handles(c, OP_BIND_TEX, st, i, 1, &v); } // "Deferred" binding: the GPU reads the handles h points to when it executes this command, not at recording. The per-texture binding of The Legend of Zelda: Breath of the Wild's engine (main+0xec2e64) always uses it, -@@ -1573,4 +1694,12 @@ int nvn_host_signal_sync(void *nvnsync) { +@@ -1573,4 +1723,12 @@ int nvn_host_signal_sync(void *nvnsync) { if (!o || o->magic != MAGIC('S', 'Y', 'N', 'C')) return -1; o->fence = 0; o->fenced = 1; return 0; } @@ -307,6 +375,7 @@ index d4c3531..de5f4f5 100644 + if (!(CTX(t)->d.flags & (NVN_TEXTURE_FLAGS_LINEAR | NVN_TEXTURE_FLAGS_LINEAR_RENDER_TARGET))) + mtl_tex_cpu_written(CTX(t)); +} + diff --git a/dm/gfx/nvn/nvn_command_copy.h b/dm/gfx/nvn/nvn_command_copy.h new file mode 100644 index 0000000..06df5cf From 00a7d31deac5013da100d1cc56dff73eb8b7994a Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:53:18 +0000 Subject: [PATCH 11/13] Raise the wide profile to 1920x720 Render area 1,382,400 px stays below the original docked 1,440,000, so the pool-budget envelope is unchanged; horizontal FOV grows 50% and MetalFX now reconstructs 1920x720 into 2560x960 at 1.333x instead of 1568x720 into 2560x1176 at 1.633x. Guard words regenerated from the emitted image rather than hand-encoded; the previous 1568 words are now a reject vector. Verified: rewrite/verify clean, 6 profile tests pass, headless wide run presents 1920x720 -> 2560x960 with no red lines at 59.8 fps (gpu 4.10 ms mean, 5.05 p95). --- PRODUCT.md | 2 +- README.md | 2 +- README.zh-CN.md | 2 +- STATUS.md | 2 +- docs/LAUNCH_UI.md | 2 +- docs/METALFX.md | 4 ++-- docs/MOBILE_WIDESCREEN.md | 16 ++++++------- patches/nxnative.patch | 23 ++++++++++--------- platform/ios/Sources/front_ios.m | 8 +++---- platform/ios/Sources/main.m | 4 ++-- tests/test_d3_graphics.c | 7 +++++- tests/test_mobile_graphics_profile.py | 6 ++--- tools/build_ios.py | 2 +- tools/mac-i18n/en.lproj/Localizable.strings | 2 +- .../zh-Hans.lproj/Localizable.strings | 2 +- tools/mobile_graphics_profile.py | 2 +- 16 files changed, 46 insertions(+), 40 deletions(-) diff --git a/PRODUCT.md b/PRODUCT.md index cae28a0..93c3759 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -14,7 +14,7 @@ Inherit the current Bayonetta3 Mobile native launcher's two-column UIKit setting ## Rendering and network truth -The selected Air widescreen profile renders 1568×720 with expanded horizontal camera view. MetalFX Spatial targets 2560×1176; normal mode targets 2560×1440. Device rendering and performance must be verified separately from build or simulator UI results. Local multiplayer uses a native LAN transport and Bonjour discovery; actual two-device gameplay requires an end-to-end test. Battle.net and mesh are outside this request's implementation. +The selected Air widescreen profile renders 1920×720 with expanded horizontal camera view. MetalFX Spatial targets 2560×960; normal mode targets 2560×1440. Device rendering and performance must be verified separately from build or simulator UI results. Local multiplayer uses a native LAN transport and Bonjour discovery; actual two-device gameplay requires an end-to-end test. Battle.net and mesh are outside this request's implementation. ## Constraints diff --git a/README.md b/README.md index c474501..09f0a76 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ As of **2026-10-18**. Research preview, not complete-game compatibility. | Local Wi-Fi | Mac host → iPhone client joined the same party; user confirmed both characters visible. Long sessions, combat/drop/scene synchronization, four players and reverse hosting remain unverified | | Public Internet / Mesh | Design contract only; no released Mesh integration or Battle.net services | -The launcher offers Metal HUD, MetalFX Spatial, normal/wide view and local Wi-Fi options. The tested wide profile renders at 1568×720; mobile MetalFX targets approximately 2K while preserving aspect. macOS and iOS use separate shader builds. Frame rate varies with device and scene; this is not a guarantee of sustained 60 FPS. +The launcher offers Metal HUD, MetalFX Spatial, normal/wide view and local Wi-Fi options. The wide profile renders at 1920×720; mobile MetalFX targets approximately 2K while preserving aspect. macOS and iOS use separate shader builds. Frame rate varies with device and scene; this is not a guarantee of sustained 60 FPS. Constant-update forwarding substantially improved the observed Mac scene performance, but the original lantern flicker reproduced when forwarding was enabled. Attachment-dependency guards retain the optimization; the original location still needs dynamic visual acceptance. Full chapters, sustained thermal behavior, every rendering path and extended multiplayer stability are pending. See [status](STATUS.md), [acceptance checklist](docs/COMPLETION_CHECKLIST.md), [rendering notes](docs/LANTERN_STABILITY.md) and [LAN scope](docs/LAN_MULTIPLAYER.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 9b38dba..8cd0bac 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -23,7 +23,7 @@ | 本地 Wi-Fi | Mac 建房、iPhone 加入同一队伍,用户确认看到双方角色;长时间同步、战斗/掉落/换场景、四人及反向建房待验收 | | 公网 / Mesh | 仅有接入契约,尚未完成;不提供战网、商店及互联网好友服务 | -实测宽屏为 1568×720,保留纵向视野;手机 MetalFX 按画幅输出约 2K。帧率随设备和场景变化,不承诺全程 60 FPS。常量更新转发曾显著改善 Mac 实测帧率,也曾引发灯笼闪烁;附件依赖守卫保留优化,原位置动态画面仍需验收。详见[当前状态](STATUS.md)、[剩余验收](docs/COMPLETION_CHECKLIST.md)与[灯笼记录](docs/LANTERN_STABILITY.md)。 +宽屏为 1920×720,保留纵向视野;手机 MetalFX 按画幅输出约 2K。帧率随设备和场景变化,不承诺全程 60 FPS。常量更新转发曾显著改善 Mac 实测帧率,也曾引发灯笼闪烁;附件依赖守卫保留优化,原位置动态画面仍需验收。详见[当前状态](STATUS.md)、[剩余验收](docs/COMPLETION_CHECKLIST.md)与[灯笼记录](docs/LANTERN_STABILITY.md)。 ## 自行构建 diff --git a/STATUS.md b/STATUS.md index 9345192..a36c7ad 100644 --- a/STATUS.md +++ b/STATUS.md @@ -16,7 +16,7 @@ Current LAN result (2026-10-18): Latest configuration/LAN integration: - D2R Mobile fast-forwarded from 21cf97b to 9393b00 (v1.0.18); three existing local modified files preserved byte-for-byte. Generic MIT touch joystick/socket artwork copied with provenance, original D3 bindings retained. -- Native iOS launch menu selects HUD, MetalFX, wide/normal and Wi-Fi LAN before guest preload. Real camera/UI wide profile 1568×720 is embedded as signed code alongside original; MetalFX output is 2560×1176 for Air or 2560×1440 for normal. Differently shaped iPads preserve picture aspect. +- Native iOS launch menu selects HUD, MetalFX, wide/normal and Wi-Fi LAN before guest preload. Real camera/UI wide profile 1920×720 is embedded as signed code alongside original; MetalFX output is 2560×960 for Air or 2560×1440 for normal. Differently shaped iPads preserve picture aspect. - Complete `make test` and Mac/iPhoneOS builds passed; actual MetalFX GPU fixture passed 336 channel checks. Four opt-in LAN ASan/UBSan tests include actual Bonjour discovery, UDP/TCP and lifecycle boundaries. These are separate from actual multiplayer gameplay acceptance. - Candidate Mac app: `work/macapp-lan-metalfx/DR3 Mobile.app`. Signed iOS SHA: ac59ec201249df26df12c5b72c2a25758dbbad6e7d6458a313245e09577a457f, developer team, both memory entitlements verified. Current install/session status is in `work/run/ios-launch-settings-20261018/` and `work/ios-device-session.json`. - User confirmed old iPhone build reached town with working touch and audible sound. Original Mac save remains unchanged. User saved to title before authorizing this update; device save and original app separately backed up. diff --git a/docs/LAUNCH_UI.md b/docs/LAUNCH_UI.md index 9a02b45..2bf3877 100644 --- a/docs/LAUNCH_UI.md +++ b/docs/LAUNCH_UI.md @@ -22,7 +22,7 @@ Mac 是上述原生设置界面的 AppKit 适配,继续沿用左侧游戏身 - 标题使用系统字体 28 pt semibold,说明与状态使用系统字体 12 pt;分组标题与控件文字沿用 AppKit 默认排印。窗口初始内容区为 760×470 pt,最小内容区为 700×450 pt;左右边距 28 pt、上边距 28 pt、底部至少 24 pt,左栏宽 240 pt,栏间距 30 pt。左栏间距 16 pt,右侧分组间距 14 pt,分组内部间距 8 pt。最小尺寸和大字号下的实际布局尚未独立截图验收。 - 新的偏好域默认选择正常 16:9,Metal HUD、MetalFX 超分与本地 Wi-Fi 联机默认开启。正常/宽屏和三个开关立即保存至 `NSUserDefaults`;重新打开启动器可重新选择。宽屏选项依赖包内独立的 `rewrite-wide` 映像,打包时检查其配置与独立验证结果;资源缺失时该分段不可选并回到正常模式。 - 玩家选择后点击“开始游戏”(Return 快捷键)才启动游戏。启动器先设置本次画面、HUD、MetalFX 与 LAN 环境,再以 `execv` 执行新的 host 进程;重复开始受保护。源码为启动失败提供原生 `NSAlert` 并恢复开始按钮,但错误状态外观尚未截图验证。 -- 正常模式说明为 1280×720、原版 16:9 视野;宽屏说明为 1568×720、扩大左右视野。MetalFX 开关会切换“超分至 2K”或“直接适配窗口”的辅助文字。`third_party/nxnative/dm/host/front_mac.m` 按所选画面比例居中显示,在窗口尺寸或 backing scale 改变时重新计算画面区域,允许留边;MetalFX 的输出目标为正常 2560×1440/宽屏 2560×1176。这是源码中的显示契约,完整窗口调整与性能验收另行记录。 +- 正常模式说明为 1280×720、原版 16:9 视野;宽屏说明为 1920×720、扩大左右视野。MetalFX 开关会切换“超分至 2K”或“直接适配窗口”的辅助文字。`third_party/nxnative/dm/host/front_mac.m` 按所选画面比例居中显示,在窗口尺寸或 backing scale 改变时重新计算画面区域,允许留边;MetalFX 的输出目标为正常 2560×1440/宽屏 2560×960。这是源码中的显示契约,完整窗口调整与性能验收另行记录。 - 常规包使用本机原有 `work/run/save`,界面显示“存档:本机游戏进度”。私有 `tools/mac_app.py --test-session <目录>` 将既有独立存档副本路径写入 bundle 的 `DR3TestSessionRoot`,启动器显示“存档:联机测试副本”;测试包的该标记不代表常规包改用了副本。 当前有效截图是 `.impeccable/review/mac-launcher/desktop.png`(1520×1004),来自实际 AppKit 启动器的系统深色外观,可确认两栏、三个设置分组、宽屏选择、开启的图形/LAN 开关与测试存档标记均可读。早期 `initial-layout.png` 是已被替换的压缩布局,不作为当前界面依据。`.impeccable/review/mac-launcher/finish-review.json` 的 `ship` 只覆盖 Mac 启动器 UI;本次另有宽屏选择持久化及 MetalFX 关闭/开启辅助文字的运行检查。浅色外观、其他语言、大字号、辅助功能遍历和错误状态外观仍未验收。 diff --git a/docs/METALFX.md b/docs/METALFX.md index 5434f5c..27a0be0 100644 --- a/docs/METALFX.md +++ b/docs/METALFX.md @@ -6,11 +6,11 @@ - 启动前设置 `DM_METALFX=spatial`;`off` 或未设置时继续常规呈现。 - `mtl_set_metalfx(int)` 可切换呈现路径,但不会改变游戏渲染尺寸或相机。 -- 游戏/前端负责实际的原生宽屏几何和渲染分辨率,例如 `DM_GAME_RES=1568x720`。后端不修改游戏 shader、c1、原始链 `87c50a868147`、相机投影或 NVN render target 尺寸。 +- 游戏/前端负责实际的原生宽屏几何和渲染分辨率,例如 `DM_GAME_RES=1920x720`。后端不修改游戏 shader、c1、原始链 `87c50a868147`、相机投影或 NVN render target 尺寸。 - 前端负责 `CAMetalLayer.drawableSize`。后端直接使用实际 drawable 尺寸,不硬编码 16:9 或 4K。2560×1176 是约 2K 宽屏输出的测试例,2048×940 也已验证;应根据实际屏幕比例计算尺寸。 - macOS/iOS 目标必须链接 `MetalFX.framework`。当前 backend 使用 Metal 4 呈现队列,目标系统仍为 macOS/iOS 26。 -**`content=1568x720` 的 MetalFX 日志只证明 upscaler 输入区域是 720 高;它本身不能证明游戏的全部渲染目标已经降到 720p。** 实际分辨率、相机宽屏和性能还需要游戏路径与设备日志共同验收。 +**`content=1920x720` 的 MetalFX 日志只证明 upscaler 输入区域是 720 高;它本身不能证明游戏的全部渲染目标已经降到 720p。** 实际分辨率、相机宽屏和性能还需要游戏路径与设备日志共同验收。 ## 图形实现 diff --git a/docs/MOBILE_WIDESCREEN.md b/docs/MOBILE_WIDESCREEN.md index eb2b56f..73fbc4f 100644 --- a/docs/MOBILE_WIDESCREEN.md +++ b/docs/MOBILE_WIDESCREEN.md @@ -1,6 +1,6 @@ # D3 原生宽屏与 720p 渲染配置 -2026-10-18。实现是原始游戏的渲染尺寸、显示比例和相机投影配置,不是把 16:9 帧拉伸或裁切。当前固定 iPhone 宽屏配置为 **1568×720,aspect=98/45≈2.17778**;两种 performance mode 使用同一尺寸。相对 16:9,相同垂直视野下的水平可见跨度增加 **22.5%**。MetalFX 和最终 drawable 分辨率由显示后端单独控制。 +2026-10-18。实现是原始游戏的渲染尺寸、显示比例和相机投影配置,不是把 16:9 帧拉伸或裁切。当前固定 iPhone 宽屏配置为 **1920×720,aspect=8/3≈2.66667**;两种 performance mode 使用同一尺寸。相对 16:9,相同垂直视野下的水平可见跨度增加 **50%**。MetalFX 和最终 drawable 分辨率由显示后端单独控制。 首轮实机宽屏出现嵌套矩形、清屏底色和右/下黑区,**未通过运行验收**。随后独立 Mac 宽屏在关闭 MetalFX 时也复现,说明故障先于最终上屏。已定位并修复漏掉的 handheld 纹理尺寸查询转换,见下节;修复版本仍需实际画面回归,不能把先前投影数学通过当作整条渲染链通过。本轮没有操作正在运行的设备、存档或窗口。 @@ -54,13 +54,13 @@ ```python from mobile_graphics_profile import launch_directory, verify -wide_dir = launch_directory(work, unique_destination, 1568, 720) -report = verify(original_verified_main_bytes, width=1568, height=720) +wide_dir = launch_directory(work, unique_destination, 1920, 720) +report = verify(original_verified_main_bytes, width=1920, height=720) ``` `launch_directory` 校验 main/SDK 原始 NSO 的完整 Build ID 和 SHA-256、精确配置文件哈希、成功 verification 回执,以及**完整** rewrite 工件集合及每项 SHA-256。先校验所有指令和投影/UI 证据,再创建新目录;拒绝覆盖。输出独立 `main.patched.bin`、其余原 rewrite 工件的链接和 `graphics.json`。原始 rewrite、fixups、客体身份保持不变。 -纯配置器的保守数学验证范围为 height=720、width 1280..1920 且按 8 对齐;面积低于原 docked 1600×900。但 iOS 当前签名宽屏选项固定 **1568×720**,运行时 guard 拒绝其他配置。像素面积较低不证明所有更宽纹理步长/分配都安全。 +纯配置器的保守数学验证范围为 height=720、width 1280..1920 且按 8 对齐;面积低于原 docked 1600×900。但 iOS 当前签名宽屏选项固定 **1920×720**,运行时 guard 拒绝其他配置。像素面积较低不证明所有更宽纹理步长/分配都安全。 iOS 打包器把宽屏复制作为 `mainwide` 的签名节别名,仍使用 main 的 fixups。`loader.c` 只在 D3 iOS 构建中读取启动前的 `DM_IOS_GRAPHICS_MODE`: @@ -70,21 +70,21 @@ iOS 打包器把宽屏复制作为 `mainwide` 的签名节别名,仍使用 mai 选择改变的是节名称;`m.name`、模块布局、重定位和游戏身份仍为 main。正常启动后不修改可执行代码。真实完整 NSO 身份由打包阶段的完整哈希校验保证;运行时另核对 fixups 中的原 Build ID 与宽屏签名内容。 -1568:720 与 iPhone Air 的 2736:1260 相差约 0.292%;最终显示后端可在宽屏模式使用全窗口分辨率,吸收这项小于 1% 的像素舍入差异。它不会把原 16:9 的水平视野冒充超宽视野。横竖屏/设备几何应在 guest 预加载前确定;运行中切换需要另行生命周期方案。 +1920×720 的渲染面积 1,382,400 px 仍低于原 docked 1600×900 的 1,440,000 px;MetalFX 以 1.333× 倍放大到 2560×960,相对正常模式的 2560×1440 输出,在窗口/屏幕内按 8:3 居中并上下留边。8:3 比 iPhone Air 的 2736:1260 更宽,显示后端只居中不拉伸或裁切。它不会把原 16:9 的水平视野冒充超宽视野。横竖屏/设备几何应在 guest 预加载前确定;运行中切换需要另行生命周期方案。 ## 已完成的独立验证 ```sh .venv/bin/python -m unittest discover -s tests -p test_mobile_graphics_profile.py -v -.venv/bin/python tools/mobile_graphics_profile.py --width 1568 +.venv/bin/python tools/mobile_graphics_profile.py --width 1920 ``` - LLVM 独立解码确认目标寄存器、尺寸、位移和约束谓词;Unicorn 执行真实 initializer、display query、UI 尺寸与投影切片。 -- 对 1280、1568、1920 各执行 64 组透视和 64 组正交 normal/wide 对照,确认水平系数降低且垂直完全不变。 +- 对 1280、1600、1920 各执行 64 组透视和 64 组正交 normal/wide 对照,确认水平系数降低且垂直完全不变。 - 新增完整纹理查询函数的真实 PC/GOT 执行,每个尺寸配置 28 项:原版 1600×900→1280×720、首版错误的全/半/四分之一尺寸、修复后的双模式,以及无关纹理和宽高不匹配的负对照。它补充了首版验证漏掉的中间 RT 依赖;不代替运行画面回归。 - 修改范围恢复比对、原输入不变、重复配置/越界尺寸/损坏指令/损坏投影证据均拒绝。 - 打包负对照包括编辑点外的 hash 损坏、缺失工件、未知原 NSO,失败时不创建目标目录。 - C fixture 使用与 iOS loader **同一个** `dm_d3_graphics.h`,验证 normal/SDK 身份、未知 build/模式拒绝、真实配置映像关键字与破坏变异;另已通过 ASan/UBSan。 - `loader.c` 通过 iPhoneOS SDK 的独立 syntax-only 编译;不代表签名安装或游戏画面验收。 -当前原始 rewrite SHA-256 `3d8df7cf3f9526d0379f93eaea1b50f7c53a61a7d0d4e4453a0462a41f124a7a`,对应修复后的 1568×720 配置 SHA-256 `9b4271cd74ad0df8988aa23eb52d43483507a3d076ea3397994825cd2c9275b2`。首版失败的配置 SHA 为 `1d7c9b839a87610c38b76cda3bf54732eebf830aff97f4e6acec6c4ab5ca81ba`,仅保留作失败证据。若通用 rewrite 更新,应重新生成并验证,不绕过 guard。 +当前原始 rewrite SHA-256 `05e9888c3a766d966ceb4c6e3c67de200027673a9310f840b6a0f6e850458e4d`,对应修复后的 1920×720 配置 SHA-256 `df6148a9175765db0c5864d0b73aafef03258e247af00ac74849b765743dbda7`。首版失败的配置 SHA 为 `1d7c9b839a87610c38b76cda3bf54732eebf830aff97f4e6acec6c4ab5ca81ba`,仅保留作失败证据。若通用 rewrite 更新,应重新生成并验证,不绕过 guard。 diff --git a/patches/nxnative.patch b/patches/nxnative.patch index 221df7f..984aa3b 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -1682,10 +1682,10 @@ index 31b4420..6c2626e 100644 + env -u SOURCE_DATE_EPOCH clang $(CFLAGS) -I../gfx/nvn/include -I$(dir $(GAME_H)) -I$(GAME_DIR) -I$(VPX) -I../third_party/stb_vorbis -fobjc-arc -o $@ $(SRC) $(GFX) $(VPX_LIB) -framework Cocoa -framework GameController -framework CoreHaptics -framework QuartzCore -framework Metal -framework MetalFX -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers diff --git a/dm/host/dm_d3_graphics.h b/dm/host/dm_d3_graphics.h new file mode 100644 -index 0000000..c6da2da +index 0000000..fe7203b --- /dev/null +++ b/dm/host/dm_d3_graphics.h -@@ -0,0 +1,34 @@ +@@ -0,0 +1,35 @@ +// D3 exact-build signed-image selection. No executable bytes are written. +#pragma once +#include @@ -1700,12 +1700,13 @@ index 0000000..c6da2da + return "mainwide"; +} +static inline int dm_d3_wide_text_valid(const uint8_t *text,size_t length) { -+ // Fixed packaged profile: 1568x720 in both modes, aspect 98/45, authored ++ // Fixed packaged profile: 1920x720 in both modes, aspect 8/3, authored + // 16:9 constraint predicate disabled. This is not a generic image patcher. + static const struct { size_t offset;uint32_t word; } expected[]={ -+ {0xe7858,0xd280c408},{0xe785c,0xd280c409}, ++ // Words emitted by sites(1920,720) over the verified rewrite, not hand-encoded. ++ {0xe7858,0xd280f008},{0xe785c,0xd280f009}, + {0xe7860,0xf2c05a08},{0xe7864,0xf2c05a09}, -+ {0xe7868,0x528c16ca},{0xe786c,0x72a8016a}, ++ {0xe7868,0x5295556a},{0xe786c,0x72a8054a}, + {0xe7870,0xb90012ca},{0xe7874,0xa90026c8}, + {0xebb48,0x1e2e1001}, + {0x29b480,0x52800000},{0x29b484,0xd65f03c0}, @@ -1812,7 +1813,7 @@ index c7559ca..d71b581 100644 +} +static void update_game_layer(NSView *view,NSWindow *window) { + if(!configured_display())return; -+ double aspect=configured_wide()?1568.0/720.0:16.0/9.0; ++ double aspect=configured_wide()?1920.0/720.0:16.0/9.0; + CGRect bounds=view.bounds,frame=bounds; + if(bounds.size.height<=0||bounds.size.width<=0)return; + if(bounds.size.width/bounds.size.height>aspect)frame.size.width=bounds.size.height*aspect; @@ -1821,7 +1822,7 @@ index c7559ca..d71b581 100644 + [CATransaction begin];[CATransaction setDisableActions:YES];g_layer.frame=frame; + g_layer.contentsScale=window.backingScaleFactor; + const char *fx=getenv("DM_METALFX"); -+ g_layer.drawableSize=fx&&!strcmp(fx,"spatial")?CGSizeMake(2560,configured_wide()?1176:1440): ++ g_layer.drawableSize=fx&&!strcmp(fx,"spatial")?CGSizeMake(2560,configured_wide()?960:1440): + CGSizeMake(round(frame.size.width*g_layer.contentsScale),round(frame.size.height*g_layer.contentsScale)); + [CATransaction commit]; +} @@ -1829,7 +1830,7 @@ index c7559ca..d71b581 100644 void *front_metal_layer(void) { return (__bridge void *)g_layer; } // The original game's 16:9 constants, behavior unchanged; DM_GAME_RES=x (docked mode; handheld scaled by 720/900) is only for side-by-side comparison with iOS widescreen uint64_t front_game_res(int docked) { -+ if(configured_wide())return 720ull<<32|1568; ++ if(configured_wide())return 720ull<<32|1920; unsigned w, h; const char *e = getenv("DM_GAME_RES"); if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4; return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280; @@ -1838,7 +1839,7 @@ index c7559ca..d71b581 100644 [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - NSRect r = NSMakeRect(0, 0, 1280, 720); -+ NSRect r = NSMakeRect(0, 0, 1280, configured_wide()?588:720); ++ NSRect r = NSMakeRect(0, 0, 1280, configured_wide()?480:720); NSWindow *win = [[NSWindow alloc] initWithContentRect:r styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; @@ -1855,7 +1856,7 @@ index c7559ca..d71b581 100644 - v.layer = g_layer; + if(configured_display()) { + v.layer=[CALayer layer];v.layer.backgroundColor=NSColor.blackColor.CGColor;[v.layer addSublayer:g_layer]; -+ win.contentAspectRatio=NSMakeSize(configured_wide()?1568:1280,720);win.contentMinSize=NSMakeSize(640,configured_wide()?294:360); ++ win.contentAspectRatio=NSMakeSize(configured_wide()?1920:1280,720);win.contentMinSize=NSMakeSize(640,configured_wide()?240:360); + v.postsFrameChangedNotifications=YES;update_game_layer(v,win); + [NSNotificationCenter.defaultCenter addObserverForName:NSViewFrameDidChangeNotification object:v queue:nil + usingBlock:^(NSNotification *n){(void)n;update_game_layer(v,win);}]; @@ -3791,7 +3792,7 @@ index e237a24..2fe8d62 100644 const uint8_t *x0 = getsectiondata(IMAGE_MH, "__TEXT", sx0, &z0), *w = getsectiondata(IMAGE_MH, dm, "__img", &zw), *x1 = getsectiondata(IMAGE_MH, "__TEXT", sx1, &z1); if (!x0 || !w || !x1) die("内嵌节 %s / %s / %s 缺失", sx0, dm, sx1); +#if DM_GAME_PROGRAM_ID == 0x01001B300B9BE000ull -+ if(!strcmp(section_name,"mainwide")&&!dm_d3_wide_text_valid(x0,z0))die("D3 signed wide image words/geometry mismatch; rebuild the verified 1568x720 profile"); ++ if(!strcmp(section_name,"mainwide")&&!dm_d3_wide_text_valid(x0,z0))die("D3 signed wide image words/geometry mismatch; rebuild the verified 1920x720 profile"); +#endif // Patch area before the base (patch_off < 0): W ends at the end of data (FILE_IMAGE_LEN); bss and the key page are zero pages from vm_allocate and are not in the executable int front = m->patch_off < 0; diff --git a/platform/ios/Sources/front_ios.m b/platform/ios/Sources/front_ios.m index f32df25..c237d59 100644 --- a/platform/ios/Sources/front_ios.m +++ b/platform/ios/Sources/front_ios.m @@ -36,7 +36,7 @@ - (instancetype)initWithFrame:(CGRect)f { - (void)layoutSubviews { [super layoutSubviews]; CAMetalLayer *l = (CAMetalLayer *)self.layer; - l.drawableSize = g_metalfx?CGSizeMake(2560,g_wide?1176:1440):CGSizeMake(round(self.bounds.size.width*l.contentsScale),round(self.bounds.size.height*l.contentsScale)); + l.drawableSize = g_metalfx?CGSizeMake(2560,g_wide?960:1440):CGSizeMake(round(self.bounds.size.width*l.contentsScale),round(self.bounds.size.height*l.contentsScale)); } @end @@ -66,8 +66,8 @@ - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; CGRect b = self.view.bounds; if (!self.game) return; CGFloat w = b.size.width, h = b.size.height; - CGFloat aspect=g_wide?1568.0/720.0:16.0/9.0; - // Fill the matching Air panel; preserve geometry on differently shaped iPads. + CGFloat aspect=g_wide?1920.0/720.0:16.0/9.0; + // Center at the profile aspect; panels with another shape are letterboxed. if(!g_wide || fabs(w/h/aspect-1.0)>=0.01) { if(w/h>aspect)w=h*aspect;else h=w/aspect; } @@ -82,7 +82,7 @@ - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfac UIViewController *front_ios_root(void) { return [DmRootVC new]; } void *front_metal_layer(void) { return (__bridge void *)g_layer; } -uint64_t front_game_res(int docked) { return g_wide?(720ull<<32|1568):docked?(900ull<<32|1600):(720ull<<32|1280); } +uint64_t front_game_res(int docked) { return g_wide?(720ull<<32|1920):docked?(900ull<<32|1600):(720ull<<32|1280); } void front_run(void (*guest)(void)) { guest(); } // Already on main.m's big-stack thread // Software keyboard: show a UIAlertController on the main thread, the calling thread waits for the result diff --git a/platform/ios/Sources/main.m b/platform/ios/Sources/main.m index bb189cc..6d89f6c 100644 --- a/platform/ios/Sources/main.m +++ b/platform/ios/Sources/main.m @@ -27,7 +27,7 @@ static BOOL wide_available(void) { NSDictionary *profile=graphics_profile(),*p=profile[@"parameters"]; return [profile[@"startup_selection"] boolValue] && [profile[@"mode"] isEqual:@"d3-mobile-graphics"] && - [p[@"width"] intValue]==1568 && [p[@"height"] intValue]==720; + [p[@"width"] intValue]==1920 && [p[@"height"] intValue]==720; } #include "../../../native/asset_inventory.h" @@ -119,7 +119,7 @@ - (void)startWide:(BOOL)wide hud:(BOOL)hud metalfx:(BOOL)metalfx lan:(BOOL)lan { setenv("MTL_HUD_ENABLED",hud?"1":"0",1); setenv("DM_METALFX",metalfx?"spatial":"off",1); setenv("DM_IOS_GRAPHICS_MODE",wide?"wide":"normal",1); - setenv("DM_GAME_RES",wide?"1568x720":"1280x720",1); + setenv("DM_GAME_RES",wide?"1920x720":"1280x720",1); setenv("DM_DR3_LAN",lan?"1":"0",1); fprintf(stderr,"boot: launch mode=%s render=%s HUD=%d MetalFX=%s LAN=%d\n",wide?"wide":"normal",getenv("DM_GAME_RES"),hud,metalfx?"spatial":"off",lan); front_ios_configure_display(wide,metalfx); diff --git a/tests/test_d3_graphics.c b/tests/test_d3_graphics.c index 4c0295f..fd317dc 100644 --- a/tests/test_d3_graphics.c +++ b/tests/test_d3_graphics.c @@ -20,7 +20,12 @@ int main(int argc,char **argv) { for(unsigned i=0;i Date: Tue, 27 Oct 2026 14:08:08 +0000 Subject: [PATCH 12/13] Bypass the challenge-rift callback gate without touching online state Writing bit 0x4 into the resolved service object made the front end believe an online session existed, so the main-menu Continue action stalled (measured: works with DM_D3_CHALLENGE=0, dead with the write). Replace it with an equal-length cut: main+0x185fd0 tbz w8,#2,#0x186044 -> nop (original word 0x361003a8 read from the image). Verified: rewrite/verify clean with the 9th registered main cut, and a headless run with the injection on still publishes (valid=0x1, number 346) while Continue loads the hero and commits the save. --- patches/nxnative.patch | 42 ++++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/patches/nxnative.patch b/patches/nxnative.patch index 984aa3b..6f545bb 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -2034,10 +2034,10 @@ index 3d309a1..ec44a2c 100644 +} diff --git a/dm/host/hle_d3_pubfile.c b/dm/host/hle_d3_pubfile.c new file mode 100644 -index 0000000..d9da2dc +index 0000000..161e0a1 --- /dev/null +++ b/dm/host/hle_d3_pubfile.c -@@ -0,0 +1,458 @@ +@@ -0,0 +1,455 @@ +/* Diablo III offline publisher files: hand Seasons.txt / Blacklist.txt to the game's own lobby callbacks. + * + * The game fetches both files from the online service; with no service the season calendar stays empty and the @@ -2337,9 +2337,9 @@ index 0000000..d9da2dc +static void challenge_once(uint8_t *base) { + if (s_cr_off || s_cr_attempted) return; + s_cr_attempted = 1; -+ // The registry ready byte (OFF_CR_READY + 0x18) is measured 0xc6 offline but 0xc1 in a live session, so bit 0x4 is -+ // not set there and has to be written (on the resolved object, below); the XVar above is turned on for the same -+ // reason, the callback wants rifts enabled on both. ++ // The XVar above is turned on because the callback wants rifts enabled. The other input, the registry ready byte ++ // (OFF_CR_READY + 0x18, measured 0xc6 offline but 0xc1 in a live session), is left alone: that byte is the game's ++ // online-service state, and the branch that tests it is bypassed statically instead (patch_nso.py cut 0x185fd0). + void *xvar = grab(base, OFF_CR_XVAR); + int set = xvar ? ((xvar_bool_set_fn)(base + OFF_XVAR_BOOL_SET))(xvar, 1, XVAR_DIRTY) : -1; + LOG("d3 pubfile: challenge xvar=%p set(1)=%d", xvar, set); @@ -2375,16 +2375,13 @@ index 0000000..d9da2dc + void *handle = grab(base, OFF_CR_READY); + void *resolved = handle ? ((resolve_ns_fn)(base + OFF_CR_RESOLVE))(handle, 1) : NULL; + unsigned flags = resolved ? *(uint8_t *)((uint8_t *)resolved + 0x18) & 0xffu : 0u; -+ // The early exit at 0x185fd0 (tbz w8,#2) tests this byte on the resolved object, so the write has to land on -+ // that same pointer; setting it on the registry handle (what cr_probe samples) would not be seen. -+ unsigned flags_after = flags; -+ if (resolved) { -+ ((uint8_t *)resolved)[0x18] |= 0x4; -+ flags_after = *(uint8_t *)((uint8_t *)resolved + 0x18) & 0xffu; -+ } ++ // The early exit at 0x185fd0 (tbz w8,#2) tests this byte on the resolved object, not on the registry handle ++ // that cr_probe samples. The rewriter nops that branch (patch_nso.py cut 0x185fd0) and the byte stays ++ // untouched: setting bit 0x4 here made the rest of the front end believe an online session exists, which broke ++ // the main-menu Continue action. + if (handle) -+ LOG("d3 pubfile: challenge gate handle=%p resolved=%p same=%d flags=%#x -> %#x", handle, resolved, -+ resolved == handle, flags, flags_after); ++ LOG("d3 pubfile: challenge gate handle=%p resolved=%p same=%d flags=%#x", handle, resolved, ++ resolved == handle, flags); + else + LOG("d3 pubfile: challenge gate handle=%p resolved=(skipped) same=%d flags=%#x", handle, 0, flags); + uint64_t now = ((now_ns_fn)(base + OFF_CLOCK_NOW))(); @@ -3798,10 +3795,10 @@ index e237a24..2fe8d62 100644 int front = m->patch_off < 0; if (z0 + zw != (front ? m->file_image_len : (uint64_t)m->patch_off) || (z0 & 0x3FFF) || (zw & 0x3FFF) || (z1 & 0x3FFF) || ((uintptr_t)x0 & 0x3FFF) || ((uintptr_t)w & 0x3FFF) || ((uintptr_t)x1 & 0x3FFF)) diff --git a/dm/tools/patch_nso.py b/dm/tools/patch_nso.py -index 837700c..911c355 100644 +index 837700c..98f861c 100644 --- a/dm/tools/patch_nso.py +++ b/dm/tools/patch_nso.py -@@ -46,6 +46,19 @@ else: +@@ -46,6 +46,28 @@ else: # Networking cuts (excluded scope: Battle.net / online play): taken from a community offline fix (LFS Mod Offline Fix for v2228224, which differs from the official 94012 main in only these 7 words). # Measured: the system service layer (nifm offline / DNS black hole / account service) cannot get around it: the game itself sends Battle.net requests directly and allows offline play according to the "last online" time. CUTS = { @@ -3817,11 +3814,20 @@ index 837700c..911c355 100644 + (0x1bd140, '159140b9', 'b5048052', 'd3hack dynamic_seasonal_05:season_created 的 ldr w21,[x8,#0x90] → movz w21,#37'), + (0x1bf5f0, 'ff0304d1', '00008052', 'd3hack dynamic_seasonal_08:ValidateHeroForPartyMember 的 sub sp,sp,#0x100 → movz w0,#0,返回 error_none'), + (0x1bf5f4, 'f76300f9', 'c0035fd6', 'd3hack dynamic_seasonal_09:紧随其后的 str x23,[sp,#0xc0] → ret,跳过函数体'), ++ # Cut, not a host write: the host calls 0x185f70 directly offline (host/hle_d3_pubfile.c challenge_once), and ++ # 0x185fd0 tests bit 0x4 of *(resolve_ns(*(0x114d998), 1) + 0x18), the game's online-service state, which the host ++ # must not modify (setting it made the rest of the front end believe a session exists and broke the main-menu ++ # Continue). Original word derived from the image rather than encoded by hand: struct.unpack_from(' host swaps w1 to the item\'s own type for ring/amulet/boots/gloves/belt (rift best >= 10); x8 stays 0, original insn runs ->0x3beb5c; svc8e', '仅宿主')) From 94b47c3344659498b32c0504d18f5bce11e5a533 Mon Sep 17 00:00:00 2001 From: leah <348866666+leahd3@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:24:05 +0000 Subject: [PATCH 13/13] Add a third display mode to the Mac launcher normal 1600x900, wide 1568x720, wider 1920x720. mac_app builds and independently verifies one patched image per wide size (rewrite-wide, rewrite-wider); loader.c validates the image against the word table of the mode it was asked for, so the pair cannot be swapped. Preference is LaunchDisplayMode with LaunchWide migrated (true -> wide). Verified: 58 unit tests, per-mode C guard accept/reject, rewrite/verify clean, make app builds both images and passes the i18n key-set check; headless runs present 1568x720 -> 2560x1176 and 1920x720 -> 2560x960 with no red lines. --- .gitignore | 3 + README.md | 7 +- README.zh-CN.md | 7 +- STATUS.md | 11 +- docs/LAUNCH_UI.md | 4 +- docs/METALFX.md | 6 +- docs/MOBILE_WIDESCREEN.md | 40 +++-- docs/UPSTREAM_CHANGES.md | 2 +- patches/nxnative.patch | 159 ++++++++++++------ tests/test_d3_graphics.c | 67 ++++++-- tests/test_mobile_graphics_profile.py | 40 +++-- tools/mac-i18n/en.lproj/Localizable.strings | 6 +- .../zh-Hans.lproj/Localizable.strings | 6 +- tools/mac_app.py | 23 ++- tools/mac_launcher.m | 49 ++++-- 15 files changed, 303 insertions(+), 127 deletions(-) diff --git a/.gitignore b/.gitignore index 2f91082..9c4e23b 100644 --- a/.gitignore +++ b/.gitignore @@ -69,6 +69,9 @@ obj/ # Upstream source is reconstructed from its pinned revision and patch. third_party/nxnative/ + +# Reference-only checkouts kept on disk but never published. +vendor/d3hack/ .impeccable/ *.cpk *.shd diff --git a/README.md b/README.md index 09f0a76..6c65a6a 100644 --- a/README.md +++ b/README.md @@ -12,18 +12,19 @@ Independent community research; not an official port and not affiliated with or ## Observed status -As of **2026-10-18**. Research preview, not complete-game compatibility. +As of **2026-10-27**. Research preview, not complete-game compatibility. | Area | Verified scope | |---|---| | macOS / Apple silicon | Native startup, town/menu/inventory interaction, controller input and isolated save/reload checks | | iPhone Air / A19 Pro / iOS 27.2 | User-confirmed town entry, working touch input, audible sound and corrected wide-screen output | | iPhone 15 Pro / A17 Pro / iOS 27.2 | Device-specific build, development-signed USB install, complete resource checks and app launch; gameplay/performance not yet verified | -| Graphics | 1,323 unique original stages compiled locally; 1,993 iPhoneOS libraries including fetch/layout variants; MetalFX Spatial and Normal/Wide launch options | +| Graphics | 1,323 unique original stages compiled locally; 1,993 iPhoneOS libraries including fetch/layout variants; MetalFX Spatial and Normal/Wide/Wider launch options | +| Offline seasons and challenge rifts | Season 37 calendar, season XVars and the weekly challenge-rift payload are injected from the host with no online state; the Challenge Rifts row appears in Mode Select. Entry is still locked until a Greater Rift is cleared, so rift entry is **not** verified | | Local Wi-Fi | Mac host → iPhone client joined the same party; user confirmed both characters visible. Long sessions, combat/drop/scene synchronization, four players and reverse hosting remain unverified | | Public Internet / Mesh | Design contract only; no released Mesh integration or Battle.net services | -The launcher offers Metal HUD, MetalFX Spatial, normal/wide view and local Wi-Fi options. The wide profile renders at 1920×720; mobile MetalFX targets approximately 2K while preserving aspect. macOS and iOS use separate shader builds. Frame rate varies with device and scene; this is not a guarantee of sustained 60 FPS. +The macOS launcher offers three display modes — Normal 16:9 (1600×900), Wide (1568×720) and Wider (1920×720) — plus Metal HUD, MetalFX Spatial and local Wi-Fi options. Both patched modes expand the horizontal view while keeping the vertical field of view; iOS keeps its single wide mode at 1920×720. Mobile MetalFX targets approximately 2K while preserving aspect. macOS and iOS use separate shader builds. Frame rate varies with device and scene; this is not a guarantee of sustained 60 FPS. Constant-update forwarding substantially improved the observed Mac scene performance, but the original lantern flicker reproduced when forwarding was enabled. Attachment-dependency guards retain the optimization; the original location still needs dynamic visual acceptance. Full chapters, sustained thermal behavior, every rendering path and extended multiplayer stability are pending. See [status](STATUS.md), [acceptance checklist](docs/COMPLETION_CHECKLIST.md), [rendering notes](docs/LANTERN_STABILITY.md) and [LAN scope](docs/LAN_MULTIPLAYER.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 8cd0bac..89aece3 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -12,18 +12,19 @@ ## 实测范围 -截至 **2026-10-18**,仍是研究预览版,不代表全流程兼容。 +截至 **2026-10-27**,仍是研究预览版,不代表全流程兼容。 | 平台 / 功能 | 已验证范围 | |---|---| | Apple silicon Mac | 原生启动、城镇/菜单/背包操作、实体手柄、隔离存档保存与重载 | | iPhone Air / A19 Pro / iOS 27.2 | 用户确认进入城镇、触摸正常、有声音、宽屏显示修正 | | iPhone 15 Pro / A17 Pro / iOS 27.2 | 按 A17 编译、开发签名 USB 安装、完整资源检查和启动;游玩与性能待确认 | -| 图形 | 本地提取 1323 个唯一阶段,iOS 含变体共 1993 个库;启动可选 HUD、MetalFX Spatial、正常/宽屏 | +| 图形 | 本地提取 1323 个唯一阶段,iOS 含变体共 1993 个库;启动可选 HUD、MetalFX Spatial、正常/宽屏/超宽屏 | +| 离线赛季与挑战秘境 | 主机注入第 37 赛季日历、赛季 XVar 与每周挑战秘境数据,不依赖联网;模式选择已出现挑战秘境一行,但需先通关一个大秘境才解锁,**进入秘境尚未验证** | | 本地 Wi-Fi | Mac 建房、iPhone 加入同一队伍,用户确认看到双方角色;长时间同步、战斗/掉落/换场景、四人及反向建房待验收 | | 公网 / Mesh | 仅有接入契约,尚未完成;不提供战网、商店及互联网好友服务 | -宽屏为 1920×720,保留纵向视野;手机 MetalFX 按画幅输出约 2K。帧率随设备和场景变化,不承诺全程 60 FPS。常量更新转发曾显著改善 Mac 实测帧率,也曾引发灯笼闪烁;附件依赖守卫保留优化,原位置动态画面仍需验收。详见[当前状态](STATUS.md)、[剩余验收](docs/COMPLETION_CHECKLIST.md)与[灯笼记录](docs/LANTERN_STABILITY.md)。 +macOS 启动器提供三档画面:正常 16:9(1600×900)、宽屏(1568×720)与超宽屏(1920×720),后两者扩大左右视野并保留纵向视野;iOS 仍只有 1920×720 一档宽屏。手机 MetalFX 按画幅输出约 2K。帧率随设备和场景变化,不承诺全程 60 FPS。常量更新转发曾显著改善 Mac 实测帧率,也曾引发灯笼闪烁;附件依赖守卫保留优化,原位置动态画面仍需验收。详见[当前状态](STATUS.md)、[剩余验收](docs/COMPLETION_CHECKLIST.md)与[灯笼记录](docs/LANTERN_STABILITY.md)。 ## 自行构建 diff --git a/STATUS.md b/STATUS.md index a36c7ad..2e3cbd7 100644 --- a/STATUS.md +++ b/STATUS.md @@ -1,3 +1,12 @@ +# Local development status — 2026-10-27 + +Offline season content: +- The offline lobby never issues the publisher fetch, so the host now calls the game's own callbacks with the documents it would have downloaded: Seasons and Blacklist (branches gated observe-only first, then seeded), the season XVars pair, and the weekly challenge-rift payload read from `work/rift_data`. A 90 s run reports season vector size 1, season 37, seasons/blacklist flags 1; the challenge call publishes `valid=1, number 346` while Continue loads the hero and commits the save. Derivation recorded in docs/UPSTREAM_CHANGES.md; the d3hack reference checkout is no longer distributed. +- The Challenge Rifts row now appears in Game Settings → Mode Select but stays locked until a Greater Rift is cleared, so **rift entry is not verified**. `Config.txt` is not injected because that callback dereferences `self`. +- Two earlier approaches were removed after measurement: writing bit `0x4` into the resolved service object made the front end believe an online session existed and stalled main-menu Continue; d3hack's spawn gate (site 10) made every hero hang on world entry. +- A third display mode (Wider 1920×720) and the raised wide profile ship with per-mode patched images that are verified against the requested mode's word table. MSAA logging shows 2.7.7 never calls `nvnTextureBuilderSetSamples`: every texture and the swapchain is single-sample. +- Synthetic state: 58 Python tests discovered, 52 executed and 6 opt-in (Bonjour/LAN) skipped, plus the native Metal/GameController suite from `make test`. `tools/audit_public.py --all-history` passes on the published tree. + # Local development status — 2026-10-18 Public source snapshot: @@ -31,7 +40,7 @@ Target: Diablo III Eternal Collection, base title 01001B300B9BE000, update 2.7.7 Latest integration (2026-10-17, local Apple Silicon): - Candidate: `work/macapp-complete/DR3 Mobile.app`, runtime `fcffb365d4d29c767abd2378a11ee1042c0e25682374e4c04fec1bd404131749`. Old baseline/candidate apps remain separate. Uniform forwarding and targeted attachment guard stay on. -- Final packaging also enables forwarding from startup in both Mac app and CLI; launcher source/binary hashes are in the app receipt. The app was repackaged and signature-verified without launching a game window. The 39 Python tests passed again; the tested native runtime and shader chain are unchanged. +- Final packaging also enables forwarding from startup in both Mac app and CLI; launcher source/binary hashes are in the app receipt. The app was repackaged and signature-verified without launching a game window. The Python tests passed again (39 at the time; 58 are discovered now); the tested native runtime and shader chain are unchanged. - Production CopyCommands and GPU synchronization are implemented and SDK 8.2 semantics checked. New integration fixture: 64/64; upstream GPU fixture: 64/64; GPU validation rerun passed. Normalized vertex input failures fixed with actual-format fetch shims, 9 prebuilt layouts, 544 hash-bound source records, 128 independently expected GPU register channels and three real PSO positive/negative controls. - Strict CPK decoding now verifies 51/51 archives, 1,386,014 sectors and stored-payload CRC. Original 1569 SHD bytes match. A fresh exact-runtime registry audit reports 314 implemented NVN entries / 16 no-ops / 206 unregistered, with 129 observed APIs and no observed no-op or unregistered calls in the integrated town run. Unobserved is not unused. - Integrated offscreen town: 110 seconds, 5912 frames, graceful exit 0, no CRASH/FATAL/red warning, original save unchanged. Last 30 seconds: 442 draws / 56 passes / one attachment boundary, GPU p50 3.959 ms, p95 5.035 ms. These are offscreen work times, not foreground FPS or the original blue-lantern visual acceptance. diff --git a/docs/LAUNCH_UI.md b/docs/LAUNCH_UI.md index 2bf3877..bc2dff8 100644 --- a/docs/LAUNCH_UI.md +++ b/docs/LAUNCH_UI.md @@ -20,9 +20,9 @@ Mac 是上述原生设置界面的 AppKit 适配,继续沿用左侧游戏身 - 使用真实 `NSWindow`、`NSBox`、`NSSegmentedControl`、原生 checkbox 与圆角开始按钮;窗口、分组表面和控件状态交由 AppKit 绘制。自建文字使用 `labelColor`/`secondaryLabelColor`,不把深色截图中的采样色写成固定色值。 - 标题使用系统字体 28 pt semibold,说明与状态使用系统字体 12 pt;分组标题与控件文字沿用 AppKit 默认排印。窗口初始内容区为 760×470 pt,最小内容区为 700×450 pt;左右边距 28 pt、上边距 28 pt、底部至少 24 pt,左栏宽 240 pt,栏间距 30 pt。左栏间距 16 pt,右侧分组间距 14 pt,分组内部间距 8 pt。最小尺寸和大字号下的实际布局尚未独立截图验收。 -- 新的偏好域默认选择正常 16:9,Metal HUD、MetalFX 超分与本地 Wi-Fi 联机默认开启。正常/宽屏和三个开关立即保存至 `NSUserDefaults`;重新打开启动器可重新选择。宽屏选项依赖包内独立的 `rewrite-wide` 映像,打包时检查其配置与独立验证结果;资源缺失时该分段不可选并回到正常模式。 +- 新的偏好域默认选择正常 16:9,Metal HUD、MetalFX 超分与本地 Wi-Fi 联机默认开启。画面模式分为 `Normal` / `Wide` / `Wider` 三段,保存为 `LaunchDisplayMode`(`"normal" | "wide" | "wider"`);旧 `LaunchWide` 布尔只在缺少新键时迁移(true → `wide`,false 或缺失 → `normal`)。两个 patched 分段分别依赖包内 `rewrite-wide` 与 `rewrite-wider` 映像;打包时各自检查配置与独立验证结果,目录缺失时该分段不可选,选择也会回退到正常模式。三个开关同样立即保存至 `NSUserDefaults`。 - 玩家选择后点击“开始游戏”(Return 快捷键)才启动游戏。启动器先设置本次画面、HUD、MetalFX 与 LAN 环境,再以 `execv` 执行新的 host 进程;重复开始受保护。源码为启动失败提供原生 `NSAlert` 并恢复开始按钮,但错误状态外观尚未截图验证。 -- 正常模式说明为 1280×720、原版 16:9 视野;宽屏说明为 1920×720、扩大左右视野。MetalFX 开关会切换“超分至 2K”或“直接适配窗口”的辅助文字。`third_party/nxnative/dm/host/front_mac.m` 按所选画面比例居中显示,在窗口尺寸或 backing scale 改变时重新计算画面区域,允许留边;MetalFX 的输出目标为正常 2560×1440/宽屏 2560×960。这是源码中的显示契约,完整窗口调整与性能验收另行记录。 +- 正常模式说明为 1600×900、原版 16:9 视野;宽屏说明为 1568×720;超宽屏说明为 1920×720,均扩大左右视野。MetalFX 开关会切换“超分至 2K”或“直接适配窗口”的辅助文字。`third_party/nxnative/dm/host/front_mac.m` 按所选画面比例居中显示,窗口默认尺寸由该比例推导,在窗口尺寸或 backing scale 改变时重新计算画面区域,允许留边;MetalFX 的输出目标为正常 2560×1440/宽屏 2560×1176/超宽屏 2560×960。这是源码中的显示契约,完整窗口调整与性能验收另行记录。 - 常规包使用本机原有 `work/run/save`,界面显示“存档:本机游戏进度”。私有 `tools/mac_app.py --test-session <目录>` 将既有独立存档副本路径写入 bundle 的 `DR3TestSessionRoot`,启动器显示“存档:联机测试副本”;测试包的该标记不代表常规包改用了副本。 当前有效截图是 `.impeccable/review/mac-launcher/desktop.png`(1520×1004),来自实际 AppKit 启动器的系统深色外观,可确认两栏、三个设置分组、宽屏选择、开启的图形/LAN 开关与测试存档标记均可读。早期 `initial-layout.png` 是已被替换的压缩布局,不作为当前界面依据。`.impeccable/review/mac-launcher/finish-review.json` 的 `ship` 只覆盖 Mac 启动器 UI;本次另有宽屏选择持久化及 MetalFX 关闭/开启辅助文字的运行检查。浅色外观、其他语言、大字号、辅助功能遍历和错误状态外观仍未验收。 diff --git a/docs/METALFX.md b/docs/METALFX.md index 27a0be0..f4d09a9 100644 --- a/docs/METALFX.md +++ b/docs/METALFX.md @@ -6,8 +6,8 @@ - 启动前设置 `DM_METALFX=spatial`;`off` 或未设置时继续常规呈现。 - `mtl_set_metalfx(int)` 可切换呈现路径,但不会改变游戏渲染尺寸或相机。 -- 游戏/前端负责实际的原生宽屏几何和渲染分辨率,例如 `DM_GAME_RES=1920x720`。后端不修改游戏 shader、c1、原始链 `87c50a868147`、相机投影或 NVN render target 尺寸。 -- 前端负责 `CAMetalLayer.drawableSize`。后端直接使用实际 drawable 尺寸,不硬编码 16:9 或 4K。2560×1176 是约 2K 宽屏输出的测试例,2048×940 也已验证;应根据实际屏幕比例计算尺寸。 +- 游戏/前端负责实际的原生宽屏几何和渲染分辨率。Mac 启动器由 `DM_MAC_DISPLAY_MODE=normal|wide|wider` 选择 1600×900 / 1568×720 / 1920×720;iOS 仍使用 `DM_IOS_GRAPHICS_MODE` 与 `DM_GAME_RES=1920x720` 的单档宽屏。后端不修改游戏 shader、c1、原始链 `87c50a868147`、相机投影或 NVN render target 尺寸。 +- 前端负责 `CAMetalLayer.drawableSize`。后端直接使用实际 drawable 尺寸,不硬编码 16:9 或 4K。macOS 的 MetalFX drawable 为 normal 2560×1440、wide 2560×1176、wider 2560×960;2048×940 的宽屏尺寸也已验证。应根据实际屏幕比例计算尺寸。 - macOS/iOS 目标必须链接 `MetalFX.framework`。当前 backend 使用 Metal 4 呈现队列,目标系统仍为 macOS/iOS 26。 **`content=1920x720` 的 MetalFX 日志只证明 upscaler 输入区域是 720 高;它本身不能证明游戏的全部渲染目标已经降到 720p。** 实际分辨率、相机宽屏和性能还需要游戏路径与设备日志共同验收。 @@ -35,7 +35,7 @@ work/test-metalfx-spatial 已在本机 M3 Max 的真实 MetalFX 上通过: -- 1568×720 到 2560×1176 与 2048×940 的尺寸检查。 +- 1568×720(Mac `wide`)到 2560×1176 与 2048×940 的尺寸检查。 - 三 slot 重复使用和全部输出尺寸变化。 - 非零 crop,排除 allocation 外围的洋红哨兵像素。 - sRGB raw view、RGBA→BGRA 顺序、感知色阶和上下两半不同内容,共 336 个独立颜色通道检查。 diff --git a/docs/MOBILE_WIDESCREEN.md b/docs/MOBILE_WIDESCREEN.md index 73fbc4f..527a05b 100644 --- a/docs/MOBILE_WIDESCREEN.md +++ b/docs/MOBILE_WIDESCREEN.md @@ -1,6 +1,14 @@ # D3 原生宽屏与 720p 渲染配置 -2026-10-18。实现是原始游戏的渲染尺寸、显示比例和相机投影配置,不是把 16:9 帧拉伸或裁切。当前固定 iPhone 宽屏配置为 **1920×720,aspect=8/3≈2.66667**;两种 performance mode 使用同一尺寸。相对 16:9,相同垂直视野下的水平可见跨度增加 **50%**。MetalFX 和最终 drawable 分辨率由显示后端单独控制。 +2026-10-18,2026-10-27 扩展为三档。实现是原始游戏的渲染尺寸、显示比例和相机投影配置,不是把 16:9 帧拉伸或裁切。macOS 启动器提供三档,iOS 仍只打包 **1920×720** 一档: + +| 模式 | 打包映像 | 客体渲染尺寸 | 窗口宽高比 | MetalFX drawable | +| --- | --- | --- | --- | --- | +| `normal` | 未打补丁的 `rewrite` | 1600×900 | 16:9 | 2560×1440 | +| `wide` | `rewrite-wide`(1568×720 补丁) | 1568×720 | 1568:720 | 2560×1176 | +| `wider` | `rewrite-wider`(1920×720 补丁) | 1920×720 | 8:3 | 2560×960 | + +两种 patched performance mode 各自内部使用同一尺寸。相对 16:9,相同垂直视野下 `wide` 的水平可见跨度增加 **22.5%**,`wider` 增加 **50%**。MetalFX 和最终 drawable 分辨率由显示后端单独控制。 首轮实机宽屏出现嵌套矩形、清屏底色和右/下黑区,**未通过运行验收**。随后独立 Mac 宽屏在关闭 MetalFX 时也复现,说明故障先于最终上屏。已定位并修复漏掉的 handheld 纹理尺寸查询转换,见下节;修复版本仍需实际画面回归,不能把先前投影数学通过当作整条渲染链通过。本轮没有操作正在运行的设备、存档或窗口。 @@ -50,41 +58,47 @@ ## 构建与加载接口 -`tools/mobile_graphics_profile.py`: +`tools/mobile_graphics_profile.py` 的 `DEFAULT_WIDTH` 保持 **1920**(iOS 打包与 `verify` 的默认值);Mac 打包显式传入宽度: ```python from mobile_graphics_profile import launch_directory, verify -wide_dir = launch_directory(work, unique_destination, 1920, 720) -report = verify(original_verified_main_bytes, width=1920, height=720) +wide_dir = launch_directory(work, unique_destination, 1568, 720) +wider_dir = launch_directory(work, unique_destination, 1920, 720) +report = verify(verified_rewrite_main_bytes, width=1568, height=720) ``` +Mac 的 `tools/mac_app.py` 对两个尺寸分别执行 `launch_directory`,各自 `verify` 原始已验证 rewrite bytes,并交叉核对 `graphics.json` 的 `configured_sha256` 与目录中实际 `main.patched.bin` 的哈希,然后复制到 `Contents/Resources/rewrite-wide` 与 `rewrite-wider`。 + `launch_directory` 校验 main/SDK 原始 NSO 的完整 Build ID 和 SHA-256、精确配置文件哈希、成功 verification 回执,以及**完整** rewrite 工件集合及每项 SHA-256。先校验所有指令和投影/UI 证据,再创建新目录;拒绝覆盖。输出独立 `main.patched.bin`、其余原 rewrite 工件的链接和 `graphics.json`。原始 rewrite、fixups、客体身份保持不变。 -纯配置器的保守数学验证范围为 height=720、width 1280..1920 且按 8 对齐;面积低于原 docked 1600×900。但 iOS 当前签名宽屏选项固定 **1920×720**,运行时 guard 拒绝其他配置。像素面积较低不证明所有更宽纹理步长/分配都安全。 +纯配置器的保守数学验证范围为 height=720、width 1280..1920 且按 8 对齐;面积低于原 docked 1600×900。Mac 只打包 1568 与 1920 两档,iOS 签名宽屏固定 **1920×720**,运行时按档位词表拒绝其他配置。像素面积较低不证明所有更宽纹理步长/分配都安全。 -iOS 打包器把宽屏复制作为 `mainwide` 的签名节别名,仍使用 main 的 fixups。`loader.c` 只在 D3 iOS 构建中读取启动前的 `DM_IOS_GRAPHICS_MODE`: +iOS 打包器把宽屏复制作为 `mainwide` 的签名节别名,仍使用 main 的 fixups,并继续只打包 **1920×720**。`loader.c` 在 D3 iOS 构建中读取启动前的 `DM_IOS_GRAPHICS_MODE`: - `normal` / 未设置:原始 `main` 签名节,行为不变。 -- `wide`:只有原 main Build ID 前 16 字节与锁定值完全匹配才选择 `__dmmainwidex0` / `__DMmainwideW` / `__dmmainwidex1`。 -- 未知模式、未知 main build、缺失签名节、宽屏 text 的尺寸/aspect/投影关键字不匹配:显式失败。 +- `wide`:只有原 main Build ID 前 16 字节与锁定值完全匹配才选择 `__dmmainwidex0` / `__DMmainwideW` / `__dmmainwidex1`,并按 **1920×720** 词表校验(iOS 的单档 `wide` 映射到 `wider` 词表)。 +- 未知模式、未知 main build、缺失签名节、签名 text 的尺寸/aspect/投影关键字不匹配:显式失败。 + +Mac host 不切换签名节,而是直接读启动器选定的映像目录。`loader.c` 在映射 `main.patched.bin` 前读取 `DM_MAC_DISPLAY_MODE`,按 `normal` / `wide` / `wider` 选择词表:1568×720 映像带 1920×720 词(或反向)会立即 die,未知模式同样失败;未设置该变量时不做补丁词表校验。 -选择改变的是节名称;`m.name`、模块布局、重定位和游戏身份仍为 main。正常启动后不修改可执行代码。真实完整 NSO 身份由打包阶段的完整哈希校验保证;运行时另核对 fixups 中的原 Build ID 与宽屏签名内容。 +选择改变的是节名称或目录;`m.name`、模块布局、重定位和游戏身份仍为 main。正常启动后不修改可执行代码。真实完整 NSO 身份由打包阶段的完整哈希校验保证;运行时另核对 fixups 中的原 Build ID 与所选尺寸的签名内容。 -1920×720 的渲染面积 1,382,400 px 仍低于原 docked 1600×900 的 1,440,000 px;MetalFX 以 1.333× 倍放大到 2560×960,相对正常模式的 2560×1440 输出,在窗口/屏幕内按 8:3 居中并上下留边。8:3 比 iPhone Air 的 2736:1260 更宽,显示后端只居中不拉伸或裁切。它不会把原 16:9 的水平视野冒充超宽视野。横竖屏/设备几何应在 guest 预加载前确定;运行中切换需要另行生命周期方案。 +1568×720 的渲染面积 1,128,960 px 与 1920×720 的 1,382,400 px 都低于原 docked 1600×900 的 1,440,000 px。MetalFX 按前端给出的 drawable 尺寸输出:`wide` 为 2560×1176(约 1.633×),`wider` 为 2560×960(1.333×),相对正常模式的 2560×1440 输出在窗口/屏幕内按各自比例居中并上下留边。8:3 比 iPhone Air 的 2736:1260 更宽,显示后端只居中不拉伸或裁切。它不会把原 16:9 的水平视野冒充超宽视野。横竖屏/设备几何应在 guest 预加载前确定;运行中切换需要另行生命周期方案。 ## 已完成的独立验证 ```sh .venv/bin/python -m unittest discover -s tests -p test_mobile_graphics_profile.py -v +.venv/bin/python tools/mobile_graphics_profile.py --width 1568 .venv/bin/python tools/mobile_graphics_profile.py --width 1920 ``` - LLVM 独立解码确认目标寄存器、尺寸、位移和约束谓词;Unicorn 执行真实 initializer、display query、UI 尺寸与投影切片。 -- 对 1280、1600、1920 各执行 64 组透视和 64 组正交 normal/wide 对照,确认水平系数降低且垂直完全不变。 +- 对 1280、1568、1600、1920 各执行 64 组透视和 64 组正交 normal/wide 对照,确认水平系数降低且垂直完全不变。 - 新增完整纹理查询函数的真实 PC/GOT 执行,每个尺寸配置 28 项:原版 1600×900→1280×720、首版错误的全/半/四分之一尺寸、修复后的双模式,以及无关纹理和宽高不匹配的负对照。它补充了首版验证漏掉的中间 RT 依赖;不代替运行画面回归。 - 修改范围恢复比对、原输入不变、重复配置/越界尺寸/损坏指令/损坏投影证据均拒绝。 - 打包负对照包括编辑点外的 hash 损坏、缺失工件、未知原 NSO,失败时不创建目标目录。 -- C fixture 使用与 iOS loader **同一个** `dm_d3_graphics.h`,验证 normal/SDK 身份、未知 build/模式拒绝、真实配置映像关键字与破坏变异;另已通过 ASan/UBSan。 +- C fixture 使用与 loader **同一个** `dm_d3_graphics.h`,分别以真实 1568×720 与 1920×720 配置映像验证 normal/SDK 身份、每档词表只接受本档、拒绝另一档、拒绝只改一半宽度的混合映像,以及未知 build/模式与破坏变异;另已通过 ASan/UBSan。 - `loader.c` 通过 iPhoneOS SDK 的独立 syntax-only 编译;不代表签名安装或游戏画面验收。 -当前原始 rewrite SHA-256 `05e9888c3a766d966ceb4c6e3c67de200027673a9310f840b6a0f6e850458e4d`,对应修复后的 1920×720 配置 SHA-256 `df6148a9175765db0c5864d0b73aafef03258e247af00ac74849b765743dbda7`。首版失败的配置 SHA 为 `1d7c9b839a87610c38b76cda3bf54732eebf830aff97f4e6acec6c4ab5ca81ba`,仅保留作失败证据。若通用 rewrite 更新,应重新生成并验证,不绕过 guard。 +当前原始 rewrite SHA-256 `248e4b0b98bb6cd57ddf4f714dc9ffcd950a45593c9762dfaf7070f5941d11ba`,对应 1568×720 配置 SHA-256 `16453e873a8c86fef8048690c4584c8328fa293ff6664e1d7031d5d1d52181a5`、1920×720 配置 SHA-256 `4344e89c36aeb39e201544f15b70adea7a677e5987491a2a9db4ee8aab5d6780`。首版失败的配置 SHA 为 `1d7c9b839a87610c38b76cda3bf54732eebf830aff97f4e6acec6c4ab5ca81ba`,仅保留作失败证据。若通用 rewrite 更新,应重新生成并验证,不绕过 guard。 diff --git a/docs/UPSTREAM_CHANGES.md b/docs/UPSTREAM_CHANGES.md index 3d72498..7ec8bcb 100644 --- a/docs/UPSTREAM_CHANGES.md +++ b/docs/UPSTREAM_CHANGES.md @@ -8,7 +8,7 @@ Base: seedds/nxnative `9579030e5b1f0443c12b7376559560915b6d4c4b` (MIT, includes - `patch_nso.py`: record the four in-place CTR_EL0 adaptations as explicit cuts, including original and new bytes. These set the host cache-line policy (DminLine=4); they are intentional adaptations, not claimed register-value equivalence. - `hle_account.c`: SDK 8 `OpenPreselectedUser(UserHandle*)` returns Result, unlike `TryOpenPreselectedUser`'s bool. Return the existing local user's complete 24-byte handle. The SDK public implementation requires a platform-populated UID and otherwise aborts; D3 calls it at `main+0x4c51cc`. A synthetic C test checks output canaries and GetUserId roundtrip. - `hle_misc.c`: adapt SDK 8 `CheckFreeCommunicationPermission(bool)` to the host's existing offline policy, returning false. Its SDK implementation tries to connect to `sm:` for the missing pctl service (`sdk+0x33a620`; observed guest backtrace). -- `hle_d3_pubfile.c`: offline publisher documents. The lobby never issues its own fetch offline, so the host hands the game's own callbacks the documents it would have downloaded: Seasons and Blacklist (season 37 calendar, `0x65270`/`0x657f0`), then the weekly challenge-rift protobufs (`0x185f70`, payloads read from `work/rift_data`, GPL sample weeklies in `vendor/d3hack`). Measured: the season calendar, season XVars and the challenge `valid` flag all land. The challenge mode row is visible in Game Settings → Mode Select but stays locked until a Greater Rift is cleared, so rift entry is unverified. +- `hle_d3_pubfile.c`: offline publisher documents. The lobby never issues its own fetch offline, so the host hands the game's own callbacks the documents it would have downloaded: Seasons and Blacklist (season 37 calendar, `0x65270`/`0x657f0`), then the weekly challenge-rift protobufs (`0x185f70`, payloads read from `work/rift_data`; the GPL sample weeklies come from the pinned d3hack revision in `third_party/README.md`, which this repository does not distribute). Measured: the season calendar, season XVars and the challenge `valid` flag all land. The challenge mode row is visible in Game Settings → Mode Select but stays locked until a Greater Rift is cleared, so rift entry is unverified. The D3 profile uses exact full NSO Build IDs and SHA-256 in `config/diablo3-2.7.7.json`. The Mac address-space profile was increased after observing nninitStartup's 768 MiB allocation fail against the initial 256 MiB alias candidate. This is a virtual reservation policy, not an iPhone memory validation. diff --git a/patches/nxnative.patch b/patches/nxnative.patch index 6f545bb..3eabb39 100644 --- a/patches/nxnative.patch +++ b/patches/nxnative.patch @@ -1682,39 +1682,75 @@ index 31b4420..6c2626e 100644 + env -u SOURCE_DATE_EPOCH clang $(CFLAGS) -I../gfx/nvn/include -I$(dir $(GAME_H)) -I$(GAME_DIR) -I$(VPX) -I../third_party/stb_vorbis -fobjc-arc -o $@ $(SRC) $(GFX) $(VPX_LIB) -framework Cocoa -framework GameController -framework CoreHaptics -framework QuartzCore -framework Metal -framework MetalFX -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers diff --git a/dm/host/dm_d3_graphics.h b/dm/host/dm_d3_graphics.h new file mode 100644 -index 0000000..fe7203b +index 0000000..e201e21 --- /dev/null +++ b/dm/host/dm_d3_graphics.h -@@ -0,0 +1,35 @@ -+// D3 exact-build signed-image selection. No executable bytes are written. +@@ -0,0 +1,71 @@ ++// D3 exact-build signed-image selection and per-size word guards. No executable bytes are written. +#pragma once +#include +#include +#include ++ +#define DM_D3_MAIN_BUILD_ID "2607a74f5df7754cc0357b5df7e49693" ++// Mac exposes both patched sizes; iOS keeps its single 1920x720 image and calls it "wide". ++#define DM_D3_WIDE_WIDTH 1568 ++#define DM_D3_WIDER_WIDTH 1920 ++ +static inline const char *dm_d3_graphics_image(const char *mode,const char *module,const char *build_id) { + if(!module)return NULL; + if(strcmp(module,"main"))return module; + if(!mode||!strcmp(mode,"normal"))return module; -+ if(strcmp(mode,"wide")||!build_id||strcmp(build_id,DM_D3_MAIN_BUILD_ID))return NULL; ++ if((strcmp(mode,"wide")&&strcmp(mode,"wider"))||!build_id||strcmp(build_id,DM_D3_MAIN_BUILD_ID))return NULL; + return "mainwide"; +} -+static inline int dm_d3_wide_text_valid(const uint8_t *text,size_t length) { -+ // Fixed packaged profile: 1920x720 in both modes, aspect 8/3, authored -+ // 16:9 constraint predicate disabled. This is not a generic image patcher. -+ static const struct { size_t offset;uint32_t word; } expected[]={ -+ // Words emitted by sites(1920,720) over the verified rewrite, not hand-encoded. -+ {0xe7858,0xd280f008},{0xe785c,0xd280f009}, -+ {0xe7860,0xf2c05a08},{0xe7864,0xf2c05a09}, -+ {0xe7868,0x5295556a},{0xe786c,0x72a8054a}, -+ {0xe7870,0xb90012ca},{0xe7874,0xa90026c8}, -+ {0xebb48,0x1e2e1001}, -+ {0x29b480,0x52800000},{0x29b484,0xd65f03c0}, -+ {0x29b7e8,0x1e2a1802},{0x29b854,0x1e211881}, -+ {0x29b914,0xbd000000},{0x29b918,0x1e211840},{0x29b91c,0xbd001400}, -+ }; ++ ++static inline int dm_d3_graphics_mode_width(const char *mode) { ++ if(!mode||!strcmp(mode,"normal"))return 0; ++ if(!strcmp(mode,"wide"))return DM_D3_WIDE_WIDTH; ++ if(!strcmp(mode,"wider"))return DM_D3_WIDER_WIDTH; ++ return -1; ++} ++ ++static inline const char *dm_d3_graphics_ios_mode(const char *mode) { ++ // iOS packages only the 1920x720 patched image, so its launch menu's "wide" is the wider table. ++ return mode&&!strcmp(mode,"wide")?"wider":mode; ++} ++ ++struct dm_d3_graphics_word { size_t offset;uint32_t word; }; ++ ++static const struct dm_d3_graphics_word dm_d3_wide_words[]={ ++ // Words emitted by sites(1568,720) over the verified rewrite, not hand-encoded. ++ {0xe7858,0xd280c408},{0xe785c,0xd280c409}, ++ {0xe7860,0xf2c05a08},{0xe7864,0xf2c05a09}, ++ {0xe7868,0x528c16ca},{0xe786c,0x72a8016a}, ++ {0xe7870,0xb90012ca},{0xe7874,0xa90026c8}, ++ {0xebb48,0x1e2e1001}, ++ {0x29b480,0x52800000},{0x29b484,0xd65f03c0}, ++ {0x29b7e8,0x1e2a1802},{0x29b854,0x1e211881}, ++ {0x29b914,0xbd000000},{0x29b918,0x1e211840},{0x29b91c,0xbd001400}, ++}; ++static const struct dm_d3_graphics_word dm_d3_wider_words[]={ ++ // Words emitted by sites(1920,720) over the verified rewrite, not hand-encoded. ++ {0xe7858,0xd280f008},{0xe785c,0xd280f009}, ++ {0xe7860,0xf2c05a08},{0xe7864,0xf2c05a09}, ++ {0xe7868,0x5295556a},{0xe786c,0x72a8054a}, ++ {0xe7870,0xb90012ca},{0xe7874,0xa90026c8}, ++ {0xebb48,0x1e2e1001}, ++ {0x29b480,0x52800000},{0x29b484,0xd65f03c0}, ++ {0x29b7e8,0x1e2a1802},{0x29b854,0x1e211881}, ++ {0x29b914,0xbd000000},{0x29b918,0x1e211840},{0x29b91c,0xbd001400}, ++}; ++ ++static inline int dm_d3_graphics_text_valid(const char *mode,const uint8_t *text,size_t length) { ++ int width=dm_d3_graphics_mode_width(mode); ++ if(width<0)return 0; ++ if(width==0)return 1; // original image: there are no patched words to check + if(!text)return 0; -+ for(size_t i=0;ilength||length-expected[i].offset<4)return 0; + uint32_t word;memcpy(&word,text+expected[i].offset,4); + if(word!=expected[i].word)return 0; @@ -1743,7 +1779,7 @@ index 933c85b..6dfad7a 100644 +void dm_pad_clear(void); +void dm_input_clear(void); diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m -index c7559ca..d71b581 100644 +index c7559ca..177f23e 100644 --- a/dm/host/front_mac.m +++ b/dm/host/front_mac.m @@ -3,7 +3,9 @@ @@ -1756,7 +1792,7 @@ index c7559ca..d71b581 100644 #include "dm.h" #include "dm_input.h" #include "dm_uiscreen.h" -@@ -13,14 +15,77 @@ __attribute__((constructor)) static void ui_shift_reg(void) { mtl_set_ui_rect_fn +@@ -13,14 +15,83 @@ __attribute__((constructor)) static void ui_shift_reg(void) { mtl_set_ui_rect_fn #include "front.h" #include "hle.h" #include @@ -1804,16 +1840,21 @@ index c7559ca..d71b581 100644 static uint64_t g_btn; static int g_w, g_a, g_s, g_d; -+static int configured_display(void) { ++typedef struct { int patched;double aspect;double drawable_height;uint64_t game_width; } display_mode; ++static display_mode configured_mode(void) { + const char *mode=getenv("DM_MAC_DISPLAY_MODE"); -+ return mode&&(!strcmp(mode,"normal")||!strcmp(mode,"wide")); ++ if(mode&&!strcmp(mode,"wide"))return (display_mode){1,1568.0/720.0,1176,1568}; ++ if(mode&&!strcmp(mode,"wider"))return (display_mode){1,1920.0/720.0,960,1920}; ++ return (display_mode){0,16.0/9.0,1440,1600}; +} -+static int configured_wide(void) { -+ const char *mode=getenv("DM_MAC_DISPLAY_MODE");return mode&&!strcmp(mode,"wide"); ++static int configured_display(void) { ++ const char *mode=getenv("DM_MAC_DISPLAY_MODE"); ++ return mode&&(!strcmp(mode,"normal")||!strcmp(mode,"wide")||!strcmp(mode,"wider")); +} +static void update_game_layer(NSView *view,NSWindow *window) { + if(!configured_display())return; -+ double aspect=configured_wide()?1920.0/720.0:16.0/9.0; ++ display_mode mode=configured_mode(); ++ double aspect=mode.aspect; + CGRect bounds=view.bounds,frame=bounds; + if(bounds.size.height<=0||bounds.size.width<=0)return; + if(bounds.size.width/bounds.size.height>aspect)frame.size.width=bounds.size.height*aspect; @@ -1822,7 +1863,7 @@ index c7559ca..d71b581 100644 + [CATransaction begin];[CATransaction setDisableActions:YES];g_layer.frame=frame; + g_layer.contentsScale=window.backingScaleFactor; + const char *fx=getenv("DM_METALFX"); -+ g_layer.drawableSize=fx&&!strcmp(fx,"spatial")?CGSizeMake(2560,configured_wide()?960:1440): ++ g_layer.drawableSize=fx&&!strcmp(fx,"spatial")?CGSizeMake(2560,mode.drawable_height): + CGSizeMake(round(frame.size.width*g_layer.contentsScale),round(frame.size.height*g_layer.contentsScale)); + [CATransaction commit]; +} @@ -1830,16 +1871,18 @@ index c7559ca..d71b581 100644 void *front_metal_layer(void) { return (__bridge void *)g_layer; } // The original game's 16:9 constants, behavior unchanged; DM_GAME_RES=x (docked mode; handheld scaled by 720/900) is only for side-by-side comparison with iOS widescreen uint64_t front_game_res(int docked) { -+ if(configured_wide())return 720ull<<32|1920; ++ display_mode mode=configured_mode(); ++ if(mode.patched)return 720ull<<32|mode.game_width; unsigned w, h; const char *e = getenv("DM_GAME_RES"); if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4; return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280; -@@ -60,23 +125,34 @@ void front_run(void (*guest)(void)) { +@@ -60,23 +131,35 @@ void front_run(void (*guest)(void)) { @autoreleasepool { [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - NSRect r = NSMakeRect(0, 0, 1280, 720); -+ NSRect r = NSMakeRect(0, 0, 1280, configured_wide()?480:720); ++ display_mode mode=configured_mode(); ++ NSRect r = NSMakeRect(0, 0, 1280, round(1280/mode.aspect)); NSWindow *win = [[NSWindow alloc] initWithContentRect:r styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; @@ -1856,7 +1899,7 @@ index c7559ca..d71b581 100644 - v.layer = g_layer; + if(configured_display()) { + v.layer=[CALayer layer];v.layer.backgroundColor=NSColor.blackColor.CGColor;[v.layer addSublayer:g_layer]; -+ win.contentAspectRatio=NSMakeSize(configured_wide()?1920:1280,720);win.contentMinSize=NSMakeSize(640,configured_wide()?240:360); ++ win.contentAspectRatio=NSMakeSize(mode.patched?(CGFloat)mode.game_width:1280,720);win.contentMinSize=NSMakeSize(640,round(640/mode.aspect)); + v.postsFrameChangedNotifications=YES;update_game_layer(v,win); + [NSNotificationCenter.defaultCenter addObserverForName:NSViewFrameDidChangeNotification object:v queue:nil + usingBlock:^(NSNotification *n){(void)n;update_game_layer(v,win);}]; @@ -1872,7 +1915,7 @@ index c7559ca..d71b581 100644 if (!e.isARepeat) on_key(e, e.type == NSEventTypeKeyDown); return nil; // Swallow it to avoid the system beep }]; -@@ -93,14 +169,15 @@ void front_run(void (*guest)(void)) { +@@ -93,14 +176,15 @@ void front_run(void (*guest)(void)) { usingBlock:^(NSNotification *n) { (void)n; exit(0); }]; // Lifecycle (hle.h / dm.h): focus lost → 2, focus regained → 1; minimized → 3 + audio paused + GPU suspended, restored → resume (followed by focus regained → 1) NSNotificationCenter *nc = NSNotificationCenter.defaultCenter; @@ -3736,10 +3779,20 @@ index 0000000..00d42c8 +void dm_lan_freeaddrinfo(void *); +void *dm_lan_gethostbyname(const char *); diff --git a/dm/host/loader.c b/dm/host/loader.c -index e237a24..2fe8d62 100644 +index e237a24..9994ab1 100644 --- a/dm/host/loader.c +++ b/dm/host/loader.c -@@ -17,6 +17,7 @@ pthread_key_t g_keyres[2], g_keyaspect, g_keyaspectui; // g_keyaspect: aspect +@@ -9,6 +9,9 @@ + #include + #include + #include "hle.h" ++#if DM_GAME_PROGRAM_ID == 0x01001B300B9BE000ull ++#include "dm_d3_graphics.h" ++#endif + + module_t g_mod[MAX_MOD]; + int g_nmod; +@@ -17,6 +20,7 @@ pthread_key_t g_keyres[2], g_keyaspect, g_keyaspectui; // g_keyaspect: aspect enum { KEY_K18, KEY_KTLS, KEY_KTLR, KEY_KGATE, KEY_KRES0, KEY_KRES1, KEY_KASPECT, KEY_KASPECTUI, KEY_N }; uint64_t resolve_import(module_t *m, const char *name); @@ -3747,7 +3800,7 @@ index e237a24..2fe8d62 100644 void gate_register(uint64_t ret_addr, const char *kind, int arg, uint64_t orig); static pthread_key_t key_value(unsigned i) { -@@ -246,7 +247,11 @@ static void relocate(module_t *m) { +@@ -246,7 +250,11 @@ static void relocate(module_t *m) { if (!v) v = self; if (v != self && nint++ < 8) LOG("%s: %s 绑到先装模块的定义(%s) | bound to an earlier module's definition", m->name, m->strtab + s->st_name, module_of((void *)v) ? module_of((void *)v)->name : "?"); } @@ -3760,17 +3813,7 @@ index e237a24..2fe8d62 100644 if (type == R_AARCH64_JUMP_SLOT) { *where = v; cnt[2]++; } else { *where = v + r->r_addend; cnt[1]++; } // ABS64 / GLOB_DAT } -@@ -307,6 +312,9 @@ void loader_hash_log(void) { - // and they are vm_remap'ed back at their original relative positions: code pages with copy=FALSE (sharing the same signed pages with __TEXT, r-x), W with copy=TRUE (copy-on-write, paged only when used). - // The run-time layout is byte-identical to the original image. Remapping signed pages to a new address and then executing them on iOS is exactly what libffi's trampoline table (FFI_EXEC_TRAMPOLINE_TABLE) does - #include -+#if DM_GAME_PROGRAM_ID == 0x01001B300B9BE000ull -+#include "dm_d3_graphics.h" -+#endif - static void remap_at(module_t *m, vm_address_t to, const void *from, unsigned long size, boolean_t copy, vm_prot_t need) { - vm_address_t a = to; vm_prot_t cur = 0, max = 0; - kern_return_t kr = vm_remap(mach_task_self(), &a, size, 0, VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, mach_task_self(), (vm_address_t)from, copy, &cur, &max, VM_INHERIT_NONE); -@@ -333,10 +341,22 @@ static const struct mach_header_64 *image_mh(void) { +@@ -333,10 +341,26 @@ static const struct mach_header_64 *image_mh(void) { #endif static void map_image(module_t *m, const char *dir) { (void)dir; @@ -3789,11 +3832,33 @@ index e237a24..2fe8d62 100644 const uint8_t *x0 = getsectiondata(IMAGE_MH, "__TEXT", sx0, &z0), *w = getsectiondata(IMAGE_MH, dm, "__img", &zw), *x1 = getsectiondata(IMAGE_MH, "__TEXT", sx1, &z1); if (!x0 || !w || !x1) die("内嵌节 %s / %s / %s 缺失", sx0, dm, sx1); +#if DM_GAME_PROGRAM_ID == 0x01001B300B9BE000ull -+ if(!strcmp(section_name,"mainwide")&&!dm_d3_wide_text_valid(x0,z0))die("D3 signed wide image words/geometry mismatch; rebuild the verified 1920x720 profile"); ++ if(!strcmp(m->name,"main")) { ++ const char *word_mode=dm_d3_graphics_ios_mode(mode); ++ if(!dm_d3_graphics_text_valid(word_mode,x0,z0)) ++ die("D3 signed image words/geometry mismatch for mode %s: iOS embeds the %dx720 patched image; rebuild the verified profile",mode?:"normal",dm_d3_graphics_mode_width(word_mode)); ++ } +#endif // Patch area before the base (patch_off < 0): W ends at the end of data (FILE_IMAGE_LEN); bss and the key page are zero pages from vm_allocate and are not in the executable int front = m->patch_off < 0; if (z0 + zw != (front ? m->file_image_len : (uint64_t)m->patch_off) || (z0 & 0x3FFF) || (zw & 0x3FFF) || (z1 & 0x3FFF) || ((uintptr_t)x0 & 0x3FFF) || ((uintptr_t)w & 0x3FFF) || ((uintptr_t)x1 & 0x3FFF)) +@@ -367,6 +391,17 @@ static uint8_t *slurp(const char *path, size_t *n) { + static void map_image(module_t *m, const char *dir) { + char path[1024]; snprintf(path, sizeof path, "%s/%s.patched.bin", dir, m->name); + size_t sz; uint8_t *raw = slurp(path, &sz); ++#if DM_GAME_PROGRAM_ID == 0x01001B300B9BE000ull ++ // The Mac launcher names the directory and sets the mode before exec; the words must match that ++ // mode, so a 1568x720 image loaded as wider (or the reverse) dies before any byte is mapped. ++ const char *mode=getenv("DM_MAC_DISPLAY_MODE"); ++ int width=dm_d3_graphics_mode_width(mode); ++ if(!strcmp(m->name,"main")) { ++ if(width<0)die("D3 patched image %s: unknown DM_MAC_DISPLAY_MODE %s (expected normal, wide or wider)",path,mode); ++ if(width>0&&!dm_d3_graphics_text_valid(mode,raw,sz)) ++ die("D3 patched image %s does not match display mode %s: expected the %dx720 word table; rebuild the verified profile",path,mode,width); ++ } ++#endif + if (m->patch_off < 0) { + // Patch area before the base: file = the first part of the image (text + ro + data) + patch area; bss and the key page are anonymous zero pages. The gap from the patch area's end to the base is left inaccessible (PROT_NONE) + uint64_t pre = (uint64_t)-m->patch_off, fl = m->file_image_len; diff --git a/dm/tools/patch_nso.py b/dm/tools/patch_nso.py index 837700c..98f861c 100644 --- a/dm/tools/patch_nso.py diff --git a/tests/test_d3_graphics.c b/tests/test_d3_graphics.c index fd317dc..055c3e0 100644 --- a/tests/test_d3_graphics.c +++ b/tests/test_d3_graphics.c @@ -2,30 +2,63 @@ #include #include #include + +// Offsets guarded by both word tables; each one must be load-bearing. +static const size_t guarded[]={0xe7858,0xe785c,0xe7860,0xe7864,0xe7868,0xe786c, + 0xe7870,0xe7874,0xebb48,0x29b480,0x29b484,0x29b7e8,0x29b854,0x29b914, + 0x29b918,0x29b91c}; + +static uint8_t *load(const char *path,size_t *n) { + FILE *f=fopen(path,"rb");assert(f);assert(!fseek(f,0,SEEK_END));long size=ftell(f);assert(size>0);rewind(f); + uint8_t *text=malloc((size_t)size);assert(text);assert(fread(text,1,(size_t)size,f)==(size_t)size);fclose(f); + *n=(size_t)size;return text; +} + +static void check_image(const char *path,const char *mode,const char *other) { + size_t n;uint8_t *text=load(path,&n); + assert(dm_d3_graphics_text_valid(mode,text,n)); + // The other patched size's words must be rejected, not merely tolerated. + assert(!dm_d3_graphics_text_valid(other,text,n)); + for(unsigned i=0;i1) { - FILE *f=fopen(argv[1],"rb");assert(f);assert(!fseek(f,0,SEEK_END));long n=ftell(f);assert(n>0);rewind(f); - uint8_t *text=malloc((size_t)n);assert(text);assert(fread(text,1,(size_t)n,f)==(size_t)n);fclose(f); - assert(dm_d3_wide_text_valid(text,(size_t)n)); - const size_t offsets[]={0xe7858,0xe785c,0xe7860,0xe7864,0xe7868,0xe786c,0xebb48,0x29b480,0x29b484,0x29b7e8,0x29b914}; - for(unsigned i=0;i *display_modes(void) { return @[@"normal",@"wide",@"wider"]; } +static NSString *display_folder(NSString *mode) { + return [mode isEqualToString:@"normal"]?@"rewrite":[@"rewrite-" stringByAppendingString:mode]; +} +static BOOL display_available(NSString *mode) { + if([mode isEqualToString:@"normal"])return YES; + NSString *folder=[g_resources stringByAppendingPathComponent:display_folder(mode)]; + return [NSFileManager.defaultManager fileExistsAtPath:[folder stringByAppendingPathComponent:@"main.patched.bin"]]; +} +static NSString *display_note(NSString *mode) { + if([mode isEqualToString:@"wide"])return NSLocalizedString(@"note.display.wide",nil); + if([mode isEqualToString:@"wider"])return NSLocalizedString(@"note.display.wider",nil); + return NSLocalizedString(@"note.display.normal",nil); +} +static NSString *selected_mode(NSSegmentedControl *control) { + NSInteger index=control.selectedSegment; + return display_modes()[index>=0&&index<(NSInteger)display_modes().count?index:0]; +} @interface DR3Launcher : NSObject @property(strong) NSWindow *window; @@ -54,7 +73,7 @@ - (void)applicationDidFinishLaunching:(NSNotification *)note { NSMenu *applicationMenu=[[NSMenu alloc] initWithTitle:@"DR3 Mobile"]; NSMenuItem *quit=[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"menu.quit",nil) action:@selector(terminate:) keyEquivalent:@"q"]; quit.target=NSApp;[applicationMenu addItem:quit];applicationItem.submenu=applicationMenu;NSApp.mainMenu=menu; - [NSUserDefaults.standardUserDefaults registerDefaults:@{@"LaunchWide":@NO,@"LaunchMetalHUD":@YES,@"LaunchMetalFX":@YES,@"LaunchLocalLAN":@YES,@"LaunchLanguage":@"system"}]; + [NSUserDefaults.standardUserDefaults registerDefaults:@{@"LaunchMetalHUD":@YES,@"LaunchMetalFX":@YES,@"LaunchLocalLAN":@YES,@"LaunchLanguage":@"system"}]; self.window=[[NSWindow alloc] initWithContentRect:NSMakeRect(0,0,760,610) styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; @@ -68,10 +87,15 @@ - (void)applicationDidFinishLaunching:(NSNotification *)note { NSStackView *left=column(@[icon,title,label(NSLocalizedString(@"subtitle",nil),12,YES),self.play, label(NSLocalizedString(@"note.autosave",nil),12,YES), label(g_testSession?NSLocalizedString(@"save.test",nil):NSLocalizedString(@"save.local",nil),12,YES)],16); - self.mode=[NSSegmentedControl segmentedControlWithLabels:@[NSLocalizedString(@"mode.normal",nil),NSLocalizedString(@"mode.wide",nil)] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(changed:)]; - self.mode.selectedSegment=[NSUserDefaults.standardUserDefaults boolForKey:@"LaunchWide"]?1:0;self.mode.identifier=@"display-mode"; - [self.mode setEnabled:[NSFileManager.defaultManager fileExistsAtPath:[g_resources stringByAppendingPathComponent:@"rewrite-wide/main.patched.bin"]] forSegment:1]; - if(![self.mode isEnabledForSegment:1])self.mode.selectedSegment=0; + NSArray *modes=display_modes(); + self.mode=[NSSegmentedControl segmentedControlWithLabels:@[NSLocalizedString(@"mode.normal",nil),NSLocalizedString(@"mode.wide",nil),NSLocalizedString(@"mode.wider",nil)] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(changed:)]; + for(NSInteger i=1;i<(NSInteger)modes.count;i++)[self.mode setEnabled:display_available(modes[i]) forSegment:i]; + // LaunchDisplayMode supersedes the retired LaunchWide bool; a missing preference migrates from it. + NSString *saved=[NSUserDefaults.standardUserDefaults stringForKey:@"LaunchDisplayMode"]; + if(!saved)saved=[NSUserDefaults.standardUserDefaults boolForKey:@"LaunchWide"]?@"wide":@"normal"; + NSInteger segment=[modes indexOfObject:saved]; + if(segment==NSNotFound||!display_available(modes[segment]))segment=0; + self.mode.selectedSegment=segment;self.mode.identifier=@"display-mode"; self.displayNote=label(@"",12,YES);self.graphicsNote=label(@"",12,YES); self.hud=[self toggle:NSLocalizedString(@"toggle.hud",nil) key:@"LaunchMetalHUD"]; self.fx=[self toggle:NSLocalizedString(@"toggle.metalfx",nil) key:@"LaunchMetalFX"]; @@ -102,17 +126,20 @@ - (void)applicationDidFinishLaunching:(NSNotification *)note { } - (void)changed:(id)sender { (void)sender;NSUserDefaults *d=NSUserDefaults.standardUserDefaults; - [d setBool:self.mode.selectedSegment==1 forKey:@"LaunchWide"]; + NSString *mode=selected_mode(self.mode); + [d setObject:mode forKey:@"LaunchDisplayMode"]; for(NSButton *b in @[self.hud,self.fx,self.lan])[d setBool:b.state==NSControlStateValueOn forKey:b.identifier]; [d setObject:self.language.selectedItem.representedObject forKey:@"LaunchLanguage"]; - self.displayNote.stringValue=self.mode.selectedSegment==1?NSLocalizedString(@"note.display.wide",nil):NSLocalizedString(@"note.display.normal",nil); + self.displayNote.stringValue=display_note(mode); self.graphicsNote.stringValue=self.fx.state==NSControlStateValueOn?NSLocalizedString(@"note.graphics.fx",nil):NSLocalizedString(@"note.graphics.direct",nil); } - (void)start:(id)sender { (void)sender;if(self.starting)return;self.starting=YES;self.play.enabled=NO; @try { - BOOL wide=self.mode.selectedSegment==1,fx=self.fx.state==NSControlStateValueOn; - NSString *rewrite=[g_resources stringByAppendingPathComponent:wide?@"rewrite-wide":@"rewrite"]; + BOOL fx=self.fx.state==NSControlStateValueOn; + NSString *mode=selected_mode(self.mode); + if(!display_available(mode))mode=@"normal"; + NSString *rewrite=[g_resources stringByAppendingPathComponent:display_folder(mode)]; NSString *binary=[[[g_resources stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"MacOS"] stringByAppendingPathComponent:@"dmhost"]; NSFileManager *fm=NSFileManager.defaultManager;NSError *error=nil; if(![fm createDirectoryAtPath:[g_runRoot stringByAppendingPathComponent:@"temp"] withIntermediateDirectories:YES attributes:nil error:&error]) @@ -132,10 +159,10 @@ - (void)start:(id)sender { setenv("DM_HID_RECEIPT_LIMIT","65536",1);setenv("DM_NVN_TSV_CALLS","0",1);setenv("DM_NVN_UNIFORM_FORWARD","1",1); setenv("DM_NVN_TBDR","0",1);setenv("DM_PSO_MANIFEST","off",1); setenv("MTL_HUD_ENABLED",self.hud.state==NSControlStateValueOn?"1":"0",1); - setenv("DM_METALFX",fx?"spatial":"off",1);setenv("DM_MAC_DISPLAY_MODE",wide?"wide":"normal",1); + setenv("DM_METALFX",fx?"spatial":"off",1);setenv("DM_MAC_DISPLAY_MODE",mode.UTF8String,1); setenv("DM_DR3_LAN",self.lan.state==NSControlStateValueOn?"1":"0",1); [NSUserDefaults.standardUserDefaults synchronize]; - fprintf(stderr,"launch: mode=%s HUD=%s MetalFX=%s LAN=%s lang=%s save=%s\n",wide?"wide":"normal",getenv("MTL_HUD_ENABLED"),getenv("DM_METALFX"),getenv("DM_DR3_LAN"),getenv("DM_LANG"),g_testSession?"test-copy":"local"); + fprintf(stderr,"launch: mode=%s HUD=%s MetalFX=%s LAN=%s lang=%s save=%s\n",mode.UTF8String,getenv("MTL_HUD_ENABLED"),getenv("DM_METALFX"),getenv("DM_DR3_LAN"),getenv("DM_LANG"),g_testSession?"test-copy":"local"); char *args[]={(char *)binary.fileSystemRepresentation,(char *)rewrite.fileSystemRepresentation,"main","sdk",NULL}; execv(args[0],args);[NSException raise:@"Launch failed" format:@"%s",strerror(errno)]; } @catch(NSException *e) {