/*
	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:   GameObject_Ship
// Purpose:      Class that describes the spacestation. Tracks the players ship
//               and initiates the spacestation menu if the player gets close
//               enough to the spacestation entrance.
//
//
//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################

#include "GameObject_SpaceStation.h"

//------------------------------------------------------------------------------
// Each of the four particle sets: coordinates are described in object space
//------------------------------------------------------------------------------

// Particle set 1: xyz coordinates for each particle:

    const float PARTICLE_SET_1[] =
    {
        -250,     +650,     +200,
        +250,     +650,     +200,
        -250,     -650,     +200,
        +250,     -650,     +200,

        -250,     +650,     -200,
        +250,     +650,     -200,
        -250,     -650,     -200,
        +250,     -650,     -200
    };

// Particle set 2: xyz coordinates for each particle:

    const float PARTICLE_SET_2[] =
    {
        -650,     +650,     +150,
        +650,     +650,     +150,
        -650,     -650,     +150,
        +650,     -650,     +150,

        -650,     +650,     -150,
        +650,     +650,     -150,
        -650,     -650,     -150,
        +650,     -650,     -150
    };

// Particle set 3: xyz coordinates for each particle:

    const float PARTICLE_SET_3[] =
    {
        -950,     +650,     +150,
        +950,     +650,     +150,
        -950,     -650,     +150,
        +950,     -650,     +150,

        -950,     +650,     -150,
        +950,     +650,     -150,
        -950,     -650,     -150,
        +950,     -650,     -150
    };

// Particle set 4: xyz coordinates for each particle:

    const float PARTICLE_SET_4[] =
    {
        -1300,     +650,    +200,
        +1300,     +650,    +200,
        -1300,     -650,    +200,
        +1300,     -650,    +200,

        -1300,     +650,    -200,
        +1300,     +650,    -200,
        -1300,     -650,    -200,
        +1300,     -650,    -200
    };

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

const float GameObject_SpaceStation::DOCK_SPHERE_X              = 0;        // bounding sphere which player must enter to initiate docking, position x in objects coordinate system
const float GameObject_SpaceStation::DOCK_SPHERE_Y              = 0;        // bounding sphere which player must enter to initiate docking, position y in objects coordinate system
const float GameObject_SpaceStation::DOCK_SPHERE_Z              = 200;      // bounding sphere which player must enter to initiate docking, position z in objects coordinate system
const float GameObject_SpaceStation::DOCK_SPHERE_RADIUS         = 100;      // bounding sphere which player must enter to initiate docking, radius
const float GameObject_SpaceStation::DOCK_FADE_TIME             = 0.5f;     // Time the screen fade when docking takes in seconds
const float GameObject_SpaceStation::ROTATE_SPEED               = 0.05f;    // speed at which the spacestation rotates about the z axis
const float GameObject_SpaceStation::PARTICLE_INTERVAL          = 0.6f;     // time in betweeen when spacestation creates particles
const float GameObject_SpaceStation::PARTICLE_TIME              = 0.4f;     // time the particles created live for
const float GameObject_SpaceStation::PARTICLE_SIZE              = 64.0f;    // size of the particles created
const float GameObject_SpaceStation::PARTICLE_R                 = 1.0f;     // color of space station particles: red
const float GameObject_SpaceStation::PARTICLE_G                 = 0.0f;     // color of space station particles: green
const float GameObject_SpaceStation::PARTICLE_B                 = 0.0f;     // color of space station particles: blue
const float GameObject_SpaceStation::PARTICLE_NOISE_DISTANCE    = 32000;    // distance from which the particle noise can be heard

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

Name:     GameObject_SpaceStation::GameObject_SpaceStation()
Purpose:  SpaceStation constructor
Params:   as per commented
Returns:  n/a

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

GameObject_SpaceStation::GameObject_SpaceStation
(
    float  pos_x,   // initial position: x
    float  pos_y,   // initial position: y
    float  pos_z,   // initial position: z
    Game * game     // Game the spacestation belongs to
)
:
StaticGameObject( pos_x , pos_y , pos_z , MeshManager::getMeshSpacestation() )
{
    // Save a pointer to the game:

    this->game = game;

    // Set the current set of particles to spawn as zero

    this->spawnParticleSet = 0;

    // Set the time to the next lot of particles to zero

    this->timeToParticles = 0;

    // Set the name of the object:

    name = "Spacestation";
}

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

Name:     GameObject_SpaceStation::onDraw()
Purpose:  On draw event for the spacestation. Draws 'fog' in the spacestation
          entrance.
Params:   Camera the scene is viewed from.
Returns:  none

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

// No unreferenced param warning

#pragma warning(disable:4100)   

void GameObject_SpaceStation::onDraw( Camera * camera )
{
    //--------------------------------------------------------------------------
    // Get the current openGL transformation matrix
    //--------------------------------------------------------------------------

    float matrix[16]; glGetFloatv( GL_MODELVIEW_MATRIX , matrix );

    //--------------------------------------------------------------------------
    // Setup the opengl state:
    //--------------------------------------------------------------------------

    // Save the enables state first:

    glPushAttrib( GL_ENABLE_BIT );

    // Enables

    glEnable( GL_BLEND );

    // Disables

    glDisable( GL_TEXTURE_2D );
    glDisable( GL_LIGHTING   );
    glDisable( GL_CULL_FACE  );

    // Set blending mode:

    glBlendFunc( GL_ZERO , GL_SRC_COLOR );
    glShadeModel(GL_SMOOTH);

    //--------------------------------------------------------------------------
    // Save the current OpenGL transform matrix
    //--------------------------------------------------------------------------

    glPushMatrix();

    //--------------------------------------------------------------------------
    // Makeup two 4x4 matrices to translate by both objects position and orientation
    //--------------------------------------------------------------------------

    // Declare the matrices:

    float rotation    [16];
    float translation [16];

    // Get objects position

    float position[3]; getPosition( position );

    // Get objects orientation matrix:

    float orientation[9]; getOrientationMatrix( orientation );

    // Make up the rotation matrix:

    rotation[0 ] = orientation[0];
    rotation[1 ] = orientation[1];
    rotation[2 ] = orientation[2];
    rotation[3 ] = 0;

    rotation[4 ] = orientation[3];
    rotation[5 ] = orientation[4];
    rotation[6 ] = orientation[5];
    rotation[7 ] = 0;

    rotation[8 ] = orientation[6];
    rotation[9 ] = orientation[7];
    rotation[10] = orientation[8];
    rotation[11] = 0;

    rotation[12] = 0;
    rotation[13] = 0;
    rotation[14] = 0;
    rotation[15] = 1;

    translation[0 ] = 1;
    translation[1 ] = 0;
    translation[2 ] = 0;
    translation[3 ] = 0;

    translation[4 ] = 0;
    translation[5 ] = 1;
    translation[6 ] = 0;
    translation[7 ] = 0;

    translation[8 ] = 0;
    translation[9 ] = 0;
    translation[10] = 1;
    translation[11] = 0;

    translation[12] = position[0];
    translation[13] = position[1];
    translation[14] = position[2];
    translation[15] = 1;

    //--------------------------------------------------------------------------
    // Combine the rotation and translation transforms, doing rotation first.
    // Save to translation matrix.
    //--------------------------------------------------------------------------

    mlMatrixMult4x4( rotation , translation );

    //--------------------------------------------------------------------------
    // Now combine the object transforms with the world transforms, or the
    // previously gotten transfrom matrix
    //--------------------------------------------------------------------------

    mlMatrixMult4x4( translation , matrix );

    //--------------------------------------------------------------------------
    // Load the modified matrix with openGL
    //--------------------------------------------------------------------------

    glLoadMatrixf( matrix );

    //--------------------------------------------------------------------------
    // Draw the fog:
    //--------------------------------------------------------------------------

    glBegin( GL_QUADS );

        // 1st fog quad:

        glColor3f(0.0f,0.0f,0.0f);       glVertex3f( -100 , - 100 , -150 );
        glColor3f(0.0f,0.0f,0.0f);       glVertex3f( -100 , + 100 , -150 );
        glColor3f(0.0f,0.0f,0.0f);       glVertex3f( +100 , + 100 , -150 );
        glColor3f(0.0f,0.0f,0.0f);       glVertex3f( +100 , - 100 , -150 );

        // 1st fog quad:

        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( -100 , - 100 , -100 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( -100 , + 100 , -100 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( +100 , + 100 , -100 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( +100 , - 100 , -100 );

        // 1st fog quad:

        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( -100 , - 100 , 0 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( -100 , + 100 , 0 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( +100 , + 100 , 0 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( +100 , - 100 , 0 );

        // 2nd fog quad:

        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( -100 , - 100 , 100 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( -100 , + 100 , 100 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( +100 , + 100 , 100 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( +100 , - 100 , 100 );

        // 3rd fog quad:

        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( -100 , - 100 , 200 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( -100 , + 100 , 200 );
        glColor3f(0.4f,0.4f,0.4f);      glVertex3f( +100 , + 100 , 200 );
        glColor3f(0.4f,0.4f,0.4f);		glVertex3f( +100 , - 100 , 200 );

    glEnd();

    //--------------------------------------------------------------------------
    // Restore the previous OpenGL transform matrix
    //--------------------------------------------------------------------------

    glPopMatrix();

    //--------------------------------------------------------------------------
    // Restore enables state:
    //--------------------------------------------------------------------------

    glPopAttrib();
}

// Restore this to normal

#pragma warning(default:4100)

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

Name:     GameObject_SpaceStation::onFrame()
Purpose:  On frame event for the spacestation. Spawns little particles representing
          lights along the spacestations arms every so often. Also rotates the
          spacestation slightly.
Params:   time the last frame took in seconds
Returns:  none

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

void GameObject_SpaceStation::onFrame( float frameTime )
{
    //--------------------------------------------------------------------------
    // Rotate the spacestation:
    //--------------------------------------------------------------------------

    rotateZ( ROTATE_SPEED * frameTime );

    //--------------------------------------------------------------------------
    // Spawn particles along the arms of the ship at regular intervals:
    //--------------------------------------------------------------------------

    spawnParticles(frameTime);

    //--------------------------------------------------------------------------
    // Check if the player is in positio to dock with the spacestation
    //--------------------------------------------------------------------------

    dockingCheck();
}

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

Name:     GameObject_SpaceStation::dockingCheck
Purpose:  Checks if the player has entered the bounding sphere that intiates docking.
Params:   none
Returns:  none

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

void GameObject_SpaceStation::dockingCheck()
{
    //--------------------------------------------------------------------------
    // Get the players position if possible:
    //--------------------------------------------------------------------------

    // Get the player from the game:

    const Player * player = game->getPlayer();

    // Get a hook to the players ship

    const GameObjectHook * hookShip = player->getShipHook();

    // Try and get the players ship from the hook:

    GameObject_Ship * ship =(GameObject_Ship*) hookShip->getObject();

    // If the object is null then players ship no longer exists: abort

    if ( ship == 0 ) return;

    // Otherwise get the position of the ship

    float shipPosition[3]; ship->getPosition(shipPosition);

    //--------------------------------------------------------------------------
    // Transform the docking sphere position from object to world coordinates:
    //--------------------------------------------------------------------------

    // Get position and orientation of the spacestation:

    float position[3];      getPosition(position);
    float orientation[9];   getOrientationMatrix(orientation);

    // Get the position of the docking bounding sphere:

    float dockSpherePosition[3] =
    {
        DOCK_SPHERE_X,
        DOCK_SPHERE_Y,
        DOCK_SPHERE_Z
    };

    // First rotate it by the objects orientation:

    mlTransform3d( dockSpherePosition , orientation );

    // Now translate it by the objects position:

    dockSpherePosition[0] += position[0];
    dockSpherePosition[1] += position[1];
    dockSpherePosition[2] += position[2];

    //--------------------------------------------------------------------------
    // Now see if the players position is within this bounding sphere:
    //--------------------------------------------------------------------------

    if ( mlPointInSphere3d( shipPosition , dockSpherePosition , DOCK_SPHERE_RADIUS ) )
    {
        // Player is inside the docking sphere: initiate docking procedure

        dock();

        // Refuel the players ship after the dock:

        ship->refuel();
    }
}

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

Name:     GameObject_SpaceStation::dock()
Purpose:  Begins the docking procedure. Fading out the screen and pulling up
          the spacestation menu.
Params:   none
Returns:  none

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

void GameObject_SpaceStation::dock()
{
    //--------------------------------------------------------------------------
    // Kill all enemies in the game: pirates go away after docking
    //--------------------------------------------------------------------------

    game->killEnemies();

    //--------------------------------------------------------------------------
    // Play the docking sound:
    //--------------------------------------------------------------------------

    SoundSystem::playSound( SoundManager::getSndDock() );

    //--------------------------------------------------------------------------
    // Fade out the screen by fade time:
    //--------------------------------------------------------------------------

    GLWindow::fadeScreen(DOCK_FADE_TIME);

    //--------------------------------------------------------------------------
    // Pause the game:
    //--------------------------------------------------------------------------

    game->pause();

    //--------------------------------------------------------------------------
    // Make a new spacestation gui screen and run it:
    //--------------------------------------------------------------------------

    GuiScreen_SpaceStation * gui = new GuiScreen_SpaceStation(game); gui->run();

    //--------------------------------------------------------------------------
    // Delete the spacestation gui when done
    //--------------------------------------------------------------------------

    delete gui;

    //--------------------------------------------------------------------------
    // Play the launch sound:
    //--------------------------------------------------------------------------

    SoundSystem::playSound( SoundManager::getSndLaunch() );

    //--------------------------------------------------------------------------
    // Unpause the game
    //--------------------------------------------------------------------------

    game->unpause();

    //--------------------------------------------------------------------------
    // Tell the game to set the players position to where it should be after docking:
    //--------------------------------------------------------------------------

    game->setPlayerPosition_dockStart();
}

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

Name:     GameObject_SpaceStation::spwanParticles()
Purpose:  Spawns particles along the arms of the ship at regular intervals
Params:   time the last frame took in seconds
Returns:  none

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

void GameObject_SpaceStation::spawnParticles( float frameTime )
{
    //--------------------------------------------------------------------------
    // See if the time to the next lot of particles is zero or less:
    //--------------------------------------------------------------------------

    if ( timeToParticles <= 0 )
    {
        //----------------------------------------------------------------------
        // Time to create particles. Reset time to the next lot of particles
        //----------------------------------------------------------------------

        timeToParticles = PARTICLE_INTERVAL;

        //----------------------------------------------------------------------
        // Get a pointer to the spacestations game object scene:
        //----------------------------------------------------------------------

        // Assume this is in actual fact a gamescene object!

        GameScene * scene = (GameScene *) this->getScene();

        //----------------------------------------------------------------------
        // Spawn a one shot noise for the space station particles
        //----------------------------------------------------------------------

        scene->addSound
        (
            SoundManager::getSndStationLights(),        // sound to play
            getPosX(),                                  // position of sound
            getPosY(),                                  // position of sound
            getPosZ(),                                  // position of sound
            PARTICLE_NOISE_DISTANCE,                    // distance noise can be heard from
            1,                                          // frequency of the sound
            false                                       // looping ?
        );

        //----------------------------------------------------------------------
        // Get the objects orientation matrix and position: these will be used
        // to transform particles from object to world coordinates:
        //----------------------------------------------------------------------

        // Get position of the spacestation:

        float position[3];      getPosition(position);
        float orientation[9];   getOrientationMatrix(orientation);

        //----------------------------------------------------------------------
        // Get the amount of particles in the current particle set and pointer
        // to the array of particle coordinates for that set:
        //----------------------------------------------------------------------

        // Pointer to particle set coordinates to draw:

        const float * particleSet;

        // Number of particles in that set:

        unsigned numParticles;

        // See what particle set is going to be spawned:

        switch ( spawnParticleSet )
        {
            case 0:     particleSet = PARTICLE_SET_1; numParticles = sizeof(PARTICLE_SET_1) / 12; break;
            case 1:     particleSet = PARTICLE_SET_2; numParticles = sizeof(PARTICLE_SET_2) / 12; break;
            case 2:     particleSet = PARTICLE_SET_3; numParticles = sizeof(PARTICLE_SET_3) / 12; break;
            case 3:     particleSet = PARTICLE_SET_4; numParticles = sizeof(PARTICLE_SET_4) / 12; break;
            default:    particleSet = PARTICLE_SET_1; numParticles = sizeof(PARTICLE_SET_1) / 12; break;
        }

        //----------------------------------------------------------------------
        // Draw the particles in the current set:
        //----------------------------------------------------------------------

        for ( unsigned i = numParticles ; i ; i-- )
        {
            // Get the coordinates of the particle:

            float particle[3] =
            {
                particleSet[0],
                particleSet[1],
                particleSet[2]
            };

            // Move onto the next point in the particle set:

            particleSet += 3;

            // Part 1 of transform to world coordinates: transform by object orientation

            mlTransform3d(particle,orientation);

            // Part 2 of transform to world coordinates: transform by object translation

            particle[0] += position[0];
            particle[1] += position[1];
            particle[2] += position[2];

            // Create the particle

            scene->createParticle
            (
                particle[0],
                particle[1],
                particle[2],
                PARTICLE_R,
                PARTICLE_G,
                PARTICLE_B,
                0,
                0,
                0,
                PARTICLE_SIZE,
                PARTICLE_TIME
            );

        }

        //----------------------------------------------------------------------
        // Move onto the next particle set for the next particle creation:
        //----------------------------------------------------------------------

        // Move onto the next set

        spawnParticleSet++;

        // Wrap around set to between 0-3:

        spawnParticleSet &= 3;
    }
    else
    {
        //----------------------------------------------------------------------
        // Not time yet for particles: decerease time to next lot of particles
        //----------------------------------------------------------------------

        timeToParticles -= frameTime;
    }
}
