Introduction
A .metal file holds shaders written in the Metal Shading Language, the
language of Apple’s Metal graphics and
compute API on macOS, iOS and Apple’s other systems. The language is based on C++, with
vector and matrix types and attributes that tie functions and their arguments to the
pipeline.
Xcode compiles the .metal files in a project into a Metal library,
default.metallib, which is shipped inside the app and loaded at run time.
Source can also be compiled while the app runs.
Structure
A Metal file is plain text in C++ syntax. It usually includes
<metal_stdlib> and uses the metal namespace. Each shader
is a function marked vertex, fragment or kernel
(for compute). Attributes in double square brackets say where values come from, such as
[[buffer(0)]], [[stage_in]] or [[position]].
Language versions, function types, address spaces and the compile steps are on the
language page; the compiled library’s
layout, which Apple does not document, is on
Metal library (.metallib).
#include <metal_stdlib>
using namespace metal;
struct VertexOut {
float4 position [[position]];
float4 colour;
};
fragment float4 fragmentMain(VertexOut in [[stage_in]]) {
return in.colour;
}
Not described
Known, not yet covered
- Reference: most of the 383-page Metal Shading Language Specification (a free PDF from Apple): matrix, packed, atomic, texture, sampler and imageblock types, operators, the fragment, kernel, intersection, object and mesh function attributes, function constants, the standard library (chapter 6) and Metal Performance Primitives (chapter 7). The language page has scalar and vector types and the vertex function attributes.
- Viewer: there is no viewer for .metal source or .metallib files yet.
Unknown
- Reference: the layout of the
.metallibcontainer: Apple publishes none, and the metallib page’s reverse-engineered layout is marked unconfirmed.
Links
Software
- Xcode – Apple’s IDE, which compiles and debugs Metal shaders (macOS)
- SPIRV-Cross – translates SPIR-V shaders into Metal (Windows, macOS, Linux)
Reference
- Metal resources – Apple’s page, with the Metal Shading Language Specification