render_we.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. #!/usr/bin/env python3
  2. """Real Wallpaper Engine reference frames under Wine, a fresh WE instance per item.
  3. render_we.py [ids...] (default: every item in the scan.py database)
  4. render_we.py <dir|scene.json|scene.pkg> ... test scenes, frames go to $REFS/<dir name>
  5. Writes $REFS/<id>/f*.png (default ~/.local/share/we_live/refs; full :98 screen, window at +4+30) + we.log.
  6. Items that already have frames are skipped unless FORCE=1. Instead of fixed sleeps it waits until the window
  7. isn't a flat colour any more (the first rendered frame), then SETTLE seconds, then FRAMES frames INTERVAL
  8. seconds apart (env overrides). -control openWallpaper sent to a running instance doesn't switch wallpapers under
  9. Wine (it only brings the UI window back), hence one instance per item.
  10. Audio is pointed at dead sockets, see README.md. Setup of the Wine prefix: README.md.
  11. WE_PROTON=<name> runs an installed Proton build (wine/proton.sh) with frames in $WE_LIVE_DIR/refs_proton/<name>,
  12. WE_WINE_DIR/WE_PREFIX another Wine build like the wine/ scripts.
  13. """
  14. import os, shutil, subprocess, sys, time
  15. import resource
  16. import numpy as np
  17. import mss
  18. from PIL import Image
  19. from Xlib import display as xdisplay
  20. S = os.environ.get('WE_LIVE_DIR', os.path.expanduser('~/.local/share/we_live'))
  21. HERE = os.path.dirname(os.path.abspath(__file__)) + '/wine'
  22. W = os.environ.get('LWE_WORKSHOP_DIR', '/workspace/SteamLibrary/steamapps/workshop/content/431960')
  23. LIB = os.environ.get('LWE_LIBRARY_DIR', os.path.expanduser('~/.local/share/lwe-library'))
  24. PROTON = os.environ.get('WE_PROTON')
  25. if PROTON:
  26. out = subprocess.run(['bash', HERE + '/proton.sh', 'env', PROTON], capture_output=True, text=True)
  27. if out.returncode:
  28. sys.exit(out.stdout + out.stderr)
  29. for k, v in (kv.split('=', 1) for kv in out.stdout.split()[1:]):
  30. os.environ[k] = v
  31. REFS = os.environ.get('REFS', S + ('/refs_proton/' + PROTON if PROTON else '/refs'))
  32. D = ':98'
  33. FRAMES = int(os.environ.get('FRAMES', 5))
  34. INTERVAL = float(os.environ.get('INTERVAL', 1.0))
  35. SETTLE = float(os.environ.get('SETTLE', 4.0))
  36. TIMEOUT = float(os.environ.get('SWITCH_TIMEOUT', 30))
  37. RETRIES = int(os.environ.get('RETRIES', 3))
  38. # Wine must only see the isolated :98, not the desktop session (wayland-0, D-Bus) in the shared runtime dir
  39. env = {k: v for k, v in os.environ.items() if k not in ('WAYLAND_DISPLAY', 'WAYLAND_SOCKET', 'DBUS_SESSION_BUS_ADDRESS')}
  40. env = dict(env, XDG_RUNTIME_DIR=S + '/run', WINEPREFIX=os.environ.get('WE_PREFIX', S + '/wineprefix'), DISPLAY=D, WINEDEBUG='-all', DXVK_LOG_PATH=S,
  41. PULSE_SERVER=f'unix:{S}/run/no-pulse', PIPEWIRE_REMOTE=f'{S}/run/no-pipewire', ALSA_CONFIG_PATH=S + '/run/asound-null.conf')
  42. # Debian keeps the 64-bit loader out of PATH, Fedora's wine is the wow64 build
  43. WINE = '/usr/lib/wine/wine64' if os.path.exists('/usr/lib/wine/wine64') else shutil.which('wine')
  44. WINESERVER = '/usr/lib/wine/wineserver' if os.path.exists('/usr/lib/wine/wineserver') else shutil.which('wineserver')
  45. if os.environ.get('WE_WINE_DIR'):
  46. WINE = os.environ['WE_WINE_DIR'] + '/bin/wine'
  47. WINESERVER = os.environ['WE_WINE_DIR'] + '/bin/wineserver'
  48. we_proc = None
  49. log = None
  50. # no core files: the sandbox shares the desktop's user and its crash handler picks them up
  51. resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
  52. def winpath(p):
  53. return 'Z:' + p.replace('/', '\\')
  54. def grab(m):
  55. s = m.grab({'left': 0, 'top': 0, 'width': 1920, 'height': 1080})
  56. return Image.frombytes('RGB', s.size, s.rgb)
  57. def small(img):
  58. return np.asarray(img.crop((4, 30, 1920, 1080)).resize((240, 131))).astype(np.float32)
  59. def hide_ui():
  60. d = xdisplay.Display(D)
  61. root = d.screen().root
  62. def walk(w):
  63. # windows can disappear while walking the tree
  64. try:
  65. children = w.query_tree().children
  66. except Exception:
  67. return
  68. for c in children:
  69. yield c
  70. yield from walk(c)
  71. for w in walk(root):
  72. try:
  73. if w.get_wm_name() == 'Wallpaper UI':
  74. w.unmap()
  75. except Exception:
  76. pass
  77. try:
  78. top = root.query_tree().children
  79. except Exception:
  80. top = []
  81. for w in top:
  82. try:
  83. g = w.get_geometry()
  84. if w.get_attributes().map_state == 2 and min(g.width, g.height) <= 20 and (g.width, g.height) != (1, 1):
  85. w.unmap()
  86. except Exception:
  87. pass
  88. d.sync()
  89. d.close()
  90. def start_we(first):
  91. global we_proc, log
  92. subprocess.run([WINESERVER, '-k'], env=env, stderr=subprocess.DEVNULL)
  93. time.sleep(1)
  94. log = open(S + '/we_run_last.log', 'w')
  95. we_proc = subprocess.Popen([WINE, 'wallpaper64.exe', '-control', 'openWallpaper', '-file', winpath(first),
  96. '-monitor', '0', '-playInWindow', '-silent'], cwd=S + '/we28', env=env,
  97. stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, start_new_session=True)
  98. def wait_rendered(m, t0, timeout):
  99. """until the window isn't a flat colour any more, or timeout"""
  100. while time.time() - t0 < timeout:
  101. hide_ui()
  102. if small(grab(m)).std() > 3:
  103. return True
  104. time.sleep(0.3)
  105. return False
  106. def item_file(id_, info):
  107. if info.get('type') == 'scene':
  108. # "file" is scene.json, or gifscene.json for gif scenes, packed into the .pkg of the same name
  109. name = info.get('file') or 'scene.json'
  110. pkg = os.path.join(W, id_, os.path.splitext(name)[0] + '.pkg')
  111. return pkg if os.path.exists(pkg) else os.path.join(W, id_, name)
  112. return os.path.join(W, id_, 'project.json')
  113. def main():
  114. import json, glob
  115. db = json.load(open(LIB + '/features.json'))
  116. ids = sys.argv[1:] or sorted(db)
  117. if not os.environ.get('FORCE'):
  118. ids = [i for i in ids if os.path.exists(i) or not glob.glob(f'{REFS}/{i}/f*.png')]
  119. out_root = REFS
  120. files = []
  121. for n, i in enumerate(ids):
  122. if os.path.exists(i):
  123. path = os.path.abspath(i)
  124. files.append(path + '/scene.json' if os.path.isdir(path) else path)
  125. ids[n] = os.path.basename(path if os.path.isdir(path) else os.path.dirname(path))
  126. else:
  127. files.append(item_file(i, db.get(i, {}).get('info', {})))
  128. subprocess.run(['bash', HERE + '/we_display.sh'], stdout=subprocess.DEVNULL, check=True)
  129. with mss.MSS(display=D) as m:
  130. for n, f in enumerate(files):
  131. id_ = ids[n]
  132. out = os.path.join(out_root, id_)
  133. os.makedirs(out, exist_ok=True)
  134. for old in os.listdir(out):
  135. os.remove(os.path.join(out, old))
  136. t0 = time.time()
  137. # scenes with video textures sometimes never get past a flat first frame under Wine, a new
  138. # instance usually does
  139. for attempt in range(RETRIES):
  140. start = time.time()
  141. start_we(f)
  142. # the killed instance's window must be gone before "not flat" means anything
  143. while time.time() - start < 10 and small(grab(m)).std() > 3:
  144. time.sleep(0.2)
  145. ok = wait_rendered(m, start, TIMEOUT)
  146. if ok:
  147. break
  148. time.sleep(SETTLE)
  149. hide_ui()
  150. t1 = time.time()
  151. last = None
  152. for i in range(FRAMES):
  153. last = grab(m)
  154. last.save('%s/f%03d_%.1f.png' % (out, i, time.time() - t1))
  155. time.sleep(INTERVAL)
  156. log.flush()
  157. try:
  158. with open(S + '/we_run_last.log', errors='replace') as src, open(out + '/we.log', 'w') as dst:
  159. dst.write(src.read()[-20000:])
  160. except OSError:
  161. pass
  162. print(f'we {id_} {FRAMES} frames{"" if ok else " (still flat)"} {time.time() - t0:.1f}s', flush=True)
  163. subprocess.run([WINESERVER, '-k'], env=env, stderr=subprocess.DEVNULL)
  164. if __name__ == '__main__':
  165. main()