Merge branch 'master' into vulkan

This commit is contained in:
Lynix 2016-11-21 00:32:57 +01:00
commit e0935edd00
140 changed files with 4261 additions and 1744 deletions

16
.editorconfig Normal file
View File

@ -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

4
.gitignore vendored
View File

@ -35,6 +35,7 @@ build/scripts/features/index.html
doc doc
# Codeblocks # Codeblocks
*.save-failed
build/**/*.cbp build/**/*.cbp
build/**/*.cbp build/**/*.cbp
build/**/*.cbTemp build/**/*.cbTemp
@ -46,6 +47,9 @@ build/**/*.workspace
# CodeLite # CodeLite
build/**/*.project build/**/*.project
# GMake
build/**/*.make
# Visual Studio # Visual Studio
build/**/*.pdb build/**/*.pdb
build/**/*.filters build/**/*.filters

View File

@ -38,7 +38,7 @@ PROJECT_NAME = "Nazara Engine"
# could be handy for archiving the generated documentation or if some version # could be handy for archiving the generated documentation or if some version
# control system is used. # 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 # 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 # for a project that appears at the top of each page and should give viewer a

View File

@ -59,7 +59,7 @@ namespace Ndk
* \param args Arguments used to create the window * \param args Arguments used to create the window
*/ */
#ifndef NDK_SERVER #ifndef NDK_SERVER
template<typename T, typename... Args> template<typename T, typename... Args>
T& Application::AddWindow(Args&&... args) T& Application::AddWindow(Args&&... args)
{ {
static_assert(std::is_base_of<Nz::Window, T>::value, "Type must inherit Window"); static_assert(std::is_base_of<Nz::Window, T>::value, "Type must inherit Window");
@ -82,7 +82,7 @@ namespace Ndk
* \param args Arguments used to create the world * \param args Arguments used to create the world
*/ */
template<typename... Args> template<typename... Args>
World& Application::AddWorld(Args&&... args) World& Application::AddWorld(Args&&... args)
{ {
m_worlds.emplace_back(std::forward<Args>(args)...); m_worlds.emplace_back(std::forward<Args>(args)...);
@ -373,9 +373,9 @@ namespace Ndk
{ {
} }
inline Application::WindowInfo::WindowInfo(std::unique_ptr<Nz::Window>&& window) : inline Application::WindowInfo::WindowInfo(std::unique_ptr<Nz::Window>&& windowPtr) :
renderTarget(nullptr), renderTarget(nullptr),
window(std::move(window)) window(std::move(windowPtr))
{ {
} }
#endif #endif

View File

@ -35,6 +35,7 @@ namespace Ndk
inline const std::vector<EntityHandle>& GetEntities() const; inline const std::vector<EntityHandle>& GetEntities() const;
inline SystemIndex GetIndex() const; inline SystemIndex GetIndex() const;
inline int GetUpdateOrder() const;
inline float GetUpdateRate() const; inline float GetUpdateRate() const;
inline World& GetWorld() const; inline World& GetWorld() const;
@ -42,6 +43,7 @@ namespace Ndk
inline bool HasEntity(const Entity* entity) const; inline bool HasEntity(const Entity* entity) const;
void SetUpdateOrder(int updateOrder);
inline void SetUpdateRate(float updatePerSecond); inline void SetUpdateRate(float updatePerSecond);
inline void Update(float elapsedTime); inline void Update(float elapsedTime);
@ -93,6 +95,7 @@ namespace Ndk
bool m_updateEnabled; bool m_updateEnabled;
float m_updateCounter; float m_updateCounter;
float m_updateRate; float m_updateRate;
int m_updateOrder;
static SystemIndex s_nextIndex; static SystemIndex s_nextIndex;
}; };

View File

@ -16,7 +16,9 @@ namespace Ndk
inline BaseSystem::BaseSystem(SystemIndex systemId) : inline BaseSystem::BaseSystem(SystemIndex systemId) :
m_systemIndex(systemId), m_systemIndex(systemId),
m_updateEnabled(true) m_world(nullptr),
m_updateEnabled(true),
m_updateOrder(0)
{ {
SetUpdateRate(30); SetUpdateRate(30);
} }
@ -33,7 +35,8 @@ namespace Ndk
m_systemIndex(system.m_systemIndex), m_systemIndex(system.m_systemIndex),
m_updateEnabled(system.m_updateEnabled), m_updateEnabled(system.m_updateEnabled),
m_updateCounter(0.f), 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 * \return Update rate
*/ */

View File

@ -6,6 +6,7 @@
#define NDK_COMPONENTS_GLOBAL_HPP #define NDK_COMPONENTS_GLOBAL_HPP
#include <NDK/Components/CameraComponent.hpp> #include <NDK/Components/CameraComponent.hpp>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/CollisionComponent3D.hpp> #include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/GraphicsComponent.hpp> #include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/LightComponent.hpp> #include <NDK/Components/LightComponent.hpp>
@ -13,6 +14,7 @@
#include <NDK/Components/NodeComponent.hpp> #include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/ParticleEmitterComponent.hpp> #include <NDK/Components/ParticleEmitterComponent.hpp>
#include <NDK/Components/ParticleGroupComponent.hpp> #include <NDK/Components/ParticleGroupComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp> #include <NDK/Components/PhysicsComponent3D.hpp>
#include <NDK/Components/VelocityComponent.hpp> #include <NDK/Components/VelocityComponent.hpp>

View File

@ -18,9 +18,12 @@
namespace Ndk namespace Ndk
{ {
class CameraComponent;
class Entity; class Entity;
class NDK_API CameraComponent : public Component<CameraComponent>, public Nz::AbstractViewer using CameraComponentHandle = Nz::ObjectHandle<CameraComponent>;
class NDK_API CameraComponent : public Component<CameraComponent>, public Nz::AbstractViewer, public Nz::HandledObject<CameraComponent>
{ {
public: public:
inline CameraComponent(); inline CameraComponent();
@ -51,7 +54,7 @@ namespace Ndk
float GetZNear() const override; float GetZNear() const override;
inline void SetFOV(float fov); inline void SetFOV(float fov);
inline void SetLayer(unsigned int layer); void SetLayer(unsigned int layer);
inline void SetProjectionType(Nz::ProjectionType projection); inline void SetProjectionType(Nz::ProjectionType projection);
inline void SetSize(const Nz::Vector2f& size); inline void SetSize(const Nz::Vector2f& size);
inline void SetSize(float width, float height); inline void SetSize(float width, float height);

View File

@ -99,7 +99,7 @@ namespace Ndk
* \brief Gets the field of view of the camera * \brief Gets the field of view of the camera
* \return 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; return m_fov;
} }

View File

@ -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 <Nazara/Physics2D/Collider2D.hpp>
#include <NDK/Component.hpp>
#include <memory>
namespace Nz
{
class RigidBody2D;
}
namespace Ndk
{
class Entity;
class NDK_API CollisionComponent2D : public Component<CollisionComponent2D>
{
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<Nz::RigidBody2D> m_staticBody;
Nz::Collider2DRef m_geom;
bool m_bodyUpdated;
};
}
#include <NDK/Components/CollisionComponent2D.inl>
#endif // NDK_COMPONENTS_COLLISIONCOMPONENT2D_HPP

View File

@ -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 <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Entity.hpp>
#include <NDK/World.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
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();
}
}

View File

@ -4,8 +4,8 @@
#pragma once #pragma once
#ifndef NDK_COMPONENTS_COLLISIONCOMPONENT_HPP #ifndef NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP
#define NDK_COMPONENTS_COLLISIONCOMPONENT_HPP #define NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP
#include <Nazara/Physics3D/Collider3D.hpp> #include <Nazara/Physics3D/Collider3D.hpp>
#include <NDK/Component.hpp> #include <NDK/Component.hpp>
@ -23,7 +23,6 @@ namespace Ndk
class NDK_API CollisionComponent3D : public Component<CollisionComponent3D> class NDK_API CollisionComponent3D : public Component<CollisionComponent3D>
{ {
friend class PhysicsSystem3D; friend class PhysicsSystem3D;
friend class StaticCollisionSystem;
public: public:
CollisionComponent3D(Nz::Collider3DRef geom = Nz::Collider3DRef()); CollisionComponent3D(Nz::Collider3DRef geom = Nz::Collider3DRef());
@ -56,4 +55,4 @@ namespace Ndk
#include <NDK/Components/CollisionComponent3D.inl> #include <NDK/Components/CollisionComponent3D.inl>
#endif // NDK_COMPONENTS_COLLISIONCOMPONENT_HPP #endif // NDK_COMPONENTS_COLLISIONCOMPONENT3D_HPP

View File

@ -73,19 +73,19 @@ namespace Ndk
{ {
} }
Renderable(Renderable&& renderable) noexcept : Renderable(Renderable&& rhs) noexcept :
renderableInvalidationSlot(std::move(renderable.renderableInvalidationSlot)), renderableInvalidationSlot(std::move(rhs.renderableInvalidationSlot)),
renderableReleaseSlot(std::move(renderable.renderableReleaseSlot)), renderableReleaseSlot(std::move(rhs.renderableReleaseSlot)),
data(std::move(renderable.data)), data(std::move(rhs.data)),
renderable(std::move(renderable.renderable)), renderable(std::move(rhs.renderable)),
dataUpdated(renderable.dataUpdated) dataUpdated(rhs.dataUpdated)
{ {
} }
~Renderable() ~Renderable()
{ {
// Disconnect release slot before releasing instanced renderable reference // Disconnect release slot before releasing instanced renderable reference
renderableReleaseSlot.Disconnect(); renderableReleaseSlot.Disconnect();
} }
Renderable& operator=(Renderable&& r) noexcept Renderable& operator=(Renderable&& r) noexcept
@ -118,4 +118,4 @@ namespace Ndk
#include <NDK/Components/GraphicsComponent.inl> #include <NDK/Components/GraphicsComponent.inl>
#endif // NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP #endif // NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP
#endif // NDK_SERVER #endif // NDK_SERVER

View File

@ -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 <Nazara/Physics2D/RigidBody2D.hpp>
#include <NDK/Component.hpp>
#include <memory>
namespace Ndk
{
class Entity;
class NDK_API PhysicsComponent2D : public Component<PhysicsComponent2D>
{
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<Nz::RigidBody2D> m_object;
};
}
#include <NDK/Components/PhysicsComponent2D.inl>
#endif // NDK_COMPONENTS_PHYSICSCOMPONENT2D_HPP

View File

@ -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 <Nazara/Core/Error.hpp>
#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();
}
}

View File

@ -56,7 +56,7 @@ namespace Ndk
static ComponentIndex componentIndex; static ComponentIndex componentIndex;
private: private:
Nz::RigidBody3D& GetPhysObject(); Nz::RigidBody3D& GetRigidBody();
void OnAttached() override; void OnAttached() override;
void OnComponentAttached(BaseComponent& component) override; void OnComponentAttached(BaseComponent& component) override;

View File

@ -350,7 +350,7 @@ namespace Ndk
* \return A reference to the physics object * \return A reference to the physics object
*/ */
inline Nz::RigidBody3D& PhysicsComponent3D::GetPhysObject() inline Nz::RigidBody3D& PhysicsComponent3D::GetRigidBody()
{ {
return *m_object.get(); return *m_object.get();
} }

View File

@ -28,15 +28,6 @@
namespace Nz 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<Color>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Color* color, TypeTag<Color>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -49,15 +40,6 @@ namespace Nz
return 1; 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<EulerAnglesd>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesd* angles, TypeTag<EulerAnglesd>)
{ {
switch (instance.GetType(index)) 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<EulerAnglesf>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, EulerAnglesf* angles, TypeTag<EulerAnglesf>)
{ {
EulerAnglesd anglesDouble; EulerAnglesd anglesDouble;
@ -96,15 +69,6 @@ namespace Nz
return ret; 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>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontRef* fontRef, TypeTag<FontRef>)
{ {
*fontRef = *static_cast<FontRef*>(instance.CheckUserdata(index, "Font")); *fontRef = *static_cast<FontRef*>(instance.CheckUserdata(index, "Font"));
@ -112,15 +76,6 @@ namespace Nz
return 1; 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<FontParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, FontParams* params, TypeTag<FontParams>)
{ {
NazaraUnused(params); NazaraUnused(params);
@ -132,14 +87,6 @@ namespace Nz
return 1; 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<ImageParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ImageParams* params, TypeTag<ImageParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -150,15 +97,6 @@ namespace Nz
return 1; 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<IpAddress>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, IpAddress* address, TypeTag<IpAddress>)
{ {
switch (instance.GetType(index)) 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<Matrix4d>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4d* mat, TypeTag<Matrix4d>)
{ {
switch (instance.GetType(index)) switch (instance.GetType(index))
@ -212,33 +141,15 @@ 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<Matrix4f>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Matrix4f* mat, TypeTag<Matrix4f>)
{ {
Matrix4d matDouble; Matrix4d matDouble = Matrix4d::Identity();
unsigned int ret = LuaImplQueryArg(instance, index, &matDouble, TypeTag<Matrix4d>()); unsigned int ret = LuaImplQueryArg(instance, index, &matDouble, TypeTag<Matrix4d>());
mat->Set(matDouble); mat->Set(matDouble);
return ret; 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<MeshParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MeshParams* params, TypeTag<MeshParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -252,15 +163,6 @@ namespace Nz
return 1; 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<Quaterniond>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaterniond* quat, TypeTag<Quaterniond>)
{ {
switch (instance.GetType(index)) switch (instance.GetType(index))
@ -281,15 +183,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<Quaternionf>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaternionf* quat, TypeTag<Quaternionf>)
{ {
Quaterniond quatDouble; Quaterniond quatDouble;
@ -299,15 +192,6 @@ namespace Nz
return ret; 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<Rectd>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectd* rect, TypeTag<Rectd>)
{ {
instance.CheckType(index, LuaType_Table); instance.CheckType(index, LuaType_Table);
@ -320,15 +204,6 @@ namespace Nz
return 1; 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<Rectf>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectf* rect, TypeTag<Rectf>)
{ {
Rectd rectDouble; Rectd rectDouble;
@ -338,14 +213,14 @@ namespace Nz
return ret; return ret;
} }
/*! inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Recti* rect, TypeTag<Recti>)
* \brief Queries arguments for Lua {
* \return 1 in case of success Rectd rectDouble;
* unsigned int ret = LuaImplQueryArg(instance, index, &rectDouble, TypeTag<Rectd>());
* \param instance Lua instance to interact with
* \param index Index type rect->Set(rectDouble);
* \param rect Resulting rectangle return ret;
*/ }
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectui* rect, TypeTag<Rectui>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Rectui* rect, TypeTag<Rectui>)
{ {
@ -356,15 +231,6 @@ namespace Nz
return ret; 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<Vector2d>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2d* vec, TypeTag<Vector2d>)
{ {
switch (instance.GetType(index)) switch (instance.GetType(index))
@ -386,15 +252,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<Vector2f>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2f* vec, TypeTag<Vector2f>)
{ {
Vector2d vecDouble; Vector2d vecDouble;
@ -404,15 +261,6 @@ namespace Nz
return ret; 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<Vector2ui>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector2ui* vec, TypeTag<Vector2ui>)
{ {
Vector2d vecDouble; Vector2d vecDouble;
@ -422,15 +270,6 @@ namespace Nz
return ret; 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<Vector3d>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3d* vec, TypeTag<Vector3d>)
{ {
switch (instance.GetType(index)) switch (instance.GetType(index))
@ -452,15 +291,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<Vector3f>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3f* vec, TypeTag<Vector3f>)
{ {
Vector3d vecDouble; Vector3d vecDouble;
@ -470,15 +300,6 @@ namespace Nz
return ret; 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<Vector3ui>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Vector3ui* vec, TypeTag<Vector3ui>)
{ {
Vector3d vecDouble; Vector3d vecDouble;
@ -488,15 +309,6 @@ namespace Nz
return ret; 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<Ndk::EntityHandle>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::EntityHandle* handle, TypeTag<Ndk::EntityHandle>)
{ {
*handle = *static_cast<Ndk::EntityHandle*>(instance.CheckUserdata(index, "Entity")); *handle = *static_cast<Ndk::EntityHandle*>(instance.CheckUserdata(index, "Entity"));
@ -504,15 +316,6 @@ namespace Nz
return 1; 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<Ndk::WorldHandle>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Ndk::WorldHandle* handle, TypeTag<Ndk::WorldHandle>)
{ {
*handle = *static_cast<Ndk::WorldHandle*>(instance.CheckUserdata(index, "World")); *handle = *static_cast<Ndk::WorldHandle*>(instance.CheckUserdata(index, "World"));
@ -521,16 +324,6 @@ namespace Nz
} }
#ifndef NDK_SERVER #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<InstancedRenderableRef>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, InstancedRenderableRef* renderable, TypeTag<InstancedRenderableRef>)
{ {
if (instance.IsOfType(index, "InstancedRenderable") || if (instance.IsOfType(index, "InstancedRenderable") ||
@ -545,15 +338,6 @@ namespace Nz
return 1; 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>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialRef* materialRef, TypeTag<MaterialRef>)
{ {
*materialRef = *static_cast<MaterialRef*>(instance.CheckUserdata(index, "Material")); *materialRef = *static_cast<MaterialRef*>(instance.CheckUserdata(index, "Material"));
@ -561,15 +345,6 @@ namespace Nz
return 1; 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<MaterialParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MaterialParams* params, TypeTag<MaterialParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -585,15 +360,6 @@ namespace Nz
return 1; 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<ModelParameters>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, ModelParameters* params, TypeTag<ModelParameters>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -606,15 +372,6 @@ namespace Nz
return 1; 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<MusicParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, MusicParams* params, TypeTag<MusicParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -624,15 +381,6 @@ namespace Nz
return 1; 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<SoundBufferParams>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SoundBufferParams* params, TypeTag<SoundBufferParams>)
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
@ -642,15 +390,6 @@ namespace Nz
return 1; 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>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, SpriteRef* spriteRef, TypeTag<SpriteRef>)
{ {
*spriteRef = *static_cast<SpriteRef*>(instance.CheckUserdata(index, "Sprite")); *spriteRef = *static_cast<SpriteRef*>(instance.CheckUserdata(index, "Sprite"));
@ -658,15 +397,6 @@ namespace Nz
return 1; 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>) inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, TextureRef* textureRef, TypeTag<TextureRef>)
{ {
*textureRef = *static_cast<TextureRef*>(instance.CheckUserdata(index, "Texture")); *textureRef = *static_cast<TextureRef*>(instance.CheckUserdata(index, "Texture"));
@ -676,14 +406,6 @@ namespace Nz
#endif #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<Color>) inline int LuaImplReplyVal(const LuaInstance& instance, Color&& val, TypeTag<Color>)
{ {
instance.PushTable(); instance.PushTable();
@ -695,56 +417,24 @@ namespace Nz
return 1; 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<EulerAnglesd>) inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesd&& val, TypeTag<EulerAnglesd>)
{ {
instance.PushInstance<EulerAnglesd>("EulerAngles", val); instance.PushInstance<EulerAnglesd>("EulerAngles", val);
return 1; 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<EulerAnglesf>) inline int LuaImplReplyVal(const LuaInstance& instance, EulerAnglesf&& val, TypeTag<EulerAnglesf>)
{ {
instance.PushInstance<EulerAnglesd>("EulerAngles", val); instance.PushInstance<EulerAnglesd>("EulerAngles", val);
return 1; 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<FontRef>) inline int LuaImplReplyVal(const LuaInstance& instance, FontRef&& val, TypeTag<FontRef>)
{ {
instance.PushInstance<FontRef>("Font", val); instance.PushInstance<FontRef>("Font", val);
return 1; 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<Font::SizeInfo>) inline int LuaImplReplyVal(const LuaInstance& instance, Font::SizeInfo&& val, TypeTag<Font::SizeInfo>)
{ {
instance.PushTable(); instance.PushTable();
@ -756,14 +446,6 @@ namespace Nz
return 1; 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<ImageParams>) inline int LuaImplReplyVal(const LuaInstance& instance, ImageParams&& val, TypeTag<ImageParams>)
{ {
instance.PushTable(0, 2); instance.PushTable(0, 2);
@ -773,111 +455,53 @@ namespace Nz
return 1; 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<IpAddress>) inline int LuaImplReplyVal(const LuaInstance& instance, IpAddress&& val, TypeTag<IpAddress>)
{ {
instance.PushInstance<IpAddress>("IpAddress", val); instance.PushInstance<IpAddress>("IpAddress", val);
return 1; 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<Matrix4d>) inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4d&& val, TypeTag<Matrix4d>)
{ {
instance.PushInstance<Matrix4d>("Matrix4", val); instance.PushInstance<Matrix4d>("Matrix4", val);
return 1; 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<Matrix4f>) inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4f&& val, TypeTag<Matrix4f>)
{ {
instance.PushInstance<Matrix4d>("Matrix4", val); instance.PushInstance<Matrix4d>("Matrix4", val);
return 1; 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<Quaterniond>) inline int LuaImplReplyVal(const LuaInstance& instance, Quaterniond&& val, TypeTag<Quaterniond>)
{ {
instance.PushInstance<Quaterniond>("Quaternion", val); instance.PushInstance<Quaterniond>("Quaternion", val);
return 1; 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<Quaternionf>) inline int LuaImplReplyVal(const LuaInstance& instance, Quaternionf&& val, TypeTag<Quaternionf>)
{ {
instance.PushInstance<Quaterniond>("Quaternion", val); instance.PushInstance<Quaterniond>("Quaternion", val);
return 1; 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<Rectd>) inline int LuaImplReplyVal(const LuaInstance& instance, Rectd&& val, TypeTag<Rectd>)
{ {
instance.PushInstance<Rectd>("Rect", val); instance.PushInstance<Rectd>("Rect", val);
return 1; 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<Rectf>) inline int LuaImplReplyVal(const LuaInstance& instance, Rectf&& val, TypeTag<Rectf>)
{ {
instance.PushInstance<Rectd>("Rect", val); instance.PushInstance<Rectd>("Rect", val);
return 1; return 1;
} }
/*! inline int LuaImplReplyVal(const LuaInstance& instance, Recti&& val, TypeTag<Recti>)
* \brief Replies by value for Lua {
* \return 1 in case of success instance.PushInstance<Rectd>("Rect", val);
* return 1;
* \param instance Lua instance to interact with }
* \param val Resulting rectangle
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Rectui&& val, TypeTag<Rectui>) inline int LuaImplReplyVal(const LuaInstance& instance, Rectui&& val, TypeTag<Rectui>)
{ {
@ -885,182 +509,78 @@ namespace Nz
return 1; 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<Vector2d>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector2d&& val, TypeTag<Vector2d>)
{ {
instance.PushInstance<Vector2d>("Vector2", val); instance.PushInstance<Vector2d>("Vector2", val);
return 1; 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<Vector2f>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector2f&& val, TypeTag<Vector2f>)
{ {
instance.PushInstance<Vector2d>("Vector2", val); instance.PushInstance<Vector2d>("Vector2", val);
return 1; 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<Vector2ui>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector2ui&& val, TypeTag<Vector2ui>)
{ {
instance.PushInstance<Vector2d>("Vector2", val); instance.PushInstance<Vector2d>("Vector2", val);
return 1; 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<Vector3d>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector3d&& val, TypeTag<Vector3d>)
{ {
instance.PushInstance<Vector3d>("Vector3", val); instance.PushInstance<Vector3d>("Vector3", val);
return 1; 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<Vector3f>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector3f&& val, TypeTag<Vector3f>)
{ {
instance.PushInstance<Vector3d>("Vector3", val); instance.PushInstance<Vector3d>("Vector3", val);
return 1; 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<Vector3ui>) inline int LuaImplReplyVal(const LuaInstance& instance, Vector3ui&& val, TypeTag<Vector3ui>)
{ {
instance.PushInstance<Vector3d>("Vector3", val); instance.PushInstance<Vector3d>("Vector3", val);
return 1; 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<Ndk::Entity*>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Entity* ptr, TypeTag<Ndk::Entity*>)
{ {
instance.PushInstance<Ndk::EntityHandle>("Entity", ptr); instance.PushInstance<Ndk::EntityHandle>("Entity", ptr);
return 1; 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<Ndk::Application*>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::Application* ptr, TypeTag<Ndk::Application*>)
{ {
instance.PushInstance<Ndk::Application*>("Application", ptr); instance.PushInstance<Ndk::Application*>("Application", ptr);
return 1; 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<Ndk::EntityHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::EntityHandle&& handle, TypeTag<Ndk::EntityHandle>)
{ {
instance.PushInstance<Ndk::EntityHandle>("Entity", handle); instance.PushInstance<Ndk::EntityHandle>("Entity", handle);
return 1; 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<Ndk::NodeComponentHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::NodeComponentHandle&& handle, TypeTag<Ndk::NodeComponentHandle>)
{ {
instance.PushInstance<Ndk::NodeComponentHandle>("NodeComponent", handle); instance.PushInstance<Ndk::NodeComponentHandle>("NodeComponent", handle);
return 1; 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<Ndk::VelocityComponentHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::VelocityComponentHandle&& handle, TypeTag<Ndk::VelocityComponentHandle>)
{ {
instance.PushInstance<Ndk::VelocityComponentHandle>("VelocityComponent", handle); instance.PushInstance<Ndk::VelocityComponentHandle>("VelocityComponent", handle);
return 1; 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<Ndk::World*>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::World* ptr, TypeTag<Ndk::World*>)
{ {
instance.PushInstance<Ndk::WorldHandle>("World", ptr); instance.PushInstance<Ndk::WorldHandle>("World", ptr);
return 1; 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<Ndk::WorldHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::WorldHandle&& handle, TypeTag<Ndk::WorldHandle>)
{ {
instance.PushInstance<Ndk::WorldHandle>("World", handle); instance.PushInstance<Ndk::WorldHandle>("World", handle);
@ -1068,70 +588,35 @@ namespace Nz
} }
#ifndef NDK_SERVER #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<MaterialRef>) inline int LuaImplReplyVal(const LuaInstance& instance, MaterialRef&& handle, TypeTag<MaterialRef>)
{ {
instance.PushInstance<MaterialRef>("Material", handle); instance.PushInstance<MaterialRef>("Material", handle);
return 1; 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<const SoundBuffer*>) inline int LuaImplReplyVal(const LuaInstance& instance, const SoundBuffer* val, TypeTag<const SoundBuffer*>)
{ {
instance.PushInstance<SoundBufferConstRef>("SoundBuffer", val); instance.PushInstance<SoundBufferConstRef>("SoundBuffer", val);
return 1; 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<SpriteRef>) inline int LuaImplReplyVal(const LuaInstance& instance, SpriteRef&& handle, TypeTag<SpriteRef>)
{ {
instance.PushInstance<SpriteRef>("Sprite", handle); instance.PushInstance<SpriteRef>("Sprite", handle);
return 1; 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<TextureRef>) inline int LuaImplReplyVal(const LuaInstance& instance, TextureRef&& handle, TypeTag<TextureRef>)
{ {
instance.PushInstance<TextureRef>("Texture", handle); instance.PushInstance<TextureRef>("Texture", handle);
return 1; return 1;
} }
/*! inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::CameraComponentHandle&& handle, TypeTag<Ndk::CameraComponentHandle>)
* \brief Replies by value for Lua {
* \return 1 in case of success instance.PushInstance<Ndk::CameraComponentHandle>("CameraComponent", handle);
* return 1;
* \param instance Lua instance to interact with }
* \param handle Resulting console
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::ConsoleHandle&& handle, TypeTag<Ndk::ConsoleHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::ConsoleHandle&& handle, TypeTag<Ndk::ConsoleHandle>)
{ {
@ -1139,14 +624,6 @@ namespace Nz
return 1; 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<Ndk::GraphicsComponentHandle>) inline int LuaImplReplyVal(const LuaInstance& instance, Ndk::GraphicsComponentHandle&& handle, TypeTag<Ndk::GraphicsComponentHandle>)
{ {
instance.PushInstance<Ndk::GraphicsComponentHandle>("GraphicsComponent", handle); instance.PushInstance<Ndk::GraphicsComponentHandle>("GraphicsComponent", handle);

View File

@ -58,6 +58,7 @@ namespace Ndk
// Utility // Utility
Nz::LuaClass<Nz::AbstractImageRef> abstractImage; Nz::LuaClass<Nz::AbstractImageRef> abstractImage;
Nz::LuaClass<Nz::FontRef> font; Nz::LuaClass<Nz::FontRef> font;
Nz::LuaClass<Nz::Keyboard> keyboard;
Nz::LuaClass<Nz::Node> node; Nz::LuaClass<Nz::Node> node;
// SDK // SDK
@ -75,6 +76,7 @@ namespace Ndk
Nz::LuaClass<Nz::SoundEmitter> soundEmitter; Nz::LuaClass<Nz::SoundEmitter> soundEmitter;
// Graphics // Graphics
Nz::LuaClass<Nz::AbstractViewer> abstractViewer;
Nz::LuaClass<Nz::InstancedRenderableRef> instancedRenderable; Nz::LuaClass<Nz::InstancedRenderableRef> instancedRenderable;
Nz::LuaClass<Nz::MaterialRef> material; Nz::LuaClass<Nz::MaterialRef> material;
Nz::LuaClass<Nz::ModelRef> model; Nz::LuaClass<Nz::ModelRef> model;
@ -87,6 +89,7 @@ namespace Ndk
Nz::LuaClass<Nz::TextureRef> texture; Nz::LuaClass<Nz::TextureRef> texture;
// SDK // SDK
Nz::LuaClass<CameraComponentHandle> cameraComponent;
Nz::LuaClass<ConsoleHandle> console; Nz::LuaClass<ConsoleHandle> console;
Nz::LuaClass<GraphicsComponentHandle> graphicsComponent; Nz::LuaClass<GraphicsComponentHandle> graphicsComponent;
#endif #endif

View File

@ -25,11 +25,16 @@
#ifndef NDK_PREREQUESITES_HPP #ifndef NDK_PREREQUESITES_HPP
#define 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 <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
// Importation/Exportation of the API // Importation/Exportation of the API
#if defined(NAZARA_STATIC) #if defined(NAZARA_STATIC)
#define #define NDK_API #define NDK_API
#else #else
#ifdef NDK_BUILD #ifdef NDK_BUILD
#define NDK_API NAZARA_EXPORT #define NDK_API NAZARA_EXPORT

View File

@ -7,6 +7,7 @@
#include <NDK/Systems/ListenerSystem.hpp> #include <NDK/Systems/ListenerSystem.hpp>
#include <NDK/Systems/ParticleSystem.hpp> #include <NDK/Systems/ParticleSystem.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
#include <NDK/Systems/PhysicsSystem3D.hpp> #include <NDK/Systems/PhysicsSystem3D.hpp>
#include <NDK/Systems/RenderSystem.hpp> #include <NDK/Systems/RenderSystem.hpp>
#include <NDK/Systems/VelocitySystem.hpp> #include <NDK/Systems/VelocitySystem.hpp>

View File

@ -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 <Nazara/Physics2D/PhysWorld2D.hpp>
#include <NDK/EntityList.hpp>
#include <NDK/System.hpp>
#include <memory>
namespace Ndk
{
class NDK_API PhysicsSystem2D : public System<PhysicsSystem2D>
{
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<Nz::PhysWorld2D> m_world; ///TODO: std::optional (Should I make a Nz::Optional class?)
};
}
#include <NDK/Systems/PhysicsSystem2D.inl>
#endif // NDK_SYSTEMS_PHYSICSSYSTEM2D_HPP

View File

@ -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;
}
}

View File

@ -24,6 +24,7 @@ namespace Ndk
class NDK_API World : public Nz::HandledObject<World> class NDK_API World : public Nz::HandledObject<World>
{ {
friend BaseSystem;
friend Entity; friend Entity;
public: public:
@ -72,6 +73,8 @@ namespace Ndk
private: private:
inline void Invalidate(); inline void Invalidate();
inline void Invalidate(EntityId id); inline void Invalidate(EntityId id);
inline void InvalidateSystemOrder();
void ReorderSystems();
struct EntityBlock struct EntityBlock
{ {
@ -83,15 +86,17 @@ namespace Ndk
EntityBlock(EntityBlock&& block) = default; EntityBlock(EntityBlock&& block) = default;
Entity entity; Entity entity;
unsigned int aliveIndex; std::size_t aliveIndex;
}; };
std::vector<std::unique_ptr<BaseSystem>> m_systems; std::vector<std::unique_ptr<BaseSystem>> m_systems;
std::vector<BaseSystem*> m_orderedSystems;
std::vector<EntityBlock> m_entities; std::vector<EntityBlock> m_entities;
std::vector<EntityId> m_freeIdList; std::vector<EntityId> m_freeIdList;
EntityList m_aliveEntities; EntityList m_aliveEntities;
Nz::Bitset<Nz::UInt64> m_dirtyEntities; Nz::Bitset<Nz::UInt64> m_dirtyEntities;
Nz::Bitset<Nz::UInt64> m_killedEntities; Nz::Bitset<Nz::UInt64> m_killedEntities;
bool m_orderedSystemsUpdated;
}; };
} }

View File

@ -53,6 +53,7 @@ namespace Ndk
m_systems[index]->SetWorld(this); m_systems[index]->SetWorld(this);
Invalidate(); // We force an update for every entities Invalidate(); // We force an update for every entities
InvalidateSystemOrder(); // And regenerate the system update list
return *m_systems[index].get(); return *m_systems[index].get();
} }
@ -206,6 +207,8 @@ namespace Ndk
inline void World::RemoveAllSystems() inline void World::RemoveAllSystems()
{ {
m_systems.clear(); m_systems.clear();
InvalidateSystemOrder();
} }
/*! /*!
@ -219,7 +222,11 @@ namespace Ndk
inline void World::RemoveSystem(SystemIndex index) inline void World::RemoveSystem(SystemIndex index)
{ {
if (HasSystem(index)) if (HasSystem(index))
{
m_systems[index].reset(); m_systems[index].reset();
InvalidateSystemOrder();
}
} }
/*! /*!
@ -246,32 +253,8 @@ namespace Ndk
Update(); //< Update entities Update(); //< Update entities
// And then update systems // And then update systems
for (auto& systemPtr : m_systems) for (auto& systemPtr : m_orderedSystems)
{ systemPtr->Update(elapsedTime);
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);
} }
/*! /*!
@ -281,10 +264,12 @@ namespace Ndk
inline World& World::operator=(World&& world) noexcept inline World& World::operator=(World&& world) noexcept
{ {
m_aliveEntities = std::move(world.m_aliveEntities); m_aliveEntities = std::move(world.m_aliveEntities);
m_dirtyEntities = std::move(world.m_dirtyEntities); m_dirtyEntities = std::move(world.m_dirtyEntities);
m_freeIdList = std::move(world.m_freeIdList); m_freeIdList = std::move(world.m_freeIdList);
m_killedEntities = std::move(world.m_killedEntities); 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); m_entities = std::move(world.m_entities);
for (EntityBlock& block : m_entities) for (EntityBlock& block : m_entities)
@ -296,4 +281,20 @@ namespace Ndk
return *this; 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;
}
} }

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp // For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/BaseSystem.hpp> #include <NDK/BaseSystem.hpp>
#include <NDK/World.hpp>
namespace Ndk namespace Ndk
{ {
@ -56,6 +57,26 @@ namespace Ndk
return true; 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 * \brief Operation to perform when entity is added to the system
* *

View File

@ -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 <NDK/Components/CollisionComponent2D.hpp>
#include <Nazara/Physics2D/RigidBody2D.hpp>
#include <NDK/Algorithm.hpp>
#include <NDK/World.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
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<PhysicsComponent2D>())
{
// We update the geometry of the PhysiscsObject linked to the PhysicsComponent2D
PhysicsComponent2D& physComponent = m_entity->GetComponent<PhysicsComponent2D>();
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<PhysicsSystem2D>(), "World must have a physics system");
Nz::PhysWorld2D& physWorld = entityWorld->GetSystem<PhysicsSystem2D>().GetWorld();
m_staticBody.reset(new Nz::RigidBody2D(&physWorld, 0.f, m_geom));
Nz::Matrix4f matrix;
if (m_entity->HasComponent<NodeComponent>())
matrix = m_entity->GetComponent<NodeComponent>().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<PhysicsComponent2D>())
InitializeStaticBody();
}
/*!
* \brief Operation to perform when component is attached to this component
*
* \param component Component being attached
*/
void CollisionComponent2D::OnComponentAttached(BaseComponent& component)
{
if (IsComponent<PhysicsComponent2D>(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<PhysicsComponent2D>(component))
InitializeStaticBody();
}
/*!
* \brief Operation to perform when component is detached from an entity
*/
void CollisionComponent2D::OnDetached()
{
m_staticBody.reset();
}
ComponentIndex CollisionComponent2D::componentIndex;
}

View File

@ -33,7 +33,7 @@ namespace Ndk
{ {
// We update the geometry of the PhysiscsObject linked to the PhysicsComponent3D // We update the geometry of the PhysiscsObject linked to the PhysicsComponent3D
PhysicsComponent3D& physComponent = m_entity->GetComponent<PhysicsComponent3D>(); PhysicsComponent3D& physComponent = m_entity->GetComponent<PhysicsComponent3D>();
physComponent.GetPhysObject().SetGeom(m_geom); physComponent.GetRigidBody().SetGeom(m_geom);
} }
else else
{ {

View File

@ -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 <NDK/Components/PhysicsComponent2D.hpp>
#include <Nazara/Physics2D/RigidBody2D.hpp>
#include <NDK/Algorithm.hpp>
#include <NDK/World.hpp>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Systems/PhysicsSystem3D.hpp>
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<PhysicsSystem2D>(), "World must have a 2D physics system");
Nz::PhysWorld2D& world = entityWorld->GetSystem<PhysicsSystem2D>().GetWorld();
Nz::Collider2DRef geom;
if (m_entity->HasComponent<CollisionComponent2D>())
geom = m_entity->GetComponent<CollisionComponent2D>().GetGeom();
Nz::Matrix4f matrix;
if (m_entity->HasComponent<NodeComponent>())
matrix = m_entity->GetComponent<NodeComponent>().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<CollisionComponent2D>(component))
{
NazaraAssert(m_object, "Invalid object");
m_object->SetGeom(static_cast<CollisionComponent2D&>(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<CollisionComponent2D>(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;
}

View File

@ -148,9 +148,11 @@ namespace Ndk
// We alert each system // We alert each system
for (std::size_t index = m_systemBits.FindFirst(); index != m_systemBits.npos; index = m_systemBits.FindNext(index)) 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<Ndk::SystemIndex>(index);
if (m_world->HasSystem(sysIndex))
{ {
BaseSystem& system = m_world->GetSystem(index); BaseSystem& system = m_world->GetSystem(sysIndex);
system.RemoveEntity(this); system.RemoveEntity(this);
} }
} }

View File

@ -36,6 +36,7 @@ namespace Ndk
// Utility // Utility
abstractImage("AbstractImage"), abstractImage("AbstractImage"),
font("Font"), font("Font"),
keyboard("Keyboard"),
node("Node"), node("Node"),
// SDK // SDK
@ -55,6 +56,7 @@ namespace Ndk
soundEmitter("SoundEmitter"), soundEmitter("SoundEmitter"),
// Graphics // Graphics
abstractViewer("AbstractViewer"),
instancedRenderable("InstancedRenderable"), instancedRenderable("InstancedRenderable"),
material("Material"), material("Material"),
model("Model"), model("Model"),
@ -67,6 +69,7 @@ namespace Ndk
texture("Texture"), texture("Texture"),
// SDK // SDK
cameraComponent("CameraComponent"),
console("Console"), console("Console"),
graphicsComponent("GraphicsComponent") graphicsComponent("GraphicsComponent")
#endif #endif

View File

@ -41,12 +41,12 @@ namespace Ndk
music.BindMethod("Stop", &Nz::Music::Stop); music.BindMethod("Stop", &Nz::Music::Stop);
// Manual // Manual
music.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& music, std::size_t /*argumentCount*/) -> int music.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& instance, std::size_t /*argumentCount*/) -> int
{ {
Nz::StringStream stream("Music("); Nz::StringStream ss("Music(");
stream << music.GetFilePath() << ')'; ss << instance.GetFilePath() << ')';
lua.PushString(stream); lua.PushString(ss);
return 1; return 1;
}); });
@ -65,15 +65,15 @@ namespace Ndk
sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset); sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset);
// Manual // Manual
sound.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& sound, std::size_t /*argumentCount*/) -> int sound.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& instance, std::size_t /*argumentCount*/) -> int
{ {
Nz::StringStream stream("Sound("); Nz::StringStream ss("Sound(");
if (const Nz::SoundBuffer* buffer = sound.GetBuffer()) if (const Nz::SoundBuffer* buffer = instance.GetBuffer())
stream << buffer; ss << buffer;
stream << ')'; ss << ')';
lua.PushString(stream); lua.PushString(ss);
return 1; return 1;
}); });
@ -124,18 +124,18 @@ namespace Ndk
soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{ {
Nz::StringStream stream("SoundBuffer("); Nz::StringStream ss("SoundBuffer(");
if (instance->IsValid()) if (instance->IsValid())
{ {
Nz::String filePath = instance->GetFilePath(); Nz::String filePath = instance->GetFilePath();
if (!filePath.IsEmpty()) if (!filePath.IsEmpty())
stream << "File: " << filePath << ", "; ss << "File: " << filePath << ", ";
stream << "Duration: " << instance->GetDuration() / 1000.f << "s"; ss << "Duration: " << instance->GetDuration() / 1000.f << "s";
} }
stream << ')'; ss << ')';
lua.PushString(stream); lua.PushString(ss);
return 1; return 1;
}); });

View File

@ -13,14 +13,37 @@ namespace Ndk
void LuaBinding::BindCore() void LuaBinding::BindCore()
{ {
/*********************************** Nz::Clock **********************************/ /*********************************** Nz::Clock **********************************/
clock.SetConstructor([](Nz::LuaInstance& lua, Nz::Clock* clock, std::size_t /*argumentCount*/) clock.SetConstructor([](Nz::LuaInstance& lua, Nz::Clock* instance, std::size_t argumentCount)
{ {
int argIndex = 2; std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
Nz::Int64 startingValue = lua.Check<Nz::Int64>(&argIndex, 0);
bool paused = lua.Check<bool>(&argIndex, false);
Nz::PlacementNew(clock, startingValue, paused); int argIndex = 2;
return true; switch (argCount)
{
case 0:
Nz::PlacementNew(instance);
return true;
case 1:
{
Nz::Int64 startingValue = lua.Check<Nz::Int64>(&argIndex, 0);
Nz::PlacementNew(instance, startingValue);
return true;
}
case 2:
{
Nz::Int64 startingValue = lua.Check<Nz::Int64>(&argIndex, 0);
bool paused = lua.Check<bool>(&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("GetMicroseconds", &Nz::Clock::GetMicroseconds);
@ -32,19 +55,19 @@ namespace Ndk
clock.BindMethod("Unpause", &Nz::Clock::Unpause); clock.BindMethod("Unpause", &Nz::Clock::Unpause);
// Manual // Manual
clock.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& clock, std::size_t /*argumentCount*/) -> int { clock.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream stream("Clock(Elapsed: "); Nz::StringStream ss("Clock(Elapsed: ");
stream << clock.GetSeconds(); ss << instance.GetSeconds();
stream << "s, Paused: "; ss << "s, Paused: ";
stream << clock.IsPaused(); ss << instance.IsPaused();
stream << ')'; ss << ')';
lua.PushString(stream); lua.PushString(ss);
return 1; return 1;
}); });
/********************************* Nz::Directory ********************************/ /********************************* Nz::Directory ********************************/
directory.SetConstructor([](Nz::LuaInstance& lua, Nz::Directory* directory, std::size_t argumentCount) directory.SetConstructor([](Nz::LuaInstance& lua, Nz::Directory* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U); std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
@ -52,11 +75,11 @@ namespace Ndk
switch (argCount) switch (argCount)
{ {
case 0: case 0:
Nz::PlacementNew(directory); Nz::PlacementNew(instance);
return true; return true;
case 1: case 1:
Nz::PlacementNew(directory, lua.Check<Nz::String>(&argIndex)); Nz::PlacementNew(instance, lua.Check<Nz::String>(&argIndex));
return true; return true;
} }
@ -85,12 +108,12 @@ namespace Ndk
directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent);
// Manual // Manual
directory.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& directory, std::size_t /*argumentCount*/) -> int { directory.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream stream("Directory("); Nz::StringStream ss("Directory(");
stream << directory.GetPath(); ss << instance.GetPath();
stream << ')'; ss << ')';
lua.PushString(stream); lua.PushString(ss);
return 1; return 1;
}); });
@ -110,35 +133,35 @@ namespace Ndk
stream.BindMethod("IsWritable", &Nz::Stream::IsWritable); stream.BindMethod("IsWritable", &Nz::Stream::IsWritable);
stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos); stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos);
stream.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int { stream.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int {
int argIndex = 2; int argIndex = 2;
std::size_t length = lua.Check<std::size_t>(&argIndex); std::size_t length = lua.Check<std::size_t>(&argIndex);
std::unique_ptr<char[]> buffer(new char[length]); std::unique_ptr<char[]> buffer(new char[length]);
std::size_t readLength = stream.Read(buffer.get(), length); std::size_t readLength = instance.Read(buffer.get(), length);
lua.PushString(Nz::String(buffer.get(), readLength)); lua.PushString(Nz::String(buffer.get(), readLength));
return 1; return 1;
}); });
stream.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& stream, std::size_t /*argumentCount*/) -> int { stream.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int {
int argIndex = 2; int argIndex = 2;
std::size_t bufferSize = 0; std::size_t bufferSize = 0;
const char* buffer = lua.CheckString(argIndex, &bufferSize); const char* buffer = lua.CheckString(argIndex, &bufferSize);
if (stream.IsTextModeEnabled()) if (instance.IsTextModeEnabled())
lua.Push(stream.Write(Nz::String(buffer, bufferSize))); lua.Push(instance.Write(Nz::String(buffer, bufferSize)));
else else
lua.Push(stream.Write(buffer, bufferSize)); lua.Push(instance.Write(buffer, bufferSize));
return 1; return 1;
}); });
/*********************************** Nz::File ***********************************/ /*********************************** Nz::File ***********************************/
file.Inherit(stream); file.Inherit(stream);
file.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* file, std::size_t argumentCount) file.SetConstructor([] (Nz::LuaInstance& lua, Nz::File* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U); std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
@ -146,14 +169,14 @@ namespace Ndk
switch (argCount) switch (argCount)
{ {
case 0: case 0:
Nz::PlacementNew(file); Nz::PlacementNew(instance);
return true; return true;
case 1: case 1:
{ {
Nz::String filePath = lua.Check<Nz::String>(&argIndex); Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::PlacementNew(file, filePath); Nz::PlacementNew(instance, filePath);
return true; return true;
} }
@ -162,7 +185,7 @@ namespace Ndk
Nz::String filePath = lua.Check<Nz::String>(&argIndex); Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex); Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex);
Nz::PlacementNew(file, filePath, openMode); Nz::PlacementNew(instance, filePath, openMode);
return true; return true;
} }
} }
@ -201,7 +224,7 @@ namespace Ndk
file.BindStaticMethod("Rename", &Nz::File::Rename); file.BindStaticMethod("Rename", &Nz::File::Rename);
// Manual // Manual
file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t argumentCount) -> int file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
@ -210,13 +233,13 @@ namespace Ndk
{ {
case 0: case 0:
case 1: case 1:
return lua.Push(file.Open(lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen))); return lua.Push(instance.Open(lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen)));
case 2: case 2:
{ {
Nz::String filePath = lua.Check<Nz::String>(&argIndex); Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen); Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen);
return lua.Push(file.Open(filePath, openMode)); return lua.Push(instance.Open(filePath, openMode));
} }
} }
@ -224,7 +247,7 @@ namespace Ndk
return 0; return 0;
}); });
file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t argumentCount) -> int file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
@ -232,13 +255,13 @@ namespace Ndk
switch (argCount) switch (argCount)
{ {
case 1: case 1:
return lua.Push(file.SetCursorPos(lua.Check<Nz::UInt64>(&argIndex))); return lua.Push(instance.SetCursorPos(lua.Check<Nz::UInt64>(&argIndex)));
case 2: case 2:
{ {
Nz::CursorPosition curPos = lua.Check<Nz::CursorPosition>(&argIndex); Nz::CursorPosition curPos = lua.Check<Nz::CursorPosition>(&argIndex);
Nz::Int64 offset = lua.Check<Nz::Int64>(&argIndex); Nz::Int64 offset = lua.Check<Nz::Int64>(&argIndex);
return lua.Push(file.SetCursorPos(curPos, offset)); return lua.Push(instance.SetCursorPos(curPos, offset));
} }
} }
@ -246,14 +269,14 @@ namespace Ndk
return 0; return 0;
}); });
file.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& file, std::size_t /*argumentCount*/) -> int { file.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream stream("File("); Nz::StringStream ss("File(");
if (file.IsOpen()) if (instance.IsOpen())
stream << "Path: " << file.GetPath(); ss << "Path: " << instance.GetPath();
stream << ')'; ss << ')';
lua.PushString(stream); lua.PushString(ss);
return 1; return 1;
}); });
} }

View File

@ -12,6 +12,18 @@ namespace Ndk
void LuaBinding::BindGraphics() void LuaBinding::BindGraphics()
{ {
/*********************************** Nz::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 ***********************************/ /*********************************** Nz::InstancedRenderable ***********************************/
/*********************************** Nz::Material ***********************************/ /*********************************** Nz::Material ***********************************/
@ -122,7 +134,7 @@ namespace Ndk
material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled); material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled);
material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled); material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled);
material.BindMethod("LoadFromFile", &Nz::Material::LoadFromFile); material.BindMethod("LoadFromFile", &Nz::Material::LoadFromFile, Nz::MaterialParams());
material.BindMethod("Reset", &Nz::Material::Reset); material.BindMethod("Reset", &Nz::Material::Reset);
@ -231,14 +243,14 @@ namespace Ndk
}); });
/*********************************** Nz::Model ***********************************/ /*********************************** Nz::Model ***********************************/
model.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::ModelRef* model) -> Nz::InstancedRenderableRef* model.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::ModelRef* modelRef) -> Nz::InstancedRenderableRef*
{ {
return reinterpret_cast<Nz::InstancedRenderableRef*>(model); //TODO: Make a ObjectRefCast return reinterpret_cast<Nz::InstancedRenderableRef*>(modelRef); //TODO: Make a ObjectRefCast
}); });
model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* model, std::size_t /*argumentCount*/) model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* instance, std::size_t /*argumentCount*/)
{ {
Nz::PlacementNew(model, Nz::Model::New()); Nz::PlacementNew(instance, Nz::Model::New());
return true; return true;
}); });
@ -260,14 +272,14 @@ namespace Ndk
model.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount); model.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount);
/*********************************** Nz::Sprite ***********************************/ /*********************************** Nz::Sprite ***********************************/
sprite.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::SpriteRef* sprite) -> Nz::InstancedRenderableRef* sprite.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::SpriteRef* spriteRef) -> Nz::InstancedRenderableRef*
{ {
return reinterpret_cast<Nz::InstancedRenderableRef*>(sprite); //TODO: Make a ObjectRefCast return reinterpret_cast<Nz::InstancedRenderableRef*>(spriteRef); //TODO: Make a ObjectRefCast
}); });
sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* sprite, std::size_t /*argumentCount*/) sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* instance, std::size_t /*argumentCount*/)
{ {
Nz::PlacementNew(sprite, Nz::Sprite::New()); Nz::PlacementNew(instance, Nz::Sprite::New());
return true; return true;
}); });
@ -281,13 +293,37 @@ namespace Ndk
sprite.BindMethod("SetColor", &Nz::Sprite::SetColor); sprite.BindMethod("SetColor", &Nz::Sprite::SetColor);
sprite.BindMethod("SetCornerColor", &Nz::Sprite::SetCornerColor); sprite.BindMethod("SetCornerColor", &Nz::Sprite::SetCornerColor);
sprite.BindMethod("SetDefaultMaterial", &Nz::Sprite::SetDefaultMaterial); sprite.BindMethod("SetDefaultMaterial", &Nz::Sprite::SetDefaultMaterial);
sprite.BindMethod("SetMaterial", &Nz::Sprite::SetMaterial, true);
sprite.BindMethod("SetOrigin", &Nz::Sprite::SetOrigin); sprite.BindMethod("SetOrigin", &Nz::Sprite::SetOrigin);
sprite.BindMethod("SetSize", (void(Nz::Sprite::*)(const Nz::Vector2f&)) &Nz::Sprite::SetSize); 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("SetTextureCoords", &Nz::Sprite::SetTextureCoords);
sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect); 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<Nz::MaterialRef*>(lua.ToUserdata(argIndex)), resizeSprite);
else
instance->SetMaterial(lua.Check<Nz::String>(&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<Nz::TextureRef*>(lua.ToUserdata(argIndex)), resizeSprite);
else
instance->SetTexture(lua.Check<Nz::String>(&argIndex), resizeSprite);
return 0;
});
/*********************************** Nz::SpriteLibrary ***********************************/ /*********************************** Nz::SpriteLibrary ***********************************/
spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get); spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get);
@ -323,6 +359,7 @@ namespace Ndk
void LuaBinding::RegisterGraphics(Nz::LuaInstance& instance) void LuaBinding::RegisterGraphics(Nz::LuaInstance& instance)
{ {
abstractViewer.Register(instance);
instancedRenderable.Register(instance); instancedRenderable.Register(instance);
material.Register(instance); material.Register(instance);
model.Register(instance); model.Register(instance);

View File

@ -14,22 +14,22 @@ namespace Ndk
void LuaBinding::BindMath() void LuaBinding::BindMath()
{ {
/*********************************** Nz::EulerAngles **********************************/ /*********************************** Nz::EulerAngles **********************************/
eulerAngles.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* angles, std::size_t argumentCount) eulerAngles.SetConstructor([] (Nz::LuaInstance& lua, Nz::EulerAnglesd* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U); std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
switch (argCount) switch (argCount)
{ {
case 0: case 0:
Nz::PlacementNew(angles, Nz::EulerAnglesd::Zero()); Nz::PlacementNew(instance, Nz::EulerAnglesd::Zero());
return true; return true;
case 1: case 1:
Nz::PlacementNew(angles, *static_cast<Nz::EulerAnglesd*>(lua.CheckUserdata(1, "EulerAngles"))); Nz::PlacementNew(instance, *static_cast<Nz::EulerAnglesd*>(lua.CheckUserdata(1, "EulerAngles")));
return true; return true;
case 3: case 3:
Nz::PlacementNew(angles, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3)); Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3));
return true; return true;
} }
@ -37,6 +37,9 @@ namespace Ndk
return false; return false;
}); });
eulerAngles.BindMethod("Normalize", &Nz::EulerAnglesd::Normalize);
eulerAngles.BindMethod("ToQuaternion", &Nz::EulerAnglesd::ToQuaternion);
eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString); eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString);
eulerAngles.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) eulerAngles.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance)
@ -154,7 +157,7 @@ namespace Ndk
return false; return false;
}); });
/*********************************** Nz::Matrix4 **********************************/ /*********************************** Nz::Matrix4 **********************************/
matrix4d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Matrix4d* matrix, std::size_t argumentCount) matrix4d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Matrix4d* matrix, std::size_t argumentCount)
{ {
@ -174,7 +177,7 @@ namespace Ndk
case 16: case 16:
{ {
double values[16]; double values[16];
for (std::size_t i = 0; i < 16; ++i) for (int i = 0; i < 16; ++i)
values[i] = lua.CheckNumber(i); values[i] = lua.CheckNumber(i);
Nz::PlacementNew(matrix, values); Nz::PlacementNew(matrix, values);
@ -227,7 +230,7 @@ namespace Ndk
{ {
Nz::Matrix4d result; Nz::Matrix4d result;
instance.GetTransposed(&result); instance.GetTransposed(&result);
return lua.Push(result); return lua.Push(result);
}); });
@ -360,7 +363,7 @@ namespace Ndk
}); });
/*********************************** Nz::Rect **********************************/ /*********************************** Nz::Rect **********************************/
rect.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* rect, std::size_t argumentCount) rect.SetConstructor([] (Nz::LuaInstance& lua, Nz::Rectd* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
@ -368,23 +371,23 @@ namespace Ndk
{ {
case 0: case 0:
case 4: case 4:
PlacementNew(rect, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0), lua.CheckNumber(4, 0.0)); PlacementNew(instance, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0), lua.CheckNumber(4, 0.0));
return true; return true;
case 1: case 1:
{ {
if (lua.IsOfType(1, "Rect")) if (lua.IsOfType(1, "Rect"))
PlacementNew(rect, *static_cast<Nz::Rectd*>(lua.ToUserdata(1))); PlacementNew(instance, *static_cast<Nz::Rectd*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, Nz::LuaType_Table)) 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 // 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<double>("x", 1), PlacementNew(instance, lua.CheckField<double>("x", 1),
lua.CheckField<double>("y", 1), lua.CheckField<double>("y", 1),
lua.CheckField<double>("width", 1), lua.CheckField<double>("width", 1),
lua.CheckField<double>("height", 1)); lua.CheckField<double>("height", 1));
} }
else if (lua.IsOfType(1, "Vector2")) else if (lua.IsOfType(1, "Vector2"))
PlacementNew(rect, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1))); PlacementNew(instance, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)));
else else
break; break;
@ -394,9 +397,9 @@ namespace Ndk
case 2: case 2:
{ {
if (lua.IsOfType(1, Nz::LuaType_Number) && lua.IsOfType(2, Nz::LuaType_Number)) if (lua.IsOfType(1, Nz::LuaType_Number) && lua.IsOfType(2, Nz::LuaType_Number))
PlacementNew(rect, lua.CheckNumber(1), lua.CheckNumber(2)); PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2));
else if (lua.IsOfType(1, "Vector2") && lua.IsOfType(2, "Vector2")) else if (lua.IsOfType(1, "Vector2") && lua.IsOfType(2, "Vector2"))
PlacementNew(rect, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)), *static_cast<Nz::Vector2d*>(lua.ToUserdata(2))); PlacementNew(instance, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)), *static_cast<Nz::Vector2d*>(lua.ToUserdata(2)));
else else
break; break;
@ -516,22 +519,22 @@ namespace Ndk
}); });
/*********************************** Nz::Quaternion **********************************/ /*********************************** Nz::Quaternion **********************************/
quaternion.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* quaternion, std::size_t argumentCount) quaternion.SetConstructor([] (Nz::LuaInstance& lua, Nz::Quaterniond* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
switch (argCount) switch (argCount)
{ {
case 0: case 0:
Nz::PlacementNew(quaternion, Nz::Quaterniond::Zero()); Nz::PlacementNew(instance, Nz::Quaterniond::Zero());
return true; return true;
case 1: case 1:
{ {
if (lua.IsOfType(1, "EulerAngles")) if (lua.IsOfType(1, "EulerAngles"))
Nz::PlacementNew(quaternion, *static_cast<Nz::EulerAnglesd*>(lua.ToUserdata(1))); Nz::PlacementNew(instance, *static_cast<Nz::EulerAnglesd*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, "Quaternion")) else if (lua.IsOfType(1, "Quaternion"))
Nz::PlacementNew(quaternion, *static_cast<Nz::Quaterniond*>(lua.ToUserdata(1))); Nz::PlacementNew(instance, *static_cast<Nz::Quaterniond*>(lua.ToUserdata(1)));
else else
break; break;
@ -539,11 +542,11 @@ namespace Ndk
} }
case 2: case 2:
Nz::PlacementNew(quaternion, lua.CheckNumber(1), *static_cast<Nz::Vector3d*>(lua.CheckUserdata(2, "Vector3"))); Nz::PlacementNew(instance, lua.CheckNumber(1), *static_cast<Nz::Vector3d*>(lua.CheckUserdata(2, "Vector3")));
return true; return true;
case 4: case 4:
Nz::PlacementNew(quaternion, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3), lua.CheckNumber(4)); Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3), lua.CheckNumber(4));
return true; return true;
default: default:
@ -554,8 +557,58 @@ namespace Ndk
return false; 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.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<Nz::Quaterniond>(&argIndex);
double length;
instance.Push(Nz::Quaterniond::Normalize(quat, &length));
instance.Push(length);
return 2;
});
quaternion.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) quaternion.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance)
{ {
std::size_t length; std::size_t length;
@ -904,5 +957,12 @@ namespace Ndk
rect.Register(instance); rect.Register(instance);
vector2d.Register(instance); vector2d.Register(instance);
vector3d.Register(instance); vector3d.Register(instance);
quaternion.PushGlobalTable(instance);
{
instance.PushField("Identity", Nz::Quaterniond::Identity());
instance.PushField("Zero", Nz::Quaterniond::Zero());
}
instance.Pop();
} }
} }

View File

@ -21,7 +21,7 @@ namespace Ndk
abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes); abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes);
/*********************************** Nz::IpAddress **********************************/ /*********************************** Nz::IpAddress **********************************/
ipAddress.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* address, std::size_t argumentCount) ipAddress.SetConstructor([] (Nz::LuaInstance& lua, Nz::IpAddress* instance, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 9U); std::size_t argCount = std::min<std::size_t>(argumentCount, 9U);
@ -29,11 +29,11 @@ namespace Ndk
switch (argCount) switch (argCount)
{ {
case 0: case 0:
Nz::PlacementNew(address); Nz::PlacementNew(instance);
return true; return true;
case 1: case 1:
Nz::PlacementNew(address, lua.CheckString(argIndex)); Nz::PlacementNew(instance, lua.CheckString(argIndex));
return true; return true;
case 4: case 4:
@ -45,7 +45,7 @@ namespace Ndk
Nz::UInt8 d = lua.Check<Nz::UInt8>(&argIndex); Nz::UInt8 d = lua.Check<Nz::UInt8>(&argIndex);
Nz::UInt16 port = lua.Check<Nz::UInt16>(&argIndex, 0); Nz::UInt16 port = lua.Check<Nz::UInt16>(&argIndex, 0);
Nz::PlacementNew(address, a, b, c, d, port); Nz::PlacementNew(instance, a, b, c, d, port);
return true; return true;
} }
@ -62,7 +62,7 @@ namespace Ndk
Nz::UInt16 h = lua.Check<Nz::UInt16>(&argIndex); Nz::UInt16 h = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 port = lua.Check<Nz::UInt16>(&argIndex, 0); Nz::UInt16 port = lua.Check<Nz::UInt16>(&argIndex, 0);
Nz::PlacementNew(address, a, b, c, d, e, f, g, h, port); Nz::PlacementNew(instance, a, b, c, d, e, f, g, h, port);
return true; return true;
} }
} }
@ -199,7 +199,7 @@ namespace Ndk
instance.PushField("Unknown", Nz::ResolveError_Unknown); instance.PushField("Unknown", Nz::ResolveError_Unknown);
} }
instance.SetGlobal("ResolveError"); instance.SetGlobal("ResolveError");
// Nz::SocketError // Nz::SocketError
static_assert(Nz::SocketError_Max + 1 == 15, "Nz::ResolveError has been updated but change was not reflected to Lua binding"); static_assert(Nz::SocketError_Max + 1 == 15, "Nz::ResolveError has been updated but change was not reflected to Lua binding");
instance.PushTable(0, 15); instance.PushTable(0, 15);

View File

@ -13,14 +13,14 @@ namespace Ndk
void LuaBinding::BindRenderer() void LuaBinding::BindRenderer()
{ {
/*********************************** Nz::Texture ***********************************/ /*********************************** Nz::Texture ***********************************/
texture.Inherit<Nz::AbstractImageRef>(abstractImage, [] (Nz::TextureRef* texture) -> Nz::AbstractImageRef* texture.Inherit<Nz::AbstractImageRef>(abstractImage, [] (Nz::TextureRef* textureRef) -> Nz::AbstractImageRef*
{ {
return reinterpret_cast<Nz::AbstractImageRef*>(texture); //TODO: Make a ObjectRefCast return reinterpret_cast<Nz::AbstractImageRef*>(textureRef); //TODO: Make a ObjectRefCast
}); });
texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* texture, std::size_t /*argumentCount*/) texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* instance, std::size_t /*argumentCount*/)
{ {
Nz::PlacementNew(texture, Nz::Texture::New()); Nz::PlacementNew(instance, Nz::Texture::New());
return true; return true;
}); });
@ -28,7 +28,7 @@ namespace Ndk
texture.BindMethod("Destroy", &Nz::Texture::Destroy); texture.BindMethod("Destroy", &Nz::Texture::Destroy);
//texture.BindMethod("Download", &Nz::Texture::Download); //texture.BindMethod("Download", &Nz::Texture::Download);
texture.BindMethod("EnableMipmapping", &Nz::Texture::EnableMipmapping); texture.BindMethod("EnableMipmapping", &Nz::Texture::EnableMipmapping);
texture.BindMethod("EnsureMipmapsUpdate", &Nz::Texture::EnsureMipmapsUpdate); texture.BindMethod("EnsureMipmapsUpdate", &Nz::Texture::EnsureMipmapsUpdate);
texture.BindMethod("HasMipmaps", &Nz::Texture::HasMipmaps); texture.BindMethod("HasMipmaps", &Nz::Texture::HasMipmaps);
@ -73,4 +73,4 @@ namespace Ndk
{ {
texture.Register(instance); texture.Register(instance);
} }
} }

View File

@ -1,4 +1,4 @@
// Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot // Copyright (C) 2016 Jérôme Leclercq, Arnaud Cadot
// This file is part of the "Nazara Development Kit" // This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp // For conditions of distribution and use, see copyright notice in Prerequesites.hpp
@ -25,9 +25,9 @@ namespace Ndk
application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled); application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled);
#endif #endif
application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application, std::size_t /*argumentCount*/) -> int application.BindMethod("AddWorld", [] (Nz::LuaInstance& lua, Application* instance, std::size_t /*argumentCount*/) -> int
{ {
instance.Push(application->AddWorld().CreateHandle()); lua.Push(instance->AddWorld().CreateHandle());
return 1; return 1;
}); });
@ -59,7 +59,7 @@ namespace Ndk
console.BindMethod("SetCharacterSize", &Console::SetCharacterSize); console.BindMethod("SetCharacterSize", &Console::SetCharacterSize);
console.BindMethod("SetSize", &Console::SetSize); console.BindMethod("SetSize", &Console::SetSize);
console.BindMethod("SetTextFont", &Console::SetTextFont); console.BindMethod("SetTextFont", &Console::SetTextFont);
console.BindMethod("Show", &Console::Show, true); console.BindMethod("Show", &Console::Show, true);
#endif #endif
@ -138,8 +138,27 @@ namespace Ndk
#ifndef NDK_SERVER #ifndef NDK_SERVER
/*********************************** Ndk::CameraComponent **********************************/
cameraComponent.Inherit<Nz::AbstractViewer>(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 **********************************/ /*********************************** Ndk::GraphicsComponent **********************************/
graphicsComponent.BindMethod("Attach", [] (Nz::LuaInstance& lua, Ndk::GraphicsComponent *gfxComponent, std::size_t argumentCount) -> int 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, int renderOrder = 0);
@ -153,7 +172,7 @@ namespace Ndk
case 1: case 1:
{ {
int argIndex = 2; int argIndex = 2;
gfxComponent->Attach(lua.Check<Nz::InstancedRenderableRef>(&argIndex)); instance->Attach(lua.Check<Nz::InstancedRenderableRef>(&argIndex));
return 0; return 0;
} }
@ -166,13 +185,13 @@ namespace Ndk
{ {
int renderOrder = lua.Check<int>(&argIndex); int renderOrder = lua.Check<int>(&argIndex);
gfxComponent->Attach(renderable, renderOrder); instance->Attach(renderable, renderOrder);
} }
else if (lua.IsOfType(argIndex, "Matrix4")) else if (lua.IsOfType(argIndex, "Matrix4"))
{ {
Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex); Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex);
gfxComponent->Attach(renderable, localMatrix); instance->Attach(renderable, localMatrix);
} }
else else
break; break;
@ -187,7 +206,7 @@ namespace Ndk
Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex); Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex);
int renderOrder = lua.Check<int>(&argIndex); int renderOrder = lua.Check<int>(&argIndex);
gfxComponent->Attach(renderable, localMatrix, renderOrder); instance->Attach(renderable, localMatrix, renderOrder);
return 0; return 0;
} }
} }
@ -205,6 +224,7 @@ namespace Ndk
BindComponent<VelocityComponent>("Velocity"); BindComponent<VelocityComponent>("Velocity");
#ifndef NDK_SERVER #ifndef NDK_SERVER
BindComponent<CameraComponent>("Camera");
BindComponent<GraphicsComponent>("Graphics"); BindComponent<GraphicsComponent>("Graphics");
#endif #endif
} }
@ -225,6 +245,7 @@ namespace Ndk
world.Register(instance); world.Register(instance);
#ifndef NDK_SERVER #ifndef NDK_SERVER
cameraComponent.Register(instance);
console.Register(instance); console.Register(instance);
graphicsComponent.Register(instance); graphicsComponent.Register(instance);
#endif #endif

View File

@ -25,20 +25,20 @@ namespace Ndk
abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed); abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed);
abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap); abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap);
abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage, std::size_t argumentCount) -> int abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U); std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
switch (argCount) switch (argCount)
{ {
case 0: case 0:
return lua.Push(abstractImage->GetMemoryUsage()); return lua.Push(instance->GetMemoryUsage());
case 1: case 1:
{ {
int argIndex = 2; int argIndex = 2;
Nz::UInt8 level(lua.Check<Nz::UInt8>(&argIndex)); Nz::UInt8 level(lua.Check<Nz::UInt8>(&argIndex));
return lua.Push(abstractImage->GetMemoryUsage(level)); return lua.Push(instance->GetMemoryUsage(level));
} }
} }
@ -46,7 +46,7 @@ namespace Ndk
return 0; return 0;
}); });
abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage, std::size_t argumentCount) -> int abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 6U); std::size_t argCount = std::min<std::size_t>(argumentCount, 6U);
int argIndex = 2; int argIndex = 2;
@ -62,7 +62,7 @@ namespace Ndk
Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0); Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0);
///TODO: Buffer checks (Nz::ByteBufferView ?) ///TODO: Buffer checks (Nz::ByteBufferView ?)
return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level)); return lua.Push(instance->Update(pixels, srcWidth, srcHeight, level));
} }
/* Disabled until Box and Rect have been ported /* Disabled until Box and Rect have been ported
else if (lua.IsOfType(2, "Box")) else if (lua.IsOfType(2, "Box"))
@ -93,9 +93,9 @@ namespace Ndk
}); });
/*********************************** Nz::Font **********************************/ /*********************************** Nz::Font **********************************/
font.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::FontRef* font, std::size_t /*argumentCount*/) font.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::FontRef* instance, std::size_t /*argumentCount*/)
{ {
Nz::PlacementNew(font, Nz::Font::New()); Nz::PlacementNew(instance, Nz::Font::New());
return true; return true;
}); });
@ -153,6 +153,10 @@ namespace Ndk
font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder); font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder);
font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize); font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize);
/*********************************** Nz::Keyboard **********************************/
keyboard.BindStaticMethod("GetKeyName", &Nz::Keyboard::GetKeyName);
keyboard.BindStaticMethod("IsKeyPressed", &Nz::Keyboard::IsKeyPressed);
/*********************************** Nz::Node **********************************/ /*********************************** Nz::Node **********************************/
node.BindMethod("GetBackward", &Nz::Node::GetBackward); node.BindMethod("GetBackward", &Nz::Node::GetBackward);
//nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds); //nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds);
@ -199,29 +203,29 @@ namespace Ndk
node.BindMethod("SetPosition", (void(Nz::Node::*)(const Nz::Vector3f&, Nz::CoordSys)) &Nz::Node::SetPosition, Nz::CoordSys_Local); 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("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 node.BindMethod("Move", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
Nz::Vector3f offset = lua.Check<Nz::Vector3f>(&argIndex); Nz::Vector3f offset = lua.Check<Nz::Vector3f>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local); Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
node.Move(offset, coordSys); instance.Move(offset, coordSys);
return 0; return 0;
}); });
node.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t /*argumentCount*/) -> int node.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 2; int argIndex = 2;
Nz::Quaternionf rotation = lua.Check<Nz::Quaternionf>(&argIndex); Nz::Quaternionf rotation = lua.Check<Nz::Quaternionf>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local); Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
node.Rotate(rotation, coordSys); instance.Rotate(rotation, coordSys);
return 0; return 0;
}); });
node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
@ -231,15 +235,15 @@ namespace Ndk
case 1: case 1:
{ {
if (lua.IsOfType(argIndex, Nz::LuaType_Number)) if (lua.IsOfType(argIndex, Nz::LuaType_Number))
node.Scale(lua.Check<float>(&argIndex)); instance.Scale(lua.Check<float>(&argIndex));
else else
node.Scale(lua.Check<Nz::Vector3f>(&argIndex)); instance.Scale(lua.Check<Nz::Vector3f>(&argIndex));
return 0; return 0;
} }
case 3: case 3:
node.Scale(lua.Check<Nz::Vector3f>(&argIndex)); instance.Scale(lua.Check<Nz::Vector3f>(&argIndex));
return 0; return 0;
} }
@ -247,7 +251,7 @@ namespace Ndk
return 0; return 0;
}); });
node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
@ -261,10 +265,10 @@ namespace Ndk
{ {
float scale = lua.Check<float>(&argIndex); float scale = lua.Check<float>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local); Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
node.SetScale(scale, coordSys); instance.SetScale(scale, coordSys);
} }
else else
node.SetScale(lua.Check<Nz::Vector3f>(&argIndex)); instance.SetScale(lua.Check<Nz::Vector3f>(&argIndex));
return 0; return 0;
} }
@ -275,7 +279,7 @@ namespace Ndk
Nz::Vector3f scale = lua.Check<Nz::Vector3f>(&argIndex); Nz::Vector3f scale = lua.Check<Nz::Vector3f>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local); Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
node.SetScale(scale, coordSys); instance.SetScale(scale, coordSys);
return 0; return 0;
} }
} }
@ -284,7 +288,7 @@ namespace Ndk
return 0; return 0;
}); });
node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& node, std::size_t argumentCount) -> int node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
@ -294,16 +298,16 @@ namespace Ndk
case 1: case 1:
{ {
if (lua.IsOfType(argIndex, Nz::LuaType_Number)) if (lua.IsOfType(argIndex, Nz::LuaType_Number))
node.SetInitialScale(lua.Check<float>(&argIndex)); instance.SetInitialScale(lua.Check<float>(&argIndex));
else else
node.SetInitialScale(lua.Check<Nz::Vector2f>(&argIndex)); instance.SetInitialScale(lua.Check<Nz::Vector2f>(&argIndex));
return 0; return 0;
} }
case 2: case 2:
case 3: case 3:
node.SetInitialScale(lua.Check<Nz::Vector3f>(&argIndex)); instance.SetInitialScale(lua.Check<Nz::Vector3f>(&argIndex));
return 0; return 0;
} }
@ -322,6 +326,92 @@ namespace Ndk
{ {
abstractImage.Register(instance); abstractImage.Register(instance);
font.Register(instance); font.Register(instance);
keyboard.Register(instance);
node.Register(instance); node.Register(instance);
keyboard.PushGlobalTable(instance);
{
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();
} }
} }

View File

@ -9,14 +9,18 @@
#include <Nazara/Graphics/Graphics.hpp> #include <Nazara/Graphics/Graphics.hpp>
#include <Nazara/Lua/Lua.hpp> #include <Nazara/Lua/Lua.hpp>
#include <Nazara/Noise/Noise.hpp> #include <Nazara/Noise/Noise.hpp>
#include <Nazara/Physics2D/Physics2D.hpp>
#include <Nazara/Physics3D/Physics3D.hpp> #include <Nazara/Physics3D/Physics3D.hpp>
#include <Nazara/Utility/Utility.hpp> #include <Nazara/Utility/Utility.hpp>
#include <NDK/Algorithm.hpp> #include <NDK/Algorithm.hpp>
#include <NDK/BaseSystem.hpp> #include <NDK/BaseSystem.hpp>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/CollisionComponent3D.hpp> #include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/NodeComponent.hpp> #include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp> #include <NDK/Components/PhysicsComponent3D.hpp>
#include <NDK/Components/VelocityComponent.hpp> #include <NDK/Components/VelocityComponent.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
#include <NDK/Systems/PhysicsSystem3D.hpp> #include <NDK/Systems/PhysicsSystem3D.hpp>
#include <NDK/Systems/VelocitySystem.hpp> #include <NDK/Systems/VelocitySystem.hpp>
@ -68,6 +72,7 @@ namespace Ndk
Nz::Lua::Initialize(); Nz::Lua::Initialize();
Nz::Noise::Initialize(); Nz::Noise::Initialize();
Nz::Physics2D::Initialize();
Nz::Physics3D::Initialize(); Nz::Physics3D::Initialize();
Nz::Utility::Initialize(); Nz::Utility::Initialize();
@ -83,9 +88,11 @@ namespace Ndk
BaseComponent::Initialize(); BaseComponent::Initialize();
// Shared components // Shared components
InitializeComponent<CollisionComponent3D>("NdkColli"); InitializeComponent<CollisionComponent2D>("NdkColl2");
InitializeComponent<CollisionComponent3D>("NdkColl3");
InitializeComponent<NodeComponent>("NdkNode"); InitializeComponent<NodeComponent>("NdkNode");
InitializeComponent<PhysicsComponent3D>("NdkPhys"); InitializeComponent<PhysicsComponent2D>("NdkPhys2");
InitializeComponent<PhysicsComponent3D>("NdkPhys3");
InitializeComponent<VelocityComponent>("NdkVeloc"); InitializeComponent<VelocityComponent>("NdkVeloc");
#ifndef NDK_SERVER #ifndef NDK_SERVER
@ -103,6 +110,7 @@ namespace Ndk
BaseSystem::Initialize(); BaseSystem::Initialize();
// Shared systems // Shared systems
InitializeSystem<PhysicsSystem2D>();
InitializeSystem<PhysicsSystem3D>(); InitializeSystem<PhysicsSystem3D>();
InitializeSystem<VelocitySystem>(); InitializeSystem<VelocitySystem>();
@ -161,6 +169,7 @@ namespace Ndk
// Shared modules // Shared modules
Nz::Lua::Uninitialize(); Nz::Lua::Uninitialize();
Nz::Noise::Uninitialize(); Nz::Noise::Uninitialize();
Nz::Physics2D::Uninitialize();
Nz::Physics3D::Uninitialize(); Nz::Physics3D::Uninitialize();
Nz::Utility::Uninitialize(); Nz::Utility::Uninitialize();

View File

@ -25,6 +25,7 @@ namespace Ndk
ListenerSystem::ListenerSystem() ListenerSystem::ListenerSystem()
{ {
Requires<ListenerComponent, NodeComponent>(); Requires<ListenerComponent, NodeComponent>();
SetUpdateOrder(100); //< Update last, after every movement is done
} }
/*! /*!
@ -33,11 +34,9 @@ namespace Ndk
* \param elapsedTime Delta time used for the update * \param elapsedTime Delta time used for the update
*/ */
void ListenerSystem::OnUpdate(float elapsedTime) void ListenerSystem::OnUpdate(float /*elapsedTime*/)
{ {
NazaraUnused(elapsedTime); std::size_t activeListenerCount = 0;
unsigned int activeListenerCount = 0;
for (const Ndk::EntityHandle& entity : GetEntities()) for (const Ndk::EntityHandle& entity : GetEntities())
{ {

View File

@ -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 <NDK/Systems/PhysicsSystem2D.hpp>
#include <Nazara/Physics2D/RigidBody2D.hpp>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp>
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<NodeComponent>();
RequiresAny<CollisionComponent2D, PhysicsComponent2D>();
Excludes<PhysicsComponent3D>();
}
/*!
* \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<Nz::PhysWorld2D>();
}
/*!
* \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<PhysicsComponent2D>()) ? m_staticObjects : m_dynamicObjects;
entities.Remove(entity);
}
auto& entities = (entity->HasComponent<PhysicsComponent2D>()) ? 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<NodeComponent>();
PhysicsComponent2D& phys = entity->GetComponent<PhysicsComponent2D>();
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<CollisionComponent2D>();
NodeComponent& node = entity->GetComponent<NodeComponent>();
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;
}

View File

@ -6,6 +6,7 @@
#include <Nazara/Physics3D/RigidBody3D.hpp> #include <Nazara/Physics3D/RigidBody3D.hpp>
#include <NDK/Components/CollisionComponent3D.hpp> #include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/NodeComponent.hpp> #include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp> #include <NDK/Components/PhysicsComponent3D.hpp>
namespace Ndk namespace Ndk
@ -27,6 +28,7 @@ namespace Ndk
{ {
Requires<NodeComponent>(); Requires<NodeComponent>();
RequiresAny<CollisionComponent3D, PhysicsComponent3D>(); RequiresAny<CollisionComponent3D, PhysicsComponent3D>();
Excludes<PhysicsComponent2D>();
} }
/*! /*!
@ -90,7 +92,7 @@ namespace Ndk
NodeComponent& node = entity->GetComponent<NodeComponent>(); NodeComponent& node = entity->GetComponent<NodeComponent>();
PhysicsComponent3D& phys = entity->GetComponent<PhysicsComponent3D>(); PhysicsComponent3D& phys = entity->GetComponent<PhysicsComponent3D>();
Nz::RigidBody3D& physObj = phys.GetPhysObject(); Nz::RigidBody3D& physObj = phys.GetRigidBody();
node.SetRotation(physObj.GetRotation(), Nz::CoordSys_Global); node.SetRotation(physObj.GetRotation(), Nz::CoordSys_Global);
node.SetPosition(physObj.GetPosition(), Nz::CoordSys_Global); node.SetPosition(physObj.GetPosition(), Nz::CoordSys_Global);
} }

View File

@ -35,7 +35,8 @@ namespace Ndk
{ {
ChangeRenderTechnique<Nz::ForwardRenderTechnique>(); ChangeRenderTechnique<Nz::ForwardRenderTechnique>();
SetDefaultBackground(Nz::ColorBackground::New()); 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
} }
/*! /*!
@ -116,10 +117,8 @@ namespace Ndk
* \param elapsedTime Delta time used for the update * \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 // Invalidate every renderable if the coordinate system changed
if (m_coordinateSystemInvalidated) if (m_coordinateSystemInvalidated)
{ {

View File

@ -24,8 +24,9 @@ namespace Ndk
VelocitySystem::VelocitySystem() VelocitySystem::VelocitySystem()
{ {
Requires<NodeComponent, VelocityComponent>();
Excludes<PhysicsComponent3D>(); Excludes<PhysicsComponent3D>();
Requires<NodeComponent, VelocityComponent>();
SetUpdateOrder(10); //< Since some systems may want to stop us
} }
/*! /*!

View File

@ -5,6 +5,7 @@
#include <NDK/World.hpp> #include <NDK/World.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <NDK/BaseComponent.hpp> #include <NDK/BaseComponent.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
#include <NDK/Systems/PhysicsSystem3D.hpp> #include <NDK/Systems/PhysicsSystem3D.hpp>
#include <NDK/Systems/VelocitySystem.hpp> #include <NDK/Systems/VelocitySystem.hpp>
@ -40,6 +41,7 @@ namespace Ndk
void World::AddDefaultSystems() void World::AddDefaultSystems()
{ {
AddSystem<PhysicsSystem2D>();
AddSystem<PhysicsSystem3D>(); AddSystem<PhysicsSystem3D>();
AddSystem<VelocitySystem>(); AddSystem<VelocitySystem>();
@ -67,7 +69,7 @@ namespace Ndk
else else
{ {
// We allocate a new entity // We allocate a new entity
id = m_entities.size(); id = static_cast<Ndk::EntityId>(m_entities.size());
// We can't use emplace_back due to the scope // We can't use emplace_back due to the scope
m_entities.push_back(Entity(this, id)); m_entities.push_back(Entity(this, id));
@ -172,6 +174,9 @@ namespace Ndk
void World::Update() void World::Update()
{ {
if (!m_orderedSystemsUpdated)
ReorderSystems();
// Handle killed entities before last call // Handle killed entities before last call
for (std::size_t i = m_killedEntities.FindFirst(); i != m_killedEntities.npos; i = m_killedEntities.FindNext(i)) 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(); Nz::Bitset<>& removedComponents = entity->GetRemovedComponentBits();
for (std::size_t j = removedComponents.FindFirst(); j != m_dirtyEntities.npos; j = removedComponents.FindNext(j)) for (std::size_t j = removedComponents.FindFirst(); j != m_dirtyEntities.npos; j = removedComponents.FindNext(j))
entity->DestroyComponent(j); entity->DestroyComponent(static_cast<Ndk::ComponentIndex>(j));
removedComponents.Reset(); 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? // Is our entity already part of this system?
bool partOfSystem = system->HasEntity(entity); bool partOfSystem = system->HasEntity(entity);
@ -249,4 +250,22 @@ namespace Ndk
} }
m_dirtyEntities.Reset(); 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;
}
} }

View File

@ -1 +1 @@
premake4 codeblocks premake5 codeblocks

View File

@ -0,0 +1,4 @@
dofile("codeblocks/_codeblocks.lua")
dofile("codeblocks/codeblocks.lua")
ACTION.Manual = true

View File

@ -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
}

View File

@ -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('"', '&quot;')
result = result:gsub('<', '&lt;')
result = result:gsub('>', '&gt;')
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")

View File

@ -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('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>')
_p('<CodeBlocks_project_file>')
_p(1,'<FileVersion major="1" minor="6" />')
-- write project block header
_p(1,'<Project>')
_p(2,'<Option title="%s" />', prj.name)
_p(2,'<Option pch_mode="2" />')
end
function m.footer(prj)
-- write project block footer
_p(1,'</Project>')
_p('</CodeBlocks_project_file>')
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,'<Build>')
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,'<Target title="%s">', cfg.longname)
_p(4,'<Option output="%s" prefix_auto="0" extension_auto="0" />', p.esc(cfg.buildtarget.relpath))
if cfg.debugdir then
_p(4,'<Option working_dir="%s" />', p.esc(path.getrelative(prj.location, cfg.debugdir)))
end
_p(4,'<Option object_output="%s" />', p.esc(path.getrelative(prj.location, cfg.objdir)))
-- identify the type of binary
local types = { WindowedApp = 0, ConsoleApp = 1, StaticLib = 2, SharedLib = 3 }
_p(4,'<Option type="%d" />', types[cfg.kind])
_p(4,'<Option compiler="%s" />', m.getcompilername(cfg))
if (cfg.kind == "SharedLib") then
_p(4,'<Option createDefFile="0" />')
_p(4,'<Option createStaticLib="%s" />', iif(cfg.flags.NoImportLib, 0, 1))
end
-- begin compiler block --
_p(4,'<Compiler>')
for _,flag in ipairs(table.join(compiler.getcflags(cfg), compiler.getcxxflags(cfg), compiler.getdefines(cfg.defines), cfg.buildoptions)) do
_p(5,'<Add option="%s" />', p.esc(flag))
end
if not cfg.flags.NoPCH and cfg.pchheader then
_p(5,'<Add option="-Winvalid-pch" />')
_p(5,'<Add option="-include &quot;%s&quot;" />', p.esc(cfg.pchheader))
end
for _,v in ipairs(cfg.includedirs) do
_p(5,'<Add directory="%s" />', p.esc(path.getrelative(prj.location, v)))
end
_p(4,'</Compiler>')
-- end compiler block --
-- begin linker block --
_p(4,'<Linker>')
for _,flag in ipairs(table.join(compiler.getldflags(cfg), cfg.linkoptions)) do
_p(5,'<Add option="%s" />', p.esc(flag))
end
for _,v in ipairs(config.getlinks(cfg, "all", "directory")) do
_p(5,'<Add directory="%s" />', p.esc(v))
end
for _,v in ipairs(config.getlinks(cfg, "all", "basename")) do
_p(5,'<Add library="%s" />', p.esc(v))
end
_p(4,'</Linker>')
-- end linker block --
-- begin resource compiler block --
if config.findfile(cfg, ".rc") then
_p(4,'<ResourceCompiler>')
for _,v in ipairs(cfg.includedirs) do
_p(5,'<Add directory="%s" />', p.esc(v))
end
for _,v in ipairs(cfg.resincludedirs) do
_p(5,'<Add directory="%s" />', p.esc(v))
end
_p(4,'</ResourceCompiler>')
end
-- end resource compiler block --
-- begin build steps --
if #cfg.prebuildcommands > 0 or #cfg.postbuildcommands > 0 then
_p(4,'<ExtraCommands>')
for _,v in ipairs(cfg.prebuildcommands) do
_p(5,'<Add before="%s" />', p.esc(v))
end
for _,v in ipairs(cfg.postbuildcommands) do
_p(5,'<Add after="%s" />', p.esc(v))
end
_p(4,'</ExtraCommands>')
end
-- end build steps --
_p(3,'</Target>')
end
end
_p(2,'</Build>')
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,'<Unit filename="%s">', node.relpath)
else
_p(2,'<Unit filename="%s">', node.name)
_p(3,'<Option virtualFolder="%s" />', path.getdirectory(node.vpath))
end
if path.isresourcefile(node.name) then
_p(3,'<Option compilerVar="WINDRES" />')
elseif path.iscfile(node.name) and prj.language == "C++" then
_p(3,'<Option compilerVar="CC" />')
end
if not prj.flags.NoPCH and node.name == pchheader then
_p(3,'<Option compilerVar="%s" />', iif(prj.language == "C", "CC", "CPP"))
_p(3,'<Option compile="1" />')
_p(3,'<Option weight="0" />')
_p(3,'<Add option="-x c++-header" />')
end
_p(2,'</Unit>')
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,'<debugger>')
_p(4,'<remote_debugging target="%s">', 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 .. '&#x0A;' end
end
_p(5,'<options additional_cmds_before="%s" />',args)
_p(4,'</remote_debugging>')
_p(3,'</debugger>')
else
error('Sorry at this moment there is no support for debug environment variables with this debugger and codeblocks')
end
end
end
end

View File

@ -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('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>')
_p('<CodeBlocks_workspace_file>')
_p(1,'<Workspace title="%s">', 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,'<Project filename="%s.cbp"%s>', fname, active)
for _,dep in ipairs(project.getdependencies(prj)) do
_p(3,'<Depends filename="%s.cbp" />', path.join(path.getrelative(wks.location, dep.location), dep.name))
end
_p(2,'</Project>')
end
_p(1,'</Workspace>')
_p('</CodeBlocks_workspace_file>')
end

View File

@ -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) function NazaraBuild:AddExecutablePath(path)
self.ExecutableDir[path] = true self.ExecutableDir[path] = true
@ -9,21 +12,47 @@ function NazaraBuild:AddInstallPath(path)
self.InstallDir[path] = true self.InstallDir[path] = true
end 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() 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 return -- Alors l'utilisateur voulait probablement savoir comment utiliser le programme, on ne fait rien
end end
local platformData local platformData
if (os.is64bit()) then if (os.is64bit()) then
platformData = {"x64", "x32"} platformData = {"x64", "x86"}
else else
platformData = {"x32", "x64"} platformData = {"x86", "x64"}
end end
if (self.Actions[_ACTION] == nil) then if (self.Actions[_ACTION] == nil) then
local makeLibDir = os.is("windows") and "mingw" or "gmake"
if (self.Config["BuildDependencies"]) then if (self.Config["BuildDependencies"]) then
workspace("NazaraExtlibs") workspace("NazaraExtlibs")
platforms(platformData) platforms(platformData)
@ -34,63 +63,19 @@ function NazaraBuild:Execute()
"ReleaseStatic" "ReleaseStatic"
}) })
self:PrepareGeneric()
self:FilterLibDirectory("../extlibs/lib/", targetdir)
filter(clangGccActions)
buildoptions("-U__STRICT_ANSI__")
filter({})
includedirs("../extlibs/include") includedirs("../extlibs/include")
libdirs("../extlibs/lib/common") libdirs("../extlibs/lib/common")
location(_ACTION) location(_ACTION)
kind("StaticLib") 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 for k, libTable in ipairs(self.OrderedExtLibs) do
project(libTable.Name) project(libTable.Name)
@ -105,25 +90,30 @@ function NazaraBuild:Execute()
includedirs(libTable.Includes) includedirs(libTable.Includes)
links(libTable.Libraries) links(libTable.Libraries)
configuration("x32") filter("architecture:x86")
libdirs(libTable.LibraryPaths.x86) libdirs(libTable.LibraryPaths.x86)
configuration("x64") filter("architecture:x86_64")
libdirs(libTable.LibraryPaths.x64) libdirs(libTable.LibraryPaths.x64)
for k,v in pairs(libTable.ConfigurationLibraries) do for k,v in pairs(libTable.ConfigurationLibraries) do
configuration(k) filter(k)
links(v) links(v)
end end
configuration({}) filter({})
end end
end end
-- Start defining projects
workspace("NazaraEngine") workspace("NazaraEngine")
platforms(platformData) platforms(platformData)
-- Configuration générale self:PrepareMainWorkspace()
-- Add lib/conf/arch to library search path
self:FilterLibDirectory("../lib/", libdirs)
configurations({ configurations({
-- "DebugStatic", -- "DebugStatic",
-- "ReleaseStatic", -- "ReleaseStatic",
@ -134,36 +124,7 @@ function NazaraBuild:Execute()
language("C++") language("C++")
location(_ACTION) location(_ACTION)
configuration("Debug*") -- Modules
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
if (_OPTIONS["united"]) then if (_OPTIONS["united"]) then
project("NazaraEngine") project("NazaraEngine")
end end
@ -175,78 +136,12 @@ function NazaraBuild:Execute()
location(_ACTION .. "/modules") location(_ACTION .. "/modules")
defines("NAZARA_BUILD")
includedirs({ includedirs({
"../include", "../include",
"../src/", "../src/",
"../extlibs/include" "../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) files(moduleTable.Files)
excludes(moduleTable.FilesExcluded) excludes(moduleTable.FilesExcluded)
@ -255,12 +150,29 @@ function NazaraBuild:Execute()
includedirs(moduleTable.Includes) includedirs(moduleTable.Includes)
links(moduleTable.Libraries) 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 for k,v in pairs(moduleTable.ConfigurationLibraries) do
configuration(k) filter(k)
links(v) links(v)
end end
configuration({}) filter({})
end end
-- Tools -- Tools
@ -288,7 +200,7 @@ function NazaraBuild:Execute()
kind("WindowedApp") kind("WindowedApp")
end end
else else
assert(false, "Invalid tool Kind") assert(false, "Invalid tool kind")
end end
includedirs({ includedirs({
@ -296,94 +208,10 @@ function NazaraBuild:Execute()
"../extlibs/include" "../extlibs/include"
}) })
libdirs("../lib") libdirs({
libdirs("../extlibs/lib/common") "../extlibs/lib/common",
"../lib"
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({})
files(toolTable.Files) files(toolTable.Files)
excludes(toolTable.FilesExcluded) excludes(toolTable.FilesExcluded)
@ -393,12 +221,25 @@ function NazaraBuild:Execute()
includedirs(toolTable.Includes) includedirs(toolTable.Includes)
links(toolTable.Libraries) 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 for k,v in pairs(toolTable.ConfigurationLibraries) do
configuration(k) filter(k)
links(v) links(v)
end end
configuration({}) filter({})
end end
for k, exampleTable in ipairs(self.OrderedExamples) do for k, exampleTable in ipairs(self.OrderedExamples) do
@ -429,7 +270,6 @@ function NazaraBuild:Execute()
"../extlibs/include" "../extlibs/include"
}) })
libdirs("../lib") libdirs("../lib")
targetdir(destPath)
files(exampleTable.Files) files(exampleTable.Files)
excludes(exampleTable.FilesExcluded) excludes(exampleTable.FilesExcluded)
@ -438,41 +278,14 @@ function NazaraBuild:Execute()
flags(exampleTable.Flags) flags(exampleTable.Flags)
includedirs(exampleTable.Includes) includedirs(exampleTable.Includes)
links(exampleTable.Libraries) links(exampleTable.Libraries)
targetdir(destPath)
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")
for k,v in pairs(exampleTable.ConfigurationLibraries) do for k,v in pairs(exampleTable.ConfigurationLibraries) do
configuration(k) filter(k)
links(v) links(v)
end end
configuration({}) filter({})
end end
end end
end end
@ -712,39 +525,37 @@ function NazaraBuild:LoadConfig()
end end
function NazaraBuild:MakeInstallCommands(infoTable) function NazaraBuild:MakeInstallCommands(infoTable)
if (PremakeVersion < 50) then
return
end
if (os.is("windows")) then 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 for k,v in pairs(self.InstallDir) do
local destPath = path.translate(path.isabsolute(k) and k or "../../" .. k) 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 end
for k,fileName in pairs(table.join(infoTable.Libraries, infoTable.DynLib)) do for k,fileName in pairs(table.join(infoTable.Libraries, infoTable.DynLib)) do
local paths = {} local paths = {}
for k,v in pairs(infoTable.BinaryPaths.x86) do for k,v in pairs(infoTable.BinaryPaths.x86) do
table.insert(paths, {"x32", v .. "/" .. fileName .. ".dll"}) table.insert(paths, {"x86", v .. "/" .. fileName .. ".dll"})
table.insert(paths, {"x32", v .. "/lib" .. fileName .. ".dll"}) table.insert(paths, {"x86", v .. "/lib" .. fileName .. ".dll"})
end end
for k,v in pairs(infoTable.BinaryPaths.x64) do for k,v in pairs(infoTable.BinaryPaths.x64) do
table.insert(paths, {"x64", v .. "/" .. fileName .. ".dll"}) table.insert(paths, {"x86_64", v .. "/" .. fileName .. ".dll"})
table.insert(paths, {"x64", v .. "/lib" .. fileName .. ".dll"}) table.insert(paths, {"x86_64", v .. "/lib" .. fileName .. ".dll"})
end end
for k,v in pairs(paths) do for k,v in pairs(paths) do
local config = v[1] local arch = v[1]
local srcPath = v[2] local srcPath = v[2]
if (os.isfile(srcPath)) then if (os.isfile(srcPath)) then
if (infoTable.Kind == "plugin") then if (infoTable.Kind == "plugin") then
srcPath = "../../" .. srcPath srcPath = "../../" .. srcPath
end end
configuration(config) filter("architecture:" .. arch)
for k,v in pairs(self.ExecutableDir) do 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 .. [[")}]] 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 end
end end
filter({})
end end
end end
@ -876,41 +689,125 @@ function NazaraBuild:Process(infoTable)
return true return true
end 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) function NazaraBuild:RegisterAction(actionTable)
if (actionTable.Name == nil or type(actionTable.Name) ~= "string" or string.len(actionTable.Name) == 0) then if (not actionTable.Manual) then
return false, "Invalid action name" 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 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 return true
end end

View File

@ -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
*/

View File

@ -22,6 +22,7 @@ namespace Nz
template<typename F, typename Tuple> decltype(auto) Apply(F&& fn, Tuple&& t); template<typename F, typename Tuple> decltype(auto) Apply(F&& fn, Tuple&& t);
template<typename O, typename F, typename Tuple> decltype(auto) Apply(O& object, F&& fn, Tuple&& t); template<typename O, typename F, typename Tuple> decltype(auto) Apply(O& object, F&& fn, Tuple&& t);
template<typename T> constexpr std::size_t BitCount();
template<typename T> ByteArray ComputeHash(HashType hash, const T& v); template<typename T> ByteArray ComputeHash(HashType hash, const T& v);
template<typename T> ByteArray ComputeHash(AbstractHash* hash, const T& v); template<typename T> ByteArray ComputeHash(AbstractHash* hash, const T& v);
template<typename T, std::size_t N> constexpr std::size_t CountOf(T(&name)[N]) noexcept; template<typename T, std::size_t N> constexpr std::size_t CountOf(T(&name)[N]) noexcept;

View File

@ -11,6 +11,7 @@
#include <Nazara/Core/ByteArray.hpp> #include <Nazara/Core/ByteArray.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Stream.hpp> #include <Nazara/Core/Stream.hpp>
#include <climits>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
namespace Nz namespace Nz
@ -70,6 +71,17 @@ namespace Nz
return Detail::ApplyImplMethod(object, std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>()); return Detail::ApplyImplMethod(object, std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>());
} }
/*!
* \ingroup core
* \brief Returns the number of bits occupied by the type T
* \return Number of bits occupied by the type
*/
template<typename T>
constexpr std::size_t BitCount()
{
return CHAR_BIT * sizeof(T);
}
/*! /*!
* \ingroup core * \ingroup core
* \brief Computes the hash of a hashable object * \brief Computes the hash of a hashable object

View File

@ -8,6 +8,7 @@
#define NAZARA_BITSET_HPP #define NAZARA_BITSET_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/String.hpp> #include <Nazara/Core/String.hpp>
#include <limits> #include <limits>
#include <memory> #include <memory>
@ -24,6 +25,7 @@ namespace Nz
public: public:
class Bit; class Bit;
using PointerSequence = std::pair<const void*, std::size_t>; //< Start pointer, bit offset
Bitset(); Bitset();
explicit Bitset(std::size_t bitCount, bool val); explicit Bitset(std::size_t bitCount, bool val);
@ -35,6 +37,8 @@ namespace Nz
Bitset(Bitset&& bitset) noexcept = default; Bitset(Bitset&& bitset) noexcept = default;
~Bitset() noexcept = default; ~Bitset() noexcept = default;
template<typename T> void AppendBits(T bits, std::size_t bitCount);
void Clear() noexcept; void Clear() noexcept;
std::size_t Count() const; std::size_t Count() const;
void Flip(); void Flip();
@ -47,6 +51,9 @@ namespace Nz
std::size_t GetCapacity() const; std::size_t GetCapacity() const;
std::size_t GetSize() 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 PerformsAND(const Bitset& a, const Bitset& b);
void PerformsNOT(const Bitset& a); void PerformsNOT(const Bitset& a);
void PerformsOR(const Bitset& a, const Bitset& b); void PerformsOR(const Bitset& a, const Bitset& b);
@ -60,6 +67,8 @@ namespace Nz
void Reset(); void Reset();
void Reset(std::size_t bit); void Reset(std::size_t bit);
void Reverse();
void Set(bool val = true); void Set(bool val = true);
void Set(std::size_t bit, bool val = true); void Set(std::size_t bit, bool val = true);
void SetBlock(std::size_t i, Block block); void SetBlock(std::size_t i, Block block);
@ -102,9 +111,11 @@ namespace Nz
Bitset& operator^=(const Bitset& bitset); Bitset& operator^=(const Bitset& bitset);
static constexpr Block fullBitMask = std::numeric_limits<Block>::max(); static constexpr Block fullBitMask = std::numeric_limits<Block>::max();
static constexpr std::size_t bitsPerBlock = std::numeric_limits<Block>::digits; static constexpr std::size_t bitsPerBlock = BitCount<Block>();
static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max(); static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max();
static Bitset FromPointer(const void* ptr, std::size_t bitCount, PointerSequence* sequence = nullptr);
private: private:
std::size_t FindFirstFrom(std::size_t blockIndex) const; std::size_t FindFirstFrom(std::size_t blockIndex) const;
Block GetLastBlockMask() const; Block GetLastBlockMask() const;
@ -154,6 +165,9 @@ namespace Nz
Block m_mask; Block m_mask;
}; };
template<typename Block, class Allocator>
std::ostream& operator<<(std::ostream& out, const Bitset<Block, Allocator>& bitset);
template<typename Block, class Allocator> template<typename Block, class Allocator>
bool operator==(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs); bool operator==(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);

View File

@ -6,7 +6,6 @@
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Math/Algorithm.hpp> #include <Nazara/Math/Algorithm.hpp>
#include <cstdlib> #include <cstdlib>
#include <limits>
#include <utility> #include <utility>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
@ -122,13 +121,13 @@ namespace Nz
{ {
if (sizeof(T) <= sizeof(Block)) if (sizeof(T) <= sizeof(Block))
{ {
m_bitCount = std::numeric_limits<T>::digits; m_bitCount = BitCount<T>();
m_blocks.push_back(static_cast<Block>(value)); m_blocks.push_back(static_cast<Block>(value));
} }
else else
{ {
// Note: I was kinda tired when I wrote this, there's probably a much easier method than checking bits to write bits // 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<T>::digits; bitPos++) for (std::size_t bitPos = 0; bitPos < BitCount<T>(); bitPos++)
{ {
if (value & (T(1U) << bitPos)) if (value & (T(1U) << bitPos))
UnboundedSet(bitPos, true); 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<typename Block, class Allocator>
template<typename T>
void Bitset<Block, Allocator>::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<Block>(bits));
bits = (BitCount<Block>() < BitCount<T>()) ? bits >> BitCount<Block>() : 0U;
bitCount -= BitCount<Block>();
}
// 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<Block>(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<typename Block, class Allocator> template<typename Block, class Allocator>
void Bitset<Block, Allocator>::Clear() noexcept void Bitset<Block, Allocator>::Clear() noexcept
{ {
@ -151,9 +202,9 @@ namespace Nz
/*! /*!
* \brief Counts the number of bits set to 1 * \brief Counts the number of bits set to 1
*
* \return Number of bits set to 1 * \return Number of bits set to 1
*/ */
template<typename Block, class Allocator> template<typename Block, class Allocator>
std::size_t Bitset<Block, Allocator>::Count() const std::size_t Bitset<Block, Allocator>::Count() const
{ {
@ -169,8 +220,9 @@ namespace Nz
/*! /*!
* \brief Flips each bit of the bitset * \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<typename Block, class Allocator> template<typename Block, class Allocator>
void Bitset<Block, Allocator>::Flip() void Bitset<Block, Allocator>::Flip()
{ {
@ -182,9 +234,9 @@ namespace Nz
/*! /*!
* \brief Finds the first bit set to one in the bitset * \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<typename Block, class Allocator> template<typename Block, class Allocator>
std::size_t Bitset<Block, Allocator>::FindFirst() const std::size_t Bitset<Block, Allocator>::FindFirst() const
{ {
@ -192,14 +244,14 @@ namespace Nz
} }
/*! /*!
* \brief Finds the next bit set to one in the bitset * \brief Finds the next enabled in the bitset
* \return Index of the next bit if exists or npos
* *
* \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<typename Block, class Allocator> template<typename Block, class Allocator>
std::size_t Bitset<Block, Allocator>::FindNext(std::size_t bit) const std::size_t Bitset<Block, Allocator>::FindNext(std::size_t bit) const
{ {
@ -275,6 +327,76 @@ namespace Nz
return m_bitCount; 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 Block, class Allocator>
typename Bitset<Block, Allocator>::PointerSequence Bitset<Block, Allocator>::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 Block, class Allocator>
typename Bitset<Block, Allocator>::PointerSequence Bitset<Block, Allocator>::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<const UInt8*>(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<std::size_t>(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 * \brief Performs the "AND" operator between two bitsets
* *
@ -289,15 +411,17 @@ namespace Nz
{ {
std::pair<std::size_t, std::size_t> minmax = std::minmax(a.GetBlockCount(), b.GetBlockCount()); std::pair<std::size_t, std::size_t> minmax = std::minmax(a.GetBlockCount(), b.GetBlockCount());
// We reinitialise our blocks with zero m_blocks.resize(minmax.second);
m_blocks.clear();
m_blocks.resize(minmax.second, 0U);
m_bitCount = std::max(a.GetSize(), b.GetSize()); m_bitCount = std::max(a.GetSize(), b.GetSize());
// In case of the "AND", we can stop with the smallest size (because x & 0 = 0) // 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) for (std::size_t i = 0; i < minmax.first; ++i)
m_blocks[i] = a.GetBlock(i) & b.GetBlock(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(); ResetExtraBits();
} }
@ -458,6 +582,30 @@ namespace Nz
Set(bit, false); 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<typename Block, class Allocator>
void Bitset<Block, Allocator>::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 * \brief Sets the bitset to val
* *
@ -535,27 +683,28 @@ namespace Nz
return; return;
} }
auto div = std::lldiv(pos, bitsPerBlock); std::size_t blockShift = pos / bitsPerBlock;
if (div.rem != 0) std::size_t remainder = pos % bitsPerBlock;
if (remainder != 0)
{ {
std::size_t lastIndex = m_blocks.size() - 1; 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) for (std::size_t i = lastIndex - blockShift; i > 0; --i)
m_blocks[i + div.quot] = (m_blocks[i] << div.rem) | (m_blocks[i - 1] >> remaining); 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 else
{ {
for (auto it = m_blocks.rbegin(); it != m_blocks.rend(); ++it) for (auto it = m_blocks.rbegin(); it != m_blocks.rend(); ++it)
{ {
if (static_cast<std::size_t>(std::distance(m_blocks.rbegin(), it) + div.quot) < m_blocks.size()) if (static_cast<std::size_t>(std::distance(m_blocks.rbegin(), it) + blockShift) < m_blocks.size())
{ {
auto shiftedIt = it; auto shiftedIt = it;
std::advance(shiftedIt, div.quot); std::advance(shiftedIt, blockShift);
*it = *shiftedIt; *it = *shiftedIt;
} }
@ -588,27 +737,28 @@ namespace Nz
return; return;
} }
auto div = std::lldiv(pos, bitsPerBlock); std::size_t blockShift = pos / bitsPerBlock;
if (div.rem != 0) std::size_t remainder = pos % bitsPerBlock;
if (remainder != 0)
{ {
std::size_t lastIndex = m_blocks.size() - 1; 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) for (std::size_t i = blockShift; i < lastIndex; ++i)
m_blocks[i - div.quot] = (m_blocks[i] >> div.rem) | (m_blocks[i + 1] << remaining); 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 else
{ {
for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it) for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it)
{ {
if (static_cast<std::size_t>(std::distance(m_blocks.begin(), it) + div.quot) < m_blocks.size()) if (static_cast<std::size_t>(std::distance(m_blocks.begin(), it) + blockShift) < m_blocks.size())
{ {
auto shiftedIt = it; auto shiftedIt = it;
std::advance(shiftedIt, div.quot); std::advance(shiftedIt, blockShift);
*it = *shiftedIt; *it = *shiftedIt;
} }
@ -716,7 +866,7 @@ namespace Nz
{ {
static_assert(std::is_integral<T>() && std::is_unsigned<T>(), "T must be a unsigned integral type"); static_assert(std::is_integral<T>() && std::is_unsigned<T>(), "T must be a unsigned integral type");
NazaraAssert(m_bitCount <= std::numeric_limits<T>::digits, "Bit count cannot be greater than T bit count"); NazaraAssert(m_bitCount <= BitCount<T>(), "Bit count cannot be greater than T bit count");
T value = 0; T value = 0;
for (std::size_t i = 0; i < m_blocks.size(); ++i) for (std::size_t i = 0; i < m_blocks.size(); ++i)
@ -989,13 +1139,41 @@ namespace Nz
return *this; 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<typename Block, class Allocator>
Bitset<Block, Allocator> Bitset<Block, Allocator>::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 * \brief Finds the position of the first bit set to true after the blockIndex
* \return The position of the bit * \return The position of the bit
* *
* \param blockIndex Index of the block * \param blockIndex Index of the block
*/ */
template<typename Block, class Allocator> template<typename Block, class Allocator>
std::size_t Bitset<Block, Allocator>::FindFirstFrom(std::size_t blockIndex) const std::size_t Bitset<Block, Allocator>::FindFirstFrom(std::size_t blockIndex) const
{ {
@ -1124,7 +1302,7 @@ namespace Nz
template<typename Block, class Allocator> template<typename Block, class Allocator>
bool Bitset<Block, Allocator>::Bit::Test() const bool Bitset<Block, Allocator>::Bit::Test() const
{ {
return m_block & m_mask; return (m_block & m_mask) != 0;
} }
/*! /*!
@ -1269,6 +1447,14 @@ namespace Nz
return *this; return *this;
} }
template<typename Block, class Allocator>
std::ostream& operator<<(std::ostream& out, const Bitset<Block, Allocator>& bitset)
{
return out << bitset.ToString();
}
/*! /*!
* \brief Compares two bitsets * \brief Compares two bitsets
* \return true if the two bitsets are the same * \return true if the two bitsets are the same

View File

@ -88,7 +88,7 @@ namespace Nz
inline void ShrinkToFit(); inline void ShrinkToFit();
inline void Swap(ByteArray& other); inline void Swap(ByteArray& other);
inline String ToHex() const; String ToHex() const;
inline String ToString() const; inline String ToString() const;
// STL interface // STL interface

View File

@ -465,22 +465,6 @@ namespace Nz
m_array.swap(other.m_array); 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 * \brief Gives a string representation
* \return String where each byte is converted to char * \return String where each byte is converted to char

View File

@ -29,7 +29,7 @@ namespace Nz
bool Wait(Mutex* mutex, UInt32 timeout); bool Wait(Mutex* mutex, UInt32 timeout);
ConditionVariable& operator=(const ConditionVariable&) = delete; ConditionVariable& operator=(const ConditionVariable&) = delete;
inline ConditionVariable& operator=(ConditionVariable&& condition) noexcept; ConditionVariable& operator=(ConditionVariable&& condition) noexcept;
private: private:
ConditionVariableImpl* m_impl; ConditionVariableImpl* m_impl;

View File

@ -60,10 +60,10 @@ namespace Nz
{ {
struct UserdataValue struct UserdataValue
{ {
UserdataValue(Destructor Destructor, void* value) : UserdataValue(Destructor func, void* ud) :
counter(1), counter(1),
destructor(Destructor), destructor(func),
ptr(value) ptr(ud)
{ {
} }

View File

@ -87,7 +87,7 @@ namespace Nz
struct SpriteChain_XYZ_Color_UV struct SpriteChain_XYZ_Color_UV
{ {
const VertexStruct_XYZ_Color_UV* vertices; const VertexStruct_XYZ_Color_UV* vertices;
unsigned int spriteCount; std::size_t spriteCount;
}; };
struct BatchedSpriteEntry struct BatchedSpriteEntry
@ -160,7 +160,7 @@ namespace Nz
const Material* material; const Material* material;
}; };
typedef std::vector<unsigned int> TransparentModelContainer; typedef std::vector<std::size_t> TransparentModelContainer;
struct Layer struct Layer
{ {

View File

@ -36,10 +36,10 @@ namespace Nz
~ParticleDeclaration(); ~ParticleDeclaration();
void DisableComponent(ParticleComponent component); 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; void GetComponent(ParticleComponent component, bool* enabled, ComponentType* type, std::size_t* offset) const;
unsigned int GetStride() const; std::size_t GetStride() const;
void SetStride(unsigned int stride); void SetStride(unsigned int stride);
@ -60,7 +60,7 @@ namespace Nz
{ {
ComponentType type; ComponentType type;
bool enabled = false; bool enabled = false;
unsigned int offset; std::size_t offset;
/* /*
** -Lynix: ** -Lynix:
@ -71,7 +71,7 @@ namespace Nz
}; };
std::array<Component, ParticleComponent_Max + 1> m_components; std::array<Component, ParticleComponent_Max + 1> m_components;
unsigned int m_stride; std::size_t m_stride;
static std::array<ParticleDeclaration, ParticleLayout_Max + 1> s_declarations; static std::array<ParticleDeclaration, ParticleLayout_Max + 1> s_declarations;
static ParticleDeclarationLibrary::LibraryMap s_library; static ParticleDeclarationLibrary::LibraryMap s_library;

View File

@ -28,12 +28,12 @@ namespace Nz
void EnableLagCompensation(bool enable); void EnableLagCompensation(bool enable);
unsigned int GetEmissionCount() const; std::size_t GetEmissionCount() const;
float GetEmissionRate() const; float GetEmissionRate() const;
bool IsLagCompensationEnabled() const; bool IsLagCompensationEnabled() const;
void SetEmissionCount(unsigned int count); void SetEmissionCount(std::size_t count);
void SetEmissionRate(float rate); void SetEmissionRate(float rate);
ParticleEmitter& operator=(const ParticleEmitter& emitter) = default; ParticleEmitter& operator=(const ParticleEmitter& emitter) = default;
@ -49,7 +49,7 @@ namespace Nz
bool m_lagCompensationEnabled; bool m_lagCompensationEnabled;
mutable float m_emissionAccumulator; mutable float m_emissionAccumulator;
float m_emissionRate; float m_emissionRate;
unsigned int m_emissionCount; std::size_t m_emissionCount;
}; };
} }

View File

@ -45,11 +45,11 @@ namespace Nz
void* GenerateParticles(unsigned int count); void* GenerateParticles(unsigned int count);
const ParticleDeclarationConstRef& GetDeclaration() const; const ParticleDeclarationConstRef& GetDeclaration() const;
unsigned int GetMaxParticleCount() const; std::size_t GetMaxParticleCount() const;
unsigned int GetParticleCount() const; std::size_t GetParticleCount() const;
unsigned int GetParticleSize() const; std::size_t GetParticleSize() const;
void KillParticle(unsigned int index); void KillParticle(std::size_t index);
void KillParticles(); void KillParticles();
void RemoveController(ParticleController* controller); void RemoveController(ParticleController* controller);
@ -81,6 +81,9 @@ namespace Nz
}; };
std::set<unsigned int, std::greater<unsigned int>> m_dyingParticles; std::set<unsigned int, std::greater<unsigned int>> m_dyingParticles;
std::size_t m_maxParticleCount;
std::size_t m_particleCount;
std::size_t m_particleSize;
mutable std::vector<UInt8> m_buffer; mutable std::vector<UInt8> m_buffer;
std::vector<ParticleControllerRef> m_controllers; std::vector<ParticleControllerRef> m_controllers;
std::vector<EmitterEntry> m_emitters; std::vector<EmitterEntry> m_emitters;
@ -88,9 +91,6 @@ namespace Nz
ParticleDeclarationConstRef m_declaration; ParticleDeclarationConstRef m_declaration;
ParticleRendererRef m_renderer; ParticleRendererRef m_renderer;
bool m_processing; bool m_processing;
unsigned int m_maxParticleCount;
unsigned int m_particleCount;
unsigned int m_particleSize;
}; };
} }

View File

@ -23,7 +23,7 @@ namespace Nz
// Then the component that are interesting // Then the component that are interesting
bool enabled; bool enabled;
ComponentType type; ComponentType type;
unsigned int offset; std::size_t offset;
m_declaration->GetComponent(component, &enabled, &type, &offset); m_declaration->GetComponent(component, &enabled, &type, &offset);
if (enabled) if (enabled)
@ -54,7 +54,7 @@ namespace Nz
// Then the component that are interesting // Then the component that are interesting
bool enabled; bool enabled;
ComponentType type; ComponentType type;
unsigned int offset; std::size_t offset;
m_declaration->GetComponent(component, &enabled, &type, &offset); m_declaration->GetComponent(component, &enabled, &type, &offset);
if (enabled) if (enabled)

View File

@ -29,7 +29,7 @@ namespace Nz
static AbstractRenderTechnique* GetByName(const String& name, int* techniqueRanking = nullptr); static AbstractRenderTechnique* GetByName(const String& name, int* techniqueRanking = nullptr);
static AbstractRenderTechnique* GetByRanking(int maxRanking, 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); static void Register(const String& name, int ranking, RenderTechniqueFactory factory);

View File

@ -47,9 +47,11 @@ namespace Nz
inline void SetCornerColor(RectCorner corner, const Color& color); inline void SetCornerColor(RectCorner corner, const Color& color);
inline void SetDefaultMaterial(); inline void SetDefaultMaterial();
inline void SetMaterial(MaterialRef material, bool resizeSprite = true); inline void SetMaterial(MaterialRef material, bool resizeSprite = true);
bool SetMaterial(String materialName, bool resizeSprite = true);
inline void SetOrigin(const Vector3f& origin); inline void SetOrigin(const Vector3f& origin);
inline void SetSize(const Vector2f& size); inline void SetSize(const Vector2f& size);
inline void SetSize(float sizeX, float sizeY); inline void SetSize(float sizeX, float sizeY);
bool SetTexture(String textureName, bool resizeSprite = true);
inline void SetTexture(TextureRef texture, bool resizeSprite = true); inline void SetTexture(TextureRef texture, bool resizeSprite = true);
inline void SetTextureCoords(const Rectf& coords); inline void SetTextureCoords(const Rectf& coords);
inline void SetTextureRect(const Rectui& rect); inline void SetTextureRect(const Rectui& rect);

View File

@ -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 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) inline void Sprite::SetMaterial(MaterialRef material, bool resizeSprite)
{ {
m_material = std::move(material); m_material = std::move(material);
@ -249,16 +248,19 @@ namespace Nz
/*! /*!
* \brief Sets the texture of the sprite * \brief Sets the texture of the sprite
* *
* Assign a texture to the sprite material
*
* \param texture Texture for the sprite * \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) inline void Sprite::SetTexture(TextureRef texture, bool resizeSprite)
{ {
if (!m_material) if (!m_material)
SetDefaultMaterial(); SetDefaultMaterial();
else if (m_material->GetReferenceCount() > 1) 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()) if (resizeSprite && texture && texture->IsValid())
SetSize(Vector2f(Vector2ui(texture->GetSize()))); SetSize(Vector2f(Vector2ui(texture->GetSize())));

View File

@ -29,7 +29,7 @@ namespace Nz
m_isometricModeEnabled(false) m_isometricModeEnabled(false)
{ {
NazaraAssert(m_tiles.size() != 0U, "Invalid map size"); 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"); NazaraAssert(m_layers.size() != 0U, "Invalid material count");
for (Layer& layer : m_layers) for (Layer& layer : m_layers)
@ -175,7 +175,7 @@ namespace Nz
* \param color The multiplicative color applied to the tile * \param color The multiplicative color applied to the tile
* \param materialIndex The material which will be used for rendering this 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. * as the size of the material diffuse map is used to compute normalized texture coordinates before returning.
* *
* \see EnableTiles * \see EnableTiles
@ -253,7 +253,7 @@ namespace Nz
Rectf unnormalizedCoords(invWidth * rect.x, invHeight * rect.y, invWidth * rect.width, invHeight * rect.height); Rectf unnormalizedCoords(invWidth * rect.x, invHeight * rect.y, invWidth * rect.width, invHeight * rect.height);
EnableTiles(unnormalizedCoords, color, materialIndex); EnableTiles(unnormalizedCoords, color, materialIndex);
} }
/*! /*!
* \brief Enable and sets tileCount tiles at positions contained at tilesPos location, enabling rendering at those locations * \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 * \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_layers = tileMap.m_layers;
m_mapSize = TileMap.m_mapSize; m_mapSize = tileMap.m_mapSize;
m_tiles = TileMap.m_tiles; m_tiles = tileMap.m_tiles;
m_tileSize = TileMap.m_tileSize; 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 // We do not copy final vertices because it's highly probable that our parameters are modified and they must be regenerated
InvalidateBoundingVolume(); InvalidateBoundingVolume();

View File

@ -129,7 +129,7 @@ namespace Nz
BindMethod(name, [func, handler] (LuaInstance& lua, T& object, std::size_t /*argumentCount*/) -> int 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); 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 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); 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 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); 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 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); return handler.Invoke(lua, object, func);
}); });
@ -203,7 +203,7 @@ namespace Nz
BindStaticMethod(name, [func, handler] (LuaInstance& lua) -> int BindStaticMethod(name, [func, handler] (LuaInstance& lua) -> int
{ {
handler.ProcessArgs(lua); handler.ProcessArguments(lua);
return handler.Invoke(lua, func); return handler.Invoke(lua, func);
}); });
@ -335,7 +335,7 @@ namespace Nz
NazaraWarning("Class \"" + m_info->name + "\" already registred in this instance"); NazaraWarning("Class \"" + m_info->name + "\" already registred in this instance");
{ {
SetupFinalizer(lua); SetupFinalizer(lua);
if (m_info->getter || !m_info->parentGetters.empty()) if (m_info->getter || !m_info->parentGetters.empty())
SetupGetter(lua, GetterProxy); SetupGetter(lua, GetterProxy);
else else

View File

@ -59,7 +59,7 @@ namespace Nz
m_memoryUsage = instance.m_memoryUsage; m_memoryUsage = instance.m_memoryUsage;
m_state = instance.m_state; m_state = instance.m_state;
m_timeLimit = instance.m_timeLimit; m_timeLimit = instance.m_timeLimit;
instance.m_state = nullptr; instance.m_state = nullptr;
return *this; return *this;
@ -320,7 +320,7 @@ namespace Nz
{ {
} }
void ProcessArgs(const LuaInstance& instance) const void ProcessArguments(const LuaInstance& instance) const
{ {
m_index = 1; m_index = 1;
ProcessArgs<0, Args...>(instance); ProcessArgs<0, Args...>(instance);
@ -391,7 +391,7 @@ namespace Nz
{ {
} }
void ProcessArgs(const LuaInstance& instance) const void ProcessArguments(const LuaInstance& instance) const
{ {
m_index = 2; //< 1 being the instance m_index = 2; //< 1 being the instance
ProcessArgs<0, Args...>(instance); ProcessArgs<0, Args...>(instance);
@ -714,7 +714,7 @@ namespace Nz
PushFunction([func, handler] (LuaInstance& lua) -> int PushFunction([func, handler] (LuaInstance& lua) -> int
{ {
handler.ProcessArgs(lua); handler.ProcessArguments(lua);
return handler.Invoke(lua, func); return handler.Invoke(lua, func);
}); });

View File

@ -37,7 +37,7 @@ namespace Nz
{ {
template<typename T> /*constexpr*/ T Approach(T value, T objective, T increment); template<typename T> /*constexpr*/ T Approach(T value, T objective, T increment);
template<typename T> constexpr T Clamp(T value, T min, T max); template<typename T> constexpr T Clamp(T value, T min, T max);
template<typename T> /*constexpr*/ T CountBits(T value); template<typename T> /*constexpr*/ std::size_t CountBits(T value);
template<typename T> constexpr T FromDegrees(T degrees); template<typename T> constexpr T FromDegrees(T degrees);
template<typename T> constexpr T FromRadians(T radians); template<typename T> constexpr T FromRadians(T radians);
template<typename T> constexpr T DegreeToRadian(T degrees); template<typename T> constexpr T DegreeToRadian(T degrees);

View File

@ -147,10 +147,10 @@ namespace Nz
template<typename T> template<typename T>
//TODO: Mark as constexpr when supported by all major compilers //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 // https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
unsigned int count = 0; std::size_t count = 0;
while (value) while (value)
{ {
value &= value - 1; value &= value - 1;

View File

@ -17,11 +17,11 @@ namespace Nz
{ {
/*! /*!
* \ingroup math * \ingroup math
* \class Nz::EulerAngles * \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 * \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<typename T> template<typename T>
Quaternion<T> EulerAngles<T>::ToQuaternion() const Quaternion<T> EulerAngles<T>::ToQuaternion() const
{ {
// XYZ
T c1 = std::cos(ToRadians(yaw) / F(2.0)); T c1 = std::cos(ToRadians(yaw) / F(2.0));
T c2 = std::cos(ToRadians(roll) / F(2.0)); T c2 = std::cos(ToRadians(roll) / F(2.0));
T c3 = std::cos(ToRadians(pitch) / F(2.0)); T c3 = std::cos(ToRadians(pitch) / F(2.0));

View File

@ -792,7 +792,7 @@ namespace Nz
template<typename T> template<typename T>
bool Matrix4<T>::IsAffine() const bool Matrix4<T>::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));
} }
/*! /*!

View File

@ -714,10 +714,10 @@ namespace Nz
#endif #endif
Quaternion interpolated; Quaternion interpolated;
interpolated.w = Lerp(from.w, to.w, interpolation); interpolated.w = Nz::Lerp(from.w, to.w, interpolation);
interpolated.x = Lerp(from.x, to.x, interpolation); interpolated.x = Nz::Lerp(from.x, to.x, interpolation);
interpolated.y = Lerp(from.y, to.y, interpolation); interpolated.y = Nz::Lerp(from.y, to.y, interpolation);
interpolated.z = Lerp(from.z, to.z, interpolation); interpolated.z = Nz::Lerp(from.z, to.z, interpolation);
return interpolated; return interpolated;
} }

View File

@ -911,9 +911,9 @@ namespace Nz
template<typename T> template<typename T>
bool Vector3<T>::operator<(const Vector3& vec) const bool Vector3<T>::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; return z < vec.z;
else else
return y < vec.y; return y < vec.y;
@ -931,10 +931,10 @@ namespace Nz
template<typename T> template<typename T>
bool Vector3<T>::operator<=(const Vector3& vec) const bool Vector3<T>::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; return NumberEquals(z, vec.z) || z < vec.z;
else else
return y < vec.y; return y < vec.y;
} }
@ -1371,7 +1371,7 @@ namespace std
} }
}; };
} }
#undef F #undef F
#include <Nazara/Core/DebugOff.hpp> #include <Nazara/Core/DebugOff.hpp>

View File

@ -843,11 +843,11 @@ namespace Nz
template<typename T> template<typename T>
bool Vector4<T>::operator<(const Vector4& vec) const bool Vector4<T>::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; return w < vec.w;
else else
return z < vec.z; return z < vec.z;
@ -869,12 +869,12 @@ namespace Nz
template<typename T> template<typename T>
bool Vector4<T>::operator<=(const Vector4& vec) const bool Vector4<T>::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; return NumberEquals(w, vec.w) || w < vec.w;
else else
return z < vec.z; return z < vec.z;
} }
@ -1144,7 +1144,7 @@ namespace std
} }
}; };
} }
#undef F #undef F
#include <Nazara/Core/DebugOff.hpp> #include <Nazara/Core/DebugOff.hpp>

View File

@ -380,7 +380,7 @@ namespace std
// This is SDBM adapted for IP addresses, tested to generate the least collisions possible // This is SDBM adapted for IP addresses, tested to generate the least collisions possible
// (It doesn't mean it cannot be improved though) // (It doesn't mean it cannot be improved though)
std::size_t hash = 0; std::size_t h = 0;
switch (ip.GetProtocol()) switch (ip.GetProtocol())
{ {
case Nz::NetProtocol_Any: case Nz::NetProtocol_Any:
@ -389,20 +389,20 @@ namespace std
case Nz::NetProtocol_IPv4: case Nz::NetProtocol_IPv4:
{ {
hash = ip.ToUInt32() + (hash << 6) + (hash << 16) - hash; h = ip.ToUInt32() + (h << 6) + (h << 16) - h;
break; break;
} }
case Nz::NetProtocol_IPv6: case Nz::NetProtocol_IPv6:
{ {
Nz::IpAddress::IPv6 v6 = ip.ToIPv6(); Nz::IpAddress::IPv6 v6 = ip.ToIPv6();
for (std::size_t i = 0; i < v6.size(); i++) 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; break;
} }
} }
return ip.GetPort() + (hash << 6) + (hash << 16) - hash; return ip.GetPort() + (h << 6) + (h << 16) - h;
} }
}; };
} }

View File

@ -125,6 +125,33 @@ namespace Nz
private: private:
std::vector<cpShape*> CreateShapes(RigidBody2D* body) const override; std::vector<cpShape*> CreateShapes(RigidBody2D* body) const override;
}; };
class SegmentCollider2D;
using SegmentCollider2DConstRef = ObjectRef<const SegmentCollider2D>;
using SegmentCollider2DRef = ObjectRef<SegmentCollider2D>;
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<typename... Args> static SegmentCollider2DRef New(Args&&... args);
private:
std::vector<cpShape*> CreateShapes(RigidBody2D* body) const override;
Vector2f m_first;
Vector2f m_second;
float m_thickness;
};
} }
#include <Nazara/Physics2D/Collider2D.inl> #include <Nazara/Physics2D/Collider2D.inl>

View File

@ -49,6 +49,36 @@ namespace Nz
return object.release(); 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<typename... Args>
SegmentCollider2DRef SegmentCollider2D::New(Args&&... args)
{
std::unique_ptr<SegmentCollider2D> object(new SegmentCollider2D(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
}
} }
#include <Nazara/Physics2D/DebugOff.hpp> #include <Nazara/Physics2D/DebugOff.hpp>

View File

@ -10,9 +10,9 @@
/// Ce fichier sert à vérifier la valeur des constantes du fichier Config.hpp /// Ce fichier sert à vérifier la valeur des constantes du fichier Config.hpp
// On force la valeur de MANAGE_MEMORY en mode debug // On force la valeur de MANAGE_MEMORY en mode debug
#if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS_MANAGE_MEMORY #if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS2D_MANAGE_MEMORY
#undef NAZARA_PHYSICS_MANAGE_MEMORY #undef NAZARA_PHYSICS2D_MANAGE_MEMORY
#define NAZARA_PHYSICS3D_MANAGE_MEMORY 0 #define NAZARA_PHYSICS2D_MANAGE_MEMORY 0
#endif #endif
#endif // NAZARA_CONFIG_CHECK_PHYSICS_HPP #endif // NAZARA_CONFIG_CHECK_PHYSICS_HPP

View File

@ -2,7 +2,7 @@
// This file is part of the "Nazara Engine - Physics 2D module" // This file is part of the "Nazara Engine - Physics 2D module"
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Physics3D/Config.hpp> #include <Nazara/Physics2D/Config.hpp>
#if NAZARA_PHYSICS_MANAGE_MEMORY #if NAZARA_PHYSICS2D_MANAGE_MEMORY
#include <Nazara/Core/Debug/NewRedefinition.hpp> #include <Nazara/Core/Debug/NewRedefinition.hpp>
#endif #endif

View File

@ -3,7 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // 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 // 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 delete
#undef new #undef new
#endif #endif

View File

@ -49,6 +49,7 @@ namespace Nz
bool IsSleeping() const; bool IsSleeping() const;
void SetAngularVelocity(float angularVelocity); void SetAngularVelocity(float angularVelocity);
void SetGeom(Collider2DRef geom);
void SetMass(float mass); void SetMass(float mass);
void SetMassCenter(const Vector2f& center); void SetMassCenter(const Vector2f& center);
void SetPosition(const Vector2f& position); void SetPosition(const Vector2f& position);
@ -59,8 +60,8 @@ namespace Nz
RigidBody2D& operator=(RigidBody2D&& object); RigidBody2D& operator=(RigidBody2D&& object);
private: private:
void Create(float mass = 1.f, float moment = 1.f);
void Destroy(); void Destroy();
void SetGeom(Collider2DRef geom);
std::vector<cpShape*> m_shapes; std::vector<cpShape*> m_shapes;
Collider2DRef m_geom; Collider2DRef m_geom;

View File

@ -10,8 +10,8 @@
/// Ce fichier sert à vérifier la valeur des constantes du fichier Config.hpp /// Ce fichier sert à vérifier la valeur des constantes du fichier Config.hpp
// On force la valeur de MANAGE_MEMORY en mode debug // On force la valeur de MANAGE_MEMORY en mode debug
#if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS_MANAGE_MEMORY #if defined(NAZARA_DEBUG) && !NAZARA_PHYSICS3D_MANAGE_MEMORY
#undef NAZARA_PHYSICS_MANAGE_MEMORY #undef NAZARA_PHYSICS3D_MANAGE_MEMORY
#define NAZARA_PHYSICS3D_MANAGE_MEMORY 0 #define NAZARA_PHYSICS3D_MANAGE_MEMORY 0
#endif #endif

View File

@ -3,6 +3,6 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Physics3D/Config.hpp> #include <Nazara/Physics3D/Config.hpp>
#if NAZARA_PHYSICS_MANAGE_MEMORY #if NAZARA_PHYSICS3D_MANAGE_MEMORY
#include <Nazara/Core/Debug/NewRedefinition.hpp> #include <Nazara/Core/Debug/NewRedefinition.hpp>
#endif #endif

View File

@ -3,7 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // 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 // 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 delete
#undef new #undef new
#endif #endif

View File

@ -25,6 +25,6 @@ namespace Nz
ColliderType3D_Max = ColliderType3D_Tree ColliderType3D_Max = ColliderType3D_Tree
}; };
}; }
#endif // NAZARA_ENUMS_PHYSICS3D_HPP #endif // NAZARA_ENUMS_PHYSICS3D_HPP

View File

@ -25,8 +25,7 @@
#ifndef NAZARA_PREREQUESITES_HPP #ifndef NAZARA_PREREQUESITES_HPP
#define NAZARA_PREREQUESITES_HPP #define NAZARA_PREREQUESITES_HPP
// Identification du compilateur // Try to identify the compiler
///TODO: Rajouter des tests d'identification de compilateurs
#if defined(__BORLANDC__) #if defined(__BORLANDC__)
#define NAZARA_COMPILER_BORDLAND #define NAZARA_COMPILER_BORDLAND
#define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L)
@ -63,10 +62,10 @@
#pragma warning(disable: 4251) #pragma warning(disable: 4251)
#else #else
#define NAZARA_COMPILER_UNKNOWN #define NAZARA_COMPILER_UNKNOWN
#define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L)
#define NAZARA_DEPRECATED(txt) #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 #pragma message This compiler is not fully supported
#endif #endif
@ -76,20 +75,20 @@
// Nazara version macro // Nazara version macro
#define NAZARA_VERSION_MAJOR 0 #define NAZARA_VERSION_MAJOR 0
#define NAZARA_VERSION_MINOR 1 #define NAZARA_VERSION_MINOR 2
#define NAZARA_VERSION_PATCH 1 #define NAZARA_VERSION_PATCH 1
#include <Nazara/Core/Config.hpp> #include <Nazara/Core/Config.hpp>
// Identification de la plateforme // Try to identify target platform via defines
#if defined(_WIN32) #if defined(_WIN32)
#define NAZARA_PLATFORM_WINDOWS #define NAZARA_PLATFORM_WINDOWS
#define NAZARA_EXPORT __declspec(dllexport) #define NAZARA_EXPORT __declspec(dllexport)
#define NAZARA_IMPORT __declspec(dllimport) #define NAZARA_IMPORT __declspec(dllimport)
// Des defines pour le header Windows // Somes defines for windows.h include..
#if defined(NAZARA_BUILD) // Pour ne pas entrer en conflit avec les defines de l'application ou d'une autre bibliothèque #if defined(NAZARA_BUILD)
#ifndef WIN32_LEAN_AND_MEAN #ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#endif #endif
@ -99,13 +98,12 @@
#endif #endif
#if NAZARA_CORE_WINDOWS_NT6 #if NAZARA_CORE_WINDOWS_NT6
// Version de Windows minimale : Vista
#define NAZARA_WINNT 0x0600 #define NAZARA_WINNT 0x0600
#else #else
#define NAZARA_WINNT 0x0501 #define NAZARA_WINNT 0x0501
#endif #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 defined(_WIN32_WINNT)
#if _WIN32_WINNT < NAZARA_WINNT #if _WIN32_WINNT < NAZARA_WINNT
#undef _WIN32_WINNT #undef _WIN32_WINNT
@ -128,7 +126,6 @@
#define NAZARA_PLATFORM_MACOSX #define NAZARA_PLATFORM_MACOSX
#define NAZARA_PLATFORM_POSIX*/ #define NAZARA_PLATFORM_POSIX*/
#else #else
// À commenter pour tenter quand même une compilation
#error This operating system is not fully supported by the Nazara Engine #error This operating system is not fully supported by the Nazara Engine
#define NAZARA_PLATFORM_UNKNOWN #define NAZARA_PLATFORM_UNKNOWN
@ -141,12 +138,7 @@
#define NAZARA_PLATFORM_x64 #define NAZARA_PLATFORM_x64
#endif #endif
// Définit NDEBUG si NAZARA_DEBUG n'est pas présent // A bunch of useful macros
#if !defined(NAZARA_DEBUG) && !defined(NDEBUG)
#define NDEBUG
#endif
// Macros supplémentaires
#define NazaraPrefix(a, prefix) prefix ## a #define NazaraPrefix(a, prefix) prefix ## a
#define NazaraPrefixMacro(a, prefix) NazaraPrefix(a, prefix) #define NazaraPrefixMacro(a, prefix) NazaraPrefix(a, prefix)
#define NazaraSuffix(a, suffix) a ## suffix #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 NazaraStringifyMacro(s) NazaraStringify(s) // http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification
#define NazaraUnused(a) (void) a #define NazaraUnused(a) (void) a
#include <climits>
#include <cstdint> #include <cstdint>
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(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(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"); 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 namespace Nz
{ {
typedef int8_t Int8; typedef int8_t Int8;
typedef uint8_t UInt8; typedef uint8_t UInt8;
typedef int16_t Int16; typedef int16_t Int16;
typedef uint16_t UInt16; typedef uint16_t UInt16;
typedef int32_t Int32; typedef int32_t Int32;
typedef uint32_t UInt32; typedef uint32_t UInt32;
typedef int64_t Int64; typedef int64_t Int64;
typedef uint64_t UInt64; typedef uint64_t UInt64;
} }
#endif // NAZARA_PREREQUESITES_HPP #endif // NAZARA_PREREQUESITES_HPP

View File

@ -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) // 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 #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 // Protège les classes des accès concurrentiels
//#define NAZARA_UTILITY_THREADSAFE 1 //#define NAZARA_UTILITY_THREADSAFE 1

View File

@ -432,15 +432,17 @@ namespace Nz
enum WindowStyleFlags enum WindowStyleFlags
{ {
WindowStyle_None = 0x0, WindowStyle_None = 0x0, ///< Window has no border nor titlebar.
WindowStyle_Fullscreen = 0x1, WindowStyle_Fullscreen = 0x1, ///< At the window creation, the OS tries to set it in fullscreen.
WindowStyle_Closable = 0x2, WindowStyle_Closable = 0x2, ///< Allows the window to be closed by a button in the titlebar, generating a Quit event.
WindowStyle_Resizable = 0x4, WindowStyle_Resizable = 0x4, ///< Allows the window to be resized by dragging its corners or by a button of the titlebar.
WindowStyle_Titlebar = 0x8, WindowStyle_Titlebar = 0x8, ///< Adds a titlebar to the window, this option is automatically enabled if buttons of the titlebar are enabled.
WindowStyle_Threaded = 0x10, ///< Runs the window into a thread, allowing the application to keep updating while resizing/dragging the window.
WindowStyle_Default = WindowStyle_Closable | WindowStyle_Resizable | WindowStyle_Titlebar, WindowStyle_Default = WindowStyle_Closable | WindowStyle_Resizable | WindowStyle_Titlebar,
WindowStyle_Max = WindowStyle_Titlebar*2-1 WindowStyle_Max = WindowStyle_Threaded*2-1
}; };
} }

View File

@ -24,6 +24,9 @@ namespace Nz
inline void Dispatch(const WindowEvent& event); inline void Dispatch(const WindowEvent& event);
EventHandler& operator=(const EventHandler&) = delete;
EventHandler& operator=(EventHandler&&) = default;
NazaraSignal(OnEvent, const EventHandler* /*eventHandler*/, const WindowEvent& /*event*/); NazaraSignal(OnEvent, const EventHandler* /*eventHandler*/, const WindowEvent& /*event*/);
NazaraSignal(OnGainedFocus, const EventHandler* /*eventHandler*/); NazaraSignal(OnGainedFocus, const EventHandler* /*eventHandler*/);
NazaraSignal(OnLostFocus, const EventHandler* /*eventHandler*/); NazaraSignal(OnLostFocus, const EventHandler* /*eventHandler*/);

View File

@ -91,6 +91,8 @@ namespace Nz
ImageType GetType() const; ImageType GetType() const;
unsigned int GetWidth(UInt8 level = 0) const; unsigned int GetWidth(UInt8 level = 0) const;
bool HasAlpha() const;
bool IsValid() const; bool IsValid() const;
// Load // Load

View File

@ -39,18 +39,8 @@ namespace Nz
} }
inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) : inline PixelFormatInfo::PixelFormatInfo(const String& formatName, PixelFormatContent formatContent, Bitset<> rMask, Bitset<> gMask, Bitset<> bMask, Bitset<> aMask, PixelFormatSubType subType) :
redMask(rMask), PixelFormatInfo(formatName, formatContent, subType, rMask, subType, gMask, subType, bMask, subType, aMask)
greenMask(gMask),
blueMask(bMask),
alphaMask(aMask),
content(formatContent),
redType(subType),
greenType(subType),
blueType(subType),
alphaType(subType),
name(formatName)
{ {
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) : 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), alphaType(aType),
name(formatName) name(formatName)
{ {
redMask.Reverse();
greenMask.Reverse();
blueMask.Reverse();
alphaMask.Reverse();
if (bpp == 0) if (bpp == 0)
RecomputeBitsPerPixel(); RecomputeBitsPerPixel();
} }
@ -123,6 +118,9 @@ namespace Nz
if (usedBits > bitsPerPixel) if (usedBits > bitsPerPixel)
return false; return false;
if (usedBits > 64) //< Currently, formats with over 64 bits per component are not supported
return false;
switch (types[i]) switch (types[i])
{ {
case PixelFormatSubType_Half: case PixelFormatSubType_Half:

View File

@ -19,6 +19,7 @@ namespace Nz
{ {
public: public:
VideoMode(); VideoMode();
VideoMode(unsigned int w, unsigned int h);
VideoMode(unsigned int w, unsigned int h, UInt8 bpp); VideoMode(unsigned int w, unsigned int h, UInt8 bpp);
bool IsFullscreenValid() const; bool IsFullscreenValid() const;

View File

@ -10,6 +10,8 @@
#define NAZARA_WINDOW_HPP #define NAZARA_WINDOW_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/ConditionVariable.hpp>
#include <Nazara/Core/Mutex.hpp>
#include <Nazara/Core/String.hpp> #include <Nazara/Core/String.hpp>
#include <Nazara/Math/Vector2.hpp> #include <Nazara/Math/Vector2.hpp>
#include <Nazara/Utility/Config.hpp> #include <Nazara/Utility/Config.hpp>
@ -19,11 +21,6 @@
#include <Nazara/Utility/WindowHandle.hpp> #include <Nazara/Utility/WindowHandle.hpp>
#include <queue> #include <queue>
#if NAZARA_UTILITY_THREADED_WINDOW
#include <Nazara/Core/ConditionVariable.hpp>
#include <Nazara/Core/Mutex.hpp>
#endif
namespace Nz namespace Nz
{ {
class Cursor; class Cursor;
@ -114,23 +111,24 @@ namespace Nz
private: private:
void IgnoreNextMouseEvent(int mouseX, int mouseY) const; void IgnoreNextMouseEvent(int mouseX, int mouseY) const;
inline void HandleEvent(const WindowEvent& event);
inline void PushEvent(const WindowEvent& event); inline void PushEvent(const WindowEvent& event);
static bool Initialize(); static bool Initialize();
static void Uninitialize(); static void Uninitialize();
std::queue<WindowEvent> m_events; std::queue<WindowEvent> m_events;
#if NAZARA_UTILITY_THREADED_WINDOW std::vector<WindowEvent> m_pendingEvents;
ConditionVariable m_eventCondition; ConditionVariable m_eventCondition;
EventHandler m_eventHandler;
Mutex m_eventMutex; Mutex m_eventMutex;
Mutex m_eventConditionMutex; Mutex m_eventConditionMutex;
bool m_waitForEvent; bool m_asyncWindow;
#endif
EventHandler m_eventHandler;
bool m_closed; bool m_closed;
bool m_closeOnQuit; bool m_closeOnQuit;
bool m_eventPolling; bool m_eventPolling;
bool m_ownsWindow; bool m_ownsWindow;
bool m_waitForEvent;
}; };
} }

View File

@ -4,6 +4,7 @@
#include <Nazara/Utility/Window.hpp> #include <Nazara/Utility/Window.hpp>
#include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Core/LockGuard.hpp>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
namespace Nz namespace Nz
@ -13,11 +14,10 @@ namespace Nz
*/ */
inline Window::Window() : inline Window::Window() :
m_impl(nullptr), m_impl(nullptr),
#if NAZARA_UTILITY_THREADED_WINDOW m_asyncWindow(false),
m_waitForEvent(false),
#endif
m_closeOnQuit(true), m_closeOnQuit(true),
m_eventPolling(false) m_eventPolling(false),
m_waitForEvent(false)
{ {
} }
@ -41,16 +41,16 @@ namespace Nz
inline Window::Window(Window&& window) noexcept : inline Window::Window(Window&& window) noexcept :
m_impl(window.m_impl), m_impl(window.m_impl),
m_events(std::move(window.m_events)), 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_eventCondition(std::move(window.m_eventCondition)),
m_eventHandler(std::move(window.m_eventHandler)),
m_eventMutex(std::move(window.m_eventMutex)), m_eventMutex(std::move(window.m_eventMutex)),
m_eventConditionMutex(std::move(window.m_eventConditionMutex)), m_eventConditionMutex(std::move(window.m_eventConditionMutex)),
m_waitForEvent(window.m_waitForEvent),
#endif
m_closed(window.m_closed), m_closed(window.m_closed),
m_closeOnQuit(window.m_closeOnQuit), m_closeOnQuit(window.m_closeOnQuit),
m_eventPolling(window.m_eventPolling), m_eventPolling(window.m_eventPolling),
m_ownsWindow(window.m_ownsWindow) m_ownsWindow(window.m_ownsWindow),
m_waitForEvent(window.m_waitForEvent)
{ {
window.m_impl = nullptr; window.m_impl = nullptr;
} }
@ -104,12 +104,8 @@ namespace Nz
return m_impl != nullptr; 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) if (m_eventPolling)
m_events.push(event); m_events.push(event);
@ -120,17 +116,27 @@ namespace Nz
if (event.type == WindowEventType_Quit && m_closeOnQuit) if (event.type == WindowEventType_Quit && m_closeOnQuit)
Close(); Close();
}
#if NAZARA_UTILITY_THREADED_WINDOW inline void Window::PushEvent(const WindowEvent& event)
m_eventMutex.Unlock(); {
if (!m_asyncWindow)
if (m_waitForEvent) HandleEvent(event);
else
{ {
m_eventConditionMutex.Lock(); {
m_eventCondition.Signal(); LockGuard eventLock(m_eventMutex);
m_eventConditionMutex.Unlock();
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(); Destroy();
m_closed = window.m_closed; m_closed = window.m_closed;
m_closeOnQuit = window.m_closeOnQuit; m_closeOnQuit = window.m_closeOnQuit;
m_eventPolling = window.m_eventPolling; m_eventCondition = std::move(window.m_eventCondition);
m_impl = window.m_impl; m_eventConditionMutex = std::move(window.m_eventConditionMutex);
m_events = std::move(window.m_events); m_eventHandler = std::move(window.m_eventHandler);
m_ownsWindow = window.m_ownsWindow; 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; 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; return *this;
} }
} }

Some files were not shown because too many files have changed in this diff Show More