What is the difference from atan (y / x) and atan2 (y, x) in OpenGL GLSL

I have some trouble understanding the result of the atan function in glsl. The documentation is also lacking.

For example, I need to convert a vertex to spherical coordinates, convert the radius to spherical coordinates, and then convert it back to cartesian coordinates. I use the following transform on the icosphere vertices of radius 2 centered at 0.

vec3 to_sphere(vec3 P)
{
    float r = sqrt(P.x*P.x + P.y*P.y + P.z*P.z);
    float theta = atan(P.y,(P.x+1E-18));
    float phi= acos(P.z/r); // in [0,pi]
    return vec3(r,theta, phi);
}

vec3 to_cart(vec3 P)
{
    float r = P.x;
    float theta = P.y;
    float phi = P.z;
    return r * vec3(cos(phi)*sin(theta),sin(phi)*sin(theta),cos(theta);
}

void main()
{
    vec4 V = gl_Vertex.xyz;
    vec3 S = to_sphere(V.xyz);
    S.x += S.y;
    V.xyz = to_cartesian(S);

    gl_Position = gl_ModelViewProjectionMatrix * V;
}

      

but the result is different if I use atan(y/x)

or atan2(y,x)

. I put in a small constant 1E-18

to avoid the pole.

Why is this behavior? I believe the value returned by atan(y/x)

and atan2(y,x)

has a different range. Specifically, in this implementation, I believe I theta

should be in the range from [0-Pi]

, a Phi

- to [0,2Pi]

.

I'm right? Are there more numerically accurate realizations of transformations of spherical coordinates?

+3


source to share


1 answer


atan2

correctly accounts for all 4 quadrants and can deal with x==0

.



atan2(-1,-1)

returns correctly -3/4*PI

, but atan(-1/-1)

returns1/4*PI

+7


source







All Articles