/game-porting-skills:using-metalfx-temporal-upscalerfrom game-porting-skills
Adds MetalFX temporal upscaling (MTLFXTemporalScaler/MTL4FXTemporalScaler) to Metal apps, covering shader motion vectors, jitter, and renderer integration.
Ships in game-porting-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
This skill walks through integrating MTLFXTemporalScaler into an existing Metal rendering application. The scaler renders at a lower resolution and uses motion vectors, depth, and temporal jitter to produce a high-quality upscaled output.
@import MetalFX; (auto-links with CLANG_ENABLE_MODULES = YES)The integration touches 3 areas:
Read references/integration-guide.md for the complete technical reference including API details, texture formats, jitter sequences, motion vector conventions, and troubleshooting.
Before starting integration, check if the engine already has a high-level abstraction for temporal upscaling (e.g., from DLSS, FSR, XeSS). If it does, integrate MetalFX through the existing abstraction — follow the same execution paths wherever the APIs are compatible. This makes debugging easier and minimizes the chance for bugs. Only diverge from the existing patterns where MetalFX API differences require it.
If no existing upscaling abstraction exists, ask the developer: introduce a minimal abstraction layer (Recommended — cleaner, easier to maintain and debug), or implement MetalFX directly in the source without abstractions (faster, but harder to extend later)?
Before writing code, identify:
Add to the shared frame data struct (the struct used by both CPU and shaders):
matrix_float4x4 prevModelViewProjectionMatrix; // For motion vectors
vector_float2 jitterOffset; // Clip-space subpixel jitter
Vertex shader changes:
clipPos = MVP * worldPosprevClipPos = prevMVP * worldPosposition = clipPos; position.xy += jitterOffset * clipPos.wcurrentClipPos and prevClipPos to fragment shaderFragment shader changes:
[[color(0)]] for color (RGBA16Float) and [[color(1)]] for motion (RG16Float)prevNDC - currentNDC (perspective divide both, then subtract)motionVectorScale on the scaler converts this NDC delta to pixel displacementreferences/integration-guide.md for the formula. Without this, textures appear blurry at the lower render resolutionAdd a fullscreen blit shader for copying the upscaled output to the drawable:
vertex FullscreenOut fullscreenVertex(uint vid [[vertex_id]]) {
FullscreenOut out;
out.texCoord = float2((vid << 1) & 2, vid & 2);
out.position = float4(out.texCoord * float2(2, -2) + float2(-1, 1), 0, 1);
return out;
}
fragment float4 fullscreenFragment(FullscreenOut in [[stage_in]], texture2d<float> tex [[texture(0)]]) {
constexpr sampler s(min_filter::linear, mag_filter::linear);
return tex.sample(s, in.texCoord);
}
Render at displaySize / scaleFactor (e.g., 2x means half width and half height):
| Texture | Format | Resolution | Usage Flags |
|---|---|---|---|
| Color target | RGBA16Float (HDR default; substitute your engine's format if supported) | Render | RenderTarget | ShaderRead |
| Depth target | Depth32Float | Render | RenderTarget | ShaderRead |
| Motion target | RG16Float | Render | RenderTarget | ShaderRead |
| Upscaled output | RGBA16Float (HDR default; substitute your engine's format if supported) | Display | RenderTarget | ShaderRead | ShaderWrite |
Critical: The output texture MUST have ShaderWrite because MetalFX writes via internal compute shaders, not as a render target. Missing this causes silent black output with no error.
MTLFXTemporalScalerDescriptor *desc = [[MTLFXTemporalScalerDescriptor alloc] init];
desc.inputWidth = renderWidth; desc.inputHeight = renderHeight;
desc.outputWidth = displayWidth; desc.outputHeight = displayHeight;
desc.colorTextureFormat = MTLPixelFormatRGBA16Float;
desc.depthTextureFormat = MTLPixelFormatDepth32Float;
desc.motionTextureFormat = MTLPixelFormatRG16Float;
desc.outputTextureFormat = MTLPixelFormatRGBA16Float;
// colorTextureFormat / outputTextureFormat must match your render-target formats; verify with [MTLFXTemporalScalerDescriptor supportsDevice:]
// Metal 3: id<MTLFXTemporalScaler> scaler = [desc newTemporalScalerWithDevice:device];
// Metal 4 (macOS/iOS 26.0+): pass an MTL4Compiler for pipeline state compilation
id<MTL4FXTemporalScaler> scaler = [desc newTemporalScalerWithDevice:device compiler:compiler];
scaler.motionVectorScaleX = renderWidth * 0.5f; // NDC→pixel conversion
scaler.motionVectorScaleY = renderHeight * 0.5f;
scaler.inputContentWidth = renderWidth;
scaler.inputContentHeight = renderHeight;
The scene pipeline must match the offscreen MRT layout:
pipelineDesc.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA16Float; // color
pipelineDesc.colorAttachments[1].pixelFormat = MTLPixelFormatRG16Float; // motion
pipelineDesc.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float;
pipelineDesc.stencilAttachmentPixelFormat = MTLPixelFormatInvalid;
Also create a separate blit pipeline targeting the view's colorPixelFormat (typically BGRA8Unorm_sRGB).
Per frame:
Pass 2 encode call — the command buffer protocol differs between Metal 3 and Metal 4:
// Metal 3: [scaler encodeToCommandBuffer:cmdBuf]; // cmdBuf is id<MTLCommandBuffer>
// Metal 4 (macOS/iOS 26.0+): cmdBuf is id<MTL4CommandBuffer>
[scaler encodeToCommandBuffer:cmdBuf];
The selector is the same, but the argument type changed from id<MTLCommandBuffer> to id<MTL4CommandBuffer>. All per-frame properties (textures, jitterOffsetX/Y, motionVectorScaleX/Y, inputContentWidth/Height, reset) are identical across both APIs — they live on the shared MTLFXTemporalScalerBase protocol.
The jitter must match between what the shader applies and what MetalFX receives:
2*jitterX/renderWidth, -2*jitterY/renderHeightstatic float halton(int index, int base) {
float result = 0.0f, f = 1.0f / base;
int i = index;
while (i > 0) { result += f * (i % base); i /= base; f /= base; }
return result;
}
// Per frame: jitterX = halton(index+1, 2) - 0.5; jitterY = halton(index+1, 3) - 0.5;
Phase count by scale factor: 1.5x→18, 2x→32, 3x→72. Formula: ceil(8 * scale²).
Each frame, before computing new matrices:
prevModelViewProjectionMatrix = prevVP * prevModel and store in frame dataWhen the view size changes, recreate all offscreen textures and the temporal scaler at the new dimensions. Update the projection matrix using render resolution aspect ratio.
See references/integration-guide.md for the full troubleshooting guide. The top issues:
ShaderWrite usage flag[MTLFXTemporalScalerDescriptor supportsDevice:]Consult Apple's reference. Applying Temporal Antialiasing and Upscaling Using MetalFX — AAPLRenderer.swift and Shaders.metal for jitter signs, motionVectorScaleX/Y signs, and the prevUV - currentUV convention. Deviate once you understand why your engine differs.
Build a hotkey-triggered diagnostic dump. Each dump should include:
jitterOffsetX/Y, motionVectorScaleX/Y, inputContentWidth/Height, depthReversedcamera.jitter in both clip and pixel unitshalton - 0.5 alongside the values fed to camera.jitter and scaler.jitterOffsetTrigger it in the failing situation — static camera (isolates jitter), pure rotation (uniform motion), pure translation (depth-dependent parallax). For interactive cases, ask the developer to trigger the dump while reproducing the artifact. Comparing the three dumps isolates most sign and scale errors directly.
Confirm the integration from debug logs:
The developer must confirm the debug log verification before the integration is considered complete.
If the scene can be rendered with a static camera, capture a GPU frame and inspect the motion vector texture — it should be uniform zero (solid black). Per-geometry color variation indicates non-zero motion vectors, typically from incorrect prevMVP or jitter leaking into the motion vector computation.
After building and launching the app, verify rendering is working by capturing a screenshot of the app window. This is useful both for self-checking your work and for showing the user what the result looks like.
Capture the app window (not the full screen — just the window):
# Find the main content window by app name, filtering for the largest window
APP_NAME="MyApp" # Replace with the actual app/process name
WID=$(python3 -c "
import Quartz
for w in Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListOptionAll, Quartz.kCGNullWindowID):
if '$APP_NAME' in w.get('kCGWindowOwnerName', ''):
b = w.get('kCGWindowBounds', {})
if b.get('Height', 0) > 100:
print(w['kCGWindowNumber']); break
")
screencapture -x -o -l "$WID" /tmp/mfx_screenshot.png
Then view the screenshot at /tmp/mfx_screenshot.png. Look for:
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub apple/game-porting-toolkit --plugin game-porting-skills24 skills in this plugin
/compiling-with-metal-shaderconverterALWAYS use when compiling DXIL/HLSL to metallib with Metal shader converter (commonly referred to as MSC) via the metal-shaderconverter CLI or libmetalirconverter (IRCompiler, IRObject, IRShaderReflection) at runtime. Covers offline/runtime DXIL compilation, root signatures, reflection output, ray tracing shaders, geometry/tessellation emulation compilation, framebuffer fetch in HLSL, programmable blending in HLSL, Metal_HLSL.inc, and compatibility flags. Do NOT trigger for binding compiled shaders to encoders — use integrating-metal-shaderconverter-shaders for that./creating-metal4-shader-pipelinesALWAYS use when creating Metal pipeline state objects with Metal 4 descriptors (MTL4RenderPipelineDescriptor, MTL4ComputePipelineDescriptor, MTL4MeshRenderPipelineDescriptor) via MTL4Compiler. Covers function descriptors, function constant specialization, flexible/unspecialized PSOs, color-attachment mapping, async compilation (MTL4CompilerTask), pipeline caching (MTL4Archive, MTL4PipelineDataSetSerializer), static/binary shader linking, and pipeline reflection. Do NOT trigger for HLSL/DXIL → metallib — use compiling-with-metal-shaderconverter.Other plugins' skills for the same job