I am trying to create an image effect where only a part of the image has the effect applied to.
One way I can think of to do this is to define the portion of the image using the stencil buffer.
Stencil Mask Shader:
Stencil
{
Ref 1
Comp always
Pass replace
}
Image Effect Shader:
Stencil
{
Ref 1
Comp equal
Pass keep
}
OnRenderImage Function
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
saturationPassMat = CheckShaderAndCreateMaterial(saturationShader, saturationPassMat);
saturationPassTex = RenderTexture.GetTemporary(source.width, source.height, 24);
Graphics.SetRenderTarget(saturationPassTex.colorBuffer, source.depthBuffer);
Desaturate(source, saturationPassTex, saturation);
Graphics.Blit(saturationPassTex, destination);
}
Applying the stencil portion of the image effect shader to any other object produces a desirable stencil effect (aka: it works).
The Problem:
By the time OnRenderImage is called, it seems that the stencil buffer has already been cleared. Changing Ref
to 0 in the Image Effect shader will apply the effect to the entire screen. Any other value will result in a black screen. This can only mean that the stencil buffer has been cleared to 0.
Is there a way to prevent the stencil buffer from clearing? Or is this the right method to use the stencil buffer with image effects? Or perhaps there are other solutions that are still efficient, without the use of Stencils?