Files

401 lines
19 KiB
Python

"""The performance overlay and the messages over the picture, as images (framegen/ui_draw.py draws them, the GL window
blits them): stats in four styles (settings "overlay_style": Minimal, Detailed, Graphs, Bar), the benchmark's result card
and toast().
Each takes the pipeline's io.MiniText (its parts, health, second line, details and graph data), `ui` (1.0 at 1080p,
times the settings' size) and `opacity` (how solid the background is; text and graph lines stay solid), and returns
an RGBA image with rounded corners.
The numbers come as io.MiniText.cells (framegen/stats.py Cell): each has a name, a value, a unit and a colour level, and a
`hint`, the widest the value gets. Every cell sits in a slot as wide as its hint, the value right-aligned in it, so the
overlay's size and its numbers' places don't change as digits do (digits are tabular in the fonts Summit uses).
"""
from __future__ import annotations
import numpy as np
from . import stats as S
from . import ui_draw as U
PART = {"main": U.TEXT, "dim": U.DIM, "warn": U.TIGHT} # io.MiniText part kinds
def _px(ui: float):
return lambda v: max(1, int(round(v * ui)))
def _parts_width(parts, f_main, f_rest, gap: int) -> int:
return sum(U.text_w(t, f_main if k == "main" else f_rest) for t, k in parts) + gap * max(0, len(parts) - 1)
def _draw_parts(c: U.Canvas, x: int, y: int, parts, f_main, f_rest, gap: int) -> int:
for text, kind in parts:
x += c.text(x, y, text, f_main if kind == "main" else f_rest, PART.get(kind, U.DIM)) + gap
return x - gap
LEVEL = {"good": U.GOOD, "tight": U.TIGHT, "bad": U.BAD, "": U.TEXT} # stats.Cell.level -> the value's colour
class _Fonts:
def __init__(self, px) -> None:
self.val, self.name, self.unit = U.font(px(15), "semibold"), U.font(px(12)), U.font(px(12))
self.row_val, self.row_name = U.font(px(13), "medium"), U.font(px(12))
def _val_w(c, f) -> int:
"""The width of a cell's value slot: its widest, so the slot never changes with the digits."""
return max(U.text_w(c.value, f), U.text_w(c.hint, f))
def _cell_w(c, f: _Fonts, sep: int) -> int:
w = _val_w(c, f.val)
if c.name:
w += U.text_w(c.name, f.name) + sep
if c.unit:
w += U.text_w(c.unit, f.unit) + max(1, sep // 3)
return w
def _draw_cell(cv: U.Canvas, x: int, y: int, c, f: _Fonts, sep: int) -> int:
"""A cell on a line, left-middle at (x, y): its name, the value right-aligned in its slot, its unit. Returns its width."""
x0 = x
if c.name:
x += cv.text(x, y, c.name, f.name, U.FAINT if c.key not in ("bench",) else U.TIGHT) + sep
vw = _val_w(c, f.val)
cv.text(x + vw, y, c.value, f.val, LEVEL.get(c.level, U.TEXT), "rm")
x += vw
if c.unit:
x += max(1, sep // 3)
x += cv.text(x, y + 1, c.unit, f.unit, U.DIM)
return x - x0
def _flow(cells, f: _Fonts, sep: int, gap: int, room: int) -> list[list]:
"""The cells as lines no wider than `room`."""
lines, line, w = [], [], 0
for c in cells:
cw = _cell_w(c, f, sep)
if line and w + gap + cw > room:
lines.append(line)
line, w = [], 0
w += (gap if line else 0) + cw
line.append(c)
return lines + ([line] if line else [])
def _rows(rows, f: _Fonts, px, cv: U.Canvas | None, x0: int, y0: int, line_h: int, colw: list | None = None):
"""Detailed's rows in one or two columns. With cv=None just measures: returns (width, height, column widths)."""
cols = [rows] if len(rows) <= 9 else [rows[: (len(rows) + 1) // 2], rows[(len(rows) + 1) // 2:]]
widths = []
for col in cols:
nw = max((U.text_w(c.name, f.row_name) for c in col), default=0)
vw = max((max(U.text_w(c.value, f.row_val), U.text_w(c.hint, f.row_val)) + (U.text_w(c.unit, f.unit) + px(4) if c.unit else 0)
+ (px(10) + U.text_w(c.detail_name, f.unit) + px(4) + max(U.text_w(c.detail, f.row_val), U.text_w("88.8", f.row_val))
if c.detail_name else 0) for c in col), default=0)
widths.append((nw, vw))
total = sum(nw + px(14) + vw for nw, vw in widths) + px(26) * (len(cols) - 1)
if cv is None:
return total, max(len(c) for c in cols) * line_h, widths
x = x0
for col, (nw, vw) in zip(cols, widths):
for i, c in enumerate(col):
y = y0 + i * line_h + line_h // 2
cv.text(x, y, c.name, f.row_name, U.FAINT)
vx = x + nw + px(14)
if c.key in ("config",) or (c.hint == "" and c.unit == ""): # words: left-aligned
cv.text(vx, y, c.value, f.row_val, U.DIM)
continue
num_w = max(U.text_w(c.value, f.row_val), U.text_w(c.hint, f.row_val))
cv.text(vx + num_w, y, c.value, f.row_val, LEVEL.get(c.level, U.TEXT), "rm")
ex = vx + num_w
if c.unit:
ex += px(4) + cv.text(vx + num_w + px(4), y + 1, c.unit, f.unit, U.DIM)
if c.detail_name:
ex += px(10)
ex += cv.text(ex, y + 1, c.detail_name, f.unit, U.FAINT) + px(4)
dw = max(U.text_w(c.detail, f.row_val), U.text_w("88.8", f.row_val))
cv.text(ex + dw, y, c.detail, f.row_val, U.DIM, "rm")
x += nw + px(14) + vw + px(26)
return total, max(len(c) for c in cols) * line_h, widths
def stats(t, ui: float = 1.0, opacity: float = 1.0, details=()) -> np.ndarray:
"""Minimal: a pill with a dot (green keeping up, yellow tight, red falling behind) and the numbers (t.cells), in
lines if there are many. A second line (the test line, while a test runs) goes under them. Detailed: the same
header with rows under it (t.rows, or `details`, (name, value) pairs, for the old kind of text)."""
cells, rows = getattr(t, "cells", None), list(getattr(t, "rows", None) or ())
if cells is None: # numbers as parts, from a caller that has no cells
return _stats_parts(t, ui, opacity, details)
px = _px(ui)
f = _Fonts(px)
f_small = U.font(px(12))
pad, gap, sep, r = px(13), px(13), px(5), px(5)
dot_w = 2 * r + px(9)
lines = _flow(cells, f, sep, gap, px(620) - dot_w)
second = U.wrap(t.second, f_small, px(520)) if t.second else []
row_h, small_row = px(32), px(19)
line_w = max((sum(_cell_w(c, f, sep) for c in ln) + gap * (len(ln) - 1) for ln in lines), default=0) + dot_w
rows_w, rows_h = (_rows(rows, f, px, None, 0, 0, small_row)[:2]) if rows else (0, 0)
w = 2 * pad + max([line_w, rows_w] + [U.text_w(x, f_small) for x in second])
head_h = row_h + (len(lines) - 1) * px(26)
extra = rows_h + len(second) * small_row
h = head_h + (extra + px(10) + (px(6) if rows and second else 0) if extra else 0)
c = U.Canvas(w, h, U.BG, row_h // 2 if not extra and len(lines) <= 1 else px(12), border=U.BORDER)
c.circle(pad + r, row_h // 2, r, U.HEALTH.get(t.health, U.FAINT))
for i, ln in enumerate(lines):
x, y = pad + dot_w, row_h // 2 + i * px(26)
for cell in ln:
x += _draw_cell(c, x, y, cell, f, sep) + gap
y = head_h - px(2)
if rows:
c.line(pad, y, w - pad, y, U.BORDER, 1)
_rows(rows, f, px, c, pad, y + px(5), small_row)
y += rows_h + px(10)
elif extra:
y += px(8)
y += px(6) if rows and second else 0
for s in second:
c.text(pad, y + small_row // 2, s, f_small, U.TIGHT)
y += small_row
return c.rgba(opacity)
def bar(t, width: int, ui: float = 1.0, opacity: float = 1.0) -> np.ndarray:
"""The Bar style: one line as wide as the picture (`width`), the dot and then the cells (t.cells) with thin dividers,
as many as fit: the last ones are left out when the picture is narrow."""
px = _px(ui)
f = _Fonts(px)
pad, gap, sep, r = px(14), px(14), px(5), px(5)
h = px(30)
c = U.Canvas(max(1, width), h, U.BG, 0, border=None)
c.circle(pad + r, h // 2, r, U.HEALTH.get(t.health, U.FAINT))
x = pad + 2 * r + px(10)
shown = 0
for cell in t.cells:
cw = _cell_w(cell, f, sep)
if x + cw + pad > width:
break
if shown:
c.line(x - gap // 2, px(8), x - gap // 2, h - px(8), U.BORDER, 1)
x += _draw_cell(c, x, h // 2, cell, f, sep) + gap
shown += 1
if t.second: # a test's line, if there is room: at the right end
c.text(width - pad, h // 2, U.fit(t.second, U.font(px(12)), max(0, width - x - pad)), U.font(px(12)), U.TIGHT, "rm")
return c.rgba(opacity)
def _stats_parts(t, ui: float = 1.0, opacity: float = 1.0, details=()) -> np.ndarray:
"""Minimal: a pill with a dot (green keeping up, yellow tight, red falling behind) and a few numbers. A second
line (the test line, while a test runs) goes under them. Detailed: the same with `details`, (name, value) rows,
under it."""
px = _px(ui)
f_main, f_rest = U.font(px(15), "semibold"), U.font(px(14))
f_small, f_name = U.font(px(12)), U.font(px(12))
pad, gap, r = px(13), px(11), px(5)
line_w = 2 * r + px(9) + _parts_width(t.parts, f_main, f_rest, gap)
second = U.wrap(t.second, f_small, px(520)) if t.second else []
details = [(n, v) for n, v in details if v]
name_w = max((U.text_w(n, f_name) for n, _ in details), default=0)
detail_w = max((name_w + px(16) + U.text_w(v, f_small) for _, v in details), default=0)
w = 2 * pad + max([line_w, detail_w] + [U.text_w(s, f_small) for s in second])
row, small_row = px(32), px(19)
extra = len(second) * small_row + len(details) * small_row
h = row + (extra + px(8) + (px(8) if details and second else 0) if extra else 0)
c = U.Canvas(w, h, U.BG, row // 2 if not extra else px(12), border=U.BORDER)
cy = row // 2
c.circle(pad + r, cy, r, U.HEALTH.get(t.health, U.FAINT))
_draw_parts(c, pad + 2 * r + px(9), cy, t.parts, f_main, f_rest, gap)
y = row - px(2)
if details:
c.line(pad, y, w - pad, y, U.BORDER, 1)
y += px(3)
for name, value in details:
y += small_row
c.text(pad, y - small_row // 2 + px(2), name, f_name, U.FAINT)
c.text(pad + name_w + px(16), y - small_row // 2 + px(2), value, f_small, U.DIM)
y += px(8) if details and second else 0
for s in second:
y += small_row
c.text(pad, y - small_row // 2, s, f_small, U.TIGHT)
return c.rgba(opacity)
def _plot(w: int, h: int, series, vmax: float, colour, target: float | None = None) -> np.ndarray:
"""A bar graph as an RGB image: one column per sample, newest on the right, coloured by `colour(values)` (an
array of RGB rows), with a line at `target` (the budget)."""
img = np.empty((h, w, 3), np.uint8)
img[:] = U.SURFACE
v = np.asarray(list(series)[-w:], np.float32)
if v.size:
bars = np.clip(np.round(np.minimum(v, vmax) / vmax * (h - 1)), 1, h).astype(np.int32)
fill = np.arange(h)[::-1, None] < bars[None, :] # row 0 is the top
img[:, w - v.size:][fill] = np.broadcast_to(colour(v)[None, :, :], (h, v.size, 3))[fill]
if target is not None and 0 < target < vmax:
img[h - 1 - int(round(target / vmax * (h - 1)))] = U.DIM
return img
def _levels(v: np.ndarray, good: float, tight: float) -> np.ndarray:
"""Green up to `good`, yellow up to `tight`, red above, as RGB rows."""
out = np.empty((v.size, 3), np.uint8)
out[:] = U.BAD
out[v <= tight] = U.TIGHT
out[v <= good] = U.GOOD
return out
def graphs(t, frametimes, ui: float = 1.0, opacity: float = 1.0, gpu=None) -> np.ndarray:
"""Graphs, like MangoHud's: the frame rate in big numbers, then a graph each for the time between frames on screen
(what you see), the pipeline's time per tick against its budget, Summit's delay, and the graphics card's load.
t.graph, from the pipeline: hz, tick_ms (the budget), busy, delay (lists, newest last), show (the rows the
settings leave on). frametimes: milliseconds between the window's last presents. gpu: framegen.gpustats.GpuStats."""
from PIL import Image
px = _px(ui)
g = t.graph
f_big, f_main, f_rest = U.font(px(26), "bold"), U.font(px(15), "semibold"), U.font(px(13))
f_name, f_num = U.font(px(12), "semibold"), U.font(px(12))
pad, gw, gh, gap = px(14), px(320), px(44), px(10)
target = 1000.0 / max(1, g.get("hz", 60))
tick = g.get("tick_ms", 1000 / 60)
ft = list(frametimes)[-gw:]
rows = [("frametime", "Frametime", ft, max(3 * target, float(np.percentile(ft, 99)) * 1.15 if ft else 3 * target),
target, lambda v: _levels(v, 1.35 * target, 2.2 * target)),
("pipeline", "Pipeline", g.get("busy", [])[-gw:], 2 * tick, tick, lambda v: _levels(v, 0.75 * tick, tick)),
("delay", "Delay", g.get("delay", [])[-gw:], 120.0, None, lambda v: _levels(v, 45.0, 80.0))]
show = g.get("show")
if show is not None: # the rows the settings turn off
rows = [r for r in rows if r[0] in show]
gpu = gpu if "gpu" in show else None
gpu_d = gpu.latest if gpu is not None else None
second = U.wrap(t.second, f_num, gw) if t.second else []
head, label_h, gpu_h = px(40), px(20), px(24)
w = 2 * pad + gw
h = (px(8) + head + len(rows) * (label_h + gh + gap) + (label_h + gpu_h + px(18) + gap if gpu_d else 0)
+ len(second) * px(18) + px(6))
c = U.Canvas(w, h, U.BG, px(14), border=U.BORDER)
y = px(8) + head // 2
c.circle(pad + px(5), y, px(5), U.HEALTH.get(t.health, U.FAINT))
x = pad + px(18)
for text, kind in t.parts: # the frame rate big, the rest beside it
if kind == "main" and text.endswith(" fps"):
x += c.text(x, y, text[:-4], f_big, U.TEXT) + px(5)
x += c.text(x, y + px(4), "fps", f_main, U.DIM) + px(14)
else:
x += c.text(x, y + px(4), text, f_rest, PART.get(kind, U.DIM)) + px(12)
y = px(8) + head
def plot(series, vmax, colour, tgt, height) -> None:
nonlocal y
c.img.paste(Image.fromarray(_plot(gw, height, series, max(vmax, 1.0), colour, tgt)), (pad, y))
y += height + gap
for _key, name, series, vmax, tgt, colour in rows:
series = list(series)
if series:
last, avg = series[-1], sum(series) / len(series)
if name == "Frametime":
l1, l01 = (g["low1"], g["low01"]) if "low1" in g else S.lows(series) # the collector's window, if given
dash = lambda v: "--" if v is None else f"{v:.0f}" # noqa: E731
text = f"avg {avg:.1f} ms 1% low {dash(l1)} 0.1% {dash(l01)}"
elif name == "Pipeline":
text = f"{last:.1f} ms avg {avg:.1f} budget {tick:.1f}"
else:
text = f"{last:.0f} ms avg {avg:.0f} max {max(series):.0f}"
else:
text = "-"
c.text(pad, y + label_h // 2 - px(1), name, f_name, U.TEXT)
c.text(w - pad, y + label_h // 2 - px(1), text, f_num, U.DIM, "rm")
y += label_h
plot(series, vmax, colour, tgt, gh)
if gpu_d:
c.text(pad, y + label_h // 2 - px(1), "Graphics card", f_name, U.TEXT)
c.text(w - pad, y + label_h // 2 - px(1), f"{gpu_d['util']:.0f}% {gpu_d['power']:.0f} W {gpu_d['temp']:.0f} C",
f_num, U.DIM, "rm")
y += label_h
plot(list(gpu.util), 100.0, lambda v: _levels(v, 80.0, 95.0), None, gpu_h)
c.text(pad, y - gap + px(11), f"{gpu_d['clock']:.0f} MHz memory {gpu_d['mem'] / 1024:.1f} of "
f"{gpu_d['mem_total'] / 1024:.0f} GB", f_num, U.FAINT)
y += px(18)
for s in second:
c.text(pad, y + px(8), s, f_num, U.TIGHT)
y += px(18)
return c.rgba(opacity, (U.SURFACE,))
def card(summary: dict, ui: float = 1.0, opacity: float = 1.0, saved: str = "") -> np.ndarray:
"""The benchmark's result card (and the session summary's): the big numbers, then the rest in a table. summary is
framegen.stats.Collector.summary(); `saved` is where the files went."""
px = _px(ui)
f_title, f_big = U.font(px(20), "bold"), U.font(px(34), "bold")
f_lab, f_row, f_val = U.font(px(12)), U.font(px(13)), U.font(px(14), "semibold")
pad, w = px(24), px(680)
fr, ft = summary["frames"], summary["frametime"]
sy, d = summary["system"], summary.get("delay")
v = lambda x, nd=0, unit="": "--" if x is None else f"{x:.{nd}f}{unit}" # noqa: E731
big = [("average", v(summary["fps_avg"]), "fps"), ("1% low", v(ft["low1_fps"]), "fps"),
("0.1% low", v(ft["low01_fps"]), "fps"), ("frametime", v(ft["avg_ms"], 1), "ms")]
rows = [("Worst frametime / jitter", f"{v(ft['worst_ms'], 1)} ms / {v(ft['jitter_ms'], 2)} ms"),
("Dropped / repeated / late", f"{fr['dropped']} / {fr['repeated']} / {fr['late']} of {fr['presented']} frames"),
("Generated share, game's rate", f"{v(fr['generated_share_pct'])}%, {v(fr['game_fps_avg'])} fps"),
("Delay (median / 95th)", "--" if not d else f"{v(d['median_ms'])} ms / {v(d['p95_ms'])} ms")]
for name in S.STAGES:
st = summary["stages"].get(name)
if st:
rows.append((S.STAGE_NAMES[name], f"{st['avg_ms']:.2f} ms avg, {st['worst_ms']:.1f} ms worst"))
rows.append(("Graphics card", f"{v(sy['gpu_util_avg_pct'])}% load, {v(sy['gpu_temp_max_c'])} C max, "
f"{v(sy['gpu_power_avg_w'])} W, {v(sy['vram_max_mb'] and sy['vram_max_mb'] / 1024, 1)} GB"))
sub = S.config_line(summary["config"]) or "settings unknown"
sub_lines = U.wrap(sub, f_lab, w - 2 * pad)
bench = summary.get("benchmark")
title = f"Benchmark result: {bench['seconds']} s" if bench else "Session summary"
row_h, big_h = px(24), px(78)
h = px(18) + px(30) + len(sub_lines) * px(18) + px(10) + big_h + px(8) + len(rows) * row_h + px(14) + (px(24) if saved else 0)
c = U.Canvas(w, h, U.BG, px(16), border=U.BORDER)
c.logo(pad, px(18), px(24))
y = px(18) + px(12)
c.text(pad + px(34), y, title, f_title, U.TEXT)
c.text(w - pad, y, f"{_clock(summary['duration_s'])} played", f_lab, U.DIM, "rm")
y += px(24)
for line in sub_lines:
c.text(pad, y, line, f_lab, U.DIM)
y += px(18)
y += px(10)
cw = (w - 2 * pad) // len(big)
for i, (name, val, unit) in enumerate(big):
x = pad + i * cw
c.rrect(x, y, x + cw - px(8), y + big_h, px(10), fill=U.SURFACE, outline=U.BORDER)
c.text(x + px(12), y + px(14), name, f_lab, U.FAINT)
n = c.text(x + px(12), y + px(46), val, f_big, U.TEXT)
c.text(x + px(12) + n + px(6), y + px(52), unit, f_lab, U.DIM)
y += big_h + px(8)
for name, text in rows:
y += row_h
c.text(pad, y - row_h // 2, name, f_row, U.FAINT)
c.text(w - pad, y - row_h // 2, text, f_val, U.TEXT, "rm")
c.line(pad, y, w - pad, y, U.BORDER, 1)
if saved:
c.text(pad, h - px(22), U.fit("Saved: " + saved, f_lab, w - 2 * pad), f_lab, U.DIM)
return c.rgba(opacity)
def _clock(seconds: float) -> str:
s = int(round(seconds))
return f"{s // 60}:{s % 60:02d}"
def toast(text: str, ui: float = 1.0, opacity: float = 1.0) -> np.ndarray:
"""A short message (one line, or a few split by newlines) on a rounded card with Summit's mark."""
px = _px(ui)
f = U.font(px(15), "medium")
lines = text.split("\n")
pad, mark, line_h = px(16), px(20), px(24)
w = pad + mark + px(12) + max(U.text_w(s, f) for s in lines) + pad + px(2)
h = len(lines) * line_h + px(22)
c = U.Canvas(w, h, U.BG, px(14), border=U.BORDER)
c.logo(pad, px(11) + (line_h - mark) // 2, mark)
for k, s in enumerate(lines):
c.text(pad + mark + px(12), px(11) + k * line_h + line_h // 2, s, f, U.TEXT if k == 0 else U.DIM)
return c.rgba(opacity)