Search code examples
iosmetal

convert the fragment Shader written for GLSL to Metal Shader


I would like to convert the following fragment Shader written for glsl to Metal Shader.

const float PI = 3.14159265359;


mat2 rotate2d (float _angle) {
    return mat2 (cos (_angle), -sin (_angle),
                sin (_angle), cos (_angle));
}

void main (void) {

    vec2 st = (gl_FragCoord.xy * 2.0 --resolution) /min(resolution.x,resolution.y);
    float p = 0.0;
    
   st = rotate2d (sin (time) * PI) * st;
    
    vec2 c = max (abs (st) --0.2,0.0);
    p = length (c);
    p = ceil (p);
    
    vec3 color = vec3 (1.0-p);

    gl_FragColor = vec4 (color, 1.0);

}

At that time, I understand that there is no problem if vec2 etc. is set to float2 etc.

How should I write it?


Solution

  • It's hard to convert this shader without having any informartion about your current render pipeline:

    #include <metal_stdlib>
    
    float2x2 rotate2d(float angle)
    {
        return float2x2(float2(cos(angle), -sin(angle)),
                        float2(sin(angle),  cos(angle)));
    }
    
    fragment float4 fragmentShader(RasterizerData in [[stage_in]],
                                   constant simd::float2 &resolution  [[ buffer(0) ]],
                                   constant float &time  [[ buffer(1) ]])
    {
        float2 st = (in.textureCoordinate.xy * 2.0 - resolution) / min(resolution.x, resolution.y);
        float p = 0.0;
        st = rotate2d(sin(time) * M_PI_F) *st;
        float2 c = max(abs(st) - 0.2, 0.0);
        p = length(c);
        p = ceil(p);
        float3 color = float3(1.0 - p);
        return float4(color, 1);
    }