diff --git a/NazaraModuleTemplate/include/Nazara/ModuleName/Config.hpp b/NazaraModuleTemplate/include/Nazara/ModuleName/Config.hpp index 7f620bb59..d311f8991 100644 --- a/NazaraModuleTemplate/include/Nazara/ModuleName/Config.hpp +++ b/NazaraModuleTemplate/include/Nazara/ModuleName/Config.hpp @@ -27,17 +27,17 @@ #ifndef NAZARA_CONFIG_MODULENAME_HPP #define NAZARA_CONFIG_MODULENAME_HPP -/// Chaque modification d'un paramètre du module nécessite une recompilation de celui-ci +/// Each modification of a parameter needs a recompilation of the module -// Utilise le MemoryManager pour gérer les allocations dynamiques (détecte les leaks au prix d'allocations/libérations dynamiques plus lentes) +// Use the MemoryManager to manage dynamic allocations (can detect memory leak but allocations/frees are slower) #define NAZARA_MODULENAME_MANAGE_MEMORY 0 -// Active les tests de sécurité basés sur le code (Conseillé pour le développement) +// Activate the security tests based on the code (Advised for development) #define NAZARA_MODULENAME_SAFE 1 -/// Chaque modification d'un paramètre ci-dessous implique une modification (souvent mineure) du code +/// Each modification of a parameter following implies a modification (often minor) of the code -/// Vérification des valeurs et types de certaines constantes +/// Checking the values and types of certain constants #include #if !defined(NAZARA_STATIC) diff --git a/NazaraModuleTemplate/include/Nazara/ModuleName/ConfigCheck.hpp b/NazaraModuleTemplate/include/Nazara/ModuleName/ConfigCheck.hpp index 8decf9091..723b9ac02 100644 --- a/NazaraModuleTemplate/include/Nazara/ModuleName/ConfigCheck.hpp +++ b/NazaraModuleTemplate/include/Nazara/ModuleName/ConfigCheck.hpp @@ -7,13 +7,13 @@ #ifndef NAZARA_CONFIG_CHECK_MODULENAME_HPP #define NAZARA_CONFIG_CHECK_MODULENAME_HPP -/// Ce fichier sert à vérifier la valeur des constantes du fichier Config.hpp +/// This file is used to check the constant values defined in Config.hpp #include #define CheckType(name, type, err) static_assert(std::is_ ##type ::value, #type err) #define CheckTypeAndVal(name, type, op, val, err) static_assert(std::is_ ##type ::value && name op val, #type err) -// On force la valeur de MANAGE_MEMORY en mode debug +// We force the value of MANAGE_MEMORY in debug #if defined(NAZARA_DEBUG) && !NAZARA_MODULENAME_MANAGE_MEMORY #undef NAZARA_MODULENAME_MANAGE_MEMORY #define NAZARA_MODULENAME_MANAGE_MEMORY 0 diff --git a/NazaraModuleTemplate/include/Nazara/ModuleName/DebugOff.hpp b/NazaraModuleTemplate/include/Nazara/ModuleName/DebugOff.hpp index 3e9cda8eb..29147254e 100644 --- a/NazaraModuleTemplate/include/Nazara/ModuleName/DebugOff.hpp +++ b/NazaraModuleTemplate/include/Nazara/ModuleName/DebugOff.hpp @@ -2,7 +2,7 @@ // This file is part of the "Nazara Engine - Module name" // For conditions of distribution and use, see copyright notice in Config.hpp -// On suppose que Debug.hpp a déjà été inclus, tout comme Config.hpp +// We suppose that Debug.hpp is already included, same goes for Config.hpp #if NAZARA_MODULENAME_MANAGE_MEMORY #undef delete #undef new diff --git a/SDK/include/NDK/Application.hpp b/SDK/include/NDK/Application.hpp index 2ada48555..3b53488e4 100644 --- a/SDK/include/NDK/Application.hpp +++ b/SDK/include/NDK/Application.hpp @@ -8,13 +8,11 @@ #define NDK_APPLICATION_HPP #include -#include #include #include #include #include #include -#include #ifndef NDK_SERVER #include @@ -22,7 +20,7 @@ #include #include #include -#include +#include #endif namespace Ndk diff --git a/SDK/include/NDK/Application.inl b/SDK/include/NDK/Application.inl index e7f074c3e..cf5160e2f 100644 --- a/SDK/include/NDK/Application.inl +++ b/SDK/include/NDK/Application.inl @@ -2,9 +2,7 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include #include -#include #include namespace Ndk diff --git a/SDK/include/NDK/BaseComponent.inl b/SDK/include/NDK/BaseComponent.inl index 0596eb589..0e27c1731 100644 --- a/SDK/include/NDK/BaseComponent.inl +++ b/SDK/include/NDK/BaseComponent.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include #include namespace Ndk diff --git a/SDK/include/NDK/BaseSystem.hpp b/SDK/include/NDK/BaseSystem.hpp index 99dcbf768..abd4081c9 100644 --- a/SDK/include/NDK/BaseSystem.hpp +++ b/SDK/include/NDK/BaseSystem.hpp @@ -8,9 +8,7 @@ #define NDK_BASESYSTEM_HPP #include -#include #include -#include namespace Ndk { @@ -35,17 +33,19 @@ namespace Ndk bool Filters(const Entity* entity) const; inline const EntityList& GetEntities() const; + inline float GetFixedUpdateRate() const; inline SystemIndex GetIndex() const; + inline float GetMaximumUpdateRate() const; inline int GetUpdateOrder() const; - inline float GetUpdateRate() const; inline World& GetWorld() const; inline bool IsEnabled() const; inline bool HasEntity(const Entity* entity) const; + inline void SetFixedUpdateRate(float updatePerSecond); + inline void SetMaximumUpdateRate(float updatePerSecond); void SetUpdateOrder(int updateOrder); - inline void SetUpdateRate(float updatePerSecond); inline void Update(float elapsedTime); @@ -93,8 +93,9 @@ namespace Ndk SystemIndex m_systemIndex; World* m_world; bool m_updateEnabled; + float m_fixedUpdateRate; + float m_maxUpdateRate; float m_updateCounter; - float m_updateRate; int m_updateOrder; static SystemIndex s_nextIndex; diff --git a/SDK/include/NDK/BaseSystem.inl b/SDK/include/NDK/BaseSystem.inl index 5969dd8e3..c537fbca1 100644 --- a/SDK/include/NDK/BaseSystem.inl +++ b/SDK/include/NDK/BaseSystem.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include #include #include @@ -20,7 +19,8 @@ namespace Ndk m_updateEnabled(true), m_updateOrder(0) { - SetUpdateRate(30); + SetFixedUpdateRate(0); + SetMaximumUpdateRate(30); } /*! @@ -34,8 +34,9 @@ namespace Ndk m_requiredComponents(system.m_requiredComponents), m_systemIndex(system.m_systemIndex), m_updateEnabled(system.m_updateEnabled), + m_fixedUpdateRate(system.m_fixedUpdateRate), + m_maxUpdateRate(system.m_maxUpdateRate), m_updateCounter(0.f), - m_updateRate(system.m_updateRate), m_updateOrder(system.m_updateOrder) { } @@ -61,6 +62,24 @@ namespace Ndk return m_entities; } + /*! + * \brief Gets the maximum rate of update of the system + * \return Update rate + */ + inline float BaseSystem::GetFixedUpdateRate() const + { + return (m_fixedUpdateRate > 0.f) ? 1.f / m_fixedUpdateRate : 0.f; + } + + /*! + * \brief Gets the maximum rate of update of the system + * \return Update rate + */ + inline float BaseSystem::GetMaximumUpdateRate() const + { + return (m_maxUpdateRate > 0.f) ? 1.f / m_maxUpdateRate : 0.f; + } + /*! * \brief Gets the index of the system * \return Index of the system @@ -82,16 +101,6 @@ namespace Ndk return m_updateOrder; } - /*! - * \brief Gets the rate of update of the system - * \return Update rate - */ - - inline float BaseSystem::GetUpdateRate() const - { - return (m_updateRate > 0.f) ? 1.f / m_updateRate : 0.f; - } - /*! * \brief Gets the world on which the system operate * \return World in which the system is @@ -125,15 +134,25 @@ namespace Ndk } /*! - * \brief Sets the rate of update for the system + * \brief Sets the fixed update rate for the system + * + * \param updatePerSecond Update rate, 0 means update rate is not fixed + */ + inline void BaseSystem::SetFixedUpdateRate(float updatePerSecond) + { + m_updateCounter = 0.f; + m_fixedUpdateRate = (updatePerSecond > 0.f) ? 1.f / updatePerSecond : 0.f; // 0.f means no limit + } + + /*! + * \brief Sets the maximum update rate for the system * * \param updatePerSecond Update rate, 0 means as much as possible */ - - inline void BaseSystem::SetUpdateRate(float updatePerSecond) + inline void BaseSystem::SetMaximumUpdateRate(float updatePerSecond) { m_updateCounter = 0.f; - m_updateRate = (updatePerSecond > 0.f) ? 1.f / updatePerSecond : 0.f; // 0.f means no limit + m_maxUpdateRate = (updatePerSecond > 0.f) ? 1.f / updatePerSecond : 0.f; // 0.f means no limit } /*! @@ -147,18 +166,40 @@ namespace Ndk if (!IsEnabled()) return; - if (m_updateRate > 0.f) - { - m_updateCounter += elapsedTime; + m_updateCounter += elapsedTime; - while (m_updateCounter >= m_updateRate) + if (m_maxUpdateRate > 0.f) + { + if (m_updateCounter >= m_maxUpdateRate) { - OnUpdate(m_updateRate); - m_updateCounter -= m_updateRate; + if (m_fixedUpdateRate > 0.f) + { + while (m_updateCounter >= m_fixedUpdateRate) + { + OnUpdate(m_fixedUpdateRate); + m_updateCounter -= m_fixedUpdateRate; + } + } + else + { + OnUpdate(m_maxUpdateRate); + m_updateCounter -= m_maxUpdateRate; + } } } else - OnUpdate(elapsedTime); + { + if (m_fixedUpdateRate > 0.f) + { + while (m_updateCounter >= m_fixedUpdateRate) + { + OnUpdate(m_fixedUpdateRate); + m_updateCounter -= m_fixedUpdateRate; + } + } + else + OnUpdate(elapsedTime); + } } /*! diff --git a/SDK/include/NDK/BaseWidget.hpp b/SDK/include/NDK/BaseWidget.hpp index 723e93e80..2494f37f4 100644 --- a/SDK/include/NDK/BaseWidget.hpp +++ b/SDK/include/NDK/BaseWidget.hpp @@ -12,9 +12,8 @@ #include #include #include -#include -#include -#include +#include +#include #include #include @@ -38,6 +37,8 @@ namespace Ndk inline void AddChild(std::unique_ptr&& widget); inline void Center(); + inline void CenterHorizontal(); + inline void CenterVertical(); inline void Destroy(); diff --git a/SDK/include/NDK/BaseWidget.inl b/SDK/include/NDK/BaseWidget.inl index e84a67a49..948769890 100644 --- a/SDK/include/NDK/BaseWidget.inl +++ b/SDK/include/NDK/BaseWidget.inl @@ -46,6 +46,24 @@ namespace Ndk SetPosition((parentSize.x - mySize.x) / 2.f, (parentSize.y - mySize.y) / 2.f); } + inline void BaseWidget::CenterHorizontal() + { + NazaraAssert(m_widgetParent, "Widget has no parent"); + + Nz::Vector2f parentSize = m_widgetParent->GetSize(); + Nz::Vector2f mySize = GetSize(); + SetPosition((parentSize.x - mySize.x) / 2.f, GetPosition(Nz::CoordSys_Local).y); + } + + inline void BaseWidget::CenterVertical() + { + NazaraAssert(m_widgetParent, "Widget has no parent"); + + Nz::Vector2f parentSize = m_widgetParent->GetSize(); + Nz::Vector2f mySize = GetSize(); + SetPosition(GetPosition(Nz::CoordSys_Local).x, (parentSize.y - mySize.y) / 2.f); + } + inline const Nz::Color& BaseWidget::GetBackgroundColor() const { return m_backgroundColor; diff --git a/SDK/include/NDK/Canvas.hpp b/SDK/include/NDK/Canvas.hpp index 0cc314b73..f37ad3cda 100644 --- a/SDK/include/NDK/Canvas.hpp +++ b/SDK/include/NDK/Canvas.hpp @@ -9,8 +9,8 @@ #include #include -#include -#include +#include +#include namespace Ndk { @@ -44,13 +44,13 @@ namespace Ndk void UnregisterWidget(std::size_t index); private: - void OnMouseButtonPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event); - void OnMouseButtonRelease(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event); - void OnMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event); - void OnMouseLeft(const Nz::EventHandler* eventHandler); - void OnKeyPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event); - void OnKeyReleased(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event); - void OnTextEntered(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::TextEvent& event); + void OnEventMouseButtonPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event); + void OnEventMouseButtonRelease(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event); + void OnEventMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event); + void OnEventMouseLeft(const Nz::EventHandler* eventHandler); + void OnEventKeyPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event); + void OnEventKeyReleased(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event); + void OnEventTextEntered(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::TextEvent& event); struct WidgetBox { diff --git a/SDK/include/NDK/Canvas.inl b/SDK/include/NDK/Canvas.inl index 3dd5de87f..f3a8dea88 100644 --- a/SDK/include/NDK/Canvas.inl +++ b/SDK/include/NDK/Canvas.inl @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include -#include +#include namespace Ndk { @@ -20,13 +20,13 @@ namespace Ndk RegisterToCanvas(); // Connect to every meaningful event - m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, this, &Canvas::OnKeyPressed); - m_keyReleasedSlot.Connect(eventHandler.OnKeyReleased, this, &Canvas::OnKeyReleased); - m_mouseButtonPressedSlot.Connect(eventHandler.OnMouseButtonPressed, this, &Canvas::OnMouseButtonPressed); - m_mouseButtonReleasedSlot.Connect(eventHandler.OnMouseButtonReleased, this, &Canvas::OnMouseButtonRelease); - m_mouseMovedSlot.Connect(eventHandler.OnMouseMoved, this, &Canvas::OnMouseMoved); - m_mouseLeftSlot.Connect(eventHandler.OnMouseLeft, this, &Canvas::OnMouseLeft); - m_textEnteredSlot.Connect(eventHandler.OnTextEntered, this, &Canvas::OnTextEntered); + m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, this, &Canvas::OnEventKeyPressed); + m_keyReleasedSlot.Connect(eventHandler.OnKeyReleased, this, &Canvas::OnEventKeyReleased); + m_mouseButtonPressedSlot.Connect(eventHandler.OnMouseButtonPressed, this, &Canvas::OnEventMouseButtonPressed); + m_mouseButtonReleasedSlot.Connect(eventHandler.OnMouseButtonReleased, this, &Canvas::OnEventMouseButtonRelease); + m_mouseMovedSlot.Connect(eventHandler.OnMouseMoved, this, &Canvas::OnEventMouseMoved); + m_mouseLeftSlot.Connect(eventHandler.OnMouseLeft, this, &Canvas::OnEventMouseLeft); + m_textEnteredSlot.Connect(eventHandler.OnTextEntered, this, &Canvas::OnEventTextEntered); // Disable padding by default SetPadding(0.f, 0.f, 0.f, 0.f); diff --git a/SDK/include/NDK/Components/CameraComponent.hpp b/SDK/include/NDK/Components/CameraComponent.hpp index f4a29f2e4..2474a093e 100644 --- a/SDK/include/NDK/Components/CameraComponent.hpp +++ b/SDK/include/NDK/Components/CameraComponent.hpp @@ -19,7 +19,6 @@ namespace Ndk { class CameraComponent; - class Entity; using CameraComponentHandle = Nz::ObjectHandle; diff --git a/SDK/include/NDK/Components/CameraComponent.inl b/SDK/include/NDK/Components/CameraComponent.inl index 1018f9f3d..14e76176a 100644 --- a/SDK/include/NDK/Components/CameraComponent.inl +++ b/SDK/include/NDK/Components/CameraComponent.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include #include #include diff --git a/SDK/include/NDK/Components/CollisionComponent2D.hpp b/SDK/include/NDK/Components/CollisionComponent2D.hpp index 28c3637a2..524097e32 100644 --- a/SDK/include/NDK/Components/CollisionComponent2D.hpp +++ b/SDK/include/NDK/Components/CollisionComponent2D.hpp @@ -8,18 +8,12 @@ #define NDK_COMPONENTS_COLLISIONCOMPONENT2D_HPP #include +#include #include #include -namespace Nz -{ - class RigidBody2D; -} - namespace Ndk { - class Entity; - class NDK_API CollisionComponent2D : public Component { friend class PhysicsSystem2D; @@ -29,6 +23,7 @@ namespace Ndk CollisionComponent2D(const CollisionComponent2D& collision); ~CollisionComponent2D() = default; + Nz::Rectf GetAABB() const; const Nz::Collider2DRef& GetGeom() const; void SetGeom(Nz::Collider2DRef geom); diff --git a/SDK/include/NDK/Components/CollisionComponent2D.inl b/SDK/include/NDK/Components/CollisionComponent2D.inl index 147e8ec32..f3728de84 100644 --- a/SDK/include/NDK/Components/CollisionComponent2D.inl +++ b/SDK/include/NDK/Components/CollisionComponent2D.inl @@ -2,12 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include -#include -#include -#include -#include - namespace Ndk { /*! @@ -34,6 +28,16 @@ namespace Ndk { } + /*! + * \brief Gets the collision box representing the entity + * \return The physics collision box + */ + + inline Nz::Rectf CollisionComponent2D::GetAABB() const + { + return m_staticBody->GetAABB(); + } + /*! * \brief Gets the geometry representing the entity * \return A constant reference to the physics geometry diff --git a/SDK/include/NDK/Components/CollisionComponent3D.hpp b/SDK/include/NDK/Components/CollisionComponent3D.hpp index 992e73053..ce1b719ca 100644 --- a/SDK/include/NDK/Components/CollisionComponent3D.hpp +++ b/SDK/include/NDK/Components/CollisionComponent3D.hpp @@ -8,18 +8,12 @@ #define NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP #include +#include #include #include -namespace Nz -{ - class RigidBody3D; -} - namespace Ndk { - class Entity; - class NDK_API CollisionComponent3D : public Component { friend class PhysicsSystem3D; diff --git a/SDK/include/NDK/Components/CollisionComponent3D.inl b/SDK/include/NDK/Components/CollisionComponent3D.inl index 7d82252af..69842c867 100644 --- a/SDK/include/NDK/Components/CollisionComponent3D.inl +++ b/SDK/include/NDK/Components/CollisionComponent3D.inl @@ -2,11 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include -#include -#include -#include - namespace Ndk { /*! diff --git a/SDK/include/NDK/Components/ParticleEmitterComponent.hpp b/SDK/include/NDK/Components/ParticleEmitterComponent.hpp index dd40f7aaa..d89d9114f 100644 --- a/SDK/include/NDK/Components/ParticleEmitterComponent.hpp +++ b/SDK/include/NDK/Components/ParticleEmitterComponent.hpp @@ -9,7 +9,6 @@ #define NDK_COMPONENTS_PARTICLEEMITTERCOMPONENT_HPP #include -#include #include namespace Ndk @@ -24,7 +23,7 @@ namespace Ndk ParticleEmitterComponent(ParticleEmitterComponent&& emitter) = default; ~ParticleEmitterComponent() = default; - void Enable(bool active = true); + inline void Enable(bool active = true); inline bool IsActive() const; diff --git a/SDK/include/NDK/Components/ParticleEmitterComponent.inl b/SDK/include/NDK/Components/ParticleEmitterComponent.inl index 292a2ed8f..47c3602ab 100644 --- a/SDK/include/NDK/Components/ParticleEmitterComponent.inl +++ b/SDK/include/NDK/Components/ParticleEmitterComponent.inl @@ -2,8 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include - namespace Ndk { /*! diff --git a/SDK/include/NDK/Components/ParticleGroupComponent.inl b/SDK/include/NDK/Components/ParticleGroupComponent.inl index dc3072faa..afbfc15da 100644 --- a/SDK/include/NDK/Components/ParticleGroupComponent.inl +++ b/SDK/include/NDK/Components/ParticleGroupComponent.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include #include #include diff --git a/SDK/include/NDK/Components/PhysicsComponent2D.hpp b/SDK/include/NDK/Components/PhysicsComponent2D.hpp index 2bbe693a1..e43b87814 100644 --- a/SDK/include/NDK/Components/PhysicsComponent2D.hpp +++ b/SDK/include/NDK/Components/PhysicsComponent2D.hpp @@ -13,8 +13,6 @@ namespace Ndk { - class Entity; - class NDK_API PhysicsComponent2D : public Component { friend class CollisionComponent2D; diff --git a/SDK/include/NDK/Components/PhysicsComponent2D.inl b/SDK/include/NDK/Components/PhysicsComponent2D.inl index 7aea6dca6..5d1b23110 100644 --- a/SDK/include/NDK/Components/PhysicsComponent2D.inl +++ b/SDK/include/NDK/Components/PhysicsComponent2D.inl @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include -#include "PhysicsComponent2D.hpp" namespace Ndk { diff --git a/SDK/include/NDK/Components/PhysicsComponent3D.hpp b/SDK/include/NDK/Components/PhysicsComponent3D.hpp index 8be86537e..610b8e1df 100644 --- a/SDK/include/NDK/Components/PhysicsComponent3D.hpp +++ b/SDK/include/NDK/Components/PhysicsComponent3D.hpp @@ -13,8 +13,6 @@ namespace Ndk { - class Entity; - class NDK_API PhysicsComponent3D : public Component { friend class CollisionComponent3D; diff --git a/SDK/include/NDK/Components/VelocityComponent.inl b/SDK/include/NDK/Components/VelocityComponent.inl index 2cf4f1ec3..052985ddf 100644 --- a/SDK/include/NDK/Components/VelocityComponent.inl +++ b/SDK/include/NDK/Components/VelocityComponent.inl @@ -2,9 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include -#include - namespace Ndk { /*! diff --git a/SDK/include/NDK/Console.hpp b/SDK/include/NDK/Console.hpp index 9635373e0..afe4b156e 100644 --- a/SDK/include/NDK/Console.hpp +++ b/SDK/include/NDK/Console.hpp @@ -12,7 +12,6 @@ #include #include #include -#include #include #include #include @@ -20,12 +19,12 @@ namespace Nz { class LuaState; + struct WindowEvent; } namespace Ndk { class Console; - class Entity; using ConsoleHandle = Nz::ObjectHandle; diff --git a/SDK/include/NDK/Console.inl b/SDK/include/NDK/Console.inl index c97adda20..fd461905f 100644 --- a/SDK/include/NDK/Console.inl +++ b/SDK/include/NDK/Console.inl @@ -2,9 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include -#include "Console.hpp" - namespace Ndk { /*! diff --git a/SDK/include/NDK/Entity.hpp b/SDK/include/NDK/Entity.hpp index 5419da0d2..3009d1151 100644 --- a/SDK/include/NDK/Entity.hpp +++ b/SDK/include/NDK/Entity.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include diff --git a/SDK/include/NDK/Entity.inl b/SDK/include/NDK/Entity.inl index adb2153d8..89dcf9ae2 100644 --- a/SDK/include/NDK/Entity.inl +++ b/SDK/include/NDK/Entity.inl @@ -2,13 +2,11 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include #include #include #include #include #include -#include namespace Ndk { diff --git a/SDK/include/NDK/EntityList.hpp b/SDK/include/NDK/EntityList.hpp index 8303f7fa4..4620837a0 100644 --- a/SDK/include/NDK/EntityList.hpp +++ b/SDK/include/NDK/EntityList.hpp @@ -35,6 +35,7 @@ namespace Ndk inline void Insert(Entity* entity); inline void Remove(Entity* entity); + inline void Reserve(std::size_t entityCount); // STL API inline iterator begin() const; diff --git a/SDK/include/NDK/EntityList.inl b/SDK/include/NDK/EntityList.inl index 8d871e2c6..a56eafa24 100644 --- a/SDK/include/NDK/EntityList.inl +++ b/SDK/include/NDK/EntityList.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include #include #include @@ -137,6 +136,16 @@ namespace Ndk } } + /*! + * \brief Reserves enough space to contains entityCount entities + * + * \param entityCount Number of entities to reserve + */ + inline void EntityList::Reserve(std::size_t entityCount) + { + m_entityBits.Reserve(entityCount); + } + // STL Interface inline EntityList::iterator EntityList::begin() const { diff --git a/SDK/include/NDK/Lua/LuaBinding.hpp b/SDK/include/NDK/Lua/LuaBinding.hpp index c1ea9206d..c93f21a42 100644 --- a/SDK/include/NDK/Lua/LuaBinding.hpp +++ b/SDK/include/NDK/Lua/LuaBinding.hpp @@ -7,7 +7,6 @@ #ifndef NDK_LUABINDING_HPP #define NDK_LUABINDING_HPP -#include #include #include #include @@ -36,6 +35,7 @@ namespace Ndk std::unique_ptr audio; std::unique_ptr graphics; std::unique_ptr renderer; + std::unique_ptr platform; #endif private: diff --git a/SDK/include/NDK/Lua/LuaBinding.inl b/SDK/include/NDK/Lua/LuaBinding.inl index 502f179ae..c7fb53ed4 100644 --- a/SDK/include/NDK/Lua/LuaBinding.inl +++ b/SDK/include/NDK/Lua/LuaBinding.inl @@ -2,10 +2,37 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include - namespace Ndk { + namespace Detail + { + template + struct AddComponentIf; + + template<> + struct AddComponentIf + { + template + static int AddComponent(Nz::LuaState& lua, EntityHandle& handle) + { + T& component = handle->AddComponent(); + lua.Push(component.CreateHandle()); + return 1; + } + }; + + template<> + struct AddComponentIf + { + template + static int AddComponent(Nz::LuaState& lua, EntityHandle& /*handle*/) + { + lua.Error("Component has no default constructor and cannot be created from Lua yet"); + return 0; + } + }; + } + /*! * \brief Binds a component to a name * @@ -13,14 +40,15 @@ namespace Ndk * * \remark Produces a NazaraAssert if name is empty */ - template void LuaBinding::BindComponent(const Nz::String& name) { NazaraAssert(!name.IsEmpty(), "Component name cannot be empty"); + static_assert(std::is_base_of::value, "ComponentType must inherit BaseComponent"); + ComponentBinding binding; - binding.adder = &AddComponentOfType; + binding.adder = &Detail::AddComponentIf::value>::template AddComponent; binding.getter = &PushComponentOfType; binding.index = T::componentIndex; binding.name = name; @@ -32,21 +60,9 @@ namespace Ndk m_componentBindingByName[name] = T::componentIndex; } - template - int LuaBinding::AddComponentOfType(Nz::LuaState& lua, EntityHandle& handle) - { - static_assert(std::is_base_of::value, "ComponentType must inherit BaseComponent"); - - T& component = handle->AddComponent(); - lua.Push(component.CreateHandle()); - return 1; - } - template int LuaBinding::PushComponentOfType(Nz::LuaState& lua, BaseComponent& component) { - static_assert(std::is_base_of::value, "ComponentType must inherit BaseComponent"); - T& rightComponent = static_cast(component); lua.Push(rightComponent.CreateHandle()); return 1; diff --git a/SDK/include/NDK/Lua/LuaBinding_Base.hpp b/SDK/include/NDK/Lua/LuaBinding_Base.hpp index 8e596e999..21d86f191 100644 --- a/SDK/include/NDK/Lua/LuaBinding_Base.hpp +++ b/SDK/include/NDK/Lua/LuaBinding_Base.hpp @@ -23,6 +23,7 @@ namespace Ndk class LuaBinding_Renderer; class LuaBinding_SDK; class LuaBinding_Utility; + class LuaBinding_Platform; class NDK_API LuaBinding_Base { @@ -43,6 +44,7 @@ namespace Ndk static std::unique_ptr BindAudio(LuaBinding& binding); static std::unique_ptr BindGraphics(LuaBinding& binding); static std::unique_ptr BindRenderer(LuaBinding& binding); + static std::unique_ptr BindPlatform(LuaBinding& binding); #endif protected: diff --git a/SDK/include/NDK/Lua/LuaBinding_Platform.hpp b/SDK/include/NDK/Lua/LuaBinding_Platform.hpp new file mode 100644 index 000000000..502a443a5 --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding_Platform.hpp @@ -0,0 +1,28 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequesites.hpp + +#pragma once + +#ifndef NDK_LUABINDING_SYSTEM_HPP +#define NDK_LUABINDING_SYSTEM_HPP + +#include +#include + +namespace Ndk +{ + class NDK_API LuaBinding_Platform : public LuaBinding_Base + { + public: + LuaBinding_Platform(LuaBinding& binding); + ~LuaBinding_Platform() = default; + + void Register(Nz::LuaState& state) override; + + // Platform + Nz::LuaClass keyboard; + }; +} + +#endif // NDK_LUABINDING_SYSTEM_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_SDK.hpp b/SDK/include/NDK/Lua/LuaBinding_SDK.hpp index 8a6a0915e..18cbe96c2 100644 --- a/SDK/include/NDK/Lua/LuaBinding_SDK.hpp +++ b/SDK/include/NDK/Lua/LuaBinding_SDK.hpp @@ -11,6 +11,7 @@ #include #include #include +#include namespace Ndk { diff --git a/SDK/include/NDK/Lua/LuaBinding_Utility.hpp b/SDK/include/NDK/Lua/LuaBinding_Utility.hpp index 8aefd20c6..33f19184d 100644 --- a/SDK/include/NDK/Lua/LuaBinding_Utility.hpp +++ b/SDK/include/NDK/Lua/LuaBinding_Utility.hpp @@ -9,7 +9,6 @@ #include #include -#include #include #include @@ -26,7 +25,6 @@ namespace Ndk // Utility Nz::LuaClass abstractImage; Nz::LuaClass font; - Nz::LuaClass keyboard; Nz::LuaClass node; }; } diff --git a/SDK/include/NDK/LuaAPI.inl b/SDK/include/NDK/LuaAPI.inl index 84e3fb34e..1f9780200 100644 --- a/SDK/include/NDK/LuaAPI.inl +++ b/SDK/include/NDK/LuaAPI.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp -#include #include #include #include @@ -16,7 +15,6 @@ #include #include #include -#include #ifndef NDK_SERVER #include diff --git a/SDK/include/NDK/Systems/RenderSystem.hpp b/SDK/include/NDK/Systems/RenderSystem.hpp index a74cb9d0e..1ff5cedde 100644 --- a/SDK/include/NDK/Systems/RenderSystem.hpp +++ b/SDK/include/NDK/Systems/RenderSystem.hpp @@ -11,16 +11,16 @@ #include #include #include -#include #include -#include #include #include -#include +#include #include namespace Ndk { + class AbstractViewer; + class NDK_API RenderSystem : public System { public: diff --git a/SDK/include/NDK/Widgets.hpp b/SDK/include/NDK/Widgets.hpp index a019c007b..2c3ba7dad 100644 --- a/SDK/include/NDK/Widgets.hpp +++ b/SDK/include/NDK/Widgets.hpp @@ -6,7 +6,9 @@ #define NDK_WIDGETS_GLOBAL_HPP #include +#include #include +#include #include #endif // NDK_WIDGETS_GLOBAL_HPP diff --git a/SDK/include/NDK/Widgets/ButtonWidget.hpp b/SDK/include/NDK/Widgets/ButtonWidget.hpp index 8f2231501..6214c8599 100644 --- a/SDK/include/NDK/Widgets/ButtonWidget.hpp +++ b/SDK/include/NDK/Widgets/ButtonWidget.hpp @@ -9,14 +9,17 @@ #include #include -#include +#include #include #include +namespace Nz +{ + class AbstractTextDrawer; +} + namespace Ndk { - class World; - class NDK_API ButtonWidget : public BaseWidget { public: @@ -29,17 +32,44 @@ namespace Ndk void ResizeToContent() override; + inline const Nz::Color& GetColor() const; + inline const Nz::Color& GetCornerColor() const; + inline const Nz::Color& GetHoverColor() const; + inline const Nz::Color& GetHoverCornerColor() const; + inline const Nz::Color& GetPressColor() const; + inline const Nz::Color& GetPressCornerColor() const; + + inline const Nz::TextureRef& GetTexture() const; + inline const Nz::TextureRef& GetHoverTexture() const; + inline const Nz::TextureRef& GetPressTexture() const; + + inline void SetColor(const Nz::Color& color, const Nz::Color& cornerColor); + inline void SetHoverColor(const Nz::Color& color, const Nz::Color& cornerColor); + inline void SetPressColor(const Nz::Color& color, const Nz::Color& cornerColor); + + inline void SetTexture(const Nz::TextureRef& texture); + inline void SetHoverTexture(const Nz::TextureRef& texture); + inline void SetPressTexture(const Nz::TextureRef& texture); + inline void UpdateText(const Nz::AbstractTextDrawer& drawer); ButtonWidget& operator=(const ButtonWidget&) = delete; ButtonWidget& operator=(ButtonWidget&&) = default; + static const Nz::Color& GetDefaultColor(); + static const Nz::Color& GetDefaultCornerColor(); + static const Nz::Color& GetDefaultHoverColor(); + static const Nz::Color& GetDefaultHoverCornerColor(); + static const Nz::Color& GetDefaultPressColor(); + static const Nz::Color& GetDefaultPressCornerColor(); + NazaraSignal(OnButtonTrigger, const ButtonWidget* /*button*/); private: void Layout() override; void OnMouseEnter() override; + void OnMouseButtonPress(int x, int y, Nz::Mouse::Button button) override; void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) override; void OnMouseExit() override; @@ -47,6 +77,24 @@ namespace Ndk EntityHandle m_gradientEntity; Nz::SpriteRef m_gradientSprite; Nz::TextSpriteRef m_textSprite; + + Nz::Color m_color; + Nz::Color m_cornerColor; + Nz::Color m_hoverColor; + Nz::Color m_hoverCornerColor; + Nz::Color m_pressColor; + Nz::Color m_pressCornerColor; + + Nz::TextureRef m_texture; + Nz::TextureRef m_hoverTexture; + Nz::TextureRef m_pressTexture; + + static Nz::Color s_color; + static Nz::Color s_cornerColor; + static Nz::Color s_hoverColor; + static Nz::Color s_hoverCornerColor; + static Nz::Color s_pressColor; + static Nz::Color s_pressCornerColor; }; } diff --git a/SDK/include/NDK/Widgets/ButtonWidget.inl b/SDK/include/NDK/Widgets/ButtonWidget.inl index fedc7614a..68df431bd 100644 --- a/SDK/include/NDK/Widgets/ButtonWidget.inl +++ b/SDK/include/NDK/Widgets/ButtonWidget.inl @@ -6,8 +6,93 @@ namespace Ndk { + inline const Nz::Color& ButtonWidget::GetColor() const + { + return m_color; + } + + inline const Nz::Color& ButtonWidget::GetCornerColor() const + { + return m_cornerColor; + } + + inline const Nz::Color& ButtonWidget::GetHoverColor() const + { + return m_hoverColor; + } + + inline const Nz::Color& ButtonWidget::GetHoverCornerColor() const + { + return m_hoverCornerColor; + } + + inline const Nz::Color& ButtonWidget::GetPressColor() const + { + return m_pressColor; + } + + inline const Nz::Color& ButtonWidget::GetPressCornerColor() const + { + return m_pressCornerColor; + } + + inline const Nz::TextureRef& ButtonWidget::GetTexture() const + { + return m_texture; + } + + inline const Nz::TextureRef& ButtonWidget::GetHoverTexture() const + { + return m_hoverTexture; + } + + inline const Nz::TextureRef& ButtonWidget::GetPressTexture() const + { + return m_pressTexture; + } + + inline void ButtonWidget::SetColor(const Nz::Color& color, const Nz::Color& cornerColor) + { + m_color = color; + m_cornerColor = cornerColor; + + m_gradientSprite->SetColor(m_color); + m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_cornerColor); + m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_cornerColor); + } + + inline void ButtonWidget::SetHoverColor(const Nz::Color& color, const Nz::Color& cornerColor) + { + m_hoverColor = color; + m_hoverCornerColor = cornerColor; + } + + inline void ButtonWidget::SetPressColor(const Nz::Color& color, const Nz::Color& cornerColor) + { + m_pressColor = color; + m_pressCornerColor = cornerColor; + } + + inline void ButtonWidget::SetTexture(const Nz::TextureRef& texture) + { + m_texture = texture; + m_gradientSprite->SetTexture(m_texture); + } + + inline void ButtonWidget::SetHoverTexture(const Nz::TextureRef& texture) + { + m_hoverTexture = texture; + } + + inline void ButtonWidget::SetPressTexture(const Nz::TextureRef& texture) + { + m_pressTexture = texture; + } + inline void ButtonWidget::UpdateText(const Nz::AbstractTextDrawer& drawer) { m_textSprite->Update(drawer); + + Layout(); } } diff --git a/SDK/include/NDK/Widgets/CheckboxWidget.hpp b/SDK/include/NDK/Widgets/CheckboxWidget.hpp new file mode 100644 index 000000000..1659199d6 --- /dev/null +++ b/SDK/include/NDK/Widgets/CheckboxWidget.hpp @@ -0,0 +1,105 @@ +// Copyright (C) 2017 Samy Bensaid +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequesites.hpp + +#pragma once + +#ifndef NDK_WIDGETS_CHECKBOXWIDGET_HPP +#define NDK_WIDGETS_CHECKBOXWIDGET_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Nz +{ + class AbstractTextDrawer; +} + +namespace Ndk +{ + class NDK_API CheckboxWidget : public BaseWidget + { + friend class Sdk; + + public: + CheckboxWidget(BaseWidget* parent = nullptr); + CheckboxWidget(const CheckboxWidget&) = delete; + CheckboxWidget(CheckboxWidget&&) = default; + ~CheckboxWidget() = default; + + //virtual CheckboxWidget* Clone() const = 0; + + inline void EnableAdaptativeMargin(bool enable = true); + inline void EnableCheckbox(bool enable = true); + inline void EnableTristate(bool enable = true); + + inline bool IsCheckboxEnabled() const; + inline bool IsMarginAdaptative() const; + inline bool IsTristateEnabled() const; + + inline const Nz::Vector2f& GetCheckboxSize() const; + inline Nz::Vector2f GetCheckboxBorderSize() const; + inline CheckboxState GetState() const; + inline float GetTextMargin() const; + + inline void SetCheckboxSize(const Nz::Vector2f& size); + CheckboxState SwitchToNextState(); + void SetState(CheckboxState state); + inline void SetTextMargin(float margin); + + void ResizeToContent() override; + inline void UpdateText(const Nz::AbstractTextDrawer& drawer); + + + CheckboxWidget& operator=(const CheckboxWidget&) = delete; + CheckboxWidget& operator=(CheckboxWidget&&) = default; + + NazaraSignal(OnStateChanged, const CheckboxWidget* /*checkbox*/); + + private: + static bool Initialize(); + static void Uninitialize(); + + void Layout() override; + void UpdateCheckbox(); + + void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) override; + inline bool ContainsCheckbox(int x, int y) const; + + + EntityHandle m_checkboxBorderEntity; + EntityHandle m_checkboxBackgroundEntity; + EntityHandle m_checkboxContentEntity; + EntityHandle m_textEntity; + + Nz::TextureRef m_checkMark; + + Nz::SpriteRef m_checkboxContentSprite; + Nz::SpriteRef m_checkboxBorderSprite; + Nz::SpriteRef m_checkboxBackgroundSprite; + Nz::TextSpriteRef m_textSprite; + + static Nz::Color s_backgroundColor; + static Nz::Color s_disabledBackgroundColor; + static Nz::Color s_disabledBorderColor; + static Nz::Color s_borderColor; + + bool m_adaptativeMargin; + bool m_checkboxEnabled; + bool m_tristateEnabled; + + static float s_borderScale; + float m_textMargin; + CheckboxState m_state; + }; +} + +#include + +#endif // NDK_WIDGETS_CHECKBOXWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/CheckboxWidget.inl b/SDK/include/NDK/Widgets/CheckboxWidget.inl new file mode 100644 index 000000000..cb20a1c0c --- /dev/null +++ b/SDK/include/NDK/Widgets/CheckboxWidget.inl @@ -0,0 +1,91 @@ +// Copyright (C) 2017 Samy Bensaid +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequesites.hpp + +namespace Ndk +{ + inline void CheckboxWidget::EnableAdaptativeMargin(bool enable) + { + m_adaptativeMargin = enable; + Layout(); + } + + inline void CheckboxWidget::EnableCheckbox(bool enable) + { + m_checkboxEnabled = enable; + UpdateCheckbox(); + } + + inline void CheckboxWidget::EnableTristate(bool enable) + { + m_tristateEnabled = enable; + + if (m_tristateEnabled && GetState() == CheckboxState_Tristate) + SetState(CheckboxState_Unchecked); + } + + inline bool CheckboxWidget::IsCheckboxEnabled() const + { + return m_checkboxEnabled; + } + + inline bool CheckboxWidget::IsMarginAdaptative() const + { + return m_adaptativeMargin; + } + + inline bool CheckboxWidget::IsTristateEnabled() const + { + return m_tristateEnabled; + } + + inline const Nz::Vector2f& CheckboxWidget::GetCheckboxSize() const + { + return m_checkboxBorderSprite->GetSize(); + } + + inline Nz::Vector2f CheckboxWidget::GetCheckboxBorderSize() const + { + return GetCheckboxSize() / s_borderScale; + } + + inline CheckboxState CheckboxWidget::GetState() const + { + return m_state; + } + + inline float CheckboxWidget::GetTextMargin() const + { + return m_textMargin; + } + + inline void CheckboxWidget::SetCheckboxSize(const Nz::Vector2f& size) + { + m_checkboxBorderSprite->SetSize(size); + m_checkboxBackgroundSprite->SetSize(size - GetCheckboxBorderSize() * 2.f); + m_checkboxContentSprite->SetSize(GetCheckboxSize() - GetCheckboxBorderSize() * 2.f - Nz::Vector2f { 4.f, 4.f }); + + Layout(); + } + + inline void CheckboxWidget::SetTextMargin(float margin) + { + m_textMargin = margin; + Layout(); + } + + inline void CheckboxWidget::UpdateText(const Nz::AbstractTextDrawer& drawer) + { + m_textSprite->Update(drawer); + Layout(); + } + + inline bool CheckboxWidget::ContainsCheckbox(int x, int y) const + { + Nz::Vector2f checkboxSize = GetCheckboxSize(); + Nz::Vector3f pos = m_checkboxBorderEntity->GetComponent().GetPosition(Nz::CoordSys_Local); + + return x > pos.x && x < pos.x + checkboxSize.x && + y > pos.y && y < pos.y + checkboxSize.y; + } +} diff --git a/SDK/include/NDK/Widgets/Enums.hpp b/SDK/include/NDK/Widgets/Enums.hpp new file mode 100644 index 000000000..38891e3d5 --- /dev/null +++ b/SDK/include/NDK/Widgets/Enums.hpp @@ -0,0 +1,22 @@ +// Copyright (C) 2017 Samy Bensaid +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequesites.hpp + +#pragma once + +#ifndef NAZARA_ENUMS_SDK_HPP +#define NAZARA_ENUMS_SDK_HPP + +namespace Ndk +{ + enum CheckboxState + { + CheckboxState_Checked, + CheckboxState_Tristate, + CheckboxState_Unchecked, + + CheckboxState_Max = CheckboxState_Unchecked + }; +} + +#endif // NAZARA_ENUMS_SDK_HPP diff --git a/SDK/include/NDK/Widgets/LabelWidget.hpp b/SDK/include/NDK/Widgets/LabelWidget.hpp index 06f53273c..afad46f3c 100644 --- a/SDK/include/NDK/Widgets/LabelWidget.hpp +++ b/SDK/include/NDK/Widgets/LabelWidget.hpp @@ -9,13 +9,15 @@ #include #include -#include #include +namespace Nz +{ + class AbstractTextDrawer; +} + namespace Ndk { - class World; - class NDK_API LabelWidget : public BaseWidget { public: diff --git a/SDK/include/NDK/Widgets/ProgressBarWidget.hpp b/SDK/include/NDK/Widgets/ProgressBarWidget.hpp new file mode 100644 index 000000000..f8399ca6c --- /dev/null +++ b/SDK/include/NDK/Widgets/ProgressBarWidget.hpp @@ -0,0 +1,103 @@ +// Copyright (C) 2017 Samy Bensaid +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequesites.hpp + +#pragma once + +#ifndef NDK_WIDGETS_PROGRESSBARWIDGET_HPP +#define NDK_WIDGETS_PROGRESSBARWIDGET_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Ndk +{ + class NDK_API ProgressBarWidget : public BaseWidget + { + friend class Sdk; + + public: + ProgressBarWidget(BaseWidget* parent = nullptr); + ProgressBarWidget(const ProgressBarWidget&) = delete; + ProgressBarWidget(ProgressBarWidget&&) = default; + ~ProgressBarWidget() = default; + + //virtual ProgressBarWidget* Clone() const = 0; + + inline void EnableText(bool enable = true); + inline void EnableBorder(bool enable = true); + + inline bool IsTextEnabled() const; + inline bool IsBorderEnabled() const; + + + inline unsigned GetPercentageValue() const; + inline Nz::Vector2f GetProgressBarSize() const; + inline Nz::Vector2f GetProgressBarBorderSize() const; + inline float GetTextMargin() const; + + + inline const Nz::Color& GetBarBackgroundColor() const; + inline const Nz::Color& GetBarBackgroundCornerColor() const; + inline const Nz::Color& GetBarColor() const; + inline const Nz::Color& GetBarCornerColor() const; + + inline const Nz::TextureRef& GetBarBackgroundTexture() const; + inline const Nz::TextureRef& GetBarTexture() const; + + static const Nz::Color& GetDefaultBarColor(); + static const Nz::Color& GetDefaultBarCornerColor(); + static const Nz::Color& GetDefaultBarBackgroundColor(); + static const Nz::Color& GetDefaultBarBackgroundCornerColor(); + + + inline void SetBarBackgroundColor(const Nz::Color& globalColor, const Nz::Color& cornerColor); + inline void SetBarBackgroundTexture(Nz::TextureRef texture, bool resetColors = true); + inline void SetBarColor(const Nz::Color& globalColor, const Nz::Color& cornerColor); + inline void SetBarTexture(Nz::TextureRef texture, bool resetColors = true); + + + inline void SetPercentageValue(unsigned percentage); + inline void SetTextMargin(float margin); + inline void SetTextColor(const Nz::Color& color); + + inline void ResizeToContent() override {} + + NazaraSignal(OnValueChanged, const ProgressBarWidget* /*progressBar*/); + + private: + void Layout() override; + inline void UpdateText(); + + + EntityHandle m_borderEntity; + EntityHandle m_barEntity; + EntityHandle m_textEntity; + + static Nz::Color s_borderColor; + static Nz::Color s_barBackgroundColor; + static Nz::Color s_barBackgroundCornerColor; + static Nz::Color s_barColor; + static Nz::Color s_barCornerColor; + Nz::Color m_textColor; + + Nz::SpriteRef m_borderSprite; + Nz::SpriteRef m_barBackgroundSprite; + Nz::SpriteRef m_barSprite; + Nz::TextSpriteRef m_textSprite; + + static float s_borderScale; + float m_textMargin; + unsigned m_value; + }; +} + +#include + +#endif // NDK_WIDGETS_PROGRESSBARWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/ProgressBarWidget.inl b/SDK/include/NDK/Widgets/ProgressBarWidget.inl new file mode 100644 index 000000000..325149af9 --- /dev/null +++ b/SDK/include/NDK/Widgets/ProgressBarWidget.inl @@ -0,0 +1,156 @@ +// Copyright (C) 2017 Samy Bensaid +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequesites.hpp + +namespace Ndk +{ + inline void ProgressBarWidget::EnableText(bool enable) + { + m_textEntity->Enable(enable); + Layout(); + } + + inline void ProgressBarWidget::EnableBorder(bool enable) + { + m_borderEntity->Enable(enable); + } + + inline bool ProgressBarWidget::IsTextEnabled() const + { + return m_textEntity->IsEnabled(); + } + + inline bool ProgressBarWidget::IsBorderEnabled() const + { + return m_borderEntity->IsEnabled(); + } + + + inline unsigned ProgressBarWidget::GetPercentageValue() const + { + return m_value; + } + + inline Nz::Vector2f ProgressBarWidget::GetProgressBarSize() const + { + Nz::Vector3f progressBarSize = m_borderSprite->GetBoundingVolume().obb.localBox.GetLengths(); + + if (IsTextEnabled()) + { + Nz::Vector3f textSize = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths(); + progressBarSize -= { textSize.x + m_textMargin, 0.f, 0.f }; + } + + return { progressBarSize.x, progressBarSize.y }; + } + + inline Nz::Vector2f ProgressBarWidget::GetProgressBarBorderSize() const + { + Nz::Vector2f barSize = GetProgressBarSize(); + return { barSize.y / s_borderScale, barSize.y / s_borderScale }; + } + + inline float ProgressBarWidget::GetTextMargin() const + { + return m_textMargin; + } + + + inline const Nz::Color& ProgressBarWidget::GetBarBackgroundColor() const + { + return m_barBackgroundSprite->GetColor(); + } + + inline const Nz::Color& ProgressBarWidget::GetBarBackgroundCornerColor() const + { + return m_barBackgroundSprite->GetCornerColor(Nz::RectCorner_LeftTop); + } + + inline const Nz::Color& ProgressBarWidget::GetBarColor() const + { + return m_barSprite->GetColor(); + } + + inline const Nz::Color& ProgressBarWidget::GetBarCornerColor() const + { + return m_barSprite->GetCornerColor(Nz::RectCorner_LeftTop); + } + + + inline const Nz::TextureRef& ProgressBarWidget::GetBarBackgroundTexture() const + { + return m_barBackgroundSprite->GetMaterial()->GetDiffuseMap(); + } + + inline const Nz::TextureRef& ProgressBarWidget::GetBarTexture() const + { + return m_barSprite->GetMaterial()->GetDiffuseMap(); + } + + + inline void ProgressBarWidget::SetBarBackgroundColor(const Nz::Color& globalColor, const Nz::Color& cornerColor) + { + m_barBackgroundSprite->SetColor(globalColor); + m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_LeftTop, cornerColor); + m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_RightTop, cornerColor); + m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_LeftBottom, globalColor); + m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_RightBottom, globalColor); + } + + inline void ProgressBarWidget::SetBarBackgroundTexture(Nz::TextureRef texture, bool resetColors) + { + m_barBackgroundSprite->SetTexture(texture, false); + + if (resetColors) + SetBarBackgroundColor(Nz::Color::White, Nz::Color::White); + } + + inline void ProgressBarWidget::SetBarColor(const Nz::Color& globalColor, const Nz::Color& cornerColor) + { + m_barSprite->SetColor(globalColor); + m_barSprite->SetCornerColor(Nz::RectCorner_LeftTop, cornerColor); + m_barSprite->SetCornerColor(Nz::RectCorner_RightTop, cornerColor); + m_barSprite->SetCornerColor(Nz::RectCorner_LeftBottom, globalColor); + m_barSprite->SetCornerColor(Nz::RectCorner_RightBottom, globalColor); + } + + inline void ProgressBarWidget::SetBarTexture(Nz::TextureRef texture, bool resetColors) + { + m_barSprite->SetTexture(texture, false); + + if (resetColors) + SetBarColor(Nz::Color::White, Nz::Color::White); + } + + + inline void ProgressBarWidget::SetPercentageValue(unsigned percentage) + { + m_value = percentage; + OnValueChanged(this); + Layout(); + } + + inline void ProgressBarWidget::SetTextMargin(float margin) + { + m_textMargin = margin; + + if (IsTextEnabled()) + Layout(); + } + + inline void ProgressBarWidget::SetTextColor(const Nz::Color& color) + { + m_textColor = color; + UpdateText(); + } + + inline void ProgressBarWidget::UpdateText() + { + if (IsTextEnabled()) + { + Nz::Vector2f size = GetContentSize(); + m_textSprite->Update(Nz::SimpleTextDrawer::Draw(Nz::String::Number(m_value).Append('%'), + static_cast(std::min(size.x, size.y) / 2.f), 0u, m_textColor)); + } + } +} diff --git a/SDK/include/NDK/Widgets/TextAreaWidget.hpp b/SDK/include/NDK/Widgets/TextAreaWidget.hpp index 0bf5a3a59..e1ed41a0c 100644 --- a/SDK/include/NDK/Widgets/TextAreaWidget.hpp +++ b/SDK/include/NDK/Widgets/TextAreaWidget.hpp @@ -14,8 +14,6 @@ namespace Ndk { - class World; - class NDK_API TextAreaWidget : public BaseWidget { public: @@ -32,7 +30,8 @@ namespace Ndk inline void EnableMultiline(bool enable = true); - inline std::size_t GetCursorPosition() const; + inline const Nz::Vector2ui& GetCursorPosition() const; + inline std::size_t GetGlyphUnderCursor() const; inline std::size_t GetLineCount() const; inline const Nz::String& GetText() const; inline const Nz::Color& GetTextColor() const; @@ -43,10 +42,12 @@ namespace Ndk inline bool IsReadOnly() const; inline void MoveCursor(int offset); + inline void MoveCursor(const Nz::Vector2i& offset); void ResizeToContent() override; - inline void SetCursorPosition(std::size_t cursorPosition); + inline void SetCursorPosition(std::size_t glyphIndex); + inline void SetCursorPosition(Nz::Vector2ui cursorPosition); inline void SetReadOnly(bool readOnly = true); inline void SetText(const Nz::String& text); inline void SetTextColor(const Nz::Color& text); @@ -82,7 +83,8 @@ namespace Ndk Nz::SimpleTextDrawer m_drawer; Nz::SpriteRef m_cursorSprite; Nz::TextSpriteRef m_textSprite; - std::size_t m_cursorPosition; + Nz::Vector2ui m_cursorPosition; + std::size_t m_cursorGlyph; bool m_multiLineEnabled; bool m_readOnly; }; diff --git a/SDK/include/NDK/Widgets/TextAreaWidget.inl b/SDK/include/NDK/Widgets/TextAreaWidget.inl index 077f538ec..7c2192e6b 100644 --- a/SDK/include/NDK/Widgets/TextAreaWidget.inl +++ b/SDK/include/NDK/Widgets/TextAreaWidget.inl @@ -20,11 +20,16 @@ namespace Ndk m_multiLineEnabled = enable; } - inline std::size_t TextAreaWidget::GetCursorPosition() const + inline const Nz::Vector2ui& TextAreaWidget::GetCursorPosition() const { return m_cursorPosition; } + inline std::size_t Ndk::TextAreaWidget::GetGlyphUnderCursor() const + { + return m_cursorGlyph; + } + inline std::size_t TextAreaWidget::GetLineCount() const { return m_drawer.GetLineCount(); @@ -53,22 +58,84 @@ namespace Ndk inline void TextAreaWidget::MoveCursor(int offset) { if (offset >= 0) - SetCursorPosition(m_cursorPosition += static_cast(offset)); + SetCursorPosition(m_cursorGlyph + static_cast(offset)); else { std::size_t nOffset = static_cast(-offset); - if (nOffset >= m_cursorPosition) + if (nOffset >= m_cursorGlyph) SetCursorPosition(0); else - SetCursorPosition(m_cursorPosition - nOffset); + SetCursorPosition(m_cursorGlyph - nOffset); } } - inline void TextAreaWidget::SetCursorPosition(std::size_t cursorPosition) + inline void TextAreaWidget::MoveCursor(const Nz::Vector2i& offset) { - OnTextAreaCursorMove(this, &cursorPosition); + auto BoundOffset = [] (unsigned int cursorPosition, int cursorOffset) -> unsigned int + { + if (cursorOffset >= 0) + return cursorPosition + cursorOffset; + else + { + unsigned int nOffset = static_cast(-cursorOffset); + if (nOffset >= cursorPosition) + return 0; + else + return cursorPosition - nOffset; + } + }; - m_cursorPosition = std::min(cursorPosition, m_drawer.GetGlyphCount()); + Nz::Vector2ui cursorPosition = m_cursorPosition; + cursorPosition.x = BoundOffset(static_cast(cursorPosition.x), offset.x); + cursorPosition.y = BoundOffset(static_cast(cursorPosition.y), offset.y); + + SetCursorPosition(cursorPosition); + } + + inline void TextAreaWidget::SetCursorPosition(std::size_t glyphIndex) + { + OnTextAreaCursorMove(this, &glyphIndex); + + m_cursorGlyph = std::min(glyphIndex, m_drawer.GetGlyphCount()); + + std::size_t lineCount = m_drawer.GetLineCount(); + std::size_t line = 0U; + for (std::size_t i = line + 1; i < lineCount; ++i) + { + if (m_drawer.GetLine(i).glyphIndex > m_cursorGlyph) + break; + + line = i; + } + + const auto& lineInfo = m_drawer.GetLine(line); + + m_cursorPosition.y = line; + m_cursorPosition.x = m_cursorGlyph - lineInfo.glyphIndex; + + RefreshCursor(); + } + + inline void TextAreaWidget::SetCursorPosition(Nz::Vector2ui cursorPosition) + { + std::size_t lineCount = m_drawer.GetLineCount(); + if (cursorPosition.y >= lineCount) + cursorPosition.y = static_cast(lineCount - 1); + + m_cursorPosition = cursorPosition; + + const auto& lineInfo = m_drawer.GetLine(cursorPosition.y); + if (cursorPosition.y + 1 < lineCount) + { + const auto& nextLineInfo = m_drawer.GetLine(cursorPosition.y + 1); + cursorPosition.x = std::min(cursorPosition.x, static_cast(nextLineInfo.glyphIndex - lineInfo.glyphIndex - 1)); + } + + std::size_t glyphIndex = lineInfo.glyphIndex + cursorPosition.x; + + OnTextAreaCursorMove(this, &glyphIndex); + + m_cursorGlyph = std::min(glyphIndex, m_drawer.GetGlyphCount()); RefreshCursor(); } diff --git a/SDK/include/NDK/World.hpp b/SDK/include/NDK/World.hpp index 29b9a4a9e..9cc6d8901 100644 --- a/SDK/include/NDK/World.hpp +++ b/SDK/include/NDK/World.hpp @@ -15,7 +15,6 @@ #include #include #include -#include namespace Ndk { diff --git a/SDK/include/NDK/World.inl b/SDK/include/NDK/World.inl index d45f0ff1d..0cb0fc7c9 100644 --- a/SDK/include/NDK/World.inl +++ b/SDK/include/NDK/World.inl @@ -314,7 +314,8 @@ namespace Ndk m_systems = std::move(world.m_systems); for (const auto& systemPtr : m_systems) - systemPtr->SetWorld(this); + if (systemPtr) + systemPtr->SetWorld(this); return *this; } diff --git a/SDK/src/NDK/Application.cpp b/SDK/src/NDK/Application.cpp index c70ec181b..67040db69 100644 --- a/SDK/src/NDK/Application.cpp +++ b/SDK/src/NDK/Application.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #endif diff --git a/SDK/src/NDK/BaseWidget.cpp b/SDK/src/NDK/BaseWidget.cpp index c4ef2d1f8..7368558d3 100644 --- a/SDK/src/NDK/BaseWidget.cpp +++ b/SDK/src/NDK/BaseWidget.cpp @@ -11,6 +11,20 @@ namespace Ndk { + /*! + * \ingroup NDK + * \class Ndk::BaseWidget + * \brief Abstract class serving as a base class for all widgets + */ + + /*! + * \brief Constructs a BaseWidget object using another widget as its parent + * + * \param parent Parent widget, must be valid and attached to a canvas + * + * Constructs a BaseWidget object using another widget as a base. + * This will also register the widget to the canvas owning the top-most widget. + */ BaseWidget::BaseWidget(BaseWidget* parent) : BaseWidget() { @@ -24,11 +38,19 @@ namespace Ndk RegisterToCanvas(); } + /*! + * \brief Frees the widget, unregistering it from its canvas + */ BaseWidget::~BaseWidget() { UnregisterFromCanvas(); } + /*! + * \brief Destroy the widget, deleting it in the process. + * + * Calling this function immediately destroys the widget, freeing its memory. + */ void BaseWidget::Destroy() { NazaraAssert(this != m_canvas, "Canvas cannot be destroyed by calling Destroy()"); @@ -36,6 +58,9 @@ namespace Ndk m_widgetParent->DestroyChild(this); //< This does delete us } + /*! + * \brief Enable or disables the widget background. + */ void BaseWidget::EnableBackground(bool enable) { if (m_backgroundEntity.IsValid() == enable) @@ -142,11 +167,11 @@ namespace Ndk m_canvas->NotifyWidgetBoxUpdate(m_canvasIndex); } - void BaseWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& key) + void BaseWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& /*key*/) { } - void BaseWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& key) + void BaseWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& /*key*/) { } @@ -154,15 +179,15 @@ namespace Ndk { } - void BaseWidget::OnMouseMoved(int x, int y, int deltaX, int deltaY) + void BaseWidget::OnMouseMoved(int /*x*/, int /*y*/, int /*deltaX*/, int /*deltaY*/) { } - void BaseWidget::OnMouseButtonPress(int x, int y, Nz::Mouse::Button button) + void BaseWidget::OnMouseButtonPress(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/) { } - void BaseWidget::OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) + void BaseWidget::OnMouseButtonRelease(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/) { } @@ -170,11 +195,11 @@ namespace Ndk { } - void BaseWidget::OnParentResized(const Nz::Vector2f& newSize) + void BaseWidget::OnParentResized(const Nz::Vector2f& /*newSize*/) { } - void BaseWidget::OnTextEntered(char32_t character, bool repeated) + void BaseWidget::OnTextEntered(char32_t /*character*/, bool /*repeated*/) { } diff --git a/SDK/src/NDK/Canvas.cpp b/SDK/src/NDK/Canvas.cpp index 84e4b5bd8..81f5ea994 100644 --- a/SDK/src/NDK/Canvas.cpp +++ b/SDK/src/NDK/Canvas.cpp @@ -3,9 +3,6 @@ // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include -#include -#include -#include #include namespace Ndk @@ -48,7 +45,7 @@ namespace Ndk m_widgetBoxes.pop_back(); } - void Canvas::OnMouseButtonPressed(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent& event) + void Canvas::OnEventMouseButtonPressed(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent& event) { if (m_hoveredWidget) { @@ -59,7 +56,7 @@ namespace Ndk } } - void Canvas::OnMouseButtonRelease(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent & event) + void Canvas::OnEventMouseButtonRelease(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent & event) { if (m_hoveredWidget) { @@ -70,7 +67,7 @@ namespace Ndk } } - void Canvas::OnMouseMoved(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseMoveEvent& event) + void Canvas::OnEventMouseMoved(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseMoveEvent& event) { const WidgetBox* bestEntry = nullptr; float bestEntryArea = std::numeric_limits::infinity(); @@ -120,7 +117,7 @@ namespace Ndk } } - void Canvas::OnMouseLeft(const Nz::EventHandler* /*eventHandler*/) + void Canvas::OnEventMouseLeft(const Nz::EventHandler* /*eventHandler*/) { if (m_hoveredWidget) { @@ -129,19 +126,19 @@ namespace Ndk } } - void Canvas::OnKeyPressed(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& event) + void Canvas::OnEventKeyPressed(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& event) { if (m_keyboardOwner) m_keyboardOwner->OnKeyPressed(event); } - void Canvas::OnKeyReleased(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& event) + void Canvas::OnEventKeyReleased(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& event) { if (m_keyboardOwner) m_keyboardOwner->OnKeyReleased(event); } - void Canvas::OnTextEntered(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::TextEvent& event) + void Canvas::OnEventTextEntered(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::TextEvent& event) { if (m_keyboardOwner) m_keyboardOwner->OnTextEntered(event.character, event.repeated); diff --git a/SDK/src/NDK/Components/CollisionComponent2D.cpp b/SDK/src/NDK/Components/CollisionComponent2D.cpp index ff10019f6..5a37d5e04 100644 --- a/SDK/src/NDK/Components/CollisionComponent2D.cpp +++ b/SDK/src/NDK/Components/CollisionComponent2D.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include diff --git a/SDK/src/NDK/Components/CollisionComponent3D.cpp b/SDK/src/NDK/Components/CollisionComponent3D.cpp index 4ec2bff81..a853cbb55 100644 --- a/SDK/src/NDK/Components/CollisionComponent3D.cpp +++ b/SDK/src/NDK/Components/CollisionComponent3D.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include diff --git a/SDK/src/NDK/Components/PhysicsComponent2D.cpp b/SDK/src/NDK/Components/PhysicsComponent2D.cpp index 58cab2982..2061029de 100644 --- a/SDK/src/NDK/Components/PhysicsComponent2D.cpp +++ b/SDK/src/NDK/Components/PhysicsComponent2D.cpp @@ -4,11 +4,10 @@ #include #include -#include #include #include #include -#include +#include namespace Ndk { diff --git a/SDK/src/NDK/Components/PhysicsComponent3D.cpp b/SDK/src/NDK/Components/PhysicsComponent3D.cpp index 31b3fb6ac..1e6ccf0c7 100644 --- a/SDK/src/NDK/Components/PhysicsComponent3D.cpp +++ b/SDK/src/NDK/Components/PhysicsComponent3D.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include diff --git a/SDK/src/NDK/Console.cpp b/SDK/src/NDK/Console.cpp index a59bfdf81..0c8ceaa5d 100644 --- a/SDK/src/NDK/Console.cpp +++ b/SDK/src/NDK/Console.cpp @@ -4,7 +4,8 @@ #include #include -#include +#include +#include #include #include #include diff --git a/SDK/src/NDK/Lua/LuaBinding.cpp b/SDK/src/NDK/Lua/LuaBinding.cpp index 715351e52..4bca51e19 100644 --- a/SDK/src/NDK/Lua/LuaBinding.cpp +++ b/SDK/src/NDK/Lua/LuaBinding.cpp @@ -25,6 +25,7 @@ namespace Ndk audio = LuaBinding_Base::BindAudio(*this); renderer = LuaBinding_Base::BindRenderer(*this); graphics = LuaBinding_Base::BindGraphics(*this); + platform = LuaBinding_Base::BindPlatform(*this); #endif sdk = LuaBinding_Base::BindSDK(*this); @@ -48,6 +49,7 @@ namespace Ndk audio->Register(state); graphics->Register(state); renderer->Register(state); + platform->Register(state); #endif // ComponentType (fake enumeration to expose component indexes) diff --git a/SDK/src/NDK/Lua/LuaBinding_Core.cpp b/SDK/src/NDK/Lua/LuaBinding_Core.cpp index f86aafa98..6091c88e2 100644 --- a/SDK/src/NDK/Lua/LuaBinding_Core.cpp +++ b/SDK/src/NDK/Lua/LuaBinding_Core.cpp @@ -32,28 +32,28 @@ namespace Ndk stream.BindMethod("IsWritable", &Nz::Stream::IsWritable); stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos); - stream.BindMethod("Read", [] (Nz::LuaState& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int { + stream.BindMethod("Read", [] (Nz::LuaState& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int { int argIndex = 2; std::size_t length = lua.Check(&argIndex); std::unique_ptr buffer(new char[length]); - std::size_t readLength = stream.Read(buffer.get(), length); + std::size_t readLength = instance.Read(buffer.get(), length); lua.PushString(Nz::String(buffer.get(), readLength)); return 1; }); - stream.BindMethod("Write", [] (Nz::LuaState& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int { + stream.BindMethod("Write", [] (Nz::LuaState& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int { int argIndex = 2; std::size_t bufferSize = 0; const char* buffer = lua.CheckString(argIndex, &bufferSize); - if (stream.IsTextModeEnabled()) - lua.Push(stream.Write(Nz::String(buffer, bufferSize))); + if (instance.IsTextModeEnabled()) + lua.Push(instance.Write(Nz::String(buffer, bufferSize))); else - lua.Push(stream.Write(buffer, bufferSize)); + lua.Push(instance.Write(buffer, bufferSize)); return 1; }); } @@ -103,11 +103,11 @@ namespace Ndk clock.BindMethod("Unpause", &Nz::Clock::Unpause); // Manual - clock.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Clock& clock, std::size_t /*argumentCount*/) -> int { + clock.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Clock& instance, std::size_t /*argumentCount*/) -> int { Nz::StringStream ss("Clock(Elapsed: "); - ss << clock.GetSeconds(); + ss << instance.GetSeconds(); ss << "s, Paused: "; - ss << clock.IsPaused(); + ss << instance.IsPaused(); ss << ')'; lua.PushString(ss); @@ -159,9 +159,9 @@ namespace Ndk directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); // Manual - directory.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Directory& dir, std::size_t /*argumentCount*/) -> int { + directory.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Directory& instance, std::size_t /*argumentCount*/) -> int { Nz::StringStream ss("Directory("); - ss << dir.GetPath(); + ss << instance.GetPath(); ss << ')'; lua.PushString(ss); @@ -237,7 +237,7 @@ namespace Ndk file.BindStaticMethod("Rename", &Nz::File::Rename); // Manual - file.BindMethod("Open", [] (Nz::LuaState& lua, Nz::File& file, std::size_t argumentCount) -> int + file.BindMethod("Open", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 2U); @@ -246,13 +246,13 @@ namespace Ndk { case 0: case 1: - return lua.Push(file.Open(lua.Check(&argIndex, Nz::OpenMode_NotOpen))); + return lua.Push(instance.Open(lua.Check(&argIndex, Nz::OpenMode_NotOpen))); case 2: { Nz::String filePath = lua.Check(&argIndex); Nz::UInt32 openMode = lua.Check(&argIndex, Nz::OpenMode_NotOpen); - return lua.Push(file.Open(filePath, openMode)); + return lua.Push(instance.Open(filePath, openMode)); } } @@ -260,7 +260,7 @@ namespace Ndk return 0; }); - file.BindMethod("SetCursorPos", [] (Nz::LuaState& lua, Nz::File& file, std::size_t argumentCount) -> int + file.BindMethod("SetCursorPos", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 2U); @@ -268,13 +268,13 @@ namespace Ndk switch (argCount) { case 1: - return lua.Push(file.SetCursorPos(lua.Check(&argIndex))); + return lua.Push(instance.SetCursorPos(lua.Check(&argIndex))); case 2: { Nz::CursorPosition curPos = lua.Check(&argIndex); Nz::Int64 offset = lua.Check(&argIndex); - return lua.Push(file.SetCursorPos(curPos, offset)); + return lua.Push(instance.SetCursorPos(curPos, offset)); } } @@ -282,10 +282,10 @@ namespace Ndk return 0; }); - file.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::File& file, std::size_t /*argumentCount*/) -> int { + file.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t /*argumentCount*/) -> int { Nz::StringStream ss("File("); - if (file.IsOpen()) - ss << "Path: " << file.GetPath(); + if (instance.IsOpen()) + ss << "Path: " << instance.GetPath(); ss << ')'; @@ -321,10 +321,11 @@ namespace Ndk state.SetGlobal("CursorPosition"); // Nz::HashType - static_assert(Nz::HashType_Max + 1 == 9, "Nz::HashType has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 9); + static_assert(Nz::HashType_Max + 1 == 10, "Nz::HashType has been updated but change was not reflected to Lua binding"); + state.PushTable(0, 10); { state.PushField("CRC32", Nz::HashType_CRC32); + state.PushField("CRC64", Nz::HashType_CRC64); state.PushField("Fletcher16", Nz::HashType_Fletcher16); state.PushField("MD5", Nz::HashType_MD5); state.PushField("SHA1", Nz::HashType_SHA1); diff --git a/SDK/src/NDK/Lua/LuaBinding_Platform.cpp b/SDK/src/NDK/Lua/LuaBinding_Platform.cpp new file mode 100644 index 000000000..b910770fa --- /dev/null +++ b/SDK/src/NDK/Lua/LuaBinding_Platform.cpp @@ -0,0 +1,133 @@ +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequesites.hpp + +#include +#include + +namespace Ndk +{ + std::unique_ptr LuaBinding_Base::BindPlatform(LuaBinding& binding) + { + return std::make_unique(binding); + } + + LuaBinding_Platform::LuaBinding_Platform(LuaBinding& binding) : + LuaBinding_Base(binding) + { + /*********************************** Nz::Keyboard **********************************/ + keyboard.Reset("Keyboard"); + { + keyboard.BindStaticMethod("GetKeyName", &Nz::Keyboard::GetKeyName); + keyboard.BindStaticMethod("IsKeyPressed", &Nz::Keyboard::IsKeyPressed); + } + } + + /*! + * \brief Registers the classes that will be used by the Lua instance + * + * \param instance Lua instance that will interact with the Utility classes + */ + void LuaBinding_Platform::Register(Nz::LuaState& state) + { + keyboard.Register(state); + + keyboard.PushGlobalTable(state); + { + static_assert(Nz::Keyboard::Count == 121, "Nz::Keyboard::Key has been updated but change was not reflected to Lua binding"); + + state.PushField("Undefined", Nz::Keyboard::Undefined); + + // A-Z + for (std::size_t i = 0; i < 26; ++i) + state.PushField(Nz::String('A' + char(i)), Nz::Keyboard::A + i); + + // Numerical + for (std::size_t i = 0; i < 10; ++i) + { + state.PushField("Num" + Nz::String::Number(i), Nz::Keyboard::Num0 + i); + state.PushField("Numpad" + Nz::String::Number(i), Nz::Keyboard::Numpad0 + i); + } + + // F1-F15 + for (std::size_t i = 0; i < 15; ++i) + state.PushField('F' + Nz::String::Number(i+1), Nz::Keyboard::F1 + i); + + // And all the others... + state.PushField("Down", Nz::Keyboard::Down); + state.PushField("Left", Nz::Keyboard::Left); + state.PushField("Right", Nz::Keyboard::Right); + state.PushField("Up", Nz::Keyboard::Up); + + state.PushField("Add", Nz::Keyboard::Add); + state.PushField("Decimal", Nz::Keyboard::Decimal); + state.PushField("Divide", Nz::Keyboard::Divide); + state.PushField("Multiply", Nz::Keyboard::Multiply); + state.PushField("Subtract", Nz::Keyboard::Subtract); + + state.PushField("Backslash", Nz::Keyboard::Backslash); + state.PushField("Backspace", Nz::Keyboard::Backspace); + state.PushField("Clear", Nz::Keyboard::Clear); + state.PushField("Comma", Nz::Keyboard::Comma); + state.PushField("Dash", Nz::Keyboard::Dash); + state.PushField("Delete", Nz::Keyboard::Delete); + state.PushField("End", Nz::Keyboard::End); + state.PushField("Equal", Nz::Keyboard::Equal); + state.PushField("Escape", Nz::Keyboard::Escape); + state.PushField("Home", Nz::Keyboard::Home); + state.PushField("Insert", Nz::Keyboard::Insert); + state.PushField("LAlt", Nz::Keyboard::LAlt); + state.PushField("LBracket", Nz::Keyboard::LBracket); + state.PushField("LControl", Nz::Keyboard::LControl); + state.PushField("LShift", Nz::Keyboard::LShift); + state.PushField("LSystem", Nz::Keyboard::LSystem); + state.PushField("PageDown", Nz::Keyboard::PageDown); + state.PushField("PageUp", Nz::Keyboard::PageUp); + state.PushField("Pause", Nz::Keyboard::Pause); + state.PushField("Period", Nz::Keyboard::Period); + state.PushField("Print", Nz::Keyboard::Print); + state.PushField("PrintScreen", Nz::Keyboard::PrintScreen); + state.PushField("Quote", Nz::Keyboard::Quote); + state.PushField("RAlt", Nz::Keyboard::RAlt); + state.PushField("RBracket", Nz::Keyboard::RBracket); + state.PushField("RControl", Nz::Keyboard::RControl); + state.PushField("Return", Nz::Keyboard::Return); + state.PushField("RShift", Nz::Keyboard::RShift); + state.PushField("RSystem", Nz::Keyboard::RSystem); + state.PushField("Semicolon", Nz::Keyboard::Semicolon); + state.PushField("Slash", Nz::Keyboard::Slash); + state.PushField("Space", Nz::Keyboard::Space); + state.PushField("Tab", Nz::Keyboard::Tab); + state.PushField("Tilde", Nz::Keyboard::Tilde); + state.PushField("Browser_Back", Nz::Keyboard::Browser_Back); + state.PushField("Browser_Favorites", Nz::Keyboard::Browser_Favorites); + state.PushField("Browser_Forward", Nz::Keyboard::Browser_Forward); + state.PushField("Browser_Home", Nz::Keyboard::Browser_Home); + state.PushField("Browser_Refresh", Nz::Keyboard::Browser_Refresh); + state.PushField("Browser_Search", Nz::Keyboard::Browser_Search); + state.PushField("Browser_Stop", Nz::Keyboard::Browser_Stop); + state.PushField("Media_Next", Nz::Keyboard::Media_Next); + state.PushField("Media_Play", Nz::Keyboard::Media_Play); + state.PushField("Media_Previous", Nz::Keyboard::Media_Previous); + state.PushField("Media_Stop", Nz::Keyboard::Media_Stop); + state.PushField("Volume_Down", Nz::Keyboard::Volume_Down); + state.PushField("Volume_Mute", Nz::Keyboard::Volume_Mute); + state.PushField("Volume_Up", Nz::Keyboard::Volume_Up); + state.PushField("CapsLock", Nz::Keyboard::CapsLock); + state.PushField("NumLock", Nz::Keyboard::NumLock); + state.PushField("ScrollLock", Nz::Keyboard::ScrollLock); + } + state.Pop(); + + static_assert(Nz::WindowStyle_Max + 1 == 6, "Nz::WindowStyle has been updated but change was not reflected to Lua binding"); + state.PushTable(0, Nz::WindowStyle_Max + 1); + { + state.PushField("None", Nz::WindowStyle_None); + state.PushField("Fullscreen", Nz::WindowStyle_Fullscreen); + state.PushField("Closable", Nz::WindowStyle_Closable); + state.PushField("Resizable", Nz::WindowStyle_Resizable); + state.PushField("Titlebar", Nz::WindowStyle_Titlebar); + state.PushField("Threaded", Nz::WindowStyle_Threaded); + } + state.SetGlobal("WindowStyle"); + } +} diff --git a/SDK/src/NDK/Lua/LuaBinding_Renderer.cpp b/SDK/src/NDK/Lua/LuaBinding_Renderer.cpp index 064d21cfe..1ab24cedb 100644 --- a/SDK/src/NDK/Lua/LuaBinding_Renderer.cpp +++ b/SDK/src/NDK/Lua/LuaBinding_Renderer.cpp @@ -84,7 +84,7 @@ namespace Ndk } /*********************************** Nz::TextureManager ***********************************/ - textureManager.Reset("textureManager"); + textureManager.Reset("TextureManager"); { textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear); textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get); diff --git a/SDK/src/NDK/Lua/LuaBinding_SDK.cpp b/SDK/src/NDK/Lua/LuaBinding_SDK.cpp index a4ae0b792..8952ce7d9 100644 --- a/SDK/src/NDK/Lua/LuaBinding_SDK.cpp +++ b/SDK/src/NDK/Lua/LuaBinding_SDK.cpp @@ -69,6 +69,7 @@ namespace Ndk console.BindMethod("GetSize", &Console::GetSize); console.BindMethod("GetTextFont", &Console::GetTextFont); + console.BindMethod("IsValidHandle", &ConsoleHandle::IsValid); console.BindMethod("IsVisible", &Console::IsVisible); console.BindMethod("SendCharacter", &Console::SendCharacter); @@ -91,6 +92,7 @@ namespace Ndk entity.BindMethod("Kill", &Entity::Kill); entity.BindMethod("IsEnabled", &Entity::IsEnabled); entity.BindMethod("IsValid", &Entity::IsValid); + entity.BindMethod("IsValidHandle", &EntityHandle::IsValid); entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); entity.BindMethod("__tostring", &EntityHandle::ToString); @@ -101,6 +103,14 @@ namespace Ndk return bindingComponent->adder(state, handle); }); + entity.BindMethod("HasComponent", [this](Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int + { + LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state); + + state.PushBoolean(handle->HasComponent(bindingComponent->index)); + return 1; + }); + entity.BindMethod("GetComponent", [this] (Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int { LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state); @@ -120,6 +130,8 @@ namespace Ndk /*********************************** Ndk::NodeComponent **********************************/ nodeComponent.Reset("NodeComponent"); { + nodeComponent.BindMethod("IsValidHandle", &NodeComponentHandle::IsValid); + nodeComponent.Inherit(utility.node, [] (NodeComponentHandle* handle) -> Nz::Node* { return handle->GetObject(); @@ -129,6 +141,8 @@ namespace Ndk /*********************************** Ndk::VelocityComponent **********************************/ velocityComponent.Reset("VelocityComponent"); { + velocityComponent.BindMethod("IsValidHandle", &VelocityComponentHandle::IsValid); + velocityComponent.SetGetter([] (Nz::LuaState& lua, VelocityComponentHandle& instance) { std::size_t length; @@ -165,6 +179,8 @@ namespace Ndk world.BindMethod("CreateEntity", &World::CreateEntity); world.BindMethod("CreateEntities", &World::CreateEntities); world.BindMethod("Clear", &World::Clear); + + world.BindMethod("IsValidHandle", &WorldHandle::IsValid); } #ifndef NDK_SERVER @@ -176,18 +192,20 @@ namespace Ndk return handle->GetObject(); }); - cameraComponent.BindMethod("GetFOV", &Ndk::CameraComponent::GetFOV); - cameraComponent.BindMethod("GetLayer", &Ndk::CameraComponent::GetLayer); + cameraComponent.BindMethod("GetFOV", &CameraComponent::GetFOV); + cameraComponent.BindMethod("GetLayer", &CameraComponent::GetLayer); - cameraComponent.BindMethod("SetFOV", &Ndk::CameraComponent::SetFOV); - cameraComponent.BindMethod("SetLayer", &Ndk::CameraComponent::SetLayer); - cameraComponent.BindMethod("SetProjectionType", &Ndk::CameraComponent::SetProjectionType); - cameraComponent.BindMethod("SetSize", (void(Ndk::CameraComponent::*)(const Nz::Vector2f&)) &Ndk::CameraComponent::SetSize); - //cameraComponent.BindMethod("SetTarget", &Ndk::CameraComponent::SetTarget); - cameraComponent.BindMethod("SetTargetRegion", &Ndk::CameraComponent::SetTargetRegion); - cameraComponent.BindMethod("SetViewport", &Ndk::CameraComponent::SetViewport); - cameraComponent.BindMethod("SetZFar", &Ndk::CameraComponent::SetZFar); - cameraComponent.BindMethod("SetZNear", &Ndk::CameraComponent::SetZNear); + cameraComponent.BindMethod("IsValidHandle", &CameraComponentHandle::IsValid); + + cameraComponent.BindMethod("SetFOV", &CameraComponent::SetFOV); + cameraComponent.BindMethod("SetLayer", &CameraComponent::SetLayer); + cameraComponent.BindMethod("SetProjectionType", &CameraComponent::SetProjectionType); + cameraComponent.BindMethod("SetSize", (void(CameraComponent::*)(const Nz::Vector2f&)) &CameraComponent::SetSize); + //cameraComponent.BindMethod("SetTarget", &CameraComponent::SetTarget); + cameraComponent.BindMethod("SetTargetRegion", &CameraComponent::SetTargetRegion); + cameraComponent.BindMethod("SetViewport", &CameraComponent::SetViewport); + cameraComponent.BindMethod("SetZFar", &CameraComponent::SetZFar); + cameraComponent.BindMethod("SetZNear", &CameraComponent::SetZNear); } /*********************************** Ndk::GraphicsComponent **********************************/ @@ -249,6 +267,8 @@ namespace Ndk lua.Error("No matching overload for method GetMemoryUsage"); return 0; }); + + graphicsComponent.BindMethod("IsValidHandle", &GraphicsComponentHandle::IsValid); } #endif diff --git a/SDK/src/NDK/Lua/LuaBinding_Utility.cpp b/SDK/src/NDK/Lua/LuaBinding_Utility.cpp index 6d7baf588..14fddec73 100644 --- a/SDK/src/NDK/Lua/LuaBinding_Utility.cpp +++ b/SDK/src/NDK/Lua/LuaBinding_Utility.cpp @@ -161,13 +161,6 @@ namespace Ndk font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize); } - /*********************************** Nz::Keyboard **********************************/ - keyboard.Reset("Keyboard"); - { - keyboard.BindStaticMethod("GetKeyName", &Nz::Keyboard::GetKeyName); - keyboard.BindStaticMethod("IsKeyPressed", &Nz::Keyboard::IsKeyPressed); - } - /*********************************** Nz::Node **********************************/ node.Reset("Node"); { @@ -216,29 +209,29 @@ namespace Ndk node.BindMethod("SetPosition", (void(Nz::Node::*)(const Nz::Vector3f&, Nz::CoordSys)) &Nz::Node::SetPosition, Nz::CoordSys_Local); node.BindMethod("SetRotation", (void(Nz::Node::*)(const Nz::Quaternionf&, Nz::CoordSys)) &Nz::Node::SetRotation, Nz::CoordSys_Local); - node.BindMethod("Move", [] (Nz::LuaState& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int + node.BindMethod("Move", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int { int argIndex = 2; Nz::Vector3f offset = lua.Check(&argIndex); Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - node.Move(offset, coordSys); + instance.Move(offset, coordSys); return 0; }); - node.BindMethod("Rotate", [] (Nz::LuaState& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int + node.BindMethod("Rotate", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int { int argIndex = 2; Nz::Quaternionf rotation = lua.Check(&argIndex); Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - node.Rotate(rotation, coordSys); + instance.Rotate(rotation, coordSys); return 0; }); - node.BindMethod("Scale", [] (Nz::LuaState& lua, Nz::Node& node, std::size_t argumentCount) -> int + node.BindMethod("Scale", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 4U); @@ -248,15 +241,15 @@ namespace Ndk case 1: { if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - node.Scale(lua.Check(&argIndex)); + instance.Scale(lua.Check(&argIndex)); else - node.Scale(lua.Check(&argIndex)); + instance.Scale(lua.Check(&argIndex)); return 0; } case 3: - node.Scale(lua.Check(&argIndex)); + instance.Scale(lua.Check(&argIndex)); return 0; } @@ -264,7 +257,7 @@ namespace Ndk return 0; }); - node.BindMethod("SetScale", [] (Nz::LuaState& lua, Nz::Node& node, std::size_t argumentCount) -> int + node.BindMethod("SetScale", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 4U); @@ -278,10 +271,10 @@ namespace Ndk { float scale = lua.Check(&argIndex); Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - node.SetScale(scale, coordSys); + instance.SetScale(scale, coordSys); } else - node.SetScale(lua.Check(&argIndex)); + instance.SetScale(lua.Check(&argIndex)); return 0; } @@ -292,7 +285,7 @@ namespace Ndk Nz::Vector3f scale = lua.Check(&argIndex); Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - node.SetScale(scale, coordSys); + instance.SetScale(scale, coordSys); return 0; } } @@ -301,7 +294,7 @@ namespace Ndk return 0; }); - node.BindMethod("SetInitialScale", [] (Nz::LuaState& lua, Nz::Node& node, std::size_t argumentCount) -> int + node.BindMethod("SetInitialScale", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t argumentCount) -> int { std::size_t argCount = std::min(argumentCount, 4U); @@ -311,16 +304,16 @@ namespace Ndk case 1: { if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - node.SetInitialScale(lua.Check(&argIndex)); + instance.SetInitialScale(lua.Check(&argIndex)); else - node.SetInitialScale(lua.Check(&argIndex)); + instance.SetInitialScale(lua.Check(&argIndex)); return 0; } case 2: case 3: - node.SetInitialScale(lua.Check(&argIndex)); + instance.SetInitialScale(lua.Check(&argIndex)); return 0; } @@ -339,106 +332,6 @@ namespace Ndk { abstractImage.Register(state); font.Register(state); - keyboard.Register(state); node.Register(state); - - keyboard.PushGlobalTable(state); - { - static_assert(Nz::Keyboard::Count == 121, "Nz::Keyboard::Key has been updated but change was not reflected to Lua binding"); - - state.PushField("Undefined", Nz::Keyboard::Undefined); - - // A-Z - for (std::size_t i = 0; i < 26; ++i) - state.PushField(Nz::String('A' + char(i)), Nz::Keyboard::A + i); - - // Numerical - for (std::size_t i = 0; i < 10; ++i) - { - state.PushField("Num" + Nz::String::Number(i), Nz::Keyboard::Num0 + i); - state.PushField("Numpad" + Nz::String::Number(i), Nz::Keyboard::Numpad0 + i); - } - - // F1-F15 - for (std::size_t i = 0; i < 15; ++i) - state.PushField('F' + Nz::String::Number(i+1), Nz::Keyboard::F1 + i); - - // And all the others... - state.PushField("Down", Nz::Keyboard::Down); - state.PushField("Left", Nz::Keyboard::Left); - state.PushField("Right", Nz::Keyboard::Right); - state.PushField("Up", Nz::Keyboard::Up); - - state.PushField("Add", Nz::Keyboard::Add); - state.PushField("Decimal", Nz::Keyboard::Decimal); - state.PushField("Divide", Nz::Keyboard::Divide); - state.PushField("Multiply", Nz::Keyboard::Multiply); - state.PushField("Subtract", Nz::Keyboard::Subtract); - - state.PushField("Backslash", Nz::Keyboard::Backslash); - state.PushField("Backspace", Nz::Keyboard::Backspace); - state.PushField("Clear", Nz::Keyboard::Clear); - state.PushField("Comma", Nz::Keyboard::Comma); - state.PushField("Dash", Nz::Keyboard::Dash); - state.PushField("Delete", Nz::Keyboard::Delete); - state.PushField("End", Nz::Keyboard::End); - state.PushField("Equal", Nz::Keyboard::Equal); - state.PushField("Escape", Nz::Keyboard::Escape); - state.PushField("Home", Nz::Keyboard::Home); - state.PushField("Insert", Nz::Keyboard::Insert); - state.PushField("LAlt", Nz::Keyboard::LAlt); - state.PushField("LBracket", Nz::Keyboard::LBracket); - state.PushField("LControl", Nz::Keyboard::LControl); - state.PushField("LShift", Nz::Keyboard::LShift); - state.PushField("LSystem", Nz::Keyboard::LSystem); - state.PushField("PageDown", Nz::Keyboard::PageDown); - state.PushField("PageUp", Nz::Keyboard::PageUp); - state.PushField("Pause", Nz::Keyboard::Pause); - state.PushField("Period", Nz::Keyboard::Period); - state.PushField("Print", Nz::Keyboard::Print); - state.PushField("PrintScreen", Nz::Keyboard::PrintScreen); - state.PushField("Quote", Nz::Keyboard::Quote); - state.PushField("RAlt", Nz::Keyboard::RAlt); - state.PushField("RBracket", Nz::Keyboard::RBracket); - state.PushField("RControl", Nz::Keyboard::RControl); - state.PushField("Return", Nz::Keyboard::Return); - state.PushField("RShift", Nz::Keyboard::RShift); - state.PushField("RSystem", Nz::Keyboard::RSystem); - state.PushField("Semicolon", Nz::Keyboard::Semicolon); - state.PushField("Slash", Nz::Keyboard::Slash); - state.PushField("Space", Nz::Keyboard::Space); - state.PushField("Tab", Nz::Keyboard::Tab); - state.PushField("Tilde", Nz::Keyboard::Tilde); - state.PushField("Browser_Back", Nz::Keyboard::Browser_Back); - state.PushField("Browser_Favorites", Nz::Keyboard::Browser_Favorites); - state.PushField("Browser_Forward", Nz::Keyboard::Browser_Forward); - state.PushField("Browser_Home", Nz::Keyboard::Browser_Home); - state.PushField("Browser_Refresh", Nz::Keyboard::Browser_Refresh); - state.PushField("Browser_Search", Nz::Keyboard::Browser_Search); - state.PushField("Browser_Stop", Nz::Keyboard::Browser_Stop); - state.PushField("Media_Next", Nz::Keyboard::Media_Next); - state.PushField("Media_Play", Nz::Keyboard::Media_Play); - state.PushField("Media_Previous", Nz::Keyboard::Media_Previous); - state.PushField("Media_Stop", Nz::Keyboard::Media_Stop); - state.PushField("Volume_Down", Nz::Keyboard::Volume_Down); - state.PushField("Volume_Mute", Nz::Keyboard::Volume_Mute); - state.PushField("Volume_Up", Nz::Keyboard::Volume_Up); - state.PushField("CapsLock", Nz::Keyboard::CapsLock); - state.PushField("NumLock", Nz::Keyboard::NumLock); - state.PushField("ScrollLock", Nz::Keyboard::ScrollLock); - } - state.Pop(); - - static_assert(Nz::WindowStyle_Max + 1 == 6, "Nz::WindowStyle has been updated but change was not reflected to Lua binding"); - state.PushTable(0, Nz::WindowStyle_Max + 1); - { - state.PushField("None", Nz::WindowStyle_None); - state.PushField("Fullscreen", Nz::WindowStyle_Fullscreen); - state.PushField("Closable", Nz::WindowStyle_Closable); - state.PushField("Resizable", Nz::WindowStyle_Resizable); - state.PushField("Titlebar", Nz::WindowStyle_Titlebar); - state.PushField("Threaded", Nz::WindowStyle_Threaded); - } - state.SetGlobal("WindowStyle"); } } diff --git a/SDK/src/NDK/Resources/checkmark.png.h b/SDK/src/NDK/Resources/checkmark.png.h new file mode 100644 index 000000000..644161149 --- /dev/null +++ b/SDK/src/NDK/Resources/checkmark.png.h @@ -0,0 +1 @@ +137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,133,0,0,0,138,8,6,0,0,0,132,140,137,233,0,0,0,6,98,75,71,68,0,255,0,255,0,255,160,189,167,147,0,0,0,9,112,72,89,115,0,0,11,19,0,0,11,19,1,0,154,156,24,0,0,0,7,116,73,77,69,7,225,8,14,14,24,3,208,239,186,156,0,0,0,29,105,84,88,116,67,111,109,109,101,110,116,0,0,0,0,0,67,114,101,97,116,101,100,32,119,105,116,104,32,71,73,77,80,100,46,101,7,0,0,6,196,73,68,65,84,120,218,237,157,125,172,143,101,24,199,63,199,251,33,135,136,232,197,176,70,50,105,147,90,167,49,165,161,204,50,147,151,82,44,217,26,90,141,169,182,214,106,42,42,36,189,140,106,42,170,63,196,42,127,136,229,101,52,53,83,35,33,47,203,41,9,181,157,18,149,151,195,113,250,227,121,112,58,167,56,63,231,119,95,191,235,62,190,159,237,254,211,126,183,239,245,61,207,243,220,247,125,221,215,5,66,84,32,79,18,92,16,92,4,52,7,242,203,141,218,192,49,224,32,176,23,248,75,166,168,153,180,7,186,165,163,11,208,6,184,2,104,122,142,127,87,6,236,4,222,1,102,72,198,184,105,0,244,7,222,0,246,165,193,173,238,120,77,178,198,251,68,120,9,248,35,75,70,40,63,182,74,222,184,104,11,124,8,148,6,48,195,169,241,186,100,142,231,53,49,25,56,18,208,12,101,233,135,103,59,201,29,199,171,98,99,96,51,156,26,79,75,110,255,244,3,14,24,25,98,35,80,79,146,251,166,127,250,56,183,48,196,159,64,71,73,238,155,190,192,81,35,67,148,1,67,37,185,111,186,166,127,185,86,134,152,38,201,125,211,26,248,201,208,16,159,2,181,36,187,95,242,129,175,12,13,177,29,104,34,217,253,146,7,44,50,52,196,1,160,131,100,247,205,115,134,134,56,145,46,117,133,99,134,27,26,162,12,152,40,201,125,211,157,240,91,215,229,199,60,73,238,155,203,72,146,91,172,12,177,14,168,47,217,253,210,0,88,111,104,136,189,233,114,87,56,102,190,161,33,142,164,175,41,225,152,9,198,31,150,35,36,185,111,122,167,75,66,43,67,188,40,201,125,211,14,40,70,91,216,34,165,33,176,201,208,16,219,208,22,182,123,222,71,91,216,162,28,15,27,26,162,20,184,93,146,251,166,7,112,220,208,20,79,74,114,223,180,6,246,27,26,98,49,186,241,231,154,186,192,90,67,67,236,0,10,36,187,111,102,26,26,226,16,208,73,146,251,102,48,182,59,150,131,36,185,111,58,164,127,185,86,134,152,34,201,253,111,80,109,54,52,196,50,180,99,233,158,121,134,134,40,2,154,73,114,223,140,54,52,196,97,146,187,33,194,49,93,210,64,89,153,226,30,73,238,155,70,36,135,79,86,134,152,41,201,253,99,121,208,181,26,168,35,201,125,243,128,161,33,246,0,45,37,185,111,58,27,126,71,28,3,110,144,228,190,201,39,41,22,102,245,148,24,43,201,253,243,150,161,33,62,144,220,254,25,106,104,136,173,233,234,70,56,166,61,73,201,98,171,114,67,58,249,116,78,93,108,111,116,13,147,228,254,121,193,208,16,175,74,110,255,244,38,108,133,219,138,151,128,85,182,208,57,205,177,187,25,94,76,82,117,95,56,103,177,145,33,78,162,234,50,81,48,206,240,59,98,178,228,246,207,53,216,109,99,47,71,25,84,238,169,135,93,129,244,61,64,11,73,238,159,233,70,134,40,1,10,37,119,28,203,207,147,70,166,120,68,114,251,167,25,240,179,145,33,22,73,238,56,88,104,100,136,93,168,118,68,20,220,135,93,194,204,245,146,219,63,109,8,211,181,79,223,17,145,146,7,172,194,174,84,128,136,128,137,70,134,216,141,110,116,69,65,103,108,90,50,29,215,126,68,28,212,197,110,215,242,113,201,29,7,86,253,53,150,161,146,67,81,112,35,54,85,111,247,162,115,141,40,200,39,233,157,101,81,186,176,151,228,142,131,89,70,175,141,167,36,117,28,244,194,230,176,107,21,202,143,136,130,198,192,143,6,134,248,21,53,91,137,134,55,177,201,179,236,35,169,227,160,143,209,119,196,84,73,29,7,5,216,180,137,94,135,10,138,68,195,92,3,67,28,34,185,103,42,34,160,159,209,107,227,94,73,29,7,77,72,50,165,85,63,66,156,230,109,3,67,20,161,202,249,209,208,23,155,227,240,155,36,117,60,155,84,187,13,76,161,14,60,17,49,199,192,16,159,163,109,236,104,184,149,240,103,27,7,80,185,128,104,104,148,126,248,133,126,74,220,117,33,136,89,157,93,184,75,72,186,233,21,2,151,147,20,248,248,13,88,153,46,213,142,26,254,63,166,146,116,8,14,189,162,89,168,191,191,202,52,0,238,6,86,156,227,81,253,61,112,173,209,156,10,9,95,126,104,7,42,95,88,137,124,146,139,44,153,180,84,60,0,116,12,60,175,250,132,175,162,95,2,116,147,5,206,144,7,140,2,246,157,167,160,155,73,50,167,67,97,145,128,59,73,54,56,195,213,192,151,89,16,117,66,160,249,117,37,124,119,224,229,40,27,251,52,227,201,94,121,159,95,210,199,124,54,169,13,124,77,248,106,117,202,162,34,41,237,243,110,0,129,71,102,121,158,143,25,188,54,6,203,14,137,33,150,4,124,12,103,139,171,8,95,164,108,190,236,144,16,178,245,81,41,208,42,75,243,92,73,248,203,192,58,253,76,31,239,161,31,199,15,101,97,158,247,163,75,60,102,27,82,22,165,134,215,86,115,158,151,2,191,7,158,227,116,217,33,225,78,108,210,214,78,2,87,86,99,158,11,2,207,239,219,0,171,164,40,169,133,93,178,72,30,231,223,104,117,0,48,36,224,220,74,128,17,36,53,169,4,54,23,101,202,183,64,202,148,198,132,207,183,124,84,54,248,55,211,12,77,81,70,230,213,225,94,9,60,159,53,40,105,166,18,99,141,77,49,59,131,185,117,39,236,9,232,65,160,173,44,80,153,94,198,166,56,72,213,142,161,235,0,223,4,158,203,40,133,255,191,41,192,174,29,210,169,49,166,10,243,154,20,120,14,31,41,244,103,103,139,177,41,182,156,99,62,109,129,191,3,254,254,126,146,204,49,113,22,102,27,155,162,12,184,227,44,243,89,154,195,223,22,41,67,114,96,138,245,255,51,151,225,129,127,119,142,194,93,53,90,96,215,231,162,252,168,184,153,213,145,176,93,130,119,161,92,203,140,216,144,3,83,20,3,29,210,223,47,228,252,211,254,170,186,205,222,83,97,206,140,41,57,48,197,169,190,222,155,13,126,103,150,66,156,57,61,114,100,10,139,177,19,104,168,16,103,78,109,146,203,60,53,205,16,165,192,205,10,111,213,41,191,231,95,154,46,5,107,26,51,129,47,20,234,184,150,166,33,199,54,146,36,34,81,13,10,72,114,10,106,130,33,78,144,20,103,23,89,96,105,13,49,197,243,10,101,246,24,83,3,12,177,5,165,214,101,149,150,216,159,154,102,187,30,149,218,60,6,96,117,196,166,120,70,225,11,195,248,72,13,177,137,176,183,220,47,104,90,69,248,10,41,1,174,83,232,194,178,38,50,83,168,27,143,1,227,34,50,196,6,84,69,95,175,144,10,171,141,174,10,151,29,43,34,48,197,179,10,147,45,163,157,27,226,59,109,82,217,115,49,126,207,66,74,81,209,244,156,241,137,83,83,188,172,208,228,142,129,14,13,81,132,18,112,115,74,29,146,126,155,158,76,113,155,194,146,123,102,56,50,196,92,133,195,7,29,201,205,189,144,138,99,31,208,84,225,240,195,103,14,76,49,80,97,240,197,128,28,27,98,129,66,224,143,90,192,246,28,25,162,152,36,249,71,56,100,100,142,76,49,66,210,251,94,158,22,25,27,98,137,100,247,207,48,67,67,28,162,122,181,55,133,33,107,141,76,241,160,164,142,135,78,132,175,164,175,213,70,132,132,188,31,242,30,74,192,141,150,39,178,108,134,173,192,32,201,26,63,183,0,31,3,63,144,121,79,175,195,192,58,146,179,149,158,168,95,151,11,254,1,48,107,33,165,213,10,148,99,0,0,0,0,73,69,78,68,174,66,96,130, \ No newline at end of file diff --git a/SDK/src/NDK/Sdk.cpp b/SDK/src/NDK/Sdk.cpp index 312e9a777..ee3764224 100644 --- a/SDK/src/NDK/Sdk.cpp +++ b/SDK/src/NDK/Sdk.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -34,6 +35,7 @@ #include #include #include +#include #endif namespace Ndk @@ -63,13 +65,6 @@ namespace Ndk // Initialize the engine first // Shared modules - #ifdef NDK_SERVER - Nz::ParameterList parameters; - parameters.SetParameter("NoWindowSystem", true); - - Nz::Utility::SetParameters(parameters); - #endif - Nz::Lua::Initialize(); Nz::Noise::Initialize(); Nz::Physics2D::Initialize(); @@ -119,6 +114,13 @@ namespace Ndk InitializeSystem(); InitializeSystem(); InitializeSystem(); + + // Widgets + if (!CheckboxWidget::Initialize()) + { + NazaraError("Failed to initialize Checkbox Widget"); + return false; + } #endif NazaraNotice("Initialized: SDK"); @@ -127,7 +129,6 @@ namespace Ndk catch (const std::exception& e) { NazaraError("Failed to initialize NDK: " + Nz::String(e.what())); - return false; } } @@ -173,6 +174,11 @@ namespace Ndk Nz::Physics3D::Uninitialize(); Nz::Utility::Uninitialize(); + #ifndef NDK_SERVER + // Widgets + CheckboxWidget::Uninitialize(); + #endif + NazaraNotice("Uninitialized: SDK"); } diff --git a/SDK/src/NDK/Systems/RenderSystem.cpp b/SDK/src/NDK/Systems/RenderSystem.cpp index 603dda022..6b745dfc3 100644 --- a/SDK/src/NDK/Systems/RenderSystem.cpp +++ b/SDK/src/NDK/Systems/RenderSystem.cpp @@ -4,6 +4,8 @@ #include #include +#include +#include #include #include #include @@ -37,7 +39,7 @@ namespace Ndk ChangeRenderTechnique(); SetDefaultBackground(Nz::ColorBackground::New()); SetUpdateOrder(100); //< Render last, after every movement is done - SetUpdateRate(0.f); //< We don't want any rate limit + SetMaximumUpdateRate(0.f); //< We don't want any rate limit } /*! diff --git a/SDK/src/NDK/Widgets/ButtonWidget.cpp b/SDK/src/NDK/Widgets/ButtonWidget.cpp index 29c04c98f..35e781992 100644 --- a/SDK/src/NDK/Widgets/ButtonWidget.cpp +++ b/SDK/src/NDK/Widgets/ButtonWidget.cpp @@ -5,17 +5,29 @@ #include #include #include -#include namespace Ndk { + Nz::Color ButtonWidget::s_color { 74, 74, 74 }; + Nz::Color ButtonWidget::s_cornerColor { 180, 180, 180 }; + Nz::Color ButtonWidget::s_hoverColor { 128, 128, 128 }; + Nz::Color ButtonWidget::s_hoverCornerColor { s_cornerColor }; + Nz::Color ButtonWidget::s_pressColor { s_cornerColor }; + Nz::Color ButtonWidget::s_pressCornerColor { s_color }; + ButtonWidget::ButtonWidget(BaseWidget* parent) : - BaseWidget(parent) + BaseWidget(parent), + m_color { s_color }, + m_cornerColor { s_cornerColor }, + m_hoverColor { s_hoverColor }, + m_hoverCornerColor { s_hoverCornerColor }, + m_pressColor { s_pressColor }, + m_pressCornerColor { s_pressCornerColor } { m_gradientSprite = Nz::Sprite::New(); - m_gradientSprite->SetColor(Nz::Color(74, 74, 74)); - m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, Nz::Color(180, 180, 180)); - m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, Nz::Color(180, 180, 180)); + m_gradientSprite->SetColor(m_color); + m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_cornerColor); + m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_cornerColor); m_gradientSprite->SetMaterial(Nz::Material::New("Basic2D")); m_gradientEntity = CreateEntity(); @@ -31,6 +43,36 @@ namespace Ndk Layout(); } + const Nz::Color& ButtonWidget::GetDefaultColor() + { + return s_color; + } + + const Nz::Color& ButtonWidget::GetDefaultCornerColor() + { + return s_cornerColor; + } + + const Nz::Color& ButtonWidget::GetDefaultHoverColor() + { + return s_hoverColor; + } + + const Nz::Color& ButtonWidget::GetDefaultHoverCornerColor() + { + return s_hoverCornerColor; + } + + const Nz::Color& ButtonWidget::GetDefaultPressColor() + { + return s_pressColor; + } + + const Nz::Color& ButtonWidget::GetDefaultPressCornerColor() + { + return s_pressCornerColor; + } + void ButtonWidget::ResizeToContent() { SetContentSize(Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths())); @@ -46,24 +88,47 @@ namespace Ndk m_gradientEntity->GetComponent().SetPosition(origin); m_gradientSprite->SetSize(contentSize); - Nz::Boxf textBox = m_textEntity->GetComponent().GetBoundingVolume().aabb; + Nz::Boxf textBox = m_textEntity->GetComponent().GetBoundingVolume().obb.localBox; m_textEntity->GetComponent().SetPosition(origin.x + contentSize.x / 2 - textBox.width / 2, origin.y + contentSize.y / 2 - textBox.height / 2); } + void ButtonWidget::OnMouseButtonPress(int /*x*/, int /*y*/, Nz::Mouse::Button button) + { + if (button == Nz::Mouse::Left) + { + m_gradientSprite->SetColor(m_pressColor); + m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_pressCornerColor); + m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_pressCornerColor); + m_gradientSprite->SetTexture(m_pressTexture, false); + } + } + void ButtonWidget::OnMouseButtonRelease(int /*x*/, int /*y*/, Nz::Mouse::Button button) { if (button == Nz::Mouse::Left) + { + m_gradientSprite->SetColor(m_hoverColor); + m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_hoverCornerColor); + m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_hoverCornerColor); + m_gradientSprite->SetTexture(m_hoverTexture, false); + OnButtonTrigger(this); + } } void ButtonWidget::OnMouseEnter() { - m_gradientSprite->SetColor(Nz::Color(128, 128, 128)); + m_gradientSprite->SetColor(m_hoverColor); + m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_hoverCornerColor); + m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_hoverCornerColor); + m_gradientSprite->SetTexture(m_hoverTexture, false); } - void ButtonWidget::OnMouseExit() { - m_gradientSprite->SetColor(Nz::Color(74, 74, 74)); + m_gradientSprite->SetColor(m_color); + m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_cornerColor); + m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_cornerColor); + m_gradientSprite->SetTexture(m_texture, false); } } diff --git a/SDK/src/NDK/Widgets/CheckboxWidget.cpp b/SDK/src/NDK/Widgets/CheckboxWidget.cpp new file mode 100644 index 000000000..ab513c7f8 --- /dev/null +++ b/SDK/src/NDK/Widgets/CheckboxWidget.cpp @@ -0,0 +1,181 @@ +// Copyright (C) 2017 Samy Bensaid +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequesites.hpp + +#include +#include +#include +#include + +namespace Ndk +{ + Nz::Color CheckboxWidget::s_backgroundColor { Nz::Color::White }; + Nz::Color CheckboxWidget::s_disabledBackgroundColor { 201, 201, 201 }; + Nz::Color CheckboxWidget::s_disabledBorderColor { 62, 62, 62 }; + Nz::Color CheckboxWidget::s_borderColor { Nz::Color::Black }; + float CheckboxWidget::s_borderScale { 16.f }; + + CheckboxWidget::CheckboxWidget(BaseWidget* parent) : + BaseWidget(parent), + m_adaptativeMargin { true }, + m_checkboxEnabled { true }, + m_tristateEnabled { false }, + m_textMargin { 16.f }, + m_state { CheckboxState_Unchecked } + { + m_checkboxBorderSprite = Nz::Sprite::New(Nz::Material::New("Basic2D")); + m_checkboxBackgroundSprite = Nz::Sprite::New(Nz::Material::New("Basic2D")); + m_checkboxContentSprite = Nz::Sprite::New(Nz::Material::New("Translucent2D")); + m_textSprite = Nz::TextSprite::New(); + + m_checkboxBorderEntity = CreateEntity(); + m_checkboxBorderEntity->AddComponent().SetParent(this); + m_checkboxBorderEntity->AddComponent().Attach(m_checkboxBorderSprite); + + m_checkboxBackgroundEntity = CreateEntity(); + m_checkboxBackgroundEntity->AddComponent().SetParent(this); + m_checkboxBackgroundEntity->AddComponent().Attach(m_checkboxBackgroundSprite, 1); + + m_checkboxContentEntity = CreateEntity(); + m_checkboxContentEntity->AddComponent().SetParent(this); + m_checkboxContentEntity->AddComponent().Attach(m_checkboxContentSprite, 2); + + m_textEntity = CreateEntity(); + m_textEntity->AddComponent().SetParent(this); + m_textEntity->AddComponent().Attach(m_textSprite); + + m_checkMark = Nz::TextureLibrary::Get("Ndk::CheckboxWidget::checkmark"); + + SetCheckboxSize({ 32.f, 32.f }); + UpdateCheckbox(); + } + + bool CheckboxWidget::Initialize() + { + const Nz::UInt8 r_checkmark[] = + { + #include + }; + + Nz::TextureRef checkmarkTexture = Nz::Texture::New(); + if (!checkmarkTexture->LoadFromMemory(r_checkmark, sizeof(r_checkmark) / sizeof(r_checkmark[0]))) + { + NazaraError("Failed to load embedded checkmark"); + return false; + } + + Nz::TextureLibrary::Register("Ndk::CheckboxWidget::checkmark", checkmarkTexture); + return true; + } + + void CheckboxWidget::Uninitialize() + { + Nz::TextureLibrary::Unregister("Ndk::CheckboxWidget::checkmark"); + } + + void CheckboxWidget::SetState(CheckboxState state) + { + if (!m_checkboxEnabled) + return; + + if (state == CheckboxState_Tristate) + m_tristateEnabled = true; + + m_state = state; + UpdateCheckbox(); + } + + CheckboxState CheckboxWidget::SwitchToNextState() + { + if (!m_checkboxEnabled) + return m_state; + + switch (m_state) + { + case CheckboxState_Unchecked: + SetState(CheckboxState_Checked); + break; + + case CheckboxState_Checked: + SetState(m_tristateEnabled ? CheckboxState_Tristate : CheckboxState_Unchecked); + break; + + case CheckboxState_Tristate: + SetState(CheckboxState_Unchecked); + break; + } + + return m_state; + } + + void CheckboxWidget::ResizeToContent() + { + Nz::Vector3f textSize = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths(); + Nz::Vector2f checkboxSize = GetCheckboxSize(); + + Nz::Vector2f finalSize { checkboxSize.x + (m_adaptativeMargin ? checkboxSize.x / 2.f : m_textMargin) + textSize.x, std::max(textSize.y, checkboxSize.y) }; + SetContentSize(finalSize); + } + + void CheckboxWidget::Layout() + { + BaseWidget::Layout(); + + Nz::Vector2f origin = GetContentOrigin(); + Nz::Vector2f checkboxSize = GetCheckboxSize(); + Nz::Vector2f borderSize = GetCheckboxBorderSize(); + + m_checkboxBorderEntity->GetComponent().SetPosition(origin); + m_checkboxBackgroundEntity->GetComponent().SetPosition(origin + borderSize); + + Nz::Vector3f checkboxBox = m_checkboxContentSprite->GetBoundingVolume().obb.localBox.GetLengths(); + m_checkboxContentEntity->GetComponent().SetPosition(origin.x + checkboxSize.x / 2.f - checkboxBox.x / 2.f, + origin.y + checkboxSize.y / 2.f - checkboxBox.y / 2.f); + + Nz::Vector3f textBox = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths(); + m_textEntity->GetComponent().SetPosition(origin.x + checkboxSize.x + (m_adaptativeMargin ? checkboxSize.x / 2.f : m_textMargin), + origin.y + checkboxSize.y / 2.f - textBox.y / 2.f); + } + + void CheckboxWidget::OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) + { + if (button == Nz::Mouse::Left && ContainsCheckbox(x, y) && IsCheckboxEnabled()) + { + SwitchToNextState(); + OnStateChanged(this); + } + } + + void CheckboxWidget::UpdateCheckbox() + { + if (m_checkboxEnabled) + { + m_checkboxBorderSprite->SetColor(s_borderColor); + m_checkboxBackgroundSprite->SetColor(s_backgroundColor); + } + else + { + m_checkboxBorderSprite->SetColor(s_disabledBorderColor); + m_checkboxBackgroundSprite->SetColor(s_disabledBackgroundColor); + } + + + if (m_state == CheckboxState_Unchecked) + { + m_checkboxContentEntity->Enable(false); + return; + } + else if (m_state == CheckboxState_Checked) + { + m_checkboxContentEntity->Enable(); + m_checkboxContentSprite->SetColor(Nz::Color::White); + m_checkboxContentSprite->SetTexture(m_checkMark, false); + } + else // Tristate + { + m_checkboxContentEntity->Enable(); + m_checkboxContentSprite->SetColor(Nz::Color::Black); + m_checkboxContentSprite->SetTexture(Nz::TextureRef {}); + } + } +} diff --git a/SDK/src/NDK/Widgets/LabelWidget.cpp b/SDK/src/NDK/Widgets/LabelWidget.cpp index 7e4cdf840..ae05450de 100644 --- a/SDK/src/NDK/Widgets/LabelWidget.cpp +++ b/SDK/src/NDK/Widgets/LabelWidget.cpp @@ -5,7 +5,6 @@ #include #include #include -#include namespace Ndk { diff --git a/SDK/src/NDK/Widgets/ProgressBarWidget.cpp b/SDK/src/NDK/Widgets/ProgressBarWidget.cpp new file mode 100644 index 000000000..7ad293539 --- /dev/null +++ b/SDK/src/NDK/Widgets/ProgressBarWidget.cpp @@ -0,0 +1,102 @@ +// Copyright (C) 2017 Samy Bensaid +// This file is part of the "Nazara Development Kit" +// For conditions of distribution and use, see copyright notice in Prerequesites.hpp + +#include +#include +#include + +namespace Ndk +{ + float ProgressBarWidget::s_borderScale { 16.f }; + Nz::Color ProgressBarWidget::s_borderColor { Nz::Color::Black }; + Nz::Color ProgressBarWidget::s_barBackgroundColor { Nz::Color { 225, 225, 225 } }; + Nz::Color ProgressBarWidget::s_barBackgroundCornerColor { Nz::Color { 255, 255, 255 } }; + Nz::Color ProgressBarWidget::s_barColor { Nz::Color { 0, 225, 0 } }; + Nz::Color ProgressBarWidget::s_barCornerColor { Nz::Color { 220, 255, 220 } }; + + ProgressBarWidget::ProgressBarWidget(BaseWidget* parent) : + BaseWidget(parent), + m_textColor { Nz::Color::Black }, + m_textMargin { 16.f }, + m_value { 0u } + { + m_borderSprite = Nz::Sprite::New(Nz::Material::New("Basic2D")); + m_barBackgroundSprite = Nz::Sprite::New(Nz::Material::New("Basic2D")); + m_barSprite = Nz::Sprite::New(Nz::Material::New("Basic2D")); + + m_borderSprite->SetColor(s_borderColor); + SetBarBackgroundColor(s_barBackgroundColor, s_barBackgroundCornerColor); + SetBarColor(s_barColor, s_barCornerColor); + + + m_borderEntity = CreateEntity(); + m_borderEntity->AddComponent().SetParent(this); + m_borderEntity->AddComponent().Attach(m_borderSprite); + + m_barEntity = CreateEntity(); + m_barEntity->AddComponent().SetParent(this); + GraphicsComponent& graphics = m_barEntity->AddComponent(); + + graphics.Attach(m_barBackgroundSprite, 1); + graphics.Attach(m_barSprite, 2); + + + m_textSprite = Nz::TextSprite::New(); + m_textEntity = CreateEntity(); + + m_textEntity->AddComponent().SetParent(this); + m_textEntity->AddComponent().Attach(m_textSprite); + + UpdateText(); + Layout(); + } + + + const Nz::Color& ProgressBarWidget::GetDefaultBarColor() + { + return s_barColor; + } + + const Nz::Color& ProgressBarWidget::GetDefaultBarCornerColor() + { + return s_barCornerColor; + } + + const Nz::Color& ProgressBarWidget::GetDefaultBarBackgroundColor() + { + return s_barBackgroundColor; + } + + const Nz::Color& ProgressBarWidget::GetDefaultBarBackgroundCornerColor() + { + return s_barBackgroundCornerColor; + } + + + void ProgressBarWidget::Layout() + { + Nz::Vector2f origin = GetContentOrigin(); + Nz::Vector2f size = GetContentSize(); + Nz::Vector2f progressBarSize = size; + + if (IsTextEnabled()) + { + UpdateText(); + + Nz::Vector3f textSize = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths(); + m_textEntity->GetComponent().SetPosition(origin.x + size.x - textSize.x, origin.y + size.y / 2.f - textSize.y); + + progressBarSize -= { textSize.x + m_textMargin, 0.f }; + } + + m_borderSprite->SetSize(progressBarSize); + Nz::Vector2f borderSize = GetProgressBarBorderSize(); + + m_barBackgroundSprite->SetSize(progressBarSize - (borderSize * 2.f)); + m_barSprite->SetSize((progressBarSize.x - (borderSize.x * 2.f)) / 100.f * static_cast(m_value), progressBarSize.y - (borderSize.y * 2.f)); + + m_borderEntity->GetComponent().SetPosition(origin.x, origin.y); + m_barEntity->GetComponent().SetPosition(origin.x + borderSize.x, origin.y + borderSize.y); + } +} diff --git a/SDK/src/NDK/Widgets/TextAreaWidget.cpp b/SDK/src/NDK/Widgets/TextAreaWidget.cpp index 932757621..da59f45ff 100644 --- a/SDK/src/NDK/Widgets/TextAreaWidget.cpp +++ b/SDK/src/NDK/Widgets/TextAreaWidget.cpp @@ -6,14 +6,13 @@ #include #include #include -#include -#include namespace Ndk { TextAreaWidget::TextAreaWidget(BaseWidget* parent) : BaseWidget(parent), - m_cursorPosition(0U), + m_cursorPosition(0U, 0U), + m_cursorGlyph(0), m_multiLineEnabled(false), m_readOnly(false) { @@ -81,7 +80,7 @@ namespace Ndk void TextAreaWidget::Write(const Nz::String& text) { - if (m_cursorPosition >= m_drawer.GetGlyphCount()) + if (m_cursorGlyph >= m_drawer.GetGlyphCount()) { AppendText(text); SetCursorPosition(m_drawer.GetGlyphCount()); @@ -89,10 +88,10 @@ namespace Ndk else { Nz::String currentText = m_drawer.GetText(); - currentText.Insert(currentText.GetCharacterPosition(m_cursorPosition), text); + currentText.Insert(currentText.GetCharacterPosition(m_cursorGlyph), text); SetText(currentText); - SetCursorPosition(m_cursorPosition + text.GetLength()); + SetCursorPosition(m_cursorGlyph + text.GetLength()); } } @@ -114,11 +113,11 @@ namespace Ndk const Nz::String& text = m_drawer.GetText(); Nz::String newText; - if (m_cursorPosition > 0) - newText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorPosition) - 1)); + if (m_cursorGlyph > 0) + newText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorGlyph) - 1)); - if (m_cursorPosition < m_drawer.GetGlyphCount()) - newText.Append(text.SubString(text.GetCharacterPosition(m_cursorPosition + 1))); + if (m_cursorGlyph < m_drawer.GetGlyphCount()) + newText.Append(text.SubString(text.GetCharacterPosition(m_cursorGlyph + 1))); m_drawer.SetText(newText); m_textSprite->Update(m_drawer); @@ -133,7 +132,7 @@ namespace Ndk if (ignoreDefaultAction) break; - //TODO + MoveCursor({0, 1}); break; } @@ -145,7 +144,7 @@ namespace Ndk if (ignoreDefaultAction) break; - MoveCursor(-1); + MoveCursor({-1, 0}); break; } @@ -157,7 +156,7 @@ namespace Ndk if (ignoreDefaultAction) break; - MoveCursor(1); + MoveCursor({1, 0}); break; } @@ -169,13 +168,16 @@ namespace Ndk if (ignoreDefaultAction) break; - //TODO + MoveCursor({0, -1}); break; } + + default: + break; } } - void TextAreaWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& key) + void TextAreaWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& /*key*/) { } @@ -194,7 +196,7 @@ namespace Ndk } } - void TextAreaWidget::OnMouseMoved(int x, int y, int deltaX, int deltaY) + void TextAreaWidget::OnMouseMoved(int x, int y, int /*deltaX*/, int /*deltaY*/) { } @@ -221,13 +223,13 @@ namespace Ndk const Nz::String& text = m_drawer.GetText(); Nz::String newText; - if (m_cursorPosition > 1) - newText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorPosition - 1) - 1)); + if (m_cursorGlyph > 1) + newText.Append(text.SubString(0, text.GetCharacterPosition(m_cursorGlyph - 1) - 1)); - if (m_cursorPosition < m_drawer.GetGlyphCount()) - newText.Append(text.SubString(text.GetCharacterPosition(m_cursorPosition))); + if (m_cursorGlyph < m_drawer.GetGlyphCount()) + newText.Append(text.SubString(text.GetCharacterPosition(m_cursorGlyph))); - MoveCursor(-1); + MoveCursor({-1, 0}); SetText(newText); break; } @@ -258,25 +260,15 @@ namespace Ndk void TextAreaWidget::RefreshCursor() { - std::size_t lineCount = m_drawer.GetLineCount(); - std::size_t line = 0U; - for (std::size_t i = line + 1; i < lineCount; ++i) - { - if (m_drawer.GetLine(i).glyphIndex > m_cursorPosition) - break; - - line = i; - } - - const auto& lineInfo = m_drawer.GetLine(line); + const auto& lineInfo = m_drawer.GetLine(m_cursorPosition.y); std::size_t glyphCount = m_drawer.GetGlyphCount(); float position; - if (glyphCount > 0 && lineInfo.glyphIndex < m_cursorPosition) + if (glyphCount > 0 && lineInfo.glyphIndex < m_cursorGlyph) { - const auto& glyph = m_drawer.GetGlyph(std::min(m_cursorPosition, glyphCount - 1)); + const auto& glyph = m_drawer.GetGlyph(std::min(m_cursorGlyph, glyphCount - 1)); position = glyph.bounds.x; - if (m_cursorPosition >= glyphCount) + if (m_cursorGlyph >= glyphCount) position += glyph.bounds.width; } else diff --git a/SDK/src/NDK/World.cpp b/SDK/src/NDK/World.cpp index 3ed1a25d0..702452fc4 100644 --- a/SDK/src/NDK/World.cpp +++ b/SDK/src/NDK/World.cpp @@ -119,6 +119,7 @@ namespace Ndk // This is made to avoid that handle warn uselessly entities before their destruction m_entities.clear(); m_entityBlocks.clear(); + m_freeIdList.clear(); m_waitingEntities.clear(); m_aliveEntities.Clear(); diff --git a/build/Build_VS2017.bat b/build/Build_VS2017.bat new file mode 100644 index 000000000..b569c559d --- /dev/null +++ b/build/Build_VS2017.bat @@ -0,0 +1 @@ +premake5 vs2017 \ No newline at end of file diff --git a/build/config.lua b/build/config.lua index 12a9f8e77..571bf6dc9 100644 --- a/build/config.lua +++ b/build/config.lua @@ -16,6 +16,9 @@ Configurations = "Debug,Release" -- "Debug,Release,ReleaseWithDebug" -- Setup additionnals install directories, separated by a semi-colon ; (library binaries will be copied there) --InstallDir = "/usr/local/lib64" +-- Adds a project which will recall premake with its original arguments when built (only works on Windows for now) +PremakeProject = false + -- Excludes client-only modules/tools/examples ServerMode = false diff --git a/build/scripts/actions/encodesresources.lua b/build/scripts/actions/encodesresources.lua index 5e5376fee..f508c5c69 100644 --- a/build/scripts/actions/encodesresources.lua +++ b/build/scripts/actions/encodesresources.lua @@ -5,8 +5,14 @@ ACTION.Function = function () print("Encoding resources ...") local startClock = os.clock() local modules = os.matchdirs("../src/Nazara/*") + table.insert(modules, "../SDK/src/NDK") for k, modulePath in pairs(modules) do - local moduleName = modulePath:sub(15, -1) + local moduleName + if (modulePath:sub(4, 6) == "src") then + moduleName = modulePath:sub(15, -1) + else + moduleName = "SDK" + end local files = os.matchfiles(modulePath .. "/Resources/**") for k, filePath in pairs(files) do if (filePath:sub(-2) ~= ".h") then diff --git a/build/scripts/actions/package.lua b/build/scripts/actions/package.lua index bc86c4ba4..0797d5441 100644 --- a/build/scripts/actions/package.lua +++ b/build/scripts/actions/package.lua @@ -203,5 +203,5 @@ ACTION.Function = function () end local config = libDir .. " - " .. enabledArchs - print(string.format("Package successfully created at \"%s\" (%u MB, %s)", packageDir, size / (1024 * 1024), config)) + print(string.format("Package successfully created at \"%s\" (%u MB, %s)", packageDir, size // (1024 * 1024), config)) end diff --git a/build/scripts/common.lua b/build/scripts/common.lua index ea7097e97..da9facd74 100644 --- a/build/scripts/common.lua +++ b/build/scripts/common.lua @@ -42,7 +42,7 @@ end function NazaraBuild:Execute() if (_ACTION == nil) then -- If no action is specified, the user probably only wants to know how all of this works - return -- Alors l'utilisateur voulait probablement savoir comment utiliser le programme, on ne fait rien + return end local platformData @@ -74,7 +74,6 @@ function NazaraBuild:Execute() includedirs("../extlibs/include") libdirs("../extlibs/lib/common") location(_ACTION) - kind("StaticLib") for k, libTable in ipairs(self.OrderedExtLibs) do project(libTable.Name) @@ -129,6 +128,13 @@ function NazaraBuild:Execute() language("C++") location(_ACTION) + if (self.Config["PremakeProject"] and os.ishost("windows")) then + local commandLine = "premake5.exe " .. table.concat(_ARGV, ' ') + project("_PremakeProject") + kind("Utility") + prebuildcommands("cd .. && " .. commandLine) + end + -- Modules if (_OPTIONS["united"]) then project("NazaraEngine") @@ -471,10 +477,8 @@ function NazaraBuild:LoadConfig() local content = f:read("*a") f:close() - local func, err = loadstring(content) + local func, err = load(content, "Config file", "t", self.Config) if (func) then - setfenv(func, self.Config) - local status, err = pcall(func) if (not status) then print("Failed to load config.lua: " .. err) @@ -517,9 +521,9 @@ function NazaraBuild:LoadConfig() end end - AddBoolOption("BuildDependencies", "with-extlibs", "Builds the extern libraries") AddBoolOption("BuildExamples", "with-examples", "Builds the examples") + AddBoolOption("PremakeProject", "premakeproject", "Add a PremakeProject as a shortcut to call Premake") AddBoolOption("ServerMode", "server", "Excludes client-only modules/tools/examples") AddBoolOption("UniteModules", "united", "Builds all the modules as one united library") @@ -601,7 +605,7 @@ function NazaraBuild:LoadConfig() end function NazaraBuild:MakeInstallCommands(infoTable) - if (os.is("windows")) then + if (os.istarget("windows")) then filter("kind:SharedLib") postbuildmessage("Copying " .. infoTable.Name .. " library and its dependencies to install/executable directories...") @@ -733,13 +737,13 @@ function NazaraBuild:Process(infoTable) for platform, defineTable in pairs(v) do platform = string.lower(platform) if (platform == "posix") then - local osname = os.get() + local osname = os.target() if (PosixOSes[osname]) then platform = osname end end - if (os.is(platform)) then + if (os.istarget(platform)) then for k,v in ipairs(defineTable) do table.insert(targetTable, v) end @@ -773,13 +777,14 @@ end function NazaraBuild:PrepareGeneric() flags({ - "C++14", "MultiProcessorCompile", "NoMinimalRebuild", "RelativeLinks", "ShadowedVariables", "UndefinedIdentifiers" }) + + cppdialect("C++14") self:FilterLibDirectory("../extlibs/lib/", libdirs) diff --git a/build/scripts/features/index_template.html b/build/scripts/features/index_template.html index 852811a4c..43bf5aea9 100644 --- a/build/scripts/features/index_template.html +++ b/build/scripts/features/index_template.html @@ -1,71 +1,71 @@ - - - - - - Avancement de Nazara - - -
- Nazara Engine - -
- - Retrouvez le moteur sur GitHub !
- Dépôt GitHub

- Venez vous renseigner sur les topics dédiés à Nazara présents sur plusieurs sites web :
- OpenClassrooms, Progdupeupl ou ZesteDeSavoir -

- ... ou pourquoi ne pas venir faire un tour sur le forum dédié au moteur ? - -
- -

Fonctionnalités de Nazara

- -
Dernière mise à jour : - %DATE% -
- -

Important:

-

Afin de faciliter la mise à jour, la page que vous voyez ici a été générée automatiquement par un script Lua, ce qui m'oblige néanmoins à encoder les fonctionnalités de chaque module dans un premier temps. - C'est un travail assez long (pour vous donner une idée, les données du noyau représentent un fichier de 200 lignes), et il n'est pas encore complet, c'est pourquoi des modules manquent sur cette page.
- Gardez donc à l'esprit que le moteur possède plus de fonctionnalités que ce qui est décrit actuellement sur cette page.

- -

Oh et bien sûr je ne suis pas concepteur de site web, c'est pourquoi cette page est moche (j'ai essayé de minimiser les dégâts).
- Si vous sentez en vous l'irrésistible envie d'améliorer cette page, sachez que votre aide serait grandement appréciée (vous pouvez me contacter via le lien de votre choix plus haut).

- -

Le pourcentage indiqué est calculé automatiquement en fonction des fonctionnalités, cela signifie qu'une fonctionnalité présente sera comptée à 100% à partir du moment où son implémentation de base est considérée fonctionnelle, cela n'est donc pas une assurance qu'aucun bug n'existe concernant cette fonctionnalité (cependant cela signifie que la fonctionnalité est utilisable).
- Et bien entendu, un module ou une fonctionnalité ayant atteint les 100% peut toujours évoluer par la suite.

- -
- - - - - - - - - - - %MODULELIST% - -
Sommaire
ModuleAvancement
- - %MODULEDESCRIPTION% -
- - - - - - - - - - %MODULELIST% - -
Sommaire
ModulePourcentage
-
- + + + + + + Avancement de Nazara + + +
+ Nazara Engine + +
+ + Retrouvez le moteur sur GitHub !
+ Dépôt GitHub

+ Venez vous renseigner sur les topics dédiés à Nazara présents sur plusieurs sites web :
+ OpenClassrooms, Progdupeupl ou ZesteDeSavoir +

+ ... ou pourquoi ne pas venir faire un tour sur le forum dédié au moteur ? + +
+ +

Fonctionnalités de Nazara

+ +
Dernière mise à jour : + %DATE% +
+ +

Important:

+

Afin de faciliter la mise à jour, la page que vous voyez ici a été générée automatiquement par un script Lua, ce qui m'oblige néanmoins à encoder les fonctionnalités de chaque module dans un premier temps. + C'est un travail assez long (pour vous donner une idée, les données du noyau représentent un fichier de 200 lignes), et il n'est pas encore complet, c'est pourquoi des modules manquent sur cette page.
+ Gardez donc à l'esprit que le moteur possède plus de fonctionnalités que ce qui est décrit actuellement sur cette page.

+ +

Oh et bien sûr je ne suis pas concepteur de site web, c'est pourquoi cette page est moche (j'ai essayé de minimiser les dégâts).
+ Si vous sentez en vous l'irrésistible envie d'améliorer cette page, sachez que votre aide serait grandement appréciée (vous pouvez me contacter via le lien de votre choix plus haut).

+ +

Le pourcentage indiqué est calculé automatiquement en fonction des fonctionnalités, cela signifie qu'une fonctionnalité présente sera comptée à 100% à partir du moment où son implémentation de base est considérée fonctionnelle, cela n'est donc pas une assurance qu'aucun bug n'existe concernant cette fonctionnalité (cependant cela signifie que la fonctionnalité est utilisable).
+ Et bien entendu, un module ou une fonctionnalité ayant atteint les 100% peut toujours évoluer par la suite.

+ +
+ + + + + + + + + + + %MODULELIST% + +
Sommaire
ModuleAvancement
+ + %MODULEDESCRIPTION% +
+ + + + + + + + + + %MODULELIST% + +
Sommaire
ModulePourcentage
+
+ \ No newline at end of file diff --git a/build/scripts/features/style.css b/build/scripts/features/style.css index 189b2a090..ff83f706c 100644 --- a/build/scripts/features/style.css +++ b/build/scripts/features/style.css @@ -1,121 +1,121 @@ -/* Je ne suis pas développeur HTML/CSS, je dois y toucher une fois l'an, désolé pour les quelques atrocités que vous pourrez trouver ici */ - -body -{ - font-family: sans-serif; - text-align: center; - margin: 0; - background-color: #f1f1f1; -} - -#englob { - display: block; - margin-left: auto; - margin-right: auto; - background-color: white; - width: 50%; - min-width: 765px; - padding: 0 20px; -} - -hr { - height: 0; - border: 0; - border-top: 1px solid #eee; -} - -a -{ - color: #007ACC; -} - -a:hover -{ - color: lightblue; -} - -h1 -{ - display: inline; -} - -h2 -{ - display: inline; - text-decoration: underline; -} - -h4 -{ - text-decoration: underline; -} - -p { - text-align: justify; -} - -ol -{ - list-style-type: none; -} - -table -{ - border-collapse: collapse; - text-align: center; - display: inline-block; - border: white groove; - border-radius: 10px; - box-shadow: 0px 0px 10px lightblue; -} - -th -{ - text-shadow: 2px 2px 4px black; -} - -tr -{ - border: 1px solid white; -} - -tbody tr:hover -{ - text-shadow: 0px 0px 4px white; -} - -.description -{ - margin-left: 20px; -} - -.lastupdate -{ - font-size: x-large; - font-weight: bold; - color: #f1c40f; -} - -.modulename -{ - font-size: x-large; - font-weight: bold; - text-shadow: 2px 2px 10px #007ACC; -} - -.note -{ - margin-left: 20px; - color: #007ACC; -} - -.notedesc -{ - color: rgb(200, 200, 255); -} - -.portability -{ - margin-left: 20px; - color: red; +/* Je ne suis pas développeur HTML/CSS, je dois y toucher une fois l'an, désolé pour les quelques atrocités que vous pourrez trouver ici */ + +body +{ + font-family: sans-serif; + text-align: center; + margin: 0; + background-color: #f1f1f1; +} + +#englob { + display: block; + margin-left: auto; + margin-right: auto; + background-color: white; + width: 50%; + min-width: 765px; + padding: 0 20px; +} + +hr { + height: 0; + border: 0; + border-top: 1px solid #eee; +} + +a +{ + color: #007ACC; +} + +a:hover +{ + color: lightblue; +} + +h1 +{ + display: inline; +} + +h2 +{ + display: inline; + text-decoration: underline; +} + +h4 +{ + text-decoration: underline; +} + +p { + text-align: justify; +} + +ol +{ + list-style-type: none; +} + +table +{ + border-collapse: collapse; + text-align: center; + display: inline-block; + border: white groove; + border-radius: 10px; + box-shadow: 0px 0px 10px lightblue; +} + +th +{ + text-shadow: 2px 2px 4px black; +} + +tr +{ + border: 1px solid white; +} + +tbody tr:hover +{ + text-shadow: 0px 0px 4px white; +} + +.description +{ + margin-left: 20px; +} + +.lastupdate +{ + font-size: x-large; + font-weight: bold; + color: #f1c40f; +} + +.modulename +{ + font-size: x-large; + font-weight: bold; + text-shadow: 2px 2px 10px #007ACC; +} + +.note +{ + margin-left: 20px; + color: #007ACC; +} + +.notedesc +{ + color: rgb(200, 200, 255); +} + +.portability +{ + margin-left: 20px; + color: red; } \ No newline at end of file diff --git a/build/scripts/modules/graphics.lua b/build/scripts/modules/graphics.lua index 9d393d3a7..5c0bf4224 100644 --- a/build/scripts/modules/graphics.lua +++ b/build/scripts/modules/graphics.lua @@ -3,5 +3,6 @@ MODULE.Name = "Graphics" MODULE.Libraries = { "NazaraCore", "NazaraUtility", + "NazaraPlatform", "NazaraRenderer" } diff --git a/build/scripts/modules/platform.lua b/build/scripts/modules/platform.lua new file mode 100644 index 000000000..c90f6663a --- /dev/null +++ b/build/scripts/modules/platform.lua @@ -0,0 +1,31 @@ +MODULE.Name = "Platform" + +MODULE.Libraries = { + "NazaraCore", + "NazaraUtility" +} + +MODULE.OsFiles.Windows = { + "../src/Nazara/Platform/Win32/**.hpp", + "../src/Nazara/Platform/Win32/**.cpp" +} + +MODULE.OsFiles.Posix = { + "../src/Nazara/Platform/X11/**.hpp", + "../src/Nazara/Platform/X11/**.cpp" +} + +MODULE.OsLibraries.Windows = { + "gdi32" +} + +MODULE.OsLibraries.Posix = { + "X11", + "xcb", + "xcb-cursor", + "xcb-ewmh", + "xcb-icccm", + "xcb-keysyms", + "xcb-randr" +} + diff --git a/build/scripts/modules/renderer.lua b/build/scripts/modules/renderer.lua index bbc472b75..11b378d2b 100644 --- a/build/scripts/modules/renderer.lua +++ b/build/scripts/modules/renderer.lua @@ -8,7 +8,8 @@ MODULE.Defines = { MODULE.Libraries = { "NazaraCore", - "NazaraUtility" + "NazaraUtility", + "NazaraPlatform" } MODULE.OsFiles.Windows = { diff --git a/build/scripts/modules/utility.lua b/build/scripts/modules/utility.lua index c1bc186c0..fc4c989d8 100644 --- a/build/scripts/modules/utility.lua +++ b/build/scripts/modules/utility.lua @@ -5,29 +5,11 @@ MODULE.Libraries = { "stb_image" } -MODULE.OsFiles.Windows = { - "../src/Nazara/Utility/Win32/**.hpp", - "../src/Nazara/Utility/Win32/**.cpp" -} - -MODULE.OsFiles.Posix = { - "../src/Nazara/Utility/X11/**.hpp", - "../src/Nazara/Utility/X11/**.cpp" -} - MODULE.OsLibraries.Windows = { - "freetype-s", - "gdi32" + "freetype-s" } MODULE.OsLibraries.Posix = { - "freetype", - "X11", - "xcb", - "xcb-cursor", - "xcb-ewmh", - "xcb-icccm", - "xcb-keysyms", - "xcb-randr" + "freetype" } diff --git a/build/scripts/tools/ndk_server.lua b/build/scripts/tools/ndk_server.lua index c439e47b1..cea295f7e 100644 --- a/build/scripts/tools/ndk_server.lua +++ b/build/scripts/tools/ndk_server.lua @@ -37,7 +37,8 @@ TOOL.FilesExcluded = { "../SDK/**/*Widget*.*", "../SDK/**/LuaBinding_Audio.*", "../SDK/**/LuaBinding_Graphics.*", - "../SDK/**/LuaBinding_Renderer.*" + "../SDK/**/LuaBinding_Renderer.*", + "../SDK/**/LuaBinding_Platform.*" } diff --git a/build/scripts/tools/unittests_server.lua b/build/scripts/tools/unittests_server.lua index c94a54d6d..63c268347 100644 --- a/build/scripts/tools/unittests_server.lua +++ b/build/scripts/tools/unittests_server.lua @@ -25,7 +25,7 @@ TOOL.Files = { TOOL.FilesExcluded = { "../tests/Engine/Audio/**", "../tests/Engine/Graphics/**", - "../tests/Engine/Utility/**", + "../tests/Engine/Platform/**", "../tests/SDK/NDK/Application.cpp", "../tests/SDK/NDK/Systems/ListenerSystem.cpp", "../tests/SDK/NDK/Systems/RenderSystem.cpp" diff --git a/examples/DopplerEffect/build.lua b/examples/DopplerEffect/build.lua index 302011b81..837f62af4 100644 --- a/examples/DopplerEffect/build.lua +++ b/examples/DopplerEffect/build.lua @@ -9,5 +9,6 @@ EXAMPLE.Files = { EXAMPLE.Libraries = { "NazaraAudio", "NazaraCore", + "NazaraPlatform", "NazaraUtility" -} \ No newline at end of file +} diff --git a/examples/DopplerEffect/main.cpp b/examples/DopplerEffect/main.cpp index b6d2d034b..24120a2f5 100644 --- a/examples/DopplerEffect/main.cpp +++ b/examples/DopplerEffect/main.cpp @@ -12,14 +12,14 @@ #include #include // Thread::Sleep #include -#include -#include +#include +#include #include int main() { // NzKeyboard nécessite l'initialisation du module Utilitaire - Nz::Initializer audio; + Nz::Initializer audio; if (!audio) { std::cout << "Failed to initialize audio module" << std::endl; diff --git a/examples/HardwareInfo/build.lua b/examples/HardwareInfo/build.lua index afcc7b544..953cba7d9 100644 --- a/examples/HardwareInfo/build.lua +++ b/examples/HardwareInfo/build.lua @@ -12,6 +12,7 @@ EXAMPLE.Files = { EXAMPLE.Libraries = { "NazaraCore", + "NazaraPlatform", "NazaraRenderer", "NazaraUtility" } diff --git a/examples/MeshInfos/build.lua b/examples/MeshInfos/build.lua index 4e26f318b..74616762e 100644 --- a/examples/MeshInfos/build.lua +++ b/examples/MeshInfos/build.lua @@ -8,6 +8,7 @@ EXAMPLE.Files = { EXAMPLE.Libraries = { "NazaraCore", + "NazaraPlatform", "NazaraUtility" } diff --git a/examples/MeshInfos/main.cpp b/examples/MeshInfos/main.cpp index e95a2a4c2..bac5398fe 100644 --- a/examples/MeshInfos/main.cpp +++ b/examples/MeshInfos/main.cpp @@ -2,8 +2,11 @@ #include #include #include +#include #include #include +#include +#include #include #include #include diff --git a/examples/Particles/Common.cpp b/examples/Particles/Common.cpp index 5af7225f7..0ed9096ef 100644 --- a/examples/Particles/Common.cpp +++ b/examples/Particles/Common.cpp @@ -11,7 +11,7 @@ m_name(name) { } -void ParticleDemo::Enter(Ndk::StateMachine& fsm) +void ParticleDemo::Enter(Ndk::StateMachine& /*fsm*/) { m_shared.demoName->Update(Nz::SimpleTextDrawer::Draw(Nz::String::Number(m_index+1) + " - " + m_name, 48)); m_fpsCounter = 0; @@ -23,7 +23,7 @@ void ParticleDemo::Enter(Ndk::StateMachine& fsm) m_oldBackground3D = renderSystem3D.GetDefaultBackground(); } -void ParticleDemo::Leave(Ndk::StateMachine& fsm) +void ParticleDemo::Leave(Ndk::StateMachine& /*fsm*/) { m_shared.world2D->GetSystem().SetDefaultBackground(m_oldBackground2D); m_shared.world3D->GetSystem().SetDefaultBackground(m_oldBackground3D); @@ -32,7 +32,7 @@ void ParticleDemo::Leave(Ndk::StateMachine& fsm) m_particleGroups.clear(); } -bool ParticleDemo::Update(Ndk::StateMachine& fsm, float elapsedTime) +bool ParticleDemo::Update(Ndk::StateMachine& /*fsm*/, float elapsedTime) { m_fpsCounter++; if (m_updateClock.GetMilliseconds() > 1000) diff --git a/examples/Particles/LogoDemo.cpp b/examples/Particles/LogoDemo.cpp index cc0c2a610..831fcffd5 100644 --- a/examples/Particles/LogoDemo.cpp +++ b/examples/Particles/LogoDemo.cpp @@ -1,4 +1,5 @@ #include "LogoDemo.hpp" +#include #include #include #include @@ -8,12 +9,22 @@ namespace { const float duration = 10.f; - const float maxVel = 50.f; + const float maxSpeed = 100.f; + const float maxMouseForce = 1000.f; + const float mouseForce = 500.f; const float pauseTime = 3.f; const float startTime = 2.f; const float speed = 3.f; } +struct ParticleData +{ + Nz::Color color; + Nz::Vector2f destination; + Nz::Vector2f position; + Nz::Vector2f velocity; +}; + struct SpriteController : public Nz::ParticleController { void Apply(Nz::ParticleGroup& system, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) override @@ -21,15 +32,70 @@ struct SpriteController : public Nz::ParticleController if (!enabled) return; - auto posPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); - auto velPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); + auto destPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Userdata0); + auto posPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); + auto velPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); + + std::uniform_real_distribution dis(-1.f, 1.f); for (unsigned int i = startId; i <= endId; ++i) - posPtr[i] += velPtr[i] * elapsedTime * factor; + { + Nz::Vector2f newVel = destPtr[i] - posPtr[i]; + float length; + newVel.Normalize(&length); + + float distance = SquaredDistancePointSegment(oldMousePos, actualMousePos, posPtr[i]); + if (distance < 250.f) + { + Nz::Vector2f mouseLine = actualMousePos - oldMousePos; + float mouseLength; + mouseLine.Normalize(&mouseLength); + if (mouseLength > 5.f) + { + velPtr[i] += mouseLine * std::min(mouseLength * mouseForce, maxMouseForce) * elapsedTime; + velPtr[i] += Nz::Vector2f(dis(randomGen), dis(randomGen)) * std::min(mouseLength, maxMouseForce * 0.1f); + } + } + + if (length > 1.f || velPtr[i].GetSquaredLength() > Nz::IntegralPow(30.f, 2)) + { + newVel *= maxSpeed; + + velPtr[i] = Nz::Lerp(velPtr[i], newVel, 0.4f * elapsedTime); + posPtr[i] += velPtr[i] * elapsedTime; + } + else + { + velPtr[i] = Nz::Vector2f::Zero(); + posPtr[i] = destPtr[i]; + } + } } + static float SquaredDistancePointSegment(const Nz::Vector2f& s0, const Nz::Vector2f& s1, const Nz::Vector2f& point) + { + // http://geomalgorithms.com/a02-_lines.html + Nz::Vector2f v = s1 - s0; + Nz::Vector2f w = point - s0; + + float c1 = Nz::Vector2f::DotProduct(w, v); + if (c1 <= 0.f) + return point.SquaredDistance(s0); + + float c2 = Nz::Vector2f::DotProduct(v, v); + if (c2 <= c1) + return point.SquaredDistance(s1); + + float b = c1 / c2; + Nz::Vector2f projPoint = s0 + b * v; + return projPoint.SquaredDistance(point); + } + + std::mt19937 randomGen; bool enabled = false; - float factor = 1.f; + float factor = 1000.f; + Nz::Vector2f actualMousePos; + Nz::Vector2f oldMousePos; }; @@ -67,9 +133,9 @@ ParticleDemo("Logo", sharedData) unsigned int height = m_logo.GetHeight(); m_pixels.reserve(width * height); - for (unsigned int y = 0; y < height; ++y) + for (unsigned int x = 0; x < width; ++x) { - for (unsigned int x = 0; x < width; ++x) + for (unsigned int y = 0; y < height; ++y) { Nz::Color color = m_logo.GetPixelColor(x, y); if (color.a == 0) @@ -93,6 +159,12 @@ ParticleDemo("Logo", sharedData) m_controller = new SpriteController; m_renderer = new SpriteRenderer(std::move(material)); + + m_declaration = Nz::ParticleDeclaration::New(); + m_declaration->EnableComponent(Nz::ParticleComponent_Color, Nz::ComponentType_Color, NazaraOffsetOf(ParticleData, color)); + m_declaration->EnableComponent(Nz::ParticleComponent_Position, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, position)); + m_declaration->EnableComponent(Nz::ParticleComponent_Userdata0, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, destination)); + m_declaration->EnableComponent(Nz::ParticleComponent_Velocity, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, velocity)); } void LogoExample::Enter(Ndk::StateMachine& fsm) @@ -106,17 +178,20 @@ void LogoExample::Enter(Ndk::StateMachine& fsm) m_shared.world2D->GetSystem().SetDefaultBackground(Nz::TextureBackground::New(std::move(backgroundTexture))); Ndk::EntityHandle particleGroupEntity = m_shared.world2D->CreateEntity(); - Ndk::ParticleGroupComponent& particleGroup = particleGroupEntity->AddComponent(m_pixels.size(), Nz::ParticleLayout_Sprite); + Ndk::ParticleGroupComponent& particleGroup = particleGroupEntity->AddComponent(m_pixels.size(), m_declaration); RegisterParticleGroup(particleGroupEntity); particleGroup.AddController(m_controller); particleGroup.SetRenderer(m_renderer); - m_particles = static_cast(particleGroup.CreateParticles(m_pixels.size())); + m_particles = particleGroup.CreateParticles(m_pixels.size()); ResetParticles(-duration * (speed / 2.f)); m_accumulator = pauseTime + duration; m_totalAccumulator = 0.f; + + SpriteController* controller = static_cast(m_controller.Get()); + controller->actualMousePos = controller->oldMousePos = Nz::Vector2f(Nz::Mouse::GetPosition(*m_shared.target)); } void LogoExample::Leave(Ndk::StateMachine & fsm) @@ -136,35 +211,62 @@ bool LogoExample::Update(Ndk::StateMachine& fsm, float elapsedTime) m_accumulator += elapsedTime; SpriteController* controller = static_cast(m_controller.Get()); - if (m_accumulator > pauseTime + 2.f * duration) + controller->enabled = (m_accumulator > pauseTime); + + if (m_mouseClock.GetMilliseconds() > 1000/30) { - ResetParticles(0.f); - m_accumulator = 0.f; + m_mouseClock.Restart(); + + controller->oldMousePos = controller->actualMousePos; + controller->actualMousePos = Nz::Vector2f(Nz::Mouse::GetPosition(*m_shared.target)); } - controller->enabled = (m_accumulator > pauseTime); - controller->factor = -speed + speed * (m_accumulator - pauseTime) / (duration); + if (Nz::Mouse::IsButtonPressed(Nz::Mouse::Left)) + { + if (!m_hasClicked) + { + m_hasClicked = true; + std::uniform_real_distribution dis(50.f, 60.f); + + ParticleData* sprite = static_cast(m_particles); + for (std::size_t i = 0; i < m_pixels.size(); ++i) + { + Nz::Vector2f particleToMouse = sprite[i].position - controller->actualMousePos; + float sqDist = particleToMouse.GetSquaredLength(); + if (sqDist < 10000.f) + { + float dist = std::sqrt(sqDist); + particleToMouse /= std::max(dist, 1.f); + + sprite[i].velocity += particleToMouse * dis(m_shared.randomGen); + } + } + } + } + else + m_hasClicked = false; return true; } void LogoExample::ResetParticles(float elapsed) { - Nz::Vector2f center = {m_shared.target->GetWidth() / 2.f, m_shared.target->GetHeight() / 2.f}; + unsigned int width = m_shared.target->GetWidth(); + unsigned int height = m_shared.target->GetHeight(); + + Nz::Vector2f center = {width / 2.f, height / 2.f}; Nz::Vector2f offset = center - Nz::Vector2f(Nz::Vector2ui(m_logo.GetSize()) / 2); - float ratio = float(m_shared.target->GetWidth()) / m_shared.target->GetHeight(); - std::uniform_real_distribution disX(-maxVel * ratio, maxVel * ratio); - std::uniform_real_distribution disY(-maxVel, maxVel); + std::uniform_real_distribution disX(0.f, float(width)); + std::uniform_real_distribution disY(-float(height) * 0.5f, float(height) * 1.5f); - Nz::ParticleStruct_Sprite* sprite = m_particles; + ParticleData* sprite = static_cast(m_particles); for (PixelData& data : m_pixels) { sprite->color = data.color; - sprite->position = offset + Nz::Vector2f(data.pos); - sprite->rotation = 0.f; - sprite->velocity.Set(disX(m_shared.randomGen), disY(m_shared.randomGen), 0.f); - sprite->position += sprite->velocity * elapsed; + sprite->destination = offset + Nz::Vector2f(data.pos); + sprite->position.Set(disX(m_shared.randomGen) - float(width), disY(m_shared.randomGen)); + sprite->velocity = Nz::Vector2f::Zero(); sprite++; } } diff --git a/examples/Particles/LogoDemo.hpp b/examples/Particles/LogoDemo.hpp index d5c374d32..7ce594080 100644 --- a/examples/Particles/LogoDemo.hpp +++ b/examples/Particles/LogoDemo.hpp @@ -30,10 +30,13 @@ class LogoExample : public ParticleDemo std::vector m_pixels; Nz::BackgroundRef m_oldBackground; - Nz::ParticleStruct_Sprite* m_particles; + void* m_particles; + Nz::Clock m_mouseClock; Nz::Image m_logo; Nz::ParticleControllerRef m_controller; + Nz::ParticleDeclarationRef m_declaration; Nz::ParticleRendererRef m_renderer; + bool m_hasClicked; float m_accumulator; float m_totalAccumulator; }; diff --git a/examples/Particles/SpacebattleDemo.cpp b/examples/Particles/SpacebattleDemo.cpp index 7f2cd6b4c..bb7a760ef 100644 --- a/examples/Particles/SpacebattleDemo.cpp +++ b/examples/Particles/SpacebattleDemo.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -317,10 +318,10 @@ ParticleDemo("Space battle", sharedData) m_spaceshipTemplate = m_shared.world3D->CreateEntity(); m_spaceshipTemplate->Enable(false); + m_spaceshipTemplate->AddComponent(); + m_spaceshipTemplate->AddComponent(); + m_spaceshipTemplate->AddComponent(); auto& gfxComponent = m_spaceshipTemplate->AddComponent(); - auto& nodeComponent = m_spaceshipTemplate->AddComponent(); - auto& velocityComponent = m_spaceshipTemplate->AddComponent(); - auto& spaceshipComponent = m_spaceshipTemplate->AddComponent(); gfxComponent.Attach(&m_spaceshipModel); m_ambientMusic.OpenFromFile("resources/ambience.ogg"); @@ -385,9 +386,7 @@ void SpacebattleExample::Enter(Ndk::StateMachine& fsm) m_torpedoGroup->AddController(Nz::ParticleFunctionController::New([this] (Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) { auto positionPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); - auto rotationPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Rotation); auto sizePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Size); - auto velocityPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); auto& spaceshipSystem = m_shared.world3D->GetSystem(); @@ -421,7 +420,7 @@ void SpacebattleExample::Enter(Ndk::StateMachine& fsm) emitter.SetEmissionCount(2); emitter.SetEmissionRate(200.f); - emitter.SetSetupFunc([this] (const Ndk::EntityHandle& entity, Nz::ParticleMapper& mapper, unsigned int count) + emitter.SetSetupFunc([this] (const Ndk::EntityHandle& emitter, Nz::ParticleMapper& particleMapper, unsigned int count) { auto& gen = m_shared.randomGen; @@ -433,29 +432,29 @@ void SpacebattleExample::Enter(Ndk::StateMachine& fsm) std::uniform_real_distribution sizeDis(1.0f, 4.f); std::uniform_real_distribution velDis(-maxFireVel, maxFireVel); - Nz::Vector3f pos = entity->GetComponent().GetPosition(); + Nz::Vector3f pos = emitter->GetComponent().GetPosition(); - Nz::ParticleStruct_Billboard* billboards = static_cast(mapper.GetPointer()); + Nz::ParticleStruct_Billboard* billboards = static_cast(particleMapper.GetPointer()); Nz::ParticleStruct_Billboard* smokeParticles = static_cast(m_smokeGroup->CreateParticles(count)); - for (unsigned int i = 0; i < count; ++i) + for (unsigned int j = 0; j < count; ++j) { - billboards[i].color = Nz::Color::White; - billboards[i].life = 1.f + lifeDis(gen); - billboards[i].position = pos + Nz::Vector3f(posDis(gen), posDis(gen), posDis(gen)); - billboards[i].rotation = rotDis(gen); - billboards[i].size = {1.28f, 1.28f}; - billboards[i].size *= sizeDis(gen); - billboards[i].velocity.Set(normalDis(gen), normalDis(gen), normalDis(gen)); - billboards[i].velocity.Normalize(); - billboards[i].velocity *= velDis(gen); + billboards[j].color = Nz::Color::White; + billboards[j].life = 1.f + lifeDis(gen); + billboards[j].position = pos + Nz::Vector3f(posDis(gen), posDis(gen), posDis(gen)); + billboards[j].rotation = rotDis(gen); + billboards[j].size = {1.28f, 1.28f}; + billboards[j].size *= sizeDis(gen); + billboards[j].velocity.Set(normalDis(gen), normalDis(gen), normalDis(gen)); + billboards[j].velocity.Normalize(); + billboards[j].velocity *= velDis(gen); - smokeParticles[i].color = Nz::Color(128, 128, 128, 0); - smokeParticles[i].life = maxSmokeLife; - smokeParticles[i].position = billboards[i].position; - smokeParticles[i].rotation = billboards[i].rotation; - smokeParticles[i].size = {2.56f, 2.56f}; - smokeParticles[i].size *= sizeDis(gen); - smokeParticles[i].velocity = billboards[i].velocity / 2.f; + smokeParticles[j].color = Nz::Color(128, 128, 128, 0); + smokeParticles[j].life = maxSmokeLife; + smokeParticles[j].position = billboards[j].position; + smokeParticles[j].rotation = billboards[j].rotation; + smokeParticles[j].size = {2.56f, 2.56f}; + smokeParticles[j].size *= sizeDis(gen); + smokeParticles[j].velocity = billboards[j].velocity / 2.f; } }); m_fireGroup->AddEmitter(entity); @@ -466,12 +465,11 @@ void SpacebattleExample::Enter(Ndk::StateMachine& fsm) } })); - m_torpedoGroup->SetRenderer(Nz::ParticleFunctionRenderer::New([sparkleMat1 = Nz::MaterialLibrary::Get("TorpedoFlare1")] (const Nz::ParticleGroup& group, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue) + m_torpedoGroup->SetRenderer(Nz::ParticleFunctionRenderer::New([sparkleMat1 = Nz::MaterialLibrary::Get("TorpedoFlare1")] (const Nz::ParticleGroup& /*group*/, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue) { auto positionPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); auto rotationPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Rotation); auto sizePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Size); - auto velocityPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); renderQueue->AddBillboards(0, sparkleMat1, endId - startId + 1, positionPtr, sizePtr, rotationPtr); for (unsigned int i = startId; i <= endId; ++i) @@ -580,7 +578,7 @@ void SpacebattleExample::Enter(Ndk::StateMachine& fsm) }); m_fireGroup->AddController(movementController); - m_fireGroup->AddController(Nz::ParticleFunctionController::New([] (Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) + m_fireGroup->AddController(Nz::ParticleFunctionController::New([] (Nz::ParticleGroup& /*group*/, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) { auto colorPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Color); auto lifePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Life); @@ -591,7 +589,7 @@ void SpacebattleExample::Enter(Ndk::StateMachine& fsm) })); m_smokeGroup->AddController(movementController); - m_smokeGroup->AddController(Nz::ParticleFunctionController::New([] (Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) + m_smokeGroup->AddController(Nz::ParticleFunctionController::New([] (Nz::ParticleGroup& /*group*/, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) { auto colorPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Color); auto lifePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Life); @@ -617,7 +615,7 @@ void SpacebattleExample::Enter(Ndk::StateMachine& fsm) smokeMat->SetDiffuseColor(Nz::Color(128, 128, 128)); smokeMat->SetDiffuseMap("resources/smoke.png"); - m_fireGroup->SetRenderer(Nz::ParticleFunctionRenderer::New([fireMat] (const Nz::ParticleGroup& group, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue) + m_fireGroup->SetRenderer(Nz::ParticleFunctionRenderer::New([fireMat] (const Nz::ParticleGroup& /*group*/, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue) { auto colorPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Color); auto posPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); @@ -627,7 +625,7 @@ void SpacebattleExample::Enter(Ndk::StateMachine& fsm) renderQueue->AddBillboards(0, fireMat, endId - startId + 1, posPtr, sizePtr, rotPtr, colorPtr); })); - m_smokeGroup->SetRenderer(Nz::ParticleFunctionRenderer::New([smokeMat] (const Nz::ParticleGroup& group, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue) + m_smokeGroup->SetRenderer(Nz::ParticleFunctionRenderer::New([smokeMat] (const Nz::ParticleGroup& /*group*/, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue) { auto colorPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Color); auto posPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); @@ -815,7 +813,7 @@ void SpacebattleExample::CreateTurret() cannonGfx.Attach(&m_turret.cannonModel); } -void SpacebattleExample::OnMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event) +void SpacebattleExample::OnMouseMoved(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseMoveEvent& event) { const float speed = 0.1f; diff --git a/examples/Particles/SpacebattleDemo.hpp b/examples/Particles/SpacebattleDemo.hpp index 44852a61f..a41be7504 100644 --- a/examples/Particles/SpacebattleDemo.hpp +++ b/examples/Particles/SpacebattleDemo.hpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/examples/Particles/main.cpp b/examples/Particles/main.cpp index bf230bfe7..f4754c136 100644 --- a/examples/Particles/main.cpp +++ b/examples/Particles/main.cpp @@ -105,7 +105,7 @@ int main() fpsNode.SetPosition(5.f, window.GetHeight() - fpsCountBox.height - particleCountBox.height - 5.f); - //shared.demos.push_back(std::make_shared(shared)); + shared.demos.push_back(std::make_shared(shared)); shared.demos.push_back(std::make_shared(shared)); std::size_t demoIndex = 0; diff --git a/examples/Tut00/build.lua b/examples/Tut00/build.lua index 678aa3394..baf738d1d 100644 --- a/examples/Tut00/build.lua +++ b/examples/Tut00/build.lua @@ -15,6 +15,7 @@ EXAMPLE.Libraries = { "NazaraNoise", "NazaraPhysics2D", "NazaraPhysics3D", + "NazaraPlatform", "NazaraRenderer", "NazaraUtility", "NazaraSDK" diff --git a/include/Nazara/Audio/Audio.hpp b/include/Nazara/Audio/Audio.hpp index 1a7c7a1a4..84aee8b84 100644 --- a/include/Nazara/Audio/Audio.hpp +++ b/include/Nazara/Audio/Audio.hpp @@ -10,7 +10,6 @@ #include #include #include -#include #include #include diff --git a/include/Nazara/Audio/Music.hpp b/include/Nazara/Audio/Music.hpp index 86ccc6906..34b8926a4 100644 --- a/include/Nazara/Audio/Music.hpp +++ b/include/Nazara/Audio/Music.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -37,7 +38,7 @@ namespace Nz public: Music() = default; Music(const Music&) = delete; - Music(Music&&) = delete; ///TODO + Music(Music&&) = delete; ~Music(); bool Create(SoundStream* soundStream); @@ -66,10 +67,10 @@ namespace Nz void Stop() override; Music& operator=(const Music&) = delete; - Music& operator=(Music&&) = delete; ///TODO + Music& operator=(Music&&) = delete; private: - MusicImpl* m_impl = nullptr; + MovablePtr m_impl = nullptr; bool FillAndQueueBuffer(unsigned int buffer); void MusicThread(); diff --git a/include/Nazara/Audio/SoundBuffer.hpp b/include/Nazara/Audio/SoundBuffer.hpp index db38f780f..ee2671070 100644 --- a/include/Nazara/Audio/SoundBuffer.hpp +++ b/include/Nazara/Audio/SoundBuffer.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -18,7 +19,6 @@ #include #include #include -#include namespace Nz { @@ -74,7 +74,7 @@ namespace Nz template static SoundBufferRef New(Args&&... args); SoundBuffer& operator=(const SoundBuffer&) = delete; - SoundBuffer& operator=(SoundBuffer&&) = delete; ///TODO + SoundBuffer& operator=(SoundBuffer&&) = delete; // Signals: NazaraSignal(OnSoundBufferDestroy, const SoundBuffer* /*soundBuffer*/); @@ -86,7 +86,7 @@ namespace Nz static bool Initialize(); static void Uninitialize(); - SoundBufferImpl* m_impl = nullptr; + MovablePtr m_impl = nullptr; static SoundBufferLibrary::LibraryMap s_library; static SoundBufferLoader::LoaderList s_loaders; diff --git a/include/Nazara/Audio/SoundEmitter.hpp b/include/Nazara/Audio/SoundEmitter.hpp index 4bcdca176..5c755d253 100644 --- a/include/Nazara/Audio/SoundEmitter.hpp +++ b/include/Nazara/Audio/SoundEmitter.hpp @@ -52,12 +52,12 @@ namespace Nz virtual void Stop() = 0; SoundEmitter& operator=(const SoundEmitter&) = delete; ///TODO - SoundEmitter& operator=(SoundEmitter&&) = delete; ///TODO + SoundEmitter& operator=(SoundEmitter&&) = delete; protected: SoundEmitter(); SoundEmitter(const SoundEmitter& emitter); - SoundEmitter(SoundEmitter&&) = delete; ///TODO + SoundEmitter(SoundEmitter&&) = delete; SoundStatus GetInternalStatus() const; diff --git a/include/Nazara/Core/AbstractLogger.hpp b/include/Nazara/Core/AbstractLogger.hpp index fb2ba6c0f..2f523e2d2 100644 --- a/include/Nazara/Core/AbstractLogger.hpp +++ b/include/Nazara/Core/AbstractLogger.hpp @@ -8,7 +8,6 @@ #define NAZARA_ABSTRACTLOGGER_HPP #include -#include #include namespace Nz diff --git a/include/Nazara/Core/Bitset.hpp b/include/Nazara/Core/Bitset.hpp index 2ea0502a4..97bcc43f3 100644 --- a/include/Nazara/Core/Bitset.hpp +++ b/include/Nazara/Core/Bitset.hpp @@ -90,8 +90,8 @@ namespace Nz void UnboundedSet(std::size_t bit, bool val = true); bool UnboundedTest(std::size_t bit) const; - Bit operator[](int index); - bool operator[](int index) const; + Bit operator[](std::size_t index); + bool operator[](std::size_t index) const; Bitset operator~() const; @@ -145,7 +145,7 @@ namespace Nz template void* operator&() const; - operator bool() const; + explicit operator bool() const; Bit& operator=(bool val); Bit& operator=(const Bit& bit); diff --git a/include/Nazara/Core/Bitset.inl b/include/Nazara/Core/Bitset.inl index 44a5e2c16..044c7d0af 100644 --- a/include/Nazara/Core/Bitset.inl +++ b/include/Nazara/Core/Bitset.inl @@ -958,7 +958,7 @@ namespace Nz */ template - typename Bitset::Bit Bitset::operator[](int index) + typename Bitset::Bit Bitset::operator[](std::size_t index) { return Bit(m_blocks[GetBlockIndex(index)], Block(1U) << GetBitIndex(index)); } @@ -969,7 +969,7 @@ namespace Nz */ template - bool Bitset::operator[](int index) const + bool Bitset::operator[](std::size_t index) const { return Test(index); } diff --git a/include/Nazara/Core/ByteArray.inl b/include/Nazara/Core/ByteArray.inl index 81406d84f..108b672cb 100644 --- a/include/Nazara/Core/ByteArray.inl +++ b/include/Nazara/Core/ByteArray.inl @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include namespace Nz diff --git a/include/Nazara/Core/ByteStream.hpp b/include/Nazara/Core/ByteStream.hpp index eed461205..0cdf1b795 100644 --- a/include/Nazara/Core/ByteStream.hpp +++ b/include/Nazara/Core/ByteStream.hpp @@ -8,13 +8,14 @@ #define NAZARA_BYTESTREAM_HPP #include -#include #include -#include #include namespace Nz { + class ByteArray; + class Stream; + class NAZARA_CORE_API ByteStream { public: diff --git a/include/Nazara/Core/Color.inl b/include/Nazara/Core/Color.inl index 6d9fe4d35..77b6be8ae 100644 --- a/include/Nazara/Core/Color.inl +++ b/include/Nazara/Core/Color.inl @@ -2,12 +2,9 @@ // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include #include -#include -#include #include namespace Nz diff --git a/include/Nazara/Core/ConditionVariable.hpp b/include/Nazara/Core/ConditionVariable.hpp index d73cb0f8f..97d4ed10f 100644 --- a/include/Nazara/Core/ConditionVariable.hpp +++ b/include/Nazara/Core/ConditionVariable.hpp @@ -8,6 +8,7 @@ #define NAZARA_CONDITIONVARIABLE_HPP #include +#include namespace Nz { @@ -19,7 +20,7 @@ namespace Nz public: ConditionVariable(); ConditionVariable(const ConditionVariable&) = delete; - inline ConditionVariable(ConditionVariable&& condition) noexcept; + ConditionVariable(ConditionVariable&& condition) noexcept = default; ~ConditionVariable(); void Signal(); @@ -29,10 +30,10 @@ namespace Nz bool Wait(Mutex* mutex, UInt32 timeout); ConditionVariable& operator=(const ConditionVariable&) = delete; - ConditionVariable& operator=(ConditionVariable&& condition) noexcept; + ConditionVariable& operator=(ConditionVariable&& condition) noexcept = default; private: - ConditionVariableImpl* m_impl; + MovablePtr m_impl; }; } diff --git a/include/Nazara/Core/ConditionVariable.inl b/include/Nazara/Core/ConditionVariable.inl index f9603e1c1..71866b880 100644 --- a/include/Nazara/Core/ConditionVariable.inl +++ b/include/Nazara/Core/ConditionVariable.inl @@ -2,8 +2,6 @@ // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include #include namespace Nz @@ -11,15 +9,6 @@ namespace Nz /*! * \class Nz::ConditionVariable */ - - /*! - * \brief Constructs a ConditionVariable object by moving another one - */ - inline ConditionVariable::ConditionVariable(ConditionVariable&& condition) noexcept : - m_impl(condition.m_impl) - { - condition.m_impl = nullptr; - } } #include diff --git a/include/Nazara/Core/Config.hpp b/include/Nazara/Core/Config.hpp index 2ad2513ac..5aa9fccec 100644 --- a/include/Nazara/Core/Config.hpp +++ b/include/Nazara/Core/Config.hpp @@ -73,7 +73,7 @@ #define NAZARA_CORE_WINDOWS_CS_SPINLOCKS 4096 // Optimize the Windows implementation with technologies of Windows NT 6.0 (and greater) (Break the compatibility with Windows XP) -#define NAZARA_CORE_WINDOWS_NT6 0 +#define NAZARA_CORE_WINDOWS_NT6 1 /* diff --git a/include/Nazara/Core/Core.hpp b/include/Nazara/Core/Core.hpp index 672e4ecc9..e5b0166d5 100644 --- a/include/Nazara/Core/Core.hpp +++ b/include/Nazara/Core/Core.hpp @@ -8,7 +8,6 @@ #define NAZARA_CORE_HPP #include -#include namespace Nz { diff --git a/include/Nazara/Core/Directory.hpp b/include/Nazara/Core/Directory.hpp index 21a1da8da..ea828fe45 100644 --- a/include/Nazara/Core/Directory.hpp +++ b/include/Nazara/Core/Directory.hpp @@ -8,6 +8,7 @@ #define NAZARA_DIRECTORY_HPP #include +#include #include #if defined(NAZARA_PLATFORM_WINDOWS) @@ -35,7 +36,7 @@ namespace Nz Directory(); Directory(const String& dirPath); Directory(const Directory&) = delete; - Directory(Directory&&) = delete; ///TODO + Directory(Directory&&) noexcept = default; ~Directory(); void Close(); @@ -67,14 +68,14 @@ namespace Nz static bool SetCurrent(const String& dirPath); Directory& operator=(const Directory&) = delete; - Directory& operator=(Directory&&) = delete; ///TODO + Directory& operator=(Directory&&) noexcept = delete; private: NazaraMutexAttrib(m_mutex, mutable) String m_dirPath; String m_pattern; - DirectoryImpl* m_impl; + MovablePtr m_impl; }; } diff --git a/include/Nazara/Core/DynLib.hpp b/include/Nazara/Core/DynLib.hpp index 2f4ccb530..edf8ed647 100644 --- a/include/Nazara/Core/DynLib.hpp +++ b/include/Nazara/Core/DynLib.hpp @@ -8,6 +8,7 @@ #define NAZARA_DYNLIB_HPP #include +#include #include #if defined(NAZARA_PLATFORM_WINDOWS) @@ -28,7 +29,7 @@ namespace Nz { - using DynLibFunc = int (*)(); // "Generic" type of poiter to function + using DynLibFunc = int (*)(); // "Generic" type of pointer to function class DynLibImpl; @@ -37,7 +38,7 @@ namespace Nz public: DynLib(); DynLib(const DynLib&) = delete; - DynLib(DynLib&& lib); + DynLib(DynLib&&) noexcept = default; ~DynLib(); String GetLastError() const; @@ -49,13 +50,13 @@ namespace Nz void Unload(); DynLib& operator=(const DynLib&) = delete; - DynLib& operator=(DynLib&& lib); + DynLib& operator=(DynLib&& lib) noexcept = default; private: NazaraMutexAttrib(m_mutex, mutable) mutable String m_lastError; - DynLibImpl* m_impl; + MovablePtr m_impl; }; } diff --git a/include/Nazara/Core/Enums.hpp b/include/Nazara/Core/Enums.hpp index 2bacb1f2d..937c01a44 100644 --- a/include/Nazara/Core/Enums.hpp +++ b/include/Nazara/Core/Enums.hpp @@ -63,6 +63,7 @@ namespace Nz enum HashType { HashType_CRC32, + HashType_CRC64, HashType_Fletcher16, HashType_MD5, HashType_SHA1, diff --git a/include/Nazara/Core/ErrorFlags.hpp b/include/Nazara/Core/ErrorFlags.hpp index 76d89a858..945acc45c 100644 --- a/include/Nazara/Core/ErrorFlags.hpp +++ b/include/Nazara/Core/ErrorFlags.hpp @@ -8,7 +8,6 @@ #define NAZARA_ERRORFLAGS_HPP #include -#include namespace Nz { diff --git a/include/Nazara/Core/File.hpp b/include/Nazara/Core/File.hpp index 86a224314..859b7395b 100644 --- a/include/Nazara/Core/File.hpp +++ b/include/Nazara/Core/File.hpp @@ -9,8 +9,8 @@ #include #include -#include #include +#include #include #include @@ -33,7 +33,7 @@ namespace Nz File(const String& filePath); File(const String& filePath, OpenModeFlags openMode); File(const File&) = delete; - File(File&& file) noexcept; + File(File&& file) noexcept = default; ~File(); bool Copy(const String& newFilePath); @@ -69,7 +69,7 @@ namespace Nz File& operator=(const String& filePath); File& operator=(const File&) = delete; - File& operator=(File&& file) noexcept; + File& operator=(File&& file) noexcept = default; static String AbsolutePath(const String& filePath); static inline ByteArray ComputeHash(HashType hash, const String& filePath); @@ -95,7 +95,7 @@ namespace Nz std::size_t WriteBlock(const void* buffer, std::size_t size) override; String m_filePath; - FileImpl* m_impl; + MovablePtr m_impl; }; NAZARA_CORE_API bool HashAppend(AbstractHash* hash, const File& originalFile); diff --git a/include/Nazara/Core/File.inl b/include/Nazara/Core/File.inl index 15ac3fabd..8a93fbc28 100644 --- a/include/Nazara/Core/File.inl +++ b/include/Nazara/Core/File.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include diff --git a/include/Nazara/Core/Flags.hpp b/include/Nazara/Core/Flags.hpp index 293a8dfa8..b7dff544b 100644 --- a/include/Nazara/Core/Flags.hpp +++ b/include/Nazara/Core/Flags.hpp @@ -56,7 +56,7 @@ namespace Nz }; // Little hack to have them in both Nz and global scope - namespace DetailFlagOperators + namespace FlagsOperators { template constexpr std::enable_if_t::value, Flags> operator~(E lhs); template constexpr std::enable_if_t::value, Flags> operator|(E lhs, E rhs); @@ -64,10 +64,10 @@ namespace Nz template constexpr std::enable_if_t::value, Flags> operator^(E lhs, E rhs); } - using namespace DetailFlagOperators; + using namespace FlagsOperators; } -using namespace Nz::DetailFlagOperators; +using namespace Nz::FlagsOperators; #include diff --git a/include/Nazara/Core/Flags.inl b/include/Nazara/Core/Flags.inl index 11cd22109..1899e7576 100644 --- a/include/Nazara/Core/Flags.inl +++ b/include/Nazara/Core/Flags.inl @@ -211,7 +211,7 @@ namespace Nz } - namespace DetailFlagOperators + namespace FlagsOperators { /*! * \brief Override binary NOT operator on enum to turns into a Flags object. diff --git a/include/Nazara/Core/GuillotineBinPack.hpp b/include/Nazara/Core/GuillotineBinPack.hpp index 61671ff50..0736447fc 100644 --- a/include/Nazara/Core/GuillotineBinPack.hpp +++ b/include/Nazara/Core/GuillotineBinPack.hpp @@ -11,7 +11,6 @@ #define NAZARA_GUILLOTINEBINPACK_HPP #include -#include #include #include diff --git a/include/Nazara/Core/Hash/CRC64.hpp b/include/Nazara/Core/Hash/CRC64.hpp new file mode 100644 index 000000000..1c9819e5f --- /dev/null +++ b/include/Nazara/Core/Hash/CRC64.hpp @@ -0,0 +1,34 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Core module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_HASH_CRC64_HPP +#define NAZARA_HASH_CRC64_HPP + +#include +#include +#include + +namespace Nz +{ + class NAZARA_CORE_API HashCRC64 : public AbstractHash + { + public: + HashCRC64() = default; + ~HashCRC64() = default; + + void Append(const UInt8* data, std::size_t len) override; + void Begin() override; + ByteArray End() override; + + std::size_t GetDigestLength() const override; + const char* GetHashName() const override; + + private: + Nz::UInt64 m_crc; + }; +} + +#endif // NAZARA_HASH_CRC64_HPP diff --git a/include/Nazara/Core/Hash/Fletcher16.hpp b/include/Nazara/Core/Hash/Fletcher16.hpp index a360c3adf..85325e20c 100644 --- a/include/Nazara/Core/Hash/Fletcher16.hpp +++ b/include/Nazara/Core/Hash/Fletcher16.hpp @@ -10,7 +10,6 @@ #include #include #include -#include namespace Nz { diff --git a/include/Nazara/Core/Initializer.hpp b/include/Nazara/Core/Initializer.hpp index 7fb19e69e..c09ae55af 100644 --- a/include/Nazara/Core/Initializer.hpp +++ b/include/Nazara/Core/Initializer.hpp @@ -24,7 +24,7 @@ namespace Nz bool IsInitialized() const; void Uninitialize(); - operator bool() const; + explicit operator bool() const; Initializer& operator=(const Initializer&) = delete; Initializer& operator=(Initializer&&) = delete; ///TODO diff --git a/include/Nazara/Core/Log.hpp b/include/Nazara/Core/Log.hpp index f3826f568..1538068a2 100644 --- a/include/Nazara/Core/Log.hpp +++ b/include/Nazara/Core/Log.hpp @@ -8,11 +8,8 @@ #define NAZARA_LOG_HPP #include -#include -#include #include #include -#include #if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_LOG #include @@ -30,6 +27,8 @@ namespace Nz { + class AbstractLogger; + class NAZARA_CORE_API Log { friend class Core; diff --git a/include/Nazara/Core/MemoryManager.hpp b/include/Nazara/Core/MemoryManager.hpp index caed09b61..22c59de2d 100644 --- a/include/Nazara/Core/MemoryManager.hpp +++ b/include/Nazara/Core/MemoryManager.hpp @@ -8,8 +8,7 @@ #define NAZARA_MEMORYMANAGER_HPP #include -#include -#include +#include namespace Nz { diff --git a/include/Nazara/Core/MovablePtr.hpp b/include/Nazara/Core/MovablePtr.hpp new file mode 100644 index 000000000..f27e365e6 --- /dev/null +++ b/include/Nazara/Core/MovablePtr.hpp @@ -0,0 +1,38 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Core module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_MOVABLE_PTR_HPP +#define NAZARA_MOVABLE_PTR_HPP + +namespace Nz +{ + template + class MovablePtr + { + public: + MovablePtr(T* value = nullptr); + MovablePtr(const MovablePtr&) = default; + MovablePtr(MovablePtr&& ptr) noexcept; + ~MovablePtr() = default; + + T* Get() const; + + T* operator->() const; + + operator T*() const; + + MovablePtr& operator=(T* value); + MovablePtr& operator=(const MovablePtr&) = default; + MovablePtr& operator=(MovablePtr&& ptr) noexcept; + + private: + T* m_value; + }; +} + +#include + +#endif // NAZARA_MOVABLE_PTR_HPP diff --git a/include/Nazara/Core/MovablePtr.inl b/include/Nazara/Core/MovablePtr.inl new file mode 100644 index 000000000..80d342e4a --- /dev/null +++ b/include/Nazara/Core/MovablePtr.inl @@ -0,0 +1,61 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Core module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include + +namespace Nz +{ + /*! + * \ingroup core + * \class Nz::MovablePtr + * \brief Wraps a raw (non-proprietary) to allows it to be moved implicitly + */ + + template + MovablePtr::MovablePtr(T* value) : + m_value(value) + { + } + + template + MovablePtr::MovablePtr(MovablePtr&& ptr) noexcept : + m_value(ptr.m_value) + { + ptr.m_value = nullptr; + } + + template + inline T* MovablePtr::Get() const + { + return m_value; + } + + template + T* MovablePtr::operator->() const + { + return m_value; + } + + template + MovablePtr::operator T*() const + { + return m_value; + } + + template + inline MovablePtr& MovablePtr::operator=(T* value) + { + m_value = value; + + return *this; + } + + template + MovablePtr& MovablePtr::operator=(MovablePtr&& ptr) noexcept + { + std::swap(m_value, ptr.m_value); + return *this; + } +} diff --git a/include/Nazara/Core/Mutex.hpp b/include/Nazara/Core/Mutex.hpp index 303b163f1..b317cf58b 100644 --- a/include/Nazara/Core/Mutex.hpp +++ b/include/Nazara/Core/Mutex.hpp @@ -8,6 +8,7 @@ #define NAZARA_MUTEX_HPP #include +#include namespace Nz { @@ -20,7 +21,7 @@ namespace Nz public: Mutex(); Mutex(const Mutex&) = delete; - inline Mutex(Mutex&& mutex) noexcept; + Mutex(Mutex&&) noexcept = default; ~Mutex(); void Lock(); @@ -28,10 +29,10 @@ namespace Nz void Unlock(); Mutex& operator=(const Mutex&) = delete; - Mutex& operator=(Mutex&& mutex) noexcept; + Mutex& operator=(Mutex&&) noexcept = default; private: - MutexImpl* m_impl; + MovablePtr m_impl; }; } diff --git a/include/Nazara/Core/Mutex.inl b/include/Nazara/Core/Mutex.inl index 9e79fff02..ca9e5ec2f 100644 --- a/include/Nazara/Core/Mutex.inl +++ b/include/Nazara/Core/Mutex.inl @@ -12,15 +12,6 @@ namespace Nz * \ingroup core * \class Nz::Mutex */ - - /*! - * \brief Constructs a Mutex object by moving another one - */ - inline Mutex::Mutex(Mutex&& mutex) noexcept : - m_impl(mutex.m_impl) - { - mutex.m_impl = nullptr; - } } #include diff --git a/include/Nazara/Core/ObjectHandle.hpp b/include/Nazara/Core/ObjectHandle.hpp index bf22734d3..022344488 100644 --- a/include/Nazara/Core/ObjectHandle.hpp +++ b/include/Nazara/Core/ObjectHandle.hpp @@ -38,7 +38,7 @@ namespace Nz Nz::String ToString() const; - operator bool() const; + explicit operator bool() const; operator T*() const; T* operator->() const; diff --git a/include/Nazara/Core/ObjectRef.hpp b/include/Nazara/Core/ObjectRef.hpp index 1414e5d78..3a9e57628 100644 --- a/include/Nazara/Core/ObjectRef.hpp +++ b/include/Nazara/Core/ObjectRef.hpp @@ -31,7 +31,7 @@ namespace Nz bool Reset(T* object = nullptr); ObjectRef& Swap(ObjectRef& ref); - operator bool() const; + explicit operator bool() const; operator T*() const; T* operator->() const; diff --git a/include/Nazara/Core/ParameterList.inl b/include/Nazara/Core/ParameterList.inl index b1983b49b..029d3d4f3 100644 --- a/include/Nazara/Core/ParameterList.inl +++ b/include/Nazara/Core/ParameterList.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include namespace Nz diff --git a/include/Nazara/Core/RefCounted.hpp b/include/Nazara/Core/RefCounted.hpp index 7a2f8c7fc..472c8a2fa 100644 --- a/include/Nazara/Core/RefCounted.hpp +++ b/include/Nazara/Core/RefCounted.hpp @@ -9,7 +9,6 @@ #include #include -#include #if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_REFCOUNTED #include diff --git a/include/Nazara/Core/Resource.hpp b/include/Nazara/Core/Resource.hpp index 2322b25c1..aea1e4d6c 100644 --- a/include/Nazara/Core/Resource.hpp +++ b/include/Nazara/Core/Resource.hpp @@ -17,7 +17,7 @@ namespace Nz public: Resource() = default; Resource(const Resource&) = default; - Resource(Resource&&) = default; + Resource(Resource&&) noexcept = default; virtual ~Resource(); const String& GetFilePath() const; @@ -25,7 +25,7 @@ namespace Nz void SetFilePath(const String& filePath); Resource& operator=(const Resource&) = default; - Resource& operator=(Resource&&) = default; + Resource& operator=(Resource&&) noexcept = default; private: String m_filePath; diff --git a/include/Nazara/Core/Semaphore.hpp b/include/Nazara/Core/Semaphore.hpp index 8c18cf6f4..985b49ba6 100644 --- a/include/Nazara/Core/Semaphore.hpp +++ b/include/Nazara/Core/Semaphore.hpp @@ -8,6 +8,7 @@ #define NAZARA_SEMAPHORE_HPP #include +#include namespace Nz { @@ -18,7 +19,7 @@ namespace Nz public: Semaphore(unsigned int count); Semaphore(const Semaphore&) = delete; - Semaphore(Semaphore&&) = delete; ///TODO + Semaphore(Semaphore&&) noexcept = default; ~Semaphore(); unsigned int GetCount() const; @@ -29,10 +30,10 @@ namespace Nz bool Wait(UInt32 timeout); Semaphore& operator=(const Semaphore&) = delete; - Semaphore& operator=(Semaphore&&) = delete; ///TODO + Semaphore& operator=(Semaphore&&) noexcept = default; private: - SemaphoreImpl* m_impl; + MovablePtr m_impl; }; } diff --git a/include/Nazara/Core/SerializationContext.hpp b/include/Nazara/Core/SerializationContext.hpp index cf5d83223..7839c484a 100644 --- a/include/Nazara/Core/SerializationContext.hpp +++ b/include/Nazara/Core/SerializationContext.hpp @@ -10,9 +10,6 @@ #include #include #include -#include -#include -#include namespace Nz { diff --git a/include/Nazara/Core/SerializationContext.inl b/include/Nazara/Core/SerializationContext.inl index 5edd4e618..870972655 100644 --- a/include/Nazara/Core/SerializationContext.inl +++ b/include/Nazara/Core/SerializationContext.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include namespace Nz diff --git a/include/Nazara/Core/SparsePtr.hpp b/include/Nazara/Core/SparsePtr.hpp index f4d777fa8..b90067bc2 100644 --- a/include/Nazara/Core/SparsePtr.hpp +++ b/include/Nazara/Core/SparsePtr.hpp @@ -25,6 +25,7 @@ namespace Nz SparsePtr(); SparsePtr(T* ptr); SparsePtr(VoidPtr ptr, int stride); + SparsePtr(VoidPtr ptr, std::size_t stride); template SparsePtr(const SparsePtr& ptr); SparsePtr(const SparsePtr& ptr) = default; ~SparsePtr() = default; @@ -41,7 +42,7 @@ namespace Nz void SetPtr(VoidPtr ptr); void SetStride(int stride); - operator bool() const; + explicit operator bool() const; operator T*() const; T& operator*() const; T* operator->() const; diff --git a/include/Nazara/Core/SparsePtr.inl b/include/Nazara/Core/SparsePtr.inl index db8fb6b33..a5c9d6212 100644 --- a/include/Nazara/Core/SparsePtr.inl +++ b/include/Nazara/Core/SparsePtr.inl @@ -2,7 +2,10 @@ // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp +#include +#include #include +#include #include namespace Nz @@ -48,6 +51,22 @@ namespace Nz Reset(ptr, stride); } + /*! + * \brief Constructs a SparsePtr object with a pointer and a step + * + * \param ptr Pointer to data + * \param stride Step between two elements + * + * \remark This constructor only exists because std::size_t is a frequent type for constructing this object, but stride may not be higher than int max + */ + + template + SparsePtr::SparsePtr(VoidPtr ptr, std::size_t stride) + { + assert(stride <= std::numeric_limits::max()); + Reset(ptr, static_cast(stride)); + } + /*! * \brief Constructs a SparsePtr object from another type of SparsePtr * diff --git a/include/Nazara/Core/Stream.inl b/include/Nazara/Core/Stream.inl index abd97c051..5fb3186d6 100644 --- a/include/Nazara/Core/Stream.inl +++ b/include/Nazara/Core/Stream.inl @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include "Stream.hpp" namespace Nz { diff --git a/include/Nazara/Core/String.hpp b/include/Nazara/Core/String.hpp index 30f88de00..1294535ef 100644 --- a/include/Nazara/Core/String.hpp +++ b/include/Nazara/Core/String.hpp @@ -9,8 +9,6 @@ #include #include -#include -#include #include #include #include @@ -19,6 +17,8 @@ namespace Nz { + struct SerializationContext; + class NAZARA_CORE_API String { public: diff --git a/include/Nazara/Core/Thread.hpp b/include/Nazara/Core/Thread.hpp index a4b4d92f6..c622fd309 100644 --- a/include/Nazara/Core/Thread.hpp +++ b/include/Nazara/Core/Thread.hpp @@ -9,10 +9,12 @@ #include #include +#include #include namespace Nz { + class String; class ThreadImpl; class NAZARA_CORE_API Thread @@ -25,24 +27,26 @@ namespace Nz template Thread(F function, Args&&... args); template Thread(void (C::*function)(), C* object); Thread(const Thread&) = delete; - Thread(Thread&& other) noexcept; + Thread(Thread&& other) noexcept = default; ~Thread(); void Detach(); Id GetId() const; bool IsJoinable() const; void Join(); + void SetName(const String& name); Thread& operator=(const Thread&) = delete; - Thread& operator=(Thread&& thread); + Thread& operator=(Thread&& thread) noexcept = default; static unsigned int HardwareConcurrency(); + static void SetCurrentThreadName(const String& name); static void Sleep(UInt32 milliseconds); private: void CreateImpl(Functor* functor); - ThreadImpl* m_impl; + MovablePtr m_impl; }; class NAZARA_CORE_API Thread::Id diff --git a/include/Nazara/Graphics/AbstractRenderQueue.hpp b/include/Nazara/Graphics/AbstractRenderQueue.hpp index 0e3b94f2f..173ea0142 100644 --- a/include/Nazara/Graphics/AbstractRenderQueue.hpp +++ b/include/Nazara/Graphics/AbstractRenderQueue.hpp @@ -13,8 +13,6 @@ #include #include #include -#include -#include #include namespace Nz @@ -23,6 +21,7 @@ namespace Nz class Material; class Texture; struct MeshData; + struct VertexStruct_XYZ_Color_UV; class NAZARA_GRAPHICS_API AbstractRenderQueue { diff --git a/include/Nazara/Graphics/AbstractRenderTechnique.hpp b/include/Nazara/Graphics/AbstractRenderTechnique.hpp index 4279a5f39..7dba6273c 100644 --- a/include/Nazara/Graphics/AbstractRenderTechnique.hpp +++ b/include/Nazara/Graphics/AbstractRenderTechnique.hpp @@ -8,16 +8,13 @@ #define NAZARA_ABSTRACTRENDERTECHNIQUE_HPP #include -#include #include -#include +#include #include -#include namespace Nz { - class AbstractViewer; - class Background; + class AbstractRenderQueue; struct SceneData; class NAZARA_GRAPHICS_API AbstractRenderTechnique diff --git a/include/Nazara/Graphics/ConfigCheck.hpp b/include/Nazara/Graphics/ConfigCheck.hpp index 3ec60640d..8aa8164db 100644 --- a/include/Nazara/Graphics/ConfigCheck.hpp +++ b/include/Nazara/Graphics/ConfigCheck.hpp @@ -12,7 +12,7 @@ #include #define NazaraCheckTypeAndVal(name, type, op, val, err) static_assert(std::is_ ##type ::value && name op val, #type err) -// We fore the value of MANAGE_MEMORY in debug +// We force the value of MANAGE_MEMORY in debug #if defined(NAZARA_DEBUG) && !NAZARA_GRAPHICS_MANAGE_MEMORY #undef NAZARA_GRAPHICS_MANAGE_MEMORY #define NAZARA_GRAPHICS_MANAGE_MEMORY 0 diff --git a/include/Nazara/Graphics/DeferredRenderPass.hpp b/include/Nazara/Graphics/DeferredRenderPass.hpp index 784ad3c29..77dff072e 100644 --- a/include/Nazara/Graphics/DeferredRenderPass.hpp +++ b/include/Nazara/Graphics/DeferredRenderPass.hpp @@ -9,18 +9,14 @@ #include #include -#include -#include #include namespace Nz { - class AbstractViewer; class DeferredRenderTechnique; class DeferredRenderQueue; - class RenderBuffer; + struct SceneData; class RenderTexture; - class Scene; class Texture; class NAZARA_GRAPHICS_API DeferredRenderPass diff --git a/include/Nazara/Graphics/DeferredRenderQueue.hpp b/include/Nazara/Graphics/DeferredRenderQueue.hpp index 5f9f7538e..c6ffcacac 100644 --- a/include/Nazara/Graphics/DeferredRenderQueue.hpp +++ b/include/Nazara/Graphics/DeferredRenderQueue.hpp @@ -8,7 +8,6 @@ #define NAZARA_DEFERREDRENDERQUEUE_HPP #include -#include #include #include #include @@ -17,7 +16,6 @@ #include #include #include -#include namespace Nz { diff --git a/include/Nazara/Graphics/DeferredRenderTechnique.hpp b/include/Nazara/Graphics/DeferredRenderTechnique.hpp index bdac459e9..025fb1e52 100644 --- a/include/Nazara/Graphics/DeferredRenderTechnique.hpp +++ b/include/Nazara/Graphics/DeferredRenderTechnique.hpp @@ -9,21 +9,18 @@ #include #include -#include #include #include #include -#include -#include #include #include -#include -#include #include #include namespace Nz { + class DeferredRenderPass; + class NAZARA_GRAPHICS_API DeferredRenderTechnique : public AbstractRenderTechnique { friend class Graphics; diff --git a/include/Nazara/Graphics/DepthRenderQueue.hpp b/include/Nazara/Graphics/DepthRenderQueue.hpp index 871cefa66..8de0a2bf2 100644 --- a/include/Nazara/Graphics/DepthRenderQueue.hpp +++ b/include/Nazara/Graphics/DepthRenderQueue.hpp @@ -8,15 +8,9 @@ #define NAZARA_DEPTHRENDERQUEUE_HPP #include -#include -#include #include #include #include -#include -#include -#include -#include namespace Nz { diff --git a/include/Nazara/Graphics/DepthRenderTechnique.hpp b/include/Nazara/Graphics/DepthRenderTechnique.hpp index d28b8a5c4..cc3b7bcd8 100644 --- a/include/Nazara/Graphics/DepthRenderTechnique.hpp +++ b/include/Nazara/Graphics/DepthRenderTechnique.hpp @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include diff --git a/include/Nazara/Graphics/ForwardRenderQueue.hpp b/include/Nazara/Graphics/ForwardRenderQueue.hpp index bc5c2456e..a51e617c3 100644 --- a/include/Nazara/Graphics/ForwardRenderQueue.hpp +++ b/include/Nazara/Graphics/ForwardRenderQueue.hpp @@ -18,7 +18,6 @@ #include #include #include -#include namespace Nz { diff --git a/include/Nazara/Graphics/Graphics.hpp b/include/Nazara/Graphics/Graphics.hpp index 499837466..f8687b80e 100644 --- a/include/Nazara/Graphics/Graphics.hpp +++ b/include/Nazara/Graphics/Graphics.hpp @@ -8,7 +8,6 @@ #define NAZARA_GRAPHICS_HPP #include -#include #include namespace Nz diff --git a/include/Nazara/Graphics/InstancedRenderable.hpp b/include/Nazara/Graphics/InstancedRenderable.hpp index 25cc74ec6..56e7bc0a1 100644 --- a/include/Nazara/Graphics/InstancedRenderable.hpp +++ b/include/Nazara/Graphics/InstancedRenderable.hpp @@ -7,7 +7,6 @@ #ifndef NAZARA_INSTANCEDRENDERABLE_HPP #define NAZARA_INSTANCEDRENDERABLE_HPP -#include #include #include #include diff --git a/include/Nazara/Graphics/Light.hpp b/include/Nazara/Graphics/Light.hpp index 8574bb783..77274b6ca 100644 --- a/include/Nazara/Graphics/Light.hpp +++ b/include/Nazara/Graphics/Light.hpp @@ -11,14 +11,10 @@ #include #include #include -#include #include namespace Nz { - class Light; - struct LightUniforms; - class NAZARA_GRAPHICS_API Light : public Renderable { public: diff --git a/include/Nazara/Graphics/Light.inl b/include/Nazara/Graphics/Light.inl index b30daaf60..509016112 100644 --- a/include/Nazara/Graphics/Light.inl +++ b/include/Nazara/Graphics/Light.inl @@ -2,7 +2,7 @@ // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include namespace Nz diff --git a/include/Nazara/Graphics/Material.hpp b/include/Nazara/Graphics/Material.hpp index 3d32a7014..b509be459 100644 --- a/include/Nazara/Graphics/Material.hpp +++ b/include/Nazara/Graphics/Material.hpp @@ -24,7 +24,6 @@ #include #include #include -#include namespace Nz { diff --git a/include/Nazara/Graphics/Material.inl b/include/Nazara/Graphics/Material.inl index 00e5be457..2893dee97 100644 --- a/include/Nazara/Graphics/Material.inl +++ b/include/Nazara/Graphics/Material.inl @@ -1465,4 +1465,3 @@ namespace Nz } #include -#include "Material.hpp" diff --git a/include/Nazara/Graphics/MaterialPipeline.hpp b/include/Nazara/Graphics/MaterialPipeline.hpp index 1718720db..372572264 100644 --- a/include/Nazara/Graphics/MaterialPipeline.hpp +++ b/include/Nazara/Graphics/MaterialPipeline.hpp @@ -10,10 +10,8 @@ #include #include #include -#include #include #include -#include #include namespace Nz diff --git a/include/Nazara/Graphics/MaterialPipeline.inl b/include/Nazara/Graphics/MaterialPipeline.inl index c13268943..bc7ca1b72 100644 --- a/include/Nazara/Graphics/MaterialPipeline.inl +++ b/include/Nazara/Graphics/MaterialPipeline.inl @@ -2,9 +2,8 @@ // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include #include +#include #include #include diff --git a/include/Nazara/Graphics/ParticleFunctionController.inl b/include/Nazara/Graphics/ParticleFunctionController.inl index 92e78e4af..ae2b2ca6d 100644 --- a/include/Nazara/Graphics/ParticleFunctionController.inl +++ b/include/Nazara/Graphics/ParticleFunctionController.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include diff --git a/include/Nazara/Graphics/ParticleFunctionGenerator.inl b/include/Nazara/Graphics/ParticleFunctionGenerator.inl index 787e1cdce..f52afaaf9 100644 --- a/include/Nazara/Graphics/ParticleFunctionGenerator.inl +++ b/include/Nazara/Graphics/ParticleFunctionGenerator.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include diff --git a/include/Nazara/Graphics/ParticleFunctionRenderer.inl b/include/Nazara/Graphics/ParticleFunctionRenderer.inl index 12b53bf88..e51178b7a 100644 --- a/include/Nazara/Graphics/ParticleFunctionRenderer.inl +++ b/include/Nazara/Graphics/ParticleFunctionRenderer.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include diff --git a/include/Nazara/Graphics/ParticleGroup.hpp b/include/Nazara/Graphics/ParticleGroup.hpp index 93d3f63d4..22f15432d 100644 --- a/include/Nazara/Graphics/ParticleGroup.hpp +++ b/include/Nazara/Graphics/ParticleGroup.hpp @@ -15,9 +15,7 @@ #include #include #include -#include #include -#include #include #include diff --git a/include/Nazara/Graphics/ParticleGroup.inl b/include/Nazara/Graphics/ParticleGroup.inl index 330d6546f..bc12fe145 100644 --- a/include/Nazara/Graphics/ParticleGroup.inl +++ b/include/Nazara/Graphics/ParticleGroup.inl @@ -2,8 +2,6 @@ // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include #include namespace Nz diff --git a/include/Nazara/Graphics/ParticleMapper.inl b/include/Nazara/Graphics/ParticleMapper.inl index 289fdf045..b60eab4bf 100644 --- a/include/Nazara/Graphics/ParticleMapper.inl +++ b/include/Nazara/Graphics/ParticleMapper.inl @@ -1,9 +1,10 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include #include +#include namespace Nz { @@ -26,7 +27,7 @@ namespace Nz std::size_t offset; m_declaration->GetComponent(component, &enabled, &type, &offset); - if (enabled) + if (enabled && GetComponentTypeOf() == type) { ///TODO: Check the ratio between the type of the attribute and the template type ? return SparsePtr(m_ptr + offset, m_declaration->GetStride()); @@ -57,7 +58,7 @@ namespace Nz std::size_t offset; m_declaration->GetComponent(component, &enabled, &type, &offset); - if (enabled) + if (enabled && GetComponentTypeOf() == type) { ///TODO: Check the ratio between the type of the attribute and the template type ? return SparsePtr(m_ptr + offset, m_declaration->GetStride()); diff --git a/include/Nazara/Graphics/SkeletalModel.hpp b/include/Nazara/Graphics/SkeletalModel.hpp index a503a2126..2f7630af2 100644 --- a/include/Nazara/Graphics/SkeletalModel.hpp +++ b/include/Nazara/Graphics/SkeletalModel.hpp @@ -12,9 +12,7 @@ #include #include #include -#include -#include -#include +#include namespace Nz { diff --git a/include/Nazara/Graphics/SkyboxBackground.hpp b/include/Nazara/Graphics/SkyboxBackground.hpp index 4f433ed3e..1e80d7be4 100644 --- a/include/Nazara/Graphics/SkyboxBackground.hpp +++ b/include/Nazara/Graphics/SkyboxBackground.hpp @@ -9,14 +9,12 @@ #include #include -#include #include #include -#include -#include namespace Nz { + class AbstractViewer; class SkyboxBackground; using SkyboxBackgroundConstRef = ObjectRef; diff --git a/include/Nazara/Graphics/Sprite.hpp b/include/Nazara/Graphics/Sprite.hpp index b0cc8a6d8..5b0702ed1 100644 --- a/include/Nazara/Graphics/Sprite.hpp +++ b/include/Nazara/Graphics/Sprite.hpp @@ -10,7 +10,6 @@ #include #include #include -#include #include namespace Nz diff --git a/include/Nazara/Graphics/TextSprite.hpp b/include/Nazara/Graphics/TextSprite.hpp index 99262493b..c4f774774 100644 --- a/include/Nazara/Graphics/TextSprite.hpp +++ b/include/Nazara/Graphics/TextSprite.hpp @@ -11,13 +11,11 @@ #include #include #include -#include #include -#include -#include namespace Nz { + class AbstractTextDrawer; class TextSprite; using TextSpriteConstRef = ObjectRef; diff --git a/include/Nazara/Graphics/TileMap.hpp b/include/Nazara/Graphics/TileMap.hpp index f6809c0c7..310d94afd 100644 --- a/include/Nazara/Graphics/TileMap.hpp +++ b/include/Nazara/Graphics/TileMap.hpp @@ -10,8 +10,6 @@ #include #include #include -#include -#include #include namespace Nz diff --git a/include/Nazara/Graphics/TileMap.inl b/include/Nazara/Graphics/TileMap.inl index ee3e51c72..23065d429 100644 --- a/include/Nazara/Graphics/TileMap.inl +++ b/include/Nazara/Graphics/TileMap.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include #include diff --git a/include/Nazara/Lua/Lua.hpp b/include/Nazara/Lua/Lua.hpp index e1c084f8f..011b9e36f 100644 --- a/include/Nazara/Lua/Lua.hpp +++ b/include/Nazara/Lua/Lua.hpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Lua scripting module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -8,7 +8,6 @@ #define NAZARA_LUA_HPP #include -#include #include namespace Nz diff --git a/include/Nazara/Lua/LuaCoroutine.hpp b/include/Nazara/Lua/LuaCoroutine.hpp index a740f635b..71232791a 100644 --- a/include/Nazara/Lua/LuaCoroutine.hpp +++ b/include/Nazara/Lua/LuaCoroutine.hpp @@ -9,8 +9,6 @@ #include #include -#include -#include namespace Nz { diff --git a/include/Nazara/Lua/LuaCoroutine.inl b/include/Nazara/Lua/LuaCoroutine.inl index 7dcdd0e07..63c7d0eda 100644 --- a/include/Nazara/Lua/LuaCoroutine.inl +++ b/include/Nazara/Lua/LuaCoroutine.inl @@ -2,8 +2,6 @@ // This file is part of the "Nazara Engine - Lua scripting module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include - namespace Nz { inline LuaCoroutine::LuaCoroutine(LuaCoroutine&& instance) : diff --git a/include/Nazara/Lua/LuaInstance.hpp b/include/Nazara/Lua/LuaInstance.hpp index 93374958b..64f998641 100644 --- a/include/Nazara/Lua/LuaInstance.hpp +++ b/include/Nazara/Lua/LuaInstance.hpp @@ -8,9 +8,9 @@ #define NAZARA_LUAINSTANCE_HPP #include +#include #include #include -#include namespace Nz { diff --git a/include/Nazara/Lua/LuaInstance.inl b/include/Nazara/Lua/LuaInstance.inl index 6752eb0e0..1a37cf27a 100644 --- a/include/Nazara/Lua/LuaInstance.inl +++ b/include/Nazara/Lua/LuaInstance.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Lua scripting module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include namespace Nz @@ -24,7 +23,7 @@ namespace Nz inline void LuaInstance::SetMemoryLimit(std::size_t memoryLimit) { - m_memoryLimit = m_memoryLimit; + m_memoryLimit = memoryLimit; } inline void LuaInstance::SetTimeLimit(UInt32 limit) diff --git a/include/Nazara/Lua/LuaState.hpp b/include/Nazara/Lua/LuaState.hpp index f3bfdc34a..a9e229d31 100644 --- a/include/Nazara/Lua/LuaState.hpp +++ b/include/Nazara/Lua/LuaState.hpp @@ -8,13 +8,12 @@ #define NAZARA_LUASTATE_HPP #include -#include -#include #include #include #include #include #include +#include struct lua_Debug; struct lua_State; @@ -24,6 +23,7 @@ namespace Nz class LuaCoroutine; class LuaInstance; class LuaState; + class Stream; using LuaCFunction = int (*)(lua_State* internalState); using LuaFunction = std::function; @@ -32,7 +32,7 @@ namespace Nz { public: LuaState(const LuaState&) = default; - LuaState(LuaState&& instance) noexcept; + inline LuaState(LuaState&& instance) noexcept; ~LuaState() = default; void ArgCheck(bool condition, unsigned int argNum, const char* error) const; @@ -173,7 +173,7 @@ namespace Nz void* ToUserdata(int index, const String& tname) const; LuaState& operator=(const LuaState&) = default; - LuaState& operator=(LuaState&& instance) noexcept; + inline LuaState& operator=(LuaState&& instance) noexcept; static int GetIndexOfUpValue(int upValue); static LuaInstance& GetInstance(lua_State* internalState); @@ -182,7 +182,8 @@ namespace Nz protected: LuaState(lua_State* internalState); - template T CheckBounds(int index, long long value) const; + template std::enable_if_t::value, T> CheckBounds(int index, long long value) const; + template std::enable_if_t::value, T> CheckBounds(int index, long long value) const; virtual bool Run(int argCount, int resultCount); static int ProxyFunc(lua_State* internalState); diff --git a/include/Nazara/Lua/LuaState.inl b/include/Nazara/Lua/LuaState.inl index fa4ecaaf0..12fcdb226 100644 --- a/include/Nazara/Lua/LuaState.inl +++ b/include/Nazara/Lua/LuaState.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Lua scripting module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include #include @@ -20,6 +19,13 @@ namespace Nz { } + inline LuaState::LuaState(LuaState&& state) noexcept : + m_lastError(state.m_lastError), + m_state(state.m_state) + { + state.m_state = nullptr; + } + inline lua_State* LuaState::GetInternalState() const { return m_state; @@ -770,8 +776,18 @@ namespace Nz SetMetatable(tname); } + inline LuaState& LuaState::operator=(LuaState&& state) noexcept + { + m_lastError = std::move(state.m_lastError); + m_state = state.m_state; + + state.m_state = nullptr; + + return *this; + } + template - T LuaState::CheckBounds(int index, long long value) const + std::enable_if_t::value, T> LuaState::CheckBounds(int index, long long value) const { constexpr long long minBounds = std::numeric_limits::min(); constexpr long long maxBounds = std::numeric_limits::max(); @@ -785,6 +801,22 @@ namespace Nz return static_cast(value); } + template + std::enable_if_t::value, T> LuaState::CheckBounds(int index, long long value) const + { + unsigned long long uValue = static_cast(value); + constexpr unsigned long long minBounds = 0; + constexpr unsigned long long maxBounds = std::numeric_limits::max(); + if (uValue < minBounds || uValue > maxBounds) + { + Nz::StringStream stream; + stream << "Argument #" << index << " is outside value range [" << minBounds << ", " << maxBounds << "] (" << value << ')'; + Error(stream); + } + + return static_cast(uValue); + } + inline LuaState LuaState::GetState(lua_State* internalState) { return LuaState(internalState); diff --git a/include/Nazara/Math/Quaternion.inl b/include/Nazara/Math/Quaternion.inl index def663ee4..553dedad8 100644 --- a/include/Nazara/Math/Quaternion.inl +++ b/include/Nazara/Math/Quaternion.inl @@ -481,11 +481,11 @@ namespace Nz T test = x * y + z * w; if (test > F(0.499)) // singularity at north pole - return EulerAngles(FromDegrees(F(90.0)), FromRadians(F(2.0) * std::atan2(x, w)), F(0.0)); + return EulerAngles(F(0.0), FromRadians(F(2.0) * std::atan2(x, w)), FromDegrees(F(90.0))); if (test < F(-0.499)) // singularity at south pole - return EulerAngles(FromDegrees(F(-90.0)), FromRadians(F(-2.0) * std::atan2(x, w)), F(0.0)); + return EulerAngles(F(0.0), FromRadians(F(-2.0) * std::atan2(x, w)), FromDegrees(F(-90.0))); return EulerAngles(FromRadians(std::atan2(F(2.0) * x * w - F(2.0) * y * z, F(1.0) - F(2.0) * x * x - F(2.0) * z * z)), FromRadians(std::atan2(F(2.0) * y * w - F(2.0) * x * z, F(1.0) - F(2.0) * y * y - F(2.0) * z * z)), diff --git a/include/Nazara/Network.hpp b/include/Nazara/Network.hpp index 1b2dc72c5..151bc3f52 100644 --- a/include/Nazara/Network.hpp +++ b/include/Nazara/Network.hpp @@ -32,6 +32,10 @@ #include #include #include +#include +#include +#include +#include #include #include #include diff --git a/include/Nazara/Network/ENetCompressor.hpp b/include/Nazara/Network/ENetCompressor.hpp new file mode 100644 index 000000000..5466c80b6 --- /dev/null +++ b/include/Nazara/Network/ENetCompressor.hpp @@ -0,0 +1,39 @@ +/* + Copyright(c) 2002 - 2016 Lee Salzman + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Network module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_ENETCOMPRESSOR_HPP +#define NAZARA_ENETCOMPRESSOR_HPP + +#include +#include +#include + +namespace Nz +{ + class ENetPeer; + + class NAZARA_NETWORK_API ENetCompressor + { + public: + ENetCompressor() = default; + ~ENetCompressor(); + + virtual std::size_t Compress(const ENetPeer* peer, const NetBuffer* buffers, std::size_t bufferCount, std::size_t totalInputSize, UInt8* output, std::size_t maxOutputSize) = 0; + virtual std::size_t Decompress(const ENetPeer* peer, const UInt8* input, std::size_t inputSize, UInt8* output, std::size_t maxOutputSize) = 0; + }; +} + +#endif // NAZARA_ENETCOMPRESSOR_HPP diff --git a/include/Nazara/Network/ENetHost.hpp b/include/Nazara/Network/ENetHost.hpp index eb5c7d6de..39d6134a3 100644 --- a/include/Nazara/Network/ENetHost.hpp +++ b/include/Nazara/Network/ENetHost.hpp @@ -1,4 +1,4 @@ -/* +/* Copyright(c) 2002 - 2016 Lee Salzman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : @@ -19,8 +19,8 @@ #include #include -#include #include +#include #include #include #include @@ -28,11 +28,7 @@ #include #include #include -#include -#include #include -#include -#include namespace Nz { @@ -55,8 +51,8 @@ namespace Nz ENetPeer* Connect(const String& hostName, NetProtocol protocol = NetProtocol_Any, const String& service = "http", ResolveError* error = nullptr, std::size_t channelCount = 0, UInt32 data = 0); inline bool Create(NetProtocol protocol, UInt16 port, std::size_t peerCount, std::size_t channelCount = 0); - bool Create(const IpAddress& address, std::size_t peerCount, std::size_t channelCount = 0); - bool Create(const IpAddress& address, std::size_t peerCount, std::size_t channelCount, UInt32 incomingBandwidth, UInt32 outgoingBandwidth); + bool Create(const IpAddress& listenAddress, std::size_t peerCount, std::size_t channelCount = 0); + bool Create(const IpAddress& listenAddress, std::size_t peerCount, std::size_t channelCount, UInt32 incomingBandwidth, UInt32 outgoingBandwidth); void Destroy(); void Flush(); @@ -66,6 +62,8 @@ namespace Nz int Service(ENetEvent* event, UInt32 timeout); + inline void SetCompressor(std::unique_ptr&& compressor); + void SimulateNetwork(double packetLossProbability, UInt16 minDelay, UInt16 maxDelay); ENetHost& operator=(const ENetHost&) = delete; @@ -130,6 +128,7 @@ namespace Nz std::size_t m_peerCount; std::size_t m_receivedDataLength; std::uniform_int_distribution m_packetDelayDistribution; + std::unique_ptr m_compressor; std::vector m_peers; std::vector m_pendingIncomingPackets; std::vector m_pendingOutgoingPackets; @@ -152,6 +151,7 @@ namespace Nz UInt32 m_totalReceivedPackets; UInt64 m_totalSentData; UInt64 m_totalReceivedData; + bool m_allowsIncomingConnections; bool m_continueSending; bool m_isSimulationEnabled; bool m_recalculateBandwidthLimits; diff --git a/include/Nazara/Network/ENetHost.inl b/include/Nazara/Network/ENetHost.inl index 3f35a8f39..1fabd38e6 100644 --- a/include/Nazara/Network/ENetHost.inl +++ b/include/Nazara/Network/ENetHost.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include @@ -52,16 +51,21 @@ namespace Nz m_socket.Close(); } - inline Nz::IpAddress ENetHost::GetBoundAddress() const + inline IpAddress ENetHost::GetBoundAddress() const { return m_address; } - inline UInt32 Nz::ENetHost::GetServiceTime() const + inline UInt32 ENetHost::GetServiceTime() const { return m_serviceTime; } + inline void ENetHost::SetCompressor(std::unique_ptr&& compressor) + { + m_compressor = std::move(compressor); + } + inline ENetPacketRef ENetHost::AllocatePacket(ENetPacketFlags flags, NetPacket&& data) { ENetPacketRef ref = AllocatePacket(flags); diff --git a/include/Nazara/Network/ENetPeer.hpp b/include/Nazara/Network/ENetPeer.hpp index 4e36378a5..b8aa0fead 100644 --- a/include/Nazara/Network/ENetPeer.hpp +++ b/include/Nazara/Network/ENetPeer.hpp @@ -19,12 +19,9 @@ #include #include -#include #include #include #include -#include -#include #include #include #include @@ -82,7 +79,6 @@ namespace Nz void InitIncoming(std::size_t channelCount, const IpAddress& address, ENetProtocolConnect& incomingCommand); void InitOutgoing(std::size_t channelCount, const IpAddress& address, UInt32 connectId, UInt32 windowSize); - struct Acknowledgement; struct Channel; struct IncomingCommmand; struct OutgoingCommand; diff --git a/include/Nazara/Network/ENetPeer.inl b/include/Nazara/Network/ENetPeer.inl index d831b4d0d..c3ede0978 100644 --- a/include/Nazara/Network/ENetPeer.inl +++ b/include/Nazara/Network/ENetPeer.inl @@ -2,8 +2,6 @@ // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include #include namespace Nz diff --git a/include/Nazara/Network/IpAddress.hpp b/include/Nazara/Network/IpAddress.hpp index c3775effd..f5e1ca9d8 100644 --- a/include/Nazara/Network/IpAddress.hpp +++ b/include/Nazara/Network/IpAddress.hpp @@ -50,7 +50,7 @@ namespace Nz String ToString() const; inline UInt32 ToUInt32() const; - inline operator bool() const; + inline explicit operator bool() const; IpAddress& operator=(const IpAddress&) = default; IpAddress& operator=(IpAddress&&) = default; diff --git a/include/Nazara/Network/NetPacket.hpp b/include/Nazara/Network/NetPacket.hpp index 9d5bb99a4..8de3d9258 100644 --- a/include/Nazara/Network/NetPacket.hpp +++ b/include/Nazara/Network/NetPacket.hpp @@ -11,7 +11,6 @@ #include #include #include -#include #include namespace Nz diff --git a/include/Nazara/Network/Network.hpp b/include/Nazara/Network/Network.hpp index ca6ca9ee6..bcda5a83e 100644 --- a/include/Nazara/Network/Network.hpp +++ b/include/Nazara/Network/Network.hpp @@ -8,7 +8,6 @@ #define NAZARA_MODULENAME_HPP #include -#include #include namespace Nz diff --git a/include/Nazara/Network/RUdpConnection.hpp b/include/Nazara/Network/RUdpConnection.hpp index 3cdb6c3be..d04211d07 100644 --- a/include/Nazara/Network/RUdpConnection.hpp +++ b/include/Nazara/Network/RUdpConnection.hpp @@ -22,8 +22,6 @@ namespace Nz { - class RUdpClient; - class NAZARA_NETWORK_API RUdpConnection { friend class Network; diff --git a/include/Nazara/Network/RUdpConnection.inl b/include/Nazara/Network/RUdpConnection.inl index eaf4a0e7a..fa61ec136 100644 --- a/include/Nazara/Network/RUdpConnection.inl +++ b/include/Nazara/Network/RUdpConnection.inl @@ -2,8 +2,6 @@ // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include #include namespace Nz diff --git a/include/Nazara/Network/SocketPoller.hpp b/include/Nazara/Network/SocketPoller.hpp index c801ca5e2..9e7d34a61 100644 --- a/include/Nazara/Network/SocketPoller.hpp +++ b/include/Nazara/Network/SocketPoller.hpp @@ -8,8 +8,8 @@ #define NAZARA_SOCKETPOLLER_HPP #include +#include #include -#include namespace Nz { @@ -19,7 +19,7 @@ namespace Nz { public: SocketPoller(); - inline SocketPoller(SocketPoller&& socketPoller); + SocketPoller(SocketPoller&&) noexcept = default; ~SocketPoller(); void Clear(); @@ -31,12 +31,12 @@ namespace Nz bool RegisterSocket(AbstractSocket& socket, SocketPollEventFlags eventFlags); void UnregisterSocket(AbstractSocket& socket); - bool Wait(UInt64 msTimeout); + bool Wait(int msTimeout); - inline SocketPoller& operator=(SocketPoller&& socketPoller); + SocketPoller& operator=(SocketPoller&&) noexcept = default; private: - SocketPollerImpl* m_impl; + MovablePtr m_impl; }; } diff --git a/include/Nazara/Network/SocketPoller.inl b/include/Nazara/Network/SocketPoller.inl index 66331b9cb..7c9dfe7cb 100644 --- a/include/Nazara/Network/SocketPoller.inl +++ b/include/Nazara/Network/SocketPoller.inl @@ -2,36 +2,10 @@ // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include #include namespace Nz { - /*! - * \brief Constructs a SocketPoller object with another one by move semantic - * - * \param socketPoller SocketPoller to move into this - */ - inline SocketPoller::SocketPoller(SocketPoller&& socketPoller) : - m_impl(socketPoller.m_impl) - { - socketPoller.m_impl = nullptr; - } - - /*! - * \brief Moves the SocketPoller into this - * \return A reference to this - * - * \param socketPoller SocketPoller to move in this - */ - inline SocketPoller& SocketPoller::operator=(SocketPoller&& socketPoller) - { - m_impl = socketPoller.m_impl; - socketPoller.m_impl = nullptr; - - return *this; - } } #include diff --git a/include/Nazara/Network/TcpClient.hpp b/include/Nazara/Network/TcpClient.hpp index a3b229bda..8acdc0b5d 100644 --- a/include/Nazara/Network/TcpClient.hpp +++ b/include/Nazara/Network/TcpClient.hpp @@ -9,14 +9,13 @@ #include #include -#include #include #include #include -#include namespace Nz { + struct NetBuffer; class NetPacket; class NAZARA_NETWORK_API TcpClient : public AbstractSocket, public Stream diff --git a/include/Nazara/Network/TcpClient.inl b/include/Nazara/Network/TcpClient.inl index 0ab267436..2d410d4f3 100644 --- a/include/Nazara/Network/TcpClient.inl +++ b/include/Nazara/Network/TcpClient.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include namespace Nz diff --git a/include/Nazara/Network/UdpSocket.hpp b/include/Nazara/Network/UdpSocket.hpp index 0086249e9..ec4228bd3 100644 --- a/include/Nazara/Network/UdpSocket.hpp +++ b/include/Nazara/Network/UdpSocket.hpp @@ -10,10 +10,10 @@ #include #include #include -#include namespace Nz { + struct NetBuffer; class NetPacket; class NAZARA_NETWORK_API UdpSocket : public AbstractSocket @@ -39,6 +39,7 @@ namespace Nz std::size_t QueryMaxDatagramSize(); bool Receive(void* buffer, std::size_t size, IpAddress* from, std::size_t* received); + bool ReceiveMultiple(NetBuffer* buffers, std::size_t bufferCount, IpAddress* from, std::size_t* received); bool ReceivePacket(NetPacket* packet, IpAddress* from); bool Send(const IpAddress& to, const void* buffer, std::size_t size, std::size_t* sent); diff --git a/include/Nazara/Noise/FBM.hpp b/include/Nazara/Noise/FBM.hpp index 41cbc5758..3f573f630 100644 --- a/include/Nazara/Noise/FBM.hpp +++ b/include/Nazara/Noise/FBM.hpp @@ -6,7 +6,6 @@ #define NAZARA_FBM_HPP #include -#include #include namespace Nz diff --git a/include/Nazara/Noise/MixerBase.hpp b/include/Nazara/Noise/MixerBase.hpp index 954932114..06d658282 100644 --- a/include/Nazara/Noise/MixerBase.hpp +++ b/include/Nazara/Noise/MixerBase.hpp @@ -7,7 +7,6 @@ #include #include -#include namespace Nz { diff --git a/include/Nazara/Noise/Noise.hpp b/include/Nazara/Noise/Noise.hpp index 8138ee41b..49ddcedd3 100644 --- a/include/Nazara/Noise/Noise.hpp +++ b/include/Nazara/Noise/Noise.hpp @@ -8,7 +8,6 @@ #define NAZARA_NOISE_HPP #include -#include #include namespace Nz diff --git a/include/Nazara/Noise/Perlin.hpp b/include/Nazara/Noise/Perlin.hpp index 64211c4e4..f5af29bcf 100644 --- a/include/Nazara/Noise/Perlin.hpp +++ b/include/Nazara/Noise/Perlin.hpp @@ -8,7 +8,6 @@ #include #include #include -#include namespace Nz { diff --git a/include/Nazara/Noise/Simplex.hpp b/include/Nazara/Noise/Simplex.hpp index 2b6309671..90bab5ec5 100644 --- a/include/Nazara/Noise/Simplex.hpp +++ b/include/Nazara/Noise/Simplex.hpp @@ -8,7 +8,6 @@ #include #include #include -#include namespace Nz { diff --git a/include/Nazara/Noise/Worley.hpp b/include/Nazara/Noise/Worley.hpp index 1b820e513..421f192a5 100644 --- a/include/Nazara/Noise/Worley.hpp +++ b/include/Nazara/Noise/Worley.hpp @@ -10,7 +10,6 @@ #include #include #include -#include #include namespace Nz diff --git a/include/Nazara/Physics2D/Collider2D.hpp b/include/Nazara/Physics2D/Collider2D.hpp index b09e8781f..633d556a8 100644 --- a/include/Nazara/Physics2D/Collider2D.hpp +++ b/include/Nazara/Physics2D/Collider2D.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -18,7 +19,6 @@ #include struct cpShape; -struct cpSpace; namespace Nz { @@ -33,6 +33,7 @@ namespace Nz { friend Collider2DLibrary; friend RigidBody2D; + friend class CompoundCollider2D; //< See CompoundCollider2D::CreateShapes public: inline Collider2D(); @@ -40,7 +41,7 @@ namespace Nz Collider2D(Collider2D&&) = delete; virtual ~Collider2D(); - virtual float ComputeInertialMatrix(float mass) const = 0; + virtual float ComputeMomentOfInertia(float mass) const = 0; inline Nz::UInt32 GetCategoryMask() const; inline Nz::UInt32 GetCollisionGroup() const; @@ -64,7 +65,7 @@ namespace Nz NazaraSignal(OnColliderRelease, const Collider2D* /*collider*/); protected: - virtual std::vector CreateShapes(RigidBody2D* body) const = 0; + virtual void CreateShapes(RigidBody2D* body, std::vector& shapes) const = 0; bool m_trigger; Nz::UInt32 m_categoryMask; @@ -89,7 +90,7 @@ namespace Nz BoxCollider2D(const Vector2f& size, float radius = 0.f); BoxCollider2D(const Rectf& rect, float radius = 0.f); - float ComputeInertialMatrix(float mass) const override; + float ComputeMomentOfInertia(float mass) const override; inline const Rectf& GetRect() const; inline Vector2f GetSize() const; @@ -98,7 +99,7 @@ namespace Nz template static BoxCollider2DRef New(Args&&... args); private: - std::vector CreateShapes(RigidBody2D* body) const override; + void CreateShapes(RigidBody2D* body, std::vector& shapes) const override; Rectf m_rect; float m_radius; @@ -114,7 +115,7 @@ namespace Nz public: CircleCollider2D(float radius, const Vector2f& offset = Vector2f::Zero()); - float ComputeInertialMatrix(float mass) const override; + float ComputeMomentOfInertia(float mass) const override; inline float GetRadius() const; ColliderType2D GetType() const override; @@ -122,12 +123,58 @@ namespace Nz template static CircleCollider2DRef New(Args&&... args); private: - std::vector CreateShapes(RigidBody2D* body) const override; + void CreateShapes(RigidBody2D* body, std::vector& shapes) const override; Vector2f m_offset; float m_radius; }; + class CompoundCollider2D; + + using CompoundCollider2DConstRef = ObjectRef; + using CompoundCollider2DRef = ObjectRef; + + class NAZARA_PHYSICS2D_API CompoundCollider2D : public Collider2D + { + public: + CompoundCollider2D(std::vector geoms); + + float ComputeMomentOfInertia(float mass) const override; + + inline const std::vector& GetGeoms() const; + ColliderType2D GetType() const override; + + template static CompoundCollider2DRef New(Args&&... args); + + private: + void CreateShapes(RigidBody2D* body, std::vector& shapes) const override; + + std::vector m_geoms; + }; + + class ConvexCollider2D; + + using ConvexCollider2DConstRef = ObjectRef; + using ConvexCollider2DRef = ObjectRef; + + class NAZARA_PHYSICS2D_API ConvexCollider2D : public Collider2D + { + public: + ConvexCollider2D(SparsePtr vertices, std::size_t vertexCount, float radius = 0.f); + + float ComputeMomentOfInertia(float mass) const override; + + ColliderType2D GetType() const override; + + template static ConvexCollider2DRef New(Args&&... args); + + private: + void CreateShapes(RigidBody2D* body, std::vector& shapes) const override; + + std::vector m_vertices; + float m_radius; + }; + class NullCollider2D; using NullCollider2DConstRef = ObjectRef; @@ -138,14 +185,14 @@ namespace Nz public: NullCollider2D() = default; - float ComputeInertialMatrix(float mass) const override; + float ComputeMomentOfInertia(float mass) const override; ColliderType2D GetType() const override; template static NullCollider2DRef New(Args&&... args); private: - std::vector CreateShapes(RigidBody2D* body) const override; + void CreateShapes(RigidBody2D* body, std::vector& shapes) const override; }; class SegmentCollider2D; @@ -158,7 +205,7 @@ namespace Nz public: inline SegmentCollider2D(const Vector2f& first, const Vector2f& second, float thickness = 1.f); - float ComputeInertialMatrix(float mass) const override; + float ComputeMomentOfInertia(float mass) const override; inline const Vector2f& GetFirstPoint() const; inline float GetLength() const; @@ -168,7 +215,7 @@ namespace Nz template static SegmentCollider2DRef New(Args&&... args); private: - std::vector CreateShapes(RigidBody2D* body) const override; + void CreateShapes(RigidBody2D* body, std::vector& shapes) const override; Vector2f m_first; Vector2f m_second; diff --git a/include/Nazara/Physics2D/Collider2D.inl b/include/Nazara/Physics2D/Collider2D.inl index 60cf8559f..79af0942d 100644 --- a/include/Nazara/Physics2D/Collider2D.inl +++ b/include/Nazara/Physics2D/Collider2D.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Physics 2D module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include @@ -100,6 +99,29 @@ namespace Nz return object.release(); } + inline const std::vector& Nz::CompoundCollider2D::GetGeoms() const + { + return m_geoms; + } + + template + CompoundCollider2DRef CompoundCollider2D::New(Args&&... args) + { + std::unique_ptr object(new CompoundCollider2D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + + template + ConvexCollider2DRef ConvexCollider2D::New(Args&&... args) + { + std::unique_ptr object(new ConvexCollider2D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } + template NullCollider2DRef NullCollider2D::New(Args&&... args) { diff --git a/include/Nazara/Physics2D/Enums.hpp b/include/Nazara/Physics2D/Enums.hpp index 86c1411f4..8cbb73d39 100644 --- a/include/Nazara/Physics2D/Enums.hpp +++ b/include/Nazara/Physics2D/Enums.hpp @@ -12,6 +12,7 @@ namespace Nz enum ColliderType2D { ColliderType2D_Box, + ColliderType2D_Compound, ColliderType2D_Convex, ColliderType2D_Circle, ColliderType2D_Null, diff --git a/include/Nazara/Physics2D/PhysWorld2D.hpp b/include/Nazara/Physics2D/PhysWorld2D.hpp index 30a3b1141..939943df5 100644 --- a/include/Nazara/Physics2D/PhysWorld2D.hpp +++ b/include/Nazara/Physics2D/PhysWorld2D.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -24,10 +25,10 @@ namespace Nz { friend RigidBody2D; - using ContactEndCallback = void(*)(PhysWorld2D& world, RigidBody2D& bodyA, RigidBody2D& bodyB, void* userdata); - using ContactPreSolveCallback = bool(*)(PhysWorld2D& world, RigidBody2D& bodyA, RigidBody2D& bodyB, void* userdata); - using ContactPostSolveCallback = void(*)(PhysWorld2D& world, RigidBody2D& bodyA, RigidBody2D& bodyB, void* userdata); - using ContactStartCallback = bool(*)(PhysWorld2D& world, RigidBody2D& bodyA, RigidBody2D& bodyB, void* userdata); + using ContactEndCallback = std::function; + using ContactPreSolveCallback = std::function; + using ContactPostSolveCallback = std::function; + using ContactStartCallback = std::function; public: struct Callback; @@ -39,6 +40,7 @@ namespace Nz PhysWorld2D(PhysWorld2D&&) = delete; ///TODO ~PhysWorld2D(); + float GetDamping() const; Vector2f GetGravity() const; cpSpace* GetHandle() const; float GetStepSize() const; @@ -54,6 +56,7 @@ namespace Nz void RegisterCallbacks(unsigned int collisionId, const Callback& callbacks); void RegisterCallbacks(unsigned int collisionIdA, unsigned int collisionIdB, const Callback& callbacks); + void SetDamping(float dampingValue); void SetGravity(const Vector2f& gravity); void SetStepSize(float stepSize); diff --git a/include/Nazara/Physics2D/Physics2D.hpp b/include/Nazara/Physics2D/Physics2D.hpp index 3a9f2b731..73387980e 100644 --- a/include/Nazara/Physics2D/Physics2D.hpp +++ b/include/Nazara/Physics2D/Physics2D.hpp @@ -8,7 +8,6 @@ #define NAZARA_PHYSICS2D_HPP #include -#include #include namespace Nz diff --git a/include/Nazara/Physics2D/RigidBody2D.hpp b/include/Nazara/Physics2D/RigidBody2D.hpp index 9763aba47..1319d8e64 100644 --- a/include/Nazara/Physics2D/RigidBody2D.hpp +++ b/include/Nazara/Physics2D/RigidBody2D.hpp @@ -10,10 +10,7 @@ #include #include #include -#include -#include #include -#include #include #include @@ -44,18 +41,21 @@ namespace Nz const Collider2DRef& GetGeom() const; cpBody* GetHandle() const; float GetMass() const; + float GetMomentOfInertia() const; Vector2f GetPosition() const; float GetRotation() const; void* GetUserdata() const; Vector2f GetVelocity() const; + PhysWorld2D* GetWorld() const; - bool IsMoveable() const; + bool IsKinematic() const; bool IsSleeping() const; void SetAngularVelocity(float angularVelocity); - void SetGeom(Collider2DRef geom); - void SetMass(float mass); + void SetGeom(Collider2DRef geom, bool recomputeMoment = true); + void SetMass(float mass, bool recomputeMoment = true); void SetMassCenter(const Vector2f& center); + void SetMomentOfInertia(float moment); void SetPosition(const Vector2f& position); void SetRotation(float rotation); void SetUserdata(void* ud); @@ -68,7 +68,8 @@ namespace Nz NazaraSignal(OnRigidBody2DRelease, RigidBody2D* /*rigidBody*/); private: - void Create(float mass = 1.f, float moment = 1.f); + void CopyBodyData(cpBody* body); + cpBody* Create(float mass = 1.f, float moment = 1.f); void Destroy(); std::vector m_shapes; diff --git a/include/Nazara/Physics3D/Collider3D.hpp b/include/Nazara/Physics3D/Collider3D.hpp index 13bf32c2f..b7a5fe08c 100644 --- a/include/Nazara/Physics3D/Collider3D.hpp +++ b/include/Nazara/Physics3D/Collider3D.hpp @@ -8,7 +8,6 @@ #define NAZARA_COLLIDER3D_HPP #include -#include #include #include #include @@ -32,6 +31,7 @@ namespace Nz ///TODO: TreeGeom class Collider3D; + class PrimitiveList; class PhysWorld3D; using Collider3DConstRef = ObjectRef; @@ -135,7 +135,7 @@ namespace Nz class NAZARA_PHYSICS3D_API CompoundCollider3D : public Collider3D { public: - CompoundCollider3D(Collider3D** geoms, std::size_t geomCount); + CompoundCollider3D(std::vector geoms); const std::vector& GetGeoms() const; ColliderType3D GetType() const override; diff --git a/include/Nazara/Physics3D/PhysWorld3D.hpp b/include/Nazara/Physics3D/PhysWorld3D.hpp index 633be2b61..db6c5af00 100644 --- a/include/Nazara/Physics3D/PhysWorld3D.hpp +++ b/include/Nazara/Physics3D/PhysWorld3D.hpp @@ -8,7 +8,6 @@ #define NAZARA_PHYSWORLD_HPP #include -#include #include #include diff --git a/include/Nazara/Physics3D/Physics3D.hpp b/include/Nazara/Physics3D/Physics3D.hpp index b0d6f69f5..d97e7405d 100644 --- a/include/Nazara/Physics3D/Physics3D.hpp +++ b/include/Nazara/Physics3D/Physics3D.hpp @@ -8,7 +8,6 @@ #define NAZARA_PHYSICS3D_HPP #include -#include #include namespace Nz diff --git a/include/Nazara/Physics3D/RigidBody3D.hpp b/include/Nazara/Physics3D/RigidBody3D.hpp index 502fd21a7..bc7f668b0 100644 --- a/include/Nazara/Physics3D/RigidBody3D.hpp +++ b/include/Nazara/Physics3D/RigidBody3D.hpp @@ -47,6 +47,7 @@ namespace Nz Vector3f GetPosition() const; Quaternionf GetRotation() const; Vector3f GetVelocity() const; + PhysWorld3D* GetWorld() const; bool IsAutoSleepEnabled() const; bool IsMoveable() const; diff --git a/include/Nazara/Platform.hpp b/include/Nazara/Platform.hpp new file mode 100644 index 000000000..fc2b3c0d3 --- /dev/null +++ b/include/Nazara/Platform.hpp @@ -0,0 +1,48 @@ +// This file was automatically generated + +/* + Nazara Engine - Platform module + + Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do + so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +#pragma once + +#ifndef NAZARA_GLOBAL_PLATFORM_HPP +#define NAZARA_GLOBAL_PLATFORM_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif // NAZARA_GLOBAL_PLATFORM_HPP + diff --git a/include/Nazara/Platform/Config.hpp b/include/Nazara/Platform/Config.hpp new file mode 100644 index 000000000..6bb056f27 --- /dev/null +++ b/include/Nazara/Platform/Config.hpp @@ -0,0 +1,54 @@ +/* + Nazara Engine - Platform module + + Copyright (C) 2015 Jérôme "Lynix" Leclercq (Lynix680@gmail.com) + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do + so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +#pragma once + +#ifndef NAZARA_CONFIG_PLATFORM_HPP +#define NAZARA_CONFIG_PLATFORM_HPP + +/// Each modification of a parameter needs a recompilation of the module + +// Use the MemoryManager to manage dynamic allocations (can detect memory leak but allocations/frees are slower) +#define NAZARA_PLATFORM_MANAGE_MEMORY 0 + +// Activate the security tests based on the code (Advised for development) +#define NAZARA_PLATFORM_SAFE 1 + +// Protect the classes against data race +//#define NAZARA_PLATFORM_THREADSAFE 1 + +// On Windows, ALT and F10 keys do not activate the window menu +#define NAZARA_PLATFORM_WINDOWS_DISABLE_MENU_KEYS 1 + +#if defined(NAZARA_STATIC) + #define NAZARA_PLATFORM_API +#else + #ifdef NAZARA_PLATFORM_BUILD + #define NAZARA_PLATFORM_API NAZARA_EXPORT + #else + #define NAZARA_PLATFORM_API NAZARA_IMPORT + #endif +#endif + +#endif // NAZARA_CONFIG_PLATFORM_HPP diff --git a/include/Nazara/Platform/ConfigCheck.hpp b/include/Nazara/Platform/ConfigCheck.hpp new file mode 100644 index 000000000..2b58e4586 --- /dev/null +++ b/include/Nazara/Platform/ConfigCheck.hpp @@ -0,0 +1,23 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Platform module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_CONFIG_CHECK_PLATFORM_HPP +#define NAZARA_CONFIG_CHECK_PLATFORM_HPP + +/// This file is used to check the constant values defined in Config.hpp + +#include +#define NazaraCheckTypeAndVal(name, type, op, val, err) static_assert(std::is_ ##type ::value && name op val, #type err) + +// We force the value of MANAGE_MEMORY in debug +#if defined(NAZARA_DEBUG) && !NAZARA_PLATFORM_MANAGE_MEMORY + #undef NAZARA_PLATFORM_MANAGE_MEMORY + #define NAZARA_PLATFORM_MANAGE_MEMORY 0 +#endif + +#undef NazaraCheckTypeAndVal + +#endif // NAZARA_CONFIG_CHECK_PLATFORM_HPP diff --git a/include/Nazara/Utility/Cursor.hpp b/include/Nazara/Platform/Cursor.hpp similarity index 85% rename from include/Nazara/Utility/Cursor.hpp rename to include/Nazara/Platform/Cursor.hpp index 870b17b55..7cf5c979d 100644 --- a/include/Nazara/Utility/Cursor.hpp +++ b/include/Nazara/Platform/Cursor.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -10,7 +10,8 @@ #include #include #include -#include +#include +#include #include #include @@ -23,9 +24,9 @@ namespace Nz using CursorConstRef = ObjectRef; using CursorRef = ObjectRef; - class NAZARA_UTILITY_API Cursor : public RefCounted + class NAZARA_PLATFORM_API Cursor : public RefCounted { - friend class Utility; + friend class Platform; friend class WindowImpl; public: @@ -66,6 +67,6 @@ namespace Nz }; } -#include +#include #endif // NAZARA_CURSOR_HPP diff --git a/include/Nazara/Utility/Cursor.inl b/include/Nazara/Platform/Cursor.inl similarity index 88% rename from include/Nazara/Utility/Cursor.inl rename to include/Nazara/Platform/Cursor.inl index 58d15bdec..5177faeea 100644 --- a/include/Nazara/Utility/Cursor.inl +++ b/include/Nazara/Platform/Cursor.inl @@ -1,10 +1,9 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include -#include +#include namespace Nz { @@ -66,4 +65,4 @@ namespace Nz } } -#include +#include diff --git a/include/Nazara/Utility/CursorController.hpp b/include/Nazara/Platform/CursorController.hpp similarity index 85% rename from include/Nazara/Utility/CursorController.hpp rename to include/Nazara/Platform/CursorController.hpp index 0c2943356..07c86e92b 100644 --- a/include/Nazara/Utility/CursorController.hpp +++ b/include/Nazara/Platform/CursorController.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -11,8 +11,8 @@ #include #include #include -#include -#include +#include +#include namespace Nz { @@ -37,6 +37,6 @@ namespace Nz }; } -#include +#include #endif // NAZARA_CURSORCONTROLLER_HPP diff --git a/include/Nazara/Utility/CursorController.inl b/include/Nazara/Platform/CursorController.inl similarity index 56% rename from include/Nazara/Utility/CursorController.inl rename to include/Nazara/Platform/CursorController.inl index b1f54d05a..75260b66d 100644 --- a/include/Nazara/Utility/CursorController.inl +++ b/include/Nazara/Platform/CursorController.inl @@ -1,9 +1,9 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include +#include +#include namespace Nz { @@ -13,4 +13,4 @@ namespace Nz } } -#include +#include diff --git a/include/Nazara/Platform/Debug.hpp b/include/Nazara/Platform/Debug.hpp new file mode 100644 index 000000000..94d6e9134 --- /dev/null +++ b/include/Nazara/Platform/Debug.hpp @@ -0,0 +1,8 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Platform module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#if NAZARA_PLATFORM_MANAGE_MEMORY + #include +#endif diff --git a/include/Nazara/Platform/DebugOff.hpp b/include/Nazara/Platform/DebugOff.hpp new file mode 100644 index 000000000..d6072e479 --- /dev/null +++ b/include/Nazara/Platform/DebugOff.hpp @@ -0,0 +1,9 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Platform module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +// We suppose that Debug.hpp is already included, same goes for Config.hpp +#if NAZARA_PLATFORM_MANAGE_MEMORY + #undef delete + #undef new +#endif diff --git a/include/Nazara/Platform/Enums.hpp b/include/Nazara/Platform/Enums.hpp new file mode 100644 index 000000000..252412904 --- /dev/null +++ b/include/Nazara/Platform/Enums.hpp @@ -0,0 +1,85 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Platform module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_ENUMS_PLATFORM_HPP +#define NAZARA_ENUMS_PLATFORM_HPP + +#include + +namespace Nz +{ + enum SystemCursor + { + SystemCursor_Crosshair, + SystemCursor_Default, + SystemCursor_Hand, + SystemCursor_Help, + SystemCursor_Move, + SystemCursor_None, + SystemCursor_Pointer, + SystemCursor_Progress, + SystemCursor_ResizeE, + SystemCursor_ResizeN, + SystemCursor_ResizeNE, + SystemCursor_ResizeNW, + SystemCursor_ResizeS, + SystemCursor_ResizeSE, + SystemCursor_ResizeSW, + SystemCursor_ResizeW, + SystemCursor_Text, + SystemCursor_Wait, + + SystemCursor_Max = SystemCursor_Wait + }; + + enum WindowEventType + { + WindowEventType_GainedFocus, + WindowEventType_LostFocus, + WindowEventType_KeyPressed, + WindowEventType_KeyReleased, + WindowEventType_MouseButtonDoubleClicked, + WindowEventType_MouseButtonPressed, + WindowEventType_MouseButtonReleased, + WindowEventType_MouseEntered, + WindowEventType_MouseLeft, + WindowEventType_MouseMoved, + WindowEventType_MouseWheelMoved, + WindowEventType_Moved, + WindowEventType_Quit, + WindowEventType_Resized, + WindowEventType_TextEntered, + + WindowEventType_Max = WindowEventType_TextEntered + }; + + enum WindowStyle + { + WindowStyle_None, ///< Window has no border nor titlebar. + WindowStyle_Fullscreen, ///< At the window creation, the OS tries to set it in fullscreen. + + WindowStyle_Closable, ///< Allows the window to be closed by a button in the titlebar, generating a Quit event. + WindowStyle_Resizable, ///< Allows the window to be resized by dragging its corners or by a button of the titlebar. + WindowStyle_Titlebar, ///< Adds a titlebar to the window, this option is automatically enabled if buttons of the titlebar are enabled. + + WindowStyle_Threaded, ///< Runs the window into a thread, allowing the application to keep updating while resizing/dragging the window. + + WindowStyle_Max = WindowStyle_Threaded + }; + + template<> + struct EnumAsFlags + { + static constexpr bool value = true; + static constexpr int max = WindowStyle_Max; + }; + + using WindowStyleFlags = Flags; + + constexpr WindowStyleFlags WindowStyle_Default = WindowStyle_Closable | WindowStyle_Resizable | WindowStyle_Titlebar; +} + +#endif // NAZARA_ENUMS_PLATFORM_HPP diff --git a/include/Nazara/Utility/Event.hpp b/include/Nazara/Platform/Event.hpp similarity index 77% rename from include/Nazara/Utility/Event.hpp rename to include/Nazara/Platform/Event.hpp index b67eedc0c..ece401890 100644 --- a/include/Nazara/Utility/Event.hpp +++ b/include/Nazara/Platform/Event.hpp @@ -1,23 +1,23 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -// Interface inspirée de la SFML par Laurent Gomila +// Interface inspired by the SFML of Laurent Gomila (and its team) #pragma once #ifndef NAZARA_EVENT_HPP #define NAZARA_EVENT_HPP -#include -#include -#include +#include +#include +#include namespace Nz { struct WindowEvent { - // Utilisé par: + // Used by: // -WindowEventType_KeyPressed // -WindowEventType_KeyReleased struct KeyEvent @@ -30,7 +30,7 @@ namespace Nz bool system; }; - // Utilisé par: + // Used by: // -WindowEventType_MouseButtonDoubleClicked // -WindowEventType_MouseButtonPressed struct MouseButtonEvent @@ -40,7 +40,7 @@ namespace Nz unsigned int y; }; - // Utilisé par: + // Used by: // -WindowEventType_MouseMoved struct MouseMoveEvent { @@ -50,14 +50,14 @@ namespace Nz unsigned int y; }; - // Utilisé par: + // Used by: // -WindowEventType_MouseWheelMoved struct MouseWheelEvent { float delta; }; - // Utilisé par: + // Used by: // -WindowEventType_Moved struct PositionEvent { @@ -65,7 +65,7 @@ namespace Nz int y; }; - // Utilisé par: + // Used by: // -WindowEventType_Resized struct SizeEvent { @@ -73,7 +73,7 @@ namespace Nz unsigned int width; }; - // Utilisé par: + // Used by: // -WindowEventType_TextEntered struct TextEvent { @@ -85,33 +85,33 @@ namespace Nz union { - // Utilisé par: + // Used by: // -WindowEventType_KeyPressed // -WindowEventType_KeyReleased KeyEvent key; - // Utilisé par: + // Used by: // -WindowEventType_MouseButtonDoubleClicked // -WindowEventType_MouseButtonPressed MouseButtonEvent mouseButton; - // Utilisé par: + // Used by: // -WindowEventType_MouseMoved MouseMoveEvent mouseMove; - // Utilisé par: + // Used by: // -WindowEventType_MouseWheelMoved MouseWheelEvent mouseWheel; - // Utilisé par: + // Used by: // -WindowEventType_Moved PositionEvent position; - // Utilisé par: + // Used by: // -WindowEventType_Resized SizeEvent size; - // Utilisé par: + // Used by: // -WindowEventType_TextEntered TextEvent text; }; diff --git a/include/Nazara/Utility/EventHandler.hpp b/include/Nazara/Platform/EventHandler.hpp similarity index 93% rename from include/Nazara/Utility/EventHandler.hpp rename to include/Nazara/Platform/EventHandler.hpp index 78cba94bc..b2390c35e 100644 --- a/include/Nazara/Utility/EventHandler.hpp +++ b/include/Nazara/Platform/EventHandler.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -11,8 +11,8 @@ #include #include #include -#include -#include +#include +#include namespace Nz { @@ -52,6 +52,6 @@ namespace Nz }; } -#include +#include #endif // NAZARA_EVENTHANDLER_HPP diff --git a/include/Nazara/Utility/EventHandler.inl b/include/Nazara/Platform/EventHandler.inl similarity index 90% rename from include/Nazara/Utility/EventHandler.inl rename to include/Nazara/Platform/EventHandler.inl index 39191300d..6cc31efe5 100644 --- a/include/Nazara/Utility/EventHandler.inl +++ b/include/Nazara/Platform/EventHandler.inl @@ -1,10 +1,10 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include -#include +#include namespace Nz { @@ -82,4 +82,4 @@ namespace Nz } } -#include +#include diff --git a/include/Nazara/Utility/Icon.hpp b/include/Nazara/Platform/Icon.hpp similarity index 76% rename from include/Nazara/Utility/Icon.hpp rename to include/Nazara/Platform/Icon.hpp index db93e9495..7426cf265 100644 --- a/include/Nazara/Utility/Icon.hpp +++ b/include/Nazara/Platform/Icon.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -9,8 +9,7 @@ #include #include -#include -#include +#include namespace Nz { @@ -21,7 +20,7 @@ namespace Nz using IconRef = ObjectRef; - class NAZARA_UTILITY_API Icon : public RefCounted + class NAZARA_PLATFORM_API Icon : public RefCounted { friend class WindowImpl; @@ -42,6 +41,6 @@ namespace Nz }; } -#include +#include #endif // NAZARA_ICON_HPP diff --git a/include/Nazara/Utility/Icon.inl b/include/Nazara/Platform/Icon.inl similarity index 78% rename from include/Nazara/Utility/Icon.inl rename to include/Nazara/Platform/Icon.inl index 5c6b60068..d2b1a5318 100644 --- a/include/Nazara/Utility/Icon.inl +++ b/include/Nazara/Platform/Icon.inl @@ -1,10 +1,9 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include -#include +#include namespace Nz { @@ -39,4 +38,4 @@ namespace Nz } } -#include +#include diff --git a/include/Nazara/Utility/Joystick.hpp b/include/Nazara/Platform/Joystick.hpp similarity index 82% rename from include/Nazara/Utility/Joystick.hpp rename to include/Nazara/Platform/Joystick.hpp index f80b4b590..eb961b87d 100644 --- a/include/Nazara/Utility/Joystick.hpp +++ b/include/Nazara/Platform/Joystick.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -12,7 +12,7 @@ namespace Nz { - class NAZARA_UTILITY_API Joystick + class NAZARA_PLATFORM_API Joystick { public: Joystick() = delete; diff --git a/include/Nazara/Utility/Keyboard.hpp b/include/Nazara/Platform/Keyboard.hpp similarity index 81% rename from include/Nazara/Utility/Keyboard.hpp rename to include/Nazara/Platform/Keyboard.hpp index bfd050d73..df0513c2d 100644 --- a/include/Nazara/Utility/Keyboard.hpp +++ b/include/Nazara/Platform/Keyboard.hpp @@ -1,8 +1,8 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -// Interface inspirée de la SFML par Laurent Gomila +// Interface inspired by the SFML of Laurent Gomila (and its team) #pragma once @@ -11,11 +11,11 @@ #include #include -#include +#include namespace Nz { - class NAZARA_UTILITY_API Keyboard + class NAZARA_PLATFORM_API Keyboard { public: enum Key @@ -50,7 +50,7 @@ namespace Nz Y, Z, - // Touches de fonction + // Functional keys F1, F2, F3, @@ -67,13 +67,13 @@ namespace Nz F14, F15, - // Flèches directionnelles + // Directional keys Down, Left, Right, Up, - // Pavé numérique + // Numerical pad Add, Decimal, Divide, @@ -90,7 +90,7 @@ namespace Nz Numpad9, Subtract, - // Divers + // Various Backslash, Backspace, Clear, @@ -136,7 +136,7 @@ namespace Nz Tab, Tilde, - // Touches navigateur + // Navigator keys Browser_Back, Browser_Favorites, Browser_Forward, @@ -145,18 +145,18 @@ namespace Nz Browser_Search, Browser_Stop, - // Touches de contrôle de lecture + // Lecture control keys Media_Next, Media_Play, Media_Previous, Media_Stop, - // Touches de contrôle du volume + // Volume control keys Volume_Down, Volume_Mute, Volume_Up, - // Touches à verrouillage + // Locking keys CapsLock, NumLock, ScrollLock, diff --git a/include/Nazara/Utility/Mouse.hpp b/include/Nazara/Platform/Mouse.hpp similarity index 82% rename from include/Nazara/Utility/Mouse.hpp rename to include/Nazara/Platform/Mouse.hpp index 552011904..74af3a419 100644 --- a/include/Nazara/Utility/Mouse.hpp +++ b/include/Nazara/Platform/Mouse.hpp @@ -1,8 +1,8 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -// Interface inspirée de la SFML par Laurent Gomila +// Interface inspired by the SFML of Laurent Gomila (and its team) #pragma once @@ -11,13 +11,13 @@ #include #include -#include +#include namespace Nz { class Window; - class NAZARA_UTILITY_API Mouse + class NAZARA_PLATFORM_API Mouse { public: enum Button diff --git a/include/Nazara/Platform/Platform.hpp b/include/Nazara/Platform/Platform.hpp new file mode 100644 index 000000000..59a36ebc5 --- /dev/null +++ b/include/Nazara/Platform/Platform.hpp @@ -0,0 +1,32 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Platform module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_PLATFORM_HPP +#define NAZARA_PLATFORM_HPP + +#include +#include + +namespace Nz +{ + class NAZARA_PLATFORM_API Platform + { + public: + Platform() = delete; + ~Platform() = delete; + + static bool Initialize(); + + static bool IsInitialized(); + + static void Uninitialize(); + + private: + static unsigned int s_moduleReferenceCounter; + }; +} + +#endif // NAZARA_PLATFORM_HPP diff --git a/include/Nazara/Utility/VideoMode.hpp b/include/Nazara/Platform/VideoMode.hpp similarity index 88% rename from include/Nazara/Utility/VideoMode.hpp rename to include/Nazara/Platform/VideoMode.hpp index 4d6a77768..364da9488 100644 --- a/include/Nazara/Utility/VideoMode.hpp +++ b/include/Nazara/Platform/VideoMode.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp // Interface inspirée de la SFML par Laurent Gomila @@ -10,12 +10,12 @@ #define NAZARA_VIDEOMODE_HPP #include -#include +#include #include namespace Nz { - class NAZARA_UTILITY_API VideoMode + class NAZARA_PLATFORM_API VideoMode { public: VideoMode(); diff --git a/include/Nazara/Utility/Window.hpp b/include/Nazara/Platform/Window.hpp similarity index 84% rename from include/Nazara/Utility/Window.hpp rename to include/Nazara/Platform/Window.hpp index 32487370a..c22c00d64 100644 --- a/include/Nazara/Utility/Window.hpp +++ b/include/Nazara/Platform/Window.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp // Interface inspirée de la SFML par Laurent Gomila @@ -11,36 +11,36 @@ #include #include +#include #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include #include namespace Nz { - class Image; class WindowImpl; - class NAZARA_UTILITY_API Window + class NAZARA_PLATFORM_API Window { friend WindowImpl; friend class Mouse; - friend class Utility; + friend class Platform; public: Window(); inline Window(VideoMode mode, const String& title, WindowStyleFlags style = WindowStyle_Default); - inline Window(WindowHandle handle); + inline explicit Window(WindowHandle handle); Window(const Window&) = delete; - inline Window(Window&& window) noexcept; + Window(Window&&) = default; virtual ~Window(); inline void Close(); @@ -103,14 +103,14 @@ namespace Nz bool WaitEvent(WindowEvent* event); Window& operator=(const Window&) = delete; - inline Window& operator=(Window&& window); + Window& operator=(Window&&) = default; protected: virtual bool OnWindowCreated(); virtual void OnWindowDestroy(); virtual void OnWindowResized(); - WindowImpl* m_impl; + MovablePtr m_impl; private: void IgnoreNextMouseEvent(int mouseX, int mouseY) const; @@ -138,6 +138,6 @@ namespace Nz }; } -#include +#include #endif // NAZARA_WINDOW_HPP diff --git a/include/Nazara/Utility/Window.inl b/include/Nazara/Platform/Window.inl similarity index 57% rename from include/Nazara/Utility/Window.inl rename to include/Nazara/Platform/Window.inl index c81c89b80..9ce95a78a 100644 --- a/include/Nazara/Utility/Window.inl +++ b/include/Nazara/Platform/Window.inl @@ -1,11 +1,10 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include -#include +#include namespace Nz { @@ -27,26 +26,6 @@ namespace Nz Create(handle); } - /*! - * \brief Constructs a Window object by moving another one - */ - inline Window::Window(Window&& window) noexcept : - m_impl(window.m_impl), - m_events(std::move(window.m_events)), - m_pendingEvents(std::move(window.m_pendingEvents)), - m_eventCondition(std::move(window.m_eventCondition)), - m_eventHandler(std::move(window.m_eventHandler)), - m_eventMutex(std::move(window.m_eventMutex)), - m_eventConditionMutex(std::move(window.m_eventConditionMutex)), - m_closed(window.m_closed), - m_closeOnQuit(window.m_closeOnQuit), - m_eventPolling(window.m_eventPolling), - m_ownsWindow(window.m_ownsWindow), - m_waitForEvent(window.m_waitForEvent) - { - window.m_impl = nullptr; - } - inline void Window::Close() { m_closed = true; // The window will be closed at the next non-const IsOpen() call @@ -145,32 +124,6 @@ namespace Nz } } } - - /*! - * \brief Moves a window to another window object - * \return A reference to the object - */ - inline Window& Window::operator=(Window&& window) - { - Destroy(); - - m_closed = window.m_closed; - m_closeOnQuit = window.m_closeOnQuit; - m_eventCondition = std::move(window.m_eventCondition); - m_eventConditionMutex = std::move(window.m_eventConditionMutex); - m_eventHandler = std::move(window.m_eventHandler); - m_eventMutex = std::move(window.m_eventMutex); - m_eventPolling = window.m_eventPolling; - m_impl = window.m_impl; - m_events = std::move(window.m_events); - m_pendingEvents = std::move(window.m_pendingEvents); - m_ownsWindow = window.m_ownsWindow; - m_waitForEvent = window.m_waitForEvent; - - window.m_impl = nullptr; - - return *this; - } } -#include +#include diff --git a/include/Nazara/Utility/WindowHandle.hpp b/include/Nazara/Platform/WindowHandle.hpp similarity index 91% rename from include/Nazara/Utility/WindowHandle.hpp rename to include/Nazara/Platform/WindowHandle.hpp index f49a400e0..ea034d4e8 100644 --- a/include/Nazara/Utility/WindowHandle.hpp +++ b/include/Nazara/Platform/WindowHandle.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once diff --git a/include/Nazara/Renderer/Config.hpp b/include/Nazara/Renderer/Config.hpp index f4458216f..873008941 100644 --- a/include/Nazara/Renderer/Config.hpp +++ b/include/Nazara/Renderer/Config.hpp @@ -30,7 +30,7 @@ /// Chaque modification d'un paramètre du module nécessite une recompilation de celui-ci // La taille du buffer d'Instancing (définit le nombre maximum d'instances en un rendu) -#define NAZARA_RENDERER_INSTANCE_BUFFER_SIZE 524288 // 8192 matrices 4x4 flottantes +#define NAZARA_RENDERER_INSTANCE_BUFFER_SIZE 1 * 1024 * 1024 // Utilise un manager de mémoire pour gérer les allocations dynamiques (détecte les leaks au prix d'allocations/libérations dynamiques plus lentes) #define NAZARA_RENDERER_MANAGE_MEMORY 0 diff --git a/include/Nazara/Renderer/ContextParameters.hpp b/include/Nazara/Renderer/ContextParameters.hpp index 99940a24f..830a1bdcf 100644 --- a/include/Nazara/Renderer/ContextParameters.hpp +++ b/include/Nazara/Renderer/ContextParameters.hpp @@ -9,8 +9,8 @@ #include #include -#include -#include +#include +#include namespace Nz { diff --git a/include/Nazara/Renderer/DebugDrawer.hpp b/include/Nazara/Renderer/DebugDrawer.hpp index 491183605..ad893cf35 100644 --- a/include/Nazara/Renderer/DebugDrawer.hpp +++ b/include/Nazara/Renderer/DebugDrawer.hpp @@ -14,11 +14,11 @@ #include #include #include -#include namespace Nz { class Skeleton; + class StaticMesh; class NAZARA_RENDERER_API DebugDrawer { diff --git a/include/Nazara/Renderer/GlslWriter.hpp b/include/Nazara/Renderer/GlslWriter.hpp new file mode 100644 index 000000000..3767846b9 --- /dev/null +++ b/include/Nazara/Renderer/GlslWriter.hpp @@ -0,0 +1,88 @@ +// Copyright (C) 2016 Jérôme Leclercq +// This file is part of the "Nazara Engine - Renderer module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_GLSLWRITER_HPP +#define NAZARA_GLSLWRITER_HPP + +#include +#include +#include +#include +#include +#include + +namespace Nz +{ + class NAZARA_RENDERER_API GlslWriter : public ShaderWriter + { + public: + GlslWriter(); + GlslWriter(const GlslWriter&) = delete; + GlslWriter(GlslWriter&&) = delete; + ~GlslWriter() = default; + + Nz::String Generate(const ShaderAst::StatementPtr& node) override; + + void RegisterFunction(const String& name, ShaderAst::StatementPtr statement, std::initializer_list parameters, ShaderAst::ExpressionType ret) override; + void RegisterVariable(ShaderAst::VariableType kind, const String& name, ShaderAst::ExpressionType type) override; + + void SetGlslVersion(unsigned int version); + + void Write(const ShaderAst::AssignOp& node) override; + void Write(const ShaderAst::Branch& node) override; + void Write(const ShaderAst::BinaryOp& node) override; + void Write(const ShaderAst::BuiltinVariable& node) override; + void Write(const ShaderAst::Cast& node) override; + void Write(const ShaderAst::Constant& node) override; + void Write(const ShaderAst::ExpressionStatement& node) override; + void Write(const ShaderAst::NamedVariable& node) override; + void Write(const ShaderAst::NodePtr& node) override; + void Write(const ShaderAst::StatementBlock& node) override; + void Write(const ShaderAst::SwizzleOp& node) override; + + private: + struct Function; + using VariableContainer = std::set>; + + void Append(ShaderAst::BuiltinEntry builtin); + void Append(ShaderAst::ExpressionType type); + void Append(const String& txt); + void AppendCommentSection(const String& section); + void AppendFunction(Function& func); + void AppendLine(const String& txt = String()); + + void DeclareVariables(const VariableContainer& variables, const String& keyword = String(), const String& section = String()); + + void EnterScope(); + void LeaveScope(); + + + struct Function + { + VariableContainer variables; + std::vector parameters; + ShaderAst::ExpressionType retType; + ShaderAst::StatementPtr node; + String name; + }; + + struct State + { + VariableContainer inputs; + VariableContainer outputs; + VariableContainer uniforms; + StringStream stream; + unsigned int indentLevel = 0; + }; + + std::unordered_map m_functions; + Function* m_currentFunction; + State* m_currentState; + unsigned int m_glslVersion; + }; +} + +#endif // NAZARA_GLSLWRITER_HPP diff --git a/include/Nazara/Renderer/OpenGL.hpp b/include/Nazara/Renderer/OpenGL.hpp index 08b741b97..0fb7859f6 100644 --- a/include/Nazara/Renderer/OpenGL.hpp +++ b/include/Nazara/Renderer/OpenGL.hpp @@ -12,8 +12,8 @@ #include #include #include +#include #include -#include #include // Inclusion des headers OpenGL @@ -46,6 +46,7 @@ namespace Nz }; class Context; + struct RenderStates; class RenderTarget; using OpenGLFunc = void (*)(); diff --git a/include/Nazara/Renderer/RenderTarget.hpp b/include/Nazara/Renderer/RenderTarget.hpp index b30f77ebf..673996a93 100644 --- a/include/Nazara/Renderer/RenderTarget.hpp +++ b/include/Nazara/Renderer/RenderTarget.hpp @@ -11,12 +11,9 @@ #include #include #include -#include namespace Nz { - class Renderer; - class NAZARA_RENDERER_API RenderTarget { friend class Renderer; @@ -24,7 +21,7 @@ namespace Nz public: RenderTarget() = default; RenderTarget(const RenderTarget&) = delete; - RenderTarget(RenderTarget&&) = delete; ///TOOD? + RenderTarget(RenderTarget&&) noexcept = default; virtual ~RenderTarget(); virtual unsigned int GetHeight() const = 0; @@ -40,7 +37,7 @@ namespace Nz virtual bool HasContext() const = 0; RenderTarget& operator=(const RenderTarget&) = delete; - RenderTarget& operator=(RenderTarget&&) = delete; ///TOOD? + RenderTarget& operator=(RenderTarget&&) noexcept = default; // Signals: NazaraSignal(OnRenderTargetParametersChange, const RenderTarget* /*renderTarget*/); diff --git a/include/Nazara/Renderer/RenderTexture.hpp b/include/Nazara/Renderer/RenderTexture.hpp index ad340009e..253f4a680 100644 --- a/include/Nazara/Renderer/RenderTexture.hpp +++ b/include/Nazara/Renderer/RenderTexture.hpp @@ -8,6 +8,7 @@ #define NAZARA_RENDERTEXTURE_HPP #include +#include #include #include #include @@ -30,7 +31,7 @@ namespace Nz public: inline RenderTexture(); RenderTexture(const RenderTexture&) = delete; - RenderTexture(RenderTexture&&) = delete; ///TODO? + RenderTexture(RenderTexture&&) noexcept = default; inline ~RenderTexture(); bool AttachBuffer(AttachmentPoint attachmentPoint, UInt8 index, RenderBuffer* buffer); @@ -64,7 +65,7 @@ namespace Nz bool HasContext() const override; RenderTexture& operator=(const RenderTexture&) = delete; - RenderTexture& operator=(RenderTexture&&) = delete; ///TODO? + RenderTexture& operator=(RenderTexture&&) noexcept = default; static inline void Blit(RenderTexture* src, RenderTexture* dst, UInt32 buffers = RendererBuffer_Color | RendererBuffer_Depth | RendererBuffer_Stencil, bool bilinearFilter = false); static void Blit(RenderTexture* src, Rectui srcRect, RenderTexture* dst, Rectui dstRect, UInt32 buffers = RendererBuffer_Color | RendererBuffer_Depth | RendererBuffer_Stencil, bool bilinearFilter = false); @@ -85,7 +86,7 @@ namespace Nz void UpdateSize() const; void UpdateTargets() const; - RenderTextureImpl* m_impl; + MovablePtr m_impl; mutable bool m_checked ; mutable bool m_drawBuffersUpdated; mutable bool m_sizeUpdated; diff --git a/include/Nazara/Renderer/RenderWindow.hpp b/include/Nazara/Renderer/RenderWindow.hpp index c71ad2b34..33f9bd4df 100644 --- a/include/Nazara/Renderer/RenderWindow.hpp +++ b/include/Nazara/Renderer/RenderWindow.hpp @@ -16,22 +16,20 @@ #include #include #include -#include +#include #include namespace Nz { class AbstractImage; class Context; - class Texture; - struct ContextParameters; class NAZARA_RENDERER_API RenderWindow : public RenderTarget, public Window { public: RenderWindow() = default; RenderWindow(VideoMode mode, const String& title, WindowStyleFlags style = WindowStyle_Default, const ContextParameters& parameters = ContextParameters()); - RenderWindow(WindowHandle handle, const ContextParameters& parameters = ContextParameters()); + explicit RenderWindow(WindowHandle handle, const ContextParameters& parameters = ContextParameters()); RenderWindow(const RenderWindow&) = delete; RenderWindow(RenderWindow&&) = delete; ///TODO virtual ~RenderWindow(); diff --git a/include/Nazara/Renderer/Renderer.hpp b/include/Nazara/Renderer/Renderer.hpp index d549a48bb..092f97262 100644 --- a/include/Nazara/Renderer/Renderer.hpp +++ b/include/Nazara/Renderer/Renderer.hpp @@ -8,25 +8,25 @@ #define NAZARA_RENDERER_HPP #include -#include #include #include +#include #include -#include -#include -#include #include -#include namespace Nz { class Color; class Context; + class GpuQuery; class IndexBuffer; class RenderTarget; + struct RenderStates; class Shader; class Texture; + class TextureSampler; class VertexBuffer; + class VertexDeclaration; class NAZARA_RENDERER_API Renderer { @@ -112,6 +112,7 @@ namespace Nz private: static void EnableInstancing(bool instancing); static bool EnsureStateUpdate(); + static bool GenerateDebugShader(); static void OnContextRelease(const Context* context); static void OnIndexBufferRelease(const IndexBuffer* indexBuffer); static void OnShaderReleased(const Shader* shader); diff --git a/include/Nazara/Renderer/Shader.hpp b/include/Nazara/Renderer/Shader.hpp index 27c68a9d6..8db02e356 100644 --- a/include/Nazara/Renderer/Shader.hpp +++ b/include/Nazara/Renderer/Shader.hpp @@ -9,7 +9,6 @@ #include #include -#include #include #include #include @@ -24,6 +23,7 @@ namespace Nz { + class Color; class Shader; class ShaderStage; diff --git a/include/Nazara/Renderer/ShaderAst.hpp b/include/Nazara/Renderer/ShaderAst.hpp new file mode 100644 index 000000000..fd7c6dd30 --- /dev/null +++ b/include/Nazara/Renderer/ShaderAst.hpp @@ -0,0 +1,292 @@ +// Copyright (C) 2016 Jérôme Leclercq +// This file is part of the "Nazara Engine - Renderer module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_SHADER_AST_HPP +#define NAZARA_SHADER_AST_HPP + +#include +#include +#include +#include +#include +#include +#include + +namespace Nz +{ + class ShaderWriter; + + namespace ShaderAst + { + enum class AssignType + { + Simple //< = + }; + + enum class BinaryType + { + Add, //< + + Substract, //< - + Multiply, //< * + Divide, //< / + Equality //< == + }; + + enum class BuiltinEntry + { + VertexPosition, // gl_Position + }; + + enum class ExpressionType + { + Boolean, // bool + Float1, // float + Float2, // vec2 + Float3, // vec3 + Float4, // vec4 + Mat4x4, // mat4 + + Void // void + }; + + enum class SwizzleComponent + { + First, + Second, + Third, + Fourth + }; + + enum class VariableType + { + Builtin, + Input, + Output, + Parameter, + Uniform, + Variable + }; + + ////////////////////////////////////////////////////////////////////////// + + class Node; + + using NodePtr = std::shared_ptr; + + class NAZARA_RENDERER_API Node + { + public: + virtual ~Node() = default; + + virtual void Register(ShaderWriter& visitor) = 0; + virtual void Visit(ShaderWriter& visitor) = 0; + + static inline unsigned int GetComponentCount(ExpressionType type); + static inline ExpressionType GetComponentType(ExpressionType type); + }; + + class Statement; + + using StatementPtr = std::shared_ptr; + + class NAZARA_RENDERER_API Statement : public Node + { + }; + + class Expression; + + using ExpressionPtr = std::shared_ptr; + + class NAZARA_RENDERER_API Expression : public Node + { + public: + virtual ExpressionType GetExpressionType() const = 0; + }; + + class NAZARA_RENDERER_API ExpressionStatement : public Statement + { + public: + inline explicit ExpressionStatement(ExpressionPtr expr); + + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + ExpressionPtr expression; + }; + + ////////////////////////////////////////////////////////////////////////// + + class NAZARA_RENDERER_API ConditionalStatement : public Statement + { + public: + inline ConditionalStatement(const String& condition, StatementPtr statementPtr); + + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + String conditionName; + StatementPtr statement; + }; + + class NAZARA_RENDERER_API StatementBlock : public Statement + { + public: + template explicit StatementBlock(Args&&... args); + + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + std::vector statements; + }; + + class Variable; + + using VariablePtr = std::shared_ptr; + + class NAZARA_RENDERER_API Variable : public Expression + { + public: + inline Variable(VariableType varKind, ExpressionType varType); + + ExpressionType GetExpressionType() const override; + + ExpressionType type; + VariableType kind; + }; + + + class NAZARA_RENDERER_API BuiltinVariable : public Variable + { + public: + inline BuiltinVariable(BuiltinEntry variable, ExpressionType varType); + + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + BuiltinEntry var; + }; + + + class NamedVariable; + + using NamedVariablePtr = std::shared_ptr; + + class NAZARA_RENDERER_API NamedVariable : public Variable + { + public: + inline NamedVariable(VariableType varKind, const Nz::String& varName, ExpressionType varType); + + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + Nz::String name; + }; + + ////////////////////////////////////////////////////////////////////////// + + class NAZARA_RENDERER_API AssignOp : public Expression + { + public: + inline AssignOp(AssignType Op, VariablePtr Var, ExpressionPtr Right); + + ExpressionType GetExpressionType() const override; + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + AssignType op; + VariablePtr variable; + ExpressionPtr right; + }; + + class NAZARA_RENDERER_API BinaryOp : public Expression + { + public: + inline BinaryOp(BinaryType Op, ExpressionPtr Left, ExpressionPtr Right); + + ExpressionType GetExpressionType() const override; + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + BinaryType op; + ExpressionPtr left; + ExpressionPtr right; + }; + + class NAZARA_RENDERER_API Branch : public Statement + { + public: + inline Branch(ExpressionPtr condition, StatementPtr trueStatement, StatementPtr falseStatement = nullptr); + + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + struct ConditionalStatement + { + ExpressionPtr condition; + StatementPtr statement; + }; + + std::vector condStatements; + StatementPtr elseStatement; + }; + + class NAZARA_RENDERER_API Cast : public Expression + { + public: + inline Cast(ExpressionType castTo, ExpressionPtr first, ExpressionPtr second = nullptr, ExpressionPtr third = nullptr, ExpressionPtr fourth = nullptr); + + ExpressionType GetExpressionType() const override; + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + ExpressionType exprType; + std::array expressions; + }; + + class NAZARA_RENDERER_API Constant : public Expression + { + public: + inline explicit Constant(bool value); + inline explicit Constant(float value); + inline explicit Constant(const Vector2f& value); + inline explicit Constant(const Vector3f& value); + inline explicit Constant(const Vector4f& value); + + ExpressionType GetExpressionType() const override; + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + ExpressionType exprType; + + union + { + bool bool1; + float vec1; + Vector2f vec2; + Vector3f vec3; + Vector4f vec4; + } values; + }; + + class NAZARA_RENDERER_API SwizzleOp : public Expression + { + public: + inline SwizzleOp(ExpressionPtr expressionPtr, std::initializer_list swizzleComponents); + + ExpressionType GetExpressionType() const override; + void Register(ShaderWriter& visitor) override; + void Visit(ShaderWriter& visitor) override; + + std::array components; + std::size_t componentCount; + ExpressionPtr expression; + }; + } +} + +#include + +#endif // NAZARA_SHADER_AST_HPP diff --git a/include/Nazara/Renderer/ShaderAst.inl b/include/Nazara/Renderer/ShaderAst.inl new file mode 100644 index 000000000..35bdab9fe --- /dev/null +++ b/include/Nazara/Renderer/ShaderAst.inl @@ -0,0 +1,231 @@ +// Copyright (C) 2016 Jérôme Leclercq +// This file is part of the "Nazara Engine - Renderer module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include + +namespace Nz +{ + namespace ShaderAst + { + inline unsigned int Node::GetComponentCount(ExpressionType type) + { + switch (type) + { + case ExpressionType::Float2: + return 2; + + case ExpressionType::Float3: + return 3; + + case ExpressionType::Float4: + return 4; + + case ExpressionType::Mat4x4: + return 4; + + default: + return 1; + } + } + + inline ExpressionType Node::GetComponentType(ExpressionType type) + { + switch (type) + { + case ExpressionType::Float2: + case ExpressionType::Float3: + case ExpressionType::Float4: + return ExpressionType::Float1; + + case ExpressionType::Mat4x4: + return ExpressionType::Float4; + + default: + return type; + } + } + + inline ExpressionStatement::ExpressionStatement(ExpressionPtr expr) : + expression(std::move(expr)) + { + } + + inline ConditionalStatement::ConditionalStatement(const String& condition, StatementPtr statementPtr) : + conditionName(condition), + statement(std::move(statementPtr)) + { + } + + template + StatementBlock::StatementBlock(Args&& ...args) : + statements({std::forward(args)...}) + { + } + + inline Variable::Variable(VariableType varKind, ExpressionType varType) : + type(varType), + kind(varKind) + { + } + + inline BuiltinVariable::BuiltinVariable(BuiltinEntry variable, ExpressionType varType) : + Variable(VariableType::Builtin, varType), + var(variable) + { + } + + inline NamedVariable::NamedVariable(VariableType varKind, const Nz::String& varName, ExpressionType varType) : + Variable(varKind, varType), + name(varName) + { + } + + inline AssignOp::AssignOp(AssignType Op, VariablePtr Var, ExpressionPtr Right) : + op(Op), + variable(std::move(Var)), + right(std::move(Right)) + { + } + + inline BinaryOp::BinaryOp(BinaryType Op, ExpressionPtr Left, ExpressionPtr Right) : + op(Op), + left(std::move(Left)), + right(std::move(Right)) + { + ExpressionType leftType = left->GetExpressionType(); + ExpressionType rightType = right->GetExpressionType(); + + if (leftType != rightType) + { + switch (op) + { + case BinaryType::Add: + case BinaryType::Equality: + case BinaryType::Substract: + { + //TODO: AstParseError + throw std::runtime_error("Left expression type must match right expression type"); + } + + case BinaryType::Multiply: + case BinaryType::Divide: + { + switch (leftType) + { + case ExpressionType::Float2: + case ExpressionType::Float3: + case ExpressionType::Float4: + { + if (rightType != ExpressionType::Float1) + throw std::runtime_error("Left expression type is not compatible with right expression type"); + + break; + } + + case ExpressionType::Mat4x4: + { + switch (rightType) + { + case ExpressionType::Float1: + case ExpressionType::Float4: + case ExpressionType::Mat4x4: + break; + + //TODO: AstParseError + default: + throw std::runtime_error("Left expression type is not compatible with right expression type"); + } + + break; + } + + default: + //TODO: AstParseError + throw std::runtime_error("Left expression type must match right expression type"); + } + } + } + } + } + + inline Branch::Branch(ExpressionPtr condition, StatementPtr trueStatement, StatementPtr falseStatement) + { + condStatements.emplace_back(ConditionalStatement{ std::move(condition), std::move(trueStatement) }); + elseStatement = std::move(falseStatement); + } + + inline Cast::Cast(ExpressionType castTo, ExpressionPtr first, ExpressionPtr second, ExpressionPtr third, ExpressionPtr fourth) : + exprType(castTo), + expressions({ {first, second, third, fourth} }) + { + unsigned int componentCount = 0; + unsigned int requiredComponents = GetComponentCount(exprType); + for (const auto& exprPtr : expressions) + { + if (!exprPtr) + break; + + componentCount += GetComponentCount(exprPtr->GetExpressionType()); + } + + //TODO: AstParseError + if (componentCount != requiredComponents) + throw std::runtime_error("Component count doesn't match required component count"); + } + + inline Constant::Constant(bool value) : + exprType(ExpressionType::Boolean) + { + values.bool1 = value; + } + + inline Constant::Constant(float value) : + exprType(ExpressionType::Float1) + { + values.vec1 = value; + } + + inline Constant::Constant(const Vector2f& value) : + exprType(ExpressionType::Float2) + { + values.vec2 = value; + } + + inline Constant::Constant(const Vector3f& value) : + exprType(ExpressionType::Float3) + { + values.vec3 = value; + } + + inline Constant::Constant(const Vector4f& value) : + exprType(ExpressionType::Float4) + { + values.vec4 = value; + } + + inline SwizzleOp::SwizzleOp(ExpressionPtr expressionPtr, std::initializer_list swizzleComponents) : + componentCount(swizzleComponents.size()), + expression(expressionPtr) + { + if (componentCount > 4) + throw std::runtime_error("Cannot swizzle more than four elements"); + + switch (expressionPtr->GetExpressionType()) + { + case ExpressionType::Float1: + case ExpressionType::Float2: + case ExpressionType::Float3: + case ExpressionType::Float4: + break; + + default: + throw std::runtime_error("Cannot swizzle this type"); + } + + std::copy(swizzleComponents.begin(), swizzleComponents.end(), components.begin()); + } + } +} + +#include diff --git a/include/Nazara/Renderer/ShaderBuilder.hpp b/include/Nazara/Renderer/ShaderBuilder.hpp new file mode 100644 index 000000000..e642ea8d3 --- /dev/null +++ b/include/Nazara/Renderer/ShaderBuilder.hpp @@ -0,0 +1,79 @@ +// Copyright (C) 2016 Jérôme Leclercq +// This file is part of the "Nazara Engine - Renderer module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_SHADER_BUILDER_HPP +#define NAZARA_SHADER_BUILDER_HPP + +#include +#include +#include + +namespace Nz { namespace ShaderBuilder +{ + template + struct AssignOpBuilder + { + constexpr AssignOpBuilder() {} + + std::shared_ptr operator()(const ShaderAst::VariablePtr& left, const ShaderAst::ExpressionPtr& right) const; + }; + + template + struct BinOpBuilder + { + constexpr BinOpBuilder() {} + + std::shared_ptr operator()(const ShaderAst::ExpressionPtr& left, const ShaderAst::ExpressionPtr& right) const; + }; + + struct BuiltinBuilder + { + constexpr BuiltinBuilder() {} + + std::shared_ptr operator()(ShaderAst::BuiltinEntry builtin) const; + }; + + template + struct GenBuilder + { + constexpr GenBuilder() {} + + template std::shared_ptr operator()(Args&&... args) const; + }; + + template + struct VarBuilder + { + constexpr VarBuilder() {} + + template std::shared_ptr operator()(Args&&... args) const; + }; + + constexpr BinOpBuilder Add; + constexpr AssignOpBuilder Assign; + constexpr BuiltinBuilder Builtin; + constexpr GenBuilder Block; + constexpr GenBuilder Branch; + constexpr GenBuilder ConditionalStatement; + constexpr GenBuilder Constant; + constexpr BinOpBuilder Divide; + constexpr BinOpBuilder Equal; + constexpr GenBuilder ExprStatement; + constexpr VarBuilder Input; + constexpr BinOpBuilder Multiply; + constexpr VarBuilder Output; + constexpr VarBuilder Parameter; + constexpr GenBuilder Swizzle; + constexpr BinOpBuilder Substract; + constexpr VarBuilder Uniform; + constexpr VarBuilder Variable; + + template std::shared_ptr Cast(Args&&... args); +} } + +#include + +#endif // NAZARA_SHADER_BUILDER_HPP diff --git a/include/Nazara/Renderer/ShaderBuilder.inl b/include/Nazara/Renderer/ShaderBuilder.inl new file mode 100644 index 000000000..05e01ed40 --- /dev/null +++ b/include/Nazara/Renderer/ShaderBuilder.inl @@ -0,0 +1,59 @@ +// Copyright (C) 2016 Jérôme Leclercq +// This file is part of the "Nazara Engine - Renderer module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include + +namespace Nz { namespace ShaderBuilder +{ + template + template + std::shared_ptr GenBuilder::operator()(Args&&... args) const + { + return std::make_shared(std::forward(args)...); + } + + template + std::shared_ptr AssignOpBuilder::operator()(const ShaderAst::VariablePtr& left, const ShaderAst::ExpressionPtr& right) const + { + return std::make_shared(op, left, right); + } + + template + std::shared_ptr BinOpBuilder::operator()(const ShaderAst::ExpressionPtr& left, const ShaderAst::ExpressionPtr& right) const + { + return std::make_shared(op, left, right); + } + + std::shared_ptr BuiltinBuilder::operator()(ShaderAst::BuiltinEntry builtin) const + { + ShaderAst::ExpressionType exprType = ShaderAst::ExpressionType::Void; + + switch (builtin) + { + case ShaderAst::BuiltinEntry::VertexPosition: + exprType = ShaderAst::ExpressionType::Float4; + break; + } + + NazaraAssert(exprType != ShaderAst::ExpressionType::Void, "Unhandled builtin"); + + return std::make_shared(builtin, exprType); + } + + template + template + std::shared_ptr VarBuilder::operator()(Args&&... args) const + { + return std::make_shared(type, std::forward(args)...); + } + + template + std::shared_ptr Cast(Args&&... args) + { + return std::make_shared(Type, std::forward(args)...); + } +} } + +#include diff --git a/include/Nazara/Renderer/ShaderWriter.hpp b/include/Nazara/Renderer/ShaderWriter.hpp new file mode 100644 index 000000000..13ef6e367 --- /dev/null +++ b/include/Nazara/Renderer/ShaderWriter.hpp @@ -0,0 +1,52 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Renderer module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_SHADERWRITER_HPP +#define NAZARA_SHADERWRITER_HPP + +#include +#include +#include +#include +#include + +namespace Nz +{ + class NAZARA_RENDERER_API ShaderWriter + { + public: + ShaderWriter() = default; + ShaderWriter(const ShaderWriter&) = delete; + ShaderWriter(ShaderWriter&&) = delete; + virtual ~ShaderWriter(); + + void EnableCondition(const String& name, bool cond); + + bool IsConditionEnabled(const String& name) const; + + virtual Nz::String Generate(const ShaderAst::StatementPtr& node) = 0; + + virtual void RegisterFunction(const String& name, ShaderAst::StatementPtr node, std::initializer_list parameters, ShaderAst::ExpressionType ret) = 0; + virtual void RegisterVariable(ShaderAst::VariableType kind, const String& name, ShaderAst::ExpressionType type) = 0; + + virtual void Write(const ShaderAst::AssignOp& node) = 0; + virtual void Write(const ShaderAst::Branch& node) = 0; + virtual void Write(const ShaderAst::BinaryOp& node) = 0; + virtual void Write(const ShaderAst::BuiltinVariable& node) = 0; + virtual void Write(const ShaderAst::Cast& node) = 0; + virtual void Write(const ShaderAst::Constant& node) = 0; + virtual void Write(const ShaderAst::ExpressionStatement& node) = 0; + virtual void Write(const ShaderAst::NamedVariable& node) = 0; + virtual void Write(const ShaderAst::NodePtr& node) = 0; + virtual void Write(const ShaderAst::StatementBlock& node) = 0; + virtual void Write(const ShaderAst::SwizzleOp& node) = 0; + + private: + std::unordered_set m_conditions; + }; +} + +#endif // NAZARA_SHADERWRITER_HPP diff --git a/include/Nazara/Renderer/Texture.hpp b/include/Nazara/Renderer/Texture.hpp index 7c5f9ab6e..638d1da15 100644 --- a/include/Nazara/Renderer/Texture.hpp +++ b/include/Nazara/Renderer/Texture.hpp @@ -14,7 +14,6 @@ #include #include #include -#include #include #include #include diff --git a/include/Nazara/Renderer/UberShader.hpp b/include/Nazara/Renderer/UberShader.hpp index af822db89..fc268533d 100644 --- a/include/Nazara/Renderer/UberShader.hpp +++ b/include/Nazara/Renderer/UberShader.hpp @@ -8,16 +8,17 @@ #define NAZARA_UBERSHADER_HPP #include -#include #include #include #include -#include -#include +#include +#include namespace Nz { + class ParameterList; class UberShader; + class UberShaderInstance; using UberShaderConstRef = ObjectRef; using UberShaderLibrary = ObjectLibrary; diff --git a/include/Nazara/Renderer/UberShaderPreprocessor.hpp b/include/Nazara/Renderer/UberShaderPreprocessor.hpp index 710835ec2..1244ee0cb 100644 --- a/include/Nazara/Renderer/UberShaderPreprocessor.hpp +++ b/include/Nazara/Renderer/UberShaderPreprocessor.hpp @@ -10,7 +10,6 @@ #include #include #include -#include #include #include #include @@ -18,6 +17,7 @@ namespace Nz { + class UberShaderInstance; class UberShaderPreprocessor; using UberShaderPreprocessorConstRef = ObjectRef; diff --git a/include/Nazara/Utility.hpp b/include/Nazara/Utility.hpp index fbb100476..2ccf84080 100644 --- a/include/Nazara/Utility.hpp +++ b/include/Nazara/Utility.hpp @@ -39,27 +39,19 @@ #include #include #include -#include -#include #include -#include -#include #include #include #include #include -#include #include #include #include #include #include -#include -#include #include #include #include -#include #include #include #include @@ -75,8 +67,5 @@ #include #include #include -#include -#include -#include #endif // NAZARA_GLOBAL_UTILITY_HPP diff --git a/include/Nazara/Utility/AbstractAtlas.hpp b/include/Nazara/Utility/AbstractAtlas.hpp index 49565cdf2..95890a248 100644 --- a/include/Nazara/Utility/AbstractAtlas.hpp +++ b/include/Nazara/Utility/AbstractAtlas.hpp @@ -12,8 +12,6 @@ #include #include #include -#include -#include namespace Nz { diff --git a/include/Nazara/Utility/AbstractImage.inl b/include/Nazara/Utility/AbstractImage.inl index fe456669f..98dbabfdd 100644 --- a/include/Nazara/Utility/AbstractImage.inl +++ b/include/Nazara/Utility/AbstractImage.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include namespace Nz diff --git a/include/Nazara/Utility/Algorithm.hpp b/include/Nazara/Utility/Algorithm.hpp index 1652976c3..aadec8aaa 100644 --- a/include/Nazara/Utility/Algorithm.hpp +++ b/include/Nazara/Utility/Algorithm.hpp @@ -8,17 +8,25 @@ #define NAZARA_ALGORITHM_UTILITY_HPP #include +#include #include #include #include +#include #include #include +#include #include -#include -#include namespace Nz { + class Joint; + struct VertexStruct_XYZ_Normal_UV_Tangent; + struct VertexStruct_XYZ_Normal_UV_Tangent_Skinning; + + using MeshVertex = VertexStruct_XYZ_Normal_UV_Tangent; + using SkeletalMeshVertex = VertexStruct_XYZ_Normal_UV_Tangent_Skinning; + struct SkinningData { const Joint* joints; @@ -57,6 +65,10 @@ namespace Nz NAZARA_UTILITY_API void SkinPositionNormalTangent(const SkinningData& data, unsigned int startVertex, unsigned int vertexCount); NAZARA_UTILITY_API void TransformVertices(VertexPointers vertexPointers, unsigned int vertexCount, const Matrix4f& matrix); + + template constexpr ComponentType ComponentTypeId(); + template constexpr const ComponentType GetComponentTypeOf(); } +#include #endif // NAZARA_ALGORITHM_UTILITY_HPP diff --git a/include/Nazara/Utility/Algorithm.inl b/include/Nazara/Utility/Algorithm.inl new file mode 100644 index 000000000..61bdb9e77 --- /dev/null +++ b/include/Nazara/Utility/Algorithm.inl @@ -0,0 +1,45 @@ +#pragma once + +#include +#include + +namespace Nz +{ + namespace Detail + { + template + struct IsSuitableForComponent + { + constexpr static bool value = false; + }; + } + + template constexpr ComponentType ComponentTypeId() + { + static_assert(Detail::IsSuitableForComponent::value, "This type cannot be used as a component."); + return ComponentType{}; + } + + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Color; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Double1; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Double2; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Double3; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Double4; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Float1; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Float2; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Float3; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Float4; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Int1; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Int2; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Int3; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Int4; } + template<> constexpr ComponentType ComponentTypeId() { return ComponentType_Quaternion; } + + template + constexpr const ComponentType GetComponentTypeOf() + { + return ComponentTypeId>(); + } +} + +#include \ No newline at end of file diff --git a/include/Nazara/Utility/Animation.hpp b/include/Nazara/Utility/Animation.hpp index 7f7595bbd..2e1753c6a 100644 --- a/include/Nazara/Utility/Animation.hpp +++ b/include/Nazara/Utility/Animation.hpp @@ -8,6 +8,7 @@ #define NAZARA_ANIMATION_HPP #include +#include #include #include #include @@ -19,7 +20,6 @@ #include #include #include -#include namespace Nz { @@ -34,6 +34,8 @@ namespace Nz }; class Animation; + struct Sequence; + struct SequenceJoint; class Skeleton; using AnimationConstRef = ObjectRef; @@ -98,7 +100,7 @@ namespace Nz static bool Initialize(); static void Uninitialize(); - AnimationImpl* m_impl = nullptr; + MovablePtr m_impl = nullptr; static AnimationLibrary::LibraryMap s_library; static AnimationLoader::LoaderList s_loaders; diff --git a/include/Nazara/Utility/Config.hpp b/include/Nazara/Utility/Config.hpp index 39aa014af..489a6192b 100644 --- a/include/Nazara/Utility/Config.hpp +++ b/include/Nazara/Utility/Config.hpp @@ -27,32 +27,29 @@ #ifndef NAZARA_CONFIG_UTILITY_HPP #define NAZARA_CONFIG_UTILITY_HPP -/// Chaque modification d'un paramètre du module nécessite une recompilation de celui-ci +/// Each modification of a parameter needs a recompilation of the module -// Utilise un manager de mémoire pour gérer les allocations dynamiques (détecte les leaks au prix d'allocations/libérations dynamiques plus lentes) +// Use the MemoryManager to manage dynamic allocations (can detect memory leak but allocations/frees are slower) #define NAZARA_UTILITY_MANAGE_MEMORY 0 -// Active les tests de sécurité basés sur le code (Conseillé pour le développement) +// Activate the security tests based on the code (Advised for development) #define NAZARA_UTILITY_SAFE 1 -// Lors du parsage d'une ressource, déclenche un avertissement si une erreur non-critique est repérée dans une ressource (Plus lent) +// When a resource is being parsed, it triggers a warning if a non-critical error is found in the resource (Slower) #define NAZARA_UTILITY_STRICT_RESOURCE_PARSING 1 -// Protège les classes des accès concurrentiels +// Protect the classes against data race //#define NAZARA_UTILITY_THREADSAFE 1 -// Force les buffers à posséder un stride multiple de 32 bytes (Gain de performances sur certaines cartes/plus de consommation mémoire) -#define NAZARA_UTILITY_VERTEX_DECLARATION_FORCE_STRIDE_MULTIPLE_OF_32 0 ///FIXME: Ne peut pas être utilisé pour l'instant +// Force the buffers to have a stride which is a multiple of 32 bytes (Gain of performances on certain cards/more memory consumption) +#define NAZARA_UTILITY_VERTEX_DECLARATION_FORCE_STRIDE_MULTIPLE_OF_32 0 ///FIXME: Can not be used for the moment -// Sous Windows, fait en sorte que les touches ALT et F10 n'activent pas le menu de la fenêtre -#define NAZARA_UTILITY_WINDOWS_DISABLE_MENU_KEYS 1 +/// Each modification of a parameter following implies a modification (often minor) of the code -/// Chaque modification d'un paramètre ci-dessous implique une modification (souvent mineure) du code - -// Le nombre maximum de poids affectant un sommet (En cas de dépassement, les poids supplémentaires seront ignorés et les autres renormalisés) +// The maximal number of weights acting on a vertex (In case of overflow, the surnumerous weights would be ignored and the others renormalized) #define NAZARA_UTILITY_SKINNING_MAX_WEIGHTS 4 -/// Vérification des valeurs et types de certaines constantes +/// Checking the values and types of certain constants #include #if defined(NAZARA_STATIC) diff --git a/include/Nazara/Utility/ConfigCheck.hpp b/include/Nazara/Utility/ConfigCheck.hpp index bbfd6ea66..42aa5f92c 100644 --- a/include/Nazara/Utility/ConfigCheck.hpp +++ b/include/Nazara/Utility/ConfigCheck.hpp @@ -7,12 +7,12 @@ #ifndef NAZARA_CONFIG_CHECK_UTILITY_HPP #define NAZARA_CONFIG_CHECK_UTILITY_HPP -/// Ce fichier sert à vérifier la valeur des constantes du fichier Config.hpp +/// This file is used to check the constant values defined in Config.hpp #include #define NazaraCheckTypeAndVal(name, type, op, val, err) static_assert(std::is_ ##type ::value && name op val, #type err) -// On force la valeur de MANAGE_MEMORY en mode debug +// We force the value of MANAGE_MEMORY in debug #if defined(NAZARA_DEBUG) && !NAZARA_UTILITY_MANAGE_MEMORY #undef NAZARA_UTILITY_MANAGE_MEMORY #define NAZARA_UTILITY_MANAGE_MEMORY 0 diff --git a/include/Nazara/Utility/Enums.hpp b/include/Nazara/Utility/Enums.hpp index d72b90d6c..2fda92e70 100644 --- a/include/Nazara/Utility/Enums.hpp +++ b/include/Nazara/Utility/Enums.hpp @@ -92,8 +92,8 @@ namespace Nz enum CubemapFace { - // Cette énumération est prévue pour remplacer l'argument "z" des méthodes de Image contenant un cubemap - // L'ordre est X, -X, Y, -Y, Z, -Z + // This enumeration is intended to replace the "z" argument of Image's methods containing cubemap + // The order is X, -X, Y, -Y, Z, -Z CubemapFace_PositiveX = 0, CubemapFace_PositiveY = 2, CubemapFace_PositiveZ = 4, @@ -307,30 +307,6 @@ namespace Nz SamplerWrap_Max = SamplerWrap_Repeat }; - enum SystemCursor - { - SystemCursor_Crosshair, - SystemCursor_Default, - SystemCursor_Hand, - SystemCursor_Help, - SystemCursor_Move, - SystemCursor_None, - SystemCursor_Pointer, - SystemCursor_Progress, - SystemCursor_ResizeE, - SystemCursor_ResizeN, - SystemCursor_ResizeNE, - SystemCursor_ResizeNW, - SystemCursor_ResizeS, - SystemCursor_ResizeSE, - SystemCursor_ResizeSW, - SystemCursor_ResizeW, - SystemCursor_Text, - SystemCursor_Wait, - - SystemCursor_Max = SystemCursor_Wait - }; - enum StencilOperation { StencilOperation_Decrement, @@ -370,7 +346,7 @@ namespace Nz { VertexComponent_Unused = -1, - // Nous nous limitons à 16 composants de sommets car c'est le minimum supporté par le GPU + // We limit to 16 components by vertex since it's the minimal number supported by the GPU VertexComponent_InstanceData0, VertexComponent_InstanceData1, VertexComponent_InstanceData2, @@ -398,7 +374,7 @@ namespace Nz enum VertexLayout { - // Déclarations destinées au rendu + // Declarations meant for the rendering VertexLayout_XY, VertexLayout_XY_Color, VertexLayout_XY_UV, @@ -411,57 +387,11 @@ namespace Nz VertexLayout_XYZ_Normal_UV_Tangent_Skinning, VertexLayout_XYZ_UV, - // Déclarations destinées à l'instancing + // Declarations meant for the instancing VertexLayout_Matrix4, VertexLayout_Max = VertexLayout_Matrix4 }; - - enum WindowEventType - { - WindowEventType_GainedFocus, - WindowEventType_LostFocus, - WindowEventType_KeyPressed, - WindowEventType_KeyReleased, - WindowEventType_MouseButtonDoubleClicked, - WindowEventType_MouseButtonPressed, - WindowEventType_MouseButtonReleased, - WindowEventType_MouseEntered, - WindowEventType_MouseLeft, - WindowEventType_MouseMoved, - WindowEventType_MouseWheelMoved, - WindowEventType_Moved, - WindowEventType_Quit, - WindowEventType_Resized, - WindowEventType_TextEntered, - - WindowEventType_Max = WindowEventType_TextEntered - }; - - enum WindowStyle - { - WindowStyle_None, ///< Window has no border nor titlebar. - WindowStyle_Fullscreen, ///< At the window creation, the OS tries to set it in fullscreen. - - WindowStyle_Closable, ///< Allows the window to be closed by a button in the titlebar, generating a Quit event. - WindowStyle_Resizable, ///< Allows the window to be resized by dragging its corners or by a button of the titlebar. - WindowStyle_Titlebar, ///< Adds a titlebar to the window, this option is automatically enabled if buttons of the titlebar are enabled. - - WindowStyle_Threaded, ///< Runs the window into a thread, allowing the application to keep updating while resizing/dragging the window. - - WindowStyle_Max = WindowStyle_Threaded - }; - - template<> - struct EnumAsFlags - { - static constexpr bool value = true; - static constexpr int max = WindowStyle_Max; - }; - - using WindowStyleFlags = Flags; - - constexpr WindowStyleFlags WindowStyle_Default = WindowStyle_Closable | WindowStyle_Resizable | WindowStyle_Titlebar; } #endif // NAZARA_ENUMS_UTILITY_HPP diff --git a/include/Nazara/Utility/Formats/MD5AnimParser.hpp b/include/Nazara/Utility/Formats/MD5AnimParser.hpp index d62cdaae8..f6a75165a 100644 --- a/include/Nazara/Utility/Formats/MD5AnimParser.hpp +++ b/include/Nazara/Utility/Formats/MD5AnimParser.hpp @@ -8,11 +8,10 @@ #define NAZARA_FORMATS_MD5ANIMPARSER_HPP #include -#include +#include #include #include #include -#include #include namespace Nz diff --git a/include/Nazara/Utility/Formats/MD5MeshParser.hpp b/include/Nazara/Utility/Formats/MD5MeshParser.hpp index dce6bcc72..d40b40d4e 100644 --- a/include/Nazara/Utility/Formats/MD5MeshParser.hpp +++ b/include/Nazara/Utility/Formats/MD5MeshParser.hpp @@ -8,11 +8,11 @@ #define NAZARA_FORMATS_MD5MESHPARSER_HPP #include -#include #include #include +#include #include -#include +#include #include namespace Nz diff --git a/include/Nazara/Utility/Formats/MTLParser.hpp b/include/Nazara/Utility/Formats/MTLParser.hpp index ec50f2137..272d67062 100644 --- a/include/Nazara/Utility/Formats/MTLParser.hpp +++ b/include/Nazara/Utility/Formats/MTLParser.hpp @@ -9,7 +9,6 @@ #include #include -#include #include #include #include diff --git a/include/Nazara/Utility/Formats/MTLParser.inl b/include/Nazara/Utility/Formats/MTLParser.inl index 00e9e8b89..cde870fee 100644 --- a/include/Nazara/Utility/Formats/MTLParser.inl +++ b/include/Nazara/Utility/Formats/MTLParser.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include @@ -80,4 +79,3 @@ namespace Nz } #include -#include "MTLParser.hpp" diff --git a/include/Nazara/Utility/Formats/OBJParser.hpp b/include/Nazara/Utility/Formats/OBJParser.hpp index c01f7724a..86b0e9f12 100644 --- a/include/Nazara/Utility/Formats/OBJParser.hpp +++ b/include/Nazara/Utility/Formats/OBJParser.hpp @@ -8,7 +8,6 @@ #define NAZARA_FORMATS_OBJPARSER_HPP #include -#include #include #include #include @@ -20,8 +19,6 @@ namespace Nz class NAZARA_UTILITY_API OBJParser { public: - struct Face; - struct FaceVertex; struct Mesh; OBJParser() = default; diff --git a/include/Nazara/Utility/Formats/OBJParser.inl b/include/Nazara/Utility/Formats/OBJParser.inl index 4b780672b..e1d821a44 100644 --- a/include/Nazara/Utility/Formats/OBJParser.inl +++ b/include/Nazara/Utility/Formats/OBJParser.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include diff --git a/include/Nazara/Utility/Image.hpp b/include/Nazara/Utility/Image.hpp index cbae97f9a..53c3efbb4 100644 --- a/include/Nazara/Utility/Image.hpp +++ b/include/Nazara/Utility/Image.hpp @@ -10,14 +10,12 @@ #include #include #include -#include #include #include #include #include #include #include -#include #include #include #include diff --git a/include/Nazara/Utility/IndexBuffer.inl b/include/Nazara/Utility/IndexBuffer.inl index b439623eb..1bcf60b26 100644 --- a/include/Nazara/Utility/IndexBuffer.inl +++ b/include/Nazara/Utility/IndexBuffer.inl @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include @@ -45,7 +44,7 @@ namespace Nz inline bool IndexBuffer::IsValid() const { - return m_buffer; + return m_buffer.IsValid(); } inline void* IndexBuffer::Map(BufferAccess access, UInt32 startIndex, UInt32 length) diff --git a/include/Nazara/Utility/IndexMapper.hpp b/include/Nazara/Utility/IndexMapper.hpp index b18e8989f..fe7ab318c 100644 --- a/include/Nazara/Utility/IndexMapper.hpp +++ b/include/Nazara/Utility/IndexMapper.hpp @@ -13,7 +13,6 @@ namespace Nz { - class IndexBuffer; class IndexIterator; class SubMesh; diff --git a/include/Nazara/Utility/Mesh.hpp b/include/Nazara/Utility/Mesh.hpp index a05f7c9f4..d3082b82f 100644 --- a/include/Nazara/Utility/Mesh.hpp +++ b/include/Nazara/Utility/Mesh.hpp @@ -10,18 +10,17 @@ #include #include #include -#include #include #include #include #include #include #include -#include #include #include -#include -#include +#include +#include +#include #include namespace Nz @@ -38,14 +37,24 @@ namespace Nz bool center = false; ///< If true, will center the mesh vertices around the origin bool optimizeIndexBuffers = true; ///< Optimize the index buffers after loading, improve cache locality (and thus rendering speed) but increase loading time. + /* The declaration must have a Vector3f position component enabled + * If the declaration has a Vector2f UV component enabled, UV are generated + * If the declaration has a Vector3f Normals component enabled, Normals are generated. + * If the declaration has a Vector3f Tangents component enabled, Tangents are generated. + */ + VertexDeclaration* vertexDeclaration = VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent); + bool IsValid() const; }; class Mesh; + struct Primitive; class PrimitiveList; + class Skeleton; + class SubMesh; - typedef VertexStruct_XYZ_Normal_UV_Tangent MeshVertex; - typedef VertexStruct_XYZ_Normal_UV_Tangent_Skinning SkeletalMeshVertex; + using MeshVertex = VertexStruct_XYZ_Normal_UV_Tangent; + using SkeletalMeshVertex = VertexStruct_XYZ_Normal_UV_Tangent_Skinning; using MeshConstRef = ObjectRef; using MeshLibrary = ObjectLibrary; diff --git a/include/Nazara/Utility/Node.hpp b/include/Nazara/Utility/Node.hpp index e70732837..22a96eed2 100644 --- a/include/Nazara/Utility/Node.hpp +++ b/include/Nazara/Utility/Node.hpp @@ -14,7 +14,6 @@ #include #include #include -#include #include namespace Nz diff --git a/include/Nazara/Utility/PixelFormat.inl b/include/Nazara/Utility/PixelFormat.inl index 4fe75c8b5..7fe11d1a4 100644 --- a/include/Nazara/Utility/PixelFormat.inl +++ b/include/Nazara/Utility/PixelFormat.inl @@ -2,9 +2,7 @@ // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include -#include #include #include #include diff --git a/include/Nazara/Utility/SkeletalMesh.hpp b/include/Nazara/Utility/SkeletalMesh.hpp index d67210c74..0dc436588 100644 --- a/include/Nazara/Utility/SkeletalMesh.hpp +++ b/include/Nazara/Utility/SkeletalMesh.hpp @@ -10,7 +10,9 @@ #include #include #include +#include #include +#include namespace Nz { diff --git a/include/Nazara/Utility/Skeleton.hpp b/include/Nazara/Utility/Skeleton.hpp index 0ed6c6691..f2c2fb5a8 100644 --- a/include/Nazara/Utility/Skeleton.hpp +++ b/include/Nazara/Utility/Skeleton.hpp @@ -13,11 +13,11 @@ #include #include #include -#include -#include +#include namespace Nz { + class Joint; class Skeleton; using SkeletonConstRef = ObjectRef; diff --git a/include/Nazara/Utility/SubMesh.hpp b/include/Nazara/Utility/SubMesh.hpp index d9d5cd2bf..c3c6e4dbb 100644 --- a/include/Nazara/Utility/SubMesh.hpp +++ b/include/Nazara/Utility/SubMesh.hpp @@ -14,7 +14,6 @@ #include #include #include -#include namespace Nz { diff --git a/include/Nazara/Utility/Utility.hpp b/include/Nazara/Utility/Utility.hpp index d78121f2c..8f4556de6 100644 --- a/include/Nazara/Utility/Utility.hpp +++ b/include/Nazara/Utility/Utility.hpp @@ -8,8 +8,6 @@ #define NAZARA_UTILITY_HPP #include -#include -#include #include #include @@ -25,15 +23,12 @@ namespace Nz static bool IsInitialized(); - static void SetParameters(const ParameterList& parameters); - static void Uninitialize(); static unsigned int ComponentCount[ComponentType_Max+1]; static std::size_t ComponentStride[ComponentType_Max+1]; private: - static ParameterList s_initializationParameters; static unsigned int s_moduleReferenceCounter; }; } diff --git a/include/Nazara/Utility/VertexBuffer.inl b/include/Nazara/Utility/VertexBuffer.inl index 588289f92..09f701d12 100644 --- a/include/Nazara/Utility/VertexBuffer.inl +++ b/include/Nazara/Utility/VertexBuffer.inl @@ -39,7 +39,7 @@ namespace Nz inline bool VertexBuffer::IsValid() const { - return m_buffer && m_vertexDeclaration; + return m_buffer.IsValid() && m_vertexDeclaration.IsValid(); } template diff --git a/include/Nazara/Utility/VertexDeclaration.hpp b/include/Nazara/Utility/VertexDeclaration.hpp index 594f1b5f0..1490857cf 100644 --- a/include/Nazara/Utility/VertexDeclaration.hpp +++ b/include/Nazara/Utility/VertexDeclaration.hpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -38,6 +38,8 @@ namespace Nz void EnableComponent(VertexComponent component, ComponentType type, std::size_t offset); void GetComponent(VertexComponent component, bool* enabled, ComponentType* type, std::size_t* offset) const; + bool HasComponent(VertexComponent component) const; + template bool HasComponentOfType(VertexComponent component) const; std::size_t GetStride() const; void SetStride(std::size_t stride); diff --git a/include/Nazara/Utility/VertexDeclaration.inl b/include/Nazara/Utility/VertexDeclaration.inl index 26cd39736..8f8e74179 100644 --- a/include/Nazara/Utility/VertexDeclaration.inl +++ b/include/Nazara/Utility/VertexDeclaration.inl @@ -1,9 +1,10 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp #include #include +#include namespace Nz { @@ -15,6 +16,17 @@ namespace Nz return object.release(); } + + template + bool VertexDeclaration::HasComponentOfType(VertexComponent component) const + { + bool enabled; + Nz::ComponentType type; + + GetComponent(component, &enabled, &type, nullptr); + + return enabled && GetComponentTypeOf() == type; + } } #include diff --git a/include/Nazara/Utility/VertexMapper.hpp b/include/Nazara/Utility/VertexMapper.hpp index 486d000fd..cfa27efe7 100644 --- a/include/Nazara/Utility/VertexMapper.hpp +++ b/include/Nazara/Utility/VertexMapper.hpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -27,6 +27,7 @@ namespace Nz ~VertexMapper(); template SparsePtr GetComponentPtr(VertexComponent component); + template bool HasComponentOfType(VertexComponent component) const; void Unmap(); diff --git a/include/Nazara/Utility/VertexMapper.inl b/include/Nazara/Utility/VertexMapper.inl index 6892f9091..3c4a95959 100644 --- a/include/Nazara/Utility/VertexMapper.inl +++ b/include/Nazara/Utility/VertexMapper.inl @@ -1,9 +1,10 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp #include #include +#include namespace Nz { @@ -19,7 +20,7 @@ namespace Nz std::size_t offset; declaration->GetComponent(component, &enabled, &type, &offset); - if (enabled) + if (enabled && GetComponentTypeOf() == type) { ///TODO: Vérifier le rapport entre le type de l'attribut et le type template ? return SparsePtr(static_cast(m_mapper.GetPointer()) + offset, declaration->GetStride()); @@ -30,6 +31,12 @@ namespace Nz return SparsePtr(); } } + + template + bool VertexMapper::HasComponentOfType(VertexComponent component) const + { + return m_mapper.GetBuffer()->GetVertexDeclaration()->HasComponentOfType(component); + } } #include diff --git a/plugins/Assimp/Plugin.cpp b/plugins/Assimp/Plugin.cpp index 744434137..08c48b372 100644 --- a/plugins/Assimp/Plugin.cpp +++ b/plugins/Assimp/Plugin.cpp @@ -28,7 +28,9 @@ SOFTWARE. #include #include #include +#include #include +#include #include #include #include @@ -202,6 +204,12 @@ bool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters) indexMapper.Unmap(); // Vertex buffer + + // Make sure the normal/tangent matrix won't rescale our vectors + Nz::Matrix4f normalTangentMatrix = parameters.matrix; + if (normalTangentMatrix.HasScale()) + normalTangentMatrix.ApplyScale(1.f / normalTangentMatrix.GetScale()); + VertexBufferRef vertexBuffer = VertexBuffer::New(VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent), vertexCount, parameters.storage, 0); BufferMapper vertexMapper(vertexBuffer, BufferAccess_WriteOnly); @@ -214,8 +222,8 @@ bool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters) aiVector3D uv = (iMesh->HasTextureCoords(0)) ? iMesh->mTextureCoords[0][j] : aiVector3D(0.f); vertex->position = parameters.matrix * Vector3f(position.x, position.y, position.z); - vertex->normal.Set(normal.x, normal.y, normal.z); - vertex->tangent.Set(tangent.x, tangent.y, tangent.z); + vertex->normal = normalTangentMatrix.Transform({normal.x, normal.y, normal.z}, 0.f); + vertex->tangent = normalTangentMatrix.Transform({tangent.x, tangent.y, tangent.z}, 0.f); vertex->uv.Set(parameters.texCoordOffset + Vector2f(uv.x, uv.y) * parameters.texCoordScale); vertex++; } diff --git a/src/Nazara/Audio/Music.cpp b/src/Nazara/Audio/Music.cpp index cdfe4caac..185b911b6 100644 --- a/src/Nazara/Audio/Music.cpp +++ b/src/Nazara/Audio/Music.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include diff --git a/src/Nazara/Audio/Sound.cpp b/src/Nazara/Audio/Sound.cpp index 87e15ee2c..a3beac029 100644 --- a/src/Nazara/Audio/Sound.cpp +++ b/src/Nazara/Audio/Sound.cpp @@ -3,13 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include -#include -#include -#include #include namespace Nz diff --git a/src/Nazara/Core/AbstractHash.cpp b/src/Nazara/Core/AbstractHash.cpp index ae2cb63b5..39e5a2ef2 100644 --- a/src/Nazara/Core/AbstractHash.cpp +++ b/src/Nazara/Core/AbstractHash.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -48,6 +49,9 @@ namespace Nz case HashType_CRC32: return std::make_unique(); + case HashType_CRC64: + return std::make_unique(); + case HashType_MD5: return std::make_unique(); diff --git a/src/Nazara/Core/ByteArray.cpp b/src/Nazara/Core/ByteArray.cpp index 4402af91d..a6556c6d2 100644 --- a/src/Nazara/Core/ByteArray.cpp +++ b/src/Nazara/Core/ByteArray.cpp @@ -3,8 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include #include namespace Nz diff --git a/src/Nazara/Core/ByteStream.cpp b/src/Nazara/Core/ByteStream.cpp index 489f90338..a61cae520 100644 --- a/src/Nazara/Core/ByteStream.cpp +++ b/src/Nazara/Core/ByteStream.cpp @@ -6,7 +6,6 @@ #include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Core/Clock.cpp b/src/Nazara/Core/Clock.cpp index 881d7c40e..92183674c 100644 --- a/src/Nazara/Core/Clock.cpp +++ b/src/Nazara/Core/Clock.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #if defined(NAZARA_PLATFORM_WINDOWS) #include diff --git a/src/Nazara/Core/ConditionVariable.cpp b/src/Nazara/Core/ConditionVariable.cpp index 86ecb11ed..f4314870c 100644 --- a/src/Nazara/Core/ConditionVariable.cpp +++ b/src/Nazara/Core/ConditionVariable.cpp @@ -102,18 +102,4 @@ namespace Nz NazaraAssert(mutex != nullptr, "Mutex must be valid"); return m_impl->Wait(mutex->m_impl, timeout); } - - /*! - * \brief Moves a condition to another ConditionVariable object - * \return A reference to the object - */ - ConditionVariable& ConditionVariable::operator=(ConditionVariable&& condition) noexcept - { - delete m_impl; - - m_impl = condition.m_impl; - condition.m_impl = nullptr; - - return *this; - } } diff --git a/src/Nazara/Core/Core.cpp b/src/Nazara/Core/Core.cpp index 4a27bd482..614d6217b 100644 --- a/src/Nazara/Core/Core.cpp +++ b/src/Nazara/Core/Core.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include diff --git a/src/Nazara/Core/DynLib.cpp b/src/Nazara/Core/DynLib.cpp index 10e5d4247..1558f5a37 100644 --- a/src/Nazara/Core/DynLib.cpp +++ b/src/Nazara/Core/DynLib.cpp @@ -40,19 +40,6 @@ namespace Nz { } - /*! - * \brief Constructs a DynLib object by move semantic - * - * \param lib DynLib to move into this - */ - - DynLib::DynLib(DynLib&& lib) : - m_lastError(std::move(lib.m_lastError)), - m_impl(lib.m_impl) - { - lib.m_impl = nullptr; - } - /*! * \brief Destructs the object and calls Unload * @@ -150,23 +137,4 @@ namespace Nz m_impl = nullptr; } } - - /*! - * \brief Moves the other lib into this - * \return A reference to this - * - * \param lib DynLib to move in this - */ - - DynLib& DynLib::operator=(DynLib&& lib) - { - Unload(); - - m_impl = lib.m_impl; - m_lastError = std::move(lib.m_lastError); - - lib.m_impl = nullptr; - - return *this; - } } diff --git a/src/Nazara/Core/File.cpp b/src/Nazara/Core/File.cpp index 9aa9374e0..6181f7d1b 100644 --- a/src/Nazara/Core/File.cpp +++ b/src/Nazara/Core/File.cpp @@ -5,12 +5,11 @@ #include #include #include +#include #include #include #include -#include #include -#include #if defined(NAZARA_PLATFORM_WINDOWS) #include @@ -70,20 +69,6 @@ namespace Nz Open(filePath, openMode); } - /*! - * \brief Constructs a File object by move semantic - * - * \param file File to move into this - */ - - File::File(File&& file) noexcept : - Stream(std::move(file)), - m_filePath(std::move(file.m_filePath)), - m_impl(file.m_impl) - { - file.m_impl = nullptr; - } - /*! * \brief Destructs the object and calls Close * @@ -487,23 +472,6 @@ namespace Nz return *this; } - /*! - * \brief Moves the other file into this - * \return A reference to this - * - * \param file File to move in this - */ - - File& File::operator=(File&& file) noexcept - { - NazaraLock(m_mutex) - - std::swap(m_filePath, file.m_filePath); - std::swap(m_impl, file.m_impl); - - return *this; - } - /*! * \brief Gets the absolute path of the file * \return Absolute path of the file diff --git a/src/Nazara/Core/GuillotineBinPack.cpp b/src/Nazara/Core/GuillotineBinPack.cpp index 85270a562..0df4e0429 100644 --- a/src/Nazara/Core/GuillotineBinPack.cpp +++ b/src/Nazara/Core/GuillotineBinPack.cpp @@ -9,8 +9,6 @@ #include #include #include -#include -#include #include #include diff --git a/src/Nazara/Core/HardwareInfo.cpp b/src/Nazara/Core/HardwareInfo.cpp index a4bec3194..a22bbbdf6 100644 --- a/src/Nazara/Core/HardwareInfo.cpp +++ b/src/Nazara/Core/HardwareInfo.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #if defined(NAZARA_PLATFORM_WINDOWS) diff --git a/src/Nazara/Core/Hash/CRC64.cpp b/src/Nazara/Core/Hash/CRC64.cpp new file mode 100644 index 000000000..3001009a3 --- /dev/null +++ b/src/Nazara/Core/Hash/CRC64.cpp @@ -0,0 +1,115 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Core module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include +#include + +namespace Nz +{ + struct HashCRC64_state + { + UInt64 crc; + }; + + namespace + { + static const UInt64 crc64_table[256] = { + 0x0000000000000000ULL, 0x7ad870c830358979ULL, 0xf5b0e190606b12f2ULL, 0x8f689158505e9b8bULL, + 0xc038e5739841b68fULL, 0xbae095bba8743ff6ULL, 0x358804e3f82aa47dULL, 0x4f50742bc81f2d04ULL, + 0xab28ecb46814fe75ULL, 0xd1f09c7c5821770cULL, 0x5e980d24087fec87ULL, 0x24407dec384a65feULL, + 0x6b1009c7f05548faULL, 0x11c8790fc060c183ULL, 0x9ea0e857903e5a08ULL, 0xe478989fa00bd371ULL, + 0x7d08ff3b88be6f81ULL, 0x07d08ff3b88be6f8ULL, 0x88b81eabe8d57d73ULL, 0xf2606e63d8e0f40aULL, + 0xbd301a4810ffd90eULL, 0xc7e86a8020ca5077ULL, 0x4880fbd87094cbfcULL, 0x32588b1040a14285ULL, + 0xd620138fe0aa91f4ULL, 0xacf86347d09f188dULL, 0x2390f21f80c18306ULL, 0x594882d7b0f40a7fULL, + 0x1618f6fc78eb277bULL, 0x6cc0863448deae02ULL, 0xe3a8176c18803589ULL, 0x997067a428b5bcf0ULL, + 0xfa11fe77117cdf02ULL, 0x80c98ebf2149567bULL, 0x0fa11fe77117cdf0ULL, 0x75796f2f41224489ULL, + 0x3a291b04893d698dULL, 0x40f16bccb908e0f4ULL, 0xcf99fa94e9567b7fULL, 0xb5418a5cd963f206ULL, + 0x513912c379682177ULL, 0x2be1620b495da80eULL, 0xa489f35319033385ULL, 0xde51839b2936bafcULL, + 0x9101f7b0e12997f8ULL, 0xebd98778d11c1e81ULL, 0x64b116208142850aULL, 0x1e6966e8b1770c73ULL, + 0x8719014c99c2b083ULL, 0xfdc17184a9f739faULL, 0x72a9e0dcf9a9a271ULL, 0x08719014c99c2b08ULL, + 0x4721e43f0183060cULL, 0x3df994f731b68f75ULL, 0xb29105af61e814feULL, 0xc849756751dd9d87ULL, + 0x2c31edf8f1d64ef6ULL, 0x56e99d30c1e3c78fULL, 0xd9810c6891bd5c04ULL, 0xa3597ca0a188d57dULL, + 0xec09088b6997f879ULL, 0x96d1784359a27100ULL, 0x19b9e91b09fcea8bULL, 0x636199d339c963f2ULL, + 0xdf7adabd7a6e2d6fULL, 0xa5a2aa754a5ba416ULL, 0x2aca3b2d1a053f9dULL, 0x50124be52a30b6e4ULL, + 0x1f423fcee22f9be0ULL, 0x659a4f06d21a1299ULL, 0xeaf2de5e82448912ULL, 0x902aae96b271006bULL, + 0x74523609127ad31aULL, 0x0e8a46c1224f5a63ULL, 0x81e2d7997211c1e8ULL, 0xfb3aa75142244891ULL, + 0xb46ad37a8a3b6595ULL, 0xceb2a3b2ba0eececULL, 0x41da32eaea507767ULL, 0x3b024222da65fe1eULL, + 0xa2722586f2d042eeULL, 0xd8aa554ec2e5cb97ULL, 0x57c2c41692bb501cULL, 0x2d1ab4dea28ed965ULL, + 0x624ac0f56a91f461ULL, 0x1892b03d5aa47d18ULL, 0x97fa21650afae693ULL, 0xed2251ad3acf6feaULL, + 0x095ac9329ac4bc9bULL, 0x7382b9faaaf135e2ULL, 0xfcea28a2faafae69ULL, 0x8632586aca9a2710ULL, + 0xc9622c4102850a14ULL, 0xb3ba5c8932b0836dULL, 0x3cd2cdd162ee18e6ULL, 0x460abd1952db919fULL, + 0x256b24ca6b12f26dULL, 0x5fb354025b277b14ULL, 0xd0dbc55a0b79e09fULL, 0xaa03b5923b4c69e6ULL, + 0xe553c1b9f35344e2ULL, 0x9f8bb171c366cd9bULL, 0x10e3202993385610ULL, 0x6a3b50e1a30ddf69ULL, + 0x8e43c87e03060c18ULL, 0xf49bb8b633338561ULL, 0x7bf329ee636d1eeaULL, 0x012b592653589793ULL, + 0x4e7b2d0d9b47ba97ULL, 0x34a35dc5ab7233eeULL, 0xbbcbcc9dfb2ca865ULL, 0xc113bc55cb19211cULL, + 0x5863dbf1e3ac9decULL, 0x22bbab39d3991495ULL, 0xadd33a6183c78f1eULL, 0xd70b4aa9b3f20667ULL, + 0x985b3e827bed2b63ULL, 0xe2834e4a4bd8a21aULL, 0x6debdf121b863991ULL, 0x1733afda2bb3b0e8ULL, + 0xf34b37458bb86399ULL, 0x8993478dbb8deae0ULL, 0x06fbd6d5ebd3716bULL, 0x7c23a61ddbe6f812ULL, + 0x3373d23613f9d516ULL, 0x49aba2fe23cc5c6fULL, 0xc6c333a67392c7e4ULL, 0xbc1b436e43a74e9dULL, + 0x95ac9329ac4bc9b5ULL, 0xef74e3e19c7e40ccULL, 0x601c72b9cc20db47ULL, 0x1ac40271fc15523eULL, + 0x5594765a340a7f3aULL, 0x2f4c0692043ff643ULL, 0xa02497ca54616dc8ULL, 0xdafce7026454e4b1ULL, + 0x3e847f9dc45f37c0ULL, 0x445c0f55f46abeb9ULL, 0xcb349e0da4342532ULL, 0xb1eceec59401ac4bULL, + 0xfebc9aee5c1e814fULL, 0x8464ea266c2b0836ULL, 0x0b0c7b7e3c7593bdULL, 0x71d40bb60c401ac4ULL, + 0xe8a46c1224f5a634ULL, 0x927c1cda14c02f4dULL, 0x1d148d82449eb4c6ULL, 0x67ccfd4a74ab3dbfULL, + 0x289c8961bcb410bbULL, 0x5244f9a98c8199c2ULL, 0xdd2c68f1dcdf0249ULL, 0xa7f41839ecea8b30ULL, + 0x438c80a64ce15841ULL, 0x3954f06e7cd4d138ULL, 0xb63c61362c8a4ab3ULL, 0xcce411fe1cbfc3caULL, + 0x83b465d5d4a0eeceULL, 0xf96c151de49567b7ULL, 0x76048445b4cbfc3cULL, 0x0cdcf48d84fe7545ULL, + 0x6fbd6d5ebd3716b7ULL, 0x15651d968d029fceULL, 0x9a0d8ccedd5c0445ULL, 0xe0d5fc06ed698d3cULL, + 0xaf85882d2576a038ULL, 0xd55df8e515432941ULL, 0x5a3569bd451db2caULL, 0x20ed197575283bb3ULL, + 0xc49581ead523e8c2ULL, 0xbe4df122e51661bbULL, 0x3125607ab548fa30ULL, 0x4bfd10b2857d7349ULL, + 0x04ad64994d625e4dULL, 0x7e7514517d57d734ULL, 0xf11d85092d094cbfULL, 0x8bc5f5c11d3cc5c6ULL, + 0x12b5926535897936ULL, 0x686de2ad05bcf04fULL, 0xe70573f555e26bc4ULL, 0x9ddd033d65d7e2bdULL, + 0xd28d7716adc8cfb9ULL, 0xa85507de9dfd46c0ULL, 0x273d9686cda3dd4bULL, 0x5de5e64efd965432ULL, + 0xb99d7ed15d9d8743ULL, 0xc3450e196da80e3aULL, 0x4c2d9f413df695b1ULL, 0x36f5ef890dc31cc8ULL, + 0x79a59ba2c5dc31ccULL, 0x037deb6af5e9b8b5ULL, 0x8c157a32a5b7233eULL, 0xf6cd0afa9582aa47ULL, + 0x4ad64994d625e4daULL, 0x300e395ce6106da3ULL, 0xbf66a804b64ef628ULL, 0xc5bed8cc867b7f51ULL, + 0x8aeeace74e645255ULL, 0xf036dc2f7e51db2cULL, 0x7f5e4d772e0f40a7ULL, 0x05863dbf1e3ac9deULL, + 0xe1fea520be311aafULL, 0x9b26d5e88e0493d6ULL, 0x144e44b0de5a085dULL, 0x6e963478ee6f8124ULL, + 0x21c640532670ac20ULL, 0x5b1e309b16452559ULL, 0xd476a1c3461bbed2ULL, 0xaeaed10b762e37abULL, + 0x37deb6af5e9b8b5bULL, 0x4d06c6676eae0222ULL, 0xc26e573f3ef099a9ULL, 0xb8b627f70ec510d0ULL, + 0xf7e653dcc6da3dd4ULL, 0x8d3e2314f6efb4adULL, 0x0256b24ca6b12f26ULL, 0x788ec2849684a65fULL, + 0x9cf65a1b368f752eULL, 0xe62e2ad306bafc57ULL, 0x6946bb8b56e467dcULL, 0x139ecb4366d1eea5ULL, + 0x5ccebf68aecec3a1ULL, 0x2616cfa09efb4ad8ULL, 0xa97e5ef8cea5d153ULL, 0xd3a62e30fe90582aULL, + 0xb0c7b7e3c7593bd8ULL, 0xca1fc72bf76cb2a1ULL, 0x45775673a732292aULL, 0x3faf26bb9707a053ULL, + 0x70ff52905f188d57ULL, 0x0a2722586f2d042eULL, 0x854fb3003f739fa5ULL, 0xff97c3c80f4616dcULL, + 0x1bef5b57af4dc5adULL, 0x61372b9f9f784cd4ULL, 0xee5fbac7cf26d75fULL, 0x9487ca0fff135e26ULL, + 0xdbd7be24370c7322ULL, 0xa10fceec0739fa5bULL, 0x2e675fb4576761d0ULL, 0x54bf2f7c6752e8a9ULL, + 0xcdcf48d84fe75459ULL, 0xb71738107fd2dd20ULL, 0x387fa9482f8c46abULL, 0x42a7d9801fb9cfd2ULL, + 0x0df7adabd7a6e2d6ULL, 0x772fdd63e7936bafULL, 0xf8474c3bb7cdf024ULL, 0x829f3cf387f8795dULL, + 0x66e7a46c27f3aa2cULL, 0x1c3fd4a417c62355ULL, 0x935745fc4798b8deULL, 0xe98f353477ad31a7ULL, + 0xa6df411fbfb21ca3ULL, 0xdc0731d78f8795daULL, 0x536fa08fdfd90e51ULL, 0x29b7d047efec8728ULL + }; + } + + void HashCRC64::Append(const UInt8* data, std::size_t len) + { + while (len--) + m_crc = crc64_table[(m_crc ^ *data++) & 0xFF] ^ (m_crc >> 8); + } + + void HashCRC64::Begin() + { + m_crc = 0; + } + + ByteArray HashCRC64::End() + { + #ifdef NAZARA_LITTLE_ENDIAN + SwapBytes(&m_crc, sizeof(UInt64)); + #endif + + return ByteArray(reinterpret_cast(&m_crc), 8); + } + + std::size_t HashCRC64::GetDigestLength() const + { + return 8; + } + + const char* HashCRC64::GetHashName() const + { + return "CRC64"; + } +} diff --git a/src/Nazara/Core/MemoryManager.cpp b/src/Nazara/Core/MemoryManager.cpp index aaf6bc520..2b1bd6a72 100644 --- a/src/Nazara/Core/MemoryManager.cpp +++ b/src/Nazara/Core/MemoryManager.cpp @@ -5,9 +5,9 @@ #include #include #include +#include #include #include -#include #if defined(NAZARA_PLATFORM_WINDOWS) #include diff --git a/src/Nazara/Core/Mutex.cpp b/src/Nazara/Core/Mutex.cpp index 953568ecc..473ee233e 100644 --- a/src/Nazara/Core/Mutex.cpp +++ b/src/Nazara/Core/Mutex.cpp @@ -77,18 +77,4 @@ namespace Nz NazaraAssert(m_impl, "Cannot unlock a moved mutex"); m_impl->Unlock(); } - - /*! - * \brief Moves a mutex to another mutex object - * \return A reference to the object - */ - Mutex& Mutex::operator=(Mutex&& mutex) noexcept - { - delete m_impl; - - m_impl = mutex.m_impl; - mutex.m_impl = nullptr; - - return *this; - } } diff --git a/src/Nazara/Core/ParameterList.cpp b/src/Nazara/Core/ParameterList.cpp index 89fdb4591..7d3b82972 100644 --- a/src/Nazara/Core/ParameterList.cpp +++ b/src/Nazara/Core/ParameterList.cpp @@ -7,8 +7,6 @@ #include #include #include -#include -#include #include namespace Nz diff --git a/src/Nazara/Core/Posix/ClockImpl.cpp b/src/Nazara/Core/Posix/ClockImpl.cpp index 73b45b6e7..203b1fbbb 100644 --- a/src/Nazara/Core/Posix/ClockImpl.cpp +++ b/src/Nazara/Core/Posix/ClockImpl.cpp @@ -3,8 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include #include #include diff --git a/src/Nazara/Core/Posix/ConditionVariableImpl.cpp b/src/Nazara/Core/Posix/ConditionVariableImpl.cpp index c1c6e891d..69eb691fa 100644 --- a/src/Nazara/Core/Posix/ConditionVariableImpl.cpp +++ b/src/Nazara/Core/Posix/ConditionVariableImpl.cpp @@ -4,6 +4,8 @@ #include #include +#include +#include #include namespace Nz diff --git a/src/Nazara/Core/Posix/ConditionVariableImpl.hpp b/src/Nazara/Core/Posix/ConditionVariableImpl.hpp index 1781711c4..a5dea1e8b 100644 --- a/src/Nazara/Core/Posix/ConditionVariableImpl.hpp +++ b/src/Nazara/Core/Posix/ConditionVariableImpl.hpp @@ -11,8 +11,6 @@ #include #include -#include -#include namespace Nz { diff --git a/src/Nazara/Core/Posix/DirectoryImpl.cpp b/src/Nazara/Core/Posix/DirectoryImpl.cpp index e23c82626..805a44232 100644 --- a/src/Nazara/Core/Posix/DirectoryImpl.cpp +++ b/src/Nazara/Core/Posix/DirectoryImpl.cpp @@ -4,10 +4,12 @@ #include #include -#include - +#include #include #include +#include +#include +#include namespace Nz { diff --git a/src/Nazara/Core/Posix/DirectoryImpl.hpp b/src/Nazara/Core/Posix/DirectoryImpl.hpp index 5f77fbb43..af857fada 100644 --- a/src/Nazara/Core/Posix/DirectoryImpl.hpp +++ b/src/Nazara/Core/Posix/DirectoryImpl.hpp @@ -9,9 +9,6 @@ #include #include -#include -#include -#include namespace Nz { diff --git a/src/Nazara/Core/Posix/DynLibImpl.cpp b/src/Nazara/Core/Posix/DynLibImpl.cpp index dbb8463fa..27204443e 100644 --- a/src/Nazara/Core/Posix/DynLibImpl.cpp +++ b/src/Nazara/Core/Posix/DynLibImpl.cpp @@ -4,8 +4,8 @@ #include #include -#include #include +#include #include namespace Nz diff --git a/src/Nazara/Core/Posix/DynLibImpl.hpp b/src/Nazara/Core/Posix/DynLibImpl.hpp index 1f36fa9e3..e101abc84 100644 --- a/src/Nazara/Core/Posix/DynLibImpl.hpp +++ b/src/Nazara/Core/Posix/DynLibImpl.hpp @@ -8,7 +8,6 @@ #define NAZARA_DYNLIBIMPL_HPP #include -#include namespace Nz { diff --git a/src/Nazara/Core/Posix/FileImpl.cpp b/src/Nazara/Core/Posix/FileImpl.cpp index 5603ed79b..59935dd35 100644 --- a/src/Nazara/Core/Posix/FileImpl.cpp +++ b/src/Nazara/Core/Posix/FileImpl.cpp @@ -4,6 +4,9 @@ #include #include +#include +#include +#include #include #include @@ -72,11 +75,47 @@ namespace Nz if (mode & OpenMode_Truncate) flags |= O_TRUNC; - ///TODO: lock - //if ((mode & OpenMode_Lock) == 0) - // shareMode |= FILE_SHARE_WRITE; - m_fileDescriptor = open64(filePath.GetConstBuffer(), flags, permissions); + + static struct flock lock; + + auto initialize_flock = [](struct flock& fileLock) + { + fileLock.l_type = F_WRLCK; + fileLock.l_start = 0; + fileLock.l_whence = SEEK_SET; + fileLock.l_len = 0; + fileLock.l_pid = getpid(); + }; + + initialize_flock(lock); + + if (fcntl(m_fileDescriptor, F_GETLK, &lock) == -1) + { + Close(); + NazaraError("Unable to detect presence of lock on the file"); + return false; + } + + if (lock.l_type != F_UNLCK) + { + Close(); + NazaraError("A lock is present on the file"); + return false; + } + + if (mode & OpenMode_Lock) + { + initialize_flock(lock); + + if (fcntl(m_fileDescriptor, F_SETLK, &lock) == -1) + { + Close(); + NazaraError("Unable to place a lock on the file"); + return false; + } + } + return m_fileDescriptor != -1; } @@ -128,10 +167,7 @@ namespace Nz std::size_t FileImpl::Write(const void* buffer, std::size_t size) { - lockf64(m_fileDescriptor, F_LOCK, size); ssize_t written = write(m_fileDescriptor, buffer, size); - lockf64(m_fileDescriptor, F_ULOCK, size); - m_endOfFileUpdated = false; return written; diff --git a/src/Nazara/Core/Posix/FileImpl.hpp b/src/Nazara/Core/Posix/FileImpl.hpp index 51f966980..cf396e0fa 100644 --- a/src/Nazara/Core/Posix/FileImpl.hpp +++ b/src/Nazara/Core/Posix/FileImpl.hpp @@ -12,12 +12,8 @@ #endif #include -#include +#include #include -#include -#include -#include -#include namespace Nz { diff --git a/src/Nazara/Core/Posix/HardwareInfoImpl.cpp b/src/Nazara/Core/Posix/HardwareInfoImpl.cpp index 20ea4950f..6e23c2f8b 100644 --- a/src/Nazara/Core/Posix/HardwareInfoImpl.cpp +++ b/src/Nazara/Core/Posix/HardwareInfoImpl.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include +#include #include namespace Nz diff --git a/src/Nazara/Core/Posix/HardwareInfoImpl.hpp b/src/Nazara/Core/Posix/HardwareInfoImpl.hpp index 671802c52..fec00ec93 100644 --- a/src/Nazara/Core/Posix/HardwareInfoImpl.hpp +++ b/src/Nazara/Core/Posix/HardwareInfoImpl.hpp @@ -8,7 +8,6 @@ #define NAZARA_HARDWAREINFOIMPL_POSIX_HPP #include -#include namespace Nz { diff --git a/src/Nazara/Core/Posix/SemaphoreImpl.cpp b/src/Nazara/Core/Posix/SemaphoreImpl.cpp index eb1b7d1dd..c53928407 100644 --- a/src/Nazara/Core/Posix/SemaphoreImpl.cpp +++ b/src/Nazara/Core/Posix/SemaphoreImpl.cpp @@ -3,9 +3,8 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include -#include +#include #include #include diff --git a/src/Nazara/Core/Posix/TaskSchedulerImpl.cpp b/src/Nazara/Core/Posix/TaskSchedulerImpl.cpp index b04fdcfd9..e8cbb3de8 100644 --- a/src/Nazara/Core/Posix/TaskSchedulerImpl.cpp +++ b/src/Nazara/Core/Posix/TaskSchedulerImpl.cpp @@ -3,8 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include +#include #include namespace Nz diff --git a/src/Nazara/Core/Posix/TaskSchedulerImpl.hpp b/src/Nazara/Core/Posix/TaskSchedulerImpl.hpp index e132e4686..43ce552b6 100644 --- a/src/Nazara/Core/Posix/TaskSchedulerImpl.hpp +++ b/src/Nazara/Core/Posix/TaskSchedulerImpl.hpp @@ -8,7 +8,6 @@ #define NAZARA_TASKSCHEDULERIMPL_HPP #include -#include #include #include #include @@ -16,6 +15,8 @@ namespace Nz { + struct Functor; + class TaskSchedulerImpl { public: diff --git a/src/Nazara/Core/Posix/ThreadImpl.cpp b/src/Nazara/Core/Posix/ThreadImpl.cpp index c16424328..3793ddcf5 100644 --- a/src/Nazara/Core/Posix/ThreadImpl.cpp +++ b/src/Nazara/Core/Posix/ThreadImpl.cpp @@ -5,8 +5,10 @@ #include #include #include -#include -#include +#include +#include +#include +#include #include namespace Nz @@ -28,6 +30,43 @@ namespace Nz pthread_join(m_handle, nullptr); } + void ThreadImpl::SetName(const Nz::String& name) + { +#ifdef __GNUC__ + pthread_setname_np(m_handle, name.GetConstBuffer()); +#else + NazaraWarning("Setting thread name is not supported on this platform"); +#endif + } + + void ThreadImpl::SetCurrentName(const Nz::String& name) + { +#ifdef __GNUC__ + pthread_setname_np(pthread_self(), name.GetConstBuffer()); +#else + NazaraWarning("Setting current thread name is not supported on this platform"); +#endif + } + + void ThreadImpl::Sleep(UInt32 time) + { + if (time == 0) + sched_yield(); + else + { + struct timespec ts; + ts.tv_sec = time / 1000; + ts.tv_nsec = (time - ts.tv_sec * 1000) * 1'000'000; + + int r; + do + { + r = nanosleep(&ts, &ts); + } + while (r == -1 && errno == EINTR); + } + } + void* ThreadImpl::ThreadProc(void* userdata) { Functor* func = static_cast(userdata); @@ -36,40 +75,4 @@ namespace Nz return nullptr; } - - void ThreadImpl::Sleep(UInt32 time) - { - // code from SFML2 Unix SleepImpl.cpp source https://github.com/LaurentGomila/SFML/blob/master/src/SFML/System/Unix/SleepImpl.cpp - - // usleep is not reliable enough (it might block the - // whole process instead of just the current thread) - // so we must use pthread_cond_timedwait instead - - // this implementation is inspired from Qt - - // get the current time - timeval tv; - gettimeofday(&tv, nullptr); - - // construct the time limit (current time + time to wait) - timespec ti; - ti.tv_nsec = (tv.tv_usec + (time % 1000)) * 1000; - ti.tv_sec = tv.tv_sec + (time / 1000) + (ti.tv_nsec / 1000000000); - ti.tv_nsec %= 1000000000; - - // create a mutex and thread condition - pthread_mutex_t mutex; - pthread_mutex_init(&mutex, nullptr); - pthread_cond_t condition; - pthread_cond_init(&condition, nullptr); - - // wait... - pthread_mutex_lock(&mutex); - pthread_cond_timedwait(&condition, &mutex, &ti); - pthread_mutex_unlock(&mutex); - - // destroy the mutex and condition - pthread_cond_destroy(&condition); - pthread_mutex_destroy(&mutex); - } } diff --git a/src/Nazara/Core/Posix/ThreadImpl.hpp b/src/Nazara/Core/Posix/ThreadImpl.hpp index 1ed6f3c8a..fe3e593fe 100644 --- a/src/Nazara/Core/Posix/ThreadImpl.hpp +++ b/src/Nazara/Core/Posix/ThreadImpl.hpp @@ -8,11 +8,17 @@ #define NAZARA_THREADIMPL_HPP #include + +#if defined(__GNUC__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif + #include namespace Nz { struct Functor; + class String; class ThreadImpl { @@ -21,7 +27,9 @@ namespace Nz void Detach(); void Join(); + void SetName(const Nz::String& name); + static void SetCurrentName(const Nz::String& name); static void Sleep(UInt32 time); private: diff --git a/src/Nazara/Core/RefCounted.cpp b/src/Nazara/Core/RefCounted.cpp index 9532e5d86..42fbe5aaa 100644 --- a/src/Nazara/Core/RefCounted.cpp +++ b/src/Nazara/Core/RefCounted.cpp @@ -5,13 +5,6 @@ #include #include #include - -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_REFCOUNTED - #include -#else - #include -#endif - #include namespace Nz diff --git a/src/Nazara/Core/String.cpp b/src/Nazara/Core/String.cpp index 98a8b882c..2551ceb34 100644 --- a/src/Nazara/Core/String.cpp +++ b/src/Nazara/Core/String.cpp @@ -5975,20 +5975,7 @@ namespace std istream& getline(istream& is, Nz::String& str) { - str.Clear(); - - char c; - - for (;;) - { - is.get(c); - if (c != '\n' && c != '\0') - str += c; - else - break; - } - - return is; + return getline(is, str, is.widen('\n')); } /*! @@ -6012,7 +5999,11 @@ namespace std if (c != delim && c != '\0') str += c; else + { + if (c == '\0') + is.setstate(std::ios_base::eofbit); break; + } } return is; diff --git a/src/Nazara/Core/Thread.cpp b/src/Nazara/Core/Thread.cpp index c9532ec19..8f9f0b5b6 100644 --- a/src/Nazara/Core/Thread.cpp +++ b/src/Nazara/Core/Thread.cpp @@ -6,8 +6,7 @@ #include #include #include -#include -#include +#include #if defined(NAZARA_PLATFORM_WINDOWS) #include @@ -36,18 +35,6 @@ namespace Nz { } - /*! - * \brief Constructs a Thread object by move semantic - * - * \param other Thread to move into this - */ - - Thread::Thread(Thread&& other) noexcept : - m_impl(other.m_impl) - { - other.m_impl = nullptr; - } - /*! * \brief Waits that the thread ends and then destroys this */ @@ -118,45 +105,57 @@ namespace Nz } /*! - * \brief Moves the other thread into this - * \return A reference to this + * \brief Changes the debugging name associated to a thread * - * \param thread Thread to move in this + * Changes the debugging name associated with a particular thread, and may helps with debugging tools. * - * \remark Produce a NazaraError if no functor was assigned and NAZARA_CORE_SAFE is defined - * \remark And call std::terminate if no functor was assigned and NAZARA_CORE_SAFE is defined + * \param name The new name of the thread + * + * \remark Due to system limitations, thread name cannot exceed 15 characters (excluding null-terminator) + * + * \see SetCurrentThreadName */ - - Thread& Thread::operator=(Thread&& thread) + void Thread::SetName(const String& name) { - #if NAZARA_CORE_SAFE - if (m_impl) - { - NazaraError("This thread cannot be joined"); - std::terminate(); - } - #endif + NazaraAssert(m_impl, "Invalid thread"); + NazaraAssert(name.GetSize() < 16, "Thread name is too long"); - std::swap(m_impl, thread.m_impl); - return *this; + m_impl->SetName(name); } /*! * \brief Gets the number of simulatenous threads that can run on the same cpu * \return The number of simulatenous threads */ - unsigned int Thread::HardwareConcurrency() { return HardwareInfo::GetProcessorCount(); } + + /*! + * \brief Changes the debugging name associated to the calling thread + * + * Changes the debugging name associated with the calling thread, and may helps with debugging tools. + * + * \param name The new name associated with this thread + * + * \remark Due to system limitations, thread name cannot exceed 15 characters (excluding null-terminator) + * + * \see SetName + */ + void Thread::SetCurrentThreadName(const String& name) + { + NazaraAssert(name.GetSize() < 16, "Thread name is too long"); + + ThreadImpl::SetCurrentName(name); + } + /*! * \brief Makes sleep this thread * * \param milliseconds The number of milliseconds to sleep */ - void Thread::Sleep(UInt32 milliseconds) { ThreadImpl::Sleep(milliseconds); diff --git a/src/Nazara/Core/Win32/FileImpl.cpp b/src/Nazara/Core/Win32/FileImpl.cpp index b7c5d0f2d..4e5d75c6c 100644 --- a/src/Nazara/Core/Win32/FileImpl.cpp +++ b/src/Nazara/Core/Win32/FileImpl.cpp @@ -191,9 +191,7 @@ namespace Nz LARGE_INTEGER cursorPos; cursorPos.QuadPart = GetCursorPos(); - LockFile(m_handle, cursorPos.LowPart, cursorPos.HighPart, static_cast(size), 0); WriteFile(m_handle, buffer, static_cast(size), &written, nullptr); - UnlockFile(m_handle, cursorPos.LowPart, cursorPos.HighPart, static_cast(size), 0); m_endOfFileUpdated = false; diff --git a/src/Nazara/Core/Win32/ThreadImpl.cpp b/src/Nazara/Core/Win32/ThreadImpl.cpp index 5b44b94b6..cae997874 100644 --- a/src/Nazara/Core/Win32/ThreadImpl.cpp +++ b/src/Nazara/Core/Win32/ThreadImpl.cpp @@ -6,15 +6,32 @@ #include #include #include +#include #include namespace Nz { + namespace + { +#pragma pack(push,8) + struct THREADNAME_INFO + { + DWORD dwType; + LPCSTR szName; + DWORD dwThreadID; + DWORD dwFlags; + }; +#pragma pack(pop) + } + ThreadImpl::ThreadImpl(Functor* functor) { - m_handle = reinterpret_cast(_beginthreadex(nullptr, 0, &ThreadImpl::ThreadProc, functor, 0, nullptr)); + unsigned int threadId; + m_handle = reinterpret_cast(_beginthreadex(nullptr, 0, &ThreadImpl::ThreadProc, functor, 0, &threadId)); if (!m_handle) NazaraInternalError("Failed to create thread: " + Error::GetLastSystemError()); + + m_threadId = threadId; } void ThreadImpl::Detach() @@ -29,6 +46,44 @@ namespace Nz CloseHandle(m_handle); } + void ThreadImpl::SetName(const Nz::String& name) + { + SetThreadName(m_threadId, name.GetConstBuffer()); + } + + void ThreadImpl::SetCurrentName(const Nz::String& name) + { + SetThreadName(::GetCurrentThreadId(), name.GetConstBuffer()); + } + + void ThreadImpl::Sleep(UInt32 time) + { + ::Sleep(time); + } + + void ThreadImpl::SetThreadName(DWORD threadId, const char* threadName) + { + // https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx + constexpr DWORD MS_VC_EXCEPTION = 0x406D1388; + + THREADNAME_INFO info; + info.dwType = 0x1000; + info.szName = threadName; + info.dwThreadID = threadId; + info.dwFlags = 0; + +#pragma warning(push) +#pragma warning(disable: 6320 6322) + __try + { + RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), reinterpret_cast(&info)); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + } +#pragma warning(pop) + } + unsigned int __stdcall ThreadImpl::ThreadProc(void* userdata) { Functor* func = static_cast(userdata); @@ -42,9 +97,4 @@ namespace Nz return 0; } - - void ThreadImpl::Sleep(UInt32 time) - { - ::Sleep(time); - } } diff --git a/src/Nazara/Core/Win32/ThreadImpl.hpp b/src/Nazara/Core/Win32/ThreadImpl.hpp index 12e7f5c14..8070f7a22 100644 --- a/src/Nazara/Core/Win32/ThreadImpl.hpp +++ b/src/Nazara/Core/Win32/ThreadImpl.hpp @@ -10,6 +10,7 @@ #define NAZARA_THREADIMPL_HPP #include +#include #include namespace Nz @@ -23,12 +24,16 @@ namespace Nz void Detach(); void Join(); + void SetName(const Nz::String& name); + static void SetCurrentName(const Nz::String& name); static void Sleep(UInt32 time); private: + static void SetThreadName(DWORD threadId, const char* threadName); static unsigned int __stdcall ThreadProc(void* userdata); + DWORD m_threadId; HANDLE m_handle; }; } diff --git a/src/Nazara/Graphics/AbstractRenderTechnique.cpp b/src/Nazara/Graphics/AbstractRenderTechnique.cpp index 8a33b7b46..963582d45 100644 --- a/src/Nazara/Graphics/AbstractRenderTechnique.cpp +++ b/src/Nazara/Graphics/AbstractRenderTechnique.cpp @@ -3,9 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/Billboard.cpp b/src/Nazara/Graphics/Billboard.cpp index 045a77ece..e228a2a59 100644 --- a/src/Nazara/Graphics/Billboard.cpp +++ b/src/Nazara/Graphics/Billboard.cpp @@ -4,10 +4,6 @@ #include #include -#include -#include -#include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/ColorBackground.cpp b/src/Nazara/Graphics/ColorBackground.cpp index 52653a8e7..6004783ac 100644 --- a/src/Nazara/Graphics/ColorBackground.cpp +++ b/src/Nazara/Graphics/ColorBackground.cpp @@ -3,8 +3,10 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include +#include #include -#include +#include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/DeferredBloomPass.cpp b/src/Nazara/Graphics/DeferredBloomPass.cpp index e51543641..380bf532d 100644 --- a/src/Nazara/Graphics/DeferredBloomPass.cpp +++ b/src/Nazara/Graphics/DeferredBloomPass.cpp @@ -4,7 +4,6 @@ #include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/DeferredDOFPass.cpp b/src/Nazara/Graphics/DeferredDOFPass.cpp index 9760ff300..1aebdcaa6 100644 --- a/src/Nazara/Graphics/DeferredDOFPass.cpp +++ b/src/Nazara/Graphics/DeferredDOFPass.cpp @@ -3,10 +3,8 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/DeferredFXAAPass.cpp b/src/Nazara/Graphics/DeferredFXAAPass.cpp index fa2d80d46..91174aaa7 100644 --- a/src/Nazara/Graphics/DeferredFXAAPass.cpp +++ b/src/Nazara/Graphics/DeferredFXAAPass.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/DeferredFinalPass.cpp b/src/Nazara/Graphics/DeferredFinalPass.cpp index 228e9d035..265989233 100644 --- a/src/Nazara/Graphics/DeferredFinalPass.cpp +++ b/src/Nazara/Graphics/DeferredFinalPass.cpp @@ -3,9 +3,12 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include +#include #include +#include #include -#include +#include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/DeferredFogPass.cpp b/src/Nazara/Graphics/DeferredFogPass.cpp index c6fbfddf9..77432f6d2 100644 --- a/src/Nazara/Graphics/DeferredFogPass.cpp +++ b/src/Nazara/Graphics/DeferredFogPass.cpp @@ -4,9 +4,9 @@ #include #include +#include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/DeferredForwardPass.cpp b/src/Nazara/Graphics/DeferredForwardPass.cpp index 55780708f..e4685d3ae 100644 --- a/src/Nazara/Graphics/DeferredForwardPass.cpp +++ b/src/Nazara/Graphics/DeferredForwardPass.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include diff --git a/src/Nazara/Graphics/DeferredGeometryPass.cpp b/src/Nazara/Graphics/DeferredGeometryPass.cpp index 6d5883c48..b679c873a 100644 --- a/src/Nazara/Graphics/DeferredGeometryPass.cpp +++ b/src/Nazara/Graphics/DeferredGeometryPass.cpp @@ -8,12 +8,9 @@ #include #include #include +#include #include #include -#include -#include -#include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/DeferredPhongLightingPass.cpp b/src/Nazara/Graphics/DeferredPhongLightingPass.cpp index 2eff9abc9..3902c9d9d 100644 --- a/src/Nazara/Graphics/DeferredPhongLightingPass.cpp +++ b/src/Nazara/Graphics/DeferredPhongLightingPass.cpp @@ -3,12 +3,13 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include +#include #include #include +#include #include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/DeferredRenderPass.cpp b/src/Nazara/Graphics/DeferredRenderPass.cpp index c4c265b58..8b0b7fde5 100644 --- a/src/Nazara/Graphics/DeferredRenderPass.cpp +++ b/src/Nazara/Graphics/DeferredRenderPass.cpp @@ -3,8 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include +#include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/DeferredRenderQueue.cpp b/src/Nazara/Graphics/DeferredRenderQueue.cpp index a0455fe11..76bc666be 100644 --- a/src/Nazara/Graphics/DeferredRenderQueue.cpp +++ b/src/Nazara/Graphics/DeferredRenderQueue.cpp @@ -3,9 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include -#include #include ///TODO: Render billboards using Deferred Shading if possible diff --git a/src/Nazara/Graphics/DeferredRenderTechnique.cpp b/src/Nazara/Graphics/DeferredRenderTechnique.cpp index 01a0d1fa8..f930871fe 100644 --- a/src/Nazara/Graphics/DeferredRenderTechnique.cpp +++ b/src/Nazara/Graphics/DeferredRenderTechnique.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -18,18 +17,13 @@ #include #include #include -#include -#include -#include -#include +#include #include #include #include #include #include -#include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/DepthRenderQueue.cpp b/src/Nazara/Graphics/DepthRenderQueue.cpp index a2acdf4bb..775276c37 100644 --- a/src/Nazara/Graphics/DepthRenderQueue.cpp +++ b/src/Nazara/Graphics/DepthRenderQueue.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/DepthRenderTechnique.cpp b/src/Nazara/Graphics/DepthRenderTechnique.cpp index 4acbbc56d..c58b4e4ee 100644 --- a/src/Nazara/Graphics/DepthRenderTechnique.cpp +++ b/src/Nazara/Graphics/DepthRenderTechnique.cpp @@ -5,19 +5,14 @@ #include #include #include -#include -#include #include -#include #include -#include +#include #include #include #include -#include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/Formats/MeshLoader.cpp b/src/Nazara/Graphics/Formats/MeshLoader.cpp index 1f9f340da..439039cad 100644 --- a/src/Nazara/Graphics/Formats/MeshLoader.cpp +++ b/src/Nazara/Graphics/Formats/MeshLoader.cpp @@ -3,13 +3,11 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/Formats/TextureLoader.cpp b/src/Nazara/Graphics/Formats/TextureLoader.cpp index d3667a945..02f51d5ad 100644 --- a/src/Nazara/Graphics/Formats/TextureLoader.cpp +++ b/src/Nazara/Graphics/Formats/TextureLoader.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/ForwardRenderQueue.cpp b/src/Nazara/Graphics/ForwardRenderQueue.cpp index ba8c68358..d55901de0 100644 --- a/src/Nazara/Graphics/ForwardRenderQueue.cpp +++ b/src/Nazara/Graphics/ForwardRenderQueue.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include ///TODO: Replace sinus/cosinus by a lookup table (which will lead to a speed up about 10x) @@ -697,7 +697,7 @@ namespace Nz auto it = layers.find(i); if (it == layers.end()) it = layers.insert(std::make_pair(i, Layer())).first; - + Layer& layer = it->second; layer.clearCount = 0; @@ -729,7 +729,6 @@ namespace Nz void ForwardRenderQueue::SortForOrthographic(const AbstractViewer * viewer) { Planef nearPlane = viewer->GetFrustum().GetPlane(FrustumPlane_Near); - Vector3f viewerPos = viewer->GetEyePosition(); for (auto& pair : layers) { diff --git a/src/Nazara/Graphics/ForwardRenderTechnique.cpp b/src/Nazara/Graphics/ForwardRenderTechnique.cpp index 028af936f..99452eaa1 100644 --- a/src/Nazara/Graphics/ForwardRenderTechnique.cpp +++ b/src/Nazara/Graphics/ForwardRenderTechnique.cpp @@ -10,14 +10,12 @@ #include #include #include -#include +#include #include #include #include -#include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/Graphics.cpp b/src/Nazara/Graphics/Graphics.cpp index e1b202716..5ae1d8554 100644 --- a/src/Nazara/Graphics/Graphics.cpp +++ b/src/Nazara/Graphics/Graphics.cpp @@ -173,7 +173,7 @@ namespace Nz } /*! - * \brief Uninitializes the Core module + * \brief Uninitializes the Graphics module * * \remark Produces a NazaraNotice */ diff --git a/src/Nazara/Graphics/GuillotineTextureAtlas.cpp b/src/Nazara/Graphics/GuillotineTextureAtlas.cpp index 0699b7fcf..16ae46be4 100644 --- a/src/Nazara/Graphics/GuillotineTextureAtlas.cpp +++ b/src/Nazara/Graphics/GuillotineTextureAtlas.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include diff --git a/src/Nazara/Graphics/Light.cpp b/src/Nazara/Graphics/Light.cpp index a2b188006..c891204a7 100644 --- a/src/Nazara/Graphics/Light.cpp +++ b/src/Nazara/Graphics/Light.cpp @@ -8,9 +8,6 @@ #include #include #include -#include -#include -#include #include ///TODO: Use of UBOs diff --git a/src/Nazara/Graphics/Material.cpp b/src/Nazara/Graphics/Material.cpp index 0e865038a..b7f2aeabe 100644 --- a/src/Nazara/Graphics/Material.cpp +++ b/src/Nazara/Graphics/Material.cpp @@ -5,8 +5,7 @@ #include #include #include -#include -#include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/ParticleDeclaration.cpp b/src/Nazara/Graphics/ParticleDeclaration.cpp index 63b329aa4..a9a8e983d 100644 --- a/src/Nazara/Graphics/ParticleDeclaration.cpp +++ b/src/Nazara/Graphics/ParticleDeclaration.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -10,7 +10,6 @@ #include #include #include -#include #include namespace Nz @@ -287,7 +286,7 @@ namespace Nz // ParticleLayout_Billboard : ParticleStruct_Billboard declaration = &s_declarations[ParticleLayout_Billboard]; declaration->EnableComponent(ParticleComponent_Color, ComponentType_Color, NazaraOffsetOf(ParticleStruct_Billboard, color)); - declaration->EnableComponent(ParticleComponent_Life, ComponentType_Int1, NazaraOffsetOf(ParticleStruct_Billboard, life)); + declaration->EnableComponent(ParticleComponent_Life, ComponentType_Float1, NazaraOffsetOf(ParticleStruct_Billboard, life)); declaration->EnableComponent(ParticleComponent_Normal, ComponentType_Float3, NazaraOffsetOf(ParticleStruct_Billboard, normal)); declaration->EnableComponent(ParticleComponent_Position, ComponentType_Float3, NazaraOffsetOf(ParticleStruct_Billboard, position)); declaration->EnableComponent(ParticleComponent_Rotation, ComponentType_Float1, NazaraOffsetOf(ParticleStruct_Billboard, rotation)); @@ -298,7 +297,7 @@ namespace Nz // ParticleLayout_Model : ParticleStruct_Model declaration = &s_declarations[ParticleLayout_Model]; - declaration->EnableComponent(ParticleComponent_Life, ComponentType_Int1, NazaraOffsetOf(ParticleStruct_Model, life)); + declaration->EnableComponent(ParticleComponent_Life, ComponentType_Float1, NazaraOffsetOf(ParticleStruct_Model, life)); declaration->EnableComponent(ParticleComponent_Position, ComponentType_Float3, NazaraOffsetOf(ParticleStruct_Model, position)); declaration->EnableComponent(ParticleComponent_Rotation, ComponentType_Quaternion, NazaraOffsetOf(ParticleStruct_Model, rotation)); declaration->EnableComponent(ParticleComponent_Velocity, ComponentType_Float3, NazaraOffsetOf(ParticleStruct_Model, velocity)); @@ -308,7 +307,7 @@ namespace Nz // ParticleLayout_Sprite : ParticleStruct_Sprite declaration = &s_declarations[ParticleLayout_Sprite]; declaration->EnableComponent(ParticleComponent_Color, ComponentType_Color, NazaraOffsetOf(ParticleStruct_Sprite, color)); - declaration->EnableComponent(ParticleComponent_Life, ComponentType_Int1, NazaraOffsetOf(ParticleStruct_Sprite, life)); + declaration->EnableComponent(ParticleComponent_Life, ComponentType_Float1, NazaraOffsetOf(ParticleStruct_Sprite, life)); declaration->EnableComponent(ParticleComponent_Position, ComponentType_Float3, NazaraOffsetOf(ParticleStruct_Sprite, position)); declaration->EnableComponent(ParticleComponent_Rotation, ComponentType_Float1, NazaraOffsetOf(ParticleStruct_Sprite, rotation)); declaration->EnableComponent(ParticleComponent_Velocity, ComponentType_Float3, NazaraOffsetOf(ParticleStruct_Sprite, velocity)); diff --git a/src/Nazara/Graphics/ParticleEmitter.cpp b/src/Nazara/Graphics/ParticleEmitter.cpp index 89811dd53..fe1b17e82 100644 --- a/src/Nazara/Graphics/ParticleEmitter.cpp +++ b/src/Nazara/Graphics/ParticleEmitter.cpp @@ -3,13 +3,8 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include -#include #include #include -#include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/ParticleGroup.cpp b/src/Nazara/Graphics/ParticleGroup.cpp index 34a46089b..0bad010a4 100644 --- a/src/Nazara/Graphics/ParticleGroup.cpp +++ b/src/Nazara/Graphics/ParticleGroup.cpp @@ -7,8 +7,6 @@ #include #include #include -#include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/ParticleMapper.cpp b/src/Nazara/Graphics/ParticleMapper.cpp index 05932abaa..ef48e8c14 100644 --- a/src/Nazara/Graphics/ParticleMapper.cpp +++ b/src/Nazara/Graphics/ParticleMapper.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/SkeletalModel.cpp b/src/Nazara/Graphics/SkeletalModel.cpp index 505c628ef..433a748f6 100644 --- a/src/Nazara/Graphics/SkeletalModel.cpp +++ b/src/Nazara/Graphics/SkeletalModel.cpp @@ -6,8 +6,8 @@ #include #include #include -#include #include +#include #include #include #include diff --git a/src/Nazara/Graphics/SkinningManager.cpp b/src/Nazara/Graphics/SkinningManager.cpp index 3472238b9..6460a1f1c 100644 --- a/src/Nazara/Graphics/SkinningManager.cpp +++ b/src/Nazara/Graphics/SkinningManager.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -6,10 +6,11 @@ #include #include #include +#include +#include #include +#include #include -#include -#include #include #include diff --git a/src/Nazara/Graphics/SkyboxBackground.cpp b/src/Nazara/Graphics/SkyboxBackground.cpp index 58c1c7371..85fe3559b 100644 --- a/src/Nazara/Graphics/SkyboxBackground.cpp +++ b/src/Nazara/Graphics/SkyboxBackground.cpp @@ -6,10 +6,11 @@ #include #include #include +#include +#include #include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Graphics/Sprite.cpp b/src/Nazara/Graphics/Sprite.cpp index 09350554e..5d51a1ae1 100644 --- a/src/Nazara/Graphics/Sprite.cpp +++ b/src/Nazara/Graphics/Sprite.cpp @@ -4,9 +4,7 @@ #include #include -#include -#include -#include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/TextSprite.cpp b/src/Nazara/Graphics/TextSprite.cpp index def62fba5..3d82037d4 100644 --- a/src/Nazara/Graphics/TextSprite.cpp +++ b/src/Nazara/Graphics/TextSprite.cpp @@ -6,9 +6,9 @@ #include #include #include -#include -#include +#include #include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/TextureBackground.cpp b/src/Nazara/Graphics/TextureBackground.cpp index cd6c68c05..25de25d9e 100644 --- a/src/Nazara/Graphics/TextureBackground.cpp +++ b/src/Nazara/Graphics/TextureBackground.cpp @@ -4,7 +4,8 @@ #include #include -#include +#include +#include #include namespace Nz diff --git a/src/Nazara/Graphics/TileMap.cpp b/src/Nazara/Graphics/TileMap.cpp index 1f4676de7..192341472 100644 --- a/src/Nazara/Graphics/TileMap.cpp +++ b/src/Nazara/Graphics/TileMap.cpp @@ -4,10 +4,8 @@ #include #include -#include #include -#include -#include +#include #include namespace Nz diff --git a/src/Nazara/Lua/LuaCoroutine.cpp b/src/Nazara/Lua/LuaCoroutine.cpp index 197244134..bccf8d7fc 100644 --- a/src/Nazara/Lua/LuaCoroutine.cpp +++ b/src/Nazara/Lua/LuaCoroutine.cpp @@ -3,9 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include -#include #include #include diff --git a/src/Nazara/Lua/LuaInstance.cpp b/src/Nazara/Lua/LuaInstance.cpp index cd47ac5c7..366ccab27 100644 --- a/src/Nazara/Lua/LuaInstance.cpp +++ b/src/Nazara/Lua/LuaInstance.cpp @@ -8,14 +8,9 @@ #include #include #include -#include -#include -#include -#include #include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Lua/LuaState.cpp b/src/Nazara/Lua/LuaState.cpp index 94170aee0..67bf8efa0 100644 --- a/src/Nazara/Lua/LuaState.cpp +++ b/src/Nazara/Lua/LuaState.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -14,9 +13,6 @@ #include #include #include -#include -#include -#include #include namespace Nz @@ -126,12 +122,6 @@ namespace Nz static_assert(sizeof(s_types)/sizeof(int) == LuaType_Max+1, "Lua type array is incomplete"); } - LuaState::LuaState(LuaState&& state) noexcept : - m_lastError(state.m_lastError), - m_state(state.m_state) - { - } - void LuaState::ArgCheck(bool condition, unsigned int argNum, const char* error) const { luaL_argcheck(m_state, condition, argNum, error); @@ -373,7 +363,7 @@ namespace Nz return false; } - return Run(0, 0); + return Run(0, LUA_MULTRET); } bool LuaState::ExecuteFromFile(const String& filePath) @@ -419,7 +409,7 @@ namespace Nz return false; } - return Run(0, 0); + return Run(0, LUA_MULTRET); } int LuaState::GetAbsIndex(int index) const @@ -789,14 +779,6 @@ namespace Nz return luaL_testudata(m_state, index, tname.GetConstBuffer()); } - LuaState& LuaState::operator=(LuaState&& state) noexcept - { - m_lastError = std::move(state.m_lastError); - m_state = state.m_state; - - return *this; - } - bool LuaState::Run(int argCount, int resultCount) { LuaInstance& instance = GetInstance(m_state); diff --git a/src/Nazara/Network/AbstractSocket.cpp b/src/Nazara/Network/AbstractSocket.cpp index 3b3d9cb56..b070a93cb 100644 --- a/src/Nazara/Network/AbstractSocket.cpp +++ b/src/Nazara/Network/AbstractSocket.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #if defined(NAZARA_PLATFORM_WINDOWS) diff --git a/src/Nazara/Network/ENetCompressor.cpp b/src/Nazara/Network/ENetCompressor.cpp new file mode 100644 index 000000000..373389ecc --- /dev/null +++ b/src/Nazara/Network/ENetCompressor.cpp @@ -0,0 +1,11 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Network module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include + +namespace Nz +{ + ENetCompressor::~ENetCompressor() = default; +} diff --git a/src/Nazara/Network/ENetHost.cpp b/src/Nazara/Network/ENetHost.cpp index 5850d4ab7..f86b2289f 100644 --- a/src/Nazara/Network/ENetHost.cpp +++ b/src/Nazara/Network/ENetHost.cpp @@ -86,7 +86,7 @@ namespace Nz return nullptr; } - m_channelLimit = Clamp(channelCount, ENetConstants::ENetProtocol_MinimumChannelCount, ENetConstants::ENetProtocol_MaximumChannelCount); + channelCount = Clamp(channelCount, ENetConstants::ENetProtocol_MinimumChannelCount, ENetConstants::ENetProtocol_MaximumChannelCount); UInt32 windowSize; if (m_outgoingBandwidth == 0) @@ -128,24 +128,29 @@ namespace Nz if (!result.address) continue; - if (result.socketType != SocketType_UDP) - continue; - hostnameAddress = result.address; break; //< Take first valid address } + if (!hostnameAddress.IsValid()) + { + if (error) + *error = ResolveError_NotFound; + + return nullptr; + } + return Connect(hostnameAddress, channelCount, data); } - bool ENetHost::Create(const IpAddress& address, std::size_t peerCount, std::size_t channelCount) + bool ENetHost::Create(const IpAddress& listenAddress, std::size_t peerCount, std::size_t channelCount) { - return Create(address, peerCount, channelCount, 0, 0); + return Create(listenAddress, peerCount, channelCount, 0, 0); } - bool ENetHost::Create(const IpAddress& address, std::size_t peerCount, std::size_t channelCount, UInt32 incomingBandwidth, UInt32 outgoingBandwidth) + bool ENetHost::Create(const IpAddress& listenAddress, std::size_t peerCount, std::size_t channelCount, UInt32 incomingBandwidth, UInt32 outgoingBandwidth) { - NazaraAssert(address.IsValid(), "Invalid listening address"); + NazaraAssert(listenAddress.IsValid(), "Invalid listening address"); if (peerCount > ENetConstants::ENetProtocol_MaximumPeerId) { @@ -153,10 +158,11 @@ namespace Nz return false; } - if (!InitSocket(address)) + if (!InitSocket(listenAddress)) return false; - m_address = address; + m_address = listenAddress; + m_allowsIncomingConnections = (listenAddress.IsValid() && !listenAddress.IsLoopback()); m_randomSeed = *reinterpret_cast(this); m_randomSeed += s_randomGenerator(); m_randomSeed = (m_randomSeed << 16) | (m_randomSeed >> 16); @@ -231,6 +237,10 @@ namespace Nz break; } + // Receiving on an unbound socket which has never sent data is an invalid operation + if (!m_allowsIncomingConnections && m_totalSentData == 0) + return 0; + switch (ReceiveIncomingCommands(event)) { case 1: @@ -318,7 +328,7 @@ namespace Nz m_socket.SetReceiveBufferSize(ENetConstants::ENetHost_ReceiveBufferSize); m_socket.SetSendBufferSize(ENetConstants::ENetHost_SendBufferSize); - if (!address.IsLoopback()) + if (address.IsValid() && !address.IsLoopback()) { if (m_socket.Bind(address) != SocketState_Bound) { @@ -402,6 +412,9 @@ namespace Nz ENetPeer* ENetHost::HandleConnect(ENetProtocolHeader* /*header*/, ENetProtocol* command) { + if (!m_allowsIncomingConnections) + return nullptr; + UInt32 channelCount = NetToHost(command->connect.channelCount); if (channelCount < ENetProtocol_MinimumChannelCount || channelCount > ENetProtocol_MaximumChannelCount) @@ -508,6 +521,19 @@ namespace Nz } // Compression handling + if (flags & ENetProtocolHeaderFlag_Compressed) + { + if (!m_compressor) + return false; + + std::size_t newSize = m_compressor->Decompress(peer, m_receivedData, m_receivedDataLength, m_packetData[1].data() + headerSize, m_packetData[1].size() - headerSize); + if (newSize == 0 || newSize > m_packetData[1].size() - headerSize) + return false; + + std::memcpy(m_packetData[1].data(), header, headerSize); + m_receivedData = m_packetData[1].data(); + m_receivedDataLength = headerSize + newSize; + } // Checksum @@ -868,8 +894,6 @@ namespace Nz break; } - ++currentCommand; - if (channel && outgoingCommand->sendAttempts < 1) { channel->usedReliableWindows |= 1 << reliableWindow; @@ -888,7 +912,7 @@ namespace Nz peer->m_nextTimeout = m_serviceTime + outgoingCommand->roundTripTimeout; peer->m_sentReliableCommands.emplace_back(std::move(*outgoingCommand)); - peer->m_outgoingReliableCommands.erase(outgoingCommand); + currentCommand = peer->m_outgoingReliableCommands.erase(outgoingCommand); outgoingCommand = peer->m_sentReliableCommands.end(); --outgoingCommand; @@ -911,7 +935,7 @@ namespace Nz ++m_bufferCount; NetBuffer& packetBuffer = m_buffers[m_bufferCount]; - packetBuffer.data = outgoingCommand->packet->data.GetData() + Nz::NetPacket::HeaderSize + outgoingCommand->fragmentOffset; + packetBuffer.data = outgoingCommand->packet->data.GetData() + NetPacket::HeaderSize + outgoingCommand->fragmentOffset; packetBuffer.dataLength = outgoingCommand->fragmentLength; m_packetSize += packetBuffer.dataLength; @@ -1013,11 +1037,27 @@ namespace Nz else m_buffers[0].dataLength = NazaraOffsetOf(ENetProtocolHeader, sentTime); + // Compress packet buffers if possible + std::size_t compressedSize = 0; + if (m_compressor) + { + compressedSize = m_compressor->Compress(currentPeer, &m_buffers[1], m_bufferCount, m_packetSize - sizeof(ENetProtocolHeader), m_packetData[1].data(), m_packetData[1].size()); + if (compressedSize > 0) + m_headerFlags |= ENetProtocolHeaderFlag_Compressed; + } + if (currentPeer->m_outgoingPeerID < ENetConstants::ENetProtocol_MaximumPeerId) m_headerFlags |= currentPeer->m_outgoingSessionID << ENetProtocolHeaderSessionShift; header->peerID = HostToNet(static_cast(currentPeer->m_outgoingPeerID | m_headerFlags)); + if (compressedSize > 0) + { + m_buffers[1].data = m_packetData[1].data(); + m_buffers[1].dataLength = compressedSize; + m_bufferCount = 2; + } + currentPeer->m_lastSendTime = m_serviceTime; // Simulate network by adding delay to packet sending and losing some packets @@ -1027,7 +1067,7 @@ namespace Nz sendNow = false; if (!currentPeer->m_packetLossProbability(s_randomGenerator)) { - Nz::UInt16 delay = currentPeer->m_packetDelayDistribution(s_randomGenerator); + UInt16 delay = currentPeer->m_packetDelayDistribution(s_randomGenerator); if (delay == 0) sendNow = true; else @@ -1148,7 +1188,7 @@ namespace Nz ++m_bufferCount; NetBuffer& packetBuffer = m_buffers[m_bufferCount]; - packetBuffer.data = outgoingCommand->packet->data.GetData() + Nz::NetPacket::HeaderSize + outgoingCommand->fragmentOffset; + packetBuffer.data = outgoingCommand->packet->data.GetData() + NetPacket::HeaderSize + outgoingCommand->fragmentOffset; packetBuffer.dataLength = outgoingCommand->fragmentLength; m_packetSize += packetBuffer.dataLength; diff --git a/src/Nazara/Network/ENetPeer.cpp b/src/Nazara/Network/ENetPeer.cpp index cbae37148..80e46a36b 100644 --- a/src/Nazara/Network/ENetPeer.cpp +++ b/src/Nazara/Network/ENetPeer.cpp @@ -139,7 +139,7 @@ namespace Nz m_packetsLost = 0; m_packetLoss = 0; m_packetLossVariance = 0; - m_packetThrottle = ENetConstants::ENetProtocol_MaximumWindowSize; + m_packetThrottle = ENetConstants::ENetPeer_DefaultPacketThrottle; m_packetThrottleLimit = ENetConstants::ENetPeer_PacketThrottleScale; m_packetThrottleCounter = 0; m_packetThrottleEpoch = 0; @@ -1330,7 +1330,7 @@ namespace Nz { if (rtt < m_lastRoundTripTime) { - m_packetThrottle = std::max(m_packetThrottle + m_packetThrottleAcceleration, m_packetThrottleLimit); + m_packetThrottle = std::min(m_packetThrottle + m_packetThrottleAcceleration, m_packetThrottleLimit); return 1; } else if (rtt > m_lastRoundTripTime + 2 * m_lastRoundTripTimeVariance) diff --git a/src/Nazara/Network/IpAddress.cpp b/src/Nazara/Network/IpAddress.cpp index fc63be189..aee2550f3 100644 --- a/src/Nazara/Network/IpAddress.cpp +++ b/src/Nazara/Network/IpAddress.cpp @@ -8,7 +8,6 @@ #include #include #include -#include #if defined(NAZARA_PLATFORM_WINDOWS) #include diff --git a/src/Nazara/Network/Linux/SocketPollerImpl.cpp b/src/Nazara/Network/Linux/SocketPollerImpl.cpp index 6617efd37..6e902a587 100644 --- a/src/Nazara/Network/Linux/SocketPollerImpl.cpp +++ b/src/Nazara/Network/Linux/SocketPollerImpl.cpp @@ -80,7 +80,7 @@ namespace Nz NazaraWarning("An error occured while removing socket from epoll structure (errno " + String::Number(errno) + ": " + Error::GetLastSystemError() + ')'); } - int SocketPollerImpl::Wait(UInt64 msTimeout, SocketError* error) + int SocketPollerImpl::Wait(int msTimeout, SocketError* error) { int activeSockets; diff --git a/src/Nazara/Network/Linux/SocketPollerImpl.hpp b/src/Nazara/Network/Linux/SocketPollerImpl.hpp index a804102fa..882141d38 100644 --- a/src/Nazara/Network/Linux/SocketPollerImpl.hpp +++ b/src/Nazara/Network/Linux/SocketPollerImpl.hpp @@ -30,7 +30,7 @@ namespace Nz bool RegisterSocket(SocketHandle socket, SocketPollEventFlags eventFlags); void UnregisterSocket(SocketHandle socket); - int Wait(UInt64 msTimeout, SocketError* error); + int Wait(int msTimeout, SocketError* error); private: std::unordered_set m_readyToReadSockets; diff --git a/src/Nazara/Network/Network.cpp b/src/Nazara/Network/Network.cpp index 57ddfd83b..392b196b6 100644 --- a/src/Nazara/Network/Network.cpp +++ b/src/Nazara/Network/Network.cpp @@ -10,7 +10,6 @@ #include #include #include -#include #if defined(NAZARA_PLATFORM_WINDOWS) #include diff --git a/src/Nazara/Network/Posix/SocketImpl.cpp b/src/Nazara/Network/Posix/SocketImpl.cpp index be6f84581..3a2c8e81f 100644 --- a/src/Nazara/Network/Posix/SocketImpl.cpp +++ b/src/Nazara/Network/Posix/SocketImpl.cpp @@ -4,8 +4,8 @@ #include #include -#include #include +#include #include #include #include @@ -509,12 +509,12 @@ namespace Nz NazaraAssert(buffer && length > 0, "Invalid buffer"); IpAddressImpl::SockAddrBuffer nameBuffer; - socklen_t bufferLength = sizeof(sockaddr_in); + socklen_t bufferLength = static_cast(nameBuffer.size()); IpAddress senderIp; int byteRead = recvfrom(handle, buffer, length, 0, reinterpret_cast(&nameBuffer), &bufferLength); - if (byteRead == SOCKET_ERROR) + if (byteRead == -1) { int errorCode = GetLastErrorCode(); if (errorCode == EAGAIN) @@ -549,6 +549,92 @@ namespace Nz else // else we received something senderIp = IpAddressImpl::FromSockAddr(reinterpret_cast(&nameBuffer)); + if (from) + *from = IpAddressImpl::FromSockAddr(reinterpret_cast(&nameBuffer)); + + if (read) + *read = byteRead; + + if (error) + *error = SocketError_NoError; + + return true; + } + + bool SocketImpl::ReceiveMultiple(SocketHandle handle, NetBuffer* buffers, std::size_t bufferCount, IpAddress* from, int* read, SocketError* error) + { + NazaraAssert(handle != InvalidHandle, "Invalid handle"); + NazaraAssert(buffers && bufferCount > 0, "Invalid buffers"); + + StackAllocation memory = NazaraStackAllocation(bufferCount * sizeof(iovec)); + struct iovec* sysBuffers = static_cast(memory.GetPtr()); + for (std::size_t i = 0; i < bufferCount; ++i) + { + sysBuffers[i].iov_base = buffers[i].data; + sysBuffers[i].iov_len = buffers[i].dataLength; + } + + struct msghdr msgHdr; + std::memset(&msgHdr, 0, sizeof(msgHdr)); + + msgHdr.msg_iov = sysBuffers; + msgHdr.msg_iovlen = static_cast(bufferCount); + + IpAddressImpl::SockAddrBuffer nameBuffer; + if (from) + { + msgHdr.msg_name = nameBuffer.data(); + msgHdr.msg_namelen = static_cast(nameBuffer.size()); + } + + IpAddress senderIp; + + int byteRead = recvmsg(handle, &msgHdr, MSG_NOSIGNAL); + if (byteRead == -1) + { + int errorCode = GetLastErrorCode(); + if (errorCode == EAGAIN) + errorCode = EWOULDBLOCK; + + switch (errorCode) + { + case EWOULDBLOCK: + { + // If we have no data and are not blocking, return true with 0 byte read + byteRead = 0; + senderIp = IpAddress::Invalid; + break; + } + + default: + { + if (error) + *error = TranslateErrnoToResolveError(errorCode); + + return false; //< Error + } + } + } + else if (byteRead == 0) + { + if (error) + *error = SocketError_ConnectionClosed; + + return false; //< Connection closed + } + else // else we received something + senderIp = IpAddressImpl::FromSockAddr(reinterpret_cast(nameBuffer.data())); + +#ifdef HAS_MSGHDR_FLAGS + if (msgHdr.msg_flags & MSG_TRUNC) + { + if (error) + *error = SocketError_DatagramSize; + + return false; + } +#endif + if (from) *from = senderIp; diff --git a/src/Nazara/Network/Posix/SocketImpl.hpp b/src/Nazara/Network/Posix/SocketImpl.hpp index 7ee2e24f6..e9f094cc3 100644 --- a/src/Nazara/Network/Posix/SocketImpl.hpp +++ b/src/Nazara/Network/Posix/SocketImpl.hpp @@ -10,12 +10,13 @@ #include #include #include -#include #define NAZARA_NETWORK_POLL_SUPPORT 1 namespace Nz { + struct NetBuffer; + struct PollSocket { SocketHandle fd; @@ -63,6 +64,7 @@ namespace Nz static bool Receive(SocketHandle handle, void* buffer, int length, int* read, SocketError* error); static bool ReceiveFrom(SocketHandle handle, void* buffer, int length, IpAddress* from, int* read, SocketError* error); + static bool ReceiveMultiple(SocketHandle handle, NetBuffer* buffers, std::size_t bufferCount, IpAddress* from, int* read, SocketError* error); static bool Send(SocketHandle handle, const void* buffer, int length, int* sent, SocketError* error); static bool SendMultiple(SocketHandle handle, const NetBuffer* buffers, std::size_t bufferCount, const IpAddress& to, int* sent, SocketError* error); diff --git a/src/Nazara/Network/Posix/SocketPollerImpl.cpp b/src/Nazara/Network/Posix/SocketPollerImpl.cpp index 59b8a8ca7..ed391c6f3 100644 --- a/src/Nazara/Network/Posix/SocketPollerImpl.cpp +++ b/src/Nazara/Network/Posix/SocketPollerImpl.cpp @@ -76,7 +76,7 @@ namespace Nz m_readyToWriteSockets.erase(socket); } - int SocketPollerImpl::Wait(UInt64 msTimeout, SocketError* error) + int SocketPollerImpl::Wait(int msTimeout, SocketError* error) { int activeSockets; diff --git a/src/Nazara/Network/Posix/SocketPollerImpl.hpp b/src/Nazara/Network/Posix/SocketPollerImpl.hpp index 3582121d4..5c4ad1743 100644 --- a/src/Nazara/Network/Posix/SocketPollerImpl.hpp +++ b/src/Nazara/Network/Posix/SocketPollerImpl.hpp @@ -7,7 +7,6 @@ #ifndef NAZARA_SOCKETPOLLERIMPL_HPP #define NAZARA_SOCKETPOLLERIMPL_HPP -#include #include #include #include @@ -30,7 +29,7 @@ namespace Nz bool RegisterSocket(SocketHandle socket, SocketPollEventFlags eventFlags); void UnregisterSocket(SocketHandle socket); - int Wait(UInt64 msTimeout, SocketError* error); + int Wait(int msTimeout, SocketError* error); private: std::unordered_set m_readyToReadSockets; diff --git a/src/Nazara/Network/RUdpConnection.cpp b/src/Nazara/Network/RUdpConnection.cpp index f704b9568..3667eb113 100644 --- a/src/Nazara/Network/RUdpConnection.cpp +++ b/src/Nazara/Network/RUdpConnection.cpp @@ -527,7 +527,7 @@ namespace Nz } else { - NazaraNotice("Received wrong token (" + String::Number(token) + " instead of " + String::Number(~peer.stateData1) + ") from client " + peer.address); + NazaraNotice("Received wrong token (" + String::Number(token) + " instead of " + String::Number(~peer.stateData1) + ") from client " + peer.address.ToString()); return; //< Ignore } diff --git a/src/Nazara/Network/SocketPoller.cpp b/src/Nazara/Network/SocketPoller.cpp index 7ef261ef9..50eeb5cdf 100644 --- a/src/Nazara/Network/SocketPoller.cpp +++ b/src/Nazara/Network/SocketPoller.cpp @@ -170,7 +170,7 @@ namespace Nz * Waits a specific/undetermined amount of time until at least one socket part of the SocketPoller becomes ready. * To query the ready state of the registered socket, use the IsReadyToRead or IsReadyToWrite functions. * - * \param msTimeout Maximum time to wait in milliseconds, 0 for infinity + * \param msTimeout Maximum time to wait in milliseconds, 0 will returns immediately and -1 will block indefinitely * * \return True if at least one socket registered to the poller is ready. * @@ -179,7 +179,7 @@ namespace Nz * \see IsReady * \see RegisterSocket */ - bool SocketPoller::Wait(UInt64 msTimeout) + bool SocketPoller::Wait(int msTimeout) { SocketError error; diff --git a/src/Nazara/Network/TcpClient.cpp b/src/Nazara/Network/TcpClient.cpp index 54144e8fd..9e2eb7e0c 100644 --- a/src/Nazara/Network/TcpClient.cpp +++ b/src/Nazara/Network/TcpClient.cpp @@ -326,7 +326,7 @@ namespace Nz }); } - while (totalByteSent < size) + while (totalByteSent < size || !IsBlockingEnabled()) { int sendSize = static_cast(std::min(size - totalByteSent, std::numeric_limits::max())); //< Handle very large send int sentSize; diff --git a/src/Nazara/Network/TcpServer.cpp b/src/Nazara/Network/TcpServer.cpp index 95aaaf098..ebeb2392e 100644 --- a/src/Nazara/Network/TcpServer.cpp +++ b/src/Nazara/Network/TcpServer.cpp @@ -3,10 +3,8 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include -#include #include #if defined(NAZARA_PLATFORM_WINDOWS) diff --git a/src/Nazara/Network/UdpSocket.cpp b/src/Nazara/Network/UdpSocket.cpp index bc86f8401..c0a88eb88 100644 --- a/src/Nazara/Network/UdpSocket.cpp +++ b/src/Nazara/Network/UdpSocket.cpp @@ -118,6 +118,42 @@ namespace Nz return true; } + /*! + * \brief Receive multiple datagram from one peer + * \return true If data were sent + * + * \param to Destination IpAddress (must match socket protocol) + * \param buffers A pointer to an array of NetBuffer containing buffers and size data + * \param bufferCount Number of buffers available + * \param from IpAddress of the peer + * \param received Optional argument to get the number of bytes received + */ + bool UdpSocket::ReceiveMultiple(NetBuffer* buffers, std::size_t bufferCount, IpAddress* from, std::size_t* received) + { + NazaraAssert(m_handle != SocketImpl::InvalidHandle, "Socket hasn't been created"); + NazaraAssert(buffers && bufferCount > 0, "Invalid buffer"); + + int read; + if (!SocketImpl::ReceiveMultiple(m_handle, buffers, bufferCount, from, &read, &m_lastError)) + { + switch (m_lastError) + { + case SocketError_ConnectionClosed: + m_lastError = SocketError_NoError; + read = 0; + break; + + default: + return false; + } + } + + if (received) + *received = read; + + return true; + } + /*! * \brief Receives the packet available * \return true If packet received diff --git a/src/Nazara/Network/Win32/SocketImpl.cpp b/src/Nazara/Network/Win32/SocketImpl.cpp index 32404f53a..6c82f0505 100644 --- a/src/Nazara/Network/Win32/SocketImpl.cpp +++ b/src/Nazara/Network/Win32/SocketImpl.cpp @@ -586,6 +586,72 @@ namespace Nz return true; } + bool SocketImpl::ReceiveMultiple(SocketHandle handle, NetBuffer* buffers, std::size_t bufferCount, IpAddress* from, int* read, SocketError* error) + { + NazaraAssert(handle != InvalidHandle, "Invalid handle"); + NazaraAssert(buffers && bufferCount > 0, "Invalid buffers"); + + IpAddressImpl::SockAddrBuffer nameBuffer; + int bufferLength = static_cast(nameBuffer.size()); + + IpAddress senderIp; + + StackAllocation memory = NazaraStackAllocation(bufferCount * sizeof(WSABUF)); + WSABUF* winBuffers = static_cast(memory.GetPtr()); + for (std::size_t i = 0; i < bufferCount; ++i) + { + winBuffers[i].buf = static_cast(buffers[i].data); + winBuffers[i].len = static_cast(buffers[i].dataLength); + } + + DWORD flags = 0; + DWORD byteRead; + if (WSARecvFrom(handle, winBuffers, static_cast(bufferCount), &byteRead, &flags, reinterpret_cast(nameBuffer.data()), &bufferLength, nullptr, nullptr) == SOCKET_ERROR) + { + int errorCode = WSAGetLastError(); + switch (errorCode) + { + case WSAECONNRESET: + case WSAEWOULDBLOCK: + { + // If we have no data and are not blocking, return true with 0 byte read + byteRead = 0; + senderIp = IpAddress::Invalid; + break; + } + + default: + { + if (error) + *error = TranslateWSAErrorToSocketError(errorCode); + + return false; //< Error + } + } + } + else + senderIp = IpAddressImpl::FromSockAddr(reinterpret_cast(&nameBuffer)); + + if (flags & MSG_PARTIAL) + { + if (error) + *error = SocketError_DatagramSize; + + return false; + } + + if (from) + *from = senderIp; + + if (read) + *read = byteRead; + + if (error) + *error = SocketError_NoError; + + return true; + } + bool SocketImpl::Send(SocketHandle handle, const void* buffer, int length, int* sent, SocketError* error) { NazaraAssert(handle != InvalidHandle, "Invalid handle"); diff --git a/src/Nazara/Network/Win32/SocketImpl.hpp b/src/Nazara/Network/Win32/SocketImpl.hpp index edcc7ce09..864e629dd 100644 --- a/src/Nazara/Network/Win32/SocketImpl.hpp +++ b/src/Nazara/Network/Win32/SocketImpl.hpp @@ -64,6 +64,7 @@ namespace Nz static bool Receive(SocketHandle handle, void* buffer, int length, int* read, SocketError* error); static bool ReceiveFrom(SocketHandle handle, void* buffer, int length, IpAddress* from, int* read, SocketError* error); + static bool ReceiveMultiple(SocketHandle handle, NetBuffer* buffers, std::size_t bufferCount, IpAddress* from, int* read, SocketError* error); static bool Send(SocketHandle handle, const void* buffer, int length, int* sent, SocketError* error); static bool SendMultiple(SocketHandle handle, const NetBuffer* buffers, std::size_t bufferCount, const IpAddress& to, int* sent, SocketError* error); diff --git a/src/Nazara/Network/Win32/SocketPollerImpl.cpp b/src/Nazara/Network/Win32/SocketPollerImpl.cpp index 3513ce722..6789f35f4 100644 --- a/src/Nazara/Network/Win32/SocketPollerImpl.cpp +++ b/src/Nazara/Network/Win32/SocketPollerImpl.cpp @@ -129,12 +129,36 @@ namespace Nz #endif } - int SocketPollerImpl::Wait(UInt64 msTimeout, SocketError* error) + int SocketPollerImpl::Wait(int msTimeout, SocketError* error) { int activeSockets; #if NAZARA_NETWORK_POLL_SUPPORT activeSockets = SocketImpl::Poll(m_sockets.data(), m_sockets.size(), static_cast(msTimeout), error); + + m_readyToReadSockets.clear(); + m_readyToWriteSockets.clear(); + if (activeSockets > 0U) + { + int socketRemaining = activeSockets; + for (PollSocket& entry : m_sockets) + { + if (entry.revents != 0) + { + if (entry.revents & POLLRDNORM) + m_readyToReadSockets.insert(entry.fd); + + if (entry.revents & POLLWRNORM) + m_readyToWriteSockets.insert(entry.fd); + + entry.revents = 0; + + if (--socketRemaining == 0) + break; + } + } + } + #else fd_set* readSet = nullptr; fd_set* writeSet = nullptr; @@ -155,7 +179,7 @@ namespace Nz tv.tv_sec = static_cast(msTimeout / 1000ULL); tv.tv_usec = static_cast((msTimeout % 1000ULL) * 1000ULL); - activeSockets = ::select(0xDEADBEEF, readSet, writeSet, nullptr, (msTimeout > 0) ? &tv : nullptr); //< The first argument is ignored on Windows + activeSockets = ::select(0xDEADBEEF, readSet, writeSet, nullptr, (msTimeout >= 0) ? &tv : nullptr); //< The first argument is ignored on Windows if (activeSockets == SOCKET_ERROR) { if (error) diff --git a/src/Nazara/Network/Win32/SocketPollerImpl.hpp b/src/Nazara/Network/Win32/SocketPollerImpl.hpp index a94af1372..2dfb32070 100644 --- a/src/Nazara/Network/Win32/SocketPollerImpl.hpp +++ b/src/Nazara/Network/Win32/SocketPollerImpl.hpp @@ -32,7 +32,7 @@ namespace Nz bool RegisterSocket(SocketHandle socket, SocketPollEventFlags eventFlags); void UnregisterSocket(SocketHandle socket); - int Wait(UInt64 msTimeout, SocketError* error); + int Wait(int msTimeout, SocketError* error); private: #if NAZARA_NETWORK_POLL_SUPPORT diff --git a/src/Nazara/Noise/Perlin.cpp b/src/Nazara/Noise/Perlin.cpp index 9d0249759..d80bf7c84 100644 --- a/src/Nazara/Noise/Perlin.cpp +++ b/src/Nazara/Noise/Perlin.cpp @@ -4,8 +4,6 @@ #include #include -#include -#include #include namespace Nz diff --git a/src/Nazara/Noise/Simplex.cpp b/src/Nazara/Noise/Simplex.cpp index d73465c70..b9e6ba957 100644 --- a/src/Nazara/Noise/Simplex.cpp +++ b/src/Nazara/Noise/Simplex.cpp @@ -4,8 +4,6 @@ #include #include -#include -#include #include namespace Nz diff --git a/src/Nazara/Noise/Worley.cpp b/src/Nazara/Noise/Worley.cpp index 81fd8aad0..82366234b 100644 --- a/src/Nazara/Noise/Worley.cpp +++ b/src/Nazara/Noise/Worley.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include diff --git a/src/Nazara/Physics2D/Collider2D.cpp b/src/Nazara/Physics2D/Collider2D.cpp index 3a679fad9..95cd633af 100644 --- a/src/Nazara/Physics2D/Collider2D.cpp +++ b/src/Nazara/Physics2D/Collider2D.cpp @@ -15,7 +15,9 @@ namespace Nz { cpShapeFilter filter = cpShapeFilterNew(m_collisionGroup, m_categoryMask, m_collisionMask); - std::vector shapes = CreateShapes(body); + std::vector shapes; + CreateShapes(body, shapes); + for (cpShape* shape : shapes) { cpShapeSetFilter(shape, filter); @@ -29,7 +31,7 @@ namespace Nz /******************************** BoxCollider2D *********************************/ BoxCollider2D::BoxCollider2D(const Vector2f& size, float radius) : - BoxCollider2D(Rectf(-size.x / 2.f, -size.y / 2.f, size.x / 2.f, size.y / 2.f), radius) + BoxCollider2D(Rectf(-size.x / 2.f, -size.y / 2.f, size.x, size.y), radius) { } @@ -39,9 +41,9 @@ namespace Nz { } - float BoxCollider2D::ComputeInertialMatrix(float mass) const + float BoxCollider2D::ComputeMomentOfInertia(float mass) const { - return static_cast(cpMomentForBox2(mass, cpBBNew(m_rect.x, m_rect.y + m_rect.height, m_rect.x + m_rect.width, m_rect.y))); + return static_cast(cpMomentForBox2(mass, cpBBNew(m_rect.x, m_rect.y, m_rect.x + m_rect.width, m_rect.y + m_rect.height))); } ColliderType2D BoxCollider2D::GetType() const @@ -49,12 +51,9 @@ namespace Nz return ColliderType2D_Box; } - std::vector BoxCollider2D::CreateShapes(RigidBody2D* body) const + void BoxCollider2D::CreateShapes(RigidBody2D* body, std::vector& shapes) const { - std::vector shapes; - shapes.push_back(cpBoxShapeNew2(body->GetHandle(), cpBBNew(m_rect.x, m_rect.y + m_rect.height, m_rect.x + m_rect.width, m_rect.y), m_radius)); - - return shapes; + shapes.push_back(cpBoxShapeNew2(body->GetHandle(), cpBBNew(m_rect.x, m_rect.y, m_rect.x + m_rect.width, m_rect.y + m_rect.height), m_radius)); } /******************************** CircleCollider2D *********************************/ @@ -65,7 +64,7 @@ namespace Nz { } - float CircleCollider2D::ComputeInertialMatrix(float mass) const + float CircleCollider2D::ComputeMomentOfInertia(float mass) const { return static_cast(cpMomentForCircle(mass, 0.f, m_radius, cpv(m_offset.x, m_offset.y))); } @@ -75,12 +74,66 @@ namespace Nz return ColliderType2D_Circle; } - std::vector CircleCollider2D::CreateShapes(RigidBody2D* body) const + void CircleCollider2D::CreateShapes(RigidBody2D* body, std::vector& shapes) const { - std::vector shapes; shapes.push_back(cpCircleShapeNew(body->GetHandle(), m_radius, cpv(m_offset.x, m_offset.y))); + } - return shapes; + /******************************** CompoundCollider2D *********************************/ + + CompoundCollider2D::CompoundCollider2D(std::vector geoms) : + m_geoms(std::move(geoms)) + { + } + + float CompoundCollider2D::ComputeMomentOfInertia(float mass) const + { + ///TODO: Correctly compute moment using parallel axis theorem: + /// https://chipmunk-physics.net/forum/viewtopic.php?t=1056 + float momentOfInertia = 0.f; + for (const auto& geom : m_geoms) + momentOfInertia += geom->ComputeMomentOfInertia(mass); //< Eeeer + + return momentOfInertia; + } + + ColliderType2D CompoundCollider2D::GetType() const + { + return ColliderType2D_Compound; + } + + void CompoundCollider2D::CreateShapes(RigidBody2D* body, std::vector& shapes) const + { + // Since C++ does not allow protected call from other objects, we have to be a friend of Collider2D, yay + for (const auto& geom : m_geoms) + geom->CreateShapes(body, shapes); + } + + /******************************** ConvexCollider2D *********************************/ + + ConvexCollider2D::ConvexCollider2D(SparsePtr vertices, std::size_t vertexCount, float radius) : + m_radius(radius) + { + m_vertices.resize(vertexCount); + for (std::size_t i = 0; i < vertexCount; ++i) + m_vertices[i].Set(*vertices++); + } + + float ConvexCollider2D::ComputeMomentOfInertia(float mass) const + { + static_assert(sizeof(cpVect) == sizeof(Vector2d), "Chipmunk vector is not equivalent to Vector2d"); + + return static_cast(cpMomentForPoly(mass, int(m_vertices.size()), reinterpret_cast(m_vertices.data()), cpv(0.0, 0.0), m_radius)); + } + + ColliderType2D ConvexCollider2D::GetType() const + { + return ColliderType2D_Convex; + } + + void ConvexCollider2D::CreateShapes(RigidBody2D* body, std::vector& shapes) const + { + shapes.push_back(cpPolyShapeNew(body->GetHandle(), int(m_vertices.size()), reinterpret_cast(m_vertices.data()), cpTransformIdentity, m_radius)); } /********************************* NullCollider2D **********************************/ @@ -90,19 +143,18 @@ namespace Nz return ColliderType2D_Null; } - float NullCollider2D::ComputeInertialMatrix(float /*mass*/) const + float NullCollider2D::ComputeMomentOfInertia(float mass) const { - return 0.f; + return (mass > 0.f) ? 1.f : 0.f; //< Null inertia is only possible for static/kinematic objects } - std::vector NullCollider2D::CreateShapes(RigidBody2D* /*body*/) const + void NullCollider2D::CreateShapes(RigidBody2D* /*body*/, std::vector& /*shapes*/) const { - return std::vector(); } /******************************** SegmentCollider2D *********************************/ - float SegmentCollider2D::ComputeInertialMatrix(float mass) const + float SegmentCollider2D::ComputeMomentOfInertia(float mass) const { return static_cast(cpMomentForSegment(mass, cpv(m_first.x, m_first.y), cpv(m_second.x, m_second.y), m_thickness)); } @@ -112,12 +164,8 @@ namespace Nz return ColliderType2D_Segment; } - std::vector SegmentCollider2D::CreateShapes(RigidBody2D* body) const + void SegmentCollider2D::CreateShapes(RigidBody2D* body, std::vector& shapes) const { - std::vector shapes; shapes.push_back(cpSegmentShapeNew(body->GetHandle(), cpv(m_first.x, m_first.y), cpv(m_second.x, m_second.y), m_thickness)); - - return shapes; } - } diff --git a/src/Nazara/Physics2D/PhysWorld2D.cpp b/src/Nazara/Physics2D/PhysWorld2D.cpp index cbf098786..06075a782 100644 --- a/src/Nazara/Physics2D/PhysWorld2D.cpp +++ b/src/Nazara/Physics2D/PhysWorld2D.cpp @@ -21,6 +21,11 @@ namespace Nz cpSpaceFree(m_handle); } + float PhysWorld2D::GetDamping() const + { + return float(cpSpaceGetDamping(m_handle)); + } + Vector2f PhysWorld2D::GetGravity() const { cpVect gravity = cpSpaceGetGravity(m_handle); @@ -60,12 +65,12 @@ namespace Nz { cpPointQueryInfo queryInfo; - if (cpShape* shape = cpSpacePointQueryNearest(m_handle, { from.x, from.y }, maxDistance, filter, &queryInfo)) + if (cpSpacePointQueryNearest(m_handle, { from.x, from.y }, maxDistance, filter, &queryInfo)) { result->closestPoint.Set(Nz::Vector2(queryInfo.point.x, queryInfo.point.y)); result->distance = float(queryInfo.distance); result->fraction.Set(Nz::Vector2(queryInfo.gradient.x, queryInfo.gradient.y)); - result->nearestBody = static_cast(cpShapeGetUserData(shape)); + result->nearestBody = static_cast(cpShapeGetUserData(queryInfo.shape)); return true; } @@ -74,7 +79,7 @@ namespace Nz } else { - if (cpShape* shape = cpSpacePointQueryNearest(m_handle, { from.x, from.y }, maxDistance, filter, nullptr)) + if (cpSpacePointQueryNearest(m_handle, { from.x, from.y }, maxDistance, filter, nullptr)) return true; else return false; @@ -114,7 +119,7 @@ namespace Nz { cpSegmentQueryInfo queryInfo; - if (cpShape* shape = cpSpaceSegmentQueryFirst(m_handle, { from.x, from.y }, { to.x, to.y }, radius, filter, &queryInfo)) + if (cpSpaceSegmentQueryFirst(m_handle, { from.x, from.y }, { to.x, to.y }, radius, filter, &queryInfo)) { hitInfo->fraction = float(queryInfo.alpha); hitInfo->hitNormal.Set(Nz::Vector2(queryInfo.normal.x, queryInfo.normal.y)); @@ -128,7 +133,7 @@ namespace Nz } else { - if (cpShape* shape = cpSpaceSegmentQueryFirst(m_handle, { from.x, from.y }, { to.x, to.y }, radius, filter, nullptr)) + if (cpSpaceSegmentQueryFirst(m_handle, { from.x, from.y }, { to.x, to.y }, radius, filter, nullptr)) return true; else return false; @@ -146,7 +151,7 @@ namespace Nz }; cpShapeFilter filter = cpShapeFilterNew(collisionGroup, categoryMask, collisionMask); - cpSpaceBBQuery(m_handle, cpBBNew(boundingBox.x, boundingBox.y + boundingBox.height, boundingBox.x + boundingBox.width, boundingBox.y), filter, callback, bodies); + cpSpaceBBQuery(m_handle, cpBBNew(boundingBox.x, boundingBox.y, boundingBox.x + boundingBox.width, boundingBox.y + boundingBox.height), filter, callback, bodies); } void PhysWorld2D::RegisterCallbacks(unsigned int collisionId, const Callback& callbacks) @@ -159,6 +164,11 @@ namespace Nz InitCallbacks(cpSpaceAddCollisionHandler(m_handle, collisionIdA, collisionIdB), callbacks); } + void PhysWorld2D::SetDamping(float dampingValue) + { + cpSpaceSetDamping(m_handle, dampingValue); + } + void PhysWorld2D::SetGravity(const Vector2f& gravity) { cpSpaceSetGravity(m_handle, cpv(gravity.x, gravity.y)); diff --git a/src/Nazara/Physics2D/RigidBody2D.cpp b/src/Nazara/Physics2D/RigidBody2D.cpp index 3b2f927f9..b21810c4f 100644 --- a/src/Nazara/Physics2D/RigidBody2D.cpp +++ b/src/Nazara/Physics2D/RigidBody2D.cpp @@ -3,8 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include #include #include #include @@ -27,10 +25,8 @@ namespace Nz { NazaraAssert(m_world, "Invalid world"); - Create(); - + m_handle = Create(mass); SetGeom(geom); - SetMass(mass); } RigidBody2D::RigidBody2D(const RigidBody2D& object) : @@ -38,15 +34,18 @@ namespace Nz m_userData(object.m_userData), m_world(object.m_world), m_gravityFactor(object.m_gravityFactor), - m_mass(0.f) + m_mass(object.GetMass()) { NazaraAssert(m_world, "Invalid world"); NazaraAssert(m_geom, "Invalid geometry"); - Create(); + m_handle = Create(m_mass, object.GetMomentOfInertia()); + SetGeom(object.GetGeom(), false); - SetGeom(object.GetGeom()); - SetMass(object.GetMass()); + CopyBodyData(object.GetHandle()); + + for (std::size_t i = 0; i < m_shapes.size(); ++i) + m_shapes[i]->bb = cpShapeCacheBB(object.m_shapes[i]); } RigidBody2D::RigidBody2D(RigidBody2D&& object) : @@ -93,7 +92,7 @@ namespace Nz cpBodyApplyForceAtLocalPoint(m_handle, cpv(force.x, force.y), cpv(point.x, point.y)); break; } - } +} void RigidBody2D::AddImpulse(const Vector2f& impulse, CoordSys coordSys) { @@ -116,21 +115,25 @@ namespace Nz void RigidBody2D::AddTorque(float torque) { - cpBodySetTorque(m_handle, cpBodyGetTorque(m_handle) + torque); + cpBodySetTorque(m_handle, cpBodyGetTorque(m_handle) + ToRadians(torque)); } Rectf RigidBody2D::GetAABB() const { - cpBB bb = cpBBNew(0.f, 0.f, 0.f, 0.f); - for (cpShape* shape : m_shapes) - bb = cpBBMerge(bb, cpShapeGetBB(shape)); + if (m_shapes.empty()) + return Rectf::Zero(); - return Rectf(Rect(bb.l, bb.t, bb.r - bb.l, bb.b - bb.t)); + auto it = m_shapes.begin(); + cpBB bb = cpShapeGetBB(*it++); + for (; it != m_shapes.end(); ++it) + bb = cpBBMerge(bb, cpShapeGetBB(*it)); + + return Rectf(Rect(bb.l, bb.b, bb.r - bb.l, bb.t - bb.b)); } float RigidBody2D::GetAngularVelocity() const { - return static_cast(cpBodyGetAngularVelocity(m_handle)); + return FromRadians(static_cast(cpBodyGetAngularVelocity(m_handle))); } const Collider2DRef& RigidBody2D::GetGeom() const @@ -148,6 +151,11 @@ namespace Nz return m_mass; } + float RigidBody2D::GetMomentOfInertia() const + { + return float(cpBodyGetMoment(m_handle)); + } + Vector2f RigidBody2D::GetCenterOfGravity(CoordSys coordSys) const { cpVect cog = cpBodyGetCenterOfGravity(m_handle); @@ -173,7 +181,7 @@ namespace Nz float RigidBody2D::GetRotation() const { - return static_cast(cpBodyGetAngle(m_handle)); + return FromRadians(static_cast(cpBodyGetAngle(m_handle))); } void* RigidBody2D::GetUserdata() const @@ -187,9 +195,14 @@ namespace Nz return Vector2f(static_cast(vel.x), static_cast(vel.y)); } - bool RigidBody2D::IsMoveable() const + PhysWorld2D* RigidBody2D::GetWorld() const { - return m_mass > 0.f; + return m_world; + } + + bool RigidBody2D::IsKinematic() const + { + return m_mass <= 0.f; } bool RigidBody2D::IsSleeping() const @@ -199,27 +212,24 @@ namespace Nz void RigidBody2D::SetAngularVelocity(float angularVelocity) { - cpBodySetAngularVelocity(m_handle, angularVelocity); + cpBodySetAngularVelocity(m_handle, ToRadians(angularVelocity)); } - void RigidBody2D::SetGeom(Collider2DRef geom) + void RigidBody2D::SetGeom(Collider2DRef geom, bool recomputeMoment) { // We have no public way of getting rid of an existing geom without removing the whole body // So let's save some attributes of the body, destroy it and rebuild it if (m_geom) { - cpVect pos = cpBodyGetPosition(m_handle); cpFloat mass = cpBodyGetMass(m_handle); cpFloat moment = cpBodyGetMoment(m_handle); - cpFloat rot = cpBodyGetAngle(m_handle); - cpVect vel = cpBodyGetVelocity(m_handle); + cpBody* newHandle = Create(static_cast(mass), static_cast(moment)); + + CopyBodyData(m_handle); Destroy(); - Create(float(mass), float(moment)); - cpBodySetAngle(m_handle, rot); - cpBodySetPosition(m_handle, pos); - cpBodySetVelocity(m_handle, vel); + m_handle = newHandle; } if (geom) @@ -236,33 +246,38 @@ namespace Nz cpSpaceAddShape(space, shape); } - cpBodySetMoment(m_handle, m_geom->ComputeInertialMatrix(m_mass)); + if (recomputeMoment) + cpBodySetMoment(m_handle, m_geom->ComputeMomentOfInertia(m_mass)); } - void RigidBody2D::SetMass(float mass) + void RigidBody2D::SetMass(float mass, bool recomputeMoment) { if (m_mass > 0.f) { if (mass > 0.f) { - m_world->RegisterPostStep(this, [mass](Nz::RigidBody2D* body) + m_world->RegisterPostStep(this, [mass, recomputeMoment](Nz::RigidBody2D* body) { cpBodySetMass(body->GetHandle(), mass); - cpBodySetMoment(body->GetHandle(), body->GetGeom()->ComputeInertialMatrix(mass)); + + if (recomputeMoment) + cpBodySetMoment(body->GetHandle(), body->GetGeom()->ComputeMomentOfInertia(mass)); }); } else - m_world->RegisterPostStep(this, [](Nz::RigidBody2D* body) { cpBodySetType(body->GetHandle(), CP_BODY_TYPE_STATIC); } ); + m_world->RegisterPostStep(this, [](Nz::RigidBody2D* body) { cpBodySetType(body->GetHandle(), CP_BODY_TYPE_KINEMATIC); } ); } else if (mass > 0.f) { - m_world->RegisterPostStep(this, [mass](Nz::RigidBody2D* body) + m_world->RegisterPostStep(this, [mass, recomputeMoment](Nz::RigidBody2D* body) { - if (cpBodyGetType(body->GetHandle()) == CP_BODY_TYPE_STATIC) + if (cpBodyGetType(body->GetHandle()) == CP_BODY_TYPE_KINEMATIC) { cpBodySetType(body->GetHandle(), CP_BODY_TYPE_DYNAMIC); cpBodySetMass(body->GetHandle(), mass); - cpBodySetMoment(body->GetHandle(), body->GetGeom()->ComputeInertialMatrix(mass)); + + if (recomputeMoment) + cpBodySetMoment(body->GetHandle(), body->GetGeom()->ComputeMomentOfInertia(mass)); } }); } @@ -272,20 +287,26 @@ namespace Nz void RigidBody2D::SetMassCenter(const Vector2f& center) { - if (m_mass > 0.f) - cpBodySetCenterOfGravity(m_handle, cpv(center.x, center.y)); + cpBodySetCenterOfGravity(m_handle, cpv(center.x, center.y)); + } + + void RigidBody2D::SetMomentOfInertia(float moment) + { + // Even though Chipmunk allows us to change this anytime, we need to do it in a post-step to prevent other post-steps to override this + m_world->RegisterPostStep(this, [moment] (Nz::RigidBody2D* body) + { + cpBodySetMoment(body->GetHandle(), moment); + }); } void RigidBody2D::SetPosition(const Vector2f& position) { cpBodySetPosition(m_handle, cpv(position.x, position.y)); - if (cpBodyGetType(m_handle) == CP_BODY_TYPE_STATIC) - cpSpaceReindexShapesForBody(m_world->GetHandle(), m_handle); } void RigidBody2D::SetRotation(float rotation) { - cpBodySetAngle(m_handle, rotation); + cpBodySetAngle(m_handle, ToRadians(rotation)); } void RigidBody2D::SetUserdata(void* ud) @@ -330,12 +351,28 @@ namespace Nz return *this; } - void RigidBody2D::Create(float mass, float moment) + void RigidBody2D::CopyBodyData(cpBody* body) { - m_handle = cpBodyNew(mass, moment); - cpBodySetUserData(m_handle, this); + cpBodySetAngle(m_handle, cpBodyGetAngle(body)); + cpBodySetAngularVelocity(m_handle, cpBodyGetAngularVelocity(body)); + cpBodySetCenterOfGravity(m_handle, cpBodyGetCenterOfGravity(body)); + cpBodySetForce(m_handle, cpBodyGetForce(body)); + cpBodySetPosition(m_handle, cpBodyGetPosition(body)); + cpBodySetTorque(m_handle, cpBodyGetTorque(body)); + cpBodySetVelocity(m_handle, cpBodyGetVelocity(body)); + } - cpSpaceAddBody(m_world->GetHandle(), m_handle); + cpBody* RigidBody2D::Create(float mass, float moment) + { + cpBody* handle = cpBodyNew(mass, moment); + cpBodySetUserData(handle, this); + + if (mass <= 0.f) + cpBodySetType(handle, CP_BODY_TYPE_KINEMATIC); + + cpSpaceAddBody(m_world->GetHandle(), handle); + + return handle; } void RigidBody2D::Destroy() @@ -352,5 +389,6 @@ namespace Nz cpSpaceRemoveBody(space, m_handle); cpBodyFree(m_handle); } + m_shapes.clear(); } } diff --git a/src/Nazara/Physics3D/Collider3D.cpp b/src/Nazara/Physics3D/Collider3D.cpp index d71f4caa8..454c18037 100644 --- a/src/Nazara/Physics3D/Collider3D.cpp +++ b/src/Nazara/Physics3D/Collider3D.cpp @@ -3,9 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include +#include #include #include -#include #include namespace Nz @@ -50,7 +50,7 @@ namespace Nz { Vector3f min, max; - // Si nous n'avons aucune instance, nous en créons une temporaire + // Si nous n'avons aucune instance, nous en cr�ons une temporaire if (m_handles.empty()) { PhysWorld3D world; @@ -61,7 +61,7 @@ namespace Nz } NewtonDestroyCollision(collision); } - else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute façon) + else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute fa�on) NewtonCollisionCalculateAABB(m_handles.begin()->second, offsetMatrix, min, max); return Boxf(scale * min, scale * max); @@ -72,7 +72,7 @@ namespace Nz float inertiaMatrix[3]; float origin[3]; - // Si nous n'avons aucune instance, nous en créons une temporaire + // Si nous n'avons aucune instance, nous en cr�ons une temporaire if (m_handles.empty()) { PhysWorld3D world; @@ -83,7 +83,7 @@ namespace Nz } NewtonDestroyCollision(collision); } - else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute façon) + else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute fa�on) NewtonConvexCollisionCalculateInertialMatrix(m_handles.begin()->second, inertiaMatrix, origin); if (inertia) @@ -97,7 +97,7 @@ namespace Nz { float volume; - // Si nous n'avons aucune instance, nous en créons une temporaire + // Si nous n'avons aucune instance, nous en cr�ons une temporaire if (m_handles.empty()) { PhysWorld3D world; @@ -108,7 +108,7 @@ namespace Nz } NewtonDestroyCollision(collision); } - else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute façon) + else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute fa�on) volume = NewtonConvexCollisionCalculateVolume(m_handles.begin()->second); return volume; @@ -128,12 +128,12 @@ namespace Nz std::size_t primitiveCount = list.GetSize(); if (primitiveCount > 1) { - std::vector geoms(primitiveCount); + std::vector geoms(primitiveCount); for (unsigned int i = 0; i < primitiveCount; ++i) geoms[i] = CreateGeomFromPrimitive(list.GetPrimitive(i)); - return CompoundCollider3D::New(&geoms[0], primitiveCount); + return CompoundCollider3D::New(std::move(geoms)); } else if (primitiveCount > 0) return CreateGeomFromPrimitive(list.GetPrimitive(0)); @@ -239,11 +239,9 @@ namespace Nz /******************************* CompoundCollider3D ********************************/ - CompoundCollider3D::CompoundCollider3D(Collider3D** geoms, std::size_t geomCount) + CompoundCollider3D::CompoundCollider3D(std::vector geoms) : + m_geoms(std::move(geoms)) { - m_geoms.reserve(geomCount); - for (std::size_t i = 0; i < geomCount; ++i) - m_geoms.emplace_back(geoms[i]); } const std::vector& CompoundCollider3D::GetGeoms() const diff --git a/src/Nazara/Physics3D/RigidBody3D.cpp b/src/Nazara/Physics3D/RigidBody3D.cpp index 9a909f98f..af4b91a32 100644 --- a/src/Nazara/Physics3D/RigidBody3D.cpp +++ b/src/Nazara/Physics3D/RigidBody3D.cpp @@ -3,8 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include -#include #include #include #include @@ -204,6 +202,11 @@ namespace Nz return velocity; } + PhysWorld3D* RigidBody3D::GetWorld() const + { + return m_world; + } + bool RigidBody3D::IsAutoSleepEnabled() const { return NewtonBodyGetAutoSleep(m_body) != 0; @@ -314,7 +317,7 @@ namespace Nz NazaraUnused(userData); NewtonBodySetSleepState(body, 0); return 1; - }, + }, nullptr); } } diff --git a/src/Nazara/Utility/Cursor.cpp b/src/Nazara/Platform/Cursor.cpp similarity index 86% rename from src/Nazara/Utility/Cursor.cpp rename to src/Nazara/Platform/Cursor.cpp index e8b3e0b21..7d68a460b 100644 --- a/src/Nazara/Utility/Cursor.cpp +++ b/src/Nazara/Platform/Cursor.cpp @@ -1,18 +1,18 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #if defined(NAZARA_PLATFORM_WINDOWS) - #include + #include #elif defined(NAZARA_PLATFORM_X11) - #include + #include #else #error Lack of implementation: Cursor #endif -#include +#include namespace Nz { diff --git a/src/Nazara/Platform/Debug/NewOverload.cpp b/src/Nazara/Platform/Debug/NewOverload.cpp new file mode 100644 index 000000000..c5522beb8 --- /dev/null +++ b/src/Nazara/Platform/Debug/NewOverload.cpp @@ -0,0 +1,31 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Platform module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#if NAZARA_PLATFORM_MANAGE_MEMORY + +#include +#include // Needed ? + +void* operator new(std::size_t size) +{ + return Nz::MemoryManager::Allocate(size, false); +} + +void* operator new[](std::size_t size) +{ + return Nz::MemoryManager::Allocate(size, true); +} + +void operator delete(void* pointer) noexcept +{ + Nz::MemoryManager::Free(pointer, false); +} + +void operator delete[](void* pointer) noexcept +{ + Nz::MemoryManager::Free(pointer, true); +} + +#endif // NAZARA_PLATFORM_MANAGE_MEMORY diff --git a/src/Nazara/Utility/Icon.cpp b/src/Nazara/Platform/Icon.cpp similarity index 73% rename from src/Nazara/Utility/Icon.cpp rename to src/Nazara/Platform/Icon.cpp index 843e64456..010e9dfc2 100644 --- a/src/Nazara/Utility/Icon.cpp +++ b/src/Nazara/Platform/Icon.cpp @@ -1,18 +1,18 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #if defined(NAZARA_PLATFORM_WINDOWS) - #include + #include #elif defined(NAZARA_PLATFORM_X11) - #include + #include #else #error Lack of implementation: Icon #endif -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/Keyboard.cpp b/src/Nazara/Platform/Keyboard.cpp similarity index 64% rename from src/Nazara/Utility/Keyboard.cpp rename to src/Nazara/Platform/Keyboard.cpp index 08f4b05a7..be1341eb6 100644 --- a/src/Nazara/Utility/Keyboard.cpp +++ b/src/Nazara/Platform/Keyboard.cpp @@ -1,18 +1,18 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #if defined(NAZARA_PLATFORM_WINDOWS) - #include + #include #elif defined(NAZARA_PLATFORM_X11) - #include + #include #else #error Lack of implementation: Keyboard #endif -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/Mouse.cpp b/src/Nazara/Platform/Mouse.cpp similarity index 82% rename from src/Nazara/Utility/Mouse.cpp rename to src/Nazara/Platform/Mouse.cpp index b25ce2506..6d589697e 100644 --- a/src/Nazara/Utility/Mouse.cpp +++ b/src/Nazara/Platform/Mouse.cpp @@ -1,19 +1,19 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include +#include +#include #if defined(NAZARA_PLATFORM_WINDOWS) - #include + #include #elif defined(NAZARA_PLATFORM_X11) - #include + #include #else #error Lack of implementation: Mouse #endif -#include +#include namespace Nz { diff --git a/src/Nazara/Platform/Platform.cpp b/src/Nazara/Platform/Platform.cpp new file mode 100644 index 000000000..5151ed123 --- /dev/null +++ b/src/Nazara/Platform/Platform.cpp @@ -0,0 +1,108 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Platform module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include +#include +#include +#include +#include +#include + +namespace Nz +{ + /*! + * \ingroup system + * \class Nz::Platform + * \brief Platform class that represents the module initializer of Platform + */ + + /*! + * \brief Initializes the Platform module + * \return true if initialization is successful + * + * \remark Produces a NazaraNotice + * \remark Produces a NazaraError if one submodule failed + */ + + bool Platform::Initialize() + { + if (s_moduleReferenceCounter > 0) + { + s_moduleReferenceCounter++; + return true; // Already initialized + } + + // Initialize module dependencies + if (!Utility::Initialize()) + { + NazaraError("Failed to initialize utility module"); + return false; + } + + s_moduleReferenceCounter++; + + // Initialisation of the module + CallOnExit onExit(Platform::Uninitialize); + + if (!Window::Initialize()) + { + NazaraError("Failed to initialize window's system"); + return false; + } + + // Must be initialized after Window + if (!Cursor::Initialize()) + { + NazaraError("Failed to initialize cursors"); + return false; + } + + onExit.Reset(); + + NazaraNotice("Initialized: Platform module"); + return true; + } + + /*! + * \brief Checks whether the module is initialized + * \return true if module is initialized + */ + + bool Platform::IsInitialized() + { + return s_moduleReferenceCounter != 0; + } + + /*! + * \brief Uninitializes the Platform module + * + * \remark Produces a NazaraNotice + */ + + void Platform::Uninitialize() + { + if (s_moduleReferenceCounter != 1) + { + // The module is still in use, or can not be uninitialized + if (s_moduleReferenceCounter > 1) + s_moduleReferenceCounter--; + + return; + } + + // Free of module + s_moduleReferenceCounter = 0; + + Cursor::Uninitialize(); //< Must be done before Window + Window::Uninitialize(); + + NazaraNotice("Uninitialized: Platform module"); + + // Free of dependances + Utility::Uninitialize(); + } + + unsigned int Platform::s_moduleReferenceCounter = 0; +} diff --git a/src/Nazara/Utility/VideoMode.cpp b/src/Nazara/Platform/VideoMode.cpp similarity index 90% rename from src/Nazara/Utility/VideoMode.cpp rename to src/Nazara/Platform/VideoMode.cpp index 7d1f3beec..5cc78d981 100644 --- a/src/Nazara/Utility/VideoMode.cpp +++ b/src/Nazara/Platform/VideoMode.cpp @@ -1,20 +1,20 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include #include #if defined(NAZARA_PLATFORM_WINDOWS) - #include + #include #elif defined(NAZARA_PLATFORM_X11) - #include + #include #else #error Lack of implementation: Window #endif -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/VideoModeImpl.hpp b/src/Nazara/Platform/VideoModeImpl.hpp similarity index 86% rename from src/Nazara/Utility/VideoModeImpl.hpp rename to src/Nazara/Platform/VideoModeImpl.hpp index e5c5c0118..b5be4b3b1 100644 --- a/src/Nazara/Utility/VideoModeImpl.hpp +++ b/src/Nazara/Platform/VideoModeImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once diff --git a/src/Nazara/Utility/Win32/CursorImpl.cpp b/src/Nazara/Platform/Win32/CursorImpl.cpp similarity index 94% rename from src/Nazara/Utility/Win32/CursorImpl.cpp rename to src/Nazara/Platform/Win32/CursorImpl.cpp index c2fff0a40..399320c59 100644 --- a/src/Nazara/Utility/Win32/CursorImpl.cpp +++ b/src/Nazara/Platform/Win32/CursorImpl.cpp @@ -1,12 +1,12 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include #include #include -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/Win32/CursorImpl.hpp b/src/Nazara/Platform/Win32/CursorImpl.hpp similarity index 88% rename from src/Nazara/Utility/Win32/CursorImpl.hpp rename to src/Nazara/Platform/Win32/CursorImpl.hpp index a8f82377c..ad0324d79 100644 --- a/src/Nazara/Utility/Win32/CursorImpl.hpp +++ b/src/Nazara/Platform/Win32/CursorImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -8,7 +8,7 @@ #define NAZARA_CURSORIMPL_HPP #include -#include +#include #include #include diff --git a/src/Nazara/Utility/Win32/IconImpl.cpp b/src/Nazara/Platform/Win32/IconImpl.cpp similarity index 89% rename from src/Nazara/Utility/Win32/IconImpl.cpp rename to src/Nazara/Platform/Win32/IconImpl.cpp index 19e7fffb0..14a67cfba 100644 --- a/src/Nazara/Utility/Win32/IconImpl.cpp +++ b/src/Nazara/Platform/Win32/IconImpl.cpp @@ -1,11 +1,11 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include #include -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/Win32/IconImpl.hpp b/src/Nazara/Platform/Win32/IconImpl.hpp similarity index 88% rename from src/Nazara/Utility/Win32/IconImpl.hpp rename to src/Nazara/Platform/Win32/IconImpl.hpp index 7ba9acc7a..48644198c 100644 --- a/src/Nazara/Utility/Win32/IconImpl.hpp +++ b/src/Nazara/Platform/Win32/IconImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once diff --git a/src/Nazara/Utility/Win32/InputImpl.cpp b/src/Nazara/Platform/Win32/InputImpl.cpp similarity index 97% rename from src/Nazara/Utility/Win32/InputImpl.cpp rename to src/Nazara/Platform/Win32/InputImpl.cpp index e250ae8be..f44594fa4 100644 --- a/src/Nazara/Utility/Win32/InputImpl.cpp +++ b/src/Nazara/Platform/Win32/InputImpl.cpp @@ -1,12 +1,12 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include -#include +#include #include -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/Win32/InputImpl.hpp b/src/Nazara/Platform/Win32/InputImpl.hpp similarity index 83% rename from src/Nazara/Utility/Win32/InputImpl.hpp rename to src/Nazara/Platform/Win32/InputImpl.hpp index e91bfd889..fc5e226a5 100644 --- a/src/Nazara/Utility/Win32/InputImpl.hpp +++ b/src/Nazara/Platform/Win32/InputImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -9,8 +9,8 @@ #include #include -#include -#include +#include +#include namespace Nz { diff --git a/src/Nazara/Utility/Win32/VideoModeImpl.cpp b/src/Nazara/Platform/Win32/VideoModeImpl.cpp similarity index 83% rename from src/Nazara/Utility/Win32/VideoModeImpl.cpp rename to src/Nazara/Platform/Win32/VideoModeImpl.cpp index 95a964790..6102a568e 100644 --- a/src/Nazara/Utility/Win32/VideoModeImpl.cpp +++ b/src/Nazara/Platform/Win32/VideoModeImpl.cpp @@ -1,12 +1,12 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include +#include +#include #include #include -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/Win32/VideoModeImpl.hpp b/src/Nazara/Platform/Win32/VideoModeImpl.hpp similarity index 79% rename from src/Nazara/Utility/Win32/VideoModeImpl.hpp rename to src/Nazara/Platform/Win32/VideoModeImpl.hpp index 460cec364..39579b9a2 100644 --- a/src/Nazara/Utility/Win32/VideoModeImpl.hpp +++ b/src/Nazara/Platform/Win32/VideoModeImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -7,7 +7,7 @@ #ifndef NAZARA_VIDEOMODEIMPL_HPP #define NAZARA_VIDEOMODEIMPL_HPP -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/Win32/WindowImpl.cpp b/src/Nazara/Platform/Win32/WindowImpl.cpp similarity index 98% rename from src/Nazara/Utility/Win32/WindowImpl.cpp rename to src/Nazara/Platform/Win32/WindowImpl.cpp index c9e94876e..e2278bebb 100644 --- a/src/Nazara/Utility/Win32/WindowImpl.cpp +++ b/src/Nazara/Platform/Win32/WindowImpl.cpp @@ -1,24 +1,24 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp // Un grand merci à Laurent Gomila pour la SFML qui m'aura bien aidé à réaliser cette implémentation -#include +#include #include #include #include #include -#include -#include +#include +#include +#include +#include +#include #include -#include -#include -#include #include #include #include -#include +#include #ifdef _WIN64 #define GCL_HCURSOR GCLP_HCURSOR @@ -907,7 +907,7 @@ namespace Nz } } - #if NAZARA_UTILITY_WINDOWS_DISABLE_MENU_KEYS + #if NAZARA_PLATFORM_WINDOWS_DISABLE_MENU_KEYS // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646360(v=vs.85).aspx if (message == WM_SYSCOMMAND && wParam == SC_KEYMENU) return true; diff --git a/src/Nazara/Utility/Win32/WindowImpl.hpp b/src/Nazara/Platform/Win32/WindowImpl.hpp similarity index 92% rename from src/Nazara/Utility/Win32/WindowImpl.hpp rename to src/Nazara/Platform/Win32/WindowImpl.hpp index 83056f825..1cdaff70e 100644 --- a/src/Nazara/Utility/Win32/WindowImpl.hpp +++ b/src/Nazara/Platform/Win32/WindowImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp // Interface inspirée de la SFML par Laurent Gomila @@ -14,11 +14,11 @@ #include #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include namespace Nz diff --git a/src/Nazara/Utility/Window.cpp b/src/Nazara/Platform/Window.cpp similarity index 88% rename from src/Nazara/Utility/Window.cpp rename to src/Nazara/Platform/Window.cpp index 3130c6641..8bab956b1 100644 --- a/src/Nazara/Utility/Window.cpp +++ b/src/Nazara/Platform/Window.cpp @@ -1,26 +1,23 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include #include -#include #include -#include -#include -#include -#include +#include +#include #if defined(NAZARA_PLATFORM_WINDOWS) - #include + #include #elif defined(NAZARA_PLATFORM_X11) - #include + #include #else #error Lack of implementation: Window #endif -#include +#include namespace Nz { @@ -50,7 +47,7 @@ namespace Nz bool Window::Create(VideoMode mode, const String& title, WindowStyleFlags style) { - // Si la fenêtre est déjà ouverte, nous conservons sa position + // If the window is already open, we keep its position bool opened = IsOpen(); Vector2i position; if (opened) @@ -58,7 +55,7 @@ namespace Nz Destroy(); - // Inspiré du code de la SFML par Laurent Gomila + // Inspired by the code of the SFML by Laurent Gomila (and its team) if (style & WindowStyle_Fullscreen) { if (fullscreenWindow) @@ -101,7 +98,7 @@ namespace Nz return false; } - // Paramètres par défaut + // Default parameters m_impl->EnableKeyRepeat(true); m_impl->EnableSmoothScrolling(false); m_impl->SetMaximumSize(-1, -1); @@ -169,7 +166,7 @@ namespace Nz void Window::EnableKeyRepeat(bool enable) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -182,7 +179,7 @@ namespace Nz void Window::EnableSmoothScrolling(bool enable) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -195,7 +192,7 @@ namespace Nz WindowHandle Window::GetHandle() const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -208,7 +205,7 @@ namespace Nz unsigned int Window::GetHeight() const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -221,7 +218,7 @@ namespace Nz Vector2i Window::GetPosition() const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -234,7 +231,7 @@ namespace Nz Vector2ui Window::GetSize() const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -247,7 +244,7 @@ namespace Nz WindowStyleFlags Window::GetStyle() const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -260,7 +257,7 @@ namespace Nz String Window::GetTitle() const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -273,7 +270,7 @@ namespace Nz unsigned int Window::GetWidth() const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -286,7 +283,7 @@ namespace Nz bool Window::HasFocus() const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -299,7 +296,7 @@ namespace Nz bool Window::IsMinimized() const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -312,7 +309,7 @@ namespace Nz bool Window::IsVisible() const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -325,7 +322,7 @@ namespace Nz bool Window::PollEvent(WindowEvent* event) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -378,7 +375,7 @@ namespace Nz void Window::SetEventListener(bool listener) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -397,7 +394,7 @@ namespace Nz void Window::SetFocus() { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -419,7 +416,7 @@ namespace Nz void Window::SetMaximumSize(const Vector2i& maxSize) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -432,7 +429,7 @@ namespace Nz void Window::SetMaximumSize(int width, int height) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -445,7 +442,7 @@ namespace Nz void Window::SetMinimumSize(const Vector2i& minSize) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -458,7 +455,7 @@ namespace Nz void Window::SetMinimumSize(int width, int height) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -471,7 +468,7 @@ namespace Nz void Window::SetPosition(const Vector2i& position) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -484,7 +481,7 @@ namespace Nz void Window::SetPosition(int x, int y) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -497,7 +494,7 @@ namespace Nz void Window::SetSize(const Vector2i& size) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -510,7 +507,7 @@ namespace Nz void Window::SetSize(unsigned int width, unsigned int height) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -523,7 +520,7 @@ namespace Nz void Window::SetStayOnTop(bool stayOnTop) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -536,7 +533,7 @@ namespace Nz void Window::SetTitle(const String& title) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -549,7 +546,7 @@ namespace Nz void Window::SetVisible(bool visible) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -562,7 +559,7 @@ namespace Nz bool Window::WaitEvent(WindowEvent* event) { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); @@ -626,7 +623,7 @@ namespace Nz void Window::IgnoreNextMouseEvent(int mouseX, int mouseY) const { - #if NAZARA_UTILITY_SAFE + #if NAZARA_PLATFORM_SAFE if (!m_impl) { NazaraError("Window not created"); diff --git a/src/Nazara/Utility/X11/CursorImpl.cpp b/src/Nazara/Platform/X11/CursorImpl.cpp similarity index 96% rename from src/Nazara/Utility/X11/CursorImpl.cpp rename to src/Nazara/Platform/X11/CursorImpl.cpp index aa59290b3..cee8cea88 100644 --- a/src/Nazara/Utility/X11/CursorImpl.cpp +++ b/src/Nazara/Platform/X11/CursorImpl.cpp @@ -1,13 +1,13 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include #include #include -#include -#include +#include +#include #include // Some older versions of xcb/util-renderutil (notably the one available on Travis CI) use `template` as an argument name @@ -20,7 +20,7 @@ extern "C" } #undef template -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/X11/CursorImpl.hpp b/src/Nazara/Platform/X11/CursorImpl.hpp similarity index 89% rename from src/Nazara/Utility/X11/CursorImpl.hpp rename to src/Nazara/Platform/X11/CursorImpl.hpp index 4041b81ed..85b0bf4ef 100644 --- a/src/Nazara/Utility/X11/CursorImpl.hpp +++ b/src/Nazara/Platform/X11/CursorImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -8,7 +8,7 @@ #define NAZARA_CURSORIMPL_HPP #include -#include +#include #include #include diff --git a/src/Nazara/Utility/X11/Display.cpp b/src/Nazara/Platform/X11/Display.cpp similarity index 97% rename from src/Nazara/Utility/X11/Display.cpp rename to src/Nazara/Platform/X11/Display.cpp index 1232cea64..e24c1ef2f 100644 --- a/src/Nazara/Utility/X11/Display.cpp +++ b/src/Nazara/Platform/X11/Display.cpp @@ -1,14 +1,14 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include -#include #include +#include #include #include -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/X11/Display.hpp b/src/Nazara/Platform/X11/Display.hpp similarity index 88% rename from src/Nazara/Utility/X11/Display.hpp rename to src/Nazara/Platform/X11/Display.hpp index 88f80f2ee..37ee8877d 100644 --- a/src/Nazara/Utility/X11/Display.hpp +++ b/src/Nazara/Platform/X11/Display.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -8,8 +8,9 @@ #define NAZARA_X11DISPLAY_HPP #include -#include -#include +#include +#include +#include typedef struct _XCBKeySymbols xcb_key_symbols_t; @@ -17,7 +18,7 @@ namespace Nz { class String; - class NAZARA_UTILITY_API X11 + class NAZARA_PLATFORM_API X11 { public: X11() = delete; diff --git a/src/Nazara/Utility/X11/IconImpl.cpp b/src/Nazara/Platform/X11/IconImpl.cpp similarity index 91% rename from src/Nazara/Utility/X11/IconImpl.cpp rename to src/Nazara/Platform/X11/IconImpl.cpp index 030cbdf8b..5eb266122 100644 --- a/src/Nazara/Utility/X11/IconImpl.cpp +++ b/src/Nazara/Platform/X11/IconImpl.cpp @@ -1,14 +1,13 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include #include #include -#include -#include -#include +#include +#include namespace Nz { diff --git a/src/Nazara/Utility/X11/IconImpl.hpp b/src/Nazara/Platform/X11/IconImpl.hpp similarity index 82% rename from src/Nazara/Utility/X11/IconImpl.hpp rename to src/Nazara/Platform/X11/IconImpl.hpp index 1e8b301bc..e72faa26a 100644 --- a/src/Nazara/Utility/X11/IconImpl.hpp +++ b/src/Nazara/Platform/X11/IconImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -8,7 +8,7 @@ #define NAZARA_ICONIMPL_HPP #include -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/X11/InputImpl.cpp b/src/Nazara/Platform/X11/InputImpl.cpp similarity index 97% rename from src/Nazara/Utility/X11/InputImpl.cpp rename to src/Nazara/Platform/X11/InputImpl.cpp index 7083100db..152ba0337 100644 --- a/src/Nazara/Utility/X11/InputImpl.cpp +++ b/src/Nazara/Platform/X11/InputImpl.cpp @@ -1,16 +1,17 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include -#include -#include +#include +#include +#include #include #include #include #include -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/X11/InputImpl.hpp b/src/Nazara/Platform/X11/InputImpl.hpp similarity index 84% rename from src/Nazara/Utility/X11/InputImpl.hpp rename to src/Nazara/Platform/X11/InputImpl.hpp index 608585b1e..b6c30df0a 100644 --- a/src/Nazara/Utility/X11/InputImpl.hpp +++ b/src/Nazara/Platform/X11/InputImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -10,8 +10,8 @@ #include #include #include -#include -#include +#include +#include namespace Nz { diff --git a/src/Nazara/Utility/X11/ScopedXCB.cpp b/src/Nazara/Platform/X11/ScopedXCB.cpp similarity index 95% rename from src/Nazara/Utility/X11/ScopedXCB.cpp rename to src/Nazara/Platform/X11/ScopedXCB.cpp index 49bd76b26..9911fa760 100644 --- a/src/Nazara/Utility/X11/ScopedXCB.cpp +++ b/src/Nazara/Platform/X11/ScopedXCB.cpp @@ -1,12 +1,12 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include -#include +#include #include -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/X11/ScopedXCB.hpp b/src/Nazara/Platform/X11/ScopedXCB.hpp similarity index 93% rename from src/Nazara/Utility/X11/ScopedXCB.hpp rename to src/Nazara/Platform/X11/ScopedXCB.hpp index 452379bc4..3e6131db2 100644 --- a/src/Nazara/Utility/X11/ScopedXCB.hpp +++ b/src/Nazara/Platform/X11/ScopedXCB.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -10,6 +10,7 @@ #include #include #include +#include namespace Nz { @@ -95,6 +96,6 @@ namespace Nz }; } -#include +#include #endif // NAZARA_SCOPEDXCB_HPP diff --git a/src/Nazara/Utility/X11/ScopedXCB.inl b/src/Nazara/Platform/X11/ScopedXCB.inl similarity index 79% rename from src/Nazara/Utility/X11/ScopedXCB.inl rename to src/Nazara/Platform/X11/ScopedXCB.inl index d9881b9af..13c62bd56 100644 --- a/src/Nazara/Utility/X11/ScopedXCB.inl +++ b/src/Nazara/Platform/X11/ScopedXCB.inl @@ -1,9 +1,8 @@ // Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include +#include namespace Nz { @@ -44,4 +43,4 @@ namespace Nz } } -#include +#include diff --git a/src/Nazara/Utility/X11/VideoModeImpl.cpp b/src/Nazara/Platform/X11/VideoModeImpl.cpp similarity index 94% rename from src/Nazara/Utility/X11/VideoModeImpl.cpp rename to src/Nazara/Platform/X11/VideoModeImpl.cpp index e0b9a5ce7..26a2bc32c 100644 --- a/src/Nazara/Utility/X11/VideoModeImpl.cpp +++ b/src/Nazara/Platform/X11/VideoModeImpl.cpp @@ -1,14 +1,15 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include +#include #include -#include -#include +#include +#include +#include #include #include -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/X11/VideoModeImpl.hpp b/src/Nazara/Platform/X11/VideoModeImpl.hpp similarity index 80% rename from src/Nazara/Utility/X11/VideoModeImpl.hpp rename to src/Nazara/Platform/X11/VideoModeImpl.hpp index 2e63e8a09..fd502b828 100644 --- a/src/Nazara/Utility/X11/VideoModeImpl.hpp +++ b/src/Nazara/Platform/X11/VideoModeImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once @@ -8,7 +8,7 @@ #define NAZARA_VIDEOMODEIMPL_HPP #include -#include +#include namespace Nz { diff --git a/src/Nazara/Utility/X11/WindowImpl.cpp b/src/Nazara/Platform/X11/WindowImpl.cpp similarity index 98% rename from src/Nazara/Utility/X11/WindowImpl.cpp rename to src/Nazara/Platform/X11/WindowImpl.cpp index 884244287..278e6fec8 100644 --- a/src/Nazara/Utility/X11/WindowImpl.cpp +++ b/src/Nazara/Platform/X11/WindowImpl.cpp @@ -1,26 +1,25 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp // Un grand merci à Laurent Gomila pour la SFML qui m'aura bien aidé à réaliser cette implémentation -#include +#include #include #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include #include -#include #include -#include +#include /* Things to do left: diff --git a/src/Nazara/Utility/X11/WindowImpl.hpp b/src/Nazara/Platform/X11/WindowImpl.hpp similarity index 94% rename from src/Nazara/Utility/X11/WindowImpl.hpp rename to src/Nazara/Platform/X11/WindowImpl.hpp index d82ff06cc..0bd286944 100644 --- a/src/Nazara/Utility/X11/WindowImpl.hpp +++ b/src/Nazara/Platform/X11/WindowImpl.hpp @@ -1,5 +1,5 @@ // Copyright (C) 2015 Jérôme Leclercq -// This file is part of the "Nazara Engine - Utility module" +// This file is part of the "Nazara Engine - Platform module" // For conditions of distribution and use, see copyright notice in Config.hpp // Interface inspirée de la SFML par Laurent Gomila @@ -12,9 +12,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include #include #include diff --git a/src/Nazara/Renderer/DebugDrawer.cpp b/src/Nazara/Renderer/DebugDrawer.cpp index 9357d17f9..ef6136b31 100644 --- a/src/Nazara/Renderer/DebugDrawer.cpp +++ b/src/Nazara/Renderer/DebugDrawer.cpp @@ -4,17 +4,17 @@ #include #include -#include #include #include #include #include +#include #include #include +#include #include #include #include -#include #include ///TODO: Améliorer diff --git a/src/Nazara/Renderer/GLX/ContextImpl.cpp b/src/Nazara/Renderer/GLX/ContextImpl.cpp index 8bff9793a..2f25e680d 100644 --- a/src/Nazara/Renderer/GLX/ContextImpl.cpp +++ b/src/Nazara/Renderer/GLX/ContextImpl.cpp @@ -50,7 +50,7 @@ namespace Nz } } - bool ContextImpl::Activate() + bool ContextImpl::Activate() const { return glXMakeCurrent(m_display, m_window, m_context) == true; } diff --git a/src/Nazara/Renderer/GLX/ContextImpl.hpp b/src/Nazara/Renderer/GLX/ContextImpl.hpp index 7508537d1..7aaf6409f 100644 --- a/src/Nazara/Renderer/GLX/ContextImpl.hpp +++ b/src/Nazara/Renderer/GLX/ContextImpl.hpp @@ -19,7 +19,7 @@ namespace Nz ContextImpl(); ~ContextImpl(); - bool Activate(); + bool Activate() const; bool Create(ContextParameters& parameters); diff --git a/src/Nazara/Renderer/GlslWriter.cpp b/src/Nazara/Renderer/GlslWriter.cpp new file mode 100644 index 000000000..074082165 --- /dev/null +++ b/src/Nazara/Renderer/GlslWriter.cpp @@ -0,0 +1,451 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Renderer module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include +#include + +namespace Nz +{ + GlslWriter::GlslWriter() : + m_currentFunction(nullptr), + m_currentState(nullptr), + m_glslVersion(110) + { + } + + String GlslWriter::Generate(const ShaderAst::StatementPtr& node) + { + State state; + m_currentState = &state; + CallOnExit onExit([this]() + { + m_currentState = nullptr; + }); + + // Register global variables (uniforms, varying, ..) + node->Register(*this); + + // Header + Append("#version "); + AppendLine(String::Number(m_glslVersion)); + AppendLine(); + + // Global variables (uniforms, input and outputs) + DeclareVariables(state.uniforms, "uniform", "Uniforms"); + DeclareVariables(state.inputs, "in", "Inputs"); + DeclareVariables(state.outputs, "out", "Outputs"); + + Function entryPoint; + entryPoint.name = "main"; //< GLSL has only one entry point name possible + entryPoint.node = node; + entryPoint.retType = ShaderAst::ExpressionType::Void; + + AppendFunction(entryPoint); + + return state.stream; + } + + void GlslWriter::RegisterFunction(const String& name, ShaderAst::StatementPtr statement, std::initializer_list parameters, ShaderAst::ExpressionType retType) + { + Function func; + func.retType = retType; + func.name = name; + func.node = std::move(statement); + func.parameters.assign(parameters); + + m_functions[name] = std::move(func); + } + + void GlslWriter::RegisterVariable(ShaderAst::VariableType kind, const String& name, ShaderAst::ExpressionType type) + { + NazaraAssert(m_currentState, "This function should only be called while processing an AST"); + NazaraAssert(kind != ShaderAst::VariableType::Builtin, "Builtin variables should not be registered"); + + switch (kind) + { + case ShaderAst::VariableType::Builtin: //< Only there to make compiler happy + break; + + case ShaderAst::VariableType::Input: + m_currentState->inputs.insert(std::make_pair(type, name)); + break; + + case ShaderAst::VariableType::Output: + m_currentState->outputs.insert(std::make_pair(type, name)); + break; + + case ShaderAst::VariableType::Parameter: + { + if (m_currentFunction) + { + bool found = false; + for (const auto& varPtr : m_currentFunction->parameters) + { + if (varPtr->name == name) + { + found = true; + if (varPtr->type != type) + { + //TODO: AstParseError + throw std::runtime_error("Function uses parameter \"" + name + "\" with a different type than specified in the function arguments"); + } + + break; + } + } + + if (!found) + //TODO: AstParseError + throw std::runtime_error("Function has no parameter \"" + name + "\""); + } + + break; + } + + case ShaderAst::VariableType::Uniform: + m_currentState->uniforms.insert(std::make_pair(type, name)); + break; + + case ShaderAst::VariableType::Variable: + { + if (m_currentFunction) + m_currentFunction->variables.insert(std::make_pair(type, name)); + + break; + } + } + } + + void GlslWriter::SetGlslVersion(unsigned int version) + { + m_glslVersion = version; + } + + void GlslWriter::Write(const ShaderAst::NodePtr& node) + { + node->Visit(*this); + } + + void GlslWriter::Write(const ShaderAst::AssignOp& node) + { + Write(node.variable); + + switch (node.op) + { + case ShaderAst::AssignType::Simple: + Append(" = "); + break; + } + + Write(node.right); + } + + void GlslWriter::Write(const ShaderAst::Branch& node) + { + bool first = true; + for (const auto& statement : node.condStatements) + { + if (!first) + Append("else "); + + Append("if ("); + Write(statement.condition); + AppendLine(")"); + + EnterScope(); + Write(statement.statement); + LeaveScope(); + + first = false; + } + + if (node.elseStatement) + { + AppendLine("else"); + + EnterScope(); + Write(node.elseStatement); + LeaveScope(); + } + } + + void GlslWriter::Write(const ShaderAst::BinaryOp& node) + { + Write(node.left); + + switch (node.op) + { + case ShaderAst::BinaryType::Add: + Append(" + "); + break; + case ShaderAst::BinaryType::Substract: + Append(" - "); + break; + case ShaderAst::BinaryType::Multiply: + Append(" * "); + break; + case ShaderAst::BinaryType::Divide: + Append(" / "); + break; + case ShaderAst::BinaryType::Equality: + Append(" == "); + break; + } + + Write(node.right); + } + + void GlslWriter::Write(const ShaderAst::BuiltinVariable& node) + { + Append(node.var); + } + + void GlslWriter::Write(const ShaderAst::Cast& node) + { + Append(node.exprType); + Append("("); + + unsigned int i = 0; + unsigned int requiredComponents = ShaderAst::Node::GetComponentCount(node.exprType); + while (requiredComponents > 0) + { + if (i != 0) + m_currentState->stream << ", "; + + const auto& exprPtr = node.expressions[i++]; + NazaraAssert(exprPtr, "Invalid expression"); + + Write(exprPtr); + requiredComponents -= ShaderAst::Node::GetComponentCount(exprPtr->GetExpressionType()); + } + + Append(")"); + } + + void GlslWriter::Write(const ShaderAst::Constant& node) + { + switch (node.exprType) + { + case ShaderAst::ExpressionType::Boolean: + Append((node.values.bool1) ? "true" : "false"); + break; + + case ShaderAst::ExpressionType::Float1: + Append(String::Format("%F", node.values.vec1)); + break; + + case ShaderAst::ExpressionType::Float2: + Append(String::Format("vec2(%F, %F)", node.values.vec2.x, node.values.vec2.y)); + break; + + case ShaderAst::ExpressionType::Float3: + Append(String::Format("vec3(%F, %F, %F)", node.values.vec3.x, node.values.vec3.y, node.values.vec3.z)); + break; + + case ShaderAst::ExpressionType::Float4: + Append(String::Format("vec4(%F, %F, %F, %F)", node.values.vec4.x, node.values.vec4.y, node.values.vec4.z, node.values.vec4.w)); + break; + + default: + throw std::runtime_error("Unhandled expression type"); + } + } + + void GlslWriter::Write(const ShaderAst::ExpressionStatement& node) + { + Write(node.expression); + Append(";"); + } + + void GlslWriter::Write(const ShaderAst::NamedVariable& node) + { + Append(node.name); + } + + void GlslWriter::Write(const ShaderAst::StatementBlock& node) + { + bool first = true; + for (const ShaderAst::StatementPtr& statement : node.statements) + { + if (!first) + AppendLine(); + + Write(statement); + + first = false; + } + } + + void GlslWriter::Write(const ShaderAst::SwizzleOp& node) + { + Write(node.expression); + Append("."); + + for (std::size_t i = 0; i < node.componentCount; ++i) + { + switch (node.components[i]) + { + case ShaderAst::SwizzleComponent::First: + Append("x"); + break; + + case ShaderAst::SwizzleComponent::Second: + Append("y"); + break; + + case ShaderAst::SwizzleComponent::Third: + Append("z"); + break; + + case ShaderAst::SwizzleComponent::Fourth: + Append("w"); + break; + } + } + } + + void GlslWriter::Append(ShaderAst::BuiltinEntry builtin) + { + switch (builtin) + { + case ShaderAst::BuiltinEntry::VertexPosition: + Append("gl_Position"); + break; + } + } + + void GlslWriter::Append(ShaderAst::ExpressionType type) + { + switch (type) + { + case ShaderAst::ExpressionType::Boolean: + Append("bool"); + break; + case ShaderAst::ExpressionType::Float1: + Append("float"); + break; + case ShaderAst::ExpressionType::Float2: + Append("vec2"); + break; + case ShaderAst::ExpressionType::Float3: + Append("vec3"); + break; + case ShaderAst::ExpressionType::Float4: + Append("vec4"); + break; + case ShaderAst::ExpressionType::Mat4x4: + Append("mat4"); + break; + case ShaderAst::ExpressionType::Void: + Append("void"); + break; + } + } + + void GlslWriter::Append(const String& txt) + { + NazaraAssert(m_currentState, "This function should only be called while processing an AST"); + + m_currentState->stream << txt; + } + + void GlslWriter::AppendCommentSection(const String& section) + { + NazaraAssert(m_currentState, "This function should only be called while processing an AST"); + + String stars((section.GetSize() < 33) ? (36 - section.GetSize()) / 2 : 3, '*'); + m_currentState->stream << "/*" << stars << ' ' << section << ' ' << stars << "*/"; + AppendLine(); + } + + void GlslWriter::AppendFunction(Function& func) + { + NazaraAssert(!m_currentFunction, "A function is already being processed"); + NazaraAssert(m_currentState, "This function should only be called while processing an AST"); + + m_currentFunction = &func; + CallOnExit onExit([this] () + { + m_currentFunction = nullptr; + }); + + func.node->Register(*this); + + Append(func.retType); + + m_currentState->stream << ' '; + Append(func.name); + + m_currentState->stream << '('; + for (std::size_t i = 0; i < func.parameters.size(); ++i) + { + if (i != 0) + m_currentState->stream << ", "; + + Append(func.parameters[i]->type); + m_currentState->stream << ' '; + Append(func.parameters[i]->name); + } + m_currentState->stream << ")\n"; + + EnterScope(); + { + DeclareVariables(func.variables); + + Write(func.node); + } + LeaveScope(); + } + + void GlslWriter::AppendLine(const String& txt) + { + NazaraAssert(m_currentState, "This function should only be called while processing an AST"); + + m_currentState->stream << txt << '\n' << String(m_currentState->indentLevel, '\t'); + } + + void GlslWriter::DeclareVariables(const VariableContainer& variables, const String& keyword, const String& section) + { + if (!variables.empty()) + { + if (!section.IsEmpty()) + AppendCommentSection(section); + + for (const auto& pair : variables) + { + if (!keyword.IsEmpty()) + { + Append(keyword); + Append(" "); + } + + Append(pair.first); + Append(" "); + Append(pair.second); + AppendLine(";"); + } + + AppendLine(); + } + } + + void GlslWriter::EnterScope() + { + NazaraAssert(m_currentState, "This function should only be called while processing an AST"); + + m_currentState->indentLevel++; + AppendLine("{"); + } + + void GlslWriter::LeaveScope() + { + NazaraAssert(m_currentState, "This function should only be called while processing an AST"); + + m_currentState->indentLevel--; + AppendLine(); + AppendLine("}"); + } + +} diff --git a/src/Nazara/Renderer/GpuQuery.cpp b/src/Nazara/Renderer/GpuQuery.cpp index ce3235e63..dcc73f38a 100644 --- a/src/Nazara/Renderer/GpuQuery.cpp +++ b/src/Nazara/Renderer/GpuQuery.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include diff --git a/src/Nazara/Renderer/HardwareBuffer.cpp b/src/Nazara/Renderer/HardwareBuffer.cpp index 52bc339c2..682f4392a 100644 --- a/src/Nazara/Renderer/HardwareBuffer.cpp +++ b/src/Nazara/Renderer/HardwareBuffer.cpp @@ -3,13 +3,11 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include #include #include -#include #include namespace Nz @@ -50,7 +48,8 @@ namespace Nz UInt32 totalSize = m_parent->GetSize(); - bool forceDiscard = (size == totalSize); + //bool forceDiscard = (size == totalSize); + bool forceDiscard = true; OpenGL::BindBuffer(m_type, m_buffer); diff --git a/src/Nazara/Renderer/OpenGL.cpp b/src/Nazara/Renderer/OpenGL.cpp index 455247952..b748c8e7d 100644 --- a/src/Nazara/Renderer/OpenGL.cpp +++ b/src/Nazara/Renderer/OpenGL.cpp @@ -6,13 +6,12 @@ #include #include #include -#include #include +#include #include #if defined(NAZARA_PLATFORM_GLX) -#include +#include #endif // NAZARA_PLATFORM_GLX -#include #include #include #include diff --git a/src/Nazara/Renderer/RenderWindow.cpp b/src/Nazara/Renderer/RenderWindow.cpp index 61c299bf7..bc7210975 100644 --- a/src/Nazara/Renderer/RenderWindow.cpp +++ b/src/Nazara/Renderer/RenderWindow.cpp @@ -9,8 +9,6 @@ #include #include #include -#include -#include #include namespace Nz diff --git a/src/Nazara/Renderer/Renderer.cpp b/src/Nazara/Renderer/Renderer.cpp index 39405c38b..5461ad510 100644 --- a/src/Nazara/Renderer/Renderer.cpp +++ b/src/Nazara/Renderer/Renderer.cpp @@ -13,22 +13,25 @@ #include #include #include +#include +#include #include #include #include #include +#include #include +#include #include +#include #include -#include #include #include #include #include +#include #include #include -#include -#include #include #include #include @@ -40,14 +43,6 @@ namespace Nz { namespace { - const UInt8 r_coreFragmentShader[] = { - #include - }; - - const UInt8 r_coreVertexShader[] = { - #include - }; - enum ObjectType { ObjectType_Context, @@ -579,9 +574,9 @@ namespace Nz } // Initialisation des dépendances - if (!Utility::Initialize()) + if (!Platform::Initialize()) { - NazaraError("Failed to initialize Utility module"); + NazaraError("Failed to initialize Platform module"); return false; } @@ -719,34 +714,12 @@ namespace Nz return false; } - // Création du shader de Debug - ShaderRef debugShader = Shader::New(); - if (!debugShader->Create()) + if (!GenerateDebugShader()) { - NazaraError("Failed to create debug shader"); + NazaraError("Failed to generate debug shader"); return false; } - if (!debugShader->AttachStageFromSource(ShaderStageType_Fragment, reinterpret_cast(r_coreFragmentShader), sizeof(r_coreFragmentShader))) - { - NazaraError("Failed to attach fragment stage"); - return false; - } - - if (!debugShader->AttachStageFromSource(ShaderStageType_Vertex, reinterpret_cast(r_coreVertexShader), sizeof(r_coreVertexShader))) - { - NazaraError("Failed to attach vertex stage"); - return false; - } - - if (!debugShader->Link()) - { - NazaraError("Failed to link shader"); - return false; - } - - ShaderLibrary::Register("DebugSimple", debugShader); - onExit.Reset(); NazaraNotice("Initialized: Renderer module"); @@ -1402,7 +1375,7 @@ namespace Nz NazaraNotice("Uninitialized: Renderer module"); // Libération des dépendances - Utility::Uninitialize(); + Platform::Uninitialize(); } void Renderer::EnableInstancing(bool instancing) @@ -1869,6 +1842,74 @@ namespace Nz return true; } + bool Renderer::GenerateDebugShader() + { + GlslWriter writer; + writer.SetGlslVersion(OpenGL::GetGLSLVersion()); + + String fragmentShader; + String vertexShader; + + try + { + using namespace ShaderBuilder; + using ShaderAst::BuiltinEntry; + using ShaderAst::ExpressionType; + + // Fragment shader + { + auto rt0 = Output("RenderTarget0", ExpressionType::Float4); + auto color = Uniform("Color", ExpressionType::Float4); + + fragmentShader = writer.Generate(ExprStatement(Assign(rt0, color))); + } + + // Vertex shader + { + auto vertexPosition = Input("VertexPosition", ExpressionType::Float3); + auto wvpMatrix = Uniform("WorldViewProjMatrix", ExpressionType::Mat4x4); + auto builtinPos = Builtin(BuiltinEntry::VertexPosition); + + vertexShader = writer.Generate(ExprStatement(Assign(builtinPos, Multiply(wvpMatrix, Cast(vertexPosition, Constant(1.f)))))); + } + } + catch (const std::exception& e) + { + NazaraError("Failed to generate shader code: " + String(e.what())); + return false; + } + + + ShaderRef debugShader = Shader::New(); + if (!debugShader->Create()) + { + NazaraError("Failed to create debug shader"); + return false; + } + + if (!debugShader->AttachStageFromSource(ShaderStageType_Fragment, fragmentShader)) + { + NazaraError("Failed to attach fragment stage"); + return false; + } + + if (!debugShader->AttachStageFromSource(ShaderStageType_Vertex, vertexShader)) + { + NazaraError("Failed to attach vertex stage"); + return false; + } + + if (!debugShader->Link()) + { + NazaraError("Failed to link shader"); + return false; + } + + ShaderLibrary::Register("DebugSimple", debugShader); + + return true; + } + void Renderer::OnContextRelease(const Context* context) { s_vaos.erase(context); diff --git a/src/Nazara/Renderer/Resources/Shaders/Debug/core.frag b/src/Nazara/Renderer/Resources/Shaders/Debug/core.frag deleted file mode 100644 index 4bb28b00c..000000000 --- a/src/Nazara/Renderer/Resources/Shaders/Debug/core.frag +++ /dev/null @@ -1,13 +0,0 @@ -#version 140 - -/********************Sortant********************/ -out vec4 RenderTarget0; - -/********************Uniformes********************/ -uniform vec4 Color; - -/********************Fonctions********************/ -void main() -{ - RenderTarget0 = Color; -} \ No newline at end of file diff --git a/src/Nazara/Renderer/Resources/Shaders/Debug/core.frag.h b/src/Nazara/Renderer/Resources/Shaders/Debug/core.frag.h deleted file mode 100644 index bbb324c3c..000000000 --- a/src/Nazara/Renderer/Resources/Shaders/Debug/core.frag.h +++ /dev/null @@ -1 +0,0 @@ -35,118,101,114,115,105,111,110,32,49,52,48,13,10,13,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,83,111,114,116,97,110,116,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,13,10,111,117,116,32,118,101,99,52,32,82,101,110,100,101,114,84,97,114,103,101,116,48,59,13,10,13,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,85,110,105,102,111,114,109,101,115,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,13,10,117,110,105,102,111,114,109,32,118,101,99,52,32,67,111,108,111,114,59,13,10,13,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,70,111,110,99,116,105,111,110,115,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,13,10,118,111,105,100,32,109,97,105,110,40,41,13,10,123,13,10,9,82,101,110,100,101,114,84,97,114,103,101,116,48,32,61,32,67,111,108,111,114,59,13,10,125, \ No newline at end of file diff --git a/src/Nazara/Renderer/Resources/Shaders/Debug/core.vert b/src/Nazara/Renderer/Resources/Shaders/Debug/core.vert deleted file mode 100644 index e7806ffdf..000000000 --- a/src/Nazara/Renderer/Resources/Shaders/Debug/core.vert +++ /dev/null @@ -1,13 +0,0 @@ -#version 140 - -/********************Entrant********************/ -in vec3 VertexPosition; - -/********************Uniformes********************/ -uniform mat4 WorldViewProjMatrix; - -/********************Fonctions********************/ -void main() -{ - gl_Position = WorldViewProjMatrix * vec4(VertexPosition, 1.0); -} diff --git a/src/Nazara/Renderer/Resources/Shaders/Debug/core.vert.h b/src/Nazara/Renderer/Resources/Shaders/Debug/core.vert.h deleted file mode 100644 index 48c552e2d..000000000 --- a/src/Nazara/Renderer/Resources/Shaders/Debug/core.vert.h +++ /dev/null @@ -1 +0,0 @@ -35,118,101,114,115,105,111,110,32,49,52,48,13,10,13,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,69,110,116,114,97,110,116,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,13,10,105,110,32,118,101,99,51,32,86,101,114,116,101,120,80,111,115,105,116,105,111,110,59,13,10,13,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,85,110,105,102,111,114,109,101,115,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,13,10,117,110,105,102,111,114,109,32,109,97,116,52,32,87,111,114,108,100,86,105,101,119,80,114,111,106,77,97,116,114,105,120,59,13,10,13,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,70,111,110,99,116,105,111,110,115,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,13,10,118,111,105,100,32,109,97,105,110,40,41,13,10,123,13,10,9,103,108,95,80,111,115,105,116,105,111,110,32,61,32,87,111,114,108,100,86,105,101,119,80,114,111,106,77,97,116,114,105,120,32,42,32,118,101,99,52,40,86,101,114,116,101,120,80,111,115,105,116,105,111,110,44,32,49,46,48,41,59,13,10,125,13,10, \ No newline at end of file diff --git a/src/Nazara/Renderer/Shader.cpp b/src/Nazara/Renderer/Shader.cpp index 5b9c95cab..bfef4c12d 100644 --- a/src/Nazara/Renderer/Shader.cpp +++ b/src/Nazara/Renderer/Shader.cpp @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include +#include #include #include #include diff --git a/src/Nazara/Renderer/ShaderAst.cpp b/src/Nazara/Renderer/ShaderAst.cpp new file mode 100644 index 000000000..ef6860d68 --- /dev/null +++ b/src/Nazara/Renderer/ShaderAst.cpp @@ -0,0 +1,196 @@ +// Copyright (C) 2016 Jérôme Leclercq +// This file is part of the "Nazara Engine - Renderer module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include +#include + +namespace Nz { namespace ShaderAst +{ + void ExpressionStatement::Register(ShaderWriter& visitor) + { + expression->Register(visitor); + } + + void ExpressionStatement::Visit(ShaderWriter& visitor) + { + visitor.Write(*this); + } + + + void ConditionalStatement::Register(ShaderWriter& visitor) + { + if (visitor.IsConditionEnabled(conditionName)) + statement->Register(visitor); + } + + void ConditionalStatement::Visit(ShaderWriter& visitor) + { + if (visitor.IsConditionEnabled(conditionName)) + statement->Visit(visitor); + } + + + void StatementBlock::Register(ShaderWriter& visitor) + { + for (auto& statementPtr : statements) + statementPtr->Register(visitor); + } + + void StatementBlock::Visit(ShaderWriter& visitor) + { + visitor.Write(*this); + } + + + ExpressionType Variable::GetExpressionType() const + { + return type; + } + + void NamedVariable::Register(ShaderWriter& visitor) + { + visitor.RegisterVariable(kind, name, type); + } + + void NamedVariable::Visit(ShaderWriter& visitor) + { + visitor.Write(*this); + } + + + void BuiltinVariable::Register(ShaderWriter& visitor) + { + } + + void BuiltinVariable::Visit(ShaderWriter& visitor) + { + visitor.Write(*this); + } + + + ExpressionType AssignOp::GetExpressionType() const + { + return variable->GetExpressionType(); + } + + void AssignOp::Register(ShaderWriter& visitor) + { + variable->Register(visitor); + right->Register(visitor); + } + + void AssignOp::Visit(ShaderWriter& visitor) + { + visitor.Write(*this); + } + + + ExpressionType BinaryOp::GetExpressionType() const + { + ShaderAst::ExpressionType exprType = ShaderAst::ExpressionType::Void; + + switch (op) + { + case ShaderAst::BinaryType::Add: + case ShaderAst::BinaryType::Divide: + case ShaderAst::BinaryType::Multiply: + case ShaderAst::BinaryType::Substract: + exprType = left->GetExpressionType(); + break; + + case ShaderAst::BinaryType::Equality: + exprType = ExpressionType::Boolean; + } + + NazaraAssert(exprType != ShaderAst::ExpressionType::Void, "Unhandled builtin"); + + return exprType; + } + + void BinaryOp::Register(ShaderWriter& visitor) + { + left->Register(visitor); + right->Register(visitor); + } + + void BinaryOp::Visit(ShaderWriter& visitor) + { + visitor.Write(*this); + } + + + void Branch::Register(ShaderWriter& visitor) + { + for (ConditionalStatement& statement : condStatements) + { + statement.condition->Register(visitor); + statement.statement->Register(visitor); + } + + if (elseStatement) + elseStatement->Register(visitor); + } + + void Branch::Visit(ShaderWriter& visitor) + { + visitor.Write(*this); + } + + + ExpressionType Constant::GetExpressionType() const + { + return exprType; + } + + void Constant::Register(ShaderWriter&) + { + } + + void Constant::Visit(ShaderWriter& visitor) + { + visitor.Write(*this); + } + + ExpressionType Cast::GetExpressionType() const + { + return exprType; + } + + void Cast::Register(ShaderWriter& visitor) + { + auto it = expressions.begin(); + (*it)->Register(visitor); + + for (; it != expressions.end(); ++it) + { + if (!*it) + break; + + (*it)->Register(visitor); + } + } + + void Cast::Visit(ShaderWriter& visitor) + { + visitor.Write(*this); + } + + + ExpressionType ShaderAst::SwizzleOp::GetExpressionType() const + { + return GetComponentType(expression->GetExpressionType()); + } + + void SwizzleOp::Register(ShaderWriter& visitor) + { + expression->Register(visitor); + } + + void SwizzleOp::Visit(ShaderWriter& visitor) + { + visitor.Write(*this); + } +} +} diff --git a/src/Nazara/Renderer/ShaderStage.cpp b/src/Nazara/Renderer/ShaderStage.cpp index 98f863d59..29f434091 100644 --- a/src/Nazara/Renderer/ShaderStage.cpp +++ b/src/Nazara/Renderer/ShaderStage.cpp @@ -161,7 +161,7 @@ namespace Nz #endif const char* tmp = source.GetConstBuffer(); - GLint length = source.GetSize(); + GLint length = static_cast(source.GetSize()); glShaderSource(m_id, 1, &tmp, &length); } diff --git a/src/Nazara/Renderer/ShaderWriter.cpp b/src/Nazara/Renderer/ShaderWriter.cpp new file mode 100644 index 000000000..c862572ab --- /dev/null +++ b/src/Nazara/Renderer/ShaderWriter.cpp @@ -0,0 +1,24 @@ +// Copyright (C) 2015 Jérôme Leclercq +// This file is part of the "Nazara Engine - Renderer module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include + +namespace Nz +{ + ShaderWriter::~ShaderWriter() = default; + + void ShaderWriter::EnableCondition(const String& name, bool cond) + { + if (cond) + m_conditions.insert(name); + else + m_conditions.erase(name); + } + + bool ShaderWriter::IsConditionEnabled(const String & name) const + { + return m_conditions.count(name) != 0; + } +} diff --git a/src/Nazara/Renderer/Texture.cpp b/src/Nazara/Renderer/Texture.cpp index 9feb83de1..bba567cf4 100644 --- a/src/Nazara/Renderer/Texture.cpp +++ b/src/Nazara/Renderer/Texture.cpp @@ -10,8 +10,6 @@ #include #include #include -#include -#include #include namespace Nz diff --git a/src/Nazara/Renderer/UberShaderInstance.cpp b/src/Nazara/Renderer/UberShaderInstance.cpp index cef1c517e..965995b92 100644 --- a/src/Nazara/Renderer/UberShaderInstance.cpp +++ b/src/Nazara/Renderer/UberShaderInstance.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include namespace Nz diff --git a/src/Nazara/Renderer/UberShaderPreprocessor.cpp b/src/Nazara/Renderer/UberShaderPreprocessor.cpp index b6d524645..50eed66ac 100644 --- a/src/Nazara/Renderer/UberShaderPreprocessor.cpp +++ b/src/Nazara/Renderer/UberShaderPreprocessor.cpp @@ -5,10 +5,9 @@ #include #include #include -#include +#include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Renderer/Win32/ContextImpl.cpp b/src/Nazara/Renderer/Win32/ContextImpl.cpp index e99e672dc..9c50faabd 100644 --- a/src/Nazara/Renderer/Win32/ContextImpl.cpp +++ b/src/Nazara/Renderer/Win32/ContextImpl.cpp @@ -20,7 +20,7 @@ namespace Nz { } - bool ContextImpl::Activate() + bool ContextImpl::Activate() const { return wglMakeCurrent(m_deviceContext, m_context) == TRUE; } diff --git a/src/Nazara/Renderer/Win32/ContextImpl.hpp b/src/Nazara/Renderer/Win32/ContextImpl.hpp index b9ac2c460..0f982f18c 100644 --- a/src/Nazara/Renderer/Win32/ContextImpl.hpp +++ b/src/Nazara/Renderer/Win32/ContextImpl.hpp @@ -18,7 +18,7 @@ namespace Nz public: ContextImpl(); - bool Activate(); + bool Activate() const; bool Create(ContextParameters& parameters); diff --git a/src/Nazara/Utility/AlgorithmUtility.cpp b/src/Nazara/Utility/AlgorithmUtility.cpp index d37d02f96..111c45f1e 100644 --- a/src/Nazara/Utility/AlgorithmUtility.cpp +++ b/src/Nazara/Utility/AlgorithmUtility.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -26,11 +26,13 @@ */ #include -#include #include +#include #include #include #include +#include +#include namespace Nz { diff --git a/src/Nazara/Utility/Animation.cpp b/src/Nazara/Utility/Animation.cpp index eb53424fe..f851a430b 100644 --- a/src/Nazara/Utility/Animation.cpp +++ b/src/Nazara/Utility/Animation.cpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include #include #include @@ -88,8 +90,8 @@ namespace Nz { Joint* joint = targetSkeleton->GetJoint(i); - SequenceJoint& sequenceJointA = m_impl->sequenceJoints[frameA*m_impl->jointCount + i]; - SequenceJoint& sequenceJointB = m_impl->sequenceJoints[frameB*m_impl->jointCount + i]; + const SequenceJoint& sequenceJointA = m_impl->sequenceJoints[frameA*m_impl->jointCount + i]; + const SequenceJoint& sequenceJointB = m_impl->sequenceJoints[frameB*m_impl->jointCount + i]; joint->SetPosition(Vector3f::Lerp(sequenceJointA.position, sequenceJointB.position, interpolation)); joint->SetRotation(Quaternionf::Slerp(sequenceJointA.rotation, sequenceJointB.rotation, interpolation)); diff --git a/src/Nazara/Utility/Buffer.cpp b/src/Nazara/Utility/Buffer.cpp index e65488d28..99b87a685 100644 --- a/src/Nazara/Utility/Buffer.cpp +++ b/src/Nazara/Utility/Buffer.cpp @@ -9,9 +9,7 @@ #include #include #include -#include #include -#include #include namespace Nz diff --git a/src/Nazara/Utility/Formats/DDSLoader.cpp b/src/Nazara/Utility/Formats/DDSLoader.cpp index ad2ff9969..dd24a1469 100644 --- a/src/Nazara/Utility/Formats/DDSLoader.cpp +++ b/src/Nazara/Utility/Formats/DDSLoader.cpp @@ -5,11 +5,9 @@ #include #include #include -#include #include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Utility/Formats/MD2Loader.cpp b/src/Nazara/Utility/Formats/MD2Loader.cpp index 76ee1c1ea..01286f886 100644 --- a/src/Nazara/Utility/Formats/MD2Loader.cpp +++ b/src/Nazara/Utility/Formats/MD2Loader.cpp @@ -6,15 +6,12 @@ #include #include #include -#include #include #include #include #include #include #include -#include -#include #include #include @@ -219,13 +216,16 @@ namespace Nz Nz::Matrix4f matrix = Matrix4f::Transform(translate, rotationQuat, scale); matrix *= parameters.matrix; + Nz::Matrix4f normalMatrix = Matrix4f::Rotate(rotationQuat); + normalMatrix *= parameters.matrix; + for (unsigned int v = 0; v < header.num_vertices; ++v) { const MD2_Vertex& vert = vertices[v]; Vector3f position = matrix * Vector3f(vert.x, vert.y, vert.z); vertex->position = position; - vertex->normal = rotationQuat * md2Normals[vert.n]; + vertex->normal = normalMatrix.Transform(md2Normals[vert.n], 0.f); vertex++; } diff --git a/src/Nazara/Utility/Formats/MD5AnimLoader.cpp b/src/Nazara/Utility/Formats/MD5AnimLoader.cpp index 026c9e5d7..e67389409 100644 --- a/src/Nazara/Utility/Formats/MD5AnimLoader.cpp +++ b/src/Nazara/Utility/Formats/MD5AnimLoader.cpp @@ -3,7 +3,10 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include +#include #include +#include +#include #include namespace Nz diff --git a/src/Nazara/Utility/Formats/MD5AnimParser.cpp b/src/Nazara/Utility/Formats/MD5AnimParser.cpp index 5930fe5a3..145811afc 100644 --- a/src/Nazara/Utility/Formats/MD5AnimParser.cpp +++ b/src/Nazara/Utility/Formats/MD5AnimParser.cpp @@ -4,13 +4,8 @@ #include #include -#include #include -#include -#include #include -#include -#include #include namespace Nz diff --git a/src/Nazara/Utility/Formats/MD5MeshLoader.cpp b/src/Nazara/Utility/Formats/MD5MeshLoader.cpp index 5284d1d2c..efb8f9d5e 100644 --- a/src/Nazara/Utility/Formats/MD5MeshLoader.cpp +++ b/src/Nazara/Utility/Formats/MD5MeshLoader.cpp @@ -5,8 +5,11 @@ #include #include #include +#include #include +#include #include +#include #include #include #include diff --git a/src/Nazara/Utility/Formats/MD5MeshParser.cpp b/src/Nazara/Utility/Formats/MD5MeshParser.cpp index 470e9a41a..04816746d 100644 --- a/src/Nazara/Utility/Formats/MD5MeshParser.cpp +++ b/src/Nazara/Utility/Formats/MD5MeshParser.cpp @@ -4,18 +4,8 @@ #include #include -#include -#include #include -#include -#include -#include -#include -#include -#include #include -#include -#include #include #include diff --git a/src/Nazara/Utility/Formats/MTLParser.cpp b/src/Nazara/Utility/Formats/MTLParser.cpp index 894f20f02..d001588a4 100644 --- a/src/Nazara/Utility/Formats/MTLParser.cpp +++ b/src/Nazara/Utility/Formats/MTLParser.cpp @@ -4,11 +4,8 @@ #include #include -#include -#include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Utility/Formats/OBJLoader.cpp b/src/Nazara/Utility/Formats/OBJLoader.cpp index d7dd15d14..2905284b1 100644 --- a/src/Nazara/Utility/Formats/OBJLoader.cpp +++ b/src/Nazara/Utility/Formats/OBJLoader.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include @@ -12,7 +11,6 @@ #include #include #include -#include #include #include #include @@ -244,6 +242,12 @@ namespace Nz indexMapper.Unmap(); // Pour laisser les autres tâches affecter l'index buffer // Remplissage des vertices + + // Make sure the normal matrix won't rescale our normals + Nz::Matrix4f normalMatrix = parameters.matrix; + if (normalMatrix.HasScale()) + normalMatrix.ApplyScale(1.f / normalMatrix.GetScale()); + bool hasNormals = true; bool hasTexCoords = true; BufferMapper vertexMapper(vertexBuffer, BufferAccess_WriteOnly); @@ -259,7 +263,7 @@ namespace Nz vertex.position = Vector3f(parameters.matrix * vec); if (vertexIndices.normal > 0) - vertex.normal = normals[vertexIndices.normal-1]; + vertex.normal = normalMatrix.Transform(normals[vertexIndices.normal - 1], 0.f); else hasNormals = false; diff --git a/src/Nazara/Utility/Formats/OBJParser.cpp b/src/Nazara/Utility/Formats/OBJParser.cpp index f85251f57..95d7fa6ce 100644 --- a/src/Nazara/Utility/Formats/OBJParser.cpp +++ b/src/Nazara/Utility/Formats/OBJParser.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include diff --git a/src/Nazara/Utility/Formats/OBJSaver.cpp b/src/Nazara/Utility/Formats/OBJSaver.cpp index 7b3507730..74585971d 100644 --- a/src/Nazara/Utility/Formats/OBJSaver.cpp +++ b/src/Nazara/Utility/Formats/OBJSaver.cpp @@ -2,11 +2,7 @@ // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#include -#include -#include -#include +#include #include #include #include @@ -14,10 +10,7 @@ #include #include #include -#include -#include #include -#include #include #include diff --git a/src/Nazara/Utility/Formats/STBLoader.cpp b/src/Nazara/Utility/Formats/STBLoader.cpp index 83b9880dd..c7fcc7e8f 100644 --- a/src/Nazara/Utility/Formats/STBLoader.cpp +++ b/src/Nazara/Utility/Formats/STBLoader.cpp @@ -6,8 +6,6 @@ #include #include #include -#include -#include #include #include #include diff --git a/src/Nazara/Utility/Formats/STBSaver.cpp b/src/Nazara/Utility/Formats/STBSaver.cpp index 0e2f31e3f..4ec466c23 100644 --- a/src/Nazara/Utility/Formats/STBSaver.cpp +++ b/src/Nazara/Utility/Formats/STBSaver.cpp @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include #include diff --git a/src/Nazara/Utility/Image.cpp b/src/Nazara/Utility/Image.cpp index 15d9133fe..54c47b5a3 100644 --- a/src/Nazara/Utility/Image.cpp +++ b/src/Nazara/Utility/Image.cpp @@ -7,9 +7,7 @@ #include #include #include -#include #include -#include #include ///TODO: Rajouter des warnings (Formats compressés avec les méthodes Copy/Update, tests taille dans Copy) diff --git a/src/Nazara/Utility/IndexBuffer.cpp b/src/Nazara/Utility/IndexBuffer.cpp index 306fffb7f..4455a2f0c 100644 --- a/src/Nazara/Utility/IndexBuffer.cpp +++ b/src/Nazara/Utility/IndexBuffer.cpp @@ -9,7 +9,6 @@ #include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Utility/Mesh.cpp b/src/Nazara/Utility/Mesh.cpp index b6985714e..8feef9f8d 100644 --- a/src/Nazara/Utility/Mesh.cpp +++ b/src/Nazara/Utility/Mesh.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -6,18 +6,14 @@ #include #include #include -#include #include -#include #include #include #include -#include #include #include #include #include -#include #include #include #include @@ -45,6 +41,12 @@ namespace Nz return false; } + if (vertexDeclaration == nullptr) + { + NazaraError("The vertex declaration can't be null"); + return false; + } + return true; } @@ -105,6 +107,7 @@ namespace Nz NazaraAssert(m_impl, "Mesh should be created first"); NazaraAssert(m_impl->animationType == AnimationType_Static, "Submesh building only works for static meshes"); NazaraAssert(params.IsValid(), "Invalid parameters"); + NazaraAssert(params.vertexDeclaration->HasComponentOfType(VertexComponent_Position), "The vertex declaration doesn't have a Vector3 position component"); Boxf aabb; IndexBufferRef indexBuffer; @@ -113,7 +116,7 @@ namespace Nz Matrix4f matrix(primitive.matrix); matrix *= params.matrix; - VertexDeclaration* declaration = VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent); + VertexDeclaration* declaration = params.vertexDeclaration; switch (primitive.type) { diff --git a/src/Nazara/Utility/SimpleTextDrawer.cpp b/src/Nazara/Utility/SimpleTextDrawer.cpp index 1b53f808f..6216a815b 100644 --- a/src/Nazara/Utility/SimpleTextDrawer.cpp +++ b/src/Nazara/Utility/SimpleTextDrawer.cpp @@ -105,11 +105,10 @@ namespace Nz const AbstractTextDrawer::Line& SimpleTextDrawer::GetLine(std::size_t index) const { - NazaraAssert(index < m_lines.size(), "Line index out of range"); - if (!m_glyphUpdated) UpdateGlyphs(); + NazaraAssert(index < m_lines.size(), "Line index out of range"); return m_lines[index]; } @@ -319,6 +318,10 @@ namespace Nz glyph.color = m_color; glyph.flipped = fontGlyph.flipped; + glyph.bounds.Set(fontGlyph.aabb); + glyph.bounds.x += m_drawPos.x; + glyph.bounds.y += m_drawPos.y; + if (fontGlyph.requireFauxBold) { // Let's simulate bold by enlarging the glyph (not a neat idea, but should work) @@ -330,16 +333,13 @@ namespace Nz // Replace it at the correct height Vector2f offset(glyph.bounds.GetCenter() - center); + glyph.bounds.x -= offset.x; glyph.bounds.y -= offset.y; // Adjust advance (+10%) advance += advance / 10; } - glyph.bounds.Set(fontGlyph.aabb); - glyph.bounds.x += m_drawPos.x; - glyph.bounds.y += m_drawPos.y; - // We "lean" the glyph to simulate italics style float italic = (fontGlyph.requireFauxItalic) ? 0.208f : 0.f; float italicTop = italic * glyph.bounds.y; @@ -377,6 +377,7 @@ namespace Nz m_drawPos.x = 0; m_drawPos.y += sizeInfo.lineHeight; + m_workingBounds.ExtendTo(m_lines.back().bounds); m_lines.emplace_back(Line{Rectf(0.f, float(sizeInfo.lineHeight * m_lines.size()), 0.f, float(sizeInfo.lineHeight)), m_glyphs.size() + 1}); break; } @@ -385,17 +386,16 @@ namespace Nz m_lines.back().bounds.ExtendTo(glyph.bounds); - if (!m_workingBounds.IsValid()) - m_workingBounds.Set(glyph.bounds); - else - m_workingBounds.ExtendTo(glyph.bounds); - m_drawPos.x += advance; m_glyphs.push_back(glyph); } m_lines.back().bounds.ExtendTo(m_glyphs.back().bounds); + m_workingBounds.ExtendTo(m_lines.back().bounds); m_bounds.Set(Rectf(std::floor(m_workingBounds.x), std::floor(m_workingBounds.y), std::ceil(m_workingBounds.width), std::ceil(m_workingBounds.height))); + + m_colorUpdated = true; + m_glyphUpdated = true; } void SimpleTextDrawer::OnFontAtlasLayerChanged(const Font* font, AbstractImage* oldLayer, AbstractImage* newLayer) diff --git a/src/Nazara/Utility/SkeletalMesh.cpp b/src/Nazara/Utility/SkeletalMesh.cpp index e866c0d33..02550a4d6 100644 --- a/src/Nazara/Utility/SkeletalMesh.cpp +++ b/src/Nazara/Utility/SkeletalMesh.cpp @@ -4,9 +4,6 @@ #include #include -#include -#include -#include #include namespace Nz diff --git a/src/Nazara/Utility/Skeleton.cpp b/src/Nazara/Utility/Skeleton.cpp index 480522b4e..45958980f 100644 --- a/src/Nazara/Utility/Skeleton.cpp +++ b/src/Nazara/Utility/Skeleton.cpp @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include +#include #include #include diff --git a/src/Nazara/Utility/SoftwareBuffer.cpp b/src/Nazara/Utility/SoftwareBuffer.cpp index 6dce1fc6a..c76f20784 100644 --- a/src/Nazara/Utility/SoftwareBuffer.cpp +++ b/src/Nazara/Utility/SoftwareBuffer.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include namespace Nz diff --git a/src/Nazara/Utility/StaticMesh.cpp b/src/Nazara/Utility/StaticMesh.cpp index a1a25f3d7..7c7637481 100644 --- a/src/Nazara/Utility/StaticMesh.cpp +++ b/src/Nazara/Utility/StaticMesh.cpp @@ -5,10 +5,7 @@ #include #include #include -#include -#include #include -#include #include namespace Nz diff --git a/src/Nazara/Utility/SubMesh.cpp b/src/Nazara/Utility/SubMesh.cpp index 9607052fb..910b3b2fb 100644 --- a/src/Nazara/Utility/SubMesh.cpp +++ b/src/Nazara/Utility/SubMesh.cpp @@ -6,10 +6,8 @@ #include #include #include -#include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Utility/Utility.cpp b/src/Nazara/Utility/Utility.cpp index c6e87e0bb..4c8f1809e 100644 --- a/src/Nazara/Utility/Utility.cpp +++ b/src/Nazara/Utility/Utility.cpp @@ -6,21 +6,15 @@ #include #include #include -#include -#include -#include -#include #include #include #include -#include #include #include #include #include #include #include -#include #include #include #include @@ -35,15 +29,29 @@ namespace Nz { + /*! + * \ingroup utility + * \class Nz::Utility + * \brief Utility class that represents the module initializer of Utility + */ + + /*! + * \brief Initializes the Utility module + * \return true if initialization is successful + * + * \remark Produces a NazaraNotice + * \remark Produces a NazaraError if one submodule failed + */ + bool Utility::Initialize() { if (s_moduleReferenceCounter > 0) { s_moduleReferenceCounter++; - return true; // Déjà initialisé + return true; // Already initialized } - // Initialisation des dépendances + // Initialisation of dependencies if (!Core::Initialize()) { NazaraError("Failed to initialize core module"); @@ -103,23 +111,6 @@ namespace Nz return false; } - bool bParam; - if (!s_initializationParameters.GetBooleanParameter("NoWindowSystem", &bParam) || !bParam) - { - if (!Window::Initialize()) - { - NazaraError("Failed to initialize window's system"); - return false; - } - - // Must be initialized after Window - if (!Cursor::Initialize()) - { - NazaraError("Failed to initialize cursors"); - return false; - } - } - // On enregistre les loaders pour les extensions // Il s'agit ici d'une liste LIFO, le dernier loader enregistré possède la priorité @@ -159,11 +150,6 @@ namespace Nz return s_moduleReferenceCounter != 0; } - void Utility::SetParameters(const ParameterList& parameters) - { - s_initializationParameters = parameters; - } - void Utility::Uninitialize() { if (s_moduleReferenceCounter != 1) @@ -188,9 +174,6 @@ namespace Nz Loaders::UnregisterSTBLoader(); Loaders::UnregisterSTBSaver(); - Cursor::Uninitialize(); //< Must be done before Window - Window::Uninitialize(); - VertexDeclaration::Uninitialize(); Skeleton::Uninitialize(); PixelFormat::Uninitialize(); @@ -246,6 +229,5 @@ namespace Nz static_assert(ComponentType_Max+1 == 14, "Component stride array is incomplete"); - ParameterList Utility::s_initializationParameters; unsigned int Utility::s_moduleReferenceCounter = 0; } diff --git a/src/Nazara/Utility/VertexBuffer.cpp b/src/Nazara/Utility/VertexBuffer.cpp index f06d46ed0..e072c4aa1 100644 --- a/src/Nazara/Utility/VertexBuffer.cpp +++ b/src/Nazara/Utility/VertexBuffer.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include namespace Nz diff --git a/src/Nazara/Utility/VertexDeclaration.cpp b/src/Nazara/Utility/VertexDeclaration.cpp index 51160ab3f..7edbd3124 100644 --- a/src/Nazara/Utility/VertexDeclaration.cpp +++ b/src/Nazara/Utility/VertexDeclaration.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -10,7 +10,6 @@ #include #include #include -#include #include namespace Nz @@ -121,6 +120,15 @@ namespace Nz *offset = vertexComponent.offset; } + bool VertexDeclaration::HasComponent(VertexComponent component) const + { + bool enabled; + + GetComponent(component, &enabled, nullptr, nullptr); + + return enabled; + } + std::size_t VertexDeclaration::GetStride() const { return m_stride; diff --git a/tests/Engine/Core/AlgorithmCore.cpp b/tests/Engine/Core/AlgorithmCore.cpp index 8aff5cb24..9401a974d 100644 --- a/tests/Engine/Core/AlgorithmCore.cpp +++ b/tests/Engine/Core/AlgorithmCore.cpp @@ -3,8 +3,6 @@ #include -#include - TEST_CASE("Apply", "[CORE][ALGORITHM]") { SECTION("Apply lambda to two vector2") diff --git a/tests/Engine/Core/ByteArray.cpp b/tests/Engine/Core/ByteArray.cpp index d085585a5..d7bf4cf3c 100644 --- a/tests/Engine/Core/ByteArray.cpp +++ b/tests/Engine/Core/ByteArray.cpp @@ -102,7 +102,7 @@ SCENARIO("ByteArray", "[CORE][BYTEARRAY]") { Nz::ByteArray abc("abc", 3); Nz::ByteArray cba; - cba = std::move(Nz::ByteArray("cba", 3)); + cba = Nz::ByteArray("cba", 3); WHEN("We do some antagonists operations") { diff --git a/tests/Engine/Core/File.cpp b/tests/Engine/Core/File.cpp index 1163a8aad..60b5bcc40 100644 --- a/tests/Engine/Core/File.cpp +++ b/tests/Engine/Core/File.cpp @@ -1,4 +1,5 @@ #include +#include #include SCENARIO("File", "[CORE][FILE]") diff --git a/tests/Engine/Math/Quaternion.cpp b/tests/Engine/Math/Quaternion.cpp index 7ebf6ede5..46a0c5f89 100644 --- a/tests/Engine/Math/Quaternion.cpp +++ b/tests/Engine/Math/Quaternion.cpp @@ -173,15 +173,52 @@ SCENARIO("Quaternion", "[MATH][QUATERNION]") WHEN("We get the rotation between two vectors") { - /*TODO - * Nz::Quaternionf rotationBetweenXY = Nz::Quaternionf::RotationBetween(Nz::Vector3f::UnitX(), Nz::Vector3f::UnitY()); + Nz::Quaternionf rotationBetweenXY = Nz::Quaternionf::RotationBetween(Nz::Vector3f::UnitX(), Nz::Vector3f::UnitY()); - THEN("The rotation in left-handed is 270 degree on z") + THEN("The rotation in right-handed is 90 degree on z") { - Nz::Quaternionf rotation270Z(Nz::FromDegrees(270.f), Nz::Vector3f::UnitZ()); Nz::Quaternionf rotation90Z(Nz::FromDegrees(90.f), Nz::Vector3f::UnitZ()); REQUIRE(rotation90Z == rotationBetweenXY); - }*/ + } + } + } + + GIVEN("Different angles") + { + Nz::Quaternionf rotation90X(0.707f, 0.707f, 0.f, 0.f); + Nz::Quaternionf rotation90Y(0.707f, 0.f, 0.707f, 0.f); + Nz::Quaternionf rotation90Z(0.707f, 0.f, 0.f, 0.707f); + + Nz::Quaternionf rotation180X(0.f, 1.f, 0.f, 0.f); + Nz::Quaternionf rotation180Y(0.f, 0.f, 1.f, 0.f); + Nz::Quaternionf rotation180Z(0.f, 0.f, 0.f, 1.f); + + Nz::Quaternionf rotation270X(-0.707f, 0.707f, 0.f, 0.f); + Nz::Quaternionf rotation270Y(-0.707f, 0.f, 0.707f, 0.f); + Nz::Quaternionf rotation270Z(-0.707f, 0.f, 0.f, 0.707f); + + Nz::Quaternionf special(0.707f, 0.006f, 0.006f, 0.707f); + + WHEN("We convert them to euler angles") + { + THEN("Those are equal to") + { + CHECK(Nz::NumberEquals(rotation90X.ToEulerAngles().pitch, Nz::FromDegrees(90.f), 0.1f)); + CHECK(Nz::NumberEquals(rotation90Y.ToEulerAngles().yaw, Nz::FromDegrees(90.f), 0.1f)); + CHECK(Nz::NumberEquals(rotation90Z.ToEulerAngles().roll, Nz::FromDegrees(90.f), 0.1f)); + + CHECK(rotation180X == Nz::EulerAnglesf(180.f, 0.f, 0.f)); + CHECK(rotation180Y == Nz::EulerAnglesf(0.f, 180.f, 0.f)); + CHECK(rotation180Z == Nz::EulerAnglesf(0.f, 0.f, 180.f)); + + CHECK(Nz::NumberEquals(rotation270X.ToEulerAngles().pitch, Nz::FromDegrees(-90.f), 0.1f)); + CHECK(Nz::NumberEquals(rotation270Y.ToEulerAngles().yaw, Nz::FromDegrees(-90.f), 0.1f)); + CHECK(Nz::NumberEquals(rotation270Z.ToEulerAngles().roll, Nz::FromDegrees(-90.f), 0.1f)); + + CHECK(Nz::NumberEquals(special.ToEulerAngles().pitch, Nz::FromDegrees(0.f), 0.1f)); + CHECK(Nz::NumberEquals(special.ToEulerAngles().yaw, Nz::FromDegrees(1.f), 0.1f)); + CHECK(Nz::NumberEquals(special.ToEulerAngles().roll, Nz::FromDegrees(90.f), 0.1f)); + } } } } diff --git a/tests/Engine/Physics2D/Collider2D.cpp b/tests/Engine/Physics2D/Collider2D.cpp new file mode 100644 index 000000000..dee2b85c8 --- /dev/null +++ b/tests/Engine/Physics2D/Collider2D.cpp @@ -0,0 +1,133 @@ +#include +#include + +SCENARIO("Collider2D", "[PHYSICS2D][COLLIDER2D]") +{ + GIVEN("No particular elements") + { + WHEN("We construct a box with Rect") + { + Nz::Rectf aabb(5.f, 3.f, 10.f, 6.f); + Nz::BoxCollider2D box(aabb); + + THEN("We expect those to be true") + { + CHECK(box.GetRect() == aabb); + CHECK(box.GetSize() == aabb.GetLengths()); + CHECK(box.GetType() == Nz::ColliderType2D_Box); + } + } + + WHEN("We construct a box with Vector2D") + { + Nz::Vector2f vec(5.f, 3.f); + Nz::Rectf aabb(-2.5f, -1.5f, 5.f, 3.f); + Nz::BoxCollider2D box(vec); + + THEN("We expect those to be true") + { + CHECK(box.GetRect() == aabb); + CHECK(box.GetSize() == vec); + CHECK(box.GetType() == Nz::ColliderType2D_Box); + } + } + + WHEN("We construct a circle") + { + Nz::Vector2f position(5.f, 3.f); + float radius = 7.f; + Nz::CircleCollider2D circle(radius, position); + + THEN("We expect those to be true") + { + CHECK(circle.GetRadius() == Approx(radius)); + CHECK(circle.GetType() == Nz::ColliderType2D_Circle); + } + } + + WHEN("We construct a compound") + { + Nz::Rectf aabb(0.f, 0.f, 1.f, 1.f); + Nz::BoxCollider2DRef box1 = Nz::BoxCollider2D::New(aabb); + aabb.Translate(Nz::Vector2f::Unit()); + Nz::BoxCollider2DRef box2 = Nz::BoxCollider2D::New(aabb); + + std::vector colliders; + colliders.push_back(box1); + colliders.push_back(box2); + Nz::CompoundCollider2D compound(colliders); + + THEN("We expect those to be true") + { + CHECK(compound.GetType() == Nz::ColliderType2D_Compound); + } + } + + WHEN("We construct a convex") + { + std::vector vertices; + vertices.push_back(Nz::Vector2f(0.f, 0.f)); + vertices.push_back(Nz::Vector2f(0.f, 1.f)); + vertices.push_back(Nz::Vector2f(1.f, 1.f)); + vertices.push_back(Nz::Vector2f(1.f, 0.f)); + + Nz::ConvexCollider2D convex(Nz::SparsePtr(vertices.data()), vertices.size()); + + THEN("We expect those to be true") + { + CHECK(convex.GetType() == Nz::ColliderType2D_Convex); + } + } + + WHEN("We construct a null") + { + Nz::NullCollider2D null; + + THEN("We expect those to be true") + { + CHECK(null.GetType() == Nz::ColliderType2D_Null); + } + } + + WHEN("We construct a segment") + { + Nz::Vector2f firstPoint(2.f, 1.f); + Nz::Vector2f secondPoint(-4.f, -3.f); + Nz::SegmentCollider2D segment(firstPoint, secondPoint); + + THEN("We expect those to be true") + { + CHECK(segment.GetFirstPoint() == firstPoint); + CHECK(segment.GetLength() == firstPoint.Distance(secondPoint)); + CHECK(segment.GetSecondPoint() == secondPoint); + CHECK(segment.GetType() == Nz::ColliderType2D_Segment); + } + } + + WHEN("We verify general purpose methods") + { + Nz::Rectf aabb(5.f, 3.f, 10.f, 6.f); + Nz::BoxCollider2D box(aabb); + + Nz::UInt32 categoryMask = 1; + Nz::UInt32 groupId = 2; + Nz::UInt32 typeId = 3; + Nz::UInt32 mask = 4; + bool trigger = true; + box.SetCategoryMask(categoryMask); + box.SetCollisionGroup(groupId); + box.SetCollisionId(typeId); + box.SetCollisionMask(mask); + box.SetTrigger(trigger); + + THEN("We expect those to be true") + { + CHECK(box.GetCategoryMask() == categoryMask); + CHECK(box.GetCollisionGroup() == groupId); + CHECK(box.GetCollisionId() == typeId); + CHECK(box.GetCollisionMask() == mask); + CHECK(box.IsTrigger() == trigger); + } + } + } +} diff --git a/tests/Engine/Physics2D/PhysWorld2D.cpp b/tests/Engine/Physics2D/PhysWorld2D.cpp new file mode 100644 index 000000000..539932f71 --- /dev/null +++ b/tests/Engine/Physics2D/PhysWorld2D.cpp @@ -0,0 +1,114 @@ +#include +#include + +Nz::RigidBody2D CreateBody(Nz::PhysWorld2D& world, const Nz::Vector2f& position, bool isMoving = true, const Nz::Vector2f& lengths = Nz::Vector2f::Unit()); + +Nz::UInt32 collisionGroup = 1; +Nz::UInt32 categoryMask = 2; +Nz::UInt32 collisionMask = 3; + +SCENARIO("PhysWorld2D", "[PHYSICS2D][PHYSWORLD2D]") +{ + GIVEN("A physic world and a bunch of entities on a grid") + { + Nz::PhysWorld2D world; + + std::vector bodies; + const int numberOfBodiesPerLign = 3; + for (int i = 0; i != numberOfBodiesPerLign; ++i) + { + for (int j = 0; j != numberOfBodiesPerLign; ++j) + { + bodies.push_back(CreateBody(world, Nz::Vector2f(10.f * i, 10.f * j))); + } + } + + world.Step(1.f); + + WHEN("We ask for the nearest body") + { + Nz::PhysWorld2D::NearestQueryResult result; + REQUIRE(world.NearestBodyQuery(-Nz::Vector2f::UnitY() * 1.f, 2.f, collisionGroup, categoryMask, collisionMask, &result)); + + THEN("It should be the one on the origin") + { + CHECK(result.nearestBody == &bodies[0]); + CHECK(result.closestPoint == Nz::Vector2f::Zero()); + CHECK(result.fraction == -Nz::Vector2f::UnitY()); + CHECK(result.distance == Approx(1.f)); + } + + REQUIRE(world.NearestBodyQuery(Nz::Vector2f::UnitY() * 2.f, 2.f, collisionGroup, categoryMask, collisionMask, &result)); + + THEN("It should be the one on the origin") + { + CHECK(result.nearestBody == &bodies[0]); + CHECK(result.closestPoint == Nz::Vector2f::UnitY()); + CHECK(result.fraction == Nz::Vector2f::UnitY()); + CHECK(result.distance == Approx(1.f)); + } + } + + WHEN("We ask for the first ray collision") + { + Nz::Vector2f origin = -Nz::Vector2f::UnitY() * 2.f; + Nz::Vector2f end = (numberOfBodiesPerLign + 1) * 10.f * Nz::Vector2f::UnitY(); + Nz::PhysWorld2D::RaycastHit result; + REQUIRE(world.RaycastQueryFirst(origin, end, 1.f, collisionGroup, categoryMask, collisionMask, &result)); + + THEN("It should be the one on the origin") + { + CHECK(result.nearestBody == &bodies[0]); + CHECK(result.fraction == Approx(1.f / 42.f)); + CHECK(result.hitPos == Nz::Vector2f::Zero()); + CHECK(result.hitNormal == -Nz::Vector2f::UnitY()); + } + } + + WHEN("We ask for the ray collisions") + { + Nz::Vector2f origin = -Nz::Vector2f::UnitY() * 2.f; + Nz::Vector2f end = (numberOfBodiesPerLign + 1) * 10.f * Nz::Vector2f::UnitY(); + std::vector results; + REQUIRE(world.RaycastQuery(origin, end, 1.f, collisionGroup, categoryMask, collisionMask, &results)); + + THEN("It should be the first lign") + { + REQUIRE(results.size() == numberOfBodiesPerLign); + + for (int i = 0; i != numberOfBodiesPerLign; ++i) + { + const Nz::PhysWorld2D::RaycastHit& result = results[i]; + CHECK(result.nearestBody == &bodies[i]); + CHECK(result.fraction == Approx(i / 4.f).epsilon(0.1f)); + CHECK(result.hitPos == Nz::Vector2f(0.f, i * 10.f)); + CHECK(result.hitNormal == -Nz::Vector2f::UnitY()); + } + } + } + + WHEN("We ask for a region") + { + std::vector results; + world.RegionQuery(Nz::Rectf(-5.f, -5.f, 5.f, 5.f), collisionGroup, categoryMask, collisionMask, &results); + + THEN("It should be the one on the origin") + { + REQUIRE(results.size() == 1); + CHECK(results[0] == &bodies[0]); + } + } + } +} + +Nz::RigidBody2D CreateBody(Nz::PhysWorld2D& world, const Nz::Vector2f& position, bool isMoving, const Nz::Vector2f& lengths) +{ + Nz::Rectf aabb(0.f, 0.f, lengths.x, lengths.y); + Nz::Collider2DRef box = Nz::BoxCollider2D::New(aabb); + box->SetCategoryMask(categoryMask); + box->SetCollisionMask(collisionMask); + float mass = isMoving ? 1.f : 0.f; + Nz::RigidBody2D rigidBody(&world, mass, box); + rigidBody.SetPosition(position); + return rigidBody; +} diff --git a/tests/Engine/Physics2D/RigidBody2D.cpp b/tests/Engine/Physics2D/RigidBody2D.cpp new file mode 100644 index 000000000..98a7fc35a --- /dev/null +++ b/tests/Engine/Physics2D/RigidBody2D.cpp @@ -0,0 +1,318 @@ +#include +#include +#include + +Nz::RigidBody2D CreateBody(Nz::PhysWorld2D& world); +void EQUALITY(const Nz::RigidBody2D& left, const Nz::RigidBody2D& right); + +SCENARIO("RigidBody2D", "[PHYSICS2D][RIGIDBODY2D]") +{ + GIVEN("A physic world and a rigid body") + { + Nz::PhysWorld2D world; + + Nz::Vector2f positionAABB(3.f, 4.f); + Nz::Rectf aabb(positionAABB.x, positionAABB.y, 1.f, 2.f); + Nz::Collider2DRef box = Nz::BoxCollider2D::New(aabb); + float mass = 1.f; + Nz::RigidBody2D body(&world, mass, box); + float angularVelocity = 0.2f; + body.SetAngularVelocity(angularVelocity); + Nz::Vector2f massCenter(5.f, 7.f); + body.SetMassCenter(massCenter); + Nz::Vector2f position(9.f, 1.f); + body.SetPosition(position); + float rotation = 0.1f; + body.SetRotation(rotation); + Nz::Vector2f velocity(-4.f, -2.f); + body.SetVelocity(velocity); + bool userdata = false; + body.SetUserdata(&userdata); + + world.Step(1.f); + + WHEN("We copy construct the body") + { + body.AddForce(Nz::Vector2f(3.f, 5.f)); + Nz::RigidBody2D copiedBody(body); + EQUALITY(copiedBody, body); + world.Step(1.f); + EQUALITY(copiedBody, body); + } + + WHEN("We move construct the body") + { + Nz::RigidBody2D copiedBody(body); + Nz::RigidBody2D movedBody(std::move(body)); + EQUALITY(movedBody, copiedBody); + } + + WHEN("We copy assign the body") + { + Nz::RigidBody2D copiedBody(&world, 0.f); + copiedBody = body; + EQUALITY(copiedBody, body); + } + + WHEN("We move assign the body") + { + Nz::RigidBody2D copiedBody(body); + Nz::RigidBody2D movedBody(&world, 0.f); + movedBody = std::move(body); + EQUALITY(movedBody, copiedBody); + } + + WHEN("We set a new geometry") + { + float radius = 5.f; + Nz::Vector2f positionCircle(0.f, 0.f); + Nz::Collider2DRef circle = Nz::CircleCollider2D::New(radius, position); + body.SetGeom(circle); + + world.Step(1.f); + + THEN("The aabb should be updated") + { + Nz::Rectf circleAABB(position.x - radius, position.y - radius, 2.f * radius, 2.f* radius); + REQUIRE(body.GetAABB() == circleAABB); + } + } + } + + GIVEN("A physic world") + { + Nz::PhysWorld2D world; + Nz::Rectf aabb(3.f, 4.f, 1.f, 2.f); + + WHEN("We get a rigid body from a function") + { + std::vector tmp; + tmp.push_back(CreateBody(world)); + tmp.push_back(CreateBody(world)); + world.Step(1.f); + + THEN("They should be valid") + { + CHECK(tmp[0].GetAABB() == aabb); + CHECK(tmp[1].GetAABB() == aabb); + } + } + } + + GIVEN("A physic world and a rigid body") + { + Nz::PhysWorld2D world; + Nz::Vector2f positionAABB(3.f, 4.f); + Nz::Rectf aabb(positionAABB.x, positionAABB.y, 1.f, 2.f); + Nz::Collider2DRef box = Nz::BoxCollider2D::New(aabb); + float mass = 1.f; + Nz::RigidBody2D body(&world, mass, box); + bool userData = false; + body.SetUserdata(&userData); + + Nz::Vector2f position = Nz::Vector2f::Zero(); + + world.Step(1.f); + + WHEN("We retrieve standard information") + { + THEN("We expect those to be true") + { + CHECK(body.GetAABB() == aabb); + CHECK(body.GetAngularVelocity() == Approx(0.f)); + CHECK(body.GetCenterOfGravity() == Nz::Vector2f::Zero()); + CHECK(body.GetGeom() == box); + CHECK(body.GetMass() == Approx(mass)); + CHECK(body.GetPosition() == position); + CHECK(body.GetRotation() == Approx(0.f)); + CHECK(body.GetUserdata() == &userData); + CHECK(body.GetVelocity() == Nz::Vector2f::Zero()); + + CHECK(body.IsKinematic() == false); + CHECK(body.IsSleeping() == false); + } + } + + WHEN("We set a velocity") + { + Nz::Vector2f velocity(Nz::Vector2f::Unit()); + body.SetVelocity(velocity); + position += velocity; + world.Step(1.f); + + THEN("We expect those to be true") + { + aabb.Translate(velocity); + CHECK(body.GetAABB() == aabb); + CHECK(body.GetCenterOfGravity() == Nz::Vector2f::Zero()); + CHECK(body.GetPosition() == position); + CHECK(body.GetVelocity() == velocity); + } + + AND_THEN("We apply an impulse in the opposite direction") + { + body.AddImpulse(-velocity); + world.Step(1.f); + + REQUIRE(body.GetVelocity() == Nz::Vector2f::Zero()); + } + } + + WHEN("We set an angular velocity") + { + float angularSpeed = Nz::FromDegrees(90.f); + body.SetAngularVelocity(angularSpeed); + world.Step(1.f); + + THEN("We expect those to be true") + { + CHECK(body.GetAngularVelocity() == Approx(angularSpeed)); + CHECK(body.GetRotation() == Approx(angularSpeed)); + CHECK(body.GetAABB() == Nz::Rectf(-6.f, 3.f, 2.f, 1.f)); + + world.Step(1.f); + CHECK(body.GetRotation() == Approx(2.f * angularSpeed)); + CHECK(body.GetAABB() == Nz::Rectf(-4.f, -6.f, 1.f, 2.f)); + + world.Step(1.f); + CHECK(body.GetRotation() == Approx(3.f * angularSpeed)); + CHECK(body.GetAABB() == Nz::Rectf(4.f, -4.f, 2.f, 1.f)); + + world.Step(1.f); + CHECK(body.GetRotation() == Approx(4.f * angularSpeed)); + } + } + + WHEN("We apply a torque") + { + float angularSpeed = Nz::DegreeToRadian(90.f); + body.AddTorque(angularSpeed); + world.Step(1.f); + + THEN("It is also counter-clockwise") + { + CHECK(body.GetAngularVelocity() >= 0.f); + CHECK(body.GetRotation() >= 0.f); + } + } + } + + GIVEN("A physic world and a rigid body of circle") + { + Nz::PhysWorld2D world; + + Nz::Vector2f position(3.f, 4.f); + float radius = 5.f; + Nz::Collider2DRef circle = Nz::CircleCollider2D::New(radius, position); + float mass = 1.f; + Nz::RigidBody2D body(&world, mass, circle); + world.Step(1.f); + + WHEN("We ask for the aabb of the circle") + { + THEN("We expect this to be true") + { + Nz::Rectf circleAABB(position.x - radius, position.y - radius, 2.f * radius, 2.f* radius); + REQUIRE(body.GetAABB() == circleAABB); + } + } + } + + GIVEN("A physic world and a rigid body of compound") + { + Nz::PhysWorld2D world; + + Nz::Rectf aabb(0.f, 0.f, 1.f, 1.f); + Nz::BoxCollider2DRef box1 = Nz::BoxCollider2D::New(aabb); + aabb.Translate(Nz::Vector2f::Unit()); + Nz::BoxCollider2DRef box2 = Nz::BoxCollider2D::New(aabb); + + std::vector colliders; + colliders.push_back(box1); + colliders.push_back(box2); + Nz::CompoundCollider2DRef compound = Nz::CompoundCollider2D::New(colliders); + + float mass = 1.f; + Nz::RigidBody2D body(&world, mass, compound); + world.Step(1.f); + + WHEN("We ask for the aabb of the compound") + { + THEN("We expect this to be true") + { + Nz::Rectf compoundAABB(0.f, 0.f, 2.f, 2.f); + REQUIRE(body.GetAABB() == compoundAABB); + } + } + } + + GIVEN("A physic world and a rigid body of circle") + { + Nz::PhysWorld2D world; + + std::vector vertices; + vertices.push_back(Nz::Vector2f(0.f, 0.f)); + vertices.push_back(Nz::Vector2f(0.f, 1.f)); + vertices.push_back(Nz::Vector2f(1.f, 1.f)); + vertices.push_back(Nz::Vector2f(1.f, 0.f)); + + Nz::SparsePtr sparsePtr(vertices.data()); + Nz::ConvexCollider2DRef convex = Nz::ConvexCollider2D::New(sparsePtr, vertices.size()); + float mass = 1.f; + Nz::RigidBody2D body(&world, mass, convex); + world.Step(1.f); + + WHEN("We ask for the aabb of the convex") + { + THEN("We expect this to be true") + { + Nz::Rectf convexAABB(0.f, 0.f, 1.f, 1.f); + REQUIRE(body.GetAABB() == convexAABB); + } + } + } + + GIVEN("A physic world and a rigid body of segment") + { + Nz::PhysWorld2D world; + + Nz::Vector2f positionA(3.f, 4.f); + Nz::Vector2f positionB(1.f, -4.f); + Nz::Collider2DRef segment = Nz::SegmentCollider2D::New(positionA, positionB, 0.f); + float mass = 1.f; + Nz::RigidBody2D body(&world, mass, segment); + world.Step(1.f); + + WHEN("We ask for the aabb of the segment") + { + THEN("We expect this to be true") + { + Nz::Rectf segmentAABB(positionA, positionB); + REQUIRE(body.GetAABB() == segmentAABB); + } + } + } +} + +Nz::RigidBody2D CreateBody(Nz::PhysWorld2D& world) +{ + Nz::Vector2f positionAABB(3.f, 4.f); + Nz::Rectf aabb(positionAABB.x, positionAABB.y, 1.f, 2.f); + Nz::Collider2DRef box = Nz::BoxCollider2D::New(aabb); + float mass = 1.f; + return Nz::RigidBody2D(&world, mass, box); +} + +void EQUALITY(const Nz::RigidBody2D& left, const Nz::RigidBody2D& right) +{ + CHECK(left.GetAABB() == right.GetAABB()); + CHECK(left.GetAngularVelocity() == right.GetAngularVelocity()); + CHECK(left.GetCenterOfGravity() == right.GetCenterOfGravity()); + CHECK(left.GetGeom() == right.GetGeom()); + CHECK(left.GetHandle() != right.GetHandle()); + CHECK(left.GetMass() == right.GetMass()); + CHECK(left.GetPosition() == right.GetPosition()); + CHECK(left.GetRotation() == right.GetRotation()); + CHECK(left.GetUserdata() == right.GetUserdata()); + CHECK(left.GetVelocity() == right.GetVelocity()); +} diff --git a/tests/Engine/Utility/EventHandler.cpp b/tests/Engine/Platform/EventHandler.cpp similarity index 97% rename from tests/Engine/Utility/EventHandler.cpp rename to tests/Engine/Platform/EventHandler.cpp index dedf3fc31..b143b949a 100644 --- a/tests/Engine/Utility/EventHandler.cpp +++ b/tests/Engine/Platform/EventHandler.cpp @@ -25,7 +25,7 @@ Ndk::EntityHandle AddCamera(Ndk::World& world, Nz::RenderWindow& window); - Text entered is never repeated */ -SCENARIO("EventHandler", "[UTILITY][EVENTHANDLER][INTERACTIVE][.]") +SCENARIO("EventHandler", "[PLATFORM][EVENTHANDLER][INTERACTIVE][.]") { GIVEN("An application") { diff --git a/tests/Engine/Platform/EventHandler/BaseState.cpp b/tests/Engine/Platform/EventHandler/BaseState.cpp new file mode 100644 index 000000000..8cb229445 --- /dev/null +++ b/tests/Engine/Platform/EventHandler/BaseState.cpp @@ -0,0 +1,39 @@ +#include "BaseState.hpp" + +#include "StateContext.hpp" +#include "StateFactory.hpp" + +#include +#include + +BaseState::BaseState(StateContext& context) : +State(), +m_context(context), +m_text(context) +{ +} + +BaseState::~BaseState() +{ +} + +void BaseState::Enter(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(true); + DrawMenu(); +} + +void BaseState::Leave(Ndk::StateMachine& /*fsm*/) +{ + m_text.SetVisible(false); +} + +bool BaseState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) +{ + return true; +} + +void BaseState::DrawMenu() +{ + m_text.SetContent("This shouldn't be visible\nM for Menu"); +} \ No newline at end of file diff --git a/tests/Engine/Platform/EventHandler/BaseState.hpp b/tests/Engine/Platform/EventHandler/BaseState.hpp new file mode 100644 index 000000000..2356e39cd --- /dev/null +++ b/tests/Engine/Platform/EventHandler/BaseState.hpp @@ -0,0 +1,31 @@ +#ifndef BASESTATE_HPP +#define BASESTATE_HPP + +#include "Text.hpp" + +#include + +#include + +class StateContext; + +class BaseState : public Ndk::State +{ + public: + BaseState(StateContext& stateContext); + virtual ~BaseState(); + + virtual void Enter(Ndk::StateMachine& fsm) override; + + virtual void Leave(Ndk::StateMachine& fsm) override; + + virtual bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + protected: + virtual void DrawMenu(); + + StateContext& m_context; + Text m_text; +}; + +#endif // BASESTATE_HPP \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/EventState.cpp b/tests/Engine/Platform/EventHandler/EventState.cpp similarity index 90% rename from tests/Engine/Utility/EventHandler/EventState.cpp rename to tests/Engine/Platform/EventHandler/EventState.cpp index 9fa5ea244..1d6a6784a 100644 --- a/tests/Engine/Utility/EventHandler/EventState.cpp +++ b/tests/Engine/Platform/EventHandler/EventState.cpp @@ -7,17 +7,14 @@ #include EventState::EventState(StateContext& context) : -State(), -m_context(context), -m_text(context), +BaseState(context), m_count(0) { } void EventState::Enter(Ndk::StateMachine& fsm) { - m_text.SetVisible(true); - DrawMenu(); + BaseState::Enter(fsm); Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) @@ -35,16 +32,6 @@ void EventState::Enter(Ndk::StateMachine& fsm) }); } -void EventState::Leave(Ndk::StateMachine& /*fsm*/) -{ - m_text.SetVisible(false); -} - -bool EventState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) -{ - return true; -} - void EventState::AddEvent(const Nz::WindowEvent& event) { if (m_events.size() > 9) diff --git a/tests/Engine/Utility/EventHandler/EventState.hpp b/tests/Engine/Platform/EventHandler/EventState.hpp similarity index 59% rename from tests/Engine/Utility/EventHandler/EventState.hpp rename to tests/Engine/Platform/EventHandler/EventState.hpp index 7b1cc63d7..d22ebd4c4 100644 --- a/tests/Engine/Utility/EventHandler/EventState.hpp +++ b/tests/Engine/Platform/EventHandler/EventState.hpp @@ -1,32 +1,26 @@ #ifndef __EVENTSTATE_HPP__ #define __EVENTSTATE_HPP__ -#include "Text.hpp" - -#include - -#include +#include "BaseState.hpp" #include class StateContext; -class EventState : public Ndk::State +class EventState : public BaseState { public: EventState(StateContext& stateContext); void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; private: void AddEvent(const Nz::WindowEvent& event); - void DrawMenu(); + + void DrawMenu() override; + Nz::String ToString(const Nz::WindowEvent& event) const; - StateContext& m_context; - Text m_text; std::deque m_events; int m_count; NazaraSlot(Nz::EventHandler, OnEvent, m_eventSlot); diff --git a/tests/Engine/Utility/EventHandler/FocusState.cpp b/tests/Engine/Platform/EventHandler/FocusState.cpp similarity index 78% rename from tests/Engine/Utility/EventHandler/FocusState.cpp rename to tests/Engine/Platform/EventHandler/FocusState.cpp index bc9c77ab5..ee5fd5f7e 100644 --- a/tests/Engine/Utility/EventHandler/FocusState.cpp +++ b/tests/Engine/Platform/EventHandler/FocusState.cpp @@ -7,16 +7,13 @@ #include FocusState::FocusState(StateContext& context) : -State(), -m_context(context), -m_text(context) +BaseState(context) { } void FocusState::Enter(Ndk::StateMachine& fsm) { - m_text.SetVisible(true); - DrawMenu(); + BaseState::Enter(fsm); Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) @@ -38,16 +35,6 @@ void FocusState::Enter(Ndk::StateMachine& fsm) }); } -void FocusState::Leave(Ndk::StateMachine& /*fsm*/) -{ - m_text.SetVisible(false); -} - -bool FocusState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) -{ - return true; -} - void FocusState::DrawMenu() { m_text.SetContent("Click outside the windows, this text should change !\nM for Menu"); diff --git a/tests/Engine/Utility/EventHandler/FocusState.hpp b/tests/Engine/Platform/EventHandler/FocusState.hpp similarity index 53% rename from tests/Engine/Utility/EventHandler/FocusState.hpp rename to tests/Engine/Platform/EventHandler/FocusState.hpp index 9287722ab..359dceaa1 100644 --- a/tests/Engine/Utility/EventHandler/FocusState.hpp +++ b/tests/Engine/Platform/EventHandler/FocusState.hpp @@ -1,28 +1,20 @@ #ifndef __FOCUSSTATE_HPP__ #define __FOCUSSTATE_HPP__ -#include "Text.hpp" - -#include - -#include +#include "BaseState.hpp" class StateContext; -class FocusState : public Ndk::State +class FocusState : public BaseState { public: FocusState(StateContext& stateContext); void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; private: - void DrawMenu(); + void DrawMenu() override; - StateContext& m_context; - Text m_text; NazaraSlot(Nz::EventHandler, OnGainedFocus, m_gainedFocusSlot); NazaraSlot(Nz::EventHandler, OnLostFocus, m_lostFocusSlot); NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); diff --git a/tests/Engine/Utility/EventHandler/KeyState.cpp b/tests/Engine/Platform/EventHandler/KeyState.cpp similarity index 87% rename from tests/Engine/Utility/EventHandler/KeyState.cpp rename to tests/Engine/Platform/EventHandler/KeyState.cpp index 6244e8ed6..40bd785f1 100644 --- a/tests/Engine/Utility/EventHandler/KeyState.cpp +++ b/tests/Engine/Platform/EventHandler/KeyState.cpp @@ -7,17 +7,14 @@ #include KeyState::KeyState(StateContext& context) : -State(), -m_context(context), -m_text(context), +BaseState(context), m_keyStatus(KeyStatus::Pressed) { } void KeyState::Enter(Ndk::StateMachine& fsm) { - m_text.SetVisible(true); - DrawMenu(); + BaseState::Enter(fsm); Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) @@ -31,16 +28,6 @@ void KeyState::Enter(Ndk::StateMachine& fsm) }); } -void KeyState::Leave(Ndk::StateMachine& /*fsm*/) -{ - m_text.SetVisible(false); -} - -bool KeyState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) -{ - return true; -} - void KeyState::DrawMenu() { m_text.SetContent("Clic on a key, this text should change !\nN for alternating event\nM for Menu"); diff --git a/tests/Engine/Utility/EventHandler/KeyState.hpp b/tests/Engine/Platform/EventHandler/KeyState.hpp similarity index 60% rename from tests/Engine/Utility/EventHandler/KeyState.hpp rename to tests/Engine/Platform/EventHandler/KeyState.hpp index 9b0fb1fcd..8e16c85f2 100644 --- a/tests/Engine/Utility/EventHandler/KeyState.hpp +++ b/tests/Engine/Platform/EventHandler/KeyState.hpp @@ -1,11 +1,7 @@ #ifndef __KEYSTATE_HPP__ #define __KEYSTATE_HPP__ -#include "Text.hpp" - -#include - -#include +#include "BaseState.hpp" class StateContext; @@ -15,21 +11,18 @@ enum class KeyStatus Released }; -class KeyState : public Ndk::State +class KeyState : public BaseState { public: KeyState(StateContext& stateContext); void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; private: - void DrawMenu(); + void DrawMenu() override; + void ManageInput(KeyStatus isKeyPressed, const Nz::WindowEvent::KeyEvent& key, Ndk::StateMachine& fsm); - StateContext& m_context; - Text m_text; KeyStatus m_keyStatus; NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); NazaraSlot(Nz::EventHandler, OnKeyReleased, m_keyReleasedSlot); diff --git a/tests/Engine/Utility/EventHandler/MenuState.cpp b/tests/Engine/Platform/EventHandler/MenuState.cpp similarity index 82% rename from tests/Engine/Utility/EventHandler/MenuState.cpp rename to tests/Engine/Platform/EventHandler/MenuState.cpp index b659f51b2..d1a244369 100644 --- a/tests/Engine/Utility/EventHandler/MenuState.cpp +++ b/tests/Engine/Platform/EventHandler/MenuState.cpp @@ -7,17 +7,14 @@ #include MenuState::MenuState(StateContext& context) : -State(), -m_context(context), -m_text(context), +BaseState(context), m_selectedNextState(-1) { } -void MenuState::Enter(Ndk::StateMachine& /*fsm*/) +void MenuState::Enter(Ndk::StateMachine& fsm) { - m_text.SetVisible(true); - DrawMenu(); + BaseState::Enter(fsm); Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [this] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) @@ -29,9 +26,9 @@ void MenuState::Enter(Ndk::StateMachine& /*fsm*/) }); } -void MenuState::Leave(Ndk::StateMachine& /*fsm*/) +void MenuState::Leave(Ndk::StateMachine& fsm) { - m_text.SetVisible(false); + BaseState::Leave(fsm); m_selectedNextState = -1; } diff --git a/tests/Engine/Utility/EventHandler/MenuState.hpp b/tests/Engine/Platform/EventHandler/MenuState.hpp similarity index 69% rename from tests/Engine/Utility/EventHandler/MenuState.hpp rename to tests/Engine/Platform/EventHandler/MenuState.hpp index 356a12a72..56c7d594c 100644 --- a/tests/Engine/Utility/EventHandler/MenuState.hpp +++ b/tests/Engine/Platform/EventHandler/MenuState.hpp @@ -1,28 +1,24 @@ #ifndef __MENUSTATE_HPP__ #define __MENUSTATE_HPP__ -#include "Text.hpp" - -#include - -#include +#include "BaseState.hpp" class StateContext; -class MenuState : public Ndk::State +class MenuState : public BaseState { public: MenuState(StateContext& stateContext); void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; private: - void DrawMenu(); + void DrawMenu() override; - StateContext& m_context; - Text m_text; NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); int m_selectedNextState; }; diff --git a/tests/Engine/Utility/EventHandler/MouseClickState.cpp b/tests/Engine/Platform/EventHandler/MouseClickState.cpp similarity index 88% rename from tests/Engine/Utility/EventHandler/MouseClickState.cpp rename to tests/Engine/Platform/EventHandler/MouseClickState.cpp index bc2627195..74cb8ef79 100644 --- a/tests/Engine/Utility/EventHandler/MouseClickState.cpp +++ b/tests/Engine/Platform/EventHandler/MouseClickState.cpp @@ -7,16 +7,13 @@ #include MouseClickState::MouseClickState(StateContext& context) : -State(), -m_context(context), -m_text(context) +BaseState(context) { } void MouseClickState::Enter(Ndk::StateMachine& fsm) { - m_text.SetVisible(true); - DrawMenu(); + BaseState::Enter(fsm); Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) @@ -43,16 +40,6 @@ void MouseClickState::Enter(Ndk::StateMachine& fsm) }); } -void MouseClickState::Leave(Ndk::StateMachine& /*fsm*/) -{ - m_text.SetVisible(false); -} - -bool MouseClickState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) -{ - return true; -} - void MouseClickState::DrawMenu() { m_text.SetContent("Click in the windows, this text should change !\nM for Menu"); diff --git a/tests/Engine/Utility/EventHandler/MouseClickState.hpp b/tests/Engine/Platform/EventHandler/MouseClickState.hpp similarity index 67% rename from tests/Engine/Utility/EventHandler/MouseClickState.hpp rename to tests/Engine/Platform/EventHandler/MouseClickState.hpp index 28c4203a9..9a0e38077 100644 --- a/tests/Engine/Utility/EventHandler/MouseClickState.hpp +++ b/tests/Engine/Platform/EventHandler/MouseClickState.hpp @@ -1,11 +1,7 @@ #ifndef __MOUSECLICKSTATE_HPP__ #define __MOUSECLICKSTATE_HPP__ -#include "Text.hpp" - -#include - -#include +#include "BaseState.hpp" class StateContext; @@ -16,21 +12,18 @@ enum class MouseStatus Released }; -class MouseClickState : public Ndk::State +class MouseClickState : public BaseState { public: MouseClickState(StateContext& stateContext); void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; private: - void DrawMenu(); + void DrawMenu() override; + void ManageInput(MouseStatus mouseStatus, const Nz::WindowEvent::MouseButtonEvent& mouse, Ndk::StateMachine& fsm); - StateContext& m_context; - Text m_text; NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); NazaraSlot(Nz::EventHandler, OnMouseButtonDoubleClicked, m_mouseButtonDoubleClickedSlot); NazaraSlot(Nz::EventHandler, OnMouseButtonPressed, m_mouseButtonPressedSlot); diff --git a/tests/Engine/Utility/EventHandler/MouseEnterState.cpp b/tests/Engine/Platform/EventHandler/MouseEnterState.cpp similarity index 78% rename from tests/Engine/Utility/EventHandler/MouseEnterState.cpp rename to tests/Engine/Platform/EventHandler/MouseEnterState.cpp index 2a13f1c1e..1eb2ca9e2 100644 --- a/tests/Engine/Utility/EventHandler/MouseEnterState.cpp +++ b/tests/Engine/Platform/EventHandler/MouseEnterState.cpp @@ -7,16 +7,13 @@ #include MouseEnterState::MouseEnterState(StateContext& context) : -State(), -m_context(context), -m_text(context) +BaseState(context) { } void MouseEnterState::Enter(Ndk::StateMachine& fsm) { - m_text.SetVisible(true); - DrawMenu(); + BaseState::Enter(fsm); Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) @@ -38,16 +35,6 @@ void MouseEnterState::Enter(Ndk::StateMachine& fsm) }); } -void MouseEnterState::Leave(Ndk::StateMachine& /*fsm*/) -{ - m_text.SetVisible(false); -} - -bool MouseEnterState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) -{ - return true; -} - void MouseEnterState::DrawMenu() { m_text.SetContent("Move your mouse outside the windows, this text should change !\nM for Menu"); diff --git a/tests/Engine/Utility/EventHandler/MouseEnterState.hpp b/tests/Engine/Platform/EventHandler/MouseEnterState.hpp similarity index 54% rename from tests/Engine/Utility/EventHandler/MouseEnterState.hpp rename to tests/Engine/Platform/EventHandler/MouseEnterState.hpp index b5c7a72be..2328149ea 100644 --- a/tests/Engine/Utility/EventHandler/MouseEnterState.hpp +++ b/tests/Engine/Platform/EventHandler/MouseEnterState.hpp @@ -1,28 +1,20 @@ #ifndef __MOUSEENTERSTATE_HPP__ #define __MOUSEENTERSTATE_HPP__ -#include "Text.hpp" - -#include - -#include +#include "BaseState.hpp" class StateContext; -class MouseEnterState : public Ndk::State +class MouseEnterState : public BaseState { public: MouseEnterState(StateContext& stateContext); void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; private: - void DrawMenu(); + void DrawMenu() override; - StateContext& m_context; - Text m_text; NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); NazaraSlot(Nz::EventHandler, OnMouseEntered, m_mouseEnteredSlot); NazaraSlot(Nz::EventHandler, OnMouseLeft, m_mouseLeftSlot); diff --git a/tests/Engine/Utility/EventHandler/MouseMoveState.cpp b/tests/Engine/Platform/EventHandler/MouseMoveState.cpp similarity index 82% rename from tests/Engine/Utility/EventHandler/MouseMoveState.cpp rename to tests/Engine/Platform/EventHandler/MouseMoveState.cpp index 6a2cbd947..f0fcb3659 100644 --- a/tests/Engine/Utility/EventHandler/MouseMoveState.cpp +++ b/tests/Engine/Platform/EventHandler/MouseMoveState.cpp @@ -7,16 +7,13 @@ #include MouseMoveState::MouseMoveState(StateContext& context) : -State(), -m_context(context), -m_text(context) +BaseState(context) { } void MouseMoveState::Enter(Ndk::StateMachine& fsm) { - m_text.SetVisible(true); - DrawMenu(); + BaseState::Enter(fsm); Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) @@ -38,16 +35,6 @@ void MouseMoveState::Enter(Ndk::StateMachine& fsm) }); } -void MouseMoveState::Leave(Ndk::StateMachine& /*fsm*/) -{ - m_text.SetVisible(false); -} - -bool MouseMoveState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) -{ - return true; -} - void MouseMoveState::DrawMenu() { m_text.SetContent("Move your mouse or your wheel, this text should change !\nM for Menu"); diff --git a/tests/Engine/Utility/EventHandler/MouseMoveState.hpp b/tests/Engine/Platform/EventHandler/MouseMoveState.hpp similarity index 54% rename from tests/Engine/Utility/EventHandler/MouseMoveState.hpp rename to tests/Engine/Platform/EventHandler/MouseMoveState.hpp index f94dc0998..9aade79f8 100644 --- a/tests/Engine/Utility/EventHandler/MouseMoveState.hpp +++ b/tests/Engine/Platform/EventHandler/MouseMoveState.hpp @@ -1,28 +1,20 @@ #ifndef __MOUSEMOVESTATE_HPP__ #define __MOUSEMOVESTATE_HPP__ -#include "Text.hpp" - -#include - -#include +#include "BaseState.hpp" class StateContext; -class MouseMoveState : public Ndk::State +class MouseMoveState : public BaseState { public: MouseMoveState(StateContext& stateContext); void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; private: - void DrawMenu(); + void DrawMenu() override; - StateContext& m_context; - Text m_text; NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); NazaraSlot(Nz::EventHandler, OnMouseMoved, m_mouseMovedSlot); NazaraSlot(Nz::EventHandler, OnMouseWheelMoved, m_mouseWheelMovedSlot); diff --git a/tests/Engine/Utility/EventHandler/StateContext.cpp b/tests/Engine/Platform/EventHandler/StateContext.cpp similarity index 100% rename from tests/Engine/Utility/EventHandler/StateContext.cpp rename to tests/Engine/Platform/EventHandler/StateContext.cpp diff --git a/tests/Engine/Utility/EventHandler/StateContext.hpp b/tests/Engine/Platform/EventHandler/StateContext.hpp similarity index 100% rename from tests/Engine/Utility/EventHandler/StateContext.hpp rename to tests/Engine/Platform/EventHandler/StateContext.hpp diff --git a/tests/Engine/Utility/EventHandler/StateFactory.cpp b/tests/Engine/Platform/EventHandler/StateFactory.cpp similarity index 100% rename from tests/Engine/Utility/EventHandler/StateFactory.cpp rename to tests/Engine/Platform/EventHandler/StateFactory.cpp diff --git a/tests/Engine/Utility/EventHandler/StateFactory.hpp b/tests/Engine/Platform/EventHandler/StateFactory.hpp similarity index 100% rename from tests/Engine/Utility/EventHandler/StateFactory.hpp rename to tests/Engine/Platform/EventHandler/StateFactory.hpp diff --git a/tests/Engine/Utility/EventHandler/Text.cpp b/tests/Engine/Platform/EventHandler/Text.cpp similarity index 100% rename from tests/Engine/Utility/EventHandler/Text.cpp rename to tests/Engine/Platform/EventHandler/Text.cpp diff --git a/tests/Engine/Utility/EventHandler/Text.hpp b/tests/Engine/Platform/EventHandler/Text.hpp similarity index 100% rename from tests/Engine/Utility/EventHandler/Text.hpp rename to tests/Engine/Platform/EventHandler/Text.hpp diff --git a/tests/Engine/Utility/EventHandler/TextEnterState.cpp b/tests/Engine/Platform/EventHandler/TextEnterState.cpp similarity index 79% rename from tests/Engine/Utility/EventHandler/TextEnterState.cpp rename to tests/Engine/Platform/EventHandler/TextEnterState.cpp index 1a0516f29..2aa58da69 100644 --- a/tests/Engine/Utility/EventHandler/TextEnterState.cpp +++ b/tests/Engine/Platform/EventHandler/TextEnterState.cpp @@ -7,16 +7,13 @@ #include TextEnterState::TextEnterState(StateContext& context) : -State(), -m_context(context), -m_text(context) +BaseState(context) { } void TextEnterState::Enter(Ndk::StateMachine& fsm) { - m_text.SetVisible(true); - DrawMenu(); + BaseState::Enter(fsm); Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) @@ -36,16 +33,6 @@ void TextEnterState::Enter(Ndk::StateMachine& fsm) }); } -void TextEnterState::Leave(Ndk::StateMachine& /*fsm*/) -{ - m_text.SetVisible(false); -} - -bool TextEnterState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) -{ - return true; -} - void TextEnterState::DrawMenu() { m_text.SetContent("Enter some text, this text should change !\nM for Menu"); diff --git a/tests/Engine/Platform/EventHandler/TextEnterState.hpp b/tests/Engine/Platform/EventHandler/TextEnterState.hpp new file mode 100644 index 000000000..ed193d204 --- /dev/null +++ b/tests/Engine/Platform/EventHandler/TextEnterState.hpp @@ -0,0 +1,22 @@ +#ifndef __TEXTENTERSTATE_HPP__ +#define __TEXTENTERSTATE_HPP__ + +#include "BaseState.hpp" + +class StateContext; + +class TextEnterState : public BaseState +{ + public: + TextEnterState(StateContext& stateContext); + + void Enter(Ndk::StateMachine& fsm) override; + + private: + void DrawMenu() override; + + NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); + NazaraSlot(Nz::EventHandler, OnTextEntered, m_textEnteredSlot); +}; + +#endif // __TEXTENTERSTATE_HPP__ \ No newline at end of file diff --git a/tests/Engine/Utility/EventHandler/WindowModificationState.cpp b/tests/Engine/Platform/EventHandler/WindowModificationState.cpp similarity index 81% rename from tests/Engine/Utility/EventHandler/WindowModificationState.cpp rename to tests/Engine/Platform/EventHandler/WindowModificationState.cpp index e50d94f51..027185fe6 100644 --- a/tests/Engine/Utility/EventHandler/WindowModificationState.cpp +++ b/tests/Engine/Platform/EventHandler/WindowModificationState.cpp @@ -7,16 +7,13 @@ #include WindowModificationState::WindowModificationState(StateContext& context) : -State(), -m_context(context), -m_text(context) +BaseState(context) { } void WindowModificationState::Enter(Ndk::StateMachine& fsm) { - m_text.SetVisible(true); - DrawMenu(); + BaseState::Enter(fsm); Nz::EventHandler& eventHandler = m_context.window.GetEventHandler(); m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& key) @@ -38,16 +35,6 @@ void WindowModificationState::Enter(Ndk::StateMachine& fsm) }); } -void WindowModificationState::Leave(Ndk::StateMachine& /*fsm*/) -{ - m_text.SetVisible(false); -} - -bool WindowModificationState::Update(Ndk::StateMachine& /*fsm*/, float /*elapsedTime*/) -{ - return true; -} - void WindowModificationState::DrawMenu() { m_text.SetContent("Move the window or resize it, this text should change !\nM for Menu"); diff --git a/tests/Engine/Utility/EventHandler/WindowModificationState.hpp b/tests/Engine/Platform/EventHandler/WindowModificationState.hpp similarity index 53% rename from tests/Engine/Utility/EventHandler/WindowModificationState.hpp rename to tests/Engine/Platform/EventHandler/WindowModificationState.hpp index 4fb84188d..fce207039 100644 --- a/tests/Engine/Utility/EventHandler/WindowModificationState.hpp +++ b/tests/Engine/Platform/EventHandler/WindowModificationState.hpp @@ -1,28 +1,20 @@ #ifndef __WINDOWMODIFICATIONSTATE_HPP__ #define __WINDOWMODIFICATIONSTATE_HPP__ -#include "Text.hpp" - -#include - -#include +#include "BaseState.hpp" class StateContext; -class WindowModificationState : public Ndk::State +class WindowModificationState : public BaseState { public: WindowModificationState(StateContext& stateContext); void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; private: - void DrawMenu(); + void DrawMenu() override; - StateContext& m_context; - Text m_text; NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); NazaraSlot(Nz::EventHandler, OnMoved, m_movedSlot); NazaraSlot(Nz::EventHandler, OnResized, m_resizedSlot); diff --git a/tests/Engine/Utility/EventHandler/TextEnterState.hpp b/tests/Engine/Utility/EventHandler/TextEnterState.hpp deleted file mode 100644 index c9137c51d..000000000 --- a/tests/Engine/Utility/EventHandler/TextEnterState.hpp +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef __TEXTENTERSTATE_HPP__ -#define __TEXTENTERSTATE_HPP__ - -#include "Text.hpp" - -#include - -#include - -class StateContext; - -class TextEnterState : public Ndk::State -{ - public: - TextEnterState(StateContext& stateContext); - - void Enter(Ndk::StateMachine& fsm) override; - void Leave(Ndk::StateMachine& fsm) override; - bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; - - private: - void DrawMenu(); - - StateContext& m_context; - Text m_text; - NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); - NazaraSlot(Nz::EventHandler, OnTextEntered, m_textEnteredSlot); -}; - -#endif // __TEXTENTERSTATE_HPP__ \ No newline at end of file diff --git a/tests/SDK/NDK/BaseSystem.cpp b/tests/SDK/NDK/BaseSystem.cpp index 3bb0fa9e4..84649df22 100644 --- a/tests/SDK/NDK/BaseSystem.cpp +++ b/tests/SDK/NDK/BaseSystem.cpp @@ -32,7 +32,8 @@ SCENARIO("BaseSystem", "[NDK][BASESYSTEM]") { GIVEN("Our TestSystem") { - Ndk::World world; + Ndk::World world(false); + Ndk::BaseSystem& system = world.AddSystem(); REQUIRE(&system.GetWorld() == &world); diff --git a/tests/SDK/NDK/Entity.cpp b/tests/SDK/NDK/Entity.cpp index dd3216fb0..7d59cfc20 100644 --- a/tests/SDK/NDK/Entity.cpp +++ b/tests/SDK/NDK/Entity.cpp @@ -55,7 +55,8 @@ SCENARIO("Entity", "[NDK][ENTITY]") { GIVEN("A world & an entity") { - Ndk::World world; + Ndk::World world(false); + Ndk::BaseSystem& system = world.AddSystem(); Ndk::EntityHandle entity = world.CreateEntity(); diff --git a/tests/SDK/NDK/EntityList.cpp b/tests/SDK/NDK/EntityList.cpp index 30a57573d..0642b50b7 100644 --- a/tests/SDK/NDK/EntityList.cpp +++ b/tests/SDK/NDK/EntityList.cpp @@ -6,7 +6,8 @@ SCENARIO("EntityList", "[NDK][ENTITYLIST]") { GIVEN("A world & a set of entities") { - Ndk::World world; + Ndk::World world(false); + const Ndk::EntityHandle& entity = world.CreateEntity(); Ndk::EntityList entityList; entityList.Insert(entity); diff --git a/tests/SDK/NDK/EntityOwner.cpp b/tests/SDK/NDK/EntityOwner.cpp index f2fd76d58..c28ed7d91 100644 --- a/tests/SDK/NDK/EntityOwner.cpp +++ b/tests/SDK/NDK/EntityOwner.cpp @@ -6,7 +6,7 @@ SCENARIO("EntityOwner", "[NDK][ENTITYOWNER]") { GIVEN("A world & an entity") { - Ndk::World world; + Ndk::World world(false); Ndk::EntityHandle entity = world.CreateEntity(); WHEN("We set the ownership of the entity to our owner") diff --git a/tests/SDK/NDK/Systems/PhysicsSystem2D.cpp b/tests/SDK/NDK/Systems/PhysicsSystem2D.cpp new file mode 100644 index 000000000..9173ab167 --- /dev/null +++ b/tests/SDK/NDK/Systems/PhysicsSystem2D.cpp @@ -0,0 +1,154 @@ +#include +#include +#include +#include +#include +#include + +Ndk::EntityHandle CreateBaseEntity(Ndk::World& world, const Nz::Vector2f& position, const Nz::Rectf AABB); + +SCENARIO("PhysicsSystem2D", "[NDK][PHYSICSSYSTEM2D]") +{ + GIVEN("A world and an entity") + { + Ndk::World world; + + Nz::Vector2f position(2.f, 3.f); + Nz::Rectf movingAABB(0.f, 0.f, 16.f, 18.f); + Ndk::EntityHandle movingEntity = CreateBaseEntity(world, position, movingAABB); + Ndk::NodeComponent& nodeComponent = movingEntity->GetComponent(); + Ndk::PhysicsComponent2D& physicsComponent2D = movingEntity->AddComponent(); + + world.GetSystem().SetFixedUpdateRate(30.f); + + WHEN("We update the world") + { + world.Update(1.f); + + THEN("Entity should have correct bounding box") + { + REQUIRE(nodeComponent.GetPosition() == position); + movingAABB.Translate(position); + REQUIRE(physicsComponent2D.GetAABB() == movingAABB); + } + } + + WHEN("We make it collide with a wall") + { + int rawDistance = 3; + Nz::Vector2f distance(rawDistance, 0.f); + Nz::Vector2f wallPosition = position + Nz::Vector2f(movingAABB.width, 0.f) + distance; + Nz::Rectf wallAABB(0.f, 0.f, 100.f, 100.f); + Ndk::EntityHandle wallEntity = CreateBaseEntity(world, wallPosition, wallAABB); + + world.Update(1.f); + + THEN("It should moved freely") + { + REQUIRE(nodeComponent.GetPosition() == position); + movingAABB.Translate(position); + REQUIRE(physicsComponent2D.GetAABB() == movingAABB); + + physicsComponent2D.SetVelocity(Nz::Vector2f::UnitX()); + + for (int i = 0; i < rawDistance; ++i) + { + world.Update(1.f); + position += Nz::Vector2f::UnitX(); + REQUIRE(nodeComponent.GetPosition() == position); + movingAABB.Translate(Nz::Vector2f::UnitX()); + REQUIRE(physicsComponent2D.GetAABB() == movingAABB); + } + } + + AND_THEN("It should be stopped by it") + { + world.Update(1.f); + REQUIRE(nodeComponent.GetPosition().SquaredDistance(position) < 0.1f); + } + } + } + + GIVEN("A world and a simple entity") + { + Ndk::World world; + + Nz::Vector2f position(0.f, 0.f); + Nz::Rectf movingAABB(0.f, 0.f, 1.f, 2.f); + Ndk::EntityHandle movingEntity = CreateBaseEntity(world, position, movingAABB); + Ndk::NodeComponent& nodeComponent = movingEntity->GetComponent(); + Ndk::PhysicsComponent2D& physicsComponent2D = movingEntity->AddComponent(); + + world.GetSystem().SetFixedUpdateRate(30.f); + + WHEN("We make rotate our entity") + { + float angularSpeed = Nz::FromDegrees(45.f); + physicsComponent2D.SetAngularVelocity(angularSpeed); + world.Update(2.f); + + THEN("It should have been rotated") + { + CHECK(physicsComponent2D.GetAngularVelocity() == angularSpeed); + CHECK(physicsComponent2D.GetAABB() == Nz::Rectf(-2.f, 0.f, 2.f, 1.f)); + CHECK(physicsComponent2D.GetRotation() == Approx(Nz::FromDegrees(90.f))); + CHECK(nodeComponent.GetRotation().ToEulerAngles().roll == Approx(Nz::FromDegrees(90.f))); + } + } + + WHEN("We put a force on it") + { + float stepSize = world.GetSystem().GetWorld().GetStepSize(); + Nz::Vector2f velocity = Nz::Vector2f::UnitX(); + physicsComponent2D.AddForce(velocity / stepSize); + world.Update(1.f); + + THEN("Velocity should be the one targetted") + { + REQUIRE(physicsComponent2D.GetVelocity() == velocity); + world.Update(99.f); + REQUIRE(physicsComponent2D.GetPosition().Distance(Nz::Vector2f::UnitX() * 100.f) < 1.f); + REQUIRE(nodeComponent.GetPosition().Distance(Nz::Vector2f::UnitX() * 100.f) < 1.f); + } + } + } + + GIVEN("A world and a simple entity not at the origin") + { + Ndk::World world; + + Nz::Vector2f position(3.f, 4.f); + Nz::Rectf movingAABB(0.f, 0.f, 1.f, 2.f); + Ndk::EntityHandle movingEntity = CreateBaseEntity(world, position, movingAABB); + Ndk::NodeComponent& nodeComponent = movingEntity->GetComponent(); + Ndk::PhysicsComponent2D& physicsComponent2D = movingEntity->AddComponent(); + + world.GetSystem().SetFixedUpdateRate(30.f); + + WHEN("We make rotate our entity") + { + float angularSpeed = Nz::FromDegrees(45.f); + physicsComponent2D.SetAngularVelocity(angularSpeed); + world.Update(2.f); + + THEN("It should have been rotated") + { + CHECK(physicsComponent2D.GetAngularVelocity() == angularSpeed); + CHECK(physicsComponent2D.GetAABB() == Nz::Rectf(1.f, 4.f, 2.f, 1.f)); + CHECK(physicsComponent2D.GetRotation() == Approx(Nz::FromDegrees(90.f))); + CHECK(nodeComponent.GetPosition() == position); + CHECK(nodeComponent.GetRotation().ToEulerAngles().roll == Approx(Nz::FromDegrees(90.f))); + } + } + } +} + +Ndk::EntityHandle CreateBaseEntity(Ndk::World& world, const Nz::Vector2f& position, const Nz::Rectf AABB) +{ + Ndk::EntityHandle entity = world.CreateEntity(); + Ndk::NodeComponent& nodeComponent = entity->AddComponent(); + nodeComponent.SetPosition(position); + Nz::BoxCollider2DRef collisionBox = Nz::BoxCollider2D::New(AABB); + entity->AddComponent(collisionBox); + return entity; +} diff --git a/tests/SDK/NDK/Systems/PhysicsSystem3D.cpp b/tests/SDK/NDK/Systems/PhysicsSystem3D.cpp index 3cb0d6bdb..b66aa89b7 100644 --- a/tests/SDK/NDK/Systems/PhysicsSystem3D.cpp +++ b/tests/SDK/NDK/Systems/PhysicsSystem3D.cpp @@ -5,7 +5,7 @@ #include #include -SCENARIO("PhysicsSystem", "[NDK][PHYSICSSYSTEM]") +SCENARIO("PhysicsSystem3D", "[NDK][PHYSICSSYSTEM3D]") { GIVEN("A world and a static entity & a dynamic entity") { diff --git a/tests/SDK/NDK/Systems/RenderSystem.cpp b/tests/SDK/NDK/Systems/RenderSystem.cpp index f106b3aae..0ceefaa07 100644 --- a/tests/SDK/NDK/Systems/RenderSystem.cpp +++ b/tests/SDK/NDK/Systems/RenderSystem.cpp @@ -1,13 +1,12 @@ #include #include -#include -#include -#include -#include -#include +#include +#include #include #include +void CompareAABB(const Nz::Rectf& aabb, const Nz::BoundingVolumef& boundingVolume); + SCENARIO("RenderSystem", "[NDK][RenderSystem]") { GIVEN("A world with a camera, a drawable, a light and some particles") @@ -41,4 +40,79 @@ SCENARIO("RenderSystem", "[NDK][RenderSystem]") } } } + + GIVEN("A world with 2D coordinates (upper-left) and an entity with graphics and physics") + { + Ndk::World world; + world.GetSystem().SetGlobalUp(Nz::Vector3f::Down()); + const Ndk::EntityHandle& entity = world.CreateEntity(); + + Nz::Vector2f position(3.f, 4.f); + Ndk::NodeComponent& nodeComponent = entity->AddComponent(); + nodeComponent.SetPosition(position); + + Nz::Vector2f dimensions(1.f, 2.f); + Ndk::GraphicsComponent& graphicsComponent = entity->AddComponent(); + Nz::SpriteRef sprite = Nz::Sprite::New(); + sprite->SetSize(dimensions); + graphicsComponent.Attach(sprite); + + Nz::Rectf aabb(Nz::Vector2f::Zero(), dimensions); + Nz::BoxCollider2DRef boxCollider2D = Nz::BoxCollider2D::New(aabb); + entity->AddComponent(boxCollider2D); + Ndk::PhysicsComponent2D& physicsComponent2D = entity->AddComponent(); + + world.Update(1.f); + + WHEN("We move it") + { + Nz::Vector2f velocity = Nz::Vector2f::UnitY(); + physicsComponent2D.SetVelocity(velocity); + world.Update(1.f); + + THEN("Graphics and physics should be synchronised") + { + CHECK(nodeComponent.GetPosition() == position + velocity); + CHECK(physicsComponent2D.GetAABB() == aabb.Translate(position + velocity)); + CompareAABB(physicsComponent2D.GetAABB(), graphicsComponent.GetBoundingVolume()); + } + } + + WHEN("We set an angular velocity") + { + float angularSpeed = Nz::FromDegrees(90.f); + physicsComponent2D.SetAngularVelocity(angularSpeed); + world.Update(1.f); + + THEN("We expect those to be true") + { + CHECK(physicsComponent2D.GetAngularVelocity() == Approx(angularSpeed)); + CHECK(physicsComponent2D.GetRotation() == Approx(angularSpeed)); + CHECK(physicsComponent2D.GetAABB() == Nz::Rectf(1.f, 4.f, 2.f, 1.f)); + CompareAABB(physicsComponent2D.GetAABB(), graphicsComponent.GetBoundingVolume()); + + world.Update(1.f); + CHECK(physicsComponent2D.GetRotation() == Approx(2.f * angularSpeed)); + CHECK(physicsComponent2D.GetAABB() == Nz::Rectf(2.f, 2.f, 1.f, 2.f)); + CompareAABB(physicsComponent2D.GetAABB(), graphicsComponent.GetBoundingVolume()); + + world.Update(1.f); + CHECK(physicsComponent2D.GetRotation() == Approx(3.f * angularSpeed)); + CHECK(physicsComponent2D.GetAABB() == Nz::Rectf(3.f, 3.f, 2.f, 1.f)); + CompareAABB(physicsComponent2D.GetAABB(), graphicsComponent.GetBoundingVolume()); + + world.Update(1.f); + CHECK(physicsComponent2D.GetRotation() == Approx(4.f * angularSpeed)); + } + } + } +} + +void CompareAABB(const Nz::Rectf& aabb, const Nz::BoundingVolumef& boundingVolume) +{ + Nz::Boxf box = boundingVolume.aabb; + CHECK(aabb.x == Approx(box.x)); + CHECK(aabb.y == Approx(box.y)); + CHECK(aabb.width == Approx(box.width)); + CHECK(aabb.height == Approx(box.height)); } \ No newline at end of file diff --git a/tests/SDK/NDK/Systems/VelocitySystem.cpp b/tests/SDK/NDK/Systems/VelocitySystem.cpp index bfde34896..aff645106 100644 --- a/tests/SDK/NDK/Systems/VelocitySystem.cpp +++ b/tests/SDK/NDK/Systems/VelocitySystem.cpp @@ -13,6 +13,8 @@ SCENARIO("VelocitySystem", "[NDK][VELOCITYSYSTEM]") Ndk::VelocityComponent& velocityComponent = entity->AddComponent(); Ndk::NodeComponent& nodeComponent = entity->AddComponent(); + world.GetSystem().SetFixedUpdateRate(30.f); + WHEN("We give a speed to our entity") { Nz::Vector3f velocity = Nz::Vector3f::Unit() * 2.f; diff --git a/tests/SDK/NDK/World.cpp b/tests/SDK/NDK/World.cpp index d46b6621b..4d25db5f6 100644 --- a/tests/SDK/NDK/World.cpp +++ b/tests/SDK/NDK/World.cpp @@ -55,7 +55,7 @@ SCENARIO("World", "[NDK][WORLD]") { GIVEN("A brave new world and the update system") { - Ndk::World world; + Ndk::World world(false); Ndk::BaseSystem& system = world.AddSystem(); WHEN("We had a new entity with an updatable component and a system") diff --git a/tests/main.cpp b/tests/main.cpp index 112b7498c..34bb79e5f 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include