Search code examples
iosmetalmetalkit

Line Pixellating


Using Metal I am drawing line using Bezier Curves using four points. I am using nearly 1500 triangles for the lines. The line is Pixellated. How can i reduce pixellated.

vertex VertexOutBezier bezier_vertex(constant BezierParameters *allParams[[buffer(0)]],
                               constant GlobalParameters& globalParams[[buffer(1)]],
                               uint vertexId [[vertex_id]],
                               uint instanceId [[instance_id]])
{

    float t = (float) vertexId / globalParams.elementsPerInstance;


    rint(t);
    BezierParameters params = allParams[instanceId];

    float lineWidth = (1 - (((float) (vertexId % 2)) * 2.0)) * params.lineThickness;
 float2 a = params.a;
    float2 b = params.b;

    float cx = distance(a , b);


float2 p1 = params.p1 * 3.0;  // float2 p1 = params.p1 * 3.0;
    float2 p2 = params.p2 * 3.0;  // float2 p2 = params.p2 * 3.0;

    float nt = 1.0f - t;
    float nt_2 = nt * nt;
    float nt_3 = nt_2 * nt;
    float t_2 = t * t;
    float t_3 = t_2 * t;

    // Calculate a single point in this Bezier curve:
    float2 point = a * nt_3 + p1 * nt_2 * t + p2 * nt * t_2 + b * t_3;

    float2 tangent = -3.0 * a * nt_2 + p1 * (1.0 - 4.0 * t + 3.0 * t_2) + p2 * (2.0 * t - 3.0 * t_2) + 3 * b * t_2;
    tangent = (float2(-tangent.y , tangent.x  ));
    VertexOutBezier vo;       
    vo.pos.xy = point + (tangent * (lineWidth / 2.0f));
    vo.pos.zw = float2(0, 1);
    vo.color = params.color;

    return vo;
}

Solution

  • You need to enable MSAA (multisample anti-aliasing). How you do this depends on your exact Metal view configuration, but the easiest way is if you're using MTKView. To enable MSAA in an MTKView, all you have to do is:

    metalView.sampleCount = 4
    

    Then, when you configure your MTLRenderPipelineDescriptor before calling makeRenderPipelineState(), add the following:

    pipelineDescriptor.sampleCount = 4
    

    This should greatly improve the quality of your curves and reduce pixelation. It does come with a performance cost however, as the GPU has to do substantially more work to render your frame.