summaryrefslogtreecommitdiff
path: root/test/gpu_snake.py
blob: 430cabe97f51508ab429571d0001861ef47f0bb7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env python3
"""GPU snake pixels and frame timings in a private GUI session.

python3 test/gpu_snake.py BINARY ADDON OUTPUT [--text] [--crt]
The output keeps pixels, timings, and logs; no installed session is touched.
"""
import argparse
import json
import os
from pathlib import Path
import statistics
import subprocess
import time
from ninep import Client

def wait(check, timeout=15):
    until = time.monotonic() + timeout
    while time.monotonic() < until:
        value = check()
        if value:
            return value
        time.sleep(0.02)
    raise TimeoutError('GUI did not reach the expected state')

def run(binary, addon, root, text=False, crt=False):
    root.mkdir(parents=True, exist_ok=True, mode=0o700)
    root.chmod(0o700)
    config = root / 'config/pardes'
    config.mkdir(parents=True, exist_ok=True)
    (config / 'init').write_text('Shell /bin/sh\nTheme orchard\n')
    fixture = root / 'fixture.txt'
    fixture.write_text(''.join((f'line {i:05d}: a reproducible scrolling fixture\n' for i in range(10000))))
    demo = root / 'demo.txt'
    if text:
        demo.write_text('500 phase scroll\n500 120x16 wheel 1\n2600 120x16 wheel -1\n4800 end\n')
    else:
        demo.write_text(f'100 exec Addon load {addon}\n200 exec SnakeShader\n500 phase snake\n500 180x16 key r\n3600 end\n')
    env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_')}
    env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), PARDES_TEST='1', PARDES_TEST_CAPTURE_DIR=str(root), PARDES_TEST_COLS='100', PARDES_TEST_ROWS='30', SDL_VIDEO_DRIVER='offscreen', PARDES_FRAMES=str(root / 'frames.tsv'), PARDES_FRAMES_DEMO=str(demo))
    with (root / 'stderr.log').open('w') as log:
        child = subprocess.Popen([str(binary), '--9p=gpu', str(fixture)], env=env, cwd=root, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=log, start_new_session=True)
        try:
            socket = root / '9p/pardes/gpu'
            wait(lambda: socket.exists() or child.poll() is not None)
            if child.poll() is not None:
                raise AssertionError((child.returncode, (root / 'stderr.log').read_text()))
            with Client(socket) as client:
                wait(lambda: (root / 'latest.ppm').exists())
                if not text:
                    wait(lambda: b'snake_shader' in client.read('/index'))
                    time.sleep(0.4)
                    (root / 'snake.ppm').write_bytes((root / 'latest.ppm').read_bytes())
                    (root / 'index.txt').write_bytes(client.read('/index'))
                child.wait(timeout=20)
            assert child.returncode == 0, (child.returncode, (root / 'stderr.log').read_text())
        finally:
            if child.poll() is None:
                child.terminate()
                child.wait(timeout=10)
            child.stdin.close()
    rows = []
    for line in (root / 'frames.tsv').read_text().splitlines():
        if not line or line.startswith('#'):
            continue
        values = list(map(float, line.split()))
        if values[0] >= 500:
            rows.append(values)
    assert len(rows) >= 20, len(rows)
    work = sorted((sum(row[1:4]) for row in rows))
    result = {'frames': len(rows), 'median_work_us': statistics.median(work), 'p95_work_us': work[int(len(work) * 0.95)], 'max_work_us': max(work), 'over_16ms': sum((v > 16667 for v in work))}
    if not text:
        from PIL import Image
        im = Image.open(root / 'snake.ppm').convert('RGB')
        green = sum((g > 90 and g > r * 1.7 and (g > b * 1.2) for r, g, b in im.get_flattened_data()))
        orange = sum((r > 110 and r > g * 1.5 and (g > b * 1.5) for r, g, b in im.get_flattened_data()))
        assert green > 300 and orange > 50, (green, orange)
        result.update(green_pixels=green, orange_pixels=orange)
        if crt:
            pixels = list(im.get_flattened_data())
            triads = scanlines = 0
            for y in range(im.height // 2, im.height - 4):
                for x in range(im.width - 3):
                    at = y * im.width + x
                    r, g, b = pixels[at:at + 3]
                    if min(r + g + b) < 8:
                        continue
                    if r[0] > g[0] * 1.8 and g[1] > r[1] * 1.8 and b[2] > g[2] * 1.8:
                        triads += 1
                        rows = [pixels[at + 1 + dy * im.width][1] for dy in range(4)]
                        scanlines += max(rows) > min(rows) * 1.3
            assert triads > 100 and scanlines > 100, (triads, scanlines)
            result.update(rgb_triads=triads, scanline_patches=scanlines)
    (root / 'result.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps(result), flush=True)
if __name__ == '__main__':
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('binary', type=Path)
    p.add_argument('addon', type=Path)
    p.add_argument('output', type=Path)
    p.add_argument('--text', action='store_true')
    p.add_argument('--crt', action='store_true', help='also require the RGB triads and scanline modulation')
    a = p.parse_args()
    run(a.binary.resolve(), a.addon.resolve(), a.output.resolve(), a.text, a.crt)