Search code examples
shaderscenekitmetal

Metal Shader with SceneKit SCNProgram


I'm looking for just a working Metal shader that works in SceneKit with SCNProgram.

Can someone show me the correct method declarations/how to hook this up?

let program = SCNProgram()
program.vertexFunctionName = "myVertex"
program.fragmentFunctionName = "myFragment"
material.program = program

and then the shader

//MyShader.metal

vertex something myVertex(something)
{
    return something;
}

fragment float4 myFragment(something)
{
    return something
}

I'm just looking for the most basic example please.


Solution

  • I clipped out all the 'unnecessary' stuff, this is about as basic as it gets and pretty much what my first Metal shader was.

    Next I'd start looking into wiring up the other vertex attributes (colour, normals), and maybe do some basic lighting calculations.

    #include <metal_stdlib>
    using namespace metal;
    #include <SceneKit/scn_metal>
    
    struct MyNodeBuffer {
        float4x4 modelTransform;
        float4x4 modelViewTransform;
        float4x4 normalTransform;
        float4x4 modelViewProjectionTransform;
    };
    
    typedef struct {
        float3 position [[ attribute(SCNVertexSemanticPosition) ]];
    } MyVertexInput;
    
    struct SimpleVertex
    {
        float4 position [[position]];
    };
    
    
    vertex SimpleVertex myVertex(MyVertexInput in [[ stage_in ]],
                                 constant SCNSceneBuffer& scn_frame [[buffer(0)]],
                                 constant MyNodeBuffer& scn_node [[buffer(1)]])
    {
        SimpleVertex vert;
        vert.position = scn_node.modelViewProjectionTransform * float4(in.position, 1.0);
    
        return vert;
    }
    
    fragment half4 myFragment(SimpleVertex in [[stage_in]])
    {
        half4 color;
        color = half4(1.0 ,0.0 ,0.0, 1.0);
    
        return color;
    }
    

    Apologies for any typos, edited it down on my phone...