/*
	Wheels Of Steel
	Copyright (c) 2006, 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:   Obj_Car
// Purpose:      Class for all cars in the game.
//
//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################

#include "Obj_Car.h"
#include "PI.h"

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Constants
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// normal speed at which the car accelerates: may be reduced for ai cars by whatever handicaps the user has picked

const float Obj_Car::CAR_ACCELERATION =  17000.0f;

// speed at which the car brakes

const float Obj_Car::CAR_DEACCELERATION = -6000.0f;

// Car dimensions

const float Obj_Car::CAR_SIZE_X = 600.0f;    // size of car: x
const float Obj_Car::CAR_SIZE_Y = 400.0f;    // size of car: y
const float Obj_Car::CAR_SIZE_Z = 256.0f;    // size of car: z

// Other

const float Obj_Car::CAR_TORQUE                   =  1.35f;    // times the velocity the amount the car can turn
const float Obj_Car::CAR_WEIGHT                   =  60.0f;    // the weight of each car
const float Obj_Car::CAR_IMAGE_CHANGE_DEGREES     =  4.0f;     // Number of degrees turning that causes the car image to change
const float Obj_Car::CAR_SCORE_TO_SNOW_PUFF       =  500.0f;   // The 'score' required to make a snow puff: see

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Name:     Obj_Car::Obj_Car
Purpose:  Constructor for the car
Params:   As commented
Returns:  none

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


Obj_Car::Obj_Car
(
    const Mipmap ** mipArrayCar,    // Array of 7 car images for various orientations of the car. The 'skin' of the car.
    float pos_x,                    // position: x
    float pos_y,                    // position: y
    float pos_z,                    // position: z
    float acceleration              // ultimately affects the max speed of the car

) : GameObject(pos_x,pos_y,pos_z,true)
{
    // Save the array pointer of mipmaps for all the orientaions of the car

    this->mipArrayCar = mipArrayCar;

    // Set the acceleration amount of the car

    this->acceleration = acceleration;

    // Set object size

    this->size_x = CAR_SIZE_X;
    this->size_y = CAR_SIZE_Y;
    this->size_z = CAR_SIZE_Z;

    // Set object attributes

    this->solid             = true;
    this->gravityAffected   = true;
    this->weight            = CAR_WEIGHT;

    // Set the snowPuff score to 0. See header for explanation of this variable

    this->snowPuffScore = 0;
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Name:     Obj_Car::~Obj_Car
Purpose:  Destructor. Does nothing.
Params:   none
Returns:  none

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

Obj_Car::~Obj_Car()
{
    // DO NOTHING
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Name:     Obj_Car::event_collision
Purpose:  Collision event for the car. Does nothing.
Params:   Object that collided with this object.
Returns:  none

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

// No unreferenced param warning

#pragma warning(disable:4100)

void Obj_Car::event_collision( GameObject * collider)
{
    // DO NOTHING
}

// Restore this warning to normal

#pragma warning(default:4100)

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Name:     Obj_Car::event_move
Purpose:  Move event for the car. Adds to the snow puff score if the object is
          in the rough. If you are scratching your head and wondering what the
          hell the snow puff score is, see the header file for an explanation...
Params:   Track and time last frame took in seconds
Returns:  none

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

void Obj_Car::event_move( Track * track , float frameTime )
{
    //--------------------------------------------------------------------------
    // See if the car is touching the ground or (just about) touching it..
    //--------------------------------------------------------------------------

    if ( this->getPos_y() - size_y * 0.5 <= track->getY( this->getPos_z() ) + 0.5f )
    {
        //----------------------------------------------------------------------
        // Touching the ground: see if the car is off the track
        //----------------------------------------------------------------------

        if (
                this->getPos_x() <= track->getLX( this->getPos_z() )    // see if off the track to the left of the road
                ||
                this->getPos_x() >= track->getRX( this->getPos_z() )    // see if off the track to the right of the road
            )
        {
            //------------------------------------------------------------------
            // Car is off the road. Add to the snow puff score by the z velocity
            // times the frame time
            //------------------------------------------------------------------

            snowPuffScore += fabs( this->vel_z * frameTime );

            // If the snow puff score is sufficient to make a snow puff then make one
            // and add it into the game. make around the cars position..

            if ( snowPuffScore >= CAR_SCORE_TO_SNOW_PUFF )
            {
                // Can make a snow puff: make one and add it to the game

                GameObjectManager::addObject
                (
                    new Obj_SnowPuff
                    (
                        this->getPos_x(),
                        this->getPos_y(),
                        this->getPos_z()
                    )
                );

                // Reset the snow puff score to zero

                snowPuffScore = 0;
            }

        }   // end if off the road

    }   // end if touching the ground
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Name:     Obj_Car::accelerate
Purpose:  Accelerate the car
Params:   none
Returns:  none

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

void Obj_Car::accelerate()
{
    acl_z = acceleration;
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Name:     Obj_Car::brake
Purpose:  Brake the car
Params:   none
Returns:  none

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

void Obj_Car::brake()
{
    // Reverse the car: but only if it is not past the starting line of the track:

    if ( this->getPos_z() >= Game::CAR_STARTING_Z )
    {
        // Not past the start line. reverse.

        acl_z = CAR_DEACCELERATION;
    }
    else
    {
        // Past the start line: stop the car

        setVel_z(0);
    }
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Name:     Obj_Car::turnLeft
Purpose:  Turn the car left
Params:   none
Returns:  none

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

void Obj_Car::turnLeft()
{
    // Decrease the x velocity by the forward velocity times the torque

    acl_x = -vel_z * CAR_TORQUE;
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Name:     Obj_Car::turnRight
Purpose:  Turn the car right
Params:   none
Returns:  none

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

void Obj_Car::turnRight()
{
    // Increase the x velocity by the forward velocity times the torque

    acl_x = vel_z * CAR_TORQUE;
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Name:     Obj_Car::event_draw
Purpose:  Draw event for the car. Draws the appropriate car image depending on orientation.
Params:   Window and camera position
Returns:  none

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

void Obj_Car::event_draw( Window & window, Camera * camera)
{
    //--------------------------------------------------------------------------
    // Decide on which image to draw depending which angle the car is moving at
    //--------------------------------------------------------------------------

    // Get the amount the car is moving in the z and x directions

    float move_x = vel_x;
    float move_z = vel_z;

    // Store the angle of movement (in degrees here). default is forward: 90 degrees

    float moveAngle = 90;

    // Only figure out move angle if not moving straight vertically

    if ( move_x != 0 )
    {
        // Get the lenght of the movement vector in two dimensions

        float move_lenght;

        move_lenght  = move_x * move_x;
        move_lenght += move_z * move_z;
        move_lenght  = sqrt(move_lenght);

        // Normalise the movement vector

        move_x /= move_lenght;
        move_z /= move_lenght;

        // Get the inverse cosine and convert to degrees.
        
        moveAngle = acos(move_x) * ( 180.0f / M_PI );

        // Map all negative angles back into a 90-180 degree range.

        if ( moveAngle < 0 ) moveAngle += 180;
    }

    // Figure out what image to use. Normal forward image index is 3. reverse
    // the method in the case that the car is going backwards.

    int imageNum = 3;

    if ( vel_z >= 0 )
    {
        // car going forwards. figure out image number

        imageNum -= int( ( moveAngle - 90 )  / CAR_IMAGE_CHANGE_DEGREES );
    }
    else
    {
        // car going backwards. figure out image number.

        imageNum += int( ( moveAngle - 90 )  / CAR_IMAGE_CHANGE_DEGREES );
    }

    // Clamp image to image array range

    imageNum = imageNum < 0 ? 0 : imageNum;
    imageNum = imageNum > 6 ? 6 : imageNum;

    //--------------------------------------------------------------------------
    // Draw the chosen image from the array
    //--------------------------------------------------------------------------

    this->drawPerspectiveImage(window,camera,mipArrayCar[imageNum]);
}
