////////////////////////////////////////////////////////////////////////////////
// LightSource.cpp
// Stores data on a light source
// Copyright Bjoern Ganster
// Developed since 2021
////////////////////////////////////////////////////////////////////////////////

#include "LightSource.h"

LightSource::LightSource(GLenum lightNo)
: RenderableObject("RenderableObject", RenderableObjectID),
  mLightNo(lightNo),
  mAmbientFactor(0.3f),
  mSpecularFactor(1.0f),
  mConstantAttenuation(1.0),
  mLinearAttenuation(0.0), 
  mQuadraticAttenuation(0.0),
  mRenderShadows(false)
{
}

// Destructor
LightSource::~LightSource()
{
	deactivate();
}

// Activate light source
void LightSource::activate(bool renderingShadows)
{
	// Activate light source
	glEnable(GL_LIGHTING);
	glEnable(GL_COLOR_MATERIAL);

	GLfloat posArray[4] = {(GLfloat)mPos.x, (GLfloat)mPos.y, (GLfloat)mPos.z, (GLfloat)mPos.w};
	GLfloat ambient[3] = {mAmbientFactor * color.r, mAmbientFactor * color.g, mAmbientFactor * color.b};
	GLfloat diffuse[3] = {0.0, 0.0, 0.0};
	GLfloat specular[3] = {0.0, 0.0, 0.0};

	if (!renderingShadows) {
		diffuse[0] = color.r;
		diffuse[1] = color.g;
		diffuse[2] = color.b;
		specular[0] = mSpecularFactor * color.r;
		specular[1] = mSpecularFactor * color.g;
		specular[2] = mSpecularFactor * color.b;
	}

	glEnable(mLightNo);
	glLightfv(mLightNo, GL_POSITION, posArray);
	glLightfv(mLightNo, GL_AMBIENT, ambient);
	glLightfv(mLightNo, GL_DIFFUSE, diffuse);
	glLightfv(mLightNo, GL_SPECULAR, specular);
	glLightfv(mLightNo, GL_CONSTANT_ATTENUATION, &mConstantAttenuation);
	glLightfv(mLightNo, GL_LINEAR_ATTENUATION, &mLinearAttenuation);
	glLightfv(mLightNo, GL_QUADRATIC_ATTENUATION, &mQuadraticAttenuation);
}

// Deactivate light source
void LightSource::deactivate() 
{
	glDisable(mLightNo);

	GLfloat black[4] = {0.0, 0.0, 0.0, 1.0};

	glLightfv(mLightNo, GL_AMBIENT, black);
	glLightfv(mLightNo, GL_DIFFUSE, black);
	glLightfv(mLightNo, GL_SPECULAR, black);
}
