#version 330

in vec2 UV;

layout(location = 0) out vec4 ND;
layout(location = 1) out vec4 albedo;

uniform sampler2D texNormalDepth;
uniform sampler2D texAlbedo;
uniform vec2 resolution;

vec2 offset[] = vec2[](vec2(-1,-1), vec2(0,-1), vec2(1,-1),
vec2(-1,0), vec2(1,0),
vec2(-1,1), vec2(0,1), vec2(1,1));

//ND: packed normal xy, var1, depth
//albedo: albedo rgb, var2
 
void main(){
	ND = texture(texNormalDepth, UV).rgba;
	albedo = texture(texAlbedo, UV).rgba;
	//copy color, look around when not found
	if (ND.a<=0.001) {

		ND = vec4(0);
		albedo = vec4(0);
		int cnt = 0;
		for(int i = 0; i < 8; i++) {
			vec2 UV2 = UV + offset[i]/resolution;
			vec4 ND2 = texture(texNormalDepth, UV2).rgba;
			vec4 albedo2 = texture(texAlbedo, UV2).rgba;

			if (ND2.a>0.001) {
				ND.rgb += ND2.rgb;
				if (ND2.a > ND.a)
					ND.a = ND2.a;
				albedo += albedo2;
				cnt++;
			}
		}

		//average or reject
		if (cnt!=0) {
			ND.rgb /= cnt;
			albedo /= cnt;
		}
	}
	else {

		float var1 = 0;
		float var2 = 0;
		int cnt = 0;
		for(int i = 0; i < 8; i++) {
			vec2 UV2 = UV + offset[i]/resolution;
			vec4 ND2 = texture(texNormalDepth, UV2).rgba;
			vec4 albedo2 = texture(texAlbedo, UV2).rgba;

			if (ND2.a>0.001) {
				var1 += ND2.b;
				var2 += albedo2.a;
				cnt++;
			}
		}

		//average or reject
		if (cnt!=0) {
			var1 /= cnt;
			var2 /= cnt;
			ND.b = var1;
			albedo.a = var2;
		}
	}
}