
#ifdef FLAG_FOG
varying float fogDist;
#endif

#ifdef FLAG_DIFFUSE_MAP
uniform sampler2D sBasemap;
#endif

#ifdef FLAG_GLOW_MAP
uniform sampler2D sGlowmap;
#endif

#ifdef FLAG_SPEC_MAP
uniform sampler2D sSpecmap;
#endif

#ifdef FLAG_ENV_MAP
varying vec3 envReflect;

uniform samplerCube sEnvmap;

uniform bool alpha_spec;
#endif

#ifdef FLAG_NORMAL_MAP
varying vec3 lightVec, halfVec;

uniform sampler2D sNormalmap;
#endif

#ifdef FLAG_HEIGHT_MAP
uniform sampler2D sHeightmap;
#endif

void main()
{
	vec4 final_color;

#ifdef FLAG_NORMAL_MAP
	vec3 c_bump;

	// bump map - convert from DXT5nm
	c_bump.rg = (texture2D(sNormalmap, gl_TexCoord[0].xy).ag * 2.0) - 1.0;
	c_bump.b = sqrt(1.0 - dot(c_bump.rg, c_bump.rg));
#endif

#ifdef FLAG_HEIGHT_MAP
	vec3 c_hght = texture2D(sHeightmap, gl_TexCoord[0].xy).rgb;
	float h_offset = (0.04 * (length(c_hght) * 0.5)) - 0.01;
	vec2 uv_coords = (h_offset * normalize(halfVec).xy) + gl_TexCoord[0].xy;

	vec3 env_coords = c_bump * normalize(lightVec);
#else
	vec2 uv_coords = gl_TexCoord[0].xy;
	vec3 env_coords = vec3(0, 0, 0);
#endif

#ifdef FLAG_DIFFUSE_MAP
	vec4 c_base = texture2D(sBasemap, uv_coords);
#endif

#ifdef FLAG_GLOW_MAP
	vec3 c_glow = texture2D(sGlowmap, uv_coords).rgb * 1.5;
#endif

#ifdef FLAG_SPEC_MAP
	vec4 c_spec = texture2D(sSpecmap, uv_coords);
#endif

#ifdef FLAG_ENV_MAP
	vec3 c_env = textureCube(sEnvmap, envReflect + env_coords).rgb;
#endif

#ifdef FLAG_NORMAL_MAP
	float diffuseLight = max( dot(c_bump, normalize(lightVec)), 0.0 );
	vec4 lDiffuse = gl_Color + (gl_FrontLightProduct[0].diffuse * diffuseLight);

	float specLight = 0.0;

	if (diffuseLight > 0.0) {
		float dotV = clamp( dot(c_bump, normalize(halfVec)), 0.0, 1.0 );
		specLight = pow(max(0.0, dotV), gl_FrontMaterial.shininess);
	}

	vec4 lSpecular = gl_SecondaryColor + (gl_FrontLightProduct[0].specular * specLight);
#else
	vec4 lDiffuse = gl_Color;
	vec4 lSpecular = gl_SecondaryColor;
#endif

#ifdef FLAG_LIGHT

 #ifdef FLAG_DIFFUSE_MAP
	final_color.a = (lDiffuse.a * c_base.a) + (dot(lSpecular, lSpecular) * 0.1);
	final_color.rgb = lDiffuse.rgb * c_base.rgb;

  #ifdef FLAG_ENV_MAP
	final_color.a += dot(c_env, c_env) * 0.3;
  #endif

  #ifndef FLAG_SPEC_MAP
	final_color.rgb += lSpecular.rgb * (c_base.rgb * 1.2);
  #endif

 #else
	final_color = lDiffuse;

  #ifndef FLAG_SPEC_MAP
	final_color.rgb += lSpecular.rgb;
  #endif

 #endif

#else
	final_color = lDiffuse;

 #ifdef FLAG_DIFFUSE_MAP
	final_color *= c_base;
 #endif

#endif

#ifdef FLAG_ENV_MAP 
	final_color.rgb += (c_env * ((alpha_spec) ? vec3(c_spec.a) : c_spec.rgb));
#endif

#ifdef FLAG_SPEC_MAP
	final_color.rgb += lSpecular.rgb * (c_spec.rgb * 3.0);
#endif

#ifdef FLAG_GLOW_MAP
	final_color.rgb += c_glow;
#endif

#ifdef FLAG_FOG
	final_color.rgb = mix(final_color.rgb, gl_Fog.color.rgb, fogDist);
#endif

#ifdef FLAG_NORMAL_MAP
	gl_FragColor.rgb = c_bump.rgb;
#else
	gl_FragColor = vec4(0.0);
#endif
	gl_FragColor.a = 1.0;
	gl_FragColor = final_color;
}
