LoginSignup
3
5

More than 5 years have passed since last update.

SwiftでMetalを呼び出すときのメモ

Last updated at Posted at 2015-03-21

私的メモ

C++11で書くシェーダーにはまった

次のような構成(Swift)
renderEncoder.setVertexBuffer(頂点バッファー, offset: 0, atIndex: 0)
renderEncoder.setVertexBuffer(テクスチャの頂点バッファー, offset: 0, atIndex: 1)
renderEncoder.setFragmentTexture(テクスチャ本体, atIndex: 0)
で、頂点バッファーがXYZAのフォーマット、テクスチャの頂点がXYフォーマットのときの一番簡単なシェーダーをつけておきます。この構成でPNGファイルを三角形に貼り付けることができました。

Shaders.metal

#include <metal_stdlib>
using namespace metal;

struct MyVertex
{
    float4 m_Vertex [[position]];
    float2 m_Texture [[user(texturecoord)]];
};

vertex MyVertex my_vertex(constant float4         *pPosition   [[ buffer(0) ]],
                                      constant packed_float2  *pTexCoords  [[ buffer(1) ]],
                                      uint                     vid         [[ vertex_id ]])
{
    MyVertex outVertices;
    outVertices.m_Vertex = pPosition[vid];
    outVertices.m_Texture = pTexCoords[vid];
    return outVertices;
}

fragment half4 my_fragment(MyVertex     inFrag    [[ stage_in ]],
                                    texture2d<half>  tex2D     [[ texture(0) ]])
{
    constexpr sampler quad_sampler;
    half4 color = tex2D.sample(quad_sampler, inFrag.m_Texture);
    if (color[3] < 0.5) discard_fragment();//透明の処理
    return color;
}

エンコーダーはレンダーエンコーダをつかっています。透明の処理を0.5で敷居していますが、ちょっと乱暴ですね。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5