Metal之fragment顏色透明和半透明

descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm

pipelineState的像素格式設置爲 bgra8Unorm 後,就可以在Shaderfragment返回的float4中按(r, g, b, a) 來描述像素的顏色值。

而其中 a 代表 alpha,也就是透明的意思。

alpha通道通常是用來表示顏色的透明度或者這個像素的可見性(RGBA表示一個像素的話,color.a就是Alpha通道)。

一、透明 discard_fragment

fragment float4 anchorGeometryFragmentLighting(ColorInOut in [[stage_in]],
                                               const float2 coords [[point_coord]],
                                               constant SharedUniforms &uniforms [[ buffer(kBufferIndexSharedUniforms) ]]) {
    const float distSquared = length_squared(coords - float2(0.5));
    if (in.color.a == 0 || distSquared > 0.25) {
        discard_fragment();
    }
    return in.color;
}

discard_fragment 就會直接丟棄當前的片元。

二、半透明 alpha混合

另一種渲染方法是 alpha 混合。 下面的混合方程是將原像素和目標像素做alpha混合。一般渲染這種半透明的表面都是按離相機的距離由遠到近進行渲染。

需要先在 pipelinedescriptor開啓混合isBlendingEnabled屬性,這個屬性默認是關閉的,像UIView中渲染一樣,混合渲染會影響性能

        descriptor.colorAttachments[0].isBlendingEnabled = true
        descriptor.colorAttachments[0].pixelFormat = renderDestination.colorPixelFormat
        descriptor.colorAttachments[0].rgbBlendOperation = .add
        descriptor.colorAttachments[0].alphaBlendOperation = .add
        descriptor.colorAttachments[0].sourceRGBBlendFactor = .sourceAlpha
        descriptor.colorAttachments[0].sourceAlphaBlendFactor = .sourceAlpha
        descriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
        descriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha

開啓後,就可以在fragment中,返回如 (1, 0, 0, 0.5) 的顏色值。會渲染出半透明的紅色。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章