/*
	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:   ParticleScene
// Purpose:      Class responsible for managing a scene full of particles. Creates
//               a pool of spare particles to save on creation / deletion overhead
//               and has several functions for creating particles. Also handles
//               all particle movement and drawing. One of the base classes of the
//               combined super class, GameScene. The particles themselves are
//               stored in a queue based on an array. This is about the fastest
//               data structure that could be used and is only made possible by
//               the fact that all particles have the exact same lifespan.
//
//
//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################

#include "ParticleScene.h"
#include <cstdio>

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

const unsigned ParticleScene::MAX_PARTICLES = 4096;    // maximum number of particles in a scene:

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

Name:     ParticleScene::ParticleScene()
Purpose:  ParticleScene constructor. Initialises the scene of particles.
Params:   none
Returns:  n/a

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

ParticleScene::ParticleScene()
{
    // Initialise particle count:

    numParticles = 0;

    // Create the particle queue

    particles = new Particle[MAX_PARTICLES];
}

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

Name:     ParticleScene::~ParticleScene()
Purpose:  ParticleScene destructor. Frees any memory used
Params:   n/a
Returns:  n/a

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

ParticleScene::~ParticleScene()
{
    // Delete the array queue of particles

    delete particles;
}

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

Name:     ParticleScene::createParticle()
Purpose:  Adds a particle into the scene if possible
Params:   As commented
Returns:  none

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

void ParticleScene::createParticle
(
    float x,        // particle position: x
    float y,        // particle position: y
    float z,        // particle position: z
    float r,        // particle color:  r
    float g,        // particle color:  g
    float b,        // particle color:  b
    float vel_x,    // particle movement speed: x
    float vel_y,    // particle movement speed: y
    float vel_z,    // particle movement speed: z
    float size,     // particle size
    float time      // particle live time
)
{
    // If no spare particles left then abort

    if ( numParticles >= MAX_PARTICLES ) return;

    // Get a pointer to the one past the last particle in the array:

    Particle * p = particles + numParticles;

    // Increment the number of particles in existance

    numParticles++;

    // Set the particles attributes

    p->pos_x    = x;
    p->pos_y    = y;
    p->pos_z    = z;

    p->col_r    = r;
    p->col_g    = g;
    p->col_b    = b;

    p->vel_x    = vel_x;
    p->vel_y    = vel_y;
    p->vel_z    = vel_z;

    p->size     = size;
    p->timeLeft = time;
    p->liveTime = time;
}

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

Name:     ParticleScene::createExplosion()
Purpose:  Creates an explosion of particles at a given point
Params:   as commented
Returns:  none

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

void ParticleScene::createExplosion
(
    float       x,      // position to make explostion at: x
    float       y,      // position to make explostion at: y
    float       z,      // position to make explostion at: z
    float       r1,     // 1st explosion color: r
    float       g1,     // 1st explosion color: r
    float       b1,     // 1st explosion color: r
    float       r2,     // 2nd explosion color: r
    float       g2,     // 2nd explosion color: r
    float       b2,     // 2nd explosion color: r
    float       size1,  // 1st explosion particle size
    float       size2,  // 2nd explosion particle size
    float       vel1,   // 1st explosion velocity
    float       vel2,   // 2nd explosion velocity
    float       time1,  // particle live time 1
    float       time2,  // particle live time 2
    unsigned    count   // number of particles to create in the explosion
)
{
    //--------------------------------------------------------------------------
    // Create the number of particles specified, randomnly choosing parameters
    //--------------------------------------------------------------------------

    for ( ; count ; count-- )
    {
        //----------------------------------------------------------------------
        // Store random floats here
        //----------------------------------------------------------------------

        float random;

        //----------------------------------------------------------------------
        // Decide on particle color
        //----------------------------------------------------------------------

        random = mlRandomFloat();

        float r = r1 * random + ( 1 - random ) * r2;
        float g = g1 * random + ( 1 - random ) * g2;
        float b = b1 * random + ( 1 - random ) * b2;

        //----------------------------------------------------------------------
        // Decide on particle size
        //----------------------------------------------------------------------

        random = mlRandomFloat();

        float size = size1 * random + ( 1 - random ) * size2;

        //----------------------------------------------------------------------
        // Decide on particle live time
        //----------------------------------------------------------------------

        random = mlRandomFloat();

        float time = time1 * random + ( 1 - random ) * time2;

        //----------------------------------------------------------------------
        // Decide on particle velocity and velocity direction
        //----------------------------------------------------------------------

        // Decide on direction

        float dir[3] =
        {
            mlRandomFloat() - 0.5f ,
            mlRandomFloat() - 0.5f ,
            mlRandomFloat() - 0.5f
        };

        // Normalise direction

        mlNormalise3d(dir);

        // Pick velocity magnitude

        random = mlRandomFloat();

        float vel = vel1 * random + ( 1 - random ) * vel2;

        // Scale direction by velocity magnitude

        dir[0] *= vel;
        dir[1] *= vel;
        dir[2] *= vel;

        //----------------------------------------------------------------------
        // Create the particle
        //----------------------------------------------------------------------

        createParticle
        (
            x,
            y,
            z,
            r,
            g,
            b,
            dir[0],
            dir[1],
            dir[2],
            size,
            time
        );
    }
}

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

Name:     ParticleScene::createStream()
Purpose:  Like createExplosion, but givens control over the direction the particles
          move in. use to create particles moving in a certain direction.
Params:   as commented
Returns:  none

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

void ParticleScene::createStream
(
    float       x,          // position to make explostion at: x
    float       y,          // position to make explostion at: y
    float       z,          // position to make explostion at: z
    float       r1,         // 1st explosion color: r
    float       g1,         // 1st explosion color: r
    float       b1,         // 1st explosion color: r
    float       r2,         // 2nd explosion color: r
    float       g2,         // 2nd explosion color: r
    float       b2,         // 2nd explosion color: r
    float       size1,      // 1st explosion particle size
    float       size2,      // 2nd explosion particle size
    float       vel1,       // 1st explosion velocity
    float       vel2,       // 2nd explosion velocity
    float       dir1_x,     // stream direction 1: x
    float       dir1_y,     // stream direction 1: y
    float       dir1_z,     // stream direction 1: z
    float       dir2_x,     // stream direction 2: x
    float       dir2_y,     // stream direction 2: y
    float       dir2_z,     // stream direction 2: z
    float       time1,      // particle live time 1
    float       time2,      // particle live time 2
    unsigned    count       // number of particles to create in the explosion
)
{
    //--------------------------------------------------------------------------
    // Create the number of particles specified, randomnly choosing parameters
    //--------------------------------------------------------------------------

    for ( ; count ; count-- )
    {
        //----------------------------------------------------------------------
        // Store random floats here
        //----------------------------------------------------------------------

        float random;

        //----------------------------------------------------------------------
        // Decide on particle color
        //----------------------------------------------------------------------

        random = mlRandomFloat();

        float r = r1 * random + ( 1 - random ) * r2;
        float g = g1 * random + ( 1 - random ) * g2;
        float b = b1 * random + ( 1 - random ) * b2;

        //----------------------------------------------------------------------
        // Decide on particle size
        //----------------------------------------------------------------------

        random = mlRandomFloat();

        float size = size1 * random + ( 1 - random ) * size2;

        //----------------------------------------------------------------------
        // Decide on particle live time
        //----------------------------------------------------------------------

        random = mlRandomFloat();

        float time = time1 * random + ( 1 - random ) * time2;

        //----------------------------------------------------------------------
        // Decide on particle velocity and velocity direction
        //----------------------------------------------------------------------

        // Decide on direction

        float dir[3];

        random = mlRandomFloat(); dir[0] = dir1_x * random + ( 1 - random ) * dir2_x;
        random = mlRandomFloat(); dir[1] = dir1_y * random + ( 1 - random ) * dir2_y;
        random = mlRandomFloat(); dir[2] = dir1_z * random + ( 1 - random ) * dir2_z;

        // Normalise direction

        mlNormalise3d(dir);

        // Pick velocity magnitude

        random = mlRandomFloat();

        float vel = vel1 * random + ( 1 - random ) * vel2;

        // Scale direction by velocity magnitude

        dir[0] *= vel;
        dir[1] *= vel;
        dir[2] *= vel;

        //----------------------------------------------------------------------
        // Create the particle
        //----------------------------------------------------------------------

        createParticle
        (
            x,
            y,
            z,
            r,
            g,
            b,
            dir[0],
            dir[1],
            dir[2],
            size,
            time
        );
    }
}

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

Name:     ParticleScene::moveParticles
Purpose:  Moves all of the particles in the ParticleScene, killing particles
          that are past their time to live.
Params:   time in seconds the last frame took
Returns:  none

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

void ParticleScene::moveParticles( float frameTime )
{
    //--------------------------------------------------------------------------
    // If the number of particles left is zero then quit
    //--------------------------------------------------------------------------

    if ( numParticles == 0 ) return;

    //--------------------------------------------------------------------------
    // Otherwise do a pass through the array, killing any dead particles:
    //--------------------------------------------------------------------------

    Particle * p = particles;

    for ( unsigned i = numParticles; i != 0 ; i-- )
    {
        // See if this particle is dead or not: dead if time to kill is zero or less

        if ( p->timeLeft <= 0 )
        {
            //------------------------------------------------------------------
            // Particle dead: swap the last particle in the array into this
            // particles position and decrement particle count.
            //------------------------------------------------------------------

            * p = particles[ numParticles - 1]; numParticles--;
        }

        // Move onto the next particle

        p++;
    }

    //--------------------------------------------------------------------------
    // Now do a pass through the array and move all active particles
    //--------------------------------------------------------------------------

    p = particles;

    for ( unsigned i = numParticles; i != 0 ; i-- )
    {
        // Move the current particle:

        p->pos_x += p->vel_x * frameTime;
        p->pos_y += p->vel_y * frameTime;
        p->pos_z += p->vel_z * frameTime;

        // Decrement its time to live:

        p->timeLeft -= frameTime;

        // Move onto the next particle

        p++;
    }
}

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

Name:     ParticleScene::drawParticles
Purpose:  Draws all the particles in the ParticleScene
Params:   camera scene is being viewed from
Returns:  none

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

void ParticleScene::drawParticles( Camera * camera )
{
    //--------------------------------------------------------------------------
    // Abort on null camera pointer
    //--------------------------------------------------------------------------

    if ( camera == 0 ) return;

    //--------------------------------------------------------------------------
    // If the number of particles left is zero then quit
    //--------------------------------------------------------------------------

    if ( numParticles == 0 ) return;

    //--------------------------------------------------------------------------
    // OpenGL setup
    //--------------------------------------------------------------------------

    // Enables / disables

    glEnable  ( GL_BLEND        );
    glDisable ( GL_LIGHTING     );
    glDisable ( GL_CULL_FACE    );

    // Set blending mode: additive blending

    glBlendFunc( GL_ONE , GL_ONE );

    // No depth writes

    glDepthMask ( GL_FALSE );

    // Bind the texture used for particles

    GLTextureManager::getTexParticle()->bind();

    //--------------------------------------------------------------------------
    // Get the camera's orientation matrix and its xy axis vectors
    //--------------------------------------------------------------------------

    float matrix[9]; camera->getOrientationMatrix(matrix);

    float xaxis[3] = { matrix[0] , matrix[3] , matrix[6] };
    float yaxis[3] = { matrix[1] , matrix[4] , matrix[7] };

    //--------------------------------------------------------------------------
    // Begin drawing quads
    //--------------------------------------------------------------------------

    glBegin( GL_QUADS );

    //--------------------------------------------------------------------------
    // Get pointer to first particle in the array
    //--------------------------------------------------------------------------

    Particle * p = particles;

    //--------------------------------------------------------------------------
    // Draw all particles in the array:
    //--------------------------------------------------------------------------

    for ( unsigned i = numParticles ; i != 0 ; i-- )
    {
        // Specify particle color: fade out with time

        float fadeFactor = p->timeLeft / p->liveTime;

        glColor3f
        (
            p->col_r * fadeFactor,
            p->col_g * fadeFactor,
            p->col_b * fadeFactor
        );

        // Specify particle vertex and texture coordinates and align it to face the view

        glTexCoord2f(0,0);

        glVertex3f
        (
            p->pos_x - p->size * xaxis[0] + p->size * yaxis[0],
            p->pos_y - p->size * xaxis[1] + p->size * yaxis[1],
            p->pos_z - p->size * xaxis[2] + p->size * yaxis[2]
        );

        glTexCoord2f(1,0);

        glVertex3f
        (
            p->pos_x + p->size * xaxis[0] + p->size * yaxis[0],
            p->pos_y + p->size * xaxis[1] + p->size * yaxis[1],
            p->pos_z + p->size * xaxis[2] + p->size * yaxis[2]
        );

        glTexCoord2f(1,1);

        glVertex3f
        (
            p->pos_x + p->size * xaxis[0] - p->size * yaxis[0],
            p->pos_y + p->size * xaxis[1] - p->size * yaxis[1],
            p->pos_z + p->size * xaxis[2] - p->size * yaxis[2]
        );

        glTexCoord2f(0,1);

        glVertex3f
        (
            p->pos_x - p->size * xaxis[0] - p->size * yaxis[0],
            p->pos_y - p->size * xaxis[1] - p->size * yaxis[1],
            p->pos_z - p->size * xaxis[2] - p->size * yaxis[2]
        );

        // Move onto the next particle in the array

        p++;
    }

    //--------------------------------------------------------------------------
    // End drawing quads
    //--------------------------------------------------------------------------

    glEnd();
}
