问题
I was able to do this in XNA 3.1, however I see that we now use state objects in XNA 4, which is certainly an improvement, although I can't accomplish what I want so far :)
I am trying to:
Clear the stencil buffer to 0.
Draw a texture to the stencil buffer, setting the stencil buffer to 1 where the texture is drawn.
Draw another texture that will only appear where the stencil buffer is not 1.
Here is what I have so far, which appears to have no effect on the drawing of texture 2:
BlendState blend = new BlendState();
blend.ColorWriteChannels = ColorWriteChannels.None;
_preSparkStencil = new DepthStencilState();
_preSparkStencil.StencilEnable = true;
_preSparkStencil.StencilFunction = CompareFunction.Always;
_preSparkStencil.ReferenceStencil = 1;
_preSparkStencil.DepthBufferEnable = true;
_sparkStencil = new DepthStencilState();
_sparkStencil.StencilEnable = true;
_sparkStencil.StencilFunction = CompareFunction.NotEqual;
_sparkStencil.ReferenceStencil = 1;
_sparkStencil.DepthBufferEnable = true;
gd.DepthStencilState = _preSparkStencil;
gd.Clear(ClearOptions.Stencil, Color.Black, 0, 0);
sb.Begin(SpriteSortMode.Deferred, blend);
DrawTexture1();
sb.End();
gd.DepthStencilState = _sparkStencil;
sb.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
DrawTexture2();
sb.End();
gd.DepthStencilState = old;
回答1:
The problem was that the RenderState needs to be passed into SpriteBatch, or else the SpriteBatch will use it's own RenderState.
sb.Begin(SpriteSortMode.Deferred, BlendState.Opaque,
SamplerState.LinearWrap, _preSparkStencil,
RasterizerState.CullCounterClockwise, CLM.AlphaClip);
来源:https://stackoverflow.com/questions/5054839/stencil-testing-in-xna-4