Found live on the VM: the drag ended as a click (back to picking). SUMMIT_SHOT=<prefix> plus a <prefix>.req file makes the window write the frame it is about to show (the shared, composited llvmpipe display gave out-of-order window captures).
1131 lines
55 KiB
Python
1131 lines
55 KiB
Python
"""Compare settings live ("part-screen rendering"): one picture cut into 2 to 4 strips, each strip drawn with a
|
|
different choice of one setting, with its name and its measured cost on it, in step (the same game frame in every
|
|
strip). The C key (or the Compare tab of the overlay) turns it on; Shift+C goes to the next thing to compare.
|
|
|
|
What can be compared (a "dimension") and its choices ("variants"):
|
|
|
|
- "aa", Anti-aliasing: Off, FXAA, SMAA-style, CAS sharpening (framegen/aa.py). Drawn at the game's size, before the
|
|
upscaler, by the pipeline (Composer), like the setting itself.
|
|
- "scaler", Upscaler: Off (the game's pixels enlarged as they are, nearest neighbour: Upscaler Off itself shows the
|
|
picture small, in the middle, which a strip would mostly miss), Bilinear, AMD FSR 1 (at your sharpening, or at each of its levels), NVIDIA RTX VSR. Drawn
|
|
by the video window (framegen/io.py), each variant on the whole picture, then its strip cut out.
|
|
- "framegen", Frame generation: Off (the game's own frames, each held until the next) against On (your multiplier and
|
|
model), or a smaller multiplier shown from the same run (every 2nd frame of a 4x run is a real 2x). Two AI models
|
|
can't run at once: the one not running is shown as unavailable, with why.
|
|
- "look", Look: Off against the look picked in the settings (framegen/looks.py), drawn by the video window.
|
|
|
|
A variant that can't run here (RTX VSR without NVIDIA's SDK, a model that isn't the one running) gets a black strip
|
|
with its name and why: never another variant in its place.
|
|
|
|
This file holds the logic, without a GPU or a window: the choices and their names, what is available (why_not), the
|
|
layouts and where the dividers go (rects, dividers), the label text and the timings (Timings), putting strips together
|
|
(compose, for numpy and torch alike), the frame generation strips (FrameGenStrips) and the labels and dividers as
|
|
images (overlay_items, drawn with framegen/ui_draw.py). The settings rows are in framegen/settings.py ("Compare").
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import collections
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
|
|
DIMENSIONS = ("aa", "scaler", "framegen", "look")
|
|
DIM_NAMES = {"aa": "Anti-aliasing", "scaler": "Upscaler", "framegen": "Frame generation", "look": "Look"}
|
|
DIM_ALIASES = {"aa": "aa", "antialiasing": "aa", "anti-aliasing": "aa", "scaler": "scaler", "upscaler": "scaler",
|
|
"upscaling": "scaler", "framegen": "framegen", "fg": "framegen", "frame-generation": "framegen",
|
|
"interp": "framegen", "look": "look", "looks": "look"}
|
|
|
|
FSR_LEVELS = {"fsr-max": 0.0, "fsr-high": 0.25, "fsr-medium": 0.5, "fsr-low": 1.0, "fsr-minimal": 2.0}
|
|
VARIANTS: dict[str, tuple[str, ...]] = {
|
|
"aa": ("off", "fxaa", "smaa", "cas"),
|
|
"scaler": ("off", "bilinear", "fsr", *FSR_LEVELS, "vsr"),
|
|
"framegen": ("off", "on", "2x", "3x", "4x", "rife", "vfg"),
|
|
"look": ("off", "on"),
|
|
}
|
|
NAMES: dict[str, dict[str, str]] = {
|
|
"aa": {"off": "Off", "fxaa": "FXAA", "smaa": "SMAA-style", "cas": "CAS sharpen"},
|
|
"scaler": {"off": "Off (nearest)", "bilinear": "Bilinear", "fsr": "FSR 1", "fsr-max": "FSR 1 Max", "fsr-high": "FSR 1 High",
|
|
"fsr-medium": "FSR 1 Medium", "fsr-low": "FSR 1 Low", "fsr-minimal": "FSR 1 Minimal",
|
|
"vsr": "RTX VSR"},
|
|
"framegen": {"off": "Off", "on": "On", "2x": "2x", "3x": "3x", "4x": "4x", "rife": "RIFE", "vfg": "NVIDIA VFG"},
|
|
"look": {"off": "Off", "on": "Look"},
|
|
}
|
|
# the strips' choices before the player picks any (strip 1, 2, 3, 4)
|
|
DEFAULTS = {"aa": ("off", "fxaa", "smaa", "cas"), "scaler": ("off", "bilinear", "fsr", "vsr"),
|
|
"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": "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 <version>
|
|
|
|
|
|
# what the launcher offers to start a game with, one per dimension (registry() below; framegen.settings prints it)
|
|
SUGGESTED = {"aa": ("off", "fxaa", "smaa", "cas"), "scaler": ("off", "bilinear", "fsr", "vsr"),
|
|
"framegen": ("off", "on"), "look": ("off", "on")}
|
|
|
|
|
|
def registry() -> dict:
|
|
"""--compare as the launcher builds it: the spelling, each dimension's choices (in order, with names) and how many
|
|
strips it takes, and the comparison to suggest. The launcher keeps no copy of these (settings.specs_json)."""
|
|
return {"syntax": "<dimension>:<choice>,<choice>,...",
|
|
"dimensions": [{"key": d, "name": DIM_NAMES[d], "max": MAX_STRIPS[d], "suggested": list(SUGGESTED[d]),
|
|
"choices": [{"value": v, "name": NAMES[d][v]} for v in VARIANTS[d]]}
|
|
for d in DIMENSIONS]}
|
|
|
|
|
|
def strip_key(dim: str, i: int) -> str:
|
|
"""The setting that holds strip i's choice (1-based) for this dimension."""
|
|
return f"compare_{dim}_{i}"
|
|
|
|
|
|
def parse(spec: str) -> tuple[str, list[str]]:
|
|
"""--compare "<dimension>:<v1>,<v2>,...": ("aa", ["off", "fxaa"]). The dimension alone takes its defaults."""
|
|
dim_s, _, rest = spec.strip().partition(":")
|
|
dim = DIM_ALIASES.get(dim_s.strip().lower())
|
|
if dim is None:
|
|
raise ValueError(f"--compare: {dim_s!r} isn't something to compare: one of {', '.join(DIMENSIONS)}")
|
|
picks = [v.strip().lower() for v in rest.split(",") if v.strip()] if rest.strip() else list(DEFAULTS[dim][:2])
|
|
picks = ["off" if p == "none" else p for p in picks]
|
|
bad = [p for p in picks if p not in VARIANTS[dim]]
|
|
if bad:
|
|
raise ValueError(f"--compare: {', '.join(bad)} isn't a choice for {DIM_NAMES[dim]}: "
|
|
f"{', '.join(VARIANTS[dim])}")
|
|
if not 2 <= len(picks) <= MAX_STRIPS[dim]:
|
|
raise ValueError(f"--compare: {DIM_NAMES[dim]} takes 2 to {MAX_STRIPS[dim]} choices, not {len(picks)}")
|
|
return dim, picks
|
|
|
|
|
|
def settings_for(spec: str) -> dict:
|
|
"""The settings --compare sets: Compare on, the dimension, the number of strips and each strip's choice."""
|
|
dim, picks = parse(spec)
|
|
out = {"compare": True, "compare_dim": dim, "compare_strips": len(picks)}
|
|
out.update({strip_key(dim, i + 1): v for i, v in enumerate(picks)})
|
|
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:
|
|
"""What this machine and session can draw, for why_not. scalers: the upscalers the window has ("off", "bilinear",
|
|
"fsr", "vsr"); scaler_why: why one isn't there. interp: frame generation on; model: the one running ("4.22.lite",
|
|
"vfg"); multiplier: frames shown per game frame (2 = 2x); look: the look's name ("" = none can be drawn) and
|
|
look_why. window: the upscaler and look comparisons need the video window (or devtools/compare_shot.py's GL)."""
|
|
scalers: tuple = ("off", "bilinear", "fsr", "vsr")
|
|
scaler_why: dict = field(default_factory=dict)
|
|
interp: bool = True
|
|
interp_why: str = ""
|
|
model: str = "4.22.lite"
|
|
models: tuple = ("4.22.lite", "vfg")
|
|
multiplier: int = 2
|
|
look: str = "Look"
|
|
look_why: str = ""
|
|
window: bool = True
|
|
private: bool = False # NVIDIA VFG or NVIDIA's RTX VSR package runs: its numbers stay on screen (its licence),
|
|
# never in a saved clip
|
|
|
|
|
|
def model_name(model: str) -> str:
|
|
return MODEL_NAMES.get(model, f"RIFE {model}")
|
|
|
|
|
|
def multiplier_of(variant: str) -> int | None:
|
|
return int(variant[:-1]) if variant.endswith("x") and variant[:-1].isdigit() else None
|
|
|
|
|
|
def why_not(dim: str, variant: str, caps: Caps) -> str | None:
|
|
"""Why this variant can't be shown here, or None when it can."""
|
|
if dim in ("scaler", "look") and not caps.window:
|
|
return "Needs the video window's OpenGL"
|
|
if dim == "scaler":
|
|
mode = "fsr" if variant in FSR_LEVELS else variant
|
|
if mode not in caps.scalers:
|
|
return caps.scaler_why.get(mode) or f"{NAMES['scaler'][variant]} isn't available here"
|
|
return None
|
|
if dim == "look":
|
|
if variant == "on" and not caps.look:
|
|
return caps.look_why or "No look can be drawn here"
|
|
return None
|
|
if dim == "framegen":
|
|
if variant == "off":
|
|
return None
|
|
if not caps.interp:
|
|
return caps.interp_why or "Frame generation is off: turn it on to compare"
|
|
if variant in ("rife", "vfg"):
|
|
running = "vfg" if caps.model == "vfg" else "rife"
|
|
if variant != running:
|
|
if variant == "vfg" and "vfg" not in caps.models:
|
|
return "NVIDIA VFG isn't set up on this PC"
|
|
return (f"One AI model runs at a time: this is {model_name(caps.model)}. "
|
|
f"Pick {NAMES['framegen'][variant]} in Interpolation model to see it")
|
|
return None
|
|
m = multiplier_of(variant)
|
|
if m is not None:
|
|
if m > caps.multiplier:
|
|
return f"Above the {caps.multiplier}x running now: raise the Frame multiplier to see it"
|
|
if caps.multiplier % m:
|
|
return f"Not a part of the {caps.multiplier}x running now (try {caps.multiplier}x or a divisor of it)"
|
|
return None
|
|
return None # aa: runs anywhere (GPU or the CPU fallback)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Strip:
|
|
variant: str
|
|
name: str
|
|
why: str | None = None # unavailable: why
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Plan:
|
|
dim: str
|
|
strips: tuple[Strip, ...]
|
|
layout: str = "columns"
|
|
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, 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")
|
|
if dim not in DIMENSIONS:
|
|
dim = "aa"
|
|
n = max(2, min(int(values.get("compare_strips", 2)), MAX_STRIPS[dim]))
|
|
strips = []
|
|
for i in range(n):
|
|
v = values.get(strip_key(dim, i + 1), DEFAULTS[dim][i])
|
|
if v not in VARIANTS[dim]:
|
|
v = DEFAULTS[dim][i]
|
|
strips.append(Strip(v, variant_name(dim, v, caps), why_not(dim, v, caps)))
|
|
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:
|
|
"""The strip's title: "FXAA", "FSR 1 High", "2x", "On (3x RIFE 4.22.lite)"."""
|
|
if dim == "framegen" and caps is not None and variant == "on":
|
|
return f"{caps.multiplier}x {model_name(caps.model)}"
|
|
if dim == "look" and caps is not None and variant == "on" and caps.look:
|
|
return caps.look
|
|
return NAMES[dim].get(variant, variant)
|
|
|
|
|
|
# ---- where the strips go -----------------------------------------------------------------------------------------
|
|
Rect = tuple[int, int, int, int] # x0, y0, x1, y1 in the picture's pixels, y down, x1/y1 not included
|
|
|
|
|
|
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)]
|
|
|
|
|
|
@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). 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":
|
|
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":
|
|
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]]
|
|
|
|
|
|
def drag_split(layout: str, x: float, y: float, w: int, h: int) -> float:
|
|
"""The divider dragged to (x, y) in the picture: the new split (2 strips, side by side or stacked)."""
|
|
t = (y / h) if layout == "rows" else (x / w)
|
|
return min(0.95, max(0.05, t))
|
|
|
|
|
|
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" 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 _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()
|
|
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
|
|
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
|
|
|
|
|
|
# ---- timings -----------------------------------------------------------------------------------------------------
|
|
class Timings:
|
|
"""Each variant's cost per frame, over the last WINDOW frames: average and worst, in ms."""
|
|
|
|
def __init__(self, n: int = WINDOW) -> None:
|
|
self.n = n
|
|
self._ms: dict[str, collections.deque] = {}
|
|
|
|
def add(self, key: str, ms: float) -> None:
|
|
self._ms.setdefault(key, collections.deque(maxlen=self.n)).append(float(ms))
|
|
|
|
def stat(self, key: str) -> tuple[float, float] | None:
|
|
d = self._ms.get(key)
|
|
if not d:
|
|
return None
|
|
return sum(d) / len(d), max(d)
|
|
|
|
def text(self, key: str) -> str:
|
|
s = self.stat(key)
|
|
return "" if s is None else f"{s[0]:.2f} / {s[1]:.2f} ms"
|
|
|
|
def clear(self) -> None:
|
|
self._ms.clear()
|
|
|
|
|
|
def timing_key(dim: str, variant: str) -> str:
|
|
return f"{dim}:{variant}"
|
|
|
|
|
|
def labels(p: Plan, timings: Timings, rates: dict | None = None, caps: Caps | None = None) -> list[tuple[str, str]]:
|
|
"""(title, second line) for each strip. The second line is the measured cost ("0.40 / 0.42 ms": average / worst
|
|
over the last 120 frames), for frame generation the measured frame rate of each side and the AI's time per frame,
|
|
or why the strip is unavailable. rates: {"game": fps, "shown": fps} as measured by the pipeline."""
|
|
rates = rates or {}
|
|
out = []
|
|
for s in p.strips:
|
|
if s.why:
|
|
out.append((s.name, f"Unavailable: {s.why}"))
|
|
continue
|
|
if p.dim == "framegen":
|
|
fps = strip_fps(s.variant, rates, caps)
|
|
line = f"{fps:.0f} fps" if fps else ""
|
|
if s.variant != "off" and p.timings:
|
|
t = timings.text(timing_key("framegen", "ai"))
|
|
if t:
|
|
line = f"{line} · AI {t}" if line else f"AI {t}"
|
|
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."""
|
|
game, shown = rates.get("game"), rates.get("shown")
|
|
if variant == "off":
|
|
return game
|
|
m = multiplier_of(variant)
|
|
if m is not None and caps is not None and caps.multiplier and shown:
|
|
return shown * m / caps.multiplier
|
|
return shown
|
|
|
|
|
|
# ---- frame generation strips -------------------------------------------------------------------------------------
|
|
def _copy_into(dst, src):
|
|
if dst is None or tuple(dst.shape) != tuple(src.shape) or type(dst) is not type(src) or (
|
|
hasattr(src, "device") and getattr(dst, "device", None) != src.device):
|
|
return src.clone() if hasattr(src, "clone") else src.copy()
|
|
dst[...] = src
|
|
return dst
|
|
|
|
|
|
class FrameGenStrips:
|
|
"""The frame generation comparison, fed every frame the window is about to show, in order. "Off" strips show
|
|
the game's own frames only, each held until the next (as with frame generation off), from the same timeline as
|
|
the generated ones, so both sides stay in step; "On" strips show every frame; a smaller multiplier (2x of a 4x
|
|
run) shows every k-th frame, held. present() returns the picture to show."""
|
|
|
|
def __init__(self) -> None:
|
|
self._real = None # the game's latest frame shown so far (a copy)
|
|
self._held: dict[int, object] = {} # strip -> its last frame (smaller multipliers)
|
|
self._out = None
|
|
self._count = 0
|
|
|
|
def reset(self) -> None:
|
|
self._real, self._held, self._out, self._count = None, {}, None, 0
|
|
|
|
def real(self, frame) -> None:
|
|
"""The game's own frame that the timeline has reached (call before present(), for real frames and for
|
|
generated ones whose earlier real frame is new)."""
|
|
self._real = _copy_into(self._real, frame)
|
|
|
|
def present(self, frame, p: Plan, multiplier: int, w: int, h: int):
|
|
self._count += 1
|
|
images = []
|
|
for i, s in enumerate(p.strips):
|
|
if s.why or s.variant == "off":
|
|
images.append(None if s.why else (self._real if self._real is not None else frame))
|
|
continue
|
|
m = multiplier_of(s.variant)
|
|
if m is not None and m < multiplier:
|
|
k = multiplier // m
|
|
if (self._count - 1) % k == 0 or i not in self._held:
|
|
self._held[i] = _copy_into(self._held.get(i), frame)
|
|
images.append(self._held[i])
|
|
continue
|
|
images.append(frame)
|
|
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, draws(p, w, h), self._out)
|
|
|
|
|
|
# ---- anti-aliasing strips ----------------------------------------------------------------------------------------
|
|
def _sync(frame) -> None:
|
|
if hasattr(frame, "is_cuda") and frame.is_cuda:
|
|
import torch
|
|
torch.cuda.synchronize(frame.device)
|
|
|
|
|
|
def aa_strips(frame, p: Plan, timings: Timings, out=None, gpu: bool = True):
|
|
"""The anti-aliasing comparison: each variant run on the whole frame (so its time is its real cost per frame,
|
|
including the trip to the GPU and back for a frame on the CPU), then its strip taken. Returns the picture to
|
|
show. gpu=False: a numpy frame stays on the CPU."""
|
|
from . import aa
|
|
h, w = frame.shape[:2]
|
|
images = []
|
|
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":
|
|
images.append(frame)
|
|
continue
|
|
_sync(frame)
|
|
t0 = time.perf_counter()
|
|
im = aa.apply(frame, s.variant, gpu)
|
|
_sync(im)
|
|
timings.add(timing_key("aa", s.variant), (time.perf_counter() - t0) * 1000)
|
|
images.append(im)
|
|
return compose(images, draws(p, w, h), out)
|
|
|
|
|
|
# ---- labels and dividers -----------------------------------------------------------------------------------------
|
|
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) 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
|
|
img[:, 1:-1, :3] = (235, 238, 245)
|
|
img[:, [0, -1], 3] = 140
|
|
items.append((x0 - img.shape[1] // 2, y0, img))
|
|
else:
|
|
img = np.zeros((line + 2, x1 - x0, 4), np.uint8)
|
|
img[:, :, 3] = 255
|
|
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 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 []
|
|
bw = min(room, px(24) + max([U.text_w(title, f_title)] + [U.text_w(s, f_sub) for s in subs]))
|
|
bh = px(44) + px(23) * len(subs)
|
|
c = U.Canvas(bw, bh, U.BG, px(9), border=U.BORDER)
|
|
c.text(bw // 2, px(22), title, f_title, U.TIGHT if sub.startswith("Unavailable") else U.TEXT, anchor="mm")
|
|
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")
|
|
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
|
|
|
|
|
|
def blend(img, items):
|
|
"""The items drawn over img (HxWx3 BGR uint8, numpy; a copy is returned): for stills and clips."""
|
|
import numpy as np
|
|
out = img.copy()
|
|
h, w = out.shape[:2]
|
|
for x, y, rgba in items:
|
|
ih, iw = rgba.shape[:2]
|
|
ax0, ay0, ax1, ay1 = max(0, x), max(0, y), min(w, x + iw), min(h, y + ih)
|
|
if ax1 <= ax0 or ay1 <= ay0:
|
|
continue
|
|
part = rgba[ay0 - y:ay1 - y, ax0 - x:ax1 - x].astype(np.float32)
|
|
a = part[..., 3:4] / 255.0
|
|
bgr = part[..., 2::-1]
|
|
dst = out[ay0:ay1, ax0:ax1].astype(np.float32)
|
|
out[ay0:ay1, ax0:ax1] = (dst * (1.0 - a) + bgr * a + 0.5).astype(np.uint8)
|
|
return out
|
|
|
|
|
|
# ---- while playing -----------------------------------------------------------------------------------------------
|
|
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). 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 = 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 == "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, [])
|
|
|
|
def plan(self) -> Plan | None:
|
|
if not self.settings.compare:
|
|
return None
|
|
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()
|
|
when, was, texts = self._texts
|
|
if was != p or now - when >= self.LABEL_EVERY:
|
|
texts = labels(p, self.timings, self.rates, self.caps())
|
|
self._texts = (now, p, texts)
|
|
return texts
|
|
|
|
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), self.hint)
|
|
if self._items[0] != key:
|
|
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). 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 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)
|
|
if real is not None:
|
|
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."""
|
|
if p is None or p.dim not in SOURCE_SIDE or not self.settings.compare_clips:
|
|
return frame
|
|
if p.timings and self.caps().private:
|
|
from dataclasses import replace
|
|
p = replace(p, timings=False)
|
|
host = shown.cpu().numpy() if hasattr(shown, "cpu") else shown
|
|
h = host.shape[0]
|
|
return blend(host, self.items(p, host.shape[1], h, max(0.5, h / 1080)))
|
|
|
|
def multiplier(self) -> int:
|
|
"""Frames shown per game frame now (1: frame generation off)."""
|
|
st = self.settings
|
|
if not st.interp:
|
|
return 1
|
|
return max(1, int(st.hz) // (60 if self.game60 else 30))
|