diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..ee31794e8 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +# http://editorconfig.org/ + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{hpp,inl,cpp,lua}] +indent_style = tab + +[*.html] +indent_size = 4 +indent_style = space diff --git a/.gitignore b/.gitignore index bc5494fc0..d455ab7a9 100644 --- a/.gitignore +++ b/.gitignore @@ -11,7 +11,6 @@ plugins/lib/* package/* # Example files ->>>>>>> master examples/bin/*.exe examples/bin/*.pdb examples/bin/*.dll @@ -36,6 +35,7 @@ build/scripts/features/index.html doc # Codeblocks +*.save-failed build/**/*.cbp build/**/*.cbp build/**/*.cbTemp @@ -47,6 +47,9 @@ build/**/*.workspace # CodeLite build/**/*.project +# GMake +build/**/*.make + # Visual Studio build/**/*.pdb build/**/*.filters diff --git a/Doxyfile b/Doxyfile index 47af03df4..04a327a38 100644 --- a/Doxyfile +++ b/Doxyfile @@ -38,7 +38,7 @@ PROJECT_NAME = "Nazara Engine" # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = 0.1 +PROJECT_NUMBER = 0.2 # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a diff --git a/SDK/include/NDK/Application.inl b/SDK/include/NDK/Application.inl index d26a2daa8..0b4f2ce10 100644 --- a/SDK/include/NDK/Application.inl +++ b/SDK/include/NDK/Application.inl @@ -59,7 +59,7 @@ namespace Ndk * \param args Arguments used to create the window */ #ifndef NDK_SERVER - template + template T& Application::AddWindow(Args&&... args) { static_assert(std::is_base_of::value, "Type must inherit Window"); @@ -82,7 +82,7 @@ namespace Ndk * \param args Arguments used to create the world */ - template + template World& Application::AddWorld(Args&&... args) { m_worlds.emplace_back(std::forward(args)...); @@ -373,9 +373,9 @@ namespace Ndk { } - inline Application::WindowInfo::WindowInfo(std::unique_ptr&& window) : + inline Application::WindowInfo::WindowInfo(std::unique_ptr&& windowPtr) : renderTarget(nullptr), - window(std::move(window)) + window(std::move(windowPtr)) { } #endif diff --git a/SDK/include/NDK/BaseSystem.hpp b/SDK/include/NDK/BaseSystem.hpp index a4ff0bf41..7433f7d04 100644 --- a/SDK/include/NDK/BaseSystem.hpp +++ b/SDK/include/NDK/BaseSystem.hpp @@ -35,6 +35,7 @@ namespace Ndk inline const std::vector& GetEntities() const; inline SystemIndex GetIndex() const; + inline int GetUpdateOrder() const; inline float GetUpdateRate() const; inline World& GetWorld() const; @@ -42,6 +43,7 @@ namespace Ndk inline bool HasEntity(const Entity* entity) const; + void SetUpdateOrder(int updateOrder); inline void SetUpdateRate(float updatePerSecond); inline void Update(float elapsedTime); @@ -93,6 +95,7 @@ namespace Ndk bool m_updateEnabled; 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 31a0c314e..79971e3d6 100644 --- a/SDK/include/NDK/BaseSystem.inl +++ b/SDK/include/NDK/BaseSystem.inl @@ -16,7 +16,9 @@ namespace Ndk inline BaseSystem::BaseSystem(SystemIndex systemId) : m_systemIndex(systemId), - m_updateEnabled(true) + m_world(nullptr), + m_updateEnabled(true), + m_updateOrder(0) { SetUpdateRate(30); } @@ -33,7 +35,8 @@ namespace Ndk m_systemIndex(system.m_systemIndex), m_updateEnabled(system.m_updateEnabled), m_updateCounter(0.f), - m_updateRate(system.m_updateRate) + m_updateRate(system.m_updateRate), + m_updateOrder(system.m_updateOrder) { } @@ -69,7 +72,18 @@ namespace Ndk } /*! - * \brief Gets the rate of update for the system + * \brief Gets the update order of the system + * \return Update order + * + * \see SetUpdateOrder + */ + inline int BaseSystem::GetUpdateOrder() const + { + return m_updateOrder; + } + + /*! + * \brief Gets the rate of update of the system * \return Update rate */ diff --git a/SDK/include/NDK/Components.hpp b/SDK/include/NDK/Components.hpp index afa25ade8..3a2916009 100644 --- a/SDK/include/NDK/Components.hpp +++ b/SDK/include/NDK/Components.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 30 Jul 2016 at 15:29:16 +// This file was automatically generated #pragma once @@ -6,6 +6,7 @@ #define NDK_COMPONENTS_GLOBAL_HPP #include +#include #include #include #include @@ -13,6 +14,7 @@ #include #include #include +#include #include #include diff --git a/SDK/include/NDK/Components/CameraComponent.hpp b/SDK/include/NDK/Components/CameraComponent.hpp index b26901a79..5a9efe742 100644 --- a/SDK/include/NDK/Components/CameraComponent.hpp +++ b/SDK/include/NDK/Components/CameraComponent.hpp @@ -18,9 +18,12 @@ namespace Ndk { + class CameraComponent; class Entity; - class NDK_API CameraComponent : public Component, public Nz::AbstractViewer + using CameraComponentHandle = Nz::ObjectHandle; + + class NDK_API CameraComponent : public Component, public Nz::AbstractViewer, public Nz::HandledObject { public: inline CameraComponent(); @@ -51,7 +54,7 @@ namespace Ndk float GetZNear() const override; inline void SetFOV(float fov); - inline void SetLayer(unsigned int layer); + void SetLayer(unsigned int layer); inline void SetProjectionType(Nz::ProjectionType projection); inline void SetSize(const Nz::Vector2f& size); inline void SetSize(float width, float height); @@ -61,6 +64,8 @@ namespace Ndk inline void SetZFar(float zFar); inline void SetZNear(float zNear); + inline bool UpdateVisibility(std::size_t visibilityHash); + static ComponentIndex componentIndex; private: @@ -86,6 +91,7 @@ namespace Ndk NazaraSlot(Nz::RenderTarget, OnRenderTargetRelease, m_targetReleaseSlot); NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_targetResizeSlot); + std::size_t m_visibilityHash; Nz::ProjectionType m_projectionType; mutable Nz::Frustumf m_frustum; mutable Nz::Matrix4f m_projectionMatrix; diff --git a/SDK/include/NDK/Components/CameraComponent.inl b/SDK/include/NDK/Components/CameraComponent.inl index 541096de5..9aadfd509 100644 --- a/SDK/include/NDK/Components/CameraComponent.inl +++ b/SDK/include/NDK/Components/CameraComponent.inl @@ -13,6 +13,7 @@ namespace Ndk */ inline CameraComponent::CameraComponent() : + m_visibilityHash(0U), m_projectionType(Nz::ProjectionType_Perspective), m_targetRegion(0.f, 0.f, 1.f, 1.f), m_target(nullptr), @@ -38,6 +39,7 @@ namespace Ndk inline CameraComponent::CameraComponent(const CameraComponent& camera) : Component(camera), AbstractViewer(camera), + m_visibilityHash(camera.m_visibilityHash), m_projectionType(camera.m_projectionType), m_targetRegion(camera.m_targetRegion), m_target(nullptr), @@ -99,7 +101,7 @@ namespace Ndk * \brief Gets the field of view of the camera * \return Field of view of the camera */ - float CameraComponent::GetFOV() const + inline float CameraComponent::GetFOV() const { return m_fov; } @@ -280,6 +282,26 @@ namespace Ndk InvalidateProjectionMatrix(); } + /*! + * \brief Update the camera component visibility hash + * + * This is used with CullingList (which produce a visibility hash) + * + * \param visibilityHash New visibility hash + * + * \return True if the visibility hash is not the same as before + */ + inline bool CameraComponent::UpdateVisibility(std::size_t visibilityHash) + { + if (m_visibilityHash != visibilityHash) + { + m_visibilityHash = visibilityHash; + return true; + } + + return false; + } + /*! * \brief Invalidates the frustum */ diff --git a/SDK/include/NDK/Components/CollisionComponent2D.hpp b/SDK/include/NDK/Components/CollisionComponent2D.hpp new file mode 100644 index 000000000..b282a850e --- /dev/null +++ b/SDK/include/NDK/Components/CollisionComponent2D.hpp @@ -0,0 +1,58 @@ +// Copyright (C) 2015 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_COMPONENTS_COLLISIONCOMPONENT2D_HPP +#define NDK_COMPONENTS_COLLISIONCOMPONENT2D_HPP + +#include +#include +#include + +namespace Nz +{ + class RigidBody2D; +} + +namespace Ndk +{ + class Entity; + + class NDK_API CollisionComponent2D : public Component + { + friend class PhysicsSystem2D; + + public: + CollisionComponent2D(Nz::Collider2DRef geom = Nz::Collider2DRef()); + CollisionComponent2D(const CollisionComponent2D& collision); + ~CollisionComponent2D() = default; + + const Nz::Collider2DRef& GetGeom() const; + + void SetGeom(Nz::Collider2DRef geom); + + CollisionComponent2D& operator=(Nz::Collider2DRef geom); + CollisionComponent2D& operator=(CollisionComponent2D&& collision) = default; + + static ComponentIndex componentIndex; + + private: + void InitializeStaticBody(); + Nz::RigidBody2D* GetStaticBody(); + + void OnAttached() override; + void OnComponentAttached(BaseComponent& component) override; + void OnComponentDetached(BaseComponent& component) override; + void OnDetached() override; + + std::unique_ptr m_staticBody; + Nz::Collider2DRef m_geom; + bool m_bodyUpdated; + }; +} + +#include + +#endif // NDK_COMPONENTS_COLLISIONCOMPONENT2D_HPP diff --git a/SDK/include/NDK/Components/CollisionComponent2D.inl b/SDK/include/NDK/Components/CollisionComponent2D.inl new file mode 100644 index 000000000..62bf422cb --- /dev/null +++ b/SDK/include/NDK/Components/CollisionComponent2D.inl @@ -0,0 +1,70 @@ +// Copyright (C) 2015 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 + +#include +#include +#include +#include +#include + +namespace Ndk +{ + /*! + * \brief Constructs a CollisionComponent2D object with a geometry + * + * \param geom Reference to a geometry symbolizing the entity + */ + + inline CollisionComponent2D::CollisionComponent2D(Nz::Collider2DRef geom) : + m_geom(std::move(geom)), + m_bodyUpdated(false) + { + } + + /*! + * \brief Constructs a CollisionComponent2D object by copy semantic + * + * \param collision CollisionComponent2D to copy + */ + + inline CollisionComponent2D::CollisionComponent2D(const CollisionComponent2D& collision) : + m_geom(collision.m_geom), + m_bodyUpdated(false) + { + } + + /*! + * \brief Gets the geometry representing the entity + * \return A constant reference to the physics geometry + */ + + inline const Nz::Collider2DRef& CollisionComponent2D::GetGeom() const + { + return m_geom; + } + + /*! + * \brief Assigns the geometry to this component + * \return A reference to this + * + * \param geom Reference to a geometry symbolizing the entity + */ + + inline CollisionComponent2D& CollisionComponent2D::operator=(Nz::Collider2DRef geom) + { + SetGeom(geom); + + return *this; + } + + /*! + * \brief Gets the static body used by the entity + * \return A pointer to the entity + */ + + inline Nz::RigidBody2D* CollisionComponent2D::GetStaticBody() + { + return m_staticBody.get(); + } +} diff --git a/SDK/include/NDK/Components/CollisionComponent3D.hpp b/SDK/include/NDK/Components/CollisionComponent3D.hpp index f6a07ede6..9a9671660 100644 --- a/SDK/include/NDK/Components/CollisionComponent3D.hpp +++ b/SDK/include/NDK/Components/CollisionComponent3D.hpp @@ -4,8 +4,8 @@ #pragma once -#ifndef NDK_COMPONENTS_COLLISIONCOMPONENT_HPP -#define NDK_COMPONENTS_COLLISIONCOMPONENT_HPP +#ifndef NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP +#define NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP #include #include @@ -23,7 +23,6 @@ namespace Ndk class NDK_API CollisionComponent3D : public Component { friend class PhysicsSystem3D; - friend class StaticCollisionSystem; public: CollisionComponent3D(Nz::Collider3DRef geom = Nz::Collider3DRef()); @@ -56,4 +55,4 @@ namespace Ndk #include -#endif // NDK_COMPONENTS_COLLISIONCOMPONENT_HPP +#endif // NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP diff --git a/SDK/include/NDK/Components/GraphicsComponent.hpp b/SDK/include/NDK/Components/GraphicsComponent.hpp index b536fc154..418500a96 100644 --- a/SDK/include/NDK/Components/GraphicsComponent.hpp +++ b/SDK/include/NDK/Components/GraphicsComponent.hpp @@ -8,6 +8,7 @@ #ifndef NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP #define NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP +#include #include #include #include @@ -16,6 +17,7 @@ namespace Ndk { class GraphicsComponent; + using GraphicsComponentCullingList = Nz::CullingList; using GraphicsComponentHandle = Nz::ObjectHandle; class NDK_API GraphicsComponent : public Component, public Nz::HandledObject @@ -29,10 +31,11 @@ namespace Ndk inline GraphicsComponent(const GraphicsComponent& graphicsComponent); ~GraphicsComponent() = default; - inline void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const; + inline void AddToCullingList(GraphicsComponentCullingList* cullingList) const; + void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const; - inline void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0); - inline void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0); + void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0); + void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0); inline void Clear(); @@ -46,10 +49,12 @@ namespace Ndk inline const Nz::BoundingVolumef& GetBoundingVolume() const; + inline void RemoveFromCullingList(GraphicsComponentCullingList* cullingList) const; + static ComponentIndex componentIndex; private: - inline void InvalidateBoundingVolume(); + inline void InvalidateBoundingVolume() const; void InvalidateRenderableData(const Nz::InstancedRenderable* renderable, Nz::UInt32 flags, std::size_t index); inline void InvalidateRenderables(); inline void InvalidateTransformMatrix(); @@ -73,19 +78,20 @@ namespace Ndk { } - Renderable(Renderable&& renderable) noexcept : - renderableInvalidationSlot(std::move(renderable.renderableInvalidationSlot)), - renderableReleaseSlot(std::move(renderable.renderableReleaseSlot)), - data(std::move(renderable.data)), - renderable(std::move(renderable.renderable)), - dataUpdated(renderable.dataUpdated) + Renderable(Renderable&& rhs) noexcept : + renderableBoundingVolumeInvalidationSlot(std::move(rhs.renderableBoundingVolumeInvalidationSlot)), + renderableDataInvalidationSlot(std::move(rhs.renderableDataInvalidationSlot)), + renderableReleaseSlot(std::move(rhs.renderableReleaseSlot)), + data(std::move(rhs.data)), + renderable(std::move(rhs.renderable)), + dataUpdated(rhs.dataUpdated) { } ~Renderable() { // Disconnect release slot before releasing instanced renderable reference - renderableReleaseSlot.Disconnect(); + renderableReleaseSlot.Disconnect(); } Renderable& operator=(Renderable&& r) noexcept @@ -93,13 +99,15 @@ namespace Ndk data = std::move(r.data); dataUpdated = r.dataUpdated; renderable = std::move(r.renderable); - renderableInvalidationSlot = std::move(r.renderableInvalidationSlot); + renderableBoundingVolumeInvalidationSlot = std::move(r.renderableBoundingVolumeInvalidationSlot); + renderableDataInvalidationSlot = std::move(r.renderableDataInvalidationSlot); renderableReleaseSlot = std::move(r.renderableReleaseSlot); return *this; } - NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateData, renderableInvalidationSlot); + NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateBoundingVolume, renderableBoundingVolumeInvalidationSlot); + NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateData, renderableDataInvalidationSlot); NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableRelease, renderableReleaseSlot); mutable Nz::InstancedRenderable::InstanceData data; @@ -107,6 +115,16 @@ namespace Ndk mutable bool dataUpdated; }; + using VolumeCullingListEntry = GraphicsComponentCullingList::VolumeEntry; + + struct VolumeCullingEntry + { + VolumeCullingListEntry listEntry; + + NazaraSlot(GraphicsComponentCullingList, OnCullingListRelease, cullingListReleaseSlot); + }; + + mutable std::vector m_volumeCullingEntries; std::vector m_renderables; mutable Nz::BoundingVolumef m_boundingVolume; mutable Nz::Matrix4f m_transformMatrix; @@ -118,4 +136,4 @@ namespace Ndk #include #endif // NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP -#endif // NDK_SERVER \ No newline at end of file +#endif // NDK_SERVER diff --git a/SDK/include/NDK/Components/GraphicsComponent.inl b/SDK/include/NDK/Components/GraphicsComponent.inl index bd3e6dbfb..6ca950e24 100644 --- a/SDK/include/NDK/Components/GraphicsComponent.inl +++ b/SDK/include/NDK/Components/GraphicsComponent.inl @@ -28,52 +28,12 @@ namespace Ndk Attach(r.renderable, r.data.renderOrder); } - /*! - * \brief Adds the renderable elements to the render queue - * - * \param renderQueue Queue to be added - */ - - inline void GraphicsComponent::AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const + inline void GraphicsComponent::AddToCullingList(GraphicsComponentCullingList* cullingList) const { - EnsureTransformMatrixUpdate(); - - Ndk::RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem(); - - for (const Renderable& object : m_renderables) - { - if (!object.dataUpdated) - { - object.data.transformMatrix = Nz::Matrix4f::ConcatenateAffine(renderSystem.GetCoordinateSystemMatrix(), Nz::Matrix4f::ConcatenateAffine(object.data.localMatrix, m_transformMatrix)); - object.renderable->UpdateData(&object.data); - object.dataUpdated = true; - } - - object.renderable->AddToRenderQueue(renderQueue, object.data); - } - } - - /*! - * \brief Attaches a renderable to the entity - * - * \param renderable Reference to a renderable element - * \param renderOrder Render order of the element - */ - - inline void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, int renderOrder) - { - return Attach(renderable, Nz::Matrix4f::Identity(), renderOrder); - } - - inline void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder) - { - m_renderables.emplace_back(m_transformMatrix); - Renderable& r = m_renderables.back(); - r.data.localMatrix = localMatrix; - r.data.renderOrder = renderOrder; - r.renderable = std::move(renderable); - r.renderableInvalidationSlot.Connect(r.renderable->OnInstancedRenderableInvalidateData, std::bind(&GraphicsComponent::InvalidateRenderableData, this, std::placeholders::_1, std::placeholders::_2, m_renderables.size() - 1)); - r.renderableReleaseSlot.Connect(r.renderable->OnInstancedRenderableRelease, this, &GraphicsComponent::Detach); + m_volumeCullingEntries.emplace_back(VolumeCullingEntry{}); + VolumeCullingEntry& entry = m_volumeCullingEntries.back(); + entry.cullingListReleaseSlot.Connect(cullingList->OnCullingListRelease, this, &GraphicsComponent::RemoveFromCullingList); + entry.listEntry = cullingList->RegisterVolumeTest(this); InvalidateBoundingVolume(); } @@ -167,11 +127,26 @@ namespace Ndk return m_boundingVolume; } + inline void GraphicsComponent::RemoveFromCullingList(GraphicsComponentCullingList* cullingList) const + { + for (auto it = m_volumeCullingEntries.begin(); it != m_volumeCullingEntries.end(); ++it) + { + if (it->listEntry.GetParent() == cullingList) + { + if (m_volumeCullingEntries.size() > 1) + *it = std::move(m_volumeCullingEntries.back()); + + m_volumeCullingEntries.pop_back(); + break; + } + } + } + /*! * \brief Invalidates the bounding volume */ - inline void GraphicsComponent::InvalidateBoundingVolume() + inline void GraphicsComponent::InvalidateBoundingVolume() const { m_boundingVolumeUpdated = false; } @@ -192,9 +167,9 @@ namespace Ndk inline void GraphicsComponent::InvalidateTransformMatrix() { - m_boundingVolumeUpdated = false; m_transformMatrixUpdated = false; + InvalidateBoundingVolume(); InvalidateRenderables(); } -} +} \ No newline at end of file diff --git a/SDK/include/NDK/Components/PhysicsComponent2D.hpp b/SDK/include/NDK/Components/PhysicsComponent2D.hpp new file mode 100644 index 000000000..90dd7a5e6 --- /dev/null +++ b/SDK/include/NDK/Components/PhysicsComponent2D.hpp @@ -0,0 +1,65 @@ +// Copyright (C) 2015 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_COMPONENTS_PHYSICSCOMPONENT2D_HPP +#define NDK_COMPONENTS_PHYSICSCOMPONENT2D_HPP + +#include +#include +#include + +namespace Ndk +{ + class Entity; + + class NDK_API PhysicsComponent2D : public Component + { + friend class CollisionComponent2D; + friend class PhysicsSystem2D; + + public: + PhysicsComponent2D() = default; + PhysicsComponent2D(const PhysicsComponent2D& physics); + ~PhysicsComponent2D() = default; + + void AddForce(const Nz::Vector2f& force, Nz::CoordSys coordSys = Nz::CoordSys_Global); + void AddForce(const Nz::Vector2f& force, const Nz::Vector2f& point, Nz::CoordSys coordSys = Nz::CoordSys_Global); + void AddTorque(float torque); + + Nz::Rectf GetAABB() const; + float GetAngularVelocity() const; + Nz::Vector2f GetCenterOfGravity(Nz::CoordSys coordSys = Nz::CoordSys_Local) const; + float GetMass() const; + Nz::Vector2f GetPosition() const; + float GetRotation() const; + Nz::Vector2f GetVelocity() const; + + bool IsSleeping() const; + + void SetAngularVelocity(float angularVelocity); + void SetMass(float mass); + void SetMassCenter(const Nz::Vector2f& center); + void SetPosition(const Nz::Vector2f& position); + void SetRotation(float rotation); + void SetVelocity(const Nz::Vector2f& velocity); + + static ComponentIndex componentIndex; + + private: + Nz::RigidBody2D& GetRigidBody(); + + void OnAttached() override; + void OnComponentAttached(BaseComponent& component) override; + void OnComponentDetached(BaseComponent& component) override; + void OnDetached() override; + + std::unique_ptr m_object; + }; +} + +#include + +#endif // NDK_COMPONENTS_PHYSICSCOMPONENT2D_HPP diff --git a/SDK/include/NDK/Components/PhysicsComponent2D.inl b/SDK/include/NDK/Components/PhysicsComponent2D.inl new file mode 100644 index 000000000..312e23e3a --- /dev/null +++ b/SDK/include/NDK/Components/PhysicsComponent2D.inl @@ -0,0 +1,284 @@ +// Copyright (C) 2015 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 + +#include +#include "PhysicsComponent2D.hpp" + +namespace Ndk +{ + /*! + * \brief Constructs a PhysicsComponent2D object by copy semantic + * + * \param physics PhysicsComponent2D to copy + */ + + inline PhysicsComponent2D::PhysicsComponent2D(const PhysicsComponent2D& physics) + { + // No copy of physical object (because we only create it when attached to an entity) + NazaraUnused(physics); + } + + /*! + * \brief Applies a physics force to the entity + * + * \param force Force to apply on the entity + * \param coordSys System coordinates to consider + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::AddForce(const Nz::Vector2f& force, Nz::CoordSys coordSys) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->AddForce(force, coordSys); + } + + /*! + * \brief Applies a physics force to the entity + * + * \param force Force to apply on the entity + * \param point Point where to apply the force + * \param coordSys System coordinates to consider + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::AddForce(const Nz::Vector2f& force, const Nz::Vector2f& point, Nz::CoordSys coordSys) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->AddForce(force, point, coordSys); + } + + /*! + * \brief Applies a torque to the entity + * + * \param torque Torque to apply on the entity + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::AddTorque(float torque) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->AddTorque(torque); + } + + /*! + * \brief Gets the AABB of the physics object + * \return AABB of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + inline Nz::Rectf PhysicsComponent2D::GetAABB() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetAABB(); + } + + /*! + * \brief Gets the angular velocity of the physics object + * \return Angular velocity of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline float PhysicsComponent2D::GetAngularVelocity() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetAngularVelocity(); + } + + /*! + * \brief Gets the gravity center of the physics object + * \return Gravity center of the object + * + * \param coordSys System coordinates to consider + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline Nz::Vector2f PhysicsComponent2D::GetCenterOfGravity(Nz::CoordSys coordSys) const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetCenterOfGravity(coordSys); + } + + /*! + * \brief Gets the mass of the physics object + * \return Mass of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline float PhysicsComponent2D::GetMass() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetMass(); + } + + /*! + * \brief Gets the position of the physics object + * \return Position of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline Nz::Vector2f PhysicsComponent2D::GetPosition() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetPosition(); + } + + /*! + * \brief Gets the rotation of the physics object + * \return Rotation of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline float PhysicsComponent2D::GetRotation() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetRotation(); + } + + /*! + * \brief Gets the velocity of the physics object + * \return Velocity of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline Nz::Vector2f PhysicsComponent2D::GetVelocity() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->GetVelocity(); + } + + /*! + * \brief Checks whether the entity is currently sleeping + * \return true If it is the case + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline bool PhysicsComponent2D::IsSleeping() const + { + NazaraAssert(m_object, "Invalid physics object"); + + return m_object->IsSleeping(); + } + + /*! + * \brief Sets the angular velocity of the physics object + * + * \param angularVelocity Angular velocity of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::SetAngularVelocity(float angularVelocity) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->SetAngularVelocity(angularVelocity); + } + + /*! + * \brief Sets the mass of the physics object + * + * \param mass Mass of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + * \remark Produces a NazaraAssert if the mass is negative + */ + + inline void PhysicsComponent2D::SetMass(float mass) + { + NazaraAssert(m_object, "Invalid physics object"); + NazaraAssert(mass > 0.f, "Mass should be positive"); + + m_object->SetMass(mass); + } + + /*! + * \brief Sets the gravity center of the physics object + * + * \param center Gravity center of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::SetMassCenter(const Nz::Vector2f& center) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->SetMassCenter(center); + } + + /*! + * \brief Sets the position of the physics object + * + * \param position Position of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::SetPosition(const Nz::Vector2f& position) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->SetPosition(position); + } + + /*! + * \brief Sets the rotation of the physics object + * + * \param rotation Rotation of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::SetRotation(float rotation) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->SetRotation(rotation); + } + + /*! + * \brief Sets the velocity of the physics object + * + * \param velocity Velocity of the object + * + * \remark Produces a NazaraAssert if the physics object is invalid + */ + + inline void PhysicsComponent2D::SetVelocity(const Nz::Vector2f& velocity) + { + NazaraAssert(m_object, "Invalid physics object"); + + m_object->SetVelocity(velocity); + } + + /*! + * \brief Gets the underlying physics object + * \return A reference to the physics object + */ + + inline Nz::RigidBody2D& PhysicsComponent2D::GetRigidBody() + { + return *m_object.get(); + } +} diff --git a/SDK/include/NDK/Components/PhysicsComponent3D.hpp b/SDK/include/NDK/Components/PhysicsComponent3D.hpp index fc1367d84..9fb1bb45e 100644 --- a/SDK/include/NDK/Components/PhysicsComponent3D.hpp +++ b/SDK/include/NDK/Components/PhysicsComponent3D.hpp @@ -56,7 +56,7 @@ namespace Ndk static ComponentIndex componentIndex; private: - Nz::RigidBody3D& GetPhysObject(); + Nz::RigidBody3D& GetRigidBody(); void OnAttached() override; void OnComponentAttached(BaseComponent& component) override; diff --git a/SDK/include/NDK/Components/PhysicsComponent3D.inl b/SDK/include/NDK/Components/PhysicsComponent3D.inl index 84bc36db7..cad098af8 100644 --- a/SDK/include/NDK/Components/PhysicsComponent3D.inl +++ b/SDK/include/NDK/Components/PhysicsComponent3D.inl @@ -350,7 +350,7 @@ namespace Ndk * \return A reference to the physics object */ - inline Nz::RigidBody3D& PhysicsComponent3D::GetPhysObject() + inline Nz::RigidBody3D& PhysicsComponent3D::GetRigidBody() { return *m_object.get(); } diff --git a/SDK/include/NDK/Console.hpp b/SDK/include/NDK/Console.hpp index 1c007065f..59a98df0d 100644 --- a/SDK/include/NDK/Console.hpp +++ b/SDK/include/NDK/Console.hpp @@ -4,6 +4,7 @@ #pragma once +#ifndef NDK_SERVER #ifndef NDK_CONSOLE_HPP #define NDK_CONSOLE_HPP @@ -99,3 +100,4 @@ namespace Ndk #include #endif // NDK_CONSOLE_HPP +#endif // NDK_SERVER diff --git a/SDK/include/NDK/Lua/LuaBinding.hpp b/SDK/include/NDK/Lua/LuaBinding.hpp new file mode 100644 index 000000000..307345589 --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding.hpp @@ -0,0 +1,68 @@ +// Copyright (C) 2015 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_HPP +#define NDK_LUABINDING_HPP + +#include +#include +#include +#include + +namespace Ndk +{ + class NDK_API LuaBinding + { + friend class LuaBinding_SDK; + + public: + LuaBinding(); + ~LuaBinding() = default; + + template void BindComponent(const Nz::String& name); + + void RegisterClasses(Nz::LuaInstance& instance); + + std::unique_ptr core; + std::unique_ptr math; + std::unique_ptr network; + std::unique_ptr sdk; + std::unique_ptr utility; + + #ifndef NDK_SERVER + std::unique_ptr audio; + std::unique_ptr graphics; + std::unique_ptr renderer; + #endif + + private: + template + static int AddComponentOfType(Nz::LuaInstance& lua, EntityHandle& handle); + + template + static int PushComponentOfType(Nz::LuaInstance& lua, BaseComponent& component); + + using AddComponentFunc = int(*)(Nz::LuaInstance&, EntityHandle&); + using GetComponentFunc = int(*)(Nz::LuaInstance&, BaseComponent&); + + struct ComponentBinding + { + AddComponentFunc adder; + ComponentIndex index; + GetComponentFunc getter; + Nz::String name; + }; + + ComponentBinding* QueryComponentIndex(Nz::LuaInstance& lua, int argIndex = 2); + + std::vector m_componentBinding; + std::unordered_map m_componentBindingByName; + }; +} + +#include + +#endif // NDK_LUABINDING_HPP diff --git a/SDK/include/NDK/LuaBinding.inl b/SDK/include/NDK/Lua/LuaBinding.inl similarity index 66% rename from SDK/include/NDK/LuaBinding.inl rename to SDK/include/NDK/Lua/LuaBinding.inl index e4ae72254..ca77dfcf6 100644 --- a/SDK/include/NDK/LuaBinding.inl +++ b/SDK/include/NDK/Lua/LuaBinding.inl @@ -2,7 +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 namespace Ndk { @@ -32,18 +32,8 @@ namespace Ndk m_componentBindingByName[name] = T::componentIndex; } - /*! - * \brief Adds a component to an entity - * \return 1 in case of success - * - * \param instance Lua instance that will interact with the component - * \param handle Entity which component will be added to - * - * \remark T must be a subtype of BaseComponent - */ - template - int AddComponentOfType(Nz::LuaInstance& lua, EntityHandle& handle) + int LuaBinding::AddComponentOfType(Nz::LuaInstance& lua, EntityHandle& handle) { static_assert(std::is_base_of::value, "ComponentType must inherit BaseComponent"); @@ -52,18 +42,8 @@ namespace Ndk return 1; } - /*! - * \brief Pushes a component - * \return 1 in case of success - * - * \param instance Lua instance that will interact with the component - * \param component Component that will be pushed - * - * \remark T must be a subtype of BaseComponent - */ - template - int PushComponentOfType(Nz::LuaInstance& lua, BaseComponent& component) + int LuaBinding::PushComponentOfType(Nz::LuaInstance& lua, BaseComponent& component) { static_assert(std::is_base_of::value, "ComponentType must inherit BaseComponent"); diff --git a/SDK/include/NDK/Lua/LuaBinding_Audio.hpp b/SDK/include/NDK/Lua/LuaBinding_Audio.hpp new file mode 100644 index 000000000..510654342 --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding_Audio.hpp @@ -0,0 +1,33 @@ +// Copyright (C) 2015 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_AUDIO_HPP +#define NDK_LUABINDING_AUDIO_HPP + +#include +#include +#include +#include +#include + +namespace Ndk +{ + class NDK_API LuaBinding_Audio : public LuaBinding_Base + { + public: + LuaBinding_Audio(LuaBinding& binding); + ~LuaBinding_Audio() = default; + + void Register(Nz::LuaInstance& instance) override; + + Nz::LuaClass music; + Nz::LuaClass sound; + Nz::LuaClass soundBuffer; + Nz::LuaClass soundEmitter; + }; +} + +#endif // NDK_LUABINDING_CORE_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Base.hpp b/SDK/include/NDK/Lua/LuaBinding_Base.hpp new file mode 100644 index 000000000..29c486835 --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding_Base.hpp @@ -0,0 +1,53 @@ +// Copyright (C) 2015 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_BASE_HPP +#define NDK_LUABINDING_BASE_HPP + +#include +#include +#include + +namespace Ndk +{ + class LuaBinding; + + class LuaBinding_Audio; + class LuaBinding_Core; + class LuaBinding_Graphics; + class LuaBinding_Math; + class LuaBinding_Network; + class LuaBinding_Renderer; + class LuaBinding_SDK; + class LuaBinding_Utility; + + class NDK_API LuaBinding_Base + { + public: + LuaBinding_Base(LuaBinding& binding); + virtual ~LuaBinding_Base(); + + virtual void Register(Nz::LuaInstance& instance) = 0; + + // Implementation lies in the respective .cpp files (still searching for a cleaner way..) + static std::unique_ptr BindCore(LuaBinding& binding); + static std::unique_ptr BindMath(LuaBinding& binding); + static std::unique_ptr BindNetwork(LuaBinding& binding); + static std::unique_ptr BindSDK(LuaBinding& binding); + static std::unique_ptr BindUtility(LuaBinding& binding); + + #ifndef NDK_SERVER + static std::unique_ptr BindAudio(LuaBinding& binding); + static std::unique_ptr BindGraphics(LuaBinding& binding); + static std::unique_ptr BindRenderer(LuaBinding& binding); + #endif + + protected: + LuaBinding& m_binding; + }; +} + +#endif // NDK_LUABINDING_BASE_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Core.hpp b/SDK/include/NDK/Lua/LuaBinding_Core.hpp new file mode 100644 index 000000000..54400958f --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding_Core.hpp @@ -0,0 +1,33 @@ +// Copyright (C) 2015 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_CORE_HPP +#define NDK_LUABINDING_CORE_HPP + +#include +#include +#include +#include +#include + +namespace Ndk +{ + class NDK_API LuaBinding_Core : public LuaBinding_Base + { + public: + LuaBinding_Core(LuaBinding& binding); + ~LuaBinding_Core() = default; + + void Register(Nz::LuaInstance& instance) override; + + Nz::LuaClass clock; + Nz::LuaClass directory; + Nz::LuaClass file; + Nz::LuaClass stream; + }; +} + +#endif // NDK_LUABINDING_CORE_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Graphics.hpp b/SDK/include/NDK/Lua/LuaBinding_Graphics.hpp new file mode 100644 index 000000000..75a6eff8f --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding_Graphics.hpp @@ -0,0 +1,36 @@ +// Copyright (C) 2015 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_GRAPHICS_HPP +#define NDK_LUABINDING_GRAPHICS_HPP + +#include +#include +#include +#include +#include +#include + +namespace Ndk +{ + class NDK_API LuaBinding_Graphics : public LuaBinding_Base + { + public: + LuaBinding_Graphics(LuaBinding& binding); + ~LuaBinding_Graphics() = default; + + void Register(Nz::LuaInstance& instance) override; + + Nz::LuaClass abstractViewer; + Nz::LuaClass instancedRenderable; + Nz::LuaClass material; + Nz::LuaClass model; + Nz::LuaClass sprite; + Nz::LuaClass spriteLibrary; + }; +} + +#endif // NDK_LUABINDING_GRAPHICS_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Math.hpp b/SDK/include/NDK/Lua/LuaBinding_Math.hpp new file mode 100644 index 000000000..195d34ec2 --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding_Math.hpp @@ -0,0 +1,37 @@ +// Copyright (C) 2015 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_MATH_HPP +#define NDK_LUABINDING_MATH_HPP + +#include +#include +#include +#include +#include +#include +#include + +namespace Ndk +{ + class NDK_API LuaBinding_Math : public LuaBinding_Base + { + public: + LuaBinding_Math(LuaBinding& binding); + ~LuaBinding_Math() = default; + + void Register(Nz::LuaInstance& instance) override; + + Nz::LuaClass eulerAngles; + Nz::LuaClass matrix4d; + Nz::LuaClass quaternion; + Nz::LuaClass rect; + Nz::LuaClass vector2d; + Nz::LuaClass vector3d; + }; +} + +#endif // NDK_LUABINDING_MATH_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Network.hpp b/SDK/include/NDK/Lua/LuaBinding_Network.hpp new file mode 100644 index 000000000..f69e038a7 --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding_Network.hpp @@ -0,0 +1,29 @@ +// Copyright (C) 2015 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_NETWORK_HPP +#define NDK_LUABINDING_NETWORK_HPP + +#include +#include +#include + +namespace Ndk +{ + class NDK_API LuaBinding_Network : public LuaBinding_Base + { + public: + LuaBinding_Network(LuaBinding& binding); + ~LuaBinding_Network() = default; + + void Register(Nz::LuaInstance& instance) override; + + Nz::LuaClass abstractSocket; + Nz::LuaClass ipAddress; + }; +} + +#endif // NDK_LUABINDING_NETWORK_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Renderer.hpp b/SDK/include/NDK/Lua/LuaBinding_Renderer.hpp new file mode 100644 index 000000000..7655c9ac3 --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding_Renderer.hpp @@ -0,0 +1,29 @@ +// Copyright (C) 2015 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_RENDERER_HPP +#define NDK_LUABINDING_RENDERER_HPP + +#include +#include + +namespace Ndk +{ + class NDK_API LuaBinding_Renderer : public LuaBinding_Base + { + public: + LuaBinding_Renderer(LuaBinding& binding); + ~LuaBinding_Renderer() = default; + + void Register(Nz::LuaInstance& instance) override; + + Nz::LuaClass texture; + Nz::LuaClass textureLibrary; + Nz::LuaClass textureManager; + }; +} + +#endif // NDK_LUABINDING_RENDERER_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_SDK.hpp b/SDK/include/NDK/Lua/LuaBinding_SDK.hpp new file mode 100644 index 000000000..facfd5620 --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding_SDK.hpp @@ -0,0 +1,42 @@ +// Copyright (C) 2015 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_SDK_HPP +#define NDK_LUABINDING_SDK_HPP + +#include +#include +#include +#include + +namespace Ndk +{ + class Application; + + class NDK_API LuaBinding_SDK : public LuaBinding_Base + { + public: + LuaBinding_SDK(LuaBinding& binding); + ~LuaBinding_SDK() = default; + + void Register(Nz::LuaInstance& instance) override; + + Nz::LuaClass application; + Nz::LuaClass entity; + Nz::LuaClass nodeComponent; + Nz::LuaClass velocityComponent; + Nz::LuaClass world; + + #ifndef NDK_SERVER + Nz::LuaClass cameraComponent; + Nz::LuaClass console; + Nz::LuaClass graphicsComponent; + #endif + + }; +} + +#endif // NDK_LUABINDING_SDK_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Utility.hpp b/SDK/include/NDK/Lua/LuaBinding_Utility.hpp new file mode 100644 index 000000000..80afde5bf --- /dev/null +++ b/SDK/include/NDK/Lua/LuaBinding_Utility.hpp @@ -0,0 +1,34 @@ +// Copyright (C) 2015 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_UTILITY_HPP +#define NDK_LUABINDING_UTILITY_HPP + +#include +#include +#include +#include +#include + +namespace Ndk +{ + class NDK_API LuaBinding_Utility : public LuaBinding_Base + { + public: + LuaBinding_Utility(LuaBinding& binding); + ~LuaBinding_Utility() = default; + + void Register(Nz::LuaInstance& instance) override; + + // Utility + Nz::LuaClass abstractImage; + Nz::LuaClass font; + Nz::LuaClass keyboard; + Nz::LuaClass node; + }; +} + +#endif // NDK_LUABINDING_UTILITY_HPP diff --git a/SDK/include/NDK/LuaAPI.inl b/SDK/include/NDK/LuaAPI.inl index 1ae2ddd43..6b7573597 100644 --- a/SDK/include/NDK/LuaAPI.inl +++ b/SDK/include/NDK/LuaAPI.inl @@ -28,15 +28,6 @@ namespace Nz { - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param color Resulting color - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Color* color, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -49,15 +40,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param angles Resulting euler angles - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesd* angles, TypeTag) { switch (instance.GetType(index)) @@ -78,15 +60,6 @@ namespace Nz } } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param angles Resulting euler angles - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesf* angles, TypeTag) { EulerAnglesd anglesDouble; @@ -96,15 +69,6 @@ namespace Nz return ret; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param fontRef Resulting reference to a font - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontRef* fontRef, TypeTag) { *fontRef = *static_cast(instance.CheckUserdata(index, "Font")); @@ -112,15 +76,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param params Resulting parameters for a font - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontParams* params, TypeTag) { NazaraUnused(params); @@ -132,14 +87,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param params Resulting parameters for an image - */ inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ImageParams* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -150,15 +97,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param address Resulting IP address - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, IpAddress* address, TypeTag) { switch (instance.GetType(index)) @@ -173,15 +111,6 @@ namespace Nz } } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param quat Resulting quaternion - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4d* mat, TypeTag) { switch (instance.GetType(index)) @@ -212,55 +141,29 @@ namespace Nz } } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param quat Resulting quaternion - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4f* mat, TypeTag) { - Matrix4d matDouble; + Matrix4d matDouble = Matrix4d::Identity(); unsigned int ret = LuaImplQueryArg(instance, index, &matDouble, TypeTag()); mat->Set(matDouble); return ret; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param params Resulting parameters for a mesh - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MeshParams* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); params->animated = instance.CheckField("Animated", params->animated); params->center = instance.CheckField("Center", params->center); - params->flipUVs = instance.CheckField("FlipUVs", params->flipUVs); params->matrix = instance.CheckField("Matrix", params->matrix); params->optimizeIndexBuffers = instance.CheckField("OptimizeIndexBuffers", params->optimizeIndexBuffers); + params->texCoordOffset = instance.CheckField("TexCoordOffset", params->texCoordOffset); + params->texCoordScale = instance.CheckField("TexCoordScale", params->texCoordScale); return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param quat Resulting quaternion - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaterniond* quat, TypeTag) { switch (instance.GetType(index)) @@ -281,15 +184,6 @@ namespace Nz } } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param quat Resulting quaternion - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaternionf* quat, TypeTag) { Quaterniond quatDouble; @@ -299,15 +193,6 @@ namespace Nz return ret; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param rect Resulting rectangle - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectd* rect, TypeTag) { instance.CheckType(index, LuaType_Table); @@ -320,15 +205,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param rect Resulting rectangle - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectf* rect, TypeTag) { Rectd rectDouble; @@ -338,14 +214,14 @@ namespace Nz return ret; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param rect Resulting rectangle - */ + inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Recti* rect, TypeTag) + { + Rectd rectDouble; + unsigned int ret = LuaImplQueryArg(instance, index, &rectDouble, TypeTag()); + + rect->Set(rectDouble); + return ret; + } inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectui* rect, TypeTag) { @@ -356,15 +232,6 @@ namespace Nz return ret; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param vec Resulting vector2D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2d* vec, TypeTag) { switch (instance.GetType(index)) @@ -386,15 +253,6 @@ namespace Nz } } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param vec Resulting vector2D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2f* vec, TypeTag) { Vector2d vecDouble; @@ -404,15 +262,6 @@ namespace Nz return ret; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param vec Resulting vector2D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2ui* vec, TypeTag) { Vector2d vecDouble; @@ -422,15 +271,6 @@ namespace Nz return ret; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param vec Resulting vector3D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3d* vec, TypeTag) { switch (instance.GetType(index)) @@ -452,15 +292,6 @@ namespace Nz } } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param vec Resulting vector3D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3f* vec, TypeTag) { Vector3d vecDouble; @@ -470,15 +301,6 @@ namespace Nz return ret; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param vec Resulting vector3D - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3ui* vec, TypeTag) { Vector3d vecDouble; @@ -488,15 +310,6 @@ namespace Nz return ret; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param handle Resulting entity - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::EntityHandle* handle, TypeTag) { *handle = *static_cast(instance.CheckUserdata(index, "Entity")); @@ -504,15 +317,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param handle Resulting world - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::WorldHandle* handle, TypeTag) { *handle = *static_cast(instance.CheckUserdata(index, "World")); @@ -521,16 +325,6 @@ namespace Nz } #ifndef NDK_SERVER - - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param renderable Resulting reference to a instanced renderable - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, InstancedRenderableRef* renderable, TypeTag) { if (instance.IsOfType(index, "InstancedRenderable") || @@ -545,15 +339,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param renderable Resulting reference to a material - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialRef* materialRef, TypeTag) { *materialRef = *static_cast(instance.CheckUserdata(index, "Material")); @@ -561,15 +346,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param params Resulting parameters for a material - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialParams* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -585,15 +361,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param params Resulting parameters for a model - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ModelParameters* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -606,15 +373,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param params Resulting parameters for a music - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MusicParams* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -624,15 +382,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param params Resulting parameters for a sound buffer - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SoundBufferParams* params, TypeTag) { instance.CheckType(index, Nz::LuaType_Table); @@ -642,15 +391,6 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param renderable Resulting reference to a sprite - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SpriteRef* spriteRef, TypeTag) { *spriteRef = *static_cast(instance.CheckUserdata(index, "Sprite")); @@ -658,32 +398,14 @@ namespace Nz return 1; } - /*! - * \brief Queries arguments for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param index Index type - * \param fontRef Resulting reference to a font - */ - inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, TextureRef* textureRef, TypeTag) { *textureRef = *static_cast(instance.CheckUserdata(index, "Texture")); return 1; } - #endif - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting color - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Color&& val, TypeTag) { instance.PushTable(); @@ -695,56 +417,24 @@ namespace Nz return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting euler angles - */ - inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesd&& val, TypeTag) { instance.PushInstance("EulerAngles", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting euler angles - */ - inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesf&& val, TypeTag) { instance.PushInstance("EulerAngles", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting reference to a font - */ - inline int LuaImplReplyVal(const LuaInstance& instance, FontRef&& val, TypeTag) { instance.PushInstance("Font", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting size information for a font - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Font::SizeInfo&& val, TypeTag) { instance.PushTable(); @@ -756,14 +446,6 @@ namespace Nz return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting ImageParams - */ - inline int LuaImplReplyVal(const LuaInstance& instance, ImageParams&& val, TypeTag) { instance.PushTable(0, 2); @@ -773,111 +455,53 @@ namespace Nz return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting IP address - */ - inline int LuaImplReplyVal(const LuaInstance& instance, IpAddress&& val, TypeTag) { instance.PushInstance("IpAddress", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting rectangle - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4d&& val, TypeTag) { instance.PushInstance("Matrix4", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting rectangle - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4f&& val, TypeTag) { instance.PushInstance("Matrix4", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting quaternion - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Quaterniond&& val, TypeTag) { instance.PushInstance("Quaternion", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting quaternion - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Quaternionf&& val, TypeTag) { instance.PushInstance("Quaternion", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting rectangle - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Rectd&& val, TypeTag) { instance.PushInstance("Rect", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting rectangle - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Rectf&& val, TypeTag) { instance.PushInstance("Rect", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting rectangle - */ + inline int LuaImplReplyVal(const LuaInstance& instance, Recti&& val, TypeTag) + { + instance.PushInstance("Rect", val); + return 1; + } inline int LuaImplReplyVal(const LuaInstance& instance, Rectui&& val, TypeTag) { @@ -885,182 +509,78 @@ namespace Nz return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting vector2D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector2d&& val, TypeTag) { instance.PushInstance("Vector2", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting vector2D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector2f&& val, TypeTag) { instance.PushInstance("Vector2", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting vector2D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector2ui&& val, TypeTag) { instance.PushInstance("Vector2", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting vector3D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector3d&& val, TypeTag) { instance.PushInstance("Vector3", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting vector3D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector3f&& val, TypeTag) { instance.PushInstance("Vector3", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting vector3D - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Vector3ui&& val, TypeTag) { instance.PushInstance("Vector3", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param ptr Resulting entity - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Entity* ptr, TypeTag) { instance.PushInstance("Entity", ptr); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param ptr Resulting application - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Application* ptr, TypeTag) { instance.PushInstance("Application", ptr); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param handle Resulting entity - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::EntityHandle&& handle, TypeTag) { instance.PushInstance("Entity", handle); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param handle Resulting node component - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::NodeComponentHandle&& handle, TypeTag) { instance.PushInstance("NodeComponent", handle); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param handle Resulting velocity component - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::VelocityComponentHandle&& handle, TypeTag) { instance.PushInstance("VelocityComponent", handle); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param ptr Resulting world - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::World* ptr, TypeTag) { instance.PushInstance("World", ptr); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param ptr Resulting world - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::WorldHandle&& handle, TypeTag) { instance.PushInstance("World", handle); @@ -1068,70 +588,35 @@ namespace Nz } #ifndef NDK_SERVER - - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param handle Resulting material - */ - inline int LuaImplReplyVal(const LuaInstance& instance, MaterialRef&& handle, TypeTag) { instance.PushInstance("Material", handle); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param val Resulting sound buffer - */ - inline int LuaImplReplyVal(const LuaInstance& instance, const SoundBuffer* val, TypeTag) { instance.PushInstance("SoundBuffer", val); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param handle Resulting sprite - */ - inline int LuaImplReplyVal(const LuaInstance& instance, SpriteRef&& handle, TypeTag) { instance.PushInstance("Sprite", handle); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param handle Resulting texture - */ - inline int LuaImplReplyVal(const LuaInstance& instance, TextureRef&& handle, TypeTag) { instance.PushInstance("Texture", handle); return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param handle Resulting console - */ + inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::CameraComponentHandle&& handle, TypeTag) + { + instance.PushInstance("CameraComponent", handle); + return 1; + } inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::ConsoleHandle&& handle, TypeTag) { @@ -1139,14 +624,6 @@ namespace Nz return 1; } - /*! - * \brief Replies by value for Lua - * \return 1 in case of success - * - * \param instance Lua instance to interact with - * \param handle Resulting graphics component - */ - inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::GraphicsComponentHandle&& handle, TypeTag) { instance.PushInstance("GraphicsComponent", handle); diff --git a/SDK/include/NDK/LuaBinding.hpp b/SDK/include/NDK/LuaBinding.hpp deleted file mode 100644 index 0eb083162..000000000 --- a/SDK/include/NDK/LuaBinding.hpp +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (C) 2015 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_HPP -#define NDK_LUABINDING_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef NDK_SERVER -#include -#include -#include -#include -#endif - -namespace Ndk -{ - class NDK_API LuaBinding - { - public: - LuaBinding(); - ~LuaBinding() = default; - - template void BindComponent(const Nz::String& name); - - void RegisterClasses(Nz::LuaInstance& instance); - - // Core - Nz::LuaClass clock; - Nz::LuaClass directory; - Nz::LuaClass file; - Nz::LuaClass stream; - - // Math - Nz::LuaClass eulerAngles; - Nz::LuaClass matrix4d; - Nz::LuaClass quaternion; - Nz::LuaClass rect; - Nz::LuaClass vector2d; - Nz::LuaClass vector3d; - - // Network - Nz::LuaClass abstractSocket; - Nz::LuaClass ipAddress; - - // Utility - Nz::LuaClass abstractImage; - Nz::LuaClass font; - Nz::LuaClass node; - - // SDK - Nz::LuaClass application; - Nz::LuaClass entity; - Nz::LuaClass nodeComponent; - Nz::LuaClass velocityComponent; - Nz::LuaClass world; - - #ifndef NDK_SERVER - // Audio - Nz::LuaClass music; - Nz::LuaClass sound; - Nz::LuaClass soundBuffer; - Nz::LuaClass soundEmitter; - - // Graphics - Nz::LuaClass instancedRenderable; - Nz::LuaClass material; - Nz::LuaClass model; - Nz::LuaClass sprite; - Nz::LuaClass spriteLibrary; - Nz::LuaClass textureLibrary; - Nz::LuaClass textureManager; - - // Renderer - Nz::LuaClass texture; - - // SDK - Nz::LuaClass console; - Nz::LuaClass graphicsComponent; - #endif - - private: - void BindCore(); - void BindMath(); - void BindNetwork(); - void BindSDK(); - void BindUtility(); - - void RegisterCore(Nz::LuaInstance& instance); - void RegisterMath(Nz::LuaInstance& instance); - void RegisterNetwork(Nz::LuaInstance& instance); - void RegisterSDK(Nz::LuaInstance& instance); - void RegisterUtility(Nz::LuaInstance& instance); - - #ifndef NDK_SERVER - void BindAudio(); - void BindGraphics(); - void BindRenderer(); - - void RegisterAudio(Nz::LuaInstance& instance); - void RegisterGraphics(Nz::LuaInstance& instance); - void RegisterRenderer(Nz::LuaInstance& instance); - #endif - - - using AddComponentFunc = int(*)(Nz::LuaInstance&, EntityHandle&); - using GetComponentFunc = int(*)(Nz::LuaInstance&, BaseComponent&); - - struct ComponentBinding - { - AddComponentFunc adder; - ComponentIndex index; - GetComponentFunc getter; - Nz::String name; - }; - - ComponentBinding* QueryComponentIndex(Nz::LuaInstance& lua, int argIndex = 2); - - std::vector m_componentBinding; - std::unordered_map m_componentBindingByName; - }; - - template - int AddComponentOfType(Nz::LuaInstance& lua, EntityHandle& handle); - - template - int PushComponentOfType(Nz::LuaInstance& lua, BaseComponent& component); -} - -#include - -#endif // NDK_LUABINDING_HPP diff --git a/SDK/include/NDK/Prerequesites.hpp b/SDK/include/NDK/Prerequesites.hpp index a2305c70f..f1ff2757a 100644 --- a/SDK/include/NDK/Prerequesites.hpp +++ b/SDK/include/NDK/Prerequesites.hpp @@ -25,11 +25,16 @@ #ifndef NDK_PREREQUESITES_HPP #define NDK_PREREQUESITES_HPP +/*! +* \defgroup NDK (NazaraSDK) Nazara Development Kit +* A library grouping every modules of Nazara into multiple higher-level features suchs as scene management (handled by an ECS), application, lua binding, etc. +*/ + #include // Importation/Exportation of the API #if defined(NAZARA_STATIC) - #define #define NDK_API + #define NDK_API #else #ifdef NDK_BUILD #define NDK_API NAZARA_EXPORT diff --git a/SDK/include/NDK/Systems.hpp b/SDK/include/NDK/Systems.hpp index 287a2d61a..a0ee23e77 100644 --- a/SDK/include/NDK/Systems.hpp +++ b/SDK/include/NDK/Systems.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 30 Jul 2016 at 15:29:16 +// This file was automatically generated #pragma once @@ -7,6 +7,7 @@ #include #include +#include #include #include #include diff --git a/SDK/include/NDK/Systems/PhysicsSystem2D.hpp b/SDK/include/NDK/Systems/PhysicsSystem2D.hpp new file mode 100644 index 000000000..31426450a --- /dev/null +++ b/SDK/include/NDK/Systems/PhysicsSystem2D.hpp @@ -0,0 +1,42 @@ +// Copyright (C) 2015 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_SYSTEMS_PHYSICSSYSTEM2D_HPP +#define NDK_SYSTEMS_PHYSICSSYSTEM2D_HPP + +#include +#include +#include +#include + +namespace Ndk +{ + class NDK_API PhysicsSystem2D : public System + { + public: + PhysicsSystem2D(); + PhysicsSystem2D(const PhysicsSystem2D& system); + ~PhysicsSystem2D() = default; + + Nz::PhysWorld2D& GetWorld(); + const Nz::PhysWorld2D& GetWorld() const; + + static SystemIndex systemIndex; + + private: + void CreatePhysWorld() const; + void OnEntityValidation(Entity* entity, bool justAdded) override; + void OnUpdate(float elapsedTime) override; + + EntityList m_dynamicObjects; + EntityList m_staticObjects; + mutable std::unique_ptr m_world; ///TODO: std::optional (Should I make a Nz::Optional class?) + }; +} + +#include + +#endif // NDK_SYSTEMS_PHYSICSSYSTEM2D_HPP diff --git a/SDK/include/NDK/Systems/PhysicsSystem2D.inl b/SDK/include/NDK/Systems/PhysicsSystem2D.inl new file mode 100644 index 000000000..21a34a6d4 --- /dev/null +++ b/SDK/include/NDK/Systems/PhysicsSystem2D.inl @@ -0,0 +1,32 @@ +// Copyright (C) 2015 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 + +namespace Ndk +{ + /*! + * \brief Gets the physical world + * \return A reference to the physical world + */ + + inline Nz::PhysWorld2D& PhysicsSystem2D::GetWorld() + { + if (!m_world) + CreatePhysWorld(); + + return *m_world; + } + + /*! + * \brief Gets the physical world + * \return A constant reference to the physical world + */ + + inline const Nz::PhysWorld2D& PhysicsSystem2D::GetWorld() const + { + if (!m_world) + CreatePhysWorld(); + + return *m_world; + } +} diff --git a/SDK/include/NDK/Systems/RenderSystem.hpp b/SDK/include/NDK/Systems/RenderSystem.hpp index 488d1a7d4..61ccefe75 100644 --- a/SDK/include/NDK/Systems/RenderSystem.hpp +++ b/SDK/include/NDK/Systems/RenderSystem.hpp @@ -9,9 +9,11 @@ #define NDK_SYSTEMS_RENDERSYSTEM_HPP #include +#include #include #include #include +#include #include #include #include @@ -19,8 +21,6 @@ namespace Ndk { - class GraphicsComponent; - class NDK_API RenderSystem : public System { public: @@ -51,21 +51,25 @@ namespace Ndk void OnEntityRemoved(Entity* entity) override; void OnEntityValidation(Entity* entity, bool justAdded) override; void OnUpdate(float elapsedTime) override; + void UpdateDirectionalShadowMaps(const Nz::AbstractViewer& viewer); void UpdatePointSpotShadowMaps(); std::unique_ptr m_renderTechnique; + std::vector m_volumeEntries; EntityList m_cameras; EntityList m_drawables; EntityList m_directionalLights; EntityList m_lights; EntityList m_pointSpotLights; EntityList m_particleGroups; + GraphicsComponentCullingList m_drawableCulling; Nz::BackgroundRef m_background; Nz::DepthRenderTechnique m_shadowTechnique; Nz::Matrix4f m_coordinateSystemMatrix; Nz::RenderTexture m_shadowRT; bool m_coordinateSystemInvalidated; + bool m_forceRenderQueueInvalidation; }; } diff --git a/SDK/include/NDK/Widgets.hpp b/SDK/include/NDK/Widgets.hpp index 26e7f39ad..a019c007b 100644 --- a/SDK/include/NDK/Widgets.hpp +++ b/SDK/include/NDK/Widgets.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 27 Oct 2016 at 21:39:00 +// This file was automatically generated #pragma once diff --git a/SDK/include/NDK/World.hpp b/SDK/include/NDK/World.hpp index 5d1dabb77..5e819e517 100644 --- a/SDK/include/NDK/World.hpp +++ b/SDK/include/NDK/World.hpp @@ -24,6 +24,7 @@ namespace Ndk class NDK_API World : public Nz::HandledObject { + friend BaseSystem; friend Entity; public: @@ -72,6 +73,8 @@ namespace Ndk private: inline void Invalidate(); inline void Invalidate(EntityId id); + inline void InvalidateSystemOrder(); + void ReorderSystems(); struct EntityBlock { @@ -83,15 +86,17 @@ namespace Ndk EntityBlock(EntityBlock&& block) = default; Entity entity; - unsigned int aliveIndex; + std::size_t aliveIndex; }; std::vector> m_systems; + std::vector m_orderedSystems; std::vector m_entities; std::vector m_freeIdList; EntityList m_aliveEntities; Nz::Bitset m_dirtyEntities; Nz::Bitset m_killedEntities; + bool m_orderedSystemsUpdated; }; } diff --git a/SDK/include/NDK/World.inl b/SDK/include/NDK/World.inl index 9960aef05..212038625 100644 --- a/SDK/include/NDK/World.inl +++ b/SDK/include/NDK/World.inl @@ -53,6 +53,7 @@ namespace Ndk m_systems[index]->SetWorld(this); Invalidate(); // We force an update for every entities + InvalidateSystemOrder(); // And regenerate the system update list return *m_systems[index].get(); } @@ -206,6 +207,8 @@ namespace Ndk inline void World::RemoveAllSystems() { m_systems.clear(); + + InvalidateSystemOrder(); } /*! @@ -219,7 +222,11 @@ namespace Ndk inline void World::RemoveSystem(SystemIndex index) { if (HasSystem(index)) + { m_systems[index].reset(); + + InvalidateSystemOrder(); + } } /*! @@ -246,32 +253,8 @@ namespace Ndk Update(); //< Update entities // And then update systems - for (auto& systemPtr : m_systems) - { - if (systemPtr) - systemPtr->Update(elapsedTime); - } - } - - /*! - * \brief Invalidates each entity in the world - */ - - inline void World::Invalidate() - { - m_dirtyEntities.Resize(m_entities.size(), false); - m_dirtyEntities.Set(true); // Activation of all bits - } - - /*! - * \brief Invalidates an entity in the world - * - * \param id Identifier of the entity - */ - - inline void World::Invalidate(EntityId id) - { - m_dirtyEntities.UnboundedSet(id, true); + for (auto& systemPtr : m_orderedSystems) + systemPtr->Update(elapsedTime); } /*! @@ -281,10 +264,12 @@ namespace Ndk inline World& World::operator=(World&& world) noexcept { - m_aliveEntities = std::move(world.m_aliveEntities); - m_dirtyEntities = std::move(world.m_dirtyEntities); - m_freeIdList = std::move(world.m_freeIdList); - m_killedEntities = std::move(world.m_killedEntities); + m_aliveEntities = std::move(world.m_aliveEntities); + m_dirtyEntities = std::move(world.m_dirtyEntities); + m_freeIdList = std::move(world.m_freeIdList); + m_killedEntities = std::move(world.m_killedEntities); + m_orderedSystems = std::move(world.m_orderedSystems); + m_orderedSystemsUpdated = world.m_orderedSystemsUpdated; m_entities = std::move(world.m_entities); for (EntityBlock& block : m_entities) @@ -296,4 +281,20 @@ namespace Ndk return *this; } + + inline void World::Invalidate() + { + m_dirtyEntities.Resize(m_entities.size(), false); + m_dirtyEntities.Set(true); // Activation of all bits + } + + inline void World::Invalidate(EntityId id) + { + m_dirtyEntities.UnboundedSet(id, true); + } + + inline void World::InvalidateSystemOrder() + { + m_orderedSystemsUpdated = false; + } } diff --git a/SDK/src/NDK/Application.cpp b/SDK/src/NDK/Application.cpp index f184d5b0b..4098b8a2b 100644 --- a/SDK/src/NDK/Application.cpp +++ b/SDK/src/NDK/Application.cpp @@ -152,7 +152,7 @@ namespace Ndk windowDimensions.MakeZero(); overlay->console = std::make_unique(*info.overlayWorld, Nz::Vector2f(windowDimensions), overlay->lua); - + Console& consoleRef = *overlay->console; // Redirect logs toward the console @@ -248,4 +248,4 @@ namespace Ndk #endif Application* Application::s_application = nullptr; -} \ No newline at end of file +} diff --git a/SDK/src/NDK/BaseSystem.cpp b/SDK/src/NDK/BaseSystem.cpp index 8a2a9dce5..b6ebe9892 100644 --- a/SDK/src/NDK/BaseSystem.cpp +++ b/SDK/src/NDK/BaseSystem.cpp @@ -3,6 +3,7 @@ // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include +#include namespace Ndk { @@ -56,6 +57,26 @@ namespace Ndk return true; } + /*! + * \brief Sets the update order of this system + * + * The system update order is used by the world it belongs to in order to know in which order they should be updated, as some application logic may rely a specific update order. + * A system with a greater update order (ex: 1) is guaranteed to be updated after a system with a lesser update order (ex: -1), otherwise the order is unspecified (and is not guaranteed to be stable). + * + * \param updateOrder The relative update order of the system + * + * \remark The update order is only used by World::Update(float) and does not have any effect regarding a call to BaseSystem::Update(float) + * + * \see GetUpdateOrder + */ + void BaseSystem::SetUpdateOrder(int updateOrder) + { + m_updateOrder = updateOrder; + + if (m_world) + m_world->InvalidateSystemOrder(); + } + /*! * \brief Operation to perform when entity is added to the system * diff --git a/SDK/src/NDK/Components/CameraComponent.cpp b/SDK/src/NDK/Components/CameraComponent.cpp index 28f4e31d5..ae1c129c3 100644 --- a/SDK/src/NDK/Components/CameraComponent.cpp +++ b/SDK/src/NDK/Components/CameraComponent.cpp @@ -141,6 +141,7 @@ namespace Ndk { return m_zNear; } + /*! * \brief Sets the layer of the camera in case of multiples fields * diff --git a/SDK/src/NDK/Components/CollisionComponent2D.cpp b/SDK/src/NDK/Components/CollisionComponent2D.cpp new file mode 100644 index 000000000..912742b0e --- /dev/null +++ b/SDK/src/NDK/Components/CollisionComponent2D.cpp @@ -0,0 +1,118 @@ +// Copyright (C) 2015 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 + +#include +#include +#include +#include +#include +#include +#include + +namespace Ndk +{ + /*! + * \ingroup NDK + * \class Ndk::CollisionComponent2D + * \brief NDK class that represents a two-dimensional collision geometry + */ + + /*! + * \brief Sets geometry for the entity + * + * \param geom Geometry used for collisions + * + * \remark Produces a NazaraAssert if the entity has no physics component and has no static body + */ + + void CollisionComponent2D::SetGeom(Nz::Collider2DRef geom) + { + m_geom = std::move(geom); + + if (m_entity->HasComponent()) + { + // We update the geometry of the PhysiscsObject linked to the PhysicsComponent2D + PhysicsComponent2D& physComponent = m_entity->GetComponent(); + physComponent.GetRigidBody().SetGeom(m_geom); + } + else + { + NazaraAssert(m_staticBody, "An entity without physics component should have a static body"); + m_staticBody->SetGeom(m_geom); + } + } + + /*! + * \brief Initializes the static body + * + * \remark Produces a NazaraAssert if entity is invalid + * \remark Produces a NazaraAssert if entity is not linked to a world, or the world has no physics system + */ + + void CollisionComponent2D::InitializeStaticBody() + { + NazaraAssert(m_entity, "Invalid entity"); + World* entityWorld = m_entity->GetWorld(); + + NazaraAssert(entityWorld, "Entity must have world"); + NazaraAssert(entityWorld->HasSystem(), "World must have a physics system"); + Nz::PhysWorld2D& physWorld = entityWorld->GetSystem().GetWorld(); + + m_staticBody.reset(new Nz::RigidBody2D(&physWorld, 0.f, m_geom)); + + Nz::Matrix4f matrix; + if (m_entity->HasComponent()) + matrix = m_entity->GetComponent().GetTransformMatrix(); + else + matrix.MakeIdentity(); + + m_staticBody->SetPosition(Nz::Vector2f(matrix.GetTranslation())); + + } + + /*! + * \brief Operation to perform when component is attached to an entity + */ + + void CollisionComponent2D::OnAttached() + { + if (!m_entity->HasComponent()) + InitializeStaticBody(); + } + + /*! + * \brief Operation to perform when component is attached to this component + * + * \param component Component being attached + */ + + void CollisionComponent2D::OnComponentAttached(BaseComponent& component) + { + if (IsComponent(component)) + m_staticBody.reset(); + } + + /*! + * \brief Operation to perform when component is detached from this component + * + * \param component Component being detached + */ + + void CollisionComponent2D::OnComponentDetached(BaseComponent& component) + { + if (IsComponent(component)) + InitializeStaticBody(); + } + + /*! + * \brief Operation to perform when component is detached from an entity + */ + + void CollisionComponent2D::OnDetached() + { + m_staticBody.reset(); + } + + ComponentIndex CollisionComponent2D::componentIndex; +} diff --git a/SDK/src/NDK/Components/CollisionComponent3D.cpp b/SDK/src/NDK/Components/CollisionComponent3D.cpp index 423b06cb4..d54c460be 100644 --- a/SDK/src/NDK/Components/CollisionComponent3D.cpp +++ b/SDK/src/NDK/Components/CollisionComponent3D.cpp @@ -33,7 +33,7 @@ namespace Ndk { // We update the geometry of the PhysiscsObject linked to the PhysicsComponent3D PhysicsComponent3D& physComponent = m_entity->GetComponent(); - physComponent.GetPhysObject().SetGeom(m_geom); + physComponent.GetRigidBody().SetGeom(m_geom); } else { diff --git a/SDK/src/NDK/Components/GraphicsComponent.cpp b/SDK/src/NDK/Components/GraphicsComponent.cpp index 954dd2de2..8a8516e16 100644 --- a/SDK/src/NDK/Components/GraphicsComponent.cpp +++ b/SDK/src/NDK/Components/GraphicsComponent.cpp @@ -15,6 +15,62 @@ namespace Ndk * \brief NDK class that represents the component for graphics */ + /*! + * \brief Adds the renderable elements to the render queue + * + * \param renderQueue Queue to be added + */ + void GraphicsComponent::AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const + { + EnsureTransformMatrixUpdate(); + + RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem(); + + for (const Renderable& object : m_renderables) + { + if (!object.dataUpdated) + { + object.data.transformMatrix = Nz::Matrix4f::ConcatenateAffine(renderSystem.GetCoordinateSystemMatrix(), Nz::Matrix4f::ConcatenateAffine(object.data.localMatrix, m_transformMatrix)); + object.renderable->UpdateData(&object.data); + object.dataUpdated = true; + } + + object.renderable->AddToRenderQueue(renderQueue, object.data); + } + } + + /*! + * \brief Attaches a renderable to the entity + * + * \param renderable Reference to a renderable element + * \param renderOrder Render order of the element + */ + void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, int renderOrder) + { + return Attach(renderable, Nz::Matrix4f::Identity(), renderOrder); + } + + /*! + * \brief Attaches a renderable to the entity with a specific matrix + * + * \param renderable Reference to a renderable element + * \param localMatrix Local matrix that will be applied to the instanced renderable + * \param renderOrder Render order of the element + */ + void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder) + { + m_renderables.emplace_back(m_transformMatrix); + Renderable& r = m_renderables.back(); + r.data.localMatrix = localMatrix; + r.data.renderOrder = renderOrder; + r.renderable = std::move(renderable); + r.renderableBoundingVolumeInvalidationSlot.Connect(r.renderable->OnInstancedRenderableInvalidateBoundingVolume, [this] (const Nz::InstancedRenderable*) { InvalidateBoundingVolume(); }); + r.renderableDataInvalidationSlot.Connect(r.renderable->OnInstancedRenderableInvalidateData, std::bind(&GraphicsComponent::InvalidateRenderableData, this, std::placeholders::_1, std::placeholders::_2, m_renderables.size() - 1)); + r.renderableReleaseSlot.Connect(r.renderable->OnInstancedRenderableRelease, this, &GraphicsComponent::Detach); + + InvalidateBoundingVolume(); + } + /*! * \brief Invalidates the data for renderable * @@ -33,6 +89,9 @@ namespace Ndk Renderable& r = m_renderables[index]; r.dataUpdated = false; r.renderable->InvalidateData(&r.data, flags); + + for (VolumeCullingEntry& entry : m_volumeCullingEntries) + entry.listEntry.ForceInvalidation(); } /*! @@ -102,7 +161,11 @@ namespace Ndk NazaraUnused(node); // Our view matrix depends on NodeComponent position/rotation + InvalidateBoundingVolume(); InvalidateTransformMatrix(); + + for (VolumeCullingEntry& entry : m_volumeCullingEntries) + entry.listEntry.ForceInvalidation(); //< Force invalidation on movement } /*! @@ -115,10 +178,29 @@ namespace Ndk m_boundingVolume.MakeNull(); for (const Renderable& r : m_renderables) - m_boundingVolume.ExtendTo(r.renderable->GetBoundingVolume()); + { + Nz::BoundingVolumef boundingVolume = r.renderable->GetBoundingVolume(); - m_boundingVolume.Update(m_transformMatrix); + // Adjust renderable bounding volume by local matrix + if (boundingVolume.IsFinite()) + { + Nz::Boxf localBox = boundingVolume.obb.localBox; + Nz::Vector3f newPos = r.data.localMatrix * localBox.GetPosition(); + Nz::Vector3f newLengths = r.data.localMatrix * localBox.GetLengths(); + + boundingVolume.Set(Nz::Boxf(newPos.x, newPos.y, newPos.z, newLengths.x, newLengths.y, newLengths.z)); + } + + m_boundingVolume.ExtendTo(r.renderable->GetBoundingVolume()); + } + + RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem(); + + m_boundingVolume.Update(Nz::Matrix4f::ConcatenateAffine(renderSystem.GetCoordinateSystemMatrix(), m_transformMatrix)); m_boundingVolumeUpdated = true; + + for (VolumeCullingEntry& entry : m_volumeCullingEntries) + entry.listEntry.UpdateVolume(m_boundingVolume); } /*! diff --git a/SDK/src/NDK/Components/PhysicsComponent2D.cpp b/SDK/src/NDK/Components/PhysicsComponent2D.cpp new file mode 100644 index 000000000..db66178b9 --- /dev/null +++ b/SDK/src/NDK/Components/PhysicsComponent2D.cpp @@ -0,0 +1,92 @@ +// Copyright (C) 2015 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 + +#include +#include +#include +#include +#include +#include +#include + +namespace Ndk +{ + /*! + * \ingroup NDK + * \class Ndk::PhysicsComponent2D + * \brief NDK class that represents a physics point, without any collision + */ + + /*! + * \brief Operation to perform when component is attached to an entity + * + * \remark Produces a NazaraAssert if the world does not have a physics system + */ + + void PhysicsComponent2D::OnAttached() + { + World* entityWorld = m_entity->GetWorld(); + NazaraAssert(entityWorld->HasSystem(), "World must have a 2D physics system"); + + Nz::PhysWorld2D& world = entityWorld->GetSystem().GetWorld(); + + Nz::Collider2DRef geom; + if (m_entity->HasComponent()) + geom = m_entity->GetComponent().GetGeom(); + + Nz::Matrix4f matrix; + if (m_entity->HasComponent()) + matrix = m_entity->GetComponent().GetTransformMatrix(); + else + matrix.MakeIdentity(); + + m_object.reset(new Nz::RigidBody2D(&world, 1.f, geom)); + m_object->SetPosition(Nz::Vector2f(matrix.GetTranslation())); + } + + /*! + * \brief Operation to perform when component is attached to this component + * + * \param component Component being attached + * + * \remark Produces a NazaraAssert if physical object is invalid + */ + + void PhysicsComponent2D::OnComponentAttached(BaseComponent& component) + { + if (IsComponent(component)) + { + NazaraAssert(m_object, "Invalid object"); + m_object->SetGeom(static_cast(component).GetGeom()); + } + } + + /*! + * \brief Operation to perform when component is detached from this component + * + * \param component Component being detached + * + * \remark Produces a NazaraAssert if physical object is invalid + */ + + void PhysicsComponent2D::OnComponentDetached(BaseComponent& component) + { + if (IsComponent(component)) + { + NazaraAssert(m_object, "Invalid object"); + m_object->SetGeom(Nz::NullCollider2D::New()); + } + } + + /*! + * \brief Operation to perform when component is detached from an entity + */ + + void PhysicsComponent2D::OnDetached() + { + m_object.reset(); + } + + ComponentIndex PhysicsComponent2D::componentIndex; +} diff --git a/SDK/src/NDK/Console.cpp b/SDK/src/NDK/Console.cpp index 122e2a125..82d3d40af 100644 --- a/SDK/src/NDK/Console.cpp +++ b/SDK/src/NDK/Console.cpp @@ -167,7 +167,6 @@ namespace Ndk * * \param event Event to be takin into consideration by the console */ - void Console::SendEvent(const Nz::WindowEvent& event) { switch (event.type) diff --git a/SDK/src/NDK/Entity.cpp b/SDK/src/NDK/Entity.cpp index a49a8f6aa..4f60bb427 100644 --- a/SDK/src/NDK/Entity.cpp +++ b/SDK/src/NDK/Entity.cpp @@ -148,9 +148,11 @@ namespace Ndk // We alert each system for (std::size_t index = m_systemBits.FindFirst(); index != m_systemBits.npos; index = m_systemBits.FindNext(index)) { - if (m_world->HasSystem(index)) + auto sysIndex = static_cast(index); + + if (m_world->HasSystem(sysIndex)) { - BaseSystem& system = m_world->GetSystem(index); + BaseSystem& system = m_world->GetSystem(sysIndex); system.RemoveEntity(this); } } diff --git a/SDK/src/NDK/Lua/LuaBinding.cpp b/SDK/src/NDK/Lua/LuaBinding.cpp new file mode 100644 index 000000000..cb763b3b4 --- /dev/null +++ b/SDK/src/NDK/Lua/LuaBinding.cpp @@ -0,0 +1,66 @@ +// This file was automatically generated on 26 May 2014 at 01:05:31 + +#include + +namespace Ndk +{ + /*! + * \ingroup NDK + * \class Ndk::LuaBinding + * \brief NDK class that represents the binding between the engine & the SDK with the Lua scripting + */ + + /*! + * \brief Binds modules to Lua + */ + + LuaBinding::LuaBinding() + { + core = LuaBinding_Base::BindCore(*this); + math = LuaBinding_Base::BindMath(*this); + network = LuaBinding_Base::BindNetwork(*this); + utility = LuaBinding_Base::BindUtility(*this); + + #ifndef NDK_SERVER + audio = LuaBinding_Base::BindAudio(*this); + renderer = LuaBinding_Base::BindRenderer(*this); + graphics = LuaBinding_Base::BindGraphics(*this); + #endif + + sdk = LuaBinding_Base::BindSDK(*this); + } + + /*! + * \brief Registers the classes that will be used by the Lua instance + * + * \param instance Lua instance that will interact with the engine & SDK + */ + + void LuaBinding::RegisterClasses(Nz::LuaInstance& instance) + { + core->Register(instance); + math->Register(instance); + network->Register(instance); + sdk->Register(instance); + utility->Register(instance); + + #ifndef NDK_SERVER + audio->Register(instance); + graphics->Register(instance); + renderer->Register(instance); + #endif + + // ComponentType (fake enumeration to expose component indexes) + instance.PushTable(0, m_componentBinding.size()); + { + for (const ComponentBinding& entry : m_componentBinding) + { + if (entry.name.IsEmpty()) + continue; + + instance.PushField(entry.name, entry.index); + } + } + instance.SetGlobal("ComponentType"); + } +} diff --git a/SDK/src/NDK/Lua/LuaBinding_Audio.cpp b/SDK/src/NDK/Lua/LuaBinding_Audio.cpp new file mode 100644 index 000000000..619fe2850 --- /dev/null +++ b/SDK/src/NDK/Lua/LuaBinding_Audio.cpp @@ -0,0 +1,198 @@ +// This file was automatically generated on 26 May 2014 at 01:05:31 + +#include +#include +#include + +namespace Ndk +{ + std::unique_ptr LuaBinding_Base::BindAudio(LuaBinding& binding) + { + return std::make_unique(binding); + } + + LuaBinding_Audio::LuaBinding_Audio(LuaBinding& binding) : + LuaBinding_Base(binding) + { + /*********************************** Nz::SoundEmitter **********************************/ + soundEmitter.Reset("SoundEmitter"); + { + soundEmitter.BindMethod("EnableLooping", &Nz::SoundEmitter::EnableLooping); + soundEmitter.BindMethod("EnableSpatialization", &Nz::SoundEmitter::EnableSpatialization); + + soundEmitter.BindMethod("GetAttenuation", &Nz::SoundEmitter::GetAttenuation); + soundEmitter.BindMethod("GetDuration", &Nz::SoundEmitter::GetDuration); + soundEmitter.BindMethod("GetMinDistance", &Nz::SoundEmitter::GetMinDistance); + soundEmitter.BindMethod("GetPitch", &Nz::SoundEmitter::GetPitch); + soundEmitter.BindMethod("GetPlayingOffset", &Nz::SoundEmitter::GetPlayingOffset); + soundEmitter.BindMethod("GetPosition", &Nz::Sound::GetPosition); + soundEmitter.BindMethod("GetStatus", &Nz::SoundEmitter::GetStatus); + soundEmitter.BindMethod("GetVelocity", &Nz::Sound::GetVelocity); + soundEmitter.BindMethod("GetVolume", &Nz::SoundEmitter::GetVolume); + + soundEmitter.BindMethod("IsLooping", &Nz::SoundEmitter::IsLooping); + soundEmitter.BindMethod("IsSpatialized", &Nz::SoundEmitter::IsSpatialized); + + soundEmitter.BindMethod("Pause", &Nz::SoundEmitter::Pause); + soundEmitter.BindMethod("Play", &Nz::SoundEmitter::Play); + + soundEmitter.BindMethod("SetAttenuation", &Nz::SoundEmitter::SetAttenuation); + soundEmitter.BindMethod("SetMinDistance", &Nz::SoundEmitter::SetMinDistance); + soundEmitter.BindMethod("SetPitch", &Nz::SoundEmitter::SetPitch); + soundEmitter.BindMethod("SetPosition", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetPosition); + soundEmitter.BindMethod("SetVelocity", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetVelocity); + soundEmitter.BindMethod("SetVolume", &Nz::SoundEmitter::SetVolume); + + soundEmitter.BindMethod("Stop", &Nz::SoundEmitter::Stop); + } + + /*********************************** Nz::Music **********************************/ + music.Reset("Music"); + { + music.Inherit(soundEmitter); + + music.BindDefaultConstructor(); + + //musicClass.SetMethod("Create", &Nz::Music::Create); + //musicClass.SetMethod("Destroy", &Nz::Music::Destroy); + + music.BindMethod("EnableLooping", &Nz::Music::EnableLooping); + + music.BindMethod("GetDuration", &Nz::Music::GetDuration); + music.BindMethod("GetFormat", &Nz::Music::GetFormat); + music.BindMethod("GetPlayingOffset", &Nz::Music::GetPlayingOffset); + music.BindMethod("GetSampleCount", &Nz::Music::GetSampleCount); + music.BindMethod("GetSampleRate", &Nz::Music::GetSampleRate); + music.BindMethod("GetStatus", &Nz::Music::GetStatus); + + music.BindMethod("IsLooping", &Nz::Music::IsLooping); + + music.BindMethod("OpenFromFile", &Nz::Music::OpenFromFile, Nz::MusicParams()); + + music.BindMethod("Pause", &Nz::Music::Pause); + music.BindMethod("Play", &Nz::Music::Play); + + music.BindMethod("SetPlayingOffset", &Nz::Music::SetPlayingOffset); + + music.BindMethod("Stop", &Nz::Music::Stop); + + // Manual + music.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& instance, std::size_t /*argumentCount*/) -> int + { + Nz::StringStream ss("Music("); + ss << instance.GetFilePath() << ')'; + + lua.PushString(ss); + return 1; + }); + } + + /*********************************** Nz::Sound **********************************/ + sound.Reset("Sound"); + { + sound.Inherit(soundEmitter); + + sound.BindDefaultConstructor(); + + sound.BindMethod("GetBuffer", &Nz::Sound::GetBuffer); + + sound.BindMethod("IsPlayable", &Nz::Sound::IsPlayable); + sound.BindMethod("IsPlaying", &Nz::Sound::IsPlaying); + + sound.BindMethod("LoadFromFile", &Nz::Sound::LoadFromFile, Nz::SoundBufferParams()); + + sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset); + + // Manual + sound.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& instance, std::size_t /*argumentCount*/) -> int + { + Nz::StringStream ss("Sound("); + if (const Nz::SoundBuffer* buffer = instance.GetBuffer()) + ss << buffer; + + ss << ')'; + + lua.PushString(ss); + return 1; + }); + } + + /*********************************** Nz::SoundBuffer **********************************/ + soundBuffer.Reset("SoundBuffer"); + { + soundBuffer.SetConstructor([] (Nz::LuaInstance& lua, Nz::SoundBufferRef* instance, std::size_t argumentCount) + { + NazaraUnused(lua); + NazaraUnused(argumentCount); + + Nz::PlacementNew(instance, Nz::SoundBuffer::New()); + return true; + }); + + soundBuffer.BindMethod("Destroy", &Nz::SoundBuffer::Destroy); + + soundBuffer.BindMethod("GetDuration", &Nz::SoundBuffer::GetDuration); + soundBuffer.BindMethod("GetFormat", &Nz::SoundBuffer::GetFormat); + soundBuffer.BindMethod("GetSampleCount", &Nz::SoundBuffer::GetSampleCount); + soundBuffer.BindMethod("GetSampleRate", &Nz::SoundBuffer::GetSampleRate); + + soundBuffer.BindMethod("IsValid", &Nz::SoundBuffer::IsValid); + + soundBuffer.BindMethod("LoadFromFile", &Nz::SoundBuffer::LoadFromFile, Nz::SoundBufferParams()); + + soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported); + + // Manual + soundBuffer.BindMethod("Create", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int + { + int index = 2; + Nz::AudioFormat format = lua.Check(&index); + unsigned int sampleCount = lua.Check(&index); + unsigned int sampleRate = lua.Check(&index); + + std::size_t bufferSize = 0; + const char* buffer = lua.CheckString(index, &bufferSize); + lua.ArgCheck(buffer && bufferSize >= sampleCount * sizeof(Nz::Int16), index, "Invalid buffer"); + + lua.PushBoolean(instance->Create(format, sampleCount, sampleRate, reinterpret_cast(buffer))); + return 1; + }); + + soundBuffer.BindMethod("GetSamples", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int + { + lua.PushString(reinterpret_cast(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16)); + return 1; + }); + + soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int + { + Nz::StringStream ss("SoundBuffer("); + if (instance->IsValid()) + { + Nz::String filePath = instance->GetFilePath(); + if (!filePath.IsEmpty()) + ss << "File: " << filePath << ", "; + + ss << "Duration: " << instance->GetDuration() / 1000.f << "s"; + } + ss << ')'; + + lua.PushString(ss); + return 1; + }); + } + } + + /*! + * \brief Registers the classes that will be used by the Lua instance + * + * \param instance Lua instance that will interact with the Audio classes + */ + void LuaBinding_Audio::Register(Nz::LuaInstance& instance) + { + music.Register(instance); + sound.Register(instance); + soundBuffer.Register(instance); + soundEmitter.Register(instance); + } +} diff --git a/SDK/src/NDK/Lua/LuaBinding_Base.cpp b/SDK/src/NDK/Lua/LuaBinding_Base.cpp new file mode 100644 index 000000000..b9bd44c57 --- /dev/null +++ b/SDK/src/NDK/Lua/LuaBinding_Base.cpp @@ -0,0 +1,13 @@ +// This file was automatically generated on 26 May 2014 at 01:05:31 + +#include + +namespace Ndk +{ + LuaBinding_Base::LuaBinding_Base(LuaBinding& binding) : + m_binding(binding) + { + } + + LuaBinding_Base::~LuaBinding_Base() = default; +} diff --git a/SDK/src/NDK/Lua/LuaBinding_Core.cpp b/SDK/src/NDK/Lua/LuaBinding_Core.cpp new file mode 100644 index 000000000..e808c3804 --- /dev/null +++ b/SDK/src/NDK/Lua/LuaBinding_Core.cpp @@ -0,0 +1,354 @@ +// This file was automatically generated on 26 May 2014 at 01:05:31 + +#include +#include +#include + +namespace Ndk +{ + std::unique_ptr LuaBinding_Base::BindCore(LuaBinding& binding) + { + return std::make_unique(binding); + } + + LuaBinding_Core::LuaBinding_Core(LuaBinding& binding) : + LuaBinding_Base(binding) + { + /*********************************** Nz::Stream ***********************************/ + stream.Reset("Stream"); + { + stream.BindMethod("EnableTextMode", &Nz::Stream::EnableTextMode); + stream.BindMethod("Flush", &Nz::Stream::Flush); + stream.BindMethod("GetCursorPos", &Nz::Stream::GetCursorPos); + stream.BindMethod("GetDirectory", &Nz::Stream::GetDirectory); + stream.BindMethod("GetPath", &Nz::Stream::GetPath); + stream.BindMethod("GetOpenMode", &Nz::Stream::GetOpenMode); + stream.BindMethod("GetStreamOptions", &Nz::Stream::GetStreamOptions); + stream.BindMethod("GetSize", &Nz::Stream::GetSize); + stream.BindMethod("ReadLine", &Nz::Stream::ReadLine, 0U); + stream.BindMethod("IsReadable", &Nz::Stream::IsReadable); + stream.BindMethod("IsSequential", &Nz::Stream::IsSequential); + stream.BindMethod("IsTextModeEnabled", &Nz::Stream::IsTextModeEnabled); + stream.BindMethod("IsWritable", &Nz::Stream::IsWritable); + stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos); + + stream.BindMethod("Read", [] (Nz::LuaInstance& 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 = instance.Read(buffer.get(), length); + + lua.PushString(Nz::String(buffer.get(), readLength)); + return 1; + }); + + stream.BindMethod("Write", [] (Nz::LuaInstance& 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 (instance.IsTextModeEnabled()) + lua.Push(instance.Write(Nz::String(buffer, bufferSize))); + else + lua.Push(instance.Write(buffer, bufferSize)); + return 1; + }); + } + + /*********************************** Nz::Clock **********************************/ + clock.Reset("Clock"); + { + clock.SetConstructor([] (Nz::LuaInstance& lua, Nz::Clock* instance, std::size_t argumentCount) + { + std::size_t argCount = std::min(argumentCount, 2U); + + int argIndex = 2; + switch (argCount) + { + case 0: + Nz::PlacementNew(instance); + return true; + + case 1: + { + Nz::Int64 startingValue = lua.Check(&argIndex, 0); + + Nz::PlacementNew(instance, startingValue); + return true; + } + + case 2: + { + Nz::Int64 startingValue = lua.Check(&argIndex, 0); + bool paused = lua.Check(&argIndex, false); + + Nz::PlacementNew(instance, startingValue, paused); + return true; + } + } + + lua.Error("No matching overload for Clock constructor"); + return false; + }); + + clock.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds); + clock.BindMethod("GetMilliseconds", &Nz::Clock::GetMilliseconds); + clock.BindMethod("GetSeconds", &Nz::Clock::GetSeconds); + clock.BindMethod("IsPaused", &Nz::Clock::IsPaused); + clock.BindMethod("Pause", &Nz::Clock::Pause); + clock.BindMethod("Restart", &Nz::Clock::Restart); + clock.BindMethod("Unpause", &Nz::Clock::Unpause); + + // Manual + clock.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& instance, std::size_t /*argumentCount*/) -> int { + Nz::StringStream ss("Clock(Elapsed: "); + ss << instance.GetSeconds(); + ss << "s, Paused: "; + ss << instance.IsPaused(); + ss << ')'; + + lua.PushString(ss); + return 1; + }); + } + + /********************************* Nz::Directory ********************************/ + directory.Reset("Directory"); + { + directory.SetConstructor([] (Nz::LuaInstance& lua, Nz::Directory* instance, std::size_t argumentCount) + { + std::size_t argCount = std::min(argumentCount, 1U); + + int argIndex = 2; + switch (argCount) + { + case 0: + Nz::PlacementNew(instance); + return true; + + case 1: + Nz::PlacementNew(instance, lua.Check(&argIndex)); + return true; + } + + return false; + }); + + directory.BindMethod("Close", &Nz::Directory::Close); + directory.BindMethod("Exists", &Nz::Directory::Exists); + directory.BindMethod("GetPath", &Nz::Directory::GetPath); + directory.BindMethod("GetPattern", &Nz::Directory::GetPattern); + directory.BindMethod("GetResultName", &Nz::Directory::GetResultName); + directory.BindMethod("GetResultPath", &Nz::Directory::GetResultPath); + directory.BindMethod("GetResultSize", &Nz::Directory::GetResultSize); + directory.BindMethod("IsOpen", &Nz::Directory::IsOpen); + directory.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory); + directory.BindMethod("NextResult", &Nz::Directory::NextResult, true); + directory.BindMethod("Open", &Nz::Directory::Open); + directory.BindMethod("SetPath", &Nz::Directory::SetPath); + directory.BindMethod("SetPattern", &Nz::Directory::SetPattern); + + directory.BindStaticMethod("Copy", Nz::Directory::Copy); + directory.BindStaticMethod("Create", Nz::Directory::Create); + directory.BindStaticMethod("Exists", Nz::Directory::Exists); + directory.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent); + directory.BindStaticMethod("Remove", Nz::Directory::Remove); + directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); + + // Manual + directory.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& instance, std::size_t /*argumentCount*/) -> int { + Nz::StringStream ss("Directory("); + ss << instance.GetPath(); + ss << ')'; + + lua.PushString(ss); + return 1; + }); + } + + /*********************************** Nz::File ***********************************/ + file.Reset("Stream"); + { + file.Inherit(stream); + + file.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* instance, std::size_t argumentCount) + { + std::size_t argCount = std::min(argumentCount, 1U); + + int argIndex = 2; + switch (argCount) + { + case 0: + Nz::PlacementNew(instance); + return true; + + case 1: + { + Nz::String filePath = lua.Check(&argIndex); + + Nz::PlacementNew(instance, filePath); + return true; + } + + case 2: + { + Nz::String filePath = lua.Check(&argIndex); + Nz::UInt32 openMode = lua.Check(&argIndex); + + Nz::PlacementNew(instance, filePath, openMode); + return true; + } + } + + lua.Error("No matching overload for File constructor"); + return false; + }); + + file.BindMethod("Close", &Nz::File::Close); + file.BindMethod("Copy", &Nz::File::Copy); + file.BindMethod("Delete", &Nz::File::Delete); + file.BindMethod("EndOfFile", &Nz::File::EndOfFile); + file.BindMethod("Exists", &Nz::File::Exists); + file.BindMethod("GetCreationTime", &Nz::File::GetCreationTime); + file.BindMethod("GetFileName", &Nz::File::GetFileName); + file.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); + file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); + file.BindMethod("IsOpen", &Nz::File::IsOpen); + file.BindMethod("Rename", &Nz::File::GetLastWriteTime); + file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); + file.BindMethod("SetFile", &Nz::File::GetLastWriteTime); + + file.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath); + file.BindStaticMethod("ComputeHash", (Nz::ByteArray(*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash); + file.BindStaticMethod("Copy", &Nz::File::Copy); + file.BindStaticMethod("Delete", &Nz::File::Delete); + file.BindStaticMethod("Exists", &Nz::File::Exists); + //fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime); + file.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory); + //fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); + //fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); + file.BindStaticMethod("GetSize", &Nz::File::GetSize); + file.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute); + file.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath); + file.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators); + file.BindStaticMethod("Rename", &Nz::File::Rename); + + // Manual + file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int + { + std::size_t argCount = std::min(argumentCount, 2U); + + int argIndex = 2; + switch (argCount) + { + case 0: + case 1: + 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(instance.Open(filePath, openMode)); + } + } + + lua.Error("No matching overload for method Open"); + return 0; + }); + + file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int + { + std::size_t argCount = std::min(argumentCount, 2U); + + int argIndex = 2; + switch (argCount) + { + case 1: + 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(instance.SetCursorPos(curPos, offset)); + } + } + + lua.Error("No matching overload for method SetCursorPos"); + return 0; + }); + + file.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t /*argumentCount*/) -> int { + Nz::StringStream ss("File("); + if (instance.IsOpen()) + ss << "Path: " << instance.GetPath(); + + ss << ')'; + + lua.PushString(ss); + return 1; + }); + } + } + + /*! + * \brief Registers the classes that will be used by the Lua instance + * + * \param instance Lua instance that will interact with the Core classes + */ + void LuaBinding_Core::Register(Nz::LuaInstance& instance) + { + // Classes + clock.Register(instance); + directory.Register(instance); + file.Register(instance); + stream.Register(instance); + + // Enums + + // Nz::CursorPosition + static_assert(Nz::CursorPosition_Max + 1 == 3, "Nz::CursorPosition has been updated but change was not reflected to Lua binding"); + instance.PushTable(0, 3); + { + instance.PushField("AtBegin", Nz::CursorPosition_AtBegin); + instance.PushField("AtCurrent", Nz::CursorPosition_AtCurrent); + instance.PushField("AtEnd", Nz::CursorPosition_AtEnd); + } + instance.SetGlobal("CursorPosition"); + + // Nz::HashType + static_assert(Nz::HashType_Max + 1 == 9, "Nz::HashType has been updated but change was not reflected to Lua binding"); + instance.PushTable(0, 9); + { + instance.PushField("CRC32", Nz::HashType_CRC32); + instance.PushField("Fletcher16", Nz::HashType_Fletcher16); + instance.PushField("MD5", Nz::HashType_MD5); + instance.PushField("SHA1", Nz::HashType_SHA1); + instance.PushField("SHA224", Nz::HashType_SHA224); + instance.PushField("SHA256", Nz::HashType_SHA256); + instance.PushField("SHA384", Nz::HashType_SHA384); + instance.PushField("SHA512", Nz::HashType_SHA512); + instance.PushField("Whirlpool", Nz::HashType_Whirlpool); + } + instance.SetGlobal("HashType"); + + // Nz::OpenMode + static_assert(Nz::OpenMode_Max + 1 == 8, "Nz::OpenModeFlags has been updated but change was not reflected to Lua binding"); + instance.PushTable(0, Nz::OpenMode_Max + 1); + { + instance.PushField("Append", Nz::OpenMode_Append); + instance.PushField("NotOpen", Nz::OpenMode_NotOpen); + instance.PushField("Lock", Nz::OpenMode_Lock); + instance.PushField("ReadOnly", Nz::OpenMode_ReadOnly); + instance.PushField("ReadWrite", Nz::OpenMode_ReadWrite); + instance.PushField("Text", Nz::OpenMode_Text); + instance.PushField("Truncate", Nz::OpenMode_Truncate); + instance.PushField("WriteOnly", Nz::OpenMode_WriteOnly); + } + instance.SetGlobal("OpenMode"); + } +} diff --git a/SDK/src/NDK/Lua/LuaBinding_Graphics.cpp b/SDK/src/NDK/Lua/LuaBinding_Graphics.cpp new file mode 100644 index 000000000..f87ac6556 --- /dev/null +++ b/SDK/src/NDK/Lua/LuaBinding_Graphics.cpp @@ -0,0 +1,370 @@ +// 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::BindGraphics(LuaBinding& binding) + { + return std::make_unique(binding); + } + + LuaBinding_Graphics::LuaBinding_Graphics(LuaBinding& binding) : + LuaBinding_Base(binding) + { + /*********************************** Nz::AbstractViewer ***********************************/ + abstractViewer.Reset("AbstractViewer"); + { + abstractViewer.BindMethod("GetAspectRatio", &Nz::AbstractViewer::GetAspectRatio); + abstractViewer.BindMethod("GetEyePosition", &Nz::AbstractViewer::GetEyePosition); + abstractViewer.BindMethod("GetForward", &Nz::AbstractViewer::GetForward); + //abstractViewer.BindMethod("GetFrustum", &Nz::AbstractViewer::GetFrustum); + abstractViewer.BindMethod("GetProjectionMatrix", &Nz::AbstractViewer::GetProjectionMatrix); + //abstractViewer.BindMethod("GetTarget", &Nz::AbstractViewer::GetTarget); + abstractViewer.BindMethod("GetViewMatrix", &Nz::AbstractViewer::GetViewMatrix); + abstractViewer.BindMethod("GetViewport", &Nz::AbstractViewer::GetViewport); + abstractViewer.BindMethod("GetZFar", &Nz::AbstractViewer::GetZFar); + abstractViewer.BindMethod("GetZNear", &Nz::AbstractViewer::GetZNear); + } + + /*********************************** Nz::InstancedRenderable ***********************************/ + instancedRenderable.Reset("InstancedRenderable"); + { + } + + /*********************************** Nz::Material ***********************************/ + material.Reset("Material"); + { + material.SetConstructor([] (Nz::LuaInstance& lua, Nz::MaterialRef* instance, std::size_t argumentCount) + { + switch (argumentCount) + { + case 0: + Nz::PlacementNew(instance, Nz::Material::New()); + return true; + + case 1: + { + int argIndex = 1; + if (lua.IsOfType(argIndex, "MaterialPipeline")) + { + Nz::PlacementNew(instance, Nz::Material::New(*static_cast(lua.ToUserdata(argIndex)))); + return true; + } + else if (lua.IsOfType(argIndex, "Material")) + { + Nz::PlacementNew(instance, Nz::Material::New(**static_cast(lua.ToUserdata(argIndex)))); + return true; + } + else + { + Nz::PlacementNew(instance, Nz::Material::New(lua.Check(&argIndex))); + return true; + } + } + } + + lua.Error("No matching overload for constructor"); + return false; + }); + + material.BindMethod("Configure", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "MaterialPipeline")) + { + instance->Configure(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + { + lua.Push(instance->Configure(lua.Check(&argIndex))); + return 1; + } + }); + + material.BindMethod("EnableAlphaTest", &Nz::Material::EnableAlphaTest); + material.BindMethod("EnableBlending", &Nz::Material::EnableBlending); + material.BindMethod("EnableColorWrite", &Nz::Material::EnableColorWrite); + material.BindMethod("EnableDepthBuffer", &Nz::Material::EnableDepthBuffer); + material.BindMethod("EnableDepthSorting", &Nz::Material::EnableDepthSorting); + material.BindMethod("EnableDepthWrite", &Nz::Material::EnableDepthWrite); + material.BindMethod("EnableFaceCulling", &Nz::Material::EnableFaceCulling); + material.BindMethod("EnableScissorTest", &Nz::Material::EnableScissorTest); + material.BindMethod("EnableShadowCasting", &Nz::Material::EnableShadowCasting); + material.BindMethod("EnableShadowReceive", &Nz::Material::EnableShadowReceive); + material.BindMethod("EnableStencilTest", &Nz::Material::EnableStencilTest); + + material.BindMethod("EnsurePipelineUpdate", &Nz::Material::EnsurePipelineUpdate); + + material.BindMethod("GetAlphaMap", &Nz::Material::GetAlphaMap); + material.BindMethod("GetAlphaThreshold", &Nz::Material::GetAlphaThreshold); + material.BindMethod("GetAmbientColor", &Nz::Material::GetAmbientColor); + material.BindMethod("GetDepthFunc", &Nz::Material::GetDepthFunc); + material.BindMethod("GetDepthMaterial", &Nz::Material::GetDepthMaterial); + material.BindMethod("GetDiffuseColor", &Nz::Material::GetDiffuseColor); + material.BindMethod("GetDiffuseMap", &Nz::Material::GetDiffuseMap); + //material.BindMethod("GetDiffuseSampler", &Nz::Material::GetDiffuseSampler); + material.BindMethod("GetDstBlend", &Nz::Material::GetDstBlend); + material.BindMethod("GetEmissiveMap", &Nz::Material::GetEmissiveMap); + material.BindMethod("GetFaceCulling", &Nz::Material::GetFaceCulling); + material.BindMethod("GetFaceFilling", &Nz::Material::GetFaceFilling); + material.BindMethod("GetHeightMap", &Nz::Material::GetHeightMap); + material.BindMethod("GetLineWidth", &Nz::Material::GetLineWidth); + material.BindMethod("GetNormalMap", &Nz::Material::GetNormalMap); + //material.BindMethod("GetPipeline", &Nz::Material::GetPipeline); + //material.BindMethod("GetPipelineInfo", &Nz::Material::GetPipelineInfo); + material.BindMethod("GetPointSize", &Nz::Material::GetPointSize); + //material.BindMethod("GetShader", &Nz::Material::GetShader); + material.BindMethod("GetShininess", &Nz::Material::GetShininess); + material.BindMethod("GetSpecularColor", &Nz::Material::GetSpecularColor); + material.BindMethod("GetSpecularMap", &Nz::Material::GetSpecularMap); + //material.BindMethod("GetSpecularSampler", &Nz::Material::GetSpecularSampler); + material.BindMethod("GetSrcBlend", &Nz::Material::GetSrcBlend); + + material.BindMethod("HasAlphaMap", &Nz::Material::HasAlphaMap); + material.BindMethod("HasDepthMaterial", &Nz::Material::HasDepthMaterial); + material.BindMethod("HasDiffuseMap", &Nz::Material::HasDiffuseMap); + material.BindMethod("HasEmissiveMap", &Nz::Material::HasEmissiveMap); + material.BindMethod("HasHeightMap", &Nz::Material::HasHeightMap); + material.BindMethod("HasNormalMap", &Nz::Material::HasNormalMap); + material.BindMethod("HasSpecularMap", &Nz::Material::HasSpecularMap); + + material.BindMethod("IsAlphaTestEnabled", &Nz::Material::IsAlphaTestEnabled); + material.BindMethod("IsBlendingEnabled", &Nz::Material::IsBlendingEnabled); + material.BindMethod("IsColorWriteEnabled", &Nz::Material::IsColorWriteEnabled); + material.BindMethod("IsDepthBufferEnabled", &Nz::Material::IsDepthBufferEnabled); + material.BindMethod("IsDepthSortingEnabled", &Nz::Material::IsDepthSortingEnabled); + material.BindMethod("IsDepthWriteEnabled", &Nz::Material::IsDepthWriteEnabled); + material.BindMethod("IsFaceCullingEnabled", &Nz::Material::IsFaceCullingEnabled); + material.BindMethod("IsScissorTestEnabled", &Nz::Material::IsScissorTestEnabled); + material.BindMethod("IsStencilTestEnabled", &Nz::Material::IsStencilTestEnabled); + material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled); + material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled); + + material.BindMethod("LoadFromFile", &Nz::Material::LoadFromFile, Nz::MaterialParams()); + + material.BindMethod("Reset", &Nz::Material::Reset); + + material.BindMethod("SetAlphaThreshold", &Nz::Material::SetAlphaThreshold); + material.BindMethod("SetAmbientColor", &Nz::Material::SetAmbientColor); + material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc); + material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc); + material.BindMethod("SetDepthMaterial", &Nz::Material::SetDepthMaterial); + material.BindMethod("SetDiffuseColor", &Nz::Material::SetDiffuseColor); + //material.BindMethod("SetDiffuseSampler", &Nz::Material::SetDiffuseSampler); + material.BindMethod("SetDstBlend", &Nz::Material::SetDstBlend); + material.BindMethod("SetFaceCulling", &Nz::Material::SetFaceCulling); + material.BindMethod("SetFaceFilling", &Nz::Material::SetFaceFilling); + material.BindMethod("SetLineWidth", &Nz::Material::SetLineWidth); + material.BindMethod("SetPointSize", &Nz::Material::SetPointSize); + material.BindMethod("SetShininess", &Nz::Material::SetShininess); + material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor); + material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor); + //material.BindMethod("SetSpecularSampler", &Nz::Material::SetSpecularSampler); + material.BindMethod("SetSrcBlend", &Nz::Material::SetSrcBlend); + + material.BindStaticMethod("GetDefault", &Nz::Material::GetDefault); + + material.BindMethod("SetAlphaMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetAlphaMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetAlphaMap(lua.Check(&argIndex))); + }); + + material.BindMethod("SetDiffuseMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetDiffuseMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetDiffuseMap(lua.Check(&argIndex))); + }); + + material.BindMethod("SetEmissiveMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetEmissiveMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetEmissiveMap(lua.Check(&argIndex))); + }); + + material.BindMethod("SetHeightMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetHeightMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetHeightMap(lua.Check(&argIndex))); + }); + + material.BindMethod("SetNormalMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetNormalMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetNormalMap(lua.Check(&argIndex))); + }); + + material.BindMethod("SetShader", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "UberShader")) + { + instance->SetShader(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetShader(lua.Check(&argIndex))); + }); + + material.BindMethod("SetSpecularMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Texture")) + { + instance->SetSpecularMap(*static_cast(lua.ToUserdata(argIndex))); + return 0; + } + else + return lua.Push(instance->SetSpecularMap(lua.Check(&argIndex))); + }); + } + + /*********************************** Nz::Model ***********************************/ + model.Reset("Model"); + { + model.Inherit(instancedRenderable, [] (Nz::ModelRef* modelRef) -> Nz::InstancedRenderableRef* + { + return reinterpret_cast(modelRef); //TODO: Make a ObjectRefCast + }); + + model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* instance, std::size_t /*argumentCount*/) + { + Nz::PlacementNew(instance, Nz::Model::New()); + return true; + }); + + //model.BindMethod("GetMaterial", &Nz::Model::GetMaterial); + model.BindMethod("GetMaterialCount", &Nz::Model::GetMaterialCount); + //modelClass.SetMethod("GetMesh", &Nz::Model::GetMesh); + model.BindMethod("GetSkin", &Nz::Model::GetSkin); + model.BindMethod("GetSkinCount", &Nz::Model::GetSkinCount); + + model.BindMethod("IsAnimated", &Nz::Model::IsAnimated); + model.BindMethod("LoadFromFile", &Nz::Model::LoadFromFile, Nz::ModelParameters()); + + model.BindMethod("Reset", &Nz::Model::Reset); + + //model.BindMethod("SetMaterial", &Nz::Model::SetMaterial); + //modelClass.SetMethod("SetMesh", &Nz::Model::SetMesh); + //modelClass.SetMethod("SetSequence", &Nz::Model::SetSequence); + model.BindMethod("SetSkin", &Nz::Model::SetSkin); + model.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount); + } + + /*********************************** Nz::Sprite ***********************************/ + sprite.Reset("Sprite"); + { + sprite.Inherit(instancedRenderable, [] (Nz::SpriteRef* spriteRef) -> Nz::InstancedRenderableRef* + { + return reinterpret_cast(spriteRef); //TODO: Make a ObjectRefCast + }); + + sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* instance, std::size_t /*argumentCount*/) + { + Nz::PlacementNew(instance, Nz::Sprite::New()); + return true; + }); + + sprite.BindMethod("GetColor", &Nz::Sprite::GetColor); + sprite.BindMethod("GetCornerColor", &Nz::Sprite::GetCornerColor); + sprite.BindMethod("GetMaterial", &Nz::Sprite::GetMaterial); + sprite.BindMethod("GetOrigin", &Nz::Sprite::GetOrigin); + sprite.BindMethod("GetSize", &Nz::Sprite::GetSize); + sprite.BindMethod("GetTextureCoords", &Nz::Sprite::GetTextureCoords); + + sprite.BindMethod("SetColor", &Nz::Sprite::SetColor); + sprite.BindMethod("SetCornerColor", &Nz::Sprite::SetCornerColor); + sprite.BindMethod("SetDefaultMaterial", &Nz::Sprite::SetDefaultMaterial); + sprite.BindMethod("SetOrigin", &Nz::Sprite::SetOrigin); + sprite.BindMethod("SetSize", (void(Nz::Sprite::*)(const Nz::Vector2f&)) &Nz::Sprite::SetSize); + sprite.BindMethod("SetTextureCoords", &Nz::Sprite::SetTextureCoords); + sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect); + + sprite.BindMethod("SetMaterial", [] (Nz::LuaInstance& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); + + if (lua.IsOfType(argIndex, "Material")) + instance->SetMaterial(*static_cast(lua.ToUserdata(argIndex)), resizeSprite); + else + instance->SetMaterial(lua.Check(&argIndex), resizeSprite); + + return 0; + }); + + sprite.BindMethod("SetTexture", [] (Nz::LuaInstance& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); + + if (lua.IsOfType(argIndex, "Texture")) + instance->SetTexture(*static_cast(lua.ToUserdata(argIndex)), resizeSprite); + else + instance->SetTexture(lua.Check(&argIndex), resizeSprite); + + return 0; + }); + } + + /*********************************** Nz::SpriteLibrary ***********************************/ + spriteLibrary.Reset("SpriteLibrary"); + { + spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get); + spriteLibrary.BindStaticMethod("Has", &Nz::SpriteLibrary::Has); + spriteLibrary.BindStaticMethod("Register", &Nz::SpriteLibrary::Register); + spriteLibrary.BindStaticMethod("Query", &Nz::SpriteLibrary::Query); + spriteLibrary.BindStaticMethod("Unregister", &Nz::SpriteLibrary::Unregister); + } + } + + /*! + * \brief Registers the classes that will be used by the Lua instance + * + * \param instance Lua instance that will interact with the Graphics classes + */ + + void LuaBinding_Graphics::Register(Nz::LuaInstance& instance) + { + abstractViewer.Register(instance); + instancedRenderable.Register(instance); + material.Register(instance); + model.Register(instance); + sprite.Register(instance); + spriteLibrary.Register(instance); + } +} diff --git a/SDK/src/NDK/Lua/LuaBinding_Math.cpp b/SDK/src/NDK/Lua/LuaBinding_Math.cpp new file mode 100644 index 000000000..6d30bb137 --- /dev/null +++ b/SDK/src/NDK/Lua/LuaBinding_Math.cpp @@ -0,0 +1,986 @@ +// This file was automatically generated on 26 May 2014 at 01:05:31 + +#include +#include +#include +#include + +namespace Ndk +{ + std::unique_ptr LuaBinding_Base::BindMath(LuaBinding& binding) + { + return std::make_unique(binding); + } + + LuaBinding_Math::LuaBinding_Math(LuaBinding& binding) : + LuaBinding_Base(binding) + { + /*********************************** Nz::EulerAngles **********************************/ + eulerAngles.Reset("EulerAngles"); + { + eulerAngles.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* instance, std::size_t argumentCount) + { + std::size_t argCount = std::min(argumentCount, 1U); + + switch (argCount) + { + case 0: + Nz::PlacementNew(instance, Nz::EulerAnglesd::Zero()); + return true; + + case 1: + Nz::PlacementNew(instance, *static_cast(lua.CheckUserdata(1, "EulerAngles"))); + return true; + + case 3: + Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3)); + return true; + } + + lua.Error("No matching overload for EulerAngles constructor"); + return false; + }); + + eulerAngles.BindMethod("Normalize", &Nz::EulerAnglesd::Normalize); + eulerAngles.BindMethod("ToQuaternion", &Nz::EulerAnglesd::ToQuaternion); + + eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString); + + eulerAngles.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) + { + std::size_t length; + const char* ypr = lua.CheckString(2, &length); + + switch (length) + { + case 1: + { + switch (ypr[0]) + { + case 'p': + lua.Push(instance.pitch); + return true; + + case 'y': + lua.Push(instance.yaw); + return true; + + case 'r': + lua.Push(instance.roll); + return true; + } + break; + } + + case 3: + { + if (std::memcmp(ypr, "yaw", 3) != 0) + break; + + lua.Push(instance.yaw); + return true; + } + + case 4: + { + if (std::memcmp(ypr, "roll", 4) != 0) + break; + + lua.Push(instance.roll); + return true; + } + + case 5: + { + if (std::memcmp(ypr, "pitch", 5) != 0) + break; + + lua.Push(instance.pitch); + return true; + } + } + + return false; + }); + + eulerAngles.SetSetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) + { + std::size_t length; + const char* ypr = lua.CheckString(2, &length); + double value = lua.CheckNumber(3); + + switch (length) + { + case 1: + { + switch (ypr[0]) + { + case 'p': + instance.pitch = value; + return true; + + case 'y': + instance.yaw = value; + return true; + + case 'r': + instance.roll = value; + return true; + } + break; + } + + case 3: + { + if (std::memcmp(ypr, "yaw", 3) != 0) + break; + + instance.yaw = value; + return true; + } + + case 4: + { + if (std::memcmp(ypr, "roll", 4) != 0) + break; + + instance.roll = value; + return true; + } + + case 5: + { + if (std::memcmp(ypr, "pitch", 5) != 0) + break; + + instance.pitch = value; + return true; + } + } + + return false; + }); + } + + /*********************************** Nz::Matrix4 **********************************/ + matrix4d.Reset("Matrix4"); + { + matrix4d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Matrix4d* matrix, std::size_t argumentCount) + { + std::size_t argCount = std::min(argumentCount, 3U); + + switch (argCount) + { + case 0: + Nz::PlacementNew(matrix, Nz::Matrix4d::Zero()); + return true; + + case 1: + if (lua.IsOfType(1, "Matrix4")) + Nz::PlacementNew(matrix, *static_cast(lua.ToUserdata(1))); + break; + + case 16: + { + double values[16]; + for (int i = 0; i < 16; ++i) + values[i] = lua.CheckNumber(i); + + Nz::PlacementNew(matrix, values); + + return true; + } + } + + lua.Error("No matching overload for constructor"); + return false; + }); + + matrix4d.BindMethod("ApplyRotation", &Nz::Matrix4d::ApplyRotation); + matrix4d.BindMethod("ApplyScale", &Nz::Matrix4d::ApplyScale); + matrix4d.BindMethod("ApplyTranslation", &Nz::Matrix4d::ApplyTranslation); + + matrix4d.BindMethod("Concatenate", &Nz::Matrix4d::Concatenate); + matrix4d.BindMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine); + + //matrix4d.BindMethod("GetColumn", &Nz::Matrix4d::GetColumn); + matrix4d.BindMethod("GetDeterminant", &Nz::Matrix4d::GetDeterminant); + matrix4d.BindMethod("GetDeterminantAffine", &Nz::Matrix4d::GetDeterminantAffine); + + matrix4d.BindMethod("GetInverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + Nz::Matrix4d result; + if (instance.GetInverse(&result)) + return lua.Push(true, result); + else + return lua.Push(false); + }); + + matrix4d.BindMethod("GetInverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + Nz::Matrix4d result; + if (instance.GetInverseAffine(&result)) + return lua.Push(true, result); + else + return lua.Push(false); + }); + + matrix4d.BindMethod("GetRotation", &Nz::Matrix4d::GetRotation); + + //matrix4d.BindMethod("GetRow", &Nz::Matrix4d::GetRow); + matrix4d.BindMethod("GetScale", &Nz::Matrix4d::GetScale); + matrix4d.BindMethod("GetSquaredScale", &Nz::Matrix4d::GetSquaredScale); + matrix4d.BindMethod("GetTranslation", &Nz::Matrix4d::GetTranslation); + + matrix4d.BindMethod("GetTransposed", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + Nz::Matrix4d result; + instance.GetTransposed(&result); + + return lua.Push(result); + }); + + matrix4d.BindMethod("HasNegativeScale", &Nz::Matrix4d::HasNegativeScale); + matrix4d.BindMethod("HasScale", &Nz::Matrix4d::HasScale); + + matrix4d.BindMethod("Inverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + bool succeeded; + instance.Inverse(&succeeded); + + return lua.Push(succeeded); + }); + + matrix4d.BindMethod("InverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + bool succeeded; + instance.InverseAffine(&succeeded); + + return lua.Push(succeeded); + }); + + matrix4d.BindMethod("IsAffine", &Nz::Matrix4d::IsAffine); + matrix4d.BindMethod("IsIdentity", &Nz::Matrix4d::IsIdentity); + + matrix4d.BindMethod("MakeIdentity", &Nz::Matrix4d::MakeIdentity); + matrix4d.BindMethod("MakeLookAt", &Nz::Matrix4d::MakeLookAt, Nz::Vector3d::Up()); + matrix4d.BindMethod("MakeOrtho", &Nz::Matrix4d::MakeOrtho, -1.0, 1.0); + matrix4d.BindMethod("MakePerspective", &Nz::Matrix4d::MakePerspective); + matrix4d.BindMethod("MakeRotation", &Nz::Matrix4d::MakeRotation); + matrix4d.BindMethod("MakeScale", &Nz::Matrix4d::MakeScale); + matrix4d.BindMethod("MakeTranslation", &Nz::Matrix4d::MakeTranslation); + matrix4d.BindMethod("MakeTransform", (Nz::Matrix4d&(Nz::Matrix4d::*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::MakeTransform, Nz::Vector3d::Unit()); + matrix4d.BindMethod("MakeViewMatrix", &Nz::Matrix4d::MakeViewMatrix); + matrix4d.BindMethod("MakeZero", &Nz::Matrix4d::MakeZero); + + matrix4d.BindMethod("Set", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t argumentCount) -> int + { + std::size_t argCount = std::min(argumentCount, 3U); + + int argIndex = 2; + switch (argCount) + { + case 1: + if (lua.IsOfType(argIndex, "Matrix4")) + instance.Set(*static_cast(lua.ToUserdata(argIndex))); + break; + + case 16: + { + double values[16]; + for (std::size_t i = 0; i < 16; ++i) + values[i] = lua.CheckNumber(argIndex++); + + instance.Set(values); + + return 0; + } + } + + lua.Error("No matching overload for method Set"); + return 0; + }); + + matrix4d.BindMethod("SetRotation", &Nz::Matrix4d::SetRotation); + matrix4d.BindMethod("SetScale", &Nz::Matrix4d::SetScale); + matrix4d.BindMethod("SetTranslation", &Nz::Matrix4d::SetTranslation); + + matrix4d.BindMethod("Transform", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int + { + int argIndex = 2; + if (lua.IsOfType(argIndex, "Vector2")) + { + double z(lua.CheckNumber(argIndex + 1, 0.0)); + double w(lua.CheckNumber(argIndex + 2, 1.0)); + + return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(argIndex)), z, w)); + } + else if (lua.IsOfType(argIndex, "Vector3")) + { + double w(lua.CheckNumber(argIndex + 1, 1.0)); + + return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(argIndex)), w)); + } + //else if (lua.IsOfType(2, "Vector4")) + // return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(1)))); + + lua.Error("No matching overload for method Transform"); + return 0; + }); + + matrix4d.BindMethod("Transpose", &Nz::Matrix4d::Transpose); + + matrix4d.BindMethod("__tostring", &Nz::Matrix4d::ToString); + + matrix4d.BindStaticMethod("Concatenate", &Nz::Matrix4d::Concatenate); + matrix4d.BindStaticMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine); + matrix4d.BindStaticMethod("Identity", &Nz::Matrix4d::Identity); + matrix4d.BindStaticMethod("LookAt", &Nz::Matrix4d::LookAt, Nz::Vector3d::Up()); + matrix4d.BindStaticMethod("Ortho", &Nz::Matrix4d::Ortho, -1.0, 1.0); + matrix4d.BindStaticMethod("Perspective", &Nz::Matrix4d::Perspective); + matrix4d.BindStaticMethod("Rotate", &Nz::Matrix4d::Rotate); + matrix4d.BindStaticMethod("Scale", &Nz::Matrix4d::Scale); + matrix4d.BindStaticMethod("Translate", &Nz::Matrix4d::Translate); + matrix4d.BindStaticMethod("Transform", (Nz::Matrix4d(*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::Transform, Nz::Vector3d::Unit()); + matrix4d.BindStaticMethod("ViewMatrix", &Nz::Matrix4d::ViewMatrix); + matrix4d.BindStaticMethod("Zero", &Nz::Matrix4d::Zero); + + matrix4d.SetGetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance) + { + bool succeeded = false; + std::size_t index = static_cast(lua.ToInteger(2, &succeeded)); + if (!succeeded || index < 1 || index > 16) + return false; + + lua.Push(instance[index - 1]); + return true; + }); + + matrix4d.SetSetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance) + { + bool succeeded = false; + std::size_t index = static_cast(lua.ToInteger(2, &succeeded)); + if (!succeeded || index < 1 || index > 16) + return false; + + instance[index - 1] = lua.CheckNumber(3); + + return true; + }); + } + + /*********************************** Nz::Rect **********************************/ + rect.Reset("Rect"); + { + rect.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* instance, std::size_t argumentCount) + { + std::size_t argCount = std::min(argumentCount, 4U); + + switch (argCount) + { + case 0: + case 4: + PlacementNew(instance, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0), lua.CheckNumber(4, 0.0)); + return true; + + case 1: + { + if (lua.IsOfType(1, "Rect")) + PlacementNew(instance, *static_cast(lua.ToUserdata(1))); + else if (lua.IsOfType(1, Nz::LuaType_Table)) + { + // TODO => Faire sans avoir à mettre de nom dans la table et prendre les éléments un à un pour créer le Rectd + PlacementNew(instance, lua.CheckField("x", 1), + lua.CheckField("y", 1), + lua.CheckField("width", 1), + lua.CheckField("height", 1)); + } + else if (lua.IsOfType(1, "Vector2")) + PlacementNew(instance, *static_cast(lua.ToUserdata(1))); + else + break; + + return true; + } + + case 2: + { + if (lua.IsOfType(1, Nz::LuaType_Number) && lua.IsOfType(2, Nz::LuaType_Number)) + PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2)); + else if (lua.IsOfType(1, "Vector2") && lua.IsOfType(2, "Vector2")) + PlacementNew(instance, *static_cast(lua.ToUserdata(1)), *static_cast(lua.ToUserdata(2))); + else + break; + + return true; + } + } + + lua.Error("No matching overload for Rect constructor"); + return false; + }); + + rect.BindMethod("__tostring", &Nz::Rectd::ToString); + + rect.SetGetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) + { + switch (lua.GetType(2)) + { + case Nz::LuaType_Number: + { + auto index = lua.CheckBoundInteger(2); + if (index < 1 || index > 4) + return false; + + lua.Push(instance[index - 1]); + return true; + } + + case Nz::LuaType_String: + { + std::size_t length; + const char* xywh = lua.CheckString(2, &length); + + if (length != 1) + break; + + switch (xywh[0]) + { + case 'x': + lua.Push(instance.x); + return true; + + case 'y': + lua.Push(instance.y); + return true; + + case 'w': + lua.Push(instance.width); + return true; + + case 'h': + lua.Push(instance.height); + return true; + + default: + break; + } + break; + } + + default: + break; + } + + return false; + }); + + rect.SetSetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) + { + switch (lua.GetType(2)) + { + case Nz::LuaType_Number: + { + auto index = lua.CheckBoundInteger(2); + if (index < 1 || index > 4) + return false; + + instance[index - 1] = lua.CheckNumber(2); + return true; + } + + case Nz::LuaType_String: + { + std::size_t length; + const char* xywh = lua.CheckString(2, &length); + + if (length != 1) + break; + + double value = lua.CheckNumber(3); + + switch (xywh[0]) + { + case 'x': + instance.x = value; + return true; + + case 'y': + instance.y = value; + return true; + + case 'w': + instance.width = value; + return true; + + case 'h': + instance.height = value; + return true; + } + break; + } + + default: + break; + } + + return false; + }); + } + + /*********************************** Nz::Quaternion **********************************/ + quaternion.Reset("Quaternion"); + { + quaternion.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* instance, std::size_t argumentCount) + { + std::size_t argCount = std::min(argumentCount, 4U); + + switch (argCount) + { + case 0: + Nz::PlacementNew(instance, Nz::Quaterniond::Zero()); + return true; + + case 1: + { + if (lua.IsOfType(1, "EulerAngles")) + Nz::PlacementNew(instance, *static_cast(lua.ToUserdata(1))); + else if (lua.IsOfType(1, "Quaternion")) + Nz::PlacementNew(instance, *static_cast(lua.ToUserdata(1))); + else + break; + + return true; + } + + case 2: + Nz::PlacementNew(instance, lua.CheckNumber(1), *static_cast(lua.CheckUserdata(2, "Vector3"))); + return true; + + case 4: + Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3), lua.CheckNumber(4)); + return true; + + default: + break; + } + + lua.Error("No matching overload for Quaternion constructor"); + return false; + }); + + quaternion.BindMethod("ComputeW", &Nz::Quaterniond::ComputeW); + quaternion.BindMethod("Conjugate", &Nz::Quaterniond::Conjugate); + quaternion.BindMethod("DotProduct", &Nz::Quaterniond::DotProduct); + quaternion.BindMethod("GetConjugate", &Nz::Quaterniond::GetConjugate); + quaternion.BindMethod("GetInverse", &Nz::Quaterniond::GetInverse); + + quaternion.BindMethod("Inverse", &Nz::Quaterniond::Inverse); + quaternion.BindMethod("Magnitude", &Nz::Quaterniond::Magnitude); + + quaternion.BindMethod("SquaredMagnitude", &Nz::Quaterniond::SquaredMagnitude); + quaternion.BindMethod("ToEulerAngles", &Nz::Quaterniond::ToEulerAngles); + + quaternion.BindMethod("__tostring", &Nz::Quaterniond::ToString); + + quaternion.BindStaticMethod("Lerp", &Nz::Quaterniond::Lerp); + quaternion.BindStaticMethod("RotationBetween", &Nz::Quaterniond::RotationBetween); + quaternion.BindStaticMethod("Slerp", &Nz::Quaterniond::Slerp); + + quaternion.BindMethod("GetNormal", [] (Nz::LuaInstance& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int + { + double length; + + lua.Push(instance.GetNormal(&length)); + lua.Push(length); + + return 2; + }); + + quaternion.BindMethod("Normalize", [] (Nz::LuaInstance& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int + { + double length; + + instance.Normalize(&length); + lua.Push(1); //< instance + lua.Push(length); + + return 2; + }); + + quaternion.BindStaticMethod("Normalize", [] (Nz::LuaInstance& instance) -> int + { + int argIndex = 1; + Nz::Quaterniond quat = instance.Check(&argIndex); + + double length; + + instance.Push(Nz::Quaterniond::Normalize(quat, &length)); + instance.Push(length); + + return 2; + }); + + quaternion.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) + { + std::size_t length; + const char* wxyz = lua.CheckString(2, &length); + + if (length != 1) + return false; + + switch (wxyz[0]) + { + case 'w': + lua.Push(instance.w); + return true; + + case 'x': + lua.Push(instance.x); + return true; + + case 'y': + lua.Push(instance.y); + return true; + + case 'z': + lua.Push(instance.z); + return true; + } + + return false; + }); + + quaternion.SetSetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) + { + std::size_t length; + const char* wxyz = lua.CheckString(2, &length); + + if (length != 1) + return false; + + double value = lua.CheckNumber(3); + + switch (wxyz[0]) + { + case 'w': + instance.w = value; + return true; + + case 'x': + instance.x = value; + return true; + + case 'y': + instance.y = value; + return true; + + case 'z': + instance.z = value; + return true; + + default: + break; + } + + return false; + }); + } + + /*********************************** Nz::Vector2 **********************************/ + vector2d.Reset("Vector2"); + { + vector2d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector2d* vector, std::size_t argumentCount) + { + std::size_t argCount = std::min(argumentCount, 2U); + + switch (argCount) + { + case 0: + case 2: + Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0)); + return true; + + case 1: + { + if (lua.IsOfType(1, Nz::LuaType_Number)) + Nz::PlacementNew(vector, lua.CheckNumber(1)); + else if (lua.IsOfType(1, "Vector2")) + Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1))); + else + break; + + return true; + } + } + + lua.Error("No matching overload for Vector2 constructor"); + return false; + }); + + vector2d.BindMethod("__tostring", &Nz::Vector2d::ToString); + + vector2d.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector2d& instance) + { + switch (lua.GetType(2)) + { + case Nz::LuaType_Number: + { + long long index = lua.CheckInteger(2); + if (index < 1 || index > 2) + return false; + + lua.Push(instance[index - 1]); + return true; + } + + case Nz::LuaType_String: + { + std::size_t length; + const char* xy = lua.CheckString(2, &length); + + if (length != 1) + break; + + switch (xy[0]) + { + case 'x': + lua.Push(instance.x); + return true; + + case 'y': + lua.Push(instance.y); + return true; + + default: + break; + } + break; + } + + default: + break; + } + + return false; + }); + + vector2d.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector2d& instance) + { + switch (lua.GetType(2)) + { + case Nz::LuaType_Number: + { + long long index = lua.CheckInteger(2); + if (index < 1 || index > 2) + return false; + + instance[index - 1] = lua.CheckNumber(3); + return true; + } + + case Nz::LuaType_String: + { + std::size_t length; + const char* xy = lua.CheckString(2, &length); + + if (length != 1) + break; + + double value = lua.CheckNumber(3); + + switch (xy[0]) + { + case 'x': + instance.x = value; + return true; + + case 'y': + instance.y = value; + return true; + + default: + break; + } + break; + } + + default: + break; + } + + return false; + }); + } + + /*********************************** Nz::Vector3 **********************************/ + vector3d.Reset("Vector3"); + { + vector3d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector3d* vector, std::size_t argumentCount) + { + std::size_t argCount = std::min(argumentCount, 3U); + + switch (argCount) + { + case 0: + case 3: + Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0)); + return true; + + case 1: + { + if (lua.IsOfType(1, Nz::LuaType_Number)) + Nz::PlacementNew(vector, lua.CheckNumber(1)); + else if (lua.IsOfType(1, "Vector2")) + Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1))); + else if (lua.IsOfType(1, "Vector3")) + Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1))); + else + break; + + return true; + } + + case 2: + { + if (lua.IsOfType(1, Nz::LuaType_Number)) + Nz::PlacementNew(vector, lua.CheckNumber(1), *static_cast(lua.CheckUserdata(2, "Vector2"))); + else if (lua.IsOfType(1, "Vector2")) + Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1)), lua.CheckNumber(2)); + else + break; + + return true; + } + } + + lua.Error("No matching overload for constructor"); + return false; + }); + + vector3d.BindMethod("__tostring", &Nz::Vector3d::ToString); + + vector3d.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) + { + switch (lua.GetType(2)) + { + case Nz::LuaType_Number: + { + long long index = lua.CheckInteger(2); + if (index < 1 || index > 3) + return false; + + lua.Push(instance[index - 1]); + return true; + } + + case Nz::LuaType_String: + { + std::size_t length; + const char* xyz = lua.CheckString(2, &length); + + if (length != 1) + break; + + switch (xyz[0]) + { + case 'x': + lua.Push(instance.x); + return true; + + case 'y': + lua.Push(instance.y); + return true; + + case 'z': + lua.Push(instance.z); + return true; + + default: + break; + } + break; + } + + default: + break; + } + + return false; + }); + + vector3d.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) + { + switch (lua.GetType(2)) + { + case Nz::LuaType_Number: + { + long long index = lua.CheckInteger(2); + if (index < 1 || index > 3) + return false; + + instance[index - 1] = lua.CheckNumber(3); + return true; + } + + case Nz::LuaType_String: + { + std::size_t length; + const char* xyz = lua.CheckString(2, &length); + + if (length != 1) + break; + + double value = lua.CheckNumber(3); + + switch (xyz[0]) + { + case 'x': + instance.x = value; + return true; + + case 'y': + instance.y = value; + return true; + + case 'z': + instance.z = value; + return true; + + default: + break; + } + break; + } + + default: + break; + } + + return false; + }); + } + } + + /*! + * \brief Registers the classes that will be used by the Lua instance + * + * \param instance Lua instance that will interact with the Math classes + */ + void LuaBinding_Math::Register(Nz::LuaInstance& instance) + { + eulerAngles.Register(instance); + matrix4d.Register(instance); + quaternion.Register(instance); + rect.Register(instance); + vector2d.Register(instance); + vector3d.Register(instance); + + quaternion.PushGlobalTable(instance); + { + instance.PushField("Identity", Nz::Quaterniond::Identity()); + instance.PushField("Zero", Nz::Quaterniond::Zero()); + } + instance.Pop(); + } +} diff --git a/SDK/src/NDK/LuaBinding_Network.cpp b/SDK/src/NDK/Lua/LuaBinding_Network.cpp similarity index 55% rename from SDK/src/NDK/LuaBinding_Network.cpp rename to SDK/src/NDK/Lua/LuaBinding_Network.cpp index bd1105962..d6f92cb40 100644 --- a/SDK/src/NDK/LuaBinding_Network.cpp +++ b/SDK/src/NDK/Lua/LuaBinding_Network.cpp @@ -1,139 +1,147 @@ // This file was automatically generated on 26 May 2014 at 01:05:31 -#include +#include #include namespace Ndk { - /*! - * \brief Binds Network module to Lua - */ + std::unique_ptr LuaBinding_Base::BindNetwork(LuaBinding& binding) + { + return std::make_unique(binding); + } - void LuaBinding::BindNetwork() + LuaBinding_Network::LuaBinding_Network(LuaBinding& binding) : + LuaBinding_Base(binding) { /*********************************** Nz::AbstractSocket **********************************/ - abstractSocket.BindMethod("Close", &Nz::AbstractSocket::Close); - abstractSocket.BindMethod("EnableBlocking", &Nz::AbstractSocket::EnableBlocking); - abstractSocket.BindMethod("GetLastError", &Nz::AbstractSocket::GetLastError); - abstractSocket.BindMethod("GetState", &Nz::AbstractSocket::GetState); - abstractSocket.BindMethod("GetType", &Nz::AbstractSocket::GetType); - abstractSocket.BindMethod("IsBlockingEnabled", &Nz::AbstractSocket::IsBlockingEnabled); - abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes); + abstractSocket.Reset("AbstractSocket"); + { + abstractSocket.BindMethod("Close", &Nz::AbstractSocket::Close); + abstractSocket.BindMethod("EnableBlocking", &Nz::AbstractSocket::EnableBlocking); + abstractSocket.BindMethod("GetLastError", &Nz::AbstractSocket::GetLastError); + abstractSocket.BindMethod("GetState", &Nz::AbstractSocket::GetState); + abstractSocket.BindMethod("GetType", &Nz::AbstractSocket::GetType); + abstractSocket.BindMethod("IsBlockingEnabled", &Nz::AbstractSocket::IsBlockingEnabled); + abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes); + } /*********************************** Nz::IpAddress **********************************/ - ipAddress.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* address, std::size_t argumentCount) + ipAddress.Reset("IpAddress"); { - std::size_t argCount = std::min(argumentCount, 9U); - - int argIndex = 2; - switch (argCount) + ipAddress.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* instance, std::size_t argumentCount) { - case 0: - Nz::PlacementNew(address); - return true; + std::size_t argCount = std::min(argumentCount, 9U); - case 1: - Nz::PlacementNew(address, lua.CheckString(argIndex)); - return true; - - case 4: - case 5: + int argIndex = 2; + switch (argCount) { - Nz::UInt8 a = lua.Check(&argIndex); - Nz::UInt8 b = lua.Check(&argIndex); - Nz::UInt8 c = lua.Check(&argIndex); - Nz::UInt8 d = lua.Check(&argIndex); - Nz::UInt16 port = lua.Check(&argIndex, 0); + case 0: + Nz::PlacementNew(instance); + return true; - Nz::PlacementNew(address, a, b, c, d, port); - return true; + case 1: + Nz::PlacementNew(instance, lua.CheckString(argIndex)); + return true; + + case 4: + case 5: + { + Nz::UInt8 a = lua.Check(&argIndex); + Nz::UInt8 b = lua.Check(&argIndex); + Nz::UInt8 c = lua.Check(&argIndex); + Nz::UInt8 d = lua.Check(&argIndex); + Nz::UInt16 port = lua.Check(&argIndex, 0); + + Nz::PlacementNew(instance, a, b, c, d, port); + return true; + } + + case 8: + case 9: + { + Nz::UInt16 a = lua.Check(&argIndex); + Nz::UInt16 b = lua.Check(&argIndex); + Nz::UInt16 c = lua.Check(&argIndex); + Nz::UInt16 d = lua.Check(&argIndex); + Nz::UInt16 e = lua.Check(&argIndex); + Nz::UInt16 f = lua.Check(&argIndex); + Nz::UInt16 g = lua.Check(&argIndex); + Nz::UInt16 h = lua.Check(&argIndex); + Nz::UInt16 port = lua.Check(&argIndex, 0); + + Nz::PlacementNew(instance, a, b, c, d, e, f, g, h, port); + return true; + } } - case 8: - case 9: + lua.Error("No matching overload for constructor"); + return false; + }); + + ipAddress.BindMethod("GetPort", &Nz::IpAddress::GetPort); + ipAddress.BindMethod("GetProtocol", &Nz::IpAddress::GetProtocol); + ipAddress.BindMethod("IsLoopback", &Nz::IpAddress::IsLoopback); + ipAddress.BindMethod("IsValid", &Nz::IpAddress::IsValid); + ipAddress.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32); + ipAddress.BindMethod("__tostring", &Nz::IpAddress::ToString); + + ipAddress.BindStaticMethod("ResolveAddress", [] (Nz::LuaInstance& instance) -> int + { + Nz::String service; + Nz::ResolveError error = Nz::ResolveError_Unknown; + + int argIndex = 2; + Nz::String hostName = Nz::IpAddress::ResolveAddress(instance.Check(&argIndex), &service, &error); + + if (error == Nz::ResolveError_NoError) { - Nz::UInt16 a = lua.Check(&argIndex); - Nz::UInt16 b = lua.Check(&argIndex); - Nz::UInt16 c = lua.Check(&argIndex); - Nz::UInt16 d = lua.Check(&argIndex); - Nz::UInt16 e = lua.Check(&argIndex); - Nz::UInt16 f = lua.Check(&argIndex); - Nz::UInt16 g = lua.Check(&argIndex); - Nz::UInt16 h = lua.Check(&argIndex); - Nz::UInt16 port = lua.Check(&argIndex, 0); - - Nz::PlacementNew(address, a, b, c, d, e, f, g, h, port); - return true; + instance.Push(hostName); + instance.Push(service); + return 2; } - } - - lua.Error("No matching overload for constructor"); - return false; - }); - - ipAddress.BindMethod("GetPort", &Nz::IpAddress::GetPort); - ipAddress.BindMethod("GetProtocol", &Nz::IpAddress::GetProtocol); - ipAddress.BindMethod("IsLoopback", &Nz::IpAddress::IsLoopback); - ipAddress.BindMethod("IsValid", &Nz::IpAddress::IsValid); - ipAddress.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32); - ipAddress.BindMethod("__tostring", &Nz::IpAddress::ToString); - - ipAddress.BindStaticMethod("ResolveAddress", [] (Nz::LuaInstance& instance) -> int - { - Nz::String service; - Nz::ResolveError error = Nz::ResolveError_Unknown; - - int argIndex = 2; - Nz::String hostName = Nz::IpAddress::ResolveAddress(instance.Check(&argIndex), &service, &error); - - if (error == Nz::ResolveError_NoError) - { - instance.Push(hostName); - instance.Push(service); - return 2; - } - else - { - instance.PushBoolean(false); - instance.Push(error); - return 2; - } - }); - - ipAddress.BindStaticMethod("ResolveHostname", [] (Nz::LuaInstance& instance) -> int - { - Nz::ResolveError error = Nz::ResolveError_Unknown; - - int argIndex = 2; - Nz::NetProtocol protocol = instance.Check(&argIndex); - Nz::String hostname = instance.Check(&argIndex); - Nz::String service = instance.Check(&argIndex, "http"); - - std::vector addresses = Nz::IpAddress::ResolveHostname(protocol, hostname, service, &error); - if (error == Nz::ResolveError_NoError) - { - int index = 1; - instance.PushTable(addresses.size()); - for (Nz::HostnameInfo& info : addresses) + else { - instance.PushInteger(index++); - instance.PushTable(0, 4); - instance.PushField("Address", std::move(info.address)); - instance.PushField("CanonicalName", std::move(info.canonicalName)); - instance.PushField("Protocol", std::move(info.protocol)); - instance.PushField("SocketType", std::move(info.socketType)); - instance.SetTable(); + instance.PushBoolean(false); + instance.Push(error); + return 2; } + }); - return 1; - } - else + ipAddress.BindStaticMethod("ResolveHostname", [] (Nz::LuaInstance& instance) -> int { - instance.PushBoolean(false); - instance.Push(error); - return 2; - } - }); + Nz::ResolveError error = Nz::ResolveError_Unknown; + + int argIndex = 2; + Nz::NetProtocol protocol = instance.Check(&argIndex); + Nz::String hostname = instance.Check(&argIndex); + Nz::String service = instance.Check(&argIndex, "http"); + + std::vector addresses = Nz::IpAddress::ResolveHostname(protocol, hostname, service, &error); + if (error == Nz::ResolveError_NoError) + { + int index = 1; + instance.PushTable(addresses.size()); + for (Nz::HostnameInfo& info : addresses) + { + instance.PushInteger(index++); + instance.PushTable(0, 4); + instance.PushField("Address", std::move(info.address)); + instance.PushField("CanonicalName", std::move(info.canonicalName)); + instance.PushField("Protocol", std::move(info.protocol)); + instance.PushField("SocketType", std::move(info.socketType)); + instance.SetTable(); + } + + return 1; + } + else + { + instance.PushBoolean(false); + instance.Push(error); + return 2; + } + }); + } } /*! @@ -141,8 +149,7 @@ namespace Ndk * * \param instance Lua instance that will interact with the Network classes */ - - void LuaBinding::RegisterNetwork(Nz::LuaInstance& instance) + void LuaBinding_Network::Register(Nz::LuaInstance& instance) { // Classes abstractSocket.Register(instance); @@ -199,7 +206,7 @@ namespace Ndk instance.PushField("Unknown", Nz::ResolveError_Unknown); } instance.SetGlobal("ResolveError"); - + // Nz::SocketError static_assert(Nz::SocketError_Max + 1 == 15, "Nz::ResolveError has been updated but change was not reflected to Lua binding"); instance.PushTable(0, 15); diff --git a/SDK/src/NDK/Lua/LuaBinding_Renderer.cpp b/SDK/src/NDK/Lua/LuaBinding_Renderer.cpp new file mode 100644 index 000000000..7f881e20d --- /dev/null +++ b/SDK/src/NDK/Lua/LuaBinding_Renderer.cpp @@ -0,0 +1,110 @@ +// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot +// 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 +{ + std::unique_ptr LuaBinding_Base::BindRenderer(LuaBinding& binding) + { + return std::make_unique(binding); + } + + LuaBinding_Renderer::LuaBinding_Renderer(LuaBinding& binding) : + LuaBinding_Base(binding) + { + LuaBinding_Utility& utility = static_cast(*m_binding.utility); + + /*********************************** Nz::Texture ***********************************/ + texture.Reset("Texture"); + { + texture.Inherit(utility.abstractImage, [] (Nz::TextureRef* textureRef) -> Nz::AbstractImageRef* + { + return reinterpret_cast(textureRef); //TODO: Make a ObjectRefCast + }); + + texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* instance, std::size_t /*argumentCount*/) + { + Nz::PlacementNew(instance, Nz::Texture::New()); + return true; + }); + + texture.BindMethod("Create", &Nz::Texture::Create, static_cast(1), 1U); + texture.BindMethod("Destroy", &Nz::Texture::Destroy); + + //texture.BindMethod("Download", &Nz::Texture::Download); + + texture.BindMethod("EnableMipmapping", &Nz::Texture::EnableMipmapping); + texture.BindMethod("EnsureMipmapsUpdate", &Nz::Texture::EnsureMipmapsUpdate); + texture.BindMethod("HasMipmaps", &Nz::Texture::HasMipmaps); + texture.BindMethod("InvalidateMipmaps", &Nz::Texture::InvalidateMipmaps); + texture.BindMethod("IsValid", &Nz::Texture::IsValid); + + texture.BindMethod("LoadFromFile", &Nz::Texture::LoadFromFile, true, Nz::ImageParams()); + //bool LoadFromImage(const Image& image, bool generateMipmaps = true); + //bool LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams(), bool generateMipmaps = true); + //bool LoadFromStream(Stream& stream, const ImageParams& params = ImageParams(), bool generateMipmaps = true); + + texture.BindMethod("LoadArrayFromFile", &Nz::Texture::LoadArrayFromFile, Nz::Vector2ui(2, 2), true, Nz::ImageParams()); + //bool LoadArrayFromImage(const Image& image, bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); + //bool LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); + //bool LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); + + //bool LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); + //bool LoadCubemapFromImage(const Image& image, bool generateMipmaps = true, const CubemapParams& params = CubemapParams()); + //bool LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); + //bool LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); + + texture.BindMethod("LoadFaceFromFile", &Nz::Texture::LoadFaceFromFile, Nz::ImageParams()); + //bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams()); + //bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams()); + + texture.BindMethod("SaveToFile", &Nz::Texture::SaveToFile, Nz::ImageParams()); + //bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams()); + + texture.BindMethod("SetMipmapRange", &Nz::Texture::SetMipmapRange); + + texture.BindStaticMethod("IsFormatSupported", &Nz::Texture::IsFormatSupported); + texture.BindStaticMethod("IsMipmappingSupported", &Nz::Texture::IsMipmappingSupported); + texture.BindStaticMethod("IsTypeSupported", &Nz::Texture::IsTypeSupported); + } + + /*********************************** Nz::TextureLibrary ***********************************/ + textureLibrary.Reset("TextureLibrary"); + { + textureLibrary.BindStaticMethod("Get", &Nz::TextureLibrary::Get); + textureLibrary.BindStaticMethod("Has", &Nz::TextureLibrary::Has); + textureLibrary.BindStaticMethod("Register", &Nz::TextureLibrary::Register); + textureLibrary.BindStaticMethod("Query", &Nz::TextureLibrary::Query); + textureLibrary.BindStaticMethod("Unregister", &Nz::TextureLibrary::Unregister); + } + + /*********************************** Nz::TextureManager ***********************************/ + textureManager.Reset("textureManager"); + { + textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear); + textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get); + textureManager.BindStaticMethod("GetDefaultParameters", &Nz::TextureManager::GetDefaultParameters); + textureManager.BindStaticMethod("Purge", &Nz::TextureManager::Purge); + textureManager.BindStaticMethod("Register", &Nz::TextureManager::Register); + textureManager.BindStaticMethod("SetDefaultParameters", &Nz::TextureManager::SetDefaultParameters); + textureManager.BindStaticMethod("Unregister", &Nz::TextureManager::Unregister); + } + } + + /*! + * \brief Registers the classes that will be used by the Lua instance + * + * \param instance Lua instance that will interact with the Renderer classes + */ + void LuaBinding_Renderer::Register(Nz::LuaInstance& instance) + { + texture.Register(instance); + textureLibrary.Register(instance); + textureManager.Register(instance); + } +} diff --git a/SDK/src/NDK/Lua/LuaBinding_SDK.cpp b/SDK/src/NDK/Lua/LuaBinding_SDK.cpp new file mode 100644 index 000000000..ad9bb49e9 --- /dev/null +++ b/SDK/src/NDK/Lua/LuaBinding_SDK.cpp @@ -0,0 +1,338 @@ +// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot +// 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 + +#ifndef NDK_SERVER +#include +#endif + +namespace Ndk +{ + std::unique_ptr LuaBinding_Base::BindSDK(LuaBinding& binding) + { + return std::make_unique(binding); + } + + LuaBinding_SDK::LuaBinding_SDK(LuaBinding& binding) : + LuaBinding_Base(binding) + { + #ifndef NDK_SERVER + LuaBinding_Graphics& graphics = static_cast(*m_binding.graphics); + #endif + + LuaBinding_Utility& utility = static_cast(*m_binding.utility); + + /*********************************** Ndk::Application **********************************/ + application.Reset("Application"); + { + #ifndef NDK_SERVER + //application.SetMethod("AddWindow", &Application::AddWindow); + + application.BindMethod("EnableConsole", &Application::EnableConsole); + application.BindMethod("EnableFPSCounter", &Application::EnableFPSCounter); + + application.BindMethod("IsConsoleEnabled", &Application::IsConsoleEnabled); + application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled); + #endif + + application.BindMethod("AddWorld", [] (Nz::LuaInstance& lua, Application* instance, std::size_t /*argumentCount*/) -> int + { + lua.Push(instance->AddWorld().CreateHandle()); + return 1; + }); + + application.BindMethod("GetUpdateTime", &Application::GetUpdateTime); + application.BindMethod("Quit", &Application::Quit); + } + + /*********************************** Ndk::Console **********************************/ + #ifndef NDK_SERVER + console.Reset("Console"); + { + console.Inherit(utility.node, [] (ConsoleHandle* handle) -> Nz::Node* + { + return handle->GetObject(); + }); + + console.BindMethod("AddLine", &Console::AddLine, Nz::Color::White); + console.BindMethod("Clear", &Console::Clear); + console.BindMethod("GetCharacterSize", &Console::GetCharacterSize); + console.BindMethod("GetHistory", &Console::GetHistory); + console.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground); + console.BindMethod("GetInput", &Console::GetInput); + console.BindMethod("GetInputBackground", &Console::GetInputBackground); + console.BindMethod("GetSize", &Console::GetSize); + console.BindMethod("GetTextFont", &Console::GetTextFont); + + console.BindMethod("IsVisible", &Console::IsVisible); + + console.BindMethod("SendCharacter", &Console::SendCharacter); + //consoleClass.SetMethod("SendEvent", &Console::SendEvent); + + console.BindMethod("SetCharacterSize", &Console::SetCharacterSize); + console.BindMethod("SetSize", &Console::SetSize); + console.BindMethod("SetTextFont", &Console::SetTextFont); + + console.BindMethod("Show", &Console::Show, true); + } + #endif + + /*********************************** Ndk::Entity **********************************/ + entity.Reset("Entity"); + { + entity.BindMethod("Enable", &Entity::Enable, true); + entity.BindMethod("GetId", &Entity::GetId); + entity.BindMethod("GetWorld", &Entity::GetWorld); + entity.BindMethod("Kill", &Entity::Kill); + entity.BindMethod("IsEnabled", &Entity::IsEnabled); + entity.BindMethod("IsValid", &Entity::IsValid); + entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); + entity.BindMethod("__tostring", &EntityHandle::ToString); + + entity.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int + { + LuaBinding::ComponentBinding* binding = m_binding.QueryComponentIndex(instance); + + return binding->adder(instance, handle); + }); + + entity.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int + { + LuaBinding::ComponentBinding* binding = m_binding.QueryComponentIndex(instance); + + return binding->getter(instance, handle->GetComponent(binding->index)); + }); + + entity.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int + { + LuaBinding::ComponentBinding* binding = m_binding.QueryComponentIndex(instance); + + handle->RemoveComponent(binding->index); + return 0; + }); + } + + /*********************************** Ndk::NodeComponent **********************************/ + nodeComponent.Reset("NodeComponent"); + { + nodeComponent.Inherit(utility.node, [] (NodeComponentHandle* handle) -> Nz::Node* + { + return handle->GetObject(); + }); + } + + /*********************************** Ndk::VelocityComponent **********************************/ + velocityComponent.Reset("VelocityComponent"); + { + velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) + { + std::size_t length; + const char* member = lua.CheckString(2, &length); + + if (std::strcmp(member, "Linear") == 0) + { + lua.Push(instance->linearVelocity); + return true; + } + + return false; + }); + + velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) + { + std::size_t length; + const char* member = lua.CheckString(2, &length); + + int argIndex = 3; + if (std::strcmp(member, "Linear") == 0) + { + instance->linearVelocity = lua.Check(&argIndex); + return true; + } + + return false; + }); + } + + /*********************************** Ndk::World **********************************/ + world.Reset("World"); + { + world.BindMethod("CreateEntity", &World::CreateEntity); + world.BindMethod("CreateEntities", &World::CreateEntities); + world.BindMethod("Clear", &World::Clear); + } + + #ifndef NDK_SERVER + /*********************************** Ndk::CameraComponent **********************************/ + cameraComponent.Reset("CameraComponent"); + { + cameraComponent.Inherit(graphics.abstractViewer, [] (CameraComponentHandle* handle) -> Nz::AbstractViewer* + { + return handle->GetObject(); + }); + + cameraComponent.BindMethod("GetFOV", &Ndk::CameraComponent::GetFOV); + cameraComponent.BindMethod("GetLayer", &Ndk::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); + } + + /*********************************** Ndk::GraphicsComponent **********************************/ + graphicsComponent.Reset("GraphicsComponent"); + { + graphicsComponent.BindMethod("Attach", [] (Nz::LuaInstance& lua, Ndk::GraphicsComponent* instance, std::size_t argumentCount) -> int + { + /* + void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0); + void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0); + */ + + std::size_t argCount = std::min(argumentCount, 3U); + + switch (argCount) + { + case 1: + { + int argIndex = 2; + instance->Attach(lua.Check(&argIndex)); + return 0; + } + + case 2: + { + int argIndex = 2; + Nz::InstancedRenderableRef renderable = lua.Check(&argIndex); + + if (lua.IsOfType(argIndex, Nz::LuaType_Number)) + { + int renderOrder = lua.Check(&argIndex); + + instance->Attach(renderable, renderOrder); + } + else if (lua.IsOfType(argIndex, "Matrix4")) + { + Nz::Matrix4f localMatrix = lua.Check(&argIndex); + + instance->Attach(renderable, localMatrix); + } + else + break; + + return 0; + } + + case 3: + { + int argIndex = 2; + Nz::InstancedRenderableRef renderable = lua.Check(&argIndex); + Nz::Matrix4f localMatrix = lua.Check(&argIndex); + int renderOrder = lua.Check(&argIndex); + + instance->Attach(renderable, localMatrix, renderOrder); + return 0; + } + } + + lua.Error("No matching overload for method GetMemoryUsage"); + return 0; + }); + } + #endif + + // Components functions + m_binding.BindComponent("Node"); + m_binding.BindComponent("Velocity"); + + #ifndef NDK_SERVER + m_binding.BindComponent("Camera"); + m_binding.BindComponent("Graphics"); + #endif + } + + /*! + * \brief Registers the classes that will be used by the Lua instance + * + * \param instance Lua instance that will interact with the SDK classes + */ + void LuaBinding_SDK::Register(Nz::LuaInstance& instance) + { + // Classes + application.Register(instance); + entity.Register(instance); + nodeComponent.Register(instance); + velocityComponent.Register(instance); + world.Register(instance); + + #ifndef NDK_SERVER + cameraComponent.Register(instance); + console.Register(instance); + graphicsComponent.Register(instance); + #endif + + // Enums + } + + /*! + * \brief Gets the index of the component + * \return A pointer to the binding linked to a component + * + * \param instance Lua instance that will interact with the component + * \param argIndex Index of the component + */ + LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex) + { + switch (instance.GetType(argIndex)) + { + case Nz::LuaType_Number: + { + ComponentIndex componentIndex = instance.Check(&argIndex); + if (componentIndex > m_componentBinding.size()) + { + instance.Error("Invalid component index"); + return nullptr; + } + + ComponentBinding& binding = m_componentBinding[componentIndex]; + if (binding.name.IsEmpty()) + { + instance.Error("Invalid component index"); + return nullptr; + } + + return &binding; + } + + case Nz::LuaType_String: + { + const char* key = instance.CheckString(argIndex); + auto it = m_componentBindingByName.find(key); + if (it == m_componentBindingByName.end()) + { + instance.Error("Invalid component name"); + return nullptr; + } + + return &m_componentBinding[it->second]; + } + + default: + break; + } + + instance.Error("Invalid component index at #" + Nz::String::Number(argIndex)); + return nullptr; + } +} diff --git a/SDK/src/NDK/Lua/LuaBinding_Utility.cpp b/SDK/src/NDK/Lua/LuaBinding_Utility.cpp new file mode 100644 index 000000000..173d6c3c5 --- /dev/null +++ b/SDK/src/NDK/Lua/LuaBinding_Utility.cpp @@ -0,0 +1,446 @@ +// 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::BindUtility(LuaBinding& binding) + { + return std::make_unique(binding); + } + + LuaBinding_Utility::LuaBinding_Utility(LuaBinding& binding) : + LuaBinding_Base(binding) + { + /*********************************** Nz::AbstractImage **********************************/ + abstractImage.Reset("AbstractImage"); + { + abstractImage.BindMethod("GetBytesPerPixel", &Nz::AbstractImage::GetBytesPerPixel); + abstractImage.BindMethod("GetDepth", &Nz::AbstractImage::GetDepth, static_cast(0)); + abstractImage.BindMethod("GetFormat", &Nz::AbstractImage::GetFormat); + abstractImage.BindMethod("GetHeight", &Nz::AbstractImage::GetHeight, static_cast(0)); + abstractImage.BindMethod("GetLevelCount", &Nz::AbstractImage::GetLevelCount); + abstractImage.BindMethod("GetMaxLevel", &Nz::AbstractImage::GetMaxLevel); + abstractImage.BindMethod("GetSize", &Nz::AbstractImage::GetSize, static_cast(0)); + abstractImage.BindMethod("GetType", &Nz::AbstractImage::GetType); + abstractImage.BindMethod("GetWidth", &Nz::AbstractImage::GetWidth, static_cast(0)); + abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed); + abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap); + + abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int + { + std::size_t argCount = std::min(argumentCount, 1U); + switch (argCount) + { + case 0: + return lua.Push(instance->GetMemoryUsage()); + + case 1: + { + int argIndex = 2; + Nz::UInt8 level(lua.Check(&argIndex)); + + return lua.Push(instance->GetMemoryUsage(level)); + } + } + + lua.Error("No matching overload for method GetMemoryUsage"); + return 0; + }); + + abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int + { + std::size_t argCount = std::min(argumentCount, 6U); + int argIndex = 2; + + std::size_t bufferSize = 0; + const Nz::UInt8* pixels = reinterpret_cast(lua.CheckString(argIndex++, &bufferSize)); + + if (argCount < 2 || lua.IsOfType(2, Nz::LuaType_Number)) + { + // bool Update(const UInt8* pixels, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) + unsigned int srcWidth = lua.Check(&argIndex, 0); + unsigned int srcHeight = lua.Check(&argIndex, 0); + Nz::UInt8 level = lua.Check(&argIndex, 0); + + ///TODO: Buffer checks (Nz::ByteBufferView ?) + return lua.Push(instance->Update(pixels, srcWidth, srcHeight, level)); + } + /* Disabled until Box and Rect have been ported + else if (lua.IsOfType(2, "Box")) + { + // bool Update(const UInt8* pixels, const Boxui& box, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) + Nz::Boxui box = lua.Check(&argIndex); + unsigned int srcWidth = lua.Check(&argIndex, 0); + unsigned int srcHeight = lua.Check(&argIndex, 0); + Nz::UInt8 level = lua.Check(&argIndex, 0); + + ///TODO: Buffer checks (Nz::ByteBufferView ?) + return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level)); + } + else if (lua.IsOfType(2, "Rect")) + { + // bool Update(const UInt8* pixels, const Rectui& rect, unsigned int z = 0, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) + Nz::Rectui box = lua.Check(&argIndex); + unsigned int srcWidth = lua.Check(&argIndex, 0); + unsigned int srcHeight = lua.Check(&argIndex, 0); + Nz::UInt8 level = lua.Check(&argIndex, 0); + + ///TODO: Buffer checks (Nz::ByteBufferView ?) + return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level)); + }*/ + + lua.Error("No matching overload for method Update"); + return 0; + }); + } + + /*********************************** Nz::Font **********************************/ + font.Reset("Font"); + { + font.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::FontRef* instance, std::size_t /*argumentCount*/) + { + Nz::PlacementNew(instance, Nz::Font::New()); + return true; + }); + + font.BindMethod("ClearGlyphCache", &Nz::Font::ClearGlyphCache); + font.BindMethod("ClearKerningCache", &Nz::Font::ClearKerningCache); + font.BindMethod("ClearSizeInfoCache", &Nz::Font::ClearSizeInfoCache); + + font.BindMethod("Destroy", &Nz::Font::Destroy); + + font.BindMethod("GetCachedGlyphCount", [] (Nz::LuaInstance& lua, Nz::FontRef& instance, std::size_t argumentCount) -> int + { + std::size_t argCount = std::min(argumentCount, 2U); + + int argIndex = 2; + switch (argCount) + { + case 0: + lua.Push(instance->GetCachedGlyphCount()); + return 1; + + case 2: + { + unsigned int characterSize = lua.Check(&argIndex); + Nz::UInt32 style = lua.Check(&argIndex); + + lua.Push(instance->GetCachedGlyphCount(characterSize, style)); + return 1; + } + } + + lua.Error("No matching overload for method GetCachedGlyphCount"); + return 0; + }); + + font.BindMethod("GetFamilyName", &Nz::Font::GetFamilyName); + font.BindMethod("GetKerning", &Nz::Font::GetKerning); + font.BindMethod("GetGlyphBorder", &Nz::Font::GetGlyphBorder); + font.BindMethod("GetMinimumStepSize", &Nz::Font::GetMinimumStepSize); + font.BindMethod("GetSizeInfo", &Nz::Font::GetSizeInfo); + font.BindMethod("GetStyleName", &Nz::Font::GetStyleName); + + font.BindMethod("IsValid", &Nz::Font::IsValid); + + font.BindMethod("Precache", (bool(Nz::Font::*)(unsigned int, Nz::UInt32, const Nz::String&) const) &Nz::Font::Precache); + + font.BindMethod("OpenFromFile", &Nz::Font::OpenFromFile, Nz::FontParams()); + + font.BindMethod("SetGlyphBorder", &Nz::Font::SetGlyphBorder); + font.BindMethod("SetMinimumStepSize", &Nz::Font::SetMinimumStepSize); + + font.BindStaticMethod("GetDefault", &Nz::Font::GetDefault); + font.BindStaticMethod("GetDefaultGlyphBorder", &Nz::Font::GetDefaultGlyphBorder); + font.BindStaticMethod("GetDefaultMinimumStepSize", &Nz::Font::GetDefaultMinimumStepSize); + + font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder); + 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"); + { + node.BindMethod("GetBackward", &Nz::Node::GetBackward); + //nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds); + node.BindMethod("GetDown", &Nz::Node::GetDown); + node.BindMethod("GetForward", &Nz::Node::GetForward); + node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); + node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); + node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); + node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); + //nodeClass.SetMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); + node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); + node.BindMethod("GetLeft", &Nz::Node::GetLeft); + node.BindMethod("GetNodeType", &Nz::Node::GetNodeType); + //nodeClass.SetMethod("GetParent", &Nz::Node::GetParent); + node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); + node.BindMethod("GetRight", &Nz::Node::GetRight); + //nodeClass.SetMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); + node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); + //nodeClass.SetMethod("GetTransformMatrix", &Nz::Node::GetTransformMatrix); + node.BindMethod("GetUp", &Nz::Node::GetUp); + + node.BindMethod("HasChilds", &Nz::Node::HasChilds); + + node.BindMethod("GetBackward", &Nz::Node::GetBackward); + node.BindMethod("GetDown", &Nz::Node::GetDown); + node.BindMethod("GetForward", &Nz::Node::GetForward); + node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); + node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); + node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); + node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); + node.BindMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); + node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); + node.BindMethod("GetLeft", &Nz::Node::GetLeft); + node.BindMethod("GetNodeType", &Nz::Node::GetNodeType); + node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); + node.BindMethod("GetRight", &Nz::Node::GetRight); + node.BindMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); + node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); + node.BindMethod("GetUp", &Nz::Node::GetUp); + + node.BindMethod("SetInitialPosition", (void(Nz::Node::*)(const Nz::Vector3f&)) &Nz::Node::SetInitialPosition); + node.BindMethod("SetInitialRotation", (void(Nz::Node::*)(const Nz::Quaternionf&)) &Nz::Node::SetInitialRotation); + + 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::LuaInstance& 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); + instance.Move(offset, coordSys); + + return 0; + }); + + node.BindMethod("Rotate", [] (Nz::LuaInstance& 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); + instance.Rotate(rotation, coordSys); + + return 0; + }); + + node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int + { + std::size_t argCount = std::min(argumentCount, 4U); + + int argIndex = 2; + switch (argCount) + { + case 1: + { + if (lua.IsOfType(argIndex, Nz::LuaType_Number)) + instance.Scale(lua.Check(&argIndex)); + else + instance.Scale(lua.Check(&argIndex)); + + return 0; + } + + case 3: + instance.Scale(lua.Check(&argIndex)); + return 0; + } + + lua.Error("No matching overload for method Scale"); + return 0; + }); + + node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int + { + std::size_t argCount = std::min(argumentCount, 4U); + + int argIndex = 2; + switch (argCount) + { + case 1: + case 2: + { + if (lua.IsOfType(argIndex, Nz::LuaType_Number)) + { + float scale = lua.Check(&argIndex); + Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); + instance.SetScale(scale, coordSys); + } + else + instance.SetScale(lua.Check(&argIndex)); + + return 0; + } + + case 3: + case 4: + { + Nz::Vector3f scale = lua.Check(&argIndex); + Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); + + instance.SetScale(scale, coordSys); + return 0; + } + } + + lua.Error("No matching overload for method SetScale"); + return 0; + }); + + node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int + { + std::size_t argCount = std::min(argumentCount, 4U); + + int argIndex = 2; + switch (argCount) + { + case 1: + { + if (lua.IsOfType(argIndex, Nz::LuaType_Number)) + instance.SetInitialScale(lua.Check(&argIndex)); + else + instance.SetInitialScale(lua.Check(&argIndex)); + + return 0; + } + + case 2: + case 3: + instance.SetInitialScale(lua.Check(&argIndex)); + return 0; + } + + lua.Error("No matching overload for method SetInitialScale"); + return 0; + }); + } + } + + /*! + * \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_Utility::Register(Nz::LuaInstance& instance) + { + abstractImage.Register(instance); + font.Register(instance); + keyboard.Register(instance); + node.Register(instance); + + keyboard.PushGlobalTable(instance); + { + static_assert(Nz::Keyboard::Count == 121, "Nz::Keyboard::Key has been updated but change was not reflected to Lua binding"); + + instance.PushField("Undefined", Nz::Keyboard::Undefined); + + // A-Z + for (std::size_t i = 0; i < 26; ++i) + instance.PushField(Nz::String('A' + char(i)), Nz::Keyboard::A + i); + + // Numerical + for (std::size_t i = 0; i < 10; ++i) + { + instance.PushField("Num" + Nz::String::Number(i), Nz::Keyboard::Num0 + i); + instance.PushField("Numpad" + Nz::String::Number(i), Nz::Keyboard::Numpad0 + i); + } + + // F1-F15 + for (std::size_t i = 0; i < 15; ++i) + instance.PushField('F' + Nz::String::Number(i+1), Nz::Keyboard::F1 + i); + + // And all the others... + instance.PushField("Down", Nz::Keyboard::Down); + instance.PushField("Left", Nz::Keyboard::Left); + instance.PushField("Right", Nz::Keyboard::Right); + instance.PushField("Up", Nz::Keyboard::Up); + + instance.PushField("Add", Nz::Keyboard::Add); + instance.PushField("Decimal", Nz::Keyboard::Decimal); + instance.PushField("Divide", Nz::Keyboard::Divide); + instance.PushField("Multiply", Nz::Keyboard::Multiply); + instance.PushField("Subtract", Nz::Keyboard::Subtract); + + instance.PushField("Backslash", Nz::Keyboard::Backslash); + instance.PushField("Backspace", Nz::Keyboard::Backspace); + instance.PushField("Clear", Nz::Keyboard::Clear); + instance.PushField("Comma", Nz::Keyboard::Comma); + instance.PushField("Dash", Nz::Keyboard::Dash); + instance.PushField("Delete", Nz::Keyboard::Delete); + instance.PushField("End", Nz::Keyboard::End); + instance.PushField("Equal", Nz::Keyboard::Equal); + instance.PushField("Escape", Nz::Keyboard::Escape); + instance.PushField("Home", Nz::Keyboard::Home); + instance.PushField("Insert", Nz::Keyboard::Insert); + instance.PushField("LAlt", Nz::Keyboard::LAlt); + instance.PushField("LBracket", Nz::Keyboard::LBracket); + instance.PushField("LControl", Nz::Keyboard::LControl); + instance.PushField("LShift", Nz::Keyboard::LShift); + instance.PushField("LSystem", Nz::Keyboard::LSystem); + instance.PushField("PageDown", Nz::Keyboard::PageDown); + instance.PushField("PageUp", Nz::Keyboard::PageUp); + instance.PushField("Pause", Nz::Keyboard::Pause); + instance.PushField("Period", Nz::Keyboard::Period); + instance.PushField("Print", Nz::Keyboard::Print); + instance.PushField("PrintScreen", Nz::Keyboard::PrintScreen); + instance.PushField("Quote", Nz::Keyboard::Quote); + instance.PushField("RAlt", Nz::Keyboard::RAlt); + instance.PushField("RBracket", Nz::Keyboard::RBracket); + instance.PushField("RControl", Nz::Keyboard::RControl); + instance.PushField("Return", Nz::Keyboard::Return); + instance.PushField("RShift", Nz::Keyboard::RShift); + instance.PushField("RSystem", Nz::Keyboard::RSystem); + instance.PushField("Semicolon", Nz::Keyboard::Semicolon); + instance.PushField("Slash", Nz::Keyboard::Slash); + instance.PushField("Space", Nz::Keyboard::Space); + instance.PushField("Tab", Nz::Keyboard::Tab); + instance.PushField("Tilde", Nz::Keyboard::Tilde); + instance.PushField("Browser_Back", Nz::Keyboard::Browser_Back); + instance.PushField("Browser_Favorites", Nz::Keyboard::Browser_Favorites); + instance.PushField("Browser_Forward", Nz::Keyboard::Browser_Forward); + instance.PushField("Browser_Home", Nz::Keyboard::Browser_Home); + instance.PushField("Browser_Refresh", Nz::Keyboard::Browser_Refresh); + instance.PushField("Browser_Search", Nz::Keyboard::Browser_Search); + instance.PushField("Browser_Stop", Nz::Keyboard::Browser_Stop); + instance.PushField("Media_Next", Nz::Keyboard::Media_Next); + instance.PushField("Media_Play", Nz::Keyboard::Media_Play); + instance.PushField("Media_Previous", Nz::Keyboard::Media_Previous); + instance.PushField("Media_Stop", Nz::Keyboard::Media_Stop); + instance.PushField("Volume_Down", Nz::Keyboard::Volume_Down); + instance.PushField("Volume_Mute", Nz::Keyboard::Volume_Mute); + instance.PushField("Volume_Up", Nz::Keyboard::Volume_Up); + instance.PushField("CapsLock", Nz::Keyboard::CapsLock); + instance.PushField("NumLock", Nz::Keyboard::NumLock); + instance.PushField("ScrollLock", Nz::Keyboard::ScrollLock); + } + instance.Pop(); + + static_assert(Nz::WindowStyle_Max + 1 == 6, "Nz::WindowStyle has been updated but change was not reflected to Lua binding"); + instance.PushTable(0, Nz::WindowStyle_Max + 1); + { + instance.PushField("None", Nz::WindowStyle_None); + instance.PushField("Fullscreen", Nz::WindowStyle_Fullscreen); + instance.PushField("Closable", Nz::WindowStyle_Closable); + instance.PushField("Resizable", Nz::WindowStyle_Resizable); + instance.PushField("Titlebar", Nz::WindowStyle_Titlebar); + instance.PushField("Threaded", Nz::WindowStyle_Threaded); + } + instance.SetGlobal("WindowStyle"); + + + } +} diff --git a/SDK/src/NDK/LuaAPI.cpp b/SDK/src/NDK/LuaAPI.cpp index fba28b2b3..a28fbb05f 100644 --- a/SDK/src/NDK/LuaAPI.cpp +++ b/SDK/src/NDK/LuaAPI.cpp @@ -2,7 +2,7 @@ #include #include -#include +#include namespace Ndk { diff --git a/SDK/src/NDK/LuaBinding.cpp b/SDK/src/NDK/LuaBinding.cpp deleted file mode 100644 index 789427f26..000000000 --- a/SDK/src/NDK/LuaBinding.cpp +++ /dev/null @@ -1,107 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::LuaBinding - * \brief NDK class that represents the binding between the engine & the SDK with the Lua scripting - */ - - /*! - * \brief Binds modules to Lua - */ - - LuaBinding::LuaBinding() : - // Core - clock("Clock"), - directory("Directory"), - file("File"), - stream("Stream"), - - // Math - eulerAngles("EulerAngles"), - matrix4d("Matrix4"), - quaternion("Quaternion"), - rect("Rect"), - vector2d("Vector2"), - vector3d("Vector3"), - - // Network - abstractSocket("AbstractSocket"), - ipAddress("IpAddress"), - - // Utility - abstractImage("AbstractImage"), - font("Font"), - node("Node"), - - // SDK - application("Application"), - entity("Entity"), - nodeComponent("NodeComponent"), - velocityComponent("VelocityComponent"), - world("World") - - #ifndef NDK_SERVER - , - - // Audio - music("Music"), - sound("Sound"), - soundBuffer("SoundBuffer"), - soundEmitter("SoundEmitter"), - - // Graphics - instancedRenderable("InstancedRenderable"), - material("Material"), - model("Model"), - sprite("Sprite"), - spriteLibrary("SpriteLibrary"), - textureLibrary("TextureLibrary"), - textureManager("TextureManager"), - - // Renderer - texture("Texture"), - - // SDK - console("Console"), - graphicsComponent("GraphicsComponent") - #endif - { - BindCore(); - BindMath(); - BindNetwork(); - BindSDK(); - BindUtility(); - - #ifndef NDK_SERVER - BindAudio(); - BindGraphics(); - BindRenderer(); - #endif - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the engine & SDK - */ - - void LuaBinding::RegisterClasses(Nz::LuaInstance& instance) - { - RegisterCore(instance); - RegisterMath(instance); - RegisterNetwork(instance); - RegisterSDK(instance); - RegisterUtility(instance); - - #ifndef NDK_SERVER - RegisterAudio(instance); - RegisterGraphics(instance); - RegisterRenderer(instance); - #endif - } -} diff --git a/SDK/src/NDK/LuaBinding_Audio.cpp b/SDK/src/NDK/LuaBinding_Audio.cpp deleted file mode 100644 index 46791b6c7..000000000 --- a/SDK/src/NDK/LuaBinding_Audio.cpp +++ /dev/null @@ -1,185 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include -#include -#include - -namespace Ndk -{ - /*! - * \brief Binds Audio module to Lua - */ - - void LuaBinding::BindAudio() - { - /*********************************** Nz::Music **********************************/ - music.Inherit(soundEmitter); - - music.BindDefaultConstructor(); - - //musicClass.SetMethod("Create", &Nz::Music::Create); - //musicClass.SetMethod("Destroy", &Nz::Music::Destroy); - - music.BindMethod("EnableLooping", &Nz::Music::EnableLooping); - - music.BindMethod("GetDuration", &Nz::Music::GetDuration); - music.BindMethod("GetFormat", &Nz::Music::GetFormat); - music.BindMethod("GetPlayingOffset", &Nz::Music::GetPlayingOffset); - music.BindMethod("GetSampleCount", &Nz::Music::GetSampleCount); - music.BindMethod("GetSampleRate", &Nz::Music::GetSampleRate); - music.BindMethod("GetStatus", &Nz::Music::GetStatus); - - music.BindMethod("IsLooping", &Nz::Music::IsLooping); - - music.BindMethod("OpenFromFile", &Nz::Music::OpenFromFile, Nz::MusicParams()); - - music.BindMethod("Pause", &Nz::Music::Pause); - music.BindMethod("Play", &Nz::Music::Play); - - music.BindMethod("SetPlayingOffset", &Nz::Music::SetPlayingOffset); - - music.BindMethod("Stop", &Nz::Music::Stop); - - // Manual - music.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& music, std::size_t /*argumentCount*/) -> int - { - Nz::StringStream stream("Music("); - stream << music.GetFilePath() << ')'; - - lua.PushString(stream); - return 1; - }); - - /*********************************** Nz::Sound **********************************/ - sound.Inherit(soundEmitter); - - sound.BindDefaultConstructor(); - - sound.BindMethod("GetBuffer", &Nz::Sound::GetBuffer); - - sound.BindMethod("IsPlayable", &Nz::Sound::IsPlayable); - sound.BindMethod("IsPlaying", &Nz::Sound::IsPlaying); - - sound.BindMethod("LoadFromFile", &Nz::Sound::LoadFromFile, Nz::SoundBufferParams()); - - sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset); - - // Manual - sound.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& sound, std::size_t /*argumentCount*/) -> int - { - Nz::StringStream stream("Sound("); - if (const Nz::SoundBuffer* buffer = sound.GetBuffer()) - stream << buffer; - - stream << ')'; - - lua.PushString(stream); - return 1; - }); - - /*********************************** Nz::SoundBuffer **********************************/ - soundBuffer.SetConstructor([] (Nz::LuaInstance& lua, Nz::SoundBufferRef* instance, std::size_t argumentCount) - { - NazaraUnused(lua); - NazaraUnused(argumentCount); - - Nz::PlacementNew(instance, Nz::SoundBuffer::New()); - return true; - }); - - soundBuffer.BindMethod("Destroy", &Nz::SoundBuffer::Destroy); - - soundBuffer.BindMethod("GetDuration", &Nz::SoundBuffer::GetDuration); - soundBuffer.BindMethod("GetFormat", &Nz::SoundBuffer::GetFormat); - soundBuffer.BindMethod("GetSampleCount", &Nz::SoundBuffer::GetSampleCount); - soundBuffer.BindMethod("GetSampleRate", &Nz::SoundBuffer::GetSampleRate); - - soundBuffer.BindMethod("IsValid", &Nz::SoundBuffer::IsValid); - - soundBuffer.BindMethod("LoadFromFile", &Nz::SoundBuffer::LoadFromFile, Nz::SoundBufferParams()); - - soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported); - - // Manual - soundBuffer.BindMethod("Create", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int - { - int index = 2; - Nz::AudioFormat format = lua.Check(&index); - unsigned int sampleCount = lua.Check(&index); - unsigned int sampleRate = lua.Check(&index); - - std::size_t bufferSize = 0; - const char* buffer = lua.CheckString(index, &bufferSize); - lua.ArgCheck(buffer && bufferSize >= sampleCount * sizeof(Nz::Int16), index, "Invalid buffer"); - - lua.PushBoolean(instance->Create(format, sampleCount, sampleRate, reinterpret_cast(buffer))); - return 1; - }); - - soundBuffer.BindMethod("GetSamples", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int - { - lua.PushString(reinterpret_cast(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16)); - return 1; - }); - - soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int - { - Nz::StringStream stream("SoundBuffer("); - if (instance->IsValid()) - { - Nz::String filePath = instance->GetFilePath(); - if (!filePath.IsEmpty()) - stream << "File: " << filePath << ", "; - - stream << "Duration: " << instance->GetDuration() / 1000.f << "s"; - } - stream << ')'; - - lua.PushString(stream); - return 1; - }); - - /*********************************** Nz::SoundEmitter **********************************/ - soundEmitter.BindMethod("EnableLooping", &Nz::SoundEmitter::EnableLooping); - soundEmitter.BindMethod("EnableSpatialization", &Nz::SoundEmitter::EnableSpatialization); - - soundEmitter.BindMethod("GetAttenuation", &Nz::SoundEmitter::GetAttenuation); - soundEmitter.BindMethod("GetDuration", &Nz::SoundEmitter::GetDuration); - soundEmitter.BindMethod("GetMinDistance", &Nz::SoundEmitter::GetMinDistance); - soundEmitter.BindMethod("GetPitch", &Nz::SoundEmitter::GetPitch); - soundEmitter.BindMethod("GetPlayingOffset", &Nz::SoundEmitter::GetPlayingOffset); - soundEmitter.BindMethod("GetPosition", &Nz::Sound::GetPosition); - soundEmitter.BindMethod("GetStatus", &Nz::SoundEmitter::GetStatus); - soundEmitter.BindMethod("GetVelocity", &Nz::Sound::GetVelocity); - soundEmitter.BindMethod("GetVolume", &Nz::SoundEmitter::GetVolume); - - soundEmitter.BindMethod("IsLooping", &Nz::SoundEmitter::IsLooping); - soundEmitter.BindMethod("IsSpatialized", &Nz::SoundEmitter::IsSpatialized); - - soundEmitter.BindMethod("Pause", &Nz::SoundEmitter::Pause); - soundEmitter.BindMethod("Play", &Nz::SoundEmitter::Play); - - soundEmitter.BindMethod("SetAttenuation", &Nz::SoundEmitter::SetAttenuation); - soundEmitter.BindMethod("SetMinDistance", &Nz::SoundEmitter::SetMinDistance); - soundEmitter.BindMethod("SetPitch", &Nz::SoundEmitter::SetPitch); - soundEmitter.BindMethod("SetPosition", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetPosition); - soundEmitter.BindMethod("SetVelocity", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetVelocity); - soundEmitter.BindMethod("SetVolume", &Nz::SoundEmitter::SetVolume); - - soundEmitter.BindMethod("Stop", &Nz::SoundEmitter::Stop); - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Audio classes - */ - - void LuaBinding::RegisterAudio(Nz::LuaInstance& instance) - { - music.Register(instance); - sound.Register(instance); - soundBuffer.Register(instance); - soundEmitter.Register(instance); - } -} diff --git a/SDK/src/NDK/LuaBinding_Core.cpp b/SDK/src/NDK/LuaBinding_Core.cpp deleted file mode 100644 index dc149e3d0..000000000 --- a/SDK/src/NDK/LuaBinding_Core.cpp +++ /dev/null @@ -1,318 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include -#include -#include - -namespace Ndk -{ - /*! - * \brief Binds Core module to Lua - */ - - void LuaBinding::BindCore() - { - /*********************************** Nz::Clock **********************************/ - clock.SetConstructor([](Nz::LuaInstance& lua, Nz::Clock* clock, std::size_t /*argumentCount*/) - { - int argIndex = 2; - Nz::Int64 startingValue = lua.Check(&argIndex, 0); - bool paused = lua.Check(&argIndex, false); - - Nz::PlacementNew(clock, startingValue, paused); - return true; - }); - - clock.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds); - clock.BindMethod("GetMilliseconds", &Nz::Clock::GetMilliseconds); - clock.BindMethod("GetSeconds", &Nz::Clock::GetSeconds); - clock.BindMethod("IsPaused", &Nz::Clock::IsPaused); - clock.BindMethod("Pause", &Nz::Clock::Pause); - clock.BindMethod("Restart", &Nz::Clock::Restart); - clock.BindMethod("Unpause", &Nz::Clock::Unpause); - - // Manual - clock.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& clock, std::size_t /*argumentCount*/) -> int { - Nz::StringStream stream("Clock(Elapsed: "); - stream << clock.GetSeconds(); - stream << "s, Paused: "; - stream << clock.IsPaused(); - stream << ')'; - - lua.PushString(stream); - return 1; - }); - - /********************************* Nz::Directory ********************************/ - directory.SetConstructor([](Nz::LuaInstance& lua, Nz::Directory* directory, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 1U); - - int argIndex = 2; - switch (argCount) - { - case 0: - Nz::PlacementNew(directory); - return true; - - case 1: - Nz::PlacementNew(directory, lua.Check(&argIndex)); - return true; - } - - return false; - }); - - directory.BindMethod("Close", &Nz::Directory::Close); - directory.BindMethod("Exists", &Nz::Directory::Exists); - directory.BindMethod("GetPath", &Nz::Directory::GetPath); - directory.BindMethod("GetPattern", &Nz::Directory::GetPattern); - directory.BindMethod("GetResultName", &Nz::Directory::GetResultName); - directory.BindMethod("GetResultPath", &Nz::Directory::GetResultPath); - directory.BindMethod("GetResultSize", &Nz::Directory::GetResultSize); - directory.BindMethod("IsOpen", &Nz::Directory::IsOpen); - directory.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory); - directory.BindMethod("NextResult", &Nz::Directory::NextResult, true); - directory.BindMethod("Open", &Nz::Directory::Open); - directory.BindMethod("SetPath", &Nz::Directory::SetPath); - directory.BindMethod("SetPattern", &Nz::Directory::SetPattern); - - directory.BindStaticMethod("Copy", Nz::Directory::Copy); - directory.BindStaticMethod("Create", Nz::Directory::Create); - directory.BindStaticMethod("Exists", Nz::Directory::Exists); - directory.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent); - directory.BindStaticMethod("Remove", Nz::Directory::Remove); - directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); - - // Manual - directory.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& directory, std::size_t /*argumentCount*/) -> int { - Nz::StringStream stream("Directory("); - stream << directory.GetPath(); - stream << ')'; - - lua.PushString(stream); - return 1; - }); - - /*********************************** Nz::Stream ***********************************/ - stream.BindMethod("EnableTextMode", &Nz::Stream::EnableTextMode); - stream.BindMethod("Flush", &Nz::Stream::Flush); - stream.BindMethod("GetCursorPos", &Nz::Stream::GetCursorPos); - stream.BindMethod("GetDirectory", &Nz::Stream::GetDirectory); - stream.BindMethod("GetPath", &Nz::Stream::GetPath); - stream.BindMethod("GetOpenMode", &Nz::Stream::GetOpenMode); - stream.BindMethod("GetStreamOptions", &Nz::Stream::GetStreamOptions); - stream.BindMethod("GetSize", &Nz::Stream::GetSize); - stream.BindMethod("ReadLine", &Nz::Stream::ReadLine, 0U); - stream.BindMethod("IsReadable", &Nz::Stream::IsReadable); - stream.BindMethod("IsSequential", &Nz::Stream::IsSequential); - stream.BindMethod("IsTextModeEnabled", &Nz::Stream::IsTextModeEnabled); - stream.BindMethod("IsWritable", &Nz::Stream::IsWritable); - stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos); - - stream.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& stream, 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); - - lua.PushString(Nz::String(buffer.get(), readLength)); - return 1; - }); - - stream.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& stream, 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))); - else - lua.Push(stream.Write(buffer, bufferSize)); - return 1; - }); - - /*********************************** Nz::File ***********************************/ - file.Inherit(stream); - - file.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* file, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 1U); - - int argIndex = 2; - switch (argCount) - { - case 0: - Nz::PlacementNew(file); - return true; - - case 1: - { - Nz::String filePath = lua.Check(&argIndex); - - Nz::PlacementNew(file, filePath); - return true; - } - - case 2: - { - Nz::String filePath = lua.Check(&argIndex); - Nz::UInt32 openMode = lua.Check(&argIndex); - - Nz::PlacementNew(file, filePath, openMode); - return true; - } - } - - lua.Error("No matching overload for File constructor"); - return false; - }); - - file.BindMethod("Close", &Nz::File::Close); - file.BindMethod("Copy", &Nz::File::Copy); - file.BindMethod("Delete", &Nz::File::Delete); - file.BindMethod("EndOfFile", &Nz::File::EndOfFile); - file.BindMethod("Exists", &Nz::File::Exists); - file.BindMethod("GetCreationTime", &Nz::File::GetCreationTime); - file.BindMethod("GetFileName", &Nz::File::GetFileName); - file.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); - file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - file.BindMethod("IsOpen", &Nz::File::IsOpen); - file.BindMethod("Rename", &Nz::File::GetLastWriteTime); - file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - file.BindMethod("SetFile", &Nz::File::GetLastWriteTime); - - file.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath); - file.BindStaticMethod("ComputeHash", (Nz::ByteArray (*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash); - file.BindStaticMethod("Copy", &Nz::File::Copy); - file.BindStaticMethod("Delete", &Nz::File::Delete); - file.BindStaticMethod("Exists", &Nz::File::Exists); - //fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime); - file.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory); - //fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); - //fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - file.BindStaticMethod("GetSize", &Nz::File::GetSize); - file.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute); - file.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath); - file.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators); - file.BindStaticMethod("Rename", &Nz::File::Rename); - - // Manual - file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 2U); - - int argIndex = 2; - switch (argCount) - { - case 0: - case 1: - return lua.Push(file.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)); - } - } - - lua.Error("No matching overload for method Open"); - return 0; - }); - - file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 2U); - - int argIndex = 2; - switch (argCount) - { - case 1: - return lua.Push(file.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)); - } - } - - lua.Error("No matching overload for method SetCursorPos"); - return 0; - }); - - file.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t /*argumentCount*/) -> int { - Nz::StringStream stream("File("); - if (file.IsOpen()) - stream << "Path: " << file.GetPath(); - - stream << ')'; - - lua.PushString(stream); - return 1; - }); - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Core classes - */ - - void LuaBinding::RegisterCore(Nz::LuaInstance& instance) - { - // Classes - clock.Register(instance); - directory.Register(instance); - file.Register(instance); - stream.Register(instance); - - // Enums - - // Nz::CursorPosition - static_assert(Nz::CursorPosition_Max + 1 == 3, "Nz::CursorPosition has been updated but change was not reflected to Lua binding"); - instance.PushTable(0, 3); - { - instance.PushField("AtBegin", Nz::CursorPosition_AtBegin); - instance.PushField("AtCurrent", Nz::CursorPosition_AtCurrent); - instance.PushField("AtEnd", Nz::CursorPosition_AtEnd); - } - instance.SetGlobal("CursorPosition"); - - // Nz::HashType - static_assert(Nz::HashType_Max + 1 == 9, "Nz::HashType has been updated but change was not reflected to Lua binding"); - instance.PushTable(0, 9); - { - instance.PushField("CRC32", Nz::HashType_CRC32); - instance.PushField("Fletcher16", Nz::HashType_Fletcher16); - instance.PushField("MD5", Nz::HashType_MD5); - instance.PushField("SHA1", Nz::HashType_SHA1); - instance.PushField("SHA224", Nz::HashType_SHA224); - instance.PushField("SHA256", Nz::HashType_SHA256); - instance.PushField("SHA384", Nz::HashType_SHA384); - instance.PushField("SHA512", Nz::HashType_SHA512); - instance.PushField("Whirlpool", Nz::HashType_Whirlpool); - } - instance.SetGlobal("HashType"); - - // Nz::OpenMode - static_assert(Nz::OpenMode_Max + 1 == 2 * (64), "Nz::OpenModeFlags has been updated but change was not reflected to Lua binding"); - instance.PushTable(0, 8); - { - instance.PushField("Append", Nz::OpenMode_Append); - instance.PushField("NotOpen", Nz::OpenMode_NotOpen); - instance.PushField("Lock", Nz::OpenMode_Lock); - instance.PushField("ReadOnly", Nz::OpenMode_ReadOnly); - instance.PushField("ReadWrite", Nz::OpenMode_ReadWrite); - instance.PushField("Text", Nz::OpenMode_Text); - instance.PushField("Truncate", Nz::OpenMode_Truncate); - instance.PushField("WriteOnly", Nz::OpenMode_WriteOnly); - } - instance.SetGlobal("OpenMode"); - } -} diff --git a/SDK/src/NDK/LuaBinding_Graphics.cpp b/SDK/src/NDK/LuaBinding_Graphics.cpp deleted file mode 100644 index 4a2b53422..000000000 --- a/SDK/src/NDK/LuaBinding_Graphics.cpp +++ /dev/null @@ -1,334 +0,0 @@ -// 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 -{ - /*! - * \brief Binds Graphics module to Lua - */ - - void LuaBinding::BindGraphics() - { - /*********************************** Nz::InstancedRenderable ***********************************/ - - /*********************************** Nz::Material ***********************************/ - material.SetConstructor([] (Nz::LuaInstance& lua, Nz::MaterialRef* instance, std::size_t argumentCount) - { - switch (argumentCount) - { - case 0: - Nz::PlacementNew(instance, Nz::Material::New()); - return true; - - case 1: - { - int argIndex = 1; - if (lua.IsOfType(argIndex, "MaterialPipeline")) - { - Nz::PlacementNew(instance, Nz::Material::New(*static_cast(lua.ToUserdata(argIndex)))); - return true; - } - else if (lua.IsOfType(argIndex, "Material")) - { - Nz::PlacementNew(instance, Nz::Material::New(**static_cast(lua.ToUserdata(argIndex)))); - return true; - } - else - { - Nz::PlacementNew(instance, Nz::Material::New(lua.Check(&argIndex))); - return true; - } - } - } - - lua.Error("No matching overload for constructor"); - return false; - }); - - material.BindMethod("Configure", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "MaterialPipeline")) - { - instance->Configure(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - { - lua.Push(instance->Configure(lua.Check(&argIndex))); - return 1; - } - }); - - material.BindMethod("EnableAlphaTest", &Nz::Material::EnableAlphaTest); - material.BindMethod("EnableBlending", &Nz::Material::EnableBlending); - material.BindMethod("EnableColorWrite", &Nz::Material::EnableColorWrite); - material.BindMethod("EnableDepthBuffer", &Nz::Material::EnableDepthBuffer); - material.BindMethod("EnableDepthSorting", &Nz::Material::EnableDepthSorting); - material.BindMethod("EnableDepthWrite", &Nz::Material::EnableDepthWrite); - material.BindMethod("EnableFaceCulling", &Nz::Material::EnableFaceCulling); - material.BindMethod("EnableScissorTest", &Nz::Material::EnableScissorTest); - material.BindMethod("EnableShadowCasting", &Nz::Material::EnableShadowCasting); - material.BindMethod("EnableShadowReceive", &Nz::Material::EnableShadowReceive); - material.BindMethod("EnableStencilTest", &Nz::Material::EnableStencilTest); - - material.BindMethod("EnsurePipelineUpdate", &Nz::Material::EnsurePipelineUpdate); - - material.BindMethod("GetAlphaMap", &Nz::Material::GetAlphaMap); - material.BindMethod("GetAlphaThreshold", &Nz::Material::GetAlphaThreshold); - material.BindMethod("GetAmbientColor", &Nz::Material::GetAmbientColor); - material.BindMethod("GetDepthFunc", &Nz::Material::GetDepthFunc); - material.BindMethod("GetDepthMaterial", &Nz::Material::GetDepthMaterial); - material.BindMethod("GetDiffuseColor", &Nz::Material::GetDiffuseColor); - material.BindMethod("GetDiffuseMap", &Nz::Material::GetDiffuseMap); - //material.BindMethod("GetDiffuseSampler", &Nz::Material::GetDiffuseSampler); - material.BindMethod("GetDstBlend", &Nz::Material::GetDstBlend); - material.BindMethod("GetEmissiveMap", &Nz::Material::GetEmissiveMap); - material.BindMethod("GetFaceCulling", &Nz::Material::GetFaceCulling); - material.BindMethod("GetFaceFilling", &Nz::Material::GetFaceFilling); - material.BindMethod("GetHeightMap", &Nz::Material::GetHeightMap); - material.BindMethod("GetLineWidth", &Nz::Material::GetLineWidth); - material.BindMethod("GetNormalMap", &Nz::Material::GetNormalMap); - //material.BindMethod("GetPipeline", &Nz::Material::GetPipeline); - //material.BindMethod("GetPipelineInfo", &Nz::Material::GetPipelineInfo); - material.BindMethod("GetPointSize", &Nz::Material::GetPointSize); - //material.BindMethod("GetShader", &Nz::Material::GetShader); - material.BindMethod("GetShininess", &Nz::Material::GetShininess); - material.BindMethod("GetSpecularColor", &Nz::Material::GetSpecularColor); - material.BindMethod("GetSpecularMap", &Nz::Material::GetSpecularMap); - //material.BindMethod("GetSpecularSampler", &Nz::Material::GetSpecularSampler); - material.BindMethod("GetSrcBlend", &Nz::Material::GetSrcBlend); - - material.BindMethod("HasAlphaMap", &Nz::Material::HasAlphaMap); - material.BindMethod("HasDepthMaterial", &Nz::Material::HasDepthMaterial); - material.BindMethod("HasDiffuseMap", &Nz::Material::HasDiffuseMap); - material.BindMethod("HasEmissiveMap", &Nz::Material::HasEmissiveMap); - material.BindMethod("HasHeightMap", &Nz::Material::HasHeightMap); - material.BindMethod("HasNormalMap", &Nz::Material::HasNormalMap); - material.BindMethod("HasSpecularMap", &Nz::Material::HasSpecularMap); - - material.BindMethod("IsAlphaTestEnabled", &Nz::Material::IsAlphaTestEnabled); - material.BindMethod("IsBlendingEnabled", &Nz::Material::IsBlendingEnabled); - material.BindMethod("IsColorWriteEnabled", &Nz::Material::IsColorWriteEnabled); - material.BindMethod("IsDepthBufferEnabled", &Nz::Material::IsDepthBufferEnabled); - material.BindMethod("IsDepthSortingEnabled", &Nz::Material::IsDepthSortingEnabled); - material.BindMethod("IsDepthWriteEnabled", &Nz::Material::IsDepthWriteEnabled); - material.BindMethod("IsFaceCullingEnabled", &Nz::Material::IsFaceCullingEnabled); - material.BindMethod("IsScissorTestEnabled", &Nz::Material::IsScissorTestEnabled); - material.BindMethod("IsStencilTestEnabled", &Nz::Material::IsStencilTestEnabled); - material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled); - material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled); - - material.BindMethod("LoadFromFile", &Nz::Material::LoadFromFile); - - material.BindMethod("Reset", &Nz::Material::Reset); - - material.BindMethod("SetAlphaThreshold", &Nz::Material::SetAlphaThreshold); - material.BindMethod("SetAmbientColor", &Nz::Material::SetAmbientColor); - material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc); - material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc); - material.BindMethod("SetDepthMaterial", &Nz::Material::SetDepthMaterial); - material.BindMethod("SetDiffuseColor", &Nz::Material::SetDiffuseColor); - //material.BindMethod("SetDiffuseSampler", &Nz::Material::SetDiffuseSampler); - material.BindMethod("SetDstBlend", &Nz::Material::SetDstBlend); - material.BindMethod("SetFaceCulling", &Nz::Material::SetFaceCulling); - material.BindMethod("SetFaceFilling", &Nz::Material::SetFaceFilling); - material.BindMethod("SetLineWidth", &Nz::Material::SetLineWidth); - material.BindMethod("SetPointSize", &Nz::Material::SetPointSize); - material.BindMethod("SetShininess", &Nz::Material::SetShininess); - material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor); - material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor); - //material.BindMethod("SetSpecularSampler", &Nz::Material::SetSpecularSampler); - material.BindMethod("SetSrcBlend", &Nz::Material::SetSrcBlend); - - material.BindStaticMethod("GetDefault", &Nz::Material::GetDefault); - - material.BindMethod("SetAlphaMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetAlphaMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetAlphaMap(lua.Check(&argIndex))); - }); - - material.BindMethod("SetDiffuseMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetDiffuseMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetDiffuseMap(lua.Check(&argIndex))); - }); - - material.BindMethod("SetEmissiveMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetEmissiveMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetEmissiveMap(lua.Check(&argIndex))); - }); - - material.BindMethod("SetHeightMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetHeightMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetHeightMap(lua.Check(&argIndex))); - }); - - material.BindMethod("SetNormalMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetNormalMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetNormalMap(lua.Check(&argIndex))); - }); - - material.BindMethod("SetShader", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "UberShader")) - { - instance->SetShader(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetShader(lua.Check(&argIndex))); - }); - - material.BindMethod("SetSpecularMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetSpecularMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetSpecularMap(lua.Check(&argIndex))); - }); - - /*********************************** Nz::Model ***********************************/ - model.Inherit(instancedRenderable, [] (Nz::ModelRef* model) -> Nz::InstancedRenderableRef* - { - return reinterpret_cast(model); //TODO: Make a ObjectRefCast - }); - - model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* model, std::size_t /*argumentCount*/) - { - Nz::PlacementNew(model, Nz::Model::New()); - return true; - }); - - //model.BindMethod("GetMaterial", &Nz::Model::GetMaterial); - model.BindMethod("GetMaterialCount", &Nz::Model::GetMaterialCount); - //modelClass.SetMethod("GetMesh", &Nz::Model::GetMesh); - model.BindMethod("GetSkin", &Nz::Model::GetSkin); - model.BindMethod("GetSkinCount", &Nz::Model::GetSkinCount); - - model.BindMethod("IsAnimated", &Nz::Model::IsAnimated); - model.BindMethod("LoadFromFile", &Nz::Model::LoadFromFile, Nz::ModelParameters()); - - model.BindMethod("Reset", &Nz::Model::Reset); - - //model.BindMethod("SetMaterial", &Nz::Model::SetMaterial); - //modelClass.SetMethod("SetMesh", &Nz::Model::SetMesh); - //modelClass.SetMethod("SetSequence", &Nz::Model::SetSequence); - model.BindMethod("SetSkin", &Nz::Model::SetSkin); - model.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount); - - /*********************************** Nz::Sprite ***********************************/ - sprite.Inherit(instancedRenderable, [] (Nz::SpriteRef* sprite) -> Nz::InstancedRenderableRef* - { - return reinterpret_cast(sprite); //TODO: Make a ObjectRefCast - }); - - sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* sprite, std::size_t /*argumentCount*/) - { - Nz::PlacementNew(sprite, Nz::Sprite::New()); - return true; - }); - - sprite.BindMethod("GetColor", &Nz::Sprite::GetColor); - sprite.BindMethod("GetCornerColor", &Nz::Sprite::GetCornerColor); - sprite.BindMethod("GetMaterial", &Nz::Sprite::GetMaterial); - sprite.BindMethod("GetOrigin", &Nz::Sprite::GetOrigin); - sprite.BindMethod("GetSize", &Nz::Sprite::GetSize); - sprite.BindMethod("GetTextureCoords", &Nz::Sprite::GetTextureCoords); - - sprite.BindMethod("SetColor", &Nz::Sprite::SetColor); - sprite.BindMethod("SetCornerColor", &Nz::Sprite::SetCornerColor); - sprite.BindMethod("SetDefaultMaterial", &Nz::Sprite::SetDefaultMaterial); - sprite.BindMethod("SetMaterial", &Nz::Sprite::SetMaterial, true); - sprite.BindMethod("SetOrigin", &Nz::Sprite::SetOrigin); - sprite.BindMethod("SetSize", (void(Nz::Sprite::*)(const Nz::Vector2f&)) &Nz::Sprite::SetSize); - sprite.BindMethod("SetTexture", &Nz::Sprite::SetTexture, true); - sprite.BindMethod("SetTextureCoords", &Nz::Sprite::SetTextureCoords); - sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect); - - /*********************************** Nz::SpriteLibrary ***********************************/ - - spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get); - spriteLibrary.BindStaticMethod("Has", &Nz::SpriteLibrary::Has); - spriteLibrary.BindStaticMethod("Register", &Nz::SpriteLibrary::Register); - spriteLibrary.BindStaticMethod("Query", &Nz::SpriteLibrary::Query); - spriteLibrary.BindStaticMethod("Unregister", &Nz::SpriteLibrary::Unregister); - - /*********************************** Nz::TextureLibrary ***********************************/ - - textureLibrary.BindStaticMethod("Get", &Nz::TextureLibrary::Get); - textureLibrary.BindStaticMethod("Has", &Nz::TextureLibrary::Has); - textureLibrary.BindStaticMethod("Register", &Nz::TextureLibrary::Register); - textureLibrary.BindStaticMethod("Query", &Nz::TextureLibrary::Query); - textureLibrary.BindStaticMethod("Unregister", &Nz::TextureLibrary::Unregister); - - /*********************************** Nz::TextureManager ***********************************/ - - textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear); - textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get); - textureManager.BindStaticMethod("GetDefaultParameters", &Nz::TextureManager::GetDefaultParameters); - textureManager.BindStaticMethod("Purge", &Nz::TextureManager::Purge); - textureManager.BindStaticMethod("Register", &Nz::TextureManager::Register); - textureManager.BindStaticMethod("SetDefaultParameters", &Nz::TextureManager::SetDefaultParameters); - textureManager.BindStaticMethod("Unregister", &Nz::TextureManager::Unregister); - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Graphics classes - */ - - void LuaBinding::RegisterGraphics(Nz::LuaInstance& instance) - { - instancedRenderable.Register(instance); - material.Register(instance); - model.Register(instance); - sprite.Register(instance); - spriteLibrary.Register(instance); - textureLibrary.Register(instance); - textureManager.Register(instance); - } -} diff --git a/SDK/src/NDK/LuaBinding_Math.cpp b/SDK/src/NDK/LuaBinding_Math.cpp deleted file mode 100644 index 51a510238..000000000 --- a/SDK/src/NDK/LuaBinding_Math.cpp +++ /dev/null @@ -1,908 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include -#include -#include -#include - -namespace Ndk -{ - /*! - * \brief Binds Math module to Lua - */ - - void LuaBinding::BindMath() - { - /*********************************** Nz::EulerAngles **********************************/ - eulerAngles.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* angles, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 1U); - - switch (argCount) - { - case 0: - Nz::PlacementNew(angles, Nz::EulerAnglesd::Zero()); - return true; - - case 1: - Nz::PlacementNew(angles, *static_cast(lua.CheckUserdata(1, "EulerAngles"))); - return true; - - case 3: - Nz::PlacementNew(angles, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3)); - return true; - } - - lua.Error("No matching overload for EulerAngles constructor"); - return false; - }); - - eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString); - - eulerAngles.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) - { - std::size_t length; - const char* ypr = lua.CheckString(2, &length); - - switch (length) - { - case 1: - { - switch (ypr[0]) - { - case 'p': - lua.Push(instance.pitch); - return true; - - case 'y': - lua.Push(instance.yaw); - return true; - - case 'r': - lua.Push(instance.roll); - return true; - } - break; - } - - case 3: - { - if (std::memcmp(ypr, "yaw", 3) != 0) - break; - - lua.Push(instance.yaw); - return true; - } - - case 4: - { - if (std::memcmp(ypr, "roll", 4) != 0) - break; - - lua.Push(instance.roll); - return true; - } - - case 5: - { - if (std::memcmp(ypr, "pitch", 5) != 0) - break; - - lua.Push(instance.pitch); - return true; - } - } - - return false; - }); - - eulerAngles.SetSetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) - { - std::size_t length; - const char* ypr = lua.CheckString(2, &length); - double value = lua.CheckNumber(3); - - switch (length) - { - case 1: - { - switch (ypr[0]) - { - case 'p': - instance.pitch = value; - return true; - - case 'y': - instance.yaw = value; - return true; - - case 'r': - instance.roll = value; - return true; - } - break; - } - - case 3: - { - if (std::memcmp(ypr, "yaw", 3) != 0) - break; - - instance.yaw = value; - return true; - } - - case 4: - { - if (std::memcmp(ypr, "roll", 4) != 0) - break; - - instance.roll = value; - return true; - } - - case 5: - { - if (std::memcmp(ypr, "pitch", 5) != 0) - break; - - instance.pitch = value; - return true; - } - } - - return false; - }); - - - /*********************************** Nz::Matrix4 **********************************/ - matrix4d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Matrix4d* matrix, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 3U); - - switch (argCount) - { - case 0: - Nz::PlacementNew(matrix, Nz::Matrix4d::Zero()); - return true; - - case 1: - if (lua.IsOfType(1, "Matrix4")) - Nz::PlacementNew(matrix, *static_cast(lua.ToUserdata(1))); - break; - - case 16: - { - double values[16]; - for (std::size_t i = 0; i < 16; ++i) - values[i] = lua.CheckNumber(i); - - Nz::PlacementNew(matrix, values); - - return true; - } - } - - lua.Error("No matching overload for constructor"); - return false; - }); - - matrix4d.BindMethod("ApplyRotation", &Nz::Matrix4d::ApplyRotation); - matrix4d.BindMethod("ApplyScale", &Nz::Matrix4d::ApplyScale); - matrix4d.BindMethod("ApplyTranslation", &Nz::Matrix4d::ApplyTranslation); - - matrix4d.BindMethod("Concatenate", &Nz::Matrix4d::Concatenate); - matrix4d.BindMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine); - - //matrix4d.BindMethod("GetColumn", &Nz::Matrix4d::GetColumn); - matrix4d.BindMethod("GetDeterminant", &Nz::Matrix4d::GetDeterminant); - matrix4d.BindMethod("GetDeterminantAffine", &Nz::Matrix4d::GetDeterminantAffine); - - matrix4d.BindMethod("GetInverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - Nz::Matrix4d result; - if (instance.GetInverse(&result)) - return lua.Push(true, result); - else - return lua.Push(false); - }); - - matrix4d.BindMethod("GetInverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - Nz::Matrix4d result; - if (instance.GetInverseAffine(&result)) - return lua.Push(true, result); - else - return lua.Push(false); - }); - - matrix4d.BindMethod("GetRotation", &Nz::Matrix4d::GetRotation); - - //matrix4d.BindMethod("GetRow", &Nz::Matrix4d::GetRow); - matrix4d.BindMethod("GetScale", &Nz::Matrix4d::GetScale); - matrix4d.BindMethod("GetSquaredScale", &Nz::Matrix4d::GetSquaredScale); - matrix4d.BindMethod("GetTranslation", &Nz::Matrix4d::GetTranslation); - - matrix4d.BindMethod("GetTransposed", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - Nz::Matrix4d result; - instance.GetTransposed(&result); - - return lua.Push(result); - }); - - matrix4d.BindMethod("HasNegativeScale", &Nz::Matrix4d::HasNegativeScale); - matrix4d.BindMethod("HasScale", &Nz::Matrix4d::HasScale); - - matrix4d.BindMethod("Inverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - bool succeeded; - instance.Inverse(&succeeded); - - return lua.Push(succeeded); - }); - - matrix4d.BindMethod("InverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - bool succeeded; - instance.InverseAffine(&succeeded); - - return lua.Push(succeeded); - }); - - matrix4d.BindMethod("IsAffine", &Nz::Matrix4d::IsAffine); - matrix4d.BindMethod("IsIdentity", &Nz::Matrix4d::IsIdentity); - - matrix4d.BindMethod("MakeIdentity", &Nz::Matrix4d::MakeIdentity); - matrix4d.BindMethod("MakeLookAt", &Nz::Matrix4d::MakeLookAt, Nz::Vector3d::Up()); - matrix4d.BindMethod("MakeOrtho", &Nz::Matrix4d::MakeOrtho, -1.0, 1.0); - matrix4d.BindMethod("MakePerspective", &Nz::Matrix4d::MakePerspective); - matrix4d.BindMethod("MakeRotation", &Nz::Matrix4d::MakeRotation); - matrix4d.BindMethod("MakeScale", &Nz::Matrix4d::MakeScale); - matrix4d.BindMethod("MakeTranslation", &Nz::Matrix4d::MakeTranslation); - matrix4d.BindMethod("MakeTransform", (Nz::Matrix4d&(Nz::Matrix4d::*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::MakeTransform, Nz::Vector3d::Unit()); - matrix4d.BindMethod("MakeViewMatrix", &Nz::Matrix4d::MakeViewMatrix); - matrix4d.BindMethod("MakeZero", &Nz::Matrix4d::MakeZero); - - matrix4d.BindMethod("Set", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 3U); - - int argIndex = 2; - switch (argCount) - { - case 1: - if (lua.IsOfType(argIndex, "Matrix4")) - instance.Set(*static_cast(lua.ToUserdata(argIndex))); - break; - - case 16: - { - double values[16]; - for (std::size_t i = 0; i < 16; ++i) - values[i] = lua.CheckNumber(argIndex++); - - instance.Set(values); - - return 0; - } - } - - lua.Error("No matching overload for method Set"); - return 0; - }); - - matrix4d.BindMethod("SetRotation", &Nz::Matrix4d::SetRotation); - matrix4d.BindMethod("SetScale", &Nz::Matrix4d::SetScale); - matrix4d.BindMethod("SetTranslation", &Nz::Matrix4d::SetTranslation); - - matrix4d.BindMethod("Transform", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Vector2")) - { - double z(lua.CheckNumber(argIndex+1, 0.0)); - double w(lua.CheckNumber(argIndex+2, 1.0)); - - return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(argIndex)), z, w)); - } - else if (lua.IsOfType(argIndex, "Vector3")) - { - double w(lua.CheckNumber(argIndex+1, 1.0)); - - return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(argIndex)), w)); - } - //else if (lua.IsOfType(2, "Vector4")) - // return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(1)))); - - lua.Error("No matching overload for method Transform"); - return 0; - }); - - matrix4d.BindMethod("Transpose", &Nz::Matrix4d::Transpose); - - matrix4d.BindMethod("__tostring", &Nz::Matrix4d::ToString); - - matrix4d.BindStaticMethod("Concatenate", &Nz::Matrix4d::Concatenate); - matrix4d.BindStaticMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine); - matrix4d.BindStaticMethod("Identity", &Nz::Matrix4d::Identity); - matrix4d.BindStaticMethod("LookAt", &Nz::Matrix4d::LookAt, Nz::Vector3d::Up()); - matrix4d.BindStaticMethod("Ortho", &Nz::Matrix4d::Ortho, -1.0, 1.0); - matrix4d.BindStaticMethod("Perspective", &Nz::Matrix4d::Perspective); - matrix4d.BindStaticMethod("Rotate", &Nz::Matrix4d::Rotate); - matrix4d.BindStaticMethod("Scale", &Nz::Matrix4d::Scale); - matrix4d.BindStaticMethod("Translate", &Nz::Matrix4d::Translate); - matrix4d.BindStaticMethod("Transform", (Nz::Matrix4d(*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::Transform, Nz::Vector3d::Unit()); - matrix4d.BindStaticMethod("ViewMatrix", &Nz::Matrix4d::ViewMatrix); - matrix4d.BindStaticMethod("Zero", &Nz::Matrix4d::Zero); - - matrix4d.SetGetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance) - { - bool succeeded = false; - std::size_t index = static_cast(lua.ToInteger(2, &succeeded)); - if (!succeeded || index < 1 || index > 16) - return false; - - lua.Push(instance[index - 1]); - return true; - }); - - matrix4d.SetSetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance) - { - bool succeeded = false; - std::size_t index = static_cast(lua.ToInteger(2, &succeeded)); - if (!succeeded || index < 1 || index > 16) - return false; - - instance[index - 1] = lua.CheckNumber(3); - - return true; - }); - - /*********************************** Nz::Rect **********************************/ - rect.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* rect, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 4U); - - switch (argCount) - { - case 0: - case 4: - PlacementNew(rect, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0), lua.CheckNumber(4, 0.0)); - return true; - - case 1: - { - if (lua.IsOfType(1, "Rect")) - PlacementNew(rect, *static_cast(lua.ToUserdata(1))); - else if (lua.IsOfType(1, Nz::LuaType_Table)) - { - // TODO => Faire sans avoir à mettre de nom dans la table et prendre les éléments un à un pour créer le Rectd - PlacementNew(rect, lua.CheckField("x", 1), - lua.CheckField("y", 1), - lua.CheckField("width", 1), - lua.CheckField("height", 1)); - } - else if (lua.IsOfType(1, "Vector2")) - PlacementNew(rect, *static_cast(lua.ToUserdata(1))); - else - break; - - return true; - } - - case 2: - { - if (lua.IsOfType(1, Nz::LuaType_Number) && lua.IsOfType(2, Nz::LuaType_Number)) - PlacementNew(rect, lua.CheckNumber(1), lua.CheckNumber(2)); - else if (lua.IsOfType(1, "Vector2") && lua.IsOfType(2, "Vector2")) - PlacementNew(rect, *static_cast(lua.ToUserdata(1)), *static_cast(lua.ToUserdata(2))); - else - break; - - return true; - } - } - - lua.Error("No matching overload for Rect constructor"); - return false; - }); - - rect.BindMethod("__tostring", &Nz::Rectd::ToString); - - rect.SetGetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - auto index = lua.CheckBoundInteger(2); - if (index < 1 || index > 4) - return false; - - lua.Push(instance[index - 1]); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xywh = lua.CheckString(2, &length); - - if (length != 1) - break; - - switch (xywh[0]) - { - case 'x': - lua.Push(instance.x); - return true; - - case 'y': - lua.Push(instance.y); - return true; - - case 'w': - lua.Push(instance.width); - return true; - - case 'h': - lua.Push(instance.height); - return true; - - default: - break; - } - break; - } - - default: - break; - } - - return false; - }); - - rect.SetSetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - auto index = lua.CheckBoundInteger(2); - if (index < 1 || index > 4) - return false; - - instance[index - 1] = lua.CheckNumber(2); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xywh = lua.CheckString(2, &length); - - if (length != 1) - break; - - double value = lua.CheckNumber(3); - - switch (xywh[0]) - { - case 'x': - instance.x = value; - return true; - - case 'y': - instance.y = value; - return true; - - case 'w': - instance.width = value; - return true; - - case 'h': - instance.height = value; - return true; - } - break; - } - - default: - break; - } - - return false; - }); - - /*********************************** Nz::Quaternion **********************************/ - quaternion.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* quaternion, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 4U); - - switch (argCount) - { - case 0: - Nz::PlacementNew(quaternion, Nz::Quaterniond::Zero()); - return true; - - case 1: - { - if (lua.IsOfType(1, "EulerAngles")) - Nz::PlacementNew(quaternion, *static_cast(lua.ToUserdata(1))); - else if (lua.IsOfType(1, "Quaternion")) - Nz::PlacementNew(quaternion, *static_cast(lua.ToUserdata(1))); - else - break; - - return true; - } - - case 2: - Nz::PlacementNew(quaternion, lua.CheckNumber(1), *static_cast(lua.CheckUserdata(2, "Vector3"))); - return true; - - case 4: - Nz::PlacementNew(quaternion, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3), lua.CheckNumber(4)); - return true; - - default: - break; - } - - lua.Error("No matching overload for Quaternion constructor"); - return false; - }); - - quaternion.BindMethod("__tostring", &Nz::Quaterniond::ToString); - - quaternion.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) - { - std::size_t length; - const char* wxyz = lua.CheckString(2, &length); - - if (length != 1) - return false; - - switch (wxyz[0]) - { - case 'w': - lua.Push(instance.w); - return true; - - case 'x': - lua.Push(instance.x); - return true; - - case 'y': - lua.Push(instance.y); - return true; - - case 'z': - lua.Push(instance.z); - return true; - } - - return false; - }); - - quaternion.SetSetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) - { - std::size_t length; - const char* wxyz = lua.CheckString(2, &length); - - if (length != 1) - return false; - - double value = lua.CheckNumber(3); - - switch (wxyz[0]) - { - case 'w': - instance.w = value; - return true; - - case 'x': - instance.x = value; - return true; - - case 'y': - instance.y = value; - return true; - - case 'z': - instance.z = value; - return true; - - default: - break; - } - - return false; - }); - - /*********************************** Nz::Vector2 **********************************/ - vector2d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector2d* vector, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 2U); - - switch (argCount) - { - case 0: - case 2: - Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0)); - return true; - - case 1: - { - if (lua.IsOfType(1, Nz::LuaType_Number)) - Nz::PlacementNew(vector, lua.CheckNumber(1)); - else if (lua.IsOfType(1, "Vector2")) - Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1))); - else - break; - - return true; - } - } - - lua.Error("No matching overload for Vector2 constructor"); - return false; - }); - - vector2d.BindMethod("__tostring", &Nz::Vector2d::ToString); - - vector2d.SetGetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - long long index = lua.CheckInteger(2); - if (index < 1 || index > 2) - return false; - - lua.Push(instance[index - 1]); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xy = lua.CheckString(2, &length); - - if (length != 1) - break; - - switch (xy[0]) - { - case 'x': - lua.Push(instance.x); - return true; - - case 'y': - lua.Push(instance.y); - return true; - - default: - break; - } - break; - } - - default: - break; - } - - return false; - }); - - vector2d.SetSetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - long long index = lua.CheckInteger(2); - if (index < 1 || index > 2) - return false; - - instance[index - 1] = lua.CheckNumber(3); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xy = lua.CheckString(2, &length); - - if (length != 1) - break; - - double value = lua.CheckNumber(3); - - switch (xy[0]) - { - case 'x': - instance.x = value; - return true; - - case 'y': - instance.y = value; - return true; - - default: - break; - } - break; - } - - default: - break; - } - - return false; - }); - - /*********************************** Nz::Vector3 **********************************/ - vector3d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector3d* vector, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 3U); - - switch (argCount) - { - case 0: - case 3: - Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0)); - return true; - - case 1: - { - if (lua.IsOfType(1, Nz::LuaType_Number)) - Nz::PlacementNew(vector, lua.CheckNumber(1)); - else if (lua.IsOfType(1, "Vector2")) - Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1))); - else if (lua.IsOfType(1, "Vector3")) - Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1))); - else - break; - - return true; - } - - case 2: - { - if (lua.IsOfType(1, Nz::LuaType_Number)) - Nz::PlacementNew(vector, lua.CheckNumber(1), *static_cast(lua.CheckUserdata(2, "Vector2"))); - else if (lua.IsOfType(1, "Vector2")) - Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1)), lua.CheckNumber(2)); - else - break; - - return true; - } - } - - lua.Error("No matching overload for constructor"); - return false; - }); - - vector3d.BindMethod("__tostring", &Nz::Vector3d::ToString); - - vector3d.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - long long index = lua.CheckInteger(2); - if (index < 1 || index > 3) - return false; - - lua.Push(instance[index - 1]); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xyz = lua.CheckString(2, &length); - - if (length != 1) - break; - - switch (xyz[0]) - { - case 'x': - lua.Push(instance.x); - return true; - - case 'y': - lua.Push(instance.y); - return true; - - case 'z': - lua.Push(instance.z); - return true; - - default: - break; - } - break; - } - - default: - break; - } - - return false; - }); - - vector3d.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - long long index = lua.CheckInteger(2); - if (index < 1 || index > 3) - return false; - - instance[index - 1] = lua.CheckNumber(3); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xyz = lua.CheckString(2, &length); - - if (length != 1) - break; - - double value = lua.CheckNumber(3); - - switch (xyz[0]) - { - case 'x': - instance.x = value; - return true; - - case 'y': - instance.y = value; - return true; - - case 'z': - instance.z = value; - return true; - - default: - break; - } - break; - } - - default: - break; - } - - return false; - }); - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Math classes - */ - - void LuaBinding::RegisterMath(Nz::LuaInstance& instance) - { - eulerAngles.Register(instance); - matrix4d.Register(instance); - quaternion.Register(instance); - rect.Register(instance); - vector2d.Register(instance); - vector3d.Register(instance); - } -} diff --git a/SDK/src/NDK/LuaBinding_Renderer.cpp b/SDK/src/NDK/LuaBinding_Renderer.cpp deleted file mode 100644 index 8ffe76c69..000000000 --- a/SDK/src/NDK/LuaBinding_Renderer.cpp +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot -// 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 -{ - /*! - * \brief Binds Renderer module to Lua - */ - void LuaBinding::BindRenderer() - { - /*********************************** Nz::Texture ***********************************/ - texture.Inherit(abstractImage, [] (Nz::TextureRef* texture) -> Nz::AbstractImageRef* - { - return reinterpret_cast(texture); //TODO: Make a ObjectRefCast - }); - - texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* texture, std::size_t /*argumentCount*/) - { - Nz::PlacementNew(texture, Nz::Texture::New()); - return true; - }); - - texture.BindMethod("Create", &Nz::Texture::Create, static_cast(1), 1U); - texture.BindMethod("Destroy", &Nz::Texture::Destroy); - - //texture.BindMethod("Download", &Nz::Texture::Download); - - texture.BindMethod("EnableMipmapping", &Nz::Texture::EnableMipmapping); - texture.BindMethod("EnsureMipmapsUpdate", &Nz::Texture::EnsureMipmapsUpdate); - texture.BindMethod("HasMipmaps", &Nz::Texture::HasMipmaps); - texture.BindMethod("InvalidateMipmaps", &Nz::Texture::InvalidateMipmaps); - texture.BindMethod("IsValid", &Nz::Texture::IsValid); - - texture.BindMethod("LoadFromFile", &Nz::Texture::LoadFromFile, true, Nz::ImageParams()); - //bool LoadFromImage(const Image& image, bool generateMipmaps = true); - //bool LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams(), bool generateMipmaps = true); - //bool LoadFromStream(Stream& stream, const ImageParams& params = ImageParams(), bool generateMipmaps = true); - - texture.BindMethod("LoadArrayFromFile", &Nz::Texture::LoadArrayFromFile, Nz::Vector2ui(2, 2), true, Nz::ImageParams()); - //bool LoadArrayFromImage(const Image& image, bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); - //bool LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); - //bool LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); - - //bool LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); - //bool LoadCubemapFromImage(const Image& image, bool generateMipmaps = true, const CubemapParams& params = CubemapParams()); - //bool LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); - //bool LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); - - texture.BindMethod("LoadFaceFromFile", &Nz::Texture::LoadFaceFromFile, Nz::ImageParams()); - //bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams()); - //bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams()); - - texture.BindMethod("SaveToFile", &Nz::Texture::SaveToFile, Nz::ImageParams()); - //bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams()); - - texture.BindMethod("SetMipmapRange", &Nz::Texture::SetMipmapRange); - - texture.BindStaticMethod("IsFormatSupported", &Nz::Texture::IsFormatSupported); - texture.BindStaticMethod("IsMipmappingSupported", &Nz::Texture::IsMipmappingSupported); - texture.BindStaticMethod("IsTypeSupported", &Nz::Texture::IsTypeSupported); - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Renderer classes - */ - void LuaBinding::RegisterRenderer(Nz::LuaInstance& instance) - { - texture.Register(instance); - } -} \ No newline at end of file diff --git a/SDK/src/NDK/LuaBinding_SDK.cpp b/SDK/src/NDK/LuaBinding_SDK.cpp deleted file mode 100644 index 3046f2483..000000000 --- a/SDK/src/NDK/LuaBinding_SDK.cpp +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot -// 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 -{ - /*! - * \brief Binds SDK module to Lua - */ - - void LuaBinding::BindSDK() - { - /*********************************** Ndk::Application **********************************/ - - #ifndef NDK_SERVER - //application.SetMethod("AddWindow", &Application::AddWindow); - - application.BindMethod("EnableConsole", &Application::EnableConsole); - application.BindMethod("EnableFPSCounter", &Application::EnableFPSCounter); - - application.BindMethod("IsConsoleEnabled", &Application::IsConsoleEnabled); - application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled); - #endif - - application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application, std::size_t /*argumentCount*/) -> int - { - instance.Push(application->AddWorld().CreateHandle()); - return 1; - }); - - application.BindMethod("GetUpdateTime", &Application::GetUpdateTime); - application.BindMethod("Quit", &Application::Quit); - - /*********************************** Ndk::Console **********************************/ - #ifndef NDK_SERVER - console.Inherit(node, [] (ConsoleHandle* handle) -> Nz::Node* - { - return handle->GetObject(); - }); - - console.BindMethod("AddLine", &Console::AddLine, Nz::Color::White); - console.BindMethod("Clear", &Console::Clear); - console.BindMethod("GetCharacterSize", &Console::GetCharacterSize); - console.BindMethod("GetHistory", &Console::GetHistory); - console.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground); - console.BindMethod("GetInput", &Console::GetInput); - console.BindMethod("GetInputBackground", &Console::GetInputBackground); - console.BindMethod("GetSize", &Console::GetSize); - console.BindMethod("GetTextFont", &Console::GetTextFont); - - console.BindMethod("IsVisible", &Console::IsVisible); - - console.BindMethod("SendCharacter", &Console::SendCharacter); - //consoleClass.SetMethod("SendEvent", &Console::SendEvent); - - console.BindMethod("SetCharacterSize", &Console::SetCharacterSize); - console.BindMethod("SetSize", &Console::SetSize); - console.BindMethod("SetTextFont", &Console::SetTextFont); - - console.BindMethod("Show", &Console::Show, true); - #endif - - /*********************************** Ndk::Entity **********************************/ - entity.BindMethod("Enable", &Entity::Enable, true); - entity.BindMethod("GetId", &Entity::GetId); - entity.BindMethod("GetWorld", &Entity::GetWorld); - entity.BindMethod("Kill", &Entity::Kill); - entity.BindMethod("IsEnabled", &Entity::IsEnabled); - entity.BindMethod("IsValid", &Entity::IsValid); - entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); - entity.BindMethod("__tostring", &EntityHandle::ToString); - - entity.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int - { - ComponentBinding* binding = QueryComponentIndex(instance); - - return binding->adder(instance, handle); - }); - - entity.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int - { - ComponentBinding* binding = QueryComponentIndex(instance); - - return binding->getter(instance, handle->GetComponent(binding->index)); - }); - - entity.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int - { - ComponentBinding* binding = QueryComponentIndex(instance); - - handle->RemoveComponent(binding->index); - return 0; - }); - - /*********************************** Ndk::NodeComponent **********************************/ - nodeComponent.Inherit(node, [] (NodeComponentHandle* handle) -> Nz::Node* - { - return handle->GetObject(); - }); - - /*********************************** Ndk::VelocityComponent **********************************/ - velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) - { - std::size_t length; - const char* member = lua.CheckString(2, &length); - - if (std::strcmp(member, "Linear") == 0) - { - lua.Push(instance->linearVelocity); - return true; - } - - return false; - }); - - velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) - { - std::size_t length; - const char* member = lua.CheckString(2, &length); - - int argIndex = 3; - if (std::strcmp(member, "Linear") == 0) - { - instance->linearVelocity = lua.Check(&argIndex); - return true; - } - - return false; - }); - - /*********************************** Ndk::World **********************************/ - world.BindMethod("CreateEntity", &World::CreateEntity); - world.BindMethod("CreateEntities", &World::CreateEntities); - world.BindMethod("Clear", &World::Clear); - - - #ifndef NDK_SERVER - /*********************************** Ndk::GraphicsComponent **********************************/ - graphicsComponent.BindMethod("Attach", [] (Nz::LuaInstance& lua, Ndk::GraphicsComponent *gfxComponent, std::size_t argumentCount) -> int - { - /* - void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0); - void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0); - */ - - std::size_t argCount = std::min(argumentCount, 3U); - - switch (argCount) - { - case 1: - { - int argIndex = 2; - gfxComponent->Attach(lua.Check(&argIndex)); - return 0; - } - - case 2: - { - int argIndex = 2; - Nz::InstancedRenderableRef renderable = lua.Check(&argIndex); - - if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - { - int renderOrder = lua.Check(&argIndex); - - gfxComponent->Attach(renderable, renderOrder); - } - else if (lua.IsOfType(argIndex, "Matrix4")) - { - Nz::Matrix4f localMatrix = lua.Check(&argIndex); - - gfxComponent->Attach(renderable, localMatrix); - } - else - break; - - return 0; - } - - case 3: - { - int argIndex = 2; - Nz::InstancedRenderableRef renderable = lua.Check(&argIndex); - Nz::Matrix4f localMatrix = lua.Check(&argIndex); - int renderOrder = lua.Check(&argIndex); - - gfxComponent->Attach(renderable, localMatrix, renderOrder); - return 0; - } - } - - lua.Error("No matching overload for method GetMemoryUsage"); - return 0; - }); - #endif - - - // Components functions - m_componentBinding.resize(BaseComponent::GetMaxComponentIndex()); - - BindComponent("Node"); - BindComponent("Velocity"); - - #ifndef NDK_SERVER - BindComponent("Graphics"); - #endif - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the SDK classes - */ - - void LuaBinding::RegisterSDK(Nz::LuaInstance& instance) - { - // Classes - application.Register(instance); - entity.Register(instance); - nodeComponent.Register(instance); - velocityComponent.Register(instance); - world.Register(instance); - - #ifndef NDK_SERVER - console.Register(instance); - graphicsComponent.Register(instance); - #endif - - // Enums - - // ComponentType (fake enumeration to expose component indexes) - instance.PushTable(0, m_componentBinding.size()); - { - for (const ComponentBinding& entry : m_componentBinding) - { - if (entry.name.IsEmpty()) - continue; - - instance.PushField(entry.name, entry.index); - } - } - instance.SetGlobal("ComponentType"); - } - - /*! - * \brief Gets the index of the component - * \return A pointer to the binding linked to a component - * - * \param instance Lua instance that will interact with the component - * \param argIndex Index of the component - */ - - LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex) - { - switch (instance.GetType(argIndex)) - { - case Nz::LuaType_Number: - { - ComponentIndex componentIndex = instance.Check(&argIndex); - if (componentIndex > m_componentBinding.size()) - { - instance.Error("Invalid component index"); - return nullptr; - } - - ComponentBinding& binding = m_componentBinding[componentIndex]; - if (binding.name.IsEmpty()) - { - instance.Error("Invalid component index"); - return nullptr; - } - - return &binding; - } - - case Nz::LuaType_String: - { - const char* key = instance.CheckString(argIndex); - auto it = m_componentBindingByName.find(key); - if (it == m_componentBindingByName.end()) - { - instance.Error("Invalid component name"); - return nullptr; - } - - return &m_componentBinding[it->second]; - } - - default: - break; - } - - instance.Error("Invalid component index at #" + Nz::String::Number(argIndex)); - return nullptr; - } -} diff --git a/SDK/src/NDK/LuaBinding_Utility.cpp b/SDK/src/NDK/LuaBinding_Utility.cpp deleted file mode 100644 index 5ae37f669..000000000 --- a/SDK/src/NDK/LuaBinding_Utility.cpp +++ /dev/null @@ -1,327 +0,0 @@ -// 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 -{ - /*! - * \brief Binds Utility module to Lua - */ - - void LuaBinding::BindUtility() - { - /*********************************** Nz::AbstractImage **********************************/ - abstractImage.BindMethod("GetBytesPerPixel", &Nz::AbstractImage::GetBytesPerPixel); - abstractImage.BindMethod("GetDepth", &Nz::AbstractImage::GetDepth, static_cast(0)); - abstractImage.BindMethod("GetFormat", &Nz::AbstractImage::GetFormat); - abstractImage.BindMethod("GetHeight", &Nz::AbstractImage::GetHeight, static_cast(0)); - abstractImage.BindMethod("GetLevelCount", &Nz::AbstractImage::GetLevelCount); - abstractImage.BindMethod("GetMaxLevel", &Nz::AbstractImage::GetMaxLevel); - abstractImage.BindMethod("GetSize", &Nz::AbstractImage::GetSize, static_cast(0)); - abstractImage.BindMethod("GetType", &Nz::AbstractImage::GetType); - abstractImage.BindMethod("GetWidth", &Nz::AbstractImage::GetWidth, static_cast(0)); - abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed); - abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap); - - abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 1U); - switch (argCount) - { - case 0: - return lua.Push(abstractImage->GetMemoryUsage()); - - case 1: - { - int argIndex = 2; - Nz::UInt8 level(lua.Check(&argIndex)); - - return lua.Push(abstractImage->GetMemoryUsage(level)); - } - } - - lua.Error("No matching overload for method GetMemoryUsage"); - return 0; - }); - - abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 6U); - int argIndex = 2; - - std::size_t bufferSize = 0; - const Nz::UInt8* pixels = reinterpret_cast(lua.CheckString(argIndex++, &bufferSize)); - - if (argCount < 2 || lua.IsOfType(2, Nz::LuaType_Number)) - { - // bool Update(const UInt8* pixels, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) - unsigned int srcWidth = lua.Check(&argIndex, 0); - unsigned int srcHeight = lua.Check(&argIndex, 0); - Nz::UInt8 level = lua.Check(&argIndex, 0); - - ///TODO: Buffer checks (Nz::ByteBufferView ?) - return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level)); - } - /* Disabled until Box and Rect have been ported - else if (lua.IsOfType(2, "Box")) - { - // bool Update(const UInt8* pixels, const Boxui& box, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) - Nz::Boxui box = lua.Check(&argIndex); - unsigned int srcWidth = lua.Check(&argIndex, 0); - unsigned int srcHeight = lua.Check(&argIndex, 0); - Nz::UInt8 level = lua.Check(&argIndex, 0); - - ///TODO: Buffer checks (Nz::ByteBufferView ?) - return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level)); - } - else if (lua.IsOfType(2, "Rect")) - { - // bool Update(const UInt8* pixels, const Rectui& rect, unsigned int z = 0, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) - Nz::Rectui box = lua.Check(&argIndex); - unsigned int srcWidth = lua.Check(&argIndex, 0); - unsigned int srcHeight = lua.Check(&argIndex, 0); - Nz::UInt8 level = lua.Check(&argIndex, 0); - - ///TODO: Buffer checks (Nz::ByteBufferView ?) - return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level)); - }*/ - - lua.Error("No matching overload for method Update"); - return 0; - }); - - /*********************************** Nz::Font **********************************/ - font.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::FontRef* font, std::size_t /*argumentCount*/) - { - Nz::PlacementNew(font, Nz::Font::New()); - return true; - }); - - font.BindMethod("ClearGlyphCache", &Nz::Font::ClearGlyphCache); - font.BindMethod("ClearKerningCache", &Nz::Font::ClearKerningCache); - font.BindMethod("ClearSizeInfoCache", &Nz::Font::ClearSizeInfoCache); - - font.BindMethod("Destroy", &Nz::Font::Destroy); - - font.BindMethod("GetCachedGlyphCount", [] (Nz::LuaInstance& lua, Nz::FontRef& instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 2U); - - int argIndex = 2; - switch (argCount) - { - case 0: - lua.Push(instance->GetCachedGlyphCount()); - return 1; - - case 2: - { - unsigned int characterSize = lua.Check(&argIndex); - Nz::UInt32 style = lua.Check(&argIndex); - - lua.Push(instance->GetCachedGlyphCount(characterSize, style)); - return 1; - } - } - - lua.Error("No matching overload for method GetCachedGlyphCount"); - return 0; - }); - - font.BindMethod("GetFamilyName", &Nz::Font::GetFamilyName); - font.BindMethod("GetKerning", &Nz::Font::GetKerning); - font.BindMethod("GetGlyphBorder", &Nz::Font::GetGlyphBorder); - font.BindMethod("GetMinimumStepSize", &Nz::Font::GetMinimumStepSize); - font.BindMethod("GetSizeInfo", &Nz::Font::GetSizeInfo); - font.BindMethod("GetStyleName", &Nz::Font::GetStyleName); - - font.BindMethod("IsValid", &Nz::Font::IsValid); - - font.BindMethod("Precache", (bool(Nz::Font::*)(unsigned int, Nz::UInt32, const Nz::String&) const) &Nz::Font::Precache); - - font.BindMethod("OpenFromFile", &Nz::Font::OpenFromFile, Nz::FontParams()); - - font.BindMethod("SetGlyphBorder", &Nz::Font::SetGlyphBorder); - font.BindMethod("SetMinimumStepSize", &Nz::Font::SetMinimumStepSize); - - font.BindStaticMethod("GetDefault", &Nz::Font::GetDefault); - font.BindStaticMethod("GetDefaultGlyphBorder", &Nz::Font::GetDefaultGlyphBorder); - font.BindStaticMethod("GetDefaultMinimumStepSize", &Nz::Font::GetDefaultMinimumStepSize); - - font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder); - font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize); - - /*********************************** Nz::Node **********************************/ - node.BindMethod("GetBackward", &Nz::Node::GetBackward); - //nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds); - node.BindMethod("GetDown", &Nz::Node::GetDown); - node.BindMethod("GetForward", &Nz::Node::GetForward); - node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); - node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); - node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); - node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); - //nodeClass.SetMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); - node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); - node.BindMethod("GetLeft", &Nz::Node::GetLeft); - node.BindMethod("GetNodeType", &Nz::Node::GetNodeType); - //nodeClass.SetMethod("GetParent", &Nz::Node::GetParent); - node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); - node.BindMethod("GetRight", &Nz::Node::GetRight); - //nodeClass.SetMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); - node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); - //nodeClass.SetMethod("GetTransformMatrix", &Nz::Node::GetTransformMatrix); - node.BindMethod("GetUp", &Nz::Node::GetUp); - - node.BindMethod("HasChilds", &Nz::Node::HasChilds); - - node.BindMethod("GetBackward", &Nz::Node::GetBackward); - node.BindMethod("GetDown", &Nz::Node::GetDown); - node.BindMethod("GetForward", &Nz::Node::GetForward); - node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); - node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); - node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); - node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); - node.BindMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); - node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); - node.BindMethod("GetLeft", &Nz::Node::GetLeft); - node.BindMethod("GetNodeType", &Nz::Node::GetNodeType); - node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); - node.BindMethod("GetRight", &Nz::Node::GetRight); - node.BindMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); - node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); - node.BindMethod("GetUp", &Nz::Node::GetUp); - - node.BindMethod("SetInitialPosition", (void(Nz::Node::*)(const Nz::Vector3f&)) &Nz::Node::SetInitialPosition); - node.BindMethod("SetInitialRotation", (void(Nz::Node::*)(const Nz::Quaternionf&)) &Nz::Node::SetInitialRotation); - - 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::LuaInstance& lua, Nz::Node& node, 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); - - return 0; - }); - - node.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& node, 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); - - return 0; - }); - - node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 4U); - - int argIndex = 2; - switch (argCount) - { - case 1: - { - if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - node.Scale(lua.Check(&argIndex)); - else - node.Scale(lua.Check(&argIndex)); - - return 0; - } - - case 3: - node.Scale(lua.Check(&argIndex)); - return 0; - } - - lua.Error("No matching overload for method Scale"); - return 0; - }); - - node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 4U); - - int argIndex = 2; - switch (argCount) - { - case 1: - case 2: - { - if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - { - float scale = lua.Check(&argIndex); - Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - node.SetScale(scale, coordSys); - } - else - node.SetScale(lua.Check(&argIndex)); - - return 0; - } - - case 3: - case 4: - { - Nz::Vector3f scale = lua.Check(&argIndex); - Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - - node.SetScale(scale, coordSys); - return 0; - } - } - - lua.Error("No matching overload for method SetScale"); - return 0; - }); - - node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 4U); - - int argIndex = 2; - switch (argCount) - { - case 1: - { - if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - node.SetInitialScale(lua.Check(&argIndex)); - else - node.SetInitialScale(lua.Check(&argIndex)); - - return 0; - } - - case 2: - case 3: - node.SetInitialScale(lua.Check(&argIndex)); - return 0; - } - - lua.Error("No matching overload for method SetInitialScale"); - return 0; - }); - } - - /*! - * \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::RegisterUtility(Nz::LuaInstance& instance) - { - abstractImage.Register(instance); - font.Register(instance); - node.Register(instance); - } -} \ No newline at end of file diff --git a/SDK/src/NDK/Sdk.cpp b/SDK/src/NDK/Sdk.cpp index 36283ada3..81080af06 100644 --- a/SDK/src/NDK/Sdk.cpp +++ b/SDK/src/NDK/Sdk.cpp @@ -9,14 +9,18 @@ #include #include #include +#include #include #include #include #include +#include #include #include +#include #include #include +#include #include #include @@ -68,6 +72,7 @@ namespace Ndk Nz::Lua::Initialize(); Nz::Noise::Initialize(); + Nz::Physics2D::Initialize(); Nz::Physics3D::Initialize(); Nz::Utility::Initialize(); @@ -83,9 +88,11 @@ namespace Ndk BaseComponent::Initialize(); // Shared components - InitializeComponent("NdkColli"); + InitializeComponent("NdkColl2"); + InitializeComponent("NdkColl3"); InitializeComponent("NdkNode"); - InitializeComponent("NdkPhys"); + InitializeComponent("NdkPhys2"); + InitializeComponent("NdkPhys3"); InitializeComponent("NdkVeloc"); #ifndef NDK_SERVER @@ -103,6 +110,7 @@ namespace Ndk BaseSystem::Initialize(); // Shared systems + InitializeSystem(); InitializeSystem(); InitializeSystem(); @@ -161,6 +169,7 @@ namespace Ndk // Shared modules Nz::Lua::Uninitialize(); Nz::Noise::Uninitialize(); + Nz::Physics2D::Uninitialize(); Nz::Physics3D::Uninitialize(); Nz::Utility::Uninitialize(); diff --git a/SDK/src/NDK/Systems/ListenerSystem.cpp b/SDK/src/NDK/Systems/ListenerSystem.cpp index 9c7333d34..3de647a08 100644 --- a/SDK/src/NDK/Systems/ListenerSystem.cpp +++ b/SDK/src/NDK/Systems/ListenerSystem.cpp @@ -25,6 +25,7 @@ namespace Ndk ListenerSystem::ListenerSystem() { Requires(); + SetUpdateOrder(100); //< Update last, after every movement is done } /*! @@ -33,11 +34,9 @@ namespace Ndk * \param elapsedTime Delta time used for the update */ - void ListenerSystem::OnUpdate(float elapsedTime) + void ListenerSystem::OnUpdate(float /*elapsedTime*/) { - NazaraUnused(elapsedTime); - - unsigned int activeListenerCount = 0; + std::size_t activeListenerCount = 0; for (const Ndk::EntityHandle& entity : GetEntities()) { diff --git a/SDK/src/NDK/Systems/PhysicsSystem2D.cpp b/SDK/src/NDK/Systems/PhysicsSystem2D.cpp new file mode 100644 index 000000000..adedfc170 --- /dev/null +++ b/SDK/src/NDK/Systems/PhysicsSystem2D.cpp @@ -0,0 +1,140 @@ +// Copyright (C) 2015 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 + +#include +#include +#include +#include +#include +#include + +namespace Ndk +{ + /*! + * \ingroup NDK + * \class Ndk::PhysicsSystem2D + * \brief NDK class that represents a two-dimensional physics system + * + * \remark This system is enabled if the entity has the trait: NodeComponent and any of these two: CollisionComponent3D or PhysicsComponent3D + * \remark Static objects do not have a velocity specified by the physical engine + */ + + /*! + * \brief Constructs an PhysicsSystem object by default + */ + + PhysicsSystem2D::PhysicsSystem2D() + { + Requires(); + RequiresAny(); + Excludes(); + } + + /*! + * \brief Constructs a PhysicsSystem object by copy semantic + * + * \param system PhysicsSystem to copy + */ + + PhysicsSystem2D::PhysicsSystem2D(const PhysicsSystem2D& system) : + System(system), + m_world() + { + } + + void PhysicsSystem2D::CreatePhysWorld() const + { + NazaraAssert(!m_world, "Physics world should not be created twice"); + + m_world = std::make_unique(); + } + + /*! + * \brief Operation to perform when entity is validated for the system + * + * \param entity Pointer to the entity + * \param justAdded Is the entity newly added + */ + + void PhysicsSystem2D::OnEntityValidation(Entity* entity, bool justAdded) + { + // It's possible our entity got revalidated because of the addition/removal of a PhysicsComponent3D + if (!justAdded) + { + // We take the opposite array from which the entity should belong to + auto& entities = (entity->HasComponent()) ? m_staticObjects : m_dynamicObjects; + entities.Remove(entity); + } + + auto& entities = (entity->HasComponent()) ? m_dynamicObjects : m_staticObjects; + entities.Insert(entity); + + if (!m_world) + CreatePhysWorld(); + } + + /*! + * \brief Operation to perform when system is updated + * + * \param elapsedTime Delta time used for the update + */ + + void PhysicsSystem2D::OnUpdate(float elapsedTime) + { + if (!m_world) + return; + + m_world->Step(elapsedTime); + + for (const Ndk::EntityHandle& entity : m_dynamicObjects) + { + NodeComponent& node = entity->GetComponent(); + PhysicsComponent2D& phys = entity->GetComponent(); + + Nz::RigidBody2D& body = phys.GetRigidBody(); + node.SetRotation(Nz::EulerAnglesf(0.f, 0.f, body.GetRotation()), Nz::CoordSys_Global); + node.SetPosition(Nz::Vector3f(body.GetPosition(), node.GetPosition(Nz::CoordSys_Global).z), Nz::CoordSys_Global); + } + + float invElapsedTime = 1.f / elapsedTime; + for (const Ndk::EntityHandle& entity : m_staticObjects) + { + CollisionComponent2D& collision = entity->GetComponent(); + NodeComponent& node = entity->GetComponent(); + + Nz::RigidBody2D* body = collision.GetStaticBody(); + + Nz::Vector2f oldPosition = body->GetPosition(); + Nz::Vector2f newPosition = Nz::Vector2f(node.GetPosition(Nz::CoordSys_Global)); + + // To move static objects and ensure their collisions, we have to specify them a velocity + // (/!\: the physical motor does not apply the speed on static objects) + if (newPosition != oldPosition) + { + body->SetPosition(newPosition); + body->SetVelocity((newPosition - oldPosition) * invElapsedTime); + } + else + body->SetVelocity(Nz::Vector2f::Zero()); + +/* + if (newRotation != oldRotation) + { + Nz::Quaternionf transition = newRotation * oldRotation.GetConjugate(); + Nz::EulerAnglesf angles = transition.ToEulerAngles(); + Nz::Vector3f angularVelocity(Nz::ToRadians(angles.pitch * invElapsedTime), + Nz::ToRadians(angles.yaw * invElapsedTime), + Nz::ToRadians(angles.roll * invElapsedTime)); + + physObj->SetRotation(oldRotation); + physObj->SetAngularVelocity(angularVelocity); + } + else + physObj->SetAngularVelocity(Nz::Vector3f::Zero()); +*/ + } + } + + SystemIndex PhysicsSystem2D::systemIndex; +} diff --git a/SDK/src/NDK/Systems/PhysicsSystem3D.cpp b/SDK/src/NDK/Systems/PhysicsSystem3D.cpp index fd5e05d66..c26c932e0 100644 --- a/SDK/src/NDK/Systems/PhysicsSystem3D.cpp +++ b/SDK/src/NDK/Systems/PhysicsSystem3D.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace Ndk @@ -27,6 +28,7 @@ namespace Ndk { Requires(); RequiresAny(); + Excludes(); } /*! @@ -90,7 +92,7 @@ namespace Ndk NodeComponent& node = entity->GetComponent(); PhysicsComponent3D& phys = entity->GetComponent(); - Nz::RigidBody3D& physObj = phys.GetPhysObject(); + Nz::RigidBody3D& physObj = phys.GetRigidBody(); node.SetRotation(physObj.GetRotation(), Nz::CoordSys_Global); node.SetPosition(physObj.GetPosition(), Nz::CoordSys_Global); } diff --git a/SDK/src/NDK/Systems/RenderSystem.cpp b/SDK/src/NDK/Systems/RenderSystem.cpp index fbc2d3e08..bdbb6cb5b 100644 --- a/SDK/src/NDK/Systems/RenderSystem.cpp +++ b/SDK/src/NDK/Systems/RenderSystem.cpp @@ -28,14 +28,15 @@ namespace Ndk /*! * \brief Constructs an RenderSystem object by default */ - RenderSystem::RenderSystem() : m_coordinateSystemMatrix(Nz::Matrix4f::Identity()), - m_coordinateSystemInvalidated(true) + m_coordinateSystemInvalidated(true), + m_forceRenderQueueInvalidation(false) { ChangeRenderTechnique(); SetDefaultBackground(Nz::ColorBackground::New()); - SetUpdateRate(0.f); + SetUpdateOrder(100); //< Render last, after every movement is done + SetUpdateRate(0.f); //< We don't want any rate limit } /*! @@ -43,15 +44,22 @@ namespace Ndk * * \param entity Pointer to the entity */ - void RenderSystem::OnEntityRemoved(Entity* entity) { + m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list + m_cameras.Remove(entity); m_directionalLights.Remove(entity); m_drawables.Remove(entity); m_lights.Remove(entity); m_particleGroups.Remove(entity); m_pointSpotLights.Remove(entity); + + if (entity->HasComponent()) + { + GraphicsComponent& gfxComponent = entity->GetComponent(); + gfxComponent.RemoveFromCullingList(&m_drawableCulling); + } } /*! @@ -60,7 +68,6 @@ namespace Ndk * \param entity Pointer to the entity * \param justAdded Is the entity newly added */ - void RenderSystem::OnEntityValidation(Entity* entity, bool justAdded) { NazaraUnused(justAdded); @@ -77,12 +84,30 @@ namespace Ndk m_cameras.Remove(entity); if (entity->HasComponent() && entity->HasComponent()) + { m_drawables.Insert(entity); + + if (justAdded) + { + GraphicsComponent& gfxComponent = entity->GetComponent(); + gfxComponent.AddToCullingList(&m_drawableCulling); + } + } else + { m_drawables.Remove(entity); + if (entity->HasComponent()) + { + GraphicsComponent& gfxComponent = entity->GetComponent(); + gfxComponent.RemoveFromCullingList(&m_drawableCulling); + } + } + if (entity->HasComponent() && entity->HasComponent()) { + m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list + LightComponent& lightComponent = entity->GetComponent(); if (lightComponent.GetLightType() == Nz::LightType_Directional) { @@ -99,15 +124,25 @@ namespace Ndk } else { + m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list + m_directionalLights.Remove(entity); m_lights.Remove(entity); m_pointSpotLights.Remove(entity); } if (entity->HasComponent()) + { + m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list + m_particleGroups.Insert(entity); + } else + { + m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list + m_particleGroups.Remove(entity); + } } /*! @@ -116,10 +151,8 @@ namespace Ndk * \param elapsedTime Delta time used for the update */ - void RenderSystem::OnUpdate(float elapsedTime) + void RenderSystem::OnUpdate(float /*elapsedTime*/) { - NazaraUnused(elapsedTime); - // Invalidate every renderable if the coordinate system changed if (m_coordinateSystemInvalidated) { @@ -141,30 +174,45 @@ namespace Ndk //UpdateDirectionalShadowMaps(camComponent); Nz::AbstractRenderQueue* renderQueue = m_renderTechnique->GetRenderQueue(); - renderQueue->Clear(); - //TODO: Culling + // To make sure the bounding volume used by the culling list is updated for (const Ndk::EntityHandle& drawable : m_drawables) { GraphicsComponent& graphicsComponent = drawable->GetComponent(); - - graphicsComponent.AddToRenderQueue(renderQueue); + graphicsComponent.EnsureBoundingVolumeUpdate(); } + + bool forceInvalidation = false; - for (const Ndk::EntityHandle& light : m_lights) + std::size_t visibilityHash = m_drawableCulling.Cull(camComponent.GetFrustum(), &forceInvalidation); + + // Always regenerate renderqueue if particle groups are present for now (FIXME) + if (!m_particleGroups.empty()) + forceInvalidation = true; + + if (camComponent.UpdateVisibility(visibilityHash) || m_forceRenderQueueInvalidation || forceInvalidation) { - LightComponent& lightComponent = light->GetComponent(); - NodeComponent& lightNode = light->GetComponent(); + renderQueue->Clear(); + for (const GraphicsComponent* gfxComponent : m_drawableCulling) + gfxComponent->AddToRenderQueue(renderQueue); - ///TODO: Cache somehow? - lightComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::ConcatenateAffine(m_coordinateSystemMatrix, lightNode.GetTransformMatrix())); - } + for (const Ndk::EntityHandle& light : m_lights) + { + LightComponent& lightComponent = light->GetComponent(); + NodeComponent& lightNode = light->GetComponent(); - for (const Ndk::EntityHandle& particleGroup : m_particleGroups) - { - ParticleGroupComponent& groupComponent = particleGroup->GetComponent(); + ///TODO: Cache somehow? + lightComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::ConcatenateAffine(m_coordinateSystemMatrix, lightNode.GetTransformMatrix())); + } - groupComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::Identity()); //< ParticleGroup doesn't use Matrix4f + for (const Ndk::EntityHandle& particleGroup : m_particleGroups) + { + ParticleGroupComponent& groupComponent = particleGroup->GetComponent(); + + groupComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::Identity()); //< ParticleGroup doesn't use any transform matrix (yet) + } + + m_forceRenderQueueInvalidation = false; } camComponent.ApplyView(); diff --git a/SDK/src/NDK/Systems/VelocitySystem.cpp b/SDK/src/NDK/Systems/VelocitySystem.cpp index c1298bde3..bc8042cd7 100644 --- a/SDK/src/NDK/Systems/VelocitySystem.cpp +++ b/SDK/src/NDK/Systems/VelocitySystem.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -14,8 +15,8 @@ namespace Ndk * \class Ndk::VelocitySystem * \brief NDK class that represents the velocity system * - * \remark This system is enabled if the entity owns the trait: NodeComponent and VelocityComponent - * but it's disabled with the trait: PhysicsComponent3D + * \remark This system is enabled if the entity owns the traits NodeComponent and VelocityComponent + * but it's disabled with the traits: PhysicsComponent2D, PhysicsComponent3D */ /*! @@ -24,8 +25,9 @@ namespace Ndk VelocitySystem::VelocitySystem() { + Excludes(); Requires(); - Excludes(); + SetUpdateOrder(10); //< Since some systems may want to stop us } /*! diff --git a/SDK/src/NDK/World.cpp b/SDK/src/NDK/World.cpp index 6ba110aee..78b250aaf 100644 --- a/SDK/src/NDK/World.cpp +++ b/SDK/src/NDK/World.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -40,6 +41,7 @@ namespace Ndk void World::AddDefaultSystems() { + AddSystem(); AddSystem(); AddSystem(); @@ -67,7 +69,7 @@ namespace Ndk else { // We allocate a new entity - id = m_entities.size(); + id = static_cast(m_entities.size()); // We can't use emplace_back due to the scope m_entities.push_back(Entity(this, id)); @@ -172,6 +174,9 @@ namespace Ndk void World::Update() { + if (!m_orderedSystemsUpdated) + ReorderSystems(); + // Handle killed entities before last call for (std::size_t i = m_killedEntities.FindFirst(); i != m_killedEntities.npos; i = m_killedEntities.FindNext(i)) { @@ -218,15 +223,11 @@ namespace Ndk Nz::Bitset<>& removedComponents = entity->GetRemovedComponentBits(); for (std::size_t j = removedComponents.FindFirst(); j != m_dirtyEntities.npos; j = removedComponents.FindNext(j)) - entity->DestroyComponent(j); + entity->DestroyComponent(static_cast(j)); removedComponents.Reset(); - for (auto& system : m_systems) + for (auto& system : m_orderedSystems) { - // Ignore non-existent systems - if (!system) - continue; - // Is our entity already part of this system? bool partOfSystem = system->HasEntity(entity); @@ -249,4 +250,22 @@ namespace Ndk } m_dirtyEntities.Reset(); } + + void World::ReorderSystems() + { + m_orderedSystems.clear(); + + for (auto& systemPtr : m_systems) + { + if (systemPtr) + m_orderedSystems.push_back(systemPtr.get()); + } + + std::sort(m_orderedSystems.begin(), m_orderedSystems.end(), [] (BaseSystem* first, BaseSystem* second) + { + return first->GetUpdateOrder() < second->GetUpdateOrder(); + }); + + m_orderedSystemsUpdated = true; + } } diff --git a/build/Build_CodeBlocks.bat b/build/Build_CodeBlocks.bat index 439c5efac..5e6c23c44 100644 --- a/build/Build_CodeBlocks.bat +++ b/build/Build_CodeBlocks.bat @@ -1 +1 @@ -premake4 codeblocks \ No newline at end of file +premake5 codeblocks \ No newline at end of file diff --git a/build/scripts/actions/codeblocks.lua b/build/scripts/actions/codeblocks.lua new file mode 100644 index 000000000..f96a6d591 --- /dev/null +++ b/build/scripts/actions/codeblocks.lua @@ -0,0 +1,4 @@ +dofile("codeblocks/_codeblocks.lua") +dofile("codeblocks/codeblocks.lua") + +ACTION.Manual = true diff --git a/build/scripts/actions/codeblocks/_codeblocks.lua b/build/scripts/actions/codeblocks/_codeblocks.lua new file mode 100644 index 000000000..6a52bc404 --- /dev/null +++ b/build/scripts/actions/codeblocks/_codeblocks.lua @@ -0,0 +1,44 @@ +-- +-- _codeblocks.lua +-- Define the Code::Blocks action(s). +-- Copyright (c) 2002-2011 Jason Perkins and the Premake project +-- + local p = premake + + p.modules.codeblocks = {} + p.modules.codeblocks._VERSION = p._VERSION + + local codeblocks = p.modules.codeblocks + + newaction { + trigger = "codeblocks", + shortname = "Code::Blocks", + description = "Generate Code::Blocks project files", + + valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib" }, + + valid_languages = { "C", "C++" }, + + valid_tools = { + cc = { "clang", "gcc", "ow" }, + }, + + onWorkspace = function(wks) + p.modules.codeblocks.generateWorkspace(wks) + end, + + onProject = function(prj) + p.modules.codeblocks.generateProject(prj) + end, + + onCleanWorkspace = function(wks) + p.clean.file(wks, wks.name .. ".workspace") + p.clean.file(wks, wks.name .. ".workspace.layout") + end, + + onCleanProject = function(prj) + p.clean.file(prj, prj.name .. ".workspace") + p.clean.file(prj, prj.name .. ".depend") + p.clean.file(prj, prj.name .. ".layout") + end + } diff --git a/build/scripts/actions/codeblocks/codeblocks.lua b/build/scripts/actions/codeblocks/codeblocks.lua new file mode 100644 index 000000000..ebd8d11fa --- /dev/null +++ b/build/scripts/actions/codeblocks/codeblocks.lua @@ -0,0 +1,67 @@ +-- +-- codeblocks_workspace.lua +-- Generate a Code::Blocks workspace. +-- Copyright (c) 2009 Jason Perkins and the Premake project +-- + + local p = premake + + p.modules.codeblocks = {} + p.modules.codeblocks._VERSION = p._VERSION + + local codeblocks = p.modules.codeblocks + local project = p.project + + + function codeblocks.cfgname(cfg) + local cfgname = cfg.buildcfg + if codeblocks.workspace.multiplePlatforms then + cfgname = string.format("%s|%s", cfg.platform, cfg.buildcfg) + end + return cfgname + end + + function codeblocks.esc(value) + local result = value:gsub('"', '"') + result = result:gsub('<', '<') + result = result:gsub('>', '>') + return result + end + + function codeblocks.generateWorkspace(wks) + p.eol("\r\n") + p.indent("\t") + p.escaper(codeblocks.esc) + + p.generate(wks, ".workspace", codeblocks.workspace.generate) + end + + function codeblocks.generateProject(prj) + p.eol("\r\n") + p.indent("\t") + p.escaper(codeblocks.esc) + + if project.iscpp(prj) then + p.generate(prj, ".cbp", codeblocks.project.generate) + end + end + + function codeblocks.cleanWorkspace(wks) + p.clean.file(wks, wks.name .. ".workspace") + p.clean.file(wks, wks.name .. ".workspace.layout") + end + + function codeblocks.cleanProject(prj) + p.clean.file(prj, prj.name .. ".workspace") + p.clean.file(prj, prj.name .. ".depend") + p.clean.file(prj, prj.name .. ".layout") + end + + function codeblocks.cleanTarget(prj) + -- TODO.. + end + + include("codeblocks_workspace.lua") + include("codeblocks_project.lua") + + diff --git a/build/scripts/actions/codeblocks/codeblocks_project.lua b/build/scripts/actions/codeblocks/codeblocks_project.lua new file mode 100644 index 000000000..acfede4c2 --- /dev/null +++ b/build/scripts/actions/codeblocks/codeblocks_project.lua @@ -0,0 +1,243 @@ +-- +-- codeblocks_cbp.lua +-- Generate a Code::Blocks C/C++ project. +-- Copyright (c) 2009, 2011 Jason Perkins and the Premake project +-- + + local p = premake + local project = p.project + local config = p.config + local tree = p.tree + local codeblocks = p.modules.codeblocks + + codeblocks.project = {} + local m = codeblocks.project + m.elements = {} + + m.ctools = { + gcc = "gcc", + msc = "Visual C++", + } + + function m.getcompilername(cfg) + local tool = _OPTIONS.cc or cfg.toolset or p.GCC + + local toolset = p.tools[tool] + if not toolset then + error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'") + end + + return m.ctools[tool] + end + + function m.getcompiler(cfg) + local toolset = p.tools[_OPTIONS.cc or cfg.toolset or p.GCC] + if not toolset then + error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'") + end + return toolset + end + + function m.header(prj) + _p('') + _p('') + _p(1,'') + + -- write project block header + _p(1,'') + _p(2,'') + _p('') + end + + m.elements.project = function(prj) + return { + m.header, + m.configurations, + m.files, + m.extensions, + m.footer + } + end + +-- +-- Project: Generate the CodeBlocks project file. +-- + function m.generate(prj) + p.utf8() + + p.callArray(m.elements.project, prj) + end + + function m.configurations(prj) + -- write configuration blocks + _p(2,'') + local platforms = {} + for cfg in project.eachconfig(prj) do + local found = false + for k,v in pairs(platforms) do + if (v.platform == cfg.platform) then + table.insert(v.configs, cfg) + found = true + break + end + end + + if (not found) then + table.insert(platforms, {platform = cfg.platform, configs = {cfg}}) + end + end + + for k,platform in pairs(platforms) do + for k,cfg in pairs(platform.configs) do + local compiler = m.getcompiler(cfg) + + _p(3,'', cfg.longname) + + _p(4,'') + end + end + _p(2,'') + end + +-- +-- Write out a list of the source code files in the project. +-- + + function m.files(prj) + local pchheader + if (prj.pchheader) then + pchheader = path.getrelative(prj.location, prj.pchheader) + end + + local tr = project.getsourcetree(prj) + tree.traverse(tr, { + -- source files are handled at the leaves + onleaf = function(node, depth) + if node.relpath == node.vpath then + _p(2,'', node.relpath) + else + _p(2,'', node.name) + _p(3,'') + + end, + }, false, 1) + end + + function m.extensions(prj) + for cfg in project.eachconfig(prj) do + if cfg.debugenvs and #cfg.debugenvs > 0 then + --Assumption: if gcc is being used then so is gdb although this section will be ignored by + --other debuggers. If using gcc and not gdb it will silently not pass the + --environment arguments to the debugger + if m.getcompilername(cfg) == "gcc" then + _p(3,'') + _p(4,'', p.esc(cfg.longname)) + local args = '' + local sz = #cfg.debugenvs + for idx, v in ipairs(cfg.debugenvs) do + args = args .. 'set env ' .. v + if sz ~= idx then args = args .. ' ' end + end + _p(5,'',args) + _p(4,'') + _p(3,'') + else + error('Sorry at this moment there is no support for debug environment variables with this debugger and codeblocks') + end + end + end + end diff --git a/build/scripts/actions/codeblocks/codeblocks_workspace.lua b/build/scripts/actions/codeblocks/codeblocks_workspace.lua new file mode 100644 index 000000000..3de935877 --- /dev/null +++ b/build/scripts/actions/codeblocks/codeblocks_workspace.lua @@ -0,0 +1,44 @@ +-- +-- Name: codelite/codelite_workspace.lua +-- Purpose: Generate a CodeLite workspace. +-- Author: Ryan Pusztai +-- Modified by: Andrea Zanellato +-- Manu Evans +-- Created: 2013/05/06 +-- Copyright: (c) 2008-2015 Jason Perkins and the Premake project +-- + + local p = premake + local project = p.project + local workspace = p.workspace + local tree = p.tree + local codeblocks = p.modules.codeblocks + + codeblocks.workspace = {} + local m = codeblocks.workspace + +-- +-- Generate a CodeBlocks workspace +-- + function m.generate(wks) + p.utf8() + + _p('') + _p('') + _p(1,'', wks.name) + + for prj in workspace.eachproject(wks) do + local fname = path.join(path.getrelative(wks.location, prj.location), prj.name) + local active = iif(prj.project == wks.projects[1], ' active="1"', '') + + _p(2,'', fname, active) + for _,dep in ipairs(project.getdependencies(prj)) do + _p(3,'', path.join(path.getrelative(wks.location, dep.location), dep.name)) + end + + _p(2,'') + end + + _p(1,'') + _p('') + end \ No newline at end of file diff --git a/build/scripts/actions/generateheaders.lua b/build/scripts/actions/generateheaders.lua index 9c253dcac..2e35f8226 100644 --- a/build/scripts/actions/generateheaders.lua +++ b/build/scripts/actions/generateheaders.lua @@ -76,7 +76,7 @@ ACTION.Function = function () error("Failed to create header file (" .. v.Target .. "): " .. err) end - header:write("// This file was automatically generated on " .. os.date("%d %b %Y at %X") .. "\n\n") + header:write("// This file was automatically generated\n\n") if (v.Header) then header:write(v.Header) end diff --git a/build/scripts/common.lua b/build/scripts/common.lua index 423ebad0d..01b51562d 100644 --- a/build/scripts/common.lua +++ b/build/scripts/common.lua @@ -1,4 +1,7 @@ -NazaraBuild = {} -- L'équivalent d'un namespace en Lua est une table +NazaraBuild = {} + +-- I wish Premake had a way to know the compiler in advance +local clangGccActions = "action:" .. table.concat({"codeblocks", "codelite", "gmake", "xcode3", "xcode4"}, " or ") function NazaraBuild:AddExecutablePath(path) self.ExecutableDir[path] = true @@ -9,21 +12,47 @@ function NazaraBuild:AddInstallPath(path) self.InstallDir[path] = true end +function NazaraBuild:FilterLibDirectory(prefix, func) + filter({"action:codeblocks or codelite or gmake", "architecture:x86", "system:Windows"}) + func(prefix .. "mingw/x86") + + filter({"action:codeblocks or codelite or gmake", "architecture:x86_64", "system:Windows"}) + func(prefix .. "mingw/x64") + + filter({"action:codeblocks or codelite or gmake", "architecture:x86", "system:not Windows"}) + func(prefix .. "gmake/x86") + + filter({"action:codeblocks or codelite or gmake", "architecture:x86_64", "system:not Windows"}) + func(prefix .. "gmake/x64") + + filter({"action:vs*", "architecture:x86"}) + func(prefix .. "msvc/x86") + + filter({"action:vs*", "architecture:x86_64"}) + func(prefix .. "msvc/x64") + + filter({"action:xcode3 or xcode4", "architecture:x86"}) + func(prefix .. "xcode/x86") + + filter({"action:xcode3 or xcode4", "architecture:x86_64"}) + func(prefix .. "xcode/x64") + + filter({}) +end + function NazaraBuild:Execute() - if (_ACTION == nil) then -- Si aucune action n'est spécifiée + 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 end local platformData if (os.is64bit()) then - platformData = {"x64", "x32"} + platformData = {"x64", "x86"} else - platformData = {"x32", "x64"} + platformData = {"x86", "x64"} end if (self.Actions[_ACTION] == nil) then - local makeLibDir = os.is("windows") and "mingw" or "gmake" - if (self.Config["BuildDependencies"]) then workspace("NazaraExtlibs") platforms(platformData) @@ -34,63 +63,19 @@ function NazaraBuild:Execute() "ReleaseStatic" }) + self:PrepareGeneric() + self:FilterLibDirectory("../extlibs/lib/", targetdir) + + filter(clangGccActions) + buildoptions("-U__STRICT_ANSI__") + + filter({}) + includedirs("../extlibs/include") libdirs("../extlibs/lib/common") location(_ACTION) kind("StaticLib") - configuration({"codeblocks or codelite or gmake", "x32"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x86") - targetdir("../extlibs/lib/" .. makeLibDir .. "/x86") - - configuration({"codeblocks or codelite or gmake", "x64"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x64") - targetdir("../extlibs/lib/" .. makeLibDir .. "/x64") - - configuration("vs*") - buildoptions({"/MP", "/bigobj"}) -- Multiprocessus build and big .obj - - configuration({"vs*", "x32"}) - libdirs("../extlibs/lib/msvc/x86") - targetdir("../extlibs/lib/msvc/x86") - - configuration({"vs*", "x64"}) - libdirs("../extlibs/lib/msvc/x64") - targetdir("../extlibs/lib/msvc/x64") - - configuration({"xcode3 or xcode4", "x32"}) - libdirs("../extlibs/lib/xcode/x86") - targetdir("../extlibs/lib/xcode/x86") - - configuration({"xcode3 or xcode4", "x64"}) - libdirs("../extlibs/lib/xcode/x64") - targetdir("../extlibs/lib/xcode/x64") - - configuration("Debug*") - flags("Symbols") - - configuration("Release*") - flags("NoFramePointer") - optimize("Speed") - rtti("Off") - vectorextensions("SSE2") - - configuration({"Release*", "codeblocks or codelite or gmake or xcode3 or xcode4"}) - buildoptions("-mfpmath=sse") -- Utilisation du SSE pour les calculs flottants - buildoptions("-ftree-vectorize") -- Activation de la vectorisation du code - - configuration("DebugStatic") - targetsuffix("-s-d") - - configuration("ReleaseStatic") - targetsuffix("-s") - - configuration({"not windows", "codeblocks or codelite or gmake or xcode3 or xcode4"}) - buildoptions("-fPIC") - - configuration("codeblocks or codelite or gmake or xcode3 or xcode4") - buildoptions({"-std=c++14", "-U__STRICT_ANSI__"}) - for k, libTable in ipairs(self.OrderedExtLibs) do project(libTable.Name) @@ -105,25 +90,30 @@ function NazaraBuild:Execute() includedirs(libTable.Includes) links(libTable.Libraries) - configuration("x32") + filter("architecture:x86") libdirs(libTable.LibraryPaths.x86) - configuration("x64") + filter("architecture:x86_64") libdirs(libTable.LibraryPaths.x64) for k,v in pairs(libTable.ConfigurationLibraries) do - configuration(k) - links(v) + filter(k) + links(v) end - configuration({}) + filter({}) end end - + + -- Start defining projects workspace("NazaraEngine") platforms(platformData) - -- Configuration générale + self:PrepareMainWorkspace() + + -- Add lib/conf/arch to library search path + self:FilterLibDirectory("../lib/", libdirs) + configurations({ -- "DebugStatic", -- "ReleaseStatic", @@ -134,36 +124,7 @@ function NazaraBuild:Execute() language("C++") location(_ACTION) - configuration("Debug*") - defines("NAZARA_DEBUG") - flags("Symbols") - - configuration("Release*") - flags("NoFramePointer") - optimize("Speed") - vectorextensions("SSE2") - - configuration({"Release*", "codeblocks or codelite or gmake or xcode3 or xcode4"}) - buildoptions("-mfpmath=sse") -- Utilisation du SSE pour les calculs flottants - buildoptions("-ftree-vectorize") -- Activation de la vectorisation du code - - configuration("*Static") - defines("NAZARA_STATIC") - - configuration("codeblocks or codelite or gmake or xcode3 or xcode4") - buildoptions("-std=c++14") - - configuration({"linux or bsd or macosx", "gmake"}) - buildoptions("-fvisibility=hidden") - - configuration("vs*") - buildoptions({"/MP", "/bigobj"}) -- Multiprocessus build and big .obj - flags("NoMinimalRebuild") - defines("_CRT_SECURE_NO_WARNINGS") - defines("_SCL_SECURE_NO_WARNINGS") - - - -- Spécification des modules + -- Modules if (_OPTIONS["united"]) then project("NazaraEngine") end @@ -175,78 +136,12 @@ function NazaraBuild:Execute() location(_ACTION .. "/modules") - defines("NAZARA_BUILD") - includedirs({ "../include", "../src/", "../extlibs/include" }) - libdirs("../lib") - libdirs("../extlibs/lib/common") - - configuration("x32") - libdirs(moduleTable.LibraryPaths.x86) - - configuration("x64") - defines("NAZARA_PLATFORM_x64") - libdirs(moduleTable.LibraryPaths.x64) - - configuration({"codeblocks or codelite or gmake", "x32"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x86") - libdirs("../lib/" .. makeLibDir .. "/x86") - targetdir("../lib/" .. makeLibDir .. "/x86") - - configuration({"codeblocks or codelite or gmake", "x64"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x64") - libdirs("../lib/" .. makeLibDir .. "/x64") - targetdir("../lib/" .. makeLibDir .. "/x64") - - -- Copy the module binaries to the example folder - self:MakeInstallCommands(moduleTable) - - configuration({"vs*", "x32"}) - libdirs("../extlibs/lib/msvc/x86") - libdirs("../lib/msvc/x86") - targetdir("../lib/msvc/x86") - - configuration({"vs*", "x64"}) - libdirs("../extlibs/lib/msvc/x64") - libdirs("../lib/msvc/x64") - targetdir("../lib/msvc/x64") - - configuration({"xcode3 or xcode4", "x32"}) - libdirs("../extlibs/lib/xcode/x86") - libdirs("../lib/xcode/x86") - targetdir("../lib/xcode/x86") - - configuration({"xcode3 or xcode4", "x64"}) - libdirs("../extlibs/lib/xcode/x64") - libdirs("../lib/xcode/x64") - targetdir("../lib/xcode/x64") - - configuration("*Static") - defines("NAZARA_STATIC") - kind("StaticLib") - - configuration("*Dynamic") - kind("SharedLib") - - configuration("DebugStatic") - targetsuffix("-s-d") - - configuration("ReleaseStatic") - targetsuffix("-s") - - configuration("DebugDynamic") - targetsuffix("-d") - - configuration("Release*") - rtti(moduleTable.EnableRTTI and "On" or "Off") - - configuration({}) - files(moduleTable.Files) excludes(moduleTable.FilesExcluded) @@ -255,12 +150,29 @@ function NazaraBuild:Execute() includedirs(moduleTable.Includes) links(moduleTable.Libraries) + libdirs({ + "../extlibs/lib/common", + "../lib" + }) + + -- Output to lib/conf/arch + self:FilterLibDirectory("../lib/", targetdir) + + -- Copy the module binaries to the example folder + self:MakeInstallCommands(moduleTable) + + filter("architecture:x86") + libdirs(moduleTable.LibraryPaths.x86) + + filter("architecture:x86_64") + libdirs(moduleTable.LibraryPaths.x64) + for k,v in pairs(moduleTable.ConfigurationLibraries) do - configuration(k) + filter(k) links(v) end - configuration({}) + filter({}) end -- Tools @@ -288,7 +200,7 @@ function NazaraBuild:Execute() kind("WindowedApp") end else - assert(false, "Invalid tool Kind") + assert(false, "Invalid tool kind") end includedirs({ @@ -296,94 +208,10 @@ function NazaraBuild:Execute() "../extlibs/include" }) - libdirs("../lib") - libdirs("../extlibs/lib/common") - - configuration("x32") - libdirs(toolTable.LibraryPaths.x86) - - configuration("x64") - defines("NAZARA_PLATFORM_x64") - libdirs(toolTable.LibraryPaths.x64) - - configuration({"codeblocks or codelite or gmake", "x32"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x86") - libdirs("../lib/" .. makeLibDir .. "/x86") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/" .. makeLibDir .. "/x86") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/" .. makeLibDir .. "/x86") - end - - configuration({"codeblocks or codelite or gmake", "x64"}) - libdirs("../extlibs/lib/" .. makeLibDir .. "/x64") - libdirs("../lib/" .. makeLibDir .. "/x64") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/" .. makeLibDir .. "/x64") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/" .. makeLibDir .. "/x64") - end - - configuration({"vs*", "x32"}) - libdirs("../extlibs/lib/msvc/x86") - libdirs("../lib/msvc/x86") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/msvc/x86") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/msvc/x86") - end - - configuration({"vs*", "x64"}) - libdirs("../extlibs/lib/msvc/x64") - libdirs("../lib/msvc/x64") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/msvc/x64") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/msvc/x64") - end - - configuration({"xcode3 or xcode4", "x32"}) - libdirs("../extlibs/lib/xcode/x86") - libdirs("../lib/xcode/x86") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/xcode/x86") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/xcode/x86") - end - - configuration({"xcode3 or xcode4", "x64"}) - libdirs("../extlibs/lib/xcode/x64") - libdirs("../lib/xcode/x64") - if (toolTable.Kind == "library") then - targetdir(toolTable.TargetDirectory .. "/xcode/x64") - elseif (toolTable.Kind == "plugin") then - targetdir("../plugins/lib/xcode/x64") - end - - configuration("*Static") - defines("NAZARA_STATIC") - - configuration("Release*") - rtti(toolTable.EnableRTTI and "On" or "Off") - - if (toolTable.Kind == "library" or toolTable.Kind == "plugin") then - configuration("*Static") - kind("StaticLib") - - configuration("*Dynamic") - kind("SharedLib") - - configuration("DebugStatic") - targetsuffix("-s-d") - - configuration("ReleaseStatic") - targetsuffix("-s") - - configuration("DebugDynamic") - targetsuffix("-d") - end - - configuration({}) + libdirs({ + "../extlibs/lib/common", + "../lib" + }) files(toolTable.Files) excludes(toolTable.FilesExcluded) @@ -393,12 +221,25 @@ function NazaraBuild:Execute() includedirs(toolTable.Includes) links(toolTable.Libraries) + -- Output to lib/conf/arch + if (toolTable.Kind == "library") then + self:FilterLibDirectory(toolTable.TargetDirectory .. "/", targetdir) + elseif (toolTable.Kind == "plugin") then + self:FilterLibDirectory("../plugins/lib/", targetdir) + end + + filter("architecture:x86") + libdirs(toolTable.LibraryPaths.x86) + + filter("architecture:x86_64") + libdirs(toolTable.LibraryPaths.x64) + for k,v in pairs(toolTable.ConfigurationLibraries) do - configuration(k) + filter(k) links(v) end - configuration({}) + filter({}) end for k, exampleTable in ipairs(self.OrderedExamples) do @@ -429,7 +270,6 @@ function NazaraBuild:Execute() "../extlibs/include" }) libdirs("../lib") - targetdir(destPath) files(exampleTable.Files) excludes(exampleTable.FilesExcluded) @@ -438,41 +278,14 @@ function NazaraBuild:Execute() flags(exampleTable.Flags) includedirs(exampleTable.Includes) links(exampleTable.Libraries) - - configuration("Release*") - rtti(exampleTable.EnableRTTI and "On" or "Off") - - configuration("x32") - libdirs(exampleTable.LibraryPaths.x86) - - configuration("x64") - defines("NAZARA_PLATFORM_x64") - libdirs(exampleTable.LibraryPaths.x64) - - configuration({"codeblocks or codelite or gmake", "x32"}) - libdirs("../lib/" .. makeLibDir .. "/x86") - - configuration({"codeblocks or codelite or gmake", "x64"}) - libdirs("../lib/" .. makeLibDir .. "/x64") - - configuration({"vs*", "x32"}) - libdirs("../lib/msvc/x86") - - configuration({"vs*", "x64"}) - libdirs("../lib/msvc/x64") - - configuration({"xcode3 or xcode4", "x32"}) - libdirs("../lib/xcode/x86") - - configuration({"xcode3 or xcode4", "x64"}) - libdirs("../lib/xcode/x64") + targetdir(destPath) for k,v in pairs(exampleTable.ConfigurationLibraries) do - configuration(k) + filter(k) links(v) end - configuration({}) + filter({}) end end end @@ -712,39 +525,37 @@ function NazaraBuild:LoadConfig() end function NazaraBuild:MakeInstallCommands(infoTable) - if (PremakeVersion < 50) then - return - end - if (os.is("windows")) then - configuration("*Dynamic") - + filter("kind:SharedLib") + + postbuildmessage("Copying " .. infoTable.Name .. " library and its dependencies to install/executable directories...") + for k,v in pairs(self.InstallDir) do local destPath = path.translate(path.isabsolute(k) and k or "../../" .. k) - postbuildcommands({[[xcopy "%{path.translate(cfg.linktarget.relpath):sub(1, -5) .. ".dll"}" "]] .. destPath .. [[\" /E /Y]]}) + postbuildcommands({[[xcopy "%{path.translate(cfg.buildtarget.relpath)}" "]] .. destPath .. [[\" /E /Y]]}) end for k,fileName in pairs(table.join(infoTable.Libraries, infoTable.DynLib)) do local paths = {} for k,v in pairs(infoTable.BinaryPaths.x86) do - table.insert(paths, {"x32", v .. "/" .. fileName .. ".dll"}) - table.insert(paths, {"x32", v .. "/lib" .. fileName .. ".dll"}) + table.insert(paths, {"x86", v .. "/" .. fileName .. ".dll"}) + table.insert(paths, {"x86", v .. "/lib" .. fileName .. ".dll"}) end for k,v in pairs(infoTable.BinaryPaths.x64) do - table.insert(paths, {"x64", v .. "/" .. fileName .. ".dll"}) - table.insert(paths, {"x64", v .. "/lib" .. fileName .. ".dll"}) + table.insert(paths, {"x86_64", v .. "/" .. fileName .. ".dll"}) + table.insert(paths, {"x86_64", v .. "/lib" .. fileName .. ".dll"}) end for k,v in pairs(paths) do - local config = v[1] + local arch = v[1] local srcPath = v[2] if (os.isfile(srcPath)) then if (infoTable.Kind == "plugin") then srcPath = "../../" .. srcPath end - configuration(config) + filter("architecture:" .. arch) for k,v in pairs(self.ExecutableDir) do local srcPath = path.isabsolute(srcPath) and path.translate(srcPath) or [[%{path.translate(cfg.linktarget.relpath:sub(1, -#cfg.linktarget.name - 1) .. "../../]] .. srcPath .. [[")}]] @@ -754,6 +565,8 @@ function NazaraBuild:MakeInstallCommands(infoTable) end end end + + filter({}) end end @@ -876,41 +689,125 @@ function NazaraBuild:Process(infoTable) return true end +function NazaraBuild:PrepareGeneric() + flags({ + "C++14", + "MultiProcessorCompile", + "NoMinimalRebuild", + "RelativeLinks", + "ShadowedVariables", + "UndefinedIdentifiers" + }) + + self:FilterLibDirectory("../extlibs/lib/", libdirs) + + -- Fixes Premake stuff + filter({"kind:SharedLib", clangGccActions}) + implibprefix("lib") + filter({"kind:*Lib", clangGccActions, "system:Windows"}) + implibextension(".a") + filter({"kind:StaticLib", clangGccActions}) + targetextension(".a") + targetprefix("lib") + + -- General configuration + filter("kind:*Lib") + pic("On") + + filter({"kind:*Lib", "configurations:DebugStatic"}) + targetsuffix("-s-d") + + filter({"kind:*Lib", "configurations:ReleaseStatic"}) + targetsuffix("-s") + + filter({"kind:*Lib", "configurations:DebugDynamic"}) + targetsuffix("-d") + + filter("configurations:Debug*") + symbols("On") + + -- Setup some optimizations for release + filter("configurations:Release*") + flags("NoFramePointer") + optimize("Speed") + vectorextensions("SSE2") + + filter("configurations:*Static") + kind("StaticLib") + + filter("configurations:*Dynamic") + kind("SharedLib") + + -- Enable SSE math and vectorization optimizations + filter({"configurations:Release*", clangGccActions}) + buildoptions("-mfpmath=sse") + buildoptions("-ftree-vectorize") + + filter({}) +end + +function NazaraBuild:PrepareMainWorkspace() + self:PrepareGeneric() + + filter("action:vs*") + buildoptions({"/MP", "/bigobj"}) -- Multiprocessus build and big .obj + defines("_CRT_SECURE_NO_WARNINGS") + defines("_SCL_SECURE_NO_WARNINGS") + + filter("architecture:x86_64") + defines("NAZARA_PLATFORM_x64") + + filter("configurations:Debug*") + defines("NAZARA_DEBUG") + + filter("configurations:*Static") + defines("NAZARA_STATIC") + + filter("kind:*Lib") + defines("NAZARA_BUILD") + + filter({"system:Windows", clangGccActions}) + buildoptions("-Wa,-mbig-obj") -- big object + + filter({"system:not Windows", clangGccActions}) + buildoptions("-fvisibility=hidden") + + filter({}) +end + function NazaraBuild:RegisterAction(actionTable) - if (actionTable.Name == nil or type(actionTable.Name) ~= "string" or string.len(actionTable.Name) == 0) then - return false, "Invalid action name" + if (not actionTable.Manual) then + if (actionTable.Name == nil or type(actionTable.Name) ~= "string" or string.len(actionTable.Name) == 0) then + return false, "Invalid action name" + end + + local lowerCaseName = string.lower(actionTable.Name) + if (self.Actions[lowerCaseName] ~= nil) then + return false, "This action name is already in use" + end + + if (actionTable.Description == nil or type(actionTable.Description) ~= "string") then + return false, "Action description is invalid" + end + + if (string.len(actionTable.Description) == 0) then + return false, "Action description is empty" + end + + if (actionTable.Function == nil or type(actionTable.Function) ~= "function") then + return false, "Action function is invalid" + end + + self.Actions[lowerCaseName] = actionTable + + newaction + { + trigger = lowerCaseName, + description = actionTable.Description, + execute = function () actionTable:Function() end + } end - local lowerCaseName = string.lower(actionTable.Name) - if (self.Actions[lowerCaseName] ~= nil) then - return false, "This action name is already in use" - end - - if (actionTable.Description == nil or type(actionTable.Description) ~= "string") then - return false, "Action description is invalid" - end - - if (string.len(actionTable.Description) == 0) then - return false, "Action description is empty" - end - - if (self.Actions[actionTable.name] ~= nil) then - return false, "Action name \"" .. actionTable.name .. " is already registred" - end - - if (actionTable.Function == nil or type(actionTable.Function) ~= "function") then - return false, "Action function is invalid" - end - - self.Actions[lowerCaseName] = actionTable - - newaction - { - trigger = lowerCaseName, - description = actionTable.Description, - execute = function () actionTable:Function() end - } - return true end diff --git a/examples/FirstScene/main.cpp b/examples/FirstScene/main.cpp index e7c5b2c90..863d3edea 100644 --- a/examples/FirstScene/main.cpp +++ b/examples/FirstScene/main.cpp @@ -96,7 +96,7 @@ int main() // Les UVs de ce fichier sont retournées (repère OpenGL, origine coin bas-gauche) par rapport à ce que le moteur attend (haut-gauche) // Nous devons donc indiquer au moteur de les retourner lors du chargement - params.mesh.flipUVs = true; + params.mesh.texCoordScale.Set(1.f, -1.f); // Nazara va par défaut optimiser les modèles pour un rendu plus rapide, cela peut prendre du temps et n'est pas nécessaire ici params.mesh.optimizeIndexBuffers = false; diff --git a/examples/Particles/Common.cpp b/examples/Particles/Common.cpp new file mode 100644 index 000000000..5af7225f7 --- /dev/null +++ b/examples/Particles/Common.cpp @@ -0,0 +1,70 @@ +#include "Common.hpp" +#include +#include +#include +#include + +ParticleDemo::ParticleDemo(const Nz::String& name, const ExampleShared& exampleShared) : +m_shared(exampleShared), +m_index(s_demoIndex++), +m_name(name) +{ +} + +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; + m_updateClock.Restart(); + + Ndk::RenderSystem& renderSystem2D = m_shared.world2D->GetSystem(); + Ndk::RenderSystem& renderSystem3D = m_shared.world3D->GetSystem(); + m_oldBackground2D = renderSystem2D.GetDefaultBackground(); + m_oldBackground3D = renderSystem3D.GetDefaultBackground(); +} + +void ParticleDemo::Leave(Ndk::StateMachine& fsm) +{ + m_shared.world2D->GetSystem().SetDefaultBackground(m_oldBackground2D); + m_shared.world3D->GetSystem().SetDefaultBackground(m_oldBackground3D); + + m_entities.clear(); + m_particleGroups.clear(); +} + +bool ParticleDemo::Update(Ndk::StateMachine& fsm, float elapsedTime) +{ + m_fpsCounter++; + if (m_updateClock.GetMilliseconds() > 1000) + { + m_updateClock.Restart(); + + m_shared.fpsCount->Update(Nz::SimpleTextDrawer::Draw(Nz::String::Number(m_fpsCounter) + " FPS", 24)); + m_fpsCounter = 0; + + unsigned int particleCount = 0; + for (const Ndk::EntityHandle& entity : m_particleGroups) + { + const Ndk::ParticleGroupComponent& group = entity->GetComponent(); + particleCount += group.GetParticleCount(); + } + + m_shared.particleCount->Update(Nz::SimpleTextDrawer::Draw(Nz::String::Number(particleCount) + " particles", 36)); + } + + return true; +} + +void ParticleDemo::RegisterEntity(const Ndk::EntityHandle& entity) +{ + m_entities.emplace_back(entity); +} + +void ParticleDemo::RegisterParticleGroup(const Ndk::EntityHandle& entity) +{ + NazaraAssert(entity->HasComponent(), "Must have particle group component"); + + m_particleGroups.emplace_back(entity); +} + +std::size_t ParticleDemo::s_demoIndex = 0; diff --git a/examples/Particles/Common.hpp b/examples/Particles/Common.hpp new file mode 100644 index 000000000..658b97419 --- /dev/null +++ b/examples/Particles/Common.hpp @@ -0,0 +1,64 @@ +#pragma once + +#ifndef NAZARA_EXAMPLES_PARTICLES_COMMON_HPP +#define NAZARA_EXAMPLES_PARTICLES_COMMON_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class ParticleDemo; + +struct ExampleShared +{ + mutable std::mt19937 randomGen; + std::vector> demos; + Nz::RenderWindow* target; + Nz::TextSpriteRef demoName; + Nz::TextSpriteRef fpsCount; + Nz::TextSpriteRef particleCount; + Ndk::EntityHandle viewer2D; + Ndk::EntityHandle viewer3D; + Ndk::WorldHandle world2D; + Ndk::WorldHandle world3D; +}; + +class ParticleDemo : public Ndk::State +{ + public: + ParticleDemo(const Nz::String& name, const ExampleShared& exampleShared); + ~ParticleDemo() = default; + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + protected: + const ExampleShared& m_shared; + + void RegisterEntity(const Ndk::EntityHandle& entity); + void RegisterParticleGroup(const Ndk::EntityHandle& entity); + + private: + std::size_t m_index; + std::vector m_entities; + std::vector m_particleGroups; + Nz::BackgroundRef m_oldBackground2D; + Nz::BackgroundRef m_oldBackground3D; + Nz::Clock m_updateClock; + Nz::String m_name; + unsigned int m_fpsCounter; + + static std::size_t s_demoIndex; +}; + +#endif // NAZARA_EXAMPLES_PARTICLES_COMMON_HPP diff --git a/examples/Particles/LogoDemo.cpp b/examples/Particles/LogoDemo.cpp new file mode 100644 index 000000000..cc0c2a610 --- /dev/null +++ b/examples/Particles/LogoDemo.cpp @@ -0,0 +1,170 @@ +#include "LogoDemo.hpp" +#include +#include +#include +#include +#include + +namespace +{ + const float duration = 10.f; + const float maxVel = 50.f; + const float pauseTime = 3.f; + const float startTime = 2.f; + const float speed = 3.f; +} + +struct SpriteController : public Nz::ParticleController +{ + void Apply(Nz::ParticleGroup& system, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) override + { + if (!enabled) + return; + + auto posPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); + auto velPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); + + for (unsigned int i = startId; i <= endId; ++i) + posPtr[i] += velPtr[i] * elapsedTime * factor; + } + + bool enabled = false; + float factor = 1.f; +}; + + +class SpriteRenderer : public Nz::ParticleRenderer +{ + public: + SpriteRenderer(Nz::MaterialRef mat) : + m_material(mat) + { + } + + void Render(const Nz::ParticleGroup& system, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue) + { + Nz::Vector2f size(1.f, 1.f); + Nz::SparsePtr sizePtr(&size, 0); + Nz::SparsePtr sinCosPtr(nullptr, 0); + + renderQueue->AddBillboards(0, m_material, endId - startId + 1, mapper.GetComponentPtr(Nz::ParticleComponent_Position), sizePtr, sinCosPtr, mapper.GetComponentPtr(Nz::ParticleComponent_Color)); + } + + private: + Nz::MaterialRef m_material; +}; + +LogoExample::LogoExample(ExampleShared& sharedData) : +ParticleDemo("Logo", sharedData) +{ + Nz::ImageParams params; + params.loadFormat = Nz::PixelFormatType_RGBA8; + + if (!m_logo.LoadFromFile("resources/Logo.png", params)) + NazaraError("Failed to load logo!"); + + unsigned int width = m_logo.GetWidth(); + 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) + { + Nz::Color color = m_logo.GetPixelColor(x, y); + if (color.a == 0) + continue; + + PixelData data; + data.pos.Set(x, y); + data.color = color; + + m_pixels.push_back(data); + } + } + + + Nz::MaterialRef material = Nz::Material::New(); + material->EnableBlending(true); + material->EnableDepthWrite(false); + material->EnableFaceCulling(false); + material->SetDstBlend(Nz::BlendFunc_InvSrcAlpha); + material->SetSrcBlend(Nz::BlendFunc_SrcAlpha); + + m_controller = new SpriteController; + m_renderer = new SpriteRenderer(std::move(material)); +} + +void LogoExample::Enter(Ndk::StateMachine& fsm) +{ + ParticleDemo::Enter(fsm); + + m_shared.world3D->GetSystem().SetDefaultBackground(nullptr); + + Nz::TextureRef backgroundTexture = Nz::Texture::New(); + if (backgroundTexture->LoadFromFile("resources/stars-background.jpg")) + 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); + RegisterParticleGroup(particleGroupEntity); + + particleGroup.AddController(m_controller); + particleGroup.SetRenderer(m_renderer); + + m_particles = static_cast(particleGroup.CreateParticles(m_pixels.size())); + ResetParticles(-duration * (speed / 2.f)); + + m_accumulator = pauseTime + duration; + m_totalAccumulator = 0.f; +} + +void LogoExample::Leave(Ndk::StateMachine & fsm) +{ + ParticleDemo::Leave(fsm); +} + +bool LogoExample::Update(Ndk::StateMachine& fsm, float elapsedTime) +{ + if (!ParticleDemo::Update(fsm, elapsedTime)) + return false; + + m_totalAccumulator += elapsedTime; + if (m_totalAccumulator <= startTime) + return true; + + m_accumulator += elapsedTime; + + SpriteController* controller = static_cast(m_controller.Get()); + if (m_accumulator > pauseTime + 2.f * duration) + { + ResetParticles(0.f); + m_accumulator = 0.f; + } + + controller->enabled = (m_accumulator > pauseTime); + controller->factor = -speed + speed * (m_accumulator - pauseTime) / (duration); + + return true; +} + +void LogoExample::ResetParticles(float elapsed) +{ + Nz::Vector2f center = {m_shared.target->GetWidth() / 2.f, m_shared.target->GetHeight() / 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); + + Nz::ParticleStruct_Sprite* sprite = 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++; + } +} diff --git a/examples/Particles/LogoDemo.hpp b/examples/Particles/LogoDemo.hpp new file mode 100644 index 000000000..d5c374d32 --- /dev/null +++ b/examples/Particles/LogoDemo.hpp @@ -0,0 +1,41 @@ +#pragma once + +#ifndef NAZARA_EXAMPLES_PARTICLES_LOGO_HPP +#define NAZARA_EXAMPLES_PARTICLES_LOGO_HPP + +#include +#include +#include +#include +#include "Common.hpp" + +class LogoExample : public ParticleDemo +{ + public: + LogoExample(ExampleShared& sharedData); + ~LogoExample() = default; + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void ResetParticles(float elapsed); + + struct PixelData + { + Nz::Vector2ui pos; + Nz::Color color; + }; + + std::vector m_pixels; + Nz::BackgroundRef m_oldBackground; + Nz::ParticleStruct_Sprite* m_particles; + Nz::Image m_logo; + Nz::ParticleControllerRef m_controller; + Nz::ParticleRendererRef m_renderer; + float m_accumulator; + float m_totalAccumulator; +}; + +#endif // NAZARA_EXAMPLES_PARTICLES_LOGO_HPP diff --git a/examples/Particles/SpacebattleDemo.cpp b/examples/Particles/SpacebattleDemo.cpp new file mode 100644 index 000000000..8cc1558c6 --- /dev/null +++ b/examples/Particles/SpacebattleDemo.cpp @@ -0,0 +1,826 @@ +#include "SpacebattleDemo.hpp" +#include +#include +#include +#include +#include +#include + +namespace +{ + const float maxLaserLife = 15.f; + const float maxSmokeLife = 20.f; +} + +struct SpaceshipComponent : public Ndk::Component +{ + SpaceshipComponent() + { + engineSound.SetBuffer(Nz::SoundBufferManager::Get("resources/spaceship_loop.wav")); + engineSound.EnableSpatialization(true); + engineSound.SetMinDistance(10.f); + engineSound.SetPitch(1.5f); + + hitSound.SetBuffer(Nz::SoundBufferManager::Get("resources/explosion.wav")); + hitSound.EnableSpatialization(true); + hitSound.SetMinDistance(150.f); + + laserSound.SetBuffer(Nz::SoundBufferManager::Get("resources/laser.wav")); + laserSound.EnableSpatialization(true); + laserSound.SetMinDistance(150.f); + laserSound.SetVolume(60.f); + } + + std::array laserBeamSprites; + Nz::Sound engineSound; + Nz::Sound hitSound; + Nz::Sound laserSound; + Nz::UInt64 hitTime = 0; + Nz::Vector3f targetPos = Nz::Vector3f::Zero(); + bool attacking = true; + + static Ndk::ComponentIndex componentIndex; +}; +Ndk::ComponentIndex SpaceshipComponent::componentIndex; + +struct LaserBeamComponent : public Ndk::Component +{ + LaserBeamComponent() + { + Nz::MaterialRef laserBeamMaterial = Nz::MaterialLibrary::Get("LaserBeam"); + for (Nz::Sprite& sprite : sprites) + { + sprite.SetMaterial(laserBeamMaterial); + sprite.SetOrigin(Nz::Vector2f(0.f, 0.5f)); + sprite.SetTextureCoords(Nz::Rectf(0.f, 0.f, 50.f, 1.f)); + } + } + + void OnAttached() override + { + auto& spaceshipCom = m_entity->GetComponent(); + spaceshipCom.laserSound.Play(); + } + + std::array sprites; + Nz::Vector3f origin = Nz::Vector3f::Zero(); + float length = 1500.f; + float life = 2.f; + float width = 2.f; + + static Ndk::ComponentIndex componentIndex; +}; +Ndk::ComponentIndex LaserBeamComponent::componentIndex; + +class LaserBeamSystem : public Ndk::System +{ + public: + LaserBeamSystem(const ExampleShared& sharedData) : + m_sharedData(sharedData) + { + Requires(); + } + + void OnEntityAdded(Ndk::Entity* entity) override + { + auto& laserComponent = entity->GetComponent(); + auto& gfxComponent = entity->GetComponent(); + + for (Nz::Sprite& sprite : laserComponent.sprites) + sprite.SetSize({laserComponent.length, laserComponent.width}); + + gfxComponent.Attach(&laserComponent.sprites[0], Nz::Matrix4f::Transform(laserComponent.origin, Nz::EulerAnglesf(0.f, 90.f, 0.f))); + gfxComponent.Attach(&laserComponent.sprites[1], Nz::Matrix4f::Transform(laserComponent.origin, Nz::EulerAnglesf(90.f, 90.f, 0.f))); + } + + void OnUpdate(float elapsedTime) override + { + const float scrollSpeed = 2.f; + for (const Ndk::EntityHandle& entity : GetEntities()) + { + auto& laserComponent = entity->GetComponent(); + for (Nz::Sprite& sprite : laserComponent.sprites) + { + Nz::Rectf rect = sprite.GetTextureCoords(); + rect.x = std::fmod(rect.x - elapsedTime * scrollSpeed, rect.width); + + sprite.SetTextureCoords(rect); + } + } + } + + static Ndk::SystemIndex systemIndex; + + private: + const ExampleShared& m_sharedData; +}; +Ndk::SystemIndex LaserBeamSystem::systemIndex; + +class SpaceshipSystem : public Ndk::System +{ + public: + SpaceshipSystem(const ExampleShared& sharedData) : + m_sharedData(sharedData) + { + Requires(); + } + + void OnEntityAdded(Ndk::Entity* entity) override + { + std::uniform_real_distribution pitchDis(0.8f, 1.5f); + + auto& nodeComponent = entity->GetComponent(); + auto& spaceshipComponent = entity->GetComponent(); + + spaceshipComponent.engineSound.SetPosition(nodeComponent.GetPosition()); + spaceshipComponent.engineSound.Play(); + spaceshipComponent.engineSound.EnableLooping(true); + + spaceshipComponent.laserSound.SetPitch(pitchDis(m_sharedData.randomGen)); + } + + void OnUpdate(float elapsedTime) override + { + const float escapeMaxDist = 50.f; + const float speed = 200.f; + + Nz::UInt64 curTime = Nz::GetElapsedMilliseconds(); + std::uniform_real_distribution dis(-escapeMaxDist, escapeMaxDist); + + for (const Ndk::EntityHandle& entity : GetEntities()) + { + auto& nodeComponent = entity->GetComponent(); + auto& spaceshipComponent = entity->GetComponent(); + auto& velocityComponent = entity->GetComponent(); + + //< I agree, I need some kind of SoundEmitterComponent + spaceshipComponent.engineSound.SetPosition(nodeComponent.GetPosition()); + spaceshipComponent.engineSound.SetVelocity(velocityComponent.linearVelocity); + + spaceshipComponent.hitSound.SetPosition(nodeComponent.GetPosition()); + spaceshipComponent.hitSound.SetVelocity(velocityComponent.linearVelocity); + + spaceshipComponent.laserSound.SetPosition(nodeComponent.GetPosition()); + spaceshipComponent.laserSound.SetVelocity(velocityComponent.linearVelocity); + + Nz::Vector3f targetDir = spaceshipComponent.targetPos - nodeComponent.GetPosition(); + targetDir.Normalize(); + + Nz::Quaternionf targetRotation = Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), targetDir); + + nodeComponent.SetRotation(Nz::Quaternionf::Slerp(nodeComponent.GetRotation(), targetRotation, elapsedTime * 1.5f)); + + Nz::Vector3f actualDir = nodeComponent.GetForward(); + float sqDistance = spaceshipComponent.targetPos.SquaredDistance(nodeComponent.GetPosition()); + + if (spaceshipComponent.attacking) + { + float dotProduct = targetDir.DotProduct(actualDir); + if (dotProduct > 0.9f && sqDistance < (150.f * 150.f) && !entity->HasComponent()) + { + auto& laserBeam = entity->AddComponent(); + laserBeam.origin = Nz::Vector3f::Forward() * 12.f + Nz::Vector3f::Down() * 2.f; + } + + if (sqDistance < (100.f * 100.f)) + { + entity->RemoveComponent(); + + spaceshipComponent.targetPos -= Nz::Vector3f(dis(m_sharedData.randomGen), dis(m_sharedData.randomGen), dis(m_sharedData.randomGen)) * -actualDir * escapeMaxDist / 2.f; + spaceshipComponent.attacking = false; + } + } + else if (sqDistance < (50.f * 50.f) && spaceshipComponent.hitTime == 0) + { + spaceshipComponent.targetPos = Nz::Vector3f::Zero(); + spaceshipComponent.attacking = true; + } + + if (spaceshipComponent.hitTime == 0 || curTime - spaceshipComponent.hitTime <= 1000) + velocityComponent.linearVelocity = actualDir * speed; + else if (curTime - spaceshipComponent.hitTime > 10000) + entity->Kill(); + } + } + + static Ndk::SystemIndex systemIndex; + + private: + const ExampleShared& m_sharedData; +}; +Ndk::SystemIndex SpaceshipSystem::systemIndex; + +struct TorpedoParticle +{ + Nz::Color color; + Nz::Vector2f size; + Nz::Vector3f position; + Nz::Vector3f velocity; + float rotation; + float life; +}; + +SpacebattleExample::SpacebattleExample(ExampleShared& sharedData) : +ParticleDemo("Space battle", sharedData) +{ + Ndk::InitializeComponent("Lasrbeam"); + Ndk::InitializeComponent("Spceship"); + Ndk::InitializeSystem(); + Ndk::InitializeSystem(); + + Nz::ModelParameters parameters; + parameters.mesh.optimizeIndexBuffers = false; + + Nz::Color grey(100, 100, 100); + + if (!m_turret.baseModel.LoadFromFile("resources/Turret/base.obj", parameters)) + NazaraWarning("Failed to load base.obj"); + + for (unsigned int i = 0; i < m_turret.baseModel.GetMaterialCount(); ++i) + m_turret.baseModel.GetMaterial(i)->SetDiffuseColor(grey); + + if (!m_turret.rotatingBaseModel.LoadFromFile("resources/Turret/rotating_base.obj", parameters)) + NazaraWarning("Failed to load rotating_base.obj"); + + for (unsigned int i = 0; i < m_turret.rotatingBaseModel.GetMaterialCount(); ++i) + m_turret.rotatingBaseModel.GetMaterial(i)->SetDiffuseColor(grey); + + if (!m_turret.cannonBaseModel.LoadFromFile("resources/Turret/cannon_base.obj", parameters)) + NazaraWarning("Failed to load cannon_base.obj"); + + for (unsigned int i = 0; i < m_turret.cannonBaseModel.GetMaterialCount(); ++i) + m_turret.cannonBaseModel.GetMaterial(i)->SetDiffuseColor(grey); + + parameters.mesh.texCoordScale.Set(40.f, 40.f); + parameters.mesh.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, 180.f, 0.f)); + if (!m_turret.cannonModel.LoadFromFile("resources/Turret/cannon.obj", parameters)) + NazaraWarning("Failed to load cannon.obj"); + + // Since OBJ don't support normal maps.. + m_turret.cannonModel.GetMaterial(0)->SetNormalMap("resources/Turret/198_norm.jpg"); + + parameters.mesh.matrix.MakeIdentity(); + parameters.mesh.texCoordScale.Set(1.f, 1.f); + + parameters.mesh.center = true; + if (!m_spacestationModel.LoadFromFile("resources/SpaceStation/space_station.obj", parameters)) + NazaraWarning("Failed to load space_station.obj"); + + parameters.mesh.texCoordScale.Set(1.f, -1.f); + parameters.mesh.matrix.MakeRotation(Nz::EulerAnglesf(0.f, -90.f, 0.f)); + + if (!m_spaceshipModel.LoadFromFile("resources/space_frigate_6/space_frigate_6.obj", parameters)) + NazaraWarning("Failed to load space_frigate_6.obj"); + + // Since OBJ don't support normal maps.. + for (unsigned int i = 0; i < m_spaceshipModel.GetMaterialCount(); ++i) + { + m_spaceshipModel.GetMaterial(i)->SetEmissiveMap("resources/space_frigate_6/space_frigate_6_illumination.jpg"); + m_spaceshipModel.GetMaterial(i)->SetNormalMap("resources/space_frigate_6/space_frigate_6_normal.png"); + } + + Nz::TextureRef skyboxCubemap = Nz::Texture::New(); + if (skyboxCubemap->Create(Nz::ImageType_Cubemap, Nz::PixelFormatType_RGBA8, 2048, 2048)) + { + skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_PositiveX, "resources/purple_nebula_skybox/purple_nebula_skybox_right1.png"); + skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_PositiveY, "resources/purple_nebula_skybox/purple_nebula_skybox_top3.png"); + skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_PositiveZ, "resources/purple_nebula_skybox/purple_nebula_skybox_front5.png"); + skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_NegativeX, "resources/purple_nebula_skybox/purple_nebula_skybox_left2.png"); + skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_NegativeY, "resources/purple_nebula_skybox/purple_nebula_skybox_bottom4.png"); + skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_NegativeZ, "resources/purple_nebula_skybox/purple_nebula_skybox_back6.png"); + + m_skybox.SetTexture(std::move(skyboxCubemap)); + } + + m_torpedoDeclaration = Nz::ParticleDeclaration::New(); + m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Color, Nz::ComponentType_Color, NazaraOffsetOf(TorpedoParticle, color)); + m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Position, Nz::ComponentType_Float3, NazaraOffsetOf(TorpedoParticle, position)); + m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Rotation, Nz::ComponentType_Float1, NazaraOffsetOf(TorpedoParticle, rotation)); + m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Size, Nz::ComponentType_Float2, NazaraOffsetOf(TorpedoParticle, size)); + m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Life, Nz::ComponentType_Float1, NazaraOffsetOf(TorpedoParticle, life)); + m_torpedoDeclaration->EnableComponent(Nz::ParticleComponent_Velocity, Nz::ComponentType_Float3, NazaraOffsetOf(TorpedoParticle, velocity)); + + Nz::TextureSampler diffuseSampler; + diffuseSampler.SetWrapMode(Nz::SamplerWrap_Repeat); + + Nz::MaterialRef material = Nz::Material::New("Translucent3D"); + material->SetDiffuseMap("resources/LaserBeam.png"); + material->SetDiffuseSampler(diffuseSampler); + + Nz::MaterialLibrary::Register("LaserBeam", std::move(material)); + + Nz::MaterialRef sparkleMat1 = Nz::Material::New("Translucent3D"); + + sparkleMat1->SetDiffuseMap("resources/flare1.png"); + Nz::MaterialLibrary::Register("TorpedoFlare1", std::move(sparkleMat1)); + + m_spaceshipTemplate = m_shared.world3D->CreateEntity(); + m_spaceshipTemplate->Enable(false); + + 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"); + m_ambientMusic.SetVolume(60.f); +} + +void SpacebattleExample::Enter(Ndk::StateMachine& fsm) +{ + ParticleDemo::Enter(fsm); + + m_shared.world3D->AddSystem(m_shared); + m_shared.world3D->AddSystem(m_shared); + + Ndk::RenderSystem& renderSystem2D = m_shared.world2D->GetSystem(); + Ndk::RenderSystem& renderSystem3D = m_shared.world3D->GetSystem(); + renderSystem2D.SetDefaultBackground(nullptr); + renderSystem3D.SetDefaultBackground(&m_skybox); + + CreateSpaceShip(); + CreateTurret(); + + Ndk::EntityHandle light = m_shared.world3D->CreateEntity(); + Ndk::NodeComponent& lightNode = light->AddComponent(); + Ndk::LightComponent& lightComp = light->AddComponent(Nz::LightType_Directional); + lightNode.SetRotation(Nz::EulerAnglesf(-30.f, 0.f, 0.f)); + RegisterEntity(light); + + Ndk::NodeComponent& cameraNode = m_shared.viewer3D->GetComponent(); + cameraNode.SetParent(m_turret.cannonAnchorEntity); + cameraNode.SetPosition(Nz::Vector3f::Up() * 4.f - Nz::Vector3f::Backward() * 6.f); + cameraNode.SetRotation(Nz::EulerAnglesf(0.f, 180.f, 0.f)); + + m_introTimer = 10.f; + m_spaceshipSpawnCounter = -5.f; + m_turretBaseRotation = 0.f; + m_turretCannonBaseRotation = 0.f; + m_turretShootTimer = 0.f; + + Ndk::EntityHandle torpedoGroupEntity = m_shared.world3D->CreateEntity(); + m_torpedoGroup = torpedoGroupEntity->AddComponent(200, m_torpedoDeclaration).CreateHandle(); + RegisterParticleGroup(torpedoGroupEntity); + + m_torpedoGroup->AddController(Nz::ParticleFunctionController::New([] (Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) + { + auto positionPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); + auto lifePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Life); + auto rotationPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Rotation); + auto velocityPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); + + for (unsigned int i = startId; i <= endId; ++i) + { + rotationPtr[i] += elapsedTime * 90.f; + positionPtr[i] += velocityPtr[i] * elapsedTime; + + lifePtr[i] -= elapsedTime; + if (lifePtr[i] < 0.f) + group.KillParticle(i); + } + })); + + + 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(); + + for (unsigned int i = startId; i <= endId; ++i) + { + Nz::Spheref torpedoSphere(positionPtr[i], std::max(sizePtr[i].x, sizePtr[i].y) * 0.1f); + + for (const Ndk::EntityHandle& entity : spaceshipSystem.GetEntities()) + { + auto& spaceshipNode = entity->GetComponent(); + + Nz::Spheref spaceshipSphere(spaceshipNode.GetPosition(), 10.f); + if (torpedoSphere.Intersect(spaceshipSphere)) + { + entity->RemoveComponent(); + + group.KillParticle(i); + + const float hitMaxDist = 500.f; + + std::uniform_real_distribution dis(-hitMaxDist, hitMaxDist); + + auto& spaceshipComponent = entity->GetComponent(); + spaceshipComponent.attacking = false; + spaceshipComponent.engineSound.Stop(); + spaceshipComponent.hitSound.Play(); + spaceshipComponent.hitTime = Nz::GetElapsedMilliseconds(); + spaceshipComponent.targetPos = Nz::Vector3f(dis(m_shared.randomGen), dis(m_shared.randomGen), dis(m_shared.randomGen)); + + auto& emitter = entity->AddComponent(); + emitter.SetEmissionCount(2); + emitter.SetEmissionRate(200.f); + + emitter.SetSetupFunc([this] (const Ndk::EntityHandle& entity, Nz::ParticleMapper& mapper, unsigned int count) + { + auto& gen = m_shared.randomGen; + + const float maxFireVel = 15.f; + std::uniform_real_distribution lifeDis(-0.5f, 0.5f); + std::uniform_real_distribution normalDis(-1.f, 1.f); + std::uniform_real_distribution posDis(-0.1f, 0.1f); + std::uniform_real_distribution rotDis(-180.f, 180.f); + std::uniform_real_distribution sizeDis(1.0f, 4.f); + std::uniform_real_distribution velDis(-maxFireVel, maxFireVel); + + Nz::Vector3f pos = entity->GetComponent().GetPosition(); + + Nz::ParticleStruct_Billboard* billboards = static_cast(mapper.GetPointer()); + Nz::ParticleStruct_Billboard* smokeParticles = static_cast(m_smokeGroup->CreateParticles(count)); + for (unsigned int i = 0; i < count; ++i) + { + 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); + + 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; + } + }); + m_fireGroup->AddEmitter(entity); + + break; + } + } + } + })); + + 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) + { + Nz::AbstractRenderQueue::PointLight pointLight; + pointLight.ambientFactor = 0.f; + pointLight.attenuation = 0.9f; + pointLight.color = Nz::Color::Cyan; + pointLight.diffuseFactor = 1.f; + pointLight.position = positionPtr[i]; + pointLight.radius = std::max(sizePtr[i].x, sizePtr[i].y) * 2.f; + pointLight.invRadius = 1.f / pointLight.radius; + pointLight.shadowMap = nullptr; + + renderQueue->AddPointLight(pointLight); + } + })); + + + ////////////////////////////////////////////////////////////////////////// + + Ndk::EntityHandle fireGroupEntity = m_shared.world3D->CreateEntity(); + m_fireGroup = fireGroupEntity->AddComponent(40000, Nz::ParticleDeclaration::Get(Nz::ParticleLayout_Billboard)).CreateHandle(); + RegisterParticleGroup(fireGroupEntity); + + Ndk::EntityHandle smokeGroupEntity = m_shared.world3D->CreateEntity(); + m_smokeGroup = smokeGroupEntity->AddComponent(40000, Nz::ParticleDeclaration::Get(Nz::ParticleLayout_Billboard)).CreateHandle(); + RegisterParticleGroup(smokeGroupEntity); + + auto movementController = Nz::ParticleFunctionController::New([this] (Nz::ParticleGroup& group, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) + { + auto lifePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Life); + auto posPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); + auto sizePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Size); + auto velPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Velocity); + + auto& spaceshipSystem = m_shared.world3D->GetSystem(); + + const Nz::Vector2f sizeGrowth(0.5f); + + float velFactor = std::pow(0.9f, elapsedTime * 15.f); + for (unsigned int i = startId; i <= endId; ++i) + { + float& remainingLife = lifePtr[i]; + + remainingLife -= elapsedTime; + if (remainingLife <= 0.f) + { + group.KillParticle(i); + continue; + } + + Nz::Vector3f& position = posPtr[i]; + Nz::Vector2f& size = sizePtr[i]; + Nz::Vector3f& velocity = velPtr[i]; + + position += velPtr[i] * elapsedTime; + size += sizeGrowth * elapsedTime; + velocity *= (velocity.GetSquaredLength() >= 1.f) ? velFactor : 1.f; + + if (remainingLife <= 18.f) + { + for (const Ndk::EntityHandle& entity : spaceshipSystem.GetEntities()) + { + auto& spaceshipNode = entity->GetComponent(); + + Nz::Spheref spaceshipSphere(spaceshipNode.GetPosition(), 5.f); + if (spaceshipSphere.Contains(position)) + { + auto& spaceshipVel = entity->GetComponent(); + + Nz::Vector3f force = spaceshipVel.linearVelocity * 2.f + (position - spaceshipSphere.GetPosition()) * 10.f; + velocity += force * elapsedTime; + } + } + + TorpedoParticle* torpedos = static_cast(m_torpedoGroup->GetBuffer()); + std::size_t torpedoCount = m_torpedoGroup->GetParticleCount(); + for (std::size_t j = 0; j < torpedoCount; ++j) + { + Nz::Spheref tordedoSphere(torpedos[j].position, 5.f); + + if (tordedoSphere.Contains(position)) + { + Nz::Spheref tordedoCenter(torpedos[j].position, 2.f); + if (tordedoCenter.Contains(position)) + { + group.KillParticle(i); + break; + } + + Nz::Vector3f dir = (torpedos[j].position - position); + float length; + dir.Normalize(&length); + + remainingLife -= 100.f * elapsedTime / length; + size -= 100.f * sizeGrowth * elapsedTime / length; + velocity += 500.f * dir * elapsedTime / length; + velocity += torpedos[j].velocity * elapsedTime; + + break; //< There's no way a particle would be in multiple torpedo at once + } + } + } + } + }); + + m_fireGroup->AddController(movementController); + 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); + + float velFactor = std::pow(0.9f, elapsedTime / 0.1f); + for (unsigned int i = startId; i <= endId; ++i) + colorPtr[i].a = static_cast(Nz::Clamp(lifePtr[i] * 255.f, 0.f, 255.f)); + })); + + m_smokeGroup->AddController(movementController); + 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); + + for (unsigned int i = startId; i <= endId; ++i) + { + float alpha = std::min((maxSmokeLife - lifePtr[i]) * 255.f / 5.f, 255.f); + alpha -= std::max((maxSmokeLife - lifePtr[i]) / maxSmokeLife * 255.f, 0.f); + + colorPtr[i].a = static_cast(Nz::Clamp(alpha, 0.f, 255.f)); + } + })); + + Nz::MaterialRef fireMat = Nz::Material::New("Translucent3D"); + fireMat->EnableFaceCulling(true); + fireMat->SetDiffuseMap("resources/fire_particle.png"); + // Additive blending for fire + fireMat->SetDstBlend(Nz::BlendFunc_One); + fireMat->SetSrcBlend(Nz::BlendFunc_SrcAlpha); + + Nz::MaterialRef smokeMat = Nz::Material::New("Translucent3D"); + smokeMat->EnableFaceCulling(true); + 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) + { + auto colorPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Color); + auto posPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); + auto rotPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Rotation); + auto sizePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Size); + + 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) + { + auto colorPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Color); + auto posPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Position); + auto rotPtr = mapper.GetComponentPtr(Nz::ParticleComponent_Rotation); + auto sizePtr = mapper.GetComponentPtr(Nz::ParticleComponent_Size); + + renderQueue->AddBillboards(0, smokeMat, endId - startId + 1, posPtr, sizePtr, rotPtr, colorPtr); + })); + + ////////////////////////////////////////////////////////////////////////// + + m_ambientMusic.Play(); + m_turretFireSound.LoadFromFile("resources/turretFire.wav"); + m_turretReloadSound.LoadFromFile("resources/turretReload.wav"); + + //m_onMouseMoved.Connect(m_shared.target->GetEventHandler().OnMouseMoved, this, &SpacebattleExample::OnMouseMoved); + //m_shared.target->SetCursor(Nz::WindowCursor_None); + + ////////////////////////////////////////////////////////////////////////// + + Nz::TextSpriteRef introText = Nz::TextSprite::New(); + introText->Update(Nz::SimpleTextDrawer::Draw("--Tourelle de défense du secteur A407M2--\nLes contrôles ont été adaptés à vos contrôleurs:\nZQSD pour orienter la tourelle, espace pour tirer.\n", 72)); + introText->SetScale(0.5f); + + m_introText = m_shared.world3D->CreateEntity(); + Ndk::NodeComponent& introNode = m_introText->AddComponent(); + Ndk::GraphicsComponent& introGfx = m_introText->AddComponent(); + introGfx.Attach(introText, 1); + RegisterEntity(m_introText); + + Ndk::NodeComponent& cannonNode = m_turret.cannonEntity->GetComponent(); + + Nz::Boxf introAABB = introGfx.GetBoundingVolume().aabb; + introNode.SetPosition(cannonNode.GetForward() * 500.f + introNode.GetLeft() * introAABB.width / 2.f + introNode.GetUp() * introAABB.height / 2.f); +} + +void SpacebattleExample::Leave(Ndk::StateMachine& fsm) +{ + m_ambientMusic.Stop(); + m_shared.world3D->RemoveSystem(); + m_shared.world3D->RemoveSystem(); + m_turretFireSound.Stop(); + m_turretReloadSound.Stop(); + + ParticleDemo::Leave(fsm); +} + +bool SpacebattleExample::Update(Ndk::StateMachine& fsm, float elapsedTime) +{ + if (!ParticleDemo::Update(fsm, elapsedTime)) + return false; + + const float speed = 100.f; + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Z)) + m_turretCannonBaseRotation = std::max(m_turretCannonBaseRotation - speed * elapsedTime, -65.f); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::S)) + m_turretCannonBaseRotation = std::min(m_turretCannonBaseRotation + speed * elapsedTime, 40.f); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Q)) + m_turretBaseRotation += speed * elapsedTime; + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::D)) + m_turretBaseRotation -= speed * elapsedTime; + + m_turret.cannonBaseEntity->GetComponent().SetRotation(Nz::EulerAnglesf(m_turretCannonBaseRotation, 0.f, 0.f)); + m_turret.rotatingBaseEntity->GetComponent().SetRotation(Nz::EulerAnglesf(0.f, m_turretBaseRotation, 0.f)); + + bool discharged = m_turretShootTimer < 1.f; + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Space) && !discharged) + { + m_turretFireSound.Play(); + + m_turretShootTimer = -1.f; + + Ndk::NodeComponent& cannonNode = m_turret.cannonEntity->GetComponent(); + + TorpedoParticle* particle = static_cast(m_torpedoGroup->CreateParticle()); + particle->color = Nz::Color::White; + particle->position = cannonNode.ToGlobalPosition(Nz::Vector3f::Forward() * 10.f); + particle->rotation = 0.f; + particle->life = 15.f; + particle->size.Set(13.34f, 7.41f); + particle->size *= 2.f; + particle->velocity = cannonNode.GetForward() * 100.f; + } + + m_turretShootTimer += elapsedTime * 2.f; + if (discharged && m_turretShootTimer >= 1.f) + m_turretReloadSound.Play(); + + m_turret.cannonEntity->GetComponent().SetPosition(Nz::Vector3f::Backward() * std::sin(std::min(m_turretShootTimer, 0.f) * float(M_PI)) * 3.f); + + m_spaceshipSpawnCounter += elapsedTime; + if (m_spaceshipSpawnCounter >= 10.f) + { + m_spaceshipSpawnCounter -= 10.f; + + auto& spacestationNode = m_spacestationEntity->GetComponent(); + + Ndk::EntityHandle spaceship = m_spaceshipTemplate->Clone(); + RegisterEntity(spaceship); + auto& nodeComponent = spaceship->GetComponent(); + auto& spaceshipComponent = spaceship->GetComponent(); + + spaceshipComponent.targetPos = m_shared.viewer3D->GetComponent().GetPosition(); + nodeComponent.SetPosition(spacestationNode.GetPosition()); + nodeComponent.SetRotation(Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), spacestationNode.GetRight())); + nodeComponent.Move(Nz::Vector3f::Forward() * 15.f + Nz::Vector3f::Down() * 5.f, Nz::CoordSys_Local); + } + + m_introTimer -= elapsedTime; + if (m_introTimer <= 0.f && m_introText) + m_introText->Kill(); + + return true; +} + +void SpacebattleExample::CreateSpaceShip() +{ + m_spacestationEntity = m_shared.world3D->CreateEntity(); + RegisterEntity(m_spacestationEntity); + + Ndk::NodeComponent& spacestationNode = m_spacestationEntity->AddComponent(); + spacestationNode.SetPosition(Nz::Vector3f::Forward() * 500.f + Nz::Vector3f::Up() * 200.f + Nz::Vector3f::Right() * 250.f); + spacestationNode.SetRotation(Nz::EulerAnglesf(0.f, 15.f, 0.f)); + spacestationNode.SetScale(0.1f); + + Ndk::GraphicsComponent& spacestationGfx = m_spacestationEntity->AddComponent(); + spacestationGfx.Attach(&m_spacestationModel); +} + +void SpacebattleExample::CreateTurret() +{ + // Fixed base + m_turret.baseEntity = m_shared.world3D->CreateEntity(); + RegisterEntity(m_turret.baseEntity); + + Ndk::NodeComponent& baseNode = m_turret.baseEntity->AddComponent(); + //baseNode.SetParent(m_spacestationEntity); + baseNode.SetRotation(Nz::EulerAnglesf(0.f, 180.f, 0.f)); + + Ndk::GraphicsComponent& baseGfx = m_turret.baseEntity->AddComponent(); + baseGfx.Attach(&m_turret.baseModel); + + // Rotating base + m_turret.rotatingBaseEntity = m_shared.world3D->CreateEntity(); + RegisterEntity(m_turret.rotatingBaseEntity); + + Ndk::NodeComponent& rotatingBaseNode = m_turret.rotatingBaseEntity->AddComponent(); + rotatingBaseNode.SetParent(m_turret.baseEntity); + + Ndk::GraphicsComponent& rotatingBaseGfx = m_turret.rotatingBaseEntity->AddComponent(); + rotatingBaseGfx.Attach(&m_turret.rotatingBaseModel); + + // Cannon base + m_turret.cannonBaseEntity = m_shared.world3D->CreateEntity(); + RegisterEntity(m_turret.cannonBaseEntity); + + Ndk::NodeComponent& cannonBaseNode = m_turret.cannonBaseEntity->AddComponent(); + cannonBaseNode.SetPosition({0.f, 3.39623547f, 0.f}); + cannonBaseNode.SetParent(m_turret.rotatingBaseEntity); + + Ndk::GraphicsComponent& cannonBaseGfx = m_turret.cannonBaseEntity->AddComponent(); + cannonBaseGfx.Attach(&m_turret.cannonBaseModel); + + // Cannon anchor + m_turret.cannonAnchorEntity = m_shared.world3D->CreateEntity(); + RegisterEntity(m_turret.cannonAnchorEntity); + + Ndk::NodeComponent& cannonAnchorNode = m_turret.cannonAnchorEntity->AddComponent(); + cannonAnchorNode.SetPosition({0.f, 2.96482944f, 3.20705462f}); + cannonAnchorNode.SetParent(m_turret.cannonBaseEntity); + + // Cannon + m_turret.cannonEntity = m_shared.world3D->CreateEntity(); + RegisterEntity(m_turret.cannonEntity); + + Ndk::NodeComponent& cannonNode = m_turret.cannonEntity->AddComponent(); + cannonNode.SetParent(m_turret.cannonAnchorEntity); + cannonNode.SetRotation(Nz::EulerAnglesf(0.f, 180.f, 0.f)); + + Ndk::GraphicsComponent& cannonGfx = m_turret.cannonEntity->AddComponent(); + cannonGfx.Attach(&m_turret.cannonModel); +} + +void SpacebattleExample::OnMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event) +{ + const float speed = 0.1f; + + m_turretCannonBaseRotation = Nz::Clamp(m_turretCannonBaseRotation + speed * event.deltaY, -65.f, 40.f); + m_turretBaseRotation -= event.deltaX * speed; + + Nz::Mouse::SetPosition(m_shared.target->GetWidth() / 2, m_shared.target->GetHeight() / 2, *m_shared.target); +} diff --git a/examples/Particles/SpacebattleDemo.hpp b/examples/Particles/SpacebattleDemo.hpp new file mode 100644 index 000000000..44852a61f --- /dev/null +++ b/examples/Particles/SpacebattleDemo.hpp @@ -0,0 +1,71 @@ +#pragma once + +#ifndef NAZARA_EXAMPLES_PARTICLES_SPACEBATTLE_HPP +#define NAZARA_EXAMPLES_PARTICLES_SPACEBATTLE_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common.hpp" + +class SpacebattleExample : public ParticleDemo +{ + public: + SpacebattleExample(ExampleShared& sharedData); + ~SpacebattleExample() = default; + + void Enter(Ndk::StateMachine& fsm) override; + void Leave(Ndk::StateMachine& fsm) override; + bool Update(Ndk::StateMachine& fsm, float elapsedTime) override; + + private: + void CreateSpaceShip(); + void CreateTurret(); + void OnMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event); + + struct Turret + { + Nz::Model baseModel; + Nz::Model cannonModel; + Nz::Model cannonBaseModel; + Nz::Model rotatingBaseModel; + Ndk::EntityHandle baseEntity; + Ndk::EntityHandle cannonAnchorEntity; + Ndk::EntityHandle cannonEntity; + Ndk::EntityHandle cannonBaseEntity; + Ndk::EntityHandle rotatingBaseEntity; + }; + + Turret m_turret; + float m_introTimer; + float m_spaceshipSpawnCounter; + float m_turretBaseRotation; + float m_turretCannonBaseRotation; + float m_turretShootTimer; + Nz::Model m_spaceshipModel; + Nz::Model m_spacestationModel; + Nz::Music m_ambientMusic; + Nz::ParticleDeclarationRef m_torpedoDeclaration; + Nz::ParticleRendererRef m_laserBeamRenderer; + Nz::Sound m_turretFireSound; + Nz::Sound m_turretReloadSound; + Nz::SkyboxBackground m_skybox; + Ndk::EntityHandle m_introText; + Ndk::EntityHandle m_spaceshipTemplate; + Ndk::EntityHandle m_spacestationEntity; + Ndk::ParticleGroupComponentHandle m_fireGroup; + Ndk::ParticleGroupComponentHandle m_smokeGroup; + Ndk::ParticleGroupComponentHandle m_torpedoGroup; + + NazaraSlot(Nz::EventHandler, OnMouseMoved, m_onMouseMoved); +}; + +#endif // NAZARA_EXAMPLES_PARTICLES_SPACEBATTLE_HPP diff --git a/examples/Particles/build.lua b/examples/Particles/build.lua new file mode 100644 index 000000000..2e1a37801 --- /dev/null +++ b/examples/Particles/build.lua @@ -0,0 +1,13 @@ +EXAMPLE.Name = "Particles" + +EXAMPLE.EnableConsole = true + +EXAMPLE.Files = { + "*.hpp", + "*.inl", + "*.cpp" +} + +EXAMPLE.Libraries = { + "NazaraSDK" +} diff --git a/examples/Particles/main.cpp b/examples/Particles/main.cpp new file mode 100644 index 000000000..67bf99754 --- /dev/null +++ b/examples/Particles/main.cpp @@ -0,0 +1,202 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "LogoDemo.hpp" +#include "SpacebattleDemo.hpp" +#include + +int main() +{ + Nz::ContextParameters::defaultCompatibilityProfile = true; + + Ndk::Application app; + + // Mix all sounds in mono (in order to give them 3D position) + Nz::SoundBufferParams soundParams; + soundParams.forceMono = true; + + Nz::SoundBufferManager::SetDefaultParameters(soundParams); + + // Pour commencer le mode vidéo, celui-ci va définir la taille de la zone de rendu et le nombre de bits par pixels + Nz::VideoMode mode = Nz::VideoMode::GetDesktopMode(); // Nous récupérons le mode vidéo du bureau + + // Nous allons prendre les trois quarts de la résolution du bureau pour notre fenêtre + mode.width = 3 * mode.width / 4; + mode.height = 3 * mode.height / 4; + + Nz::ContextParameters targetParams; + targetParams.antialiasingLevel = 0; + + Nz::RenderWindow& window = app.AddWindow(mode, "Nazara demo - Particles", Nz::WindowStyle_Closable, targetParams); + //Nz::RenderWindow& window = app.AddWindow(Nz::VideoMode(1920, 1080), "Nazara demo - Particles", Nz::WindowStyle_Fullscreen, targetParams); + + Ndk::World& world3D = app.AddWorld(); + Ndk::World& world2D = app.AddWorld(); + + std::random_device randomDevice; + + ExampleShared shared; + shared.randomGen.seed(randomDevice()); + shared.target = &window; + shared.world2D = &world2D; + shared.world3D = &world3D; + + shared.demoName = Nz::TextSprite::New(); + shared.demoName->Update(Nz::SimpleTextDrawer::Draw("XX - DemoName", 48)); + + shared.fpsCount = Nz::TextSprite::New(); + shared.fpsCount->Update(Nz::SimpleTextDrawer::Draw("XXXXX FPS", 24)); + + shared.particleCount = Nz::TextSprite::New(); + shared.particleCount->Update(Nz::SimpleTextDrawer::Draw("XXXXX particles", 36)); + + world2D.GetSystem().SetGlobalUp(Nz::Vector3f::Down()); + world3D.GetSystem().ChangeRenderTechnique(); + + + Ndk::EntityHandle viewEntity = world2D.CreateEntity(); + viewEntity->AddComponent(); + + Ndk::CameraComponent& viewer = viewEntity->AddComponent(); + viewer.SetTarget(&window); + viewer.SetProjectionType(Nz::ProjectionType_Orthogonal); + + shared.viewer2D = viewEntity; + + Ndk::EntityHandle cameraEntity = world3D.CreateEntity(); + cameraEntity->AddComponent(); + cameraEntity->AddComponent(); + + Ndk::CameraComponent& camera = cameraEntity->AddComponent(); + camera.SetTarget(&window); + camera.SetZFar(10000.f); + + shared.viewer3D = cameraEntity; + + Ndk::EntityHandle demoNameEntity = world2D.CreateEntity(); + Ndk::NodeComponent& demoNameNode = demoNameEntity->AddComponent(); + Ndk::GraphicsComponent& demoNameGfx = demoNameEntity->AddComponent(); + demoNameGfx.Attach(shared.demoName, 1); + + Ndk::EntityHandle fpsCountEntity = world2D.CreateEntity(); + Ndk::NodeComponent& fpsNode = fpsCountEntity->AddComponent(); + Ndk::GraphicsComponent& fpsGfx = fpsCountEntity->AddComponent(); + fpsGfx.Attach(shared.fpsCount, 1); + + Ndk::EntityHandle particleCountEntity = world2D.CreateEntity(); + Ndk::NodeComponent& particleCountNode = particleCountEntity->AddComponent(); + Ndk::GraphicsComponent& particleCountGfx = particleCountEntity->AddComponent(); + particleCountGfx.Attach(shared.particleCount, 1); + + + Nz::Boxf fpsCountBox = fpsGfx.GetBoundingVolume().aabb; + Nz::Boxf particleCountBox = particleCountGfx.GetBoundingVolume().aabb; + + demoNameNode.SetPosition(5.f, 5.f); + particleCountNode.SetPosition(5.f, window.GetHeight() - particleCountBox.height - 5.f); + 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)); + + std::size_t demoIndex = 0; + Ndk::StateMachine stateMachine(shared.demos[demoIndex]); + + window.EnableEventPolling(true); + + while (app.Run()) + { + Nz::WindowEvent event; + while (window.PollEvent(&event)) + { + switch (event.type) + { + case Nz::WindowEventType_KeyPressed: + { + switch (event.key.code) + { + case Nz::Keyboard::Backspace: + stateMachine.ChangeState(stateMachine.GetCurrentState()); + break; + + case Nz::Keyboard::Escape: + app.Quit(); + break; + + case Nz::Keyboard::Left: + { + if (shared.demos.size() <= 1) + break; + + if (demoIndex == 0) + demoIndex = shared.demos.size(); + + demoIndex--; + stateMachine.ChangeState(shared.demos[demoIndex]); + break; + } + + case Nz::Keyboard::Right: + { + if (shared.demos.size() <= 1) + break; + + demoIndex++; + if (demoIndex == shared.demos.size()) + demoIndex = 0; + + stateMachine.ChangeState(shared.demos[demoIndex]); + break; + } + + case Nz::Keyboard::Pause: + { + auto& velocitySystem = shared.world3D->GetSystem(); + velocitySystem.Enable(!velocitySystem.IsEnabled()); + break; + } + + case Nz::Keyboard::F5: + { + Nz::Image screenshot; + screenshot.Create(Nz::ImageType_2D, Nz::PixelFormatType_RGBA8, 1920, 1080); + window.CopyToImage(&screenshot); + + static unsigned int counter = 1; + screenshot.SaveToFile("screenshot_" + Nz::String::Number(counter++) + ".png"); + break; + } + + default: + break; + } + break; + } + + case Nz::WindowEventType_Quit: + window.Close(); + break; + + default: + break; + } + } + + stateMachine.Update(app.GetUpdateTime()); + + window.Display(); + } + + return EXIT_SUCCESS; +} diff --git a/include/Nazara/Audio.hpp b/include/Nazara/Audio.hpp index d0fd17d6f..5becbb066 100644 --- a/include/Nazara/Audio.hpp +++ b/include/Nazara/Audio.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 24 Jun 2015 at 13:55:50 +// This file was automatically generated /* Nazara Engine - Audio module diff --git a/include/Nazara/Audio/Music.hpp b/include/Nazara/Audio/Music.hpp index f31882890..29e71fab7 100644 --- a/include/Nazara/Audio/Music.hpp +++ b/include/Nazara/Audio/Music.hpp @@ -73,6 +73,7 @@ namespace Nz bool FillAndQueueBuffer(unsigned int buffer); void MusicThread(); + void StopThread(); static MusicLoader::LoaderList s_loaders; }; diff --git a/include/Nazara/Core.hpp b/include/Nazara/Core.hpp index 5f3c85c4c..419ddaae9 100644 --- a/include/Nazara/Core.hpp +++ b/include/Nazara/Core.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 09 May 2016 at 17:07:09 +// This file was automatically generated /* Nazara Engine - Core module diff --git a/include/Nazara/Core/AbstractLogger.docx b/include/Nazara/Core/AbstractLogger.docx deleted file mode 100644 index 6ac06b95c..000000000 --- a/include/Nazara/Core/AbstractLogger.docx +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2015 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 - -/*! -* \ingroup core -* \class Nz::AbstractLogger -* \brief Logger interface -*/ - diff --git a/include/Nazara/Core/Algorithm.hpp b/include/Nazara/Core/Algorithm.hpp index 5bb461f26..a6d5e77a7 100644 --- a/include/Nazara/Core/Algorithm.hpp +++ b/include/Nazara/Core/Algorithm.hpp @@ -22,6 +22,7 @@ namespace Nz template decltype(auto) Apply(F&& fn, Tuple&& t); template decltype(auto) Apply(O& object, F&& fn, Tuple&& t); + template constexpr std::size_t BitCount(); template ByteArray ComputeHash(HashType hash, const T& v); template ByteArray ComputeHash(AbstractHash* hash, const T& v); template constexpr std::size_t CountOf(T(&name)[N]) noexcept; diff --git a/include/Nazara/Core/Algorithm.inl b/include/Nazara/Core/Algorithm.inl index b02924446..fea1fd964 100644 --- a/include/Nazara/Core/Algorithm.inl +++ b/include/Nazara/Core/Algorithm.inl @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace Nz @@ -70,6 +71,17 @@ namespace Nz return Detail::ApplyImplMethod(object, std::forward(fn), std::forward(t), std::make_index_sequence()); } + /*! + * \ingroup core + * \brief Returns the number of bits occupied by the type T + * \return Number of bits occupied by the type + */ + template + constexpr std::size_t BitCount() + { + return CHAR_BIT * sizeof(T); + } + /*! * \ingroup core * \brief Computes the hash of a hashable object diff --git a/include/Nazara/Core/Bitset.hpp b/include/Nazara/Core/Bitset.hpp index 5c2746d16..622238854 100644 --- a/include/Nazara/Core/Bitset.hpp +++ b/include/Nazara/Core/Bitset.hpp @@ -8,6 +8,7 @@ #define NAZARA_BITSET_HPP #include +#include #include #include #include @@ -24,6 +25,7 @@ namespace Nz public: class Bit; + using PointerSequence = std::pair; //< Start pointer, bit offset Bitset(); explicit Bitset(std::size_t bitCount, bool val); @@ -35,6 +37,8 @@ namespace Nz Bitset(Bitset&& bitset) noexcept = default; ~Bitset() noexcept = default; + template void AppendBits(T bits, std::size_t bitCount); + void Clear() noexcept; std::size_t Count() const; void Flip(); @@ -47,6 +51,9 @@ namespace Nz std::size_t GetCapacity() const; std::size_t GetSize() const; + PointerSequence Read(const void* ptr, std::size_t bitCount); + PointerSequence Read(const PointerSequence& sequence, std::size_t bitCount); + void PerformsAND(const Bitset& a, const Bitset& b); void PerformsNOT(const Bitset& a); void PerformsOR(const Bitset& a, const Bitset& b); @@ -60,6 +67,8 @@ namespace Nz void Reset(); void Reset(std::size_t bit); + void Reverse(); + void Set(bool val = true); void Set(std::size_t bit, bool val = true); void SetBlock(std::size_t i, Block block); @@ -102,9 +111,11 @@ namespace Nz Bitset& operator^=(const Bitset& bitset); static constexpr Block fullBitMask = std::numeric_limits::max(); - static constexpr std::size_t bitsPerBlock = std::numeric_limits::digits; + static constexpr std::size_t bitsPerBlock = BitCount(); static constexpr std::size_t npos = std::numeric_limits::max(); + static Bitset FromPointer(const void* ptr, std::size_t bitCount, PointerSequence* sequence = nullptr); + private: std::size_t FindFirstFrom(std::size_t blockIndex) const; Block GetLastBlockMask() const; @@ -154,6 +165,9 @@ namespace Nz Block m_mask; }; + template + std::ostream& operator<<(std::ostream& out, const Bitset& bitset); + template bool operator==(const Bitset& lhs, const Nz::Bitset& rhs); diff --git a/include/Nazara/Core/Bitset.inl b/include/Nazara/Core/Bitset.inl index 6ddb252e7..afec6983a 100644 --- a/include/Nazara/Core/Bitset.inl +++ b/include/Nazara/Core/Bitset.inl @@ -6,7 +6,6 @@ #include #include #include -#include #include #include @@ -122,13 +121,13 @@ namespace Nz { if (sizeof(T) <= sizeof(Block)) { - m_bitCount = std::numeric_limits::digits; + m_bitCount = BitCount(); m_blocks.push_back(static_cast(value)); } else { // Note: I was kinda tired when I wrote this, there's probably a much easier method than checking bits to write bits - for (std::size_t bitPos = 0; bitPos < std::numeric_limits::digits; bitPos++) + for (std::size_t bitPos = 0; bitPos < BitCount(); bitPos++) { if (value & (T(1U) << bitPos)) UnboundedSet(bitPos, true); @@ -137,11 +136,63 @@ namespace Nz } /*! - * \brief Clears the content of the bitset, GetSize() is now equals to 0 + * \brief Appends bits to the bitset * - * \remark The memory allocated is not released + * This function extends the bitset with bits extracted from an integer value + * + * \param bits An integer value from where bits will be extracted + * \param bitCount Number of bits to extract from the value + * + * \remark This function does not require bitCount to be lower or equal to the number of bits of T, thus + * reading 32 bits from a UInt8 will work (by extracting the first 8 bits values and appending 24 zeros afterneath). + * + * \see AppendBits + * \see Read */ + template + template + void Bitset::AppendBits(T bits, std::size_t bitCount) + { + std::size_t bitShift = m_bitCount % bitsPerBlock; + m_bitCount += bitCount; + if (bitShift != 0) + { + std::size_t remainingBits = bitsPerBlock - bitShift; + m_blocks.back() |= Block(bits) << bitShift; + bits >>= bitsPerBlock - bitShift; + + bitCount -= std::min(remainingBits, bitCount); + } + + if (bitCount > 0) + { + std::size_t blockCount = ComputeBlockCount(bitCount); + for (std::size_t block = 0; block < blockCount - 1; ++block) + { + m_blocks.push_back(static_cast(bits)); + bits = (BitCount() < BitCount()) ? bits >> BitCount() : 0U; + bitCount -= BitCount(); + } + + // For the last iteration, mask out the bits we don't want + std::size_t remainingBits = bitCount; + + bits &= ((Block(1U) << remainingBits) - 1U); + m_blocks.push_back(static_cast(bits)); + } + } + + /*! + * \brief Clears the content of the bitset + * + * This function clears the bitset content, resetting its bit and block count at zero. + * + * \remark This does not changes the bits values to zero but empties the bitset, to reset the bits use the Reset() function + * \remark This call does not changes the bitset capacity + * + * \see Reset() + */ template void Bitset::Clear() noexcept { @@ -151,9 +202,9 @@ namespace Nz /*! * \brief Counts the number of bits set to 1 + * * \return Number of bits set to 1 */ - template std::size_t Bitset::Count() const { @@ -169,8 +220,9 @@ namespace Nz /*! * \brief Flips each bit of the bitset + * + * This function flips every bit of the bitset, which means every '1' turns into a '0' and conversely. */ - template void Bitset::Flip() { @@ -182,9 +234,9 @@ namespace Nz /*! * \brief Finds the first bit set to one in the bitset - * \return Index of the first bit + * + * \return The 0-based index of the first bit enabled */ - template std::size_t Bitset::FindFirst() const { @@ -192,14 +244,14 @@ namespace Nz } /*! - * \brief Finds the next bit set to one in the bitset - * \return Index of the next bit if exists or npos + * \brief Finds the next enabled in the bitset * - * \param bit Index of the bit, the search begin with bit + 1 + * \param bit Index of the last bit found, which will not be treated by this function * - * \remark Produce a NazaraAssert if bit is greather than number of bits in bitset + * \return Index of the next enabled bit or npos if all the following bits are disabled + * + * \remark This function is typically used in for-loops to iterate on bits */ - template std::size_t Bitset::FindNext(std::size_t bit) const { @@ -275,6 +327,76 @@ namespace Nz return m_bitCount; } + /*! + * \brief Read a byte sequence into a bitset + * + * This function extends the bitset with bits read from a byte sequence + * + * \param ptr A pointer to the start of the byte sequence + * \param bitCount Number of bits to read from the byte sequence + * + * \returns A pointer to the next byte to read along with the next bit index (useful when reading multiple times) + * + * \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount) + * + * \see AppendBits + * \see Read + */ + template + typename Bitset::PointerSequence Bitset::Read(const void* ptr, std::size_t bitCount) + { + return Read(PointerSequence(ptr, 0U), bitCount); + } + + /*! + * \brief Read a byte sequence into a bitset + * + * This function extends the bitset with bits read from a pointer sequence (made of a pointer and a bit index) + * + * \param sequence A pointer sequence to the start of the byte sequence + * \param bitCount Number of bits to read from the byte sequence + * + * \returns A pointer to the next byte to read along with the next bit index (useful when reading multiple times) + * + * \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount) + * + * \see AppendBits + * \see Read + */ + template + typename Bitset::PointerSequence Bitset::Read(const PointerSequence& sequence, std::size_t bitCount) + { + NazaraAssert(sequence.first, "Invalid pointer sequence"); + NazaraAssert(sequence.second < 8, "Invalid next bit index (must be < 8)"); + + std::size_t totalBitCount = sequence.second + bitCount; + + const UInt8* u8Ptr = static_cast(sequence.first); + const UInt8* endPtr = u8Ptr + ((totalBitCount != 0) ? (totalBitCount - 1) / 8 : 0); + const UInt8* nextPtr = endPtr + ((totalBitCount % 8 != 0) ? 0 : 1); + + // Read the first block apart to apply a mask on the first byte if necessary + if (sequence.second != 0) + { + UInt8 mask = ~((1U << sequence.second) - 1U); + + std::size_t readCount = std::min(bitCount, 8 - sequence.second); + AppendBits(Block(*u8Ptr++ & mask) >> sequence.second, readCount); + bitCount -= readCount; + } + + // And then read the remaining bytes + while (u8Ptr <= endPtr) + { + std::size_t bitToRead = std::min(bitCount, 8); + AppendBits(*u8Ptr++, bitToRead); + bitCount -= bitToRead; + } + + // Returns informations to continue reading + return PointerSequence(nextPtr, totalBitCount % 8); + } + /*! * \brief Performs the "AND" operator between two bitsets * @@ -289,15 +411,17 @@ namespace Nz { std::pair minmax = std::minmax(a.GetBlockCount(), b.GetBlockCount()); - // We reinitialise our blocks with zero - m_blocks.clear(); - m_blocks.resize(minmax.second, 0U); + m_blocks.resize(minmax.second); m_bitCount = std::max(a.GetSize(), b.GetSize()); // In case of the "AND", we can stop with the smallest size (because x & 0 = 0) for (std::size_t i = 0; i < minmax.first; ++i) m_blocks[i] = a.GetBlock(i) & b.GetBlock(i); + // And then reset every other block to zero + for (std::size_t i = minmax.first; i < minmax.second; ++i) + m_blocks[i] = 0U; + ResetExtraBits(); } @@ -458,6 +582,30 @@ namespace Nz Set(bit, false); } + /*! + * \brief Reverse the order of bits in a bitset + * + * Reverse the order of bits in the bitset (first bit swap with the last one, etc.) + */ + template + void Bitset::Reverse() + { + if (m_bitCount == 0) + return; + + std::size_t i = 0; + std::size_t j = m_bitCount - 1; + + while (i < j) + { + bool bit1 = Test(i); + bool bit2 = Test(j); + + Set(i++, bit2); + Set(j--, bit1); + } + } + /*! * \brief Sets the bitset to val * @@ -535,27 +683,28 @@ namespace Nz return; } - auto div = std::lldiv(pos, bitsPerBlock); - if (div.rem != 0) + std::size_t blockShift = pos / bitsPerBlock; + std::size_t remainder = pos % bitsPerBlock; + if (remainder != 0) { std::size_t lastIndex = m_blocks.size() - 1; - std::size_t remaining = bitsPerBlock - div.rem; + std::size_t remaining = bitsPerBlock - remainder; - for (std::size_t i = lastIndex - div.quot; i > 0; --i) - m_blocks[i + div.quot] = (m_blocks[i] << div.rem) | (m_blocks[i - 1] >> remaining); + for (std::size_t i = lastIndex - blockShift; i > 0; --i) + m_blocks[i + blockShift] = (m_blocks[i] << remainder) | (m_blocks[i - 1] >> remaining); - m_blocks[div.quot] = m_blocks[0] << div.rem; + m_blocks[blockShift] = m_blocks[0] << remainder; - std::fill_n(m_blocks.begin(), div.quot, Block(0)); + std::fill_n(m_blocks.begin(), blockShift, Block(0)); } else { for (auto it = m_blocks.rbegin(); it != m_blocks.rend(); ++it) { - if (static_cast(std::distance(m_blocks.rbegin(), it) + div.quot) < m_blocks.size()) + if (static_cast(std::distance(m_blocks.rbegin(), it) + blockShift) < m_blocks.size()) { auto shiftedIt = it; - std::advance(shiftedIt, div.quot); + std::advance(shiftedIt, blockShift); *it = *shiftedIt; } @@ -588,27 +737,28 @@ namespace Nz return; } - auto div = std::lldiv(pos, bitsPerBlock); - if (div.rem != 0) + std::size_t blockShift = pos / bitsPerBlock; + std::size_t remainder = pos % bitsPerBlock; + if (remainder != 0) { std::size_t lastIndex = m_blocks.size() - 1; - std::size_t remaining = bitsPerBlock - div.rem; + std::size_t remaining = bitsPerBlock - remainder; - for (std::size_t i = div.quot; i < lastIndex; ++i) - m_blocks[i - div.quot] = (m_blocks[i] >> div.rem) | (m_blocks[i + 1] << remaining); + for (std::size_t i = blockShift; i < lastIndex; ++i) + m_blocks[i - blockShift] = (m_blocks[i] >> remainder) | (m_blocks[i + 1] << remaining); - m_blocks[lastIndex - div.quot] = m_blocks[lastIndex] >> div.rem; + m_blocks[lastIndex - blockShift] = m_blocks[lastIndex] >> remainder; - std::fill_n(m_blocks.begin() + (m_blocks.size() - div.quot), div.quot, Block(0)); + std::fill_n(m_blocks.begin() + (m_blocks.size() - blockShift), blockShift, Block(0)); } else { for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it) { - if (static_cast(std::distance(m_blocks.begin(), it) + div.quot) < m_blocks.size()) + if (static_cast(std::distance(m_blocks.begin(), it) + blockShift) < m_blocks.size()) { auto shiftedIt = it; - std::advance(shiftedIt, div.quot); + std::advance(shiftedIt, blockShift); *it = *shiftedIt; } @@ -716,7 +866,7 @@ namespace Nz { static_assert(std::is_integral() && std::is_unsigned(), "T must be a unsigned integral type"); - NazaraAssert(m_bitCount <= std::numeric_limits::digits, "Bit count cannot be greater than T bit count"); + NazaraAssert(m_bitCount <= BitCount(), "Bit count cannot be greater than T bit count"); T value = 0; for (std::size_t i = 0; i < m_blocks.size(); ++i) @@ -989,13 +1139,41 @@ namespace Nz return *this; } + /*! + * \brief Builds a bitset from a byte sequence + * + * This function builds a bitset using a byte sequence by reading bitCount bits from it + * + * \param ptr A pointer to the start of the byte sequence + * \param bitCount Number of bits to read from the byte sequence + * \param sequence Optional data to pass to a next call to Read + * + * \return The constructed bitset + * + * \remark For technical reasons, ceil(bitCount / 8) bytes from the sequence will always be read (even with non-multiple-of-8 bitCount) + * + * \see AppendBits + * \see Read + */ + template + Bitset Bitset::FromPointer(const void* ptr, std::size_t bitCount, PointerSequence* sequence) + { + Bitset bitset; + + if (sequence) + *sequence = bitset.Read(ptr, bitCount); + else + bitset.Read(ptr, bitCount); + + return bitset; + } + /*! * \brief Finds the position of the first bit set to true after the blockIndex * \return The position of the bit * * \param blockIndex Index of the block */ - template std::size_t Bitset::FindFirstFrom(std::size_t blockIndex) const { @@ -1124,7 +1302,7 @@ namespace Nz template bool Bitset::Bit::Test() const { - return m_block & m_mask; + return (m_block & m_mask) != 0; } /*! @@ -1269,6 +1447,14 @@ namespace Nz return *this; } + + template + std::ostream& operator<<(std::ostream& out, const Bitset& bitset) + { + return out << bitset.ToString(); + } + + /*! * \brief Compares two bitsets * \return true if the two bitsets are the same diff --git a/include/Nazara/Core/ByteArray.hpp b/include/Nazara/Core/ByteArray.hpp index 90f9c5d03..4bdc34150 100644 --- a/include/Nazara/Core/ByteArray.hpp +++ b/include/Nazara/Core/ByteArray.hpp @@ -88,7 +88,7 @@ namespace Nz inline void ShrinkToFit(); inline void Swap(ByteArray& other); - inline String ToHex() const; + String ToHex() const; inline String ToString() const; // STL interface diff --git a/include/Nazara/Core/ByteArray.inl b/include/Nazara/Core/ByteArray.inl index 068bee4b6..b5d8b1510 100644 --- a/include/Nazara/Core/ByteArray.inl +++ b/include/Nazara/Core/ByteArray.inl @@ -465,22 +465,6 @@ namespace Nz m_array.swap(other.m_array); } - /*! - * \brief Gives a string representation in base 16 - * \return String in base 16 - */ - - inline String ByteArray::ToHex() const - { - std::size_t length = m_array.size() * 2; - - String hexOutput(length, '\0'); - for (std::size_t i = 0; i < m_array.size(); ++i) - std::sprintf(&hexOutput[i * 2], "%02x", m_array[i]); - - return hexOutput; - } - /*! * \brief Gives a string representation * \return String where each byte is converted to char diff --git a/include/Nazara/Core/ByteStream.hpp b/include/Nazara/Core/ByteStream.hpp index fe1516b06..fab7c8f4a 100644 --- a/include/Nazara/Core/ByteStream.hpp +++ b/include/Nazara/Core/ByteStream.hpp @@ -1,4 +1,4 @@ -// Copyright (C) 2015 Jérôme Leclercq +// Copyright (C) 2015 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 @@ -19,7 +19,7 @@ namespace Nz { public: inline ByteStream(Stream* stream = nullptr); - ByteStream(ByteArray* byteArray, UInt32 openMode = OpenMode_ReadWrite); + ByteStream(ByteArray* byteArray, OpenModeFlags openMode = OpenMode_ReadWrite); ByteStream(void* ptr, Nz::UInt64 size); ByteStream(const void* ptr, Nz::UInt64 size); ByteStream(const ByteStream&) = delete; @@ -36,7 +36,7 @@ namespace Nz inline void SetDataEndianness(Endianness endiannes); inline void SetStream(Stream* stream); - void SetStream(ByteArray* byteArray, UInt32 openMode = OpenMode_ReadWrite); + void SetStream(ByteArray* byteArray, OpenModeFlags openMode = OpenMode_ReadWrite); void SetStream(void* ptr, Nz::UInt64 size); void SetStream(const void* ptr, Nz::UInt64 size); diff --git a/include/Nazara/Core/ConditionVariable.hpp b/include/Nazara/Core/ConditionVariable.hpp index f6aeafe9b..19ab9e863 100644 --- a/include/Nazara/Core/ConditionVariable.hpp +++ b/include/Nazara/Core/ConditionVariable.hpp @@ -29,7 +29,7 @@ namespace Nz bool Wait(Mutex* mutex, UInt32 timeout); ConditionVariable& operator=(const ConditionVariable&) = delete; - inline ConditionVariable& operator=(ConditionVariable&& condition) noexcept; + ConditionVariable& operator=(ConditionVariable&& condition) noexcept; private: ConditionVariableImpl* m_impl; diff --git a/include/Nazara/Core/Enums.hpp b/include/Nazara/Core/Enums.hpp index 7a5c161ab..765505575 100644 --- a/include/Nazara/Core/Enums.hpp +++ b/include/Nazara/Core/Enums.hpp @@ -7,6 +7,8 @@ #ifndef NAZARA_ENUMS_CORE_HPP #define NAZARA_ENUMS_CORE_HPP +#include + namespace Nz { enum CoordSys @@ -73,23 +75,31 @@ namespace Nz HashType_Max = HashType_Whirlpool }; - enum OpenModeFlags + enum OpenMode { - OpenMode_NotOpen = 0x00, // Use the current mod of opening + OpenMode_NotOpen, // Use the current mod of opening - OpenMode_Append = 0x01, // Disable writing on existing parts and put the cursor at the end - OpenMode_Lock = 0x02, // Disable modifying the file before it is open - OpenMode_MustExit = 0x04, // Fail if the file doesn't exists, even if opened in write mode - OpenMode_ReadOnly = 0x08, // Open in read only - OpenMode_Text = 0x10, // Open in text mod - OpenMode_Truncate = 0x20, // Create the file if it doesn't exist and empty it if it exists - OpenMode_WriteOnly = 0x40, // Open in write only, create the file if it doesn't exist + OpenMode_Append, // Disable writing on existing parts and put the cursor at the end + OpenMode_Lock, // Disable modifying the file before it is open + OpenMode_MustExist, // Fail if the file doesn't exists, even if opened in write mode + OpenMode_ReadOnly, // Open in read only + OpenMode_Text, // Open in text mod + OpenMode_Truncate, // Create the file if it doesn't exist and empty it if it exists + OpenMode_WriteOnly, // Open in write only, create the file if it doesn't exist - OpenMode_ReadWrite = OpenMode_ReadOnly | OpenMode_WriteOnly, // Open in read and write - - OpenMode_Max = OpenMode_WriteOnly * 2 - 1 + OpenMode_Max = OpenMode_WriteOnly }; + template<> + struct EnableFlagsOperators + { + static constexpr bool value = true; + }; + + using OpenModeFlags = Flags; + + constexpr OpenModeFlags OpenMode_ReadWrite = OpenMode_ReadOnly | OpenMode_WriteOnly; + enum ParameterType { ParameterType_Boolean, @@ -173,16 +183,24 @@ namespace Nz SphereType_Max = SphereType_UV }; - enum StreamOptionFlags + enum StreamOption { - StreamOption_None = 0, + StreamOption_None, - StreamOption_Sequential = 0x1, - StreamOption_Text = 0x2, + StreamOption_Sequential, + StreamOption_Text, - StreamOption_Max = StreamOption_Text * 2 - 1 + StreamOption_Max = StreamOption_Text }; + template<> + struct EnableFlagsOperators + { + static constexpr bool value = true; + }; + + using StreamOptionFlags = Flags; + enum Ternary { Ternary_False, diff --git a/include/Nazara/Core/File.hpp b/include/Nazara/Core/File.hpp index 59b2b5457..d4d1e6522 100644 --- a/include/Nazara/Core/File.hpp +++ b/include/Nazara/Core/File.hpp @@ -31,7 +31,7 @@ namespace Nz public: File(); File(const String& filePath); - File(const String& filePath, UInt32 openMode); + File(const String& filePath, OpenModeFlags openMode); File(const File&) = delete; File(File&& file) noexcept; ~File(); @@ -57,8 +57,8 @@ namespace Nz bool IsOpen() const; - bool Open(unsigned int openMode = OpenMode_NotOpen); - bool Open(const String& filePath, unsigned int openMode = OpenMode_NotOpen); + bool Open(OpenModeFlags openMode = OpenMode_NotOpen); + bool Open(const String& filePath, OpenModeFlags openMode = OpenMode_NotOpen); bool Rename(const String& newFilePath); diff --git a/include/Nazara/Core/Flags.hpp b/include/Nazara/Core/Flags.hpp new file mode 100644 index 000000000..e56d723e5 --- /dev/null +++ b/include/Nazara/Core/Flags.hpp @@ -0,0 +1,60 @@ +// Copyright (C) 2016 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_FLAGS_HPP +#define NAZARA_FLAGS_HPP + +#include +#include + +namespace Nz +{ + template + class Flags + { + static_assert(std::is_enum::value, "Type must be an enumeration"); + + public: + constexpr Flags(UInt32 value); + constexpr Flags(E enumVal); + + explicit constexpr operator bool() const; + explicit constexpr operator UInt32() const; + + constexpr Flags operator~() const; + constexpr Flags operator&(Flags rhs) const; + constexpr Flags operator|(Flags rhs) const; + constexpr Flags operator^(Flags rhs) const; + + constexpr bool operator==(Flags rhs) const; + constexpr bool operator!=(Flags rhs) const; + + /*constexpr*/ Flags& operator|=(Flags rhs); + /*constexpr*/ Flags& operator&=(Flags rhs); + /*constexpr*/ Flags& operator^=(Flags rhs); + + static constexpr UInt32 GetFlagValue(E enumValue); + + private: + UInt32 m_value; + }; + + // From: https://www.justsoftwaresolutions.co.uk/cplusplus/using-enum-classes-as-bitfields.html + template + struct EnableFlagsOperators + { + static constexpr bool value = false; + }; + + template constexpr std::enable_if_t::value, Flags> operator~(E lhs); + template constexpr std::enable_if_t::value, Flags> operator|(E lhs, E rhs); + template constexpr std::enable_if_t::value, Flags> operator&(E lhs, E rhs); + template constexpr std::enable_if_t::value, Flags> operator^(E lhs, E rhs); +} + +#include + +#endif // NAZARA_FLAGS_HPP diff --git a/include/Nazara/Core/Flags.inl b/include/Nazara/Core/Flags.inl new file mode 100644 index 000000000..7a23861a2 --- /dev/null +++ b/include/Nazara/Core/Flags.inl @@ -0,0 +1,134 @@ +// Copyright (C) 2015 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::Flags + * \brief Core class that represents a set of bits + * + * This class meets the requirements of Container, AllocatorAwareContainer, SequenceContainer + */ + + template + constexpr Flags::Flags(UInt32 value) : + m_value(value) + { + } + + template + constexpr Flags::Flags(E enumVal) : + Flags(GetFlagValue(enumVal)) + { + } + + template + constexpr Flags::operator bool() const + { + return m_value != 0; + } + + template + constexpr Flags::operator UInt32() const + { + return m_value; + } + + template + constexpr Flags Flags::operator~() const + { + return Flags(~m_value); + } + + template + constexpr Flags Flags::operator&(Flags rhs) const + { + return Flags(m_value & rhs.m_value); + } + + template + constexpr Flags Flags::operator|(Flags rhs) const + { + return Flags(m_value | rhs.m_value); + } + + template + constexpr Flags Flags::operator^(Flags rhs) const + { + return Flags(m_value ^ rhs.m_value); + } + + template + constexpr bool Flags::operator==(Flags rhs) const + { + return m_value == rhs.m_value; + } + + template + constexpr bool Flags::operator!=(Flags rhs) const + { + return !operator==(rhs); + } + + template + /*constexpr*/ Flags& Flags::operator|=(Flags rhs) + { + m_value |= rhs.m_value; + + return *this; + } + + template + /*constexpr*/ Flags& Flags::operator&=(Flags rhs) + { + m_value &= rhs.m_value; + + return *this; + } + + template + /*constexpr*/ Flags& Flags::operator^=(Flags rhs) + { + m_value ^= rhs.m_value; + + return *this; + } + + template + constexpr UInt32 Flags::GetFlagValue(E enumValue) + { + return 1U << static_cast(enumValue); + } + + + template + constexpr std::enable_if_t::value, Flags> operator~(E lhs) + { + return ~Flags(lhs); + } + + template + constexpr std::enable_if_t::value, Flags> operator|(E lhs, E rhs) + { + return Flags(lhs) | rhs; + } + + template + constexpr std::enable_if_t::value, Flags> operator&(E lhs, E rhs) + { + return Flags(lhs) & rhs; + } + + template + constexpr std::enable_if_t::value, Flags> operator^(E lhs, E rhs) + { + return Flags(lhs) ^ rhs; + } +} + +#include diff --git a/include/Nazara/Core/MemoryStream.hpp b/include/Nazara/Core/MemoryStream.hpp index f5d15fcf0..929e8e5bd 100644 --- a/include/Nazara/Core/MemoryStream.hpp +++ b/include/Nazara/Core/MemoryStream.hpp @@ -1,4 +1,4 @@ -// Copyright (C) 2015 Jérôme Leclercq +// Copyright (C) 2015 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 @@ -18,7 +18,7 @@ namespace Nz { public: inline MemoryStream(); - inline MemoryStream(ByteArray* byteArray, UInt32 openMode = OpenMode_ReadWrite); + inline MemoryStream(ByteArray* byteArray, OpenModeFlags openMode = OpenMode_ReadWrite); MemoryStream(const MemoryStream&) = default; MemoryStream(MemoryStream&&) = default; ~MemoryStream() = default; @@ -32,7 +32,7 @@ namespace Nz UInt64 GetCursorPos() const override; UInt64 GetSize() const override; - void SetBuffer(ByteArray* byteArray, UInt32 openMode = OpenMode_ReadWrite); + void SetBuffer(ByteArray* byteArray, OpenModeFlags openMode = OpenMode_ReadWrite); bool SetCursorPos(UInt64 offset) override; MemoryStream& operator=(const MemoryStream&) = default; diff --git a/include/Nazara/Core/MemoryStream.inl b/include/Nazara/Core/MemoryStream.inl index 79a19f467..6cdf06b26 100644 --- a/include/Nazara/Core/MemoryStream.inl +++ b/include/Nazara/Core/MemoryStream.inl @@ -24,7 +24,7 @@ namespace Nz * \param byteArray Bytes to stream * \param openMode Reading/writing mode for the stream */ - inline MemoryStream::MemoryStream(ByteArray* byteArray, UInt32 openMode) : + inline MemoryStream::MemoryStream(ByteArray* byteArray, OpenModeFlags openMode) : MemoryStream() { SetBuffer(byteArray, openMode); diff --git a/include/Nazara/Core/ParameterList.hpp b/include/Nazara/Core/ParameterList.hpp index 751746aea..b34f0eca0 100644 --- a/include/Nazara/Core/ParameterList.hpp +++ b/include/Nazara/Core/ParameterList.hpp @@ -60,10 +60,10 @@ namespace Nz { struct UserdataValue { - UserdataValue(Destructor Destructor, void* value) : + UserdataValue(Destructor func, void* ud) : counter(1), - destructor(Destructor), - ptr(value) + destructor(func), + ptr(ud) { } diff --git a/include/Nazara/Core/Stream.hpp b/include/Nazara/Core/Stream.hpp index 63d7e781b..e4949d441 100644 --- a/include/Nazara/Core/Stream.hpp +++ b/include/Nazara/Core/Stream.hpp @@ -32,8 +32,8 @@ namespace Nz virtual UInt64 GetCursorPos() const = 0; virtual String GetDirectory() const; virtual String GetPath() const; - inline UInt32 GetOpenMode() const; - inline UInt32 GetStreamOptions() const; + inline OpenModeFlags GetOpenMode() const; + inline StreamOptionFlags GetStreamOptions() const; virtual UInt64 GetSize() const = 0; @@ -55,14 +55,14 @@ namespace Nz Stream& operator=(Stream&&) = default; protected: - inline Stream(UInt32 streamOptions = StreamOption_None, UInt32 openMode = OpenMode_NotOpen); + inline Stream(StreamOptionFlags streamOptions = StreamOption_None, OpenModeFlags openMode = OpenMode_NotOpen); virtual void FlushStream() = 0; virtual std::size_t ReadBlock(void* buffer, std::size_t size) = 0; virtual std::size_t WriteBlock(const void* buffer, std::size_t size) = 0; - UInt32 m_openMode; - UInt32 m_streamOptions; + OpenModeFlags m_openMode; + StreamOptionFlags m_streamOptions; }; } diff --git a/include/Nazara/Core/Stream.inl b/include/Nazara/Core/Stream.inl index aae7fe155..f4f1557d7 100644 --- a/include/Nazara/Core/Stream.inl +++ b/include/Nazara/Core/Stream.inl @@ -15,7 +15,7 @@ namespace Nz * \param openMode Reading/writing mode for the stream */ - inline Stream::Stream(UInt32 streamOptions, UInt32 openMode) : + inline Stream::Stream(StreamOptionFlags streamOptions, OpenModeFlags openMode) : m_openMode(openMode), m_streamOptions(streamOptions) { @@ -53,7 +53,7 @@ namespace Nz * \return Reading/writing mode for the stream */ - inline UInt32 Stream::GetOpenMode() const + inline OpenModeFlags Stream::GetOpenMode() const { return m_openMode; } @@ -63,7 +63,7 @@ namespace Nz * \return Options of the stream */ - inline UInt32 Stream::GetStreamOptions() const + inline StreamOptionFlags Stream::GetStreamOptions() const { return m_streamOptions; } @@ -116,7 +116,7 @@ namespace Nz * \param size Size meant to be read * * \remark Produces a NazaraAssert if stream is not readable - * \remark If preallocated space of buffer is less than the size, the behaviour is undefined + * \remark If preallocated space of buffer is less than the size, the behavior is undefined */ inline std::size_t Stream::Read(void* buffer, std::size_t size) @@ -134,7 +134,7 @@ namespace Nz * \param size Size meant to be written * * \remark Produces a NazaraAssert if stream is not writable - * \remark If preallocated space of buffer is less than the size, the behaviour is undefined + * \remark If preallocated space of buffer is less than the size, the behavior is undefined */ inline std::size_t Stream::Write(const void* buffer, std::size_t size) diff --git a/include/Nazara/Graphics.hpp b/include/Nazara/Graphics.hpp index c317001a1..3d7edd264 100644 --- a/include/Nazara/Graphics.hpp +++ b/include/Nazara/Graphics.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 15 Sep 2016 at 00:43:26 +// This file was automatically generated /* Nazara Engine - Graphics module @@ -36,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -72,7 +73,6 @@ #include #include #include -#include #include #include #include diff --git a/include/Nazara/Graphics/CullingList.hpp b/include/Nazara/Graphics/CullingList.hpp new file mode 100644 index 000000000..f8c50d83d --- /dev/null +++ b/include/Nazara/Graphics/CullingList.hpp @@ -0,0 +1,180 @@ +// Copyright (C) 2015 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 + +#pragma once + +#ifndef NAZARA_CULLINGLIST_HPP +#define NAZARA_CULLINGLIST_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Nz +{ + template + class CullingList + { + public: + template class Entry; + class NoTestEntry; + class SphereEntry; + class VolumeEntry; + + template friend class Entry; + friend NoTestEntry; + friend SphereEntry; + friend VolumeEntry; + + using ResultContainer = std::vector; + + CullingList() = default; + CullingList(const CullingList& renderable) = delete; + CullingList(CullingList&& renderable) = delete; + ~CullingList(); + + std::size_t Cull(const Frustumf& frustum, bool* forceInvalidation = nullptr); + + NoTestEntry RegisterNoTest(const T* renderable); + SphereEntry RegisterSphereTest(const T* renderable); + VolumeEntry RegisterVolumeTest(const T* renderable); + + CullingList& operator=(const CullingList& renderable) = delete; + CullingList& operator=(CullingList&& renderable) = delete; + + // STL API + typename ResultContainer::iterator begin(); + typename ResultContainer::const_iterator begin() const; + + typename ResultContainer::const_iterator cbegin() const; + typename ResultContainer::const_iterator cend() const; + typename ResultContainer::const_reverse_iterator crbegin() const; + typename ResultContainer::const_reverse_iterator crend() const; + + bool empty() const; + + typename ResultContainer::iterator end(); + typename ResultContainer::const_iterator end() const; + + typename ResultContainer::reverse_iterator rbegin(); + typename ResultContainer::const_reverse_iterator rbegin() const; + + typename ResultContainer::reverse_iterator rend(); + typename ResultContainer::const_reverse_iterator rend() const; + + typename ResultContainer::size_type size() const; + + NazaraSignal(OnCullingListRelease, CullingList* /*cullingList*/); + + private: + inline void NotifyForceInvalidation(CullTest type, std::size_t index); + inline void NotifyMovement(CullTest type, std::size_t index, void* oldPtr, void* newPtr); + inline void NotifyRelease(CullTest type, std::size_t index); + inline void NotifySphereUpdate(std::size_t index, const Spheref& sphere); + inline void NotifyVolumeUpdate(std::size_t index, const BoundingVolumef& boundingVolume); + + struct NoTestVisibilityEntry + { + NoTestEntry* entry; + const T* renderable; + bool forceInvalidation; + }; + + struct SphereVisibilityEntry + { + Spheref sphere; + SphereEntry* entry; + const T* renderable; + bool forceInvalidation; + }; + + struct VolumeVisibilityEntry + { + BoundingVolumef volume; + VolumeEntry* entry; + const T* renderable; + bool forceInvalidation; + }; + + std::vector m_noTestList; + std::vector m_sphereTestList; + std::vector m_volumeTestList; + ResultContainer m_results; + }; + + template + template + class CullingList::Entry + { + public: + Entry(); + Entry(const Entry&) = delete; + Entry(Entry&& entry); + ~Entry(); + + void ForceInvalidation(); + + CullingList* GetParent() const; + + void UpdateIndex(std::size_t index); + + Entry& operator=(const Entry&) = delete; + Entry& operator=(Entry&& entry); + + protected: + Entry(CullingList* parent, std::size_t index); + + std::size_t m_index; + CullingList* m_parent; + }; + + template + class CullingList::NoTestEntry : public CullingList::template Entry + { + friend CullingList; + + public: + NoTestEntry(); + + private: + NoTestEntry(CullingList* parent, std::size_t index); + }; + + template + class CullingList::SphereEntry : public CullingList::template Entry + { + friend CullingList; + + public: + SphereEntry(); + + void UpdateSphere(const Spheref& sphere); + + private: + SphereEntry(CullingList* parent, std::size_t index); + }; + + template + class CullingList::VolumeEntry : public CullingList::template Entry + { + friend CullingList; + + public: + VolumeEntry(); + + void UpdateVolume(const BoundingVolumef& sphere); + + private: + VolumeEntry(CullingList* parent, std::size_t index); + }; +} + +#include + +#endif // NAZARA_CULLINGLIST_HPP diff --git a/include/Nazara/Graphics/CullingList.inl b/include/Nazara/Graphics/CullingList.inl new file mode 100644 index 000000000..d4f80b3d7 --- /dev/null +++ b/include/Nazara/Graphics/CullingList.inl @@ -0,0 +1,431 @@ +// Copyright (C) 2015 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 + +namespace Nz +{ + template + CullingList::~CullingList() + { + OnCullingListRelease(this); + } + + template + std::size_t CullingList::Cull(const Frustumf& frustum, bool* forceInvalidation) + { + m_results.clear(); + + bool forcedInvalidation = false; + + std::size_t visibleHash = 0U; + + for (NoTestVisibilityEntry& entry : m_noTestList) + { + m_results.push_back(entry.renderable); + Nz::HashCombine(visibleHash, entry.renderable); + + if (entry.forceInvalidation) + { + forcedInvalidation = true; + entry.forceInvalidation = false; + } + } + + for (SphereVisibilityEntry& entry : m_sphereTestList) + { + if (frustum.Contains(entry.sphere)) + { + m_results.push_back(entry.renderable); + Nz::HashCombine(visibleHash, entry.renderable); + + if (entry.forceInvalidation) + { + forcedInvalidation = true; + entry.forceInvalidation = false; + } + } + } + + for (VolumeVisibilityEntry& entry : m_volumeTestList) + { + if (frustum.Contains(entry.volume)) + { + m_results.push_back(entry.renderable); + Nz::HashCombine(visibleHash, entry.renderable); + + if (entry.forceInvalidation) + { + forcedInvalidation = true; + entry.forceInvalidation = false; + } + } + } + + if (forceInvalidation) + *forceInvalidation = forcedInvalidation; + + return visibleHash; + } + + template + typename CullingList::NoTestEntry CullingList::RegisterNoTest(const T* renderable) + { + NoTestEntry entry(this, m_noTestList.size()); + m_noTestList.emplace_back(NoTestVisibilityEntry{&entry, renderable, false}); //< Address of entry will be updated when moving + + return entry; + } + + template + typename CullingList::SphereEntry CullingList::RegisterSphereTest(const T* renderable) + { + SphereEntry entry(this, m_sphereTestList.size()); + m_sphereTestList.emplace_back(SphereVisibilityEntry{Nz::Spheref(), &entry, renderable, false}); //< Address of entry will be updated when moving + + return entry; + } + + template + typename CullingList::VolumeEntry CullingList::RegisterVolumeTest(const T* renderable) + { + VolumeEntry entry(this, m_volumeTestList.size()); + m_volumeTestList.emplace_back(VolumeVisibilityEntry{Nz::BoundingVolumef(), &entry, renderable, false}); //< Address of entry will be updated when moving + + return entry; + } + + // Interface STD + template + typename CullingList::ResultContainer::iterator CullingList::begin() + { + return m_results.begin(); + } + + template + typename CullingList::ResultContainer::const_iterator CullingList::begin() const + { + return m_results.begin(); + } + + template + typename CullingList::ResultContainer::const_iterator CullingList::cbegin() const + { + return m_results.cbegin(); + } + + template + typename CullingList::ResultContainer::const_iterator CullingList::cend() const + { + return m_results.cend(); + } + + template + typename CullingList::ResultContainer::const_reverse_iterator CullingList::crbegin() const + { + return m_results.crbegin(); + } + + template + typename CullingList::ResultContainer::const_reverse_iterator CullingList::crend() const + { + return m_results.crend(); + } + + template + bool CullingList::empty() const + { + return m_results.empty(); + } + + template + typename CullingList::ResultContainer::iterator CullingList::end() + { + return m_results.end(); + } + + template + typename CullingList::ResultContainer::const_iterator CullingList::end() const + { + return m_results.end(); + } + + template + typename CullingList::ResultContainer::reverse_iterator CullingList::rbegin() + { + return m_results.rbegin(); + } + + template + typename CullingList::ResultContainer::const_reverse_iterator CullingList::rbegin() const + { + return m_results.rbegin(); + } + + template + typename CullingList::ResultContainer::reverse_iterator CullingList::rend() + { + return m_results.rend(); + } + + template + typename CullingList::ResultContainer::const_reverse_iterator CullingList::rend() const + { + return m_results.rend(); + } + + template + typename CullingList::ResultContainer::size_type CullingList::size() const + { + return m_results.size(); + } + + template + void CullingList::NotifyForceInvalidation(CullTest type, std::size_t index) + { + switch (type) + { + case CullTest::NoTest: + { + m_noTestList[index].forceInvalidation = true; + break; + } + + case CullTest::Sphere: + { + m_sphereTestList[index].forceInvalidation = true; + break; + } + + case CullTest::Volume: + { + m_volumeTestList[index].forceInvalidation = true; + break; + } + + default: + NazaraInternalError("Unhandled culltype"); + break; + } + } + + template + void CullingList::NotifyMovement(CullTest type, std::size_t index, void* oldPtr, void* newPtr) + { + switch (type) + { + case CullTest::NoTest: + { + NoTestVisibilityEntry& entry = m_noTestList[index]; + NazaraAssert(entry.entry == oldPtr, "Invalid entry"); + + entry.entry = static_cast(newPtr); + break; + } + + case CullTest::Sphere: + { + SphereVisibilityEntry& entry = m_sphereTestList[index]; + NazaraAssert(entry.entry == oldPtr, "Invalid sphere entry"); + + entry.entry = static_cast(newPtr); + break; + } + + case CullTest::Volume: + { + VolumeVisibilityEntry& entry = m_volumeTestList[index]; + NazaraAssert(entry.entry == oldPtr, "Invalid volume entry"); + + entry.entry = static_cast(newPtr); + break; + } + + default: + NazaraInternalError("Unhandled culltype"); + break; + } + } + + template + void CullingList::NotifyRelease(CullTest type, std::size_t index) + { + switch (type) + { + case CullTest::NoTest: + { + m_noTestList[index] = std::move(m_noTestList.back()); + m_noTestList[index].entry->UpdateIndex(index); + m_noTestList.pop_back(); + break; + } + + case CullTest::Sphere: + { + m_sphereTestList[index] = std::move(m_sphereTestList.back()); + m_sphereTestList[index].entry->UpdateIndex(index); + m_sphereTestList.pop_back(); + break; + } + + case CullTest::Volume: + { + m_volumeTestList[index] = std::move(m_volumeTestList.back()); + m_volumeTestList[index].entry->UpdateIndex(index); + m_volumeTestList.pop_back(); + break; + } + + default: + NazaraInternalError("Unhandled culltype"); + break; + } + } + + template + void CullingList::NotifySphereUpdate(std::size_t index, const Spheref& sphere) + { + m_sphereTestList[index].sphere = sphere; + } + + template + void CullingList::NotifyVolumeUpdate(std::size_t index, const BoundingVolumef& boundingVolume) + { + m_volumeTestList[index].volume = boundingVolume; + } + + ////////////////////////////////////////////////////////////////////////// + + template + template + CullingList::Entry::Entry() : + m_parent(nullptr) + { + } + + template + template + CullingList::Entry::Entry(CullingList* parent, std::size_t index) : + m_index(index), + m_parent(parent) + { + } + + template + template + CullingList::Entry::Entry(Entry&& entry) : + m_index(entry.m_index), + m_parent(entry.m_parent) + { + if (m_parent) + m_parent->NotifyMovement(Type, m_index, &entry, this); + + entry.m_parent = nullptr; + } + + template + template + CullingList::Entry::~Entry() + { + if (m_parent) + m_parent->NotifyRelease(Type, m_index); + } + + template + template + void CullingList::Entry::ForceInvalidation() + { + m_parent->NotifyForceInvalidation(Type, m_index); + } + + template + template + CullingList* CullingList::Entry::GetParent() const + { + return m_parent; + } + + template + template + void CullingList::Entry::UpdateIndex(std::size_t index) + { + m_index = index; + } + + template + template + #ifdef NAZARA_COMPILER_MSVC + // MSVC bug + typename CullingList::Entry& CullingList::Entry::operator=(Entry&& entry) + #else + typename CullingList::template Entry& CullingList::Entry::operator=(Entry&& entry) + #endif + { + m_index = entry.m_index; + m_parent = entry.m_parent; + if (m_parent) + m_parent->NotifyMovement(Type, m_index, &entry, this); + + entry.m_parent = nullptr; + + return *this; + } + + ////////////////////////////////////////////////////////////////////////// + + template + CullingList::NoTestEntry::NoTestEntry() : + Entry() + { + } + + template + CullingList::NoTestEntry::NoTestEntry(CullingList* parent, std::size_t index) : + Entry(parent, index) + { + } + + ////////////////////////////////////////////////////////////////////////// + + template + CullingList::SphereEntry::SphereEntry() : + Entry() + { + } + + template + CullingList::SphereEntry::SphereEntry(CullingList* parent, std::size_t index) : + Entry(parent, index) + { + } + + template + void CullingList::SphereEntry::UpdateSphere(const Spheref& sphere) + { + this->m_parent->NotifySphereUpdate(this->m_index, sphere); + } + + ////////////////////////////////////////////////////////////////////////// + + template + CullingList::VolumeEntry::VolumeEntry() : + Entry() + { + } + + template + CullingList::VolumeEntry::VolumeEntry(CullingList* parent, std::size_t index) : + Entry(parent, index) + { + } + + template + void CullingList::VolumeEntry::UpdateVolume(const BoundingVolumef& volume) + { + this->m_parent->NotifyVolumeUpdate(this->m_index, volume); + } +} + +#include diff --git a/include/Nazara/Graphics/Enums.hpp b/include/Nazara/Graphics/Enums.hpp index d378058f7..fd87cac6c 100644 --- a/include/Nazara/Graphics/Enums.hpp +++ b/include/Nazara/Graphics/Enums.hpp @@ -19,6 +19,13 @@ namespace Nz BackgroundType_Max = BackgroundType_User }; + enum class CullTest + { + NoTest, + Sphere, + Volume + }; + enum ProjectionType { ProjectionType_Orthogonal, diff --git a/include/Nazara/Graphics/ForwardRenderQueue.hpp b/include/Nazara/Graphics/ForwardRenderQueue.hpp index 99be2743e..56474a642 100644 --- a/include/Nazara/Graphics/ForwardRenderQueue.hpp +++ b/include/Nazara/Graphics/ForwardRenderQueue.hpp @@ -87,7 +87,7 @@ namespace Nz struct SpriteChain_XYZ_Color_UV { const VertexStruct_XYZ_Color_UV* vertices; - unsigned int spriteCount; + std::size_t spriteCount; }; struct BatchedSpriteEntry @@ -160,7 +160,7 @@ namespace Nz const Material* material; }; - typedef std::vector TransparentModelContainer; + typedef std::vector TransparentModelContainer; struct Layer { diff --git a/include/Nazara/Graphics/InstancedRenderable.hpp b/include/Nazara/Graphics/InstancedRenderable.hpp index 8b44d7512..3f117c84b 100644 --- a/include/Nazara/Graphics/InstancedRenderable.hpp +++ b/include/Nazara/Graphics/InstancedRenderable.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -31,15 +32,17 @@ namespace Nz public: struct InstanceData; - InstancedRenderable() = default; + inline InstancedRenderable(); inline InstancedRenderable(const InstancedRenderable& renderable); InstancedRenderable(InstancedRenderable&& renderable) = delete; virtual ~InstancedRenderable(); + virtual void AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData) const = 0; + + virtual bool Cull(const Frustumf& frustum, const InstanceData& instanceData) const; + inline void EnsureBoundingVolumeUpdated() const; - virtual void AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData) const = 0; - virtual bool Cull(const Frustumf& frustum, const InstanceData& instanceData) const; virtual const BoundingVolumef& GetBoundingVolume() const; virtual void InvalidateData(InstanceData* instanceData, UInt32 flags) const; virtual void UpdateBoundingVolume(InstanceData* instanceData) const; @@ -49,6 +52,7 @@ namespace Nz InstancedRenderable& operator=(InstancedRenderable&& renderable) = delete; // Signals: + NazaraSignal(OnInstancedRenderableInvalidateBoundingVolume, const InstancedRenderable* /*instancedRenderable*/); NazaraSignal(OnInstancedRenderableInvalidateData, const InstancedRenderable* /*instancedRenderable*/, UInt32 /*flags*/); NazaraSignal(OnInstancedRenderableRelease, const InstancedRenderable* /*instancedRenderable*/); @@ -83,14 +87,16 @@ namespace Nz }; protected: - virtual void MakeBoundingVolume() const = 0; - void InvalidateBoundingVolume(); + inline void InvalidateBoundingVolume(); inline void InvalidateInstanceData(UInt32 flags); - inline void UpdateBoundingVolume() const; + + virtual void MakeBoundingVolume() const = 0; mutable BoundingVolumef m_boundingVolume; private: + inline void UpdateBoundingVolume() const; + mutable bool m_boundingVolumeUpdated; static InstancedRenderableLibrary::LibraryMap s_library; diff --git a/include/Nazara/Graphics/InstancedRenderable.inl b/include/Nazara/Graphics/InstancedRenderable.inl index 7f2537fbf..5ee49dc6a 100644 --- a/include/Nazara/Graphics/InstancedRenderable.inl +++ b/include/Nazara/Graphics/InstancedRenderable.inl @@ -4,12 +4,19 @@ namespace Nz { + /*! + * \brief Constructs a InstancedRenderable object by default + */ + inline InstancedRenderable::InstancedRenderable() : + m_boundingVolumeUpdated(false) + { + } + /*! * \brief Constructs a InstancedRenderable object by assignation * * \param renderable InstancedRenderable to copy into this */ - inline InstancedRenderable::InstancedRenderable(const InstancedRenderable& renderable) : RefCounted(), m_boundingVolume(renderable.m_boundingVolume), @@ -34,6 +41,8 @@ namespace Nz inline void InstancedRenderable::InvalidateBoundingVolume() { m_boundingVolumeUpdated = false; + + OnInstancedRenderableInvalidateBoundingVolume(this); } /*! @@ -69,6 +78,7 @@ namespace Nz inline void InstancedRenderable::UpdateBoundingVolume() const { MakeBoundingVolume(); + m_boundingVolumeUpdated = true; } } diff --git a/include/Nazara/Graphics/ParticleDeclaration.hpp b/include/Nazara/Graphics/ParticleDeclaration.hpp index 278d25961..770cbe31d 100644 --- a/include/Nazara/Graphics/ParticleDeclaration.hpp +++ b/include/Nazara/Graphics/ParticleDeclaration.hpp @@ -36,10 +36,10 @@ namespace Nz ~ParticleDeclaration(); void DisableComponent(ParticleComponent component); - void EnableComponent(ParticleComponent component, ComponentType type, unsigned int offset); + void EnableComponent(ParticleComponent component, ComponentType type, std::size_t offset); - void GetComponent(ParticleComponent component, bool* enabled, ComponentType* type, unsigned int* offset) const; - unsigned int GetStride() const; + void GetComponent(ParticleComponent component, bool* enabled, ComponentType* type, std::size_t* offset) const; + std::size_t GetStride() const; void SetStride(unsigned int stride); @@ -60,7 +60,7 @@ namespace Nz { ComponentType type; bool enabled = false; - unsigned int offset; + std::size_t offset; /* ** -Lynix: @@ -71,7 +71,7 @@ namespace Nz }; std::array m_components; - unsigned int m_stride; + std::size_t m_stride; static std::array s_declarations; static ParticleDeclarationLibrary::LibraryMap s_library; diff --git a/include/Nazara/Graphics/ParticleEmitter.hpp b/include/Nazara/Graphics/ParticleEmitter.hpp index 8bd26a4bd..cfbb9e98a 100644 --- a/include/Nazara/Graphics/ParticleEmitter.hpp +++ b/include/Nazara/Graphics/ParticleEmitter.hpp @@ -28,12 +28,12 @@ namespace Nz void EnableLagCompensation(bool enable); - unsigned int GetEmissionCount() const; + std::size_t GetEmissionCount() const; float GetEmissionRate() const; bool IsLagCompensationEnabled() const; - void SetEmissionCount(unsigned int count); + void SetEmissionCount(std::size_t count); void SetEmissionRate(float rate); ParticleEmitter& operator=(const ParticleEmitter& emitter) = default; @@ -49,7 +49,7 @@ namespace Nz bool m_lagCompensationEnabled; mutable float m_emissionAccumulator; float m_emissionRate; - unsigned int m_emissionCount; + std::size_t m_emissionCount; }; } diff --git a/include/Nazara/Graphics/ParticleGroup.hpp b/include/Nazara/Graphics/ParticleGroup.hpp index 409090284..460694160 100644 --- a/include/Nazara/Graphics/ParticleGroup.hpp +++ b/include/Nazara/Graphics/ParticleGroup.hpp @@ -44,12 +44,14 @@ namespace Nz void* GenerateParticle(); void* GenerateParticles(unsigned int count); + inline void* GetBuffer(); + inline const void* GetBuffer() const; const ParticleDeclarationConstRef& GetDeclaration() const; - unsigned int GetMaxParticleCount() const; - unsigned int GetParticleCount() const; - unsigned int GetParticleSize() const; + std::size_t GetMaxParticleCount() const; + std::size_t GetParticleCount() const; + std::size_t GetParticleSize() const; - void KillParticle(unsigned int index); + void KillParticle(std::size_t index); void KillParticles(); void RemoveController(ParticleController* controller); @@ -81,6 +83,9 @@ namespace Nz }; std::set> m_dyingParticles; + std::size_t m_maxParticleCount; + std::size_t m_particleCount; + std::size_t m_particleSize; mutable std::vector m_buffer; std::vector m_controllers; std::vector m_emitters; @@ -88,10 +93,9 @@ namespace Nz ParticleDeclarationConstRef m_declaration; ParticleRendererRef m_renderer; bool m_processing; - unsigned int m_maxParticleCount; - unsigned int m_particleCount; - unsigned int m_particleSize; }; } +#include + #endif // NAZARA_PARTICLEGROUP_HPP diff --git a/include/Nazara/Graphics/ParticleGroup.inl b/include/Nazara/Graphics/ParticleGroup.inl new file mode 100644 index 000000000..f0e205346 --- /dev/null +++ b/include/Nazara/Graphics/ParticleGroup.inl @@ -0,0 +1,40 @@ +// Copyright (C) 2016 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 +{ + /*! + * \brief Gets a raw pointer to the particle buffer + * + * This can be useful when working directly with a struct, or needing to iterate over all particles. + * + * \return Pointer to the buffer + * + * \see GetParticleCount + */ + inline void* ParticleGroup::GetBuffer() + { + return m_buffer.data(); + } + + /*! + * \brief Gets a raw pointer to the particle buffer + * + * This can be useful when working directly with a struct, or needing to iterate over all particles. + * + * \return Pointer to the buffer + * + * \see GetParticleCount + */ + inline const void* ParticleGroup::GetBuffer() const + { + return m_buffer.data(); + } +} + +#include diff --git a/include/Nazara/Graphics/ParticleMapper.hpp b/include/Nazara/Graphics/ParticleMapper.hpp index e66b519a7..ffbe2a5ad 100644 --- a/include/Nazara/Graphics/ParticleMapper.hpp +++ b/include/Nazara/Graphics/ParticleMapper.hpp @@ -22,6 +22,7 @@ namespace Nz template SparsePtr GetComponentPtr(ParticleComponent component); template SparsePtr GetComponentPtr(ParticleComponent component) const; + inline void* GetPointer(); private: const ParticleDeclaration* m_declaration; diff --git a/include/Nazara/Graphics/ParticleMapper.inl b/include/Nazara/Graphics/ParticleMapper.inl index 63c9c49ba..1a4566c33 100644 --- a/include/Nazara/Graphics/ParticleMapper.inl +++ b/include/Nazara/Graphics/ParticleMapper.inl @@ -23,7 +23,7 @@ namespace Nz // Then the component that are interesting bool enabled; ComponentType type; - unsigned int offset; + std::size_t offset; m_declaration->GetComponent(component, &enabled, &type, &offset); if (enabled) @@ -54,7 +54,7 @@ namespace Nz // Then the component that are interesting bool enabled; ComponentType type; - unsigned int offset; + std::size_t offset; m_declaration->GetComponent(component, &enabled, &type, &offset); if (enabled) @@ -68,6 +68,18 @@ namespace Nz return SparsePtr(); } } + + /*! + * \brief Gets a raw pointer to the particle buffer + * + * This can be useful when working directly with a struct + * + * \return Pointer to the buffer + */ + inline void* ParticleMapper::GetPointer() + { + return m_ptr; + } } #include diff --git a/include/Nazara/Graphics/ParticleStruct.hpp b/include/Nazara/Graphics/ParticleStruct.hpp index 895e8fca2..b4f55a3a1 100644 --- a/include/Nazara/Graphics/ParticleStruct.hpp +++ b/include/Nazara/Graphics/ParticleStruct.hpp @@ -21,16 +21,16 @@ namespace Nz Vector3f normal; Vector3f position; Vector3f velocity; - UInt32 life; + float life; float rotation; }; struct ParticleStruct_Model { + Quaternionf rotation; Vector3f position; Vector3f velocity; - UInt32 life; - Quaternionf rotation; + float life; }; struct ParticleStruct_Sprite @@ -38,7 +38,7 @@ namespace Nz Color color; Vector3f position; Vector3f velocity; - UInt32 life; + float life; float rotation; }; } diff --git a/include/Nazara/Graphics/RenderTechniques.hpp b/include/Nazara/Graphics/RenderTechniques.hpp index 1e006858a..a4642ffc8 100644 --- a/include/Nazara/Graphics/RenderTechniques.hpp +++ b/include/Nazara/Graphics/RenderTechniques.hpp @@ -29,7 +29,7 @@ namespace Nz static AbstractRenderTechnique* GetByName(const String& name, int* techniqueRanking = nullptr); static AbstractRenderTechnique* GetByRanking(int maxRanking, int* techniqueRanking = nullptr); - static unsigned int GetCount(); + static std::size_t GetCount(); static void Register(const String& name, int ranking, RenderTechniqueFactory factory); diff --git a/include/Nazara/Graphics/Renderable.hpp b/include/Nazara/Graphics/Renderable.hpp index f8d441955..412caa301 100644 --- a/include/Nazara/Graphics/Renderable.hpp +++ b/include/Nazara/Graphics/Renderable.hpp @@ -25,7 +25,9 @@ namespace Nz virtual ~Renderable(); virtual void AddToRenderQueue(AbstractRenderQueue* renderQueue, const Matrix4f& transformMatrix) const = 0; + virtual bool Cull(const Frustumf& frustum, const Matrix4f& transformMatrix) const; + inline void EnsureBoundingVolumeUpdated() const; virtual const BoundingVolumef& GetBoundingVolume() const; virtual void UpdateBoundingVolume(const Matrix4f& transformMatrix); @@ -36,11 +38,12 @@ namespace Nz protected: virtual void MakeBoundingVolume() const = 0; inline void InvalidateBoundingVolume(); - inline void UpdateBoundingVolume() const; mutable BoundingVolumef m_boundingVolume; private: + inline void UpdateBoundingVolume() const; + mutable bool m_boundingVolumeUpdated; }; } diff --git a/include/Nazara/Graphics/Sprite.hpp b/include/Nazara/Graphics/Sprite.hpp index 13bcc289b..2c42f4ce1 100644 --- a/include/Nazara/Graphics/Sprite.hpp +++ b/include/Nazara/Graphics/Sprite.hpp @@ -47,9 +47,11 @@ namespace Nz inline void SetCornerColor(RectCorner corner, const Color& color); inline void SetDefaultMaterial(); inline void SetMaterial(MaterialRef material, bool resizeSprite = true); + bool SetMaterial(String materialName, bool resizeSprite = true); inline void SetOrigin(const Vector3f& origin); inline void SetSize(const Vector2f& size); inline void SetSize(float sizeX, float sizeY); + bool SetTexture(String textureName, bool resizeSprite = true); inline void SetTexture(TextureRef texture, bool resizeSprite = true); inline void SetTextureCoords(const Rectf& coords); inline void SetTextureRect(const Rectui& rect); diff --git a/include/Nazara/Graphics/Sprite.inl b/include/Nazara/Graphics/Sprite.inl index 35885a94a..deec75959 100644 --- a/include/Nazara/Graphics/Sprite.inl +++ b/include/Nazara/Graphics/Sprite.inl @@ -184,12 +184,11 @@ namespace Nz } /*! - * \brief Sets the material of the sprite + * \brief Changes the material of the sprite * * \param material Material for the sprite - * \param resizeSprite Should sprite be resized to the material size (diffuse map) + * \param resizeSprite Should the sprite be resized to the texture size? */ - inline void Sprite::SetMaterial(MaterialRef material, bool resizeSprite) { m_material = std::move(material); @@ -249,16 +248,19 @@ namespace Nz /*! * \brief Sets the texture of the sprite * + * Assign a texture to the sprite material + * * \param texture Texture for the sprite - * \param resizeSprite Should sprite be resized to the texture size + * \param resizeSprite Should the sprite be resized to the texture size? + * + * \remark The sprite material gets copied to prevent accidentally changing other drawable materials */ - inline void Sprite::SetTexture(TextureRef texture, bool resizeSprite) { if (!m_material) SetDefaultMaterial(); else if (m_material->GetReferenceCount() > 1) - m_material = Material::New(*m_material); // Copie + m_material = Material::New(*m_material); // Copy the material if (resizeSprite && texture && texture->IsValid()) SetSize(Vector2f(Vector2ui(texture->GetSize()))); diff --git a/include/Nazara/Graphics/TextSprite.inl b/include/Nazara/Graphics/TextSprite.inl index 2ed880a38..d5db90805 100644 --- a/include/Nazara/Graphics/TextSprite.inl +++ b/include/Nazara/Graphics/TextSprite.inl @@ -149,6 +149,7 @@ namespace Nz { m_scale = scale; + InvalidateBoundingVolume(); InvalidateVertices(); } diff --git a/include/Nazara/Graphics/TileMap.inl b/include/Nazara/Graphics/TileMap.inl index 4473a8600..f8faa7b54 100644 --- a/include/Nazara/Graphics/TileMap.inl +++ b/include/Nazara/Graphics/TileMap.inl @@ -29,7 +29,7 @@ namespace Nz m_isometricModeEnabled(false) { NazaraAssert(m_tiles.size() != 0U, "Invalid map size"); - NazaraAssert(m_tileSize.x != 0U && m_tileSize.y != 0U, "Invalid tile size"); + NazaraAssert(m_tileSize.x > 0 && m_tileSize.y > 0, "Invalid tile size"); NazaraAssert(m_layers.size() != 0U, "Invalid material count"); for (Layer& layer : m_layers) @@ -175,7 +175,7 @@ namespace Nz * \param color The multiplicative color applied to the tile * \param materialIndex The material which will be used for rendering this tile * - * \remark The material at [materialIndex] must have a valid diffuse map before using this function, + * \remark The material at [materialIndex] must have a valid diffuse map before using this function, * as the size of the material diffuse map is used to compute normalized texture coordinates before returning. * * \see EnableTiles @@ -253,7 +253,7 @@ namespace Nz Rectf unnormalizedCoords(invWidth * rect.x, invHeight * rect.y, invWidth * rect.width, invHeight * rect.height); EnableTiles(unnormalizedCoords, color, materialIndex); } - + /*! * \brief Enable and sets tileCount tiles at positions contained at tilesPos location, enabling rendering at those locations * @@ -434,14 +434,14 @@ namespace Nz * * \param TileMap The other TileMap */ - inline TileMap& TileMap::operator=(const TileMap& TileMap) + inline TileMap& TileMap::operator=(const TileMap& tileMap) { - InstancedRenderable::operator=(TileMap); + InstancedRenderable::operator=(tileMap); - m_layers = TileMap.m_layers; - m_mapSize = TileMap.m_mapSize; - m_tiles = TileMap.m_tiles; - m_tileSize = TileMap.m_tileSize; + m_layers = tileMap.m_layers; + m_mapSize = tileMap.m_mapSize; + m_tiles = tileMap.m_tiles; + m_tileSize = tileMap.m_tileSize; // We do not copy final vertices because it's highly probable that our parameters are modified and they must be regenerated InvalidateBoundingVolume(); diff --git a/include/Nazara/Lua.hpp b/include/Nazara/Lua.hpp index f73541cb8..a0e68204c 100644 --- a/include/Nazara/Lua.hpp +++ b/include/Nazara/Lua.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 24 Jun 2015 at 13:55:50 +// This file was automatically generated /* Nazara Engine - Lua scripting module diff --git a/include/Nazara/Lua/LuaClass.inl b/include/Nazara/Lua/LuaClass.inl index daf7a632a..3168ba43d 100644 --- a/include/Nazara/Lua/LuaClass.inl +++ b/include/Nazara/Lua/LuaClass.inl @@ -129,7 +129,7 @@ namespace Nz BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, object, func); }); @@ -143,7 +143,7 @@ namespace Nz BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, object, func); }); @@ -157,7 +157,7 @@ namespace Nz BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, object, func); }); @@ -171,7 +171,7 @@ namespace Nz BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, object, func); }); @@ -203,7 +203,7 @@ namespace Nz BindStaticMethod(name, [func, handler] (LuaInstance& lua) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, func); }); @@ -335,7 +335,7 @@ namespace Nz NazaraWarning("Class \"" + m_info->name + "\" already registred in this instance"); { SetupFinalizer(lua); - + if (m_info->getter || !m_info->parentGetters.empty()) SetupGetter(lua, GetterProxy); else diff --git a/include/Nazara/Lua/LuaInstance.inl b/include/Nazara/Lua/LuaInstance.inl index 25f193675..99ef94ea4 100644 --- a/include/Nazara/Lua/LuaInstance.inl +++ b/include/Nazara/Lua/LuaInstance.inl @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -59,7 +60,7 @@ namespace Nz m_memoryUsage = instance.m_memoryUsage; m_state = instance.m_state; m_timeLimit = instance.m_timeLimit; - + instance.m_state = nullptr; return *this; @@ -99,19 +100,50 @@ namespace Nz } template - std::enable_if_t::value, unsigned int> LuaImplQueryArg(const LuaInstance& instance, int index, T* arg, TypeTag) + std::enable_if_t::value && !EnableFlagsOperators::value, unsigned int> LuaImplQueryArg(const LuaInstance& instance, int index, T* arg, TypeTag) { using UnderlyingT = std::underlying_type_t; return LuaImplQueryArg(instance, index, reinterpret_cast(arg), TypeTag()); } template - std::enable_if_t::value, unsigned int> LuaImplQueryArg(const LuaInstance& instance, int index, T* arg, T defValue, TypeTag) + std::enable_if_t::value && !EnableFlagsOperators::value, unsigned int> LuaImplQueryArg(const LuaInstance& instance, int index, T* arg, T defValue, TypeTag) { using UnderlyingT = std::underlying_type_t; return LuaImplQueryArg(instance, index, reinterpret_cast(arg), static_cast(defValue), TypeTag()); } + template + std::enable_if_t::value && EnableFlagsOperators::value, unsigned int> LuaImplQueryArg(const LuaInstance& instance, int index, T* arg, TypeTag) + { + using UnderlyingT = std::underlying_type_t; + + UnderlyingT pot2Val; + unsigned int ret = LuaImplQueryArg(instance, index, &pot2Val, TypeTag()); + + *arg = static_cast(IntegralLog2Pot(pot2Val)); + return ret; + } + + template + std::enable_if_t::value && EnableFlagsOperators::value, unsigned int> LuaImplQueryArg(const LuaInstance& instance, int index, T* arg, T defValue, TypeTag) + { + using UnderlyingT = std::underlying_type_t; + + UnderlyingT pot2Val; + unsigned int ret = LuaImplQueryArg(instance, index, &pot2Val, 1U << static_cast(defValue), TypeTag()); + + *arg = static_cast(IntegralLog2Pot(pot2Val)); + return ret; + } + + template + unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Flags* arg, TypeTag>) + { + *arg = Flags(instance.CheckBoundInteger(index)); + return 1; + } + template std::enable_if_t::value, unsigned int> LuaImplQueryArg(const LuaInstance& instance, int index, T* arg, TypeTag) { @@ -184,12 +216,26 @@ namespace Nz } template - std::enable_if_t::value, int> LuaImplReplyVal(const LuaInstance& instance, T val, TypeTag) + std::enable_if_t::value && !EnableFlagsOperators::value, int> LuaImplReplyVal(const LuaInstance& instance, T val, TypeTag) { using EnumT = typename std::underlying_type::type; return LuaImplReplyVal(instance, static_cast(val), TypeTag()); } + template + std::enable_if_t::value && EnableFlagsOperators::value, int> LuaImplReplyVal(const LuaInstance& instance, T val, TypeTag) + { + Flags flags(val); + return LuaImplReplyVal(instance, flags, TypeTag()); + } + + template + int LuaImplReplyVal(const LuaInstance& instance, Flags val, TypeTag>) + { + instance.PushInteger(UInt32(val)); + return 1; + } + template std::enable_if_t::value, int> LuaImplReplyVal(const LuaInstance& instance, T val, TypeTag) { @@ -320,7 +366,7 @@ namespace Nz { } - void ProcessArgs(const LuaInstance& instance) const + void ProcessArguments(const LuaInstance& instance) const { m_index = 1; ProcessArgs<0, Args...>(instance); @@ -391,7 +437,7 @@ namespace Nz { } - void ProcessArgs(const LuaInstance& instance) const + void ProcessArguments(const LuaInstance& instance) const { m_index = 2; //< 1 being the instance ProcessArgs<0, Args...>(instance); @@ -714,7 +760,7 @@ namespace Nz PushFunction([func, handler] (LuaInstance& lua) -> int { - handler.ProcessArgs(lua); + handler.ProcessArguments(lua); return handler.Invoke(lua, func); }); diff --git a/include/Nazara/Math.hpp b/include/Nazara/Math.hpp index fd0239a61..9ee9a2351 100644 --- a/include/Nazara/Math.hpp +++ b/include/Nazara/Math.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 24 Jun 2015 at 13:55:50 +// This file was automatically generated /* Nazara Engine - Mathematics module diff --git a/include/Nazara/Math/Algorithm.hpp b/include/Nazara/Math/Algorithm.hpp index 45281bb50..f138a8fc9 100644 --- a/include/Nazara/Math/Algorithm.hpp +++ b/include/Nazara/Math/Algorithm.hpp @@ -37,7 +37,7 @@ namespace Nz { template /*constexpr*/ T Approach(T value, T objective, T increment); template constexpr T Clamp(T value, T min, T max); - template /*constexpr*/ T CountBits(T value); + template /*constexpr*/ std::size_t CountBits(T value); template constexpr T FromDegrees(T degrees); template constexpr T FromRadians(T radians); template constexpr T DegreeToRadian(T degrees); diff --git a/include/Nazara/Math/Algorithm.inl b/include/Nazara/Math/Algorithm.inl index b61d82916..02ede739a 100644 --- a/include/Nazara/Math/Algorithm.inl +++ b/include/Nazara/Math/Algorithm.inl @@ -147,10 +147,10 @@ namespace Nz template //TODO: Mark as constexpr when supported by all major compilers - /*constexpr*/ inline T CountBits(T value) + /*constexpr*/ inline std::size_t CountBits(T value) { // https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan - unsigned int count = 0; + std::size_t count = 0; while (value) { value &= value - 1; diff --git a/include/Nazara/Math/EulerAngles.inl b/include/Nazara/Math/EulerAngles.inl index 24bfd4630..3b12e7abe 100644 --- a/include/Nazara/Math/EulerAngles.inl +++ b/include/Nazara/Math/EulerAngles.inl @@ -17,11 +17,11 @@ namespace Nz { /*! - * \ingroup math + * \ingroup math * \class Nz::EulerAngles * \brief Math class that represents an Euler angle. Those describe a rotation transformation by rotating an object on its various axes in specified amounts per axis, and a specified axis order * - * \remark Rotation are "left-handed", it means that you take your left hand, put your thumb finger in the direction you want and you other fingers represent the way of rotating + * \remark Rotation are "right-handed", it means that you take your right hand, put your thumb finger in the direction you want and you other fingers represent the way of rotating */ /*! @@ -197,6 +197,7 @@ namespace Nz template Quaternion EulerAngles::ToQuaternion() const { + // XYZ T c1 = std::cos(ToRadians(yaw) / F(2.0)); T c2 = std::cos(ToRadians(roll) / F(2.0)); T c3 = std::cos(ToRadians(pitch) / F(2.0)); diff --git a/include/Nazara/Math/Matrix4.inl b/include/Nazara/Math/Matrix4.inl index 021cb6378..f045ac28a 100644 --- a/include/Nazara/Math/Matrix4.inl +++ b/include/Nazara/Math/Matrix4.inl @@ -792,7 +792,7 @@ namespace Nz template bool Matrix4::IsAffine() const { - return m14 == F(0.0) && m24 == F(0.0) && m34 == F(0.0) && m44 == F(1.0); + return NumberEquals(m14, F(0.0)) && NumberEquals(m24, F(0.0)) && NumberEquals(m34, F(0.0)) && NumberEquals(m44, F(1.0)); } /*! diff --git a/include/Nazara/Math/Quaternion.inl b/include/Nazara/Math/Quaternion.inl index 5c7df28cd..f7f7c693c 100644 --- a/include/Nazara/Math/Quaternion.inl +++ b/include/Nazara/Math/Quaternion.inl @@ -714,10 +714,10 @@ namespace Nz #endif Quaternion interpolated; - interpolated.w = Lerp(from.w, to.w, interpolation); - interpolated.x = Lerp(from.x, to.x, interpolation); - interpolated.y = Lerp(from.y, to.y, interpolation); - interpolated.z = Lerp(from.z, to.z, interpolation); + interpolated.w = Nz::Lerp(from.w, to.w, interpolation); + interpolated.x = Nz::Lerp(from.x, to.x, interpolation); + interpolated.y = Nz::Lerp(from.y, to.y, interpolation); + interpolated.z = Nz::Lerp(from.z, to.z, interpolation); return interpolated; } diff --git a/include/Nazara/Math/Vector3.inl b/include/Nazara/Math/Vector3.inl index 555286024..604cbfb86 100644 --- a/include/Nazara/Math/Vector3.inl +++ b/include/Nazara/Math/Vector3.inl @@ -911,9 +911,9 @@ namespace Nz template bool Vector3::operator<(const Vector3& vec) const { - if (x == vec.x) + if (NumberEquals(x, vec.x)) { - if (y == vec.y) + if (NumberEquals(y, vec.y)) return z < vec.z; else return y < vec.y; @@ -931,10 +931,10 @@ namespace Nz template bool Vector3::operator<=(const Vector3& vec) const { - if (x == vec.x) + if (NumberEquals(x, vec.x)) { - if (y == vec.y) - return z <= vec.z; + if (NumberEquals(y, vec.y)) + return NumberEquals(z, vec.z) || z < vec.z; else return y < vec.y; } @@ -1371,7 +1371,7 @@ namespace std } }; } - + #undef F #include diff --git a/include/Nazara/Math/Vector4.inl b/include/Nazara/Math/Vector4.inl index 190d31b99..f3cad0a31 100644 --- a/include/Nazara/Math/Vector4.inl +++ b/include/Nazara/Math/Vector4.inl @@ -843,11 +843,11 @@ namespace Nz template bool Vector4::operator<(const Vector4& vec) const { - if (x == vec.x) + if (NumberEquals(x, vec.x)) { - if (y == vec.y) + if (NumberEquals(y, vec.y)) { - if (z == vec.z) + if (NumberEquals(z, vec.z)) return w < vec.w; else return z < vec.z; @@ -869,12 +869,12 @@ namespace Nz template bool Vector4::operator<=(const Vector4& vec) const { - if (x == vec.x) + if (NumberEquals(x, vec.x)) { - if (y == vec.y) + if (NumberEquals(y, vec.y)) { - if (z == vec.z) - return w <= vec.w; + if (NumberEquals(z, vec.z)) + return NumberEquals(w, vec.w) || w < vec.w; else return z < vec.z; } @@ -1144,7 +1144,7 @@ namespace std } }; } - + #undef F #include diff --git a/include/Nazara/Network.hpp b/include/Nazara/Network.hpp index 72565a17f..41b7fce71 100644 --- a/include/Nazara/Network.hpp +++ b/include/Nazara/Network.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 03 Feb 2016 at 00:06:56 +// This file was automatically generated /* Nazara Engine - Network module @@ -36,7 +36,10 @@ #include #include #include +#include +#include #include +#include #include #include #include diff --git a/include/Nazara/Network/IpAddress.inl b/include/Nazara/Network/IpAddress.inl index 1eaef4341..ed06b1af7 100644 --- a/include/Nazara/Network/IpAddress.inl +++ b/include/Nazara/Network/IpAddress.inl @@ -380,7 +380,7 @@ namespace std // This is SDBM adapted for IP addresses, tested to generate the least collisions possible // (It doesn't mean it cannot be improved though) - std::size_t hash = 0; + std::size_t h = 0; switch (ip.GetProtocol()) { case Nz::NetProtocol_Any: @@ -389,20 +389,20 @@ namespace std case Nz::NetProtocol_IPv4: { - hash = ip.ToUInt32() + (hash << 6) + (hash << 16) - hash; + h = ip.ToUInt32() + (h << 6) + (h << 16) - h; break; } case Nz::NetProtocol_IPv6: { Nz::IpAddress::IPv6 v6 = ip.ToIPv6(); for (std::size_t i = 0; i < v6.size(); i++) - hash = v6[i] + (hash << 6) + (hash << 16) - hash; + h = v6[i] + (h << 6) + (h << 16) - h; break; } } - return ip.GetPort() + (hash << 6) + (hash << 16) - hash; + return ip.GetPort() + (h << 6) + (h << 16) - h; } }; } diff --git a/include/Nazara/Network/NetPacket.hpp b/include/Nazara/Network/NetPacket.hpp index 272808a33..7eef2979a 100644 --- a/include/Nazara/Network/NetPacket.hpp +++ b/include/Nazara/Network/NetPacket.hpp @@ -1,4 +1,4 @@ -// Copyright (C) 2015 Jérôme Leclercq +// Copyright (C) 2015 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 @@ -56,7 +56,7 @@ namespace Nz void OnEmptyStream() override; void FreeStream(); - void InitStream(std::size_t minCapacity, UInt64 cursorPos, UInt32 openMode); + void InitStream(std::size_t minCapacity, UInt64 cursorPos, OpenModeFlags openMode); static bool Initialize(); static void Uninitialize(); diff --git a/include/Nazara/Noise.hpp b/include/Nazara/Noise.hpp index e1d14460e..f8ecfb82e 100644 --- a/include/Nazara/Noise.hpp +++ b/include/Nazara/Noise.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 12 Jul 2016 at 17:44:43 +// This file was automatically generated /* Nazara Engine - Noise module diff --git a/include/Nazara/Physics2D.hpp b/include/Nazara/Physics2D.hpp index 9b4ce41f4..2c908ca79 100644 --- a/include/Nazara/Physics2D.hpp +++ b/include/Nazara/Physics2D.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 14 Oct 2016 at 18:58:18 +// This file was automatically generated /* Nazara Engine - Physics 2D module @@ -29,11 +29,11 @@ #ifndef NAZARA_GLOBAL_PHYSICS2D_HPP #define NAZARA_GLOBAL_PHYSICS2D_HPP -#include -#include #include -#include #include +#include +#include +#include #include #endif // NAZARA_GLOBAL_PHYSICS2D_HPP diff --git a/include/Nazara/Physics2D/Collider2D.hpp b/include/Nazara/Physics2D/Collider2D.hpp index f8cd7d6af..7bc1c7618 100644 --- a/include/Nazara/Physics2D/Collider2D.hpp +++ b/include/Nazara/Physics2D/Collider2D.hpp @@ -125,6 +125,33 @@ namespace Nz private: std::vector CreateShapes(RigidBody2D* body) const override; }; + + class SegmentCollider2D; + + using SegmentCollider2DConstRef = ObjectRef; + using SegmentCollider2DRef = ObjectRef; + + class NAZARA_PHYSICS2D_API SegmentCollider2D : public Collider2D + { + public: + inline SegmentCollider2D(const Vector2f& first, const Vector2f& second, float thickness = 1.f); + + float ComputeInertialMatrix(float mass) const override; + + inline const Vector2f& GetFirstPoint() const; + inline float GetLength() const; + inline const Vector2f& GetSecondPoint() const; + ColliderType2D GetType() const override; + + template static SegmentCollider2DRef New(Args&&... args); + + private: + std::vector CreateShapes(RigidBody2D* body) const override; + + Vector2f m_first; + Vector2f m_second; + float m_thickness; + }; } #include diff --git a/include/Nazara/Physics2D/Collider2D.inl b/include/Nazara/Physics2D/Collider2D.inl index 2cd44d326..5c3909cde 100644 --- a/include/Nazara/Physics2D/Collider2D.inl +++ b/include/Nazara/Physics2D/Collider2D.inl @@ -49,6 +49,36 @@ namespace Nz return object.release(); } + SegmentCollider2D::SegmentCollider2D(const Vector2f& first, const Vector2f& second, float thickness) : + m_first(first), + m_second(second), + m_thickness(thickness) + { + } + + inline const Vector2f& SegmentCollider2D::GetFirstPoint() const + { + return m_first; + } + + inline float SegmentCollider2D::GetLength() const + { + return m_first.Distance(m_second); + } + + inline const Vector2f& SegmentCollider2D::GetSecondPoint() const + { + return m_second; + } + + template + SegmentCollider2DRef SegmentCollider2D::New(Args&&... args) + { + std::unique_ptr object(new SegmentCollider2D(std::forward(args)...)); + object->SetPersistent(false); + + return object.release(); + } } #include diff --git a/include/Nazara/Physics2D/ConfigCheck.hpp b/include/Nazara/Physics2D/ConfigCheck.hpp index 4689d6e68..3b3b90afc 100644 --- a/include/Nazara/Physics2D/ConfigCheck.hpp +++ b/include/Nazara/Physics2D/ConfigCheck.hpp @@ -10,9 +10,9 @@ /// Ce fichier sert à vérifier la valeur des constantes du fichier Config.hpp // On force la valeur de MANAGE_MEMORY en mode debug -#if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS_MANAGE_MEMORY - #undef NAZARA_PHYSICS_MANAGE_MEMORY - #define NAZARA_PHYSICS3D_MANAGE_MEMORY 0 +#if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS2D_MANAGE_MEMORY + #undef NAZARA_PHYSICS2D_MANAGE_MEMORY + #define NAZARA_PHYSICS2D_MANAGE_MEMORY 0 #endif #endif // NAZARA_CONFIG_CHECK_PHYSICS_HPP diff --git a/include/Nazara/Physics2D/Debug.hpp b/include/Nazara/Physics2D/Debug.hpp index f9cebc624..729491e7c 100644 --- a/include/Nazara/Physics2D/Debug.hpp +++ b/include/Nazara/Physics2D/Debug.hpp @@ -2,7 +2,7 @@ // This file is part of the "Nazara Engine - Physics 2D module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#if NAZARA_PHYSICS_MANAGE_MEMORY +#include +#if NAZARA_PHYSICS2D_MANAGE_MEMORY #include #endif diff --git a/include/Nazara/Physics2D/DebugOff.hpp b/include/Nazara/Physics2D/DebugOff.hpp index dd95ffe34..ffbd0a25a 100644 --- a/include/Nazara/Physics2D/DebugOff.hpp +++ b/include/Nazara/Physics2D/DebugOff.hpp @@ -3,7 +3,7 @@ // 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 -#if NAZARA_PHYSICS_MANAGE_MEMORY +#if NAZARA_PHYSICS2D_MANAGE_MEMORY #undef delete #undef new #endif diff --git a/include/Nazara/Physics2D/RigidBody2D.hpp b/include/Nazara/Physics2D/RigidBody2D.hpp index 7d521fbe6..79b7d64bc 100644 --- a/include/Nazara/Physics2D/RigidBody2D.hpp +++ b/include/Nazara/Physics2D/RigidBody2D.hpp @@ -49,6 +49,7 @@ namespace Nz bool IsSleeping() const; void SetAngularVelocity(float angularVelocity); + void SetGeom(Collider2DRef geom); void SetMass(float mass); void SetMassCenter(const Vector2f& center); void SetPosition(const Vector2f& position); @@ -59,8 +60,8 @@ namespace Nz RigidBody2D& operator=(RigidBody2D&& object); private: + void Create(float mass = 1.f, float moment = 1.f); void Destroy(); - void SetGeom(Collider2DRef geom); std::vector m_shapes; Collider2DRef m_geom; diff --git a/include/Nazara/Physics3D.hpp b/include/Nazara/Physics3D.hpp index e9c84e757..a40c40b9c 100644 --- a/include/Nazara/Physics3D.hpp +++ b/include/Nazara/Physics3D.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 14 Oct 2016 at 18:58:18 +// This file was automatically generated /* Nazara Engine - Physics 3D module @@ -29,11 +29,11 @@ #ifndef NAZARA_GLOBAL_PHYSICS3D_HPP #define NAZARA_GLOBAL_PHYSICS3D_HPP -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include #endif // NAZARA_GLOBAL_PHYSICS3D_HPP diff --git a/include/Nazara/Physics3D/ConfigCheck.hpp b/include/Nazara/Physics3D/ConfigCheck.hpp index 6b1c82073..012cc426c 100644 --- a/include/Nazara/Physics3D/ConfigCheck.hpp +++ b/include/Nazara/Physics3D/ConfigCheck.hpp @@ -10,8 +10,8 @@ /// Ce fichier sert à vérifier la valeur des constantes du fichier Config.hpp // On force la valeur de MANAGE_MEMORY en mode debug -#if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS_MANAGE_MEMORY - #undef NAZARA_PHYSICS_MANAGE_MEMORY +#if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS3D_MANAGE_MEMORY + #undef NAZARA_PHYSICS3D_MANAGE_MEMORY #define NAZARA_PHYSICS3D_MANAGE_MEMORY 0 #endif diff --git a/include/Nazara/Physics3D/Debug.hpp b/include/Nazara/Physics3D/Debug.hpp index f70a8b570..ef111fb96 100644 --- a/include/Nazara/Physics3D/Debug.hpp +++ b/include/Nazara/Physics3D/Debug.hpp @@ -3,6 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#if NAZARA_PHYSICS_MANAGE_MEMORY +#if NAZARA_PHYSICS3D_MANAGE_MEMORY #include #endif diff --git a/include/Nazara/Physics3D/DebugOff.hpp b/include/Nazara/Physics3D/DebugOff.hpp index 595f0ad94..b8b84c240 100644 --- a/include/Nazara/Physics3D/DebugOff.hpp +++ b/include/Nazara/Physics3D/DebugOff.hpp @@ -3,7 +3,7 @@ // 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 -#if NAZARA_PHYSICS_MANAGE_MEMORY +#if NAZARA_PHYSICS3D_MANAGE_MEMORY #undef delete #undef new #endif diff --git a/include/Nazara/Physics3D/Enums.hpp b/include/Nazara/Physics3D/Enums.hpp index 1b8920cbc..b01c9bb83 100644 --- a/include/Nazara/Physics3D/Enums.hpp +++ b/include/Nazara/Physics3D/Enums.hpp @@ -25,6 +25,6 @@ namespace Nz ColliderType3D_Max = ColliderType3D_Tree }; -}; +} #endif // NAZARA_ENUMS_PHYSICS3D_HPP diff --git a/include/Nazara/Prerequesites.hpp b/include/Nazara/Prerequesites.hpp index bf9d1d75f..dbe478661 100644 --- a/include/Nazara/Prerequesites.hpp +++ b/include/Nazara/Prerequesites.hpp @@ -25,8 +25,7 @@ #ifndef NAZARA_PREREQUESITES_HPP #define NAZARA_PREREQUESITES_HPP -// Identification du compilateur -///TODO: Rajouter des tests d'identification de compilateurs +// Try to identify the compiler #if defined(__BORLANDC__) #define NAZARA_COMPILER_BORDLAND #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) @@ -63,10 +62,10 @@ #pragma warning(disable: 4251) #else #define NAZARA_COMPILER_UNKNOWN + #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) - #define NAZARA_FUNCTION __func__ // __func__ est standard depuis le C++11 + #define NAZARA_FUNCTION __func__ // __func__ has been standardized in C++ 2011 - /// Cette ligne n'est là que pour prévenir, n'hésitez pas à la commenter si elle vous empêche de compiler #pragma message This compiler is not fully supported #endif @@ -76,20 +75,20 @@ // Nazara version macro #define NAZARA_VERSION_MAJOR 0 -#define NAZARA_VERSION_MINOR 1 +#define NAZARA_VERSION_MINOR 2 #define NAZARA_VERSION_PATCH 1 #include -// Identification de la plateforme +// Try to identify target platform via defines #if defined(_WIN32) #define NAZARA_PLATFORM_WINDOWS #define NAZARA_EXPORT __declspec(dllexport) #define NAZARA_IMPORT __declspec(dllimport) - // Des defines pour le header Windows - #if defined(NAZARA_BUILD) // Pour ne pas entrer en conflit avec les defines de l'application ou d'une autre bibliothèque + // Somes defines for windows.h include.. + #if defined(NAZARA_BUILD) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -99,13 +98,12 @@ #endif #if NAZARA_CORE_WINDOWS_NT6 - // Version de Windows minimale : Vista #define NAZARA_WINNT 0x0600 #else #define NAZARA_WINNT 0x0501 #endif - // Pour ne pas casser le define déjà en place s'il est applicable + // Keep the actual define if existing and greater than our requirement #if defined(_WIN32_WINNT) #if _WIN32_WINNT < NAZARA_WINNT #undef _WIN32_WINNT @@ -128,7 +126,6 @@ #define NAZARA_PLATFORM_MACOSX #define NAZARA_PLATFORM_POSIX*/ #else - // À commenter pour tenter quand même une compilation #error This operating system is not fully supported by the Nazara Engine #define NAZARA_PLATFORM_UNKNOWN @@ -141,12 +138,7 @@ #define NAZARA_PLATFORM_x64 #endif -// Définit NDEBUG si NAZARA_DEBUG n'est pas présent -#if !defined(NAZARA_DEBUG) && !defined(NDEBUG) - #define NDEBUG -#endif - -// Macros supplémentaires +// A bunch of useful macros #define NazaraPrefix(a, prefix) prefix ## a #define NazaraPrefixMacro(a, prefix) NazaraPrefix(a, prefix) #define NazaraSuffix(a, suffix) a ## suffix @@ -155,8 +147,11 @@ #define NazaraStringifyMacro(s) NazaraStringify(s) // http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification #define NazaraUnused(a) (void) a +#include #include +static_assert(CHAR_BIT == 8, "CHAR_BIT is expected to be 8"); + static_assert(sizeof(int8_t) == 1, "int8_t is not of the correct size" ); static_assert(sizeof(int16_t) == 2, "int16_t is not of the correct size"); static_assert(sizeof(int32_t) == 4, "int32_t is not of the correct size"); @@ -169,17 +164,17 @@ static_assert(sizeof(uint64_t) == 8, "uint64_t is not of the correct size"); namespace Nz { - typedef int8_t Int8; - typedef uint8_t UInt8; + typedef int8_t Int8; + typedef uint8_t UInt8; - typedef int16_t Int16; - typedef uint16_t UInt16; + typedef int16_t Int16; + typedef uint16_t UInt16; - typedef int32_t Int32; - typedef uint32_t UInt32; + typedef int32_t Int32; + typedef uint32_t UInt32; - typedef int64_t Int64; - typedef uint64_t UInt64; + typedef int64_t Int64; + typedef uint64_t UInt64; } #endif // NAZARA_PREREQUESITES_HPP diff --git a/include/Nazara/Renderer.hpp b/include/Nazara/Renderer.hpp index b57d4c5a5..159b990de 100644 --- a/include/Nazara/Renderer.hpp +++ b/include/Nazara/Renderer.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 24 Jun 2015 at 13:55:50 +// This file was automatically generated /* Nazara Engine - Renderer module @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include diff --git a/include/Nazara/Renderer/RenderWindow.hpp b/include/Nazara/Renderer/RenderWindow.hpp index 1cda9d63d..3560dfcc9 100644 --- a/include/Nazara/Renderer/RenderWindow.hpp +++ b/include/Nazara/Renderer/RenderWindow.hpp @@ -30,7 +30,7 @@ namespace Nz { public: RenderWindow() = default; - RenderWindow(VideoMode mode, const String& title, UInt32 style = WindowStyle_Default, const ContextParameters& parameters = ContextParameters()); + RenderWindow(VideoMode mode, const String& title, WindowStyleFlags style = WindowStyle_Default, const ContextParameters& parameters = ContextParameters()); RenderWindow(WindowHandle handle, const ContextParameters& parameters = ContextParameters()); RenderWindow(const RenderWindow&) = delete; RenderWindow(RenderWindow&&) = delete; ///TODO @@ -39,7 +39,7 @@ namespace Nz bool CopyToImage(AbstractImage* image, const Vector3ui& dstPos = Vector3ui(0U)) const; bool CopyToImage(AbstractImage* image, const Rectui& rect, const Vector3ui& dstPos = Vector3ui(0U)) const; - bool Create(VideoMode mode, const String& title, UInt32 style = WindowStyle_Default, const ContextParameters& parameters = ContextParameters()); + bool Create(VideoMode mode, const String& title, WindowStyleFlags style = WindowStyle_Default, const ContextParameters& parameters = ContextParameters()); bool Create(WindowHandle handle, const ContextParameters& parameters = ContextParameters()); void Display(); diff --git a/include/Nazara/Utility.hpp b/include/Nazara/Utility.hpp index d7676277e..3734b919e 100644 --- a/include/Nazara/Utility.hpp +++ b/include/Nazara/Utility.hpp @@ -1,4 +1,4 @@ -// This file was automatically generated on 12 Jul 2016 at 17:44:43 +// This file was automatically generated /* Nazara Engine - Utility module @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include diff --git a/include/Nazara/Utility/Config.hpp b/include/Nazara/Utility/Config.hpp index ee77405be..39aa014af 100644 --- a/include/Nazara/Utility/Config.hpp +++ b/include/Nazara/Utility/Config.hpp @@ -38,9 +38,6 @@ // Lors du parsage d'une ressource, déclenche un avertissement si une erreur non-critique est repérée dans une ressource (Plus lent) #define NAZARA_UTILITY_STRICT_RESOURCE_PARSING 1 -// Fait tourner chaque fenêtre dans un thread séparé si le système le supporte -#define NAZARA_UTILITY_THREADED_WINDOW 0 - // Protège les classes des accès concurrentiels //#define NAZARA_UTILITY_THREADSAFE 1 diff --git a/include/Nazara/Utility/Enums.hpp b/include/Nazara/Utility/Enums.hpp index 3f32945c2..2c162cd7d 100644 --- a/include/Nazara/Utility/Enums.hpp +++ b/include/Nazara/Utility/Enums.hpp @@ -7,6 +7,8 @@ #ifndef NAZARA_ENUMS_UTILITY_HPP #define NAZARA_ENUMS_UTILITY_HPP +#include + namespace Nz { enum AnimationType @@ -430,18 +432,29 @@ namespace Nz WindowEventType_Max = WindowEventType_TextEntered }; - enum WindowStyleFlags + enum WindowStyle { - WindowStyle_None = 0x0, - WindowStyle_Fullscreen = 0x1, + WindowStyle_None, ///< Window has no border nor titlebar. + WindowStyle_Fullscreen, ///< At the window creation, the OS tries to set it in fullscreen. - WindowStyle_Closable = 0x2, - WindowStyle_Resizable = 0x4, - WindowStyle_Titlebar = 0x8, + 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_Default = WindowStyle_Closable | WindowStyle_Resizable | WindowStyle_Titlebar, - WindowStyle_Max = WindowStyle_Titlebar*2-1 + 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 EnableFlagsOperators + { + static constexpr bool value = true; + }; + + using WindowStyleFlags = Flags; + + constexpr WindowStyleFlags WindowStyle_Default = WindowStyle_Closable | WindowStyle_Resizable | WindowStyle_Titlebar; } #endif // NAZARA_ENUMS_UTILITY_HPP diff --git a/include/Nazara/Utility/EventHandler.hpp b/include/Nazara/Utility/EventHandler.hpp index 2464d5e72..5bc47bdea 100644 --- a/include/Nazara/Utility/EventHandler.hpp +++ b/include/Nazara/Utility/EventHandler.hpp @@ -24,6 +24,9 @@ namespace Nz inline void Dispatch(const WindowEvent& event); + EventHandler& operator=(const EventHandler&) = delete; + EventHandler& operator=(EventHandler&&) = default; + NazaraSignal(OnEvent, const EventHandler* /*eventHandler*/, const WindowEvent& /*event*/); NazaraSignal(OnGainedFocus, const EventHandler* /*eventHandler*/); NazaraSignal(OnLostFocus, const EventHandler* /*eventHandler*/); diff --git a/include/Nazara/Utility/Image.hpp b/include/Nazara/Utility/Image.hpp index 029157885..e1712aed1 100644 --- a/include/Nazara/Utility/Image.hpp +++ b/include/Nazara/Utility/Image.hpp @@ -91,6 +91,8 @@ namespace Nz ImageType GetType() const; unsigned int GetWidth(UInt8 level = 0) const; + bool HasAlpha() const; + bool IsValid() const; // Load diff --git a/include/Nazara/Utility/Mesh.hpp b/include/Nazara/Utility/Mesh.hpp index 60ccb98b1..38067ce81 100644 --- a/include/Nazara/Utility/Mesh.hpp +++ b/include/Nazara/Utility/Mesh.hpp @@ -28,25 +28,15 @@ namespace Nz { struct NAZARA_UTILITY_API MeshParams : ResourceParameters { - MeshParams(); // Vérifie que le storage par défaut est supporté (software autrement) + MeshParams(); - // La transformation appliquée à tous les sommets du mesh - Matrix4f matrix = Matrix4f::Identity(); - - // Si ceci sera le stockage utilisé par les buffers - UInt32 storage = DataStorage_Hardware; - - // Charger une version animée du mesh si possible ? - bool animated = true; - - // Faut-il centrer le mesh autour de l'origine ? - bool center = false; - - // Faut-il retourner les UV ? - bool flipUVs = false; - - // Faut-il optimiser les index buffers ? (Rendu plus rapide, mais le chargement dure plus longtemps) - bool optimizeIndexBuffers = true; + Matrix4f matrix = Matrix4f::Identity(); ///< A matrix which will transform every vertex position + UInt32 storage = DataStorage_Hardware; ///< The place where the buffers will be allocated + Vector2f texCoordOffset = {0.f, 0.f}; ///< Offset to apply on the texture coordinates (not scaled) + Vector2f texCoordScale = {1.f, 1.f}; ///< Scale to apply on the texture coordinates + bool animated = true; ///< If true, will load an animated version of the model if possible + 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. bool IsValid() const; }; diff --git a/include/Nazara/Utility/PixelFormat.inl b/include/Nazara/Utility/PixelFormat.inl index 4d8676916..59ad2ab04 100644 --- a/include/Nazara/Utility/PixelFormat.inl +++ b/include/Nazara/Utility/PixelFormat.inl @@ -39,18 +39,8 @@ namespace Nz } inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) : - redMask(rMask), - greenMask(gMask), - blueMask(bMask), - alphaMask(aMask), - content(formatContent), - redType(subType), - greenType(subType), - blueType(subType), - alphaType(subType), - name(formatName) + PixelFormatInfo(formatName, formatContent, subType, rMask, subType, gMask, subType, bMask, subType, aMask) { - RecomputeBitsPerPixel(); } inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, PixelFormatSubType rType, Bitset<> rMask, PixelFormatSubType gType, Bitset<> gMask, PixelFormatSubType bType, Bitset<> bMask, PixelFormatSubType aType, Bitset<> aMask, UInt8 bpp) : @@ -65,6 +55,11 @@ namespace Nz alphaType(aType), name(formatName) { + redMask.Reverse(); + greenMask.Reverse(); + blueMask.Reverse(); + alphaMask.Reverse(); + if (bpp == 0) RecomputeBitsPerPixel(); } @@ -123,6 +118,9 @@ namespace Nz if (usedBits > bitsPerPixel) return false; + if (usedBits > 64) //< Currently, formats with over 64 bits per component are not supported + return false; + switch (types[i]) { case PixelFormatSubType_Half: diff --git a/include/Nazara/Utility/VideoMode.hpp b/include/Nazara/Utility/VideoMode.hpp index dae9a5410..3c2243817 100644 --- a/include/Nazara/Utility/VideoMode.hpp +++ b/include/Nazara/Utility/VideoMode.hpp @@ -19,6 +19,7 @@ namespace Nz { public: VideoMode(); + VideoMode(unsigned int w, unsigned int h); VideoMode(unsigned int w, unsigned int h, UInt8 bpp); bool IsFullscreenValid() const; diff --git a/include/Nazara/Utility/Window.hpp b/include/Nazara/Utility/Window.hpp index e544093c5..5ecabd8dd 100644 --- a/include/Nazara/Utility/Window.hpp +++ b/include/Nazara/Utility/Window.hpp @@ -10,6 +10,8 @@ #define NAZARA_WINDOW_HPP #include +#include +#include #include #include #include @@ -19,11 +21,6 @@ #include #include -#if NAZARA_UTILITY_THREADED_WINDOW -#include -#include -#endif - namespace Nz { class Cursor; @@ -39,7 +36,7 @@ namespace Nz public: inline Window(); - inline Window(VideoMode mode, const String& title, UInt32 style = WindowStyle_Default); + inline Window(VideoMode mode, const String& title, WindowStyleFlags style = WindowStyle_Default); inline Window(WindowHandle handle); Window(const Window&) = delete; inline Window(Window&& window) noexcept; @@ -47,7 +44,7 @@ namespace Nz inline void Close(); - bool Create(VideoMode mode, const String& title, UInt32 style = WindowStyle_Default); + bool Create(VideoMode mode, const String& title, WindowStyleFlags style = WindowStyle_Default); bool Create(WindowHandle handle); void Destroy(); @@ -65,7 +62,7 @@ namespace Nz unsigned int GetHeight() const; Vector2i GetPosition() const; Vector2ui GetSize() const; - UInt32 GetStyle() const; + WindowStyleFlags GetStyle() const; String GetTitle() const; unsigned int GetWidth() const; @@ -114,23 +111,24 @@ namespace Nz private: void IgnoreNextMouseEvent(int mouseX, int mouseY) const; + inline void HandleEvent(const WindowEvent& event); inline void PushEvent(const WindowEvent& event); static bool Initialize(); static void Uninitialize(); std::queue m_events; - #if NAZARA_UTILITY_THREADED_WINDOW + std::vector m_pendingEvents; ConditionVariable m_eventCondition; + EventHandler m_eventHandler; Mutex m_eventMutex; Mutex m_eventConditionMutex; - bool m_waitForEvent; - #endif - EventHandler m_eventHandler; + bool m_asyncWindow; bool m_closed; bool m_closeOnQuit; bool m_eventPolling; bool m_ownsWindow; + bool m_waitForEvent; }; } diff --git a/include/Nazara/Utility/Window.inl b/include/Nazara/Utility/Window.inl index 08b23fc04..0fce86ba6 100644 --- a/include/Nazara/Utility/Window.inl +++ b/include/Nazara/Utility/Window.inl @@ -4,6 +4,7 @@ #include #include +#include #include namespace Nz @@ -13,15 +14,14 @@ namespace Nz */ inline Window::Window() : m_impl(nullptr), - #if NAZARA_UTILITY_THREADED_WINDOW - m_waitForEvent(false), - #endif + m_asyncWindow(false), m_closeOnQuit(true), - m_eventPolling(false) + m_eventPolling(false), + m_waitForEvent(false) { } - inline Window::Window(VideoMode mode, const String& title, UInt32 style) : + inline Window::Window(VideoMode mode, const String& title, WindowStyleFlags style) : Window() { ErrorFlags flags(ErrorFlag_ThrowException, true); @@ -41,16 +41,16 @@ namespace Nz inline Window::Window(Window&& window) noexcept : m_impl(window.m_impl), m_events(std::move(window.m_events)), - #if NAZARA_UTILITY_THREADED_WINDOW + 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_waitForEvent(window.m_waitForEvent), - #endif m_closed(window.m_closed), m_closeOnQuit(window.m_closeOnQuit), m_eventPolling(window.m_eventPolling), - m_ownsWindow(window.m_ownsWindow) + m_ownsWindow(window.m_ownsWindow), + m_waitForEvent(window.m_waitForEvent) { window.m_impl = nullptr; } @@ -104,12 +104,8 @@ namespace Nz return m_impl != nullptr; } - inline void Window::PushEvent(const WindowEvent& event) + inline void Window::HandleEvent(const WindowEvent& event) { - #if NAZARA_UTILITY_THREADED_WINDOW - m_eventMutex.Lock(); - #endif - if (m_eventPolling) m_events.push(event); @@ -120,17 +116,27 @@ namespace Nz if (event.type == WindowEventType_Quit && m_closeOnQuit) Close(); + } - #if NAZARA_UTILITY_THREADED_WINDOW - m_eventMutex.Unlock(); - - if (m_waitForEvent) + inline void Window::PushEvent(const WindowEvent& event) + { + if (!m_asyncWindow) + HandleEvent(event); + else { - m_eventConditionMutex.Lock(); - m_eventCondition.Signal(); - m_eventConditionMutex.Unlock(); + { + LockGuard eventLock(m_eventMutex); + + m_pendingEvents.push_back(event); + } + + if (m_waitForEvent) + { + m_eventConditionMutex.Lock(); + m_eventCondition.Signal(); + m_eventConditionMutex.Unlock(); + } } - #endif } /*! @@ -141,22 +147,21 @@ namespace Nz { Destroy(); - m_closed = window.m_closed; - m_closeOnQuit = window.m_closeOnQuit; - m_eventPolling = window.m_eventPolling; - m_impl = window.m_impl; - m_events = std::move(window.m_events); - m_ownsWindow = window.m_ownsWindow; + 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; - #if NAZARA_UTILITY_THREADED_WINDOW - m_eventCondition = std::move(window.m_eventCondition); - m_eventMutex = std::move(window.m_eventMutex); - m_eventConditionMutex = std::move(window.m_eventConditionMutex); - m_waitForEvent = window.m_waitForEvent; - #endif - return *this; } } diff --git a/plugins/Assimp/CustomStream.cpp b/plugins/Assimp/CustomStream.cpp index 643a5b13f..6dbdd90b6 100644 --- a/plugins/Assimp/CustomStream.cpp +++ b/plugins/Assimp/CustomStream.cpp @@ -69,7 +69,7 @@ size_t StreamWrite(aiFile* file, const char* buffer, size_t size, size_t count) aiFile* StreamOpener(aiFileIO* fileIO, const char* filePath, const char* openMode) { - FileIOUserdata* fileIOUserdata = reinterpret_cast(fileIO->UserData); + FileIOUserdata* fileIOUserdata = reinterpret_cast(fileIO->UserData); bool isOriginalStream = (std::strcmp(filePath, fileIOUserdata->originalFilePath) == 0); if (!isOriginalStream && strstr(filePath, StreamPath) != 0) @@ -83,13 +83,13 @@ aiFile* StreamOpener(aiFileIO* fileIO, const char* filePath, const char* openMod ErrorFlags errFlags(ErrorFlag_ThrowExceptionDisabled, true); ///TODO: Move to File::DecodeOpenMode - UInt32 openModeEnum = 0; + OpenModeFlags openModeEnum = 0; if (std::strchr(openMode, 'r')) { openModeEnum |= OpenMode_ReadOnly; if (std::strchr(openMode, '+')) - openModeEnum |= OpenMode_ReadWrite | OpenMode_MustExit; + openModeEnum |= OpenMode_ReadWrite | OpenMode_MustExist; } else if (std::strchr(openMode, 'w')) { @@ -133,10 +133,10 @@ aiFile* StreamOpener(aiFileIO* fileIO, const char* filePath, const char* openMod void StreamCloser(aiFileIO* fileIO, aiFile* file) { - FileIOUserdata* fileIOUserdata = reinterpret_cast(fileIO->UserData); - Stream* fileUserdata = reinterpret_cast(file->UserData); - - if (fileUserdata != fileIOUserdata->originalStream) + FileIOUserdata* fileIOUserdata = reinterpret_cast(fileIO->UserData); + Stream* fileUserdata = reinterpret_cast(file->UserData); + + if (fileUserdata != fileIOUserdata->originalStream) delete reinterpret_cast(file->UserData); delete file; diff --git a/plugins/Assimp/Plugin.cpp b/plugins/Assimp/Plugin.cpp index a668ec634..746549568 100644 --- a/plugins/Assimp/Plugin.cpp +++ b/plugins/Assimp/Plugin.cpp @@ -97,17 +97,14 @@ bool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters) unsigned int postProcess = aiProcess_CalcTangentSpace | aiProcess_JoinIdenticalVertices | aiProcess_MakeLeftHanded | aiProcess_Triangulate | aiProcess_RemoveComponent | aiProcess_GenSmoothNormals - | aiProcess_SplitLargeMeshes | aiProcess_LimitBoneWeights - | aiProcess_ImproveCacheLocality | aiProcess_RemoveRedundantMaterials - | aiProcess_FixInfacingNormals | aiProcess_SortByPType - | aiProcess_FindInvalidData | aiProcess_GenUVCoords - | aiProcess_TransformUVCoords | aiProcess_OptimizeMeshes - | aiProcess_OptimizeGraph | aiProcess_FlipWindingOrder + | aiProcess_SplitLargeMeshes | aiProcess_LimitBoneWeights + | aiProcess_ImproveCacheLocality | aiProcess_RemoveRedundantMaterials + | aiProcess_FixInfacingNormals | aiProcess_SortByPType + | aiProcess_FindInvalidData | aiProcess_GenUVCoords + | aiProcess_TransformUVCoords | aiProcess_OptimizeMeshes + | aiProcess_OptimizeGraph | aiProcess_FlipWindingOrder | aiProcess_Debone; - if (parameters.flipUVs) - postProcess |= aiProcess_FlipUVs; - if (parameters.optimizeIndexBuffers) postProcess |= aiProcess_ImproveCacheLocality; @@ -157,7 +154,7 @@ bool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters) if (animatedMesh) { mesh->CreateSkeletal(joints.size()); - + Skeleton* skeleton = mesh->GetSkeleton(); // First, assign names @@ -172,9 +169,9 @@ bool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters) else { mesh->CreateStatic(); - + // aiMaterial index in scene => Material index and data in Mesh - std::unordered_map> materials; + std::unordered_map> materials; for (unsigned int i = 0; i < scene->mNumMeshes; ++i) { @@ -219,7 +216,7 @@ bool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters) 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->uv.Set(uv.x, uv.y); + vertex->uv.Set(parameters.texCoordOffset + Vector2f(uv.x, uv.y) * parameters.texCoordScale); vertex++; } @@ -311,7 +308,7 @@ bool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters) mesh->AddSubMesh(subMesh); } - mesh->SetMaterialCount(std::max(materials.size(), 1)); + mesh->SetMaterialCount(std::max(materials.size(), 1)); for (const auto& pair : materials) mesh->SetMaterialData(pair.second.first, pair.second.second); } diff --git a/readme.md b/readme.md index edb58080e..ea054e608 100644 --- a/readme.md +++ b/readme.md @@ -1,7 +1,7 @@ Platform | Build Status ------------ | ------------- Windows | [![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/dj5qx7axym4uakmy/branch/master?svg=true)](https://ci.appveyor.com/project/DPSLynix/nazaraengine/branch/master) -Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine) +Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg?branch=master)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine) # Nazara Engine diff --git a/readme_fr.md b/readme_fr.md index d7aff37b9..422be6a0e 100644 --- a/readme_fr.md +++ b/readme_fr.md @@ -1,7 +1,7 @@ Platforme | Build Status ------------ | ------------- Windows | [![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/dj5qx7axym4uakmy/branch/master?svg=true)](https://ci.appveyor.com/project/DPSLynix/nazaraengine/branch/master) -Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine) +Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg?branch=master)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine) # Nazara Engine diff --git a/src/Nazara/Audio/Music.cpp b/src/Nazara/Audio/Music.cpp index 1f0df6ba5..b2b0e7e3b 100644 --- a/src/Nazara/Audio/Music.cpp +++ b/src/Nazara/Audio/Music.cpp @@ -61,8 +61,6 @@ namespace Nz * \return true if creation was succesful * * \param soundStream Sound stream which is the source for the music - * - * \remark Produces a NazaraError if soundStream is invalid with NAZARA_AUDIO_SAFE defined */ bool Music::Create(SoundStream* soundStream) @@ -86,13 +84,14 @@ namespace Nz /*! * \brief Destroys the current music and frees resources + * + * \remark If the Music is playing, it is stopped first. */ - void Music::Destroy() { if (m_impl) { - Stop(); + StopThread(); delete m_impl; m_impl = nullptr; @@ -104,18 +103,11 @@ namespace Nz * * \param loop Should music loop * - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * \remark Music must be valid when calling this function */ - void Music::EnableLooping(bool loop) { - #if NAZARA_AUDIO_SAFE - if (!m_impl) - { - NazaraError("Music not created"); - return; - } - #endif + NazaraAssert(m_impl, "Music not created"); m_impl->loop = loop; } @@ -124,18 +116,11 @@ namespace Nz * \brief Gets the duration of the music * \return Duration of the music in milliseconds * - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * \remark Music must be valid when calling this function */ - UInt32 Music::GetDuration() const { - #if NAZARA_AUDIO_SAFE - if (!m_impl) - { - NazaraError("Music not created"); - return 0; - } - #endif + NazaraAssert(m_impl, "Music not created"); return m_impl->stream->GetDuration(); } @@ -144,18 +129,11 @@ namespace Nz * \brief Gets the format of the music * \return Enumeration of type AudioFormat (mono, stereo, ...) * - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * \remark Music must be valid when calling this function */ - AudioFormat Music::GetFormat() const { - #if NAZARA_AUDIO_SAFE - if (!m_impl) - { - NazaraError("Music not created"); - return AudioFormat_Unknown; - } - #endif + NazaraAssert(m_impl, "Music not created"); return m_impl->stream->GetFormat(); } @@ -164,7 +142,7 @@ namespace Nz * \brief Gets the current offset in the music * \return Offset in milliseconds (works with entire seconds) * - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * \remark Music must be valid when calling this function */ UInt32 Music::GetPlayingOffset() const { @@ -183,7 +161,7 @@ namespace Nz * \brief Gets the number of samples in the music * \return Count of samples (number of seconds * sample rate * channel count) * - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * \remark Music must be valid when calling this function */ UInt64 Music::GetSampleCount() const { @@ -196,7 +174,7 @@ namespace Nz * \brief Gets the rates of sample in the music * \return Rate of sample in Hertz (Hz) * - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * \remark Music must be valid when calling this function */ UInt32 Music::GetSampleRate() const { @@ -209,8 +187,7 @@ namespace Nz * \brief Gets the status of the music * \return Enumeration of type SoundStatus (Playing, Stopped, ...) * - * \remark If the music is not playing, Stopped is returned - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * \remark Music must be valid when calling this function */ SoundStatus Music::GetStatus() const { @@ -229,44 +206,37 @@ namespace Nz * \brief Checks whether the music is looping * \return true if it is the case * - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * \remark Music must be valid when calling this function */ - bool Music::IsLooping() const { - #if NAZARA_AUDIO_SAFE - if (!m_impl) - { - NazaraError("Music not created"); - return false; - } - #endif + NazaraAssert(m_impl, "Music not created"); return m_impl->loop; } /*! - * \brief Loads the music from file - * \return true if loading is successful + * \brief Opens the music from a file + * \return true if the file was successfully opened * * \param filePath Path to the file * \param params Parameters for the music */ - bool Music::OpenFromFile(const String& filePath, const MusicParams& params) { return MusicLoader::LoadFromFile(this, filePath, params); } /*! - * \brief Loads the music from memory + * \brief Opens the music from memory * \return true if loading is successful * * \param data Raw memory * \param size Size of the memory * \param params Parameters for the music + * + * \remark The memory pointer must stay valid (accessible) as long as the music is playing */ - bool Music::OpenFromMemory(const void* data, std::size_t size, const MusicParams& params) { return MusicLoader::LoadFromMemory(this, data, size, params); @@ -278,8 +248,9 @@ namespace Nz * * \param stream Stream to the music * \param params Parameters for the music + * + * \remark The stream must stay valid as long as the music is playing */ - bool Music::OpenFromStream(Stream& stream, const MusicParams& params) { return MusicLoader::LoadFromStream(this, stream, params); @@ -287,8 +258,9 @@ namespace Nz /*! * \brief Pauses the music + * + * \remark Music must be valid when calling this function */ - void Music::Pause() { alSourcePause(m_source); @@ -297,18 +269,16 @@ namespace Nz /*! * \brief Plays the music * - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * Plays/Resume the music. + * If the music is currently playing, resets the playing offset to the beginning offset. + * If the music is currently paused, resumes the playing. + * If the music is currently stopped, starts the playing at the previously set playing offset. + * + * \remark Music must be valid when calling this function */ - void Music::Play() { - #if NAZARA_AUDIO_SAFE - if (!m_impl) - { - NazaraError("Music not created"); - return; - } - #endif + NazaraAssert(m_impl, "Music not created"); // Maybe we are already playing if (m_impl->streaming) @@ -336,25 +306,20 @@ namespace Nz } /*! - * \brief Sets the playing offset for the music + * \brief Changes the playing offset of the music * - * \param offset Offset in the music in milliseconds + * If the music is not playing, this sets the playing offset for the next Play call * - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * \param offset The offset in milliseconds + * + * \remark Music must be valid when calling this function */ - void Music::SetPlayingOffset(UInt32 offset) { - #if NAZARA_AUDIO_SAFE - if (!m_impl) - { - NazaraError("Music not created"); - return; - } - #endif + NazaraAssert(m_impl, "Music not created"); bool isPlaying = m_impl->streaming; - + if (isPlaying) Stop(); @@ -368,33 +333,16 @@ namespace Nz /*! * \brief Stops the music * - * \remark Produces a NazaraError if there is no music with NAZARA_AUDIO_SAFE defined + * \remark Music must be valid when calling this function */ - void Music::Stop() { - #if NAZARA_AUDIO_SAFE - if (!m_impl) - { - NazaraError("Music not created"); - return; - } - #endif + NazaraAssert(m_impl, "Music not created"); - if (m_impl->streaming) - { - m_impl->streaming = false; - m_impl->thread.Join(); - } + StopThread(); + SetPlayingOffset(0); } - /*! - * \brief Fills the buffer and queues it up - * \return true if operation was successful - * - * \param buffer Index of the buffer - */ - bool Music::FillAndQueueBuffer(unsigned int buffer) { std::size_t sampleCount = m_impl->chunkSamples.size(); @@ -425,10 +373,6 @@ namespace Nz return sampleRead != sampleCount; // End of stream (Does not happen when looping) } - /*! - * \brief Thread function for the music - */ - void Music::MusicThread() { // Allocation of streaming buffers @@ -463,11 +407,11 @@ namespace Nz { ALuint buffer; alSourceUnqueueBuffers(m_source, 1, &buffer); - + ALint bits, size; alGetBufferi(buffer, AL_BITS, &bits); alGetBufferi(buffer, AL_SIZE, &size); - + if (bits != 0) m_impl->processedSamples += (8 * size) / bits; @@ -495,5 +439,14 @@ namespace Nz alDeleteBuffers(NAZARA_AUDIO_STREAMED_BUFFER_COUNT, buffers); } + void Music::StopThread() + { + if (m_impl->streaming) + { + m_impl->streaming = false; + m_impl->thread.Join(); + } + } + MusicLoader::LoaderList Music::s_loaders; } diff --git a/src/Nazara/Core/ByteArray.cpp b/src/Nazara/Core/ByteArray.cpp index e505f13f2..592170e40 100644 --- a/src/Nazara/Core/ByteArray.cpp +++ b/src/Nazara/Core/ByteArray.cpp @@ -15,6 +15,22 @@ namespace Nz * \brief Core class that represents an array of bytes */ + /*! + * \brief Gives a string representation in base 16 + * \return String in base 16 + */ + + String ByteArray::ToHex() const + { + std::size_t length = m_array.size() * 2; + + String hexOutput(length, '\0'); + for (std::size_t i = 0; i < m_array.size(); ++i) + std::sprintf(&hexOutput[i * 2], "%02x", m_array[i]); + + return hexOutput; + } + /*! * \brief Output operator * \return The stream diff --git a/src/Nazara/Core/ByteStream.cpp b/src/Nazara/Core/ByteStream.cpp index bca3db240..bc52f1782 100644 --- a/src/Nazara/Core/ByteStream.cpp +++ b/src/Nazara/Core/ByteStream.cpp @@ -24,7 +24,7 @@ namespace Nz * \param openMode Reading/writing mode for the stream */ - ByteStream::ByteStream(ByteArray* byteArray, UInt32 openMode) : + ByteStream::ByteStream(ByteArray* byteArray, OpenModeFlags openMode) : ByteStream() { SetStream(byteArray, openMode); @@ -67,7 +67,7 @@ namespace Nz * \param openMode Reading/writing mode for the stream */ - void ByteStream::SetStream(ByteArray* byteArray, UInt32 openMode) + void ByteStream::SetStream(ByteArray* byteArray, OpenModeFlags openMode) { std::unique_ptr stream(new MemoryStream(byteArray, openMode)); diff --git a/src/Nazara/Core/File.cpp b/src/Nazara/Core/File.cpp index 131ceb7f3..35706fb70 100644 --- a/src/Nazara/Core/File.cpp +++ b/src/Nazara/Core/File.cpp @@ -64,7 +64,7 @@ namespace Nz * \param openMode Flag of the file */ - File::File(const String& filePath, UInt32 openMode) : + File::File(const String& filePath, OpenModeFlags openMode) : File() { Open(filePath, openMode); @@ -311,7 +311,7 @@ namespace Nz * \remark Produces a NazaraError if OS error to open a file */ - bool File::Open(unsigned int openMode) + bool File::Open(OpenModeFlags openMode) { NazaraLock(m_mutex) @@ -352,7 +352,7 @@ namespace Nz * \remark Produces a NazaraError if OS error to open a file */ - bool File::Open(const String& filePath, unsigned int openMode) + bool File::Open(const String& filePath, OpenModeFlags openMode) { NazaraLock(m_mutex) @@ -906,5 +906,5 @@ namespace Nz } return true; - }; + } } diff --git a/src/Nazara/Core/MemoryStream.cpp b/src/Nazara/Core/MemoryStream.cpp index bb77f35f8..a2fb7ff2b 100644 --- a/src/Nazara/Core/MemoryStream.cpp +++ b/src/Nazara/Core/MemoryStream.cpp @@ -65,7 +65,7 @@ namespace Nz * \remark Produces a NazaraAssert if byteArray is nullptr */ - void MemoryStream::SetBuffer(ByteArray* byteArray, UInt32 openMode) + void MemoryStream::SetBuffer(ByteArray* byteArray, OpenModeFlags openMode) { NazaraAssert(byteArray, "Invalid ByteArray"); diff --git a/src/Nazara/Core/Posix/FileImpl.cpp b/src/Nazara/Core/Posix/FileImpl.cpp index 037d795f0..5603ed79b 100644 --- a/src/Nazara/Core/Posix/FileImpl.cpp +++ b/src/Nazara/Core/Posix/FileImpl.cpp @@ -49,7 +49,7 @@ namespace Nz return static_cast(position); } - bool FileImpl::Open(const String& filePath, UInt32 mode) + bool FileImpl::Open(const String& filePath, OpenModeFlags mode) { int flags; mode_t permissions = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; @@ -66,6 +66,9 @@ namespace Nz if (mode & OpenMode_Append) flags |= O_APPEND; + if (mode & OpenMode_MustExist) + flags &= ~O_CREAT; + if (mode & OpenMode_Truncate) flags |= O_TRUNC; diff --git a/src/Nazara/Core/Posix/FileImpl.hpp b/src/Nazara/Core/Posix/FileImpl.hpp index 4981a832e..51f966980 100644 --- a/src/Nazara/Core/Posix/FileImpl.hpp +++ b/src/Nazara/Core/Posix/FileImpl.hpp @@ -36,7 +36,7 @@ namespace Nz bool EndOfFile() const; void Flush(); UInt64 GetCursorPos() const; - bool Open(const String& filePath, UInt32 mode); + bool Open(const String& filePath, OpenModeFlags mode); std::size_t Read(void* buffer, std::size_t size); bool SetCursorPos(CursorPosition pos, Int64 offset); bool SetSize(UInt64 size); diff --git a/src/Nazara/Core/Win32/FileImpl.cpp b/src/Nazara/Core/Win32/FileImpl.cpp index 5ed051adb..1fb5a19eb 100644 --- a/src/Nazara/Core/Win32/FileImpl.cpp +++ b/src/Nazara/Core/Win32/FileImpl.cpp @@ -55,20 +55,20 @@ namespace Nz return position.QuadPart; } - bool FileImpl::Open(const String& filePath, UInt32 mode) + bool FileImpl::Open(const String& filePath, OpenModeFlags mode) { DWORD access = 0; DWORD shareMode = FILE_SHARE_READ; DWORD openMode = 0; - + if (mode & OpenMode_ReadOnly) { access |= GENERIC_READ; - if (mode & OpenMode_MustExit || (mode & OpenMode_WriteOnly) == 0) + if (mode & OpenMode_MustExist || (mode & OpenMode_WriteOnly) == 0) openMode |= OPEN_EXISTING; } - + if (mode & OpenMode_WriteOnly) { if (mode & OpenMode_Append) @@ -78,7 +78,7 @@ namespace Nz if (mode & OpenMode_Truncate) openMode |= CREATE_ALWAYS; - else if (mode & OpenMode_MustExit) + else if (mode & OpenMode_MustExist) openMode |= OPEN_EXISTING; else openMode |= OPEN_ALWAYS; diff --git a/src/Nazara/Core/Win32/FileImpl.hpp b/src/Nazara/Core/Win32/FileImpl.hpp index 9a669cb19..dabfc266c 100644 --- a/src/Nazara/Core/Win32/FileImpl.hpp +++ b/src/Nazara/Core/Win32/FileImpl.hpp @@ -29,7 +29,7 @@ namespace Nz bool EndOfFile() const; void Flush(); UInt64 GetCursorPos() const; - bool Open(const String& filePath, UInt32 mode); + bool Open(const String& filePath, OpenModeFlags mode); std::size_t Read(void* buffer, std::size_t size); bool SetCursorPos(CursorPosition pos, Int64 offset); bool SetSize(UInt64 size); diff --git a/src/Nazara/Graphics/DeferredGeometryPass.cpp b/src/Nazara/Graphics/DeferredGeometryPass.cpp index 79e651926..e95bf250b 100644 --- a/src/Nazara/Graphics/DeferredGeometryPass.cpp +++ b/src/Nazara/Graphics/DeferredGeometryPass.cpp @@ -159,13 +159,13 @@ namespace Nz instanceBuffer->SetVertexDeclaration(VertexDeclaration::Get(VertexLayout_Matrix4)); const Matrix4f* instanceMatrices = &instances[0]; - unsigned int instanceCount = instances.size(); - unsigned int maxInstanceCount = instanceBuffer->GetVertexCount(); // The number of matrices that can be hold in the buffer + std::size_t instanceCount = instances.size(); + std::size_t maxInstanceCount = instanceBuffer->GetVertexCount(); // The number of matrices that can be hold in the buffer while (instanceCount > 0) { // We compute the number of instances that we will be able to show this time (Depending on the instance buffer size) - unsigned int renderedInstanceCount = std::min(instanceCount, maxInstanceCount); + std::size_t renderedInstanceCount = std::min(instanceCount, maxInstanceCount); instanceCount -= renderedInstanceCount; // We fill the instancing buffer with our world matrices diff --git a/src/Nazara/Graphics/DepthRenderTechnique.cpp b/src/Nazara/Graphics/DepthRenderTechnique.cpp index bcae2eb57..60d344fb7 100644 --- a/src/Nazara/Graphics/DepthRenderTechnique.cpp +++ b/src/Nazara/Graphics/DepthRenderTechnique.cpp @@ -267,13 +267,13 @@ namespace Nz const Texture* overlay = overlayIt.first; auto& spriteChainVector = overlayIt.second.spriteChains; - unsigned int spriteChainCount = spriteChainVector.size(); + std::size_t spriteChainCount = spriteChainVector.size(); if (spriteChainCount > 0) { Renderer::SetTexture(overlayUnit, (overlay) ? overlay : &m_whiteTexture); - unsigned int spriteChain = 0; // Which chain of sprites are we treating - unsigned int spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain + std::size_t spriteChain = 0; // Which chain of sprites are we treating + std::size_t spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain do { @@ -281,13 +281,13 @@ namespace Nz BufferMapper vertexMapper(m_spriteBuffer, BufferAccess_DiscardAndWrite); VertexStruct_XYZ_Color_UV* vertices = static_cast(vertexMapper.GetPointer()); - unsigned int spriteCount = 0; - unsigned int maxSpriteCount = std::min(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4); + std::size_t spriteCount = 0; + std::size_t maxSpriteCount = std::min(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4); do { ForwardRenderQueue::SpriteChain_XYZ_Color_UV& currentChain = spriteChainVector[spriteChain]; - unsigned int count = std::min(maxSpriteCount - spriteCount, currentChain.spriteCount - spriteChainOffset); + std::size_t count = std::min(maxSpriteCount - spriteCount, currentChain.spriteCount - spriteChainOffset); std::memcpy(vertices, currentChain.vertices + spriteChainOffset * 4, 4 * count * sizeof(VertexStruct_XYZ_Color_UV)); vertices += count * 4; @@ -373,17 +373,17 @@ namespace Nz auto& entry = matIt.second; auto& billboardVector = entry.billboards; - unsigned int billboardCount = billboardVector.size(); + std::size_t billboardCount = billboardVector.size(); if (billboardCount > 0) { // We begin to apply the material (and get the shader activated doing so) material->Apply(pipelineInstance); const ForwardRenderQueue::BillboardData* data = &billboardVector[0]; - unsigned int maxBillboardPerDraw = instanceBuffer->GetVertexCount(); + std::size_t maxBillboardPerDraw = instanceBuffer->GetVertexCount(); do { - unsigned int renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); + std::size_t renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); billboardCount -= renderedBillboardCount; instanceBuffer->Fill(data, 0, renderedBillboardCount, true); @@ -435,12 +435,12 @@ namespace Nz auto& billboardVector = entry.billboards; const ForwardRenderQueue::BillboardData* data = &billboardVector[0]; - unsigned int maxBillboardPerDraw = std::min(s_maxQuads, m_billboardPointBuffer.GetVertexCount() / 4); + std::size_t maxBillboardPerDraw = std::min(s_maxQuads, m_billboardPointBuffer.GetVertexCount() / 4); - unsigned int billboardCount = billboardVector.size(); + std::size_t billboardCount = billboardVector.size(); do { - unsigned int renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); + std::size_t renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); billboardCount -= renderedBillboardCount; BufferMapper vertexMapper(m_billboardPointBuffer, BufferAccess_DiscardAndWrite, 0, renderedBillboardCount * 4); @@ -584,13 +584,13 @@ namespace Nz instanceBuffer->SetVertexDeclaration(VertexDeclaration::Get(VertexLayout_Matrix4)); const Matrix4f* instanceMatrices = &instances[0]; - unsigned int instanceCount = instances.size(); - unsigned int maxInstanceCount = instanceBuffer->GetVertexCount(); // Maximum number of instance in one batch + std::size_t instanceCount = instances.size(); + std::size_t maxInstanceCount = instanceBuffer->GetVertexCount(); // Maximum number of instance in one batch while (instanceCount > 0) { // We compute the number of instances that we will be able to draw this time (depending on the instancing buffer size) - unsigned int renderedInstanceCount = std::min(instanceCount, maxInstanceCount); + std::size_t renderedInstanceCount = std::min(instanceCount, maxInstanceCount); instanceCount -= renderedInstanceCount; // We fill the instancing buffer with our world matrices diff --git a/src/Nazara/Graphics/ForwardRenderQueue.cpp b/src/Nazara/Graphics/ForwardRenderQueue.cpp index b74ffa732..6c6915214 100644 --- a/src/Nazara/Graphics/ForwardRenderQueue.cpp +++ b/src/Nazara/Graphics/ForwardRenderQueue.cpp @@ -383,7 +383,7 @@ namespace Nz auto& transparentModelData = currentLayer.transparentModelData; // The material is transparent, we must draw this mesh using another way (after the rendering of opages objects while sorting them) - unsigned int index = transparentModelData.size(); + std::size_t index = transparentModelData.size(); transparentModelData.resize(index+1); TransparentModelData& data = transparentModelData.back(); @@ -527,6 +527,24 @@ namespace Nz layers.erase(it++); else { + for (auto& pipelinePair : layer.billboards) + { + auto& pipelineEntry = pipelinePair.second; + + if (pipelineEntry.enabled) + { + for (auto& matIt : pipelinePair.second.materialMap) + { + auto& entry = matIt.second; + auto& billboardVector = entry.billboards; + + billboardVector.clear(); + } + } + + pipelineEntry.enabled = false; + } + for (auto& pipelinePair : layer.basicSprites) { auto& pipelineEntry = pipelinePair.second; @@ -603,7 +621,7 @@ namespace Nz { Layer& layer = pair.second; - std::sort(layer.transparentModels.begin(), layer.transparentModels.end(), [&layer, &nearPlane, &viewerNormal] (unsigned int index1, unsigned int index2) + std::sort(layer.transparentModels.begin(), layer.transparentModels.end(), [&layer, &nearPlane, &viewerNormal] (std::size_t index1, std::size_t index2) { const Spheref& sphere1 = layer.transparentModelData[index1].squaredBoundingSphere; const Spheref& sphere2 = layer.transparentModelData[index2].squaredBoundingSphere; @@ -672,7 +690,7 @@ namespace Nz BatchedBillboardEntry& entry = it->second; auto& billboardVector = entry.billboards; - unsigned int prevSize = billboardVector.size(); + std::size_t prevSize = billboardVector.size(); billboardVector.resize(prevSize + count); return &billboardVector[prevSize]; diff --git a/src/Nazara/Graphics/ForwardRenderTechnique.cpp b/src/Nazara/Graphics/ForwardRenderTechnique.cpp index 699ae416a..76541c982 100644 --- a/src/Nazara/Graphics/ForwardRenderTechnique.cpp +++ b/src/Nazara/Graphics/ForwardRenderTechnique.cpp @@ -33,8 +33,8 @@ namespace Nz Vector2f uv; }; - unsigned int s_maxQuads = std::numeric_limits::max() / 6; - unsigned int s_vertexBufferSize = 4 * 1024 * 1024; // 4 MiB + std::size_t s_maxQuads = std::numeric_limits::max() / 6; + std::size_t s_vertexBufferSize = 4 * 1024 * 1024; // 4 MiB } /*! @@ -347,13 +347,13 @@ namespace Nz const Texture* overlay = overlayIt.first; auto& spriteChainVector = overlayIt.second.spriteChains; - unsigned int spriteChainCount = spriteChainVector.size(); + std::size_t spriteChainCount = spriteChainVector.size(); if (spriteChainCount > 0) { Renderer::SetTexture(overlayUnit, (overlay) ? overlay : &m_whiteTexture); - unsigned int spriteChain = 0; // Which chain of sprites are we treating - unsigned int spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain + std::size_t spriteChain = 0; // Which chain of sprites are we treating + std::size_t spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain do { @@ -361,13 +361,13 @@ namespace Nz BufferMapper vertexMapper(m_spriteBuffer, BufferAccess_DiscardAndWrite); VertexStruct_XYZ_Color_UV* vertices = static_cast(vertexMapper.GetPointer()); - unsigned int spriteCount = 0; - unsigned int maxSpriteCount = std::min(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4); + std::size_t spriteCount = 0; + std::size_t maxSpriteCount = std::min(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4); do { ForwardRenderQueue::SpriteChain_XYZ_Color_UV& currentChain = spriteChainVector[spriteChain]; - unsigned int count = std::min(maxSpriteCount - spriteCount, currentChain.spriteCount - spriteChainOffset); + std::size_t count = std::min(maxSpriteCount - spriteCount, currentChain.spriteCount - spriteChainOffset); std::memcpy(vertices, currentChain.vertices + spriteChainOffset * 4, 4 * count * sizeof(VertexStruct_XYZ_Color_UV)); vertices += count * 4; @@ -450,17 +450,17 @@ namespace Nz auto& entry = matIt.second; auto& billboardVector = entry.billboards; - unsigned int billboardCount = billboardVector.size(); + std::size_t billboardCount = billboardVector.size(); if (billboardCount > 0) { // We begin to apply the material (and get the shader activated doing so) material->Apply(pipelineInstance); const ForwardRenderQueue::BillboardData* data = &billboardVector[0]; - unsigned int maxBillboardPerDraw = instanceBuffer->GetVertexCount(); + std::size_t maxBillboardPerDraw = instanceBuffer->GetVertexCount(); do { - unsigned int renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); + std::size_t renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); billboardCount -= renderedBillboardCount; instanceBuffer->Fill(data, 0, renderedBillboardCount, true); @@ -512,12 +512,12 @@ namespace Nz auto& billboardVector = entry.billboards; const ForwardRenderQueue::BillboardData* data = &billboardVector[0]; - unsigned int maxBillboardPerDraw = std::min(s_maxQuads, m_billboardPointBuffer.GetVertexCount() / 4); + std::size_t maxBillboardPerDraw = std::min(s_maxQuads, m_billboardPointBuffer.GetVertexCount() / 4); - unsigned int billboardCount = billboardVector.size(); + std::size_t billboardCount = billboardVector.size(); do { - unsigned int renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); + std::size_t renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw); billboardCount -= renderedBillboardCount; BufferMapper vertexMapper(m_billboardPointBuffer, BufferAccess_DiscardAndWrite, 0, renderedBillboardCount * 4); @@ -561,8 +561,6 @@ namespace Nz Renderer::DrawIndexedPrimitives(PrimitiveMode_TriangleList, 0, renderedBillboardCount * 6); } while (billboardCount > 0); - - billboardVector.clear(); } } } @@ -666,16 +664,16 @@ namespace Nz // With instancing, impossible to select the lights for each object // So, it's only activated for directional lights - unsigned int lightCount = m_renderQueue.directionalLights.size(); - unsigned int lightIndex = 0; + std::size_t lightCount = m_renderQueue.directionalLights.size(); + std::size_t lightIndex = 0; RendererComparison oldDepthFunc = Renderer::GetDepthFunc(); - unsigned int passCount = (lightCount == 0) ? 1 : (lightCount - 1) / NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS + 1; - for (unsigned int pass = 0; pass < passCount; ++pass) + std::size_t passCount = (lightCount == 0) ? 1 : (lightCount - 1) / NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS + 1; + for (std::size_t pass = 0; pass < passCount; ++pass) { if (shaderUniforms->hasLightUniforms) { - unsigned int renderedLightCount = std::min(lightCount, NazaraSuffixMacro(NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS, U)); + std::size_t renderedLightCount = std::min(lightCount, NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS); lightCount -= renderedLightCount; if (pass == 1) @@ -690,18 +688,18 @@ namespace Nz } // Sends the uniforms - for (unsigned int i = 0; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) + for (std::size_t i = 0; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) SendLightUniforms(shader, shaderUniforms->lightUniforms, lightIndex++, shaderUniforms->lightOffset * i, freeTextureUnit + i); } const Matrix4f* instanceMatrices = &instances[0]; - unsigned int instanceCount = instances.size(); - unsigned int maxInstanceCount = instanceBuffer->GetVertexCount(); // Maximum number of instance in one batch + std::size_t instanceCount = instances.size(); + std::size_t maxInstanceCount = instanceBuffer->GetVertexCount(); // Maximum number of instance in one batch while (instanceCount > 0) { // We compute the number of instances that we will be able to draw this time (depending on the instancing buffer size) - unsigned int renderedInstanceCount = std::min(instanceCount, maxInstanceCount); + std::size_t renderedInstanceCount = std::min(instanceCount, maxInstanceCount); instanceCount -= renderedInstanceCount; // We fill the instancing buffer with our world matrices @@ -726,16 +724,16 @@ namespace Nz // Choose the lights depending on an object position and apparent radius ChooseLights(Spheref(matrix.GetTranslation() + squaredBoundingSphere.GetPosition(), squaredBoundingSphere.radius)); - unsigned int lightCount = m_lights.size(); + std::size_t lightCount = m_lights.size(); Renderer::SetMatrix(MatrixType_World, matrix); - unsigned int lightIndex = 0; + std::size_t lightIndex = 0; RendererComparison oldDepthFunc = Renderer::GetDepthFunc(); // In the case where we have to change it - unsigned int passCount = (lightCount == 0) ? 1 : (lightCount - 1) / NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS + 1; - for (unsigned int pass = 0; pass < passCount; ++pass) + std::size_t passCount = (lightCount == 0) ? 1 : (lightCount - 1) / NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS + 1; + for (std::size_t pass = 0; pass < passCount; ++pass) { - lightCount -= std::min(lightCount, NazaraSuffixMacro(NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS, U)); + lightCount -= std::min(lightCount, NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS); if (pass == 1) { @@ -749,7 +747,7 @@ namespace Nz } // Sends the light uniforms to the shader - for (unsigned int i = 0; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) + for (std::size_t i = 0; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) SendLightUniforms(shader, shaderUniforms->lightUniforms, lightIndex++, shaderUniforms->lightOffset*i, freeTextureUnit + i); // And we draw @@ -772,7 +770,6 @@ namespace Nz } } } - instances.clear(); } } } @@ -835,7 +832,7 @@ namespace Nz { lightCount = std::min(m_renderQueue.directionalLights.size(), static_cast(NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS)); - for (unsigned int i = 0; i < lightCount; ++i) + for (std::size_t i = 0; i < lightCount; ++i) SendLightUniforms(shader, shaderUniforms->lightUniforms, i, shaderUniforms->lightOffset * i, freeTextureUnit++); } @@ -874,7 +871,7 @@ namespace Nz float radius = modelData.squaredBoundingSphere.radius; ChooseLights(Spheref(position, radius), false); - for (unsigned int i = lightCount; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) + for (std::size_t i = lightCount; i < NAZARA_GRAPHICS_MAX_LIGHT_PER_PASS; ++i) SendLightUniforms(shader, shaderUniforms->lightUniforms, i, shaderUniforms->lightOffset*i, freeTextureUnit++); } diff --git a/src/Nazara/Graphics/InstancedRenderable.cpp b/src/Nazara/Graphics/InstancedRenderable.cpp index ef5f62b96..e927e2d22 100644 --- a/src/Nazara/Graphics/InstancedRenderable.cpp +++ b/src/Nazara/Graphics/InstancedRenderable.cpp @@ -94,6 +94,7 @@ namespace Nz void InstancedRenderable::UpdateData(InstanceData* instanceData) const { NazaraAssert(instanceData, "Invalid instance data"); + NazaraUnused(instanceData); } InstancedRenderableLibrary::LibraryMap InstancedRenderable::s_library; diff --git a/src/Nazara/Graphics/ParticleDeclaration.cpp b/src/Nazara/Graphics/ParticleDeclaration.cpp index ebd84e95d..60786c1f1 100644 --- a/src/Nazara/Graphics/ParticleDeclaration.cpp +++ b/src/Nazara/Graphics/ParticleDeclaration.cpp @@ -100,7 +100,7 @@ namespace Nz * \remark Produces a NazaraError with NAZARA_GRAPHICS_SAFE defined if type is not supported */ - void ParticleDeclaration::EnableComponent(ParticleComponent component, ComponentType type, unsigned int offset) + void ParticleDeclaration::EnableComponent(ParticleComponent component, ComponentType type, std::size_t offset) { #ifdef NAZARA_DEBUG if (component > ParticleComponent_Max) @@ -145,7 +145,7 @@ namespace Nz * \remark Produces a NazaraError with NAZARA_GRAPHICS_SAFE defined if enumeration is equal to ParticleComponent_Unused */ - void ParticleDeclaration::GetComponent(ParticleComponent component, bool* enabled, ComponentType* type, unsigned int* offset) const + void ParticleDeclaration::GetComponent(ParticleComponent component, bool* enabled, ComponentType* type, std::size_t* offset) const { #ifdef NAZARA_DEBUG if (component > ParticleComponent_Max) @@ -180,7 +180,7 @@ namespace Nz * \return Stride of the declaration */ - unsigned int ParticleDeclaration::GetStride() const + std::size_t ParticleDeclaration::GetStride() const { return m_stride; } diff --git a/src/Nazara/Graphics/ParticleEmitter.cpp b/src/Nazara/Graphics/ParticleEmitter.cpp index fe27575e7..038e69ce9 100644 --- a/src/Nazara/Graphics/ParticleEmitter.cpp +++ b/src/Nazara/Graphics/ParticleEmitter.cpp @@ -74,11 +74,11 @@ namespace Nz if (emissionCount >= 1.f) { // We compute the maximum number of particles which can be emitted - unsigned int emissionCountInt = static_cast(emissionCount); - unsigned int maxParticleCount = emissionCountInt * m_emissionCount; + std::size_t emissionCountInt = static_cast(emissionCount); + std::size_t maxParticleCount = emissionCountInt * m_emissionCount; // We get the number of particles that we are able to create (depending on the free space) - unsigned int particleCount = std::min(maxParticleCount, system.GetMaxParticleCount() - system.GetParticleCount()); + std::size_t particleCount = std::min(maxParticleCount, system.GetMaxParticleCount() - system.GetParticleCount()); if (particleCount == 0) return; @@ -115,7 +115,7 @@ namespace Nz * \return Current emission count */ - unsigned int ParticleEmitter::GetEmissionCount() const + std::size_t ParticleEmitter::GetEmissionCount() const { return m_emissionCount; } @@ -146,7 +146,7 @@ namespace Nz * \param count Emission count */ - void ParticleEmitter::SetEmissionCount(unsigned int count) + void ParticleEmitter::SetEmissionCount(std::size_t count) { m_emissionCount = count; } diff --git a/src/Nazara/Graphics/ParticleGroup.cpp b/src/Nazara/Graphics/ParticleGroup.cpp index 5aca6c2b4..f2c46d91c 100644 --- a/src/Nazara/Graphics/ParticleGroup.cpp +++ b/src/Nazara/Graphics/ParticleGroup.cpp @@ -142,11 +142,10 @@ namespace Nz * \remark Produces a NazaraAssert if renderQueue is invalid */ - void ParticleGroup::AddToRenderQueue(AbstractRenderQueue* renderQueue, const Matrix4f& transformMatrix) const + void ParticleGroup::AddToRenderQueue(AbstractRenderQueue* renderQueue, const Matrix4f& /*transformMatrix*/) const { NazaraAssert(m_renderer, "Invalid particle renderer"); NazaraAssert(renderQueue, "Invalid renderqueue"); - NazaraUnused(transformMatrix); if (m_particleCount > 0) { @@ -215,7 +214,7 @@ namespace Nz if (m_particleCount + count > m_maxParticleCount) return nullptr; - unsigned int particlesIndex = m_particleCount; + std::size_t particlesIndex = m_particleCount; m_particleCount += count; return &m_buffer[particlesIndex * m_particleSize]; @@ -264,7 +263,7 @@ namespace Nz * \return Current maximum number */ - unsigned int ParticleGroup::GetMaxParticleCount() const + std::size_t ParticleGroup::GetMaxParticleCount() const { return m_maxParticleCount; } @@ -274,7 +273,7 @@ namespace Nz * \return Current number */ - unsigned int ParticleGroup::GetParticleCount() const + std::size_t ParticleGroup::GetParticleCount() const { return m_particleCount; } @@ -284,7 +283,7 @@ namespace Nz * \return Current size */ - unsigned int ParticleGroup::GetParticleSize() const + std::size_t ParticleGroup::GetParticleSize() const { return m_particleSize; } @@ -295,7 +294,7 @@ namespace Nz * \param index Index of the particle */ - void ParticleGroup::KillParticle(unsigned int index) + void ParticleGroup::KillParticle(std::size_t index) { ///FIXME: Verify the index @@ -402,10 +401,8 @@ namespace Nz * \param transformMatrix Matrix transformation for our bounding volume */ - void ParticleGroup::UpdateBoundingVolume(const Matrix4f& transformMatrix) + void ParticleGroup::UpdateBoundingVolume(const Matrix4f& /*transformMatrix*/) { - NazaraUnused(transformMatrix); - // Nothing to do here (our bounding volume is global) } diff --git a/src/Nazara/Graphics/RenderTechniques.cpp b/src/Nazara/Graphics/RenderTechniques.cpp index 46d84d9c4..8298245b7 100644 --- a/src/Nazara/Graphics/RenderTechniques.cpp +++ b/src/Nazara/Graphics/RenderTechniques.cpp @@ -170,7 +170,7 @@ namespace Nz * \return Number of techniques */ - unsigned int RenderTechniques::GetCount() + std::size_t RenderTechniques::GetCount() { return s_renderTechniques.size(); } diff --git a/src/Nazara/Graphics/Sprite.cpp b/src/Nazara/Graphics/Sprite.cpp index 1b14ab6de..d23fe4122 100644 --- a/src/Nazara/Graphics/Sprite.cpp +++ b/src/Nazara/Graphics/Sprite.cpp @@ -44,6 +44,64 @@ namespace Nz m_boundingVolume.Set(-origin, m_size.x*Vector3f::Right() + m_size.y*Vector3f::Down() - origin); } + /*! + * \brief Sets the material of the sprite from a name + * + * Tries to get a material from the MaterialLibrary and then the MaterialManager (which will treat the name as a path) + * Fails if the texture name is not a part of the MaterialLibrary nor the MaterialManager (which fails if it couldn't load the texture from its filepath) + * + * \param materialName Named texture for the material + * \param resizeSprite Should the sprite be resized to the material diffuse map size? + * + * \return True if the material was found or loaded from its name/path, false if it couldn't + */ + bool Sprite::SetMaterial(String materialName, bool resizeSprite) + { + MaterialRef material = MaterialLibrary::Query(materialName); + if (!material) + { + material = MaterialManager::Get(materialName); + if (!material) + { + NazaraError("Failed to get material \"" + materialName + "\""); + return false; + } + } + + SetMaterial(std::move(material), resizeSprite); + return true; + } + + /*! + * \brief Sets the texture of the sprite from a name + * + * Tries to get a texture from the TextureLibrary and then the TextureManager (which will treat the name as a path) + * Fails if the texture name is not a part of the TextureLibrary nor the TextureManager (which fails if it couldn't load the texture from its filepath) + * + * \param textureName Named texture for the sprite + * \param resizeSprite Should the sprite be resized to the texture size? + * + * \return True if the texture was found or loaded from its name/path, false if it couldn't + * + * \remark The sprite material gets copied to prevent accidentally changing other drawable materials + */ + bool Sprite::SetTexture(String textureName, bool resizeSprite) + { + TextureRef texture = TextureLibrary::Query(textureName); + if (!texture) + { + texture = TextureManager::Get(textureName); + if (!texture) + { + NazaraError("Failed to get texture \"" + textureName + "\""); + return false; + } + } + + SetTexture(std::move(texture), resizeSprite); + return true; + } + /*! * \brief Updates the data of the sprite * diff --git a/src/Nazara/Graphics/TextSprite.cpp b/src/Nazara/Graphics/TextSprite.cpp index d838af6b5..0bf987118 100644 --- a/src/Nazara/Graphics/TextSprite.cpp +++ b/src/Nazara/Graphics/TextSprite.cpp @@ -202,8 +202,8 @@ namespace Nz void TextSprite::MakeBoundingVolume() const { Rectf bounds(m_localBounds); - Vector2f max = bounds.GetMaximum(); - Vector2f min = bounds.GetMinimum(); + Vector2f max = m_scale * bounds.GetMaximum(); + Vector2f min = m_scale * bounds.GetMinimum(); m_boundingVolume.Set(min.x * Vector3f::Right() + min.y * Vector3f::Down(), max.x * Vector3f::Right() + max.y * Vector3f::Down()); } diff --git a/src/Nazara/Network/NetPacket.cpp b/src/Nazara/Network/NetPacket.cpp index 0823f5258..900170b89 100644 --- a/src/Nazara/Network/NetPacket.cpp +++ b/src/Nazara/Network/NetPacket.cpp @@ -127,7 +127,7 @@ namespace Nz * \remark Produces a NazaraAssert if cursor position is greather than the capacity */ - void NetPacket::InitStream(std::size_t minCapacity, UInt64 cursorPos, UInt32 openMode) + void NetPacket::InitStream(std::size_t minCapacity, UInt64 cursorPos, OpenModeFlags openMode) { NazaraAssert(minCapacity >= cursorPos, "Cannot init stream with a smaller capacity than wanted cursor pos"); @@ -146,7 +146,7 @@ namespace Nz if (!m_buffer) m_buffer = std::make_unique(); - m_buffer->Resize(static_cast(cursorPos)); + m_buffer->Resize(minCapacity); m_memoryStream.SetBuffer(m_buffer.get(), openMode); m_memoryStream.SetCursorPos(cursorPos); diff --git a/src/Nazara/Network/TcpClient.cpp b/src/Nazara/Network/TcpClient.cpp index 1c84dc498..2be3d44cf 100644 --- a/src/Nazara/Network/TcpClient.cpp +++ b/src/Nazara/Network/TcpClient.cpp @@ -385,7 +385,7 @@ namespace Nz * \remark Produces a NazaraError because it is a special stream */ - bool TcpClient::SetCursorPos(UInt64 offset) + bool TcpClient::SetCursorPos(UInt64 /*offset*/) { NazaraError("SetCursorPos() cannot be used on sequential streams"); return false; diff --git a/src/Nazara/Network/Win32/SocketImpl.cpp b/src/Nazara/Network/Win32/SocketImpl.cpp index 628d29807..5a02b4bae 100644 --- a/src/Nazara/Network/Win32/SocketImpl.cpp +++ b/src/Nazara/Network/Win32/SocketImpl.cpp @@ -437,6 +437,10 @@ namespace Nz return result; #else + NazaraUnused(fdarray); + NazaraUnused(nfds); + NazaraUnused(timeout); + if (error) *error = SocketError_NotSupported; diff --git a/src/Nazara/Physics2D/Collider2D.cpp b/src/Nazara/Physics2D/Collider2D.cpp index a840393e8..986a03ccf 100644 --- a/src/Nazara/Physics2D/Collider2D.cpp +++ b/src/Nazara/Physics2D/Collider2D.cpp @@ -10,7 +10,7 @@ namespace Nz { Collider2D::~Collider2D() = default; - + /******************************** BoxCollider2D *********************************/ BoxCollider2D::BoxCollider2D(const Vector2f& size, float radius) : @@ -84,4 +84,25 @@ namespace Nz { return std::vector(); } + + /******************************** SegmentCollider2D *********************************/ + + float SegmentCollider2D::ComputeInertialMatrix(float mass) const + { + return static_cast(cpMomentForSegment(mass, cpv(m_first.x, m_first.y), cpv(m_second.x, m_second.y), m_thickness)); + } + + ColliderType2D SegmentCollider2D::GetType() const + { + return ColliderType2D_Segment; + } + + std::vector SegmentCollider2D::CreateShapes(RigidBody2D* body) 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/Debug/NewOverload.cpp b/src/Nazara/Physics2D/Debug/NewOverload.cpp index bd3153d1d..0c82acc94 100644 --- a/src/Nazara/Physics2D/Debug/NewOverload.cpp +++ b/src/Nazara/Physics2D/Debug/NewOverload.cpp @@ -2,8 +2,8 @@ // This file is part of the "Nazara Engine - Physics 2D module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include -#if NAZARA_PHYSICS_MANAGE_MEMORY +#include +#if NAZARA_PHYSICS2D_MANAGE_MEMORY #include #include // Nécessaire ? diff --git a/src/Nazara/Physics2D/PhysWorld2D.cpp b/src/Nazara/Physics2D/PhysWorld2D.cpp index 5290abfcd..878a84400 100644 --- a/src/Nazara/Physics2D/PhysWorld2D.cpp +++ b/src/Nazara/Physics2D/PhysWorld2D.cpp @@ -24,7 +24,7 @@ namespace Nz Vector2f PhysWorld2D::GetGravity() const { cpVect gravity = cpSpaceGetGravity(m_handle); - return Vector2f(gravity.x, gravity.y); + return Vector2f(Vector2(gravity.x, gravity.y)); } cpSpace* PhysWorld2D::GetHandle() const diff --git a/src/Nazara/Physics2D/RigidBody2D.cpp b/src/Nazara/Physics2D/RigidBody2D.cpp index faa6223d1..9fdb34d50 100644 --- a/src/Nazara/Physics2D/RigidBody2D.cpp +++ b/src/Nazara/Physics2D/RigidBody2D.cpp @@ -22,13 +22,11 @@ namespace Nz m_geom(), m_world(world), m_gravityFactor(1.f), - m_mass(0.f) + m_mass(1.f) { NazaraAssert(m_world, "Invalid world"); - m_handle = cpBodyNew(0.f, 0.f); - cpBodySetUserData(m_handle, this); - cpSpaceAddBody(m_world->GetHandle(), m_handle); + Create(); SetGeom(geom); SetMass(mass); @@ -43,9 +41,7 @@ namespace Nz NazaraAssert(m_world, "Invalid world"); NazaraAssert(m_geom, "Invalid geometry"); - m_handle = cpBodyNew(0.f, 0.f); - cpBodySetUserData(m_handle, this); - cpSpaceAddBody(m_world->GetHandle(), m_handle); + Create(); SetGeom(object.GetGeom()); SetMass(object.GetMass()); @@ -77,7 +73,7 @@ namespace Nz switch (coordSys) { case CoordSys_Global: - cpBodyApplyForceAtWorldPoint(m_handle, cpv(force.x, force.y), cpv(force.x, force.y)); + cpBodyApplyForceAtWorldPoint(m_handle, cpv(force.x, force.y), cpv(point.x, point.y)); break; case CoordSys_Local: @@ -169,19 +165,60 @@ namespace Nz cpBodySetAngularVelocity(m_handle, angularVelocity); } + void RigidBody2D::SetGeom(Collider2DRef geom) + { + // 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); + + Destroy(); + Create(mass, moment); + + cpBodySetAngle(m_handle, rot); + cpBodySetPosition(m_handle, pos); + cpBodySetVelocity(m_handle, vel); + } + + if (geom) + m_geom = geom; + else + m_geom = NullCollider2D::New(); + + m_shapes = m_geom->CreateShapes(this); + + cpSpace* space = m_world->GetHandle(); + for (cpShape* shape : m_shapes) + cpSpaceAddShape(space, shape); + + cpBodySetMoment(m_handle, m_geom->ComputeInertialMatrix(m_mass)); + } + void RigidBody2D::SetMass(float mass) { if (m_mass > 0.f) { if (mass > 0.f) + { cpBodySetMass(m_handle, mass); + cpBodySetMoment(m_handle, m_geom->ComputeInertialMatrix(m_mass)); + } else cpBodySetType(m_handle, CP_BODY_TYPE_STATIC); } else if (mass > 0.f) { if (cpBodyGetType(m_handle) == CP_BODY_TYPE_STATIC) + { cpBodySetType(m_handle, CP_BODY_TYPE_DYNAMIC); + cpBodySetMass(m_handle, mass); + cpBodySetMoment(m_handle, m_geom->ComputeInertialMatrix(m_mass)); + } } m_mass = mass; @@ -196,6 +233,8 @@ namespace Nz 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) @@ -230,22 +269,26 @@ namespace Nz return *this; } + void RigidBody2D::Create(float mass, float moment) + { + m_handle = cpBodyNew(mass, moment); + cpBodySetUserData(m_handle, this); + cpSpaceAddBody(m_world->GetHandle(), m_handle); + } + void RigidBody2D::Destroy() { + cpSpace* space = m_world->GetHandle(); for (cpShape* shape : m_shapes) + { + cpSpaceRemoveShape(space, shape); cpShapeFree(shape); + } if (m_handle) + { + cpSpaceRemoveBody(space, m_handle); cpBodyFree(m_handle); - } - - void RigidBody2D::SetGeom(Collider2DRef geom) - { - if (geom) - m_geom = geom; - else - m_geom = NullCollider2D::New(); - - m_shapes = m_geom->CreateShapes(this); + } } } diff --git a/src/Nazara/Physics3D/Debug/NewOverload.cpp b/src/Nazara/Physics3D/Debug/NewOverload.cpp index 18092514c..b87984066 100644 --- a/src/Nazara/Physics3D/Debug/NewOverload.cpp +++ b/src/Nazara/Physics3D/Debug/NewOverload.cpp @@ -3,7 +3,7 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#if NAZARA_PHYSICS_MANAGE_MEMORY +#if NAZARA_PHYSICS3D_MANAGE_MEMORY #include #include // Nécessaire ? diff --git a/src/Nazara/Renderer/RenderTexture.cpp b/src/Nazara/Renderer/RenderTexture.cpp index 647b8ff91..d90ba5f1a 100644 --- a/src/Nazara/Renderer/RenderTexture.cpp +++ b/src/Nazara/Renderer/RenderTexture.cpp @@ -795,6 +795,7 @@ namespace Nz NazaraAssert(attachmentIndex < m_impl->attachments.size(), "Invalid attachment index"); NazaraAssert(!m_impl->attachments[attachmentIndex].isBuffer, "Invalid attachment state"); NazaraUnused(texture); + NazaraUnused(attachmentIndex); InvalidateTargets(); } diff --git a/src/Nazara/Renderer/RenderWindow.cpp b/src/Nazara/Renderer/RenderWindow.cpp index a9effa622..61131d9f1 100644 --- a/src/Nazara/Renderer/RenderWindow.cpp +++ b/src/Nazara/Renderer/RenderWindow.cpp @@ -15,7 +15,7 @@ namespace Nz { - RenderWindow::RenderWindow(VideoMode mode, const String& title, UInt32 style, const ContextParameters& parameters) : + RenderWindow::RenderWindow(VideoMode mode, const String& title, WindowStyleFlags style, const ContextParameters& parameters) : RenderTarget(), Window() { ErrorFlags flags(ErrorFlag_ThrowException, true); @@ -121,7 +121,7 @@ namespace Nz return true; } - bool RenderWindow::Create(VideoMode mode, const String& title, UInt32 style, const ContextParameters& parameters) + bool RenderWindow::Create(VideoMode mode, const String& title, WindowStyleFlags style, const ContextParameters& parameters) { m_parameters = parameters; return Window::Create(mode, title, style); diff --git a/src/Nazara/Utility/AlgorithmUtility.cpp b/src/Nazara/Utility/AlgorithmUtility.cpp index d82af98af..90a3d53e3 100644 --- a/src/Nazara/Utility/AlgorithmUtility.cpp +++ b/src/Nazara/Utility/AlgorithmUtility.cpp @@ -742,7 +742,7 @@ namespace Nz Vector3f halfLengths = lengths/2.f; // Face +X - transform.MakeTransform(Vector3f::UnitX() * halfLengths.x, EulerAnglesf(-90.f, 0.f, -90.f)); + transform.MakeTransform(Vector3f::UnitX() * halfLengths.x, EulerAnglesf(-90.f, -90.f, 180.f)); GeneratePlane(Vector2ui(subdivision.z, subdivision.y), Vector2f(lengths.z, lengths.y), Matrix4f::ConcatenateAffine(matrix, transform), textureCoords, vertexPointers, indices, nullptr, indexOffset); indexOffset += xVertexCount; indices += xIndexCount; @@ -776,7 +776,7 @@ namespace Nz vertexPointers.uvPtr += yVertexCount; // Face +Z - transform.MakeTransform(Vector3f::UnitZ() * halfLengths.z, EulerAnglesf(-90.f, 90.f, 90.f)); + transform.MakeTransform(Vector3f::UnitZ() * halfLengths.z, EulerAnglesf(90.f, 0.f, 0.f)); GeneratePlane(Vector2ui(subdivision.x, subdivision.y), Vector2f(lengths.x, lengths.y), Matrix4f::ConcatenateAffine(matrix, transform), textureCoords, vertexPointers, indices, nullptr, indexOffset); indexOffset += zVertexCount; indices += zIndexCount; @@ -793,7 +793,7 @@ namespace Nz vertexPointers.uvPtr += zVertexCount; // Face -X - transform.MakeTransform(-Vector3f::UnitX() * halfLengths.x, EulerAnglesf(-90.f, 0.f, 90.f)); + transform.MakeTransform(-Vector3f::UnitX() * halfLengths.x, EulerAnglesf(-90.f, 90.f, 180.f)); GeneratePlane(Vector2ui(subdivision.z, subdivision.y), Vector2f(lengths.z, lengths.y), Matrix4f::ConcatenateAffine(matrix, transform), textureCoords, vertexPointers, indices, nullptr, indexOffset); indexOffset += xVertexCount; indices += xIndexCount; @@ -810,7 +810,7 @@ namespace Nz vertexPointers.uvPtr += xVertexCount; // Face -Y - transform.MakeTransform(-Vector3f::UnitY() * halfLengths.y, EulerAnglesf(0.f, 0.f, 180.f)); + transform.MakeTransform(-Vector3f::UnitY() * halfLengths.y, EulerAnglesf(0.f, 180.f, 180.f)); GeneratePlane(Vector2ui(subdivision.x, subdivision.z), Vector2f(lengths.x, lengths.z), Matrix4f::ConcatenateAffine(matrix, transform), textureCoords, vertexPointers, indices, nullptr, indexOffset); indexOffset += yVertexCount; indices += yIndexCount; @@ -827,7 +827,7 @@ namespace Nz vertexPointers.uvPtr += yVertexCount; // Face -Z - transform.MakeTransform(-Vector3f::UnitZ() * halfLengths.z, EulerAnglesf(-90.f, -90.f, 90.f)); + transform.MakeTransform(-Vector3f::UnitZ() * halfLengths.z, EulerAnglesf(90.f, 180.f, 0.f)); GeneratePlane(Vector2ui(subdivision.x, subdivision.y), Vector2f(lengths.x, lengths.y), Matrix4f::ConcatenateAffine(matrix, transform), textureCoords, vertexPointers, indices, nullptr, indexOffset); indexOffset += zVertexCount; indices += zIndexCount; diff --git a/src/Nazara/Utility/Formats/DDSLoader.cpp b/src/Nazara/Utility/Formats/DDSLoader.cpp index d9783115b..1e707e610 100644 --- a/src/Nazara/Utility/Formats/DDSLoader.cpp +++ b/src/Nazara/Utility/Formats/DDSLoader.cpp @@ -174,15 +174,15 @@ namespace Nz if (header.format.flags & DDPF_RGB) { // Reverse bits for our masks - info.redMask = ReverseBits(header.format.redMask); - info.greenMask = ReverseBits(header.format.greenMask); - info.blueMask = ReverseBits(header.format.blueMask); + info.redMask = header.format.redMask; + info.greenMask = header.format.greenMask; + info.blueMask = header.format.blueMask; } else if (header.format.flags & DDPF_LUMINANCE) - info.redMask = ReverseBits(header.format.redMask); + info.redMask = header.format.redMask; if (header.format.flags & (DDPF_ALPHA | DDPF_ALPHAPIXELS)) - info.alphaMask = ReverseBits(header.format.alphaMask); + info.alphaMask = header.format.alphaMask; *format = PixelFormat::IdentifyFormat(info); if (!PixelFormat::IsValid(*format)) diff --git a/src/Nazara/Utility/Formats/MD2Loader.cpp b/src/Nazara/Utility/Formats/MD2Loader.cpp index dde203482..04628ba90 100644 --- a/src/Nazara/Utility/Formats/MD2Loader.cpp +++ b/src/Nazara/Utility/Formats/MD2Loader.cpp @@ -81,15 +81,14 @@ namespace Nz return false; } - /// Création du mesh - // Le moteur ne supporte plus les animations image-clé, nous ne pouvons charger qu'en statique - if (!mesh->CreateStatic()) // Ne devrait jamais échouer + // Since the engine no longer supports keyframe animations, let's make a static mesh + if (!mesh->CreateStatic()) { NazaraInternalError("Failed to create mesh"); return false; } - /// Chargement des skins + // Extract skins (texture name) if (header.num_skins > 0) { mesh->SetMaterialCount(header.num_skins); @@ -109,16 +108,15 @@ namespace Nz } } - /// Chargement des submesh - // Actuellement le loader ne charge qu'un submesh IndexBufferRef indexBuffer = IndexBuffer::New(false, header.num_tris*3, parameters.storage, BufferUsage_Static); - /// Lecture des triangles + // Extract triangles data std::vector triangles(header.num_tris); stream.SetCursorPos(header.offset_tris); stream.Read(&triangles[0], header.num_tris*sizeof(MD2_Triangle)); + // And convert them into an index buffer BufferMapper indexMapper(indexBuffer, BufferAccess_DiscardAndWrite); UInt16* index = static_cast(indexMapper.GetPointer()); @@ -135,7 +133,7 @@ namespace Nz SwapBytes(&triangles[i].texCoords[2], sizeof(UInt16)); #endif - // On respécifie le triangle dans l'ordre attendu + // Reverse winding order *index++ = triangles[i].vertices[0]; *index++ = triangles[i].vertices[2]; *index++ = triangles[i].vertices[1]; @@ -143,10 +141,11 @@ namespace Nz indexMapper.Unmap(); + // Optimize if requested (improves cache locality) if (parameters.optimizeIndexBuffers) indexBuffer->Optimize(); - /// Lecture des coordonnées de texture + // Extracting texture coordinates std::vector texCoords(header.num_st); stream.SetCursorPos(header.offset_st); @@ -168,15 +167,15 @@ namespace Nz return false; } - /// Chargement des vertices + // Extracting vertices stream.SetCursorPos(header.offset_frames); - std::unique_ptr vertices(new MD2_Vertex[header.num_vertices]); + std::vector vertices(header.num_vertices); Vector3f scale, translate; stream.Read(scale, sizeof(Vector3f)); stream.Read(translate, sizeof(Vector3f)); - stream.Read(nullptr, 16*sizeof(char)); // Nom de la frame, inutile ici - stream.Read(vertices.get(), header.num_vertices*sizeof(MD2_Vertex)); + stream.Read(nullptr, 16*sizeof(char)); //< Frame name, unused + stream.Read(vertices.data(), header.num_vertices*sizeof(MD2_Vertex)); #ifdef NAZARA_BIG_ENDIAN SwapBytes(&scale.x, sizeof(float)); @@ -196,23 +195,26 @@ namespace Nz BufferMapper vertexMapper(vertexBuffer, BufferAccess_DiscardAndWrite); MeshVertex* vertex = static_cast(vertexMapper.GetPointer()); - /// Chargement des coordonnées de texture - const unsigned int indexFix[3] = {0, 2, 1}; // Pour respécifier les indices dans le bon ordre + // Loading texture coordinates + const unsigned int indexFix[3] = {0, 2, 1}; + Vector2f invSkinSize(1.f / header.skinwidth, 1.f / header.skinheight); for (unsigned int i = 0; i < header.num_tris; ++i) { for (unsigned int j = 0; j < 3; ++j) { - const unsigned int fixedIndex = indexFix[j]; - const MD2_TexCoord& texC = texCoords[triangles[i].texCoords[fixedIndex]]; - float u = static_cast(texC.u) / header.skinwidth; - float v = static_cast(texC.v) / header.skinheight; + const unsigned int fixedIndex = indexFix[j]; //< Reverse winding order - vertex[triangles[i].vertices[fixedIndex]].uv.Set(u, (parameters.flipUVs) ? 1.f - v : v); + const MD2_TexCoord& texC = texCoords[triangles[i].texCoords[fixedIndex]]; + Vector2f uv(texC.u, texC.v); + uv *= invSkinSize; + + vertex[triangles[i].vertices[fixedIndex]].uv.Set(parameters.texCoordOffset + uv * parameters.texCoordScale); } } - /// Chargement des positions - // Pour que le modèle soit correctement aligné, on génère un quaternion que nous appliquerons à chacune des vertices + // Loading vertex position + + // Align the model to our coordinates system Quaternionf rotationQuat = EulerAnglesf(-90.f, 90.f, 0.f); Nz::Matrix4f matrix = Matrix4f::Transform(translate, rotationQuat, scale); matrix *= parameters.matrix; diff --git a/src/Nazara/Utility/Formats/MD5MeshLoader.cpp b/src/Nazara/Utility/Formats/MD5MeshLoader.cpp index 59988405a..bccf17568 100644 --- a/src/Nazara/Utility/Formats/MD5MeshLoader.cpp +++ b/src/Nazara/Utility/Formats/MD5MeshLoader.cpp @@ -184,7 +184,7 @@ namespace Nz } vertices->position = finalPos; - vertices->uv.Set(vertex.uv.x, (parameters.flipUVs) ? 1.f - vertex.uv.y : vertex.uv.y); // Inversion des UV si demandé + vertices->uv.Set(parameters.texCoordOffset + vertex.uv * parameters.texCoordScale); vertices++; } @@ -254,7 +254,7 @@ namespace Nz VertexBufferRef vertexBuffer = VertexBuffer::New(VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent), vertexCount, parameters.storage); BufferMapper vertexMapper(vertexBuffer, BufferAccess_WriteOnly); - MeshVertex* vertex = static_cast(vertexMapper.GetPointer()); + MeshVertex* vertices = static_cast(vertexMapper.GetPointer()); for (const MD5MeshParser::Vertex& md5Vertex : md5Mesh.vertices) { // Skinning MD5 (Formule d'Id Tech) @@ -268,9 +268,9 @@ namespace Nz } // On retourne le modèle dans le bon sens - vertex->position = matrix * finalPos; - vertex->uv.Set(md5Vertex.uv.x, (parameters.flipUVs) ? 1.f - md5Vertex.uv.y : md5Vertex.uv.y); // Inversion des UV si demandé - vertex++; + vertices->position = matrix * finalPos; + vertices->uv.Set(parameters.texCoordOffset + md5Vertex.uv * parameters.texCoordScale); + vertices++; } vertexMapper.Unmap(); diff --git a/src/Nazara/Utility/Formats/MTLParser.cpp b/src/Nazara/Utility/Formats/MTLParser.cpp index 1bbed892f..c3b60a6e5 100644 --- a/src/Nazara/Utility/Formats/MTLParser.cpp +++ b/src/Nazara/Utility/Formats/MTLParser.cpp @@ -331,19 +331,19 @@ namespace Nz Emit(mat.specular.b / 255.f); EmitLine(); - if (mat.alpha != 1.f) + if (!NumberEquals(mat.alpha, 1.f)) { Emit("d "); EmitLine(mat.alpha); } - if (mat.refractionIndex != 1.f) + if (!NumberEquals(mat.refractionIndex, 1.f)) { Emit("ni "); EmitLine(mat.refractionIndex); } - if (mat.shininess != 1.f) + if (!NumberEquals(mat.shininess, 1.f)) { Emit("ns "); EmitLine(mat.shininess); diff --git a/src/Nazara/Utility/Formats/OBJLoader.cpp b/src/Nazara/Utility/Formats/OBJLoader.cpp index 2a59ba703..d65d3e913 100644 --- a/src/Nazara/Utility/Formats/OBJLoader.cpp +++ b/src/Nazara/Utility/Formats/OBJLoader.cpp @@ -265,8 +265,8 @@ namespace Nz if (vertexIndices.texCoord > 0) { - const Vector3f& uvw = texCoords[vertexIndices.texCoord-1]; - vertex.uv.Set(uvw.x, (parameters.flipUVs) ? 1.f - uvw.y : uvw.y); // Inversion des UVs si demandé + Vector2f uv = Vector2f(texCoords[vertexIndices.texCoord - 1]); + vertex.uv.Set(parameters.texCoordOffset + uv * parameters.texCoordScale); } else hasTexCoords = false; diff --git a/src/Nazara/Utility/Formats/OBJParser.cpp b/src/Nazara/Utility/Formats/OBJParser.cpp index 3b03b7f78..eed0ee2b1 100644 --- a/src/Nazara/Utility/Formats/OBJParser.cpp +++ b/src/Nazara/Utility/Formats/OBJParser.cpp @@ -128,17 +128,17 @@ namespace Nz UInt32 faceReserve = 0; UInt32 vertexReserve = 0; unsigned int matCount = 0; - auto GetMaterial = [&] (const String& meshName, const String& matName) -> Mesh* + auto GetMaterial = [&] (const String& mesh, const String& mat) -> Mesh* { - auto& map = meshesByName[meshName]; - auto it = map.find(matName); + auto& map = meshesByName[mesh]; + auto it = map.find(mat); if (it == map.end()) - it = map.insert(std::make_pair(matName, MatPair(Mesh(), matCount++))).first; + it = map.insert(std::make_pair(mat, MatPair(Mesh(), matCount++))).first; - Mesh& mesh = it->second.first; + Mesh& meshData = it->second.first; - mesh.faces.reserve(faceReserve); - mesh.vertices.reserve(vertexReserve); + meshData.faces.reserve(faceReserve); + meshData.vertices.reserve(vertexReserve); faceReserve = 0; vertexReserve = 0; @@ -550,19 +550,19 @@ namespace Nz EmitLine(pair.second.size()); EmitLine(); - for (std::size_t meshIndex : pair.second) + for (std::size_t index : pair.second) { - const Mesh& mesh = m_meshes[meshIndex]; + const Mesh& mesh = m_meshes[index]; Emit("g "); EmitLine(mesh.name); EmitLine(); - + Emit("# face count: "); EmitLine(mesh.faces.size()); Emit("# vertex count: "); EmitLine(mesh.vertices.size()); - + for (const Face& face : mesh.faces) { Emit('f'); diff --git a/src/Nazara/Utility/Image.cpp b/src/Nazara/Utility/Image.cpp index 160c2ac90..39d99cdd1 100644 --- a/src/Nazara/Utility/Image.cpp +++ b/src/Nazara/Utility/Image.cpp @@ -825,6 +825,44 @@ namespace Nz return GetLevelSize(m_sharedImage->width, level); } + bool Image::HasAlpha() const + { + NazaraAssert(m_sharedImage != &emptyImage, "Image must be valid"); + + if (!PixelFormat::HasAlpha(m_sharedImage->format)) + return false; + + if (!PixelFormat::IsCompressed(m_sharedImage->format)) + { + const PixelFormatInfo& info = PixelFormat::GetInfo(m_sharedImage->format); + const UInt8* pixel = GetConstPixels(); + + Bitset<> workingBitset; + std::size_t pixelCount = m_sharedImage->width * m_sharedImage->height * ((m_sharedImage->type == ImageType_Cubemap) ? 6 : m_sharedImage->depth); + if (pixelCount == 0) + return false; + + auto seq = workingBitset.Read(GetConstPixels(), info.bitsPerPixel); + do + { + workingBitset &= info.alphaMask; + if (workingBitset.Count() != info.alphaMask.Count()) //< Means that at least one bit of the alpha mask of this pixel is disabled + return true; + + workingBitset.Clear(); + workingBitset.Read(seq, info.bitsPerPixel); + } + while (--pixelCount > 0); + + return false; + } + else + { + // FIXME: Currently, we assume the pixel format is already the right one + return true; + } + } + bool Image::IsValid() const { return m_sharedImage != &emptyImage; @@ -1441,7 +1479,7 @@ namespace Nz SharedImage::PixelContainer levels(m_sharedImage->levels.size()); for (unsigned int i = 0; i < levels.size(); ++i) { - unsigned int size = GetMemoryUsage(i); + std::size_t size = GetMemoryUsage(i); levels[i].reset(new UInt8[size]); std::memcpy(levels[i].get(), m_sharedImage->levels[i].get(), size); } diff --git a/src/Nazara/Utility/SimpleTextDrawer.cpp b/src/Nazara/Utility/SimpleTextDrawer.cpp index b34e141dc..ae194534a 100644 --- a/src/Nazara/Utility/SimpleTextDrawer.cpp +++ b/src/Nazara/Utility/SimpleTextDrawer.cpp @@ -75,6 +75,7 @@ namespace Nz Font* SimpleTextDrawer::GetFont(std::size_t index) const { NazaraAssert(index == 0, "Font index out of range"); + NazaraUnused(index); return m_font; } diff --git a/src/Nazara/Utility/SoftwareBuffer.cpp b/src/Nazara/Utility/SoftwareBuffer.cpp index 081f0fda3..040017c1e 100644 --- a/src/Nazara/Utility/SoftwareBuffer.cpp +++ b/src/Nazara/Utility/SoftwareBuffer.cpp @@ -11,7 +11,7 @@ namespace Nz { - SoftwareBuffer::SoftwareBuffer(Buffer* /*parent*/, BufferType type) + SoftwareBuffer::SoftwareBuffer(Buffer* /*parent*/, BufferType /*type*/) { } diff --git a/src/Nazara/Utility/VertexBuffer.cpp b/src/Nazara/Utility/VertexBuffer.cpp index 0bc890340..b196d723a 100644 --- a/src/Nazara/Utility/VertexBuffer.cpp +++ b/src/Nazara/Utility/VertexBuffer.cpp @@ -45,7 +45,7 @@ namespace Nz bool VertexBuffer::Fill(const void* data, unsigned int startVertex, unsigned int length, bool forceDiscard) { - unsigned int stride = m_vertexDeclaration->GetStride(); + std::size_t stride = m_vertexDeclaration->GetStride(); return FillRaw(data, startVertex*stride, length*stride, forceDiscard); } diff --git a/src/Nazara/Utility/VideoMode.cpp b/src/Nazara/Utility/VideoMode.cpp index 6313ff460..2c6a2f321 100644 --- a/src/Nazara/Utility/VideoMode.cpp +++ b/src/Nazara/Utility/VideoMode.cpp @@ -24,6 +24,11 @@ namespace Nz width(0) { } + + VideoMode::VideoMode(unsigned int w, unsigned int h) : + VideoMode(w, h, GetDesktopMode().bitsPerPixel) + { + } VideoMode::VideoMode(unsigned int w, unsigned int h, UInt8 bpp) : bitsPerPixel(bpp), diff --git a/src/Nazara/Utility/Win32/WindowImpl.cpp b/src/Nazara/Utility/Win32/WindowImpl.cpp index b494a7789..e32caf95f 100644 --- a/src/Nazara/Utility/Win32/WindowImpl.cpp +++ b/src/Nazara/Utility/Win32/WindowImpl.cpp @@ -81,8 +81,9 @@ namespace Nz { } - bool WindowImpl::Create(const VideoMode& mode, const String& title, UInt32 style) + bool WindowImpl::Create(const VideoMode& mode, const String& title, WindowStyleFlags style) { + bool async = (style & WindowStyle_Threaded) != 0; bool fullscreen = (style & WindowStyle_Fullscreen) != 0; DWORD win32Style, win32StyleEx; unsigned int x, y; @@ -147,19 +148,25 @@ namespace Nz m_callback = 0; - #if NAZARA_UTILITY_THREADED_WINDOW - Mutex mutex; - ConditionVariable condition; - m_threadActive = true; + m_eventListener = true; + m_ownsWindow = true; + m_sizemove = false; + m_style = style; - // On attend que la fenêtre soit créée - mutex.Lock(); - m_thread = Thread(WindowThread, &m_handle, win32StyleEx, title.GetWideString().data(), win32Style, x, y, width, height, this, &mutex, &condition); - condition.Wait(&mutex); - mutex.Unlock(); - #else - m_handle = CreateWindowExW(win32StyleEx, className, title.GetWideString().data(), win32Style, x, y, width, height, nullptr, nullptr, GetModuleHandle(nullptr), this); - #endif + if (async) + { + Mutex mutex; + ConditionVariable condition; + m_threadActive = true; + + // On attend que la fenêtre soit créée + mutex.Lock(); + m_thread = Thread(WindowThread, &m_handle, win32StyleEx, title, win32Style, fullscreen, Rectui(x, y, width, height), this, &mutex, &condition); + condition.Wait(&mutex); + mutex.Unlock(); + } + else + m_handle = CreateWindowExW(win32StyleEx, className, title.GetWideString().data(), win32Style, x, y, width, height, nullptr, nullptr, GetModuleHandle(nullptr), this); if (!m_handle) { @@ -167,26 +174,8 @@ namespace Nz return false; } - if (fullscreen) - { - SetForegroundWindow(m_handle); - ShowWindow(m_handle, SW_SHOW); - } - - m_eventListener = true; - m_ownsWindow = true; - #if !NAZARA_UTILITY_THREADED_WINDOW - m_sizemove = false; - #endif - m_style = style; - - // Récupération de la position/taille de la fenêtre (Après sa création) - RECT clientRect, windowRect; - GetClientRect(m_handle, &clientRect); - GetWindowRect(m_handle, &windowRect); - - m_position.Set(windowRect.left, windowRect.top); - m_size.Set(clientRect.right - clientRect.left, clientRect.bottom - clientRect.top); + if (!async) + PrepareWindow(fullscreen); return true; } @@ -203,9 +192,7 @@ namespace Nz m_eventListener = false; m_ownsWindow = false; - #if !NAZARA_UTILITY_THREADED_WINDOW m_sizemove = false; - #endif m_style = RetrieveStyle(m_handle); RECT clientRect, windowRect; @@ -222,18 +209,21 @@ namespace Nz { if (m_ownsWindow) { - #if NAZARA_UTILITY_THREADED_WINDOW - if (m_thread.IsJoinable()) + if (m_style & WindowStyle_Threaded) { - m_threadActive = false; - PostMessageW(m_handle, WM_NULL, 0, 0); // Pour réveiller le thread + if (m_thread.IsJoinable()) + { + m_threadActive = false; + PostMessageW(m_handle, WM_NULL, 0, 0); // Wake up our thread - m_thread.Join(); + m_thread.Join(); + } + } + else + { + if (m_handle) + DestroyWindow(m_handle); } - #else - if (m_handle) - DestroyWindow(m_handle); - #endif } else SetEventListener(false); @@ -269,7 +259,7 @@ namespace Nz return m_size; } - UInt32 WindowImpl::GetStyle() const + WindowStyleFlags WindowImpl::GetStyle() const { return m_style; } @@ -280,7 +270,7 @@ namespace Nz if (titleSize == 0) return String(); - titleSize++; // Caractère nul + titleSize++; // \0 std::unique_ptr wTitle(new wchar_t[titleSize]); GetWindowTextW(m_handle, wTitle.get(), titleSize); @@ -525,7 +515,6 @@ namespace Nz return true; // Afin que Windows ne ferme pas la fenêtre automatiquement } - #if !NAZARA_UTILITY_THREADED_WINDOW case WM_ENTERSIZEMOVE: { m_sizemove = true; @@ -536,6 +525,10 @@ namespace Nz { m_sizemove = false; + // In case of threaded window, size and move events are not blocked + if (m_style & WindowStyle_Threaded) + break; + // On vérifie ce qui a changé RECT clientRect, windowRect; GetClientRect(m_handle, &clientRect); @@ -565,7 +558,6 @@ namespace Nz m_parent->PushEvent(event); } } - #endif case WM_KEYDOWN: case WM_SYSKEYDOWN: @@ -789,15 +781,23 @@ namespace Nz case WM_MOVE: { + if (m_sizemove && (m_style & WindowStyle_Threaded) == 0) + break; + RECT windowRect; GetWindowRect(m_handle, &windowRect); - WindowEvent event; - event.type = WindowEventType_Moved; - event.position.x = windowRect.left; - event.position.y = windowRect.top; - m_parent->PushEvent(event); + Vector2i position(windowRect.left, windowRect.top); + if (m_position != position) + { + m_position = position; + WindowEvent event; + event.type = WindowEventType_Moved; + event.position.x = position.x; + event.position.y = position.y; + m_parent->PushEvent(event); + } break; } @@ -852,27 +852,26 @@ namespace Nz case WM_SIZE: { - #if NAZARA_UTILITY_THREADED_WINDOW - if (wParam != SIZE_MINIMIZED) - #else - if (!m_sizemove && wParam != SIZE_MINIMIZED) - #endif - { - RECT rect; - GetClientRect(m_handle, &rect); + if (m_sizemove && (m_style & WindowStyle_Threaded) == 0) + break; - Vector2ui size(rect.right-rect.left, rect.bottom-rect.top); // On récupère uniquement la taille de la zone client - if (m_size == size) - break; + if (wParam == SIZE_MINIMIZED) + break; - m_size = size; + RECT rect; + GetClientRect(m_handle, &rect); - WindowEvent event; - event.type = WindowEventType_Resized; - event.size.width = size.x; - event.size.height = size.y; - m_parent->PushEvent(event); - } + Vector2ui size(rect.right-rect.left, rect.bottom-rect.top); // On récupère uniquement la taille de la zone client + if (m_size == size) + break; + + m_size = size; + + WindowEvent event; + event.type = WindowEventType_Resized; + event.size.width = size.x; + event.size.height = size.y; + m_parent->PushEvent(event); break; } @@ -963,6 +962,23 @@ namespace Nz return false; } + void WindowImpl::PrepareWindow(bool fullscreen) + { + if (fullscreen) + { + SetForegroundWindow(m_handle); + ShowWindow(m_handle, SW_SHOW); + } + + // Cache window position/size after creation + RECT clientRect, windowRect; + GetClientRect(m_handle, &clientRect); + GetWindowRect(m_handle, &windowRect); + + m_position.Set(windowRect.left, windowRect.top); + m_size.Set(clientRect.right - clientRect.left, clientRect.bottom - clientRect.top); + } + bool WindowImpl::Initialize() { // Nous devons faire un type Unicode pour que la fenêtre le soit également @@ -1177,15 +1193,17 @@ namespace Nz return style; } - #if NAZARA_UTILITY_THREADED_WINDOW - void WindowImpl::WindowThread(HWND* handle, DWORD styleEx, const wchar_t* title, DWORD style, unsigned int x, unsigned int y, unsigned int width, unsigned int height, WindowImpl* window, Mutex* mutex, ConditionVariable* condition) + void WindowImpl::WindowThread(HWND* handle, DWORD styleEx, const String& title, DWORD style, bool fullscreen, const Rectui& dimensions, WindowImpl* window, Mutex* mutex, ConditionVariable* condition) { HWND& winHandle = *handle; - winHandle = CreateWindowExW(styleEx, className, title, style, x, y, width, height, nullptr, nullptr, GetModuleHandle(nullptr), window); + winHandle = CreateWindowExW(styleEx, className, title.GetWideString().data(), style, dimensions.x, dimensions.y, dimensions.width, dimensions.height, nullptr, nullptr, GetModuleHandle(nullptr), window); + + if (winHandle) + window->PrepareWindow(fullscreen); mutex->Lock(); condition->Signal(); - mutex->Unlock(); // mutex et condition sont considérés invalides à partir d'ici + mutex->Unlock(); // mutex and condition may be destroyed after this line if (!winHandle) return; @@ -1195,5 +1213,4 @@ namespace Nz DestroyWindow(winHandle); } -#endif } diff --git a/src/Nazara/Utility/Win32/WindowImpl.hpp b/src/Nazara/Utility/Win32/WindowImpl.hpp index b0fcf8ae0..ae08e42ad 100644 --- a/src/Nazara/Utility/Win32/WindowImpl.hpp +++ b/src/Nazara/Utility/Win32/WindowImpl.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -22,10 +23,8 @@ namespace Nz { - #if NAZARA_UTILITY_THREADED_WINDOW class ConditionVariable; class Mutex; - #endif class Window; #undef IsMinimized // Conflit avec la méthode du même nom @@ -38,7 +37,7 @@ namespace Nz WindowImpl(WindowImpl&&) = delete; ///TODO? ~WindowImpl() = default; - bool Create(const VideoMode& mode, const String& title, UInt32 style); + bool Create(const VideoMode& mode, const String& title, WindowStyleFlags style); bool Create(WindowHandle handle); void Destroy(); @@ -50,7 +49,7 @@ namespace Nz unsigned int GetHeight() const; Vector2i GetPosition() const; Vector2ui GetSize() const; - UInt32 GetStyle() const; + WindowStyleFlags GetStyle() const; String GetTitle() const; unsigned int GetWidth() const; @@ -84,38 +83,31 @@ namespace Nz private: bool HandleMessage(HWND window, UINT message, WPARAM wParam, LPARAM lParam); + void PrepareWindow(bool fullscreen); static Keyboard::Key ConvertVirtualKey(WPARAM key, LPARAM flags); static LRESULT CALLBACK MessageHandler(HWND window, UINT message, WPARAM wParam, LPARAM lParam); static UInt32 RetrieveStyle(HWND window); - #if NAZARA_UTILITY_THREADED_WINDOW - static void WindowThread(HWND* handle, DWORD styleEx, const wchar_t* title, DWORD style, unsigned int x, unsigned int y, unsigned int width, unsigned int height, WindowImpl* window, Mutex* mutex, ConditionVariable* condition); - #endif + static void WindowThread(HWND* handle, DWORD styleEx, const String& title, DWORD style, bool fullscreen, const Rectui& dimensions, WindowImpl* window, Mutex* mutex, ConditionVariable* condition); HCURSOR m_cursor; HWND m_handle; LONG_PTR m_callback; - UInt32 m_style; + WindowStyleFlags m_style; Vector2i m_maxSize; Vector2i m_minSize; Vector2i m_mousePos; Vector2i m_position; Vector2ui m_size; - #if NAZARA_UTILITY_THREADED_WINDOW Thread m_thread; - #endif Window* m_parent; bool m_eventListener; bool m_keyRepeat; bool m_mouseInside; bool m_ownsWindow; - #if !NAZARA_UTILITY_THREADED_WINDOW bool m_sizemove; - #endif bool m_smoothScrolling; - #if NAZARA_UTILITY_THREADED_WINDOW bool m_threadActive; - #endif short m_scrolling; }; } diff --git a/src/Nazara/Utility/Window.cpp b/src/Nazara/Utility/Window.cpp index 078ff2bc5..73c91168a 100644 --- a/src/Nazara/Utility/Window.cpp +++ b/src/Nazara/Utility/Window.cpp @@ -34,7 +34,7 @@ namespace Nz Destroy(); } - bool Window::Create(VideoMode mode, const String& title, UInt32 style) + bool Window::Create(VideoMode mode, const String& title, WindowStyleFlags style) { // Si la fenêtre est déjà ouverte, nous conservons sa position bool opened = IsOpen(); @@ -66,6 +66,8 @@ namespace Nz else if (style & WindowStyle_Closable || style & WindowStyle_Resizable) style |= WindowStyle_Titlebar; + m_asyncWindow = (style & WindowStyle_Threaded) != 0; + std::unique_ptr impl = std::make_unique(this); if (!impl->Create(mode, title, style)) { @@ -107,6 +109,7 @@ namespace Nz { Destroy(); + m_asyncWindow = false; m_impl = new WindowImpl(this); if (!m_impl->Create(handle)) { @@ -225,7 +228,7 @@ namespace Nz return m_impl->GetSize(); } - UInt32 Window::GetStyle() const + WindowStyleFlags Window::GetStyle() const { #if NAZARA_UTILITY_SAFE if (!m_impl) @@ -313,11 +316,8 @@ namespace Nz } #endif - #if NAZARA_UTILITY_THREADED_WINDOW - LockGuard lock(m_eventMutex); - #else - m_impl->ProcessEvents(false); - #endif + if (!m_asyncWindow) + m_impl->ProcessEvents(false); if (!m_events.empty()) { @@ -335,10 +335,19 @@ namespace Nz void Window::ProcessEvents(bool block) { NazaraAssert(m_impl, "Window not created"); + NazaraUnused(block); - #if !NAZARA_UTILITY_THREADED_WINDOW - m_impl->ProcessEvents(block); - #endif + if (!m_asyncWindow) + m_impl->ProcessEvents(block); + else + { + LockGuard eventLock(m_eventMutex); + + for (const WindowEvent& event : m_pendingEvents) + HandleEvent(event); + + m_pendingEvents.clear(); + } } void Window::SetCursor(WindowCursor cursor) @@ -383,25 +392,13 @@ namespace Nz } #endif - #if NAZARA_UTILITY_THREADED_WINDOW m_impl->SetEventListener(listener); if (!listener) { - // On vide la pile des évènements - LockGuard lock(m_eventMutex); + // Empty the event queue while (!m_events.empty()) m_events.pop(); } - #else - if (m_ownsWindow) - { - // Inutile de transmettre l'ordre dans ce cas-là - if (!listener) - NazaraError("A non-threaded window needs to listen to events"); - } - else - m_impl->SetEventListener(listener); - #endif } void Window::SetFocus() @@ -589,22 +586,11 @@ namespace Nz } #endif - #if NAZARA_UTILITY_THREADED_WINDOW - LockGuard lock(m_eventMutex); - - if (m_events.empty()) + if (!m_asyncWindow) { - m_waitForEvent = true; - m_eventConditionMutex.Lock(); - m_eventMutex.Unlock(); - m_eventCondition.Wait(&m_eventConditionMutex); - m_eventMutex.Lock(); - m_eventConditionMutex.Unlock(); - m_waitForEvent = false; - } + while (m_events.empty()) + m_impl->ProcessEvents(true); - if (!m_events.empty()) - { if (event) *event = m_events.front(); @@ -612,19 +598,33 @@ namespace Nz return true; } + else + { + LockGuard lock(m_eventMutex); - return false; - #else - while (m_events.empty()) - m_impl->ProcessEvents(true); + if (m_events.empty()) + { + m_waitForEvent = true; + m_eventConditionMutex.Lock(); + m_eventMutex.Unlock(); + m_eventCondition.Wait(&m_eventConditionMutex); + m_eventMutex.Lock(); + m_eventConditionMutex.Unlock(); + m_waitForEvent = false; + } - if (event) - *event = m_events.front(); + if (!m_events.empty()) + { + if (event) + *event = m_events.front(); - m_events.pop(); + m_events.pop(); - return true; - #endif + return true; + } + + return false; + } } bool Window::OnWindowCreated() diff --git a/src/Nazara/Utility/X11/InputImpl.cpp b/src/Nazara/Utility/X11/InputImpl.cpp index e21fdae96..7083100db 100644 --- a/src/Nazara/Utility/X11/InputImpl.cpp +++ b/src/Nazara/Utility/X11/InputImpl.cpp @@ -23,32 +23,32 @@ namespace Nz switch (key) { // Lettres - case Keyboard::A: keysym = XK_A; break; - case Keyboard::B: keysym = XK_B; break; - case Keyboard::C: keysym = XK_C; break; - case Keyboard::D: keysym = XK_D; break; - case Keyboard::E: keysym = XK_E; break; - case Keyboard::F: keysym = XK_F; break; - case Keyboard::G: keysym = XK_G; break; - case Keyboard::H: keysym = XK_H; break; - case Keyboard::I: keysym = XK_I; break; - case Keyboard::J: keysym = XK_J; break; - case Keyboard::K: keysym = XK_K; break; - case Keyboard::L: keysym = XK_L; break; - case Keyboard::M: keysym = XK_M; break; - case Keyboard::N: keysym = XK_N; break; - case Keyboard::O: keysym = XK_O; break; - case Keyboard::P: keysym = XK_P; break; - case Keyboard::Q: keysym = XK_Q; break; - case Keyboard::R: keysym = XK_R; break; - case Keyboard::S: keysym = XK_S; break; - case Keyboard::T: keysym = XK_T; break; - case Keyboard::U: keysym = XK_U; break; - case Keyboard::V: keysym = XK_V; break; - case Keyboard::W: keysym = XK_W; break; - case Keyboard::X: keysym = XK_X; break; - case Keyboard::Y: keysym = XK_Y; break; - case Keyboard::Z: keysym = XK_Z; break; + case Keyboard::A: keysym = XK_a; break; + case Keyboard::B: keysym = XK_b; break; + case Keyboard::C: keysym = XK_c; break; + case Keyboard::D: keysym = XK_d; break; + case Keyboard::E: keysym = XK_e; break; + case Keyboard::F: keysym = XK_f; break; + case Keyboard::G: keysym = XK_g; break; + case Keyboard::H: keysym = XK_h; break; + case Keyboard::I: keysym = XK_i; break; + case Keyboard::J: keysym = XK_j; break; + case Keyboard::K: keysym = XK_k; break; + case Keyboard::L: keysym = XK_l; break; + case Keyboard::M: keysym = XK_m; break; + case Keyboard::N: keysym = XK_n; break; + case Keyboard::O: keysym = XK_o; break; + case Keyboard::P: keysym = XK_p; break; + case Keyboard::Q: keysym = XK_q; break; + case Keyboard::R: keysym = XK_r; break; + case Keyboard::S: keysym = XK_s; break; + case Keyboard::T: keysym = XK_t; break; + case Keyboard::U: keysym = XK_u; break; + case Keyboard::V: keysym = XK_v; break; + case Keyboard::W: keysym = XK_w; break; + case Keyboard::X: keysym = XK_x; break; + case Keyboard::Y: keysym = XK_y; break; + case Keyboard::Z: keysym = XK_z; break; // Touches de fonction case Keyboard::F1: keysym = XK_F1; break; @@ -248,6 +248,8 @@ namespace Nz xcb_keysym_t keySym = GetKeySym(key); + xcb_keycode_t realKeyCode = XCB_NO_SYMBOL; + xcb_key_symbols_t* keySymbols = X11::XCBKeySymbolsAlloc(connection); if (!keySymbols) { @@ -261,6 +263,20 @@ namespace Nz NazaraError("Failed to get key code"); return false; } + + // One keysym is associated with multiple key codes, we have to find the matching one ... + int i = 0; + while (keyCode.get()[i] != XCB_NO_SYMBOL) + { + xcb_keycode_t toTry = keyCode.get()[i]; + if (keySym == xcb_key_symbols_get_keysym(keySymbols, toTry, 0)) + { + realKeyCode = toTry; + break; + } + ++i; + } + X11::XCBKeySymbolsFree(keySymbols); ScopedXCB error(nullptr); @@ -281,7 +297,7 @@ namespace Nz } // Check our keycode - return (keymap->keys[*keyCode.get() / 8] & (1 << (*keyCode.get() % 8))) != 0; + return (keymap->keys[realKeyCode / 8] & (1 << (realKeyCode % 8))) != 0; } bool EventImpl::IsMouseButtonPressed(Mouse::Button button) diff --git a/src/Nazara/Utility/X11/WindowImpl.cpp b/src/Nazara/Utility/X11/WindowImpl.cpp index 72b85912a..700b8c6ee 100644 --- a/src/Nazara/Utility/X11/WindowImpl.cpp +++ b/src/Nazara/Utility/X11/WindowImpl.cpp @@ -113,7 +113,7 @@ namespace Nz UpdateEventQueue(nullptr); } - bool WindowImpl::Create(const VideoMode& mode, const String& title, UInt32 style) + bool WindowImpl::Create(const VideoMode& mode, const String& title, WindowStyleFlags style) { bool fullscreen = (style & Nz::WindowStyle_Fullscreen) != 0; m_eventListener = true; @@ -203,17 +203,18 @@ namespace Nz // Set the window's name SetTitle(title); - #if NAZARA_UTILITY_THREADED_WINDOW - Mutex mutex; - ConditionVariable condition; - m_threadActive = true; + if (m_style & WindowStyle_Threaded) + { + Mutex mutex; + ConditionVariable condition; + m_threadActive = true; - // We wait that thread is well launched - mutex.Lock(); - m_thread = Thread(WindowThread, this, &mutex, &condition); - condition.Wait(&mutex); - mutex.Unlock(); - #endif + // Wait until the thread is ready + mutex.Lock(); + m_thread = Thread(WindowThread, this, &mutex, &condition); + condition.Wait(&mutex); + mutex.Unlock(); + } // Set fullscreen video mode and switch to fullscreen if necessary if (fullscreen) @@ -275,13 +276,15 @@ namespace Nz { if (m_ownsWindow) { - #if NAZARA_UTILITY_THREADED_WINDOW - if (m_thread.IsJoinable()) + if (m_style & WindowStyle_Threaded) { - m_threadActive = false; - m_thread.Join(); + if (m_thread.IsJoinable()) + { + m_threadActive = false; + m_thread.Join(); + } } - #else + // Destroy the window if (m_window && m_ownsWindow) { @@ -293,13 +296,11 @@ namespace Nz xcb_destroy_window( connection, m_window - )) - ) + ))) NazaraError("Failed to destroy window"); xcb_flush(connection); } - #endif } else SetEventListener(false); @@ -335,7 +336,7 @@ namespace Nz return Vector2ui(m_size_hints.width, m_size_hints.height); } - UInt32 WindowImpl::GetStyle() const + WindowStyleFlags WindowImpl::GetStyle() const { return m_style; } @@ -1247,7 +1248,7 @@ namespace Nz char32_t codePoint = GetRepresentation(keysym); - // WTF if (std::isprint(codePoint, std::locale(""))) + handle combining ? + // if (std::isprint(codePoint)) Is not working ? + handle combining ? { WindowEvent event; event.type = Nz::WindowEventType_TextEntered; @@ -1405,7 +1406,7 @@ namespace Nz // Catch reparent events to properly apply fullscreen on // some "strange" window managers (like Awesome) which // seem to make use of temporary parents during mapping - if (m_style & Nz::WindowStyle_Fullscreen) + if (m_style & WindowStyle_Fullscreen) SwitchToFullscreen(); break; @@ -1685,12 +1686,11 @@ namespace Nz )); } - #if NAZARA_UTILITY_THREADED_WINDOW void WindowImpl::WindowThread(WindowImpl* window, Mutex* mutex, ConditionVariable* condition) { mutex->Lock(); condition->Signal(); - mutex->Unlock(); // mutex et condition sont considérés invalides à partir d'ici + mutex->Unlock(); // mutex and condition may be destroyed after this line if (!window->m_window) return; @@ -1700,5 +1700,4 @@ namespace Nz window->Destroy(); } - #endif } diff --git a/src/Nazara/Utility/X11/WindowImpl.hpp b/src/Nazara/Utility/X11/WindowImpl.hpp index 6096dcac2..414140179 100644 --- a/src/Nazara/Utility/X11/WindowImpl.hpp +++ b/src/Nazara/Utility/X11/WindowImpl.hpp @@ -20,10 +20,8 @@ namespace Nz { - #if NAZARA_UTILITY_THREADED_WINDOW class ConditionVariable; class Mutex; - #endif class Cursor; class Icon; class VideoMode; @@ -37,7 +35,7 @@ namespace Nz WindowImpl(WindowImpl&&) = delete; ///TODO? ~WindowImpl(); - bool Create(const VideoMode& mode, const String& title, UInt32 style); + bool Create(const VideoMode& mode, const String& title, WindowStyleFlags style); bool Create(WindowHandle handle); void Destroy(); @@ -49,7 +47,7 @@ namespace Nz unsigned int GetHeight() const; Vector2i GetPosition() const; Vector2ui GetSize() const; - UInt32 GetStyle() const; + WindowStyleFlags GetStyle() const; String GetTitle() const; unsigned int GetWidth() const; @@ -103,25 +101,19 @@ namespace Nz bool UpdateNormalHints(); void UpdateEventQueue(xcb_generic_event_t* event); - #if NAZARA_UTILITY_THREADED_WINDOW static void WindowThread(WindowImpl* window, Mutex* mutex, ConditionVariable* condition); - #endif xcb_window_t m_window; xcb_screen_t* m_screen; xcb_randr_get_screen_info_reply_t m_oldVideoMode; xcb_size_hints_t m_size_hints; - UInt32 m_style; - #if NAZARA_UTILITY_THREADED_WINDOW Thread m_thread; - #endif + WindowStyleFlags m_style; Window* m_parent; bool m_eventListener; bool m_ownsWindow; bool m_smoothScrolling; - #if NAZARA_UTILITY_THREADED_WINDOW bool m_threadActive; - #endif short m_scrolling; Vector2i m_mousePos; bool m_keyRepeat; diff --git a/tests/Engine/Core/Bitset.cpp b/tests/Engine/Core/Bitset.cpp index 124556170..b06a38aa8 100644 --- a/tests/Engine/Core/Bitset.cpp +++ b/tests/Engine/Core/Bitset.cpp @@ -1,116 +1,308 @@ +#include #include #include - +#include #include +#include + +template void Check(const char* title); +template void CheckAppend(const char* title); +template void CheckBitOps(const char* title); +template void CheckConstructor(const char* title); +template void CheckCopyMoveSwap(const char* title); +template void CheckRead(const char* title); +template void CheckReverse(const char* title); SCENARIO("Bitset", "[CORE][BITSET]") { - GIVEN("Allocate and constructor") + Check("Bitset made of 8bits blocks"); + Check("Bitset made of 16bits blocks"); + Check("Bitset made of 32bits blocks"); + Check("Bitset made of 64bits blocks"); +} + +template +void Check(const char* title) +{ + CheckConstructor(title); + CheckCopyMoveSwap(title); + + CheckBitOps(title); + + CheckAppend(title); + CheckRead(title); + CheckReverse(title); +} + +template +void CheckAppend(const char* title) +{ + SECTION(title) { - Nz::Bitset<> bitset(3, false); - - THEN("Capacity is 3 and size is 3") + GIVEN("An empty bitset filled by bytes") { - CHECK(bitset.GetSize() == 3); - CHECK(bitset.GetCapacity() >= 3); - } - } + #define BitVal1 00110111 + #define BitVal2 11011110 + #define BitVal3 01000010 + std::array data = {{NazaraPrefixMacro(BitVal1, 0b), NazaraPrefixMacro(BitVal2, 0b), NazaraPrefixMacro(BitVal3, 0b)}}; + const char result[] = NazaraStringifyMacro(BitVal3) NazaraStringifyMacro(BitVal2) NazaraStringifyMacro(BitVal1); + std::size_t resultLength = Nz::CountOf(result) - 1; + std::size_t bitCount = data.size() * 8; + #undef BitVal1 + #undef BitVal2 + #undef BitVal3 - GIVEN("Iterator and default constructor") - { - Nz::String anotherDataString("0101"); - Nz::Bitset<> defaultByte; - Nz::Bitset<> anotherData(anotherDataString.GetConstBuffer()); - - WHEN("We assign 'anotherData'") - { - defaultByte = anotherDataString; - CHECK(anotherData == defaultByte); - CHECK(defaultByte.GetSize() == 4); - CHECK(defaultByte.GetCapacity() >= 4); - CHECK(anotherData.GetSize() == 4); - CHECK(anotherData.GetCapacity() >= 4); - } - } - - GIVEN("Copy and Move constructor") - { - Nz::Bitset<> originalArray(3, true); - - WHEN("We copy") - { - Nz::Bitset<> copyBitset(originalArray); - - THEN("We get a copy") - { - CHECK(copyBitset == originalArray); - - AND_WHEN("We modify one") + std::array, 7> tests = { { - for (std::size_t i = 0; i < copyBitset.GetSize(); ++i) - copyBitset[i] = false; - - THEN("They are no more equal") - { - CHECK(copyBitset != originalArray); - CHECK(copyBitset == Nz::Bitset<>(3, false)); - } + {"We append bits one by one", 1}, + {"We append bits two by two", 2}, + {"We append bits three by three", 3}, + {"We append bits four by four", 4}, + {"We append bits six by six", 6}, + {"We append bits byte by byte", 8}, + {"We append bits twelve by twelve", 12} } - } - } + }; - WHEN("We move") - { - Nz::Bitset<> moveBitset(std::move(originalArray)); - - THEN("These results are expected") + for (auto& pair : tests) { - REQUIRE(moveBitset == Nz::Bitset<>(3, true)); - REQUIRE(originalArray.GetCapacity() == 0); - } - } - } + WHEN(pair.first) + { + Nz::Bitset bitset; - GIVEN("Three bitsets") - { - Nz::Bitset<> first("01001"); - Nz::Bitset<> second("10110"); - Nz::Bitset<> third; + for (std::size_t i = 0; i < bitCount; i += pair.second) + { + Nz::UInt16 value = data[i / 8] >> (i % 8); + if ((i % 8) + pair.second > 8 && i/8 != data.size()-1) + value |= static_cast(data[i / 8 + 1]) << (8 - (i % 8)); - WHEN("We swap first and third, then second and third and finally third and first") - { - Nz::Bitset<> oldFirst(first); - Nz::Bitset<> oldSecond(second); + bitset.AppendBits(value, pair.second); + } - first.Swap(third); - std::swap(second, third); - third.Swap(first); + REQUIRE(bitset.GetSize() == bitCount); - THEN("First and second have been swapped and third is still empty.") - { - REQUIRE(oldFirst == second); - REQUIRE(oldSecond == first); - REQUIRE(third.GetSize() == 0); - } - } - } + Nz::Bitset expectedBitset(result); - GIVEN("Two bitsets") - { - Nz::Bitset<> first("01001"); - Nz::Bitset<> second("10111"); - - WHEN("We perform operators") - { - Nz::Bitset<> andBitset = first & second; - Nz::Bitset<> orBitset = first | second; - Nz::Bitset<> xorBitset = first ^ second; - - THEN("They should operate as logical operators") - { - REQUIRE(andBitset == Nz::Bitset<>("00001")); - REQUIRE(orBitset == Nz::Bitset<>("11111")); - REQUIRE(xorBitset == Nz::Bitset<>("11110")); + CHECK(bitset == expectedBitset); + CHECK(bitset.GetBlockCount() == (bitCount / bitset.bitsPerBlock + std::min(1, bitCount % bitset.bitsPerBlock))); + } + } + } + } +} + +template +void CheckBitOps(const char* title) +{ + SECTION(title) + { + GIVEN("Two bitsets") + { + Nz::Bitset first("01001"); + Nz::Bitset second("10111"); + + WHEN("We perform operators") + { + Nz::Bitset andBitset = first & second; + Nz::Bitset orBitset = first | second; + Nz::Bitset xorBitset = first ^ second; + + THEN("They should operate as logical operators") + { + CHECK(andBitset == Nz::Bitset("00001")); + CHECK(orBitset == Nz::Bitset("11111")); + CHECK(xorBitset == Nz::Bitset("11110")); + } + } + } + } +} + +template +void CheckConstructor(const char* title) +{ + SECTION(title) + { + GIVEN("Allocate and constructor") + { + Nz::Bitset bitset(3, false); + + THEN("Capacity is 3 and size is 3") + { + CHECK(bitset.GetSize() == 3); + CHECK(bitset.GetCapacity() >= 3); + } + } + + GIVEN("Iterator and default constructor") + { + Nz::String anotherDataString("0101"); + Nz::Bitset defaultByte; + Nz::Bitset anotherData(anotherDataString.GetConstBuffer()); + + WHEN("We assign 'anotherData'") + { + defaultByte = anotherDataString; + CHECK(anotherData == defaultByte); + CHECK(defaultByte.GetSize() == 4); + CHECK(defaultByte.GetCapacity() >= 4); + CHECK(anotherData.GetSize() == 4); + CHECK(anotherData.GetCapacity() >= 4); + } + } + } +} + +template +void CheckCopyMoveSwap(const char* title) +{ + SECTION(title) + { + GIVEN("Copy and Move constructor") + { + Nz::Bitset originalArray(3, true); + + WHEN("We copy") + { + Nz::Bitset copyBitset(originalArray); + + THEN("We get a copy") + { + CHECK(copyBitset == originalArray); + + AND_WHEN("We modify one") + { + for (std::size_t i = 0; i < copyBitset.GetSize(); ++i) + copyBitset[i] = false; + + THEN("They are no more equal") + { + CHECK(copyBitset != originalArray); + CHECK(copyBitset == Nz::Bitset(3, false)); + } + } + } + } + + WHEN("We move") + { + Nz::Bitset moveBitset(std::move(originalArray)); + + THEN("These results are expected") + { + CHECK(moveBitset == Nz::Bitset(3, true)); + CHECK(originalArray.GetCapacity() == 0); + } + } + } + + GIVEN("Three bitsets") + { + Nz::Bitset first("01001"); + Nz::Bitset second("10110"); + Nz::Bitset third; + + WHEN("We swap first and third, then second and third and finally third and first") + { + Nz::Bitset oldFirst(first); + Nz::Bitset oldSecond(second); + + first.Swap(third); + std::swap(second, third); + third.Swap(first); + + THEN("First and second have been swapped and third is still empty.") + { + CHECK(oldFirst == second); + CHECK(oldSecond == first); + CHECK(third.GetSize() == 0); + } + } + } + } +} + +template +void CheckRead(const char* title) +{ + SECTION(title) + { + GIVEN("An empty bitset filled by reading") + { + #define BitVal1 10010101 + #define BitVal2 11010010 + #define BitVal3 01101010 + std::array data = {{NazaraPrefixMacro(BitVal1, 0b), NazaraPrefixMacro(BitVal2, 0b), NazaraPrefixMacro(BitVal3, 0b)}}; + const char result[] = NazaraStringifyMacro(BitVal3) NazaraStringifyMacro(BitVal2) NazaraStringifyMacro(BitVal1); + std::size_t resultLength = Nz::CountOf(result) - 1; + std::size_t bitCount = data.size() * 8; + #undef BitVal1 + #undef BitVal2 + #undef BitVal3 + + std::array, 8> tests = { + { + {"We read bits one by one", 1}, + {"We read bits two by two", 2}, + {"We read bits three by three", 3}, + {"We read bits four by four", 4}, + {"We read bits six by six", 6}, + {"We read bits byte by byte", 8}, + {"We read bits twelve by twelve", 12}, + {"We read bits all at once", 24} + } + }; + + for (auto& pair : tests) + { + WHEN(pair.first) + { + Nz::Bitset bitset; + + auto seq = bitset.Read(data.data(), pair.second); + for (std::size_t i = pair.second; i < bitCount; i += pair.second) + seq = bitset.Read(seq, pair.second); + + REQUIRE(bitset.GetSize() == bitCount); + + Nz::Bitset expectedBitset(result); + + CHECK(bitset == expectedBitset); + CHECK(bitset.GetBlockCount() == (bitCount / bitset.bitsPerBlock + std::min(1, bitCount % bitset.bitsPerBlock))); + } + } + } + } +} + +template +void CheckReverse(const char* title) +{ + SECTION(title) + { + GIVEN("A bitset") + { + Nz::String bits = "010011100010001101001111"; + Nz::Bitset expected(bits); + + WHEN("We reverse the order of bits") + { + Nz::Bitset bitset(bits); + bitset.Reverse(); + + THEN("The order of bits should be reversed") + { + CHECK(bitset == Nz::Bitset(bits.Reversed())); + } + AND_WHEN("We reverse the bit order again") + { + bitset.Reverse(); + + THEN("It should be back to normal") + { + CHECK(bitset == expected); + } + } } } } diff --git a/tests/Engine/Graphics/ParticleDeclaration.cpp b/tests/Engine/Graphics/ParticleDeclaration.cpp index 1bc1739d3..4cde9c5d2 100644 --- a/tests/Engine/Graphics/ParticleDeclaration.cpp +++ b/tests/Engine/Graphics/ParticleDeclaration.cpp @@ -11,10 +11,10 @@ SCENARIO("ParticleDeclaration", "[GRAPHICS][PARTICLEDECLARATION]") { bool enabled; Nz::ComponentType type; - unsigned int offset; + std::size_t offset; particleDeclaration->GetComponent(Nz::ParticleComponent_Position, &enabled, &type, &offset); REQUIRE(enabled); - unsigned int oldStride = particleDeclaration->GetStride(); + std::size_t oldStride = particleDeclaration->GetStride(); particleDeclaration->DisableComponent(Nz::ParticleComponent_Position); REQUIRE(oldStride != particleDeclaration->GetStride());