summaryrefslogblamecommitdiff
path: root/game.cpp
blob: d933c2f1cdf43f63e572c9da1779c886381fa5aa (plain) (tree)






































































































                                                                                                    
#include "game.h"

#include <fstream>
#include <sstream>
#include <string>
#include <iostream>

#include "automation.h"
#include "net/nethandler.h"
#include "net/network.h"
#include "onlinelist.h"

std::string map_path;
volatile int tick_time;
volatile int cur_time;
const int MAX_TIME = 10000;
bool done = false;

OnlineList *onlinelist;

/**
 * Advances game logic counter.
 */
Uint32 nextTick(Uint32 interval, void *param)
{
    tick_time++;
    if (tick_time == MAX_TIME) tick_time = 0;
    return interval;
}

int get_elapsed_time(int start_time)
{
    if (start_time <= tick_time) {
        return (tick_time - start_time) * 10;
    }
    else {
        return (tick_time + (MAX_TIME - start_time)) * 10;
    }
}

Game::Game()
{
    // Initialize timers
    tick_time = 0;
    SDL_AddTimer(10, nextTick, NULL);                     // Logic counter
    onlinelist = new OnlineList();
}

Game::~Game()
{
    delete onlinelist;
}

int stay_awake(void *data)
{
    /* Eathena seems to kick the client after 10 mins of inactivity. 
	A teenky hack to keep it alive.*/
    while (!done)
    {
	NetHandler::getNetInstance()->sit();
	std::cout << "I'm still here." << std::endl;
	SDL_Delay(5 * 60 * 1000);
    }
}

void Game::logic()
{
    done = false;
    int gameTime = tick_time;

    SDL_Thread *wakeywakey;


    Network *mNetwork = NetHandler::getNetInstance()->getNetwork();
    NetHandler::getNetInstance()->mapLoaded();
    NetHandler::getNetInstance()->ping(tick_time);
    //NetHandler::getNetInstance()->sit();
    NetHandler::getNetInstance()->loadHandlers();
    wakeywakey = SDL_CreateThread(stay_awake, NULL);
    
    while (!done)
    {
        if (mNetwork->getState() == Network::ERROR_BROKE) //get out of this loop to allow a restart.
	    done = true;

        mNetwork->flush();
        mNetwork->dispatchMessages();

        while (get_elapsed_time(gameTime) > 0)
        {
            cur_time = static_cast<int>(time(0));
            onlinelist->logic();
    	    Automation::getAutomationHandler()->logic();
            ++gameTime;
        }

        gameTime = tick_time;

        SDL_Delay(10); // Don't steal all the cpu time.
    }

    SDL_KillThread(wakeywakey);
}