0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Unity】VRで左右の目で異なるものを描画するシェーダー

Posted at

Unityのビルドインパイプラインで左右の目で異なる絵を描画したいときのシェーダー

重要なのは、v2f構造体でUNITY_VERTEX_OUTPUT_STEREOを定義、頂点シェーダーでUNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o)マクロを呼び出し、フラグメントシェーダーでUNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i)マクロを呼び出すこと。

unity_StereoEyeIndexにどちらの目かどうかの情報が入ります。

Shader "Unlit/SpacialPictureShader"
{
    Properties
    {
        _LeftEyeTex("Left Eye Texture", 2D) = "white" {}
        _RightEyeTex("Right Eye Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;

                UNITY_VERTEX_OUTPUT_STEREO // シングルパスステレオレンダリングで必要なパラメーター構造体
            };

            sampler2D _LeftEyeTex;
            sampler2D _RightEyeTex;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                UNITY_TRANSFER_FOG(o,o.vertex);

                // unity_StereoEyeIndexを頂点シェーダーからフラグメントシェーダーに転送するためのマクロ
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); 

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // このマクロを使用することでunity_StereoEyeIndexにフラグメントシェーダーでアクセスできるようになる。
                UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
                
                fixed4 col = fixed4(0, 0, 0, 1);

                if (unity_StereoEyeIndex == 0)
                {
                    // 左目の場合の処理
                    col = tex2D(_LeftEyeTex, i.uv);
                }
                else
                {
                    // 右目の場合の処理
                    col = tex2D(_RightEyeTex, i.uv);
                }

                // apply fog
                UNITY_APPLY_FOG(i.fogCoord, col);
                return col;
            }
            ENDCG
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?