Shaders : Is Transparency + Depth Testing possible ?

In unity I’m using CG Shaders and I want to fade objects in. There’s a slight problem/pop-in/glitch when going from a shader that has depth testing enabled to a shader that has alpha blending on.

From the pragma flags in a CGPROGRAM I can only enable/disable alpha blending, but this turns off depth testing. I want to keep depth testing on, so my fading is smooth (and I only get the front faces of objects rendered, not backfaces too, like it seems to be the default when blending is on). All the other standard “shader” flags like ZTest do not seem to affect shaders written with CGPROGRAMs, nor does ZTest configure wether depth testing is on or off.

Another question I’d have is if I can control the color mask ?(i.e. glColorMask).

Is there any other way to control render states besides shaders ?

Got my answer, the issue is CGPROGRAM + Surface “shaders”. If you use the surface function path that adds in extra shader code behind the curtains about lights & shadows, you get your render states overwritten. So anything like

Blend SrcAlpha OneMinusSrcAlpha
ZTest Always
ZWrite Off

will get overwritten. What you need to do is provide full vertex & fragment shaders and probably reproduce Unity default functionality (lights & shadows).

Note that because of this there’s 2 distinct ways to write CGPROGRAMs, one major difference being the extra “Pass {” bracket which is not required when writting “surface shaders”.