#version 330

layout( triangles ) in;
layout( triangle_strip, max_vertices = 6) out;

uniform mat4 WorldView;
uniform mat4 WorldViewProj;
uniform int ResolutionX;
uniform int ResolutionY;

uniform int OutlineWidthMode;
uniform float OutlineWidthFactor;

in vec3 VSWorldPos[];
in vec4 VSColor[];
in vec3 VSNormal[];
in vec2 VSTexCoord[];
#if USE_TANGENT
in vec3 VSTangent[];
in vec3 VSBinormal[];
#endif
#if MULTIUV >= 1
in vec2 VSTexCoord1[];
#endif
#if MULTIUV >= 2
in vec2 VSTexCoord2[];
#endif
#if MULTIUV >= 3
in vec2 VSTexCoord3[];
#endif

out vec4 GSWorldPos;
out vec4 GSColor;
out vec3 GSNormal;
out vec2 GSTexCoord;
#if USE_TANGENT
out vec3 GSTangent;
out vec3 GSBinormal;
#endif
#if MULTIUV >= 1
out vec2 GSTexCoord1;
#endif
#if MULTIUV >= 2
out vec2 GSTexCoord2;
#endif
#if MULTIUV >= 3
out vec2 GSTexCoord3;
#endif

vec4 GetOutlinePos(int id)
{
	float width = OutlineWidthFactor;
	//if(HasOutlineWidthMultiplyMap)
	//	width *= OutlineWidthMultiplyMap.Sample(ColorMapSampler, GetTexCoord(input,HasOutlineWidthMultiplyMap)).g; // GS not support sample.
	if(OutlineWidthMode == 2){
		if(gl_in[id].gl_Position.w != 0.0 && gl_in[id].gl_Position.z/gl_in[id].gl_Position.w > -1.0){
			vec3 axisX = vec3(WorldView[0][0], WorldView[1][0], WorldView[2][0]);
			vec4 pos = WorldViewProj * vec4(VSWorldPos[id] + axisX, 1);
			vec2 p1 = pos.xy / pos.w;
			vec2 p0 = gl_in[id].gl_Position.xy / gl_in[id].gl_Position.w;
			float w = 1.0 / float(ResolutionX) * (float(ResolutionY) / 1000.0) * 2;
			float scale = width * w / length(p1 - p0);
			return WorldViewProj * vec4(VSWorldPos[id] + VSNormal[id] * scale, 1);
		}else{
			return gl_in[id].gl_Position;
		}
	}else{
		return WorldViewProj * vec4(VSWorldPos[id] + VSNormal[id] * width, 1);
	}
}

void main(void)
{
	for(int i=0; i<3; i++){
		GSWorldPos = vec4(VSWorldPos[i],1);
		GSColor = VSColor[i];
		GSNormal = VSNormal[i];
		GSTexCoord = VSTexCoord[i];
#if USE_TANGENT
		GSTangent = VSTangent[i];
		GSBinormal = VSBinormal[i];
#endif
#if MULTIUV >= 1
		GSTexCoord1 = VSTexCoord1[i];
#endif
#if MULTIUV >= 2
		GSTexCoord2 = VSTexCoord2[i];
#endif
#if MULTIUV >= 3
		GSTexCoord3 = VSTexCoord3[i];
#endif
		gl_Position = gl_in[i].gl_Position;
		EmitVertex();
	}
	EndPrimitive();

	if(OutlineWidthMode != 0 && OutlineWidthFactor > 0.0){
		for(int i=2; i>=0; i--){
			GSWorldPos = vec4(VSWorldPos[i],0);
			GSColor = VSColor[i];
			GSNormal = VSNormal[i];
			GSTexCoord = VSTexCoord[i];
#if USE_TANGENT
			GSTangent = VSTangent[i];
			GSBinormal = VSBinormal[i];
#endif
#if MULTIUV >= 1
			GSTexCoord1 = VSTexCoord1[i];
#endif
#if MULTIUV >= 2
			GSTexCoord2 = VSTexCoord2[i];
#endif
#if MULTIUV >= 3
			GSTexCoord3 = VSTexCoord3[i];
#endif
			gl_Position = GetOutlinePos(i);
			EmitVertex();
		}
		EndPrimitive();
	}
}

