/*
	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:   TrackPopulator
// Purpose:      Has the simple responsibility for putting objects along the
//               track. These include the cars, static obstacles, oil spills
//               and such. This code was getting slightly bulky for the game
//               class, hence why it is placed here.
//
//
//##############################################################################
//##############################################################################
//##############################################################################
//##############################################################################

#include "TrackPopulator.h"

//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------

// Trees and rocks generation parameters

const float TrackPopulator::TREE_ROCK_CHANCE     = 0.35f;    // Chance that there will be an tree/rock on a side of the road at each track segment
const float TrackPopulator::TREE_ROCK_SCALE      = 16.0f;    // Scale of the tree/rock from original bitmap size
const float TrackPopulator::TREE_ROCK_X_PADDING  = 1024.0f;  // Minimum distance from the track edge the trees/rocks are
const float TrackPopulator::TREE_ROCK_X_JITTER   = 40000.0f; // How much the distance from the track side randomnly varies for trees and rocks: higher values mean further out..

// Oil spill generation parameters

const float TrackPopulator::OIL_SPILL_CHANCE = 0.005f;  // Chance there will be an oil spill in a particular section

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

Name:     TrackPopulator::createTreesAndRocks
Purpose:  Creates all the trees and rocks along the sides of the track.
Params:   Pointer to the track.
Returns:  none

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

void TrackPopulator::createTreesAndRocks(Track * track)
{
    //--------------------------------------------------------------------------
    // Random float macro: gives a float between 0.0 and 1.0
    //--------------------------------------------------------------------------

    #define RANDOM_FLOAT() ( float(rand() & 0xffff) / float(0xffff) )

    //--------------------------------------------------------------------------
    // Create obstacles randomly at each track section
    //--------------------------------------------------------------------------

    for ( unsigned int section = 0 ; section < track->getSections_count() ; section++ )
    {
        //----------------------------------------------------------------------
        // Make object at left side of track
        //----------------------------------------------------------------------

        // If the next random float <= obstacle creation likelyhood then create

        if ( RANDOM_FLOAT() <= TREE_ROCK_CHANCE )
        {
            //------------------------------------------------------------------
            // Create an obstacle at this side of the road, now pick which image
            //------------------------------------------------------------------

            int image_num = rand() % 4;

            // Select the image

            Mipmap const * obstacleImage;

            switch ( image_num )
            {
                case 0:     obstacleImage = MipmapManager::getMipTree1();   break;
                case 1:     obstacleImage = MipmapManager::getMipTree2();   break;
                case 2:     obstacleImage = MipmapManager::getMipTree3();   break;
                case 3:     obstacleImage = MipmapManager::getMipRock1();   break;
                default:    obstacleImage = MipmapManager::getMipTree1();   break;
            }

            //------------------------------------------------------------------
            // Decide on object position
            //------------------------------------------------------------------

            // Get the z value half way through this track section

            float z = section * Track::SECTION_SIZE_Z + Track::SECTION_SIZE_Z / 2.0f;

            // Get the x value at the left of the track at this z

            float x = track->getLX(z);

            // Subtract the obstacle padding value from this to move a bit away from side of track
            // Also subtract the random jitter amount to vary the x position a little bit

            x -= TREE_ROCK_X_PADDING;
            x -= TREE_ROCK_X_JITTER * RANDOM_FLOAT();

            // Get the y value at this z

            float y = track->getY(z);

            // Add half the scaled image width to the y value to put the objects logical center well above the track

            y += ( obstacleImage->getBaseHeight() * TREE_ROCK_SCALE ) * 0.5f,

            //------------------------------------------------------------------
            // Create the obstacle object and send to the object manager to look after
            //------------------------------------------------------------------

            GameObjectManager::addObject
            (
                new Obj_SolidObstacle
                (
                    obstacleImage,                                      // image to use
                    x,                                                  // position x
                    y,                                                  // position y
                    z,                                                  // position z
                    obstacleImage->getBaseWidth () * TREE_ROCK_SCALE,   // size x
                    obstacleImage->getBaseHeight() * TREE_ROCK_SCALE,   // size y
                    512                                                 // size z
                )
            );

        } // end if random chance has succeeded and create object at left of track

        //----------------------------------------------------------------------
        // Make object at right side of track
        //----------------------------------------------------------------------

        // If the next random float <= obstacle creation likelyhood then create

        if ( RANDOM_FLOAT() <= TREE_ROCK_CHANCE )
        {
            //------------------------------------------------------------------
            // Create an obstacle at this side of the road, now pick which image
            //------------------------------------------------------------------

            int image_num = rand() % 4;

            // Select the image

            Mipmap const * obstacleImage;

            switch ( image_num )
            {
                case 0:     obstacleImage = MipmapManager::getMipTree1();    break;
                case 1:     obstacleImage = MipmapManager::getMipTree2();    break;
                case 2:     obstacleImage = MipmapManager::getMipTree3();    break;
                case 3:     obstacleImage = MipmapManager::getMipRock1();    break;
                default:    obstacleImage = MipmapManager::getMipTree1();    break;
            }

            //------------------------------------------------------------------
            // Decide on object position
            //------------------------------------------------------------------

            // Get the z value half way through this track section

            float z = section * Track::SECTION_SIZE_Z + Track::SECTION_SIZE_Z / 2.0f;

            // Get the x value at the right of the track at this z

            float x = track->getRX(z);

            // Add the obstacle padding value from this to move a bit away from side of track
            // Also add the random jitter amount to vary the x position a little bit

            x += TREE_ROCK_X_PADDING;
            x += TREE_ROCK_X_JITTER * RANDOM_FLOAT();

            // Get the y value at this z

            float y = track->getY(z);

            // Add half the scaled image width to the y value to put the objects logical center well above the track

            y += ( obstacleImage->getBaseHeight() * TREE_ROCK_SCALE ) * 0.5f,

            //------------------------------------------------------------------
            // Create the obstacle object and send to the object manager to look after
            //------------------------------------------------------------------

            GameObjectManager::addObject
            (
                new Obj_SolidObstacle
                (
                    obstacleImage,                                      // image to use
                    x,                                                  // position x
                    y,                                                  // position y
                    z,                                                  // position z
                    obstacleImage->getBaseWidth () * TREE_ROCK_SCALE,   // size x
                    obstacleImage->getBaseHeight() * TREE_ROCK_SCALE,   // size y
                    obstacleImage->getBaseWidth () * TREE_ROCK_SCALE    // size z
                )
            );

        } // end if random chance has succeeded and create object at right of track

    } // end cycle through each track section loop

    // Undo this macro

    #undef RANDOM_FLOAT
}

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

Name:     TrackPopulator::createOilSpills
Purpose:  Creates all the oil spills that mar the track..
Params:   Pointer to the track.
Returns:  none

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

void TrackPopulator::createOilSpills(Track * track)
{
    //--------------------------------------------------------------------------
    // Random float macro: gives a float between 0.0 and 1.0
    //--------------------------------------------------------------------------

    #define RANDOM_FLOAT() ( float(rand() & 0xffff) / float(0xffff) )

    //--------------------------------------------------------------------------
    // Create spills randomly at each track section
    //--------------------------------------------------------------------------

    for ( unsigned int section = 8 ; section < track->getSections_count() ; section++ )
    {
        //----------------------------------------------------------------------
        // Make spill object if passed random chance test
        //----------------------------------------------------------------------

        // If the next random float <= obstacle creation likelyhood then create

        if ( RANDOM_FLOAT() <= OIL_SPILL_CHANCE )
        {
            //------------------------------------------------------------------
            // Create a spill: decide first on object position
            //------------------------------------------------------------------

            // Pick a z value randomnly within this section

            float z;

            z  = RANDOM_FLOAT() * Track::SECTION_SIZE_Z;    // range
            z += section        * Track::SECTION_SIZE_Z;    // translate to interval of values

            // Decide on the x position: somehwere inside the tarmac part of the section

            float x;

            x  = Track::SECTION_SIZE_X;                     // range to pick value from
            x *= 2;                                         // section size x is only half the width, multiply by two
            x -= Obj_OilSpill::OIL_SPILL_SIZE_X * 2;        // take this from range to account for padding at edges
            x *= RANDOM_FLOAT();                            // pick value in this range
            x += track->getLX(z);                           // translate to interval of values
            x += Obj_OilSpill::OIL_SPILL_SIZE_X * 0.5f;     // add padding to the edge

            // Get the y value at this z

            float y;

            y  = track->getY(z);                            // base y value
            y += Obj_OilSpill::OIL_SPILL_SIZE_Y * 0.5f;     // move object up so it touches track

            //------------------------------------------------------------------
            // Create the oil spill object and send to the object manager to look after
            //------------------------------------------------------------------

            GameObjectManager::addObject( new Obj_OilSpill(x,y,z) );

        } // end if random chance to crreate has succeeded

    } // end cycle through each track section loop

    // Undo this macro

    #undef RANDOM_FLOAT
}

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

Name:     TrackPopulator::createCars
Purpose:  Creates all the cars in the game at their starting positions.
          Also creates the AI players that control these cars.
Params:   As commented.
Returns:  none

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

void TrackPopulator::createCars
(
    Track    *   track,                    // track the cars go on
    unsigned     carCount,                 // number of cars in the game
    Obj_Car  **  cars,                     // game array where cars are stored
    AIPlayer **  aiPlayers,                // game array where ai players are stored
    float        playerSpeedHandicap,      // acceleration or speed advantage player has over ALL the AI cars
    float        aiCarGridSpeedDifference, // difference in acceleration between any two AI cars on the grid. as we go further back the cars get slower..
    float        gridSpacing               // space between all the cars on the grid
)
{
    //--------------------------------------------------------------------------
    // Create all the cars. First car in the array is the players car
    //--------------------------------------------------------------------------

    for ( unsigned int i = 0 ; i < carCount; i++ )
    {
        //----------------------------------------------------------------------
        // Decide on car position
        //----------------------------------------------------------------------

        // Decide on starting z position of the car

        float z = Game::CAR_STARTING_Z + gridSpacing * i;

        // Decide on the y value of the car

        float y = track->getY(z) + Obj_Car::CAR_SIZE_Y / 2.0f;

        // Decide on the x value of the car

        float x;

        x  = track->getLX(z);                           // base x value is at left side of the track
        x += Track::SECTION_SIZE_X * 0.25f;              // move to the middle of the track
        x += Track::SECTION_SIZE_X * 0.50f * ( i & 1);   // move every second car to the right side of the road

        //----------------------------------------------------------------------
        // Randomnly decide on the car image array.
        // There are 4 car skins to choose from.
        //----------------------------------------------------------------------

        Mipmap const ** carImageArray;

        int imageNum = rand() % 4;

        switch ( imageNum )
        {
            case 0:     carImageArray = MipmapManager::getMipArrayCar1(); break;
            case 1:     carImageArray = MipmapManager::getMipArrayCar2(); break;
            case 2:     carImageArray = MipmapManager::getMipArrayCar3(); break;
            case 3:     carImageArray = MipmapManager::getMipArrayCar4(); break;
            default:    carImageArray = MipmapManager::getMipArrayCar1(); break;
        }

        //----------------------------------------------------------------------
        // Create the car: give AI cars less acceleration depending on their
        // grid starting position. cars further back in the grid are slower.
        //----------------------------------------------------------------------

        if ( i != 0 )
        {
            //------------------------------------------------------------------
            // AI car: slow down according to grid position and player handicap
            //------------------------------------------------------------------

            cars[i] = new Obj_Car
            (
                carImageArray,
                x,
                y,
                z,
                Obj_Car::CAR_ACCELERATION - ( ( carCount - i ) * aiCarGridSpeedDifference ) - playerSpeedHandicap
            );
        }
        else
        {
            //------------------------------------------------------------------
            // Player car: car accelerates at normal speed
            //------------------------------------------------------------------

            cars[i] = new Obj_Car
            (
                carImageArray,
                x,
                y,
                z,
                Obj_Car::CAR_ACCELERATION
            );
        }

        //----------------------------------------------------------------------
        // Add the car into the game
        //----------------------------------------------------------------------

        GameObjectManager::addObject(cars[i]);

        //----------------------------------------------------------------------
        // Create a new AI player and assign this car to it if not the first car
        // (first car is controlled by player!)
        //----------------------------------------------------------------------

        if ( i != 0 )
        {
            // Create and save AI player

            aiPlayers[i-1] = new AIPlayer
            (
                cars[i],    // car for ai to control
                track       // track the car is on
            );
        }

    } // end of the create car loop

}


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

Name:     TrackPopulator::createFinishFlags
Purpose:  Creates the two finish flags that are at the end of the track.
Params:   Pointer to the track.
Returns:  none

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

void TrackPopulator::createFinishFlags( Track * track )
{
    //--------------------------------------------------------------------------
    // Scale of the finish sign and how far it is from the side of the track
    // (times its width)
    //--------------------------------------------------------------------------

    #define FINISH_SIGN_SCALE   32.0f
    #define FINISH_SIGN_PADDING  1.5f

    //--------------------------------------------------------------------------
    // Get the finish sign from the mipmap manager
    //--------------------------------------------------------------------------

    const Mipmap * mipFinishSign = MipmapManager::getMipFinishSign();

    //--------------------------------------------------------------------------
    // Decide on the z value of the finish flags
    //--------------------------------------------------------------------------

    float z;

    z  = float( track->getSections_count() - Game::RACE_FINISH_SECTION_FROM_END );
    z *= Track::SECTION_SIZE_Z;

    //--------------------------------------------------------------------------
    // Decide on y value at this z
    //--------------------------------------------------------------------------

    float y;

    y = track->getY(z) + mipFinishSign->getBaseHeight() * 0.5f * FINISH_SIGN_SCALE;

    //--------------------------------------------------------------------------
    // Pick x value for the flag at the left side of the road
    //--------------------------------------------------------------------------

    float x;

    x  =  (float) mipFinishSign->getBaseWidth();
    x *=  FINISH_SIGN_SCALE;
    x *= -FINISH_SIGN_PADDING;
    x +=  track->getLX(z);

    //--------------------------------------------------------------------------
    // Create the sign at the left side of the road
    //--------------------------------------------------------------------------

    GameObjectManager::addObject
    (
        new Obj_SolidObstacle
        (
            mipFinishSign,                                      // image to use for obstacle
            x,                                                  // position x
            y,                                                  // position y
            z,                                                  // position z
            mipFinishSign->getBaseWidth() * FINISH_SIGN_SCALE,  // size x
            mipFinishSign->getBaseHeight() * FINISH_SIGN_SCALE, // size y
            256                                                 // size z
        )
    );

    //--------------------------------------------------------------------------
    // Pick x value for the flag at the right side of the road
    //--------------------------------------------------------------------------

    x  = (float) mipFinishSign->getBaseWidth();
    x *= FINISH_SIGN_SCALE;
    x *= FINISH_SIGN_PADDING;
    x += track->getRX(z);

    //--------------------------------------------------------------------------
    // Create the sign at the right side of the road
    //--------------------------------------------------------------------------

    GameObjectManager::addObject
    (
        new Obj_SolidObstacle
        (
            mipFinishSign,                                      // image to use for obstacle
            x,                                                  // position x
            y,                                                  // position y
            z,                                                  // position z
            mipFinishSign->getBaseWidth()  * FINISH_SIGN_SCALE, // size x
            mipFinishSign->getBaseHeight() * FINISH_SIGN_SCALE, // size y
            256                                                 // size z
        )
    );
}
