From a20ef0504aac7b9f1b199823a78a4559a1a66875 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 2 Mar 2016 16:58:24 +0100 Subject: [PATCH] Revert "Merge remote-tracking branch 'origin/master' into SniperSprint" This reverts commit 62653cf65df3871de00e7b5ddd0e59aa9381012a, reversing changes made to b81bb9eeead495e600517d9ec5b54d806512a398. --- assets | 2 +- include/Engine/Collision/Collision.h | 10 +- include/Engine/Collision/CollisionSystem.h | 5 +- include/Engine/Core/ComponentInfo.h | 4 +- include/Engine/Core/ComponentPool.h | 4 +- include/Engine/Core/ComponentWrapper.h | 76 +- include/Engine/Core/ECaptured.h | 3 +- include/Engine/Core/EntityWrapper.h | 6 - include/Engine/Core/MemoryPool.h | 27 +- include/Engine/Core/PerformanceTimer.h | 25 - include/Engine/Core/System.h | 2 +- include/Engine/Core/SystemPipeline.h | 13 +- include/Engine/Core/Util/Any.h | 7 +- include/Engine/Core/World.h | 3 +- .../Editor/EditorCameraInputController.h | 5 - include/Engine/Editor/EditorGUI.h | 8 - include/Engine/Editor/EditorSystem.h | 1 - include/Engine/GUI/Button.h | 165 +++ include/Engine/GUI/ButtonSystem.h | 44 - include/Engine/GUI/EButtonClicked.h | 16 - include/Engine/GUI/EButtonEnter.h | 17 + include/Engine/GUI/EButtonLeave.h | 17 + include/Engine/GUI/EButtonPress.h | 20 + include/Engine/GUI/EButtonPressed.h | 16 - include/Engine/GUI/EButtonRelease.h | 20 + include/Engine/GUI/EButtonReleased.h | 16 - include/Engine/GUI/Frame.h | 261 +++++ include/Engine/GUI/MainMenuSystem.h | 33 - include/Engine/GUI/TextureFrame.h | 112 ++ .../Engine/Input/FirstPersonInputController.h | 17 +- include/Engine/Network/Client.h | 40 +- include/Engine/Network/ESearchForServers.h | 12 - include/Engine/Network/HybridClient.h | 13 + include/Engine/Network/HybridServer.h | 12 + include/Engine/Network/MessageType.h | 3 - include/Engine/Network/NetworkClient.h | 5 +- include/Engine/Network/NetworkServer.h | 5 +- include/Engine/Network/Server.h | 18 +- include/Engine/Network/TCPClient.h | 2 +- include/Engine/Network/TCPServer.h | 14 +- include/Engine/Network/UDPClient.h | 3 +- include/Engine/Network/UDPServer.h | 7 +- include/Engine/Rendering/CubeMapPass.h | 27 - include/Engine/Rendering/DrawBloomPass.h | 25 +- .../Rendering/DrawColorCorrectionPass.h | 2 +- include/Engine/Rendering/DrawFinalPass.h | 44 +- include/Engine/Rendering/ExplosionEffectJob.h | 4 +- include/Engine/Rendering/IRenderer.h | 2 - include/Engine/Rendering/LightCullingPass.h | 1 - include/Engine/Rendering/ModelJob.h | 11 +- include/Engine/Rendering/PickingPass.h | 8 +- include/Engine/Rendering/RenderQueue.h | 2 + include/Engine/Rendering/RenderState.h | 2 - include/Engine/Rendering/Renderer.h | 21 +- include/Engine/Rendering/SSAOPass.h | 87 -- include/Engine/Rendering/SSAOPassState.h | 15 - include/Engine/Rendering/SpriteJob.h | 9 +- include/Engine/Rendering/Texture.h | 1 - .../Engine/Rendering/Util/CommonFunctions.h | 4 - include/Game/Events/EDoubleJump.h | 2 +- include/Game/Game.h | 5 +- include/Game/Systems/AmmoPickupSystem.h | 3 - include/Game/Systems/CapturePointSystem.h | 4 +- include/Game/Systems/DamageIndicatorSystem.h | 18 +- include/Game/Systems/HealthSystem.h | 5 +- include/Game/Systems/PickupSpawnSystem.h | 1 - include/Game/Systems/PlayerMovementSystem.h | 6 +- include/Game/Systems/PlayerSpawnSystem.h | 6 +- include/Game/Systems/SpawnerSystem.h | 7 +- .../Systems/Weapon/AssaultWeaponBehaviour.h | 30 +- .../Systems/Weapon/DefenderWeaponBehaviour.h | 38 - include/Game/Systems/Weapon/WeaponBehaviour.h | 173 +-- resources/DefaultConfig.ini | 47 +- resources/DefaultInput.ini | 4 +- resources/Schema/Components.xsd | 8 - resources/Schema/Components/AssaultWeapon.xml | 1 - resources/Schema/Components/AssaultWeapon.xsd | 2 - resources/Schema/Components/Button.xml | 3 - resources/Schema/Components/Button.xsd | 10 - .../Components/CapturePointGameMode.xml | 5 - .../Components/CapturePointGameMode.xsd | 18 - resources/Schema/Components/DashAbility.xml | 1 - resources/Schema/Components/DashAbility.xsd | 5 +- .../Schema/Components/DefenderWeapon.xml | 16 - .../Schema/Components/DefenderWeapon.xsd | 44 - resources/Schema/Components/DoubleJump.xml | 4 - resources/Schema/Components/DoubleJump.xsd | 16 - resources/Schema/Components/Menu.xml | 3 - resources/Schema/Components/Menu.xsd | 9 - resources/Schema/Components/Model.xml | 1 - resources/Schema/Components/Model.xsd | 3 - resources/Schema/Components/Page.xml | 4 - resources/Schema/Components/Page.xsd | 14 - resources/Schema/Components/Player.xml | 2 - resources/Schema/Components/Player.xsd | 4 - .../Schema/Components/SpriteIndicator.xml | 5 - .../Schema/Components/SpriteIndicator.xsd | 19 - resources/Schema/Components/Weapon.xml | 3 + resources/Schema/Components/Weapon.xsd | 17 + .../Schema/Components/WeaponAttachment.xml | 5 - .../Schema/Components/WeaponAttachment.xsd | 28 - resources/Schema/Entities/AmmoPickup.xml | 10 +- .../Schema/Entities/AssaultWeaponView.xml | 99 -- .../Schema/Entities/AssaultWeaponWorld.xml | 40 - resources/Schema/Entities/Button.xml | 32 - resources/Schema/Entities/DefenderShield.xml | 40 - .../Schema/Entities/DefenderWeaponView.xml | 99 -- .../Schema/Entities/DefenderWeaponViewRed.xml | 99 -- .../Schema/Entities/DefenderWeaponWorld.xml | 41 - .../Entities/DefenderWeaponWorldRed.xml | 41 - resources/Schema/Entities/GameMap.xml | 8 +- resources/Schema/Entities/HealthPickup.xml | 10 +- resources/Schema/Entities/MovementTest.xml | 253 +++- resources/Schema/Entities/Player.xml | 253 ++-- resources/Schema/Entities/PlayerRed.xml | 255 ++-- .../Schema/Entities/QualityAssurance.xml | 425 +------ resources/Schema/Entities/TestMenu.xml | 299 ----- resources/Schema/Types/Entity.xsd | 5 - resources/Schema/Types/WeaponSlotEnum.xsd | 16 - .../Shaders/DrawColorCorrection.frag.glsl | 16 +- resources/Shaders/ForwardPlus.frag.glsl | 39 +- resources/Shaders/ForwardPlus.vert.glsl | 8 +- .../Shaders/ForwardPlusShieldCheck.frag.glsl | 207 ---- .../Shaders/ForwardPlusSplatMapRGB.frag.glsl | 39 +- ...orwardPlusSplatMapRGBShieldCheck.frag.glsl | 254 ---- resources/Shaders/SSAO.frag.glsl | 109 -- resources/Shaders/SSAO.vert.glsl | 13 - resources/Shaders/SSAOViewSpaceZ.frag.glsl | 18 - resources/Shaders/Sprite.frag.glsl | 4 +- resources/Shaders/SpriteShieldCheck.frag.glsl | 41 - src/Engine/CMakeLists.txt | 2 +- src/Engine/Collision/Collision.cpp | 60 +- src/Engine/Collision/CollisionSystem.cpp | 66 +- src/Engine/Core/ComponentPool.cpp | 42 +- src/Engine/Core/EntityFilePreprocessor.cpp | 5 +- src/Engine/Core/EntityWrapper.cpp | 80 +- src/Engine/Core/PerformanceTimer.cpp | 76 -- src/Engine/Core/Util/Logging.cpp | 4 +- src/Engine/Core/World.cpp | 21 +- src/Engine/Editor/EditorGUI.cpp | 18 - src/Engine/Editor/EditorRenderSystem.cpp | 2 +- src/Engine/Editor/EditorSystem.cpp | 12 - src/Engine/GUI/ButtonSystem.cpp | 84 -- src/Engine/GUI/MainMenuSystem.cpp | 57 - src/Engine/Network/Client.cpp | 150 +-- src/Engine/Network/HybridClient.cpp | 10 + src/Engine/Network/HybridServer.cpp | 9 + src/Engine/Network/NetworkClient.cpp | 11 - src/Engine/Network/NetworkServer.cpp | 11 - src/Engine/Network/Server.cpp | 145 +-- src/Engine/Network/TCPClient.cpp | 30 +- src/Engine/Network/TCPServer.cpp | 93 +- src/Engine/Network/UDPClient.cpp | 48 +- src/Engine/Network/UDPServer.cpp | 75 +- src/Engine/Rendering/CubeMapPass.cpp | 41 - src/Engine/Rendering/DrawBloomPass.cpp | 120 +- .../Rendering/DrawColorCorrectionPass.cpp | 6 +- src/Engine/Rendering/DrawFinalPass.cpp | 1021 ++++++----------- src/Engine/Rendering/DrawFinalPassState.cpp | 15 +- src/Engine/Rendering/FrameBuffer.cpp | 46 +- src/Engine/Rendering/LightCullingPass.cpp | 28 - src/Engine/Rendering/PickingPass.cpp | 89 +- src/Engine/Rendering/PickingPassState.cpp | 7 +- src/Engine/Rendering/RenderState.cpp | 20 - src/Engine/Rendering/RenderSystem.cpp | 121 +- src/Engine/Rendering/Renderer.cpp | 106 +- src/Engine/Rendering/SSAOPass.cpp | 288 ----- src/Engine/Rendering/SSAOPassState.cpp | 16 - src/Engine/Rendering/ShaderProgram.cpp | 3 +- src/Engine/Rendering/Texture.cpp | 2 - src/Engine/Rendering/Util/CommonFunctions.cpp | 43 - src/Engine/Rendering/Util/ScreenCoords.cpp | 9 +- src/Game/Game.cpp | 33 +- .../Network/MultiplayerSnapshotFilter.cpp | 1 - src/Game/Systems/AmmoPickupSystem.cpp | 85 +- src/Game/Systems/CapturePointSystem.cpp | 57 +- src/Game/Systems/DamageIndicatorSystem.cpp | 135 +-- src/Game/Systems/HealthSystem.cpp | 2 +- src/Game/Systems/PickupSpawnSystem.cpp | 54 +- src/Game/Systems/PlayerDeathSystem.cpp | 5 +- src/Game/Systems/PlayerMovementSystem.cpp | 76 +- src/Game/Systems/PlayerSpawnSystem.cpp | 39 +- src/Game/Systems/SoundSystem.cpp | 25 +- src/Game/Systems/SpawnerSystem.cpp | 95 +- ...aviour.cpp_ => AssaultWeaponBehaviour.cpp} | 52 +- .../Weapon/DefenderWeaponBehaviour.cpp | 188 --- .../{WeaponSystem.cpp_ => WeaponSystem.cpp} | 56 +- src/Game/main.cpp | 2 - src/Tests/CapturePointTest.cpp | 2 +- src/Tests/CollisionTest.cpp | 18 +- src/Tests/HealthSystemTest.cpp | 30 +- src/Tests/HealthSystemTest.h | 5 +- src/Tests/PickupSpawnTest.cpp | 214 ---- src/Tests/PickupSpawnTest.h | 72 -- src/Tests/WorldTest.cpp | 44 - 195 files changed, 2303 insertions(+), 6805 deletions(-) delete mode 100644 include/Engine/Core/PerformanceTimer.h create mode 100644 include/Engine/GUI/Button.h delete mode 100644 include/Engine/GUI/ButtonSystem.h delete mode 100644 include/Engine/GUI/EButtonClicked.h create mode 100644 include/Engine/GUI/EButtonEnter.h create mode 100644 include/Engine/GUI/EButtonLeave.h create mode 100644 include/Engine/GUI/EButtonPress.h delete mode 100644 include/Engine/GUI/EButtonPressed.h create mode 100644 include/Engine/GUI/EButtonRelease.h delete mode 100644 include/Engine/GUI/EButtonReleased.h create mode 100644 include/Engine/GUI/Frame.h delete mode 100644 include/Engine/GUI/MainMenuSystem.h create mode 100644 include/Engine/GUI/TextureFrame.h delete mode 100644 include/Engine/Network/ESearchForServers.h create mode 100644 include/Engine/Network/HybridClient.h create mode 100644 include/Engine/Network/HybridServer.h delete mode 100644 include/Engine/Rendering/CubeMapPass.h delete mode 100644 include/Engine/Rendering/SSAOPass.h delete mode 100644 include/Engine/Rendering/SSAOPassState.h delete mode 100644 include/Game/Systems/Weapon/DefenderWeaponBehaviour.h delete mode 100644 resources/Schema/Components/Button.xml delete mode 100644 resources/Schema/Components/Button.xsd delete mode 100644 resources/Schema/Components/CapturePointGameMode.xml delete mode 100644 resources/Schema/Components/CapturePointGameMode.xsd delete mode 100755 resources/Schema/Components/DefenderWeapon.xml delete mode 100755 resources/Schema/Components/DefenderWeapon.xsd delete mode 100644 resources/Schema/Components/DoubleJump.xml delete mode 100644 resources/Schema/Components/DoubleJump.xsd delete mode 100644 resources/Schema/Components/Menu.xml delete mode 100644 resources/Schema/Components/Menu.xsd delete mode 100644 resources/Schema/Components/Page.xml delete mode 100644 resources/Schema/Components/Page.xsd delete mode 100644 resources/Schema/Components/SpriteIndicator.xml delete mode 100644 resources/Schema/Components/SpriteIndicator.xsd create mode 100644 resources/Schema/Components/Weapon.xml create mode 100644 resources/Schema/Components/Weapon.xsd delete mode 100644 resources/Schema/Components/WeaponAttachment.xml delete mode 100644 resources/Schema/Components/WeaponAttachment.xsd delete mode 100755 resources/Schema/Entities/AssaultWeaponView.xml delete mode 100755 resources/Schema/Entities/AssaultWeaponWorld.xml delete mode 100644 resources/Schema/Entities/Button.xml delete mode 100755 resources/Schema/Entities/DefenderShield.xml delete mode 100755 resources/Schema/Entities/DefenderWeaponView.xml delete mode 100755 resources/Schema/Entities/DefenderWeaponViewRed.xml delete mode 100755 resources/Schema/Entities/DefenderWeaponWorld.xml delete mode 100755 resources/Schema/Entities/DefenderWeaponWorldRed.xml delete mode 100644 resources/Schema/Entities/TestMenu.xml delete mode 100644 resources/Schema/Types/WeaponSlotEnum.xsd delete mode 100644 resources/Shaders/ForwardPlusShieldCheck.frag.glsl delete mode 100644 resources/Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl delete mode 100644 resources/Shaders/SSAO.frag.glsl delete mode 100644 resources/Shaders/SSAO.vert.glsl delete mode 100644 resources/Shaders/SSAOViewSpaceZ.frag.glsl delete mode 100644 resources/Shaders/SpriteShieldCheck.frag.glsl delete mode 100644 src/Engine/Core/PerformanceTimer.cpp delete mode 100644 src/Engine/GUI/ButtonSystem.cpp delete mode 100644 src/Engine/GUI/MainMenuSystem.cpp create mode 100644 src/Engine/Network/HybridClient.cpp create mode 100644 src/Engine/Network/HybridServer.cpp delete mode 100644 src/Engine/Network/NetworkServer.cpp delete mode 100644 src/Engine/Rendering/CubeMapPass.cpp delete mode 100644 src/Engine/Rendering/SSAOPass.cpp delete mode 100644 src/Engine/Rendering/SSAOPassState.cpp rename src/Game/Systems/Weapon/{AssaultWeaponBehaviour.cpp_ => AssaultWeaponBehaviour.cpp} (87%) delete mode 100644 src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp rename src/Game/Systems/Weapon/{WeaponSystem.cpp_ => WeaponSystem.cpp} (56%) delete mode 100644 src/Tests/PickupSpawnTest.cpp delete mode 100644 src/Tests/PickupSpawnTest.h diff --git a/assets b/assets index 10a61165..1e7adc74 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 10a611659ddaadfea6a560e707d395834855a979 +Subproject commit 1e7adc749e02144615a20a82c847d3c8df46ee3d diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 9e1a81db..546d03f5 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -78,21 +78,13 @@ bool AABBvsTriangles(const AABB& box, bool& isOnGround, glm::vec3& outResolutionVector); -//Detects collision, but does not resolve. -bool AABBvsTriangles(const AABB& box, - const RawModel::Vertex* modelVertices, - const std::vector& modelIndices, - const glm::mat4& modelMatrix); - //Return true if the boxes are intersecting. bool AABBVsAABB(const AABB& a, const AABB& b); //Return true if the boxes are intersecting. //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); -// Calculates an absolute AABB from an entity AABB component or Model component. -// if takeModelBox is true, the AABB component will be ignored and box is calculated from Model. -// if takeModelBox is false, the AABB component will be prefered, if it exists. +// Calculates an absolute AABB from an entity AABB component boost::optional EntityAbsoluteAABB(EntityWrapper& entity, bool takeModelBox = false); boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity); //Returns the first entity hit by the input ray. entitiesPotentiallyHitSorted needs to be sorted diff --git a/include/Engine/Collision/CollisionSystem.h b/include/Engine/Collision/CollisionSystem.h index 19adea35..c963e6b8 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -15,16 +15,15 @@ class CollisionSystem : public PureSystem public: CollisionSystem(SystemParams params, Octree* octree) : System(params) - , PureSystem("Physics") + , PureSystem("Collidable") , m_Octree(octree) { } - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPhysics, double dt) override; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; private: Octree* m_Octree; std::vector m_OctreeResult; - std::unordered_map m_PrevPositions; }; #endif \ No newline at end of file diff --git a/include/Engine/Core/ComponentInfo.h b/include/Engine/Core/ComponentInfo.h index 137a44d8..d9799059 100644 --- a/include/Engine/Core/ComponentInfo.h +++ b/include/Engine/Core/ComponentInfo.h @@ -2,7 +2,6 @@ #define ComponentInfo_h__ #include "../Common.h" -#include struct ComponentInfo { @@ -28,9 +27,8 @@ struct ComponentInfo std::string Name; std::unordered_map Fields; std::vector FieldsInOrder; - std::vector StringFields; unsigned int Stride = 0; - boost::shared_array Defaults = nullptr; + std::shared_ptr Defaults = nullptr; std::shared_ptr Meta = nullptr; }; diff --git a/include/Engine/Core/ComponentPool.h b/include/Engine/Core/ComponentPool.h index aedfd06b..957b8756 100644 --- a/include/Engine/Core/ComponentPool.h +++ b/include/Engine/Core/ComponentPool.h @@ -1,7 +1,6 @@ #ifndef ComponentPool_h__ #define ComponentPool_h__ -#include #include "MemoryPool.h" #include "ComponentInfo.h" #include "ComponentWrapper.h" @@ -46,8 +45,7 @@ public: : m_ComponentInfo(ci) , m_Pool(ci.Meta->Allocation, sizeof(EntityID) + ci.Stride) { } - ~ComponentPool(); - ComponentPool(const ComponentPool& other); + ComponentPool(const ComponentPool& other) = delete; ComponentPool(const ComponentPool&& other) = delete; const ::ComponentInfo& ComponentInfo() const { return m_ComponentInfo; } diff --git a/include/Engine/Core/ComponentWrapper.h b/include/Engine/Core/ComponentWrapper.h index 7897e874..0b9f7357 100644 --- a/include/Engine/Core/ComponentWrapper.h +++ b/include/Engine/Core/ComponentWrapper.h @@ -2,29 +2,11 @@ #define ComponentWrapper_h__ #include -#include #include "../Common.h" #include "Entity.h" #include "ComponentInfo.h" #include "Util/Any.h" -template -struct ComponentField { }; - -template -struct ComponentField::value>::type> -{ - static T& Get(const ComponentInfo::Field_t& info, char* data) { return *reinterpret_cast(data); } - static void Set(const ComponentInfo::Field_t& info, char* data, const T& value) { Get(data) = value; } -}; - -template <> -struct ComponentField -{ - static std::string& Get(const ComponentInfo::Field_t& info, char* data) { return **reinterpret_cast(data); } - static void Set(const ComponentInfo::Field_t& info, char* data, const std::string& value) { Get(info, data) = value; } -}; - struct ComponentWrapper { ComponentWrapper(const ComponentInfo& componentInfo, char* data) @@ -65,31 +47,7 @@ struct ComponentWrapper void Copy(ComponentWrapper& destination) { - // Copy trivial data - memcpy(destination.Data, Data, Info.Stride); - // Duplicate strings - SolidifyStrings(destination); - } - - // When component data has been copied, strings need to be reconstructed or they'll refer to the same data! - static void SolidifyStrings(ComponentWrapper& component) - { - for (auto& name : component.Info.StringFields) { - std::size_t offset = component.Info.Fields.at(name).Offset; - std::string value = *reinterpret_cast(component.Data + offset); - new (component.Data + offset) std::string(value); - } - } - - // This needs to be called to properly free component data, because strings. - static void Destroy(ComponentInfo info, char* data) - { - // Call std::string destructors - for (auto& name : info.StringFields) { - std::size_t offset = info.Fields.at(name).Offset; - auto field = reinterpret_cast(data + offset); - field->~basic_string(); - } + memcpy(destination.Data, this->Data, Info.Stride); } struct SubscriptProxy @@ -144,38 +102,26 @@ public: ComponentWrapperFactory(std::string componentTypeName, unsigned int allocation = 0) { m_ComponentInfo.Name = componentTypeName; - m_ComponentInfo.Meta = std::make_shared(); m_ComponentInfo.Meta->Allocation = allocation; } template void AddProperty(std::string fieldName, T defaultValue) { - auto& field = m_ComponentInfo.Fields[fieldName]; - field.Name = fieldName; - field.Type = typeid(T).name(); - field.Offset = m_ComponentInfo.Stride; - field.Stride = sizeof(T); - m_ComponentInfo.FieldsInOrder.push_back(field.Name); - if (field.Type == typeid(std::string).name()) { - field.Type = "string"; - m_ComponentInfo.StringFields.push_back(field.Name); - } + m_DefaultValues.push_back(defaultValue); + m_ComponentInfo.Fields[fieldName].Type = typeid(T).name(); + m_ComponentInfo.Fields[fieldName].Offset = m_ComponentInfo.Stride; + m_ComponentInfo.Fields[fieldName].Stride = sizeof(T); m_ComponentInfo.Stride += sizeof(T); - m_DefaultValues.push_back(std::make_pair(field, defaultValue)); } - + ComponentInfo& Finalize() { - m_ComponentInfo.Defaults = boost::shared_array(new char[m_ComponentInfo.Stride]); + m_ComponentInfo.Defaults = std::shared_ptr(new char[m_ComponentInfo.Stride]); std::size_t offset = 0; - for (auto& pair : m_DefaultValues) { - if (pair.first.Type == "string") { - new (m_ComponentInfo.Defaults.get() + offset) std::string(*reinterpret_cast(pair.second.Data.get())); - } else { - memcpy(m_ComponentInfo.Defaults.get() + offset, pair.second.Data.get(), pair.second.Size); - } - offset += pair.second.Size; + for (auto& val : m_DefaultValues) { + memcpy(m_ComponentInfo.Defaults.get() + offset, val.Data.get(), val.Size); + offset += val.Size; } return m_ComponentInfo; @@ -185,7 +131,7 @@ public: private: ComponentInfo m_ComponentInfo; - std::vector> m_DefaultValues; + std::vector m_DefaultValues; }; #endif diff --git a/include/Engine/Core/ECaptured.h b/include/Engine/Core/ECaptured.h index 48771cd7..d891c7b0 100644 --- a/include/Engine/Core/ECaptured.h +++ b/include/Engine/Core/ECaptured.h @@ -12,8 +12,7 @@ namespace Events struct Captured : Event { int TeamNumberThatCapturedCapturePoint; - EntityID CapturePointTakenID; - EntityWrapper NextCapturePoint; + EntityID CapturePointID; }; } diff --git a/include/Engine/Core/EntityWrapper.h b/include/Engine/Core/EntityWrapper.h index 8ece8e59..b0e65d9e 100644 --- a/include/Engine/Core/EntityWrapper.h +++ b/include/Engine/Core/EntityWrapper.h @@ -29,22 +29,16 @@ struct EntityWrapper EntityWrapper Parent(); EntityWrapper FirstChildByName(const std::string& name); EntityWrapper FirstParentWithComponent(const std::string& componentType); - EntityWrapper Clone(EntityWrapper parent = EntityWrapper::Invalid); - std::vector ChildrenWithComponent(const std::string& componentType); - void DeleteChildren(); bool IsChildOf(EntityWrapper potentialParent); bool Valid() const; ComponentWrapper operator[](const char* componentName); - ComponentWrapper operator[](const std::string& componentName); bool operator==(const EntityWrapper& e) const; bool operator!=(const EntityWrapper& e) const; explicit operator EntityID() const; private: EntityWrapper firstChildByNameRecursive(const std::string& name, EntityID parent); - EntityWrapper cloneRecursive(EntityWrapper entity, EntityWrapper parent); - void childrenWithComponentRecursive(const std::string& componentType, EntityWrapper& entity, std::vector& childrenWithComponent); }; namespace std diff --git a/include/Engine/Core/MemoryPool.h b/include/Engine/Core/MemoryPool.h index 053e75aa..f4073294 100644 --- a/include/Engine/Core/MemoryPool.h +++ b/include/Engine/Core/MemoryPool.h @@ -66,25 +66,9 @@ public: , m_LowestAllocatedSlot(m_NumSlots) { } - MemoryPool(const MemoryPool& other) - : m_StartAddress(new char[other.m_NumSlots*other.m_Stride]) - , m_SlotIsAllocated(other.m_SlotIsAllocated) - , m_ExtraMemory() - , m_NumSlots(other.m_NumSlots) - , m_LowestAllocatedSlot(other.m_LowestAllocatedSlot) - , m_NumAllocatedSlots(other.m_NumAllocatedSlots) - , m_Stride(other.m_Stride) - , m_CurrentAllocSlot(other.m_CurrentAllocSlot) - { - // Copy statically allocated pool - memcpy(m_StartAddress, other.m_StartAddress, m_NumSlots*m_Stride); - // Copy dynamically allocated memory - for (char* otherAddr : other.m_ExtraMemory) { - char* addr = (char*)malloc(m_Stride); - memcpy(addr, otherAddr, m_Stride); - m_ExtraMemory.push_back(addr); - } - } + //We may get problems with memory being released + //prematurely, etc. if we allow copies. + MemoryPool(const MemoryPool& other) = delete; MemoryPool(const MemoryPool&& other) = delete; //Free all memory that has been allocated. @@ -94,9 +78,8 @@ public: delete[] m_StartAddress; m_StartAddress = nullptr; } - for (char* addr : m_ExtraMemory) { - free(addr); - } + for (char* addr : m_ExtraMemory) + free(addr); m_ExtraMemory.clear(); } diff --git a/include/Engine/Core/PerformanceTimer.h b/include/Engine/Core/PerformanceTimer.h deleted file mode 100644 index a3cdfa92..00000000 --- a/include/Engine/Core/PerformanceTimer.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef PerformanceTimer_h__ -#define PerformanceTimer_h__ - -#include "../Common.h" -#include -using boost::timer::cpu_timer; - -class PerformanceTimer -{ -public: - static void StartTimer(std::string nameOfTimer); - static void StartTimerAndStopPrevious(std::string nameOfTimer); - static void StopTimer(std::string nameOfTimer); - static void SetFrameNumber(int frameNumber); - - static void ResetAllTimers(); - static void CreateExcelData(); - -private: - static std::map timers; - static cpu_timer m_Timer; - static std::string currentTimerRunning; -}; - -#endif diff --git a/include/Engine/Core/System.h b/include/Engine/Core/System.h index 23d5f9a5..1a387855 100644 --- a/include/Engine/Core/System.h +++ b/include/Engine/Core/System.h @@ -68,7 +68,7 @@ protected: const std::string m_ComponentType; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) = 0; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) = 0; }; class ImpureSystem : public virtual System diff --git a/include/Engine/Core/SystemPipeline.h b/include/Engine/Core/SystemPipeline.h index c4801fde..5f7aee0b 100644 --- a/include/Engine/Core/SystemPipeline.h +++ b/include/Engine/Core/SystemPipeline.h @@ -6,7 +6,6 @@ #include "System.h" #include "World.h" #include "EPause.h" -#include "PerformanceTimer.h" class SystemPipeline { @@ -73,10 +72,7 @@ public: // Update for (auto& system : group.ImpureSystems) { - auto className = (std::string)typeid(*system).name(); - PerformanceTimer::StartTimer(className); system->Update(dt); - PerformanceTimer::StopTimer(className); } for (auto& pair : group.PureSystems) { const std::string& componentName = pair.first; @@ -87,10 +83,7 @@ public: } for (auto& component : *pool) { for (auto& system : systems) { - auto className = (std::string)typeid(*system).name(); - PerformanceTimer::StartTimer(className); system->UpdateComponent(EntityWrapper(m_World, component.EntityID), component, dt); - PerformanceTimer::StopTimer(className); } } } @@ -113,9 +106,9 @@ private: std::vector m_OrderedSystemGroups; EventRelay m_EPause; - bool OnPause(const Events::Pause& e) { - if (e.World == m_World) { - m_Paused = true; + bool OnPause(const Events::Pause& e) { + if (e.World == m_World) { + m_Paused = true; } return true; } diff --git a/include/Engine/Core/Util/Any.h b/include/Engine/Core/Util/Any.h index e7b93dfb..f0f90737 100644 --- a/include/Engine/Core/Util/Any.h +++ b/include/Engine/Core/Util/Any.h @@ -2,7 +2,6 @@ #define Util_Any_h__ #include -#include struct Any { @@ -11,7 +10,7 @@ struct Any template Any(const T& value) { - Data = boost::shared_array(new char[sizeof(T)]); + Data = std::shared_ptr(new char[sizeof(T)]); Size = sizeof(T); memcpy(Data.get(), &value, Size); } @@ -19,7 +18,7 @@ struct Any template Any(T&& value) { - Data = boost::shared_array(new char[sizeof(T)]); + Data = std::shared_ptr(new char[sizeof(T)]); Size = sizeof(T); memcpy(Data.get(), &value, Size); } @@ -36,7 +35,7 @@ struct Any return Any(value); } - boost::shared_array Data = nullptr; + std::shared_ptr Data = nullptr; std::size_t Size = 0; }; diff --git a/include/Engine/Core/World.h b/include/Engine/Core/World.h index c9f738ce..35394b9f 100644 --- a/include/Engine/Core/World.h +++ b/include/Engine/Core/World.h @@ -15,7 +15,6 @@ public: : m_EventBroker(eventBroker) { } ~World(); - World(const World& other); // Create empty entity EntityID CreateEntity(EntityID parent = 0); @@ -40,7 +39,7 @@ public: // Change the parent of an entity void SetParent(EntityID entity, EntityID parent); // Get children of an entity - const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetDirectChildren(EntityID entity); + const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetChildren(EntityID entity); // Get all component pools const std::unordered_map& GetComponentPools() const { return m_ComponentPools; } // Get the entity children map diff --git a/include/Engine/Editor/EditorCameraInputController.h b/include/Engine/Editor/EditorCameraInputController.h index 6cb31d99..4c139e01 100644 --- a/include/Engine/Editor/EditorCameraInputController.h +++ b/include/Engine/Editor/EditorCameraInputController.h @@ -104,11 +104,6 @@ protected: if (!m_Enabled) { return false; } - - ImGuiIO& io = ImGui::GetIO(); - if (io.WantCaptureMouse || io.WantCaptureKeyboard) { - return false; - } m_SpeedMultiplier += e.DeltaY * (0.1 * m_SpeedMultiplier); m_Config->Set("Editor.CameraSpeed", m_SpeedMultiplier); diff --git a/include/Engine/Editor/EditorGUI.h b/include/Engine/Editor/EditorGUI.h index 57574e66..7a0289c6 100644 --- a/include/Engine/Editor/EditorGUI.h +++ b/include/Engine/Editor/EditorGUI.h @@ -73,12 +73,6 @@ public: // Called when the user means to rename an entity. typedef std::function OnEntityChangeName_t; void SetEntityChangeNameCallback(OnEntityChangeName_t f) { m_OnEntityChangeName = f; } - // Called when the user pastes an entity previously "copied" - // @param EntityWrapper The entity to copy - // @param EntityWrapper The entity to parent the new copy to - // @return The new copy of the entity - typedef std::function OnEntityPaste_t; - void SetEntityPasteCallback(OnEntityPaste_t f) { m_OnEntityPaste = f; } // Called when the user means to attach a new component to an entity. typedef std::function OnComponentAttach_t; void SetComponentAttachCallback(OnComponentAttach_t f) { m_OnComponentAttach = f; } @@ -117,7 +111,6 @@ private: std::string m_DroppedFile = ""; bool m_Paused = false; bool m_MouseLocked = false; - EntityWrapper m_CopyTarget = EntityWrapper::Invalid; // Callbacks OnEntitySelectedCallback_t m_OnEntitySelected = nullptr; @@ -131,7 +124,6 @@ private: OnComponentDelete_t m_OnComponentDelete = nullptr; OnWidgetMode_t m_OnWidgetMode = nullptr; OnWidgetSpace_t m_OnWidgetSpace = nullptr; - OnEntityPaste_t m_OnEntityPaste = nullptr; // Events EventRelay m_EKeyDown; diff --git a/include/Engine/Editor/EditorSystem.h b/include/Engine/Editor/EditorSystem.h index 06ee53b6..fcaa2e47 100644 --- a/include/Engine/Editor/EditorSystem.h +++ b/include/Engine/Editor/EditorSystem.h @@ -56,7 +56,6 @@ private: void OnEntityDelete(EntityWrapper entity); void OnEntityChangeParent(EntityWrapper entity, EntityWrapper parent); void OnEntityChangeName(EntityWrapper entity, const std::string& name); - EntityWrapper OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent); void OnComponentAttach(EntityWrapper entity, const std::string& componentType); void OnComponentDelete(EntityWrapper entity, const std::string& componentType); void OnWidgetSpace(EditorGUI::WidgetSpace widgetSpace); diff --git a/include/Engine/GUI/Button.h b/include/Engine/GUI/Button.h new file mode 100644 index 00000000..80845cb7 --- /dev/null +++ b/include/Engine/GUI/Button.h @@ -0,0 +1,165 @@ +#ifndef GUI_BUTTON_H__ +#define GUI_BUTTON_H__ + +#include "GUI/TextureFrame.h" +#include "GUI/EButtonEnter.h" +#include "GUI/EButtonLeave.h" +#include "GUI/EButtonPress.h" +#include "GUI/EButtonRelease.h" +#include "Core/EMouseMove.h" +#include "Core/EMousePress.h" +#include "Core/EMouseRelease.h" + +namespace dd +{ +namespace GUI +{ + +class Button : public TextureFrame +{ +public: + Button(Frame* parent, std::string name) + : TextureFrame(parent, name) + { + EVENT_SUBSCRIBE_MEMBER(m_EMouseMove, &Button::OnMouseMove); + EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &Button::OnMousePress); + EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &Button::OnMouseRelease); + } + + void SetTextureHover(std::string resourceName) + { + m_TextureHover = resourceName; + } + void SetTextureReleased(std::string resourceName) + { + m_TextureReleased = resourceName; + SetTexture(resourceName); + } + void SetTexturePressed(std::string resourceName) + { + m_TexturePressed = resourceName; + } + + void Draw(RenderScene& rq) override + { + if (m_Texture == nullptr && !m_TextureReleased.empty()) { + SetTexture(m_TextureReleased); + } + + TextureFrame::Draw(rq); + } + + virtual void OnEnter() { } + virtual void OnLeave() { } + virtual void OnPress() { } + virtual void OnRelease() { } + +protected: + bool m_MouseIsOver = false; + bool m_IsDown = false; + + virtual bool OnMouseMove(const Events::MouseMove& event) + { + if (Hidden()) { + return false; + } + + bool isOver = Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1)); + if (isOver && !m_MouseIsOver) { // Enter + if (!m_IsDown) { + if (!m_TextureHover.empty()) { + SetTexture(m_TextureHover); + } + } + OnEnter(); + Events::ButtonEnter e; + e.FrameName = m_Name; + EventBroker->Publish(e); + Events::PlaySound soundEvent; + soundEvent.FilePath = "Sounds/GUI/hover-n.wav"; + EventBroker->Publish(soundEvent); + + } else if (!isOver && m_MouseIsOver) { // Leave + if (!m_IsDown) { + if (!m_TextureReleased.empty()) { + SetTexture(m_TextureReleased); + } + } + OnLeave(); + Events::ButtonLeave e; + e.FrameName = m_Name; + EventBroker->Publish(e); + } + m_MouseIsOver = isOver; + + return true; + } + virtual bool OnMousePress(const Events::MousePress& event) + { + if (Hidden()) { + //LOG_DEBUG("Pressed hidden button"); + return false; + } + + if (!Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1))) { + return false; + } + + if (!m_TexturePressed.empty()) { + SetTexture(m_TexturePressed); + } + + m_IsDown = true; + OnPress(); + Events::ButtonPress e; + e.FrameName = m_Name; + e.Button = this; + EventBroker->Publish(e); + + return true; + } + virtual bool OnMouseRelease(const Events::MouseRelease& event) + { + if (Hidden()) { + //LOG_DEBUG("Released hidden button"); + return false; + } + + bool isOver = Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1)); + if (!isOver && !m_IsDown) { + return false; + } + + if (m_MouseIsOver) { + if (!m_TextureHover.empty()) { + SetTexture(m_TextureHover); + } + } else { + if (!m_TextureReleased.empty()) { + SetTexture(m_TextureReleased); + } + } + + m_IsDown = false; + OnRelease(); + Events::ButtonRelease e; + e.FrameName = m_Name; + e.Button = this; + EventBroker->Publish(e); + + return true; + } + +private: + EventRelay m_EMouseMove; + EventRelay m_EMousePress; + EventRelay m_EMouseRelease; + + std::string m_TextureHover; + std::string m_TexturePressed; + std::string m_TextureReleased; +}; + +} +} +#endif diff --git a/include/Engine/GUI/ButtonSystem.h b/include/Engine/GUI/ButtonSystem.h deleted file mode 100644 index 7dfe6b48..00000000 --- a/include/Engine/GUI/ButtonSystem.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef ButtonSystem_h__ -#define ButtonSystem_h__ - -#include "../Rendering/IRenderer.h" -#include "../Core/ConfigFile.h" -#include "../Rendering/PickingPass.h" -#include "../Core/ResourceManager.h" -#include "../Core/System.h" -#include "../Core/Event.h" -#include "../Core/EMousePress.h" -#include "../Core/EMouseRelease.h" -#include "../Core/ELockMouse.h" - -#include "EButtonPressed.h" -#include "EButtonReleased.h" -#include "EButtonClicked.h" - - -class ButtonSystem : public PureSystem -{ -public: - ButtonSystem(SystemParams params, IRenderer* renderer); - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; -private: - IRenderer* m_Renderer; - bool m_MouseIsLocked = false; - - EntityWrapper m_PickEntity = EntityWrapper::Invalid; - PickData m_PickData; - - EventRelay m_EMouseLock; - bool OnMouseLock(const Events::LockMouse& e); - EventRelay m_EMouseUnlock; - bool OnMouseUnlock(const Events::UnlockMouse& e); - - EventRelay m_EMousePress; - bool OnMousePress(const Events::MousePress& e); - EventRelay m_EMouseRelease; - bool OnMouseRelease(const Events::MouseRelease& e); -}; - - - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonClicked.h b/include/Engine/GUI/EButtonClicked.h deleted file mode 100644 index e4fe7abe..00000000 --- a/include/Engine/GUI/EButtonClicked.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef Events_ButtonClicked_h__ -#define Events_ButtonClicked_h__ - -#include "Core/Event.h" - -namespace Events -{ - -struct ButtonClicked : public Event { - std::string EntityName; - EntityWrapper Entity; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonEnter.h b/include/Engine/GUI/EButtonEnter.h new file mode 100644 index 00000000..13a78383 --- /dev/null +++ b/include/Engine/GUI/EButtonEnter.h @@ -0,0 +1,17 @@ +#ifndef Events_ButtonEnter_h__ +#define Events_ButtonEnter_h__ + +#include "../Core/EventBroker.h" + +namespace Events +{ + +/** Thrown on GUI button hover. */ +struct ButtonEnter : Event +{ + std::string FrameName; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonLeave.h b/include/Engine/GUI/EButtonLeave.h new file mode 100644 index 00000000..789e5aec --- /dev/null +++ b/include/Engine/GUI/EButtonLeave.h @@ -0,0 +1,17 @@ +#ifndef Events_ButtonLeave_h__ +#define Events_ButtonLeave_h__ + +#include "../Core/EventBroker.h" + +namespace Events +{ + +/** Thrown on GUI button hover. */ +struct ButtonLeave : Event +{ + std::string FrameName; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonPress.h b/include/Engine/GUI/EButtonPress.h new file mode 100644 index 00000000..6f925b2b --- /dev/null +++ b/include/Engine/GUI/EButtonPress.h @@ -0,0 +1,20 @@ +#ifndef Events_ButtonPress_h__ +#define Events_ButtonPress_h__ + +#include "../Core/EventBroker.h" + +namespace GUI { class Button; } + +namespace Events +{ + +/** Thrown on GUI button press. */ +struct ButtonPress : Event +{ + std::string FrameName; + GUI::Button* Button; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonPressed.h b/include/Engine/GUI/EButtonPressed.h deleted file mode 100644 index 3615ac8a..00000000 --- a/include/Engine/GUI/EButtonPressed.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef Events_ButtonPressed_h__ -#define Events_ButtonPressed_h__ - -#include "Core/Event.h" - -namespace Events -{ - -struct ButtonPressed : public Event { - std::string EntityName; - EntityWrapper Entity; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonRelease.h b/include/Engine/GUI/EButtonRelease.h new file mode 100644 index 00000000..d13a8ad6 --- /dev/null +++ b/include/Engine/GUI/EButtonRelease.h @@ -0,0 +1,20 @@ +#ifndef Events_ButtonRelease_h__ +#define Events_ButtonRelease_h__ + +#include "../Core/EventBroker.h" + +namespace GUI { class Button; } + +namespace Events +{ + +/** Thrown on GUI button release. */ +struct ButtonRelease : Event +{ + std::string FrameName; + GUI::Button* Button; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonReleased.h b/include/Engine/GUI/EButtonReleased.h deleted file mode 100644 index ecd8dde2..00000000 --- a/include/Engine/GUI/EButtonReleased.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef Events_ButtonReleased_h__ -#define Events_ButtonReleased_h__ - -#include "Core/Event.h" - -namespace Events -{ - -struct ButtonReleased : public Event { - std::string EntityName; - EntityWrapper Entity; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/Frame.h b/include/Engine/GUI/Frame.h new file mode 100644 index 00000000..4c5f2eb9 --- /dev/null +++ b/include/Engine/GUI/Frame.h @@ -0,0 +1,261 @@ +#ifndef GUI_Frame_h__ +#define GUI_Frame_h__ + +#include "../Common.h" +#include "../Core/Util/Rectangle.h" +#include "../Core/EventBroker.h" +#include "../Core/EKeyDown.h" +#include "../Core/EKeyUp.h" +#include "../Core/ResourceManager.h" +#include "../Rendering/RenderQueue.h" +#include "../Rendering/Texture.h" +#include "../Input/EInputCommand.h" + +namespace GUI +{ + +class Frame : public Rectangle +{ +public: + enum class Anchor + { + Left, + Right, + Top, + Bottom + }; + + static const int BaseWidth = 1280; + static const int BaseHeight = 720; + + // Set up a base frame with an event broker + Frame(EventBroker* eventBroker) + : m_EventBroker(eventBroker) + , BaseFrame(this) + , m_Name("UIParent") + , Rectangle() { } + + // Create a frame as a child + Frame(Frame* parent, std::string name) + : m_Name(name) + { + SetParent(parent); + Width = parent->Width; + Height = parent->Height; + EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &Frame::OnKeyDown); + EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &Frame::OnKeyUp); + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Frame::OnCommand); + } + + ~Frame() + { + /*for (auto layer : m_Children) + { + for (auto child : layer.second) + { + delete child.second; + } + } + + if (m_Parent) + { + m_Parent->RemoveChild(this); + }*/ + } + + Frame* Parent() const { return m_Parent; } + + void SetParent(Frame* parent) + { + if (parent == nullptr) { + LOG_ERROR("Failed to parent frame \"%s\": Invalid parent", m_Name.c_str()); + return; + } + + m_Layer = parent->Layer() + 1; + parent->AddChild(this); + m_Parent = parent; + m_EventBroker = parent->m_EventBroker; + BaseFrame = parent->BaseFrame; + } + + void AddChild(Frame* child) + { + m_Children[child->m_Layer].insert(std::make_pair(child->Name(), child)); + if (m_Parent) { + m_Parent->AddChild(child); + } + } + + void RemoveChild(Frame* child) + { + auto it = m_Children.find(child->m_Layer); + if (it != m_Children.end()) { + m_Children.erase(it); + } + + if (m_Parent) { + m_Parent->RemoveChild(child); + } + } + + std::string Name() const { return m_Name; } + void SetName(std::string val) { m_Name = val; } + + int Layer() const { return m_Layer; } + + bool Hidden() const + { + if (m_Parent) + return m_Parent->Hidden() || m_Hidden; + else + return m_Hidden; + } + bool Visible() const + { + return !Hidden(); + } + + virtual void Hide() { m_Hidden = true; } + virtual void Show() { m_Hidden = false; } + + int Left() const override + { + if (m_Parent) + return m_Parent->Left() + X; + else + return X; + } + void SetLeft(int absLeft) override + { + if (m_Parent) { + X = absLeft - m_Parent->Left(); + } else { + X = absLeft; + } + } + int Right() const override + { + return Left() + Width; + } + void SetRight(int absRight) override + { + if (m_Parent) { + X = absRight - Width - m_Parent->Left(); + } else { + X = absRight - Width; + } + } + int Top() const override + { + if (m_Parent) + return m_Parent->Top() + Y; + else + return Y; + } + void SetTop(int absTop) override + { + if (m_Parent) { + Y = absTop - m_Parent->Top(); + } else { + Y = absTop; + } + } + int Bottom() const override + { + return Top() + Height; + } + void SetBottom(int absBottom) override + { + if (m_Parent) { + Y = absBottom - Height - m_Parent->Top(); + } else { + Y = absBottom - Height; + } + } + + glm::vec2 Scale() + { + if (m_Parent) + return m_Parent->Scale(); + else + return glm::vec2(Width, Height) / glm::vec2(BaseWidth, BaseHeight); + } + + Rectangle AbsoluteRectangle() + { + int left = Left(); + if (m_Parent) + left = std::max(left, m_Parent->Left()); + int top = Top(); + if (m_Parent) + top = std::max(top, m_Parent->Top()); + int width = Right() - left; + int height = Bottom() - top; + return Rectangle(left, top, width, height); + } + + void UpdateLayered(double dt) + { + // Update ourselves + this->Update(dt); + + // Update children + for (auto& pairLayer : m_Children) { + auto children = pairLayer.second; + for (auto& pairChild : children) { + auto child = pairChild.second; + child->Update(dt); + } + } + } + + virtual void Update(double dt) { } + + void DrawLayered(RenderScene& rq) + { + if (this->Hidden()) + return; + + // Draw ourselves + this->Draw(rq); + + // Draw children + for (auto& pairLayer : m_Children) { + auto children = pairLayer.second; + for (auto& pairChild : children) { + auto child = pairChild.second; + if (child->Hidden()) + continue; + child->Draw(rq); + } + } + } + + virtual void Draw(RenderScene& rq) { } + +protected: + ::EventBroker* m_EventBroker; + Frame* BaseFrame = nullptr; + + std::string m_Name = "Unnamed"; + int m_Layer = 0; + bool m_Hidden = false; + + Frame* m_Parent = nullptr; + typedef std::multimap Children_t; // name -> frame + std::map m_Children; // layer -> Children_t + + virtual bool OnKeyDown(const Events::KeyDown& event) { return false; } + virtual bool OnKeyUp(const Events::KeyUp& event) { return false; } + virtual bool OnCommand(const Events::InputCommand& event) { return false; } + +private: + EventRelay m_EKeyDown; + EventRelay m_EKeyUp; + EventRelay m_EInputCommand; +}; + +} + +#endif diff --git a/include/Engine/GUI/MainMenuSystem.h b/include/Engine/GUI/MainMenuSystem.h deleted file mode 100644 index ba69ff0d..00000000 --- a/include/Engine/GUI/MainMenuSystem.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef MainMenuSystem_h__ -#define MainMenuSystem_h__ - -#include "../Core/System.h" -#include "../Rendering/IRenderer.h" -#include "../Core/ResourceManager.h" -#include "../Core/Event.h" - - -#include "EButtonClicked.h" -#include "EButtonPressed.h" -#include "EButtonReleased.h" - - -class MainMenuSystem : public ImpureSystem -{ -public: - MainMenuSystem(SystemParams params, IRenderer* renderer); - virtual void Update(double dt) override; - -private: - IRenderer* m_Renderer; - - EventRelay m_EClicked; - bool OnButtonClick(const Events::ButtonClicked& e); - EventRelay m_EReleased; - bool OnButtonRelease(const Events::ButtonReleased& e); - EventRelay m_EPressed; - bool OnButtonPress(const Events::ButtonPressed& e); - -}; - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/TextureFrame.h b/include/Engine/GUI/TextureFrame.h new file mode 100644 index 00000000..77967b4d --- /dev/null +++ b/include/Engine/GUI/TextureFrame.h @@ -0,0 +1,112 @@ +#ifndef GUI_TextureFrame_h__ +#define GUI_TextureFrame_h__ + +#include "Frame.h" +#include "../Rendering/Texture.h" +#include "../Rendering/Util/CommonFunctions.h" + +namespace GUI +{ + +class TextureFrame : public Frame +{ +public: + TextureFrame(Frame* parent, std::string name) + : Frame(parent, name) { } + + void EnableScissor() { m_ScissorEnabled = true; } + void DisableScissor() { m_ScissorEnabled = false; } + + void Draw(RenderScene& rq) override + { + if (m_Texture == nullptr) + return; + + // Texture while fading + if (m_FadeTexture && m_CurrentFade < 1) { + FrameJob job; + job.Scissor = (m_ScissorEnabled) ? m_Parent->AbsoluteRectangle() : Rectangle(); + job.Viewport = Rectangle(Left(), Top(), Width, Height); + job.TextureID = m_FadeTexture->ResourceID; + job.DiffuseTexture = m_FadeTexture; + job.Color = glm::vec4(m_Color.r, m_Color.g, m_Color.b, m_Color.a); + job.Name = Name(); + rq.GUI.Add(job); + } + + // Main texture + { + FrameJob job; + job.Scissor = (m_ScissorEnabled) ? m_Parent->AbsoluteRectangle() : Rectangle(); + job.Viewport = Rectangle(Left(), Top(), Width, Height); + job.TextureID = m_Texture->ResourceID; + job.DiffuseTexture = m_Texture; + job.Color = glm::vec4(m_Color.r, m_Color.g, m_Color.b, m_Color.a * m_CurrentFade); + job.Name = Name(); + rq.GUI.Add(job); + } + } + + std::string Texture() const { return m_TextureName; } + + void SetTexture(std::string resourceName) + { + if (resourceName.empty()) { + m_Texture = nullptr; + return; + } + + m_Texture = CommonFunctions::LoadTexture(resourceName, false); + m_TextureName = resourceName; + if (m_Texture == nullptr) { + m_Texture = CommonFunctions::LoadTexture("Textures/Core/ErrorTexture.png", false); + } + + SizeToTexture(); + } + + void SizeToTexture() + { + if (m_Texture != nullptr) { + this->Width = m_Texture->Width; + this->Height = m_Texture->Height; + } + } + + void FadeToTexture(std::string resourceName, double duration) + { + m_FadeTexture = m_Texture; + SetTexture(resourceName); + m_FadeDuration = duration; + m_CurrentFade = 0.f; + } + + void Update(double dt) override + { + if (m_CurrentFade < 1) { + m_CurrentFade += dt / m_FadeDuration; + if (m_CurrentFade > 1) { + m_FadeTexture = nullptr; + m_CurrentFade = 1; + m_FadeDuration = 0; + } + } + } + + glm::vec4 Color() const { return m_Color; } + void SetColor(glm::vec4 val) { m_Color = val; } + +protected: + bool m_ScissorEnabled = true; + Texture* m_Texture = nullptr; + std::string m_TextureName; + Texture* m_FadeTexture = nullptr; + glm::vec4 m_Color = glm::vec4(1.f, 1.f, 1.f, 1.f); + float m_FadeDuration = 0.f; + float m_CurrentFade = 1.f; + +}; + +} + +#endif diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index 28795a7f..21833864 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -27,7 +27,7 @@ public: virtual bool OnCommand(const Events::InputCommand& e) override; virtual void Reset(); - void AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer, double& assaultDashCoolDownTimer); + void AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer); bool SniperSprintingCheck(); virtual bool AssaultDashDoubleTapped() const { return m_AssaultDashDoubleTapped; } virtual bool PlayerIsDashing() const { return m_PlayerIsDashing; } @@ -42,6 +42,7 @@ protected: bool m_Crouching = false; //assault dash membervariables - needed to calculate the doubletap- and dashlogic double m_AssaultDashDoubleTapDeltaTime = 0.0; + double m_AssaultDashCoolDownTimer = 0.0; //i will let m_AssaultDashDoubleTapSensitivityTimer stay hardcoded, its not really a gamevariable (more an inputvariable), //and its very unlikely that someone wants to change that value const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f; @@ -191,21 +192,21 @@ bool FirstPersonInputController::OnLockMouse(const Events::LockMou } template -void FirstPersonInputController::AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer, double& assaultDashCoolDownTimer) { +void FirstPersonInputController::AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer) { m_AssaultDashDoubleTapDeltaTime += dt; - assaultDashCoolDownTimer -= dt; + m_AssaultDashCoolDownTimer -= dt; //cooldown = assaultDashCoolDownMaxTimer sec, pretend the dash lasts 0.25 sec (for friction to do its work) - if (assaultDashCoolDownTimer > (assaultDashCoolDownMaxTimer - 0.25f)) { + if (m_AssaultDashCoolDownTimer > (assaultDashCoolDownMaxTimer - 0.25f)) { m_PlayerIsDashing = true; } else { m_PlayerIsDashing = false; } //dashing with shift - if (m_ShiftDashing && assaultDashCoolDownTimer <= 0.0f) { + if (m_ShiftDashing && m_AssaultDashCoolDownTimer <= 0.0f) { //player is dashing with shift //the wanted-direction is set in playermovement already so we dont need to check what direction we want to dash in! - assaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; + m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; m_AssaultDashDoubleTapped = true; m_AssaultDashDoubleTapDeltaTime = 0.f; return; @@ -227,7 +228,7 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool } m_ValidDoubleTap = false; - if (!(assaultDashCoolDownTimer <= 0.0f)) { + if (!(m_AssaultDashCoolDownTimer <= 0.0f)) { //if we cant dash at the moment, then just reset the tap-sensitivity-timer m_AssaultDashDoubleTapDeltaTime = 0.f; return; @@ -235,7 +236,7 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool //ok, we have a valid tap, lets do it m_AssaultDashDoubleTapped = true; m_AssaultDashDoubleTapDeltaTime = 0.f; - assaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; + m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; Events::DashAbility e; m_EventBroker->Publish(e); diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index c407f7f8..978c9b65 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -19,27 +19,11 @@ #include "Core/World.h" #include "Core/EventBroker.h" #include "Core/ConfigFile.h" -#include "Core/EPlayerDeath.h" #include "Input/EInputCommand.h" #include "Core/EPlayerDamage.h" -#include "../Game/Events/EDoubleJump.h" #include "Network/EInterpolate.h" #include "Network/SnapshotFilter.h" #include "Core/EPlayerSpawned.h" -#include "Core/EAmmoPickup.h" -#include "Network/ESearchForServers.h" - -struct ServerInfo -{ - ServerInfo(std::string a, int b, std::string c, int d) - { - Address = a; Port = b; Name = c; PlayersConnected = d; - } - std::string Address = ""; - int Port = 0; - std::string Name = ""; - int PlayersConnected = 0; -}; class Client : public Network { @@ -50,9 +34,7 @@ public: void Connect(std::string address, int port); void Update() override; -private: - UDPClient m_Unreliable; - TCPClient m_Reliable; + std::vector m_PlayerSpawnEvents; void parseSpawnEvents(); // Save for children @@ -100,15 +82,11 @@ private: void parseTCPConnect(Packet& packet); void parsePlayerConnected(Packet& packet); void parsePing(); - void parseServerlist(Packet& packet); void parseKick(); void parsePlayersSpawned(Packet& packet); void parseEntityDeletion(Packet& packet); - void parsePlayerDamage(Packet& packet); void parseComponentDeletion(Packet& packet); - void parseDoubleJump(Packet& packet); - void parseAmmoPickup(Packet& packet); - void InterpolateFields(Packet& packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); + void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void parseSnapshot(Packet& packet); void identifyPacketLoss(); void hasServerTimedOut(); @@ -116,7 +94,6 @@ private: void sendInputCommands(); void sendLocalPlayerTransform(); void becomePlayer(); - void displayServerlist(); // Mapping Logic // Returns if local EntityID exist in map bool clientServerMapsHasEntity(EntityID clientEntityID); @@ -132,15 +109,10 @@ private: bool OnPlayerDamage(const Events::PlayerDamage& e); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned& e); - EventRelay< Client, Events::SearchForServers> m_ESearchForServers; - EventRelay m_EDoubleJump; - bool OnDoubleJump(Events::DoubleJump & e); - bool OnSearchForServers(const Events::SearchForServers& e); - UDPClient m_ServerlistRequest; - std::vector m_Serverlist; - bool m_SearchingForServers = false; - std::clock_t m_StartSearchTime; - double m_SearchingTime = 2000; // Config I guess + void parsePlayerDamage(Packet& packet); +private: + UDPClient m_Unreliable; + TCPClient m_Reliable; }; #endif diff --git a/include/Engine/Network/ESearchForServers.h b/include/Engine/Network/ESearchForServers.h deleted file mode 100644 index 1b08a8f3..00000000 --- a/include/Engine/Network/ESearchForServers.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef Events_SearchForServers_h__ -#define Events_SearchForServers_h__ - -#include "Core/Event.h" - -namespace Events -{ - -struct SearchForServers : public Event { }; - -} -#endif diff --git a/include/Engine/Network/HybridClient.h b/include/Engine/Network/HybridClient.h new file mode 100644 index 00000000..8d96bf6e --- /dev/null +++ b/include/Engine/Network/HybridClient.h @@ -0,0 +1,13 @@ +#ifndef HybridClient_h__ +#define HybridClient_h__ + +class HybridClient +{ +public: + HybridClient(); + ~HybridClient(); +private: + +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/HybridServer.h b/include/Engine/Network/HybridServer.h new file mode 100644 index 00000000..48d6fe63 --- /dev/null +++ b/include/Engine/Network/HybridServer.h @@ -0,0 +1,12 @@ +#ifndef HybridServer_h__ +#define HybridServer_h__ + +class HybridServer +{ +public: + HybridServer(); + ~HybridServer(); +private: +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/MessageType.h b/include/Engine/Network/MessageType.h index bf773618..a72f054e 100644 --- a/include/Engine/Network/MessageType.h +++ b/include/Engine/Network/MessageType.h @@ -19,9 +19,6 @@ enum class MessageType EntityDeleted, ComponentDeleted, PlayerTransform, - OnDoubleJump, - ServerlistRequest, - AmmoPickup, Invalid }; diff --git a/include/Engine/Network/NetworkClient.h b/include/Engine/Network/NetworkClient.h index 4adc68f5..d0339d84 100644 --- a/include/Engine/Network/NetworkClient.h +++ b/include/Engine/Network/NetworkClient.h @@ -9,16 +9,13 @@ typedef unsigned int PacketID; class NetworkClient { public: - NetworkClient(); - virtual ~NetworkClient(); virtual void Connect(std::string playerName, std::string address, int port) = 0; virtual void Disconnect() = 0; virtual void Receive(Packet& packet) = 0; virtual void Send(Packet & packet) = 0; virtual bool IsSocketAvailable() = 0; protected: - char* m_ReadBuffer; - unsigned int m_BufferSize = BUFFERSIZE; + char m_ReadBuffer[BUFFERSIZE] = { 0 }; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/NetworkServer.h b/include/Engine/Network/NetworkServer.h index 296c8762..ccec82cc 100644 --- a/include/Engine/Network/NetworkServer.h +++ b/include/Engine/Network/NetworkServer.h @@ -10,15 +10,12 @@ typedef unsigned int PacketID; class NetworkServer { public: - NetworkServer(); - virtual ~NetworkServer(); virtual void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) = 0; virtual void Receive(Packet & packet, PlayerDefinition & playerDefinition) = 0; virtual void Send(Packet & packet, PlayerDefinition & playerDefinition) = 0; virtual void Send(Packet & packet) = 0; protected: - char* m_ReadBuffer; - unsigned int m_BufferSize = BUFFERSIZE; + char m_ReadBuffer[BUFFERSIZE] = { 0 }; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 3c956ed9..b37bffab 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -17,10 +17,8 @@ #include "Core/EPlayerDamage.h" #include "Network/EPlayerDisconnected.h" #include "Core/EPlayerSpawned.h" -#include "../Game/Events/EDoubleJump.h" #include "Core/EEntityDeleted.h" #include "Core/EComponentDeleted.h" -#include "Core/EAmmoPickup.h" class Server : public Network { @@ -34,7 +32,6 @@ private: // Network channels TCPServer m_Reliable; UDPServer m_Unreliable; - UDPServer m_ServerlistRequest; // dont forget to set these in the childrens receive logic boost::asio::ip::address m_Address; int m_Port = 27666; @@ -57,7 +54,7 @@ private: std::vector m_InputCommandsToBroadcast; //Timers std::clock_t m_StartPingTime; - + // Packet loss logic PacketID m_PacketID = 0; PacketID m_PreviousPacketID = 0; @@ -67,7 +64,6 @@ private: void reliableBroadcast(Packet& packet); void unreliableBroadcast(Packet& packet); void sendSnapshot(); - void addPlayersToPacket(Packet& packet, EntityID entityID); void addChildrenToPacket(Packet& packet, EntityID entityID); void addInputCommandsToPacket(Packet& packet); void sendPing(); @@ -81,15 +77,13 @@ private: void parsePlayerTransform(Packet& packet); void parseOnInputCommand(Packet& packet); void parseClientPing(); - void parsePing(); - bool parseDoubleJump(Packet& packet); - void parseUDPConnect(Packet& packet); - void parseTCPConnect(Packet& packet); + void parsePing(); + void parseUDPConnect(Packet & packet); + void parseTCPConnect(Packet & packet); void parseDisconnect(); - void parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint); bool shouldSendToClient(EntityWrapper childEntity); - // Events + // Debug event EventRelay m_EInputCommand; bool OnInputCommand(const Events::InputCommand& e); EventRelay m_EPlayerSpawned; @@ -100,8 +94,6 @@ private: bool OnComponentDeleted(const Events::ComponentDeleted& e); EventRelay m_EPlayerDamage; bool OnPlayerDamage(const Events::PlayerDamage& e); - EventRelay m_EAmmoPickup; - bool OnAmmoPickup(const Events::AmmoPickup& e); }; #endif diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h index 2108fa3d..a666cbbe 100644 --- a/include/Engine/Network/TCPClient.h +++ b/include/Engine/Network/TCPClient.h @@ -20,7 +20,7 @@ private: boost::asio::ip::tcp::endpoint m_Endpoint; boost::asio::io_service m_IOService; std::unique_ptr m_Socket; - size_t readBuffer(); + size_t readBuffer(char* data); PacketID m_SendPacketID = 0; bool m_IsConnected = false; }; diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 55631a22..9cc7646a 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -16,22 +16,16 @@ public: void Send(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet); void Disconnect(); - int Port() { return m_Port; } - std::string Address() { return m_Address; } - private: // TCP logic boost::asio::io_service m_IOService; std::unique_ptr acceptor; boost::shared_ptr lastReceivedSocket; - int readBuffer(PlayerDefinition& playerDefinition); - PlayerID getPlayerIDFromEndpoint(const std::map& connectedPlayers, - boost::asio::ip::address address, unsigned short port); - int GetPort(); - std::string GetAddress(); - int m_Port = 0; - std::string m_Address = ""; + void handle_accept(boost::shared_ptr socket, + int& nextPlayerID, std::map& connectedPlayers, + const boost::system::error_code& error); + int readBuffer(char* data, PlayerDefinition& playerDefinition); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/UDPClient.h b/include/Engine/Network/UDPClient.h index 42c27783..3a458d3e 100644 --- a/include/Engine/Network/UDPClient.h +++ b/include/Engine/Network/UDPClient.h @@ -14,14 +14,13 @@ public: void Disconnect(); void Receive(Packet& packet); void Send(Packet & packet); - void Broadcast(Packet& packet, int port); bool IsSocketAvailable(); private: // Assio UDP logic boost::asio::io_service m_IOService; boost::asio::ip::udp::endpoint m_ReceiverEndpoint; boost::shared_ptr m_Socket; - int readBuffer(); + int readBuffer(char* data); PacketID m_SendPacketID = 0; }; diff --git a/include/Engine/Network/UDPServer.h b/include/Engine/Network/UDPServer.h index 54f4e327..246fb333 100644 --- a/include/Engine/Network/UDPServer.h +++ b/include/Engine/Network/UDPServer.h @@ -8,21 +8,18 @@ class UDPServer : public NetworkServer { public: UDPServer(); - UDPServer(int port); ~UDPServer(); void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers); void Receive(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet, PlayerDefinition & playerDefinition); - void Send(Packet & packet); - void Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint); - void Broadcast(Packet & packet, int port); + void Send(Packet & packet); bool IsSocketAvailable(); private: // UDP logic boost::asio::io_service m_IOService; boost::asio::ip::udp::endpoint m_ReceiverEndpoint; std::unique_ptr m_Socket; - int readBuffer(); + int readBuffer(char* data); }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/CubeMapPass.h b/include/Engine/Rendering/CubeMapPass.h deleted file mode 100644 index 3cda8cad..00000000 --- a/include/Engine/Rendering/CubeMapPass.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef CubeMapPass_h__ -#define CubeMapPass_h__ - -#include "IRenderer.h" -#include "ShaderProgram.h" - -class CubeMapPass -{ -public: - CubeMapPass(IRenderer* renderer); - ~CubeMapPass() { } - - void LoadTextures(std::string input); - void FillCubeMap(glm::vec3 originPosition); - void GenerateCubeMapTexture(); - - //GLuint CubeMapTexture() const { return m_CubeMapTexture; } - GLuint m_CubeMapTexture = -1; - -private: - IRenderer* m_Renderer; - std::string m_PreviusCubeMapTexture; - - std::vector m_CubeMapTextures; -}; - -#endif \ No newline at end of file diff --git a/include/Engine/Rendering/DrawBloomPass.h b/include/Engine/Rendering/DrawBloomPass.h index ee3a8489..539d6957 100644 --- a/include/Engine/Rendering/DrawBloomPass.h +++ b/include/Engine/Rendering/DrawBloomPass.h @@ -12,7 +12,7 @@ class DrawBloomPass { public: - DrawBloomPass(IRenderer* renderer, ConfigFile* config); + DrawBloomPass(IRenderer* renderer /* ,Texture or finalpass*/ ); ~DrawBloomPass() { } void InitializeTextures(); void InitializeFrameBuffers(); @@ -23,33 +23,24 @@ public: void FillGaussianBuffer(FrameBuffer* fb); void Draw(GLuint texture); - void ChangeQuality(int quality); - - void OnWindowResize(); //Getters //Return the blurred result of the texture that was sent into draw - GLuint GaussianTexture() const { - if (m_Quality == 0) { - return m_BlackTexture->m_Texture; - } else { - return m_GaussianTexture_vert; - } - } + GLuint GaussianTexture() const { return m_GaussianTexture_vert; } private: - Texture* m_BlackTexture; + void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; + + Texture* m_WhiteTexture; Model* m_ScreenQuad; const IRenderer* m_Renderer; - ConfigFile* m_Config; //const LightCullingPass* m_LightCullingPass - int m_Iterations; - int m_Quality = 0; + GLuint m_iterations = 9; - GLuint m_GaussianTexture_horiz = 0; - GLuint m_GaussianTexture_vert = 0; + GLuint m_GaussianTexture_horiz; + GLuint m_GaussianTexture_vert; FrameBuffer m_GaussianFrameBuffer_horiz; FrameBuffer m_GaussianFrameBuffer_vert; 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 cfddd5c6..bf8d4d76 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -4,8 +4,6 @@ #include "IRenderer.h" #include "DrawFinalPassState.h" #include "LightCullingPass.h" -#include "CubeMapPass.h" -#include "SSAOPass.h" #include "FrameBuffer.h" #include "ShaderProgram.h" #include "Util/UnorderedMapVec2.h" @@ -15,28 +13,34 @@ class DrawFinalPass { public: - DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, SSAOPass* ssaoPass); + DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass); ~DrawFinalPass() { } void InitializeTextures(); void InitializeFrameBuffers(); void InitializeShaderPrograms(); void Draw(RenderScene& scene); void ClearBuffer(); - void OnWindowResize(); //Return the texture that is used in later stages to apply the bloom effect GLuint BloomTexture() const { return m_BloomTexture; } + GLuint BloomTextureLowRes() const { return m_BloomTextureLowRes; } //Return the texture with diffuse and lighting of the scene. GLuint SceneTexture() const { return m_SceneTexture; } + GLuint SceneTextureLowRes() const { return m_SceneTextureLowRes; } //Return the framebuffer used in the scene rendering stage. FrameBuffer* FinalPassFrameBuffer() { return &m_FinalPassFrameBuffer; } + FrameBuffer* FinalPassFrameBufferLowRes() { return &m_FinalPassFrameBufferLowRes; } + private: + void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; + void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const; + void DrawSprites(std::list>&jobs, RenderScene& scene); void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene); - void DrawModelRenderQueuesWithShieldCheck(std::list>& jobs, RenderScene& scene); + void DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene); void DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene); - void DrawToDepthStencilBuffer(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); @@ -51,47 +55,35 @@ private: Texture* m_ErrorTexture; FrameBuffer m_FinalPassFrameBuffer; - FrameBuffer m_ShieldDepthFrameBuffer; + FrameBuffer m_FinalPassFrameBufferLowRes; GLuint m_BloomTexture; GLuint m_SceneTexture; + GLuint m_BloomTextureLowRes; + GLuint m_SceneTextureLowRes; GLuint m_DepthBuffer; - GLuint m_ShieldBuffer; - GLuint m_CubeMapTexture; + GLuint m_DepthBufferLowRes; //maqke this component based i guess? GLuint m_ShieldPixelRate = 16; const IRenderer* m_Renderer; const LightCullingPass* m_LightCullingPass; - const CubeMapPass* m_CubeMapPass; - const SSAOPass* m_SSAOPass; ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; ShaderProgram* m_ExplosionEffectSplatMapProgram; ShaderProgram* m_SpriteProgram; ShaderProgram* m_ForwardPlusSplatMapProgram; - ShaderProgram* m_FillDepthStencilBufferProgram; - - ShaderProgram* m_ForwardPlusShieldCheckProgram; - ShaderProgram* m_ExplosionEffectShieldCheckProgram; - ShaderProgram* m_ExplosionEffectSplatMapShieldCheckProgram; - ShaderProgram* m_SpriteShieldCheckProgram; - ShaderProgram* m_ForwardPlusSplatMapShieldCheckProgram; - + ShaderProgram* m_ShieldToStencilProgram; + ShaderProgram* m_FillDepthBufferProgram; ShaderProgram* m_ForwardPlusSkinnedProgram; ShaderProgram* m_ExplosionEffectSkinnedProgram; ShaderProgram* m_ExplosionEffectSplatMapSkinnedProgram; ShaderProgram* m_ForwardPlusSplatMapSkinnedProgram; - ShaderProgram* m_FillDepthStencilBufferSkinnedProgram; - - ShaderProgram* m_ForwardPlusSkinnedShieldCheckProgram; - ShaderProgram* m_ExplosionEffectSkinnedShieldCheckProgram; - ShaderProgram* m_ExplosionEffectSplatMapSkinnedShieldCheckProgram; - ShaderProgram* m_ForwardPlusSplatMapSkinnedShieldCheckProgram; - ShaderProgram* m_FillDepthBufferSkinnedShieldCheckProgram; + ShaderProgram* m_ShieldToStencilSkinnedProgram; + ShaderProgram* m_FillDepthBufferSkinnedProgram; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/ExplosionEffectJob.h b/include/Engine/Rendering/ExplosionEffectJob.h index 695a8dfe..8f339526 100644 --- a/include/Engine/Rendering/ExplosionEffectJob.h +++ b/include/Engine/Rendering/ExplosionEffectJob.h @@ -15,8 +15,8 @@ struct ExplosionEffectJob : ModelJob { - ExplosionEffectJob(ComponentWrapper explosionEffectComponent, ::Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matGroup, ComponentWrapper modelComponent, ::World* world, glm::vec4 fillColor, float fillPercentage, bool isShielded) - : ModelJob(model, camera, matrix, matGroup, modelComponent, world, fillColor, fillPercentage, isShielded) + ExplosionEffectJob(ComponentWrapper explosionEffectComponent, ::Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matGroup, ComponentWrapper modelComponent, ::World* world, glm::vec4 fillColor, float fillPercentage) + : ModelJob(model, camera, matrix, matGroup, modelComponent, world, fillColor, fillPercentage) { ExplosionOrigin = (glm::vec3)explosionEffectComponent["ExplosionOrigin"]; TimeSinceDeath = (double)explosionEffectComponent["TimeSinceDeath"]; diff --git a/include/Engine/Rendering/IRenderer.h b/include/Engine/Rendering/IRenderer.h index 2e6f3a97..4441bb7d 100644 --- a/include/Engine/Rendering/IRenderer.h +++ b/include/Engine/Rendering/IRenderer.h @@ -5,13 +5,11 @@ #include "../OpenGL.h" #include "../GLM.h" #include "../Core/Util/Rectangle.h" -#include "../Core/ConfigFile.h" #include "Util/ScreenCoords.h" #include "Camera.h" #include "RenderQueue.h" #include "Model.h" #include "../Core/World.h" //So temp -#include "Util/CommonFunctions.h" struct PickData diff --git a/include/Engine/Rendering/LightCullingPass.h b/include/Engine/Rendering/LightCullingPass.h index 914fb8bb..d8852df0 100644 --- a/include/Engine/Rendering/LightCullingPass.h +++ b/include/Engine/Rendering/LightCullingPass.h @@ -21,7 +21,6 @@ public: void SetSSBOSizes(); void CullLights(RenderScene& scene); void FillLightList(RenderScene& scene); - void OnWindowResize(); GLuint FrustumSSBO() const { return m_FrustumSSBO; } GLuint LightSSBO() const { return m_LightSSBO; } diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index 58993ea1..ba801f60 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -18,7 +18,7 @@ struct ModelJob : RenderJob { - ModelJob(Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matProp, ComponentWrapper modelComponent, World* world, glm::vec4 fillColor, float fillPercentage, bool isShielded) + ModelJob(Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matProp, ComponentWrapper modelComponent, World* world, glm::vec4 fillColor, float fillPercentage) : RenderJob() { Model = model; @@ -108,7 +108,6 @@ struct ModelJob : RenderJob EndIndex = matGroup->EndIndex; Matrix = matrix; Color = modelComponent["Color"]; - GlowIntensity = ((double)modelComponent["GlowIntensity"]); Entity = modelComponent.EntityID; glm::vec3 abspos = Transform::AbsolutePosition(world, modelComponent.EntityID); glm::vec3 worldpos = glm::vec3(camera->ViewMatrix() * glm::vec4(abspos, 1)); @@ -117,7 +116,7 @@ struct ModelJob : RenderJob FillColor = fillColor; FillPercentage = fillPercentage; - IsShielded = isShielded; + if (model->IsSkinned()) { Skeleton = Model->m_RawModel->m_Skeleton; @@ -171,7 +170,7 @@ struct ModelJob : RenderJob ::Skeleton::AnimationOffset AnimationOffset; - float GlowIntensity = 8.0; + glm::vec4 DiffuseColor; glm::vec4 SpecularColor; glm::vec4 IncandescenceColor; @@ -181,10 +180,10 @@ struct ModelJob : RenderJob glm::vec4 FillColor = glm::vec4(0); float FillPercentage = 0.0; - bool IsShielded; + void CalculateHash() override { - Hash = ShaderID << 20 + ModelID << 10 + TextureID; + Hash = TextureID + ModelID << 10 + ShaderID << 20; } }; diff --git a/include/Engine/Rendering/PickingPass.h b/include/Engine/Rendering/PickingPass.h index df99a615..2ce2e78d 100644 --- a/include/Engine/Rendering/PickingPass.h +++ b/include/Engine/Rendering/PickingPass.h @@ -22,25 +22,25 @@ public: void Draw(RenderScene& scene); void ClearPicking(); - void OnWindowResize(); - //Getters const ShaderProgram& PickingProgram() const { return *m_PickingProgram; } //const std::unordered_map& PickingColorsToEntity() const { return m_PickingColorsToEntity; } GLuint PickingTexture() const { return m_PickingTexture; } - GLuint* DepthBuffer() { return &m_DepthBuffer; } + GLuint DepthBuffer() const { return m_DepthBuffer; } const FrameBuffer& PickingBuffer() const { return m_PickingBuffer; } PickData Pick(glm::vec2 screenCoord); private: + void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; + EventBroker* m_EventBroker; const IRenderer* m_Renderer; ShaderProgram* m_PickingProgram; - ShaderProgram* m_PickingSkinnedProgram; + ShaderProgram* m_PickingSkinnedProgram; Camera* m_Camera; struct PickingInfo diff --git a/include/Engine/Rendering/RenderQueue.h b/include/Engine/Rendering/RenderQueue.h index e3c46e85..647adab8 100644 --- a/include/Engine/Rendering/RenderQueue.h +++ b/include/Engine/Rendering/RenderQueue.h @@ -24,6 +24,7 @@ struct RenderScene std::list> OpaqueObjects; std::list> TransparentObjects; std::list> OpaqueShieldedObjects; + std::list> TransparentShieldedObjects; std::list> ShieldObjects; std::list> SpriteJob; std::list> PointLight; @@ -40,6 +41,7 @@ struct RenderScene Jobs.OpaqueObjects.clear(); Jobs.TransparentObjects.clear(); Jobs.OpaqueShieldedObjects.clear(); + Jobs.TransparentShieldedObjects.clear(); Jobs.ShieldObjects.clear(); Jobs.SpriteJob.clear(); Jobs.DirectionalLight.clear(); diff --git a/include/Engine/Rendering/RenderState.h b/include/Engine/Rendering/RenderState.h index 24f908a9..c1886247 100644 --- a/include/Engine/Rendering/RenderState.h +++ b/include/Engine/Rendering/RenderState.h @@ -24,8 +24,6 @@ public: bool StencilFunc(GLenum func, GLint ref, GLuint mask); bool StencilMask(GLuint mask); bool DepthMask(GLboolean flag); - bool DepthFunc(GLenum func); - bool AlphaFunc(GLenum func, GLclampf thresholder); private: std::vector> m_ResetFunctions; diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index a64a4aa3..04754514 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -16,8 +16,6 @@ #include "DrawScreenQuadPass.h" #include "DrawBloomPass.h" #include "DrawColorCorrectionPass.h" -#include "SSAOPass.h" -#include "CubeMapPass.h" #include "../Core/EventBroker.h" #include "ImGuiRenderPass.h" #include "Camera.h" @@ -25,16 +23,12 @@ #include "imgui/imgui.h" #include "TextPass.h" #include "Util/CommonFunctions.h" -#include "Core/PerformanceTimer.h" class Renderer : public IRenderer { - static void glfwFrameBufferCallback(GLFWwindow* window, int width, int height); - public: - Renderer(EventBroker* eventBroker, ConfigFile* config) - : m_EventBroker(eventBroker) - , m_Config(config) + Renderer(EventBroker* eventBroker) + : m_EventBroker(eventBroker) { } virtual void Initialize() override; @@ -43,13 +37,8 @@ public: virtual PickData Pick(glm::vec2 screenCoord) override; - private: //----------------------Variables----------------------// - - static std::unordered_map m_WindowToRenderer; - ConfigFile* m_Config; - EventBroker* m_EventBroker; TextPass* m_TextPass; @@ -61,10 +50,6 @@ private: Model* m_UnitSphere; int m_DebugTextureToDraw = 0; - int m_CubeMapTexture = 0; - bool m_ResizeWindow = false; - int m_SSAO_Quality = 0; - int m_GLOW_Quality = 2; PickingPass* m_PickingPass; LightCullingPass* m_LightCullingPass; @@ -73,8 +58,6 @@ private: DrawScreenQuadPass* m_DrawScreenQuadPass; DrawBloomPass* m_DrawBloomPass; DrawColorCorrectionPass* m_DrawColorCorrectionPass; - SSAOPass* m_SSAOPass; - CubeMapPass* m_CubeMapPass; //----------------------Functions----------------------// void InitializeWindow(); diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h deleted file mode 100644 index 1cb28009..00000000 --- a/include/Engine/Rendering/SSAOPass.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef SSAOPass_h__ -#define SSAOPass_h__ - -#include "IRenderer.h" -#include "SSAOPassState.h" -//#include "LightCullingPass.h" Finalpass om den skall skickas in -#include "FrameBuffer.h" -#include "ShaderProgram.h" -#include "DrawBloomPass.h" -//#include "Util/UnorderedMapVec2.h" -#include "Texture.h" - -class SSAOPass -{ -public: - SSAOPass(IRenderer* renderer, ConfigFile* config); - ~SSAOPass() { }; - - void ChangeQuality(int quality); - - void Draw(GLuint depthBuffer, Camera* camera); - void Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int numOfTurns, int iterations, int quality); - void ClearBuffer(); - void OnWindowResize(); - - //Return the SSAO of the texture sent to Draw - GLuint SSAOTexture() const { - if (m_Quality == 0) { - return m_WhiteTexture->m_Texture; - } else { - return m_Gaussian_vert; - } - } - - int TextureQuality() const { - if (m_Quality == 0) { - return 13; - } else { - return m_TextureQuality; - } - } - -private: - void InitializeTexture(); - void InitializeFrameBuffer(); - void InitializeShaderProgram(); - void InitializeBuffer(); - - //void blurHorizontal(GLuint depthBuffer); - //void blurVertical(GLuint depthBuffer); - - Model* m_ScreenQuad; - - const IRenderer* m_Renderer; - ConfigFile* m_Config; - - float m_Radius; - float m_Bias; - float m_Contrast; - float m_IntensityScale; - int m_NumOfSamples; - int m_NumOfTurns; - int m_Iterations; - int m_TextureQuality; - int m_Quality = 0; - - Texture* m_WhiteTexture; - - GLuint m_SSAOTexture = 0; - FrameBuffer m_SSAOFramBuffer; - - GLuint m_SSAOViewSpaceZTexture = 0; - FrameBuffer m_SSAOViewSpaceZFramBuffer; - - GLuint m_Gaussian_horiz = 0; - GLuint m_Gaussian_vert = 0; - - FrameBuffer m_GaussianFrameBuffer_horiz; - FrameBuffer m_GaussianFrameBuffer_vert; - - ShaderProgram* m_SSAOProgram; - ShaderProgram* m_SSAOViewSpaceZProgram; - ShaderProgram* m_GaussianProgram_horiz; - ShaderProgram* m_GaussianProgram_vert; -}; - -#endif \ No newline at end of file diff --git a/include/Engine/Rendering/SSAOPassState.h b/include/Engine/Rendering/SSAOPassState.h deleted file mode 100644 index 115fdcf7..00000000 --- a/include/Engine/Rendering/SSAOPassState.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef SSAOPassState_h__ -#define SSAOPassState_h__ - -#include "Rendering/RenderState.h" - -class SSAOPassState : public RenderState -{ -public: - SSAOPassState(); - ~SSAOPassState(); -private: - -}; - -#endif \ No newline at end of file diff --git a/include/Engine/Rendering/SpriteJob.h b/include/Engine/Rendering/SpriteJob.h index 25c2d5cb..3bb43a1c 100644 --- a/include/Engine/Rendering/SpriteJob.h +++ b/include/Engine/Rendering/SpriteJob.h @@ -17,7 +17,7 @@ struct SpriteJob : RenderJob { - SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage, bool depthSorted, bool isIndicator) + SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage, bool depthSorted) : RenderJob() { Model = ResourceManager::Load<::Model>("Models/Core/UnitQuad.mesh"); @@ -30,7 +30,7 @@ struct SpriteJob : RenderJob StartIndex = matProp.material->StartIndex; EndIndex = matProp.material->EndIndex; - Matrix = matrix; + Matrix = matrix; Color = cSprite["Color"]; Entity = cSprite.EntityID; Position = Transform::AbsolutePosition(world, cSprite.EntityID); @@ -40,8 +40,6 @@ struct SpriteJob : RenderJob Depth = viewpos.z; } World = world; - Pickable = world->HasComponent(cSprite.EntityID, "Button"); - IsIndicator = isIndicator; FillColor = fillColor; FillPercentage = fillPercentage; @@ -63,9 +61,6 @@ struct SpriteJob : RenderJob unsigned int EndIndex = 0; World* World; - bool Pickable; - bool IsIndicator = false; - glm::vec4 FillColor = glm::vec4(0); float FillPercentage = 0.0; diff --git a/include/Engine/Rendering/Texture.h b/include/Engine/Rendering/Texture.h index d159e636..0fe650b3 100644 --- a/include/Engine/Rendering/Texture.h +++ b/include/Engine/Rendering/Texture.h @@ -18,7 +18,6 @@ public: void Bind(GLenum textureUnit = GL_TEXTURE0); GLuint m_Texture = 0; - unsigned char* Data = nullptr; }; diff --git a/include/Engine/Rendering/Util/CommonFunctions.h b/include/Engine/Rendering/Util/CommonFunctions.h index 1ed3d82a..e178f52d 100644 --- a/include/Engine/Rendering/Util/CommonFunctions.h +++ b/include/Engine/Rendering/Util/CommonFunctions.h @@ -9,10 +9,6 @@ namespace CommonFunctions { Texture* LoadTexture(std::string path, bool threaded); -void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type); -void GenerateMultiSampleTexture(GLuint* texture, int numSamples, glm::vec2 dimensions, GLint internalFormat); -void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps); -void DeleteTexture(GLuint* texture); }; #endif \ No newline at end of file diff --git a/include/Game/Events/EDoubleJump.h b/include/Game/Events/EDoubleJump.h index f5cad1fd..767d5b39 100644 --- a/include/Game/Events/EDoubleJump.h +++ b/include/Game/Events/EDoubleJump.h @@ -8,7 +8,7 @@ namespace Events struct DoubleJump : public Event { - EntityID entityID; + }; } diff --git a/include/Game/Game.h b/include/Game/Game.h index 06fd4703..baf15656 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -8,6 +8,7 @@ #include "Core/EventBroker.h" #include "Rendering/Renderer.h" #include "Core/InputManager.h" +#include "GUI/Frame.h" #include "Core/World.h" #include "Input/InputProxy.h" #include "Input/KeyboardInputHandler.h" @@ -34,9 +35,6 @@ #include "Sound/SoundManager.h" #include "Systems/SoundSystem.h" -//Performance -#include "Core/PerformanceTimer.h" - class Game { public: @@ -55,6 +53,7 @@ private: IRenderer* m_Renderer; InputManager* m_InputManager; InputProxy* m_InputProxy; + GUI::Frame* m_FrameStack; World* m_World; Octree* m_OctreeCollision; Octree* m_OctreeTrigger; diff --git a/include/Game/Systems/AmmoPickupSystem.h b/include/Game/Systems/AmmoPickupSystem.h index e4a6df59..a54b8495 100644 --- a/include/Game/Systems/AmmoPickupSystem.h +++ b/include/Game/Systems/AmmoPickupSystem.h @@ -20,15 +20,12 @@ public: private: EventRelay m_ETriggerTouch; bool OnTriggerTouch(Events::TriggerTouch& e); - EventRelay m_EAmmoPickup; - bool OnAmmoPickup(Events::AmmoPickup& e); struct NewAmmoPickup { glm::vec3 Pos; double AmmoGain; double RespawnTimer; double DecreaseThisRespawnTimer; - EntityID parentID; }; std::vector m_ETriggerTouchVector; }; diff --git a/include/Game/Systems/CapturePointSystem.h b/include/Game/Systems/CapturePointSystem.h index 3cf72e15..34a23e14 100644 --- a/include/Game/Systems/CapturePointSystem.h +++ b/include/Game/Systems/CapturePointSystem.h @@ -42,9 +42,9 @@ private: int m_NumberOfCapturePoints = 0; std::map m_CapturePointNumberToEntityMap; + //std::vector + bool m_ResetTimers = false; - bool m_RecentlyCapturedNeedNextCapturePointNow = false; - Events::Captured m_CapturedEvent; //vectors which will keep track of enter/leave changes std::vector> m_ETriggerTouchVector; diff --git a/include/Game/Systems/DamageIndicatorSystem.h b/include/Game/Systems/DamageIndicatorSystem.h index ae9ba195..053b196b 100644 --- a/include/Game/Systems/DamageIndicatorSystem.h +++ b/include/Game/Systems/DamageIndicatorSystem.h @@ -14,13 +14,11 @@ #include #include "Rendering/Util/CommonFunctions.h" -//#define INDICATOR_TEST -class DamageIndicatorSystem : public ImpureSystem +class DamageIndicatorSystem : public System { public: DamageIndicatorSystem(SystemParams params); - virtual void Update(double dt) override; private: EventRelay m_EPlayerDamage; @@ -30,20 +28,6 @@ private: bool OnSetCamera(const Events::SetCamera& e); EntityID m_CurrentCamera = -1; - struct DamageIndicatorStruct { - EntityWrapper spriteEntity; - glm::vec3 enemyPosition; - DamageIndicatorStruct(EntityWrapper sprite, glm::vec3 pos) - : spriteEntity(sprite) - , enemyPosition(pos) {} - }; - std::vector updateDamageIndicatorVector; - float CalculateAngle(EntityWrapper player, glm::vec3 enemyPos); - //for tests -#ifdef INDICATOR_TEST - glm::vec3 DamageIndicatorTest(EntityWrapper player); - int m_TestVar = 0; -#endif }; #endif diff --git a/include/Game/Systems/HealthSystem.h b/include/Game/Systems/HealthSystem.h index 962e3737..56f2f838 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -27,16 +27,17 @@ public: private: bool m_NetworkEnabled; - // methods which will take care of specific events + //methods which will take care of specific events EventRelay m_EPlayerDamage; bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e); EventRelay m_EPlayerHealthPickup; bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e); EventRelay m_InputCommand; bool HealthSystem::OnInputCommand(Events::InputCommand& e); - + //vector which will keep track of health changes std::vector> m_DeltaHealthVector; + }; #endif \ No newline at end of file diff --git a/include/Game/Systems/PickupSpawnSystem.h b/include/Game/Systems/PickupSpawnSystem.h index 66c5f630..f912e8ff 100644 --- a/include/Game/Systems/PickupSpawnSystem.h +++ b/include/Game/Systems/PickupSpawnSystem.h @@ -27,7 +27,6 @@ private: double HealthGain; double RespawnTimer; double DecreaseThisRespawnTimer; - EntityID parentID; }; std::vector m_ETriggerTouchVector; }; diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index 92aa1915..2bcae866 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -34,14 +34,10 @@ private: glm::vec3 m_LastPosition = glm::vec3(); // The logic for making the sound play when player is moving void playerStep(double dt); - // Spawn a hexagon at origin of an Entity - void spawnHexagon(EntityWrapper target); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); - EventRelay m_EDoubleJump; - bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e); void updateMovementControllers(double dt); - void updateVelocity(EntityWrapper player, double dt); + void updateVelocity(double dt); }; \ No newline at end of file diff --git a/include/Game/Systems/PlayerSpawnSystem.h b/include/Game/Systems/PlayerSpawnSystem.h index 70f94807..bf87bef8 100644 --- a/include/Game/Systems/PlayerSpawnSystem.h +++ b/include/Game/Systems/PlayerSpawnSystem.h @@ -13,6 +13,8 @@ public: PlayerSpawnSystem(SystemParams params); virtual void Update(double dt) override; + + static void SetRespawnTime(float respawnTime) { m_RespawnTime = respawnTime; }; private: struct SpawnRequest @@ -29,8 +31,8 @@ private: //EntityWrapper ID -> Player ID. std::map m_PlayerIDs; - float m_ForcedRespawnTime; - bool m_DbgConfigForceRespawn; + static float m_RespawnTime; + float m_Timer; EventRelay m_OnInputCommand; bool OnInputCommand(Events::InputCommand& e); diff --git a/include/Game/Systems/SpawnerSystem.h b/include/Game/Systems/SpawnerSystem.h index e4a44738..9cb4bd06 100644 --- a/include/Game/Systems/SpawnerSystem.h +++ b/include/Game/Systems/SpawnerSystem.h @@ -15,16 +15,11 @@ class SpawnerSystem : public System public: SpawnerSystem(SystemParams params); - // If dontCollideComponent is set, to e.g. "Player", then all the spawner - // will try to pick a spawn location so that the spawned entity doesn't - // collide with anything that has that component and is collidable. - static EntityWrapper Spawn(EntityWrapper spawner, EntityWrapper parent = EntityWrapper::Invalid, const std::string& dontCollideComponent = ""); + static EntityWrapper Spawn(EntityWrapper spawner, EntityWrapper parent = EntityWrapper::Invalid); private: EventRelay m_OnSpawnerSpawn; bool OnSpawnerSpawn(Events::SpawnerSpawn& e); - static void transformEntityToSpawnPoint(EntityWrapper spawnedEntity, EntityWrapper spawnPoint); - static bool spawnedEntityIsColliding(EntityWrapper spawnedEntity, EntityWrapper spawnPoint, const std::string& dontCollideComponent); }; #endif \ No newline at end of file diff --git a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h index 993dd060..7bd9c175 100644 --- a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h +++ b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h @@ -1,33 +1,37 @@ -#ifndef AssaultWeaponBehaviour_h__ -#define AssaultWeaponBehaviour_h__ - #include "Sound/EPlaySoundOnEntity.h" #include "Collision/Collision.h" +#include "Rendering/AnimationSystem.h" #include "Core/ConfigFile.h" #include "WeaponBehaviour.h" #include "../SpawnerSystem.h" #include "Core/EPlayerDamage.h" #include "Core/EShoot.h" -class AssaultWeaponBehaviour : public WeaponBehaviour + +class AssaultWeaponBehaviour : public WeaponBehaviour { public: - AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree) - : WeaponBehaviour(systemParams, "AssaultWeapon", renderer, collisionOctree) - { } + AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper weaponEntity); + + virtual void Fire() override; + virtual void CeaseFire() override; + virtual void Reload() override; -protected: - virtual void OnPrimaryFire(WeaponInfo& wi) override; - virtual void OnCeasePrimaryFire(WeaponInfo& wi) override; - virtual void OnReload(WeaponInfo& wi) override; + virtual void Update(double dt) override; private: + EntityWrapper m_FirstPersonModel; + EntityWrapper m_ThirdPersonModel; // State bool m_Firing = false; bool m_Reloading = false; double m_ReloadTimer = 0.0; + EntityWrapper m_FirstPersonReloadImpersonator; + EntityWrapper m_ThirdPersonReloadImpersonator; double m_TimeSinceLastFire = 0.0; - EntityWrapper m_FirstPersonReloadImpostor; + + EventRelay m_EAnimationComplete; + bool OnAnimationComplete(Events::AnimationComplete& e); bool hasAmmo(); void fireRound(); @@ -43,5 +47,3 @@ private: bool shoot(double damage); void showHitMarker(); }; - -#endif \ No newline at end of file diff --git a/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h b/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h deleted file mode 100644 index 5ca13d3e..00000000 --- a/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h +++ /dev/null @@ -1,38 +0,0 @@ -#include "WeaponBehaviour.h" -#include "Collision/Collision.h" -#include "Core/EPlayerDamage.h" -#include "Rendering/ESetCamera.h" - -class DefenderWeaponBehaviour : public WeaponBehaviour -{ -public: - DefenderWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree) - : System(systemParams) - , WeaponBehaviour(systemParams, "DefenderWeapon", renderer, collisionOctree) - , m_RandomEngine(m_RandomDevice()) - { - EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &DefenderWeaponBehaviour::OnSetCamera); - } - - void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cWeapon, double dt) override; - void UpdateWeapon(WeaponInfo& wi, double dt) override; - void OnPrimaryFire(WeaponInfo& wi) override; - void OnCeasePrimaryFire(WeaponInfo& wi) override; - bool OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) override; - -private: - std::random_device m_RandomDevice; - std::mt19937 m_RandomEngine; - EntityWrapper m_CurrentCamera; - - EventRelay m_ESetCamera; - bool OnSetCamera(const Events::SetCamera& e); - - // Weapon functions - void fireShell(WeaponInfo& wi); - void dealDamage(WeaponInfo& wi, glm::vec3 direction, double damage); - - // Utility - float traceRayDistance(glm::vec3 origin, glm::vec3 direction); - Camera cameraFromEntity(EntityWrapper camera); -}; \ No newline at end of file diff --git a/include/Game/Systems/Weapon/WeaponBehaviour.h b/include/Game/Systems/Weapon/WeaponBehaviour.h index f23269df..7a0b4626 100644 --- a/include/Game/Systems/Weapon/WeaponBehaviour.h +++ b/include/Game/Systems/Weapon/WeaponBehaviour.h @@ -5,177 +5,30 @@ #include "Rendering/IRenderer.h" #include "Core/Octree.h" #include "Collision/EntityAABB.h" -#include "Input/EInputCommand.h" -#include "Systems/SpawnerSystem.h" -template -class WeaponBehaviour : public PureSystem +class WeaponBehaviour : public System { - friend class WeaponSystem; - public: - WeaponBehaviour(SystemParams params, std::string componentType, IRenderer* renderer, Octree* collisionOctree) - : System(params) - , PureSystem(componentType) + WeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) + : System(systemParams) , m_Renderer(renderer) , m_CollisionOctree(collisionOctree) - { - EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &WeaponBehaviour::_OnInputCommand) - } + , m_Player(player) + { } virtual ~WeaponBehaviour() = default; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override - { - auto weapon = getActiveWeapon(entity); - if (!weapon) { - return; - } else { - UpdateWeapon(*weapon, dt); - } - } + WeaponBehaviour(const WeaponBehaviour&) = delete; + WeaponBehaviour& operator=(const WeaponBehaviour &) = delete; + + virtual void Fire() = 0; + virtual void CeaseFire() { } + virtual void Reload() { } + virtual void Update(double dt) { } protected: - struct WeaponInfo - { - std::string WeaponComponent; - EntityWrapper Player; - EntityWrapper WeaponEntity; - EntityWrapper FirstPersonEntity; - EntityWrapper ThirdPersonEntity; - ComponentWrapper GetComponent() { return WeaponEntity[WeaponComponent]; } - }; - IRenderer* m_Renderer; Octree* m_CollisionOctree; - std::unordered_map m_ActiveWeapons; - - virtual void UpdateWeapon(WeaponInfo& wi, double dt) { } - virtual void OnPrimaryFire(WeaponInfo& wi) { } - virtual void OnCeasePrimaryFire(WeaponInfo& wi) { } - virtual void OnReload(WeaponInfo& wi) { } - virtual bool OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) { return false; } - -private: - EventRelay m_EInputCommand; - bool _OnInputCommand(const Events::InputCommand& e) - { - EntityWrapper player = e.Player; - if (e.PlayerID == -1) { - player = LocalPlayer; - } - - // Make sure the player is alive - if (!player.Valid()) { - return false; - } - - // Make sure the player has this weapon - auto weapon = getWeaponComponent(player); - if (!weapon) { - return false; - } - - // Weapon selection - if (e.Command == "SelectWeapon") { - if (static_cast(e.Value) == static_cast((*weapon)["Slot"])) { - selectWeapon(player); - } - } - - // Only handle weapon actions if the weapon is active - auto activeWeapon = getActiveWeapon(player); - if (!activeWeapon) { - return false; - } - - // Fire - if (e.Command == "PrimaryFire") { - if (e.Value > 0) { - OnPrimaryFire(*activeWeapon); - } else { - OnCeasePrimaryFire(*activeWeapon); - } - } - - // Reload - if (e.Command == "Reload" && e.Value != 0) { - OnReload(*activeWeapon); - } - - return OnInputCommand(*activeWeapon, e); - } - - boost::optional getWeaponComponent(EntityWrapper player) - { - if (!player.HasComponent(m_ComponentType)) { - return boost::none; - } - - return player[m_ComponentType]; - } - - boost::optional getActiveWeapon(EntityWrapper player) - { - auto it = m_ActiveWeapons.find(player); - if (it == m_ActiveWeapons.end()) { - return boost::none; - } - WeaponInfo& activeWeapon = it->second; - - if (!activeWeapon.FirstPersonEntity.Valid() && !activeWeapon.ThirdPersonEntity.Valid()) { - return boost::none; - } - - return activeWeapon; - } - - void selectWeapon(EntityWrapper player) - { - // Find the weapon attachments matching the weapon type - std::vector weaponAttachments = player.ChildrenWithComponent("WeaponAttachment"); - EntityWrapper firstPersonAttachment; - EntityWrapper thirdPersonAttachment; - for (auto& attachment : weaponAttachments) { - ComponentWrapper cWeaponAttachment = attachment["WeaponAttachment"]; - if ((std::string&)cWeaponAttachment["Weapon"] == m_ComponentType) { - ComponentWrapper::SubscriptProxy person = cWeaponAttachment["Person"]; - if ((ComponentInfo::EnumType)person == person.Enum("FirstPerson")) { - firstPersonAttachment = attachment; - } else if ((ComponentInfo::EnumType)person == person.Enum("ThirdPerson")) { - thirdPersonAttachment = attachment; - } - } - } - - if (!firstPersonAttachment.Valid() && !thirdPersonAttachment.Valid()) { - LOG_WARNING("No weapon attachment found for %s of player #%i", m_ComponentType.c_str(), player.ID); - return; - } - - // Purge other weapon entities - for (auto& attachment : weaponAttachments) { - //if (attachment == firstPersonAttachment || attachment == thirdPersonAttachment) { - // continue; - //} - attachment.DeleteChildren(); - } - - // Spawn the weapon(s) - EntityWrapper firstPersonWeapon; - EntityWrapper thirdPersonWeapon; - if (firstPersonAttachment.Valid()) { - firstPersonWeapon = SpawnerSystem::Spawn(firstPersonAttachment, firstPersonAttachment); - } - if (thirdPersonAttachment.Valid()) { - thirdPersonWeapon = SpawnerSystem::Spawn(thirdPersonAttachment, thirdPersonAttachment); - } - - m_ActiveWeapons[player].WeaponComponent = m_ComponentType; - m_ActiveWeapons[player].Player = player; - m_ActiveWeapons[player].WeaponEntity = player; - m_ActiveWeapons[player].FirstPersonEntity = firstPersonWeapon; - m_ActiveWeapons[player].ThirdPersonEntity = thirdPersonWeapon; - } + EntityWrapper m_Player; }; #endif diff --git a/resources/DefaultConfig.ini b/resources/DefaultConfig.ini index e99e3437..60ee4823 100644 --- a/resources/DefaultConfig.ini +++ b/resources/DefaultConfig.ini @@ -36,49 +36,4 @@ ResourceLoading=true [Sound] BGMVolume=1.0 SFXVolume=1.0 -Announcer=female - -[SSAO] -Quality=0 - -[SSAO1] -Radius=1.0 -Bias=0.02 -Contrast=1.5 -Intensity=1.0 -NumSamples=8 -NumTurns=3 -NumIterations=5 -TextureQuality=2 - -[SSAO2] -Radius=1.0 -Bias=0.02 -Contrast=1.5 -Intensity=1.0 -NumSamples=16 -NumTurns=13 -NumIterations=9 -TextureQuality=1 - -[SSAO3] -Radius=1.0 -Bias=0.02 -Contrast=1.5 -Intensity=1.0 -NumSamples=24 -NumTurns=17 -NumIterations=9 -TextureQuality=0 - -[GLOW] -Quality=3; - -[GLOW1] -NumIterations=5 - -[GLOW2] -NumIterations=9 - -[GLOW3] -NumIterations=13 \ No newline at end of file +Announcer=female \ No newline at end of file diff --git a/resources/DefaultInput.ini b/resources/DefaultInput.ini index 776cbecd..d5489c3a 100644 --- a/resources/DefaultInput.ini +++ b/resources/DefaultInput.ini @@ -25,6 +25,4 @@ C=ConnectToServer N=SwitchToServer M=SwitchToClient P=SwitchToPlayer -K=TakeDamage,1500 -F2=PerformanceTimingResetAllTimers -F3=PerformanceTimingCreateExcelData \ No newline at end of file +K=TakeDamage,1500 \ No newline at end of file diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 97b835ee..c9d8a70e 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -46,13 +46,5 @@ - - - - - - - - \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xml b/resources/Schema/Components/AssaultWeapon.xml index c835217b..6c645624 100755 --- a/resources/Schema/Components/AssaultWeapon.xml +++ b/resources/Schema/Components/AssaultWeapon.xml @@ -8,5 +8,4 @@ 120 0.01 2 - \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xsd b/resources/Schema/Components/AssaultWeapon.xsd index 7e9854a2..95df64b7 100755 --- a/resources/Schema/Components/AssaultWeapon.xsd +++ b/resources/Schema/Components/AssaultWeapon.xsd @@ -2,7 +2,6 @@ - @@ -29,7 +28,6 @@ Time it takes to reload the weapon in seconds - diff --git a/resources/Schema/Components/Button.xml b/resources/Schema/Components/Button.xml deleted file mode 100644 index cbfd80d4..00000000 --- a/resources/Schema/Components/Button.xml +++ /dev/null @@ -1,3 +0,0 @@ - - \ No newline at end of file diff --git a/resources/Schema/Components/Button.xsd b/resources/Schema/Components/Button.xsd deleted file mode 100644 index 7d97fef1..00000000 --- a/resources/Schema/Components/Button.xsd +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - Makes sprites klickable. - - - \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointGameMode.xml b/resources/Schema/Components/CapturePointGameMode.xml deleted file mode 100644 index 3104e71f..00000000 --- a/resources/Schema/Components/CapturePointGameMode.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - 0.0 - 8.0 - \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointGameMode.xsd b/resources/Schema/Components/CapturePointGameMode.xsd deleted file mode 100644 index 8b81d67a..00000000 --- a/resources/Schema/Components/CapturePointGameMode.xsd +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - The time since the last respawn wave. Players will be spawned when this reaches MaxRespawnTime. - - - Players will be spawned when RespawnTime reaches this. - - - - - \ No newline at end of file diff --git a/resources/Schema/Components/DashAbility.xml b/resources/Schema/Components/DashAbility.xml index a71e4e52..a313c447 100644 --- a/resources/Schema/Components/DashAbility.xml +++ b/resources/Schema/Components/DashAbility.xml @@ -1,5 +1,4 @@ 2.0 - 0.0 \ No newline at end of file diff --git a/resources/Schema/Components/DashAbility.xsd b/resources/Schema/Components/DashAbility.xsd index 6fc59c77..4273cc71 100644 --- a/resources/Schema/Components/DashAbility.xsd +++ b/resources/Schema/Components/DashAbility.xsd @@ -10,10 +10,7 @@ - This is the max cooldown on dash - - - This is the current cooldown on dash + This is the cooldown on dash diff --git a/resources/Schema/Components/DefenderWeapon.xml b/resources/Schema/Components/DefenderWeapon.xml deleted file mode 100755 index 998f3bde..00000000 --- a/resources/Schema/Components/DefenderWeapon.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 8 - 8 - 64 - 64 - 90 - 0.174533 - 10 - 120 - 0.01 - 0.5 - - false - 0 - \ No newline at end of file diff --git a/resources/Schema/Components/DefenderWeapon.xsd b/resources/Schema/Components/DefenderWeapon.xsd deleted file mode 100755 index 3fe5a64a..00000000 --- a/resources/Schema/Components/DefenderWeapon.xsd +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - Ammo currently loaded into the magazine - - - Max number of rounds in a magazine - - - Current ammo carried - - - Maximum ammo able to be carried - - - Damage dealt if all shotgun pellets hit - - - Spread angle in radians - - - - Rate of fire in rounds per minute - - - View punch in radians for each shell fired - - - Time it takes to load ONE SHELL into the weapon in seconds - - - - - - - - diff --git a/resources/Schema/Components/DoubleJump.xml b/resources/Schema/Components/DoubleJump.xml deleted file mode 100644 index bb0d3bc7..00000000 --- a/resources/Schema/Components/DoubleJump.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - 4.0 - \ No newline at end of file diff --git a/resources/Schema/Components/DoubleJump.xsd b/resources/Schema/Components/DoubleJump.xsd deleted file mode 100644 index 65ff0419..00000000 --- a/resources/Schema/Components/DoubleJump.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - Enables a Player to double jump. - - - - Vertical velocity set on double jump. - - - - - \ No newline at end of file diff --git a/resources/Schema/Components/Menu.xml b/resources/Schema/Components/Menu.xml deleted file mode 100644 index f17427b8..00000000 --- a/resources/Schema/Components/Menu.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/resources/Schema/Components/Menu.xsd b/resources/Schema/Components/Menu.xsd deleted file mode 100644 index 18ea8565..00000000 --- a/resources/Schema/Components/Menu.xsd +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - Attach this to the center point of a menu that uses several pages. - - - \ No newline at end of file diff --git a/resources/Schema/Components/Model.xml b/resources/Schema/Components/Model.xml index f81c8210..4b77dacb 100644 --- a/resources/Schema/Components/Model.xml +++ b/resources/Schema/Components/Model.xml @@ -8,5 +8,4 @@ true true true - 3.0 \ No newline at end of file diff --git a/resources/Schema/Components/Model.xsd b/resources/Schema/Components/Model.xsd index 31203ff6..9c0cd519 100644 --- a/resources/Schema/Components/Model.xsd +++ b/resources/Schema/Components/Model.xsd @@ -33,9 +33,6 @@ Whether the model should use the Glowmap or not - - Intensity of the glow map - diff --git a/resources/Schema/Components/Page.xml b/resources/Schema/Components/Page.xml deleted file mode 100644 index db7b9cc2..00000000 --- a/resources/Schema/Components/Page.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - 0 - \ No newline at end of file diff --git a/resources/Schema/Components/Page.xsd b/resources/Schema/Components/Page.xsd deleted file mode 100644 index 777124a2..00000000 --- a/resources/Schema/Components/Page.xsd +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - Use this on a child to a Menu entity and make sure that ID is not the same as other pages. - - - - - - - - \ No newline at end of file diff --git a/resources/Schema/Components/Player.xml b/resources/Schema/Components/Player.xml index b50274ac..00cff257 100644 --- a/resources/Schema/Components/Player.xml +++ b/resources/Schema/Components/Player.xml @@ -2,7 +2,5 @@ 3 1.5 - 4.0 - \ No newline at end of file diff --git a/resources/Schema/Components/Player.xsd b/resources/Schema/Components/Player.xsd index 006ae9d7..1b33d222 100644 --- a/resources/Schema/Components/Player.xsd +++ b/resources/Schema/Components/Player.xsd @@ -11,11 +11,7 @@ - - Vertical velocity set when jumping. - - diff --git a/resources/Schema/Components/SpriteIndicator.xml b/resources/Schema/Components/SpriteIndicator.xml deleted file mode 100644 index cbed22f0..00000000 --- a/resources/Schema/Components/SpriteIndicator.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - 10 - false - \ No newline at end of file diff --git a/resources/Schema/Components/SpriteIndicator.xsd b/resources/Schema/Components/SpriteIndicator.xsd deleted file mode 100644 index bd8c1038..00000000 --- a/resources/Schema/Components/SpriteIndicator.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - Billbord a Sprite around global Y axis - - - - - - Add a Team component to this Entity or Parent to make it visible only for that team - - - - - \ No newline at end of file diff --git a/resources/Schema/Components/Weapon.xml b/resources/Schema/Components/Weapon.xml new file mode 100644 index 00000000..38c6fce9 --- /dev/null +++ b/resources/Schema/Components/Weapon.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Weapon.xsd b/resources/Schema/Components/Weapon.xsd new file mode 100644 index 00000000..8bddd8a9 --- /dev/null +++ b/resources/Schema/Components/Weapon.xsd @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/WeaponAttachment.xml b/resources/Schema/Components/WeaponAttachment.xml deleted file mode 100644 index 8867b2b7..00000000 --- a/resources/Schema/Components/WeaponAttachment.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/resources/Schema/Components/WeaponAttachment.xsd b/resources/Schema/Components/WeaponAttachment.xsd deleted file mode 100644 index 3b1291ae..00000000 --- a/resources/Schema/Components/WeaponAttachment.xsd +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - Combine with a spawner to define a weapon attachment point - - - - The weapon component type this attachment refers to - - - - - - \ No newline at end of file diff --git a/resources/Schema/Entities/AmmoPickup.xml b/resources/Schema/Entities/AmmoPickup.xml index bebde467..1d1435f7 100644 --- a/resources/Schema/Entities/AmmoPickup.xml +++ b/resources/Schema/Entities/AmmoPickup.xml @@ -2,18 +2,18 @@ + Models/Props/PickUps/AmmoPickUp.mesh - 8 - + 0.1 + - - - + + diff --git a/resources/Schema/Entities/AssaultWeaponView.xml b/resources/Schema/Entities/AssaultWeaponView.xml deleted file mode 100755 index 4b985fbb..00000000 --- a/resources/Schema/Entities/AssaultWeaponView.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectView.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - diff --git a/resources/Schema/Entities/AssaultWeaponWorld.xml b/resources/Schema/Entities/AssaultWeaponWorld.xml deleted file mode 100755 index 6fcb97b3..00000000 --- a/resources/Schema/Entities/AssaultWeaponWorld.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorld.xml - - - - - - - - diff --git a/resources/Schema/Entities/Button.xml b/resources/Schema/Entities/Button.xml deleted file mode 100644 index 21f64334..00000000 --- a/resources/Schema/Entities/Button.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - Textures/Core/White.png - - - - - - - - - - - - Play - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - diff --git a/resources/Schema/Entities/DefenderShield.xml b/resources/Schema/Entities/DefenderShield.xml deleted file mode 100755 index da760e72..00000000 --- a/resources/Schema/Entities/DefenderShield.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - Models/Core/UnitPlane.mesh - - - - - - - - - - - - - - Models/Core/UnitHexagon.mesh - - true - - - - - - - - - - - - diff --git a/resources/Schema/Entities/DefenderWeaponView.xml b/resources/Schema/Entities/DefenderWeaponView.xml deleted file mode 100755 index f6b6e89d..00000000 --- a/resources/Schema/Entities/DefenderWeaponView.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - R_Arm_Weapon_Joint - - - - Models/Weapons/Blue/DefenderGunBlue.mesh - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectView.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - diff --git a/resources/Schema/Entities/DefenderWeaponViewRed.xml b/resources/Schema/Entities/DefenderWeaponViewRed.xml deleted file mode 100755 index b5b1c322..00000000 --- a/resources/Schema/Entities/DefenderWeaponViewRed.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - R_Arm_Weapon_Joint - - - - Models/Weapons/Red/DefenderGunRed.mesh - - - - - - - - - - - Schema/Entities/RayRed.xml - - - - - - - - - - - Schema/Entities/ReloadEffectView.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - diff --git a/resources/Schema/Entities/DefenderWeaponWorld.xml b/resources/Schema/Entities/DefenderWeaponWorld.xml deleted file mode 100755 index 826301b4..00000000 --- a/resources/Schema/Entities/DefenderWeaponWorld.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - R_Arm_Weapon_Joint - - - - Models/Weapons/Blue/DefenderGunBlue.mesh - - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorld.xml - - - - - - - - diff --git a/resources/Schema/Entities/DefenderWeaponWorldRed.xml b/resources/Schema/Entities/DefenderWeaponWorldRed.xml deleted file mode 100755 index 7f697304..00000000 --- a/resources/Schema/Entities/DefenderWeaponWorldRed.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - R_Arm_Weapon_Joint - - - - Models/Weapons/Red/DefenderGunRed.mesh - - - - - - - - - - - - Schema/Entities/RayRed.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorld.xml - - - - - - - - diff --git a/resources/Schema/Entities/GameMap.xml b/resources/Schema/Entities/GameMap.xml index c3a16361..84a1e363 100644 --- a/resources/Schema/Entities/GameMap.xml +++ b/resources/Schema/Entities/GameMap.xml @@ -144,7 +144,7 @@ - + @@ -206,16 +206,14 @@ - + - - - + diff --git a/resources/Schema/Entities/HealthPickup.xml b/resources/Schema/Entities/HealthPickup.xml index b4b83392..c6fbc4f4 100644 --- a/resources/Schema/Entities/HealthPickup.xml +++ b/resources/Schema/Entities/HealthPickup.xml @@ -2,18 +2,18 @@ + Models/Props/PickUps/HealthPickUp.mesh - 8 - + 0.1 + - - - + + diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index 41474568..84aaa03a 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -10,7 +10,7 @@ - Schema/Entities/PlayerRed.xml + Schema/Entities/Player.xml @@ -118,6 +118,257 @@ + + + + + + + + 600 + + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 1 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 1.9569972344146196 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 1.8055945618467364 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 28ace561..be6009ba 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -7,40 +7,29 @@ - - - + 600 - - 52.867678870419283 - - + 5 - - - - + - - 0.10000000149011612 - 300 - + @@ -71,7 +60,6 @@ Textures/Weapons/Crosshair/SmallThickHoleDot.png false - @@ -122,7 +110,6 @@ Textures/HealthHUD3.png - @@ -148,7 +135,6 @@ Textures/Core/UnitHexagon.png - @@ -166,7 +152,6 @@ Textures/Core/UnitHexagon_Rotated.png - @@ -182,7 +167,6 @@ Textures/Core/UnitHexagon.png - @@ -201,7 +185,6 @@ Textures/Core/UnitHexagon_Rotated.png - @@ -217,7 +200,6 @@ Textures/Core/UnitHexagon.png - @@ -235,7 +217,6 @@ Textures/Core/UnitHexagon_Rotated.png - @@ -251,7 +232,6 @@ Textures/Core/UnitHexagon.png - @@ -269,7 +249,6 @@ Textures/Core/UnitHexagon_Rotated.png - @@ -285,7 +264,6 @@ Textures/Core/UnitHexagon.png - @@ -301,7 +279,6 @@ Textures/Core/UnitHexagon_Rotated.png - @@ -327,7 +304,6 @@ - Fonts/DroidSans.ttf,64 @@ -340,7 +316,6 @@ - Fonts/DroidSans.ttf,64 @@ -355,7 +330,6 @@ - Fonts/DroidSans.ttf,64 @@ -375,41 +349,111 @@ Idle - 1.9408570429715581 + 1.6050530664521858 1 - - Models/Characters/Assault/FirstPerson.mesh + true - + - - DefenderWeapon - - - Schema/Entities/DefenderWeaponView.xml - - + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + - - - - - - AssaultWeapon - - - Schema/Entities/AssaultWeaponView.xml - - - - + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + @@ -417,10 +461,7 @@ - - 0.10000000149011612 - 300 - + Models/Widgets/Camera.mesh false @@ -436,16 +477,13 @@ Idle - 1.5631122524686134 + 1.620305457513453 1 - - AimRifle - Models/Characters/Assault/AssaultAnimations.mesh @@ -454,35 +492,41 @@ - + - - DefenderWeapon - - - - - - Schema/Entities/DefenderWeaponWorld.xml - - + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + - - - - - - AssaultWeapon - - - - - - Schema/Entities/AssaultWeaponWorld.xml - - - - + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + @@ -528,37 +572,6 @@ - - - - Textures/Icons/Arrow.png - false - - - - - - 50 - true - - - - - - - - - - - - Schema/Entities/DefenderShield.xml - - - - - - - diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index c46b9d79..d9839e9f 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -7,40 +7,29 @@ - - - + 600 - - 22.22055262342397 - - + 5 - - - - + - - 0.10000000149011612 - 300 - + @@ -71,7 +60,6 @@ Textures/Weapons/Crosshair/SmallThickHoleDot.png false - @@ -122,7 +110,6 @@ Textures/HealthHUD3.png - @@ -148,7 +135,6 @@ Textures/Core/UnitHexagon.png - @@ -166,7 +152,6 @@ Textures/Core/UnitHexagon_Rotated.png - @@ -182,7 +167,6 @@ Textures/Core/UnitHexagon.png - @@ -201,7 +185,6 @@ Textures/Core/UnitHexagon_Rotated.png - @@ -217,7 +200,6 @@ Textures/Core/UnitHexagon.png - @@ -235,7 +217,6 @@ Textures/Core/UnitHexagon_Rotated.png - @@ -251,7 +232,6 @@ Textures/Core/UnitHexagon.png - @@ -269,7 +249,6 @@ Textures/Core/UnitHexagon_Rotated.png - @@ -285,7 +264,6 @@ Textures/Core/UnitHexagon.png - @@ -301,7 +279,6 @@ Textures/Core/UnitHexagon_Rotated.png - @@ -327,7 +304,6 @@ - Fonts/DroidSans.ttf,64 @@ -340,7 +316,6 @@ - Fonts/DroidSans.ttf,64 @@ -355,7 +330,6 @@ - Fonts/DroidSans.ttf,64 @@ -375,41 +349,111 @@ Idle - 1.1978087298230946 + 1.6050530664521858 1 - - Models/Characters/Assault/FirstPerson.mesh + true - + - - DefenderWeapon - - - Schema/Entities/DefenderWeaponViewRed.xml - - + + R_Arm_Weapon_Joint + + + Models/Weapons/Red/AssaultWeaponRed.mesh + true + + + + + - - - - - - AssaultWeapon - - - Schema/Entities/AssaultWeaponView.xml - - - - + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectViewRed.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + @@ -417,10 +461,7 @@ - - 0.10000000149011612 - 300 - + Models/Widgets/Camera.mesh false @@ -436,16 +477,13 @@ Idle - 0.69274608502888668 + 1.620305457513453 1 - - AimRifle - Models/Characters/Assault/AssaultAnimations.mesh @@ -454,35 +492,41 @@ - + - - DefenderWeapon - - - - - - Schema/Entities/DefenderWeaponWorldRed.xml - - + + R_Arm_Weapon_Joint + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + - - - - - - AssaultWeapon - - - - - - Schema/Entities/AssaultWeaponWorld.xml - - - - + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorldRed.xml + + + + + + @@ -521,44 +565,13 @@ - + - - - - Textures/Icons/Arrow.png - false - - - - - - 50 - true - - - - - - - - - - - - Schema/Entities/DefenderShield.xml - - - - - - - diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 0aa2fbe7..40951468 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -77,6 +77,18 @@ + + + + Sound Test + Fonts/DroidSans.ttf,64 + + + + + + + @@ -93,7 +105,7 @@ - + @@ -168,7 +180,7 @@ - + @@ -213,7 +225,7 @@ - + @@ -277,7 +289,7 @@ - + @@ -309,7 +321,7 @@ - + @@ -659,7 +671,7 @@ - + @@ -706,7 +718,7 @@ - + @@ -766,7 +778,7 @@ - + @@ -813,7 +825,7 @@ - + @@ -859,7 +871,7 @@ - + @@ -906,7 +918,7 @@ - + @@ -953,7 +965,7 @@ - + @@ -1015,7 +1027,7 @@ Models/Core/UnitCube.mesh - + true @@ -1065,7 +1077,7 @@ Models/Core/UnitCube.mesh - + true @@ -1155,7 +1167,7 @@ Models/Core/UnitCube.mesh - + true @@ -1205,7 +1217,7 @@ Models/Core/UnitCube.mesh - + true @@ -1367,7 +1379,7 @@ - + @@ -1376,7 +1388,7 @@ true - 0.8256214817261025 + 0.75205058136495551 3.7999999523162842 true @@ -1423,7 +1435,7 @@ - + @@ -1432,7 +1444,7 @@ - 1.8641349174045843 + 1.2019563319790627 Models/Characters/Assault/AssaultTPose.mesh @@ -1475,7 +1487,7 @@ - + @@ -1486,7 +1498,7 @@ true - 1.8641349174045843 + 0.68540211563899389 true @@ -1531,7 +1543,7 @@ - + @@ -1541,7 +1553,7 @@ true - 1.2301962937648341 + 0.95150063648635763 10 3 @@ -1589,7 +1601,7 @@ - + @@ -1599,7 +1611,7 @@ true - 3.4214855659573402 + 1.3515288978624223 true 5 true @@ -1666,10 +1678,10 @@ - Models/Core/UnitCube.mesh + @@ -1780,7 +1792,7 @@ true - 0.8256214817261025 + 1.3682019578975679 3.7999999523162842 true @@ -1824,12 +1836,12 @@ - Models/AssaultAnimated.mesh + @@ -2083,7 +2095,7 @@ Textures/Core/UnitHexagon.png - + @@ -2095,7 +2107,7 @@ 1 - + Textures/Core/UnitHexagon_Rotated.png @@ -2133,355 +2145,6 @@ - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - - - - - - - - - - Textures/Core/ErrorTexture.png - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Play - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Host - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Connect - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Settings - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Quit - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - 1 - - - - - - - - - - Textures/Core/ErrorTexture.png - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - 1920x1080 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - 1280x720 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - 854x480 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - FullScreen - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - - - Menu test area - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - Sound Test - Fonts/DroidSans.ttf,64 - - - - - - - diff --git a/resources/Schema/Entities/TestMenu.xml b/resources/Schema/Entities/TestMenu.xml deleted file mode 100644 index 73678601..00000000 --- a/resources/Schema/Entities/TestMenu.xml +++ /dev/null @@ -1,299 +0,0 @@ - - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - - - - - - - - - - - - - - - - - - - - - Textures/Core/ErrorTexture.png - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Play - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Host - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Connect - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Settings - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Quit - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - 1 - - - - - - - - - - Textures/Core/ErrorTexture.png - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Resolution - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Option2 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - Textures/Core/White.png - - - - - - - - - - - Butts - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - - diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 0965ef89..9ea264d1 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -47,11 +47,6 @@ - - - - - diff --git a/resources/Schema/Types/WeaponSlotEnum.xsd b/resources/Schema/Types/WeaponSlotEnum.xsd deleted file mode 100644 index 6713ca9d..00000000 --- a/resources/Schema/Types/WeaponSlotEnum.xsd +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/resources/Shaders/DrawColorCorrection.frag.glsl b/resources/Shaders/DrawColorCorrection.frag.glsl index d8273547..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,15 +17,23 @@ void main() { vec4 hdrColor = texture(SceneTexture, Input.TextureCoordinate); vec4 bloomColor = texture(BloomTexture, Input.TextureCoordinate); - - //hdrColor = hdrColor * SSAO; + 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)); + fragmentColor = vec4(result, 1.0); //fragmentColor = hdrColor; //fragmentColor = bloomColor; diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index aa45d118..471ee20b 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -1,7 +1,5 @@ #version 430 -#define MIN_AMBIENT_LIGHT 0.3 - uniform mat4 M; uniform mat4 V; uniform mat4 P; @@ -11,20 +9,15 @@ uniform vec2 ScreenDimensions; uniform vec4 FillColor; uniform vec4 AmbientColor; uniform float FillPercentage; -uniform float GlowIntensity = 10; -uniform vec3 CameraPosition; -uniform int SSAOQuality; uniform vec2 DiffuseUVRepeat; uniform vec2 NormalUVRepeat; uniform vec2 SpecularUVRepeat; uniform vec2 GlowUVRepeat; -layout (binding = 0) uniform sampler2D AOTexture; -layout (binding = 1) uniform sampler2D DiffuseTexture; -layout (binding = 2) uniform sampler2D NormalMapTexture; -layout (binding = 3) uniform sampler2D SpecularMapTexture; -layout (binding = 4) uniform sampler2D GlowMapTexture; -layout (binding = 5) uniform samplerCube CubeMap; +layout (binding = 0) uniform sampler2D DiffuseTexture; +layout (binding = 1) uniform sampler2D NormalMapTexture; +layout (binding = 2) uniform sampler2D SpecularMapTexture; +layout (binding = 3) uniform sampler2D GlowMapTexture; #define TILE_SIZE 16 @@ -79,7 +72,7 @@ struct LightResult { }; float CalcAttenuation(float radius, float dist, float falloff) { - return 1.0 - smoothstep(radius * falloff, radius, dist); + return 1.0 - smoothstep(radius * 0.3, radius, dist); } vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { @@ -126,8 +119,6 @@ vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textu void main() { - float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy) >> int(SSAOQuality), 0).r; - ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate * DiffuseUVRepeat); vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate * GlowUVRepeat); vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate * SpecularUVRepeat); @@ -135,18 +126,14 @@ void main() vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate * NormalUVRepeat, NormalMapTexture); normal = normalize(normal); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); - vec4 viewVec = normalize(-position); - vec3 I = normalize(vec3(M * vec4(Input.Position, 1.0)) - CameraPosition); - vec3 R = reflect(-I, Input.Normal); - //R = vec3(P * vec4(R, 1.0)); - vec4 reflectionColor = texture(CubeMap, R); + vec4 viewVec = normalize(-position); vec2 tilePos; tilePos.x = int(gl_FragCoord.x/TILE_SIZE); tilePos.y = int(gl_FragCoord.y/TILE_SIZE); LightResult totalLighting; - totalLighting.Diffuse = vec4(AmbientColor.rgb * ao, 1.0); + totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); int start = int(LightGrids.Data[currentTile].Start); @@ -164,15 +151,12 @@ void main() } else if (light.Type == 2) { //Directional light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); } - totalLighting.Diffuse += vec4(light_result.Diffuse.rgb * ao, light_result.Diffuse.a); - totalLighting.Specular += vec4(light_result.Specular.rgb * ao, light_result.Specular.a); + totalLighting.Diffuse += light_result.Diffuse; + totalLighting.Specular += light_result.Specular; } vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); - float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; - vec4 reflectionTotal = reflectionColor * (1-specularTexel.a) * color_result.a; - color_result = color_result * clamp(1/specularTexel.a, 0, 1) + reflectionTotal; //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; @@ -182,10 +166,9 @@ void main() color_result += FillColor; } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - //sceneColor = vec4(reflectionColor.xyz, 1); - color_result.xyz += glowTexel.xyz*GlowIntensity; + color_result += glowTexel*3; - bloomColor = vec4(max(color_result.xyz - 1.0, 0.0), clamp(color_result.a, 0, 1)); + bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); //Tiled Debug Code /* diff --git a/resources/Shaders/ForwardPlus.vert.glsl b/resources/Shaders/ForwardPlus.vert.glsl index 26686222..d475d825 100644 --- a/resources/Shaders/ForwardPlus.vert.glsl +++ b/resources/Shaders/ForwardPlus.vert.glsl @@ -23,12 +23,12 @@ out VertexData{ void main() { gl_Position = P*V*M * vec4(Position, 1.0); - mat4 TIM = transpose(inverse(M)); + Output.Position = Position; Output.TextureCoordinate = TextureCoords; - Output.Normal = vec3(TIM * vec4(Normal, 0.0)); - Output.Tangent = vec3(TIM * vec4(Tangent, 0.0)); - Output.BiTangent = vec3(TIM * vec4(BiTangent, 0.0)); + Output.Normal = vec3(M * vec4(Normal, 0.0)); + Output.Tangent = vec3(M * vec4(Tangent, 0.0)); + Output.BiTangent = vec3(M * vec4(BiTangent, 0.0)); Output.ExplosionColor = vec4(1.0); Output.ExplosionPercentageElapsed = 0.0; } \ No newline at end of file diff --git a/resources/Shaders/ForwardPlusShieldCheck.frag.glsl b/resources/Shaders/ForwardPlusShieldCheck.frag.glsl deleted file mode 100644 index 35db495b..00000000 --- a/resources/Shaders/ForwardPlusShieldCheck.frag.glsl +++ /dev/null @@ -1,207 +0,0 @@ -#version 430 - -#define MIN_AMBIENT_LIGHT 0.3 - -uniform mat4 M; -uniform mat4 V; -uniform mat4 P; -uniform vec4 Color; -uniform vec4 DiffuseColor; -uniform vec2 ScreenDimensions; -uniform vec4 FillColor; -uniform vec4 AmbientColor; -uniform float FillPercentage; -uniform float GlowIntensity = 10; -uniform vec3 CameraPosition; -uniform int SSAOQuality; - -uniform vec2 DiffuseUVRepeat; -uniform vec2 NormalUVRepeat; -uniform vec2 SpecularUVRepeat; -uniform vec2 GlowUVRepeat; -layout (binding = 0) uniform sampler2D AOTexture; -layout (binding = 1) uniform sampler2D DiffuseTexture; -layout (binding = 2) uniform sampler2D NormalMapTexture; -layout (binding = 3) uniform sampler2D SpecularMapTexture; -layout (binding = 4) uniform sampler2D GlowMapTexture; -layout (binding = 5) uniform samplerCube CubeMap; -layout (binding = 31) uniform sampler2D ShieldBuffer; - -#define TILE_SIZE 16 - -struct LightSource { - vec4 Position; - vec4 Direction; - vec4 Color; - float Radius; - float Intensity; - float Falloff; - int Type; -}; - -layout (std430, binding = 1) buffer LightBuffer -{ - LightSource List[]; -} LightSources; - -struct LightGrid { - float Start; - float Amount; - vec2 Padding; -}; - -layout (std430, binding = 2) buffer LightGridBuffer -{ - LightGrid Data[]; -} LightGrids; - -layout (std430, binding = 4) buffer LightIndexBuffer -{ - float LightIndex[]; -}; - - -in VertexData{ - vec3 Position; - vec3 Normal; - vec3 Tangent; - vec3 BiTangent; - vec2 TextureCoordinate; - vec4 ExplosionColor; - float ExplosionPercentageElapsed; -}Input; - -out vec4 sceneColor; -out vec4 bloomColor; - -struct LightResult { - vec4 Diffuse; - vec4 Specular; -}; - -float CalcAttenuation(float radius, float dist, float falloff) { - return 1.0 - smoothstep(radius * falloff, radius, dist); -} - -vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { - vec4 R = normalize( reflect(-lightVec, normal)); - float RdotV = max( dot(R, viewVec), 0.0); - return lightColor * pow(RdotV, 90.0); -} - -vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) { - float power = max( dot(normal, lightVec), 0.0); - return lightColor * power; -} - -LightResult CalcPointLightSource(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal, float falloff) -{ - vec4 L = lightPos - position; - float dist = length(L); - L = normalize(L); - - float attenuation = CalcAttenuation(lightRadius, dist, falloff); - - LightResult result; - result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity; - result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity; - return result; -} - -LightResult CalcDirectionalLightSource(vec4 direction, vec4 color, float intensity, vec4 viewVec, vec4 vertNormal) -{ - vec4 L = normalize( -vec4(direction.xyz, 0) ); - - LightResult result; - result.Diffuse = CalcDiffuse(color, L, vertNormal) * intensity; - result.Specular = CalcSpecular(color, viewVec, L, vertNormal) * intensity; - return result; -} - -vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textureCoordinate, sampler2D normalMap) -{ - mat3 TBN = mat3(tangent, bitangent, normal); - vec3 NormalMap = texture(normalMap, textureCoordinate).xyz * 2.0 - vec3(1.0); - return vec4(TBN * normalize(NormalMap), 0.0); -} - -void main() -{ - float shieldDepthValue = texelFetch(ShieldBuffer, ivec2(gl_FragCoord.xy), 0).r; - - if(shieldDepthValue < gl_FragCoord.z){ - discard; - } - - float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy) >> int(SSAOQuality), 0).r; - ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); - vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate * DiffuseUVRepeat); - vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate * GlowUVRepeat); - vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate * SpecularUVRepeat); - vec4 position = V * M * vec4(Input.Position, 1.0); - vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate * NormalUVRepeat, NormalMapTexture); - normal = normalize(normal); - //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); - vec4 viewVec = normalize(-position); - vec3 I = normalize(vec3(M * vec4(Input.Position, 1.0)) - CameraPosition); - vec3 R = reflect(-I, Input.Normal); - //R = vec3(P * vec4(R, 1.0)); - vec4 reflectionColor = texture(CubeMap, R); - - vec2 tilePos; - tilePos.x = int(gl_FragCoord.x/TILE_SIZE); - tilePos.y = int(gl_FragCoord.y/TILE_SIZE); - - LightResult totalLighting; - totalLighting.Diffuse = vec4(AmbientColor.rgb * ao, 1.0); - int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); - - int start = int(LightGrids.Data[currentTile].Start); - int amount = int(LightGrids.Data[currentTile].Amount); - - for(int i = start; i < start + amount; i++) { - - int l = int(LightIndex[i]); - LightSource light = LightSources.List[l]; - - LightResult light_result; - //These if statements should be removed. - if(light.Type == 1) { // point - light_result = CalcPointLightSource(V * light.Position, light.Radius, light.Color, light.Intensity, viewVec, position, normal, light.Falloff); - } else if (light.Type == 2) { //Directional - light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); - } - totalLighting.Diffuse += vec4(light_result.Diffuse.rgb * ao, light_result.Diffuse.a); - totalLighting.Specular += vec4(light_result.Specular.rgb * ao, light_result.Specular.a); - } - - vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); - color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); - float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; - vec4 reflectionTotal = reflectionColor * (1-specularTexel.a) * color_result.a; - color_result = color_result * clamp(1/specularTexel.a, 0, 1) + reflectionTotal; - //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; - - - float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; - - if(pos <= FillPercentage) { - color_result += FillColor; - } - sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - //sceneColor = vec4(reflectionColor.xyz, 1); - color_result.xyz += glowTexel.xyz*GlowIntensity; - - bloomColor = vec4(max(color_result.xyz - 1.0, 0.0), clamp(color_result.a, 0, 1)); - - //Tiled Debug Code - /* - if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 ) { - sceneColor += vec4(0.5, 0, 0, 0); - } else { - sceneColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/LightSources.List.length(), 0, 0, 1); - } - */ -} - - diff --git a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl index c67a9c99..e862d926 100644 --- a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl +++ b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl @@ -1,7 +1,5 @@ #version 430 -#define MIN_AMBIENT_LIGHT 0.3 - uniform mat4 M; uniform mat4 V; uniform mat4 P; @@ -11,7 +9,6 @@ uniform vec4 DiffuseColor; uniform vec4 FillColor; uniform vec4 Color; uniform vec4 AmbientColor; -uniform int SSAOQuality; //Get bineded at the same time as the textures uniform vec2 DiffuseUVRepeat1; @@ -26,20 +23,19 @@ uniform vec2 SpecularUVRepeat3; uniform vec2 GlowUVRepeat1; uniform vec2 GlowUVRepeat2; uniform vec2 GlowUVRepeat3; -layout (binding = 0) uniform sampler2D AOTexture; -layout (binding = 1) uniform sampler2D SplatMapTexture; -layout (binding = 2) uniform sampler2D DiffuseTexture1; -layout (binding = 3) uniform sampler2D DiffuseTexture2; -layout (binding = 4) uniform sampler2D DiffuseTexture3; -layout (binding = 5) uniform sampler2D NormalMapTexture1; -layout (binding = 6) uniform sampler2D NormalMapTexture2; -layout (binding = 7) uniform sampler2D NormalMapTexture3; -layout (binding = 8) uniform sampler2D SpecularMapTexture1; -layout (binding = 9) uniform sampler2D SpecularMapTexture2; -layout (binding = 10) uniform sampler2D SpecularMapTexture3; -layout (binding = 11) uniform sampler2D GlowMapTexture1; -layout (binding = 12) uniform sampler2D GlowMapTexture2; -layout (binding = 13) uniform sampler2D GlowMapTexture3; +layout (binding = 0) uniform sampler2D SplatMapTexture; +layout (binding = 1) uniform sampler2D DiffuseTexture1; +layout (binding = 2) uniform sampler2D DiffuseTexture2; +layout (binding = 3) uniform sampler2D DiffuseTexture3; +layout (binding = 4) uniform sampler2D NormalMapTexture1; +layout (binding = 5) uniform sampler2D NormalMapTexture2; +layout (binding = 6) uniform sampler2D NormalMapTexture3; +layout (binding = 7) uniform sampler2D SpecularMapTexture1; +layout (binding = 8) uniform sampler2D SpecularMapTexture2; +layout (binding = 9) uniform sampler2D SpecularMapTexture3; +layout (binding = 10) uniform sampler2D GlowMapTexture1; +layout (binding = 11) uniform sampler2D GlowMapTexture2; +layout (binding = 12) uniform sampler2D GlowMapTexture3; #define TILE_SIZE 16 @@ -178,9 +174,6 @@ vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, void main() { - float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy) >> int(SSAOQuality), 0).r; - ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); - vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); vec4 diffuseTexel = CalcBlendedTexel(splatTexel, DiffuseTexture1, DiffuseTexture2, DiffuseTexture3, @@ -202,7 +195,7 @@ void main() tilePos.y = int(gl_FragCoord.y/TILE_SIZE); LightResult totalLighting; - totalLighting.Diffuse = vec4(AmbientColor.rgb * ao, 1.0); + totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); int start = int(LightGrids.Data[currentTile].Start); @@ -220,8 +213,8 @@ void main() } else if (light.Type == 2) { //Directional light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); } - totalLighting.Diffuse += vec4(light_result.Diffuse.rgb * ao, light_result.Diffuse.a); - totalLighting.Specular += vec4(light_result.Specular.rgb * ao, light_result.Specular.a); + totalLighting.Diffuse += light_result.Diffuse; + totalLighting.Specular += light_result.Specular; } vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); diff --git a/resources/Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl b/resources/Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl deleted file mode 100644 index fa3af6ac..00000000 --- a/resources/Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl +++ /dev/null @@ -1,254 +0,0 @@ -#version 430 - -#define MIN_AMBIENT_LIGHT 0.3 - -uniform mat4 M; -uniform mat4 V; -uniform mat4 P; -uniform vec2 ScreenDimensions; -uniform float FillPercentage; -uniform vec4 DiffuseColor; -uniform vec4 FillColor; -uniform vec4 Color; -uniform vec4 AmbientColor; -uniform int SSAOQuality; - -//Get bineded at the same time as the textures -uniform vec2 DiffuseUVRepeat1; -uniform vec2 DiffuseUVRepeat2; -uniform vec2 DiffuseUVRepeat3; -uniform vec2 NormalUVRepeat1; -uniform vec2 NormalUVRepeat2; -uniform vec2 NormalUVRepeat3; -uniform vec2 SpecularUVRepeat1; -uniform vec2 SpecularUVRepeat2; -uniform vec2 SpecularUVRepeat3; -uniform vec2 GlowUVRepeat1; -uniform vec2 GlowUVRepeat2; -uniform vec2 GlowUVRepeat3; -layout (binding = 0) uniform sampler2D AOTexture; -layout (binding = 1) uniform sampler2D SplatMapTexture; -layout (binding = 2) uniform sampler2D DiffuseTexture1; -layout (binding = 3) uniform sampler2D DiffuseTexture2; -layout (binding = 4) uniform sampler2D DiffuseTexture3; -layout (binding = 5) uniform sampler2D NormalMapTexture1; -layout (binding = 6) uniform sampler2D NormalMapTexture2; -layout (binding = 7) uniform sampler2D NormalMapTexture3; -layout (binding = 8) uniform sampler2D SpecularMapTexture1; -layout (binding = 9) uniform sampler2D SpecularMapTexture2; -layout (binding = 10) uniform sampler2D SpecularMapTexture3; -layout (binding = 11) uniform sampler2D GlowMapTexture1; -layout (binding = 12) uniform sampler2D GlowMapTexture2; -layout (binding = 13) uniform sampler2D GlowMapTexture3; -layout (binding = 13) uniform sampler2D GlowMapTexture3; -layout (binding = 31) uniform samplerCube ShieldBuffer; - -#define TILE_SIZE 16 - -struct LightSource { - vec4 Position; - vec4 Direction; - vec4 Color; - float Radius; - float Intensity; - float Falloff; - int Type; -}; - -layout (std430, binding = 1) buffer LightBuffer -{ - LightSource List[]; -} LightSources; - -struct LightGrid { - float Start; - float Amount; - vec2 Padding; -}; - -layout (std430, binding = 2) buffer LightGridBuffer -{ - LightGrid Data[]; -} LightGrids; - -layout (std430, binding = 4) buffer LightIndexBuffer -{ - float LightIndex[]; -}; - - -in VertexData{ - vec3 Position; - vec3 Normal; - vec3 Tangent; - vec3 BiTangent; - vec2 TextureCoordinate; - vec4 ExplosionColor; - float ExplosionPercentageElapsed; -}Input; - -out vec4 sceneColor; -out vec4 bloomColor; - -struct LightResult { - vec4 Diffuse; - vec4 Specular; -}; - -float CalcAttenuation(float radius, float dist, float falloff) { - return 1.0 - smoothstep(radius * 0.3, radius, dist); -} - -vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { - vec4 R = normalize( reflect(-lightVec, normal)); - float RdotV = max( dot(R, viewVec), 0.0); - return lightColor * pow(RdotV, 90.0); -} - -vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) { - float power = max( dot(normal, lightVec), 0.0); - return lightColor * power; -} - -LightResult CalcPointLightSource(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal, float falloff) -{ - vec4 L = lightPos - position; - float dist = length(L); - L = normalize(L); - - float attenuation = CalcAttenuation(lightRadius, dist, falloff); - - LightResult result; - result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity; - result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity; - return result; -} - -LightResult CalcDirectionalLightSource(vec4 direction, vec4 color, float intensity, vec4 viewVec, vec4 vertNormal) -{ - vec4 L = normalize( -vec4(direction.xyz, 0) ); - - LightResult result; - result.Diffuse = CalcDiffuse(color, L, vertNormal) * intensity; - result.Specular = CalcSpecular(color, viewVec, L, vertNormal) * intensity; - return result; -} - -vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textureCoordinate, sampler2D normalMap) -{ - mat3 TBN = mat3(tangent, bitangent, normal); - vec3 NormalMap = texture(normalMap, textureCoordinate).xyz * 2.0 - vec3(1.0); - return vec4(TBN * normalize(NormalMap), 0.0); -} - -vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, - vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues){ - vec4 R_Channel = texture2D(R, Input.TextureCoordinate * R_TileValues); - vec4 G_Channel = texture2D(G, Input.TextureCoordinate * G_TileValues); - vec4 B_Channel = texture2D(B, Input.TextureCoordinate * B_TileValues); - - float total = blendValue.r + blendValue.g + blendValue.b; - float totalDiv = 1.0f / total; - blendValue.r = blendValue.r * totalDiv; - blendValue.g = blendValue.g * totalDiv; - blendValue.b = blendValue.b * totalDiv; - - return blendValue.r * R_Channel - + blendValue.g * G_Channel - + blendValue.b * B_Channel; -} - -vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, - vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues){ - mat3 TBN = mat3(Input.Tangent, Input.BiTangent, Input.Normal); - vec3 R_Channel = texture(R, Input.TextureCoordinate * R_TileValues).xyz * 2.0 - vec3(1.0); - vec3 G_Channel = texture(G, Input.TextureCoordinate * G_TileValues).xyz * 2.0 - vec3(1.0); - vec3 B_Channel = texture(B, Input.TextureCoordinate * B_TileValues).xyz * 2.0 - vec3(1.0); - - float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; - float totalDiv = 1 / total; - blendValue.r = blendValue.r * totalDiv; - blendValue.g = blendValue.g * totalDiv; - blendValue.b = blendValue.b * totalDiv; - - vec3 Normal_result = blendValue.r * R_Channel - + blendValue.g * G_Channel - + blendValue.b * B_Channel; - - return vec4(TBN * normalize(Normal_result), 0.0); -} - -void main() -{ - float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy) >> int(SSAOQuality), 0).r; - ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); - - vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); - - vec4 diffuseTexel = CalcBlendedTexel(splatTexel, DiffuseTexture1, DiffuseTexture2, DiffuseTexture3, - DiffuseUVRepeat1, DiffuseUVRepeat2, DiffuseUVRepeat3); - vec4 glowTexel = CalcBlendedTexel(splatTexel, GlowMapTexture1, GlowMapTexture2, GlowMapTexture3, - GlowUVRepeat1, GlowUVRepeat2, GlowUVRepeat3); - vec4 specularTexel = CalcBlendedTexel(splatTexel, SpecularMapTexture1, SpecularMapTexture2, SpecularMapTexture3, - SpecularUVRepeat1, SpecularUVRepeat2, SpecularUVRepeat3); - vec4 position = V * M * vec4(Input.Position, 1.0); - //vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, SplatMapTexture); - vec4 normal = V * CalcBlendedNormal(splatTexel, NormalMapTexture1, NormalMapTexture2, NormalMapTexture3, - NormalUVRepeat1, NormalUVRepeat2, NormalUVRepeat3); - normal = normalize(normal); - //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); - vec4 viewVec = normalize(-position); - - vec2 tilePos; - tilePos.x = int(gl_FragCoord.x/TILE_SIZE); - tilePos.y = int(gl_FragCoord.y/TILE_SIZE); - - LightResult totalLighting; - totalLighting.Diffuse = vec4(AmbientColor.rgb * ao, 1.0); - int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); - - int start = int(LightGrids.Data[currentTile].Start); - int amount = int(LightGrids.Data[currentTile].Amount); - - for(int i = start; i < start + amount; i++) { - - int l = int(LightIndex[i]); - LightSource light = LightSources.List[l]; - - LightResult light_result; - //These if statements should be removed. - if(light.Type == 1) { // point - light_result = CalcPointLightSource(V * light.Position, light.Radius, light.Color, light.Intensity, viewVec, position, normal, light.Falloff); - } else if (light.Type == 2) { //Directional - light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); - } - totalLighting.Diffuse += vec4(light_result.Diffuse.rgb * ao, light_result.Diffuse.a); - totalLighting.Specular += vec4(light_result.Specular.rgb * ao, light_result.Specular.a); - } - - vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); - color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); - //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; - - - float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; - - if(pos <= FillPercentage) { - color_result += FillColor; - } - sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - color_result += glowTexel*3; - - bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); - - //Tiled Debug Code - /* - if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 ) { - sceneColor += vec4(0.5, 0, 0, 0); - } else { - sceneColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/LightSources.List.length(), 0, 0, 1); - } - */ -} - - diff --git a/resources/Shaders/SSAO.frag.glsl b/resources/Shaders/SSAO.frag.glsl deleted file mode 100644 index 749881c4..00000000 --- a/resources/Shaders/SSAO.frag.glsl +++ /dev/null @@ -1,109 +0,0 @@ -#version 430 - -//Number of samples per pixel -uniform int uNumOfSamples; -//#define uNumOfSamples (11) - -//Number of turns around the cirle -uniform int uNumOfTurns; -//#define uNumOfTurns (7) - -layout (binding = 0) uniform sampler2D ViewSpaceZ; - -uniform vec4 uProjInfo; - -uniform float uProjScale; -//#define ProjScale 500 - -uniform float uRadius; -//#define uRadius 1.0f - -uniform float uBias; -//#define uBias 0.05f - -uniform float uContrast; -//#define uContrast 1.5f - -uniform float uIntensityScale; -//#define uIntensityScale 1.0f - -out float AO; - -vec3 getVSPosition(ivec2 ScreenSpaceCoord) { - float z = texelFetch(ViewSpaceZ, ScreenSpaceCoord, 0).r; - //Get the xy view space coordinates and add the z value from ViewSpaceZ buffer. - return vec3((uProjInfo[0] + (ScreenSpaceCoord.x * uProjInfo[1])) * z, (uProjInfo[2] + (ScreenSpaceCoord.y * uProjInfo[3])) * z, z); -} - -vec3 getVSFaceNormal(vec3 ViewSpacePosition) { - // Get tangets vector for the plane and ViewSpacePositin... don't ask how this functions works. It's pure magic. - // They do this and it just works... I would guess that they approximate the function of a plane from pixels close to the pixel were on now. - return normalize(cross(dFdx(ViewSpacePosition), dFdy(ViewSpacePosition))); -} - - -vec3 getSampleViewSpacePos(ivec2 ScreenSpaceCoord, int SampleIndex, float RotationAngle, float ScreenSpaceSampleRadius){ - // Pure Magic... - float alpha = float(SampleIndex) * (1.0 / uNumOfSamples); - - // Angle to where to sample - float angle = alpha * (uNumOfTurns * 6.28) + RotationAngle; - - //Lenght to were to sample - ScreenSpaceSampleRadius = ScreenSpaceSampleRadius * alpha; - - vec2 screenSpaceSampleOffsetVecor = vec2(cos(angle), sin(angle)); - - // Get texel coordinate on where to sample by going screenSpaceSampleOffsetVecor direction in ScreenSpaceSampleRadius units from ScreenSpaceCoord (the point being shaded); - ivec2 screenSpaceSampleTexel = ivec2(ScreenSpaceSampleRadius * screenSpaceSampleOffsetVecor) + ScreenSpaceCoord; - - return getVSPosition(screenSpaceSampleTexel); -} - - - -float sampleAO(ivec2 ScreenSpaceCoord, vec3 Origin, vec3 OriginNormal, float ScreenSpaceSampleRadius, int SampleIndex, float RotationAngle, float Radius) { - float radius2 = Radius * Radius; - vec3 sampleViewSpacePosition = getSampleViewSpacePos(ScreenSpaceCoord, SampleIndex, RotationAngle, ScreenSpaceSampleRadius); - - vec3 sampleVector = Origin - sampleViewSpacePosition; - - // vv = sampleVectorLenght ^ 2 - float vv = dot(sampleVector, sampleVector); - // vn = angle between sampleVector and Normal - float vn = dot(sampleVector, OriginNormal); - - const float epsilon = 0.0001f; - - // vv < radius2 if the vector is shorter then the radius; - // vn - bias, offset the angle to reduse self occlusion. - // epsilon is here to make divison by 0 impossible. - return float(vv < radius2) * max((vn - uBias) / (epsilon + vv), 0.0); - //float f = max(radius2 - vv, 0.0); - //return f * f * f * max((vn - uBias) / (epsilon + vv), 0.0); -} - - -void main() { - ivec2 originScreenCoord = ivec2(gl_FragCoord.xy); - - vec3 origin = getVSPosition(originScreenCoord); - - float radius = min(origin.z, uRadius); - - vec3 originNormal = getVSFaceNormal(origin); - - float screenSpaceSampleRadius = -uProjScale * radius / origin.z; - - float rotationAngleOffset = 30 * originScreenCoord.x ^ originScreenCoord.y + 10 * originScreenCoord.x * originScreenCoord.y; - - float sum = 0.0; - for (int i = 0; i < uNumOfSamples; i++) { - sum += sampleAO(originScreenCoord, origin, originNormal, screenSpaceSampleRadius, i, rotationAngleOffset, radius); - } - - //float A = max(0.0, 1.0 - sum * (2.0f / uNumOfSamples)); - float A = 1.0 - sum * (2.0f * uIntensityScale / float(uNumOfSamples)); - AO = clamp(pow(A, uContrast), 0.0f, 1.0f); - //AO = vec4(originNormal, 1.0f); -} diff --git a/resources/Shaders/SSAO.vert.glsl b/resources/Shaders/SSAO.vert.glsl deleted file mode 100644 index 346bc141..00000000 --- a/resources/Shaders/SSAO.vert.glsl +++ /dev/null @@ -1,13 +0,0 @@ -#version 430 - -layout (location = 0) in vec3 Position; - -out VertexData{ - vec2 TextureCoordinate; -}Output; - -void main() -{ - gl_Position = vec4(Position, 1.0); - Output.TextureCoordinate = (vec2(Position) + 1) / 2; -} \ No newline at end of file diff --git a/resources/Shaders/SSAOViewSpaceZ.frag.glsl b/resources/Shaders/SSAOViewSpaceZ.frag.glsl deleted file mode 100644 index d1bf6f17..00000000 --- a/resources/Shaders/SSAOViewSpaceZ.frag.glsl +++ /dev/null @@ -1,18 +0,0 @@ -#version 430 - -layout (binding = 0) uniform sampler2D DepthBuffer; -uniform vec3 ClipInfo; - -in VertexData{ - vec2 TextureCoordinate; -}Input; - -out float depthLinear; -//Just for Debug, should be depthLinear -//out vec4 fragmentColor; -void main() { - float depthSample = texture2D(DepthBuffer, Input.TextureCoordinate).r; - depthLinear = ClipInfo[0] / (ClipInfo[1] * depthSample + ClipInfo[2]); - //float depthLinear = (NearClip) / ( -depthSample + 1.0f); - //fragmentColor = vec4(depthLinear, depthLinear, depthLinear, 1.0f); -} \ No newline at end of file diff --git a/resources/Shaders/Sprite.frag.glsl b/resources/Shaders/Sprite.frag.glsl index 754be6ac..9ce2bbdf 100644 --- a/resources/Shaders/Sprite.frag.glsl +++ b/resources/Shaders/Sprite.frag.glsl @@ -7,8 +7,8 @@ uniform mat4 M; uniform mat4 V; uniform mat4 P; -layout (binding = 1) uniform sampler2D DiffuseTexture; -layout (binding = 2) uniform sampler2D GlowMapTexture; +layout (binding = 0) uniform sampler2D DiffuseTexture; +layout (binding = 1) uniform sampler2D GlowMapTexture; in VertexData{ diff --git a/resources/Shaders/SpriteShieldCheck.frag.glsl b/resources/Shaders/SpriteShieldCheck.frag.glsl deleted file mode 100644 index 754be6ac..00000000 --- a/resources/Shaders/SpriteShieldCheck.frag.glsl +++ /dev/null @@ -1,41 +0,0 @@ -#version 430 - -uniform vec4 Color; -uniform vec4 FillColor; -uniform float FillPercentage; -uniform mat4 M; -uniform mat4 V; -uniform mat4 P; - -layout (binding = 1) uniform sampler2D DiffuseTexture; -layout (binding = 2) uniform sampler2D GlowMapTexture; - - -in VertexData{ - vec3 Position; - vec3 Normal; - vec2 TextureCoordinate; -}Input; - - -out vec4 sceneColor; -out vec4 bloomColor; - -void main() -{ - vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate); - vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate); - - vec4 color_result = Color * diffuseTexel; - - float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; - if(pos <= FillPercentage) { - color_result = FillColor*diffuseTexel.a; - } - sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - - //bloomColor = vec4(clamp((glowTexel.xyz*3) - 1.0, 0, 100), 1.0); - bloomColor = vec4(1.0, 1.0, 1.0, 0.0); -} - - diff --git a/src/Engine/CMakeLists.txt b/src/Engine/CMakeLists.txt index e74214cf..19763310 100644 --- a/src/Engine/CMakeLists.txt +++ b/src/Engine/CMakeLists.txt @@ -3,7 +3,7 @@ project(TacticalZ-Engine) find_package(OpenGL REQUIRED) find_package(GLEW REQUIRED) find_package(GLFW REQUIRED) -find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono timer program_options) +find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono program_options) find_package(assimp REQUIRED) find_package(ZLIB REQUIRED) find_package(PNG REQUIRED) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 68d99d92..ab2098b7 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -207,7 +207,7 @@ bool RayVsModel(const Ray& ray, glm::vec3 v0 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); glm::vec3 v1 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); glm::vec3 v2 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); - float dist = outDistance; + float dist = INFINITY; float u; float v; if (RayVsTriangle(ray, v0, v1, v2, dist, u, v)) { @@ -366,8 +366,7 @@ bool AABBvsTriangle(const AABB& box, float verticalStepHeight, bool& isOnGround, glm::vec3& boxVelocity, - glm::vec3& outResolution, - bool resolveCollision) + 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. @@ -427,7 +426,7 @@ bool AABBvsTriangle(const AABB& box, //if projections don't overlap, return false. if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) { return false; - } else if (resolveCollision) { + } else { //Overwrite the smallest resolution if this is smaller. if (resolutionDist < resolveShortest.DistanceSq) { resolveShortest.Vector = glm::vec3(0.f); @@ -464,11 +463,6 @@ bool AABBvsTriangle(const AABB& box, if (glm::abs(t) > 1) { return false; } - - if (!resolveCollision) { - return true; - } - glm::vec3 cornerResolution = (1+t) * diagonal; //Overwrite the smallest resolution if cornerResolution is smaller. float lenSq = glm::length2(cornerResolution); @@ -543,8 +537,7 @@ bool AABBvsTriangles(const AABB& box, glm::vec3& boxVelocity, float verticalStepHeight, bool& isOnGround, - glm::vec3& outResolutionVector, - bool resolveCollision) + glm::vec3& outResolutionVector) { bool hit = false; @@ -560,7 +553,7 @@ bool AABBvsTriangles(const AABB& box, }; glm::vec3 outVec; bool collideWithGround = isOnGround; - if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec, resolveCollision)) { + if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec)) { hit = true; outResolutionVector += outVec; newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); @@ -576,44 +569,6 @@ bool AABBvsTriangles(const AABB& box, return hit; } -bool AABBvsTriangles(const AABB& box, - const RawModel::Vertex* modelVertices, - const std::vector& modelIndices, - const glm::mat4& modelMatrix, - glm::vec3& boxVelocity, - float verticalStepHeight, - bool& isOnGround, - glm::vec3& outResolutionVector) -{ - return AABBvsTriangles(box, - modelVertices, - modelIndices, - modelMatrix, - boxVelocity, - verticalStepHeight, - isOnGround, - outResolutionVector, - true); -} - -bool AABBvsTriangles(const AABB& box, - const RawModel::Vertex* modelVertices, - const std::vector& modelIndices, - const glm::mat4& modelMatrix) -{ - glm::vec3 vel, outres; - bool g; - return AABBvsTriangles(box, - modelVertices, - modelIndices, - modelMatrix, - vel, - 0.f, - g, - outres, - false); -} - boost::optional EntityAbsoluteAABB(EntityWrapper& entity, bool takeModelBox) { AABB modelSpaceBox; @@ -693,9 +648,8 @@ boost::optional EntityFirstHitByRay(const Ray& ray, std::vector boundingBox = Collision::EntityAbsoluteAABB(entity); if (!boundingBox) { return; } - ComponentWrapper& cTransform = entity["Transform"]; EntityAABB& boxA = *boundingBox; - bool everHitTheGround = false; - - auto prevPosIt = m_PrevPositions.find(entity); - if (prevPosIt != m_PrevPositions.end()) { - glm::vec3 size = boxA.Size(); - float diameter = std::min(size.x, size.z); - glm::vec3 prevOrigin = prevPosIt->second; - glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; - float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; - //If the entity has moved farther than the size of its box, we need to handle it specially. - if (rayLength > diameter) { - Ray ray(prevOrigin, toCurrentPos); - m_OctreeResult.clear(); - m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); - for (auto& boxB : m_OctreeResult) { - if (boxA.Entity == boxB.Entity) { - continue; - } - bool hit; - float dist; - if (boxB.Entity.HasComponent("Model")) { - RawModel* model; - std::string res = (std::string)boxB.Entity["Model"]["Resource"]; - try { - model = ResourceManager::Load(res); - } catch (const std::exception&) { - continue; - } - float u, v; - hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v); - } else { - hit = Collision::RayVsAABB(ray, boxB, dist); - } - if (hit && dist < rayLength) { - //Set the entity to where it was colliding, minus the maximum box size. - //TODO: Perhaps this should be done slightly more properly. - glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction(); - glm::vec3 resolve = newOriginPos - boxA.Origin(); - (glm::vec3&)cTransform["Position"] += resolve; - boxA = *Collision::EntityAbsoluteAABB(entity); - if (resolve.y > 0) { - everHitTheGround = true; - (bool)cPhysics["IsOnGround"] = true; - ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; - } - break; - } - } - } - } // 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) { @@ -87,13 +39,10 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity); glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"]; - bool notMovingxz = glm::all(glm::lessThan(glm::abs(glm::vec2(inOutVelocity.x, inOutVelocity.z)), glm::vec2(0.01f))) && prevPosIt != m_PrevPositions.end(); bool isOnGround = (bool)cPhysics["IsOnGround"]; float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { - //Move the position to previous position if it is not moving in the xz-plane, else resolve with the resolution vector. - (glm::vec3&)cTransform["Position"] += notMovingxz ? prevPosIt->second - boxA.Origin() : resolutionVector; - boxA = *Collision::EntityAbsoluteAABB(entity); + (glm::vec3&)cTransform["Position"] += resolutionVector; cPhysics["Velocity"] = inOutVelocity; if (isOnGround) { everHitTheGround = true; @@ -103,7 +52,6 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; - boxA = *Collision::EntityAbsoluteAABB(entity); if (resolutionVector.y > 0) { everHitTheGround = true; (bool)cPhysics["IsOnGround"] = true; @@ -116,6 +64,4 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c if (!everHitTheGround) { (bool)cPhysics["IsOnGround"] = false; } - - m_PrevPositions[entity] = boxA.Origin(); } diff --git a/src/Engine/Core/ComponentPool.cpp b/src/Engine/Core/ComponentPool.cpp index 059b2e38..7b465fbc 100644 --- a/src/Engine/Core/ComponentPool.cpp +++ b/src/Engine/Core/ComponentPool.cpp @@ -1,5 +1,7 @@ #include "Core/ComponentPool.h" + + ComponentWrapper ComponentPoolForwardIterator::operator*() const { char* data = &(*m_MemoryPoolIterator); @@ -30,34 +32,6 @@ ComponentPoolForwardIterator& ComponentPoolForwardIterator::operator++() return *this; } -ComponentPool::ComponentPool(const ComponentPool& other) - : m_ComponentInfo(other.m_ComponentInfo) - , m_Pool(other.m_Pool) - , m_EntityToComponent() -{ - // Update EntityToComponent pointers - for (char& ptr : m_Pool) { - EntityID entity = *reinterpret_cast(&ptr); - m_EntityToComponent[entity] = &ptr; - } - - // Duplicate strings - for (auto& name : m_ComponentInfo.StringFields) { - for (auto& c : *this) { - std::string& val = c[name]; - ComponentWrapper::SolidifyStrings(c); - } - } -} - -ComponentPool::~ComponentPool() -{ - // Destroy component data - for (auto& c : *this) { - ComponentWrapper::Destroy(c.Info, c.Data); - } -} - //const ::ComponentInfo& ComponentPool::ComponentInfo() const //{ // return m_ComponentInfo; @@ -65,19 +39,10 @@ ComponentPool::~ComponentPool() ComponentWrapper ComponentPool::Allocate(EntityID entity) { - // Allocate pool data char* data = m_Pool.Allocate(); - // Copy EntityID memcpy(data, &entity, sizeof(EntityID)); - m_EntityToComponent[entity] = data; - ComponentWrapper component(m_ComponentInfo, data); - - // Copy defaults - memcpy(component.Data, m_ComponentInfo.Defaults.get(), m_ComponentInfo.Stride); - ComponentWrapper::SolidifyStrings(component); - - return component; + return ComponentWrapper(m_ComponentInfo, data); } ComponentWrapper ComponentPool::GetByEntity(EntityID ent) @@ -92,7 +57,6 @@ bool ComponentPool::KnowsEntity(EntityID ent) void ComponentPool::Delete(ComponentWrapper& wrapper) { - ComponentWrapper::Destroy(wrapper.Info, wrapper.Data); m_EntityToComponent.erase(wrapper.EntityID); m_Pool.Free(wrapper.Data - sizeof(EntityID)); } diff --git a/src/Engine/Core/EntityFilePreprocessor.cpp b/src/Engine/Core/EntityFilePreprocessor.cpp index 592daedb..a1370dd2 100644 --- a/src/Engine/Core/EntityFilePreprocessor.cpp +++ b/src/Engine/Core/EntityFilePreprocessor.cpp @@ -185,9 +185,6 @@ void EntityFilePreprocessor::parseComponentInfo() field.Offset = fieldOffset; field.Stride = stride; compInfo.FieldsInOrder.push_back(name); - if (field.Type == "string") { - compInfo.StringFields.push_back(name); - } fieldOffset += stride; } @@ -204,7 +201,7 @@ void EntityFilePreprocessor::parseDefaults() for (auto& ci : m_ComponentInfo) { // Allocate memory for default values - ci.second.Defaults = boost::shared_array(new char[ci.second.Stride], std::bind(&ComponentWrapper::Destroy, ci.second, std::placeholders::_1)); + ci.second.Defaults = std::shared_ptr(new char[ci.second.Stride]); memset(ci.second.Defaults.get(), 0, ci.second.Stride); std::string componentName = ci.first; diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index b3bef55a..4b45b8d0 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -51,40 +51,6 @@ EntityWrapper EntityWrapper::FirstParentWithComponent(const std::string& compone return EntityWrapper::Invalid; } -EntityWrapper EntityWrapper::Clone(EntityWrapper parent /*= Invalid*/) -{ - if (!Valid()) { - return EntityWrapper::Invalid; - } - - EntityWrapper clone = cloneRecursive(*this, EntityWrapper::Invalid); - this->World->SetParent(clone.ID, parent.ID); - return clone; -} - -std::vector EntityWrapper::ChildrenWithComponent(const std::string& componentType) -{ - std::vector childrenWithComponent; - childrenWithComponentRecursive(componentType, *this, childrenWithComponent); - return childrenWithComponent; -} - -void EntityWrapper::DeleteChildren() -{ - auto itPair = this->World->GetDirectChildren(this->ID); - if (itPair.first == itPair.second) { - return; - } - - std::vector entitiesToDelete; - for (auto it = itPair.first; it != itPair.second; it++) { - entitiesToDelete.push_back(it->second); - } - for (auto& e : entitiesToDelete) { - this->World->DeleteEntity(e); - } -} - bool EntityWrapper::IsChildOf(EntityWrapper potentialParent) { EntityWrapper entity = *this; @@ -124,11 +90,6 @@ ComponentWrapper EntityWrapper::operator[](const char* componentName) } } -ComponentWrapper EntityWrapper::operator[](const std::string& componentName) -{ - return this->operator[](componentName.c_str()); -} - bool EntityWrapper::operator==(const EntityWrapper& e) const { return (this->ID == e.ID) && (this->World == e.World); @@ -150,7 +111,7 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } - auto itPair = this->World->GetDirectChildren(parent); + auto itPair = this->World->GetChildren(parent); if (itPair.first == itPair.second) { return EntityWrapper::Invalid; } @@ -170,42 +131,3 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } -EntityWrapper EntityWrapper::cloneRecursive(EntityWrapper entity, EntityWrapper parent) -{ - EntityWrapper clone = EntityWrapper(entity.World, entity.World->CreateEntity(parent.ID)); - entity.World->SetName(clone.ID, entity.Name()); - - // Clone components - for (auto& kv : entity.World->GetComponentPools()) { - if (kv.second->KnowsEntity(entity.ID)) { - ComponentWrapper c1 = kv.second->GetByEntity(entity.ID); - ComponentWrapper c2 = entity.World->AttachComponent(clone.ID, kv.first); - c1.Copy(c2); - } - } - - // Clone children - auto children = entity.World->GetDirectChildren(entity.ID); - for (auto it = children.first; it != children.second; ++it) { - EntityWrapper child(entity.World, it->second); - cloneRecursive(child, clone); - } - - return clone; -} - -void EntityWrapper::childrenWithComponentRecursive(const std::string& componentType, EntityWrapper& entity, std::vector& childrenWithComponent) -{ - auto itPair = this->World->GetDirectChildren(entity.ID); - if (itPair.first == itPair.second) { - return; - } - - for (auto it = itPair.first; it != itPair.second; ++it) { - EntityWrapper child = EntityWrapper(entity.World, it->second); - if (child.HasComponent(componentType)) { - childrenWithComponent.push_back(child); - } - childrenWithComponentRecursive(componentType, child, childrenWithComponent); - } -} diff --git a/src/Engine/Core/PerformanceTimer.cpp b/src/Engine/Core/PerformanceTimer.cpp deleted file mode 100644 index 50983e79..00000000 --- a/src/Engine/Core/PerformanceTimer.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include "Core/PerformanceTimer.h" -#include -#include - -cpu_timer PerformanceTimer::m_Timer; -std::map PerformanceTimer::timers; -std::string PerformanceTimer::currentTimerRunning = ""; - -void PerformanceTimer::StartTimer(std::string nameOfTimer) -{ - timers[nameOfTimer].stop(); - timers[nameOfTimer].start(); - currentTimerRunning = nameOfTimer; -} - -void PerformanceTimer::StartTimerAndStopPrevious(std::string nameOfTimer) -{ - //stop the current timer and start some other - useful to not have to stop timers all the time - if (currentTimerRunning != "") { - timers[currentTimerRunning].stop(); - } - timers[nameOfTimer].stop(); - timers[nameOfTimer].start(); - currentTimerRunning = nameOfTimer; -} - -void PerformanceTimer::StopTimer(std::string nameOfTimer) -{ - timers[nameOfTimer].stop(); - currentTimerRunning = nameOfTimer; -} - -void PerformanceTimer::SetFrameNumber(int frameNumber) -{ -} - -void PerformanceTimer::ResetAllTimers() -{ - //stop all timers - for (auto aTimer : timers) - { - aTimer.second.stop(); - } - currentTimerRunning = ""; - timers.clear(); -} - -void PerformanceTimer::CreateExcelData() -{ - //get time - std::time_t t = std::time(NULL); - char tStr[16]; - std::strftime(tStr, 32, " %a %H-%M-%S", std::localtime(&t)); - std::string time(tStr); - std::string path("TacticalZ"); - path += time + ".csv"; - std::ofstream someFileStream; - someFileStream.open(path, std::ofstream::out); - someFileStream << "classname" << ',' << "walltime" << ',' << "userTime" << ',' << "systemTime" << '\n'; - - //write all timers to file - for (auto aTimer : timers) - { - //remove the "class" name in front of the string - auto className = aTimer.first; - if (className.find("class ") != std::string::npos) { - className.replace(0, 6, ""); - } - auto wallTime = (double)aTimer.second.elapsed().wall*1e-3; - auto userTime = (double)aTimer.second.elapsed().user*1e-3; - auto systemTime = (double)aTimer.second.elapsed().system*1e-3; - - someFileStream << className << "," << wallTime << ',' << userTime << ',' << systemTime << '\n'; - } - someFileStream.close(); -} diff --git a/src/Engine/Core/Util/Logging.cpp b/src/Engine/Core/Util/Logging.cpp index c7612fd8..63a6f380 100644 --- a/src/Engine/Core/Util/Logging.cpp +++ b/src/Engine/Core/Util/Logging.cpp @@ -33,8 +33,8 @@ void _LOG(_LOG_LEVEL logLevel, const char* file, const char* func, unsigned int va_end(args); if (logLevel == LOG_LEVEL_ERROR) { - //std::cerr << file << ":" << line << " " << func << std::endl; - //std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; + std::cerr << file << ":" << line << " " << func << std::endl; + std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; } else { std::cout << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; } diff --git a/src/Engine/Core/World.cpp b/src/Engine/Core/World.cpp index 9b323ff4..69c25f61 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -9,20 +9,7 @@ World::~World() } } -World::World(const World& other) - : m_EventBroker(other.m_EventBroker) - , m_CurrentEntityID(other.m_CurrentEntityID) - , m_EntityParents(other.m_EntityParents) - , m_EntityChildren(other.m_EntityChildren) - , m_EntityNames(other.m_EntityNames) -{ - // Deep copy component pools - for (auto& kv : other.m_ComponentPools) { - m_ComponentPools[kv.first] = new ComponentPool(*kv.second); - } -} - -EntityID World::CreateEntity(EntityID parent /*= EntityID_Invalid*/) +EntityID World::CreateEntity(EntityID parent /*= 0*/) { EntityID newEntity = generateEntityID(); if (newEntity == parent) { @@ -57,8 +44,10 @@ ComponentWrapper World::AttachComponent(EntityID entity, const std::string& comp ComponentPool* pool = m_ComponentPools.at(componentType); const ComponentInfo& ci = pool->ComponentInfo(); - // Allocate component with default values + // Allocate space for the component ComponentWrapper c = pool->Allocate(entity); + // Write default values + memcpy(c.Data, ci.Defaults.get(), ci.Stride); return c; } @@ -127,7 +116,7 @@ void World::SetParent(EntityID entity, EntityID parent) m_EntityChildren.insert(std::make_pair(parent, entity)); } -const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetDirectChildren(EntityID entity) +const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetChildren(EntityID entity) { return m_EntityChildren.equal_range(entity); } diff --git a/src/Engine/Editor/EditorGUI.cpp b/src/Engine/Editor/EditorGUI.cpp index 8ce15d0a..70775a2b 100644 --- a/src/Engine/Editor/EditorGUI.cpp +++ b/src/Engine/Editor/EditorGUI.cpp @@ -580,11 +580,6 @@ void EditorGUI::createWidgetToolButton(WidgetMode mode) bool EditorGUI::OnKeyDown(const Events::KeyDown& e) { - ImGuiIO& io = ImGui::GetIO(); - if (io.WantCaptureKeyboard) { - return false; - } - if (e.ModCtrl && e.KeyCode == GLFW_KEY_S) { if (m_CurrentSelection.Valid()) { EntityWrapper baseParent = m_CurrentSelection; @@ -603,19 +598,6 @@ bool EditorGUI::OnKeyDown(const Events::KeyDown& e) entityImport(m_World); } - if (e.ModCtrl && e.KeyCode == GLFW_KEY_C) { - m_CopyTarget = m_CurrentSelection; - } - - if (e.ModCtrl && e.KeyCode == GLFW_KEY_V) { - if (m_OnEntityPaste != nullptr) { - EntityWrapper copy = m_OnEntityPaste(m_CopyTarget, m_CurrentSelection); - if (copy != EntityWrapper::Invalid) { - SelectEntity(copy); - } - } - } - if (e.KeyCode == GLFW_KEY_DELETE) { if (m_CurrentSelection.Valid()) { entityDelete(m_CurrentSelection); diff --git a/src/Engine/Editor/EditorRenderSystem.cpp b/src/Engine/Editor/EditorRenderSystem.cpp index f5fcc1a1..9a385e7d 100644 --- a/src/Engine/Editor/EditorRenderSystem.cpp +++ b/src/Engine/Editor/EditorRenderSystem.cpp @@ -54,7 +54,7 @@ void EditorRenderSystem::Update(double dt) EntityWrapper entity(m_World, cModel.EntityID); glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, entity.World); for (auto matGroup : model->MaterialGroups()) { - std::shared_ptr modelJob = std::make_shared(model, scene.Camera, modelMatrix, matGroup, cModel, entity.World, glm::vec4(0), 0.f, false); + std::shared_ptr modelJob = std::make_shared(model, scene.Camera, modelMatrix, matGroup, cModel, entity.World, glm::vec4(0), 0.f); if (cModel["Transparent"]) { scene.Jobs.TransparentObjects.push_back(modelJob); } else { diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index 4bee1427..921df4dc 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -28,7 +28,6 @@ EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame m_EditorGUI->SetEntityDeleteCallback(std::bind(&EditorSystem::OnEntityDelete, this, std::placeholders::_1)); m_EditorGUI->SetEntityChangeParentCallback(std::bind(&EditorSystem::OnEntityChangeParent, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetEntityChangeNameCallback(std::bind(&EditorSystem::OnEntityChangeName, this, std::placeholders::_1, std::placeholders::_2)); - m_EditorGUI->SetEntityPasteCallback(std::bind(&EditorSystem::OnEntityPaste, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentAttachCallback(std::bind(&EditorSystem::OnComponentAttach, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentDeleteCallback(std::bind(&EditorSystem::OnComponentDelete, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetWidgetModeCallback(std::bind(&EditorSystem::setWidgetMode, this, std::placeholders::_1)); @@ -161,11 +160,6 @@ void EditorSystem::OnEntityChangeName(EntityWrapper entity, const std::string& n } } -EntityWrapper EditorSystem::OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent) -{ - return entityToCopy.Clone(parent); -} - void EditorSystem::OnComponentAttach(EntityWrapper entity, const std::string& componentType) { if (entity.Valid()) { @@ -231,12 +225,6 @@ bool EditorSystem::OnInputCommand(const Events::InputCommand& e) Enable(); } } - if (e.Command == "PerformanceTimingResetAllTimers" && e.Value > 0) { - PerformanceTimer::ResetAllTimers(); - } - if (e.Command == "PerformanceTimingCreateExcelData" && e.Value > 0) { - PerformanceTimer::CreateExcelData(); - } return true; } diff --git a/src/Engine/GUI/ButtonSystem.cpp b/src/Engine/GUI/ButtonSystem.cpp deleted file mode 100644 index 93ae1811..00000000 --- a/src/Engine/GUI/ButtonSystem.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include "GUI/ButtonSystem.h" - -ButtonSystem::ButtonSystem(SystemParams params, IRenderer* renderer) - : System(params) - , PureSystem("Button") - , m_Renderer(renderer) -{ - EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &ButtonSystem::OnMousePress); - EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &ButtonSystem::OnMouseRelease); - EVENT_SUBSCRIBE_MEMBER(m_EMouseLock, &ButtonSystem::OnMouseLock); - EVENT_SUBSCRIBE_MEMBER(m_EMouseUnlock, &ButtonSystem::OnMouseUnlock); -} - - -bool ButtonSystem::OnMouseLock(const Events::LockMouse& e) -{ - m_MouseIsLocked = true; - return true; -} - - -bool ButtonSystem::OnMouseUnlock(const Events::UnlockMouse& e) -{ - m_MouseIsLocked = false; - return true; -} - - -bool ButtonSystem::OnMousePress(const Events::MousePress& e) -{ - if (e.Button == GLFW_MOUSE_BUTTON_1 && !m_MouseIsLocked) { - m_PickData = m_Renderer->Pick(glm::vec2(e.X, e.Y)); - if (m_PickData.Entity != EntityID_Invalid && m_PickData.World == m_World) { - if(m_World->HasComponent(m_PickData.Entity, "Button")) { - //Entity is a button, save it and send pressed event. - - m_PickEntity = EntityWrapper(m_World, m_PickData.Entity); - - //You have clicked on a button entity, send pressed event. - Events::ButtonPressed ePressed; - ePressed.Entity = m_PickEntity; - ePressed.EntityName = m_PickEntity.Name(); - m_EventBroker->Publish(ePressed); - } - } - } - return true; -} - -bool ButtonSystem::OnMouseRelease(const Events::MouseRelease& e) -{ - if(!m_MouseIsLocked) { - //Mouse is not locked, send release event. - m_PickData = m_Renderer->Pick(glm::vec2(e.X, e.Y)); - if(m_PickData.Entity != EntityID_Invalid && m_PickData.World == m_World) { - EntityWrapper ent = EntityWrapper(m_World, m_PickData.Entity); - - Events::ButtonReleased eReleased; - eReleased.EntityName = m_PickEntity.Name(); - eReleased.Entity = m_PickEntity; - m_EventBroker->Publish(eReleased); - - if(m_World->HasComponent(m_PickData.Entity, "Button")) { - if (ent == m_PickEntity) { - //The entity you released the mouse button on is the same as you pressed it on. "Clicked" - Events::ButtonClicked eClicked; - eClicked.Entity = m_PickEntity; - eClicked.EntityName = m_PickEntity.Name(); - m_EventBroker->Publish(eClicked); - } - } - } - } - return true; -} - -void ButtonSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cHealth, double dt) -{ - -} - - - - \ No newline at end of file diff --git a/src/Engine/GUI/MainMenuSystem.cpp b/src/Engine/GUI/MainMenuSystem.cpp deleted file mode 100644 index f8bf032b..00000000 --- a/src/Engine/GUI/MainMenuSystem.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "GUI/MainMenuSystem.h" - -MainMenuSystem::MainMenuSystem(SystemParams params, IRenderer* renderer) - : System(params) - , ImpureSystem() - , m_Renderer(renderer) -{ - EVENT_SUBSCRIBE_MEMBER(m_EPressed, &MainMenuSystem::OnButtonPress); - EVENT_SUBSCRIBE_MEMBER(m_EReleased, &MainMenuSystem::OnButtonRelease); - EVENT_SUBSCRIBE_MEMBER(m_EClicked, &MainMenuSystem::OnButtonClick); -} - -void MainMenuSystem::Update(double dt) -{ - -} - -bool MainMenuSystem::OnButtonClick(const Events::ButtonClicked& e) -{ - if(e.EntityName == "Play") { - //Run play code - } else if(e.EntityName == "Connect") { - //Run connect code - } else if(e.EntityName == "Host") { - //Run host code - } else if(e.EntityName == "Quit") { - printf("No, you stay"); - } else if (e.EntityName == "Res1080") { - glfwSetWindowSize(m_Renderer->Window(), 1920, 1080); - printf("\n1080"); - } else if (e.EntityName == "Res720") { - glfwSetWindowSize(m_Renderer->Window(), 1280, 720); - glViewport(0, 0, 1280, 720); - printf("\n720"); - } else if (e.EntityName == "Res480") { - glfwSetWindowSize(m_Renderer->Window(), 854, 480); - glViewport(0, 0, 854, 480); - printf("\n480"); - } else if (e.EntityName == "FullScreen") { - printf("No fullscreen for now"); - } - - return true; -} - -bool MainMenuSystem::OnButtonRelease(const Events::ButtonReleased& e) -{ - - return true; -} - -bool MainMenuSystem::OnButtonPress(const Events::ButtonPressed& e) -{ - - return true; -} - diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index aa87f6ff..3406535a 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -1,7 +1,7 @@ #include "Network/Client.h" using namespace boost::asio::ip; -Client::Client(World* world, EventBroker* eventBroker) +Client::Client(World* world, EventBroker* eventBroker) : Network(world, eventBroker) { // Asumes root node is EntityID_Invalid @@ -13,8 +13,6 @@ Client::Client(World* world, EventBroker* eventBroker) m_PlayerName = config->Get("Networking.Name", "Raptorcopter"); m_SendInputIntervalMs = config->Get("Networking.SendInputIntervalMs", 33); LOG_INFO("Client initialized"); - - m_ServerlistRequest.Connect(m_PlayerName, "192.168.1.255", 32554); } Client::Client(World* world, EventBroker* eventBroker, std::unique_ptr snapshotFilter) @@ -32,8 +30,6 @@ void Client::Connect(std::string address, int port) EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned); - EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &Client::OnDoubleJump); - EVENT_SUBSCRIBE_MEMBER(m_ESearchForServers, &Client::OnSearchForServers); auto config = ResourceManager::Load("Config.ini"); m_Address = address; if (address.empty()) { @@ -70,21 +66,6 @@ void Client::Update() } - while (m_ServerlistRequest.IsSocketAvailable()) { - Packet packet(MessageType::Invalid); - m_ServerlistRequest.Receive(packet); - if (packet.GetMessageType() == MessageType::ServerlistRequest) { - parseServerlist(packet); - } - } - - if (m_SearchingForServers) { - if (m_SearchingTime < (1000* (std::clock() - m_StartSearchTime) / (double)CLOCKS_PER_SEC)) { - m_SearchingForServers = false; - displayServerlist(); - } - } - if (m_IsConnected) { // Don't send 1 input in 1 packet, bunch em up. if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) { @@ -101,7 +82,8 @@ void Client::Update() void Client::parseMessageType(Packet& packet) { - // Pop packetSize + // Pop packetSize which is used by TCP Client to + // create a packet of the correct size packet.ReadPrimitive(); int messageType = packet.ReadPrimitive(); if (messageType == -1) @@ -140,12 +122,6 @@ void Client::parseMessageType(Packet& packet) case MessageType::OnPlayerDamage: parsePlayerDamage(packet); break; - case MessageType::OnDoubleJump: - parseDoubleJump(packet); - break; - case MessageType::AmmoPickup: - parseAmmoPickup(packet); - break; default: break; } @@ -197,22 +173,6 @@ void Client::parsePing() m_Reliable.Send(packet); } - -void Client::parseServerlist(Packet& packet) -{ - // Pop size, message type, and ID - packet.ReadPrimitive(); - packet.ReadPrimitive(); - packet.ReadPrimitive(); - std::string address = packet.ReadString(); - int port = packet.ReadPrimitive(); - std::string serverName = packet.ReadString(); - int playersConnected = packet.ReadPrimitive(); - //TODO: This should not happen when a client is connected to a server - - m_Serverlist.push_back({ address, port, serverName, playersConnected }); -} - void Client::parseKick() { LOG_WARNING("You have been kicked from the server."); @@ -230,11 +190,12 @@ void Client::parseSpawnEvents() } e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Player.ID)); //e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID)); - e.PlayerID = -1; + e.PlayerID = -1; e.PlayerName = m_PlayerSpawnEvents.at(i).PlayerName; m_EventBroker->Publish(e); } m_PlayerSpawnEvents = tempSpawn; + // m_PlayerSpawnEvents.clear(); } void Client::parsePlayersSpawned(Packet& packet) @@ -262,14 +223,8 @@ void Client::parseEntityDeletion(Packet & packet) if (m_ServerIDToClientID.find(entityToDelete) != m_ServerIDToClientID.end()) { EntityID localEntity = m_ServerIDToClientID.at(entityToDelete); if (m_World->ValidEntity(localEntity)) { - if (m_World->HasComponent(localEntity,"Player")) { - Events::PlayerDeath e; - e.Player = EntityWrapper(m_World, localEntity); - m_EventBroker->Publish(e); - } else { - m_World->DeleteEntity(localEntity); - deleteFromServerClientMaps(entityToDelete, localEntity); - } + m_World->DeleteEntity(localEntity); + deleteFromServerClientMaps(entityToDelete, localEntity); } } } @@ -283,28 +238,6 @@ void Client::parseComponentDeletion(Packet & packet) } } -void Client::parseDoubleJump(Packet & packet) -{ - EntityID serverID = packet.ReadPrimitive(); - if (!serverClientMapsHasEntity(serverID)) { - return; - } - Events::DoubleJump e; - e.entityID = m_ServerIDToClientID.at(serverID); - // If player is local player do not publish to prevent infinite feedback loop - if (e.entityID != m_LocalPlayer.ID) { - m_EventBroker->Publish(e); - } -} - -void Client::parseAmmoPickup(Packet & packet) -{ - Events::AmmoPickup e; - e.AmmoGain = packet.ReadPrimitive(); - e.Player = m_LocalPlayer; - m_EventBroker->Publish(e); -} - void Client::updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID) { for (auto field : componentInfo.FieldsInOrder) { @@ -379,20 +312,19 @@ void Client::parseSnapshot(Packet& packet) if (serverClientMapsHasEntity(serverEntityID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); EntityWrapper localEntity(m_World, localEntityID); + // Update entity if (m_World->HasComponent(localEntityID, componentType)) { - // TODO Fix memory leak here SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); bool shouldApply = true; // Apply potential filter function if (m_SnapshotFilter != nullptr) { shouldApply = m_SnapshotFilter->FilterComponent(localEntity, newComponent); } - if (shouldApply) { + if (shouldApply) { ComponentWrapper currentComponent = m_World->GetComponent(localEntityID, componentType); memcpy(currentComponent.Data, newComponent.Data, componentInfo.Stride); } - //if (localEntity != m_LocalPlayer && !localEntity.IsChildOf(m_LocalPlayer)) { // updateFields(packet, componentInfo, localEntityID); //} else { @@ -409,11 +341,7 @@ void Client::parseSnapshot(Packet& packet) if (serverParentID == EntityID_Invalid) { newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); } else { - if (serverClientMapsHasEntity(serverParentID)) { - newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID)); - } else { - newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); - } + newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID)); } m_World->SetName(newLocalEntityID, serverEntityName); insertIntoServerClientMaps(serverEntityID, newLocalEntityID); @@ -423,11 +351,9 @@ void Client::parseSnapshot(Packet& packet) } // Parent logic // This should be enough beacause we know that the entities arives in pre-order (there will always be a parent) - if (serverParentID != EntityID_Invalid && serverClientMapsHasEntity(serverParentID)) { + if (serverParentID != EntityID_Invalid) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); - if (m_World->GetParent(localEntityID) != m_ServerIDToClientID.at(serverParentID)) { - m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); - } + m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); } } parseSpawnEvents(); @@ -445,12 +371,6 @@ void Client::disconnect() bool Client::OnInputCommand(const Events::InputCommand & e) { - // TEMP - if (e.Command == "SearchForServers" && e.Value > 0) { - Events::SearchForServers e; - m_EventBroker->Publish(e); - } - if (e.PlayerID != -1) { return false; } @@ -495,11 +415,6 @@ bool Client::OnPlayerDamage(const Events::PlayerDamage & e) if (e.Inflictor != m_LocalPlayer) { return false; } - // Could this happen? - //if (!clientServerMapsHasEntity(e.Inflictor.ID) - // || !clientServerMapsHasEntity(e.Victim.ID)) { - // return; - //} Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); packet.WritePrimitive(m_ClientIDToServerID.at(e.Inflictor.ID)); @@ -518,27 +433,15 @@ bool Client::OnPlayerSpawned(const Events::PlayerSpawned& e) return true; } -bool Client::OnSearchForServers(const Events::SearchForServers& e) -{ - m_SearchingForServers = true; - m_StartSearchTime = std::clock(); - m_Serverlist.clear(); - LOG_INFO("Searching for LAN servers...\n"); - Packet packet(MessageType::ServerlistRequest); - m_ServerlistRequest.Broadcast(packet, 13); // TODO: Config - return true; -} - void Client::parsePlayerDamage(Packet& packet) { Events::PlayerDamage e; PlayerID victimID = packet.ReadPrimitive(); - PlayerID inflictorID = packet.ReadPrimitive(); - if (!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)) { + if(serverClientMapsHasEntity(victimID)){ return; } e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); - e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(inflictorID)); + e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(packet.ReadPrimitive())); e.Damage = packet.ReadPrimitive(); // Don't rebroadcast our own player damage events or we'll have an infinite loop! if (e.Inflictor != m_LocalPlayer) { @@ -546,17 +449,6 @@ void Client::parsePlayerDamage(Packet& packet) } } -bool Client::OnDoubleJump(Events::DoubleJump & e) -{ - if (!clientServerMapsHasEntity(e.entityID) || e.entityID != m_LocalPlayer.ID) { - return false; - } - Packet packet(MessageType::OnDoubleJump); - packet.WritePrimitive(m_ClientIDToServerID.at(e.entityID)); - m_Reliable.Send(packet); - return true; -} - void Client::sendLocalPlayerTransform() { if (!m_LocalPlayer.Valid()) { @@ -574,7 +466,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.z); - + bool hasAssaultWeapon = m_LocalPlayer.HasComponent("AssaultWeapon"); packet.WritePrimitive(hasAssaultWeapon); if (hasAssaultWeapon) { @@ -582,7 +474,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive((int)cAssaultWeapon["MagazineAmmo"]); packet.WritePrimitive((int)cAssaultWeapon["Ammo"]); } - + m_Unreliable.Send(packet); } @@ -635,16 +527,6 @@ void Client::becomePlayer() m_Reliable.Send(packet); } - -void Client::displayServerlist() -{ - LOG_INFO("This is a serverlist:\n"); - for (int i = 0; i < m_Serverlist.size(); i++) { - ServerInfo si = m_Serverlist[i]; - LOG_INFO("%s:%i\t%s\t%i\n", si.Address.c_str(), si.Port, si.Name.c_str(), si.PlayersConnected); - } -} - bool Client::clientServerMapsHasEntity(EntityID clientEntityID) { if (m_ClientIDToServerID.find(clientEntityID) != m_ClientIDToServerID.end()) { diff --git a/src/Engine/Network/HybridClient.cpp b/src/Engine/Network/HybridClient.cpp new file mode 100644 index 00000000..4200e8e3 --- /dev/null +++ b/src/Engine/Network/HybridClient.cpp @@ -0,0 +1,10 @@ +#include "Network/HybridClient.h" + + +HybridClient::HybridClient() +{ +} + +HybridClient::~HybridClient() +{ +} \ No newline at end of file diff --git a/src/Engine/Network/HybridServer.cpp b/src/Engine/Network/HybridServer.cpp new file mode 100644 index 00000000..bfcdaee0 --- /dev/null +++ b/src/Engine/Network/HybridServer.cpp @@ -0,0 +1,9 @@ +#include "Network/HybridServer.h" + +HybridServer::HybridServer() +{ +} + +HybridServer::~HybridServer() +{ +} \ No newline at end of file diff --git a/src/Engine/Network/NetworkClient.cpp b/src/Engine/Network/NetworkClient.cpp index 7a61d5f3..e69de29b 100644 --- a/src/Engine/Network/NetworkClient.cpp +++ b/src/Engine/Network/NetworkClient.cpp @@ -1,11 +0,0 @@ -#include "Network/NetworkClient.h" - -NetworkClient::NetworkClient() -{ - m_ReadBuffer = new char[m_BufferSize]; -} - -NetworkClient::~NetworkClient() -{ - delete[] m_ReadBuffer; -} diff --git a/src/Engine/Network/NetworkServer.cpp b/src/Engine/Network/NetworkServer.cpp deleted file mode 100644 index 1412621d..00000000 --- a/src/Engine/Network/NetworkServer.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "Network/NetworkServer.h" - -NetworkServer::NetworkServer() -{ - m_ReadBuffer = new char[m_BufferSize]; -} - -NetworkServer::~NetworkServer() -{ - delete[] m_ReadBuffer; -} diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 08b72304..082849c7 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -1,8 +1,7 @@ #include "Network/Server.h" -Server::Server(World* world, EventBroker* eventBroker, int port) +Server::Server(World* world, EventBroker* eventBroker, int port) : Network(world, eventBroker) - , m_ServerlistRequest(13) { ConfigFile* config = ResourceManager::Load("Config.ini"); snapshotInterval = 1000 * config->Get("Networking.SnapshotInterval", 0.05f); @@ -13,8 +12,8 @@ Server::Server(World* world, EventBroker* eventBroker, int port) EVENT_SUBSCRIBE_MEMBER(m_EEntityDeleted, &Server::OnEntityDeleted); EVENT_SUBSCRIBE_MEMBER(m_EComponentDeleted, &Server::OnComponentDeleted); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Server::OnPlayerDamage); - EVENT_SUBSCRIBE_MEMBER(m_EAmmoPickup, &Server::OnAmmoPickup); - // BindWW + + // Bind if (port == 0) { port = config->Get("Networking.Port", 27666); } @@ -29,8 +28,9 @@ Server::~Server() void Server::Update() { - m_Reliable.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); + PlayerDefinition pd; + m_Reliable.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); for (auto& kv : m_ConnectedPlayers) { while (kv.second.TCPSocket->available()) { // Packet will get real data in receive @@ -46,7 +46,6 @@ void Server::Update() } } - PlayerDefinition pd; while (m_Unreliable.IsSocketAvailable()) { // Packet will get real data in receive Packet packet(MessageType::Invalid); @@ -59,22 +58,6 @@ void Server::Update() parseMessageType(packet); } } - - while (m_ServerlistRequest.IsSocketAvailable()) { - Packet packet(MessageType::Invalid); - PlayerDefinition localArea; - localArea.Endpoint = boost::asio::ip::udp::endpoint(); - m_ServerlistRequest.Receive(packet, localArea); - if (packet.GetMessageType() == MessageType::ServerlistRequest) { - packet.ReadPrimitive(); // Pop size - packet.ReadPrimitive(); // Pop MsgType - packet.ReadPrimitive(); // Pop packet ID - int port = packet.ReadPrimitive(); - std::string address = localArea.Endpoint.address().to_string(); - parseServerlistRequest(boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string(address), port)); - } - } - // Check if players have disconnected for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { disconnect(m_PlayersToDisconnect.at(i)); @@ -92,7 +75,6 @@ void Server::Update() sendPing(); previousePingMessage = currentTime; } - // Time out logic if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { checkForTimeOuts(); @@ -102,6 +84,7 @@ void Server::Update() if (isReadingData) { Network::Update(); } + } void Server::parseMessageType(Packet& packet) @@ -138,9 +121,6 @@ void Server::parseMessageType(Packet& packet) case MessageType::PlayerTransform: parsePlayerTransform(packet); break; - case MessageType::OnDoubleJump: - parseDoubleJump(packet); - break; default: break; } @@ -167,7 +147,7 @@ void Server::sendSnapshot() { Packet packet(MessageType::Snapshot); addInputCommandsToPacket(packet); - addPlayersToPacket(packet, EntityID_Invalid); + addChildrenToPacket(packet, EntityID_Invalid); unreliableBroadcast(packet); } @@ -184,61 +164,19 @@ void Server::addInputCommandsToPacket(Packet& packet) m_InputCommandsToBroadcast.clear(); } -void Server::addPlayersToPacket(Packet & packet, EntityID entityID) +void Server::addChildrenToPacket(Packet & packet, EntityID entityID) { - auto itPair = m_World->GetDirectChildren(entityID); + auto itPair = m_World->GetChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { EntityID childEntityID = it->second; // HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself - // HACK: Also checked CapturePointHUD for now. (this would get out of sync); EntityWrapper childEntity(m_World, childEntityID); - if (shouldSendToClient(childEntity)) { - // Write EntityID and parentsID and Entity name - packet.WritePrimitive(childEntityID); - packet.WritePrimitive(entityID); - packet.WriteString(m_World->GetName(childEntityID)); - // Write components to child - int numberOfComponents = 0; - for (auto& i : worldComponentPools) { - if (i.second->KnowsEntity(childEntityID)) { - numberOfComponents++; - } - } - // Write how many components should be read - packet.WritePrimitive(numberOfComponents); - for (auto& i : worldComponentPools) { - // If the entity exist in the pool - if (i.second->KnowsEntity(childEntityID)) { - ComponentWrapper componentWrapper = i.second->GetByEntity(childEntityID); - // ComponentType - packet.WriteString(componentWrapper.Info.Name); - // Loop through fields - for (auto& componentField : componentWrapper.Info.FieldsInOrder) { - ComponentInfo::Field_t fieldInfo = componentWrapper.Info.Fields.at(componentField); - if (fieldInfo.Type == "string") { - std::string& value = componentWrapper[componentField]; - packet.WriteString(value); - } else { - packet.WriteData(componentWrapper.Data + fieldInfo.Offset, fieldInfo.Stride); - } - } - } - } + if (!shouldSendToClient(childEntity)) { + continue; } - // Go to to your children - addPlayersToPacket(packet, childEntityID); - } -} -void Server::addChildrenToPacket(Packet & packet, EntityID entityID) -{ - auto itPair = m_World->GetDirectChildren(entityID); - std::unordered_map worldComponentPools = m_World->GetComponentPools(); - // Loop through every child - for (auto it = itPair.first; it != itPair.second; it++) { - EntityID childEntityID = it->second; // Write EntityID and parentsID and Entity name packet.WritePrimitive(childEntityID); packet.WritePrimitive(entityID); @@ -293,8 +231,6 @@ void Server::sendPing() reliableBroadcast(packet); } - - void Server::checkForTimeOuts() { double startPing = 1000 * m_StartPingTime @@ -344,7 +280,7 @@ void Server::parseTCPConnect(Packet & packet) // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id m_PacketID = packet.ReadPrimitive(); //Read new packet id - + LOG_INFO("Parsing connections"); // Check if player is already connected // Ska vara till lagd i TCPServer receive @@ -369,11 +305,6 @@ void Server::parseTCPConnect(Packet & packet) connnectPacket.WritePrimitive(playerID); m_Reliable.Send(connnectPacket); - Packet firstSnapshot(MessageType::Snapshot); - addInputCommandsToPacket(firstSnapshot); - addChildrenToPacket(firstSnapshot, EntityID_Invalid); - m_Reliable.Send(firstSnapshot); - // Send notification that a player has connected //Packet notificationPacket(MessageType::PlayerConnected); //broadcast(notificationPacket); @@ -392,17 +323,6 @@ void Server::parseDisconnect() } } - -void Server::parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint) -{ - Packet packet(MessageType::ServerlistRequest); - packet.WriteString(m_Reliable.Address()); - packet.WritePrimitive(m_Reliable.Port()); - packet.WriteString("SERVERNAME"); - packet.WritePrimitive(m_ConnectedPlayers.size()); - m_ServerlistRequest.Send(packet); -} - void Server::disconnect(PlayerID playerID) { //broadcast("A player disconnected"); @@ -427,7 +347,6 @@ void Server::parseOnPlayerDamage(Packet & packet) e.Victim = EntityWrapper(m_World, packet.ReadPrimitive()); e.Damage = packet.ReadPrimitive(); m_EventBroker->Publish(e); - //LOG_DEBUG("Server::parseOnPlayerDamage: Command is %s. Value is %f. PlayerID is %i.", e.DamageAmount, e.PlayerDamagedID, e.TypeOfDamage.c_str()); } @@ -456,7 +375,8 @@ bool Server::OnInputCommand(const Events::InputCommand & e) } isReadingData = !isReadingData; m_SaveDataTimer = std::clock(); - } else if (e.Command == "KickPlayer" && e.Value > 0) { + } + if (e.Command == "KickPlayer" && e.Value > 0) { kick(0); } @@ -507,20 +427,7 @@ bool Server::OnPlayerDamage(const Events::PlayerDamage& e) packet.WritePrimitive(e.Damage); reliableBroadcast(packet); - return true; -} - -bool Server::OnAmmoPickup(const Events::AmmoPickup & e) -{ - for (auto& kv : m_ConnectedPlayers) { - if (e.Player.ID == kv.second.EntityID) { - Packet packet(MessageType::AmmoPickup); - // We dont send playerID as it will be set at client to local - packet.WritePrimitive(e.AmmoGain); - m_Reliable.Send(packet, kv.second); - } - } - return true; + return false; } void Server::parseClientPing() @@ -540,21 +447,13 @@ void Server::parsePing() { for (auto& kv : m_ConnectedPlayers) { if (kv.second.TCPAddress == m_Address && - kv.second.TCPPort == m_Port - || (kv.second.Endpoint.address() == m_Address - && kv.second.Endpoint.port() == m_Port)) { + kv.second.TCPPort == m_Port) { kv.second.StopTime = std::clock(); break; } } } -bool Server::parseDoubleJump(Packet & packet) -{ - reliableBroadcast(packet); - return true; -} - void Server::parseOnInputCommand(Packet& packet) { PlayerID player = -1; @@ -614,17 +513,7 @@ void Server::parsePlayerTransform(Packet& packet) bool Server::shouldSendToClient(EntityWrapper childEntity) { - auto children = m_World->GetDirectChildren(childEntity.ID); - for (auto it = children.first; it != children.second; it++) { - EntityWrapper child(m_World, it->second); - if (child.HasComponent("CapturePoint") || child.HasComponent("HealthPickup") - || child.HasComponent("AmmoPickup")) { - return true; - } - } - return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid() - || childEntity.HasComponent("CapturePoint") || childEntity.HasComponent("HealthPickup") - || childEntity.HasComponent("AmmoPickup"); + return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid(); } PlayerID Server::GetPlayerIDFromEndpoint() diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index f3394d3d..df4f3826 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -56,42 +56,32 @@ void TCPClient::Disconnect() void TCPClient::Receive(Packet& packet) { - size_t bytesRead = readBuffer(); + size_t bytesRead = readBuffer(m_ReadBuffer); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } } -size_t TCPClient::readBuffer() +size_t TCPClient::readBuffer(char* data) { if (!m_Socket) { return 0; } boost::system::error_code error; // Read size of packet - m_Socket->receive(boost - ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), - boost::asio::ip::tcp::socket::message_peek, error); - unsigned int sizeOfPacket = 0; - memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); - - // if the buffer is to small increase the size of it - // TODO if message is huge 1 time the buffer will not decrease. - if (sizeOfPacket > m_BufferSize) { - delete[] m_ReadBuffer; - m_ReadBuffer = new char[sizeOfPacket]; - m_BufferSize = sizeOfPacket; - } - // Read the rest of the message size_t bytesReceived = m_Socket->read_some(boost - ::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket), + ::asio::buffer((void*)data, sizeof(int)), + error); + int sizeOfPacket = 0; + memcpy(&sizeOfPacket, data, sizeof(int)); + + // Read the rest of the message + bytesReceived += m_Socket->read_some(boost + ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), error); if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } - if (sizeOfPacket > 1000000) - LOG_WARNING("The packets received are bigger than 1MB"); - return bytesReceived; } diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index acd3d6d0..a449e684 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -1,38 +1,25 @@ #include "Network/TCPServer.h" using namespace boost::asio::ip; -TCPServer::TCPServer() +TCPServer::TCPServer() { acceptor = std::unique_ptr(new tcp::acceptor(m_IOService, tcp::endpoint(tcp::v4(), 27666))); - // Make the acceptor non-blocking so we wont get stuck in AcceptNewConnections(). - acceptor->non_blocking(true); - m_Port = GetPort(); - m_Address = GetAddress(); } TCPServer::~TCPServer() -{ } +{ +} void TCPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) { - boost::system::error_code error; boost::shared_ptr newSocket = boost::shared_ptr(new tcp::socket(m_IOService)); - acceptor->accept(*newSocket, error); - // If no error occured add new tcp connection - if (!error) { - // Add tcp socket to connections - boost::asio::ip::tcp::no_delay option(true); - newSocket->set_option(option); - PlayerDefinition pd; - pd.StopTime = std::clock(); - pd.TCPSocket = newSocket; - pd.TCPAddress = newSocket.get()->remote_endpoint().address(); - pd.TCPPort = newSocket.get()->remote_endpoint().port(); - connectedPlayers[nextPlayerID++] = pd; - } + m_IOService.poll(); + acceptor->async_accept(*newSocket, + boost::bind(&TCPServer::handle_accept, this, newSocket, boost::ref(nextPlayerID), boost::ref(connectedPlayers), + boost::asio::placeholders::error)); } -PlayerID TCPServer::getPlayerIDFromEndpoint(const std::map& connectedPlayers, +PlayerID GetPlayerIDFromEndpoint(const std::map& connectedPlayers, boost::asio::ip::address address, unsigned short port) { for (auto& kv : connectedPlayers) { @@ -44,10 +31,28 @@ PlayerID TCPServer::getPlayerIDFromEndpoint(const std::map socket, + int& nextPlayerID, std::map& connectedPlayers, + const boost::system::error_code& error) +{ + if (!error && GetPlayerIDFromEndpoint(connectedPlayers, socket->remote_endpoint().address(), + socket->remote_endpoint().port()) == -1) { + // Add tcp socket to connections + boost::asio::ip::tcp::no_delay option(true); + socket->set_option(option); + PlayerDefinition pd; + pd.StopTime = std::clock(); + pd.TCPSocket = socket; + pd.TCPAddress = socket.get()->remote_endpoint().address(); + pd.TCPPort = socket.get()->remote_endpoint().port(); + connectedPlayers[nextPlayerID++] = pd; + } +} + void TCPServer::Send(Packet & packet, PlayerDefinition & playerDefinition) { - packet.UpdateSize(); try { + packet.UpdateSize(); int bytesSent = playerDefinition.TCPSocket->send( boost::asio::buffer(packet.Data(), packet.Size()), 0); @@ -68,60 +73,38 @@ void TCPServer::Send(Packet & packet) } void TCPServer::Disconnect() -{ -} +{ -int TCPServer::GetPort() -{ - return acceptor->local_endpoint().port(); -} - -std::string TCPServer::GetAddress() -{ - boost::asio::ip::tcp::resolver resolver(m_IOService); - boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), boost::asio::ip::host_name(), ""); - boost::asio::ip::tcp::resolver::iterator it = resolver.resolve(query); - boost::asio::ip::tcp::endpoint endpoint = *it; - return endpoint.address().to_string().c_str(); } void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { - int bytesRead = readBuffer(playerDefinition); + int bytesRead = readBuffer(m_ReadBuffer, playerDefinition); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } lastReceivedSocket = playerDefinition.TCPSocket; } -int TCPServer::readBuffer(PlayerDefinition & playerDefinition) +int TCPServer::readBuffer(char* data, PlayerDefinition & playerDefinition) { if (!playerDefinition.TCPSocket) { return 0; } boost::system::error_code error; // Read size of packet - playerDefinition.TCPSocket->receive(boost - ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), - boost::asio::ip::tcp::socket::message_peek, error); - unsigned int sizeOfPacket = 0; - memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); - - // if the buffer is to small increase the size of it - if (sizeOfPacket > m_BufferSize) { - delete[] m_ReadBuffer; - m_ReadBuffer = new char[sizeOfPacket]; - m_BufferSize = sizeOfPacket; - } - // Read the rest of the message size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost - ::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket), + ::asio::buffer((void*)data, sizeof(int)), + error); + int sizeOfPacket = 0; + memcpy(&sizeOfPacket, data, sizeof(int)); + + // Read the rest of the message + bytesReceived += playerDefinition.TCPSocket->read_some(boost + ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), error); if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } - if (sizeOfPacket > 1000000) - LOG_WARNING("The packets received are bigger than 1MB"); - return bytesReceived; } \ No newline at end of file diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp index 51c29920..c76de084 100644 --- a/src/Engine/Network/UDPClient.cpp +++ b/src/Engine/Network/UDPClient.cpp @@ -15,9 +15,9 @@ void UDPClient::Connect(std::string playerName, std::string address, int port) if (m_Socket) { return; } - m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address().from_string(address), port); + m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); m_Socket = boost::shared_ptr(new boost::asio::ip::udp::socket(m_IOService)); - m_Socket->open(boost::asio::ip::udp::v4()); + m_Socket->connect(m_ReceiverEndpoint); } void UDPClient::Disconnect() @@ -27,66 +27,34 @@ void UDPClient::Disconnect() void UDPClient::Receive(Packet& packet) { - int bytesRead = readBuffer(); + int bytesRead = readBuffer(m_ReadBuffer); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } } -int UDPClient::readBuffer() +int UDPClient::readBuffer(char* data) { if (!m_Socket) { return 0; } boost::system::error_code error; - // Read size of packet - m_Socket->receive(boost - ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), - boost::asio::ip::udp::socket::message_peek, error); - int sizeOfPacket = 0; - memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); - - // if the buffer is to small increase the size of it - if (sizeOfPacket > m_BufferSize) { - delete[] m_ReadBuffer; - m_ReadBuffer = new char[sizeOfPacket]; - m_BufferSize = sizeOfPacket; - } - - size_t availableData = m_Socket->available(); - // Read the rest of the message - size_t bytesReceived = m_Socket->receive_from(boost - ::asio::buffer((void*)(m_ReadBuffer), - sizeOfPacket), - m_ReceiverEndpoint, 0, error); + int bytesReceived = m_Socket->receive_from(boost + ::asio::buffer((void*)data, BUFFERSIZE), + m_ReceiverEndpoint, + 0, error); if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } - if (sizeOfPacket > 1000000) - LOG_WARNING("The packets received are bigger than 1MB"); - return bytesReceived; } void UDPClient::Send(Packet& packet) { - packet.UpdateSize(); m_Socket->send_to(boost::asio::buffer( packet.Data(), packet.Size()), m_ReceiverEndpoint, 0); -} - -void UDPClient::Broadcast(Packet& packet, int port) -{ - packet.UpdateSize(); - m_Socket->set_option(boost::asio::socket_base::broadcast(true)); - m_Socket->send_to(boost::asio::buffer( - packet.Data(), - packet.Size()), - udp::endpoint(boost::asio::ip::address_v4().broadcast(), port) - , 0); - m_Socket->set_option(boost::asio::socket_base::broadcast(false)); } bool UDPClient::IsSocketAvailable() diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index 635ebd4d..4b0a08ba 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -5,17 +5,11 @@ UDPServer::UDPServer() m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666))); } -UDPServer::UDPServer(int port) -{ - m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), port))); -} - UDPServer::~UDPServer() { } void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition) { - packet.UpdateSize(); try { int bytesSent = m_Socket->send_to( boost::asio::buffer(packet.Data(), packet.Size()), @@ -29,7 +23,6 @@ void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition) // Send back to endpoint of received packet void UDPServer::Send(Packet & packet) { - packet.UpdateSize(); m_Socket->send_to( boost::asio::buffer( packet.Data(), @@ -38,35 +31,9 @@ void UDPServer::Send(Packet & packet) 0); } -// Broadcasting respond specific logic -void UDPServer::Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint) -{ - packet.UpdateSize(); - m_Socket->send_to( - boost::asio::buffer( - packet.Data(), - packet.Size()), - endpoint, - 0); -} - -// Broadcasting -void UDPServer::Broadcast(Packet & packet, int port) -{ - packet.UpdateSize(); - m_Socket->set_option(boost::asio::socket_base::broadcast(true)); - m_Socket->send_to( - boost::asio::buffer( - packet.Data(), - packet.Size()), - boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4().broadcast(),port), - 0); - m_Socket->set_option(boost::asio::socket_base::broadcast(false)); -} - void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { - int bytesRead = readBuffer(); + int bytesRead = readBuffer(m_ReadBuffer); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } @@ -78,39 +45,17 @@ bool UDPServer::IsSocketAvailable() return m_Socket->available(); } -int UDPServer::readBuffer() +int UDPServer::readBuffer(char* data) { - if (!m_Socket) { - return 0; + boost::system::error_code error = boost::asio::error::host_not_found; + unsigned int length = m_Socket->receive_from( + boost::asio::buffer((void*)data + , BUFFERSIZE) + , m_ReceiverEndpoint, 0, error); + if (error) { + LOG_WARNING(error.message().c_str()); } - int addasdasd = m_Socket->available(); - boost::system::error_code error; - // Read size of packet - m_Socket->receive_from(boost - ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), - m_ReceiverEndpoint, boost::asio::ip::udp::socket::message_peek, error); - unsigned int sizeOfPacket = 0; - memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); - - // if the buffer is to small increase the size of it - if (sizeOfPacket > m_BufferSize) { - delete[] m_ReadBuffer; - m_ReadBuffer = new char[sizeOfPacket]; - m_BufferSize = sizeOfPacket; - } - - // Read the rest of the message - size_t bytesReceived = m_Socket->receive_from(boost - ::asio::buffer((void*)(m_ReadBuffer), - sizeOfPacket), - m_ReceiverEndpoint, 0, error); - if (error) { - //LOG_ERROR("receive: %s", error.message().c_str()); - } - if (sizeOfPacket > 1000000) - LOG_WARNING("The packets received are bigger than 1MB"); - - return bytesReceived; + return length; } void UDPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp deleted file mode 100644 index e2a55b74..00000000 --- a/src/Engine/Rendering/CubeMapPass.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include "Rendering/CubeMapPass.h" - -CubeMapPass::CubeMapPass(IRenderer* renderer) - :m_Renderer(renderer) -{ - LoadTextures("Nevada"); -} - -void CubeMapPass::LoadTextures(std::string input) -{ - if (m_PreviusCubeMapTexture != input) { - m_CubeMapTextures.clear(); - for (int i = 0; i < 6; i++) { - std::string str; - str = "Textures/Test/CubeMap/" + input + "/CubeMapTest0" + std::to_string(i) + ".png"; - Texture* img = ResourceManager::Load(str); - m_CubeMapTextures.push_back(img); - } - GenerateCubeMapTexture(); - m_PreviusCubeMapTexture = input; - } -} - -void CubeMapPass::GenerateCubeMapTexture() -{ - if (m_CubeMapTexture == -1) { - glGenTextures(1, &m_CubeMapTexture); - } - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapTexture); - - for (int i = 0; i < 6; i++) { - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, m_CubeMapTextures[0]->Width, m_CubeMapTextures[0]->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_CubeMapTextures[i]->Data); - } - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - GLERROR("Generate Cubemap"); -} - diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 12777941..46612d5e 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -1,101 +1,65 @@ #include "Rendering/DrawBloomPass.h" -DrawBloomPass::DrawBloomPass(IRenderer* renderer, ConfigFile* config) - : m_Renderer(renderer) - , m_Config(config) +DrawBloomPass::DrawBloomPass(IRenderer* renderer) { - InitializeTextures(); + m_Renderer = renderer; - ChangeQuality(m_Config->Get("GLOW.Quality", 2)); + m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); + + InitializeTextures(); + InitializeBuffers(); + InitializeShaderPrograms(); } void DrawBloomPass::InitializeTextures() { - m_BlackTexture = CommonFunctions::LoadTexture("Textures/Core/Black.png", false); -} - -void DrawBloomPass::ChangeQuality(int quality) -{ - if (m_Quality == quality) { - return; - } - m_Quality = quality; - - m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); - - if (m_Quality == 0) { - CommonFunctions::DeleteTexture(&m_GaussianTexture_horiz); - CommonFunctions::DeleteTexture(&m_GaussianTexture_vert); - m_GaussianTexture_horiz = 0; - m_GaussianTexture_vert = 0; - return; - } - InitializeTextures(); - - InitializeBuffers(); - InitializeShaderPrograms(); - std::string qStr = std::to_string(m_Quality); - m_Iterations = m_Config->Get("GLOW" + qStr + ".NumIterations", 0); + m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); } void DrawBloomPass::InitializeShaderPrograms() { m_GaussianProgram_horiz = ResourceManager::Load("##GaussianProgramHoriz"); - if (m_GaussianProgram_horiz->GetHandle() == 0) { - m_GaussianProgram_horiz->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_horiz.vert.glsl"))); - m_GaussianProgram_horiz->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_horiz.frag.glsl"))); - m_GaussianProgram_horiz->Compile(); - m_GaussianProgram_horiz->Link(); - } + m_GaussianProgram_horiz->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_horiz.vert.glsl"))); + m_GaussianProgram_horiz->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_horiz.frag.glsl"))); + m_GaussianProgram_horiz->Compile(); + m_GaussianProgram_horiz->Link(); - m_GaussianProgram_vert = ResourceManager::Load("##GaussianProgramVert"); - if (m_GaussianProgram_vert->GetHandle() == 0) { - m_GaussianProgram_vert->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_vert.vert.glsl"))); - m_GaussianProgram_vert->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_vert.frag.glsl"))); - m_GaussianProgram_vert->Compile(); - m_GaussianProgram_vert->Link(); - } + m_GaussianProgram_vert = ResourceManager::Load("##GaussianProgramVert"); + m_GaussianProgram_vert->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_vert.vert.glsl"))); + m_GaussianProgram_vert->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_vert.frag.glsl"))); + m_GaussianProgram_vert->Compile(); + m_GaussianProgram_vert->Link(); } + void DrawBloomPass::InitializeBuffers() { - CommonFunctions::GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) { - m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); - } - m_GaussianFrameBuffer_horiz.Generate(); + m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); + m_GaussianFrameBuffer_horiz.Generate(); - CommonFunctions::GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - if (m_GaussianFrameBuffer_vert.GetHandle() == 0) { - m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); - } - m_GaussianFrameBuffer_vert.Generate(); + GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + + m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); + m_GaussianFrameBuffer_vert.Generate(); } void DrawBloomPass::ClearBuffer() { - if (m_Quality == 0) { - return; - } - GLERROR("PRE"); m_GaussianFrameBuffer_horiz.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); - glClear(GL_COLOR_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_GaussianFrameBuffer_horiz.Unbind(); m_GaussianFrameBuffer_vert.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); - glClear(GL_COLOR_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_GaussianFrameBuffer_vert.Unbind(); - GLERROR("END"); } void DrawBloomPass::Draw(GLuint texture) { - if (m_Quality == 0) { - return; - } GLERROR("DrawBloomPass::Draw: Pre"); DrawBloomPassState state; @@ -107,39 +71,39 @@ void DrawBloomPass::Draw(GLuint texture) //Horizontal pass, first use the given texture then save it to the horizontal framebuffer. m_GaussianFrameBuffer_horiz.Bind(); m_GaussianProgram_horiz->Bind(); + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); + glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + //Iterate some times to make it more gaussian. - for (int i = 1; i < m_Iterations; i++) { + for (int i = 1; i < m_iterations; i++) { //Vertical pass m_GaussianFrameBuffer_vert.Bind(); m_GaussianProgram_vert->Bind(); - glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + //horizontal pass - m_GaussianFrameBuffer_vert.Unbind(); m_GaussianFrameBuffer_horiz.Bind(); m_GaussianProgram_horiz->Bind(); - glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_vert); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); - m_GaussianFrameBuffer_horiz.Unbind(); } //final vertical gaussian after the iterations are done @@ -147,8 +111,8 @@ void DrawBloomPass::Draw(GLuint texture) m_GaussianFrameBuffer_vert.Bind(); m_GaussianProgram_vert->Bind(); - glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); + glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 @@ -157,14 +121,14 @@ void DrawBloomPass::Draw(GLuint texture) GLERROR("DrawBloomPass::Draw: END"); } - -void DrawBloomPass::OnWindowResize() +void DrawBloomPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const { - if (m_Quality == 0) { - return; - } - CommonFunctions::GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - m_GaussianFrameBuffer_vert.Generate(); - CommonFunctions::GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - m_GaussianFrameBuffer_horiz.Generate(); + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D, *texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); + glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr);//TODO: Renderer: Fix the precision and Resolution + GLERROR("Texture initialization failed"); } diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index 70d3a053..c82d614f 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -18,7 +18,7 @@ void DrawColorCorrectionPass::InitializeShaderPrograms() m_ColorCorrectionProgram->Link(); } -void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, 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"); @@ -33,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 6cdf42d1..11db71f0 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -1,11 +1,10 @@ #include "Rendering/DrawFinalPass.h" -DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, SSAOPass* ssaoPass) - : m_Renderer(renderer) - , m_LightCullingPass(lightCullingPass) - , m_CubeMapPass(cubeMapPass) - , m_SSAOPass(ssaoPass) + +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(); @@ -23,26 +22,41 @@ void DrawFinalPass::InitializeTextures() void DrawFinalPass::InitializeFrameBuffers() { - CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + glGenRenderbuffers(1, &m_DepthBuffer); + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("RenderBuffer generation"); + + GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); //GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + 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); - CommonFunctions::GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST, - glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8); - - m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); + m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new 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"); - CommonFunctions::GenerateTexture(&m_ShieldBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST, - glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT); - m_ShieldDepthFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_ShieldBuffer, GL_DEPTH_ATTACHMENT))); - m_ShieldDepthFrameBuffer.Generate(); + 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() @@ -74,7 +88,6 @@ void DrawFinalPass::InitializeShaderPrograms() m_SpriteProgram->BindFragDataLocation(1, "bloomColor"); m_SpriteProgram->Link(); GLERROR("Creating sprite program"); - m_ForwardPlusSplatMapProgram = ResourceManager::Load("#ForwardPlusSplatMapProgram"); m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGB.frag.glsl"))); @@ -130,291 +143,247 @@ void DrawFinalPass::InitializeShaderPrograms() m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor"); m_ForwardPlusSplatMapSkinnedProgram->Link(); GLERROR("Creating Forward SplatMap Skinned program"); - - m_FillDepthStencilBufferProgram = ResourceManager::Load("#FillDepthBufferProgram"); - m_FillDepthStencilBufferProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBuffer.vert.glsl"))); - m_FillDepthStencilBufferProgram->Compile(); - m_FillDepthStencilBufferProgram->Link(); - GLERROR("Creating DepthFill program"); - - m_FillDepthStencilBufferSkinnedProgram = ResourceManager::Load("#FillDepthBufferProgramSkinned"); - m_FillDepthStencilBufferSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBufferSkinned.vert.glsl"))); - m_FillDepthStencilBufferSkinnedProgram->Compile(); - m_FillDepthStencilBufferSkinnedProgram->Link(); - GLERROR("Creating DepthFill program"); - - - - - - m_ForwardPlusShieldCheckProgram = ResourceManager::Load("#ForwardPlusShieldCheckProgram"); - m_ForwardPlusShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); - m_ForwardPlusShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusShieldCheck.frag.glsl"))); - m_ForwardPlusShieldCheckProgram->Compile(); - m_ForwardPlusShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); - m_ForwardPlusShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); - m_ForwardPlusShieldCheckProgram->Link(); - GLERROR("Creating forward+ program"); - - m_ExplosionEffectShieldCheckProgram = ResourceManager::Load("#ExplosionEffectShieldCheckProgram"); - m_ExplosionEffectShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); - m_ExplosionEffectShieldCheckProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); - m_ExplosionEffectShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusShieldCheck.frag.glsl"))); - m_ExplosionEffectShieldCheckProgram->Compile(); - m_ExplosionEffectShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); - m_ExplosionEffectShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); - m_ExplosionEffectShieldCheckProgram->Link(); - GLERROR("Creating explosion program"); - - m_SpriteShieldCheckProgram = ResourceManager::Load("#SpriteShieldCheckProgram"); - m_SpriteShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/Sprite.vert.glsl"))); - m_SpriteShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SpriteShieldCheck.frag.glsl"))); - m_SpriteShieldCheckProgram->Compile(); - m_SpriteShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); - m_SpriteShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); - m_SpriteShieldCheckProgram->Link(); - GLERROR("Creating sprite program"); - - m_ForwardPlusSplatMapShieldCheckProgram = ResourceManager::Load("#ForwardPlusSplatMapShieldCheckProgram"); - m_ForwardPlusSplatMapShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); - m_ForwardPlusSplatMapShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl"))); - m_ForwardPlusSplatMapShieldCheckProgram->Compile(); - m_ForwardPlusSplatMapShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); - m_ForwardPlusSplatMapShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); - m_ForwardPlusSplatMapShieldCheckProgram->Link(); - GLERROR("Creating Forward SplatMap program"); - - m_ExplosionEffectSplatMapShieldCheckProgram = ResourceManager::Load("#ExplosionEffectSplatMapShieldCheckProgram"); - m_ExplosionEffectSplatMapShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); - m_ExplosionEffectSplatMapShieldCheckProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); - m_ExplosionEffectSplatMapShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl"))); - m_ExplosionEffectSplatMapShieldCheckProgram->Compile(); - m_ExplosionEffectSplatMapShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); - m_ExplosionEffectSplatMapShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); - m_ExplosionEffectSplatMapShieldCheckProgram->Link(); - GLERROR("Creating explosion SplatMap program"); - - m_ForwardPlusSkinnedShieldCheckProgram = ResourceManager::Load("#ForwardPlusSkinnedShieldCheckProgram"); - m_ForwardPlusSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); - m_ForwardPlusSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusShieldCheck.frag.glsl"))); - m_ForwardPlusSkinnedShieldCheckProgram->Compile(); - m_ForwardPlusSkinnedShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); - m_ForwardPlusSkinnedShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); - m_ForwardPlusSkinnedShieldCheckProgram->Link(); - GLERROR("Creating forward+ Skinned program"); - - m_ExplosionEffectSkinnedShieldCheckProgram = ResourceManager::Load("#ExplosionEffectSkinnedShieldCheckProgram"); - m_ExplosionEffectSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); - m_ExplosionEffectSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); - m_ExplosionEffectSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusShieldCheck.frag.glsl"))); - m_ExplosionEffectSkinnedShieldCheckProgram->Compile(); - m_ExplosionEffectSkinnedShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); - m_ExplosionEffectSkinnedShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); - m_ExplosionEffectSkinnedShieldCheckProgram->Link(); - GLERROR("Creating explosion Skinned program"); - - m_ExplosionEffectSplatMapSkinnedShieldCheckProgram = ResourceManager::Load("#ExplosionEffectSplatMapSkinnedShieldCheckProgram"); - m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); - m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl"))); - m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->Compile(); - m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); - m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); - m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->Link(); - GLERROR("Creating Forward SplatMap Skinned program"); - - m_ForwardPlusSplatMapSkinnedShieldCheckProgram = ResourceManager::Load("#ForwardPlusSplatMapSkinnedShieldCheckProgram"); - m_ForwardPlusSplatMapSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); - m_ForwardPlusSplatMapSkinnedShieldCheckProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGBShieldCheck.frag.glsl"))); - m_ForwardPlusSplatMapSkinnedShieldCheckProgram->Compile(); - m_ForwardPlusSplatMapSkinnedShieldCheckProgram->BindFragDataLocation(0, "sceneColor"); - m_ForwardPlusSplatMapSkinnedShieldCheckProgram->BindFragDataLocation(1, "bloomColor"); - m_ForwardPlusSplatMapSkinnedShieldCheckProgram->Link(); - GLERROR("Creating Forward SplatMap Skinned program"); + m_ShieldToStencilProgram = ResourceManager::Load("#ShieldToStencilProgram"); + m_ShieldToStencilProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ShieldStencil.vert.glsl"))); + m_ShieldToStencilProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ShieldStencil.frag.glsl"))); + m_ShieldToStencilProgram->Compile(); + m_ShieldToStencilProgram->Link(); + GLERROR("Creating Shield program"); + + m_ShieldToStencilSkinnedProgram = ResourceManager::Load("#ShieldToStencilProgramSkinned"); + m_ShieldToStencilSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ShieldStencilSkinned.vert.glsl"))); + m_ShieldToStencilSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ShieldStencil.frag.glsl"))); + m_ShieldToStencilSkinnedProgram->Compile(); + m_ShieldToStencilSkinnedProgram->Link(); + GLERROR("Creating Shield Skinned program"); + + m_FillDepthBufferProgram = ResourceManager::Load("#FillDepthBufferProgram"); + m_FillDepthBufferProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBuffer.vert.glsl"))); + m_FillDepthBufferProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); + m_FillDepthBufferProgram->Compile(); + m_FillDepthBufferProgram->Link(); + GLERROR("Creating DepthFill program"); + + m_FillDepthBufferSkinnedProgram = ResourceManager::Load("#FillDepthBufferProgramSkinned"); + m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBufferSkinned.vert.glsl"))); + m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); + m_FillDepthBufferSkinnedProgram->Compile(); + m_FillDepthBufferSkinnedProgram->Link(); + GLERROR("Creating DepthFill program"); } void DrawFinalPass::Draw(RenderScene& scene) { GLERROR("Pre"); - DrawFinalPassState* stateDethp = new DrawFinalPassState(m_ShieldDepthFrameBuffer.GetHandle()); - //Draw shields to stencil - DrawToDepthStencilBuffer(scene.Jobs.ShieldObjects, scene); - GLERROR("StencilPass"); - delete stateDethp; - - DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); + DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); if (scene.ClearDepth) { - //glClear(GL_DEPTH_BUFFER_BIT); - state->Disable(GL_DEPTH_TEST); - state->DepthMask(GL_FALSE); + 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); //Fill depth buffer - state->Enable(GL_STENCIL_TEST); - state->StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); - state->StencilFunc(GL_ALWAYS, 1, 0xFF); - state->StencilMask(0xFF); - state->DepthMask(GL_FALSE); - //DrawToDepthStencilBuffer(scene.Jobs.ShieldObjects, scene); - state->DepthMask(GL_TRUE); + + + state->StencilMask(0x00); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); + GLERROR("OpaqueObjects"); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); + GLERROR("TransparentObjects"); + DrawSprites(scene.Jobs.SpriteJob, scene); + GLERROR("SpriteJobs"); + + //DrawStencilState* stencilState = new DrawStencilState(m_FinalPassFrameBuffer.GetHandle()); + //Draw shields to stencil pass + state->StencilFunc(GL_ALWAYS, 1, 0xFF); + state->StencilMask(0xFF); + DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); + GLERROR("StencilPass"); //Draw Opaque shielded objects - state->Disable(GL_STENCIL_TEST); state->StencilFunc(GL_NOTEQUAL, 1, 0xFF); state->StencilMask(0x00); - DrawModelRenderQueuesWithShieldCheck(scene.Jobs.OpaqueShieldedObjects, scene); //might need changing + DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene); //might need changing GLERROR("Shielded Opaque object"); - //Draw Opaque objects - //state->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); - GLERROR("OpaqueObjects"); - - //state->Disable(GL_STENCIL_TEST); //Draw Transparen Shielded objects - state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - DrawModelRenderQueuesWithShieldCheck(scene.Jobs.TransparentObjects, scene); //might need changing + DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene); //might need changing GLERROR("Shielded Transparent objects"); - //Draw Transparen objects - //state->BlendFunc(GL_ONE, GL_ONE); - //state->StencilFunc(GL_EQUAL, 1, 0xFF); - //DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); - GLERROR("TransparentObjects"); - //state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - DrawSprites(scene.Jobs.SpriteJob, scene); - GLERROR("SpriteJobs"); - - delete state; GLERROR("END"); - + delete state; + + + DrawFinalPassState* stateLowRes = new DrawFinalPassState(m_FinalPassFrameBufferLowRes.GetHandle()); + //Draw the lowres texture that will be shown behind the shield. + stateLowRes->Enable(GL_SCISSOR_TEST); + stateLowRes->Enable(GL_DEPTH_TEST); + //TODO: Viewports and scissor should be in state + glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate); + glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + + glClearStencil(0x00); + glClear(GL_STENCIL_BUFFER_BIT); + + //TODO: This should not be here... + stateLowRes->StencilFunc(GL_ALWAYS, 1, 0xFF); + stateLowRes->StencilMask(0x00); + DrawToDepthBuffer(scene.Jobs.OpaqueObjects, scene); + DrawToDepthBuffer(scene.Jobs.TransparentObjects, scene); + + //Draw shields to stencil pass + stateLowRes->StencilFunc(GL_ALWAYS, 1, 0xFF); + stateLowRes->StencilMask(0xFF); + stateLowRes->Enable(GL_DEPTH_TEST); + DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); + GLERROR("StencilPass"); + + glClear(GL_DEPTH_BUFFER_BIT); + + stateLowRes->Enable(GL_DEPTH_TEST); + stateLowRes->StencilFunc(GL_LEQUAL, 1, 0xFF); + stateLowRes->StencilMask(0x00); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); + 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() { - GLERROR("PRE"); - m_ShieldDepthFrameBuffer.Bind(); - glClear(GL_DEPTH_BUFFER_BIT); - m_ShieldDepthFrameBuffer.Unbind(); + 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(); - GLERROR("Bind HighRes"); glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - GLERROR("ViewPort,Scissor LowRes"); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_FinalPassFrameBuffer.Unbind(); - GLERROR("END"); } - -void DrawFinalPass::OnWindowResize() +void DrawFinalPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const { - //InitializeFrameBuffers(); - CommonFunctions::GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST, - glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8); - CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - m_FinalPassFrameBuffer.Generate(); + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D, *texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); + glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr);//TODO: Renderer: Fix the precision and Resolution + GLERROR("Texture initialization failed"); +} - GLERROR("Error changing texture resolutions"); +void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const +{ + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D, *texture); + glTexStorage2D(GL_TEXTURE_2D, numMipMaps, GL_RGBA8, dimensions.x, dimensions.y); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dimensions.x, dimensions.y, format, type, texture); + glGenerateMipmap(GL_TEXTURE_2D); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + GLERROR("MipMap Texture initialization failed"); } void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); + GLERROR("forwardHandle"); GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); + GLERROR("explosionHandle"); GLuint explosionSplatMapHandle = m_ExplosionEffectSplatMapProgram->GetHandle(); - GLuint forwardSplatMapHandle = m_ForwardPlusSplatMapProgram->GetHandle(); + GLERROR("explosionSplatMapHandle"); + GLuint forwardSplatHandle = m_ForwardPlusSplatMapProgram->GetHandle(); + GLERROR("forwardSplatHandle"); GLuint forwardSkinnedHandle = m_ForwardPlusSkinnedProgram->GetHandle(); + GLERROR("forwardSkinnedHandle"); GLuint explosionSkinnedHandle = m_ExplosionEffectSkinnedProgram->GetHandle(); + GLERROR("explosionSkinnedHandle"); GLuint explosionSplatMapSkinnedHandle = m_ExplosionEffectSplatMapSkinnedProgram->GetHandle(); + GLERROR("explosionSplatMapSkinnedHandle"); GLuint forwardSplatMapSkinnedHandle = m_ForwardPlusSplatMapSkinnedProgram->GetHandle(); + GLERROR("forwardSplatSkinnedHandle"); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_SSAOPass->SSAOTexture()); - for (auto &job : jobs) { auto explosionEffectJob = std::dynamic_pointer_cast(job); if (explosionEffectJob) { switch (explosionEffectJob->Type) { case RawModel::MaterialType::Basic: - case RawModel::MaterialType::SingleTextures: - { - if (explosionEffectJob->Model->IsSkinned()) { + case RawModel::MaterialType::SingleTextures: + { + if (explosionEffectJob->Model->IsSkinned()) { + m_ExplosionEffectSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { + m_ExplosionEffectProgram->Bind(); + GLERROR("Bind ExplosionEffect program"); + //bind uniforms + BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionHandle, explosionEffectJob); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (explosionEffectJob->Model->IsSkinned()) { + m_ExplosionEffectSplatMapSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMapSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); + GLERROR("asdasd"); + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - m_ExplosionEffectSkinnedProgram->Bind(); - GLERROR("Bind ExplosionEffectSkinned program"); - //bind uniforms - BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(explosionSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - - std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } - else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - else { - m_ExplosionEffectProgram->Bind(); - GLERROR("Bind ExplosionEffect program"); - //bind uniforms - BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionHandle, explosionEffectJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(explosionHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - } - break; - } - case RawModel::MaterialType::SplatMapping: - { - if (explosionEffectJob->Model->IsSkinned()) { - m_ExplosionEffectSplatMapSkinnedProgram->Bind(); - GLERROR("Bind ExplosionEffectSplatMapSkinned program"); - //bind uniforms - BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); - GLERROR("asdasd"); - std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } - else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - else { - m_ExplosionEffectSplatMapProgram->Bind(); - GLERROR("Bind ExplosionEffectSplatMap program"); - //bind uniforms - //bind uniforms - BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob); - GLERROR("asdasd"); - } - break; - } + } else { + m_ExplosionEffectSplatMapProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMap program"); + //bind uniforms + //bind uniforms + BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob); + GLERROR("asdasd"); + } + break; + } } glDisable(GL_CULL_FACE); @@ -424,437 +393,123 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); glEnable(GL_CULL_FACE); GLERROR("explosion effect end"); - } else { - auto modelJob = std::dynamic_pointer_cast(job); - if (modelJob) { - //bind forward program - //TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID; - switch (modelJob->Type) { - case RawModel::MaterialType::Basic: - case RawModel::MaterialType::SingleTextures: - { - if (modelJob->Model->IsSkinned()) { - m_ForwardPlusSkinnedProgram->Bind(); - GLERROR("Bind ForwardPlusSkinnedProgram"); - //bind uniforms - BindModelUniforms(forwardSkinnedHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSkinnedHandle, modelJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(forwardSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + } else { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + //bind forward program + //TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID; + switch (modelJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (modelJob->Model->IsSkinned()) { + m_ForwardPlusSkinnedProgram->Bind(); + GLERROR("Bind ForwardPlusSkinnedProgram"); + //bind uniforms + BindModelUniforms(forwardSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSkinnedHandle, modelJob); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } - else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { + m_ForwardPlusProgram->Bind(); + GLERROR("Bind ForwardPlusProgram"); + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardHandle, modelJob); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (modelJob->Model->IsSkinned()) { + m_ForwardPlusSplatMapSkinnedProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); + GLERROR("asdasd"); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - else { - m_ForwardPlusProgram->Bind(); - GLERROR("Bind ForwardPlusProgram"); - //bind uniforms - BindModelUniforms(forwardHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardHandle, modelJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - } - break; - } - case RawModel::MaterialType::SplatMapping: - { - if (modelJob->Model->IsSkinned()) { - m_ForwardPlusSplatMapSkinnedProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); - GLERROR("asdasd"); - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } - else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - - } - else { - m_ForwardPlusSplatMapProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatMapHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatMapHandle, modelJob); - GLERROR("asdasd"); - } - break; - } - } - //draw - glBindVertexArray(modelJob->Model->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); - glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); - if (GLERROR("models end")) { - continue; + } else { + m_ForwardPlusSplatMapProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatHandle, modelJob); + GLERROR("asdasd"); + } + break; + } + } + //draw + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); + if (GLERROR("models end")) { + continue; + } } } } - } } -void DrawFinalPass::DrawModelRenderQueuesWithShieldCheck(std::list>& jobs, RenderScene& scene) + +void DrawFinalPass::DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene) { - GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); - GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); - GLuint explosionSplatMapHandle = m_ExplosionEffectSplatMapProgram->GetHandle(); - GLuint forwardSplatMapHandle = m_ForwardPlusSplatMapProgram->GetHandle(); - GLuint forwardSkinnedHandle = m_ForwardPlusSkinnedProgram->GetHandle(); - GLuint explosionSkinnedHandle = m_ExplosionEffectSkinnedProgram->GetHandle(); - GLuint explosionSplatMapSkinnedHandle = m_ExplosionEffectSplatMapSkinnedProgram->GetHandle(); - GLuint forwardSplatMapSkinnedHandle = m_ForwardPlusSplatMapSkinnedProgram->GetHandle(); - GLuint forwardShieldCheckHandle = m_ForwardPlusShieldCheckProgram->GetHandle(); - GLuint explosionShieldCheckHandle = m_ExplosionEffectShieldCheckProgram->GetHandle(); - GLuint explosionSplatMapShieldCheckHandle = m_ExplosionEffectSplatMapShieldCheckProgram->GetHandle(); - GLuint forwardSplatShieldCheckHandle = m_ForwardPlusSplatMapShieldCheckProgram->GetHandle(); - GLuint forwardSkinnedShieldCheckHandle = m_ForwardPlusSkinnedShieldCheckProgram->GetHandle(); - GLuint explosionSkinnedShieldCheckHandle = m_ExplosionEffectSkinnedShieldCheckProgram->GetHandle(); - GLuint explosionSplatMapSkinnedShieldCheckHandle = m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->GetHandle(); - GLuint forwardSplatMapSkinnedShieldCheckHandle = m_ForwardPlusSplatMapSkinnedShieldCheckProgram->GetHandle(); - glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); - glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); - glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); + for (auto &job : jobs) { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_SSAOPass->SSAOTexture()); + if(modelJob->Model->IsSkinned()) { + m_ShieldToStencilSkinnedProgram->Bind(); + GLuint shaderHandle = m_ShieldToStencilSkinnedProgram->GetHandle(); - glActiveTexture(GL_TEXTURE31); - glBindTexture(GL_TEXTURE_2D, m_ShieldBuffer); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { + m_ShieldToStencilProgram->Bind(); + GLuint shaderHandle = m_ShieldToStencilProgram->GetHandle(); - for (auto &job : jobs) { - auto explosionEffectJob = std::dynamic_pointer_cast(job); - if (explosionEffectJob) { - if (explosionEffectJob->IsShielded) { - switch (explosionEffectJob->Type) { - case RawModel::MaterialType::Basic: - case RawModel::MaterialType::SingleTextures: - { - if (explosionEffectJob->Model->IsSkinned()) { + 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())); - m_ExplosionEffectSkinnedShieldCheckProgram->Bind(); - GLERROR("Bind ExplosionEffectSkinned program"); - //bind uniforms - BindExplosionUniforms(explosionSkinnedShieldCheckHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSkinnedShieldCheckHandle, explosionEffectJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(explosionSkinnedShieldCheckHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + } - std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } - else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedShieldCheckHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - else { - m_ExplosionEffectShieldCheckProgram->Bind(); - GLERROR("Bind ExplosionEffect program"); - //bind uniforms - BindExplosionUniforms(explosionShieldCheckHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionShieldCheckHandle, explosionEffectJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(explosionShieldCheckHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - - } - break; - } - case RawModel::MaterialType::SplatMapping: - { - if (explosionEffectJob->Model->IsSkinned()) { - m_ExplosionEffectSplatMapSkinnedShieldCheckProgram->Bind(); - GLERROR("Bind ExplosionEffectSplatMapSkinned program"); - //bind uniforms - BindExplosionUniforms(explosionSplatMapSkinnedShieldCheckHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSplatMapSkinnedShieldCheckHandle, explosionEffectJob); - GLERROR("asdasd"); - std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } - else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedShieldCheckHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - - } - else { - m_ExplosionEffectSplatMapShieldCheckProgram->Bind(); - GLERROR("Bind ExplosionEffectSplatMap program"); - //bind uniforms - //bind uniforms - BindExplosionUniforms(explosionSplatMapShieldCheckHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSplatMapShieldCheckHandle, explosionEffectJob); - GLERROR("asdasd"); - } - break; - } - } - } else { - switch (explosionEffectJob->Type) { - case RawModel::MaterialType::Basic: - case RawModel::MaterialType::SingleTextures: - { - if (explosionEffectJob->Model->IsSkinned()) { - - m_ExplosionEffectSkinnedProgram->Bind(); - GLERROR("Bind ExplosionEffectSkinned program"); - //bind uniforms - BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(explosionSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - - std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } - else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - else { - m_ExplosionEffectProgram->Bind(); - GLERROR("Bind ExplosionEffect program"); - //bind uniforms - BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionHandle, explosionEffectJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(explosionHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - } - break; - } - case RawModel::MaterialType::SplatMapping: - { - if (explosionEffectJob->Model->IsSkinned()) { - m_ExplosionEffectSplatMapSkinnedProgram->Bind(); - GLERROR("Bind ExplosionEffectSplatMapSkinned program"); - //bind uniforms - BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); - GLERROR("asdasd"); - std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } - else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - else { - m_ExplosionEffectSplatMapProgram->Bind(); - GLERROR("Bind ExplosionEffectSplatMap program"); - //bind uniforms - //bind uniforms - BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob); - GLERROR("asdasd"); - } - break; - } - } - } - glDisable(GL_CULL_FACE); - - //draw - glBindVertexArray(explosionEffectJob->Model->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer); - glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); - glEnable(GL_CULL_FACE); - GLERROR("explosion effect end"); - } else { - auto modelJob = std::dynamic_pointer_cast(job); - if (modelJob) { - //bind forward program - //TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID; - if (modelJob->IsShielded) { - switch (modelJob->Type) { - case RawModel::MaterialType::Basic: - case RawModel::MaterialType::SingleTextures: - { - if (modelJob->Model->IsSkinned()) { - m_ForwardPlusSkinnedShieldCheckProgram->Bind(); - GLERROR("Bind ForwardPlusSkinnedProgram"); - //bind uniforms - BindModelUniforms(forwardSkinnedShieldCheckHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSkinnedShieldCheckHandle, modelJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(forwardSkinnedShieldCheckHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } - else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedShieldCheckHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - - } - else { - m_ForwardPlusShieldCheckProgram->Bind(); - GLERROR("Bind ForwardPlusProgram"); - //bind uniforms - BindModelUniforms(forwardShieldCheckHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardShieldCheckHandle, modelJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(forwardShieldCheckHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - } - break; - } - case RawModel::MaterialType::SplatMapping: - { - if (modelJob->Model->IsSkinned()) { - m_ForwardPlusSplatMapSkinnedShieldCheckProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatMapSkinnedShieldCheckHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatMapSkinnedShieldCheckHandle, modelJob); - GLERROR("asdasd"); - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } - else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedShieldCheckHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - - } - else { - m_ForwardPlusSplatMapShieldCheckProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatShieldCheckHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatShieldCheckHandle, modelJob); - GLERROR("asdasd"); - } - break; - } - } - } else { - switch (modelJob->Type) { - case RawModel::MaterialType::Basic: - case RawModel::MaterialType::SingleTextures: - { - if (modelJob->Model->IsSkinned()) { - m_ForwardPlusSkinnedProgram->Bind(); - GLERROR("Bind ForwardPlusSkinnedProgram"); - //bind uniforms - BindModelUniforms(forwardSkinnedHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSkinnedHandle, modelJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(forwardSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } - else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - - } - else { - m_ForwardPlusProgram->Bind(); - GLERROR("Bind ForwardPlusProgram"); - //bind uniforms - BindModelUniforms(forwardHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardHandle, modelJob); - glActiveTexture(GL_TEXTURE5); - glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); - } - break; - } - case RawModel::MaterialType::SplatMapping: - { - if (modelJob->Model->IsSkinned()) { - m_ForwardPlusSplatMapSkinnedProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); - GLERROR("asdasd"); - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } - else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - - } - else { - m_ForwardPlusSplatMapProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatMapHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatMapHandle, modelJob); - GLERROR("asdasd"); - } - break; - } - } - } - //draw - glBindVertexArray(modelJob->Model->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); - glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); - if (GLERROR("models end")) { - continue; - } - } - } - } + 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) @@ -949,7 +604,7 @@ void DrawFinalPass::DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene) +void DrawFinalPass::DrawToDepthBuffer(std::list>& jobs, RenderScene& scene) { @@ -957,8 +612,8 @@ void DrawFinalPass::DrawToDepthStencilBuffer(std::list(job); if(modelJob->Model->IsSkinned()) { - m_FillDepthStencilBufferSkinnedProgram->Bind(); - GLuint shaderHandle = m_FillDepthStencilBufferSkinnedProgram->GetHandle(); + m_FillDepthBufferSkinnedProgram->Bind(); + GLuint shaderHandle = m_FillDepthBufferSkinnedProgram->GetHandle(); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); @@ -972,8 +627,8 @@ void DrawFinalPass::DrawToDepthStencilBuffer(std::listBind(); - GLuint shaderHandle = m_FillDepthStencilBufferProgram->GetHandle(); + 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())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); @@ -1014,14 +669,14 @@ void DrawFinalPass::DrawSprites(std::list>&jobs, Rend glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(spriteJob->FillColor)); glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), spriteJob->FillPercentage); - glActiveTexture(GL_TEXTURE1); + glActiveTexture(GL_TEXTURE0); if (spriteJob->DiffuseTexture != nullptr) { glBindTexture(GL_TEXTURE_2D, spriteJob->DiffuseTexture->m_Texture); } else { glBindTexture(GL_TEXTURE_2D, m_ErrorTexture->m_Texture); } - glActiveTexture(GL_TEXTURE2); + glActiveTexture(GL_TEXTURE1); if (spriteJob->IncandescenceTexture != nullptr) { glBindTexture(GL_TEXTURE_2D, spriteJob->IncandescenceTexture->m_Texture); } else { @@ -1034,12 +689,14 @@ void DrawFinalPass::DrawSprites(std::list>&jobs, Rend glDrawElements(GL_TRIANGLES, spriteJob->EndIndex - spriteJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(spriteJob->StartIndex*sizeof(unsigned int))); } } + + + // m_SpriteProgram->Unbind(); } void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { - glUniform1i(glGetUniformLocation(shaderHandle, "SSAOQuality"), m_SSAOPass->TextureQuality()); GLERROR("Bind 1 uniform"); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); GLERROR("Bind 2 uniform"); @@ -1048,7 +705,7 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptrProjectionMatrix())); GLERROR("Bind 4 uniform"); - glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); GLERROR("Bind 5 uniform"); glUniform3fv(glGetUniformLocation(shaderHandle, "ExplosionOrigin"), 1, glm::value_ptr(job->ExplosionOrigin)); @@ -1081,14 +738,11 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptrFillPercentage); GLERROR("Bind 19 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor)); - GLERROR("Bind 20 uniform"); - glUniform1f(glGetUniformLocation(shaderHandle, "GlowIntensity"), job->GlowIntensity); GLERROR("END"); } void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { - glUniform1i(glGetUniformLocation(shaderHandle, "SSAOQuality"), m_SSAOPass->TextureQuality()); GLERROR("Bind 1 uniform"); GLint Location_M = glGetUniformLocation(shaderHandle, "M"); glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); @@ -1101,7 +755,7 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptrGetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glUniform2f(Location_ScreenDimensions, m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); GLERROR("Bind 5 uniform"); GLint Location_FillPercentage = glGetUniformLocation(shaderHandle, "FillPercentage"); @@ -1119,23 +773,16 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptrGlowIntensity); - GLERROR("END"); } void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptr& job) { - - switch (job->Type) { case RawModel::MaterialType::SingleTextures: case RawModel::MaterialType::Basic: { - glActiveTexture(GL_TEXTURE1); + glActiveTexture(GL_TEXTURE0); if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(job->DiffuseTexture[0]->UVRepeat)); @@ -1145,7 +792,7 @@ void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptrNormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(job->NormalTexture[0]->UVRepeat)); @@ -1155,7 +802,7 @@ void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptrSpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(job->SpecularTexture[0]->UVRepeat)); @@ -1165,7 +812,7 @@ void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptrIncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(job->IncandescenceTexture[0]->UVRepeat)); @@ -1178,7 +825,7 @@ void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptrSplatMap->Texture->m_Texture); int texturePosition = GL_TEXTURE1; @@ -1253,7 +900,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrDiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(job->DiffuseTexture[0]->UVRepeat)); @@ -1263,7 +910,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrNormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(job->NormalTexture[0]->UVRepeat)); @@ -1273,7 +920,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrSpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(job->SpecularTexture[0]->UVRepeat)); @@ -1283,7 +930,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrIncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(job->IncandescenceTexture[0]->UVRepeat)); @@ -1296,10 +943,10 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrSplatMap->Texture->m_Texture); - int texturePosition = GL_TEXTURE2; + int texturePosition = GL_TEXTURE1; //Bind 5 diffuse textures std::string UniformName = "DiffuseUVRepeat"; diff --git a/src/Engine/Rendering/DrawFinalPassState.cpp b/src/Engine/Rendering/DrawFinalPassState.cpp index 5c238985..8b5ddc8b 100644 --- a/src/Engine/Rendering/DrawFinalPassState.cpp +++ b/src/Engine/Rendering/DrawFinalPassState.cpp @@ -8,12 +8,11 @@ DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) Enable(GL_BLEND); BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Enable(GL_DEPTH_TEST); - DepthMask(GL_TRUE); Enable(GL_CULL_FACE); - // Enable(GL_STENCIL_TEST); - // StencilFunc(GL_NOTEQUAL, 1, 0xFF); - // StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); - // StencilMask(0xFF); + Enable(GL_STENCIL_TEST); + StencilFunc(GL_NOTEQUAL, 1, 0xFF); + StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); + StencilMask(0xFF); ClearColor(glm::vec4(0.f, 0.f, 0.f, 0.f)); } @@ -25,9 +24,11 @@ DrawFinalPassState::~DrawFinalPassState() DrawStencilState::DrawStencilState(GLuint frameBuffer) { BindFramebuffer(frameBuffer); + Enable(GL_STENCIL_TEST); + StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); + StencilFunc(GL_ALWAYS, 1, 0xFF); + StencilMask(0xFF); Enable(GL_DEPTH_TEST); - DepthMask(GL_TRUE); - Enable(GL_CULL_FACE); ClearColor(glm::vec4(0.f)); } diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index 9ba0d2d8..c0be4cb1 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -42,38 +42,38 @@ void FrameBuffer::Generate() GLERROR("PRE"); std::vector attachments; - if (m_BufferHandle == 0) { - glGenFramebuffers(1, &m_BufferHandle); - } + + glGenFramebuffers(1, &m_BufferHandle); glBindFramebuffer(GL_FRAMEBUFFER, m_BufferHandle); GLERROR("1"); - for (auto it = m_Resources.begin(); it != m_Resources.end(); it++) { - switch ((*it)->m_ResourceType) { - case GL_TEXTURE_2D: - glFramebufferTexture2D(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle, 0); - GLERROR("FrameBuffer generate: glFramebufferTexture2D"); + for (auto it = m_Resources.begin(); it != m_Resources.end(); it++) { + switch ((*it)->m_ResourceType) { + case GL_TEXTURE_2D: + glFramebufferTexture2D(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle, 0); + GLERROR("FrameBuffer generate: glFramebufferTexture2D"); - break; - case GL_RENDERBUFFER: - glFramebufferRenderbuffer(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle); - GLERROR("FrameBuffer generate: glFramebufferRenderbuffer"); - break; - } - GLERROR("2"); + break; + case GL_RENDERBUFFER: + glFramebufferRenderbuffer(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle); + GLERROR("FrameBuffer generate: glFramebufferRenderbuffer"); + break; + } + GLERROR("2"); - if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT && (*it)->m_Attachment != GL_STENCIL_ATTACHMENT && (*it)->m_Attachment != GL_DEPTH_STENCIL_ATTACHMENT) { - attachments.push_back((*it)->m_Attachment); - } - GLERROR("Attachment"); + 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"); - } - GLERROR("3"); GLenum* bufferTextures = &attachments[0]; glDrawBuffers(attachments.size(), bufferTextures); - if (GLERROR("GLBufferAttachement error")) { - printf(": AttachmentSize %i", attachments.size()); + if(GLERROR("4")) { + printf("hello"); } if (GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { diff --git a/src/Engine/Rendering/LightCullingPass.cpp b/src/Engine/Rendering/LightCullingPass.cpp index 1ce1f88c..0ae359db 100644 --- a/src/Engine/Rendering/LightCullingPass.cpp +++ b/src/Engine/Rendering/LightCullingPass.cpp @@ -110,34 +110,6 @@ void LightCullingPass::FillLightList(RenderScene& scene) } } - -void LightCullingPass::OnWindowResize() -{ - SetSSBOSizes(); - - glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_FrustumSSBO); - glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(Frustum)*m_NumberOfTiles, nullptr, GL_DYNAMIC_COPY); - GLERROR("m_FrustumSSBO"); - - glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightSSBO); - glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(LightSource) * 200, nullptr, GL_DYNAMIC_COPY); - GLERROR("m_LightSSBO"); - - glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightGridSSBO); - glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(LightGrid)*m_NumberOfTiles, nullptr, GL_DYNAMIC_COPY); - GLERROR("m_LightGridSSBO"); - - glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightOffsetSSBO); - glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightOffset), &m_LightOffset, GL_DYNAMIC_COPY); - GLERROR("m_LightOffsetSSBO"); - - glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightIndexSSBO); - glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(float)*m_NumberOfTiles*MAX_LIGHTS_PER_TILE, m_LightIndex, GL_DYNAMIC_COPY); - GLERROR("m_LightIndexSSBO"); - - glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); -} - void LightCullingPass::InitializeSSBOs() { glGenBuffers(1, &m_FrustumSSBO); diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 7b9e2498..ecd0a4b8 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -15,21 +15,19 @@ PickingPass::~PickingPass() } - - void PickingPass::InitializeTextures() { - CommonFunctions::GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, + GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE); - - CommonFunctions::GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST, - glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT); } void PickingPass::InitializeFrameBuffers() { + glGenRenderbuffers(1, &m_DepthBuffer); + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); + m_PickingBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0))); m_PickingBuffer.Generate(); } @@ -55,7 +53,6 @@ void PickingPass::InitializeShaderPrograms() void PickingPass::Draw(RenderScene& scene) { - GLERROR("PRE"); PickingPassState* state = new PickingPassState(m_PickingBuffer.GetHandle()); //TODO: Render: Add code for more jobs than modeljobs. @@ -64,9 +61,7 @@ void PickingPass::Draw(RenderScene& scene) m_PickingProgram->Bind(); if (scene.ClearDepth) { - //glClear(GL_DEPTH_BUFFER_BIT); - state->Disable(GL_DEPTH_TEST); - state->DepthMask(GL_FALSE); + glClear(GL_DEPTH_BUFFER_BIT); } m_Camera = scene.Camera; @@ -239,52 +234,6 @@ void PickingPass::Draw(RenderScene& scene) } } - for (auto& job : scene.Jobs.SpriteJob) { - auto spriteJob = std::dynamic_pointer_cast(job); - if (!spriteJob->Pickable) { - continue; - } - RenderState jobState; - - if (spriteJob) { - if (spriteJob->Depth == 0) { - jobState.Disable(GL_DEPTH_TEST); - } - int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; - - PickingInfo pickInfo; - pickInfo.Entity = spriteJob->Entity; - pickInfo.World = spriteJob->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; - - m_PickingProgram->Bind(); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(spriteJob->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]))); - - glBindVertexArray(spriteJob->Model->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, spriteJob->Model->ElementBuffer); - glDrawElements(GL_TRIANGLES, spriteJob->EndIndex - spriteJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(spriteJob->StartIndex * sizeof(unsigned int))); - } - } - /* for (auto &job : scene.Jobs.TransparentShieldedObjects) { auto modelJob = std::dynamic_pointer_cast(job); @@ -357,9 +306,10 @@ void PickingPass::Draw(RenderScene& scene) delete state; } + + void PickingPass::ClearPicking() { - GLERROR("PRE"); m_PickingColorsToEntity.clear(); m_EntityColors.clear(); m_ColorCounter[0] = 0; @@ -367,16 +317,8 @@ void PickingPass::ClearPicking() m_PickingBuffer.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_PickingBuffer.Unbind(); - GLERROR("END"); -} - - -void PickingPass::OnWindowResize() -{ - InitializeTextures(); - m_PickingBuffer.Generate(); } PickData PickingPass::Pick(glm::vec2 screenCoord) @@ -408,3 +350,16 @@ PickData PickingPass::Pick(glm::vec2 screenCoord) pickData.World = pickInfo.World; return pickData; } + +void PickingPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const +{ + //TODO: Renderer: Make this in a sparate class + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D, *texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); + glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr);//TODO: Renderer: Fix the precision and Resolution + GLERROR("Texture initialization failed"); +} diff --git a/src/Engine/Rendering/PickingPassState.cpp b/src/Engine/Rendering/PickingPassState.cpp index 767b9577..0c4f4aca 100644 --- a/src/Engine/Rendering/PickingPassState.cpp +++ b/src/Engine/Rendering/PickingPassState.cpp @@ -3,17 +3,16 @@ PickingPassState::PickingPassState(GLuint frameBuffer) { - GLERROR("PRE"); + GLERROR("---2"); BindFramebuffer(frameBuffer); - GLERROR("Bind Framebuffer"); + GLERROR("---3"); Enable(GL_DEPTH_TEST); Enable(GL_CULL_FACE); Disable(GL_BLEND); + glm::vec4 clearColor = glm::vec4(0.f); //ClearColor(clearColor); //Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - GLERROR("END"); - } PickingPassState::~PickingPassState() diff --git a/src/Engine/Rendering/RenderState.cpp b/src/Engine/Rendering/RenderState.cpp index 56812f9a..26ba18a1 100644 --- a/src/Engine/Rendering/RenderState.cpp +++ b/src/Engine/Rendering/RenderState.cpp @@ -135,26 +135,6 @@ bool RenderState::DepthMask(GLboolean flag) return !GLERROR("DepthMask"); } -bool RenderState::DepthFunc(GLenum func) -{ - GLint original; - glGetIntegerv(GL_DEPTH_FUNC, &original); - m_ResetFunctions.push_back(std::bind(glDepthFunc, original)); - glDepthFunc(func); - return !GLERROR("DepthFunc"); -} - -bool RenderState::AlphaFunc(GLenum func, GLclampf thresholder) -{ - GLint originalFunc; - glGetIntegerv(GL_ALPHA_TEST_FUNC, &originalFunc); - GLint originalRef; - glGetIntegerv(GL_ALPHA_TEST_REF, &originalRef); - m_ResetFunctions.push_back(std::bind(glAlphaFunc, originalFunc, originalRef)); - glAlphaFunc(func, thresholder); - return !GLERROR("AlphaFunc"); -} - RenderState::~RenderState() { for (auto& f : boost::adaptors::reverse(m_ResetFunctions)) { diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index a1f00c88..665c4027 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -52,101 +52,6 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl continue; } - glm::mat4 modelMatrix; - - // See a sprite is an SpriteIndicator - bool isIndicator = false; - if (world->HasComponent(entity.ID, "SpriteIndicator")) - { - auto indicator = entity["SpriteIndicator"]; - - float minScale = (float)(double)indicator["MinScale"]; - bool hasTeam = indicator["VisibleForSingleTeamOnly"]; - isIndicator = true; - glm::vec3 pos = Transform::AbsolutePosition(entity); - - - EntityWrapper entityTeam; - if (hasTeam && (entity.HasComponent("Team") || entity.FirstParentWithComponent("Team").Valid()) && m_LocalPlayer.World != nullptr) { - if (!entity.HasComponent("Team")) { - entityTeam = entity.FirstParentWithComponent("Team"); - } - else { - entityTeam = entity; - } - - ComponentWrapper& entityTeamComponent = entityTeam["Team"]; - ComponentWrapper& localComponent = m_LocalPlayer["Team"]; - int entityTeamInt = entityTeamComponent["Team"]; - int localComponentInt = localComponent["Team"]; - int SpectatorInt = localComponent["Team"].Enum("Spectator"); - if (entityTeamInt != localComponentInt && localComponentInt != SpectatorInt) { - continue; - } - } - - // Code for check if sprite is inside or outside of screen - //glm::vec4 projectedPos = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * glm::vec4(pos, 1.0f); - //projectedPos /= projectedPos.w; - //// Check if inside of outside of screen. - //if (projectedPos.x < -1.0f || projectedPos.x > 1.0f || projectedPos.y < -1.0f || projectedPos.y > 1.0f) { - // // is outside of screen - //} else { - // // is inside of screen - //} - - - glm::vec3 zAxis = glm::vec3(0.0f, 1.0f, 0.0f); - glm::vec3 normal = pos - m_Camera->Position(); - - //float distance = glm::length(normal); - //if (distance < minDistance) { - // pos = pos - glm::normalize(normal) * (distance - minDistance); - //} else if (distance > maxDistance) { - // pos = pos - glm::normalize(normal) * (distance - maxDistance); - //} - normal.y = 0; - normal = glm::normalize(normal); - glm::vec3 right = glm::cross(normal, zAxis); - glm::vec3 up = glm::cross(right, normal); - - modelMatrix[0][0] = right.x; - modelMatrix[0][1] = right.y; - modelMatrix[0][2] = right.z; - modelMatrix[0][3] = 0.0f; - - modelMatrix[1][0] = zAxis.x; - modelMatrix[1][1] = zAxis.y; - modelMatrix[1][2] = zAxis.z; - modelMatrix[1][3] = 0.0f; - - modelMatrix[2][0] = normal.x; - modelMatrix[2][1] = normal.y; - modelMatrix[2][2] = normal.z; - modelMatrix[2][3] = 0.0f; - - modelMatrix[3][0] = pos.x; - modelMatrix[3][1] = pos.y; - modelMatrix[3][2] = pos.z; - modelMatrix[3][3] = 1.0f; - - glm::mat4 tranformationMatrix = modelMatrix * glm::scale(Transform::AbsoluteScale(entity)); - glm::vec4 tmp = tranformationMatrix * glm::vec4(glm::vec3(0.5, 0.5, 0), 1.0f); - glm::vec2 projectedTopRight = m_Camera->WorldToScreen(glm::vec3(tmp), m_Renderer->GetViewportSize()); - tmp = tranformationMatrix * glm::vec4(glm::vec3(-0.5, -0.5, 0), 1.0f); - glm::vec2 projectedBottomLeft = m_Camera->WorldToScreen(glm::vec3(tmp), m_Renderer->GetViewportSize()); - - float diag = glm::length(projectedBottomLeft - projectedTopRight); - if (diag < minScale) { - tranformationMatrix = tranformationMatrix * glm::scale(glm::vec3(minScale / diag, minScale / diag, minScale / diag)); - } - modelMatrix = tranformationMatrix; - } - else { - modelMatrix = Transform::ModelMatrix(entity.ID, world); - } - - std::string diffuseResource = cSprite["DiffuseTexture"]; std::string glowResource = cSprite["GlowMap"]; bool depthSorted = cSprite["DepthSort"]; @@ -162,7 +67,11 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl fillColor = (glm::vec4)fillComponent["Color"]; } - std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted, isIndicator)); + glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, world); + //modelMatrix *= m_Camera->BillboardMatrix(); + + + std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted)); jobs.push_back(spriteJob); } @@ -184,6 +93,7 @@ bool RenderSystem::isEntityVisible(EntityWrapper& entity) ) { return false; } + return true; } @@ -240,8 +150,6 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) fillColor = (glm::vec4)fillComponent["Color"]; } - bool isShielded = m_World->HasComponent(cModel.EntityID, "Shielded") || m_World->HasComponent(cModel.EntityID, "Player"); - glm::mat4 modelMatrix = Transform::ModelMatrix(cModel.EntityID, m_World); //Loop through all materialgroups of a model for (auto matGroup : model->MaterialGroups()) { @@ -257,19 +165,20 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) cModel, m_World, fillColor, - fillPercentage, - isShielded + fillPercentage )); if (m_World->HasComponent(cModel.EntityID, "Shield")){ explosionEffectJob->CalculateHash(); Jobs.ShieldObjects.push_back(explosionEffectJob); - } else if (isShielded) { + } else if (m_World->HasComponent(cModel.EntityID, "Shielded") + || m_World->HasComponent(cModel.EntityID, "Player")) { + if (explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { cModel["Transparent"] = true; } if (cModel["Transparent"]) { - Jobs.TransparentObjects.push_back(explosionEffectJob); + Jobs.TransparentShieldedObjects.push_back(explosionEffectJob); } else { explosionEffectJob->CalculateHash(); Jobs.OpaqueShieldedObjects.push_back(explosionEffectJob); @@ -295,20 +204,20 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) cModel, m_World, fillColor, - fillPercentage, - isShielded + fillPercentage )); if (m_World->HasComponent(cModel.EntityID, "Shield")) { modelJob->CalculateHash(); Jobs.ShieldObjects.push_back(modelJob); - } else if (isShielded) { + } 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"]) { - Jobs.TransparentObjects.push_back(modelJob); + Jobs.TransparentShieldedObjects.push_back(modelJob); } else { modelJob->CalculateHash(); Jobs.OpaqueShieldedObjects.push_back(modelJob); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 3ce985b6..be84160c 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -1,11 +1,7 @@ #include "Rendering/Renderer.h" -std::unordered_map Renderer::m_WindowToRenderer; - void Renderer::Initialize() { - m_SSAO_Quality = m_Config->Get("SSAO.Quality", 0); - m_GLOW_Quality = m_Config->Get("GLOW.Quality", 0); InitializeWindow(); InitializeRenderPasses(); @@ -16,6 +12,7 @@ void Renderer::Initialize() m_TextPass = new TextPass(); m_TextPass->Initialize(); + /* m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.obj"); m_UnitQuad = ResourceManager::Load("Models/Core/UnitQuad.obj"); m_UnitSphere = ResourceManager::Load("Models/Core/UnitSphere.obj");*/ @@ -23,18 +20,6 @@ void Renderer::Initialize() m_ImGuiRenderPass = new ImGuiRenderPass(this, m_EventBroker); } -void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height) -{ - glViewport(0, 0, width, height); - Renderer* currentRenderer = m_WindowToRenderer[window]; - currentRenderer->m_ViewportSize = Rectangle(width, height); - currentRenderer->m_PickingPass->OnWindowResize(); - currentRenderer->m_DrawFinalPass->OnWindowResize(); - currentRenderer->m_LightCullingPass->OnWindowResize(); - currentRenderer->m_DrawBloomPass->OnWindowResize(); - currentRenderer->m_SSAOPass->OnWindowResize(); -} - void Renderer::InitializeWindow() { // Initialize GLFW @@ -54,7 +39,6 @@ void Renderer::InitializeWindow() LOG_ERROR("GLFW: Failed to create window"); exit(EXIT_FAILURE); } - glfwSetFramebufferSizeCallback(m_Window, &glfwFrameBufferCallback); glfwMakeContextCurrent(m_Window); // GL version info @@ -75,10 +59,8 @@ void Renderer::InitializeWindow() exit(EXIT_FAILURE); } - m_WindowToRenderer[m_Window] = this; - int windowSize[2]; - glfwGetFramebufferSize(m_Window, &windowSize[0], &windowSize[1]); + glfwGetWindowSize(m_Window, &windowSize[0], &windowSize[1]); m_ViewportSize = Rectangle(windowSize[0], windowSize[1]); } @@ -91,6 +73,9 @@ void Renderer::InitializeShaders() //m_ExplosionEffectProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ExplosionEffect.frag.glsl"))); //m_ExplosionEffectProgram->Compile(); //m_ExplosionEffectProgram->Link(); + + + } void Renderer::InputUpdate(double dt) @@ -108,77 +93,40 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { - GLERROR("PRE"); - glBindFramebuffer(GL_FRAMEBUFFER, 0); - ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0Gaussian\0Picking\0Ambient Occlusion"); - ImGui::Combo("CubeMap", &m_CubeMapTexture, "Nevada(512)\0Sky(1024)"); - if(m_CubeMapTexture == 0) { - m_CubeMapPass->LoadTextures("Nevada"); - } else if (m_CubeMapTexture == 1) { - m_CubeMapPass->LoadTextures("Sky"); - } - - ImGui::SliderInt("SSAO Quality", &m_SSAO_Quality, 0, 3); - ImGui::SliderInt("Glow Quality", &m_GLOW_Quality, 0, 3); - m_SSAOPass->ChangeQuality(m_SSAO_Quality); - m_DrawBloomPass->ChangeQuality(m_GLOW_Quality); - GLERROR("SSAO Settings"); + 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); - //Clear other buffers - PerformanceTimer::StartTimer("Renderer-ClearBuffers"); + //Clear other buffers m_PickingPass->ClearPicking(); m_DrawFinalPass->ClearBuffer(); m_DrawBloomPass->ClearBuffer(); - m_SSAOPass->ClearBuffer(); - PerformanceTimer::StopTimer("Renderer-ClearBuffers"); - GLERROR("ClearBuffers"); - for (auto scene : frame.RenderScenes) { - PerformanceTimer::StartTimer("Renderer-PickingPass"); - m_PickingPass->Draw(*scene); - GLERROR("Drawing pickingpass"); - PerformanceTimer::StopTimer("Renderer-PickingPass"); - } - PerformanceTimer::StartTimer("Renderer-AO generation"); - m_SSAOPass->Draw(*m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); - PerformanceTimer::StopTimer("Renderer-AO generation"); + for (auto scene : frame.RenderScenes){ - PerformanceTimer::StartTimer("Renderer-Depth"); + SortRenderJobsByDepth(*scene); GLERROR("SortByDepth"); - PerformanceTimer::StartTimerAndStopPrevious("Renderer-Generate Frustrums"); + m_PickingPass->Draw(*scene); + GLERROR("Drawing pickingpass"); m_LightCullingPass->GenerateNewFrustum(*scene); GLERROR("Generate frustums"); - PerformanceTimer::StartTimerAndStopPrevious("Renderer-Filling Light List"); m_LightCullingPass->FillLightList(*scene); GLERROR("Filling light list"); - PerformanceTimer::StartTimerAndStopPrevious("Renderer-Light Culling"); m_LightCullingPass->CullLights(*scene); GLERROR("LightCulling"); - PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Geometry+Light"); - m_DrawFinalPass->Draw(*scene); + m_DrawFinalPass->Draw(*scene); GLERROR("Draw Geometry+Light"); //m_DrawScenePass->Draw(*scene); - PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Text"); m_TextPass->Draw(*scene, *m_DrawFinalPass->FinalPassFrameBuffer()); GLERROR("Draw Text"); - PerformanceTimer::StopTimer("Renderer-Draw Text"); - } - PerformanceTimer::StartTimer("Renderer-Draw Bloom"); + } m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); - PerformanceTimer::StopTimer("Renderer-Draw Bloom"); - if (m_DebugTextureToDraw == 0) { - PerformanceTimer::StartTimer("Renderer-Color Correction Pass"); - m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), frame.Gamma, frame.Exposure); - PerformanceTimer::StopTimer("Renderer-Color Correction Pass"); + m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure); } - - PerformanceTimer::StartTimer("Renderer-Misc Debug Draws"); if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); } @@ -186,24 +134,21 @@ 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()); } - if (m_DebugTextureToDraw == 5) { - m_DrawScreenQuadPass->Draw(m_SSAOPass->SSAOTexture()); - } - PerformanceTimer::StopTimer("Renderer-Misc Debug Draws"); - PerformanceTimer::StartTimer("Renderer-ImGuiRenderPass"); m_ImGuiRenderPass->Draw(); GLERROR("Imgui draw"); - PerformanceTimer::StopTimer("Renderer-ImGuiRenderPass"); - - PerformanceTimer::StartTimer("Renderer-SwapBuffer"); glfwSwapBuffers(m_Window); - PerformanceTimer::StopTimer("Renderer-SwapBuffer"); } PickData Renderer::Pick(glm::vec2 screenCoord) @@ -242,11 +187,8 @@ void Renderer::InitializeRenderPasses() { m_PickingPass = new PickingPass(this, m_EventBroker); m_LightCullingPass = new LightCullingPass(this); - m_CubeMapPass = new CubeMapPass(this); - m_SSAOPass = new SSAOPass(this, m_Config); - m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass, m_SSAOPass); + m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass); m_DrawScreenQuadPass = new DrawScreenQuadPass(this); - m_DrawBloomPass = new DrawBloomPass(this, m_Config); + m_DrawBloomPass = new DrawBloomPass(this); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); - -} \ No newline at end of file +} diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp deleted file mode 100644 index 9992db70..00000000 --- a/src/Engine/Rendering/SSAOPass.cpp +++ /dev/null @@ -1,288 +0,0 @@ -#include "Rendering/SSAOPass.h" - -SSAOPass::SSAOPass(IRenderer* renderer, ConfigFile* config) - : m_Renderer(renderer) - , m_Config(config) -{ - m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); - - ChangeQuality(m_Config->Get("SSAO.Quality", 0)); - -} - -void SSAOPass::ChangeQuality(int quality) -{ - if (m_Quality == quality) { - return; - } - - m_Quality = quality; - - if (m_Quality == 0) { - CommonFunctions::DeleteTexture(&m_SSAOTexture); - CommonFunctions::DeleteTexture(&m_SSAOViewSpaceZTexture); - CommonFunctions::DeleteTexture(&m_Gaussian_horiz); - CommonFunctions::DeleteTexture(&m_Gaussian_vert); - return; - } - - std::string qStr = std::to_string(m_Quality); - Setting( - m_Config->Get("SSAO" + qStr + ".Radius", 0.01), - m_Config->Get("SSAO" + qStr + ".Bias", 0.012), - m_Config->Get("SSAO" + qStr + ".Contrast", 1.0), - m_Config->Get("SSAO" + qStr + ".Intensity", 1.0), - m_Config->Get("SSAO" + qStr + ".NumSamples", 0), - m_Config->Get("SSAO" + qStr + ".NumTurns", 0), - m_Config->Get("SSAO" + qStr + ".NumIterations", 0), - m_Config->Get("SSAO" + qStr + ".TextureQuality", 4) - ); - - - - m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); - - InitializeTexture(); - InitializeBuffer(); - InitializeShaderProgram(); - - -} - -void SSAOPass::InitializeShaderProgram() -{ - m_SSAOProgram = ResourceManager::Load("##SSAOProgram"); - if (m_SSAOProgram->GetHandle() == 0) { - m_SSAOProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); - m_SSAOProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAO.frag.glsl"))); - m_SSAOProgram->Compile(); - m_SSAOProgram->Link(); - } - - m_SSAOViewSpaceZProgram = ResourceManager::Load("##SSAOViewSpaceZProgram"); - if (m_SSAOViewSpaceZProgram->GetHandle() == 0) { - m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); - m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAOViewSpaceZ.frag.glsl"))); - m_SSAOViewSpaceZProgram->Compile(); - m_SSAOViewSpaceZProgram->Link(); - } - - m_GaussianProgram_horiz = ResourceManager::Load("##GaussianProgramHoriz"); - if (m_GaussianProgram_horiz->GetHandle() == 0) { - m_GaussianProgram_horiz->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_horiz.vert.glsl"))); - m_GaussianProgram_horiz->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_horiz.frag.glsl"))); - m_GaussianProgram_horiz->Compile(); - m_GaussianProgram_horiz->Link(); - } - - m_GaussianProgram_vert = ResourceManager::Load("##GaussianProgramVert"); - if (m_GaussianProgram_vert->GetHandle() == 0) { - m_GaussianProgram_vert->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_vert.vert.glsl"))); - m_GaussianProgram_vert->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_vert.frag.glsl"))); - m_GaussianProgram_vert->Compile(); - m_GaussianProgram_vert->Link(); - } -} - -void SSAOPass::InitializeTexture() { - CommonFunctions::GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); - CommonFunctions::GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R32F, GL_RED, GL_FLOAT); - - CommonFunctions::GenerateTexture(&m_Gaussian_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); - CommonFunctions::GenerateTexture(&m_Gaussian_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); -} - -void SSAOPass::InitializeBuffer() -{ - if (m_SSAOFramBuffer.GetHandle() == 0) { - m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); - } - m_SSAOFramBuffer.Generate(); - - - if (m_SSAOViewSpaceZFramBuffer.GetHandle() == 0) { - m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); - } - m_SSAOViewSpaceZFramBuffer.Generate(); - - - - if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) { - m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_Gaussian_horiz, GL_COLOR_ATTACHMENT0))); - } - m_GaussianFrameBuffer_horiz.Generate(); - - - if (m_GaussianFrameBuffer_vert.GetHandle() == 0) { - m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_Gaussian_vert, GL_COLOR_ATTACHMENT0))); - } - m_GaussianFrameBuffer_vert.Generate(); - -} - -void SSAOPass::ClearBuffer() -{ - if (m_Quality == 0) { - return; - } - m_SSAOFramBuffer.Bind(); - glClearColor(1.f, 1.f, 1.f, 1.f); - glClear(GL_COLOR_BUFFER_BIT); - m_SSAOFramBuffer.Unbind(); - - m_SSAOViewSpaceZFramBuffer.Bind(); - glClearColor(1.f, 1.f, 1.f, 1.f); - glClear(GL_COLOR_BUFFER_BIT); - m_SSAOViewSpaceZFramBuffer.Unbind(); - - m_GaussianFrameBuffer_horiz.Bind(); - glClearColor(1.f, 1.f, 1.f, 1.f); - glClear(GL_COLOR_BUFFER_BIT); - m_GaussianFrameBuffer_horiz.Unbind(); - - m_GaussianFrameBuffer_vert.Bind(); - glClearColor(1.f, 1.f, 1.f, 1.f); - glClear(GL_COLOR_BUFFER_BIT); - m_GaussianFrameBuffer_vert.Unbind(); -} - -void SSAOPass::Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int numOfTurns, int iterations, int quality) { - m_Radius = radius; - m_Bias = bias; - m_Contrast = contrast; - m_IntensityScale = intensityScale; - m_NumOfSamples = numOfSamples; - m_NumOfTurns = numOfTurns; - m_Iterations = iterations; - m_TextureQuality = quality; -} - -void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) -{ - if (m_Quality == 0) { - return; - } - - SSAOPassState state; - GLuint viewSpaceZPShaderHandle = m_SSAOViewSpaceZProgram->GetHandle(); - GLuint SSAOShaderHandle = m_SSAOProgram->GetHandle(); - - m_SSAOViewSpaceZFramBuffer.Bind(); - m_SSAOViewSpaceZProgram->Bind(); - - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, depthBuffer); - glm::vec3 clipInfo = glm::vec3( - (camera->NearClip() * camera->FarClip()), - (camera->NearClip() - camera->FarClip()), - (camera->FarClip()) - ); - /*glm::vec3 clipInfo = glm::vec3( - (camera->NearClip()), - (-1.0f), - (+1.0f) - );*/ - glViewport(0, 0, (m_Renderer->GetViewportSize().Width >> m_TextureQuality), (m_Renderer->GetViewportSize().Height >> m_TextureQuality)); //JOHAN TODO: Get this into state - glUniform3fv(glGetUniformLocation(viewSpaceZPShaderHandle, "ClipInfo"), 1, glm::value_ptr(clipInfo)); - - glBindVertexArray(m_ScreenQuad->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); - - glm::vec4 projInfo = glm::vec4( - ((1.0 - camera->ProjectionMatrix()[0][2]) / camera->ProjectionMatrix()[0][0]), - (-2.0 / ((m_Renderer->GetViewportSize().Width >> m_TextureQuality) * camera->ProjectionMatrix()[0][0])), - ((1.0 + camera->ProjectionMatrix()[1][2]) / camera->ProjectionMatrix()[1][1]), - (-2.0 / ((m_Renderer->GetViewportSize().Height >> m_TextureQuality) * camera->ProjectionMatrix()[1][1])) - ); - - - m_SSAOFramBuffer.Bind(); - m_SSAOProgram->Bind(); - - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_SSAOViewSpaceZTexture); - - // How many pixel there are in a 1m long object 1m away from the camera - glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uProjScale"), (m_Renderer->GetViewportSize().Height >> m_TextureQuality) / (-2.0f * glm::tan(camera->FOV() * 0.5f))); - - glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uRadius"), m_Radius); - glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uBias"), m_Bias); - glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uContrast"), m_Contrast); - glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uIntensityScale"), m_IntensityScale); - glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfSamples"), m_NumOfSamples); - glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfTurns"), m_NumOfTurns); - - glUniform4fv(glGetUniformLocation(SSAOShaderHandle, "uProjInfo"), 1, glm::value_ptr(projInfo)); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); - - DrawBloomPassState BloomState; - GLuint shaderHandle_horiz = m_GaussianProgram_horiz->GetHandle(); - GLuint shaderHandle_vert = m_GaussianProgram_vert->GetHandle(); - - m_GaussianFrameBuffer_horiz.Bind(); - m_GaussianProgram_horiz->Bind(); - - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_SSAOTexture); - - glBindVertexArray(m_ScreenQuad->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); - //Iterate some times to make it more gaussian. - for (int i = 1; i < m_Iterations; i++) { - //Vertical pass - m_GaussianFrameBuffer_vert.Bind(); - m_GaussianProgram_vert->Bind(); - - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_Gaussian_horiz); - - glBindVertexArray(m_ScreenQuad->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); - //horizontal pass - m_GaussianFrameBuffer_vert.Unbind(); - - m_GaussianFrameBuffer_horiz.Bind(); - m_GaussianProgram_horiz->Bind(); - - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_Gaussian_vert); - - glBindVertexArray(m_ScreenQuad->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); - m_GaussianFrameBuffer_horiz.Unbind(); - } - - //final vertical gaussian after the iterations are done - - m_GaussianFrameBuffer_vert.Bind(); - m_GaussianProgram_vert->Bind(); - - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_Gaussian_horiz); - glBindVertexArray(m_ScreenQuad->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); - - m_GaussianFrameBuffer_vert.Unbind(); - - glViewport(0, 0, (m_Renderer->GetViewportSize().Width), (m_Renderer->GetViewportSize().Height)); -} - -void SSAOPass::OnWindowResize() { - if (m_Quality == 0) { - return; - } - - InitializeTexture(); - InitializeBuffer(); -} \ No newline at end of file diff --git a/src/Engine/Rendering/SSAOPassState.cpp b/src/Engine/Rendering/SSAOPassState.cpp deleted file mode 100644 index 7dd49841..00000000 --- a/src/Engine/Rendering/SSAOPassState.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "Rendering/SSAOPassState.h" - - -SSAOPassState::SSAOPassState() -{ - //BindFramebuffer(0); - Disable(GL_BLEND); - Disable(GL_DEPTH_TEST); - Disable(GL_CULL_FACE); -} - -SSAOPassState::~SSAOPassState() -{ - -} - diff --git a/src/Engine/Rendering/ShaderProgram.cpp b/src/Engine/Rendering/ShaderProgram.cpp index ae536bc0..9c26c15c 100644 --- a/src/Engine/Rendering/ShaderProgram.cpp +++ b/src/Engine/Rendering/ShaderProgram.cpp @@ -98,7 +98,8 @@ void ShaderProgram::AddShader(std::shared_ptr shader) void ShaderProgram::Compile() { - if (m_ShaderProgramHandle == 0) { + if (m_ShaderProgramHandle == 0) + { m_ShaderProgramHandle = glCreateProgram(); } diff --git a/src/Engine/Rendering/Texture.cpp b/src/Engine/Rendering/Texture.cpp index 03347044..256246a9 100644 --- a/src/Engine/Rendering/Texture.cpp +++ b/src/Engine/Rendering/Texture.cpp @@ -18,7 +18,6 @@ Texture::Texture(std::string path) this->Width = img->Width; this->Height = img->Height; - this->Data = img->Data; GLint format; switch (img->Format) { @@ -29,7 +28,6 @@ Texture::Texture(std::string path) format = GL_RGBA; break; } - // Construct the OpenGL texture glGenTextures(1, &m_Texture); diff --git a/src/Engine/Rendering/Util/CommonFunctions.cpp b/src/Engine/Rendering/Util/CommonFunctions.cpp index 913e005e..382cb790 100644 --- a/src/Engine/Rendering/Util/CommonFunctions.cpp +++ b/src/Engine/Rendering/Util/CommonFunctions.cpp @@ -17,46 +17,3 @@ Texture* CommonFunctions::LoadTexture(std::string path, bool threaded) return img; } - -void CommonFunctions::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) -{ - glDeleteTextures(1, texture); - glGenTextures(1, texture); - glBindTexture(GL_TEXTURE_2D, *texture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); - glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr); - GLERROR("Texture initialization failed"); -} - -void CommonFunctions::GenerateMultiSampleTexture(GLuint* texture, int numSamples, glm::vec2 dimensions, GLint internalFormat) -{ - glDeleteTextures(1, texture); - glGenTextures(1, texture); - glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, *texture); - glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, numSamples, internalFormat, dimensions.x, dimensions.y, false); - GLERROR("Texture initialization failed"); -} - - -void CommonFunctions::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) -{ - glGenTextures(1, texture); - glBindTexture(GL_TEXTURE_2D, *texture); - glTexStorage2D(GL_TEXTURE_2D, numMipMaps, GL_RGBA8, dimensions.x, dimensions.y); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dimensions.x, dimensions.y, format, type, texture); - glGenerateMipmap(GL_TEXTURE_2D); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - GLERROR("MipMap Texture initialization failed"); -} - -void CommonFunctions::DeleteTexture(GLuint* texture) -{ - glDeleteTextures(1, texture); - *texture = 0; -} \ No newline at end of file diff --git a/src/Engine/Rendering/Util/ScreenCoords.cpp b/src/Engine/Rendering/Util/ScreenCoords.cpp index 8b7768c8..36f1295e 100644 --- a/src/Engine/Rendering/Util/ScreenCoords.cpp +++ b/src/Engine/Rendering/Util/ScreenCoords.cpp @@ -31,27 +31,22 @@ glm::vec3 ScreenCoords::ToWorldPos(glm::vec2 screenCoord, float depth, float scr ScreenCoords::PixelData ScreenCoords::ToPixelData(float x, float y, FrameBuffer* PickDataBuffer, GLuint DepthBuffer) { - GLERROR("Pre"); PickDataBuffer->Bind(); unsigned char pdata[3]; glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pdata); - GLERROR("glReadPixels(pdata) Error"); PickDataBuffer->Unbind(); - glBindFramebuffer(GL_FRAMEBUFFER, DepthBuffer); - GLERROR("glBindFramebuffer(DepthBuffer) Error"); + glBindFramebuffer(GL_FRAMEBUFFER, DepthBuffer); float depthData; glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depthData); - GLERROR("glReadPixels(depthData) Error"); glBindFramebuffer(GL_FRAMEBUFFER, 0); - GLERROR("glBindFramebuffer(0) Error"); PixelData p; p.Color[0] = (int)pdata[0]; p.Color[1] = (int)pdata[1]; p.Depth = depthData; - GLERROR("End"); + GLERROR("ScreenCoords::ToPixelData Error"); return p; } diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 61c1ac9e..2cc5d715 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -16,7 +16,7 @@ #include "Game/Systems/PickupSpawnSystem.h" #include "Game/Systems/AmmoPickupSystem.h" #include "Game/Systems/DamageIndicatorSystem.h" -#include "Game/Systems/Weapon/DefenderWeaponBehaviour.h" +#include "Game/Systems/Weapon/WeaponSystem.h" #include "Rendering/AnimationSystem.h" #include "Game/Systems/HealthHUDSystem.h" #include "Rendering/BoneAttachmentSystem.h" @@ -27,8 +27,6 @@ #include "Game/Systems/AmmunitionHUDSystem.h" #include "Game/Systems/KillFeedSystem.h" #include "Game/Systems/BoostSystem.h" -#include "GUI/ButtonSystem.h" -#include "GUI/MainMenuSystem.h" Game::Game(int argc, char* argv[]) @@ -49,12 +47,13 @@ Game::Game(int argc, char* argv[]) ResourceManager::UseThreading = m_Config->Get("Multithreading.ResourceLoading", true); DisableMemoryPool::Value = m_Config->Get("Debug.DisableMemoryPool", false); LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get("Debug.LogLevel", 1)); + PlayerSpawnSystem::SetRespawnTime(m_Config->Get("Debug.RespawnTime", 15.0f)); // Create the core event broker m_EventBroker = new EventBroker(); // Create the renderer - m_Renderer = new Renderer(m_EventBroker, m_Config); + m_Renderer = new Renderer(m_EventBroker); m_Renderer->SetFullscreen(m_Config->Get("Video.Fullscreen", false)); m_Renderer->SetVSYNC(m_Config->Get("Video.VSYNC", false)); m_Renderer->SetResolution(Rectangle::Rectangle( @@ -74,6 +73,11 @@ Game::Game(int argc, char* argv[]) m_InputProxy->AddHandler(); m_InputProxy->LoadBindings("Input.ini"); + // Create the root level GUI frame + m_FrameStack = new GUI::Frame(m_EventBroker); + m_FrameStack->Width = m_Renderer->Resolution().Width; + m_FrameStack->Height = m_Renderer->Resolution().Height; + // Create a world m_World = new World(m_EventBroker); std::string mapToLoad = m_Config->Get("Debug.LoadMap", ""); @@ -98,10 +102,6 @@ Game::Game(int argc, char* argv[]) m_NetworkClient->Connect(m_NetworkAddress, m_NetworkPort); m_Renderer->SetWindowTitle(m_Renderer->WindowTitle() + " CLIENT"); } - } else { - // If network is disabled, pretend we're a server - m_IsClient = true; - m_IsServer = true; } // Create Octrees @@ -124,7 +124,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -134,12 +134,11 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); - m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); // Populate Octree with collidables ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -149,9 +148,6 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger); - // Octree for frustum culling must be updated after collisions, otherwise players frustum may be moved after tree is filled, and wrong things are culled. - ++updateOrderLevel; - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame, m_OctreeFrustrumCulling); ++updateOrderLevel; @@ -174,6 +170,7 @@ Game::~Game() delete m_NetworkServer; } delete m_World; + delete m_FrameStack; delete m_InputProxy; delete m_InputManager; delete m_RenderFrame; @@ -192,20 +189,16 @@ void Game::Tick() // Handle input in a weird looking but responsive way m_EventBroker->Process(); m_EventBroker->Swap(); - PerformanceTimer::StartTimer("InputManager"); m_InputManager->Update(dt); m_EventBroker->Swap(); - PerformanceTimer::StartTimerAndStopPrevious("InputProxy"); m_InputProxy->Update(dt); m_EventBroker->Swap(); m_InputProxy->Process(); m_EventBroker->Swap(); - PerformanceTimer::StartTimerAndStopPrevious("SoundManager"); m_SoundManager->Update(dt); // Update network - PerformanceTimer::StartTimerAndStopPrevious("Network"); m_EventBroker->Process(); if (m_NetworkClient != nullptr) { m_NetworkClient->Update(); @@ -216,14 +209,10 @@ void Game::Tick() //m_SoundManager->Update(dt); // Iterate through systems and update world! - PerformanceTimer::StartTimerAndStopPrevious("SystemPipeline"); m_EventBroker->Process(); m_SystemPipeline->Update(dt); - PerformanceTimer::StartTimerAndStopPrevious("RendererUpdate"); m_Renderer->Update(dt); - PerformanceTimer::StartTimerAndStopPrevious("RendererDraw"); m_Renderer->Draw(*m_RenderFrame); - PerformanceTimer::StopTimer("RendererDraw"); m_RenderFrame->Clear(); m_EventBroker->Swap(); m_EventBroker->Clear(); diff --git a/src/Game/Network/MultiplayerSnapshotFilter.cpp b/src/Game/Network/MultiplayerSnapshotFilter.cpp index 295cdd7a..69b7f282 100644 --- a/src/Game/Network/MultiplayerSnapshotFilter.cpp +++ b/src/Game/Network/MultiplayerSnapshotFilter.cpp @@ -13,7 +13,6 @@ bool MultiplayerSnapshotFilter::FilterComponent(EntityWrapper entity, SharedComp component.Info.Name == "Transform" || component.Info.Name == "Physics" || component.Info.Name == "AssaultWeapon" - || component.Info.Name == "DefenderWeapon" || component.Info.Name == "Animation" || component.Info.Name == "AnimationOffset" || entity.Name() == "PlayerName" diff --git a/src/Game/Systems/AmmoPickupSystem.cpp b/src/Game/Systems/AmmoPickupSystem.cpp index 5927c495..f6778fe4 100644 --- a/src/Game/Systems/AmmoPickupSystem.cpp +++ b/src/Game/Systems/AmmoPickupSystem.cpp @@ -3,43 +3,36 @@ AmmoPickupSystem::AmmoPickupSystem(SystemParams params) : System(params) { - if (IsServer) { - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &AmmoPickupSystem::OnTriggerTouch); - } - if (IsClient) { - EVENT_SUBSCRIBE_MEMBER(m_EAmmoPickup, &AmmoPickupSystem::OnAmmoPickup); - } + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &AmmoPickupSystem::OnTriggerTouch); } void AmmoPickupSystem::Update(double dt) { - if (IsServer) { - for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) { - auto& ammoPickupPosition = *it; - //set the double timer value (value 3) - ammoPickupPosition.DecreaseThisRespawnTimer -= dt; - if (ammoPickupPosition.DecreaseThisRespawnTimer < 0.0) { - //spawn and delete the vector item - auto entityFile = ResourceManager::Load("Schema/Entities/AmmoPickup.xml"); - EntityFileParser parser(entityFile); - EntityID ammoPickupID = parser.MergeEntities(m_World); + for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) + { + auto& ammoPickupPosition = *it; + //set the double timer value (value 3) + ammoPickupPosition.DecreaseThisRespawnTimer -= dt; + if (ammoPickupPosition.DecreaseThisRespawnTimer < 0.0) { + //spawn and delete the vector item + auto entityFile = ResourceManager::Load("Schema/Entities/AmmoPickup.xml"); + EntityFileParser parser(entityFile); + EntityID ammoPickupID = parser.MergeEntities(m_World); - //let the world know a pickup has spawned (graphics effects, etc) - Events::PickupSpawned ePickupSpawned; - ePickupSpawned.Pickup = EntityWrapper(m_World, ammoPickupID); - m_EventBroker->Publish(ePickupSpawned); + //let the world know a pickup has spawned (graphics effects, etc) + Events::PickupSpawned ePickupSpawned; + ePickupSpawned.Pickup = EntityWrapper(m_World, ammoPickupID); + m_EventBroker->Publish(ePickupSpawned); - //set values from the old entity to the new entity - auto& newAmmoPickupEntity = EntityWrapper(m_World, ammoPickupID); - newAmmoPickupEntity["Transform"]["Position"] = ammoPickupPosition.Pos; - newAmmoPickupEntity["AmmoPickup"]["AmmoGain"] = ammoPickupPosition.AmmoGain; - newAmmoPickupEntity["AmmoPickup"]["RespawnTimer"] = ammoPickupPosition.RespawnTimer; - m_World->SetParent(newAmmoPickupEntity.ID, ammoPickupPosition.parentID); + //set values from the old entity to the new entity + auto& newAmmoPickupEntity = EntityWrapper(m_World, ammoPickupID); + newAmmoPickupEntity["Transform"]["Position"] = ammoPickupPosition.Pos; + newAmmoPickupEntity["AmmoPickup"]["AmmoGain"] = ammoPickupPosition.AmmoGain; + newAmmoPickupEntity["AmmoPickup"]["RespawnTimer"] = ammoPickupPosition.RespawnTimer; - //erase the current element (AmmoPickupPosition) - m_ETriggerTouchVector.erase(it); - break; - } + //erase the current element (AmmoPickupPosition) + m_ETriggerTouchVector.erase(it); + break; } } } @@ -47,11 +40,7 @@ void AmmoPickupSystem::Update(double dt) bool AmmoPickupSystem::OnTriggerTouch(Events::TriggerTouch& e) { - /*if (e.Entity != LocalPlayer) { - return false; - }*/ - - if (!e.Entity.Valid()) { + if (e.Entity != LocalPlayer) { return false; } //TODO: add other weapontypes @@ -76,34 +65,14 @@ bool AmmoPickupSystem::OnTriggerTouch(Events::TriggerTouch& e) ePlayerAmmoPickup.Player = e.Entity; m_EventBroker->Publish(ePlayerAmmoPickup); //immediately give the player the ammo - //currentAmmo = std::min(currentAmmo + ammoGiven, maxWeaponAmmo); + currentAmmo = std::min(currentAmmo + ammoGiven, maxWeaponAmmo); //copy position, ammogain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) //we need to copy all values since each value can be different for each ammoPickup - m_ETriggerTouchVector.push_back({ e.Trigger["Transform"]["Position"], e.Trigger["AmmoPickup"]["AmmoGain"], - e.Trigger["AmmoPickup"]["RespawnTimer"], e.Trigger["AmmoPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); + m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["AmmoPickup"]["AmmoGain"], + e.Trigger["AmmoPickup"]["RespawnTimer"],e.Trigger["AmmoPickup"]["RespawnTimer"] }); //delete the ammopickup m_World->DeleteEntity(e.Trigger.ID); return true; } - -bool AmmoPickupSystem::OnAmmoPickup(Events::AmmoPickup & e) -{ - if (!e.Player.Valid()) { - return false; - } - //TODO: add other weapontypes - if (!e.Player.HasComponent("AssaultWeapon")) { - return false; - } - int maxWeaponAmmo = (int)e.Player["AssaultWeapon"]["MaxAmmo"]; - int& currentAmmo = (int)e.Player["AssaultWeapon"]["Ammo"]; - //cant pick up ammopacks if you are already at MaxAmmo - if (currentAmmo >= maxWeaponAmmo) { - return false; - } - - currentAmmo = std::min(currentAmmo + e.AmmoGain, maxWeaponAmmo); - return false; -} diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index f748ff09..5fdd74cd 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -1,39 +1,32 @@ #include "Systems/CapturePointSystem.h" #include -CapturePointSystem::CapturePointSystem(SystemParams params) +CapturePointSystem::CapturePointSystem(SystemParams params) : System(params) , PureSystem("CapturePoint") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - if (IsServer) { + if (IsClient) { EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); } - } //here all capturepoints will update their component //NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) { - if (!IsServer) { + if (!IsClient) { return; } + if (m_WinnerWasFound) { return; } const int capturePointNumber = cCapturePoint["CapturePointNumber"]; const bool hasTeamComponent = capturePointEntity.HasComponent("Team"); - if (m_NumberOfCapturePoints != 0) { - if (!m_CapturePointNumberToEntityMap[0].HasComponent("CapturePoint")) { - //if map has changed, the capturepoints has changed, now have to redo them - m_NumberOfCapturePoints = 0; - m_CapturePointNumberToEntityMap.clear(); - } - } //if point doesnt have a teamComponent yet, add one. since: //what if capture point has no team -> we cant get/use the team enum from it... if (!hasTeamComponent) { @@ -78,7 +71,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp std::map nextPossibleCapturePoint; nextPossibleCapturePoint["Red"] = -1; nextPossibleCapturePoint["Blue"] = -1; - for (int i = 0; i < m_NumberOfCapturePoints; i++) { + for (int i = 0; i < m_NumberOfCapturePoints; i++) + { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } @@ -90,7 +84,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp nextPossibleCapturePoint["Blue"] = i + 1; } } - for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) { + for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) + { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } @@ -102,17 +97,11 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp nextPossibleCapturePoint["Blue"] = i - 1; } } - if (m_RecentlyCapturedNeedNextCapturePointNow) { - m_CapturedEvent.NextCapturePoint = m_CapturedEvent.TeamNumberThatCapturedCapturePoint == blueTeam ? - m_CapturePointNumberToEntityMap[nextPossibleCapturePoint["Blue"]] : - m_CapturePointNumberToEntityMap[nextPossibleCapturePoint["Red"]]; - m_EventBroker->Publish(m_CapturedEvent); - m_RecentlyCapturedNeedNextCapturePointNow = false; - } //reset timers and reset the bool that triggers this if (m_ResetTimers) { - for (int i = 0; i < m_NumberOfCapturePoints; i++) { + for (int i = 0; i < m_NumberOfCapturePoints; i++) + { ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { @@ -127,7 +116,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp } //check how many players are standing inside and are healthy - for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) { + for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) + { auto triggerTouched = m_ETriggerTouchVector[i - 1]; if (std::get<1>(triggerTouched) == capturePointEntity) { //some player has touched this - lets figure out: what team, health @@ -186,8 +176,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } //if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0 - if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < captureTimeToTakeOver) || - (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > -captureTimeToTakeOver)) { + if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < 0.0) || + (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) { cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } //check if captureTimer > captureTimeToTakeOver and if so change owner and publish the eCaptured event @@ -195,23 +185,27 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp teamComponent["Team"] = currentTeam; cCapturePoint["CaptureTimer"] = glm::sign((double)cCapturePoint["CaptureTimer"])*captureTimeToTakeOver; //publish Captured event - m_RecentlyCapturedNeedNextCapturePointNow = true; - m_CapturedEvent.CapturePointTakenID = cCapturePoint.EntityID; - m_CapturedEvent.TeamNumberThatCapturedCapturePoint = currentTeam; + Events::Captured e; + e.CapturePointID = cCapturePoint.EntityID; + e.TeamNumberThatCapturedCapturePoint = currentTeam; + m_EventBroker->Publish(e); //NextPossibleCapturePoint will be calculated in the next update... } } //check for possible winCondition = check if the homebase is owned by the other team bool checkForWinner = false; - if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) { + if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) + { checkForWinner = true; } - if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) { + if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) + { checkForWinner = true; } - if (checkForWinner && !m_WinnerWasFound) { + if (checkForWinner && !m_WinnerWasFound) + { //publish Win event Events::Win e; e.TeamThatWon = ownedBy; @@ -230,7 +224,8 @@ bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e) bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e) { - for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) { + for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) + { auto triggerTouched = m_ETriggerTouchVector[i]; if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) { m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i); diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index ca26052d..235eced0 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -12,41 +12,51 @@ DamageIndicatorSystem::DamageIndicatorSystem(SystemParams params) auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); } -void DamageIndicatorSystem::Update(double dt) { - if (!IsServer && LocalPlayer.Valid()) { - for (auto& iter = updateDamageIndicatorVector.begin(); iter != updateDamageIndicatorVector.end(); iter++) { - if (!iter->spriteEntity.Valid()) { - updateDamageIndicatorVector.erase(iter); - break; - } - auto angleBetweenVectors = CalculateAngle(LocalPlayer, iter->enemyPosition); - //simply set the rotation z-wise to the angleBetweenVectors - iter->spriteEntity["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors); - } - } -} - bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) { if (m_CurrentCamera == EntityID_Invalid) { return false; } + //if (e.Victim != LocalPlayer) { + // return false; + //} if (e.Victim.Valid() && e.Victim != LocalPlayer && !e.Victim.IsChildOf(LocalPlayer)) { return false; } if (!e.Inflictor.Valid() || !e.Victim.Valid()) { - return false; + return false; } - glm::vec3 inflictorPos = e.Inflictor["Transform"]["Position"]; - //if testing -#ifdef INDICATOR_TEST - inflictorPos = DamageIndicatorTest(e.Victim); -#endif + //grab players direction + auto playerOrientation = glm::quat((glm::vec3)e.Victim["Transform"]["Orientation"]); - float angleBetweenVectors = CalculateAngle(e.Victim, inflictorPos); + //get the position vectors, but ignore the y-height + auto enemyPosition = (glm::vec3)e.Inflictor["Transform"]["Position"]; + auto playerPosition = (glm::vec3)e.Victim["Transform"]["Position"]; + enemyPosition.y = 0.0f; + playerPosition.y = 0.0f; + + //calculate the enemy to player vector + auto enemyPlayerVector = glm::normalize(playerPosition - enemyPosition); + + //get angle from players current rotation, this angle is how much you rotate around the y-axis + auto playerAngle = glm::angle(playerOrientation); + auto playerRotationVector = glm::normalize(glm::rotateY(glm::vec3(0, 0, 1), playerAngle)); + + //dot product of players direction-vector and enemys-to-playervector will give the cos of the angle between the vectors + auto playerRotationDot = glm::dot(playerRotationVector, enemyPlayerVector); + //to get the angle between the vectors just do cos-inverse + auto angleBetweenVectors = glm::acos(playerRotationDot); + + //rotate the direction-vector 90 degrees to get the players side-vector + auto playerSideVector = glm::normalize(glm::rotateY(glm::vec3(0, 0, 1), playerAngle + 1.57f)); + //dot of sidevector positive = enemy is on the right side, dot sidevector negative = left side + auto playerSideVectorDot = glm::dot(playerSideVector, enemyPlayerVector); + if (playerSideVectorDot < 0) { + angleBetweenVectors = -angleBetweenVectors; + } //load & set the "2d" sprite auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); @@ -57,10 +67,6 @@ bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) //simply set the rotation z-wise to the angleBetweenVectors spriteWrapper["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors); - if (!IsServer) { - updateDamageIndicatorVector.emplace_back(spriteWrapper, inflictorPos); - } - return true; } @@ -68,82 +74,3 @@ bool DamageIndicatorSystem::OnSetCamera(const Events::SetCamera& e) { m_CurrentCamera = e.CameraEntity.ID; return true; } - -float DamageIndicatorSystem::CalculateAngle(EntityWrapper player, glm::vec3 enemyPos) { - //grab players direction - auto playerOrientation = glm::quat((glm::vec3)player["Transform"]["Orientation"]); - - //get the position vectors, but ignore the y-height - auto enemyPosition = enemyPos; - auto playerPosition = (glm::vec3)player["Transform"]["Position"]; - enemyPosition.y = 0.0f; - playerPosition.y = 0.0f; - - //calculate the enemy to player vector - auto enemyPlayerVector = glm::normalize(playerPosition - enemyPosition); - - //get the rotationvector relative to the z-axis - auto rotationVectorVec3 = glm::vec3(glm::toMat4(Transform::AbsoluteOrientation(player))*glm::vec4(0, 0, 1, 0)); - //rotate the direction-vector 90 degrees to get the players side-vector - auto playerSideVector = glm::vec3(glm::rotateY(rotationVectorVec3, 1.57f)); - - //dot product of players direction-vector and enemys-to-playervector will give the cos of the angle between the vectors - auto playerRotationDot = glm::dot(rotationVectorVec3, enemyPlayerVector); - //to get the angle between the vectors just do cos-inverse - auto angleBetweenVectors = glm::acos(playerRotationDot); - - //dot of sidevector positive = enemy is on the right side, dot sidevector negative = left side - auto playerSideVectorDot = glm::dot(playerSideVector, enemyPlayerVector); - if (playerSideVectorDot < 0) { - angleBetweenVectors = -angleBetweenVectors; - } - - return angleBetweenVectors; -} -#ifdef INDICATOR_TEST -glm::vec3 DamageIndicatorSystem::DamageIndicatorTest(EntityWrapper player) { - auto currentPos = (glm::vec3)player["Transform"]["Position"]; - - auto testVar = 1; - auto testVar2 = 1; - if (m_TestVar % 4 == 0) { - testVar = -1; - testVar2 = 1; - } - if (m_TestVar % 4 == 1) { - testVar = 1; - testVar2 = 1; - } - if (m_TestVar % 4 == 2) { - testVar *= -1; - testVar2 = -1; - } - if (m_TestVar % 4 == 3) { - testVar = 1; - testVar2 = -1; - } - m_TestVar++; - - auto inflictorPos = glm::vec3(currentPos.x + testVar*6.0f, currentPos.y, currentPos.z + testVar2*6.0f); - - //load the explosioneffect XML - auto deathEffect = ResourceManager::Load("Schema/Entities/PlayerDeathExplosionWithCamera.xml"); - EntityFileParser parser(deathEffect); - EntityID deathEffectID = parser.MergeEntities(m_World); - EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); - - //components that we need from player - auto playerModel = player.FirstChildByName("PlayerModel"); - auto playerEntityModel = playerModel["Model"]; - auto playerEntityAnimation = playerModel["Animation"]; - - //copy the data from player to explosioneffectmodel - playerEntityModel.Copy(deathEffectEW["Model"]); - playerEntityAnimation.Copy(deathEffectEW["Animation"]); - - //copy the models position,orientation - deathEffectEW["Transform"]["Position"] = inflictorPos; - deathEffectEW["Transform"]["Orientation"] = (glm::vec3)player["Transform"]["Orientation"]; - return inflictorPos; -} -#endif \ No newline at end of file diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index b4ace6b9..6e1e276f 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -24,7 +24,7 @@ void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cHea bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) { - if (!IsServer && m_NetworkEnabled || !e.Victim.Valid()) { + if (!IsServer && m_NetworkEnabled) { return false; } diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp index 94fee4c6..159f716b 100644 --- a/src/Game/Systems/PickupSpawnSystem.cpp +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -3,40 +3,36 @@ PickupSpawnSystem::PickupSpawnSystem(SystemParams params) : System(params) { - if (IsServer) { - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &PickupSpawnSystem::OnTriggerTouch); - } + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &PickupSpawnSystem::OnTriggerTouch); } void PickupSpawnSystem::Update(double dt) { - if (IsServer) { - for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) { - auto& healthPickupPosition = *it; - //set the double timer value (value 3) - healthPickupPosition.DecreaseThisRespawnTimer -= dt; - if (healthPickupPosition.DecreaseThisRespawnTimer < 0) { - //spawn and delete the vector item - auto entityFile = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); - EntityFileParser parser(entityFile); - EntityID healthPickupID = parser.MergeEntities(m_World); + for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) + { + auto& healthPickupPosition = *it; + //set the double timer value (value 3) + healthPickupPosition.DecreaseThisRespawnTimer -= dt; + if (healthPickupPosition.DecreaseThisRespawnTimer < 0) { + //spawn and delete the vector item + auto entityFile = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); + EntityFileParser parser(entityFile); + EntityID healthPickupID = parser.MergeEntities(m_World); - //let the world know a pickup has spawned (graphics effects, etc) - Events::PickupSpawned ePickupSpawned; - ePickupSpawned.Pickup = EntityWrapper(m_World, healthPickupID); - m_EventBroker->Publish(ePickupSpawned); + //let the world know a pickup has spawned (graphics effects, etc) + Events::PickupSpawned ePickupSpawned; + ePickupSpawned.Pickup = EntityWrapper(m_World, healthPickupID); + m_EventBroker->Publish(ePickupSpawned); - //set values from the old entity to the new entity - auto& newHealthPickupEntity = EntityWrapper(m_World, healthPickupID); - newHealthPickupEntity["Transform"]["Position"] = healthPickupPosition.Pos; - newHealthPickupEntity["HealthPickup"]["HealthGain"] = healthPickupPosition.HealthGain; - newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = healthPickupPosition.RespawnTimer; - m_World->SetParent(newHealthPickupEntity.ID, healthPickupPosition.parentID); + //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; - } + //erase the current element (healthPickupPosition) + m_ETriggerTouchVector.erase(it); + break; } } } @@ -61,8 +57,8 @@ bool PickupSpawnSystem::OnTriggerTouch(Events::TriggerTouch& e) //copy position, healthgain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) //we need to copy all values since each value can be different for each healthPickup - m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"], e.Trigger["HealthPickup"]["HealthGain"], - e.Trigger["HealthPickup"]["RespawnTimer"], e.Trigger["HealthPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); + 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); diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index 844d2ed1..40a98278 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -33,8 +33,9 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player) EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); //components that we need from player + auto playerCamera = player.FirstChildByName("Camera"); auto playerModel = player.FirstChildByName("PlayerModel"); - if (!playerModel.Valid()) { + if (!playerCamera.Valid() || !playerModel.Valid()) { return; } if (!playerModel.HasComponent("Model") || !playerModel.HasComponent("Animation")) { @@ -43,7 +44,7 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player) auto playerEntityModel = playerModel["Model"]; auto playerEntityAnimation = playerModel["Animation"]; - //copy the data from player to explosioneffectmodel + //copy the data from player to explisioneffectmodel playerEntityModel.Copy(deathEffectEW["Model"]); playerEntityAnimation.Copy(deathEffectEW["Animation"]); //freeze the animation diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 8bcf092f..ee2f9ca3 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -4,7 +4,6 @@ PlayerMovementSystem::PlayerMovementSystem(SystemParams params) : System(params) { EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned); - EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &PlayerMovementSystem::OnDoubleJump); } PlayerMovementSystem::~PlayerMovementSystem() @@ -17,15 +16,7 @@ PlayerMovementSystem::~PlayerMovementSystem() void PlayerMovementSystem::Update(double dt) { updateMovementControllers(dt); - if (IsServer) { - for (auto& kv : m_PlayerInputControllers) { - updateVelocity(kv.first, dt); - } - } else { - if (LocalPlayer.Valid()) { - updateVelocity(LocalPlayer, dt); - } - } + updateVelocity(dt); } void PlayerMovementSystem::updateMovementControllers(double dt) @@ -37,6 +28,7 @@ void PlayerMovementSystem::updateMovementControllers(double dt) if (!player.Valid()) { continue; } + // Aim pitch EntityWrapper cameraEntity = player.FirstChildByName("Camera"); if (cameraEntity.Valid()) { @@ -48,7 +40,7 @@ void PlayerMovementSystem::updateMovementControllers(double dt) EntityWrapper playerModel = player.FirstChildByName("PlayerModel"); if (playerModel.Valid()) { ComponentWrapper cAnimationOffset = playerModel["AnimationOffset"]; - float pitch = cameraOrientation.x + 0.2f; + float pitch = cameraOrientation.x + 0.2; double time = (pitch + glm::half_pi()) / glm::pi(); cAnimationOffset["Time"] = time; } @@ -79,7 +71,7 @@ void PlayerMovementSystem::updateMovementControllers(double dt) ComponentWrapper cPhysics = player["Physics"]; //Assault Dash Check if (player.HasComponent("DashAbility")) { - controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f, player["DashAbility"]["CoolDownMaxTimer"], player["DashAbility"]["CoolDownTimer"]); + controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f, player["DashAbility"]["CoolDownMaxTimer"]); } wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); //this makes sure you can only dash in the 4 directions: forw,backw,left,right @@ -136,29 +128,25 @@ void PlayerMovementSystem::updateMovementControllers(double dt) ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); } - if (isOnGround) { - controller->SetDoubleJumping(false); - } - //If player presses Jump and is not crouching. - if (controller->Jumping() && !controller->Crouching()) { + //you cant jump and dash at the same time - since there is no friction in the air and we would thus dash much further in the air + if (!controller->PlayerIsDashing() && controller->Jumping() && !controller->Crouching() && (isOnGround || !controller->DoubleJumping())) { + (bool)cPhysics["IsOnGround"] = false; if (isOnGround) { - (bool)cPhysics["IsOnGround"] = false; - velocity.y = player["Player"]["JumpSpeed"]; - } else if (player.HasComponent("DoubleJump") && !controller->DoubleJumping()) { - //Enter here if player can double jump and is doing so. - (bool)cPhysics["IsOnGround"] = false; - velocity.y = player["DoubleJump"]["DoubleJumpSpeed"]; - // If IsServer and network is off this will not work + controller->SetDoubleJumping(false); + } else { if (IsClient) { //put a hexagon at the players feet - spawnHexagon(player); + auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); + EntityFileParser parser(hexagonEffect); + EntityID hexagonEffectID = parser.MergeEntities(m_World); + EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID); + hexagonEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; controller->SetDoubleJumping(true); - // Publish event for client to listen to Events::DoubleJump e; - e.entityID = player.ID; m_EventBroker->Publish(e); } } + velocity.y = 4.f; } if (player.HasComponent("AABB")) { @@ -253,11 +241,15 @@ void PlayerMovementSystem::updateMovementControllers(double dt) } -void PlayerMovementSystem::updateVelocity(EntityWrapper player, double dt) +void PlayerMovementSystem::updateVelocity(double dt) { // Only apply velocity to local player - ComponentWrapper& cTransform = player["Transform"]; - ComponentWrapper& cPhysics = player["Physics"]; + if (!LocalPlayer.Valid()) { + return; + } + + ComponentWrapper& cTransform = LocalPlayer["Transform"]; + ComponentWrapper& cPhysics = LocalPlayer["Physics"]; glm::vec3& velocity = cPhysics["Velocity"]; bool isOnGround = (bool)cPhysics["IsOnGround"]; @@ -319,27 +311,3 @@ bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e) } return true; } - -bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e) -{ - // If entity does not exist, exit - if (!EntityWrapper(m_World, e.entityID).Valid()) { - return false; - } - // If entity IsLocalPlayer, exit - if (e.entityID == m_LocalPlayer.ID) { - return false; - } - spawnHexagon(EntityWrapper(m_World, e.entityID)); - return true; -} - -void PlayerMovementSystem::spawnHexagon(EntityWrapper target) -{ - //put a hexagon at the entitys... feet? - auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); - EntityFileParser parser(hexagonEffect); - EntityID hexagonEffectID = parser.MergeEntities(m_World); - EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID); - hexagonEW["Transform"]["Position"] = (glm::vec3)target["Transform"]["Position"]; -} \ No newline at end of file diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index e03a1778..5f53a1fc 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -1,40 +1,29 @@ #include "Systems/PlayerSpawnSystem.h" -PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) +//This should be set by the config anyway. +float PlayerSpawnSystem::m_RespawnTime = 15.0f; + +PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) : System(params) - , m_DbgConfigForceRespawn(false) + , m_Timer(0.f) { EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerSpawnSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerSpawnerd, &PlayerSpawnSystem::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerSpawnSystem::OnPlayerDeath); - ConfigFile* config = ResourceManager::Load("Config.ini"); - m_NetworkEnabled = config->Get("Networking.StartNetwork", false); - m_ForcedRespawnTime = config->Get("Debug.RespawnTime", -1.0f); - m_DbgConfigForceRespawn = m_ForcedRespawnTime > 0; + m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); } void PlayerSpawnSystem::Update(double dt) { - // If there are no CapturePointGameMode components we will just spawn immediately. - // Should be able to support older maps with this. - // TODO: In the future we might want to return instead, to avoid spawning in the menu for instance. - auto pool = m_World->GetComponents("CapturePointGameMode"); - if (pool != nullptr && pool->size() > 0) - { - // Take the first CapturePointGameMode component found. - ComponentWrapper& modeComponent = *pool->begin(); - // Increase timer. - double& timer = (double&)modeComponent["RespawnTime"]; - timer += dt; - double maxRespawnTime = m_DbgConfigForceRespawn ? m_ForcedRespawnTime : (double)modeComponent["MaxRespawnTime"]; - if (timer < maxRespawnTime) { - return; - } - // If respawn time has passed, we spawn all players that have requested to be spawned. - timer = 0; + //Increase timer. + m_Timer += dt; + if (m_Timer < m_RespawnTime) { + return; } + //If respawn time has passed, we spawn all players that have requested to be spawned. + m_Timer = 0.f; - // If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. + //If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. if (m_SpawnRequests.size() == 0) { return; } @@ -60,7 +49,7 @@ void PlayerSpawnSystem::Update(double dt) } // Spawn the player! - EntityWrapper player = SpawnerSystem::Spawn(spawner, EntityWrapper::Invalid, "Player"); + EntityWrapper player = SpawnerSystem::Spawn(spawner); // Set the player team affiliation player["Team"]["Team"] = req.Team; diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index be9c8aaf..7101311d 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -14,7 +14,6 @@ SoundSystem::SoundSystem(SystemParams params) EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerDeath, &SoundSystem::OnPlayerDeath); } } @@ -91,10 +90,7 @@ bool SoundSystem::drumTimer(double dt) bool SoundSystem::OnCaptured(const Events::Captured & e) { - if (!LocalPlayer.Valid()) { - return false; - } - int homeTeam = (int)m_World->GetComponent(e.CapturePointTakenID, "Team")["Team"]; + int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; int team = (int)m_World->GetComponent(LocalPlayer.ID, "Team")["Team"]; Events::PlaySoundOnEntity ev; if (team == homeTeam) { @@ -112,12 +108,7 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) // Testing purposes atm... bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) { - if (!IsClient) { // Only play for clients - return false; - } - if (LocalPlayer.ID = e.Victim.ID) { // You're local player was the one who took dmg - return false; - } + // Should check for only local players here... std::uniform_int_distribution dist(1, 12); int rand = dist(generator); std::vector paths; @@ -137,16 +128,8 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) { - if (e.Player.ID != LocalPlayer.ID) { - return false; - } - if (!IsClient) { - return false; - } - // The local player is dead. The local player might be invalid? - // Play the sound from the listener. - // TODO: We might want to hear other players die. - Events::PlayBackgroundMusic ev; + Events::PlaySoundOnEntity ev; + ev.EmitterID = LocalPlayer.ID; ev.FilePath = "Audio/die/die2.wav"; m_EventBroker->Publish(ev); return false; diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index 6500460f..b3c556f1 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -1,13 +1,12 @@ #include "Systems/SpawnerSystem.h" -#include "Collision/Collision.h" -SpawnerSystem::SpawnerSystem(SystemParams params) +SpawnerSystem::SpawnerSystem(SystemParams params) : System(params) { EVENT_SUBSCRIBE_MEMBER(m_OnSpawnerSpawn, &SpawnerSystem::OnSpawnerSpawn); } -EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent /*= EntityWrapper::Invalid*/, const std::string& dontCollideComponent) +EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent /*= EntityWrapper::Invalid*/) { // Spawn the entity in the parent's world if it exists, otherwise in the spawner's world World* world = parent.World; @@ -15,41 +14,17 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / world = spawner.World; } - // Load the entity file and parse it - const std::string& entityFilePath = spawner["Spawner"]["EntityFile"]; - auto entityFile = ResourceManager::Load(entityFilePath); - if (entityFile == nullptr) { - return EntityWrapper::Invalid; - } - EntityFileParser parser(entityFile); - EntityWrapper spawnedEntity(world, parser.MergeEntities(world, parent.ID)); - - //If the spawned entity is collideable, then we must not spawn it where it collides with something that - //has a dontCollideComponent attached. - bool spawnOnCollidable = dontCollideComponent.empty() || !spawnedEntity.HasComponent("Collidable"); - if (!spawnOnCollidable) { - boost::optional optBox = Collision::EntityAbsoluteAABB(spawnedEntity); - //If we can't calculate the box for some reason, then just spawn somewhere anyway. - if (!optBox) { - spawnOnCollidable = true; - } - } - // Find any SpawnPoints existing as children of spawner - auto children = spawner.World->GetDirectChildren(spawner.ID); + auto children = spawner.World->GetChildren(spawner.ID); std::vector spawnPoints; for (auto kv = children.first; kv != children.second; ++kv) { const EntityID& child = kv->second; if (spawner.World->HasComponent(child, "SpawnPoint")) { - EntityWrapper spawnPoint = EntityWrapper(spawner.World, child); - if (spawnOnCollidable || !spawnedEntityIsColliding(spawnedEntity, spawnPoint, dontCollideComponent)) { - spawnPoints.push_back(spawnPoint); - } + spawnPoints.push_back(EntityWrapper(spawner.World, child)); } } // Choose a random SpawnPoint - // If there are no children, or if they are all blocked, then the entity will be spawned at the spawner itself. EntityWrapper spawnPoint = spawner; if (!spawnPoints.empty()) { if (spawnPoints.size() > 1) { @@ -64,61 +39,25 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / } } + // Load the entity file and parse it + const std::string& entityFilePath = spawner["Spawner"]["EntityFile"]; + auto entityFile = ResourceManager::Load(entityFilePath); + if (entityFile == nullptr) { + return EntityWrapper::Invalid; + } + EntityFileParser parser(entityFile); + EntityWrapper spawnedEntity(world, parser.MergeEntities(world, parent.ID)); + if (spawnPoint != parent) { - transformEntityToSpawnPoint(spawnedEntity, spawnPoint); + // Set its position and orientation to that of the SpawnPoint + spawnedEntity["Transform"]["Position"] = Transform::AbsolutePosition(spawnPoint.World, spawnPoint.ID); + // TODO: Quaternions, bitch + spawnedEntity["Transform"]["Orientation"] = glm::eulerAngles(Transform::AbsoluteOrientation(spawnPoint)); } return spawnedEntity; } -void SpawnerSystem::transformEntityToSpawnPoint(EntityWrapper spawnedEntity, EntityWrapper spawnPoint) -{ - // Set its position and orientation to that of the SpawnPoint - spawnedEntity["Transform"]["Position"] = Transform::AbsolutePosition(spawnPoint.World, spawnPoint.ID); - // TODO: Quaternions, bitch - spawnedEntity["Transform"]["Orientation"] = glm::eulerAngles(Transform::AbsoluteOrientation(spawnPoint)); -} - -bool SpawnerSystem::spawnedEntityIsColliding(EntityWrapper spawnedEntity, EntityWrapper spawnPoint, const std::string& dontCollideComponent) -{ - transformEntityToSpawnPoint(spawnedEntity, spawnPoint); - //Check if the spawned entity collides with anything, and if so, continue to the next spawnpoint. - EntityAABB spawnedBox = *Collision::EntityAbsoluteAABB(spawnedEntity); - const ComponentPool* otherSpawnedEntities = spawnPoint.World->GetComponents(dontCollideComponent); - for (const auto& obj : *otherSpawnedEntities) { - if (spawnedEntity.ID == obj.EntityID) { - continue; - } - EntityWrapper otherEntity = EntityWrapper(spawnPoint.World, obj.EntityID); - if (!otherEntity.HasComponent("Collidable")) { - continue; - } - auto otherBox = Collision::EntityAbsoluteAABB(otherEntity); - if (!otherBox) { - continue; - } - if (Collision::AABBVsAABB(spawnedBox, *otherBox)) { - if (!spawnedBox.Entity.HasComponent("Model")) { - return true; - } - RawModel* model = nullptr; - try { - model = ResourceManager::Load(otherEntity["Model"]["Resource"]); - } catch (const std::exception&) { - } - - if (model != nullptr && Collision::AABBvsTriangles( - spawnedBox, - model->Vertices(), - model->m_Indices, - Transform::ModelMatrix(otherEntity))) { - return true; - } - } - } - return false; -} - bool SpawnerSystem::OnSpawnerSpawn(Events::SpawnerSpawn& e) { EntityWrapper spawnedEntity = Spawn(e.Spawner, e.Parent); diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp similarity index 87% rename from src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ rename to src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp index 547ed36a..7ea6f4f1 100644 --- a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp @@ -1,5 +1,13 @@ #include "Systems/Weapon/AssaultWeaponBehaviour.h" +AssaultWeaponBehaviour::AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) + : WeaponBehaviour(systemParams, renderer, collisionOctree, player) +{ + m_FirstPersonModel = m_Player.FirstChildByName("Hands"); + m_ThirdPersonModel = m_Player.FirstChildByName("PlayerModel"); + EVENT_SUBSCRIBE_MEMBER(m_EAnimationComplete, &AssaultWeaponBehaviour::OnAnimationComplete); +} + void AssaultWeaponBehaviour::Fire() { m_TimeSinceLastFire = 0.0; @@ -28,7 +36,7 @@ void AssaultWeaponBehaviour::Reload() return; } - // Don't reload if we're completely out of ammo + // Don't reload if we're completly out of ammo if (ammo == 0) { playEmptySound(); m_TimeSinceLastFire = -0.0f; // HACK: To make empty sound play with interval @@ -48,14 +56,14 @@ void AssaultWeaponBehaviour::Update(double dt) { if (m_Reloading) { m_ReloadTimer -= dt; - // Re-enable glow on reload impostor half-way through the animation + // Re-enable glow on reload impersonator half-way through the animation if (IsClient) { if (m_ReloadTimer <= (double)m_Player["AssaultWeapon"]["ReloadTime"] / 2.0) { - if (m_FirstPersonReloadImpostor.Valid()) { - m_FirstPersonReloadImpostor["Model"]["GlowMap"] = true; + if (m_FirstPersonReloadImpersonator.Valid()) { + m_FirstPersonReloadImpersonator["Model"]["GlowMap"] = true; } - if (m_ThirdPersonReloadImpostor.Valid()) { - m_ThirdPersonReloadImpostor["Model"]["GlowMap"] = true; + if (m_ThirdPersonReloadImpersonator.Valid()) { + m_ThirdPersonReloadImpersonator["Model"]["GlowMap"] = true; } } } @@ -88,6 +96,21 @@ void AssaultWeaponBehaviour::Update(double dt) } } +bool AssaultWeaponBehaviour::OnAnimationComplete(Events::AnimationComplete& e) +{ + if (e.Entity != m_FirstPersonModel) { + return false; + } + + //if (e.Name == "ShootRifle") { + // if (!m_Firing) { + // playIdleAnimation(); + // } + //} + + return true; +} + bool AssaultWeaponBehaviour::hasAmmo() { ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; @@ -154,6 +177,7 @@ void AssaultWeaponBehaviour::spawnTracer() float AssaultWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) { + // TODO: Cast a ray and size tracer appropriately float distance; glm::vec3 pos; auto entity = Collision::EntityFirstHitByRay(Ray(origin, direction), m_CollisionOctree, distance, pos); @@ -191,12 +215,6 @@ void AssaultWeaponBehaviour::playEmptySound() void AssaultWeaponBehaviour::viewPunch() { - // Since we send absolute client orientations to server, running this server side would - // cause aim desync. - if (!IsClient) { - return; - } - EntityWrapper playerCamera = m_Player.FirstChildByName("Camera"); if (!playerCamera.Valid()) { return; @@ -305,8 +323,8 @@ void AssaultWeaponBehaviour::playReloadAnimation() EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); EntityWrapper reloadSpawner = m_Player.FirstChildByName("FirstPersonReloadSpawner"); if (IsClient) { - m_FirstPersonReloadImpostor = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); - firstPersonWeaponModel["Model"].Copy(m_FirstPersonReloadImpostor["Model"]); + m_FirstPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + firstPersonWeaponModel["Model"].Copy(m_FirstPersonReloadImpersonator["Model"]); } firstPersonWeaponModel["Model"]["Visible"] = false; } @@ -314,8 +332,8 @@ void AssaultWeaponBehaviour::playReloadAnimation() EntityWrapper thirdPersonWeaponModel = m_Player.FirstChildByName("ThirdPersonWeaponModel"); EntityWrapper reloadSpawner = m_Player.FirstChildByName("ThirdPersonReloadSpawner"); if (IsClient) { - m_ThirdPersonReloadImpostor = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); - thirdPersonWeaponModel["Model"].Copy(m_ThirdPersonReloadImpostor["Model"]); + m_ThirdPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + thirdPersonWeaponModel["Model"].Copy(m_ThirdPersonReloadImpersonator["Model"]); } thirdPersonWeaponModel["Model"]["Visible"] = false; } @@ -353,7 +371,7 @@ bool AssaultWeaponBehaviour::shoot(double damage) return false; } - // Don't let us shoot ourselves in the foot somehow + // Don't let us shoot ourselves in the foot if (victim == LocalPlayer) { return false; } diff --git a/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp b/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp deleted file mode 100644 index 028bd10c..00000000 --- a/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp +++ /dev/null @@ -1,188 +0,0 @@ -#include "Systems/Weapon/DefenderWeaponBehaviour.h" - -void DefenderWeaponBehaviour::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cWeapon, double dt) -{ - (double&)cWeapon["TimeSinceLastFire"] += dt; - WeaponBehaviour::UpdateComponent(entity, cWeapon, dt); -} - -void DefenderWeaponBehaviour::UpdateWeapon(WeaponInfo& wi, double dt) -{ - ComponentWrapper cWeapon = wi.GetComponent(); - - bool isFiring = cWeapon["IsFiring"]; - bool cooldownPassed = (double)cWeapon["TimeSinceLastFire"] >= (60.0 / (double)cWeapon["RPM"]); - bool isNotShielding = wi.Player.ChildrenWithComponent("Shield").size() == 0; - if (isFiring && cooldownPassed && isNotShielding) { - fireShell(wi); - } -} - -void DefenderWeaponBehaviour::OnPrimaryFire(WeaponInfo& wi) -{ - ComponentWrapper cWeapon = wi.GetComponent(); - cWeapon["IsFiring"] = true; - bool cooldownPassed = (double)cWeapon["TimeSinceLastFire"] >= (60.0 / (double)cWeapon["RPM"]); - bool isNotShielding = wi.Player.ChildrenWithComponent("Shield").size() == 0; - if (cooldownPassed && isNotShielding) { - fireShell(wi); - } -} - -void DefenderWeaponBehaviour::OnCeasePrimaryFire(WeaponInfo& wi) -{ - ComponentWrapper cWeapon = wi.GetComponent(); - cWeapon["IsFiring"] = false; -} - -bool DefenderWeaponBehaviour::OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) -{ - if (e.Command == "SpecialAbility" && IsServer) { - EntityWrapper attachment = wi.Player.FirstChildByName("ShieldAttachment"); - if (attachment.Valid()) { - if (e.Value > 0) { - SpawnerSystem::Spawn(attachment, attachment); - } else { - attachment.DeleteChildren(); - } - } - } - - return false; -} - -bool DefenderWeaponBehaviour::OnSetCamera(const Events::SetCamera& e) -{ - m_CurrentCamera = e.CameraEntity; - return true; -} - -void DefenderWeaponBehaviour::fireShell(WeaponInfo& wi) -{ - ComponentWrapper cWeapon = wi.GetComponent(); - - cWeapon["TimeSinceLastFire"] = 0.0; - int numPellets = cWeapon["NumPellets"]; - float spreadAngle = cWeapon["SpreadAngle"]; - std::uniform_real_distribution randomSpreadAngle(-spreadAngle, spreadAngle); - - // Calculate pellet angles - // HACK: Random for now? - // TODO: Make distribution even for each quadrant - std::vector pelletAngles; - for (int i = 0; i < numPellets; i++) { - pelletAngles.push_back(glm::vec2(randomSpreadAngle(m_RandomEngine), randomSpreadAngle(m_RandomEngine))); - LOG_DEBUG("%f %f", pelletAngles[i].x, pelletAngles[i].y); - } - - double pelletDamage = (double)cWeapon["BaseDamage"] / numPellets; - - // Tracers - EntityWrapper weaponModelEntity; - if (wi.Player == LocalPlayer) { - weaponModelEntity = wi.FirstPersonEntity; - } else { - weaponModelEntity = wi.ThirdPersonEntity; - } - if (weaponModelEntity.Valid()) { - EntityWrapper spawner = weaponModelEntity.FirstChildByName("WeaponMuzzle"); - for (auto& angles : pelletAngles) { - glm::vec3 direction = Transform::AbsoluteOrientation(spawner) * glm::quat(glm::vec3(angles, 0.f)) * glm::vec3(0, 0, -1); - float distance = traceRayDistance(Transform::AbsolutePosition(spawner), direction); - EntityWrapper ray = SpawnerSystem::Spawn(spawner); - ((glm::vec3&)ray["Transform"]["Scale"]).z = (distance / 100.f); - glm::vec3& orientation = ray["Transform"]["Orientation"]; - orientation.x += angles.x; - orientation.y += angles.y; - glm::vec3 trajectory = direction * distance; - dealDamage(wi, direction, pelletDamage); - } - } - -} - -void DefenderWeaponBehaviour::dealDamage(WeaponInfo& wi, glm::vec3 direction, double damage) -{ - // Only deal damage client side - if (!IsClient) { - return; - } - - // Only handle shooting for the local player - if (wi.Player != LocalPlayer) { - return; - } - - // Make sure the player isn't shooting from the grave - if (!wi.Player.Valid()) { - return; - } - - glm::vec3 maxRange = direction * 2.f; - EntityWrapper camera = wi.Player.FirstChildByName("Camera"); - glm::vec3 cameraPosition = Transform::AbsolutePosition(camera); - if (!camera.Valid()) { - return; - } - Rectangle screenResolution = m_Renderer->GetViewportSize(); - glm::vec2 centerScreen = glm::vec2(screenResolution.Width / 2, screenResolution.Height / 2); - glm::vec2 screenCoords = cameraFromEntity(m_CurrentCamera).WorldToScreen(cameraPosition + maxRange, m_Renderer->GetViewportSize()); - PickData pickData = m_Renderer->Pick(centerScreen + screenCoords); - EntityWrapper victim(m_World, pickData.Entity); - if (!victim.Valid()) { - return; - } - - // Don't let us shoot ourselves in the foot somehow - if (victim == LocalPlayer) { - return; - } - - // Only care about players being hit - if (!victim.HasComponent("Player")) { - victim = victim.FirstParentWithComponent("Player"); - } - if (!victim.Valid()) { - return; - } - - // Check for friendly fire - if ((ComponentInfo::EnumType)victim["Team"]["Team"] == (ComponentInfo::EnumType)wi.Player["Team"]["Team"]) { - return; - } - - // Deal damage! - Events::PlayerDamage ePlayerDamage; - ePlayerDamage.Inflictor = wi.Player; - ePlayerDamage.Victim = victim; - ePlayerDamage.Damage = damage; - m_EventBroker->Publish(ePlayerDamage); - LOG_DEBUG("Damage: %f", damage); -} - -float DefenderWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) -{ - float distance; - glm::vec3 pos; - auto entity = Collision::EntityFirstHitByRay(Ray(origin, direction), m_CollisionOctree, distance, pos); - if (entity) { - return distance; - } else { - return 100.f; - } -} - -Camera DefenderWeaponBehaviour::cameraFromEntity(EntityWrapper camera) -{ - ComponentWrapper cTransform = camera["Transform"]; - ComponentWrapper cCamera = camera["Camera"]; - Camera cam( - (float)m_Renderer->Resolution().Width / m_Renderer->Resolution().Height, - (double)cCamera["FOV"], - (double)cCamera["NearClip"], - (double)cCamera["FarClip"] - ); - cam.SetPosition(cTransform["Position"]); - cam.SetOrientation(glm::quat((const glm::vec3&)cTransform["Orientation"])); - return cam; -} diff --git a/src/Game/Systems/Weapon/WeaponSystem.cpp_ b/src/Game/Systems/Weapon/WeaponSystem.cpp similarity index 56% rename from src/Game/Systems/Weapon/WeaponSystem.cpp_ rename to src/Game/Systems/Weapon/WeaponSystem.cpp index d33c5098..3a49ae90 100644 --- a/src/Game/Systems/Weapon/WeaponSystem.cpp_ +++ b/src/Game/Systems/Weapon/WeaponSystem.cpp @@ -13,7 +13,7 @@ WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer, Octree weaponAttachments = player.ChildrenWithComponent("WeaponAttachment"); - - // Find the weapon attachments matching the slot selected - EntityWrapper firstPersonAttachment; - EntityWrapper thirdPersonAttachment; - for (auto& attachment : weaponAttachments) { - ComponentWrapper cWeaponAttachment = attachment["WeaponAttachment"]; - if ((ComponentInfo::EnumType)cWeaponAttachment["Slot"] == slot) { - ComponentWrapper::SubscriptProxy person = cWeaponAttachment["Person"]; - if (person == person.Enum("FirstPerson")) { - firstPersonAttachment = attachment; - } else if (person == person.Enum("ThirdPerson")) { - thirdPersonAttachment = attachment; - } - } - } - - if (firstPersonAttachment.Valid() && thirdPersonAttachment.Valid()) { - LOG_WARNING("No weapon attachment found for slot %i of player #%i", slot, player.ID); - return; - } - - // TODO: Delete old weapons - - // Spawn the weapon(s) - EntityWrapper firstPersonWeapon; - EntityWrapper thirdPersonWeapon; - if (firstPersonAttachment.Valid()) { - firstPersonWeapon = SpawnerSystem::Spawn(firstPersonAttachment, firstPersonAttachment); - } - if (thirdPersonAttachment.Valid()) { - firstPersonWeapon = SpawnerSystem::Spawn(thirdPersonAttachment, thirdPersonAttachment); - } - - // Create the correct behaviour - if (firstPersonWeapon.Valid()) { - if (firstPersonWeapon.HasComponent("AssaultWeapon") { - - } - } - // Primary if (slot == 1) { // TODO: if class... - nextBehaviour = std::make_shared(m_SystemParams, m_Renderer, m_CollisionOctree, player); + if (m_ActiveWeapons.count(player) == 0) { + m_ActiveWeapons.insert(std::make_pair(player, std::make_shared(m_SystemParams, m_Renderer, m_CollisionOctree, player))); + } else { + //m_ActiveWeapons.erase(player); + } } // Secondary if (slot == 2) { //m_ActiveWeapons[player] = std::make_shared(); } - - if (nextBehaviour != nullptr) { - // TODO: Destroy previous behaviour and make new - if (m_ActiveWeapons.count(player) == 0) { - m_ActiveWeapons[player] = nextBehaviour; - } - } } bool WeaponSystem::OnPlayerSpawned(Events::PlayerSpawned& e) diff --git a/src/Game/main.cpp b/src/Game/main.cpp index 3c9b6d38..dd2a5a84 100644 --- a/src/Game/main.cpp +++ b/src/Game/main.cpp @@ -9,9 +9,7 @@ int main(int argc, char* argv[]) Game game(argc, argv); while (game.Running()) { - PerformanceTimer::StartTimer("Game-Tick"); game.Tick(); - PerformanceTimer::StopTimer("Game-Tick"); } return 0; diff --git a/src/Tests/CapturePointTest.cpp b/src/Tests/CapturePointTest.cpp index 8a9baf40..2c7bf430 100644 --- a/src/Tests/CapturePointTest.cpp +++ b/src/Tests/CapturePointTest.cpp @@ -94,7 +94,7 @@ CapturePointTest::CapturePointTest(int runTestNumber) m_World = new World(); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World,m_EventBroker, true, false); + m_SystemPipeline = new SystemPipeline(m_World,m_EventBroker); m_SystemPipeline->AddSystem(0); m_SystemPipeline->AddSystem(1); diff --git a/src/Tests/CollisionTest.cpp b/src/Tests/CollisionTest.cpp index b5ba8245..6cb6c88b 100644 --- a/src/Tests/CollisionTest.cpp +++ b/src/Tests/CollisionTest.cpp @@ -33,10 +33,10 @@ void RayTest(std::string fileName) { ResourceManager::RegisterType("RawModel"); auto unitBox = ResourceManager::Load(fileName); BOOST_REQUIRE(unitBox != nullptr); - bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); + bool hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); BOOST_CHECK(hit); ray.SetDirection(glm::vec3(-1, 0, 0)); - hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); + hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); BOOST_CHECK(!hit); } @@ -146,12 +146,12 @@ BOOST_AUTO_TEST_CASE(rayVsModelTest2) z = Collision::RayVsAABB(ray, someAABB); if (z) { //hit - bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices,glm::mat4(1)); + bool hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); if (!hit) { //if rayvsaabb hit but rayvvmodel didnt hit, we get to here - glm::mat4 outtttttttt; - hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); - hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); + glm::vec3 outtttttttt; + hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices, outtttttttt); + hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); } else { hit = hit; @@ -163,7 +163,7 @@ BOOST_AUTO_TEST_CASE(rayVsModelTest2) // z = z; //} // - bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); + bool hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); ////breakpoint test //if (!hit) { // hit = hit; @@ -175,8 +175,8 @@ BOOST_AUTO_TEST_CASE(rayVsModelTest2) //if rayvsmodel hit but rayvsaabb didnt hit then we get to here z = Collision::RayVsAABB(ray, someAABB); glm::vec3 outtttttttt; - hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); - hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); + hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices, outtttttttt); + hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); } else { z = z; diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index bf2650a3..8bf16024 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -48,21 +48,26 @@ GameHealthSystemTest::GameHealthSystemTest() fp.MergeEntities(m_World); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker, false, false); + 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 player = m_World->AttachComponent(playerID, "Player"); - ComponentWrapper& health = m_World->AttachComponent(playerID, "Health"); - health["Health"] = 100.0; - m_PlayersID = playerID; + ComponentWrapper health = m_World->AttachComponent(playerID, "Health"); + healthsID = playerID; 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.Player = EntityWrapper(m_World, player.EntityID); + m_EventBroker->Publish(e3); + //damage player with 50 Events::PlayerDamage e; e.Damage = 50.0f; @@ -98,18 +103,9 @@ void GameHealthSystemTest::Tick() m_EventBroker->Swap(); m_EventBroker->Clear(); - - double currentHealth = (double)m_World->GetComponent(m_PlayersID, "Health")["Health"]; - //if players health reach 50 means he got damaged by 50 - if (currentHealth == 50.0) { - m_TestStage1Success = true; - //heal player with 40 - Events::PlayerHealthPickup e3; - e3.HealthAmount = 40.0f; - e3.Player = EntityWrapper(m_World, m_PlayersID); - m_EventBroker->Publish(e3); - } - if (m_TestStage1Success && currentHealth == 90.0f) { + + //if health reaches 90 then we know the test has succeeded (start with 100hp, remove 50hp, add 40hp) + double currentHealth = (double)m_World->GetComponent(healthsID, "Health")["Health"]; + if (currentHealth == 90) TestSucceeded = true; - } } diff --git a/src/Tests/HealthSystemTest.h b/src/Tests/HealthSystemTest.h index 275558d2..62c5f55b 100644 --- a/src/Tests/HealthSystemTest.h +++ b/src/Tests/HealthSystemTest.h @@ -6,6 +6,7 @@ #include "Core/EventBroker.h" #include "Rendering/Renderer.h" #include "Core/InputManager.h" +#include "GUI/Frame.h" #include "Core/World.h" #include "Input/InputProxy.h" #include "Input/KeyboardInputHandler.h" @@ -30,9 +31,7 @@ private: EventBroker* m_EventBroker; World* m_World; SystemPipeline* m_SystemPipeline; - int m_PlayersID; - bool m_TestStage1Success = false; - + int healthsID; }; #endif diff --git a/src/Tests/PickupSpawnTest.cpp b/src/Tests/PickupSpawnTest.cpp deleted file mode 100644 index 4acd897e..00000000 --- a/src/Tests/PickupSpawnTest.cpp +++ /dev/null @@ -1,214 +0,0 @@ -#include -using boost::unit_test_framework::test_suite; -using boost::unit_test_framework::test_case; - -#include "PickupSpawnTest.h" - -BOOST_AUTO_TEST_SUITE(PickupSpawnTestSuite) - -//dont use the same name as the classname in test cases... -BOOST_AUTO_TEST_CASE(PickupSpawnTest_HealthPickupRespawns_PlayerHealthPickupEventTriggers) -{ - PickupSpawnTest game(1); - bool success = game.Game_Loop_OneHundredTimes(); - BOOST_TEST(success); -} -BOOST_AUTO_TEST_CASE(PickupSpawnTest_APlayerAtMaxHealth_CantTakeHealthPickup) -{ - PickupSpawnTest game(2); - bool success = game.Game_Loop_OneHundredTimes(); - BOOST_TEST(success); -} -BOOST_AUTO_TEST_CASE(PickupSpawnTest_APickupCanRespawnSlowly) -{ - PickupSpawnTest game(3); - bool success = game.Game_Loop_OneHundredTimes(); - BOOST_TEST(success); -} -BOOST_AUTO_TEST_SUITE_END() - -PickupSpawnTest::PickupSpawnTest(int runTestNumber) -{ - ResourceManager::RegisterType("ConfigFile"); - ResourceManager::RegisterType("EntityFile"); - - m_Config = ResourceManager::Load("Config.ini"); - LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get("Debug.LogLevel", 1)); - - m_EventBroker = new EventBroker(); - m_World = new World(); - - // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker, false, false); - m_SystemPipeline->AddSystem(0); - m_SystemPipeline->AddSystem(1); - - //must register components (Components.xsd), else you cant create entities. Easiest done by loading a test xsd file - auto file = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); - EntityFilePreprocessor fpp(file); - fpp.RegisterComponents(m_World); - EntityFileParser fp(file); - //connect the healthpickup to the world - m_HealthPickupID = fp.MergeEntities(m_World); - - //create a player - m_PlayerID = m_World->CreateEntity(); - auto& player = m_World->AttachComponent(m_PlayerID, "Player"); - - m_RunTestNumber = runTestNumber; - - //further testsetups - TestSetup(m_RunTestNumber); - - //init glfw so dt works - glfwInit(); - - //listen to the 2 events that are related to PickupSpawn - EVENT_SUBSCRIBE_MEMBER(m_HP, &PickupSpawnTest::OnHealthPickup); - EVENT_SUBSCRIBE_MEMBER(m_PS, &PickupSpawnTest::OnPickupSpawned); -} - -bool PickupSpawnTest::OnHealthPickup(Events::PlayerHealthPickup& e) { - switch (m_RunTestNumber) - { - case 1: - //verify that the event has the correct healthgain number and playerid - if (e.HealthAmount == 22.0 && e.Player.ID == m_PlayerID) { - m_TestStage1Success = true; - } - break; - case 2: - m_TestStage1Success = false; - break; - case 3: - //verify that the event has the correct healthgain number and playerid - if (e.HealthAmount == 50.0 && e.Player.ID == m_PlayerID) { - m_TestStage1Success = true; - } - break; - } - return true; -} -bool PickupSpawnTest::OnPickupSpawned(Events::PickupSpawned& e) { - switch (m_RunTestNumber) - { - case 1: - //verify that the newly spawned pickup has the same variable values as the original one - if ((double)e.Pickup["HealthPickup"]["HealthGain"] == 22.0 && (double)e.Pickup["HealthPickup"]["RespawnTimer"] == 2.0) { - m_TestStage2Success = true; - } - break; - case 2: - m_TestStage2Success = false; - break; - case 3: - m_TestStage2Success = false; - break; - } - return true; -} - -void PickupSpawnTest::TestSetup(int testNumber) -{ - switch (m_RunTestNumber) - { - case 1: - { - //PickupSpawnTest_HealthPickupRespawns_PlayerHealthPickupEventTriggers - auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); - healthPickupEW["HealthPickup"]["RespawnTimer"] = 2.0; - healthPickupEW["HealthPickup"]["HealthGain"] = 22.0; - - //create a player - auto& health = m_World->AttachComponent(m_PlayerID, "Health"); - health["Health"] = 20.0; - health["MaxHealth"] = 100.0; - } - break; - case 2: - { - //PickupSpawnTest_APlayerAtMaxHealth_CantTakeHealthPickup - auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); - healthPickupEW["HealthPickup"]["RespawnTimer"] = 1.0; - healthPickupEW["HealthPickup"]["HealthGain"] = 50.0; - - //create a player at max health - auto& health = m_World->AttachComponent(m_PlayerID, "Health"); - health["Health"] = 100.0; - health["MaxHealth"] = 100.0; - } - break; - case 3: - { - //PickupSpawnTest_APickupCanRespawnSlowly - auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); - healthPickupEW["HealthPickup"]["RespawnTimer"] = 100.0; - healthPickupEW["HealthPickup"]["HealthGain"] = 50.0; - - //create a player - auto& health = m_World->AttachComponent(m_PlayerID, "Health"); - health["Health"] = 1.0; - health["MaxHealth"] = 100.0; - } - break; - default: - break; - } - //do the triggerTouch event to get the pickupSpawnTest started - Events::TriggerTouch eTriggerTouch; - DoTouchEvent(m_PlayerID, m_HealthPickupID); -} - -//generic stuff -void PickupSpawnTest::Tick() -{ - glfwPollEvents(); - - //just set dt to 1.0 since we want fast testing - double dt = 1.0; - - // Iterate through systems and update world! - m_SystemPipeline->Update(dt); - - m_EventBroker->Swap(); - m_EventBroker->Clear(); - - //verify that healthgain event has been published and pickup has respawned - if (m_RunTestNumber == 1 && m_TestStage1Success && m_TestStage2Success) { - m_TestSucceeded = true; - } - //verify that no healthgain event has been published and that no pickup has respawned - if (m_NumLoops > 90 && m_RunTestNumber == 2 && !m_TestStage1Success && !m_TestStage2Success) { - m_TestSucceeded = true; - } - //3: verify that the pickup hasnt spawned - if (m_NumLoops > 90 && m_RunTestNumber == 3 && m_TestStage1Success && !m_TestStage2Success) { - m_TestSucceeded = true; - } -} -bool PickupSpawnTest::Game_Loop_OneHundredTimes() { - //100 loops will be more than enough to do the test - int loops = 100; - bool success = false; - while (loops > 0) { - Tick(); - m_NumLoops++; - if (m_TestSucceeded) { - success = true; - break; - } - loops--; - } - return success; -} -PickupSpawnTest::~PickupSpawnTest() -{ - delete m_SystemPipeline; - delete m_World; -} -void PickupSpawnTest::DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject) { - Events::TriggerTouch touchEvent; - touchEvent.Entity = EntityWrapper(m_World, whoDidSomething); - touchEvent.Trigger = EntityWrapper(m_World, onWhatObject); - m_EventBroker->Publish(touchEvent); -} diff --git a/src/Tests/PickupSpawnTest.h b/src/Tests/PickupSpawnTest.h deleted file mode 100644 index b9d5483a..00000000 --- a/src/Tests/PickupSpawnTest.h +++ /dev/null @@ -1,72 +0,0 @@ -#ifndef PickupSpawnTest_h__ -#define PickupSpawnTest_h__ - -#include "Core/ResourceManager.h" -#include "Core/ConfigFile.h" -#include "Core/EventBroker.h" -#include "Core/World.h" -#include "Input/InputProxy.h" -#include "Input/KeyboardInputHandler.h" -#include "Input/MouseInputHandler.h" -#include "Core/EKeyDown.h" -#include "Core/EntityFile.h" -#include "Core/SystemPipeline.h" - -#include "Core/EntityFilePreprocessor.h" -#include "Core/EntityFileParser.h" -#include "Core/EntityFileWriter.h" - -#include "Engine/Collision/ETrigger.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 -#include "Collision/TriggerSystem.h" -#include "Collision/CollisionSystem.h" -#include "Core/EntityFileWriter.h" -#include "Game/Systems/HealthSystem.h" -#include "Game/Systems/PickupSpawnSystem.h" - -#include "Core/ResourceManager.h" - -class PickupSpawnTest -{ -public: - PickupSpawnTest(int runTestNumber); - ~PickupSpawnTest(); - - void Tick(); - - bool Game_Loop_OneHundredTimes(); - void TestSetup(int testNumber); - void DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject); - -private: - double m_LastTime; - ConfigFile* m_Config = nullptr; - EventBroker* m_EventBroker; - World* m_World; - SystemPipeline* m_SystemPipeline; - EntityID m_PlayerID, m_HealthPickupID; - int m_RunTestNumber; - - EventRelay m_HP; - bool OnHealthPickup(Events::PlayerHealthPickup& e); - EventRelay m_PS; - bool OnPickupSpawned(Events::PickupSpawned& e); - - bool m_TestStage1Success = false; - bool m_TestStage2Success = false; - - bool m_TestSucceeded = false; - int m_NumLoops = 0; - -}; - -#endif diff --git a/src/Tests/WorldTest.cpp b/src/Tests/WorldTest.cpp index 633e617a..03008562 100644 --- a/src/Tests/WorldTest.cpp +++ b/src/Tests/WorldTest.cpp @@ -69,47 +69,3 @@ BOOST_AUTO_TEST_CASE(WorldTestMultipleAllocations, * utf::tolerance(0.00001)) i++; } } - -BOOST_AUTO_TEST_CASE(WorldCopy, *utf::tolerance(0.00001)) -{ - World w1; - - // Create a test component - auto testComponent = ComponentWrapperFactory("Test", 2); - testComponent.AddProperty("TestInteger", 1337); - testComponent.AddProperty("TestDouble", 13.37); - testComponent.AddProperty("TestString", std::string("DefaultString")); - testComponent.AddProperty("TestVec3", glm::vec3(1.f, 2.f, 3.f)); - w1.RegisterComponent(testComponent); - - // Create a test entity - EntityID w1_e1 = w1.CreateEntity(); - auto w1_c1 = w1.AttachComponent(w1_e1, "Test"); - - // Create a child - EntityID w1_e2 = w1.CreateEntity(w1_e1); - auto w1_c2 = w1.AttachComponent(w1_e2, "Test"); - w1_c2["TestString"] = "NonDefaultString"; - - // Copy the world! - World w2 = w1; - - // Fetch the components - auto w2_c1 = w2.GetComponent(w1_e1, "Test"); - auto w2_c2 = w2.GetComponent(w1_e2, "Test"); - - // Check that built-in types are copied but don't reside in the same memory - BOOST_CHECK((int)w1_c1["TestInteger"] == (int)w2_c1["TestInteger"]); - BOOST_CHECK(&(int&)w1_c1["TestInteger"] != &(int&)w2_c1["TestInteger"]); - BOOST_CHECK((double)w1_c1["TestDouble"] == (double)w2_c1["TestDouble"]); - BOOST_CHECK(&(int&)w1_c1["TestDouble"] != &(int&)w2_c1["TestDouble"]); - BOOST_CHECK((int)w1_c2["TestInteger"] == (int)w2_c2["TestInteger"]); - BOOST_CHECK(&(int&)w1_c2["TestInteger"] != &(int&)w2_c2["TestInteger"]); - BOOST_CHECK((double)w1_c2["TestDouble"] == (double)w2_c2["TestDouble"]); - BOOST_CHECK(&(int&)w1_c2["TestDouble"] != &(int&)w2_c2["TestDouble"]); - // Check that specially handled strings are fine - BOOST_CHECK((std::string)w1_c1["TestString"] == (std::string)w2_c1["TestString"]); - BOOST_CHECK(&(std::string&)w1_c1["TestString"] != &(std::string&)w2_c1["TestString"]); - BOOST_CHECK((std::string)w1_c2["TestString"] == (std::string)w2_c2["TestString"]); - BOOST_CHECK(&(std::string&)w1_c2["TestString"] != &(std::string&)w2_c2["TestString"]); -}