GL - merge with server

This commit is contained in:
lindaandersson 2014-01-31 09:14:55 +01:00
commit a6ff6eba42
19 changed files with 520 additions and 547 deletions

View File

@ -54,6 +54,7 @@ namespace DanBias
DanBiasClientReturn DanBiasGame::Initiate(DanBiasGameDesc& desc) DanBiasClientReturn DanBiasGame::Initiate(DanBiasGameDesc& desc)
{ {
WindowShell::CreateConsoleWindow();
if(! m_data->window->CreateWin(WindowShell::WINDOW_INIT_DESC())) if(! m_data->window->CreateWin(WindowShell::WINDOW_INIT_DESC()))
return DanBiasClientReturn_Error; return DanBiasClientReturn_Error;

View File

@ -1,316 +0,0 @@
//--------------------------------------------------------------------------------------
// File: TemplateMain.cpp
//
// BTH-D3D-Template
//
// Copyright (c) Stefan Petersson 2011. All rights reserved.
//--------------------------------------------------------------------------------------
#define NOMINMAX
#include <Windows.h>
#include <
#include "DllInterfaces/GFXAPI.h"
//#include "IGame.h"
#include "L_inputClass.h"
// debug window include
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
//--------------------------------------------------------------------------------------
// Global Variables
//--------------------------------------------------------------------------------------
HINSTANCE g_hInst = NULL;
HWND g_hWnd = NULL;
//GameLogic::IGame* game;
InputClass* inputObj;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow );
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
HRESULT Render(float deltaTime);
HRESULT Update(float deltaTime);
HRESULT InitDirect3D();
HRESULT InitGame();
HRESULT CleanUp();
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
void SetStdOutToNewConsole()
{
// allocate a console for this app
AllocConsole();
// redirect unbuffered STDOUT to the console
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
int fileDescriptor = _open_osfhandle((intptr_t)consoleHandle, _O_TEXT);
FILE *fp = _fdopen( fileDescriptor, "w" );
*stdout = *fp;
setvbuf( stdout, NULL, _IONBF, 0 );
// give the console window a nicer title
SetConsoleTitle(L"Debug Output");
// give the console window a bigger buffer size
CONSOLE_SCREEN_BUFFER_INFO csbi;
if ( GetConsoleScreenBufferInfo(consoleHandle, &csbi) )
{
COORD bufferSize;
bufferSize.X = csbi.dwSize.X;
bufferSize.Y = 50;
SetConsoleScreenBufferSize(consoleHandle, bufferSize);
}
}
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
// for dynamic .dll loading
// path is relative to the .exe and .dll pos
// also change the VC directories - working dir is set to $(SolutionDir)..\Bin\Executable\Tester
// to fit with where the .obj files is
// linker/ input/ delayed load .dll - specify the .dll that should be loaded
BOOL success = SetDllDirectory(L"..\\..\\DLL");
if (success == 0)
{
return 0;
}
if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
return 0;
if( FAILED( InitDirect3D() ) )
return 0;
if( FAILED( InitGame() ) )
return 0;
__int64 cntsPerSec = 0;
QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec);
float secsPerCnt = 1.0f / (float)cntsPerSec;
__int64 prevTimeStamp = 0;
QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp);
//debug window
//SetStdOutToNewConsole();
// Main message loop
MSG msg = {0};
while(WM_QUIT != msg.message)
{
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
{
__int64 currTimeStamp = 0;
QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp);
float dt = (currTimeStamp - prevTimeStamp) * secsPerCnt;
//render
Update(dt);
Render(dt);
prevTimeStamp = currTimeStamp;
}
}
CleanUp();
return (int) msg.wParam;
}
//--------------------------------------------------------------------------------------
// Register class and create window
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow )
{
// Register class
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = 0;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = L"BTH_D3D_Template";
wcex.hIconSm = 0;
if( !RegisterClassEx(&wcex) )
return E_FAIL;
// Adjust and create window
g_hInst = hInstance;
RECT rc = { 0, 0, 1024, 768 };
AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
if(!(g_hWnd = CreateWindow(
L"BTH_D3D_Template",
L"BTH - Direct3D 11.0 Template",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
rc.right - rc.left,
rc.bottom - rc.top,
NULL,
NULL,
hInstance,
NULL)))
{
return E_FAIL;
}
ShowWindow( g_hWnd, nCmdShow );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create Direct3D with Oyster Graphics
//--------------------------------------------------------------------------------------
HRESULT InitDirect3D()
{
if(Oyster::Graphics::API::Init(g_hWnd, false, false, Oyster::Math::Float2( 1024, 768)) != Oyster::Graphics::API::Sucsess)
return E_FAIL;
return S_OK;
}
//--------------------------------------------------------------------------------------
// Init the input and the game
//-------------------------------------------------------------------------------------
HRESULT InitGame()
{
inputObj = new InputClass;
if(!inputObj->Initialize(g_hInst, g_hWnd, 1024, 768))
{
MessageBox(0, L"Could not initialize the input object.", L"Error", MB_OK);
return false;
}
/*game = new GameLogic::IGame();
game->Init();
game->StartGame();
*/
return S_OK;
}
HRESULT Update(float deltaTime)
{
inputObj->Update();
//GameLogic::keyInput key = GameLogic::keyInput_none;
//if(inputObj->IsKeyPressed(DIK_W))
//{
// key = GameLogic::keyInput_W;
//}
//else if(inputObj->IsKeyPressed(DIK_A))
//{
// key = GameLogic::keyInput_A;
//}
//else if(inputObj->IsKeyPressed(DIK_S))
//{
// key = GameLogic::keyInput_S;
//}
//else if(inputObj->IsKeyPressed(DIK_D))
//{
// key = GameLogic::keyInput_D;
//}
float pitch = 0;
float yaw = 0;
//if(inputObj->IsMousePressed())
//{
pitch = inputObj->GetPitch();
yaw = inputObj->GetYaw();
//}
//game->Update(key, pitch, yaw);
return S_OK;
}
HRESULT Render(float deltaTime)
{
int isPressed = 0;
if(inputObj->IsKeyPressed(DIK_A))
{
isPressed = 1;
//std::cout<<"test";
}
//game->Render();
wchar_t title[255];
swprintf(title, sizeof(title), L"| Pressing A: %d | \n", (int)(isPressed));
SetWindowText(g_hWnd, title);
Oyster::Graphics::API::EndFrame();
return S_OK;
}
HRESULT CleanUp()
{
/*if(game)
{
delete game;
game = NULL;
}*/
return S_OK;
}
//--------------------------------------------------------------------------------------
// Called every time the application receives a message
//--------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_KEYDOWN:
switch(wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
break;
}
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}

View File

@ -5,8 +5,9 @@
namespace DanBias namespace DanBias
{ {
struct GameRecieverObject :public Oyster::Network::NetworkClient
{ struct GameRecieverObject :public Oyster::Network::NetworkClient
{
Client::GameClientState* gameClientState; Client::GameClientState* gameClientState;
// receiver function for server messages // receiver function for server messages
@ -104,7 +105,39 @@ struct GameRecieverObject :public Oyster::Network::NetworkClient
break; break;
} }
if(ProtocolIsLobby(p[0].value.netInt)) ParseLobbyProtocol(p);
} }
};
void ParseLobbyProtocol(Oyster::Network::CustomNetProtocol& p)
{
switch (p[0].value.netShort)
{
case protocol_General_Status: //this->GeneralStatus (Protocol_General_Status (p), c);
break;
case protocol_General_Text: //this->GeneralText (Protocol_General_Text (p), c);
break;
//case protocol_Lobby_Create: this->LobbyCreateGame (Protocol_LobbyCreateGame (p), c);
//break;
case protocol_Lobby_Start: //this->LobbyStartGame (Protocol_LobbyStartGame (p), c);
break;
//case protocol_Lobby_Join: this->LobbyJoin (Protocol_LobbyJoin (p), c);
//break;
case protocol_Lobby_Login: //this->LobbyLogin (Protocol_LobbyLogin (p), c);
break;
case protocol_Lobby_Refresh: //this->LobbyRefresh (Protocol_LobbyRefresh (p), c);
break;
case protocol_Lobby_GameData: //this->LobbyGameData (Protocol_LobbyGameData (p), c);
{
GameLogic::Protocol_LobbyGameData temp(p);
printf("%s, %i.%i\n", temp.mapName.c_str(), temp.majorVersion, temp.minorVersion);
}
break;
case protocol_Lobby_ClientData: //this->LobbyMainData (Protocol_LobbyClientData (p), c);
break;
//case protocol_Lobby_GameData: this->LobbyGameData (Protocol_LobbyGameData (p), c);
//break;
}
}
};
} }
#endif #endif

View File

@ -91,7 +91,8 @@ GameClientState::ClientState LobbyState::Update(float deltaTime, InputClass* Key
if( KeyInput->IsKeyPressed(DIK_G)) if( KeyInput->IsKeyPressed(DIK_G))
{ {
DanBias::GameServerAPI::GameStart(); if(!DanBias::GameServerAPI::GameStart())
return GameClientState::ClientState_Same;
return ClientState_Game; return ClientState_Game;
} }

View File

@ -128,8 +128,7 @@ bool Game::NewFrame()
if(this->players[i]->player) this->players[i]->player->EndFrame(); if(this->players[i]->player) this->players[i]->player->EndFrame();
} }
gameInstance.onMoveFnc(this->level);
//gameInstance.onMoveFnc(this->level);
return true; return true;
} }

View File

@ -158,8 +158,6 @@ namespace GameLogic
this->protocol[0].value = protocol_Lobby_ClientData; this->protocol[0].value = protocol_Lobby_ClientData;
this->protocol[0].type = Oyster::Network::NetAttributeType_Short; this->protocol[0].type = Oyster::Network::NetAttributeType_Short;
this->protocol[1].type = Oyster::Network::NetAttributeType_UnsignedInt; //DataType
list.Reserve(10); list.Reserve(10);
} }
Protocol_LobbyClientData(Oyster::Network::CustomNetProtocol& p) Protocol_LobbyClientData(Oyster::Network::CustomNetProtocol& p)
@ -229,7 +227,7 @@ namespace GameLogic
{ {
this->protocol[1].value = majorVersion; this->protocol[1].value = majorVersion;
this->protocol[2].value = minorVersion; this->protocol[2].value = minorVersion;
this->protocol[3].value.netCharPtr = const_cast<char*>(mapName.c_str()); this->protocol.Set(3, mapName.c_str());
return &protocol; return &protocol;
} }

View File

@ -8,7 +8,7 @@ namespace GameLogic
{ {
struct Protocol_ObjectPickup :public Oyster::Network::CustomProtocolObject struct Protocol_ObjectPickup :public Oyster::Network::CustomProtocolObject
{ {
int object_ID; short object_ID;
short pickup_ID; short pickup_ID;
Protocol_ObjectPickup() Protocol_ObjectPickup()
@ -16,7 +16,7 @@ namespace GameLogic
this->protocol[0].value = protocol_Gameplay_ObjectPickup; this->protocol[0].value = protocol_Gameplay_ObjectPickup;
this->protocol[0].type = Oyster::Network::NetAttributeType_Short; this->protocol[0].type = Oyster::Network::NetAttributeType_Short;
this->protocol[1].type = Oyster::Network::NetAttributeType_Int; this->protocol[1].type = Oyster::Network::NetAttributeType_Short;
this->protocol[2].type = Oyster::Network::NetAttributeType_Short; this->protocol[2].type = Oyster::Network::NetAttributeType_Short;
object_ID = -1; object_ID = -1;
@ -24,14 +24,15 @@ namespace GameLogic
} }
Protocol_ObjectPickup(Oyster::Network::CustomNetProtocol& p) Protocol_ObjectPickup(Oyster::Network::CustomNetProtocol& p)
{ {
object_ID = p[1].value.netShort;
pickup_ID = p[2].value.netShort;
} }
Protocol_ObjectPickup(int objectID, short pickupID) Protocol_ObjectPickup(int objectID, short pickupID)
{ {
this->protocol[0].value = protocol_Gameplay_ObjectPosition; this->protocol[0].value = protocol_Gameplay_ObjectPosition;
this->protocol[0].type = Oyster::Network::NetAttributeType_Short; this->protocol[0].type = Oyster::Network::NetAttributeType_Short;
this->protocol[1].type = Oyster::Network::NetAttributeType_Int; this->protocol[1].type = Oyster::Network::NetAttributeType_Short;
this->protocol[2].type = Oyster::Network::NetAttributeType_Short; this->protocol[2].type = Oyster::Network::NetAttributeType_Short;
object_ID = objectID; object_ID = objectID;

View File

@ -35,7 +35,10 @@ namespace GameLogic
} }
Protocol_PlayerMovement(Oyster::Network::CustomNetProtocol& p) Protocol_PlayerMovement(Oyster::Network::CustomNetProtocol& p)
{ {
bForward = p[1].value.netBool;
bBackward = p[2].value.netBool;
bLeft = p[3].value.netBool;
bRight = p[4].value.netBool;
} }
const Protocol_PlayerMovement& operator=(Oyster::Network::CustomNetProtocol& val) const Protocol_PlayerMovement& operator=(Oyster::Network::CustomNetProtocol& val)
{ {
@ -79,7 +82,9 @@ namespace GameLogic
} }
Protocol_PlayerLook(Oyster::Network::CustomNetProtocol& p) Protocol_PlayerLook(Oyster::Network::CustomNetProtocol& p)
{ {
lookDirX = p[1].value.netFloat;
lookDirY = p[2].value.netFloat;
lookDirZ = p[3].value.netFloat;
} }
const Protocol_PlayerLook& operator=(Oyster::Network::CustomNetProtocol& val) const Protocol_PlayerLook& operator=(Oyster::Network::CustomNetProtocol& val)
{ {
@ -111,11 +116,6 @@ namespace GameLogic
{ {
this->protocol[0].value = protocol_Gameplay_PlayerChangeWeapon; this->protocol[0].value = protocol_Gameplay_PlayerChangeWeapon;
this->protocol[0].type = Oyster::Network::NetAttributeType_Short; this->protocol[0].type = Oyster::Network::NetAttributeType_Short;
this->protocol[1].type = Oyster::Network::NetAttributeType_Float;
this->protocol[2].type = Oyster::Network::NetAttributeType_Float;
this->protocol[3].type = Oyster::Network::NetAttributeType_Float;
} }
Protocol_PlayerChangeWeapon(Oyster::Network::CustomNetProtocol& p) Protocol_PlayerChangeWeapon(Oyster::Network::CustomNetProtocol& p)
{ {
@ -147,7 +147,7 @@ namespace GameLogic
} }
Protocol_PlayerShot(Oyster::Network::CustomNetProtocol& p) Protocol_PlayerShot(Oyster::Network::CustomNetProtocol& p)
{ {
hasShot = p[1].value.netBool;
} }
const Protocol_PlayerShot& operator=(Oyster::Network::CustomNetProtocol& val) const Protocol_PlayerShot& operator=(Oyster::Network::CustomNetProtocol& val)
{ {
@ -177,7 +177,7 @@ namespace GameLogic
} }
Protocol_PlayerJump(Oyster::Network::CustomNetProtocol& p) Protocol_PlayerJump(Oyster::Network::CustomNetProtocol& p)
{ {
hasJumped = p[1].value.netBool;
} }
const Protocol_PlayerJump& operator=(Oyster::Network::CustomNetProtocol& val) const Protocol_PlayerJump& operator=(Oyster::Network::CustomNetProtocol& val)
{ {

View File

@ -26,6 +26,8 @@ namespace DanBias
Utility::DynamicMemory::SmartPointer<Oyster::Network::NetworkClient> ReleaseClient(); Utility::DynamicMemory::SmartPointer<Oyster::Network::NetworkClient> ReleaseClient();
int GetID() const; int GetID() const;
bool Equals(const Oyster::Network::NetworkClient* c);
private: private:
GameLogic::IPlayerData* player; GameLogic::IPlayerData* player;
Utility::DynamicMemory::SmartPointer<Oyster::Network::NetworkClient> client; Utility::DynamicMemory::SmartPointer<Oyster::Network::NetworkClient> client;

View File

@ -50,3 +50,9 @@ int GameClient::GetID() const
{ {
return this->id; return this->id;
} }
bool GameClient::Equals(const NetworkClient* c)
{
return (c->GetID() == this->client->GetID());
}

View File

@ -54,6 +54,8 @@ namespace DanBias
desc.owner = this; desc.owner = this;
desc.clients = this->clients; desc.clients = this->clients;
this->clients.Clear();
if(this->gameSession.Create(desc)) if(this->gameSession.Create(desc))
{ {
this->gameSession.Run(); this->gameSession.Run();

View File

@ -47,24 +47,80 @@ namespace DanBias
void GameSession::ClientEventCallback(NetEvent<NetworkClient*, NetworkClient::ClientEventArgs> e) void GameSession::ClientEventCallback(NetEvent<NetworkClient*, NetworkClient::ClientEventArgs> e)
{ {
int temp = -1;
//Find the idiot
for (unsigned int i = 0; i < this->clients.Size(); i++)
{
if(this->clients[i]->Equals(e.sender))
{
temp = i;
}
}
if(temp == -1)
{
this->Detach(e.sender)->Disconnect();
return;
}
SmartPointer<GameClient> cl = this->clients[temp];
switch (e.args.type)
{
case NetworkClient::ClientEventArgs::EventType_Disconnect:
break;
case NetworkClient::ClientEventArgs::EventType_ProtocolFailedToRecieve:
break;
case NetworkClient::ClientEventArgs::EventType_ProtocolFailedToSend:
printf("\t(%i : %s) - EventType_ProtocolFailedToSend\n", e.sender->GetID(), e.sender->GetIpAddress().c_str());
this->Detach(e.sender)->Disconnect();
break;
case NetworkClient::ClientEventArgs::EventType_ProtocolRecieved:
printf("\t(%i : %s) - EventType_ProtocolRecieved\n", e.sender->GetID(), e.sender->GetIpAddress().c_str());
this->ParseProtocol(e.args.data.protocol, cl);
break;
}
} }
void GameSession::ObjectMove(GameLogic::IObjectData* movedObject) void GameSession::ObjectMove(GameLogic::IObjectData* movedObject)
{ {
//GameLogic::IObjectData* obj = NULL; if(dynamic_cast<IPlayerData*> (movedObject))
//if(dynamic_cast<GameLogic::ILevelData*>(movedObject)) {
// obj =((GameLogic::ILevelData*)movedObject)->GetObjectAt(0); IPlayerData* temp = (IPlayerData*)movedObject;
//if(obj) temp->GetID();
//{ Oyster::Math::Float4x4 world = temp->GetOrientation();
// if(obj->GetType() == OBJECT_TYPE_BOX)
// { Protocol_ObjectPosition p(world, 2);
// obj->GetID(); GameSession::gameSession->Send(*p.GetProtocol());
// Oyster::Math::Float4x4 world =obj->GetOrientation(); }
// Protocol_ObjectPosition p(world, 1); GameLogic::IObjectData* obj = NULL;
// GameSession::gameSession->Send(p.GetProtocol()); if(dynamic_cast<GameLogic::ILevelData*>(movedObject))
// } {
//} obj = ((GameLogic::ILevelData*)movedObject)->GetObjectAt(0);
if(obj)
{
if(obj->GetObjectType() == OBJECT_TYPE_WORLD)
{
obj->GetID();
Oyster::Math::Float4x4 world =obj->GetOrientation();
Protocol_ObjectPosition p(world, 0);
GameSession::gameSession->Send(*p.GetProtocol());
}
}
obj = NULL;
obj =((GameLogic::ILevelData*)movedObject)->GetObjectAt(1);
if(obj)
{
if(obj->GetObjectType() == OBJECT_TYPE_BOX)
{
obj->GetID();
Oyster::Math::Float4x4 world = obj->GetOrientation();
Protocol_ObjectPosition p(world, 1);
GameSession::gameSession->Send(*p.GetProtocol());
}
}
}
} }

View File

@ -51,6 +51,7 @@ namespace DanBias
if(this->isCreated) return false; if(this->isCreated) return false;
/* standard initialization of some data */ /* standard initialization of some data */
NetworkSession::clients = desc.clients;
this->clients.Resize(desc.clients.Size()); this->clients.Resize(desc.clients.Size());
this->owner = desc.owner; this->owner = desc.owner;
@ -73,6 +74,7 @@ namespace DanBias
{ {
if( (p = this->gameInstance.CreatePlayer()) ) if( (p = this->gameInstance.CreatePlayer()) )
{ {
desc.clients[i]->SetOwner(this);
this->clients[i] = new GameClient(desc.clients[i], p); this->clients[i] = new GameClient(desc.clients[i], p);
} }
else else

View File

@ -38,11 +38,11 @@ namespace Oyster
{ {
return this->resourceData; return this->resourceData;
} }
inline unsigned long long GetResourceSize() const inline unsigned int GetResourceSize() const
{ {
return this->resourceSize; return this->resourceSize;
} }
inline unsigned long long GetResourceElementSize() const inline unsigned int GetResourceElementSize() const
{ {
return this->resourceElementSize; return this->resourceElementSize;
} }

View File

@ -4,83 +4,267 @@
#include "ResourceManager.h" #include "ResourceManager.h"
#include "..\Utilities.h"
using namespace Oyster::Resource; using namespace Oyster::Resource;
struct Oyster::Resource::ResourceData struct ::ResourceData
{ {
LoadFunction loadFnc;
UnloadFunction unloadFnc;
ResourceType resourcetype;
HRESOURCE resource;
unsigned int resourceSize;
int resourceID;
Utility::DynamicMemory::ReferenceCount referenceCount;
};
bool ReadFromFile(const wchar_t fileName[], const char openFlag[], std::string& outData, size_t elemSize, bool ANSI = false)
{
std::string sFilename;
std::wstring wsFile = fileName;
::Utility::String::WStringToString(wsFile, sFilename);
size_t bytesTotal = 0;
size_t bytesRead = 0;
FILE *stream;
if( fopen_s( &stream, sFilename.c_str(), openFlag ) == 0 )
{
//Get size of the file
fseek(stream, 0L, SEEK_END);
bytesTotal = ftell(stream);
fseek(stream, 0L, SEEK_SET);
fflush(stream);
//Sanity check
if(bytesTotal == 0) return false;
//Create the new byte buffer
char *buff = new char[bytesTotal + 1];
//Read the bytes to the end
bytesRead = fread_s( buff, bytesTotal, elemSize, bytesTotal ,stream );
fclose( stream );
//Did we read enough bytes (Get the bytes if we read with ANSI since the hidden characters is ignored)
if(!ANSI && bytesRead != bytesTotal) return false;
buff[bytesRead + 1];
outData.clear();
outData.resize(bytesRead);
memcpy(&outData[0], &buff[0], bytesRead);
delete [] buff;
}
else
{
std::string msg = "Failed to open file: \n";
msg.append(sFilename.c_str());
return false;
}
return true;
} }
const wchar_t* FindResourceKey(std::map<std::wstring, ResourceData*>& resources, const HRESOURCE h)
ResourceData* FindResource(std::map<std::wstring, ResourceData*> resources, const HRESOURCE& h) const
{ {
for (auto i = resources.begin(); i != resources.end() ; i++) for (auto i = resources.begin(); i != resources.end() ; i++)
{ {
if(i->second->GetResourceHandle() == h) if(i->second->resource == h)
{
return i->first.c_str();
}
}
return 0;
}
ResourceData* FindResource(std::map<std::wstring, ResourceData*>& resources, const HRESOURCE h)
{
for (auto i = resources.begin(); i != resources.end() ; i++)
{
if(i->second->resource == h)
{ {
return i->second; return i->second;
} }
} }
return 0; return 0;
} }
ResourceData* FindResource(std::map<std::wstring, ResourceData*> resources, const wchar_t c[]) const ResourceData* FindResource(std::map<std::wstring, ResourceData*>& resources, const wchar_t c[])
{ {
std::wstring temp = c; std::wstring temp = c;
auto t = this->resources.find(c); auto t = resources.find(c);
if(t == this->resources.end()) return 0; if(t == resources.end()) return 0;
return t->second; return t->second;
} }
void SaveResource( std::map<std::wstring, ResourceData*> resources, OResource* r, bool addNew ) void SaveResource( std::map<std::wstring, ResourceData*>& resources, ResourceData* r, const std::wstring& key, bool addNew )
{ {
if(!r) return;
if(addNew) if(addNew)
{ {
this->resources[r->GetResourceFilename()] = r; resources[key] = r;
} }
r->resourceRef.Incref(); r->referenceCount.Incref();
} }
bool Release(std::map<std::wstring, ResourceData*>& resources, ResourceData* resource)
{
if(resource->referenceCount.Decref() == 0)
{
const wchar_t* temp = FindResourceKey(resources, resource->resource);
switch (resource->resourcetype)
{
case Oyster::Resource::ResourceType_Byte_Raw:
case Oyster::Resource::ResourceType_Byte_ANSI:
case Oyster::Resource::ResourceType_Byte_UTF8:
case Oyster::Resource::ResourceType_Byte_UNICODE:
case Oyster::Resource::ResourceType_Byte_UTF16LE:
delete [] ((char*)resource->resource);
resource->resource = 0;
break;
case Oyster::Resource::ResourceType_UNKNOWN:
resource->unloadFnc(resource->resource);
resource->resource = 0;
break;
}
if(temp) delete resources[temp];
return true;
}
return false;
}
ResourceData* Load(/*Out*/ResourceData* targetMem, /*in*/const wchar_t source[], /*in*/ResourceType type)
{
std::string sOut;
bool success = false;
switch (type)
{
case Oyster::Resource::ResourceType_Byte_Raw:
success = ReadFromFile(source, "rb", sOut, sizeof(char));
break;
case Oyster::Resource::ResourceType_Byte_ANSI:
success = ReadFromFile(source, "r", sOut, sizeof(char), true);
break;
case Oyster::Resource::ResourceType_Byte_UTF8:
success = ReadFromFile(source, "r, ccs=UTF-8", sOut, sizeof(char));
break;
case Oyster::Resource::ResourceType_Byte_UNICODE:
success = ReadFromFile(source, "r, ccs=UNICODE", sOut, sizeof(char));
break;
case Oyster::Resource::ResourceType_Byte_UTF16LE:
success = ReadFromFile(source, "r, ccs=UTF-16LE", sOut, sizeof(char));
break;
}
if(!success) return 0;
if(sOut.size())
{
char *data = new char[sOut.size()+1];
data[sOut.size()] = '\0';
memcpy(&data[0], &sOut[0], sOut.size());
targetMem->resource = (HRESOURCE&)data;
targetMem->loadFnc = 0;
targetMem->unloadFnc = 0;
targetMem->resourceID = 0;
targetMem->resourcetype = type;
}
return targetMem;
}
ResourceData* Load(/*Out*/ResourceData* targetMem, /*in*/const wchar_t source[], LoadFunction loadFnc, UnloadFunction unloadFnc)
{
if(loadFnc)
{
targetMem->resource = loadFnc(source);
if(targetMem->resource)
{
targetMem->resourceSize = 0;
targetMem->resourcetype = ResourceType_UNKNOWN;
targetMem->loadFnc = loadFnc;
targetMem->unloadFnc = unloadFnc;
}
}
return targetMem;
}
ResourceData* Reload(std::map<std::wstring, ResourceData*> resources, ResourceData* resource, const wchar_t* filename)
{
switch (resource->resourcetype)
{
case Oyster::Resource::ResourceType_Byte_Raw:
case Oyster::Resource::ResourceType_Byte_ANSI:
case Oyster::Resource::ResourceType_Byte_UTF8:
case Oyster::Resource::ResourceType_Byte_UNICODE:
case Oyster::Resource::ResourceType_Byte_UTF16LE:
if(Release(resources, resource))
return Load(resource, filename, resource->loadFnc, resource->unloadFnc);
break;
case Oyster::Resource::ResourceType_UNKNOWN:
{
resource->unloadFnc(resource->resource);
HRESOURCE r = resource->loadFnc(filename);
if(!r) return 0;
resource->resource = r;
}
break;
}
return resource;
}
ResourceManager::ResourceManager() ResourceManager::ResourceManager()
{ { }
ResourceManager::~ResourceManager()
{ Clean(); }
} HBYTEARRAY ResourceManager::LoadBytes(const wchar_t filename[], ResourceType type, int customID, bool force)
ResourceManager::
HRESOURCE OysterResource::LoadResource(const wchar_t* filename, ResourceType type, int customID, bool force)
{ {
if(!filename) return 0; if(!filename) return 0;
OResource *resourceData = FindResource(filename); ResourceData *t = FindResource(this->resources, filename);
if(resourceData) if(t)
{ {
if(force) if(force)
{ {
return OysterResource::ReloadResource(filename); return (HBYTEARRAY)Reload(resources, t, filename )->resource;
} }
else else
{ {
//Add new reference //Add new reference
resourcePrivate.SaveResource(resourceData, false); SaveResource(this->resources, t, filename, false);
return resourceData->GetResourceHandle(); return (HBYTEARRAY)t->resource;
} }
} }
else else
{ {
resourceData = OResource::Load(filename, type); t = Load(new ResourceData(), filename, type);
if(resourceData) if(t)
{ {
resourceData->SetResourceID(customID); t->resourceID = (customID);
resourcePrivate.SaveResource(resourceData); SaveResource(this->resources, t, filename, true);
}
else
{
return 0;
} }
} }
return resourceData->GetResourceHandle(); return (HBYTE*)t->resource;
} }
HRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunction loadFnc, int customId, bool force) HRESOURCE ResourceManager::LoadResource(const wchar_t filename[], LoadFunction loadFnc, UnloadFunction unloadFnc, int customId, bool force)
{ {
if(!filename) if(!filename)
{ {
@ -91,152 +275,153 @@ HRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunct
return 0; return 0;
} }
OResource *resourceData = resourcePrivate.FindResource(filename); ResourceData *t = FindResource(this->resources, filename);
if(resourceData) if(t)
{ {
if(force) if(force)
{ {
return OysterResource::ReloadResource(filename); return ResourceManager::ReloadResource(filename);
} }
else else
{ {
//Add new reference //Add new reference
resourcePrivate.SaveResource(resourceData, false); SaveResource(this->resources, t, filename, false);
return resourceData->GetResourceHandle(); return t->resource;
} }
} }
else else
{ {
resourceData = OResource::Load(filename, loadFnc); t = Load(new ResourceData(), filename, loadFnc, unloadFnc );
if(resourceData) if(t)
{ {
resourceData->SetResourceID(customId); t->resourceID = (customId);
resourcePrivate.SaveResource(resourceData); SaveResource(this->resources, t, filename, true);
}
else
{
delete t;
} }
} }
if(!resourceData) if(!t)
{ {
return 0; return 0;
} }
return (OHRESOURCE)resourceData->GetResourceHandle(); return (HRESOURCE)t->resource;
} }
OHRESOURCE OysterResource::ReloadResource(const wchar_t filename[]) HRESOURCE ResourceManager::ReloadResource(const wchar_t filename[])
{ {
OResource *resourceData = resourcePrivate.FindResource(filename); ResourceData *t = FindResource(this->resources, filename);
if(!resourceData) return 0; //The resource has not been loaded if(!t) return 0; //The resource has not been loaded
return OResource::Reload(resourceData)->GetResourceHandle(); return Reload(this->resources, t, filename)->resource;
} }
OHRESOURCE OysterResource::ReloadResource(OHRESOURCE resource) HRESOURCE ResourceManager::ReloadResource(HRESOURCE& resource)
{ {
OResource *resourceData = resourcePrivate.FindResource(resource); ResourceData *t = FindResource(this->resources, resource);
if(!resourceData) return 0; //The resource has not been loaded if(!t) return 0;
return Reload(this->resources, t, FindResourceKey(this->resources, resource))->resource;
return OResource::Reload(resourceData)->GetResourceHandle();
} }
void OysterResource::Clean() void ResourceManager::Clean()
{ {
auto i = resourcePrivate.resources.begin(); if(this->resources.empty()) return;
auto last = resourcePrivate.resources.end();
auto i = this->resources.begin();
auto last = resources.end();
for (i; i != last; i++) for (i; i != last; i++)
{ {
//Remove all the references //Remove all the references
while (!OResource::Release(i->second)); while (!Release(this->resources, i->second));
std::wstring temp = i->second->GetResourceFilename();
delete resourcePrivate.resources[temp];
} }
resourcePrivate.resources.clear(); resources.clear();
} }
void OysterResource::ReleaseResource(const OHRESOURCE& resourceData) void ResourceManager::ReleaseResource(const HRESOURCE& resourceData)
{ {
OResource* t = resourcePrivate.FindResource(resourceData); ResourceData *t = FindResource(this->resources, resourceData);
if(t) if(t)
{ {
if(OResource::Release(t)) if(Release(resources, t))
{ {
std::wstring temp = t->GetResourceFilename(); const wchar_t* temp = 0;
delete resourcePrivate.resources[temp]; if((temp = FindResourceKey(resources, resourceData)))
resourcePrivate.resources.erase(temp); {
std::wstring ws = std::wstring(temp);
delete resources[ws];
resources.erase(ws);
}
} }
} }
} }
void OysterResource::ReleaseResource(const wchar_t filename[]) void ResourceManager::ReleaseResource(const wchar_t filename[])
{ {
OResource* t = resourcePrivate.FindResource(filename); ResourceData *t = FindResource(this->resources, filename);
if(t) if(t)
{ {
if(OResource::Release(t)) if(Release(resources, t))
{ {
std::wstring temp = t->GetResourceFilename(); delete resources[filename];
delete resourcePrivate.resources[temp]; resources.erase(filename);
resourcePrivate.resources.erase(temp);
} }
} }
} }
void OysterResource::SetResourceId (const OHRESOURCE& resourceData, unsigned int id)
{
OResource* t = resourcePrivate.FindResource(resourceData);
if(t) t->SetResourceID(id);
void ResourceManager::SetResourceId (const HRESOURCE& resourceData, unsigned int id)
{
ResourceData *t = FindResource(this->resources, resourceData);
if(t) t->resourceID = (id);
} }
void OysterResource::SetResourceId(const wchar_t c[], unsigned int id) void ResourceManager::SetResourceId(const wchar_t c[], unsigned int id)
{ {
OResource* t = resourcePrivate.FindResource(c); ResourceData *t = FindResource(this->resources, c);
if(t) t->SetResourceID(id); if(t) t->resourceID = (id);
} }
ResourceType OysterResource::GetResourceType (const OHRESOURCE& resourceData) ResourceType ResourceManager::GetResourceType (const HRESOURCE& resourceData)
{ {
OResource* t = resourcePrivate.FindResource(resourceData); ResourceData *t = FindResource(this->resources, resourceData);
if(t) return t->GetResourceType(); if(t) return t->resourcetype;
return ResourceType_INVALID; return ResourceType_INVALID;
} }
ResourceType OysterResource::GetResourceType (const wchar_t c[]) ResourceType ResourceManager::GetResourceType (const wchar_t c[])
{ {
OResource* t = resourcePrivate.FindResource(c); ResourceData *t = FindResource(this->resources, c);
if(t) return t->GetResourceType(); if(t) return t->resourcetype;
return ResourceType_INVALID; return ResourceType_INVALID;
} }
const wchar_t* OysterResource::GetResourceFilename (const OHRESOURCE& resourceData) const wchar_t* ResourceManager::GetResourceFilename (const HRESOURCE& resourceData)
{ {
OResource* t = resourcePrivate.FindResource(resourceData); return FindResourceKey(this->resources, resourceData);
}
HRESOURCE ResourceManager::GetResourceHandle(const wchar_t filename[])
{
ResourceData *t = FindResource(this->resources, filename);
if(t) return t->GetResourceFilename(); if(t) return t->resource;
return 0; return 0;
} }
OHRESOURCE OysterResource::GetResourceHandle(const wchar_t filename[]) int ResourceManager::GetResourceId (const HRESOURCE& resourceData)
{ {
OResource* t = resourcePrivate.FindResource(filename); ResourceData *t = FindResource(this->resources, resourceData);
if(t) return t->GetResourceHandle(); if(t) return t->resourceID;
return 0;
}
int OysterResource::GetResourceId (const OHRESOURCE& resourceData)
{
OResource* t = resourcePrivate.FindResource(resourceData);
if(t) return t->GetResourceID();
return -1; return -1;
} }
int OysterResource::GetResourceId(const wchar_t c[]) int ResourceManager::GetResourceId(const wchar_t c[])
{ {
OResource* t = resourcePrivate.FindResource(c); ResourceData *t = FindResource(this->resources, c);
if(t) return t->GetResourceID(); if(t) return t->resourceID;
return -1; return -1;
} }

View File

@ -11,6 +11,8 @@ namespace Oyster
struct ResourceData; struct ResourceData;
typedef void* HRESOURCE; typedef void* HRESOURCE;
typedef char HBYTE;
typedef HBYTE* HBYTEARRAY;
/** Typedef on a fuction required for custom unloading */ /** Typedef on a fuction required for custom unloading */
typedef void(*UnloadFunction)(void* loadedData); typedef void(*UnloadFunction)(void* loadedData);
@ -41,8 +43,6 @@ namespace Oyster
public: public:
ResourceManager(); ResourceManager();
~ResourceManager(); ~ResourceManager();
ResourceManager(const ResourceManager&) = delete;
const ResourceManager& operator=(const ResourceManager&) = delete;
/** /**
* Load a resource given a type. * Load a resource given a type.
@ -52,7 +52,7 @@ namespace Oyster
* @param force If set to true, the resource will be reloaded if it already exists. If it does not, nothing happens. * @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. * @return If function suceeds, a handle to the resource will be returned. If failed 0 is returned.
*/ */
char* LoadBytes(const wchar_t filename[], ResourceType type, int customId = -1, bool force = false); HBYTEARRAY LoadBytes(const wchar_t filename[], ResourceType type, int customId = -1, bool force = false);
/** /**
* Load a resource with a custom loading function * Load a resource with a custom loading function
@ -68,16 +68,16 @@ namespace Oyster
/** /**
* Reload a resource * Reload a resource
* @param filename The path to the resource. * @param filename The path to the resource.
* @return If function suceeds, the return value is true. * @return If function suceeds, the return value is the reloaded resource.
*/ */
bool ReloadResource(const wchar_t filename[]); HRESOURCE ReloadResource(const wchar_t filename[]);
/** /**
* Reload a resource * Reload a resource
* @param filename The path to the resource. * @param filename The path to the resource.
* @return If function suceeds, a handle to the resource will be returned. If failed 0 is returned. * @return If function suceeds, the return value is the reloaded resource.
*/ */
bool ReloadResource(HRESOURCE resource); HRESOURCE ReloadResource(HRESOURCE& resource);
/** /**
* Releases all resources loaded by the resource handler. * Releases all resources loaded by the resource handler.
@ -151,6 +151,8 @@ namespace Oyster
int GetResourceId(const wchar_t filename[]); int GetResourceId(const wchar_t filename[]);
private: private:
ResourceManager(const ResourceManager& obj);
const ResourceManager& operator=(const ResourceManager&);
std::map<std::wstring, ResourceData*> resources; std::map<std::wstring, ResourceData*> resources;
}; };

View File

@ -243,7 +243,7 @@ namespace Utility
this->_ptr = p._ptr; this->_ptr = p._ptr;
this->_rc = p._rc; this->_rc = p._rc;
this->_rc->Incref(); if(this->_rc) this->_rc->Incref();
} }
return *this; return *this;
} }

View File

@ -159,6 +159,7 @@ bool NetworkClient::operator ==(const int& ID)
void NetworkClient::Update() void NetworkClient::Update()
{ {
if(!this->privateData) return;
while (!this->privateData->recieveQueue.IsEmpty()) while (!this->privateData->recieveQueue.IsEmpty())
{ {
NetEvent<NetworkClient*, ClientEventArgs> temp = this->privateData->recieveQueue.Pop(); NetEvent<NetworkClient*, ClientEventArgs> temp = this->privateData->recieveQueue.Pop();
@ -199,7 +200,7 @@ bool NetworkClient::Connect(unsigned short port, const char serverIP[])
//Connect has succeeded //Connect has succeeded
if(result != 0) return false; if(result != 0) return false;
this->privateData->owner = 0;
this->privateData->parent = this; this->privateData->parent = this;
this->privateData->thread.Start(); this->privateData->thread.Start();

View File

@ -32,7 +32,7 @@ namespace Oyster
/** Parse session events such as protocols recieved etc. /** Parse session events such as protocols recieved etc.
*/ */
void ProcessClients(); virtual void ProcessClients();
/** /**
* *