Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dm/games/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ None of them has a default game: without one they stop and list the profiles. To
- `python3 dm/games/game.py list` lists the profiles.
- `python3 dm/games/game.py <id> <key>` prints one key.

**Launcher settings.** `settings.tsv` lists the player-facing settings once (the environment variable each sets, its kind, default, the condition under which a game offers it and its section on the single settings screen, **Game**, **Controls** or **Performance**; Reset to tested defaults forgets all launcher choices so the profile's defaults apply again; its header describes the columns). A profile key a setting defaults to (`DM_GAME_<NAME>`) is the value the game was tested with, which the player page [docs/settings.md](../../docs/settings.md#tested-defaults) explains. `build_ipa.sh` runs `settings.py <id> <rewritten modules> <control.nacp> <out.json>`, which keeps the rows that hold for the game: a profile macro (`DM_GAME_FPS_TARGET!=0`), a key in `main`'s rewriter table (`RENDER_SCALE`, written by `patch_nso.py` for the builds with a render-scale stub), the game's languages. It writes them into the app as `dm/launcher.json`, from which the iOS launcher (`dm/ios/Sources/Launcher.swift`) draws its screen. A new player setting is one row; diagnostic switches stay environment-only.
**Launcher settings.** `settings.tsv` lists the player-facing settings once (the environment variable each sets, its kind, default, the condition under which a game offers it and its section on the single settings screen, **Game**, **Controls** or **Performance**; Reset to tested defaults forgets all launcher choices so the profile's defaults apply again; its header describes the columns). A profile key a setting defaults to (`DM_GAME_<NAME>`) is the value the game was tested with, which the player page [docs/settings.md](../../docs/settings.md#tested-defaults) explains. `build_ipa.sh` runs `settings.py <id> <rewritten modules> <control.nacp> <out.json>`, which keeps the rows that hold for the game: a profile macro (`DM_GAME_FPS_TARGET!=0`), a key in `main`'s rewriter table (`RENDER_SCALE`, written by `patch_nso.py` for the builds with a render-scale stub), the game's languages. It writes them into the app as `dm/launcher.json`, from which the iOS launcher (`dm/ios/Sources/Launcher.swift`) draws its screen; the NSP script packs the Mac app's copy (`SETTINGS_PLATFORM=mac`, without the rows marked `platform:ios`, `Contents/Resources/dm/launcher.json`) for a Mac front end, which shows the list and starts the app with the chosen values in its environment. A new player setting is one row; diagnostic switches stay environment-only.

## Games

Expand Down
4 changes: 3 additions & 1 deletion dm/games/settings.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env python3
# The iOS launcher's settings for one game, from settings.tsv (its header describes the columns): the rows whose condition holds for the game, with the game's defaults, as JSON.
# build_ipa.sh writes it into the app as dm/launcher.json; Launcher.swift draws the screen from it (an app without the file starts the game at once).
# Usage: settings.py <game id> <rewritten modules dir> <control.nacp> <out.json> (DM_GAMES_DIR finds provisional profiles, as in game.py; build:<VAR> defaults come from the environment)
# Usage: settings.py <game id> <rewritten modules dir> <control.nacp> <out.json> (DM_GAMES_DIR finds provisional profiles, as in game.py; build:<VAR> defaults come from the environment;
# GFXAPI is the packer's graphics API, SETTINGS_PLATFORM the app's platform: ios (default) or mac, whose launcher is the Mac front end)
import json, os, re, sys
from pathlib import Path

Expand Down Expand Up @@ -41,6 +42,7 @@ def shown(cond, n):
if cond == 'languages>1': return len(langs) > 1
if cond.startswith('fixups:'): return cond[7:] in keys
if cond.startswith('gfxapi:'): return os.environ.get('GFXAPI', '') == cond[7:]
if cond.startswith('platform:'): return (os.environ.get('SETTINGS_PLATFORM') or 'ios') == cond[9:]
m = re.fullmatch(r'(DM_GAME_\w+)(!=|==)(.*)', cond)
if m: return (macro(m[1], n) == m[3]) == (m[2] == '==')
sys.exit(f'settings.tsv:{n}: unknown condition {cond}')
Expand Down
11 changes: 6 additions & 5 deletions dm/games/settings.tsv
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# Player-facing settings: the iOS launcher (dm/ios/Sources/Launcher.swift) shows them before the game starts. dm/games/settings.py writes one game's list into its app (dm/launcher.json,
# build_ipa.sh): the rows whose condition holds for that game, with its defaults. Each sets an environment variable the host reads when the game starts; one an env file sets
# Player-facing settings: the iOS launcher (dm/ios/Sources/Launcher.swift) shows them before the game starts, the Mac front end (frontend/) before it starts a Mac app.
# dm/games/settings.py writes one game's list into its app (dm/launcher.json; build_ipa.sh, and dm/mac/pack_app.py through the NSP script): the rows whose condition holds for that game, with its defaults. Each sets an environment variable the host reads when the game starts; one an env file sets
# (Documents/env.txt, the bundle's dm/env.txt) is shown but kept. Diagnostic switches stay environment-only, so they are not listed here. The player's page is docs/settings.md.
# Columns, separated by tabs:
# variable the environment variable the setting sets
# kind choice: values value=label,... (languages: the game's own, from its control data); range: values low:high:step, shown as a percentage;
# toggle: values - (on sets 1, off 0) or <on>/<off>, the two values the variable takes (on/off)
# default a value (a toggle's: 1 on, 0 off); DM_GAME_<NAME>: the host's own default from the game profile (game_profile.h, game.py); build:<VAR>: the IPA build's setting (build_ipa.sh)
# shown always; DM_GAME_<NAME>!=<value> or ==<value>; fixups:<KEY>: main's rewriter table has that key (a stub in the game's build, patch_nso.py); languages>1; gfxapi:<API>: the packer's GFXAPI
# shown always; DM_GAME_<NAME>!=<value> or ==<value>; fixups:<KEY>: main's rewriter table has that key (a stub in the game's build, patch_nso.py); languages>1; gfxapi:<API>: the packer's GFXAPI;
# platform:<ios | mac>: the app's platform (SETTINGS_PLATFORM, ios when unset), for a switch only that platform's front end reads
# section Game, Controls or Performance: a heading on the single settings screen. Rows appear in table order within each section
# Reset to tested defaults clears all launcher choices; values fixed by an env file stay
# label, note the setting's name and the line under it (may be empty; only for a setting with a cost: latency, memory, heat)
Expand All @@ -15,8 +16,8 @@ DM_RENDER_SCALE range 0.5:1.0:0.05 1.0 fixups:RENDER_SCALE Game Render scale
DM_OPMODE choice 1=Docked,0=Handheld DM_GAME_OPMODE always Game Console mode
DM_PRESENT_UPSCALE choice off=Standard,metalfx=MetalFX off always Game Upscaling Uses more GPU time and can increase heat.
DM_LANG choice languages build:DM_LANG languages>1 Game Game language
DM_SHOW_FPS toggle - build:DM_SHOW_FPS always Game Frame-rate counter
DM_TOUCH_HAPTICS toggle - 1 always Controls Touch feedback
DM_SHOW_FPS toggle - build:DM_SHOW_FPS platform:ios Game Frame-rate counter
DM_TOUCH_HAPTICS toggle - 1 platform:ios Controls Touch feedback
DM_RUMBLE toggle - 1 always Controls Game rumble
DM_RUMBLE_GAIN range 0:3:0.1 1.0 always Controls Rumble strength
DM_RUMBLE_MIN range 0:0.9:0.05 0 always Controls Rumble cutoff
Expand Down
42 changes: 42 additions & 0 deletions dm/gfx/tests/test_shader_split_progress.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""shader_split.py's progress lines: the jobs are counted as they finish, in any order, while the results keep the job order."""
import concurrent.futures as cf
import contextlib
import io
from pathlib import Path
import sys
import threading
import unittest
from unittest import mock

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
import shader_split as split


class PooledProgressTests(unittest.TestCase):
def test_a_slow_first_job_does_not_hold_the_count(self):
release = threading.Event()
def scan(job): # job 0 is a large archive range: it finishes only after the others
if job == 0: release.wait(5)
return job
lines = io.StringIO()
with mock.patch.object(split, 'scan_file', scan), cf.ThreadPoolExecutor(4) as ex, contextlib.redirect_stdout(lines):
def watch(): # the count reaches 19 of 20 while job 0 still runs, then job 0 is let go
while 'progress: 19/20' not in lines.getvalue(): threading.Event().wait(0.05)
release.set()
threading.Thread(target=watch, daemon=True).start()
results = split.pooled(ex, list(range(20)), 20)
self.assertEqual(results, list(range(20))) # the job order, as pool.map gave it
counts = [l for l in lines.getvalue().split('\n') if l.startswith('progress: ')]
self.assertIn('progress: 19/20', counts)
self.assertEqual(counts[-1], 'progress: 20/20')

def test_batches_and_an_offset_count_every_job_once(self):
lines = io.StringIO()
with mock.patch.object(split, 'scan_file', lambda job: job * 2), cf.ThreadPoolExecutor(3) as ex, contextlib.redirect_stdout(lines):
results = split.pooled(ex, list(range(37)), 40, start=3, chunk=16)
self.assertEqual(results, [j * 2 for j in range(37)])
self.assertEqual(lines.getvalue().split('\n')[-2], 'progress: 40/40') # the 3 jobs before, then all 37 of these


if __name__ == '__main__':
unittest.main()
22 changes: 20 additions & 2 deletions dm/gfx/tools/shader_split.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
# With an update: give RomFS and main as comma-separated lists (base game first, e.g. data/v0/RomFS,data/v327680/RomFS); the output is the union of both versions (see main())
# Unity type trees need Unity's common string table, which is taken from the first main
# Pair table: (vertex key, pixel key) of every BNSH variation (every Unity program); dmsh_build uses it to give vertex shaders the outputs their pixel shaders read but they do not write (see dmsh_build.py vs_pad)
import collections, concurrent.futures as cf, hashlib, json, os, re, struct, subprocess, sys, zlib
import collections, concurrent.futures as cf, hashlib, json, os, re, struct, subprocess, sys, time, zlib
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../tools'))
from romfs import os, open, is_image
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../games')); import game as _game
Expand Down Expand Up @@ -2125,6 +2125,23 @@ def nso_image(path):
img[mo:mo + sz] = lz4.block.decompress(raw, uncompressed_size=sz) if flags >> i & 1 else raw
return bytes(img)

def scan_batch(jobs): # scan_file over a batch of jobs, in a pool worker
return [scan_file(j) for j in jobs]


def pooled(ex, jobs, total, start=0, chunk=1):
"""scan_file over jobs in the pool, the results in job order, with a 'progress: <done>/<total>' line at most twice a second (the NSP script shows it as
the stage's count). The count is of the jobs finished in any order: counted in order it would stall behind one slow archive range while the others finish"""
batches = [jobs[i:i + chunk] for i in range(0, len(jobs), chunk)]
futures = {ex.submit(scan_batch, b): len(b) for b in batches}
done, pending, shown = start, set(futures), 0.0
while pending:
finished, pending = cf.wait(pending, timeout=0.5)
done += sum(futures[f] for f in finished)
if not pending or time.monotonic() - shown >= 0.5: print(f'progress: {done}/{total}', flush=True); shown = time.monotonic()
return [r for f in futures for r in f.result()]


def main():
romfs_l, main_l, pkg, mapout, factsout = sys.argv[1:6]
pairsout = sys.argv[6] if len(sys.argv) > 6 else None
Expand Down Expand Up @@ -2182,7 +2199,8 @@ def main():
big += pak_jobs + tr_jobs + ue_jobs + bd_jobs + arc_jobs + pz_jobs + ck_jobs + zp_jobs + ah_jobs
files = [(p, r) for p, r in files if not linkdata_jobs(p, r) and p not in paks and p not in trp and p not in uep and p not in bdts and p not in arcs and p not in pkzs and p not in cpks and p not in zips and p not in arhs]
with cf.ProcessPoolExecutor(J, initializer=_pool_init, initargs=(common, {}, zdicts)) as ex:
results += list(ex.map(scan_file, big)) + list(ex.map(scan_file, files, chunksize=16))
n = len(big) + len(files)
results += pooled(ex, big, n) + pooled(ex, files, n, len(big), chunk=16)
trees, defer = {}, []
for rel, uniq, pr, extra in results:
if extra == 'defer': defer.append(rel)
Expand Down
9 changes: 6 additions & 3 deletions dm/mac/pack_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
# Pack a self-contained, double-clickable Mac app of a game (the NSP script's --platform mac-app): the launcher (dm/mac/launcher.c, compiled here) as CFBundleExecutable, the Mac host beside it,
# and in Contents/Resources what the IPA carries (dm/ios/tools/build_ipa.sh): romfs.img (the RomFS image), msl/<b-chain | vk | gl>/ (the Mac shader libraries, the folder named as in the IPA),
# aoc/<index>/ (DLC), pso/ (an NVN game's pipeline archive made offline for this Mac's GPU, dm/gfx/tools/pso_offline.py: the launcher hands it to the host as DM_PSO_BUNDLE),
# and dm/ (the rewritten modules and their rewriter tables, nro.tsv, the profile's shader_map.tsv / pso_manifest.tsv / c1_full.tsv / cb_extent.tsv / shader_pairs.tsv / pso_pairs.tsv, font/, env.txt),
# and dm/ (the rewritten modules and their rewriter tables, nro.tsv, the profile's shader_map.tsv / pso_manifest.tsv / c1_full.tsv / cb_extent.tsv / shader_pairs.tsv / pso_pairs.tsv, font/, env.txt,
# launcher.json: the game's launcher settings, dm/games/settings.py, which a Mac front end shows and passes to the app as its environment),
# plus AppIcon.icns from the game's icon (sips, iconutil) and the Info.plist keys the launcher reads (DMTitleID, DMRomfsMarker, DMLanguage).
# The large folders are APFS clones (cp -c) when the app is on the same APFS volume as the build, so they take no space; plain copies otherwise.
# Signing: the inner host first, then the bundle (codesign --force --sign <identity>; '-' = ad-hoc), without the hardened runtime: the host maps the game's code executable, which the hardened
Expand Down Expand Up @@ -150,7 +151,7 @@ def selected_inputs(a):
pairs = Path(a.pso_pairs) if a.pso_pairs and not any(p.name == 'pso_pairs.tsv' for p in tables) else None
fonts = sorted(Path(a.font).glob('*.ttf'))
files = [Path(a.host)] + mods + msls + pso + tables + fonts + ([pairs] if pairs else [])
files += [Path(p) for p in (a.env_file, a.icon) if p]
files += [Path(p) for p in (a.env_file, a.settings, a.icon) if p]
for p in files:
if not p.is_file(): raise SystemExit(f'no input file at {p}')
return mods, msls, pso, tables, pairs, fonts, files
Expand All @@ -177,7 +178,7 @@ def pack(a):
except (OSError, ValueError): previous = None
try:
a = argparse.Namespace(**vars(a))
for name in ('out', 'host', 'patched', 'romfs', 'msl', 'tables', 'font', 'aoc', 'pso', 'pso_pairs', 'env_file', 'icon'):
for name in ('out', 'host', 'patched', 'romfs', 'msl', 'tables', 'font', 'aoc', 'pso', 'pso_pairs', 'env_file', 'settings', 'icon'):
if getattr(a, name): setattr(a, name, str(Path(getattr(a, name)).resolve()))
mods, msls, pso, tables, pairs, fonts, files = selected_inputs(a)
clang = Path(run(['xcrun', '--find', 'clang']).strip()).resolve()
Expand Down Expand Up @@ -219,6 +220,7 @@ def pack(a):
if pairs: shutil.copyfile(pairs, dm / 'pso_pairs.tsv') # the split's copy, for a profile without the table
if fonts: copy(fonts, dm / 'font', False)
if a.env_file: shutil.copyfile(a.env_file, dm / 'env.txt')
if a.settings: shutil.copyfile(a.settings, dm / 'launcher.json')
step('shader libraries'); msl_dst = res / 'msl' / (a.msl_name or msl.name); msl_dst.mkdir(parents=True); copy(msls, msl_dst, clone)
if aoc: step('add-on content'); copy([aoc], res / 'aoc', clone)
if pso: step('pipeline archive'); (res / 'pso').mkdir(); copy(pso, res / 'pso', pso_clone)
Expand Down Expand Up @@ -260,6 +262,7 @@ def parse(argv):
ap.add_argument('--pso', help='the pipeline archive made offline for this Mac (pso_offline.py --platform macos output: <arch>.mtl4a, prebuilt.tsv)')
ap.add_argument('--pso-pairs', help='pso_pairs.tsv for a profile that has none (the shader split\'s copy)')
ap.add_argument('--env-file', help='environment switches baked in (Resources/dm/env.txt)')
ap.add_argument('--settings', help='the game\'s launcher settings (dm/games/settings.py output; Resources/dm/launcher.json, which the Mac front end reads)')
ap.add_argument('--title-id', required=True); ap.add_argument('--name', required=True)
ap.add_argument('--version'); ap.add_argument('--bundle-id'); ap.add_argument('--category'); ap.add_argument('--lang'); ap.add_argument('--marker', help='the profile\'s romfs_marker')
ap.add_argument('--icon', help='the game icon (icon.jpg from the control data)')
Expand Down
1 change: 0 additions & 1 deletion dm/tools/lint_python_baseline.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,6 @@ pyright dm/tools/tests/test_nsp_incremental.py reportArgumentType 1 Argument of
pyright dm/tools/tests/test_nsp_incremental.py reportArgumentType 1 Argument of type "int | str | tuple[str, str]" cannot be assigned to parameter "ver" of type "str" in function "derive" Type "int | str | tuple[str, str]" is not assignable to type "str" "int" is not assignable to "str"
pyright dm/tools/tests/test_nsp_incremental.py reportAttributeAccessIssue 1 Cannot assign to attribute "nacp" for class "ModuleType" Attribute "nacp" is unknown
pyright dm/tools/tests/test_nsp_incremental.py reportAttributeAccessIssue 1 Cannot assign to attribute "pg" for class "ModuleType" Attribute "pg" is unknown
pyright dm/tools/tests/test_nsp_incremental.py reportOptionalCall 2 Object of type "None" cannot be called
pyright dm/tools/tests/test_nsp_incremental.py reportOptionalMemberAccess 1 "exec_module" is not a known attribute of "None"
pyright dm/tools/tests/test_nsp_incremental.py reportOptionalMemberAccess 1 "loader" is not a known attribute of "None"
pyright dm/tools/tests/test_nsp_mac.py reportArgumentType 1 Argument of type "ModuleSpec | None" cannot be assigned to parameter "spec" of type "ModuleSpec" in function "module_from_spec" Type "ModuleSpec | None" is not assignable to type "ModuleSpec" "None" is not assignable to "ModuleSpec"
Expand Down
12 changes: 10 additions & 2 deletions dm/tools/tests/test_launcher_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
PERFORMANCE_NVN = ['DM_PRESENT_SNAP', 'DM_PSO_MTL4', 'DM_PSO_PREBUILD', 'DM_NVN_ENC_THREAD', 'DM_FPS_HOLD', 'DM_METAL_HUD']


def build(gid, api):
with tempfile.TemporaryDirectory() as tmp, patch.object(settings.nacp, 'languages', return_value=['en-US']), patch.dict(os.environ, {'GFXAPI': api}):
def build(gid, api, platform=None):
env = {'GFXAPI': api, **({'SETTINGS_PLATFORM': platform} if platform else {})}
with tempfile.TemporaryDirectory() as tmp, patch.object(settings.nacp, 'languages', return_value=['en-US']), patch.dict(os.environ, env):
if not platform: os.environ.pop('SETTINGS_PLATFORM', None)
return {s['env']: s for s in settings.build(gid, tmp, Path(tmp) / 'control.nacp')['settings']}


Expand Down Expand Up @@ -54,6 +56,12 @@ def test_hold_frames_takes_on_and_off(self): # the host reads DM_FPS_HOLD as o
s = build(BOTW, 'nvn')['DM_SHOW_FPS']
self.assertEqual((s['on'], s['off']), ('1', '0'))

def test_iphone_switches_only_on_the_iphone(self): # the frame-rate counter and touch feedback are the iOS front end's (front_ios.m, DmGamepad.m)
ios, mac = build(BOTW, 'nvn'), build(BOTW, 'nvn', 'mac')
self.assertEqual(build(BOTW, 'nvn', 'ios').keys(), ios.keys()) # ios when unset
self.assertEqual(set(ios) - set(mac), {'DM_SHOW_FPS', 'DM_TOUCH_HAPTICS'})
self.assertIn('DM_RUMBLE', mac); self.assertIn('DM_METAL_HUD', mac)

def test_table_format_is_strict(self):
good = 'DM_X\ttoggle\t-\t0\talways\tGame\tX\n'
for bad, why in [('DM_X\ttoggle\t-\t0\talways\tX\n', 'columns'), ('DM_X\ttoggle\t-\t0\talways\tsecret\tX\n', 'section'),
Expand Down
1 change: 1 addition & 0 deletions dm/tools/tests/test_nsp_incremental.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,7 @@ class MacApp(Base):
def test_packer_reports_reuse_and_first_pack_steps(self):
t = self.tmp; out = t / 'Game.app'; packs = []
def pack(cmd, log, env=None, on_line=None):
if not on_line: return # the launcher settings (dm/games/settings.py)
packs.append(cmd)
(out / 'Contents/MacOS').mkdir(parents=True, exist_ok=True)
(out / 'Contents/MacOS/dmhost').write_bytes(b'host')
Expand Down
Loading
Loading