LoginSignup
3
1

More than 3 years have passed since last update.

Linear01Depth()で線形にした深度値を元の値に戻したい

Last updated at Posted at 2020-07-13

UnityでDepthTextureを取得する際に、線形にして見やすくするアプローチがあります。
その際使用する関数Linear01Depth()ですが、
それで求めた線形の深度値を「元の深度値に戻したい」時に使うべき関数が見当たらなかったので自作した時のメモを残しておきます。

そもそもLinear01Depth()は内部で何をやっているかというと、BuiltInShaderの内部のUnityCG.cgincを覗くとこんなコードが、

UnityCG.cginc
// Z buffer to linear 0..1 depth
inline float Linear01Depth( float z )
{
    return 1.0 / (_ZBufferParams.x * z + _ZBufferParams.y);
}

という事で、この計算を元にzを求めましょう。

depth01 = 1.0 / (__ZBufferParams.x * z + _ZBufferParams.y);
↓除算部分をひっくり返す
(_ZBufferParams.x * z + _ZBufferParams.y) * depth01 = 1.0;
↓()を外す
_ZBufferParams.x * z * depth01 + _ZBufferParams.y * depth01 = 1.0;
↓左辺の右半分を右辺に
_ZBufferParams.x * z * depth01 = 1.0 - _ZBufferParams.y * depth01;
↓zだけに残して完成
z = (1.0 - _ZBufferParams.y * depth01) / (_ZBufferParams.x * depth01);

わざわざ中学生レベルの式を書いてしまった。。
という事で、下記の関数で元の深度値に戻すことができます。

float Linear01DepthToSrcDepth( float depth01 )
{
    return (1.0 - _ZBufferParams.y * depth01) / (_ZBufferParams.x * depth01);
}

ちゃんと探せていないだけですでにある予感はしていますが、一応書き残しておきます。
もしご存じの方いれば情報いただけますと幸いです;

3
1
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
3
1