mirage_old/scripts/compile_shaders.py
daiqingshuang aa317a55d5 init
2025-02-07 19:10:00 +08:00

99 lines
3.4 KiB
Python

import argparse
import os
import subprocess
import sys
import re
def find_shader_files(input_dir, extensions):
for root, _, files in os.walk(input_dir):
for file in files:
if any(file.endswith(ext) for ext in extensions):
yield os.path.join(root, file)
def find_slang_entries(input_file):
try:
with open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
pattern = r'\[shader\(\s*"(?:\w+)"\s*\)\]\s*\n\s*\w+\s+(\w+)\s*\('
return list(set(re.findall(pattern, content)))
except Exception as e:
print(f"Error parsing {input_file}: {str(e)}")
return []
def compile_slang(input_file, build_types, output_dir, args):
try:
entries = find_slang_entries(input_file)
if not entries:
print(f"Skipping {input_file}: No shader entries found")
return True
slangc = args.slangc
base = os.path.splitext(os.path.basename(input_file))[0]
abs_path = os.path.abspath(output_dir)
os.makedirs(abs_path, exist_ok=True)
success = True
for build_type, enabled in build_types:
if not enabled:
continue
for entry in entries:
output_file = os.path.join(abs_path, f"{base}_{entry}.spv")
cmd = [slangc, input_file, "-entry", entry, "-o", output_file, "-target", build_type]
try:
subprocess.run(cmd, check=True, capture_output=True, text=True)
print(f"Compiled Slang: {input_file}:{entry} -> {output_file}")
except subprocess.CalledProcessError as e:
print(f"Error compiling {input_file}:{entry}")
print(e.stderr)
success = False
return success
except Exception as e:
print(f"Unexpected error with {input_file}: {str(e)}")
return False
def main():
parser = argparse.ArgumentParser(description="Compile slang shaders using slangc")
parser.add_argument("--output-dir", help="Output directory")
parser.add_argument("--slangc", default="slangc", help="Path to slangc")
parser.add_argument("--debug", action="store_true", help="Compile in debug mode")
parser.add_argument("--opengl", action="store_true", help="Compile Slang for OpenGL")
parser.add_argument("--vulkan", action="store_true", help="Compile Slang for Vulkan")
parser.add_argument("--d3d11", action="store_true", help="Compile Slang for D3D11")
parser.add_argument("--d3d12", action="store_true", help="Compile Slang for D3D12")
parser.add_argument("--metal", action="store_true", help="Compile Slang for Metal")
args = parser.parse_args()
build_types = [
['glsl', args.opengl],
['spirv', args.vulkan],
['hlsl', args.d3d11],
['d3d12', args.d3d12],
['metal', args.metal]
]
output_dir = args.output_dir or "shaders"
# 读取当前同级目录下的shader_paths.txt
with open("shader_paths.txt", 'r') as f:
shader_paths = f.readlines()
slang_ext = [".slang"]
all_success = True
for shader_path in shader_paths:
# Compile Slang
for file in find_shader_files(shader_path, slang_ext):
if not compile_slang(file, output_dir, build_types, args):
all_success = False
if not all_success:
sys.exit(1)
if __name__ == "__main__":
main()