仅对某些输出颜色进行Alpha混合

时间:2018-11-30 22:36:10

标签: xna shader monogame hlsl alphablending

在MonoGame中,我有一个具有两种输出颜色的像素着色器。

第一个是绘制到标准4通道32位Color渲染目标的常规颜色。

第二个是绘制到1通道16位HalfSingle渲染目标的z索引。

我想在第一种颜色上进行alpha混合,而不是在z-index上。

有没有一种方法无需声明底层纹理的采样器并手动进行alphablending?

matrix WorldViewProjection;

Texture2D SpriteTexture;

sampler2D SpriteTextureSampler = sampler_state
{
    Texture = <SpriteTexture>;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float4 Color : COLOR0;
    float2 TextureCoordinates : TEXCOORD0;
    float2 depth : TEXCOORD1;
};

struct PS_OUTPUT
{
    float4 color : COLOR0;
    float4 depth : COLOR1;
};

VertexShaderOutput SpriteVertexShader(float4 position : POSITION0, float2 float4 color : COLOR0, float2 texCoord : TEXCOORD0)
{
    VertexShaderOutput output = (VertexShaderOutput)0;
    output.Position = mul(position, WorldViewProjection);
    output.Color = color;
    output.TextureCoordinates = texCoord;
    output.depth.x = position.z;
    return output;
}

PS_OUTPUT SpritePixelShader(VertexShaderOutput input) : COLOR
{
    PS_OUTPUT output = (PS_OUTPUT)0;
    float4 color = tex2D(SpriteTextureSampler, input.TextureCoordinates) * input.Color;
    output.color = color;
    output.depth.x = input.depth.x;
    return output;
}

technique SpriteDrawing
{
    pass P0
    {
        VertexShader = compile vs_2_0 SpriteVertexShader();
        PixelShader = compile ps_2_0 SpritePixelShader();
    }
};

2 个答案:

答案 0 :(得分:0)

您可以设置一个与每个渲染目标无关的混合状态:

BlendState myBlendState = new BlendState();
myBlendState.IndependentBlendEnable = true;

//0 is default and is opaque, modify the blend operation
myBlendState[0].ColorDestinationBlend = Blend.DestinationAlpha;
myBlendState[0].ColorSourceBlend = Blend.InverseDestinationAlpha;

//1 is opaque, no changes needed
myBlendState[1] = noBlend ;

然后您可以使用:

//if you want to restore
var oldBlendState = device.BlendState;

device.BlendState = myBlendState;

//do your draw here
//Restore old blend state if needed
device.BlendState = oldBlendState;

答案 1 :(得分:0)

您可以将您不想混合的颜色的Alpha设置为1。这里,我用于深度的渲染目标没有Alpha通道,但这仍然有效。

output.depth.a = 1;