diff --git a/include/Engine/Collision/CollisionSystem.h b/include/Engine/Collision/CollisionSystem.h index 9cd2fe63..19adea35 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -24,6 +24,7 @@ public: private: Octree* m_Octree; std::vector m_OctreeResult; + std::unordered_map m_PrevPositions; }; #endif \ No newline at end of file diff --git a/include/Engine/Core/ECaptured.h b/include/Engine/Core/ECaptured.h index d891c7b0..48771cd7 100644 --- a/include/Engine/Core/ECaptured.h +++ b/include/Engine/Core/ECaptured.h @@ -12,7 +12,8 @@ namespace Events struct Captured : Event { int TeamNumberThatCapturedCapturePoint; - EntityID CapturePointID; + EntityID CapturePointTakenID; + EntityWrapper NextCapturePoint; }; } diff --git a/include/Engine/Core/EntityWrapper.h b/include/Engine/Core/EntityWrapper.h index b0e65d9e..8ece8e59 100644 --- a/include/Engine/Core/EntityWrapper.h +++ b/include/Engine/Core/EntityWrapper.h @@ -29,16 +29,22 @@ struct EntityWrapper EntityWrapper Parent(); EntityWrapper FirstChildByName(const std::string& name); EntityWrapper FirstParentWithComponent(const std::string& componentType); + EntityWrapper Clone(EntityWrapper parent = EntityWrapper::Invalid); + std::vector ChildrenWithComponent(const std::string& componentType); + void DeleteChildren(); bool IsChildOf(EntityWrapper potentialParent); bool Valid() const; ComponentWrapper operator[](const char* componentName); + ComponentWrapper operator[](const std::string& componentName); bool operator==(const EntityWrapper& e) const; bool operator!=(const EntityWrapper& e) const; explicit operator EntityID() const; private: EntityWrapper firstChildByNameRecursive(const std::string& name, EntityID parent); + EntityWrapper cloneRecursive(EntityWrapper entity, EntityWrapper parent); + void childrenWithComponentRecursive(const std::string& componentType, EntityWrapper& entity, std::vector& childrenWithComponent); }; namespace std diff --git a/include/Engine/Core/System.h b/include/Engine/Core/System.h index 1a387855..23d5f9a5 100644 --- a/include/Engine/Core/System.h +++ b/include/Engine/Core/System.h @@ -68,7 +68,7 @@ protected: const std::string m_ComponentType; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) = 0; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) = 0; }; class ImpureSystem : public virtual System diff --git a/include/Engine/Core/World.h b/include/Engine/Core/World.h index 1604df37..c9f738ce 100644 --- a/include/Engine/Core/World.h +++ b/include/Engine/Core/World.h @@ -40,7 +40,7 @@ public: // Change the parent of an entity void SetParent(EntityID entity, EntityID parent); // Get children of an entity - const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetChildren(EntityID entity); + const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetDirectChildren(EntityID entity); // Get all component pools const std::unordered_map& GetComponentPools() const { return m_ComponentPools; } // Get the entity children map diff --git a/include/Engine/Editor/EditorCameraInputController.h b/include/Engine/Editor/EditorCameraInputController.h index 4c139e01..6cb31d99 100644 --- a/include/Engine/Editor/EditorCameraInputController.h +++ b/include/Engine/Editor/EditorCameraInputController.h @@ -104,6 +104,11 @@ protected: if (!m_Enabled) { return false; } + + ImGuiIO& io = ImGui::GetIO(); + if (io.WantCaptureMouse || io.WantCaptureKeyboard) { + return false; + } m_SpeedMultiplier += e.DeltaY * (0.1 * m_SpeedMultiplier); m_Config->Set("Editor.CameraSpeed", m_SpeedMultiplier); diff --git a/include/Engine/Editor/EditorGUI.h b/include/Engine/Editor/EditorGUI.h index 7a0289c6..57574e66 100644 --- a/include/Engine/Editor/EditorGUI.h +++ b/include/Engine/Editor/EditorGUI.h @@ -73,6 +73,12 @@ public: // Called when the user means to rename an entity. typedef std::function OnEntityChangeName_t; 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 OnEntityPaste_t; + void SetEntityPasteCallback(OnEntityPaste_t f) { m_OnEntityPaste = f; } // Called when the user means to attach a new component to an entity. typedef std::function OnComponentAttach_t; void SetComponentAttachCallback(OnComponentAttach_t f) { m_OnComponentAttach = f; } @@ -111,6 +117,7 @@ private: std::string m_DroppedFile = ""; bool m_Paused = false; bool m_MouseLocked = false; + EntityWrapper m_CopyTarget = EntityWrapper::Invalid; // Callbacks OnEntitySelectedCallback_t m_OnEntitySelected = nullptr; @@ -124,6 +131,7 @@ private: OnComponentDelete_t m_OnComponentDelete = nullptr; OnWidgetMode_t m_OnWidgetMode = nullptr; OnWidgetSpace_t m_OnWidgetSpace = nullptr; + OnEntityPaste_t m_OnEntityPaste = nullptr; // Events EventRelay m_EKeyDown; diff --git a/include/Engine/Editor/EditorSystem.h b/include/Engine/Editor/EditorSystem.h index fcaa2e47..06ee53b6 100644 --- a/include/Engine/Editor/EditorSystem.h +++ b/include/Engine/Editor/EditorSystem.h @@ -56,6 +56,7 @@ private: void OnEntityDelete(EntityWrapper entity); void OnEntityChangeParent(EntityWrapper entity, EntityWrapper parent); void OnEntityChangeName(EntityWrapper entity, const std::string& name); + EntityWrapper OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent); void OnComponentAttach(EntityWrapper entity, const std::string& componentType); void OnComponentDelete(EntityWrapper entity, const std::string& componentType); void OnWidgetSpace(EditorGUI::WidgetSpace widgetSpace); diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index 7dc24a2c..d86af088 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -27,7 +27,7 @@ public: virtual bool OnCommand(const Events::InputCommand& e) override; virtual void Reset(); - void AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer); + void AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer, double& assaultDashCoolDownTimer); virtual bool AssaultDashDoubleTapped() const { return m_AssaultDashDoubleTapped; } virtual bool PlayerIsDashing() const { return m_PlayerIsDashing; } @@ -41,7 +41,6 @@ protected: bool m_Crouching = false; //assault dash membervariables - needed to calculate the doubletap- and dashlogic double m_AssaultDashDoubleTapDeltaTime = 0.0; - double m_AssaultDashCoolDownTimer = 0.0; //i will let m_AssaultDashDoubleTapSensitivityTimer stay hardcoded, its not really a gamevariable (more an inputvariable), //and its very unlikely that someone wants to change that value const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f; @@ -191,21 +190,21 @@ bool FirstPersonInputController::OnLockMouse(const Events::LockMou } template -void FirstPersonInputController::AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer) { +void FirstPersonInputController::AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer, double& assaultDashCoolDownTimer) { m_AssaultDashDoubleTapDeltaTime += dt; - m_AssaultDashCoolDownTimer -= dt; + assaultDashCoolDownTimer -= dt; //cooldown = assaultDashCoolDownMaxTimer sec, pretend the dash lasts 0.25 sec (for friction to do its work) - if (m_AssaultDashCoolDownTimer > (assaultDashCoolDownMaxTimer - 0.25f)) { + if (assaultDashCoolDownTimer > (assaultDashCoolDownMaxTimer - 0.25f)) { m_PlayerIsDashing = true; } else { m_PlayerIsDashing = false; } //dashing with shift - if (m_ShiftDashing && m_AssaultDashCoolDownTimer <= 0.0f) { + if (m_ShiftDashing && assaultDashCoolDownTimer <= 0.0f) { //player is dashing with shift //the wanted-direction is set in playermovement already so we dont need to check what direction we want to dash in! - m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; + assaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; m_AssaultDashDoubleTapped = true; m_AssaultDashDoubleTapDeltaTime = 0.f; return; @@ -227,7 +226,7 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool } m_ValidDoubleTap = false; - if (!(m_AssaultDashCoolDownTimer <= 0.0f)) { + if (!(assaultDashCoolDownTimer <= 0.0f)) { //if we cant dash at the moment, then just reset the tap-sensitivity-timer m_AssaultDashDoubleTapDeltaTime = 0.f; return; @@ -235,7 +234,7 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool //ok, we have a valid tap, lets do it m_AssaultDashDoubleTapped = true; m_AssaultDashDoubleTapDeltaTime = 0.f; - m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; + assaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; Events::DashAbility e; m_EventBroker->Publish(e); diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index d08b863a..c407f7f8 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -19,11 +19,14 @@ #include "Core/World.h" #include "Core/EventBroker.h" #include "Core/ConfigFile.h" +#include "Core/EPlayerDeath.h" #include "Input/EInputCommand.h" #include "Core/EPlayerDamage.h" +#include "../Game/Events/EDoubleJump.h" #include "Network/EInterpolate.h" #include "Network/SnapshotFilter.h" #include "Core/EPlayerSpawned.h" +#include "Core/EAmmoPickup.h" #include "Network/ESearchForServers.h" struct ServerInfo @@ -47,7 +50,9 @@ public: void Connect(std::string address, int port); void Update() override; - +private: + UDPClient m_Unreliable; + TCPClient m_Reliable; std::vector m_PlayerSpawnEvents; void parseSpawnEvents(); // Save for children @@ -101,9 +106,10 @@ public: void parseEntityDeletion(Packet& packet); void parsePlayerDamage(Packet& packet); void parseComponentDeletion(Packet& packet); - void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); + void parseDoubleJump(Packet& packet); + void parseAmmoPickup(Packet& packet); + void InterpolateFields(Packet& packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void parseSnapshot(Packet& packet); - void UpdateLocalCapturePointHUD(EntityWrapper capturePointHUD); void identifyPacketLoss(); void hasServerTimedOut(); EntityID createPlayer(); @@ -127,11 +133,10 @@ public: EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned& e); EventRelay< Client, Events::SearchForServers> m_ESearchForServers; + EventRelay m_EDoubleJump; + bool OnDoubleJump(Events::DoubleJump & e); bool OnSearchForServers(const Events::SearchForServers& e); -private: - UDPClient m_Unreliable; UDPClient m_ServerlistRequest; - TCPClient m_Reliable; std::vector m_Serverlist; bool m_SearchingForServers = false; std::clock_t m_StartSearchTime; diff --git a/include/Engine/Network/MessageType.h b/include/Engine/Network/MessageType.h index 93695063..bf773618 100644 --- a/include/Engine/Network/MessageType.h +++ b/include/Engine/Network/MessageType.h @@ -19,7 +19,9 @@ enum class MessageType EntityDeleted, ComponentDeleted, PlayerTransform, + OnDoubleJump, ServerlistRequest, + AmmoPickup, Invalid }; diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 542792b2..3c956ed9 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -8,7 +8,6 @@ #include "Network/TCPServer.h" #include "Network/UDPServer.h" -#include "Network/UDPClient.h" //LOL #include "Network/MessageType.h" #include "Network/PlayerDefinition.h" #include "Core/World.h" @@ -18,8 +17,10 @@ #include "Core/EPlayerDamage.h" #include "Network/EPlayerDisconnected.h" #include "Core/EPlayerSpawned.h" +#include "../Game/Events/EDoubleJump.h" #include "Core/EEntityDeleted.h" #include "Core/EComponentDeleted.h" +#include "Core/EAmmoPickup.h" class Server : public Network { @@ -81,13 +82,14 @@ private: void parseOnInputCommand(Packet& packet); void parseClientPing(); void parsePing(); - void parseUDPConnect(Packet & packet); - void parseTCPConnect(Packet & packet); + bool parseDoubleJump(Packet& packet); + void parseUDPConnect(Packet& packet); + void parseTCPConnect(Packet& packet); void parseDisconnect(); void parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint); bool shouldSendToClient(EntityWrapper childEntity); - // Debug event + // Events EventRelay m_EInputCommand; bool OnInputCommand(const Events::InputCommand& e); EventRelay m_EPlayerSpawned; @@ -98,6 +100,8 @@ private: bool OnComponentDeleted(const Events::ComponentDeleted& e); EventRelay m_EPlayerDamage; bool OnPlayerDamage(const Events::PlayerDamage& e); + EventRelay m_EAmmoPickup; + bool OnAmmoPickup(const Events::AmmoPickup& e); }; #endif diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 66caef08..55631a22 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -25,10 +25,9 @@ private: std::unique_ptr acceptor; boost::shared_ptr lastReceivedSocket; - void handle_accept(boost::shared_ptr socket, - int& nextPlayerID, std::map& connectedPlayers, - const boost::system::error_code& error); int readBuffer(PlayerDefinition& playerDefinition); + PlayerID getPlayerIDFromEndpoint(const std::map& connectedPlayers, + boost::asio::ip::address address, unsigned short port); int GetPort(); std::string GetAddress(); int m_Port = 0; diff --git a/include/Engine/Rendering/DrawBloomPass.h b/include/Engine/Rendering/DrawBloomPass.h index 07c90e23..ee3a8489 100644 --- a/include/Engine/Rendering/DrawBloomPass.h +++ b/include/Engine/Rendering/DrawBloomPass.h @@ -12,7 +12,7 @@ class DrawBloomPass { public: - DrawBloomPass(IRenderer* renderer /* ,Texture or finalpass*/ ); + DrawBloomPass(IRenderer* renderer, ConfigFile* config); ~DrawBloomPass() { } void InitializeTextures(); void InitializeFrameBuffers(); @@ -23,26 +23,33 @@ public: void FillGaussianBuffer(FrameBuffer* fb); void Draw(GLuint texture); + void ChangeQuality(int quality); void OnWindowResize(); //Getters //Return the blurred result of the texture that was sent into draw - GLuint GaussianTexture() const { return m_GaussianTexture_vert; } + GLuint GaussianTexture() const { + if (m_Quality == 0) { + return m_BlackTexture->m_Texture; + } else { + return m_GaussianTexture_vert; + } + } private: - void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; - - Texture* m_WhiteTexture; + Texture* m_BlackTexture; Model* m_ScreenQuad; const IRenderer* m_Renderer; + ConfigFile* m_Config; //const LightCullingPass* m_LightCullingPass - GLuint m_iterations = 9; + int m_Iterations; + int m_Quality = 0; - GLuint m_GaussianTexture_horiz; - GLuint m_GaussianTexture_vert; + GLuint m_GaussianTexture_horiz = 0; + GLuint m_GaussianTexture_vert = 0; FrameBuffer m_GaussianFrameBuffer_horiz; FrameBuffer m_GaussianFrameBuffer_vert; diff --git a/include/Engine/Rendering/DrawColorCorrectionPass.h b/include/Engine/Rendering/DrawColorCorrectionPass.h index 231e2d33..fcde73d7 100644 --- a/include/Engine/Rendering/DrawColorCorrectionPass.h +++ b/include/Engine/Rendering/DrawColorCorrectionPass.h @@ -17,7 +17,7 @@ public: void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure); + void Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure); private: const IRenderer* m_Renderer; diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 1800c90e..cfddd5c6 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -5,6 +5,7 @@ #include "DrawFinalPassState.h" #include "LightCullingPass.h" #include "CubeMapPass.h" +#include "SSAOPass.h" #include "FrameBuffer.h" #include "ShaderProgram.h" #include "Util/UnorderedMapVec2.h" @@ -14,34 +15,28 @@ class DrawFinalPass { public: - DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass); + DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, SSAOPass* ssaoPass); ~DrawFinalPass() { } void InitializeTextures(); void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(RenderScene& scene, GLuint SSAOTexture); + void Draw(RenderScene& scene); void ClearBuffer(); void OnWindowResize(); //Return the texture that is used in later stages to apply the bloom effect GLuint BloomTexture() const { return m_BloomTexture; } - GLuint BloomTextureLowRes() const { return m_BloomTextureLowRes; } //Return the texture with diffuse and lighting of the scene. GLuint SceneTexture() const { return m_SceneTexture; } - GLuint SceneTextureLowRes() const { return m_SceneTextureLowRes; } //Return the framebuffer used in the scene rendering stage. FrameBuffer* FinalPassFrameBuffer() { return &m_FinalPassFrameBuffer; } - FrameBuffer* FinalPassFrameBufferLowRes() { return &m_FinalPassFrameBufferLowRes; } private: - void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; - void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const; - void DrawSprites(std::list>&jobs, RenderScene& scene); - void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene, GLuint SSAOTexture); - void DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene); + void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene); + void DrawModelRenderQueuesWithShieldCheck(std::list>& jobs, RenderScene& scene); void DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene); - void DrawToDepthBuffer(std::list>& jobs, RenderScene& scene); + void DrawToDepthStencilBuffer(std::list>& jobs, RenderScene& scene); void BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); void BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); @@ -56,13 +51,11 @@ private: Texture* m_ErrorTexture; FrameBuffer m_FinalPassFrameBuffer; - FrameBuffer m_FinalPassFrameBufferLowRes; + FrameBuffer m_ShieldDepthFrameBuffer; GLuint m_BloomTexture; GLuint m_SceneTexture; - GLuint m_BloomTextureLowRes; - GLuint m_SceneTextureLowRes; GLuint m_DepthBuffer; - GLuint m_DepthBufferLowRes; + GLuint m_ShieldBuffer; GLuint m_CubeMapTexture; //maqke this component based i guess? @@ -71,22 +64,34 @@ private: const IRenderer* m_Renderer; const LightCullingPass* m_LightCullingPass; const CubeMapPass* m_CubeMapPass; + const SSAOPass* m_SSAOPass; ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; ShaderProgram* m_ExplosionEffectSplatMapProgram; ShaderProgram* m_SpriteProgram; ShaderProgram* m_ForwardPlusSplatMapProgram; - ShaderProgram* m_ShieldToStencilProgram; - ShaderProgram* m_FillDepthBufferProgram; + ShaderProgram* m_FillDepthStencilBufferProgram; + + ShaderProgram* m_ForwardPlusShieldCheckProgram; + ShaderProgram* m_ExplosionEffectShieldCheckProgram; + ShaderProgram* m_ExplosionEffectSplatMapShieldCheckProgram; + ShaderProgram* m_SpriteShieldCheckProgram; + ShaderProgram* m_ForwardPlusSplatMapShieldCheckProgram; + ShaderProgram* m_ForwardPlusSkinnedProgram; ShaderProgram* m_ExplosionEffectSkinnedProgram; ShaderProgram* m_ExplosionEffectSplatMapSkinnedProgram; ShaderProgram* m_ForwardPlusSplatMapSkinnedProgram; - ShaderProgram* m_ShieldToStencilSkinnedProgram; - ShaderProgram* m_FillDepthBufferSkinnedProgram; + ShaderProgram* m_FillDepthStencilBufferSkinnedProgram; + + ShaderProgram* m_ForwardPlusSkinnedShieldCheckProgram; + ShaderProgram* m_ExplosionEffectSkinnedShieldCheckProgram; + ShaderProgram* m_ExplosionEffectSplatMapSkinnedShieldCheckProgram; + ShaderProgram* m_ForwardPlusSplatMapSkinnedShieldCheckProgram; + ShaderProgram* m_FillDepthBufferSkinnedShieldCheckProgram; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/ExplosionEffectJob.h b/include/Engine/Rendering/ExplosionEffectJob.h index 8f339526..695a8dfe 100644 --- a/include/Engine/Rendering/ExplosionEffectJob.h +++ b/include/Engine/Rendering/ExplosionEffectJob.h @@ -15,8 +15,8 @@ struct ExplosionEffectJob : ModelJob { - ExplosionEffectJob(ComponentWrapper explosionEffectComponent, ::Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matGroup, ComponentWrapper modelComponent, ::World* world, glm::vec4 fillColor, float fillPercentage) - : ModelJob(model, camera, matrix, matGroup, modelComponent, world, fillColor, fillPercentage) + ExplosionEffectJob(ComponentWrapper explosionEffectComponent, ::Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matGroup, ComponentWrapper modelComponent, ::World* world, glm::vec4 fillColor, float fillPercentage, bool isShielded) + : ModelJob(model, camera, matrix, matGroup, modelComponent, world, fillColor, fillPercentage, isShielded) { ExplosionOrigin = (glm::vec3)explosionEffectComponent["ExplosionOrigin"]; TimeSinceDeath = (double)explosionEffectComponent["TimeSinceDeath"]; diff --git a/include/Engine/Rendering/IRenderer.h b/include/Engine/Rendering/IRenderer.h index 4441bb7d..2e6f3a97 100644 --- a/include/Engine/Rendering/IRenderer.h +++ b/include/Engine/Rendering/IRenderer.h @@ -5,11 +5,13 @@ #include "../OpenGL.h" #include "../GLM.h" #include "../Core/Util/Rectangle.h" +#include "../Core/ConfigFile.h" #include "Util/ScreenCoords.h" #include "Camera.h" #include "RenderQueue.h" #include "Model.h" #include "../Core/World.h" //So temp +#include "Util/CommonFunctions.h" struct PickData diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index c2a469d2..58993ea1 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -18,7 +18,7 @@ struct ModelJob : RenderJob { - ModelJob(Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matProp, ComponentWrapper modelComponent, World* world, glm::vec4 fillColor, float fillPercentage) + ModelJob(Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matProp, ComponentWrapper modelComponent, World* world, glm::vec4 fillColor, float fillPercentage, bool isShielded) : RenderJob() { Model = model; @@ -117,7 +117,7 @@ struct ModelJob : RenderJob FillColor = fillColor; FillPercentage = fillPercentage; - + IsShielded = isShielded; if (model->IsSkinned()) { Skeleton = Model->m_RawModel->m_Skeleton; @@ -181,7 +181,7 @@ struct ModelJob : RenderJob glm::vec4 FillColor = glm::vec4(0); float FillPercentage = 0.0; - + bool IsShielded; void CalculateHash() override { Hash = ShaderID << 20 + ModelID << 10 + TextureID; diff --git a/include/Engine/Rendering/PickingPass.h b/include/Engine/Rendering/PickingPass.h index f6434781..df99a615 100644 --- a/include/Engine/Rendering/PickingPass.h +++ b/include/Engine/Rendering/PickingPass.h @@ -28,15 +28,13 @@ public: const ShaderProgram& PickingProgram() const { return *m_PickingProgram; } //const std::unordered_map& PickingColorsToEntity() const { return m_PickingColorsToEntity; } GLuint PickingTexture() const { return m_PickingTexture; } - GLuint DepthBuffer() const { return m_DepthBuffer; } + GLuint* DepthBuffer() { return &m_DepthBuffer; } const FrameBuffer& PickingBuffer() const { return m_PickingBuffer; } PickData Pick(glm::vec2 screenCoord); private: - void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; - EventBroker* m_EventBroker; const IRenderer* m_Renderer; diff --git a/include/Engine/Rendering/RenderQueue.h b/include/Engine/Rendering/RenderQueue.h index 647adab8..e3c46e85 100644 --- a/include/Engine/Rendering/RenderQueue.h +++ b/include/Engine/Rendering/RenderQueue.h @@ -24,7 +24,6 @@ struct RenderScene std::list> OpaqueObjects; std::list> TransparentObjects; std::list> OpaqueShieldedObjects; - std::list> TransparentShieldedObjects; std::list> ShieldObjects; std::list> SpriteJob; std::list> PointLight; @@ -41,7 +40,6 @@ struct RenderScene Jobs.OpaqueObjects.clear(); Jobs.TransparentObjects.clear(); Jobs.OpaqueShieldedObjects.clear(); - Jobs.TransparentShieldedObjects.clear(); Jobs.ShieldObjects.clear(); Jobs.SpriteJob.clear(); Jobs.DirectionalLight.clear(); diff --git a/include/Engine/Rendering/RenderState.h b/include/Engine/Rendering/RenderState.h index c1886247..24f908a9 100644 --- a/include/Engine/Rendering/RenderState.h +++ b/include/Engine/Rendering/RenderState.h @@ -24,6 +24,8 @@ public: bool StencilFunc(GLenum func, GLint ref, GLuint mask); bool StencilMask(GLuint mask); bool DepthMask(GLboolean flag); + bool DepthFunc(GLenum func); + bool AlphaFunc(GLenum func, GLclampf thresholder); private: std::vector> m_ResetFunctions; diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index f3a6bf31..a64a4aa3 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -32,8 +32,9 @@ class Renderer : public IRenderer static void glfwFrameBufferCallback(GLFWwindow* window, int width, int height); public: - Renderer(EventBroker* eventBroker) - : m_EventBroker(eventBroker) + Renderer(EventBroker* eventBroker, ConfigFile* config) + : m_EventBroker(eventBroker) + , m_Config(config) { } virtual void Initialize() override; @@ -47,6 +48,7 @@ private: //----------------------Variables----------------------// static std::unordered_map m_WindowToRenderer; + ConfigFile* m_Config; EventBroker* m_EventBroker; TextPass* m_TextPass; @@ -61,12 +63,8 @@ private: int m_DebugTextureToDraw = 0; int m_CubeMapTexture = 0; bool m_ResizeWindow = false; - float m_SSAO_Radius = 1.0f; - float m_SSAO_Bias = 0.05f; - float m_SSAO_Contrast = 1.5f; - float m_SSAO_IntensityScale = 1.0f; - int m_SSAO_NumOfSamples = 24; - int m_SSAO_NumOfTurns = 7; + int m_SSAO_Quality = 0; + int m_GLOW_Quality = 2; PickingPass* m_PickingPass; LightCullingPass* m_LightCullingPass; diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h index 792d1d82..1cb28009 100644 --- a/include/Engine/Rendering/SSAOPass.h +++ b/include/Engine/Rendering/SSAOPass.h @@ -13,18 +13,32 @@ class SSAOPass { public: - SSAOPass(IRenderer* rendere); - ~SSAOPass() { - delete m_DrawBloomPass; - }; + SSAOPass(IRenderer* renderer, ConfigFile* config); + ~SSAOPass() { }; + + void ChangeQuality(int quality); 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, int iterations, int quality); void ClearBuffer(); void OnWindowResize(); //Return the SSAO of the texture sent to Draw - GLuint SSAOTexture() const { return m_DrawBloomPass->GaussianTexture(); } + GLuint SSAOTexture() const { + if (m_Quality == 0) { + return m_WhiteTexture->m_Texture; + } else { + return m_Gaussian_vert; + } + } + + int TextureQuality() const { + if (m_Quality == 0) { + return 13; + } else { + return m_TextureQuality; + } + } private: void InitializeTexture(); @@ -32,14 +46,13 @@ private: void InitializeShaderProgram(); void InitializeBuffer(); - void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; - //void blurHorizontal(GLuint depthBuffer); //void blurVertical(GLuint depthBuffer); Model* m_ScreenQuad; const IRenderer* m_Renderer; + ConfigFile* m_Config; float m_Radius; float m_Bias; @@ -47,17 +60,28 @@ private: float m_IntensityScale; int m_NumOfSamples; int m_NumOfTurns; + int m_Iterations; + int m_TextureQuality; + int m_Quality = 0; - GLuint m_SSAOTexture; + Texture* m_WhiteTexture; + + GLuint m_SSAOTexture = 0; FrameBuffer m_SSAOFramBuffer; - GLuint m_SSAOViewSpaceZTexture; + GLuint m_SSAOViewSpaceZTexture = 0; FrameBuffer m_SSAOViewSpaceZFramBuffer; + GLuint m_Gaussian_horiz = 0; + GLuint m_Gaussian_vert = 0; + + FrameBuffer m_GaussianFrameBuffer_horiz; + FrameBuffer m_GaussianFrameBuffer_vert; + ShaderProgram* m_SSAOProgram; ShaderProgram* m_SSAOViewSpaceZProgram; - - DrawBloomPass* m_DrawBloomPass; + ShaderProgram* m_GaussianProgram_horiz; + ShaderProgram* m_GaussianProgram_vert; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/Util/CommonFunctions.h b/include/Engine/Rendering/Util/CommonFunctions.h index e178f52d..1ed3d82a 100644 --- a/include/Engine/Rendering/Util/CommonFunctions.h +++ b/include/Engine/Rendering/Util/CommonFunctions.h @@ -9,6 +9,10 @@ namespace CommonFunctions { Texture* LoadTexture(std::string path, bool threaded); +void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type); +void GenerateMultiSampleTexture(GLuint* texture, int numSamples, glm::vec2 dimensions, GLint internalFormat); +void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps); +void DeleteTexture(GLuint* texture); }; #endif \ No newline at end of file diff --git a/include/Game/Events/EDoubleJump.h b/include/Game/Events/EDoubleJump.h index 767d5b39..f5cad1fd 100644 --- a/include/Game/Events/EDoubleJump.h +++ b/include/Game/Events/EDoubleJump.h @@ -8,7 +8,7 @@ namespace Events struct DoubleJump : public Event { - + EntityID entityID; }; } diff --git a/include/Game/Systems/AmmoPickupSystem.h b/include/Game/Systems/AmmoPickupSystem.h index a54b8495..e4a6df59 100644 --- a/include/Game/Systems/AmmoPickupSystem.h +++ b/include/Game/Systems/AmmoPickupSystem.h @@ -20,12 +20,15 @@ public: private: EventRelay m_ETriggerTouch; bool OnTriggerTouch(Events::TriggerTouch& e); + EventRelay m_EAmmoPickup; + bool OnAmmoPickup(Events::AmmoPickup& e); struct NewAmmoPickup { glm::vec3 Pos; double AmmoGain; double RespawnTimer; double DecreaseThisRespawnTimer; + EntityID parentID; }; std::vector m_ETriggerTouchVector; }; diff --git a/include/Game/Systems/CapturePointSystem.h b/include/Game/Systems/CapturePointSystem.h index 34a23e14..3cf72e15 100644 --- a/include/Game/Systems/CapturePointSystem.h +++ b/include/Game/Systems/CapturePointSystem.h @@ -42,9 +42,9 @@ private: int m_NumberOfCapturePoints = 0; std::map m_CapturePointNumberToEntityMap; - //std::vector - bool m_ResetTimers = false; + bool m_RecentlyCapturedNeedNextCapturePointNow = false; + Events::Captured m_CapturedEvent; //vectors which will keep track of enter/leave changes std::vector> m_ETriggerTouchVector; diff --git a/include/Game/Systems/PickupSpawnSystem.h b/include/Game/Systems/PickupSpawnSystem.h index f912e8ff..66c5f630 100644 --- a/include/Game/Systems/PickupSpawnSystem.h +++ b/include/Game/Systems/PickupSpawnSystem.h @@ -27,6 +27,7 @@ private: double HealthGain; double RespawnTimer; double DecreaseThisRespawnTimer; + EntityID parentID; }; std::vector m_ETriggerTouchVector; }; diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index d9006504..92aa1915 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -34,9 +34,13 @@ private: glm::vec3 m_LastPosition = glm::vec3(); // The logic for making the sound play when player is moving void playerStep(double dt); + // Spawn a hexagon at origin of an Entity + void spawnHexagon(EntityWrapper target); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); + EventRelay m_EDoubleJump; + bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e); void updateMovementControllers(double dt); void updateVelocity(EntityWrapper player, double dt); diff --git a/include/Game/Systems/PlayerSpawnSystem.h b/include/Game/Systems/PlayerSpawnSystem.h index bf87bef8..70f94807 100644 --- a/include/Game/Systems/PlayerSpawnSystem.h +++ b/include/Game/Systems/PlayerSpawnSystem.h @@ -13,8 +13,6 @@ public: PlayerSpawnSystem(SystemParams params); virtual void Update(double dt) override; - - static void SetRespawnTime(float respawnTime) { m_RespawnTime = respawnTime; }; private: struct SpawnRequest @@ -31,8 +29,8 @@ private: //EntityWrapper ID -> Player ID. std::map m_PlayerIDs; - static float m_RespawnTime; - float m_Timer; + float m_ForcedRespawnTime; + bool m_DbgConfigForceRespawn; EventRelay m_OnInputCommand; bool OnInputCommand(Events::InputCommand& e); diff --git a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h index 7bd9c175..993dd060 100644 --- a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h +++ b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h @@ -1,37 +1,33 @@ +#ifndef AssaultWeaponBehaviour_h__ +#define AssaultWeaponBehaviour_h__ + #include "Sound/EPlaySoundOnEntity.h" #include "Collision/Collision.h" -#include "Rendering/AnimationSystem.h" #include "Core/ConfigFile.h" #include "WeaponBehaviour.h" #include "../SpawnerSystem.h" #include "Core/EPlayerDamage.h" #include "Core/EShoot.h" - -class AssaultWeaponBehaviour : public WeaponBehaviour +class AssaultWeaponBehaviour : public WeaponBehaviour { public: - AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper weaponEntity); - - virtual void Fire() override; - virtual void CeaseFire() override; - virtual void Reload() override; + AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree) + : WeaponBehaviour(systemParams, "AssaultWeapon", renderer, collisionOctree) + { } - virtual void Update(double dt) override; +protected: + virtual void OnPrimaryFire(WeaponInfo& wi) override; + virtual void OnCeasePrimaryFire(WeaponInfo& wi) override; + virtual void OnReload(WeaponInfo& wi) override; private: - EntityWrapper m_FirstPersonModel; - EntityWrapper m_ThirdPersonModel; // State bool m_Firing = false; bool m_Reloading = false; double m_ReloadTimer = 0.0; - EntityWrapper m_FirstPersonReloadImpersonator; - EntityWrapper m_ThirdPersonReloadImpersonator; double m_TimeSinceLastFire = 0.0; - - EventRelay m_EAnimationComplete; - bool OnAnimationComplete(Events::AnimationComplete& e); + EntityWrapper m_FirstPersonReloadImpostor; bool hasAmmo(); void fireRound(); @@ -47,3 +43,5 @@ private: bool shoot(double damage); void showHitMarker(); }; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h b/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h new file mode 100644 index 00000000..5ca13d3e --- /dev/null +++ b/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h @@ -0,0 +1,38 @@ +#include "WeaponBehaviour.h" +#include "Collision/Collision.h" +#include "Core/EPlayerDamage.h" +#include "Rendering/ESetCamera.h" + +class DefenderWeaponBehaviour : public WeaponBehaviour +{ +public: + DefenderWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree) + : System(systemParams) + , WeaponBehaviour(systemParams, "DefenderWeapon", renderer, collisionOctree) + , m_RandomEngine(m_RandomDevice()) + { + EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &DefenderWeaponBehaviour::OnSetCamera); + } + + void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cWeapon, double dt) override; + void UpdateWeapon(WeaponInfo& wi, double dt) override; + void OnPrimaryFire(WeaponInfo& wi) override; + void OnCeasePrimaryFire(WeaponInfo& wi) override; + bool OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) override; + +private: + std::random_device m_RandomDevice; + std::mt19937 m_RandomEngine; + EntityWrapper m_CurrentCamera; + + EventRelay m_ESetCamera; + bool OnSetCamera(const Events::SetCamera& e); + + // Weapon functions + void fireShell(WeaponInfo& wi); + void dealDamage(WeaponInfo& wi, glm::vec3 direction, double damage); + + // Utility + float traceRayDistance(glm::vec3 origin, glm::vec3 direction); + Camera cameraFromEntity(EntityWrapper camera); +}; \ No newline at end of file diff --git a/include/Game/Systems/Weapon/WeaponBehaviour.h b/include/Game/Systems/Weapon/WeaponBehaviour.h index 7a0b4626..f23269df 100644 --- a/include/Game/Systems/Weapon/WeaponBehaviour.h +++ b/include/Game/Systems/Weapon/WeaponBehaviour.h @@ -5,30 +5,177 @@ #include "Rendering/IRenderer.h" #include "Core/Octree.h" #include "Collision/EntityAABB.h" +#include "Input/EInputCommand.h" +#include "Systems/SpawnerSystem.h" -class WeaponBehaviour : public System +template +class WeaponBehaviour : public PureSystem { + friend class WeaponSystem; + public: - WeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) - : System(systemParams) + WeaponBehaviour(SystemParams params, std::string componentType, IRenderer* renderer, Octree* collisionOctree) + : System(params) + , PureSystem(componentType) , m_Renderer(renderer) , m_CollisionOctree(collisionOctree) - , m_Player(player) - { } + { + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &WeaponBehaviour::_OnInputCommand) + } virtual ~WeaponBehaviour() = default; - WeaponBehaviour(const WeaponBehaviour&) = delete; - WeaponBehaviour& operator=(const WeaponBehaviour &) = delete; - - virtual void Fire() = 0; - virtual void CeaseFire() { } - virtual void Reload() { } - virtual void Update(double dt) { } + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override + { + auto weapon = getActiveWeapon(entity); + if (!weapon) { + return; + } else { + UpdateWeapon(*weapon, dt); + } + } protected: + struct WeaponInfo + { + std::string WeaponComponent; + EntityWrapper Player; + EntityWrapper WeaponEntity; + EntityWrapper FirstPersonEntity; + EntityWrapper ThirdPersonEntity; + ComponentWrapper GetComponent() { return WeaponEntity[WeaponComponent]; } + }; + IRenderer* m_Renderer; Octree* m_CollisionOctree; - EntityWrapper m_Player; + std::unordered_map m_ActiveWeapons; + + virtual void UpdateWeapon(WeaponInfo& wi, double dt) { } + virtual void OnPrimaryFire(WeaponInfo& wi) { } + virtual void OnCeasePrimaryFire(WeaponInfo& wi) { } + virtual void OnReload(WeaponInfo& wi) { } + virtual bool OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) { return false; } + +private: + EventRelay m_EInputCommand; + bool _OnInputCommand(const Events::InputCommand& e) + { + EntityWrapper player = e.Player; + if (e.PlayerID == -1) { + player = LocalPlayer; + } + + // Make sure the player is alive + if (!player.Valid()) { + return false; + } + + // Make sure the player has this weapon + auto weapon = getWeaponComponent(player); + if (!weapon) { + return false; + } + + // Weapon selection + if (e.Command == "SelectWeapon") { + if (static_cast(e.Value) == static_cast((*weapon)["Slot"])) { + selectWeapon(player); + } + } + + // Only handle weapon actions if the weapon is active + auto activeWeapon = getActiveWeapon(player); + if (!activeWeapon) { + return false; + } + + // Fire + if (e.Command == "PrimaryFire") { + if (e.Value > 0) { + OnPrimaryFire(*activeWeapon); + } else { + OnCeasePrimaryFire(*activeWeapon); + } + } + + // Reload + if (e.Command == "Reload" && e.Value != 0) { + OnReload(*activeWeapon); + } + + return OnInputCommand(*activeWeapon, e); + } + + boost::optional getWeaponComponent(EntityWrapper player) + { + if (!player.HasComponent(m_ComponentType)) { + return boost::none; + } + + return player[m_ComponentType]; + } + + boost::optional getActiveWeapon(EntityWrapper player) + { + auto it = m_ActiveWeapons.find(player); + if (it == m_ActiveWeapons.end()) { + return boost::none; + } + WeaponInfo& activeWeapon = it->second; + + if (!activeWeapon.FirstPersonEntity.Valid() && !activeWeapon.ThirdPersonEntity.Valid()) { + return boost::none; + } + + return activeWeapon; + } + + void selectWeapon(EntityWrapper player) + { + // Find the weapon attachments matching the weapon type + std::vector weaponAttachments = player.ChildrenWithComponent("WeaponAttachment"); + EntityWrapper firstPersonAttachment; + EntityWrapper thirdPersonAttachment; + for (auto& attachment : weaponAttachments) { + ComponentWrapper cWeaponAttachment = attachment["WeaponAttachment"]; + if ((std::string&)cWeaponAttachment["Weapon"] == m_ComponentType) { + ComponentWrapper::SubscriptProxy person = cWeaponAttachment["Person"]; + if ((ComponentInfo::EnumType)person == person.Enum("FirstPerson")) { + firstPersonAttachment = attachment; + } else if ((ComponentInfo::EnumType)person == person.Enum("ThirdPerson")) { + thirdPersonAttachment = attachment; + } + } + } + + if (!firstPersonAttachment.Valid() && !thirdPersonAttachment.Valid()) { + LOG_WARNING("No weapon attachment found for %s of player #%i", m_ComponentType.c_str(), player.ID); + return; + } + + // Purge other weapon entities + for (auto& attachment : weaponAttachments) { + //if (attachment == firstPersonAttachment || attachment == thirdPersonAttachment) { + // continue; + //} + attachment.DeleteChildren(); + } + + // Spawn the weapon(s) + EntityWrapper firstPersonWeapon; + EntityWrapper thirdPersonWeapon; + if (firstPersonAttachment.Valid()) { + firstPersonWeapon = SpawnerSystem::Spawn(firstPersonAttachment, firstPersonAttachment); + } + if (thirdPersonAttachment.Valid()) { + thirdPersonWeapon = SpawnerSystem::Spawn(thirdPersonAttachment, thirdPersonAttachment); + } + + m_ActiveWeapons[player].WeaponComponent = m_ComponentType; + m_ActiveWeapons[player].Player = player; + m_ActiveWeapons[player].WeaponEntity = player; + m_ActiveWeapons[player].FirstPersonEntity = firstPersonWeapon; + m_ActiveWeapons[player].ThirdPersonEntity = thirdPersonWeapon; + } }; #endif diff --git a/resources/DefaultConfig.ini b/resources/DefaultConfig.ini index 60ee4823..e99e3437 100644 --- a/resources/DefaultConfig.ini +++ b/resources/DefaultConfig.ini @@ -36,4 +36,49 @@ ResourceLoading=true [Sound] BGMVolume=1.0 SFXVolume=1.0 -Announcer=female \ No newline at end of file +Announcer=female + +[SSAO] +Quality=0 + +[SSAO1] +Radius=1.0 +Bias=0.02 +Contrast=1.5 +Intensity=1.0 +NumSamples=8 +NumTurns=3 +NumIterations=5 +TextureQuality=2 + +[SSAO2] +Radius=1.0 +Bias=0.02 +Contrast=1.5 +Intensity=1.0 +NumSamples=16 +NumTurns=13 +NumIterations=9 +TextureQuality=1 + +[SSAO3] +Radius=1.0 +Bias=0.02 +Contrast=1.5 +Intensity=1.0 +NumSamples=24 +NumTurns=17 +NumIterations=9 +TextureQuality=0 + +[GLOW] +Quality=3; + +[GLOW1] +NumIterations=5 + +[GLOW2] +NumIterations=9 + +[GLOW3] +NumIterations=13 \ No newline at end of file diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 42abed82..eb41ed6a 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -46,4 +46,8 @@ + + + + \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xml b/resources/Schema/Components/AssaultWeapon.xml index 6c645624..c835217b 100755 --- a/resources/Schema/Components/AssaultWeapon.xml +++ b/resources/Schema/Components/AssaultWeapon.xml @@ -8,4 +8,5 @@ 120 0.01 2 + \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xsd b/resources/Schema/Components/AssaultWeapon.xsd index 95df64b7..7e9854a2 100755 --- a/resources/Schema/Components/AssaultWeapon.xsd +++ b/resources/Schema/Components/AssaultWeapon.xsd @@ -2,6 +2,7 @@ + @@ -28,6 +29,7 @@ Time it takes to reload the weapon in seconds + diff --git a/resources/Schema/Components/CapturePointGameMode.xml b/resources/Schema/Components/CapturePointGameMode.xml new file mode 100644 index 00000000..3104e71f --- /dev/null +++ b/resources/Schema/Components/CapturePointGameMode.xml @@ -0,0 +1,5 @@ + + + 0.0 + 8.0 + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointGameMode.xsd b/resources/Schema/Components/CapturePointGameMode.xsd new file mode 100644 index 00000000..8b81d67a --- /dev/null +++ b/resources/Schema/Components/CapturePointGameMode.xsd @@ -0,0 +1,18 @@ + + + + + + + + + + The time since the last respawn wave. Players will be spawned when this reaches MaxRespawnTime. + + + Players will be spawned when RespawnTime reaches this. + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/DashAbility.xml b/resources/Schema/Components/DashAbility.xml index a313c447..a71e4e52 100644 --- a/resources/Schema/Components/DashAbility.xml +++ b/resources/Schema/Components/DashAbility.xml @@ -1,4 +1,5 @@ 2.0 + 0.0 \ No newline at end of file diff --git a/resources/Schema/Components/DashAbility.xsd b/resources/Schema/Components/DashAbility.xsd index 4273cc71..6fc59c77 100644 --- a/resources/Schema/Components/DashAbility.xsd +++ b/resources/Schema/Components/DashAbility.xsd @@ -10,7 +10,10 @@ - This is the cooldown on dash + This is the max cooldown on dash + + + This is the current cooldown on dash diff --git a/resources/Schema/Components/DefenderWeapon.xml b/resources/Schema/Components/DefenderWeapon.xml new file mode 100755 index 00000000..998f3bde --- /dev/null +++ b/resources/Schema/Components/DefenderWeapon.xml @@ -0,0 +1,16 @@ + + + 8 + 8 + 64 + 64 + 90 + 0.174533 + 10 + 120 + 0.01 + 0.5 + + false + 0 + \ No newline at end of file diff --git a/resources/Schema/Components/DefenderWeapon.xsd b/resources/Schema/Components/DefenderWeapon.xsd new file mode 100755 index 00000000..3fe5a64a --- /dev/null +++ b/resources/Schema/Components/DefenderWeapon.xsd @@ -0,0 +1,44 @@ + + + + + + + + + + + Ammo currently loaded into the magazine + + + Max number of rounds in a magazine + + + Current ammo carried + + + Maximum ammo able to be carried + + + Damage dealt if all shotgun pellets hit + + + Spread angle in radians + + + + Rate of fire in rounds per minute + + + View punch in radians for each shell fired + + + Time it takes to load ONE SHELL into the weapon in seconds + + + + + + + + diff --git a/resources/Schema/Components/DoubleJump.xml b/resources/Schema/Components/DoubleJump.xml new file mode 100644 index 00000000..bb0d3bc7 --- /dev/null +++ b/resources/Schema/Components/DoubleJump.xml @@ -0,0 +1,4 @@ + + + 4.0 + \ No newline at end of file diff --git a/resources/Schema/Components/DoubleJump.xsd b/resources/Schema/Components/DoubleJump.xsd new file mode 100644 index 00000000..65ff0419 --- /dev/null +++ b/resources/Schema/Components/DoubleJump.xsd @@ -0,0 +1,16 @@ + + + + + + + Enables a Player to double jump. + + + + Vertical velocity set on double jump. + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Physics.xml b/resources/Schema/Components/Physics.xml index 84b6aba3..6cb73c75 100644 --- a/resources/Schema/Components/Physics.xml +++ b/resources/Schema/Components/Physics.xml @@ -2,7 +2,6 @@ true - false 0.33 diff --git a/resources/Schema/Components/Physics.xsd b/resources/Schema/Components/Physics.xsd index 206e2a23..7fed1fb5 100644 --- a/resources/Schema/Components/Physics.xsd +++ b/resources/Schema/Components/Physics.xsd @@ -13,7 +13,6 @@ m/s^2 - The largest height of a "stair-step" that can be walked over diff --git a/resources/Schema/Components/Player.xml b/resources/Schema/Components/Player.xml index 00cff257..b50274ac 100644 --- a/resources/Schema/Components/Player.xml +++ b/resources/Schema/Components/Player.xml @@ -2,5 +2,7 @@ 3 1.5 + 4.0 + \ No newline at end of file diff --git a/resources/Schema/Components/Player.xsd b/resources/Schema/Components/Player.xsd index 1b33d222..006ae9d7 100644 --- a/resources/Schema/Components/Player.xsd +++ b/resources/Schema/Components/Player.xsd @@ -11,7 +11,11 @@ + + Vertical velocity set when jumping. + + diff --git a/resources/Schema/Components/Weapon.xml b/resources/Schema/Components/Weapon.xml deleted file mode 100644 index 38c6fce9..00000000 --- a/resources/Schema/Components/Weapon.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/resources/Schema/Components/Weapon.xsd b/resources/Schema/Components/Weapon.xsd deleted file mode 100644 index 8bddd8a9..00000000 --- a/resources/Schema/Components/Weapon.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/resources/Schema/Components/WeaponAttachment.xml b/resources/Schema/Components/WeaponAttachment.xml new file mode 100644 index 00000000..8867b2b7 --- /dev/null +++ b/resources/Schema/Components/WeaponAttachment.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/WeaponAttachment.xsd b/resources/Schema/Components/WeaponAttachment.xsd new file mode 100644 index 00000000..3b1291ae --- /dev/null +++ b/resources/Schema/Components/WeaponAttachment.xsd @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + Combine with a spawner to define a weapon attachment point + + + + The weapon component type this attachment refers to + + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/AmmoPickup.xml b/resources/Schema/Entities/AmmoPickup.xml index 1d1435f7..bebde467 100644 --- a/resources/Schema/Entities/AmmoPickup.xml +++ b/resources/Schema/Entities/AmmoPickup.xml @@ -2,18 +2,18 @@ - Models/Props/PickUps/AmmoPickUp.mesh - 0.1 - + 8 + - - + + + diff --git a/resources/Schema/Entities/AssaultWeaponView.xml b/resources/Schema/Entities/AssaultWeaponView.xml new file mode 100755 index 00000000..4b985fbb --- /dev/null +++ b/resources/Schema/Entities/AssaultWeaponView.xml @@ -0,0 +1,99 @@ + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/AssaultWeaponWorld.xml b/resources/Schema/Entities/AssaultWeaponWorld.xml new file mode 100755 index 00000000..6fcb97b3 --- /dev/null +++ b/resources/Schema/Entities/AssaultWeaponWorld.xml @@ -0,0 +1,40 @@ + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + diff --git a/resources/Schema/Entities/DefenderShield.xml b/resources/Schema/Entities/DefenderShield.xml new file mode 100755 index 00000000..da760e72 --- /dev/null +++ b/resources/Schema/Entities/DefenderShield.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + + + + Models/Core/UnitHexagon.mesh + + true + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponView.xml b/resources/Schema/Entities/DefenderWeaponView.xml new file mode 100755 index 00000000..f6b6e89d --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponView.xml @@ -0,0 +1,99 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Blue/DefenderGunBlue.mesh + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponViewRed.xml b/resources/Schema/Entities/DefenderWeaponViewRed.xml new file mode 100755 index 00000000..b5b1c322 --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponViewRed.xml @@ -0,0 +1,99 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Red/DefenderGunRed.mesh + + + + + + + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponWorld.xml b/resources/Schema/Entities/DefenderWeaponWorld.xml new file mode 100755 index 00000000..826301b4 --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponWorld.xml @@ -0,0 +1,41 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Blue/DefenderGunBlue.mesh + + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponWorldRed.xml b/resources/Schema/Entities/DefenderWeaponWorldRed.xml new file mode 100755 index 00000000..7f697304 --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponWorldRed.xml @@ -0,0 +1,41 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Red/DefenderGunRed.mesh + + + + + + + + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + diff --git a/resources/Schema/Entities/HealthPickup.xml b/resources/Schema/Entities/HealthPickup.xml index c6fbc4f4..b4b83392 100644 --- a/resources/Schema/Entities/HealthPickup.xml +++ b/resources/Schema/Entities/HealthPickup.xml @@ -2,18 +2,18 @@ - Models/Props/PickUps/HealthPickUp.mesh - 0.1 - + 8 + - - + + + diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index 84aaa03a..41474568 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -10,7 +10,7 @@ - Schema/Entities/Player.xml + Schema/Entities/PlayerRed.xml @@ -118,257 +118,6 @@ - - - - - - - - 600 - - - - - - - - - 5 - - - - - - - - - - - - - - - - - - - - - - - Fonts/DroidSans.ttf,100 - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - - - - - - - - 1 - - - - - Models/Core/UnitHexagon.mesh - - - - - - - - - - - - - - Textures/Weapons/Crosshair/SmallThickHoleDot.png - false - - - - - - - - - - - - - - Idle - 1.9569972344146196 - 1 - - - Models/Characters/Assault/FirstPerson.mesh - true - - - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - true - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - - - Schema/Entities/WeaponReloadEffect.xml - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - Idle - 1.8055945618467364 - 1 - - - AimRifle - - - - - Models/Characters/Assault/AssaultAnimations.mesh - - - - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - false - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 202cdfb6..28ace561 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -7,29 +7,40 @@ - 600 + + + - + + 52.867678870419283 + + - + 5 + - + + + - + + 0.10000000149011612 + 300 + @@ -303,7 +314,8 @@ - + + @@ -363,7 +375,7 @@ Idle - 0.97725610639912475 + 1.9408570429715581 1 @@ -375,100 +387,29 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - - - - - + + DefenderWeapon + + + Schema/Entities/DefenderWeaponView.xml + + - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectView.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - + + + + + + AssaultWeapon + + + Schema/Entities/AssaultWeaponView.xml + + + + @@ -476,7 +417,10 @@ - + + 0.10000000149011612 + 300 + Models/Widgets/Camera.mesh false @@ -492,7 +436,7 @@ Idle - 0.87583812735846323 + 1.5631122524686134 1 @@ -501,6 +445,7 @@ AimRifle + Models/Characters/Assault/AssaultAnimations.mesh @@ -509,41 +454,35 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - - - - - + + DefenderWeapon + + + + + + Schema/Entities/DefenderWeaponWorld.xml + + - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorld.xml - - - - - - + + + + + + AssaultWeapon + + + + + + Schema/Entities/AssaultWeaponWorld.xml + + + + @@ -609,6 +548,17 @@ + + + + Schema/Entities/DefenderShield.xml + + + + + + + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index cd01632e..c46b9d79 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -7,30 +7,40 @@ - 600 + + + - + + 22.22055262342397 + + - 5 + - + + + - + + 0.10000000149011612 + 300 + @@ -365,7 +375,7 @@ Idle - 1.2667383999985162 + 1.1978087298230946 1 @@ -377,100 +387,29 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Red/AssaultWeaponRed.mesh - - - - - + + DefenderWeapon + + + Schema/Entities/DefenderWeaponViewRed.xml + + - - - - - Schema/Entities/RayRed.xml - - - - - - - - - - - Schema/Entities/ReloadEffectViewRed.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - + + + + + + AssaultWeapon + + + Schema/Entities/AssaultWeaponView.xml + + + + @@ -478,7 +417,10 @@ - + + 0.10000000149011612 + 300 + Models/Widgets/Camera.mesh false @@ -494,7 +436,7 @@ Idle - 0.26532318661337229 + 0.69274608502888668 1 @@ -503,6 +445,7 @@ AimRifle + Models/Characters/Assault/AssaultAnimations.mesh @@ -511,41 +454,35 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Red/AssaultWeaponRed.mesh - - - - - + + DefenderWeapon + + + + + + Schema/Entities/DefenderWeaponWorldRed.xml + + - - - - - Schema/Entities/RayRed.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorldRed.xml - - - - - - + + + + + + AssaultWeapon + + + + + + Schema/Entities/AssaultWeaponWorld.xml + + + + @@ -584,20 +521,20 @@ - + - + Textures/Icons/Arrow.png false - + @@ -605,12 +542,23 @@ true - + + + + + Schema/Entities/DefenderShield.xml + + + + + + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index a9c5f641..0965ef89 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -50,6 +50,8 @@ + + diff --git a/resources/Schema/Types/WeaponSlotEnum.xsd b/resources/Schema/Types/WeaponSlotEnum.xsd new file mode 100644 index 00000000..6713ca9d --- /dev/null +++ b/resources/Schema/Types/WeaponSlotEnum.xsd @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/Shaders/DrawColorCorrection.frag.glsl b/resources/Shaders/DrawColorCorrection.frag.glsl index bae50887..d8273547 100644 --- a/resources/Shaders/DrawColorCorrection.frag.glsl +++ b/resources/Shaders/DrawColorCorrection.frag.glsl @@ -2,8 +2,6 @@ layout (binding = 0) uniform sampler2D SceneTexture; layout (binding = 1) uniform sampler2D BloomTexture; -layout (binding = 2) uniform sampler2D SceneTextureLowRes; -layout (binding = 3) uniform sampler2D BloomTextureLowRes; uniform float Exposure; uniform float Gamma; @@ -17,21 +15,12 @@ void main() { vec4 hdrColor = texture(SceneTexture, Input.TextureCoordinate); vec4 bloomColor = texture(BloomTexture, Input.TextureCoordinate); - vec4 hdrColorLowRes = texture(SceneTextureLowRes, Input.TextureCoordinate); - vec4 bloomColorLowRes = texture(BloomTextureLowRes, Input.TextureCoordinate); //hdrColor = hdrColor * SSAO; hdrColor += bloomColor; - hdrColorLowRes; - float hdrColorsum = hdrColorLowRes.r + hdrColorLowRes.g + hdrColorLowRes.b; //Toon mapping thingy - vec3 result; - if(hdrColorsum > 0.0) { - result = vec3(1.0) - exp(-hdrColorLowRes.rgb * Exposure); - } else { - result = vec3(1.0) - exp(-hdrColor.rgb * Exposure); - } + vec3 result = vec3(1.0) - exp(-hdrColor.rgb * Exposure); //gamme correction result = pow(result, vec3(1.0 / Gamma)); diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 6fbc9c27..aa45d118 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -13,6 +13,7 @@ uniform vec4 AmbientColor; uniform float FillPercentage; uniform float GlowIntensity = 10; uniform vec3 CameraPosition; +uniform int SSAOQuality; uniform vec2 DiffuseUVRepeat; uniform vec2 NormalUVRepeat; @@ -125,7 +126,7 @@ vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textu void main() { - float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy), 0).r; + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy) >> int(SSAOQuality), 0).r; ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate * DiffuseUVRepeat); vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate * GlowUVRepeat); @@ -170,7 +171,8 @@ void main() vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); 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 reflectionTotal = reflectionColor * (1-specularTexel.a) * color_result.a; + color_result = color_result * clamp(1/specularTexel.a, 0, 1) + reflectionTotal; //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; @@ -181,9 +183,9 @@ void main() } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); //sceneColor = vec4(reflectionColor.xyz, 1); - color_result += glowTexel*GlowIntensity; + color_result.xyz += glowTexel.xyz*GlowIntensity; - bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), clamp(color_result.a, 0, 1)); + bloomColor = vec4(max(color_result.xyz - 1.0, 0.0), clamp(color_result.a, 0, 1)); //Tiled Debug Code /* diff --git a/resources/Shaders/ForwardPlusShieldCheck.frag.glsl b/resources/Shaders/ForwardPlusShieldCheck.frag.glsl new file mode 100644 index 00000000..35db495b --- /dev/null +++ b/resources/Shaders/ForwardPlusShieldCheck.frag.glsl @@ -0,0 +1,207 @@ +#version 430 + +#define MIN_AMBIENT_LIGHT 0.3 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform vec4 Color; +uniform vec4 DiffuseColor; +uniform vec2 ScreenDimensions; +uniform vec4 FillColor; +uniform vec4 AmbientColor; +uniform float FillPercentage; +uniform float GlowIntensity = 10; +uniform vec3 CameraPosition; +uniform int SSAOQuality; + +uniform vec2 DiffuseUVRepeat; +uniform vec2 NormalUVRepeat; +uniform vec2 SpecularUVRepeat; +uniform vec2 GlowUVRepeat; +layout (binding = 0) uniform sampler2D AOTexture; +layout (binding = 1) uniform sampler2D DiffuseTexture; +layout (binding = 2) uniform sampler2D NormalMapTexture; +layout (binding = 3) uniform sampler2D SpecularMapTexture; +layout (binding = 4) uniform sampler2D GlowMapTexture; +layout (binding = 5) uniform samplerCube CubeMap; +layout (binding = 31) uniform sampler2D ShieldBuffer; + +#define TILE_SIZE 16 + +struct LightSource { + vec4 Position; + vec4 Direction; + vec4 Color; + float Radius; + float Intensity; + float Falloff; + int Type; +}; + +layout (std430, binding = 1) buffer LightBuffer +{ + LightSource List[]; +} LightSources; + +struct LightGrid { + float Start; + float Amount; + vec2 Padding; +}; + +layout (std430, binding = 2) buffer LightGridBuffer +{ + LightGrid Data[]; +} LightGrids; + +layout (std430, binding = 4) buffer LightIndexBuffer +{ + float LightIndex[]; +}; + + +in VertexData{ + vec3 Position; + vec3 Normal; + vec3 Tangent; + vec3 BiTangent; + vec2 TextureCoordinate; + vec4 ExplosionColor; + float ExplosionPercentageElapsed; +}Input; + +out vec4 sceneColor; +out vec4 bloomColor; + +struct LightResult { + vec4 Diffuse; + vec4 Specular; +}; + +float CalcAttenuation(float radius, float dist, float falloff) { + return 1.0 - smoothstep(radius * falloff, radius, dist); +} + +vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { + vec4 R = normalize( reflect(-lightVec, normal)); + float RdotV = max( dot(R, viewVec), 0.0); + return lightColor * pow(RdotV, 90.0); +} + +vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) { + float power = max( dot(normal, lightVec), 0.0); + return lightColor * power; +} + +LightResult CalcPointLightSource(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal, float falloff) +{ + vec4 L = lightPos - position; + float dist = length(L); + L = normalize(L); + + float attenuation = CalcAttenuation(lightRadius, dist, falloff); + + LightResult result; + result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity; + result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity; + return result; +} + +LightResult CalcDirectionalLightSource(vec4 direction, vec4 color, float intensity, vec4 viewVec, vec4 vertNormal) +{ + vec4 L = normalize( -vec4(direction.xyz, 0) ); + + LightResult result; + result.Diffuse = CalcDiffuse(color, L, vertNormal) * intensity; + result.Specular = CalcSpecular(color, viewVec, L, vertNormal) * intensity; + return result; +} + +vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textureCoordinate, sampler2D normalMap) +{ + mat3 TBN = mat3(tangent, bitangent, normal); + vec3 NormalMap = texture(normalMap, textureCoordinate).xyz * 2.0 - vec3(1.0); + return vec4(TBN * normalize(NormalMap), 0.0); +} + +void main() +{ + float shieldDepthValue = texelFetch(ShieldBuffer, ivec2(gl_FragCoord.xy), 0).r; + + if(shieldDepthValue < gl_FragCoord.z){ + discard; + } + + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy) >> int(SSAOQuality), 0).r; + ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); + vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate * DiffuseUVRepeat); + vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate * GlowUVRepeat); + vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate * SpecularUVRepeat); + vec4 position = V * M * vec4(Input.Position, 1.0); + vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate * NormalUVRepeat, NormalMapTexture); + normal = normalize(normal); + //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); + 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; + tilePos.x = int(gl_FragCoord.x/TILE_SIZE); + tilePos.y = int(gl_FragCoord.y/TILE_SIZE); + + LightResult totalLighting; + totalLighting.Diffuse = vec4(AmbientColor.rgb * ao, 1.0); + int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); + + int start = int(LightGrids.Data[currentTile].Start); + int amount = int(LightGrids.Data[currentTile].Amount); + + for(int i = start; i < start + amount; i++) { + + int l = int(LightIndex[i]); + LightSource light = LightSources.List[l]; + + LightResult light_result; + //These if statements should be removed. + if(light.Type == 1) { // point + light_result = CalcPointLightSource(V * light.Position, light.Radius, light.Color, light.Intensity, viewVec, position, normal, light.Falloff); + } else if (light.Type == 2) { //Directional + light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); + } + totalLighting.Diffuse += vec4(light_result.Diffuse.rgb * ao, light_result.Diffuse.a); + totalLighting.Specular += vec4(light_result.Specular.rgb * ao, light_result.Specular.a); + } + + vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); + color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); + float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; + vec4 reflectionTotal = reflectionColor * (1-specularTexel.a) * color_result.a; + color_result = color_result * clamp(1/specularTexel.a, 0, 1) + reflectionTotal; + //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; + + + float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; + + if(pos <= FillPercentage) { + color_result += FillColor; + } + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + //sceneColor = vec4(reflectionColor.xyz, 1); + color_result.xyz += glowTexel.xyz*GlowIntensity; + + bloomColor = vec4(max(color_result.xyz - 1.0, 0.0), clamp(color_result.a, 0, 1)); + + //Tiled Debug Code + /* + if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 ) { + sceneColor += vec4(0.5, 0, 0, 0); + } else { + sceneColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/LightSources.List.length(), 0, 0, 1); + } + */ +} + + diff --git a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl index cf358b96..c67a9c99 100644 --- a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl +++ b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl @@ -11,6 +11,7 @@ uniform vec4 DiffuseColor; uniform vec4 FillColor; uniform vec4 Color; uniform vec4 AmbientColor; +uniform int SSAOQuality; //Get bineded at the same time as the textures uniform vec2 DiffuseUVRepeat1; @@ -177,7 +178,7 @@ vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, void main() { - float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy), 0).r; + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy) >> int(SSAOQuality), 0).r; ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); diff --git a/resources/Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl b/resources/Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl new file mode 100644 index 00000000..fa3af6ac --- /dev/null +++ b/resources/Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl @@ -0,0 +1,254 @@ +#version 430 + +#define MIN_AMBIENT_LIGHT 0.3 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform vec2 ScreenDimensions; +uniform float FillPercentage; +uniform vec4 DiffuseColor; +uniform vec4 FillColor; +uniform vec4 Color; +uniform vec4 AmbientColor; +uniform int SSAOQuality; + +//Get bineded at the same time as the textures +uniform vec2 DiffuseUVRepeat1; +uniform vec2 DiffuseUVRepeat2; +uniform vec2 DiffuseUVRepeat3; +uniform vec2 NormalUVRepeat1; +uniform vec2 NormalUVRepeat2; +uniform vec2 NormalUVRepeat3; +uniform vec2 SpecularUVRepeat1; +uniform vec2 SpecularUVRepeat2; +uniform vec2 SpecularUVRepeat3; +uniform vec2 GlowUVRepeat1; +uniform vec2 GlowUVRepeat2; +uniform vec2 GlowUVRepeat3; +layout (binding = 0) uniform sampler2D AOTexture; +layout (binding = 1) uniform sampler2D SplatMapTexture; +layout (binding = 2) uniform sampler2D DiffuseTexture1; +layout (binding = 3) uniform sampler2D DiffuseTexture2; +layout (binding = 4) uniform sampler2D DiffuseTexture3; +layout (binding = 5) uniform sampler2D NormalMapTexture1; +layout (binding = 6) uniform sampler2D NormalMapTexture2; +layout (binding = 7) uniform sampler2D NormalMapTexture3; +layout (binding = 8) uniform sampler2D SpecularMapTexture1; +layout (binding = 9) uniform sampler2D SpecularMapTexture2; +layout (binding = 10) uniform sampler2D SpecularMapTexture3; +layout (binding = 11) uniform sampler2D GlowMapTexture1; +layout (binding = 12) uniform sampler2D GlowMapTexture2; +layout (binding = 13) uniform sampler2D GlowMapTexture3; +layout (binding = 13) uniform sampler2D GlowMapTexture3; +layout (binding = 31) uniform samplerCube ShieldBuffer; + +#define TILE_SIZE 16 + +struct LightSource { + vec4 Position; + vec4 Direction; + vec4 Color; + float Radius; + float Intensity; + float Falloff; + int Type; +}; + +layout (std430, binding = 1) buffer LightBuffer +{ + LightSource List[]; +} LightSources; + +struct LightGrid { + float Start; + float Amount; + vec2 Padding; +}; + +layout (std430, binding = 2) buffer LightGridBuffer +{ + LightGrid Data[]; +} LightGrids; + +layout (std430, binding = 4) buffer LightIndexBuffer +{ + float LightIndex[]; +}; + + +in VertexData{ + vec3 Position; + vec3 Normal; + vec3 Tangent; + vec3 BiTangent; + vec2 TextureCoordinate; + vec4 ExplosionColor; + float ExplosionPercentageElapsed; +}Input; + +out vec4 sceneColor; +out vec4 bloomColor; + +struct LightResult { + vec4 Diffuse; + vec4 Specular; +}; + +float CalcAttenuation(float radius, float dist, float falloff) { + return 1.0 - smoothstep(radius * 0.3, radius, dist); +} + +vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { + vec4 R = normalize( reflect(-lightVec, normal)); + float RdotV = max( dot(R, viewVec), 0.0); + return lightColor * pow(RdotV, 90.0); +} + +vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) { + float power = max( dot(normal, lightVec), 0.0); + return lightColor * power; +} + +LightResult CalcPointLightSource(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal, float falloff) +{ + vec4 L = lightPos - position; + float dist = length(L); + L = normalize(L); + + float attenuation = CalcAttenuation(lightRadius, dist, falloff); + + LightResult result; + result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity; + result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity; + return result; +} + +LightResult CalcDirectionalLightSource(vec4 direction, vec4 color, float intensity, vec4 viewVec, vec4 vertNormal) +{ + vec4 L = normalize( -vec4(direction.xyz, 0) ); + + LightResult result; + result.Diffuse = CalcDiffuse(color, L, vertNormal) * intensity; + result.Specular = CalcSpecular(color, viewVec, L, vertNormal) * intensity; + return result; +} + +vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textureCoordinate, sampler2D normalMap) +{ + mat3 TBN = mat3(tangent, bitangent, normal); + vec3 NormalMap = texture(normalMap, textureCoordinate).xyz * 2.0 - vec3(1.0); + return vec4(TBN * normalize(NormalMap), 0.0); +} + +vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, + vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues){ + vec4 R_Channel = texture2D(R, Input.TextureCoordinate * R_TileValues); + vec4 G_Channel = texture2D(G, Input.TextureCoordinate * G_TileValues); + vec4 B_Channel = texture2D(B, Input.TextureCoordinate * B_TileValues); + + float total = blendValue.r + blendValue.g + blendValue.b; + float totalDiv = 1.0f / total; + blendValue.r = blendValue.r * totalDiv; + blendValue.g = blendValue.g * totalDiv; + blendValue.b = blendValue.b * totalDiv; + + return blendValue.r * R_Channel + + blendValue.g * G_Channel + + blendValue.b * B_Channel; +} + +vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, + vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues){ + mat3 TBN = mat3(Input.Tangent, Input.BiTangent, Input.Normal); + vec3 R_Channel = texture(R, Input.TextureCoordinate * R_TileValues).xyz * 2.0 - vec3(1.0); + vec3 G_Channel = texture(G, Input.TextureCoordinate * G_TileValues).xyz * 2.0 - vec3(1.0); + vec3 B_Channel = texture(B, Input.TextureCoordinate * B_TileValues).xyz * 2.0 - vec3(1.0); + + float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; + float totalDiv = 1 / total; + blendValue.r = blendValue.r * totalDiv; + blendValue.g = blendValue.g * totalDiv; + blendValue.b = blendValue.b * totalDiv; + + vec3 Normal_result = blendValue.r * R_Channel + + blendValue.g * G_Channel + + blendValue.b * B_Channel; + + return vec4(TBN * normalize(Normal_result), 0.0); +} + +void main() +{ + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy) >> int(SSAOQuality), 0).r; + ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); + + vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); + + vec4 diffuseTexel = CalcBlendedTexel(splatTexel, DiffuseTexture1, DiffuseTexture2, DiffuseTexture3, + DiffuseUVRepeat1, DiffuseUVRepeat2, DiffuseUVRepeat3); + vec4 glowTexel = CalcBlendedTexel(splatTexel, GlowMapTexture1, GlowMapTexture2, GlowMapTexture3, + GlowUVRepeat1, GlowUVRepeat2, GlowUVRepeat3); + vec4 specularTexel = CalcBlendedTexel(splatTexel, SpecularMapTexture1, SpecularMapTexture2, SpecularMapTexture3, + SpecularUVRepeat1, SpecularUVRepeat2, SpecularUVRepeat3); + vec4 position = V * M * vec4(Input.Position, 1.0); + //vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, SplatMapTexture); + vec4 normal = V * CalcBlendedNormal(splatTexel, NormalMapTexture1, NormalMapTexture2, NormalMapTexture3, + NormalUVRepeat1, NormalUVRepeat2, NormalUVRepeat3); + normal = normalize(normal); + //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); + vec4 viewVec = normalize(-position); + + vec2 tilePos; + tilePos.x = int(gl_FragCoord.x/TILE_SIZE); + tilePos.y = int(gl_FragCoord.y/TILE_SIZE); + + LightResult totalLighting; + totalLighting.Diffuse = vec4(AmbientColor.rgb * ao, 1.0); + int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); + + int start = int(LightGrids.Data[currentTile].Start); + int amount = int(LightGrids.Data[currentTile].Amount); + + for(int i = start; i < start + amount; i++) { + + int l = int(LightIndex[i]); + LightSource light = LightSources.List[l]; + + LightResult light_result; + //These if statements should be removed. + if(light.Type == 1) { // point + light_result = CalcPointLightSource(V * light.Position, light.Radius, light.Color, light.Intensity, viewVec, position, normal, light.Falloff); + } else if (light.Type == 2) { //Directional + light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); + } + totalLighting.Diffuse += vec4(light_result.Diffuse.rgb * ao, light_result.Diffuse.a); + totalLighting.Specular += vec4(light_result.Specular.rgb * ao, light_result.Specular.a); + } + + vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); + color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); + //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; + + + float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; + + if(pos <= FillPercentage) { + color_result += FillColor; + } + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + color_result += glowTexel*3; + + bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); + + //Tiled Debug Code + /* + if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 ) { + sceneColor += vec4(0.5, 0, 0, 0); + } else { + sceneColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/LightSources.List.length(), 0, 0, 1); + } + */ +} + + diff --git a/resources/Shaders/SSAO.frag.glsl b/resources/Shaders/SSAO.frag.glsl index 68c830f8..749881c4 100644 --- a/resources/Shaders/SSAO.frag.glsl +++ b/resources/Shaders/SSAO.frag.glsl @@ -2,11 +2,11 @@ //Number of samples per pixel uniform int uNumOfSamples; -//#define NUM_SAMPLES (11) +//#define uNumOfSamples (11) //Number of turns around the cirle uniform int uNumOfTurns; -//#define NUM_TURNS (7) +//#define uNumOfTurns (7) layout (binding = 0) uniform sampler2D ViewSpaceZ; @@ -16,15 +16,16 @@ uniform float uProjScale; //#define ProjScale 500 uniform float uRadius; -//#define Radius 1.0f +//#define uRadius 1.0f uniform float uBias; -//#define Bias 0.012f +//#define uBias 0.05f uniform float uContrast; -//#define IntensityDivR6 1 +//#define uContrast 1.5f uniform float uIntensityScale; +//#define uIntensityScale 1.0f out float AO; @@ -88,13 +89,7 @@ void main() { vec3 origin = getVSPosition(originScreenCoord); - float radius; - if(origin.z < uRadius){ - radius = origin.z; - } else { - radius = uRadius; - } - + float radius = min(origin.z, uRadius); vec3 originNormal = getVSFaceNormal(origin); diff --git a/resources/Shaders/SSAO.vert.glsl b/resources/Shaders/SSAO.vert.glsl index a019c5ef..346bc141 100644 --- a/resources/Shaders/SSAO.vert.glsl +++ b/resources/Shaders/SSAO.vert.glsl @@ -2,7 +2,12 @@ layout (location = 0) in vec3 Position; +out VertexData{ + vec2 TextureCoordinate; +}Output; + void main() { gl_Position = vec4(Position, 1.0); + Output.TextureCoordinate = (vec2(Position) + 1) / 2; } \ No newline at end of file diff --git a/resources/Shaders/SSAOViewSpaceZ.frag.glsl b/resources/Shaders/SSAOViewSpaceZ.frag.glsl index dbcfd899..d1bf6f17 100644 --- a/resources/Shaders/SSAOViewSpaceZ.frag.glsl +++ b/resources/Shaders/SSAOViewSpaceZ.frag.glsl @@ -3,11 +3,15 @@ layout (binding = 0) uniform sampler2D DepthBuffer; uniform vec3 ClipInfo; +in VertexData{ + vec2 TextureCoordinate; +}Input; + out float depthLinear; //Just for Debug, should be depthLinear //out vec4 fragmentColor; void main() { - float depthSample = texelFetch(DepthBuffer, ivec2(gl_FragCoord.xy), 0).r; + float depthSample = texture2D(DepthBuffer, Input.TextureCoordinate).r; depthLinear = ClipInfo[0] / (ClipInfo[1] * depthSample + ClipInfo[2]); //float depthLinear = (NearClip) / ( -depthSample + 1.0f); //fragmentColor = vec4(depthLinear, depthLinear, depthLinear, 1.0f); diff --git a/resources/Shaders/SpriteShieldCheck.frag.glsl b/resources/Shaders/SpriteShieldCheck.frag.glsl new file mode 100644 index 00000000..754be6ac --- /dev/null +++ b/resources/Shaders/SpriteShieldCheck.frag.glsl @@ -0,0 +1,41 @@ +#version 430 + +uniform vec4 Color; +uniform vec4 FillColor; +uniform float FillPercentage; +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout (binding = 1) uniform sampler2D DiffuseTexture; +layout (binding = 2) uniform sampler2D GlowMapTexture; + + +in VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; +}Input; + + +out vec4 sceneColor; +out vec4 bloomColor; + +void main() +{ + vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate); + vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate); + + vec4 color_result = Color * diffuseTexel; + + float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; + if(pos <= FillPercentage) { + color_result = FillColor*diffuseTexel.a; + } + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + + //bloomColor = vec4(clamp((glowTexel.xyz*3) - 1.0, 0, 100), 1.0); + bloomColor = vec4(1.0, 1.0, 1.0, 0.0); +} + + diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 83876efa..3b28142e 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -12,55 +12,56 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c if (!boundingBox) { return; } + ComponentWrapper& cTransform = entity["Transform"]; EntityAABB& boxA = *boundingBox; bool everHitTheGround = false; - glm::vec3 size = boxA.Size(); - float diameter = std::min(size.x, size.z); - glm::vec3 prevOrigin = (glm::vec3)cPhysics["PrevOrigin"]; - glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; - float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; - //If the entity has moved farther than the size of its box, we need to handle it specially. - bool traceCollision = rayLength > diameter; - //hack solution: If prevOrigin is less than -9000 in all dimensions, - //then it means it is not set, i.e. this is the first collision check for the entity. - if (traceCollision && glm::any(glm::greaterThan((glm::vec3)cPhysics["PrevOrigin"], glm::vec3(-9000.f)))) { - Ray ray(prevOrigin, toCurrentPos); - m_OctreeResult.clear(); - m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); - 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(res); - } catch (const std::exception&) { + auto prevPosIt = m_PrevPositions.find(entity); + if (prevPosIt != m_PrevPositions.end()) { + glm::vec3 size = boxA.Size(); + float diameter = std::min(size.x, size.z); + glm::vec3 prevOrigin = prevPosIt->second; + glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; + float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; + //If the entity has moved farther than the size of its box, we need to handle it specially. + if (rayLength > diameter) { + Ray ray(prevOrigin, toCurrentPos); + m_OctreeResult.clear(); + m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); + for (auto& boxB : m_OctreeResult) { + if (boxA.Entity == boxB.Entity) { continue; } - float u, v; + bool hit; + float dist; + if (boxB.Entity.HasComponent("Model")) { + RawModel* model; + std::string res = (std::string)boxB.Entity["Model"]["Resource"]; + try { + model = ResourceManager::Load(res); + } catch (const std::exception&) { + continue; + } + float u, v; hit = Collision::RayVsModel(ray, model->CollisionVertices(), model->CollisionIndices(), Transform::ModelMatrix(boxB.Entity), dist, u, v); - } else { - hit = Collision::RayVsAABB(ray, boxB, dist); - } - if (hit && dist < rayLength) { - //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; + } else { + hit = Collision::RayVsAABB(ray, boxB, dist); + } + if (hit && dist < rayLength) { + //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; } } } @@ -86,10 +87,13 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity); glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"]; + bool notMovingxz = glm::all(glm::lessThan(glm::abs(glm::vec2(inOutVelocity.x, inOutVelocity.z)), glm::vec2(0.01f))) && prevPosIt != m_PrevPositions.end(); bool isOnGround = (bool)cPhysics["IsOnGround"]; float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; if (Collision::AABBvsTriangles(boxA, model->CollisionVertices(), model->CollisionIndices(), modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { - (glm::vec3&)cTransform["Position"] += resolutionVector; + //Move the position to previous position if it is not moving in the xz-plane, else resolve with the resolution vector. + (glm::vec3&)cTransform["Position"] += notMovingxz ? prevPosIt->second - boxA.Origin() : resolutionVector; + boxA = *Collision::EntityAbsoluteAABB(entity); cPhysics["Velocity"] = inOutVelocity; if (isOnGround) { everHitTheGround = true; @@ -99,6 +103,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; + boxA = *Collision::EntityAbsoluteAABB(entity); if (resolutionVector.y > 0) { everHitTheGround = true; (bool)cPhysics["IsOnGround"] = true; @@ -112,5 +117,5 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c (bool)cPhysics["IsOnGround"] = false; } - (glm::vec3&)cPhysics["PrevOrigin"] = boxA.Origin(); + m_PrevPositions[entity] = boxA.Origin(); } diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index 4b45b8d0..b3bef55a 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -51,6 +51,40 @@ EntityWrapper EntityWrapper::FirstParentWithComponent(const std::string& compone 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; +} + +std::vector EntityWrapper::ChildrenWithComponent(const std::string& componentType) +{ + std::vector childrenWithComponent; + childrenWithComponentRecursive(componentType, *this, childrenWithComponent); + return childrenWithComponent; +} + +void EntityWrapper::DeleteChildren() +{ + auto itPair = this->World->GetDirectChildren(this->ID); + if (itPair.first == itPair.second) { + return; + } + + std::vector entitiesToDelete; + for (auto it = itPair.first; it != itPair.second; it++) { + entitiesToDelete.push_back(it->second); + } + for (auto& e : entitiesToDelete) { + this->World->DeleteEntity(e); + } +} + bool EntityWrapper::IsChildOf(EntityWrapper potentialParent) { EntityWrapper entity = *this; @@ -90,6 +124,11 @@ ComponentWrapper EntityWrapper::operator[](const char* componentName) } } +ComponentWrapper EntityWrapper::operator[](const std::string& componentName) +{ + return this->operator[](componentName.c_str()); +} + bool EntityWrapper::operator==(const EntityWrapper& e) const { return (this->ID == e.ID) && (this->World == e.World); @@ -111,7 +150,7 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } - auto itPair = this->World->GetChildren(parent); + auto itPair = this->World->GetDirectChildren(parent); if (itPair.first == itPair.second) { return EntityWrapper::Invalid; } @@ -131,3 +170,42 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, 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; +} + +void EntityWrapper::childrenWithComponentRecursive(const std::string& componentType, EntityWrapper& entity, std::vector& childrenWithComponent) +{ + auto itPair = this->World->GetDirectChildren(entity.ID); + if (itPair.first == itPair.second) { + return; + } + + for (auto it = itPair.first; it != itPair.second; ++it) { + EntityWrapper child = EntityWrapper(entity.World, it->second); + if (child.HasComponent(componentType)) { + childrenWithComponent.push_back(child); + } + childrenWithComponentRecursive(componentType, child, childrenWithComponent); + } +} diff --git a/src/Engine/Core/Util/Logging.cpp b/src/Engine/Core/Util/Logging.cpp index 63a6f380..c7612fd8 100644 --- a/src/Engine/Core/Util/Logging.cpp +++ b/src/Engine/Core/Util/Logging.cpp @@ -33,8 +33,8 @@ void _LOG(_LOG_LEVEL logLevel, const char* file, const char* func, unsigned int va_end(args); if (logLevel == LOG_LEVEL_ERROR) { - std::cerr << file << ":" << line << " " << func << std::endl; - std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; + //std::cerr << file << ":" << line << " " << func << std::endl; + //std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; } else { std::cout << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; } diff --git a/src/Engine/Core/World.cpp b/src/Engine/Core/World.cpp index 8788a92e..9b323ff4 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -127,7 +127,7 @@ void World::SetParent(EntityID entity, EntityID parent) m_EntityChildren.insert(std::make_pair(parent, entity)); } -const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetChildren(EntityID entity) +const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetDirectChildren(EntityID entity) { return m_EntityChildren.equal_range(entity); } diff --git a/src/Engine/Editor/EditorGUI.cpp b/src/Engine/Editor/EditorGUI.cpp index 70775a2b..8ce15d0a 100644 --- a/src/Engine/Editor/EditorGUI.cpp +++ b/src/Engine/Editor/EditorGUI.cpp @@ -580,6 +580,11 @@ void EditorGUI::createWidgetToolButton(WidgetMode mode) 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 (m_CurrentSelection.Valid()) { EntityWrapper baseParent = m_CurrentSelection; @@ -598,6 +603,19 @@ bool EditorGUI::OnKeyDown(const Events::KeyDown& e) 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 (m_CurrentSelection.Valid()) { entityDelete(m_CurrentSelection); diff --git a/src/Engine/Editor/EditorRenderSystem.cpp b/src/Engine/Editor/EditorRenderSystem.cpp index 9a385e7d..f5fcc1a1 100644 --- a/src/Engine/Editor/EditorRenderSystem.cpp +++ b/src/Engine/Editor/EditorRenderSystem.cpp @@ -54,7 +54,7 @@ void EditorRenderSystem::Update(double dt) EntityWrapper entity(m_World, cModel.EntityID); glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, entity.World); for (auto matGroup : model->MaterialGroups()) { - std::shared_ptr modelJob = std::make_shared(model, scene.Camera, modelMatrix, matGroup, cModel, entity.World, glm::vec4(0), 0.f); + std::shared_ptr modelJob = std::make_shared(model, scene.Camera, modelMatrix, matGroup, cModel, entity.World, glm::vec4(0), 0.f, false); if (cModel["Transparent"]) { scene.Jobs.TransparentObjects.push_back(modelJob); } else { diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index 97ea9d53..4bee1427 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -28,6 +28,7 @@ EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame 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->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->SetComponentDeleteCallback(std::bind(&EditorSystem::OnComponentDelete, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetWidgetModeCallback(std::bind(&EditorSystem::setWidgetMode, this, std::placeholders::_1)); @@ -160,6 +161,11 @@ 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) { if (entity.Valid()) { diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 903cd929..aa87f6ff 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -32,6 +32,7 @@ void Client::Connect(std::string address, int port) EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); 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("Config.ini"); m_Address = address; @@ -100,8 +101,7 @@ void Client::Update() void Client::parseMessageType(Packet& packet) { - // Pop packetSize which is used by TCP Client to - // create a packet of the correct size + // Pop packetSize packet.ReadPrimitive(); int messageType = packet.ReadPrimitive(); if (messageType == -1) @@ -140,6 +140,12 @@ void Client::parseMessageType(Packet& packet) case MessageType::OnPlayerDamage: parsePlayerDamage(packet); break; + case MessageType::OnDoubleJump: + parseDoubleJump(packet); + break; + case MessageType::AmmoPickup: + parseAmmoPickup(packet); + break; default: break; } @@ -229,7 +235,6 @@ void Client::parseSpawnEvents() m_EventBroker->Publish(e); } m_PlayerSpawnEvents = tempSpawn; - // m_PlayerSpawnEvents.clear(); } void Client::parsePlayersSpawned(Packet& packet) @@ -257,8 +262,14 @@ void Client::parseEntityDeletion(Packet & packet) if (m_ServerIDToClientID.find(entityToDelete) != m_ServerIDToClientID.end()) { EntityID localEntity = m_ServerIDToClientID.at(entityToDelete); if (m_World->ValidEntity(localEntity)) { - m_World->DeleteEntity(localEntity); - deleteFromServerClientMaps(entityToDelete, localEntity); + if (m_World->HasComponent(localEntity,"Player")) { + Events::PlayerDeath e; + e.Player = EntityWrapper(m_World, localEntity); + m_EventBroker->Publish(e); + } else { + m_World->DeleteEntity(localEntity); + deleteFromServerClientMaps(entityToDelete, localEntity); + } } } } @@ -272,6 +283,28 @@ void Client::parseComponentDeletion(Packet & packet) } } +void Client::parseDoubleJump(Packet & packet) +{ + EntityID serverID = packet.ReadPrimitive(); + 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::parseAmmoPickup(Packet & packet) +{ + Events::AmmoPickup e; + e.AmmoGain = packet.ReadPrimitive(); + e.Player = m_LocalPlayer; + m_EventBroker->Publish(e); +} + void Client::updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID) { for (auto field : componentInfo.FieldsInOrder) { @@ -348,9 +381,7 @@ void Client::parseSnapshot(Packet& packet) EntityWrapper localEntity(m_World, localEntityID); // Update entity if (m_World->HasComponent(localEntityID, componentType)) { - if (localEntity.Name() == "CapturePointHUD") { - UpdateLocalCapturePointHUD(localEntity); - } + // TODO Fix memory leak here SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); bool shouldApply = true; // Apply potential filter function @@ -361,6 +392,7 @@ void Client::parseSnapshot(Packet& packet) ComponentWrapper currentComponent = m_World->GetComponent(localEntityID, componentType); memcpy(currentComponent.Data, newComponent.Data, componentInfo.Stride); } + //if (localEntity != m_LocalPlayer && !localEntity.IsChildOf(m_LocalPlayer)) { // updateFields(packet, componentInfo, localEntityID); //} else { @@ -377,7 +409,11 @@ void Client::parseSnapshot(Packet& packet) if (serverParentID == EntityID_Invalid) { newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); } else { - newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID)); + if (serverClientMapsHasEntity(serverParentID)) { + newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID)); + } else { + newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); + } } m_World->SetName(newLocalEntityID, serverEntityName); insertIntoServerClientMaps(serverEntityID, newLocalEntityID); @@ -387,26 +423,16 @@ void Client::parseSnapshot(Packet& packet) } // Parent logic // This should be enough beacause we know that the entities arives in pre-order (there will always be a parent) - if (serverParentID != EntityID_Invalid) { + if (serverParentID != EntityID_Invalid && serverClientMapsHasEntity(serverParentID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); - m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); + if (m_World->GetParent(localEntityID) != m_ServerIDToClientID.at(serverParentID)) { + m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); + } } } parseSpawnEvents(); } - -void Client::UpdateLocalCapturePointHUD(EntityWrapper capturePointHUD) -{ - //auto children = m_World->GetChildren(capturePointHUD.ID); - //for (auto it = children.first; it != children.second; it++) { - // it->first - //} - // - //EntityWrapper& localHUD = m_LocalPlayer.FirstChildByName("HUD").FirstChildByName("CapturePointHUD"); - //m_World->GetComponentPools() -} - void Client::disconnect() { m_IsConnected = false; @@ -469,6 +495,11 @@ bool Client::OnPlayerDamage(const Events::PlayerDamage & e) if (e.Inflictor != m_LocalPlayer) { return false; } + // Could this happen? + //if (!clientServerMapsHasEntity(e.Inflictor.ID) + // || !clientServerMapsHasEntity(e.Victim.ID)) { + // return; + //} Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); packet.WritePrimitive(m_ClientIDToServerID.at(e.Inflictor.ID)); @@ -503,7 +534,7 @@ void Client::parsePlayerDamage(Packet& packet) Events::PlayerDamage e; PlayerID victimID = packet.ReadPrimitive(); PlayerID inflictorID = packet.ReadPrimitive(); - if(!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)){ + if (!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)) { return; } e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); @@ -515,6 +546,17 @@ 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() { if (!m_LocalPlayer.Valid()) { diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 8783a7b0..08b72304 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -13,7 +13,7 @@ Server::Server(World* world, EventBroker* eventBroker, int port) EVENT_SUBSCRIBE_MEMBER(m_EEntityDeleted, &Server::OnEntityDeleted); EVENT_SUBSCRIBE_MEMBER(m_EComponentDeleted, &Server::OnComponentDeleted); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Server::OnPlayerDamage); - + EVENT_SUBSCRIBE_MEMBER(m_EAmmoPickup, &Server::OnAmmoPickup); // BindWW if (port == 0) { port = config->Get("Networking.Port", 27666); @@ -29,9 +29,8 @@ Server::~Server() void Server::Update() { - PlayerDefinition pd; - m_Reliable.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); + for (auto& kv : m_ConnectedPlayers) { while (kv.second.TCPSocket->available()) { // Packet will get real data in receive @@ -47,6 +46,7 @@ void Server::Update() } } + PlayerDefinition pd; while (m_Unreliable.IsSocketAvailable()) { // Packet will get real data in receive Packet packet(MessageType::Invalid); @@ -65,7 +65,7 @@ void Server::Update() PlayerDefinition localArea; localArea.Endpoint = boost::asio::ip::udp::endpoint(); m_ServerlistRequest.Receive(packet, localArea); - if(packet.GetMessageType() == MessageType::ServerlistRequest) { + if (packet.GetMessageType() == MessageType::ServerlistRequest) { packet.ReadPrimitive(); // Pop size packet.ReadPrimitive(); // Pop MsgType packet.ReadPrimitive(); // Pop packet ID @@ -76,7 +76,7 @@ void Server::Update() } // 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)); } m_PlayersToDisconnect.clear(); @@ -136,7 +136,10 @@ void Server::parseMessageType(Packet& packet) parseOnPlayerDamage(packet); break; case MessageType::PlayerTransform: - parsePlayerTransform(packet); + parsePlayerTransform(packet); + break; + case MessageType::OnDoubleJump: + parseDoubleJump(packet); break; default: break; @@ -183,7 +186,7 @@ void Server::addInputCommandsToPacket(Packet& packet) void Server::addPlayersToPacket(Packet & packet, EntityID entityID) { - auto itPair = m_World->GetChildren(entityID); + auto itPair = m_World->GetDirectChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { @@ -191,49 +194,47 @@ void Server::addPlayersToPacket(Packet & packet, EntityID entityID) // 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); - if (!shouldSendToClient(childEntity)) { - continue; - } - - // Write EntityID and parentsID and Entity name - 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++; + if (shouldSendToClient(childEntity)) { + // Write EntityID and parentsID and Entity name + 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); + // 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 - addChildrenToPacket(packet, childEntityID); + addPlayersToPacket(packet, childEntityID); } } void Server::addChildrenToPacket(Packet & packet, EntityID entityID) { - auto itPair = m_World->GetChildren(entityID); + auto itPair = m_World->GetDirectChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { @@ -343,7 +344,7 @@ void Server::parseTCPConnect(Packet & packet) // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id m_PacketID = packet.ReadPrimitive(); //Read new packet id - + LOG_INFO("Parsing connections"); // Check if player is already connected // Ska vara till lagd i TCPServer receive @@ -455,8 +456,7 @@ bool Server::OnInputCommand(const Events::InputCommand & e) } isReadingData = !isReadingData; m_SaveDataTimer = std::clock(); - } - else if (e.Command == "KickPlayer" && e.Value > 0) { + } else if (e.Command == "KickPlayer" && e.Value > 0) { kick(0); } @@ -507,7 +507,20 @@ bool Server::OnPlayerDamage(const Events::PlayerDamage& e) packet.WritePrimitive(e.Damage); reliableBroadcast(packet); - return false; + return true; +} + +bool Server::OnAmmoPickup(const Events::AmmoPickup & e) +{ + for (auto& kv : m_ConnectedPlayers) { + if (e.Player.ID == kv.second.EntityID) { + Packet packet(MessageType::AmmoPickup); + // We dont send playerID as it will be set at client to local + packet.WritePrimitive(e.AmmoGain); + m_Reliable.Send(packet, kv.second); + } + } + return true; } void Server::parseClientPing() @@ -536,6 +549,12 @@ void Server::parsePing() } } +bool Server::parseDoubleJump(Packet & packet) +{ + reliableBroadcast(packet); + return true; +} + void Server::parseOnInputCommand(Packet& packet) { PlayerID player = -1; @@ -595,8 +614,17 @@ void Server::parsePlayerTransform(Packet& packet) bool Server::shouldSendToClient(EntityWrapper childEntity) { + auto children = m_World->GetDirectChildren(childEntity.ID); + for (auto it = children.first; it != children.second; it++) { + EntityWrapper child(m_World, it->second); + if (child.HasComponent("CapturePoint") || child.HasComponent("HealthPickup") + || child.HasComponent("AmmoPickup")) { + return true; + } + } return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid() - || childEntity.HasComponent("CapturePoint") || childEntity.FirstParentWithComponent("CapturePoint").Valid(); + || childEntity.HasComponent("CapturePoint") || childEntity.HasComponent("HealthPickup") + || childEntity.HasComponent("AmmoPickup"); } PlayerID Server::GetPlayerIDFromEndpoint() diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index 24a0b2c1..acd3d6d0 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -4,6 +4,8 @@ using namespace boost::asio::ip; TCPServer::TCPServer() { acceptor = std::unique_ptr(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(); } @@ -13,14 +15,24 @@ TCPServer::~TCPServer() void TCPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) { + boost::system::error_code error; boost::shared_ptr newSocket = boost::shared_ptr(new tcp::socket(m_IOService)); - m_IOService.poll(); - acceptor->async_accept(*newSocket, - boost::bind(&TCPServer::handle_accept, this, newSocket, boost::ref(nextPlayerID), boost::ref(connectedPlayers), - boost::asio::placeholders::error)); + acceptor->accept(*newSocket, error); + // If no error occured add new tcp connection + if (!error) { + // Add tcp socket to connections + 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 GetPlayerIDFromEndpoint(const std::map& connectedPlayers, +PlayerID TCPServer::getPlayerIDFromEndpoint(const std::map& connectedPlayers, boost::asio::ip::address address, unsigned short port) { for (auto& kv : connectedPlayers) { @@ -32,24 +44,6 @@ PlayerID GetPlayerIDFromEndpoint(const std::map& con return -1; } -void TCPServer::handle_accept(boost::shared_ptr socket, - int& nextPlayerID, std::map& 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) { packet.UpdateSize(); diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp index 75f5e1c9..e2a55b74 100644 --- a/src/Engine/Rendering/CubeMapPass.cpp +++ b/src/Engine/Rendering/CubeMapPass.cpp @@ -17,6 +17,7 @@ void CubeMapPass::LoadTextures(std::string input) m_CubeMapTextures.push_back(img); } GenerateCubeMapTexture(); + m_PreviusCubeMapTexture = input; } } diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index e8ad4cd5..12777941 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -1,19 +1,41 @@ #include "Rendering/DrawBloomPass.h" -DrawBloomPass::DrawBloomPass(IRenderer* renderer) +DrawBloomPass::DrawBloomPass(IRenderer* renderer, ConfigFile* config) + : m_Renderer(renderer) + , m_Config(config) { - m_Renderer = renderer; + InitializeTextures(); - m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); - - InitializeTextures(); - InitializeBuffers(); - InitializeShaderPrograms(); + ChangeQuality(m_Config->Get("GLOW.Quality", 2)); } void DrawBloomPass::InitializeTextures() { - m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); + m_BlackTexture = CommonFunctions::LoadTexture("Textures/Core/Black.png", false); +} + +void DrawBloomPass::ChangeQuality(int quality) +{ + if (m_Quality == quality) { + return; + } + m_Quality = quality; + + m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); + + if (m_Quality == 0) { + CommonFunctions::DeleteTexture(&m_GaussianTexture_horiz); + CommonFunctions::DeleteTexture(&m_GaussianTexture_vert); + m_GaussianTexture_horiz = 0; + m_GaussianTexture_vert = 0; + return; + } + InitializeTextures(); + + InitializeBuffers(); + InitializeShaderPrograms(); + std::string qStr = std::to_string(m_Quality); + m_Iterations = m_Config->Get("GLOW" + qStr + ".NumIterations", 0); } void DrawBloomPass::InitializeShaderPrograms() @@ -35,37 +57,45 @@ void DrawBloomPass::InitializeShaderPrograms() } } - void DrawBloomPass::InitializeBuffers() { - GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); - m_GaussianFrameBuffer_horiz.Generate(); + if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) { + m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); + } + m_GaussianFrameBuffer_horiz.Generate(); - GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - - m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); - m_GaussianFrameBuffer_vert.Generate(); + CommonFunctions::GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + if (m_GaussianFrameBuffer_vert.GetHandle() == 0) { + m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); + } + m_GaussianFrameBuffer_vert.Generate(); } void DrawBloomPass::ClearBuffer() { + if (m_Quality == 0) { + return; + } GLERROR("PRE"); m_GaussianFrameBuffer_horiz.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_GaussianFrameBuffer_horiz.Unbind(); m_GaussianFrameBuffer_vert.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_GaussianFrameBuffer_vert.Unbind(); GLERROR("END"); } void DrawBloomPass::Draw(GLuint texture) { + if (m_Quality == 0) { + return; + } GLERROR("DrawBloomPass::Draw: Pre"); DrawBloomPassState state; @@ -84,11 +114,12 @@ void DrawBloomPass::Draw(GLuint texture) glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); //Iterate some times to make it more gaussian. - for (int i = 1; i < m_iterations; i++) { + for (int i = 1; i < m_Iterations; i++) { //Vertical pass m_GaussianFrameBuffer_vert.Bind(); m_GaussianProgram_vert->Bind(); + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); glBindVertexArray(m_ScreenQuad->VAO); @@ -96,16 +127,19 @@ void DrawBloomPass::Draw(GLuint texture) glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); //horizontal pass + m_GaussianFrameBuffer_vert.Unbind(); m_GaussianFrameBuffer_horiz.Bind(); m_GaussianProgram_horiz->Bind(); + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_vert); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + m_GaussianFrameBuffer_horiz.Unbind(); } //final vertical gaussian after the iterations are done @@ -113,6 +147,7 @@ void DrawBloomPass::Draw(GLuint texture) m_GaussianFrameBuffer_vert.Bind(); m_GaussianProgram_vert->Bind(); + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); @@ -125,20 +160,11 @@ void DrawBloomPass::Draw(GLuint texture) void DrawBloomPass::OnWindowResize() { - GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + if (m_Quality == 0) { + return; + } + CommonFunctions::GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); m_GaussianFrameBuffer_vert.Generate(); - GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); m_GaussianFrameBuffer_horiz.Generate(); } - -void DrawBloomPass::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);//TODO: Renderer: Fix the precision and Resolution - GLERROR("Texture initialization failed"); -} diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index c82d614f..70d3a053 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -18,7 +18,7 @@ void DrawColorCorrectionPass::InitializeShaderPrograms() m_ColorCorrectionProgram->Link(); } -void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure) +void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure) { //glBindFramebuffer(GL_FRAMEBUFFER, 0); GLERROR("DrawScreenQuadPass::Draw: Pre"); @@ -33,10 +33,6 @@ void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLu glBindTexture(GL_TEXTURE_2D, sceneTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, bloomTexture); - glActiveTexture(GL_TEXTURE2); - glBindTexture(GL_TEXTURE_2D, sceneTextureLowRes); - glActiveTexture(GL_TEXTURE3); - glBindTexture(GL_TEXTURE_2D, bloomTextureLowRes); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 9b85cf98..7aa18288 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -1,9 +1,9 @@ #include "Rendering/DrawFinalPass.h" - -DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass) - : m_Renderer(renderer) - , m_LightCullingPass(lightCullingPass) - , m_CubeMapPass(cubeMapPass) +DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, SSAOPass* ssaoPass) + : m_Renderer(renderer) + , m_LightCullingPass(lightCullingPass) + , m_CubeMapPass(cubeMapPass) + , m_SSAOPass(ssaoPass) { //TODO: Make sure that uniforms are not sent into shader if not needed. m_ShieldPixelRate = 8; @@ -23,42 +23,26 @@ void DrawFinalPass::InitializeTextures() void DrawFinalPass::InitializeFrameBuffers() { - glGenRenderbuffers(1, &m_DepthBuffer); - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - GLERROR("RenderBuffer generation"); - - - GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); //GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); //GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_FLOAT, 4); //GenerateTexture(&m_StencilTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_STENCIL, GL_STENCIL_INDEX8, GL_INT); - m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); + CommonFunctions::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); + + m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); //m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SceneTexture, GL_COLOR_ATTACHMENT0))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_BloomTexture, GL_COLOR_ATTACHMENT1))); m_FinalPassFrameBuffer.Generate(); GLERROR("FBO generation"); - glGenRenderbuffers(1, &m_DepthBufferLowRes); - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBufferLowRes); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)); - GLERROR("RenderBufferLowRes generation"); - - GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); - //GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); - //GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_FLOAT, 4); - //GenerateTexture(&m_StencilTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_STENCIL, GL_STENCIL_INDEX8, GL_INT); - - m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBufferLowRes, GL_DEPTH_STENCIL_ATTACHMENT))); - //m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT))); - m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_SceneTextureLowRes, GL_COLOR_ATTACHMENT0))); - m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_BloomTextureLowRes, GL_COLOR_ATTACHMENT1))); - m_FinalPassFrameBufferLowRes.Generate(); - GLERROR("FBO2 generation"); + CommonFunctions::GenerateTexture(&m_ShieldBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST, + glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT); + m_ShieldDepthFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_ShieldBuffer, GL_DEPTH_ATTACHMENT))); + m_ShieldDepthFrameBuffer.Generate(); } void DrawFinalPass::InitializeShaderPrograms() @@ -90,6 +74,7 @@ void DrawFinalPass::InitializeShaderPrograms() m_SpriteProgram->BindFragDataLocation(1, "bloomColor"); m_SpriteProgram->Link(); GLERROR("Creating sprite program"); + m_ForwardPlusSplatMapProgram = ResourceManager::Load("#ForwardPlusSplatMapProgram"); m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGB.frag.glsl"))); @@ -145,40 +130,120 @@ void DrawFinalPass::InitializeShaderPrograms() m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor"); m_ForwardPlusSplatMapSkinnedProgram->Link(); GLERROR("Creating Forward SplatMap Skinned program"); + + m_FillDepthStencilBufferProgram = ResourceManager::Load("#FillDepthBufferProgram"); + m_FillDepthStencilBufferProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBuffer.vert.glsl"))); + m_FillDepthStencilBufferProgram->Compile(); + m_FillDepthStencilBufferProgram->Link(); + GLERROR("Creating DepthFill program"); + + m_FillDepthStencilBufferSkinnedProgram = ResourceManager::Load("#FillDepthBufferProgramSkinned"); + m_FillDepthStencilBufferSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBufferSkinned.vert.glsl"))); + m_FillDepthStencilBufferSkinnedProgram->Compile(); + m_FillDepthStencilBufferSkinnedProgram->Link(); + GLERROR("Creating DepthFill program"); + + + + + + m_ForwardPlusShieldCheckProgram = ResourceManager::Load("#ForwardPlusShieldCheckProgram"); + m_ForwardPlusShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); + m_ForwardPlusShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusShieldCheck.frag.glsl"))); + m_ForwardPlusShieldCheckProgram->Compile(); + m_ForwardPlusShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); + m_ForwardPlusShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); + m_ForwardPlusShieldCheckProgram->Link(); + GLERROR("Creating forward+ program"); + + m_ExplosionEffectShieldCheckProgram = ResourceManager::Load("#ExplosionEffectShieldCheckProgram"); + m_ExplosionEffectShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); + m_ExplosionEffectShieldCheckProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); + m_ExplosionEffectShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusShieldCheck.frag.glsl"))); + m_ExplosionEffectShieldCheckProgram->Compile(); + m_ExplosionEffectShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectShieldCheckProgram->Link(); + GLERROR("Creating explosion program"); + + m_SpriteShieldCheckProgram = ResourceManager::Load("#SpriteShieldCheckProgram"); + m_SpriteShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/Sprite.vert.glsl"))); + m_SpriteShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SpriteShieldCheck.frag.glsl"))); + m_SpriteShieldCheckProgram->Compile(); + m_SpriteShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); + m_SpriteShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); + m_SpriteShieldCheckProgram->Link(); + GLERROR("Creating sprite program"); + + m_ForwardPlusSplatMapShieldCheckProgram = ResourceManager::Load("#ForwardPlusSplatMapShieldCheckProgram"); + m_ForwardPlusSplatMapShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); + m_ForwardPlusSplatMapShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl"))); + m_ForwardPlusSplatMapShieldCheckProgram->Compile(); + m_ForwardPlusSplatMapShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); + m_ForwardPlusSplatMapShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); + m_ForwardPlusSplatMapShieldCheckProgram->Link(); + GLERROR("Creating Forward SplatMap program"); + + m_ExplosionEffectSplatMapShieldCheckProgram = ResourceManager::Load("#ExplosionEffectSplatMapShieldCheckProgram"); + m_ExplosionEffectSplatMapShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); + m_ExplosionEffectSplatMapShieldCheckProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); + m_ExplosionEffectSplatMapShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl"))); + m_ExplosionEffectSplatMapShieldCheckProgram->Compile(); + m_ExplosionEffectSplatMapShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectSplatMapShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectSplatMapShieldCheckProgram->Link(); + GLERROR("Creating explosion SplatMap program"); + + m_ForwardPlusSkinnedShieldCheckProgram = ResourceManager::Load("#ForwardPlusSkinnedShieldCheckProgram"); + m_ForwardPlusSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ForwardPlusSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusShieldCheck.frag.glsl"))); + m_ForwardPlusSkinnedShieldCheckProgram->Compile(); + m_ForwardPlusSkinnedShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); + m_ForwardPlusSkinnedShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); + m_ForwardPlusSkinnedShieldCheckProgram->Link(); + GLERROR("Creating forward+ Skinned program"); + + m_ExplosionEffectSkinnedShieldCheckProgram = ResourceManager::Load("#ExplosionEffectSkinnedShieldCheckProgram"); + m_ExplosionEffectSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ExplosionEffectSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); + m_ExplosionEffectSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusShieldCheck.frag.glsl"))); + m_ExplosionEffectSkinnedShieldCheckProgram->Compile(); + m_ExplosionEffectSkinnedShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectSkinnedShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectSkinnedShieldCheckProgram->Link(); + GLERROR("Creating explosion Skinned program"); + + m_ExplosionEffectSplatMapSkinnedShieldCheckProgram = ResourceManager::Load("#ExplosionEffectSplatMapSkinnedShieldCheckProgram"); + m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl"))); + m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->Compile(); + m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->Link(); + GLERROR("Creating Forward SplatMap Skinned program"); + + m_ForwardPlusSplatMapSkinnedShieldCheckProgram = ResourceManager::Load("#ForwardPlusSplatMapSkinnedShieldCheckProgram"); + m_ForwardPlusSplatMapSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ForwardPlusSplatMapSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl"))); + m_ForwardPlusSplatMapSkinnedShieldCheckProgram->Compile(); + m_ForwardPlusSplatMapSkinnedShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); + m_ForwardPlusSplatMapSkinnedShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); + m_ForwardPlusSplatMapSkinnedShieldCheckProgram->Link(); + GLERROR("Creating Forward SplatMap Skinned program"); - m_ShieldToStencilProgram = ResourceManager::Load("#ShieldToStencilProgram"); - m_ShieldToStencilProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ShieldStencil.vert.glsl"))); - m_ShieldToStencilProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ShieldStencil.frag.glsl"))); - m_ShieldToStencilProgram->Compile(); - m_ShieldToStencilProgram->Link(); - GLERROR("Creating Shield program"); - - m_ShieldToStencilSkinnedProgram = ResourceManager::Load("#ShieldToStencilProgramSkinned"); - m_ShieldToStencilSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ShieldStencilSkinned.vert.glsl"))); - m_ShieldToStencilSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ShieldStencil.frag.glsl"))); - m_ShieldToStencilSkinnedProgram->Compile(); - m_ShieldToStencilSkinnedProgram->Link(); - GLERROR("Creating Shield Skinned program"); - - m_FillDepthBufferProgram = ResourceManager::Load("#FillDepthBufferProgram"); - m_FillDepthBufferProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBuffer.vert.glsl"))); - m_FillDepthBufferProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); - m_FillDepthBufferProgram->Compile(); - m_FillDepthBufferProgram->Link(); - GLERROR("Creating DepthFill program"); - - m_FillDepthBufferSkinnedProgram = ResourceManager::Load("#FillDepthBufferProgramSkinned"); - m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBufferSkinned.vert.glsl"))); - m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); - m_FillDepthBufferSkinnedProgram->Compile(); - m_FillDepthBufferSkinnedProgram->Link(); - GLERROR("Creating DepthFill program"); } -void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) +void DrawFinalPass::Draw(RenderScene& scene) { GLERROR("Pre"); - DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); + DrawFinalPassState* stateDethp = new DrawFinalPassState(m_ShieldDepthFrameBuffer.GetHandle()); + //Draw shields to stencil + DrawToDepthStencilBuffer(scene.Jobs.ShieldObjects, scene); + GLERROR("StencilPass"); + delete stateDethp; + + + DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); if (scene.ClearDepth) { //glClear(GL_DEPTH_BUFFER_BIT); state->Disable(GL_DEPTH_TEST); @@ -189,99 +254,53 @@ void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) glClear(GL_STENCIL_BUFFER_BIT); //Fill depth buffer - - state->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); - GLERROR("OpaqueObjects"); - state->BlendFunc(GL_ONE, GL_ONE); - DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); - GLERROR("TransparentObjects"); - state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - DrawSprites(scene.Jobs.SpriteJob, scene); - GLERROR("SpriteJobs"); - - //DrawStencilState* stencilState = new DrawStencilState(m_FinalPassFrameBuffer.GetHandle()); - //Draw shields to stencil pass - state->StencilFunc(GL_ALWAYS, 1, 0xFF); - state->StencilMask(0xFF); - DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); - GLERROR("StencilPass"); + state->Enable(GL_STENCIL_TEST); + state->StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); + state->StencilFunc(GL_ALWAYS, 1, 0xFF); + state->StencilMask(0xFF); + state->DepthMask(GL_FALSE); + //DrawToDepthStencilBuffer(scene.Jobs.ShieldObjects, scene); + state->DepthMask(GL_TRUE); //Draw Opaque shielded objects + state->Disable(GL_STENCIL_TEST); state->StencilFunc(GL_NOTEQUAL, 1, 0xFF); state->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene, SSAOTexture); //might need changing + DrawModelRenderQueuesWithShieldCheck(scene.Jobs.OpaqueShieldedObjects, scene); //might need changing GLERROR("Shielded Opaque object"); + //Draw Opaque objects + //state->StencilMask(0x00); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); + GLERROR("OpaqueObjects"); + + //state->Disable(GL_STENCIL_TEST); //Draw Transparen Shielded objects - DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene, SSAOTexture); //might need changing + state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + DrawModelRenderQueuesWithShieldCheck(scene.Jobs.TransparentObjects, scene); //might need changing GLERROR("Shielded Transparent objects"); + //Draw Transparen objects + //state->BlendFunc(GL_ONE, GL_ONE); + //state->StencilFunc(GL_EQUAL, 1, 0xFF); + //DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); + GLERROR("TransparentObjects"); + //state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + DrawSprites(scene.Jobs.SpriteJob, scene); + GLERROR("SpriteJobs"); + + delete state; GLERROR("END"); - delete state; - - - DrawFinalPassState* stateLowRes = new DrawFinalPassState(m_FinalPassFrameBufferLowRes.GetHandle()); - //Draw the lowres texture that will be shown behind the shield. - stateLowRes->Enable(GL_SCISSOR_TEST); - stateLowRes->Enable(GL_DEPTH_TEST); - //TODO: Viewports and scissor should be in state - 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); - - glClearStencil(0x00); - glClear(GL_STENCIL_BUFFER_BIT); - - //TODO: This should not be here... - stateLowRes->StencilFunc(GL_ALWAYS, 1, 0xFF); - stateLowRes->StencilMask(0x00); - DrawToDepthBuffer(scene.Jobs.OpaqueObjects, scene); - DrawToDepthBuffer(scene.Jobs.TransparentObjects, scene); - - //Draw shields to stencil pass - stateLowRes->StencilFunc(GL_ALWAYS, 1, 0xFF); - stateLowRes->StencilMask(0xFF); - stateLowRes->Enable(GL_DEPTH_TEST); - DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); - GLERROR("StencilPass"); - - //glClear(GL_DEPTH_BUFFER_BIT); - - stateLowRes->Enable(GL_DEPTH_TEST); - stateLowRes->StencilFunc(GL_LEQUAL, 1, 0xFF); - stateLowRes->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); - GLERROR("OpaqueObjects"); - DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); - GLERROR("TransparentObjects"); - glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - delete stateLowRes; + } void DrawFinalPass::ClearBuffer() { GLERROR("PRE"); - m_FinalPassFrameBufferLowRes.Bind(); - GLERROR("Bind LowRes"); - - 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); - GLERROR("ViewPort,Scissor LowRes"); - - glClearColor(0.f, 0.f, 0.f, 0.f); - GLERROR("1"); - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - GLERROR("2"); - - glDisable(GL_SCISSOR_TEST); - GLERROR("3"); - - m_FinalPassFrameBufferLowRes.Unbind(); - - GLERROR("prebind HighRes"); + m_ShieldDepthFrameBuffer.Bind(); + glClear(GL_DEPTH_BUFFER_BIT); + m_ShieldDepthFrameBuffer.Unbind(); m_FinalPassFrameBuffer.Bind(); GLERROR("Bind HighRes"); glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); @@ -297,145 +316,105 @@ void DrawFinalPass::ClearBuffer() void DrawFinalPass::OnWindowResize() { //InitializeFrameBuffers(); - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - - GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::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); + CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); m_FinalPassFrameBuffer.Generate(); - - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBufferLowRes); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)); - - GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); - GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); - m_FinalPassFrameBufferLowRes.Generate(); GLERROR("Error changing texture resolutions"); } -void DrawFinalPass::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);//TODO: Renderer: Fix the precision and Resolution - GLERROR("Texture initialization failed"); -} - -void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const -{ - glGenTextures(1, texture); - glBindTexture(GL_TEXTURE_2D, *texture); - glTexStorage2D(GL_TEXTURE_2D, numMipMaps, GL_RGBA8, dimensions.x, dimensions.y); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dimensions.x, dimensions.y, format, type, texture); - glGenerateMipmap(GL_TEXTURE_2D); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - GLERROR("MipMap Texture initialization failed"); -} - -void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene, GLuint SSAOTexture) +void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); - GLERROR("forwardHandle"); GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); - GLERROR("explosionHandle"); GLuint explosionSplatMapHandle = m_ExplosionEffectSplatMapProgram->GetHandle(); - GLERROR("explosionSplatMapHandle"); - GLuint forwardSplatHandle = m_ForwardPlusSplatMapProgram->GetHandle(); - GLERROR("forwardSplatHandle"); + GLuint forwardSplatMapHandle = m_ForwardPlusSplatMapProgram->GetHandle(); GLuint forwardSkinnedHandle = m_ForwardPlusSkinnedProgram->GetHandle(); - GLERROR("forwardSkinnedHandle"); GLuint explosionSkinnedHandle = m_ExplosionEffectSkinnedProgram->GetHandle(); - GLERROR("explosionSkinnedHandle"); GLuint explosionSplatMapSkinnedHandle = m_ExplosionEffectSplatMapSkinnedProgram->GetHandle(); - GLERROR("explosionSplatMapSkinnedHandle"); GLuint forwardSplatMapSkinnedHandle = m_ForwardPlusSplatMapSkinnedProgram->GetHandle(); - GLERROR("forwardSplatSkinnedHandle"); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, SSAOTexture); + glBindTexture(GL_TEXTURE_2D, m_SSAOPass->SSAOTexture()); for (auto &job : jobs) { auto explosionEffectJob = std::dynamic_pointer_cast(job); if (explosionEffectJob) { switch (explosionEffectJob->Type) { case RawModel::MaterialType::Basic: - case RawModel::MaterialType::SingleTextures: - { - if (explosionEffectJob->Model->IsSkinned()) { + case RawModel::MaterialType::SingleTextures: + { + if (explosionEffectJob->Model->IsSkinned()) { - m_ExplosionEffectSkinnedProgram->Bind(); - GLERROR("Bind ExplosionEffectSkinned program"); - //bind uniforms - BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(explosionSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + m_ExplosionEffectSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(explosionSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } else { - m_ExplosionEffectProgram->Bind(); - GLERROR("Bind ExplosionEffect program"); - //bind uniforms - BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionHandle, explosionEffectJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(explosionHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - - } - break; - } - case RawModel::MaterialType::SplatMapping: - { - if (explosionEffectJob->Model->IsSkinned()) { - m_ExplosionEffectSplatMapSkinnedProgram->Bind(); - GLERROR("Bind ExplosionEffectSplatMapSkinned program"); - //bind uniforms - BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); - GLERROR("asdasd"); - std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - - } else { - m_ExplosionEffectSplatMapProgram->Bind(); - GLERROR("Bind ExplosionEffectSplatMap program"); - //bind uniforms - //bind uniforms - BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob); - GLERROR("asdasd"); - } - break; - } + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } + else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + else { + m_ExplosionEffectProgram->Bind(); + GLERROR("Bind ExplosionEffect program"); + //bind uniforms + BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(explosionHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (explosionEffectJob->Model->IsSkinned()) { + m_ExplosionEffectSplatMapSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMapSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); + GLERROR("asdasd"); + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } + else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + else { + m_ExplosionEffectSplatMapProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMap program"); + //bind uniforms + //bind uniforms + BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob); + GLERROR("asdasd"); + } + break; + } } glDisable(GL_CULL_FACE); @@ -445,136 +424,444 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); glEnable(GL_CULL_FACE); GLERROR("explosion effect end"); - } else { - auto modelJob = std::dynamic_pointer_cast(job); - if (modelJob) { - //bind forward program - //TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID; - switch (modelJob->Type) { - case RawModel::MaterialType::Basic: - case RawModel::MaterialType::SingleTextures: - { - if (modelJob->Model->IsSkinned()) { - m_ForwardPlusSkinnedProgram->Bind(); - GLERROR("Bind ForwardPlusSkinnedProgram"); - //bind uniforms - BindModelUniforms(forwardSkinnedHandle, modelJob, scene); + } else { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + //bind forward program + //TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID; + switch (modelJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (modelJob->Model->IsSkinned()) { + m_ForwardPlusSkinnedProgram->Bind(); + GLERROR("Bind ForwardPlusSkinnedProgram"); + //bind uniforms + BindModelUniforms(forwardSkinnedHandle, modelJob, scene); GLERROR("Basic/SingleTextures BindModelUniforms"); - //bind textures - BindModelTextures(forwardSkinnedHandle, modelJob); + //bind textures + BindModelTextures(forwardSkinnedHandle, modelJob); GLERROR("Basic/SingleTextures BindModelTextures"); - glActiveTexture(GL_TEXTURE5); + glActiveTexture(GL_TEXTURE5); GLERROR("Basic/SingleTextures CameraPosition1"); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); GLERROR("Basic/SingleTextures CameraPosition2"); glUniform3fv(glGetUniformLocation(forwardSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); GLERROR("Basic/SingleTextures CameraPosition3"); - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } + else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); GLERROR("Basic/SingleTextures skinned end"); - } else { - m_ForwardPlusProgram->Bind(); - GLERROR("Bind ForwardPlusProgram"); - //bind uniforms - BindModelUniforms(forwardHandle, modelJob, scene); - //bind textures - 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())); + } + else { + m_ForwardPlusProgram->Bind(); + GLERROR("Bind ForwardPlusProgram"); + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + //bind textures + 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())); GLERROR("Basic/SingleTextures end"); - } - break; - } - case RawModel::MaterialType::SplatMapping: - { - if (modelJob->Model->IsSkinned()) { - m_ForwardPlusSplatMapSkinnedProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (modelJob->Model->IsSkinned()) { + m_ForwardPlusSplatMapSkinnedProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); + GLERROR("asdasd"); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } + else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); GLERROR("SplatMapping skinned end"); - } else { - m_ForwardPlusSplatMapProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatHandle, modelJob); - GLERROR("SplatMapping end"); - } - break; - } - } - //draw - glBindVertexArray(modelJob->Model->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); - glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); - if (GLERROR("models end")) { - continue; - } + } + else { + m_ForwardPlusSplatMapProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatMapHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatMapHandle, modelJob); + GLERROR("SplatMapping end"); + } + break; + } } - } - } -} - - -void DrawFinalPass::DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene) -{ - - - for (auto &job : jobs) { - auto modelJob = std::dynamic_pointer_cast(job); - if (modelJob) { - - if(modelJob->Model->IsSkinned()) { - m_ShieldToStencilSkinnedProgram->Bind(); - GLuint shaderHandle = m_ShieldToStencilSkinnedProgram->GetHandle(); - - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + //draw + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); + if (GLERROR("models end")) { + continue; } - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } else { - m_ShieldToStencilProgram->Bind(); - GLuint shaderHandle = m_ShieldToStencilProgram->GetHandle(); - - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); - - } - - glBindVertexArray(modelJob->Model->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); - glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); - if (GLERROR("models end")) { - continue; } } } } +void DrawFinalPass::DrawModelRenderQueuesWithShieldCheck(std::list>& jobs, RenderScene& scene) +{ + GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); + GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); + GLuint explosionSplatMapHandle = m_ExplosionEffectSplatMapProgram->GetHandle(); + GLuint forwardSplatMapHandle = m_ForwardPlusSplatMapProgram->GetHandle(); + GLuint forwardSkinnedHandle = m_ForwardPlusSkinnedProgram->GetHandle(); + GLuint explosionSkinnedHandle = m_ExplosionEffectSkinnedProgram->GetHandle(); + GLuint explosionSplatMapSkinnedHandle = m_ExplosionEffectSplatMapSkinnedProgram->GetHandle(); + GLuint forwardSplatMapSkinnedHandle = m_ForwardPlusSplatMapSkinnedProgram->GetHandle(); + + GLuint forwardShieldCheckHandle = m_ForwardPlusShieldCheckProgram->GetHandle(); + GLuint explosionShieldCheckHandle = m_ExplosionEffectShieldCheckProgram->GetHandle(); + GLuint explosionSplatMapShieldCheckHandle = m_ExplosionEffectSplatMapShieldCheckProgram->GetHandle(); + GLuint forwardSplatShieldCheckHandle = m_ForwardPlusSplatMapShieldCheckProgram->GetHandle(); + GLuint forwardSkinnedShieldCheckHandle = m_ForwardPlusSkinnedShieldCheckProgram->GetHandle(); + GLuint explosionSkinnedShieldCheckHandle = m_ExplosionEffectSkinnedShieldCheckProgram->GetHandle(); + GLuint explosionSplatMapSkinnedShieldCheckHandle = m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->GetHandle(); + GLuint forwardSplatMapSkinnedShieldCheckHandle = m_ForwardPlusSplatMapSkinnedShieldCheckProgram->GetHandle(); + + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_SSAOPass->SSAOTexture()); + + glActiveTexture(GL_TEXTURE31); + glBindTexture(GL_TEXTURE_2D, m_ShieldBuffer); + + for (auto &job : jobs) { + auto explosionEffectJob = std::dynamic_pointer_cast(job); + if (explosionEffectJob) { + if (explosionEffectJob->IsShielded) { + switch (explosionEffectJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (explosionEffectJob->Model->IsSkinned()) { + + m_ExplosionEffectSkinnedShieldCheckProgram->Bind(); + GLERROR("Bind ExplosionEffectSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSkinnedShieldCheckHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSkinnedShieldCheckHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(explosionSkinnedShieldCheckHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } + else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedShieldCheckHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + else { + m_ExplosionEffectShieldCheckProgram->Bind(); + GLERROR("Bind ExplosionEffect program"); + //bind uniforms + BindExplosionUniforms(explosionShieldCheckHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionShieldCheckHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(explosionShieldCheckHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (explosionEffectJob->Model->IsSkinned()) { + m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMapSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSplatMapSkinnedShieldCheckHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapSkinnedShieldCheckHandle, explosionEffectJob); + GLERROR("asdasd"); + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } + else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedShieldCheckHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } + else { + m_ExplosionEffectSplatMapShieldCheckProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMap program"); + //bind uniforms + //bind uniforms + BindExplosionUniforms(explosionSplatMapShieldCheckHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapShieldCheckHandle, explosionEffectJob); + GLERROR("asdasd"); + } + break; + } + } + } else { + switch (explosionEffectJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (explosionEffectJob->Model->IsSkinned()) { + + m_ExplosionEffectSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(explosionSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } + else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + else { + m_ExplosionEffectProgram->Bind(); + GLERROR("Bind ExplosionEffect program"); + //bind uniforms + BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(explosionHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (explosionEffectJob->Model->IsSkinned()) { + m_ExplosionEffectSplatMapSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMapSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); + GLERROR("asdasd"); + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } + else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + else { + m_ExplosionEffectSplatMapProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMap program"); + //bind uniforms + //bind uniforms + BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob); + GLERROR("asdasd"); + } + break; + } + } + } + glDisable(GL_CULL_FACE); + + //draw + glBindVertexArray(explosionEffectJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); + glEnable(GL_CULL_FACE); + GLERROR("explosion effect end"); + } else { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + //bind forward program + //TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID; + if (modelJob->IsShielded) { + switch (modelJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (modelJob->Model->IsSkinned()) { + m_ForwardPlusSkinnedShieldCheckProgram->Bind(); + GLERROR("Bind ForwardPlusSkinnedProgram"); + //bind uniforms + BindModelUniforms(forwardSkinnedShieldCheckHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSkinnedShieldCheckHandle, modelJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardSkinnedShieldCheckHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } + else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedShieldCheckHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } + else { + m_ForwardPlusShieldCheckProgram->Bind(); + GLERROR("Bind ForwardPlusProgram"); + //bind uniforms + BindModelUniforms(forwardShieldCheckHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardShieldCheckHandle, modelJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardShieldCheckHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (modelJob->Model->IsSkinned()) { + m_ForwardPlusSplatMapSkinnedShieldCheckProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatMapSkinnedShieldCheckHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatMapSkinnedShieldCheckHandle, modelJob); + GLERROR("asdasd"); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } + else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedShieldCheckHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } + else { + m_ForwardPlusSplatMapShieldCheckProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatShieldCheckHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatShieldCheckHandle, modelJob); + GLERROR("asdasd"); + } + break; + } + } + } else { + switch (modelJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (modelJob->Model->IsSkinned()) { + m_ForwardPlusSkinnedProgram->Bind(); + GLERROR("Bind ForwardPlusSkinnedProgram"); + //bind uniforms + BindModelUniforms(forwardSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSkinnedHandle, modelJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } + else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } + else { + m_ForwardPlusProgram->Bind(); + GLERROR("Bind ForwardPlusProgram"); + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + //bind textures + 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; + } + case RawModel::MaterialType::SplatMapping: + { + if (modelJob->Model->IsSkinned()) { + m_ForwardPlusSplatMapSkinnedProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); + GLERROR("asdasd"); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } + else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } + else { + m_ForwardPlusSplatMapProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatMapHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatMapHandle, modelJob); + GLERROR("asdasd"); + } + break; + } + } + } + //draw + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); + if (GLERROR("models end")) { + continue; + } + } + } + } +} + void DrawFinalPass::DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); @@ -667,7 +954,7 @@ void DrawFinalPass::DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene) +void DrawFinalPass::DrawToDepthStencilBuffer(std::list>& jobs, RenderScene& scene) { @@ -675,8 +962,8 @@ void DrawFinalPass::DrawToDepthBuffer(std::list>& job auto modelJob = std::dynamic_pointer_cast(job); if(modelJob->Model->IsSkinned()) { - m_FillDepthBufferSkinnedProgram->Bind(); - GLuint shaderHandle = m_FillDepthBufferSkinnedProgram->GetHandle(); + m_FillDepthStencilBufferSkinnedProgram->Bind(); + GLuint shaderHandle = m_FillDepthStencilBufferSkinnedProgram->GetHandle(); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); @@ -690,8 +977,8 @@ void DrawFinalPass::DrawToDepthBuffer(std::list>& job glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { - m_FillDepthBufferProgram->Bind(); - GLuint shaderHandle = m_FillDepthBufferProgram->GetHandle(); + m_FillDepthStencilBufferProgram->Bind(); + GLuint shaderHandle = m_FillDepthStencilBufferProgram->GetHandle(); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); @@ -757,6 +1044,7 @@ void DrawFinalPass::DrawSprites(std::list>&jobs, Rend void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { + glUniform1i(glGetUniformLocation(shaderHandle, "SSAOQuality"), m_SSAOPass->TextureQuality()); GLERROR("Bind 1 uniform"); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); GLERROR("Bind 2 uniform"); @@ -805,6 +1093,7 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { + glUniform1i(glGetUniformLocation(shaderHandle, "SSAOQuality"), m_SSAOPass->TextureQuality()); GLERROR("Bind 1 uniform"); GLint Location_M = glGetUniformLocation(shaderHandle, "M"); glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); diff --git a/src/Engine/Rendering/DrawFinalPassState.cpp b/src/Engine/Rendering/DrawFinalPassState.cpp index 8b5ddc8b..5c238985 100644 --- a/src/Engine/Rendering/DrawFinalPassState.cpp +++ b/src/Engine/Rendering/DrawFinalPassState.cpp @@ -8,11 +8,12 @@ DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) Enable(GL_BLEND); BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Enable(GL_DEPTH_TEST); + DepthMask(GL_TRUE); Enable(GL_CULL_FACE); - Enable(GL_STENCIL_TEST); - StencilFunc(GL_NOTEQUAL, 1, 0xFF); - StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); - StencilMask(0xFF); + // Enable(GL_STENCIL_TEST); + // StencilFunc(GL_NOTEQUAL, 1, 0xFF); + // StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); + // StencilMask(0xFF); ClearColor(glm::vec4(0.f, 0.f, 0.f, 0.f)); } @@ -24,11 +25,9 @@ DrawFinalPassState::~DrawFinalPassState() DrawStencilState::DrawStencilState(GLuint frameBuffer) { BindFramebuffer(frameBuffer); - Enable(GL_STENCIL_TEST); - StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); - StencilFunc(GL_ALWAYS, 1, 0xFF); - StencilMask(0xFF); Enable(GL_DEPTH_TEST); + DepthMask(GL_TRUE); + Enable(GL_CULL_FACE); ClearColor(glm::vec4(0.f)); } diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index 794fb84e..9ba0d2d8 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -42,33 +42,33 @@ void FrameBuffer::Generate() GLERROR("PRE"); std::vector attachments; - - glGenFramebuffers(1, &m_BufferHandle); + if (m_BufferHandle == 0) { + glGenFramebuffers(1, &m_BufferHandle); + } glBindFramebuffer(GL_FRAMEBUFFER, m_BufferHandle); GLERROR("1"); - for (auto it = m_Resources.begin(); it != m_Resources.end(); it++) { - switch ((*it)->m_ResourceType) { - case GL_TEXTURE_2D: - glFramebufferTexture2D(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle, 0); - GLERROR("FrameBuffer generate: glFramebufferTexture2D"); + for (auto it = m_Resources.begin(); it != m_Resources.end(); it++) { + switch ((*it)->m_ResourceType) { + case GL_TEXTURE_2D: + glFramebufferTexture2D(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle, 0); + GLERROR("FrameBuffer generate: glFramebufferTexture2D"); - break; - case GL_RENDERBUFFER: - glFramebufferRenderbuffer(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle); - GLERROR("FrameBuffer generate: glFramebufferRenderbuffer"); - break; - } - GLERROR("2"); + break; + case GL_RENDERBUFFER: + glFramebufferRenderbuffer(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle); + GLERROR("FrameBuffer generate: glFramebufferRenderbuffer"); + break; + } + GLERROR("2"); - if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT && (*it)->m_Attachment != GL_STENCIL_ATTACHMENT && (*it)->m_Attachment != GL_DEPTH_STENCIL_ATTACHMENT) { - attachments.push_back((*it)->m_Attachment); - } - GLERROR("Attachment"); - - } - GLERROR("3"); + if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT && (*it)->m_Attachment != GL_STENCIL_ATTACHMENT && (*it)->m_Attachment != GL_DEPTH_STENCIL_ATTACHMENT) { + attachments.push_back((*it)->m_Attachment); + } + GLERROR("Attachment"); + } + GLERROR("3"); GLenum* bufferTextures = &attachments[0]; glDrawBuffers(attachments.size(), bufferTextures); diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 1eab9939..7b9e2498 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -19,15 +19,16 @@ PickingPass::~PickingPass() void PickingPass::InitializeTextures() { - GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, + CommonFunctions::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); - 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); + CommonFunctions::GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST, + glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT); } void PickingPass::InitializeFrameBuffers() { + m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0))); m_PickingBuffer.Generate(); @@ -366,7 +367,7 @@ void PickingPass::ClearPicking() m_PickingBuffer.Bind(); 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 | GL_STENCIL_BUFFER_BIT); m_PickingBuffer.Unbind(); GLERROR("END"); } @@ -407,16 +408,3 @@ PickData PickingPass::Pick(glm::vec2 screenCoord) pickData.World = pickInfo.World; return pickData; } - -void PickingPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const -{ - //TODO: Renderer: Make this in a sparate class - 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);//TODO: Renderer: Fix the precision and Resolution - GLERROR("Texture initialization failed"); -} diff --git a/src/Engine/Rendering/PickingPassState.cpp b/src/Engine/Rendering/PickingPassState.cpp index f2d42bff..767b9577 100644 --- a/src/Engine/Rendering/PickingPassState.cpp +++ b/src/Engine/Rendering/PickingPassState.cpp @@ -9,11 +9,11 @@ PickingPassState::PickingPassState(GLuint frameBuffer) Enable(GL_DEPTH_TEST); Enable(GL_CULL_FACE); Disable(GL_BLEND); - glm::vec4 clearColor = glm::vec4(0.f); //ClearColor(clearColor); //Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GLERROR("END"); + } PickingPassState::~PickingPassState() diff --git a/src/Engine/Rendering/RenderState.cpp b/src/Engine/Rendering/RenderState.cpp index 26ba18a1..56812f9a 100644 --- a/src/Engine/Rendering/RenderState.cpp +++ b/src/Engine/Rendering/RenderState.cpp @@ -135,6 +135,26 @@ bool RenderState::DepthMask(GLboolean flag) return !GLERROR("DepthMask"); } +bool RenderState::DepthFunc(GLenum func) +{ + GLint original; + glGetIntegerv(GL_DEPTH_FUNC, &original); + m_ResetFunctions.push_back(std::bind(glDepthFunc, original)); + glDepthFunc(func); + return !GLERROR("DepthFunc"); +} + +bool RenderState::AlphaFunc(GLenum func, GLclampf thresholder) +{ + GLint originalFunc; + glGetIntegerv(GL_ALPHA_TEST_FUNC, &originalFunc); + GLint originalRef; + glGetIntegerv(GL_ALPHA_TEST_REF, &originalRef); + m_ResetFunctions.push_back(std::bind(glAlphaFunc, originalFunc, originalRef)); + glAlphaFunc(func, thresholder); + return !GLERROR("AlphaFunc"); +} + RenderState::~RenderState() { for (auto& f : boost::adaptors::reverse(m_ResetFunctions)) { diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 7b0ea84f..a1f00c88 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -240,6 +240,8 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) fillColor = (glm::vec4)fillComponent["Color"]; } + bool isShielded = m_World->HasComponent(cModel.EntityID, "Shielded") || m_World->HasComponent(cModel.EntityID, "Player"); + glm::mat4 modelMatrix = Transform::ModelMatrix(cModel.EntityID, m_World); //Loop through all materialgroups of a model for (auto matGroup : model->MaterialGroups()) { @@ -255,20 +257,19 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) cModel, m_World, fillColor, - fillPercentage + fillPercentage, + isShielded )); if (m_World->HasComponent(cModel.EntityID, "Shield")){ explosionEffectJob->CalculateHash(); Jobs.ShieldObjects.push_back(explosionEffectJob); - } else if (m_World->HasComponent(cModel.EntityID, "Shielded") - || m_World->HasComponent(cModel.EntityID, "Player")) { - + } else if (isShielded) { if (explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { cModel["Transparent"] = true; } if (cModel["Transparent"]) { - Jobs.TransparentShieldedObjects.push_back(explosionEffectJob); + Jobs.TransparentObjects.push_back(explosionEffectJob); } else { explosionEffectJob->CalculateHash(); Jobs.OpaqueShieldedObjects.push_back(explosionEffectJob); @@ -294,20 +295,20 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) cModel, m_World, fillColor, - fillPercentage + fillPercentage, + isShielded )); if (m_World->HasComponent(cModel.EntityID, "Shield")) { modelJob->CalculateHash(); Jobs.ShieldObjects.push_back(modelJob); - } else if (m_World->HasComponent(cModel.EntityID, "Shielded") - || m_World->HasComponent(cModel.EntityID, "Player")) { + } else if (isShielded) { if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { cModel["Transparent"] = true; } if (cModel["Transparent"]) { - Jobs.TransparentShieldedObjects.push_back(modelJob); + Jobs.TransparentObjects.push_back(modelJob); } else { modelJob->CalculateHash(); Jobs.OpaqueShieldedObjects.push_back(modelJob); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 251bba2b..3ce985b6 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -4,6 +4,8 @@ std::unordered_map Renderer::m_WindowToRenderer; void Renderer::Initialize() { + m_SSAO_Quality = m_Config->Get("SSAO.Quality", 0); + m_GLOW_Quality = m_Config->Get("GLOW.Quality", 0); InitializeWindow(); InitializeRenderPasses(); @@ -26,9 +28,9 @@ void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height glViewport(0, 0, width, height); Renderer* currentRenderer = m_WindowToRenderer[window]; currentRenderer->m_ViewportSize = Rectangle(width, height); + currentRenderer->m_PickingPass->OnWindowResize(); currentRenderer->m_DrawFinalPass->OnWindowResize(); currentRenderer->m_LightCullingPass->OnWindowResize(); - currentRenderer->m_PickingPass->OnWindowResize(); currentRenderer->m_DrawBloomPass->OnWindowResize(); currentRenderer->m_SSAOPass->OnWindowResize(); } @@ -107,7 +109,8 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { GLERROR("PRE"); - ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0Ambient Occlusion"); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0Gaussian\0Picking\0Ambient Occlusion"); ImGui::Combo("CubeMap", &m_CubeMapTexture, "Nevada(512)\0Sky(1024)"); if(m_CubeMapTexture == 0) { m_CubeMapPass->LoadTextures("Nevada"); @@ -115,19 +118,16 @@ void Renderer::Draw(RenderFrame& frame) m_CubeMapPass->LoadTextures("Sky"); } - 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 contrast", &m_SSAO_Contrast, 0.0f, 10.0f); - ImGui::SliderFloat("SSAO IntensityScale", &m_SSAO_IntensityScale, 0.0f, 10.0f); - ImGui::SliderInt("SSAO Number of Samples", &m_SSAO_NumOfSamples, 2, 100); - 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); + ImGui::SliderInt("SSAO Quality", &m_SSAO_Quality, 0, 3); + ImGui::SliderInt("Glow Quality", &m_GLOW_Quality, 0, 3); + m_SSAOPass->ChangeQuality(m_SSAO_Quality); + m_DrawBloomPass->ChangeQuality(m_GLOW_Quality); GLERROR("SSAO Settings"); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - //Clear other buffers + //Clear other buffers PerformanceTimer::StartTimer("Renderer-ClearBuffers"); m_PickingPass->ClearPicking(); m_DrawFinalPass->ClearBuffer(); @@ -136,18 +136,16 @@ void Renderer::Draw(RenderFrame& frame) PerformanceTimer::StopTimer("Renderer-ClearBuffers"); GLERROR("ClearBuffers"); for (auto scene : frame.RenderScenes) { - PerformanceTimer::StartTimer("Renderer-Depth"); + PerformanceTimer::StartTimer("Renderer-PickingPass"); m_PickingPass->Draw(*scene); GLERROR("Drawing pickingpass"); - PerformanceTimer::StopTimer("Renderer-Depth"); + PerformanceTimer::StopTimer("Renderer-PickingPass"); } - PerformanceTimer::StartTimer("AO generation"); - m_SSAOPass->Draw(m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); - GLuint ao = m_SSAOPass->SSAOTexture(); - PerformanceTimer::StopTimer("AO generation"); + PerformanceTimer::StartTimer("Renderer-AO generation"); + m_SSAOPass->Draw(*m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); + PerformanceTimer::StopTimer("Renderer-AO generation"); for (auto scene : frame.RenderScenes){ - - PerformanceTimer::StartTimer("Renderer-Drawing PickingPass"); + PerformanceTimer::StartTimer("Renderer-Depth"); SortRenderJobsByDepth(*scene); GLERROR("SortByDepth"); PerformanceTimer::StartTimerAndStopPrevious("Renderer-Generate Frustrums"); @@ -159,8 +157,8 @@ void Renderer::Draw(RenderFrame& frame) PerformanceTimer::StartTimerAndStopPrevious("Renderer-Light Culling"); m_LightCullingPass->CullLights(*scene); GLERROR("LightCulling"); - m_DrawFinalPass->Draw(*scene, ao); - PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Geometry+Light"); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Geometry+Light"); + m_DrawFinalPass->Draw(*scene); GLERROR("Draw Geometry+Light"); //m_DrawScenePass->Draw(*scene); @@ -176,7 +174,7 @@ void Renderer::Draw(RenderFrame& frame) if (m_DebugTextureToDraw == 0) { PerformanceTimer::StartTimer("Renderer-Color Correction Pass"); - m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure); + m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), frame.Gamma, frame.Exposure); PerformanceTimer::StopTimer("Renderer-Color Correction Pass"); } @@ -188,18 +186,12 @@ void Renderer::Draw(RenderFrame& frame) m_DrawScreenQuadPass->Draw(m_DrawFinalPass->BloomTexture()); } if (m_DebugTextureToDraw == 3) { - m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTextureLowRes()); - } - if (m_DebugTextureToDraw == 4) { - m_DrawScreenQuadPass->Draw(m_DrawFinalPass->BloomTextureLowRes()); - } - if (m_DebugTextureToDraw == 5) { m_DrawScreenQuadPass->Draw(m_DrawBloomPass->GaussianTexture()); } - if (m_DebugTextureToDraw == 6) { + if (m_DebugTextureToDraw == 4) { m_DrawScreenQuadPass->Draw(m_PickingPass->PickingTexture()); } - if (m_DebugTextureToDraw == 7) { + if (m_DebugTextureToDraw == 5) { m_DrawScreenQuadPass->Draw(m_SSAOPass->SSAOTexture()); } PerformanceTimer::StopTimer("Renderer-Misc Debug Draws"); @@ -207,8 +199,11 @@ void Renderer::Draw(RenderFrame& frame) PerformanceTimer::StartTimer("Renderer-ImGuiRenderPass"); m_ImGuiRenderPass->Draw(); GLERROR("Imgui draw"); + PerformanceTimer::StopTimer("Renderer-ImGuiRenderPass"); + + PerformanceTimer::StartTimer("Renderer-SwapBuffer"); glfwSwapBuffers(m_Window); - PerformanceTimer::StopTimer("Renderer-ImGuiRenderPass"); + PerformanceTimer::StopTimer("Renderer-SwapBuffer"); } PickData Renderer::Pick(glm::vec2 screenCoord) @@ -248,9 +243,10 @@ void Renderer::InitializeRenderPasses() m_PickingPass = new PickingPass(this, m_EventBroker); m_LightCullingPass = new LightCullingPass(this); m_CubeMapPass = new CubeMapPass(this); - m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass); + m_SSAOPass = new SSAOPass(this, m_Config); + m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass, m_SSAOPass); m_DrawScreenQuadPass = new DrawScreenQuadPass(this); - m_DrawBloomPass = new DrawBloomPass(this); + m_DrawBloomPass = new DrawBloomPass(this, m_Config); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); - m_SSAOPass = new SSAOPass(this); -} + +} \ No newline at end of file diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp index d4cdcb19..9992db70 100644 --- a/src/Engine/Rendering/SSAOPass.cpp +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -1,84 +1,168 @@ #include "Rendering/SSAOPass.h" -SSAOPass::SSAOPass(IRenderer* renderer) +SSAOPass::SSAOPass(IRenderer* renderer, ConfigFile* config) + : m_Renderer(renderer) + , m_Config(config) { - m_Renderer = renderer; + m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); + + ChangeQuality(m_Config->Get("SSAO.Quality", 0)); + +} + +void SSAOPass::ChangeQuality(int quality) +{ + if (m_Quality == quality) { + return; + } + + m_Quality = quality; + + if (m_Quality == 0) { + CommonFunctions::DeleteTexture(&m_SSAOTexture); + CommonFunctions::DeleteTexture(&m_SSAOViewSpaceZTexture); + CommonFunctions::DeleteTexture(&m_Gaussian_horiz); + CommonFunctions::DeleteTexture(&m_Gaussian_vert); + return; + } + + std::string qStr = std::to_string(m_Quality); + Setting( + m_Config->Get("SSAO" + qStr + ".Radius", 0.01), + m_Config->Get("SSAO" + qStr + ".Bias", 0.012), + m_Config->Get("SSAO" + qStr + ".Contrast", 1.0), + m_Config->Get("SSAO" + qStr + ".Intensity", 1.0), + m_Config->Get("SSAO" + qStr + ".NumSamples", 0), + m_Config->Get("SSAO" + qStr + ".NumTurns", 0), + m_Config->Get("SSAO" + qStr + ".NumIterations", 0), + m_Config->Get("SSAO" + qStr + ".TextureQuality", 4) + ); + + m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); InitializeTexture(); InitializeBuffer(); InitializeShaderProgram(); - Setting(0.1f, 0.012f, 1.0f, 1.0f, 13, 7); - m_DrawBloomPass = new DrawBloomPass(renderer); + } void SSAOPass::InitializeShaderProgram() { m_SSAOProgram = ResourceManager::Load("##SSAOProgram"); - m_SSAOProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); - m_SSAOProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAO.frag.glsl"))); - m_SSAOProgram->Compile(); - m_SSAOProgram->Link(); + if (m_SSAOProgram->GetHandle() == 0) { + m_SSAOProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); + m_SSAOProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAO.frag.glsl"))); + m_SSAOProgram->Compile(); + m_SSAOProgram->Link(); + } m_SSAOViewSpaceZProgram = ResourceManager::Load("##SSAOViewSpaceZProgram"); - m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); - m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAOViewSpaceZ.frag.glsl"))); - m_SSAOViewSpaceZProgram->Compile(); - m_SSAOViewSpaceZProgram->Link(); + if (m_SSAOViewSpaceZProgram->GetHandle() == 0) { + m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); + m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAOViewSpaceZ.frag.glsl"))); + m_SSAOViewSpaceZProgram->Compile(); + m_SSAOViewSpaceZProgram->Link(); + } + + m_GaussianProgram_horiz = ResourceManager::Load("##GaussianProgramHoriz"); + if (m_GaussianProgram_horiz->GetHandle() == 0) { + m_GaussianProgram_horiz->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_horiz.vert.glsl"))); + m_GaussianProgram_horiz->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_horiz.frag.glsl"))); + m_GaussianProgram_horiz->Compile(); + m_GaussianProgram_horiz->Link(); + } + + m_GaussianProgram_vert = ResourceManager::Load("##GaussianProgramVert"); + if (m_GaussianProgram_vert->GetHandle() == 0) { + m_GaussianProgram_vert->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_vert.vert.glsl"))); + m_GaussianProgram_vert->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_vert.frag.glsl"))); + m_GaussianProgram_vert->Compile(); + m_GaussianProgram_vert->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); + CommonFunctions::GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R32F, GL_RED, GL_FLOAT); + + CommonFunctions::GenerateTexture(&m_Gaussian_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_Gaussian_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); } void SSAOPass::InitializeBuffer() { - m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); + if (m_SSAOFramBuffer.GetHandle() == 0) { + m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); + } m_SSAOFramBuffer.Generate(); - m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); + + if (m_SSAOViewSpaceZFramBuffer.GetHandle() == 0) { + m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); + } m_SSAOViewSpaceZFramBuffer.Generate(); + + + + if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) { + m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_Gaussian_horiz, GL_COLOR_ATTACHMENT0))); + } + m_GaussianFrameBuffer_horiz.Generate(); + + + if (m_GaussianFrameBuffer_vert.GetHandle() == 0) { + m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_Gaussian_vert, GL_COLOR_ATTACHMENT0))); + } + m_GaussianFrameBuffer_vert.Generate(); + } void SSAOPass::ClearBuffer() { + if (m_Quality == 0) { + return; + } m_SSAOFramBuffer.Bind(); glClearColor(1.f, 1.f, 1.f, 1.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_SSAOFramBuffer.Unbind(); m_SSAOViewSpaceZFramBuffer.Bind(); glClearColor(1.f, 1.f, 1.f, 1.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_SSAOViewSpaceZFramBuffer.Unbind(); + + m_GaussianFrameBuffer_horiz.Bind(); + glClearColor(1.f, 1.f, 1.f, 1.f); + glClear(GL_COLOR_BUFFER_BIT); + m_GaussianFrameBuffer_horiz.Unbind(); + + m_GaussianFrameBuffer_vert.Bind(); + glClearColor(1.f, 1.f, 1.f, 1.f); + glClear(GL_COLOR_BUFFER_BIT); + m_GaussianFrameBuffer_vert.Unbind(); } -void SSAOPass::Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns) { +void SSAOPass::Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int numOfTurns, int iterations, int quality) { m_Radius = radius; m_Bias = bias; m_Contrast = contrast; m_IntensityScale = intensityScale; m_NumOfSamples = numOfSamples; - 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"); + m_NumOfTurns = numOfTurns; + m_Iterations = iterations; + m_TextureQuality = quality; } void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) { + if (m_Quality == 0) { + return; + } + SSAOPassState state; GLuint viewSpaceZPShaderHandle = m_SSAOViewSpaceZProgram->GetHandle(); GLuint SSAOShaderHandle = m_SSAOProgram->GetHandle(); @@ -98,6 +182,7 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) (-1.0f), (+1.0f) );*/ + glViewport(0, 0, (m_Renderer->GetViewportSize().Width >> m_TextureQuality), (m_Renderer->GetViewportSize().Height >> m_TextureQuality)); //JOHAN TODO: Get this into state glUniform3fv(glGetUniformLocation(viewSpaceZPShaderHandle, "ClipInfo"), 1, glm::value_ptr(clipInfo)); glBindVertexArray(m_ScreenQuad->VAO); @@ -107,9 +192,9 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) glm::vec4 projInfo = glm::vec4( ((1.0 - camera->ProjectionMatrix()[0][2]) / camera->ProjectionMatrix()[0][0]), - (-2.0 / (m_Renderer->GetViewportSize().Width * camera->ProjectionMatrix()[0][0])), + (-2.0 / ((m_Renderer->GetViewportSize().Width >> m_TextureQuality) * camera->ProjectionMatrix()[0][0])), ((1.0 + camera->ProjectionMatrix()[1][2]) / camera->ProjectionMatrix()[1][1]), - (-2.0 / (m_Renderer->GetViewportSize().Height * camera->ProjectionMatrix()[1][1])) + (-2.0 / ((m_Renderer->GetViewportSize().Height >> m_TextureQuality) * camera->ProjectionMatrix()[1][1])) ); @@ -120,26 +205,84 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) glBindTexture(GL_TEXTURE_2D, m_SSAOViewSpaceZTexture); // 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 >> m_TextureQuality) / (-2.0f * glm::tan(camera->FOV() * 0.5f))); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uRadius"), m_Radius); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uBias"), m_Bias); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uContrast"), m_Contrast); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uIntensityScale"), m_IntensityScale); glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfSamples"), m_NumOfSamples); - glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfTurns"), m_NumOfTurns);; + glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfTurns"), m_NumOfTurns); glUniform4fv(glGetUniformLocation(SSAOShaderHandle, "uProjInfo"), 1, glm::value_ptr(projInfo)); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); - m_DrawBloomPass->ClearBuffer(); - m_DrawBloomPass->Draw(m_SSAOTexture); + DrawBloomPassState BloomState; + GLuint shaderHandle_horiz = m_GaussianProgram_horiz->GetHandle(); + GLuint shaderHandle_vert = m_GaussianProgram_vert->GetHandle(); + + m_GaussianFrameBuffer_horiz.Bind(); + m_GaussianProgram_horiz->Bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_SSAOTexture); + + glBindVertexArray(m_ScreenQuad->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + //Iterate some times to make it more gaussian. + for (int i = 1; i < m_Iterations; i++) { + //Vertical pass + m_GaussianFrameBuffer_vert.Bind(); + m_GaussianProgram_vert->Bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_Gaussian_horiz); + + glBindVertexArray(m_ScreenQuad->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + //horizontal pass + m_GaussianFrameBuffer_vert.Unbind(); + + m_GaussianFrameBuffer_horiz.Bind(); + m_GaussianProgram_horiz->Bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_Gaussian_vert); + + glBindVertexArray(m_ScreenQuad->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + m_GaussianFrameBuffer_horiz.Unbind(); + } + + //final vertical gaussian after the iterations are done + + m_GaussianFrameBuffer_vert.Bind(); + m_GaussianProgram_vert->Bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_Gaussian_horiz); + glBindVertexArray(m_ScreenQuad->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + + m_GaussianFrameBuffer_vert.Unbind(); + + glViewport(0, 0, (m_Renderer->GetViewportSize().Width), (m_Renderer->GetViewportSize().Height)); } void SSAOPass::OnWindowResize() { - m_DrawBloomPass->OnWindowResize(); + if (m_Quality == 0) { + return; + } + InitializeTexture(); - m_SSAOFramBuffer.Generate(); - m_SSAOViewSpaceZFramBuffer.Generate(); + InitializeBuffer(); } \ No newline at end of file diff --git a/src/Engine/Rendering/Util/CommonFunctions.cpp b/src/Engine/Rendering/Util/CommonFunctions.cpp index 382cb790..913e005e 100644 --- a/src/Engine/Rendering/Util/CommonFunctions.cpp +++ b/src/Engine/Rendering/Util/CommonFunctions.cpp @@ -17,3 +17,46 @@ Texture* CommonFunctions::LoadTexture(std::string path, bool threaded) return img; } + +void CommonFunctions::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) +{ + glDeleteTextures(1, texture); + 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 CommonFunctions::GenerateMultiSampleTexture(GLuint* texture, int numSamples, glm::vec2 dimensions, GLint internalFormat) +{ + glDeleteTextures(1, texture); + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, *texture); + glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, numSamples, internalFormat, dimensions.x, dimensions.y, false); + GLERROR("Texture initialization failed"); +} + + +void CommonFunctions::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) +{ + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D, *texture); + glTexStorage2D(GL_TEXTURE_2D, numMipMaps, GL_RGBA8, dimensions.x, dimensions.y); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dimensions.x, dimensions.y, format, type, texture); + glGenerateMipmap(GL_TEXTURE_2D); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + GLERROR("MipMap Texture initialization failed"); +} + +void CommonFunctions::DeleteTexture(GLuint* texture) +{ + glDeleteTextures(1, texture); + *texture = 0; +} \ No newline at end of file diff --git a/src/Engine/Rendering/Util/ScreenCoords.cpp b/src/Engine/Rendering/Util/ScreenCoords.cpp index 36f1295e..8b7768c8 100644 --- a/src/Engine/Rendering/Util/ScreenCoords.cpp +++ b/src/Engine/Rendering/Util/ScreenCoords.cpp @@ -31,22 +31,27 @@ glm::vec3 ScreenCoords::ToWorldPos(glm::vec2 screenCoord, float depth, float scr ScreenCoords::PixelData ScreenCoords::ToPixelData(float x, float y, FrameBuffer* PickDataBuffer, GLuint DepthBuffer) { + GLERROR("Pre"); PickDataBuffer->Bind(); unsigned char pdata[3]; glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pdata); + GLERROR("glReadPixels(pdata) Error"); PickDataBuffer->Unbind(); - glBindFramebuffer(GL_FRAMEBUFFER, DepthBuffer); + glBindFramebuffer(GL_FRAMEBUFFER, DepthBuffer); + GLERROR("glBindFramebuffer(DepthBuffer) Error"); float depthData; glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depthData); + GLERROR("glReadPixels(depthData) Error"); glBindFramebuffer(GL_FRAMEBUFFER, 0); + GLERROR("glBindFramebuffer(0) Error"); PixelData p; p.Color[0] = (int)pdata[0]; p.Color[1] = (int)pdata[1]; p.Depth = depthData; - GLERROR("ScreenCoords::ToPixelData Error"); + GLERROR("End"); return p; } diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 24b7cd1e..2946d656 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -16,7 +16,7 @@ #include "Game/Systems/PickupSpawnSystem.h" #include "Game/Systems/AmmoPickupSystem.h" #include "Game/Systems/DamageIndicatorSystem.h" -#include "Game/Systems/Weapon/WeaponSystem.h" +#include "Game/Systems/Weapon/DefenderWeaponBehaviour.h" #include "Rendering/AnimationSystem.h" #include "Game/Systems/HealthHUDSystem.h" #include "Rendering/BoneAttachmentSystem.h" @@ -48,13 +48,12 @@ Game::Game(int argc, char* argv[]) ResourceManager::UseThreading = m_Config->Get("Multithreading.ResourceLoading", true); DisableMemoryPool::Value = m_Config->Get("Debug.DisableMemoryPool", false); LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get("Debug.LogLevel", 1)); - PlayerSpawnSystem::SetRespawnTime(m_Config->Get("Debug.RespawnTime", 15.0f)); // Create the core event broker m_EventBroker = new EventBroker(); // Create the renderer - m_Renderer = new Renderer(m_EventBroker); + m_Renderer = new Renderer(m_EventBroker, m_Config); m_Renderer->SetFullscreen(m_Config->Get("Video.Fullscreen", false)); m_Renderer->SetVSYNC(m_Config->Get("Video.VSYNC", false)); m_Renderer->SetResolution(Rectangle::Rectangle( @@ -98,6 +97,10 @@ Game::Game(int argc, char* argv[]) m_NetworkClient->Connect(m_NetworkAddress, m_NetworkPort); m_Renderer->SetWindowTitle(m_Renderer->WindowTitle() + " CLIENT"); } + } else { + // If network is disabled, pretend we're a server + m_IsClient = true; + m_IsServer = true; } // Create Octrees @@ -120,7 +123,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -135,7 +138,6 @@ Game::Game(int argc, char* argv[]) ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -145,6 +147,9 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger); + // Octree for frustum culling must be updated after collisions, otherwise players frustum may be moved after tree is filled, and wrong things are culled. + ++updateOrderLevel; + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame, m_OctreeFrustrumCulling); ++updateOrderLevel; diff --git a/src/Game/Network/MultiplayerSnapshotFilter.cpp b/src/Game/Network/MultiplayerSnapshotFilter.cpp index 69b7f282..295cdd7a 100644 --- a/src/Game/Network/MultiplayerSnapshotFilter.cpp +++ b/src/Game/Network/MultiplayerSnapshotFilter.cpp @@ -13,6 +13,7 @@ bool MultiplayerSnapshotFilter::FilterComponent(EntityWrapper entity, SharedComp component.Info.Name == "Transform" || component.Info.Name == "Physics" || component.Info.Name == "AssaultWeapon" + || component.Info.Name == "DefenderWeapon" || component.Info.Name == "Animation" || component.Info.Name == "AnimationOffset" || entity.Name() == "PlayerName" diff --git a/src/Game/Systems/AmmoPickupSystem.cpp b/src/Game/Systems/AmmoPickupSystem.cpp index f6778fe4..5927c495 100644 --- a/src/Game/Systems/AmmoPickupSystem.cpp +++ b/src/Game/Systems/AmmoPickupSystem.cpp @@ -3,36 +3,43 @@ AmmoPickupSystem::AmmoPickupSystem(SystemParams params) : System(params) { - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &AmmoPickupSystem::OnTriggerTouch); + if (IsServer) { + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &AmmoPickupSystem::OnTriggerTouch); + } + if (IsClient) { + EVENT_SUBSCRIBE_MEMBER(m_EAmmoPickup, &AmmoPickupSystem::OnAmmoPickup); + } } void AmmoPickupSystem::Update(double dt) { - for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) - { - auto& ammoPickupPosition = *it; - //set the double timer value (value 3) - ammoPickupPosition.DecreaseThisRespawnTimer -= dt; - if (ammoPickupPosition.DecreaseThisRespawnTimer < 0.0) { - //spawn and delete the vector item - auto entityFile = ResourceManager::Load("Schema/Entities/AmmoPickup.xml"); - EntityFileParser parser(entityFile); - EntityID ammoPickupID = parser.MergeEntities(m_World); + if (IsServer) { + for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) { + auto& ammoPickupPosition = *it; + //set the double timer value (value 3) + ammoPickupPosition.DecreaseThisRespawnTimer -= dt; + if (ammoPickupPosition.DecreaseThisRespawnTimer < 0.0) { + //spawn and delete the vector item + auto entityFile = ResourceManager::Load("Schema/Entities/AmmoPickup.xml"); + EntityFileParser parser(entityFile); + EntityID ammoPickupID = parser.MergeEntities(m_World); - //let the world know a pickup has spawned (graphics effects, etc) - Events::PickupSpawned ePickupSpawned; - ePickupSpawned.Pickup = EntityWrapper(m_World, ammoPickupID); - m_EventBroker->Publish(ePickupSpawned); + //let the world know a pickup has spawned (graphics effects, etc) + Events::PickupSpawned ePickupSpawned; + ePickupSpawned.Pickup = EntityWrapper(m_World, ammoPickupID); + m_EventBroker->Publish(ePickupSpawned); - //set values from the old entity to the new entity - auto& newAmmoPickupEntity = EntityWrapper(m_World, ammoPickupID); - newAmmoPickupEntity["Transform"]["Position"] = ammoPickupPosition.Pos; - newAmmoPickupEntity["AmmoPickup"]["AmmoGain"] = ammoPickupPosition.AmmoGain; - newAmmoPickupEntity["AmmoPickup"]["RespawnTimer"] = ammoPickupPosition.RespawnTimer; + //set values from the old entity to the new entity + auto& newAmmoPickupEntity = EntityWrapper(m_World, ammoPickupID); + newAmmoPickupEntity["Transform"]["Position"] = ammoPickupPosition.Pos; + newAmmoPickupEntity["AmmoPickup"]["AmmoGain"] = ammoPickupPosition.AmmoGain; + newAmmoPickupEntity["AmmoPickup"]["RespawnTimer"] = ammoPickupPosition.RespawnTimer; + m_World->SetParent(newAmmoPickupEntity.ID, ammoPickupPosition.parentID); - //erase the current element (AmmoPickupPosition) - m_ETriggerTouchVector.erase(it); - break; + //erase the current element (AmmoPickupPosition) + m_ETriggerTouchVector.erase(it); + break; + } } } } @@ -40,7 +47,11 @@ void AmmoPickupSystem::Update(double dt) bool AmmoPickupSystem::OnTriggerTouch(Events::TriggerTouch& e) { - if (e.Entity != LocalPlayer) { + /*if (e.Entity != LocalPlayer) { + return false; + }*/ + + if (!e.Entity.Valid()) { return false; } //TODO: add other weapontypes @@ -65,14 +76,34 @@ bool AmmoPickupSystem::OnTriggerTouch(Events::TriggerTouch& e) ePlayerAmmoPickup.Player = e.Entity; m_EventBroker->Publish(ePlayerAmmoPickup); //immediately give the player the ammo - currentAmmo = std::min(currentAmmo + ammoGiven, maxWeaponAmmo); + //currentAmmo = std::min(currentAmmo + ammoGiven, maxWeaponAmmo); //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 - m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["AmmoPickup"]["AmmoGain"], - e.Trigger["AmmoPickup"]["RespawnTimer"],e.Trigger["AmmoPickup"]["RespawnTimer"] }); + m_ETriggerTouchVector.push_back({ e.Trigger["Transform"]["Position"], e.Trigger["AmmoPickup"]["AmmoGain"], + e.Trigger["AmmoPickup"]["RespawnTimer"], e.Trigger["AmmoPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); //delete the ammopickup m_World->DeleteEntity(e.Trigger.ID); return true; } + +bool AmmoPickupSystem::OnAmmoPickup(Events::AmmoPickup & e) +{ + if (!e.Player.Valid()) { + return false; + } + //TODO: add other weapontypes + if (!e.Player.HasComponent("AssaultWeapon")) { + return false; + } + int maxWeaponAmmo = (int)e.Player["AssaultWeapon"]["MaxAmmo"]; + int& currentAmmo = (int)e.Player["AssaultWeapon"]["Ammo"]; + //cant pick up ammopacks if you are already at MaxAmmo + if (currentAmmo >= maxWeaponAmmo) { + return false; + } + + currentAmmo = std::min(currentAmmo + e.AmmoGain, maxWeaponAmmo); + return false; +} diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index b45f6ced..f748ff09 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -6,9 +6,11 @@ CapturePointSystem::CapturePointSystem(SystemParams params) , PureSystem("CapturePoint") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); - EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); - EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + if (IsServer) { + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + } } @@ -16,6 +18,9 @@ CapturePointSystem::CapturePointSystem(SystemParams params) //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) { + if (!IsServer) { + return; + } if (m_WinnerWasFound) { return; } @@ -97,6 +102,13 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp nextPossibleCapturePoint["Blue"] = i - 1; } } + if (m_RecentlyCapturedNeedNextCapturePointNow) { + m_CapturedEvent.NextCapturePoint = m_CapturedEvent.TeamNumberThatCapturedCapturePoint == blueTeam ? + m_CapturePointNumberToEntityMap[nextPossibleCapturePoint["Blue"]] : + m_CapturePointNumberToEntityMap[nextPossibleCapturePoint["Red"]]; + m_EventBroker->Publish(m_CapturedEvent); + m_RecentlyCapturedNeedNextCapturePointNow = false; + } //reset timers and reset the bool that triggers this if (m_ResetTimers) { @@ -183,10 +195,9 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp teamComponent["Team"] = currentTeam; cCapturePoint["CaptureTimer"] = glm::sign((double)cCapturePoint["CaptureTimer"])*captureTimeToTakeOver; //publish Captured event - Events::Captured e; - e.CapturePointID = cCapturePoint.EntityID; - e.TeamNumberThatCapturedCapturePoint = currentTeam; - m_EventBroker->Publish(e); + m_RecentlyCapturedNeedNextCapturePointNow = true; + m_CapturedEvent.CapturePointTakenID = cCapturePoint.EntityID; + m_CapturedEvent.TeamNumberThatCapturedCapturePoint = currentTeam; //NextPossibleCapturePoint will be calculated in the next update... } } diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 92fbe607..ca26052d 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -13,7 +13,7 @@ DamageIndicatorSystem::DamageIndicatorSystem(SystemParams params) } void DamageIndicatorSystem::Update(double dt) { - if (!IsServer) { + if (!IsServer && LocalPlayer.Valid()) { for (auto& iter = updateDamageIndicatorVector.begin(); iter != updateDamageIndicatorVector.end(); iter++) { if (!iter->spriteEntity.Valid()) { updateDamageIndicatorVector.erase(iter); diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp index 159f716b..94fee4c6 100644 --- a/src/Game/Systems/PickupSpawnSystem.cpp +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -3,36 +3,40 @@ PickupSpawnSystem::PickupSpawnSystem(SystemParams params) : System(params) { - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &PickupSpawnSystem::OnTriggerTouch); + if (IsServer) { + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &PickupSpawnSystem::OnTriggerTouch); + } } void PickupSpawnSystem::Update(double dt) { - for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) - { - auto& healthPickupPosition = *it; - //set the double timer value (value 3) - healthPickupPosition.DecreaseThisRespawnTimer -= dt; - if (healthPickupPosition.DecreaseThisRespawnTimer < 0) { - //spawn and delete the vector item - auto entityFile = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); - EntityFileParser parser(entityFile); - EntityID healthPickupID = parser.MergeEntities(m_World); + if (IsServer) { + for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) { + auto& healthPickupPosition = *it; + //set the double timer value (value 3) + healthPickupPosition.DecreaseThisRespawnTimer -= dt; + if (healthPickupPosition.DecreaseThisRespawnTimer < 0) { + //spawn and delete the vector item + auto entityFile = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); + EntityFileParser parser(entityFile); + EntityID healthPickupID = parser.MergeEntities(m_World); - //let the world know a pickup has spawned (graphics effects, etc) - Events::PickupSpawned ePickupSpawned; - ePickupSpawned.Pickup = EntityWrapper(m_World, healthPickupID); - m_EventBroker->Publish(ePickupSpawned); + //let the world know a pickup has spawned (graphics effects, etc) + Events::PickupSpawned ePickupSpawned; + ePickupSpawned.Pickup = EntityWrapper(m_World, healthPickupID); + m_EventBroker->Publish(ePickupSpawned); - //set values from the old entity to the new entity - auto& newHealthPickupEntity = EntityWrapper(m_World, healthPickupID); - newHealthPickupEntity["Transform"]["Position"] = healthPickupPosition.Pos; - newHealthPickupEntity["HealthPickup"]["HealthGain"] = healthPickupPosition.HealthGain; - newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = healthPickupPosition.RespawnTimer; + //set values from the old entity to the new entity + auto& newHealthPickupEntity = EntityWrapper(m_World, healthPickupID); + newHealthPickupEntity["Transform"]["Position"] = healthPickupPosition.Pos; + newHealthPickupEntity["HealthPickup"]["HealthGain"] = healthPickupPosition.HealthGain; + newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = healthPickupPosition.RespawnTimer; + m_World->SetParent(newHealthPickupEntity.ID, healthPickupPosition.parentID); - //erase the current element (healthPickupPosition) - m_ETriggerTouchVector.erase(it); - break; + //erase the current element (healthPickupPosition) + m_ETriggerTouchVector.erase(it); + break; + } } } } @@ -57,8 +61,8 @@ 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) //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"], - e.Trigger["HealthPickup"]["RespawnTimer"],e.Trigger["HealthPickup"]["RespawnTimer"] }); + 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) }); //delete the healthpickup m_World->DeleteEntity(e.Trigger.ID); diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index a144dd18..47612ca0 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -4,6 +4,7 @@ PlayerMovementSystem::PlayerMovementSystem(SystemParams params) : System(params) { EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &PlayerMovementSystem::OnDoubleJump); } PlayerMovementSystem::~PlayerMovementSystem() @@ -36,7 +37,6 @@ void PlayerMovementSystem::updateMovementControllers(double dt) if (!player.Valid()) { continue; } - // Aim pitch EntityWrapper cameraEntity = player.FirstChildByName("Camera"); if (cameraEntity.Valid()) { @@ -48,7 +48,7 @@ void PlayerMovementSystem::updateMovementControllers(double dt) EntityWrapper playerModel = player.FirstChildByName("PlayerModel"); if (playerModel.Valid()) { ComponentWrapper cAnimationOffset = playerModel["AnimationOffset"]; - float pitch = cameraOrientation.x + 0.2; + float pitch = cameraOrientation.x + 0.2f; double time = (pitch + glm::half_pi()) / glm::pi(); cAnimationOffset["Time"] = time; } @@ -66,7 +66,7 @@ void PlayerMovementSystem::updateMovementControllers(double dt) ComponentWrapper cPhysics = player["Physics"]; //Assault Dash Check if (player.HasComponent("DashAbility")) { - controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f, player["DashAbility"]["CoolDownMaxTimer"]); + controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f, player["DashAbility"]["CoolDownMaxTimer"], player["DashAbility"]["CoolDownTimer"]); } wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); //this makes sure you can only dash in the 4 directions: forw,backw,left,right @@ -116,25 +116,29 @@ void PlayerMovementSystem::updateMovementControllers(double dt) ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); } - //you cant jump and dash at the same time - since there is no friction in the air and we would thus dash much further in the air - if (!controller->PlayerIsDashing() && controller->Jumping() && !controller->Crouching() && (isOnGround || !controller->DoubleJumping())) { - (bool)cPhysics["IsOnGround"] = false; + if (isOnGround) { + controller->SetDoubleJumping(false); + } + //If player presses Jump and is not crouching. + if (controller->Jumping() && !controller->Crouching()) { if (isOnGround) { - controller->SetDoubleJumping(false); - } else { + (bool)cPhysics["IsOnGround"] = false; + velocity.y = player["Player"]["JumpSpeed"]; + } else if (player.HasComponent("DoubleJump") && !controller->DoubleJumping()) { + //Enter here if player can double jump and is doing so. + (bool)cPhysics["IsOnGround"] = false; + velocity.y = player["DoubleJump"]["DoubleJumpSpeed"]; + // If IsServer and network is off this will not work if (IsClient) { //put a hexagon at the players feet - auto hexagonEffect = ResourceManager::Load("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"]; + spawnHexagon(player); controller->SetDoubleJumping(true); + // Publish event for client to listen to Events::DoubleJump e; + e.entityID = player.ID; m_EventBroker->Publish(e); } } - velocity.y = 4.f; } if (player.HasComponent("AABB")) { @@ -295,3 +299,27 @@ bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e) } 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)); + return true; +} + +void PlayerMovementSystem::spawnHexagon(EntityWrapper target) +{ + //put a hexagon at the entitys... feet? + auto hexagonEffect = ResourceManager::Load("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"]; +} \ No newline at end of file diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 6254c674..e03a1778 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -1,29 +1,40 @@ #include "Systems/PlayerSpawnSystem.h" -//This should be set by the config anyway. -float PlayerSpawnSystem::m_RespawnTime = 15.0f; - PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) : System(params) - , m_Timer(0.f) + , m_DbgConfigForceRespawn(false) { EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerSpawnSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerSpawnerd, &PlayerSpawnSystem::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerSpawnSystem::OnPlayerDeath); - m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); + ConfigFile* config = ResourceManager::Load("Config.ini"); + m_NetworkEnabled = config->Get("Networking.StartNetwork", false); + m_ForcedRespawnTime = config->Get("Debug.RespawnTime", -1.0f); + m_DbgConfigForceRespawn = m_ForcedRespawnTime > 0; } void PlayerSpawnSystem::Update(double dt) { - //Increase timer. - m_Timer += dt; - if (m_Timer < m_RespawnTime) { - return; + // If there are no CapturePointGameMode components we will just spawn immediately. + // Should be able to support older maps with this. + // TODO: In the future we might want to return instead, to avoid spawning in the menu for instance. + auto pool = m_World->GetComponents("CapturePointGameMode"); + if (pool != nullptr && pool->size() > 0) + { + // Take the first CapturePointGameMode component found. + ComponentWrapper& modeComponent = *pool->begin(); + // Increase timer. + double& timer = (double&)modeComponent["RespawnTime"]; + timer += dt; + double maxRespawnTime = m_DbgConfigForceRespawn ? m_ForcedRespawnTime : (double)modeComponent["MaxRespawnTime"]; + if (timer < maxRespawnTime) { + return; + } + // If respawn time has passed, we spawn all players that have requested to be spawned. + timer = 0; } - //If respawn time has passed, we spawn all players that have requested to be spawned. - m_Timer = 0.f; - //If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. + // If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. if (m_SpawnRequests.size() == 0) { return; } diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index b4a37ad0..be9c8aaf 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -94,7 +94,7 @@ 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.CapturePointTakenID, "Team")["Team"]; int team = (int)m_World->GetComponent(LocalPlayer.ID, "Team")["Team"]; Events::PlaySoundOnEntity ev; if (team == homeTeam) { diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index 7f73d4e2..85eda6d1 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -36,7 +36,7 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / } // Find any SpawnPoints existing as children of spawner - auto children = spawner.World->GetChildren(spawner.ID); + auto children = spawner.World->GetDirectChildren(spawner.ID); std::vector spawnPoints; for (auto kv = children.first; kv != children.second; ++kv) { const EntityID& child = kv->second; diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ similarity index 87% rename from src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp rename to src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ index 84d3ccd4..c3b3385f 100644 --- a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ @@ -1,13 +1,5 @@ #include "Systems/Weapon/AssaultWeaponBehaviour.h" -AssaultWeaponBehaviour::AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) - : WeaponBehaviour(systemParams, renderer, collisionOctree, player) -{ - m_FirstPersonModel = m_Player.FirstChildByName("Hands"); - m_ThirdPersonModel = m_Player.FirstChildByName("PlayerModel"); - EVENT_SUBSCRIBE_MEMBER(m_EAnimationComplete, &AssaultWeaponBehaviour::OnAnimationComplete); -} - void AssaultWeaponBehaviour::Fire() { m_TimeSinceLastFire = 0.0; @@ -36,7 +28,7 @@ void AssaultWeaponBehaviour::Reload() return; } - // Don't reload if we're completly out of ammo + // Don't reload if we're completely out of ammo if (ammo == 0) { playEmptySound(); m_TimeSinceLastFire = -0.0f; // HACK: To make empty sound play with interval @@ -56,14 +48,14 @@ void AssaultWeaponBehaviour::Update(double dt) { if (m_Reloading) { m_ReloadTimer -= dt; - // Re-enable glow on reload impersonator half-way through the animation + // Re-enable glow on reload impostor half-way through the animation if (IsClient) { if (m_ReloadTimer <= (double)m_Player["AssaultWeapon"]["ReloadTime"] / 2.0) { - if (m_FirstPersonReloadImpersonator.Valid()) { - m_FirstPersonReloadImpersonator["Model"]["GlowMap"] = true; + if (m_FirstPersonReloadImpostor.Valid()) { + m_FirstPersonReloadImpostor["Model"]["GlowMap"] = true; } - if (m_ThirdPersonReloadImpersonator.Valid()) { - m_ThirdPersonReloadImpersonator["Model"]["GlowMap"] = true; + if (m_ThirdPersonReloadImpostor.Valid()) { + m_ThirdPersonReloadImpostor["Model"]["GlowMap"] = true; } } } @@ -96,21 +88,6 @@ void AssaultWeaponBehaviour::Update(double dt) } } -bool AssaultWeaponBehaviour::OnAnimationComplete(Events::AnimationComplete& e) -{ - if (e.Entity != m_FirstPersonModel) { - return false; - } - - //if (e.Name == "ShootRifle") { - // if (!m_Firing) { - // playIdleAnimation(); - // } - //} - - return true; -} - bool AssaultWeaponBehaviour::hasAmmo() { ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; @@ -177,7 +154,6 @@ void AssaultWeaponBehaviour::spawnTracer() float AssaultWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) { - // TODO: Cast a ray and size tracer appropriately float distance; glm::vec3 pos; auto entity = Collision::EntityFirstHitByRay(Ray(origin, direction), m_CollisionOctree, distance, pos); @@ -215,6 +191,12 @@ void AssaultWeaponBehaviour::playEmptySound() void AssaultWeaponBehaviour::viewPunch() { + // Since we send absolute client orientations to server, running this server side would + // cause aim desync. + if (!IsClient) { + return; + } + EntityWrapper playerCamera = m_Player.FirstChildByName("Camera"); if (!playerCamera.Valid()) { return; @@ -323,8 +305,8 @@ void AssaultWeaponBehaviour::playReloadAnimation() EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); EntityWrapper reloadSpawner = m_Player.FirstChildByName("FirstPersonReloadSpawner"); if (IsClient) { - m_FirstPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); - firstPersonWeaponModel["Model"].Copy(m_FirstPersonReloadImpersonator["Model"]); + m_FirstPersonReloadImpostor = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + firstPersonWeaponModel["Model"].Copy(m_FirstPersonReloadImpostor["Model"]); } firstPersonWeaponModel["Model"]["Visible"] = false; } @@ -332,8 +314,8 @@ void AssaultWeaponBehaviour::playReloadAnimation() EntityWrapper thirdPersonWeaponModel = m_Player.FirstChildByName("ThirdPersonWeaponModel"); EntityWrapper reloadSpawner = m_Player.FirstChildByName("ThirdPersonReloadSpawner"); if (IsClient) { - m_ThirdPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); - thirdPersonWeaponModel["Model"].Copy(m_ThirdPersonReloadImpersonator["Model"]); + m_ThirdPersonReloadImpostor = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + thirdPersonWeaponModel["Model"].Copy(m_ThirdPersonReloadImpostor["Model"]); } thirdPersonWeaponModel["Model"]["Visible"] = false; } @@ -371,7 +353,7 @@ bool AssaultWeaponBehaviour::shoot(double damage) return false; } - // Don't let us shoot ourselves in the foot + // Don't let us shoot ourselves in the foot somehow if (victim == LocalPlayer) { return false; } diff --git a/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp b/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp new file mode 100644 index 00000000..028bd10c --- /dev/null +++ b/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp @@ -0,0 +1,188 @@ +#include "Systems/Weapon/DefenderWeaponBehaviour.h" + +void DefenderWeaponBehaviour::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cWeapon, double dt) +{ + (double&)cWeapon["TimeSinceLastFire"] += dt; + WeaponBehaviour::UpdateComponent(entity, cWeapon, dt); +} + +void DefenderWeaponBehaviour::UpdateWeapon(WeaponInfo& wi, double dt) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + + bool isFiring = cWeapon["IsFiring"]; + bool cooldownPassed = (double)cWeapon["TimeSinceLastFire"] >= (60.0 / (double)cWeapon["RPM"]); + bool isNotShielding = wi.Player.ChildrenWithComponent("Shield").size() == 0; + if (isFiring && cooldownPassed && isNotShielding) { + fireShell(wi); + } +} + +void DefenderWeaponBehaviour::OnPrimaryFire(WeaponInfo& wi) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + cWeapon["IsFiring"] = true; + bool cooldownPassed = (double)cWeapon["TimeSinceLastFire"] >= (60.0 / (double)cWeapon["RPM"]); + bool isNotShielding = wi.Player.ChildrenWithComponent("Shield").size() == 0; + if (cooldownPassed && isNotShielding) { + fireShell(wi); + } +} + +void DefenderWeaponBehaviour::OnCeasePrimaryFire(WeaponInfo& wi) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + cWeapon["IsFiring"] = false; +} + +bool DefenderWeaponBehaviour::OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) +{ + if (e.Command == "SpecialAbility" && IsServer) { + EntityWrapper attachment = wi.Player.FirstChildByName("ShieldAttachment"); + if (attachment.Valid()) { + if (e.Value > 0) { + SpawnerSystem::Spawn(attachment, attachment); + } else { + attachment.DeleteChildren(); + } + } + } + + return false; +} + +bool DefenderWeaponBehaviour::OnSetCamera(const Events::SetCamera& e) +{ + m_CurrentCamera = e.CameraEntity; + return true; +} + +void DefenderWeaponBehaviour::fireShell(WeaponInfo& wi) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + + cWeapon["TimeSinceLastFire"] = 0.0; + int numPellets = cWeapon["NumPellets"]; + float spreadAngle = cWeapon["SpreadAngle"]; + std::uniform_real_distribution randomSpreadAngle(-spreadAngle, spreadAngle); + + // Calculate pellet angles + // HACK: Random for now? + // TODO: Make distribution even for each quadrant + std::vector pelletAngles; + for (int i = 0; i < numPellets; i++) { + pelletAngles.push_back(glm::vec2(randomSpreadAngle(m_RandomEngine), randomSpreadAngle(m_RandomEngine))); + LOG_DEBUG("%f %f", pelletAngles[i].x, pelletAngles[i].y); + } + + double pelletDamage = (double)cWeapon["BaseDamage"] / numPellets; + + // Tracers + EntityWrapper weaponModelEntity; + if (wi.Player == LocalPlayer) { + weaponModelEntity = wi.FirstPersonEntity; + } else { + weaponModelEntity = wi.ThirdPersonEntity; + } + if (weaponModelEntity.Valid()) { + EntityWrapper spawner = weaponModelEntity.FirstChildByName("WeaponMuzzle"); + for (auto& angles : pelletAngles) { + glm::vec3 direction = Transform::AbsoluteOrientation(spawner) * glm::quat(glm::vec3(angles, 0.f)) * glm::vec3(0, 0, -1); + float distance = traceRayDistance(Transform::AbsolutePosition(spawner), direction); + EntityWrapper ray = SpawnerSystem::Spawn(spawner); + ((glm::vec3&)ray["Transform"]["Scale"]).z = (distance / 100.f); + glm::vec3& orientation = ray["Transform"]["Orientation"]; + orientation.x += angles.x; + orientation.y += angles.y; + glm::vec3 trajectory = direction * distance; + dealDamage(wi, direction, pelletDamage); + } + } + +} + +void DefenderWeaponBehaviour::dealDamage(WeaponInfo& wi, glm::vec3 direction, double damage) +{ + // Only deal damage client side + if (!IsClient) { + return; + } + + // Only handle shooting for the local player + if (wi.Player != LocalPlayer) { + return; + } + + // Make sure the player isn't shooting from the grave + if (!wi.Player.Valid()) { + return; + } + + glm::vec3 maxRange = direction * 2.f; + EntityWrapper camera = wi.Player.FirstChildByName("Camera"); + glm::vec3 cameraPosition = Transform::AbsolutePosition(camera); + if (!camera.Valid()) { + return; + } + Rectangle screenResolution = m_Renderer->GetViewportSize(); + glm::vec2 centerScreen = glm::vec2(screenResolution.Width / 2, screenResolution.Height / 2); + glm::vec2 screenCoords = cameraFromEntity(m_CurrentCamera).WorldToScreen(cameraPosition + maxRange, m_Renderer->GetViewportSize()); + PickData pickData = m_Renderer->Pick(centerScreen + screenCoords); + EntityWrapper victim(m_World, pickData.Entity); + if (!victim.Valid()) { + return; + } + + // Don't let us shoot ourselves in the foot somehow + if (victim == LocalPlayer) { + return; + } + + // Only care about players being hit + if (!victim.HasComponent("Player")) { + victim = victim.FirstParentWithComponent("Player"); + } + if (!victim.Valid()) { + return; + } + + // Check for friendly fire + if ((ComponentInfo::EnumType)victim["Team"]["Team"] == (ComponentInfo::EnumType)wi.Player["Team"]["Team"]) { + return; + } + + // Deal damage! + Events::PlayerDamage ePlayerDamage; + ePlayerDamage.Inflictor = wi.Player; + ePlayerDamage.Victim = victim; + ePlayerDamage.Damage = damage; + m_EventBroker->Publish(ePlayerDamage); + LOG_DEBUG("Damage: %f", damage); +} + +float DefenderWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) +{ + float distance; + glm::vec3 pos; + auto entity = Collision::EntityFirstHitByRay(Ray(origin, direction), m_CollisionOctree, distance, pos); + if (entity) { + return distance; + } else { + return 100.f; + } +} + +Camera DefenderWeaponBehaviour::cameraFromEntity(EntityWrapper camera) +{ + ComponentWrapper cTransform = camera["Transform"]; + ComponentWrapper cCamera = camera["Camera"]; + Camera cam( + (float)m_Renderer->Resolution().Width / m_Renderer->Resolution().Height, + (double)cCamera["FOV"], + (double)cCamera["NearClip"], + (double)cCamera["FarClip"] + ); + cam.SetPosition(cTransform["Position"]); + cam.SetOrientation(glm::quat((const glm::vec3&)cTransform["Orientation"])); + return cam; +} diff --git a/src/Game/Systems/Weapon/WeaponSystem.cpp b/src/Game/Systems/Weapon/WeaponSystem.cpp_ similarity index 56% rename from src/Game/Systems/Weapon/WeaponSystem.cpp rename to src/Game/Systems/Weapon/WeaponSystem.cpp_ index 3a49ae90..d33c5098 100644 --- a/src/Game/Systems/Weapon/WeaponSystem.cpp +++ b/src/Game/Systems/Weapon/WeaponSystem.cpp_ @@ -13,7 +13,7 @@ WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer, Octree weaponAttachments = player.ChildrenWithComponent("WeaponAttachment"); + + // Find the weapon attachments matching the slot selected + EntityWrapper firstPersonAttachment; + EntityWrapper thirdPersonAttachment; + for (auto& attachment : weaponAttachments) { + ComponentWrapper cWeaponAttachment = attachment["WeaponAttachment"]; + if ((ComponentInfo::EnumType)cWeaponAttachment["Slot"] == slot) { + ComponentWrapper::SubscriptProxy person = cWeaponAttachment["Person"]; + if (person == person.Enum("FirstPerson")) { + firstPersonAttachment = attachment; + } else if (person == person.Enum("ThirdPerson")) { + thirdPersonAttachment = attachment; + } + } + } + + if (firstPersonAttachment.Valid() && thirdPersonAttachment.Valid()) { + LOG_WARNING("No weapon attachment found for slot %i of player #%i", slot, player.ID); + return; + } + + // TODO: Delete old weapons + + // Spawn the weapon(s) + EntityWrapper firstPersonWeapon; + EntityWrapper thirdPersonWeapon; + if (firstPersonAttachment.Valid()) { + firstPersonWeapon = SpawnerSystem::Spawn(firstPersonAttachment, firstPersonAttachment); + } + if (thirdPersonAttachment.Valid()) { + firstPersonWeapon = SpawnerSystem::Spawn(thirdPersonAttachment, thirdPersonAttachment); + } + + // Create the correct behaviour + if (firstPersonWeapon.Valid()) { + if (firstPersonWeapon.HasComponent("AssaultWeapon") { + + } + } + // Primary if (slot == 1) { // TODO: if class... - if (m_ActiveWeapons.count(player) == 0) { - m_ActiveWeapons.insert(std::make_pair(player, std::make_shared(m_SystemParams, m_Renderer, m_CollisionOctree, player))); - } else { - //m_ActiveWeapons.erase(player); - } + nextBehaviour = std::make_shared(m_SystemParams, m_Renderer, m_CollisionOctree, player); } // Secondary if (slot == 2) { //m_ActiveWeapons[player] = std::make_shared(); } + + if (nextBehaviour != nullptr) { + // TODO: Destroy previous behaviour and make new + if (m_ActiveWeapons.count(player) == 0) { + m_ActiveWeapons[player] = nextBehaviour; + } + } } bool WeaponSystem::OnPlayerSpawned(Events::PlayerSpawned& e) diff --git a/src/Game/main.cpp b/src/Game/main.cpp index dd2a5a84..3c9b6d38 100644 --- a/src/Game/main.cpp +++ b/src/Game/main.cpp @@ -9,7 +9,9 @@ int main(int argc, char* argv[]) Game game(argc, argv); while (game.Running()) { + PerformanceTimer::StartTimer("Game-Tick"); game.Tick(); + PerformanceTimer::StopTimer("Game-Tick"); } return 0;