//stencil.cpp
//draw a covering plane whereever stencil values are !=0, to simulate shadow and light volumes

#include <OpenGL/gl.h>
#include "vectors.h"
#include "environment.h"
#include "screen.h"
#include "gamemem.h"
#include "config.h"

float gStencilZoom=1.0;

//draw a covering plane whereever stencil values are !=0
//if shadow is true draw using shadow color to simulate shadow volumes
//else draw using spotlight color to simulate light cones.
void RenderStencilLayer(int shadow,int stencil)
{
	if(!stencil)
		return;
	glPushAttrib(GL_DEPTH_BUFFER_BIT+GL_LIGHTING_BIT+GL_COLOR_BUFFER_BIT+GL_TEXTURE_BIT+GL_CURRENT_BIT+GL_STENCIL_BUFFER_BIT);

	GLfloat shadowColor[4];	
	if(shadow)
	{
		*(tVector3*)shadowColor=gEnvironment->shadowColor;
		shadowColor[3]=gEnvironment->shadowIntensity;
		shadowColor[3]/=stencil;
	}
	else
	{
		*(tVector3*)shadowColor=gEnvironment->spotLightColor*(1/(stencil*1.5));
		shadowColor[3]=1;		
	}
	
	
	glColor4fv(shadowColor);

	glDisable(GL_LIGHTING);
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_DEPTH_TEST);

	glEnable(GL_BLEND);
    glEnable(GL_STENCIL_TEST);

	glStencilFunc(GL_NOTEQUAL, 1, 0xffffffff);

	glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);
		
	if(shadow)
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	else
		glBlendFunc(GL_DST_COLOR, GL_ONE);
	
	glLoadIdentity();
	glBegin(GL_TRIANGLE_STRIP);
		glVertex3f(-2.0f, 1.0f,-1.00f);
		glVertex3f(-2.0f,-1.0f,-1.00f);
		glVertex3f( 2.0f, 1.0f,-1.00f);
		glVertex3f( 2.0f,-1.0f,-1.00f);
	glEnd();

	glPopAttrib();
}
