Linear01値からDepth値を求める
環境
Unity2022.3.1f1
概要
Linear01Depth(float z)の逆の関数です。参考のままです。
C#でテスト。同じ値になりました。
using UnityEngine;
public class TestDepthValue : MonoBehaviour
{
Vector4 _ZBufferParams;
void Start()
{
_ZBufferParams = Shader.GetGlobalVector("_ZBufferParams");
var depth = 0.5f;
var linear01 = Linear01Depth(depth);
Debug.Log($"1 linear01:{depth}>{linear01}");
depth = DepthFromLinear01(linear01);
Debug.Log($"1 linear01:{linear01}>{depth}");
linear01 = 0.2345f;
depth = DepthFromLinear01(linear01);
Debug.Log($"2 linear01:{linear01}>{depth}");
linear01 = Linear01Depth(depth);
Debug.Log($"2 linear01:{depth}>{linear01}");
depth = 0.5f;
var linearEye = LinearEyeDepth(depth);
Debug.Log($"3 linearEye:{depth}>{linearEye}");
depth = DepthFromLinearEye(linearEye);
Debug.Log($"3 linear01:{linearEye}>{depth}");
linearEye = 0.4567f;
depth = DepthFromLinearEye(linearEye);
Debug.Log($"4 linear01:{linearEye}>{depth}");
linearEye = LinearEyeDepth(depth);
Debug.Log($"4 linearEye:{depth}>{linearEye}");
}
float Linear01Depth(float z)
{
return 1.0f / (_ZBufferParams.x * z + _ZBufferParams.y);
}
float DepthFromLinear01(float linear01)
{
//linear01といっても1.0f / _ZBufferParams.y未満にはならないと思われる
//return (1.0f / ( linear01 * _ZBufferParams.x)) - (_ZBufferParams.y / _ZBufferParams.x);
//return ((1.0f / linear01) - _ZBufferParams.y) / _ZBufferParams.x;
return (1.0f - _ZBufferParams.y * linear01) / (_ZBufferParams.x * linear01);
}
float LinearEyeDepth(float z)
{
return 1.0f / (_ZBufferParams.z * z + _ZBufferParams.w);
}
float DepthFromLinearEye(float linearEye)
{
//return ((1.0f / linearEye) - _ZBufferParams.w) / _ZBufferParams.z;
return (1.0f - _ZBufferParams.w * linearEye) / (_ZBufferParams.z * linearEye);
}
}
参考
Linear01Depth()で線形にした深度値を元の値に戻したい #Unity - Qiita
DecodeDepthNormal/Linear01Depth/LinearEyeDepth explanations - Unity Forum