Created
May 1, 2019 13:59
-
-
Save raphlinus/8fa15590b40af2bdd37ff52437f66574 to your computer and use it in GitHub Desktop.
Research code to do RGB subpixel antialiasing using angle info in signed distance fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
# http://vcl.itn.liu.se/publications/2011/GS11/edtaa_preprint.pdf | |
def tex(df, cos_th): | |
cos_th = abs(cos_th) | |
sin_th = math.sqrt(1 - cos_th ** 2) | |
if cos_th < sin_th: | |
cos_th, sin_th = sin_th, cos_th | |
a1 = 0.5 * sin_th / cos_th # note: paper is missing the 0.5! | |
a2 = 1 - 2 * a1 | |
d1 = sin_th | |
d2 = math.sqrt(.5) * math.sin(0.25 * math.pi - math.asin(sin_th)) | |
if df <= -d1 - d2: | |
return 0 | |
elif df <= -d2: | |
return (d1 + d2 + df) ** 2 * (a1 / d1 ** 2) | |
elif df <= d2: | |
return a1 + (0.5 * a2) * (1 + df / d2) | |
elif df <= d1 + d2: | |
return 1 - (d1 + d2 - df) ** 2 * (a1 / d1 ** 2) | |
else: | |
return 1 | |
def tex_color(df, cos_th): | |
a = tex(df, cos_th) | |
delta = (0.5, -0.0968, -0.5) | |
strength = 1.5 * min(a, 1 - a) * cos_th | |
return [a + x * strength for x in delta] | |
def pcwalton_aa(df): | |
dist = -0.5 * df / 0.35355 | |
dist = -df | |
if dist < -0.5: | |
return 1 | |
elif dist > 0.5: | |
return 0 | |
return 0.5 + dist * (0.8431027 * dist ** 2 - 1.14453603) | |
def gen_tex(): | |
print('P2') | |
print('256 256') | |
print('256') | |
for y in range(256): | |
cos_th = (y - 128)/128.0 | |
for x in range(256): | |
df = (x - 128) / 128.0 / math.sqrt(2) | |
a = tex(df, cos_th) | |
print(math.floor(a * 255.0 + 0.5)) | |
def fan(): | |
w = 512 | |
h = 512 | |
print('P3') | |
print('%d %d' % (w, h)) | |
print('256') | |
n = 47 | |
for y in range(h): | |
for x in range(w): | |
df = 1e9 | |
best_cth = 0 | |
if False: | |
for i in range(n): | |
th = math.pi * i / n | |
cth = math.cos(th) | |
sth = math.sin(th) | |
d = (x - w/2) * cth - (y - h/2) * sth | |
dist = abs(d) | |
if dist < df: | |
df = dist | |
best_cth = cth * math.copysign(1, d) | |
else: | |
r = math.hypot(x - w/2, y - h/2) | |
df = r - 32 * math.floor(r / 32 + 0.5) | |
best_cth = math.cos(math.atan2(y - h/2, x - w/2)) * math.copysign(1, df) | |
df = abs(df) | |
#a = tex(2 - df, best_cth) | |
#a = pcwalton_aa(2 - df) | |
#a = (1 - a) ** 0.45 # todo: proper srgb conversion | |
#print(math.floor(a * 255.0 + 0.5)) | |
rgb = tex_color(1.25 - df, best_cth) | |
for x in rgb: | |
x = (1 - x) ** 0.45 | |
print(math.floor(x * 255.0 + 0.5)) | |
fan() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment