我很擅长构建图形引擎,并且对某个特定问题感到难过。
我在使用相同的参数集来处理像素着色器时遇到问题。导致我必须为每种方法创建2种不同的技术。如果我尝试为两者使用相同的参数,其中一个将只返回任何内容。
我的目标是只为着色器使用一组参数,从而消除了我使用的每种技术的精灵特定版本。
HLSL像素着色器
Texture2D Texture : register(t0);
SamplerState TextureSampler : register(s0);
Texture2D TextureAlpha;
cbuffer ProjectionMatrix : register(b0)
{
row_major float4x4 MatrixTransform : packoffset(c0);
};
void VS(
inout float4 color : COLOR0,
inout float2 texCoord : TEXCOORD0,
inout float4 position : SV_POSITION)
{
position = mul(position, MatrixTransform);
}
//Method required for using DrawQuad
float4 PS(
float2 tex : TEXCOORD0
) : SV_TARGET
{
float3 tcolor = Texture.Sample(TextureSampler, tex).rgb * TextureAlpha.Sample(TextureSampler, tex).a;
float alpha = TextureAlpha.Sample(TextureSampler, tex).a * Texture.Sample(TextureSampler, tex);
return float4(tcolor, alpha);
}
//Method required for using in SpriteBatches
float4 PSSprite(
float4 color : COLOR0,
float2 tex : TEXCOORD0
) : SV_TARGET
{
return PS(tex);
}
technique MaskSprite
{
pass
{
Profile = 9.3;
//Sprite's also require the VS to be set as well.
VertexShader = compile vs_4_0_level_9_1 VS();
PixelShader = compile ps_4_0_level_9_1 PSSprite();
}
}
technique Mask
{
pass
{
Profile = 9.3;
PixelShader = compile ps_4_0_level_9_1 PS();
}
}
LoadContent()代码
protected override void LoadContent()
{
//...
//render target to mask
var backDesc = GraphicsDevice.BackBuffer.Description;
renderTargetMask = ToDisposeContent(RenderTarget2D.New(GraphicsDevice, backDesc.Width, backDesc.Height, 1, backDesc.Format));
//sprite batch initialization
spriteBatch = ToDisposeContent(new SpriteBatch(GraphicsDevice));
//load in fx and textures
ballsTexture = Content.Load<Texture2D>("Balls");
alphaMapTexture= Content.Load<Texture2D>("AlphaMap");
maskEffect = Content.Load<Effect>("Mask");
//...
}
SpriteBatch代码
protected override void Draw(GameTime gameTime)
{
//...
maskEffect.CurrentTechnique = bloomEffect.Techniques["MaskSprite"];
maskEffect.Parameters["Destination"].SetResource(alphaMapTexture); //Texture2D
spriteBatch.Begin(
SpriteSortMode.Deferred,
GraphicsDevice.BlendStates.NonPremultiplied,
null, null, null, maskEffect);
spriteBatch.Draw(
ballsTexture, //Texture2D
new Vector2(10, 10),
new Rectangle(0, 0, ballsDestTexture.Width, ballsDestTexture.Height),
Color.White,
0.0f,
new Vector2(0, 0),
Vector2.One,
SpriteEffects.None,
0f);
spriteBatch.End();
//...
}
绘制四码
protected override void Draw(GameTime gameTime)
{
//Draw stuff to renderTargetMask
//...
maskEffect.CurrentTechnique = maskEffect.Techniques["Mask"];
maskEffect.Parameters["Texture"].SetResource(renderTargetMask);
maskEffect.Parameters["TextureAlpha"].SetResource(ballsDestTexture);
maskEffect.Parameters["TextureSampler"]
.SetResource(GraphicsDevice.SamplerStates.PointClamp);
var pQuad = new PrimitiveQuad(GraphicsDevice);
pQuad.Draw(maskEffect.CurrentTechnique.Passes[0]);
//...
}