如何在着色器中获得纹理大小?

时间:2018-10-19 12:26:40

标签: unity3d shader cg shaderlab

我正在尝试为LineRenderer(Unity组件)实现着色器。而且我需要在碎片着色器中获得x轴的值从0到1,这意味着在局部纹理坐标中的位置(0表示纹理左侧的像素,1表示右侧边框)。

正如文档所述,_MainTex_TexelSize包含有关纹理大小的信息,_MainTex_ST包含有关拼贴的信息。这样看来很简单。我需要将uv.x(_MainTex_TexelSize.z * _MainTex_ST.x)相乘。

有我的着色器:

Shader "LineRendering/Test"
{
    Properties
    {
        [PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
    }

    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
            "PreviewType" = "Plane"
            "CanUseSpriteAtlas" = "True"
        }

        LOD 200

        Cull Off
        Lighting Off
        ZWrite Off
        Fog { Mode Off }
        Blend One OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM

            #pragma target 3.0          
            #pragma vertex vert
            #pragma fragment frag
            #pragma enable_d3d11_debug_symbols

            #include "UnityCG.cginc"
            #include "noiseSimplex.cginc"

            struct appdata_t
            {
                fixed4 vertex : POSITION;
                fixed2 uv : TEXCOORD0;
            };

            struct v2f
            {
                fixed4 vertex : SV_POSITION;
                fixed2 uv : TEXCOORD0;
                fixed2 srcPos : TEXCOORD1;
                fixed2 texelSize : TEXCOORD2;
                fixed2 tilingCapacity : TEXCOORD3;
            };

            uniform fixed4 _MainTex_TexelSize, _MainTex_ST;

            v2f vert(appdata_t IN)
            {
                v2f OUT;

                OUT.vertex = UnityObjectToClipPos(IN.vertex);
                OUT.uv = IN.uv;
                //OUT.uv = TRANSFORM_TEX(IN.uv, _MainTex);
                //OUT.uv = fixed2(IN.uv.x * (_MainTex_ST.x + _MainTex_ST.z), (IN.uv.y +  * _MainTex_ST.y));
                //OUT.uv = (IN.uv * _MainTex_ST.xy + _MainTex_ST.zw);               

                OUT.texelSize = fixed2(_MainTex_TexelSize.z, _MainTex_TexelSize.w);
                OUT.tilingCapacity = fixed2(_MainTex_ST.x, _MainTex_ST.y);

                return OUT;
            }

            fixed4 frag(v2f IN) : COLOR
            {
                fixed4 output;
                output.a = 1;

                fixed relativeWidth = IN.uv.x / (IN.texelSize.x * IN.tilingCapacity.x);             

                //fixed relativeWidth = IN.uv.x / (_MainTex_TexelSize.z * _MainTex_ST.x);                   

                output.rgb = fixed3(relativeWidth, relativeWidth, relativeWidth);

                return output;
            }

            ENDCG
        }
    }
}

但是此着色器无法正常工作。

How it's looks like

我正在尝试在运行时调试此着色器,但结果却很奇怪。特塞尔尺寸和切片容量变量的值为1

Shader debug.

所以我需要你的帮助。我究竟做错了什么?在Unity中还有其他方法来获取LineRenderer的纹理大小吗?

0 个答案:

没有答案