Files
alex 893cc9e7d5 Anti-aliasing: FXAA and CAS as a GLSL pass in the video window (aa_gl.py), and a bench for both paths
Measured on the RTX 3090 (headless EGL, 1080p Voidrunner frame): GLSL FXAA 0.072 ms, CAS 0.022 ms against
torch (compiled) 0.99 and 1.03 ms. The window runs the setting this way unless OpenGL is software and CUDA is
there (SUMMIT_AA_GL=1/0 forces it); SMAA-style and the AA comparison stay torch.
2026-11-26 06:11:11 +00:00

134 lines
5.9 KiB
Python

"""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])