#version 400 core

out vec4 FragColor;

uniform vec2 u_resolution;
uniform sampler2D posX;
uniform sampler2D negX;
uniform sampler2D posY;
uniform sampler2D negY;
uniform sampler2D posZ;
uniform sampler2D negZ;

float pi = 3.1415926536;

vec3 sampleSkybox(vec3 rd);

void get_panorama( out vec4 fragColor, in vec2 P ) {
    float theta = (1.0 - P.y) * pi;
    float phi   = P.x * pi * 2.0;
    vec3 dir = vec3(sin(theta) * sin(phi), cos(theta), sin(theta) * cos(phi));
    fragColor.rgb = (sampleSkybox(dir));
    fragColor.a=1.;
}


void mainImage( out vec4 fragColor, in vec2 fragCoord) {
    vec2 P = fragCoord.xy / u_resolution.xy;
    get_panorama(fragColor,P);
    fragColor.a=1.;
}

void main() {
    //FragColor = vec4(1, 0.5, 0.5, 1.0f);
    vec4 fragColor = vec4(0,0,0,0);
    mainImage(fragColor,gl_FragCoord.xy);
    gl_FragColor = fragColor;
} 

vec3 sampleSkybox(vec3 rd) {
	vec3 cg = vec3(0,0,0);
	if(abs(rd.y) > abs(rd.x) && abs(rd.y) > abs(rd.z)) {
		if(abs(rd.y) < 1e-8) return cg;
		float t = -1 / rd.y;
		vec3 a = rd * t;
		vec2 uv = a.xz * 0.5 + 0.5;
		while(abs(uv.x) > 1) uv.x -= sign(uv.x);
		while(abs(uv.y) > 1) uv.y -= sign(uv.y);
		if(t < 0) {
			uv = 1 - uv;
			return texture(posY, uv).rgb;
		}else {
			uv.y = 1 - uv.y;
			return texture(negY, uv).rgb;
		}
	}else if(abs(rd.x) > abs(rd.y) && abs(rd.x) > abs(rd.z)) {
		if(abs(rd.x) < 1e-8) return cg;
		float t = -1 / rd.x;
		vec3 a = rd * t;
		vec2 uv = a.zy * 0.5 + 0.5;
		while(abs(uv.y) > 1) uv.y -= sign(uv.y);
		if(t < 0) {
			return texture(posX, uv).rgb;
		}else {
			uv.y = 1 - uv.y;
			return texture(negX, uv).rgb;
		}
	}else if(abs(rd.z) > abs(rd.x) && abs(rd.z) > abs(rd.y)) {
		if(abs(rd.z) < 1e-8) return cg;
		float t = -1 / rd.z;
		vec3 a = rd * t;
		vec2 uv = a.xy * 0.5 + 0.5;
		while(abs(uv.x) > 1) uv.x -= sign(uv.x);
		while(abs(uv.y) > 1) uv.y -= sign(uv.y);
		if(t < 0) {
			uv.x = 1 - uv.x;
			return texture(posZ, uv).rgb;
		}else {
			uv.x = 1 - uv.x;
			uv.y = 1 - uv.y;
			return texture(negZ, uv).rgb;
		}
	}

	return vec3(0,0,0);
}
