diff --git a/Bin/DLL/GamePhysics_x86D.exp b/Bin/DLL/GamePhysics_x86D.exp deleted file mode 100644 index 0cea5aa6..00000000 Binary files a/Bin/DLL/GamePhysics_x86D.exp and /dev/null differ diff --git a/Bin/DLL/LightPass.cso b/Bin/DLL/LightPass.cso new file mode 100644 index 00000000..1764d62a Binary files /dev/null and b/Bin/DLL/LightPass.cso differ diff --git a/Code/DanBiasGame/DanBiasMaincpp.cpp b/Code/DanBiasGame/DanBiasMaincpp.cpp index 688a916f..23c1a119 100644 --- a/Code/DanBiasGame/DanBiasMaincpp.cpp +++ b/Code/DanBiasGame/DanBiasMaincpp.cpp @@ -39,6 +39,7 @@ 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(); @@ -78,16 +79,24 @@ void SetStdOutToNewConsole() 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; @@ -175,7 +184,19 @@ HRESULT InitWindow( HINSTANCE hInstance, int 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; @@ -184,18 +205,13 @@ HRESULT InitGame() MessageBox(0, L"Could not initialize the input object.", L"Error", MB_OK); return false; } - if(Oyster::Graphics::API::Init(g_hWnd, false, false, Oyster::Math::Float2( 1024, 768)) != Oyster::Graphics::API::Sucsess) - return E_FAIL; - - game = new GameLogic::IGame(); game->Init(); game->StartGame(); - - return S_OK; } + HRESULT Update(float deltaTime) { inputObj->Update(); @@ -218,7 +234,17 @@ HRESULT Update(float deltaTime) key = GameLogic::keyInput_D; } - game->Update(key); + float pitch = 0; + float yaw = 0; + + //if(inputObj->IsMousePressed()) + //{ + pitch = inputObj->GetPitch(); + yaw = inputObj->GetYaw(); + //} + + game->Update(key, pitch, yaw); + return S_OK; } @@ -232,18 +258,6 @@ HRESULT Render(float deltaTime) //std::cout<<"test"; } - // test view and projection matrix - Oyster::Math::Float3 dir = Oyster::Math::Float3(0,0,-1); - Oyster::Math::Float3 up =Oyster::Math::Float3(0,1,0); - Oyster::Math::Float3 pos = Oyster::Math::Float3(0, 0, 100); - - Oyster::Math::Float4x4 view =Oyster::Math3D::OrientationMatrix_LookAtDirection(dir, up, pos); - view = view.GetInverse(); - - Oyster::Math::Float4x4 proj = Oyster::Math3D::ProjectionMatrix_Perspective(3.14f/2, 1024/768, 1, 1000); - - Oyster::Graphics::API::NewFrame(view, proj); - game->Render(); wchar_t title[255]; swprintf(title, sizeof(title), L"| Pressing A: %d | \n", (int)(isPressed)); diff --git a/Code/GameLogic/Camera.cpp b/Code/GameLogic/Camera.cpp new file mode 100644 index 00000000..a969ced5 --- /dev/null +++ b/Code/GameLogic/Camera.cpp @@ -0,0 +1,185 @@ +#include "Camera.h" + +Camera::Camera() +{ + this->m_position = Oyster::Math::Float3(0, 50, 0); + this->mRight = Oyster::Math::Float3(1, 0, 0); + this->mUp = Oyster::Math::Float3(0, 1, 0); + this->mLook = Oyster::Math::Float3(0, 0, 1); +} + +Camera::~Camera() +{ +} + +void Camera::SetPosition(const Oyster::Math::Float3& v) +{ + this->m_position = v; +} + +Oyster::Math::Float3 Camera::GetPosition()const +{ + return this->m_position; +} + +Oyster::Math::Float3 Camera::GetRight()const +{ + return this->mRight; +} + +Oyster::Math::Float3 Camera::GetUp()const +{ + return this->mUp; +} + +Oyster::Math::Float3 Camera::GetLook()const +{ + return this->mLook; +} + +float Camera::GetNearZ()const +{ + return this->mNearZ; +} + +float Camera::GetFarZ()const +{ + return this->mFarZ; +} + +float Camera::GetAspect()const +{ + return this->mAspect; +} + +Oyster::Math::Float3 Camera::CrossMatrix(const Oyster::Math::Float3& vector, const Oyster::Math::Float4x4& matrix) +{ + Oyster::Math::Float3 vec; + vec.x = matrix.m11*vector.x + matrix.m12*vector.y + matrix.m13*vector.z; + vec.y = matrix.m21*vector.x + matrix.m22*vector.y + matrix.m23*vector.z; + vec.z = matrix.m31*vector.x + matrix.m32*vector.y + matrix.m33*vector.z; + return vec; +} + +void Camera::SetLens(float fovY, float aspect, float zn, float zf) +{ + this->mFovY = fovY; + this->mAspect = aspect; + this->mNearZ = zn; + this->mFarZ = zf; + + float yScale = tan((Oyster::Math::pi*0.5f) - (mFovY*0.5f)); + float xScale = yScale/this->mAspect; + + mProj = Oyster::Math::Float4x4(xScale, 0, 0, 0, + 0, yScale, 0, 0, + 0, 0, zf/(zf-zn), 1, + 0, 0, -zn*zf/(zf-zn), 0); + mProj.Transpose(); +} + +void Camera::LookAt(Oyster::Math::Float3 pos, Oyster::Math::Float3 target, Oyster::Math::Float3 worldUp) +{ + Oyster::Math::Float3 L; + + L = target - pos; + L.Normalize(); + + Oyster::Math::Float3 R; + R = worldUp.Cross(L); + R.Normalize(); + + Oyster::Math::Float3 U; + U = L.Cross(R); + + this->m_position = pos; + this->mLook = L; + this->mRight = R; + this->mUp = U; +} + +Oyster::Math::Float4x4 Camera::View()const +{ + return this->mView; +} + +Oyster::Math::Float4x4 Camera::Proj()const +{ + return this->mProj; +} + +Oyster::Math::Float4x4 Camera::ViewsProj()const +{ + Oyster::Math::Float4x4 M; + M = mView * mProj; + return M; +} + +void Camera::Walk(float dist) +{ + this->m_position += dist*this->mLook; +} + +void Camera::Strafe(float dist) +{ + this->m_position += dist*this->mRight; +} + +void Camera::Pitch(float angle) +{ + float radians = angle * 0.0174532925f; + + Oyster::Math::Float4x4 R; + + Oyster::Math3D::RotationMatrix(radians,-mRight,R); + this->mUp = CrossMatrix(this->mUp, R); + this->mLook = CrossMatrix(this->mLook, R); +} + +void Camera::Yaw(float angle) +{ + float radians = angle * 0.0174532925f; + + Oyster::Math::Float4x4 R; + + Oyster::Math::Float3 up(0,1,0); + Oyster::Math3D::RotationMatrix(radians,-up,R); + + this->mRight = CrossMatrix(this->mRight, R); + this->mUp = CrossMatrix(mUp, R); + this->mLook = CrossMatrix(this->mLook, R); +} + +void Camera::UpdateViewMatrix() +{ + mLook.Normalize(); + mUp = mLook.Cross(mRight); + mUp.Normalize(); + mRight = mUp.Cross(mLook); + + float x = -m_position.Dot(mRight); + float y = -m_position.Dot(mUp); + float z = -m_position.Dot(mLook); + + mView.m11 = mRight.x; + mView.m21 = mRight.y; + mView.m31 = mRight.z; + mView.m41 = x; + + mView.m12 = mUp.x; + mView.m22 = mUp.y; + mView.m32 = mUp.z; + mView.m42 = y; + + mView.m13 = mLook.x; + mView.m23 = mLook.y; + mView.m33 = mLook.z; + mView.m43 = z; + + mView.m14 = 0.0f; + mView.m24 = 0.0f; + mView.m34 = 0.0f; + mView.m44 = 1.0f; + + mView.Transpose(); +} \ No newline at end of file diff --git a/Code/GameLogic/Camera.h b/Code/GameLogic/Camera.h new file mode 100644 index 00000000..deb9df62 --- /dev/null +++ b/Code/GameLogic/Camera.h @@ -0,0 +1,63 @@ +#ifndef CAMERA__H +#define CAMERA__H + +#include "OysterMath.h" + +class Camera +{ +private: + + Oyster::Math::Float3 m_position; + Oyster::Math::Float3 mRight; + Oyster::Math::Float3 mUp; + Oyster::Math::Float3 mLook; + + + + float mNearZ; + float mFarZ; + float mAspect; + float mFovY; + + Oyster::Math::Float4x4 mView; + Oyster::Math::Float4x4 mProj; + +public: + Camera(); + virtual ~Camera(); + + void SetPosition(const Oyster::Math::Float3& v); + + Oyster::Math::Float3 GetPosition()const; + + Oyster::Math::Float3 GetRight()const; + Oyster::Math::Float3 GetUp()const; + Oyster::Math::Float3 GetLook()const; + + float GetNearZ()const; + float GetFarZ()const; + float GetAspect()const; + + Oyster::Math::Float3 CrossMatrix(const Oyster::Math::Float3& v, const Oyster::Math::Float4x4& m); + + void SetLens(float fovY, float aspect, float zn, float zf); + + void LookAt(Oyster::Math::Float3 pos, Oyster::Math::Float3 target, Oyster::Math::Float3 worldUp); + + void setLook(Oyster::Math::Float3 look) { mLook = look; } + void setUp(Oyster::Math::Float3 up) { mUp = up; } + void setRight(Oyster::Math::Float3 right) { mRight = right; } + + Oyster::Math::Float4x4 View()const; + Oyster::Math::Float4x4 Proj()const; + Oyster::Math::Float4x4 ViewsProj()const; + + void Walk(float dist); + void Strafe(float dist); + + void Pitch(float angle); + void Yaw(float angle); + + void UpdateViewMatrix(); +}; +#endif \ No newline at end of file diff --git a/Code/GameLogic/CollisionManager.cpp b/Code/GameLogic/CollisionManager.cpp index 253056cc..f7868b79 100644 --- a/Code/GameLogic/CollisionManager.cpp +++ b/Code/GameLogic/CollisionManager.cpp @@ -8,38 +8,6 @@ namespace GameLogic namespace CollisionManager { - - - - void ColisionEvent(Oyster::Physics::ICustomBody &obj1, Oyster::Physics::ICustomBody &obj2) - { - - - //Object *realObj1 = refManager.GetMap(obj1); - //Object *realObj2 = refManager.GetMap(obj2); - // - //switch(realObj1->GetType()) - //{ - //case Object::OBJECT_TYPE_PLAYER: - - // if (realObj2->GetType() == Object::OBJECT_TYPE_BOX ) - // { - //CollisionManager::PlayerVBox(*((Player*)realObj1),*((DynamicObject*)realObj2)); - // } - - // break; - //case Object::OBJECT_TYPE_BOX: - - // if (realObj2->GetType() == Object::OBJECT_TYPE_PLAYER) - // { - // CollisionManager::PlayerVBox(*((Player*)realObj2),*((DynamicObject*)realObj1)); - // } - - // break; - //} - - } - void PlayerCollision(Oyster::Physics::ICustomBody &rigidBodyPlayer,Oyster::Physics::ICustomBody &obj) { Player *player = ((Player*)GameLogic::RefManager::getInstance()->GetMap(rigidBodyPlayer)); diff --git a/Code/GameLogic/CollisionManager.h b/Code/GameLogic/CollisionManager.h index 878d6f25..a650f595 100644 --- a/Code/GameLogic/CollisionManager.h +++ b/Code/GameLogic/CollisionManager.h @@ -12,11 +12,11 @@ namespace GameLogic namespace CollisionManager { + //these are the main collision functions void PlayerCollision(Oyster::Physics::ICustomBody &rigidBodyPlayer,Oyster::Physics::ICustomBody &obj); void BoxCollision(Oyster::Physics::ICustomBody &rigidBodyBox, Oyster::Physics::ICustomBody &obj); - - + //these are the specific collision case functions void PlayerVBox(Player &player, DynamicObject &box); void BoxVBox(DynamicObject &box1, DynamicObject &box2); diff --git a/Code/GameLogic/DynamicObject.cpp b/Code/GameLogic/DynamicObject.cpp index ec175f59..14e0518d 100644 --- a/Code/GameLogic/DynamicObject.cpp +++ b/Code/GameLogic/DynamicObject.cpp @@ -5,9 +5,8 @@ using namespace Oyster::Physics; using namespace Utility::DynamicMemory; DynamicObject::DynamicObject(void) + :Object() { - rigidBody = API::Instance().CreateSimpleRigidBody(); - API::Instance().AddObject(rigidBody); } @@ -17,5 +16,5 @@ DynamicObject::~DynamicObject(void) void DynamicObject::Update() { - //updatera objectet + //update object } \ No newline at end of file diff --git a/Code/GameLogic/Game.cpp b/Code/GameLogic/Game.cpp index 6d6d367d..b4095130 100644 --- a/Code/GameLogic/Game.cpp +++ b/Code/GameLogic/Game.cpp @@ -3,7 +3,9 @@ using namespace GameLogic; Game::Game(void) { - + player = NULL; + level = NULL; + camera = NULL; } @@ -15,21 +17,52 @@ Game::~Game(void) delete player; player = NULL; } + if(camera) + { + delete camera; + camera = NULL; + } } void Game::Init() { player = new Player(); + camera = new Camera(); } void Game::StartGame() { + Oyster::Math::Float3 dir = Oyster::Math::Float3(0,0,-1); + Oyster::Math::Float3 up =Oyster::Math::Float3(0,1,0); + Oyster::Math::Float3 pos = Oyster::Math::Float3(0, 0, 100); + camera->LookAt(pos, dir, up); + camera->SetLens(3.14f/2, 1024/768, 1, 1000); } -void Game::Update(keyInput keyPressed) +void Game::Update(keyInput keyPressed, float pitch, float yaw) { - player->Update(keyPressed); + //player->Update(keyPressed); + camera->Yaw(yaw); + camera->Pitch(pitch); + if(keyPressed == keyInput_A) + { + camera->Strafe(-0.1); + } + if(keyPressed == keyInput_D) + { + camera->Strafe(0.1); + } + if(keyPressed == keyInput_S) + { + camera->Walk(-0.1); + } + if(keyPressed == keyInput_W) + { + camera->Walk(0.1); + } + camera->UpdateViewMatrix(); } void Game::Render() { + Oyster::Graphics::API::NewFrame(camera->View(), camera->Proj()); player->Render(); } \ No newline at end of file diff --git a/Code/GameLogic/Game.h b/Code/GameLogic/Game.h index ab2e57e5..0a8a031a 100644 --- a/Code/GameLogic/Game.h +++ b/Code/GameLogic/Game.h @@ -4,11 +4,10 @@ #include "Level.h" #include "Player.h" #include "IGame.h" +#include "Camera.h" namespace GameLogic { - - class Game { public: @@ -17,15 +16,13 @@ namespace GameLogic void Init(); void StartGame(); - void Update(keyInput keyPressed); + void Update(keyInput keyPressed, float pitch, float yaw); void Render(); - private: Level* level; Player* player; - - + Camera* camera; }; } #endif \ No newline at end of file diff --git a/Code/GameLogic/GameLogic.vcxproj b/Code/GameLogic/GameLogic.vcxproj index e4e48526..236258d2 100644 --- a/Code/GameLogic/GameLogic.vcxproj +++ b/Code/GameLogic/GameLogic.vcxproj @@ -176,8 +176,11 @@ + + + @@ -187,8 +190,11 @@ + + + diff --git a/Code/GameLogic/GameLogic.vcxproj.filters b/Code/GameLogic/GameLogic.vcxproj.filters index 38b2d5fa..f2c5e978 100644 --- a/Code/GameLogic/GameLogic.vcxproj.filters +++ b/Code/GameLogic/GameLogic.vcxproj.filters @@ -42,6 +42,15 @@ Header Files + + Header Files + + + Header Files + + + Header Files + @@ -74,5 +83,14 @@ Source Files + + Source Files + + + Source Files + + + Source Files + \ No newline at end of file diff --git a/Code/GameLogic/IGame.cpp b/Code/GameLogic/IGame.cpp index 883a9285..dd07c9f8 100644 --- a/Code/GameLogic/IGame.cpp +++ b/Code/GameLogic/IGame.cpp @@ -8,16 +8,14 @@ BOOL WINAPI DllMain( _In_ LPVOID lpvReserved ) { - return TRUE; } using namespace GameLogic; + IGame::IGame() { gameModule = new Game(); } - - IGame::~IGame() { delete gameModule; @@ -31,9 +29,9 @@ void IGame::StartGame() { gameModule->StartGame(); } -void IGame::Update(keyInput keyPressed) +void IGame::Update(keyInput keyPressed, float pitch, float yaw) { - gameModule->Update(keyPressed); + gameModule->Update(keyPressed, pitch, yaw); } void IGame::Render() { diff --git a/Code/GameLogic/IGame.h b/Code/GameLogic/IGame.h index ce46b7d8..41b2e0d5 100644 --- a/Code/GameLogic/IGame.h +++ b/Code/GameLogic/IGame.h @@ -38,7 +38,7 @@ namespace GameLogic /************************************************************************/ /* Get key input to update the player */ /************************************************************************/ - void Update(keyInput keyPressed); + void Update(keyInput keyPressed, float pitch, float yaw); void Render(); Game* getGameModule(); private: diff --git a/Code/GameLogic/Object.cpp b/Code/GameLogic/Object.cpp index a83d1fb6..33679058 100644 --- a/Code/GameLogic/Object.cpp +++ b/Code/GameLogic/Object.cpp @@ -16,16 +16,12 @@ Object::Object(void) { model = new Model(); - model = Oyster::Graphics::API::CreateModel(L"bth.obj"); + model = Oyster::Graphics::API::CreateModel(L"orca"); - ICustomBody* temp = rigidBody = API::Instance().CreateSimpleRigidBody().Release(); - - rigidBody->SetCenter(Float3(50,0,0)); - rigidBody->SetMass_KeepMomentum(30); - rigidBody->SetSize(Float3(2,2,2)); - rigidBody->SetSubscription(true); - rigidBody->SetMomentOfInertiaTensor_KeepMomentum(Float4x4(MomentOfInertia::CreateCuboidMatrix(30, 2, 2, 2))); + API::SimpleBodyDescription sbDesc; + //sbDesc.centerPosition = + ICustomBody* temp = rigidBody = API::Instance().CreateRigidBody(sbDesc).Release(); GameLogic::RefManager::getInstance()->AddMapping(*rigidBody, *this); @@ -43,7 +39,6 @@ void Object::Render() { this->rigidBody->GetOrientation(model->WorldMatrix); Oyster::Graphics::API::RenderScene(model, 1); - } Object::OBJECT_TYPE Object::GetType() diff --git a/Code/GameLogic/Object.h b/Code/GameLogic/Object.h index be2f77a6..767edb1f 100644 --- a/Code/GameLogic/Object.h +++ b/Code/GameLogic/Object.h @@ -18,16 +18,16 @@ namespace GameLogic { class Object { - public: - Object(void); - virtual ~Object(void); + public: enum OBJECT_TYPE { OBJECT_TYPE_PLAYER, OBJECT_TYPE_BOX, }; - + Object(void); + virtual ~Object(void); + void Render(); OBJECT_TYPE GetType(); diff --git a/Code/GameLogic/Player.cpp b/Code/GameLogic/Player.cpp index 3a9ae029..93a83506 100644 --- a/Code/GameLogic/Player.cpp +++ b/Code/GameLogic/Player.cpp @@ -1,54 +1,53 @@ #include "Player.h" #include "OysterMath.h" - using namespace GameLogic; using namespace Oyster::Physics; -using namespace Utility::DynamicMemory; - - - Player::Player(void) :Object() { life = 100; } - - Player::~Player(void) { delete this->rigidBody; } + void Player::Update(keyInput keyPressed) { if(keyPressed != keyInput_none) { - Move(); - - if(keyPressed == keyInput_A) - { - Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); - pos.x -= 0.1; - rigidBody->SetCenter(pos); - } - if(keyPressed == keyInput_D) - { - Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); - pos.x += 0.1; - rigidBody->SetCenter(pos); - } + Move(keyPressed); } - } -void Player::Move() +void Player::Move(keyInput keyPressed) { - //API::Instance().Update(); - /*Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); - pos.x += 0.1; - rigidBody->SetCenter(pos);*/ - //API::Instance().SetCenter(rigidBody, pos); + if(keyPressed == keyInput_A) + { + Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); + pos.x -= 0.1; + rigidBody->SetCenter(pos); + } + if(keyPressed == keyInput_D) + { + Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); + pos.x += 0.1; + rigidBody->SetCenter(pos); + } + if(keyPressed == keyInput_S) + { + Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); + pos.y -= 0.1; + rigidBody->SetCenter(pos); + } + if(keyPressed == keyInput_W) + { + Oyster::Math::Float3 pos = this->rigidBody->GetCenter(); + pos.y += 0.1; + rigidBody->SetCenter(pos); + } } void Player::Shoot() { diff --git a/Code/GameLogic/Player.h b/Code/GameLogic/Player.h index 7726fed4..7c4045e3 100644 --- a/Code/GameLogic/Player.h +++ b/Code/GameLogic/Player.h @@ -13,27 +13,25 @@ namespace GameLogic { - - class Player : public Object { public: Player(void); ~Player(void); - + + /******************************************************** + * Update the position of the rigid body + * This will be done with physics later + ********************************************************/ void Update(keyInput keyPressed); - void Move(); + void Move(keyInput keyPressed); void Shoot(); - private: - int life; - Weapon *weapon; - - + int life; + Weapon *weapon; }; - } #endif \ No newline at end of file diff --git a/Code/GameLogic/TestGLMain.cpp b/Code/GameLogic/TestGLMain.cpp index 8cf34e5f..57392224 100644 --- a/Code/GameLogic/TestGLMain.cpp +++ b/Code/GameLogic/TestGLMain.cpp @@ -5,6 +5,12 @@ // // Copyright (c) Stefan Petersson 2011. All rights reserved. //-------------------------------------------------------------------------------------- + +////////////////////////////////////////////////////////////////////////// +// Test main function for game logic when .exe +// Doesn't run when Game logic is compiled as a .dll +////////////////////////////////////////////////////////////////////////// + #define NOMINMAX #include #include "Core/Core.h" @@ -28,8 +34,8 @@ HINSTANCE g_hInst = NULL; HWND g_hWnd = NULL; -GameLogic::IGame* game; -InputClass* inputObj; +GameLogic::IGame *game; +InputClass *inputObj; //-------------------------------------------------------------------------------------- @@ -95,8 +101,9 @@ int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdL __int64 prevTimeStamp = 0; QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp); - //debugwindow + //Init debug window //SetStdOutToNewConsole(); + // Main message loop MSG msg = {0}; while(WM_QUIT != msg.message) @@ -171,56 +178,21 @@ HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow ) return S_OK; } - - //-------------------------------------------------------------------------------------- -// Create Direct3D device and swap chain +// Create Direct3D with Oyster Graphics //-------------------------------------------------------------------------------------- HRESULT InitDirect3D() { - /*HRESULT hr = S_OK;; - - Oyster::Graphics::Core::resolution = Oyster::Math::Float2( 1024, 768 ); - - if(Oyster::Graphics::Core::Init::FullInit(g_hWnd,false,false)==Oyster::Graphics::Core::Init::Fail) + if(Oyster::Graphics::API::Init(g_hWnd, false, false, Oyster::Math::Float2( 1024, 768)) != Oyster::Graphics::API::Sucsess) return E_FAIL; - - - - std::wstring ShaderPath = L"..\\OysterGraphics\\Shader\\HLSL\\"; - std::wstring EffectPath = L"SimpleDebug\\"; - - Oyster::Graphics::Core::ShaderManager::Init(ShaderPath + EffectPath + L"DebugPixel.hlsl",Oyster::Graphics::Core::ShaderManager::ShaderType::Pixel,L"Debug",false); - Oyster::Graphics::Core::ShaderManager::Init(ShaderPath + EffectPath + L"DebugVertex.hlsl",Oyster::Graphics::Core::ShaderManager::ShaderType::Vertex,L"PassThroughFloat4",false); - - Oyster::Graphics::Core::ShaderManager::Set::Vertex(Oyster::Graphics::Core::ShaderManager::Get::Vertex(L"PassThroughFloat4")); - Oyster::Graphics::Core::ShaderManager::Set::Pixel(Oyster::Graphics::Core::ShaderManager::Get::Pixel(L"Debug")); - - D3D11_INPUT_ELEMENT_DESC inputDesc[] = - { - { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 } - }; - - ID3D11InputLayout* layout; - - Oyster::Graphics::Core::ShaderManager::CreateInputLayout( inputDesc, 1, Oyster::Graphics::Core::ShaderManager::Get::Vertex(L"PassThroughFloat4"), layout); - - Oyster::Graphics::Core::deviceContext->IASetInputLayout(layout); - Oyster::Graphics::Core::deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - - Oyster::Graphics::Render::Preparations::Basic::BindBackBufferRTV(); - - Oyster::Graphics::Render::Preparations::Basic::SetViewPort();*/ - return S_OK; } +//-------------------------------------------------------------------------------------- +// Init the input and the game +//------------------------------------------------------------------------------------- HRESULT InitGame() { - - if(Oyster::Graphics::API::Init(g_hWnd, false, false, Oyster::Math::Float2( 1024, 768)) != Oyster::Graphics::API::Sucsess) - return E_FAIL; - inputObj = new InputClass; if(!inputObj->Initialize(g_hInst, g_hWnd, 1024, 768)) { @@ -231,10 +203,9 @@ HRESULT InitGame() game->Init(); game->StartGame(); - - return S_OK; } + HRESULT Update(float deltaTime) { inputObj->Update(); @@ -257,8 +228,17 @@ HRESULT Update(float deltaTime) key = GameLogic::keyInput_D; } - game->Update(key); - + float pitch = 0; + float yaw = 0; + + // move only when mouse is pressed + //if(inputObj->IsMousePressed()) + //{ + pitch = inputObj->GetPitch(); + yaw = inputObj->GetYaw(); + //} + + game->Update(key, pitch, yaw); return S_OK; } @@ -271,18 +251,6 @@ HRESULT Render(float deltaTime) //std::cout<<"test"; } - // test view and projection matrix - Oyster::Math::Float3 dir = Oyster::Math::Float3(0,0,-1); - Oyster::Math::Float3 up =Oyster::Math::Float3(0,1,0); - Oyster::Math::Float3 pos = Oyster::Math::Float3(0, 0, 100); - - Oyster::Math::Float4x4 view =Oyster::Math3D::OrientationMatrix_LookAtDirection(dir, up, pos); - view = view.GetInverse(); - - Oyster::Math::Float4x4 proj = Oyster::Math3D::ProjectionMatrix_Perspective(PI/2, 1024/768, 1, 1000); - - Oyster::Graphics::API::NewFrame(view, proj); - game->Render(); wchar_t title[255]; swprintf(title, sizeof(title), L"| Pressing A: %d | \n", (int)(isPressed)); @@ -295,7 +263,6 @@ HRESULT Render(float deltaTime) HRESULT CleanUp() { - SAFE_DELETE(game); return S_OK; } diff --git a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp index ed8f8eed..3d3080da 100644 --- a/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp +++ b/Code/GamePhysics/Implementation/PhysicsAPI_Impl.cpp @@ -11,6 +11,22 @@ using namespace ::Utility::DynamicMemory; API_Impl API_instance; +namespace +{ + void OnPossibleCollision( Octree& worldScene, unsigned int protoTempRef, unsigned int deuterTempRef ) + { /** @todo TODO: OnPossibleCollision is a temporary solution .*/ + auto proto = worldScene.GetCustomBody( protoTempRef ); + auto deuter = worldScene.GetCustomBody( deuterTempRef ); + + float deltaWhen; + Float3 worldWhere; + if( deuter->Intersects(*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. ********************************************************/ diff --git a/Code/Input/L_inputClass.cpp b/Code/Input/L_inputClass.cpp index e644b5dc..5fd15a54 100644 --- a/Code/Input/L_inputClass.cpp +++ b/Code/Input/L_inputClass.cpp @@ -172,20 +172,17 @@ bool InputClass::ReadMouse() return true; } -void InputClass::MouseMove(float &Pitch, float &RotateY ) +float InputClass::GetPitch( ) { - //if left mouse button is pressed - if (m_mouseState.rgbButtons[0]) - { - float dx = (static_cast( m_mouseState.lX)/150); - float dy = (static_cast( m_mouseState.lY)/150); - - // - Pitch=dy; - RotateY=dx; - - } + float dy = (static_cast( m_mouseState.lY)/5); + return -dy; } +float InputClass::GetYaw( ) +{ + float dX = (static_cast( m_mouseState.lX)/5); + return -dX; +} + bool InputClass::IsMousePressed() { if (m_mouseState.rgbButtons[0]) diff --git a/Code/Input/L_inputClass.h b/Code/Input/L_inputClass.h index b5a08c31..129024c2 100644 --- a/Code/Input/L_inputClass.h +++ b/Code/Input/L_inputClass.h @@ -1,3 +1,9 @@ +////////////////////////////////////////////////////////////////////////// +// Temp input handler, not stable! +// When starting the program, don't click anywhere until the program starts +// because that breaks the input.. +////////////////////////////////////////////////////////////////////////// + #ifndef _INPUTCLASS_H_ #define _INPUTCLASS_H_ @@ -23,7 +29,6 @@ private: bool ReadKeyboard(); bool ReadMouse(); - public: @@ -39,7 +44,11 @@ public: bool IsKeyPressed(int key); bool IsMousePressed(); - void MouseMove(float &Pitch, float &RoateY); + + // Call if mouse is pressed + float GetYaw(); + float GetPitch(); + }; #endif \ No newline at end of file diff --git a/Code/Misc/IQueue.h b/Code/Misc/IQueue.h new file mode 100644 index 00000000..fc85800e --- /dev/null +++ b/Code/Misc/IQueue.h @@ -0,0 +1,35 @@ +#ifndef I_QUEUE_H +#define I_QUEUE_H + +///////////////////////////////// +// Created by Sam Svensson 2013// +///////////////////////////////// + +namespace Oyster +{ + namespace Queue + { + template + class IQueue + { + public: + + //--------------------------------------------- + //standard operations of the std::queue + //--------------------------------------------- + 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 c41ed349..8cb234da 100644 --- a/Code/Misc/Misc.vcxproj +++ b/Code/Misc/Misc.vcxproj @@ -148,16 +148,18 @@ - + - + + + diff --git a/Code/Misc/Misc.vcxproj.filters b/Code/Misc/Misc.vcxproj.filters index 3f2d3b40..7151e26a 100644 --- a/Code/Misc/Misc.vcxproj.filters +++ b/Code/Misc/Misc.vcxproj.filters @@ -39,6 +39,12 @@ Source Files + + Source Files + + + Source Files + @@ -65,5 +71,20 @@ Header Files + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + \ No newline at end of file diff --git a/Code/Misc/Resource/Loaders/CustomLoader.cpp b/Code/Misc/Resource/Loaders/CustomLoader.cpp index 1e030a6b..6b67d0bd 100644 --- a/Code/Misc/Resource/Loaders/CustomLoader.cpp +++ b/Code/Misc/Resource/Loaders/CustomLoader.cpp @@ -16,7 +16,7 @@ OResource* OResource::CustomLoader(const wchar_t filename[], CustomLoadFunction memset(&data, 0, sizeof(CustomData)); fnc(filename, data); - + OHRESOURCE n = (OHRESOURCE)data.loadedData; if(!data.loadedData) { return 0; diff --git a/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig b/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig new file mode 100644 index 00000000..a37c0a76 --- /dev/null +++ b/Code/Misc/Resource/Loaders/CustomLoader.cpp.orig @@ -0,0 +1,73 @@ +///////////////////////////////////////////////////////////////////// +// Created by [Dennis Andersen] [2013] +///////////////////////////////////////////////////////////////////// + +#include "..\OResource.h" +#include "..\..\Utilities.h" + +#include + +using namespace Oyster::Resource; + + +OResource* OResource::CustomLoader(const wchar_t filename[], CustomLoadFunction fnc) +{ +<<<<<<< HEAD + CustomData &data = fnc(filename); + + if(!data.loadedData) return 0; + if(!data.resourceUnloadFnc) return 0; + OHRESOURCE n = (OHRESOURCE)data.loadedData; + OResource *resource = new OResource(n, ResourceType_UNKNOWN, 0, 0, filename); + + resource->customData = new CustomResourceData(); + resource->customData->unloadingFunction = data.resourceUnloadFnc; + //resource->resourceData = (OHRESOURCE)data.loadedData; +======= + 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); + + resource->customData = new CustomResourceData(); + resource->customData->unloadingFunction = data.resourceUnloadFnc; +>>>>>>> d08644e8e1ecc56f4d9dfa6a9aa33df94d9e655a + resource->customData->loadingFunction = fnc; + + return resource; +} +void OResource::CustomUnloader() +{ + this->customData->unloadingFunction(this->resourceData); +} +OResource* OResource::CustomReloader() +{ + CustomUnloader(); + + 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.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/Resource/OResourceHandler.cpp b/Code/Misc/Resource/OResourceHandler.cpp index 36154d09..f86c434c 100644 --- a/Code/Misc/Resource/OResourceHandler.cpp +++ b/Code/Misc/Resource/OResourceHandler.cpp @@ -88,7 +88,10 @@ OHRESOURCE OysterResource::LoadResource(const wchar_t filename[], CustomLoadFunc resourcePrivate.SaveResource(resourceData); } } - + if(!resourceData) + { + return 0; + } return (OHRESOURCE)resourceData->GetResourceHandle(); } diff --git a/Code/Misc/Resource/OysterResource.h.orig b/Code/Misc/Resource/OysterResource.h.orig new file mode 100644 index 00000000..2ec147e8 --- /dev/null +++ b/Code/Misc/Resource/OysterResource.h.orig @@ -0,0 +1,162 @@ +///////////////////////////////////////////////////////////////////// +// 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 */ + typedef void* OHRESOURCE; + /** Typedef on a fuction required for custom unloading */ + typedef void(*CustomUnloadFunction)(void* loadedData); + /** Typedef on a fuction required for custom loading */ +<<<<<<< HEAD + typedef CustomData&(*CustomLoadFunction)(const wchar_t filename[]); +======= + typedef void(*CustomLoadFunction)(const wchar_t filename[], CustomData& outData); +>>>>>>> d08644e8e1ecc56f4d9dfa6a9aa33df94d9e655a + + /** 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, /**< Not used. */ + + 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; // 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/ThreadSafeQueue.h b/Code/Misc/ThreadSafeQueue.h new file mode 100644 index 00000000..d0125f71 --- /dev/null +++ b/Code/Misc/ThreadSafeQueue.h @@ -0,0 +1,218 @@ +#ifndef THREAD_SAFE_QUEUE_H +#define THREAD_SAFE_QUEUE_H + +//////////////////////////////////////////// +// Thread safe queue implemented +// with single linked list and template. +// uses mutex to lock the queue +// otherwise its a standard queue +// 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/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" diff --git a/Code/Network/NetworkDependencies/Connection.cpp b/Code/Network/NetworkDependencies/Connection.cpp new file mode 100644 index 00000000..3f303542 --- /dev/null +++ b/Code/Network/NetworkDependencies/Connection.cpp @@ -0,0 +1,153 @@ +#include "Connection.h" + +#include +#include +#include +#include + +using namespace Oyster::Network; + +Connection::~Connection() +{ + closesocket( this->socket ); +} + +int Connection::Connect(unsigned short port , const char serverName[]) +{ + struct hostent *hostEnt; + if((hostEnt = gethostbyname(serverName)) == NULL) + { + return WSAGetLastError(); + } + + struct sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = *(unsigned long*) hostEnt->h_addr; + + if(connect(this->socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) + { + return WSAGetLastError(); + } + + //connection succesfull! + return 0; +} + +int Connection::InitiateServer(unsigned short port) +{ + int errorCode = 0; + + if((errorCode = InitiateSocket()) != 0) + { + return errorCode; + } + + struct sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = INADDR_ANY; + + if(bind(this->socket, (sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) + { + errorCode = WSAGetLastError(); + closesocket(this->socket); + return errorCode; + } + + //not our Listen function! its trying to keep our socket open for connections + if(listen(this->socket, 5) == SOCKET_ERROR) + { + errorCode = WSAGetLastError(); + closesocket(this->socket); + return errorCode; + } + + //Server started! + return 0; +} + +int Connection::InitiateClient() +{ + return InitiateSocket(); +} + +int Connection::Disconnect() +{ + closesocket(this->socket); + + return WSAGetLastError(); +} + +int Connection::Send(OysterByte& bytes) +{ + int nBytes; + + nBytes = send(this->socket, bytes, bytes.GetSize(), 0); + if(nBytes == SOCKET_ERROR) + { + return WSAGetLastError(); + } + + return 0; +} + +int Connection::Recieve(OysterByte& bytes) +{ + int nBytes; + + bytes.Clear(1000); + nBytes = recv(this->socket, bytes, 500, 0); + if(nBytes == SOCKET_ERROR) + { + return WSAGetLastError(); + } + else + { + bytes.SetSize(nBytes); + } + + std::cout << "Size of the recieved data: " << nBytes << " bytes" << std::endl; + + //bytes.byteArray[nBytes] = '\0'; + + return 0; +} + +int Connection::Listen() +{ + int clientSocket; + if((clientSocket = accept(this->socket, NULL, NULL)) == INVALID_SOCKET) + { + return WSAGetLastError(); + } + + return clientSocket; +} + +/////////////////////////////////////// +//Private functions +/////////////////////////////////////// +int Connection::InitiateSocket() +{ + this->socket = ::socket(AF_INET, SOCK_STREAM, 0); + if(this->socket == SOCKET_ERROR) + { + return WSAGetLastError(); + } + + 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 new file mode 100644 index 00000000..b46ccb02 --- /dev/null +++ b/Code/Network/NetworkDependencies/Connection.h @@ -0,0 +1,45 @@ +#ifndef NETWORK_DEPENDENCIES_CONNECTION_H +#define NETWORK_DEPENDENCIES_CONNECTION_H + +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +#include "IConnection.h" +#include "../NetworkDependencies/OysterByte.h" + +namespace Oyster +{ + namespace Network + { + class Connection : public IConnection + { + + public: + Connection() { this->socket = 0; }; + Connection( int socket ) { this->socket = socket; }; + virtual ~Connection(); + + + virtual int InitiateServer( unsigned short port ); + virtual int InitiateClient(); + + virtual int Send( OysterByte& bytes ); + virtual int Recieve( OysterByte& bytes ); + + virtual int Disconnect(); + virtual int Connect( unsigned short port , const char serverName[] ); + + virtual int Listen(); + + private: + int InitiateSocket(); + void SetBlockingMode( bool blocking ); + + int socket; + + }; + } +} + +#endif \ No newline at end of file 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; i + 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 new file mode 100644 index 00000000..80edc8b1 --- /dev/null +++ b/Code/Network/NetworkDependencies/ITranslate.h @@ -0,0 +1,24 @@ +#ifndef NETWORK_DEPENDENCIES_I_TRANSLATE +#define NETWORK_DEPENDENCIES_I_TRANSLATE + +////////////////////////////////// +// Created by Sam Svensson 2013 // +////////////////////////////////// + +namespace Oyster +{ + namespace Network + { + class OysterByte; + class ITranslate + { + + 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; + + }; + } +} +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Listener.cpp b/Code/Network/NetworkDependencies/Listener.cpp new file mode 100644 index 00000000..c441d045 --- /dev/null +++ b/Code/Network/NetworkDependencies/Listener.cpp @@ -0,0 +1,69 @@ +#include "Listener.h" + +using namespace Oyster::Network::Server; + +Listener::Listener() +{ + connection = NULL; +} + +Listener::~Listener() +{ + if(connection) + { + delete connection; + } +} + +bool Listener::Init(unsigned int port) +{ + connection = new Connection(); + + connection->InitiateServer(port); + + thread.Create(this, true); + + return true; +} + +void Listener::Shutdown() +{ + thread.Terminate(); +} + +void Listener::SetPostBox(Oyster::Network::IPostBox* postBox) +{ + mutex.LockMutex(); + this->postBox = postBox; + mutex.UnlockMutex(); +} + +int Listener::Accept() +{ + int clientSocket = 0; + clientSocket = connection->Listen(); + + mutex.LockMutex(); + postBox->PostMessage(clientSocket); + 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 new file mode 100644 index 00000000..8bb16a0f --- /dev/null +++ b/Code/Network/NetworkDependencies/Listener.h @@ -0,0 +1,54 @@ +#ifndef NETWORK_SERVER_LISTENER_H +#define NETWORK_SERVER_LISTENER_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "IListener.h" +#include "../NetworkDependencies/Connection.h" +#include "../../Misc/Thread/OysterThread.h" +#include "../../Misc/Thread/OysterMutex.h" +#include "IPostBox.h" + +namespace Oyster +{ + namespace Network + { + namespace Server + { + class Listener : public ::Oyster::Thread::IThreadObject + { + public: + Listener(); + ~Listener(); + + bool Init(unsigned int port); + void Shutdown(); + + void SetPostBox(IPostBox* postBox); + + //Thread functions + bool DoWork(); + void ThreadEntry(); + void ThreadExit(); + + private: + //Function that runs in the thread. + int Accept(); + + + private: + ::Oyster::Network::Connection* connection; + + ::Oyster::Thread::OysterThread thread; + OysterMutex mutex; + + IPostBox* postBox; + + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp new file mode 100644 index 00000000..97acf526 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.cpp @@ -0,0 +1,254 @@ +#include "MessageHeader.h" +#include "../Packing.h" +#include +using namespace std; + +using namespace Oyster::Network; +using namespace Oyster::Network::Messages; +using namespace Oyster::Network::Protocols; + +MessageHeader::MessageHeader() +{ + size = 0; +} + +MessageHeader::~MessageHeader() +{ +} + +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; + + header.size = UnpackInt(bytes); + header.packageType = UnpackInt(bytes); + header.clientID = UnpackInt(bytes); +} + +/************************** + Pack +**************************/ + +void MessageHeader::PackBool(bool i, OysterByte& bytes) +{ + bytes.AddSize(1); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 1; +} + +void MessageHeader::PackChar(char i, OysterByte& bytes) +{ + bytes.AddSize(1); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 1; +} + +void MessageHeader::PackUnsignedChar(unsigned char i, OysterByte& bytes) +{ + bytes.AddSize(1); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 1; +} + +void MessageHeader::PackShort(short i, OysterByte& bytes) +{ + bytes.AddSize(2); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 2; +} + +void MessageHeader::PackUnsignedShort(unsigned short i, OysterByte& bytes) +{ + bytes.AddSize(2); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 2; +} + +void MessageHeader::PackInt(int i, OysterByte& bytes) +{ + bytes.AddSize(4); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 4; +} + +void MessageHeader::PackUnsignedInt(unsigned int i, OysterByte& bytes) +{ + bytes.AddSize(4); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 4; +} + +void MessageHeader::PackInt64(__int64 i, OysterByte& bytes) +{ + bytes.AddSize(8); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 8; +} + +void MessageHeader::PackUnsignedInt64(unsigned __int64 i, OysterByte& bytes) +{ + bytes.AddSize(8); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 8; +} + +void MessageHeader::PackFloat(float i, OysterByte& bytes) +{ + bytes.AddSize(4); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 4; +} + +void MessageHeader::PackFloat(float i[], unsigned int elementCount, OysterByte& bytes) +{ + bytes.AddSize(4); + //Pack number of elements + PackUnsignedInt(elementCount, bytes); + + //Pack all elements + for(int j = 0; j < (int)elementCount; j++) + { + PackFloat(i[j], bytes); + } +} + +void MessageHeader::PackDouble(double i, OysterByte& bytes) +{ + bytes.AddSize(8); + Packing::Pack(&bytes.GetByteArray()[size], i); + size += 8; +} + +void MessageHeader::PackStr(char str[], OysterByte& bytes) +{ + int totalSize = 2 + strlen(str); + bytes.AddSize(totalSize); + Packing::Pack(&bytes.GetByteArray()[size], str); + size += totalSize; +} + +void MessageHeader::PackStr(std::string str, OysterByte& bytes) +{ + int totalSize = 2 + str.length(); + bytes.AddSize(totalSize); + Packing::Pack(&bytes.GetByteArray()[size], str); + size += totalSize; +} + +/************************** + Unpack +**************************/ + +bool MessageHeader::UnpackBool(OysterByte& bytes) +{ + bool i = Packing::Unpackb(&bytes.GetByteArray()[size]); + size += 1; + return i; +} + +char MessageHeader::UnpackChar(OysterByte& bytes) +{ + char i = Packing::Unpackc(&bytes.GetByteArray()[size]); + size += 1; + return i; +} + +unsigned char MessageHeader::UnpackUnsignedChar(OysterByte& bytes) +{ + unsigned char i = Packing::UnpackC(&bytes.GetByteArray()[size]); + size += 1; + return i; +} + +short MessageHeader::UnpackShort(OysterByte& bytes) +{ + short i = Packing::Unpacks(&bytes.GetByteArray()[size]); + size += 2; + return i; +} + +unsigned short MessageHeader::UnpackUnsignedShort(OysterByte& bytes) +{ + unsigned short i = Packing::UnpackS(&bytes.GetByteArray()[size]); + size += 2; + return i; +} + +int MessageHeader::UnpackInt(OysterByte& bytes) +{ + int i = Packing::Unpacki(&bytes.GetByteArray()[size]); + size += 4; + return i; +} + +unsigned int MessageHeader::UnpackUnsignedInt(OysterByte& bytes) +{ + unsigned int i = Packing::UnpackI(&bytes.GetByteArray()[size]); + size += 4; + return i; +} + +__int64 MessageHeader::UnpackInt64(OysterByte& bytes) +{ + __int64 i = Packing::Unpacki64(&bytes.GetByteArray()[size]); + size += 8; + return i; +} + +unsigned __int64 MessageHeader::UnpackUnsignedInt64(OysterByte& bytes) +{ + unsigned __int64 i = Packing::UnpackI64(&bytes.GetByteArray()[size]); + size += 8; + return i; +} + +float MessageHeader::UnpackFloat(OysterByte& bytes) +{ + float i = Packing::Unpackf(&bytes.GetByteArray()[size]); + size += 4; + return i; +} + +float* MessageHeader::UnpackFloat(unsigned int& elementCount, OysterByte& bytes) +{ + float* i; + + elementCount = UnpackUnsignedInt(bytes); + + i = new float[elementCount]; + for(int j = 0; j < (int)elementCount; j++) + { + i[j] = UnpackFloat(bytes); + } + + return i; +} + +double MessageHeader::UnpackDouble(OysterByte& bytes) +{ + double i = Packing::Unpackd(&bytes.GetByteArray()[size]); + size += 8; + return i; +} + +std::string MessageHeader::UnpackStr(OysterByte& bytes) +{ + std::string str = Packing::UnpackStr(&bytes.GetByteArray()[size]); + size += 2 + str.length(); + return str; +} + +void MessageHeader::SetSize(OysterByte& bytes) +{ + 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 new file mode 100644 index 00000000..095ebc1e --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageHeader.h @@ -0,0 +1,88 @@ +#ifndef NETWORK_DEPENDENCIES_MESSAGE_HEADER_H +#define NETWORK_DEPENDENCIES_MESSAGE_HEADER_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include +#include "../Protocols.h" +#include "../OysterByte.h" + +namespace Oyster +{ + namespace Network + { + namespace Messages + { + class MessageHeader + { + public: + MessageHeader(); + virtual ~MessageHeader(); + + 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, OysterByte& bytes); + + void PackChar(char i, OysterByte& bytes); + void PackUnsignedChar(unsigned char i, OysterByte& bytes); + + void PackShort(short i, OysterByte& bytes); + void PackUnsignedShort(unsigned short i, OysterByte& bytes); + + void PackInt(int i, OysterByte& bytes); + void PackUnsignedInt(unsigned int i, OysterByte& bytes); + + void PackInt64(__int64 i, OysterByte& bytes); + void PackUnsignedInt64(unsigned __int64 i, OysterByte& bytes); + + 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[], 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(OysterByte& bytes); + + char UnpackChar(OysterByte& bytes); + unsigned char UnpackUnsignedChar(OysterByte& bytes); + + short UnpackShort(OysterByte& bytes); + unsigned short UnpackUnsignedShort(OysterByte& bytes); + + int UnpackInt(OysterByte& bytes); + unsigned int UnpackUnsignedInt(OysterByte& bytes); + + __int64 UnpackInt64(OysterByte& bytes); + unsigned __int64 UnpackUnsignedInt64(OysterByte& bytes); + + float UnpackFloat(OysterByte& bytes); + float* UnpackFloat(unsigned int& elementCount, OysterByte& bytes); + double UnpackDouble(OysterByte& bytes); + + std::string UnpackStr(OysterByte& bytes); + + //TODO: Add Unpack functions for Vec2, 3, 4 and maybe Matrix. Etc. + + + //Sets the this->size to the first position in msg + void SetSize(OysterByte& bytes); + + private: + unsigned 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..7fcb1a71 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.cpp @@ -0,0 +1,30 @@ +#include "MessageTest.h" + +using namespace Oyster::Network; +using namespace Oyster::Network::Messages; +using namespace Oyster::Network::Protocols; + +MessageTest::MessageTest() +{ +} + +MessageTest::~MessageTest() +{ +} + +void MessageTest::Pack(ProtocolHeader& header, OysterByte& bytes) +{ + MessageHeader::Pack(header, bytes); + + PackStr(static_cast(&header)->textMessage, bytes); + PackFloat(static_cast(&header)->f, static_cast(&header)->numOfFloats, bytes); + SetSize(bytes); +} + +void MessageTest::Unpack(OysterByte& bytes, ProtocolHeader& header) +{ + MessageHeader::Unpack(bytes, header); + + 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 new file mode 100644 index 00000000..ff636e56 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessageTest.h @@ -0,0 +1,31 @@ +#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 Pack(Protocols::ProtocolHeader& header, OysterByte& bytes); + virtual void Unpack(OysterByte& bytes, Protocols::ProtocolHeader& header); + + private: + }; + } + } +} + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Messages/MessagesInclude.h b/Code/Network/NetworkDependencies/Messages/MessagesInclude.h new file mode 100644 index 00000000..8f4d41e3 --- /dev/null +++ b/Code/Network/NetworkDependencies/Messages/MessagesInclude.h @@ -0,0 +1,11 @@ +#ifndef NETWORK_DEPENDENCIES_MESSAGES_INCLUDE_H +#define NETWORK_DEPENDENCIES_MESSAGES_INCLUDE_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "MessageHeader.h" +#include "MessageTest.h" + +#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/Network.h b/Code/Network/NetworkDependencies/Network.h deleted file mode 100644 index 2aa95b45..00000000 --- a/Code/Network/NetworkDependencies/Network.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef NETWORK_H -#define NETWORK_H -#include "NetworkIncludes.h" -#include "EventStructs.h" -#include "NetworkUpdateStructs.h" -#include "NetworkInitStructs.h" -#include "EventStructs.h" -#include "Event.h" -#include "NetworkMiscFunctions.h" -#include "NetworkTimer.h" -#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkConstants.h b/Code/Network/NetworkDependencies/NetworkConstants.h deleted file mode 100644 index c0b23037..00000000 --- a/Code/Network/NetworkDependencies/NetworkConstants.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#ifndef NET_CONST_H -#define NET_CONST_H -//const int PLAYER_WAIT_COUNT = 1; -const int PLAYER_MAX_COUNT = 8; -const float LOBBY_WAIT_TIME = 4; -/*namespace Network -{ - void LoadData(){} -}*/ -#endif \ No newline at end of file diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj index d75cedab..dfabbcba 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj @@ -27,7 +27,7 @@ StaticLibrary true v110 - MultiByte + Unicode StaticLibrary @@ -69,28 +69,36 @@ $(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) Level3 Disabled true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +109,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -114,7 +122,7 @@ true true true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -129,7 +137,7 @@ true true true - ..\..\Misc;..\..\OysterMath;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -137,35 +145,38 @@ true - - - - - - - - - - - - - - - - - {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} - - {f10cbc03-9809-4cba-95d8-327c287b18ee} - true - true - true - false - false - + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters index 55401224..74cb9a56 100644 --- a/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters +++ b/Code/Network/NetworkDependencies/NetworkDependencies.vcxproj.filters @@ -1,60 +1,31 @@  - - {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 - + + + + + + + + + - - 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 - + + + + + + + + + + + + + + + \ No newline at end of file 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/OysterByte.cpp b/Code/Network/NetworkDependencies/OysterByte.cpp new file mode 100644 index 00000000..ef7aa434 --- /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 < (int)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..87a0103c --- /dev/null +++ b/Code/Network/NetworkDependencies/OysterByte.h @@ -0,0 +1,47 @@ +#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*(); + + 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/Packing.cpp b/Code/Network/NetworkDependencies/Packing.cpp new file mode 100644 index 00000000..7adc395c --- /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++ = (char)i; + } + + void Pack(unsigned char buffer[], unsigned short i) + { + *buffer++ = i >> 8; + *buffer++ = (char)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++ = (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++ = (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) + 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 (float)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..7a52c644 --- /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/NetworkDependencies/PostBox.h b/Code/Network/NetworkDependencies/PostBox.h new file mode 100644 index 00000000..b2e553f8 --- /dev/null +++ b/Code/Network/NetworkDependencies/PostBox.h @@ -0,0 +1,69 @@ +#ifndef NETWORK_DEPENDENCIES_POST_BOX_H +#define NETWORK_DEPENDENCIES_POST_BOX_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "IPostBox.h" +#include "../../Misc/Thread/OysterMutex.h" +#include "../../Misc/ThreadSafeQueue.h" + +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 + { + public: + PostBox(); + virtual ~PostBox(); + + virtual void PostMessage(T& message); + virtual void FetchMessage(T& message); + virtual bool IsFull(); + + private: + Oyster::Queue::ThreadSafeQueue messages; + + }; + + //Implementation of PostBox + template + PostBox::PostBox() + { + } + + template + PostBox::~PostBox() + { + } + + template + void PostBox::PostMessage(T& message) + { + messages.Push(message); + } + + template + void PostBox::FetchMessage(T& message) + { + if(IsFull()) + { + message = messages.Front(); + messages.Pop(); + } + } + + template + bool PostBox::IsFull() + { + return !messages.IsEmpty(); + } + } +} + +#endif \ 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..8defcfb3 --- /dev/null +++ b/Code/Network/NetworkDependencies/Protocols.h @@ -0,0 +1,85 @@ +#ifndef NETWORK_DEPENDENCIES_PROTOCOLS_H +#define NETWORK_DEPENDENCIES_PROTOCOLS_H + +////////////////////////////////////// +// Created by Sam Svensson 2013 +// Holder structs for our protocols +// with the use of union. +// each packagetyp +// is linked to a protocol +////////////////////////////////////// + +#include + +namespace Oyster +{ + namespace Network + { + namespace Protocols + { + enum PackageType + { + PackageType_header, + PackageType_test, + PackageType_input, + PackageType_update_position + }; + + struct ProtocolHeader + { + int size; + int packageType; + int clientID; + + ProtocolHeader() { this->packageType = PackageType_header; } + virtual ~ProtocolHeader() { } + }; + + struct ProtocolTest : public ProtocolHeader + { + std::string textMessage; + unsigned int numOfFloats; + float *f; + + ProtocolTest() { this->packageType = PackageType_test; } + 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: + PackageType type; + union + { + ProtocolHeader* pHeader; + ProtocolTest *pTest; + + }Protocol; + + void Release() + { + switch(type) + { + case PackageType_header: + if(Protocol.pHeader) + { + delete Protocol.pHeader; + } + break; + case PackageType_test: + if(Protocol.pTest) + { + delete Protocol.pTest; + } + break; + } + } + }; + } + } +} + +#endif \ 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..4bb739ca --- /dev/null +++ b/Code/Network/NetworkDependencies/Translator.cpp @@ -0,0 +1,64 @@ +#include "Translator.h" + +using namespace Oyster::Network; +using namespace ::Protocols; +using namespace ::Messages; + +void Translator::Pack( ProtocolHeader &header, OysterByte& bytes ) +{ + MessageHeader *message = NULL; + + switch(header.packageType) + { + case PackageType_header: + message = new MessageHeader(); + break; + + case PackageType_test: + message = new MessageTest(); + break; + } + + if(message != NULL) + { + message->Pack(header, bytes); + + delete message; + message = NULL; + } +} + +void Translator::Unpack(ProtocolSet* set, OysterByte& bytes ) +{ + ProtocolHeader *header = new ProtocolHeader(); + MessageHeader *message = new MessageHeader(); + + message->Unpack(bytes, *header); + delete message; + message = NULL; + + //Switch to the correct package. + set->type = (PackageType)header->packageType; + switch(set->type) + { + case PackageType_header: + message = new MessageHeader(); + set->Protocol.pHeader = new ProtocolHeader; + message->Unpack(bytes, *set->Protocol.pHeader); + break; + + case PackageType_test: + message = new MessageTest(); + set->Protocol.pTest = new ProtocolTest; + message->Unpack(bytes, *set->Protocol.pTest); + break; + } + + 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 new file mode 100644 index 00000000..56459f72 --- /dev/null +++ b/Code/Network/NetworkDependencies/Translator.h @@ -0,0 +1,32 @@ +#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" +#include "OysterByte.h" + +namespace Oyster +{ + namespace Network + { + class Translator : public ITranslate + { + public: + Translator () { }; + ~Translator() { }; + + void Pack (Protocols::ProtocolHeader &header, OysterByte& bytes ); + void Unpack (Protocols::ProtocolSet* set, OysterByte& bytes ); + + private: + + }; + } +} + +#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/WinsockFunctions.cpp b/Code/Network/NetworkDependencies/WinsockFunctions.cpp new file mode 100644 index 00000000..ea3c3b00 --- /dev/null +++ b/Code/Network/NetworkDependencies/WinsockFunctions.cpp @@ -0,0 +1,39 @@ +#include "WinsockFunctions.h" +#include + +bool InitWinSock() +{ + WSADATA wsaData; + return WSAStartup(MAKEWORD(2, 2), &wsaData) == NO_ERROR; +} + +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; + } + + //Added this if bufLen is 0 + return retVal; +} \ 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..a4edf38d --- /dev/null +++ b/Code/Network/NetworkDependencies/WinsockFunctions.h @@ -0,0 +1,15 @@ +#ifndef NETWORK_DEPENDENCIES_WINSOCK_FUNCTIONS_H +#define NETWORK_DEPENDENCIES_WINSOCK_FUNCTIONS_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include + +void ShutdownWinSock(); +bool InitWinSock(); + +std::wstring GetErrorMessage(int errorCode); + +#endif \ 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/Client.cpp b/Code/Network/OysterNetworkClient/Client.cpp new file mode 100644 index 00000000..daffe9b6 --- /dev/null +++ b/Code/Network/OysterNetworkClient/Client.cpp @@ -0,0 +1,41 @@ +#include "Client.h" + +using namespace Oyster::Network::Client; + +Client::Client() +{ + connection = new Connection(); +} + +Client::~Client() +{ + delete this->connection; + connection = 0; +} + +int Client::Connect(unsigned int port, char filename[]) +{ + int errorCode; + + if((errorCode = connection->InitiateClient()) != 0) + { + return errorCode; + } + + if((errorCode = connection->Connect(port, filename)) != 0) + { + return errorCode; + } + + return 0; +} + +void Client::Send(Oyster::Network::OysterByte& bytes) +{ + connection->Send(bytes); +} + +void Client::Recv(Oyster::Network::OysterByte& bytes) +{ + connection->Recieve(bytes); +} \ 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..6e69e657 --- /dev/null +++ b/Code/Network/OysterNetworkClient/Client.h @@ -0,0 +1,35 @@ +#ifndef NETWORK_CLIENT_CLIENT_H +#define NETWORK_CLIENT_CLIENT_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "../NetworkDependencies/Connection.h" +#include "../NetworkDependencies/OysterByte.h" + +namespace Oyster +{ + namespace Network + { + namespace Client + { + class Client + { + public: + Client(); + ~Client(); + + int Connect(unsigned int port, char filename[]); + + void Send(OysterByte& bytes); + void Recv(OysterByte& bytes); + + private: + ::Oyster::Network::Connection* connection; + }; + } + } +} + +#endif \ No newline at end of file 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 index 5c297686..b8f1057f 100644 --- a/Code/Network/OysterNetworkClient/ClientMain.cpp +++ b/Code/Network/OysterNetworkClient/ClientMain.cpp @@ -1,79 +1,121 @@ -#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; +#include +#include +#include +#include "../NetworkDependencies/WinsockFunctions.h" +#include "..\NetworkDependencies\Translator.h" +#include "..\NetworkDependencies\Protocols.h" +#include "../NetworkDependencies/OysterByte.h" +#include "../../Misc/ThreadSafeQueue.h" +#include "Client.h" - 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); +#pragma comment(lib, "ws2_32.lib") - 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) +using namespace std; +using namespace Oyster::Network::Protocols; +using namespace Oyster::Network::Client; + +void chat(Client &client); + +int main() +{ + int errorCode; + + char msgRecv[255] = "\0"; + + InitWinSock(); + + cout << "Client" << endl; + + //Create Client + Client client; + + //Connect to server + errorCode = client.Connect(9876, "localhost"); + + if(errorCode != 0) { - client.sendMessage(tst); - client.sendUserData(); - getline(std::cin, tst); + wstring errorTest = GetErrorMessage(errorCode); + wcout << "errorMessage: " << errorTest << endl; } - //Kills off the thread and connection - //DWORD eCode=0; - //TerminateThread(threadhandle, eCode); - client.closeConnection(); + + chat(client); + + ShutdownWinSock(); + + system("pause"); return 0; -}*/ \ No newline at end of file +} + +void chat(Client &client) +{ + Oyster::Network::Translator *t = new Oyster::Network::Translator(); + + Oyster::Network::OysterByte msgRecv; + string msgSend = ""; + + ProtocolSet* set = new ProtocolSet; + 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; + + while(!chatDone) + { + client.Recv(msgRecv); + + t->Unpack(set, msgRecv); + + switch(set->type) + { + case PackageType_header: + break; + case PackageType_test: + cout <<"Client 2: " << set->Protocol.pTest->textMessage <Protocol.pTest->numOfFloats; i++) + { + cout << set->Protocol.pTest->f[i] << ' ' ; + } + cout << endl; + break; + } + + set->Release(); + msgRecv.Clear(1000); + + /*std::getline(std::cin, msgSend); + + + + if( msgSend != "exit") + { + if(msgSend.length() < 1) + { + msgSend = "ERROR!"; + } + + test.textMessage = msgSend; + + t->Pack(test, msgRecv); + + client.Send(msgRecv); + } + + else + { + chatDone = true; + } + + cin.clear();*/ + + } + + delete t; + delete set; +} \ 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..f4e13099 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 @@ -69,28 +69,36 @@ $(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) Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +109,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -114,7 +122,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -129,7 +137,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -137,28 +145,21 @@ true - - - - - - - - - - - {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} - - {f10cbc03-9809-4cba-95d8-327c287b18ee} - {c5aa09d0-6594-4cd3-bd92-1d380c7b3b50} + + + + + + + diff --git a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters index 4327b3ae..2e5e9ef6 100644 --- a/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters +++ b/Code/Network/OysterNetworkClient/OysterNetworkClient.vcxproj.filters @@ -15,27 +15,15 @@ - - Source Files - - - Source Files - Source Files - - Source Files - - - Source Files - - + Source Files - + Header Files 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/OysterNetworkServer/Client.cpp b/Code/Network/OysterNetworkServer/Client.cpp new file mode 100644 index 00000000..5cc15eec --- /dev/null +++ b/Code/Network/OysterNetworkServer/Client.cpp @@ -0,0 +1,24 @@ +#include "Client.h" + +using namespace Oyster::Network; +using namespace Oyster::Network::Server; + +Client::Client(unsigned int socket) +{ + connection = new Connection(socket); +} + +Client::~Client() +{ + delete connection; +} + +void Client::Send(OysterByte& bytes) +{ + connection->Send(bytes); +} + +void Client::Recv(OysterByte& bytes) +{ + connection->Recieve(bytes); +} \ 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..2c5ba35f --- /dev/null +++ b/Code/Network/OysterNetworkServer/Client.h @@ -0,0 +1,34 @@ +#ifndef NETWORK_SERVER_CLIENT_H +#define NETWORK_SERVER_CLIENT_H + +///////////////////////////////////// +// Created by Pontus Fransson 2013 // +///////////////////////////////////// + +#include "../NetworkDependencies/Connection.h" +#include "../NetworkDependencies/OysterByte.h" + +namespace Oyster +{ + namespace Network + { + namespace Server + { + class Client + { + public: + Client(unsigned int socket); + ~Client(); + + void Send(OysterByte& bytes); + void Recv(OysterByte& bytes); + + private: + ::Oyster::Network::Connection* connection; + + }; + } + } +}; + +#endif \ 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..65136729 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 @@ -69,28 +69,36 @@ $(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) Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -101,7 +109,7 @@ Level3 Disabled true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -114,7 +122,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -129,7 +137,7 @@ true true true - ..\..\Misc;..\..\OysterMath;..\NetworkDependencies;%(AdditionalIncludeDirectories) + %(AdditionalIncludeDirectories) true @@ -137,37 +145,21 @@ true - - - - - - - - - - - - - - - - - - - - {2ec4dded-8f75-4c86-a10b-e1e8eb29f3ee} - - {f10cbc03-9809-4cba-95d8-327c287b18ee} - {c5aa09d0-6594-4cd3-bd92-1d380c7b3b50} + + + + + + + diff --git a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters index 15a52647..3cb5827c 100644 --- a/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters +++ b/Code/Network/OysterNetworkServer/OysterNetworkServer.vcxproj.filters @@ -15,54 +15,15 @@ - - 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 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 index 6c3d7f56..9dd0a0c1 100644 --- a/Code/Network/OysterNetworkServer/ServerMain.cpp +++ b/Code/Network/OysterNetworkServer/ServerMain.cpp @@ -1,47 +1,128 @@ -#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 +#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" -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 ); +#pragma comment(lib, "ws2_32.lib") - SocketServer server; - server.loadMapList("..\\Content\\Maplist.txt"); - while (!server.isReady()); - server.startThreads(); - GameLogic::Object::init("NOT_IMPLEMENTED"); - server.startGameCreateLoop(50); - while(true) +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; + int errorCode; + + if(!InitWinSock()) { - server.updateServers(); + cout << "errorMessage: unable to start winsock" << endl; } - server.closeConnection(); + + //Create socket + Listener listener; + listener.Init(9876); + listener.SetPostBox(postBox); + Sleep(1000); + + //Start listening + //Accept a client + ProtocolTest test; + test.clientID = 0; + test.size = 2; + test.textMessage = "hej"; + test.numOfFloats = 0; + 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); + + WinTimer timer; + + vector clients; + int client = -1; + while(1) + { + client = -1; + postBox->FetchMessage(client); + if(client != -1) + { + cout << "Client connected: " << client << endl; + clients.push_back(new Client(client)); + + clients.at(clients.size()-1)->Send(recvBuffer); + } + + //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(); + + /* + ProtocolSet* set = new ProtocolSet; + + 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; + for(int i = 0; i < (int)set->Protocol.pTest->numOfFloats; i++) + { + cout << set->Protocol.pTest->f[i] << ' '; + } + cout << endl; + set->Release(); + client2.Send(recvBuffer); + + client2.Recv(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 < (int)set->Protocol.pTest->numOfFloats; i++) + { + cout << set->Protocol.pTest->f[i] << ' '; + } + cout << endl; + set->Release(); + client1.Send(recvBuffer); + } + + + ShutdownWinSock(); + delete set; + */ + system("pause"); 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/OysterGraphics/Core/Core.cpp b/Code/OysterGraphics/Core/Core.cpp index a425ae57..6ecc4326 100644 --- a/Code/OysterGraphics/Core/Core.cpp +++ b/Code/OysterGraphics/Core/Core.cpp @@ -1,4 +1,5 @@ #include "Core.h" +#include using namespace Oyster::Graphics; using std::string; diff --git a/Code/OysterGraphics/Core/Core.h b/Code/OysterGraphics/Core/Core.h index 4efb5b8d..42343c11 100644 --- a/Code/OysterGraphics/Core/Core.h +++ b/Code/OysterGraphics/Core/Core.h @@ -158,12 +158,18 @@ namespace Oyster Pixel, Compute }; + struct ShaderData + { + size_t size; + char* data; + }; static void SetShaderEffect(ShaderEffect); static void CreateInputLayout(const D3D11_INPUT_ELEMENT_DESC *desc, int ElementCount,int VertexIndex,ID3D11InputLayout *&Layout); - static bool Init(std::wstring filename, ShaderType type, std::wstring name, bool Precompiled = true); + static bool Init(std::wstring filename, ShaderType type, std::wstring name); + static void* CreateShader(ShaderData data, ShaderType type); struct Get { @@ -184,6 +190,8 @@ namespace Oyster static void Hull(int Index); static void Domain(int Index); }; + + static void Clean(); }; //Set resulotion Before Calling Full Init diff --git a/Code/OysterGraphics/Core/Init.cpp b/Code/OysterGraphics/Core/Init.cpp index 48abd444..c69b80b4 100644 --- a/Code/OysterGraphics/Core/Init.cpp +++ b/Code/OysterGraphics/Core/Init.cpp @@ -175,7 +175,7 @@ namespace Oyster D3D11_TEXTURE2D_DESC desc; desc.MipLevels=1; desc.ArraySize=1; - desc.Format = DXGI_FORMAT_D32_FLOAT; + desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_DEPTH_STENCIL; desc.CPUAccessFlags=0; diff --git a/Code/OysterGraphics/Core/ShaderManager.cpp b/Code/OysterGraphics/Core/ShaderManager.cpp index 0b0c4fba..94f7fd57 100644 --- a/Code/OysterGraphics/Core/ShaderManager.cpp +++ b/Code/OysterGraphics/Core/ShaderManager.cpp @@ -1,6 +1,8 @@ #include "Core.h" #include #include +#include "../FileLoader/GeneralLoader.h" +#include "Resource\OysterResource.h" const char* ShaderFunction = "main"; @@ -8,15 +10,8 @@ namespace Oyster { namespace Graphics { - bool LoadPrecompiled(std::wstring filename, Core::ShaderManager::ShaderType type, std::wstring name); - bool LoadCompile(std::wstring filename, Core::ShaderManager::ShaderType type, std::wstring name); namespace { - struct ShaderData - { - size_t size; - char* data; - }; std::vector PS; std::map PSMap; @@ -26,213 +21,146 @@ namespace Oyster std::vector CS; std::map CSMap; + std::vector DS; + std::map DSMap; + + std::vector HS; + std::map HSMap; + std::vector VS; - std::vector VData; + std::vector VData; std::map VSMap; } #pragma region Init - bool Core::ShaderManager::Init(std::wstring filename, ShaderType type, std::wstring name, bool Precompiled) + bool Core::ShaderManager::Init(std::wstring filename, ShaderType type, std::wstring name) { - if(Precompiled) + void* data; + bool ForceReload; +#if defined (_DEBUG) | defined (DEBUG) + ForceReload = true; +#else + ForceReload = false; +#endif + switch (type) { - return LoadPrecompiled(filename, type, name); - } - else - { - return LoadCompile(filename, type, name); + case Oyster::Graphics::Core::ShaderManager::Vertex: + if(!VSMap.count(name) || ForceReload) + { + data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderV, -1, ForceReload); + if(data) + { + VSMap[name] = VS.size(); + VS.push_back((ID3D11VertexShader*)data); + } + } + break; + case Oyster::Graphics::Core::ShaderManager::Hull: + data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderH, -1, ForceReload); + if(!HSMap.count(name) || ForceReload) + { + if(data!=0) + { + HSMap[name] = HS.size(); + HS.push_back((ID3D11HullShader*)data); + } + } + break; + case Oyster::Graphics::Core::ShaderManager::Domain: + data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderD, -1, ForceReload); + if(!DSMap.count(name) || ForceReload) + { + if(data!=0) + { + DSMap[name] = DS.size(); + DS.push_back((ID3D11DomainShader*)data); + } + } + break; + case Oyster::Graphics::Core::ShaderManager::Geometry: + data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderG, -1, ForceReload); + if(!GSMap.count(name) || ForceReload) + { + if(data!=0) + { + GSMap[name] = GS.size(); + GS.push_back((ID3D11GeometryShader*)data); + } + } + break; + case Oyster::Graphics::Core::ShaderManager::Pixel: + data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderP, -1, ForceReload); + if(!PSMap.count(name) || ForceReload) + { + if(data!=0) + { + PSMap[name] = PS.size(); + PS.push_back((ID3D11PixelShader*)data); + } + } + break; + case Oyster::Graphics::Core::ShaderManager::Compute: + data = Resource::OysterResource::LoadResource(filename.c_str(),Loading::LoadShaderC, -1, ForceReload); + if(!CSMap.count(name) || ForceReload) + { + if(data!=0) + { + CSMap[name] = CS.size(); + CS.push_back((ID3D11ComputeShader*)data); + } + } + break; + default: + break; } return true; } - bool LoadPrecompiled(std::wstring filename, Core::ShaderManager::ShaderType type, std::wstring name) + void* Core::ShaderManager::CreateShader(Core::ShaderManager::ShaderData data, Core::ShaderManager::ShaderType type) { - - std::ifstream stream; - ShaderData sd; - - - //Create Vertex shader and Layout - stream.open(filename, std::ifstream::in | std::ifstream::binary); - if(stream.good()) - { - stream.seekg(0, std::ios::end); - sd.size = size_t(stream.tellg()); - sd.data = new char[sd.size]; - stream.seekg(0, std::ios::beg); - stream.read(&sd.data[0], sd.size); - stream.close(); - - ID3D11VertexShader* vertex; - ID3D11GeometryShader* geometry; - ID3D11PixelShader* pixel; - ID3D11ComputeShader* compute; - - switch(type) - { - case Core::ShaderManager::ShaderType::Vertex: - - if(VSMap.count(name)) - return false; - - if(FAILED(Core::device->CreateVertexShader(sd.data, sd.size, 0, &vertex))) - { - return false; - } - VSMap[name] = VS.size(); - VS.push_back(vertex); - VData.push_back(sd); - break; - - case Core::ShaderManager::ShaderType::Hull: - case Core::ShaderManager::ShaderType::Domain: - - return false; - - case Core::ShaderManager::ShaderType::Geometry: - - if(GSMap.count(name)) - return false; - if(FAILED(Core::device->CreateGeometryShader(sd.data, sd.size, 0, &geometry))) - { - return false; - } - GSMap[name] = GS.size(); - GS.push_back(geometry); - break; - - case Core::ShaderManager::ShaderType::Pixel: - - if(PSMap.count(name)) - return false; - if(FAILED(Core::device->CreatePixelShader(sd.data, sd.size, 0, &pixel))) - { - return false; - } - PSMap[name] = PS.size(); - PS.push_back(pixel); - break; - - case Core::ShaderManager::ShaderType::Compute: - - if(CSMap.count(name)) - return false; - if(FAILED(Core::device->CreateComputeShader(sd.data, sd.size, 0, &compute))) - { - return false; - } - CSMap[name] = CS.size(); - CS.push_back(compute); - break; - } - } - else + HRESULT hr; + switch (type) { - return false; + case Oyster::Graphics::Core::ShaderManager::Vertex: + ID3D11VertexShader* vs; + hr = Core::device->CreateVertexShader(data.data,data.size,NULL,&vs); + if(hr == S_OK) + VData.push_back(data); + return vs; + break; + case Oyster::Graphics::Core::ShaderManager::Hull: + ID3D11HullShader* hs; + Core::device->CreateHullShader(data.data,data.size,NULL,&hs); + delete[] data.data; + return hs; + break; + case Oyster::Graphics::Core::ShaderManager::Domain: + ID3D11DomainShader* ds; + Core::device->CreateDomainShader(data.data,data.size,NULL,&ds); + delete[] data.data; + return ds; + break; + case Oyster::Graphics::Core::ShaderManager::Geometry: + ID3D11GeometryShader* gs; + Core::device->CreateGeometryShader(data.data,data.size,NULL,&gs); + delete[] data.data; + return gs; + break; + case Oyster::Graphics::Core::ShaderManager::Pixel: + ID3D11PixelShader* ps; + Core::device->CreatePixelShader(data.data,data.size,NULL,&ps); + delete[] data.data; + return ps; + break; + case Oyster::Graphics::Core::ShaderManager::Compute: + ID3D11ComputeShader* cs; + Core::device->CreateComputeShader(data.data,data.size,NULL,&cs); + delete[] data.data; + return cs; + break; } - return true; - } - - bool LoadCompile(std::wstring filename, Core::ShaderManager::ShaderType type, std::wstring name) - { - /// \todo error reporting - ID3D10Blob *Shader,*Error; - switch(type) - { - case Core::ShaderManager::ShaderType::Pixel: - - ID3D11PixelShader* pixel; - - if(FAILED(D3DCompileFromFile(filename.c_str(),NULL,NULL,ShaderFunction,"ps_5_0",D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,0,&Shader,&Error))) - { - std::string fel = (char*)Error->GetBufferPointer(); - Error->Release(); - return false; - } - if(FAILED(Core::device->CreatePixelShader(Shader->GetBufferPointer(),Shader->GetBufferSize(),NULL,&pixel))) - { - Shader->Release(); - return false; - } - Shader->Release(); - if(!PSMap.count(name)) - { - PSMap[name] = PS.size(); - PS.push_back(pixel); - } - else - { - PS[PSMap[name]] = pixel; - } - break; - - case Core::ShaderManager::ShaderType::Geometry: - - ID3D11GeometryShader* geometry; - - if(FAILED(D3DCompileFromFile(filename.c_str(),NULL,NULL,ShaderFunction,"gs_5_0",D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,0,&Shader,&Error))) - { - std::string fel = (char*)Error->GetBufferPointer(); - Error->Release(); - return false; - } - if(FAILED(Core::device->CreateGeometryShader(Shader->GetBufferPointer(),Shader->GetBufferSize(),NULL,&geometry))) - { - Shader->Release(); - return false; - } - Shader->Release(); - if(!GSMap.count(name)) - { - GSMap[name] = GS.size(); - GS.push_back(geometry); - } - else - { - GS[GSMap[name]] = geometry; - } - break; - - case Core::ShaderManager::ShaderType::Vertex: - - ID3D11VertexShader* vertex; - - if(FAILED(D3DCompileFromFile(filename.c_str(),NULL,NULL,ShaderFunction,"vs_5_0",D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,0,&Shader,&Error))) - { - std::string fel = (char*)Error->GetBufferPointer(); - Error->Release(); - return false; - } - if(FAILED(Core::device->CreateVertexShader(Shader->GetBufferPointer(),Shader->GetBufferSize(),NULL,&vertex))) - { - Shader->Release(); - return false; - } - if(!VSMap.count(name)) - { - VSMap[name] = VS.size(); - VS.push_back(vertex); - ShaderData sd; - sd.size = Shader->GetBufferSize(); - sd.data = new char[sd.size]; - memcpy(sd.data,Shader->GetBufferPointer(),sd.size); - VData.push_back(sd); - } - else - { - VS[VSMap[name]] = vertex; - delete[] VData[VSMap[name]].data; - VData[VSMap[name]].size = Shader->GetBufferSize(); - VData[VSMap[name]].data = new char[VData[VSMap[name]].size]; - memcpy(VData[VSMap[name]].data,Shader->GetBufferPointer(),VData[VSMap[name]].size); - } - - Shader->Release(); - break; - - } - return true; + return NULL; } #pragma endregion @@ -344,8 +272,17 @@ namespace Oyster se.CBuffers.Pixel[i]->Apply(i); Core::deviceContext->RSSetState(se.RenderStates.Rasterizer); Core::deviceContext->PSSetSamplers(0,se.RenderStates.SampleCount,se.RenderStates.SampleState); + Core::deviceContext->OMSetDepthStencilState(se.RenderStates.DepthStencil,0); float test[4] = {0}; Core::deviceContext->OMSetBlendState(se.RenderStates.BlendState,test,-1); } + + void Core::ShaderManager::Clean() + { + for(int i = 0; i < VData.size(); ++i) + { + delete[] VData[i].data; + } + } } } \ No newline at end of file diff --git a/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp b/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp index e19d497f..b5de4fda 100644 --- a/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp +++ b/Code/OysterGraphics/DllInterfaces/GFXAPI.cpp @@ -3,6 +3,7 @@ #include "../Render/Resources/Resources.h" #include "../Render/Rendering/Render.h" #include "../FileLoader/ObjReader.h" +#include "../../Misc/Resource/OysterResource.h" namespace Oyster { @@ -60,7 +61,17 @@ namespace Oyster void API::DeleteModel(Model::Model* model) { + Model::ModelInfo* info = (Model::ModelInfo*)model->info; delete model; + info->Vertices->~Buffer(); + } + + void API::Clean() + { + SAFE_DELETE(Core::viewPort); + Oyster::Resource::OysterResource::Clean(); + Oyster::Graphics::Core::ShaderManager::Clean(); + Oyster::Graphics::Render::Resources::Clean(); } } } \ No newline at end of file diff --git a/Code/OysterGraphics/DllInterfaces/GFXAPI.h b/Code/OysterGraphics/DllInterfaces/GFXAPI.h index 052d99d8..e55a435f 100644 --- a/Code/OysterGraphics/DllInterfaces/GFXAPI.h +++ b/Code/OysterGraphics/DllInterfaces/GFXAPI.h @@ -28,6 +28,7 @@ namespace Oyster }; static State Init(HWND Window, bool MSAA_Quality, bool Fullscreen, Oyster::Math::Float2 StartResulotion); + static void Clean(); //! @brief from Oyster::Math Float4x4, expects corect methods static void NewFrame(Oyster::Math::Float4x4 View, Oyster::Math::Float4x4 Projection); static void RenderScene(Oyster::Graphics::Model::Model* models, int count); diff --git a/Code/OysterGraphics/FileLoader/GeneralLoader.h b/Code/OysterGraphics/FileLoader/GeneralLoader.h new file mode 100644 index 00000000..fcce1e02 --- /dev/null +++ b/Code/OysterGraphics/FileLoader/GeneralLoader.h @@ -0,0 +1,33 @@ +#pragma once +#include "..\..\Misc\Resource\OysterResource.h" +namespace Oyster +{ + namespace Graphics + { + namespace Loading + { + void UnloadTexture(void* loadedData); + void LoadTexture(const wchar_t filename[], Oyster::Resource::CustomData& out); + + void UnloadShaderP(void* loadedData); + void LoadShaderP(const wchar_t filename[], Oyster::Resource::CustomData& out); + + void UnloadShaderG(void* loadedData); + void LoadShaderG(const wchar_t filename[], Oyster::Resource::CustomData& out); + + void UnloadShaderC(void* loadedData); + void LoadShaderC(const wchar_t filename[], Oyster::Resource::CustomData& out); + + void UnloadShaderV(void* loadedData); + void LoadShaderV(const wchar_t filename[], Oyster::Resource::CustomData& out); + + void UnloadShaderH(void* loadedData); + void LoadShaderH(const wchar_t filename[], Oyster::Resource::CustomData& out); + + void UnloadShaderD(void* loadedData); + void LoadShaderD(const wchar_t filename[], Oyster::Resource::CustomData& out); + + void LoadShader(const wchar_t filename[], Oyster::Resource::CustomData& out, int type); + } + } +} \ No newline at end of file diff --git a/Code/OysterGraphics/FileLoader/ObjReader.cpp b/Code/OysterGraphics/FileLoader/ObjReader.cpp index aa613710..7eb1e268 100644 --- a/Code/OysterGraphics/FileLoader/ObjReader.cpp +++ b/Code/OysterGraphics/FileLoader/ObjReader.cpp @@ -2,7 +2,7 @@ #include "..\Definitions\GraphicalDefinition.h" #include #include -#include "TextureLoader.h" +#include "GeneralLoader.h" using namespace std; OBJReader::OBJReader() @@ -24,7 +24,7 @@ void OBJReader::readOBJFile( std::wstring fileName ) float vertexData; std::string face1, face2, face3; - inStream.open( fileName, std::fstream::in ); + inStream.open( fileName + L".obj", std::fstream::in ); if( inStream.is_open() ) { @@ -94,6 +94,8 @@ void OBJReader::readOBJFile( std::wstring fileName ) } inStream.close(); + + Mat = Oyster::Resource::OysterResource::LoadResource((fileName + L".jpg").c_str(),Oyster::Graphics::Loading::LoadTexture); } Oyster::Graphics::Model::ModelInfo* OBJReader::toModel() @@ -117,9 +119,7 @@ Oyster::Graphics::Model::ModelInfo* OBJReader::toModel() modelInfo->Indexed = false; modelInfo->VertexCount = (int)desc.NumElements; modelInfo->Vertices = b; - - //Oyster::Resource::OysterResource::LoadResource(L"Normal.png",(Oyster::Resource::CustomLoadFunction)Oyster::Graphics::Loading::LoadTexture); - + modelInfo->Material.push_back((ID3D11ShaderResourceView*)Mat); return modelInfo; } diff --git a/Code/OysterGraphics/FileLoader/ObjReader.h b/Code/OysterGraphics/FileLoader/ObjReader.h index ed579023..c4a2e399 100644 --- a/Code/OysterGraphics/FileLoader/ObjReader.h +++ b/Code/OysterGraphics/FileLoader/ObjReader.h @@ -43,6 +43,7 @@ class OBJReader int _mPos, _mNormal, _mTexel; void stringSplit( std::string strToSplit ); void addToOBJarray(); + void* Mat; public: OBJReader(); diff --git a/Code/OysterGraphics/FileLoader/ShaderLoader.cpp b/Code/OysterGraphics/FileLoader/ShaderLoader.cpp new file mode 100644 index 00000000..5a7ba9e3 --- /dev/null +++ b/Code/OysterGraphics/FileLoader/ShaderLoader.cpp @@ -0,0 +1,189 @@ +#include "GeneralLoader.h" +#include "..\Core\Dx11Includes.h" +#include "..\Core\Core.h" +#include + + +namespace Oyster +{ + namespace Graphics + { + namespace Loading + { + void UnloadShaderP(void* loadedData) + { + ID3D11PixelShader* ps = ((ID3D11PixelShader*)loadedData); + SAFE_RELEASE(ps); + } + + void UnloadShaderG(void* loadedData) + { + ID3D11GeometryShader* gs = ((ID3D11GeometryShader*)loadedData); + SAFE_RELEASE(gs); + } + + void UnloadShaderC(void* loadedData) + { + ID3D11ComputeShader* ps = ((ID3D11ComputeShader*)loadedData); + SAFE_RELEASE(ps); + } + + void UnloadShaderH(void* loadedData) + { + ID3D11HullShader* ps = ((ID3D11HullShader*)loadedData); + SAFE_RELEASE(ps); + } + + void UnloadShaderD(void* loadedData) + { + ID3D11DomainShader* ps = ((ID3D11DomainShader*)loadedData); + SAFE_RELEASE(ps); + } + + void UnloadShaderV(void* loadedData) + { + ID3D11VertexShader* ps = ((ID3D11VertexShader*)loadedData); + SAFE_RELEASE(ps); + } + + void LoadShaderP(const wchar_t filename[], Oyster::Resource::CustomData& out) + { + LoadShader(filename,out,Core::ShaderManager::Pixel); + if(out.loadedData==NULL) + { + memset(&out,0,sizeof(out)); + return; + } + out.resourceUnloadFnc = UnloadShaderP; + } + + void LoadShaderG(const wchar_t filename[], Oyster::Resource::CustomData& out) + { + + LoadShader(filename,out,Core::ShaderManager::Geometry); + if(out.loadedData==NULL) + { + memset(&out,0,sizeof(out)); + return; + } + out.resourceUnloadFnc = UnloadShaderG; + } + + void LoadShaderC(const wchar_t filename[], Oyster::Resource::CustomData& out) + { + + LoadShader(filename,out,Core::ShaderManager::Compute); + if(out.loadedData==NULL) + { + memset(&out,0,sizeof(out)); + return; + } + out.resourceUnloadFnc = UnloadShaderC; + } + + void LoadShaderH(const wchar_t filename[], Oyster::Resource::CustomData& out) + { + + LoadShader(filename,out,Core::ShaderManager::Hull); + if(out.loadedData==NULL) + { + memset(&out,0,sizeof(out)); + return; + } + out.resourceUnloadFnc = UnloadShaderH; + } + + void LoadShaderD(const wchar_t filename[], Oyster::Resource::CustomData& out) + { + + LoadShader(filename,out,Core::ShaderManager::Domain); + if(out.loadedData==NULL) + { + memset(&out,0,sizeof(out)); + return; + } + out.resourceUnloadFnc = UnloadShaderD; + } + + void LoadShaderV(const wchar_t filename[], Oyster::Resource::CustomData& out) + { + + LoadShader(filename,out,Core::ShaderManager::Vertex); + if(out.loadedData==NULL) + { + memset(&out,0,sizeof(out)); + return; + } + out.resourceUnloadFnc = UnloadShaderV; + } + + void LoadShader(const wchar_t filename[], Oyster::Resource::CustomData& out, int type) + { + Core::ShaderManager::ShaderData data; +#ifdef _DEBUG + ID3DBlob *Shader=NULL, *Error=NULL; + HRESULT hr; + switch (Core::ShaderManager::ShaderType(type)) + { + case Oyster::Graphics::Core::ShaderManager::Vertex: + hr = D3DCompileFromFile(filename,NULL,D3D_COMPILE_STANDARD_FILE_INCLUDE,"main","vs_5_0",D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,0,&Shader,&Error); + break; + case Oyster::Graphics::Core::ShaderManager::Hull: + hr = D3DCompileFromFile(filename,NULL,D3D_COMPILE_STANDARD_FILE_INCLUDE,"main","hs_5_0",D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,0,&Shader,&Error); + break; + case Oyster::Graphics::Core::ShaderManager::Domain: + hr = D3DCompileFromFile(filename,NULL,D3D_COMPILE_STANDARD_FILE_INCLUDE,"main","ds_5_0",D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,0,&Shader,&Error); + break; + case Oyster::Graphics::Core::ShaderManager::Geometry: + hr = D3DCompileFromFile(filename,NULL,D3D_COMPILE_STANDARD_FILE_INCLUDE,"main","gs_5_0",D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,0,&Shader,&Error); + break; + case Oyster::Graphics::Core::ShaderManager::Pixel: + hr = D3DCompileFromFile(filename,NULL,D3D_COMPILE_STANDARD_FILE_INCLUDE,"main","ps_5_0",D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,0,&Shader,&Error); + break; + case Oyster::Graphics::Core::ShaderManager::Compute: + hr = D3DCompileFromFile(filename,NULL,D3D_COMPILE_STANDARD_FILE_INCLUDE,"main","cs_5_0",D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,0,&Shader,&Error); + break; + default: + break; + } + + if(FAILED(hr)) + { + if(Error) + { + Error->Release(); + } + if(Shader) + { + Shader->Release(); + } + memset(&out,0,sizeof(out)); + return; + } + + data.size = Shader->GetBufferSize(); + data.data = new char[data.size]; + memcpy(data.data,Shader->GetBufferPointer(),data.size); +#else + stream.open(filename, std::ifstream::in | std::ifstream::binary); + if(stream.good()) + { + stream.seekg(0, std::ios::end); + sd.size = size_t(stream.tellg()); + sd.data = new char[sd.size]; + stream.seekg(0, std::ios::beg); + stream.read(&sd.data[0], sd.size); + stream.close(); + } + else + { + memset(&out,0,sizeof(out)); + return; + } + +#endif + out.loadedData = Core::ShaderManager::CreateShader(data, Core::ShaderManager::ShaderType(type)); + } + } + } +} \ No newline at end of file diff --git a/Code/OysterGraphics/FileLoader/TextureLoader.cpp b/Code/OysterGraphics/FileLoader/TextureLoader.cpp index 24caeae3..1c6ba263 100644 --- a/Code/OysterGraphics/FileLoader/TextureLoader.cpp +++ b/Code/OysterGraphics/FileLoader/TextureLoader.cpp @@ -1,7 +1,726 @@ -#include "TextureLoader.h" +#include "GeneralLoader.h" #include "..\Core\Dx11Includes.h" +#include "..\Core\Core.h" -Oyster::Resource::CustomData* Oyster::Graphics::Loading::LoadTexture() +HRESULT CreateWICTextureFromFileEx( ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + bool forceSRGB, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView ); + +void Oyster::Graphics::Loading::LoadTexture(const wchar_t filename[], Oyster::Resource::CustomData& out) { - return NULL; + ID3D11ShaderResourceView* srv = NULL; + HRESULT hr = CreateWICTextureFromFileEx(Core::device,Core::deviceContext,filename,0,D3D11_USAGE_DEFAULT,D3D11_BIND_SHADER_RESOURCE,0,0,false,NULL,&srv); + if(hr!=S_OK) + { + memset(&out,0,sizeof(out)); + } + else + { + out.loadedData = (void*)srv; + out.resourceUnloadFnc = Loading::UnloadTexture; + } +} + +void Oyster::Graphics::Loading::UnloadTexture(void* data) +{ + ID3D11ShaderResourceView* srv = (ID3D11ShaderResourceView*)data; + SAFE_RELEASE(srv); +} + + +#include +#include +#include + +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) +#include +#endif + +#pragma warning(push) +#pragma warning(disable : 4005) +#include +#pragma warning(pop) + + +template class ScopedObject : public Microsoft::WRL::ComPtr {}; + +//------------------------------------------------------------------------------------- +// WIC Pixel Format Translation Data +//------------------------------------------------------------------------------------- +struct WICTranslate +{ + GUID wic; + DXGI_FORMAT format; +}; + +static WICTranslate g_WICFormats[] = +{ + { GUID_WICPixelFormat128bppRGBAFloat, DXGI_FORMAT_R32G32B32A32_FLOAT }, + + { GUID_WICPixelFormat64bppRGBAHalf, DXGI_FORMAT_R16G16B16A16_FLOAT }, + { GUID_WICPixelFormat64bppRGBA, DXGI_FORMAT_R16G16B16A16_UNORM }, + + { GUID_WICPixelFormat32bppRGBA, DXGI_FORMAT_R8G8B8A8_UNORM }, + { GUID_WICPixelFormat32bppBGRA, DXGI_FORMAT_B8G8R8A8_UNORM }, // DXGI 1.1 + { GUID_WICPixelFormat32bppBGR, DXGI_FORMAT_B8G8R8X8_UNORM }, // DXGI 1.1 + + { GUID_WICPixelFormat32bppRGBA1010102XR, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM }, // DXGI 1.1 + { GUID_WICPixelFormat32bppRGBA1010102, DXGI_FORMAT_R10G10B10A2_UNORM }, + +#ifdef DXGI_1_2_FORMATS + + { GUID_WICPixelFormat16bppBGRA5551, DXGI_FORMAT_B5G5R5A1_UNORM }, + { GUID_WICPixelFormat16bppBGR565, DXGI_FORMAT_B5G6R5_UNORM }, + +#endif // DXGI_1_2_FORMATS + + { GUID_WICPixelFormat32bppGrayFloat, DXGI_FORMAT_R32_FLOAT }, + { GUID_WICPixelFormat16bppGrayHalf, DXGI_FORMAT_R16_FLOAT }, + { GUID_WICPixelFormat16bppGray, DXGI_FORMAT_R16_UNORM }, + { GUID_WICPixelFormat8bppGray, DXGI_FORMAT_R8_UNORM }, + + { GUID_WICPixelFormat8bppAlpha, DXGI_FORMAT_A8_UNORM }, +}; + +//------------------------------------------------------------------------------------- +// WIC Pixel Format nearest conversion table +//------------------------------------------------------------------------------------- + +struct WICConvert +{ + GUID source; + GUID target; +}; + +static WICConvert g_WICConvert[] = +{ + // Note target GUID in this conversion table must be one of those directly supported formats (above). + + { GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + + { GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + + { GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + { GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM + + { GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT + { GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT + +#ifdef DXGI_1_2_FORMATS + + { GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_UNORM + +#else + + { GUID_WICPixelFormat16bppBGR555, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat16bppBGRA5551, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat16bppBGR565, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + +#endif // DXGI_1_2_FORMATS + + { GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102 }, // DXGI_FORMAT_R10G10B10A2_UNORM + + { GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + + { GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + + { GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + { GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT + + { GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + { GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT + + { GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + { GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM + { GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM + { GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT +#endif + + // We don't support n-channel formats +}; + +static bool g_WIC2 = false; + +//-------------------------------------------------------------------------------------- + +bool _IsWIC2() +{ + return g_WIC2; +} + +IWICImagingFactory* _GetWIC() +{ + static IWICImagingFactory* s_Factory = nullptr; + + if ( s_Factory ) + return s_Factory; + +#if(_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + HRESULT hr = CoCreateInstance( + CLSID_WICImagingFactory2, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory2), + (LPVOID*)&s_Factory + ); + + if ( SUCCEEDED(hr) ) + { + // WIC2 is available on Windows 8 and Windows 7 SP1 with KB 2670838 installed + g_WIC2 = true; + } + else + { + hr = CoCreateInstance( + CLSID_WICImagingFactory1, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory), + (LPVOID*)&s_Factory + ); + + if ( FAILED(hr) ) + { + s_Factory = nullptr; + return nullptr; + } + } +#else + HRESULT hr = CoCreateInstance( + CLSID_WICImagingFactory, + nullptr, + CLSCTX_INPROC_SERVER, + __uuidof(IWICImagingFactory), + (LPVOID*)&s_Factory + ); + + if ( FAILED(hr) ) + { + s_Factory = nullptr; + return nullptr; + } +#endif + + return s_Factory; +} + + +//--------------------------------------------------------------------------------- +static DXGI_FORMAT _WICToDXGI( const GUID& guid ) +{ + for( size_t i=0; i < _countof(g_WICFormats); ++i ) + { + if ( memcmp( &g_WICFormats[i].wic, &guid, sizeof(GUID) ) == 0 ) + return g_WICFormats[i].format; + } + +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + if ( g_WIC2 ) + { + if ( memcmp( &GUID_WICPixelFormat96bppRGBFloat, &guid, sizeof(GUID) ) == 0 ) + return DXGI_FORMAT_R32G32B32_FLOAT; + } +#endif + + return DXGI_FORMAT_UNKNOWN; +} + +//--------------------------------------------------------------------------------- +static size_t _WICBitsPerPixel( REFGUID targetGuid ) +{ + IWICImagingFactory* pWIC = _GetWIC(); + if ( !pWIC ) + return 0; + + ScopedObject cinfo; + if ( FAILED( pWIC->CreateComponentInfo( targetGuid, &cinfo ) ) ) + return 0; + + WICComponentType type; + if ( FAILED( cinfo->GetComponentType( &type ) ) ) + return 0; + + if ( type != WICPixelFormat ) + return 0; + + Microsoft::WRL::ComPtr pfinfo; + if ( FAILED( cinfo.As( &pfinfo ) ) ) + return 0; + + UINT bpp; + if ( FAILED( pfinfo->GetBitsPerPixel( &bpp ) ) ) + return 0; + + return bpp; +} + + +//-------------------------------------------------------------------------------------- +static DXGI_FORMAT MakeSRGB( _In_ DXGI_FORMAT format ) +{ + switch( format ) + { + case DXGI_FORMAT_R8G8B8A8_UNORM: + return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + + case DXGI_FORMAT_BC1_UNORM: + return DXGI_FORMAT_BC1_UNORM_SRGB; + + case DXGI_FORMAT_BC2_UNORM: + return DXGI_FORMAT_BC2_UNORM_SRGB; + + case DXGI_FORMAT_BC3_UNORM: + return DXGI_FORMAT_BC3_UNORM_SRGB; + + case DXGI_FORMAT_B8G8R8A8_UNORM: + return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; + + case DXGI_FORMAT_B8G8R8X8_UNORM: + return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; + + case DXGI_FORMAT_BC7_UNORM: + return DXGI_FORMAT_BC7_UNORM_SRGB; + + default: + return format; + } +} + +static HRESULT CreateTextureFromWIC( _In_ ID3D11Device* d3dDevice, + _In_opt_ ID3D11DeviceContext* d3dContext, + _In_ IWICBitmapFrameDecode *frame, + _In_ size_t maxsize, + _In_ D3D11_USAGE usage, + _In_ unsigned int bindFlags, + _In_ unsigned int cpuAccessFlags, + _In_ unsigned int miscFlags, + _In_ bool forceSRGB, + _Out_opt_ ID3D11Resource** texture, + _Out_opt_ ID3D11ShaderResourceView** textureView ) +{ + UINT width, height; + HRESULT hr = frame->GetSize( &width, &height ); + if ( FAILED(hr) ) + return hr; + + assert( width > 0 && height > 0 ); + + if ( !maxsize ) + { + // This is a bit conservative because the hardware could support larger textures than + // the Feature Level defined minimums, but doing it this way is much easier and more + // performant for WIC than the 'fail and retry' model used by DDSTextureLoader + + switch( d3dDevice->GetFeatureLevel() ) + { + case D3D_FEATURE_LEVEL_9_1: + case D3D_FEATURE_LEVEL_9_2: + maxsize = 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + case D3D_FEATURE_LEVEL_9_3: + maxsize = 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + case D3D_FEATURE_LEVEL_10_0: + case D3D_FEATURE_LEVEL_10_1: + maxsize = 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/; + break; + + default: + maxsize = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; + break; + } + } + + assert( maxsize > 0 ); + + UINT twidth, theight; + if ( width > maxsize || height > maxsize ) + { + float ar = static_cast(height) / static_cast(width); + if ( width > height ) + { + twidth = static_cast( maxsize ); + theight = static_cast( static_cast(maxsize) * ar ); + } + else + { + theight = static_cast( maxsize ); + twidth = static_cast( static_cast(maxsize) / ar ); + } + assert( twidth <= maxsize && theight <= maxsize ); + } + else + { + twidth = width; + theight = height; + } + + // Determine format + WICPixelFormatGUID pixelFormat; + hr = frame->GetPixelFormat( &pixelFormat ); + if ( FAILED(hr) ) + return hr; + + WICPixelFormatGUID convertGUID; + memcpy( &convertGUID, &pixelFormat, sizeof(WICPixelFormatGUID) ); + + size_t bpp = 0; + + DXGI_FORMAT format = _WICToDXGI( pixelFormat ); + if ( format == DXGI_FORMAT_UNKNOWN ) + { + if ( memcmp( &GUID_WICPixelFormat96bppRGBFixedPoint, &pixelFormat, sizeof(WICPixelFormatGUID) ) == 0 ) + { +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + if ( g_WIC2 ) + { + memcpy( &convertGUID, &GUID_WICPixelFormat96bppRGBFloat, sizeof(WICPixelFormatGUID) ); + format = DXGI_FORMAT_R32G32B32_FLOAT; + } + else +#endif + { + memcpy( &convertGUID, &GUID_WICPixelFormat128bppRGBAFloat, sizeof(WICPixelFormatGUID) ); + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + } + } + else + { + for( size_t i=0; i < _countof(g_WICConvert); ++i ) + { + if ( memcmp( &g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID) ) == 0 ) + { + memcpy( &convertGUID, &g_WICConvert[i].target, sizeof(WICPixelFormatGUID) ); + + format = _WICToDXGI( g_WICConvert[i].target ); + assert( format != DXGI_FORMAT_UNKNOWN ); + bpp = _WICBitsPerPixel( convertGUID ); + break; + } + } + } + + if ( format == DXGI_FORMAT_UNKNOWN ) + return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED ); + } + else + { + bpp = _WICBitsPerPixel( pixelFormat ); + } + +#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) || defined(_WIN7_PLATFORM_UPDATE) + if ( (format == DXGI_FORMAT_R32G32B32_FLOAT) && d3dContext != 0 && textureView != 0 ) + { + // Special case test for optional device support for autogen mipchains for R32G32B32_FLOAT + UINT fmtSupport = 0; + hr = d3dDevice->CheckFormatSupport( DXGI_FORMAT_R32G32B32_FLOAT, &fmtSupport ); + if ( FAILED(hr) || !( fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN ) ) + { + // Use R32G32B32A32_FLOAT instead which is required for Feature Level 10.0 and up + memcpy( &convertGUID, &GUID_WICPixelFormat128bppRGBAFloat, sizeof(WICPixelFormatGUID) ); + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + bpp = 128; + } + } +#endif + + if ( !bpp ) + return E_FAIL; + + // Handle sRGB formats + if ( forceSRGB ) + { + format = MakeSRGB( format ); + } + else + { + ScopedObject metareader; + if ( SUCCEEDED( frame->GetMetadataQueryReader( &metareader ) ) ) + { + GUID containerFormat; + if ( SUCCEEDED( metareader->GetContainerFormat( &containerFormat ) ) ) + { + // Check for sRGB colorspace metadata + bool sRGB = false; + + PROPVARIANT value; + PropVariantInit( &value ); + + if ( memcmp( &containerFormat, &GUID_ContainerFormatPng, sizeof(GUID) ) == 0 ) + { + // Check for sRGB chunk + if ( SUCCEEDED( metareader->GetMetadataByName( L"/sRGB/RenderingIntent", &value ) ) && value.vt == VT_UI1 ) + { + sRGB = true; + } + } + else if ( SUCCEEDED( metareader->GetMetadataByName( L"System.Image.ColorSpace", &value ) ) && value.vt == VT_UI2 && value.uiVal == 1 ) + { + sRGB = true; + } + + PropVariantClear( &value ); + + if ( sRGB ) + format = MakeSRGB( format ); + } + } + } + + // Verify our target format is supported by the current device + // (handles WDDM 1.0 or WDDM 1.1 device driver cases as well as DirectX 11.0 Runtime without 16bpp format support) + UINT support = 0; + hr = d3dDevice->CheckFormatSupport( format, &support ); + if ( FAILED(hr) || !(support & D3D11_FORMAT_SUPPORT_TEXTURE2D) ) + { + // Fallback to RGBA 32-bit format which is supported by all devices + memcpy( &convertGUID, &GUID_WICPixelFormat32bppRGBA, sizeof(WICPixelFormatGUID) ); + format = DXGI_FORMAT_R8G8B8A8_UNORM; + bpp = 32; + } + + // Allocate temporary memory for image + size_t rowPitch = ( twidth * bpp + 7 ) / 8; + size_t imageSize = rowPitch * theight; + + std::unique_ptr temp( new (std::nothrow) uint8_t[ imageSize ] ); + if (!temp) + return E_OUTOFMEMORY; + + // Load image data + if ( memcmp( &convertGUID, &pixelFormat, sizeof(GUID) ) == 0 + && twidth == width + && theight == height ) + { + // No format conversion or resize needed + hr = frame->CopyPixels( 0, static_cast( rowPitch ), static_cast( imageSize ), temp.get() ); + if ( FAILED(hr) ) + return hr; + } + else if ( twidth != width || theight != height ) + { + // Resize + IWICImagingFactory* pWIC = _GetWIC(); + if ( !pWIC ) + return E_NOINTERFACE; + + ScopedObject scaler; + hr = pWIC->CreateBitmapScaler( &scaler ); + if ( FAILED(hr) ) + return hr; + + hr = scaler->Initialize( frame, twidth, theight, WICBitmapInterpolationModeFant ); + if ( FAILED(hr) ) + return hr; + + WICPixelFormatGUID pfScaler; + hr = scaler->GetPixelFormat( &pfScaler ); + if ( FAILED(hr) ) + return hr; + + if ( memcmp( &convertGUID, &pfScaler, sizeof(GUID) ) == 0 ) + { + // No format conversion needed + hr = scaler->CopyPixels( 0, static_cast( rowPitch ), static_cast( imageSize ), temp.get() ); + if ( FAILED(hr) ) + return hr; + } + else + { + ScopedObject FC; + hr = pWIC->CreateFormatConverter( &FC ); + if ( FAILED(hr) ) + return hr; + + hr = FC->Initialize( scaler.Get(), convertGUID, WICBitmapDitherTypeErrorDiffusion, 0, 0, WICBitmapPaletteTypeCustom ); + if ( FAILED(hr) ) + return hr; + + hr = FC->CopyPixels( 0, static_cast( rowPitch ), static_cast( imageSize ), temp.get() ); + if ( FAILED(hr) ) + return hr; + } + } + else + { + // Format conversion but no resize + IWICImagingFactory* pWIC = _GetWIC(); + if ( !pWIC ) + return E_NOINTERFACE; + + ScopedObject FC; + hr = pWIC->CreateFormatConverter( &FC ); + if ( FAILED(hr) ) + return hr; + + hr = FC->Initialize( frame, convertGUID, WICBitmapDitherTypeErrorDiffusion, 0, 0, WICBitmapPaletteTypeCustom ); + if ( FAILED(hr) ) + return hr; + + hr = FC->CopyPixels( 0, static_cast( rowPitch ), static_cast( imageSize ), temp.get() ); + if ( FAILED(hr) ) + return hr; + } + + // See if format is supported for auto-gen mipmaps (varies by feature level) + bool autogen = false; + if ( d3dContext != 0 && textureView != 0 ) // Must have context and shader-view to auto generate mipmaps + { + UINT fmtSupport = 0; + hr = d3dDevice->CheckFormatSupport( format, &fmtSupport ); + if ( SUCCEEDED(hr) && ( fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN ) ) + { + autogen = true; + } + } + + // Create texture + D3D11_TEXTURE2D_DESC desc; + desc.Width = twidth; + desc.Height = theight; + desc.MipLevels = (autogen) ? 0 : 1; + desc.ArraySize = 1; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Usage = usage; + desc.CPUAccessFlags = cpuAccessFlags; + + if ( autogen ) + { + desc.BindFlags = bindFlags | D3D11_BIND_RENDER_TARGET; + desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS; + } + else + { + desc.BindFlags = bindFlags; + desc.MiscFlags = miscFlags; + } + + D3D11_SUBRESOURCE_DATA initData; + initData.pSysMem = temp.get(); + initData.SysMemPitch = static_cast( rowPitch ); + initData.SysMemSlicePitch = static_cast( imageSize ); + + ID3D11Texture2D* tex = nullptr; + //Error with miscFlags Generate Mips + hr = d3dDevice->CreateTexture2D( &desc, (autogen) ? nullptr : &initData, &tex ); + /// Replace To get Texture Data + if ( SUCCEEDED(hr) && tex != 0 ) + { + if (textureView != 0) + { + D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc; + memset( &SRVDesc, 0, sizeof( SRVDesc ) ); + SRVDesc.Format = desc.Format; + + SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + SRVDesc.Texture2D.MipLevels = (autogen) ? -1 : 1; + + hr = d3dDevice->CreateShaderResourceView( tex, &SRVDesc, textureView ); + if ( FAILED(hr) ) + { + tex->Release(); + return hr; + } + + if ( autogen ) + { + assert( d3dContext != 0 ); + d3dContext->UpdateSubresource( tex, 0, nullptr, temp.get(), static_cast(rowPitch), static_cast(imageSize) ); + d3dContext->GenerateMips( *textureView ); + } + } + + if (texture != 0) + { + *texture = tex; + } + else + { + //SetDebugObjectName(tex, "WICTextureLoader"); + tex->Release(); + } + } + + return hr; +} + +HRESULT CreateWICTextureFromFileEx( ID3D11Device* d3dDevice, + ID3D11DeviceContext* d3dContext, + const wchar_t* fileName, + size_t maxsize, + D3D11_USAGE usage, + unsigned int bindFlags, + unsigned int cpuAccessFlags, + unsigned int miscFlags, + bool forceSRGB, + ID3D11Resource** texture, + ID3D11ShaderResourceView** textureView ) +{ + if ( texture ) + { + *texture = nullptr; + } + if ( textureView ) + { + *textureView = nullptr; + } + + if (!d3dDevice || !fileName || (!texture && !textureView)) + return E_INVALIDARG; + + IWICImagingFactory* pWIC = _GetWIC(); + if ( !pWIC ) + return E_NOINTERFACE; + + // Initialize WIC + ScopedObject decoder; + HRESULT hr = pWIC->CreateDecoderFromFilename( fileName, 0, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &decoder ); + if ( FAILED(hr) ) + return hr; + + ScopedObject frame; + hr = decoder->GetFrame( 0, &frame ); + if ( FAILED(hr) ) + return hr; + + hr = CreateTextureFromWIC( d3dDevice, d3dContext, frame.Get(), maxsize, + usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, + texture, textureView ); + + return hr; } \ No newline at end of file diff --git a/Code/OysterGraphics/FileLoader/TextureLoader.h b/Code/OysterGraphics/FileLoader/TextureLoader.h deleted file mode 100644 index a5148fb4..00000000 --- a/Code/OysterGraphics/FileLoader/TextureLoader.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once -#include "..\..\Misc\Resource\OysterResource.h" -namespace Oyster -{ - namespace Graphics - { - namespace Loading - { - void UnloadTexture(); - Oyster::Resource::CustomData* LoadTexture(); - } - } -} \ No newline at end of file diff --git a/Code/OysterGraphics/OysterGraphics.vcxproj b/Code/OysterGraphics/OysterGraphics.vcxproj index 09f743b7..0df3d45b 100644 --- a/Code/OysterGraphics/OysterGraphics.vcxproj +++ b/Code/OysterGraphics/OysterGraphics.vcxproj @@ -30,20 +30,20 @@ MultiByte - StaticLibrary + DynamicLibrary true v110 MultiByte - StaticLibrary + DynamicLibrary false v110 true MultiByte - StaticLibrary + DynamicLibrary false v110 true @@ -69,21 +69,29 @@ $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files (x86)\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files (x86)\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files (x86)\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) $(SolutionDir)..\Bin\DLL\ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files (x86)\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) @@ -99,6 +107,9 @@ true + + $(SolutionDir)..\Bin\Content\Shaders\%(Filename).cso + @@ -111,6 +122,9 @@ true + + $(SolutionDir)..\Bin\Content\Shaders\%(Filename).cso + @@ -127,6 +141,9 @@ true true + + $(SolutionDir)..\Bin\Content\Shaders\%(Filename).cso + @@ -143,6 +160,9 @@ true true + + $(SolutionDir)..\Bin\Content\Shaders\%(Filename).cso + @@ -151,6 +171,7 @@ + @@ -161,7 +182,7 @@ - + @@ -192,6 +213,16 @@ Vertex 5.0 + + Compute + 4.0 + Compute + 4.0 + Compute + 4.0 + Compute + 4.0 + Vertex Vertex @@ -223,11 +254,17 @@ + + Pixel + Pixel + Pixel + Pixel + - - + + diff --git a/Code/OysterGraphics/OysterGraphics.vcxproj.filters b/Code/OysterGraphics/OysterGraphics.vcxproj.filters index 3bb4036f..f2cc3af0 100644 --- a/Code/OysterGraphics/OysterGraphics.vcxproj.filters +++ b/Code/OysterGraphics/OysterGraphics.vcxproj.filters @@ -1,40 +1,101 @@  + + {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 + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + 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/OysterGraphics/Render/Rendering/BasicRender.cpp b/Code/OysterGraphics/Render/Rendering/BasicRender.cpp index 5e1fbb48..50e7f9f1 100644 --- a/Code/OysterGraphics/Render/Rendering/BasicRender.cpp +++ b/Code/OysterGraphics/Render/Rendering/BasicRender.cpp @@ -14,9 +14,9 @@ namespace Oyster void Basic::NewFrame(Oyster::Math::Float4x4 View, Oyster::Math::Float4x4 Projection) { - Preparations::Basic::ClearBackBuffer(Oyster::Math::Float4(0,0,0,1)); + Preparations::Basic::ClearBackBuffer(Oyster::Math::Float4(1,0,0,1)); Core::ShaderManager::SetShaderEffect(Graphics::Render::Resources::obj); - Preparations::Basic::BindBackBufferRTV(nullptr); + Preparations::Basic::BindBackBufferRTV(); Definitions::VP vp; vp.V = View; @@ -39,10 +39,11 @@ namespace Oyster memcpy(data,&(models[i].WorldMatrix),sizeof(Math::Float4x4)); Resources::ModelData.Unmap(); - //Set Materials :: NONE + + Model::ModelInfo* info = (Model::ModelInfo*)models[i].info; + + Core::deviceContext->PSSetShaderResources(0,info->Material.size(),&(info->Material[0])); - Model - ::ModelInfo* info = (Model::ModelInfo*)models[i].info; info->Vertices->Apply(); if(info->Indexed) diff --git a/Code/OysterGraphics/Render/Resources/Resources.cpp b/Code/OysterGraphics/Render/Resources/Resources.cpp index 3ff3fa3c..2bda54e1 100644 --- a/Code/OysterGraphics/Render/Resources/Resources.cpp +++ b/Code/OysterGraphics/Render/Resources/Resources.cpp @@ -7,6 +7,7 @@ const std::wstring PathFromExeToHlsl = L"..\\..\\..\\Code\\OysterGraphics\\Shade const std::wstring VertexTransformDebug = L"TransformDebugVertex"; const std::wstring VertexDebug = L"DebugVertex"; const std::wstring PixelRed = L"DebugPixel"; +const std::wstring PixelTexture = L"Texture"; typedef Oyster::Graphics::Core::ShaderManager::ShaderType ShaderType; typedef Oyster::Graphics::Core::ShaderManager::Get GetShader; @@ -19,7 +20,7 @@ namespace Oyster { namespace Render { - Shader::ShaderEffect Resources::obj; + Shader::ShaderEffect Resources::obj;// = Shader::ShaderEffect();; Buffer Resources::ModelData = Buffer(); Buffer Resources::VPData = Buffer(); @@ -31,11 +32,13 @@ namespace Oyster #ifdef _DEBUG /** Load Vertex Shader for d3dcompile*/ - Core::ShaderManager::Init(PathFromExeToHlsl + L"SimpleDebug\\" +L"DebugCameraVertex.hlsl",ShaderType::Vertex, VertexTransformDebug, false); - Core::ShaderManager::Init(PathFromExeToHlsl + L"SimpleDebug\\" +L"DebugVertex.hlsl",ShaderType::Vertex, VertexDebug, false); + Core::ShaderManager::Init(PathFromExeToHlsl + L"SimpleDebug\\" +L"DebugCameraVertex.hlsl",ShaderType::Vertex, VertexTransformDebug); + Core::ShaderManager::Init(PathFromExeToHlsl + L"SimpleDebug\\" +L"DebugVertex.hlsl",ShaderType::Vertex, VertexDebug); /** Load Pixel Shader for d3dcompile */ - Core::ShaderManager::Init(PathFromExeToHlsl + L"SimpleDebug\\" + L"DebugPixel.hlsl", ShaderType::Pixel, PixelRed, false); + Core::ShaderManager::Init(PathFromExeToHlsl + L"SimpleDebug\\" + L"DebugPixel.hlsl", ShaderType::Pixel, PixelRed); + Core::ShaderManager::Init(PathFromExeToHlsl + L"SimpleDebug\\" + L"TextureDebug.hlsl", ShaderType::Pixel, PixelTexture); + #else /** Load Vertex Shader with Precompiled */ @@ -62,9 +65,9 @@ namespace Oyster /** @todo Create DX States */ D3D11_RASTERIZER_DESC rdesc; - rdesc.CullMode = D3D11_CULL_NONE; + rdesc.CullMode = D3D11_CULL_BACK; rdesc.FillMode = D3D11_FILL_SOLID; - rdesc.FrontCounterClockwise = false; + rdesc.FrontCounterClockwise = true; rdesc.DepthBias = 0; rdesc.DepthBiasClamp = 0; rdesc.DepthClipEnable = true; @@ -75,6 +78,45 @@ namespace Oyster ID3D11RasterizerState* rs = NULL; Oyster::Graphics::Core::device->CreateRasterizerState(&rdesc,&rs); + + D3D11_SAMPLER_DESC sdesc; + sdesc.Filter = D3D11_FILTER_ANISOTROPIC; + /// @todo parata med fredrik om wraping + sdesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; + sdesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; + sdesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; + sdesc.MipLODBias = 0; + sdesc.MaxAnisotropy =4; + sdesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL; + *sdesc.BorderColor = *Oyster::Math::Float4(1,1,1,1).element; + sdesc.MinLOD = 0; + sdesc.MaxLOD = D3D11_FLOAT32_MAX; + + ID3D11SamplerState** ss = new ID3D11SamplerState*[1]; + Oyster::Graphics::Core::device->CreateSamplerState(&sdesc,ss); + + D3D11_DEPTH_STENCIL_DESC ddesc; + ddesc.DepthEnable = true; + ddesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; + ddesc.DepthFunc = D3D11_COMPARISON_LESS; + + ddesc.StencilEnable = true; + ddesc.StencilReadMask = 0xFF; + ddesc.StencilWriteMask = 0xFF; + + ddesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; + ddesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; + ddesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; + ddesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; + + ddesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; + ddesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; + ddesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; + ddesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; + + ID3D11DepthStencilState* dsState; + Core::device->CreateDepthStencilState(&ddesc,&dsState); + #pragma endregion #pragma region Setup Views @@ -83,7 +125,7 @@ namespace Oyster #pragma region Create Shader Effects /** @todo Create ShaderEffects */ - obj.Shaders.Pixel = GetShader::Pixel(PixelRed); + obj.Shaders.Pixel = GetShader::Pixel(PixelTexture); obj.Shaders.Vertex = GetShader::Vertex(VertexTransformDebug); D3D11_INPUT_ELEMENT_DESC indesc[] = @@ -98,11 +140,47 @@ namespace Oyster obj.IAStage.Topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; obj.CBuffers.Vertex.push_back(&VPData); obj.RenderStates.Rasterizer = rs; + obj.RenderStates.SampleCount = 1; + obj.RenderStates.SampleState = ss; + obj.RenderStates.DepthStencil = dsState; ModelData.Apply(1); #pragma endregion return Core::Init::Sucsess; } + + void Resources::Clean() + { + Resources::ModelData.~Buffer(); + Resources::VPData.~Buffer(); + for(int i = 0; i < obj.CBuffers.Vertex.size(); ++i) + { + //SAFE_RELEASE(obj.CBuffers.Vertex[i]); + } + for(int i = 0; i < obj.CBuffers.Pixel.size(); ++i) + { + SAFE_DELETE(obj.CBuffers.Pixel[i]); + } + for(int i = 0; i < obj.CBuffers.Geometry.size(); ++i) + { + SAFE_DELETE(obj.CBuffers.Geometry[i]); + } + + SAFE_RELEASE(obj.IAStage.Layout); + + SAFE_RELEASE(obj.RenderStates.BlendState); + + SAFE_RELEASE(obj.RenderStates.DepthStencil); + + SAFE_RELEASE(obj.RenderStates.Rasterizer); + + for(int i = 0; i < obj.RenderStates.SampleCount; ++i) + { + SAFE_RELEASE(obj.RenderStates.SampleState[i]); + } + + SAFE_DELETE_ARRAY(obj.RenderStates.SampleState); + } } } } \ No newline at end of file diff --git a/Code/OysterGraphics/Render/Resources/Resources.h b/Code/OysterGraphics/Render/Resources/Resources.h index daf77760..1e1c4c9c 100644 --- a/Code/OysterGraphics/Render/Resources/Resources.h +++ b/Code/OysterGraphics/Render/Resources/Resources.h @@ -20,6 +20,7 @@ namespace Oyster static Core::Buffer VPData; static Core::Init::State Init(); + static void Clean(); }; } } diff --git a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/Render/Defines.hlsli b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/Render/Defines.hlsli new file mode 100644 index 00000000..e5a2333f --- /dev/null +++ b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/Render/Defines.hlsli @@ -0,0 +1,7 @@ +struct PointLight +{ + float3 Pos; + float Radius; + + float3 Color; +} \ No newline at end of file diff --git a/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/Render/LightPass.hlsl b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/Render/LightPass.hlsl new file mode 100644 index 00000000..8fdac3c8 --- /dev/null +++ b/Code/OysterGraphics/Shader/HLSL/Deffered Shaders/Render/LightPass.hlsl @@ -0,0 +1,11 @@ + +//todo +//LightCulling +//Calc Diff + Spec +//Calc Ambience +//Write Glow + +[numthreads(1, 1, 1)] +void main( uint3 DTid : SV_DispatchThreadID ) +{ +} \ No newline at end of file diff --git a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/Debug.hlsl b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/Debug.hlsl new file mode 100644 index 00000000..d1ff1089 --- /dev/null +++ b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/Debug.hlsl @@ -0,0 +1,25 @@ +cbuffer PerFrame : register(b0) +{ + matrix View; + float4x4 Projection; +} + +cbuffer PerModel : register(b1) +{ + matrix World; +} + +struct VertexOut +{ + float4 Pos : SV_POSITION; + float2 UV : TEXCOORD; + float3 Normal : NORMAL; + float4 Wpos : POSITION; +}; + +struct VertexIn +{ + float3 pos : POSITION; + float2 UV : TEXCOORD; + float3 normal : NORMAL; +}; diff --git a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl index 76e7dbed..0d87411e 100644 --- a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl +++ b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugCameraVertex.hlsl @@ -1,28 +1,13 @@ -cbuffer PerFrame : register(b0) -{ - matrix View; - float4x4 Projection; -} +#include "Debug.hlsl" -cbuffer PerModel : register(b1) +VertexOut main( VertexIn input ) { - matrix World; -} - -struct VertexIn -{ - float3 pos : POSITION; - float2 UV : TEXCOORD; - float3 normal : NORMAL; -}; - -float4 main( VertexIn input ) : SV_POSITION -{ - float4 postTransform = mul( World, float4(input.pos,1) ); - //float4 postTransform = float4(input.pos,1); - //return postTransform; - //return mul(View, float4(input.pos,1)); + VertexOut outp; + outp.Wpos = mul( World, float4(input.pos,1) ); matrix VP = mul(Projection, View); - //matrix WVP = mul(World, VP); - return mul(VP, postTransform ); + outp.Pos = mul(VP, outp.Wpos ); + outp.UV = input.UV; + outp.Normal = input.normal; + + return outp; } \ No newline at end of file diff --git a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugPixel.hlsl b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugPixel.hlsl index 627d8592..ebca8dde 100644 --- a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugPixel.hlsl +++ b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/DebugPixel.hlsl @@ -1,4 +1,6 @@ -float4 main() : SV_TARGET0 +//#include "Debug.hlsli" + +float4 main() : SV_TARGET { return float4(1.0f, 0.0f, 0.0f, 1.0f); } \ No newline at end of file diff --git a/Code/OysterGraphics/Shader/HLSL/SimpleDebug/TextureDebug.hlsl b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/TextureDebug.hlsl new file mode 100644 index 00000000..d52debf3 --- /dev/null +++ b/Code/OysterGraphics/Shader/HLSL/SimpleDebug/TextureDebug.hlsl @@ -0,0 +1,9 @@ +#include "Debug.hlsl" + +Texture2D tex : register(t0); +SamplerState S1 : register(s0); + +float4 main(VertexOut inp) : SV_TARGET0 +{ + return tex.Sample(S1,inp.UV); +} \ No newline at end of file diff --git a/Code/Tester/MainTest.cpp b/Code/Tester/MainTest.cpp index 607ba3b4..cbf563c6 100644 --- a/Code/Tester/MainTest.cpp +++ b/Code/Tester/MainTest.cpp @@ -6,6 +6,7 @@ // Copyright (c) Stefan Petersson 2011. All rights reserved. //-------------------------------------------------------------------------------------- #define NOMINMAX +#include #include #include "DllInterfaces\GFXAPI.h" @@ -16,7 +17,7 @@ //-------------------------------------------------------------------------------------- HINSTANCE g_hInst = NULL; HWND g_hWnd = NULL; -Oyster::Graphics::Model::Model* m = new Oyster::Graphics::Model::Model(); +Oyster::Graphics::Model::Model* m = NULL; Oyster::Math::Float4x4 V; Oyster::Math::Float4x4 P; @@ -53,7 +54,6 @@ int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdL params.lpCmdLine=""; params.lpCmdShow=""; params.lpEnvAddress=""; - LoadModule("OysterGraphics_x86D.dll",¶ms); if( FAILED( InitWindow( hInstance, nCmdShow ) ) ) return 0; @@ -91,6 +91,8 @@ int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdL } } + Oyster::Graphics::API::DeleteModel(m); + Oyster::Graphics::API::Clean(); return (int) msg.wParam; } @@ -184,23 +186,23 @@ HRESULT InitDirect3D() #pragma endregion #pragma region Obj - m = Oyster::Graphics::API::CreateModel(L"bth.obj"); - m->WorldMatrix *= 0.1f; - m->WorldMatrix.m44 = 1; + m = Oyster::Graphics::API::CreateModel(L"orca"); #pragma endregion - P = Oyster::Math3D::ProjectionMatrix_Perspective(Oyster::Math::pi/2,1024.0f/768.0f,.1f,100); + P = Oyster::Math3D::ProjectionMatrix_Perspective(Oyster::Math::pi/2,1024.0f/768.0f,.1f,1000); - V = Oyster::Math3D::OrientationMatrix_LookAtDirection(Oyster::Math::Float3(0,0,-1),Oyster::Math::Float3(0,1,0),Oyster::Math::Float3(0,-1.5f,10.4f)); + V = Oyster::Math3D::OrientationMatrix_LookAtDirection(Oyster::Math::Float3(0,0,-1),Oyster::Math::Float3(0,1,0),Oyster::Math::Float3(0,0,5.4f)); V = Oyster::Math3D::InverseOrientationMatrix(V); return S_OK; } - +float angle = 0; HRESULT Update(float deltaTime) { + angle += Oyster::Math::pi/30000; + m->WorldMatrix = Oyster::Math3D::RotationMatrix_AxisY(angle); return S_OK; } diff --git a/Code/Tester/Tester.vcxproj b/Code/Tester/Tester.vcxproj index 528c805c..3f48d244 100644 --- a/Code/Tester/Tester.vcxproj +++ b/Code/Tester/Tester.vcxproj @@ -71,24 +71,32 @@ $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(SolutionDir)..\Bin\Executable\$(ProjectName)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files (x86)\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) true $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(SolutionDir)..\Bin\Executable\$(ProjectName)\ $(ProjectName)_$(PlatformShortName)D + C:\Program Files (x86)\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) false $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(SolutionDir)..\Bin\Executable\$(ProjectName)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files (x86)\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win32;$(LibraryPath) false $(SolutionDir)..\Obj\$(ProjectName)\$(PlatformShortName)\$(Configuration)\ $(SolutionDir)..\Bin\Executable\$(ProjectName)\ $(ProjectName)_$(PlatformShortName) + C:\Program Files (x86)\Visual Leak Detector\include;$(IncludePath) + C:\Program Files (x86)\Visual Leak Detector\lib\Win64;$(LibraryPath) @@ -105,7 +113,7 @@ true OysterGraphics_$(PlatformShortName)D.lib;%(AdditionalDependencies) $(SolutionDir)..\Bin\DLL;%(AdditionalLibraryDirectories) - OysterGraphics_x86D.dll;%(DelayLoadDLLs) + OysterGraphics_$(PlatformShortName)D.dll;%(DelayLoadDLLs) @@ -128,6 +136,7 @@ OysterGraphics_$(PlatformShortName)D.lib;%(AdditionalDependencies) $(SolutionDir)..\Bin\DLL;%(AdditionalLibraryDirectories) true + OysterGraphics_$(PlatformShortName)D.dll;%(DelayLoadDLLs) @@ -150,6 +159,7 @@ OysterGraphics_$(PlatformShortName).lib;%(AdditionalDependencies) $(SolutionDir)..\Bin\DLL;%(AdditionalLibraryDirectories) true + OysterGraphics_$(PlatformShortName)D.dll;%(DelayLoadDLLs) @@ -172,6 +182,7 @@ OysterGraphics_$(PlatformShortName).lib;%(AdditionalDependencies) $(SolutionDir)..\Bin\DLL;%(AdditionalLibraryDirectories) true + OysterGraphics_$(PlatformShortName)D.dll;%(DelayLoadDLLs)