From 32348f4cc29d296492001a56bace349710abfa54 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Mon, 18 Nov 2013 16:34:50 +0100 Subject: [PATCH 01/67] Removed old stuff, and added main files for all projects --- Code/Network/NetworkDependencies/Event.cpp | 262 ----------- Code/Network/NetworkDependencies/Event.h | 142 ------ .../NetworkDependencies/EventStructs.h | 55 --- Code/Network/NetworkDependencies/Network.h | 11 - .../NetworkDependencies/NetworkConstants.h | 11 - .../NetworkDependencies.vcxproj | 20 +- .../NetworkDependencies.vcxproj.filters | 40 +- .../NetworkDependencies/NetworkIncludes.h | 23 - .../NetworkDependencies/NetworkInitStructs.h | 70 --- .../NetworkMiscFunctions.cpp | 12 - .../NetworkMiscFunctions.h | 9 - .../NetworkDependencies/NetworkTimer.cpp | 85 ---- .../NetworkDependencies/NetworkTimer.h | 25 -- .../NetworkUpdateStructs.h | 62 --- .../NetworkDependencies/UpdateStructs.cpp | 1 - Code/Network/NetworkDependencies/main.cpp | 0 .../OysterNetworkClient/ClientDataHandler.cpp | 112 ----- .../ClientInitFunctions.cpp | 79 ---- .../OysterNetworkClient/ClientMain.cpp | 79 ---- .../OysterNetworkClient/ClientTCPSpecific.cpp | 39 -- .../OysterNetworkClient/ClientUDPSpecific.cpp | 39 -- .../OysterNetworkClient.vcxproj | 22 +- .../OysterNetworkClient.vcxproj.filters | 22 +- .../OysterNetworkClient/SocketClient.cpp | 133 ------ .../OysterNetworkClient/SocketClient.h | 147 ------ Code/Network/OysterNetworkClient/main.cpp | 5 + Code/Network/OysterNetworkServer/Game.cpp | 113 ----- Code/Network/OysterNetworkServer/Game.h | 51 --- Code/Network/OysterNetworkServer/Lobby.cpp | 73 --- Code/Network/OysterNetworkServer/Lobby.h | 27 -- .../OysterNetworkServer.vcxproj | 31 +- .../OysterNetworkServer.vcxproj.filters | 49 +- .../OysterNetworkServer/ServerDataHandler.cpp | 219 --------- .../OysterNetworkServer/ServerInclude.h | 19 - .../OysterNetworkServer/ServerMain.cpp | 47 -- .../OysterNetworkServer/ServerTCPSpecific.cpp | 66 --- .../OysterNetworkServer/ServerTimer.cpp | 85 ---- .../Network/OysterNetworkServer/ServerTimer.h | 25 -- .../OysterNetworkServer/ServerUDPSpecific.cpp | 55 --- .../OysterNetworkServer/Servercore.cpp | 420 ------------------ .../SessionRelatedFunctions.cpp | 255 ----------- .../OysterNetworkServer/SocketServer.h | 126 ------ Code/Network/OysterNetworkServer/User.cpp | 50 --- Code/Network/OysterNetworkServer/User.h | 42 -- Code/Network/OysterNetworkServer/main.cpp | 5 + 45 files changed, 30 insertions(+), 3233 deletions(-) delete mode 100644 Code/Network/NetworkDependencies/Event.cpp delete mode 100644 Code/Network/NetworkDependencies/Event.h delete mode 100644 Code/Network/NetworkDependencies/EventStructs.h delete mode 100644 Code/Network/NetworkDependencies/Network.h delete mode 100644 Code/Network/NetworkDependencies/NetworkConstants.h delete mode 100644 Code/Network/NetworkDependencies/NetworkIncludes.h delete mode 100644 Code/Network/NetworkDependencies/NetworkInitStructs.h delete mode 100644 Code/Network/NetworkDependencies/NetworkMiscFunctions.cpp delete mode 100644 Code/Network/NetworkDependencies/NetworkMiscFunctions.h delete mode 100644 Code/Network/NetworkDependencies/NetworkTimer.cpp delete mode 100644 Code/Network/NetworkDependencies/NetworkTimer.h delete mode 100644 Code/Network/NetworkDependencies/NetworkUpdateStructs.h delete mode 100644 Code/Network/NetworkDependencies/UpdateStructs.cpp create mode 100644 Code/Network/NetworkDependencies/main.cpp delete mode 100644 Code/Network/OysterNetworkClient/ClientDataHandler.cpp delete mode 100644 Code/Network/OysterNetworkClient/ClientInitFunctions.cpp delete mode 100644 Code/Network/OysterNetworkClient/ClientMain.cpp delete mode 100644 Code/Network/OysterNetworkClient/ClientTCPSpecific.cpp delete mode 100644 Code/Network/OysterNetworkClient/ClientUDPSpecific.cpp delete mode 100644 Code/Network/OysterNetworkClient/SocketClient.cpp delete mode 100644 Code/Network/OysterNetworkClient/SocketClient.h create mode 100644 Code/Network/OysterNetworkClient/main.cpp delete mode 100644 Code/Network/OysterNetworkServer/Game.cpp delete mode 100644 Code/Network/OysterNetworkServer/Game.h delete mode 100644 Code/Network/OysterNetworkServer/Lobby.cpp delete mode 100644 Code/Network/OysterNetworkServer/Lobby.h delete mode 100644 Code/Network/OysterNetworkServer/ServerDataHandler.cpp delete mode 100644 Code/Network/OysterNetworkServer/ServerInclude.h delete mode 100644 Code/Network/OysterNetworkServer/ServerMain.cpp delete mode 100644 Code/Network/OysterNetworkServer/ServerTCPSpecific.cpp delete mode 100644 Code/Network/OysterNetworkServer/ServerTimer.cpp delete mode 100644 Code/Network/OysterNetworkServer/ServerTimer.h delete mode 100644 Code/Network/OysterNetworkServer/ServerUDPSpecific.cpp delete mode 100644 Code/Network/OysterNetworkServer/Servercore.cpp delete mode 100644 Code/Network/OysterNetworkServer/SessionRelatedFunctions.cpp delete mode 100644 Code/Network/OysterNetworkServer/SocketServer.h delete mode 100644 Code/Network/OysterNetworkServer/User.cpp delete mode 100644 Code/Network/OysterNetworkServer/User.h create mode 100644 Code/Network/OysterNetworkServer/main.cpp diff --git a/Code/Network/NetworkDependencies/Event.cpp b/Code/Network/NetworkDependencies/Event.cpp deleted file mode 100644 index 33e92bbf..00000000 --- a/Code/Network/NetworkDependencies/Event.cpp +++ /dev/null @@ -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; iGetSize()); - /*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; itrue - - - - - - - - - - - - - - - - - {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} @@ -167,6 +150,9 @@ false + + + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index 55401224..8755a3a0 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -15,45 +15,7 @@ - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - - Source Files - - - Source Files - - - Source Files - - + Source Files diff --git a/Code/Network/NetworkDependencies/NetworkIncludes.h b/Code/Network/NetworkDependencies/NetworkIncludes.h deleted file mode 100644 index 89902672..00000000 --- a/Code/Network/NetworkDependencies/NetworkIncludes.h +++ /dev/null @@ -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 -#include -#include -#include -#include -#include -#include -#include - -#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 \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkInitStructs.h b/Code/Network/NetworkDependencies/NetworkInitStructs.h deleted file mode 100644 index 7ef04ed1..00000000 --- a/Code/Network/NetworkDependencies/NetworkInitStructs.h +++ /dev/null @@ -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 splitString(const char* p_inStr, char p_delim) -{ - std::stringstream ss(p_inStr); - std::vector elems; - std::string item; - while(std::getline(ss, item, p_delim)) - { - elems.push_back(item); - } - return elems; -} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkMiscFunctions.h b/Code/Network/NetworkDependencies/NetworkMiscFunctions.h deleted file mode 100644 index a6959020..00000000 --- a/Code/Network/NetworkDependencies/NetworkMiscFunctions.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef NET_MISC_FNC_H -#define NET_MISC_FNC_H -#include -#include -#include -std::vector splitString(const char* p_inStr, char p_delim); -#define SSTR( x ) dynamic_cast< std::ostringstream & >( \ - ( std::ostringstream() << std::dec << x ) ).str() -#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkTimer.cpp b/Code/Network/NetworkDependencies/NetworkTimer.cpp deleted file mode 100644 index 42b8a143..00000000 --- a/Code/Network/NetworkDependencies/NetworkTimer.cpp +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkTimer.h b/Code/Network/NetworkDependencies/NetworkTimer.h deleted file mode 100644 index c4581c50..00000000 --- a/Code/Network/NetworkDependencies/NetworkTimer.h +++ /dev/null @@ -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 \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkUpdateStructs.h b/Code/Network/NetworkDependencies/NetworkUpdateStructs.h deleted file mode 100644 index 97f2037d..00000000 --- a/Code/Network/NetworkDependencies/NetworkUpdateStructs.h +++ /dev/null @@ -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 \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/UpdateStructs.cpp b/Code/Network/NetworkDependencies/UpdateStructs.cpp deleted file mode 100644 index 05209a9c..00000000 --- a/Code/Network/NetworkDependencies/UpdateStructs.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "NetworkUpdateStructs.h" \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/main.cpp b/Code/Network/NetworkDependencies/main.cpp new file mode 100644 index 00000000..e69de29b diff --git a/Code/Network/OysterNetworkClient/ClientDataHandler.cpp b/Code/Network/OysterNetworkClient/ClientDataHandler.cpp deleted file mode 100644 index 52d0f2ff..00000000 --- a/Code/Network/OysterNetworkClient/ClientDataHandler.cpp +++ /dev/null @@ -1,112 +0,0 @@ -#include "SocketClient.h" - -#pragma once -#ifndef SOCKET_DATA_CPP -#define SOCKET_DATA_CPP - -/*std::vector splitString(char* p_inStr, char p_delim) -{ -std::stringstream ss(p_inStr); -std::vector 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 diff --git a/Code/Network/OysterNetworkClient/ClientInitFunctions.cpp b/Code/Network/OysterNetworkClient/ClientInitFunctions.cpp deleted file mode 100644 index e2c4b920..00000000 --- a/Code/Network/OysterNetworkClient/ClientInitFunctions.cpp +++ /dev/null @@ -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 diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp deleted file mode 100644 index 5c297686..00000000 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ /dev/null @@ -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 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; -}*/ \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/ClientTCPSpecific.cpp b/Code/Network/OysterNetworkClient/ClientTCPSpecific.cpp deleted file mode 100644 index 1e8b7216..00000000 --- a/Code/Network/OysterNetworkClient/ClientTCPSpecific.cpp +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/ClientUDPSpecific.cpp b/Code/Network/OysterNetworkClient/ClientUDPSpecific.cpp deleted file mode 100644 index 9cab63ae..00000000 --- a/Code/Network/OysterNetworkClient/ClientUDPSpecific.cpp +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj index e51f38e2..ebd4c40d 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj @@ -24,26 +24,26 @@ - StaticLibrary + Application true v110 MultiByte - StaticLibrary + Application true v110 MultiByte - StaticLibrary + Application false v110 true MultiByte - StaticLibrary + Application false v110 true @@ -137,17 +137,6 @@ true - - - - - - - - - - - {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} @@ -159,6 +148,9 @@ {c5aa09d0-6594-4cd3-bd92-1d380c7b3b50} + + + diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters index 4327b3ae..8755a3a0 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters @@ -15,28 +15,8 @@ - + Source Files - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/SocketClient.cpp b/Code/Network/OysterNetworkClient/SocketClient.cpp deleted file mode 100644 index cde039cf..00000000 --- a/Code/Network/OysterNetworkClient/SocketClient.cpp +++ /dev/null @@ -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 \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/SocketClient.h b/Code/Network/OysterNetworkClient/SocketClient.h deleted file mode 100644 index 46c57d8d..00000000 --- a/Code/Network/OysterNetworkClient/SocketClient.h +++ /dev/null @@ -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 -//#include -//#include -//#include -//#include "OysterMath.h" -//These are optional includes for various useful features -#include -#include -#include -#include - -//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; -}; \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/main.cpp b/Code/Network/OysterNetworkClient/main.cpp new file mode 100644 index 00000000..aa0cf6dc --- /dev/null +++ b/Code/Network/OysterNetworkClient/main.cpp @@ -0,0 +1,5 @@ +int main() +{ + + return 0; +} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Game.cpp b/Code/Network/OysterNetworkServer/Game.cpp deleted file mode 100644 index 7948603d..00000000 --- a/Code/Network/OysterNetworkServer/Game.cpp +++ /dev/null @@ -1,113 +0,0 @@ -#include "Game.h" -Game::Game() -{ - playerCount=0; - started=false; - for (int i=0; i usr, int nrOfPlayers) -{ - /*for (int i=0; isetGame(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) -{ - -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Game.h b/Code/Network/OysterNetworkServer/Game.h deleted file mode 100644 index d162a322..00000000 --- a/Code/Network/OysterNetworkServer/Game.h +++ /dev/null @@ -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 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 \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Lobby.cpp b/Code/Network/OysterNetworkServer/Lobby.cpp deleted file mode 100644 index ade4b120..00000000 --- a/Code/Network/OysterNetworkServer/Lobby.cpp +++ /dev/null @@ -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; i0) - return timeLeft; - else - return 0; - } - ReleaseMutex(timerMutex); -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Lobby.h b/Code/Network/OysterNetworkServer/Lobby.h deleted file mode 100644 index a17e771c..00000000 --- a/Code/Network/OysterNetworkServer/Lobby.h +++ /dev/null @@ -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 \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj index 6be7bc04..2c829da2 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj @@ -24,26 +24,26 @@ - StaticLibrary + Application true v110 MultiByte - StaticLibrary + Application true v110 MultiByte - StaticLibrary + Application false v110 true MultiByte - StaticLibrary + Application false v110 true @@ -137,26 +137,6 @@ true - - - - - - - - - - - - - - - - - - - - {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} @@ -168,6 +148,9 @@ {c5aa09d0-6594-4cd3-bd92-1d380c7b3b50} + + + diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters index 15a52647..8755a3a0 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters @@ -15,55 +15,8 @@ - + Source Files - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerDataHandler.cpp b/Code/Network/OysterNetworkServer/ServerDataHandler.cpp deleted file mode 100644 index 55c36a02..00000000 --- a/Code/Network/OysterNetworkServer/ServerDataHandler.cpp +++ /dev/null @@ -1,219 +0,0 @@ -#include "SocketServer.h" - - - -void SocketServer::parseReceivedData(int threadID/*char* data, int size*/) -{ - bool test=false; - for(unsigned int i=0; isrcAddr); - 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 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; i1) - { - 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()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; iaccessPlayer(i).getOrientation(); - } - char* gd=new char[sizeof(init)+1]; - gd[0]=2; - for (int i=0; i -#define DEBUG_NEW new(_NORMAL_BLOCK ,__FILE__, __LINE__) -#else -#define DEBUG_NEW new -#endif - -#include -#include -#include -#include -#include "OysterMath.h" -//#include "Session.h" -#include "ServerTimer.h" -using namespace Network; - -const float GAME_UPDATEDELAY=1.0f/120.0f; diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp deleted file mode 100644 index 6c3d7f56..00000000 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include -#include "SocketServer.h" -#include "ServerTimer.h" -#include -#include -#include -//#ifdef WINDOWS -#include -#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 - //#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; -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerTCPSpecific.cpp b/Code/Network/OysterNetworkServer/ServerTCPSpecific.cpp deleted file mode 100644 index eb6987c9..00000000 --- a/Code/Network/OysterNetworkServer/ServerTCPSpecific.cpp +++ /dev/null @@ -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); - } -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerTimer.cpp b/Code/Network/OysterNetworkServer/ServerTimer.cpp deleted file mode 100644 index 4dc3d286..00000000 --- a/Code/Network/OysterNetworkServer/ServerTimer.cpp +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerTimer.h b/Code/Network/OysterNetworkServer/ServerTimer.h deleted file mode 100644 index 660c1799..00000000 --- a/Code/Network/OysterNetworkServer/ServerTimer.h +++ /dev/null @@ -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 \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerUDPSpecific.cpp b/Code/Network/OysterNetworkServer/ServerUDPSpecific.cpp deleted file mode 100644 index 1ffdf624..00000000 --- a/Code/Network/OysterNetworkServer/ServerUDPSpecific.cpp +++ /dev/null @@ -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); - } -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Servercore.cpp b/Code/Network/OysterNetworkServer/Servercore.cpp deleted file mode 100644 index 6dd855fd..00000000 --- a/Code/Network/OysterNetworkServer/Servercore.cpp +++ /dev/null @@ -1,420 +0,0 @@ -#include "SocketServer.h" -#include -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 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; iptr)->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=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; countaccessPlayer(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(0); - sessionEffects=std::vector(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=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 -#include -namespace Benchmark -{ - struct - { - double averageTime, totalTime, minTime, maxTime; unsigned int numSamples; - } timerData[10] = { 0.0f, 0.0f, ::std::numeric_limits::max(), -::std::numeric_limits::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; iupdate( 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; iaccessPlayer(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; iGetSize(); - 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; i0) - 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(); -} - diff --git a/Code/Network/OysterNetworkServer/SocketServer.h b/Code/Network/OysterNetworkServer/SocketServer.h deleted file mode 100644 index 67eac381..00000000 --- a/Code/Network/OysterNetworkServer/SocketServer.h +++ /dev/null @@ -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 users; - std::vector games; - Lobby lobby; - int nrActiveSessions; - std::vector sessionEvents; - std::vector sessionEffects; - //GameLogic::Session* session; - std::vector timer; - int DEBUGCTR; - std::vector updateCount; - std::vector 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; -}; \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/User.cpp b/Code/Network/OysterNetworkServer/User.cpp deleted file mode 100644 index 5dcbdf8d..00000000 --- a/Code/Network/OysterNetworkServer/User.cpp +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/User.h b/Code/Network/OysterNetworkServer/User.h deleted file mode 100644 index 1a68b950..00000000 --- a/Code/Network/OysterNetworkServer/User.h +++ /dev/null @@ -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 \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/main.cpp b/Code/Network/OysterNetworkServer/main.cpp new file mode 100644 index 00000000..bd889a99 --- /dev/null +++ b/Code/Network/OysterNetworkServer/main.cpp @@ -0,0 +1,5 @@ +int main() +{ + + return 0; +} \ No newline at end of file From 1022b15ea291760cc842f12c91ff9bdcc3232dac Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Mon, 18 Nov 2013 16:47:57 +0100 Subject: [PATCH 02/67] Removed stuff from project files --- .../NetworkDependencies/NetworkDependencies.vcxproj | 8 ++++---- .../OysterNetworkClient/OysterNetworkClient.vcxproj | 8 ++++---- Code/Network/OysterNetworkClient/main.cpp | 7 ++++++- .../OysterNetworkServer/OysterNetworkServer.vcxproj | 8 ++++---- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index 309f56cb..0860584c 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -90,7 +90,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +101,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -114,7 +114,7 @@ true true true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -129,7 +129,7 @@ true true true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj index ebd4c40d..5cf417da 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj @@ -90,7 +90,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +101,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -114,7 +114,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -129,7 +129,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true diff --git a/Code/Network/OysterNetworkClient/main.cpp b/Code/Network/OysterNetworkClient/main.cpp index aa0cf6dc..79543689 100644 --- a/Code/Network/OysterNetworkClient/main.cpp +++ b/Code/Network/OysterNetworkClient/main.cpp @@ -1,5 +1,10 @@ +#include +using namespace std; + int main() { - + cout << "Asd" << endl; + + return 0; } \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj index 2c829da2..7a31279b 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj @@ -90,7 +90,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +101,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -114,7 +114,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -129,7 +129,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true From c04593b575b89574c17ec2a6d7893a59a18f0540 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Tue, 19 Nov 2013 09:34:24 +0100 Subject: [PATCH 03/67] Changed name on main files on server and client --- .../OysterNetworkClient/{main.cpp => ClientMain.cpp} | 2 +- .../OysterNetworkClient/OysterNetworkClient.vcxproj | 2 +- .../OysterNetworkClient.vcxproj.filters | 2 +- .../OysterNetworkServer/OysterNetworkServer.vcxproj | 2 +- .../OysterNetworkServer.vcxproj.filters | 2 +- Code/Network/OysterNetworkServer/ServerMain.cpp | 10 ++++++++++ Code/Network/OysterNetworkServer/main.cpp | 5 ----- 7 files changed, 15 insertions(+), 10 deletions(-) rename Code/Network/OysterNetworkClient/{main.cpp => ClientMain.cpp} (70%) create mode 100644 Code/Network/OysterNetworkServer/ServerMain.cpp delete mode 100644 Code/Network/OysterNetworkServer/main.cpp diff --git a/Code/Network/OysterNetworkClient/main.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp similarity index 70% rename from Code/Network/OysterNetworkClient/main.cpp rename to Code/Network/OysterNetworkClient/ClientMain.cpp index 79543689..0e14df6f 100644 --- a/Code/Network/OysterNetworkClient/main.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -3,7 +3,7 @@ using namespace std; int main() { - cout << "Asd" << endl; + cout << "Client" << endl; return 0; diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj index 5cf417da..6d9b69b4 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj @@ -149,7 +149,7 @@ - + diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters index 8755a3a0..cd4a498b 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters @@ -15,7 +15,7 @@ - + Source Files diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj index 7a31279b..6dba87c1 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj @@ -149,7 +149,7 @@ - + diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters index 8755a3a0..f8025a15 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters @@ -15,7 +15,7 @@ - + Source Files diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp new file mode 100644 index 00000000..10903cda --- /dev/null +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -0,0 +1,10 @@ +#include +using namespace std; + +int main() +{ + cout << "Server" << endl; + + + return 0; +} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/main.cpp b/Code/Network/OysterNetworkServer/main.cpp deleted file mode 100644 index bd889a99..00000000 --- a/Code/Network/OysterNetworkServer/main.cpp +++ /dev/null @@ -1,5 +0,0 @@ -int main() -{ - - return 0; -} \ No newline at end of file From b2710737c691be23167dfca6cbf365c518757c92 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Tue, 19 Nov 2013 09:47:58 +0100 Subject: [PATCH 04/67] Signed-off-by: Sam Mario Svensson --- Code/Network/NetworkDependencies/NetworkDependencies.vcxproj | 4 ++-- Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj | 4 ++-- Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index 309f56cb..67df034d 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -90,7 +90,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +101,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj index ebd4c40d..6fbfa7c9 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj @@ -90,7 +90,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +101,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj index 2c829da2..93f04057 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj @@ -90,7 +90,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +101,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true From 56c32fcbc3f14297adb027f931abae747fea8667 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Tue, 19 Nov 2013 12:38:13 +0100 Subject: [PATCH 05/67] Iconnection interface --- .../NetworkDependencies/Connection.cpp | 141 ++++++++++++++++++ Code/Network/NetworkDependencies/Connection.h | 28 ++++ .../Network/NetworkDependencies/IConnection.h | 22 +++ .../NetworkDependencies.vcxproj | 5 + .../NetworkDependencies.vcxproj.filters | 11 ++ 5 files changed, 207 insertions(+) create mode 100644 Code/Network/NetworkDependencies/Connection.cpp create mode 100644 Code/Network/NetworkDependencies/Connection.h create mode 100644 Code/Network/NetworkDependencies/IConnection.h diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp new file mode 100644 index 00000000..31e53110 --- /dev/null +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -0,0 +1,141 @@ +#include "Connection.h" + +Connection::Connection() +{ + mySocket = NULL; +} + +Connection::Connection(int socket) +{ + mySocket = socket; +} + +Connection::~Connection() +{ + mySocket = NULL; + + if(socket != NULL) + { + closesocket( mySocket ); + mySocket = NULL; + } +} + +bool Connection::Connect(unsigned short port , const char serverName[]) +{ + mySocket = socket(AF_INET, SOCK_STREAM, 0); + if(mySocket == SOCKET_ERROR) + { + //error opening socket + return false; + } + + + struct hostent *hostEntry; + if((hostEntry = gethostbyname(serverName)) == NULL) + { + //couldn't find host + return false; + } + struct sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = *(unsigned long*) hostEntry->h_addr; + + while(1) + { + if(connect(mySocket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) + { + //Error connecting to server + return false; + } + + else + { + break; + } + Sleep(10); + } + + //connection succesfull! + return true; + + +} + +bool Connection::InitiateServer(unsigned short port) +{ + int mySocket = socket(AF_INET, SOCK_STREAM, 0); + if(mySocket == SOCKET_ERROR) + { + //Error opening socket! + return false; + } + + struct sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = INADDR_ANY; + + if(bind(mySocket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) + { + //Bind failed!; + closesocket(mySocket); + return false; + } + + //not our Listen function! + if(listen(mySocket, 5) == SOCKET_ERROR) + { + //"Listen failed! + closesocket(mySocket); + return -1; + } + + //Server started! + return mySocket; +} + +void Connection::Disconnect() +{ + closesocket(mySocket); +} + +bool Connection::Send(int socket , const char message[]) +{ + int nBytes; + unsigned long messageSize = strlen(message); + + if((nBytes = send(socket, message , messageSize)) == SOCKET_ERROR) + { + //Send failed! + return false; + } + + return true; +} + +int Recieve(int socket, char message[]) +{ + int nBytes; + nBytes = recv(socket, message , 255, 0); + if(nBytes == SOCKET_ERROR) + { + //Recv failed + return -1; + } + + return 1; +} + +int Connection::Listen() +{ + int clientSocket; + if((clientSocket = accept(mySocket, NULL, NULL)) == INVALID_SOCKET) + { + //failed + return -1; + } + + return clientSocket; +} diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h new file mode 100644 index 00000000..96dda6fd --- /dev/null +++ b/Code/Network/NetworkDependencies/Connection.h @@ -0,0 +1,28 @@ +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#ifndef NETWORK_DEPENDENCIES_CONNECTION_H +#define NETWORK_DEPENDENCIES_CONNECTION_H + +#include "IConnection.h" + +class Connection : public IConnection +{ + private: + int mySocket; + + public: + Connection(); + Connection(int socket); + ~Connection(); + + virtual bool Connect( unsigned short port , const char serverName[] ); + virtual bool InitiateServer( unsigned short port ); + virtual void Disconnect(); + virtual bool Send(int socket , const char message[]); + virtual int Recieve(int socket); + virtual int Listen(); +}; + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h new file mode 100644 index 00000000..660fa487 --- /dev/null +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -0,0 +1,22 @@ +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#ifndef NETWORK_DEPENDENCIES_I_CONNECTION_H +#define NETWORK_DEPENDENCIES_I_CONNECTION_H + +#include +#include + +class IConnection +{ + public: + virtual bool Connect( unsigned short port, const char serverName[] ) = 0; + virtual bool InitiateServer( unsigned short port ) = 0; + virtual void Disconnect() = 0; + virtual bool Send(int socket , const char message[]); = 0; + virtual int Recieve( int socket ) = 0; + virtual int Listen() = 0; +}; + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index 0860584c..4c42ba1d 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -151,8 +151,13 @@ + + + + + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index 8755a3a0..57da6b71 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -18,5 +18,16 @@ Source Files + + Source Files + + + + + Header Files + + + Header Files + \ No newline at end of file From 89ce3dd0d13b4b4c5ec953f0ce90ce8cff56d47b Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Tue, 19 Nov 2013 12:41:58 +0100 Subject: [PATCH 06/67] Fixed IConnection and Connection --- Code/Network/NetworkDependencies/Connection.cpp | 2 +- Code/Network/NetworkDependencies/IConnection.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 31e53110..97b798d1 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -106,7 +106,7 @@ bool Connection::Send(int socket , const char message[]) int nBytes; unsigned long messageSize = strlen(message); - if((nBytes = send(socket, message , messageSize)) == SOCKET_ERROR) + if((nBytes = send(socket, message , messageSize, 0)) == SOCKET_ERROR) { //Send failed! return false; diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index 660fa487..ec7feb50 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -14,7 +14,7 @@ class IConnection virtual bool Connect( unsigned short port, const char serverName[] ) = 0; virtual bool InitiateServer( unsigned short port ) = 0; virtual void Disconnect() = 0; - virtual bool Send(int socket , const char message[]); = 0; + virtual bool Send(int socket , const char message[]) = 0; virtual int Recieve( int socket ) = 0; virtual int Listen() = 0; }; From adcef512277a669b9d4e746b54bb90fcaef01f85 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Tue, 19 Nov 2013 12:55:54 +0100 Subject: [PATCH 07/67] third time is the charm fixed send and recieve functions in IConnection --- Code/Network/NetworkDependencies/Connection.cpp | 8 ++++---- Code/Network/NetworkDependencies/Connection.h | 4 ++-- Code/Network/NetworkDependencies/IConnection.h | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 97b798d1..64111034 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -101,12 +101,12 @@ void Connection::Disconnect() closesocket(mySocket); } -bool Connection::Send(int socket , const char message[]) +bool Connection::Send(const char message[]) { int nBytes; unsigned long messageSize = strlen(message); - if((nBytes = send(socket, message , messageSize, 0)) == SOCKET_ERROR) + if((nBytes = send(mySocket, message , messageSize, 0)) == SOCKET_ERROR) { //Send failed! return false; @@ -115,10 +115,10 @@ bool Connection::Send(int socket , const char message[]) return true; } -int Recieve(int socket, char message[]) +int Connection::Recieve(char message[]) { int nBytes; - nBytes = recv(socket, message , 255, 0); + nBytes = recv(mySocket, message , 255, 0); if(nBytes == SOCKET_ERROR) { //Recv failed diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index 96dda6fd..28804cb1 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -20,8 +20,8 @@ class Connection : public IConnection virtual bool Connect( unsigned short port , const char serverName[] ); virtual bool InitiateServer( unsigned short port ); virtual void Disconnect(); - virtual bool Send(int socket , const char message[]); - virtual int Recieve(int socket); + virtual bool Send(const char message[]); + virtual int Recieve(char message[]); virtual int Listen(); }; diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index ec7feb50..fd3610fc 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -14,8 +14,8 @@ class IConnection virtual bool Connect( unsigned short port, const char serverName[] ) = 0; virtual bool InitiateServer( unsigned short port ) = 0; virtual void Disconnect() = 0; - virtual bool Send(int socket , const char message[]) = 0; - virtual int Recieve( int socket ) = 0; + virtual bool Send( const char message[] ) = 0; + virtual int Recieve(char message[]) = 0; virtual int Listen() = 0; }; From ac75e178ce448caab492b6a173080a1cb71d74ba Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Tue, 19 Nov 2013 13:42:50 +0100 Subject: [PATCH 08/67] Sending a message from server to client (done and done) --- .../NetworkDependencies/Connection.cpp | 7 ++-- Code/Network/NetworkDependencies/Connection.h | 5 ++- .../Network/NetworkDependencies/IConnection.h | 27 +++++++------ Code/Network/OysterNetworkClient/Client.cpp | 28 +++++++++++++ Code/Network/OysterNetworkClient/Client.h | 26 +++++++++++++ .../OysterNetworkClient/ClientMain.cpp | 35 +++++++++++++++++ .../OysterNetworkClient.vcxproj | 4 ++ .../OysterNetworkClient.vcxproj.filters | 8 ++++ Code/Network/OysterNetworkServer/Client.cpp | 16 ++++++++ Code/Network/OysterNetworkServer/Client.h | 24 ++++++++++++ Code/Network/OysterNetworkServer/IListener.h | 16 ++++++++ Code/Network/OysterNetworkServer/Listener.cpp | 32 +++++++++++++++ Code/Network/OysterNetworkServer/Listener.h | 25 ++++++++++++ .../OysterNetworkServer.vcxproj | 7 ++++ .../OysterNetworkServer.vcxproj.filters | 17 ++++++++ .../OysterNetworkServer/ServerMain.cpp | 39 +++++++++++++++++++ 16 files changed, 299 insertions(+), 17 deletions(-) create mode 100644 Code/Network/OysterNetworkClient/Client.cpp create mode 100644 Code/Network/OysterNetworkClient/Client.h create mode 100644 Code/Network/OysterNetworkServer/Client.cpp create mode 100644 Code/Network/OysterNetworkServer/Client.h create mode 100644 Code/Network/OysterNetworkServer/IListener.h create mode 100644 Code/Network/OysterNetworkServer/Listener.cpp create mode 100644 Code/Network/OysterNetworkServer/Listener.h diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 64111034..6fb70057 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -1,5 +1,8 @@ #include "Connection.h" +#include +#include + Connection::Connection() { mySocket = NULL; @@ -59,13 +62,11 @@ bool Connection::Connect(unsigned short port , const char serverName[]) //connection succesfull! return true; - - } bool Connection::InitiateServer(unsigned short port) { - int mySocket = socket(AF_INET, SOCK_STREAM, 0); + mySocket = socket(AF_INET, SOCK_STREAM, 0); if(mySocket == SOCKET_ERROR) { //Error opening socket! diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index 28804cb1..86ffda34 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -7,11 +7,11 @@ #include "IConnection.h" -class Connection : public IConnection +class Connection : public ::Oyster::Network::IConnection { private: int mySocket; - + public: Connection(); Connection(int socket); @@ -23,6 +23,7 @@ class Connection : public IConnection virtual bool Send(const char message[]); virtual int Recieve(char message[]); virtual int Listen(); + }; #endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index fd3610fc..b986c381 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -5,18 +5,21 @@ #ifndef NETWORK_DEPENDENCIES_I_CONNECTION_H #define NETWORK_DEPENDENCIES_I_CONNECTION_H -#include -#include - -class IConnection +namespace Oyster { - public: - virtual bool Connect( unsigned short port, const char serverName[] ) = 0; - virtual bool InitiateServer( unsigned short port ) = 0; - virtual void Disconnect() = 0; - virtual bool Send( const char message[] ) = 0; - virtual int Recieve(char message[]) = 0; - virtual int Listen() = 0; -}; + namespace Network + { + class IConnection + { + public: + virtual void Disconnect() = 0; + virtual bool Send( const char message[] ) = 0; + virtual int Recieve(char message[]) = 0; + virtual bool InitiateServer( unsigned short port ) { return false; }; + virtual int Listen() { return -1; }; + virtual bool Connect( unsigned short port, const char serverName[] ) { return false; }; + }; + } +} #endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/Client.cpp b/Code/Network/OysterNetworkClient/Client.cpp new file mode 100644 index 00000000..a947beea --- /dev/null +++ b/Code/Network/OysterNetworkClient/Client.cpp @@ -0,0 +1,28 @@ +#include "Client.h" + +Client::Client() +{ + connection = new Connection(); +} + +Client::~Client() +{ + delete connection; +} + +bool Client::Connect(unsigned int port, char filename[]) +{ + connection->Connect(port, filename); + + return true; +} + +void Client::Send(char msg[]) +{ + connection->Send(msg); +} + +void Client::Recv(char msg[]) +{ + connection->Recieve(msg); +} \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/Client.h b/Code/Network/OysterNetworkClient/Client.h new file mode 100644 index 00000000..1fd9f1f6 --- /dev/null +++ b/Code/Network/OysterNetworkClient/Client.h @@ -0,0 +1,26 @@ +#ifndef NETWORK_CLIENT_CLIENT_H +#define NETWORK_CLIENT_CLIENT_H + +///////////////////////////////////////////////////////////////////// +// Created by Pontus 2013 +///////////////////////////////////////////////////////////////////// + +#include "../NetworkDependencies/Connection.h" + +class Client +{ +public: + Client(); + ~Client(); + + bool Connect(unsigned int port, char filename[]); + + void Send(char msg[]); + void Recv(char msg[]); + +private: + Connection* connection; + +}; + +#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 0e14df6f..a3058900 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -1,10 +1,45 @@ #include +#include "Client.h" +#include using namespace std; +#pragma comment(lib, "ws2_32.lib") + +void ShutdownSockets(); +bool InitSockets(); int main() { + char msgRecv[255] = "\0"; + + InitSockets(); + cout << "Client" << endl; + //Create Client + Client client; + //Connect to server + client.Connect(9876, "127.0.0.1"); + + //Recieve message + client.Recv(msgRecv); + + //print message + cout << msgRecv << endl; + + ShutdownSockets(); + + system("pause"); return 0; +} + +bool InitSockets() +{ + WSADATA wsaData; + return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR; +} + +void ShutdownSockets() +{ + WSACleanup(); } \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj index 6d9b69b4..6bdc7921 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj @@ -149,8 +149,12 @@ + + + + diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters index cd4a498b..2e5e9ef6 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters @@ -18,5 +18,13 @@ Source Files + + Source Files + + + + + Header Files + \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Client.cpp b/Code/Network/OysterNetworkServer/Client.cpp new file mode 100644 index 00000000..7c15984d --- /dev/null +++ b/Code/Network/OysterNetworkServer/Client.cpp @@ -0,0 +1,16 @@ +#include "Client.h" + +Client::Client(unsigned int socket) +{ + connection = new Connection(socket); +} + +Client::~Client() +{ + delete connection; +} + +void Client::Send(char buffer[]) +{ + connection->Send(buffer); +} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Client.h b/Code/Network/OysterNetworkServer/Client.h new file mode 100644 index 00000000..c72c7669 --- /dev/null +++ b/Code/Network/OysterNetworkServer/Client.h @@ -0,0 +1,24 @@ +#ifndef NETWORK_SERVER_CLIENT_H +#define NETWORK_SERVER_CLIENT_H + +///////////////////////////////////////////////////////////////////// +// Created by Pontus 2013 +///////////////////////////////////////////////////////////////////// + +#include "../NetworkDependencies/Connection.h" + +class Client +{ +public: + Client(unsigned int socket); + ~Client(); + + void Send(char buffer[]); + + +private: + Connection* connection; + +}; + +#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/IListener.h b/Code/Network/OysterNetworkServer/IListener.h new file mode 100644 index 00000000..9a427f29 --- /dev/null +++ b/Code/Network/OysterNetworkServer/IListener.h @@ -0,0 +1,16 @@ +#ifndef NETWORK_SERVER_ILISTENER_H +#define NETWORK_SERVER_ILISTENER_H + +///////////////////////////////////////////////////////////////////// +// Created by Pontus 2013 +///////////////////////////////////////////////////////////////////// + +class IListener +{ +public: + virtual bool Init(unsigned int port) = 0; + virtual int Accept() = 0; + +}; + +#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Listener.cpp b/Code/Network/OysterNetworkServer/Listener.cpp new file mode 100644 index 00000000..7b340441 --- /dev/null +++ b/Code/Network/OysterNetworkServer/Listener.cpp @@ -0,0 +1,32 @@ +#include "Listener.h" + +Listener::Listener() +{ + +} + +Listener::~Listener() +{ + if(connection) + { + delete connection; + } +} + +bool Listener::Init(unsigned int port) +{ + connection = new Connection(); + + connection->InitiateServer(port); + + + return true; +} + +int Listener::Accept() +{ + int clientSocket = 0; + clientSocket = connection->Listen(); + + return clientSocket; +} \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Listener.h b/Code/Network/OysterNetworkServer/Listener.h new file mode 100644 index 00000000..8e5f99b7 --- /dev/null +++ b/Code/Network/OysterNetworkServer/Listener.h @@ -0,0 +1,25 @@ +#ifndef NETWORK_SERVER_LISTENER_H +#define NETWORK_SERVER_LISTENER_H + +///////////////////////////////////////////////////////////////////// +// Created by Pontus 2013 +///////////////////////////////////////////////////////////////////// + +#include "IListener.h" +#include "../NetworkDependencies/Connection.h" + +class Listener +{ +public: + Listener(); + ~Listener(); + + bool Init(unsigned int port); + int Accept(); + +private: + Connection* connection; + +}; + +#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj index 6dba87c1..94a6a6e1 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj @@ -149,8 +149,15 @@ + + + + + + + diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters index f8025a15..1e38f641 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters @@ -18,5 +18,22 @@ Source Files + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 10903cda..0fb81776 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -1,10 +1,49 @@ #include +#include +#include "Listener.h" +#include "Client.h" using namespace std; +#pragma comment(lib, "ws2_32.lib") + +void ShutdownSockets(); +bool InitSockets(); + int main() { cout << "Server" << endl; + if(!InitSockets()) + { + cout << "Sockets failed to initialize" << endl; + } + //Create socket + Listener listener; + listener.Init(9876); + + //Start listening + int clientSocket = listener.Accept(); + + //Accept a client + Client client(clientSocket); + + //Send a message to that client + client.Send("asd"); + + ShutdownSockets(); + + system("pause"); return 0; +} + +bool InitSockets() +{ + WSADATA wsaData; + return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR; +} + +void ShutdownSockets() +{ + WSACleanup(); } \ No newline at end of file From 1df11becf7a37134fd45524f758d872038a0dbd1 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Tue, 19 Nov 2013 14:18:34 +0100 Subject: [PATCH 09/67] chat test with server created simple chat program for the client to be able to chat between client through a server --- .../NetworkDependencies/Connection.cpp | 2 + .../OysterNetworkClient/ClientMain.cpp | 39 +++++++++++++++++-- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 6fb70057..b07e6106 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -126,6 +126,8 @@ int Connection::Recieve(char message[]) return -1; } + message[nBytes] = NULL; + return 1; } diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index a3058900..ac38ead1 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -6,6 +6,7 @@ using namespace std; void ShutdownSockets(); bool InitSockets(); +void chat(Client client); int main() { @@ -19,13 +20,16 @@ int main() Client client; //Connect to server - client.Connect(9876, "127.0.0.1"); + client.Connect(9876, "10.0.0.3"); + + + chat(client); //Recieve message - client.Recv(msgRecv); + //client.Recv(msgRecv); //print message - cout << msgRecv << endl; + //cout << msgRecv << endl; ShutdownSockets(); @@ -42,4 +46,33 @@ bool InitSockets() void ShutdownSockets() { WSACleanup(); +} + +void chat(Client client) +{ + char msgRecv[255] = "\0"; + char msgSend[255] = "\0"; + + bool chatDone = false; + + while(!chatDone) + { + client.Recv(msgRecv); + + cout<< "Server: " << msgRecv << endl; + + cin.getline(msgSend , 255 , '\n'); + + if(msgSend != "exit") + { + client.Send(msgSend); + } + + else + { + chatDone = true; + } + + } + } \ No newline at end of file From 816dced937fb8e301d4ed28066064ffa97b194c7 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Tue, 19 Nov 2013 14:21:25 +0100 Subject: [PATCH 10/67] Chat test server --- .../NetworkDependencies/Connection.cpp | 2 +- .../OysterNetworkClient/ClientMain.cpp | 2 +- Code/Network/OysterNetworkServer/Client.cpp | 5 +++++ Code/Network/OysterNetworkServer/Client.h | 1 + .../OysterNetworkServer/ServerMain.cpp | 21 ++++++++++++++++--- 5 files changed, 26 insertions(+), 5 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index b07e6106..9639329f 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -126,7 +126,7 @@ int Connection::Recieve(char message[]) return -1; } - message[nBytes] = NULL; + message[nBytes] = '\0'; return 1; } diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index ac38ead1..0c89410b 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -31,7 +31,7 @@ int main() //print message //cout << msgRecv << endl; - ShutdownSockets(); + ShutdownSockets(); system("pause"); return 0; diff --git a/Code/Network/OysterNetworkServer/Client.cpp b/Code/Network/OysterNetworkServer/Client.cpp index 7c15984d..50ce3b8c 100644 --- a/Code/Network/OysterNetworkServer/Client.cpp +++ b/Code/Network/OysterNetworkServer/Client.cpp @@ -13,4 +13,9 @@ Client::~Client() void Client::Send(char buffer[]) { connection->Send(buffer); +} + +void Client::Recv(char buffer[]) +{ + connection->Recieve(buffer); } \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Client.h b/Code/Network/OysterNetworkServer/Client.h index c72c7669..3c29c620 100644 --- a/Code/Network/OysterNetworkServer/Client.h +++ b/Code/Network/OysterNetworkServer/Client.h @@ -14,6 +14,7 @@ public: ~Client(); void Send(char buffer[]); + void Recv(char buffer[]); private: diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 0fb81776..626e91bb 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -13,6 +13,8 @@ int main() { cout << "Server" << endl; + char recvBuffer[255]; + if(!InitSockets()) { cout << "Sockets failed to initialize" << endl; @@ -23,13 +25,26 @@ int main() listener.Init(9876); //Start listening + //Accept a client int clientSocket = listener.Accept(); + Client client1(clientSocket); + cout << "First client connected." << endl; //Accept a client - Client client(clientSocket); + clientSocket = listener.Accept(); + Client client2(clientSocket); + cout << "Second client connected." << endl; - //Send a message to that client - client.Send("asd"); + client1.Send("Hej"); + + while(1) + { + client1.Recv(recvBuffer); + client2.Send(recvBuffer); + + client2.Recv(recvBuffer); + client1.Send(recvBuffer); + } ShutdownSockets(); From 58efe7fdd3928b96ee1cc1d332bc95056fcbeee9 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Tue, 19 Nov 2013 14:59:00 +0100 Subject: [PATCH 11/67] getline fix in chat program --- Code/Network/OysterNetworkClient/ClientMain.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 0c89410b..7f3687dc 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -59,10 +59,15 @@ void chat(Client client) { client.Recv(msgRecv); - cout<< "Server: " << msgRecv << endl; + cout<< "Client 2: " << msgRecv << endl; cin.getline(msgSend , 255 , '\n'); + if(strlen(msgSend) < 1) + { + strcpy_s(msgSend , " "); + } + if(msgSend != "exit") { client.Send(msgSend); @@ -73,6 +78,8 @@ void chat(Client client) chatDone = true; } + cin.clear(); + } } \ No newline at end of file From 5bcc285141dd6ea503eb6456c4839d40221f2fdb Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Wed, 20 Nov 2013 10:33:52 +0100 Subject: [PATCH 12/67] Sending empty strings, prints messages on server --- Code/Network/OysterNetworkClient/ClientMain.cpp | 4 ++++ Code/Network/OysterNetworkServer/ServerMain.cpp | 2 ++ 2 files changed, 6 insertions(+) diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 7f3687dc..cc9a786f 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -70,6 +70,10 @@ void chat(Client client) if(msgSend != "exit") { + if(strlen(msgSend) < 1) + { + strcpy_s(msgSend, "ERROR"); + } client.Send(msgSend); } diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 626e91bb..4fbe8ece 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -40,9 +40,11 @@ int main() while(1) { client1.Recv(recvBuffer); + cout << "Client1: " << recvBuffer << endl; client2.Send(recvBuffer); client2.Recv(recvBuffer); + cout << "Client2: " << recvBuffer << endl; client1.Send(recvBuffer); } From f77efb107d51c695114392b0774d5a94a23894ed Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Thu, 21 Nov 2013 13:40:52 +0100 Subject: [PATCH 13/67] Implemented Translator also fixed some coding standards with namespaces in client, connection, listener, server. added protocols with enums for packagetype. --- .../NetworkDependencies/Connection.cpp | 10 +--- Code/Network/NetworkDependencies/Connection.h | 35 +++++++------ .../Network/NetworkDependencies/IConnection.h | 15 +++--- Code/Network/NetworkDependencies/ITranslate.h | 18 +++++++ .../NetworkDependencies.vcxproj | 4 ++ .../NetworkDependencies.vcxproj.filters | 12 +++++ Code/Network/NetworkDependencies/Protocols.h | 35 +++++++++++++ .../NetworkDependencies/Translator.cpp | 50 +++++++++++++++++++ Code/Network/NetworkDependencies/Translator.h | 27 ++++++++++ Code/Network/OysterNetworkClient/Client.cpp | 2 + Code/Network/OysterNetworkClient/Client.h | 30 +++++++---- .../OysterNetworkClient/ClientMain.cpp | 1 + Code/Network/OysterNetworkServer/Client.cpp | 2 + Code/Network/OysterNetworkServer/Client.h | 26 +++++++--- Code/Network/OysterNetworkServer/Listener.cpp | 2 + Code/Network/OysterNetworkServer/Listener.h | 2 +- .../OysterNetworkServer/ServerMain.cpp | 1 + 17 files changed, 222 insertions(+), 50 deletions(-) create mode 100644 Code/Network/NetworkDependencies/ITranslate.h create mode 100644 Code/Network/NetworkDependencies/Protocols.h create mode 100644 Code/Network/NetworkDependencies/Translator.cpp create mode 100644 Code/Network/NetworkDependencies/Translator.h diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 9639329f..8a2081c0 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -3,15 +3,7 @@ #include #include -Connection::Connection() -{ - mySocket = NULL; -} - -Connection::Connection(int socket) -{ - mySocket = socket; -} +using namespace Oyster::Network; Connection::~Connection() { diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index 86ffda34..0070fed6 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -7,23 +7,30 @@ #include "IConnection.h" -class Connection : public ::Oyster::Network::IConnection +namespace Oyster { - private: - int mySocket; + namespace Network + { + class Connection : public IConnection + { - public: - Connection(); - Connection(int socket); - ~Connection(); + public: + Connection() { mySocket = 0; }; + Connection(int socket) { mySocket = socket; }; + ~Connection(); - virtual bool Connect( unsigned short port , const char serverName[] ); - virtual bool InitiateServer( unsigned short port ); - virtual void Disconnect(); - virtual bool Send(const char message[]); - virtual int Recieve(char message[]); - virtual int Listen(); + virtual bool Connect( unsigned short port , const char serverName[] ); + virtual bool InitiateServer( unsigned short port ); + virtual void Disconnect(); + virtual bool Send(const char message[]); + virtual int Recieve(char message[]); + virtual int Listen(); -}; + private: + int mySocket; + + }; + } +} #endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index b986c381..1443b781 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -11,13 +11,14 @@ namespace Oyster { class IConnection { - public: - virtual void Disconnect() = 0; - virtual bool Send( const char message[] ) = 0; - virtual int Recieve(char message[]) = 0; - virtual bool InitiateServer( unsigned short port ) { return false; }; - virtual int Listen() { return -1; }; - virtual bool Connect( unsigned short port, const char serverName[] ) { return false; }; + + public: + virtual void Disconnect() = 0; + virtual bool Send( const char message[] ) = 0; + virtual int Recieve(char message[]) = 0; + virtual bool InitiateServer( unsigned short port ) { return false; }; + virtual int Listen() { return -1; }; + virtual bool Connect( unsigned short port, const char serverName[] ) { return false; }; }; } } diff --git a/Code/Network/NetworkDependencies/ITranslate.h b/Code/Network/NetworkDependencies/ITranslate.h new file mode 100644 index 00000000..e974df54 --- /dev/null +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -0,0 +1,18 @@ +#ifndef NETWORK_DEPENDENCIES_I_TRANSLATE +#define NETWORK_DEPENDENCIES_I_TRANSLATE + +namespace Oyster +{ + namespace Network + { + class ITranslate + { + + public: + virtual char* Translate (const Protocols::ProtocolHeader &header ) = 0; + virtual Protocols::ProtocolHeader& Translate ( char message[] ) = 0; + + }; + } +} +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index 4c42ba1d..4413823d 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -153,10 +153,14 @@ + + + + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index 57da6b71..ac82be77 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -21,6 +21,9 @@ Source Files + + Source Files + @@ -29,5 +32,14 @@ Header Files + + Header Files + + + Header Files + + + Header Files + \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h new file mode 100644 index 00000000..962c3602 --- /dev/null +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -0,0 +1,35 @@ +#include "string"; + +namespace Oyster +{ + namespace Network + { + namespace Protocols + { + enum PackageType + { + package_type_header, + package_type_test, + package_type_input, + package_type_update_position + + }; + + + struct ProtocolHeader + { + int size; + int packageType; + int clientID; + + ProtocolHeader() { this->packageType = package_type_header; } + }; + + struct ProtocolTest : public ProtocolHeader + { + std::string textMessage; + ProtocolTest() { this->packageType = package_type_test; } + }; + } + } +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp new file mode 100644 index 00000000..0fad1b06 --- /dev/null +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -0,0 +1,50 @@ +//#include "Translator.h" +// +//using namespace Oyster::Network; +//using namespace ::Protocols; +//using namespace ::Messages; +// +//char* Translate ( const ProtocolHeader &header ) +//{ +// MessageHeader *message; +// +// switch(header.packageType) +// { +// +// case package_type_header: +// message = new MessageHeader(); +// break; +// +// case package_type_test: +// message = new MessageTest(); +// break; +// } +// +// message->Translate(header); +// return message->GetMsg(); +//} +// +//ProtocolHeader& Translator::Translate( char msg[] ) +//{ +// ProtocolHeader header; +// MessageHeader *message = new MessageHeader(); +// +// header = message->translate(message); +// +// switch(header.packageType) +// { +// +// case package_type_header: +// message = new MessageHeader(); +// break; +// +// case package_type_test: +// message = new MessageTest(); +// break; +// } +// +// message->Translate(msg); +// return message->GetProtocol(); +//} + + diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h new file mode 100644 index 00000000..866ae932 --- /dev/null +++ b/Code/Network/NetworkDependencies/Translator.h @@ -0,0 +1,27 @@ +//#ifndef NETWORK_DEPENDENCIES_TRANSLATOR_H +//#define NETWORK_DEPENDENCIES_TRANSLATOR_H +// +////#include "MessageHeader.h" +//#include "Protocols.h" +//#include "ITranslate.h" +// +//namespace Oyster +//{ +// namespace Network +// { +// namespace Messages +// { +// class Translator +// { +// public: +// Translator (){}; +// ~Translator(){}; +// +// char* Translate (const Protocols::ProtocolHeader &header ); +// Protocols::ProtocolHeader& Translate ( char msg[] ); +// }; +// } +// } +//} +// +//#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/Client.cpp b/Code/Network/OysterNetworkClient/Client.cpp index a947beea..a32f0996 100644 --- a/Code/Network/OysterNetworkClient/Client.cpp +++ b/Code/Network/OysterNetworkClient/Client.cpp @@ -1,5 +1,7 @@ #include "Client.h" +using namespace Oyster::Network::Client; + Client::Client() { connection = new Connection(); diff --git a/Code/Network/OysterNetworkClient/Client.h b/Code/Network/OysterNetworkClient/Client.h index 1fd9f1f6..a6042fa0 100644 --- a/Code/Network/OysterNetworkClient/Client.h +++ b/Code/Network/OysterNetworkClient/Client.h @@ -7,20 +7,28 @@ #include "../NetworkDependencies/Connection.h" -class Client +namespace Oyster { -public: - Client(); - ~Client(); + namespace Network + { + namespace Client + { + class Client + { + public: + Client(); + ~Client(); - bool Connect(unsigned int port, char filename[]); + bool Connect(unsigned int port, char filename[]); - void Send(char msg[]); - void Recv(char msg[]); + void Send(char msg[]); + void Recv(char msg[]); -private: - Connection* connection; - -}; + private: + ::Oyster::Network::Connection* connection; + }; + } + } +} #endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index cc9a786f..a6002d0a 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -2,6 +2,7 @@ #include "Client.h" #include using namespace std; +using namespace Oyster::Network::Client; #pragma comment(lib, "ws2_32.lib") void ShutdownSockets(); diff --git a/Code/Network/OysterNetworkServer/Client.cpp b/Code/Network/OysterNetworkServer/Client.cpp index 50ce3b8c..f86d37b8 100644 --- a/Code/Network/OysterNetworkServer/Client.cpp +++ b/Code/Network/OysterNetworkServer/Client.cpp @@ -1,5 +1,7 @@ #include "Client.h" +using namespace Oyster::Network::Server; + Client::Client(unsigned int socket) { connection = new Connection(socket); diff --git a/Code/Network/OysterNetworkServer/Client.h b/Code/Network/OysterNetworkServer/Client.h index 3c29c620..8c25ec45 100644 --- a/Code/Network/OysterNetworkServer/Client.h +++ b/Code/Network/OysterNetworkServer/Client.h @@ -7,19 +7,29 @@ #include "../NetworkDependencies/Connection.h" -class Client +namespace Oyster { -public: - Client(unsigned int socket); - ~Client(); + namespace Network + { + namespace Server + { + class Client + { - void Send(char buffer[]); - void Recv(char buffer[]); + public: + Client(unsigned int socket); + ~Client(); + + void Send(char buffer[]); + void Recv(char buffer[]); -private: - Connection* connection; + private: + ::Oyster::Network::Connection* connection; + }; + } + } }; #endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Listener.cpp b/Code/Network/OysterNetworkServer/Listener.cpp index 7b340441..5bda043f 100644 --- a/Code/Network/OysterNetworkServer/Listener.cpp +++ b/Code/Network/OysterNetworkServer/Listener.cpp @@ -1,5 +1,7 @@ #include "Listener.h" +using namespace Oyster::Network; + Listener::Listener() { diff --git a/Code/Network/OysterNetworkServer/Listener.h b/Code/Network/OysterNetworkServer/Listener.h index 8e5f99b7..d91fb98b 100644 --- a/Code/Network/OysterNetworkServer/Listener.h +++ b/Code/Network/OysterNetworkServer/Listener.h @@ -18,7 +18,7 @@ public: int Accept(); private: - Connection* connection; + ::Oyster::Network::Connection* connection; }; diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 4fbe8ece..e531798e 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -3,6 +3,7 @@ #include "Listener.h" #include "Client.h" using namespace std; +using namespace Oyster::Network::Server; #pragma comment(lib, "ws2_32.lib") From 87e1cf0436c1561b9d8c6f31cca03e898411f0ae Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Thu, 21 Nov 2013 13:42:38 +0100 Subject: [PATCH 14/67] Added Message base class Packing functions, MessageHeader; MessageTest, --- .../Messages/MessageHeader.cpp | 65 +++ .../Messages/MessageHeader.h | 46 ++ .../Messages/MessageTest.cpp | 26 + .../Messages/MessageTest.h | 32 ++ .../NetworkDependencies.vcxproj | 8 +- .../NetworkDependencies.vcxproj.filters | 18 + Code/Network/NetworkDependencies/Packing.cpp | 470 ++++++++++++++++++ Code/Network/NetworkDependencies/Packing.h | 106 ++++ Code/Network/OysterNetworkClient/Client.h | 2 +- Code/Network/OysterNetworkServer/Client.h | 3 +- Code/Network/OysterNetworkServer/IListener.h | 2 +- Code/Network/OysterNetworkServer/Listener.h | 2 +- .../OysterNetworkServer/ServerMain.cpp | 14 +- 13 files changed, 785 insertions(+), 9 deletions(-) create mode 100644 Code/Network/NetworkDependencies/Messages/MessageHeader.cpp create mode 100644 Code/Network/NetworkDependencies/Messages/MessageHeader.h create mode 100644 Code/Network/NetworkDependencies/Messages/MessageTest.cpp create mode 100644 Code/Network/NetworkDependencies/Messages/MessageTest.h create mode 100644 Code/Network/NetworkDependencies/Packing.cpp create mode 100644 Code/Network/NetworkDependencies/Packing.h diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp new file mode 100644 index 00000000..16468bd7 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -0,0 +1,65 @@ +#include "MessageHeader.h" +#include "../Packing.h" + +using namespace Oyster::Network::Messages; +using namespace Oyster::Network::Packing; + +MessageHeader::MessageHeader() +{ + size = 0; + msg = new unsigned char[1024]; +} + +MessageHeader::~MessageHeader() +{ + delete[] msg; +} + +void MessageHeader::Translate(/*Message& msg*/) +{ + size = 0; + + AddInt(4); + AddInt(5); + AddInt(6); +} + +void MessageHeader::Translate(unsigned char message[]) +{ + size = 0; + + int i = GetInt(message); + int j = GetInt(message); + int k = GetInt(message); +} + +unsigned char* MessageHeader::GetMsg() +{ + return msg; +} + +void MessageHeader::AddInt(int i) +{ + Pack(&msg[size], i); + size += 4; +} + +void MessageHeader::AddStr(std::string str) +{ + Pack(&msg[size], str); + size += 2 + str.length(); +} + +int MessageHeader::GetInt(unsigned char message[]) +{ + int i = Unpacki(&message[size]); + size += 4; + return i; +} + +std::string MessageHeader::GetStr(unsigned char message[]) +{ + std::string std = UnpackStr(&message[size]); + size += 2 + std.length(); + return std; +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.h b/Code/Network/NetworkDependencies/Messages/MessageHeader.h new file mode 100644 index 00000000..d6d79597 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.h @@ -0,0 +1,46 @@ +#ifndef NETWORK_DEPENDENCIES_MESSAGE_HEADER_H +#define NETWORK_DEPENDENCIES_MESSAGE_HEADER_H + +///////////////////////////////////////////////////////////////////// +// Created by Pontus Fransson 2013 +///////////////////////////////////////////////////////////////////// + +#include + +namespace Oyster +{ + namespace Network + { + namespace Messages + { + class MessageHeader + { + public: + MessageHeader(); + virtual ~MessageHeader(); + + virtual void Translate(/*Message& msg*/); + virtual void Translate(unsigned char message[]); + + unsigned char* GetMsg(); + + protected: + //Add variables to messages + void AddInt(int i); + void AddStr(std::string str); + + //Get variables from message + int GetInt(unsigned char message[]); + std::string GetStr(unsigned char message[]); + + private: + static const int max_message_length = 1024; + unsigned char* msg; + int size; + + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp new file mode 100644 index 00000000..ba15c464 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp @@ -0,0 +1,26 @@ +#include "MessageTest.h" + +using namespace Oyster::Network::Messages; + +MessageTest::MessageTest() +{ + +} + +MessageTest::~MessageTest() +{ +} + +void MessageTest::Translate() +{ + MessageHeader::Translate(); + + AddStr("Hej hur mår du idag?"); +} + +void MessageTest::Translate(unsigned char message[]) +{ + MessageHeader::Translate(message); + + std::string str = GetStr(message); +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.h b/Code/Network/NetworkDependencies/Messages/MessageTest.h new file mode 100644 index 00000000..8aebda05 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.h @@ -0,0 +1,32 @@ +#ifndef NETWORK_DEPENDENCIES_MESSAGE_TEST_H +#define NETWORK_DEPENDENCIES_MESSAGE_TEST_H + +///////////////////////////////////////////////////////////////////// +// Created by Pontus Fransson 2013 +///////////////////////////////////////////////////////////////////// + +#include "MessageHeader.h" + +namespace Oyster +{ + namespace Network + { + namespace Messages + { + class MessageTest : public MessageHeader + { + public: + MessageTest(); + virtual ~MessageTest(); + + virtual void Translate(); + virtual void Translate(unsigned char message[]); + + private: + + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index 4c42ba1d..2be0652e 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -27,7 +27,7 @@ StaticLibrary true v110 - MultiByte + Unicode StaticLibrary @@ -153,10 +153,16 @@ + + + + + + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index 57da6b71..0547fb8c 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -21,6 +21,15 @@ Source Files + + Source Files + + + Source Files + + + Source Files + @@ -29,5 +38,14 @@ Header Files + + Header Files + + + Header Files + + + Header Files + \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Packing.cpp b/Code/Network/NetworkDependencies/Packing.cpp new file mode 100644 index 00000000..6c6edfda --- /dev/null +++ b/Code/Network/NetworkDependencies/Packing.cpp @@ -0,0 +1,470 @@ +#include "Packing.h" + +/*************************** + Packing +***************************/ + +#include + +namespace Oyster +{ + namespace Network + { + namespace Packing + { + //bool (1-bit) + void Pack(unsigned char buffer[], bool i) + { + *buffer++ = i; + } + + //char (8-bit) + void Pack(unsigned char buffer[], char i) + { + *buffer++ = i; + } + + void Pack(unsigned char buffer[], unsigned char i) + { + *buffer++ = i; + } + + //short (16-bit) + void Pack(unsigned char buffer[], short i) + { + *buffer++ = i >> 8; + *buffer++ = i; + } + + void Pack(unsigned char buffer[], unsigned short i) + { + *buffer++ = i >> 8; + *buffer++ = i; + } + + //int (32-bit) + void Pack(unsigned char buffer[], int i) + { + *buffer++ = i >> 24; + *buffer++ = i >> 16; + *buffer++ = i >> 8; + *buffer++ = i; + } + + void Pack(unsigned char buffer[], unsigned int i) + { + *buffer++ = i >> 24; + *buffer++ = i >> 16; + *buffer++ = i >> 8; + *buffer++ = i; + } + + //__int64 (64-bit) + void Pack(unsigned char buffer[], __int64 i) + { + *buffer++ = i >> 56; + *buffer++ = i >> 48; + *buffer++ = i >> 40; + *buffer++ = i >> 32; + *buffer++ = i >> 24; + *buffer++ = i >> 16; + *buffer++ = i >> 8; + *buffer++ = i; + } + + void Pack(unsigned char buffer[], unsigned __int64 i) + { + *buffer++ = i >> 56; + *buffer++ = i >> 48; + *buffer++ = i >> 40; + *buffer++ = i >> 32; + *buffer++ = i >> 24; + *buffer++ = i >> 16; + *buffer++ = i >> 8; + *buffer++ = i; + } + + //floating point (32, 64-bit) + void Pack(unsigned char buffer[], float i) + { + int tempFloat = Pack754(i, 32, 8); + Pack(buffer, tempFloat); + } + + void Pack(unsigned char buffer[], double i) + { + __int64 tempDouble = Pack754(i, 64, 11); + Pack(buffer, tempDouble); + } + + //string + void Pack(unsigned char buffer[], char str[]) + { + short len = strlen(str); + Pack(buffer, len); + buffer += 2; + memcpy(buffer, str, len); + } + + void Pack(unsigned char buffer[], std::string& str) + { + short len = str.length(); + Pack(buffer, len); + buffer += 2; + memcpy(buffer, str.c_str(), len); + } + + unsigned __int64 Pack754(long double f, unsigned bits, unsigned expbits) + { + long double fnorm; + int shift; + long long sign, exp, significand; + unsigned significandbits = bits - expbits - 1; // -1 for sign bit + + if (f == 0.0) + return 0; // get this special case out of the way + + // check sign and begin normalization + if (f < 0) + { + sign = 1; + fnorm = -f; + } + else + { + sign = 0; + fnorm = f; + } + + // get the normalized form of f and track the exponent + shift = 0; + while(fnorm >= 2.0) + { + fnorm /= 2.0; + shift++; + } + + while(fnorm < 1.0) + { + fnorm *= 2.0; + shift--; + } + + fnorm = fnorm - 1.0; + + // calculate the binary form (non-float) of the significand data + significand = fnorm * ((1LL << significandbits) + 0.5f); + + // get the biased exponent + exp = shift + ((1 << (expbits - 1)) - 1); // shift + bias + + // return the final answer + return (sign << (bits - 1)) | (exp << (bits - expbits - 1)) | significand; + } + + /****************************** + Unpacking + ******************************/ + + //bool (1-bit) + bool Unpackb(unsigned char buffer[]) + { + return (bool)buffer; + } + + //char (8-bit) + char Unpackc(unsigned char buffer[]) + { + if(*buffer <= 0x7f) + { + return *buffer; + } + else + { + return (-1 - (unsigned char)(0xffu - *buffer)); + } + } + + unsigned char UnpackC(unsigned char buffer[]) + { + return *buffer; + } + + //short (16-bit) + short Unpacks(unsigned char buffer[]) + { + short i = ((short)buffer[0] << 8) | buffer[1]; + + if(i > 0x7fffu) + { + i = -1 - (unsigned short)(0xffffu - i); + } + + return i; + } + + unsigned short UnpackS(unsigned char buffer[]) + { + return ((unsigned int)buffer[0] << 8) | buffer[1]; + } + + //int (32-bit) + int Unpacki(unsigned char buffer[]) + { + int i = ((int)buffer[0] << 24) | + ((int)buffer[1] << 16) | + ((int)buffer[2] << 8) | + ((int)buffer[3]); + + if(i > 0x7fffffffu) + { + i = -1 - (int)(0xffffffffu - i); + } + + return i; + } + + unsigned int UnpackI(unsigned char buffer[]) + { + return ((unsigned int)buffer[0] << 24) | + ((unsigned int)buffer[1] << 16) | + ((unsigned int)buffer[2] << 8) | + ((unsigned int)buffer[3]); + } + + //__int64 (64-bit) + __int64 Unpacki64(unsigned char buffer[]) + { + __int64 i = ((__int64)buffer[0] << 56) | + ((__int64)buffer[1] << 48) | + ((__int64)buffer[2] << 40) | + ((__int64)buffer[3] << 32) | + ((__int64)buffer[4] << 24) | + ((__int64)buffer[5] << 16) | + ((__int64)buffer[6] << 8) | + (buffer[7]); + + if(i > 0x7fffffffffffffffu) + { + i = -1 - (__int64)(0xffffffffffffffffu - i); + } + + return i; + } + + unsigned __int64 UnpackI64(unsigned char buffer[]) + { + + return ((__int64)buffer[0] << 56) | + ((__int64)buffer[1] << 48) | + ((__int64)buffer[2] << 40) | + ((__int64)buffer[3] << 32) | + ((__int64)buffer[4] << 24) | + ((__int64)buffer[5] << 16) | + ((__int64)buffer[6] << 8) | + ((__int64)buffer[7]); + } + + //floating point (32, 64-bit) + float Unpackf(unsigned char buffer[]) + { + int tempFloat = Unpacki(buffer); + return Unpack754(tempFloat, 32, 8); + } + + double Unpackd(unsigned char buffer[]) + { + __int64 tempDouble = Unpacki64(buffer); + return Unpack754(tempDouble, 64, 11); + } + + //string + std::string UnpackStr(unsigned char buffer[]) + { + short len = UnpackS(buffer); + std::string temp; + temp.resize(len); + + buffer += 2; + for(int i = 0; i < len; i++) + { + temp[i] = buffer[i]; + } + + return temp; + } + + long double Unpack754(unsigned __int64 i, unsigned bits, unsigned expbits) + { + long double result; + long long shift; + unsigned bias; + unsigned significandbits = bits - expbits - 1; // -1 for sign bit + + if (i == 0) + return 0.0; + + // pull the significand + result = (i&((1LL << significandbits) - 1)); // mask + result /= (1LL << significandbits); // convert back to float + result += 1.0f; // add the one back on + + // deal with the exponent + bias = (1 << (expbits - 1)) - 1; + shift = ((i >> significandbits) & ((1LL << expbits) - 1)) - bias; + while(shift > 0) + { + result *= 2.0; + shift--; + } + while(shift < 0) + { + result /= 2.0; + shift++; + } + + // sign it + result *= (i >> (bits - 1)) & 1 ? -1.0 : 1.0; + + return result; + } + } + } +} + +/* +int32_t pack(unsigned char* buffer, char* format, ...) +{ + va_list ap; + int16_t h; + int32_t l; + int8_t c; + float f; + double d; + char* s; + int32_t size = 0, len; + + va_start(ap, format); + + for(; *format != '\0'; format++) + { + switch(*format) + { + case 'h': // 16-bit + size += 2; + h = (int16_t)va_arg(ap, int); + packi16(buffer, h); + buffer += 2; + break; + case 'l': // 32-bit + size += 4; + l = va_arg(ap, int32_t); + packi32(buffer, l); + buffer += 4; + break; + case 'c': // 8-bit + size += 1; + c = (int8_t)va_arg(ap, int); + *buffer++ = (c >> 0)&0xff; + break; + case 'f': // float (32-bit) + size += 4; + f = (float)va_arg(ap, double); + //l = pack754(f, 32, 8); + packi32(buffer, l); + buffer += 4; + break; + case 'd': // double (64-bit) + size += 8; + d = (float)va_arg(ap, double); + //l = pack754(f, 64, 11); + packi32(buffer, l); + buffer += 4; + break; + case 's': // string + s = va_arg(ap, char*); + len = strlen(s); + size += len + 2; + packi16(buffer, len); + buffer += 2; + memcpy(buffer, s, len); + buffer += len; + break; + } + } + + va_end(ap); + + return size; +} +*/ + +/* +void unpack(unsigned char* buffer, char* format, ...) +{ + va_list ap; + int16_t* h; + int32_t* l; + int32_t pf; + int64_t pd; + int8_t* c; + float* f; + double* d; + char* s; + int32_t len, count, maxstrlen = 0; + + va_start(ap, format); + + for(; *format != '\0'; format++) + { + switch(*format) + { + case 'h': // 16-bit + h = va_arg(ap, int16_t*); + *h = unpacki16(buffer); + buffer += 2; + break; + case 'l': // 32-bit + l = va_arg(ap, int32_t*); + *l = unpacki32(buffer); + buffer += 4; + break; + case 'c': // 8-bit + c = va_arg(ap, int8_t*); + *c = *buffer++; + break; + case 'f': // float + f = va_arg(ap, float*); + pf = unpacki32(buffer); + buffer += 4; + //*f = unpack754(pf, 32, 8); + break; + case 'd': // double (64-bit) + d = va_arg(ap, double*); + pd = unpacki64(buffer); + buffer += 8; + //*d = unpack754(pf, 64, 11); + break; + case 's': // string + s = va_arg(ap, char*); + len = unpacki16(buffer); + buffer += 2; + if (maxstrlen > 0 && len > maxstrlen) count = maxstrlen - 1; + else count = len; + memcpy(s, buffer, count); + s[count] = '\0'; + buffer += len; + break; + default: + if (isdigit(*format)) // track max str len + { + maxstrlen = maxstrlen * 10 + (*format-'0'); + } + } + + if(!isdigit(*format)) + maxstrlen = 0; + } + + va_end(ap); +}*/ \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Packing.h b/Code/Network/NetworkDependencies/Packing.h new file mode 100644 index 00000000..8339ba68 --- /dev/null +++ b/Code/Network/NetworkDependencies/Packing.h @@ -0,0 +1,106 @@ +#ifndef PACKING_H +#define PACKING_H + +///////////////////////////////////////////////////////////////////// +// Created by Pontus Fransson 2013 +///////////////////////////////////////////////////////////////////// + +#include + +/****************************** + Packing +******************************/ +namespace Oyster +{ + namespace Network + { + namespace Packing + { + //bool (1-bit) + void Pack(unsigned char buffer[], bool i); + + //char (8-bit) + void Pack(unsigned char buffer[], char i); + void Pack(unsigned char buffer[], unsigned char i); // unsigned + + //short (16-bit) + void Pack(unsigned char buffer[], short i); + void Pack(unsigned char buffer[], unsigned short i); // unsigned + + //int (32-bit) + void Pack(unsigned char buffer[], int i); + void Pack(unsigned char buffer[], unsigned int i); // unsigned + + //__int64 (64-bit) + void Pack(unsigned char buffer[], __int64 i); + void Pack(unsigned char buffer[], unsigned __int64 i); // unsigned + + //floating point (32, 64-bit) + void Pack(unsigned char buffer[], float i); + void Pack(unsigned char buffer[], double i); + + //string + void Pack(unsigned char buffer[], char str[]); + void Pack(unsigned char buffer[], std::string& str); + + unsigned __int64 Pack754(long double f, unsigned bits, unsigned expbits); + + /****************************** + Unpacking + ******************************/ + + //bool (1-bit) + bool Unpackb(unsigned char buffer[]); + + //char (8-bit) + char Unpackc(unsigned char buffer[]); + unsigned char UnpackC(unsigned char buffer[]); // unsigned + + //short (16-bit) + short Unpacks(unsigned char buffer[]); + unsigned short UnpackS(unsigned char buffer[]); // unsigned + + //int (32-bit) + int Unpacki(unsigned char buffer[]); + unsigned int UnpackI(unsigned char buffer[]); // unsigned + + //__int64 (64-bit) + __int64 Unpacki64(unsigned char buffer[]); + unsigned __int64 UnpackI64(unsigned char buffer[]); // unsigned + + //floating point (32, 64-bit) + float Unpackf(unsigned char buffer[]); + double Unpackd(unsigned char buffer[]); + + //string + std::string UnpackStr(unsigned char buffer[]); + + long double Unpack754(unsigned __int64 i, unsigned bits, unsigned expbits); + } + } +} + + +//int32_t pack(unsigned char* buffer, char* format, ...); + +//void unpack(unsigned char* buffer, char* format, ...); + + +/*********************************************** +* This table is used for naming pack/unpack functions. +* It's also used to identify types in the 'format' string in function pack()/unpack() +* +* bits |signed unsigned float string +* -----+---------------------------------- +* 1 | b +* 8 | c C +* 16 | s S f +* 32 | i I d +* 64 | q Q g +* - | str +* +* (16-bit unsigned length is automatically added in front of strings) +* +*/ + +#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/Client.h b/Code/Network/OysterNetworkClient/Client.h index 1fd9f1f6..d7a50e00 100644 --- a/Code/Network/OysterNetworkClient/Client.h +++ b/Code/Network/OysterNetworkClient/Client.h @@ -2,7 +2,7 @@ #define NETWORK_CLIENT_CLIENT_H ///////////////////////////////////////////////////////////////////// -// Created by Pontus 2013 +// Created by Pontus Fransson 2013 ///////////////////////////////////////////////////////////////////// #include "../NetworkDependencies/Connection.h" diff --git a/Code/Network/OysterNetworkServer/Client.h b/Code/Network/OysterNetworkServer/Client.h index 3c29c620..2b151af1 100644 --- a/Code/Network/OysterNetworkServer/Client.h +++ b/Code/Network/OysterNetworkServer/Client.h @@ -2,7 +2,7 @@ #define NETWORK_SERVER_CLIENT_H ///////////////////////////////////////////////////////////////////// -// Created by Pontus 2013 +// Created by Pontus Fransson 2013 ///////////////////////////////////////////////////////////////////// #include "../NetworkDependencies/Connection.h" @@ -16,7 +16,6 @@ public: void Send(char buffer[]); void Recv(char buffer[]); - private: Connection* connection; diff --git a/Code/Network/OysterNetworkServer/IListener.h b/Code/Network/OysterNetworkServer/IListener.h index 9a427f29..93b7a935 100644 --- a/Code/Network/OysterNetworkServer/IListener.h +++ b/Code/Network/OysterNetworkServer/IListener.h @@ -2,7 +2,7 @@ #define NETWORK_SERVER_ILISTENER_H ///////////////////////////////////////////////////////////////////// -// Created by Pontus 2013 +// Created by Pontus Fransson 2013 ///////////////////////////////////////////////////////////////////// class IListener diff --git a/Code/Network/OysterNetworkServer/Listener.h b/Code/Network/OysterNetworkServer/Listener.h index 8e5f99b7..316491e2 100644 --- a/Code/Network/OysterNetworkServer/Listener.h +++ b/Code/Network/OysterNetworkServer/Listener.h @@ -2,7 +2,7 @@ #define NETWORK_SERVER_LISTENER_H ///////////////////////////////////////////////////////////////////// -// Created by Pontus 2013 +// Created by Pontus Fransson 2013 ///////////////////////////////////////////////////////////////////// #include "IListener.h" diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 4fbe8ece..b63ea190 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -9,11 +9,19 @@ using namespace std; void ShutdownSockets(); bool InitSockets(); +#include "../NetworkDependencies/Messages/MessageTest.h" +using namespace Oyster::Network::Messages; + int main() { cout << "Server" << endl; - char recvBuffer[255]; + unsigned char* recvBuffer = new unsigned char[255]; + + MessageTest msg; + msg.Translate(); + recvBuffer = msg.GetMsg(); + msg.Translate(recvBuffer); if(!InitSockets()) { @@ -39,13 +47,13 @@ int main() while(1) { - client1.Recv(recvBuffer); + /*client1.Recv(recvBuffer); cout << "Client1: " << recvBuffer << endl; client2.Send(recvBuffer); client2.Recv(recvBuffer); cout << "Client2: " << recvBuffer << endl; - client1.Send(recvBuffer); + client1.Send(recvBuffer);*/ } ShutdownSockets(); From dcf456ce6d67ec2c191902ac86faac884ca8f927 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Thu, 21 Nov 2013 14:49:30 +0100 Subject: [PATCH 15/67] Fixed implementation of Translator --- Code/Network/NetworkDependencies/ITranslate.h | 4 +- .../Messages/MessageHeader.cpp | 17 ++-- .../Messages/MessageHeader.h | 5 +- .../Messages/MessageTest.cpp | 13 +-- .../Messages/MessageTest.h | 4 +- .../Messages/MessagesInclude.h | 7 ++ .../NetworkDependencies.vcxproj | 1 + .../NetworkDependencies.vcxproj.filters | 67 +++---------- Code/Network/NetworkDependencies/Protocols.h | 10 +- .../NetworkDependencies/Translator.cpp | 98 ++++++++++--------- Code/Network/NetworkDependencies/Translator.h | 51 +++++----- .../OysterNetworkServer/ServerMain.cpp | 31 ++++-- 12 files changed, 150 insertions(+), 158 deletions(-) create mode 100644 Code/Network/NetworkDependencies/Messages/MessagesInclude.h diff --git a/Code/Network/NetworkDependencies/ITranslate.h b/Code/Network/NetworkDependencies/ITranslate.h index e974df54..6f24cd72 100644 --- a/Code/Network/NetworkDependencies/ITranslate.h +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -9,8 +9,8 @@ namespace Oyster { public: - virtual char* Translate (const Protocols::ProtocolHeader &header ) = 0; - virtual Protocols::ProtocolHeader& Translate ( char message[] ) = 0; + virtual unsigned char* Translate (Protocols::ProtocolHeader &header ) = 0; + virtual Protocols::ProtocolHeader& Translate ( unsigned char message[] ) = 0; }; } diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp index 16468bd7..cf2d2b22 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -3,6 +3,7 @@ using namespace Oyster::Network::Messages; using namespace Oyster::Network::Packing; +using namespace Oyster::Network::Protocols; MessageHeader::MessageHeader() { @@ -15,22 +16,22 @@ MessageHeader::~MessageHeader() delete[] msg; } -void MessageHeader::Translate(/*Message& msg*/) +void MessageHeader::Translate(ProtocolHeader& header) { size = 0; - AddInt(4); - AddInt(5); - AddInt(6); + AddInt(header.clientID); + AddInt(header.packageType); + AddInt(header.size); } -void MessageHeader::Translate(unsigned char message[]) +void MessageHeader::Translate(unsigned char message[], ProtocolHeader& header) { size = 0; - int i = GetInt(message); - int j = GetInt(message); - int k = GetInt(message); + header.clientID = GetInt(message); + header.packageType = GetInt(message); + header.size = GetInt(message); } unsigned char* MessageHeader::GetMsg() diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.h b/Code/Network/NetworkDependencies/Messages/MessageHeader.h index d6d79597..0aa22dff 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.h +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.h @@ -6,6 +6,7 @@ ///////////////////////////////////////////////////////////////////// #include +#include "../Protocols.h" namespace Oyster { @@ -19,8 +20,8 @@ namespace Oyster MessageHeader(); virtual ~MessageHeader(); - virtual void Translate(/*Message& msg*/); - virtual void Translate(unsigned char message[]); + virtual void Translate(Protocols::ProtocolHeader& header); + virtual void Translate(unsigned char message[], Protocols::ProtocolHeader& header); unsigned char* GetMsg(); diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp index ba15c464..89fb2911 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp @@ -1,6 +1,7 @@ #include "MessageTest.h" using namespace Oyster::Network::Messages; +using namespace Oyster::Network::Protocols; MessageTest::MessageTest() { @@ -11,16 +12,16 @@ MessageTest::~MessageTest() { } -void MessageTest::Translate() +void MessageTest::Translate(ProtocolHeader& header) { - MessageHeader::Translate(); + MessageHeader::Translate(header); - AddStr("Hej hur mår du idag?"); + AddStr(static_cast(&header)->textMessage); } -void MessageTest::Translate(unsigned char message[]) +void MessageTest::Translate(unsigned char message[], ProtocolHeader& header) { - MessageHeader::Translate(message); + MessageHeader::Translate(message, header); - std::string str = GetStr(message); + static_cast(&header)->textMessage = GetStr(message); } \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.h b/Code/Network/NetworkDependencies/Messages/MessageTest.h index 8aebda05..e01847c9 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageTest.h +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.h @@ -19,8 +19,8 @@ namespace Oyster MessageTest(); virtual ~MessageTest(); - virtual void Translate(); - virtual void Translate(unsigned char message[]); + virtual void Translate(Protocols::ProtocolHeader& header); + virtual void Translate(unsigned char message[], Protocols::ProtocolHeader& header); private: diff --git a/Code/Network/NetworkDependencies/Messages/MessagesInclude.h b/Code/Network/NetworkDependencies/Messages/MessagesInclude.h new file mode 100644 index 00000000..4e1980ba --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessagesInclude.h @@ -0,0 +1,7 @@ +#ifndef NETWORK_DEPENDENCIES_MESSAGES_INCLUDE_H +#define NETWORK_DEPENDENCIES_MESSAGES_INCLUDE_H + +#include "MessageHeader.h" +#include "MessageTest.h" + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index ff978779..8c215717 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -162,6 +162,7 @@ + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index 7ff2f960..0bb7c6e2 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -1,59 +1,22 @@  - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - + + + + + + - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - - Header Files - - - Header Files - - - Header Files - + + + + + + + + + \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h index 962c3602..3f783790 100644 --- a/Code/Network/NetworkDependencies/Protocols.h +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -1,4 +1,7 @@ -#include "string"; +#ifndef NETWORK_DEPENDENCIES_PROTOCOLS_H +#define NETWORK_DEPENDENCIES_PROTOCOLS_H + +#include namespace Oyster { @@ -12,7 +15,6 @@ namespace Oyster package_type_test, package_type_input, package_type_update_position - }; @@ -32,4 +34,6 @@ namespace Oyster }; } } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp index 0fad1b06..30e1e273 100644 --- a/Code/Network/NetworkDependencies/Translator.cpp +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -1,50 +1,52 @@ -//#include "Translator.h" -// -//using namespace Oyster::Network; -//using namespace ::Protocols; -//using namespace ::Messages; -// -//char* Translate ( const ProtocolHeader &header ) -//{ -// MessageHeader *message; -// -// switch(header.packageType) -// { -// -// case package_type_header: -// message = new MessageHeader(); -// break; -// -// case package_type_test: -// message = new MessageTest(); -// break; -// } -// -// message->Translate(header); -// return message->GetMsg(); -//} -// -//ProtocolHeader& Translator::Translate( char msg[] ) -//{ -// ProtocolHeader header; -// MessageHeader *message = new MessageHeader(); -// -// header = message->translate(message); -// -// switch(header.packageType) -// { -// -// case package_type_header: -// message = new MessageHeader(); -// break; -// -// case package_type_test: -// message = new MessageTest(); -// break; -// } -// -// message->Translate(msg); -// return message->GetProtocol(); -//} +#include "Translator.h" + +using namespace Oyster::Network; +using namespace ::Protocols; +using namespace ::Messages; + +unsigned char* Translator::Translate( ProtocolHeader &header ) +{ + MessageHeader *message = NULL; + + switch(header.packageType) + { + + case package_type_header: + message = new MessageHeader(); + break; + + case package_type_test: + message = new MessageTest(); + break; + } + + message->Translate(header); + + return message->GetMsg(); +} + +ProtocolHeader& Translator::Translate(unsigned char msg[] ) +{ + ProtocolHeader* header = new ProtocolHeader(); + MessageHeader *message = new MessageHeader(); + + message->Translate(msg, *header); + + switch(header->packageType) + { + case package_type_header: + message = new MessageHeader(); + header = new ProtocolHeader(); + break; + + case package_type_test: + message = new MessageTest(); + header = new ProtocolTest(); + break; + } + + message->Translate(msg, *header); + return *header; +} diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h index 866ae932..c9eb7362 100644 --- a/Code/Network/NetworkDependencies/Translator.h +++ b/Code/Network/NetworkDependencies/Translator.h @@ -1,27 +1,24 @@ -//#ifndef NETWORK_DEPENDENCIES_TRANSLATOR_H -//#define NETWORK_DEPENDENCIES_TRANSLATOR_H -// -////#include "MessageHeader.h" -//#include "Protocols.h" -//#include "ITranslate.h" -// -//namespace Oyster -//{ -// namespace Network -// { -// namespace Messages -// { -// class Translator -// { -// public: -// Translator (){}; -// ~Translator(){}; -// -// char* Translate (const Protocols::ProtocolHeader &header ); -// Protocols::ProtocolHeader& Translate ( char msg[] ); -// }; -// } -// } -//} -// -//#endif \ No newline at end of file +#ifndef NETWORK_DEPENDENCIES_TRANSLATOR_H +#define NETWORK_DEPENDENCIES_TRANSLATOR_H + +#include "Messages/MessagesInclude.h" +#include "Protocols.h" +#include "ITranslate.h" + +namespace Oyster +{ + namespace Network + { + class Translator : public ITranslate + { + public: + Translator (){}; + ~Translator(){}; + + unsigned char* Translate (Protocols::ProtocolHeader &header ); + Protocols::ProtocolHeader& Translate (unsigned char msg[] ); + }; + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index e7bfcab6..a399dc62 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -10,19 +10,34 @@ using namespace Oyster::Network::Server; void ShutdownSockets(); bool InitSockets(); -#include "../NetworkDependencies/Messages/MessageTest.h" -using namespace Oyster::Network::Messages; +#include "../NetworkDependencies/Translator.h" +using namespace Oyster::Network; +using namespace ::Protocols; int main() { + unsigned char* recvBuffer; + Translator t; + ProtocolTest header; + header.clientID = 1; + header.packageType = package_type_test; + header.size = 12; + header.textMessage = "Hej"; + + recvBuffer = t.Translate(header); + + ProtocolHeader& asd = t.Translate(recvBuffer); + switch(asd.packageType) + { + case package_type_test: + + break; + } + cout << static_cast(&asd)->textMessage << endl; + + cout << "Server" << endl; - unsigned char* recvBuffer = new unsigned char[255]; - - MessageTest msg; - msg.Translate(); - recvBuffer = msg.GetMsg(); - msg.Translate(recvBuffer); if(!InitSockets()) { From 4142688f6c4a63aa97341205588ad6cace0f43af Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Fri, 22 Nov 2013 08:54:26 +0100 Subject: [PATCH 16/67] unsigned char instead of char and chat program with protocols --- .../NetworkDependencies/Connection.cpp | 21 +++---- Code/Network/NetworkDependencies/Connection.h | 9 ++- .../Network/NetworkDependencies/IConnection.h | 4 +- Code/Network/NetworkDependencies/Protocols.h | 8 +++ Code/Network/OysterNetworkClient/Client.cpp | 4 +- Code/Network/OysterNetworkClient/Client.h | 4 +- .../OysterNetworkClient/ClientMain.cpp | 56 ++++++++++++++----- Code/Network/OysterNetworkServer/Client.cpp | 4 +- Code/Network/OysterNetworkServer/Client.h | 4 +- .../OysterNetworkServer/ServerMain.cpp | 2 +- 10 files changed, 79 insertions(+), 37 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 8a2081c0..99cba856 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -26,8 +26,8 @@ bool Connection::Connect(unsigned short port , const char serverName[]) } - struct hostent *hostEntry; - if((hostEntry = gethostbyname(serverName)) == NULL) + struct hostent *hostEnt; + if((hostEnt = gethostbyname(serverName)) == NULL) { //couldn't find host return false; @@ -35,7 +35,7 @@ bool Connection::Connect(unsigned short port , const char serverName[]) struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(port); - server.sin_addr.s_addr = *(unsigned long*) hostEntry->h_addr; + server.sin_addr.s_addr = *(unsigned long*) hostEnt->h_addr; while(1) { @@ -77,7 +77,7 @@ bool Connection::InitiateServer(unsigned short port) return false; } - //not our Listen function! + //not our Listen function! its trying to keep our socket open for connections if(listen(mySocket, 5) == SOCKET_ERROR) { //"Listen failed! @@ -94,12 +94,13 @@ void Connection::Disconnect() closesocket(mySocket); } -bool Connection::Send(const char message[]) +bool Connection::Send(const unsigned char message[]) { int nBytes; - unsigned long messageSize = strlen(message); - - if((nBytes = send(mySocket, message , messageSize, 0)) == SOCKET_ERROR) + unsigned long messageSize = strlen((char*)message); + messageSize = 18; + nBytes = send(mySocket, (char*)message , messageSize, 0); + if(nBytes == SOCKET_ERROR) { //Send failed! return false; @@ -108,10 +109,10 @@ bool Connection::Send(const char message[]) return true; } -int Connection::Recieve(char message[]) +int Connection::Recieve(unsigned char message[]) { int nBytes; - nBytes = recv(mySocket, message , 255, 0); + nBytes = recv(mySocket, (char*)message , 255, 0); if(nBytes == SOCKET_ERROR) { //Recv failed diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index 0070fed6..109d761c 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -20,10 +20,13 @@ namespace Oyster ~Connection(); virtual bool Connect( unsigned short port , const char serverName[] ); - virtual bool InitiateServer( unsigned short port ); + virtual bool InitiateServer( unsigned short port ); + virtual void Disconnect(); - virtual bool Send(const char message[]); - virtual int Recieve(char message[]); + + virtual bool Send(const unsigned char message[]); + virtual int Recieve(unsigned char message[]); + virtual int Listen(); private: diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index 1443b781..91b7c7b4 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -14,8 +14,8 @@ namespace Oyster public: virtual void Disconnect() = 0; - virtual bool Send( const char message[] ) = 0; - virtual int Recieve(char message[]) = 0; + virtual bool Send( const unsigned char message[] ) = 0; + virtual int Recieve(unsigned char message[]) = 0; virtual bool InitiateServer( unsigned short port ) { return false; }; virtual int Listen() { return -1; }; virtual bool Connect( unsigned short port, const char serverName[] ) { return false; }; diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h index 3f783790..e0bb75a1 100644 --- a/Code/Network/NetworkDependencies/Protocols.h +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -32,6 +32,14 @@ namespace Oyster std::string textMessage; ProtocolTest() { this->packageType = package_type_test; } }; + /*struct Prutt + { + PackageType t; + union PRUTT + { + ProtocolTest *ptest, + }; + };*/ } } } diff --git a/Code/Network/OysterNetworkClient/Client.cpp b/Code/Network/OysterNetworkClient/Client.cpp index a32f0996..3569b7d4 100644 --- a/Code/Network/OysterNetworkClient/Client.cpp +++ b/Code/Network/OysterNetworkClient/Client.cpp @@ -19,12 +19,12 @@ bool Client::Connect(unsigned int port, char filename[]) return true; } -void Client::Send(char msg[]) +void Client::Send(unsigned char msg[]) { connection->Send(msg); } -void Client::Recv(char msg[]) +void Client::Recv(unsigned char msg[]) { connection->Recieve(msg); } \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/Client.h b/Code/Network/OysterNetworkClient/Client.h index e08d6348..a48e37d9 100644 --- a/Code/Network/OysterNetworkClient/Client.h +++ b/Code/Network/OysterNetworkClient/Client.h @@ -21,8 +21,8 @@ namespace Oyster bool Connect(unsigned int port, char filename[]); - void Send(char msg[]); - void Recv(char msg[]); + void Send(unsigned char msg[]); + void Recv(unsigned char msg[]); private: ::Oyster::Network::Connection* connection; diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index a6002d0a..5fa8fd0f 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -1,10 +1,14 @@ #include #include "Client.h" #include +#include "..\NetworkDependencies\Translator.h" + using namespace std; +using namespace Oyster::Network::Protocols;; using namespace Oyster::Network::Client; #pragma comment(lib, "ws2_32.lib") + void ShutdownSockets(); bool InitSockets(); void chat(Client client); @@ -23,7 +27,6 @@ int main() //Connect to server client.Connect(9876, "10.0.0.3"); - chat(client); //Recieve message @@ -51,31 +54,58 @@ void ShutdownSockets() void chat(Client client) { - char msgRecv[255] = "\0"; - char msgSend[255] = "\0"; + Oyster::Network::Translator *t = new Oyster::Network::Translator(); + + unsigned char msgRecv[255] = "\0"; + string msgSend = ""; + + ProtocolHeader header; + ProtocolTest test; bool chatDone = false; while(!chatDone) { client.Recv(msgRecv); + + header = t->Translate(msgRecv); - cout<< "Client 2: " << msgRecv << endl; - - cin.getline(msgSend , 255 , '\n'); - - if(strlen(msgSend) < 1) + switch(header.packageType) { - strcpy_s(msgSend , " "); + case package_type_header: + break; + + case package_type_test: + cout <<"Client 2: " <<((ProtocolTest*)&header)->textMessage <Translate(test); + + client.Send(message); } else diff --git a/Code/Network/OysterNetworkServer/Client.cpp b/Code/Network/OysterNetworkServer/Client.cpp index f86d37b8..8c2bdd0d 100644 --- a/Code/Network/OysterNetworkServer/Client.cpp +++ b/Code/Network/OysterNetworkServer/Client.cpp @@ -12,12 +12,12 @@ Client::~Client() delete connection; } -void Client::Send(char buffer[]) +void Client::Send(unsigned char buffer[]) { connection->Send(buffer); } -void Client::Recv(char buffer[]) +void Client::Recv(unsigned char buffer[]) { connection->Recieve(buffer); } \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Client.h b/Code/Network/OysterNetworkServer/Client.h index 2d1de909..05215b31 100644 --- a/Code/Network/OysterNetworkServer/Client.h +++ b/Code/Network/OysterNetworkServer/Client.h @@ -20,8 +20,8 @@ namespace Oyster Client(unsigned int socket); ~Client(); - void Send(char buffer[]); - void Recv(char buffer[]); + void Send(unsigned char buffer[]); + void Recv(unsigned char buffer[]); private: ::Oyster::Network::Connection* connection; diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index a399dc62..e20cb584 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -59,7 +59,7 @@ int main() Client client2(clientSocket); cout << "Second client connected." << endl; - client1.Send("Hej"); + client1.Send((unsigned char*) "Hej"); while(1) { From 954a1ac669cf27372abcacffe60c028ae4a1ee09 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Fri, 22 Nov 2013 08:56:00 +0100 Subject: [PATCH 17/67] Fixed error Fixed translation --- .../NetworkDependencies/Connection.cpp | 11 +++-- Code/Network/NetworkDependencies/Connection.h | 4 +- .../Network/NetworkDependencies/IConnection.h | 4 +- Code/Network/NetworkDependencies/ITranslate.h | 2 +- .../NetworkDependencies/Translator.cpp | 10 ++--- Code/Network/NetworkDependencies/Translator.h | 2 +- Code/Network/OysterNetworkClient/Client.cpp | 4 +- Code/Network/OysterNetworkClient/Client.h | 4 +- .../OysterNetworkClient/ClientMain.cpp | 27 +++++++----- Code/Network/OysterNetworkServer/Client.cpp | 4 +- Code/Network/OysterNetworkServer/Client.h | 4 +- .../OysterNetworkServer/ServerMain.cpp | 42 +++++++------------ 12 files changed, 56 insertions(+), 62 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 8a2081c0..c84d3344 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -94,12 +94,11 @@ void Connection::Disconnect() closesocket(mySocket); } -bool Connection::Send(const char message[]) +bool Connection::Send(const unsigned char message[]) { int nBytes; - unsigned long messageSize = strlen(message); - - if((nBytes = send(mySocket, message , messageSize, 0)) == SOCKET_ERROR) + unsigned long messageSize = strlen((char*)message); + if((nBytes = send(mySocket, (char*)message , messageSize, 0)) == SOCKET_ERROR) { //Send failed! return false; @@ -108,10 +107,10 @@ bool Connection::Send(const char message[]) return true; } -int Connection::Recieve(char message[]) +int Connection::Recieve(unsigned char message[]) { int nBytes; - nBytes = recv(mySocket, message , 255, 0); + nBytes = recv(mySocket, (char*)message , 255, 0); if(nBytes == SOCKET_ERROR) { //Recv failed diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index 0070fed6..5febafa5 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -22,8 +22,8 @@ namespace Oyster virtual bool Connect( unsigned short port , const char serverName[] ); virtual bool InitiateServer( unsigned short port ); virtual void Disconnect(); - virtual bool Send(const char message[]); - virtual int Recieve(char message[]); + virtual bool Send(const unsigned char message[]); + virtual int Recieve(char unsigned message[]); virtual int Listen(); private: diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index 1443b781..91b7c7b4 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -14,8 +14,8 @@ namespace Oyster public: virtual void Disconnect() = 0; - virtual bool Send( const char message[] ) = 0; - virtual int Recieve(char message[]) = 0; + virtual bool Send( const unsigned char message[] ) = 0; + virtual int Recieve(unsigned char message[]) = 0; virtual bool InitiateServer( unsigned short port ) { return false; }; virtual int Listen() { return -1; }; virtual bool Connect( unsigned short port, const char serverName[] ) { return false; }; diff --git a/Code/Network/NetworkDependencies/ITranslate.h b/Code/Network/NetworkDependencies/ITranslate.h index 6f24cd72..d17325a0 100644 --- a/Code/Network/NetworkDependencies/ITranslate.h +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -10,7 +10,7 @@ namespace Oyster public: virtual unsigned char* Translate (Protocols::ProtocolHeader &header ) = 0; - virtual Protocols::ProtocolHeader& Translate ( unsigned char message[] ) = 0; + virtual Protocols::ProtocolHeader* Translate ( unsigned char message[] ) = 0; }; } diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp index 30e1e273..2915f913 100644 --- a/Code/Network/NetworkDependencies/Translator.cpp +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -25,9 +25,9 @@ unsigned char* Translator::Translate( ProtocolHeader &header ) return message->GetMsg(); } -ProtocolHeader& Translator::Translate(unsigned char msg[] ) +ProtocolHeader* Translator::Translate(unsigned char msg[] ) { - ProtocolHeader* header = new ProtocolHeader(); + ProtocolHeader *header = new ProtocolHeader(); MessageHeader *message = new MessageHeader(); message->Translate(msg, *header); @@ -46,7 +46,5 @@ ProtocolHeader& Translator::Translate(unsigned char msg[] ) } message->Translate(msg, *header); - return *header; -} - - + return header; +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h index c9eb7362..14bf4318 100644 --- a/Code/Network/NetworkDependencies/Translator.h +++ b/Code/Network/NetworkDependencies/Translator.h @@ -16,7 +16,7 @@ namespace Oyster ~Translator(){}; unsigned char* Translate (Protocols::ProtocolHeader &header ); - Protocols::ProtocolHeader& Translate (unsigned char msg[] ); + Protocols::ProtocolHeader* Translate (unsigned char msg[] ); }; } } diff --git a/Code/Network/OysterNetworkClient/Client.cpp b/Code/Network/OysterNetworkClient/Client.cpp index a32f0996..3569b7d4 100644 --- a/Code/Network/OysterNetworkClient/Client.cpp +++ b/Code/Network/OysterNetworkClient/Client.cpp @@ -19,12 +19,12 @@ bool Client::Connect(unsigned int port, char filename[]) return true; } -void Client::Send(char msg[]) +void Client::Send(unsigned char msg[]) { connection->Send(msg); } -void Client::Recv(char msg[]) +void Client::Recv(unsigned char msg[]) { connection->Recieve(msg); } \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/Client.h b/Code/Network/OysterNetworkClient/Client.h index e08d6348..a48e37d9 100644 --- a/Code/Network/OysterNetworkClient/Client.h +++ b/Code/Network/OysterNetworkClient/Client.h @@ -21,8 +21,8 @@ namespace Oyster bool Connect(unsigned int port, char filename[]); - void Send(char msg[]); - void Recv(char msg[]); + void Send(unsigned char msg[]); + void Recv(unsigned char msg[]); private: ::Oyster::Network::Connection* connection; diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index a6002d0a..2e6a4bfe 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -9,6 +9,10 @@ void ShutdownSockets(); bool InitSockets(); void chat(Client client); +#include "../NetworkDependencies/Protocols.h" +#include "../NetworkDependencies/Translator.h" +using namespace Oyster::Network::Protocols; + int main() { char msgRecv[255] = "\0"; @@ -21,10 +25,13 @@ int main() Client client; //Connect to server - client.Connect(9876, "10.0.0.3"); + client.Connect(9876, "127.0.0.1"); + unsigned char* recvBuffer = new unsigned char[255]; - chat(client); + client.Send(recvBuffer); + + //chat(client); //Recieve message //client.Recv(msgRecv); @@ -51,8 +58,8 @@ void ShutdownSockets() void chat(Client client) { - char msgRecv[255] = "\0"; - char msgSend[255] = "\0"; + unsigned char msgRecv[255] = "\0"; + unsigned char msgSend[255] = "\0"; bool chatDone = false; @@ -62,18 +69,18 @@ void chat(Client client) cout<< "Client 2: " << msgRecv << endl; - cin.getline(msgSend , 255 , '\n'); + cin.getline((char*)msgSend , 255 , '\n'); - if(strlen(msgSend) < 1) + if(strlen((char*)msgSend) < 1) { - strcpy_s(msgSend , " "); + memcpy(msgSend, " ", 1); } - if(msgSend != "exit") + if((char*)msgSend != "exit") { - if(strlen(msgSend) < 1) + if(strlen((char*)msgSend) < 1) { - strcpy_s(msgSend, "ERROR"); + memcpy(msgSend, "ERROR", 1); } client.Send(msgSend); } diff --git a/Code/Network/OysterNetworkServer/Client.cpp b/Code/Network/OysterNetworkServer/Client.cpp index f86d37b8..8c2bdd0d 100644 --- a/Code/Network/OysterNetworkServer/Client.cpp +++ b/Code/Network/OysterNetworkServer/Client.cpp @@ -12,12 +12,12 @@ Client::~Client() delete connection; } -void Client::Send(char buffer[]) +void Client::Send(unsigned char buffer[]) { connection->Send(buffer); } -void Client::Recv(char buffer[]) +void Client::Recv(unsigned char buffer[]) { connection->Recieve(buffer); } \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Client.h b/Code/Network/OysterNetworkServer/Client.h index 2d1de909..05215b31 100644 --- a/Code/Network/OysterNetworkServer/Client.h +++ b/Code/Network/OysterNetworkServer/Client.h @@ -20,8 +20,8 @@ namespace Oyster Client(unsigned int socket); ~Client(); - void Send(char buffer[]); - void Recv(char buffer[]); + void Send(unsigned char buffer[]); + void Recv(unsigned char buffer[]); private: ::Oyster::Network::Connection* connection; diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index a399dc62..a75c4228 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -16,28 +16,9 @@ using namespace ::Protocols; int main() { - unsigned char* recvBuffer; - Translator t; - ProtocolTest header; - header.clientID = 1; - header.packageType = package_type_test; - header.size = 12; - header.textMessage = "Hej"; - - recvBuffer = t.Translate(header); - - ProtocolHeader& asd = t.Translate(recvBuffer); - switch(asd.packageType) - { - case package_type_test: - - break; - } - cout << static_cast(&asd)->textMessage << endl; - - + unsigned char* recvBuffer = new unsigned char[255]; cout << "Server" << endl; - + Translator t; if(!InitSockets()) { @@ -59,21 +40,30 @@ int main() Client client2(clientSocket); cout << "Second client connected." << endl; - client1.Send("Hej"); + client1.Send((unsigned char*)"Hej"); + ProtocolHeader* header = NULL; while(1) { - /*client1.Recv(recvBuffer); - cout << "Client1: " << recvBuffer << endl; + client1.Recv(recvBuffer); + + header = t.Translate(recvBuffer); + cout << header->clientID << ' ' << header->packageType << ' ' << header->size << endl; + cout << "Client1: " << ((ProtocolTest*)header)->textMessage << endl; client2.Send(recvBuffer); client2.Recv(recvBuffer); - cout << "Client2: " << recvBuffer << endl; - client1.Send(recvBuffer);*/ + + header = t.Translate(recvBuffer); + cout << header->clientID << ' ' << header->packageType << ' ' << header->size << endl; + cout << "Client1: " << ((ProtocolTest*)header)->textMessage << endl; + client1.Send(recvBuffer); } ShutdownSockets(); + delete[] recvBuffer; + system("pause"); return 0; } From 5265fd1af1ca9ede422228adc2e0c4f0e6cca8bf Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Fri, 22 Nov 2013 09:17:07 +0100 Subject: [PATCH 18/67] Fixed merge errors --- .../NetworkDependencies/Connection.cpp | 14 +++-- Code/Network/NetworkDependencies/Connection.h | 10 +++- Code/Network/NetworkDependencies/Protocols.h | 8 +++ .../OysterNetworkClient/ClientMain.cpp | 59 ++++++++++++++++++- .../OysterNetworkServer/ServerMain.cpp | 4 ++ 5 files changed, 88 insertions(+), 7 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index c84d3344..bddfe850 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -26,8 +26,8 @@ bool Connection::Connect(unsigned short port , const char serverName[]) } - struct hostent *hostEntry; - if((hostEntry = gethostbyname(serverName)) == NULL) + struct hostent *hostEnt; + if((hostEnt = gethostbyname(serverName)) == NULL) { //couldn't find host return false; @@ -35,7 +35,7 @@ bool Connection::Connect(unsigned short port , const char serverName[]) struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(port); - server.sin_addr.s_addr = *(unsigned long*) hostEntry->h_addr; + server.sin_addr.s_addr = *(unsigned long*) hostEnt->h_addr; while(1) { @@ -77,7 +77,7 @@ bool Connection::InitiateServer(unsigned short port) return false; } - //not our Listen function! + //not our Listen function! its trying to keep our socket open for connections if(listen(mySocket, 5) == SOCKET_ERROR) { //"Listen failed! @@ -98,7 +98,13 @@ bool Connection::Send(const unsigned char message[]) { int nBytes; unsigned long messageSize = strlen((char*)message); +<<<<<<< HEAD if((nBytes = send(mySocket, (char*)message , messageSize, 0)) == SOCKET_ERROR) +======= + messageSize = 18; + nBytes = send(mySocket, (char*)message , messageSize, 0); + if(nBytes == SOCKET_ERROR) +>>>>>>> 4142688f6c4a63aa97341205588ad6cace0f43af { //Send failed! return false; diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index 5febafa5..3246f431 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -20,10 +20,18 @@ namespace Oyster ~Connection(); virtual bool Connect( unsigned short port , const char serverName[] ); - virtual bool InitiateServer( unsigned short port ); + virtual bool InitiateServer( unsigned short port ); + virtual void Disconnect(); +<<<<<<< HEAD virtual bool Send(const unsigned char message[]); virtual int Recieve(char unsigned message[]); +======= + + virtual bool Send(const unsigned char message[]); + virtual int Recieve(unsigned char message[]); + +>>>>>>> 4142688f6c4a63aa97341205588ad6cace0f43af virtual int Listen(); private: diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h index 3f783790..e0bb75a1 100644 --- a/Code/Network/NetworkDependencies/Protocols.h +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -32,6 +32,14 @@ namespace Oyster std::string textMessage; ProtocolTest() { this->packageType = package_type_test; } }; + /*struct Prutt + { + PackageType t; + union PRUTT + { + ProtocolTest *ptest, + }; + };*/ } } } diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 2e6a4bfe..a558e7f5 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -1,10 +1,14 @@ #include #include "Client.h" #include +#include "..\NetworkDependencies\Translator.h" + using namespace std; +using namespace Oyster::Network::Protocols;; using namespace Oyster::Network::Client; #pragma comment(lib, "ws2_32.lib") + void ShutdownSockets(); bool InitSockets(); void chat(Client client); @@ -29,9 +33,13 @@ int main() unsigned char* recvBuffer = new unsigned char[255]; +<<<<<<< HEAD client.Send(recvBuffer); //chat(client); +======= + chat(client); +>>>>>>> 4142688f6c4a63aa97341205588ad6cace0f43af //Recieve message //client.Recv(msgRecv); @@ -58,17 +66,38 @@ void ShutdownSockets() void chat(Client client) { +<<<<<<< HEAD unsigned char msgRecv[255] = "\0"; unsigned char msgSend[255] = "\0"; +======= + Oyster::Network::Translator *t = new Oyster::Network::Translator(); + + unsigned char msgRecv[255] = "\0"; + string msgSend = ""; + + ProtocolHeader header; + ProtocolTest test; +>>>>>>> 4142688f6c4a63aa97341205588ad6cace0f43af bool chatDone = false; while(!chatDone) { client.Recv(msgRecv); + + header = t->Translate(msgRecv); - cout<< "Client 2: " << msgRecv << endl; + switch(header.packageType) + { + case package_type_header: + break; + case package_type_test: + cout <<"Client 2: " <<((ProtocolTest*)&header)->textMessage <>>>>>> 4142688f6c4a63aa97341205588ad6cace0f43af } - client.Send(msgSend); + + test.packageType = package_type_test; + test.size = msgSend.length(); + test.textMessage = msgSend; + + unsigned char *message = t->Translate(test); + + client.Send(message); } else diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index a75c4228..2f301c63 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -40,8 +40,12 @@ int main() Client client2(clientSocket); cout << "Second client connected." << endl; +<<<<<<< HEAD client1.Send((unsigned char*)"Hej"); ProtocolHeader* header = NULL; +======= + client1.Send((unsigned char*) "Hej"); +>>>>>>> 4142688f6c4a63aa97341205588ad6cace0f43af while(1) { From c5e432b566f02c85307dd34816a1fb89177da055 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Fri, 22 Nov 2013 09:43:24 +0100 Subject: [PATCH 19/67] Fixed size --- Code/Network/NetworkDependencies/Connection.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 0dd2da98..f13ff159 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -99,7 +99,7 @@ bool Connection::Send(const unsigned char message[]) int nBytes; unsigned long messageSize = strlen((char*)message); - messageSize = 18; + messageSize = 255; nBytes = send(mySocket, (char*)message , messageSize, 0); if(nBytes == SOCKET_ERROR) { From 9e6593abd12d3f964c084ec2d73bb52fb8445efc Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Fri, 22 Nov 2013 09:49:48 +0100 Subject: [PATCH 20/67] =?UTF-8?q?bug=20med=20reference=20p=C3=A5=20typecas?= =?UTF-8?q?t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Code/Network/OysterNetworkClient/ClientMain.cpp | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index a48a990e..c1ed48da 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -29,7 +29,7 @@ int main() Client client; //Connect to server - client.Connect(9876, "127.0.0.1"); + client.Connect(9876, "10.0.0.3"); chat(client); @@ -79,20 +79,12 @@ void chat(Client client) case package_type_header: break; case package_type_test: - cout <<"Client 2: " <<((ProtocolTest*)&header)->textMessage <textMessage < Date: Fri, 22 Nov 2013 11:40:55 +0100 Subject: [PATCH 21/67] Added protocols to an enum Now we don't have to type cast --- Code/Network/NetworkDependencies/ITranslate.h | 2 +- Code/Network/NetworkDependencies/Protocols.h | 34 +++++++++++++++---- .../NetworkDependencies/Translator.cpp | 21 ++++++++---- Code/Network/NetworkDependencies/Translator.h | 9 +++-- .../OysterNetworkClient/ClientMain.cpp | 8 +++-- .../OysterNetworkServer/ServerMain.cpp | 18 ++++++---- 6 files changed, 66 insertions(+), 26 deletions(-) diff --git a/Code/Network/NetworkDependencies/ITranslate.h b/Code/Network/NetworkDependencies/ITranslate.h index d17325a0..63f18e68 100644 --- a/Code/Network/NetworkDependencies/ITranslate.h +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -10,7 +10,7 @@ namespace Oyster public: virtual unsigned char* Translate (Protocols::ProtocolHeader &header ) = 0; - virtual Protocols::ProtocolHeader* Translate ( unsigned char message[] ) = 0; + virtual Protocols::ProtocolSet* Translate (Protocols::ProtocolSet* set, unsigned char message[] ) = 0; }; } diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h index e0bb75a1..dcddf797 100644 --- a/Code/Network/NetworkDependencies/Protocols.h +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -17,7 +17,6 @@ namespace Oyster package_type_update_position }; - struct ProtocolHeader { int size; @@ -32,14 +31,37 @@ namespace Oyster std::string textMessage; ProtocolTest() { this->packageType = package_type_test; } }; - /*struct Prutt + + class ProtocolSet { + public: PackageType t; - union PRUTT + union { - ProtocolTest *ptest, - }; - };*/ + ProtocolHeader* pHeader; + ProtocolTest *pTest; + + }Protocol; + + void Release() + { + switch(t) + { + case package_type_header: + if(Protocol.pHeader) + { + delete Protocol.pHeader; + } + break; + case package_type_test: + if(Protocol.pTest) + { + delete Protocol.pTest; + } + break; + } + } + }; } } } diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp index 2915f913..216123cb 100644 --- a/Code/Network/NetworkDependencies/Translator.cpp +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -25,26 +25,35 @@ unsigned char* Translator::Translate( ProtocolHeader &header ) return message->GetMsg(); } -ProtocolHeader* Translator::Translate(unsigned char msg[] ) +ProtocolSet* Translator::Translate(ProtocolSet* set, unsigned char msg[] ) { ProtocolHeader *header = new ProtocolHeader(); MessageHeader *message = new MessageHeader(); message->Translate(msg, *header); + delete message; + message = NULL; - switch(header->packageType) + //Switch to the correct package. + set->t = (PackageType)header->packageType; + switch(set->t) { case package_type_header: message = new MessageHeader(); - header = new ProtocolHeader(); + set->Protocol.pHeader = new ProtocolHeader; + message->Translate(msg, *set->Protocol.pHeader); break; case package_type_test: message = new MessageTest(); - header = new ProtocolTest(); + set->Protocol.pTest = new ProtocolTest; + message->Translate(msg, *set->Protocol.pTest); break; } - message->Translate(msg, *header); - return header; + if(message) + delete message; + delete header; + + return set; } \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h index 14bf4318..95002711 100644 --- a/Code/Network/NetworkDependencies/Translator.h +++ b/Code/Network/NetworkDependencies/Translator.h @@ -12,11 +12,14 @@ namespace Oyster class Translator : public ITranslate { public: - Translator (){}; - ~Translator(){}; + Translator (){ }; + ~Translator(){ }; unsigned char* Translate (Protocols::ProtocolHeader &header ); - Protocols::ProtocolHeader* Translate (unsigned char msg[] ); + Protocols::ProtocolSet* Translate (Protocols::ProtocolSet* set, unsigned char msg[] ); + + private: + }; } } diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index c1ed48da..359ae7bd 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -63,6 +63,7 @@ void chat(Client client) unsigned char msgRecv[255] = "\0"; string msgSend = ""; + ProtocolSet* set = new ProtocolSet; ProtocolHeader* header; ProtocolTest test; @@ -72,14 +73,14 @@ void chat(Client client) { client.Recv(msgRecv); - header = t->Translate(msgRecv); + set = t->Translate(set, msgRecv); - switch(header->packageType) + switch(set->t) { case package_type_header: break; case package_type_test: - cout <<"Client 2: " <<((ProtocolTest*)header)->textMessage <Protocol.pTest->textMessage <clientID << ' ' << header->packageType << ' ' << header->size << endl; - cout << "Client1: " << ((ProtocolTest*)header)->textMessage << endl; + set = t.Translate(set, recvBuffer); + cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; + cout << "Client1: " << set->Protocol.pTest->textMessage << endl; + set->Release(); client2.Send(recvBuffer); + client2.Recv(recvBuffer); - header = t.Translate(recvBuffer); - cout << header->clientID << ' ' << header->packageType << ' ' << header->size << endl; - cout << "Client1: " << ((ProtocolTest*)header)->textMessage << endl; + set = t.Translate(set, recvBuffer); + cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; + cout << "Client2: " << set->Protocol.pTest->textMessage << endl; + set->Release(); client1.Send(recvBuffer); } ShutdownSockets(); delete[] recvBuffer; + delete set; system("pause"); return 0; From d33220f8ca273e83f25942f610f628006253891d Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Fri, 22 Nov 2013 14:23:08 +0100 Subject: [PATCH 22/67] Fixed memory leaks Fixed memory leaks. --- .../NetworkDependencies/Connection.cpp | 4 +-- .../Messages/MessageHeader.cpp | 22 +++++++--------- .../Messages/MessageHeader.h | 9 +++---- .../Messages/MessageTest.cpp | 6 ++--- .../Messages/MessageTest.h | 2 +- .../NetworkDependencies.vcxproj | 8 ++++++ .../NetworkDependencies/Translator.cpp | 11 +++++--- Code/Network/NetworkDependencies/Translator.h | 5 ++-- Code/Network/OysterNetworkClient/Client.cpp | 3 ++- .../OysterNetworkClient/ClientMain.cpp | 26 +++++++++---------- .../OysterNetworkClient.vcxproj | 8 ++++++ .../OysterNetworkServer.vcxproj | 8 ++++++ .../OysterNetworkServer/ServerMain.cpp | 13 +++++----- 13 files changed, 73 insertions(+), 52 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index f13ff159..cac38e71 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -7,9 +7,7 @@ using namespace Oyster::Network; Connection::~Connection() { - mySocket = NULL; - - if(socket != NULL) + if(mySocket != NULL) { closesocket( mySocket ); mySocket = NULL; diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp index cf2d2b22..c2e65faf 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -8,21 +8,23 @@ using namespace Oyster::Network::Protocols; MessageHeader::MessageHeader() { size = 0; - msg = new unsigned char[1024]; + } MessageHeader::~MessageHeader() { - delete[] msg; + } -void MessageHeader::Translate(ProtocolHeader& header) +void MessageHeader::Translate(ProtocolHeader& header, unsigned char msg[] ) { size = 0; - AddInt(header.clientID); - AddInt(header.packageType); - AddInt(header.size); + AddInt(header.clientID, msg); + AddInt(header.packageType, msg); + AddInt(header.size, msg); + + } void MessageHeader::Translate(unsigned char message[], ProtocolHeader& header) @@ -34,18 +36,14 @@ void MessageHeader::Translate(unsigned char message[], ProtocolHeader& header) header.size = GetInt(message); } -unsigned char* MessageHeader::GetMsg() -{ - return msg; -} -void MessageHeader::AddInt(int i) +void MessageHeader::AddInt(int i, unsigned char msg[]) { Pack(&msg[size], i); size += 4; } -void MessageHeader::AddStr(std::string str) +void MessageHeader::AddStr(std::string str, unsigned char msg[]) { Pack(&msg[size], str); size += 2 + str.length(); diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.h b/Code/Network/NetworkDependencies/Messages/MessageHeader.h index 0aa22dff..2705a062 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.h +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.h @@ -20,23 +20,20 @@ namespace Oyster MessageHeader(); virtual ~MessageHeader(); - virtual void Translate(Protocols::ProtocolHeader& header); + virtual void Translate(Protocols::ProtocolHeader& header, unsigned char msg[] ); virtual void Translate(unsigned char message[], Protocols::ProtocolHeader& header); - unsigned char* GetMsg(); protected: //Add variables to messages - void AddInt(int i); - void AddStr(std::string str); + void AddInt(int i, unsigned char msg[]); + void AddStr(std::string str, unsigned char msg[]); //Get variables from message int GetInt(unsigned char message[]); std::string GetStr(unsigned char message[]); private: - static const int max_message_length = 1024; - unsigned char* msg; int size; }; diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp index 89fb2911..e8ddcb57 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp @@ -12,11 +12,11 @@ MessageTest::~MessageTest() { } -void MessageTest::Translate(ProtocolHeader& header) +void MessageTest::Translate(ProtocolHeader& header, unsigned char msg[]) { - MessageHeader::Translate(header); + MessageHeader::Translate(header, msg); - AddStr(static_cast(&header)->textMessage); + AddStr(static_cast(&header)->textMessage, msg); } void MessageTest::Translate(unsigned char message[], ProtocolHeader& header) diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.h b/Code/Network/NetworkDependencies/Messages/MessageTest.h index e01847c9..62a55f24 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageTest.h +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.h @@ -19,7 +19,7 @@ namespace Oyster MessageTest(); virtual ~MessageTest(); - virtual void Translate(Protocols::ProtocolHeader& header); + virtual void Translate(Protocols::ProtocolHeader& header, unsigned char msg[]); virtual void Translate(unsigned char message[], Protocols::ProtocolHeader& header); private: diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index 8c215717..c395d509 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -69,21 +69,29 @@ $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(SolutionDir)..\External\Lib\$(ProjectName)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(SolutionDir)..\External\Lib\$(ProjectName)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp index 216123cb..ad622fdc 100644 --- a/Code/Network/NetworkDependencies/Translator.cpp +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -10,7 +10,6 @@ unsigned char* Translator::Translate( ProtocolHeader &header ) switch(header.packageType) { - case package_type_header: message = new MessageHeader(); break; @@ -20,9 +19,15 @@ unsigned char* Translator::Translate( ProtocolHeader &header ) break; } - message->Translate(header); + message->Translate(header, this->msg); - return message->GetMsg(); + if(message != NULL) + { + delete message; + message = NULL; + } + + return msg; } ProtocolSet* Translator::Translate(ProtocolSet* set, unsigned char msg[] ) diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h index 95002711..26b5a56c 100644 --- a/Code/Network/NetworkDependencies/Translator.h +++ b/Code/Network/NetworkDependencies/Translator.h @@ -12,13 +12,14 @@ namespace Oyster class Translator : public ITranslate { public: - Translator (){ }; - ~Translator(){ }; + Translator () { msg = new unsigned char[256]; }; + ~Translator() { if(msg != NULL) { delete [] this->msg; }}; unsigned char* Translate (Protocols::ProtocolHeader &header ); Protocols::ProtocolSet* Translate (Protocols::ProtocolSet* set, unsigned char msg[] ); private: + unsigned char* msg; }; } diff --git a/Code/Network/OysterNetworkClient/Client.cpp b/Code/Network/OysterNetworkClient/Client.cpp index 3569b7d4..d77b1bf7 100644 --- a/Code/Network/OysterNetworkClient/Client.cpp +++ b/Code/Network/OysterNetworkClient/Client.cpp @@ -9,7 +9,8 @@ Client::Client() Client::~Client() { - delete connection; + delete this->connection; + connection = 0; } bool Client::Connect(unsigned int port, char filename[]) diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 359ae7bd..fa812365 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -1,21 +1,19 @@ #include #include "Client.h" #include +#include #include "..\NetworkDependencies\Translator.h" +#include "..\NetworkDependencies\Protocols.h" using namespace std; using namespace Oyster::Network::Protocols;; using namespace Oyster::Network::Client; -#pragma comment(lib, "ws2_32.lib") +#pragma comment(lib, "ws2_32.lib") void ShutdownSockets(); bool InitSockets(); -void chat(Client client); - -#include "../NetworkDependencies/Protocols.h" -#include "../NetworkDependencies/Translator.h" -using namespace Oyster::Network::Protocols; +void chat(Client &client); int main() { @@ -56,11 +54,11 @@ void ShutdownSockets() WSACleanup(); } -void chat(Client client) +void chat(Client &client) { Oyster::Network::Translator *t = new Oyster::Network::Translator(); - unsigned char msgRecv[255] = "\0"; + unsigned char msgRecv[256] = "\0"; string msgSend = ""; ProtocolSet* set = new ProtocolSet; @@ -73,8 +71,8 @@ void chat(Client client) { client.Recv(msgRecv); - set = t->Translate(set, msgRecv); - + t->Translate(set, msgRecv); + switch(set->t) { case package_type_header: @@ -83,17 +81,16 @@ void chat(Client client) cout <<"Client 2: " << set->Protocol.pTest->textMessage <Release(); std::getline(std::cin, msgSend); - + if( msgSend != "exit") { if(msgSend.length() < 1) { - //memcpy(msgSend, "ERROR" , 5); msgSend = "ERROR!"; - //strcpy_s(msgSend, "ERROR"); } test.packageType = package_type_test; @@ -114,5 +111,6 @@ void chat(Client client) } + delete t; delete set; } \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj index 6bdc7921..4fdfc0d4 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj @@ -69,21 +69,29 @@ $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj index 94a6a6e1..855b323e 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj @@ -69,21 +69,29 @@ $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) $(SolutionDir)..\External\Lib\$(ProjectName)\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files %28x86%29\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 2940f87d..6d104944 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "Listener.h" #include "Client.h" using namespace std; @@ -16,7 +17,7 @@ using namespace ::Protocols; int main() { - unsigned char* recvBuffer = new unsigned char[255]; + unsigned char* recvBuffer = new unsigned char[256]; cout << "Server" << endl; Translator t; @@ -42,21 +43,20 @@ int main() client1.Send((unsigned char*)"Hej"); ProtocolSet* set = new ProtocolSet; - + while(1) { client1.Recv(recvBuffer); - - set = t.Translate(set, recvBuffer); + + t.Translate(set, recvBuffer); cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; cout << "Client1: " << set->Protocol.pTest->textMessage << endl; set->Release(); client2.Send(recvBuffer); - client2.Recv(recvBuffer); - set = t.Translate(set, recvBuffer); + t.Translate(set, recvBuffer); cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; cout << "Client2: " << set->Protocol.pTest->textMessage << endl; set->Release(); @@ -64,7 +64,6 @@ int main() } ShutdownSockets(); - delete[] recvBuffer; delete set; From 6eff55e763188e660849a596ee61580a31b38b38 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Fri, 22 Nov 2013 14:31:07 +0100 Subject: [PATCH 23/67] Fixed possible crash --- Code/Network/NetworkDependencies/Translator.cpp | 4 ++-- Code/Network/OysterNetworkClient/ClientMain.cpp | 6 ------ 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp index ad622fdc..71525172 100644 --- a/Code/Network/NetworkDependencies/Translator.cpp +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -19,10 +19,10 @@ unsigned char* Translator::Translate( ProtocolHeader &header ) break; } - message->Translate(header, this->msg); - if(message != NULL) { + message->Translate(header, this->msg); + delete message; message = NULL; } diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index fa812365..47106f74 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -31,12 +31,6 @@ int main() chat(client); - //Recieve message - //client.Recv(msgRecv); - - //print message - //cout << msgRecv << endl; - ShutdownSockets(); system("pause"); From ad7091e5208c77754ebe15b9ae1fa97c404a7e43 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Fri, 22 Nov 2013 15:48:49 +0100 Subject: [PATCH 24/67] Fixed automatic size on Messages --- .../Messages/MessageHeader.cpp | 17 +++++++++-------- .../Messages/MessageHeader.h | 2 ++ .../Messages/MessageTest.cpp | 2 +- Code/Network/OysterNetworkServer/ServerMain.cpp | 7 ++++++- 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp index c2e65faf..fc26dd34 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -8,23 +8,20 @@ using namespace Oyster::Network::Protocols; MessageHeader::MessageHeader() { size = 0; - } MessageHeader::~MessageHeader() { - } void MessageHeader::Translate(ProtocolHeader& header, unsigned char msg[] ) { size = 0; - - AddInt(header.clientID, msg); - AddInt(header.packageType, msg); - AddInt(header.size, msg); - + AddInt(header.size, msg); + AddInt(header.packageType, msg); + AddInt(header.clientID, msg); + SetSize(msg); } void MessageHeader::Translate(unsigned char message[], ProtocolHeader& header) @@ -36,7 +33,6 @@ void MessageHeader::Translate(unsigned char message[], ProtocolHeader& header) header.size = GetInt(message); } - void MessageHeader::AddInt(int i, unsigned char msg[]) { Pack(&msg[size], i); @@ -61,4 +57,9 @@ std::string MessageHeader::GetStr(unsigned char message[]) std::string std = UnpackStr(&message[size]); size += 2 + std.length(); return std; +} + +void MessageHeader::SetSize(unsigned char msg[]) +{ + Pack(&msg[0], size); } \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.h b/Code/Network/NetworkDependencies/Messages/MessageHeader.h index 2705a062..af9be77f 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.h +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.h @@ -33,6 +33,8 @@ namespace Oyster int GetInt(unsigned char message[]); std::string GetStr(unsigned char message[]); + void SetSize(unsigned char msg[]); + private: int size; diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp index e8ddcb57..2d3bbe10 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp @@ -5,7 +5,6 @@ using namespace Oyster::Network::Protocols; MessageTest::MessageTest() { - } MessageTest::~MessageTest() @@ -17,6 +16,7 @@ void MessageTest::Translate(ProtocolHeader& header, unsigned char msg[]) MessageHeader::Translate(header, msg); AddStr(static_cast(&header)->textMessage, msg); + SetSize(msg); } void MessageTest::Translate(unsigned char message[], ProtocolHeader& header) diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 6d104944..2f954b69 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -41,8 +41,13 @@ int main() Client client2(clientSocket); cout << "Second client connected." << endl; - client1.Send((unsigned char*)"Hej"); ProtocolSet* set = new ProtocolSet; + ProtocolTest test; + test.clientID = 0; + test.textMessage = "hej"; + recvBuffer = t.Translate(test); + + client1.Send(recvBuffer); while(1) { From 640ac2172a90d47ea868907ffadb849028da1a70 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Mon, 25 Nov 2013 11:39:38 +0100 Subject: [PATCH 25/67] checked the coding standard and changed it accordinly --- .../NetworkDependencies/Connection.cpp | 37 +++++++++---------- Code/Network/NetworkDependencies/Connection.h | 15 ++++---- .../Network/NetworkDependencies/IConnection.h | 7 ++-- Code/Network/NetworkDependencies/ITranslate.h | 4 ++ Code/Network/NetworkDependencies/Protocols.h | 4 ++ Code/Network/NetworkDependencies/Translator.h | 4 ++ 6 files changed, 41 insertions(+), 30 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index cac38e71..08700b8c 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -3,21 +3,17 @@ #include #include -using namespace Oyster::Network; +using namespace Oyster::Network; Connection::~Connection() { - if(mySocket != NULL) - { - closesocket( mySocket ); - mySocket = NULL; - } + closesocket( this->socket ); } bool Connection::Connect(unsigned short port , const char serverName[]) { - mySocket = socket(AF_INET, SOCK_STREAM, 0); - if(mySocket == SOCKET_ERROR) + this->socket = ::socket(AF_INET, SOCK_STREAM, 0); + if(this->socket == SOCKET_ERROR) { //error opening socket return false; @@ -30,6 +26,7 @@ bool Connection::Connect(unsigned short port , const char serverName[]) //couldn't find host return false; } + struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(port); @@ -37,7 +34,7 @@ bool Connection::Connect(unsigned short port , const char serverName[]) while(1) { - if(connect(mySocket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) + if(connect(this->socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) { //Error connecting to server return false; @@ -56,8 +53,8 @@ bool Connection::Connect(unsigned short port , const char serverName[]) bool Connection::InitiateServer(unsigned short port) { - mySocket = socket(AF_INET, SOCK_STREAM, 0); - if(mySocket == SOCKET_ERROR) + this->socket = ::socket(AF_INET, SOCK_STREAM, 0); + if(this->socket == SOCKET_ERROR) { //Error opening socket! return false; @@ -68,28 +65,28 @@ bool Connection::InitiateServer(unsigned short port) server.sin_port = htons(port); server.sin_addr.s_addr = INADDR_ANY; - if(bind(mySocket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) + if(bind(this->socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) { //Bind failed!; - closesocket(mySocket); + closesocket(this->socket); return false; } //not our Listen function! its trying to keep our socket open for connections - if(listen(mySocket, 5) == SOCKET_ERROR) + if(listen(this->socket, 5) == SOCKET_ERROR) { //"Listen failed! - closesocket(mySocket); + closesocket(this->socket); return -1; } //Server started! - return mySocket; + return this->socket; } void Connection::Disconnect() { - closesocket(mySocket); + closesocket(this->socket); } bool Connection::Send(const unsigned char message[]) @@ -98,7 +95,7 @@ bool Connection::Send(const unsigned char message[]) unsigned long messageSize = strlen((char*)message); messageSize = 255; - nBytes = send(mySocket, (char*)message , messageSize, 0); + nBytes = send(this->socket, (char*)message , messageSize, 0); if(nBytes == SOCKET_ERROR) { //Send failed! @@ -111,7 +108,7 @@ bool Connection::Send(const unsigned char message[]) int Connection::Recieve(unsigned char message[]) { int nBytes; - nBytes = recv(mySocket, (char*)message , 255, 0); + nBytes = recv(this->socket, (char*)message , 255, 0); if(nBytes == SOCKET_ERROR) { //Recv failed @@ -126,7 +123,7 @@ int Connection::Recieve(unsigned char message[]) int Connection::Listen() { int clientSocket; - if((clientSocket = accept(mySocket, NULL, NULL)) == INVALID_SOCKET) + if((clientSocket = accept(this->socket, NULL, NULL)) == INVALID_SOCKET) { //failed return -1; diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index 109d761c..34fd7ff4 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -1,10 +1,10 @@ +#ifndef NETWORK_DEPENDENCIES_CONNECTION_H +#define NETWORK_DEPENDENCIES_CONNECTION_H + ////////////////////////////////// // Created by Sam Svensson 2013 // ////////////////////////////////// -#ifndef NETWORK_DEPENDENCIES_CONNECTION_H -#define NETWORK_DEPENDENCIES_CONNECTION_H - #include "IConnection.h" namespace Oyster @@ -15,12 +15,13 @@ namespace Oyster { public: - Connection() { mySocket = 0; }; - Connection(int socket) { mySocket = socket; }; - ~Connection(); + Connection() { this->socket = 0; }; + Connection(int socket) { this->socket = socket; }; + virtual ~Connection(); virtual bool Connect( unsigned short port , const char serverName[] ); virtual bool InitiateServer( unsigned short port ); + //virutal bool initiateClient(); virtual void Disconnect(); @@ -30,7 +31,7 @@ namespace Oyster virtual int Listen(); private: - int mySocket; + int socket; }; } diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index 91b7c7b4..8b934a20 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -1,10 +1,10 @@ +#ifndef NETWORK_DEPENDENCIES_I_CONNECTION_H +#define NETWORK_DEPENDENCIES_I_CONNECTION_H + ////////////////////////////////// // Created by Sam Svensson 2013 // ////////////////////////////////// -#ifndef NETWORK_DEPENDENCIES_I_CONNECTION_H -#define NETWORK_DEPENDENCIES_I_CONNECTION_H - namespace Oyster { namespace Network @@ -17,6 +17,7 @@ namespace Oyster virtual bool Send( const unsigned char message[] ) = 0; virtual int Recieve(unsigned char message[]) = 0; virtual bool InitiateServer( unsigned short port ) { return false; }; + virtual bool initiateClient( unsigned short port ) { return false; }; virtual int Listen() { return -1; }; virtual bool Connect( unsigned short port, const char serverName[] ) { return false; }; }; diff --git a/Code/Network/NetworkDependencies/ITranslate.h b/Code/Network/NetworkDependencies/ITranslate.h index 63f18e68..4fddb643 100644 --- a/Code/Network/NetworkDependencies/ITranslate.h +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -1,6 +1,10 @@ #ifndef NETWORK_DEPENDENCIES_I_TRANSLATE #define NETWORK_DEPENDENCIES_I_TRANSLATE +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + namespace Oyster { namespace Network diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h index dcddf797..cb5ad8d1 100644 --- a/Code/Network/NetworkDependencies/Protocols.h +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -1,6 +1,10 @@ #ifndef NETWORK_DEPENDENCIES_PROTOCOLS_H #define NETWORK_DEPENDENCIES_PROTOCOLS_H +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + #include namespace Oyster diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h index 26b5a56c..0e496429 100644 --- a/Code/Network/NetworkDependencies/Translator.h +++ b/Code/Network/NetworkDependencies/Translator.h @@ -1,6 +1,10 @@ #ifndef NETWORK_DEPENDENCIES_TRANSLATOR_H #define NETWORK_DEPENDENCIES_TRANSLATOR_H +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + #include "Messages/MessagesInclude.h" #include "Protocols.h" #include "ITranslate.h" From 82b8ef7b05b50c3fe292e577cb17215e9154cae7 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Mon, 25 Nov 2013 12:14:01 +0100 Subject: [PATCH 26/67] Fixed connection split up connect function and added initiateClient() --- .../NetworkDependencies/Connection.cpp | 39 ++++++++----------- Code/Network/NetworkDependencies/Connection.h | 7 ++-- .../Network/NetworkDependencies/IConnection.h | 2 +- Code/Network/OysterNetworkClient/Client.cpp | 1 + 4 files changed, 22 insertions(+), 27 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 08700b8c..26db50f8 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -12,14 +12,6 @@ Connection::~Connection() bool Connection::Connect(unsigned short port , const char serverName[]) { - this->socket = ::socket(AF_INET, SOCK_STREAM, 0); - if(this->socket == SOCKET_ERROR) - { - //error opening socket - return false; - } - - struct hostent *hostEnt; if((hostEnt = gethostbyname(serverName)) == NULL) { @@ -32,19 +24,10 @@ bool Connection::Connect(unsigned short port , const char serverName[]) server.sin_port = htons(port); server.sin_addr.s_addr = *(unsigned long*) hostEnt->h_addr; - while(1) + if(connect(this->socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) { - if(connect(this->socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) - { - //Error connecting to server - return false; - } - - else - { - break; - } - Sleep(10); + //Error connecting to server + return false; } //connection succesfull! @@ -77,11 +60,23 @@ bool Connection::InitiateServer(unsigned short port) { //"Listen failed! closesocket(this->socket); - return -1; + return false; } //Server started! - return this->socket; + return true; +} + +bool Connection::InitiateClient() +{ + this->socket = ::socket(AF_INET, SOCK_STREAM, 0); + if(this->socket == SOCKET_ERROR) + { + //error opening socket + return false; + } + + return true; } void Connection::Disconnect() diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index 34fd7ff4..6c679371 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -19,15 +19,14 @@ namespace Oyster Connection(int socket) { this->socket = socket; }; virtual ~Connection(); - virtual bool Connect( unsigned short port , const char serverName[] ); virtual bool InitiateServer( unsigned short port ); - //virutal bool initiateClient(); - - virtual void Disconnect(); + virtual bool InitiateClient(); virtual bool Send(const unsigned char message[]); virtual int Recieve(unsigned char message[]); + virtual void Disconnect(); + virtual bool Connect( unsigned short port , const char serverName[] ); virtual int Listen(); private: diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index 8b934a20..51b7631d 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -17,7 +17,7 @@ namespace Oyster virtual bool Send( const unsigned char message[] ) = 0; virtual int Recieve(unsigned char message[]) = 0; virtual bool InitiateServer( unsigned short port ) { return false; }; - virtual bool initiateClient( unsigned short port ) { return false; }; + virtual bool InitiateClient() { return false; }; virtual int Listen() { return -1; }; virtual bool Connect( unsigned short port, const char serverName[] ) { return false; }; }; diff --git a/Code/Network/OysterNetworkClient/Client.cpp b/Code/Network/OysterNetworkClient/Client.cpp index d77b1bf7..abe36d71 100644 --- a/Code/Network/OysterNetworkClient/Client.cpp +++ b/Code/Network/OysterNetworkClient/Client.cpp @@ -15,6 +15,7 @@ Client::~Client() bool Client::Connect(unsigned int port, char filename[]) { + connection->InitiateClient(); connection->Connect(port, filename); return true; From ca5e578af5c79e00aaf8162e7adf98efb5020d79 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Mon, 25 Nov 2013 14:03:32 +0100 Subject: [PATCH 27/67] reconstruction in connection. --- .../NetworkDependencies/Connection.cpp | 22 ++++++++++++++----- Code/Network/NetworkDependencies/Connection.h | 2 ++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 26db50f8..792654f8 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -36,8 +36,7 @@ bool Connection::Connect(unsigned short port , const char serverName[]) bool Connection::InitiateServer(unsigned short port) { - this->socket = ::socket(AF_INET, SOCK_STREAM, 0); - if(this->socket == SOCKET_ERROR) + if(!initiateSocket()) { //Error opening socket! return false; @@ -69,10 +68,8 @@ bool Connection::InitiateServer(unsigned short port) bool Connection::InitiateClient() { - this->socket = ::socket(AF_INET, SOCK_STREAM, 0); - if(this->socket == SOCKET_ERROR) + if(!initiateSocket()) { - //error opening socket return false; } @@ -126,3 +123,18 @@ int Connection::Listen() return clientSocket; } + +/////////////////////////////////////// +//Private functions +/////////////////////////////////////// +bool Connection::initiateSocket() +{ + this->socket = ::socket(AF_INET, SOCK_STREAM, 0); + if(this->socket == SOCKET_ERROR) + { + //error opening socket + return false; + } + + return true; +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index 6c679371..a0019a26 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -30,6 +30,8 @@ namespace Oyster virtual int Listen(); private: + bool initiateSocket(); + int socket; }; From caabb6702e93776ade210541b2b7675fed3a6271 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Mon, 25 Nov 2013 19:00:33 +0100 Subject: [PATCH 28/67] Fixed code standard, Added packing functions --- .../NetworkDependencies/Connection.cpp | 7 +- Code/Network/NetworkDependencies/IListener.h | 25 +++ Code/Network/NetworkDependencies/ITranslate.h | 4 +- .../Listener.cpp | 2 +- Code/Network/NetworkDependencies/Listener.h | 34 +++ .../Messages/MessageHeader.cpp | 210 ++++++++++++++++-- .../Messages/MessageHeader.h | 65 +++++- .../Messages/MessageTest.cpp | 14 +- .../Messages/MessageTest.h | 11 +- .../Messages/MessagesInclude.h | 4 + .../NetworkDependencies.vcxproj | 3 + .../NetworkDependencies.vcxproj.filters | 3 + Code/Network/NetworkDependencies/Packing.cpp | 36 +-- Code/Network/NetworkDependencies/Packing.h | 6 +- Code/Network/NetworkDependencies/Protocols.h | 11 +- .../NetworkDependencies/Translator.cpp | 18 +- Code/Network/NetworkDependencies/Translator.h | 4 +- Code/Network/OysterNetworkClient/Client.h | 6 +- .../OysterNetworkClient/ClientMain.cpp | 25 ++- Code/Network/OysterNetworkServer/Client.h | 7 +- Code/Network/OysterNetworkServer/IListener.h | 16 -- Code/Network/OysterNetworkServer/Listener.h | 25 --- .../OysterNetworkServer.vcxproj | 3 - .../OysterNetworkServer.vcxproj.filters | 9 - .../OysterNetworkServer/ServerMain.cpp | 29 ++- 25 files changed, 423 insertions(+), 154 deletions(-) create mode 100644 Code/Network/NetworkDependencies/IListener.h rename Code/Network/{OysterNetworkServer => NetworkDependencies}/Listener.cpp (89%) create mode 100644 Code/Network/NetworkDependencies/Listener.h delete mode 100644 Code/Network/OysterNetworkServer/IListener.h delete mode 100644 Code/Network/OysterNetworkServer/Listener.h diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index cac38e71..6d567aca 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -96,8 +96,11 @@ bool Connection::Send(const unsigned char message[]) { int nBytes; unsigned long messageSize = strlen((char*)message); + int optlen = sizeof(int); + int optval = 0; + getsockopt(mySocket, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *)&optval, &optlen); - messageSize = 255; + messageSize = 1000; nBytes = send(mySocket, (char*)message , messageSize, 0); if(nBytes == SOCKET_ERROR) { @@ -111,7 +114,7 @@ bool Connection::Send(const unsigned char message[]) int Connection::Recieve(unsigned char message[]) { int nBytes; - nBytes = recv(mySocket, (char*)message , 255, 0); + nBytes = recv(mySocket, (char*)message , 10000, 0); if(nBytes == SOCKET_ERROR) { //Recv failed diff --git a/Code/Network/NetworkDependencies/IListener.h b/Code/Network/NetworkDependencies/IListener.h new file mode 100644 index 00000000..f08cfb27 --- /dev/null +++ b/Code/Network/NetworkDependencies/IListener.h @@ -0,0 +1,25 @@ +#ifndef NETWORK_SERVER_ILISTENER_H +#define NETWORK_SERVER_ILISTENER_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +namespace Oyster +{ + namespace Network + { + namespace Server + { + class IListener + { + public: + virtual bool Init(unsigned int port) = 0; + virtual int Accept() = 0; + + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/ITranslate.h b/Code/Network/NetworkDependencies/ITranslate.h index 63f18e68..30360dcc 100644 --- a/Code/Network/NetworkDependencies/ITranslate.h +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -9,8 +9,8 @@ namespace Oyster { public: - virtual unsigned char* Translate (Protocols::ProtocolHeader &header ) = 0; - virtual Protocols::ProtocolSet* Translate (Protocols::ProtocolSet* set, unsigned char message[] ) = 0; + virtual unsigned char* Pack (Protocols::ProtocolHeader &header ) = 0; + virtual Protocols::ProtocolSet* Unpack (Protocols::ProtocolSet* set, unsigned char message[] ) = 0; }; } diff --git a/Code/Network/OysterNetworkServer/Listener.cpp b/Code/Network/NetworkDependencies/Listener.cpp similarity index 89% rename from Code/Network/OysterNetworkServer/Listener.cpp rename to Code/Network/NetworkDependencies/Listener.cpp index 5bda043f..4e0d149f 100644 --- a/Code/Network/OysterNetworkServer/Listener.cpp +++ b/Code/Network/NetworkDependencies/Listener.cpp @@ -1,6 +1,6 @@ #include "Listener.h" -using namespace Oyster::Network; +using namespace Oyster::Network::Server; Listener::Listener() { diff --git a/Code/Network/NetworkDependencies/Listener.h b/Code/Network/NetworkDependencies/Listener.h new file mode 100644 index 00000000..f72491c1 --- /dev/null +++ b/Code/Network/NetworkDependencies/Listener.h @@ -0,0 +1,34 @@ +#ifndef NETWORK_SERVER_LISTENER_H +#define NETWORK_SERVER_LISTENER_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "IListener.h" +#include "../NetworkDependencies/Connection.h" + +namespace Oyster +{ + namespace Network + { + namespace Server + { + class Listener + { + public: + Listener(); + ~Listener(); + + bool Init(unsigned int port); + int Accept(); + + private: + ::Oyster::Network::Connection* connection; + + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp index fc26dd34..8418da77 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -2,7 +2,6 @@ #include "../Packing.h" using namespace Oyster::Network::Messages; -using namespace Oyster::Network::Packing; using namespace Oyster::Network::Protocols; MessageHeader::MessageHeader() @@ -14,52 +13,223 @@ MessageHeader::~MessageHeader() { } -void MessageHeader::Translate(ProtocolHeader& header, unsigned char msg[] ) +void MessageHeader::Pack(ProtocolHeader& header, unsigned char msg[] ) { size = 0; - AddInt(header.size, msg); - AddInt(header.packageType, msg); - AddInt(header.clientID, msg); + PackInt(header.size, msg); + PackInt(header.packageType, msg); + PackInt(header.clientID, msg); SetSize(msg); } -void MessageHeader::Translate(unsigned char message[], ProtocolHeader& header) +void MessageHeader::Unpack(unsigned char msg[], ProtocolHeader& header) { size = 0; - header.clientID = GetInt(message); - header.packageType = GetInt(message); - header.size = GetInt(message); + header.clientID = UnpackInt(msg); + header.packageType = UnpackInt(msg); + header.size = UnpackInt(msg); } -void MessageHeader::AddInt(int i, unsigned char msg[]) +/************************** + Pack +**************************/ + +void MessageHeader::PackBool(bool i, unsigned char msg[]) { - Pack(&msg[size], i); + Packing::Pack(&msg[size], i); + size += 1; +} + +void MessageHeader::PackChar(char i, unsigned char msg[]) +{ + Packing::Pack(&msg[size], i); + size += 1; +} + +void MessageHeader::PackUnsignedChar(unsigned char i, unsigned char msg[]) +{ + Packing::Pack(&msg[size], i); + size += 1; +} + +void MessageHeader::PackShort(short i, unsigned char msg[]) +{ + Packing::Pack(&msg[size], i); + size += 2; +} + +void MessageHeader::PackUnsignedShort(unsigned short i, unsigned char msg[]) +{ + Packing::Pack(&msg[size], i); + size += 2; +} + +void MessageHeader::PackInt(int i, unsigned char msg[]) +{ + Packing::Pack(&msg[size], i); size += 4; } -void MessageHeader::AddStr(std::string str, unsigned char msg[]) +void MessageHeader::PackUnsignedInt(unsigned int i, unsigned char msg[]) { - Pack(&msg[size], str); + Packing::Pack(&msg[size], i); + size += 4; +} + +void MessageHeader::PackInt64(__int64 i, unsigned char msg[]) +{ + Packing::Pack(&msg[size], i); + size += 8; +} + +void MessageHeader::PackUnsignedInt64(unsigned __int64 i, unsigned char msg[]) +{ + Packing::Pack(&msg[size], i); + size += 8; +} + +void MessageHeader::PackFloat(float i, unsigned char msg[]) +{ + Packing::Pack(&msg[size], i); + size += 4; +} + +void MessageHeader::PackFloat(float i[], unsigned int elementCount, unsigned char msg[]) +{ + //Pack number of elements + PackUnsignedInt(elementCount, &msg[size]); + + //Pack all elements + for(int j = 0; j < elementCount; j++) + { + PackFloat(i[j], &msg[size]); + } +} + +void MessageHeader::PackDouble(double i, unsigned char msg[]) +{ + Packing::Pack(&msg[size], i); + size += 8; +} + +void MessageHeader::PackStr(char str[], unsigned char msg[]) +{ + Packing::Pack(&msg[size], str); + size += 2 + strlen(str); +} + +void MessageHeader::PackStr(std::string str, unsigned char msg[]) +{ + Packing::Pack(&msg[size], str); size += 2 + str.length(); } -int MessageHeader::GetInt(unsigned char message[]) +/************************** + Unpack +**************************/ + +bool MessageHeader::UnpackBool(unsigned char msg[]) { - int i = Unpacki(&message[size]); + bool i = Packing::Unpackb(&msg[size]); + size += 1; + return i; +} + +char MessageHeader::UnpackChar(unsigned char msg[]) +{ + char i = Packing::Unpackc(&msg[size]); + size += 1; + return i; +} + +unsigned char MessageHeader::UnpackUnsignedChar(unsigned char msg[]) +{ + unsigned char i = Packing::UnpackC(&msg[size]); + size += 1; + return i; +} + +short MessageHeader::UnpackShort(unsigned char msg[]) +{ + short i = Packing::Unpacks(&msg[size]); + size += 2; + return i; +} + +unsigned short MessageHeader::UnpackUnsignedShort(unsigned char msg[]) +{ + unsigned short i = Packing::UnpackS(&msg[size]); + size += 2; + return i; +} + +int MessageHeader::UnpackInt(unsigned char msg[]) +{ + int i = Packing::Unpacki(&msg[size]); size += 4; return i; } -std::string MessageHeader::GetStr(unsigned char message[]) +unsigned int MessageHeader::UnpackUnsignedInt(unsigned char msg[]) { - std::string std = UnpackStr(&message[size]); - size += 2 + std.length(); - return std; + unsigned int i = Packing::UnpackI(&msg[size]); + size += 4; + return i; +} + +__int64 MessageHeader::UnpackInt64(unsigned char msg[]) +{ + __int64 i = Packing::Unpacki64(&msg[size]); + size += 8; + return i; +} + +unsigned __int64 MessageHeader::UnpackUnsignedInt64(unsigned char msg[]) +{ + unsigned __int64 i = Packing::UnpackI64(&msg[size]); + size += 8; + return i; +} + +float MessageHeader::UnpackFloat(unsigned char msg[]) +{ + float i = Packing::Unpackf(&msg[size]); + size += 4; + return i; +} + +float* MessageHeader::UnpackFloat(unsigned int& elementCount, unsigned char msg[]) +{ + float* i; + + elementCount = UnpackUnsignedInt(&msg[size]); + + i = new float[elementCount]; + for(int j = 0; j < elementCount; j++) + { + i[j] = UnpackFloat(&msg[size]); + } + + return i; +} + +double MessageHeader::UnpackDouble(unsigned char msg[]) +{ + double i = Packing::Unpackd(&msg[size]); + size += 8; + return i; +} + +std::string MessageHeader::UnpackStr(unsigned char msg[]) +{ + std::string str = Packing::UnpackStr(&msg[size]); + size += 2 + str.length(); + return str; } void MessageHeader::SetSize(unsigned char msg[]) { - Pack(&msg[0], size); + Packing::Pack(&msg[0], size); } \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.h b/Code/Network/NetworkDependencies/Messages/MessageHeader.h index af9be77f..5852e239 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.h +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.h @@ -1,9 +1,9 @@ #ifndef NETWORK_DEPENDENCIES_MESSAGE_HEADER_H #define NETWORK_DEPENDENCIES_MESSAGE_HEADER_H -///////////////////////////////////////////////////////////////////// -// Created by Pontus Fransson 2013 -///////////////////////////////////////////////////////////////////// +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// #include #include "../Protocols.h" @@ -20,19 +20,60 @@ namespace Oyster MessageHeader(); virtual ~MessageHeader(); - virtual void Translate(Protocols::ProtocolHeader& header, unsigned char msg[] ); - virtual void Translate(unsigned char message[], Protocols::ProtocolHeader& header); - + virtual void Pack(Protocols::ProtocolHeader& header, unsigned char msg[] ); + virtual void Unpack(unsigned char msg[], Protocols::ProtocolHeader& header); protected: - //Add variables to messages - void AddInt(int i, unsigned char msg[]); - void AddStr(std::string str, unsigned char msg[]); + //Pack variables to messages + void PackBool(bool i, unsigned char msg[]); - //Get variables from message - int GetInt(unsigned char message[]); - std::string GetStr(unsigned char message[]); + void PackChar(char i, unsigned char msg[]); + void PackUnsignedChar(unsigned char i, unsigned char msg[]); + void PackShort(short i, unsigned char msg[]); + void PackUnsignedShort(unsigned short i, unsigned char msg[]); + + void PackInt(int i, unsigned char msg[]); + void PackUnsignedInt(unsigned int i, unsigned char msg[]); + + void PackInt64(__int64 i, unsigned char msg[]); + void PackUnsignedInt64(unsigned __int64 i, unsigned char msg[]); + + void PackFloat(float i, unsigned char msg[]); + void PackFloat(float i[], unsigned int elementCount, unsigned char msg[]); + void PackDouble(double i, unsigned char msg[]); + + void PackStr(char str[], unsigned char msg[]); + void PackStr(std::string str, unsigned char msg[]); + + //TODO: Add Pack functions for Vec2, 3, 4 and maybe Matrix. Etc. + + + //Unpack variables from message + bool UnpackBool(unsigned char msg[]); + + char UnpackChar(unsigned char msg[]); + unsigned char UnpackUnsignedChar(unsigned char msg[]); + + short UnpackShort(unsigned char msg[]); + unsigned short UnpackUnsignedShort(unsigned char msg[]); + + int UnpackInt(unsigned char msg[]); + unsigned int UnpackUnsignedInt(unsigned char msg[]); + + __int64 UnpackInt64(unsigned char msg[]); + unsigned __int64 UnpackUnsignedInt64(unsigned char msg[]); + + float UnpackFloat(unsigned char msg[]); + float* UnpackFloat(unsigned int& elementCount, unsigned char msg[]); + double UnpackDouble(unsigned char msg[]); + + std::string UnpackStr(unsigned char msg[]); + + //TODO: Add Unpack functions for Vec2, 3, 4 and maybe Matrix. Etc. + + + //Sets the this->size to first position in msg void SetSize(unsigned char msg[]); private: diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp index 2d3bbe10..ce5ca474 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp @@ -11,17 +11,19 @@ MessageTest::~MessageTest() { } -void MessageTest::Translate(ProtocolHeader& header, unsigned char msg[]) +void MessageTest::Pack(ProtocolHeader& header, unsigned char msg[]) { - MessageHeader::Translate(header, msg); + MessageHeader::Pack(header, msg); - AddStr(static_cast(&header)->textMessage, msg); + PackStr(static_cast(&header)->textMessage, msg); + PackFloat(static_cast(&header)->f, static_cast(&header)->numOfFloats, msg); SetSize(msg); } -void MessageTest::Translate(unsigned char message[], ProtocolHeader& header) +void MessageTest::Unpack(unsigned char msg[], ProtocolHeader& header) { - MessageHeader::Translate(message, header); + MessageHeader::Unpack(msg, header); - static_cast(&header)->textMessage = GetStr(message); + static_cast(&header)->textMessage = UnpackStr(msg); + static_cast(&header)->f = UnpackFloat(static_cast(&header)->numOfFloats, msg); } \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.h b/Code/Network/NetworkDependencies/Messages/MessageTest.h index 62a55f24..203fad23 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageTest.h +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.h @@ -1,9 +1,9 @@ #ifndef NETWORK_DEPENDENCIES_MESSAGE_TEST_H #define NETWORK_DEPENDENCIES_MESSAGE_TEST_H -///////////////////////////////////////////////////////////////////// -// Created by Pontus Fransson 2013 -///////////////////////////////////////////////////////////////////// +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// #include "MessageHeader.h" @@ -19,11 +19,10 @@ namespace Oyster MessageTest(); virtual ~MessageTest(); - virtual void Translate(Protocols::ProtocolHeader& header, unsigned char msg[]); - virtual void Translate(unsigned char message[], Protocols::ProtocolHeader& header); + virtual void Pack(Protocols::ProtocolHeader& header, unsigned char msg[]); + virtual void Unpack(unsigned char msg[], Protocols::ProtocolHeader& header); private: - }; } } diff --git a/Code/Network/NetworkDependencies/Messages/MessagesInclude.h b/Code/Network/NetworkDependencies/Messages/MessagesInclude.h index 4e1980ba..8f4d41e3 100644 --- a/Code/Network/NetworkDependencies/Messages/MessagesInclude.h +++ b/Code/Network/NetworkDependencies/Messages/MessagesInclude.h @@ -1,6 +1,10 @@ #ifndef NETWORK_DEPENDENCIES_MESSAGES_INCLUDE_H #define NETWORK_DEPENDENCIES_MESSAGES_INCLUDE_H +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + #include "MessageHeader.h" #include "MessageTest.h" diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index c395d509..d302efe7 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -160,6 +160,7 @@ + @@ -169,6 +170,8 @@ + + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index 0bb7c6e2..f3cfc718 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -7,6 +7,7 @@ + @@ -18,5 +19,7 @@ + + \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Packing.cpp b/Code/Network/NetworkDependencies/Packing.cpp index 6c6edfda..bd827cfb 100644 --- a/Code/Network/NetworkDependencies/Packing.cpp +++ b/Code/Network/NetworkDependencies/Packing.cpp @@ -33,13 +33,13 @@ namespace Oyster void Pack(unsigned char buffer[], short i) { *buffer++ = i >> 8; - *buffer++ = i; + *buffer++ = (char)i; } void Pack(unsigned char buffer[], unsigned short i) { *buffer++ = i >> 8; - *buffer++ = i; + *buffer++ = (char)i; } //int (32-bit) @@ -62,26 +62,26 @@ namespace Oyster //__int64 (64-bit) void Pack(unsigned char buffer[], __int64 i) { - *buffer++ = i >> 56; - *buffer++ = i >> 48; - *buffer++ = i >> 40; - *buffer++ = i >> 32; - *buffer++ = i >> 24; - *buffer++ = i >> 16; - *buffer++ = i >> 8; - *buffer++ = i; + *buffer++ = (char)(i >> 56); + *buffer++ = (char)(i >> 48); + *buffer++ = (char)(i >> 40); + *buffer++ = (char)(i >> 32); + *buffer++ = (char)(i >> 24); + *buffer++ = (char)(i >> 16); + *buffer++ = (char)(i >> 8); + *buffer++ = (char)i; } void Pack(unsigned char buffer[], unsigned __int64 i) { - *buffer++ = i >> 56; - *buffer++ = i >> 48; - *buffer++ = i >> 40; - *buffer++ = i >> 32; - *buffer++ = i >> 24; - *buffer++ = i >> 16; - *buffer++ = i >> 8; - *buffer++ = i; + *buffer++ = (char)(i >> 56); + *buffer++ = (char)(i >> 48); + *buffer++ = (char)(i >> 40); + *buffer++ = (char)(i >> 32); + *buffer++ = (char)(i >> 24); + *buffer++ = (char)(i >> 16); + *buffer++ = (char)(i >> 8); + *buffer++ = (char)i; } //floating point (32, 64-bit) diff --git a/Code/Network/NetworkDependencies/Packing.h b/Code/Network/NetworkDependencies/Packing.h index 8339ba68..7a52c644 100644 --- a/Code/Network/NetworkDependencies/Packing.h +++ b/Code/Network/NetworkDependencies/Packing.h @@ -1,9 +1,9 @@ #ifndef PACKING_H #define PACKING_H -///////////////////////////////////////////////////////////////////// -// Created by Pontus Fransson 2013 -///////////////////////////////////////////////////////////////////// +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// #include diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h index dcddf797..d11cd682 100644 --- a/Code/Network/NetworkDependencies/Protocols.h +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -23,19 +23,24 @@ namespace Oyster int packageType; int clientID; - ProtocolHeader() { this->packageType = package_type_header; } + ProtocolHeader() { this->packageType = package_type_header; } + virtual ~ProtocolHeader() { } }; struct ProtocolTest : public ProtocolHeader { std::string textMessage; + unsigned int numOfFloats; + float *f; + ProtocolTest() { this->packageType = package_type_test; } + virtual ~ProtocolTest() { delete[] f; } }; class ProtocolSet { public: - PackageType t; + PackageType type; union { ProtocolHeader* pHeader; @@ -45,7 +50,7 @@ namespace Oyster void Release() { - switch(t) + switch(type) { case package_type_header: if(Protocol.pHeader) diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp index 71525172..8e187c36 100644 --- a/Code/Network/NetworkDependencies/Translator.cpp +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -4,7 +4,7 @@ using namespace Oyster::Network; using namespace ::Protocols; using namespace ::Messages; -unsigned char* Translator::Translate( ProtocolHeader &header ) +unsigned char* Translator::Pack( ProtocolHeader &header ) { MessageHeader *message = NULL; @@ -21,7 +21,7 @@ unsigned char* Translator::Translate( ProtocolHeader &header ) if(message != NULL) { - message->Translate(header, this->msg); + message->Pack(header, this->msg); delete message; message = NULL; @@ -30,34 +30,36 @@ unsigned char* Translator::Translate( ProtocolHeader &header ) return msg; } -ProtocolSet* Translator::Translate(ProtocolSet* set, unsigned char msg[] ) +ProtocolSet* Translator::Unpack(ProtocolSet* set, unsigned char msg[] ) { ProtocolHeader *header = new ProtocolHeader(); MessageHeader *message = new MessageHeader(); - message->Translate(msg, *header); + message->Unpack(msg, *header); delete message; message = NULL; //Switch to the correct package. - set->t = (PackageType)header->packageType; - switch(set->t) + set->type = (PackageType)header->packageType; + switch(set->type) { case package_type_header: message = new MessageHeader(); set->Protocol.pHeader = new ProtocolHeader; - message->Translate(msg, *set->Protocol.pHeader); + message->Unpack(msg, *set->Protocol.pHeader); break; case package_type_test: message = new MessageTest(); set->Protocol.pTest = new ProtocolTest; - message->Translate(msg, *set->Protocol.pTest); + message->Unpack(msg, *set->Protocol.pTest); break; } if(message) + { delete message; + } delete header; return set; diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h index 26b5a56c..ef74bc34 100644 --- a/Code/Network/NetworkDependencies/Translator.h +++ b/Code/Network/NetworkDependencies/Translator.h @@ -15,8 +15,8 @@ namespace Oyster Translator () { msg = new unsigned char[256]; }; ~Translator() { if(msg != NULL) { delete [] this->msg; }}; - unsigned char* Translate (Protocols::ProtocolHeader &header ); - Protocols::ProtocolSet* Translate (Protocols::ProtocolSet* set, unsigned char msg[] ); + unsigned char* Pack (Protocols::ProtocolHeader &header ); + Protocols::ProtocolSet* Unpack (Protocols::ProtocolSet* set, unsigned char msg[] ); private: unsigned char* msg; diff --git a/Code/Network/OysterNetworkClient/Client.h b/Code/Network/OysterNetworkClient/Client.h index a48e37d9..0929d721 100644 --- a/Code/Network/OysterNetworkClient/Client.h +++ b/Code/Network/OysterNetworkClient/Client.h @@ -1,9 +1,9 @@ #ifndef NETWORK_CLIENT_CLIENT_H #define NETWORK_CLIENT_CLIENT_H -///////////////////////////////////////////////////////////////////// -// Created by Pontus Fransson 2013 -///////////////////////////////////////////////////////////////////// +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// #include "../NetworkDependencies/Connection.h" diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 47106f74..1976d1fe 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -27,7 +27,7 @@ int main() Client client; //Connect to server - client.Connect(9876, "10.0.0.3"); + client.Connect(9876, "localhost"); chat(client); @@ -52,12 +52,19 @@ void chat(Client &client) { Oyster::Network::Translator *t = new Oyster::Network::Translator(); - unsigned char msgRecv[256] = "\0"; + unsigned char msgRecv[2560] = "\0"; string msgSend = ""; ProtocolSet* set = new ProtocolSet; - ProtocolHeader* header; ProtocolTest test; + test.numOfFloats = 5; + test.f = new float[test.numOfFloats]; + float temp = 12345.5654f; + for(int i = 0; i < 5; i++) + { + test.f[i] = temp; + temp++; + } bool chatDone = false; @@ -65,20 +72,26 @@ void chat(Client &client) { client.Recv(msgRecv); - t->Translate(set, msgRecv); + t->Unpack(set, msgRecv); - switch(set->t) + switch(set->type) { case package_type_header: break; case package_type_test: cout <<"Client 2: " << set->Protocol.pTest->textMessage <Protocol.pTest->numOfFloats; i++) + { + cout << set->Protocol.pTest->f[i] << ' ' ; + } break; } set->Release(); std::getline(std::cin, msgSend); + + if( msgSend != "exit") { @@ -91,7 +104,7 @@ void chat(Client &client) test.size = msgSend.length(); test.textMessage = msgSend; - unsigned char *message = t->Translate(test); + unsigned char *message = t->Pack(test); client.Send(message); } diff --git a/Code/Network/OysterNetworkServer/Client.h b/Code/Network/OysterNetworkServer/Client.h index 05215b31..0e3a6c29 100644 --- a/Code/Network/OysterNetworkServer/Client.h +++ b/Code/Network/OysterNetworkServer/Client.h @@ -1,9 +1,9 @@ #ifndef NETWORK_SERVER_CLIENT_H #define NETWORK_SERVER_CLIENT_H -///////////////////////////////////////////////////////////////////// -// Created by Pontus Fransson 2013 -///////////////////////////////////////////////////////////////////// +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// #include "../NetworkDependencies/Connection.h" @@ -15,7 +15,6 @@ namespace Oyster { class Client { - public: Client(unsigned int socket); ~Client(); diff --git a/Code/Network/OysterNetworkServer/IListener.h b/Code/Network/OysterNetworkServer/IListener.h deleted file mode 100644 index 93b7a935..00000000 --- a/Code/Network/OysterNetworkServer/IListener.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef NETWORK_SERVER_ILISTENER_H -#define NETWORK_SERVER_ILISTENER_H - -///////////////////////////////////////////////////////////////////// -// Created by Pontus Fransson 2013 -///////////////////////////////////////////////////////////////////// - -class IListener -{ -public: - virtual bool Init(unsigned int port) = 0; - virtual int Accept() = 0; - -}; - -#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Listener.h b/Code/Network/OysterNetworkServer/Listener.h deleted file mode 100644 index e621a0bd..00000000 --- a/Code/Network/OysterNetworkServer/Listener.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef NETWORK_SERVER_LISTENER_H -#define NETWORK_SERVER_LISTENER_H - -///////////////////////////////////////////////////////////////////// -// Created by Pontus Fransson 2013 -///////////////////////////////////////////////////////////////////// - -#include "IListener.h" -#include "../NetworkDependencies/Connection.h" - -class Listener -{ -public: - Listener(); - ~Listener(); - - bool Init(unsigned int port); - int Accept(); - -private: - ::Oyster::Network::Connection* connection; - -}; - -#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj index 855b323e..260586da 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj @@ -158,13 +158,10 @@ - - - diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters index 1e38f641..3cb5827c 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters @@ -21,19 +21,10 @@ Source Files - - Source Files - Header Files - - Header Files - - - Header Files - \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 2f954b69..2dfbc875 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -1,8 +1,9 @@ #include #include #include -#include "Listener.h" +#include "../NetworkDependencies/Listener.h" #include "Client.h" +#include "../NetworkDependencies/Packing.h" using namespace std; using namespace Oyster::Network::Server; @@ -17,7 +18,7 @@ using namespace ::Protocols; int main() { - unsigned char* recvBuffer = new unsigned char[256]; + unsigned char* recvBuffer = new unsigned char[5000]; cout << "Server" << endl; Translator t; @@ -45,7 +46,15 @@ int main() ProtocolTest test; test.clientID = 0; test.textMessage = "hej"; - recvBuffer = t.Translate(test); + test.numOfFloats = 500; + test.f = new float[test.numOfFloats]; + float temp = 500.456f; + for(int i = 0; i < test.numOfFloats; i++) + { + test.f[i] = temp; + temp--; + } + recvBuffer = t.Pack(test); client1.Send(recvBuffer); @@ -53,17 +62,27 @@ int main() { client1.Recv(recvBuffer); - t.Translate(set, recvBuffer); + t.Unpack(set, recvBuffer); cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; cout << "Client1: " << set->Protocol.pTest->textMessage << endl; + for(int i = 0; i < set->Protocol.pTest->numOfFloats; i++) + { + cout << set->Protocol.pTest->f[i] << ' '; + } + cout << endl; set->Release(); client2.Send(recvBuffer); client2.Recv(recvBuffer); - t.Translate(set, recvBuffer); + t.Unpack(set, recvBuffer); cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; cout << "Client2: " << set->Protocol.pTest->textMessage << endl; + for(int i = 0; i < set->Protocol.pTest->numOfFloats; i++) + { + cout << set->Protocol.pTest->f[i] << ' '; + } + cout << endl; set->Release(); client1.Send(recvBuffer); } From 45c145439a76da52f899007f24c656c5a2ebfccb Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Mon, 25 Nov 2013 20:27:23 +0100 Subject: [PATCH 29/67] Fixade crash och flyttade initsockets, shutdownsockets. Moved initsocket and shutdownsockets to WinsockFunctions. --- .../NetworkDependencies/Connection.cpp | 14 +++++---- .../Messages/MessageHeader.cpp | 8 ++--- .../NetworkDependencies.vcxproj | 2 ++ .../NetworkDependencies.vcxproj.filters | 2 ++ Code/Network/NetworkDependencies/Translator.h | 2 +- .../NetworkDependencies/WinsockFunctions.cpp | 13 ++++++++ .../NetworkDependencies/WinsockFunctions.h | 11 +++++++ .../OysterNetworkClient/ClientMain.cpp | 27 +++++------------ .../OysterNetworkServer/ServerMain.cpp | 30 +++++-------------- 9 files changed, 57 insertions(+), 52 deletions(-) create mode 100644 Code/Network/NetworkDependencies/WinsockFunctions.cpp create mode 100644 Code/Network/NetworkDependencies/WinsockFunctions.h diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 4cb9c8c1..57287669 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -85,11 +85,8 @@ bool Connection::Send(const unsigned char message[]) { int nBytes; unsigned long messageSize = strlen((char*)message); - int optlen = sizeof(int); - int optval = 0; - getsockopt(this->socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *)&optval, &optlen); - messageSize = 255; + messageSize = 1600; nBytes = send(this->socket, (char*)message , messageSize, 0); if(nBytes == SOCKET_ERROR) { @@ -97,6 +94,8 @@ bool Connection::Send(const unsigned char message[]) return false; } + std::cout << "Size of the sent data: " << nBytes << " bytes" << std::endl; + return true; } @@ -104,7 +103,7 @@ int Connection::Recieve(unsigned char message[]) { int nBytes; - nBytes = recv(this->socket, (char*)message , 255, 0); + nBytes = recv(this->socket, (char*)message, 1600, 0); if(nBytes == SOCKET_ERROR) { //Recv failed @@ -118,6 +117,11 @@ int Connection::Recieve(unsigned char message[]) int Connection::Listen() { + int optlen = sizeof(int); + int optval; + int Return = getsockopt(this->socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *)&optval, &optlen); + std::cout << optval << std::endl; + int clientSocket; if((clientSocket = accept(this->socket, NULL, NULL)) == INVALID_SOCKET) { diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp index 8418da77..66d9bbfc 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -99,12 +99,12 @@ void MessageHeader::PackFloat(float i, unsigned char msg[]) void MessageHeader::PackFloat(float i[], unsigned int elementCount, unsigned char msg[]) { //Pack number of elements - PackUnsignedInt(elementCount, &msg[size]); + PackUnsignedInt(elementCount, msg); //Pack all elements for(int j = 0; j < elementCount; j++) { - PackFloat(i[j], &msg[size]); + PackFloat(i[j], msg); } } @@ -204,12 +204,12 @@ float* MessageHeader::UnpackFloat(unsigned int& elementCount, unsigned char msg[ { float* i; - elementCount = UnpackUnsignedInt(&msg[size]); + elementCount = UnpackUnsignedInt(msg); i = new float[elementCount]; for(int j = 0; j < elementCount; j++) { - i[j] = UnpackFloat(&msg[size]); + i[j] = UnpackFloat(msg); } return i; diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index d302efe7..73eb03d0 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -166,6 +166,7 @@ + @@ -179,6 +180,7 @@ + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index f3cfc718..babc0a34 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -8,6 +8,7 @@ + @@ -21,5 +22,6 @@ + \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h index 514d325c..581bb406 100644 --- a/Code/Network/NetworkDependencies/Translator.h +++ b/Code/Network/NetworkDependencies/Translator.h @@ -16,7 +16,7 @@ namespace Oyster class Translator : public ITranslate { public: - Translator () { msg = new unsigned char[256]; }; + Translator () { msg = new unsigned char[1601]; }; ~Translator() { if(msg != NULL) { delete [] this->msg; }}; unsigned char* Pack (Protocols::ProtocolHeader &header ); diff --git a/Code/Network/NetworkDependencies/WinsockFunctions.cpp b/Code/Network/NetworkDependencies/WinsockFunctions.cpp new file mode 100644 index 00000000..92382ee9 --- /dev/null +++ b/Code/Network/NetworkDependencies/WinsockFunctions.cpp @@ -0,0 +1,13 @@ +#include "WinsockFunctions.h" +#include + +bool InitSockets() +{ + WSADATA wsaData; + return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR; +} + +void ShutdownSockets() +{ + WSACleanup(); +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/WinsockFunctions.h b/Code/Network/NetworkDependencies/WinsockFunctions.h new file mode 100644 index 00000000..a2a3eee0 --- /dev/null +++ b/Code/Network/NetworkDependencies/WinsockFunctions.h @@ -0,0 +1,11 @@ +#ifndef NETWORK_DEPENDENCIES_WINSOCK_FUNCTIONS_H +#define NETWORK_DEPENDENCIES_WINSOCK_FUNCTIONS_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +void ShutdownSockets(); +bool InitSockets(); + +#endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 1976d1fe..719ca872 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -1,18 +1,17 @@ #include -#include "Client.h" #include #include +#include "../NetworkDependencies/WinsockFunctions.h" #include "..\NetworkDependencies\Translator.h" #include "..\NetworkDependencies\Protocols.h" +#include "Client.h" + +#pragma comment(lib, "ws2_32.lib") using namespace std; using namespace Oyster::Network::Protocols;; using namespace Oyster::Network::Client; -#pragma comment(lib, "ws2_32.lib") - -void ShutdownSockets(); -bool InitSockets(); void chat(Client &client); int main() @@ -37,22 +36,11 @@ int main() return 0; } -bool InitSockets() -{ - WSADATA wsaData; - return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR; -} - -void ShutdownSockets() -{ - WSACleanup(); -} - void chat(Client &client) { Oyster::Network::Translator *t = new Oyster::Network::Translator(); - unsigned char msgRecv[2560] = "\0"; + unsigned char msgRecv[1601] = "\0"; string msgSend = ""; ProtocolSet* set = new ProtocolSet; @@ -82,8 +70,9 @@ void chat(Client &client) cout <<"Client 2: " << set->Protocol.pTest->textMessage <Protocol.pTest->numOfFloats; i++) { - cout << set->Protocol.pTest->f[i] << ' ' ; + //cout << set->Protocol.pTest->f[i] << ' ' ; } + cout << endl; break; } @@ -100,8 +89,6 @@ void chat(Client &client) msgSend = "ERROR!"; } - test.packageType = package_type_test; - test.size = msgSend.length(); test.textMessage = msgSend; unsigned char *message = t->Pack(test); diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 2dfbc875..80a59eca 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -1,24 +1,21 @@ #include #include #include +#include "../NetworkDependencies/WinsockFunctions.h" #include "../NetworkDependencies/Listener.h" +#include "../NetworkDependencies/Translator.h" #include "Client.h" -#include "../NetworkDependencies/Packing.h" -using namespace std; -using namespace Oyster::Network::Server; #pragma comment(lib, "ws2_32.lib") -void ShutdownSockets(); -bool InitSockets(); - -#include "../NetworkDependencies/Translator.h" +using namespace std; +using namespace Oyster::Network::Server; using namespace Oyster::Network; using namespace ::Protocols; int main() { - unsigned char* recvBuffer = new unsigned char[5000]; + unsigned char* recvBuffer = new unsigned char[1601]; cout << "Server" << endl; Translator t; @@ -46,9 +43,9 @@ int main() ProtocolTest test; test.clientID = 0; test.textMessage = "hej"; - test.numOfFloats = 500; + test.numOfFloats = 350; test.f = new float[test.numOfFloats]; - float temp = 500.456f; + float temp = 395.456f; for(int i = 0; i < test.numOfFloats; i++) { test.f[i] = temp; @@ -57,7 +54,7 @@ int main() recvBuffer = t.Pack(test); client1.Send(recvBuffer); - + while(1) { client1.Recv(recvBuffer); @@ -94,14 +91,3 @@ int main() system("pause"); return 0; } - -bool InitSockets() -{ - WSADATA wsaData; - return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR; -} - -void ShutdownSockets() -{ - WSACleanup(); -} \ No newline at end of file From f6ade9e4fdf8b62495bbc964ba820abaa9b50d33 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Tue, 26 Nov 2013 13:45:03 +0100 Subject: [PATCH 30/67] ErrorMessages everywhere! --- .../NetworkDependencies/Connection.cpp | 72 ++++++++----------- Code/Network/NetworkDependencies/Connection.h | 12 ++-- .../Network/NetworkDependencies/IConnection.h | 10 +-- .../NetworkDependencies/WinsockFunctions.cpp | 28 +++++++- .../NetworkDependencies/WinsockFunctions.h | 8 ++- Code/Network/OysterNetworkClient/Client.cpp | 25 ++++--- Code/Network/OysterNetworkClient/Client.h | 6 +- .../OysterNetworkClient/ClientMain.cpp | 18 +++-- Code/Network/OysterNetworkServer/Client.cpp | 8 +-- Code/Network/OysterNetworkServer/Client.h | 4 +- .../OysterNetworkServer/ServerMain.cpp | 7 +- 11 files changed, 116 insertions(+), 82 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 57287669..33b932c9 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -2,6 +2,7 @@ #include #include +#include using namespace Oyster::Network; @@ -10,13 +11,12 @@ Connection::~Connection() closesocket( this->socket ); } -bool Connection::Connect(unsigned short port , const char serverName[]) +int Connection::Connect(unsigned short port , const char serverName[]) { struct hostent *hostEnt; if((hostEnt = gethostbyname(serverName)) == NULL) { - //couldn't find host - return false; + return WSAGetLastError(); } struct sockaddr_in server; @@ -26,20 +26,20 @@ bool Connection::Connect(unsigned short port , const char serverName[]) if(connect(this->socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) { - //Error connecting to server - return false; + return WSAGetLastError(); } //connection succesfull! - return true; + return 0; } -bool Connection::InitiateServer(unsigned short port) +int Connection::InitiateServer(unsigned short port) { - if(!initiateSocket()) + int errorCode = 0; + + if((errorCode = initiateSocket()) != 0) { - //Error opening socket! - return false; + return errorCode; } struct sockaddr_in server; @@ -49,39 +49,38 @@ bool Connection::InitiateServer(unsigned short port) if(bind(this->socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) { - //Bind failed!; + errorCode = WSAGetLastError(); closesocket(this->socket); - return false; + return errorCode; } //not our Listen function! its trying to keep our socket open for connections if(listen(this->socket, 5) == SOCKET_ERROR) { - //"Listen failed! + errorCode = WSAGetLastError(); closesocket(this->socket); - return false; + return errorCode; } //Server started! - return true; + return 0; } -bool Connection::InitiateClient() +int Connection::InitiateClient() { - if(!initiateSocket()) - { - return false; - } + int errorCode; + return initiateSocket(); - return true; } -void Connection::Disconnect() +int Connection::Disconnect() { closesocket(this->socket); + + return WSAGetLastError(); } -bool Connection::Send(const unsigned char message[]) +int Connection::Send(const unsigned char message[]) { int nBytes; unsigned long messageSize = strlen((char*)message); @@ -90,13 +89,10 @@ bool Connection::Send(const unsigned char message[]) nBytes = send(this->socket, (char*)message , messageSize, 0); if(nBytes == SOCKET_ERROR) { - //Send failed! - return false; + return WSAGetLastError(); } - std::cout << "Size of the sent data: " << nBytes << " bytes" << std::endl; - - return true; + return 0; } int Connection::Recieve(unsigned char message[]) @@ -106,27 +102,20 @@ int Connection::Recieve(unsigned char message[]) nBytes = recv(this->socket, (char*)message, 1600, 0); if(nBytes == SOCKET_ERROR) { - //Recv failed - return -1; + return WSAGetLastError(); } message[nBytes] = '\0'; - return 1; + return 0; } int Connection::Listen() { - int optlen = sizeof(int); - int optval; - int Return = getsockopt(this->socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *)&optval, &optlen); - std::cout << optval << std::endl; - int clientSocket; if((clientSocket = accept(this->socket, NULL, NULL)) == INVALID_SOCKET) { - //failed - return -1; + return WSAGetLastError(); } return clientSocket; @@ -135,14 +124,13 @@ int Connection::Listen() /////////////////////////////////////// //Private functions /////////////////////////////////////// -bool Connection::initiateSocket() +int Connection::initiateSocket() { this->socket = ::socket(AF_INET, SOCK_STREAM, 0); if(this->socket == SOCKET_ERROR) { - //error opening socket - return false; + return WSAGetLastError(); } - return true; + return 0; } diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index a0019a26..27ad8ac3 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -19,18 +19,18 @@ namespace Oyster Connection(int socket) { this->socket = socket; }; virtual ~Connection(); - virtual bool InitiateServer( unsigned short port ); - virtual bool InitiateClient(); + virtual int InitiateServer( unsigned short port ); + virtual int InitiateClient(); - virtual bool Send(const unsigned char message[]); + virtual int Send(const unsigned char message[]); virtual int Recieve(unsigned char message[]); - virtual void Disconnect(); - virtual bool Connect( unsigned short port , const char serverName[] ); + virtual int Disconnect(); + virtual int Connect( unsigned short port , const char serverName[] ); virtual int Listen(); private: - bool initiateSocket(); + int initiateSocket(); int socket; diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index 51b7631d..628c9f62 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -13,13 +13,13 @@ namespace Oyster { public: - virtual void Disconnect() = 0; - virtual bool Send( const unsigned char message[] ) = 0; + virtual int Disconnect() = 0; + virtual int Send( const unsigned char message[] ) = 0; virtual int Recieve(unsigned char message[]) = 0; - virtual bool InitiateServer( unsigned short port ) { return false; }; - virtual bool InitiateClient() { return false; }; + virtual int InitiateServer( unsigned short port ) { return false; }; + virtual int InitiateClient() { return false; }; virtual int Listen() { return -1; }; - virtual bool Connect( unsigned short port, const char serverName[] ) { return false; }; + virtual int Connect( unsigned short port, const char serverName[] ) { return false; }; }; } } diff --git a/Code/Network/NetworkDependencies/WinsockFunctions.cpp b/Code/Network/NetworkDependencies/WinsockFunctions.cpp index 92382ee9..3419965b 100644 --- a/Code/Network/NetworkDependencies/WinsockFunctions.cpp +++ b/Code/Network/NetworkDependencies/WinsockFunctions.cpp @@ -1,13 +1,37 @@ #include "WinsockFunctions.h" #include -bool InitSockets() +bool InitWinSock() { WSADATA wsaData; return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR; } -void ShutdownSockets() +void ShutdownWinSock() { WSACleanup(); +} + +std::wstring GetErrorMessage(int errorCode) +{ + LPWSTR lpMessage; + std::wstring retVal(L"Succesful"); + + DWORD bufLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , + NULL, + errorCode , + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) , + (LPWSTR)&lpMessage, + 0 , + NULL ); + + if(bufLen) + { + retVal = lpMessage; + + LocalFree(lpMessage); + + return retVal; + } + } \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/WinsockFunctions.h b/Code/Network/NetworkDependencies/WinsockFunctions.h index a2a3eee0..92c8957a 100644 --- a/Code/Network/NetworkDependencies/WinsockFunctions.h +++ b/Code/Network/NetworkDependencies/WinsockFunctions.h @@ -4,8 +4,12 @@ ///////////////////////////////////// // Created by Pontus Fransson 2013 // ///////////////////////////////////// +#include -void ShutdownSockets(); -bool InitSockets(); + +void ShutdownWinSock(); +bool InitWinSock(); + +std::wstring GetErrorMessage(int errorCode); #endif \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/Client.cpp b/Code/Network/OysterNetworkClient/Client.cpp index abe36d71..bcb20992 100644 --- a/Code/Network/OysterNetworkClient/Client.cpp +++ b/Code/Network/OysterNetworkClient/Client.cpp @@ -13,20 +13,29 @@ Client::~Client() connection = 0; } -bool Client::Connect(unsigned int port, char filename[]) +int Client::Connect(unsigned int port, char filename[]) { - connection->InitiateClient(); - connection->Connect(port, filename); + int errorCode; - return true; + if((errorCode = connection->InitiateClient()) != 0) + { + return errorCode; + } + + if((errorCode = connection->Connect(port, filename)) != 0) + { + return errorCode; + } + + return 0; } -void Client::Send(unsigned char msg[]) +int Client::Send(unsigned char msg[]) { - connection->Send(msg); + return connection->Send(msg); } -void Client::Recv(unsigned char msg[]) +int Client::Recv(unsigned char msg[]) { - connection->Recieve(msg); + return connection->Recieve(msg); } \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/Client.h b/Code/Network/OysterNetworkClient/Client.h index 0929d721..4bac0068 100644 --- a/Code/Network/OysterNetworkClient/Client.h +++ b/Code/Network/OysterNetworkClient/Client.h @@ -19,10 +19,10 @@ namespace Oyster Client(); ~Client(); - bool Connect(unsigned int port, char filename[]); + int Connect(unsigned int port, char filename[]); - void Send(unsigned char msg[]); - void Recv(unsigned char msg[]); + int Send(unsigned char msg[]); + int Recv(unsigned char msg[]); private: ::Oyster::Network::Connection* connection; diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 719ca872..d3e36bf5 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -2,8 +2,8 @@ #include #include #include "../NetworkDependencies/WinsockFunctions.h" -#include "..\NetworkDependencies\Translator.h" -#include "..\NetworkDependencies\Protocols.h" +#include "../NetworkDependencies/Translator.h" +#include "../NetworkDependencies/Protocols.h" #include "Client.h" #pragma comment(lib, "ws2_32.lib") @@ -16,9 +16,11 @@ void chat(Client &client); int main() { + int errorCode; + char msgRecv[255] = "\0"; - InitSockets(); + InitWinSock(); cout << "Client" << endl; @@ -26,11 +28,17 @@ int main() Client client; //Connect to server - client.Connect(9876, "localhost"); + errorCode = client.Connect(9876, "localhost"); + + if(errorCode != 0) + { + wstring errorTest = GetErrorMessage(errorCode); + wcout << "errorMessage: " << errorTest << endl; + } chat(client); - ShutdownSockets(); + ShutdownWinSock(); system("pause"); return 0; diff --git a/Code/Network/OysterNetworkServer/Client.cpp b/Code/Network/OysterNetworkServer/Client.cpp index 8c2bdd0d..423523ff 100644 --- a/Code/Network/OysterNetworkServer/Client.cpp +++ b/Code/Network/OysterNetworkServer/Client.cpp @@ -12,12 +12,12 @@ Client::~Client() delete connection; } -void Client::Send(unsigned char buffer[]) +int Client::Send(unsigned char buffer[]) { - connection->Send(buffer); + return connection->Send(buffer); } -void Client::Recv(unsigned char buffer[]) +int Client::Recv(unsigned char buffer[]) { - connection->Recieve(buffer); + return connection->Recieve(buffer); } \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Client.h b/Code/Network/OysterNetworkServer/Client.h index 0e3a6c29..f7d0f7df 100644 --- a/Code/Network/OysterNetworkServer/Client.h +++ b/Code/Network/OysterNetworkServer/Client.h @@ -19,8 +19,8 @@ namespace Oyster Client(unsigned int socket); ~Client(); - void Send(unsigned char buffer[]); - void Recv(unsigned char buffer[]); + int Send(unsigned char buffer[]); + int Recv(unsigned char buffer[]); private: ::Oyster::Network::Connection* connection; diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 80a59eca..06dd59fc 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -18,10 +18,11 @@ int main() unsigned char* recvBuffer = new unsigned char[1601]; cout << "Server" << endl; Translator t; + int errorCode; - if(!InitSockets()) + if(!InitWinSock()) { - cout << "Sockets failed to initialize" << endl; + cout << "errorMessage: unable to start winsock" << endl; } //Create socket @@ -84,7 +85,7 @@ int main() client1.Send(recvBuffer); } - ShutdownSockets(); + ShutdownWinSock(); delete[] recvBuffer; delete set; From 214e29e906d9bce5e5f046643b242c76d2f95c83 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Wed, 27 Nov 2013 11:01:22 +0100 Subject: [PATCH 31/67] OysterByte Added Byte class instead of handling byte messages manually. Converted all functions to use OysterByte. --- .../NetworkDependencies/Connection.cpp | 24 +-- Code/Network/NetworkDependencies/Connection.h | 5 +- .../Network/NetworkDependencies/IConnection.h | 5 +- Code/Network/NetworkDependencies/ITranslate.h | 5 +- .../Messages/MessageHeader.cpp | 169 ++++++++++-------- .../Messages/MessageHeader.h | 65 +++---- .../Messages/MessageTest.cpp | 21 ++- .../Messages/MessageTest.h | 4 +- .../NetworkDependencies.vcxproj | 2 + .../NetworkDependencies.vcxproj.filters | 2 + .../NetworkDependencies/OysterByte.cpp | 94 ++++++++++ Code/Network/NetworkDependencies/OysterByte.h | 49 +++++ .../NetworkDependencies/Translator.cpp | 14 +- Code/Network/NetworkDependencies/Translator.h | 12 +- Code/Network/OysterNetworkClient/Client.cpp | 8 +- Code/Network/OysterNetworkClient/Client.h | 5 +- .../OysterNetworkClient/ClientMain.cpp | 12 +- Code/Network/OysterNetworkServer/Client.cpp | 9 +- Code/Network/OysterNetworkServer/Client.h | 5 +- .../OysterNetworkServer/ServerMain.cpp | 13 +- 20 files changed, 352 insertions(+), 171 deletions(-) create mode 100644 Code/Network/NetworkDependencies/OysterByte.cpp create mode 100644 Code/Network/NetworkDependencies/OysterByte.h diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 57287669..fdd89ef4 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -81,13 +81,11 @@ void Connection::Disconnect() closesocket(this->socket); } -bool Connection::Send(const unsigned char message[]) +bool Connection::Send(OysterByte& bytes) { int nBytes; - unsigned long messageSize = strlen((char*)message); - messageSize = 1600; - nBytes = send(this->socket, (char*)message , messageSize, 0); + nBytes = send(this->socket, bytes, bytes.GetSize(), 0); if(nBytes == SOCKET_ERROR) { //Send failed! @@ -99,29 +97,31 @@ bool Connection::Send(const unsigned char message[]) return true; } -int Connection::Recieve(unsigned char message[]) +int Connection::Recieve(OysterByte& bytes) { int nBytes; - nBytes = recv(this->socket, (char*)message, 1600, 0); + bytes.Clear(1000); + nBytes = recv(this->socket, bytes, 500, 0); if(nBytes == SOCKET_ERROR) { //Recv failed return -1; } + else + { + bytes.SetSize(nBytes); + } - message[nBytes] = '\0'; + std::cout << "Size of the recieved data: " << nBytes << " bytes" << std::endl; + + //bytes.byteArray[nBytes] = '\0'; return 1; } int Connection::Listen() { - int optlen = sizeof(int); - int optval; - int Return = getsockopt(this->socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *)&optval, &optlen); - std::cout << optval << std::endl; - int clientSocket; if((clientSocket = accept(this->socket, NULL, NULL)) == INVALID_SOCKET) { diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index a0019a26..05b35070 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -6,6 +6,7 @@ ////////////////////////////////// #include "IConnection.h" +#include "../NetworkDependencies/OysterByte.h" namespace Oyster { @@ -22,8 +23,8 @@ namespace Oyster virtual bool InitiateServer( unsigned short port ); virtual bool InitiateClient(); - virtual bool Send(const unsigned char message[]); - virtual int Recieve(unsigned char message[]); + virtual bool Send( OysterByte& bytes ); + virtual int Recieve( OysterByte& bytes ); virtual void Disconnect(); virtual bool Connect( unsigned short port , const char serverName[] ); diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index 51b7631d..85b63b77 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -9,13 +9,14 @@ namespace Oyster { namespace Network { + class OysterByte; class IConnection { public: virtual void Disconnect() = 0; - virtual bool Send( const unsigned char message[] ) = 0; - virtual int Recieve(unsigned char message[]) = 0; + virtual bool Send( OysterByte& bytes ) = 0; + virtual int Recieve( OysterByte& bytes) = 0; virtual bool InitiateServer( unsigned short port ) { return false; }; virtual bool InitiateClient() { return false; }; virtual int Listen() { return -1; }; diff --git a/Code/Network/NetworkDependencies/ITranslate.h b/Code/Network/NetworkDependencies/ITranslate.h index e14ad3f1..1143c716 100644 --- a/Code/Network/NetworkDependencies/ITranslate.h +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -9,12 +9,13 @@ namespace Oyster { namespace Network { + class OysterByte; class ITranslate { public: - virtual unsigned char* Pack (Protocols::ProtocolHeader &header ) = 0; - virtual Protocols::ProtocolSet* Unpack (Protocols::ProtocolSet* set, unsigned char message[] ) = 0; + virtual void Pack (Protocols::ProtocolHeader &header, OysterByte& bytes) = 0; + virtual Protocols::ProtocolSet* Unpack (Protocols::ProtocolSet* set, OysterByte& bytes ) = 0; }; } diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp index 66d9bbfc..97c1d12f 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -1,6 +1,9 @@ #include "MessageHeader.h" #include "../Packing.h" +#include +using namespace std; +using namespace Oyster::Network; using namespace Oyster::Network::Messages; using namespace Oyster::Network::Protocols; @@ -13,223 +16,239 @@ MessageHeader::~MessageHeader() { } -void MessageHeader::Pack(ProtocolHeader& header, unsigned char msg[] ) +void MessageHeader::Pack(ProtocolHeader& header, OysterByte& bytes) +{ + size = 0; + + PackInt(header.size, bytes); + PackInt(header.packageType, bytes); + PackInt(header.clientID, bytes); + SetSize(bytes); +} + +void MessageHeader::Unpack(OysterByte& bytes, ProtocolHeader& header) { size = 0; - PackInt(header.size, msg); - PackInt(header.packageType, msg); - PackInt(header.clientID, msg); - SetSize(msg); -} - -void MessageHeader::Unpack(unsigned char msg[], ProtocolHeader& header) -{ - size = 0; - - header.clientID = UnpackInt(msg); - header.packageType = UnpackInt(msg); - header.size = UnpackInt(msg); + header.size = UnpackInt(bytes); + header.packageType = UnpackInt(bytes); + header.clientID = UnpackInt(bytes); } /************************** Pack **************************/ -void MessageHeader::PackBool(bool i, unsigned char msg[]) +void MessageHeader::PackBool(bool i, OysterByte& bytes) { - Packing::Pack(&msg[size], i); + bytes.AddSize(1); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 1; } -void MessageHeader::PackChar(char i, unsigned char msg[]) +void MessageHeader::PackChar(char i, OysterByte& bytes) { - Packing::Pack(&msg[size], i); + bytes.AddSize(1); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 1; } -void MessageHeader::PackUnsignedChar(unsigned char i, unsigned char msg[]) +void MessageHeader::PackUnsignedChar(unsigned char i, OysterByte& bytes) { - Packing::Pack(&msg[size], i); + bytes.AddSize(1); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 1; } -void MessageHeader::PackShort(short i, unsigned char msg[]) +void MessageHeader::PackShort(short i, OysterByte& bytes) { - Packing::Pack(&msg[size], i); + bytes.AddSize(2); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 2; } -void MessageHeader::PackUnsignedShort(unsigned short i, unsigned char msg[]) +void MessageHeader::PackUnsignedShort(unsigned short i, OysterByte& bytes) { - Packing::Pack(&msg[size], i); + bytes.AddSize(2); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 2; } -void MessageHeader::PackInt(int i, unsigned char msg[]) +void MessageHeader::PackInt(int i, OysterByte& bytes) { - Packing::Pack(&msg[size], i); + bytes.AddSize(4); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 4; } -void MessageHeader::PackUnsignedInt(unsigned int i, unsigned char msg[]) +void MessageHeader::PackUnsignedInt(unsigned int i, OysterByte& bytes) { - Packing::Pack(&msg[size], i); + bytes.AddSize(4); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 4; } -void MessageHeader::PackInt64(__int64 i, unsigned char msg[]) +void MessageHeader::PackInt64(__int64 i, OysterByte& bytes) { - Packing::Pack(&msg[size], i); + bytes.AddSize(8); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 8; } -void MessageHeader::PackUnsignedInt64(unsigned __int64 i, unsigned char msg[]) +void MessageHeader::PackUnsignedInt64(unsigned __int64 i, OysterByte& bytes) { - Packing::Pack(&msg[size], i); + bytes.AddSize(8); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 8; } -void MessageHeader::PackFloat(float i, unsigned char msg[]) +void MessageHeader::PackFloat(float i, OysterByte& bytes) { - Packing::Pack(&msg[size], i); + bytes.AddSize(4); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 4; } -void MessageHeader::PackFloat(float i[], unsigned int elementCount, unsigned char msg[]) +void MessageHeader::PackFloat(float i[], unsigned int elementCount, OysterByte& bytes) { + bytes.AddSize(4); //Pack number of elements - PackUnsignedInt(elementCount, msg); + PackUnsignedInt(elementCount, bytes); //Pack all elements for(int j = 0; j < elementCount; j++) { - PackFloat(i[j], msg); + PackFloat(i[j], bytes); } } -void MessageHeader::PackDouble(double i, unsigned char msg[]) -{ - Packing::Pack(&msg[size], i); +void MessageHeader::PackDouble(double i, OysterByte& bytes) +{ + bytes.AddSize(8); + Packing::Pack(&bytes.GetByteArray()[size], i); size += 8; } -void MessageHeader::PackStr(char str[], unsigned char msg[]) +void MessageHeader::PackStr(char str[], OysterByte& bytes) { - Packing::Pack(&msg[size], str); - size += 2 + strlen(str); + int totalSize = 2 + strlen(str); + bytes.AddSize(totalSize); + Packing::Pack(&bytes.GetByteArray()[size], str); + size += totalSize; } -void MessageHeader::PackStr(std::string str, unsigned char msg[]) +void MessageHeader::PackStr(std::string str, OysterByte& bytes) { - Packing::Pack(&msg[size], str); - size += 2 + str.length(); + int totalSize = 2 + str.length(); + bytes.AddSize(totalSize); + Packing::Pack(&bytes.GetByteArray()[size], str); + size += totalSize; } /************************** Unpack **************************/ -bool MessageHeader::UnpackBool(unsigned char msg[]) +bool MessageHeader::UnpackBool(OysterByte& bytes) { - bool i = Packing::Unpackb(&msg[size]); + bool i = Packing::Unpackb(&bytes.GetByteArray()[size]); size += 1; return i; } -char MessageHeader::UnpackChar(unsigned char msg[]) +char MessageHeader::UnpackChar(OysterByte& bytes) { - char i = Packing::Unpackc(&msg[size]); + char i = Packing::Unpackc(&bytes.GetByteArray()[size]); size += 1; return i; } -unsigned char MessageHeader::UnpackUnsignedChar(unsigned char msg[]) +unsigned char MessageHeader::UnpackUnsignedChar(OysterByte& bytes) { - unsigned char i = Packing::UnpackC(&msg[size]); + unsigned char i = Packing::UnpackC(&bytes.GetByteArray()[size]); size += 1; return i; } -short MessageHeader::UnpackShort(unsigned char msg[]) +short MessageHeader::UnpackShort(OysterByte& bytes) { - short i = Packing::Unpacks(&msg[size]); + short i = Packing::Unpacks(&bytes.GetByteArray()[size]); size += 2; return i; } -unsigned short MessageHeader::UnpackUnsignedShort(unsigned char msg[]) +unsigned short MessageHeader::UnpackUnsignedShort(OysterByte& bytes) { - unsigned short i = Packing::UnpackS(&msg[size]); + unsigned short i = Packing::UnpackS(&bytes.GetByteArray()[size]); size += 2; return i; } -int MessageHeader::UnpackInt(unsigned char msg[]) +int MessageHeader::UnpackInt(OysterByte& bytes) { - int i = Packing::Unpacki(&msg[size]); + int i = Packing::Unpacki(&bytes.GetByteArray()[size]); size += 4; return i; } -unsigned int MessageHeader::UnpackUnsignedInt(unsigned char msg[]) +unsigned int MessageHeader::UnpackUnsignedInt(OysterByte& bytes) { - unsigned int i = Packing::UnpackI(&msg[size]); + unsigned int i = Packing::UnpackI(&bytes.GetByteArray()[size]); size += 4; return i; } -__int64 MessageHeader::UnpackInt64(unsigned char msg[]) +__int64 MessageHeader::UnpackInt64(OysterByte& bytes) { - __int64 i = Packing::Unpacki64(&msg[size]); + __int64 i = Packing::Unpacki64(&bytes.GetByteArray()[size]); size += 8; return i; } -unsigned __int64 MessageHeader::UnpackUnsignedInt64(unsigned char msg[]) +unsigned __int64 MessageHeader::UnpackUnsignedInt64(OysterByte& bytes) { - unsigned __int64 i = Packing::UnpackI64(&msg[size]); + unsigned __int64 i = Packing::UnpackI64(&bytes.GetByteArray()[size]); size += 8; return i; } -float MessageHeader::UnpackFloat(unsigned char msg[]) +float MessageHeader::UnpackFloat(OysterByte& bytes) { - float i = Packing::Unpackf(&msg[size]); + float i = Packing::Unpackf(&bytes.GetByteArray()[size]); size += 4; return i; } -float* MessageHeader::UnpackFloat(unsigned int& elementCount, unsigned char msg[]) +float* MessageHeader::UnpackFloat(unsigned int& elementCount, OysterByte& bytes) { float* i; - elementCount = UnpackUnsignedInt(msg); + elementCount = UnpackUnsignedInt(bytes); i = new float[elementCount]; for(int j = 0; j < elementCount; j++) { - i[j] = UnpackFloat(msg); + i[j] = UnpackFloat(bytes); } return i; } -double MessageHeader::UnpackDouble(unsigned char msg[]) +double MessageHeader::UnpackDouble(OysterByte& bytes) { - double i = Packing::Unpackd(&msg[size]); + double i = Packing::Unpackd(&bytes.GetByteArray()[size]); size += 8; return i; } -std::string MessageHeader::UnpackStr(unsigned char msg[]) +std::string MessageHeader::UnpackStr(OysterByte& bytes) { - std::string str = Packing::UnpackStr(&msg[size]); + std::string str = Packing::UnpackStr(&bytes.GetByteArray()[size]); size += 2 + str.length(); return str; } -void MessageHeader::SetSize(unsigned char msg[]) +void MessageHeader::SetSize(OysterByte& bytes) { - Packing::Pack(&msg[0], size); + Packing::Pack(bytes, size); } \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.h b/Code/Network/NetworkDependencies/Messages/MessageHeader.h index 5852e239..095ebc1e 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.h +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.h @@ -7,6 +7,7 @@ #include #include "../Protocols.h" +#include "../OysterByte.h" namespace Oyster { @@ -20,64 +21,64 @@ namespace Oyster MessageHeader(); virtual ~MessageHeader(); - virtual void Pack(Protocols::ProtocolHeader& header, unsigned char msg[] ); - virtual void Unpack(unsigned char msg[], Protocols::ProtocolHeader& header); + virtual void Pack(Protocols::ProtocolHeader& header, OysterByte& bytes ); + virtual void Unpack(OysterByte& bytes, Protocols::ProtocolHeader& header); protected: //Pack variables to messages - void PackBool(bool i, unsigned char msg[]); + void PackBool(bool i, OysterByte& bytes); - void PackChar(char i, unsigned char msg[]); - void PackUnsignedChar(unsigned char i, unsigned char msg[]); + void PackChar(char i, OysterByte& bytes); + void PackUnsignedChar(unsigned char i, OysterByte& bytes); - void PackShort(short i, unsigned char msg[]); - void PackUnsignedShort(unsigned short i, unsigned char msg[]); + void PackShort(short i, OysterByte& bytes); + void PackUnsignedShort(unsigned short i, OysterByte& bytes); - void PackInt(int i, unsigned char msg[]); - void PackUnsignedInt(unsigned int i, unsigned char msg[]); + void PackInt(int i, OysterByte& bytes); + void PackUnsignedInt(unsigned int i, OysterByte& bytes); - void PackInt64(__int64 i, unsigned char msg[]); - void PackUnsignedInt64(unsigned __int64 i, unsigned char msg[]); + void PackInt64(__int64 i, OysterByte& bytes); + void PackUnsignedInt64(unsigned __int64 i, OysterByte& bytes); - void PackFloat(float i, unsigned char msg[]); - void PackFloat(float i[], unsigned int elementCount, unsigned char msg[]); - void PackDouble(double i, unsigned char msg[]); + void PackFloat(float i, OysterByte& bytes); + void PackFloat(float i[], unsigned int elementCount, OysterByte& bytes); + void PackDouble(double i, OysterByte& bytes); - void PackStr(char str[], unsigned char msg[]); - void PackStr(std::string str, unsigned char msg[]); + void PackStr(char str[], OysterByte& bytes); + void PackStr(std::string str, OysterByte& bytes); //TODO: Add Pack functions for Vec2, 3, 4 and maybe Matrix. Etc. //Unpack variables from message - bool UnpackBool(unsigned char msg[]); + bool UnpackBool(OysterByte& bytes); - char UnpackChar(unsigned char msg[]); - unsigned char UnpackUnsignedChar(unsigned char msg[]); + char UnpackChar(OysterByte& bytes); + unsigned char UnpackUnsignedChar(OysterByte& bytes); - short UnpackShort(unsigned char msg[]); - unsigned short UnpackUnsignedShort(unsigned char msg[]); + short UnpackShort(OysterByte& bytes); + unsigned short UnpackUnsignedShort(OysterByte& bytes); - int UnpackInt(unsigned char msg[]); - unsigned int UnpackUnsignedInt(unsigned char msg[]); + int UnpackInt(OysterByte& bytes); + unsigned int UnpackUnsignedInt(OysterByte& bytes); - __int64 UnpackInt64(unsigned char msg[]); - unsigned __int64 UnpackUnsignedInt64(unsigned char msg[]); + __int64 UnpackInt64(OysterByte& bytes); + unsigned __int64 UnpackUnsignedInt64(OysterByte& bytes); - float UnpackFloat(unsigned char msg[]); - float* UnpackFloat(unsigned int& elementCount, unsigned char msg[]); - double UnpackDouble(unsigned char msg[]); + float UnpackFloat(OysterByte& bytes); + float* UnpackFloat(unsigned int& elementCount, OysterByte& bytes); + double UnpackDouble(OysterByte& bytes); - std::string UnpackStr(unsigned char msg[]); + std::string UnpackStr(OysterByte& bytes); //TODO: Add Unpack functions for Vec2, 3, 4 and maybe Matrix. Etc. - //Sets the this->size to first position in msg - void SetSize(unsigned char msg[]); + //Sets the this->size to the first position in msg + void SetSize(OysterByte& bytes); private: - int size; + unsigned int size; }; } diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp index ce5ca474..71f53223 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp @@ -1,5 +1,6 @@ #include "MessageTest.h" +using namespace Oyster::Network; using namespace Oyster::Network::Messages; using namespace Oyster::Network::Protocols; @@ -11,19 +12,21 @@ MessageTest::~MessageTest() { } -void MessageTest::Pack(ProtocolHeader& header, unsigned char msg[]) +void MessageTest::Pack(ProtocolHeader& header, OysterByte& bytes) { - MessageHeader::Pack(header, msg); + MessageHeader::Pack(header, bytes); + unsigned char asd[1000]; + //strcpy_s(asd, bytes.GetSize(), bytes); - PackStr(static_cast(&header)->textMessage, msg); - PackFloat(static_cast(&header)->f, static_cast(&header)->numOfFloats, msg); - SetSize(msg); + PackStr(static_cast(&header)->textMessage, bytes); + PackFloat(static_cast(&header)->f, static_cast(&header)->numOfFloats, bytes); + SetSize(bytes); } -void MessageTest::Unpack(unsigned char msg[], ProtocolHeader& header) +void MessageTest::Unpack(OysterByte& bytes, ProtocolHeader& header) { - MessageHeader::Unpack(msg, header); + MessageHeader::Unpack(bytes, header); - static_cast(&header)->textMessage = UnpackStr(msg); - static_cast(&header)->f = UnpackFloat(static_cast(&header)->numOfFloats, msg); + static_cast(&header)->textMessage = UnpackStr(bytes); + static_cast(&header)->f = UnpackFloat(static_cast(&header)->numOfFloats, bytes); } \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.h b/Code/Network/NetworkDependencies/Messages/MessageTest.h index 203fad23..ff636e56 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageTest.h +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.h @@ -19,8 +19,8 @@ namespace Oyster MessageTest(); virtual ~MessageTest(); - virtual void Pack(Protocols::ProtocolHeader& header, unsigned char msg[]); - virtual void Unpack(unsigned char msg[], Protocols::ProtocolHeader& header); + virtual void Pack(Protocols::ProtocolHeader& header, OysterByte& bytes); + virtual void Unpack(OysterByte& bytes, Protocols::ProtocolHeader& header); private: }; diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index 73eb03d0..5b660b13 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -164,6 +164,7 @@ + @@ -176,6 +177,7 @@ + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index babc0a34..dc3225ff 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -9,6 +9,7 @@ + @@ -23,5 +24,6 @@ + \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/OysterByte.cpp b/Code/Network/NetworkDependencies/OysterByte.cpp new file mode 100644 index 00000000..6f3ecb92 --- /dev/null +++ b/Code/Network/NetworkDependencies/OysterByte.cpp @@ -0,0 +1,94 @@ +#include "OysterByte.h" + +using namespace Oyster::Network; + +OysterByte::OysterByte() +{ + size = 0; + capacity = 10; + byteArray = new unsigned char[capacity]; +} + +OysterByte::OysterByte(int cap) +{ + size = 0; + capacity = cap; + byteArray = new unsigned char[capacity]; +} + +OysterByte::~OysterByte() +{ + delete[] byteArray; +} + +void OysterByte::Clear(unsigned int cap) +{ + delete[] byteArray; + byteArray = new unsigned char[cap]; + size = 0; +} + +int OysterByte::GetSize() +{ + return size; +} + +unsigned char* OysterByte::GetByteArray() +{ + return byteArray; +} + +void OysterByte::AddSize(unsigned int size) +{ + int oldSize = this->size; + this->size += size; + + if(this->size >= capacity) + { + IncreaseCapacity(oldSize); + } +} + +void OysterByte::SetBytes(unsigned char* bytes) +{ + delete[] byteArray; + byteArray = bytes; +} + +void OysterByte::SetSize(unsigned int size) +{ + this->size = size; +} + +OysterByte::operator char*() +{ + return (char*)byteArray; +} + +OysterByte::operator const char*() +{ + return (const char*)byteArray; +} + +OysterByte::operator unsigned char*() +{ + return byteArray; +} + +///////////// +// Private // +///////////// + +void OysterByte::IncreaseCapacity(unsigned int oldSize) +{ + capacity = size * 2; + unsigned char* temp = new unsigned char[capacity]; + + for(int i = 0; i < oldSize; i++) + { + temp[i] = byteArray[i]; + } + + delete[] byteArray; + byteArray = temp; +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/OysterByte.h b/Code/Network/NetworkDependencies/OysterByte.h new file mode 100644 index 00000000..390e4398 --- /dev/null +++ b/Code/Network/NetworkDependencies/OysterByte.h @@ -0,0 +1,49 @@ +#ifndef NETWORK_DEPENDENCIES_OYSTER_BYTE_H +#define NETWORK_DEPENDENCIES_OYSTER_BYTE_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include + +namespace Oyster +{ + namespace Network + { + class OysterByte + { + public: + OysterByte(); + OysterByte(int cap); + virtual ~OysterByte(); + + void Clear(unsigned int cap); + + int GetSize(); + unsigned char* GetByteArray(); + + void AddSize(unsigned int size); + void SetBytes(unsigned char* bytes); + void SetSize(unsigned int size); //Only sets the private variable 'size' + + operator char*(); + operator const char*(); + operator unsigned char*(); + + //unsigned char& operator[](unsigned int id); + + private: + void IncreaseCapacity(unsigned int cap); //Expands the byteArray + + + private: + unsigned char* byteArray; + unsigned int size; + unsigned int capacity; + + }; + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp index 8e187c36..fbd32df0 100644 --- a/Code/Network/NetworkDependencies/Translator.cpp +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -4,7 +4,7 @@ using namespace Oyster::Network; using namespace ::Protocols; using namespace ::Messages; -unsigned char* Translator::Pack( ProtocolHeader &header ) +void Translator::Pack( ProtocolHeader &header, OysterByte& bytes ) { MessageHeader *message = NULL; @@ -21,21 +21,19 @@ unsigned char* Translator::Pack( ProtocolHeader &header ) if(message != NULL) { - message->Pack(header, this->msg); + message->Pack(header, bytes); delete message; message = NULL; } - - return msg; } -ProtocolSet* Translator::Unpack(ProtocolSet* set, unsigned char msg[] ) +ProtocolSet* Translator::Unpack(ProtocolSet* set, OysterByte& bytes ) { ProtocolHeader *header = new ProtocolHeader(); MessageHeader *message = new MessageHeader(); - message->Unpack(msg, *header); + message->Unpack(bytes, *header); delete message; message = NULL; @@ -46,13 +44,13 @@ ProtocolSet* Translator::Unpack(ProtocolSet* set, unsigned char msg[] ) case package_type_header: message = new MessageHeader(); set->Protocol.pHeader = new ProtocolHeader; - message->Unpack(msg, *set->Protocol.pHeader); + message->Unpack(bytes, *set->Protocol.pHeader); break; case package_type_test: message = new MessageTest(); set->Protocol.pTest = new ProtocolTest; - message->Unpack(msg, *set->Protocol.pTest); + message->Unpack(bytes, *set->Protocol.pTest); break; } diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h index 581bb406..44ce39d2 100644 --- a/Code/Network/NetworkDependencies/Translator.h +++ b/Code/Network/NetworkDependencies/Translator.h @@ -8,6 +8,7 @@ #include "Messages/MessagesInclude.h" #include "Protocols.h" #include "ITranslate.h" +#include "OysterByte.h" namespace Oyster { @@ -16,14 +17,15 @@ namespace Oyster class Translator : public ITranslate { public: - Translator () { msg = new unsigned char[1601]; }; - ~Translator() { if(msg != NULL) { delete [] this->msg; }}; + Translator () { /*msg = new unsigned char[1601];*/ }; + ~Translator() { /*if(msg != NULL) { delete [] this->msg; }*/ }; - unsigned char* Pack (Protocols::ProtocolHeader &header ); - Protocols::ProtocolSet* Unpack (Protocols::ProtocolSet* set, unsigned char msg[] ); + void Pack (Protocols::ProtocolHeader &header, OysterByte& bytes ); + Protocols::ProtocolSet* Unpack (Protocols::ProtocolSet* set, OysterByte& bytes ); private: - unsigned char* msg; + //unsigned char* msg; + //OysterByte bytes; }; } diff --git a/Code/Network/OysterNetworkClient/Client.cpp b/Code/Network/OysterNetworkClient/Client.cpp index abe36d71..1c6357b9 100644 --- a/Code/Network/OysterNetworkClient/Client.cpp +++ b/Code/Network/OysterNetworkClient/Client.cpp @@ -21,12 +21,12 @@ bool Client::Connect(unsigned int port, char filename[]) return true; } -void Client::Send(unsigned char msg[]) +void Client::Send(Oyster::Network::OysterByte& bytes) { - connection->Send(msg); + connection->Send(bytes); } -void Client::Recv(unsigned char msg[]) +void Client::Recv(Oyster::Network::OysterByte& bytes) { - connection->Recieve(msg); + connection->Recieve(bytes); } \ No newline at end of file diff --git a/Code/Network/OysterNetworkClient/Client.h b/Code/Network/OysterNetworkClient/Client.h index 0929d721..0ecb2a32 100644 --- a/Code/Network/OysterNetworkClient/Client.h +++ b/Code/Network/OysterNetworkClient/Client.h @@ -6,6 +6,7 @@ ///////////////////////////////////// #include "../NetworkDependencies/Connection.h" +#include "../NetworkDependencies/OysterByte.h" namespace Oyster { @@ -21,8 +22,8 @@ namespace Oyster bool Connect(unsigned int port, char filename[]); - void Send(unsigned char msg[]); - void Recv(unsigned char msg[]); + void Send(OysterByte& bytes); + void Recv(OysterByte& bytes); private: ::Oyster::Network::Connection* connection; diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 719ca872..472ae10a 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -4,12 +4,13 @@ #include "../NetworkDependencies/WinsockFunctions.h" #include "..\NetworkDependencies\Translator.h" #include "..\NetworkDependencies\Protocols.h" +#include "../NetworkDependencies/OysterByte.h" #include "Client.h" #pragma comment(lib, "ws2_32.lib") using namespace std; -using namespace Oyster::Network::Protocols;; +using namespace Oyster::Network::Protocols; using namespace Oyster::Network::Client; void chat(Client &client); @@ -40,7 +41,7 @@ void chat(Client &client) { Oyster::Network::Translator *t = new Oyster::Network::Translator(); - unsigned char msgRecv[1601] = "\0"; + Oyster::Network::OysterByte msgRecv; string msgSend = ""; ProtocolSet* set = new ProtocolSet; @@ -70,13 +71,14 @@ void chat(Client &client) cout <<"Client 2: " << set->Protocol.pTest->textMessage <Protocol.pTest->numOfFloats; i++) { - //cout << set->Protocol.pTest->f[i] << ' ' ; + cout << set->Protocol.pTest->f[i] << ' ' ; } cout << endl; break; } set->Release(); + msgRecv.Clear(1000); std::getline(std::cin, msgSend); @@ -91,9 +93,9 @@ void chat(Client &client) test.textMessage = msgSend; - unsigned char *message = t->Pack(test); + t->Pack(test, msgRecv); - client.Send(message); + client.Send(msgRecv); } else diff --git a/Code/Network/OysterNetworkServer/Client.cpp b/Code/Network/OysterNetworkServer/Client.cpp index 8c2bdd0d..5cc15eec 100644 --- a/Code/Network/OysterNetworkServer/Client.cpp +++ b/Code/Network/OysterNetworkServer/Client.cpp @@ -1,5 +1,6 @@ #include "Client.h" +using namespace Oyster::Network; using namespace Oyster::Network::Server; Client::Client(unsigned int socket) @@ -12,12 +13,12 @@ Client::~Client() delete connection; } -void Client::Send(unsigned char buffer[]) +void Client::Send(OysterByte& bytes) { - connection->Send(buffer); + connection->Send(bytes); } -void Client::Recv(unsigned char buffer[]) +void Client::Recv(OysterByte& bytes) { - connection->Recieve(buffer); + connection->Recieve(bytes); } \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/Client.h b/Code/Network/OysterNetworkServer/Client.h index 0e3a6c29..2c5ba35f 100644 --- a/Code/Network/OysterNetworkServer/Client.h +++ b/Code/Network/OysterNetworkServer/Client.h @@ -6,6 +6,7 @@ ///////////////////////////////////// #include "../NetworkDependencies/Connection.h" +#include "../NetworkDependencies/OysterByte.h" namespace Oyster { @@ -19,8 +20,8 @@ namespace Oyster Client(unsigned int socket); ~Client(); - void Send(unsigned char buffer[]); - void Recv(unsigned char buffer[]); + void Send(OysterByte& bytes); + void Recv(OysterByte& bytes); private: ::Oyster::Network::Connection* connection; diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 80a59eca..94e854f5 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -5,6 +5,7 @@ #include "../NetworkDependencies/Listener.h" #include "../NetworkDependencies/Translator.h" #include "Client.h" +#include "../NetworkDependencies/OysterByte.h" #pragma comment(lib, "ws2_32.lib") @@ -15,7 +16,8 @@ using namespace ::Protocols; int main() { - unsigned char* recvBuffer = new unsigned char[1601]; + OysterByte recvBuffer; + cout << "Server" << endl; Translator t; @@ -42,8 +44,9 @@ int main() ProtocolSet* set = new ProtocolSet; ProtocolTest test; test.clientID = 0; + test.size = 2; test.textMessage = "hej"; - test.numOfFloats = 350; + test.numOfFloats = 35; test.f = new float[test.numOfFloats]; float temp = 395.456f; for(int i = 0; i < test.numOfFloats; i++) @@ -51,14 +54,15 @@ int main() test.f[i] = temp; temp--; } - recvBuffer = t.Pack(test); + + t.Pack(test, recvBuffer); client1.Send(recvBuffer); while(1) { client1.Recv(recvBuffer); - + t.Unpack(set, recvBuffer); cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; cout << "Client1: " << set->Protocol.pTest->textMessage << endl; @@ -85,7 +89,6 @@ int main() } ShutdownSockets(); - delete[] recvBuffer; delete set; system("pause"); From 43b111f0d34a199c4f8b6d40829e37a9290fcceb Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Wed, 27 Nov 2013 11:28:11 +0100 Subject: [PATCH 32/67] Pull MiscBranch --- Code/Network/NetworkDependencies/Connection.cpp | 10 ++++------ Code/Network/NetworkDependencies/Connection.h | 4 ++-- Code/Network/NetworkDependencies/IConnection.h | 2 +- .../NetworkDependencies/Messages/MessageHeader.cpp | 4 ++-- .../NetworkDependencies/Messages/MessageTest.cpp | 2 -- Code/Network/NetworkDependencies/OysterByte.cpp | 2 +- Code/Network/NetworkDependencies/Packing.cpp | 4 ++-- Code/Network/NetworkDependencies/WinsockFunctions.cpp | 2 ++ Code/Network/OysterNetworkServer/ServerMain.cpp | 6 +++--- 9 files changed, 17 insertions(+), 19 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 522caa24..1cf5efb1 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -37,7 +37,7 @@ int Connection::InitiateServer(unsigned short port) { int errorCode = 0; - if((errorCode = initiateSocket()) != 0) + if((errorCode = InitiateSocket()) != 0) { return errorCode; } @@ -68,9 +68,7 @@ int Connection::InitiateServer(unsigned short port) int Connection::InitiateClient() { - int errorCode; - return initiateSocket(); - + return InitiateSocket(); } int Connection::Disconnect() @@ -80,7 +78,7 @@ int Connection::Disconnect() return WSAGetLastError(); } -bool Connection::Send(OysterByte& bytes) +int Connection::Send(OysterByte& bytes) { int nBytes; @@ -129,7 +127,7 @@ int Connection::Listen() /////////////////////////////////////// //Private functions /////////////////////////////////////// -int Connection::initiateSocket() +int Connection::InitiateSocket() { this->socket = ::socket(AF_INET, SOCK_STREAM, 0); if(this->socket == SOCKET_ERROR) diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index ddb3f8b7..34569807 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -23,7 +23,7 @@ namespace Oyster virtual int InitiateServer( unsigned short port ); virtual int InitiateClient(); - virtual bool Send( OysterByte& bytes ); + virtual int Send( OysterByte& bytes ); virtual int Recieve( OysterByte& bytes ); virtual int Disconnect(); @@ -31,7 +31,7 @@ namespace Oyster virtual int Listen(); private: - int initiateSocket(); + int InitiateSocket(); int socket; diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index e836a9c0..2ca895b1 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -15,7 +15,7 @@ namespace Oyster public: virtual int Disconnect() = 0; - virtual bool Send( OysterByte& bytes ) = 0; + virtual int Send( OysterByte& bytes ) = 0; virtual int Recieve( OysterByte& bytes) = 0; virtual int InitiateServer( unsigned short port ) { return false; }; virtual int InitiateClient() { return false; }; diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp index 97c1d12f..97acf526 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -116,7 +116,7 @@ void MessageHeader::PackFloat(float i[], unsigned int elementCount, OysterByte& PackUnsignedInt(elementCount, bytes); //Pack all elements - for(int j = 0; j < elementCount; j++) + for(int j = 0; j < (int)elementCount; j++) { PackFloat(i[j], bytes); } @@ -226,7 +226,7 @@ float* MessageHeader::UnpackFloat(unsigned int& elementCount, OysterByte& bytes) elementCount = UnpackUnsignedInt(bytes); i = new float[elementCount]; - for(int j = 0; j < elementCount; j++) + for(int j = 0; j < (int)elementCount; j++) { i[j] = UnpackFloat(bytes); } diff --git a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp index 71f53223..7fcb1a71 100644 --- a/Code/Network/NetworkDependencies/Messages/MessageTest.cpp +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp @@ -15,8 +15,6 @@ MessageTest::~MessageTest() void MessageTest::Pack(ProtocolHeader& header, OysterByte& bytes) { MessageHeader::Pack(header, bytes); - unsigned char asd[1000]; - //strcpy_s(asd, bytes.GetSize(), bytes); PackStr(static_cast(&header)->textMessage, bytes); PackFloat(static_cast(&header)->f, static_cast(&header)->numOfFloats, bytes); diff --git a/Code/Network/NetworkDependencies/OysterByte.cpp b/Code/Network/NetworkDependencies/OysterByte.cpp index 6f3ecb92..ef7aa434 100644 --- a/Code/Network/NetworkDependencies/OysterByte.cpp +++ b/Code/Network/NetworkDependencies/OysterByte.cpp @@ -84,7 +84,7 @@ void OysterByte::IncreaseCapacity(unsigned int oldSize) capacity = size * 2; unsigned char* temp = new unsigned char[capacity]; - for(int i = 0; i < oldSize; i++) + for(int i = 0; i < (int)oldSize; i++) { temp[i] = byteArray[i]; } diff --git a/Code/Network/NetworkDependencies/Packing.cpp b/Code/Network/NetworkDependencies/Packing.cpp index bd827cfb..f636f891 100644 --- a/Code/Network/NetworkDependencies/Packing.cpp +++ b/Code/Network/NetworkDependencies/Packing.cpp @@ -87,7 +87,7 @@ namespace Oyster //floating point (32, 64-bit) void Pack(unsigned char buffer[], float i) { - int tempFloat = Pack754(i, 32, 8); + __int64 tempFloat = Pack754(i, 32, 8); Pack(buffer, tempFloat); } @@ -269,7 +269,7 @@ namespace Oyster float Unpackf(unsigned char buffer[]) { int tempFloat = Unpacki(buffer); - return Unpack754(tempFloat, 32, 8); + return (float)Unpack754(tempFloat, 32, 8); } double Unpackd(unsigned char buffer[]) diff --git a/Code/Network/NetworkDependencies/WinsockFunctions.cpp b/Code/Network/NetworkDependencies/WinsockFunctions.cpp index 3419965b..ea3c3b00 100644 --- a/Code/Network/NetworkDependencies/WinsockFunctions.cpp +++ b/Code/Network/NetworkDependencies/WinsockFunctions.cpp @@ -34,4 +34,6 @@ std::wstring GetErrorMessage(int errorCode) return retVal; } + //Added this if bufLen is 0 + return retVal; } \ No newline at end of file diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index f7b358ed..ad8e06b9 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -50,7 +50,7 @@ int main() test.numOfFloats = 35; test.f = new float[test.numOfFloats]; float temp = 395.456f; - for(int i = 0; i < test.numOfFloats; i++) + for(int i = 0; i < (int)test.numOfFloats; i++) { test.f[i] = temp; temp--; @@ -67,7 +67,7 @@ int main() t.Unpack(set, recvBuffer); cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; cout << "Client1: " << set->Protocol.pTest->textMessage << endl; - for(int i = 0; i < set->Protocol.pTest->numOfFloats; i++) + for(int i = 0; i < (int)set->Protocol.pTest->numOfFloats; i++) { cout << set->Protocol.pTest->f[i] << ' '; } @@ -80,7 +80,7 @@ int main() t.Unpack(set, recvBuffer); cout << set->Protocol.pTest->clientID << ' ' << set->Protocol.pTest->packageType << ' ' << set->Protocol.pTest->size << endl; cout << "Client2: " << set->Protocol.pTest->textMessage << endl; - for(int i = 0; i < set->Protocol.pTest->numOfFloats; i++) + for(int i = 0; i < (int)set->Protocol.pTest->numOfFloats; i++) { cout << set->Protocol.pTest->f[i] << ' '; } From 6e24acea2b7a2cf964dcdf3eb8cd8fe28aa282c4 Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Wed, 27 Nov 2013 14:33:08 +0100 Subject: [PATCH 33/67] Listener's Accept() is now threaded. Added function private to Connection SetBlockingMode(bool blocking); But it doesn't do anything yet. Listener is now accepting clients in a thread. GetNewClient() returns the socket that has connected. -1 if there is no new client connected. (Can only connect 1 client at a time.) The simple chat program is not working anymore because of changes in the server. --- .../NetworkDependencies/Connection.cpp | 14 +++++ Code/Network/NetworkDependencies/Connection.h | 1 + Code/Network/NetworkDependencies/Listener.cpp | 42 +++++++++++++- Code/Network/NetworkDependencies/Listener.h | 19 +++++- Code/Network/NetworkDependencies/Packing.cpp | 2 +- .../OysterNetworkServer/ServerMain.cpp | 58 +++++++++++++++---- 6 files changed, 121 insertions(+), 15 deletions(-) diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp index 1cf5efb1..3f303542 100644 --- a/Code/Network/NetworkDependencies/Connection.cpp +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -3,6 +3,7 @@ #include #include #include +#include using namespace Oyster::Network; @@ -137,3 +138,16 @@ int Connection::InitiateSocket() return 0; } + +void Connection::SetBlockingMode(bool blocking) +{ + //TODO: Implement this function. Setting the socket to blocking or non-blocking. + if(blocking) + { + //fcntl(this->socket, F_SETFL, O_NONBLOCK); + } + else + { + + } +} \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index 34569807..b6b17c60 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -32,6 +32,7 @@ namespace Oyster private: int InitiateSocket(); + void SetBlockingMode(bool blocking); int socket; diff --git a/Code/Network/NetworkDependencies/Listener.cpp b/Code/Network/NetworkDependencies/Listener.cpp index 4e0d149f..1af94613 100644 --- a/Code/Network/NetworkDependencies/Listener.cpp +++ b/Code/Network/NetworkDependencies/Listener.cpp @@ -4,7 +4,8 @@ using namespace Oyster::Network::Server; Listener::Listener() { - + newSocket = false; + tempSocket = 0; } Listener::~Listener() @@ -21,14 +22,53 @@ bool Listener::Init(unsigned int port) connection->InitiateServer(port); + thread.Create(this, true); return true; } +int Listener::GetNewClient() +{ + mutex.LockMutex(); + int temp = -1; + + if(newSocket) + { + temp = tempSocket; + newSocket = false; + } + mutex.UnlockMutex(); + + return temp; +} + int Listener::Accept() { int clientSocket = 0; clientSocket = connection->Listen(); + mutex.LockMutex(); + tempSocket = clientSocket; + newSocket = true; + mutex.UnlockMutex(); + return clientSocket; +} + +bool Listener::DoWork() +{ + Accept(); + + return true; +} + +#include +void Listener::ThreadEntry() +{ + std::cout << "Thread started" << std::endl; +} + +void Listener::ThreadExit() +{ + std::cout << "Thread stopped" << std::endl; } \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Listener.h b/Code/Network/NetworkDependencies/Listener.h index f72491c1..aa3817cf 100644 --- a/Code/Network/NetworkDependencies/Listener.h +++ b/Code/Network/NetworkDependencies/Listener.h @@ -7,6 +7,9 @@ #include "IListener.h" #include "../NetworkDependencies/Connection.h" +#include "../../Misc/Thread/OysterThread.h" +#include "../../Misc/Thread/OysterMutex.h" + namespace Oyster { @@ -14,7 +17,7 @@ namespace Oyster { namespace Server { - class Listener + class Listener : public ::Oyster::Thread::IThreadObject { public: Listener(); @@ -22,9 +25,23 @@ namespace Oyster bool Init(unsigned int port); int Accept(); + int GetNewClient(); + + //Thread functions + bool DoWork(); + void ThreadEntry(); + void ThreadExit(); + + private: + private: ::Oyster::Network::Connection* connection; + int tempSocket; + bool newSocket; + + ::Oyster::Thread::OysterThread thread; + OysterMutex mutex; }; } diff --git a/Code/Network/NetworkDependencies/Packing.cpp b/Code/Network/NetworkDependencies/Packing.cpp index f636f891..7adc395c 100644 --- a/Code/Network/NetworkDependencies/Packing.cpp +++ b/Code/Network/NetworkDependencies/Packing.cpp @@ -87,7 +87,7 @@ namespace Oyster //floating point (32, 64-bit) void Pack(unsigned char buffer[], float i) { - __int64 tempFloat = Pack754(i, 32, 8); + int tempFloat = Pack754(i, 32, 8); Pack(buffer, tempFloat); } diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index ad8e06b9..6d958e2d 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -30,19 +30,9 @@ int main() //Create socket Listener listener; listener.Init(9876); - + Sleep(1000); //Start listening //Accept a client - int clientSocket = listener.Accept(); - Client client1(clientSocket); - cout << "First client connected." << endl; - - //Accept a client - clientSocket = listener.Accept(); - Client client2(clientSocket); - cout << "Second client connected." << endl; - - ProtocolSet* set = new ProtocolSet; ProtocolTest test; test.clientID = 0; test.size = 2; @@ -57,7 +47,51 @@ int main() } t.Pack(test, recvBuffer); + + while(1) + { + int client = listener.GetNewClient(); + if(client != -1) + { + cout << "Client connected: " << client << endl; + Client client1(client); + client1.Send(recvBuffer); + } + //Sleep(100); + } + + +/* int clientSocket = listener.Accept(); + Client client1(clientSocket); + cout << "First client connected." << endl; + + //Accept a client + clientSocket = listener.Accept(); + Client client2(clientSocket); + cout << "Second client connected." << endl; +*/ + + + /* + ProtocolSet* set = new ProtocolSet; + ProtocolTest test; + test.clientID = 0; + test.size = 2; + test.textMessage = "hej"; + test.numOfFloats = 35; + test.f = new float[test.numOfFloats]; + float temp = 395.456f; + for(int i = 0; i < (int)test.numOfFloats; i++) + { + test.f[i] = temp; + temp--; + } + + t.Pack(test, recvBuffer);*/ + + +/* client1.Send(recvBuffer); while(1) @@ -92,7 +126,7 @@ int main() ShutdownWinSock(); delete set; - + */ system("pause"); return 0; } From 972cfa0d39cb83f06259942b2b10ee319568911f Mon Sep 17 00:00:00 2001 From: dean11 Date: Wed, 27 Nov 2013 21:12:37 +0100 Subject: [PATCH 34/67] Fixed bugs with custom loading --- Code/Misc/Resource/Loaders/ByteLoader.cpp | 2 +- Code/Misc/Resource/Loaders/CustomLoader.cpp | 33 ++++++++--- Code/Misc/Resource/OResource.cpp | 10 ++-- Code/Misc/Resource/OResource.h | 32 +++++++--- Code/Misc/Resource/OResourceHandler.cpp | 65 +++++++++++++++++---- Code/Misc/Resource/OysterResource.h | 51 +++++++++++++--- 6 files changed, 150 insertions(+), 43 deletions(-) diff --git a/Code/Misc/Resource/Loaders/ByteLoader.cpp b/Code/Misc/Resource/Loaders/ByteLoader.cpp index 622d3a71..b20364ff 100644 --- a/Code/Misc/Resource/Loaders/ByteLoader.cpp +++ b/Code/Misc/Resource/Loaders/ByteLoader.cpp @@ -152,7 +152,7 @@ OResource* OResource::ByteLoader(const wchar_t filename[], ResourceType type, OR if(!old) { - resource = new OResource((OHRESOURCE)data, type, (sizeof(char) * sOut.size()), sizeof(char), filename); + resource = new OResource((OHRESOURCE&)data, type, (sizeof(char) * sOut.size()), sizeof(char), filename); } else { diff --git a/Code/Misc/Resource/Loaders/CustomLoader.cpp b/Code/Misc/Resource/Loaders/CustomLoader.cpp index 312c4c53..1e030a6b 100644 --- a/Code/Misc/Resource/Loaders/CustomLoader.cpp +++ b/Code/Misc/Resource/Loaders/CustomLoader.cpp @@ -12,34 +12,49 @@ using namespace Oyster::Resource; OResource* OResource::CustomLoader(const wchar_t filename[], CustomLoadFunction fnc) { - const CustomData &data = fnc(filename); + CustomData data; + memset(&data, 0, sizeof(CustomData)); - if(!data.loadedData) return 0; - if(!data.resourceUnloadFnc) return 0; + fnc(filename, data); + + if(!data.loadedData) + { + return 0; + } + if(!data.resourceUnloadFnc) + { + return 0; + } + /** For some wierd reason that i don't understand when trying to send data.loadedData directly as a + * parameter to OResource constructor, the value is changed when it arrives in the constructor. + * Doing it like this, storing in a temporary variable, the value stays correct. (What the fuck! I must be overloking something...)*/ + //OHRESOURCE temp = data.loadedData; + OResource *resource = new OResource(data.loadedData, ResourceType_UNKNOWN, 0, 0, filename); - OResource *resource = new OResource((OHRESOURCE)data.loadedData, ResourceType_UNKNOWN, 0, 0, filename); - resource->customData = new CustomResourceData(); resource->customData->unloadingFunction = data.resourceUnloadFnc; - resource->resourceData = (OHRESOURCE)data.loadedData; resource->customData->loadingFunction = fnc; return resource; } void OResource::CustomUnloader() { - this->customData->unloadingFunction((void*)this->resourceData); + this->customData->unloadingFunction(this->resourceData); } OResource* OResource::CustomReloader() { CustomUnloader(); - const CustomData &data = this->customData->loadingFunction(this->resourceFilename.c_str()); + CustomData data; + memset(&data, 0, sizeof(CustomData)); + + this->customData->loadingFunction(this->resourceFilename.c_str(), data); this->resourceData = (OHRESOURCE)data.loadedData; if(data.resourceUnloadFnc) + { this->customData->unloadingFunction = data.resourceUnloadFnc; - + } return this; } diff --git a/Code/Misc/Resource/OResource.cpp b/Code/Misc/Resource/OResource.cpp index 4311669f..e2aab644 100644 --- a/Code/Misc/Resource/OResource.cpp +++ b/Code/Misc/Resource/OResource.cpp @@ -7,17 +7,19 @@ using namespace Oyster::Resource; OResource::OResource(OHRESOURCE handle, ResourceType type, size_t resourceSize, size_t elementSize, ::std::wstring filename) - : resourceData (handle) - , resourceFilename (filename) + : resourceFilename (filename) , resourceSize (resourceSize) , resourceElementSize (elementSize) , resourceType (type) , customData (0) { - + resourceData = handle; } OResource::~OResource() -{} +{ + delete this->customData; + this->customData = 0; +} OResource* OResource::Load (const wchar_t filename[], ResourceType type) diff --git a/Code/Misc/Resource/OResource.h b/Code/Misc/Resource/OResource.h index c0e32ba5..a0573c92 100644 --- a/Code/Misc/Resource/OResource.h +++ b/Code/Misc/Resource/OResource.h @@ -27,19 +27,33 @@ namespace Oyster virtual~ OResource(); inline ResourceType GetResourceType() const - { return this->resourceType; } + { + return this->resourceType; + } inline const wchar_t* GetResourceFilename() const - { return this->resourceFilename.c_str(); } + { + return this->resourceFilename.c_str(); + } inline OHRESOURCE GetResourceHandle() const - { return this->resourceData; } + { + return this->resourceData; + } inline unsigned long long GetResourceSize() const - { return this->resourceSize; } + { + return this->resourceSize; + } inline unsigned long long GetResourceElementSize() const - { return this->resourceElementSize; } + { + return this->resourceElementSize; + } inline unsigned int GetResourceID() const - { return this->resourceID; } - inline void SetResourceID(unsigned int id) - { this->resourceID = id; } + { + return this->resourceID; + } + inline void SetResourceID(int id) + { + this->resourceID = id; + } public: static OResource* Load (const wchar_t filename[], ResourceType type); @@ -63,7 +77,7 @@ namespace Oyster size_t resourceSize; size_t resourceElementSize; ::std::wstring resourceFilename; - unsigned int resourceID; + int resourceID; CustomResourceData *customData; }; diff --git a/Code/Misc/Resource/OResourceHandler.cpp b/Code/Misc/Resource/OResourceHandler.cpp index 9d911875..21653d4e 100644 --- a/Code/Misc/Resource/OResourceHandler.cpp +++ b/Code/Misc/Resource/OResourceHandler.cpp @@ -43,7 +43,7 @@ OHRESOURCE OysterResource::LoadResource(const wchar_t* filename, ResourceType ty return resourceData->GetResourceHandle(); } -OHRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunction loadFnc, unsigned int CustomId) +OHRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunction loadFnc, int CustomId) { if(!filename) return 0; if(!loadFnc) return 0; @@ -67,14 +67,14 @@ OHRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunc return (OHRESOURCE)resourceData->GetResourceHandle(); } -OHRESOURCE ReloadResource(const wchar_t filename[]) +OHRESOURCE OysterResource::ReloadResource(const wchar_t filename[]) { OResource *resourceData = resourcePrivate.FindResource(filename); if(!resourceData) return 0; //The resource has not been loaded return OResource::Reload(resourceData)->GetResourceHandle(); } -OHRESOURCE ReloadResource(OHRESOURCE resource) +OHRESOURCE OysterResource::ReloadResource(OHRESOURCE resource) { OResource *resourceData = resourcePrivate.FindResource(resource); if(!resourceData) return 0; //The resource has not been loaded @@ -89,12 +89,13 @@ void OysterResource::Clean() for (i; i != last; i++) { - if(OResource::Release(i->second)) - { - const wchar_t* temp = i->second->GetResourceFilename(); - delete resourcePrivate.resources[temp]; - resourcePrivate.resources.erase(temp); - } + //Remove all the references + while (!OResource::Release(i->second)); + + const wchar_t* temp = i->second->GetResourceFilename(); + delete resourcePrivate.resources[temp]; + resourcePrivate.resources.erase(temp); + } } void OysterResource::ReleaseResource(const OHRESOURCE& resourceData) @@ -110,6 +111,19 @@ void OysterResource::ReleaseResource(const OHRESOURCE& resourceData) } } } +void OysterResource::ReleaseResource(const wchar_t filename[]) +{ + OResource* t = resourcePrivate.FindResource(filename); + if(t) + { + if(OResource::Release(t)) + { + const wchar_t* temp = t->GetResourceFilename(); + delete resourcePrivate.resources[temp]; + resourcePrivate.resources.erase(temp); + } + } +} void OysterResource::SetResourceId (const OHRESOURCE& resourceData, unsigned int id) { @@ -117,13 +131,27 @@ void OysterResource::SetResourceId (const OHRESOURCE& resourceData, unsigned int if(t) t->SetResourceID(id); } +void OysterResource::SetResourceId(const wchar_t c[], unsigned int id) +{ + OResource* t = resourcePrivate.FindResource(c); + + if(t) t->SetResourceID(id); +} ResourceType OysterResource::GetResourceType (const OHRESOURCE& resourceData) { OResource* t = resourcePrivate.FindResource(resourceData); if(t) return t->GetResourceType(); - return ResourceType_UNKNOWN; + return ResourceType_INVALID; +} +ResourceType OysterResource::GetResourceType (const wchar_t c[]) +{ + OResource* t = resourcePrivate.FindResource(c); + + if(t) return t->GetResourceType(); + + return ResourceType_INVALID; } const wchar_t* OysterResource::GetResourceFilename (const OHRESOURCE& resourceData) { @@ -133,7 +161,15 @@ const wchar_t* OysterResource::GetResourceFilename (const OHRESOURCE& resourceDa return 0; } -unsigned int OysterResource::GetResourceId (const OHRESOURCE& resourceData) +OHRESOURCE OysterResource::GetResourceHandle(const wchar_t filename[]) +{ + OResource* t = resourcePrivate.FindResource(filename); + + if(t) return t->GetResourceHandle(); + + return 0; +} +int OysterResource::GetResourceId (const OHRESOURCE& resourceData) { OResource* t = resourcePrivate.FindResource(resourceData); @@ -141,7 +177,14 @@ unsigned int OysterResource::GetResourceId (const OHRESOURCE& resourceData) return -1; } +int OysterResource::GetResourceId(const wchar_t c[]) +{ + OResource* t = resourcePrivate.FindResource(c); + if(t) return t->GetResourceID(); + + return -1; +} OResource* ResourcePrivate::FindResource(const OHRESOURCE& h) const diff --git a/Code/Misc/Resource/OysterResource.h b/Code/Misc/Resource/OysterResource.h index 16d5122d..8fc0e560 100644 --- a/Code/Misc/Resource/OysterResource.h +++ b/Code/Misc/Resource/OysterResource.h @@ -12,11 +12,11 @@ namespace Oyster { struct CustomData; /** A Resource handle representing various resources */ - typedef unsigned long OHRESOURCE; + typedef void* OHRESOURCE; /** Typedef on a fuction required for custom unloading */ typedef void(*CustomUnloadFunction)(void* loadedData); /** Typedef on a fuction required for custom loading */ - typedef const CustomData&(*CustomLoadFunction)(const wchar_t filename[]); + typedef void(*CustomLoadFunction)(const wchar_t filename[], CustomData& outData); /** An enum class representing all avalible resources that is supported. */ enum ResourceType @@ -31,15 +31,14 @@ namespace Oyster ResourceType_COUNT, /**< Not used. */ ResourceType_UNKNOWN = -1, /**< Handle can be interpeted as void* */ + ResourceType_INVALID = -2, /**< Invalid or non existing resource */ }; - /** A struct to return when doing a custom resource Load - * By loading this way you are handing over the ownership to the resource loaded. - */ + /** A struct to fill when doing a custom resource Load. */ struct CustomData { - void* loadedData; /// Date: Wed, 27 Nov 2013 21:47:32 +0100 Subject: [PATCH 35/67] Fixed bugs in the threading wrapper --- Code/Misc/Thread/OysterMutex.cpp | 5 - Code/Misc/Thread/OysterMutex.h | 2 - Code/Misc/Thread/OysterThread.h | 6 +- Code/Misc/Thread/OysterThread_Impl.cpp | 124 +++++++++++++++---------- Code/Misc/Utilities-InlineImpl.h | 17 ++-- Code/Misc/Utilities.h | 1 + 6 files changed, 86 insertions(+), 69 deletions(-) diff --git a/Code/Misc/Thread/OysterMutex.cpp b/Code/Misc/Thread/OysterMutex.cpp index a8dfd20f..089323ce 100644 --- a/Code/Misc/Thread/OysterMutex.cpp +++ b/Code/Misc/Thread/OysterMutex.cpp @@ -63,9 +63,4 @@ void OysterMutex::UnlockMutex() bool OysterMutex::IsTaken() { return !this->mutex.try_lock(); -} -void OysterMutex::Reset() -{ - if(!this->mutex.try_lock()) - this->mutex.unlock(); } \ No newline at end of file diff --git a/Code/Misc/Thread/OysterMutex.h b/Code/Misc/Thread/OysterMutex.h index b36585c1..18282499 100644 --- a/Code/Misc/Thread/OysterMutex.h +++ b/Code/Misc/Thread/OysterMutex.h @@ -20,8 +20,6 @@ public: void UnlockMutex(); /** Returns true if mutex is taken */ bool IsTaken(); - /** This function resets resource locking */ - void Reset(); private: std::mutex mutex; diff --git a/Code/Misc/Thread/OysterThread.h b/Code/Misc/Thread/OysterThread.h index 873497ad..05a9f8ad 100644 --- a/Code/Misc/Thread/OysterThread.h +++ b/Code/Misc/Thread/OysterThread.h @@ -6,7 +6,6 @@ #define MISC_OYSTER_THREAD_H #include "IThreadObject.h" - namespace Oyster { namespace Thread @@ -23,11 +22,10 @@ namespace Oyster struct PrivateData; PrivateData *privateData; - OysterThread(const OysterThread& original); - const OysterThread& operator=(const OysterThread& original); - public: OysterThread(); + OysterThread(const OysterThread& original); + const OysterThread& operator=(const OysterThread& original); virtual~OysterThread(); OYSTER_THREAD_ERROR Create(IThreadObject* worker, bool start); diff --git a/Code/Misc/Thread/OysterThread_Impl.cpp b/Code/Misc/Thread/OysterThread_Impl.cpp index 171c8aa9..9b01e6d5 100644 --- a/Code/Misc/Thread/OysterThread_Impl.cpp +++ b/Code/Misc/Thread/OysterThread_Impl.cpp @@ -7,6 +7,7 @@ #include "..\Utilities.h" #include #include +#include using namespace Oyster::Thread; using namespace Utility::DynamicMemory::SmartPointer; @@ -24,24 +25,23 @@ using namespace Utility::DynamicMemory::SmartPointer; OYSTER_THREAD_STATE_RUNNING, OYSTER_THREAD_STATE_PAUSED, OYSTER_THREAD_STATE_STOPED, - OYSTER_THREAD_STATE_TERMINATED, OYSTER_THREAD_STATE_DEAD, }; - //TODO: Add a threadStartPackage struct that contains all the necasary data to fire of a thread + struct ThreadData { - OYSTER_THREAD_STATE state; // workerThread; // state; // workerThread; // msec; //callingThread; threadData->state = OYSTER_THREAD_STATE_STOPED; } + PrivateData(const PrivateData& o) + { + threadData = o.threadData; + } ~PrivateData() { //@todo TODO: Make detatch avalible. @@ -70,35 +74,46 @@ using namespace Utility::DynamicMemory::SmartPointer; #pragma endregion - +int tempId = 0; +std::vector IDS; static void ThreadingFunction(StdSmartPointer &origin) { + bool shouldContinue; StdSmartPointer w = origin; theBegining: - while(w->state == OYSTER_THREAD_STATE_STOPED); - w->mutexLock.LockMutex(); - w->owner->ThreadEntry(); - w->mutexLock.UnlockMutex(); + while(w->state == OYSTER_THREAD_STATE_STOPED) + { + std::this_thread::yield(); + } + +// w->mutexLock.LockMutex(); + if(w->owner) + { + w->owner->ThreadEntry(); + } +// w->mutexLock.UnlockMutex(); while (w->state != OYSTER_THREAD_STATE_STOPED && w->state != OYSTER_THREAD_STATE_DEAD) { - - w->mutexLock.LockMutex(); +// w->mutexLock.LockMutex(); { - shouldContinue = w->owner->DoWork(); + if(w->owner) + { + shouldContinue = w->owner->DoWork(); + } } - w->mutexLock.UnlockMutex(); +// w->mutexLock.UnlockMutex(); if(!shouldContinue) { goto theEnd; } - if(w->state == OYSTER_THREAD_STATE_TERMINATED) + if(w->state == OYSTER_THREAD_STATE_DEAD) { - return; + goto theEnd; } else if(w->state == OYSTER_THREAD_STATE_RESET) { @@ -109,19 +124,26 @@ theBegining: std::this_thread::sleep_for(std::chrono::milliseconds(w->msec)); } - while (w->state == OYSTER_THREAD_STATE_PAUSED); + while (w->state == OYSTER_THREAD_STATE_PAUSED) + { + std::this_thread::yield(); + } } if(w->state == OYSTER_THREAD_STATE_DEAD) { + w->workerThread->detach(); return; } theEnd: - w->mutexLock.LockMutex(); - w->owner->ThreadExit(); - w->mutexLock.UnlockMutex(); +// w->mutexLock.LockMutex(); + if(w->owner) + { + w->owner->ThreadExit(); + } +// w->mutexLock.UnlockMutex(); w->state = OYSTER_THREAD_STATE_DEAD; } @@ -130,6 +152,14 @@ OysterThread::OysterThread() { this->privateData = new PrivateData(); } +OysterThread::OysterThread(const OysterThread& original) +{ + this->privateData = new PrivateData(*original.privateData); +} +const OysterThread& OysterThread::operator=(const OysterThread& original) +{ + return *this; +} OysterThread::~OysterThread() { delete this->privateData; @@ -153,30 +183,33 @@ OYSTER_THREAD_ERROR OysterThread::Create(IThreadObject* worker, bool start) if(start) { - //@todo TODO: No need to lock since the other thread end is only reading this value. Worst case scenario is n lost cycles. this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; } return OYSTER_THREAD_ERROR_SUCCESS; } OYSTER_THREAD_ERROR OysterThread::Start() { + if(!this->privateData->threadData->owner) + return OYSTER_THREAD_ERROR_FAILED; if(!this->privateData->threadData->workerThread) return OYSTER_THREAD_ERROR_FAILED; + if(this->privateData->threadData->state == OYSTER_THREAD_STATE_DEAD) + return OYSTER_THREAD_ERROR_FAILED; this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; return OYSTER_THREAD_ERROR_SUCCESS; } void OysterThread::Stop() { - this->privateData->threadData->mutexLock.LockMutex(); - this->privateData->threadData->state = OYSTER_THREAD_STATE_STOPED; - this->privateData->threadData->mutexLock.UnlockMutex(); + //this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_STOPED; + //this->privateData->threadData->mutexLock.UnlockMutex(); } void OysterThread::Pause() { - this->privateData->threadData->mutexLock.LockMutex(); - this->privateData->threadData->state = OYSTER_THREAD_STATE_PAUSED; - this->privateData->threadData->mutexLock.UnlockMutex(); + //this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_PAUSED; + //this->privateData->threadData->mutexLock.UnlockMutex(); } void OysterThread::Pause(int msec) { @@ -187,39 +220,34 @@ void OysterThread::Pause(int msec) } else { - this->privateData->threadData->mutexLock.LockMutex(); - this->privateData->threadData->state = OYSTER_THREAD_STATE_PAUSED; - this->privateData->threadData->msec = msec; - this->privateData->threadData->mutexLock.UnlockMutex(); + //this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_PAUSED; + this->privateData->threadData->msec = msec; + //this->privateData->threadData->mutexLock.UnlockMutex(); } } void OysterThread::Resume() { - this->privateData->threadData->mutexLock.LockMutex(); +// this->privateData->threadData->mutexLock.LockMutex(); this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; - this->privateData->threadData->mutexLock.UnlockMutex(); +// this->privateData->threadData->mutexLock.UnlockMutex(); } OYSTER_THREAD_ERROR OysterThread::Reset(IThreadObject* worker) { - this->privateData->threadData->mutexLock.LockMutex(); +// this->privateData->threadData->mutexLock.LockMutex(); if(worker) { this->privateData->threadData->owner = worker; } this->privateData->threadData->callingThread = std::this_thread::get_id(); this->privateData->threadData->msec = 0; - this->privateData->threadData->mutexLock.UnlockMutex(); +// this->privateData->threadData->mutexLock.UnlockMutex(); return OYSTER_THREAD_ERROR_SUCCESS; } void OysterThread::Terminate() { - delete this->privateData->threadData->workerThread; - this->privateData->threadData->mutexLock.Reset(); - this->privateData->threadData->workerThread = 0; - this->privateData->threadData->callingThread = std::thread::id(); - this->privateData->threadData->msec = 0; - this->privateData->threadData->state = OYSTER_THREAD_STATE_STOPED; + this->privateData->threadData->state = OYSTER_THREAD_STATE_DEAD; } void OysterThread::Wait() { @@ -250,4 +278,4 @@ bool OysterThread::IsActive() return false; } - \ No newline at end of file + diff --git a/Code/Misc/Utilities-InlineImpl.h b/Code/Misc/Utilities-InlineImpl.h index b8c4c6da..0cd164d8 100644 --- a/Code/Misc/Utilities-InlineImpl.h +++ b/Code/Misc/Utilities-InlineImpl.h @@ -165,8 +165,7 @@ namespace Utility namespace SmartPointer { - template - void StdSmartPointer::Destroy() + template void StdSmartPointer::Destroy() { delete this->_rc; this->_rc = NULL; @@ -200,7 +199,7 @@ namespace Utility if (this != &p) { //Last to go? - if(this->_rc && this->_rc->Release() == 0) + if(this->_rc && this->_rc->Decref() == 0) { //Call child specific Destroy(); @@ -208,7 +207,7 @@ namespace Utility this->_ptr = p._ptr; this->_rc = p._rc; - this->_rc->Add(); + this->_rc->Incref(); } return *this; } @@ -254,16 +253,14 @@ namespace Utility { return this->_ptr; } - - /** - * Returns the connected pointer */ + template inline StdSmartPointer::operator bool() + { + return (this->_ptr != 0); + } template inline T* StdSmartPointer::Get() { return this->_ptr; } - - /** Checks if the pointer is valid (not NULL) - Returns true for valid, else false. */ template inline bool StdSmartPointer::IsValid() { return (this->_ptr != NULL) ? true : false; diff --git a/Code/Misc/Utilities.h b/Code/Misc/Utilities.h index e1582697..8eaf18f4 100644 --- a/Code/Misc/Utilities.h +++ b/Code/Misc/Utilities.h @@ -151,6 +151,7 @@ namespace Utility T& operator* (); T* operator-> (); operator T* (); + operator bool(); /** * Returns the connected pointer */ From 5eec570768da886625ebce6bad60a7bfb74a4941 Mon Sep 17 00:00:00 2001 From: dean11 Date: Wed, 27 Nov 2013 22:39:49 +0100 Subject: [PATCH 36/67] Added an atomic to the reference counter for thread saftey --- Code/Misc/Utilities.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Code/Misc/Utilities.h b/Code/Misc/Utilities.h index 8eaf18f4..f34907de 100644 --- a/Code/Misc/Utilities.h +++ b/Code/Misc/Utilities.h @@ -12,6 +12,7 @@ #include #include #include +#include namespace Utility { @@ -110,12 +111,12 @@ namespace Utility struct ReferenceCount { private: - int count; + std::atomic count; public: ReferenceCount() :count(0) { } - ReferenceCount(const ReferenceCount& o) { count = o.count; } - inline const ReferenceCount& operator=(const ReferenceCount& o) { count = o.count; return *this;} + ReferenceCount(const ReferenceCount& o) { count.store(o.count); } + inline const ReferenceCount& operator=(const ReferenceCount& o) { count.store(o.count); return *this;} inline void Incref() { this->count++; } inline void Incref(int c) { this->count += c; } inline int Decref() { return --this->count;} From d29046652eb71501278d74b480f722cbe5b0daae Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Thu, 28 Nov 2013 08:40:08 +0100 Subject: [PATCH 37/67] enum type naming fixed --- Code/Network/NetworkDependencies/Protocols.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h index 95f68942..65beb400 100644 --- a/Code/Network/NetworkDependencies/Protocols.h +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -15,10 +15,10 @@ namespace Oyster { enum PackageType { - package_type_header, - package_type_test, - package_type_input, - package_type_update_position + PackageType_header, + PackageType_test, + PackageType_input, + PackageType_update_position }; struct ProtocolHeader From a59cd5468802967536ee5873461b48b41751da89 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Thu, 28 Nov 2013 08:51:21 +0100 Subject: [PATCH 38/67] enum type naming fixed continued. --- Code/Network/NetworkDependencies/Protocols.h | 8 ++++---- Code/Network/NetworkDependencies/Translator.cpp | 8 ++++---- Code/Network/OysterNetworkClient/ClientMain.cpp | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h index 65beb400..f90d99c6 100644 --- a/Code/Network/NetworkDependencies/Protocols.h +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -27,7 +27,7 @@ namespace Oyster int packageType; int clientID; - ProtocolHeader() { this->packageType = package_type_header; } + ProtocolHeader() { this->packageType = PackageType_header; } virtual ~ProtocolHeader() { } }; @@ -37,7 +37,7 @@ namespace Oyster unsigned int numOfFloats; float *f; - ProtocolTest() { this->packageType = package_type_test; } + ProtocolTest() { this->packageType = PackageType_test; } virtual ~ProtocolTest() { delete[] f; } }; @@ -56,13 +56,13 @@ namespace Oyster { switch(type) { - case package_type_header: + case PackageType_header: if(Protocol.pHeader) { delete Protocol.pHeader; } break; - case package_type_test: + case PackageType_test: if(Protocol.pTest) { delete Protocol.pTest; diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp index fbd32df0..b0b6d587 100644 --- a/Code/Network/NetworkDependencies/Translator.cpp +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -10,11 +10,11 @@ void Translator::Pack( ProtocolHeader &header, OysterByte& bytes ) switch(header.packageType) { - case package_type_header: + case PackageType_header: message = new MessageHeader(); break; - case package_type_test: + case PackageType_test: message = new MessageTest(); break; } @@ -41,13 +41,13 @@ ProtocolSet* Translator::Unpack(ProtocolSet* set, OysterByte& bytes ) set->type = (PackageType)header->packageType; switch(set->type) { - case package_type_header: + case PackageType_header: message = new MessageHeader(); set->Protocol.pHeader = new ProtocolHeader; message->Unpack(bytes, *set->Protocol.pHeader); break; - case package_type_test: + case PackageType_test: message = new MessageTest(); set->Protocol.pTest = new ProtocolTest; message->Unpack(bytes, *set->Protocol.pTest); diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 244ce1d4..ce66446f 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -73,9 +73,9 @@ void chat(Client &client) switch(set->type) { - case package_type_header: + case PackageType_header: break; - case package_type_test: + case PackageType_test: cout <<"Client 2: " << set->Protocol.pTest->textMessage <Protocol.pTest->numOfFloats; i++) { From 00e02b690956bb16606098d90858f3903523f30e Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Thu, 28 Nov 2013 08:52:11 +0100 Subject: [PATCH 39/67] Removed OysterMath from OysterNetworkClient --- Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj | 3 --- 1 file changed, 3 deletions(-) diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj index 4fdfc0d4..f4e13099 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj @@ -149,9 +149,6 @@ {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} - - {f10cbc03-9809-4cba-95d8-327c287b18ee} - {c5aa09d0-6594-4cd3-bd92-1d380c7b3b50} From 3a444aaae847b0f4ed6e7d30151cad0a22ff106e Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 10:24:32 +0100 Subject: [PATCH 40/67] Moved Octree.h into the Implementation Filter --- Code/GamePhysics/GamePhysics.vcxproj.filters | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/GamePhysics/GamePhysics.vcxproj.filters b/Code/GamePhysics/GamePhysics.vcxproj.filters index 4c0fd5f3..cc9a84c8 100644 --- a/Code/GamePhysics/GamePhysics.vcxproj.filters +++ b/Code/GamePhysics/GamePhysics.vcxproj.filters @@ -33,6 +33,9 @@ Header Files\Implementation + + Header Files\Implementation + From 07e3aa169741a3e50ad79bfa7df2b95e8fe8a090 Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 10:26:29 +0100 Subject: [PATCH 41/67] Improved Collision Event Subscription From now on, will each ICustomBody instance have it's own collisionAction function. --- .../Implementation/PhysicsAPI_Impl.cpp | 43 +++++++++++-------- .../Implementation/PhysicsAPI_Impl.h | 11 +++-- .../Implementation/SimpleRigidBody.cpp | 26 +++++------ .../Implementation/SimpleRigidBody.h | 6 +-- .../Implementation/SphericalRigidBody.cpp | 26 +++++------ .../Implementation/SphericalRigidBody.h | 5 ++- Code/GamePhysics/PhysicsAPI.h | 39 ++++++++--------- 7 files changed, 86 insertions(+), 70 deletions(-) diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp index 6c3e4a27..13184ce5 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp @@ -10,14 +10,6 @@ using namespace ::Utility::DynamicMemory; API_Impl API_instance; -// default API::EventAction_Collision -void defaultCollisionAction( const ICustomBody *proto, const ICustomBody *deuter ) -{ /* do nothing */ } - -// default API::EventAction_Destruction -void defaultDestructionAction( UniquePointer proto ) -{ /* do nothing besides proto auto deleting itself. */ } - Float4x4 & MomentOfInertia::CreateSphereMatrix( const Float mass, const Float radius) { return Formula::MomentOfInertia::Sphere(mass, radius); @@ -51,8 +43,7 @@ API & API::Instance() API_Impl::API_Impl() : gravityConstant( Constant::gravity_constant ), updateFrameLength( 1.0f / 120.0f ), - collisionAction( defaultCollisionAction ), - destructionAction( defaultDestructionAction ) + destructionAction( Default::EventAction_Destruction ) {} API_Impl::~API_Impl() {} @@ -66,17 +57,22 @@ void API_Impl::SetDeltaTime( float deltaTime ) { updateFrameLength = deltaTime; } + void API_Impl::SetGravityConstant( float g ) { this->gravityConstant = g; } -void API_Impl::SetAction( API::EventAction_Collision functionPointer ) + +void API_Impl::SetSubscription( API::EventAction_Destruction functionPointer ) { - this->collisionAction = functionPointer; -} -void API_Impl::SetAction( API::EventAction_Destruction functionPointer ) -{ - this->destructionAction = functionPointer; + if( functionPointer ) + { + this->destructionAction = functionPointer; + } + else + { + this->destructionAction = Default::EventAction_Destruction; + } } void API_Impl::Update() @@ -168,4 +164,17 @@ void API_Impl::SetSize( const ICustomBody* objRef, const Float3 &size ) UniquePointer API_Impl::CreateSimpleRigidBody() const { return new SimpleRigidBody(); -} \ No newline at end of file +} + +namespace Oyster { namespace Physics { namespace Default +{ + + void EventAction_Destruction( ::Utility::DynamicMemory::UniquePointer<::Oyster::Physics::ICustomBody> proto ) + { /* Do nothing except allowing the proto uniquePointer destroy itself. */ } + + ::Oyster::Physics::ICustomBody::SubscriptMessage EventAction_Collision( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter ) + { /* Do nothing except returning business as usual. */ + return ::Oyster::Physics::ICustomBody::SubscriptMessage_none; + } + +} } } \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h index 5a2e3ef6..28858da0 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h @@ -17,8 +17,7 @@ namespace Oyster void SetDeltaTime( float deltaTime ); void SetGravityConstant( float g ); - void SetAction( EventAction_Collision functionPointer ); - void SetAction( EventAction_Destruction functionPointer ); + void SetSubscription( EventAction_Destruction functionPointer ); void Update(); @@ -45,11 +44,15 @@ namespace Oyster ::Utility::DynamicMemory::UniquePointer CreateSimpleRigidBody() const; private: ::Oyster::Math::Float gravityConstant, updateFrameLength; - EventAction_Collision collisionAction; EventAction_Destruction destructionAction; }; - } + namespace Default + { + void EventAction_Destruction( ::Utility::DynamicMemory::UniquePointer<::Oyster::Physics::ICustomBody> proto ); + ::Oyster::Physics::ICustomBody::SubscriptMessage EventAction_Collision( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter ); + } + } } #endif \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp index cc1f847b..95256915 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp @@ -10,7 +10,7 @@ using namespace ::Utility::Value; SimpleRigidBody::SimpleRigidBody() : previous(), current(), gravityNormal(0.0f), - subscribeCollision(true), + collisionAction(Default::EventAction_Collision), ignoreGravity(false) {} SimpleRigidBody::~SimpleRigidBody() {} @@ -20,11 +20,6 @@ UniquePointer SimpleRigidBody::Clone() const return new SimpleRigidBody( *this ); } -bool SimpleRigidBody::IsSubscribingCollisions() const -{ // Assumption - return this->subscribeCollision; -} - bool SimpleRigidBody::IsAffectedByGravity() const { return !this->ignoreGravity; @@ -92,7 +87,19 @@ UpdateState SimpleRigidBody::Update( Float timeStepLength ) this->current.Update_LeapFrog( timeStepLength ); // compare previous and new state and return result - return this->current == this->previous ? resting : altered; + return this->current == this->previous ? UpdateState_resting : UpdateState_altered; +} + +void SimpleRigidBody::SetSubscription( ICustomBody::EventAction_Collision functionPointer ) +{ + if( functionPointer ) + { + this->collisionAction = functionPointer; + } + else + { + this->collisionAction = Default::EventAction_Collision; + } } void SimpleRigidBody::SetGravity( bool ignore) @@ -106,11 +113,6 @@ void SimpleRigidBody::SetGravityNormal( const Float3 &normalizedVector ) this->gravityNormal = normalizedVector; } -void SimpleRigidBody::SetSubscription( bool subscribeCollision ) -{ - this->subscribeCollision = subscribeCollision; -} - void SimpleRigidBody::SetMomentOfInertiaTensor_KeepVelocity( const Float4x4 &localI ) { this->current.SetMomentOfInertia_KeepVelocity( localI ); diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.h b/Code/GamePhysics/Implementation/SimpleRigidBody.h index 41be919b..c19a1ddb 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.h +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.h @@ -14,7 +14,6 @@ namespace Oyster { namespace Physics ::Utility::DynamicMemory::UniquePointer Clone() const; - bool IsSubscribingCollisions() const; bool IsAffectedByGravity() const; bool Intersects( const ICustomBody &object, ::Oyster::Math::Float timeStepLength, ::Oyster::Math::Float &deltaWhen, ::Oyster::Math::Float3 &worldPointOfContact ) const; bool Intersects( const ::Oyster::Collision3D::ICollideable &shape ) const; @@ -29,9 +28,9 @@ namespace Oyster { namespace Physics UpdateState Update( ::Oyster::Math::Float timeStepLength ); + void SetSubscription( EventAction_Collision functionPointer ); void SetGravity( bool ignore); void SetGravityNormal( const ::Oyster::Math::Float3 &normalizedVector ); - void SetSubscription( bool subscribeCollision ); void SetMomentOfInertiaTensor_KeepVelocity( const ::Oyster::Math::Float4x4 &localI ); void SetMomentOfInertiaTensor_KeepMomentum( const ::Oyster::Math::Float4x4 &localI ); void SetMass_KeepVelocity( ::Oyster::Math::Float m ); @@ -44,7 +43,8 @@ namespace Oyster { namespace Physics private: ::Oyster::Physics3D::RigidBody previous, current; ::Oyster::Math::Float3 gravityNormal; - bool subscribeCollision, ignoreGravity; + EventAction_Collision collisionAction; + bool ignoreGravity; }; } } diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp index 20d806c9..6d50b386 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp @@ -10,7 +10,7 @@ using namespace ::Utility::Value; SphericalRigidBody::SphericalRigidBody() : previous(), current( Box(Float4x4::identity, Float3::null, Float3(1.0f)) ), gravityNormal( 0.0f ), - subscribeCollision( true ), + collisionAction(Default::EventAction_Collision), ignoreGravity( false ), body( Float3::null, 0.5f ) {} @@ -21,11 +21,6 @@ UniquePointer SphericalRigidBody::Clone() const return new SphericalRigidBody( *this ); } -bool SphericalRigidBody::IsSubscribingCollisions() const -{ // Assumption - return this->subscribeCollision; -} - bool SphericalRigidBody::IsAffectedByGravity() const { return !this->ignoreGravity; @@ -94,7 +89,19 @@ UpdateState SphericalRigidBody::Update( Float timeStepLength ) this->body.center = this->current.GetCenter(); // compare previous and new state and return result - return this->current == this->previous ? resting : altered; + return this->current == this->previous ? UpdateState_resting : UpdateState_altered; +} + +void SphericalRigidBody::SetSubscription( ICustomBody::EventAction_Collision functionPointer ) +{ + if( functionPointer ) + { + this->collisionAction = functionPointer; + } + else + { + this->collisionAction = Default::EventAction_Collision; + } } void SphericalRigidBody::SetGravity( bool ignore) @@ -108,11 +115,6 @@ void SphericalRigidBody::SetGravityNormal( const Float3 &normalizedVector ) this->gravityNormal = normalizedVector; } -void SphericalRigidBody::SetSubscription( bool subscribeCollision ) -{ - this->subscribeCollision = subscribeCollision; -} - void SphericalRigidBody::SetMomentOfInertiaTensor_KeepVelocity( const Float4x4 &localI ) { this->current.SetMomentOfInertia_KeepVelocity( localI ); diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.h b/Code/GamePhysics/Implementation/SphericalRigidBody.h index 7a727ee8..1540f7a1 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.h +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.h @@ -30,9 +30,9 @@ namespace Oyster { namespace Physics UpdateState Update( ::Oyster::Math::Float timeStepLength ); + void SetSubscription( EventAction_Collision functionPointer ); void SetGravity( bool ignore); void SetGravityNormal( const ::Oyster::Math::Float3 &normalizedVector ); - void SetSubscription( bool subscribeCollision ); void SetMomentOfInertiaTensor_KeepVelocity( const ::Oyster::Math::Float4x4 &localI ); void SetMomentOfInertiaTensor_KeepMomentum( const ::Oyster::Math::Float4x4 &localI ); void SetMass_KeepVelocity( ::Oyster::Math::Float m ); @@ -45,7 +45,8 @@ namespace Oyster { namespace Physics private: ::Oyster::Physics3D::RigidBody previous, current; ::Oyster::Math::Float3 gravityNormal; - bool subscribeCollision, ignoreGravity; + EventAction_Collision collisionAction; + bool ignoreGravity; ::Oyster::Collision3D::Sphere body; }; } } diff --git a/Code/GamePhysics/PhysicsAPI.h b/Code/GamePhysics/PhysicsAPI.h index bf80e6fa..71bebc1f 100644 --- a/Code/GamePhysics/PhysicsAPI.h +++ b/Code/GamePhysics/PhysicsAPI.h @@ -19,8 +19,8 @@ namespace Oyster enum UpdateState { - resting, - altered + UpdateState_resting, + UpdateState_altered }; namespace Constant @@ -45,7 +45,6 @@ namespace Oyster class PHYSICS_DLL_USAGE API { public: - typedef void (*EventAction_Collision)( const ICustomBody *proto, const ICustomBody *deuter ); typedef void (*EventAction_Destruction)( ::Utility::DynamicMemory::UniquePointer proto ); /** Gets the Physics instance. */ @@ -70,20 +69,15 @@ namespace Oyster * @param g: Default is the real world Constant::gravity_constant [N(m/kg)^2] ********************************************************/ virtual void SetGravityConstant( float g ) = 0; - - /******************************************************** - * Sets the function that will be called by the engine - * whenever a subscribed collision occurs. - ********************************************************/ - virtual void SetAction( EventAction_Collision functionPointer ) = 0; /******************************************************** * Sets the function that will be called by the engine * whenever an object is being destroyed for some reason. * - Because DestroyObject(...) were called. * - Out of memory forced engine to destroy an object. + * @param functionPointer: If NULL, an empty default function will be set. ********************************************************/ - virtual void SetAction( EventAction_Destruction functionPointer ) = 0; + virtual void SetSubscription( EventAction_Destruction functionPointer ) = 0; /******************************************************** * Triggers the engine to run next update frame. @@ -225,6 +219,14 @@ namespace Oyster class PHYSICS_DLL_USAGE ICustomBody { public: + enum SubscriptMessage + { + SubscriptMessage_none, + SubscriptMessage_ignore_collision_response + }; + + typedef SubscriptMessage (*EventAction_Collision)( const ICustomBody *proto, const ICustomBody *deuter ); + virtual ~ICustomBody() {}; /******************************************************** @@ -232,11 +234,6 @@ namespace Oyster * @return An ICustomBody pointer along with the responsibility to delete. ********************************************************/ virtual ::Utility::DynamicMemory::UniquePointer Clone() const = 0; - - /******************************************************** - * @return true if Engine should call the EventAction_Collision function. - ********************************************************/ - virtual bool IsSubscribingCollisions() const = 0; /******************************************************** * @return true if Engine should apply gravity on this object. @@ -312,6 +309,13 @@ namespace Oyster ********************************************************/ virtual UpdateState Update( ::Oyster::Math::Float timeStepLength ) = 0; + /******************************************************** + * Sets the function that will be called by the engine + * whenever a collision occurs. + * @param functionPointer: If NULL, an empty default function will be set. + ********************************************************/ + virtual void SetSubscription( EventAction_Collision functionPointer ) = 0; + /******************************************************** * @param ignore: True if Engine should not apply Gravity. ********************************************************/ @@ -323,11 +327,6 @@ namespace Oyster ********************************************************/ virtual void SetGravityNormal( const ::Oyster::Math::Float3 &normalizedVector ) = 0; - /******************************************************** - * @param subscribeCollision: If is true, engine will call EventAction_Collision when this collides. - ********************************************************/ - virtual void SetSubscription( bool subscribeCollision ) = 0; - /******************************************************** * To not be called if is in Engine * Use API::SetMomentOfInertiaTensor_KeepVelocity(...) instead From ecbb606544f735a95daf37e88b7915baf7906dcf Mon Sep 17 00:00:00 2001 From: Robin Engman Date: Thu, 28 Nov 2013 11:14:24 +0100 Subject: [PATCH 42/67] Added basic functionality for container. --- Code/GamePhysics/GamePhysics.vcxproj | 1 + Code/GamePhysics/GamePhysics.vcxproj.filters | 6 ++ Code/GamePhysics/Implementation/Octree.cpp | 76 ++++++++++++++++++++ Code/GamePhysics/Implementation/Octree.h | 10 +-- 4 files changed, 89 insertions(+), 4 deletions(-) create mode 100644 Code/GamePhysics/Implementation/Octree.cpp diff --git a/Code/GamePhysics/GamePhysics.vcxproj b/Code/GamePhysics/GamePhysics.vcxproj index ddc37cf4..562fecb4 100644 --- a/Code/GamePhysics/GamePhysics.vcxproj +++ b/Code/GamePhysics/GamePhysics.vcxproj @@ -155,6 +155,7 @@ + diff --git a/Code/GamePhysics/GamePhysics.vcxproj.filters b/Code/GamePhysics/GamePhysics.vcxproj.filters index 256cd6b1..b971ed32 100644 --- a/Code/GamePhysics/GamePhysics.vcxproj.filters +++ b/Code/GamePhysics/GamePhysics.vcxproj.filters @@ -30,6 +30,9 @@ Header Files\Implementation + + Header Files\Implementation + @@ -41,5 +44,8 @@ Source Files + + Header Files\Implementation + \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/Octree.cpp b/Code/GamePhysics/Implementation/Octree.cpp new file mode 100644 index 00000000..64617426 --- /dev/null +++ b/Code/GamePhysics/Implementation/Octree.cpp @@ -0,0 +1,76 @@ +#include "Octree.h" + +using namespace Oyster; +using namespace Physics; + +Octree::Octree(unsigned int bufferSize, unsigned char numLayers, Math::Float3 worldSize) +{ + this->worldNode.dataPtr = NULL; + + this->worldNode.container.maxVertex = worldSize*0.5f; + this->worldNode.container.minVertex = -worldSize*0.5f; +} + +Octree::~Octree() +{ + +} + +void Octree::AddObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +{ + Data data; + //Data* tempPtr = this->worldNode.dataPtr; + + data.container = customBodyRef->GetBoundingSphere(); + data.queueRef = -1; + data.next = NULL; + data.prev = NULL; + data.customBodyRef = customBodyRef; + this->mapReferences.insert(std::pair (customBodyRef, this->leafData.size())); + this->leafData.push_back(data); + + /*if(tempPtr != NULL) + { + tempPtr->prev->next = &this->leafData[this->leafData.size() - 1]; + this->leafData[this->leafData.size() - 1].prev = tempPtr->prev; + tempPtr->prev = &this->leafData[this->leafData.size() - 1]; + this->leafData[this->leafData.size() - 1].next = tempPtr; + } + else + { + this->worldNode.dataPtr = &this->leafData[this->leafData.size() - 1]; + this->worldNode.dataPtr->next = this->worldNode.dataPtr; + this->worldNode.dataPtr->prev = this->worldNode.dataPtr; + }*/ +} + +void Octree::MoveToUpdateQueue(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +{ + /*this->leafData[this->mapReferences[customBodyRef]].queueRef = this->updateQueue.size(); + this->updateQueue.push_back(&this->leafData[this->mapReferences[customBodyRef]]);*/ +} + + +void Octree::DestroyObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +{ + std::map::iterator it = this->mapReferences.find(customBodyRef); + + this->mapReferences.erase(it); + + this->leafData.erase(this->leafData.begin() + this->leafData[this->mapReferences[customBodyRef]].queueRef); +} + +std::vector Octree::Sample(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +{ + std::vector list; + + for(unsigned int i = 0; ileafData.size(); i++) + { + if(this->leafData[i].customBodyRef != customBodyRef) if(this->leafData[i].container.Intersects(customBodyRef->GetBoundingSphere())) + { + list.push_back(this->leafData[i].customBodyRef); + } + } + + return list; +} diff --git a/Code/GamePhysics/Implementation/Octree.h b/Code/GamePhysics/Implementation/Octree.h index 22385dc6..6034d129 100644 --- a/Code/GamePhysics/Implementation/Octree.h +++ b/Code/GamePhysics/Implementation/Octree.h @@ -29,7 +29,9 @@ namespace Oyster struct OctreeNode { - + OctreeNode* children[8]; + Data* dataPtr; + Collision3D::BoxAxisAligned container; }; Octree(unsigned int bufferSize, unsigned char numLayers, Math::Float3 worldSize); @@ -39,16 +41,16 @@ namespace Oyster void MoveToUpdateQueue(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); - void Update(); - void DestroyObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); - void Sample(Collision3D::ICollideable& collideable); + std::vector Sample(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); private: std::vector < Data > leafData; + std::vector < Data* > updateQueue; std::map< ICustomBody*, unsigned int > mapReferences; + OctreeNode worldNode; }; } From 23d3af21c66852c1262031cad16aedab3e73a5ab Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 11:15:25 +0100 Subject: [PATCH 43/67] Added comparison operators to UniquePointer and UniqueArray operator == operator != --- Code/Misc/Utilities-InlineImpl.h | 24 ++++++++++++++++++++++++ Code/Misc/Utilities.h | 12 ++++++++++++ 2 files changed, 36 insertions(+) diff --git a/Code/Misc/Utilities-InlineImpl.h b/Code/Misc/Utilities-InlineImpl.h index dc047153..cd8946d3 100644 --- a/Code/Misc/Utilities-InlineImpl.h +++ b/Code/Misc/Utilities-InlineImpl.h @@ -90,6 +90,18 @@ namespace Utility return this->ownedInstance != NULL; } + template + bool UniquePointer::operator == ( Type *stray ) const + { + return this->ownedInstance == stray; + } + + template + bool UniquePointer::operator != ( Type *stray ) const + { + return this->ownedInstance != stray; + } + template Type* UniquePointer::Release() { @@ -149,6 +161,18 @@ namespace Utility return this->ownedArray != NULL; } + template + bool UniqueArray::operator == ( Type *stray ) const + { + return this->ownedArray == stray; + } + + template + bool UniqueArray::operator != ( Type *stray ) const + { + return this->ownedArray != stray; + } + template Type* UniqueArray::Release() { diff --git a/Code/Misc/Utilities.h b/Code/Misc/Utilities.h index a07143cf..d6127d73 100644 --- a/Code/Misc/Utilities.h +++ b/Code/Misc/Utilities.h @@ -56,6 +56,12 @@ namespace Utility //! If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. operator bool () const; + //! @return true if this ownedInstance matches with stray + bool operator == ( Type *stray ) const; + + //! @return false if this ownedInstance matches with stray + bool operator != ( Type *stray ) const; + //! This UniquePointer drops all claims of ownership/responsibility and returns the dynamic instance. Now it is your responsibility to delete. Type* Release(); @@ -96,6 +102,12 @@ namespace Utility //! If true, this UniqueArray have a current ownership/responsibility of a dynamic instance. operator bool () const; + //! @return true if this ownedInstance matches with stray + bool operator == ( Type *stray ) const; + + //! @return false if this ownedInstance matches with stray + bool operator != ( Type *stray ) const; + //! This UniqueArray drops all claims of ownership/responsibility and returns the dynamic array. Now it is your responsibility to delete. Type* Release(); From 3a6cb98b08912656792e52dbcd877493a7020ad1 Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 11:58:46 +0100 Subject: [PATCH 44/67] SimpleRigidBody factory done not tested though --- .../Implementation/PhysicsAPI_Impl.cpp | 12 +++- .../Implementation/PhysicsAPI_Impl.h | 4 +- .../Implementation/SimpleRigidBody.cpp | 71 ++++++++++++------- .../Implementation/SimpleRigidBody.h | 3 +- .../Implementation/SphericalRigidBody.cpp | 1 + Code/GamePhysics/PhysicsAPI.h | 59 ++++++++++++++- Code/OysterPhysics3D/RigidBody.cpp | 18 ++++- Code/OysterPhysics3D/RigidBody.h | 4 +- 8 files changed, 136 insertions(+), 36 deletions(-) diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp index 13184ce5..2c745500 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp @@ -1,6 +1,7 @@ #include "PhysicsAPI_Impl.h" -#include "SimpleRigidBody.h" #include "OysterPhysics3D.h" +#include "SimpleRigidBody.h" +#include "SphericalRigidBody.h" using namespace ::Oyster::Physics; using namespace ::Oyster::Physics3D; @@ -161,9 +162,14 @@ void API_Impl::SetSize( const ICustomBody* objRef, const Float3 &size ) //! @todo TODO: implement stub } -UniquePointer API_Impl::CreateSimpleRigidBody() const +UniquePointer API_Impl::CreateRigidBody( const API::SimpleBodyDescription &desc ) const { - return new SimpleRigidBody(); + return new SimpleRigidBody( desc ); +} + +UniquePointer API_Impl::CreateRigidBody( const API::SphericalBodyDescription &desc ) const +{ + return new SphericalRigidBody(); } namespace Oyster { namespace Physics { namespace Default diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h index 28858da0..7d6858f0 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h @@ -41,7 +41,9 @@ namespace Oyster void SetOrientation( const ICustomBody* objRef, const ::Oyster::Math::Float4x4 &orientation ); void SetSize( const ICustomBody* objRef, const ::Oyster::Math::Float3 &size ); - ::Utility::DynamicMemory::UniquePointer CreateSimpleRigidBody() const; + ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SimpleBodyDescription &desc ) const; + ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SphericalBodyDescription &desc ) const; + private: ::Oyster::Math::Float gravityConstant, updateFrameLength; EventAction_Destruction destructionAction; diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp index 95256915..d83aa399 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp @@ -2,16 +2,38 @@ #include "PhysicsAPI_Impl.h" using namespace ::Oyster::Physics; +using namespace ::Oyster::Physics3D; using namespace ::Oyster::Math3D; using namespace ::Oyster::Collision3D; using namespace ::Utility::DynamicMemory; using namespace ::Utility::Value; SimpleRigidBody::SimpleRigidBody() - : previous(), current(), - gravityNormal(0.0f), - collisionAction(Default::EventAction_Collision), - ignoreGravity(false) {} +{ + this->rigid = RigidBody(); + this->gravityNormal = Float3::null; + this->collisionAction = Default::EventAction_Collision; + this->ignoreGravity = false; +} + +SimpleRigidBody::SimpleRigidBody( const API::SimpleBodyDescription &desc ) +{ + this->rigid = RigidBody( Box( desc.rotation, desc.centerPosition, desc.size ), + desc.mass, + desc.inertiaTensor ); + this->gravityNormal = Float3::null; + + if( desc.subscription ) + { + this->collisionAction = desc.subscription; + } + else + { + this->collisionAction = Default::EventAction_Collision; + } + + this->ignoreGravity = desc.ignoreGravity; +} SimpleRigidBody::~SimpleRigidBody() {} @@ -27,10 +49,10 @@ bool SimpleRigidBody::IsAffectedByGravity() const bool SimpleRigidBody::Intersects( const ICustomBody &object, Float timeStepLength, Float &deltaWhen, Float3 &worldPointOfContact ) const { - if( object.Intersects(this->current.box) ) + if( object.Intersects(this->rigid.box) ) { //! @todo TODO: better implementation needed deltaWhen = timeStepLength; - worldPointOfContact = Average( this->current.box.center, object.GetCenter() ); + worldPointOfContact = Average( this->rigid.box.center, object.GetCenter() ); return true; } else @@ -41,18 +63,18 @@ bool SimpleRigidBody::Intersects( const ICustomBody &object, Float timeStepLengt bool SimpleRigidBody::Intersects( const ICollideable &shape ) const { - return this->current.box.Intersects( shape ); + return this->rigid.box.Intersects( shape ); } Sphere & SimpleRigidBody::GetBoundingSphere( Sphere &targetMem ) const { - return targetMem = Sphere( this->current.box.center, this->current.box.boundingOffset.GetMagnitude() ); + return targetMem = Sphere( this->rigid.box.center, this->rigid.box.boundingOffset.GetMagnitude() ); } Float3 & SimpleRigidBody::GetNormalAt( const Float3 &worldPos, Float3 &targetMem ) const { //! @todo TODO: better implementation needed - return targetMem = (worldPos - this->current.box.center).GetNormalized(); + return targetMem = (worldPos - this->rigid.box.center).GetNormalized(); } Float3 & SimpleRigidBody::GetGravityNormal( Float3 &targetMem ) const @@ -62,32 +84,31 @@ Float3 & SimpleRigidBody::GetGravityNormal( Float3 &targetMem ) const Float3 & SimpleRigidBody::GetCenter( Float3 &targetMem ) const { - return targetMem = this->current.box.center; + return targetMem = this->rigid.box.center; } Float4x4 & SimpleRigidBody::GetRotation( Float4x4 &targetMem ) const { - return targetMem = this->current.box.rotation; + return targetMem = this->rigid.box.rotation; } Float4x4 & SimpleRigidBody::GetOrientation( Float4x4 &targetMem ) const { - return targetMem = this->current.GetOrientation(); + return targetMem = this->rigid.GetOrientation(); } Float4x4 & SimpleRigidBody::GetView( Float4x4 &targetMem ) const { - return targetMem = this->current.GetView(); + return targetMem = this->rigid.GetView(); } UpdateState SimpleRigidBody::Update( Float timeStepLength ) { - this->previous = this->current; // memorizing the old state - - this->current.Update_LeapFrog( timeStepLength ); + this->rigid.Update_LeapFrog( timeStepLength ); // compare previous and new state and return result - return this->current == this->previous ? UpdateState_resting : UpdateState_altered; + //return this->current == this->previous ? UpdateState_resting : UpdateState_altered; + return UpdateState_altered; } void SimpleRigidBody::SetSubscription( ICustomBody::EventAction_Collision functionPointer ) @@ -115,40 +136,40 @@ void SimpleRigidBody::SetGravityNormal( const Float3 &normalizedVector ) void SimpleRigidBody::SetMomentOfInertiaTensor_KeepVelocity( const Float4x4 &localI ) { - this->current.SetMomentOfInertia_KeepVelocity( localI ); + this->rigid.SetMomentOfInertia_KeepVelocity( localI ); } void SimpleRigidBody::SetMomentOfInertiaTensor_KeepMomentum( const Float4x4 &localI ) { - this->current.SetMomentOfInertia_KeepMomentum( localI ); + this->rigid.SetMomentOfInertia_KeepMomentum( localI ); } void SimpleRigidBody::SetMass_KeepVelocity( Float m ) { - this->current.SetMass_KeepVelocity( m ); + this->rigid.SetMass_KeepVelocity( m ); } void SimpleRigidBody::SetMass_KeepMomentum( Float m ) { - this->current.SetMass_KeepMomentum( m ); + this->rigid.SetMass_KeepMomentum( m ); } void SimpleRigidBody::SetCenter( const Float3 &worldPos ) { - this->current.SetCenter( worldPos ); + this->rigid.SetCenter( worldPos ); } void SimpleRigidBody::SetRotation( const Float4x4 &rotation ) { - this->current.SetRotation( rotation ); + this->rigid.SetRotation( rotation ); } void SimpleRigidBody::SetOrientation( const Float4x4 &orientation ) { - this->current.SetOrientation( orientation ); + this->rigid.SetOrientation( orientation ); } void SimpleRigidBody::SetSize( const Float3 &size ) { - this->current.SetSize( size ); + this->rigid.SetSize( size ); } \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.h b/Code/GamePhysics/Implementation/SimpleRigidBody.h index c19a1ddb..c76f6a51 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.h +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.h @@ -10,6 +10,7 @@ namespace Oyster { namespace Physics { public: SimpleRigidBody(); + SimpleRigidBody( const API::SimpleBodyDescription &desc ); virtual ~SimpleRigidBody(); ::Utility::DynamicMemory::UniquePointer Clone() const; @@ -41,7 +42,7 @@ namespace Oyster { namespace Physics void SetSize( const ::Oyster::Math::Float3 &size ); private: - ::Oyster::Physics3D::RigidBody previous, current; + ::Oyster::Physics3D::RigidBody rigid; ::Oyster::Math::Float3 gravityNormal; EventAction_Collision collisionAction; bool ignoreGravity; diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp index 6d50b386..1c9b7b52 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp @@ -2,6 +2,7 @@ #include "PhysicsAPI_Impl.h" using namespace ::Oyster::Physics; +using namespace ::Oyster::Physics3D; using namespace ::Oyster::Math3D; using namespace ::Oyster::Collision3D; using namespace ::Utility::DynamicMemory; diff --git a/Code/GamePhysics/PhysicsAPI.h b/Code/GamePhysics/PhysicsAPI.h index 71bebc1f..dd36a9ee 100644 --- a/Code/GamePhysics/PhysicsAPI.h +++ b/Code/GamePhysics/PhysicsAPI.h @@ -45,6 +45,9 @@ namespace Oyster class PHYSICS_DLL_USAGE API { public: + struct SimpleBodyDescription; + struct SphericalBodyDescription; + typedef void (*EventAction_Destruction)( ::Utility::DynamicMemory::UniquePointer proto ); /** Gets the Physics instance. */ @@ -207,10 +210,18 @@ namespace Oyster /******************************************************** * Creates a new dynamically allocated object that can be used as a component for more complex ICustomBodies. + * @param desc: @see API::SimpleBodyDescription * @return A pointer along with the responsibility to delete. ********************************************************/ - virtual ::Utility::DynamicMemory::UniquePointer CreateSimpleRigidBody() const = 0; - + virtual ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SimpleBodyDescription &desc ) const = 0; + + /******************************************************** + * Creates a new dynamically allocated object that can be used as a component for more complex ICustomBodies. + * @param desc: @see API::SphericalBodyDescription + * @return A pointer along with the responsibility to delete. + ********************************************************/ + virtual ::Utility::DynamicMemory::UniquePointer CreateRigidBody( const SphericalBodyDescription &desc ) const = 0; + protected: virtual ~API() {} }; @@ -375,6 +386,50 @@ namespace Oyster ********************************************************/ virtual void SetSize( const ::Oyster::Math::Float3 &size ) = 0; }; + + struct API::SimpleBodyDescription + { + ::Oyster::Math::Float4x4 rotation; + ::Oyster::Math::Float3 centerPosition; + ::Oyster::Math::Float3 size; + ::Oyster::Math::Float mass; + ::Oyster::Math::Float4x4 inertiaTensor; + ICustomBody::EventAction_Collision subscription; + bool ignoreGravity; + + SimpleBodyDescription() + { + this->rotation = ::Oyster::Math::Float4x4::identity; + this->centerPosition = ::Oyster::Math::Float3::null; + this->size = ::Oyster::Math::Float3( 1.0f ); + this->mass = 12.0f; + this->inertiaTensor = ::Oyster::Math::Float4x4::identity; + this->subscription = NULL; + this->ignoreGravity = false; + } + }; + + struct API::SphericalBodyDescription + { + ::Oyster::Math::Float4x4 rotation; + ::Oyster::Math::Float3 centerPosition; + ::Oyster::Math::Float radius; + ::Oyster::Math::Float mass; + ::Oyster::Math::Float4x4 inertiaTensor; + ICustomBody::EventAction_Collision subscription; + bool ignoreGravity; + + SphericalBodyDescription() + { + this->rotation = ::Oyster::Math::Float4x4::identity; + this->centerPosition = ::Oyster::Math::Float3::null; + this->radius = 0.5f; + this->mass = 10.0f; + this->inertiaTensor = ::Oyster::Math::Float4x4::identity; + this->subscription = NULL; + this->ignoreGravity = false; + } + }; } } #endif \ No newline at end of file diff --git a/Code/OysterPhysics3D/RigidBody.cpp b/Code/OysterPhysics3D/RigidBody.cpp index 24648999..182a5a17 100644 --- a/Code/OysterPhysics3D/RigidBody.cpp +++ b/Code/OysterPhysics3D/RigidBody.cpp @@ -9,9 +9,14 @@ using namespace ::Oyster::Collision3D; using namespace ::Oyster::Physics3D; using namespace ::Oyster::Math3D; -RigidBody::RigidBody( const Box &b, Float m ) - : box(b), angularMomentum(0.0f), linearMomentum(0.0f), impulseTorqueSum(0.0f), impulseForceSum(0.0f) +RigidBody::RigidBody( const Box &b, Float m, const Float4x4 &inertiaTensor ) { // by Dan Andersson + this->box = b; + this->angularMomentum = Float3::null; + this->linearMomentum = Float3::null; + this->impulseTorqueSum = Float3::null; + this->impulseForceSum = Float3::null; + if( m != 0.0f ) { this->mass = m; @@ -21,7 +26,14 @@ RigidBody::RigidBody( const Box &b, Float m ) this->mass = ::Utility::Value::numeric_limits::epsilon(); } - this->momentOfInertiaTensor = Float4x4::identity; + if( inertiaTensor.GetDeterminant() != 0.0f ) + { + this->momentOfInertiaTensor = inertiaTensor; + } + else + { + this->momentOfInertiaTensor = Float4x4::identity; + } } RigidBody & RigidBody::operator = ( const RigidBody &body ) diff --git a/Code/OysterPhysics3D/RigidBody.h b/Code/OysterPhysics3D/RigidBody.h index bff6acde..81c92ae0 100644 --- a/Code/OysterPhysics3D/RigidBody.h +++ b/Code/OysterPhysics3D/RigidBody.h @@ -20,7 +20,9 @@ namespace Oyster { namespace Physics3D impulseTorqueSum, /** The impulse torque T (Nm) that will be consumed each update. (worldValue) */ impulseForceSum; /** The impulse force F (N) that will be consumed each update. (worldValue) */ - RigidBody( const ::Oyster::Collision3D::Box &box = ::Oyster::Collision3D::Box(), ::Oyster::Math::Float mass = 1.0f ); + RigidBody( const ::Oyster::Collision3D::Box &box = ::Oyster::Collision3D::Box(), + ::Oyster::Math::Float mass = 12.0f, + const ::Oyster::Math::Float4x4 &inertiaTensor = ::Oyster::Math::Float4x4::identity ); RigidBody & operator = ( const RigidBody &body ); From 2928e08252a8eb11c282bcbaa57ccfbccaf0cb58 Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 12:13:14 +0100 Subject: [PATCH 45/67] SphericalRigidBody factory done not tested though --- .../Implementation/PhysicsAPI_Impl.cpp | 2 +- .../Implementation/SimpleRigidBody.cpp | 2 +- .../Implementation/SphericalRigidBody.cpp | 69 ++++++++++++------- .../Implementation/SphericalRigidBody.h | 3 +- 4 files changed, 49 insertions(+), 27 deletions(-) diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp index 2c745500..6c9b212a 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp @@ -169,7 +169,7 @@ UniquePointer API_Impl::CreateRigidBody( const API::SimpleBodyDescr UniquePointer API_Impl::CreateRigidBody( const API::SphericalBodyDescription &desc ) const { - return new SphericalRigidBody(); + return new SphericalRigidBody( desc ); } namespace Oyster { namespace Physics { namespace Default diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp index d83aa399..40a1b7ee 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp @@ -10,7 +10,7 @@ using namespace ::Utility::Value; SimpleRigidBody::SimpleRigidBody() { - this->rigid = RigidBody(); + this->rigid = RigidBody( Box(Float4x4::identity, Float3::null, Float3(1.0f)), 16.0f, Float4x4::identity ); this->gravityNormal = Float3::null; this->collisionAction = Default::EventAction_Collision; this->ignoreGravity = false; diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp index 1c9b7b52..baf8d98b 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp @@ -9,11 +9,33 @@ using namespace ::Utility::DynamicMemory; using namespace ::Utility::Value; SphericalRigidBody::SphericalRigidBody() - : previous(), current( Box(Float4x4::identity, Float3::null, Float3(1.0f)) ), - gravityNormal( 0.0f ), - collisionAction(Default::EventAction_Collision), - ignoreGravity( false ), - body( Float3::null, 0.5f ) {} +{ + this->rigid = RigidBody( Box(Float4x4::identity, Float3::null, Float3(1.0f)), 10.0f, Float4x4::identity ); + this->gravityNormal = Float3::null; + this->collisionAction = Default::EventAction_Collision; + this->ignoreGravity = false; + this->body = Sphere( Float3::null, 0.5f ); +} + +SphericalRigidBody::SphericalRigidBody( const API::SphericalBodyDescription &desc ) +{ + this->rigid = RigidBody( Box( desc.rotation, desc.centerPosition, Float3(2.0f * desc.radius) ), + desc.mass, + desc.inertiaTensor ); + this->gravityNormal = Float3::null; + + if( desc.subscription ) + { + this->collisionAction = desc.subscription; + } + else + { + this->collisionAction = Default::EventAction_Collision; + } + + this->ignoreGravity = desc.ignoreGravity; + this->body = Sphere( desc.centerPosition, desc.radius ); +} SphericalRigidBody::~SphericalRigidBody() {} @@ -43,7 +65,7 @@ bool SphericalRigidBody::Intersects( const ICustomBody &object, Float timeStepLe bool SphericalRigidBody::Intersects( const ICollideable &shape ) const { - return this->current.box.Intersects( shape ); + return this->rigid.box.Intersects( shape ); } Sphere & SphericalRigidBody::GetBoundingSphere( Sphere &targetMem ) const @@ -54,7 +76,7 @@ Sphere & SphericalRigidBody::GetBoundingSphere( Sphere &targetMem ) const Float3 & SphericalRigidBody::GetNormalAt( const Float3 &worldPos, Float3 &targetMem ) const { //! @todo TODO: better implementation needed - return targetMem = (worldPos - this->current.box.center).GetNormalized(); + return targetMem = (worldPos - this->rigid.box.center).GetNormalized(); } Float3 & SphericalRigidBody::GetGravityNormal( Float3 &targetMem ) const @@ -64,33 +86,32 @@ Float3 & SphericalRigidBody::GetGravityNormal( Float3 &targetMem ) const Float3 & SphericalRigidBody::GetCenter( Float3 &targetMem ) const { - return targetMem = this->current.box.center; + return targetMem = this->rigid.box.center; } Float4x4 & SphericalRigidBody::GetRotation( Float4x4 &targetMem ) const { - return targetMem = this->current.box.rotation; + return targetMem = this->rigid.box.rotation; } Float4x4 & SphericalRigidBody::GetOrientation( Float4x4 &targetMem ) const { - return targetMem = this->current.GetOrientation(); + return targetMem = this->rigid.GetOrientation(); } Float4x4 & SphericalRigidBody::GetView( Float4x4 &targetMem ) const { - return targetMem = this->current.GetView(); + return targetMem = this->rigid.GetView(); } UpdateState SphericalRigidBody::Update( Float timeStepLength ) { - this->previous = this->current; // memorizing the old state - - this->current.Update_LeapFrog( timeStepLength ); - this->body.center = this->current.GetCenter(); + this->rigid.Update_LeapFrog( timeStepLength ); + this->body.center = this->rigid.GetCenter(); // compare previous and new state and return result - return this->current == this->previous ? UpdateState_resting : UpdateState_altered; + //return this->current == this->previous ? UpdateState_resting : UpdateState_altered; + return UpdateState_altered; } void SphericalRigidBody::SetSubscription( ICustomBody::EventAction_Collision functionPointer ) @@ -118,43 +139,43 @@ void SphericalRigidBody::SetGravityNormal( const Float3 &normalizedVector ) void SphericalRigidBody::SetMomentOfInertiaTensor_KeepVelocity( const Float4x4 &localI ) { - this->current.SetMomentOfInertia_KeepVelocity( localI ); + this->rigid.SetMomentOfInertia_KeepVelocity( localI ); } void SphericalRigidBody::SetMomentOfInertiaTensor_KeepMomentum( const Float4x4 &localI ) { - this->current.SetMomentOfInertia_KeepMomentum( localI ); + this->rigid.SetMomentOfInertia_KeepMomentum( localI ); } void SphericalRigidBody::SetMass_KeepVelocity( Float m ) { - this->current.SetMass_KeepVelocity( m ); + this->rigid.SetMass_KeepVelocity( m ); } void SphericalRigidBody::SetMass_KeepMomentum( Float m ) { - this->current.SetMass_KeepMomentum( m ); + this->rigid.SetMass_KeepMomentum( m ); } void SphericalRigidBody::SetCenter( const Float3 &worldPos ) { - this->current.SetCenter( worldPos ); + this->rigid.SetCenter( worldPos ); this->body.center = worldPos; } void SphericalRigidBody::SetRotation( const Float4x4 &rotation ) { - this->current.SetRotation( rotation ); + this->rigid.SetRotation( rotation ); } void SphericalRigidBody::SetOrientation( const Float4x4 &orientation ) { - this->current.SetOrientation( orientation ); + this->rigid.SetOrientation( orientation ); this->body.center = orientation.v[3].xyz; } void SphericalRigidBody::SetSize( const Float3 &size ) { - this->current.SetSize( size ); + this->rigid.SetSize( size ); this->body.radius = 0.5f * Min( Min( size.x, size.y ), size.z ); // inline Min( FloatN )? } \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.h b/Code/GamePhysics/Implementation/SphericalRigidBody.h index 1540f7a1..61f5d604 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.h +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.h @@ -11,6 +11,7 @@ namespace Oyster { namespace Physics { public: SphericalRigidBody(); + SphericalRigidBody( const API::SphericalBodyDescription &desc ); virtual ~SphericalRigidBody(); ::Utility::DynamicMemory::UniquePointer Clone() const; @@ -43,7 +44,7 @@ namespace Oyster { namespace Physics void SetSize( const ::Oyster::Math::Float3 &size ); private: - ::Oyster::Physics3D::RigidBody previous, current; + ::Oyster::Physics3D::RigidBody rigid; ::Oyster::Math::Float3 gravityNormal; EventAction_Collision collisionAction; bool ignoreGravity; From f379ed49e5266345a64ce1787ec4e19a3d6f3077 Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 12:18:06 +0100 Subject: [PATCH 46/67] inertiaTensor removed from API::SphericalBodyDescription was redundant. struct already have everything that the factory needs to generate one. --- Code/GamePhysics/Implementation/SphericalRigidBody.cpp | 2 +- Code/GamePhysics/PhysicsAPI.h | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp index baf8d98b..292a2dd2 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp @@ -21,7 +21,7 @@ SphericalRigidBody::SphericalRigidBody( const API::SphericalBodyDescription &des { this->rigid = RigidBody( Box( desc.rotation, desc.centerPosition, Float3(2.0f * desc.radius) ), desc.mass, - desc.inertiaTensor ); + MomentOfInertia::CreateSphereMatrix( desc.mass, desc.radius ) ); this->gravityNormal = Float3::null; if( desc.subscription ) diff --git a/Code/GamePhysics/PhysicsAPI.h b/Code/GamePhysics/PhysicsAPI.h index dd36a9ee..6cba993c 100644 --- a/Code/GamePhysics/PhysicsAPI.h +++ b/Code/GamePhysics/PhysicsAPI.h @@ -415,7 +415,6 @@ namespace Oyster ::Oyster::Math::Float3 centerPosition; ::Oyster::Math::Float radius; ::Oyster::Math::Float mass; - ::Oyster::Math::Float4x4 inertiaTensor; ICustomBody::EventAction_Collision subscription; bool ignoreGravity; @@ -425,7 +424,6 @@ namespace Oyster this->centerPosition = ::Oyster::Math::Float3::null; this->radius = 0.5f; this->mass = 10.0f; - this->inertiaTensor = ::Oyster::Math::Float4x4::identity; this->subscription = NULL; this->ignoreGravity = false; } From d08644e8e1ecc56f4d9dfa6a9aa33df94d9e655a Mon Sep 17 00:00:00 2001 From: dean11 Date: Thu, 28 Nov 2013 13:43:11 +0100 Subject: [PATCH 47/67] Added a force reload feture in resource loading --- Code/Misc/Resource/OResourceHandler.cpp | 73 +++++++++++++++++-------- Code/Misc/Resource/OysterResource.h | 7 ++- Code/Misc/Thread/OysterMutex.cpp | 1 + Code/Misc/Thread/OysterMutex.h | 36 +++++++----- Code/Misc/Thread/OysterThread_Impl.cpp | 2 +- 5 files changed, 76 insertions(+), 43 deletions(-) diff --git a/Code/Misc/Resource/OResourceHandler.cpp b/Code/Misc/Resource/OResourceHandler.cpp index 21653d4e..36154d09 100644 --- a/Code/Misc/Resource/OResourceHandler.cpp +++ b/Code/Misc/Resource/OResourceHandler.cpp @@ -23,46 +23,71 @@ public: } resourcePrivate; -OHRESOURCE OysterResource::LoadResource(const wchar_t* filename, ResourceType type) +OHRESOURCE OysterResource::LoadResource(const wchar_t* filename, ResourceType type, int customID, bool force) { if(!filename) return 0; OResource *resourceData = resourcePrivate.FindResource(filename); + if(resourceData) { - //Add new reference - resourcePrivate.SaveResource(resourceData, false); - return resourceData->GetResourceHandle(); + if(force) + { + return OysterResource::ReloadResource(filename); + } + else + { + //Add new reference + resourcePrivate.SaveResource(resourceData, false); + return resourceData->GetResourceHandle(); + } + } + else + { + resourceData = OResource::Load(filename, type); + if(resourceData) + { + resourceData->SetResourceID(customID); + resourcePrivate.SaveResource(resourceData); + } } - - resourceData = OResource::Load(filename, type); - - if(!resourceData) return 0; - - resourcePrivate.SaveResource(resourceData); return resourceData->GetResourceHandle(); } -OHRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunction loadFnc, int CustomId) +OHRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunction loadFnc, int customId, bool force) { - if(!filename) return 0; - if(!loadFnc) return 0; + if(!filename) + { + return 0; + } + if(!loadFnc) + { + return 0; + } OResource *resourceData = resourcePrivate.FindResource(filename); if(resourceData) { - //Add new reference - resourcePrivate.SaveResource(resourceData, false); - return resourceData->GetResourceHandle(); + if(force) + { + return OysterResource::ReloadResource(filename); + } + else + { + //Add new reference + resourcePrivate.SaveResource(resourceData, false); + return resourceData->GetResourceHandle(); + } + } + else + { + resourceData = OResource::Load(filename, loadFnc); + if(resourceData) + { + resourceData->SetResourceID(customId); + resourcePrivate.SaveResource(resourceData); + } } - - resourceData = OResource::Load(filename, loadFnc); - - if(!resourceData) return 0; - - resourceData->SetResourceID(CustomId); - - resourcePrivate.SaveResource(resourceData); return (OHRESOURCE)resourceData->GetResourceHandle(); } diff --git a/Code/Misc/Resource/OysterResource.h b/Code/Misc/Resource/OysterResource.h index 8fc0e560..4906e6c7 100644 --- a/Code/Misc/Resource/OysterResource.h +++ b/Code/Misc/Resource/OysterResource.h @@ -54,16 +54,17 @@ namespace Oyster * @param force If set to true, the resource will be reloaded if it already exists. If it does not, nothing happens. * @return If function suceeds, a handle to the resource will be returned. If failed 0 is returned. */ - static OHRESOURCE LoadResource(const wchar_t filename[], ResourceType type); + static OHRESOURCE LoadResource(const wchar_t filename[], ResourceType type, int customId = -1, bool force = false); /** * Load a resource with a custom loading function * @param filename The path to the resource. - * @param force If set to true, the resource will be reloaded even if exists. * @param loadFnc If set, this gives you the right to do custom resource loading if your recource type is not supported. + * @param customId A custom ID that can be used. + * @param force If set to true, the resource will be reloaded even if exists. * @return If function suceeds, a handle to the resource will be returned. If failed 0 is returned. */ - static OHRESOURCE LoadResource(const wchar_t filename[], CustomLoadFunction loadFnc = 0, int CustomId = -1); + static OHRESOURCE LoadResource(const wchar_t filename[], CustomLoadFunction loadFnc = 0, int customId = -1, bool force = false); /** * Reload a resource diff --git a/Code/Misc/Thread/OysterMutex.cpp b/Code/Misc/Thread/OysterMutex.cpp index 089323ce..b02ef344 100644 --- a/Code/Misc/Thread/OysterMutex.cpp +++ b/Code/Misc/Thread/OysterMutex.cpp @@ -8,6 +8,7 @@ #include #include +using namespace Oyster::Thread; OysterMutex::OysterMutex() diff --git a/Code/Misc/Thread/OysterMutex.h b/Code/Misc/Thread/OysterMutex.h index 18282499..d9f29d95 100644 --- a/Code/Misc/Thread/OysterMutex.h +++ b/Code/Misc/Thread/OysterMutex.h @@ -9,23 +9,29 @@ #include #include -class OysterMutex +namespace Oyster { -public: - OysterMutex(); - OysterMutex(bool initialOwnership); - virtual~OysterMutex(); - void LockMutex(); - void LockMutex(unsigned int timeSpan); - void UnlockMutex(); - /** Returns true if mutex is taken */ - bool IsTaken(); + namespace Thread + { + class OysterMutex + { + public: + OysterMutex(); + OysterMutex(bool initialOwnership); + virtual~OysterMutex(); + void LockMutex(); + void LockMutex(unsigned int timeSpan); + void UnlockMutex(); + /** Returns true if mutex is taken */ + bool IsTaken(); -private: - std::mutex mutex; - std::thread::id id; + private: + std::mutex mutex; + std::thread::id id; - OysterMutex(const OysterMutex&); -}; + OysterMutex(const OysterMutex&); + }; + } +} #endif // !MISC_OYSTER_MUTEX_H diff --git a/Code/Misc/Thread/OysterThread_Impl.cpp b/Code/Misc/Thread/OysterThread_Impl.cpp index 9b01e6d5..46b889fe 100644 --- a/Code/Misc/Thread/OysterThread_Impl.cpp +++ b/Code/Misc/Thread/OysterThread_Impl.cpp @@ -62,7 +62,7 @@ using namespace Utility::DynamicMemory::SmartPointer; ~PrivateData() { //@todo TODO: Make detatch avalible. - //this->threadData->workerThread->detach(); + this->threadData->workerThread->detach(); this->threadData->owner = 0; From 632d412f9cd1987901c0023bd03bb9053c9ee2dc Mon Sep 17 00:00:00 2001 From: Robin Engman Date: Thu, 28 Nov 2013 14:18:44 +0100 Subject: [PATCH 48/67] Fixed sample and added visit. --- Bin/DLL/GamePhysics_x86D.exp | Bin 0 -> 4647 bytes Code/GamePhysics/Implementation/Octree.cpp | 49 +++++++++++++++++++-- Code/GamePhysics/Implementation/Octree.h | 20 ++++++--- 3 files changed, 60 insertions(+), 9 deletions(-) create mode 100644 Bin/DLL/GamePhysics_x86D.exp diff --git a/Bin/DLL/GamePhysics_x86D.exp b/Bin/DLL/GamePhysics_x86D.exp new file mode 100644 index 0000000000000000000000000000000000000000..0cea5aa656b285c7e0ab517de7be488640d073f4 GIT binary patch literal 4647 zcmeHKOK%%h6h3LvI*&dQ-tU?cXi_R;CvKcVDvuwKM%YQ3P*b51VdA+-MmQd8WPfQo(0^ytXZtxAttK zY_HX4XYw(^W{JY8AZvmIe6%B9T9N+w&1C#DqTjj*6A^4Epjj_sJ+SySIT zIMqSHGG(IOs)|^Z`)gQ^%Z;dHyBs*OOhz79>+vPS67DmlXl{$Dv$U~L6_#UY?GC(6 zrL|PMRn24-oaMDt*fL~H&JvmsZZXGMCfiZgjGqREkQ$s0z)> zR5r!Br721ggDwNB&*M2JJl}*T`w3vbWKkfuw+M{`(a6BKA3iKu1;~vpLT7=GNLG`` zS{&?Ax#s`}B})PyldKLLl57_ExMc4Ehb5Z>@+u|`F3_LDb0T`9+6W|HSmVr-8_9<{wve$s8B>Mu$-8e#5fX_(wHSj*kR3M*` z2z>**U$VD=&r0?!@BztmAp1gut^*&GYzuf=vYWt%BpU$!iSG+I#Rcl)!jyYa&6g6% zR7#yUoal13g_ep22o)P@%$x$XufpmbjLn(9#aP0DPaZL`OO7P zN)J zpOU0Y=$oyX&(ZfjWrl{)CR<}tB7t1TOKHYF)7gnSD6nePC)rGp!^t6ehVl= zyfkmPwdMkf9Z;?Xlpg}hsGCmac4;-B{1Q-3H=Wo!8&~gAZelOQ&RX9o_IleafData = orig.leafData; + this->updateQueue = orig.updateQueue; + this->worldNode = orig.worldNode; + this->mapReferences = orig.mapReferences; + + return *this; +} + void Octree::AddObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) { Data data; @@ -50,7 +60,6 @@ void Octree::MoveToUpdateQueue(Utility::DynamicMemory::UniquePointer< ICustomBod this->updateQueue.push_back(&this->leafData[this->mapReferences[customBodyRef]]);*/ } - void Octree::DestroyObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) { std::map::iterator it = this->mapReferences.find(customBodyRef); @@ -60,13 +69,22 @@ void Octree::DestroyObject(Utility::DynamicMemory::UniquePointer< ICustomBody > this->leafData.erase(this->leafData.begin() + this->leafData[this->mapReferences[customBodyRef]].queueRef); } -std::vector Octree::Sample(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +std::vector Octree::Sample(ICustomBody* customBodyRef) { std::vector list; + auto object = this->mapReferences.find(customBodyRef); + + if(object == this->mapReferences.end()) + { + return list; + } + + unsigned int tempRef = object->second; + for(unsigned int i = 0; ileafData.size(); i++) { - if(this->leafData[i].customBodyRef != customBodyRef) if(this->leafData[i].container.Intersects(customBodyRef->GetBoundingSphere())) + if(tempRef != i) if(this->leafData[tempRef].container.Intersects(this->leafData[i].container)) { list.push_back(this->leafData[i].customBodyRef); } @@ -74,3 +92,28 @@ std::vector Octree::Sample(Utility::DynamicMemory::UniquePointer< return list; } + +void Octree::Visit(ICustomBody* customBodyRef, VistorAction hitAction ) +{ + auto object = this->mapReferences.find(customBodyRef); + + if(object == this->mapReferences.end()) + { + return; + } + + unsigned int tempRef = object->second; + + for(unsigned int i = 0; ileafData.size(); i++) + { + if(tempRef != i) if(this->leafData[tempRef].container.Intersects(this->leafData[i].container)) + { + hitAction(*this, tempRef, i); + } + } +} + +ICustomBody* Octree::GetCustomBody(const unsigned int tempRef) +{ + return this->leafData[tempRef].customBodyRef; +} \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/Octree.h b/Code/GamePhysics/Implementation/Octree.h index 6034d129..8d111329 100644 --- a/Code/GamePhysics/Implementation/Octree.h +++ b/Code/GamePhysics/Implementation/Octree.h @@ -15,6 +15,8 @@ namespace Oyster class Octree { public: + typedef void(*VistorAction)(Octree&, unsigned int, unsigned int); + struct Data { Data* prev; @@ -22,7 +24,7 @@ namespace Oyster Collision3D::Sphere container; - Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef; + ::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef; unsigned int queueRef; }; @@ -34,16 +36,22 @@ namespace Oyster Collision3D::BoxAxisAligned container; }; - Octree(unsigned int bufferSize, unsigned char numLayers, Math::Float3 worldSize); + Octree(unsigned int bufferSize = 0, unsigned char numLayers = 0, Math::Float3 worldSize = Math::Float3::null); virtual ~Octree(); - void AddObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + Octree& operator=(const Octree& orig); - void MoveToUpdateQueue(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + void AddObject(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); - void DestroyObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + void MoveToUpdateQueue(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + + void DestroyObject(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); + + std::vector Sample(ICustomBody* customBodyRef); + void Visit(ICustomBody* customBodyRef, VistorAction hitAction ); + + ICustomBody* GetCustomBody(const unsigned int tempRef); - std::vector Sample(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); private: std::vector < Data > leafData; std::vector < Data* > updateQueue; From d24129830851365130b3b6199d1acb1c64ba03f6 Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 14:52:13 +0100 Subject: [PATCH 49/67] merging MiscBranch into Physics with conflict fixes --- .../Resource/Loaders/CustomLoader.cpp.orig | 65 ++++ Code/Misc/Resource/OResourceHandler.cpp.orig | 258 +++++++++++++ Code/Misc/Resource/OysterResource.h.orig | 164 +++++++++ Code/Misc/Thread/OysterMutex.cpp.orig | 67 ++++ Code/Misc/Thread/OysterMutex.h.orig | 37 ++ Code/Misc/Thread/OysterThread.h.orig | 47 +++ Code/Misc/Thread/OysterThread_Impl.cpp.orig | 281 ++++++++++++++ Code/Misc/Utilities-InlineImpl.h.orig | 315 ++++++++++++++++ Code/Misc/Utilities.h.orig | 347 ++++++++++++++++++ 9 files changed, 1581 insertions(+) create mode 100644 Code/Misc/Resource/Loaders/CustomLoader.cpp.orig create mode 100644 Code/Misc/Resource/OResourceHandler.cpp.orig create mode 100644 Code/Misc/Resource/OysterResource.h.orig create mode 100644 Code/Misc/Thread/OysterMutex.cpp.orig create mode 100644 Code/Misc/Thread/OysterMutex.h.orig create mode 100644 Code/Misc/Thread/OysterThread.h.orig create mode 100644 Code/Misc/Thread/OysterThread_Impl.cpp.orig create mode 100644 Code/Misc/Utilities-InlineImpl.h.orig create mode 100644 Code/Misc/Utilities.h.orig diff --git a/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig b/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig new file mode 100644 index 00000000..15dea599 --- /dev/null +++ b/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig @@ -0,0 +1,65 @@ + +#include "..\OResource.h" +#include "..\..\Utilities.h" + +#include + +using namespace Oyster::Resource; + + +OResource* OResource::CustomLoader(const wchar_t filename[], CustomLoadFunction fnc) +{ +<<<<<<< HEAD + const CustomData &data = fnc(); +======= + CustomData data; + memset(&data, 0, sizeof(CustomData)); + + fnc(filename, data); + + if(!data.loadedData) + { + return 0; + } + if(!data.resourceUnloadFnc) + { + return 0; + } + /** For some wierd reason that i don't understand when trying to send data.loadedData directly as a + * parameter to OResource constructor, the value is changed when it arrives in the constructor. + * Doing it like this, storing in a temporary variable, the value stays correct. (What the fuck! I must be overloking something...)*/ + //OHRESOURCE temp = data.loadedData; + OResource *resource = new OResource(data.loadedData, ResourceType_UNKNOWN, 0, 0, filename); +>>>>>>> origin/MiscBranch + + resource->customData = new CustomResourceData(); + resource->customData->unloadingFunction = data.resourceUnloadFnc; + resource->customData->loadingFunction = fnc; + + return resource; +} +void OResource::CustomUnloader() +{ + this->customData->unloadingFunction(this->resourceData); +} +OResource* OResource::CustomReloader() +{ + CustomUnloader(); + +<<<<<<< HEAD + const CustomData &data = this->customData->loadingFunction(); +======= + CustomData data; + memset(&data, 0, sizeof(CustomData)); + + this->customData->loadingFunction(this->resourceFilename.c_str(), data); +>>>>>>> origin/MiscBranch + this->resourceData = (OHRESOURCE)data.loadedData; + + if(data.resourceUnloadFnc) + { + this->customData->unloadingFunction = data.resourceUnloadFnc; + } + return this; +} + diff --git a/Code/Misc/Resource/OResourceHandler.cpp.orig b/Code/Misc/Resource/OResourceHandler.cpp.orig new file mode 100644 index 00000000..923ab706 --- /dev/null +++ b/Code/Misc/Resource/OResourceHandler.cpp.orig @@ -0,0 +1,258 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + + +#include "OysterResource.h" +#include "OResource.h" +#include +#include + +using namespace Oyster::Resource; + +class ResourcePrivate +{ +public: + + std::map resources; + + OResource* FindResource(const OHRESOURCE& h) const; + OResource* FindResource(const wchar_t c[]) const; + void SaveResource(OResource* r, bool addNew = true); + +} resourcePrivate; + + +OHRESOURCE OysterResource::LoadResource(const wchar_t* filename, ResourceType type, int customID, bool force) +{ + if(!filename) return 0; + + OResource *resourceData = resourcePrivate.FindResource(filename); + + if(resourceData) + { + if(force) + { + return OysterResource::ReloadResource(filename); + } + else + { + //Add new reference + resourcePrivate.SaveResource(resourceData, false); + return resourceData->GetResourceHandle(); + } + } + else + { + resourceData = OResource::Load(filename, type); + if(resourceData) + { + resourceData->SetResourceID(customID); + resourcePrivate.SaveResource(resourceData); + } + } + + return resourceData->GetResourceHandle(); +} +OHRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunction loadFnc, int customId, bool force) +{ + if(!filename) + { + return 0; + } + if(!loadFnc) + { + return 0; + } + + OResource *resourceData = resourcePrivate.FindResource(filename); + if(resourceData) + { + if(force) + { + return OysterResource::ReloadResource(filename); + } + else + { + //Add new reference + resourcePrivate.SaveResource(resourceData, false); + return resourceData->GetResourceHandle(); + } + } + else + { + resourceData = OResource::Load(filename, loadFnc); + if(resourceData) + { + resourceData->SetResourceID(customId); + resourcePrivate.SaveResource(resourceData); + } + } +<<<<<<< HEAD + + resourceData = OResource::Load(filename, loadFnc); + + if(!resourceData) return 0; + + if(resourceData) resourceData->SetResourceID(CustomId); + resourcePrivate.SaveResource(resourceData); +======= +>>>>>>> origin/MiscBranch + + return (OHRESOURCE)resourceData->GetResourceHandle(); +} + +OHRESOURCE OysterResource::ReloadResource(const wchar_t filename[]) +{ + OResource *resourceData = resourcePrivate.FindResource(filename); + if(!resourceData) return 0; //The resource has not been loaded + + return OResource::Reload(resourceData)->GetResourceHandle(); +} +OHRESOURCE OysterResource::ReloadResource(OHRESOURCE resource) +{ + OResource *resourceData = resourcePrivate.FindResource(resource); + if(!resourceData) return 0; //The resource has not been loaded + + return OResource::Reload(resourceData)->GetResourceHandle(); +} + +void OysterResource::Clean() +{ + auto i = resourcePrivate.resources.begin(); + auto last = resourcePrivate.resources.end(); + + for (i; i != last; i++) + { + //Remove all the references + while (!OResource::Release(i->second)); + + const wchar_t* temp = i->second->GetResourceFilename(); + delete resourcePrivate.resources[temp]; + resourcePrivate.resources.erase(temp); + + } +} +void OysterResource::ReleaseResource(const OHRESOURCE& resourceData) +{ + OResource* t = resourcePrivate.FindResource(resourceData); + if(t) + { + if(OResource::Release(t)) + { + const wchar_t* temp = t->GetResourceFilename(); + delete resourcePrivate.resources[temp]; + resourcePrivate.resources.erase(temp); + } + } +} +void OysterResource::ReleaseResource(const wchar_t filename[]) +{ + OResource* t = resourcePrivate.FindResource(filename); + if(t) + { + if(OResource::Release(t)) + { + const wchar_t* temp = t->GetResourceFilename(); + delete resourcePrivate.resources[temp]; + resourcePrivate.resources.erase(temp); + } + } +} + +void OysterResource::SetResourceId (const OHRESOURCE& resourceData, unsigned int id) +{ + OResource* t = resourcePrivate.FindResource(resourceData); + + if(t) t->SetResourceID(id); +} +void OysterResource::SetResourceId(const wchar_t c[], unsigned int id) +{ + OResource* t = resourcePrivate.FindResource(c); + + if(t) t->SetResourceID(id); +} +ResourceType OysterResource::GetResourceType (const OHRESOURCE& resourceData) +{ + OResource* t = resourcePrivate.FindResource(resourceData); + + if(t) return t->GetResourceType(); + + return ResourceType_INVALID; +} +ResourceType OysterResource::GetResourceType (const wchar_t c[]) +{ + OResource* t = resourcePrivate.FindResource(c); + + if(t) return t->GetResourceType(); + + return ResourceType_INVALID; +} +const wchar_t* OysterResource::GetResourceFilename (const OHRESOURCE& resourceData) +{ + OResource* t = resourcePrivate.FindResource(resourceData); + + if(t) return t->GetResourceFilename(); + + return 0; +} +OHRESOURCE OysterResource::GetResourceHandle(const wchar_t filename[]) +{ + OResource* t = resourcePrivate.FindResource(filename); + + if(t) return t->GetResourceHandle(); + + return 0; +} +int OysterResource::GetResourceId (const OHRESOURCE& resourceData) +{ + OResource* t = resourcePrivate.FindResource(resourceData); + + if(t) return t->GetResourceID(); + + return -1; +} +int OysterResource::GetResourceId(const wchar_t c[]) +{ + OResource* t = resourcePrivate.FindResource(c); + + if(t) return t->GetResourceID(); + + return -1; +} + + +OResource* ResourcePrivate::FindResource(const OHRESOURCE& h) const +{ + for (auto i = this->resources.begin(); i != this->resources.end() ; i++) + { + if(i->second->GetResourceHandle() == h) + { + return i->second; + } + } + return 0; +} +OResource* ResourcePrivate::FindResource(const wchar_t c[]) const +{ + std::wstring temp = c; + auto t = this->resources.find(c); + if(t == this->resources.end()) return 0; + + return t->second; +} +void ResourcePrivate::SaveResource( OResource* r, bool addNew ) +{ + if(!r) return; + + if(addNew) + { + this->resources[r->GetResourceFilename()] = r; + } + + r->resourceRef.Incref(); +} + + + + diff --git a/Code/Misc/Resource/OysterResource.h.orig b/Code/Misc/Resource/OysterResource.h.orig new file mode 100644 index 00000000..906b77fb --- /dev/null +++ b/Code/Misc/Resource/OysterResource.h.orig @@ -0,0 +1,164 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#ifndef MISC_OYSTER_RESOURCE_H +#define MISC_OYSTER_RESOURCE_H + + +namespace Oyster +{ + namespace Resource + { + struct CustomData; + /** A Resource handle representing various resources */ +<<<<<<< HEAD + typedef unsigned long OHRESOURCE; + typedef void(*CustomUnloadFunction)(void*); + typedef const CustomData&(*CustomLoadFunction)(); +======= + typedef void* OHRESOURCE; + /** Typedef on a fuction required for custom unloading */ + typedef void(*CustomUnloadFunction)(void* loadedData); + /** Typedef on a fuction required for custom loading */ + typedef void(*CustomLoadFunction)(const wchar_t filename[], CustomData& outData); +>>>>>>> origin/MiscBranch + + /** An enum class representing all avalible resources that is supported. */ + enum ResourceType + { + //Byte + ResourceType_Byte_Raw, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_ANSI, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_UTF8, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_UNICODE, /**< Handle can be interpeted as char[] or char* */ + ResourceType_Byte_UTF16LE, /**< Handle can be interpeted as char[] or char* */ + + ResourceType_COUNT, /**< Handle can be interpeted as ? */ + + ResourceType_UNKNOWN = -1, /**< Handle can be interpeted as void* */ + ResourceType_INVALID = -2, /**< Invalid or non existing resource */ + }; + + /** A struct to fill when doing a custom resource Load. */ + struct CustomData + { + void* loadedData; // +#include +#include + +using namespace Oyster::Thread; + + +OysterMutex::OysterMutex() +{} + +OysterMutex::OysterMutex(bool initialOwnership) +{ + if(initialOwnership) + { + this->mutex.lock(); + this->id = std::this_thread::get_id(); + } +} +OysterMutex::~OysterMutex() +{ +} +void OysterMutex::LockMutex() +{ + if(std::this_thread::get_id() == this->id) return; + + this->mutex.lock(); + + this->id = std::this_thread::get_id(); +} +void OysterMutex::LockMutex(unsigned int msec) +{ + if(std::this_thread::get_id() == this->id) return; + + auto start = std::chrono::high_resolution_clock::now(); + auto end = start + std::chrono::milliseconds(msec); + + do + { + if(this->mutex.try_lock()) + { + this->mutex.lock(); + this->id = std::this_thread::get_id(); + return; + } + } while (std::chrono::high_resolution_clock::now() < end); + + this->mutex.lock(); +} +void OysterMutex::UnlockMutex() +{ + //Let the owner unlock + if(std::this_thread::get_id() != this->id) return; + + this->mutex.unlock(); + this->id = std::thread::id(); + +} +bool OysterMutex::IsTaken() +{ + return !this->mutex.try_lock(); +} \ No newline at end of file diff --git a/Code/Misc/Thread/OysterMutex.h.orig b/Code/Misc/Thread/OysterMutex.h.orig new file mode 100644 index 00000000..d9f29d95 --- /dev/null +++ b/Code/Misc/Thread/OysterMutex.h.orig @@ -0,0 +1,37 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#ifndef MISC_OYSTER_MUTEX_H +#define MISC_OYSTER_MUTEX_H + +#include +#include +#include + +namespace Oyster +{ + namespace Thread + { + class OysterMutex + { + public: + OysterMutex(); + OysterMutex(bool initialOwnership); + virtual~OysterMutex(); + void LockMutex(); + void LockMutex(unsigned int timeSpan); + void UnlockMutex(); + /** Returns true if mutex is taken */ + bool IsTaken(); + + private: + std::mutex mutex; + std::thread::id id; + + OysterMutex(const OysterMutex&); + }; + } +} + +#endif // !MISC_OYSTER_MUTEX_H diff --git a/Code/Misc/Thread/OysterThread.h.orig b/Code/Misc/Thread/OysterThread.h.orig new file mode 100644 index 00000000..05a9f8ad --- /dev/null +++ b/Code/Misc/Thread/OysterThread.h.orig @@ -0,0 +1,47 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#ifndef MISC_OYSTER_THREAD_H +#define MISC_OYSTER_THREAD_H + +#include "IThreadObject.h" +namespace Oyster +{ + namespace Thread + { + enum OYSTER_THREAD_ERROR + { + OYSTER_THREAD_ERROR_FAILED, + OYSTER_THREAD_ERROR_SUCCESS, + }; + + class OysterThread + { + private: + struct PrivateData; + PrivateData *privateData; + + public: + OysterThread(); + OysterThread(const OysterThread& original); + const OysterThread& operator=(const OysterThread& original); + virtual~OysterThread(); + + OYSTER_THREAD_ERROR Create(IThreadObject* worker, bool start); + OYSTER_THREAD_ERROR Start(); + void Stop(); + void Pause(); + void Pause(int mSec); + void Resume(); + OYSTER_THREAD_ERROR Reset(IThreadObject* worker = 0); + void Terminate(); + void Wait(); + void Wait(int mSec); + OYSTER_THREAD_ERROR Swap(const OysterThread* other); + bool IsActive(); + }; + } +} + +#endif // !MISC_OYSTER_THREAD_H diff --git a/Code/Misc/Thread/OysterThread_Impl.cpp.orig b/Code/Misc/Thread/OysterThread_Impl.cpp.orig new file mode 100644 index 00000000..46b889fe --- /dev/null +++ b/Code/Misc/Thread/OysterThread_Impl.cpp.orig @@ -0,0 +1,281 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#include "OysterThread.h" +#include "OysterMutex.h" +#include "..\Utilities.h" +#include +#include +#include + +using namespace Oyster::Thread; +using namespace Utility::DynamicMemory::SmartPointer; + + +#pragma region Declerations + + struct ThreadData; + /** A typical Oyster thread function */ + typedef void (*ThreadFunction)(StdSmartPointer&); + + enum OYSTER_THREAD_STATE + { + OYSTER_THREAD_STATE_RESET, + OYSTER_THREAD_STATE_RUNNING, + OYSTER_THREAD_STATE_PAUSED, + OYSTER_THREAD_STATE_STOPED, + OYSTER_THREAD_STATE_DEAD, + }; + + + struct ThreadData + { + std::atomic state; // workerThread; // msec; // threadData; + + PrivateData() + :threadData(new ThreadData()) + { + threadData->owner = 0; + threadData->workerThread = 0; + threadData->callingThread; + threadData->state = OYSTER_THREAD_STATE_STOPED; + } + PrivateData(const PrivateData& o) + { + threadData = o.threadData; + } + ~PrivateData() + { + //@todo TODO: Make detatch avalible. + this->threadData->workerThread->detach(); + + this->threadData->owner = 0; + + this->threadData->state = OYSTER_THREAD_STATE_DEAD; + } + + }; + +#pragma endregion + + +int tempId = 0; +std::vector IDS; +static void ThreadingFunction(StdSmartPointer &origin) +{ + + bool shouldContinue; + StdSmartPointer w = origin; + +theBegining: + + while(w->state == OYSTER_THREAD_STATE_STOPED) + { + std::this_thread::yield(); + } + +// w->mutexLock.LockMutex(); + if(w->owner) + { + w->owner->ThreadEntry(); + } +// w->mutexLock.UnlockMutex(); + + while (w->state != OYSTER_THREAD_STATE_STOPED && w->state != OYSTER_THREAD_STATE_DEAD) + { +// w->mutexLock.LockMutex(); + { + if(w->owner) + { + shouldContinue = w->owner->DoWork(); + } + } +// w->mutexLock.UnlockMutex(); + + if(!shouldContinue) + { + goto theEnd; + } + if(w->state == OYSTER_THREAD_STATE_DEAD) + { + goto theEnd; + } + else if(w->state == OYSTER_THREAD_STATE_RESET) + { + goto theBegining; + } + else if(w->msec > 0) + { + std::this_thread::sleep_for(std::chrono::milliseconds(w->msec)); + } + + while (w->state == OYSTER_THREAD_STATE_PAUSED) + { + std::this_thread::yield(); + } + } + + if(w->state == OYSTER_THREAD_STATE_DEAD) + { + w->workerThread->detach(); + return; + } + +theEnd: + +// w->mutexLock.LockMutex(); + if(w->owner) + { + w->owner->ThreadExit(); + } +// w->mutexLock.UnlockMutex(); + + w->state = OYSTER_THREAD_STATE_DEAD; +} + +OysterThread::OysterThread() +{ + this->privateData = new PrivateData(); +} +OysterThread::OysterThread(const OysterThread& original) +{ + this->privateData = new PrivateData(*original.privateData); +} +const OysterThread& OysterThread::operator=(const OysterThread& original) +{ + return *this; +} +OysterThread::~OysterThread() +{ + delete this->privateData; + this->privateData = 0; +} + +OYSTER_THREAD_ERROR OysterThread::Create(IThreadObject* worker, bool start) +{ + if(!this->privateData) return OYSTER_THREAD_ERROR_FAILED; + if(this->privateData->threadData->workerThread) return OYSTER_THREAD_ERROR_FAILED; + + this->privateData->threadData->owner = worker; + + ThreadFunction fnc = ThreadingFunction; + + //Maby move this thread creation to a seperate Start() function because std::thread fires the thread when it is created. :( + this->privateData->threadData->workerThread = new std::thread(fnc, this->privateData->threadData); + + if(!this->privateData->threadData->workerThread) + return OYSTER_THREAD_ERROR_FAILED; + + if(start) + { + this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; + } + return OYSTER_THREAD_ERROR_SUCCESS; +} +OYSTER_THREAD_ERROR OysterThread::Start() +{ + if(!this->privateData->threadData->owner) + return OYSTER_THREAD_ERROR_FAILED; + if(!this->privateData->threadData->workerThread) + return OYSTER_THREAD_ERROR_FAILED; + if(this->privateData->threadData->state == OYSTER_THREAD_STATE_DEAD) + return OYSTER_THREAD_ERROR_FAILED; + + this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; + return OYSTER_THREAD_ERROR_SUCCESS; +} +void OysterThread::Stop() +{ + //this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_STOPED; + //this->privateData->threadData->mutexLock.UnlockMutex(); +} +void OysterThread::Pause() +{ + //this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_PAUSED; + //this->privateData->threadData->mutexLock.UnlockMutex(); +} +void OysterThread::Pause(int msec) +{ + + if(std::this_thread::get_id() == this->privateData->threadData->workerThread->get_id()) + { + this->privateData->threadData->msec = msec; + } + else + { + //this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_PAUSED; + this->privateData->threadData->msec = msec; + //this->privateData->threadData->mutexLock.UnlockMutex(); + } +} +void OysterThread::Resume() +{ +// this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; +// this->privateData->threadData->mutexLock.UnlockMutex(); +} +OYSTER_THREAD_ERROR OysterThread::Reset(IThreadObject* worker) +{ +// this->privateData->threadData->mutexLock.LockMutex(); + if(worker) + { + this->privateData->threadData->owner = worker; + } + this->privateData->threadData->callingThread = std::this_thread::get_id(); + this->privateData->threadData->msec = 0; +// this->privateData->threadData->mutexLock.UnlockMutex(); + + return OYSTER_THREAD_ERROR_SUCCESS; +} +void OysterThread::Terminate() +{ + this->privateData->threadData->state = OYSTER_THREAD_STATE_DEAD; +} +void OysterThread::Wait() +{ + if(this->privateData->threadData->state == OYSTER_THREAD_STATE_DEAD) + { + return; + } + + if(this->privateData->threadData->workerThread->get_id() == std::this_thread::get_id()) return; + + this->privateData->threadData->workerThread->join(); +} +void OysterThread::Wait(int msec) +{ + if(this->privateData->threadData->workerThread->get_id() == std::this_thread::get_id()) return; + + std::this_thread::sleep_for(std::chrono::milliseconds(msec)); +} +OYSTER_THREAD_ERROR OysterThread::Swap(const OysterThread* other) +{ + this->privateData->threadData->workerThread->swap(*other->privateData->threadData->workerThread); + return OYSTER_THREAD_ERROR_SUCCESS; +} +bool OysterThread::IsActive() +{ + if (this->privateData->threadData->state == OYSTER_THREAD_STATE_RUNNING) + return true; + + return false; +} + diff --git a/Code/Misc/Utilities-InlineImpl.h.orig b/Code/Misc/Utilities-InlineImpl.h.orig new file mode 100644 index 00000000..107ea730 --- /dev/null +++ b/Code/Misc/Utilities-InlineImpl.h.orig @@ -0,0 +1,315 @@ +///////////////////////////////////////////////////////////////////// +// Inline and template implementations for +// the Utility Collection of Miscellanious Handy Functions +// © Dan Andersson 2013 +///////////////////////////////////////////////////////////////////// + +#ifndef UTILITIES_INLINE_IMPL_H +#define UTILITIES_INLINE_IMPL_H + +#include "Utilities.h" + +namespace Utility +{ + namespace DynamicMemory + { + template + inline void SafeDeleteInstance( Type *dynamicInstance ) + { + if( dynamicInstance ) + { + delete dynamicInstance; + } + } + + template + void SafeDeleteArray( Type dynamicArray[] ) + { + if( dynamicArray ) + { + delete [] dynamicArray; + } + } + + template + UniquePointer::UniquePointer( Type *assignedInstance ) + { + this->ownedInstance = assignedInstance; + } + + template + UniquePointer::UniquePointer( const UniquePointer &donor ) + { + this->ownedInstance = donor.ownedInstance; + donor.ownedInstance = NULL; + + } + + template + UniquePointer::~UniquePointer() + { + SafeDeleteInstance( this->ownedInstance ); + } + + template + UniquePointer & UniquePointer::operator = ( Type *assignedInstance ) + { + SafeDeleteInstance( this->ownedInstance ); + this->ownedInstance = assignedInstance; + return *this; + } + + template + UniquePointer & UniquePointer::operator = ( const UniquePointer &donor ) + { + SafeDeleteInstance( this->ownedInstance ); + this->ownedInstance = donor.ownedInstance; + donor.ownedInstance = NULL; + return *this; + } + + template + UniquePointer::operator Type* () + { + return this->ownedInstance; + } + + template + UniquePointer::operator const Type* () const + { + return this->ownedInstance; + } + + template + Type * UniquePointer::operator -> () + { + return this->ownedInstance; + } + + template + const Type * UniquePointer::operator -> () const + { + return this->ownedInstance; + } + + template + UniquePointer::operator bool() const + { + return this->ownedInstance != NULL; + } + + template + bool UniquePointer::operator == ( Type *stray ) const + { + return this->ownedInstance == stray; + } + + template + bool UniquePointer::operator != ( Type *stray ) const + { + return this->ownedInstance != stray; + } + + template + Type* UniquePointer::Release() + { + Type *copy = this->ownedInstance; + this->ownedInstance = NULL; + return copy; + } + + template + inline bool UniquePointer::HaveOwnership() const + { + return this->operator bool(); + } + + template + UniqueArray::UniqueArray( Type assignedArray[] ) + { + this->ownedArray = assignedArray; + } + + template + UniqueArray::UniqueArray( const UniqueArray &donor ) + { + this->ownedArray = donor.ownedArray; + donor.ownedArray = NULL; + + } + + template + UniqueArray::~UniqueArray() + { + SafeDeleteArray( this->ownedArray ); + } + + template + UniqueArray & UniqueArray::operator = ( Type assignedArray[] ) + { + SafeDeleteArray( this->ownedArray ); + this->ownedArray = assignedArray; + } + + template + UniqueArray & UniqueArray::operator = ( const UniqueArray &donor ) + { + SafeDeleteArray( this->ownedArray ); + this->ownedArray = donor.ownedInstance; + donor.owned = NULL; + } + + template template + Type & UniqueArray::operator [] ( Index i ) + { + return this->ownedArray[i]; + } + + template template + const Type & UniqueArray::operator [] ( Index i ) const + { + return this->ownedArray[i]; + } + + template + UniqueArray::operator bool () const + { + return this->ownedArray != NULL; + } + + template + bool UniqueArray::operator == ( Type *stray ) const + { + return this->ownedArray == stray; + } + + template + bool UniqueArray::operator != ( Type *stray ) const + { + return this->ownedArray != stray; + } + + template + Type* UniqueArray::Release() + { + Type *copy = this->ownedArray; + this->ownedArray = NULL; + return copy; + } + + template + inline bool UniqueArray::HaveOwnership() const + { + return this->operator bool(); + } +<<<<<<< HEAD +======= + + namespace SmartPointer + { + template void StdSmartPointer::Destroy() + { + delete this->_rc; + this->_rc = NULL; + delete this->_ptr; + this->_ptr = NULL; + } + template StdSmartPointer::StdSmartPointer() + :_rc(0), _ptr(0) + { } + template StdSmartPointer::StdSmartPointer(T* p) + :_ptr(p) + { + this->_rc = new ReferenceCount(); + this->_rc->Incref(); + } + template StdSmartPointer::StdSmartPointer(const StdSmartPointer& d) + :_ptr(d._ptr), _rc(d._rc) + { + if(this->_rc) + this->_rc->Incref(); + } + template StdSmartPointer::~StdSmartPointer() + { + if (this->_rc && this->_rc->Decref() == 0) + { + Destroy(); + } + } + template StdSmartPointer& StdSmartPointer::operator= (const StdSmartPointer& p) + { + if (this != &p) + { + //Last to go? + if(this->_rc && this->_rc->Decref() == 0) + { + //Call child specific + Destroy(); + } + + this->_ptr = p._ptr; + this->_rc = p._rc; + this->_rc->Incref(); + } + return *this; + } + template StdSmartPointer& StdSmartPointer::operator= (T* p) + { + if (this->_ptr != p) + { + //Last to go? + if(this->_rc) + { + if(this->_rc->Decref() == 0) + { + //Call child specific + Destroy(); + this->_rc = new ReferenceCount(); + } + } + else + this->_rc = new ReferenceCount(); + + this->_ptr = p; + this->_rc->Incref(); + } + return *this; + } + template inline bool StdSmartPointer::operator== (const StdSmartPointer& d) + { + return d._ptr == this->_ptr; + } + template inline bool StdSmartPointer::operator== (const T& p) + { + return &p == this->_ptr; + } + template inline T& StdSmartPointer::operator* () + { + return *this->_ptr; + } + template inline T* StdSmartPointer::operator-> () + { + return this->_ptr; + } + template inline StdSmartPointer::operator T* () + { + return this->_ptr; + } + template inline StdSmartPointer::operator bool() + { + return (this->_ptr != 0); + } + template inline T* StdSmartPointer::Get() + { + return this->_ptr; + } + template inline bool StdSmartPointer::IsValid() + { + return (this->_ptr != NULL) ? true : false; + } + } +>>>>>>> origin/MiscBranch + } +} + +#endif \ No newline at end of file diff --git a/Code/Misc/Utilities.h.orig b/Code/Misc/Utilities.h.orig new file mode 100644 index 00000000..55c4820f --- /dev/null +++ b/Code/Misc/Utilities.h.orig @@ -0,0 +1,347 @@ +//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! +// Utility Collection of Miscellanious Handy Functions +// © Dan Andersson 2013 +//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! + +#ifndef UTILITIES_H +#define UTILITIES_H + +#include +#include +#include +#include +#include +#include + +namespace Utility +{ + namespace DynamicMemory + { + //! If dynamicInstance is not NULL, then delete + template void SafeDeleteInstance( Type *dynamicInstance ); + + //! If dynamicArray is not NULL, then delete [] + template void SafeDeleteArray( Type dynamicArray[] ); + + //! Wrapper to safely transfer dynamic ownership/responsibility + template struct UniquePointer + { + public: + //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. + UniquePointer( Type *assignedInstance = NULL ); + + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. + UniquePointer( const UniquePointer &donor ); + + //! Will auto delete assigned dynamic instance. + ~UniquePointer(); + + //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. + UniquePointer & operator = ( Type *assignedInstance ); + + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. + UniquePointer & operator = ( const UniquePointer &donor ); + + //! Access the assigned dynamic instance. Will crash if nothing there + operator Type* (); + + //! Access the assigned dynamic instance. Will crash if nothing there + operator const Type* () const; + + //! Access members of the assigned dynamic instance. Will crash if nothing there + Type * operator -> (); + + //! Access members of the assigned dynamic instance. Will crash if nothing there + const Type * operator -> () const; + + //! If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. + operator bool () const; + + //! @return true if this ownedInstance matches with stray + bool operator == ( Type *stray ) const; + + //! @return false if this ownedInstance matches with stray + bool operator != ( Type *stray ) const; + + //! This UniquePointer drops all claims of ownership/responsibility and returns the dynamic instance. Now it is your responsibility to delete. + Type* Release(); + + //! (inline) If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. + bool HaveOwnership() const; + + private: + mutable Type *ownedInstance; + }; + + template + struct UniqueArray + { //! Wrapper to safely transfer dynamic ownership/responsibility + public: + //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. + UniqueArray( Type assignedArray[] = NULL ); + + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. + UniqueArray( const UniqueArray &donor ); + + //! Will auto delete assigned dynamic array. + ~UniqueArray(); + + //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. + //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. + UniqueArray & operator = ( Type assignedArray[] ); + + //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. + //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. + UniqueArray & operator = ( const UniqueArray &donor ); + + //! Accesses the instance at index i of this UniqeArray's owned dynamic array. + //! Will crash if out-of-bound or there is no assigned array. + template Type & operator [] ( Index i ); + + //! Accesses the instance at index i of this UniqeArray's owned dynamic array. + //! Will crash if out-of-bound or there is no assigned array. + template const Type & operator [] ( Index i ) const; + + //! If true, this UniqueArray have a current ownership/responsibility of a dynamic instance. + operator bool () const; + + //! @return true if this ownedInstance matches with stray + bool operator == ( Type *stray ) const; + + //! @return false if this ownedInstance matches with stray + bool operator != ( Type *stray ) const; + + //! This UniqueArray drops all claims of ownership/responsibility and returns the dynamic array. Now it is your responsibility to delete. + Type* Release(); + + //! (inline) If true, this UniqueArray have a current ownership/responsibility of a dynamic array. + bool HaveOwnership() const; + + private: + mutable Type *ownedArray; + }; + + struct RefCount + { + private: + std::atomic count; + + public: +<<<<<<< HEAD + RefCount() :count(0) { } + RefCount(const RefCount& o) { count = o.count; } + const RefCount& operator=(const RefCount& o) { count = o.count; return *this;} + void Incref() { this->count++; } + void Incref(int c) { this->count += c; } + int Decref() { return --this->count;} + void Reset() { this->count = 0; } + }; +======= + ReferenceCount() :count(0) { } + ReferenceCount(const ReferenceCount& o) { count.store(o.count); } + inline const ReferenceCount& operator=(const ReferenceCount& o) { count.store(o.count); return *this;} + inline void Incref() { this->count++; } + inline void Incref(int c) { this->count += c; } + inline int Decref() { return --this->count;} + inline void Reset() { this->count = 0; } + }; + + namespace SmartPointer + { + //! Smart pointer for a regular object. + /** + * Regular objects, objects that is deleted normaly (ie not COM objects, or array pointers) + * can use this class to easy the use of dynamic memory + */ + template + struct StdSmartPointer + { + private: + ReferenceCount *_rc; + T *_ptr; + + /** Destroys the pointer and returns the memory allocated. */ + void Destroy(); + + public: + StdSmartPointer(); + StdSmartPointer(T* p); + StdSmartPointer(const StdSmartPointer& d); + virtual~StdSmartPointer(); + StdSmartPointer& operator= (const StdSmartPointer& p); + StdSmartPointer& operator= (T* p); + bool operator== (const StdSmartPointer& d); + bool operator== (const T& p); + T& operator* (); + T* operator-> (); + operator T* (); + operator bool(); + + /** + * Returns the connected pointer */ + T* Get(); + + /** Checks if the pointer is valid (not NULL) + Returns true for valid, else false. */ + bool IsValid(); + }; + } + + +>>>>>>> origin/MiscBranch + } + + namespace String + { + // string + + ::std::vector<::std::string> & Split( ::std::vector<::std::string> &output, const ::std::string &str, char delim, ::std::string::size_type offset = 0 ); + ::std::vector<::std::string> & Split( ::std::vector<::std::string> &output, const ::std::string &str, const ::std::string &delim, ::std::string::size_type offset = 0 ); + ::std::vector<::std::string> & Split( ::std::vector<::std::string> &output, const ::std::string &str, const ::std::vector<::std::string> &delim, ::std::string::size_type offset = 0 ); + ::std::string Trim( const ::std::string &str ); + ::std::string & ToLowerCase( ::std::string &output, const ::std::string &str ); + ::std::string & ToLowerCase( ::std::string &str ); + ::std::string & ToUpperCase( ::std::string &output, const ::std::string &str ); + ::std::string & ToUpperCase( ::std::string &str ); + ::std::string & ExtractDirPath( ::std::string &output, const ::std::string &file, char dirDelimeter ); + ::std::string & ExtractDirPath( ::std::string &output, const ::std::string &file, const ::std::string &dirDelimeter ); + ::std::string & ReplaceCharacters( ::std::string &str, char characterToReplace, char newCharacter, const ::std::string::size_type &offset = 0, const ::std::string::size_type &end = ::std::string::npos ); + + // wstring + + ::std::vector<::std::wstring> & Split( ::std::vector<::std::wstring> &output, const ::std::wstring &str, char delim, ::std::wstring::size_type offset = 0 ); + ::std::vector<::std::wstring> & Split( ::std::vector<::std::wstring> &output, const ::std::wstring &str, const ::std::wstring &delim, ::std::wstring::size_type offset = 0 ); + ::std::vector<::std::wstring> & Split( ::std::vector<::std::wstring> &output, const ::std::wstring &str, const ::std::vector<::std::wstring> &delim, ::std::wstring::size_type offset = 0 ); + ::std::wstring & wToLowerCase( ::std::wstring &output, const ::std::wstring &str ); + ::std::wstring & wToLowerCase( ::std::wstring &str ); + + //To wstring + + ::std::wstring & StringToWstring( const ::std::string &str, ::std::wstring &wstr ); + ::std::string & WStringToString( const ::std::wstring &wstr, ::std::string &str ); + } + + namespace Stream + { + float* ReadFloats( float *output, ::std::istream &input, unsigned int numFloats ); + } + + namespace StaticArray + { + template + inline unsigned int NumElementsOf( const ScalarType(&)[num] ) + { return num; } + + template + inline ScalarType & FirstElementOf( ScalarType (&arr)[num] ) + { return arr[0]; } + + template + inline ScalarType & LastElementOf( ScalarType (&arr)[num] ) + { return arr[num-1]; } + } + + namespace Element + { + template + inline void Swap( ScalarType &elementA, ScalarType &elementB, ScalarType &swapSpace ) + { swapSpace = elementA; elementA = elementB; elementB = swapSpace; } + + template + inline void Swap( ScalarType &elementA, ScalarType &elementB ) + { ScalarType swapSpace; Swap( elementA, elementB, swapSpace ); } + } + + namespace Value + { + using ::std::numeric_limits; + + template + inline ValueType Abs( const ValueType &value ) + { return value < 0 ? value * -1 : value; } + + template + inline ValueType Max( const ValueType &valueA, const ValueType &valueB ) + { return valueA > valueB ? valueA : valueB; } + + template + inline ValueType Min( const ValueType &valueA, const ValueType &valueB ) + { return valueA < valueB ? valueA : valueB; } + + template + inline ValueType Average( const ValueType &valueA, const ValueType &valueB ) + { return (valueA + valueB) * 0.5f; } + + template + inline ValueType AverageWithDelta( const ValueType &origin, const ValueType &delta ) + { return origin + (delta * 0.5f); } + + template + inline ValueType Radian( const ValueType °ree ) + { return degree * (3.1415926535897932384626433832795f / 180.0f); } + + template + inline ValueType Degree( const ValueType &radian ) + { return radian * (180.0f / 3.1415926535897932384626433832795f); } + + // SPECIALIZATIONS //!//!//!//!//!//!//!//!//!//!//!//!//!//! + + template<> inline char Average( const char &valueA, const char &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline unsigned char Average( const unsigned char &valueA, const unsigned char &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline int Average( const int &valueA, const int &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline unsigned int Average( const unsigned int &valueA, const unsigned int &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline long Average( const long &valueA, const long &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline unsigned long Average( const unsigned long &valueA, const unsigned long &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline long long Average( const long long &valueA, const long long &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline unsigned long long Average( const unsigned long long &valueA, const unsigned long long &valueB ) + { return (valueA + valueB) >> 1; } + + template<> inline char AverageWithDelta( const char &origin, const char &delta ) + { return origin + (delta >> 1); } + + template<> inline unsigned char AverageWithDelta( const unsigned char &origin, const unsigned char &delta ) + { return origin + (delta >> 1); } + + template<> inline int AverageWithDelta( const int &origin, const int &delta ) + { return origin + (delta >> 1); } + + template<> inline unsigned int AverageWithDelta( const unsigned int &origin, const unsigned int &delta ) + { return origin + (delta >> 1); } + + template<> inline long AverageWithDelta( const long &origin, const long &delta ) + { return origin + (delta >> 1); } + + template<> inline unsigned long AverageWithDelta( const unsigned long &origin, const unsigned long &delta ) + { return origin + (delta >> 1); } + + template<> inline long long AverageWithDelta( const long long &origin, const long long &delta ) + { return origin + (delta >> 1); } + + template<> inline unsigned long long AverageWithDelta( const unsigned long long &origin, const unsigned long long &delta ) + { return origin + (delta >> 1); } + } +} + +#include "Utilities-InlineImpl.h" + +#endif \ No newline at end of file From 6e71b6ac545348bad3d04cdfa6101eb1cd8862e3 Mon Sep 17 00:00:00 2001 From: dean11 Date: Thu, 28 Nov 2013 15:17:25 +0100 Subject: [PATCH 50/67] Fixed merging errors --- Code/Misc/Thread/IThreadObject.h | 37 ++++ Code/Misc/Thread/OysterMutex.cpp | 66 ++++++ Code/Misc/Thread/OysterMutex.h | 36 ++-- Code/Misc/Thread/OysterThread.h | 47 +++++ Code/Misc/Thread/OysterThread_Impl.cpp | 281 +++++++++++++++++++++++++ 5 files changed, 446 insertions(+), 21 deletions(-) create mode 100644 Code/Misc/Thread/IThreadObject.h create mode 100644 Code/Misc/Thread/OysterMutex.cpp create mode 100644 Code/Misc/Thread/OysterThread.h create mode 100644 Code/Misc/Thread/OysterThread_Impl.cpp diff --git a/Code/Misc/Thread/IThreadObject.h b/Code/Misc/Thread/IThreadObject.h new file mode 100644 index 00000000..b21c942e --- /dev/null +++ b/Code/Misc/Thread/IThreadObject.h @@ -0,0 +1,37 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#ifndef MISC_I_THREAD_OBJECT_H +#define MISC_I_THREAD_OBJECT_H + + + +namespace Oyster +{ + namespace Thread + { + /** + * Inherit this class to get threading compatibility. + */ + class IThreadObject + { + public: + /** + * Override this to get notified when the thread is started. + */ + virtual void ThreadEntry() { } + /** + * Override this to get notified when the thread is about to exit. + */ + virtual void ThreadExit() { } + /** + * This function is required to get threading working. + */ + virtual bool DoWork ( ) = 0; + }; + } +} + +#endif // !MISC_I_THREAD_OBJECT_H + diff --git a/Code/Misc/Thread/OysterMutex.cpp b/Code/Misc/Thread/OysterMutex.cpp new file mode 100644 index 00000000..089323ce --- /dev/null +++ b/Code/Misc/Thread/OysterMutex.cpp @@ -0,0 +1,66 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#include "OysterMutex.h" + +#include +#include +#include + + + +OysterMutex::OysterMutex() +{} + +OysterMutex::OysterMutex(bool initialOwnership) +{ + if(initialOwnership) + { + this->mutex.lock(); + this->id = std::this_thread::get_id(); + } +} +OysterMutex::~OysterMutex() +{ +} +void OysterMutex::LockMutex() +{ + if(std::this_thread::get_id() == this->id) return; + + this->mutex.lock(); + + this->id = std::this_thread::get_id(); +} +void OysterMutex::LockMutex(unsigned int msec) +{ + if(std::this_thread::get_id() == this->id) return; + + auto start = std::chrono::high_resolution_clock::now(); + auto end = start + std::chrono::milliseconds(msec); + + do + { + if(this->mutex.try_lock()) + { + this->mutex.lock(); + this->id = std::this_thread::get_id(); + return; + } + } while (std::chrono::high_resolution_clock::now() < end); + + this->mutex.lock(); +} +void OysterMutex::UnlockMutex() +{ + //Let the owner unlock + if(std::this_thread::get_id() != this->id) return; + + this->mutex.unlock(); + this->id = std::thread::id(); + +} +bool OysterMutex::IsTaken() +{ + return !this->mutex.try_lock(); +} \ No newline at end of file diff --git a/Code/Misc/Thread/OysterMutex.h b/Code/Misc/Thread/OysterMutex.h index d9f29d95..18282499 100644 --- a/Code/Misc/Thread/OysterMutex.h +++ b/Code/Misc/Thread/OysterMutex.h @@ -9,29 +9,23 @@ #include #include -namespace Oyster +class OysterMutex { - namespace Thread - { - class OysterMutex - { - public: - OysterMutex(); - OysterMutex(bool initialOwnership); - virtual~OysterMutex(); - void LockMutex(); - void LockMutex(unsigned int timeSpan); - void UnlockMutex(); - /** Returns true if mutex is taken */ - bool IsTaken(); +public: + OysterMutex(); + OysterMutex(bool initialOwnership); + virtual~OysterMutex(); + void LockMutex(); + void LockMutex(unsigned int timeSpan); + void UnlockMutex(); + /** Returns true if mutex is taken */ + bool IsTaken(); - private: - std::mutex mutex; - std::thread::id id; +private: + std::mutex mutex; + std::thread::id id; - OysterMutex(const OysterMutex&); - }; - } -} + OysterMutex(const OysterMutex&); +}; #endif // !MISC_OYSTER_MUTEX_H diff --git a/Code/Misc/Thread/OysterThread.h b/Code/Misc/Thread/OysterThread.h new file mode 100644 index 00000000..05a9f8ad --- /dev/null +++ b/Code/Misc/Thread/OysterThread.h @@ -0,0 +1,47 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#ifndef MISC_OYSTER_THREAD_H +#define MISC_OYSTER_THREAD_H + +#include "IThreadObject.h" +namespace Oyster +{ + namespace Thread + { + enum OYSTER_THREAD_ERROR + { + OYSTER_THREAD_ERROR_FAILED, + OYSTER_THREAD_ERROR_SUCCESS, + }; + + class OysterThread + { + private: + struct PrivateData; + PrivateData *privateData; + + public: + OysterThread(); + OysterThread(const OysterThread& original); + const OysterThread& operator=(const OysterThread& original); + virtual~OysterThread(); + + OYSTER_THREAD_ERROR Create(IThreadObject* worker, bool start); + OYSTER_THREAD_ERROR Start(); + void Stop(); + void Pause(); + void Pause(int mSec); + void Resume(); + OYSTER_THREAD_ERROR Reset(IThreadObject* worker = 0); + void Terminate(); + void Wait(); + void Wait(int mSec); + OYSTER_THREAD_ERROR Swap(const OysterThread* other); + bool IsActive(); + }; + } +} + +#endif // !MISC_OYSTER_THREAD_H diff --git a/Code/Misc/Thread/OysterThread_Impl.cpp b/Code/Misc/Thread/OysterThread_Impl.cpp new file mode 100644 index 00000000..46b889fe --- /dev/null +++ b/Code/Misc/Thread/OysterThread_Impl.cpp @@ -0,0 +1,281 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#include "OysterThread.h" +#include "OysterMutex.h" +#include "..\Utilities.h" +#include +#include +#include + +using namespace Oyster::Thread; +using namespace Utility::DynamicMemory::SmartPointer; + + +#pragma region Declerations + + struct ThreadData; + /** A typical Oyster thread function */ + typedef void (*ThreadFunction)(StdSmartPointer&); + + enum OYSTER_THREAD_STATE + { + OYSTER_THREAD_STATE_RESET, + OYSTER_THREAD_STATE_RUNNING, + OYSTER_THREAD_STATE_PAUSED, + OYSTER_THREAD_STATE_STOPED, + OYSTER_THREAD_STATE_DEAD, + }; + + + struct ThreadData + { + std::atomic state; // workerThread; // msec; // threadData; + + PrivateData() + :threadData(new ThreadData()) + { + threadData->owner = 0; + threadData->workerThread = 0; + threadData->callingThread; + threadData->state = OYSTER_THREAD_STATE_STOPED; + } + PrivateData(const PrivateData& o) + { + threadData = o.threadData; + } + ~PrivateData() + { + //@todo TODO: Make detatch avalible. + this->threadData->workerThread->detach(); + + this->threadData->owner = 0; + + this->threadData->state = OYSTER_THREAD_STATE_DEAD; + } + + }; + +#pragma endregion + + +int tempId = 0; +std::vector IDS; +static void ThreadingFunction(StdSmartPointer &origin) +{ + + bool shouldContinue; + StdSmartPointer w = origin; + +theBegining: + + while(w->state == OYSTER_THREAD_STATE_STOPED) + { + std::this_thread::yield(); + } + +// w->mutexLock.LockMutex(); + if(w->owner) + { + w->owner->ThreadEntry(); + } +// w->mutexLock.UnlockMutex(); + + while (w->state != OYSTER_THREAD_STATE_STOPED && w->state != OYSTER_THREAD_STATE_DEAD) + { +// w->mutexLock.LockMutex(); + { + if(w->owner) + { + shouldContinue = w->owner->DoWork(); + } + } +// w->mutexLock.UnlockMutex(); + + if(!shouldContinue) + { + goto theEnd; + } + if(w->state == OYSTER_THREAD_STATE_DEAD) + { + goto theEnd; + } + else if(w->state == OYSTER_THREAD_STATE_RESET) + { + goto theBegining; + } + else if(w->msec > 0) + { + std::this_thread::sleep_for(std::chrono::milliseconds(w->msec)); + } + + while (w->state == OYSTER_THREAD_STATE_PAUSED) + { + std::this_thread::yield(); + } + } + + if(w->state == OYSTER_THREAD_STATE_DEAD) + { + w->workerThread->detach(); + return; + } + +theEnd: + +// w->mutexLock.LockMutex(); + if(w->owner) + { + w->owner->ThreadExit(); + } +// w->mutexLock.UnlockMutex(); + + w->state = OYSTER_THREAD_STATE_DEAD; +} + +OysterThread::OysterThread() +{ + this->privateData = new PrivateData(); +} +OysterThread::OysterThread(const OysterThread& original) +{ + this->privateData = new PrivateData(*original.privateData); +} +const OysterThread& OysterThread::operator=(const OysterThread& original) +{ + return *this; +} +OysterThread::~OysterThread() +{ + delete this->privateData; + this->privateData = 0; +} + +OYSTER_THREAD_ERROR OysterThread::Create(IThreadObject* worker, bool start) +{ + if(!this->privateData) return OYSTER_THREAD_ERROR_FAILED; + if(this->privateData->threadData->workerThread) return OYSTER_THREAD_ERROR_FAILED; + + this->privateData->threadData->owner = worker; + + ThreadFunction fnc = ThreadingFunction; + + //Maby move this thread creation to a seperate Start() function because std::thread fires the thread when it is created. :( + this->privateData->threadData->workerThread = new std::thread(fnc, this->privateData->threadData); + + if(!this->privateData->threadData->workerThread) + return OYSTER_THREAD_ERROR_FAILED; + + if(start) + { + this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; + } + return OYSTER_THREAD_ERROR_SUCCESS; +} +OYSTER_THREAD_ERROR OysterThread::Start() +{ + if(!this->privateData->threadData->owner) + return OYSTER_THREAD_ERROR_FAILED; + if(!this->privateData->threadData->workerThread) + return OYSTER_THREAD_ERROR_FAILED; + if(this->privateData->threadData->state == OYSTER_THREAD_STATE_DEAD) + return OYSTER_THREAD_ERROR_FAILED; + + this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; + return OYSTER_THREAD_ERROR_SUCCESS; +} +void OysterThread::Stop() +{ + //this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_STOPED; + //this->privateData->threadData->mutexLock.UnlockMutex(); +} +void OysterThread::Pause() +{ + //this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_PAUSED; + //this->privateData->threadData->mutexLock.UnlockMutex(); +} +void OysterThread::Pause(int msec) +{ + + if(std::this_thread::get_id() == this->privateData->threadData->workerThread->get_id()) + { + this->privateData->threadData->msec = msec; + } + else + { + //this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_PAUSED; + this->privateData->threadData->msec = msec; + //this->privateData->threadData->mutexLock.UnlockMutex(); + } +} +void OysterThread::Resume() +{ +// this->privateData->threadData->mutexLock.LockMutex(); + this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; +// this->privateData->threadData->mutexLock.UnlockMutex(); +} +OYSTER_THREAD_ERROR OysterThread::Reset(IThreadObject* worker) +{ +// this->privateData->threadData->mutexLock.LockMutex(); + if(worker) + { + this->privateData->threadData->owner = worker; + } + this->privateData->threadData->callingThread = std::this_thread::get_id(); + this->privateData->threadData->msec = 0; +// this->privateData->threadData->mutexLock.UnlockMutex(); + + return OYSTER_THREAD_ERROR_SUCCESS; +} +void OysterThread::Terminate() +{ + this->privateData->threadData->state = OYSTER_THREAD_STATE_DEAD; +} +void OysterThread::Wait() +{ + if(this->privateData->threadData->state == OYSTER_THREAD_STATE_DEAD) + { + return; + } + + if(this->privateData->threadData->workerThread->get_id() == std::this_thread::get_id()) return; + + this->privateData->threadData->workerThread->join(); +} +void OysterThread::Wait(int msec) +{ + if(this->privateData->threadData->workerThread->get_id() == std::this_thread::get_id()) return; + + std::this_thread::sleep_for(std::chrono::milliseconds(msec)); +} +OYSTER_THREAD_ERROR OysterThread::Swap(const OysterThread* other) +{ + this->privateData->threadData->workerThread->swap(*other->privateData->threadData->workerThread); + return OYSTER_THREAD_ERROR_SUCCESS; +} +bool OysterThread::IsActive() +{ + if (this->privateData->threadData->state == OYSTER_THREAD_STATE_RUNNING) + return true; + + return false; +} + From 0785e54dfd15cdd743642932abc726b5b305c464 Mon Sep 17 00:00:00 2001 From: dean11 Date: Thu, 28 Nov 2013 15:19:52 +0100 Subject: [PATCH 51/67] Removed .orig files after merge --- .../Resource/Loaders/CustomLoader.cpp.orig | 65 ---- Code/Misc/Resource/OResourceHandler.cpp.orig | 258 ------------- Code/Misc/Resource/OysterResource.h.orig | 164 --------- Code/Misc/Thread/OysterMutex.cpp.orig | 67 ---- Code/Misc/Thread/OysterMutex.h.orig | 37 -- Code/Misc/Thread/OysterThread.h.orig | 47 --- Code/Misc/Thread/OysterThread_Impl.cpp.orig | 281 -------------- Code/Misc/Utilities-InlineImpl.h.orig | 315 ---------------- Code/Misc/Utilities.h.orig | 347 ------------------ 9 files changed, 1581 deletions(-) delete mode 100644 Code/Misc/Resource/Loaders/CustomLoader.cpp.orig delete mode 100644 Code/Misc/Resource/OResourceHandler.cpp.orig delete mode 100644 Code/Misc/Resource/OysterResource.h.orig delete mode 100644 Code/Misc/Thread/OysterMutex.cpp.orig delete mode 100644 Code/Misc/Thread/OysterMutex.h.orig delete mode 100644 Code/Misc/Thread/OysterThread.h.orig delete mode 100644 Code/Misc/Thread/OysterThread_Impl.cpp.orig delete mode 100644 Code/Misc/Utilities-InlineImpl.h.orig delete mode 100644 Code/Misc/Utilities.h.orig diff --git a/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig b/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig deleted file mode 100644 index 15dea599..00000000 --- a/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig +++ /dev/null @@ -1,65 +0,0 @@ - -#include "..\OResource.h" -#include "..\..\Utilities.h" - -#include - -using namespace Oyster::Resource; - - -OResource* OResource::CustomLoader(const wchar_t filename[], CustomLoadFunction fnc) -{ -<<<<<<< HEAD - const CustomData &data = fnc(); -======= - CustomData data; - memset(&data, 0, sizeof(CustomData)); - - fnc(filename, data); - - if(!data.loadedData) - { - return 0; - } - if(!data.resourceUnloadFnc) - { - return 0; - } - /** For some wierd reason that i don't understand when trying to send data.loadedData directly as a - * parameter to OResource constructor, the value is changed when it arrives in the constructor. - * Doing it like this, storing in a temporary variable, the value stays correct. (What the fuck! I must be overloking something...)*/ - //OHRESOURCE temp = data.loadedData; - OResource *resource = new OResource(data.loadedData, ResourceType_UNKNOWN, 0, 0, filename); ->>>>>>> origin/MiscBranch - - resource->customData = new CustomResourceData(); - resource->customData->unloadingFunction = data.resourceUnloadFnc; - resource->customData->loadingFunction = fnc; - - return resource; -} -void OResource::CustomUnloader() -{ - this->customData->unloadingFunction(this->resourceData); -} -OResource* OResource::CustomReloader() -{ - CustomUnloader(); - -<<<<<<< HEAD - const CustomData &data = this->customData->loadingFunction(); -======= - CustomData data; - memset(&data, 0, sizeof(CustomData)); - - this->customData->loadingFunction(this->resourceFilename.c_str(), data); ->>>>>>> origin/MiscBranch - this->resourceData = (OHRESOURCE)data.loadedData; - - if(data.resourceUnloadFnc) - { - this->customData->unloadingFunction = data.resourceUnloadFnc; - } - return this; -} - diff --git a/Code/Misc/Resource/OResourceHandler.cpp.orig b/Code/Misc/Resource/OResourceHandler.cpp.orig deleted file mode 100644 index 923ab706..00000000 --- a/Code/Misc/Resource/OResourceHandler.cpp.orig +++ /dev/null @@ -1,258 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// - - -#include "OysterResource.h" -#include "OResource.h" -#include -#include - -using namespace Oyster::Resource; - -class ResourcePrivate -{ -public: - - std::map resources; - - OResource* FindResource(const OHRESOURCE& h) const; - OResource* FindResource(const wchar_t c[]) const; - void SaveResource(OResource* r, bool addNew = true); - -} resourcePrivate; - - -OHRESOURCE OysterResource::LoadResource(const wchar_t* filename, ResourceType type, int customID, bool force) -{ - if(!filename) return 0; - - OResource *resourceData = resourcePrivate.FindResource(filename); - - if(resourceData) - { - if(force) - { - return OysterResource::ReloadResource(filename); - } - else - { - //Add new reference - resourcePrivate.SaveResource(resourceData, false); - return resourceData->GetResourceHandle(); - } - } - else - { - resourceData = OResource::Load(filename, type); - if(resourceData) - { - resourceData->SetResourceID(customID); - resourcePrivate.SaveResource(resourceData); - } - } - - return resourceData->GetResourceHandle(); -} -OHRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunction loadFnc, int customId, bool force) -{ - if(!filename) - { - return 0; - } - if(!loadFnc) - { - return 0; - } - - OResource *resourceData = resourcePrivate.FindResource(filename); - if(resourceData) - { - if(force) - { - return OysterResource::ReloadResource(filename); - } - else - { - //Add new reference - resourcePrivate.SaveResource(resourceData, false); - return resourceData->GetResourceHandle(); - } - } - else - { - resourceData = OResource::Load(filename, loadFnc); - if(resourceData) - { - resourceData->SetResourceID(customId); - resourcePrivate.SaveResource(resourceData); - } - } -<<<<<<< HEAD - - resourceData = OResource::Load(filename, loadFnc); - - if(!resourceData) return 0; - - if(resourceData) resourceData->SetResourceID(CustomId); - resourcePrivate.SaveResource(resourceData); -======= ->>>>>>> origin/MiscBranch - - return (OHRESOURCE)resourceData->GetResourceHandle(); -} - -OHRESOURCE OysterResource::ReloadResource(const wchar_t filename[]) -{ - OResource *resourceData = resourcePrivate.FindResource(filename); - if(!resourceData) return 0; //The resource has not been loaded - - return OResource::Reload(resourceData)->GetResourceHandle(); -} -OHRESOURCE OysterResource::ReloadResource(OHRESOURCE resource) -{ - OResource *resourceData = resourcePrivate.FindResource(resource); - if(!resourceData) return 0; //The resource has not been loaded - - return OResource::Reload(resourceData)->GetResourceHandle(); -} - -void OysterResource::Clean() -{ - auto i = resourcePrivate.resources.begin(); - auto last = resourcePrivate.resources.end(); - - for (i; i != last; i++) - { - //Remove all the references - while (!OResource::Release(i->second)); - - const wchar_t* temp = i->second->GetResourceFilename(); - delete resourcePrivate.resources[temp]; - resourcePrivate.resources.erase(temp); - - } -} -void OysterResource::ReleaseResource(const OHRESOURCE& resourceData) -{ - OResource* t = resourcePrivate.FindResource(resourceData); - if(t) - { - if(OResource::Release(t)) - { - const wchar_t* temp = t->GetResourceFilename(); - delete resourcePrivate.resources[temp]; - resourcePrivate.resources.erase(temp); - } - } -} -void OysterResource::ReleaseResource(const wchar_t filename[]) -{ - OResource* t = resourcePrivate.FindResource(filename); - if(t) - { - if(OResource::Release(t)) - { - const wchar_t* temp = t->GetResourceFilename(); - delete resourcePrivate.resources[temp]; - resourcePrivate.resources.erase(temp); - } - } -} - -void OysterResource::SetResourceId (const OHRESOURCE& resourceData, unsigned int id) -{ - OResource* t = resourcePrivate.FindResource(resourceData); - - if(t) t->SetResourceID(id); -} -void OysterResource::SetResourceId(const wchar_t c[], unsigned int id) -{ - OResource* t = resourcePrivate.FindResource(c); - - if(t) t->SetResourceID(id); -} -ResourceType OysterResource::GetResourceType (const OHRESOURCE& resourceData) -{ - OResource* t = resourcePrivate.FindResource(resourceData); - - if(t) return t->GetResourceType(); - - return ResourceType_INVALID; -} -ResourceType OysterResource::GetResourceType (const wchar_t c[]) -{ - OResource* t = resourcePrivate.FindResource(c); - - if(t) return t->GetResourceType(); - - return ResourceType_INVALID; -} -const wchar_t* OysterResource::GetResourceFilename (const OHRESOURCE& resourceData) -{ - OResource* t = resourcePrivate.FindResource(resourceData); - - if(t) return t->GetResourceFilename(); - - return 0; -} -OHRESOURCE OysterResource::GetResourceHandle(const wchar_t filename[]) -{ - OResource* t = resourcePrivate.FindResource(filename); - - if(t) return t->GetResourceHandle(); - - return 0; -} -int OysterResource::GetResourceId (const OHRESOURCE& resourceData) -{ - OResource* t = resourcePrivate.FindResource(resourceData); - - if(t) return t->GetResourceID(); - - return -1; -} -int OysterResource::GetResourceId(const wchar_t c[]) -{ - OResource* t = resourcePrivate.FindResource(c); - - if(t) return t->GetResourceID(); - - return -1; -} - - -OResource* ResourcePrivate::FindResource(const OHRESOURCE& h) const -{ - for (auto i = this->resources.begin(); i != this->resources.end() ; i++) - { - if(i->second->GetResourceHandle() == h) - { - return i->second; - } - } - return 0; -} -OResource* ResourcePrivate::FindResource(const wchar_t c[]) const -{ - std::wstring temp = c; - auto t = this->resources.find(c); - if(t == this->resources.end()) return 0; - - return t->second; -} -void ResourcePrivate::SaveResource( OResource* r, bool addNew ) -{ - if(!r) return; - - if(addNew) - { - this->resources[r->GetResourceFilename()] = r; - } - - r->resourceRef.Incref(); -} - - - - diff --git a/Code/Misc/Resource/OysterResource.h.orig b/Code/Misc/Resource/OysterResource.h.orig deleted file mode 100644 index 906b77fb..00000000 --- a/Code/Misc/Resource/OysterResource.h.orig +++ /dev/null @@ -1,164 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// - -#ifndef MISC_OYSTER_RESOURCE_H -#define MISC_OYSTER_RESOURCE_H - - -namespace Oyster -{ - namespace Resource - { - struct CustomData; - /** A Resource handle representing various resources */ -<<<<<<< HEAD - typedef unsigned long OHRESOURCE; - typedef void(*CustomUnloadFunction)(void*); - typedef const CustomData&(*CustomLoadFunction)(); -======= - typedef void* OHRESOURCE; - /** Typedef on a fuction required for custom unloading */ - typedef void(*CustomUnloadFunction)(void* loadedData); - /** Typedef on a fuction required for custom loading */ - typedef void(*CustomLoadFunction)(const wchar_t filename[], CustomData& outData); ->>>>>>> origin/MiscBranch - - /** An enum class representing all avalible resources that is supported. */ - enum ResourceType - { - //Byte - ResourceType_Byte_Raw, /**< Handle can be interpeted as char[] or char* */ - ResourceType_Byte_ANSI, /**< Handle can be interpeted as char[] or char* */ - ResourceType_Byte_UTF8, /**< Handle can be interpeted as char[] or char* */ - ResourceType_Byte_UNICODE, /**< Handle can be interpeted as char[] or char* */ - ResourceType_Byte_UTF16LE, /**< Handle can be interpeted as char[] or char* */ - - ResourceType_COUNT, /**< Handle can be interpeted as ? */ - - ResourceType_UNKNOWN = -1, /**< Handle can be interpeted as void* */ - ResourceType_INVALID = -2, /**< Invalid or non existing resource */ - }; - - /** A struct to fill when doing a custom resource Load. */ - struct CustomData - { - void* loadedData; // -#include -#include - -using namespace Oyster::Thread; - - -OysterMutex::OysterMutex() -{} - -OysterMutex::OysterMutex(bool initialOwnership) -{ - if(initialOwnership) - { - this->mutex.lock(); - this->id = std::this_thread::get_id(); - } -} -OysterMutex::~OysterMutex() -{ -} -void OysterMutex::LockMutex() -{ - if(std::this_thread::get_id() == this->id) return; - - this->mutex.lock(); - - this->id = std::this_thread::get_id(); -} -void OysterMutex::LockMutex(unsigned int msec) -{ - if(std::this_thread::get_id() == this->id) return; - - auto start = std::chrono::high_resolution_clock::now(); - auto end = start + std::chrono::milliseconds(msec); - - do - { - if(this->mutex.try_lock()) - { - this->mutex.lock(); - this->id = std::this_thread::get_id(); - return; - } - } while (std::chrono::high_resolution_clock::now() < end); - - this->mutex.lock(); -} -void OysterMutex::UnlockMutex() -{ - //Let the owner unlock - if(std::this_thread::get_id() != this->id) return; - - this->mutex.unlock(); - this->id = std::thread::id(); - -} -bool OysterMutex::IsTaken() -{ - return !this->mutex.try_lock(); -} \ No newline at end of file diff --git a/Code/Misc/Thread/OysterMutex.h.orig b/Code/Misc/Thread/OysterMutex.h.orig deleted file mode 100644 index d9f29d95..00000000 --- a/Code/Misc/Thread/OysterMutex.h.orig +++ /dev/null @@ -1,37 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// - -#ifndef MISC_OYSTER_MUTEX_H -#define MISC_OYSTER_MUTEX_H - -#include -#include -#include - -namespace Oyster -{ - namespace Thread - { - class OysterMutex - { - public: - OysterMutex(); - OysterMutex(bool initialOwnership); - virtual~OysterMutex(); - void LockMutex(); - void LockMutex(unsigned int timeSpan); - void UnlockMutex(); - /** Returns true if mutex is taken */ - bool IsTaken(); - - private: - std::mutex mutex; - std::thread::id id; - - OysterMutex(const OysterMutex&); - }; - } -} - -#endif // !MISC_OYSTER_MUTEX_H diff --git a/Code/Misc/Thread/OysterThread.h.orig b/Code/Misc/Thread/OysterThread.h.orig deleted file mode 100644 index 05a9f8ad..00000000 --- a/Code/Misc/Thread/OysterThread.h.orig +++ /dev/null @@ -1,47 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// - -#ifndef MISC_OYSTER_THREAD_H -#define MISC_OYSTER_THREAD_H - -#include "IThreadObject.h" -namespace Oyster -{ - namespace Thread - { - enum OYSTER_THREAD_ERROR - { - OYSTER_THREAD_ERROR_FAILED, - OYSTER_THREAD_ERROR_SUCCESS, - }; - - class OysterThread - { - private: - struct PrivateData; - PrivateData *privateData; - - public: - OysterThread(); - OysterThread(const OysterThread& original); - const OysterThread& operator=(const OysterThread& original); - virtual~OysterThread(); - - OYSTER_THREAD_ERROR Create(IThreadObject* worker, bool start); - OYSTER_THREAD_ERROR Start(); - void Stop(); - void Pause(); - void Pause(int mSec); - void Resume(); - OYSTER_THREAD_ERROR Reset(IThreadObject* worker = 0); - void Terminate(); - void Wait(); - void Wait(int mSec); - OYSTER_THREAD_ERROR Swap(const OysterThread* other); - bool IsActive(); - }; - } -} - -#endif // !MISC_OYSTER_THREAD_H diff --git a/Code/Misc/Thread/OysterThread_Impl.cpp.orig b/Code/Misc/Thread/OysterThread_Impl.cpp.orig deleted file mode 100644 index 46b889fe..00000000 --- a/Code/Misc/Thread/OysterThread_Impl.cpp.orig +++ /dev/null @@ -1,281 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Created by [Dennis Andersen] [2013] -///////////////////////////////////////////////////////////////////// - -#include "OysterThread.h" -#include "OysterMutex.h" -#include "..\Utilities.h" -#include -#include -#include - -using namespace Oyster::Thread; -using namespace Utility::DynamicMemory::SmartPointer; - - -#pragma region Declerations - - struct ThreadData; - /** A typical Oyster thread function */ - typedef void (*ThreadFunction)(StdSmartPointer&); - - enum OYSTER_THREAD_STATE - { - OYSTER_THREAD_STATE_RESET, - OYSTER_THREAD_STATE_RUNNING, - OYSTER_THREAD_STATE_PAUSED, - OYSTER_THREAD_STATE_STOPED, - OYSTER_THREAD_STATE_DEAD, - }; - - - struct ThreadData - { - std::atomic state; // workerThread; // msec; // threadData; - - PrivateData() - :threadData(new ThreadData()) - { - threadData->owner = 0; - threadData->workerThread = 0; - threadData->callingThread; - threadData->state = OYSTER_THREAD_STATE_STOPED; - } - PrivateData(const PrivateData& o) - { - threadData = o.threadData; - } - ~PrivateData() - { - //@todo TODO: Make detatch avalible. - this->threadData->workerThread->detach(); - - this->threadData->owner = 0; - - this->threadData->state = OYSTER_THREAD_STATE_DEAD; - } - - }; - -#pragma endregion - - -int tempId = 0; -std::vector IDS; -static void ThreadingFunction(StdSmartPointer &origin) -{ - - bool shouldContinue; - StdSmartPointer w = origin; - -theBegining: - - while(w->state == OYSTER_THREAD_STATE_STOPED) - { - std::this_thread::yield(); - } - -// w->mutexLock.LockMutex(); - if(w->owner) - { - w->owner->ThreadEntry(); - } -// w->mutexLock.UnlockMutex(); - - while (w->state != OYSTER_THREAD_STATE_STOPED && w->state != OYSTER_THREAD_STATE_DEAD) - { -// w->mutexLock.LockMutex(); - { - if(w->owner) - { - shouldContinue = w->owner->DoWork(); - } - } -// w->mutexLock.UnlockMutex(); - - if(!shouldContinue) - { - goto theEnd; - } - if(w->state == OYSTER_THREAD_STATE_DEAD) - { - goto theEnd; - } - else if(w->state == OYSTER_THREAD_STATE_RESET) - { - goto theBegining; - } - else if(w->msec > 0) - { - std::this_thread::sleep_for(std::chrono::milliseconds(w->msec)); - } - - while (w->state == OYSTER_THREAD_STATE_PAUSED) - { - std::this_thread::yield(); - } - } - - if(w->state == OYSTER_THREAD_STATE_DEAD) - { - w->workerThread->detach(); - return; - } - -theEnd: - -// w->mutexLock.LockMutex(); - if(w->owner) - { - w->owner->ThreadExit(); - } -// w->mutexLock.UnlockMutex(); - - w->state = OYSTER_THREAD_STATE_DEAD; -} - -OysterThread::OysterThread() -{ - this->privateData = new PrivateData(); -} -OysterThread::OysterThread(const OysterThread& original) -{ - this->privateData = new PrivateData(*original.privateData); -} -const OysterThread& OysterThread::operator=(const OysterThread& original) -{ - return *this; -} -OysterThread::~OysterThread() -{ - delete this->privateData; - this->privateData = 0; -} - -OYSTER_THREAD_ERROR OysterThread::Create(IThreadObject* worker, bool start) -{ - if(!this->privateData) return OYSTER_THREAD_ERROR_FAILED; - if(this->privateData->threadData->workerThread) return OYSTER_THREAD_ERROR_FAILED; - - this->privateData->threadData->owner = worker; - - ThreadFunction fnc = ThreadingFunction; - - //Maby move this thread creation to a seperate Start() function because std::thread fires the thread when it is created. :( - this->privateData->threadData->workerThread = new std::thread(fnc, this->privateData->threadData); - - if(!this->privateData->threadData->workerThread) - return OYSTER_THREAD_ERROR_FAILED; - - if(start) - { - this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; - } - return OYSTER_THREAD_ERROR_SUCCESS; -} -OYSTER_THREAD_ERROR OysterThread::Start() -{ - if(!this->privateData->threadData->owner) - return OYSTER_THREAD_ERROR_FAILED; - if(!this->privateData->threadData->workerThread) - return OYSTER_THREAD_ERROR_FAILED; - if(this->privateData->threadData->state == OYSTER_THREAD_STATE_DEAD) - return OYSTER_THREAD_ERROR_FAILED; - - this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; - return OYSTER_THREAD_ERROR_SUCCESS; -} -void OysterThread::Stop() -{ - //this->privateData->threadData->mutexLock.LockMutex(); - this->privateData->threadData->state = OYSTER_THREAD_STATE_STOPED; - //this->privateData->threadData->mutexLock.UnlockMutex(); -} -void OysterThread::Pause() -{ - //this->privateData->threadData->mutexLock.LockMutex(); - this->privateData->threadData->state = OYSTER_THREAD_STATE_PAUSED; - //this->privateData->threadData->mutexLock.UnlockMutex(); -} -void OysterThread::Pause(int msec) -{ - - if(std::this_thread::get_id() == this->privateData->threadData->workerThread->get_id()) - { - this->privateData->threadData->msec = msec; - } - else - { - //this->privateData->threadData->mutexLock.LockMutex(); - this->privateData->threadData->state = OYSTER_THREAD_STATE_PAUSED; - this->privateData->threadData->msec = msec; - //this->privateData->threadData->mutexLock.UnlockMutex(); - } -} -void OysterThread::Resume() -{ -// this->privateData->threadData->mutexLock.LockMutex(); - this->privateData->threadData->state = OYSTER_THREAD_STATE_RUNNING; -// this->privateData->threadData->mutexLock.UnlockMutex(); -} -OYSTER_THREAD_ERROR OysterThread::Reset(IThreadObject* worker) -{ -// this->privateData->threadData->mutexLock.LockMutex(); - if(worker) - { - this->privateData->threadData->owner = worker; - } - this->privateData->threadData->callingThread = std::this_thread::get_id(); - this->privateData->threadData->msec = 0; -// this->privateData->threadData->mutexLock.UnlockMutex(); - - return OYSTER_THREAD_ERROR_SUCCESS; -} -void OysterThread::Terminate() -{ - this->privateData->threadData->state = OYSTER_THREAD_STATE_DEAD; -} -void OysterThread::Wait() -{ - if(this->privateData->threadData->state == OYSTER_THREAD_STATE_DEAD) - { - return; - } - - if(this->privateData->threadData->workerThread->get_id() == std::this_thread::get_id()) return; - - this->privateData->threadData->workerThread->join(); -} -void OysterThread::Wait(int msec) -{ - if(this->privateData->threadData->workerThread->get_id() == std::this_thread::get_id()) return; - - std::this_thread::sleep_for(std::chrono::milliseconds(msec)); -} -OYSTER_THREAD_ERROR OysterThread::Swap(const OysterThread* other) -{ - this->privateData->threadData->workerThread->swap(*other->privateData->threadData->workerThread); - return OYSTER_THREAD_ERROR_SUCCESS; -} -bool OysterThread::IsActive() -{ - if (this->privateData->threadData->state == OYSTER_THREAD_STATE_RUNNING) - return true; - - return false; -} - diff --git a/Code/Misc/Utilities-InlineImpl.h.orig b/Code/Misc/Utilities-InlineImpl.h.orig deleted file mode 100644 index 107ea730..00000000 --- a/Code/Misc/Utilities-InlineImpl.h.orig +++ /dev/null @@ -1,315 +0,0 @@ -///////////////////////////////////////////////////////////////////// -// Inline and template implementations for -// the Utility Collection of Miscellanious Handy Functions -// © Dan Andersson 2013 -///////////////////////////////////////////////////////////////////// - -#ifndef UTILITIES_INLINE_IMPL_H -#define UTILITIES_INLINE_IMPL_H - -#include "Utilities.h" - -namespace Utility -{ - namespace DynamicMemory - { - template - inline void SafeDeleteInstance( Type *dynamicInstance ) - { - if( dynamicInstance ) - { - delete dynamicInstance; - } - } - - template - void SafeDeleteArray( Type dynamicArray[] ) - { - if( dynamicArray ) - { - delete [] dynamicArray; - } - } - - template - UniquePointer::UniquePointer( Type *assignedInstance ) - { - this->ownedInstance = assignedInstance; - } - - template - UniquePointer::UniquePointer( const UniquePointer &donor ) - { - this->ownedInstance = donor.ownedInstance; - donor.ownedInstance = NULL; - - } - - template - UniquePointer::~UniquePointer() - { - SafeDeleteInstance( this->ownedInstance ); - } - - template - UniquePointer & UniquePointer::operator = ( Type *assignedInstance ) - { - SafeDeleteInstance( this->ownedInstance ); - this->ownedInstance = assignedInstance; - return *this; - } - - template - UniquePointer & UniquePointer::operator = ( const UniquePointer &donor ) - { - SafeDeleteInstance( this->ownedInstance ); - this->ownedInstance = donor.ownedInstance; - donor.ownedInstance = NULL; - return *this; - } - - template - UniquePointer::operator Type* () - { - return this->ownedInstance; - } - - template - UniquePointer::operator const Type* () const - { - return this->ownedInstance; - } - - template - Type * UniquePointer::operator -> () - { - return this->ownedInstance; - } - - template - const Type * UniquePointer::operator -> () const - { - return this->ownedInstance; - } - - template - UniquePointer::operator bool() const - { - return this->ownedInstance != NULL; - } - - template - bool UniquePointer::operator == ( Type *stray ) const - { - return this->ownedInstance == stray; - } - - template - bool UniquePointer::operator != ( Type *stray ) const - { - return this->ownedInstance != stray; - } - - template - Type* UniquePointer::Release() - { - Type *copy = this->ownedInstance; - this->ownedInstance = NULL; - return copy; - } - - template - inline bool UniquePointer::HaveOwnership() const - { - return this->operator bool(); - } - - template - UniqueArray::UniqueArray( Type assignedArray[] ) - { - this->ownedArray = assignedArray; - } - - template - UniqueArray::UniqueArray( const UniqueArray &donor ) - { - this->ownedArray = donor.ownedArray; - donor.ownedArray = NULL; - - } - - template - UniqueArray::~UniqueArray() - { - SafeDeleteArray( this->ownedArray ); - } - - template - UniqueArray & UniqueArray::operator = ( Type assignedArray[] ) - { - SafeDeleteArray( this->ownedArray ); - this->ownedArray = assignedArray; - } - - template - UniqueArray & UniqueArray::operator = ( const UniqueArray &donor ) - { - SafeDeleteArray( this->ownedArray ); - this->ownedArray = donor.ownedInstance; - donor.owned = NULL; - } - - template template - Type & UniqueArray::operator [] ( Index i ) - { - return this->ownedArray[i]; - } - - template template - const Type & UniqueArray::operator [] ( Index i ) const - { - return this->ownedArray[i]; - } - - template - UniqueArray::operator bool () const - { - return this->ownedArray != NULL; - } - - template - bool UniqueArray::operator == ( Type *stray ) const - { - return this->ownedArray == stray; - } - - template - bool UniqueArray::operator != ( Type *stray ) const - { - return this->ownedArray != stray; - } - - template - Type* UniqueArray::Release() - { - Type *copy = this->ownedArray; - this->ownedArray = NULL; - return copy; - } - - template - inline bool UniqueArray::HaveOwnership() const - { - return this->operator bool(); - } -<<<<<<< HEAD -======= - - namespace SmartPointer - { - template void StdSmartPointer::Destroy() - { - delete this->_rc; - this->_rc = NULL; - delete this->_ptr; - this->_ptr = NULL; - } - template StdSmartPointer::StdSmartPointer() - :_rc(0), _ptr(0) - { } - template StdSmartPointer::StdSmartPointer(T* p) - :_ptr(p) - { - this->_rc = new ReferenceCount(); - this->_rc->Incref(); - } - template StdSmartPointer::StdSmartPointer(const StdSmartPointer& d) - :_ptr(d._ptr), _rc(d._rc) - { - if(this->_rc) - this->_rc->Incref(); - } - template StdSmartPointer::~StdSmartPointer() - { - if (this->_rc && this->_rc->Decref() == 0) - { - Destroy(); - } - } - template StdSmartPointer& StdSmartPointer::operator= (const StdSmartPointer& p) - { - if (this != &p) - { - //Last to go? - if(this->_rc && this->_rc->Decref() == 0) - { - //Call child specific - Destroy(); - } - - this->_ptr = p._ptr; - this->_rc = p._rc; - this->_rc->Incref(); - } - return *this; - } - template StdSmartPointer& StdSmartPointer::operator= (T* p) - { - if (this->_ptr != p) - { - //Last to go? - if(this->_rc) - { - if(this->_rc->Decref() == 0) - { - //Call child specific - Destroy(); - this->_rc = new ReferenceCount(); - } - } - else - this->_rc = new ReferenceCount(); - - this->_ptr = p; - this->_rc->Incref(); - } - return *this; - } - template inline bool StdSmartPointer::operator== (const StdSmartPointer& d) - { - return d._ptr == this->_ptr; - } - template inline bool StdSmartPointer::operator== (const T& p) - { - return &p == this->_ptr; - } - template inline T& StdSmartPointer::operator* () - { - return *this->_ptr; - } - template inline T* StdSmartPointer::operator-> () - { - return this->_ptr; - } - template inline StdSmartPointer::operator T* () - { - return this->_ptr; - } - template inline StdSmartPointer::operator bool() - { - return (this->_ptr != 0); - } - template inline T* StdSmartPointer::Get() - { - return this->_ptr; - } - template inline bool StdSmartPointer::IsValid() - { - return (this->_ptr != NULL) ? true : false; - } - } ->>>>>>> origin/MiscBranch - } -} - -#endif \ No newline at end of file diff --git a/Code/Misc/Utilities.h.orig b/Code/Misc/Utilities.h.orig deleted file mode 100644 index 55c4820f..00000000 --- a/Code/Misc/Utilities.h.orig +++ /dev/null @@ -1,347 +0,0 @@ -//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! -// Utility Collection of Miscellanious Handy Functions -// © Dan Andersson 2013 -//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! - -#ifndef UTILITIES_H -#define UTILITIES_H - -#include -#include -#include -#include -#include -#include - -namespace Utility -{ - namespace DynamicMemory - { - //! If dynamicInstance is not NULL, then delete - template void SafeDeleteInstance( Type *dynamicInstance ); - - //! If dynamicArray is not NULL, then delete [] - template void SafeDeleteArray( Type dynamicArray[] ); - - //! Wrapper to safely transfer dynamic ownership/responsibility - template struct UniquePointer - { - public: - //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. - //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. - UniquePointer( Type *assignedInstance = NULL ); - - //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. - //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. - UniquePointer( const UniquePointer &donor ); - - //! Will auto delete assigned dynamic instance. - ~UniquePointer(); - - //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. - //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. - UniquePointer & operator = ( Type *assignedInstance ); - - //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. - //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. - UniquePointer & operator = ( const UniquePointer &donor ); - - //! Access the assigned dynamic instance. Will crash if nothing there - operator Type* (); - - //! Access the assigned dynamic instance. Will crash if nothing there - operator const Type* () const; - - //! Access members of the assigned dynamic instance. Will crash if nothing there - Type * operator -> (); - - //! Access members of the assigned dynamic instance. Will crash if nothing there - const Type * operator -> () const; - - //! If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. - operator bool () const; - - //! @return true if this ownedInstance matches with stray - bool operator == ( Type *stray ) const; - - //! @return false if this ownedInstance matches with stray - bool operator != ( Type *stray ) const; - - //! This UniquePointer drops all claims of ownership/responsibility and returns the dynamic instance. Now it is your responsibility to delete. - Type* Release(); - - //! (inline) If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. - bool HaveOwnership() const; - - private: - mutable Type *ownedInstance; - }; - - template - struct UniqueArray - { //! Wrapper to safely transfer dynamic ownership/responsibility - public: - //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. - //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. - UniqueArray( Type assignedArray[] = NULL ); - - //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. - //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. - UniqueArray( const UniqueArray &donor ); - - //! Will auto delete assigned dynamic array. - ~UniqueArray(); - - //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. - //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. - UniqueArray & operator = ( Type assignedArray[] ); - - //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. - //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. - UniqueArray & operator = ( const UniqueArray &donor ); - - //! Accesses the instance at index i of this UniqeArray's owned dynamic array. - //! Will crash if out-of-bound or there is no assigned array. - template Type & operator [] ( Index i ); - - //! Accesses the instance at index i of this UniqeArray's owned dynamic array. - //! Will crash if out-of-bound or there is no assigned array. - template const Type & operator [] ( Index i ) const; - - //! If true, this UniqueArray have a current ownership/responsibility of a dynamic instance. - operator bool () const; - - //! @return true if this ownedInstance matches with stray - bool operator == ( Type *stray ) const; - - //! @return false if this ownedInstance matches with stray - bool operator != ( Type *stray ) const; - - //! This UniqueArray drops all claims of ownership/responsibility and returns the dynamic array. Now it is your responsibility to delete. - Type* Release(); - - //! (inline) If true, this UniqueArray have a current ownership/responsibility of a dynamic array. - bool HaveOwnership() const; - - private: - mutable Type *ownedArray; - }; - - struct RefCount - { - private: - std::atomic count; - - public: -<<<<<<< HEAD - RefCount() :count(0) { } - RefCount(const RefCount& o) { count = o.count; } - const RefCount& operator=(const RefCount& o) { count = o.count; return *this;} - void Incref() { this->count++; } - void Incref(int c) { this->count += c; } - int Decref() { return --this->count;} - void Reset() { this->count = 0; } - }; -======= - ReferenceCount() :count(0) { } - ReferenceCount(const ReferenceCount& o) { count.store(o.count); } - inline const ReferenceCount& operator=(const ReferenceCount& o) { count.store(o.count); return *this;} - inline void Incref() { this->count++; } - inline void Incref(int c) { this->count += c; } - inline int Decref() { return --this->count;} - inline void Reset() { this->count = 0; } - }; - - namespace SmartPointer - { - //! Smart pointer for a regular object. - /** - * Regular objects, objects that is deleted normaly (ie not COM objects, or array pointers) - * can use this class to easy the use of dynamic memory - */ - template - struct StdSmartPointer - { - private: - ReferenceCount *_rc; - T *_ptr; - - /** Destroys the pointer and returns the memory allocated. */ - void Destroy(); - - public: - StdSmartPointer(); - StdSmartPointer(T* p); - StdSmartPointer(const StdSmartPointer& d); - virtual~StdSmartPointer(); - StdSmartPointer& operator= (const StdSmartPointer& p); - StdSmartPointer& operator= (T* p); - bool operator== (const StdSmartPointer& d); - bool operator== (const T& p); - T& operator* (); - T* operator-> (); - operator T* (); - operator bool(); - - /** - * Returns the connected pointer */ - T* Get(); - - /** Checks if the pointer is valid (not NULL) - Returns true for valid, else false. */ - bool IsValid(); - }; - } - - ->>>>>>> origin/MiscBranch - } - - namespace String - { - // string - - ::std::vector<::std::string> & Split( ::std::vector<::std::string> &output, const ::std::string &str, char delim, ::std::string::size_type offset = 0 ); - ::std::vector<::std::string> & Split( ::std::vector<::std::string> &output, const ::std::string &str, const ::std::string &delim, ::std::string::size_type offset = 0 ); - ::std::vector<::std::string> & Split( ::std::vector<::std::string> &output, const ::std::string &str, const ::std::vector<::std::string> &delim, ::std::string::size_type offset = 0 ); - ::std::string Trim( const ::std::string &str ); - ::std::string & ToLowerCase( ::std::string &output, const ::std::string &str ); - ::std::string & ToLowerCase( ::std::string &str ); - ::std::string & ToUpperCase( ::std::string &output, const ::std::string &str ); - ::std::string & ToUpperCase( ::std::string &str ); - ::std::string & ExtractDirPath( ::std::string &output, const ::std::string &file, char dirDelimeter ); - ::std::string & ExtractDirPath( ::std::string &output, const ::std::string &file, const ::std::string &dirDelimeter ); - ::std::string & ReplaceCharacters( ::std::string &str, char characterToReplace, char newCharacter, const ::std::string::size_type &offset = 0, const ::std::string::size_type &end = ::std::string::npos ); - - // wstring - - ::std::vector<::std::wstring> & Split( ::std::vector<::std::wstring> &output, const ::std::wstring &str, char delim, ::std::wstring::size_type offset = 0 ); - ::std::vector<::std::wstring> & Split( ::std::vector<::std::wstring> &output, const ::std::wstring &str, const ::std::wstring &delim, ::std::wstring::size_type offset = 0 ); - ::std::vector<::std::wstring> & Split( ::std::vector<::std::wstring> &output, const ::std::wstring &str, const ::std::vector<::std::wstring> &delim, ::std::wstring::size_type offset = 0 ); - ::std::wstring & wToLowerCase( ::std::wstring &output, const ::std::wstring &str ); - ::std::wstring & wToLowerCase( ::std::wstring &str ); - - //To wstring - - ::std::wstring & StringToWstring( const ::std::string &str, ::std::wstring &wstr ); - ::std::string & WStringToString( const ::std::wstring &wstr, ::std::string &str ); - } - - namespace Stream - { - float* ReadFloats( float *output, ::std::istream &input, unsigned int numFloats ); - } - - namespace StaticArray - { - template - inline unsigned int NumElementsOf( const ScalarType(&)[num] ) - { return num; } - - template - inline ScalarType & FirstElementOf( ScalarType (&arr)[num] ) - { return arr[0]; } - - template - inline ScalarType & LastElementOf( ScalarType (&arr)[num] ) - { return arr[num-1]; } - } - - namespace Element - { - template - inline void Swap( ScalarType &elementA, ScalarType &elementB, ScalarType &swapSpace ) - { swapSpace = elementA; elementA = elementB; elementB = swapSpace; } - - template - inline void Swap( ScalarType &elementA, ScalarType &elementB ) - { ScalarType swapSpace; Swap( elementA, elementB, swapSpace ); } - } - - namespace Value - { - using ::std::numeric_limits; - - template - inline ValueType Abs( const ValueType &value ) - { return value < 0 ? value * -1 : value; } - - template - inline ValueType Max( const ValueType &valueA, const ValueType &valueB ) - { return valueA > valueB ? valueA : valueB; } - - template - inline ValueType Min( const ValueType &valueA, const ValueType &valueB ) - { return valueA < valueB ? valueA : valueB; } - - template - inline ValueType Average( const ValueType &valueA, const ValueType &valueB ) - { return (valueA + valueB) * 0.5f; } - - template - inline ValueType AverageWithDelta( const ValueType &origin, const ValueType &delta ) - { return origin + (delta * 0.5f); } - - template - inline ValueType Radian( const ValueType °ree ) - { return degree * (3.1415926535897932384626433832795f / 180.0f); } - - template - inline ValueType Degree( const ValueType &radian ) - { return radian * (180.0f / 3.1415926535897932384626433832795f); } - - // SPECIALIZATIONS //!//!//!//!//!//!//!//!//!//!//!//!//!//! - - template<> inline char Average( const char &valueA, const char &valueB ) - { return (valueA + valueB) >> 1; } - - template<> inline unsigned char Average( const unsigned char &valueA, const unsigned char &valueB ) - { return (valueA + valueB) >> 1; } - - template<> inline int Average( const int &valueA, const int &valueB ) - { return (valueA + valueB) >> 1; } - - template<> inline unsigned int Average( const unsigned int &valueA, const unsigned int &valueB ) - { return (valueA + valueB) >> 1; } - - template<> inline long Average( const long &valueA, const long &valueB ) - { return (valueA + valueB) >> 1; } - - template<> inline unsigned long Average( const unsigned long &valueA, const unsigned long &valueB ) - { return (valueA + valueB) >> 1; } - - template<> inline long long Average( const long long &valueA, const long long &valueB ) - { return (valueA + valueB) >> 1; } - - template<> inline unsigned long long Average( const unsigned long long &valueA, const unsigned long long &valueB ) - { return (valueA + valueB) >> 1; } - - template<> inline char AverageWithDelta( const char &origin, const char &delta ) - { return origin + (delta >> 1); } - - template<> inline unsigned char AverageWithDelta( const unsigned char &origin, const unsigned char &delta ) - { return origin + (delta >> 1); } - - template<> inline int AverageWithDelta( const int &origin, const int &delta ) - { return origin + (delta >> 1); } - - template<> inline unsigned int AverageWithDelta( const unsigned int &origin, const unsigned int &delta ) - { return origin + (delta >> 1); } - - template<> inline long AverageWithDelta( const long &origin, const long &delta ) - { return origin + (delta >> 1); } - - template<> inline unsigned long AverageWithDelta( const unsigned long &origin, const unsigned long &delta ) - { return origin + (delta >> 1); } - - template<> inline long long AverageWithDelta( const long long &origin, const long long &delta ) - { return origin + (delta >> 1); } - - template<> inline unsigned long long AverageWithDelta( const unsigned long long &origin, const unsigned long long &delta ) - { return origin + (delta >> 1); } - } -} - -#include "Utilities-InlineImpl.h" - -#endif \ No newline at end of file From 045cfe28fe8960808c39d008fb1fd03f1a9c910b Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 15:45:09 +0100 Subject: [PATCH 52/67] Renamed Utilities-InlineImpl.h to Utilities-Impl.h Implied that only Inlines were implemented there. Contains template implementations as well. --- .../{Utilities-InlineImpl.h => Utilities-Impl.h} | 0 Code/Misc/Utilities.h | 12 +++++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) rename Code/Misc/{Utilities-InlineImpl.h => Utilities-Impl.h} (100%) diff --git a/Code/Misc/Utilities-InlineImpl.h b/Code/Misc/Utilities-Impl.h similarity index 100% rename from Code/Misc/Utilities-InlineImpl.h rename to Code/Misc/Utilities-Impl.h diff --git a/Code/Misc/Utilities.h b/Code/Misc/Utilities.h index 2294918e..cdceb894 100644 --- a/Code/Misc/Utilities.h +++ b/Code/Misc/Utilities.h @@ -27,6 +27,9 @@ namespace Utility template struct UniquePointer { public: + //! Creates an empty UniquePointer. + //UniquePointer(); + //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. UniquePointer( Type *assignedInstance = NULL ); @@ -40,7 +43,7 @@ namespace Utility //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. - UniquePointer & operator = ( Type *assignedInstance ); + UniquePointer & operator = ( Type *assignedInstance ); // potential ambiguous //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. @@ -81,6 +84,9 @@ namespace Utility struct UniqueArray { //! Wrapper to safely transfer dynamic ownership/responsibility public: + //! Creates an empty UniqueArray. + //UniqueArray(); + //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. UniqueArray( Type assignedArray[] = NULL ); @@ -94,7 +100,7 @@ namespace Utility //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. - UniqueArray & operator = ( Type assignedArray[] ); + UniqueArray & operator = ( Type assignedArray[] ); // potential ambiguous //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. @@ -331,6 +337,6 @@ namespace Utility } } -#include "Utilities-InlineImpl.h" +#include "Utilities-Impl.h" #endif \ No newline at end of file From 036519f3f679efb7fd8c7e2cca33a396017e2c79 Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 16:06:01 +0100 Subject: [PATCH 53/67] Fixed potential ambiguity bug Ambiguity in assignment operator with UniquePointer and UniqueArray --- Code/Misc/Misc.vcxproj | 11 ++++++++--- Code/Misc/Misc.vcxproj.filters | 23 +++++++++++++++++++---- Code/Misc/Utilities-Impl.h | 21 +++++---------------- Code/Misc/Utilities.h | 26 ++++++++------------------ 4 files changed, 40 insertions(+), 41 deletions(-) diff --git a/Code/Misc/Misc.vcxproj b/Code/Misc/Misc.vcxproj index e2947725..c41ed349 100644 --- a/Code/Misc/Misc.vcxproj +++ b/Code/Misc/Misc.vcxproj @@ -148,15 +148,20 @@ - + + + - - + + + + + diff --git a/Code/Misc/Misc.vcxproj.filters b/Code/Misc/Misc.vcxproj.filters index 6eae993b..3f2d3b40 100644 --- a/Code/Misc/Misc.vcxproj.filters +++ b/Code/Misc/Misc.vcxproj.filters @@ -27,6 +27,12 @@ Source Files + + Source Files + + + Source Files + Source Files @@ -41,14 +47,23 @@ Header Files - - Header Files - - + Header Files Header Files + + Header Files + + + Header Files + + + Header Files + + + Header Files + \ No newline at end of file diff --git a/Code/Misc/Utilities-Impl.h b/Code/Misc/Utilities-Impl.h index 50d13652..655f06c5 100644 --- a/Code/Misc/Utilities-Impl.h +++ b/Code/Misc/Utilities-Impl.h @@ -1,7 +1,11 @@ ///////////////////////////////////////////////////////////////////// // Inline and template implementations for // the Utility Collection of Miscellanious Handy Functions -// © Dan Andersson 2013 +// +// Created 2013 by Dan Andersson +// Edited 2013 by +// * Dan Andersson +// * Dennis Andersen ///////////////////////////////////////////////////////////////////// #ifndef UTILITIES_INLINE_IMPL_H @@ -51,14 +55,6 @@ namespace Utility SafeDeleteInstance( this->ownedInstance ); } - template - UniquePointer & UniquePointer::operator = ( Type *assignedInstance ) - { - SafeDeleteInstance( this->ownedInstance ); - this->ownedInstance = assignedInstance; - return *this; - } - template UniquePointer & UniquePointer::operator = ( const UniquePointer &donor ) { @@ -144,13 +140,6 @@ namespace Utility SafeDeleteArray( this->ownedArray ); } - template - UniqueArray & UniqueArray::operator = ( Type assignedArray[] ) - { - SafeDeleteArray( this->ownedArray ); - this->ownedArray = assignedArray; - } - template UniqueArray & UniqueArray::operator = ( const UniqueArray &donor ) { diff --git a/Code/Misc/Utilities.h b/Code/Misc/Utilities.h index cdceb894..abda0af5 100644 --- a/Code/Misc/Utilities.h +++ b/Code/Misc/Utilities.h @@ -1,7 +1,11 @@ -//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! +///////////////////////////////////////////////////////////////////// // Utility Collection of Miscellanious Handy Functions -// © Dan Andersson 2013 -//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//!//! +// +// Created 2013 by Dan Andersson +// Edited 2013 by +// * Dan Andersson +// * Dennis Andersen +///////////////////////////////////////////////////////////////////// #ifndef UTILITIES_H #define UTILITIES_H @@ -27,12 +31,9 @@ namespace Utility template struct UniquePointer { public: - //! Creates an empty UniquePointer. - //UniquePointer(); - //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. - UniquePointer( Type *assignedInstance = NULL ); + UniquePointer( Type *assignedInstance = NULL ); //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. @@ -41,10 +42,6 @@ namespace Utility //! Will auto delete assigned dynamic instance. ~UniquePointer(); - //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. - //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. - UniquePointer & operator = ( Type *assignedInstance ); // potential ambiguous - //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. UniquePointer & operator = ( const UniquePointer &donor ); @@ -84,9 +81,6 @@ namespace Utility struct UniqueArray { //! Wrapper to safely transfer dynamic ownership/responsibility public: - //! Creates an empty UniqueArray. - //UniqueArray(); - //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. UniqueArray( Type assignedArray[] = NULL ); @@ -97,10 +91,6 @@ namespace Utility //! Will auto delete assigned dynamic array. ~UniqueArray(); - - //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. - //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. - UniqueArray & operator = ( Type assignedArray[] ); // potential ambiguous //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. From 23fa0902960208cb30cb22e2398e87ee754f3b56 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Thu, 28 Nov 2013 16:14:42 +0100 Subject: [PATCH 54/67] Threadsafe Queue implemented with IQueue interface threadsafe by using mutex lock in the Queue --- Code/Misc/IQueue.h | 31 +++ Code/Misc/Misc.vcxproj | 2 + Code/Misc/Misc.vcxproj.filters | 6 + Code/Misc/ThreadSafeQueue.h | 216 ++++++++++++++++++ Code/Network/NetworkDependencies/Connection.h | 6 +- .../OysterNetworkClient/ClientMain.cpp | 57 ++++- 6 files changed, 314 insertions(+), 4 deletions(-) create mode 100644 Code/Misc/IQueue.h create mode 100644 Code/Misc/ThreadSafeQueue.h diff --git a/Code/Misc/IQueue.h b/Code/Misc/IQueue.h new file mode 100644 index 00000000..8ddc28a9 --- /dev/null +++ b/Code/Misc/IQueue.h @@ -0,0 +1,31 @@ +#ifndef I_QUEUE_H +#define I_QUEUE_H + +///////////////////////////////// +// Created by Sam Svensson 2013// +///////////////////////////////// + +namespace Oyster +{ + namespace Queue + { + template + class IQueue + { + public: + virtual ~IQueue() {}; + virtual void Push( Type item ) = 0; + virtual Type Pop() = 0; + + virtual Type Front() = 0; + virtual Type Back() = 0; + + virtual int Size() = 0; + virtual bool IsEmpty() = 0; + + virtual void Swap( IQueue &queue ) = 0; + }; + } +} + +#endif \ No newline at end of file diff --git a/Code/Misc/Misc.vcxproj b/Code/Misc/Misc.vcxproj index ca39cada..124024e2 100644 --- a/Code/Misc/Misc.vcxproj +++ b/Code/Misc/Misc.vcxproj @@ -156,8 +156,10 @@ + + diff --git a/Code/Misc/Misc.vcxproj.filters b/Code/Misc/Misc.vcxproj.filters index abee7ddd..55ec07ab 100644 --- a/Code/Misc/Misc.vcxproj.filters +++ b/Code/Misc/Misc.vcxproj.filters @@ -65,5 +65,11 @@ Header Files + + Header Files + + + Header Files + \ No newline at end of file diff --git a/Code/Misc/ThreadSafeQueue.h b/Code/Misc/ThreadSafeQueue.h new file mode 100644 index 00000000..019485ce --- /dev/null +++ b/Code/Misc/ThreadSafeQueue.h @@ -0,0 +1,216 @@ +#ifndef THREAD_SAFE_QUEUE_H +#define THREAD_SAFE_QUEUE_H + +//////////////////////////////////////////// +// Thread safe queue implemented +// with single linked list. +// Created by Sam Svensson 2013 +///////////////////////////////////////////// + +#include "IQueue.h" +#include "Thread/OysterMutex.h" + +namespace Oyster +{ + namespace Queue + { + template + class ThreadSafeQueue : public IQueue + { + public: + ThreadSafeQueue(); + virtual ~ThreadSafeQueue(); + + virtual void Push( Type item ); + virtual Type Pop(); + + virtual Type Front(); + virtual Type Back(); + + virtual int Size(); + virtual bool IsEmpty(); + virtual void Swap( IQueue &queue ); + + private: + class Node + { + public: + Type item; + Node *next; + Node(Type item){ this->item = item; this->next = NULL; }; + ~Node() {}; + }; + + Node *front; + Node *back; + int nrOfNodes; + OysterMutex mutex; + }; + + + + + //---------------------------------------------- + //implemented template functions + //---------------------------------------------- + + template < typename Type > + ThreadSafeQueue::ThreadSafeQueue() + { + this->front = NULL; + this->back = NULL; + this->nrOfNodes = 0; + + } + + template < typename Type > + ThreadSafeQueue::~ThreadSafeQueue() + { + this->mutex.LockMutex(); + + if(this->front != NULL) + { + Node *destroyer; + Node *walker = this->front; + + for(int i = 0; i < this->nrOfNodes; i++) + { + destroyer = walker; + walker = walker->next; + + delete destroyer; + } + + this->front = NULL; + this->back = NULL; + } + + this->mutex.UnlockMutex(); + } + + + template < typename Type > + void ThreadSafeQueue::Push(Type item) + { + Node *e = new Node(item); + + mutex.LockMutex(); + if(this->front != NULL) + { + this->back->next = e; + this->back = e; + } + + else + { + this->front = e; + this->back = e; + } + + this->nrOfNodes++; + + mutex.UnlockMutex(); + } + + template < typename Type > + Type ThreadSafeQueue::Pop() + { + mutex.LockMutex(); + if(this->front != NULL) + { + Type item = this->front->item; + Node *destroyer = this->front; + this->front = front->next; + + delete destroyer; + this->nrOfNodes--; + + if(nrOfNodes == 0) + { + this->front = NULL; + this->back = NULL; + } + return item; + } + + mutex.UnlockMutex(); + + return NULL; + } + + template < typename Type > + Type ThreadSafeQueue::Front() + { + mutex.LockMutex(); + if(front != NULL) + { + return this->front->item; + } + mutex.UnlockMutex(); + + return NULL; + } + + template < typename Type > + Type ThreadSafeQueue::Back() + { + mutex.LockMutex(); + if(back != NULL) + { + return this->back->item; + } + mutex.UnlockMutex(); + + return NULL; + } + + template < typename Type > + int ThreadSafeQueue::Size() + { + //? behövs denna låsas? + mutex.LockMutex(); + return this->nrOfNodes; + mutex.UnlockMutex(); + } + + template < typename Type > + bool ThreadSafeQueue::IsEmpty() + { + mutex.LockMutex(); + if(nrOfNodes == 0 && this->front == NULL) + { + mutex.UnlockMutex(); + return true; + } + + else + { + mutex.UnlockMutex(); + } + return false; + } + + template < typename Type > + void ThreadSafeQueue::Swap(IQueue &queue ) + { + mutex.LockMutex(); + int prevNrOfNodes = this->nrOfNodes; + int size = queue.Size(); + + for(int i = 0; i < size; i++) + { + this->Push(queue.Pop()); + } + + for(int i = 0; i < prevNrOfNodes; i++) + { + queue.Push(this->Pop()); + } + mutex.UnlockMutex(); + } + + + } +} +#endif + diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index b6b17c60..c69bb0f5 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -16,8 +16,8 @@ namespace Oyster { public: - Connection() { this->socket = 0; }; - Connection(int socket) { this->socket = socket; }; + Connection() { this->socket = 0; }; + Connection( int socket ) { this->socket = socket; }; virtual ~Connection(); virtual int InitiateServer( unsigned short port ); @@ -32,7 +32,7 @@ namespace Oyster private: int InitiateSocket(); - void SetBlockingMode(bool blocking); + void SetBlockingMode( bool blocking ); int socket; diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index ce66446f..53cb8506 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -5,6 +5,7 @@ #include "..\NetworkDependencies\Translator.h" #include "..\NetworkDependencies\Protocols.h" #include "../NetworkDependencies/OysterByte.h" +#include "../../Misc/ThreadSafeQueue.h" #include "Client.h" #pragma comment(lib, "ws2_32.lib") @@ -37,7 +38,61 @@ int main() wcout << "errorMessage: " << errorTest << endl; } - chat(client); + + //test queue + //----------------------------------------- + Oyster::Queue::IQueue *test = new Oyster::Queue::ThreadSafeQueue(); + Oyster::Queue::IQueue *test2 = new Oyster::Queue::ThreadSafeQueue(); + + for(int i = 0; i < 100; i++) + { + //test->Push(i); + //cout << test->Pop() << endl; + } + + cout << "heeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeej" < -1; i--) + { + //test->Push(i); + //cout << test->Pop() << endl; + } + + if(test->IsEmpty()) + { + for(int i = 99; i > -1; i--) + { + test->Push(i); + //cout << test->Pop() << endl; + } + } + + for(int i = 0; i < 50; i++) + { + test2->Push(i); + } + + //test2->Swap(*test); + + cout << "TEST 1-50" <Size(); + for(int i = 0; i < size; i++) + { + //cout << test->Pop() << endl; + } + + cout << "TEST2 99-1" <Size(); + for(int i = 0; i < size; i++) + { + //cout << test2->Pop() << endl; + } + + cout << test->Front() << " " << test2->Front() < Date: Thu, 28 Nov 2013 16:15:28 +0100 Subject: [PATCH 55/67] PostBox Created PostBox and IPostBox. Listener post new clients to PostBox. --- Code/Misc/Thread/OysterThread_Impl.cpp | 2 +- Code/Network/NetworkDependencies/IPostBox.h | 25 +++++++ Code/Network/NetworkDependencies/ITranslate.h | 2 +- Code/Network/NetworkDependencies/Listener.cpp | 22 +++--- Code/Network/NetworkDependencies/Listener.h | 8 ++- .../NetworkDependencies.vcxproj | 10 +-- .../NetworkDependencies.vcxproj.filters | 2 + Code/Network/NetworkDependencies/PostBox.h | 72 +++++++++++++++++++ .../NetworkDependencies/Translator.cpp | 4 +- Code/Network/NetworkDependencies/Translator.h | 8 +-- .../OysterNetworkClient/ClientMain.cpp | 4 +- .../OysterNetworkServer.vcxproj | 3 - .../OysterNetworkServer/ServerMain.cpp | 33 +++++++-- 13 files changed, 151 insertions(+), 44 deletions(-) create mode 100644 Code/Network/NetworkDependencies/IPostBox.h create mode 100644 Code/Network/NetworkDependencies/PostBox.h diff --git a/Code/Misc/Thread/OysterThread_Impl.cpp b/Code/Misc/Thread/OysterThread_Impl.cpp index 9b01e6d5..46b889fe 100644 --- a/Code/Misc/Thread/OysterThread_Impl.cpp +++ b/Code/Misc/Thread/OysterThread_Impl.cpp @@ -62,7 +62,7 @@ using namespace Utility::DynamicMemory::SmartPointer; ~PrivateData() { //@todo TODO: Make detatch avalible. - //this->threadData->workerThread->detach(); + this->threadData->workerThread->detach(); this->threadData->owner = 0; diff --git a/Code/Network/NetworkDependencies/IPostBox.h b/Code/Network/NetworkDependencies/IPostBox.h new file mode 100644 index 00000000..31c1bef7 --- /dev/null +++ b/Code/Network/NetworkDependencies/IPostBox.h @@ -0,0 +1,25 @@ +#ifndef NETWORK_DEPENDENCIES_I_POST_BOX_H +#define NETWORK_DEPENDENCIES_I_POST_BOX_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +namespace Oyster +{ + namespace Network + { + template + class IPostBox + { + public: + virtual ~IPostBox() {} + virtual void PostMessage(T& message) = 0; + virtual void FetchMessage(T& message) = 0; + virtual bool IsFull() = 0; + + }; + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/ITranslate.h b/Code/Network/NetworkDependencies/ITranslate.h index 1143c716..90eb1431 100644 --- a/Code/Network/NetworkDependencies/ITranslate.h +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -15,7 +15,7 @@ namespace Oyster public: virtual void Pack (Protocols::ProtocolHeader &header, OysterByte& bytes) = 0; - virtual Protocols::ProtocolSet* Unpack (Protocols::ProtocolSet* set, OysterByte& bytes ) = 0; + virtual void Unpack (Protocols::ProtocolSet* set, OysterByte& bytes ) = 0; }; } diff --git a/Code/Network/NetworkDependencies/Listener.cpp b/Code/Network/NetworkDependencies/Listener.cpp index 1af94613..e1b8fa08 100644 --- a/Code/Network/NetworkDependencies/Listener.cpp +++ b/Code/Network/NetworkDependencies/Listener.cpp @@ -4,8 +4,6 @@ using namespace Oyster::Network::Server; Listener::Listener() { - newSocket = false; - tempSocket = 0; } Listener::~Listener() @@ -27,19 +25,16 @@ bool Listener::Init(unsigned int port) return true; } -int Listener::GetNewClient() +void Listener::Shutdown() +{ + thread.Terminate(); +} + +void Listener::SetPostBox(Oyster::Network::IPostBox* postBox) { mutex.LockMutex(); - int temp = -1; - - if(newSocket) - { - temp = tempSocket; - newSocket = false; - } + this->postBox = postBox; mutex.UnlockMutex(); - - return temp; } int Listener::Accept() @@ -48,8 +43,7 @@ int Listener::Accept() clientSocket = connection->Listen(); mutex.LockMutex(); - tempSocket = clientSocket; - newSocket = true; + postBox->PostMessage(clientSocket); mutex.UnlockMutex(); return clientSocket; diff --git a/Code/Network/NetworkDependencies/Listener.h b/Code/Network/NetworkDependencies/Listener.h index aa3817cf..5888aed9 100644 --- a/Code/Network/NetworkDependencies/Listener.h +++ b/Code/Network/NetworkDependencies/Listener.h @@ -9,7 +9,7 @@ #include "../NetworkDependencies/Connection.h" #include "../../Misc/Thread/OysterThread.h" #include "../../Misc/Thread/OysterMutex.h" - +#include "IPostBox.h" namespace Oyster { @@ -24,8 +24,10 @@ namespace Oyster ~Listener(); bool Init(unsigned int port); + void Shutdown(); int Accept(); int GetNewClient(); + void SetPostBox(IPostBox* postBox); //Thread functions bool DoWork(); @@ -37,12 +39,12 @@ namespace Oyster private: ::Oyster::Network::Connection* connection; - int tempSocket; - bool newSocket; ::Oyster::Thread::OysterThread thread; OysterMutex mutex; + IPostBox* postBox; + }; } } diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index 5b660b13..dfabbcba 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -149,14 +149,6 @@ {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} - - {f10cbc03-9809-4cba-95d8-327c287b18ee} - true - true - true - false - false - @@ -173,6 +165,7 @@ + @@ -180,6 +173,7 @@ + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index dc3225ff..74cb9a56 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -25,5 +25,7 @@ + + \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/PostBox.h b/Code/Network/NetworkDependencies/PostBox.h new file mode 100644 index 00000000..a24cea5e --- /dev/null +++ b/Code/Network/NetworkDependencies/PostBox.h @@ -0,0 +1,72 @@ +#ifndef NETWORK_DEPENDENCIES_POST_BOX_H +#define NETWORK_DEPENDENCIES_POST_BOX_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "IPostBox.h" +#include +#include "../../Misc/Thread/OysterMutex.h" + +namespace Oyster +{ + namespace Network + { + template + class PostBox : public IPostBox + { + public: + PostBox(); + virtual ~PostBox(); + + virtual void PostMessage(T& message); + virtual void FetchMessage(T& message); + virtual bool IsFull(); + + private: + std::queue messages; + OysterMutex mutex; + + }; + + //Implementation of PostBox + template + PostBox::PostBox() + { + } + + template + PostBox::~PostBox() + { + } + + template + void PostBox::PostMessage(T& message) + { + mutex.LockMutex(); + messages.push(message); + mutex.UnlockMutex(); + } + + template + void PostBox::FetchMessage(T& message) + { + mutex.LockMutex(); + if(IsFull()) + { + message = messages.front(); + messages.pop(); + } + mutex.UnlockMutex(); + } + + template + bool PostBox::IsFull() + { + return !messages.empty(); + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Translator.cpp b/Code/Network/NetworkDependencies/Translator.cpp index b0b6d587..4bb739ca 100644 --- a/Code/Network/NetworkDependencies/Translator.cpp +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -28,7 +28,7 @@ void Translator::Pack( ProtocolHeader &header, OysterByte& bytes ) } } -ProtocolSet* Translator::Unpack(ProtocolSet* set, OysterByte& bytes ) +void Translator::Unpack(ProtocolSet* set, OysterByte& bytes ) { ProtocolHeader *header = new ProtocolHeader(); MessageHeader *message = new MessageHeader(); @@ -60,5 +60,5 @@ ProtocolSet* Translator::Unpack(ProtocolSet* set, OysterByte& bytes ) } delete header; - return set; + //return set; } \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Translator.h b/Code/Network/NetworkDependencies/Translator.h index 44ce39d2..56459f72 100644 --- a/Code/Network/NetworkDependencies/Translator.h +++ b/Code/Network/NetworkDependencies/Translator.h @@ -17,15 +17,13 @@ namespace Oyster class Translator : public ITranslate { public: - Translator () { /*msg = new unsigned char[1601];*/ }; - ~Translator() { /*if(msg != NULL) { delete [] this->msg; }*/ }; + Translator () { }; + ~Translator() { }; void Pack (Protocols::ProtocolHeader &header, OysterByte& bytes ); - Protocols::ProtocolSet* Unpack (Protocols::ProtocolSet* set, OysterByte& bytes ); + void Unpack (Protocols::ProtocolSet* set, OysterByte& bytes ); private: - //unsigned char* msg; - //OysterByte bytes; }; } diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index ce66446f..6ebc8dfc 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -88,7 +88,7 @@ void chat(Client &client) set->Release(); msgRecv.Clear(1000); - std::getline(std::cin, msgSend); + /*std::getline(std::cin, msgSend); @@ -111,7 +111,7 @@ void chat(Client &client) chatDone = true; } - cin.clear(); + cin.clear();*/ } diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj index 260586da..65136729 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj @@ -149,9 +149,6 @@ {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} - - {f10cbc03-9809-4cba-95d8-327c287b18ee} - {c5aa09d0-6594-4cd3-bd92-1d380c7b3b50} diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index 6d958e2d..cc2e398b 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -1,11 +1,14 @@ #include #include +#include #include #include "../NetworkDependencies/WinsockFunctions.h" #include "../NetworkDependencies/Listener.h" #include "../NetworkDependencies/Translator.h" #include "Client.h" #include "../NetworkDependencies/OysterByte.h" +#include "../NetworkDependencies/PostBox.h" +#include "../../Misc/WinTimer.h" #pragma comment(lib, "ws2_32.lib") @@ -13,10 +16,12 @@ using namespace std; using namespace Oyster::Network::Server; using namespace Oyster::Network; using namespace ::Protocols; +using namespace Utility; int main() { OysterByte recvBuffer; + IPostBox* postBox = new PostBox(); cout << "Server" << endl; Translator t; @@ -30,6 +35,7 @@ int main() //Create socket Listener listener; listener.Init(9876); + listener.SetPostBox(postBox); Sleep(1000); //Start listening //Accept a client @@ -37,7 +43,7 @@ int main() test.clientID = 0; test.size = 2; test.textMessage = "hej"; - test.numOfFloats = 35; + test.numOfFloats = 0; test.f = new float[test.numOfFloats]; float temp = 395.456f; for(int i = 0; i < (int)test.numOfFloats; i++) @@ -48,18 +54,35 @@ int main() t.Pack(test, recvBuffer); + WinTimer timer; + + vector clients; + int client = -1; while(1) { - int client = listener.GetNewClient(); + client = -1; + postBox->FetchMessage(client); if(client != -1) { cout << "Client connected: " << client << endl; - Client client1(client); + clients.push_back(new Client(client)); - client1.Send(recvBuffer); + clients.at(clients.size()-1)->Send(recvBuffer); } - //Sleep(100); + + //Send a message every 1 secounds to all clients. + if(timer.getElapsedSeconds() > 1) + { + cout << "Sending to " << clients.size() << " clients." << endl; + timer.reset(); + for(int i = 0; i < (int)clients.size(); i++) + { + clients.at(i)->Send(recvBuffer); + } + } + Sleep(100); } + listener.Shutdown(); /* int clientSocket = listener.Accept(); From 9d92b292d91bd7721bf05a0a486126ea6de0a8ea Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 16:18:20 +0100 Subject: [PATCH 56/67] Improved documentation of UniquePointer and UniqueArray --- Code/Misc/Utilities.h | 122 ++++++++++++++++++++++++++++++------------ 1 file changed, 88 insertions(+), 34 deletions(-) diff --git a/Code/Misc/Utilities.h b/Code/Misc/Utilities.h index abda0af5..6f5cf3ab 100644 --- a/Code/Misc/Utilities.h +++ b/Code/Misc/Utilities.h @@ -21,56 +21,87 @@ namespace Utility { namespace DynamicMemory { - //! If dynamicInstance is not NULL, then delete + /****************************************************************** + * If dynamicInstance is not NULL, then delete. + ******************************************************************/ template void SafeDeleteInstance( Type *dynamicInstance ); - //! If dynamicArray is not NULL, then delete [] + /****************************************************************** + * If dynamicArray is not NULL, then delete []. + ******************************************************************/ template void SafeDeleteArray( Type dynamicArray[] ); //! Wrapper to safely transfer dynamic ownership/responsibility template struct UniquePointer { public: - //! Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. - //! If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. + /****************************************************************** + * Assigns assignedInstance ownership to this UniquePonter, old owned instance will be deleted. + * If NULL is assigned is equivalent with clearing all responsibilities from this UniquePointer. + ******************************************************************/ UniquePointer( Type *assignedInstance = NULL ); - //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. - //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. + /****************************************************************** + * Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. + * If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. + ******************************************************************/ UniquePointer( const UniquePointer &donor ); - //! Will auto delete assigned dynamic instance. + /****************************************************************** + * Will auto delete assigned dynamic instance. + ******************************************************************/ ~UniquePointer(); - //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. - //! If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. + /****************************************************************** + * Transfers assignedInstance ownership from donor to this UniquePonter, old owned instance will be deleted. + * If donor had nothing, is equivalent with clearing all responsibilities from this UniquePointer. + ******************************************************************/ UniquePointer & operator = ( const UniquePointer &donor ); - //! Access the assigned dynamic instance. Will crash if nothing there + /****************************************************************** + * Access the assigned dynamic instance. Will crash if nothing there + ******************************************************************/ operator Type* (); - //! Access the assigned dynamic instance. Will crash if nothing there + /****************************************************************** + * Access the assigned dynamic instance. Will crash if nothing there + ******************************************************************/ operator const Type* () const; - //! Access members of the assigned dynamic instance. Will crash if nothing there + /****************************************************************** + * Access members of the assigned dynamic instance. Will crash if nothing there + ******************************************************************/ Type * operator -> (); - //! Access members of the assigned dynamic instance. Will crash if nothing there + /****************************************************************** + * Access members of the assigned dynamic instance. Will crash if nothing there + ******************************************************************/ const Type * operator -> () const; - //! If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. + /****************************************************************** + * @return true if this UniquePointer have a current ownership/responsibility of a dynamic instance. + ******************************************************************/ operator bool () const; - //! @return true if this ownedInstance matches with stray + /****************************************************************** + * @return true if this ownedInstance matches with stray + ******************************************************************/ bool operator == ( Type *stray ) const; - //! @return false if this ownedInstance matches with stray + /****************************************************************** + * @return false if this ownedInstance matches with stray + ******************************************************************/ bool operator != ( Type *stray ) const; - //! This UniquePointer drops all claims of ownership/responsibility and returns the dynamic instance. Now it is your responsibility to delete. + /****************************************************************** + * This UniquePointer drops all claims of ownership/responsibility and returns the dynamic instance. Now it is your responsibility to delete. + ******************************************************************/ Type* Release(); - //! (inline) If true, this UniquePointer have a current ownership/responsibility of a dynamic instance. + /****************************************************************** + * @return true if this UniquePointer have a current ownership/responsibility of a dynamic instance. + * inline of @see operator bool () const + ******************************************************************/ bool HaveOwnership() const; private: @@ -81,42 +112,65 @@ namespace Utility struct UniqueArray { //! Wrapper to safely transfer dynamic ownership/responsibility public: - //! Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. - //! If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. + /****************************************************************** + * Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. + * If NULL is assigned is equivalent with clearing all responsibilities from this UniqueArray. + ******************************************************************/ UniqueArray( Type assignedArray[] = NULL ); - //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. - //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. + /****************************************************************** + * Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. + * If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. + ******************************************************************/ UniqueArray( const UniqueArray &donor ); - //! Will auto delete assigned dynamic array. + /****************************************************************** + * Will auto delete assigned dynamic array. + ******************************************************************/ ~UniqueArray(); - //! Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. - //! If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. + /****************************************************************** + * Transfers assignedInstance ownership from donor to this UniquePonter, old owned array will be deleted. + * If donor had nothing, is equivalent with clearing all responsibilities from this UniqueArray. + ******************************************************************/ UniqueArray & operator = ( const UniqueArray &donor ); - //! Accesses the instance at index i of this UniqeArray's owned dynamic array. - //! Will crash if out-of-bound or there is no assigned array. + /****************************************************************** + * Accesses the instance at index i of this UniqeArray's owned dynamic array. + * Will crash if out-of-bound or there is no assigned array. + ******************************************************************/ template Type & operator [] ( Index i ); - //! Accesses the instance at index i of this UniqeArray's owned dynamic array. - //! Will crash if out-of-bound or there is no assigned array. + /****************************************************************** + * Accesses the instance at index i of this UniqeArray's owned dynamic array. + * Will crash if out-of-bound or there is no assigned array. + ******************************************************************/ template const Type & operator [] ( Index i ) const; - //! If true, this UniqueArray have a current ownership/responsibility of a dynamic instance. + /****************************************************************** + * @return true if this UniqueArray have a current ownership/responsibility of a dynamic array. + ******************************************************************/ operator bool () const; - //! @return true if this ownedInstance matches with stray + /****************************************************************** + * @return true if this ownedInstance matches with stray. + ******************************************************************/ bool operator == ( Type *stray ) const; - //! @return false if this ownedInstance matches with stray + /****************************************************************** + * @return false if this ownedInstance matches with stray. + ******************************************************************/ bool operator != ( Type *stray ) const; - //! This UniqueArray drops all claims of ownership/responsibility and returns the dynamic array. Now it is your responsibility to delete. + /****************************************************************** + * This UniqueArray drops all claims of ownership/responsibility and returns the dynamic array. Now it is your responsibility to delete. + ******************************************************************/ Type* Release(); - //! (inline) If true, this UniqueArray have a current ownership/responsibility of a dynamic array. + /****************************************************************** + * @return true if this UniqueArray have a current ownership/responsibility of a dynamic array. + * inline of @see operator bool () const + ******************************************************************/ bool HaveOwnership() const; private: From 8dab865cb66071199557cad257e9c94fde846c1a Mon Sep 17 00:00:00 2001 From: Pontus Fransson Date: Thu, 28 Nov 2013 16:20:50 +0100 Subject: [PATCH 57/67] Changed to our own Queue --- Code/Network/NetworkDependencies/PostBox.h | 17 ++++++----------- Code/Network/OysterNetworkClient/ClientMain.cpp | 6 +++--- 2 files changed, 9 insertions(+), 14 deletions(-) diff --git a/Code/Network/NetworkDependencies/PostBox.h b/Code/Network/NetworkDependencies/PostBox.h index a24cea5e..6b2c2ff8 100644 --- a/Code/Network/NetworkDependencies/PostBox.h +++ b/Code/Network/NetworkDependencies/PostBox.h @@ -6,8 +6,8 @@ ///////////////////////////////////// #include "IPostBox.h" -#include #include "../../Misc/Thread/OysterMutex.h" +#include "../../Misc/ThreadSafeQueue.h" namespace Oyster { @@ -25,8 +25,7 @@ namespace Oyster virtual bool IsFull(); private: - std::queue messages; - OysterMutex mutex; + Oyster::Queue::ThreadSafeQueue messages; }; @@ -44,27 +43,23 @@ namespace Oyster template void PostBox::PostMessage(T& message) { - mutex.LockMutex(); - messages.push(message); - mutex.UnlockMutex(); + messages.Push(message); } template void PostBox::FetchMessage(T& message) { - mutex.LockMutex(); if(IsFull()) { - message = messages.front(); - messages.pop(); + message = messages.Front(); + messages.Pop(); } - mutex.UnlockMutex(); } template bool PostBox::IsFull() { - return !messages.empty(); + return !messages.IsEmpty(); } } } diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 22eb5c40..217773a9 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -41,7 +41,7 @@ int main() //test queue //----------------------------------------- - Oyster::Queue::IQueue *test = new Oyster::Queue::ThreadSafeQueue(); + /*Oyster::Queue::IQueue *test = new Oyster::Queue::ThreadSafeQueue(); Oyster::Queue::IQueue *test2 = new Oyster::Queue::ThreadSafeQueue(); for(int i = 0; i < 100; i++) @@ -91,8 +91,8 @@ int main() cout << test->Front() << " " << test2->Front() < Date: Thu, 28 Nov 2013 23:18:48 +0100 Subject: [PATCH 58/67] Modified project file to include Thread in misc --- Code/Misc/Misc.vcxproj | 5 +++++ Code/Misc/Misc.vcxproj.filters | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/Code/Misc/Misc.vcxproj b/Code/Misc/Misc.vcxproj index e2947725..ca39cada 100644 --- a/Code/Misc/Misc.vcxproj +++ b/Code/Misc/Misc.vcxproj @@ -150,12 +150,17 @@ + + + + + diff --git a/Code/Misc/Misc.vcxproj.filters b/Code/Misc/Misc.vcxproj.filters index 6eae993b..abee7ddd 100644 --- a/Code/Misc/Misc.vcxproj.filters +++ b/Code/Misc/Misc.vcxproj.filters @@ -33,6 +33,12 @@ Source Files + + Source Files + + + Source Files + @@ -50,5 +56,14 @@ Header Files + + Header Files + + + Header Files + + + Header Files + \ No newline at end of file From 1cbdb0bcfab3879b3e9e0fd9d495a17fdc928f98 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Fri, 29 Nov 2013 08:59:36 +0100 Subject: [PATCH 59/67] cleanup commented section in ClientMain --- .../OysterNetworkClient/ClientMain.cpp | 54 ------------------- 1 file changed, 54 deletions(-) diff --git a/Code/Network/OysterNetworkClient/ClientMain.cpp b/Code/Network/OysterNetworkClient/ClientMain.cpp index 217773a9..b8f1057f 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -38,60 +38,6 @@ int main() wcout << "errorMessage: " << errorTest << endl; } - - //test queue - //----------------------------------------- - /*Oyster::Queue::IQueue *test = new Oyster::Queue::ThreadSafeQueue(); - Oyster::Queue::IQueue *test2 = new Oyster::Queue::ThreadSafeQueue(); - - for(int i = 0; i < 100; i++) - { - //test->Push(i); - //cout << test->Pop() << endl; - } - - cout << "heeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeej" < -1; i--) - { - //test->Push(i); - //cout << test->Pop() << endl; - } - - if(test->IsEmpty()) - { - for(int i = 99; i > -1; i--) - { - test->Push(i); - //cout << test->Pop() << endl; - } - } - - for(int i = 0; i < 50; i++) - { - test2->Push(i); - } - - //test2->Swap(*test); - - cout << "TEST 1-50" <Size(); - for(int i = 0; i < size; i++) - { - //cout << test->Pop() << endl; - } - - cout << "TEST2 99-1" <Size(); - for(int i = 0; i < size; i++) - { - //cout << test2->Pop() << endl; - } - - cout << test->Front() << " " << test2->Front() < Date: Fri, 29 Nov 2013 09:11:30 +0100 Subject: [PATCH 60/67] Added documentation and removed unecessesary code. --- Code/Network/NetworkDependencies/Listener.cpp | 1 + Code/Network/NetworkDependencies/Listener.h | 5 ++-- Code/Network/NetworkDependencies/OysterByte.h | 2 -- Code/Network/NetworkDependencies/PostBox.h | 2 ++ Code/Network/NetworkDependencies/Protocols.h | 3 ++ .../NetworkDependencies/WinsockFunctions.h | 2 +- .../OysterNetworkServer/ServerMain.cpp | 29 +------------------ 7 files changed, 11 insertions(+), 33 deletions(-) diff --git a/Code/Network/NetworkDependencies/Listener.cpp b/Code/Network/NetworkDependencies/Listener.cpp index e1b8fa08..c441d045 100644 --- a/Code/Network/NetworkDependencies/Listener.cpp +++ b/Code/Network/NetworkDependencies/Listener.cpp @@ -4,6 +4,7 @@ using namespace Oyster::Network::Server; Listener::Listener() { + connection = NULL; } Listener::~Listener() diff --git a/Code/Network/NetworkDependencies/Listener.h b/Code/Network/NetworkDependencies/Listener.h index 5888aed9..8bb16a0f 100644 --- a/Code/Network/NetworkDependencies/Listener.h +++ b/Code/Network/NetworkDependencies/Listener.h @@ -25,8 +25,7 @@ namespace Oyster bool Init(unsigned int port); void Shutdown(); - int Accept(); - int GetNewClient(); + void SetPostBox(IPostBox* postBox); //Thread functions @@ -35,6 +34,8 @@ namespace Oyster void ThreadExit(); private: + //Function that runs in the thread. + int Accept(); private: diff --git a/Code/Network/NetworkDependencies/OysterByte.h b/Code/Network/NetworkDependencies/OysterByte.h index 390e4398..87a0103c 100644 --- a/Code/Network/NetworkDependencies/OysterByte.h +++ b/Code/Network/NetworkDependencies/OysterByte.h @@ -30,8 +30,6 @@ namespace Oyster operator char*(); operator const char*(); operator unsigned char*(); - - //unsigned char& operator[](unsigned int id); private: void IncreaseCapacity(unsigned int cap); //Expands the byteArray diff --git a/Code/Network/NetworkDependencies/PostBox.h b/Code/Network/NetworkDependencies/PostBox.h index 6b2c2ff8..b2e553f8 100644 --- a/Code/Network/NetworkDependencies/PostBox.h +++ b/Code/Network/NetworkDependencies/PostBox.h @@ -13,6 +13,8 @@ namespace Oyster { namespace Network { + //With this class you can post items to it and then fetch them somewhere else. + //It is thread safe beacause of the ThreadSafeQueue. template class PostBox : public IPostBox { diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h index f90d99c6..12444e3e 100644 --- a/Code/Network/NetworkDependencies/Protocols.h +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -41,6 +41,9 @@ namespace Oyster virtual ~ProtocolTest() { delete[] f; } }; + + //Holding every protocol in an union. + //Used because we now don't have to type case our protocol when we recieve them. class ProtocolSet { public: diff --git a/Code/Network/NetworkDependencies/WinsockFunctions.h b/Code/Network/NetworkDependencies/WinsockFunctions.h index 92c8957a..a4edf38d 100644 --- a/Code/Network/NetworkDependencies/WinsockFunctions.h +++ b/Code/Network/NetworkDependencies/WinsockFunctions.h @@ -4,8 +4,8 @@ ///////////////////////////////////// // Created by Pontus Fransson 2013 // ///////////////////////////////////// -#include +#include void ShutdownWinSock(); bool InitWinSock(); diff --git a/Code/Network/OysterNetworkServer/ServerMain.cpp b/Code/Network/OysterNetworkServer/ServerMain.cpp index cc2e398b..9dd0a0c1 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -37,6 +37,7 @@ int main() listener.Init(9876); listener.SetPostBox(postBox); Sleep(1000); + //Start listening //Accept a client ProtocolTest test; @@ -84,37 +85,9 @@ int main() } listener.Shutdown(); - -/* int clientSocket = listener.Accept(); - Client client1(clientSocket); - cout << "First client connected." << endl; - - //Accept a client - clientSocket = listener.Accept(); - Client client2(clientSocket); - cout << "Second client connected." << endl; -*/ - - /* ProtocolSet* set = new ProtocolSet; - ProtocolTest test; - test.clientID = 0; - test.size = 2; - test.textMessage = "hej"; - test.numOfFloats = 35; - test.f = new float[test.numOfFloats]; - float temp = 395.456f; - for(int i = 0; i < (int)test.numOfFloats; i++) - { - test.f[i] = temp; - temp--; - } - t.Pack(test, recvBuffer);*/ - - -/* client1.Send(recvBuffer); while(1) From 3c681352da896cfa68a95f2438f686c60bad2574 Mon Sep 17 00:00:00 2001 From: Sam Mario Svensson Date: Fri, 29 Nov 2013 09:18:58 +0100 Subject: [PATCH 61/67] Documentation of the code done by Sam --- Code/Misc/IQueue.h | 4 ++++ Code/Misc/ThreadSafeQueue.h | 4 +++- Code/Network/NetworkDependencies/Connection.h | 2 ++ Code/Network/NetworkDependencies/IConnection.h | 14 +++++++++++++- Code/Network/NetworkDependencies/ITranslate.h | 1 + Code/Network/NetworkDependencies/Protocols.h | 10 +++++++--- 6 files changed, 30 insertions(+), 5 deletions(-) diff --git a/Code/Misc/IQueue.h b/Code/Misc/IQueue.h index 8ddc28a9..fc85800e 100644 --- a/Code/Misc/IQueue.h +++ b/Code/Misc/IQueue.h @@ -13,6 +13,10 @@ namespace Oyster class IQueue { public: + + //--------------------------------------------- + //standard operations of the std::queue + //--------------------------------------------- virtual ~IQueue() {}; virtual void Push( Type item ) = 0; virtual Type Pop() = 0; diff --git a/Code/Misc/ThreadSafeQueue.h b/Code/Misc/ThreadSafeQueue.h index 019485ce..d0125f71 100644 --- a/Code/Misc/ThreadSafeQueue.h +++ b/Code/Misc/ThreadSafeQueue.h @@ -3,7 +3,9 @@ //////////////////////////////////////////// // Thread safe queue implemented -// with single linked list. +// with single linked list and template. +// uses mutex to lock the queue +// otherwise its a standard queue // Created by Sam Svensson 2013 ///////////////////////////////////////////// diff --git a/Code/Network/NetworkDependencies/Connection.h b/Code/Network/NetworkDependencies/Connection.h index c69bb0f5..b46ccb02 100644 --- a/Code/Network/NetworkDependencies/Connection.h +++ b/Code/Network/NetworkDependencies/Connection.h @@ -20,6 +20,7 @@ namespace Oyster Connection( int socket ) { this->socket = socket; }; virtual ~Connection(); + virtual int InitiateServer( unsigned short port ); virtual int InitiateClient(); @@ -28,6 +29,7 @@ namespace Oyster virtual int Disconnect(); virtual int Connect( unsigned short port , const char serverName[] ); + virtual int Listen(); private: diff --git a/Code/Network/NetworkDependencies/IConnection.h b/Code/Network/NetworkDependencies/IConnection.h index 2ca895b1..5f88932b 100644 --- a/Code/Network/NetworkDependencies/IConnection.h +++ b/Code/Network/NetworkDependencies/IConnection.h @@ -14,13 +14,25 @@ namespace Oyster { public: - virtual int Disconnect() = 0; + + //sends and recieve functions with bytearrays, + //will send to the users connection via socket virtual int Send( OysterByte& bytes ) = 0; virtual int Recieve( OysterByte& bytes) = 0; + + //initiates sockets and address for server and client virtual int InitiateServer( unsigned short port ) { return false; }; virtual int InitiateClient() { return false; }; + + //Listen function to let client connect, only used by the server virtual int Listen() { return -1; }; + + //enables the client to connect with a server with use of name and port + //(servers uses Listen instead of connect) virtual int Connect( unsigned short port, const char serverName[] ) { return false; }; + + //Disconnects the client or server TODO: optimize! + virtual int Disconnect() = 0; }; } } diff --git a/Code/Network/NetworkDependencies/ITranslate.h b/Code/Network/NetworkDependencies/ITranslate.h index 90eb1431..80edc8b1 100644 --- a/Code/Network/NetworkDependencies/ITranslate.h +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -14,6 +14,7 @@ namespace Oyster { public: + //packs and unpacks packages for sending or recieving over the connection virtual void Pack (Protocols::ProtocolHeader &header, OysterByte& bytes) = 0; virtual void Unpack (Protocols::ProtocolSet* set, OysterByte& bytes ) = 0; diff --git a/Code/Network/NetworkDependencies/Protocols.h b/Code/Network/NetworkDependencies/Protocols.h index 12444e3e..8defcfb3 100644 --- a/Code/Network/NetworkDependencies/Protocols.h +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -1,9 +1,13 @@ #ifndef NETWORK_DEPENDENCIES_PROTOCOLS_H #define NETWORK_DEPENDENCIES_PROTOCOLS_H -////////////////////////////////// -// Created by Sam Svensson 2013 // -////////////////////////////////// +////////////////////////////////////// +// Created by Sam Svensson 2013 +// Holder structs for our protocols +// with the use of union. +// each packagetyp +// is linked to a protocol +////////////////////////////////////// #include From de01d23d1d3cf9c0ba583446537430c9ad037956 Mon Sep 17 00:00:00 2001 From: dean11 Date: Fri, 29 Nov 2013 09:23:08 +0100 Subject: [PATCH 62/67] Fixed some structure issues and commented --- Code/Misc/Misc.vcxproj | 2 - Code/Misc/Resource/OResource.h | 2 +- Code/Misc/Thread/OysterThread_Impl.cpp | 15 ++- Code/Misc/Utilities-Impl.h | 177 +++++++++++++------------ Code/Misc/Utilities.h | 108 ++++++++------- 5 files changed, 153 insertions(+), 151 deletions(-) diff --git a/Code/Misc/Misc.vcxproj b/Code/Misc/Misc.vcxproj index 82888770..beb55abe 100644 --- a/Code/Misc/Misc.vcxproj +++ b/Code/Misc/Misc.vcxproj @@ -152,7 +152,6 @@ - @@ -162,7 +161,6 @@ - diff --git a/Code/Misc/Resource/OResource.h b/Code/Misc/Resource/OResource.h index 3b0d0c17..a0573c92 100644 --- a/Code/Misc/Resource/OResource.h +++ b/Code/Misc/Resource/OResource.h @@ -61,7 +61,7 @@ namespace Oyster static OResource* Reload (OResource* resource); static bool Release (OResource* resource); - Utility::DynamicMemory::RefCount resourceRef; + Utility::DynamicMemory::ReferenceCount resourceRef; private: static OResource* ByteLoader (const wchar_t filename[], ResourceType type, OResource* old = 0); diff --git a/Code/Misc/Thread/OysterThread_Impl.cpp b/Code/Misc/Thread/OysterThread_Impl.cpp index 46b889fe..9605dd78 100644 --- a/Code/Misc/Thread/OysterThread_Impl.cpp +++ b/Code/Misc/Thread/OysterThread_Impl.cpp @@ -10,14 +10,14 @@ #include using namespace Oyster::Thread; -using namespace Utility::DynamicMemory::SmartPointer; +using namespace Utility::DynamicMemory; #pragma region Declerations struct ThreadData; /** A typical Oyster thread function */ - typedef void (*ThreadFunction)(StdSmartPointer&); + typedef void (*ThreadFunction)(SmartPointer&); enum OYSTER_THREAD_STATE { @@ -32,12 +32,13 @@ using namespace Utility::DynamicMemory::SmartPointer; struct ThreadData { std::atomic state; // workerThread; // workerThread; // msec; // threadData; + SmartPointer threadData; PrivateData() :threadData(new ThreadData()) @@ -76,11 +77,11 @@ using namespace Utility::DynamicMemory::SmartPointer; int tempId = 0; std::vector IDS; -static void ThreadingFunction(StdSmartPointer &origin) +static void ThreadingFunction(SmartPointer &origin) { bool shouldContinue; - StdSmartPointer w = origin; + SmartPointer w = origin; theBegining: diff --git a/Code/Misc/Utilities-Impl.h b/Code/Misc/Utilities-Impl.h index 655f06c5..cc82c959 100644 --- a/Code/Misc/Utilities-Impl.h +++ b/Code/Misc/Utilities-Impl.h @@ -35,6 +35,7 @@ namespace Utility } } +#pragma region UnuiqePointer template UniquePointer::UniquePointer( Type *assignedInstance ) { @@ -191,110 +192,114 @@ namespace Utility { return this->operator bool(); } - - namespace SmartPointer +#pragma endregion + +#pragma region SmartPointer + template void SmartPointer::Destroy() { - template void StdSmartPointer::Destroy() - { - delete this->_rc; - this->_rc = NULL; - delete this->_ptr; - this->_ptr = NULL; - } - template StdSmartPointer::StdSmartPointer() - :_rc(0), _ptr(0) - { } - template StdSmartPointer::StdSmartPointer(T* p) - :_ptr(p) - { - this->_rc = new ReferenceCount(); + delete this->_rc; + this->_rc = NULL; + + //Use default function for memory deallocation. + SafeDeleteInstance(this->_ptr); + + this->_ptr = NULL; + } + template SmartPointer::SmartPointer() + :_rc(0), _ptr(0) + { } + template SmartPointer::SmartPointer(T* p) + :_ptr(p) + { + this->_rc = new ReferenceCount(); + this->_rc->Incref(); + } + template SmartPointer::SmartPointer(const SmartPointer& d) + :_ptr(d._ptr), _rc(d._rc) + { + if(this->_rc) this->_rc->Incref(); - } - template StdSmartPointer::StdSmartPointer(const StdSmartPointer& d) - :_ptr(d._ptr), _rc(d._rc) + } + template SmartPointer::~SmartPointer() + { + if (this->_rc && this->_rc->Decref() == 0) { - if(this->_rc) - this->_rc->Incref(); + Destroy(); } - template StdSmartPointer::~StdSmartPointer() + } + template SmartPointer& SmartPointer::operator= (const SmartPointer& p) + { + if (this != &p) { - if (this->_rc && this->_rc->Decref() == 0) + //Last to go? + if(this->_rc && this->_rc->Decref() == 0) { + //Call child specific Destroy(); } + + this->_ptr = p._ptr; + this->_rc = p._rc; + this->_rc->Incref(); } - template StdSmartPointer& StdSmartPointer::operator= (const StdSmartPointer& p) + return *this; + } + template SmartPointer& SmartPointer::operator= (T* p) + { + if (this->_ptr != p) { - if (this != &p) + //Last to go? + if(this->_rc) { - //Last to go? - if(this->_rc && this->_rc->Decref() == 0) + if(this->_rc->Decref() == 0) { //Call child specific Destroy(); - } - - this->_ptr = p._ptr; - this->_rc = p._rc; - this->_rc->Incref(); - } - return *this; - } - template StdSmartPointer& StdSmartPointer::operator= (T* p) - { - if (this->_ptr != p) - { - //Last to go? - if(this->_rc) - { - if(this->_rc->Decref() == 0) - { - //Call child specific - Destroy(); - this->_rc = new ReferenceCount(); - } - } - else this->_rc = new ReferenceCount(); - - this->_ptr = p; - this->_rc->Incref(); + } } - return *this; - } - template inline bool StdSmartPointer::operator== (const StdSmartPointer& d) - { - return d._ptr == this->_ptr; - } - template inline bool StdSmartPointer::operator== (const T& p) - { - return &p == this->_ptr; - } - template inline T& StdSmartPointer::operator* () - { - return *this->_ptr; - } - template inline T* StdSmartPointer::operator-> () - { - return this->_ptr; - } - template inline StdSmartPointer::operator T* () - { - return this->_ptr; - } - template inline StdSmartPointer::operator bool() - { - return (this->_ptr != 0); - } - template inline T* StdSmartPointer::Get() - { - return this->_ptr; - } - template inline bool StdSmartPointer::IsValid() - { - return (this->_ptr != NULL) ? true : false; + else + this->_rc = new ReferenceCount(); + + this->_ptr = p; + this->_rc->Incref(); } + return *this; } + template inline bool SmartPointer::operator== (const SmartPointer& d) + { + return d._ptr == this->_ptr; + } + template inline bool SmartPointer::operator== (const T& p) + { + return &p == this->_ptr; + } + template inline T& SmartPointer::operator* () + { + return *this->_ptr; + } + template inline T* SmartPointer::operator-> () + { + return this->_ptr; + } + template inline SmartPointer::operator T* () + { + return this->_ptr; + } + template inline SmartPointer::operator bool() + { + return (this->_ptr != 0); + } + template inline T* SmartPointer::Get() + { + return this->_ptr; + } + template inline bool SmartPointer::IsValid() + { + return (this->_ptr != NULL) ? true : false; + } +#pragma endregion + } } diff --git a/Code/Misc/Utilities.h b/Code/Misc/Utilities.h index 6f5cf3ab..ec8b0229 100644 --- a/Code/Misc/Utilities.h +++ b/Code/Misc/Utilities.h @@ -31,6 +31,22 @@ namespace Utility ******************************************************************/ template void SafeDeleteArray( Type dynamicArray[] ); + //! A simple reference counter with some extra functionality + struct ReferenceCount + { + private: + int count; + + public: + ReferenceCount() :count(0) { } + ReferenceCount(const ReferenceCount& o) { count = o.count; } + inline const ReferenceCount& operator=(const ReferenceCount& o) { count = o.count; return *this;} + inline void Incref() { this->count++; } + inline void Incref(int c) { this->count += c; } + inline int Decref() { return --this->count;} + inline void Reset() { this->count = 0; } + }; + //! Wrapper to safely transfer dynamic ownership/responsibility template struct UniquePointer { @@ -108,9 +124,9 @@ namespace Utility mutable Type *ownedInstance; }; - template - struct UniqueArray - { //! Wrapper to safely transfer dynamic ownership/responsibility + //! Wrapper to safely transfer dynamic ownership/responsibility + template struct UniqueArray + { public: /****************************************************************** * Assigns assignedInstance ownership to this UniquePonter, old owned array will be deleted. @@ -177,63 +193,40 @@ namespace Utility mutable Type *ownedArray; }; - struct ReferenceCount + //! Wrapper to manage references on a pointer. + template struct SmartPointer { private: - std::atomic count; + ReferenceCount *_rc; + T *_ptr; + + /** Destroys the pointer and returns the memory allocated. */ + void Destroy(); public: - ReferenceCount() :count(0) { } - ReferenceCount(const ReferenceCount& o) { count.store(o.count); } - inline const ReferenceCount& operator=(const ReferenceCount& o) { count.store(o.count); return *this;} - inline void Incref() { this->count++; } - inline void Incref(int c) { this->count += c; } - inline int Decref() { return --this->count;} - inline void Reset() { this->count = 0; } + SmartPointer(); + SmartPointer(T* p); + SmartPointer(const SmartPointer& d); + virtual~SmartPointer(); + SmartPointer& operator= (const SmartPointer& p); + SmartPointer& operator= (T* p); + bool operator== (const SmartPointer& d); + bool operator== (const T& p); + T& operator* (); + T* operator-> (); + operator T* (); + operator bool(); + + /** + * Returns the connected pointer + */ + T* Get(); + + /** Checks if the pointer is valid (not NULL) + * Returns true for valid, else false. + */ + bool IsValid(); }; - - namespace SmartPointer - { - //! Smart pointer for a regular object. - /** - * Regular objects, objects that is deleted normaly (ie not COM objects, or array pointers) - * can use this class to easy the use of dynamic memory - */ - template - struct StdSmartPointer - { - private: - ReferenceCount *_rc; - T *_ptr; - - /** Destroys the pointer and returns the memory allocated. */ - void Destroy(); - - public: - StdSmartPointer(); - StdSmartPointer(T* p); - StdSmartPointer(const StdSmartPointer& d); - virtual~StdSmartPointer(); - StdSmartPointer& operator= (const StdSmartPointer& p); - StdSmartPointer& operator= (T* p); - bool operator== (const StdSmartPointer& d); - bool operator== (const T& p); - T& operator* (); - T* operator-> (); - operator T* (); - operator bool(); - - /** - * Returns the connected pointer */ - T* Get(); - - /** Checks if the pointer is valid (not NULL) - Returns true for valid, else false. */ - bool IsValid(); - }; - } - - } namespace String @@ -379,6 +372,11 @@ namespace Utility template<> inline unsigned long long AverageWithDelta( const unsigned long long &origin, const unsigned long long &delta ) { return origin + (delta >> 1); } } + + namespace Thread + { + //Utilities for threading + } } #include "Utilities-Impl.h" From ec7185f463a66df47d2a102e6bc6704f8b4521ff Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 17:59:12 +0100 Subject: [PATCH 63/67] Bunch of implementations --- Code/GamePhysics/GamePhysics.vcxproj.filters | 2 +- Code/GamePhysics/Implementation/Octree.cpp | 60 ++++++++- Code/GamePhysics/Implementation/Octree.h | 10 +- .../Implementation/PhysicsAPI_Impl.cpp | 123 +++++++++++++----- .../Implementation/PhysicsAPI_Impl.h | 4 +- Code/GamePhysics/PhysicsAPI.h | 2 +- 6 files changed, 158 insertions(+), 43 deletions(-) diff --git a/Code/GamePhysics/GamePhysics.vcxproj.filters b/Code/GamePhysics/GamePhysics.vcxproj.filters index 72b83568..694a8ec7 100644 --- a/Code/GamePhysics/GamePhysics.vcxproj.filters +++ b/Code/GamePhysics/GamePhysics.vcxproj.filters @@ -51,7 +51,7 @@ Source Files - Header Files\Implementation + Source Files \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/Octree.cpp b/Code/GamePhysics/Implementation/Octree.cpp index 6a6416b8..baa431da 100644 --- a/Code/GamePhysics/Implementation/Octree.cpp +++ b/Code/GamePhysics/Implementation/Octree.cpp @@ -2,6 +2,9 @@ using namespace Oyster; using namespace Physics; +using namespace ::Utility::DynamicMemory; + +const unsigned int Octree::invalid_ref = ::Utility::Value::numeric_limits::max(); Octree::Octree(unsigned int bufferSize, unsigned char numLayers, Math::Float3 worldSize) { @@ -26,7 +29,7 @@ Octree& Octree::operator=(const Octree& orig) return *this; } -void Octree::AddObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +void Octree::AddObject(UniquePointer< ICustomBody > customBodyRef) { Data data; //Data* tempPtr = this->worldNode.dataPtr; @@ -54,15 +57,15 @@ void Octree::AddObject(Utility::DynamicMemory::UniquePointer< ICustomBody > cust }*/ } -void Octree::MoveToUpdateQueue(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +void Octree::MoveToUpdateQueue(UniquePointer< ICustomBody > customBodyRef) { /*this->leafData[this->mapReferences[customBodyRef]].queueRef = this->updateQueue.size(); this->updateQueue.push_back(&this->leafData[this->mapReferences[customBodyRef]]);*/ } -void Octree::DestroyObject(Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef) +void Octree::DestroyObject(UniquePointer< ICustomBody > customBodyRef) { - std::map::iterator it = this->mapReferences.find(customBodyRef); + std::map::iterator it = this->mapReferences.find(customBodyRef); this->mapReferences.erase(it); @@ -116,4 +119,53 @@ void Octree::Visit(ICustomBody* customBodyRef, VistorAction hitAction ) ICustomBody* Octree::GetCustomBody(const unsigned int tempRef) { return this->leafData[tempRef].customBodyRef; +} + +UniquePointer Octree::Extract( const ICustomBody* objRef ) +{ // Dan Andersson + auto iter = this->mapReferences.find( objRef ); + if( iter != this->mapReferences.end() ) + { + return this->Extract( iter->second ); + } + else + { + return NULL; + } +} + +UniquePointer Octree::Extract( unsigned int tempRef ) +{ + if( tempRef != Octree::invalid_ref ) + { + //! @todo TODO: implement stub + return NULL; + } + else + { + return NULL; + } +} + +unsigned int Octree::GetTemporaryReferenceOf( const ICustomBody* objRef ) const +{ // Dan Andersson + auto iter = this->mapReferences.find( objRef ); + if( iter != this->mapReferences.end() ) + { + return iter->second; + } + else + { + return Octree::invalid_ref; + } +} + +void Octree::SetAsAltered( unsigned int tempRef ) +{ + //! @todo TODO: implement stub +} + +void Octree::EvaluatePosition( unsigned int tempRef ) +{ + //! @todo TODO: implement stub } \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/Octree.h b/Code/GamePhysics/Implementation/Octree.h index 8d111329..5ef3b0a8 100644 --- a/Code/GamePhysics/Implementation/Octree.h +++ b/Code/GamePhysics/Implementation/Octree.h @@ -15,6 +15,8 @@ namespace Oyster class Octree { public: + static const unsigned int invalid_ref; + typedef void(*VistorAction)(Octree&, unsigned int, unsigned int); struct Data @@ -52,11 +54,17 @@ namespace Oyster ICustomBody* GetCustomBody(const unsigned int tempRef); + ::Utility::DynamicMemory::UniquePointer Extract( const ICustomBody* objRef ); + ::Utility::DynamicMemory::UniquePointer Extract( unsigned int tempRef ); // Dan vill ha + unsigned int GetTemporaryReferenceOf( const ICustomBody* objRef ) const; // Dan vill ha + void SetAsAltered( unsigned int tempRef ); // Dan vill ha + void EvaluatePosition( unsigned int tempRef ); // Dan vill ha + private: std::vector < Data > leafData; std::vector < Data* > updateQueue; - std::map< ICustomBody*, unsigned int > mapReferences; + std::map< const ICustomBody*, unsigned int > mapReferences; OctreeNode worldNode; }; diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp index 6c9b212a..0374704f 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp @@ -42,21 +42,24 @@ API & API::Instance() } API_Impl::API_Impl() - : gravityConstant( Constant::gravity_constant ), - updateFrameLength( 1.0f / 120.0f ), - destructionAction( Default::EventAction_Destruction ) -{} +{ + this->gravityConstant = Constant::gravity_constant; + this->updateFrameLength = 1.0f / 120.0f; + this->destructionAction = Default::EventAction_Destruction; + this->worldScene = Octree(); +} API_Impl::~API_Impl() {} void API_Impl::Init( unsigned int numObjects, unsigned int numGravityWells , const Float3 &worldSize ) { - //! @todo TODO: implement stub + unsigned char numLayers = 4; //!< @todo TODO: calc numLayers from worldSize + this->worldScene = Octree( numObjects, numLayers, worldSize ); } -void API_Impl::SetDeltaTime( float deltaTime ) +void API_Impl::SetFrameTimeLength( float deltaTime ) { - updateFrameLength = deltaTime; + this->updateFrameLength = deltaTime; } void API_Impl::SetGravityConstant( float g ) @@ -98,68 +101,117 @@ void API_Impl::ReleaseFromLimbo( const ICustomBody* objRef ) void API_Impl::AddObject( ::Utility::DynamicMemory::UniquePointer handle ) { - /** @todo TODO: Fix this function.*/ + this->worldScene.AddObject( handle ); } -::Utility::DynamicMemory::UniquePointer API_Impl::ExtractObject( const ICustomBody* objRef ) +UniquePointer API_Impl::ExtractObject( const ICustomBody* objRef ) { - //! @todo TODO: implement stub - return NULL; + return this->worldScene.Extract( objRef ); } void API_Impl::DestroyObject( const ICustomBody* objRef ) { - /** @todo TODO: Fix this function.*/ + UniquePointer object = this->worldScene.Extract( objRef ); + if( object != NULL ) + { + this->destructionAction( object ); + } } void API_Impl::ApplyForceAt( const ICustomBody* objRef, const Float3 &worldPos, const Float3 &worldF ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + //this->worldScene.GetCustomBody( tempRef )->Apply //!< @todo TODO: need function + this->worldScene.SetAsAltered( tempRef ); + } } void API_Impl::ApplyCollisionResponse( const ICustomBody* objRefA, const ICustomBody* objRefB, Float &deltaWhen, Float3 &worldPointOfContact ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRefA ); + if( tempRef != this->worldScene.invalid_ref ) + { + //! @todo TODO: implement stub + this->worldScene.SetAsAltered( tempRef ); + } } void API_Impl::SetMomentOfInertiaTensor_KeepVelocity( const ICustomBody* objRef, const Float4x4 &localI ) -{ - //! @todo TODO: implement stub +{ // deprecated + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetMomentOfInertiaTensor_KeepVelocity( localI ); + } } void API_Impl::SetMomentOfInertiaTensor_KeepMomentum( const ICustomBody* objRef, const Float4x4 &localI ) -{ - //! @todo TODO: implement stub +{ // deprecated + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetMomentOfInertiaTensor_KeepMomentum( localI ); + } } void API_Impl::SetMass_KeepVelocity( const ICustomBody* objRef, Float m ) -{ - //! @todo TODO: implement stub +{ // deprecated + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetMass_KeepVelocity( m ); + } } void API_Impl::SetMass_KeepMomentum( const ICustomBody* objRef, Float m ) -{ - //! @todo TODO: implement stub +{ // deprecated + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetMass_KeepMomentum( m ); + } } void API_Impl::SetCenter( const ICustomBody* objRef, const Float3 &worldPos ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + //this->worldScene.GetCustomBody( tempRef )->Set //!< @todo TODO: need function + this->worldScene.EvaluatePosition( tempRef ); + } } void API_Impl::SetRotation( const ICustomBody* objRef, const Float4x4 &rotation ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetRotation( rotation ); + this->worldScene.EvaluatePosition( tempRef ); + } } void API_Impl::SetOrientation( const ICustomBody* objRef, const Float4x4 &orientation ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetOrientation( orientation ); + this->worldScene.EvaluatePosition( tempRef ); + } } void API_Impl::SetSize( const ICustomBody* objRef, const Float3 &size ) { - //! @todo TODO: implement stub + unsigned int tempRef = this->worldScene.GetTemporaryReferenceOf( objRef ); + if( tempRef != this->worldScene.invalid_ref ) + { + this->worldScene.GetCustomBody( tempRef )->SetSize( size ); + this->worldScene.EvaluatePosition( tempRef ); + } } UniquePointer API_Impl::CreateRigidBody( const API::SimpleBodyDescription &desc ) const @@ -172,15 +224,16 @@ UniquePointer API_Impl::CreateRigidBody( const API::SphericalBodyDe return new SphericalRigidBody( desc ); } -namespace Oyster { namespace Physics { namespace Default +namespace Oyster { namespace Physics { + namespace Default + { + void EventAction_Destruction( ::Utility::DynamicMemory::UniquePointer<::Oyster::Physics::ICustomBody> proto ) + { /* Do nothing except allowing the proto uniquePointer destroy itself. */ } - void EventAction_Destruction( ::Utility::DynamicMemory::UniquePointer<::Oyster::Physics::ICustomBody> proto ) - { /* Do nothing except allowing the proto uniquePointer destroy itself. */ } - - ::Oyster::Physics::ICustomBody::SubscriptMessage EventAction_Collision( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter ) - { /* Do nothing except returning business as usual. */ - return ::Oyster::Physics::ICustomBody::SubscriptMessage_none; + ::Oyster::Physics::ICustomBody::SubscriptMessage EventAction_Collision( const ::Oyster::Physics::ICustomBody *proto, const ::Oyster::Physics::ICustomBody *deuter ) + { /* Do nothing except returning business as usual. */ + return ::Oyster::Physics::ICustomBody::SubscriptMessage_none; + } } - -} } } \ No newline at end of file +} } \ No newline at end of file diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h index 7d6858f0..5de9c05a 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.h @@ -2,6 +2,7 @@ #define PHYSICS_API_IMPL_H #include "../PhysicsAPI.h" +#include "Octree.h" namespace Oyster { @@ -15,7 +16,7 @@ namespace Oyster void Init( unsigned int numObjects, unsigned int numGravityWells , const ::Oyster::Math::Float3 &worldSize ); - void SetDeltaTime( float deltaTime ); + void SetFrameTimeLength( float deltaTime ); void SetGravityConstant( float g ); void SetSubscription( EventAction_Destruction functionPointer ); @@ -47,6 +48,7 @@ namespace Oyster private: ::Oyster::Math::Float gravityConstant, updateFrameLength; EventAction_Destruction destructionAction; + Octree worldScene; }; namespace Default diff --git a/Code/GamePhysics/PhysicsAPI.h b/Code/GamePhysics/PhysicsAPI.h index 6cba993c..5d44b695 100644 --- a/Code/GamePhysics/PhysicsAPI.h +++ b/Code/GamePhysics/PhysicsAPI.h @@ -64,7 +64,7 @@ namespace Oyster /******************************************************** * Sets the time length of each physics update frame. ********************************************************/ - virtual void SetDeltaTime( float seconds ) = 0; + virtual void SetFrameTimeLength( float seconds ) = 0; /******************************************************** * Sets the Gravityconstant in the physics that will be From 5d5f684ad664b09c0502a3f78e72cd6641b1a460 Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Thu, 28 Nov 2013 18:05:19 +0100 Subject: [PATCH 64/67] minor compilation error fix Forgot that UniquePointer had a special operator for checking if it is not NULL >.< --- Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp index 0374704f..ed8f8eed 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp @@ -112,7 +112,7 @@ UniquePointer API_Impl::ExtractObject( const ICustomBody* objRef ) void API_Impl::DestroyObject( const ICustomBody* objRef ) { UniquePointer object = this->worldScene.Extract( objRef ); - if( object != NULL ) + if( object ) { this->destructionAction( object ); } From c31ea9730b9d989cc71a434e12eb4a56f6fa36cc Mon Sep 17 00:00:00 2001 From: Robin Engman Date: Fri, 29 Nov 2013 09:03:37 +0100 Subject: [PATCH 65/67] Added overloads for visitor and sample functions They now have an overload for accepting ICollideable --- Code/GamePhysics/Implementation/Octree.cpp | 34 ++++++++++++++++++---- Code/GamePhysics/Implementation/Octree.h | 4 ++- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/Code/GamePhysics/Implementation/Octree.cpp b/Code/GamePhysics/Implementation/Octree.cpp index baa431da..70d2842a 100644 --- a/Code/GamePhysics/Implementation/Octree.cpp +++ b/Code/GamePhysics/Implementation/Octree.cpp @@ -72,15 +72,13 @@ void Octree::DestroyObject(UniquePointer< ICustomBody > customBodyRef) this->leafData.erase(this->leafData.begin() + this->leafData[this->mapReferences[customBodyRef]].queueRef); } -std::vector Octree::Sample(ICustomBody* customBodyRef) +std::vector& Octree::Sample(ICustomBody* customBodyRef, std::vector& updateList) { - std::vector list; - auto object = this->mapReferences.find(customBodyRef); if(object == this->mapReferences.end()) { - return list; + return updateList; } unsigned int tempRef = object->second; @@ -89,11 +87,24 @@ std::vector Octree::Sample(ICustomBody* customBodyRef) { if(tempRef != i) if(this->leafData[tempRef].container.Intersects(this->leafData[i].container)) { - list.push_back(this->leafData[i].customBodyRef); + updateList.push_back(this->leafData[i].customBodyRef); } } - return list; + return updateList; +} + +std::vector& Octree::Sample(::Collision3D::ICollideable* collideable, std::vector& updateList) +{ + for(unsigned int i = 0; ileafData.size(); i++) + { + if(this->leafData[i].container.Intersects(*collideable)) + { + updateList.push_back(this->leafData[i].customBodyRef); + } + } + + return updateList; } void Octree::Visit(ICustomBody* customBodyRef, VistorAction hitAction ) @@ -116,6 +127,17 @@ void Octree::Visit(ICustomBody* customBodyRef, VistorAction hitAction ) } } +void Octree::Visit(::Collision3D::ICollideable* collideable, VistorAction hitAction) +{ + for(unsigned int i = 0; ileafData.size(); i++) + { + if(this->leafData[i].container.Intersects(*collideable)) + { + //hitAction(*this, tempRef, i); // @todo TODO: Add typedef to handle function calls with ICollideable + } + } +} + ICustomBody* Octree::GetCustomBody(const unsigned int tempRef) { return this->leafData[tempRef].customBodyRef; diff --git a/Code/GamePhysics/Implementation/Octree.h b/Code/GamePhysics/Implementation/Octree.h index 5ef3b0a8..6340fa58 100644 --- a/Code/GamePhysics/Implementation/Octree.h +++ b/Code/GamePhysics/Implementation/Octree.h @@ -49,8 +49,10 @@ namespace Oyster void DestroyObject(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); - std::vector Sample(ICustomBody* customBodyRef); + std::vector& Sample(ICustomBody* customBodyRef, std::vector& updateList); + std::vector& Sample(Oyster::Collision3D::ICollideable* collideable, std::vector& updateList); void Visit(ICustomBody* customBodyRef, VistorAction hitAction ); + void Visit(Oyster::Collision3D::ICollideable* collideable, VistorAction hitAction ); ICustomBody* GetCustomBody(const unsigned int tempRef); From 1a06c7c7e6dfd674f4e639502c7765b856a62edc Mon Sep 17 00:00:00 2001 From: Robin Engman Date: Fri, 29 Nov 2013 09:07:52 +0100 Subject: [PATCH 66/67] Changed from pointer to reference Did it in sample and visit functions --- Code/GamePhysics/Implementation/Octree.cpp | 8 ++++---- Code/GamePhysics/Implementation/Octree.h | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Code/GamePhysics/Implementation/Octree.cpp b/Code/GamePhysics/Implementation/Octree.cpp index 70d2842a..1da6045b 100644 --- a/Code/GamePhysics/Implementation/Octree.cpp +++ b/Code/GamePhysics/Implementation/Octree.cpp @@ -94,11 +94,11 @@ std::vector& Octree::Sample(ICustomBody* customBodyRef, std::vecto return updateList; } -std::vector& Octree::Sample(::Collision3D::ICollideable* collideable, std::vector& updateList) +std::vector& Octree::Sample(const Oyster::Collision3D::ICollideable& collideable, std::vector& updateList) { for(unsigned int i = 0; ileafData.size(); i++) { - if(this->leafData[i].container.Intersects(*collideable)) + if(this->leafData[i].container.Intersects(collideable)) { updateList.push_back(this->leafData[i].customBodyRef); } @@ -127,11 +127,11 @@ void Octree::Visit(ICustomBody* customBodyRef, VistorAction hitAction ) } } -void Octree::Visit(::Collision3D::ICollideable* collideable, VistorAction hitAction) +void Octree::Visit(const Oyster::Collision3D::ICollideable& collideable, VistorAction hitAction) { for(unsigned int i = 0; ileafData.size(); i++) { - if(this->leafData[i].container.Intersects(*collideable)) + if(this->leafData[i].container.Intersects(collideable)) { //hitAction(*this, tempRef, i); // @todo TODO: Add typedef to handle function calls with ICollideable } diff --git a/Code/GamePhysics/Implementation/Octree.h b/Code/GamePhysics/Implementation/Octree.h index 6340fa58..96631605 100644 --- a/Code/GamePhysics/Implementation/Octree.h +++ b/Code/GamePhysics/Implementation/Octree.h @@ -50,9 +50,9 @@ namespace Oyster void DestroyObject(::Utility::DynamicMemory::UniquePointer< ICustomBody > customBodyRef); std::vector& Sample(ICustomBody* customBodyRef, std::vector& updateList); - std::vector& Sample(Oyster::Collision3D::ICollideable* collideable, std::vector& updateList); + std::vector& Sample(const Oyster::Collision3D::ICollideable& collideable, std::vector& updateList); void Visit(ICustomBody* customBodyRef, VistorAction hitAction ); - void Visit(Oyster::Collision3D::ICollideable* collideable, VistorAction hitAction ); + void Visit(const Oyster::Collision3D::ICollideable& collideable, VistorAction hitAction ); ICustomBody* GetCustomBody(const unsigned int tempRef); From 026b427deb906d291306d8cb4c183f21510033ee Mon Sep 17 00:00:00 2001 From: Dander7BD Date: Fri, 29 Nov 2013 09:21:44 +0100 Subject: [PATCH 67/67] Implemented a temporary collision test update Will only call the subscribed CollisioEventAction whenevera collision is detected. --- Bin/DLL/GamePhysics_x86D.exp | Bin 4647 -> 0 bytes .../Implementation/PhysicsAPI_Impl.cpp | 37 +++++++++++++++++- .../Implementation/SimpleRigidBody.cpp | 5 +++ .../Implementation/SimpleRigidBody.h | 1 + .../Implementation/SphericalRigidBody.cpp | 5 +++ .../Implementation/SphericalRigidBody.h | 2 +- Code/GamePhysics/PhysicsAPI.h | 5 +++ 7 files changed, 52 insertions(+), 3 deletions(-) delete mode 100644 Bin/DLL/GamePhysics_x86D.exp diff --git a/Bin/DLL/GamePhysics_x86D.exp b/Bin/DLL/GamePhysics_x86D.exp deleted file mode 100644 index 0cea5aa656b285c7e0ab517de7be488640d073f4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4647 zcmeHKOK%%h6h3LvI*&dQ-tU?cXi_R;CvKcVDvuwKM%YQ3P*b51VdA+-MmQd8WPfQo(0^ytXZtxAttK zY_HX4XYw(^W{JY8AZvmIe6%B9T9N+w&1C#DqTjj*6A^4Epjj_sJ+SySIT zIMqSHGG(IOs)|^Z`)gQ^%Z;dHyBs*OOhz79>+vPS67DmlXl{$Dv$U~L6_#UY?GC(6 zrL|PMRn24-oaMDt*fL~H&JvmsZZXGMCfiZgjGqREkQ$s0z)> zR5r!Br721ggDwNB&*M2JJl}*T`w3vbWKkfuw+M{`(a6BKA3iKu1;~vpLT7=GNLG`` zS{&?Ax#s`}B})PyldKLLl57_ExMc4Ehb5Z>@+u|`F3_LDb0T`9+6W|HSmVr-8_9<{wve$s8B>Mu$-8e#5fX_(wHSj*kR3M*` z2z>**U$VD=&r0?!@BztmAp1gut^*&GYzuf=vYWt%BpU$!iSG+I#Rcl)!jyYa&6g6% zR7#yUoal13g_ep22o)P@%$x$XufpmbjLn(9#aP0DPaZL`OO7P zN)J zpOU0Y=$oyX&(ZfjWrl{)CR<}tB7t1TOKHYF)7gnSD6nePC)rGp!^t6ehVl= zyfkmPwdMkf9Z;?Xlpg}hsGCmac4;-B{1Q-3H=Wo!8&~gAZelOQ&RX9o_IIntersects(*deuter, 1.0f, deltaWhen, worldWhere) ) + { + proto->CallSubscription( proto, deuter ); + } + } +} + Float4x4 & MomentOfInertia::CreateSphereMatrix( const Float mass, const Float radius) { return Formula::MomentOfInertia::Sphere(mass, radius); @@ -80,8 +96,25 @@ void API_Impl::SetSubscription( API::EventAction_Destruction functionPointer ) } void API_Impl::Update() -{ - /** @todo TODO: Fix this function.*/ +{ /** @todo TODO: Update is a temporary solution .*/ + ::std::vector updateList; + auto proto = this->worldScene.Sample( Universe(), updateList ).begin(); + for( ; proto != updateList.end(); ++proto ) + { + this->worldScene.Visit( *proto, OnPossibleCollision ); + } + + proto = updateList.begin(); + for( ; proto != updateList.end(); ++proto ) + { + switch( (*proto)->Update(this->updateFrameLength) ) + { + case UpdateState_altered: + this->worldScene.SetAsAltered( this->worldScene.GetTemporaryReferenceOf(*proto) ); + case UpdateState_resting: default: + break; + } + } } bool API_Impl::IsInLimbo( const ICustomBody* objRef ) diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp index 40a1b7ee..70bc6938 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.cpp @@ -42,6 +42,11 @@ UniquePointer SimpleRigidBody::Clone() const return new SimpleRigidBody( *this ); } +void SimpleRigidBody::CallSubscription( const ICustomBody *proto, const ICustomBody *deuter ) +{ + this->collisionAction( proto, deuter ); +} + bool SimpleRigidBody::IsAffectedByGravity() const { return !this->ignoreGravity; diff --git a/Code/GamePhysics/Implementation/SimpleRigidBody.h b/Code/GamePhysics/Implementation/SimpleRigidBody.h index c76f6a51..a674a20d 100644 --- a/Code/GamePhysics/Implementation/SimpleRigidBody.h +++ b/Code/GamePhysics/Implementation/SimpleRigidBody.h @@ -15,6 +15,7 @@ namespace Oyster { namespace Physics ::Utility::DynamicMemory::UniquePointer Clone() const; + void CallSubscription( const ICustomBody *proto, const ICustomBody *deuter ); bool IsAffectedByGravity() const; bool Intersects( const ICustomBody &object, ::Oyster::Math::Float timeStepLength, ::Oyster::Math::Float &deltaWhen, ::Oyster::Math::Float3 &worldPointOfContact ) const; bool Intersects( const ::Oyster::Collision3D::ICollideable &shape ) const; diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp index 292a2dd2..c741a68a 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.cpp +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.cpp @@ -44,6 +44,11 @@ UniquePointer SphericalRigidBody::Clone() const return new SphericalRigidBody( *this ); } +void SphericalRigidBody::CallSubscription( const ICustomBody *proto, const ICustomBody *deuter ) +{ + this->collisionAction( proto, deuter ); +} + bool SphericalRigidBody::IsAffectedByGravity() const { return !this->ignoreGravity; diff --git a/Code/GamePhysics/Implementation/SphericalRigidBody.h b/Code/GamePhysics/Implementation/SphericalRigidBody.h index 61f5d604..37263e91 100644 --- a/Code/GamePhysics/Implementation/SphericalRigidBody.h +++ b/Code/GamePhysics/Implementation/SphericalRigidBody.h @@ -16,7 +16,7 @@ namespace Oyster { namespace Physics ::Utility::DynamicMemory::UniquePointer Clone() const; - bool IsSubscribingCollisions() const; + void CallSubscription( const ICustomBody *proto, const ICustomBody *deuter ); bool IsAffectedByGravity() const; bool Intersects( const ICustomBody &object, ::Oyster::Math::Float timeStepLength, ::Oyster::Math::Float &deltaWhen, ::Oyster::Math::Float3 &worldPointOfContact ) const; bool Intersects( const ::Oyster::Collision3D::ICollideable &shape ) const; diff --git a/Code/GamePhysics/PhysicsAPI.h b/Code/GamePhysics/PhysicsAPI.h index 5d44b695..29014214 100644 --- a/Code/GamePhysics/PhysicsAPI.h +++ b/Code/GamePhysics/PhysicsAPI.h @@ -246,6 +246,11 @@ namespace Oyster ********************************************************/ virtual ::Utility::DynamicMemory::UniquePointer Clone() const = 0; + /******************************************************** + * @todo TODO: need doc + ********************************************************/ + virtual void CallSubscription( const ICustomBody *proto, const ICustomBody *deuter ) = 0; + /******************************************************** * @return true if Engine should apply gravity on this object. ********************************************************/