#version 330 core
in vec2 UV;
in vec3 n;
in vec4 worldPos;
in vec4 modelPos;
layout(location = 0) out vec4 color;
layout(location = 1) out vec4 outnormal;
uniform sampler2D disp;
uniform sampler2D env;
uniform vec3 boxScale;
uniform vec3 boxOffset;
uniform int glitcherShitser;
uniform int model;

const float a = 0.9999;

vec3 toS(vec3 n) {
	float X = n.x;
	float Y = n.y;
	float Z = n.z;
	float radius = length(n);
	return vec3(radius, 0.5 * (1.0 + 2.0 * atan(Y, X) / 3.141), acos(Z / radius)/3.141);
}

bool magicFunction(float inp) {
	bvec3 modstuff = lessThan(boxScale, abs(mod(boxOffset + modelPos.xyz, 2.0 * boxScale)));
	return (glitcherShitser != 0) && (modstuff.x || modstuff.y || modstuff.z); //(mod(2.5*inp*inp, 2.0) < 0.25);
}

void fartzGang() {
	if (magicFunction(worldPos.z)) {
		discard;
	}
	vec3 nout = 0.5 + 0.5 * n;
	color = vec4(a * nout + (1.0 - a) * vec3(UV, 1.0), 1.0);
	//color = vec4(vec3(0.25), 1.0) + vec4(max(0.0, dot(n, normalize(vec3(0.0, 1.0, -1.0)))));
	vec2 lut = vec2(0.0);
	vec3 normal = n;

	if ((abs(normal.x) > abs(normal.y)) && (abs(normal.x) > abs(normal.z))) {
		lut = (normal.yz + vec2(1.0)) / abs(normal.x) / 2.0;
	}
	else if ((abs(normal.y) > abs(normal.x)) && (abs(normal.y) > abs(normal.z))) {
		lut = (normal.xz + vec2(1.0)) / abs(normal.y) / 2.0;
	}
	else {
		lut = (normal.xy + vec2(1.0)) / abs(normal.z) / 2.0;
	}
	//lut = toS(normal).yz;
	vec4 texval = texture(env, lut); // vec2(0.5) + 0.5*toS(n).yz);
	float normalfactor = max(0.0, dot(n, normalize(vec3(2.0, 0.5, -1.0))));
	float intensity = 1.0 - dot(normalize(vec3(1.0)), texval.rgb);
	vec4 inputcol = intensity * texval + (1.0 - intensity) * vec4(vec3(intensity), 1.0);
	color = normalfactor * texval * texval + (1.0 - normalfactor) * 3.4*vec4(0.25,0.25,0.25,1.0);
	color = vec4(0.25,0.25,0.25,1.0) + texval;
	color.a = 1.0;
	outnormal = vec4(n, 1.0);
}

void sphere() {
	const float siilinjarviCoefficient = 1.0;
	float quantity = worldPos.y * 10.0 / length(worldPos); // worldpos pitäisi olla jokin eri?
	float realval = quantity * siilinjarviCoefficient;
	float prev = floor(realval);
	float next = ceil(realval);
	float mindist = min(abs(realval - prev), abs(realval - next));
	float modulofactor = smoothstep(mindist*mindist, 0.0, 0.02) * float(mod(prev, 2.0) < 0.1);
	modulofactor = float(abs(mod(prev, 2.0)));


	color = vec4(vec3(0.1), 0.0) + vec4(modulofactor * vec3(1.0) * smoothstep(abs(worldPos.y), 0.0, 3.0) * 0.9, 1.0);
	outnormal = vec4(-n, 1.0);
}

void main() {
	if (model == 0) {
		fartzGang();
	} else {
		sphere();
	}
	//color = texval;
	//color = texval * texval + 0.5*vec4(0.25,0.25,0.25,1.0);
	//color = texture(disp, UV);
	//color = vec4(n, 1.0);
}
