Compare commits

..

2 Commits

76 changed files with 533 additions and 1289 deletions
+1 -1
Submodule assets updated: 10a611659d...1e7adc749e
@@ -24,7 +24,6 @@ public:
private: private:
Octree<EntityAABB>* m_Octree; Octree<EntityAABB>* m_Octree;
std::vector<EntityAABB> m_OctreeResult; std::vector<EntityAABB> m_OctreeResult;
std::unordered_map<EntityWrapper, glm::vec3> m_PrevPositions;
}; };
#endif #endif
-2
View File
@@ -29,7 +29,6 @@ struct EntityWrapper
EntityWrapper Parent(); EntityWrapper Parent();
EntityWrapper FirstChildByName(const std::string& name); EntityWrapper FirstChildByName(const std::string& name);
EntityWrapper FirstParentWithComponent(const std::string& componentType); EntityWrapper FirstParentWithComponent(const std::string& componentType);
EntityWrapper Clone(EntityWrapper parent = EntityWrapper::Invalid);
bool IsChildOf(EntityWrapper potentialParent); bool IsChildOf(EntityWrapper potentialParent);
bool Valid() const; bool Valid() const;
@@ -40,7 +39,6 @@ struct EntityWrapper
private: private:
EntityWrapper firstChildByNameRecursive(const std::string& name, EntityID parent); EntityWrapper firstChildByNameRecursive(const std::string& name, EntityID parent);
EntityWrapper cloneRecursive(EntityWrapper entity, EntityWrapper parent);
}; };
namespace std namespace std
+1 -1
View File
@@ -40,7 +40,7 @@ public:
// Change the parent of an entity // Change the parent of an entity
void SetParent(EntityID entity, EntityID parent); void SetParent(EntityID entity, EntityID parent);
// Get children of an entity // Get children of an entity
const std::pair<std::unordered_multimap<EntityID, EntityID>::const_iterator, std::unordered_multimap<EntityID, EntityID>::const_iterator> GetDirectChildren(EntityID entity); const std::pair<std::unordered_multimap<EntityID, EntityID>::const_iterator, std::unordered_multimap<EntityID, EntityID>::const_iterator> GetChildren(EntityID entity);
// Get all component pools // Get all component pools
const std::unordered_map<std::string, ComponentPool*>& GetComponentPools() const { return m_ComponentPools; } const std::unordered_map<std::string, ComponentPool*>& GetComponentPools() const { return m_ComponentPools; }
// Get the entity children map // Get the entity children map
-8
View File
@@ -73,12 +73,6 @@ public:
// Called when the user means to rename an entity. // Called when the user means to rename an entity.
typedef std::function<void(EntityWrapper, const std::string&)> OnEntityChangeName_t; typedef std::function<void(EntityWrapper, const std::string&)> OnEntityChangeName_t;
void SetEntityChangeNameCallback(OnEntityChangeName_t f) { m_OnEntityChangeName = f; } void SetEntityChangeNameCallback(OnEntityChangeName_t f) { m_OnEntityChangeName = f; }
// Called when the user pastes an entity previously "copied"
// @param EntityWrapper The entity to copy
// @param EntityWrapper The entity to parent the new copy to
// @return The new copy of the entity
typedef std::function<EntityWrapper(EntityWrapper, EntityWrapper)> OnEntityPaste_t;
void SetEntityPasteCallback(OnEntityPaste_t f) { m_OnEntityPaste = f; }
// Called when the user means to attach a new component to an entity. // Called when the user means to attach a new component to an entity.
typedef std::function<void(EntityWrapper, const std::string&)> OnComponentAttach_t; typedef std::function<void(EntityWrapper, const std::string&)> OnComponentAttach_t;
void SetComponentAttachCallback(OnComponentAttach_t f) { m_OnComponentAttach = f; } void SetComponentAttachCallback(OnComponentAttach_t f) { m_OnComponentAttach = f; }
@@ -117,7 +111,6 @@ private:
std::string m_DroppedFile = ""; std::string m_DroppedFile = "";
bool m_Paused = false; bool m_Paused = false;
bool m_MouseLocked = false; bool m_MouseLocked = false;
EntityWrapper m_CopyTarget = EntityWrapper::Invalid;
// Callbacks // Callbacks
OnEntitySelectedCallback_t m_OnEntitySelected = nullptr; OnEntitySelectedCallback_t m_OnEntitySelected = nullptr;
@@ -131,7 +124,6 @@ private:
OnComponentDelete_t m_OnComponentDelete = nullptr; OnComponentDelete_t m_OnComponentDelete = nullptr;
OnWidgetMode_t m_OnWidgetMode = nullptr; OnWidgetMode_t m_OnWidgetMode = nullptr;
OnWidgetSpace_t m_OnWidgetSpace = nullptr; OnWidgetSpace_t m_OnWidgetSpace = nullptr;
OnEntityPaste_t m_OnEntityPaste = nullptr;
// Events // Events
EventRelay<EditorGUI, Events::KeyDown> m_EKeyDown; EventRelay<EditorGUI, Events::KeyDown> m_EKeyDown;
-1
View File
@@ -56,7 +56,6 @@ private:
void OnEntityDelete(EntityWrapper entity); void OnEntityDelete(EntityWrapper entity);
void OnEntityChangeParent(EntityWrapper entity, EntityWrapper parent); void OnEntityChangeParent(EntityWrapper entity, EntityWrapper parent);
void OnEntityChangeName(EntityWrapper entity, const std::string& name); void OnEntityChangeName(EntityWrapper entity, const std::string& name);
EntityWrapper OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent);
void OnComponentAttach(EntityWrapper entity, const std::string& componentType); void OnComponentAttach(EntityWrapper entity, const std::string& componentType);
void OnComponentDelete(EntityWrapper entity, const std::string& componentType); void OnComponentDelete(EntityWrapper entity, const std::string& componentType);
void OnWidgetSpace(EditorGUI::WidgetSpace widgetSpace); void OnWidgetSpace(EditorGUI::WidgetSpace widgetSpace);
+5 -31
View File
@@ -19,26 +19,11 @@
#include "Core/World.h" #include "Core/World.h"
#include "Core/EventBroker.h" #include "Core/EventBroker.h"
#include "Core/ConfigFile.h" #include "Core/ConfigFile.h"
#include "Core/EPlayerDeath.h"
#include "Input/EInputCommand.h" #include "Input/EInputCommand.h"
#include "Core/EPlayerDamage.h" #include "Core/EPlayerDamage.h"
#include "../Game/Events/EDoubleJump.h"
#include "Network/EInterpolate.h" #include "Network/EInterpolate.h"
#include "Network/SnapshotFilter.h" #include "Network/SnapshotFilter.h"
#include "Core/EPlayerSpawned.h" #include "Core/EPlayerSpawned.h"
#include "Network/ESearchForServers.h"
struct ServerInfo
{
ServerInfo(std::string a, int b, std::string c, int d)
{
Address = a; Port = b; Name = c; PlayersConnected = d;
}
std::string Address = "";
int Port = 0;
std::string Name = "";
int PlayersConnected = 0;
};
class Client : public Network class Client : public Network
{ {
@@ -49,9 +34,7 @@ public:
void Connect(std::string address, int port); void Connect(std::string address, int port);
void Update() override; void Update() override;
private:
UDPClient m_Unreliable;
TCPClient m_Reliable;
std::vector<Events::PlayerSpawned> m_PlayerSpawnEvents; std::vector<Events::PlayerSpawned> m_PlayerSpawnEvents;
void parseSpawnEvents(); void parseSpawnEvents();
// Save for children // Save for children
@@ -99,13 +82,10 @@ private:
void parseTCPConnect(Packet& packet); void parseTCPConnect(Packet& packet);
void parsePlayerConnected(Packet& packet); void parsePlayerConnected(Packet& packet);
void parsePing(); void parsePing();
void parseServerlist(Packet& packet);
void parseKick(); void parseKick();
void parsePlayersSpawned(Packet& packet); void parsePlayersSpawned(Packet& packet);
void parseEntityDeletion(Packet& packet); void parseEntityDeletion(Packet& packet);
void parsePlayerDamage(Packet& packet);
void parseComponentDeletion(Packet& packet); void parseComponentDeletion(Packet& packet);
void parseDoubleJump(Packet& packet);
void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType);
void parseSnapshot(Packet& packet); void parseSnapshot(Packet& packet);
void identifyPacketLoss(); void identifyPacketLoss();
@@ -114,7 +94,6 @@ private:
void sendInputCommands(); void sendInputCommands();
void sendLocalPlayerTransform(); void sendLocalPlayerTransform();
void becomePlayer(); void becomePlayer();
void displayServerlist();
// Mapping Logic // Mapping Logic
// Returns if local EntityID exist in map // Returns if local EntityID exist in map
bool clientServerMapsHasEntity(EntityID clientEntityID); bool clientServerMapsHasEntity(EntityID clientEntityID);
@@ -130,15 +109,10 @@ private:
bool OnPlayerDamage(const Events::PlayerDamage& e); bool OnPlayerDamage(const Events::PlayerDamage& e);
EventRelay<Client, Events::PlayerSpawned> m_EPlayerSpawned; EventRelay<Client, Events::PlayerSpawned> m_EPlayerSpawned;
bool OnPlayerSpawned(const Events::PlayerSpawned& e); bool OnPlayerSpawned(const Events::PlayerSpawned& e);
EventRelay< Client, Events::SearchForServers> m_ESearchForServers; void parsePlayerDamage(Packet& packet);
EventRelay<Client, Events::DoubleJump> m_EDoubleJump; private:
bool OnDoubleJump(Events::DoubleJump & e); UDPClient m_Unreliable;
bool OnSearchForServers(const Events::SearchForServers& e); TCPClient m_Reliable;
UDPClient m_ServerlistRequest;
std::vector<ServerInfo> m_Serverlist;
bool m_SearchingForServers = false;
std::clock_t m_StartSearchTime;
double m_SearchingTime = 2000; // Config I guess
}; };
#endif #endif
@@ -1,12 +0,0 @@
#ifndef Events_SearchForServers_h__
#define Events_SearchForServers_h__
#include "Core/Event.h"
namespace Events
{
struct SearchForServers : public Event { };
}
#endif
+13
View File
@@ -0,0 +1,13 @@
#ifndef HybridClient_h__
#define HybridClient_h__
class HybridClient
{
public:
HybridClient();
~HybridClient();
private:
};
#endif
+12
View File
@@ -0,0 +1,12 @@
#ifndef HybridServer_h__
#define HybridServer_h__
class HybridServer
{
public:
HybridServer();
~HybridServer();
private:
};
#endif
-2
View File
@@ -19,8 +19,6 @@ enum class MessageType
EntityDeleted, EntityDeleted,
ComponentDeleted, ComponentDeleted,
PlayerTransform, PlayerTransform,
OnDoubleJump,
ServerlistRequest,
Invalid Invalid
}; };
+1 -4
View File
@@ -9,16 +9,13 @@ typedef unsigned int PacketID;
class NetworkClient class NetworkClient
{ {
public: public:
NetworkClient();
virtual ~NetworkClient();
virtual void Connect(std::string playerName, std::string address, int port) = 0; virtual void Connect(std::string playerName, std::string address, int port) = 0;
virtual void Disconnect() = 0; virtual void Disconnect() = 0;
virtual void Receive(Packet& packet) = 0; virtual void Receive(Packet& packet) = 0;
virtual void Send(Packet & packet) = 0; virtual void Send(Packet & packet) = 0;
virtual bool IsSocketAvailable() = 0; virtual bool IsSocketAvailable() = 0;
protected: protected:
char* m_ReadBuffer; char m_ReadBuffer[BUFFERSIZE] = { 0 };
unsigned int m_BufferSize = BUFFERSIZE;
}; };
#endif #endif
+1 -4
View File
@@ -10,15 +10,12 @@ typedef unsigned int PacketID;
class NetworkServer class NetworkServer
{ {
public: public:
NetworkServer();
virtual ~NetworkServer();
virtual void AcceptNewConnections(int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers) = 0; virtual void AcceptNewConnections(int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers) = 0;
virtual void Receive(Packet & packet, PlayerDefinition & playerDefinition) = 0; virtual void Receive(Packet & packet, PlayerDefinition & playerDefinition) = 0;
virtual void Send(Packet & packet, PlayerDefinition & playerDefinition) = 0; virtual void Send(Packet & packet, PlayerDefinition & playerDefinition) = 0;
virtual void Send(Packet & packet) = 0; virtual void Send(Packet & packet) = 0;
protected: protected:
char* m_ReadBuffer; char m_ReadBuffer[BUFFERSIZE] = { 0 };
unsigned int m_BufferSize = BUFFERSIZE;
}; };
#endif #endif
+4 -9
View File
@@ -17,7 +17,6 @@
#include "Core/EPlayerDamage.h" #include "Core/EPlayerDamage.h"
#include "Network/EPlayerDisconnected.h" #include "Network/EPlayerDisconnected.h"
#include "Core/EPlayerSpawned.h" #include "Core/EPlayerSpawned.h"
#include "../Game/Events/EDoubleJump.h"
#include "Core/EEntityDeleted.h" #include "Core/EEntityDeleted.h"
#include "Core/EComponentDeleted.h" #include "Core/EComponentDeleted.h"
@@ -33,7 +32,6 @@ private:
// Network channels // Network channels
TCPServer m_Reliable; TCPServer m_Reliable;
UDPServer m_Unreliable; UDPServer m_Unreliable;
UDPServer m_ServerlistRequest;
// dont forget to set these in the childrens receive logic // dont forget to set these in the childrens receive logic
boost::asio::ip::address m_Address; boost::asio::ip::address m_Address;
int m_Port = 27666; int m_Port = 27666;
@@ -56,7 +54,7 @@ private:
std::vector<Events::InputCommand> m_InputCommandsToBroadcast; std::vector<Events::InputCommand> m_InputCommandsToBroadcast;
//Timers //Timers
std::clock_t m_StartPingTime; std::clock_t m_StartPingTime;
// Packet loss logic // Packet loss logic
PacketID m_PacketID = 0; PacketID m_PacketID = 0;
PacketID m_PreviousPacketID = 0; PacketID m_PreviousPacketID = 0;
@@ -66,7 +64,6 @@ private:
void reliableBroadcast(Packet& packet); void reliableBroadcast(Packet& packet);
void unreliableBroadcast(Packet& packet); void unreliableBroadcast(Packet& packet);
void sendSnapshot(); void sendSnapshot();
void addPlayersToPacket(Packet& packet, EntityID entityID);
void addChildrenToPacket(Packet& packet, EntityID entityID); void addChildrenToPacket(Packet& packet, EntityID entityID);
void addInputCommandsToPacket(Packet& packet); void addInputCommandsToPacket(Packet& packet);
void sendPing(); void sendPing();
@@ -80,12 +77,10 @@ private:
void parsePlayerTransform(Packet& packet); void parsePlayerTransform(Packet& packet);
void parseOnInputCommand(Packet& packet); void parseOnInputCommand(Packet& packet);
void parseClientPing(); void parseClientPing();
void parsePing(); void parsePing();
bool parseDoubleJump(Packet& packet); void parseUDPConnect(Packet & packet);
void parseUDPConnect(Packet& packet); void parseTCPConnect(Packet & packet);
void parseTCPConnect(Packet& packet);
void parseDisconnect(); void parseDisconnect();
void parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint);
bool shouldSendToClient(EntityWrapper childEntity); bool shouldSendToClient(EntityWrapper childEntity);
// Debug event // Debug event
+1 -1
View File
@@ -20,7 +20,7 @@ private:
boost::asio::ip::tcp::endpoint m_Endpoint; boost::asio::ip::tcp::endpoint m_Endpoint;
boost::asio::io_service m_IOService; boost::asio::io_service m_IOService;
std::unique_ptr<boost::asio::ip::tcp::socket> m_Socket; std::unique_ptr<boost::asio::ip::tcp::socket> m_Socket;
size_t readBuffer(); size_t readBuffer(char* data);
PacketID m_SendPacketID = 0; PacketID m_SendPacketID = 0;
bool m_IsConnected = false; bool m_IsConnected = false;
}; };
+4 -10
View File
@@ -16,22 +16,16 @@ public:
void Send(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet, PlayerDefinition & playerDefinition);
void Send(Packet & packet); void Send(Packet & packet);
void Disconnect(); void Disconnect();
int Port() { return m_Port; }
std::string Address() { return m_Address; }
private: private:
// TCP logic // TCP logic
boost::asio::io_service m_IOService; boost::asio::io_service m_IOService;
std::unique_ptr<boost::asio::ip::tcp::acceptor> acceptor; std::unique_ptr<boost::asio::ip::tcp::acceptor> acceptor;
boost::shared_ptr<boost::asio::ip::tcp::socket> lastReceivedSocket; boost::shared_ptr<boost::asio::ip::tcp::socket> lastReceivedSocket;
int readBuffer(PlayerDefinition& playerDefinition); void handle_accept(boost::shared_ptr<boost::asio::ip::tcp::socket> socket,
PlayerID getPlayerIDFromEndpoint(const std::map<PlayerID, PlayerDefinition>& connectedPlayers, int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers,
boost::asio::ip::address address, unsigned short port); const boost::system::error_code& error);
int GetPort(); int readBuffer(char* data, PlayerDefinition& playerDefinition);
std::string GetAddress();
int m_Port = 0;
std::string m_Address = "";
}; };
#endif #endif
+1 -2
View File
@@ -14,14 +14,13 @@ public:
void Disconnect(); void Disconnect();
void Receive(Packet& packet); void Receive(Packet& packet);
void Send(Packet & packet); void Send(Packet & packet);
void Broadcast(Packet& packet, int port);
bool IsSocketAvailable(); bool IsSocketAvailable();
private: private:
// Assio UDP logic // Assio UDP logic
boost::asio::io_service m_IOService; boost::asio::io_service m_IOService;
boost::asio::ip::udp::endpoint m_ReceiverEndpoint; boost::asio::ip::udp::endpoint m_ReceiverEndpoint;
boost::shared_ptr<boost::asio::ip::udp::socket> m_Socket; boost::shared_ptr<boost::asio::ip::udp::socket> m_Socket;
int readBuffer(); int readBuffer(char* data);
PacketID m_SendPacketID = 0; PacketID m_SendPacketID = 0;
}; };
+2 -5
View File
@@ -8,21 +8,18 @@ class UDPServer : public NetworkServer
{ {
public: public:
UDPServer(); UDPServer();
UDPServer(int port);
~UDPServer(); ~UDPServer();
void AcceptNewConnections(int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers); void AcceptNewConnections(int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers);
void Receive(Packet & packet, PlayerDefinition & playerDefinition); void Receive(Packet & packet, PlayerDefinition & playerDefinition);
void Send(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet, PlayerDefinition & playerDefinition);
void Send(Packet & packet); void Send(Packet & packet);
void Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint);
void Broadcast(Packet & packet, int port);
bool IsSocketAvailable(); bool IsSocketAvailable();
private: private:
// UDP logic // UDP logic
boost::asio::io_service m_IOService; boost::asio::io_service m_IOService;
boost::asio::ip::udp::endpoint m_ReceiverEndpoint; boost::asio::ip::udp::endpoint m_ReceiverEndpoint;
std::unique_ptr<boost::asio::ip::udp::socket> m_Socket; std::unique_ptr<boost::asio::ip::udp::socket> m_Socket;
int readBuffer(); int readBuffer(char* data);
}; };
#endif #endif
-27
View File
@@ -1,27 +0,0 @@
#ifndef CubeMapPass_h__
#define CubeMapPass_h__
#include "IRenderer.h"
#include "ShaderProgram.h"
class CubeMapPass
{
public:
CubeMapPass(IRenderer* renderer);
~CubeMapPass() { }
void LoadTextures(std::string input);
void FillCubeMap(glm::vec3 originPosition);
void GenerateCubeMapTexture();
//GLuint CubeMapTexture() const { return m_CubeMapTexture; }
GLuint m_CubeMapTexture = -1;
private:
IRenderer* m_Renderer;
std::string m_PreviusCubeMapTexture;
std::vector<Texture*> m_CubeMapTextures;
};
#endif
+1 -4
View File
@@ -4,7 +4,6 @@
#include "IRenderer.h" #include "IRenderer.h"
#include "DrawFinalPassState.h" #include "DrawFinalPassState.h"
#include "LightCullingPass.h" #include "LightCullingPass.h"
#include "CubeMapPass.h"
#include "FrameBuffer.h" #include "FrameBuffer.h"
#include "ShaderProgram.h" #include "ShaderProgram.h"
#include "Util/UnorderedMapVec2.h" #include "Util/UnorderedMapVec2.h"
@@ -14,7 +13,7 @@
class DrawFinalPass class DrawFinalPass
{ {
public: public:
DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass); DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass);
~DrawFinalPass() { } ~DrawFinalPass() { }
void InitializeTextures(); void InitializeTextures();
void InitializeFrameBuffers(); void InitializeFrameBuffers();
@@ -63,14 +62,12 @@ private:
GLuint m_SceneTextureLowRes; GLuint m_SceneTextureLowRes;
GLuint m_DepthBuffer; GLuint m_DepthBuffer;
GLuint m_DepthBufferLowRes; GLuint m_DepthBufferLowRes;
GLuint m_CubeMapTexture;
//maqke this component based i guess? //maqke this component based i guess?
GLuint m_ShieldPixelRate = 16; GLuint m_ShieldPixelRate = 16;
const IRenderer* m_Renderer; const IRenderer* m_Renderer;
const LightCullingPass* m_LightCullingPass; const LightCullingPass* m_LightCullingPass;
const CubeMapPass* m_CubeMapPass;
ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ForwardPlusProgram;
ShaderProgram* m_ExplosionEffectProgram; ShaderProgram* m_ExplosionEffectProgram;
+1 -1
View File
@@ -184,7 +184,7 @@ struct ModelJob : RenderJob
void CalculateHash() override void CalculateHash() override
{ {
Hash = ShaderID << 20 + ModelID << 10 + TextureID; Hash = TextureID + ModelID << 10 + ShaderID << 20;
} }
}; };
-3
View File
@@ -17,7 +17,6 @@
#include "DrawBloomPass.h" #include "DrawBloomPass.h"
#include "DrawColorCorrectionPass.h" #include "DrawColorCorrectionPass.h"
#include "SSAOPass.h" #include "SSAOPass.h"
#include "CubeMapPass.h"
#include "../Core/EventBroker.h" #include "../Core/EventBroker.h"
#include "ImGuiRenderPass.h" #include "ImGuiRenderPass.h"
#include "Camera.h" #include "Camera.h"
@@ -59,7 +58,6 @@ private:
Model* m_UnitSphere; Model* m_UnitSphere;
int m_DebugTextureToDraw = 0; int m_DebugTextureToDraw = 0;
int m_CubeMapTexture = 0;
bool m_ResizeWindow = false; bool m_ResizeWindow = false;
float m_SSAO_Radius = 1.0f; float m_SSAO_Radius = 1.0f;
float m_SSAO_Bias = 0.05f; float m_SSAO_Bias = 0.05f;
@@ -76,7 +74,6 @@ private:
DrawBloomPass* m_DrawBloomPass; DrawBloomPass* m_DrawBloomPass;
DrawColorCorrectionPass* m_DrawColorCorrectionPass; DrawColorCorrectionPass* m_DrawColorCorrectionPass;
SSAOPass* m_SSAOPass; SSAOPass* m_SSAOPass;
CubeMapPass* m_CubeMapPass;
//----------------------Functions----------------------// //----------------------Functions----------------------//
void InitializeWindow(); void InitializeWindow();
+3 -7
View File
@@ -14,14 +14,11 @@ class SSAOPass
{ {
public: public:
SSAOPass(IRenderer* rendere); SSAOPass(IRenderer* rendere);
~SSAOPass() { ~SSAOPass() { };
delete m_DrawBloomPass;
};
void Draw(GLuint depthBuffer, Camera* camera); void Draw(GLuint depthBuffer, Camera* camera);
void Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns); void Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns);
void ClearBuffer(); void ClearBuffer();
void OnWindowResize();
//Return the SSAO of the texture sent to Draw //Return the SSAO of the texture sent to Draw
GLuint SSAOTexture() const { return m_DrawBloomPass->GaussianTexture(); } GLuint SSAOTexture() const { return m_DrawBloomPass->GaussianTexture(); }
@@ -32,15 +29,14 @@ private:
void InitializeShaderProgram(); void InitializeShaderProgram();
void InitializeBuffer(); void InitializeBuffer();
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; void ComputeAO(GLuint depthBuffer, Camera* camera);
//void blurHorizontal(GLuint depthBuffer); //void blurHorizontal(GLuint depthBuffer);
//void blurVertical(GLuint depthBuffer); //void blurVertical(GLuint depthBuffer);
Model* m_ScreenQuad; Model* m_ScreenQuad;
const IRenderer* m_Renderer; const IRenderer* m_Renderer;
static const GLint MAX_MIP_LEVEL = 5;
float m_Radius; float m_Radius;
float m_Bias; float m_Bias;
float m_Contrast; float m_Contrast;
+3 -6
View File
@@ -17,7 +17,7 @@
struct SpriteJob : RenderJob struct SpriteJob : RenderJob
{ {
SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage, bool depthSorted, bool isIndicator) SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage, bool depthSorted)
: RenderJob() : RenderJob()
{ {
Model = ResourceManager::Load<::Model>("Models/Core/UnitQuad.mesh"); Model = ResourceManager::Load<::Model>("Models/Core/UnitQuad.mesh");
@@ -30,7 +30,7 @@ struct SpriteJob : RenderJob
StartIndex = matProp.material->StartIndex; StartIndex = matProp.material->StartIndex;
EndIndex = matProp.material->EndIndex; EndIndex = matProp.material->EndIndex;
Matrix = matrix; Matrix = matrix;
Color = cSprite["Color"]; Color = cSprite["Color"];
Entity = cSprite.EntityID; Entity = cSprite.EntityID;
Position = Transform::AbsolutePosition(world, cSprite.EntityID); Position = Transform::AbsolutePosition(world, cSprite.EntityID);
@@ -41,8 +41,7 @@ struct SpriteJob : RenderJob
} }
World = world; World = world;
Pickable = world->HasComponent(cSprite.EntityID, "Button"); Pickable = world->HasComponent(cSprite.EntityID, "Button");
IsIndicator = isIndicator;
FillColor = fillColor; FillColor = fillColor;
FillPercentage = fillPercentage; FillPercentage = fillPercentage;
}; };
@@ -62,9 +61,7 @@ struct SpriteJob : RenderJob
unsigned int StartIndex = 0; unsigned int StartIndex = 0;
unsigned int EndIndex = 0; unsigned int EndIndex = 0;
World* World; World* World;
bool Pickable; bool Pickable;
bool IsIndicator = false;
glm::vec4 FillColor = glm::vec4(0); glm::vec4 FillColor = glm::vec4(0);
float FillPercentage = 0.0; float FillPercentage = 0.0;
-1
View File
@@ -18,7 +18,6 @@ public:
void Bind(GLenum textureUnit = GL_TEXTURE0); void Bind(GLenum textureUnit = GL_TEXTURE0);
GLuint m_Texture = 0; GLuint m_Texture = 0;
unsigned char* Data = nullptr;
}; };
+1 -1
View File
@@ -8,7 +8,7 @@ namespace Events
struct DoubleJump : public Event struct DoubleJump : public Event
{ {
EntityID entityID;
}; };
} }
-1
View File
@@ -26,7 +26,6 @@ private:
double AmmoGain; double AmmoGain;
double RespawnTimer; double RespawnTimer;
double DecreaseThisRespawnTimer; double DecreaseThisRespawnTimer;
EntityID parentID;
}; };
std::vector<NewAmmoPickup> m_ETriggerTouchVector; std::vector<NewAmmoPickup> m_ETriggerTouchVector;
}; };
+1 -17
View File
@@ -14,13 +14,11 @@
#include <glm/gtx/vector_angle.hpp> #include <glm/gtx/vector_angle.hpp>
#include "Rendering/Util/CommonFunctions.h" #include "Rendering/Util/CommonFunctions.h"
//#define INDICATOR_TEST
class DamageIndicatorSystem : public ImpureSystem class DamageIndicatorSystem : public System
{ {
public: public:
DamageIndicatorSystem(SystemParams params); DamageIndicatorSystem(SystemParams params);
virtual void Update(double dt) override;
private: private:
EventRelay<DamageIndicatorSystem, Events::PlayerDamage> m_EPlayerDamage; EventRelay<DamageIndicatorSystem, Events::PlayerDamage> m_EPlayerDamage;
@@ -30,20 +28,6 @@ private:
bool OnSetCamera(const Events::SetCamera& e); bool OnSetCamera(const Events::SetCamera& e);
EntityID m_CurrentCamera = -1; EntityID m_CurrentCamera = -1;
struct DamageIndicatorStruct {
EntityWrapper spriteEntity;
glm::vec3 enemyPosition;
DamageIndicatorStruct(EntityWrapper sprite, glm::vec3 pos)
: spriteEntity(sprite)
, enemyPosition(pos) {}
};
std::vector<DamageIndicatorStruct> updateDamageIndicatorVector;
float CalculateAngle(EntityWrapper player, glm::vec3 enemyPos);
//for tests
#ifdef INDICATOR_TEST
glm::vec3 DamageIndicatorTest(EntityWrapper player);
int m_TestVar = 0;
#endif
}; };
#endif #endif
-1
View File
@@ -27,7 +27,6 @@ private:
double HealthGain; double HealthGain;
double RespawnTimer; double RespawnTimer;
double DecreaseThisRespawnTimer; double DecreaseThisRespawnTimer;
EntityID parentID;
}; };
std::vector<NewHealthPickup> m_ETriggerTouchVector; std::vector<NewHealthPickup> m_ETriggerTouchVector;
}; };
+1 -5
View File
@@ -34,14 +34,10 @@ private:
glm::vec3 m_LastPosition = glm::vec3(); glm::vec3 m_LastPosition = glm::vec3();
// The logic for making the sound play when player is moving // The logic for making the sound play when player is moving
void playerStep(double dt); void playerStep(double dt);
// Spawn a hexagon at origin of an Entity
void spawnHexagon(EntityWrapper target);
EventRelay<PlayerMovementSystem, Events::PlayerSpawned> m_EPlayerSpawned; EventRelay<PlayerMovementSystem, Events::PlayerSpawned> m_EPlayerSpawned;
bool OnPlayerSpawned(Events::PlayerSpawned& e); bool OnPlayerSpawned(Events::PlayerSpawned& e);
EventRelay<PlayerMovementSystem, Events::DoubleJump> m_EDoubleJump;
bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e);
void updateMovementControllers(double dt); void updateMovementControllers(double dt);
void updateVelocity(EntityWrapper player, double dt); void updateVelocity(double dt);
}; };
-1
View File
@@ -44,6 +44,5 @@
<xs:include schemaLocation="Components/Menu.xsd"/> <xs:include schemaLocation="Components/Menu.xsd"/>
<xs:include schemaLocation="Components/KillFeed.xsd"/> <xs:include schemaLocation="Components/KillFeed.xsd"/>
<xs:include schemaLocation="Components/Page.xsd"/> <xs:include schemaLocation="Components/Page.xsd"/>
<xs:include schemaLocation="Components/SpriteIndicator.xsd"/>
<xs:include schemaLocation="Components/Button.xsd"/> <xs:include schemaLocation="Components/Button.xsd"/>
</xs:schema> </xs:schema>
+1
View File
@@ -2,6 +2,7 @@
<Physics xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Physics.xsd"> <Physics xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Physics.xsd">
<Velocity X="0" Y="0" Z="0"/> <Velocity X="0" Y="0" Z="0"/>
<Gravity>true</Gravity> <Gravity>true</Gravity>
<PrevOrigin X="-9876.5" Y="-9876.5" Z="-9876.5"/>
<IsOnGround>false</IsOnGround> <IsOnGround>false</IsOnGround>
<VerticalStepHeight>0.33</VerticalStepHeight> <VerticalStepHeight>0.33</VerticalStepHeight>
</Physics> </Physics>
+1
View File
@@ -13,6 +13,7 @@
<xs:annotation><xs:documentation>m/s^2</xs:documentation></xs:annotation> <xs:annotation><xs:documentation>m/s^2</xs:documentation></xs:annotation>
</xs:element> </xs:element>
<xs:element name="Gravity" type="t:bool" minOccurs="0"/> <xs:element name="Gravity" type="t:bool" minOccurs="0"/>
<xs:element name="PrevOrigin" type="t:Vector" minOccurs="0"/>
<xs:element name="IsOnGround" type="t:bool" minOccurs="0"/> <xs:element name="IsOnGround" type="t:bool" minOccurs="0"/>
<xs:element name="VerticalStepHeight" type="t:double" minOccurs="0"> <xs:element name="VerticalStepHeight" type="t:double" minOccurs="0">
<xs:annotation><xs:documentation>The largest height of a "stair-step" that can be walked over</xs:documentation></xs:annotation> <xs:annotation><xs:documentation>The largest height of a "stair-step" that can be walked over</xs:documentation></xs:annotation>
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<SpriteIndicator xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="SpriteIndicator.xsd">
<MinScale>10</MinScale>
<VisibleForSingleTeamOnly>false</VisibleForSingleTeamOnly>
</SpriteIndicator>
@@ -1,19 +0,0 @@
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="types">
<xs:import schemaLocation="../Types.xsd" namespace="types"/>
<xs:element name="SpriteIndicator">
<xs:annotation>
<xs:documentation>Billbord a Sprite around global Y axis</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:all>
<xs:element name="MinScale" type="t:double" minOccurs="0"/>
<xs:element name="VisibleForSingleTeamOnly" type="t:bool" minOccurs="0">
<xs:annotation><xs:documentation>Add a Team component to this Entity or Parent to make it visible only for that team</xs:documentation></xs:annotation>
</xs:element>
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
+5 -5
View File
@@ -2,18 +2,18 @@
<Entity xmlns:c="components" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../Types/Entity.xsd"> <Entity xmlns:c="components" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../Types/Entity.xsd">
<Components> <Components>
<c:AABB/>
<c:AmmoPickup/> <c:AmmoPickup/>
<c:Model> <c:Model>
<Resource>Models/Props/PickUps/AmmoPickUp.mesh</Resource> <Resource>Models/Props/PickUps/AmmoPickUp.mesh</Resource>
</c:Model> </c:Model>
<c:RaptorCopter> <c:RaptorCopter>
<Speed>8</Speed> <Speed>0.1</Speed>
<Axis X="0" Y="0.100000001" Z="0"/> <Axis X="0" Y="1" Z="0"/>
</c:RaptorCopter> </c:RaptorCopter>
<c:Transform> <c:Transform>
<Position X="0" Y="2.36784196" Z="0"/> <Position X="0" Y="1" Z="0"/>
<Scale X="0.600000024" Y="0.600000024" Z="0.600000024"/> <Scale X="0.3" Y="0.3" Z="0.3"/>
<Orientation X="0" Y="18717.9453" Z="0"/>
</c:Transform> </c:Transform>
<c:Trigger/> <c:Trigger/>
</Components> </Components>
+5 -5
View File
@@ -2,18 +2,18 @@
<Entity xmlns:c="components" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../Types/Entity.xsd"> <Entity xmlns:c="components" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../Types/Entity.xsd">
<Components> <Components>
<c:AABB/>
<c:HealthPickup/> <c:HealthPickup/>
<c:Model> <c:Model>
<Resource>Models/Props/PickUps/HealthPickUp.mesh</Resource> <Resource>Models/Props/PickUps/HealthPickUp.mesh</Resource>
</c:Model> </c:Model>
<c:RaptorCopter> <c:RaptorCopter>
<Speed>8</Speed> <Speed>0.1</Speed>
<Axis X="0" Y="0.100000001" Z="0"/> <Axis X="0" Y="1" Z="0"/>
</c:RaptorCopter> </c:RaptorCopter>
<c:Transform> <c:Transform>
<Position X="0" Y="2.36784196" Z="0"/> <Position X="0" Y="1" Z="0"/>
<Scale X="0.600000024" Y="0.600000024" Z="0.600000024"/> <Scale X="0.3" Y="0.3" Z="0.3"/>
<Orientation X="0" Y="18767.0273" Z="0"/>
</c:Transform> </c:Transform>
<c:Trigger/> <c:Trigger/>
</Components> </Components>
+8 -47
View File
@@ -60,7 +60,6 @@
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Weapons/Crosshair/SmallThickHoleDot.png</DiffuseTexture> <DiffuseTexture>Textures/Weapons/Crosshair/SmallThickHoleDot.png</DiffuseTexture>
<DepthSort>false</DepthSort> <DepthSort>false</DepthSort>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.200000003"/> <Position X="0" Y="0" Z="0.200000003"/>
@@ -111,7 +110,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/HealthHUD3.png</DiffuseTexture> <DiffuseTexture>Textures/HealthHUD3.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.588235319" B="0" G="0" R="0"/> <Color A="0.588235319" B="0" G="0" R="0"/>
</c:Sprite> </c:Sprite>
<c:HealthHUD/> <c:HealthHUD/>
@@ -137,7 +135,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.300000012" B="1" G="1" R="1"/> <Color A="0.300000012" B="1" G="1" R="1"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -155,7 +152,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.00999999978"/> <Position X="0" Y="0" Z="0.00999999978"/>
@@ -171,7 +167,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.300000012" B="1" G="1" R="1"/> <Color A="0.300000012" B="1" G="1" R="1"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -190,7 +185,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.00999999978"/> <Position X="0" Y="0" Z="0.00999999978"/>
@@ -206,7 +200,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.699999988" B="1" G="0.200000003" R="0"/> <Color A="0.699999988" B="1" G="0.200000003" R="0"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -224,7 +217,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.00999999978"/> <Position X="0" Y="0" Z="0.00999999978"/>
@@ -240,7 +232,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.300000012" B="1" G="1" R="1"/> <Color A="0.300000012" B="1" G="1" R="1"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -258,7 +249,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.00999999978"/> <Position X="0" Y="0" Z="0.00999999978"/>
@@ -274,7 +264,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.699999988" B="0" G="0.200000003" R="1"/> <Color A="0.699999988" B="0" G="0.200000003" R="1"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -290,7 +279,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.00999999978"/> <Position X="0" Y="0" Z="0.00999999978"/>
@@ -303,7 +291,8 @@
</Children> </Children>
</Entity> </Entity>
</Children> </Children>
</Entity> <Entity name="KillFeed"> </Entity>
<Entity name="KillFeed">
<Components> <Components>
<c:KillFeed/> <c:KillFeed/>
<c:Transform> <c:Transform>
@@ -315,7 +304,6 @@
<Entity name="KillFeed1"> <Entity name="KillFeed1">
<Components> <Components>
<c:Text> <c:Text>
<Content></Content>
<Resource>Fonts/DroidSans.ttf,64</Resource> <Resource>Fonts/DroidSans.ttf,64</Resource>
<Alignment> <Alignment>
<Right/> <Right/>
@@ -328,7 +316,6 @@
<Entity name="KillFeed2"> <Entity name="KillFeed2">
<Components> <Components>
<c:Text> <c:Text>
<Content></Content>
<Resource>Fonts/DroidSans.ttf,64</Resource> <Resource>Fonts/DroidSans.ttf,64</Resource>
<Alignment> <Alignment>
<Right/> <Right/>
@@ -343,7 +330,6 @@
<Entity name="KillFeed3"> <Entity name="KillFeed3">
<Components> <Components>
<c:Text> <c:Text>
<Content></Content>
<Resource>Fonts/DroidSans.ttf,64</Resource> <Resource>Fonts/DroidSans.ttf,64</Resource>
<Alignment> <Alignment>
<Right/> <Right/>
@@ -363,10 +349,8 @@
<Components> <Components>
<c:Animation> <c:Animation>
<AnimationName1>Idle</AnimationName1> <AnimationName1>Idle</AnimationName1>
<Time1>0.97725610639912475</Time1> <Time1>1.8314163732853146</Time1>
<Speed1>1</Speed1> <Speed1>1</Speed1>
<AnimationName2></AnimationName2>
<AnimationName3></AnimationName3>
</c:Animation> </c:Animation>
<c:Model> <c:Model>
<Resource>Models/Characters/Assault/FirstPerson.mesh</Resource> <Resource>Models/Characters/Assault/FirstPerson.mesh</Resource>
@@ -384,8 +368,8 @@
<Resource>Models/Weapons/Blue/AssaultWeaponBlue.mesh</Resource> <Resource>Models/Weapons/Blue/AssaultWeaponBlue.mesh</Resource>
</c:Model> </c:Model>
<c:Transform> <c:Transform>
<Position X="0.12043038" Y="-0.244988307" Z="-0.181454808"/> <Position X="0.120430619" Y="-0.229687244" Z="-0.181454629"/>
<Orientation X="0.010404544" Y="-0.00268173823" Z="0.0428441577"/> <Orientation X="0.0104048112" Y="-0.0026817855" Z="0.0428442657"/>
</c:Transform> </c:Transform>
</Components> </Components>
<Children> <Children>
@@ -422,7 +406,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.588235319" B="0" G="0" R="0"/> <Color A="0.588235319" B="0" G="0" R="0"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -492,10 +475,8 @@
<Components> <Components>
<c:Animation> <c:Animation>
<AnimationName1>Idle</AnimationName1> <AnimationName1>Idle</AnimationName1>
<Time1>0.87583812735846323</Time1> <Time1>0.16333512901638159</Time1>
<Speed1>1</Speed1> <Speed1>1</Speed1>
<AnimationName2></AnimationName2>
<AnimationName3></AnimationName3>
</c:Animation> </c:Animation>
<c:AnimationOffset> <c:AnimationOffset>
<AnimationName>AimRifle</AnimationName> <AnimationName>AimRifle</AnimationName>
@@ -518,8 +499,8 @@
<Resource>Models/Weapons/Blue/AssaultWeaponBlue.mesh</Resource> <Resource>Models/Weapons/Blue/AssaultWeaponBlue.mesh</Resource>
</c:Model> </c:Model>
<c:Transform> <c:Transform>
<Position X="0.163429111" Y="1.0235405" Z="-0.215489209"/> <Position X="0.158296332" Y="1.03131664" Z="-0.21615544"/>
<Orientation X="-0.0631071255" Y="-0.0576644838" Z="0.118255548"/> <Orientation X="-0.0626514703" Y="-0.0352048129" Z="0.12013837"/>
</c:Transform> </c:Transform>
</Components> </Components>
<Children> <Children>
@@ -589,26 +570,6 @@
</Components> </Components>
<Children/> <Children/>
</Entity> </Entity>
<Entity name="Indicator">
<Components>
<c:Sprite>
<DiffuseTexture>Textures/Icons/Arrow.png</DiffuseTexture>
<DepthSort>false</DepthSort>
<GlowMap></GlowMap>
<Color A="1" B="1" G="0.309803933" R="0"/>
</c:Sprite>
<c:HiddenForLocalPlayer/>
<c:SpriteIndicator>
<MinScale>50</MinScale>
<VisibleForSingleTeamOnly>true</VisibleForSingleTeamOnly>
</c:SpriteIndicator>
<c:Transform>
<Position X="0" Y="1.84019077" Z="0"/>
<Scale X="0.300000012" Y="0.300000012" Z="0.300000012"/>
</c:Transform>
</Components>
<Children/>
</Entity>
</Children> </Children>
</Entity> </Entity>
+6 -46
View File
@@ -60,7 +60,6 @@
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Weapons/Crosshair/SmallThickHoleDot.png</DiffuseTexture> <DiffuseTexture>Textures/Weapons/Crosshair/SmallThickHoleDot.png</DiffuseTexture>
<DepthSort>false</DepthSort> <DepthSort>false</DepthSort>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.200000003"/> <Position X="0" Y="0" Z="0.200000003"/>
@@ -111,7 +110,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/HealthHUD3.png</DiffuseTexture> <DiffuseTexture>Textures/HealthHUD3.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.588235319" B="0" G="0" R="0"/> <Color A="0.588235319" B="0" G="0" R="0"/>
</c:Sprite> </c:Sprite>
<c:HealthHUD/> <c:HealthHUD/>
@@ -137,7 +135,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.300000012" B="1" G="1" R="1"/> <Color A="0.300000012" B="1" G="1" R="1"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -155,7 +152,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.00999999978"/> <Position X="0" Y="0" Z="0.00999999978"/>
@@ -171,7 +167,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.300000012" B="1" G="1" R="1"/> <Color A="0.300000012" B="1" G="1" R="1"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -190,7 +185,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.00999999978"/> <Position X="0" Y="0" Z="0.00999999978"/>
@@ -206,7 +200,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.699999988" B="1" G="0.200000003" R="0"/> <Color A="0.699999988" B="1" G="0.200000003" R="0"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -224,7 +217,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.00999999978"/> <Position X="0" Y="0" Z="0.00999999978"/>
@@ -240,7 +232,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.300000012" B="1" G="1" R="1"/> <Color A="0.300000012" B="1" G="1" R="1"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -258,7 +249,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.00999999978"/> <Position X="0" Y="0" Z="0.00999999978"/>
@@ -274,7 +264,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.699999988" B="0" G="0.200000003" R="1"/> <Color A="0.699999988" B="0" G="0.200000003" R="1"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -290,7 +279,6 @@
</c:Fill> </c:Fill>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon_Rotated.png</DiffuseTexture>
<GlowMap></GlowMap>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
<Position X="0" Y="0" Z="0.00999999978"/> <Position X="0" Y="0" Z="0.00999999978"/>
@@ -316,7 +304,6 @@
<Entity name="KillFeed1"> <Entity name="KillFeed1">
<Components> <Components>
<c:Text> <c:Text>
<Content></Content>
<Resource>Fonts/DroidSans.ttf,64</Resource> <Resource>Fonts/DroidSans.ttf,64</Resource>
<Alignment> <Alignment>
<Right/> <Right/>
@@ -329,7 +316,6 @@
<Entity name="KillFeed2"> <Entity name="KillFeed2">
<Components> <Components>
<c:Text> <c:Text>
<Content></Content>
<Resource>Fonts/DroidSans.ttf,64</Resource> <Resource>Fonts/DroidSans.ttf,64</Resource>
<Alignment> <Alignment>
<Right/> <Right/>
@@ -344,7 +330,6 @@
<Entity name="KillFeed3"> <Entity name="KillFeed3">
<Components> <Components>
<c:Text> <c:Text>
<Content></Content>
<Resource>Fonts/DroidSans.ttf,64</Resource> <Resource>Fonts/DroidSans.ttf,64</Resource>
<Alignment> <Alignment>
<Right/> <Right/>
@@ -364,10 +349,8 @@
<Components> <Components>
<c:Animation> <c:Animation>
<AnimationName1>Idle</AnimationName1> <AnimationName1>Idle</AnimationName1>
<Time1>1.2667383999985162</Time1> <Time1>0.018170670865885086</Time1>
<Speed1>1</Speed1> <Speed1>1</Speed1>
<AnimationName2></AnimationName2>
<AnimationName3></AnimationName3>
</c:Animation> </c:Animation>
<c:Model> <c:Model>
<Resource>Models/Characters/Assault/FirstPerson.mesh</Resource> <Resource>Models/Characters/Assault/FirstPerson.mesh</Resource>
@@ -385,8 +368,8 @@
<Resource>Models/Weapons/Red/AssaultWeaponRed.mesh</Resource> <Resource>Models/Weapons/Red/AssaultWeaponRed.mesh</Resource>
</c:Model> </c:Model>
<c:Transform> <c:Transform>
<Position X="0.120430425" Y="-0.242105931" Z="-0.181454822"/> <Position X="0.120430693" Y="-0.2284486" Z="-0.181454509"/>
<Orientation X="0.010404665" Y="-0.00268179877" Z="0.0428443067"/> <Orientation X="0.0104046017" Y="-0.00268172775" Z="0.0428442247"/>
</c:Transform> </c:Transform>
</Components> </Components>
<Children> <Children>
@@ -423,7 +406,6 @@
<Components> <Components>
<c:Sprite> <c:Sprite>
<DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture> <DiffuseTexture>Textures/Core/UnitHexagon.png</DiffuseTexture>
<GlowMap></GlowMap>
<Color A="0.588235319" B="0" G="0" R="0"/> <Color A="0.588235319" B="0" G="0" R="0"/>
</c:Sprite> </c:Sprite>
<c:Transform> <c:Transform>
@@ -493,10 +475,8 @@
<Components> <Components>
<c:Animation> <c:Animation>
<AnimationName1>Idle</AnimationName1> <AnimationName1>Idle</AnimationName1>
<Time1>0.26532318661337229</Time1> <Time1>0.11675631578762591</Time1>
<Speed1>1</Speed1> <Speed1>1</Speed1>
<AnimationName2></AnimationName2>
<AnimationName3></AnimationName3>
</c:Animation> </c:Animation>
<c:AnimationOffset> <c:AnimationOffset>
<AnimationName>AimRifle</AnimationName> <AnimationName>AimRifle</AnimationName>
@@ -519,8 +499,8 @@
<Resource>Models/Weapons/Red/AssaultWeaponRed.mesh</Resource> <Resource>Models/Weapons/Red/AssaultWeaponRed.mesh</Resource>
</c:Model> </c:Model>
<c:Transform> <c:Transform>
<Position X="0.159282878" Y="1.0300566" Z="-0.216084003"/> <Position X="0.157842755" Y="1.03184748" Z="-0.216178894"/>
<Orientation X="-0.0626799241" Y="-0.0390551724" Z="0.119761385"/> <Orientation X="-0.0626459867" Y="-0.0335309952" Z="0.120309927"/>
</c:Transform> </c:Transform>
</Components> </Components>
<Children> <Children>
@@ -590,26 +570,6 @@
</Components> </Components>
<Children/> <Children/>
</Entity> </Entity>
<Entity>
<Components>
<c:Sprite>
<DiffuseTexture>Textures/Icons/Arrow.png</DiffuseTexture>
<DepthSort>false</DepthSort>
<GlowMap></GlowMap>
<Color A="1" B="0" G="0" R="1"/>
</c:Sprite>
<c:HiddenForLocalPlayer/>
<c:SpriteIndicator>
<MinScale>50</MinScale>
<VisibleForSingleTeamOnly>true</VisibleForSingleTeamOnly>
</c:SpriteIndicator>
<c:Transform>
<Position X="0" Y="1.84000003" Z="0"/>
<Scale X="0.300000012" Y="0.300000012" Z="0.300000012"/>
</c:Transform>
</Components>
<Children/>
</Entity>
</Children> </Children>
</Entity> </Entity>
+3 -12
View File
@@ -12,7 +12,6 @@ uniform vec4 FillColor;
uniform vec4 AmbientColor; uniform vec4 AmbientColor;
uniform float FillPercentage; uniform float FillPercentage;
uniform float GlowIntensity = 10; uniform float GlowIntensity = 10;
uniform vec3 CameraPosition;
uniform vec2 DiffuseUVRepeat; uniform vec2 DiffuseUVRepeat;
uniform vec2 NormalUVRepeat; uniform vec2 NormalUVRepeat;
@@ -23,7 +22,6 @@ layout (binding = 1) uniform sampler2D DiffuseTexture;
layout (binding = 2) uniform sampler2D NormalMapTexture; layout (binding = 2) uniform sampler2D NormalMapTexture;
layout (binding = 3) uniform sampler2D SpecularMapTexture; layout (binding = 3) uniform sampler2D SpecularMapTexture;
layout (binding = 4) uniform sampler2D GlowMapTexture; layout (binding = 4) uniform sampler2D GlowMapTexture;
layout (binding = 5) uniform samplerCube CubeMap;
#define TILE_SIZE 16 #define TILE_SIZE 16
@@ -78,7 +76,7 @@ struct LightResult {
}; };
float CalcAttenuation(float radius, float dist, float falloff) { float CalcAttenuation(float radius, float dist, float falloff) {
return 1.0 - smoothstep(radius * falloff, radius, dist); return 1.0 - smoothstep(radius * 0.3, radius, dist);
} }
vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) {
@@ -134,11 +132,7 @@ void main()
vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate * NormalUVRepeat, NormalMapTexture); vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate * NormalUVRepeat, NormalMapTexture);
normal = normalize(normal); normal = normalize(normal);
//vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0));
vec4 viewVec = normalize(-position); vec4 viewVec = normalize(-position);
vec3 I = normalize(vec3(M * vec4(Input.Position, 1.0)) - CameraPosition);
vec3 R = reflect(-I, Input.Normal);
//R = vec3(P * vec4(R, 1.0));
vec4 reflectionColor = texture(CubeMap, R);
vec2 tilePos; vec2 tilePos;
tilePos.x = int(gl_FragCoord.x/TILE_SIZE); tilePos.x = int(gl_FragCoord.x/TILE_SIZE);
@@ -169,8 +163,6 @@ void main()
vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed);
color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel));
float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0;
color_result = color_result * clamp(1/specularTexel, 0, 1)*2 + reflectionColor * clamp(specularTexel, 0, 1)/2;
//vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color;
@@ -180,10 +172,9 @@ void main()
color_result += FillColor; color_result += FillColor;
} }
sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1));
//sceneColor = vec4(reflectionColor.xyz, 1);
color_result += glowTexel*GlowIntensity; color_result += glowTexel*GlowIntensity;
bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), clamp(color_result.a, 0, 1)); bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0);
//Tiled Debug Code //Tiled Debug Code
/* /*
+4 -4
View File
@@ -23,12 +23,12 @@ out VertexData{
void main() void main()
{ {
gl_Position = P*V*M * vec4(Position, 1.0); gl_Position = P*V*M * vec4(Position, 1.0);
mat4 TIM = transpose(inverse(M));
Output.Position = Position; Output.Position = Position;
Output.TextureCoordinate = TextureCoords; Output.TextureCoordinate = TextureCoords;
Output.Normal = vec3(TIM * vec4(Normal, 0.0)); Output.Normal = vec3(M * vec4(Normal, 0.0));
Output.Tangent = vec3(TIM * vec4(Tangent, 0.0)); Output.Tangent = vec3(M * vec4(Tangent, 0.0));
Output.BiTangent = vec3(TIM * vec4(BiTangent, 0.0)); Output.BiTangent = vec3(M * vec4(BiTangent, 0.0));
Output.ExplosionColor = vec4(1.0); Output.ExplosionColor = vec4(1.0);
Output.ExplosionPercentageElapsed = 0.0; Output.ExplosionPercentageElapsed = 0.0;
} }
+25 -16
View File
@@ -1,12 +1,15 @@
#version 430 #version 430
#define MIP_MAPS_LEVELS (3)
#define MAX_PIXEL_BEFOR_LOWER_MIP_LEVEL (3)
//Number of samples per pixel //Number of samples per pixel
uniform int uNumOfSamples; uniform int uNumOfSamples;
//#define NUM_SAMPLES (11) //#define uNumOfSamples (11)
//Number of turns around the cirle //Number of turns around the cirle
uniform int uNumOfTurns; uniform int uNumOfTurns;
//#define NUM_TURNS (7) //#define uNumOfTurns (7)
layout (binding = 0) uniform sampler2D ViewSpaceZ; layout (binding = 0) uniform sampler2D ViewSpaceZ;
@@ -42,42 +45,41 @@ vec3 getVSFaceNormal(vec3 ViewSpacePosition) {
vec3 getSampleViewSpacePos(ivec2 ScreenSpaceCoord, int SampleIndex, float RotationAngle, float ScreenSpaceSampleRadius){ vec3 getSampleViewSpacePos(ivec2 ScreenSpaceCoord, int SampleIndex, float RotationAngle, float ScreenSpaceSampleRadius){
// Pure Magic... // SampleIndex + 0.5f so that we alpha != 0, since if alpha = 0 then screenSpaceSampleTexel will be the same texel as origin.
float alpha = float(SampleIndex) * (1.0 / uNumOfSamples); float alpha = float(SampleIndex + 0.5f) * (1.0f / uNumOfSamples);
// Angle to where to sample // Angle to where to sample
float angle = alpha * (uNumOfTurns * 6.28) + RotationAngle; float angle = alpha * (uNumOfTurns * 6.28f) + RotationAngle;
//Lenght to were to sample //Lenght to were to sample
ScreenSpaceSampleRadius = ScreenSpaceSampleRadius * alpha; ScreenSpaceSampleRadius = ScreenSpaceSampleRadius * alpha;
vec2 screenSpaceSampleOffsetVecor = vec2(cos(angle), sin(angle)); vec2 screenSpaceSampleOffsetVecor = vec2(cos(angle), sin(angle));
//int mipmapLevel = clamp(int(floor(log2(-ScreenSpaceSampleRadius))) - MAX_PIXEL_BEFOR_LOWER_MIP_LEVEL, 0, MIP_MAPS_LEVELS);
// Get texel coordinate on where to sample by going screenSpaceSampleOffsetVecor direction in ScreenSpaceSampleRadius units from ScreenSpaceCoord (the point being shaded); // Get texel coordinate on where to sample by going screenSpaceSampleOffsetVecor direction in ScreenSpaceSampleRadius units from ScreenSpaceCoord (the point being shaded);
ivec2 screenSpaceSampleTexel = ivec2(ScreenSpaceSampleRadius * screenSpaceSampleOffsetVecor) + ScreenSpaceCoord; ivec2 screenSpaceSampleTexel = (ivec2(ScreenSpaceSampleRadius * screenSpaceSampleOffsetVecor) + ScreenSpaceCoord);// >> mipmapLevel;
return getVSPosition(screenSpaceSampleTexel); return getVSPosition(screenSpaceSampleTexel);
} }
float sampleAO(ivec2 ScreenSpaceCoord, vec3 Origin, vec3 OriginNormal, float ScreenSpaceSampleRadius, int SampleIndex, float RotationAngle, float Radius) { float sampleAO(ivec2 ScreenSpaceCoord, vec3 Origin, vec3 OriginNormal, float ScreenSpaceSampleRadius, int SampleIndex, float RotationAngle, float Radius, float Radius2) {
float radius2 = Radius * Radius;
vec3 sampleViewSpacePosition = getSampleViewSpacePos(ScreenSpaceCoord, SampleIndex, RotationAngle, ScreenSpaceSampleRadius); vec3 sampleViewSpacePosition = getSampleViewSpacePos(ScreenSpaceCoord, SampleIndex, RotationAngle, ScreenSpaceSampleRadius);
vec3 sampleVector = Origin - sampleViewSpacePosition; vec3 sampleVector = Origin - sampleViewSpacePosition;
// vv = sampleVectorLenght ^ 2 // vv = sampleVectorLenght ^ 2
float vv = dot(sampleVector, sampleVector); float vv = dot(sampleVector, sampleVector);
// vn = angle between sampleVector and Normal // vn = angle between sampleVector and Normal
float vn = dot(sampleVector, OriginNormal); float vn = dot(sampleVector, OriginNormal);
const float epsilon = 0.0001f; const float epsilon = 0.01f;
// vv < radius2 if the vector is shorter then the radius; // vv < radius2 if the vector is shorter then the radius;
// vn - bias, offset the angle to reduse self occlusion. // vn - bias, offset the angle to reduse self occlusion.
// epsilon is here to make divison by 0 impossible. // epsilon is here to make divison by 0 impossible.
return float(vv < radius2) * max((vn - uBias) / (epsilon + vv), 0.0); return float(vv < Radius2) * max((vn - uBias) / (epsilon + vv), 0.0);
//float f = max(radius2 - vv, 0.0); //float f = max(radius2 - vv, 0.0);
//return f * f * f * max((vn - uBias) / (epsilon + vv), 0.0); //return f * f * f * max((vn - uBias) / (epsilon + vv), 0.0);
} }
@@ -86,9 +88,11 @@ float sampleAO(ivec2 ScreenSpaceCoord, vec3 Origin, vec3 OriginNormal, float Scr
void main() { void main() {
ivec2 originScreenCoord = ivec2(gl_FragCoord.xy); ivec2 originScreenCoord = ivec2(gl_FragCoord.xy);
// We always get the Orginin from the level 0 of the mipmaps
vec3 origin = getVSPosition(originScreenCoord); vec3 origin = getVSPosition(originScreenCoord);
float radius; float radius;
if(origin.z < uRadius){ if(origin.z < uRadius){
radius = origin.z; radius = origin.z;
} else { } else {
@@ -96,19 +100,24 @@ void main() {
} }
float radius2 = radius * radius;
vec3 originNormal = getVSFaceNormal(origin); vec3 originNormal = getVSFaceNormal(origin);
//screenSpaceSampleRadius is in pixels
float screenSpaceSampleRadius = -uProjScale * radius / origin.z; float screenSpaceSampleRadius = -uProjScale * radius / origin.z;
//screenSpaceSampleRadius = clamp(screenSpaceSampleRadius, 0.0f, -uProjScale * radius);
float rotationAngleOffset = 30 * originScreenCoord.x ^ originScreenCoord.y + 10 * originScreenCoord.x * originScreenCoord.y; float rotationAngleOffset = 30 * originScreenCoord.x ^ originScreenCoord.y + 10 * originScreenCoord.x * originScreenCoord.y;
float sum = 0.0; float sum = 0.0f;
for (int i = 0; i < uNumOfSamples; i++) { for(int i = 0; i < uNumOfSamples; i++) {
sum += sampleAO(originScreenCoord, origin, originNormal, screenSpaceSampleRadius, i, rotationAngleOffset, radius); sum += sampleAO(originScreenCoord, origin, originNormal, screenSpaceSampleRadius, i, rotationAngleOffset, radius, radius2);
} }
//float A = max(0.0, 1.0 - sum * (2.0f / uNumOfSamples)); //float A = max(0.0, 1.0 - sum * (2.0f / uNumOfSamples));
float A = 1.0 - sum * (2.0f * uIntensityScale / float(uNumOfSamples)); float A = 1.0f - sum * (2.0f * uIntensityScale / float(uNumOfSamples));
AO = clamp(pow(A, uContrast), 0.0f, 1.0f); AO = clamp(pow(A, uContrast), 0.0f, 1.0f);
//AO = screenSpaceSampleRadius;
//AO = vec4(originNormal, 1.0f); //AO = vec4(originNormal, 1.0f);
} }
+123
View File
@@ -0,0 +1,123 @@
#version 430
#define MIP_MAPS_LEVELS (5)
#define LOWER_MIP_LEVEL (2)
//Number of samples per pixel
uniform int uNumOfSamples;
//#define uNumOfSamples (11)
//Number of turns around the cirle
uniform int uNumOfTurns;
//#define uNumOfTurns (7)
layout (binding = 0) uniform sampler2D ViewSpaceZ;
uniform vec4 uProjInfo;
uniform float uProjScale;
//#define ProjScale 500
uniform float uRadius;
//#define Radius 1.0f
uniform float uBias;
//#define Bias 0.012f
uniform float uContrast;
//#define IntensityDivR6 1
uniform float uIntensityScale;
out float AO;
vec3 getVSPosition(ivec2 ScreenSpaceCoord, int mipmaplevel) {
float z = texelFetch(ViewSpaceZ, ScreenSpaceCoord, mipmaplevel).r;
//Get the xy view space coordinates and add the z value from ViewSpaceZ buffer.
return vec3((uProjInfo[0] + (ScreenSpaceCoord.x * uProjInfo[1])) * z, (uProjInfo[2] + (ScreenSpaceCoord.y * uProjInfo[3])) * z, z);
}
vec3 getVSFaceNormal(vec3 ViewSpacePosition) {
// Get tangets vector for the plane and ViewSpacePositin... don't ask how this functions works. It's pure magic.
// They do this and it just works... I would guess that they approximate the function of a plane from pixels close to the pixel were on now.
return normalize(cross(dFdx(ViewSpacePosition), dFdy(ViewSpacePosition)));
}
vec3 getSampleViewSpacePos(ivec2 ScreenSpaceCoord, int SampleIndex, float RotationAngle, float ScreenSpaceSampleRadius){
// SampleIndex + 0.5f so that we alpha != 0, since if alpha = 0 then screenSpaceSampleTexel will be the same texel as origin.
float alpha = float(SampleIndex + 0.5f) * (1.0f / uNumOfSamples);
// Angle to where to sample
float angle = alpha * (uNumOfTurns * 6.28f) + RotationAngle;
//Lenght to were to sample
ScreenSpaceSampleRadius = ScreenSpaceSampleRadius * alpha;
vec2 screenSpaceSampleOffsetVecor = vec2(cos(angle), sin(angle));
int mipmapLevel = clamp(int(floor(log2(-ScreenSpaceSampleRadius))) - LOWER_MIP_LEVEL, 0, MIP_MAPS_LEVELS);
// Get texel coordinate on where to sample by going screenSpaceSampleOffsetVecor direction in ScreenSpaceSampleRadius units from ScreenSpaceCoord (the point being shaded);
ivec2 screenSpaceSampleTexel = (ivec2(ScreenSpaceSampleRadius * screenSpaceSampleOffsetVecor) + ScreenSpaceCoord) >> mipmapLevel;
return getVSPosition(screenSpaceSampleTexel, mipmapLevel);
}
float sampleAO(ivec2 ScreenSpaceCoord, vec3 Origin, vec3 OriginNormal, float ScreenSpaceSampleRadius, int SampleIndex, float RotationAngle, float Radius, float Radius2) {
vec3 sampleViewSpacePosition = getSampleViewSpacePos(ScreenSpaceCoord, SampleIndex, RotationAngle, ScreenSpaceSampleRadius);
vec3 sampleVector = Origin - sampleViewSpacePosition;
// vv = sampleVectorLenght ^ 2
float vv = dot(sampleVector, sampleVector);
// vn = angle between sampleVector and Normal
float vn = dot(sampleVector, OriginNormal);
const float epsilon = 0.01f;
// vv < radius2 if the vector is shorter then the radius;
// vn - bias, offset the angle to reduse self occlusion.
// epsilon is here to make divison by 0 impossible.
return float(vv < Radius2) * max((vn - uBias) / (epsilon + vv), 0.0);
}
void main() {
ivec2 originScreenCoord = ivec2(gl_FragCoord.xy);
// We always get the Orginin from the level 0 of the mipmaps
vec3 origin = getVSPosition(originScreenCoord, 0);
float radius;
if(origin.z < uRadius){
radius = origin.z;
} else {
radius = uRadius;
}
float radius2 = radius * radius;
vec3 originNormal = getVSFaceNormal(origin);
//AO = originNormal;
//return;
//screenSpaceSampleRadius is in pixels
float screenSpaceSampleRadius = -uProjScale * radius / origin.z;
//screenSpaceSampleRadius = clamp(screenSpaceSampleRadius, 0.0f, pow(2, MIP_MAPS_LEVELS * LOWER_MIP_LEVEL + 1));
//AO = clamp(int(floor(log2(screenSpaceSampleRadius))) - LOWER_MIP_LEVEL, 0, MIP_MAPS_LEVELS);
//return;
float rotationAngleOffset = 30 * originScreenCoord.x ^ originScreenCoord.y + 10 * originScreenCoord.x * originScreenCoord.y;
float sum = 0.0f;
for(int i = 0; i < uNumOfSamples; i++) {
sum += sampleAO(originScreenCoord, origin, originNormal, screenSpaceSampleRadius, i, rotationAngleOffset, radius, radius2);
}
//float A = max(0.0, 1.0 - sum * (2.0f / uNumOfSamples));
float A = 1.0f - sum * (2.0f * uIntensityScale / float(uNumOfSamples));
AO = clamp(pow(A, uContrast), 0.0f, 1.0f);
//AO = vec4(originNormal, 1.0f);
}
+43 -45
View File
@@ -16,51 +16,51 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c
EntityAABB& boxA = *boundingBox; EntityAABB& boxA = *boundingBox;
bool everHitTheGround = false; bool everHitTheGround = false;
auto prevPosIt = m_PrevPositions.find(entity); glm::vec3 size = boxA.Size();
if (prevPosIt != m_PrevPositions.end()) { float diameter = std::min(size.x, size.z);
glm::vec3 size = boxA.Size(); glm::vec3 prevOrigin = (glm::vec3)cPhysics["PrevOrigin"];
float diameter = std::min(size.x, size.z); glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin;
glm::vec3 prevOrigin = prevPosIt->second; float rayLength = glm::length(toCurrentPos) + 0.5f*diameter;
glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; //If the entity has moved farther than the size of its box, we need to handle it specially.
float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; bool traceCollision = rayLength > diameter;
//If the entity has moved farther than the size of its box, we need to handle it specially. //hack solution: If prevOrigin is less than -9000 in all dimensions,
if (rayLength > diameter) { //then it means it is not set, i.e. this is the first collision check for the entity.
Ray ray(prevOrigin, toCurrentPos); if (traceCollision && glm::any(glm::greaterThan((glm::vec3)cPhysics["PrevOrigin"], glm::vec3(-9000.f)))) {
m_OctreeResult.clear(); Ray ray(prevOrigin, toCurrentPos);
m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); m_OctreeResult.clear();
for (auto& boxB : m_OctreeResult) { m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult);
if (boxA.Entity == boxB.Entity) { for (auto& boxB : m_OctreeResult) {
if (boxA.Entity == boxB.Entity) {
continue;
}
bool hit;
float dist;
if (boxB.Entity.HasComponent("Model")) {
RawModel* model;
std::string res = (std::string)boxB.Entity["Model"]["Resource"];
try {
model = ResourceManager::Load<RawModel, true>(res);
} catch (const std::exception&) {
continue; continue;
} }
bool hit; float u, v;
float dist; hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v);
if (boxB.Entity.HasComponent("Model")) { } else {
RawModel* model; hit = Collision::RayVsAABB(ray, boxB, dist);
std::string res = (std::string)boxB.Entity["Model"]["Resource"]; }
try { if (hit && dist < rayLength) {
model = ResourceManager::Load<RawModel, true>(res); //Set the entity to where it was colliding, minus the maximum box size.
} catch (const std::exception&) { //TODO: Perhaps this should be done slightly more properly.
continue; glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction();
} glm::vec3 resolve = newOriginPos - boxA.Origin();
float u, v; (glm::vec3&)cTransform["Position"] += resolve;
hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v); boxA = *Collision::EntityAbsoluteAABB(entity);
} else { if (resolve.y > 0) {
hit = Collision::RayVsAABB(ray, boxB, dist); everHitTheGround = true;
} (bool)cPhysics["IsOnGround"] = true;
if (hit && dist < rayLength) { ((glm::vec3&)cPhysics["Velocity"]).y = 0.f;
//Set the entity to where it was colliding, minus the maximum box size.
//TODO: Perhaps this should be done slightly more properly.
glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction();
glm::vec3 resolve = newOriginPos - boxA.Origin();
(glm::vec3&)cTransform["Position"] += resolve;
boxA = *Collision::EntityAbsoluteAABB(entity);
if (resolve.y > 0) {
everHitTheGround = true;
(bool)cPhysics["IsOnGround"] = true;
((glm::vec3&)cPhysics["Velocity"]).y = 0.f;
}
break;
} }
break;
} }
} }
} }
@@ -90,7 +90,6 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c
float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"];
if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) {
(glm::vec3&)cTransform["Position"] += resolutionVector; (glm::vec3&)cTransform["Position"] += resolutionVector;
boxA = *Collision::EntityAbsoluteAABB(entity);
cPhysics["Velocity"] = inOutVelocity; cPhysics["Velocity"] = inOutVelocity;
if (isOnGround) { if (isOnGround) {
everHitTheGround = true; everHitTheGround = true;
@@ -100,7 +99,6 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c
} else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) {
//Enter here if boxB has no Model. //Enter here if boxB has no Model.
(glm::vec3&)cTransform["Position"] += resolutionVector; (glm::vec3&)cTransform["Position"] += resolutionVector;
boxA = *Collision::EntityAbsoluteAABB(entity);
if (resolutionVector.y > 0) { if (resolutionVector.y > 0) {
everHitTheGround = true; everHitTheGround = true;
(bool)cPhysics["IsOnGround"] = true; (bool)cPhysics["IsOnGround"] = true;
@@ -114,5 +112,5 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c
(bool)cPhysics["IsOnGround"] = false; (bool)cPhysics["IsOnGround"] = false;
} }
m_PrevPositions[entity] = boxA.Origin(); (glm::vec3&)cPhysics["PrevOrigin"] = boxA.Origin();
} }
+1 -36
View File
@@ -51,17 +51,6 @@ EntityWrapper EntityWrapper::FirstParentWithComponent(const std::string& compone
return EntityWrapper::Invalid; return EntityWrapper::Invalid;
} }
EntityWrapper EntityWrapper::Clone(EntityWrapper parent /*= Invalid*/)
{
if (!Valid()) {
return EntityWrapper::Invalid;
}
EntityWrapper clone = cloneRecursive(*this, EntityWrapper::Invalid);
this->World->SetParent(clone.ID, parent.ID);
return clone;
}
bool EntityWrapper::IsChildOf(EntityWrapper potentialParent) bool EntityWrapper::IsChildOf(EntityWrapper potentialParent)
{ {
EntityWrapper entity = *this; EntityWrapper entity = *this;
@@ -122,7 +111,7 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name,
return EntityWrapper::Invalid; return EntityWrapper::Invalid;
} }
auto itPair = this->World->GetDirectChildren(parent); auto itPair = this->World->GetChildren(parent);
if (itPair.first == itPair.second) { if (itPair.first == itPair.second) {
return EntityWrapper::Invalid; return EntityWrapper::Invalid;
} }
@@ -142,27 +131,3 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name,
return EntityWrapper::Invalid; return EntityWrapper::Invalid;
} }
EntityWrapper EntityWrapper::cloneRecursive(EntityWrapper entity, EntityWrapper parent)
{
EntityWrapper clone = EntityWrapper(entity.World, entity.World->CreateEntity(parent.ID));
entity.World->SetName(clone.ID, entity.Name());
// Clone components
for (auto& kv : entity.World->GetComponentPools()) {
if (kv.second->KnowsEntity(entity.ID)) {
ComponentWrapper c1 = kv.second->GetByEntity(entity.ID);
ComponentWrapper c2 = entity.World->AttachComponent(clone.ID, kv.first);
c1.Copy(c2);
}
}
// Clone children
auto children = entity.World->GetDirectChildren(entity.ID);
for (auto it = children.first; it != children.second; ++it) {
EntityWrapper child(entity.World, it->second);
cloneRecursive(child, clone);
}
return clone;
}
+1 -1
View File
@@ -127,7 +127,7 @@ void World::SetParent(EntityID entity, EntityID parent)
m_EntityChildren.insert(std::make_pair(parent, entity)); m_EntityChildren.insert(std::make_pair(parent, entity));
} }
const std::pair<std::unordered_multimap<EntityID, EntityID>::const_iterator, std::unordered_multimap<EntityID, EntityID>::const_iterator> World::GetDirectChildren(EntityID entity) const std::pair<std::unordered_multimap<EntityID, EntityID>::const_iterator, std::unordered_multimap<EntityID, EntityID>::const_iterator> World::GetChildren(EntityID entity)
{ {
return m_EntityChildren.equal_range(entity); return m_EntityChildren.equal_range(entity);
} }
-18
View File
@@ -580,11 +580,6 @@ void EditorGUI::createWidgetToolButton(WidgetMode mode)
bool EditorGUI::OnKeyDown(const Events::KeyDown& e) bool EditorGUI::OnKeyDown(const Events::KeyDown& e)
{ {
ImGuiIO& io = ImGui::GetIO();
if (io.WantCaptureKeyboard) {
return false;
}
if (e.ModCtrl && e.KeyCode == GLFW_KEY_S) { if (e.ModCtrl && e.KeyCode == GLFW_KEY_S) {
if (m_CurrentSelection.Valid()) { if (m_CurrentSelection.Valid()) {
EntityWrapper baseParent = m_CurrentSelection; EntityWrapper baseParent = m_CurrentSelection;
@@ -603,19 +598,6 @@ bool EditorGUI::OnKeyDown(const Events::KeyDown& e)
entityImport(m_World); entityImport(m_World);
} }
if (e.ModCtrl && e.KeyCode == GLFW_KEY_C) {
m_CopyTarget = m_CurrentSelection;
}
if (e.ModCtrl && e.KeyCode == GLFW_KEY_V) {
if (m_OnEntityPaste != nullptr) {
EntityWrapper copy = m_OnEntityPaste(m_CopyTarget, m_CurrentSelection);
if (copy != EntityWrapper::Invalid) {
SelectEntity(copy);
}
}
}
if (e.KeyCode == GLFW_KEY_DELETE) { if (e.KeyCode == GLFW_KEY_DELETE) {
if (m_CurrentSelection.Valid()) { if (m_CurrentSelection.Valid()) {
entityDelete(m_CurrentSelection); entityDelete(m_CurrentSelection);
-6
View File
@@ -28,7 +28,6 @@ EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame
m_EditorGUI->SetEntityDeleteCallback(std::bind(&EditorSystem::OnEntityDelete, this, std::placeholders::_1)); m_EditorGUI->SetEntityDeleteCallback(std::bind(&EditorSystem::OnEntityDelete, this, std::placeholders::_1));
m_EditorGUI->SetEntityChangeParentCallback(std::bind(&EditorSystem::OnEntityChangeParent, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetEntityChangeParentCallback(std::bind(&EditorSystem::OnEntityChangeParent, this, std::placeholders::_1, std::placeholders::_2));
m_EditorGUI->SetEntityChangeNameCallback(std::bind(&EditorSystem::OnEntityChangeName, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetEntityChangeNameCallback(std::bind(&EditorSystem::OnEntityChangeName, this, std::placeholders::_1, std::placeholders::_2));
m_EditorGUI->SetEntityPasteCallback(std::bind(&EditorSystem::OnEntityPaste, this, std::placeholders::_1, std::placeholders::_2));
m_EditorGUI->SetComponentAttachCallback(std::bind(&EditorSystem::OnComponentAttach, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentAttachCallback(std::bind(&EditorSystem::OnComponentAttach, this, std::placeholders::_1, std::placeholders::_2));
m_EditorGUI->SetComponentDeleteCallback(std::bind(&EditorSystem::OnComponentDelete, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentDeleteCallback(std::bind(&EditorSystem::OnComponentDelete, this, std::placeholders::_1, std::placeholders::_2));
m_EditorGUI->SetWidgetModeCallback(std::bind(&EditorSystem::setWidgetMode, this, std::placeholders::_1)); m_EditorGUI->SetWidgetModeCallback(std::bind(&EditorSystem::setWidgetMode, this, std::placeholders::_1));
@@ -161,11 +160,6 @@ void EditorSystem::OnEntityChangeName(EntityWrapper entity, const std::string& n
} }
} }
EntityWrapper EditorSystem::OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent)
{
return entityToCopy.Clone(parent);
}
void EditorSystem::OnComponentAttach(EntityWrapper entity, const std::string& componentType) void EditorSystem::OnComponentAttach(EntityWrapper entity, const std::string& componentType)
{ {
if (entity.Valid()) { if (entity.Valid()) {
+13 -121
View File
@@ -1,7 +1,7 @@
#include "Network/Client.h" #include "Network/Client.h"
using namespace boost::asio::ip; using namespace boost::asio::ip;
Client::Client(World* world, EventBroker* eventBroker) Client::Client(World* world, EventBroker* eventBroker)
: Network(world, eventBroker) : Network(world, eventBroker)
{ {
// Asumes root node is EntityID_Invalid // Asumes root node is EntityID_Invalid
@@ -13,8 +13,6 @@ Client::Client(World* world, EventBroker* eventBroker)
m_PlayerName = config->Get<std::string>("Networking.Name", "Raptorcopter"); m_PlayerName = config->Get<std::string>("Networking.Name", "Raptorcopter");
m_SendInputIntervalMs = config->Get<int>("Networking.SendInputIntervalMs", 33); m_SendInputIntervalMs = config->Get<int>("Networking.SendInputIntervalMs", 33);
LOG_INFO("Client initialized"); LOG_INFO("Client initialized");
m_ServerlistRequest.Connect(m_PlayerName, "192.168.1.255", 32554);
} }
Client::Client(World* world, EventBroker* eventBroker, std::unique_ptr<SnapshotFilter> snapshotFilter) Client::Client(World* world, EventBroker* eventBroker, std::unique_ptr<SnapshotFilter> snapshotFilter)
@@ -32,8 +30,6 @@ void Client::Connect(std::string address, int port)
EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand);
EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage);
EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned);
EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &Client::OnDoubleJump);
EVENT_SUBSCRIBE_MEMBER(m_ESearchForServers, &Client::OnSearchForServers);
auto config = ResourceManager::Load<ConfigFile>("Config.ini"); auto config = ResourceManager::Load<ConfigFile>("Config.ini");
m_Address = address; m_Address = address;
if (address.empty()) { if (address.empty()) {
@@ -70,21 +66,6 @@ void Client::Update()
} }
while (m_ServerlistRequest.IsSocketAvailable()) {
Packet packet(MessageType::Invalid);
m_ServerlistRequest.Receive(packet);
if (packet.GetMessageType() == MessageType::ServerlistRequest) {
parseServerlist(packet);
}
}
if (m_SearchingForServers) {
if (m_SearchingTime < (1000* (std::clock() - m_StartSearchTime) / (double)CLOCKS_PER_SEC)) {
m_SearchingForServers = false;
displayServerlist();
}
}
if (m_IsConnected) { if (m_IsConnected) {
// Don't send 1 input in 1 packet, bunch em up. // Don't send 1 input in 1 packet, bunch em up.
if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) { if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) {
@@ -141,9 +122,6 @@ void Client::parseMessageType(Packet& packet)
case MessageType::OnPlayerDamage: case MessageType::OnPlayerDamage:
parsePlayerDamage(packet); parsePlayerDamage(packet);
break; break;
case MessageType::OnDoubleJump:
parseDoubleJump(packet);
break;
default: default:
break; break;
} }
@@ -195,22 +173,6 @@ void Client::parsePing()
m_Reliable.Send(packet); m_Reliable.Send(packet);
} }
void Client::parseServerlist(Packet& packet)
{
// Pop size, message type, and ID
packet.ReadPrimitive<int>();
packet.ReadPrimitive<int>();
packet.ReadPrimitive<int>();
std::string address = packet.ReadString();
int port = packet.ReadPrimitive<int>();
std::string serverName = packet.ReadString();
int playersConnected = packet.ReadPrimitive<int>();
//TODO: This should not happen when a client is connected to a server
m_Serverlist.push_back({ address, port, serverName, playersConnected });
}
void Client::parseKick() void Client::parseKick()
{ {
LOG_WARNING("You have been kicked from the server."); LOG_WARNING("You have been kicked from the server.");
@@ -228,12 +190,12 @@ void Client::parseSpawnEvents()
} }
e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Player.ID)); e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Player.ID));
//e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID)); //e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID));
e.PlayerID = -1; e.PlayerID = -1;
e.PlayerName = m_PlayerSpawnEvents.at(i).PlayerName; e.PlayerName = m_PlayerSpawnEvents.at(i).PlayerName;
m_EventBroker->Publish(e); m_EventBroker->Publish(e);
} }
m_PlayerSpawnEvents = tempSpawn; m_PlayerSpawnEvents = tempSpawn;
// m_PlayerSpawnEvents.clear(); // m_PlayerSpawnEvents.clear();
} }
void Client::parsePlayersSpawned(Packet& packet) void Client::parsePlayersSpawned(Packet& packet)
@@ -261,14 +223,8 @@ void Client::parseEntityDeletion(Packet & packet)
if (m_ServerIDToClientID.find(entityToDelete) != m_ServerIDToClientID.end()) { if (m_ServerIDToClientID.find(entityToDelete) != m_ServerIDToClientID.end()) {
EntityID localEntity = m_ServerIDToClientID.at(entityToDelete); EntityID localEntity = m_ServerIDToClientID.at(entityToDelete);
if (m_World->ValidEntity(localEntity)) { if (m_World->ValidEntity(localEntity)) {
if (m_World->HasComponent(localEntity,"Player")) { m_World->DeleteEntity(localEntity);
Events::PlayerDeath e; deleteFromServerClientMaps(entityToDelete, localEntity);
e.Player = EntityWrapper(m_World, localEntity);
m_EventBroker->Publish(e);
} else {
m_World->DeleteEntity(localEntity);
deleteFromServerClientMaps(entityToDelete, localEntity);
}
} }
} }
} }
@@ -282,20 +238,6 @@ void Client::parseComponentDeletion(Packet & packet)
} }
} }
void Client::parseDoubleJump(Packet & packet)
{
EntityID serverID = packet.ReadPrimitive<EntityID>();
if (!serverClientMapsHasEntity(serverID)) {
return;
}
Events::DoubleJump e;
e.entityID = m_ServerIDToClientID.at(serverID);
// If player is local player do not publish to prevent infinite feedback loop
if (e.entityID != m_LocalPlayer.ID) {
m_EventBroker->Publish(e);
}
}
void Client::updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID) void Client::updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID)
{ {
for (auto field : componentInfo.FieldsInOrder) { for (auto field : componentInfo.FieldsInOrder) {
@@ -370,20 +312,19 @@ void Client::parseSnapshot(Packet& packet)
if (serverClientMapsHasEntity(serverEntityID)) { if (serverClientMapsHasEntity(serverEntityID)) {
EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID);
EntityWrapper localEntity(m_World, localEntityID); EntityWrapper localEntity(m_World, localEntityID);
// Update entity // Update entity
if (m_World->HasComponent(localEntityID, componentType)) { if (m_World->HasComponent(localEntityID, componentType)) {
// TODO Fix memory leak here
SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo);
bool shouldApply = true; bool shouldApply = true;
// Apply potential filter function // Apply potential filter function
if (m_SnapshotFilter != nullptr) { if (m_SnapshotFilter != nullptr) {
shouldApply = m_SnapshotFilter->FilterComponent(localEntity, newComponent); shouldApply = m_SnapshotFilter->FilterComponent(localEntity, newComponent);
} }
if (shouldApply) { if (shouldApply) {
ComponentWrapper currentComponent = m_World->GetComponent(localEntityID, componentType); ComponentWrapper currentComponent = m_World->GetComponent(localEntityID, componentType);
memcpy(currentComponent.Data, newComponent.Data, componentInfo.Stride); memcpy(currentComponent.Data, newComponent.Data, componentInfo.Stride);
} }
//if (localEntity != m_LocalPlayer && !localEntity.IsChildOf(m_LocalPlayer)) { //if (localEntity != m_LocalPlayer && !localEntity.IsChildOf(m_LocalPlayer)) {
// updateFields(packet, componentInfo, localEntityID); // updateFields(packet, componentInfo, localEntityID);
//} else { //} else {
@@ -400,11 +341,7 @@ void Client::parseSnapshot(Packet& packet)
if (serverParentID == EntityID_Invalid) { if (serverParentID == EntityID_Invalid) {
newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); newLocalEntityID = m_World->CreateEntity(EntityID_Invalid);
} else { } else {
if (serverClientMapsHasEntity(serverParentID)) { newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID));
newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID));
} else {
newLocalEntityID = m_World->CreateEntity(EntityID_Invalid);
}
} }
m_World->SetName(newLocalEntityID, serverEntityName); m_World->SetName(newLocalEntityID, serverEntityName);
insertIntoServerClientMaps(serverEntityID, newLocalEntityID); insertIntoServerClientMaps(serverEntityID, newLocalEntityID);
@@ -414,11 +351,9 @@ void Client::parseSnapshot(Packet& packet)
} }
// Parent logic // Parent logic
// This should be enough beacause we know that the entities arives in pre-order (there will always be a parent) // This should be enough beacause we know that the entities arives in pre-order (there will always be a parent)
if (serverParentID != EntityID_Invalid && serverClientMapsHasEntity(serverParentID)) { if (serverParentID != EntityID_Invalid) {
EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID);
if (m_World->GetParent(localEntityID) != m_ServerIDToClientID.at(serverParentID)) { m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID));
m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID));
}
} }
} }
parseSpawnEvents(); parseSpawnEvents();
@@ -436,12 +371,6 @@ void Client::disconnect()
bool Client::OnInputCommand(const Events::InputCommand & e) bool Client::OnInputCommand(const Events::InputCommand & e)
{ {
// TEMP
if (e.Command == "SearchForServers" && e.Value > 0) {
Events::SearchForServers e;
m_EventBroker->Publish(e);
}
if (e.PlayerID != -1) { if (e.PlayerID != -1) {
return false; return false;
} }
@@ -486,11 +415,6 @@ bool Client::OnPlayerDamage(const Events::PlayerDamage & e)
if (e.Inflictor != m_LocalPlayer) { if (e.Inflictor != m_LocalPlayer) {
return false; return false;
} }
// Could this happen?
//if (!clientServerMapsHasEntity(e.Inflictor.ID)
// || !clientServerMapsHasEntity(e.Victim.ID)) {
// return;
//}
Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); Packet packet(MessageType::OnPlayerDamage, m_SendPacketID);
packet.WritePrimitive(m_ClientIDToServerID.at(e.Inflictor.ID)); packet.WritePrimitive(m_ClientIDToServerID.at(e.Inflictor.ID));
@@ -509,23 +433,12 @@ bool Client::OnPlayerSpawned(const Events::PlayerSpawned& e)
return true; return true;
} }
bool Client::OnSearchForServers(const Events::SearchForServers& e)
{
m_SearchingForServers = true;
m_StartSearchTime = std::clock();
m_Serverlist.clear();
LOG_INFO("Searching for LAN servers...\n");
Packet packet(MessageType::ServerlistRequest);
m_ServerlistRequest.Broadcast(packet, 13); // TODO: Config
return true;
}
void Client::parsePlayerDamage(Packet& packet) void Client::parsePlayerDamage(Packet& packet)
{ {
Events::PlayerDamage e; Events::PlayerDamage e;
PlayerID victimID = packet.ReadPrimitive<EntityID>(); PlayerID victimID = packet.ReadPrimitive<EntityID>();
PlayerID inflictorID = packet.ReadPrimitive<EntityID>(); PlayerID inflictorID = packet.ReadPrimitive<EntityID>();
if (!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)) { if(!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)){
return; return;
} }
e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID));
@@ -537,17 +450,6 @@ void Client::parsePlayerDamage(Packet& packet)
} }
} }
bool Client::OnDoubleJump(Events::DoubleJump & e)
{
if (!clientServerMapsHasEntity(e.entityID) || e.entityID != m_LocalPlayer.ID) {
return false;
}
Packet packet(MessageType::OnDoubleJump);
packet.WritePrimitive(m_ClientIDToServerID.at(e.entityID));
m_Reliable.Send(packet);
return true;
}
void Client::sendLocalPlayerTransform() void Client::sendLocalPlayerTransform()
{ {
if (!m_LocalPlayer.Valid()) { if (!m_LocalPlayer.Valid()) {
@@ -565,7 +467,7 @@ void Client::sendLocalPlayerTransform()
packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.x);
packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.y);
packet.WritePrimitive(orientation.z); packet.WritePrimitive(orientation.z);
bool hasAssaultWeapon = m_LocalPlayer.HasComponent("AssaultWeapon"); bool hasAssaultWeapon = m_LocalPlayer.HasComponent("AssaultWeapon");
packet.WritePrimitive(hasAssaultWeapon); packet.WritePrimitive(hasAssaultWeapon);
if (hasAssaultWeapon) { if (hasAssaultWeapon) {
@@ -573,7 +475,7 @@ void Client::sendLocalPlayerTransform()
packet.WritePrimitive((int)cAssaultWeapon["MagazineAmmo"]); packet.WritePrimitive((int)cAssaultWeapon["MagazineAmmo"]);
packet.WritePrimitive((int)cAssaultWeapon["Ammo"]); packet.WritePrimitive((int)cAssaultWeapon["Ammo"]);
} }
m_Unreliable.Send(packet); m_Unreliable.Send(packet);
} }
@@ -626,16 +528,6 @@ void Client::becomePlayer()
m_Reliable.Send(packet); m_Reliable.Send(packet);
} }
void Client::displayServerlist()
{
LOG_INFO("This is a serverlist:\n");
for (int i = 0; i < m_Serverlist.size(); i++) {
ServerInfo si = m_Serverlist[i];
LOG_INFO("%s:%i\t%s\t%i\n", si.Address.c_str(), si.Port, si.Name.c_str(), si.PlayersConnected);
}
}
bool Client::clientServerMapsHasEntity(EntityID clientEntityID) bool Client::clientServerMapsHasEntity(EntityID clientEntityID)
{ {
if (m_ClientIDToServerID.find(clientEntityID) != m_ClientIDToServerID.end()) { if (m_ClientIDToServerID.find(clientEntityID) != m_ClientIDToServerID.end()) {
+10
View File
@@ -0,0 +1,10 @@
#include "Network/HybridClient.h"
HybridClient::HybridClient()
{
}
HybridClient::~HybridClient()
{
}
+9
View File
@@ -0,0 +1,9 @@
#include "Network/HybridServer.h"
HybridServer::HybridServer()
{
}
HybridServer::~HybridServer()
{
}
-11
View File
@@ -1,11 +0,0 @@
#include "Network/NetworkClient.h"
NetworkClient::NetworkClient()
{
m_ReadBuffer = new char[m_BufferSize];
}
NetworkClient::~NetworkClient()
{
delete[] m_ReadBuffer;
}
-11
View File
@@ -1,11 +0,0 @@
#include "Network/NetworkServer.h"
NetworkServer::NetworkServer()
{
m_ReadBuffer = new char[m_BufferSize];
}
NetworkServer::~NetworkServer()
{
delete[] m_ReadBuffer;
}
+15 -112
View File
@@ -1,8 +1,7 @@
#include "Network/Server.h" #include "Network/Server.h"
Server::Server(World* world, EventBroker* eventBroker, int port) Server::Server(World* world, EventBroker* eventBroker, int port)
: Network(world, eventBroker) : Network(world, eventBroker)
, m_ServerlistRequest(13)
{ {
ConfigFile* config = ResourceManager::Load<ConfigFile>("Config.ini"); ConfigFile* config = ResourceManager::Load<ConfigFile>("Config.ini");
snapshotInterval = 1000 * config->Get<float>("Networking.SnapshotInterval", 0.05f); snapshotInterval = 1000 * config->Get<float>("Networking.SnapshotInterval", 0.05f);
@@ -14,7 +13,7 @@ Server::Server(World* world, EventBroker* eventBroker, int port)
EVENT_SUBSCRIBE_MEMBER(m_EComponentDeleted, &Server::OnComponentDeleted); EVENT_SUBSCRIBE_MEMBER(m_EComponentDeleted, &Server::OnComponentDeleted);
EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Server::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Server::OnPlayerDamage);
// BindWW // Bind
if (port == 0) { if (port == 0) {
port = config->Get<float>("Networking.Port", 27666); port = config->Get<float>("Networking.Port", 27666);
} }
@@ -29,8 +28,9 @@ Server::~Server()
void Server::Update() void Server::Update()
{ {
m_Reliable.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); PlayerDefinition pd;
m_Reliable.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers);
for (auto& kv : m_ConnectedPlayers) { for (auto& kv : m_ConnectedPlayers) {
while (kv.second.TCPSocket->available()) { while (kv.second.TCPSocket->available()) {
// Packet will get real data in receive // Packet will get real data in receive
@@ -46,7 +46,6 @@ void Server::Update()
} }
} }
PlayerDefinition pd;
while (m_Unreliable.IsSocketAvailable()) { while (m_Unreliable.IsSocketAvailable()) {
// Packet will get real data in receive // Packet will get real data in receive
Packet packet(MessageType::Invalid); Packet packet(MessageType::Invalid);
@@ -59,22 +58,6 @@ void Server::Update()
parseMessageType(packet); parseMessageType(packet);
} }
} }
while (m_ServerlistRequest.IsSocketAvailable()) {
Packet packet(MessageType::Invalid);
PlayerDefinition localArea;
localArea.Endpoint = boost::asio::ip::udp::endpoint();
m_ServerlistRequest.Receive(packet, localArea);
if (packet.GetMessageType() == MessageType::ServerlistRequest) {
packet.ReadPrimitive<int>(); // Pop size
packet.ReadPrimitive<int>(); // Pop MsgType
packet.ReadPrimitive<int>(); // Pop packet ID
int port = packet.ReadPrimitive<int>();
std::string address = localArea.Endpoint.address().to_string();
parseServerlistRequest(boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string(address), port));
}
}
// Check if players have disconnected // Check if players have disconnected
for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { for (int i = 0; i < m_PlayersToDisconnect.size(); i++) {
disconnect(m_PlayersToDisconnect.at(i)); disconnect(m_PlayersToDisconnect.at(i));
@@ -92,7 +75,6 @@ void Server::Update()
sendPing(); sendPing();
previousePingMessage = currentTime; previousePingMessage = currentTime;
} }
// Time out logic // Time out logic
if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) {
checkForTimeOuts(); checkForTimeOuts();
@@ -138,9 +120,6 @@ void Server::parseMessageType(Packet& packet)
case MessageType::PlayerTransform: case MessageType::PlayerTransform:
parsePlayerTransform(packet); parsePlayerTransform(packet);
break; break;
case MessageType::OnDoubleJump:
parseDoubleJump(packet);
break;
default: default:
break; break;
} }
@@ -167,7 +146,7 @@ void Server::sendSnapshot()
{ {
Packet packet(MessageType::Snapshot); Packet packet(MessageType::Snapshot);
addInputCommandsToPacket(packet); addInputCommandsToPacket(packet);
addPlayersToPacket(packet, EntityID_Invalid); addChildrenToPacket(packet, EntityID_Invalid);
unreliableBroadcast(packet); unreliableBroadcast(packet);
} }
@@ -184,61 +163,19 @@ void Server::addInputCommandsToPacket(Packet& packet)
m_InputCommandsToBroadcast.clear(); m_InputCommandsToBroadcast.clear();
} }
void Server::addPlayersToPacket(Packet & packet, EntityID entityID) void Server::addChildrenToPacket(Packet & packet, EntityID entityID)
{ {
auto itPair = m_World->GetDirectChildren(entityID); auto itPair = m_World->GetChildren(entityID);
std::unordered_map<std::string, ComponentPool*> worldComponentPools = m_World->GetComponentPools(); std::unordered_map<std::string, ComponentPool*> worldComponentPools = m_World->GetComponentPools();
// Loop through every child // Loop through every child
for (auto it = itPair.first; it != itPair.second; it++) { for (auto it = itPair.first; it != itPair.second; it++) {
EntityID childEntityID = it->second; EntityID childEntityID = it->second;
// HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself // HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself
// HACK: Also checked CapturePointHUD for now. (this would get out of sync);
EntityWrapper childEntity(m_World, childEntityID); EntityWrapper childEntity(m_World, childEntityID);
if (shouldSendToClient(childEntity)) { if (!shouldSendToClient(childEntity)) {
// Write EntityID and parentsID and Entity name continue;
packet.WritePrimitive(childEntityID);
packet.WritePrimitive(entityID);
packet.WriteString(m_World->GetName(childEntityID));
// Write components to child
int numberOfComponents = 0;
for (auto& i : worldComponentPools) {
if (i.second->KnowsEntity(childEntityID)) {
numberOfComponents++;
}
}
// Write how many components should be read
packet.WritePrimitive(numberOfComponents);
for (auto& i : worldComponentPools) {
// If the entity exist in the pool
if (i.second->KnowsEntity(childEntityID)) {
ComponentWrapper componentWrapper = i.second->GetByEntity(childEntityID);
// ComponentType
packet.WriteString(componentWrapper.Info.Name);
// Loop through fields
for (auto& componentField : componentWrapper.Info.FieldsInOrder) {
ComponentInfo::Field_t fieldInfo = componentWrapper.Info.Fields.at(componentField);
if (fieldInfo.Type == "string") {
std::string& value = componentWrapper[componentField];
packet.WriteString(value);
} else {
packet.WriteData(componentWrapper.Data + fieldInfo.Offset, fieldInfo.Stride);
}
}
}
}
} }
// Go to to your children
addPlayersToPacket(packet, childEntityID);
}
}
void Server::addChildrenToPacket(Packet & packet, EntityID entityID)
{
auto itPair = m_World->GetDirectChildren(entityID);
std::unordered_map<std::string, ComponentPool*> worldComponentPools = m_World->GetComponentPools();
// Loop through every child
for (auto it = itPair.first; it != itPair.second; it++) {
EntityID childEntityID = it->second;
// Write EntityID and parentsID and Entity name // Write EntityID and parentsID and Entity name
packet.WritePrimitive(childEntityID); packet.WritePrimitive(childEntityID);
packet.WritePrimitive(entityID); packet.WritePrimitive(entityID);
@@ -293,8 +230,6 @@ void Server::sendPing()
reliableBroadcast(packet); reliableBroadcast(packet);
} }
void Server::checkForTimeOuts() void Server::checkForTimeOuts()
{ {
double startPing = 1000 * m_StartPingTime double startPing = 1000 * m_StartPingTime
@@ -344,7 +279,7 @@ void Server::parseTCPConnect(Packet & packet)
// Read packet ID // Read packet ID
m_PreviousPacketID = m_PacketID; // Set previous packet id m_PreviousPacketID = m_PacketID; // Set previous packet id
m_PacketID = packet.ReadPrimitive<int>(); //Read new packet id m_PacketID = packet.ReadPrimitive<int>(); //Read new packet id
LOG_INFO("Parsing connections"); LOG_INFO("Parsing connections");
// Check if player is already connected // Check if player is already connected
// Ska vara till lagd i TCPServer receive // Ska vara till lagd i TCPServer receive
@@ -369,11 +304,6 @@ void Server::parseTCPConnect(Packet & packet)
connnectPacket.WritePrimitive(playerID); connnectPacket.WritePrimitive(playerID);
m_Reliable.Send(connnectPacket); m_Reliable.Send(connnectPacket);
Packet firstSnapshot(MessageType::Snapshot);
addInputCommandsToPacket(firstSnapshot);
addChildrenToPacket(firstSnapshot, EntityID_Invalid);
m_Reliable.Send(firstSnapshot);
// Send notification that a player has connected // Send notification that a player has connected
//Packet notificationPacket(MessageType::PlayerConnected); //Packet notificationPacket(MessageType::PlayerConnected);
//broadcast(notificationPacket); //broadcast(notificationPacket);
@@ -392,17 +322,6 @@ void Server::parseDisconnect()
} }
} }
void Server::parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint)
{
Packet packet(MessageType::ServerlistRequest);
packet.WriteString(m_Reliable.Address());
packet.WritePrimitive<int>(m_Reliable.Port());
packet.WriteString("SERVERNAME");
packet.WritePrimitive<int>(m_ConnectedPlayers.size());
m_ServerlistRequest.Send(packet);
}
void Server::disconnect(PlayerID playerID) void Server::disconnect(PlayerID playerID)
{ {
//broadcast("A player disconnected"); //broadcast("A player disconnected");
@@ -427,7 +346,6 @@ void Server::parseOnPlayerDamage(Packet & packet)
e.Victim = EntityWrapper(m_World, packet.ReadPrimitive<EntityID>()); e.Victim = EntityWrapper(m_World, packet.ReadPrimitive<EntityID>());
e.Damage = packet.ReadPrimitive<double>(); e.Damage = packet.ReadPrimitive<double>();
m_EventBroker->Publish(e); m_EventBroker->Publish(e);
//LOG_DEBUG("Server::parseOnPlayerDamage: Command is %s. Value is %f. PlayerID is %i.", e.DamageAmount, e.PlayerDamagedID, e.TypeOfDamage.c_str()); //LOG_DEBUG("Server::parseOnPlayerDamage: Command is %s. Value is %f. PlayerID is %i.", e.DamageAmount, e.PlayerDamagedID, e.TypeOfDamage.c_str());
} }
@@ -456,7 +374,8 @@ bool Server::OnInputCommand(const Events::InputCommand & e)
} }
isReadingData = !isReadingData; isReadingData = !isReadingData;
m_SaveDataTimer = std::clock(); m_SaveDataTimer = std::clock();
} else if (e.Command == "KickPlayer" && e.Value > 0) { }
if (e.Command == "KickPlayer" && e.Value > 0) {
kick(0); kick(0);
} }
@@ -507,7 +426,7 @@ bool Server::OnPlayerDamage(const Events::PlayerDamage& e)
packet.WritePrimitive(e.Damage); packet.WritePrimitive(e.Damage);
reliableBroadcast(packet); reliableBroadcast(packet);
return true; return false;
} }
void Server::parseClientPing() void Server::parseClientPing()
@@ -527,21 +446,13 @@ void Server::parsePing()
{ {
for (auto& kv : m_ConnectedPlayers) { for (auto& kv : m_ConnectedPlayers) {
if (kv.second.TCPAddress == m_Address && if (kv.second.TCPAddress == m_Address &&
kv.second.TCPPort == m_Port kv.second.TCPPort == m_Port) {
|| (kv.second.Endpoint.address() == m_Address
&& kv.second.Endpoint.port() == m_Port)) {
kv.second.StopTime = std::clock(); kv.second.StopTime = std::clock();
break; break;
} }
} }
} }
bool Server::parseDoubleJump(Packet & packet)
{
reliableBroadcast(packet);
return true;
}
void Server::parseOnInputCommand(Packet& packet) void Server::parseOnInputCommand(Packet& packet)
{ {
PlayerID player = -1; PlayerID player = -1;
@@ -601,15 +512,7 @@ void Server::parsePlayerTransform(Packet& packet)
bool Server::shouldSendToClient(EntityWrapper childEntity) bool Server::shouldSendToClient(EntityWrapper childEntity)
{ {
auto children = m_World->GetDirectChildren(childEntity.ID); return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid();
for (auto it = children.first; it != children.second; it++) {
EntityWrapper child(m_World, it->second);
if(child.HasComponent("CapturePoint")) {
return true;
}
}
return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid()
|| childEntity.HasComponent("CapturePoint");
} }
PlayerID Server::GetPlayerIDFromEndpoint() PlayerID Server::GetPlayerIDFromEndpoint()
+10 -20
View File
@@ -56,42 +56,32 @@ void TCPClient::Disconnect()
void TCPClient::Receive(Packet& packet) void TCPClient::Receive(Packet& packet)
{ {
size_t bytesRead = readBuffer(); size_t bytesRead = readBuffer(m_ReadBuffer);
if (bytesRead > 0) { if (bytesRead > 0) {
packet.ReconstructFromData(m_ReadBuffer, bytesRead); packet.ReconstructFromData(m_ReadBuffer, bytesRead);
} }
} }
size_t TCPClient::readBuffer() size_t TCPClient::readBuffer(char* data)
{ {
if (!m_Socket) { if (!m_Socket) {
return 0; return 0;
} }
boost::system::error_code error; boost::system::error_code error;
// Read size of packet // Read size of packet
m_Socket->receive(boost
::asio::buffer((void*)m_ReadBuffer, sizeof(int)),
boost::asio::ip::tcp::socket::message_peek, error);
unsigned int sizeOfPacket = 0;
memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int));
// if the buffer is to small increase the size of it
// TODO if message is huge 1 time the buffer will not decrease.
if (sizeOfPacket > m_BufferSize) {
delete[] m_ReadBuffer;
m_ReadBuffer = new char[sizeOfPacket];
m_BufferSize = sizeOfPacket;
}
// Read the rest of the message
size_t bytesReceived = m_Socket->read_some(boost size_t bytesReceived = m_Socket->read_some(boost
::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket), ::asio::buffer((void*)data, sizeof(int)),
error);
int sizeOfPacket = 0;
memcpy(&sizeOfPacket, data, sizeof(int));
// Read the rest of the message
bytesReceived += m_Socket->read_some(boost
::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived),
error); error);
if (error) { if (error) {
//LOG_ERROR("receive: %s", error.message().c_str()); //LOG_ERROR("receive: %s", error.message().c_str());
} }
if (sizeOfPacket > 1000000)
LOG_WARNING("The packets received are bigger than 1MB");
return bytesReceived; return bytesReceived;
} }
+38 -55
View File
@@ -1,38 +1,25 @@
#include "Network/TCPServer.h" #include "Network/TCPServer.h"
using namespace boost::asio::ip; using namespace boost::asio::ip;
TCPServer::TCPServer() TCPServer::TCPServer()
{ {
acceptor = std::unique_ptr<tcp::acceptor>(new tcp::acceptor(m_IOService, tcp::endpoint(tcp::v4(), 27666))); acceptor = std::unique_ptr<tcp::acceptor>(new tcp::acceptor(m_IOService, tcp::endpoint(tcp::v4(), 27666)));
// Make the acceptor non-blocking so we wont get stuck in AcceptNewConnections().
acceptor->non_blocking(true);
m_Port = GetPort();
m_Address = GetAddress();
} }
TCPServer::~TCPServer() TCPServer::~TCPServer()
{ } {
}
void TCPServer::AcceptNewConnections(int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers) void TCPServer::AcceptNewConnections(int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers)
{ {
boost::system::error_code error;
boost::shared_ptr<tcp::socket> newSocket = boost::shared_ptr<tcp::socket>(new tcp::socket(m_IOService)); boost::shared_ptr<tcp::socket> newSocket = boost::shared_ptr<tcp::socket>(new tcp::socket(m_IOService));
acceptor->accept(*newSocket, error); m_IOService.poll();
// If no error occured add new tcp connection acceptor->async_accept(*newSocket,
if (!error) { boost::bind(&TCPServer::handle_accept, this, newSocket, boost::ref(nextPlayerID), boost::ref(connectedPlayers),
// Add tcp socket to connections boost::asio::placeholders::error));
boost::asio::ip::tcp::no_delay option(true);
newSocket->set_option(option);
PlayerDefinition pd;
pd.StopTime = std::clock();
pd.TCPSocket = newSocket;
pd.TCPAddress = newSocket.get()->remote_endpoint().address();
pd.TCPPort = newSocket.get()->remote_endpoint().port();
connectedPlayers[nextPlayerID++] = pd;
}
} }
PlayerID TCPServer::getPlayerIDFromEndpoint(const std::map<PlayerID, PlayerDefinition>& connectedPlayers, PlayerID GetPlayerIDFromEndpoint(const std::map<PlayerID, PlayerDefinition>& connectedPlayers,
boost::asio::ip::address address, unsigned short port) boost::asio::ip::address address, unsigned short port)
{ {
for (auto& kv : connectedPlayers) { for (auto& kv : connectedPlayers) {
@@ -44,10 +31,28 @@ PlayerID TCPServer::getPlayerIDFromEndpoint(const std::map<PlayerID, PlayerDefin
return -1; return -1;
} }
void TCPServer::handle_accept(boost::shared_ptr<tcp::socket> socket,
int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers,
const boost::system::error_code& error)
{
if (!error && GetPlayerIDFromEndpoint(connectedPlayers, socket->remote_endpoint().address(),
socket->remote_endpoint().port()) == -1) {
// Add tcp socket to connections
boost::asio::ip::tcp::no_delay option(true);
socket->set_option(option);
PlayerDefinition pd;
pd.StopTime = std::clock();
pd.TCPSocket = socket;
pd.TCPAddress = socket.get()->remote_endpoint().address();
pd.TCPPort = socket.get()->remote_endpoint().port();
connectedPlayers[nextPlayerID++] = pd;
}
}
void TCPServer::Send(Packet & packet, PlayerDefinition & playerDefinition) void TCPServer::Send(Packet & packet, PlayerDefinition & playerDefinition)
{ {
packet.UpdateSize();
try { try {
packet.UpdateSize();
int bytesSent = playerDefinition.TCPSocket->send( int bytesSent = playerDefinition.TCPSocket->send(
boost::asio::buffer(packet.Data(), packet.Size()), boost::asio::buffer(packet.Data(), packet.Size()),
0); 0);
@@ -68,60 +73,38 @@ void TCPServer::Send(Packet & packet)
} }
void TCPServer::Disconnect() void TCPServer::Disconnect()
{ {
}
int TCPServer::GetPort()
{
return acceptor->local_endpoint().port();
}
std::string TCPServer::GetAddress()
{
boost::asio::ip::tcp::resolver resolver(m_IOService);
boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), boost::asio::ip::host_name(), "");
boost::asio::ip::tcp::resolver::iterator it = resolver.resolve(query);
boost::asio::ip::tcp::endpoint endpoint = *it;
return endpoint.address().to_string().c_str();
} }
void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition)
{ {
int bytesRead = readBuffer(playerDefinition); int bytesRead = readBuffer(m_ReadBuffer, playerDefinition);
if (bytesRead > 0) { if (bytesRead > 0) {
packet.ReconstructFromData(m_ReadBuffer, bytesRead); packet.ReconstructFromData(m_ReadBuffer, bytesRead);
} }
lastReceivedSocket = playerDefinition.TCPSocket; lastReceivedSocket = playerDefinition.TCPSocket;
} }
int TCPServer::readBuffer(PlayerDefinition & playerDefinition) int TCPServer::readBuffer(char* data, PlayerDefinition & playerDefinition)
{ {
if (!playerDefinition.TCPSocket) { if (!playerDefinition.TCPSocket) {
return 0; return 0;
} }
boost::system::error_code error; boost::system::error_code error;
// Read size of packet // Read size of packet
playerDefinition.TCPSocket->receive(boost
::asio::buffer((void*)m_ReadBuffer, sizeof(int)),
boost::asio::ip::tcp::socket::message_peek, error);
unsigned int sizeOfPacket = 0;
memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int));
// if the buffer is to small increase the size of it
if (sizeOfPacket > m_BufferSize) {
delete[] m_ReadBuffer;
m_ReadBuffer = new char[sizeOfPacket];
m_BufferSize = sizeOfPacket;
}
// Read the rest of the message
size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost
::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket), ::asio::buffer((void*)data, sizeof(int)),
error);
int sizeOfPacket = 0;
memcpy(&sizeOfPacket, data, sizeof(int));
// Read the rest of the message
bytesReceived += playerDefinition.TCPSocket->read_some(boost
::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived),
error); error);
if (error) { if (error) {
//LOG_ERROR("receive: %s", error.message().c_str()); //LOG_ERROR("receive: %s", error.message().c_str());
} }
if (sizeOfPacket > 1000000)
LOG_WARNING("The packets received are bigger than 1MB");
return bytesReceived; return bytesReceived;
} }
+8 -40
View File
@@ -15,9 +15,9 @@ void UDPClient::Connect(std::string playerName, std::string address, int port)
if (m_Socket) { if (m_Socket) {
return; return;
} }
m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address().from_string(address), port); m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port);
m_Socket = boost::shared_ptr<boost::asio::ip::udp::socket>(new boost::asio::ip::udp::socket(m_IOService)); m_Socket = boost::shared_ptr<boost::asio::ip::udp::socket>(new boost::asio::ip::udp::socket(m_IOService));
m_Socket->open(boost::asio::ip::udp::v4()); m_Socket->connect(m_ReceiverEndpoint);
} }
void UDPClient::Disconnect() void UDPClient::Disconnect()
@@ -27,66 +27,34 @@ void UDPClient::Disconnect()
void UDPClient::Receive(Packet& packet) void UDPClient::Receive(Packet& packet)
{ {
int bytesRead = readBuffer(); int bytesRead = readBuffer(m_ReadBuffer);
if (bytesRead > 0) { if (bytesRead > 0) {
packet.ReconstructFromData(m_ReadBuffer, bytesRead); packet.ReconstructFromData(m_ReadBuffer, bytesRead);
} }
} }
int UDPClient::readBuffer() int UDPClient::readBuffer(char* data)
{ {
if (!m_Socket) { if (!m_Socket) {
return 0; return 0;
} }
boost::system::error_code error; boost::system::error_code error;
// Read size of packet int bytesReceived = m_Socket->receive_from(boost
m_Socket->receive(boost ::asio::buffer((void*)data, BUFFERSIZE),
::asio::buffer((void*)m_ReadBuffer, sizeof(int)), m_ReceiverEndpoint,
boost::asio::ip::udp::socket::message_peek, error); 0, error);
int sizeOfPacket = 0;
memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int));
// if the buffer is to small increase the size of it
if (sizeOfPacket > m_BufferSize) {
delete[] m_ReadBuffer;
m_ReadBuffer = new char[sizeOfPacket];
m_BufferSize = sizeOfPacket;
}
size_t availableData = m_Socket->available();
// Read the rest of the message
size_t bytesReceived = m_Socket->receive_from(boost
::asio::buffer((void*)(m_ReadBuffer),
sizeOfPacket),
m_ReceiverEndpoint, 0, error);
if (error) { if (error) {
//LOG_ERROR("receive: %s", error.message().c_str()); //LOG_ERROR("receive: %s", error.message().c_str());
} }
if (sizeOfPacket > 1000000)
LOG_WARNING("The packets received are bigger than 1MB");
return bytesReceived; return bytesReceived;
} }
void UDPClient::Send(Packet& packet) void UDPClient::Send(Packet& packet)
{ {
packet.UpdateSize();
m_Socket->send_to(boost::asio::buffer( m_Socket->send_to(boost::asio::buffer(
packet.Data(), packet.Data(),
packet.Size()), packet.Size()),
m_ReceiverEndpoint, 0); m_ReceiverEndpoint, 0);
}
void UDPClient::Broadcast(Packet& packet, int port)
{
packet.UpdateSize();
m_Socket->set_option(boost::asio::socket_base::broadcast(true));
m_Socket->send_to(boost::asio::buffer(
packet.Data(),
packet.Size()),
udp::endpoint(boost::asio::ip::address_v4().broadcast(), port)
, 0);
m_Socket->set_option(boost::asio::socket_base::broadcast(false));
} }
bool UDPClient::IsSocketAvailable() bool UDPClient::IsSocketAvailable()
+10 -65
View File
@@ -5,17 +5,11 @@ UDPServer::UDPServer()
m_Socket = std::unique_ptr<boost::asio::ip::udp::socket>(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666))); m_Socket = std::unique_ptr<boost::asio::ip::udp::socket>(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666)));
} }
UDPServer::UDPServer(int port)
{
m_Socket = std::unique_ptr<boost::asio::ip::udp::socket>(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), port)));
}
UDPServer::~UDPServer() UDPServer::~UDPServer()
{ } { }
void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition) void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition)
{ {
packet.UpdateSize();
try { try {
int bytesSent = m_Socket->send_to( int bytesSent = m_Socket->send_to(
boost::asio::buffer(packet.Data(), packet.Size()), boost::asio::buffer(packet.Data(), packet.Size()),
@@ -29,7 +23,6 @@ void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition)
// Send back to endpoint of received packet // Send back to endpoint of received packet
void UDPServer::Send(Packet & packet) void UDPServer::Send(Packet & packet)
{ {
packet.UpdateSize();
m_Socket->send_to( m_Socket->send_to(
boost::asio::buffer( boost::asio::buffer(
packet.Data(), packet.Data(),
@@ -38,35 +31,9 @@ void UDPServer::Send(Packet & packet)
0); 0);
} }
// Broadcasting respond specific logic
void UDPServer::Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint)
{
packet.UpdateSize();
m_Socket->send_to(
boost::asio::buffer(
packet.Data(),
packet.Size()),
endpoint,
0);
}
// Broadcasting
void UDPServer::Broadcast(Packet & packet, int port)
{
packet.UpdateSize();
m_Socket->set_option(boost::asio::socket_base::broadcast(true));
m_Socket->send_to(
boost::asio::buffer(
packet.Data(),
packet.Size()),
boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4().broadcast(),port),
0);
m_Socket->set_option(boost::asio::socket_base::broadcast(false));
}
void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition)
{ {
int bytesRead = readBuffer(); int bytesRead = readBuffer(m_ReadBuffer);
if (bytesRead > 0) { if (bytesRead > 0) {
packet.ReconstructFromData(m_ReadBuffer, bytesRead); packet.ReconstructFromData(m_ReadBuffer, bytesRead);
} }
@@ -78,39 +45,17 @@ bool UDPServer::IsSocketAvailable()
return m_Socket->available(); return m_Socket->available();
} }
int UDPServer::readBuffer() int UDPServer::readBuffer(char* data)
{ {
if (!m_Socket) { boost::system::error_code error = boost::asio::error::host_not_found;
return 0; unsigned int length = m_Socket->receive_from(
boost::asio::buffer((void*)data
, BUFFERSIZE)
, m_ReceiverEndpoint, 0, error);
if (error) {
LOG_WARNING(error.message().c_str());
} }
int addasdasd = m_Socket->available(); return length;
boost::system::error_code error;
// Read size of packet
m_Socket->receive_from(boost
::asio::buffer((void*)m_ReadBuffer, sizeof(int)),
m_ReceiverEndpoint, boost::asio::ip::udp::socket::message_peek, error);
unsigned int sizeOfPacket = 0;
memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int));
// if the buffer is to small increase the size of it
if (sizeOfPacket > m_BufferSize) {
delete[] m_ReadBuffer;
m_ReadBuffer = new char[sizeOfPacket];
m_BufferSize = sizeOfPacket;
}
// Read the rest of the message
size_t bytesReceived = m_Socket->receive_from(boost
::asio::buffer((void*)(m_ReadBuffer),
sizeOfPacket),
m_ReceiverEndpoint, 0, error);
if (error) {
//LOG_ERROR("receive: %s", error.message().c_str());
}
if (sizeOfPacket > 1000000)
LOG_WARNING("The packets received are bigger than 1MB");
return bytesReceived;
} }
void UDPServer::AcceptNewConnections(int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers) void UDPServer::AcceptNewConnections(int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers)
-41
View File
@@ -1,41 +0,0 @@
#include "Rendering/CubeMapPass.h"
CubeMapPass::CubeMapPass(IRenderer* renderer)
:m_Renderer(renderer)
{
LoadTextures("Nevada");
}
void CubeMapPass::LoadTextures(std::string input)
{
if (m_PreviusCubeMapTexture != input) {
m_CubeMapTextures.clear();
for (int i = 0; i < 6; i++) {
std::string str;
str = "Textures/Test/CubeMap/" + input + "/CubeMapTest0" + std::to_string(i) + ".png";
Texture* img = ResourceManager::Load<Texture>(str);
m_CubeMapTextures.push_back(img);
}
GenerateCubeMapTexture();
m_PreviusCubeMapTexture = input;
}
}
void CubeMapPass::GenerateCubeMapTexture()
{
if (m_CubeMapTexture == -1) {
glGenTextures(1, &m_CubeMapTexture);
}
glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapTexture);
for (int i = 0; i < 6; i++) {
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, m_CubeMapTextures[0]->Width, m_CubeMapTextures[0]->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_CubeMapTextures[i]->Data);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
GLERROR("Generate Cubemap");
}
-2
View File
@@ -52,7 +52,6 @@ void DrawBloomPass::InitializeBuffers()
void DrawBloomPass::ClearBuffer() void DrawBloomPass::ClearBuffer()
{ {
GLERROR("PRE");
m_GaussianFrameBuffer_horiz.Bind(); m_GaussianFrameBuffer_horiz.Bind();
glClearColor(0.f, 0.f, 0.f, 0.f); glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -61,7 +60,6 @@ void DrawBloomPass::ClearBuffer()
glClearColor(0.f, 0.f, 0.f, 0.f); glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_GaussianFrameBuffer_vert.Unbind(); m_GaussianFrameBuffer_vert.Unbind();
GLERROR("END");
} }
void DrawBloomPass::Draw(GLuint texture) void DrawBloomPass::Draw(GLuint texture)
+3 -39
View File
@@ -1,11 +1,10 @@
#include "Rendering/DrawFinalPass.h" #include "Rendering/DrawFinalPass.h"
DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass) DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass)
: m_Renderer(renderer)
, m_LightCullingPass(lightCullingPass)
, m_CubeMapPass(cubeMapPass)
{ {
//TODO: Make sure that uniforms are not sent into shader if not needed. //TODO: Make sure that uniforms are not sent into shader if not needed.
m_Renderer = renderer;
m_LightCullingPass = lightCullingPass;
m_ShieldPixelRate = 8; m_ShieldPixelRate = 8;
InitializeTextures(); InitializeTextures();
InitializeShaderPrograms(); InitializeShaderPrograms();
@@ -193,10 +192,8 @@ void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture)
state->StencilMask(0x00); state->StencilMask(0x00);
DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture);
GLERROR("OpaqueObjects"); GLERROR("OpaqueObjects");
state->BlendFunc(GL_ONE, GL_ONE);
DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture);
GLERROR("TransparentObjects"); GLERROR("TransparentObjects");
state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
DrawSprites(scene.Jobs.SpriteJob, scene); DrawSprites(scene.Jobs.SpriteJob, scene);
GLERROR("SpriteJobs"); GLERROR("SpriteJobs");
@@ -262,35 +259,20 @@ void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture)
void DrawFinalPass::ClearBuffer() void DrawFinalPass::ClearBuffer()
{ {
GLERROR("PRE");
m_FinalPassFrameBufferLowRes.Bind(); m_FinalPassFrameBufferLowRes.Bind();
GLERROR("Bind LowRes");
glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate); glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate);
glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
GLERROR("ViewPort,Scissor LowRes");
glClearColor(0.f, 0.f, 0.f, 0.f); glClearColor(0.f, 0.f, 0.f, 0.f);
GLERROR("1");
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLERROR("2");
glDisable(GL_SCISSOR_TEST); glDisable(GL_SCISSOR_TEST);
GLERROR("3");
m_FinalPassFrameBufferLowRes.Unbind(); m_FinalPassFrameBufferLowRes.Unbind();
GLERROR("prebind HighRes");
m_FinalPassFrameBuffer.Bind(); m_FinalPassFrameBuffer.Bind();
GLERROR("Bind HighRes");
glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
GLERROR("ViewPort,Scissor LowRes");
glClearColor(0.f, 0.f, 0.f, 0.f); glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_FinalPassFrameBuffer.Unbind(); m_FinalPassFrameBuffer.Unbind();
GLERROR("END");
} }
@@ -374,17 +356,12 @@ void DrawFinalPass::DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>&
case RawModel::MaterialType::SingleTextures: case RawModel::MaterialType::SingleTextures:
{ {
if (explosionEffectJob->Model->IsSkinned()) { if (explosionEffectJob->Model->IsSkinned()) {
m_ExplosionEffectSkinnedProgram->Bind(); m_ExplosionEffectSkinnedProgram->Bind();
GLERROR("Bind ExplosionEffectSkinned program"); GLERROR("Bind ExplosionEffectSkinned program");
//bind uniforms //bind uniforms
BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene);
//bind textures //bind textures
BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob);
glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture);
glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position()));
std::vector<glm::mat4> frameBones; std::vector<glm::mat4> frameBones;
if (explosionEffectJob->AnimationOffset.animation != nullptr) { if (explosionEffectJob->AnimationOffset.animation != nullptr) {
frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset);
@@ -399,10 +376,6 @@ void DrawFinalPass::DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>&
BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); BindExplosionUniforms(explosionHandle, explosionEffectJob, scene);
//bind textures //bind textures
BindExplosionTextures(explosionHandle, explosionEffectJob); BindExplosionTextures(explosionHandle, explosionEffectJob);
glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture);
glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position()));
} }
break; break;
} }
@@ -461,10 +434,6 @@ void DrawFinalPass::DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>&
BindModelUniforms(forwardSkinnedHandle, modelJob, scene); BindModelUniforms(forwardSkinnedHandle, modelJob, scene);
//bind textures //bind textures
BindModelTextures(forwardSkinnedHandle, modelJob); BindModelTextures(forwardSkinnedHandle, modelJob);
glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture);
glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position()));
std::vector<glm::mat4> frameBones; std::vector<glm::mat4> frameBones;
if (modelJob->AnimationOffset.animation != nullptr) { if (modelJob->AnimationOffset.animation != nullptr) {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset);
@@ -480,9 +449,6 @@ void DrawFinalPass::DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>&
BindModelUniforms(forwardHandle, modelJob, scene); BindModelUniforms(forwardHandle, modelJob, scene);
//bind textures //bind textures
BindModelTextures(forwardHandle, modelJob); BindModelTextures(forwardHandle, modelJob);
glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture);
glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position()));
} }
break; break;
} }
@@ -841,8 +807,6 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr<Model
void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptr<ExplosionEffectJob>& job) void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptr<ExplosionEffectJob>& job)
{ {
switch (job->Type) { switch (job->Type) {
case RawModel::MaterialType::SingleTextures: case RawModel::MaterialType::SingleTextures:
case RawModel::MaterialType::Basic: case RawModel::MaterialType::Basic:
+15 -6
View File
@@ -21,13 +21,23 @@ void PickingPass::InitializeTextures()
{ {
GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR,
glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE); glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE);
GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST,
glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8);
} }
void PickingPass::InitializeFrameBuffers() void PickingPass::InitializeFrameBuffers()
{ {
/* glGenRenderbuffers(1, &m_DepthBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);*/
glGenTextures(1, &m_DepthBuffer);
glBindTexture(GL_TEXTURE_2D, m_DepthBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width), (int)(m_Renderer->GetViewportSize().Height), 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
m_PickingBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); m_PickingBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_DepthBuffer, GL_DEPTH_ATTACHMENT)));
m_PickingBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0))); m_PickingBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0)));
m_PickingBuffer.Generate(); m_PickingBuffer.Generate();
@@ -54,7 +64,6 @@ void PickingPass::InitializeShaderPrograms()
void PickingPass::Draw(RenderScene& scene) void PickingPass::Draw(RenderScene& scene)
{ {
GLERROR("PRE");
PickingPassState* state = new PickingPassState(m_PickingBuffer.GetHandle()); PickingPassState* state = new PickingPassState(m_PickingBuffer.GetHandle());
//TODO: Render: Add code for more jobs than modeljobs. //TODO: Render: Add code for more jobs than modeljobs.
@@ -358,7 +367,6 @@ void PickingPass::Draw(RenderScene& scene)
void PickingPass::ClearPicking() void PickingPass::ClearPicking()
{ {
GLERROR("PRE");
m_PickingColorsToEntity.clear(); m_PickingColorsToEntity.clear();
m_EntityColors.clear(); m_EntityColors.clear();
m_ColorCounter[0] = 0; m_ColorCounter[0] = 0;
@@ -368,13 +376,14 @@ void PickingPass::ClearPicking()
glClearColor(0.f, 0.f, 0.f, 0.f); glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_PickingBuffer.Unbind(); m_PickingBuffer.Unbind();
GLERROR("END");
} }
void PickingPass::OnWindowResize() void PickingPass::OnWindowResize()
{ {
InitializeTextures(); InitializeTextures();
glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
m_PickingBuffer.Generate(); m_PickingBuffer.Generate();
} }
+2 -3
View File
@@ -3,9 +3,9 @@
PickingPassState::PickingPassState(GLuint frameBuffer) PickingPassState::PickingPassState(GLuint frameBuffer)
{ {
GLERROR("PRE"); GLERROR("---2");
BindFramebuffer(frameBuffer); BindFramebuffer(frameBuffer);
GLERROR("Bind Framebuffer"); GLERROR("---3");
Enable(GL_DEPTH_TEST); Enable(GL_DEPTH_TEST);
Enable(GL_CULL_FACE); Enable(GL_CULL_FACE);
Disable(GL_BLEND); Disable(GL_BLEND);
@@ -13,7 +13,6 @@ PickingPassState::PickingPassState(GLuint frameBuffer)
glm::vec4 clearColor = glm::vec4(0.f); glm::vec4 clearColor = glm::vec4(0.f);
//ClearColor(clearColor); //ClearColor(clearColor);
//Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLERROR("END");
} }
PickingPassState::~PickingPassState() PickingPassState::~PickingPassState()
+6 -96
View File
@@ -52,101 +52,6 @@ void RenderSystem::fillSprites(std::list<std::shared_ptr<RenderJob>>& jobs, Worl
continue; continue;
} }
glm::mat4 modelMatrix;
// See a sprite is an SpriteIndicator
bool isIndicator = false;
if (world->HasComponent(entity.ID, "SpriteIndicator"))
{
auto indicator = entity["SpriteIndicator"];
float minScale = (float)(double)indicator["MinScale"];
bool hasTeam = indicator["VisibleForSingleTeamOnly"];
isIndicator = true;
glm::vec3 pos = Transform::AbsolutePosition(entity);
EntityWrapper entityTeam;
if (hasTeam && (entity.HasComponent("Team") || entity.FirstParentWithComponent("Team").Valid()) && m_LocalPlayer.World != nullptr) {
if (!entity.HasComponent("Team")) {
entityTeam = entity.FirstParentWithComponent("Team");
}
else {
entityTeam = entity;
}
ComponentWrapper& entityTeamComponent = entityTeam["Team"];
ComponentWrapper& localComponent = m_LocalPlayer["Team"];
int entityTeamInt = entityTeamComponent["Team"];
int localComponentInt = localComponent["Team"];
int SpectatorInt = localComponent["Team"].Enum("Spectator");
if (entityTeamInt != localComponentInt && localComponentInt != SpectatorInt) {
continue;
}
}
// Code for check if sprite is inside or outside of screen
//glm::vec4 projectedPos = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * glm::vec4(pos, 1.0f);
//projectedPos /= projectedPos.w;
//// Check if inside of outside of screen.
//if (projectedPos.x < -1.0f || projectedPos.x > 1.0f || projectedPos.y < -1.0f || projectedPos.y > 1.0f) {
// // is outside of screen
//} else {
// // is inside of screen
//}
glm::vec3 zAxis = glm::vec3(0.0f, 1.0f, 0.0f);
glm::vec3 normal = pos - m_Camera->Position();
//float distance = glm::length(normal);
//if (distance < minDistance) {
// pos = pos - glm::normalize(normal) * (distance - minDistance);
//} else if (distance > maxDistance) {
// pos = pos - glm::normalize(normal) * (distance - maxDistance);
//}
normal.y = 0;
normal = glm::normalize(normal);
glm::vec3 right = glm::cross(normal, zAxis);
glm::vec3 up = glm::cross(right, normal);
modelMatrix[0][0] = right.x;
modelMatrix[0][1] = right.y;
modelMatrix[0][2] = right.z;
modelMatrix[0][3] = 0.0f;
modelMatrix[1][0] = zAxis.x;
modelMatrix[1][1] = zAxis.y;
modelMatrix[1][2] = zAxis.z;
modelMatrix[1][3] = 0.0f;
modelMatrix[2][0] = normal.x;
modelMatrix[2][1] = normal.y;
modelMatrix[2][2] = normal.z;
modelMatrix[2][3] = 0.0f;
modelMatrix[3][0] = pos.x;
modelMatrix[3][1] = pos.y;
modelMatrix[3][2] = pos.z;
modelMatrix[3][3] = 1.0f;
glm::mat4 tranformationMatrix = modelMatrix * glm::scale(Transform::AbsoluteScale(entity));
glm::vec4 tmp = tranformationMatrix * glm::vec4(glm::vec3(0.5, 0.5, 0), 1.0f);
glm::vec2 projectedTopRight = m_Camera->WorldToScreen(glm::vec3(tmp), m_Renderer->GetViewportSize());
tmp = tranformationMatrix * glm::vec4(glm::vec3(-0.5, -0.5, 0), 1.0f);
glm::vec2 projectedBottomLeft = m_Camera->WorldToScreen(glm::vec3(tmp), m_Renderer->GetViewportSize());
float diag = glm::length(projectedBottomLeft - projectedTopRight);
if (diag < minScale) {
tranformationMatrix = tranformationMatrix * glm::scale(glm::vec3(minScale / diag, minScale / diag, minScale / diag));
}
modelMatrix = tranformationMatrix;
}
else {
modelMatrix = Transform::ModelMatrix(entity.ID, world);
}
std::string diffuseResource = cSprite["DiffuseTexture"]; std::string diffuseResource = cSprite["DiffuseTexture"];
std::string glowResource = cSprite["GlowMap"]; std::string glowResource = cSprite["GlowMap"];
bool depthSorted = cSprite["DepthSort"]; bool depthSorted = cSprite["DepthSort"];
@@ -162,7 +67,11 @@ void RenderSystem::fillSprites(std::list<std::shared_ptr<RenderJob>>& jobs, Worl
fillColor = (glm::vec4)fillComponent["Color"]; fillColor = (glm::vec4)fillComponent["Color"];
} }
std::shared_ptr<SpriteJob> spriteJob = std::shared_ptr<SpriteJob>(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted, isIndicator)); glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, world);
//modelMatrix *= m_Camera->BillboardMatrix();
std::shared_ptr<SpriteJob> spriteJob = std::shared_ptr<SpriteJob>(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted));
jobs.push_back(spriteJob); jobs.push_back(spriteJob);
} }
@@ -184,6 +93,7 @@ bool RenderSystem::isEntityVisible(EntityWrapper& entity)
) { ) {
return false; return false;
} }
return true; return true;
} }
+5 -14
View File
@@ -30,7 +30,6 @@ void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height
currentRenderer->m_LightCullingPass->OnWindowResize(); currentRenderer->m_LightCullingPass->OnWindowResize();
currentRenderer->m_PickingPass->OnWindowResize(); currentRenderer->m_PickingPass->OnWindowResize();
currentRenderer->m_DrawBloomPass->OnWindowResize(); currentRenderer->m_DrawBloomPass->OnWindowResize();
currentRenderer->m_SSAOPass->OnWindowResize();
} }
void Renderer::InitializeWindow() void Renderer::InitializeWindow()
@@ -89,6 +88,9 @@ void Renderer::InitializeShaders()
//m_ExplosionEffectProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ExplosionEffect.frag.glsl"))); //m_ExplosionEffectProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ExplosionEffect.frag.glsl")));
//m_ExplosionEffectProgram->Compile(); //m_ExplosionEffectProgram->Compile();
//m_ExplosionEffectProgram->Link(); //m_ExplosionEffectProgram->Link();
} }
void Renderer::InputUpdate(double dt) void Renderer::InputUpdate(double dt)
@@ -106,14 +108,7 @@ void Renderer::Update(double dt)
void Renderer::Draw(RenderFrame& frame) void Renderer::Draw(RenderFrame& frame)
{ {
GLERROR("PRE");
ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0Ambient Occlusion"); ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0Ambient Occlusion");
ImGui::Combo("CubeMap", &m_CubeMapTexture, "Nevada(512)\0Sky(1024)");
if(m_CubeMapTexture == 0) {
m_CubeMapPass->LoadTextures("Nevada");
} else if (m_CubeMapTexture == 1) {
m_CubeMapPass->LoadTextures("Sky");
}
ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.01f, 5.0f); ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.01f, 5.0f);
ImGui::SliderFloat("SSAO bias", &m_SSAO_Bias, 0.0f, 0.1f); ImGui::SliderFloat("SSAO bias", &m_SSAO_Bias, 0.0f, 0.1f);
@@ -122,7 +117,6 @@ void Renderer::Draw(RenderFrame& frame)
ImGui::SliderInt("SSAO Number of Samples", &m_SSAO_NumOfSamples, 2, 100); ImGui::SliderInt("SSAO Number of Samples", &m_SSAO_NumOfSamples, 2, 100);
ImGui::SliderInt("SSAO Number of Turns", &m_SSAO_NumOfTurns, 0, 50); ImGui::SliderInt("SSAO Number of Turns", &m_SSAO_NumOfTurns, 0, 50);
m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Contrast, m_SSAO_IntensityScale, m_SSAO_NumOfSamples, m_SSAO_NumOfTurns); m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Contrast, m_SSAO_IntensityScale, m_SSAO_NumOfSamples, m_SSAO_NumOfTurns);
GLERROR("SSAO Settings");
//clear buffer 0 //clear buffer 0
glClearColor(0.f, 0.f, 0.f, 0.f); glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -132,9 +126,7 @@ void Renderer::Draw(RenderFrame& frame)
m_PickingPass->ClearPicking(); m_PickingPass->ClearPicking();
m_DrawFinalPass->ClearBuffer(); m_DrawFinalPass->ClearBuffer();
m_DrawBloomPass->ClearBuffer(); m_DrawBloomPass->ClearBuffer();
m_SSAOPass->ClearBuffer();
PerformanceTimer::StopTimer("Renderer-ClearBuffers"); PerformanceTimer::StopTimer("Renderer-ClearBuffers");
GLERROR("ClearBuffers");
for (auto scene : frame.RenderScenes) { for (auto scene : frame.RenderScenes) {
PerformanceTimer::StartTimer("Renderer-Depth"); PerformanceTimer::StartTimer("Renderer-Depth");
m_PickingPass->Draw(*scene); m_PickingPass->Draw(*scene);
@@ -247,10 +239,9 @@ void Renderer::InitializeRenderPasses()
{ {
m_PickingPass = new PickingPass(this, m_EventBroker); m_PickingPass = new PickingPass(this, m_EventBroker);
m_LightCullingPass = new LightCullingPass(this); m_LightCullingPass = new LightCullingPass(this);
m_CubeMapPass = new CubeMapPass(this); m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass);
m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass);
m_DrawScreenQuadPass = new DrawScreenQuadPass(this); m_DrawScreenQuadPass = new DrawScreenQuadPass(this);
m_DrawBloomPass = new DrawBloomPass(this); m_DrawBloomPass = new DrawBloomPass(this);
m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this);
m_SSAOPass = new SSAOPass(this); m_SSAOPass = new SSAOPass(this);
} }
+28 -24
View File
@@ -6,7 +6,6 @@ SSAOPass::SSAOPass(IRenderer* renderer)
m_ScreenQuad = ResourceManager::Load<Model>("Models/Core/ScreenQuad.mesh"); m_ScreenQuad = ResourceManager::Load<Model>("Models/Core/ScreenQuad.mesh");
InitializeTexture();
InitializeBuffer(); InitializeBuffer();
InitializeShaderProgram(); InitializeShaderProgram();
Setting(0.1f, 0.012f, 1.0f, 1.0f, 13, 7); Setting(0.1f, 0.012f, 1.0f, 1.0f, 13, 7);
@@ -29,16 +28,34 @@ void SSAOPass::InitializeShaderProgram()
m_SSAOViewSpaceZProgram->Link(); m_SSAOViewSpaceZProgram->Link();
} }
void SSAOPass::InitializeTexture() {
GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R8, GL_RED, GL_FLOAT);
GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R32F, GL_RED, GL_FLOAT);
}
void SSAOPass::InitializeBuffer() void SSAOPass::InitializeBuffer()
{ {
glGenTextures(1, &m_SSAOTexture);
glBindTexture(GL_TEXTURE_2D, m_SSAOTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height, 0, GL_RED, GL_FLOAT, nullptr);
//glTexImage2D(GL_TEXTURE_2D, 0, GL_R32I, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height, 0, GL_RED_INTEGER, GL_INT, nullptr);
//glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height, 0, GL_RGB, GL_FLOAT, nullptr);
m_SSAOFramBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); m_SSAOFramBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0)));
m_SSAOFramBuffer.Generate(); m_SSAOFramBuffer.Generate();
glGenTextures(1, &m_SSAOViewSpaceZTexture);
glBindTexture(GL_TEXTURE_2D, m_SSAOViewSpaceZTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height, 0, GL_RED, GL_FLOAT, nullptr);
//glTexStorage2D(GL_TEXTURE_2D, MAX_MIP_LEVEL, GL_R32F, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);;
//glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height, GL_RED, GL_FLOAT, nullptr);
//glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0)));
m_SSAOViewSpaceZFramBuffer.Generate(); m_SSAOViewSpaceZFramBuffer.Generate();
} }
@@ -65,17 +82,6 @@ void SSAOPass::Setting(float radius, float bias, float contrast, float intensity
m_NumOfTurns = NumOfTurns; m_NumOfTurns = NumOfTurns;
} }
void SSAOPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const
{
glGenTextures(1, texture);
glBindTexture(GL_TEXTURE_2D, *texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering);
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr);
GLERROR("Texture initialization failed");
}
void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) void SSAOPass::Draw(GLuint depthBuffer, Camera* camera)
{ {
@@ -112,6 +118,11 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera)
(-2.0 / (m_Renderer->GetViewportSize().Height * camera->ProjectionMatrix()[1][1])) (-2.0 / (m_Renderer->GetViewportSize().Height * camera->ProjectionMatrix()[1][1]))
); );
m_SSAOViewSpaceZFramBuffer.Unbind();
//glBindTexture(GL_TEXTURE_2D, m_SSAOViewSpaceZTexture);
//glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height, GL_RED, GL_FLOAT, &m_SSAOViewSpaceZTexture);
//glGenerateMipmap(GL_TEXTURE_2D);
m_SSAOFramBuffer.Bind(); m_SSAOFramBuffer.Bind();
m_SSAOProgram->Bind(); m_SSAOProgram->Bind();
@@ -120,7 +131,7 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera)
glBindTexture(GL_TEXTURE_2D, m_SSAOViewSpaceZTexture); glBindTexture(GL_TEXTURE_2D, m_SSAOViewSpaceZTexture);
// How many pixel there are in a 1m long object 1m away from the camera // How many pixel there are in a 1m long object 1m away from the camera
glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uProjScale"), m_Renderer->GetViewportSize().Height / (-2.0f * glm::tan(camera->FOV() * 0.5f))); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uProjScale"), m_Renderer->GetViewportSize().Height / (-2.0f * glm::tan(glm::radians(camera->FOV()) * 0.5f)));
glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uRadius"), m_Radius); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uRadius"), m_Radius);
glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uBias"), m_Bias); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uBias"), m_Bias);
@@ -136,10 +147,3 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera)
m_DrawBloomPass->ClearBuffer(); m_DrawBloomPass->ClearBuffer();
m_DrawBloomPass->Draw(m_SSAOTexture); m_DrawBloomPass->Draw(m_SSAOTexture);
} }
void SSAOPass::OnWindowResize() {
m_DrawBloomPass->OnWindowResize();
InitializeTexture();
m_SSAOFramBuffer.Generate();
m_SSAOViewSpaceZFramBuffer.Generate();
}
-2
View File
@@ -18,7 +18,6 @@ Texture::Texture(std::string path)
this->Width = img->Width; this->Width = img->Width;
this->Height = img->Height; this->Height = img->Height;
this->Data = img->Data;
GLint format; GLint format;
switch (img->Format) { switch (img->Format) {
@@ -29,7 +28,6 @@ Texture::Texture(std::string path)
format = GL_RGBA; format = GL_RGBA;
break; break;
} }
// Construct the OpenGL texture // Construct the OpenGL texture
glGenTextures(1, &m_Texture); glGenTextures(1, &m_Texture);
+2 -3
View File
@@ -29,7 +29,6 @@ void AmmoPickupSystem::Update(double dt)
newAmmoPickupEntity["Transform"]["Position"] = ammoPickupPosition.Pos; newAmmoPickupEntity["Transform"]["Position"] = ammoPickupPosition.Pos;
newAmmoPickupEntity["AmmoPickup"]["AmmoGain"] = ammoPickupPosition.AmmoGain; newAmmoPickupEntity["AmmoPickup"]["AmmoGain"] = ammoPickupPosition.AmmoGain;
newAmmoPickupEntity["AmmoPickup"]["RespawnTimer"] = ammoPickupPosition.RespawnTimer; newAmmoPickupEntity["AmmoPickup"]["RespawnTimer"] = ammoPickupPosition.RespawnTimer;
m_World->SetParent(newAmmoPickupEntity.ID, ammoPickupPosition.parentID);
//erase the current element (AmmoPickupPosition) //erase the current element (AmmoPickupPosition)
m_ETriggerTouchVector.erase(it); m_ETriggerTouchVector.erase(it);
@@ -70,8 +69,8 @@ bool AmmoPickupSystem::OnTriggerTouch(Events::TriggerTouch& e)
//copy position, ammogain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) //copy position, ammogain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object)
//we need to copy all values since each value can be different for each ammoPickup //we need to copy all values since each value can be different for each ammoPickup
m_ETriggerTouchVector.push_back({ e.Trigger["Transform"]["Position"], e.Trigger["AmmoPickup"]["AmmoGain"], m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["AmmoPickup"]["AmmoGain"],
e.Trigger["AmmoPickup"]["RespawnTimer"], e.Trigger["AmmoPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); e.Trigger["AmmoPickup"]["RespawnTimer"],e.Trigger["AmmoPickup"]["RespawnTimer"] });
//delete the ammopickup //delete the ammopickup
m_World->DeleteEntity(e.Trigger.ID); m_World->DeleteEntity(e.Trigger.ID);
+22 -21
View File
@@ -1,39 +1,32 @@
#include "Systems/CapturePointSystem.h" #include "Systems/CapturePointSystem.h"
#include <algorithm> #include <algorithm>
CapturePointSystem::CapturePointSystem(SystemParams params) CapturePointSystem::CapturePointSystem(SystemParams params)
: System(params) : System(params)
, PureSystem("CapturePoint") , PureSystem("CapturePoint")
{ {
//subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker)
if (!IsClient) { if (IsClient) {
EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch);
EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave);
EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured);
} }
} }
//here all capturepoints will update their component //here all capturepoints will update their component
//NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt //NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt
void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt)
{ {
if (IsClient) { if (!IsClient) {
return; return;
} }
if (m_WinnerWasFound) { if (m_WinnerWasFound) {
return; return;
} }
const int capturePointNumber = cCapturePoint["CapturePointNumber"]; const int capturePointNumber = cCapturePoint["CapturePointNumber"];
const bool hasTeamComponent = capturePointEntity.HasComponent("Team"); const bool hasTeamComponent = capturePointEntity.HasComponent("Team");
if (m_NumberOfCapturePoints != 0) {
if (!m_CapturePointNumberToEntityMap[0].HasComponent("CapturePoint")) {
//if map has changed, the capturepoints has changed, now have to redo them
m_NumberOfCapturePoints = 0;
m_CapturePointNumberToEntityMap.clear();
}
}
//if point doesnt have a teamComponent yet, add one. since: //if point doesnt have a teamComponent yet, add one. since:
//what if capture point has no team -> we cant get/use the team enum from it... //what if capture point has no team -> we cant get/use the team enum from it...
if (!hasTeamComponent) { if (!hasTeamComponent) {
@@ -78,7 +71,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp
std::map<std::string, int> nextPossibleCapturePoint; std::map<std::string, int> nextPossibleCapturePoint;
nextPossibleCapturePoint["Red"] = -1; nextPossibleCapturePoint["Red"] = -1;
nextPossibleCapturePoint["Blue"] = -1; nextPossibleCapturePoint["Blue"] = -1;
for (int i = 0; i < m_NumberOfCapturePoints; i++) { for (int i = 0; i < m_NumberOfCapturePoints; i++)
{
if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) {
continue; continue;
} }
@@ -90,7 +84,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp
nextPossibleCapturePoint["Blue"] = i + 1; nextPossibleCapturePoint["Blue"] = i + 1;
} }
} }
for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) { for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--)
{
if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) {
continue; continue;
} }
@@ -105,7 +100,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp
//reset timers and reset the bool that triggers this //reset timers and reset the bool that triggers this
if (m_ResetTimers) { if (m_ResetTimers) {
for (int i = 0; i < m_NumberOfCapturePoints; i++) { for (int i = 0; i < m_NumberOfCapturePoints; i++)
{
ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"];
if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] &&
(int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) {
@@ -120,7 +116,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp
} }
//check how many players are standing inside and are healthy //check how many players are standing inside and are healthy
for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) { for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--)
{
auto triggerTouched = m_ETriggerTouchVector[i - 1]; auto triggerTouched = m_ETriggerTouchVector[i - 1];
if (std::get<1>(triggerTouched) == capturePointEntity) { if (std::get<1>(triggerTouched) == capturePointEntity) {
//some player has touched this - lets figure out: what team, health //some player has touched this - lets figure out: what team, health
@@ -179,8 +176,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp
cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange;
} }
//if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0 //if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0
if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < captureTimeToTakeOver) || if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < 0.0) ||
(ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > -captureTimeToTakeOver)) { (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) {
cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange;
} }
//check if captureTimer > captureTimeToTakeOver and if so change owner and publish the eCaptured event //check if captureTimer > captureTimeToTakeOver and if so change owner and publish the eCaptured event
@@ -198,14 +195,17 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp
//check for possible winCondition = check if the homebase is owned by the other team //check for possible winCondition = check if the homebase is owned by the other team
bool checkForWinner = false; bool checkForWinner = false;
if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) { if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam)
{
checkForWinner = true; checkForWinner = true;
} }
if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) { if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam)
{
checkForWinner = true; checkForWinner = true;
} }
if (checkForWinner && !m_WinnerWasFound) { if (checkForWinner && !m_WinnerWasFound)
{
//publish Win event //publish Win event
Events::Win e; Events::Win e;
e.TeamThatWon = ownedBy; e.TeamThatWon = ownedBy;
@@ -224,7 +224,8 @@ bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e)
bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e) bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e)
{ {
for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) { for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++)
{
auto triggerTouched = m_ETriggerTouchVector[i]; auto triggerTouched = m_ETriggerTouchVector[i];
if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) { if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) {
m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i); m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i);
+31 -104
View File
@@ -12,41 +12,51 @@ DamageIndicatorSystem::DamageIndicatorSystem(SystemParams params)
auto entityFile = ResourceManager::Load<EntityFile>("Schema/Entities/DamageIndicator.xml"); auto entityFile = ResourceManager::Load<EntityFile>("Schema/Entities/DamageIndicator.xml");
} }
void DamageIndicatorSystem::Update(double dt) {
if (!IsServer) {
for (auto& iter = updateDamageIndicatorVector.begin(); iter != updateDamageIndicatorVector.end(); iter++) {
if (!iter->spriteEntity.Valid()) {
updateDamageIndicatorVector.erase(iter);
break;
}
auto angleBetweenVectors = CalculateAngle(LocalPlayer, iter->enemyPosition);
//simply set the rotation z-wise to the angleBetweenVectors
iter->spriteEntity["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors);
}
}
}
bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e)
{ {
if (m_CurrentCamera == EntityID_Invalid) { if (m_CurrentCamera == EntityID_Invalid) {
return false; return false;
} }
//if (e.Victim != LocalPlayer) {
// return false;
//}
if (e.Victim.Valid() && e.Victim != LocalPlayer && !e.Victim.IsChildOf(LocalPlayer)) { if (e.Victim.Valid() && e.Victim != LocalPlayer && !e.Victim.IsChildOf(LocalPlayer)) {
return false; return false;
} }
if (!e.Inflictor.Valid() || !e.Victim.Valid()) { if (!e.Inflictor.Valid() || !e.Victim.Valid()) {
return false; return false;
} }
glm::vec3 inflictorPos = e.Inflictor["Transform"]["Position"]; //grab players direction
//if testing auto playerOrientation = glm::quat((glm::vec3)e.Victim["Transform"]["Orientation"]);
#ifdef INDICATOR_TEST
inflictorPos = DamageIndicatorTest(e.Victim);
#endif
float angleBetweenVectors = CalculateAngle(e.Victim, inflictorPos); //get the position vectors, but ignore the y-height
auto enemyPosition = (glm::vec3)e.Inflictor["Transform"]["Position"];
auto playerPosition = (glm::vec3)e.Victim["Transform"]["Position"];
enemyPosition.y = 0.0f;
playerPosition.y = 0.0f;
//calculate the enemy to player vector
auto enemyPlayerVector = glm::normalize(playerPosition - enemyPosition);
//get angle from players current rotation, this angle is how much you rotate around the y-axis
auto playerAngle = glm::angle(playerOrientation);
auto playerRotationVector = glm::normalize(glm::rotateY(glm::vec3(0, 0, 1), playerAngle));
//dot product of players direction-vector and enemys-to-playervector will give the cos of the angle between the vectors
auto playerRotationDot = glm::dot(playerRotationVector, enemyPlayerVector);
//to get the angle between the vectors just do cos-inverse
auto angleBetweenVectors = glm::acos(playerRotationDot);
//rotate the direction-vector 90 degrees to get the players side-vector
auto playerSideVector = glm::normalize(glm::rotateY(glm::vec3(0, 0, 1), playerAngle + 1.57f));
//dot of sidevector positive = enemy is on the right side, dot sidevector negative = left side
auto playerSideVectorDot = glm::dot(playerSideVector, enemyPlayerVector);
if (playerSideVectorDot < 0) {
angleBetweenVectors = -angleBetweenVectors;
}
//load & set the "2d" sprite //load & set the "2d" sprite
auto entityFile = ResourceManager::Load<EntityFile>("Schema/Entities/DamageIndicator.xml"); auto entityFile = ResourceManager::Load<EntityFile>("Schema/Entities/DamageIndicator.xml");
@@ -57,10 +67,6 @@ bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e)
//simply set the rotation z-wise to the angleBetweenVectors //simply set the rotation z-wise to the angleBetweenVectors
spriteWrapper["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors); spriteWrapper["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors);
if (!IsServer) {
updateDamageIndicatorVector.emplace_back(spriteWrapper, inflictorPos);
}
return true; return true;
} }
@@ -68,82 +74,3 @@ bool DamageIndicatorSystem::OnSetCamera(const Events::SetCamera& e) {
m_CurrentCamera = e.CameraEntity.ID; m_CurrentCamera = e.CameraEntity.ID;
return true; return true;
} }
float DamageIndicatorSystem::CalculateAngle(EntityWrapper player, glm::vec3 enemyPos) {
//grab players direction
auto playerOrientation = glm::quat((glm::vec3)player["Transform"]["Orientation"]);
//get the position vectors, but ignore the y-height
auto enemyPosition = enemyPos;
auto playerPosition = (glm::vec3)player["Transform"]["Position"];
enemyPosition.y = 0.0f;
playerPosition.y = 0.0f;
//calculate the enemy to player vector
auto enemyPlayerVector = glm::normalize(playerPosition - enemyPosition);
//get the rotationvector relative to the z-axis
auto rotationVectorVec3 = glm::vec3(glm::toMat4(Transform::AbsoluteOrientation(player))*glm::vec4(0, 0, 1, 0));
//rotate the direction-vector 90 degrees to get the players side-vector
auto playerSideVector = glm::vec3(glm::rotateY(rotationVectorVec3, 1.57f));
//dot product of players direction-vector and enemys-to-playervector will give the cos of the angle between the vectors
auto playerRotationDot = glm::dot(rotationVectorVec3, enemyPlayerVector);
//to get the angle between the vectors just do cos-inverse
auto angleBetweenVectors = glm::acos(playerRotationDot);
//dot of sidevector positive = enemy is on the right side, dot sidevector negative = left side
auto playerSideVectorDot = glm::dot(playerSideVector, enemyPlayerVector);
if (playerSideVectorDot < 0) {
angleBetweenVectors = -angleBetweenVectors;
}
return angleBetweenVectors;
}
#ifdef INDICATOR_TEST
glm::vec3 DamageIndicatorSystem::DamageIndicatorTest(EntityWrapper player) {
auto currentPos = (glm::vec3)player["Transform"]["Position"];
auto testVar = 1;
auto testVar2 = 1;
if (m_TestVar % 4 == 0) {
testVar = -1;
testVar2 = 1;
}
if (m_TestVar % 4 == 1) {
testVar = 1;
testVar2 = 1;
}
if (m_TestVar % 4 == 2) {
testVar *= -1;
testVar2 = -1;
}
if (m_TestVar % 4 == 3) {
testVar = 1;
testVar2 = -1;
}
m_TestVar++;
auto inflictorPos = glm::vec3(currentPos.x + testVar*6.0f, currentPos.y, currentPos.z + testVar2*6.0f);
//load the explosioneffect XML
auto deathEffect = ResourceManager::Load<EntityFile>("Schema/Entities/PlayerDeathExplosionWithCamera.xml");
EntityFileParser parser(deathEffect);
EntityID deathEffectID = parser.MergeEntities(m_World);
EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID);
//components that we need from player
auto playerModel = player.FirstChildByName("PlayerModel");
auto playerEntityModel = playerModel["Model"];
auto playerEntityAnimation = playerModel["Animation"];
//copy the data from player to explosioneffectmodel
playerEntityModel.Copy(deathEffectEW["Model"]);
playerEntityAnimation.Copy(deathEffectEW["Animation"]);
//copy the models position,orientation
deathEffectEW["Transform"]["Position"] = inflictorPos;
deathEffectEW["Transform"]["Orientation"] = (glm::vec3)player["Transform"]["Orientation"];
return inflictorPos;
}
#endif
+1 -2
View File
@@ -29,7 +29,6 @@ void PickupSpawnSystem::Update(double dt)
newHealthPickupEntity["Transform"]["Position"] = healthPickupPosition.Pos; newHealthPickupEntity["Transform"]["Position"] = healthPickupPosition.Pos;
newHealthPickupEntity["HealthPickup"]["HealthGain"] = healthPickupPosition.HealthGain; newHealthPickupEntity["HealthPickup"]["HealthGain"] = healthPickupPosition.HealthGain;
newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = healthPickupPosition.RespawnTimer; newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = healthPickupPosition.RespawnTimer;
m_World->SetParent(newHealthPickupEntity.ID, healthPickupPosition.parentID);
//erase the current element (healthPickupPosition) //erase the current element (healthPickupPosition)
m_ETriggerTouchVector.erase(it); m_ETriggerTouchVector.erase(it);
@@ -59,7 +58,7 @@ bool PickupSpawnSystem::OnTriggerTouch(Events::TriggerTouch& e)
//copy position, healthgain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) //copy position, healthgain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object)
//we need to copy all values since each value can be different for each healthPickup //we need to copy all values since each value can be different for each healthPickup
m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["HealthPickup"]["HealthGain"], m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["HealthPickup"]["HealthGain"],
e.Trigger["HealthPickup"]["RespawnTimer"],e.Trigger["HealthPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); e.Trigger["HealthPickup"]["RespawnTimer"],e.Trigger["HealthPickup"]["RespawnTimer"] });
//delete the healthpickup //delete the healthpickup
m_World->DeleteEntity(e.Trigger.ID); m_World->DeleteEntity(e.Trigger.ID);
+3 -2
View File
@@ -33,8 +33,9 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player)
EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID);
//components that we need from player //components that we need from player
auto playerCamera = player.FirstChildByName("Camera");
auto playerModel = player.FirstChildByName("PlayerModel"); auto playerModel = player.FirstChildByName("PlayerModel");
if (!playerModel.Valid()) { if (!playerCamera.Valid() || !playerModel.Valid()) {
return; return;
} }
if (!playerModel.HasComponent("Model") || !playerModel.HasComponent("Animation")) { if (!playerModel.HasComponent("Model") || !playerModel.HasComponent("Animation")) {
@@ -43,7 +44,7 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player)
auto playerEntityModel = playerModel["Model"]; auto playerEntityModel = playerModel["Model"];
auto playerEntityAnimation = playerModel["Animation"]; auto playerEntityAnimation = playerModel["Animation"];
//copy the data from player to explosioneffectmodel //copy the data from player to explisioneffectmodel
playerEntityModel.Copy(deathEffectEW["Model"]); playerEntityModel.Copy(deathEffectEW["Model"]);
playerEntityAnimation.Copy(deathEffectEW["Animation"]); playerEntityAnimation.Copy(deathEffectEW["Animation"]);
//freeze the animation //freeze the animation
+14 -40
View File
@@ -4,7 +4,6 @@ PlayerMovementSystem::PlayerMovementSystem(SystemParams params)
: System(params) : System(params)
{ {
EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned);
EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &PlayerMovementSystem::OnDoubleJump);
} }
PlayerMovementSystem::~PlayerMovementSystem() PlayerMovementSystem::~PlayerMovementSystem()
@@ -17,15 +16,7 @@ PlayerMovementSystem::~PlayerMovementSystem()
void PlayerMovementSystem::Update(double dt) void PlayerMovementSystem::Update(double dt)
{ {
updateMovementControllers(dt); updateMovementControllers(dt);
if (IsServer) { updateVelocity(dt);
for (auto& kv : m_PlayerInputControllers) {
updateVelocity(kv.first, dt);
}
} else {
if (LocalPlayer.Valid()) {
updateVelocity(LocalPlayer, dt);
}
}
} }
void PlayerMovementSystem::updateMovementControllers(double dt) void PlayerMovementSystem::updateMovementControllers(double dt)
@@ -37,6 +28,7 @@ void PlayerMovementSystem::updateMovementControllers(double dt)
if (!player.Valid()) { if (!player.Valid()) {
continue; continue;
} }
// Aim pitch // Aim pitch
EntityWrapper cameraEntity = player.FirstChildByName("Camera"); EntityWrapper cameraEntity = player.FirstChildByName("Camera");
if (cameraEntity.Valid()) { if (cameraEntity.Valid()) {
@@ -122,14 +114,15 @@ void PlayerMovementSystem::updateMovementControllers(double dt)
if (isOnGround) { if (isOnGround) {
controller->SetDoubleJumping(false); controller->SetDoubleJumping(false);
} else { } else {
// If IsServer and network is off this will not work
if (IsClient) { if (IsClient) {
//put a hexagon at the players feet //put a hexagon at the players feet
spawnHexagon(player); auto hexagonEffect = ResourceManager::Load<EntityFile>("Schema/Entities/DoubleJumpHexagon.xml");
EntityFileParser parser(hexagonEffect);
EntityID hexagonEffectID = parser.MergeEntities(m_World);
EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID);
hexagonEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"];
controller->SetDoubleJumping(true); controller->SetDoubleJumping(true);
// Publish event for client to listen to
Events::DoubleJump e; Events::DoubleJump e;
e.entityID = player.ID;
m_EventBroker->Publish(e); m_EventBroker->Publish(e);
} }
} }
@@ -228,11 +221,15 @@ void PlayerMovementSystem::updateMovementControllers(double dt)
} }
void PlayerMovementSystem::updateVelocity(EntityWrapper player, double dt) void PlayerMovementSystem::updateVelocity(double dt)
{ {
// Only apply velocity to local player // Only apply velocity to local player
ComponentWrapper& cTransform = player["Transform"]; if (!LocalPlayer.Valid()) {
ComponentWrapper& cPhysics = player["Physics"]; return;
}
ComponentWrapper& cTransform = LocalPlayer["Transform"];
ComponentWrapper& cPhysics = LocalPlayer["Physics"];
glm::vec3& velocity = cPhysics["Velocity"]; glm::vec3& velocity = cPhysics["Velocity"];
bool isOnGround = (bool)cPhysics["IsOnGround"]; bool isOnGround = (bool)cPhysics["IsOnGround"];
@@ -294,26 +291,3 @@ bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e)
} }
return true; return true;
} }
bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e)
{
// If entity does not exist, exit
if (!EntityWrapper(m_World, e.entityID).Valid()) {
return false;
}
// If entity IsLocalPlayer, exit
if (e.entityID == m_LocalPlayer.ID) {
return false;
}
spawnHexagon(EntityWrapper(m_World, e.entityID));
}
void PlayerMovementSystem::spawnHexagon(EntityWrapper target)
{
//put a hexagon at the entitys... feet?
auto hexagonEffect = ResourceManager::Load<EntityFile>("Schema/Entities/DoubleJumpHexagon.xml");
EntityFileParser parser(hexagonEffect);
EntityID hexagonEffectID = parser.MergeEntities(m_World);
EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID);
hexagonEW["Transform"]["Position"] = (glm::vec3)target["Transform"]["Position"];
}
+3 -20
View File
@@ -14,7 +14,6 @@ SoundSystem::SoundSystem(SystemParams params)
EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage);
EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured);
EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch);
EVENT_SUBSCRIBE_MEMBER(m_EPlayerDeath, &SoundSystem::OnPlayerDeath);
} }
} }
@@ -91,9 +90,6 @@ bool SoundSystem::drumTimer(double dt)
bool SoundSystem::OnCaptured(const Events::Captured & e) bool SoundSystem::OnCaptured(const Events::Captured & e)
{ {
if (!LocalPlayer.Valid()) {
return false;
}
int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"];
int team = (int)m_World->GetComponent(LocalPlayer.ID, "Team")["Team"]; int team = (int)m_World->GetComponent(LocalPlayer.ID, "Team")["Team"];
Events::PlaySoundOnEntity ev; Events::PlaySoundOnEntity ev;
@@ -112,12 +108,7 @@ bool SoundSystem::OnCaptured(const Events::Captured & e)
// Testing purposes atm... // Testing purposes atm...
bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e)
{ {
if (!IsClient) { // Only play for clients // Should check for only local players here...
return false;
}
if (LocalPlayer.ID = e.Victim.ID) { // You're local player was the one who took dmg
return false;
}
std::uniform_int_distribution<int> dist(1, 12); std::uniform_int_distribution<int> dist(1, 12);
int rand = dist(generator); int rand = dist(generator);
std::vector<std::string> paths; std::vector<std::string> paths;
@@ -137,16 +128,8 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e)
bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e)
{ {
if (e.Player.ID != LocalPlayer.ID) { Events::PlaySoundOnEntity ev;
return false; ev.EmitterID = LocalPlayer.ID;
}
if (!IsClient) {
return false;
}
// The local player is dead. The local player might be invalid?
// Play the sound from the listener.
// TODO: We might want to hear other players die.
Events::PlayBackgroundMusic ev;
ev.FilePath = "Audio/die/die2.wav"; ev.FilePath = "Audio/die/die2.wav";
m_EventBroker->Publish(ev); m_EventBroker->Publish(ev);
return false; return false;
+1 -1
View File
@@ -36,7 +36,7 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent /
} }
// Find any SpawnPoints existing as children of spawner // Find any SpawnPoints existing as children of spawner
auto children = spawner.World->GetDirectChildren(spawner.ID); auto children = spawner.World->GetChildren(spawner.ID);
std::vector<EntityWrapper> spawnPoints; std::vector<EntityWrapper> spawnPoints;
for (auto kv = children.first; kv != children.second; ++kv) { for (auto kv = children.first; kv != children.second; ++kv) {
const EntityID& child = kv->second; const EntityID& child = kv->second;
+1
View File
@@ -6,6 +6,7 @@
#include "Core/EventBroker.h" #include "Core/EventBroker.h"
#include "Rendering/Renderer.h" #include "Rendering/Renderer.h"
#include "Core/InputManager.h" #include "Core/InputManager.h"
#include "GUI/Frame.h"
#include "Core/World.h" #include "Core/World.h"
#include "Input/InputProxy.h" #include "Input/InputProxy.h"
#include "Input/KeyboardInputHandler.h" #include "Input/KeyboardInputHandler.h"