簡體   English   中英

Alpha 與兩個透明紋理混合無法正常工作

[英]Alpha blending with two transparent textures not working correctly

我有一個目標紋理: 在此處輸入圖片說明

這里整個紋理將是透明的(alpha = 0),除了紅色部分。 紅色的 alpha 值為 0.5。 我用一個矩形平面來呈現這個紋理。

然后我有這個源紋理。 它也是帶有黑色部分的透明紋理。 黑色的 alpha 值為 0.5。 我使用另一個矩形平面來呈現此紋理,並將MTLRenderPipelineDescriptor混合更改為

pipelineDescriptor.colorAttachments[0].isBlendingEnabled = true
pipelineDescriptor.colorAttachments[0].rgbBlendOperation = .add
pipelineDescriptor.colorAttachments[0].alphaBlendOperation = .add
pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = .one
pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = .one
pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha

在這里,兩種紋理之間的混合效果很好。

在此處輸入圖片說明

然后我嘗試將這兩個紋理合並為一個目標紋理。 使用MTLComputeCommandEncoder 我的內核函數:

kernel void compute(
                    texture2d<float, access::read_write> des [[texture(0)]],
                    texture2d<float, access::read> src [[texture(1)]],
                    uint2 gid [[thread_position_in_grid]])
{
    float4 srcColor = src.read(gid);
    float4 desColor = des.read(gid);
    float srcAlpha = srcColor.a;

    float4 outColor = srcColor  + desColor * (1 - srcAlpha);

    des.write(outColor, gid);
}

但在那之后混合的顏色將與以前不同。 混合顏色比前一種顏色淺。 在此處輸入圖片說明

如何在內核函數中正確混合兩個透明紋理? 我的解決方案有什么問題?

我認為您正在使用預乘 alpha ......

試試這個(這不是預乘 alpha):

float4 srcColor = src.read(gid);
float4 desColor = des.read(gid);

float4 outColor;
outColor.a = srcColor.a + desColor.a * (1f - srcColor.a);
if (outColor.a == 0f) {
  outColor.r = 0f;
  outColor.g = 0f;
  outColor.b = 0f;
} else {
  outColor.r = (srcColor.r * srcColor.a + desColor.r * desColor.a * (1f - srcColor.a)) / outColor.a;
  outColor.g = (srcColor.g * srcColor.a + desColor.g * desColor.a * (1f - srcColor.a)) / outColor.a;
  outColor.b = (srcColor.b * srcColor.a + desColor.b * desColor.a * (1f - srcColor.a)) / outColor.a;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM