3

我在理解 glsl 中 atan 函数的结果时遇到了一些问题。文档也缺乏。

例如,我需要将顶点转换为球坐标,转换球坐标的半径,然后将其转换回笛卡尔坐标。我在以 0 为中心的半径为 2 的 icosphere 的顶点上使用以下变换。

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;
}

但如果我使用atan(y/x)or ,结果会有所不同atan2(y,x)1E-18为了避免极点,我设置了小常数。

为什么会有这种行为?我假设atan(y/x)和返回的值atan2(y,x)具有不同的范围。特别是在这个实现中,我认为theta应该从[0-Pi]whilePhi范围内[0,2Pi]

我对吗?是否有更精确的球面坐标变换实现?

4

1 回答 1

8

atan2正确占所有 4 个象限并且可以处理x==0.

atan2(-1,-1)正确返回-3/4*PI,而atan(-1/-1)将返回1/4*PI

于 2014-09-11T08:47:24.070 回答