Search code examples
xcodecompilationshadermetal

Manually Compile Metal Shaders


I'm interested in moving away from Xcode and manually compiling Metal shaders in a project for a mixed-language application.

I have no idea how to do this, though. Xcode hides the details of shader compilation and subsequent loading into the application at runtime (you just call device.newDefaultLibrary()). Is this even possible, or will I have to use runtime shader compilation for my purposes?


Solution

  • Generally, you have three ways to load a shader library in Metal:

    • Use runtime shader compilation from shader source code via the MTLDevice newLibraryWithSource:options:error: or newLibraryWithSource:options:completionHandler: methods. Although purists may shy away from runtime compilation, this option has minimal practical overhead, and so is completely viable. Your primary practical reason for avoiding this option might be to avoid making your shader source code available as part of your application, to protect your IP.

    • Load compiled binary libraries using the MTLLibrary newLibraryWithFile:error: or newLibraryWithData:error: methods. Follow the instructions in Using Command Line Utilities to Build a Library to create these individual binary libraries at build time.

    • Let Xcode compile your various *.metal files at build time into the default library available through MTLDevice newDefaultLibrary.