render_we.py 7.1 KB

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