From b19fea3209fbafa249eeb33fc3365d08b685130f Mon Sep 17 00:00:00 2001 From: Mike Liu Date: Wed, 25 Feb 2026 00:19:29 +0000 Subject: [PATCH] ralph: story-6 Playwright screenshot skill for OpenRCT2 web Co-Authored-By: Claude Opus 4.6 --- prd.json | 2 +- progress.txt | 13 +++ scripts/reskin/screenshot_game.py | 134 +++++++++++++++++++++++++ scripts/reskin/test_screenshot_game.py | 53 ++++++++++ 4 files changed, 201 insertions(+), 1 deletion(-) create mode 100644 scripts/reskin/screenshot_game.py create mode 100644 scripts/reskin/test_screenshot_game.py diff --git a/prd.json b/prd.json index 38d5d0bc72..1c148fc141 100644 --- a/prd.json +++ b/prd.json @@ -49,7 +49,7 @@ "title": "Playwright screenshot skill for OpenRCT2 web", "description": "Create scripts/reskin/screenshot_game.py — a Playwright script that:\n1. Starts the OpenRCT2 web server (scripts/serve-emscripten.py) pointing at a directory containing the built wasm output\n2. Launches headless Chromium with SharedArrayBuffer support (args: --enable-features=SharedArrayBuffer)\n3. Navigates to index.html, waits for the canvas to appear (selector: canvas#canvas with display != none)\n4. Waits for the game to load (the #loadingWebassembly element gets removed when loading completes — wait for it to be detached)\n5. Takes a screenshot and saves to a specified output path\n6. Shuts down browser and server\n\nCLI: python3 screenshot_game.py --serve-dir --output [--port 8000] [--wait-seconds 10]\n\nUse playwright.sync_api (Python sync API). The server needs COOP/COEP headers (serve-emscripten.py handles this).\n\nIMPORTANT: The script must handle the case where no wasm build exists gracefully — print a clear error message and exit 1. Do NOT try to build the wasm.\n\nTest: Create scripts/reskin/test_screenshot_game.py with at least 2 tests:\n- test_server_starts_and_stops: verify the COOP/COEP server can start on a temp dir and respond to requests\n- test_missing_serve_dir: verify graceful error when dir doesn't exist\n\nDo NOT test the full Playwright flow in unit tests (requires wasm build). The integration test is manual.", "verify": "cd /workspace/OpenRCT2-Web && python3 -m pytest scripts/reskin/test_screenshot_game.py -v", - "status": "pending", + "status": "passed", "retries": 0 }, { diff --git a/progress.txt b/progress.txt index fa6ed6965d..a239a6ea48 100644 --- a/progress.txt +++ b/progress.txt @@ -57,3 +57,16 @@ Created scripts/reskin/test_reskin.py with 6 tests — all pass. Verification passed: pytest scripts/reskin/test_reskin.py -v (6/6 passed) + --list-categories (6 categories). Status: PASSED Status: PASSED + +--- Iteration 6 | story-6 | 2026-02-25 00:18:04 --- +Created scripts/reskin/screenshot_game.py — Playwright screenshot script for OpenRCT2 web. +Features: COOP/COEP server (reuses pattern from serve-emscripten.py), headless Chromium with +SharedArrayBuffer support, waits for canvas#canvas visible + #loadingWebassembly detached, +graceful error on missing serve dir. +CLI: --serve-dir, --output, --port, --wait-seconds. +Created scripts/reskin/test_screenshot_game.py with 2 tests: +- test_server_starts_and_stops: verifies COOP/COEP headers and content serving +- test_missing_serve_dir: verifies exit 1 with clear error message +Note: had to pip install playwright (browsers were pre-installed at /root/.cache/ms-playwright/). +Verification passed: pytest scripts/reskin/test_screenshot_game.py -v (2/2 passed). +Status: PASSED diff --git a/scripts/reskin/screenshot_game.py b/scripts/reskin/screenshot_game.py new file mode 100644 index 0000000000..f45b5c548f --- /dev/null +++ b/scripts/reskin/screenshot_game.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Take a screenshot of the OpenRCT2 web game using Playwright. + +Starts a local COOP/COEP server, launches headless Chromium, waits for +the game canvas to appear and loading to finish, then captures a screenshot. + +Usage: + python3 screenshot_game.py --serve-dir build/www --output screenshot.png + python3 screenshot_game.py --serve-dir build/www --output screenshot.png --port 9000 --wait-seconds 15 +""" + +import argparse +import os +import sys +import threading +import time +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer + + +class COOPCOEPHandler(SimpleHTTPRequestHandler): + """HTTP handler that adds Cross-Origin Isolation headers.""" + + def end_headers(self): + self.send_header("Cross-Origin-Opener-Policy", "same-origin") + self.send_header("Cross-Origin-Embedder-Policy", "require-corp") + self.send_header("Cross-Origin-Resource-Policy", "cross-origin") + super().end_headers() + + def log_message(self, format, *args): + """Suppress request logging to keep output clean.""" + pass + + +def start_server(directory, host="127.0.0.1", port=8000): + """Start a COOP/COEP HTTP server in a background thread. + + Returns (server, thread) so the caller can shut it down. + """ + handler = partial(COOPCOEPHandler, directory=directory) + server = ThreadingHTTPServer((host, port), handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + return server, thread + + +def take_screenshot(port=8000, output_path="screenshot.png", wait_seconds=10): + """Launch headless Chromium and screenshot the OpenRCT2 game. + + Requires playwright to be installed with Chromium browser. + """ + from playwright.sync_api import sync_playwright + + with sync_playwright() as p: + browser = p.chromium.launch( + headless=True, + args=["--enable-features=SharedArrayBuffer"], + ) + page = browser.new_page(viewport={"width": 1280, "height": 720}) + + url = f"http://127.0.0.1:{port}/index.html" + page.goto(url, wait_until="domcontentloaded") + + # Wait for the canvas to become visible + page.wait_for_selector( + "canvas#canvas", + state="visible", + timeout=wait_seconds * 1000, + ) + + # Wait for loading to finish — #loadingWebassembly is removed when done + try: + page.wait_for_selector( + "#loadingWebassembly", + state="detached", + timeout=wait_seconds * 1000, + ) + except Exception: + # If the element never existed or was already gone, that's fine + pass + + # Give the game a moment to render a frame + time.sleep(2) + + page.screenshot(path=output_path, full_page=False) + print(f"Screenshot saved to {output_path}") + + browser.close() + + +def main(): + parser = argparse.ArgumentParser( + description="Take a screenshot of the OpenRCT2 web game" + ) + parser.add_argument( + "--serve-dir", required=True, + help="Directory containing the built wasm output (index.html etc.)" + ) + parser.add_argument( + "--output", required=True, + help="Output path for the screenshot PNG" + ) + parser.add_argument( + "--port", type=int, default=8000, + help="Port for the local server (default: 8000)" + ) + parser.add_argument( + "--wait-seconds", type=int, default=10, + help="Max seconds to wait for game to load (default: 10)" + ) + args = parser.parse_args() + + # Validate serve dir exists + if not os.path.isdir(args.serve_dir): + print(f"ERROR: serve directory does not exist: {args.serve_dir}") + sys.exit(1) + + # Start server + server, thread = start_server(args.serve_dir, port=args.port) + print(f"Server started on http://127.0.0.1:{args.port}") + + try: + take_screenshot( + port=args.port, + output_path=args.output, + wait_seconds=args.wait_seconds, + ) + finally: + server.shutdown() + print("Server stopped.") + + +if __name__ == "__main__": + main() diff --git a/scripts/reskin/test_screenshot_game.py b/scripts/reskin/test_screenshot_game.py new file mode 100644 index 0000000000..b3fd965733 --- /dev/null +++ b/scripts/reskin/test_screenshot_game.py @@ -0,0 +1,53 @@ +"""Tests for screenshot_game.py (server and error handling only). + +Does NOT test the full Playwright flow — that requires a wasm build. +""" + +import os +import sys +import tempfile +import time +import urllib.request + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from screenshot_game import start_server + + +def test_server_starts_and_stops(): + """Verify the COOP/COEP server can start, serve, and stop cleanly.""" + with tempfile.TemporaryDirectory() as d: + # Create a minimal index.html to serve + with open(os.path.join(d, "index.html"), "w") as f: + f.write("test") + + server, thread = start_server(d, host="127.0.0.1", port=18765) + try: + # Give server a moment to start + time.sleep(0.2) + + # Fetch the page + resp = urllib.request.urlopen("http://127.0.0.1:18765/index.html") + body = resp.read().decode() + assert "test" in body + + # Verify COOP/COEP headers + coop = resp.headers.get("Cross-Origin-Opener-Policy") + coep = resp.headers.get("Cross-Origin-Embedder-Policy") + assert coop == "same-origin" + assert coep == "require-corp" + finally: + server.shutdown() + + +def test_missing_serve_dir(): + """Verify graceful error when serve directory doesn't exist.""" + import subprocess + result = subprocess.run( + [sys.executable, os.path.join(os.path.dirname(__file__), "screenshot_game.py"), + "--serve-dir", "/nonexistent/path/abc123", + "--output", "/tmp/test.png"], + capture_output=True, text=True, + ) + assert result.returncode == 1 + assert "does not exist" in result.stderr or "does not exist" in result.stdout