MetalNanoVG icon indicating copy to clipboard operation
MetalNanoVG copied to clipboard

Metal shader to bit code

Open Youlean opened this issue 2 years ago • 2 comments
trafficstars

Hey, how do you compile metal shader to bit code?

Youlean avatar Feb 03 '23 23:02 Youlean

I wrote the python script for that. You may add this to the source code as it can be useful:

import subprocess

def compile_metal_shader(input_file, metallib_file):
    compile_command = [
        "xcrun",
        "-sdk",
        "macosx",
        "Metal",
        "-c",
        input_file,
        "-o",
        "temp.air",
        "-mmacosx-version-min=10.11"
    ]
    subprocess.run(compile_command, check=True)
    
    metallib_command = [
        "xcrun",
        "-sdk",
        "macosx",
        "metallib",
        "temp.air",
        "-o",
        metallib_file
    ]
    subprocess.run(metallib_command, check=True)

def metallib_to_cpp(metallib_file, output_file):
    with open(metallib_file, 'rb') as f:
        metallib = f.read()

    with open(output_file, 'w') as f:
        f.write("const unsigned char mnvg_bitcode_macos[] = {\n")
        for i in range(0, len(metallib), 16):
            f.write("    ")
            f.write(", ".join(f"0x{b:02x}" for b in metallib[i:i + 16]))
            f.write(",\n")
        f.write("};\n")
        f.write(f"const int mnvg_bitcode_macos_len = {len(metallib)};\n")

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 4:
        print("Usage: python compile_and_convert.py input_file metallib_file output_file")
        sys.exit(1)
    input_file = sys.argv[1]
    metallib_file = sys.argv[2]
    output_file = sys.argv[3]

    compile_metal_shader(input_file, metallib_file)
    metallib_to_cpp(metallib_file, output_file)

Youlean avatar Feb 04 '23 01:02 Youlean

project is has similar bash script metallib

zeromake avatar Feb 09 '23 03:02 zeromake