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?