diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 546d03f5..9e1a81db 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -78,13 +78,21 @@ 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 +// 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. 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 c963e6b8..9cd2fe63 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -15,11 +15,11 @@ class CollisionSystem : public PureSystem public: CollisionSystem(SystemParams params, Octree* octree) : System(params) - , PureSystem("Collidable") + , PureSystem("Physics") , m_Octree(octree) { } - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPhysics, double dt) override; private: Octree* m_Octree; diff --git a/include/Engine/Core/ComponentInfo.h b/include/Engine/Core/ComponentInfo.h index d9799059..137a44d8 100644 --- a/include/Engine/Core/ComponentInfo.h +++ b/include/Engine/Core/ComponentInfo.h @@ -2,6 +2,7 @@ #define ComponentInfo_h__ #include "../Common.h" +#include struct ComponentInfo { @@ -27,8 +28,9 @@ struct ComponentInfo std::string Name; std::unordered_map Fields; std::vector FieldsInOrder; + std::vector StringFields; unsigned int Stride = 0; - std::shared_ptr Defaults = nullptr; + boost::shared_array Defaults = nullptr; std::shared_ptr Meta = nullptr; }; diff --git a/include/Engine/Core/ComponentPool.h b/include/Engine/Core/ComponentPool.h index 957b8756..aedfd06b 100644 --- a/include/Engine/Core/ComponentPool.h +++ b/include/Engine/Core/ComponentPool.h @@ -1,6 +1,7 @@ #ifndef ComponentPool_h__ #define ComponentPool_h__ +#include #include "MemoryPool.h" #include "ComponentInfo.h" #include "ComponentWrapper.h" @@ -45,7 +46,8 @@ public: : m_ComponentInfo(ci) , m_Pool(ci.Meta->Allocation, sizeof(EntityID) + ci.Stride) { } - ComponentPool(const ComponentPool& other) = delete; + ~ComponentPool(); + ComponentPool(const ComponentPool& other); 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 0b9f7357..7897e874 100644 --- a/include/Engine/Core/ComponentWrapper.h +++ b/include/Engine/Core/ComponentWrapper.h @@ -2,11 +2,29 @@ #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) @@ -47,7 +65,31 @@ struct ComponentWrapper void Copy(ComponentWrapper& destination) { - memcpy(destination.Data, this->Data, Info.Stride); + // 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(); + } } struct SubscriptProxy @@ -102,26 +144,38 @@ 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) { - 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); + 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_ComponentInfo.Stride += sizeof(T); + m_DefaultValues.push_back(std::make_pair(field, defaultValue)); } - + ComponentInfo& Finalize() { - m_ComponentInfo.Defaults = std::shared_ptr(new char[m_ComponentInfo.Stride]); + m_ComponentInfo.Defaults = boost::shared_array(new char[m_ComponentInfo.Stride]); std::size_t offset = 0; - for (auto& val : m_DefaultValues) { - memcpy(m_ComponentInfo.Defaults.get() + offset, val.Data.get(), val.Size); - offset += val.Size; + 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; } return m_ComponentInfo; @@ -131,7 +185,7 @@ public: private: ComponentInfo m_ComponentInfo; - std::vector m_DefaultValues; + std::vector> m_DefaultValues; }; #endif diff --git a/include/Engine/Core/MemoryPool.h b/include/Engine/Core/MemoryPool.h index f4073294..053e75aa 100644 --- a/include/Engine/Core/MemoryPool.h +++ b/include/Engine/Core/MemoryPool.h @@ -66,9 +66,25 @@ public: , m_LowestAllocatedSlot(m_NumSlots) { } - //We may get problems with memory being released - //prematurely, etc. if we allow copies. - MemoryPool(const MemoryPool& other) = delete; + 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); + } + } MemoryPool(const MemoryPool&& other) = delete; //Free all memory that has been allocated. @@ -78,8 +94,9 @@ 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 new file mode 100644 index 00000000..a3cdfa92 --- /dev/null +++ b/include/Engine/Core/PerformanceTimer.h @@ -0,0 +1,25 @@ +#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/SystemPipeline.h b/include/Engine/Core/SystemPipeline.h index 5f7aee0b..c4801fde 100644 --- a/include/Engine/Core/SystemPipeline.h +++ b/include/Engine/Core/SystemPipeline.h @@ -6,6 +6,7 @@ #include "System.h" #include "World.h" #include "EPause.h" +#include "PerformanceTimer.h" class SystemPipeline { @@ -72,7 +73,10 @@ 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; @@ -83,7 +87,10 @@ 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); } } } @@ -106,9 +113,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 f0f90737..e7b93dfb 100644 --- a/include/Engine/Core/Util/Any.h +++ b/include/Engine/Core/Util/Any.h @@ -2,6 +2,7 @@ #define Util_Any_h__ #include +#include struct Any { @@ -10,7 +11,7 @@ struct Any template Any(const T& value) { - Data = std::shared_ptr(new char[sizeof(T)]); + Data = boost::shared_array(new char[sizeof(T)]); Size = sizeof(T); memcpy(Data.get(), &value, Size); } @@ -18,7 +19,7 @@ struct Any template Any(T&& value) { - Data = std::shared_ptr(new char[sizeof(T)]); + Data = boost::shared_array(new char[sizeof(T)]); Size = sizeof(T); memcpy(Data.get(), &value, Size); } @@ -35,7 +36,7 @@ struct Any return Any(value); } - std::shared_ptr Data = nullptr; + boost::shared_array Data = nullptr; std::size_t Size = 0; }; diff --git a/include/Engine/Core/World.h b/include/Engine/Core/World.h index 35394b9f..1604df37 100644 --- a/include/Engine/Core/World.h +++ b/include/Engine/Core/World.h @@ -15,6 +15,7 @@ public: : m_EventBroker(eventBroker) { } ~World(); + World(const World& other); // Create empty entity EntityID CreateEntity(EntityID parent = 0); diff --git a/include/Engine/GUI/Button.h b/include/Engine/GUI/Button.h deleted file mode 100644 index 80845cb7..00000000 --- a/include/Engine/GUI/Button.h +++ /dev/null @@ -1,165 +0,0 @@ -#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 new file mode 100644 index 00000000..7dfe6b48 --- /dev/null +++ b/include/Engine/GUI/ButtonSystem.h @@ -0,0 +1,44 @@ +#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 new file mode 100644 index 00000000..e4fe7abe --- /dev/null +++ b/include/Engine/GUI/EButtonClicked.h @@ -0,0 +1,16 @@ +#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 deleted file mode 100644 index 13a78383..00000000 --- a/include/Engine/GUI/EButtonEnter.h +++ /dev/null @@ -1,17 +0,0 @@ -#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 deleted file mode 100644 index 789e5aec..00000000 --- a/include/Engine/GUI/EButtonLeave.h +++ /dev/null @@ -1,17 +0,0 @@ -#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 deleted file mode 100644 index 6f925b2b..00000000 --- a/include/Engine/GUI/EButtonPress.h +++ /dev/null @@ -1,20 +0,0 @@ -#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 new file mode 100644 index 00000000..3615ac8a --- /dev/null +++ b/include/Engine/GUI/EButtonPressed.h @@ -0,0 +1,16 @@ +#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 deleted file mode 100644 index d13a8ad6..00000000 --- a/include/Engine/GUI/EButtonRelease.h +++ /dev/null @@ -1,20 +0,0 @@ -#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 new file mode 100644 index 00000000..ecd8dde2 --- /dev/null +++ b/include/Engine/GUI/EButtonReleased.h @@ -0,0 +1,16 @@ +#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 deleted file mode 100644 index 4c5f2eb9..00000000 --- a/include/Engine/GUI/Frame.h +++ /dev/null @@ -1,261 +0,0 @@ -#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 new file mode 100644 index 00000000..ba69ff0d --- /dev/null +++ b/include/Engine/GUI/MainMenuSystem.h @@ -0,0 +1,33 @@ +#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 deleted file mode 100644 index 77967b4d..00000000 --- a/include/Engine/GUI/TextureFrame.h +++ /dev/null @@ -1,112 +0,0 @@ -#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/Rendering/DrawBloomPass.h b/include/Engine/Rendering/DrawBloomPass.h index 539d6957..07c90e23 100644 --- a/include/Engine/Rendering/DrawBloomPass.h +++ b/include/Engine/Rendering/DrawBloomPass.h @@ -24,6 +24,8 @@ public: void Draw(GLuint texture); + void OnWindowResize(); + //Getters //Return the blurred result of the texture that was sent into draw GLuint GaussianTexture() const { return m_GaussianTexture_vert; } diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index bf8d4d76..e3389471 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -18,8 +18,9 @@ public: void InitializeTextures(); void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(RenderScene& scene); + void Draw(RenderScene& scene, GLuint SSAOTexture); void ClearBuffer(); + void OnWindowResize(); //Return the texture that is used in later stages to apply the bloom effect GLuint BloomTexture() const { return m_BloomTexture; } @@ -31,13 +32,12 @@ public: 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 DrawModelRenderQueues(std::list>& jobs, RenderScene& scene, GLuint SSAOTexture); void DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene); void DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene); void DrawToDepthBuffer(std::list>& jobs, RenderScene& scene); diff --git a/include/Engine/Rendering/LightCullingPass.h b/include/Engine/Rendering/LightCullingPass.h index d8852df0..914fb8bb 100644 --- a/include/Engine/Rendering/LightCullingPass.h +++ b/include/Engine/Rendering/LightCullingPass.h @@ -21,6 +21,7 @@ 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 41b0b8dd..c2a469d2 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -108,6 +108,7 @@ 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)); @@ -170,7 +171,7 @@ struct ModelJob : RenderJob ::Skeleton::AnimationOffset AnimationOffset; - + float GlowIntensity = 8.0; glm::vec4 DiffuseColor; glm::vec4 SpecularColor; glm::vec4 IncandescenceColor; diff --git a/include/Engine/Rendering/PickingPass.h b/include/Engine/Rendering/PickingPass.h index 2ce2e78d..f6434781 100644 --- a/include/Engine/Rendering/PickingPass.h +++ b/include/Engine/Rendering/PickingPass.h @@ -22,6 +22,8 @@ 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; } @@ -40,7 +42,7 @@ private: const IRenderer* m_Renderer; ShaderProgram* m_PickingProgram; - ShaderProgram* m_PickingSkinnedProgram; + ShaderProgram* m_PickingSkinnedProgram; Camera* m_Camera; struct PickingInfo diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index 04754514..aa87536b 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -16,6 +16,7 @@ #include "DrawScreenQuadPass.h" #include "DrawBloomPass.h" #include "DrawColorCorrectionPass.h" +#include "SSAOPass.h" #include "../Core/EventBroker.h" #include "ImGuiRenderPass.h" #include "Camera.h" @@ -23,9 +24,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) : m_EventBroker(eventBroker) @@ -37,8 +41,12 @@ public: virtual PickData Pick(glm::vec2 screenCoord) override; + private: //----------------------Variables----------------------// + + static std::unordered_map m_WindowToRenderer; + EventBroker* m_EventBroker; TextPass* m_TextPass; @@ -50,6 +58,13 @@ private: Model* m_UnitSphere; int m_DebugTextureToDraw = 0; + bool m_ResizeWindow = false; + float m_SSAO_Radius = 1.0f; + float m_SSAO_Bias = 0.05f; + float m_SSAO_Contrast = 1.5f; + float m_SSAO_IntensityScale = 1.0f; + int m_SSAO_NumOfSamples = 24; + int m_SSAO_NumOfTurns = 7; PickingPass* m_PickingPass; LightCullingPass* m_LightCullingPass; @@ -58,6 +73,7 @@ private: DrawScreenQuadPass* m_DrawScreenQuadPass; DrawBloomPass* m_DrawBloomPass; DrawColorCorrectionPass* m_DrawColorCorrectionPass; + SSAOPass* m_SSAOPass; //----------------------Functions----------------------// void InitializeWindow(); diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h new file mode 100644 index 00000000..f15e20d3 --- /dev/null +++ b/include/Engine/Rendering/SSAOPass.h @@ -0,0 +1,61 @@ +#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* rendere); + ~SSAOPass() { }; + + void Draw(GLuint depthBuffer, Camera* camera); + void Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns); + void ClearBuffer(); + + //Return the SSAO of the texture sent to Draw + GLuint SSAOTexture() const { return m_DrawBloomPass->GaussianTexture(); } + +private: + void InitializeTexture(); + void InitializeFrameBuffer(); + void InitializeShaderProgram(); + void InitializeBuffer(); + + void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; + + void ComputeAO(GLuint depthBuffer, Camera* camera); + //void blurHorizontal(GLuint depthBuffer); + //void blurVertical(GLuint depthBuffer); + + Model* m_ScreenQuad; + + const IRenderer* m_Renderer; + + float m_Radius; + float m_Bias; + float m_Contrast; + float m_IntensityScale; + int m_NumOfSamples; + int m_NumOfTurns; + + GLuint m_SSAOTexture; + FrameBuffer m_SSAOFramBuffer; + + GLuint m_SSAOViewSpaceZTexture; + FrameBuffer m_SSAOViewSpaceZFramBuffer; + + ShaderProgram* m_SSAOProgram; + ShaderProgram* m_SSAOViewSpaceZProgram; + + DrawBloomPass* m_DrawBloomPass; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/SSAOPassState.h b/include/Engine/Rendering/SSAOPassState.h new file mode 100644 index 00000000..115fdcf7 --- /dev/null +++ b/include/Engine/Rendering/SSAOPassState.h @@ -0,0 +1,15 @@ +#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 07636a97..25c2d5cb 100644 --- a/include/Engine/Rendering/SpriteJob.h +++ b/include/Engine/Rendering/SpriteJob.h @@ -40,7 +40,9 @@ struct SpriteJob : RenderJob Depth = viewpos.z; } World = world; + Pickable = world->HasComponent(cSprite.EntityID, "Button"); IsIndicator = isIndicator; + FillColor = fillColor; FillPercentage = fillPercentage; }; @@ -61,6 +63,7 @@ struct SpriteJob : RenderJob unsigned int EndIndex = 0; World* World; + bool Pickable; bool IsIndicator = false; glm::vec4 FillColor = glm::vec4(0); diff --git a/include/Game/Game.h b/include/Game/Game.h index baf15656..06fd4703 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -8,7 +8,6 @@ #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" @@ -35,6 +34,9 @@ #include "Sound/SoundManager.h" #include "Systems/SoundSystem.h" +//Performance +#include "Core/PerformanceTimer.h" + class Game { public: @@ -53,7 +55,6 @@ 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/HealthSystem.h b/include/Game/Systems/HealthSystem.h index 56f2f838..962e3737 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -27,17 +27,16 @@ 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/SpawnerSystem.h b/include/Game/Systems/SpawnerSystem.h index 9cb4bd06..e4a44738 100644 --- a/include/Game/Systems/SpawnerSystem.h +++ b/include/Game/Systems/SpawnerSystem.h @@ -15,11 +15,16 @@ class SpawnerSystem : public System public: SpawnerSystem(SystemParams params); - static EntityWrapper Spawn(EntityWrapper spawner, EntityWrapper parent = EntityWrapper::Invalid); + // 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 = ""); 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/resources/DefaultInput.ini b/resources/DefaultInput.ini index d5489c3a..776cbecd 100644 --- a/resources/DefaultInput.ini +++ b/resources/DefaultInput.ini @@ -25,4 +25,6 @@ C=ConnectToServer N=SwitchToServer M=SwitchToClient P=SwitchToPlayer -K=TakeDamage,1500 \ No newline at end of file +K=TakeDamage,1500 +F2=PerformanceTimingResetAllTimers +F3=PerformanceTimingCreateExcelData \ No newline at end of file diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 8a5f51f3..c97f2a06 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -41,6 +41,9 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Button.xml b/resources/Schema/Components/Button.xml new file mode 100644 index 00000000..cbfd80d4 --- /dev/null +++ b/resources/Schema/Components/Button.xml @@ -0,0 +1,3 @@ + + \ No newline at end of file diff --git a/resources/Schema/Components/Button.xsd b/resources/Schema/Components/Button.xsd new file mode 100644 index 00000000..7d97fef1 --- /dev/null +++ b/resources/Schema/Components/Button.xsd @@ -0,0 +1,10 @@ + + + + + + + Makes sprites klickable. + + + \ No newline at end of file diff --git a/resources/Schema/Components/Menu.xml b/resources/Schema/Components/Menu.xml new file mode 100644 index 00000000..f17427b8 --- /dev/null +++ b/resources/Schema/Components/Menu.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Menu.xsd b/resources/Schema/Components/Menu.xsd new file mode 100644 index 00000000..18ea8565 --- /dev/null +++ b/resources/Schema/Components/Menu.xsd @@ -0,0 +1,9 @@ + + + + + + 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 4b77dacb..f81c8210 100644 --- a/resources/Schema/Components/Model.xml +++ b/resources/Schema/Components/Model.xml @@ -8,4 +8,5 @@ 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 9c0cd519..31203ff6 100644 --- a/resources/Schema/Components/Model.xsd +++ b/resources/Schema/Components/Model.xsd @@ -33,6 +33,9 @@ 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 new file mode 100644 index 00000000..db7b9cc2 --- /dev/null +++ b/resources/Schema/Components/Page.xml @@ -0,0 +1,4 @@ + + + 0 + \ No newline at end of file diff --git a/resources/Schema/Components/Page.xsd b/resources/Schema/Components/Page.xsd new file mode 100644 index 00000000..777124a2 --- /dev/null +++ b/resources/Schema/Components/Page.xsd @@ -0,0 +1,14 @@ + + + + + + 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/Physics.xml b/resources/Schema/Components/Physics.xml index 6cb73c75..84b6aba3 100644 --- a/resources/Schema/Components/Physics.xml +++ b/resources/Schema/Components/Physics.xml @@ -2,6 +2,7 @@ true + false 0.33 diff --git a/resources/Schema/Components/Physics.xsd b/resources/Schema/Components/Physics.xsd index 7fed1fb5..206e2a23 100644 --- a/resources/Schema/Components/Physics.xsd +++ b/resources/Schema/Components/Physics.xsd @@ -13,6 +13,7 @@ m/s^2 + The largest height of a "stair-step" that can be walked over diff --git a/resources/Schema/Entities/Button.xml b/resources/Schema/Entities/Button.xml new file mode 100644 index 00000000..21f64334 --- /dev/null +++ b/resources/Schema/Entities/Button.xml @@ -0,0 +1,32 @@ + + + + + + + Textures/Core/White.png + + + + + + + + + + + + Play + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + diff --git a/resources/Schema/Entities/GameMap.xml b/resources/Schema/Entities/GameMap.xml index 84a1e363..c3a16361 100644 --- a/resources/Schema/Entities/GameMap.xml +++ b/resources/Schema/Entities/GameMap.xml @@ -144,7 +144,7 @@ - + @@ -206,14 +206,16 @@ - + - + + + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 4fd70af1..d4485112 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -349,13 +349,12 @@ Idle - 1.9902125899398158 + 1.8314163732853146 1 Models/Characters/Assault/FirstPerson.mesh - true @@ -367,11 +366,10 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - true - - + + @@ -477,7 +475,7 @@ Idle - 1.7887947062665859 + 0.16333512901638159 1 @@ -501,8 +499,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + @@ -572,24 +570,6 @@ - - - - 60 - - - Textures/Icons/Arrow.png - false - - - - - - - - - - diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index c9ac246d..4be8fc26 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -349,13 +349,12 @@ Idle - 1.5972608217572741 + 0.018170670865885086 1 Models/Characters/Assault/FirstPerson.mesh - true @@ -367,11 +366,10 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - true - - + + @@ -477,7 +475,7 @@ Idle - 1.0291785284465931 + 0.11675631578762591 1 @@ -501,8 +499,8 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + + @@ -572,23 +570,6 @@ - - - - 60 - - - Textures/Icons/Arrow.png - - - - - - - - - - diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 40951468..0aa2fbe7 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -77,18 +77,6 @@ - - - - Sound Test - Fonts/DroidSans.ttf,64 - - - - - - - @@ -105,7 +93,7 @@ - + @@ -180,7 +168,7 @@ - + @@ -225,7 +213,7 @@ - + @@ -289,7 +277,7 @@ - + @@ -321,7 +309,7 @@ - + @@ -671,7 +659,7 @@ - + @@ -718,7 +706,7 @@ - + @@ -778,7 +766,7 @@ - + @@ -825,7 +813,7 @@ - + @@ -871,7 +859,7 @@ - + @@ -918,7 +906,7 @@ - + @@ -965,7 +953,7 @@ - + @@ -1027,7 +1015,7 @@ Models/Core/UnitCube.mesh - + true @@ -1077,7 +1065,7 @@ Models/Core/UnitCube.mesh - + true @@ -1167,7 +1155,7 @@ Models/Core/UnitCube.mesh - + true @@ -1217,7 +1205,7 @@ Models/Core/UnitCube.mesh - + true @@ -1379,7 +1367,7 @@ - + @@ -1388,7 +1376,7 @@ true - 0.75205058136495551 + 0.8256214817261025 3.7999999523162842 true @@ -1435,7 +1423,7 @@ - + @@ -1444,7 +1432,7 @@ - 1.2019563319790627 + 1.8641349174045843 Models/Characters/Assault/AssaultTPose.mesh @@ -1487,7 +1475,7 @@ - + @@ -1498,7 +1486,7 @@ true - 0.68540211563899389 + 1.8641349174045843 true @@ -1543,7 +1531,7 @@ - + @@ -1553,7 +1541,7 @@ true - 0.95150063648635763 + 1.2301962937648341 10 3 @@ -1601,7 +1589,7 @@ - + @@ -1611,7 +1599,7 @@ true - 1.3515288978624223 + 3.4214855659573402 true 5 true @@ -1678,10 +1666,10 @@ + Models/Core/UnitCube.mesh - @@ -1792,7 +1780,7 @@ true - 1.3682019578975679 + 0.8256214817261025 3.7999999523162842 true @@ -1836,12 +1824,12 @@ + Models/AssaultAnimated.mesh - @@ -2095,7 +2083,7 @@ Textures/Core/UnitHexagon.png - + @@ -2107,7 +2095,7 @@ 1 - + Textures/Core/UnitHexagon_Rotated.png @@ -2145,6 +2133,355 @@ + + + + + + + + + + + + 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 new file mode 100644 index 00000000..73678601 --- /dev/null +++ b/resources/Schema/Entities/TestMenu.xml @@ -0,0 +1,299 @@ + + + + + + + + + + + + + + + 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 9ea264d1..a9c5f641 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -47,6 +47,9 @@ + + + diff --git a/resources/Shaders/DrawColorCorrection.frag.glsl b/resources/Shaders/DrawColorCorrection.frag.glsl index 76db3e82..bae50887 100644 --- a/resources/Shaders/DrawColorCorrection.frag.glsl +++ b/resources/Shaders/DrawColorCorrection.frag.glsl @@ -19,6 +19,8 @@ void main() vec4 bloomColor = texture(BloomTexture, Input.TextureCoordinate); vec4 hdrColorLowRes = texture(SceneTextureLowRes, Input.TextureCoordinate); vec4 bloomColorLowRes = texture(BloomTextureLowRes, Input.TextureCoordinate); + + //hdrColor = hdrColor * SSAO; hdrColor += bloomColor; hdrColorLowRes; @@ -33,7 +35,6 @@ void main() //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 471ee20b..47da7480 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -1,5 +1,7 @@ #version 430 +#define MIN_AMBIENT_LIGHT 0.3 + uniform mat4 M; uniform mat4 V; uniform mat4 P; @@ -9,15 +11,17 @@ uniform vec2 ScreenDimensions; uniform vec4 FillColor; uniform vec4 AmbientColor; uniform float FillPercentage; +uniform float GlowIntensity = 10; uniform vec2 DiffuseUVRepeat; uniform vec2 NormalUVRepeat; uniform vec2 SpecularUVRepeat; uniform vec2 GlowUVRepeat; -layout (binding = 0) uniform sampler2D DiffuseTexture; -layout (binding = 1) uniform sampler2D NormalMapTexture; -layout (binding = 2) uniform sampler2D SpecularMapTexture; -layout (binding = 3) uniform sampler2D GlowMapTexture; +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; #define TILE_SIZE 16 @@ -119,6 +123,8 @@ vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textu void main() { + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy), 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); @@ -133,7 +139,7 @@ void main() tilePos.y = int(gl_FragCoord.y/TILE_SIZE); LightResult totalLighting; - totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); + 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); @@ -151,8 +157,8 @@ void main() } else if (light.Type == 2) { //Directional light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); } - totalLighting.Diffuse += light_result.Diffuse; - totalLighting.Specular += light_result.Specular; + 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); @@ -166,7 +172,7 @@ void main() color_result += FillColor; } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - color_result += glowTexel*3; + color_result += glowTexel*GlowIntensity; bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); diff --git a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl index e862d926..cf358b96 100644 --- a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl +++ b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl @@ -1,5 +1,7 @@ #version 430 +#define MIN_AMBIENT_LIGHT 0.3 + uniform mat4 M; uniform mat4 V; uniform mat4 P; @@ -23,19 +25,20 @@ uniform vec2 SpecularUVRepeat3; uniform vec2 GlowUVRepeat1; uniform vec2 GlowUVRepeat2; uniform vec2 GlowUVRepeat3; -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; +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; #define TILE_SIZE 16 @@ -174,6 +177,9 @@ vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, void main() { + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy), 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, @@ -195,7 +201,7 @@ void main() tilePos.y = int(gl_FragCoord.y/TILE_SIZE); LightResult totalLighting; - totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); + 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); @@ -213,8 +219,8 @@ void main() } else if (light.Type == 2) { //Directional light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); } - totalLighting.Diffuse += light_result.Diffuse; - totalLighting.Specular += light_result.Specular; + 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); diff --git a/resources/Shaders/SSAO.frag.glsl b/resources/Shaders/SSAO.frag.glsl new file mode 100644 index 00000000..68c830f8 --- /dev/null +++ b/resources/Shaders/SSAO.frag.glsl @@ -0,0 +1,114 @@ +#version 430 + +//Number of samples per pixel +uniform int uNumOfSamples; +//#define NUM_SAMPLES (11) + +//Number of turns around the cirle +uniform int uNumOfTurns; +//#define NUM_TURNS (7) + +layout (binding = 0) uniform sampler2D ViewSpaceZ; + +uniform vec4 uProjInfo; + +uniform float uProjScale; +//#define ProjScale 500 + +uniform float uRadius; +//#define Radius 1.0f + +uniform float uBias; +//#define Bias 0.012f + +uniform float uContrast; +//#define IntensityDivR6 1 + +uniform float uIntensityScale; + +out float AO; + +vec3 getVSPosition(ivec2 ScreenSpaceCoord) { + 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; + if(origin.z < uRadius){ + radius = origin.z; + } else { + radius = 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 new file mode 100644 index 00000000..a019c5ef --- /dev/null +++ b/resources/Shaders/SSAO.vert.glsl @@ -0,0 +1,8 @@ +#version 430 + +layout (location = 0) in vec3 Position; + +void main() +{ + gl_Position = vec4(Position, 1.0); +} \ No newline at end of file diff --git a/resources/Shaders/SSAOViewSpaceZ.frag.glsl b/resources/Shaders/SSAOViewSpaceZ.frag.glsl new file mode 100644 index 00000000..dbcfd899 --- /dev/null +++ b/resources/Shaders/SSAOViewSpaceZ.frag.glsl @@ -0,0 +1,14 @@ +#version 430 + +layout (binding = 0) uniform sampler2D DepthBuffer; +uniform vec3 ClipInfo; + +out float depthLinear; +//Just for Debug, should be depthLinear +//out vec4 fragmentColor; +void main() { + float depthSample = texelFetch(DepthBuffer, ivec2(gl_FragCoord.xy), 0).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 9ce2bbdf..754be6ac 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 = 0) uniform sampler2D DiffuseTexture; -layout (binding = 1) uniform sampler2D GlowMapTexture; +layout (binding = 1) uniform sampler2D DiffuseTexture; +layout (binding = 2) uniform sampler2D GlowMapTexture; in VertexData{ diff --git a/src/Engine/CMakeLists.txt b/src/Engine/CMakeLists.txt index 19763310..e74214cf 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 program_options) +find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono timer 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 ab2098b7..68d99d92 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 = INFINITY; + float dist = outDistance; float u; float v; if (RayVsTriangle(ray, v0, v1, v2, dist, u, v)) { @@ -366,7 +366,8 @@ bool AABBvsTriangle(const AABB& box, float verticalStepHeight, bool& isOnGround, glm::vec3& boxVelocity, - glm::vec3& outResolution) + glm::vec3& outResolution, + bool resolveCollision) { //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. @@ -426,7 +427,7 @@ bool AABBvsTriangle(const AABB& box, //if projections don't overlap, return false. if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) { return false; - } else { + } else if (resolveCollision) { //Overwrite the smallest resolution if this is smaller. if (resolutionDist < resolveShortest.DistanceSq) { resolveShortest.Vector = glm::vec3(0.f); @@ -463,6 +464,11 @@ 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); @@ -537,7 +543,8 @@ bool AABBvsTriangles(const AABB& box, glm::vec3& boxVelocity, float verticalStepHeight, bool& isOnGround, - glm::vec3& outResolutionVector) + glm::vec3& outResolutionVector, + bool resolveCollision) { bool hit = false; @@ -553,7 +560,7 @@ bool AABBvsTriangles(const AABB& box, }; glm::vec3 outVec; bool collideWithGround = isOnGround; - if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec)) { + if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec, resolveCollision)) { hit = true; outResolutionVector += outVec; newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); @@ -569,6 +576,44 @@ 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; @@ -648,8 +693,9 @@ 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; + + glm::vec3 size = boxA.Size(); + float diameter = std::min(size.x, size.z); + glm::vec3 prevOrigin = (glm::vec3)cPhysics["PrevOrigin"]; + glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; + float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; + //If the entity has moved farther than the size of its box, we need to handle it specially. + bool traceCollision = rayLength > diameter; + //hack solution: If prevOrigin is less than -9000 in all dimensions, + //then it means it is not set, i.e. this is the first collision check for the entity. + if (traceCollision && glm::any(glm::greaterThan((glm::vec3)cPhysics["PrevOrigin"], glm::vec3(-9000.f)))) { + Ray ray(prevOrigin, toCurrentPos); + m_OctreeResult.clear(); + m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); + for (auto& boxB : m_OctreeResult) { + if (boxA.Entity == boxB.Entity) { + continue; + } + bool hit; + float dist; + if (boxB.Entity.HasComponent("Model")) { + RawModel* model; + std::string res = (std::string)boxB.Entity["Model"]["Resource"]; + try { + model = ResourceManager::Load(res); + } catch (const std::exception&) { + 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) { @@ -64,4 +111,6 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c if (!everHitTheGround) { (bool)cPhysics["IsOnGround"] = false; } + + (glm::vec3&)cPhysics["PrevOrigin"] = boxA.Origin(); } diff --git a/src/Engine/Core/ComponentPool.cpp b/src/Engine/Core/ComponentPool.cpp index 7b465fbc..059b2e38 100644 --- a/src/Engine/Core/ComponentPool.cpp +++ b/src/Engine/Core/ComponentPool.cpp @@ -1,7 +1,5 @@ #include "Core/ComponentPool.h" - - ComponentWrapper ComponentPoolForwardIterator::operator*() const { char* data = &(*m_MemoryPoolIterator); @@ -32,6 +30,34 @@ 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; @@ -39,10 +65,19 @@ ComponentPoolForwardIterator& ComponentPoolForwardIterator::operator++() ComponentWrapper ComponentPool::Allocate(EntityID entity) { + // Allocate pool data char* data = m_Pool.Allocate(); + // Copy EntityID memcpy(data, &entity, sizeof(EntityID)); + m_EntityToComponent[entity] = data; - return ComponentWrapper(m_ComponentInfo, data); + ComponentWrapper component(m_ComponentInfo, data); + + // Copy defaults + memcpy(component.Data, m_ComponentInfo.Defaults.get(), m_ComponentInfo.Stride); + ComponentWrapper::SolidifyStrings(component); + + return component; } ComponentWrapper ComponentPool::GetByEntity(EntityID ent) @@ -57,6 +92,7 @@ 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 a1370dd2..592daedb 100644 --- a/src/Engine/Core/EntityFilePreprocessor.cpp +++ b/src/Engine/Core/EntityFilePreprocessor.cpp @@ -185,6 +185,9 @@ 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; } @@ -201,7 +204,7 @@ void EntityFilePreprocessor::parseDefaults() for (auto& ci : m_ComponentInfo) { // Allocate memory for default values - ci.second.Defaults = std::shared_ptr(new char[ci.second.Stride]); + ci.second.Defaults = boost::shared_array(new char[ci.second.Stride], std::bind(&ComponentWrapper::Destroy, ci.second, std::placeholders::_1)); memset(ci.second.Defaults.get(), 0, ci.second.Stride); std::string componentName = ci.first; diff --git a/src/Engine/Core/PerformanceTimer.cpp b/src/Engine/Core/PerformanceTimer.cpp new file mode 100644 index 00000000..50983e79 --- /dev/null +++ b/src/Engine/Core/PerformanceTimer.cpp @@ -0,0 +1,76 @@ +#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/World.cpp b/src/Engine/Core/World.cpp index 69c25f61..8788a92e 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -9,7 +9,20 @@ World::~World() } } -EntityID World::CreateEntity(EntityID parent /*= 0*/) +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 newEntity = generateEntityID(); if (newEntity == parent) { @@ -44,10 +57,8 @@ ComponentWrapper World::AttachComponent(EntityID entity, const std::string& comp ComponentPool* pool = m_ComponentPools.at(componentType); const ComponentInfo& ci = pool->ComponentInfo(); - // Allocate space for the component + // Allocate component with default values ComponentWrapper c = pool->Allocate(entity); - // Write default values - memcpy(c.Data, ci.Defaults.get(), ci.Stride); return c; } diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index 921df4dc..97ea9d53 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -225,6 +225,12 @@ 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 new file mode 100644 index 00000000..93ae1811 --- /dev/null +++ b/src/Engine/GUI/ButtonSystem.cpp @@ -0,0 +1,84 @@ +#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 new file mode 100644 index 00000000..f8bf032b --- /dev/null +++ b/src/Engine/GUI/MainMenuSystem.cpp @@ -0,0 +1,57 @@ +#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 3406535a..a2f52adb 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -437,11 +437,12 @@ void Client::parsePlayerDamage(Packet& packet) { Events::PlayerDamage e; PlayerID victimID = packet.ReadPrimitive(); - if(serverClientMapsHasEntity(victimID)){ + PlayerID inflictorID = packet.ReadPrimitive(); + if(!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)){ return; } e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); - e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(packet.ReadPrimitive())); + e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(inflictorID)); e.Damage = packet.ReadPrimitive(); // Don't rebroadcast our own player damage events or we'll have an infinite loop! if (e.Inflictor != m_LocalPlayer) { diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 082849c7..aa66433b 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -84,7 +84,6 @@ void Server::Update() if (isReadingData) { Network::Update(); } - } void Server::parseMessageType(Packet& packet) diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 46612d5e..6bfb58eb 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -19,16 +19,20 @@ void DrawBloomPass::InitializeTextures() void DrawBloomPass::InitializeShaderPrograms() { m_GaussianProgram_horiz = ResourceManager::Load("##GaussianProgramHoriz"); - 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(); + 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"); - 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"); + 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(); + } } @@ -71,15 +75,12 @@ 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++) { //Vertical pass @@ -92,7 +93,6 @@ void DrawBloomPass::Draw(GLuint texture) 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_horiz.Bind(); @@ -112,7 +112,6 @@ void DrawBloomPass::Draw(GLuint texture) m_GaussianProgram_vert->Bind(); 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 @@ -121,6 +120,15 @@ void DrawBloomPass::Draw(GLuint texture) GLERROR("DrawBloomPass::Draw: END"); } + +void DrawBloomPass::OnWindowResize() +{ + GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + m_GaussianFrameBuffer_vert.Generate(); + GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + m_GaussianFrameBuffer_horiz.Generate(); +} + void DrawBloomPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const { glGenTextures(1, texture); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 11db71f0..a12c52b1 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -27,6 +27,7 @@ void DrawFinalPass::InitializeFrameBuffers() glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); GLERROR("RenderBuffer generation"); + GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); //GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); @@ -173,25 +174,25 @@ void DrawFinalPass::InitializeShaderPrograms() GLERROR("Creating DepthFill program"); } -void DrawFinalPass::Draw(RenderScene& scene) +void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) { GLERROR("Pre"); - DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); if (scene.ClearDepth) { - glClear(GL_DEPTH_BUFFER_BIT); + //glClear(GL_DEPTH_BUFFER_BIT); + state->Disable(GL_DEPTH_TEST); + state->DepthMask(GL_FALSE); } //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->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); GLERROR("OpaqueObjects"); - DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); GLERROR("TransparentObjects"); DrawSprites(scene.Jobs.SpriteJob, scene); GLERROR("SpriteJobs"); @@ -206,11 +207,11 @@ void DrawFinalPass::Draw(RenderScene& scene) //Draw Opaque shielded objects state->StencilFunc(GL_NOTEQUAL, 1, 0xFF); state->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene); //might need changing + DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene, SSAOTexture); //might need changing GLERROR("Shielded Opaque object"); //Draw Transparen Shielded objects - DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene); //might need changing + DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene, SSAOTexture); //might need changing GLERROR("Shielded Transparent objects"); GLERROR("END"); @@ -241,14 +242,14 @@ void DrawFinalPass::Draw(RenderScene& scene) DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); GLERROR("StencilPass"); - glClear(GL_DEPTH_BUFFER_BIT); + //glClear(GL_DEPTH_BUFFER_BIT); stateLowRes->Enable(GL_DEPTH_TEST); stateLowRes->StencilFunc(GL_LEQUAL, 1, 0xFF); stateLowRes->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); GLERROR("OpaqueObjects"); - DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); GLERROR("TransparentObjects"); glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); @@ -274,6 +275,27 @@ void DrawFinalPass::ClearBuffer() m_FinalPassFrameBuffer.Unbind(); } + +void DrawFinalPass::OnWindowResize() +{ + //InitializeFrameBuffers(); + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + + GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + m_FinalPassFrameBuffer.Generate(); + + + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBufferLowRes); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)); + + GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); + m_FinalPassFrameBufferLowRes.Generate(); + GLERROR("Error changing texture resolutions"); +} + void DrawFinalPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const { glGenTextures(1, texture); @@ -300,7 +322,7 @@ void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm: GLERROR("MipMap Texture initialization failed"); } -void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene) +void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene, GLuint SSAOTexture) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); GLERROR("forwardHandle"); @@ -323,6 +345,9 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, SSAOTexture); + for (auto &job : jobs) { auto explosionEffectJob = std::dynamic_pointer_cast(job); if (explosionEffectJob) { @@ -669,14 +694,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_TEXTURE0); + glActiveTexture(GL_TEXTURE1); if (spriteJob->DiffuseTexture != nullptr) { glBindTexture(GL_TEXTURE_2D, spriteJob->DiffuseTexture->m_Texture); } else { glBindTexture(GL_TEXTURE_2D, m_ErrorTexture->m_Texture); } - glActiveTexture(GL_TEXTURE1); + glActiveTexture(GL_TEXTURE2); if (spriteJob->IncandescenceTexture != nullptr) { glBindTexture(GL_TEXTURE_2D, spriteJob->IncandescenceTexture->m_Texture); } else { @@ -689,9 +714,6 @@ 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(); } @@ -705,7 +727,7 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptrProjectionMatrix())); GLERROR("Bind 4 uniform"); - glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); GLERROR("Bind 5 uniform"); glUniform3fv(glGetUniformLocation(shaderHandle, "ExplosionOrigin"), 1, glm::value_ptr(job->ExplosionOrigin)); @@ -738,6 +760,8 @@ 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"); } @@ -755,7 +779,7 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptrResolution().Width, m_Renderer->Resolution().Height); + glUniform2f(Location_ScreenDimensions, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); GLERROR("Bind 5 uniform"); GLint Location_FillPercentage = glGetUniformLocation(shaderHandle, "FillPercentage"); @@ -773,6 +797,11 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptrGlowIntensity); + GLERROR("END"); } @@ -782,7 +811,7 @@ void DrawFinalPass::BindExplosionTextures(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)); @@ -792,7 +821,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)); @@ -802,7 +831,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)); @@ -812,7 +841,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)); @@ -825,7 +854,7 @@ void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptrSplatMap->Texture->m_Texture); int texturePosition = GL_TEXTURE1; @@ -900,7 +929,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)); @@ -910,7 +939,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)); @@ -920,7 +949,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)); @@ -930,7 +959,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)); @@ -943,10 +972,10 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrSplatMap->Texture->m_Texture); - int texturePosition = GL_TEXTURE1; + int texturePosition = GL_TEXTURE2; //Bind 5 diffuse textures std::string UniformName = "DiffuseUVRepeat"; diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index c0be4cb1..794fb84e 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -72,8 +72,8 @@ void FrameBuffer::Generate() GLenum* bufferTextures = &attachments[0]; glDrawBuffers(attachments.size(), bufferTextures); - if(GLERROR("4")) { - printf("hello"); + if (GLERROR("GLBufferAttachement error")) { + printf(": AttachmentSize %i", attachments.size()); } if (GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { diff --git a/src/Engine/Rendering/LightCullingPass.cpp b/src/Engine/Rendering/LightCullingPass.cpp index 0ae359db..1ce1f88c 100644 --- a/src/Engine/Rendering/LightCullingPass.cpp +++ b/src/Engine/Rendering/LightCullingPass.cpp @@ -110,6 +110,34 @@ 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 ecd0a4b8..d1ed73dd 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -15,6 +15,8 @@ PickingPass::~PickingPass() } + + void PickingPass::InitializeTextures() { GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, @@ -23,11 +25,20 @@ void PickingPass::InitializeTextures() void PickingPass::InitializeFrameBuffers() { - glGenRenderbuffers(1, &m_DepthBuffer); + /* glGenRenderbuffers(1, &m_DepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);*/ - m_PickingBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); + glGenTextures(1, &m_DepthBuffer); + + glBindTexture(GL_TEXTURE_2D, m_DepthBuffer); + glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width), (int)(m_Renderer->GetViewportSize().Height), 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); + + m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0))); m_PickingBuffer.Generate(); } @@ -61,7 +72,9 @@ void PickingPass::Draw(RenderScene& scene) m_PickingProgram->Bind(); if (scene.ClearDepth) { - glClear(GL_DEPTH_BUFFER_BIT); + //glClear(GL_DEPTH_BUFFER_BIT); + state->Disable(GL_DEPTH_TEST); + state->DepthMask(GL_FALSE); } m_Camera = scene.Camera; @@ -234,6 +247,52 @@ 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); @@ -306,8 +365,6 @@ void PickingPass::Draw(RenderScene& scene) delete state; } - - void PickingPass::ClearPicking() { m_PickingColorsToEntity.clear(); @@ -321,6 +378,15 @@ void PickingPass::ClearPicking() m_PickingBuffer.Unbind(); } + +void PickingPass::OnWindowResize() +{ + InitializeTextures(); + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + m_PickingBuffer.Generate(); +} + PickData PickingPass::Pick(glm::vec2 screenCoord) { int fbWidth; diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index be84160c..0c668cad 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -1,5 +1,7 @@ #include "Rendering/Renderer.h" +std::unordered_map Renderer::m_WindowToRenderer; + void Renderer::Initialize() { InitializeWindow(); @@ -12,7 +14,6 @@ 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");*/ @@ -20,6 +21,17 @@ 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_DrawFinalPass->OnWindowResize(); + currentRenderer->m_LightCullingPass->OnWindowResize(); + currentRenderer->m_PickingPass->OnWindowResize(); + currentRenderer->m_DrawBloomPass->OnWindowResize(); +} + void Renderer::InitializeWindow() { // Initialize GLFW @@ -39,6 +51,7 @@ void Renderer::InitializeWindow() LOG_ERROR("GLFW: Failed to create window"); exit(EXIT_FAILURE); } + glfwSetFramebufferSizeCallback(m_Window, &glfwFrameBufferCallback); glfwMakeContextCurrent(m_Window); // GL version info @@ -59,8 +72,10 @@ void Renderer::InitializeWindow() exit(EXIT_FAILURE); } + m_WindowToRenderer[m_Window] = this; + int windowSize[2]; - glfwGetWindowSize(m_Window, &windowSize[0], &windowSize[1]); + glfwGetFramebufferSize(m_Window, &windowSize[0], &windowSize[1]); m_ViewportSize = Rectangle(windowSize[0], windowSize[1]); } @@ -93,40 +108,71 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { - ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking"); + ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0Ambient Occlusion"); + + ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.01f, 5.0f); + ImGui::SliderFloat("SSAO bias", &m_SSAO_Bias, 0.0f, 0.1f); + ImGui::SliderFloat("SSAO contrast", &m_SSAO_Contrast, 0.0f, 10.0f); + ImGui::SliderFloat("SSAO IntensityScale", &m_SSAO_IntensityScale, 0.0f, 10.0f); + ImGui::SliderInt("SSAO Number of Samples", &m_SSAO_NumOfSamples, 2, 100); + ImGui::SliderInt("SSAO Number of Turns", &m_SSAO_NumOfTurns, 0, 50); + m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Contrast, m_SSAO_IntensityScale, m_SSAO_NumOfSamples, m_SSAO_NumOfTurns); //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"); m_PickingPass->ClearPicking(); m_DrawFinalPass->ClearBuffer(); m_DrawBloomPass->ClearBuffer(); - + PerformanceTimer::StopTimer("Renderer-ClearBuffers"); + for (auto scene : frame.RenderScenes) { + PerformanceTimer::StartTimer("Renderer-Depth"); + m_PickingPass->Draw(*scene); + GLERROR("Drawing pickingpass"); + PerformanceTimer::StopTimer("Renderer-Depth"); + } + PerformanceTimer::StartTimer("AO generation"); + m_SSAOPass->Draw(m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); + GLuint ao = m_SSAOPass->SSAOTexture(); + PerformanceTimer::StopTimer("AO generation"); for (auto scene : frame.RenderScenes){ + PerformanceTimer::StartTimer("Renderer-Drawing PickingPass"); SortRenderJobsByDepth(*scene); GLERROR("SortByDepth"); - m_PickingPass->Draw(*scene); - GLERROR("Drawing pickingpass"); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Generate Frustrums"); 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"); - m_DrawFinalPass->Draw(*scene); + m_DrawFinalPass->Draw(*scene, ao); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Geometry+Light"); 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(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure); + PerformanceTimer::StopTimer("Renderer-Color Correction Pass"); } + + PerformanceTimer::StartTimer("Renderer-Misc Debug Draws"); if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); } @@ -145,10 +191,16 @@ void Renderer::Draw(RenderFrame& frame) if (m_DebugTextureToDraw == 6) { m_DrawScreenQuadPass->Draw(m_PickingPass->PickingTexture()); } + if (m_DebugTextureToDraw == 7) { + m_DrawScreenQuadPass->Draw(m_SSAOPass->SSAOTexture()); + } + PerformanceTimer::StopTimer("Renderer-Misc Debug Draws"); + PerformanceTimer::StartTimer("Renderer-ImGuiRenderPass"); m_ImGuiRenderPass->Draw(); GLERROR("Imgui draw"); glfwSwapBuffers(m_Window); + PerformanceTimer::StopTimer("Renderer-ImGuiRenderPass"); } PickData Renderer::Pick(glm::vec2 screenCoord) @@ -191,4 +243,5 @@ void Renderer::InitializeRenderPasses() m_DrawScreenQuadPass = new DrawScreenQuadPass(this); m_DrawBloomPass = new DrawBloomPass(this); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); + m_SSAOPass = new SSAOPass(this); } diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp new file mode 100644 index 00000000..331e040f --- /dev/null +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -0,0 +1,141 @@ +#include "Rendering/SSAOPass.h" + +SSAOPass::SSAOPass(IRenderer* renderer) +{ + m_Renderer = renderer; + + m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); + + InitializeBuffer(); + InitializeShaderProgram(); + Setting(0.1f, 0.012f, 1.0f, 1.0f, 13, 7); + + m_DrawBloomPass = new DrawBloomPass(renderer); +} + +void SSAOPass::InitializeShaderProgram() +{ + m_SSAOProgram = ResourceManager::Load("##SSAOProgram"); + m_SSAOProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); + m_SSAOProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAO.frag.glsl"))); + m_SSAOProgram->Compile(); + m_SSAOProgram->Link(); + + m_SSAOViewSpaceZProgram = ResourceManager::Load("##SSAOViewSpaceZProgram"); + m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); + m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAOViewSpaceZ.frag.glsl"))); + m_SSAOViewSpaceZProgram->Compile(); + m_SSAOViewSpaceZProgram->Link(); +} + + +void SSAOPass::InitializeBuffer() +{ + GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R8, GL_RED, GL_FLOAT); + + m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); + m_SSAOFramBuffer.Generate(); + + GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R32F, GL_RED, GL_FLOAT); + + m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); + m_SSAOViewSpaceZFramBuffer.Generate(); +} + +void SSAOPass::ClearBuffer() +{ + m_SSAOFramBuffer.Bind(); + glClearColor(0.f, 0.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + m_SSAOFramBuffer.Unbind(); + + m_SSAOViewSpaceZFramBuffer.Bind(); + glClearColor(0.f, 0.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + m_SSAOViewSpaceZFramBuffer.Unbind(); +} + +void SSAOPass::Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns) { + m_Radius = radius; + m_Bias = bias; + m_Contrast = contrast; + m_IntensityScale = intensityScale; + m_NumOfSamples = numOfSamples; + m_NumOfTurns = NumOfTurns; +} + +void SSAOPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const +{ + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D, *texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); + glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr); + GLERROR("Texture initialization failed"); +} + +void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) +{ + 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) + );*/ + 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 * camera->ProjectionMatrix()[0][0])), + ((1.0 + camera->ProjectionMatrix()[1][2]) / camera->ProjectionMatrix()[1][1]), + (-2.0 / (m_Renderer->GetViewportSize().Height * 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 / (-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); + + m_DrawBloomPass->ClearBuffer(); + m_DrawBloomPass->Draw(m_SSAOTexture); +} + +void ComputeAO(GLuint depthBuffer, Camera* camera) { + +} \ No newline at end of file diff --git a/src/Engine/Rendering/SSAOPassState.cpp b/src/Engine/Rendering/SSAOPassState.cpp new file mode 100644 index 00000000..7dd49841 --- /dev/null +++ b/src/Engine/Rendering/SSAOPassState.cpp @@ -0,0 +1,16 @@ +#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 9c26c15c..ae536bc0 100644 --- a/src/Engine/Rendering/ShaderProgram.cpp +++ b/src/Engine/Rendering/ShaderProgram.cpp @@ -98,8 +98,7 @@ 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/Game/Game.cpp b/src/Game/Game.cpp index 49b1a963..24b7cd1e 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -26,6 +26,8 @@ #include "Network/MultiplayerSnapshotFilter.h" #include "Game/Systems/AmmunitionHUDSystem.h" #include "Game/Systems/KillFeedSystem.h" +#include "GUI/ButtonSystem.h" +#include "GUI/MainMenuSystem.h" Game::Game(int argc, char* argv[]) @@ -72,11 +74,6 @@ 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", ""); @@ -132,6 +129,8 @@ 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"); @@ -168,7 +167,6 @@ Game::~Game() delete m_NetworkServer; } delete m_World; - delete m_FrameStack; delete m_InputProxy; delete m_InputManager; delete m_RenderFrame; @@ -187,16 +185,20 @@ 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(); @@ -207,10 +209,14 @@ 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/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 7f5089c4..94f23c67 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) { + if (!IsServer && m_NetworkEnabled || !e.Victim.Valid()) { return false; } diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 5f53a1fc..6254c674 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -3,7 +3,7 @@ //This should be set by the config anyway. float PlayerSpawnSystem::m_RespawnTime = 15.0f; -PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) +PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) : System(params) , m_Timer(0.f) { @@ -49,7 +49,7 @@ void PlayerSpawnSystem::Update(double dt) } // Spawn the player! - EntityWrapper player = SpawnerSystem::Spawn(spawner); + EntityWrapper player = SpawnerSystem::Spawn(spawner, EntityWrapper::Invalid, "Player"); // Set the player team affiliation player["Team"]["Team"] = req.Team; diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index b3c556f1..90f677fe 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -1,12 +1,13 @@ #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*/) +EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent /*= EntityWrapper::Invalid*/, const std::string& dontCollideComponent) { // Spawn the entity in the parent's world if it exists, otherwise in the spawner's world World* world = parent.World; @@ -14,17 +15,41 @@ 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->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")) { - spawnPoints.push_back(EntityWrapper(spawner.World, child)); + EntityWrapper spawnPoint = EntityWrapper(spawner.World, child); + if (spawnOnCollidable || !spawnedEntityIsColliding(spawnedEntity, spawnPoint, dontCollideComponent)) { + spawnPoints.push_back(spawnPoint); + } } } // 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) { @@ -39,25 +64,61 @@ 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) { - // 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)); + transformEntityToSpawnPoint(spawnedEntity, 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/Tests/CapturePointTest.cpp b/src/Tests/CapturePointTest.cpp index 2c7bf430..8a9baf40 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); + m_SystemPipeline = new SystemPipeline(m_World,m_EventBroker, true, false); m_SystemPipeline->AddSystem(0); m_SystemPipeline->AddSystem(1); diff --git a/src/Tests/CollisionTest.cpp b/src/Tests/CollisionTest.cpp index 6cb6c88b..b5ba8245 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->m_Vertices, unitBox->m_Indices); + bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); BOOST_CHECK(hit); ray.SetDirection(glm::vec3(-1, 0, 0)); - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); 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->m_Vertices, unitBox->m_Indices); + bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices,glm::mat4(1)); if (!hit) { //if rayvsaabb hit but rayvvmodel didnt hit, we get to here - glm::vec3 outtttttttt; - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices, outtttttttt); - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + 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)); } else { hit = hit; @@ -163,7 +163,7 @@ BOOST_AUTO_TEST_CASE(rayVsModelTest2) // z = z; //} // - bool hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); ////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->m_Vertices, unitBox->m_Indices, outtttttttt); - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); } else { z = z; diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index 8bf16024..bf2650a3 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -48,26 +48,21 @@ GameHealthSystemTest::GameHealthSystemTest() fp.MergeEntities(m_World); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker); + m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker, false, false); 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"); - healthsID = playerID; + ComponentWrapper& health = m_World->AttachComponent(playerID, "Health"); + health["Health"] = 100.0; + m_PlayersID = 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; @@ -103,9 +98,18 @@ void GameHealthSystemTest::Tick() m_EventBroker->Swap(); m_EventBroker->Clear(); - - //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) + + 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) { TestSucceeded = true; + } } diff --git a/src/Tests/HealthSystemTest.h b/src/Tests/HealthSystemTest.h index 62c5f55b..685a06dd 100644 --- a/src/Tests/HealthSystemTest.h +++ b/src/Tests/HealthSystemTest.h @@ -31,7 +31,9 @@ private: EventBroker* m_EventBroker; World* m_World; SystemPipeline* m_SystemPipeline; - int healthsID; + int m_PlayersID; + bool m_TestStage1Success = false; + }; #endif diff --git a/src/Tests/PickupSpawnTest.cpp b/src/Tests/PickupSpawnTest.cpp new file mode 100644 index 00000000..4acd897e --- /dev/null +++ b/src/Tests/PickupSpawnTest.cpp @@ -0,0 +1,214 @@ +#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 new file mode 100644 index 00000000..b9d5483a --- /dev/null +++ b/src/Tests/PickupSpawnTest.h @@ -0,0 +1,72 @@ +#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 03008562..633e617a 100644 --- a/src/Tests/WorldTest.cpp +++ b/src/Tests/WorldTest.cpp @@ -69,3 +69,47 @@ 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"]); +}