Hello,
I am trying to achieve an effect such as this: http://wiki.unity3d.com/index.php?title=DepthMask
However, in deferred rendering, it does not seem to be possible to do it this way. Is there a way to make an object prevent another object behind it from rendering, in deferred mode?
Thanks.
Update:
I have managed to come up with a solution. Instead of using render queues like in the forward rendering pipeline, I draw my masks with another camera onto a render texture with the same resolution as my screen. I then pass this render texture to the shader of the object I want to mask via a texture property. Finally, I use this texture by sampling at the screen space position of the fragment and deleting pixels where the mask was rendered onto the texture. To delete pixels I use the clip function. Here is my shader:
Shader “Custom/SimpleTerrain”
{
Properties
{
_MaskTexture(“Terrain Mask”, 2D) = “white” {}
}
SubShader
{
Tags { “RenderType” = “Opaque” “Queue” = “Geometry”}
LOD 200
CGPROGRAM
#pragma surface surf Standard fullforwardshadows
#pragma target 4.0
sampler2D _MaskTexture;
struct Input
{
float4 color : COLOR;
float4 screenPos;
};
UNITY_INSTANCING_BUFFER_START(Props)
// put more per-instance properties here
UNITY_INSTANCING_BUFFER_END(Props)
void surf(Input IN, inout SurfaceOutputStandard o)
{
clip(0.5 - tex2D(_MaskTexture, IN.screenPos.xy / IN.screenPos.w).rgb);
float4 c = IN.color;
o.Albedo = c.rgb;
o.Alpha = 1;
o.Metallic = 0;
o.Smoothness = 0;
}
ENDCG
}
FallBack “Diffuse”
}
Here is the full C# script I attached to the mask render texture camera:
using UnityEngine;
public class MaskRenderer : MonoBehaviour
{
Camera maskCamera;
[SerializeField] Material terrainMaterial;
RenderTexture terrainMask;
private void Awake()
{
maskCamera = this.GetComponent<Camera>();
terrainMask = new RenderTexture(Screen.width, Screen.height, 0);
maskCamera.targetTexture = terrainMask;
terrainMaterial.SetTexture("_MaskTexture", terrainMask);
}
}
Camera: The camera used to render the texture of the masks must have identical settings to the main camera, otherwise you will be masking out the wrong areas of your object. Also, don’t forget to set the culling mask to the layer the mask objects are on, and clear flags to solid color with a black background.
Note: It is important that the mask is rendered with a material that will give you bright color. The default unlit “Color” shader works well when set to pure white.