Removed old stuff, and added main files for all projects
This commit is contained in:
parent
c9e6bbf899
commit
32348f4cc2
|
@ -1,262 +0,0 @@
|
|||
#include "Event.h"
|
||||
using namespace Event;
|
||||
|
||||
|
||||
//----------------------------
|
||||
// BulletCreated class definitions
|
||||
BulletCreated::BulletCreated(int ownerID, Float3 position, Float3 direction)
|
||||
:
|
||||
GameEvent()
|
||||
{
|
||||
data.owner=ownerID;
|
||||
data.head=direction;
|
||||
}
|
||||
void BulletCreated::LoadRawData(char* d)
|
||||
{
|
||||
memcpy(&data, d, GetSize());
|
||||
/*int offset=0;
|
||||
memcpy(&data.position, data, sizeof(Float3));
|
||||
offset+=sizeof(Float3);
|
||||
|
||||
memcpy(&data.head, d+offset, sizeof(Float3));
|
||||
offset+=sizeof(Float3);
|
||||
memcpy(&data.owner, d+offset, sizeof(int));*/
|
||||
}
|
||||
void BulletCreated::SaveRawData(char* d)
|
||||
{
|
||||
memcpy(d, &data, GetSize());
|
||||
}
|
||||
|
||||
//----------------------------
|
||||
// BulletHit class definitions
|
||||
BulletHit::BulletHit(int attacker, int hitPlayer)
|
||||
:
|
||||
GameEvent()
|
||||
{
|
||||
data.hitTarget=hitPlayer;
|
||||
data.attackingTarget=attacker;
|
||||
//this->hpLeft=hl;
|
||||
//this->shieldLeft=sl;
|
||||
}
|
||||
void BulletHit::LoadRawData(char* d)
|
||||
{
|
||||
memcpy(&data, d, GetSize());
|
||||
}
|
||||
void BulletHit::SaveRawData(char* d)
|
||||
{
|
||||
memcpy(d, &data, GetSize());
|
||||
}
|
||||
|
||||
ScoreUpdate::ScoreUpdate(Score* scores)
|
||||
{
|
||||
for (int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
data.scoreboard[i]=scores[i];
|
||||
}
|
||||
}
|
||||
void ScoreUpdate::LoadRawData(char* d)
|
||||
{
|
||||
memcpy(&data, d, GetSize());
|
||||
}
|
||||
void ScoreUpdate::SaveRawData(char* d)
|
||||
{
|
||||
memcpy(d, &data, GetSize());
|
||||
}
|
||||
|
||||
//----------------------------
|
||||
// ShipSpawned class definitions
|
||||
ShipSpawned::ShipSpawned(Float3 position, int id)
|
||||
:
|
||||
GameEvent()
|
||||
{
|
||||
data.position=position;
|
||||
data.playerID=id;
|
||||
}
|
||||
void ShipSpawned::LoadRawData(char* d)
|
||||
{
|
||||
memcpy(&data, d, this->GetSize());
|
||||
/*int offset=0;
|
||||
memcpy(&data.position, data, sizeof(Float3));
|
||||
offset+=sizeof(Float3);
|
||||
|
||||
memcpy(&playerID, data+offset, sizeof(int));*/
|
||||
}
|
||||
void ShipSpawned::SaveRawData(char* d)
|
||||
{
|
||||
memcpy(d, &data, GetSize());
|
||||
}
|
||||
|
||||
|
||||
//----------------------------
|
||||
// GameEnded class definitions
|
||||
GameEnded::GameEnded()
|
||||
:
|
||||
GameEvent()
|
||||
{
|
||||
}
|
||||
GameEnded::GameEnded(int winner)
|
||||
:
|
||||
GameEvent()
|
||||
{
|
||||
data.winningTeam=winner;
|
||||
}
|
||||
void GameEnded::LoadRawData(char* d)
|
||||
{
|
||||
memcpy(&data, d, GetSize());
|
||||
/*int offset=0;
|
||||
memcpy(&eventPosition, data, sizeof(Float3));
|
||||
offset+=sizeof(Float3);
|
||||
|
||||
memcpy(&winningTeam, data+offset, sizeof(int));
|
||||
offset+=sizeof(int);
|
||||
|
||||
for (int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
memcpy(&data.scoreboard[i], data+offset, sizeof(Score));
|
||||
offset+=sizeof(Score);
|
||||
}*/
|
||||
}
|
||||
void GameEnded::SaveRawData(char* d)
|
||||
{
|
||||
memcpy(d, &data, GetSize());
|
||||
}
|
||||
void GameEnded::setScore(int i, Score score)
|
||||
{
|
||||
data.scoreboard[i]=score;
|
||||
}
|
||||
void GameEnded::setScore(int i, int k, int d, int tk)
|
||||
{
|
||||
data.scoreboard[i].id=i;
|
||||
data.scoreboard[i].kills=k;
|
||||
data.scoreboard[i].deaths=d;
|
||||
data.scoreboard[i].teamkills=tk;
|
||||
}
|
||||
void GameEnded::sortScore()
|
||||
{
|
||||
float sort[PLAYER_MAX_COUNT];
|
||||
for(int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
sort[i]=((float)(data.scoreboard[i].kills-data.scoreboard[i].teamkills))/(float)data.scoreboard[i].deaths;
|
||||
}
|
||||
Score tmp;
|
||||
int bestID=0;
|
||||
float bestScore;
|
||||
for(int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
bestScore=sort[i];
|
||||
bestID=i;
|
||||
for (int j=i; j<PLAYER_MAX_COUNT; j++)
|
||||
{
|
||||
if(bestScore<sort[j])
|
||||
{
|
||||
bestID=j;
|
||||
bestScore=sort[j];
|
||||
}
|
||||
}
|
||||
tmp=data.scoreboard[i];
|
||||
data.scoreboard[i]=data.scoreboard[bestID];
|
||||
data.scoreboard[bestID]=tmp;
|
||||
}
|
||||
}
|
||||
|
||||
//----------------------------
|
||||
// ShipDestroyed class definitions
|
||||
ShipDestroyed::ShipDestroyed(int pid, int kid)
|
||||
:
|
||||
GameEvent()
|
||||
{
|
||||
data.playerID=pid;
|
||||
data.killerID=kid;
|
||||
}
|
||||
void ShipDestroyed::setScore(int i, Score score)
|
||||
{
|
||||
data.scoreboard[i]=score;
|
||||
}
|
||||
void ShipDestroyed::setScore(int i, int k, int d, int tk)
|
||||
{
|
||||
data.scoreboard[i].id=i;
|
||||
data.scoreboard[i].kills=k;
|
||||
data.scoreboard[i].deaths=d;
|
||||
data.scoreboard[i].teamkills=tk;
|
||||
}
|
||||
void ShipDestroyed::sortScore()
|
||||
{
|
||||
float sort[PLAYER_MAX_COUNT];
|
||||
for(int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
sort[i]=((float)(data.scoreboard[i].kills-data.scoreboard[i].teamkills))/data.scoreboard[i].deaths;
|
||||
}
|
||||
Score tmp;
|
||||
int bestID=0;
|
||||
float bestScore;
|
||||
for(int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
bestScore=sort[i];
|
||||
bestID=i;
|
||||
for (int j=i; j<PLAYER_MAX_COUNT; j++)
|
||||
{
|
||||
if(bestScore<sort[j])
|
||||
{
|
||||
bestID=j;
|
||||
bestScore=sort[j];
|
||||
}
|
||||
}
|
||||
tmp=data.scoreboard[i];
|
||||
data.scoreboard[i]=data.scoreboard[bestID];
|
||||
data.scoreboard[bestID]=tmp;
|
||||
}
|
||||
}
|
||||
void ShipDestroyed::LoadRawData(char* d)
|
||||
{
|
||||
memcpy(&data, d, GetSize());
|
||||
/*int offset=0;
|
||||
memcpy(&eventPosition, data, sizeof(Float3));
|
||||
offset+=sizeof(Float3);
|
||||
|
||||
memcpy(&playerID, data+offset, sizeof(int));
|
||||
offset+=sizeof(int);
|
||||
memcpy(&killerID, data+offset, sizeof(int));
|
||||
offset+=sizeof(int);
|
||||
for (int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
memcpy(&data.scoreboard[i], data+offset, sizeof(Score));
|
||||
offset+=sizeof(Score);
|
||||
}*/
|
||||
}
|
||||
void ShipDestroyed::SaveRawData(char* d)
|
||||
{
|
||||
memcpy(d, &data, GetSize());
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
Event::Type Event::getEventType(Event::GameEvent* evt)
|
||||
{
|
||||
if (typeid(*evt)==typeid(Event::BulletCreated))
|
||||
{
|
||||
return eBulletCreated;
|
||||
}
|
||||
else if(typeid(*evt)==typeid(Event::BulletHit))
|
||||
{
|
||||
return eBulletHit;
|
||||
}
|
||||
else if(typeid(*evt)==typeid(Event::ShipSpawned))
|
||||
{
|
||||
return eShipSpawned;
|
||||
}
|
||||
else if(typeid(*evt)==typeid(Event::GameEnded))
|
||||
{
|
||||
return eGameEnded;
|
||||
}
|
||||
else if(typeid(*evt)==typeid(Event::ShipDestroyed))
|
||||
{
|
||||
return eShipDestroyed;
|
||||
}
|
||||
else if(typeid(*evt)==typeid(Event::ScoreUpdate))
|
||||
{
|
||||
return eScoreUpdate;
|
||||
}
|
||||
printf("UNSUPPORTED EVENT at getEventType, Event.cpp\n");
|
||||
return UNSUPPORTED_TYPE;
|
||||
}
|
|
@ -1,142 +0,0 @@
|
|||
#include "NetworkIncludes.h"
|
||||
#include "EventStructs.h"
|
||||
#pragma once
|
||||
#ifndef EVENT_H
|
||||
#define EVENT_H
|
||||
//There's a variable called eventList in Session.
|
||||
//if you push_back any type of event, the server will pick them up in order after every update() is run.
|
||||
|
||||
|
||||
//Try to keep events pointer-free. Trying to send a class with a pointer over a socket will result in a problem because
|
||||
//it will send the pointer rather than the data in the pointer. That results in either
|
||||
//A: Program crashing because it's not allowed to read that space if it's on the same computer as the server or
|
||||
//B: Program crashing because the pointer most probably points to an unused space if the client is on a separate computer.
|
||||
|
||||
//This is the basic event class.
|
||||
//a position should always be given with all events, to use as a main location for sounds, effects, or whatever. We can remove it if we decide it's not needed later on.
|
||||
|
||||
namespace Event
|
||||
{
|
||||
class GameEvent
|
||||
{
|
||||
protected:
|
||||
public:
|
||||
GameEvent(){}
|
||||
virtual int GetSize()=0;
|
||||
virtual void LoadRawData(char* d)=0;
|
||||
virtual void SaveRawData(char* d)=0;
|
||||
};
|
||||
|
||||
//When a player fires a projectile, a BulletCreated event should be added.
|
||||
class BulletCreated : public GameEvent
|
||||
{
|
||||
private:
|
||||
EventStruct::BulletCreatedStruct data;
|
||||
public:
|
||||
BulletCreated():GameEvent(){}
|
||||
BulletCreated(int ownerID, Float3 position, Float3 Head);
|
||||
int GetOwner(){return data.owner;}
|
||||
int GetSize(){return sizeof(data);}
|
||||
EventStruct::BulletCreatedStruct GetAsStruct(){return data;}
|
||||
void LoadRawData(char* d);
|
||||
void SaveRawData(char* d);
|
||||
};
|
||||
|
||||
class ScoreUpdate : public GameEvent
|
||||
{
|
||||
private:
|
||||
EventStruct::ScoreUpdateStruct data;
|
||||
public:
|
||||
ScoreUpdate():GameEvent(){}
|
||||
ScoreUpdate(Score* scoreboard);
|
||||
int GetSize(){return sizeof(data);}
|
||||
EventStruct::ScoreUpdateStruct GetAsStruct(){return data;}
|
||||
void LoadRawData(char* d);
|
||||
void SaveRawData(char* d);
|
||||
};
|
||||
|
||||
//When some kind of player-fired projectile hits an enemy, a BulletHit even should be added.
|
||||
class BulletHit : public GameEvent
|
||||
{
|
||||
private:
|
||||
EventStruct::BulletHitStruct data;
|
||||
public:
|
||||
BulletHit():GameEvent(){}
|
||||
BulletHit(int attacker, int hitPlayer);
|
||||
int getAttackerID(){return data.attackingTarget;}
|
||||
int getHitTargetID(){return data.hitTarget;}
|
||||
int GetSize(){return sizeof(data);}
|
||||
EventStruct::BulletHitStruct GetAsStruct(){return data;}
|
||||
void LoadRawData(char* d);
|
||||
void SaveRawData(char* d);
|
||||
};
|
||||
|
||||
//Shipspawned event, for when a ship respawns.
|
||||
//In ShipSpawned, all data that the client requires should be given.
|
||||
class ShipSpawned : public GameEvent
|
||||
{
|
||||
private:
|
||||
EventStruct::ShipSpawnedStruct data;
|
||||
public:
|
||||
ShipSpawned():GameEvent(){}
|
||||
ShipSpawned(Float3 position, int id);
|
||||
int GetSize(){return sizeof(data);}
|
||||
EventStruct::ShipSpawnedStruct GetAsStruct(){return data;}
|
||||
void LoadRawData(char* d);
|
||||
void SaveRawData(char* d);
|
||||
};
|
||||
|
||||
class ShipDestroyed : public GameEvent
|
||||
{
|
||||
public:
|
||||
EventStruct::ShipDestroyedStruct data;
|
||||
public:
|
||||
ShipDestroyed():GameEvent(){}
|
||||
ShipDestroyed(int pid, int kid);
|
||||
void setScore(int i, Score score);
|
||||
void setScore(int i, int k, int d, int tk);
|
||||
void sortScore();
|
||||
int getDestroyedID() const {return data.playerID;}
|
||||
int getAttackerID() const {return data.killerID;}
|
||||
EventStruct::ShipDestroyedStruct GetAsStruct(){return data;}
|
||||
|
||||
int GetSize(){return sizeof(data);}
|
||||
void LoadRawData(char* d);
|
||||
void SaveRawData(char* d);
|
||||
};
|
||||
|
||||
|
||||
class GameEnded : public GameEvent
|
||||
{
|
||||
private:
|
||||
EventStruct::GameEndedStruct data;
|
||||
//Have some variables which shows scores of player, who won, etc
|
||||
//you just need the ids. Don't send names etc.
|
||||
public:
|
||||
GameEnded();
|
||||
GameEnded(int winner);
|
||||
void setScore(int i, Score score);
|
||||
void setScore(int i, int k, int d, int tk);
|
||||
void sortScore();
|
||||
int GetSize(){return sizeof(data);}
|
||||
EventStruct::GameEndedStruct GetAsStruct(){return data;}
|
||||
void LoadRawData(char* d);
|
||||
void SaveRawData(char* d);
|
||||
};
|
||||
|
||||
enum Type
|
||||
{
|
||||
UNSUPPORTED_TYPE,
|
||||
eBulletCreated,
|
||||
eBulletHit,
|
||||
eShipSpawned,
|
||||
eGameEnded,
|
||||
eShipDestroyed,
|
||||
eScoreUpdate
|
||||
};
|
||||
Event::Type getEventType(Event::GameEvent* evt);
|
||||
|
||||
|
||||
|
||||
}
|
||||
#endif
|
|
@ -1,55 +0,0 @@
|
|||
#include "NetworkIncludes.h"
|
||||
#include "NetworkConstants.h"
|
||||
#ifndef NET_EVT_STRUCTS_H
|
||||
#define NET_EVT_STRUCTS_H
|
||||
struct Score
|
||||
{
|
||||
int id;//Leaderboard var
|
||||
int kills;
|
||||
int deaths;
|
||||
int teamkills;
|
||||
Score(){id=0;kills=0;deaths=0;teamkills=0;}
|
||||
Score& operator+=(const Score add)
|
||||
{
|
||||
id+=add.id;
|
||||
kills+=add.kills;
|
||||
deaths+=add.deaths;
|
||||
teamkills+=add.teamkills;
|
||||
return *this;
|
||||
}
|
||||
};
|
||||
namespace EventStruct
|
||||
{
|
||||
struct BulletCreatedStruct
|
||||
{
|
||||
Float3 position;
|
||||
Float3 head;
|
||||
int owner;
|
||||
};
|
||||
struct BulletHitStruct
|
||||
{
|
||||
int hitTarget;
|
||||
int attackingTarget;
|
||||
};
|
||||
struct ShipSpawnedStruct
|
||||
{
|
||||
Float3 position;
|
||||
int playerID;
|
||||
};
|
||||
struct ShipDestroyedStruct
|
||||
{
|
||||
int playerID;
|
||||
int killerID;
|
||||
Score scoreboard[PLAYER_MAX_COUNT];
|
||||
};
|
||||
struct ScoreUpdateStruct
|
||||
{
|
||||
Score scoreboard[PLAYER_MAX_COUNT];
|
||||
};
|
||||
struct GameEndedStruct
|
||||
{
|
||||
int winningTeam;
|
||||
Score scoreboard[PLAYER_MAX_COUNT];
|
||||
};
|
||||
}
|
||||
#endif
|
|
@ -1,11 +0,0 @@
|
|||
#ifndef NETWORK_H
|
||||
#define NETWORK_H
|
||||
#include "NetworkIncludes.h"
|
||||
#include "EventStructs.h"
|
||||
#include "NetworkUpdateStructs.h"
|
||||
#include "NetworkInitStructs.h"
|
||||
#include "EventStructs.h"
|
||||
#include "Event.h"
|
||||
#include "NetworkMiscFunctions.h"
|
||||
#include "NetworkTimer.h"
|
||||
#endif
|
|
@ -1,11 +0,0 @@
|
|||
#pragma once
|
||||
#ifndef NET_CONST_H
|
||||
#define NET_CONST_H
|
||||
//const int PLAYER_WAIT_COUNT = 1;
|
||||
const int PLAYER_MAX_COUNT = 8;
|
||||
const float LOBBY_WAIT_TIME = 4;
|
||||
/*namespace Network
|
||||
{
|
||||
void LoadData(){}
|
||||
}*/
|
||||
#endif
|
|
@ -137,23 +137,6 @@
|
|||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="Event.h" />
|
||||
<ClInclude Include="EventStructs.h" />
|
||||
<ClInclude Include="Network.h" />
|
||||
<ClInclude Include="NetworkConstants.h" />
|
||||
<ClInclude Include="NetworkIncludes.h" />
|
||||
<ClInclude Include="NetworkInitStructs.h" />
|
||||
<ClInclude Include="NetworkMiscFunctions.h" />
|
||||
<ClInclude Include="NetworkTimer.h" />
|
||||
<ClInclude Include="NetworkUpdateStructs.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="Event.cpp" />
|
||||
<ClCompile Include="NetworkMiscFunctions.cpp" />
|
||||
<ClCompile Include="NetworkTimer.cpp" />
|
||||
<ClCompile Include="UpdateStructs.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Misc\Misc.vcxproj">
|
||||
<Project>{2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee}</Project>
|
||||
|
@ -167,6 +150,9 @@
|
|||
<UseLibraryDependencyInputs>false</UseLibraryDependencyInputs>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="main.cpp" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
|
|
@ -15,45 +15,7 @@
|
|||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="Network.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="NetworkConstants.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="NetworkIncludes.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="NetworkInitStructs.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="NetworkMiscFunctions.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="NetworkTimer.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="NetworkUpdateStructs.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="EventStructs.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Event.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="NetworkMiscFunctions.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="NetworkTimer.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="UpdateStructs.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="Event.cpp">
|
||||
<ClCompile Include="main.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
|
|
|
@ -1,23 +0,0 @@
|
|||
#ifndef NET_INCL_H
|
||||
#define NET_INCL_H
|
||||
#ifndef UNICODE
|
||||
#define UNICODE
|
||||
#endif
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define NOMINMAX
|
||||
#include <winsock2.h>
|
||||
#include <Ws2tcpip.h>
|
||||
#include <stdio.h>
|
||||
#include <windows.h>
|
||||
#include <time.h>
|
||||
#include <string>
|
||||
#include <ctime>
|
||||
#include <iostream>
|
||||
|
||||
#include "OysterMath.h"
|
||||
using namespace Oyster::Math;
|
||||
|
||||
//ws2_32.lib is a lib file the linker requires for winsock compilation
|
||||
#pragma comment(lib, "Ws2_32.lib")
|
||||
#endif
|
|
@ -1,70 +0,0 @@
|
|||
#ifndef NET_INIT_STRUCTS_H
|
||||
#define NET_INIT_STRUCTS_H
|
||||
#include "NetworkIncludes.h"
|
||||
#include "NetworkConstants.h"
|
||||
struct PlayerInitStruct
|
||||
{
|
||||
INT8 pid;
|
||||
int teamid;
|
||||
Oyster::Math::Float4x4 position;
|
||||
PlayerInitStruct()
|
||||
{
|
||||
pid=0;
|
||||
//position=Oyster::Math::Float4x4::identity;
|
||||
}
|
||||
};
|
||||
|
||||
struct GameInitData
|
||||
{
|
||||
INT8 pid;
|
||||
//std::string playerNames[PLAYER_MAX_COUNT];
|
||||
PlayerInitStruct player[PLAYER_MAX_COUNT];
|
||||
};
|
||||
|
||||
struct LobbyUserStruct
|
||||
{
|
||||
INT8 pid;
|
||||
INT8 shipID;
|
||||
char usrName[15];
|
||||
LobbyUserStruct()
|
||||
{
|
||||
pid=0;
|
||||
shipID=0;
|
||||
usrName[0]='\0';
|
||||
}
|
||||
void setName(const char* n)
|
||||
{
|
||||
strcpy_s(usrName, n);
|
||||
}
|
||||
int size()
|
||||
{
|
||||
int sz=sizeof(pid);
|
||||
sz+=sizeof(shipID);
|
||||
int tmp=(int)strlen(usrName);
|
||||
sz+=(int)strlen(usrName);
|
||||
return sz;
|
||||
}
|
||||
};
|
||||
struct LobbyInitData
|
||||
{
|
||||
INT8 pid;
|
||||
INT8 playerCount;
|
||||
int timer;
|
||||
LobbyUserStruct players[PLAYER_MAX_COUNT];
|
||||
LobbyInitData()
|
||||
{
|
||||
pid=0;
|
||||
for (int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
players[i].pid=i;
|
||||
}
|
||||
}
|
||||
int size()
|
||||
{
|
||||
int sz=sizeof(pid);
|
||||
for (int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
sz+=players[i].size();
|
||||
return sz;
|
||||
}
|
||||
};
|
||||
#endif
|
|
@ -1,12 +0,0 @@
|
|||
#include "NetworkMiscFunctions.h"
|
||||
std::vector<std::string> splitString(const char* p_inStr, char p_delim)
|
||||
{
|
||||
std::stringstream ss(p_inStr);
|
||||
std::vector<std::string> elems;
|
||||
std::string item;
|
||||
while(std::getline(ss, item, p_delim))
|
||||
{
|
||||
elems.push_back(item);
|
||||
}
|
||||
return elems;
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
#ifndef NET_MISC_FNC_H
|
||||
#define NET_MISC_FNC_H
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <sstream>
|
||||
std::vector<std::string> splitString(const char* p_inStr, char p_delim);
|
||||
#define SSTR( x ) dynamic_cast< std::ostringstream & >( \
|
||||
( std::ostringstream() << std::dec << x ) ).str()
|
||||
#endif
|
|
@ -1,85 +0,0 @@
|
|||
#include "NetworkTimer.h"
|
||||
NetworkTimer::NetworkTimer()
|
||||
:
|
||||
c_SecondsPerCount(0.0),
|
||||
c_DeltaTime(-1.0),
|
||||
c_BaseTime(0),
|
||||
c_PausedTime(0),
|
||||
c_PrevTime(0),
|
||||
c_CurrTime(0),
|
||||
c_Stopped(false)
|
||||
{
|
||||
__int64 countsPerSec;
|
||||
QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec);
|
||||
c_SecondsPerCount =1.0 / (double)countsPerSec;
|
||||
|
||||
QueryPerformanceCounter((LARGE_INTEGER*)&c_PrevTime);
|
||||
}
|
||||
|
||||
void NetworkTimer::start()
|
||||
{
|
||||
__int64 p_StartTime;
|
||||
QueryPerformanceCounter((LARGE_INTEGER*)&p_StartTime);
|
||||
if(c_Stopped)
|
||||
{
|
||||
c_PausedTime += (p_StartTime-c_StopTime);
|
||||
c_PrevTime = p_StartTime;
|
||||
c_StopTime = 0;
|
||||
c_Stopped = false;
|
||||
}
|
||||
}
|
||||
__int64 NetworkTimer::getTime()
|
||||
{
|
||||
__int64 testInt;
|
||||
return QueryPerformanceCounter((LARGE_INTEGER*)&testInt);
|
||||
return testInt;
|
||||
}
|
||||
|
||||
void NetworkTimer::stop()
|
||||
{
|
||||
if(!c_Stopped)
|
||||
{
|
||||
__int64 p_CurrTime;
|
||||
QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime);
|
||||
c_StopTime = p_CurrTime;
|
||||
c_Stopped = true;
|
||||
}
|
||||
}
|
||||
void NetworkTimer::reset()
|
||||
{
|
||||
__int64 p_CurrTime;
|
||||
QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime);
|
||||
c_BaseTime = p_CurrTime;
|
||||
c_PrevTime = p_CurrTime;
|
||||
c_StopTime = 0;
|
||||
c_Stopped = false;
|
||||
}
|
||||
void NetworkTimer::tick()
|
||||
{
|
||||
if (c_Stopped)
|
||||
{
|
||||
c_DeltaTime= 0.0;
|
||||
return;
|
||||
}
|
||||
__int64 p_CurrTime;
|
||||
QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime);
|
||||
c_CurrTime=p_CurrTime;
|
||||
|
||||
c_DeltaTime=(c_CurrTime-c_PrevTime)*c_SecondsPerCount;
|
||||
c_PrevTime=c_CurrTime;
|
||||
if(c_DeltaTime<0.0) c_DeltaTime=0.0;
|
||||
}
|
||||
float NetworkTimer::getGameTime() const
|
||||
{
|
||||
if(c_Stopped)
|
||||
{
|
||||
return (float)((c_StopTime-c_BaseTime)*c_SecondsPerCount);
|
||||
} else
|
||||
{
|
||||
return (float)(((c_CurrTime-c_PausedTime)-c_BaseTime)*c_SecondsPerCount);
|
||||
}
|
||||
}
|
||||
float NetworkTimer::getDeltaTime() const
|
||||
{
|
||||
return (float)c_DeltaTime;
|
||||
}
|
|
@ -1,25 +0,0 @@
|
|||
#include "NetworkIncludes.h"
|
||||
#ifndef _NET_TIMER_H
|
||||
#define _NET_TIMER_H
|
||||
class NetworkTimer
|
||||
{
|
||||
private:
|
||||
double c_SecondsPerCount;
|
||||
double c_DeltaTime;
|
||||
__int64 c_BaseTime;
|
||||
__int64 c_PausedTime;
|
||||
__int64 c_StopTime;
|
||||
__int64 c_PrevTime;
|
||||
__int64 c_CurrTime;
|
||||
bool c_Stopped;
|
||||
public:
|
||||
NetworkTimer();
|
||||
__int64 getTime();
|
||||
void start();
|
||||
void stop();
|
||||
void reset();
|
||||
void tick();
|
||||
float getGameTime() const;
|
||||
float getDeltaTime() const;
|
||||
};
|
||||
#endif
|
|
@ -1,62 +0,0 @@
|
|||
#ifndef NET_UPD_STRUCTS_H
|
||||
#define NET_UPD_STRUCTS_H
|
||||
#include "NetworkIncludes.h"
|
||||
namespace Network
|
||||
{
|
||||
struct EffectData
|
||||
{
|
||||
int identifier;
|
||||
Float3 head;
|
||||
Float3 tail;
|
||||
};
|
||||
struct ServerToClientUpdateData
|
||||
{
|
||||
int pid;
|
||||
Oyster::Math::Float4x4 position;
|
||||
float dirVecLen;
|
||||
int hp;
|
||||
int shield;
|
||||
long updateCount;
|
||||
ServerToClientUpdateData()
|
||||
{
|
||||
pid=0;
|
||||
updateCount=0;
|
||||
hp=0;
|
||||
shield=0;
|
||||
}
|
||||
};
|
||||
const int SERVER_PLAYER_DATA_SIZE = 84;
|
||||
struct ClientToServerUpdateData
|
||||
{
|
||||
__int8 pid;
|
||||
//Oyster::Math::Float4x4 position;
|
||||
__int8 forward;
|
||||
__int8 roll;
|
||||
__int8 straferight;
|
||||
__int8 strafeup;
|
||||
bool firePrim;
|
||||
bool fireSecond;
|
||||
bool fireSpecial;
|
||||
long updateCount;
|
||||
bool braking;
|
||||
float TurnHor;
|
||||
float TurnVer;
|
||||
ClientToServerUpdateData()
|
||||
{
|
||||
pid=0;
|
||||
forward=0;
|
||||
roll=0;
|
||||
straferight=0;
|
||||
strafeup=0;
|
||||
firePrim=false;
|
||||
fireSecond=false;
|
||||
fireSpecial=false;
|
||||
updateCount=0;
|
||||
braking=false;
|
||||
TurnHor= 0.0f;
|
||||
TurnVer= 0.0f;
|
||||
}
|
||||
};
|
||||
const int CLIENT_PLAYER_DATA_SIZE = sizeof(ClientToServerUpdateData);
|
||||
}
|
||||
#endif
|
|
@ -1 +0,0 @@
|
|||
#include "NetworkUpdateStructs.h"
|
|
@ -1,112 +0,0 @@
|
|||
#include "SocketClient.h"
|
||||
|
||||
#pragma once
|
||||
#ifndef SOCKET_DATA_CPP
|
||||
#define SOCKET_DATA_CPP
|
||||
|
||||
/*std::vector<std::string> splitString(char* p_inStr, char p_delim)
|
||||
{
|
||||
std::stringstream ss(p_inStr);
|
||||
std::vector<std::string> elems;
|
||||
std::string item;
|
||||
while(std::getline(ss, item, p_delim))
|
||||
{
|
||||
elems.push_back(item);
|
||||
}
|
||||
return elems;
|
||||
}*/
|
||||
|
||||
void SocketClient::parseReceivedData(/*char* data, int size*/)
|
||||
{
|
||||
switch (recvBuffer[0]) // TODO: runtime error occured here when shutting down client. recvBuffer invalid pointer. ~Dan 2013-05-14
|
||||
{
|
||||
case 1://It's data
|
||||
parseData();
|
||||
break;
|
||||
case 2://For the moment, this is only for init data
|
||||
parseGameInitData();
|
||||
break;
|
||||
case 3://It's a chat message
|
||||
parseMessage();
|
||||
break;
|
||||
case 4://It's a server message
|
||||
parseServermessage();
|
||||
break;
|
||||
case 5://Player has been connected to a game lobby
|
||||
parseLobbyInitData();
|
||||
break;
|
||||
case 6://It's an event
|
||||
parseReceivedEvent();
|
||||
break;
|
||||
case 7:
|
||||
parseReceivedEffect();
|
||||
break;
|
||||
case 8:
|
||||
parseRenderData();
|
||||
break;
|
||||
default:
|
||||
int a=0;
|
||||
|
||||
}
|
||||
}
|
||||
void SocketClient::parseRenderData()
|
||||
{
|
||||
receiveRenderData(recvBuffer+1, recvBufLen-1);
|
||||
}
|
||||
void SocketClient::parseReceivedEffect()
|
||||
{
|
||||
receiveEffectData(recvBuffer+1, recvBufLen-1);
|
||||
}
|
||||
void SocketClient::parseReceivedEvent()
|
||||
{
|
||||
receiveEvent(recvBuffer+1);
|
||||
}
|
||||
void SocketClient::parseGameInitData()
|
||||
{
|
||||
receiveGameInitData(recvBuffer+1);
|
||||
connectStatus=true;
|
||||
}
|
||||
|
||||
void SocketClient::parseLobbyInitData()
|
||||
{
|
||||
receiveLobbyInitData(recvBuffer+1, recvBufLen-1);
|
||||
connectStatus=true;
|
||||
}
|
||||
|
||||
void SocketClient::parseServermessage()
|
||||
{
|
||||
recvBuffer[recvBufLen]='\0';
|
||||
if(!strcmp(recvBuffer+1, "connected"))
|
||||
{
|
||||
connectStatus=true;
|
||||
connStatus=ONLINE_MAINMENU;
|
||||
receiveConnStatus(ONLINE_MAINMENU);
|
||||
}
|
||||
else if(!strcmp(recvBuffer+1, "qst"))
|
||||
{
|
||||
connStatus=ONLINE_QUEUEING;
|
||||
receiveConnStatus(ONLINE_QUEUEING);
|
||||
}
|
||||
else if(!strcmp(recvBuffer+1, "qed"))
|
||||
{
|
||||
connStatus=ONLINE_MAINMENU;
|
||||
receiveConnStatus(ONLINE_MAINMENU);
|
||||
}
|
||||
//Server message of some sort
|
||||
}
|
||||
|
||||
void SocketClient::parseData()
|
||||
{
|
||||
//memcpy(&tmpPlayer,buffer+1,playerDataSize);
|
||||
//playerContPtr->setPlayerStruct(tmpPlayer);
|
||||
receivePlayerUpdate(recvBuffer+1, recvBufLen-1);
|
||||
}
|
||||
|
||||
void SocketClient::parseMessage()
|
||||
{
|
||||
//std::string message;
|
||||
//message="[Chat] "+users[pid].getUsername()+": "+(buffer+1);
|
||||
printf("%s\n",recvBuffer+1);
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,79 +0,0 @@
|
|||
#include "SocketClient.h"
|
||||
|
||||
#pragma once
|
||||
#ifndef SOCKET_INIT_CPP
|
||||
#define SOCKET_INIT_CPP
|
||||
|
||||
bool SocketClient::startReceiveThread()
|
||||
{
|
||||
threadhandle[0]=CreateThread(
|
||||
NULL,
|
||||
0,
|
||||
(LPTHREAD_START_ROUTINE)&receiveDataThreadV,
|
||||
(LPVOID) this,
|
||||
0,
|
||||
NULL);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SocketClient::startSendDataThread()
|
||||
{
|
||||
threadhandle[1]=CreateThread(
|
||||
NULL,
|
||||
0,
|
||||
(LPTHREAD_START_ROUTINE)&receiveDataThreadV,
|
||||
(LPVOID) this,
|
||||
0,
|
||||
NULL);
|
||||
return true;
|
||||
}
|
||||
bool SocketClient::init(int listenPort)
|
||||
{
|
||||
return initUDPSocket(listenPort);
|
||||
}
|
||||
bool SocketClient::connectToIP(const char* ip, int listenPort, char* initData, int initDataSize)
|
||||
{
|
||||
init(listenPort);
|
||||
//---------------------------------------------
|
||||
// Set up the port and IP of the server
|
||||
//Port starts up as a different one from when connected, it changes once the server has exchanged some info with the client
|
||||
|
||||
UDPsendAddr.sin_family = AF_INET;
|
||||
UDPsendAddr.sin_port = htons(UDPSendPort);
|
||||
UDPsendAddr.sin_addr.s_addr = inet_addr(ip);
|
||||
|
||||
TCPsendAddr.sin_family = AF_INET;
|
||||
TCPsendAddr.sin_port = htons(TCPSendPort);
|
||||
TCPsendAddr.sin_addr.s_addr = inet_addr(ip);
|
||||
/*iResult=connect(connTCP, (SOCKADDR *) &TCPsendAddr, addrSize);
|
||||
if (iResult == SOCKET_ERROR) {
|
||||
int test=WSAGetLastError();
|
||||
wprintf(L"connect failed with error: %d\n", WSAGetLastError());
|
||||
//closesocket(connTCP);
|
||||
//WSACleanup();
|
||||
return false;
|
||||
}/*
|
||||
iResult=send(connTCP, initData, initDataSize, 0);
|
||||
if (iResult == SOCKET_ERROR) {
|
||||
int test=WSAGetLastError();
|
||||
wprintf(L"connect failed with error: %d\n", WSAGetLastError());
|
||||
//closesocket(connTCP);
|
||||
//WSACleanup();
|
||||
return false;
|
||||
}*/
|
||||
|
||||
iResult = sendto(connUDP,
|
||||
initData, initDataSize, 0, (SOCKADDR *) & UDPsendAddr, addrSize);
|
||||
if (iResult == SOCKET_ERROR) {
|
||||
wprintf(L"Client UDP sendto failed with error: %d\n", WSAGetLastError());
|
||||
//closesocket(connUDP);
|
||||
//WSACleanup();
|
||||
return false;
|
||||
}
|
||||
//connectStatus=true;
|
||||
connectStatus=false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
#endif
|
|
@ -1,79 +0,0 @@
|
|||
#include "SocketClient.h"
|
||||
const int maxThreadCount=2;
|
||||
bool validateIpAddress(const std::string ipAddress)
|
||||
{
|
||||
struct sockaddr_in sa;
|
||||
int result = inet_pton(AF_INET, ipAddress.c_str(), &(sa.sin_addr));
|
||||
return result != 0;
|
||||
}
|
||||
/*int main(int argc, char *argv[])
|
||||
{
|
||||
std::string tst;
|
||||
bool test=true;
|
||||
//Multithreading variables
|
||||
//int nThreads = 0;
|
||||
//DWORD dwThreadId[maxThreadCount];
|
||||
//HANDLE threadhandle;
|
||||
|
||||
GameClass game;
|
||||
SocketClient<GameClass> client;
|
||||
//Sets up the link to the GameClass class.
|
||||
client.setPlayerContPtr(&game);
|
||||
//This is the loop which makes the user enter the server address.
|
||||
while (!client.isReady());
|
||||
do
|
||||
{
|
||||
if (!test)
|
||||
{
|
||||
printf("Could not connect to server. Try another IP.\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Enter the server ip. \n");
|
||||
}
|
||||
getline(std::cin, tst);
|
||||
if (tst.length()==0)
|
||||
{
|
||||
tst="127.0.0.1";
|
||||
}
|
||||
if (validateIpAddress(tst))
|
||||
{
|
||||
//Tmp init connection message: set username
|
||||
char* tmp=new char[30];
|
||||
printf("What is your desired username?\n");
|
||||
std::cin.getline(tmp,30);
|
||||
if (strlen(tmp)==0)
|
||||
{
|
||||
tmp="Anonymous";
|
||||
}
|
||||
printf("Username set to %s\n", tmp);
|
||||
|
||||
test=client.connectToIP(tst.c_str(), tmp, strlen(tmp));
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Invalid IPaddress. Please enter a new IPaddress.\n");
|
||||
test=false;
|
||||
}
|
||||
} while (!test);
|
||||
while (!client.isConnected());
|
||||
Sleep(1000);
|
||||
//Starts the receive loop
|
||||
//threadhandle=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&client.receiveDataThreadV,(LPVOID) &client,0,&dwThreadId[0]);
|
||||
client.startReceiveThread();
|
||||
//GetExitCodeThread(threadhandle, eCode);
|
||||
//This is just a loop to receive user input which creates a natural delay for sendUserData.
|
||||
printf("Write what you want to send\n");
|
||||
tst="tmp init message";
|
||||
while (tst.length()>0)
|
||||
{
|
||||
client.sendMessage(tst);
|
||||
client.sendUserData();
|
||||
getline(std::cin, tst);
|
||||
}
|
||||
//Kills off the thread and connection
|
||||
//DWORD eCode=0;
|
||||
//TerminateThread(threadhandle, eCode);
|
||||
client.closeConnection();
|
||||
return 0;
|
||||
}*/
|
|
@ -1,39 +0,0 @@
|
|||
#include "SocketClient.h"
|
||||
|
||||
bool SocketClient::initTCPSocket(int listenPort)
|
||||
{
|
||||
TCPrecvAddr.sin_family = AF_INET;
|
||||
TCPrecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
TCPrecvAddr.sin_port = htons(/*TCPRecvPort*/listenPort);
|
||||
|
||||
connTCP = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
if (connTCP == INVALID_SOCKET)
|
||||
{
|
||||
wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
|
||||
iResult = bind(connTCP, (SOCKADDR *) & TCPrecvAddr, addrSize);
|
||||
if (iResult == SOCKET_ERROR)
|
||||
{
|
||||
int tst=WSAGetLastError();
|
||||
wprintf(L"bind function failed with error %d\n", WSAGetLastError());
|
||||
iResult = closesocket(connTCP);
|
||||
if (iResult == SOCKET_ERROR)
|
||||
wprintf(L"closesocket function failed with error %d\n", WSAGetLastError());
|
||||
//WSACleanup();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool SocketClient::sendDataTCP(const char* data, int size)
|
||||
{
|
||||
iResult = sendto(connTCP,
|
||||
data, size, 0, (SOCKADDR *) & TCPsendAddr, addrSize);
|
||||
if (iResult == SOCKET_ERROR) {
|
||||
wprintf(L"TCP sendto failed with error: %d\n", WSAGetLastError());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
|
@ -1,39 +0,0 @@
|
|||
#include "SocketClient.h"
|
||||
bool SocketClient::initUDPSocket(int listenPort)
|
||||
{
|
||||
UDPrecvAddr.sin_family = AF_INET;
|
||||
UDPrecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
UDPrecvAddr.sin_port = htons(listenPort);
|
||||
//---------------------------------------------
|
||||
// Create a socket for sending data
|
||||
connUDP = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||
if (connUDP == INVALID_SOCKET)
|
||||
{
|
||||
wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
iResult = bind(connUDP, (SOCKADDR *) & UDPrecvAddr, addrSize);
|
||||
if (iResult == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"bind function failed with error %d\n", WSAGetLastError());
|
||||
iResult = closesocket(connUDP);
|
||||
if (iResult == SOCKET_ERROR)
|
||||
wprintf(L"closesocket function failed with error %d\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool SocketClient::sendDataUDP(const char* data, int size)
|
||||
{
|
||||
iResult = sendto(connUDP,
|
||||
data, size, 0, (SOCKADDR *) & UDPsendAddr, addrSize);
|
||||
if (iResult == SOCKET_ERROR) {
|
||||
wprintf(L"sendto failed with error: %d\n", WSAGetLastError());
|
||||
//closesocket(connUDP);
|
||||
//WSACleanup();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
|
@ -24,26 +24,26 @@
|
|||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v110</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v110</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v110</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v110</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
|
@ -137,17 +137,6 @@
|
|||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="ClientDataHandler.cpp" />
|
||||
<ClCompile Include="ClientInitFunctions.cpp" />
|
||||
<ClCompile Include="ClientMain.cpp" />
|
||||
<ClCompile Include="ClientTCPSpecific.cpp" />
|
||||
<ClCompile Include="ClientUDPSpecific.cpp" />
|
||||
<ClCompile Include="SocketClient.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="SocketClient.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Misc\Misc.vcxproj">
|
||||
<Project>{2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee}</Project>
|
||||
|
@ -159,6 +148,9 @@
|
|||
<Project>{c5aa09d0-6594-4cd3-bd92-1d380c7b3b50}</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="main.cpp" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
|
|
@ -15,28 +15,8 @@
|
|||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="ClientDataHandler.cpp">
|
||||
<ClCompile Include="main.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ClientInitFunctions.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ClientMain.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ClientTCPSpecific.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ClientUDPSpecific.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="SocketClient.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="SocketClient.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
</Project>
|
|
@ -1,133 +0,0 @@
|
|||
#include "SocketClient.h"
|
||||
#pragma once
|
||||
#ifndef SOCKET_CLIENT_CPP
|
||||
#define SOCKET_CLIENT_CPP
|
||||
|
||||
SocketClient::SocketClient()
|
||||
{
|
||||
playerDataSize=Network::CLIENT_PLAYER_DATA_SIZE;
|
||||
sendDelayMS=10;
|
||||
connUDP = INVALID_SOCKET;
|
||||
connTCP = INVALID_SOCKET;
|
||||
//sendBuffer=new char[BUFFER_MAX_SIZE];
|
||||
//sendBufLen=BUFFER_MAX_SIZE;
|
||||
//ZeroMemory(sendBuffer,sendBufLen);
|
||||
recvBuffer=new char[BUFFER_MAX_SIZE];
|
||||
recvBufLen=BUFFER_MAX_SIZE;
|
||||
ZeroMemory(recvBuffer,recvBufLen);
|
||||
|
||||
dataBuf=new char[playerDataSize+1];
|
||||
dataBuf[0]=1;
|
||||
//ZeroMemory(b,sizeof(buffer));
|
||||
//----------------------
|
||||
// Initialize Winsock
|
||||
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
|
||||
if (iResult != NO_ERROR) {
|
||||
printf("WSAStartup failed with error: %d\n", iResult);
|
||||
}
|
||||
|
||||
|
||||
|
||||
addrSize=sizeof(sockaddr_in);
|
||||
connectStatus=false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
bool SocketClient::sendUserData()
|
||||
{
|
||||
//memcpy(dataBuf+1,&playerContPtr->getPlayerData(),playerDataSize);
|
||||
//return sendData(dataBuf, playerDataSize+1);
|
||||
printf("NOT YET IMPLEMENTED");
|
||||
return false;
|
||||
}
|
||||
|
||||
bool SocketClient::sendUserData(char* data, int size)
|
||||
{
|
||||
memcpy(dataBuf+1,data,size);
|
||||
return sendDataUDP(dataBuf, size+1);
|
||||
}
|
||||
|
||||
bool SocketClient::sendMessage(std::string msg)
|
||||
{
|
||||
if (msg[0]=='/')
|
||||
{
|
||||
//Server command
|
||||
msg[0]=2;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
//Chat message
|
||||
msg='1'+msg;
|
||||
msg[0]=3;
|
||||
}
|
||||
return sendDataUDP(msg.c_str(), (int)msg.size());
|
||||
}
|
||||
|
||||
bool SocketClient::closeConnection()
|
||||
{
|
||||
connectStatus=false;
|
||||
Sleep(5);
|
||||
//Give the threads 5 ms to quit themselves before terminating them
|
||||
DWORD eCode=0;
|
||||
TerminateThread(threadhandle[0], eCode);
|
||||
TerminateThread(threadhandle[1], eCode);
|
||||
//---------------------------------------------
|
||||
// When the application is finished sending, close the socket.
|
||||
setupStatus=false;
|
||||
printf("Finished sending. Closing socket.\n");
|
||||
iResult = closesocket(connUDP);
|
||||
if (iResult == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"closesocket failed with error: %d\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
//---------------------------------------------
|
||||
// Clean up and quit.
|
||||
printf("Exiting.\n");
|
||||
WSACleanup();
|
||||
return true;
|
||||
}
|
||||
|
||||
void SocketClient::receiveDataThreadV(SocketClient* ptr)
|
||||
{
|
||||
while(true)
|
||||
{
|
||||
ptr->recvBufLen=recvfrom(ptr->connUDP, ptr->recvBuffer, BUFFER_MAX_SIZE, 0, (SOCKADDR *) & ptr->UDPsendAddr, &ptr->addrSize);
|
||||
if (ptr->recvBufLen == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"recv failed with error %d\n", WSAGetLastError());
|
||||
}
|
||||
//ptr->buffer[ptr->iResult]='\0';
|
||||
else
|
||||
ptr->parseReceivedData();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void SocketClient::receiveDataWaitOnResponse()
|
||||
{
|
||||
recvBufLen=recvfrom(connUDP, recvBuffer, BUFFER_MAX_SIZE, 0, (SOCKADDR *) & UDPsendAddr, &addrSize);
|
||||
if (recvBufLen == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"recv failed with error %d\n", WSAGetLastError());
|
||||
}
|
||||
//buffer[iResult]='\0';
|
||||
else
|
||||
parseReceivedData();
|
||||
}
|
||||
|
||||
void SocketClient::sendDataThreadV(SocketClient* ptr)
|
||||
{
|
||||
printf("NOT YET IMPLEMENTED");
|
||||
/*while(ptr->connectStatus)
|
||||
{
|
||||
memcpy(ptr->dataBuf+1,&ptr->playerContPtr->getPlayerData(),playerDataSize);
|
||||
ptr->sendData(ptr->dataBuf, playerDataSize+1);
|
||||
Sleep(ptr->sendDelayMS);
|
||||
}*/
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,147 +0,0 @@
|
|||
#pragma once
|
||||
//Start by defining unicode
|
||||
//#ifndef UNICODE
|
||||
//#define UNICODE
|
||||
//#endif
|
||||
//defining WIN32_LEAN_AND_MEAN this early is REQUIRED if you want to avoid a certain winsock error.
|
||||
//#define WIN32_LEAN_AND_MEAN
|
||||
//#define NOMINMAX
|
||||
//#include
|
||||
//#include "GameClassExample.h"
|
||||
//These includes are required for winsock
|
||||
#include "Network.h"
|
||||
//#include <winsock2.h>
|
||||
//#include <Ws2tcpip.h>
|
||||
//#include <stdio.h>
|
||||
//#include <windows.h>
|
||||
//#include "OysterMath.h"
|
||||
//These are optional includes for various useful features
|
||||
#include <time.h>
|
||||
#include <string>
|
||||
#include <ctime>
|
||||
#include <iostream>
|
||||
|
||||
//ws2_32.lib is a lib file the linker requires for winsock compilation
|
||||
#pragma comment(lib, "Ws2_32.lib")
|
||||
|
||||
//constants used by the socket client to avoid hard coding and/or mass variable declaration
|
||||
const short TCPSendPort = 11110;
|
||||
const short TCPRecvPort = 11111;
|
||||
const short UDPSendPort = 11000;
|
||||
const short UDPRecvPort = 11001;
|
||||
const int BUFFER_MAX_SIZE = 4096;
|
||||
|
||||
enum ConnectionStatus
|
||||
{
|
||||
OFFLINE,
|
||||
ONLINE_MAINMENU,
|
||||
ONLINE_QUEUEING,
|
||||
ONLINE_INLOBBY,
|
||||
ONLINE_INGAME
|
||||
};
|
||||
class SocketClient
|
||||
{
|
||||
private:
|
||||
HANDLE threadhandle[2];
|
||||
int sendDelayMS;
|
||||
|
||||
//2 bools used to verify the activation of the client so threads can't start too early
|
||||
ConnectionStatus connStatus;
|
||||
bool setupStatus;
|
||||
bool connectStatus;
|
||||
|
||||
//iResult is used to check error codes
|
||||
int iResult;
|
||||
//wsaData records error messages and errors which winsock might encounter
|
||||
WSADATA wsaData;
|
||||
|
||||
//Main socket
|
||||
SOCKET connUDP;
|
||||
SOCKET connTCP;
|
||||
|
||||
//Addresses used for data transfer
|
||||
sockaddr_in TCPrecvAddr;
|
||||
sockaddr_in TCPsendAddr;
|
||||
//UDPrecvAddr marks the port and IP adress the server is supposed to return data to.
|
||||
sockaddr_in UDPrecvAddr;
|
||||
//UDPsendAddr marks which IP and port the client is supposed to send data to.
|
||||
sockaddr_in UDPsendAddr;
|
||||
//size of a sockaddr_in. This might as well be a constant, but i'm keeping it in the class for performance reasons.
|
||||
int addrSize;
|
||||
|
||||
//buffer which is filled when data receive happens.
|
||||
char* recvBuffer;
|
||||
//this variable tracks the buffer length.
|
||||
int recvBufLen;
|
||||
|
||||
//dataBuf is a buffer solely for sending your own user data. It never changes size in order to increase performance.
|
||||
//char* sendBuffer;
|
||||
//int sendBufLen;
|
||||
//PlayerStruct tmpPlayer;
|
||||
char* dataBuf;
|
||||
int playerDataSize;
|
||||
public:
|
||||
void setPlayerDataSize(int pds){playerDataSize=pds;}
|
||||
//Constructor
|
||||
SocketClient();
|
||||
|
||||
//Initiation for sockets.
|
||||
bool init(int listenPort);
|
||||
bool initTCPSocket(int listenPort);
|
||||
bool initUDPSocket(int listenPort);
|
||||
//Connects to a server of a user-defined IP. Can only be called after an initXSocket has gone through.
|
||||
//The 2 remaining variables are init data and size of said data. Currently username.
|
||||
bool connectToIP(const char* ip, int listenPort, char* initData, int initDataSize);
|
||||
//sends an undefined data type of (variable#2) size to the server.
|
||||
bool sendDataUDP(const char*, int);
|
||||
bool sendDataTCP(const char*, int);
|
||||
//sends a text string to the server.
|
||||
bool sendMessage(std::string str);
|
||||
bool sendServerMessage(std::string str);
|
||||
//sends user data to the server
|
||||
bool sendUserData();
|
||||
bool sendUserData(char* data, int size);
|
||||
|
||||
//Closes connection, kills off the socket.
|
||||
bool closeConnection();
|
||||
|
||||
//Simple ifBoolIsTrue checks
|
||||
bool isReady() const {return setupStatus;}
|
||||
bool isConnected() const {return connectStatus;}
|
||||
void receiveDataWaitOnResponse();
|
||||
//Sends data periodically
|
||||
static void sendDataThreadV(SocketClient* ptr);
|
||||
//Receive loop. This is event-based and is on its own thread.
|
||||
static void receiveDataThreadV(SocketClient* ptr);
|
||||
//Once data is received, it calls on the parseReceivedData function.
|
||||
void parseReceivedData();
|
||||
//void parseReceivedKeyframe();
|
||||
//If an event is called from the server, this function will be called.
|
||||
void parseReceivedEvent();
|
||||
void parseReceivedEffect();
|
||||
//It is then sent to one of the following functions based on the first byte of the buffer.
|
||||
|
||||
//Servermessage
|
||||
void parseServermessage();
|
||||
//single user data
|
||||
void parseData();
|
||||
//string (character data)
|
||||
void parseMessage();
|
||||
//init data which sets the start position etc of all characters.
|
||||
void parseLobbyInitData();
|
||||
void parseGameInitData();
|
||||
void parseRenderData();
|
||||
|
||||
bool startReceiveThread();
|
||||
bool startSendDataThread();
|
||||
void setSendDelay(int ms){sendDelayMS=ms;}
|
||||
|
||||
//virtual functions
|
||||
virtual void receiveGameInitData(char*)=0;
|
||||
virtual void receiveLobbyInitData(char*, int)=0;
|
||||
virtual void receivePlayerUpdate(char*, int)=0;
|
||||
virtual void receiveRenderData(char*, int)=0;
|
||||
virtual void receiveEffectData(char*, int)=0;
|
||||
virtual void receiveConnStatus(ConnectionStatus)=0;
|
||||
virtual void receiveEvent(char*)=0;
|
||||
};
|
|
@ -0,0 +1,5 @@
|
|||
int main()
|
||||
{
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -1,113 +0,0 @@
|
|||
#include "Game.h"
|
||||
Game::Game()
|
||||
{
|
||||
playerCount=0;
|
||||
started=false;
|
||||
for (int i=0; i<MUTEX_COUNT; i++)
|
||||
{
|
||||
mutex[i] = CreateMutex(
|
||||
NULL, // default security attributes
|
||||
FALSE, // initially not owned
|
||||
NULL); // unnamed mutex
|
||||
|
||||
if (mutex == NULL)
|
||||
{
|
||||
printf("CreateMutex error: %d\n", GetLastError());
|
||||
}
|
||||
}
|
||||
for(int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
ready[i]=false;
|
||||
}
|
||||
}
|
||||
/*bool Game::checkMoveValidity(ClientToServerUpdateData plr)
|
||||
{
|
||||
|
||||
if (false)
|
||||
{
|
||||
players[plr.pid]=plr;
|
||||
return true;
|
||||
} else
|
||||
{
|
||||
//The package that arrived is an earlier version than the last one.
|
||||
//Ignore the position data, but still check actions and such to make
|
||||
//sure that you don't miss a key press.
|
||||
|
||||
//For example, if the fire button is true in this package but false now,
|
||||
//the ship should still shoot once.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Float4x4 Game::getPlayerPos(int id)
|
||||
{
|
||||
WaitForSingleObject(mutex[0], INFINITE);
|
||||
Float4x4 tmp=players[id].position;
|
||||
ReleaseMutex(mutex[0]);
|
||||
return tmp;
|
||||
}
|
||||
void Game::setPlayerPos(int id, Float4x4 pos)
|
||||
{
|
||||
WaitForSingleObject(mutex[0], INFINITE);
|
||||
players[id].position=pos;
|
||||
ReleaseMutex(mutex[0]);
|
||||
}
|
||||
ClientToServerUpdateData Game::getPlayerData(int id)
|
||||
{
|
||||
WaitForSingleObject(mutex[0], INFINITE);
|
||||
ClientToServerUpdateData tmp=players[id];
|
||||
ReleaseMutex(mutex[0]);
|
||||
return tmp;
|
||||
}
|
||||
void Game::setPlayerData(int id, ClientToServerUpdateData ps)
|
||||
{
|
||||
WaitForSingleObject(mutex[0], INFINITE);
|
||||
players[id]=ps;
|
||||
ReleaseMutex(mutex[0]);
|
||||
}*/
|
||||
void Game::initGame(std::vector<User> usr, int nrOfPlayers)
|
||||
{
|
||||
/*for (int i=0; i<nrOfPlayers; i++)
|
||||
{
|
||||
users[i]=&usr[i];
|
||||
}*/
|
||||
Oyster::Math::Float4x4 initvariable=Oyster::Math::Float4x4::identity;
|
||||
initvariable.v[3].x=50;
|
||||
for (unsigned int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
initvariable.v[3].x=(Float)200*i;
|
||||
//players[i].position=initvariable;
|
||||
}
|
||||
//players[1].position.m11=0.1f;
|
||||
//players[1].position.m22=0.1f;
|
||||
//players[1].position.m33=0.1f;
|
||||
}
|
||||
GameInitData Game::getInitData()
|
||||
{
|
||||
//Later getInitData will need to receive a user id to set it up 100%.
|
||||
//That way, this is the only function that needs to be called in order to connect(or reconnect) to a game.
|
||||
GameInitData init;
|
||||
|
||||
init.pid=0;
|
||||
for (unsigned int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
init.player[i].pid=i;
|
||||
init.player[i].teamid=i%2;
|
||||
//init.player[i].position=getPlayerPos(i);
|
||||
//users[i]->setGame(2);
|
||||
//init.players[i]=players[i];
|
||||
}
|
||||
return init;
|
||||
}
|
||||
void Game::addUser(int uid)
|
||||
{
|
||||
userID[playerCount++]=uid;
|
||||
}
|
||||
bool Game::startGame()
|
||||
{
|
||||
started=true;
|
||||
return started;
|
||||
}
|
||||
void Game::update(float dt)
|
||||
{
|
||||
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
#pragma once
|
||||
#ifndef GAME_H
|
||||
#define GAME_H
|
||||
#include "User.h"
|
||||
#include "ServerInclude.h"
|
||||
const int MUTEX_COUNT =2;
|
||||
//Mutex #0=playerPos setGet
|
||||
//Mutex #1=
|
||||
|
||||
//#include "Session.h"
|
||||
|
||||
class Game
|
||||
{
|
||||
private:
|
||||
bool started;
|
||||
//ClientToServerUpdateData players[PLAYER_MAX_COUNT];
|
||||
User* users[PLAYER_MAX_COUNT];
|
||||
int userID[PLAYER_MAX_COUNT];
|
||||
bool ready[PLAYER_MAX_COUNT];
|
||||
int playerCount;
|
||||
|
||||
//Tracks which ship each user has
|
||||
int shipID[PLAYER_MAX_COUNT];
|
||||
HANDLE mutex[MUTEX_COUNT];
|
||||
//::Game::Session *session;
|
||||
int sessionID;
|
||||
public:
|
||||
//Will reset all data
|
||||
//playerIDs is an array of int which points toward each users connection.
|
||||
void setReady(int pid, bool rdy){ready[pid]=rdy;}
|
||||
bool allReady(){for (int i=0; i<playerCount; i++){if(ready[i]==false)return false;}return true;}
|
||||
void initGame(std::vector<User> players, int nrOfPlayers);
|
||||
GameInitData getInitData();
|
||||
bool startGame();
|
||||
bool isStarted(){return started;}
|
||||
Game();
|
||||
//Float4x4 getPlayerPos(int id);
|
||||
//void setPlayerPos(int id, Float4x4 pos);
|
||||
//bool checkMoveValidity(ClientToServerUpdateData plr);
|
||||
//ClientToServerUpdateData getPlayerData(int id);
|
||||
//void setPlayerData(int id, ClientToServerUpdateData ps);
|
||||
|
||||
int getPlayerCount() {return playerCount;}
|
||||
int getUserID(int i) {return userID[i];}
|
||||
|
||||
void initLUA(char* file);
|
||||
void update(float dt);
|
||||
void addUser(int uid);
|
||||
void removeUser(int uid){playerCount--;}
|
||||
};
|
||||
#endif
|
|
@ -1,73 +0,0 @@
|
|||
#include "Lobby.h"
|
||||
|
||||
Lobby::Lobby()
|
||||
{
|
||||
timerStarted=false;
|
||||
nrUsers=0;
|
||||
timerMutex = CreateMutex(
|
||||
NULL, // default security attributes
|
||||
FALSE, // initially not owned
|
||||
NULL); // unnamed mutex
|
||||
|
||||
if (timerMutex == NULL)
|
||||
{
|
||||
printf("CreateMutex error: %d\n", GetLastError());
|
||||
}
|
||||
for(int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
userData[i].pid=i;
|
||||
userData[i].shipID=0;
|
||||
userData[i].usrName[0]='\0';
|
||||
//userData[i].usrName="Player";
|
||||
//userData[i].usrName+=(char)i;
|
||||
}
|
||||
}
|
||||
void Lobby::removeUser()
|
||||
{
|
||||
}
|
||||
void Lobby::addUser(User usr, int i)
|
||||
{
|
||||
userID[nrUsers]=i;
|
||||
userData[nrUsers].setName(usr.getUsername().c_str());
|
||||
//userData[nrUsers].shipID=1;
|
||||
nrUsers++;
|
||||
}
|
||||
void Lobby::updateUserData(LobbyUserStruct data)
|
||||
{
|
||||
userData[data.pid]=data;
|
||||
}
|
||||
LobbyInitData Lobby::getLobbyInitData()
|
||||
{
|
||||
LobbyInitData data;
|
||||
data.playerCount=nrUsers;
|
||||
for(int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
data.players[i]=userData[i];
|
||||
}
|
||||
return data;
|
||||
}
|
||||
void Lobby::startLobbyCountdown(float seconds)
|
||||
{
|
||||
WaitForSingleObject(timerMutex, INFINITE);
|
||||
countdownLimit=seconds;
|
||||
countdownTimer.reset();
|
||||
countdownTimer.start();
|
||||
timerStarted=true;
|
||||
ReleaseMutex(timerMutex);
|
||||
}
|
||||
float Lobby::timeLeft()
|
||||
{
|
||||
WaitForSingleObject(timerMutex, INFINITE);
|
||||
countdownTimer.tick();
|
||||
if (!timerStarted)
|
||||
return -1;
|
||||
else
|
||||
{
|
||||
float timeLeft=countdownLimit-countdownTimer.getGameTime();
|
||||
if(timeLeft>0)
|
||||
return timeLeft;
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
ReleaseMutex(timerMutex);
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
#include "ServerInclude.h"
|
||||
#include "User.h"
|
||||
#ifndef LOBBY_H
|
||||
#define LOBBY_H
|
||||
class Lobby
|
||||
{
|
||||
private:
|
||||
int nrUsers;
|
||||
int userID[PLAYER_MAX_COUNT];
|
||||
ServerTimer countdownTimer;
|
||||
float countdownLimit;
|
||||
LobbyUserStruct userData[PLAYER_MAX_COUNT];
|
||||
bool timerStarted;
|
||||
HANDLE timerMutex;
|
||||
public:
|
||||
Lobby();
|
||||
void addUser(User usr, int i);
|
||||
int getUserID(int i) const {return userID[i];}
|
||||
int getNrPlayers() const {return nrUsers;}
|
||||
void removeUser();
|
||||
void updateUserData(LobbyUserStruct);
|
||||
LobbyInitData getLobbyInitData();
|
||||
void startLobbyCountdown(float seconds);
|
||||
float timeLeft();
|
||||
|
||||
};
|
||||
#endif
|
|
@ -24,26 +24,26 @@
|
|||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v110</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v110</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v110</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v110</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
|
@ -137,26 +137,6 @@
|
|||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="Game.cpp" />
|
||||
<ClCompile Include="Lobby.cpp" />
|
||||
<ClCompile Include="Servercore.cpp" />
|
||||
<ClCompile Include="ServerDataHandler.cpp" />
|
||||
<ClCompile Include="ServerMain.cpp" />
|
||||
<ClCompile Include="ServerTCPSpecific.cpp" />
|
||||
<ClCompile Include="ServerTimer.cpp" />
|
||||
<ClCompile Include="ServerUDPSpecific.cpp" />
|
||||
<ClCompile Include="SessionRelatedFunctions.cpp" />
|
||||
<ClCompile Include="User.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="Game.h" />
|
||||
<ClInclude Include="Lobby.h" />
|
||||
<ClInclude Include="ServerInclude.h" />
|
||||
<ClInclude Include="ServerTimer.h" />
|
||||
<ClInclude Include="SocketServer.h" />
|
||||
<ClInclude Include="User.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Misc\Misc.vcxproj">
|
||||
<Project>{2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee}</Project>
|
||||
|
@ -168,6 +148,9 @@
|
|||
<Project>{c5aa09d0-6594-4cd3-bd92-1d380c7b3b50}</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="main.cpp" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
|
|
@ -15,55 +15,8 @@
|
|||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="Game.cpp">
|
||||
<ClCompile Include="main.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="Lobby.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="Servercore.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ServerDataHandler.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ServerMain.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ServerTCPSpecific.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ServerTimer.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ServerUDPSpecific.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="SessionRelatedFunctions.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="User.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="Game.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Lobby.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="ServerInclude.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="ServerTimer.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="SocketServer.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="User.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
</Project>
|
|
@ -1,219 +0,0 @@
|
|||
#include "SocketServer.h"
|
||||
|
||||
|
||||
|
||||
void SocketServer::parseReceivedData(int threadID/*char* data, int size*/)
|
||||
{
|
||||
bool test=false;
|
||||
for(unsigned int i=0; i<users.size(); i++)
|
||||
{
|
||||
if(memcmp(&connData[threadID].srcAddr, &users[i].getAddr(), sizeof(sockaddr_in)) != 0)
|
||||
{
|
||||
//User i has not sent the data.
|
||||
test=false;
|
||||
}
|
||||
else
|
||||
{
|
||||
//Found the user which sent the data
|
||||
test=true;
|
||||
switch (connData[threadID].buffer[0])
|
||||
{
|
||||
case 1://It's data
|
||||
if(users[i].isIngame()) parseData(i, users[i].getGame(), threadID);
|
||||
break;
|
||||
case 2://It's a user-entered command
|
||||
parseServercommand(i, threadID);
|
||||
break;
|
||||
case 3://It's a chat message
|
||||
parseMessage(i, threadID);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if(!test)
|
||||
{
|
||||
//User does not exist yet
|
||||
//This is temporary until i have a proper login process in place
|
||||
addUser(threadID);
|
||||
}
|
||||
}
|
||||
|
||||
void SocketServer::addUser(int threadID)
|
||||
{
|
||||
printf("UDP adding user.\n");
|
||||
User usr=User((int)users.size(),connData[threadID].srcAddr);
|
||||
connData[threadID].buffer[connData[threadID].dataSize]='\0';
|
||||
usr.setUsername(connData[threadID].buffer);
|
||||
users.push_back(usr);
|
||||
sendData(((int)users.size())-1, "\4connected",10);
|
||||
std::string asd=users[users.size()-1].getUsername();
|
||||
printf("Username:%s, IP:%s\n",users[users.size()-1].getUsername().c_str(), inet_ntoa(users[users.size()-1].getAddr().sin_addr));
|
||||
}
|
||||
void SocketServer::AddUser(ConnThreadData* data)
|
||||
{
|
||||
printf("TCP adding user.\n");
|
||||
User usr=User((int)users.size(),data->srcAddr);
|
||||
data->buffer[data->dataSize]='\0';
|
||||
usr.setUsername(data->buffer);
|
||||
users.push_back(usr);
|
||||
sendData(((int)users.size())-1, "\4connected",10);
|
||||
std::string asd=users[users.size()-1].getUsername();
|
||||
printf("Username:%s, IP:%s\n",users[users.size()-1].getUsername().c_str(), inet_ntoa(users[users.size()-1].getAddr().sin_addr));
|
||||
}
|
||||
void SocketServer::removeUser(int id)
|
||||
{
|
||||
games[users[id].getGame()].removeUser(id);
|
||||
users.erase(users.begin()+id);
|
||||
}
|
||||
void SocketServer::parseServercommand(int pid, int threadID)
|
||||
{
|
||||
connData[threadID].buffer[connData[threadID].dataSize]='\0';
|
||||
wprintf(L"User %d sent a server command.\n", pid);
|
||||
printf("The command is the following:%s.\n", connData[threadID].buffer+1);
|
||||
std::vector<std::string> list=splitString(connData[threadID].buffer+1, ' ');
|
||||
bool validcommand=false;
|
||||
if(list.size()==0)
|
||||
{
|
||||
//Ignore case 1, to avoid vector subscript out of range errors
|
||||
}
|
||||
//First variable: Command
|
||||
else if(!list[0].compare(" "))
|
||||
{
|
||||
//Add rest ignore cases here
|
||||
}
|
||||
else if(!list[0].compare("help"))
|
||||
{
|
||||
validcommand=true;
|
||||
}
|
||||
//else if(!list[0].compare("startgame"))
|
||||
//{
|
||||
//validcommand=true;
|
||||
//Do more than just sending init data here
|
||||
//sendInitData();
|
||||
//}
|
||||
else if (!list[0].compare("exit"))
|
||||
{
|
||||
validcommand=true;
|
||||
//User #pid needs to be removed here, and data needs to be sorted accordingly.
|
||||
}
|
||||
else if (!list[0].compare("qst"))
|
||||
{
|
||||
validcommand=true;
|
||||
if (users[pid].getState()==ONLINE)
|
||||
{
|
||||
sendData(pid, "\4qst",4);
|
||||
users[pid].setState(ONLINE_QUEUEING);
|
||||
}
|
||||
}
|
||||
else if (!list[0].compare("qed"))
|
||||
{
|
||||
validcommand=true;
|
||||
if (users[pid].getState()==ONLINE_QUEUEING)
|
||||
{
|
||||
sendData(pid, "\4qed",4);
|
||||
users[pid].setState(ONLINE);
|
||||
}
|
||||
}
|
||||
else if (!list[0].compare("rdy"))
|
||||
{
|
||||
if (users[pid].getState()==ONLINE_INGAME)
|
||||
{
|
||||
games[users[pid].getGame()].setReady(pid, true);
|
||||
}
|
||||
}
|
||||
else if (!list[0].compare("dc"))
|
||||
{
|
||||
validcommand=true;
|
||||
printf("User %s (ID:%d) has disconnected.",users[pid].getUsername().c_str(), pid);
|
||||
users[pid].setState(OFFLINE);
|
||||
removeUser(pid);
|
||||
//Tell games that he might be in here taht he's down
|
||||
//users.erase(users.begin()
|
||||
}
|
||||
else if((!list[0].compare("w")||!list[0].compare("whisper")||!list[0].compare("msg")) && list.size()>2)
|
||||
{
|
||||
validcommand=true;
|
||||
for(unsigned int i=0; i<users.size(); i++)
|
||||
{
|
||||
//Second variable: Target user
|
||||
if (!list[1].compare(users[i].getUsername()))
|
||||
{
|
||||
//Other variables: Text message.
|
||||
//The +3 is for the 2 spaces and the first /. Calculating the start pos of the message.
|
||||
int startloc=(int)(list[0].length()+list[1].length())+3;
|
||||
//std::string msg="\3[Whisper] "+users[pid].getUsername()+":"+(connData[threadID].buffer+startloc);
|
||||
//msg+=users[pid].getUsername()
|
||||
//sendData(i,msg.c_str(), msg.length());
|
||||
}
|
||||
}
|
||||
}
|
||||
else if(!list[0].compare("setname"))
|
||||
{
|
||||
if(list.size()>1)
|
||||
{
|
||||
users[pid].setUsername(list[1]);
|
||||
//list[1]="\3Your username has been changed to "+list[1];
|
||||
//sendData(pid,list[1].c_str(), list[1].length());
|
||||
validcommand=true;
|
||||
}
|
||||
}
|
||||
if(!validcommand)
|
||||
{
|
||||
int a=0;
|
||||
//sendData(pid, "\3Invalid server command.", 24);
|
||||
//Tell user that the server command was invalid
|
||||
}
|
||||
}
|
||||
void SocketServer::parseData(int pid, int gid, int threadID)
|
||||
{
|
||||
memcpy(&connData[threadID].tmpdata,connData[threadID].buffer+1,CLIENT_PLAYER_DATA_SIZE);
|
||||
//No old packets
|
||||
if (users[pid].getLastUpdate()<connData[threadID].tmpdata.updateCount)
|
||||
{
|
||||
users[pid].setLastUpdate(connData[threadID].tmpdata.updateCount);
|
||||
users[pid].setLastUpdateData(connData[threadID].tmpdata);
|
||||
ControlPlayer(session->accessPlayer(pid),connData[threadID].tmpdata);
|
||||
}
|
||||
}
|
||||
void SocketServer::parseMessage(int pid, int threadID)
|
||||
{
|
||||
std::string message;
|
||||
message="\3[Chat] "+users[pid].getUsername()+": "+(connData[threadID].buffer+1);
|
||||
sendData(-1,message.c_str(), (int)message.length());
|
||||
}
|
||||
void SocketServer::sendInitData(int gid)
|
||||
{
|
||||
GameInitData init=games[gid].getInitData();
|
||||
//int test=session->getNumPlayers(); // getNumPlayers is removed
|
||||
for (int i=0; i<PLAYER_MAX_COUNT; i++)
|
||||
{
|
||||
init.player[i].position=session->accessPlayer(i).getOrientation();
|
||||
}
|
||||
char* gd=new char[sizeof(init)+1];
|
||||
gd[0]=2;
|
||||
for (int i=0; i<games[gid].getPlayerCount(); i++)
|
||||
{
|
||||
int c=sizeof(init);
|
||||
init.pid=i;
|
||||
memcpy(gd+1,&init, sizeof(init));
|
||||
sendData(games[gid].getUserID(i), gd, sizeof(init)+1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void SocketServer::sendLobbyInitData(int lid)
|
||||
{
|
||||
LobbyInitData init=lobby.getLobbyInitData();
|
||||
init.timer=LOBBY_WAIT_TIME;
|
||||
int c=sizeof(init);
|
||||
char* gd=new char[c+1];
|
||||
gd[0]=5;
|
||||
for (int i=0; i<lobby.getNrPlayers(); i++)
|
||||
{
|
||||
init.pid=i;
|
||||
memcpy(gd+1,&init, c);
|
||||
sendData(lobby.getUserID(i), gd, c+1);
|
||||
}
|
||||
}
|
|
@ -1,19 +0,0 @@
|
|||
#include "Network.h"
|
||||
#pragma once
|
||||
#ifdef _DEBUG
|
||||
#include <crtdbg.h>
|
||||
#define DEBUG_NEW new(_NORMAL_BLOCK ,__FILE__, __LINE__)
|
||||
#else
|
||||
#define DEBUG_NEW new
|
||||
#endif
|
||||
|
||||
#include <vector>
|
||||
#include <time.h>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include "OysterMath.h"
|
||||
//#include "Session.h"
|
||||
#include "ServerTimer.h"
|
||||
using namespace Network;
|
||||
|
||||
const float GAME_UPDATEDELAY=1.0f/120.0f;
|
|
@ -1,47 +0,0 @@
|
|||
#include <ctime>
|
||||
#include "SocketServer.h"
|
||||
#include "ServerTimer.h"
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <stdio.h>
|
||||
//#ifdef WINDOWS
|
||||
#include <direct.h>
|
||||
#include "ServerInclude.h"
|
||||
#define GetCurrentDir _getcwd
|
||||
//#else
|
||||
//For other OS than windows; can't be found on
|
||||
//all windows setups so it's commented for now
|
||||
//#include <unistd.h>
|
||||
//#define GetCurrentDir getcwd
|
||||
//#endif
|
||||
|
||||
char* getCurDir()
|
||||
{
|
||||
char* cCurrentPath;
|
||||
cCurrentPath=new char[FILENAME_MAX];
|
||||
int test=sizeof(cCurrentPath);
|
||||
if (!GetCurrentDir(cCurrentPath, FILENAME_MAX))
|
||||
{
|
||||
return "ERROR";
|
||||
}
|
||||
cCurrentPath[FILENAME_MAX - 1] = '\0';
|
||||
return cCurrentPath;
|
||||
}
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
srand((unsigned int)time(0));
|
||||
::Oyster::Game::MoveAble::setDiscreteTimeSlice( GAME_UPDATEDELAY );
|
||||
|
||||
SocketServer server;
|
||||
server.loadMapList("..\\Content\\Maplist.txt");
|
||||
while (!server.isReady());
|
||||
server.startThreads();
|
||||
GameLogic::Object::init("NOT_IMPLEMENTED");
|
||||
server.startGameCreateLoop(50);
|
||||
while(true)
|
||||
{
|
||||
server.updateServers();
|
||||
}
|
||||
server.closeConnection();
|
||||
return 0;
|
||||
}
|
|
@ -1,66 +0,0 @@
|
|||
#include "SocketServer.h"
|
||||
bool SocketServer::initTCPSocket()
|
||||
{
|
||||
//----------------------
|
||||
// Create a SOCKET for listening for incoming connection requests.
|
||||
TCPSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
if (TCPSocket == INVALID_SOCKET) {
|
||||
wprintf(L"TCP socket function failed with error: %ld\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
|
||||
iResult = bind(TCPSocket, (SOCKADDR *) & TCPRecvAddr, addrSize);
|
||||
if (iResult == SOCKET_ERROR) {
|
||||
wprintf(L"TCP bind function failed with error %d\n", WSAGetLastError());
|
||||
iResult = closesocket(TCPSocket);
|
||||
if (iResult == SOCKET_ERROR)
|
||||
wprintf(L"TCP closesocket function failed with error %d\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
DWORD SocketServer::activateTCPConnectLoop(ThreadArguments* tra)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
(tra->ptr)->receiveConnection(tra->threadID);
|
||||
}
|
||||
}
|
||||
void SocketServer::receiveConnection(int threadID)
|
||||
{
|
||||
User tmp;
|
||||
//----------------------
|
||||
// Listen for incoming connection requests
|
||||
// on the created socket
|
||||
if (listen(TCPSocket, SOMAXCONN) == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"listen function failed with error: %d\n", WSAGetLastError());
|
||||
return;
|
||||
}
|
||||
|
||||
printf("Starting TCP connection loop.\n");
|
||||
int a=0;
|
||||
while(a==0)
|
||||
{
|
||||
a=1;
|
||||
tmp.connection=accept(TCPSocket, (struct sockaddr*)&TCPRecvAddr, &addrSize);
|
||||
printf("Accepted a TCP connection from IP %s.\n", inet_ntoa(TCPRecvAddr.sin_addr));
|
||||
tcpData[threadID].dataSize=recv(
|
||||
tmp.connection,
|
||||
tcpData[threadID].buffer,
|
||||
tcpData[threadID].bufLen,
|
||||
0);
|
||||
connData[threadID].buffer[connData[threadID].dataSize]='\0';
|
||||
tmp.setUsername(tcpData[threadID].buffer);
|
||||
if (tcpData[threadID].dataSize == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"TCP recv failed with error %d\n", WSAGetLastError());
|
||||
}
|
||||
printf("TCP Thread #%d received connData from %s\n", threadID, inet_ntoa(tcpData[threadID].srcAddr.sin_addr));
|
||||
//connData[threadID].buffer[connData[threadID].dataSize]='\0';
|
||||
//AddUser(&tcpData[threadID]);
|
||||
//parseReceivedData(threadID);
|
||||
}
|
||||
}
|
|
@ -1,85 +0,0 @@
|
|||
#include "ServerTimer.h"
|
||||
ServerTimer::ServerTimer()
|
||||
:
|
||||
c_SecondsPerCount(0.0),
|
||||
c_DeltaTime(-1.0),
|
||||
c_BaseTime(0),
|
||||
c_PausedTime(0),
|
||||
c_PrevTime(0),
|
||||
c_CurrTime(0),
|
||||
c_Stopped(false)
|
||||
{
|
||||
__int64 countsPerSec;
|
||||
QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec);
|
||||
c_SecondsPerCount =1.0 / (double)countsPerSec;
|
||||
|
||||
QueryPerformanceCounter((LARGE_INTEGER*)&c_PrevTime);
|
||||
}
|
||||
|
||||
void ServerTimer::start()
|
||||
{
|
||||
__int64 p_StartTime;
|
||||
QueryPerformanceCounter((LARGE_INTEGER*)&p_StartTime);
|
||||
if(c_Stopped)
|
||||
{
|
||||
c_PausedTime += (p_StartTime-c_StopTime);
|
||||
c_PrevTime = p_StartTime;
|
||||
c_StopTime = 0;
|
||||
c_Stopped = false;
|
||||
}
|
||||
}
|
||||
__int64 ServerTimer::getTime()
|
||||
{
|
||||
__int64 testInt;
|
||||
return QueryPerformanceCounter((LARGE_INTEGER*)&testInt);
|
||||
return testInt;
|
||||
}
|
||||
|
||||
void ServerTimer::stop()
|
||||
{
|
||||
if(!c_Stopped)
|
||||
{
|
||||
__int64 p_CurrTime;
|
||||
QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime);
|
||||
c_StopTime = p_CurrTime;
|
||||
c_Stopped = true;
|
||||
}
|
||||
}
|
||||
void ServerTimer::reset()
|
||||
{
|
||||
__int64 p_CurrTime;
|
||||
QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime);
|
||||
c_BaseTime = p_CurrTime;
|
||||
c_PrevTime = p_CurrTime;
|
||||
c_StopTime = 0;
|
||||
c_Stopped = false;
|
||||
}
|
||||
void ServerTimer::tick()
|
||||
{
|
||||
if (c_Stopped)
|
||||
{
|
||||
c_DeltaTime= 0.0;
|
||||
return;
|
||||
}
|
||||
__int64 p_CurrTime;
|
||||
QueryPerformanceCounter((LARGE_INTEGER*)&p_CurrTime);
|
||||
c_CurrTime=p_CurrTime;
|
||||
|
||||
c_DeltaTime=(c_CurrTime-c_PrevTime)*c_SecondsPerCount;
|
||||
c_PrevTime=c_CurrTime;
|
||||
if(c_DeltaTime<0.0) c_DeltaTime=0.0;
|
||||
}
|
||||
float ServerTimer::getGameTime() const
|
||||
{
|
||||
if(c_Stopped)
|
||||
{
|
||||
return (float)((c_StopTime-c_BaseTime)*c_SecondsPerCount);
|
||||
} else
|
||||
{
|
||||
return (float)(((c_CurrTime-c_PausedTime)-c_BaseTime)*c_SecondsPerCount);
|
||||
}
|
||||
}
|
||||
float ServerTimer::getDeltaTime() const
|
||||
{
|
||||
return (float)c_DeltaTime;
|
||||
}
|
|
@ -1,25 +0,0 @@
|
|||
#include "ServerInclude.h"
|
||||
#ifndef _GAME_TIMER_H
|
||||
#define _GAME_TIMER_H
|
||||
class ServerTimer
|
||||
{
|
||||
private:
|
||||
double c_SecondsPerCount;
|
||||
double c_DeltaTime;
|
||||
__int64 c_BaseTime;
|
||||
__int64 c_PausedTime;
|
||||
__int64 c_StopTime;
|
||||
__int64 c_PrevTime;
|
||||
__int64 c_CurrTime;
|
||||
bool c_Stopped;
|
||||
public:
|
||||
ServerTimer();
|
||||
__int64 getTime();
|
||||
void start();
|
||||
void stop();
|
||||
void reset();
|
||||
void tick();
|
||||
float getGameTime() const;
|
||||
float getDeltaTime() const;
|
||||
};
|
||||
#endif
|
|
@ -1,55 +0,0 @@
|
|||
#include "SocketServer.h"
|
||||
bool SocketServer::initUDPSocket()
|
||||
{
|
||||
//---------------------------------------------
|
||||
// Create a socket for sending data
|
||||
UDPSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||
if (UDPSocket == INVALID_SOCKET) {
|
||||
wprintf(L"UDP socket failed with error: %ld\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
//---------------------------------------------
|
||||
// Bind socket to IP
|
||||
iResult = bind(UDPSocket, (SOCKADDR *) & UDPRecvAddr, addrSize);
|
||||
if (iResult == SOCKET_ERROR) {
|
||||
wprintf(L"UDP bind failed with error: %d\n", WSAGetLastError());
|
||||
closesocket(UDPSocket);
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
DWORD SocketServer::activateUDPReceiveLoop(ThreadArguments* tra)
|
||||
{
|
||||
(tra->ptr)->serverUDPReceiveLoopActive=true;//weird crash //PAR
|
||||
(tra->ptr)->receiveDataUDP(tra->threadID);
|
||||
return 0;
|
||||
}
|
||||
void SocketServer::stopUDPReceiveLoops()
|
||||
{
|
||||
serverUDPReceiveLoopActive=false;
|
||||
WaitForMultipleObjects(NR_CONNECTTHREADS, udpDataHandle, true, INFINITE);
|
||||
printf("All UDP data recv threads stopped.\n");
|
||||
}
|
||||
void SocketServer::receiveDataUDP(int threadID)
|
||||
{
|
||||
while(serverUDPReceiveLoopActive)
|
||||
{
|
||||
connData[threadID].dataSize=recvfrom(
|
||||
UDPSocket,
|
||||
connData[threadID].buffer,
|
||||
connData[threadID].bufLen,
|
||||
0,
|
||||
(SOCKADDR *)&connData[threadID].srcAddr,
|
||||
&addrSize);
|
||||
if (connData[threadID].dataSize == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"recvfrom failed with error %d\n", WSAGetLastError());
|
||||
}
|
||||
//printf("Thread #%d received data from %s\n", threadID, inet_ntoa(connData[threadID].srcAddr.sin_addr));
|
||||
//connData[threadID].buffer[connData[threadID].dataSize]='\0';
|
||||
else
|
||||
parseReceivedData(threadID);
|
||||
}
|
||||
}
|
|
@ -1,420 +0,0 @@
|
|||
#include "SocketServer.h"
|
||||
#include <fstream>
|
||||
bool SocketServer::loadMapList(char* maploc)
|
||||
{
|
||||
::std::string workDir;
|
||||
::Utility::String::extractDirPath( workDir, maploc, '\\' );
|
||||
|
||||
//maploc is the filename of the list which contains all maps
|
||||
//load all map file names into the server, but don't load the maps themselves.
|
||||
std::ifstream file;
|
||||
file.open(maploc);
|
||||
if (!file.is_open())
|
||||
return false;
|
||||
::std::string str;
|
||||
while(!file.eof())
|
||||
{
|
||||
::std::getline( file, str );
|
||||
maps.push_back( workDir + str );
|
||||
}
|
||||
|
||||
/*
|
||||
maps.push_back("map1test.map");
|
||||
maps.push_back("map2 test.map");
|
||||
*/
|
||||
return true;
|
||||
}
|
||||
bool SocketServer::LoadInitData(char* maploc)
|
||||
{
|
||||
std::vector<std::string> cont;
|
||||
char* in=new char[100];
|
||||
std::ifstream ifs;
|
||||
ifs.open(maploc);
|
||||
if(!ifs.is_open())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
while(!ifs.eof())
|
||||
{
|
||||
ifs.getline(in, 100);
|
||||
cont=splitString(in, '=');
|
||||
if (cont.size()==2)
|
||||
{
|
||||
if(!strcmp("nr_players_per_session", cont[0].c_str()))
|
||||
{
|
||||
playersPerSessionCount=atoi(cont[1].c_str());
|
||||
}
|
||||
else if(!strcmp("nr_kills_to_win", cont[0].c_str()))
|
||||
{
|
||||
killsRequiredPerSession=atoi(cont[1].c_str());
|
||||
}
|
||||
else if(!strcmp("match_type", cont[0].c_str()))
|
||||
{
|
||||
//Isn't used
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
ifs.close();
|
||||
}
|
||||
SocketServer::~SocketServer()
|
||||
{
|
||||
serverTCPConnectionLoopActive=false;
|
||||
serverUDPReceiveLoopActive=false;
|
||||
serverTCPReceiveLoopActive=false;
|
||||
for (int i=0; i<NR_CONNECTTHREADS; i++)
|
||||
{
|
||||
delete connData[i].buffer;
|
||||
}
|
||||
for (int i=0; i<NR_SIMULTCPCONNECTS; i++)
|
||||
{
|
||||
delete tcpData[i].buffer;
|
||||
}
|
||||
delete sendGameDataBuffer;
|
||||
delete sendEffectDataBuffer;
|
||||
closeConnection();
|
||||
}
|
||||
void SocketServer::startGameCreateLoop(int delay)
|
||||
{
|
||||
lobbyActive=false;
|
||||
DEBUGCTR=0;
|
||||
if(!serverGameCreationActive)
|
||||
{
|
||||
ThreadArguments tr;
|
||||
tr.ptr=this;
|
||||
tr.threadID=delay;
|
||||
serverGameCreationActive=true;
|
||||
gameCreateHandle=CreateThread(
|
||||
NULL, //Choose default security
|
||||
0, //Default stack size
|
||||
(LPTHREAD_START_ROUTINE)&activateServerGameLoop,
|
||||
//Routine to execute
|
||||
(LPVOID) &tr, //Thread parameter
|
||||
0, //Immediately run the thread
|
||||
0 //Thread Id
|
||||
);
|
||||
if (gameCreateHandle == NULL)
|
||||
{
|
||||
printf("Game creation thread ERROR");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Game creation thread successful\n");
|
||||
Sleep(100);
|
||||
}
|
||||
}
|
||||
}
|
||||
void SocketServer::stopGameCreateLoop()
|
||||
{
|
||||
serverGameCreationActive=false;
|
||||
WaitForSingleObject(gameCreateHandle, INFINITE);
|
||||
printf("Game Creation thread ended.\n");
|
||||
}
|
||||
DWORD SocketServer::activateServerGameLoop(ThreadArguments* tra)
|
||||
{
|
||||
srand((unsigned int)(time(0)));
|
||||
(tra->ptr)->serverGameCreationLoop(tra->threadID);
|
||||
return 0;
|
||||
}
|
||||
bool SocketServer::serverGameCreationLoop(int delay)
|
||||
{ // TODO: Mem access Violoation Crash 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ... delay = -858993460
|
||||
//Mem access violation in a thread can also be caused by failure from something else instead of it,
|
||||
//it still breaks at header even if, for example, server->load or lobby.startLobbyCountdown breaks it
|
||||
//If you get an error here, make sure that isn't the problem.
|
||||
int count;
|
||||
while(serverGameCreationActive)
|
||||
{
|
||||
if (nrActiveSessions==0)
|
||||
{
|
||||
count=0;
|
||||
for (unsigned int i=0; i<users.size(); i++)
|
||||
{
|
||||
if (users[i].getState()==ONLINE_QUEUEING)
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if (count>=playersPerSessionCount)
|
||||
{
|
||||
games.resize(1);
|
||||
//lobby.resize(games.size()+1);
|
||||
session =new GameLogic::Session();
|
||||
lobby = Lobby();
|
||||
timer.resize(1);
|
||||
timeTillUpdate.resize(1);
|
||||
timeTillUpdate[0]=GAME_UPDATEDELAY;
|
||||
updateCount.resize(1);
|
||||
updateCount[0]=0;
|
||||
int curID=(int)games.size()-1;
|
||||
int mapid=rand()%maps.size();
|
||||
session->setNrPlayers(playersPerSessionCount);
|
||||
session->setKillsRequired(killsRequiredPerSession);
|
||||
session->load(maps[mapid]);
|
||||
printf("Map nr %d loaded, name %s.\n",mapid, maps[mapid].c_str());
|
||||
count=0;
|
||||
for (unsigned int i=0; count<playersPerSessionCount && i<users.size(); i++)
|
||||
{
|
||||
if (users[i].getState()==ONLINE_QUEUEING)
|
||||
{
|
||||
//Set to INLOBBY and send lobby data, then start a lobby
|
||||
lobby.addUser(users[i], i);
|
||||
users[i].setState(ONLINE_INGAME);
|
||||
games[curID].addUser(i);
|
||||
users[i].setGame(curID);
|
||||
session->accessPlayer(i).spawn();
|
||||
count++;
|
||||
}
|
||||
}
|
||||
lobbyActive=true;
|
||||
sendLobbyInitData(curID);
|
||||
lobby.startLobbyCountdown(LOBBY_WAIT_TIME);
|
||||
sendRenderData(curID);
|
||||
//return true;
|
||||
}
|
||||
if(lobbyActive)
|
||||
{
|
||||
for (int i=0; i<1; i++)
|
||||
{
|
||||
float ttimer=lobby.timeLeft();
|
||||
if (ttimer==0)
|
||||
{
|
||||
printf("Starting game.\n");
|
||||
games[i].initGame(users,playersPerSessionCount);
|
||||
sendInitData(i);
|
||||
nrActiveSessions++;
|
||||
lobbyActive=false;
|
||||
//serverGameCreationActive=false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Sleep(delay);
|
||||
}
|
||||
printf("Maximum server count reached, shutting down the sever creation thread.\n");
|
||||
return false;
|
||||
}
|
||||
SocketServer::SocketServer()
|
||||
{
|
||||
UDPSocket = INVALID_SOCKET;
|
||||
nrActiveSessions=0;
|
||||
serverGameCreationActive=false;
|
||||
serverTCPConnectionLoopActive=false;
|
||||
serverTCPReceiveLoopActive=false;
|
||||
serverUDPReceiveLoopActive=false;
|
||||
killsRequiredPerSession=10;
|
||||
playersPerSessionCount=1;
|
||||
LoadInitData("../ServerData.dat");
|
||||
//---------------------------------------------
|
||||
// Set up the port and IP of the server
|
||||
//Port starts up as a different one from when UDPSocketected, it changes once the server has exchanged some info with the client
|
||||
UDPRecvAddr.sin_family = AF_INET;
|
||||
UDPRecvAddr.sin_port = htons(UDPRecvPort);
|
||||
UDPRecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
|
||||
sessionEvents=std::vector<Event::GameEvent*>(0);
|
||||
sessionEffects=std::vector<Network::EffectData>(0);
|
||||
TCPRecvAddr.sin_family = AF_INET;
|
||||
TCPRecvAddr.sin_port = htons(TCPRecvPort);
|
||||
TCPRecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
|
||||
addrSize=sizeof(sockaddr_in);
|
||||
for (int i=0; i<NR_CONNECTTHREADS; i++)
|
||||
{
|
||||
connData[i].buffer=new char[256];
|
||||
connData[i].bufLen=256;
|
||||
ZeroMemory(connData[i].buffer,sizeof(connData[i].buffer));
|
||||
connData[i].dataSize=0;
|
||||
//connData[i].srcAddr
|
||||
memcpy(&connData[i].srcAddr, &UDPRecvAddr,addrSize);
|
||||
}
|
||||
for (int i=0; i<NR_SIMULTCPCONNECTS; i++)
|
||||
{
|
||||
tcpData[i].buffer=new char[256];
|
||||
tcpData[i].bufLen=256;
|
||||
ZeroMemory(tcpData[i].buffer,sizeof(tcpData[i].buffer));
|
||||
tcpData[i].dataSize=0;
|
||||
memcpy(&connData[i].srcAddr, &TCPRecvAddr,addrSize);
|
||||
}
|
||||
sendGameDataBufferSize=SERVER_PLAYER_DATA_SIZE*playersPerSessionCount+1;
|
||||
sendGameDataBuffer=new char[sendGameDataBufferSize];
|
||||
sendGameDataBuffer[0]=1;
|
||||
sendEffectDataBuffer=new char[sizeof(Network::EffectData)+1];
|
||||
sendEffectDataBuffer[0]=7;
|
||||
|
||||
//----------------------
|
||||
// Initialize Winsock
|
||||
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
|
||||
if (iResult != NO_ERROR) {
|
||||
wprintf(L"WSAStartup failed with error: %d\n", iResult);
|
||||
}
|
||||
else
|
||||
{
|
||||
//Init sockets
|
||||
setupStatus=initTCPSocket();
|
||||
if(setupStatus)
|
||||
setupStatus=initUDPSocket();
|
||||
}
|
||||
}
|
||||
bool SocketServer::startThreads()
|
||||
{
|
||||
//ThreadArguments tra1[NR_SIMULTCPCONNECTS];
|
||||
ThreadArguments tra2[NR_CONNECTTHREADS];
|
||||
//for (int i=0; i< NR_SIMULTCPCONNECTS; i++)
|
||||
//{
|
||||
// tra1[i].ptr=this;
|
||||
// tra1[i].threadID=i;
|
||||
// //printf("i - %d\n",i);
|
||||
//
|
||||
// tcpDataHandle[i]=CreateThread(
|
||||
// NULL, //Choose default security
|
||||
// 0, //Default stack size
|
||||
// (LPTHREAD_START_ROUTINE)&activateTCPConnectLoop,
|
||||
// //Routine to execute
|
||||
// (LPVOID) &tra1[i], //Thread parameter
|
||||
// 0, //Immediately run the thread
|
||||
// 0 //Thread Id
|
||||
// );
|
||||
// if (tcpDataHandle[i] == NULL)
|
||||
// {
|
||||
// printf("Error Creating TCP Thread#: %d\n",i);
|
||||
// return(false);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// printf("Successfully created TCP thread #: %d\n", i);
|
||||
// Sleep(100);
|
||||
// }
|
||||
//}
|
||||
for (int i=0; i< NR_CONNECTTHREADS; i++)
|
||||
{
|
||||
tra2[i].ptr=this;
|
||||
tra2[i].threadID=i;
|
||||
//printf("i - %d\n",i);
|
||||
udpDataHandle[i]=CreateThread(
|
||||
NULL, //Choose default security
|
||||
0, //Default stack size
|
||||
(LPTHREAD_START_ROUTINE)&activateUDPReceiveLoop,
|
||||
//Routine to execute
|
||||
(LPVOID) &tra2[i], //Thread parameter
|
||||
0, //Immediately run the thread
|
||||
0 //Thread Id
|
||||
);
|
||||
if (udpDataHandle[i] == NULL)
|
||||
{
|
||||
printf("Error Creating UDP Thread#: %d\n",i);
|
||||
return(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Successfully created UDP thread #: %d\n", i);
|
||||
Sleep(100);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool SocketServer::sendData(int uid, const char* data, int size)
|
||||
{
|
||||
//---------------------------------------------
|
||||
// Send a datagram to a user
|
||||
//uid -1 = broadcast message
|
||||
if (uid<0)
|
||||
{
|
||||
for (unsigned int i=0; i<users.size(); i++)
|
||||
{
|
||||
iResult = sendto(UDPSocket, data, size, 0, (SOCKADDR *) & users[i].getAddr(), addrSize);
|
||||
if (iResult == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"UDP sendData(-1) sendto failed with error: %d\n", WSAGetLastError());
|
||||
closesocket(UDPSocket);
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if((unsigned)uid>=users.size())
|
||||
{
|
||||
//User doesn't exist
|
||||
printf("UDP sendData(%d) sendto failed because the specified user does not exist\n", uid);
|
||||
}
|
||||
else
|
||||
{
|
||||
iResult = sendto(UDPSocket, data, size, 0, (SOCKADDR *) & users[uid].getAddr(), addrSize);
|
||||
if (iResult == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"UDP sendData(%d) sendto failed with error: %d\n", uid, WSAGetLastError());
|
||||
closesocket(UDPSocket);
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool SocketServer::sendKeyFrameData(int size, const char* data)
|
||||
{
|
||||
for (int i=0; i<playersPerSessionCount; i++)
|
||||
{
|
||||
iResult = sendto(UDPSocket, data, size+1, 0, (SOCKADDR *) & users[games[0].getUserID(i)].getAddr(), addrSize);
|
||||
if (iResult == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"UDP keyFrameData sendto failed with error: %d\n", WSAGetLastError());
|
||||
closesocket(UDPSocket);
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SocketServer::checkConnection(int userID)
|
||||
{
|
||||
char* message="\3testmessage";
|
||||
int count=
|
||||
sendto(
|
||||
UDPSocket,
|
||||
message,
|
||||
(int)strlen(message),
|
||||
0,
|
||||
(SOCKADDR *) & users[userID].getAddr(),
|
||||
addrSize);
|
||||
|
||||
if (count == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"recvfrom failed with error %d\n", WSAGetLastError());
|
||||
return false;
|
||||
}
|
||||
else if (count==0)
|
||||
{
|
||||
wprintf(L"Disconnected.\n");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool SocketServer::closeConnection()
|
||||
{
|
||||
//---------------------------------------------
|
||||
// When the application is finished sending, close the sockets.
|
||||
setupStatus=false;
|
||||
wprintf(L"Finished sending. Closing socket.\n");
|
||||
iResult = closesocket(UDPSocket);
|
||||
if (iResult == SOCKET_ERROR) {
|
||||
wprintf(L"closeUDPsocket failed with error: %d\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
iResult = closesocket(TCPSocket);
|
||||
if (iResult == SOCKET_ERROR) {
|
||||
wprintf(L"closeTCPsocket failed with error: %d\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
//---------------------------------------------
|
||||
// Clean up and quit.
|
||||
wprintf(L"Exiting.\n");
|
||||
WSACleanup();
|
||||
return true;
|
||||
}
|
|
@ -1,255 +0,0 @@
|
|||
#include "SocketServer.h"
|
||||
|
||||
/*// BENCHMARK BLOCK
|
||||
#include "WinTimer.h"
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
namespace Benchmark
|
||||
{
|
||||
struct
|
||||
{
|
||||
double averageTime, totalTime, minTime, maxTime; unsigned int numSamples;
|
||||
} timerData[10] = { 0.0f, 0.0f, ::std::numeric_limits<double>::max(), -::std::numeric_limits<double>::max(), 0 };
|
||||
|
||||
void sampleTime( const ::Utility::WinTimer &timer, unsigned char ref )
|
||||
{
|
||||
double elapsedTime = timer.getElapsedSeconds();
|
||||
timerData[ref].totalTime += elapsedTime;
|
||||
timerData[ref].minTime = ::Utility::Value::min( timerData[ref].minTime, elapsedTime );
|
||||
timerData[ref].maxTime = ::Utility::Value::max( timerData[ref].maxTime, elapsedTime );
|
||||
++timerData[ref].numSamples;
|
||||
timerData[ref].averageTime = timerData[ref].totalTime / (double) timerData[ref].numSamples;
|
||||
}
|
||||
|
||||
void print( )
|
||||
{
|
||||
::std::ofstream file;
|
||||
file.open( "BenchMarkData.txt", ::std::ios_base::app | ::std::ios_base::out );
|
||||
|
||||
if( file.is_open() )
|
||||
{
|
||||
file << "minTime\t\t: maxTime\t: averageTime\t\ttotalTime\tnumSamples\n";
|
||||
for( unsigned char i = 0; i < 1; ++i )
|
||||
file << timerData[i].minTime << (timerData[i].minTime == 0.0f ? "\t\t: " : "\t: ") << timerData[i].maxTime << "\t: " << timerData[i].averageTime << "\t\t" << timerData[i].totalTime << '\t' << timerData[i].numSamples <<'\n';
|
||||
file << ::std::endl;
|
||||
file.close();
|
||||
::std::cout << "Benchmark data saved." << ::std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
// END BENCHMARK BLOCK/**/
|
||||
|
||||
void SocketServer::updateServers()
|
||||
{
|
||||
for(int i=0; i<nrActiveSessions; i++)
|
||||
{
|
||||
if(games[i].allReady())
|
||||
{
|
||||
timer[i].tick();
|
||||
//printf("%f seconds since last update\n", timer[i].getDeltaTime());
|
||||
//printf("%f seconds since the timer started\n", timer[i].getGameTime());
|
||||
|
||||
//timeTillUpdate[i]-=timer[i].getDeltaTime();
|
||||
|
||||
DEBUGCTR++;
|
||||
//Sleep(timeTillUpdate[i]*1000);
|
||||
|
||||
// BENCHMARK BLOCK
|
||||
//::Utility::WinTimer processTimer;
|
||||
// END BENCHMARK BLOCK
|
||||
|
||||
switch( session->update( timer[i].getDeltaTime() ) )
|
||||
{
|
||||
case ::GameLogic::Session::Updated:
|
||||
// BENCHMARK BLOCK
|
||||
//processTimer.reset();
|
||||
// END BENCHMARK BLOCK
|
||||
|
||||
processSessionPlayerData(i);
|
||||
processAllSessionEvents(i);
|
||||
processAllSessionEffects(i);
|
||||
|
||||
// BENCHMARK BLOCK
|
||||
//Benchmark::sampleTime( processTimer, 0 );
|
||||
// END BENCHMARK BLOCK
|
||||
|
||||
DEBUGCTR=0;
|
||||
updateCount[i]++;
|
||||
default:
|
||||
break;
|
||||
case ::GameLogic::Session::Over:
|
||||
processAllSessionEvents(i);
|
||||
nrActiveSessions=0;
|
||||
if(users.size()==0)
|
||||
{
|
||||
printf("Game with id %d done, shutting down the game.\n", 0);
|
||||
Sleep(10);
|
||||
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// BENCHMARK BLOCK
|
||||
//if( Benchmark::timerData[0].numSamples % 1000 == 1 )
|
||||
// Benchmark::print();
|
||||
// END BENCHMARK BLOCK
|
||||
}
|
||||
}
|
||||
if(nrActiveSessions==0)
|
||||
{
|
||||
Sleep(50);
|
||||
}
|
||||
}
|
||||
void SocketServer::processSessionPlayerData(int serverID)
|
||||
{
|
||||
sendGameDataStruct.updateCount=updateCount[serverID];
|
||||
int offset=1;
|
||||
for (int i=0; i<playersPerSessionCount/*games[serverID].getPlayerCount()*/; i++)
|
||||
{
|
||||
sendGameDataStruct.position=session->accessPlayer(i).getOrientation();
|
||||
sendGameDataStruct.hp=session->accessPlayer(i).getHullPoints();
|
||||
sendGameDataStruct.shield=session->accessPlayer(i).getShieldPoints();
|
||||
sendGameDataStruct.dirVecLen=session->accessPlayer(i).getMovement().length();
|
||||
sendGameDataStruct.pid=i;
|
||||
memcpy(sendGameDataBuffer+offset, &sendGameDataStruct, SERVER_PLAYER_DATA_SIZE);
|
||||
offset+=SERVER_PLAYER_DATA_SIZE;
|
||||
}
|
||||
sendData(-1,sendGameDataBuffer, sendGameDataBufferSize);
|
||||
}
|
||||
void SocketServer::processAllSessionEvents(int serverID)
|
||||
{
|
||||
session->fetchEvents(sessionEvents);
|
||||
for (int i=0; i<(int)sessionEvents.size(); i++)
|
||||
{
|
||||
sendEventData(serverID, i);
|
||||
delete sessionEvents[i];
|
||||
}
|
||||
sessionEvents.resize(0);
|
||||
}
|
||||
bool SocketServer::sendGameData(int serverID)
|
||||
{
|
||||
//data[0]=1;
|
||||
for (int i=0; i<games[serverID].getPlayerCount(); i++)
|
||||
{
|
||||
iResult = sendto(UDPSocket, sendGameDataBuffer, SERVER_PLAYER_DATA_SIZE+1, 0, (SOCKADDR *) & users[games[serverID].getUserID(i)].getAddr(), addrSize);
|
||||
if (iResult == SOCKET_ERROR)
|
||||
{
|
||||
wprintf(L"UDP gameData sendto failed with error: %d\n", WSAGetLastError());
|
||||
closesocket(UDPSocket);
|
||||
WSACleanup();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
void SocketServer::sendEventData(int gid, int sid)
|
||||
{
|
||||
int size=sessionEvents[sid]->GetSize();
|
||||
int size1=sizeof(Event::BulletCreated);
|
||||
int tst=sizeof(Event::Type);
|
||||
char* ed=new char[size+1+tst];
|
||||
ed[0]=6;
|
||||
sessionEvents[sid]->SaveRawData(ed+(1+tst));
|
||||
|
||||
Event::Type eTest=Event::getEventType(sessionEvents[sid]);
|
||||
memcpy(ed+1, &eTest, sizeof(Event::Type));
|
||||
|
||||
sendData(-1, ed, size+1+tst);
|
||||
delete ed;
|
||||
}
|
||||
void SocketServer::sendRenderData(int gid)
|
||||
{
|
||||
Protocol::RenderData data;
|
||||
session->writeToRenderResourceData(data);
|
||||
int size=data.getRequiredBufferSize()+1;
|
||||
char* sendChar=new char[size];
|
||||
data.fillBuffer(sendChar+1);
|
||||
sendChar[0]=8;
|
||||
sendData(-1, sendChar, size);
|
||||
delete sendChar;
|
||||
}
|
||||
void SocketServer::processAllSessionEffects(int gid)
|
||||
{
|
||||
session->fetchEffectData(sessionEffects);
|
||||
|
||||
if (sessionEffects.size()>0)
|
||||
{
|
||||
int size=(int)sessionEffects.size()*sizeof(Network::EffectData) + 1;
|
||||
delete sendEffectDataBuffer;
|
||||
sendEffectDataBuffer=new char[size];
|
||||
for (size_t i=0; i<sessionEffects.size(); i++)
|
||||
{
|
||||
memcpy(sendEffectDataBuffer+1+sizeof(Network::EffectData)*i, &sessionEffects[i], sizeof(Network::EffectData));
|
||||
//sessionEffects.
|
||||
}
|
||||
sendEffectDataBuffer[0]=7;
|
||||
sendData(-1, sendEffectDataBuffer, size);
|
||||
}
|
||||
|
||||
}
|
||||
//HACK PLAYER UPDATE
|
||||
void ControlPlayer( GameLogic::Player& p,const ClientToServerUpdateData &update)
|
||||
{
|
||||
|
||||
if(update.braking)
|
||||
p.enableMovementReduction( true );
|
||||
else
|
||||
p.disableMovementReduction();
|
||||
p.enableRotationReduction( true );
|
||||
|
||||
if(update.forward>0)
|
||||
p.thrustForward();
|
||||
if(update.forward<0)
|
||||
p.thrustBackward();
|
||||
|
||||
if(update.straferight>0)
|
||||
p.strafeRight();
|
||||
if(update.straferight<0)
|
||||
p.strafeLeft();
|
||||
|
||||
if(update.strafeup>0)
|
||||
p.climb();
|
||||
if(update.strafeup<0)
|
||||
p.dive();
|
||||
|
||||
if(update.roll>0)
|
||||
{
|
||||
::Oyster::Math::Float baseAcceleration = p.rotationProperty.acceleration.roll;
|
||||
p.rotationProperty.acceleration.roll /= ::Oyster::Game::MoveAble::getDiscreteTimeSlice();
|
||||
|
||||
p.rollLeft();
|
||||
p.rotationProperty.acceleration.roll = baseAcceleration;
|
||||
}
|
||||
if(update.roll<0)
|
||||
{
|
||||
::Oyster::Math::Float baseAcceleration = p.rotationProperty.acceleration.roll;
|
||||
p.rotationProperty.acceleration.roll /= ::Oyster::Game::MoveAble::getDiscreteTimeSlice();
|
||||
p.rollRight();
|
||||
p.rotationProperty.acceleration.roll = baseAcceleration;
|
||||
}
|
||||
if(update.roll==0)
|
||||
{
|
||||
p.stopRotation();
|
||||
}
|
||||
|
||||
if(update.TurnVer!=0.0f)
|
||||
{
|
||||
::Oyster::Math::Float baseAcceleration = p.rotationProperty.acceleration.pitch;
|
||||
p.rotationProperty.acceleration.pitch *= -update.TurnVer / ::Oyster::Game::MoveAble::getDiscreteTimeSlice();
|
||||
p.pitchUp( );
|
||||
p.disableRotationReduction();
|
||||
p.rotationProperty.acceleration.pitch = baseAcceleration;
|
||||
}
|
||||
|
||||
if(update.TurnHor!=0.0f)
|
||||
{
|
||||
::Oyster::Math::Float baseAcceleration = p.rotationProperty.acceleration.yaw;
|
||||
p.rotationProperty.acceleration.yaw *= -update.TurnHor / ::Oyster::Game::MoveAble::getDiscreteTimeSlice();
|
||||
p.yawLeft( );
|
||||
p.disableRotationReduction();
|
||||
p.rotationProperty.acceleration.yaw = baseAcceleration;
|
||||
}
|
||||
if(update.firePrim)
|
||||
p.firePrimaryWeapon();
|
||||
}
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
#include "Game.h"
|
||||
#include "Lobby.h"
|
||||
//void ControlPlayer( GameLogic::Player& p,const ClientToServerUpdateData &update);
|
||||
const int NR_CONNECTTHREADS=1;
|
||||
const int NR_SIMULTCPCONNECTS=1;
|
||||
//threads can only take 1 argument
|
||||
struct ThreadArguments;
|
||||
struct ConnThreadData
|
||||
{
|
||||
sockaddr_in srcAddr;
|
||||
|
||||
ClientToServerUpdateData tmpdata;
|
||||
char* buffer;
|
||||
int bufLen;
|
||||
int dataSize;
|
||||
};
|
||||
// Link with ws2_32.lib
|
||||
#pragma comment(lib, "Ws2_32.lib")
|
||||
const short TCPSendPort = 11111;
|
||||
const short TCPRecvPort = 11110;
|
||||
const short UDPSendPort = 11001;
|
||||
const short UDPRecvPort = 11000;
|
||||
|
||||
class SocketServer
|
||||
{
|
||||
private:
|
||||
bool serverGameCreationActive;
|
||||
HANDLE gameCreateHandle;
|
||||
bool serverTCPConnectionLoopActive;
|
||||
bool serverUDPReceiveLoopActive;
|
||||
bool serverTCPReceiveLoopActive;
|
||||
bool setupStatus;
|
||||
int iResult;
|
||||
WSADATA wsaData;
|
||||
|
||||
SOCKET UDPSocket;
|
||||
SOCKET TCPSocket;
|
||||
|
||||
sockaddr_in TCPRecvAddr;
|
||||
sockaddr_in UDPRecvAddr;
|
||||
|
||||
int addrSize;
|
||||
|
||||
HANDLE tcpDataHandle[NR_SIMULTCPCONNECTS];
|
||||
ConnThreadData tcpData[NR_SIMULTCPCONNECTS];
|
||||
|
||||
HANDLE udpDataHandle[NR_CONNECTTHREADS];
|
||||
ConnThreadData connData[NR_CONNECTTHREADS];
|
||||
|
||||
int dataSize;
|
||||
|
||||
|
||||
char* sendEffectDataBuffer;
|
||||
char* sendGameDataBuffer;
|
||||
int sendGameDataBufferSize;
|
||||
ServerToClientUpdateData sendGameDataStruct;
|
||||
std::vector<User> users;
|
||||
std::vector<Game> games;
|
||||
Lobby lobby;
|
||||
int nrActiveSessions;
|
||||
std::vector<Event::GameEvent*> sessionEvents;
|
||||
std::vector<Network::EffectData> sessionEffects;
|
||||
//GameLogic::Session* session;
|
||||
std::vector<ServerTimer> timer;
|
||||
int DEBUGCTR;
|
||||
std::vector<long> updateCount;
|
||||
std::vector<float> timeTillUpdate;
|
||||
std::vector<::std::string> maps;
|
||||
std::string text;
|
||||
int playersPerSessionCount;
|
||||
int killsRequiredPerSession;
|
||||
bool lobbyActive;
|
||||
public:
|
||||
virtual ~SocketServer();
|
||||
//Debug force modify functions
|
||||
void processAllSessionEvents(int serverID);
|
||||
void processAllSessionEffects(int gid);
|
||||
void processSessionPlayerData(int serverID);
|
||||
//End of debug items
|
||||
void updateServers();
|
||||
SocketServer();
|
||||
bool checkConnection(int userID);
|
||||
bool initUDPSocket();
|
||||
bool initTCPSocket();
|
||||
//void firstTimeConnect();
|
||||
bool loadMapList(char* map);
|
||||
bool serverGameCreationLoop(int delay);
|
||||
bool startThreads();
|
||||
static DWORD activateUDPReceiveLoop(ThreadArguments* tra);
|
||||
void stopUDPReceiveLoops();
|
||||
//TCP functions
|
||||
static DWORD activateTCPConnectLoop(ThreadArguments* tra);
|
||||
void receiveConnection(int threadID);
|
||||
//End of TCP functions
|
||||
bool sendData(int uid, const char*, int);
|
||||
bool sendGameData(int serverID);
|
||||
bool sendKeyFrameData(int size, const char* data);
|
||||
void sendInitData(int gid);
|
||||
void sendRenderData(int gid);
|
||||
void sendEventData(int gid, int size);
|
||||
void sendLobbyInitData(int lid);
|
||||
bool closeConnection();
|
||||
void receiveDataUDP(int threadID);
|
||||
|
||||
static DWORD activateServerGameLoop(ThreadArguments* tra);
|
||||
void startGameCreateLoop(int delay);
|
||||
void stopGameCreateLoop();
|
||||
void parseReceivedData(int threadID/*char*, int*/);//char and int required if i don't want to use the class buffer
|
||||
void ParseReceivedData(ConnThreadData* data);
|
||||
|
||||
void parseServercommand(int pid, int threadID);
|
||||
void parseData(int pid, int gid, int threadID);
|
||||
void parseMessage(int pid, int threadID);
|
||||
|
||||
void addUser(int threadID);
|
||||
void AddUser(ConnThreadData* data);
|
||||
void removeUser(int id);
|
||||
|
||||
bool isReady() const {return setupStatus;}
|
||||
bool LoadInitData(char* maploc);
|
||||
};
|
||||
struct ThreadArguments
|
||||
{
|
||||
SocketServer* ptr;
|
||||
int threadID;
|
||||
};
|
|
@ -1,50 +0,0 @@
|
|||
#include "User.h"
|
||||
User::User(int i, sockaddr_in add, std::string usr)
|
||||
{
|
||||
addr=add;
|
||||
username=usr;
|
||||
curGame=-1;
|
||||
connection=NULL;
|
||||
state=ONLINE;
|
||||
lastUpdate=-1;
|
||||
updMutex = CreateMutex(
|
||||
NULL, // default security attributes
|
||||
FALSE, // initially not owned
|
||||
NULL); // unnamed mutex
|
||||
|
||||
if (updMutex == NULL)
|
||||
{
|
||||
printf("CreateMutex error: %d\n", GetLastError());
|
||||
}
|
||||
}
|
||||
User::User()
|
||||
{
|
||||
username="";
|
||||
curGame=-1;
|
||||
connection=NULL;
|
||||
state=ONLINE;
|
||||
lastUpdate=-1;
|
||||
updMutex = CreateMutex(
|
||||
NULL, // default security attributes
|
||||
FALSE, // initially not owned
|
||||
NULL); // unnamed mutex
|
||||
|
||||
if (updMutex == NULL)
|
||||
{
|
||||
printf("CreateMutex error: %d\n", GetLastError());
|
||||
}
|
||||
lastUpdateData.pid=-1;
|
||||
}
|
||||
void User::setLastUpdateData(Network::ClientToServerUpdateData data)
|
||||
{
|
||||
WaitForSingleObject(updMutex, INFINITE);
|
||||
lastUpdateData=data;
|
||||
ReleaseMutex(updMutex);
|
||||
}
|
||||
Network::ClientToServerUpdateData User::getLastUpdateData()
|
||||
{
|
||||
WaitForSingleObject(updMutex, INFINITE);
|
||||
Network::ClientToServerUpdateData data=lastUpdateData;
|
||||
ReleaseMutex(updMutex);
|
||||
return data;
|
||||
}
|
|
@ -1,42 +0,0 @@
|
|||
#include "ServerInclude.h"
|
||||
#ifndef USER_H
|
||||
#define USER_H
|
||||
enum UserState
|
||||
{
|
||||
OFFLINE,
|
||||
OFFLINE_INGAME,
|
||||
ONLINE,
|
||||
ONLINE_QUEUEING,
|
||||
ONLINE_INLOBBY,
|
||||
ONLINE_INGAME
|
||||
};
|
||||
class User
|
||||
{
|
||||
private:
|
||||
std::string username;
|
||||
int curGame;
|
||||
sockaddr_in addr;
|
||||
UserState state;
|
||||
long lastUpdate;
|
||||
HANDLE updMutex;
|
||||
Network::ClientToServerUpdateData lastUpdateData;
|
||||
public:
|
||||
void setLastUpdateData(Network::ClientToServerUpdateData data);
|
||||
Network::ClientToServerUpdateData getLastUpdateData();
|
||||
void setLastUpdate(long upd){lastUpdate=upd;}
|
||||
long getLastUpdate() {return lastUpdate;}
|
||||
HANDLE threadHandle;
|
||||
SOCKET connection;
|
||||
User();
|
||||
User(int id, sockaddr_in addr, std::string usr="Unknown");
|
||||
//SOCKET getTCPSocket() const {return connection;}
|
||||
sockaddr_in getAddr() const {return addr;}
|
||||
std::string getUsername() const {return username;}
|
||||
void setUsername(std::string usr){username=usr;}
|
||||
void setState(UserState st){state=st;}
|
||||
UserState getState(){return state;}
|
||||
void setGame(int gid){curGame=gid;}
|
||||
bool isIngame() {return state==ONLINE_INGAME;}
|
||||
int getGame(){return curGame;}
|
||||
};
|
||||
#endif
|
|
@ -0,0 +1,5 @@
|
|||
int main()
|
||||
{
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue