Files
Neutron/tools/recon/reference_capture.py
T

167 lines
10 KiB
Python

#!/usr/bin/env python3
"""Capture a COPIED original in a filesystem/network-isolated Wine environment.
Requires project-local Wine and Xvfb plus bubblewrap and ImageMagick. Host mode
does not execute Wine directly: only the game copy and generated prefix are
writable inside the namespace, and the original directory is not mounted.
"""
import argparse
import ctypes
import json
import os
from pathlib import Path
import shutil
import subprocess
import time
def enter_key():
x = ctypes.CDLL('libX11.so.6')
x.XOpenDisplay.argtypes = [ctypes.c_char_p]
x.XOpenDisplay.restype = ctypes.c_void_p
x.XKeysymToKeycode.argtypes = [ctypes.c_void_p, ctypes.c_ulong]
x.XKeysymToKeycode.restype = ctypes.c_uint
x.XFlush.argtypes = [ctypes.c_void_p]
x.XCloseDisplay.argtypes = [ctypes.c_void_p]
display = x.XOpenDisplay(None)
if not display:
return False
test = ctypes.CDLL('libXtst.so.6')
test.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong]
key = x.XKeysymToKeycode(display, 0xff0d)
test.XTestFakeKeyEvent(display, key, 1, 0)
test.XTestFakeKeyEvent(display, key, 0, 0)
x.XFlush(display)
x.XCloseDisplay(display)
return True
def inside(args):
work = Path('/work')
if args.port_smoke: (work/'port-frame.ppm').unlink(missing_ok=True)
with (work/'xvfb.log').open('w') as xlog, (work/'wine.log').open('w') as wlog:
display = subprocess.Popen(['/native/usr/bin/Xvfb', ':89', '-screen', '0', '1024x768x24', '-nolisten', 'tcp'], stdout=xlog, stderr=xlog)
wine = None
try:
for _ in range(30):
if Path('/tmp/.X11-unix/X89').exists(): break
if display.poll() is not None: raise RuntimeError('Xvfb failed; see xvfb.log')
time.sleep(0.1)
wine_env = dict(os.environ, LIBGL_DRIVERS_PATH='/native/usr/lib/i386-linux-gnu/dri')
application = ['/opt/wine-stable/bin/wine', args.game]
if args.port_smoke:
application = ['/opt/wine-stable/bin/wine', r'Z:\port\GamePort.exe',
'--assets', r'Z:\port\assets', '--scene', r'Z:\port\scenes\level1b\scene.json',
'--level', 'gam/level1b.gam', '--original-camera', '--with-player',
'--frames', '240' if args.port_walk else '6' if args.port_window else '2', '--no-validation',
'--screenshot', r'Z:\work\port-frame.ppm']
application += ['--smoke-walk'] if args.port_walk else ['--inspect', '--time', '0.05']
application += ['--smoke-window'] if args.port_window and not args.port_walk else []
application += [] if args.port_window or args.port_walk else ['--headless']
if args.asset_probe:
application = ['/opt/wine-stable/bin/wine', r'Z:\probe.exe', args.probe_model]
wine = subprocess.Popen(application, cwd='/work' if args.port_smoke else '/work/game', stdout=wlog, stderr=wlog, env=wine_env)
captures = []
for index in range(3):
time.sleep(args.seconds / 3)
target = f'/work/frame-{index:02d}.png'
image = subprocess.run(['import', '-display', ':89', '-window', 'root', target], timeout=10, capture_output=True)
captures.append({'file': target, 'captureExit': image.returncode, 'wineExit': wine.poll()})
if args.enter:
captures[-1]['sentReturn'] = enter_key()
if (args.port_smoke or args.asset_probe) and wine.poll() is not None: break
tree = subprocess.run(['xwininfo', '-root', '-tree'], capture_output=True, text=True)
(work/'windows.txt').write_text(tree.stdout + tree.stderr)
processes = []
for path in Path('/proc').glob('[0-9]*/cmdline'):
try: processes.append(path.parent.name + ': ' + path.read_bytes().replace(b'\x00', b' ').decode('utf8', 'replace'))
except OSError: pass
(work/'processes.txt').write_text('\n'.join(processes)+'\n')
application_name = 'GamePort.exe' if args.port_smoke else 'omt_shape_probe.exe' if args.asset_probe else args.game
(work/'capture.json').write_text(json.dumps({'game': application_name, 'captures': captures}, indent=2)+'\n')
finally:
subprocess.run(['/opt/wine-stable/bin/wineserver', '-k'], timeout=10, check=False)
if wine and wine.poll() is None: wine.terminate()
display.terminate()
display.wait(timeout=5)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--inside', action='store_true', help=argparse.SUPPRESS)
p.add_argument('--game', choices=['Neutron.exe','NeutronNoCD.exe','NeutronSW.exe','NeutronHD.exe','NeutronHDnoCD.exe'], default='NeutronNoCD.exe')
p.add_argument('--seconds', type=int, default=24)
p.add_argument('--enter', action='store_true', help='Send Return after each screenshot')
p.add_argument('--debug', action='store_true', help='Record Wine process and exception diagnostics')
p.add_argument('--wine-renderer', choices=['gl','vulkan'], default='gl')
p.add_argument('--port-smoke', action='store_true', help='Preliminary Windows port check under Wine64; not native Windows validation')
p.add_argument('--port-window', action='store_true', help='Windows port SDL window/input/resize/animation smoke under Wine64')
p.add_argument('--port-walk', action='store_true', help='Windows port walking/jump/keyboard/resize checkpoint under Wine64')
p.add_argument('--asset-probe', action='store_true', help='Run compiled read-only OMT shape probe inside isolated copy')
p.add_argument('--probe-model', default=r'ASE\jimstop.ase')
p.add_argument('--output', type=Path)
args = p.parse_args()
args.port_smoke = args.port_smoke or args.port_window or args.port_walk
if args.port_smoke and args.asset_probe: p.error('Select either port smoke or asset probe')
if not 3 <= args.seconds <= 120: p.error('--seconds must be 3..120')
if args.inside: return inside(args)
project = Path(__file__).resolve().parents[2]
source = project.parent/'Original'
default_output = 'artifacts/windows-smoke' if args.port_smoke else 'artifacts/asset-probe' if args.asset_probe else 'artifacts/reference'
work = (args.output or project/default_output).resolve()
if work.is_relative_to(source.resolve()) or source.resolve().is_relative_to(work):
p.error('Output must be separate from originals')
work.mkdir(parents=True, exist_ok=True)
if not args.port_smoke and not (work/'game').exists(): shutil.copytree(source, work/'game')
(work/'home').mkdir(exist_ok=True)
(work/'home/.asoundrc').write_text('pcm.!default { type null }\nctl.!default { type hw card 0 }\n')
(work/'alsa-null.conf').write_text('pcm.default { type null }\npcm.null { type null }\n')
cmd = ['bwrap', '--unshare-all', '--new-session', '--die-with-parent', '--clearenv',
'--ro-bind', '/usr', '/usr', '--ro-bind', '/lib', '/lib', '--ro-bind', '/lib64', '/lib64',
'--symlink', 'usr/bin', '/bin', '--symlink', 'usr/sbin', '/sbin',
'--ro-bind', '/etc', '/etc', '--ro-bind', '/sys', '/sys', '--proc', '/proc', '--dev', '/dev',
'--tmpfs', '/tmp', '--dir', '/tmp/.X11-unix', '--tmpfs', '/var', '--dir', '/var/tmp',
'--dir', '/run', '--dir', '/home', '--bind', str(work), '/work',
'--ro-bind', str(project/'.tools/wine/opt/wine-stable'), '/opt/wine-stable',
'--ro-bind', str(project/'.tools/native'), '/native',
'--ro-bind', str(Path(__file__).resolve()), '/capture.py']
if args.port_smoke:
cmd += ['--ro-bind', str(project/'dist/win-x64'), '/port']
if args.asset_probe:
cmd += ['--ro-bind', str(project/'artifacts/binary/omt_shape_probe.exe'), '/probe.exe']
for key,value in {'HOME':'/work/home', 'WINEPREFIX':'/work/prefix', 'WINEARCH':'win64' if args.port_smoke else 'win32',
'DISPLAY':':89', 'PATH':'/opt/wine-stable/bin:/usr/bin:/bin', 'LANG':'C.UTF-8',
'WINEDEBUG':'-all,err+all,warn+ddraw,warn+d3d,+seh' if args.debug else '-all',
'ALSA_CONFIG_PATH':'/work/alsa-null.conf',
'WINEDLLOVERRIDES':'mscoree=b;mshtml=' if args.port_smoke else 'mscoree,mshtml=',
'WINE_D3D_CONFIG':'renderer='+args.wine_renderer,
'LD_LIBRARY_PATH':'/native/usr/lib/x86_64-linux-gnu:/native/usr/lib/i386-linux-gnu',
'LIBGL_ALWAYS_SOFTWARE':'1', '__GLX_VENDOR_LIBRARY_NAME':'mesa',
'__EGL_VENDOR_LIBRARY_FILENAMES':'/usr/share/glvnd/egl_vendor.d/50_mesa.json'}.items():
cmd += ['--setenv', key, value]
if args.port_smoke:
cmd += ['--setenv', 'VK_DRIVER_FILES', '/usr/share/vulkan/icd.d/lvp_icd.json']
elif args.wine_renderer == 'vulkan':
cmd += ['--setenv', 'VK_DRIVER_FILES', '/native/usr/share/vulkan/icd.d/lvp_icd.json']
cmd += ['/usr/bin/python3', '/capture.py', '--inside', '--game', args.game, '--seconds', str(args.seconds)]
if args.enter: cmd += ['--enter']
if args.port_smoke: cmd += ['--port-smoke']
if args.port_window: cmd += ['--port-window']
if args.port_walk: cmd += ['--port-walk']
if args.asset_probe: cmd += ['--asset-probe', '--probe-model', args.probe_model]
print('Running isolated Windows port' if args.port_smoke else 'Running copied original', 'with no network and no original-directory mount:', work, flush=True)
subprocess.run(cmd, check=True, timeout=args.seconds + 40)
print('Capture metadata:', work/'capture.json')
if args.port_smoke:
result = json.loads((work/'capture.json').read_text())
if result['captures'][-1]['wineExit'] != 0 or not (work/'port-frame.ppm').is_file():
raise SystemExit('Windows port smoke did not pass; inspect wine.log (native Windows remains unverified)')
print('Windows port rendered under Wine; native Windows validation is still required')
if args.asset_probe:
result = json.loads((work/'capture.json').read_text())
if result['captures'][-1]['wineExit'] != 0 or 'VERTICES ' not in (work/'wine.log').read_text():
raise SystemExit('OMT asset probe did not complete; inspect wine.log')
if __name__ == '__main__': main()