Robust atan(y,x) on GLSL for converting XY coordinate to angle

后端 未结 5 687
花落未央
花落未央 2021-02-02 16:34

In GLSL (specifically 3.00 that I\'m using), there are two versions of atan(): atan(y_over_x) can only return angles between -PI/2, PI/2, while

5条回答
  •  独厮守ぢ
    2021-02-02 17:08

    Your proposed solution still fails in the case x=y=0. Here both of the atan() functions return NaN.

    Further I would not rely on mix to switch between the two cases. I am not sure how this is implemented/compiled, but IEEE float rules for x*NaN and x+NaN result again in NaN. So if your compiler really used mix/interpolation the result should be NaN for x=0 or y=0.

    Here is another fix which solved the problem for me:

    float atan2(in float y, in float x)
    {
        return x == 0.0 ? sign(y)*PI/2 : atan(y, x);
    }
    

    When x=0 the angle can be ±π/2. Which of the two depends on y only. If y=0 too, the angle can be arbitrary (vector has length 0). sign(y) returns 0 in that case which is just ok.

提交回复
热议问题