【问题标题】:Transparent animation in Metal, SwiftMetal,Swift中的透明动画
【发布时间】:2021-07-06 16:58:51
【问题描述】:

我正在使用 Metal 创建动画。我使用 MTKViewDelegate 方法在黑色 MTKView 上绘制动画。我的目的是模拟汽油并使其像这样半透明:

Half-transparent animation

现在看起来像这样:

My current animation

当我在片段着色器中设置 alpha 时,没有任何反应,尽管着色效果很好:

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

我也有附件描述符,但它仍然无法使 alpha 工作:

         let attachmentDesciptor: MTLRenderPipelineColorAttachmentDescriptor =
 pipelineDescriptor.colorAttachments[0]
         attachmentDesciptor.isBlendingEnabled = true
         attachmentDesciptor.rgbBlendOperation = MTLBlendOperation.add
         attachmentDesciptor.alphaBlendOperation = MTLBlendOperation.add
         attachmentDesciptor.sourceRGBBlendFactor = .sourceAlpha
         attachmentDesciptor.sourceAlphaBlendFactor = .sourceAlpha
         attachmentDesciptor.destinationRGBBlendFactor = MTLBlendFactor.oneMinusSourceAlpha
         attachmentDesciptor.destinationAlphaBlendFactor = MTLBlendFactor.oneMinusSourceAlpha

已编辑:

我也尝试将metalView.isOpaque 设置为false,但它只是改变了背景:

Same animation with different background

任何帮助将不胜感激!

【问题讨论】:

  • 您是否尝试在MTKView 上将opaque 设置为NO
  • 是的,它使背景变白,但不改变动画

标签: ios swift shader metal


【解决方案1】:

您的着色器实现是错误的,因为您的 alpha 通道从未设置为 0.5,在这一行中:

// Setting yellow color with 0.5 alpha
color.b = (0.6, 0.2, 0.7, 0.5);

在上面的行中,您尝试将四维向量设置为一维分量,这是错误的。

也不清楚你为什么调用这个函数:

// Marking particles round shaped
color.a = 1.0 - smoothstep(0.4, 0.4, dist);

根据金属着色器语言:

如果 edge0 >= edge1,则结果未定义

为了达到预期的效果,你应该用这个替换你的着色器片段函数:

fragment half4 fragment_shader(VertexOut fragData [[stage_in]], float2 pointCoord [[point_coord]]) {
        float dist = length(pointCoord - float2(0.6));
        float4 color = fragData.color;
        // Marking particles round shaped
        // color.a = 1.0 - smoothstep(0.4, 0.4, dist);
        // Setting yellow color with 0.5 alpha
        // color.b = (0.6, 0.2, 0.7, 0.5);
        
        // Setting yellow color with 0.5 alpha
        color = (1, 1, 0, 0.5);
        return half4(color);     
    }

【讨论】:

  • 我使用 color.a 将粒子制作成圆形,而不是方形。感谢您的回复,您的片段着色器工作,但它使粒子呈方形和灰色。当我更改您的颜色参数以使粒子变为黄色时,它会再次使它们变为白色或灰色。
猜你喜欢
  • 2015-12-01
  • 2010-09-25
  • 2016-07-14
  • 2011-04-10
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-09
相关资源
最近更新 更多