- Home /
How can I distort deferred decals?
Hello everybody!
We are working on deferred decals right now. Given the shape of a cube, which can be freely scaled and rotated, the system projects the decal on the world with that shape. This allows for cool effects such as skewed decals.
What we would like to do, however, is be able to freely transform the shape of the cube, that is, be able to specify the position of each vertex as desired by code; so that the resulting decal is properly projected. We want to achieve a distortion similar as the one shown here:
To do that, we need to specify the position of each vertex and pass that into the shader, somehow, to distort the image accordingly. How can we do that?
The C# code we use is the following:
Mesh mesh = CreateCubeMesh(); //The exact implementation is irrelevant
CommandBuffer commandBuffer = new CommandBuffer();
//Some otehr code...
commandBuffer.DrawMesh(mesh, transform.localToWorldMatrix, material);
The vertex function we use is the following:
v2f vert(appdata v)
{
v2f o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = ComputeScreenPos(o.pos);
o.ray = mul(UNITY_MATRIX_MV, v.vertex).xyz * float3(-1, -1, 1);
o.decalNormal = normalize(mul((float3x3)unity_ObjectToWorld, float3(0, 1, 0)));
o.decalTangent = normalize(mul((float3x3)unity_ObjectToWorld, float3(1, 0, 0)));
return o;
}
And the fragment function is this:
void frag(v2f i, out float4 outSpecSmoothness : SV_Target0, out float4 outNormal : SV_Target1)
{
i.ray = i.ray * (_ProjectionParams.z / i.ray.z);
float2 uv = i.uv.xy / i.uv.w;
float limitTo = GetLimitTo();
if (!isnan(limitTo))
clip(abs(limitTo - tex2D(_DecaliciousLimitToGameObject, uv).r) > 0.1f ? -1 : 1);
float depth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, uv);
depth = Linear01Depth(depth);
float4 vpos = float4(i.ray * depth,1);
float3 wpos = mul(unity_CameraToWorld, vpos).xyz;
float3 clipPos = mul(unity_WorldToObject, float4(wpos, 1)).xyz;
clip(0.5f - abs(clipPos.xyz));
float2 texUV = TRANSFORM_TEX((clipPos.xz + 0.5), _MainTex);
float mask = tex2D(_MaskTex, texUV).r * GetMaskMultiplier();
clip(mask - 0.0005f);
}
Follow this Question
Related Questions
Shader is using forward lighting against my will? 1 Answer
toonLighted shader to work with deferred rendered shadows 2 Answers
Can someone explain what I'm doing wrong in these shaders? 0 Answers
exclude_path:deferred causes see through? 0 Answers
Shader not working properly in Deferred render mode 0 Answers