diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index cd10dbb2..6d16e090 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -28,6 +28,21 @@ bool RayVsAABB(const Ray& ray, const AABB& box); //Return true if the ray hits the box, also outputs distance from ray origin to intersection point in [outDistance]. bool RayVsAABB(const Ray& ray, const AABB& box, float& outDistance); +//Return true if the ray hits the triangle. +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + bool trueOnNegativeDistance = false); +//Return true if the ray hits the triangle, and the distance is less than outDistance. +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + float& outDistance, + float& outUCoord, + float& outVCoord, + bool trueOnNegativeDistance = false); //Return true if the ray hits any of the triangles in the model. Stops checking when a hit is detected. bool RayVsModel(const Ray& ray, const std::vector& modelVertices, @@ -52,6 +67,9 @@ bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, + glm::vec3& boxVelocity, + float verticalStepHeight, + bool& isOnGround, glm::vec3& outResolutionVector); //Return true if the boxes are intersecting. @@ -60,6 +78,8 @@ bool AABBVsAABB(const AABB& a, const AABB& b); //Also outputs the minimum translation that box [a] would need in order to resolve collision. bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation); +//Attaches an AABB which contains all vertices in the entitys Model. +bool AttachAABBComponentFromModel(EntityWrapper entity); // Calculates an absolute AABB from an entity AABB component boost::optional EntityAbsoluteAABB(EntityWrapper& entity); diff --git a/include/Engine/Collision/CollidableOctreeSystem.h b/include/Engine/Collision/FillOctreeSystem.h similarity index 66% rename from include/Engine/Collision/CollidableOctreeSystem.h rename to include/Engine/Collision/FillOctreeSystem.h index 0aa01d2e..9fd87b94 100644 --- a/include/Engine/Collision/CollidableOctreeSystem.h +++ b/include/Engine/Collision/FillOctreeSystem.h @@ -6,12 +6,12 @@ #include "Collision.h" #include "EntityAABB.h" -class CollidableOctreeSystem : public ImpureSystem, public PureSystem +class FillOctreeSystem : public ImpureSystem, public PureSystem { public: - CollidableOctreeSystem(World* world, EventBroker* eventBroker, Octree* octree, const std::string& componentType) + FillOctreeSystem(World* world, EventBroker* eventBroker, Octree* octree, const std::string& fillComponentType) : System(world, eventBroker) - , PureSystem(componentType) + , PureSystem(fillComponentType) , m_Octree(octree) { } diff --git a/include/Engine/Core/ComponentWrapper.h b/include/Engine/Core/ComponentWrapper.h index 1dc131d2..df16dca9 100644 --- a/include/Engine/Core/ComponentWrapper.h +++ b/include/Engine/Core/ComponentWrapper.h @@ -43,6 +43,11 @@ struct ComponentWrapper // Specialization for string literals template void SetField(std::string name, const char(&value)[N]) { Field(name) = std::string(value); } + + void Copy(ComponentWrapper& destination) + { + memcpy(destination.Data, this->Data, Info.Stride); + } struct SubscriptProxy { diff --git a/include/Engine/Core/EPickupSpawned.h b/include/Engine/Core/EPickupSpawned.h new file mode 100644 index 00000000..9f85913a --- /dev/null +++ b/include/Engine/Core/EPickupSpawned.h @@ -0,0 +1,17 @@ +#ifndef EPickupSpawned_h__ +#define EPickupSpawned_h__ + +#include "Core/Event.h" +#include "Core/EntityWrapper.h" + +namespace Events +{ + +struct PickupSpawned : Event +{ + EntityWrapper Pickup; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/Core/EPlayerDamage.h b/include/Engine/Core/EPlayerDamage.h index a7e135ce..8ba3907e 100644 --- a/include/Engine/Core/EPlayerDamage.h +++ b/include/Engine/Core/EPlayerDamage.h @@ -9,6 +9,7 @@ namespace Events struct PlayerDamage : Event { + //NOTE: this struct is missing information on what the damageSource is EntityWrapper Player; double Damage; }; diff --git a/include/Engine/Core/EPlayerDeath.h b/include/Engine/Core/EPlayerDeath.h index 00ede5ed..363745a6 100644 --- a/include/Engine/Core/EPlayerDeath.h +++ b/include/Engine/Core/EPlayerDeath.h @@ -2,7 +2,7 @@ #define EPlayerDeath_h__ #include "EventBroker.h" -#include "../Core/Entity.h" +#include "../Core/EntityWrapper.h" namespace Events { @@ -10,8 +10,7 @@ namespace Events struct PlayerDeath : Event { //KilledBy,KilledByWhat is optional for now. It might be used later in the playerlog-system - EntityID KilledBy; - EntityID PlayerID; + EntityWrapper Player; std::string KilledByWhat; }; diff --git a/include/Engine/Core/EPlayerHealthPickup.h b/include/Engine/Core/EPlayerHealthPickup.h index f3158f92..7d44e544 100644 --- a/include/Engine/Core/EPlayerHealthPickup.h +++ b/include/Engine/Core/EPlayerHealthPickup.h @@ -2,16 +2,16 @@ #define EPlayerHealthPickup_h__ #include "EventBroker.h" -#include "../Core/Entity.h" +#include "../Core/EntityWrapper.h" namespace Events { -struct PlayerHealthPickup : Event -{ - double HealthAmount; - EntityID PlayerHealedID; -}; + struct PlayerHealthPickup : Event + { + EntityWrapper Player; + double HealthAmount; + }; } diff --git a/include/Engine/Core/EntityWrapper.h b/include/Engine/Core/EntityWrapper.h index bf34b9be..087471c0 100644 --- a/include/Engine/Core/EntityWrapper.h +++ b/include/Engine/Core/EntityWrapper.h @@ -25,6 +25,7 @@ struct EntityWrapper const std::string Name(); bool HasComponent(const std::string& componentType); + void AttachComponent(const char* componentName); EntityWrapper Parent(); EntityWrapper FirstChildByName(const std::string& name); EntityWrapper FirstParentWithComponent(const std::string& componentType); diff --git a/include/Engine/Core/MemoryPool.h b/include/Engine/Core/MemoryPool.h index 3a1cc069..f4073294 100644 --- a/include/Engine/Core/MemoryPool.h +++ b/include/Engine/Core/MemoryPool.h @@ -102,7 +102,7 @@ public: m_ExtraMemory.push_back((char*)malloc(m_Stride)); //We should preferably not enter here to avoid performance issues. Set more numMaxElements in constructor instead. if (!DisableMemoryPool::Value) { - LOG_WARNING("Allocated slots exceed Pool size, extra memory allocated dynamically. Pool size: %u, dynamic size: %u.", m_NumSlots, m_ExtraMemory.size()); + LOG_DEBUG("Allocated slots exceed Pool size, extra memory allocated dynamically. Pool size: %u, dynamic size: %u.", m_NumSlots, m_ExtraMemory.size()); } return m_ExtraMemory.back(); } diff --git a/include/Engine/Core/Octree.h b/include/Engine/Core/Octree.h index 8bac5503..907d5736 100644 --- a/include/Engine/Core/Octree.h +++ b/include/Engine/Core/Octree.h @@ -111,7 +111,7 @@ struct Child std::vector& m_StaticObjectsRef; std::vector& m_DynamicObjectsRef; - bool hasChildren() const; + inline bool hasChildren() const { return m_Children[0] != nullptr; } int childIndexContainingPoint(const glm::vec3& point) const; std::vector childIndicesContainingBox(const AABB& box) const; }; diff --git a/include/Engine/Core/Ray.h b/include/Engine/Core/Ray.h index a234a488..03bfa391 100644 --- a/include/Engine/Core/Ray.h +++ b/include/Engine/Core/Ray.h @@ -7,6 +7,10 @@ class Ray { public: + Ray() + : m_Origin(glm::vec3(0.f)) + , m_Direction(glm::vec3(0, 0, 1)) + {} Ray(const glm::vec3& origin, const glm::vec3& dir) : m_Origin(origin) , m_Direction(glm::normalize(dir)) diff --git a/include/Engine/Core/Transform.h b/include/Engine/Core/Transform.h index 2f549140..bd381e8b 100644 --- a/include/Engine/Core/Transform.h +++ b/include/Engine/Core/Transform.h @@ -18,6 +18,7 @@ glm::vec3 AbsoluteScale(EntityWrapper entity); glm::vec3 AbsoluteScale(World* world, EntityID entity); glm::mat4 ModelMatrix(EntityWrapper entity); glm::mat4 ModelMatrix(EntityID entity, World* world); +glm::vec3 TransformPoint(const glm::vec3& point, const glm::mat4& matrix); } diff --git a/include/Engine/Rendering/DrawColorCorrectionPass.h b/include/Engine/Rendering/DrawColorCorrectionPass.h index fcde73d7..231e2d33 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, GLfloat gamma, GLfloat exposure); + void Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure); private: const IRenderer* m_Renderer; diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index dd0df84a..72fd756b 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -22,15 +22,23 @@ public: //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 DrawModelRenderQueues(std::list>& job, RenderScene& scene); + + void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene); + void DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene); + void DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene); + void DrawToDepthBuffer(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); @@ -44,9 +52,16 @@ private: Texture* m_GreyTexture; FrameBuffer m_FinalPassFrameBuffer; + FrameBuffer m_FinalPassFrameBufferLowRes; GLuint m_BloomTexture; GLuint m_SceneTexture; + GLuint m_BloomTextureLowRes; + GLuint m_SceneTextureLowRes; GLuint m_DepthBuffer; + GLuint m_DepthBufferLowRes; + + //maqke this component based i guess? + GLuint m_ShieldPixelRate = 16; const IRenderer* m_Renderer; const LightCullingPass* m_LightCullingPass; @@ -55,6 +70,8 @@ private: ShaderProgram* m_ExplosionEffectProgram; ShaderProgram* m_ExplosionEffectSplatMapProgram; ShaderProgram* m_ForwardPlusSplatMapProgram; + ShaderProgram* m_ShieldToStencilProgram; + ShaderProgram* m_FillDepthBufferProgram; ShaderProgram* m_ForwardPlusSkinnedProgram; diff --git a/include/Engine/Rendering/DrawFinalPassState.h b/include/Engine/Rendering/DrawFinalPassState.h index 10b840e9..91fc4cf4 100644 --- a/include/Engine/Rendering/DrawFinalPassState.h +++ b/include/Engine/Rendering/DrawFinalPassState.h @@ -12,4 +12,11 @@ private: }; +class DrawStencilState : public RenderState +{ +public: + DrawStencilState(GLuint frameBuffer); + ~DrawStencilState(); +}; + #endif \ No newline at end of file diff --git a/include/Engine/Rendering/RenderQueue.h b/include/Engine/Rendering/RenderQueue.h index af9d928e..5cc6fd78 100644 --- a/include/Engine/Rendering/RenderQueue.h +++ b/include/Engine/Rendering/RenderQueue.h @@ -19,22 +19,30 @@ struct RenderScene { ::Camera* Camera = nullptr; - std::list> OpaqueObjects; - std::list> TransparentObjects; - std::list> PointLightJobs; - std::list> TextJobs; - std::list> DirectionalLightJobs; + struct Queues { + std::list> OpaqueObjects; + std::list> TransparentObjects; + std::list> OpaqueShieldedObjects; + std::list> TransparentShieldedObjects; + std::list> ShieldObjects; + std::list> PointLight; + std::list> Text; + std::list> DirectionalLight; + } Jobs; + Rectangle Viewport; bool ClearDepth = false; glm::vec4 AmbientColor; void Clear() { - OpaqueObjects.clear(); - TransparentObjects.clear(); - PointLightJobs.clear(); - TextJobs.clear(); - DirectionalLightJobs.clear(); + Jobs.OpaqueObjects.clear(); + Jobs.TransparentObjects.clear(); + Jobs.OpaqueShieldedObjects.clear(); + Jobs.TransparentShieldedObjects.clear(); + Jobs.ShieldObjects.clear(); + Jobs.Text.clear(); + Jobs.DirectionalLight.clear(); } }; diff --git a/include/Engine/Rendering/RenderState.h b/include/Engine/Rendering/RenderState.h index 688ef520..c1886247 100644 --- a/include/Engine/Rendering/RenderState.h +++ b/include/Engine/Rendering/RenderState.h @@ -2,6 +2,7 @@ #define RenderState_h__ #include +#include #include "../Common.h" #include "../OpenGL.h" #include "../GLM.h" @@ -19,6 +20,9 @@ public: bool BindFramebuffer(GLint framebuffer); bool BlendEquation(GLenum mode); bool BlendFunc(GLenum sfactor, GLenum dfactor); + bool StencilOp(GLenum sfail, GLenum dpfail, GLenum dppass); + bool StencilFunc(GLenum func, GLint ref, GLuint mask); + bool StencilMask(GLuint mask); bool DepthMask(GLboolean flag); private: diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index 50ccdb0c..d12ca647 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -40,7 +40,7 @@ private: EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); - void fillModels(std::list>& opaqueJobs, std::list>& transparentJobs); + void fillModels(RenderScene::Queues &jobs); void fillText(std::list>& jobs, World* world); void fillPointLights(std::list>& jobs, World* world); void fillDirectionalLights(std::list>& jobs, World* world); diff --git a/include/Game/Systems/HealthSystem.h b/include/Game/Systems/HealthSystem.h index 3b069349..61456d5d 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -12,6 +12,7 @@ #include #include +#include class HealthSystem : public PureSystem { @@ -26,7 +27,7 @@ private: EventRelay m_EPlayerDamage; bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e); EventRelay m_EPlayerHealthPickup; - bool HealthSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup& e); + bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e); //vector which will keep track of health changes std::vector> m_DeltaHealthVector; diff --git a/include/Game/Systems/PickupSpawnSystem.h b/include/Game/Systems/PickupSpawnSystem.h new file mode 100644 index 00000000..24cee2b9 --- /dev/null +++ b/include/Game/Systems/PickupSpawnSystem.h @@ -0,0 +1,33 @@ +#ifndef PickupSpawnSystem_h__ +#define PickupSpawnSystem_h__ + +#include "Core/System.h" +#include "Core/Transform.h" +#include "Core/ResourceManager.h" +#include "Core/EntityFileParser.h" +#include "Core/EPickupSpawned.h" +#include "Core/EPlayerHealthPickup.h" +#include "Engine/Collision/ETrigger.h" +#include "Common.h" +#include + +class PickupSpawnSystem : public ImpureSystem +{ +public: + PickupSpawnSystem(World* world, EventBroker* eventBroker); + + virtual void Update(double dt) override; + +private: + EventRelay m_ETriggerTouch; + bool OnTriggerTouch(Events::TriggerTouch& e); + + struct NewHealthPickup { + glm::vec3 Pos; + double HealthGain; + double RespawnTimer; + double DecreaseThisRespawnTimer; + }; + std::vector m_ETriggerTouchVector; +}; +#endif diff --git a/include/Game/Systems/PlayerDeathSystem.h b/include/Game/Systems/PlayerDeathSystem.h new file mode 100644 index 00000000..988dad57 --- /dev/null +++ b/include/Game/Systems/PlayerDeathSystem.h @@ -0,0 +1,29 @@ +#ifndef PlayerDeathSystem_h__ +#define PlayerDeathSystem_h__ + +#include "Core/System.h" +#include "Input/EInputCommand.h" +#include "GLM.h" +#include "Rendering/ESetCamera.h" +#include "Core/ConfigFile.h" + +#include "Core/EntityFile.h" +#include "Core/EntityFileParser.h" + +#include "Core/EPlayerDeath.h" + +class PlayerDeathSystem : public ImpureSystem +{ +public: + PlayerDeathSystem(World* world, EventBroker* eventBroker); + + virtual void Update(double dt) override; + +private: + EventRelay m_OnPlayerDeath; + bool OnPlayerDeath(Events::PlayerDeath& e); + + void createDeathEffect(EntityWrapper player); + +}; +#endif \ No newline at end of file diff --git a/include/Game/Systems/PlayerSpawnSystem.h b/include/Game/Systems/PlayerSpawnSystem.h index b0ff1d79..f5aa7b82 100644 --- a/include/Game/Systems/PlayerSpawnSystem.h +++ b/include/Game/Systems/PlayerSpawnSystem.h @@ -3,6 +3,7 @@ #include "Systems/SpawnerSystem.h" #include "Events/ESpawnerSpawn.h" #include "Core/EPlayerSpawned.h" +#include "Core/EPlayerDeath.h" #include "Rendering/ESetCamera.h" #include "Core/ConfigFile.h" diff --git a/resources/DefaultInput.ini b/resources/DefaultInput.ini index a3f7d166..589dfb3f 100644 --- a/resources/DefaultInput.ini +++ b/resources/DefaultInput.ini @@ -13,7 +13,8 @@ A=Right,-1 R=Reload Space=Jump LeftControl=Crouch -LeftShift=Sprint +RightShift=Sprint +LeftShift=SpecialAbility F1=ToggleEditor C=ConnectToServer N=SwitchToServer diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index c8753b98..1aa98f17 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -31,6 +31,9 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/AABB.xsd b/resources/Schema/Components/AABB.xsd index daa633a6..7dec510f 100644 --- a/resources/Schema/Components/AABB.xsd +++ b/resources/Schema/Components/AABB.xsd @@ -7,10 +7,10 @@ - Middle point of the bounding box + Middle point of the bounding box, in model space - Size of the bounding box + Size of the bounding box, in model space diff --git a/resources/Schema/Components/DashAbility.xml b/resources/Schema/Components/DashAbility.xml index 25b9e19a..a313c447 100644 --- a/resources/Schema/Components/DashAbility.xml +++ b/resources/Schema/Components/DashAbility.xml @@ -1,4 +1,4 @@ - + 2.0 - \ No newline at end of file + \ No newline at end of file diff --git a/resources/Schema/Components/HealthPickup.xml b/resources/Schema/Components/HealthPickup.xml new file mode 100644 index 00000000..1c9ee0f4 --- /dev/null +++ b/resources/Schema/Components/HealthPickup.xml @@ -0,0 +1,5 @@ + + + 3 + 30 + \ No newline at end of file diff --git a/resources/Schema/Components/HealthPickup.xsd b/resources/Schema/Components/HealthPickup.xsd new file mode 100644 index 00000000..bf3b327c --- /dev/null +++ b/resources/Schema/Components/HealthPickup.xsd @@ -0,0 +1,21 @@ + + + + + + + + A Health Pickup + + + + + The respawn timer for a health pickup + + + How much percent max-health the player will get when he picks the healthPickup up + + + + + diff --git a/resources/Schema/Components/Physics.xml b/resources/Schema/Components/Physics.xml index 9d1638fb..6cb73c75 100644 --- a/resources/Schema/Components/Physics.xml +++ b/resources/Schema/Components/Physics.xml @@ -2,4 +2,6 @@ true + false + 0.33 diff --git a/resources/Schema/Components/Physics.xsd b/resources/Schema/Components/Physics.xsd index 72037f48..7fed1fb5 100644 --- a/resources/Schema/Components/Physics.xsd +++ b/resources/Schema/Components/Physics.xsd @@ -13,6 +13,10 @@ m/s^2 + + + The largest height of a "stair-step" that can be walked over + diff --git a/resources/Schema/Components/Shield.xml b/resources/Schema/Components/Shield.xml new file mode 100644 index 00000000..161f09bc --- /dev/null +++ b/resources/Schema/Components/Shield.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Shield.xsd b/resources/Schema/Components/Shield.xsd new file mode 100644 index 00000000..9831cbfc --- /dev/null +++ b/resources/Schema/Components/Shield.xsd @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Shielded.xml b/resources/Schema/Components/Shielded.xml new file mode 100644 index 00000000..0d95fb0a --- /dev/null +++ b/resources/Schema/Components/Shielded.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Shielded.xsd b/resources/Schema/Components/Shielded.xsd new file mode 100644 index 00000000..b2348cf5 --- /dev/null +++ b/resources/Schema/Components/Shielded.xsd @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/CollisionSpawnTest.xml b/resources/Schema/Entities/CollisionSpawnTest.xml new file mode 100644 index 00000000..331beae6 --- /dev/null +++ b/resources/Schema/Entities/CollisionSpawnTest.xml @@ -0,0 +1,164 @@ + + + + + + + + + + + + + + ../assets/Models/Test/ObstacleCourse.mesh + + + + + + + + + + + 0.46000027656555176 + + + + + + + + + + + + + ../assets/Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/CollisionTestLevel.xml b/resources/Schema/Entities/CollisionTestLevel.xml index 1a811f46..66b1109f 100644 --- a/resources/Schema/Entities/CollisionTestLevel.xml +++ b/resources/Schema/Entities/CollisionTestLevel.xml @@ -1,122 +1,67 @@ - + + - - - - - - - Models/Test/DummyScene.mesh - - - - - - - - - - - Models/Core/UnitSphere.mesh - - - - - - - - - - - Models/Widgets/Rotate/RotationWidgetX.mesh - - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - - - - - - - - - Models/Core/UnitRaptor.mesh - - - - - - - - - - - - 20 - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + ../assets/Models/Test/ObstacleCourse.mesh + + + + + + + + + + + 0.46000027656555176 + + + + + + + + + + + + + ../assets/Models/Core/UnitCube.mesh + + + false + + + + + + + + + + + + + + + ../assets/Models/Core/colorbox.mesh + + + + + + + + + + + diff --git a/resources/Schema/Entities/GameMap.xml b/resources/Schema/Entities/GameMap.xml index 0d6052eb..84a1e363 100644 --- a/resources/Schema/Entities/GameMap.xml +++ b/resources/Schema/Entities/GameMap.xml @@ -8,6 +8,11 @@ + + + + + Models/LevelBase/MapVersion1.mesh @@ -139,7 +144,7 @@ - + @@ -201,7 +206,7 @@ - + diff --git a/resources/Schema/Entities/HealthPickup.xml b/resources/Schema/Entities/HealthPickup.xml new file mode 100644 index 00000000..dfc6f938 --- /dev/null +++ b/resources/Schema/Entities/HealthPickup.xml @@ -0,0 +1,18 @@ + + + + + + + + Models/Core/UnitSphere.mesh + + + + + + + + + + diff --git a/resources/Schema/Entities/HealthPickupTest.xml b/resources/Schema/Entities/HealthPickupTest.xml new file mode 100644 index 00000000..2980fb51 --- /dev/null +++ b/resources/Schema/Entities/HealthPickupTest.xml @@ -0,0 +1,294 @@ + + + + + + + + + + + + Models\MapVersion1.mesh + + + + + + + + + 2 + + + Models/DirectionalLightWidget.mesh + false + + + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 22 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + + + 1 + 22 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + + + 4 + 44 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + diff --git a/resources/Schema/Entities/LevelCollisionTest.xml b/resources/Schema/Entities/LevelCollisionTest.xml new file mode 100644 index 00000000..3c3f3bab --- /dev/null +++ b/resources/Schema/Entities/LevelCollisionTest.xml @@ -0,0 +1,41 @@ + + + + + + + ../assets/Models/MapVersion1.mesh + + + + + + + + + + + ../assets/Models/Core/UnitCube.mesh + + + false + + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/ModelCollisionTest.xml b/resources/Schema/Entities/ModelCollisionTest.xml new file mode 100644 index 00000000..c4a3f81b --- /dev/null +++ b/resources/Schema/Entities/ModelCollisionTest.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + ../assets/Models/Core/Tri.obj + + + + + + + + + + + + ../assets/Models/Core/Tri.obj + + + + + + + + + + + + + + + + ../assets/Models/Core/UnitCube.obj + + + + + + + + + + + diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index a356b7ee..b8b68ef1 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -6,22 +6,6 @@ - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - @@ -81,6 +65,10 @@ + + + + Models/Test/ObstacleCourse.mesh @@ -88,51 +76,6 @@ - - - - - - Models/Core/UnitCube.mesh - false - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - false - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - false - - - - - - - - @@ -197,7 +140,7 @@ - + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 45c75c63..7c081e4c 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -101,13 +101,6 @@ - - true - - 3.7999999523162842 - - true - Models/Weapons/Red/AssaultWeaponRed.mesh diff --git a/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml new file mode 100644 index 00000000..8a9f5e5b --- /dev/null +++ b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml @@ -0,0 +1,43 @@ + + + + + + Hold Pos + + + 2.5 + + + true + + + true + 3 + + true + + + Models/AssaultAnimated.mesh + + true + + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 831e7d7c..aef0fa87 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -105,7 +105,7 @@ - + @@ -122,7 +122,7 @@ Run - + 1 @@ -138,7 +138,7 @@ Walk - + 1 @@ -188,7 +188,7 @@ - + @@ -196,7 +196,7 @@ Run - + 1 @@ -237,7 +237,7 @@ - + @@ -301,7 +301,7 @@ - + @@ -333,7 +333,7 @@ - + @@ -586,7 +586,7 @@ true - + @@ -683,7 +683,7 @@ - + @@ -730,7 +730,7 @@ - + @@ -790,7 +790,7 @@ - + @@ -837,7 +837,7 @@ - + @@ -883,7 +883,7 @@ - + @@ -930,7 +930,7 @@ - + @@ -977,7 +977,7 @@ - + @@ -1038,7 +1038,7 @@ Models/Core/UnitCube.mesh - + true @@ -1088,7 +1088,8 @@ Models/Core/UnitCube.mesh - + + true @@ -1131,6 +1132,7 @@ Models/Core/UnitCube.mesh + true @@ -1177,7 +1179,8 @@ Models/Core/UnitCube.mesh - + + true @@ -1225,7 +1228,7 @@ Models/Core/UnitCube.mesh - + true @@ -1347,6 +1350,19 @@ + + + + ExplosionEffect Test + Fonts/DroidSans.ttf,64 + + + + + + + + @@ -1374,7 +1390,7 @@ - + @@ -1383,7 +1399,7 @@ true - 0.75008034908941568 + 1.3671759474185377 3.7999999523162842 true @@ -1430,7 +1446,7 @@ - + @@ -1439,7 +1455,7 @@ - 1.1999860997035228 + 0.31711568080172703 Models/Characters/Assault/AssaultTPose.mesh @@ -1482,7 +1498,7 @@ - + @@ -1490,14 +1506,14 @@ Walk - + 1 true - 0.68343188336345406 + 0.31711568080172703 true @@ -1515,18 +1531,120 @@ - + - - ExplosionEffect Test - Fonts/DroidSans.ttf,64 - + + Models/Core/UnitCylinder.mesh + + - - + - + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + true + + + 0.95047462600732735 + 10 + + 3 + true + + + Models/Core/UnitSphere.mesh + + true + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + true + + + 1.350502887383392 + true + 5 + true + + + Models/Assault.mesh + + true + + + + + + + + + + @@ -1553,6 +1671,278 @@ + + + + + + + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + + + + + false + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 1 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Models/CrosshairQuad.mesh + + + + + + + + + + + + + true + + 1.3671759474185377 + 3.7999999523162842 + + true + + + Models/AssaultWeaponRed.mesh + + + + + + + + + + + + + + + + + + + + + + + + + Models/Camera.mesh + false + + + + + + + + + + + + Hold Pos + + 1 + + + + Models/AssaultAnimated.mesh + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + + + + + + + + + Models/Log.mesh + + + + + + + + + + + + Models/BushAlive.mesh + + + + + + + + + + + + + + + Defender Shield Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + diff --git a/resources/Schema/Entities/aaaatestremoveme.xml b/resources/Schema/Entities/aaaatestremoveme.xml new file mode 100644 index 00000000..8da40b58 --- /dev/null +++ b/resources/Schema/Entities/aaaatestremoveme.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + Models/Core/Unithexagon.mesh + + + + + + + + + + + + + + + + + + + 2.2000000476837158 + + + + + + + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 176f30e6..16366a67 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -39,6 +39,8 @@ + + diff --git a/resources/Shaders/DrawColorCorrection.frag.glsl b/resources/Shaders/DrawColorCorrection.frag.glsl index 91ace0c7..76db3e82 100644 --- a/resources/Shaders/DrawColorCorrection.frag.glsl +++ b/resources/Shaders/DrawColorCorrection.frag.glsl @@ -2,6 +2,8 @@ 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; @@ -15,10 +17,19 @@ 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 += bloomColor; + hdrColorLowRes; + float hdrColorsum = hdrColorLowRes.r + hdrColorLowRes.g + hdrColorLowRes.b; //Toon mapping thingy - vec3 result = vec3(1.0) - exp(-hdrColor.rgb * Exposure); + vec3 result; + if(hdrColorsum > 0.0) { + result = vec3(1.0) - exp(-hdrColorLowRes.rgb * Exposure); + } else { + result = vec3(1.0) - exp(-hdrColor.rgb * Exposure); + } //gamme correction result = pow(result, vec3(1.0 / Gamma)); diff --git a/resources/Shaders/FillDepthBuffer.frag.glsl b/resources/Shaders/FillDepthBuffer.frag.glsl new file mode 100644 index 00000000..a125fc25 --- /dev/null +++ b/resources/Shaders/FillDepthBuffer.frag.glsl @@ -0,0 +1,11 @@ +#version 430 + +in VertexData{ + vec3 Position; +}Input; + +void main() +{ +} + + diff --git a/resources/Shaders/FillDepthBuffer.vert.glsl b/resources/Shaders/FillDepthBuffer.vert.glsl new file mode 100644 index 00000000..ff849790 --- /dev/null +++ b/resources/Shaders/FillDepthBuffer.vert.glsl @@ -0,0 +1,21 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout(location = 0) in vec3 Position; +layout(location = 5) in vec4 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + gl_Position = P * V * M * vec4(Position, 1.0); + + Output.Position = Position; +} \ No newline at end of file diff --git a/resources/Shaders/ShieldStencil.frag.glsl b/resources/Shaders/ShieldStencil.frag.glsl new file mode 100644 index 00000000..db88ab24 --- /dev/null +++ b/resources/Shaders/ShieldStencil.frag.glsl @@ -0,0 +1,15 @@ +#version 430 + +in VertexData{ + vec3 Position; +}Input; + + +out vec4 fragmentColor; + +void main() +{ + fragmentColor = vec4(0.5, 0.0, 0.0, 0.0); +} + + diff --git a/resources/Shaders/ShieldStencil.vert.glsl b/resources/Shaders/ShieldStencil.vert.glsl new file mode 100644 index 00000000..b6669f2c --- /dev/null +++ b/resources/Shaders/ShieldStencil.vert.glsl @@ -0,0 +1,19 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout(location = 0) in vec3 Position; + + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + gl_Position = P * V * M * vec4(Position, 1.0); + + Output.Position = Position; +} \ No newline at end of file diff --git a/src/Engine/Collision/CollidableOctreeSystem.cpp b/src/Engine/Collision/CollidableOctreeSystem.cpp deleted file mode 100644 index 476414dd..00000000 --- a/src/Engine/Collision/CollidableOctreeSystem.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "Collision/CollidableOctreeSystem.h" - -void CollidableOctreeSystem::Update(double dt) -{ - m_Octree->ClearDynamicObjects(); -} - -void CollidableOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) -{ - if (entity.HasComponent("AABB")) { - boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); - if (absoluteAABB) { - m_Octree->AddDynamicObject(*absoluteAABB); - } - } else if (entity.HasComponent("Model")) { - // TODO: Derive AABB from model - } -} \ No newline at end of file diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 11288560..839a8e77 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -4,6 +4,7 @@ #include "Engine/GLM.h" #include "Core/World.h" #include "Rendering/Model.h" +#include "imgui/imgui.h" namespace Collision { @@ -116,36 +117,79 @@ bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation) return glm::all(axisesIntersecting); } +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + bool trueOnNegativeDistance) +{ + glm::vec3 e1 = v1 - v0; //v1 - v0 + glm::vec3 e2 = v2 - v0; //v2 - v0 + glm::vec3 m = ray.Origin() - v0; + glm::vec3 MxE1 = glm::cross(m, e1); + glm::vec3 DxE2 = glm::cross(ray.Direction(), e2); + float DetInv = glm::dot(e1, DxE2); + if (std::abs(DetInv) < FLT_EPSILON) { + return false; + } + DetInv = 1.0f / DetInv; + float u = glm::dot(m, DxE2) * DetInv; + float v = glm::dot(ray.Direction(), MxE1) * DetInv; + //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem + if ((u + 0.001f) < 0 || (v + 0.001f) < 0 || 1 < u + v) { + return false; + } + //Here, u and v are positive, u+v <= 1, and if distance is positive - triangle is hit. + return trueOnNegativeDistance || 0 <= glm::dot(e2, MxE1) * DetInv; +} + bool RayVsModel(const Ray& ray, const std::vector& modelVertices, const std::vector& modelIndices) { for (int i = 0; i < modelIndices.size(); ++i) { glm::vec3 v0 = modelVertices[modelIndices[i]].Position; - glm::vec3 e1 = modelVertices[modelIndices[++i]].Position - v0; //v1 - v0 - glm::vec3 e2 = modelVertices[modelIndices[++i]].Position - v0; //v2 - v0 - glm::vec3 m = ray.Origin() - v0; - glm::vec3 MxE1 = glm::cross(m, e1); - glm::vec3 DxE2 = glm::cross(ray.Direction(), e2); - float DetInv = glm::dot(e1, DxE2); - if (std::abs(DetInv) < FLT_EPSILON) { - continue; - } - DetInv = 1.0f / DetInv; - float u = glm::dot(m, DxE2) * DetInv; - float v = glm::dot(ray.Direction(), MxE1) * DetInv; - //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem - if ((u + 0.001f) < 0 || (v + 0.001f) < 0 || 1 < u + v) { - continue; - } - //Here, u and v are positive, u+v <= 1, and if distance is positive - triangle is hit. - if (0 <= glm::dot(e2, MxE1) * DetInv) { + glm::vec3 v1 = modelVertices[modelIndices[++i]].Position; + glm::vec3 v2 = modelVertices[modelIndices[++i]].Position; + if (RayVsTriangle(ray, v0, v1, v2)) { return true; } } return false; } +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + float& outDistance, + float& outUCoord, + float& outVCoord, + bool trueOnNegativeDistance) +{ + glm::vec3 e1 = v1 - v0; //v1 - v0 + glm::vec3 e2 = v2 - v0; //v2 - v0 + glm::vec3 m = ray.Origin() - v0; + glm::vec3 MxE1 = glm::cross(m, e1); + glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);//pVec + float DetInv = glm::dot(e1, DxE2); + if (std::abs(DetInv) < FLT_EPSILON) { + return false; + } + DetInv = 1.0f / DetInv; + float dist = glm::dot(e2, MxE1) * DetInv; + if (dist >= outDistance) { + return false; + } + outDistance = dist; + outUCoord = glm::dot(m, DxE2) * DetInv; + outVCoord = glm::dot(ray.Direction(), MxE1) * DetInv; + + //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem + //If u and v are positive, u+v <= 1, dist is positive, and less than closest. + return (0 <= (outUCoord + 0.001f) && 0 <= (outVCoord + 0.001f) && outUCoord + outVCoord <= 1 && (trueOnNegativeDistance || 0 <= dist)); +} + bool RayVsModel(const Ray& ray, const std::vector& modelVertices, const std::vector& modelIndices, @@ -157,26 +201,12 @@ bool RayVsModel(const Ray& ray, bool hit = false; for (int i = 0; i < modelIndices.size(); ++i) { glm::vec3 v0 = modelVertices[modelIndices[i]].Position; - glm::vec3 e1 = modelVertices[modelIndices[++i]].Position - v0; //v1 - v0 - glm::vec3 e2 = modelVertices[modelIndices[++i]].Position - v0; //v2 - v0 - glm::vec3 m = ray.Origin() - v0; - glm::vec3 MxE1 = glm::cross(m, e1); - glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);//pVec - float DetInv = glm::dot(e1, DxE2); - if (std::abs(DetInv) < FLT_EPSILON) { - continue; - } - DetInv = 1.0f / DetInv; - float dist = glm::dot(e2, MxE1) * DetInv; - if (dist >= outDistance) { - continue; - } - float u = glm::dot(m, DxE2) * DetInv; - float v = glm::dot(ray.Direction(), MxE1) * DetInv; - - //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem - //If u and v are positive, u+v <= 1, dist is positive, and less than closest. - if (0 <= (u + 0.001f) && 0 <= (v + 0.001f) && u + v <= 1 && 0 <= dist) { + glm::vec3 v1 = modelVertices[modelIndices[++i]].Position; + glm::vec3 v2 = modelVertices[modelIndices[++i]].Position; + float dist; + float u; + float v; + if (RayVsTriangle(ray, v0, v1, v2, dist, u, v)) { outDistance = dist; outUCoord = u; outVCoord = v; @@ -199,74 +229,365 @@ bool RayVsModel(const Ray& ray, return hit; } -bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) +constexpr inline int signNonZero(float x) { - bool hit = false; - + return x < 0 ? -1 : 1; +} + +inline glm::vec3 signNonZero(const glm::vec3& x) +{ + glm::vec3 r; + for (int i = 0; i < 3; ++i) { + r[i] = (float)signNonZero(x[i]); + } + return r; +} + +template +bool vectorHasLength(const T& vec) +{ + return glm::any(glm::greaterThan(glm::abs(vec), T(0.0001f))); +} + +bool rectangleVsTriangle(const glm::vec2& boxMin, + const glm::vec2& boxMax, + const std::array& triPos, + glm::vec2& resolutionDirection, + float& resolutionDistanceSq, + bool& pushedFromTriNormal) +{ + pushedFromTriNormal = false; + resolutionDistanceSq = INFINITY; + //Project along box normals (coordinate axes, since it's axis-aligned). + for (int ax = 0; ax < 2; ++ax) { + float minTri = INFINITY; + float maxTri = -INFINITY; + for (const glm::vec2& t : triPos) { + minTri = std::min(t[ax], minTri); + maxTri = std::max(t[ax], maxTri); + } + if (boxMax[ax] <= minTri || maxTri <= boxMin[ax]) { + return false; + } + + //Here: maxBox > minTri && minBox < maxTri + //Left is negative. + float leftRes = minTri - boxMax[ax]; + float rightRes = maxTri - boxMin[ax]; + float push = rightRes < -leftRes ? rightRes : leftRes; + float absPushSq = abs(push); + absPushSq *= absPushSq; + + if (absPushSq < resolutionDistanceSq) { + resolutionDistanceSq = absPushSq; + resolutionDirection[1 - ax] = 0.f; + resolutionDirection[ax] = push; + } + } + //Project along triangle normals. + //Put edges into normal vector, make normals in the loop. + std::array triNormals = { + triPos[1] - triPos[0], + triPos[2] - triPos[1], + triPos[0] - triPos[2] + }; + std::array boxPos = { + boxMax, + glm::vec2(boxMax.x, boxMin.y), + glm::vec2(boxMin.x, boxMax.y), + boxMin + }; + for (auto& normal : triNormals) { + if (!vectorHasLength(normal)) { + continue; + } + //Rotate edge to a normal. + normal = glm::normalize(glm::vec2(-normal.y, normal.x)); + //Project triangle onto the normal. + float minTri = INFINITY; + float maxTri = -INFINITY; + for (const glm::vec2& point : triPos) { + float dot = glm::dot(normal, point); + minTri = std::min(dot, minTri); + maxTri = std::max(dot, maxTri); + } + //Project box onto the normal. + float minBox = INFINITY; + float maxBox = -INFINITY; + for (const glm::vec2& point : boxPos) { + float dot = glm::dot(normal, point); + minBox = std::min(dot, minBox); + maxBox = std::max(dot, maxBox); + } + if (maxBox <= minTri || maxTri <= minBox) { + return false; + } + + //Here: maxBox > minTri && minBox < maxTri + //Left is negative. + float leftRes = minTri - maxBox; + float rightRes = maxTri - minBox; + float push = rightRes < -leftRes ? rightRes : leftRes; + float absPushSq = abs(push); + absPushSq *= absPushSq; + + if (absPushSq < resolutionDistanceSq) { + resolutionDistanceSq = absPushSq; + resolutionDirection = push * normal; + pushedFromTriNormal = true; + } + } + return true; +} + +constexpr float SlopeConstant(float degrees) +{ + return (1.0f - degrees / 90.f); +} + +//Returns true if the angle between horizon and the collision surface is less than 45 degrees. +constexpr bool FaceIsGround(float faceNormalY) +{ + //TODO: Perhaps the 45 degrees could be saved in a component or in the config.. + return faceNormalY > SlopeConstant(45.0f); +} + +//An array containing 3 int pairs { 0, 2 }, { 0, 1 }, { 1, 2 } +constexpr std::array, 3> dimensionPairs({ std::pair(0, 2), std::pair(0, 1), std::pair(1, 2) }); + +bool AABBvsTriangle(const AABB& box, + const std::array& triPos, + const glm::vec3& originalBoxVelocity, + float verticalStepHeight, + bool& isOnGround, + glm::vec3& boxVelocity, + glm::vec3& outResolution) +{ + //Check so we don't have a zero area triangle when calculating the normal. + //Also, don't check a triangle facing away from the player. + //Less checks, and we should be able to walk out from models if we are trapped inside. + glm::vec3 triNormal = glm::cross(triPos[1] - triPos[0], triPos[2] - triPos[0]); + if (!vectorHasLength(triNormal) || (glm::dot(triNormal, originalBoxVelocity) > 0)) { + return false; + } + triNormal = glm::normalize(triNormal); + + enum BoxTriResolveCase + { + ResolveDimX, + ResolveDimY, + ResolveDimZ, + Line, //Box edge colliding with triangle line. + Corner //Box corner colliding with the triangle face. + }; + struct Resolution + { + Resolution() + : DistanceSq(INFINITY) + , Vector(0.f) + {} + BoxTriResolveCase Case; + float DistanceSq; + glm::vec3 Vector; + }; + //The smallest resolution that solves the collision. + Resolution resolveShortest; + //The smallest resolution that solves the collision, that resolves upwards. + Resolution resolveUpwards; + //If player stands on the ground and collides with a ground triangle, + //we might step up onto it if the step is small enough. + bool canStairStepUp = isOnGround && FaceIsGround(triNormal.y); + const glm::vec3& origin = box.Origin(); + const glm::vec3& half = box.HalfSize(); const glm::vec3& min = box.MinCorner(); const glm::vec3& max = box.MaxCorner(); - outResolutionVector.x = INFINITY; - - for (int i = 0; i < modelIndices.size(); ++i) { - glm::vec3 p = modelVertices[i].Position; - p = glm::vec3(modelMatrix * glm::vec4(p.x, p.y, p.z, 1)); - - float distFromOrigin = glm::abs(origin.x - p.x); - float penetration = box.HalfSize().x - distFromOrigin; - if (penetration > 0 && penetration < glm::abs(outResolutionVector.x)) { - if (p.x > origin.x) { - outResolutionVector.x = -penetration; - } else { - outResolutionVector.x = penetration; + //For each projection in xy-, xz-, and yx-planes. + for (std::pair dim : dimensionPairs) { + //2D Triangle. + //Project triangle. + std::array t2D = { + glm::vec2(triPos[0][dim.first], triPos[0][dim.second]), + glm::vec2(triPos[1][dim.first], triPos[1][dim.second]), + glm::vec2(triPos[2][dim.first], triPos[2][dim.second]) + }; + //Project box. + glm::vec2 boxMin(min[dim.first], min[dim.second]); + glm::vec2 boxMax(max[dim.first], max[dim.second]); + glm::vec2 resolutionVector; + float resolutionDist; + bool pushedFromTriangleLine; + //if projections don't overlap, return false. + if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) { + return false; + } else { + //Overwrite the smallest resolution if this is smaller. + if (resolutionDist < resolveShortest.DistanceSq) { + resolveShortest.Vector = glm::vec3(0.f); + resolveShortest.Vector[dim.first] = resolutionVector.x; + resolveShortest.Vector[dim.second] = resolutionVector.y; + resolveShortest.DistanceSq = resolutionDist; + //If we pushed away from triangle line (edge), or if we + //move the player along one coordinate axis (pick the dimension that isn't zero). + resolveShortest.Case = pushedFromTriangleLine ? Line : static_cast((abs(resolveShortest.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first); + } + //Overwrite the smallest upward resolution if this is smaller, and resolves upwards. + constexpr int yAxis = 1; + bool resIsUpwardsIn3D = dim.first == yAxis && resolutionVector.x > 0 || dim.second == yAxis && resolutionVector.y > 0; + if (canStairStepUp && resIsUpwardsIn3D && resolutionDist < resolveUpwards.DistanceSq) { + resolveUpwards.Vector = glm::vec3(0.f); + resolveUpwards.Vector[dim.first] = resolutionVector.x; + resolveUpwards.Vector[dim.second] = resolutionVector.y; + resolveUpwards.DistanceSq = resolutionDist; + //If we pushed away from triangle line (edge), or if we + //move the player along one coordinate axis (pick the dimension that isn't zero). + resolveUpwards.Case = pushedFromTriangleLine ? Line : static_cast((abs(resolveUpwards.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first); } - hit = true; } - //glm::vec3 pLocal = origin - p; - //for (int axis = 0; axis < 3; ++axis) { - // if (p[axis] < min[axis] || p[axis] > max[axis]) { - // continue; - // } - - // if (glm::abs(pLocal[axis]) < box.HalfSize()[axis]) { - // outResolutionVector[axis] = (glm::sign(pLocal[axis]) * box.HalfSize()[axis]) - pLocal[axis]; - // hit = true; - // } - //} } + //If the triangle does intersect any of the cube diagonals, it will + //intersect the cube diagonal that comes + //closest to being perpendicular to the plane of the triangle. + glm::vec3 diagonal = signNonZero(triNormal) * half; + //The triangle plane contains all points P in dot(triNormal, P) == dot(triNormal, v0) + //The diagonal line contains all points P in P = origin + diagonal * t. + float t = glm::dot(triNormal, triPos[0] - origin) / glm::dot(triNormal, diagonal); + //If intersection point between plane and diagonal is within the box. + if (glm::abs(t) > 1) { + return false; + } + glm::vec3 cornerResolution = (1+t) * diagonal; + //Overwrite the smallest resolution if cornerResolution is smaller. + float lenSq = glm::length2(cornerResolution); + if (lenSq < resolveShortest.DistanceSq) { + resolveShortest.Vector = cornerResolution; + resolveShortest.Case = Corner; + } + if (canStairStepUp && cornerResolution.y > 0 && lenSq < resolveUpwards.DistanceSq) { + resolveUpwards.Vector = cornerResolution; + resolveUpwards.Case = Corner; + resolveUpwards.DistanceSq = lenSq; + } + + //Force the resolution upwards if it is smaller than the threshold verticalStepHeight. + //Else take the shortest resolution. + bool takeUp = resolveUpwards.Vector.y > 0 && resolveUpwards.Vector.y < verticalStepHeight; + Resolution& bestResolve = takeUp ? resolveUpwards : resolveShortest; + outResolution = bestResolve.Vector; + + glm::vec3 projNorm; + switch (bestResolve.Case) { + case ResolveDimY: + boxVelocity.y = 0.f; + if (outResolution.y > 0) + isOnGround = true; + case ResolveDimX: + case ResolveDimZ: + //If we get here, the resolution is along one coordinate axis. + //set velocity to 0 in y if it is along y-axis. + return true; + case Line: + projNorm = glm::normalize(outResolution); + break; + case Corner: + projNorm = triNormal; + break; + default: + break; + } + + //If the collision was not on steep wall or similarly (e.g. walking on the ground), force resolution in y only. + if (FaceIsGround(projNorm.y)) { + //Ensure that the player always is moved upwards, instead of sliding down. + float len = glm::length(outResolution); + float ang = glm::half_pi() - glm::acos(outResolution.y / len); + if (len > 0.0000001f && ang > 0.0000001f) { + outResolution.x = 0; + outResolution.y = len / glm::sin(ang); + outResolution.z = 0; + } + //Also zero the vertical velocity, if it is positive, else project it onto the normal. + //Project the velocity onto the normal of the hit line/face. + //w = v - *n, |n|==1. + boxVelocity.y = std::min(boxVelocity.y - glm::dot(boxVelocity, projNorm) * projNorm.y, 0.f); + isOnGround = true; + } else { + //Enter here if the triangle is a steep slope, and it is not facing downwards. + //Project the velocity onto the normal of the hit line/face. + //w = v - *n, |n|==1. + //"ice cream"-effect, air resistance + projected velocity. + if (!isOnGround) { + boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; + } + } + return true; +} + +bool AABBvsTriangles(const AABB& box, + const std::vector& modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix, + glm::vec3& boxVelocity, + float verticalStepHeight, + bool& isOnGround, + glm::vec3& outResolutionVector) +{ + bool hit = false; + + bool everHitTheGround = false; + AABB newBox = box; + outResolutionVector = glm::vec3(0.f); + glm::vec3 originalBoxVelocity(boxVelocity); + for (int i = 0; i < modelIndices.size(); ) { + std::array triVertices = { + Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), + Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), + Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) + }; + glm::vec3 outVec; + bool collideWithGround = isOnGround; + if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec)) { + hit = true; + outResolutionVector += outVec; + newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); + if (collideWithGround) { + everHitTheGround = isOnGround = true; + } + } + } + + if (!everHitTheGround) { + isOnGround = false; + } return hit; } -bool attachAABBComponentFromModel(World* world, EntityID id) +bool AttachAABBComponentFromModel(EntityWrapper entity) { - if (!world->HasComponent(id, "Model")) { + if (!entity.HasComponent("Model")) { return false; } - ComponentWrapper model = world->GetComponent(id, "Model"); - ComponentWrapper collision = world->AttachComponent(id, "AABB"); - Model* modelRes = ResourceManager::Load(model["Resource"]); - if (modelRes == nullptr) { + //Derive AABB from model + RawModel* model; + try { + model = ResourceManager::Load(entity["Model"]["Resource"]); + } catch (const std::exception&) { return false; } - glm::mat4 modelMatrix = modelRes->Matrix(); - - glm::vec3 mini = glm::vec3(INFINITY, INFINITY, INFINITY); - glm::vec3 maxi = glm::vec3(-INFINITY, -INFINITY, -INFINITY); + glm::vec3 mini(INFINITY); + glm::vec3 maxi(-INFINITY); + for (const auto& v : model->m_Vertices) { + mini = glm::min(mini, v.Position); for (unsigned int i = 0; i < modelRes->NumberOfVertices(); i++) { const auto& v = modelRes->Vertices()[i]; - const auto& wPos = modelMatrix * glm::vec4(v.Position.x, v.Position.y, v.Position.z, 1); - maxi.x = std::max(wPos.x, maxi.x); - maxi.y = std::max(wPos.y, maxi.y); - maxi.z = std::max(wPos.z, maxi.z); - mini.x = std::min(wPos.x, mini.x); - mini.y = std::min(wPos.y, mini.y); - mini.z = std::min(wPos.z, mini.z); } - collision["Origin"] = 0.5f * (maxi + mini); - collision["Size"] = maxi - mini; + + entity.AttachComponent("AABB"); + entity["AABB"]["Origin"] = 0.5f * (maxi + mini); + entity["AABB"]["Size"] = maxi - mini; return true; } diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 382238e7..7d8905a8 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -1,6 +1,7 @@ #include "Collision/Collision.h" #include "Collision/CollisionSystem.h" #include "Core/AABB.h" +#include "Rendering/Model.h" void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) { @@ -19,39 +20,48 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c // Collide against octree items m_OctreeResult.clear(); m_Octree->ObjectsInSameRegion(*boundingBox, m_OctreeResult); + bool everHitTheGround = false; for (auto& boxB : m_OctreeResult) { glm::vec3 resolutionVector; if (boxA.Entity == boxB.Entity) { continue; } - if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { + if (boxB.Entity.HasComponent("Model") && Collision::AABBVsAABB(boxA, boxB)) { + //Here we know boxB is a entity with Collideable, AABB, and Model. + RawModel* model; + try { + model = ResourceManager::Load(boxB.Entity["Model"]["Resource"]); + } catch (const std::exception&) { + continue; + } + + glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity); + + glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"]; + bool isOnGround = (bool)cPhysics["IsOnGround"]; + float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; + if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { + (glm::vec3&)cTransform["Position"] += resolutionVector; + cPhysics["Velocity"] = inOutVelocity; + if (isOnGround) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; + } + } + } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { + //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; if (resolutionVector.y > 0) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; } } } - // HACK: Temporarily collide against all collidable models since they're not in the octree yet - //auto otherCollidables = world->GetComponents("Model"); - //for (auto& cModel : *otherCollidables) { - // if (cModel.EntityID == entity) { - // continue; - // } - // if (!world->HasComponent(cModel.EntityID, "Collidable")) { - // continue; - // } - - // auto absPosition = RenderQueueFactory::AbsolutePosition(world, cModel.EntityID); - // auto absOrientation = RenderQueueFactory::AbsoluteOrientation(world, cModel.EntityID); - // auto absScale = RenderQueueFactory::AbsoluteScale(world, cModel.EntityID); - // glm::mat4 modelMatrix = glm::translate(absPosition); // *glm::toMat4(absOrientation) * glm::scale(absScale); - - // auto model = ResourceManager::Load(cModel["Resource"]); - // glm::vec3 resolutionVector; - // if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, resolutionVector)) { - // (glm::vec3&)cTransform["Position"] += resolutionVector; - // } - //} -} \ No newline at end of file + //This should apply air friction and such, iff zero models were hit. + if (!everHitTheGround) { + (bool)cPhysics["IsOnGround"] = false; + } +} diff --git a/src/Engine/Collision/FillOctreeSystem.cpp b/src/Engine/Collision/FillOctreeSystem.cpp new file mode 100644 index 00000000..8c03b5c2 --- /dev/null +++ b/src/Engine/Collision/FillOctreeSystem.cpp @@ -0,0 +1,20 @@ +#include "Collision/FillOctreeSystem.h" + +void FillOctreeSystem::Update(double dt) +{ + m_Octree->ClearDynamicObjects(); +} + +void FillOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +{ + if (!entity.HasComponent("AABB")) { + //Derive AABB from model. + if (!Collision::AttachAABBComponentFromModel(entity)) { + return; + } + } + boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); + if (absoluteAABB) { + m_Octree->AddDynamicObject(*absoluteAABB); + } +} \ No newline at end of file diff --git a/src/Engine/Collision/TriggerSystem.cpp b/src/Engine/Collision/TriggerSystem.cpp index 410a7fa1..adc778e5 100644 --- a/src/Engine/Collision/TriggerSystem.cpp +++ b/src/Engine/Collision/TriggerSystem.cpp @@ -6,6 +6,10 @@ void TriggerSystem::UpdateComponent(EntityWrapper& triggerEntity, ComponentWrapper& cTrigger, double dt) { // The trigger *should* have a bounding box, or something, to test against so it can be triggered. + // If it doesn't, add one as big as the model for now, then size can be modified in editor if necessary. + if (!triggerEntity.HasComponent("AABB")) { + Collision::AttachAABBComponentFromModel(triggerEntity); + } boost::optional triggerBox = Collision::EntityAbsoluteAABB(triggerEntity); if (!triggerBox) { return; diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index 071329a3..642421bc 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -16,6 +16,15 @@ bool EntityWrapper::HasComponent(const std::string& componentName) return World->HasComponent(ID, componentName); } +void EntityWrapper::AttachComponent(const char* componentName) +{ + if (!Valid()) { + LOG_WARNING("Could not attach \"%s\" component to #%i, entity is not valid.", componentName, ID); + return; + } + World->AttachComponent(ID, componentName); +} + EntityWrapper EntityWrapper::Parent() { if (this->World == nullptr || this->ID == EntityID_Invalid) { diff --git a/src/Engine/Core/Octree.cpp b/src/Engine/Core/Octree.cpp index f3cafcfc..7eee1f81 100644 --- a/src/Engine/Core/Octree.cpp +++ b/src/Engine/Core/Octree.cpp @@ -275,9 +275,4 @@ std::vector Child::childIndicesContainingBox(const AABB& box) const } } -bool Child::hasChildren() const -{ - return m_Children[0] != nullptr; -} - } \ No newline at end of file diff --git a/src/Engine/Core/Transform.cpp b/src/Engine/Core/Transform.cpp index 31b4493f..333c3532 100644 --- a/src/Engine/Core/Transform.cpp +++ b/src/Engine/Core/Transform.cpp @@ -97,3 +97,7 @@ glm::mat4 Transform::ModelMatrix(EntityID entity, World* world) return modelMatrix; } +glm::vec3 Transform::TransformPoint(const glm::vec3& point, const glm::mat4& matrix) +{ + return glm::vec3(matrix * glm::vec4(point.x, point.y, point.z, 1)); +} \ No newline at end of file diff --git a/src/Engine/Editor/EditorRenderSystem.cpp b/src/Engine/Editor/EditorRenderSystem.cpp index 4d65e9d3..c5e90865 100644 --- a/src/Engine/Editor/EditorRenderSystem.cpp +++ b/src/Engine/Editor/EditorRenderSystem.cpp @@ -56,9 +56,9 @@ void EditorRenderSystem::Update(double dt) 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); if (cModel["Transparent"]) { - scene.TransparentObjects.push_back(modelJob); + scene.Jobs.TransparentObjects.push_back(modelJob); } else { - scene.OpaqueObjects.push_back(modelJob); + scene.Jobs.OpaqueObjects.push_back(modelJob); } } } @@ -75,7 +75,7 @@ void EditorRenderSystem::Update(double dt) EntityWrapper entity(m_World, cPointLight.EntityID); ComponentWrapper& cTransform = entity["Transform"]; std::shared_ptr pointLightJob = std::make_shared(cTransform, cPointLight, entity.World); - scene.PointLightJobs.push_back(pointLightJob); + scene.Jobs.PointLight.push_back(pointLightJob); } } diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index d74a0d13..c82d614f 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -6,8 +6,6 @@ DrawColorCorrectionPass::DrawColorCorrectionPass(IRenderer* renderer) m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); - //m_Exposure = 0.4; //TODO: Renderer: Fixa så att denna går att ändra på genom komponent eller setting. - InitializeShaderPrograms(); } @@ -20,7 +18,7 @@ void DrawColorCorrectionPass::InitializeShaderPrograms() m_ColorCorrectionProgram->Link(); } -void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure) +void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure) { //glBindFramebuffer(GL_FRAMEBUFFER, 0); GLERROR("DrawScreenQuadPass::Draw: Pre"); @@ -35,6 +33,10 @@ void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLf 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 abc00b89..66f222c5 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -2,8 +2,10 @@ DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass) { + //TODO: Make sure that uniforms are not sent into shader if not needed. m_Renderer = renderer; m_LightCullingPass = lightCullingPass; + m_ShieldPixelRate = 8; InitializeTextures(); InitializeShaderPrograms(); InitializeFrameBuffers(); @@ -21,18 +23,39 @@ void DrawFinalPass::InitializeFrameBuffers() { glGenRenderbuffers(1, &m_DepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + 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); //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); //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_ATTACHMENT))); + m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&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"); } void DrawFinalPass::InitializeShaderPrograms() @@ -111,6 +134,20 @@ void DrawFinalPass::InitializeShaderPrograms() m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor"); m_ForwardPlusSplatMapSkinnedProgram->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_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"); } void DrawFinalPass::Draw(RenderScene& scene) @@ -121,20 +158,92 @@ void DrawFinalPass::Draw(RenderScene& scene) if (scene.ClearDepth) { glClear(GL_DEPTH_BUFFER_BIT); } + //TODO: Do we need check for this or will it be per scene always? + glClearStencil(0x00); + glClear(GL_STENCIL_BUFFER_BIT); - DrawModelRenderQueues(scene.OpaqueObjects, scene); + //Fill depth buffer + + + state->StencilMask(0x00); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); - DrawModelRenderQueues(scene.TransparentObjects, scene); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); GLERROR("TransparentObjects"); - delete state; + //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"); + + //Draw Opaque shielded objects + state->StencilFunc(GL_NOTEQUAL, 1, 0xFF); + state->StencilMask(0x00); + DrawShieldedModelRenderQueue(scene.Jobs.OpaqueShieldedObjects, scene); + GLERROR("Shielded Opaque object"); + + //Draw Transparen Shielded objects + DrawShieldedModelRenderQueue(scene.Jobs.TransparentShieldedObjects, scene); + GLERROR("Shielded Transparent objects"); + 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); + GLERROR("OpaqueObjects"); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); + 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() { + m_FinalPassFrameBufferLowRes.Bind(); + 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); + glClearColor(0.f, 0.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glDisable(GL_SCISSOR_TEST); + m_FinalPassFrameBufferLowRes.Unbind(); + m_FinalPassFrameBuffer.Bind(); + glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_FinalPassFrameBuffer.Unbind(); @@ -166,7 +275,7 @@ void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm: GLERROR("MipMap Texture initialization failed"); } -void DrawFinalPass::DrawModelRenderQueues(std::list>& job, RenderScene& scene) +void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); GLERROR("forwardHandle"); @@ -189,10 +298,125 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); - for(auto &job : job) + for(auto &job : jobs) { auto explosionEffectJob = std::dynamic_pointer_cast(job); if(explosionEffectJob) { + //Bind program + if(GLERROR("Prebind")) { + continue; + } + m_ExplosionEffectProgram->Bind(); + if(GLERROR("BindProgram")) { + continue; + } + + glDisable(GL_CULL_FACE); + + //Bind uniforms + BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + if(GLERROR("BindExplosionUniforms")) { + continue; + } + + if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (explosionEffectJob->Animation != nullptr) { + std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + if(GLERROR("Animation")) { + continue; + } + + //bind textures + BindExplosionTextures(explosionEffectJob); + if(GLERROR("BindExplosionTextures")) { + continue; + } + //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); + if(GLERROR("explosion effect end")) { + continue; + } + + } else { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + //bind forward program + m_ForwardPlusProgram->Bind(); + glUniform2f(glGetUniformLocation(forwardHandle, "ScreenDimensions"), m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + + //bind textures + BindModelTextures(modelJob); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + //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::DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene) +{ + m_ShieldToStencilProgram->Bind(); + GLuint shaderHandle = m_ShieldToStencilProgram->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())); + + for (auto &job : jobs) { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + + + 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(); + GLERROR("forwardHandle"); + GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); + GLERROR("explosionHandle"); + + 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()); + + for (auto &job : jobs) { + auto explosionEffectJob = std::dynamic_pointer_cast(job); + if (explosionEffectJob) { switch (explosionEffectJob->Type) { case RawModel::MaterialType::Basic: case RawModel::MaterialType::SingleTextures: @@ -331,12 +555,44 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& 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")) { + if (GLERROR("models end")) { continue; } } } } +} + + +void DrawFinalPass::DrawToDepthBuffer(std::list>& jobs, RenderScene& scene) +{ + m_FillDepthBufferProgram->Bind(); + GLuint shaderHandle = m_FillDepthBufferProgram->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())); + + for (auto &job : jobs) { + auto modelJob = std::dynamic_pointer_cast(job); + + //bind uniforms + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + //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; + } + } } diff --git a/src/Engine/Rendering/DrawFinalPassState.cpp b/src/Engine/Rendering/DrawFinalPassState.cpp index 3ebe320d..8b5ddc8b 100644 --- a/src/Engine/Rendering/DrawFinalPassState.cpp +++ b/src/Engine/Rendering/DrawFinalPassState.cpp @@ -1,6 +1,7 @@ #include "Rendering/DrawFinalPassState.h" + DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) { BindFramebuffer(frameBuffer); @@ -8,6 +9,10 @@ DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Enable(GL_DEPTH_TEST); Enable(GL_CULL_FACE); + 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)); } @@ -15,3 +20,20 @@ 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); + ClearColor(glm::vec4(0.f)); +} + +DrawStencilState::~DrawStencilState() +{ + +} + diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index 9677f50e..c0be4cb1 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -39,10 +39,13 @@ void FrameBuffer::AddResource(std::shared_ptr resource) void FrameBuffer::Generate() { + GLERROR("PRE"); + std::vector attachments; 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) { @@ -56,20 +59,30 @@ void FrameBuffer::Generate() GLERROR("FrameBuffer generate: glFramebufferRenderbuffer"); break; } - + GLERROR("2"); - if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT) { + 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); + if(GLERROR("4")) { + printf("hello"); + } if (GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { - LOG_ERROR("FrameBuffer incomplete: 0x%x\n", frameBufferStatus); + GLERROR("Framebuffer incomplete"); + //LOG_ERROR("FrameBuffer incomplete: 0x%x\n", frameBufferStatus); exit(EXIT_FAILURE); } + GLERROR("END"); + } void FrameBuffer::Bind() diff --git a/src/Engine/Rendering/LightCullingPass.cpp b/src/Engine/Rendering/LightCullingPass.cpp index 5e6da64d..0ae359db 100644 --- a/src/Engine/Rendering/LightCullingPass.cpp +++ b/src/Engine/Rendering/LightCullingPass.cpp @@ -16,7 +16,7 @@ LightCullingPass::~LightCullingPass() void LightCullingPass::GenerateNewFrustum(RenderScene& scene) { - if (scene.PointLightJobs.size() == 0) + if (scene.Jobs.PointLight.size() == 0) return; GLERROR("CalculateFrustum Error: Pre"); @@ -83,7 +83,7 @@ void LightCullingPass::FillLightList(RenderScene& scene) { m_LightSources.clear(); - for(auto &job : scene.PointLightJobs) { + for(auto &job : scene.Jobs.PointLight) { auto pointLightjob = std::dynamic_pointer_cast(job); if (pointLightjob) { LightSource p; @@ -97,7 +97,7 @@ void LightCullingPass::FillLightList(RenderScene& scene) m_LightSources.push_back(p); } } - for(auto &job : scene.DirectionalLightJobs) { + for(auto &job : scene.Jobs.DirectionalLight) { auto directionalLightJob = std::dynamic_pointer_cast(job); if(directionalLightJob) { LightSource p; diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 9842f659..795d1097 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -65,7 +65,7 @@ void PickingPass::Draw(RenderScene& scene) } m_Camera = scene.Camera; - for (auto &job : scene.OpaqueObjects) { + for (auto &job : scene.Jobs.OpaqueObjects) { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { @@ -152,7 +152,99 @@ void PickingPass::Draw(RenderScene& scene) } } - for (auto &job : scene.TransparentObjects) { + for (auto &job : scene.Jobs.TransparentObjects) { + auto modelJob = std::dynamic_pointer_cast(job); + + if (modelJob) { + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + 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())); + glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + 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))); + } + } + + for (auto &job : scene.Jobs.OpaqueShieldedObjects) { + auto modelJob = std::dynamic_pointer_cast(job); + + if (modelJob) { + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + 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())); + glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + 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))); + } + } + + for (auto &job : scene.Jobs.TransparentShieldedObjects) { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { diff --git a/src/Engine/Rendering/RenderState.cpp b/src/Engine/Rendering/RenderState.cpp index 1da2f0b1..26ba18a1 100644 --- a/src/Engine/Rendering/RenderState.cpp +++ b/src/Engine/Rendering/RenderState.cpp @@ -6,9 +6,10 @@ bool RenderState::Enable(GLenum cap) //LOG_WARNING("Trying to enable somthing that is already enabled."); return false; } + m_ResetFunctions.push_back(std::bind(glDisable, cap)); glEnable(cap); - return !GLERROR("RenderState::Enable"); + return !GLERROR("Enable"); } bool RenderState::Disable(GLenum cap) @@ -16,9 +17,10 @@ bool RenderState::Disable(GLenum cap) if (!glIsEnabled(cap)) { return false; } + m_ResetFunctions.push_back(std::bind(glEnable, cap)); glDisable(cap); - return !GLERROR("RenderState::Disable"); + return !GLERROR("Disable"); } bool RenderState::CullFace(GLenum mode) @@ -32,7 +34,7 @@ bool RenderState::CullFace(GLenum mode) glGetIntegerv(GL_CULL_FACE_MODE, &original); m_ResetFunctions.push_back(std::bind(glCullFace, original)); glCullFace(mode); - return !GLERROR("RenderState::CullFace"); + return !GLERROR("CullFace"); } bool RenderState::ClearColor(glm::vec4 color) @@ -41,7 +43,7 @@ bool RenderState::ClearColor(glm::vec4 color) glGetFloatv(GL_COLOR_CLEAR_VALUE, &original[0]); m_ResetFunctions.push_back(std::bind(glClearColor, original[0], original[1], original[2], original[3])); glClearColor(color.r, color.g, color.b, color.a); - return !GLERROR("RenderState::ClearColor"); + return !GLERROR("ClearColor"); } bool RenderState::BindFramebuffer(GLint framebuffer) @@ -55,7 +57,7 @@ bool RenderState::BindFramebuffer(GLint framebuffer) glBindFramebuffer(GL_DRAW_FRAMEBUFFER, originalDraw); }); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); - return !GLERROR("RenderState::BindBuffer"); + return !GLERROR("BindBuffer"); } @@ -67,7 +69,7 @@ bool RenderState::BlendEquation(GLenum mode) glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &originalAlpha); m_ResetFunctions.push_back(std::bind(glBlendEquationSeparate, originalRGB, originalAlpha)); glBlendEquation(mode); - return !GLERROR("RenderState::BlendEquation"); + return !GLERROR("BlendEquation"); } bool RenderState::BlendFunc(GLenum sfactor, GLenum dfactor) @@ -82,7 +84,46 @@ bool RenderState::BlendFunc(GLenum sfactor, GLenum dfactor) glGetIntegerv(GL_BLEND_DST_ALPHA, &originalDestAlpha); m_ResetFunctions.push_back(std::bind(glBlendFuncSeparate, originalSrcRGB, originalSrcAlpha, originalDestRGB, originalDestAlpha)); glBlendFunc(sfactor, dfactor); - return !GLERROR("RenderState::BlendFunc"); + return !GLERROR("BlendFunc"); +} + + +bool RenderState::StencilOp(GLenum sfail, GLenum dpfail, GLenum dppass) +{ + GLint originalSFail; + glGetIntegerv(GL_STENCIL_FAIL, &originalSFail); + GLint originalDPFail; + glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &originalDPFail); + GLint originalDPPass; + glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &originalDPPass); + m_ResetFunctions.push_back(std::bind(glStencilOp, originalSFail, originalDPFail, originalDPPass)); + glStencilOp(sfail, dpfail, dppass); + return !GLERROR("StencilOp"); +} + + +bool RenderState::StencilFunc(GLenum func, GLint ref, GLuint mask) +{ + GLint originalFunc; + glGetIntegerv(GL_STENCIL_FUNC, &originalFunc); + GLint originalRef; + glGetIntegerv(GL_STENCIL_REF, &originalRef); + GLint originalMask; + glGetIntegerv(GL_STENCIL_VALUE_MASK, &originalMask); + m_ResetFunctions.push_back(std::bind(glStencilFunc, originalFunc, originalRef, originalMask)); + glStencilFunc(func, ref, mask); + return !GLERROR("StencilFunc"); +} + + + +bool RenderState::StencilMask(GLuint mask) +{ + GLint originalMask; + glGetIntegerv(GL_STENCIL_WRITEMASK, &originalMask); + m_ResetFunctions.push_back(std::bind(glStencilMask, mask)); + glStencilMask(mask); + return !GLERROR("StencilMask"); } bool RenderState::DepthMask(GLboolean flag) @@ -91,12 +132,12 @@ bool RenderState::DepthMask(GLboolean flag) glGetBooleanv(GL_DEPTH_WRITEMASK, &original); m_ResetFunctions.push_back(std::bind(glDepthMask, original)); glDepthMask(flag); - return !GLERROR("RenderState::DepthMask"); + return !GLERROR("DepthMask"); } RenderState::~RenderState() { - for (auto& f : m_ResetFunctions) { + for (auto& f : boost::adaptors::reverse(m_ResetFunctions)) { f(); } } diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 1a3c198c..9b9b8654 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -40,7 +40,7 @@ bool RenderSystem::isChildOfCurrentCamera(EntityWrapper entity) return entity == m_CurrentCamera || entity.IsChildOf(m_CurrentCamera); } -void RenderSystem::fillModels(std::list>& opaqueJobs, std::list>& transparentJobs) +void RenderSystem::fillModels(RenderScene::Queues &Jobs) { auto models = m_World->GetComponents("Model"); if (models == nullptr) { @@ -92,7 +92,9 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, } glm::mat4 modelMatrix = Transform::ModelMatrix(cModel.EntityID, m_World); + //Loop through all materialgroups of a model for (auto matGroup : model->MaterialGroups()) { + //If the model has an explosioneffect component, we will add an explosioneffectjob if (m_World->HasComponent(cModel.EntityID, "ExplosionEffect")) { auto explosionEffectComponent = m_World->GetComponent(cModel.EntityID, "ExplosionEffect"); std::shared_ptr explosionEffectJob = std::shared_ptr(new ExplosionEffectJob( @@ -106,15 +108,35 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, fillColor, fillPercentage )); - if(explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { - cModel["Transparent"] = true; - } + if (m_World->HasComponent(cModel.EntityID, "Shield")){ + TODO Calc hash + Jobs.ShieldObjects.push_back(explosionEffectJob); + } else if (m_World->HasComponent(cModel.EntityID, "Shielded") + || m_World->HasComponent(cModel.EntityID, "Player")) { - if (cModel["Transparent"]) { - transparentJobs.push_back(explosionEffectJob); - } else { + if (explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + TODO: Calc hash + Jobs.TransparentShieldedObjects.push_back(explosionEffectJob); + } else { explosionEffectJob->CalculateHash(); - opaqueJobs.push_back(explosionEffectJob); + Jobs.OpaqueShieldedObjects.push_back(explosionEffectJob); + } + } else { + if (explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + TODO CALC HASH + Jobs.TransparentObjects.push_back(explosionEffectJob); + } else { + TODO CALC HASH + Jobs.OpaqueObjects.push_back(explosionEffectJob); + } } } else { std::shared_ptr modelJob = std::shared_ptr(new ModelJob( @@ -127,14 +149,35 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, fillColor, fillPercentage )); - if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { - cModel["Transparent"] = true; - } - if (cModel["Transparent"]) { - transparentJobs.push_back(modelJob); - } else { + if (m_World->HasComponent(cModel.EntityID, "Shield")) { + TODO: CALC HASH + Jobs.ShieldObjects.push_back(modelJob); + } else if (m_World->HasComponent(cModel.EntityID, "Shielded") + || m_World->HasComponent(cModel.EntityID, "Player")) { + + if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + TODO CALC HASH + Jobs.TransparentShieldedObjects.push_back(modelJob); + } else { modelJob->CalculateHash(); - opaqueJobs.push_back(modelJob); + Jobs.OpaqueShieldedObjects.push_back(modelJob); + } + } else { + if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + CALC HASH + Jobs.TransparentObjects.push_back(modelJob); + } else { + CALC HASH + Jobs.OpaqueObjects.push_back(modelJob); + } } } } @@ -253,11 +296,11 @@ void RenderSystem::Update(double dt) scene.AmbientColor = (glm::vec4)(*cSceneLight->begin())["AmbientColor"]; } - fillModels(scene.OpaqueObjects, scene.TransparentObjects); + fillModels(scene.Jobs); + fillPointLights(scene.Jobs.PointLight, m_World); scene.OpaqueObjects.sort(); - fillPointLights(scene.PointLightJobs, m_World); - fillDirectionalLights(scene.DirectionalLightJobs, m_World); - fillText(scene.TextJobs, m_World); + fillDirectionalLights(scene.Jobs.DirectionalLight, m_World); + fillText(scene.Jobs.Text, m_World); m_RenderFrame->Add(scene); } \ No newline at end of file diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index a63e02a0..8530b291 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -93,7 +93,7 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { - ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0Gaussian\0Picking"); + ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking"); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -120,7 +120,7 @@ void Renderer::Draw(RenderFrame& frame) } m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); if (m_DebugTextureToDraw == 0) { - m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), frame.Gamma, frame.Exposure); + m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure); } if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); @@ -129,9 +129,15 @@ void Renderer::Draw(RenderFrame& frame) m_DrawScreenQuadPass->Draw(m_DrawFinalPass->BloomTexture()); } if (m_DebugTextureToDraw == 3) { - m_DrawScreenQuadPass->Draw(m_DrawBloomPass->GaussianTexture()); + 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) { m_DrawScreenQuadPass->Draw(m_PickingPass->PickingTexture()); } @@ -154,7 +160,7 @@ void Renderer::InitializeTextures() void Renderer::SortRenderJobsByDepth(RenderScene &scene) { //Sort all forward jobs so transparency is good. - scene.TransparentObjects.sort(Renderer::DepthSort); + scene.Jobs.TransparentObjects.sort(Renderer::DepthSort); } void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) diff --git a/src/Engine/Rendering/TextPass.cpp b/src/Engine/Rendering/TextPass.cpp index 1e3d5941..9583fcfd 100644 --- a/src/Engine/Rendering/TextPass.cpp +++ b/src/Engine/Rendering/TextPass.cpp @@ -35,7 +35,7 @@ void TextPass::Draw(RenderScene& scene, FrameBuffer& frameBuffer) { GLERROR("Derp1"); TextPassState* state = new TextPassState(frameBuffer.GetHandle()); - for (auto &job : scene.TextJobs) { + for (auto &job : scene.Jobs.Text) { auto textJob = std::dynamic_pointer_cast(job); if (textJob) { diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index ad1d86d7..8272519a 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -1,5 +1,5 @@ #include "Game.h" -#include "Collision/CollidableOctreeSystem.h" +#include "Collision/FillOctreeSystem.h" #include "Collision/EntityAABB.h" #include "Collision/TriggerSystem.h" #include "Collision/CollisionSystem.h" @@ -8,8 +8,10 @@ #include "Systems/PlayerMovementSystem.h" #include "Systems/SpawnerSystem.h" #include "Systems/PlayerSpawnSystem.h" +#include "Systems/PlayerDeathSystem.h" #include "Core/EntityFileWriter.h" #include "Game/Systems/CapturePointSystem.h" +#include "Game/Systems/PickupSpawnSystem.h" #include "Game/Systems/WeaponSystem.h" #include "Rendering/AnimationSystem.h" #include "Rendering/BoneAttachmentSystem.h" @@ -89,13 +91,15 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index d26dde5f..a943e234 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -57,7 +57,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp int blueTeamPlayersStandingInside = 0; if (capturePointEntity.HasComponent("Model")) { //Now sets team color to the capturepoint, or white if it is uncaptured. - capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 1) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 1) : glm::vec4(1, 1, 1, 1); + capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 0.3) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 0.3) : glm::vec4(1, 1, 1, 0.3); } //calculate next possible capturePoint for both teams @@ -106,10 +106,10 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //colorize next possible capturepoint if (nextPossibleCapturePoint["Red"] == capturePointNumber) { - capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 1); + capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 0.3); } if (nextPossibleCapturePoint["Blue"] == capturePointNumber) { - capturePointEntity["Model"]["Color"] = glm::vec4(0, 1, 1, 1); + capturePointEntity["Model"]["Color"] = glm::vec4(0, 1, 1, 0.3); } //check how many players are standing inside and are healthy diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 9e118070..de290aa5 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -11,38 +11,6 @@ HealthSystem::HealthSystem(World* m_World, EventBroker* eventBroker) void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) { - //if entityID of health is 9 then the players ID is also 9 (player,health are connected to the same entity) - double maxHealth = (double)component["MaxHealth"]; - - //process the DeltaHealthVector and change the entitys health accordingly - for (size_t i = m_DeltaHealthVector.size(); i > 0; i--) - { - auto deltaHP = m_DeltaHealthVector[i - 1]; - //if we have a healthchange for the current player and health is greater than 0, then apply it - if (std::get<0>(deltaHP) == component.EntityID && (double)component["Health"] > 0.0f) { - //get the deltaHP value from the tuple and make sure you dont get more than maxHealth - double newHealth = std::min((double)component["Health"] + (double)std::get<1>(deltaHP), maxHealth); - component["Health"] = newHealth; - m_DeltaHealthVector.erase(m_DeltaHealthVector.begin() + i - 1); - //check if health is <= 0 - if ((double)component["Health"] <= 0.0f) { - component["Health"] = 0.0; - //publish death event - Events::PlayerDeath e; - e.PlayerID = component.EntityID; - m_EventBroker->Publish(e); - //clear the remaining hpDeltas for the dead player - for (size_t j = m_DeltaHealthVector.size(); j > 0; j--) - { - if (std::get<0>(m_DeltaHealthVector[j - 1]) == component.EntityID) - m_DeltaHealthVector.erase(m_DeltaHealthVector.begin() + j - 1); - } - //delete the player and break the loop - m_World->DeleteEntity(entity.ID); - break; - } - } - } } bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) @@ -50,18 +18,24 @@ bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) ComponentWrapper cHealth = e.Player["Health"]; double& health = cHealth["Health"]; health -= e.Damage; - + if (health <= 0.0) { - m_World->DeleteEntity(e.Player.ID); + Events::PlayerDeath ePlayerDeath; + ePlayerDeath.Player = e.Player; + m_EventBroker->Publish(ePlayerDeath); + //Note: we will delete the entity in PlayerDeathSystem } return true; } -bool HealthSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup& e) +bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e) { - //save the changed HP to a vector. it will be taken care of in UpdateComponent - m_DeltaHealthVector.push_back(std::make_tuple(e.PlayerHealedID, e.HealthAmount)); + ComponentWrapper cHealth = e.Player["Health"]; + double& health = cHealth["Health"]; + health += e.HealthAmount; + health = std::min(health, (double)cHealth["MaxHealth"]); + return true; } diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp new file mode 100644 index 00000000..e9f201c1 --- /dev/null +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -0,0 +1,66 @@ +#include "Systems/PickupSpawnSystem.h" + +PickupSpawnSystem::PickupSpawnSystem(World* m_World, EventBroker* eventBroker) + : System(m_World, eventBroker) +{ + 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); + + //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; + + //erase the current element (healthPickupPosition) + m_ETriggerTouchVector.erase(it); + break; + } + } +} + + +bool PickupSpawnSystem::OnTriggerTouch(Events::TriggerTouch& e) +{ + if (!e.Trigger.HasComponent("HealthPickup")) { + return false; + } + double healthGiven = 0.01*(double)e.Trigger["HealthPickup"]["HealthGain"] * (double)e.Entity["Health"]["MaxHealth"]; + //cant pick up healthpacks if you are already at MaxHealth + if ((double)e.Entity["Health"]["Health"] >= (double)e.Entity["Health"]["MaxHealth"]) { + return false; + } + + //personEntered = e.Entity, thingEntered = e.Trigger + Events::PlayerHealthPickup ePlayerHealthPickup; + ePlayerHealthPickup.HealthAmount = healthGiven; + ePlayerHealthPickup.Player = e.Entity; + m_EventBroker->Publish(ePlayerHealthPickup); + + //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"] }); + + //delete the healthpickup + m_World->DeleteEntity(e.Trigger.ID); + return true; +} diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp new file mode 100644 index 00000000..60c31ce5 --- /dev/null +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -0,0 +1,57 @@ +#include "Systems/PlayerDeathSystem.h" + +PlayerDeathSystem::PlayerDeathSystem(World* m_World, EventBroker* eventBroker) + : System(m_World, eventBroker) +{ + EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerDeathSystem::OnPlayerDeath); +} + +void PlayerDeathSystem::Update(double dt) +{ +} + +bool PlayerDeathSystem::OnPlayerDeath(Events::PlayerDeath& e) +{ + if (!e.Player.Valid()) { + return false; + } + + createDeathEffect(e.Player); + + // Delete player + m_World->DeleteEntity(e.Player.ID); + + return true; +} + +void PlayerDeathSystem::createDeathEffect(EntityWrapper player) +{ + //load the explosioneffect XML + auto deathEffect = ResourceManager::Load("Schema/Entities/PlayerDeathExplosionWithCamera.xml"); + EntityFileParser parser(deathEffect); + EntityID deathEffectID = parser.MergeEntities(m_World); + EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); + + //components that we need from player + auto playerCamera = player.FirstChildByName("Camera"); + auto playerEntityModel = player.FirstChildByName("PlayerModel")["Model"]; + auto playerEntityAnimation = player.FirstChildByName("PlayerModel")["Animation"]; + + //copy the data from player to explisioneffectmodel + playerEntityModel.Copy(deathEffectEW["Model"]); + playerEntityAnimation.Copy(deathEffectEW["Animation"]); + //freeze the animation + deathEffectEW["Animation"]["Speed"] = 0.0; + + //copy the models position,orientation + deathEffectEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; + deathEffectEW["Transform"]["Orientation"] = (glm::vec3)player["Transform"]["Orientation"]; + //effect,camera is relative to playersPosition + //deathEffectEW["ExplosionEffect"]["ExplosionOrigin"] = glm::vec3(0, 0, 0); + + //camera (with lifetime) behind the player + auto cam = deathEffectEW.FirstChildByName("Camera"); + Events::SetCamera eSetCamera; + eSetCamera.CameraEntity = cam; + m_EventBroker->Publish(eSetCamera); +} diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 28a45964..f022cb26 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -57,11 +57,13 @@ void PlayerMovementSystem::Update(double dt) wishSpeed = playerMovementSpeed; } glm::vec3& velocity = cPhysics["Velocity"]; - ImGui::Text("velocity: (%f, %f, %f)", velocity.x, velocity.y, velocity.z); + bool isOnGround = (bool)cPhysics["IsOnGround"]; + ImGui::Text(isOnGround ? "On ground" : "In air"); + ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); glm::vec3 groundVelocity(0.f, 0.f, 0.f); - groundVelocity.x = glm::dot(velocity, glm::vec3(1.f, 0.f, 0.f)); - groundVelocity.z = glm::dot(velocity, glm::vec3(0.f, 0.f, 1.f)); - ImGui::Text("groundVelocity: (%f, %f, %f) |%f|", groundVelocity.x, groundVelocity.y, groundVelocity.z, glm::length(wishDirection)); + groundVelocity.x = velocity.x; + groundVelocity.z = velocity.z; + ImGui::Text("groundVelocity: (%f, %f, %f) |%f|", groundVelocity.x, groundVelocity.y, groundVelocity.z, glm::length(groundVelocity)); ImGui::Text("wishDirection: (%f, %f, %f) |%f|", wishDirection.x, wishDirection.y, wishDirection.z, glm::length(wishDirection)); float currentSpeedProj = glm::dot(groundVelocity, wishDirection); float addSpeed = wishSpeed - currentSpeedProj; @@ -74,7 +76,7 @@ void PlayerMovementSystem::Update(double dt) ImGui::InputFloat("accel", &accel); static float airAccel = 0.5f; ImGui::InputFloat("airAccel", &airAccel); - float actualAccel = (velocity.y != 0) ? airAccel : accel; + float actualAccel = isOnGround ? accel : airAccel; static float surfaceFriction = 5.f; ImGui::InputFloat("surfaceFriction", &surfaceFriction); float accelerationSpeed = actualAccel * (float)dt * wishSpeed * surfaceFriction; @@ -86,13 +88,14 @@ void PlayerMovementSystem::Update(double dt) } //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() && (velocity.y == 0.f || !controller->DoubleJumping())) { + if (!controller->PlayerIsDashing() && controller->Jumping() && !controller->Crouching() && (isOnGround || !controller->DoubleJumping())) { + (bool)cPhysics["IsOnGround"] = false; if (velocity.y == 0.f) { controller->SetDoubleJumping(false); } else { controller->SetDoubleJumping(true); } - velocity.y += 4.f; + velocity.y = 4.f; } if (player.HasComponent("AABB")) { @@ -144,6 +147,7 @@ void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp ComponentWrapper& cPhysics = entity["Physics"]; glm::vec3& velocity = cPhysics["Velocity"]; + bool isOnGround = (bool)cPhysics["IsOnGround"]; // Ground friction float speed = glm::length(velocity); @@ -151,7 +155,7 @@ void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp ImGui::InputFloat("groundFriction", &groundFriction); static float airFriction = 0.f; ImGui::InputFloat("airFriction", &airFriction); - float friction = (velocity.y != 0) ? airFriction : groundFriction; + float friction = isOnGround ? groundFriction : airFriction; if (speed > 0) { float drop = speed * friction * (float)dt; float multiplier = glm::max(speed - drop, 0.f) / speed; diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 7db6e8ff..5f46cce3 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -75,7 +75,9 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) // Check if a player already exists if (m_PlayerEntities.count(e.PlayerID) != 0) { // TODO: Disallow infinite respawning here - m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID); + if (m_PlayerEntities[e.PlayerID].Valid()) { + m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID); + } } // Store the player for future reference diff --git a/src/Tests/CapturePointTest.cpp b/src/Tests/CapturePointTest.cpp index ffb01030..2c7bf430 100644 --- a/src/Tests/CapturePointTest.cpp +++ b/src/Tests/CapturePointTest.cpp @@ -255,14 +255,14 @@ void CapturePointTest::TestSetup8() } void CapturePointTest::DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject) { Events::TriggerTouch touchEvent; - touchEvent.Entity = whoDidSomething; - touchEvent.Trigger = onWhatObject; + touchEvent.Entity = EntityWrapper(m_World, whoDidSomething); + touchEvent.Trigger = EntityWrapper(m_World, onWhatObject); m_EventBroker->Publish(touchEvent); } void CapturePointTest::DoLeaveEvent(EntityID whoDidSomething, EntityID onWhatObject) { Events::TriggerLeave leaveEvent; - leaveEvent.Entity = whoDidSomething; - leaveEvent.Trigger = onWhatObject; + leaveEvent.Entity = EntityWrapper(m_World, whoDidSomething); + leaveEvent.Trigger = EntityWrapper(m_World, onWhatObject); m_EventBroker->Publish(leaveEvent); } void CapturePointTest::TestSuccess1() { diff --git a/src/Tests/CollisionTest.cpp b/src/Tests/CollisionTest.cpp index 67b6ce19..6cb6c88b 100644 --- a/src/Tests/CollisionTest.cpp +++ b/src/Tests/CollisionTest.cpp @@ -29,7 +29,7 @@ void RayTest(std::string fileName) { Ray ray(glm::vec3(-50, 0, 0), glm::vec3(1, 0, 0)); //using a - here, else we have to init the renderingsystem + //here, else we have to init the renderingsystem ResourceManager::RegisterType("RawModel"); auto unitBox = ResourceManager::Load(fileName); BOOST_REQUIRE(unitBox != nullptr); diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index bdd9ba4b..36608f8f 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -48,42 +48,38 @@ GameHealthSystemTest::GameHealthSystemTest() fp.MergeEntities(m_World); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World,m_EventBroker); + m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker); m_SystemPipeline->AddSystem(0); //The Test //create entity which has transform,player,model,health in it. i.e. is a player EntityID playerID = m_World->CreateEntity(); - ComponentWrapper transform = m_World->AttachComponent(playerID, "Transform"); - ComponentWrapper model = m_World->AttachComponent(playerID, "Model"); - model["Resource"] = "Models/Core/UnitSphere.mesh"; // 360NoScope UnitSphere ComponentWrapper player = m_World->AttachComponent(playerID, "Player"); ComponentWrapper health = m_World->AttachComponent(playerID, "Health"); healthsID = playerID; - double currentHealth = (double)m_World->GetComponent(healthsID, "Health")["Health"]; + + EntityID playerID2 = m_World->CreateEntity(); + ComponentWrapper player2 = m_World->AttachComponent(playerID2, "Player"); + ComponentWrapper health2 = m_World->AttachComponent(playerID2, "Health"); //heal player with 40 Events::PlayerHealthPickup e3; e3.HealthAmount = 40.0f; - e3.PlayerHealedID = healthsID; + e3.Player = EntityWrapper(m_World, player.EntityID); m_EventBroker->Publish(e3); + //damage player with 50 Events::PlayerDamage e; - e.DamageAmount = 50.0f; - e.PlayerDamagedID = healthsID; + e.Damage = 50.0f; + e.Player = EntityWrapper(m_World, player.EntityID); m_EventBroker->Publish(e); + //heal some other player with 40 Events::PlayerHealthPickup e2; e2.HealthAmount = 40.0f; - e2.PlayerHealedID = healthsID + 1; + e2.Player = EntityWrapper(m_World, player2.EntityID); m_EventBroker->Publish(e2); - EntityID playerID2 = m_World->CreateEntity(); - ComponentWrapper transform2 = m_World->AttachComponent(playerID2, "Transform"); - ComponentWrapper model2 = m_World->AttachComponent(playerID2, "Model"); - model2["Resource"] = "Models/Core/UnitSphere.mesh"; // 360NoScope UnitSphere - ComponentWrapper player2 = m_World->AttachComponent(playerID2, "Player"); - ComponentWrapper health2 = m_World->AttachComponent(playerID2, "Health"); //END TEST }