Created
November 12, 2022 20:44
-
-
Save danilw/c9cf7d1c630ca1ad1da10b9efc4621bd to your computer and use it in GitHub Desktop.
Shadertoy ML/Neural shaders optimization script
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 re | |
import os | |
import sys | |
# this script to convert floats in GLSL code to "less variative constants" | |
# set b_scale = <VALUE> example 64.0 | |
# floats in range 0-1 will be rescaled with float step 1/64 or 1/(b_scale step) | |
# exist to fix some ML/neural shaders, read more: | |
# https://github.com/danilw/danilw.github.io/tree/master/blog/decompiling_and_optimizing_nvidia_shaders | |
# tested only on Simple cases, like single function vec3 scene(vec4 p) from https://www.shadertoy.com/view/fl3BWB | |
# copy vec3 scene(vec4 p) to file "in.glsl" | |
# python3 cfloats.py in.glsl | |
if len(sys.argv) != 2: | |
print('Usage: python %s filename \n output is out.glsl file \n' % sys.argv[0]) | |
quit() | |
# a is text - "123." or ".123" or "123.456" | |
# return - always in format without 0 before dot so "10.0" will be converted to "10.0" no changes but "0.01" result ".010" | |
def fix_float(a): | |
b_scale = 132.0 | |
text = "" | |
val = int(float(a)) | |
fval = float(a)-val | |
fval=int(fval*b_scale) | |
fval=float(fval)/b_scale | |
text += str(val+fval) | |
if(int(val)>0 and int(val+fval)==val+fval): | |
text = text[:-1] | |
if(int(val)==0): | |
text = text[1:] | |
if(len(text)-len(a)>0): | |
text = text[:-(len(text)-len(a))] | |
if(len(text)-len(a)<0): | |
for a in range(len(a)-len(text)): | |
text+='0' | |
return text | |
inputfilepath = sys.argv[1] | |
file1 = open(inputfilepath, 'r') | |
file2 = open('out.glsl', 'w') | |
Lines = file1.readlines() | |
for line in Lines: | |
new_line = line | |
tres=re.finditer('\d*?\.\d+', line) | |
for m_obj in tres: | |
newf = fix_float(m_obj.group()) | |
new_line=new_line[:m_obj.start()]+newf+new_line[m_obj.end()-len(new_line):] | |
file2.write(new_line) | |
file1.close | |
file2.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment