'Problem wrapping equirectangular image with OpenGl fragment

I try loading a plane white image (size 1920x1920 pixels) to my OpenGl fragment shader and perform an equirectangular to spherical wrapping. However, I am getting different results than expected. The mathematics behind the following code can be found in http://paulbourke.net/dome/2fish/

the expected wrapped image should look like:

enter image description here

and the image I get looks like:

enter image description here

My code:

const GLchar* vertexSource = R"glsl(
#version 150 core
in vec2 position;
in vec2 texcoord;
out vec2 Texcoord;

void main() {
    Texcoord = texcoord;
    gl_Position = vec4(position, 0.0, 1.0);
})glsl";





const GLchar* fragmentSource = R"glsl(
#version 150 core
in vec2 Texcoord;
out vec4 outColor;
uniform sampler2D sampler;


// --- Constants ---  
float c_pi = 3.14159265358979323846264;
float c_halfPi = c_pi * 0.5;

void main() {
    float longitude = ((Texcoord.x - 0.5) * 2.0) * c_halfPi;
    float lattitude = ((Texcoord.y - 0.5) * 2.0) * c_halfPi;
    
    float x3D = cos(lattitude) * sin(longitude);
    float y3D = cos(lattitude) * cos(longitude);
    float z3D = sin(lattitude);
    
    float theta = atan(z3D,x3D);
    float r =  2 * (atan(sqrt( x3D * x3D + z3D * z3D),y3D)) / c_pi;
    
    float new_x =  (r * cos(theta) + 1.0) * 0.5;
    float new_y =  (-r * sin(theta) + 1.0) * 0.5;
    
    outColor =  texture2D(sampler, vec2(new_x, new_y));
}
)glsl";


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source