Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've some problems in understanding the result of the function atan in glsl. Documentation is also lacking.

For example I need to convert a vertex to spherical coordinates, transform the radius of the spherical coordinate and then convert it back to cartesian coordinates. I'm using the following transformation on the vertices of an icosphere of radius 2 centered in 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've put the small 1E-18 constant in order to avoid a pole.

Why this behaviour? I'm supposing that the value returned by atan(y/x) and atan2(y,x) has different range. In particular in this implementation I think that theta should range from [0-Pi] while Phi ranges in [0,2Pi].

Am I right? Are there more numerically precise implementations of spherical coordinates transformations?

like image 730
linello Avatar asked Sep 01 '25 17:09

linello


1 Answers

atan2 properly accounts for all 4 quadrants and can deal with x==0.

atan2(-1,-1) properly returns -3/4*PI while atan(-1/-1) would return 1/4*PI

like image 57
ratchet freak Avatar answered Sep 04 '25 13:09

ratchet freak