diff --git a/README.md b/README.md index 352db07..0469ad9 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,7 @@ What was really run: see [Status](#status) (a real install into a scratch prefix | Play: a loading screen, then "now playing", and the launcher back when the game closes | **Working on X11; not yet tried on KDE Wayland or with a real Steam game** | Run for real in a private X server: Play on a game Summit starts itself put the loading screen up, then "now playing"; keys pressed in the launcher meanwhile changed nothing; Stop the game ended it; Esc took the launcher back with the game still running; when the game closed the launcher was back with the session counted. A Steam-style start (a stand-in `steam` command that hands the game off and returns, the game's processes marked as Steam marks them) showed Starting until the game's process appeared and the launcher was back about 3 s after it was gone. Not checked: a real Steam, Lutris or Heroic game, a real controller, and bringing the launcher's window to the front through KWin when the game ends. | | Steam, Lutris, Heroic games started from the launcher | **Experimental** | Command lines are built and unit tested; no Steam, Lutris or Heroic on the test machines. Heroic (new): Epic and GOG games start through `xdg-open heroic://launch?appName=..&runner=..` (the format in Heroic's source), and the Flatpak Heroic's games are now found too. No Enhance for Lutris and Heroic games. Folders found on disk are not started directly: their button is **ADD** (see the Add a game row). | | Compare settings live (C), anti-aliasing (`--aa`) | **Experimental** | New. Run in the engine's own window on the GPU test machine (RTX 3090 shared with another job, **software OpenGL** for the display) on recorded Voidrunner footage, started with `--compare`: four anti-aliasing strips, frame generation Off against 2x (30 and 61 fps measured), and the upscaler strips fullscreen (RTX VSR shown as unavailable, with why); the overlay's Compare tab was opened with injected keys and seen. Anti-aliasing measured there at 720p, GPU, steady state: FXAA 0.53, SMAA-style 0.69, CAS 0.33 ms a frame on average. Upscaler and look times there are software OpenGL's and mean nothing. **Not run**: a real game (over a game, C stays the game's key), RTX VSR in a strip, the divider drag, Compare in clips, a GPU-rendered display, Windows. | +| Compare: Same area (pick a cell, zoom 1x to 8x, free box, inset map), Freeze, Flip, labels at the bottom, `--compare-area`; FXAA/CAS as an OpenGL pass | **Experimental** | New. Seen live in the engine's window on the GPU test machine (software OpenGL display) on recorded Voidrunner footage, keys and mouse injected: the picker with 4 numbered cells, the arrows and Enter picking cell 4, the quarter shown four times with the inset map, the wheel zooming to 3x and 4x, a drag making a free box, Space freezing (marked FROZEN), holding and letting go of V (A: Off / B: SMAA-style), and the overlay's Compare tab with the Area row and its map, fitting a 1280 px window. Upscaler cells as still frames (`compare_shot.py`, the window's FSR shaders). GLSL FXAA 0.07 ms and CAS 0.02 ms at 1080p on the RTX 3090 (headless EGL bench) against about 1 ms for the torch filters. **Not run**: over a real game (the overlay rows are the way there, untested), the overlay's map clicked with a real mouse, the GLSL pass in a live window on a graphics card (the test display is llvmpipe, where torch keeps doing it), Flip and Freeze for the upscaler live. | | RTX Video Super Resolution (`rtx-vsr`) | **Experimental** | Wired to the engine, not tested. | | 90/120 Hz output, choosing a monitor by name | **Experimental** | Wired, one virtual display only. | | Consoles in the library: PlayStation Remote Play (chiaki-ng with SmoovPlay's frame tap) and capture cards | **Tested** / **Experimental** | New: **+ Add a game or console** opens an in-app chooser: a game on this PC (the file dialog, as before), a capture card (the V4L2 devices, cards before webcams) or PlayStation Remote Play (the consoles linked in chiaki-ng, each one's state from a live network search). The pick becomes a library entry with its own page, profile, Enhance toggle and tracked time. Play on Remote Play finds the console by name, wakes it from rest mode and runs chiaki-ng; with Enhance the engine starts first and chiaki-ng gets `CHIAKI_FRAMETAP=1` (see [packaging/chiaki-ng](packaging/chiaki-ng/README.md), which also has the patch and the PKGBUILD; `install.sh --with-remote-play` builds it). A capture card plays through the engine. **Checked on the owner's desktop**: `summit console list` read two consoles linked in chiaki-ng, found one of them in rest mode on the network (at a different address than chiaki-ng had saved), found the Live Gamer MINI and a webcam, and saw the frame tap in the installed `chiaki`. Unit tests cover chiaki-ng's settings file, the discovery and wake-up packets, the stream command and the launch plans. **Not run**: a stream started from Summit, the wake-up, a capture card session. | @@ -292,6 +293,28 @@ python engine/devtools/compare_shot.py clip.mp4 --frame 150 --compare scaler:off More screenshots and the numbers: [docs/agent-reports/compare.md](docs/agent-reports/compare.md). +### Same area, zoom, Freeze and Flip + +

+ The engine's window: the bottom-right quarter of the scene shown four times, Off, FXAA, SMAA-style and CAS sharpen, each labelled with its cost and 1x, with a small map of the whole picture in the corner marking the quarter +

+ +**Same area** (key **A**, or Layout: Same area on the Compare tab) cuts the picture into one cell per strip (2: halves, 3: thirds, 4: a 2x2). Pick a cell (click it, or the arrows and Enter, or 1 to 4; the cells are outlined and numbered while you pick) and every cell shows **that** area of the scene, each with its own choice, in step, with the labels and timings as before. With 4 strips the picked quarter is shown four times, pixel for pixel. + +- **Zoom** (mouse wheel, + and -, or the Zoom row): 1x to 8x, by whole pixels (nearest neighbour, never a smoothing filter); the labels say the zoom. Drag on the picture to move the area (a **free box**; the cells are snap positions), or click the small map in the corner, which shows where the area is in the whole picture. A click without a drag, or Enter, goes back to picking; Esc leaves Same area. +- **Freeze** (**Space**): holds one game frame so anti-aliasing, the upscaler or the look can be studied on a still; marked FROZEN on screen. Frame generation can't be frozen (its strips differ only in motion), and says so. +- **Flip** (hold **V**, two strips): the whole picture with strip A while held, B when let go; Esc goes back to the split. +- **Labels at** the top or the bottom (when the game's HUD is at the top). +- Over a game (window capture) these keys are the game's: every Compare action is also on the overlay's Compare tab, including the area (Pick, 1 to 4, Free, and a map of the picture to click). + +```sh +python engine/run.py clip.mp4 --display --compare aa:off,fxaa,smaa,cas --compare-area 4 # a quarter, x4 +python engine/run.py clip.mp4 --display --compare scaler:off,bilinear,fsr --compare-area 0.4,0.3,0.1,0.1 # a free box, zoomed +python engine/devtools/compare_shot.py clip.mp4 --compare aa:off,fxaa,smaa,cas --compare-area 2 --out shot.png +``` + +The Anti-aliasing setting's FXAA and CAS now run as an OpenGL pass in the video window when it draws on a graphics card: measured on the test machine's RTX 3090 at 1080p (headless EGL, `devtools/aa_gl_bench.py`), 0.07 ms (FXAA) and 0.02 ms (CAS) against about 1 ms each for the torch filters. SMAA-style, and the anti-aliasing comparison itself, stay on torch. Screenshots and details: [docs/agent-reports/compare2.md](docs/agent-reports/compare2.md). + ## Statistics: overlay, summaries and benchmarks

diff --git a/docs/agent-reports/compare2.md b/docs/agent-reports/compare2.md new file mode 100644 index 0000000..8a7acee --- /dev/null +++ b/docs/agent-reports/compare2.md @@ -0,0 +1,172 @@ +# Compare, second step: Same area, zoom, Freeze, Flip, the overlay, GLSL anti-aliasing + +Task: compare2 (branch `ap/compare2`). The owner asked for "a toggle when using the comparison feature so that you +can select a chunk of the screen and then you get the comparison showing the same chunk of the screen that you +selected", e.g. with four settings: pick one of four sections, then see that section x4. + +## What changed + +**`engine/framegen/compare.py`** +- Round 2's "2x2, same crop" layout (locked to the picture's middle) is generalised into **Same area** (the layout + value stays `grid`, so `--compare-layout grid` and the launcher keep working; its name is now "Same area"): + - one cell per strip: 2 halves, 3 thirds, 4 a 2x2 (`cells`, `grid_shape`, `cell_at`); + - picking (`compare_cell = "pick"`): each cell shows its own part, outlined and numbered, the highlighted one in + the accent, with a hint at the bottom; + - picked: every cell shows **that** area (`Area`: centre, zoom, cell), enlarged by a whole number with nearest + neighbour (`compose` scales numpy and torch the same way; the GL path blits with `GL_NEAREST`); a fixed cell at + 1x is exactly that cell, pixel for pixel; a zoomed area that doesn't fill its cell to the pixel is centred, the + margin black; + - a **free box** (`compare_cell = "free"`, centre in `Live.free`), kept inside the picture, snapping to a cell's + centre when within 4% (`snap`); + - the **inset map**: the first available strip's whole picture, shrunk, in a bottom corner (top corner when the + labels are at the bottom), with the area marked and a caption ("Area 4 · 1x", "Free box · 3x nearest"); + - every label says the zoom ("FXAA · 4x nearest"; 1x is pixel for pixel). +- `draws(plan, w, h)`: one list of (strip, where, which part) used by the pipeline (anti-aliasing and frame + generation strips), the window (upscaler and look strips) and `compare_shot.py`. +- **Freeze**: `Live.source_side` holds the frame it got when Freeze went on and uses it in place of every new one, so + the window's upscaler and look strips get the still too. Marked "FROZEN · one game frame held". Refused for frame + generation, with why (`FREEZE_WHY`). The game goes on underneath; clips get its real frames. +- **Flip** (2 strips): the whole picture with strip A or B; only the strip on screen is computed and timed. Labels + "A: Off" / "B: SMAA-style". More than 2 strips: refused with a message. +- **Labels at** top or bottom. +- `Live.key / press / move / release / wheel / map_click / area_view`: every key and mouse action by name, so the + window is a thin mapping and all of it is unit-tested. +- `allowed()`: an area cell past the number of strips, Flip with more than 2, Freeze for frame generation are greyed + out in the overlay. +- `area_settings()` for `--compare-area`. +- Timings are no longer reset by view-only changes (layout, area, zoom, freeze, flip, labels). + +**`engine/framegen/settings.py`** (small local additions in the Compare tab): `compare_cell` (Area: Pick, 1-4, +Free), `compare_zoom` (1, 2, 3, 4, 6, 8), `compare_split` (the 2-strip divider, so it can be set without a mouse), +`compare_freeze`, `compare_flip` (Split / All A / All B), all session-only; `compare_labels_at` (saved). New sub +heading "Labels". The Compare row's help names the new keys. + +**`engine/framegen/menu.py`** +- The Area row is a row of buttons (6 short choices are now buttons; checked that no other setting changes kind). +- While the Area row is highlighted the help card shows a **map of the picture**: the cells numbered, the picked one + lit, the area as a box. Clicking it picks the cell there (1x) or puts the box there (zoomed). Hooks: + `Menu.area_view` / `Menu.area_click`, set by the window. +- `render(..., max_w)`: the panel is made narrower (down to 560 px at 1x) when the picture is narrower than it, + never cut. See the 1280 px finding below. + +**`engine/framegen/io.py`** +- Keys in the video window: **A** Same area on/off, **Space** Freeze, **V** held = A / let go = B, and while Same + area is on: arrows (move the highlight while picking; nudge the box once picked), Enter (pick / back to picking), + 1-4, + and -, Esc (leave Flip, then Same area). +- Mouse: click a cell to pick, drag to pan the area (the scene follows the hand), click without a drag to go back + to picking, drag on the inset map to move the box there, the wheel zooms. +- Over a game the hint on the picture says to use the overlay (keys and clicks are the game's there). +- Upscaler and look cells: each variant drawn whole into the scratch framebuffer, then every draw for it blitted + (nearest; only the inset map is linear, as it is shrunk); the black margin of a zoomed cell is cleared with a + scissor. +- The overlay gets `max_w` = the picture's width less a margin. +- **Anti-aliasing as an OpenGL pass** (`framegen/aa_gl.py`, see below), and `_dev_shot`: with `SUMMIT_SHOT=` + set, a `.req` file makes the window write the frame it is about to show to `-.png`. Off + unless the variable is set; used for this task's live screenshots. + +**`engine/framegen/aa_gl.py`** (new): FXAA-style and CAS from `aa.py`, line for line in GLSL (the same thresholds, +search steps and formulas; luma from RGB with the same weights). The window runs the Anti-aliasing setting this way +when the window's OpenGL is a graphics card, or when there is no CUDA (then torch would fall back to numpy, far too +slow to play); `SUMMIT_AA_GL=1/0` forces it. `Live.window_aa` decides who applies it, so it is never applied twice: +the pipeline skips it when the window does it. SMAA-style stays torch (its edge runs use cumulative maxima along whole +rows, which one fragment pass can't do without SMAA's multi-pass lookup-texture design), and so does the +anti-aliasing **comparison** (its strips are composed at the game's size by the pipeline). HDR10: torch. + +**`engine/run.py`**: `--compare-area ` (fractions; the zoom is the biggest of 1, 2, 3, 4, 6, 8 that +still shows the whole box). + +**`engine/devtools/compare_shot.py`**: `--compare-area`, `--freeze`, `--flip a|b`, `--labels-at`; `--layout grid` +without an area draws the picker. + +**`engine/devtools/aa_gl_bench.py`** (new): both anti-aliasing paths on the same frame and card: GLSL with GL timer +queries (optionally headless on the NVIDIA card through EGL's device platform), torch with CUDA events and wall time, +and the GLSL output against `aa.py`'s numpy reference. + +**README**: "Compare settings live" gets a "Same area, zoom, Freeze and Flip" part with the live screenshot, the keys +and the command lines; a status row (Experimental). + +## Verified, and how + +- `cd engine && pytest tests -q` here: **238 passed, 3 skipped** (the 2 GLSL tests skip without a display, and the + existing skip). On the VM (`DISPLAY=:0`, llvmpipe), at commit 893cc9e: **240 passed**, the GLSL tests included + (GLSL FXAA and CAS within 1 of the numpy reference on the aliased test scene). +- New tests: `tests/test_compare_area.py` (30: cells, picking, the picked quarter shown four times pixel for pixel, + zoom as exact nearest-neighbour blocks, torch = numpy, centring and the black margin, the free box's clamp and + snap, the inset map, keys, mouse click / drag / missed-motion drag / wheel, the overlay map click, Freeze holding + one frame and refused for frame generation, Flip running only the strip on screen, labels at the bottom, the + picker's marks, timings kept across view changes, `--compare-area`, every action a row in the overlay, the Area + row's buttons and map, greyed cells, the overlay fitting 1280 px at 150% size) and `tests/test_aa_gl.py` (3). +- No Rust was touched. +- **Anti-aliasing cost, both ways** (`aa_gl_bench.py play30.mp4 --egl --runs 300`, frame 120 resized to + **1920x1080**, RTX 3090 shared with the Strata service, OpenGL on the card through EGL, torch compiled): + + | Filter | GLSL (GPU time) | torch (GPU time, CUDA events) | torch per call with its sync | + |---|---|---|---| + | FXAA | 0.072 ms (p99 0.074) | 0.988 ms (p99 1.044) | 1.000 ms (worst 1.212) | + | CAS | 0.022 ms (p99 0.023) | 1.026 ms (p99 3.341) | 1.077 ms (worst 3.839) | + | SMAA-style | (not in GLSL) | 1.329 ms (p99 1.409) | 1.351 ms | + + GLSL against numpy: CAS max difference 1; FXAA 0.008% of values off by more than 1 (max 38: pixels where a + threshold comparison falls the other way in float). The GLSL numbers are the pass alone; in the window it is the + pass plus a same-size copy back into the frame texture. **The GLSL pass has not run in a live window on a graphics + card**: the test VM's display is llvmpipe, where the window keeps torch (by the rule above). +- **Live, in the engine's own window** on the VM (llvmpipe display, CUDA for AA), on Voidrunner footage + (`play30.mp4` looped 16 times), 1280x720, keys and mouse injected with XTest only while my window had the focus + (`_NET_ACTIVE_WINDOW` checked before every input), frames captured with `SUMMIT_SHOT`: + - `--compare aa:off,fxaa,smaa,cas --compare-layout grid`: the picker; Right, Down moved the highlight to cell 4; + Enter picked it: the bottom-right quarter four times with the inset map, labels "· 1x" and live timings; the + wheel zoomed to 4x; Space froze it (FROZEN mark); Insert, Shift+Tab, Down x8 put the overlay on the Compare tab's + Area row with the map. + - `--compare-area 4`, wheel x2 (3x), a drag: a free box over the HUD at 3x ("Free box · 3x nearest" on the map), + and the overlay's Area row on "Free" with the box on its map. + - `--compare aa:off,smaa`: the split; V held: "A: Off" over the whole picture; let go: "B: SMAA-style". + - The anti-aliasing timings on the live labels (1.5 to 3 ms) include the CPU-GPU round trip these frames need on + llvmpipe, as in round 2. +- **Found and fixed while testing live**: a drag whose motion events the window never saw (only press and release) + counted as a click and went back to picking; `release()` now takes the release position. +- **The overlay "cut off at the right in a 1280 px window" (round 2)**: at 1280x720 the panel is 733 px wide and + placed at x 527, so it ends at 1260, inside the window. My own window captures showed the same black blocks at the + same place on the screen **without the overlay open**: they were KDE's notification popups (the VM keeps "Memory + Shortage Avoided" popups at the right of the screen) over the capture, not the layout. The overlay screenshots + taken from the engine's own frame (`SUMMIT_SHOT`) show the whole panel. `max_w` was added anyway, for narrower + windows and larger overlay sizes (tested: 150% in 1280x720 fits). + +## Screenshots (`docs/media/compare2/`) + +All from Voidrunner footage (a recording of the real game, `play30.mp4`). "Live" = the engine's real window, the +frame it was about to show, written by the engine (`SUMMIT_SHOT`); "still" = `devtools/compare_shot.py`, a headless +render with the same compose and label code. + +| File | What it is | +|---|---| +| `live-picker-4-cells.png` | Live: Same area picker, 4 cells outlined and numbered, cell 1 highlighted, the hint at the bottom. | +| `live-picker-cell4-selected.png` | Live: after Right, Down: cell 4 highlighted. | +| `live-aa-quarter-x4.png` | Live: Enter: the bottom-right quarter shown four times (Off, FXAA, SMAA-style, CAS sharpen), 1x, timings, the inset map. | +| `live-aa-quarter-zoom-4x.png` | Live: the same quarter after three wheel steps: 4x nearest. | +| `live-aa-free-box-3x.png` | Live: a free box dragged over the HUD at 3x, "Free box · 3x nearest" over the inset map. | +| `live-frozen.png` | Live: Space pressed: "FROZEN · one game frame held" (taken while picking: the drag of that run had ended as a click, the bug fixed above). | +| `live-overlay-area-picking.png` | Live: the overlay's Compare tab, Area row on Pick, the map in the help card, the panel whole in a 1280 px window. | +| `live-overlay-area-free.png` | Live: the overlay's Area row on Free, the box on the map. | +| `live-flip-split.png`, `live-flip-a.png`, `live-flip-b.png` | Live: `aa:off,smaa` split; V held ("A: Off"); V let go ("B: SMAA-style"). | +| `still-scaler-quarter-x4.png` | Still: 640x360 frame to 1280x720, Off (nearest), Bilinear, FSR 1, FSR 1 Max with the window's FSR shaders (llvmpipe), cell 1 (the HUD) x4. Timings off (software OpenGL). | +| `still-scaler-free-box-4x.png` | Still: the same, a free box `0.02,0.03,0.12,0.12` at 4x nearest. | +| `still-aa-free-box-4x-labels-bottom.png` | Still: anti-aliasing on CUDA, free box `0.05,0.02,0.1,0.1` (4x: 5x isn't a zoom step), labels at the bottom, the map at the top; timings measured (20 runs). | + +## Not done, or not tested + +- **Not run over a real game.** The compare keys still don't reach the engine over a game (only the overlay key is + grabbed); everything is on the overlay's Compare tab instead, and that path was tested only in the engine's own + window (keys injected), not over a game. +- In the overlay the free box is placed with the mouse (the map); with the keyboard the overlay offers the cells and + the zoom, not nudging a free box (the video window's arrows do that). +- The overlay's map was clicked only in unit tests, not with a real or injected mouse. +- The GLSL anti-aliasing pass has not run in a live window on a GPU (see above); there is no GLSL variant **inside** + the anti-aliasing comparison, so the two paths can't be compared side by side live, only with `aa_gl_bench.py`. +- Upscaler and look Same area, Freeze and Flip live: only as stills and unit tests (the live sessions compared + anti-aliasing; the 1280x720 footage has nothing to upscale in a 1280x720 window). +- Frame generation in Same area is tested on frames only. +- Session-only settings (area, zoom, freeze, flip, divider) show in the settings file with their defaults, like + `compare` itself already did; their values aren't saved. +- On the shared VM: before I unlocked the session, one injected key reached the lock screen's password field + (cleared by `loginctl unlock-session`); my script raises and focuses only its own window, by title "Summit compare2 + test". diff --git a/docs/media/compare2/live-aa-free-box-3x.png b/docs/media/compare2/live-aa-free-box-3x.png new file mode 100644 index 0000000..f38682b Binary files /dev/null and b/docs/media/compare2/live-aa-free-box-3x.png differ diff --git a/docs/media/compare2/live-aa-quarter-x4.png b/docs/media/compare2/live-aa-quarter-x4.png new file mode 100644 index 0000000..a2debe8 Binary files /dev/null and b/docs/media/compare2/live-aa-quarter-x4.png differ diff --git a/docs/media/compare2/live-aa-quarter-zoom-4x.png b/docs/media/compare2/live-aa-quarter-zoom-4x.png new file mode 100644 index 0000000..0cb6a88 Binary files /dev/null and b/docs/media/compare2/live-aa-quarter-zoom-4x.png differ diff --git a/docs/media/compare2/live-flip-a.png b/docs/media/compare2/live-flip-a.png new file mode 100644 index 0000000..147c626 Binary files /dev/null and b/docs/media/compare2/live-flip-a.png differ diff --git a/docs/media/compare2/live-flip-b.png b/docs/media/compare2/live-flip-b.png new file mode 100644 index 0000000..e71844d Binary files /dev/null and b/docs/media/compare2/live-flip-b.png differ diff --git a/docs/media/compare2/live-flip-split.png b/docs/media/compare2/live-flip-split.png new file mode 100644 index 0000000..cf4465c Binary files /dev/null and b/docs/media/compare2/live-flip-split.png differ diff --git a/docs/media/compare2/live-frozen.png b/docs/media/compare2/live-frozen.png new file mode 100644 index 0000000..24b2947 Binary files /dev/null and b/docs/media/compare2/live-frozen.png differ diff --git a/docs/media/compare2/live-overlay-area-free.png b/docs/media/compare2/live-overlay-area-free.png new file mode 100644 index 0000000..f353980 Binary files /dev/null and b/docs/media/compare2/live-overlay-area-free.png differ diff --git a/docs/media/compare2/live-overlay-area-picking.png b/docs/media/compare2/live-overlay-area-picking.png new file mode 100644 index 0000000..1ad64c6 Binary files /dev/null and b/docs/media/compare2/live-overlay-area-picking.png differ diff --git a/docs/media/compare2/live-picker-4-cells.png b/docs/media/compare2/live-picker-4-cells.png new file mode 100644 index 0000000..99c2566 Binary files /dev/null and b/docs/media/compare2/live-picker-4-cells.png differ diff --git a/docs/media/compare2/live-picker-cell4-selected.png b/docs/media/compare2/live-picker-cell4-selected.png new file mode 100644 index 0000000..3ad633f Binary files /dev/null and b/docs/media/compare2/live-picker-cell4-selected.png differ diff --git a/docs/media/compare2/still-aa-free-box-4x-labels-bottom.png b/docs/media/compare2/still-aa-free-box-4x-labels-bottom.png new file mode 100644 index 0000000..83bbad5 Binary files /dev/null and b/docs/media/compare2/still-aa-free-box-4x-labels-bottom.png differ diff --git a/docs/media/compare2/still-scaler-free-box-4x.png b/docs/media/compare2/still-scaler-free-box-4x.png new file mode 100644 index 0000000..a4216c4 Binary files /dev/null and b/docs/media/compare2/still-scaler-free-box-4x.png differ diff --git a/docs/media/compare2/still-scaler-quarter-x4.png b/docs/media/compare2/still-scaler-quarter-x4.png new file mode 100644 index 0000000..22b65ed Binary files /dev/null and b/docs/media/compare2/still-scaler-quarter-x4.png differ diff --git a/engine/devtools/aa_gl_bench.py b/engine/devtools/aa_gl_bench.py new file mode 100644 index 0000000..0135987 --- /dev/null +++ b/engine/devtools/aa_gl_bench.py @@ -0,0 +1,165 @@ +"""Anti-aliasing cost, both ways: framegen/aa_gl.py's GLSL pass against framegen/aa.py's torch filters (compiled, on +CUDA), on the same frame and the same graphics card, and how far the GLSL output is from aa.py's numpy reference. + + python devtools/aa_gl_bench.py [VIDEO] [--size 1920x1080] [--runs 300] [--egl] + +--egl makes the OpenGL context on the NVIDIA card itself, headless (EGL's device platform), so the GLSL times are the +GPU's and not a software renderer's; without it a hidden GLFW window is used (whatever the display's OpenGL is, +llvmpipe on a VM: its times are the CPU's, and printed as such). + +GLSL: GPU time per pass from GL timer queries. torch: GPU time per filter from CUDA events, and the wall time of a +call with its synchronisation (what the pipeline pays), both after warm-up and compile. +""" +from __future__ import annotations + +import argparse +import os +import sys +import time +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + + +def egl_context(): + """A headless OpenGL 3.3+ context on the first EGL device (NVIDIA's), current on this thread.""" + os.environ["PYOPENGL_PLATFORM"] = "egl" + import ctypes + from OpenGL import EGL + from OpenGL.EGL.EXT.device_base import eglQueryDevicesEXT + from OpenGL.EGL.EXT.platform_base import eglGetPlatformDisplayEXT + from OpenGL.EGL.EXT.platform_device import EGL_PLATFORM_DEVICE_EXT + devices = (EGL.EGLDeviceEXT * 8)() + n = EGL.EGLint() + eglQueryDevicesEXT(8, devices, ctypes.byref(n)) + if n.value < 1: + raise RuntimeError("no EGL device") + dpy = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, devices[0], None) + major, minor = EGL.EGLint(), EGL.EGLint() + if not EGL.eglInitialize(dpy, ctypes.byref(major), ctypes.byref(minor)): + raise RuntimeError("eglInitialize failed") + attrs = (EGL.EGLint * 9)(EGL.EGL_SURFACE_TYPE, EGL.EGL_PBUFFER_BIT, EGL.EGL_RENDERABLE_TYPE, EGL.EGL_OPENGL_BIT, + EGL.EGL_RED_SIZE, 8, EGL.EGL_NONE, 0, 0) + cfg = EGL.EGLConfig() + count = EGL.EGLint() + EGL.eglChooseConfig(dpy, attrs, ctypes.byref(cfg), 1, ctypes.byref(count)) + if count.value < 1: + raise RuntimeError("no EGL config") + surf = EGL.eglCreatePbufferSurface(dpy, cfg, (EGL.EGLint * 5)(EGL.EGL_WIDTH, 16, EGL.EGL_HEIGHT, 16, + EGL.EGL_NONE)) + EGL.eglBindAPI(EGL.EGL_OPENGL_API) + ctx = EGL.eglCreateContext(dpy, cfg, EGL.EGL_NO_CONTEXT, (EGL.EGLint * 7)( + EGL.EGL_CONTEXT_MAJOR_VERSION, 3, EGL.EGL_CONTEXT_MINOR_VERSION, 3, + EGL.EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL.EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL.EGL_NONE)) + if not ctx or not EGL.eglMakeCurrent(dpy, surf, surf, ctx): + raise RuntimeError("no EGL OpenGL context") + + +def glfw_context(): + import glfw + if not glfw.init(): + raise RuntimeError("no display for OpenGL") + glfw.window_hint(glfw.VISIBLE, glfw.FALSE) + win = glfw.create_window(64, 64, "Summit aa bench", None, None) + if not win: + raise RuntimeError("no OpenGL context") + glfw.make_context_current(win) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("video", nargs="?") + ap.add_argument("--frame", type=int, default=120) + ap.add_argument("--size", default="1920x1080") + ap.add_argument("--runs", type=int, default=300) + ap.add_argument("--egl", action="store_true") + ap.add_argument("--no-torch", action="store_true") + a = ap.parse_args() + w, h = (int(v) for v in a.size.lower().split("x")) + import cv2 + if a.video: + cap = cv2.VideoCapture(a.video) + cap.set(cv2.CAP_PROP_POS_FRAMES, a.frame) + ok, frame = cap.read() + if not ok: + raise SystemExit(f"no frame {a.frame} in {a.video}") + else: + from compare_shot import pattern + frame = pattern(1280, 720) + frame = np.ascontiguousarray(cv2.resize(frame, (w, h), interpolation=cv2.INTER_LINEAR)) + + (egl_context if a.egl else glfw_context)() + from OpenGL import GL + from framegen import aa + from framegen.aa_gl import AaGl + renderer = GL.glGetString(GL.GL_RENDERER).decode(errors="replace") + print(f"[aa_gl_bench] {w}x{h}, OpenGL: {renderer}", flush=True) + + GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) + GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1) + + def tex(data=None): + t = GL.glGenTextures(1) + GL.glBindTexture(GL.GL_TEXTURE_2D, t) + for p in (GL.GL_TEXTURE_MIN_FILTER, GL.GL_TEXTURE_MAG_FILTER): + GL.glTexParameteri(GL.GL_TEXTURE_2D, p, GL.GL_NEAREST) + GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE, data) + return t + + src = tex(frame) # row 0 of the image in texel row 0, as the window uploads it + dst = tex() + fbo = GL.glGenFramebuffers(1) + GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, fbo) + GL.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, dst, 0) + f = AaGl(GL) + q = int(np.ravel(GL.glGenQueries(1))[0]) + results = {} + for mode in ("fxaa", "cas"): + for _ in range(20): + f.draw(mode, src, fbo, w, h) + GL.glFinish() + ms = [] + for _ in range(a.runs): + GL.glBeginQuery(GL.GL_TIME_ELAPSED, q) + f.draw(mode, src, fbo, w, h) + GL.glEndQuery(GL.GL_TIME_ELAPSED) + ms.append(int(GL.glGetQueryObjectuiv(q, GL.GL_QUERY_RESULT)) / 1e6) # (32-bit ns: PyOpenGL's ui64v fails) + GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, fbo) + out = np.frombuffer(GL.glReadPixels(0, 0, w, h, GL.GL_BGR, GL.GL_UNSIGNED_BYTE), np.uint8).reshape(h, w, 3) + ref = aa.apply(frame, mode, gpu=False) + diff = np.abs(out.astype(int) - ref) + results[mode] = {"glsl": (float(np.mean(ms)), float(np.percentile(ms, 99)), float(np.max(ms)))} + print(f" GLSL {mode}: {np.mean(ms):.3f} ms average, {np.percentile(ms, 99):.3f} p99, {np.max(ms):.3f} worst " + f"(GPU time, {a.runs} runs); against aa.py's numpy: max diff {diff.max()}, " + f"{(diff > 1).mean() * 100:.3f}% of values off by more than 1", flush=True) + if not a.no_torch: + import torch + if not torch.cuda.is_available(): + print(" torch: no CUDA here, skipped") + return 0 + t = torch.from_numpy(frame).cuda() + for mode in ("fxaa", "smaa", "cas"): + fused = aa.settle(mode, t) + for _ in range(20): + aa.apply(t, mode) + torch.cuda.synchronize() + gpu, wall = [], [] + for _ in range(a.runs): + e0, e1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) + t0 = time.perf_counter() + e0.record() + aa.apply(t, mode) + e1.record() + torch.cuda.synchronize() + wall.append((time.perf_counter() - t0) * 1000) + gpu.append(e0.elapsed_time(e1)) + print(f" torch {mode} ({'compiled' if fused else 'op by op'}): {np.mean(gpu):.3f} ms GPU average, " + f"{np.percentile(gpu, 99):.3f} p99; {np.mean(wall):.3f} ms per call with its sync, " + f"{np.max(wall):.3f} worst", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/engine/devtools/compare_shot.py b/engine/devtools/compare_shot.py index 988704a..fa16954 100644 --- a/engine/devtools/compare_shot.py +++ b/engine/devtools/compare_shot.py @@ -20,6 +20,11 @@ Each comparison is drawn by the same code as in the video window where it can be holds frame N, as the live view does. A still can't show smoothness: --sequence K writes K output frames in a row (Off repeats, On moves), two to a row. Frame rates on these labels are the file's rate (and twice it), not measured. +--layout grid is Same area: without --compare-area it shows the picker (each cell as it is, outlined and numbered); +--compare-area 2 (a cell) or --compare-area X,Y,W,H (fractions of the picture: a free box, zoomed by whole pixels to +fill a cell) shows that area in every cell, with the inset map. --freeze marks the still as frozen (as the live +window does); --flip a|b shows one of two strips over the whole picture; --labels-at bottom. + --zoom X,Y,W,H[,K] also writes -zoom.png: that part of the picture (picture pixels), K times bigger (nearest neighbour, so pixels stay pixels). """ @@ -221,6 +226,11 @@ def main() -> int: ap.add_argument("--size", default=None, metavar="WxH", help="output picture size (upscaler: what it scales to)") ap.add_argument("--layout", default="columns", choices=C.LAYOUTS) ap.add_argument("--split", type=float, default=0.5, help="where the divider is, with 2 strips (0..1)") + ap.add_argument("--compare-area", default=None, metavar="CELL|X,Y,W,H", + help="Same area, picked: a cell number or x,y,w,h as fractions (implies --layout grid)") + ap.add_argument("--freeze", action="store_true", help="mark it frozen, as the live window does") + ap.add_argument("--flip", default="off", choices=("off", "a", "b"), help="2 strips: the whole picture with one") + ap.add_argument("--labels-at", default="top", choices=("top", "bottom")) ap.add_argument("--no-labels", action="store_true") ap.add_argument("--timings", action=argparse.BooleanOptionalAction, default=None, help="cost under each name (default: on, but off on software OpenGL)") @@ -284,8 +294,16 @@ def main() -> int: caps.multiplier = 2 caps.model = a.model values = dict(C.settings_for(a.compare), compare_layout=a.layout, compare_labels=not a.no_labels, - compare_timings=show_timings) - p = C.plan(values, caps, a.split) + compare_timings=show_timings, compare_freeze=a.freeze, compare_flip=a.flip, + compare_labels_at=a.labels_at) + free = (0.5, 0.5) + if a.compare_area: + try: + area, free = C.area_settings(a.compare_area, len(picks)) + except ValueError as e: + ap.error(str(e)) + values.update(area) + p = C.plan(values, caps, a.split, free) rates: dict = {} t0 = time.perf_counter() @@ -317,7 +335,7 @@ def main() -> int: if r >= 3 and s.variant != "off" and ms == ms: # (the first 3: warm-up) timings.add(C.timing_key("scaler", s.variant), ms) images.append(img) - picture = C.compose(images, C.rects(p.layout, p.n, out_w, out_h, p.split), + picture = C.compose(images, C.draws(p, out_w, out_h), np.zeros((out_h, out_w, 3), np.uint8)) elif dim == "look": if gl is not None: @@ -333,7 +351,7 @@ def main() -> int: if r >= 3 and s.variant == "on" and ms == ms: timings.add(C.timing_key("look", "on"), ms) images.append(img) - picture = C.compose(images, C.rects(p.layout, p.n, out_w, out_h, p.split), + picture = C.compose(images, C.draws(p, out_w, out_h), np.zeros((out_h, out_w, 3), np.uint8)) else: # framegen: the in-between frame of N and N+1 from framegen.interpolator import RifeInterpolator @@ -390,7 +408,7 @@ def main() -> int: texts = C.labels(p, timings, rates, caps) ui = max(0.5, out_h / 1080) - final = C.blend(picture, C.overlay_items(p, texts, out_w, out_h, ui)) + final = C.blend(picture, C.overlay_items(p, texts, out_w, out_h, ui, C.Live.HINT)) if a.title: c = U.Canvas(U.text_w(a.title, U.font(int(18 * ui), "semibold")) + int(28 * ui), int(34 * ui), U.BG, int(8 * ui), border=U.BORDER) diff --git a/engine/framegen/aa_gl.py b/engine/framegen/aa_gl.py new file mode 100644 index 0000000..24ee649 --- /dev/null +++ b/engine/framegen/aa_gl.py @@ -0,0 +1,133 @@ +"""Anti-aliasing as an OpenGL pass in the video window: FXAA-style and CAS (framegen/aa.py's own filters, line for +line in GLSL), so the Anti-aliasing setting costs a fragment shader pass at the game's size instead of a round of +torch ops (and works on any graphics card, where aa.py without CUDA falls back to numpy, far too slow to play). + +SMAA-style stays in aa.py (torch): its edge runs are measured with cumulative maxima along whole rows, which a +single fragment pass can't do without SMAA's multi-pass lookup-texture design. + +The source is a texture holding the picture with image row 0 in texel row 0 (as the window uploads frames), RGB in +its rgb; the result goes into a framebuffer of the same size, the same way up. Values match aa.py's numpy reference +to within one step of 255 (tests/test_aa_gl.py, where an OpenGL context can be made; devtools/aa_gl_bench.py +measures both paths). +""" +from __future__ import annotations + +from . import aa + +MODES = ("fxaa", "cas") + +_VS = """#version 330 +void main() { vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); } +""" + +_COMMON = """#version 330 +uniform sampler2D src; +out vec4 color; +ivec2 SZ; +vec3 C(int dx, int dy) { // the picture at (x + dx, y + dy) (image rows), held at the borders as aa.py's _Ops.sh + ivec2 p = clamp(ivec2(gl_FragCoord.xy) + ivec2(dx, dy), ivec2(0), SZ - 1); + return texelFetch(src, p, 0).rgb; +} +float Lat(int dx, int dy) { return dot(C(dx, dy), vec3(0.299, 0.587, 0.114)); } +""" + +_FXAA = _COMMON + """ +const float EDGE = %(edge)r, EDGE_MIN = %(edge_min)r, SUBPIX = %(subpix)r, GUESS = %(guess)r; +const int STEPS[%(n)d] = int[](%(steps)s); +bool is_h, first; +float half_at(int k) { // the luma half-way to the neighbour across the edge, k pixels along it + int o = first ? -1 : 1; + return is_h ? 0.5 * (Lat(k, 0) + Lat(k, o)) : 0.5 * (Lat(0, k) + Lat(o, k)); +} +void main() { + SZ = textureSize(src, 0); + vec3 c = C(0, 0); + float L = Lat(0, 0), N = Lat(0, -1), S = Lat(0, 1), W = Lat(-1, 0), E = Lat(1, 0); + float NW = Lat(-1, -1), NE = Lat(1, -1), SW = Lat(-1, 1), SE = Lat(1, 1); + float mx = max(max(max(N, S), max(W, E)), L), mn = min(min(min(N, S), min(W, E)), L); + float rng = mx - mn; + if (!(rng >= max(mx * EDGE, EDGE_MIN))) { color = vec4(c, 1.0); return; } + float avg = (2.0 * (N + S + W + E) + NW + NE + SW + SE) / 12.0; + float sub = clamp(abs(avg - L) / max(rng, 1e-6), 0.0, 1.0); + sub = (-2.0 * sub + 3.0) * sub * sub; + sub = sub * sub * SUBPIX; + float horz = abs(N + S - 2.0 * L) * 2.0 + abs(NE + SE - 2.0 * E) + abs(NW + SW - 2.0 * W); + float vert = abs(W + E - 2.0 * L) * 2.0 + abs(NW + NE - 2.0 * N) + abs(SW + SE - 2.0 * S); + is_h = horz >= vert; + float l1 = is_h ? N : W, l2 = is_h ? S : E; + float g1 = abs(l1 - L), g2 = abs(l2 - L); + first = g1 >= g2; + float nb = first ? l1 : l2; + float grad = max(g1, g2) * 0.25, local = 0.5 * (L + nb); + float dist[2], delta[2]; + for (int s = 0; s < 2; s++) { + int sign = s == 0 ? -1 : 1; + dist[s] = GUESS; + delta[s] = half_at(sign * STEPS[%(n)d - 1]) - local; + for (int i = 0; i < %(n)d; i++) { + float d = half_at(sign * STEPS[i]) - local; + if (abs(d) >= grad) { dist[s] = float(STEPS[i]); delta[s] = d; break; } + } + } + bool nearer_n = dist[0] < dist[1]; + float d_min = min(dist[0], dist[1]); + float end_delta = nearer_n ? delta[0] : delta[1]; + bool good = (end_delta < 0.0) != ((L - local) < 0.0); + float t = max(good ? 0.5 - d_min / (dist[0] + dist[1]) : 0.0, sub); + vec3 cn = is_h ? (first ? C(0, -1) : C(0, 1)) : (first ? C(-1, 0) : C(1, 0)); + color = vec4(c + (cn - c) * t, 1.0); +} +""" % {"edge": aa.FXAA_EDGE, "edge_min": aa.FXAA_EDGE_MIN, "subpix": aa.FXAA_SUBPIX, "guess": aa.FXAA_GUESS, + "n": len(aa.FXAA_STEPS), "steps": ", ".join(str(k) for k in aa.FXAA_STEPS)} + +_CAS = _COMMON + """ +uniform float peak; +void main() { + SZ = textureSize(src, 0); + vec3 c = C(0, 0), N = C(0, -1), S = C(0, 1), W = C(-1, 0), E = C(1, 0); + vec3 mn = min(min(min(N, S), min(W, E)), c), mx = max(max(max(N, S), max(W, E)), c); + vec3 amp = sqrt(clamp(min(mn, 1.0 - mx) / max(mx, vec3(1e-6)), 0.0, 1.0)); + vec3 w = amp * peak; + color = vec4(clamp((c + w * (N + S + W + E)) / (1.0 + 4.0 * w), 0.0, 1.0), 1.0); +} +""" + + +class AaGl: + """The GLSL filters in the current OpenGL context. draw(mode, src_tex, fbo, w, h): src_tex's w x h picture + filtered into fbo (its (0, 0, w, h)).""" + + MODES = MODES + + def __init__(self, GL) -> None: + from OpenGL.GL import shaders + self.GL = GL + self.vao = GL.glGenVertexArrays(1) + self.progs = {} + for mode, fs in (("fxaa", _FXAA), ("cas", _CAS)): + self.progs[mode] = shaders.compileProgram(shaders.compileShader(_VS, GL.GL_VERTEX_SHADER), + shaders.compileShader(fs, GL.GL_FRAGMENT_SHADER), + validate=False) + self._peak = GL.glGetUniformLocation(self.progs["cas"], "peak") + + def draw(self, mode: str, src_tex: int, fbo: int, w: int, h: int, sharpness: float = aa.CAS_SHARPNESS) -> None: + GL = self.GL + prog = self.progs[mode] + GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, fbo) + GL.glViewport(0, 0, w, h) + GL.glUseProgram(prog) + if mode == "cas": + GL.glUniform1f(self._peak, -1.0 / (8.0 - 3.0 * float(sharpness))) + GL.glUniform1i(GL.glGetUniformLocation(prog, "src"), 0) + GL.glActiveTexture(GL.GL_TEXTURE0) + GL.glBindTexture(GL.GL_TEXTURE_2D, src_tex) + GL.glBindVertexArray(self.vao) + GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3) + GL.glBindVertexArray(0) + GL.glUseProgram(0) + + def close(self) -> None: + GL = self.GL + for prog in self.progs.values(): + GL.glDeleteProgram(prog) + GL.glDeleteVertexArrays(1, [self.vao]) diff --git a/engine/framegen/compare.py b/engine/framegen/compare.py index 297d604..e76dcaa 100644 --- a/engine/framegen/compare.py +++ b/engine/framegen/compare.py @@ -54,7 +54,21 @@ DEFAULTS = {"aa": ("off", "fxaa", "smaa", "cas"), "scaler": ("off", "bilinear", "framegen": ("off", "on", "2x", "4x"), "look": ("off", "on", "off", "on")} MAX_STRIPS = {"aa": 4, "scaler": 4, "framegen": 4, "look": 2} # more would only repeat (Look: off and on) LAYOUTS = ("columns", "rows", "grid") -LAYOUT_NAMES = {"columns": "Side by side", "rows": "Stacked", "grid": "2x2, same crop"} +LAYOUT_NAMES = {"columns": "Side by side", "rows": "Stacked", "grid": "Same area"} +# "Same area" (layout "grid"): the picture is cut into one cell per strip (2: halves, 3: thirds, 4: 2x2); the player +# picks one ("pick": the cells are shown as they are, outlined and numbered), then every cell shows THAT area of the +# scene, each with its own variant, enlarged by a whole number (nearest neighbour: pixels stay pixels). "free": a box +# moved with the mouse or the keys, its centre in Live.free. compare_zoom: 1x (the area is a cell's size) to 8x. +CELLS = ("pick", "1", "2", "3", "4", "free") +CELL_NAMES = {"pick": "Pick", "1": "1", "2": "2", "3": "3", "4": "4", "free": "Free"} +ZOOMS = (1, 2, 3, 4, 6, 8) +FLIPS = ("off", "a", "b") # Flip (2 strips): the whole picture with strip 1 (A) or strip 2 (B) +FLIP_NAMES = {"off": "Split", "a": "All A", "b": "All B"} +LABEL_PLACES = ("top", "bottom") +SPLITS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) # the 2-strip divider, from the overlay (the mouse: any) +VIEW_KEYS = ("compare_layout", "compare_cell", "compare_zoom", "compare_freeze", "compare_flip", "compare_labels_at", + "compare_split", "compare_labels", "compare_timings", "compare_clips") # change the view, not the cost +SNAP = 0.04 # a free box this close (picture fractions) to a cell's centre snaps to that cell SOURCE_SIDE = ("aa", "framegen") # put together at the game's size by the pipeline; the others by the window WINDOW = 120 # frames the timings are taken over MODEL_NAMES = {"vfg": "NVIDIA VFG"} # others: RIFE @@ -104,6 +118,32 @@ def settings_for(spec: str) -> dict: return out +def area_settings(spec: str, n: int) -> tuple[dict, tuple[float, float]]: + """--compare-area: a cell number ("2": the second of the n cells, at 1x) or "x,y,w,h" as fractions of the picture + (a free box: the zoom is the biggest of ZOOMS that still shows all of it, at least 1x). Returns the settings it + sets (Same area on) and the free box's centre.""" + parts = [v.strip() for v in spec.split(",") if v.strip()] + if len(parts) == 1 and parts[0].isdigit(): + k = int(parts[0]) + if not 1 <= k <= n: + raise ValueError(f"--compare-area: cell {k}: there are {n} cells (1 to {n}, left to right, then down)") + return {"compare_layout": "grid", "compare_cell": str(k), "compare_zoom": 1}, cell_centre(n, k) + try: + x, y, w, h = (float(v) for v in parts) + except ValueError: + raise ValueError(f"--compare-area: {spec!r} is neither a cell number nor x,y,w,h as fractions") from None + if not (0 <= x < 1 and 0 <= y < 1 and 0 < w <= 1 and 0 < h <= 1 and x + w <= 1.0001 and y + h <= 1.0001): + raise ValueError(f"--compare-area: {spec!r}: x,y,w,h are fractions of the picture (0 to 1), inside it") + cols, rows = grid_shape(n) + fit = min((1 / cols) / w, (1 / rows) / h) + zoom = max([z for z in ZOOMS if z <= fit + 1e-6] or [1]) + cx, cy = clamp_centre(n, zoom, x + w / 2, y + h / 2) + k = snap(n, cx, cy) + if k: + return {"compare_layout": "grid", "compare_cell": str(k), "compare_zoom": zoom}, cell_centre(n, k) + return {"compare_layout": "grid", "compare_cell": "free", "compare_zoom": zoom}, (cx, cy) + + # ---- what can run here ------------------------------------------------------------------------------------------- @dataclass class Caps: @@ -184,14 +224,22 @@ class Plan: split: float = 0.5 # where the divider is, with 2 strips (0..1 across, or down) labels: bool = True timings: bool = True + area: "Area | None" = None # Same area: the part of the scene every cell shows (None: the picture's middle) + picking: bool = False # Same area, before an area is picked: the cells as they are, outlined and numbered + sel: int = 0 # the cell the arrow keys are on while picking (0-based) + flip: str = "off" # "a" / "b": the whole picture with strip 1 / strip 2 (2 strips only) + frozen: bool = False # one game frame held, so spatial variants can be studied on a still + labels_at: str = "top" @property def n(self) -> int: return len(self.strips) -def plan(values: dict, caps: Caps, split: float = 0.5) -> Plan | None: - """The comparison the settings ask for (None: Compare is off).""" +def plan(values: dict, caps: Caps, split: float = 0.5, free: tuple[float, float] = (0.5, 0.5), + sel: int = 0) -> Plan | None: + """The comparison the settings ask for (None: Compare is off). free: the free box's centre (Live.free); sel: the + picker's highlighted cell (Live.sel).""" if not values.get("compare"): return None dim = values.get("compare_dim", "aa") @@ -204,8 +252,42 @@ def plan(values: dict, caps: Caps, split: float = 0.5) -> Plan | None: if v not in VARIANTS[dim]: v = DEFAULTS[dim][i] strips.append(Strip(v, variant_name(dim, v, caps), why_not(dim, v, caps))) - return Plan(dim, tuple(strips), values.get("compare_layout", "columns"), split, - bool(values.get("compare_labels", True)), bool(values.get("compare_timings", True))) + layout = values.get("compare_layout", "columns") + layout = layout if layout in LAYOUTS else "columns" + area, picking = None, False + if layout == "grid": + area = area_of(values.get("compare_cell", "pick"), values.get("compare_zoom", 1), n, free) + picking = area is None + flip = values.get("compare_flip", "off") + flip = flip if flip in ("a", "b") and n == 2 else "off" + return Plan(dim, tuple(strips), layout, split, + bool(values.get("compare_labels", True)), bool(values.get("compare_timings", True)), + area, picking, max(0, min(sel, n - 1)), flip, + bool(values.get("compare_freeze")) and can_freeze(dim), + "bottom" if values.get("compare_labels_at") == "bottom" else "top") + + +def can_freeze(dim: str) -> bool: + """Frame generation can't be studied on a still: its strips differ only over time (a frozen frame is the same + frame in each).""" + return dim != "framegen" + + +FREEZE_WHY = "Frame generation can't be frozen: its strips differ only in motion, so a still shows the same frame in each" + + +def allowed(key: str, value, values: dict) -> bool: + """Whether a Compare choice can be picked now (the overlay greys out the others): an area cell past the number + of strips, Flip with more than 2 strips, Freeze for frame generation.""" + dim = values.get("compare_dim", "aa") + n = max(2, min(int(values.get("compare_strips", 2)), MAX_STRIPS.get(dim, 4))) + if key == "compare_cell" and value.isdigit(): + return int(value) <= n + if key == "compare_flip" and value != "off": + return n == 2 + if key == "compare_freeze" and value: + return can_freeze(dim) + return True def variant_name(dim: str, variant: str, caps: Caps | None = None) -> str: @@ -228,37 +310,169 @@ def _cuts(n: int, size: int, split: float) -> list[int]: return [round(size * i / n) for i in range(n + 1)] -def rects(layout: str, n: int, w: int, h: int, split: float = 0.5) -> list[tuple[Rect, Rect]]: +@dataclass(frozen=True) +class Area: + """Same area: the part of the scene every cell shows. cx, cy: its centre (fractions of the picture); zoom: how + many times it is enlarged (a whole number: each of its pixels becomes zoom x zoom); cell: 1..4 when it is one of + the fixed cells (at 1x exactly that cell), 0 for a free box.""" + cx: float = 0.5 + cy: float = 0.5 + zoom: int = 1 + cell: int = 0 + + +def grid_shape(n: int) -> tuple[int, int]: + """Columns and rows of the Same area cells: 2 halves, 3 thirds, 4 a 2x2.""" + return {2: (2, 1), 3: (3, 1)}.get(n, (2, 2)) + + +def cells(n: int, w: int, h: int) -> list[Rect]: + """The Same area cells, numbered left to right, then top to bottom.""" + cols, rows = grid_shape(n) + xs = [round(w * i / cols) for i in range(cols + 1)] + ys = [round(h * j / rows) for j in range(rows + 1)] + return [(xs[i], ys[j], xs[i + 1], ys[j + 1]) for j in range(rows) for i in range(cols)][:n] + + +def cell_at(n: int, fx: float, fy: float) -> int: + """The cell (1-based) holding the point (fx, fy), fractions of the picture.""" + cols, rows = grid_shape(n) + i = min(cols - 1, max(0, int(fx * cols))) + j = min(rows - 1, max(0, int(fy * rows))) + return min(n, j * cols + i + 1) + + +def cell_centre(n: int, k: int) -> tuple[float, float]: + cols, rows = grid_shape(n) + i, j = (k - 1) % cols, (k - 1) // cols + return (i + 0.5) / cols, (j + 0.5) / rows + + +def area_of(cell: str, zoom: int, n: int, free: tuple[float, float] = (0.5, 0.5)) -> Area | None: + """The area the settings ask for: a fixed cell ("1".."4", a cell past the number of strips: none), the free box + at `free`, or None ("pick": the player is picking).""" + zoom = int(zoom) if zoom in ZOOMS else 1 + if cell == "free": + return Area(free[0], free[1], zoom, 0) + if isinstance(cell, str) and cell.isdigit() and 1 <= int(cell) <= n: + return Area(*cell_centre(n, int(cell)), zoom, int(cell)) + return None + + +def snap(n: int, cx: float, cy: float) -> int: + """The cell whose centre (cx, cy) is close enough to snap to (1-based), or 0.""" + for k in range(1, n + 1): + x, y = cell_centre(n, k) + if abs(cx - x) <= SNAP and abs(cy - y) <= SNAP: + return k + return 0 + + +def area_size(n: int, w: int, h: int, zoom: int) -> tuple[int, int]: + """The area's size in picture pixels: the smallest cell's, divided by the zoom (whole pixels).""" + cols, rows = grid_shape(n) + return max(1, (w // cols) // zoom), max(1, (h // rows) // zoom) + + +def area_rect(a: Area, n: int, w: int, h: int) -> Rect: + """The part of a w x h picture the area covers, kept inside the picture. A fixed cell at 1x is exactly that + cell.""" + if a.cell and a.zoom == 1: + return cells(n, w, h)[a.cell - 1] + aw, ah = area_size(n, w, h, a.zoom) + x0 = min(w - aw, max(0, round(a.cx * w - aw / 2))) + y0 = min(h - ah, max(0, round(a.cy * h - ah / 2))) + return x0, y0, x0 + aw, y0 + ah + + +def clamp_centre(n: int, zoom: int, cx: float, cy: float) -> tuple[float, float]: + """A free box's centre, kept where the whole box stays inside the picture.""" + cols, rows = grid_shape(n) + hw, hh = 0.5 / cols / zoom, 0.5 / rows / zoom + return min(1 - hw, max(hw, cx)), min(1 - hh, max(hh, cy)) + + +def _fit(cell: Rect, src: Rect, zoom: int) -> Rect: + """Where `src`, enlarged `zoom` times (whole pixels), goes in `cell`: centred, never past it. At 1x a cell a + pixel bigger than the area (odd sizes) gets the area stretched by that pixel instead of a black line.""" + x0, y0, x1, y1 = cell + sw, sh = src[2] - src[0], src[3] - src[1] + if zoom == 1: + return cell + dw, dh = min(x1 - x0, sw * zoom), min(y1 - y0, sh * zoom) + ox, oy = x0 + ((x1 - x0) - dw) // 2, y0 + ((y1 - y0) - dh) // 2 + return ox, oy, ox + dw, oy + dh + + +def _cuts(n: int, size: int, split: float) -> list[int]: + if n == 2: + at = round(size * min(0.95, max(0.05, split))) + return [0, at, size] + return [round(size * i / n) for i in range(n + 1)] + + +def rects(layout: str, n: int, w: int, h: int, split: float = 0.5, area: Area | None = None, + picking: bool = False) -> list[tuple[Rect, Rect]]: """For each strip: (where it goes in the picture, which part of its variant's picture it shows). Side by side and - stacked strips show their own part of the scene (the same place on screen); the grid shows the same crop of the - picture's middle in each cell, pixel for pixel, for a close look.""" + stacked strips show their own part of the scene (the same place on screen). Same area ("grid"): each cell shows + the same area of the scene (`area`; None: the picture's middle, a cell's size), enlarged by its zoom; picking: + each cell its own part, as it is.""" if layout == "rows": ys = _cuts(n, h, split) return [((0, ys[i], w, ys[i + 1]),) * 2 for i in range(n)] if layout == "grid": - if n == 2: - cells = [(0, 0, w // 2, h), (w // 2, 0, w, h)] - else: - cells = [(0, 0, w // 2, h // 2), (w // 2, 0, w, h // 2), (0, h // 2, w // 2, h), (w // 2, h // 2, w, h)] - out = [] - for x0, y0, x1, y1 in cells[:n]: - cw, ch = x1 - x0, y1 - y0 - sx, sy = (w - cw) // 2, (h - ch) // 2 - out.append(((x0, y0, x1, y1), (sx, sy, sx + cw, sy + ch))) - return out + cs = cells(n, w, h) + if picking: + return [(c, c) for c in cs] + if area is None: # the middle of the picture, a cell's size + area = Area(0.5, 0.5, 1, 0) + src = area_rect(area, n, w, h) + return [(_fit(c, src, area.zoom), src) for c in cs] xs = _cuts(n, w, split) return [((xs[i], 0, xs[i + 1], h),) * 2 for i in range(n)] +def inset_rect(w: int, h: int, at: str = "top") -> Rect: + """The small map of the whole picture (Same area), in a bottom corner (labels at the top) or a top one.""" + iw = max(32, round(w * 0.2)) + ih = max(18, round(iw * h / w)) + m = max(6, round(h / 45)) + x0 = w - iw - m + y0 = h - ih - m if at == "top" else m + return x0, y0, x0 + iw, y0 + ih + + +def draws(p: Plan, w: int, h: int) -> list[tuple[int, Rect, Rect]]: + """What goes where for this plan, in order: (strip, where in the picture, which part of that strip's picture); + strip -1 is black. Flip: one strip over the whole picture. Same area, once picked: the cells, then the inset map + (the first available strip's whole picture, shrunk).""" + if p.flip in ("a", "b"): + full = (0, 0, w, h) + return [(0 if p.flip == "a" else 1, full, full)] + out = [(i, d, s) for i, (d, s) in enumerate(rects(p.layout, p.n, w, h, p.split, p.area, p.picking))] + if p.layout == "grid" and not p.picking: + # (a zoomed area that doesn't fill its cell to the pixel: the rest of the cell black, strip -1) + out = [(-1, c, c) for c, (_, d, _) in zip(cells(p.n, w, h), out) if d != c] + out + first = next((i for i, s in enumerate(p.strips) if not s.why), None) + if first is not None: + out.append((first, inset_rect(w, h, p.labels_at), (0, 0, w, h))) + return out + + +def shown(p: Plan) -> set[int]: + """The strips this plan draws (Flip: one), so the others aren't computed.""" + return {0 if p.flip == "a" else 1} if p.flip in ("a", "b") else set(range(p.n)) + + def dividers(layout: str, n: int, w: int, h: int, split: float = 0.5) -> list[Rect]: """The lines between the strips, as (x0, y0, x1, y1) of zero width or height.""" if layout == "rows": ys = _cuts(n, h, split) return [(0, y, w, y) for y in ys[1:-1]] if layout == "grid": - if n == 2: - return [(w // 2, 0, w // 2, h)] - return [(w // 2, 0, w // 2, h), (0, h // 2, w, h // 2)] + cols, rows = grid_shape(n) + out = [(round(w * i / cols), 0, round(w * i / cols), h) for i in range(1, cols)] + return out + [(0, round(h * j / rows), w, round(h * j / rows)) for j in range(1, rows)] xs = _cuts(n, w, split) return [(x, 0, x, h) for x in xs[1:-1]] @@ -271,25 +485,47 @@ def drag_split(layout: str, x: float, y: float, w: int, h: int) -> float: def near_divider(p: Plan, x: float, y: float, w: int, h: int, reach: float) -> bool: """Whether (x, y) is close enough to the one movable divider to grab it.""" - if p.n != 2 or p.layout == "grid": + if p.n != 2 or p.layout == "grid" or p.flip != "off": return False (x0, y0, x1, y1), = dividers(p.layout, 2, w, h, p.split) return abs((y - y0) if p.layout == "rows" else (x - x0)) <= reach -def compose(images, r: list[tuple[Rect, Rect]], out=None): - """One picture from the strips: strip i's part of images[i] (None: left black). numpy arrays or torch tensors - (HxWxC), all the same size; `out`, if given, is written into and returned (else a new one is made).""" +def _index(n_out: int, start: int, n_in: int): + """Nearest neighbour: for each of n_out output pixels, the input pixel (start + ...) it shows.""" + import numpy as np + return start + (np.arange(n_out) * n_in) // max(1, n_out) + + +def compose(images, r, out=None): + """One picture from the strips. r: rects() ((where, which part) per strip, images[i] for the i-th) or draws() + ((strip, where, which part)). A part of another size than where it goes is enlarged (or shrunk) by nearest + neighbour: no smoothing that would hide the difference. images[i] None: left black. numpy arrays or torch + tensors (HxWxC), all the same size; `out`, if given, is written into and returned (else a new one is made).""" if out is None: first = next((im for im in images if im is not None), None) if first is None: raise ValueError("compose: every strip is unavailable; pass `out` (a black picture) for the size") out = first.clone() if hasattr(first, "clone") else first.copy() - for im, ((dx0, dy0, dx1, dy1), (sx0, sy0, sx1, sy1)) in zip(images, r): + triples = [t if len(t) == 3 else (i, *t) for i, t in enumerate(r)] + for i, (dx0, dy0, dx1, dy1), (sx0, sy0, sx1, sy1) in triples: + if dx1 <= dx0 or dy1 <= dy0: + continue + im = images[i] if 0 <= i < len(images) else None if im is None: out[dy0:dy1, dx0:dx1] = 0 - else: + continue + if (dx1 - dx0, dy1 - dy0) == (sx1 - sx0, sy1 - sy0): out[dy0:dy1, dx0:dx1] = im[sy0:sy1, sx0:sx1] + else: + ys, xs = _index(dy1 - dy0, sy0, sy1 - sy0), _index(dx1 - dx0, sx0, sx1 - sx0) + if hasattr(im, "index_select"): + import torch + ys_t = torch.as_tensor(ys, device=im.device) + xs_t = torch.as_tensor(xs, device=im.device) + out[dy0:dy1, dx0:dx1] = im.index_select(0, ys_t).index_select(1, xs_t) + else: + out[dy0:dy1, dx0:dx1] = im[ys][:, xs] return out @@ -342,9 +578,19 @@ def labels(p: Plan, timings: Timings, rates: dict | None = None, caps: Caps | No out.append((s.name, line)) continue out.append((s.name, timings.text(timing_key(p.dim, s.variant)) if p.timings and s.variant != "off" else "")) + if p.flip in ("a", "b"): # Flip: which one is on screen + out = [(f"{'AB'[i]}: {t}", sub) for i, (t, sub) in enumerate(out)] + elif p.layout == "grid" and not p.picking: # Same area: how much it is enlarged, on every label + z = p.area.zoom if p.area is not None else 1 + out = [(f"{t} \u00b7 {zoom_name(z)}", sub) for t, sub in out] return out +def zoom_name(zoom: int) -> str: + """How a Same area cell is enlarged, in words for its label: 1x is pixel for pixel.""" + return "1x" if zoom == 1 else f"{zoom}x nearest" + + def strip_fps(variant: str, rates: dict, caps: Caps | None) -> float | None: """The measured frame rate a frame generation strip shows: the game's for Off, the window's for On, a share of it for a smaller multiplier.""" @@ -401,10 +647,10 @@ class FrameGenStrips: images.append(self._held[i]) continue images.append(frame) - if all(im is frame for im in images): + if all(im is frame for im in images) and (p.layout != "grid" or p.picking or p.flip != "off"): return frame self._out = _copy_into(self._out, frame) - return compose(images, rects(p.layout, p.n, w, h, p.split), self._out) + return compose(images, draws(p, w, h), self._out) # ---- anti-aliasing strips ---------------------------------------------------------------------------------------- @@ -421,8 +667,9 @@ def aa_strips(frame, p: Plan, timings: Timings, out=None, gpu: bool = True): from . import aa h, w = frame.shape[:2] images = [] - for s in p.strips: - if s.why: + on = shown(p) # (Flip: only the one on screen is run, and timed) + for i, s in enumerate(p.strips): + if s.why or i not in on: images.append(None) continue if s.variant == "off": @@ -434,21 +681,48 @@ def aa_strips(frame, p: Plan, timings: Timings, out=None, gpu: bool = True): _sync(im) timings.add(timing_key("aa", s.variant), (time.perf_counter() - t0) * 1000) images.append(im) - return compose(images, rects(p.layout, p.n, w, h, p.split), out) + return compose(images, draws(p, w, h), out) # ---- labels and dividers ----------------------------------------------------------------------------------------- -def overlay_items(p: Plan, texts: list[tuple[str, str]], w: int, h: int, ui: float = 1.0): - """The dividers and the labels over a w x h picture, as [(x, y, RGBA image)] (y down, the top-left corner of each - image), drawn with framegen/ui_draw.py so they are crisp at any size. Labels sit at the top of each strip: the - name, and under it the cost (or why it's unavailable).""" +def _outline(w: int, h: int, t: int, rgb, dark: bool = True): + """A hollow rectangle w x h, t pixels thick, in rgb, with a thin dark edge so it shows on any picture.""" + import numpy as np + img = np.zeros((max(1, h), max(1, w), 4), np.uint8) + e = 1 if dark else 0 + img[:, :, :3] = 0 + for sl in ((slice(0, t + 2 * e), slice(None)), (slice(h - t - 2 * e, h), slice(None)), + (slice(None), slice(0, t + 2 * e)), (slice(None), slice(w - t - 2 * e, w))): + img[sl[0], sl[1], 3] = 150 + for sl in ((slice(e, e + t), slice(e, w - e)), (slice(h - e - t, h - e), slice(e, w - e)), + (slice(e, h - e), slice(e, e + t)), (slice(e, h - e), slice(w - e - t, w - e))): + img[sl[0], sl[1], :3] = rgb + img[sl[0], sl[1], 3] = 255 + return img + + +def _pill(text: str, U, px, f, fg=None, bg=None): + """A rounded label with one line of text, as RGBA.""" + tw = U.text_w(text, f) + c = U.Canvas(tw + px(28), px(36), bg or U.BG, px(10), border=U.BORDER) + c.text(c.w // 2, c.h // 2, text, f, fg or U.TEXT, anchor="mm") + return c.rgba(0.86) + + +def overlay_items(p: Plan, texts: list[tuple[str, str]], w: int, h: int, ui: float = 1.0, hint: str = ""): + """The dividers, the labels and the rest of Compare's marks over a w x h picture, as [(x, y, RGBA image)] (y down, + the top-left corner of each image), drawn with framegen/ui_draw.py so they are crisp at any size. Labels sit at + the top (or bottom: labels_at) of each strip: the name, and under it the cost (or why it's unavailable). Same + area: while picking, each cell outlined and numbered (the highlighted one in the accent) and `hint` (how to + pick) at the bottom; once picked, the inset map's frame with the area marked on it and its zoom. Frozen: a mark + saying so. Flip: one label, for the strip on screen.""" import numpy as np from . import ui_draw as U items = [] px = lambda v: max(1, int(round(v * ui))) # noqa: E731 line = max(2, px(2)) - for x0, y0, x1, y1 in dividers(p.layout, p.n, w, h, p.split): + for x0, y0, x1, y1 in (dividers(p.layout, p.n, w, h, p.split) if p.flip == "off" else []): if x0 == x1: # a vertical line: light, with a dark edge on each side so it shows on any picture img = np.zeros((y1 - y0, line + 2, 4), np.uint8) img[:, :, 3] = 255 @@ -461,10 +735,48 @@ def overlay_items(p: Plan, texts: list[tuple[str, str]], w: int, h: int, ui: flo img[1:-1, :, :3] = (235, 238, 245) img[[0, -1], :, 3] = 140 items.append((x0, y0 - img.shape[0] // 2, img)) + grid = p.layout == "grid" and p.flip == "off" + if p.flip in ("a", "b"): + places = {0 if p.flip == "a" else 1: (0, 0, w, h)} + elif grid: + places = dict(enumerate(cells(p.n, w, h))) + else: + places = {i: d for i, (d, _) in enumerate(rects(p.layout, p.n, w, h, p.split))} + bottom = p.labels_at == "bottom" + if grid and p.picking: # the picker: each cell outlined and numbered + f_num = U.font(px(64), "bold") + for i, (x0, y0, x1, y1) in places.items(): + on = i == p.sel + items.append((x0, y0, _outline(x1 - x0, y1 - y0, px(5) if on else px(2), + U.ACCENT if on else (235, 238, 245)))) + c = U.Canvas(px(104), px(104), U.ACCENT if on else U.BG, px(52), border=None) + c.text(c.w // 2, c.h // 2, str(i + 1), f_num, U.ON_ACCENT if on else U.TEXT, anchor="mm") + items.append(((x0 + x1 - c.w) // 2, (y0 + y1 - c.h) // 2, c.rgba(0.9))) + if hint: + img = _pill(hint, U, px, U.font(px(17), "medium")) + items.append(((w - img.shape[1]) // 2, px(14) if bottom else h - img.shape[0] - px(14), img)) + elif grid: # the inset map: its frame, and where the area is in the whole picture + ix0, iy0, ix1, iy1 = inset_rect(w, h, p.labels_at) + items.append((ix0 - 2, iy0 - 2, _outline(ix1 - ix0 + 4, iy1 - iy0 + 4, 1, (235, 238, 245)))) + a = p.area if p.area is not None else Area() + ax0, ay0, ax1, ay1 = area_rect(a, p.n, w, h) + kx, ky = (ix1 - ix0) / w, (iy1 - iy0) / h + bx0, by0 = ix0 + int(ax0 * kx), iy0 + int(ay0 * ky) + bx1, by1 = max(bx0 + 4, ix0 + int(round(ax1 * kx))), max(by0 + 4, iy0 + int(round(ay1 * ky))) + items.append((bx0, by0, _outline(bx1 - bx0, by1 - by0, max(1, px(2)), U.ACCENT))) + what = f"Area {a.cell}" if a.cell else "Free box" + img = _pill(f"{what} \u00b7 {zoom_name(a.zoom)}", U, px, U.font(px(14), "medium")) + iy = iy0 - img.shape[0] - px(6) if not bottom else iy1 + px(6) + items.append((ix1 - img.shape[1], iy, img)) + if p.frozen: # clearly marked: the picture is a still + img = _pill("FROZEN \u00b7 one game frame held", U, px, U.font(px(17), "bold"), U.ON_ACCENT, U.ACCENT) + lift = px(48) if grid and p.picking and hint else 0 # (above the picker's hint) + items.append(((w - img.shape[1]) // 2, h - img.shape[0] - px(14) - lift if not bottom else px(14) + lift, img)) if not p.labels: return items f_title, f_sub = U.font(px(26), "semibold"), U.font(px(17), "medium") - for (title, sub), ((x0, y0, x1, y1), _) in zip(texts, rects(p.layout, p.n, w, h, p.split)): + for i, (x0, y0, x1, y1) in places.items(): + title, sub = texts[i] if i < len(texts) else ("", "") room = max(px(60), (x1 - x0) - px(16)) title = U.fit(title, f_title, room - px(24)) subs = U.wrap(sub, f_sub, room - px(24), max_lines=3) if sub else [] @@ -475,8 +787,11 @@ def overlay_items(p: Plan, texts: list[tuple[str, str]], w: int, h: int, ui: flo for k, s in enumerate(subs): c.text(bw // 2, px(44) + px(23) * k + px(6), s, f_sub, U.TEXT if "ms" in s or "fps" in s else U.DIM, anchor="mm") - # (below the stats' pill, when it is in a top corner) - items.append((x0 + ((x1 - x0) - bw) // 2, y0 + (px(54) if y0 == 0 else px(14)), c.rgba(0.82))) + if bottom: # (above the stats' bar or the game's own HUD, when they are at the bottom) + y = y1 - bh - (px(54) if y1 == h else px(14)) + else: # (below the stats' pill, when it is in a top corner) + y = y0 + (px(54) if y0 == 0 else px(14)) + items.append((x0 + ((x1 - x0) - bw) // 2, y, c.rgba(0.82))) return items @@ -503,24 +818,56 @@ class Live: """The comparison while playing, shared by the pipeline (anti-aliasing and frame generation strips, at the game's size: source_side) and the video window (upscaler and look strips, and the labels and dividers over all of them). caps(): what can run (Caps), asked each frame. split: where the 2-strip divider is (the mouse drags it; this - session only).""" + session only). free: the Same area free box's centre; sel: the picker's highlighted cell. + + The window's keys and mouse come here by name (key, press, move, release, wheel), and the overlay's area map + (map_click), so what they do is the same everywhere and needs no window to test. hint: how to pick an area, + shown while picking (the window sets it: over a game its keys are the game's).""" LABEL_EVERY = 0.5 # seconds between new numbers on the labels (redrawing them costs a texture upload) + HINT = "Pick the area: click a cell, or arrows and Enter (or 1-4) \u00b7 Esc leaves" def __init__(self, settings, caps=None) -> None: self.settings = settings self.caps = caps or (lambda: Caps()) self.timings = Timings() - self.split = 0.5 + self.split = float(getattr(settings, "compare_split", 0.5) or 0.5) + self.free = (0.5, 0.5) + self.sel = 0 + self.hint = self.HINT self.fg = FrameGenStrips() self.rates: dict = {} # {"game": fps, "shown": fps}, measured by the pipeline self.game60 = False # the pipeline found a 60 fps game: multipliers count from 60 self._texts: tuple = (0.0, None, []) # (when, the plan they were for, the texts) self._items: tuple = (None, []) # (what they were drawn for, the items) + self._still = None # Freeze: the game frame held + self.gl_aa: tuple = () # anti-aliasing modes the video window runs itself (framegen/aa_gl.py), not torch + self._drag = None # the mouse on a Same area picture: ("map",) or ("pan", x, y, centre, moved) + self._layout = self._value("compare_layout", "columns") + self._back = self._layout if self._layout != "grid" else "columns" # the layout Esc goes back to self._unwatch = settings.watch(self._changed) + def _value(self, key: str, default=None): + return self.settings.values().get(key, default) + + def _set(self, key: str, value) -> None: + if self._value(key) != value: + self.settings.set(key, value) + def _changed(self, key: str) -> None: - if key.startswith("compare") or key in ("hz", "interp", "model", "scaler", "fsr_sharpness", "look", "aa"): + if key == "compare_split": + self.split = float(self._value("compare_split", 0.5)) + if key == "compare_layout": + now = self._value("compare_layout") + if now == "grid" and self._layout != "grid": # Same area starts with picking the area + self._back = self._layout + self.sel = 0 + self._set("compare_cell", "pick") + self._layout = now + if key == "compare_dim" or key == "compare_strips": + self.sel = 0 + if (key.startswith("compare") and key not in VIEW_KEYS) or key in ( + "hz", "interp", "model", "scaler", "fsr_sharpness", "look", "aa"): self.timings.clear() self.fg.reset() self._texts = (0.0, None, []) @@ -528,8 +875,195 @@ class Live: def plan(self) -> Plan | None: if not self.settings.compare: return None - return plan(self.settings.values(), self.caps(), self.split) + return plan(self.settings.values(), self.caps(), self.split, self.free, self.sel) + # ---- Same area, Freeze and Flip: keys and mouse ------------------------------------------------------------ + def key(self, name: str): + """A Compare key by name: "area" (Same area on and off), "freeze", "flip_down" / "flip_up" (held / let go), + "up" / "down" / "left" / "right", "enter", "back" (Esc), "1".."4", "zoom_in" / "zoom_out". Returns a message + to show (str), True when the key was used, or None when it means nothing here (the window does its own).""" + p = self.plan() + if name == "area": + if p is None: + self.settings.set("compare", True) + self.settings.set("compare_layout", "grid") + return "Compare: Same area. Pick the area" + self.settings.set("compare_layout", self._back if p.layout == "grid" else "grid") + return True + if p is None: + return None + if name == "freeze": + if not can_freeze(p.dim): + return FREEZE_WHY + self.settings.set("compare_freeze", not self._value("compare_freeze")) + return True + if name == "flip_down": + if p.n != 2: + return "Flip compares two: set Strips to 2" + self._set("compare_flip", "a") + return True + if name == "flip_up": + if self._value("compare_flip") == "a": + self._set("compare_flip", "b") + return True + if name == "back": + if p.flip != "off": + self._set("compare_flip", "off") + return True + if p.layout == "grid": + self.settings.set("compare_layout", self._back) + return True + return None + if p.layout != "grid" or p.flip != "off": + return None + cols, rows = grid_shape(p.n) + if name.isdigit(): + if 1 <= int(name) <= p.n: + self._set("compare_cell", name) + return True + if name in ("zoom_in", "zoom_out"): + self.zoom(1 if name == "zoom_in" else -1) + return True + if p.picking: + i, j = p.sel % cols, p.sel // cols + if name in ("left", "right"): + i = (i + (1 if name == "right" else -1)) % cols + elif name in ("up", "down"): + j = (j + (1 if name == "down" else -1)) % rows + elif name == "enter": + self._set("compare_cell", str(p.sel + 1)) + return True + else: + return None + self.sel = min(p.n - 1, j * cols + i) + return True + if name == "enter": # back to picking + self.sel = (p.area.cell - 1) if p.area is not None and p.area.cell else self.sel + self._set("compare_cell", "pick") + return True + if name in ("left", "right", "up", "down"): # the box moves a quarter of its size + a = p.area or Area() + step_x, step_y = 0.25 / cols / a.zoom, 0.25 / rows / a.zoom + dx = {"left": -step_x, "right": step_x}.get(name, 0.0) + dy = {"up": -step_y, "down": step_y}.get(name, 0.0) + self.move_to(a.cx + dx, a.cy + dy, p) + return True + return None + + def zoom(self, delta: int) -> None: + """The Same area zoom one step in (1) or out (-1), 1x to 8x, around the area's centre.""" + z = self._value("compare_zoom", 1) + i = ZOOMS.index(z) if z in ZOOMS else 0 + self._set("compare_zoom", ZOOMS[max(0, min(len(ZOOMS) - 1, i + delta))]) + p = self.plan() + if p is not None and p.area is not None and not p.area.cell: + self.move_to(p.area.cx, p.area.cy, p) + + def move_to(self, cx: float, cy: float, p: Plan | None = None) -> None: + """The area's centre to (cx, cy) (fractions): a fixed cell when that close to one's centre, else the free + box, kept inside the picture.""" + p = p or self.plan() + if p is None: + return + z = self._value("compare_zoom", 1) + cx, cy = clamp_centre(p.n, z if z in ZOOMS else 1, cx, cy) + k = snap(p.n, cx, cy) + if k: + self._set("compare_cell", str(k)) + return + self.free = (cx, cy) + self._set("compare_cell", "free") + + def map_click(self, fx: float, fy: float) -> None: + """The overlay's area map clicked at (fx, fy) of the picture: at 1x that cell, zoomed in the box's centre + there.""" + p = self.plan() + if p is None: + return + if self._value("compare_zoom", 1) == 1: + self._set("compare_cell", str(cell_at(p.n, fx, fy))) + else: + self.move_to(fx, fy, p) + + def press(self, x: float, y: float, w: int, h: int) -> bool: + """The mouse pressed at (x, y) on a w x h picture. Picking: picks that cell. Picked: on the inset map the box + goes there (and follows a drag), elsewhere a drag pans the area and a click goes back to picking. False when + Same area isn't on (the press is someone else's).""" + p = self.plan() + if p is None or p.layout != "grid" or p.flip != "off" or w <= 0 or h <= 0: + return False + if p.picking: + self._set("compare_cell", str(cell_at(p.n, x / w, y / h))) + return True + ix0, iy0, ix1, iy1 = inset_rect(w, h, p.labels_at) + if ix0 <= x < ix1 and iy0 <= y < iy1: + self._drag = ("map",) + self.move(x, y, w, h) + return True + a = p.area or Area() + self._drag = ("pan", x, y, (a.cx, a.cy), False) + return True + + def move(self, x: float, y: float, w: int, h: int) -> bool: + d = self._drag + if d is None or w <= 0 or h <= 0: + return False + p = self.plan() + if p is None: + return False + if d[0] == "map": + ix0, iy0, ix1, iy1 = inset_rect(w, h, p.labels_at) + self.move_to((x - ix0) / max(1, ix1 - ix0), (y - iy0) / max(1, iy1 - iy0), p) + return True + _, x0, y0, (cx, cy), moved = d + if not moved and abs(x - x0) + abs(y - y0) < 6: + return True + self._drag = ("pan", x0, y0, (cx, cy), True) + z = p.area.zoom if p.area is not None else 1 + self.move_to(cx - (x - x0) / (z * w), cy - (y - y0) / (z * h), p) # the scene follows the hand + return True + + def release(self, x: float | None = None, y: float | None = None, w: int = 0, h: int = 0) -> bool: + """The mouse let go (at (x, y) of a w x h picture, if known: a drag whose moves weren't all seen still + counts as a drag).""" + if self._drag is not None and self._drag[0] == "pan" and x is not None: + self.move(x, y, w, h) + d, self._drag = self._drag, None + if d is None: + return False + if d[0] == "pan" and not d[4]: # a click, not a drag: back to picking + p = self.plan() + if p is not None and p.area is not None and p.area.cell: + self.sel = p.area.cell - 1 + self._set("compare_cell", "pick") + return True + + @property + def dragging(self) -> bool: + return self._drag is not None + + def wheel(self, dy: float) -> bool: + """The mouse wheel over a picked Same area: zoom in (up) or out.""" + p = self.plan() + if p is None or p.layout != "grid" or p.picking or p.flip != "off" or not dy: + return False + self.zoom(1 if dy > 0 else -1) + return True + + def area_view(self) -> dict | None: + """What the overlay's area map draws: the number of cells, the area picked (picture fractions) or None + while picking, and the zoom. None when Same area isn't on.""" + p = self.plan() + if p is None or p.layout != "grid": + return None + box = None + if p.area is not None: + x0, y0, x1, y1 = area_rect(p.area, p.n, 1600, 900) + box = (x0 / 1600, y0 / 900, x1 / 1600, y1 / 900) + return {"n": p.n, "box": box, "cell": p.area.cell if p.area else 0, "zoom": p.area.zoom if p.area else 1, + "sel": p.sel} + + # ---- drawing --------------------------------------------------------------------------------------------------- def texts(self, p: Plan) -> list[tuple[str, str]]: """The labels' text, new numbers at most every LABEL_EVERY seconds.""" now = time.perf_counter() @@ -542,19 +1076,26 @@ class Live: def items(self, p: Plan, w: int, h: int, ui: float): """overlay_items for this picture size, drawn again only when something on them changed.""" texts = self.texts(p) - key = (p, tuple(texts), w, h, round(ui, 3)) + key = (p, tuple(texts), w, h, round(ui, 3), self.hint) if self._items[0] != key: - self._items = (key, overlay_items(p, texts, w, h, ui)) + self._items = (key, overlay_items(p, texts, w, h, ui, self.hint)) return self._items[1] def source_side(self, frame, p: Plan | None, real, multiplier: int): """The picture the pipeline sends to the window: the anti-aliasing or frame generation strips put together (other comparisons and Compare off: the frame, with the Anti-aliasing setting applied). real: the game's own frame the timeline has reached (the frame itself when it is one; None: a generated frame after the last one - given).""" + given). Frozen: the frame held when Freeze went on, in place of every new one (the game goes on underneath: + clips still get its frames).""" from . import aa + if p is not None and p.frozen: + if self._still is None or tuple(self._still.shape) != tuple(frame.shape): + self._still = frame.clone() if hasattr(frame, "clone") else frame.copy() + frame = real = self._still + else: + self._still = None if p is None or p.dim not in SOURCE_SIDE: - return aa.apply(frame, self.settings.aa) + return frame if self.window_aa(p) else aa.apply(frame, self.settings.aa) h, w = frame.shape[:2] if p.dim == "aa": return aa_strips(frame, p, self.timings, None) @@ -562,6 +1103,13 @@ class Live: self.fg.real(aa.apply(real, self.settings.aa)) return self.fg.present(aa.apply(frame, self.settings.aa), p, multiplier, w, h) + def window_aa(self, p: Plan | None) -> str | None: + """The Anti-aliasing mode the video window applies itself in OpenGL (gl_aa), or None: then the pipeline does + it with torch. The anti-aliasing and frame generation comparisons are always put together with torch, so + their strips (and the Off one) are what they say.""" + mode = self.settings.aa + return mode if mode in self.gl_aa and (p is None or p.dim not in SOURCE_SIDE) else None + def clip_frame(self, frame, shown, p: Plan | None): """What instant replay keeps of a frame shown: the game's frame as it came, or, with "Compare in clips" on (anti-aliasing and frame generation comparisons), the strips with their labels and dividers burned in.""" diff --git a/engine/framegen/io.py b/engine/framegen/io.py index edd9dc0..f1f2647 100644 --- a/engine/framegen/io.py +++ b/engine/framegen/io.py @@ -694,6 +694,22 @@ class GLWindowSink: self.fsr = FsrScaler(GL, sharpness, hdr=self.hdr10) except Exception as e: # noqa: BLE001 - shader trouble just means another scaler print(f"[display] FSR 1 unavailable ({str(e)[:200]})") + # Anti-aliasing (the setting) as a GLSL pass on the game-sized texture (framegen/aa_gl.py: FXAA and CAS), in + # place of aa.py's torch filters: about 0.07 / 0.02 ms against about 1 ms at 1080p on an RTX 3090 + # (devtools/aa_gl_bench.py), and it works on any graphics card. Not on software OpenGL when CUDA can do it + # (llvmpipe runs shaders on the CPU), nor with HDR10 frames. SUMMIT_AA_GL=1 / 0 forces it on / off. + self.aa_gl, self._aa_gl = None, {} + want = os.environ.get("SUMMIT_AA_GL", "") + software = any(k in renderer.lower() for k in ("llvmpipe", "softpipe", "swrast")) + if not self.hdr10 and want != "0": + from . import aa as _aa + if want == "1" or not software or not _aa._has_cuda(): + try: + from .aa_gl import AaGl + self.aa_gl = AaGl(GL) + print(f"[display] anti-aliasing (FXAA, CAS) runs as an OpenGL pass on {renderer}") + except Exception as e: # noqa: BLE001 - aa.py's torch filters then + print(f"[display] anti-aliasing in OpenGL unavailable ({str(e)[:200]}); torch does it") self.vsr_why = ("it isn't used with HDR output yet" if self.hdr10 else "it needs frames decoded on the GPU (the default for PS5 Remote Play)") self._vsr_args = None # (w, h, clean) while RTX VSR can run but isn't made yet (_vsr_ready) @@ -749,6 +765,9 @@ class GLWindowSink: quit_help=("Takes Summit's picture off the game. A game added to Summit by hand closes with " "it; a Steam game keeps running, as it looks without Summit." if over_game else "Closes the video window and stops playing."), window_keys=not over_game) + # Compare's Same area map in the overlay's Compare tab (self.compare is set by run.py after this) + self.menu.area_view = lambda: self.compare.area_view() if self.compare is not None else None + self.menu.area_click = lambda fx, fy: self.compare.map_click(fx, fy) if self.compare is not None else None self.menu_panel, self.toast_panel = _Panel(GL, self.hdr10), _Panel(GL, self.hdr10) self.mini_panel, self._mini_state = _Panel(GL, self.hdr10), None self.wm_panel, self._wm_state = _Panel(GL, self.hdr10), None # the Summit watermark @@ -890,6 +909,11 @@ class GLWindowSink: inside = 0 <= p[0] < self.menu_panel.w and 0 <= p[1] < self.menu_panel.h self._set_cursor(self.menu.cursor(*p) if inside else "arrow") return + if self.compare is not None and self.compare.dragging: # Same area: the box or the scene dragged + at = self._compare_xy() + if at is not None: + self.compare.move(*at) + return if self._cmp is not None and self._cmp.get("drag") and self.compare is not None: at = self._compare_xy() p = self.compare.plan() @@ -948,6 +972,9 @@ class GLWindowSink: if action == glfw.RELEASE: # the end of a drag (the overlay by its title, a slider, the scrollbar) if self._cmp is not None: self._cmp["drag"] = False # (Compare's divider) + if self.compare is not None: # (Same area: a click without a drag goes back to picking) + at = self._compare_xy() if self.compare.dragging else None + self.compare.release(*at) if at is not None else self.compare.release() self._menu_move = None self.menu.release() return @@ -962,6 +989,8 @@ class GLWindowSink: at, p = self._compare_xy(), self.compare.plan() if at is not None and p is not None and near_divider(p, at[0], at[1], at[2], at[3], 12): self._cmp["drag"] = True + elif at is not None and 0 <= at[0] < at[2] and 0 <= at[1] < at[3]: + self.compare.press(*at) # Same area: pick a cell, drag the area, click to pick again return p = self._menu_xy() inside = p is not None and 0 <= p[0] < self.menu_panel.w and 0 <= p[1] < self.menu_panel.h @@ -982,6 +1011,8 @@ class GLWindowSink: """The wheel scrolls the overlay's page (or its open list); the highlight stays where it is.""" if self.menu.open and dy: self.menu.scroll(dy) + elif dy and self.compare is not None: # Same area: the wheel zooms + self.compare.wheel(dy) def _name(self, mode: str) -> str: if mode == "vsr": @@ -1126,12 +1157,39 @@ class GLWindowSink: self.dx.present(self.settings.vsync, tear=self._may_tear()) _say_if_slow("DXGI Present", t0) else: + self._dev_shot() self.glfw.swap_buffers(self.win) + def _dev_shot(self) -> None: + """For screenshots (devtools): with SUMMIT_SHOT= set, a file .req holding a name makes this + frame, exactly as about to be shown, go to -.png (then the .req file is removed).""" + prefix = os.environ.get("SUMMIT_SHOT") + if not prefix or not os.path.exists(prefix + ".req"): + return + try: + with open(prefix + ".req", encoding="utf-8") as f: + name = f.read().strip() or "shot" + GL = self.GL + fw, fh = self.glfw.get_framebuffer_size(self.win) + GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, 0) + GL.glReadBuffer(GL.GL_BACK) + GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1) + data = GL.glReadPixels(0, 0, fw, fh, GL.GL_BGR, GL.GL_UNSIGNED_BYTE) + img = np.frombuffer(data, np.uint8).reshape(fh, fw, 3)[::-1] + cv2.imwrite(f"{prefix}-{name}.png", img) + os.remove(prefix + ".req") + except Exception as e: # noqa: BLE001 - a devtool: never in the way of the picture + print(f"[display] SUMMIT_SHOT failed: {e}") + os.environ.pop("SUMMIT_SHOT", None) + # ---- settings ------------------------------------------------------------ def allowed(self, key: str, value) -> bool: if key == "scaler": return value in self.modes + if key.startswith("compare_"): # an area cell past the strips, Flip with more than 2, Freeze for frame gen + from .compare import allowed + if not allowed(key, value, self.settings.values()): + return False return value in self.choices.get(key, (value,)) def disabled(self, key: str) -> str | None: @@ -1560,6 +1618,9 @@ class GLWindowSink: glfw, st = self.glfw, self.settings nav = {getattr(glfw, "KEY_" + k): v for k, v in self._NAV.items()} in_menu = self.menu.open and (key in nav or key == glfw.KEY_TAB) + if key == glfw.KEY_V and action == glfw.RELEASE and self.compare is not None and not self.menu.open: + self.compare.key("flip_up") # Flip: let go of V, strip 2 (B) + return if action == glfw.REPEAT and not in_menu: return if action not in (glfw.PRESS, glfw.REPEAT): @@ -1581,6 +1642,13 @@ class GLWindowSink: name = ("prev_tab" if mods & glfw.MOD_SHIFT else "next_tab") if key == glfw.KEY_TAB else nav[key] self._menu_result(self.menu.key(name)) return + if self.compare is not None and not self.menu.open and not held & ~glfw.MOD_SHIFT: + name = self._compare_key(key, mods) + r = self.compare.key(name) if name else None + if isinstance(r, str): + self.toast(r, 4.0) + if r: + return if key in (glfw.KEY_M, glfw.KEY_TAB): self._do("menu") elif key == glfw.KEY_ESCAPE: # never quits: say what does @@ -1622,6 +1690,18 @@ class GLWindowSink: else: st.set("compare", not st.compare) + def _compare_key(self, key: int, mods: int) -> str | None: + """The video window's Compare keys by name (framegen/compare.py Live.key): A Same area, Space Freeze, V Flip + (held), and while Same area is on the arrows, Enter, Esc, 1-4 and + / -.""" + glfw = self.glfw + named = {glfw.KEY_A: "area", glfw.KEY_SPACE: "freeze", glfw.KEY_V: "flip_down", glfw.KEY_UP: "up", + glfw.KEY_DOWN: "down", glfw.KEY_LEFT: "left", glfw.KEY_RIGHT: "right", glfw.KEY_ENTER: "enter", + glfw.KEY_KP_ENTER: "enter", glfw.KEY_ESCAPE: "back", glfw.KEY_EQUAL: "zoom_in", + glfw.KEY_KP_ADD: "zoom_in", glfw.KEY_MINUS: "zoom_out", glfw.KEY_KP_SUBTRACT: "zoom_out"} + if glfw.KEY_1 <= key <= glfw.KEY_4 and not mods & glfw.MOD_CONTROL: + return str(key - glfw.KEY_1 + 1) + return named.get(key) + # ---- drawing ------------------------------------------------------------- def _layout(self) -> tuple[int, int, float, int, int, int, int]: fw, fh = self.glfw.get_framebuffer_size(self.win) @@ -1683,9 +1763,10 @@ class GLWindowSink: self._menu_top = self._menu_at = self._menu_move = None self._set_cursor("arrow") else: - state = (self.menu.state(), round(ui, 3), op) + state = (self.menu.state(), round(ui, 3), op, dw) if state != self._menu_state: - self.menu_panel.update_rgba(self.menu.render(ui, op)) + # never wider than the picture (less a margin each side): narrower, not cut off + self.menu_panel.update_rgba(self.menu.render(ui, op, dw - 2 * int(16 * ui))) self._menu_state = state p = self.menu_panel # Centred top to bottom when it opens, on the side away from the stats' corner (so they stay in view @@ -1830,6 +1911,11 @@ class GLWindowSink: GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, self.w, self.h, GL.GL_BGR, GL.GL_HALF_FLOAT if host.dtype == np.float16 else GL.GL_UNSIGNED_BYTE, host) t_up = time.perf_counter() - t_up + if self.aa_gl is not None and self.compare is not None: + self.compare.gl_aa = self.aa_gl.MODES # (the pipeline leaves these to this window) + mode = self.compare.window_aa(self.compare.plan() if not self.hdr10 else None) + if mode: + self._aa_pass(mode) fw, fh, s, dw, dh, x0, y0 = self._layout() target = screen = self._target() GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target) @@ -1945,6 +2031,38 @@ class GLWindowSink: cmd, self.cmd = self.cmd, None return cmd + def _aa_pass(self, mode: str) -> None: + """The Anti-aliasing setting on the uploaded frame, in place: GLSL into a scratch texture, copied back. Its GPU + time is printed now and then (it doesn't reach the stats overlay's stages).""" + GL, c = self.GL, self._aa_gl + if c.get("size") != (self.w, self.h): + tex = GL.glGenTextures(1) + GL.glBindTexture(GL.GL_TEXTURE_2D, tex) + GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, self.w, self.h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None) + for p_ in (GL.GL_TEXTURE_MIN_FILTER, GL.GL_TEXTURE_MAG_FILTER): + GL.glTexParameteri(GL.GL_TEXTURE_2D, p_, GL.GL_NEAREST) + fbo = GL.glGenFramebuffers(1) + GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, fbo) + GL.glFramebufferTexture2D(GL.GL_DRAW_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, tex, 0) + from .fsr import GpuTimer + c.update(size=(self.w, self.h), tex=tex, fbo=fbo, timer=c.get("timer") or GpuTimer(GL, ring=16), + ms=[], told=time.perf_counter()) + vp = GL.glGetIntegerv(GL.GL_VIEWPORT) + q = c["timer"].begin() + self.aa_gl.draw(mode, self.tex, c["fbo"], self.w, self.h) + GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, c["fbo"]) + GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, self.fbo) + GL.glBlitFramebuffer(0, 0, self.w, self.h, 0, 0, self.w, self.h, GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST) + c["timer"].end(q, "aa") + GL.glViewport(*[int(v) for v in vp]) + c["timer"]._collect() + c["ms"].extend(c["timer"].ms.pop("aa", [])) + if time.perf_counter() - c["told"] >= 30.0 and c["ms"]: + ms = c["ms"][-600:] + print(f"[display] anti-aliasing {mode} in OpenGL: {sum(ms) / len(ms):.3f} ms a frame on average, " + f"{max(ms):.3f} worst (GPU time, pass and copy, {self.w}x{self.h})", flush=True) + c["ms"], c["told"] = [], time.perf_counter() + # ---- Compare (framegen/compare.py) ------------------------------------------------------------------------------ def _compare_scratch(self, w: int, h: int) -> int: """A picture-sized framebuffer each upscaler or look variant is drawn into whole, before its strip is cut.""" @@ -2020,7 +2138,7 @@ class GLWindowSink: def _compare_draw(self, p, target: int, x0: int, y0: int, dw: int, dh: int, on_gpu: bool) -> None: """Upscaler and look strips: each variant drawn on the whole picture (so its GPU time, measured with a timer query, is its real cost per frame), then its strip copied to where it goes.""" - from .compare import rects, timing_key + from .compare import draws, timing_key from .fsr import GpuTimer GL = self.GL if self._cmp is None: @@ -2030,7 +2148,18 @@ class GLWindowSink: c["timer"] = GpuTimer(GL, ring=16) timer = c["timer"] fbo = self._compare_scratch(dw, dh) - for s, ((dx0, dy0, dx1, dy1), (sx0, sy0, sx1, sy1)) in zip(p.strips, rects(p.layout, p.n, dw, dh, p.split)): + todo = draws(p, dw, dh) # (strip, where, which part): -1 is black (a zoomed area's margin) + for _, (dx0, dy0, dx1, dy1), _ in (t for t in todo if t[0] < 0): + GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target) + GL.glEnable(GL.GL_SCISSOR_TEST) + GL.glScissor(x0 + dx0, y0 + dh - dy1, dx1 - dx0, dy1 - dy0) + GL.glClearColor(0.0, 0.0, 0.0, 1.0) + GL.glClear(GL.GL_COLOR_BUFFER_BIT) + GL.glDisable(GL.GL_SCISSOR_TEST) + for i, s in enumerate(p.strips): + mine = [(d, src) for k, d, src in todo if k == i] + if not mine: # (Flip: the strip that isn't on screen isn't drawn, or timed) + continue GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, fbo) GL.glViewport(0, 0, dw, dh) GL.glClear(GL.GL_COLOR_BUFFER_BIT) @@ -2049,9 +2178,12 @@ class GLWindowSink: timer.end(q, key) GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, fbo) GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target) - # picture rows go down, GL's up - GL.glBlitFramebuffer(sx0, dh - sy1, sx1, dh - sy0, x0 + dx0, y0 + dh - dy1, x0 + dx1, y0 + dh - dy0, - GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST) + for (dx0, dy0, dx1, dy1), (sx0, sy0, sx1, sy1) in mine: + # picture rows go down, GL's up. Nearest: a Same area zoom shows the variant's own pixels; only the + # inset map (the whole picture, shrunk) is smoothed + shrink = (dx1 - dx0) < (sx1 - sx0) + GL.glBlitFramebuffer(sx0, dh - sy1, sx1, dh - sy0, x0 + dx0, y0 + dh - dy1, x0 + dx1, y0 + dh - dy0, + GL.GL_COLOR_BUFFER_BIT, GL.GL_LINEAR if shrink else GL.GL_NEAREST) timer._collect() for key, ms in timer.ms.items(): for v in ms: @@ -2067,6 +2199,9 @@ class GLWindowSink: c["pic"] = (x0, y0, w, h) if w <= 0 or h <= 0: return + # how to pick an area: over a game the keys and clicks are the game's, so in the overlay's Compare tab + self.compare.hint = (self.compare.HINT if self.overlay_of is None else + f"Pick the area in Summit's overlay ({self.overlay_key.name}): Compare tab, Area") items = self.compare.items(p, w, h, max(0.5, h / 1080)) panels = c["panels"] while len(panels) < len(items): diff --git a/engine/framegen/menu.py b/engine/framegen/menu.py index 0a9ed1b..632198f 100644 --- a/engine/framegen/menu.py +++ b/engine/framegen/menu.py @@ -108,6 +108,11 @@ class Menu: self._drag: tuple | None = None # what the mouse is dragging inside: ("slider", row index) or ("scrollbar", y0, scroll0) self._hover: tuple | None = None # ("tab", i), ("close",): what the mouse is over, besides rows self._hit: dict = {} # render()'s layout in the image's pixels, for the mouse + # Compare's Same area (framegen/compare.py Live): area_view() -> {"n", "box", "cell", "zoom", "sel"} or None, + # drawn as a map of the picture in the help card while the Area row is highlighted; area_click(fx, fy): the + # map clicked at that point of the picture. Set by the window; None: no map. + self.area_view: Callable[[], dict | None] | None = None + self.area_click: Callable[[float, float], None] | None = None self._drawn: tuple = (None, None) # render()'s last picture and what it showed (see there) self.optimizer_state: Callable[[], str] | None = None # framegen/optimize.py Control.state, when it can run self.optimizer_note: Callable[[], str] = lambda: "" # its headroom line, beside Find my settings @@ -353,7 +358,8 @@ class Menu: numeric = all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in choices) if numeric and len(choices) >= 3 and list(choices) in (sorted(choices), sorted(choices, reverse=True)): return "slider" - if len(choices) <= 4 and sum(len(self.name(row, v)) for v in choices) <= 34: + total = sum(len(self.name(row, v)) for v in choices) + if len(choices) <= 4 and total <= 34 or len(choices) <= 6 and total <= 16: return "buttons" return "list" @@ -438,6 +444,8 @@ class Menu: return "hand" if self._in(self._hit.get("title", (0, 0, 0, 0)), x, y): return "move" + if self._in(self._hit.get("map"), x, y): + return "hand" i = self._row_at(x, y) if i is not None and any(self._in(b, x, y) for b, _, _ in self._hit.get("controls", {}).get(i, ())): return "hand" @@ -526,6 +534,10 @@ class Menu: return None if self._in(self._hit.get("close", (0, 0, 0, 0)), x, y): return "close" + m = self._hit.get("map") + if self._in(m, x, y) and self.area_click is not None: + self.area_click((x - m[0]) / max(1, m[2] - m[0]), (y - m[1]) / max(1, m[3] - m[1])) + return None tabs = self.tabs() for i, box in enumerate(self._hit.get("tabs", ())): if self._in(box, x, y) and i < len(tabs): @@ -595,9 +607,11 @@ class Menu: return text, [(name, row.spec.impact[k]) for k, name in (("picture", "PICTURE"), ("speed", "SPEED")) if row.spec.impact.get(k)] - def render(self, ui: float = 1.0, opacity: float = 1.0) -> np.ndarray: + def render(self, ui: float = 1.0, opacity: float = 1.0, max_w: int | None = None) -> np.ndarray: """The overlay as an RGBA image: clear outside its rounded corners, and its background lets `1 - opacity` of - the game through (text and controls stay solid). ui scales it (1.0 suits a 1080p-tall picture).""" + the game through (text and controls stay solid). ui scales it (1.0 suits a 1080p-tall picture); max_w: the + widest it may be (the picture's width, less a margin), narrower than its own width the panel is made + narrower, never cut.""" def px(v: float) -> int: return max(1, int(round(v * ui))) @@ -605,6 +619,8 @@ class Menu: self._follow(rows) tabs = self.tabs() W, pad = px(1100), px(32) + if max_w is not None: + W = max(px(560), min(W, int(max_w))) head_h, tabs_h, row_h, help_h, foot_h = px(72), px(42), px(44), px(150), px(46) y_tabs = head_h + px(12) y_rows = y_tabs + tabs_h + px(12) @@ -614,7 +630,8 @@ class Menu: x0, x1 = pad - px(10), W - pad + px(10) # rows, cards and tabs reach a little past the text's margins # Only the header's numbers change while nothing is touched (once a second): then just the header is drawn # again, over the picture kept from last time. - key = (round(ui, 3), self._shown()) + area = self.area_view() if self.area_view is not None and rows[self.index].key == "compare_cell" else None + key = (round(ui, 3), W, self._shown(), repr(area)) if key == self._drawn[0]: c = self._drawn[1] c.d.rectangle((pad - px(2), px(8), W - pad + px(4), head_h - px(4)), fill=U.BG) @@ -712,6 +729,15 @@ class Menu: c.rrect(x0, y_help, x1, y_help + help_h, px(12), fill=U.SURFACE, outline=U.BORDER) hx, hy, hw = x0 + px(18), y_help + px(26), x1 - x0 - 2 * px(18) c.text(hx, hy, row.label, U.font(px(15), "semibold"), U.TEXT) + self._hit["map"] = None + if area is not None: # Same area's map: the picture, its cells numbered, the area picked; click to pick + mh = help_h - px(28) + mw = mh * 16 // 9 + mx1, my0 = x1 - px(14), y_help + px(14) + m = (mx1 - mw, my0, mx1, my0 + mh) + self._map(c, m, area, px) + self._hit["map"] = m + hw -= mw + px(24) text, impact = self._help(row) hy += px(12) room = 6 # lines: the help, then each effect, which gets a second line if there's room for it @@ -796,11 +822,38 @@ class Menu: c.rrect(lx1 - px(6), ty, lx1 - px(3), ty + th, px(2), fill=U.FAINT) self._hit = {"w": W, "h": H, "rows": (x0, y_rows, x1, y_rows + VISIBLE * row_h), "row_h": row_h, + "map": self._hit.get("map"), "tabs": tab_boxes, "close": close, "controls": controls, "title": (0, 0, W, head_h), "scrollbar": scrollbar, "thumb": thumb, "drop": drop_box, "drop_items": drop_items} self._drawn = (key, c) return c.rgba(opacity, (U.SURFACE,)) + @staticmethod + def _map(c: U.Canvas, box, area: dict, px) -> None: + """The Same area map: the picture's outline, its cells (numbered; the picked one, or while picking the + highlighted one, lit) and the area as a box.""" + x0, y0, x1, y1 = box + w, h = x1 - x0, y1 - y0 + c.rrect(x0, y0, x1, y1, px(6), fill=U.BG, outline=U.BORDER) + n = area["n"] + cols, rows = {2: (2, 1), 3: (3, 1)}.get(n, (2, 2)) + f = U.font(px(15), "bold") + lit = area["cell"] if area["box"] is not None else area["sel"] + 1 + for k in range(n): + i, j = k % cols, k // cols + cx0, cy0 = x0 + w * i // cols, y0 + h * j // rows + cx1, cy1 = x0 + w * (i + 1) // cols, y0 + h * (j + 1) // rows + on = k + 1 == lit + c.rrect(cx0 + px(3), cy0 + px(3), cx1 - px(3), cy1 - px(3), px(4), fill=U.HILITE if on else U.SURFACE) + c.text((cx0 + cx1) // 2, (cy0 + cy1) // 2, str(k + 1), f, U.TEXT if on else U.FAINT, "mm") + if area["box"] is not None: + bx0, by0, bx1, by1 = area["box"] + r = (x0 + int(bx0 * w), y0 + int(by0 * h), x0 + max(int(bx1 * w), int(bx0 * w) + px(4)), + y0 + max(int(by1 * h), int(by0 * h) + px(4))) + c.d.rectangle((r[0], r[1], r[2] - 1, r[3] - 1), outline=U.ACCENT, width=max(1, px(2))) + else: + c.text(x0 + w // 2, y1 - px(10), "picking", U.font(px(11), "medium"), U.DIM, "mm") + def _header(self, c: U.Canvas, px, W: int, pad: int, head_h: int) -> tuple[int, int, int, int]: """The mark, the game's name, the live numbers and Close. Returns Close's box.""" f_label = U.font(px(16), "medium") diff --git a/engine/framegen/settings.py b/engine/framegen/settings.py index 4413a18..0665d49 100644 --- a/engine/framegen/settings.py +++ b/engine/framegen/settings.py @@ -137,8 +137,8 @@ def _compare_specs() -> tuple: return ( Spec("compare", "Compare", (False, True), False, ON_OFF, saved=False, group="Compare", help="Cuts the picture into strips, each drawn with a different choice of one setting, with its name " - "and its measured cost per frame. Key: C (Shift+C: the next thing to compare). Starts off each " - "session."), + "and its measured cost per frame. Key: C (Shift+C: the next thing to compare; A: Same area; Space: " + "Freeze; hold V: Flip). Starts off each session."), Spec("compare_dim", "What to compare", compare.DIMENSIONS, "aa", compare.DIM_NAMES, group="Compare", help="Anti-aliasing, the upscaler, frame generation (the game's own frames against generated ones, " "live, to see the smoothness) or the look."), @@ -147,10 +147,34 @@ def _compare_specs() -> tuple: "the mouse."), *strips, Spec("compare_layout", "Layout", compare.LAYOUTS, "columns", compare.LAYOUT_NAMES, group="Compare", - help="Side by side: vertical strips of one picture. Stacked: horizontal strips. 2x2: the same crop of " - "the picture's middle in each cell, pixel for pixel, to look closely."), + help="Side by side: vertical strips of one picture. Stacked: horizontal strips. Same area: the picture " + "in one cell per strip (halves, thirds or 2x2); pick one, and every cell shows that area, each " + "with its own choice, to look closely. Key: A."), + Spec("compare_cell", "Area", compare.CELLS, "pick", compare.CELL_NAMES, saved=False, group="Compare", + applies=("compare_layout", ("grid",)), + help="The area every cell shows: a cell's number (left to right, then down), Free (a box moved with the " + "mouse, or by clicking this map), or Pick to choose again on the picture. Key: Enter (click, or " + "the arrows and Enter, to pick)."), + Spec("compare_zoom", "Zoom", compare.ZOOMS, 1, {z: compare.zoom_name(z) for z in compare.ZOOMS}, + saved=False, group="Compare", applies=("compare_layout", ("grid",)), + help="How much the area is enlarged, 1x (pixel for pixel) to 8x, by whole pixels (nearest neighbour: " + "no smoothing that would hide a difference). Keys: the mouse wheel, + and -."), + Spec("compare_split", "Divider", compare.SPLITS, 0.5, {v: f"{round(v * 100)}%" for v in compare.SPLITS}, + saved=False, group="Compare", applies=("compare_strips", (2,)), + also=("compare_layout", ("columns", "rows")), + help="Where the line between two strips is. The mouse can drag it too."), + Spec("compare_freeze", "Freeze", (False, True), False, ON_OFF, saved=False, group="Compare", + help="Holds one game frame, so anti-aliasing, the upscaler or the look can be studied on the same still " + "(the game goes on underneath). Frame generation can't be frozen: its strips differ only in " + "motion. Key: Space."), + Spec("compare_flip", "Flip", compare.FLIPS, "off", compare.FLIP_NAMES, saved=False, group="Compare", + help="With two strips: the whole picture with strip 1 (A) or strip 2 (B), to flip between them. Key: " + "hold V for A, let go for B; Esc goes back to the split."), Spec("compare_labels", "Labels", (True, False), True, ON_OFF, group="Compare", - help="Each strip's name at its top."), + help="Each strip's name at its top (or bottom)."), + Spec("compare_labels_at", "Labels at", compare.LABEL_PLACES, "top", {"top": "Top", "bottom": "Bottom"}, + group="Compare", applies=("compare_labels", (True,)), + help="Where the labels go: at the bottom when the game's own HUD is at the top."), Spec("compare_timings", "Timings", (True, False), True, ON_OFF, group="Compare", help="Under each name: its measured cost per frame, average / worst over the last 120 frames, in ms."), Spec("compare_clips", "Compare in clips", (False, True), False, ON_OFF, group="Compare", @@ -571,7 +595,9 @@ LAYOUT: tuple[tuple[str, str, tuple[str, ...]], ...] = ( ("Sources", "Testing", ("simulate_30",)), ("Compare", "Setup", ("compare", "compare_dim", "compare_strips", *(compare.strip_key(d, i) for d in compare.DIMENSIONS for i in range(1, 5)))), - ("Compare", "Show", ("compare_layout", "compare_labels", "compare_timings", "compare_clips")), + ("Compare", "Show", ("compare_layout", "compare_cell", "compare_zoom", "compare_split", "compare_freeze", + "compare_flip")), + ("Compare", "Labels", ("compare_labels", "compare_labels_at", "compare_timings", "compare_clips")), ) diff --git a/engine/run.py b/engine/run.py index b6c7b55..ae619a8 100644 --- a/engine/run.py +++ b/engine/run.py @@ -363,7 +363,12 @@ def main() -> int: help="start with Compare on (the C key): e.g. aa:off,fxaa,smaa,cas scaler:off,bilinear,fsr,vsr " "framegen:off,on look:off,on (framegen/compare.py lists the choices)") ap.add_argument("--compare-layout", default=None, choices=BY_KEY["compare_layout"].choices, - help="Compare's strips: columns (side by side), rows (stacked) or grid (2x2, the same crop)") + help="Compare's strips: columns (side by side), rows (stacked) or grid (Same area: one cell per " + "strip, each showing the same area of the scene)") + ap.add_argument("--compare-area", default=None, metavar="CELL|X,Y,W,H", + help="Compare's Same area, already picked: a cell number (1 to the number of strips, left to " + "right, then down) or an area as fractions of the picture, e.g. 0.4,0.3,0.1,0.1 (zoomed " + "to fill a cell, by whole pixels)") ap.add_argument("--display-cv", action="store_true", help="use the (slow) OpenCV window instead of OpenGL") ap.add_argument("--out", help="write output video") ap.add_argument("--score", action="store_true", help="[sim] PSNR of interpolated frames vs real dropped frames") @@ -521,6 +526,16 @@ def main() -> int: settings.override(key, value) except ValueError as e: ap.error(str(e)) + compare_free = None # --compare-area: the free box's centre, for Compare's Live below + if a.compare_area: + from framegen.compare import MAX_STRIPS, area_settings + n = max(2, min(int(settings.compare_strips), MAX_STRIPS.get(settings.compare_dim, 4))) + try: + area, compare_free = area_settings(a.compare_area, n) + except ValueError as e: + ap.error(str(e)) + for key, value in area.items(): + settings.override(key, value) if a.benchmark: settings.override("overlay", True) # the countdown is on it if a.frametime_log: @@ -751,6 +766,8 @@ def main() -> int: private=vfg_running or bool(w is not None and w.vsr is not None and w.vsr.private)) compare_live = CompareLive(settings, compare_caps) + if compare_free is not None: + compare_live.free = compare_free if isinstance(window, GLWindowSink): window.compare = compare_live if window is not None and sys.platform != "win32": diff --git a/engine/tests/test_aa_gl.py b/engine/tests/test_aa_gl.py new file mode 100644 index 0000000..126e5c2 --- /dev/null +++ b/engine/tests/test_aa_gl.py @@ -0,0 +1,80 @@ +"""framegen/aa_gl.py: the GLSL anti-aliasing against aa.py's numpy reference (needs an OpenGL context: skipped +without a display), and who applies the Anti-aliasing setting (no OpenGL needed).""" +import pathlib +import sys + +import numpy as np +import pytest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from framegen import aa, compare as C # noqa: E402 +from framegen.settings import Settings # noqa: E402 + + +def test_the_window_applies_the_setting_only_where_the_pipeline_leaves_it(): + st = Settings() + live = C.Live(st, lambda: C.Caps()) + img = np.random.default_rng(0).integers(0, 255, (32, 48, 3), dtype=np.uint8) + st.override("aa", "fxaa") + assert live.window_aa(None) is None # no OpenGL pass: torch does it + live.gl_aa = ("fxaa", "cas") + assert live.window_aa(None) == "fxaa" + assert live.source_side(img, None, img, 2) is img # left to the window + st.override("aa", "smaa") + assert live.window_aa(None) is None # SMAA-style stays torch + st.override("aa", "fxaa") + for k, v in C.settings_for("aa:off,fxaa").items(): + st.override(k, v) + assert live.window_aa(live.plan()) is None # the AA comparison is torch's, strip by strip + for k, v in C.settings_for("scaler:off,bilinear").items(): + st.override(k, v) + assert live.window_aa(live.plan()) == "fxaa" + + +def _context(): + glfw = pytest.importorskip("glfw") + pytest.importorskip("OpenGL") + if not glfw.init(): + pytest.skip("no display for OpenGL") + glfw.window_hint(glfw.VISIBLE, glfw.FALSE) + glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) + glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) + glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) + win = glfw.create_window(16, 16, "aa_gl test", None, None) + if not win: + glfw.terminate() + pytest.skip("no OpenGL 3.3 context") + glfw.make_context_current(win) + return glfw, win + + +@pytest.mark.parametrize("mode", ["fxaa", "cas"]) +def test_glsl_matches_the_numpy_reference(mode): + glfw, win = _context() + try: + from OpenGL import GL + from framegen.aa_gl import AaGl + from test_compare import ALIASED + img = np.ascontiguousarray(ALIASED) + h, w = img.shape[:2] + GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) + GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1) + texs = [] + for data in (img, None): + t = GL.glGenTextures(1) + GL.glBindTexture(GL.GL_TEXTURE_2D, t) + GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) + GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, w, h, 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE, data) + texs.append(t) + fbo = GL.glGenFramebuffers(1) + GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, fbo) + GL.glFramebufferTexture2D(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D, texs[1], 0) + AaGl(GL).draw(mode, texs[0], fbo, w, h) + GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, fbo) + out = np.frombuffer(GL.glReadPixels(0, 0, w, h, GL.GL_BGR, GL.GL_UNSIGNED_BYTE), np.uint8).reshape(h, w, 3) + ref = aa.apply(img, mode, gpu=False) + diff = np.abs(out.astype(int) - ref) + assert (diff > 1).mean() < 0.001 # the same filter, to within float rounding + finally: + glfw.destroy_window(win) + glfw.terminate() diff --git a/engine/tests/test_compare_area.py b/engine/tests/test_compare_area.py new file mode 100644 index 0000000..04832d8 --- /dev/null +++ b/engine/tests/test_compare_area.py @@ -0,0 +1,352 @@ +"""Compare's second step (framegen/compare.py): Same area (cells, picking, the picked area in every cell, zoom, the +free box and the inset map), Freeze, Flip, labels at the bottom, --compare-area. No GPU or window needed.""" +import pathlib +import sys + +import numpy as np +import pytest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from framegen import compare as C # noqa: E402 +from framegen.settings import Settings # noqa: E402 + + +def live_with(spec: str = "aa:off,fxaa,smaa,cas", **values) -> tuple[Settings, C.Live]: + st = Settings() + for k, v in C.settings_for(spec).items(): + st.override(k, v) + for k, v in values.items(): + st.override(k, v) + return st, C.Live(st, lambda: C.Caps()) + + +def quadrants(w: int = 64, h: int = 36) -> np.ndarray: + """A picture whose four quarters are 10, 20, 30, 40, with a pixel-wide ramp so position shows.""" + img = np.zeros((h, w, 3), np.uint8) + img[: h // 2, : w // 2], img[: h // 2, w // 2:] = 10, 20 + img[h // 2:, : w // 2], img[h // 2:, w // 2:] = 30, 40 + return img + + +# ---- cells and areas ------------------------------------------------------------------------------------------ +def test_cells_are_halves_thirds_or_a_2x2(): + assert C.cells(2, 1920, 1080) == [(0, 0, 960, 1080), (960, 0, 1920, 1080)] + assert C.cells(3, 1920, 1080) == [(0, 0, 640, 1080), (640, 0, 1280, 1080), (1280, 0, 1920, 1080)] + assert C.cells(4, 1920, 1080) == [(0, 0, 960, 540), (960, 0, 1920, 540), (0, 540, 960, 1080), + (960, 540, 1920, 1080)] + assert C.cell_at(4, 0.9, 0.9) == 4 and C.cell_at(4, 0.1, 0.9) == 3 and C.cell_at(3, 0.5, 0.2) == 2 + assert C.dividers("grid", 3, 1920, 1080) == [(640, 0, 640, 1080), (1280, 0, 1280, 1080)] + + +def test_the_picked_quarter_is_shown_in_every_cell_pixel_for_pixel(): + a = C.area_of("4", 1, 4) + r = C.rects("grid", 4, 1920, 1080, area=a) + assert all(src == (960, 540, 1920, 1080) for _, src in r) # the bottom-right quarter, four times + assert [d for d, _ in r] == C.cells(4, 1920, 1080) # each filling its cell, at 1x + img = quadrants() + out = C.compose([img] * 4, C.rects("grid", 4, 64, 36, area=a)) + assert (out == 40).all() + + +def test_the_old_grid_is_the_middle_at_1x(): + """Before an area is given, the grid shows the picture's middle, a cell's size (round 2's "same crop").""" + assert C.rects("grid", 4, 1920, 1080)[0][1] == (480, 270, 1440, 810) + + +def test_picking_shows_each_cell_as_it_is(): + r = C.rects("grid", 3, 1920, 1080, picking=True) + assert all(d == s for d, s in r) + + +def test_zoom_enlarges_by_whole_pixels_with_nearest_neighbour(): + a = C.Area(0.5, 0.5, 4, 0) + (d, s), *_ = C.rects("grid", 4, 1920, 1080, area=a) + assert (s[2] - s[0], s[3] - s[1]) == (240, 135) and (d[2] - d[0], d[3] - d[1]) == (960, 540) + # nearest neighbour: every source pixel becomes a 4x4 block, no new values in between + img = np.random.default_rng(1).integers(0, 255, (1080, 1920, 3), dtype=np.uint8) + out = C.compose([img] * 4, C.rects("grid", 4, 1920, 1080, area=a)) + cell = out[:540, :960] + src = img[s[1]:s[3], s[0]:s[2]] + assert np.array_equal(cell, np.repeat(np.repeat(src, 4, 0), 4, 1)) + + +def test_a_zoom_that_doesnt_fill_the_cell_is_centred_and_the_rest_is_black(): + st, live = live_with(compare_layout="grid", compare_cell="free", compare_zoom=6) + p = live.plan() + d = C.draws(p, 1280, 720) + assert d[0][0] == -1 # black first, under the zoomed area + (_, cell, _), = [t for t in d if t[0] == -1][:1] + _, dst, src = next(t for t in d if t[0] == 0) + assert (dst[2] - dst[0]) == (src[2] - src[0]) * 6 and dst[0] >= cell[0] and dst[2] <= cell[2] + out = C.compose([np.full((720, 1280, 3), 200, np.uint8)] * 4, d, np.full((720, 1280, 3), 99, np.uint8)) + assert out[:360, :640].min() in (0, 200) and (out[:360, :640] != 99).all() + + +def test_compose_scales_torch_the_same_as_numpy(): + torch = pytest.importorskip("torch") + img = np.random.default_rng(2).integers(0, 255, (72, 128, 3), dtype=np.uint8) + r = C.rects("grid", 4, 128, 72, area=C.Area(0.3, 0.6, 3, 0)) + a = C.compose([img] * 4, r) + b = C.compose([torch.from_numpy(img)] * 4, r) + assert np.array_equal(a, b.numpy()) + + +def test_the_free_box_stays_inside_the_picture_and_snaps_to_cells(): + assert C.clamp_centre(4, 2, 0.0, 1.0) == (0.125, 0.875) + assert C.snap(4, 0.26, 0.74) == 3 and C.snap(4, 0.4, 0.5) == 0 + r = C.area_rect(C.Area(0.99, 0.99, 2, 0), 4, 1920, 1080) + assert r[2] == 1920 and r[3] == 1080 + + +def test_the_inset_map_shows_the_whole_picture_in_a_corner(): + st, live = live_with(compare_layout="grid", compare_cell="2") + d = C.draws(live.plan(), 1920, 1080) + i, dst, src = d[-1] + assert i == 0 and src == (0, 0, 1920, 1080) + assert dst[2] < 1920 and dst[3] < 1080 and dst[0] > 1920 // 2 # bottom right, labels at the top + st.override("compare_labels_at", "bottom") + assert C.draws(live.plan(), 1920, 1080)[-1][1][1] < 100 # top right, labels at the bottom + + +# ---- the plan from the settings, and the keys and mouse -------------------------------------------------------- +def test_same_area_starts_by_picking_and_the_keys_pick(): + st, live = live_with() + assert live.key("area") is True + p = live.plan() + assert p.layout == "grid" and p.picking and p.sel == 0 + live.key("right"), live.key("down") + assert live.plan().sel == 3 + live.key("enter") + p = live.plan() + assert not p.picking and p.area.cell == 4 and p.area.zoom == 1 + assert C.labels(p, C.Timings())[1][0] == "FXAA · 1x" # the zoom, on every label + live.key("enter") # back to picking, on the cell it was + assert live.plan().picking and live.plan().sel == 3 + live.key("2") + assert live.plan().area.cell == 2 + live.key("back") # Esc leaves Same area, back to the layout before + assert live.plan().layout == "columns" + + +def test_the_mouse_picks_pans_and_zooms(): + st, live = live_with(compare_layout="grid") + live.key("area"), live.key("area") # off and on again: picking + assert live.press(1500, 300, 1920, 1080) # picking: a press picks at once + assert live.plan().area.cell == 2 + assert live.wheel(1.0) # zoom in + p = live.plan() + assert p.area.zoom == 2 and p.area.cell == 2 + live.press(1000, 500, 1920, 1080) + live.move(1400, 500, 1920, 1080) # a drag: the scene follows the hand, so the box goes left + live.release() + p = live.plan() + assert p.area.cell == 0 and p.area.cx < 0.75 and st.compare_cell == "free" + live.press(1000, 500, 1920, 1080) + live.release() # a click: back to picking + assert live.plan().picking + + +def test_a_drag_whose_moves_were_missed_is_still_a_drag(): + st, live = live_with(compare_layout="grid", compare_cell="1", compare_zoom=2) + live.press(400, 300, 1920, 1080) + live.release(100, 200, 1920, 1080) # (the window saw no motion in between) + assert st.compare_cell == "free" and live.plan().area.cx > 0.25 + + +def test_the_inset_map_moves_the_box(): + st, live = live_with(compare_layout="grid", compare_cell="1", compare_zoom=4) + ix0, iy0, ix1, iy1 = C.inset_rect(1920, 1080) + live.press(ix0 + (ix1 - ix0) * 0.6, iy0 + (iy1 - iy0) * 0.3, 1920, 1080) + live.release() + a = live.plan().area + assert a.cell == 0 and abs(a.cx - 0.6) < 0.01 and abs(a.cy - 0.3) < 0.01 + + +def test_the_overlay_map_click(): + st, live = live_with(compare_layout="grid", compare_cell="pick") + live.map_click(0.8, 0.8) + assert live.plan().area.cell == 4 # at 1x: the cell there + st.override("compare_zoom", 3) + live.map_click(0.4, 0.45) + a = live.plan().area + assert a.cell == 0 and a.zoom == 3 and (a.cx, a.cy) == (0.4, 0.45) + v = live.area_view() + assert v["n"] == 4 and v["zoom"] == 3 and v["box"][0] < 0.4 < v["box"][2] + + +def test_arrow_keys_nudge_a_picked_area(): + st, live = live_with(compare_layout="grid", compare_cell="1", compare_zoom=2) + live.key("right") + a = live.plan().area + assert a.cell == 0 and a.cx > 0.25 + + +def test_fewer_strips_fewer_cells(): + st, live = live_with("aa:off,fxaa", compare_layout="grid") + assert len(C.cells(live.plan().n, 100, 100)) == 2 + assert not C.allowed("compare_cell", "3", st.values()) and C.allowed("compare_cell", "2", st.values()) + live.key("4") + assert live.plan().picking # no fourth cell + + +# ---- Freeze ---------------------------------------------------------------------------------------------------- +def test_freeze_holds_one_frame_for_every_strip(): + st, live = live_with("aa:off,fxaa") + a, b = quadrants(), quadrants()[::-1].copy() + live.key("freeze") + p = live.plan() + assert p.frozen + first = live.source_side(a, p, a, 2) + again = live.source_side(b, p, b, 2) # a new game frame: the still stays + assert np.array_equal(first, again) + items = C.overlay_items(p, C.labels(p, C.Timings()), 640, 360, 0.5) + assert len(items) == 1 + 1 + 2 # a divider, the FROZEN mark, two labels + live.key("freeze") + assert not np.array_equal(live.source_side(b, live.plan(), b, 2), first) + + +def test_frame_generation_cant_be_frozen(): + st, live = live_with("framegen:off,on") + assert live.key("freeze") == C.FREEZE_WHY + st.override("compare_freeze", True) + assert not live.plan().frozen + assert not C.allowed("compare_freeze", True, st.values()) + + +def test_freeze_works_for_window_side_comparisons_too(): + """Upscaler and look strips are drawn by the window from the frame the pipeline sends: frozen, that is the + held one.""" + st, live = live_with("scaler:off,bilinear") + live.key("freeze") + p = live.plan() + a, b = quadrants(), quadrants()[::-1].copy() + assert np.array_equal(live.source_side(a, p, a, 2), live.source_side(b, p, b, 2)) + + +# ---- Flip ------------------------------------------------------------------------------------------------------ +def test_flip_shows_the_whole_picture_with_a_then_b(): + st, live = live_with("aa:off,fxaa") + live.key("flip_down") + p = live.plan() + assert p.flip == "a" and C.draws(p, 64, 36) == [(0, (0, 0, 64, 36), (0, 0, 64, 36))] + assert C.labels(p, C.Timings())[0][0] == "A: Off" + live.key("flip_up") + p = live.plan() + assert p.flip == "b" and C.draws(p, 64, 36)[0][0] == 1 + t = C.Timings() + C.aa_strips(quadrants(), p, t) + assert t.stat("aa:fxaa") is not None + items = C.overlay_items(p, C.labels(p, t), 640, 360, 0.5) + assert len(items) == 1 # one label, no divider + live.key("back") + assert live.plan().flip == "off" + + +def test_flip_needs_two_strips(): + st, live = live_with() + assert "two" in live.key("flip_down") + st.override("compare_flip", "a") + assert live.plan().flip == "off" + + +def test_flip_runs_only_the_strip_on_screen(): + st, live = live_with("aa:off,fxaa", compare_flip="a") + t = C.Timings() + out = C.aa_strips(quadrants(), live.plan(), t) + assert t.stat("aa:fxaa") is None and np.array_equal(out, quadrants()) + + +# ---- labels at the bottom -------------------------------------------------------------------------------------- +def test_labels_can_go_to_the_bottom(): + st, live = live_with() + p = live.plan() + top = C.overlay_items(p, C.labels(p, C.Timings()), 1280, 720, 0.67) + st.override("compare_labels_at", "bottom") + p = live.plan() + bot = C.overlay_items(p, C.labels(p, C.Timings()), 1280, 720, 0.67) + assert max(y for _, y, _ in top[3:]) < 100 and min(y for _, y, _ in bot[3:]) > 600 + + +def test_picker_marks_and_hint(): + st, live = live_with(compare_layout="grid") + p = live.plan() + items = C.overlay_items(p, C.labels(p, C.Timings()), 1280, 720, 0.67, live.hint) + # two dividers, an outline and a number per cell, the hint, four labels + assert len(items) == 2 + 8 + 1 + 4 + img = C.blend(np.zeros((720, 1280, 3), np.uint8), items) + assert img[1:4, 10:600, 2].mean() > 250 # the highlighted cell's outline, in the accent (red channel high) + + +def test_view_changes_keep_the_timings(): + st, live = live_with() + live.timings.add("aa:fxaa", 1.0) + live.key("area") + live.key("1") + live.key("freeze") + st.override("compare_labels_at", "bottom") + assert live.timings.stat("aa:fxaa") is not None + st.override("compare_dim", "scaler") + assert live.timings.stat("aa:fxaa") is None + + +# ---- --compare-area ---------------------------------------------------------------------------------------------- +def test_compare_area_takes_a_cell_or_fractions(): + s, centre = C.area_settings("3", 4) + assert s == {"compare_layout": "grid", "compare_cell": "3", "compare_zoom": 1} and centre == (0.25, 0.75) + s, centre = C.area_settings("0.1,0.1,0.1,0.1", 4) + assert s["compare_cell"] == "free" and s["compare_zoom"] == 4 and centre == pytest.approx((0.15, 0.15)) + s, _ = C.area_settings("0,0,0.5,0.5", 4) + assert s["compare_cell"] == "1" and s["compare_zoom"] == 1 + for bad in ("5", "0.9,0.9,0.5,0.5", "a,b", "1,2"): + with pytest.raises(ValueError): + C.area_settings(bad, 4) + + +# ---- the overlay's Compare tab --------------------------------------------------------------------------------- +def overlay_on(row_key: str, **values): + from framegen.menu import Menu + st, live = live_with(**values) + m = Menu(st, allowed=lambda k, v: C.allowed(k, v, st.values()) if k.startswith("compare_") else True) + m.area_view, m.area_click = live.area_view, live.map_click + m.open = True + m.show("Compare") + rows = m.rows() + m._select([r.key for r in rows].index(row_key), rows) + return st, live, m + + +def test_every_compare_action_is_a_row_in_the_overlay(): + st, live, m = overlay_on("compare_layout", compare_layout="grid") + keys = {r.key for r in m.rows()} + assert {"compare", "compare_dim", "compare_strips", "compare_layout", "compare_cell", "compare_zoom", + "compare_freeze", "compare_flip", "compare_labels_at"} <= keys + st.override("compare_layout", "columns") + st.override("compare_strips", 2) + assert "compare_split" in {r.key for r in m.rows()} and "compare_cell" not in {r.key for r in m.rows()} + + +def test_the_area_row_is_buttons_and_its_map_picks(): + st, live, m = overlay_on("compare_cell", compare_layout="grid") + row = m.rows()[m.index] + assert m.kind_of(row) == "buttons" + m.render(0.67, 0.9) + x0, y0, x1, y1 = m._hit["map"] + m.click(x0 + (x1 - x0) * 0.8, y0 + (y1 - y0) * 0.2) # the top-right cell + assert st.compare_cell == "2" and live.plan().area.cell == 2 + m.key("right") # the keys step through Pick, 1..4, Free + assert st.compare_cell == "3" + + +def test_the_area_row_greys_out_cells_past_the_strips(): + st, live, m = overlay_on("compare_cell", compare_layout="grid", compare_strips=2) + row = m.rows()[m.index] + assert m.can(row, "2") and not m.can(row, "3") + + +def test_the_overlay_fits_a_1280_wide_window(): + """Round 2's overlay was cut off at the right in a 1280 px window: render() takes the room there is.""" + st, live, m = overlay_on("compare") + ui = 720 / 1080 * 1.5 # a bigger overlay (Overlay size 150%) in a 1280 x 720 window + img = m.render(ui, 0.9, 1280 - 2 * int(16 * ui)) + assert img.shape[1] <= 1280 - 2 * int(16 * ui) + assert m.render(720 / 1080, 0.9, 1248).shape[1] == round(1100 * 720 / 1080) # room enough: its own width