mcpField
A
axiom-metal-migration-ref

axiom-metal-migration-ref

github.com/charleswiltgen開発1.2k165 回インストール今日更新
リポジトリ

axiom-metal-migration-ref について

OpenGLやDirectXの描画コードをMetalへ移植する開発者向けのリファレンススキルです。シェーダー変換、API対応表、ビューやパイプラインの設定、ストレージモードと同期を扱います。

主な機能

  1. 01GLSL・HLSLからMSLへの対応表
  2. 02OpenGLとMetal APIの対応表
  3. 03MTKViewとCAMetalLayerの設定
  4. 04描画パイプラインとストレージモード
  5. 05Metal Shader Converterの手順

活用シーン

  1. 01GLSLシェーダーのMSLへの移植
  2. 02HLSLシェーダーのMSLへの変換
  3. 03OpenGL呼び出しに対応するMetal APIの確認

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/charleswiltgen/axiom --skill axiom-metal-migration-ref

インストール後、Claude Code で/axiom-metal-migration-refを入力して読み込まれたか確認します。

詳細

Metal 移行リファレンス

OpenGL/DirectX のコードを Metal に変換するための完全なリファレンスです。

このリファレンスを使用する場面

次の場合にこのリファレンスを使用してください:

  • GLSL シェーダーを Metal Shading Language(MSL)に変換する
  • HLSL シェーダーを MSL に変換する
  • Metal における GL/D3D API の相当機能を調べる
  • MTKView または CAMetalLayer を設定する
  • レンダーパイプラインを構築する
  • DirectX 向けに Metal Shader Converter を使用する

パート 1:GLSL から MSL への変換

型の対応
GLSLMSL備考
voidvoid
boolbool
intint32 ビット符号付き
uintuint32 ビット符号なし
floatfloat32 ビット
doubleN/Afloat を使用します(MSL に 64 ビット浮動小数点型はありません)
vec2float2
vec3float3
vec4float4
ivec2int2
ivec3int3
ivec4int4
uvec2uint2
uvec3uint3
uvec4uint4
bvec2bool2
bvec3bool3
bvec4bool4
mat2float2x2
mat3float3x3
mat4float4x4
mat2x3float2x3列 x 行
mat3x4float3x4
sampler2Dtexture2d<float> + samplerMSL では分離されています
sampler3Dtexture3d<float> + sampler
samplerCubetexturecube<float> + sampler
sampler2DArraytexture2d_array<float> + sampler
sampler2DShadowdepth2d<float> + sampler
組み込み変数の対応
GLSLMSLステージ
gl_Position[[position]] を返す頂点
gl_PointSize[[point_size]] を返す頂点
gl_VertexID[[vertex_id]] パラメーター頂点
gl_InstanceID[[instance_id]] パラメーター頂点
gl_FragCoord[[position]] パラメーターフラグメント
gl_FrontFacing[[front_facing]] パラメーターフラグメント
gl_PointCoord[[point_coord]] パラメーターフラグメント
gl_FragDepth[[depth(any)]] を返すフラグメント
gl_SampleID[[sample_id]] パラメーターフラグメント
gl_SamplePosition[[sample_position]] パラメーターフラグメント
関数の対応
GLSLMSL備考
texture(sampler, uv)tex.sample(sampler, uv)テクスチャのメソッド
textureLod(sampler, uv, lod)tex.sample(sampler, uv, level(lod))
textureGrad(sampler, uv, ddx, ddy)tex.sample(sampler, uv, gradient2d(ddx, ddy))
texelFetch(sampler, coord, lod)tex.read(coord, lod)整数座標
textureSize(sampler, lod)tex.get_width(lod)、tex.get_height(lod)別々に呼び出します
dFdx(v)dfdx(v)
dFdy(v)dfdy(v)
fwidth(v)fwidth(v)同じ
mix(a, b, t)mix(a, b, t)同じ
clamp(v, lo, hi)clamp(v, lo, hi)同じ
smoothstep(e0, e1, x)smoothstep(e0, e1, x)同じ
step(edge, x)step(edge, x)同じ
mod(x, y)fmod(x, y)名前が異なります
fract(x)fract(x)同じ
inversesqrt(x)rsqrt(x)名前が異なります
atan(y, x)atan2(y, x)名前が異なります
シェーダー構造の変換

GLSL 頂点シェーダー:

#version 300 es
precision highp float;

layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec2 aTexCoord;

uniform mat4 uModelViewProjection;

out vec2 vTexCoord;

void main() {
    gl_Position = uModelViewProjection * vec4(aPosition, 1.0);
    vTexCoord = aTexCoord;
}

MSL 頂点シェーダー:

#include <metal_stdlib>
using namespace metal;

struct VertexIn {
    float3 position [[attribute(0)]];
    float2 texCoord [[attribute(1)]];
};

struct VertexOut {
    float4 position [[position]];
    float2 texCoord;
};

struct Uniforms {
    float4x4 modelViewProjection;
};

vertex VertexOut vertexShader(
    VertexIn in [[stage_in]],
    constant Uniforms& uniforms [[buffer(1)]]
) {
    VertexOut out;
    out.position = uniforms.modelViewProjection * float4(in.position, 1.0);
    out.texCoord = in.texCoord;
    return out;
}

GLSL フラグメントシェーダー:

#version 300 es
precision highp float;

in vec2 vTexCoord;
uniform sampler2D uTexture;

out vec4 fragColor;

void main() {
    fragColor = texture(uTexture, vTexCoord);
}

MSL フラグメントシェーダー:

fragment float4 fragmentShader(
    VertexOut in [[stage_in]],
    texture2d<float> tex [[texture(0)]],
    sampler samp [[sampler(0)]]
) {
    return tex.sample(samp, in.texCoord);
}
精度修飾子

GLSL の精度修飾子に直接対応する MSL の機能はありません。MSL では明示的な型を使用します。

GLSLMSL の相当型
lowp floathalf(16 ビット)
mediump floathalf(16 ビット)
highp floatfloat(32 ビット)
lowp intshort(16 ビット)
mediump intshort(16 ビット)
highp intint(32 ビット)
バッファーのアラインメント(重要)

GLSL/C での想定:

  • vec3:12 バイト、アラインメントは任意
  • vec4:16 バイト

MSL での要件:

  • float3:ストレージは 12 バイト、16 バイト境界にアラインメント
  • float4:ストレージは 16 バイト、16 バイト境界にアラインメント

解決策:CPU と GPU で共有する構造体には、Swift の simd 型を使用します。

import simd

struct Uniforms {
    var modelViewProjection: simd_float4x4  // Correct alignment
    var cameraPosition: simd_float3         // 16-byte aligned
    var padding: Float = 0                   // Explicit padding if needed
}

または、MSL のパック型を使用します(低速です)。

struct VertexPacked {
    packed_float3 position;  // 12 bytes, no padding
    packed_float2 texCoord;  // 8 bytes
};

パート 2:HLSL から MSL への変換

型マッピング
HLSLMSL注記
floatfloat
float2float2
float3float3
float4float4
halfhalf
intint
uintuint
boolbool
float2x2float2x2
float3x3float3x3
float4x4float4x4
Texture2Dtexture2d<float>
Texture3Dtexture3d<float>
TextureCubetexturecube<float>
SamplerStatesampler
RWTexture2Dtexture2d<float, access::read_write>
RWBufferdevice float* [[buffer(n)]]
StructuredBufferconstant T* [[buffer(n)]]
RWStructuredBufferdevice T* [[buffer(n)]]
セマンティクスマッピング
HLSL セマンティクスMSL 属性
SV_Position[[position]]
SV_Target0戻り値 / [[color(0)]]
SV_Target1[[color(1)]]
SV_Depth[[depth(any)]]
SV_VertexID[[vertex_id]]
SV_InstanceID[[instance_id]]
SV_IsFrontFace[[front_facing]]
SV_SampleIndex[[sample_id]]
SV_PrimitiveID[[primitive_id]]
SV_DispatchThreadID[[thread_position_in_grid]]
SV_GroupThreadID[[thread_position_in_threadgroup]]
SV_GroupID[[threadgroup_position_in_grid]]
SV_GroupIndex[[thread_index_in_threadgroup]]
関数マッピング
HLSLMSL注記
tex.Sample(samp, uv)tex.sample(samp, uv)小文字
tex.SampleLevel(samp, uv, lod)tex.sample(samp, uv, level(lod))
tex.SampleGrad(samp, uv, ddx, ddy)tex.sample(samp, uv, gradient2d(ddx, ddy))
tex.Load(coord)tex.read(coord.xy, coord.z)coord を分割
mul(a, b)a * b演算子
saturate(x)saturate(x)同じ
lerp(a, b, t)mix(a, b, t)名前が異なる
frac(x)fract(x)名前が異なる
ddx(v)dfdx(v)名前が異なる
ddy(v)dfdy(v)名前が異なる
clip(x)if (x < 0) discard_fragment()手動
discarddiscard_fragment()関数呼び出し
Metal Shader Converter(DirectX → Metal)

DXIL(コンパイル済み HLSL)を Metal ライブラリに変換する Apple の公式ツールです。

要件:

  • Xcode 15 以降を搭載した macOS 13 以降
  • または VS 2019 以降を搭載した Windows 10 以降
  • 対象デバイス:Argument Buffers Tier 2(macOS 14 以降、iOS 17 以降)

ワークフロー:

# Step 1: Compile HLSL to DXIL using DXC
dxc -T vs_6_0 -E MainVS -Fo vertex.dxil shader.hlsl
dxc -T ps_6_0 -E MainPS -Fo fragment.dxil shader.hlsl

# Step 2: Convert DXIL to Metal library
metal-shaderconverter vertex.dxil -o vertex.metallib
metal-shaderconverter fragment.dxil -o fragment.metallib

# Step 3: Load in Swift
let vertexLib = try device.makeLibrary(URL: vertexURL)
let fragmentLib = try device.makeLibrary(URL: fragmentURL)

主なオプション:

オプション用途
-o <file>出力 metallib のパス
--minimum-gpu-family対象 GPU ファミリー
--minimum-os-build-version最小 OS バージョン
--vertex-stage-in頂点フェッチ関数を分離
-dualSourceBlendingデュアルソースブレンディングを有効化

対応するシェーダーモデル:SM 6.0~6.6(6.6 の機能には制限があります)

パート 3:OpenGL API から Metal API への移行

ビュー/コンテキストの設定
OpenGLMetal
NSOpenGLViewMTKView
GLKViewMTKView
EAGLContextMTLDevice + MTLCommandQueue
CGLContextObjMTLDevice
リソースの作成
OpenGLMetal
glGenBuffers + glBufferDatadevice.makeBuffer(bytes:length:options:)
glGenTextures + glTexImage2Ddevice.makeTexture(descriptor:) + texture.replace(region:...)
glGenFramebuffersMTLRenderPassDescriptor
glGenVertexArraysMTLVertexDescriptor
glCreateShader + glCompileShaderビルド時コンパイル → MTLLibrary
glCreateProgram + glLinkProgramMTLRenderPipelineDescriptor → MTLRenderPipelineState
状態管理
OpenGLMetal
glEnable(GL_DEPTH_TEST)MTLDepthStencilDescriptor → MTLDepthStencilState
glDepthFunc(GL_LESS)descriptor.depthCompareFunction = .less
glEnable(GL_BLEND)pipelineDescriptor.colorAttachments[0].isBlendingEnabled = true
glBlendFuncsourceRGBBlendFactor, destinationRGBBlendFactor
glCullFaceencoder.setCullMode(.back)
glFrontFaceencoder.setFrontFacing(.counterClockwise)
glViewportencoder.setViewport(MTLViewport(...))
glScissorencoder.setScissorRect(MTLScissorRect(...))
描画コマンド
OpenGLMetal
glDrawArrays(mode, first, count)encoder.drawPrimitives(type:vertexStart:vertexCount:)
glDrawElements(mode, count, type, indices)encoder.drawIndexedPrimitives(type:indexCount:indexType:indexBuffer:indexBufferOffset:)
glDrawArraysInstancedencoder.drawPrimitives(type:vertexStart:vertexCount:instanceCount:)
glDrawElementsInstancedencoder.drawIndexedPrimitives(...instanceCount:)
プリミティブ型
OpenGLMetal
GL_POINTS.point
GL_LINES.line
GL_LINE_STRIP.lineStrip
GL_TRIANGLES.triangle
GL_TRIANGLE_STRIP.triangleStrip
GL_TRIANGLE_FAN該当なし(三角形に分解)

パート 4:セットアップの完全な例

MTKView のセットアップ(推奨)
import MetalKit

class GameViewController: UIViewController {
    var metalView: MTKView!
    var renderer: Renderer!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create Metal view
        guard let device = MTLCreateSystemDefaultDevice() else {
            fatalError("Metal not supported")
        }

        metalView = MTKView(frame: view.bounds, device: device)
        metalView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        metalView.colorPixelFormat = .bgra8Unorm
        metalView.depthStencilPixelFormat = .depth32Float
        metalView.clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
        metalView.preferredFramesPerSecond = 60
        view.addSubview(metalView)

        // Create renderer
        renderer = Renderer(metalView: metalView)
        metalView.delegate = renderer
    }
}

class Renderer: NSObject, MTKViewDelegate {
    let device: MTLDevice
    let commandQueue: MTLCommandQueue
    var pipelineState: MTLRenderPipelineState!
    var depthState: MTLDepthStencilState!
    var vertexBuffer: MTLBuffer!

    init(metalView: MTKView) {
        device = metalView.device!
        commandQueue = device.makeCommandQueue()!
        super.init()

        buildPipeline(metalView: metalView)
        buildDepthStencil()
        buildBuffers()
    }

    private func buildPipeline(metalView: MTKView) {
        let library = device.makeDefaultLibrary()!

        let descriptor = MTLRenderPipelineDescriptor()
        descriptor.vertexFunction = library.makeFunction(name: "vertexShader")
        descriptor.fragmentFunction = library.makeFunction(name: "fragmentShader")
        descriptor.colorAttachments[0].pixelFormat = metalView.colorPixelFormat
        descriptor.depthAttachmentPixelFormat = metalView.depthStencilPixelFormat

        // Vertex descriptor (matches shader's VertexIn struct)
        let vertexDescriptor = MTLVertexDescriptor()
        vertexDescriptor.attributes[0].format = .float3
        vertexDescriptor.attributes[0].offset = 0
        vertexDescriptor.attributes[0].bufferIndex = 0
        vertexDescriptor.attributes[1].format = .float2
        vertexDescriptor.attributes[1].offset = MemoryLayout<SIMD3<Float>>.stride
        vertexDescriptor.attributes[1].bufferIndex = 0
        vertexDescriptor.layouts[0].stride = MemoryLayout<Vertex>.stride
        descriptor.vertexDescriptor = vertexDescriptor

        pipelineState = try! device.makeRenderPipelineState(descriptor: descriptor)
    }

    private func buildDepthStencil() {
        let descriptor = MTLDepthStencilDescriptor()
        descriptor.depthCompareFunction = .less
        descriptor.isDepthWriteEnabled = true
        depthState = device.makeDepthStencilState(descriptor: descriptor)
    }

    func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
        // Handle resize
    }

    func draw(in view: MTKView) {
        guard let drawable = view.currentDrawable,
              let descriptor = view.currentRenderPassDescriptor,
              let commandBuffer = commandQueue.makeCommandBuffer(),
              let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: descriptor) else {
            return
        }

        encoder.setRenderPipelineState(pipelineState)
        encoder.setDepthStencilState(depthState)
        encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
        encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: vertexCount)
        encoder.endEncoding()

        commandBuffer.present(drawable)
        commandBuffer.commit()
    }
}
CAMetalLayer のセットアップ(カスタム制御)
import Metal
import QuartzCore

class MetalLayerView: UIView {
    var metalLayer: CAMetalLayer!
    var device: MTLDevice!
    var commandQueue: MTLCommandQueue!
    var displayLink: CADisplayLink?

    override class var layerClass: AnyClass { CAMetalLayer.self }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    private func setup() {
        device = MTLCreateSystemDefaultDevice()!
        commandQueue = device.makeCommandQueue()!

        metalLayer = layer as? CAMetalLayer
        metalLayer.device = device
        metalLayer.pixelFormat = .bgra8Unorm
        metalLayer.framebufferOnly = true

        displayLink = CADisplayLink(target: self, selector: #selector(render))
        displayLink?.add(to: .main, forMode: .common)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        metalLayer.drawableSize = CGSize(
            width: bounds.width * contentScaleFactor,
            height: bounds.height * contentScaleFactor
        )
    }

    @objc func render() {
        guard let drawable = metalLayer.nextDrawable(),
              let commandBuffer = commandQueue.makeCommandBuffer() else {
            return
        }

        let descriptor = MTLRenderPassDescriptor()
        descriptor.colorAttachments[0].texture = drawable.texture
        descriptor.colorAttachments[0].loadAction = .clear
        descriptor.colorAttachments[0].storeAction = .store
        descriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)

        guard let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: descriptor) else {
            return
        }

        // Draw commands here
        encoder.endEncoding()

        commandBuffer.present(drawable)
        commandBuffer.commit()
    }
}
コンピュートシェーダーのセットアップ
class ComputeProcessor {
    let device: MTLDevice
    let commandQueue: MTLCommandQueue
    var computePipeline: MTLComputePipelineState!

    init() {
        device = MTLCreateSystemDefaultDevice()!
        commandQueue = device.makeCommandQueue()!

        let library = device.makeDefaultLibrary()!
        let function = library.makeFunction(name: "computeKernel")!
        computePipeline = try! device.makeComputePipelineState(function: function)
    }

    func process(input: MTLBuffer, output: MTLBuffer, count: Int) {
        let commandBuffer = commandQueue.makeCommandBuffer()!
        let encoder = commandBuffer.makeComputeCommandEncoder()!

        encoder.setComputePipelineState(computePipeline)
        encoder.setBuffer(input, offset: 0, index: 0)
        encoder.setBuffer(output, offset: 0, index: 1)

        let threadGroupSize = MTLSize(width: 256, height: 1, depth: 1)
        let threadGroups = MTLSize(
            width: (count + 255) / 256,
            height: 1,
            depth: 1
        )

        encoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadGroupSize)
        encoder.endEncoding()

        commandBuffer.commit()
        commandBuffer.waitUntilCompleted()
    }
}
// Compute shader
kernel void computeKernel(
    device float* input [[buffer(0)]],
    device float* output [[buffer(1)]],
    uint id [[thread_position_in_grid]]
) {
    output[id] = input[id] * 2.0;
}

パート 5:ストレージモードと同期

バッファーのストレージモード
モードCPU アクセスGPU アクセス用途
.shared読み取り/書き込み読み取り/書き込み小さな動的データ、ユニフォーム
.privateなし読み取り/書き込み静的アセット、レンダーターゲット
.managed (macOS)読み取り/書き込み読み取り/書き込み部分更新を行う大容量バッファー
// Shared: CPU and GPU both access (iOS typical)
let uniformBuffer = device.makeBuffer(length: size, options: .storageModeShared)

// Private: GPU only (best for static geometry)
let vertexBuffer = device.makeBuffer(bytes: vertices, length: size, options: .storageModePrivate)

// Managed: Explicit sync (macOS)
#if os(macOS)
let buffer = device.makeBuffer(length: size, options: .storageModeManaged)
// After CPU write:
buffer.didModifyRange(0..<size)
#endif
テクスチャのストレージモード
let descriptor = MTLTextureDescriptor.texture2DDescriptor(
    pixelFormat: .rgba8Unorm,
    width: 1024,
    height: 1024,
    mipmapped: true
)

// For static textures (loaded once)
descriptor.storageMode = .private
descriptor.usage = [.shaderRead]

// For render targets
descriptor.storageMode = .private
descriptor.usage = [.renderTarget, .shaderRead]

// For CPU-readable (screenshots, readback)
descriptor.storageMode = .shared  // iOS
descriptor.storageMode = .managed  // macOS
descriptor.usage = [.shaderRead, .shaderWrite]

リソース

WWDC:2016-00602, 2018-00604, 2019-00611

ドキュメント:/metal/migrating-opengl-code-to-metal, /metal/shader-converter, /metalkit/mtkview

スキル:axiom-metal-migration, axiom-metal-migration-diag


最終更新日:2025-12-29 プラットフォーム:iOS 12+, macOS 10.14+, tvOS 12+ ステータス:シェーダー変換と API マッピングの完全なリファレンス

コメント