首页 > 解决方案 > 在 Metal,Swift 中为一个点设置圆形

问题描述

我正在使用 Metal 创建动画。

现在看起来像这样

我希望每个点的形状都是这样的圆形

这是我当前的着色器代码:

struct VertexOut {
  float4 position [[position]];
  float pointSize [[point_size]];
};

struct Uniforms {
  float4x4 ndcMatrix;
  float ptmRatio;
  float pointSize;
};

vertex VertexOut vertex_shader(const device packed_float2 * vertex_array [[buffer(0)]],
                               const device Uniforms& uniforms [[buffer(1)]],
                               unsigned int vid [[vertex_id]]) {
    VertexOut vertexOut;
    float2 position = vertex_array[vid];
    vertexOut.position = uniforms.ndcMatrix * float4(position.x * uniforms.ptmRatio, position.y * uniforms.ptmRatio * 1.5, 0, 1);
    vertexOut.pointSize = uniforms.pointSize * 1.5;
    return vertexOut;
}

fragment half4 fragment_shader(VertexOut fragData [[stage_in]],
                               float2 pointCoord [[point_coord]]) {
    return half4(0.3, 0.3, 0.1, 0.1);
}

之前,我已经使用片段着色器达到了预期的效果。我的代码是:

fragment half4 fragment_shader(VertexOut fragData [[stage_in]],
                               float2 pointCoord [[point_coord]]) {
    float dist = length(pointCoord - float2(0.4));
    float4 color = fragData.color;
    // Marking particles round shaped
    color.a = 1.0 - smoothstep(0.4, 0.4, dist);
    // Setting yellow color
    color.b = (0.3, 0.3, 0.1, 0.1);
    return half4(color);
}

它在形状上工作得很好,但它没有给出想要的颜色效果。所以我需要找到另一种正确设置颜色和形状的方法。

我尝试设置两个单独的片段函数,一个用于形状,一个用于颜色,然后将它们传递给 PipelineState,但它不起作用。

任何帮助表示赞赏!

标签: iosswiftshadermetal

解决方案


我已经在一个函数中解决了它:

fragment half4 fragment_shader(VertexOut fragData [[stage_in]],
                              float2 pointCoord  [[point_coord]]) {
    if (length(pointCoord - float2(0.5)) > 0.5) {
        discard_fragment();
    }
    return half4(0.3, 0.3, 0.1, 0.1);
}

推荐阅读