Texture space shader (test/demo).

Posted on 2017-06-11 in unity3d

This is a quick shader made for demonstrating transforms that can be used to render into texture space.

code:

Shader "Unlit/DecalUnwrap"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _decalBlend ("DecalBlend", Range(0.0, 1.0)) = 0.0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float3 normal: NORMAL;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float3 worldPos: TEXCOORD1;
                float3 worldNormal: TEXCOORD2;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float _decalBlend;

            v2f vert (appdata v)
            {
                v2f o;
                o.worldPos = mul(_Object2World, v.vertex).xyz;

                float3 curWorldPos = lerp(o.worldPos, float3(v.uv*2.0 - 1.0, 0.0), _decalBlend);
                o.vertex = mul(UNITY_MATRIX_VP, float4(curWorldPos, 1.0));
                o.worldNormal = mul(_Object2World, float4(v.normal, 0.0)).xyz;
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                col.xyz *= i.worldNormal*0.5+0.5;
                return col;
            }
            ENDCG
        }
    }
}