/*
	Rogue Trader.
	Copyright (c) 2007, Darragh Coy.
	All rights reserved.
	Original work(s), source code & author(s) details available at: http://www.darraghcoy.com

	Redistribution and use in source and binary forms, with or without modification, are permitted 
	provided that the following conditions are met:

		* 	Redistributions of source code must retain the above copyright notice, this list of 
			conditions and the following disclaimer.
		* 	Redistributions in binary form must reproduce the above copyright notice, this list of 
			conditions and the following disclaimer in the documentation.
		* 	Neither the name of the author nor the names of contributors may be used to endorse or 
			promote products derived from this software without specific prior written permission.
		* 	The use of any third party libraries, modules or data files provided with the source 
			form of the program must follow and respect the individual licensing terms of these 
			components. You do not have permission to modify or circumvent the licensing terms for 
			provided third party components unless the third party licenses specifically allow this. 
			If you do not agree to the terms of provided third party components then you do not have 
			permission to use them in your derived work(s).
		* 	The terms of this license do not apply to separate (but related) distributions if supplied 
			by the author(s), only to the contents of this source distribution, derived works, and the 
			binaries produced by either modified or unmodified versions of the source code. The terms 
			of this license do not also apply to any third party libraries or components provided with 
			the source distribution. Such third party elements are licensed under their own separate 
			agreements.

	THIS SOFTWARE IS PROVIDED BY DARRAGH COY ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL DARRAGH COY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
	OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
	OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################
//
//
// Class Name:   LightScene
// Purpose:      Class responsible for managing a scene of lights. Holds onto
//               the lights when not needed and deletes them upon removal. Also
//               handles opengl lighting setup. Serves as one of the base classes
//               for the GameScene super class.
//
//
//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################

#include "LightScene.h"

//------------------------------------------------------------------------------
// Constant initialisation
//------------------------------------------------------------------------------

const float LightScene::AMBIENT_R = 0.2f;    // Default ambient light color for the scene: r
const float LightScene::AMBIENT_G = 0.2f;    // Default ambient light color for the scene: g
const float LightScene::AMBIENT_B = 0.2f;    // Default ambient light color for the scene: b
const float LightScene::SHINYNESS = 0.0f;    // Specualar exponent value for objects being illuminated

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     LightScene::LightScene()
Purpose:  LightScene constructor. Queries opengl for the maximum allowed lights
          and sets up an empty array of pointers to light objects.
Params:   none
Returns:  n/a

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

LightScene::LightScene()
{
	// Assume only 1 light supported initially:
	
	this->maxLights = 1;

    // Get the maximum number of lights allowable from opengl

    glGetIntegerv( GL_MAX_LIGHTS , (GLint*)(& this->maxLights ) );
    
    // If bigger than a certain amount then clamp:
    
    if ( this->maxLights > 8 ) this->maxLights = 8;
    if ( this->maxLights < 1 ) this->maxLights = 1;

    // Allocate memory for an array of pointers to lights

    lights = new Light * [maxLights];
    
    // Clear the array:
    
    for ( unsigned i = 0 ; i < maxLights ; ++i ) lights[i] = 0;

    // Set the number of lights in the scene to 0 initially

    numLights = 0;
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     LightScene::~LightScene()
Purpose:  LightScene destructor. Deletes all lights in the light scene
Params:   n/a
Returns:  n/a

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

LightScene::~LightScene()
{
    // Delete all the lights in the light scene

    for ( unsigned i = 0 ; i < numLights ; i++ ) delete lights[i];

    // Delete the array of pointers to lights

    delete[] lights;
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     LightScene::addLight()
Purpose:  Trys to add a light into the scene. Deletes it on failure.
Params:   light to add.
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void LightScene::addLight( Light * light )
{
    //--------------------------------------------------------------------------
    // Check for null pointer
    //--------------------------------------------------------------------------

    if ( light == 0 ) return;

    //--------------------------------------------------------------------------
    // If light is already in a LightScene then abort
    //--------------------------------------------------------------------------

    if ( light->scene != 0 ) return;

    //--------------------------------------------------------------------------
    // See if there is room for another light:
    //--------------------------------------------------------------------------

    if ( numLights < maxLights )
    {
        //----------------------------------------------------------------------
        // Room for light in the scene
        //----------------------------------------------------------------------

        // add light into scene

        lights[numLights] = light;

        // Set the LightScene the light belongs to

        light->scene = this;

        // increment the number of lights

        numLights++;
    }
    else
    {
        //----------------------------------------------------------------------
        // No room for the light. Delete.
        //----------------------------------------------------------------------

        delete light;
    }
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     LightScene::delLight()
Purpose:  Trys to remove a light from the scene.
Params:   light to remove.
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void LightScene::delLight( Light * light )
{
    //--------------------------------------------------------------------------
    // Check for null pointer
    //--------------------------------------------------------------------------

    if ( light == 0 ) return;

    //--------------------------------------------------------------------------
    // Search for the light in the light array.
    //--------------------------------------------------------------------------

    int index = -1;

    for ( unsigned i = 0 ; i < numLights; i++ )
    {
        // see if the light in the array matches the light given:

        if ( lights[i] == light ){ index = i; break; }
    }

    //--------------------------------------------------------------------------
    // If the light was found then delete and swap the last light in the array
    // into this lights position.
    //--------------------------------------------------------------------------

    if ( index > -1 )
    {
        // Do the swap

        lights[index] = lights[ numLights - 1 ];

        // Delete the given light

        delete light;

        // Decrement the number of lights

        numLights--;
    }
}

/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Name:     LightScene::setupLighting()
Purpose:  Sets up the lighting for the scene.
Params:   Camera the scene is being viewed from. affects lighting...
Returns:  none

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/

void LightScene::setupLighting( Camera * camera )
{
    //--------------------------------------------------------------------------
    // Abort on null camera pointer
    //--------------------------------------------------------------------------

    if ( camera == 0 ) return;

    //--------------------------------------------------------------------------
    // Enable lighting firstly
    //--------------------------------------------------------------------------

    glEnable(GL_LIGHTING);

    //--------------------------------------------------------------------------
    // Make sure we are viewing from the camera given: this affects lighting
    //--------------------------------------------------------------------------

    camera->viewFrom();

    //--------------------------------------------------------------------------
    // The colors black and white
    //--------------------------------------------------------------------------

    float black[4] = { 0 , 0 , 0 , 1 };
    float white[4] = { 1 , 1 , 1 , 1 };

    //--------------------------------------------------------------------------
    // Setup material properties for all objects in the scene
    //--------------------------------------------------------------------------

    glMaterialfv( GL_FRONT_AND_BACK , GL_AMBIENT    , white     );
    glMaterialfv( GL_FRONT_AND_BACK , GL_DIFFUSE    , white     );
    glMaterialfv( GL_FRONT_AND_BACK , GL_EMISSION   , black     );
    glMaterialfv( GL_FRONT_AND_BACK , GL_SPECULAR   , black     );
    glMaterialf ( GL_FRONT_AND_BACK , GL_SHININESS  , SHINYNESS );

    //--------------------------------------------------------------------------
    // Put the ambient light color into an RGBA array
    //--------------------------------------------------------------------------

    float ambientLightColor[4];

    ambientLightColor[0] = AMBIENT_R;
    ambientLightColor[1] = AMBIENT_G;
    ambientLightColor[2] = AMBIENT_B;
    ambientLightColor[3] = 1;

    //--------------------------------------------------------------------------
    // Set the ambient light color
    //--------------------------------------------------------------------------

    glLightModelfv( GL_LIGHT_MODEL_AMBIENT  , ambientLightColor );

    //--------------------------------------------------------------------------
    // Enable per vertex specular direction calculations
    //--------------------------------------------------------------------------

    glLightModeli ( GL_LIGHT_MODEL_LOCAL_VIEWER , GL_TRUE );

    //--------------------------------------------------------------------------
    // Enable two sided lighting:
    //--------------------------------------------------------------------------

    glLightModeli ( GL_LIGHT_MODEL_TWO_SIDE , GL_TRUE );

    //--------------------------------------------------------------------------
    // Enable whatever lights are in the scene and set the lighting properties
    //--------------------------------------------------------------------------

    for ( unsigned i = 0 ; i < numLights ; i++ )
    {
        //----------------------------------------------------------------------
        // Enable this light
        //----------------------------------------------------------------------

        glEnable( GL_LIGHT0 + i );

        //----------------------------------------------------------------------
        // Set the light properties
        //----------------------------------------------------------------------

        glLightfv( GL_LIGHT0 + i , GL_POSITION , lights[i]->pos );      // set light position
        glLightfv( GL_LIGHT0 + i , GL_DIFFUSE  , lights[i]->col );      // set light diffuse  color
        glLightfv( GL_LIGHT0 + i , GL_SPECULAR , lights[i]->col );      // set light specular color
        glLightfv( GL_LIGHT0 + i , GL_EMISSION , lights[i]->col );      // set light emission color
        glLightfv( GL_LIGHT0 + i , GL_AMBIENT  , black          );      // set light ambient color: no ambient
        glLightf ( GL_LIGHT0 + i , GL_SPOT_CUTOFF , 180         );      // no spot lighting. full 180 degree apex on light cone.
        glLightf ( GL_LIGHT0 + i , GL_CONSTANT_ATTENUATION  , 1 );      // constant attentuation factor
        glLightf ( GL_LIGHT0 + i , GL_QUADRATIC_ATTENUATION , 0 );      // quadratic attentuation factor: no quadratic attenuation

        //----------------------------------------------------------------------
        // Finally set the linear attenuation factor to 1.0 / light strenght
        //----------------------------------------------------------------------

        glLightf( GL_LIGHT0 + i , GL_LINEAR_ATTENUATION , 1.0f / lights[i]->strenght );
    }

    //--------------------------------------------------------------------------
    // Disable all the other available opengl lights that are not being used
    //--------------------------------------------------------------------------

    for ( unsigned i = numLights ; i < maxLights ; i++ ) glDisable( GL_LIGHT0 + i );
}
