Merge branch 'master' into culling

This commit is contained in:
Jérôme Leclercq 2016-11-07 11:26:48 +01:00
commit 9e84c397ba
85 changed files with 2580 additions and 1234 deletions

4
.gitignore vendored
View File

@ -32,6 +32,7 @@ build/scripts/features/index.html
doc doc
# Codeblocks # Codeblocks
*.save-failed
build/**/*.cbp build/**/*.cbp
build/**/*.cbp build/**/*.cbp
build/**/*.cbTemp build/**/*.cbTemp
@ -43,6 +44,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

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

@ -1,4 +1,4 @@
// This file was automatically generated on 30 Jul 2016 at 15:29:16 // This file was automatically generated
#pragma once #pragma once

View File

@ -78,13 +78,13 @@ namespace Ndk
{ {
} }
Renderable(Renderable&& renderable) noexcept : Renderable(Renderable&& rhs) noexcept :
renderableBoundingVolumeInvalidationSlot(std::move(renderable.renderableBoundingVolumeInvalidationSlot)), renderableBoundingVolumeInvalidationSlot(std::move(rhs.renderableBoundingVolumeInvalidationSlot)),
renderableDataInvalidationSlot(std::move(renderable.renderableDataInvalidationSlot)), renderableDataInvalidationSlot(std::move(rhs.renderableDataInvalidationSlot)),
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.rhs)),
dataUpdated(renderable.dataUpdated) dataUpdated(rhs.dataUpdated)
{ {
} }

View File

@ -12,7 +12,6 @@
namespace Ndk namespace Ndk
{ {
class Entity;
class VelocityComponent; class VelocityComponent;
using VelocityComponentHandle = Nz::ObjectHandle<VelocityComponent>; using VelocityComponentHandle = Nz::ObjectHandle<VelocityComponent>;

View File

@ -24,7 +24,7 @@ namespace Ndk
LuaAPI() = delete; LuaAPI() = delete;
~LuaAPI() = delete; ~LuaAPI() = delete;
static inline LuaBinding* GetBinding(); static LuaBinding* GetBinding();
static bool Initialize(); static bool Initialize();

View File

@ -10,6 +10,7 @@
#include <Nazara/Math/Vector3.hpp> #include <Nazara/Math/Vector3.hpp>
#include <Nazara/Network/IpAddress.hpp> #include <Nazara/Network/IpAddress.hpp>
#include <Nazara/Utility/Font.hpp> #include <Nazara/Utility/Font.hpp>
#include <Nazara/Utility/Image.hpp>
#include <Nazara/Utility/Mesh.hpp> #include <Nazara/Utility/Mesh.hpp>
#include <NDK/Application.hpp> #include <NDK/Application.hpp>
#include <NDK/Components.hpp> #include <NDK/Components.hpp>
@ -21,22 +22,10 @@
#include <Nazara/Audio/Music.hpp> #include <Nazara/Audio/Music.hpp>
#include <Nazara/Audio/SoundBuffer.hpp> #include <Nazara/Audio/SoundBuffer.hpp>
#include <Nazara/Graphics/Model.hpp> #include <Nazara/Graphics/Model.hpp>
#include <Nazara/Renderer/Texture.hpp>
#include <NDK/Console.hpp> #include <NDK/Console.hpp>
#endif #endif
namespace Ndk
{
/*!
* \brief Gets the internal binding for Lua
* \return A pointer to the binding
*/
inline LuaBinding* LuaAPI::GetBinding()
{
return s_binding;
}
}
namespace Nz namespace Nz
{ {
/*! /*!
@ -143,6 +132,104 @@ 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>)
{
instance.CheckType(index, Nz::LuaType_Table);
params->levelCount = instance.CheckField<Nz::UInt8>("LevelCount");
params->loadFormat = instance.CheckField<Nz::PixelFormatType>("LoadFormat");
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>)
{
switch (instance.GetType(index))
{
case Nz::LuaType_String:
address->BuildFromAddress(instance.CheckString(index));
return 1;
default:
*address = *static_cast<IpAddress*>(instance.CheckUserdata(index, "IpAddress"));
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, Matrix4d* mat, TypeTag<Matrix4d>)
{
switch (instance.GetType(index))
{
case Nz::LuaType_Table:
{
double values[16];
for (std::size_t i = 0; i < 16; ++i)
{
instance.PushInteger(i + 1);
instance.GetTable();
values[i] = instance.CheckNumber(-1);
instance.Pop();
}
mat->Set(values);
return 1;
}
default:
{
if (instance.IsOfType(index, "Matrix4"))
mat->Set(*static_cast<Matrix4d*>(instance.ToUserdata(index)));
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, Matrix4f* mat, TypeTag<Matrix4f>)
{
Matrix4d matDouble = Matrix4d::Identity();
unsigned int ret = LuaImplQueryArg(instance, index, &matDouble, TypeTag<Matrix4d>());
mat->Set(matDouble);
return ret;
}
/*! /*!
* \brief Queries arguments for Lua * \brief Queries arguments for Lua
* \return 1 in case of success * \return 1 in case of success
@ -156,15 +243,62 @@ namespace Nz
{ {
instance.CheckType(index, Nz::LuaType_Table); instance.CheckType(index, Nz::LuaType_Table);
params->animated = instance.CheckField<bool>("Animated", params->animated); params->animated = instance.CheckField<bool>("Animated", params->animated);
params->center = instance.CheckField<bool>("Center", params->center); params->center = instance.CheckField<bool>("Center", params->center);
params->flipUVs = instance.CheckField<bool>("FlipUVs", params->flipUVs); params->flipUVs = instance.CheckField<bool>("FlipUVs", params->flipUVs);
//params->matrix = instance.CheckField<Matrix4f>("Matrix", params->matrix); params->matrix = instance.CheckField<Matrix4f>("Matrix", params->matrix);
params->optimizeIndexBuffers = instance.CheckField<bool>("OptimizeIndexBuffers", params->optimizeIndexBuffers); params->optimizeIndexBuffers = instance.CheckField<bool>("OptimizeIndexBuffers", params->optimizeIndexBuffers);
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>)
{
switch (instance.GetType(index))
{
case Nz::LuaType_Table:
quat->Set(instance.CheckField<double>("w", index), instance.CheckField<double>("x", index), instance.CheckField<double>("y", index), instance.CheckField<double>("z", index));
return 1;
default:
{
if (instance.IsOfType(index, "EulerAngles"))
quat->Set(*static_cast<EulerAnglesd*>(instance.ToUserdata(index)));
else
quat->Set(*static_cast<Quaterniond*>(instance.CheckUserdata(index, "Quaternion")));
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, Quaternionf* quat, TypeTag<Quaternionf>)
{
Quaterniond quatDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &quatDouble, TypeTag<Quaterniond>());
quat->Set(quatDouble);
return ret;
}
/*! /*!
* \brief Queries arguments for Lua * \brief Queries arguments for Lua
* \return 1 in case of success * \return 1 in case of success
@ -222,76 +356,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 quat Resulting quaternion
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, Quaterniond* quat, TypeTag<Quaterniond>)
{
switch (instance.GetType(index))
{
case Nz::LuaType_Table:
quat->Set(instance.CheckField<double>("w", index), instance.CheckField<double>("x", index), instance.CheckField<double>("y", index), instance.CheckField<double>("z", index));
return 1;
default:
{
if (instance.IsOfType(index, "EulerAngles"))
quat->Set(*static_cast<EulerAnglesd*>(instance.ToUserdata(index)));
else
quat->Set(*static_cast<Quaterniond*>(instance.CheckUserdata(index, "Quaternion")));
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, Quaternionf* quat, TypeTag<Quaternionf>)
{
Quaterniond quatDouble;
unsigned int ret = LuaImplQueryArg(instance, index, &quatDouble, TypeTag<Quaterniond>());
quat->Set(quatDouble);
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 address Resulting IP address
*/
inline unsigned int LuaImplQueryArg(const LuaInstance& instance, int index, IpAddress* address, TypeTag<IpAddress>)
{
switch (instance.GetType(index))
{
case Nz::LuaType_String:
address->BuildFromAddress(instance.CheckString(index));
return 1;
default:
*address = *static_cast<IpAddress*>(instance.CheckUserdata(index, "IpAddress"));
return 1;
}
}
/*! /*!
* \brief Queries arguments for Lua * \brief Queries arguments for Lua
* \return 1 in case of success * \return 1 in case of success
@ -469,10 +533,31 @@ namespace Nz
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") ||
*renderable = *static_cast<InstancedRenderableRef*>(instance.CheckUserdata(index, "InstancedRenderable")); instance.IsOfType(index, "Model") ||
instance.IsOfType(index, "Sprite"))
{
*renderable = *static_cast<InstancedRenderableRef*>(instance.ToUserdata(index));
}
else else
*renderable = *static_cast<InstancedRenderableRef*>(instance.CheckUserdata(index, "Model")); instance.ArgError(index, "is not a InstancedRenderable instance");
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>)
{
*materialRef = *static_cast<MaterialRef*>(instance.CheckUserdata(index, "Material"));
return 1; return 1;
} }
@ -495,6 +580,7 @@ namespace Nz
params->loadHeightMap = instance.CheckField<bool>("LoadHeightMap", params->loadHeightMap); params->loadHeightMap = instance.CheckField<bool>("LoadHeightMap", params->loadHeightMap);
params->loadNormalMap = instance.CheckField<bool>("LoadNormalMap", params->loadNormalMap); params->loadNormalMap = instance.CheckField<bool>("LoadNormalMap", params->loadNormalMap);
params->loadSpecularMap = instance.CheckField<bool>("LoadSpecularMap", params->loadSpecularMap); params->loadSpecularMap = instance.CheckField<bool>("LoadSpecularMap", params->loadSpecularMap);
params->shaderName = instance.CheckField<String>("ShaderName", params->shaderName);
return 1; return 1;
} }
@ -556,8 +642,59 @@ 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>)
{
*spriteRef = *static_cast<SpriteRef*>(instance.CheckUserdata(index, "Sprite"));
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>)
{
*textureRef = *static_cast<TextureRef*>(instance.CheckUserdata(index, "Texture"));
return 1;
}
#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>)
{
instance.PushTable();
instance.PushField("r", val.r);
instance.PushField("g", val.g);
instance.PushField("b", val.b);
instance.PushField("a", val.a);
return 1;
}
/*! /*!
* \brief Replies by value for Lua * \brief Replies by value for Lua
* \return 1 in case of success * \return 1 in case of success
@ -619,6 +756,65 @@ 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>)
{
instance.PushTable(0, 2);
instance.PushField("LevelCount", val.levelCount);
instance.PushField("LoadFormat", val.loadFormat);
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>)
{
instance.PushInstance<IpAddress>("IpAddress", val);
return 1;
}
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting rectangle
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4d&& val, TypeTag<Matrix4d>)
{
instance.PushInstance<Matrix4d>("Matrix4", val);
return 1;
}
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting rectangle
*/
inline int LuaImplReplyVal(const LuaInstance& instance, Matrix4f&& val, TypeTag<Matrix4f>)
{
instance.PushInstance<Matrix4d>("Matrix4", val);
return 1;
}
/*! /*!
* \brief Replies by value for Lua * \brief Replies by value for Lua
* \return 1 in case of success * \return 1 in case of success
@ -647,20 +843,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 IP address
*/
inline int LuaImplReplyVal(const LuaInstance& instance, IpAddress&& val, TypeTag<IpAddress>)
{
instance.PushInstance<IpAddress>("IpAddress", val);
return 1;
}
/*! /*!
* \brief Replies by value for Lua * \brief Replies by value for Lua
* \return 1 in case of success * \return 1 in case of success
@ -669,7 +851,7 @@ namespace Nz
* \param val Resulting rectangle * \param val Resulting rectangle
*/ */
inline int LuaImplReplyVal(const LuaInstance& instance, Rectd&& val, TypeTag<Rectf>) inline int LuaImplReplyVal(const LuaInstance& instance, Rectd&& val, TypeTag<Rectd>)
{ {
instance.PushInstance<Rectd>("Rect", val); instance.PushInstance<Rectd>("Rect", val);
return 1; return 1;
@ -887,6 +1069,62 @@ 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>)
{
instance.PushInstance<MaterialRef>("Material", handle);
return 1;
}
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param val Resulting sound buffer
*/
inline int LuaImplReplyVal(const LuaInstance& instance, const SoundBuffer* val, TypeTag<const SoundBuffer*>)
{
instance.PushInstance<SoundBufferConstRef>("SoundBuffer", val);
return 1;
}
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param handle Resulting sprite
*/
inline int LuaImplReplyVal(const LuaInstance& instance, SpriteRef&& handle, TypeTag<SpriteRef>)
{
instance.PushInstance<SpriteRef>("Sprite", handle);
return 1;
}
/*!
* \brief Replies by value for Lua
* \return 1 in case of success
*
* \param instance Lua instance to interact with
* \param handle Resulting texture
*/
inline int LuaImplReplyVal(const LuaInstance& instance, TextureRef&& handle, TypeTag<TextureRef>)
{
instance.PushInstance<TextureRef>("Texture", handle);
return 1;
}
/*! /*!
* \brief Replies by value for Lua * \brief Replies by value for Lua
* \return 1 in case of success * \return 1 in case of success
@ -914,21 +1152,6 @@ namespace Nz
instance.PushInstance<Ndk::GraphicsComponentHandle>("GraphicsComponent", handle); instance.PushInstance<Ndk::GraphicsComponentHandle>("GraphicsComponent", 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*>)
{
instance.PushInstance<SoundBufferConstRef>("SoundBuffer", val);
return 1;
}
#endif #endif
} }

View File

@ -38,47 +38,56 @@ namespace Ndk
void RegisterClasses(Nz::LuaInstance& instance); void RegisterClasses(Nz::LuaInstance& instance);
// Core // Core
Nz::LuaClass<Nz::Clock> clockClass; Nz::LuaClass<Nz::Clock> clock;
Nz::LuaClass<Nz::Directory> directoryClass; Nz::LuaClass<Nz::Directory> directory;
Nz::LuaClass<Nz::File> fileClass; Nz::LuaClass<Nz::File> file;
Nz::LuaClass<Nz::Stream> streamClass; Nz::LuaClass<Nz::Stream> stream;
// Math // Math
Nz::LuaClass<Nz::EulerAnglesd> eulerAnglesClass; Nz::LuaClass<Nz::EulerAnglesd> eulerAngles;
Nz::LuaClass<Nz::Quaterniond> quaternionClass; Nz::LuaClass<Nz::Matrix4d> matrix4d;
Nz::LuaClass<Nz::Rectd> rectClass; Nz::LuaClass<Nz::Quaterniond> quaternion;
Nz::LuaClass<Nz::Vector2d> vector2dClass; Nz::LuaClass<Nz::Rectd> rect;
Nz::LuaClass<Nz::Vector3d> vector3dClass; Nz::LuaClass<Nz::Vector2d> vector2d;
Nz::LuaClass<Nz::Vector3d> vector3d;
// Network // Network
Nz::LuaClass<Nz::AbstractSocket> abstractSocketClass; Nz::LuaClass<Nz::AbstractSocket> abstractSocket;
Nz::LuaClass<Nz::IpAddress> ipAddressClass; Nz::LuaClass<Nz::IpAddress> ipAddress;
// Utility // Utility
Nz::LuaClass<Nz::AbstractImage*> abstractImage; Nz::LuaClass<Nz::AbstractImageRef> abstractImage;
Nz::LuaClass<Nz::FontRef> fontClass; Nz::LuaClass<Nz::FontRef> font;
Nz::LuaClass<Nz::Node> nodeClass; Nz::LuaClass<Nz::Node> node;
// SDK // SDK
Nz::LuaClass<Application*> application; Nz::LuaClass<Application*> application;
Nz::LuaClass<EntityHandle> entityClass; Nz::LuaClass<EntityHandle> entity;
Nz::LuaClass<NodeComponentHandle> nodeComponent; Nz::LuaClass<NodeComponentHandle> nodeComponent;
Nz::LuaClass<VelocityComponentHandle> velocityComponent; Nz::LuaClass<VelocityComponentHandle> velocityComponent;
Nz::LuaClass<WorldHandle> worldClass; Nz::LuaClass<WorldHandle> world;
#ifndef NDK_SERVER #ifndef NDK_SERVER
// Audio // Audio
Nz::LuaClass<Nz::Music> musicClass; Nz::LuaClass<Nz::Music> music;
Nz::LuaClass<Nz::Sound> soundClass; Nz::LuaClass<Nz::Sound> sound;
Nz::LuaClass<Nz::SoundBufferRef> soundBuffer; Nz::LuaClass<Nz::SoundBufferRef> soundBuffer;
Nz::LuaClass<Nz::SoundEmitter> soundEmitter; Nz::LuaClass<Nz::SoundEmitter> soundEmitter;
// Graphics // Graphics
Nz::LuaClass<Nz::InstancedRenderableRef> instancedRenderable; Nz::LuaClass<Nz::InstancedRenderableRef> instancedRenderable;
Nz::LuaClass<Nz::ModelRef> modelClass; Nz::LuaClass<Nz::MaterialRef> material;
Nz::LuaClass<Nz::ModelRef> model;
Nz::LuaClass<Nz::SpriteRef> sprite;
Nz::LuaClass<Nz::SpriteLibrary> spriteLibrary;
Nz::LuaClass<Nz::TextureLibrary> textureLibrary;
Nz::LuaClass<Nz::TextureManager> textureManager;
// Renderer
Nz::LuaClass<Nz::TextureRef> texture;
// SDK // SDK
Nz::LuaClass<ConsoleHandle> consoleClass; Nz::LuaClass<ConsoleHandle> console;
Nz::LuaClass<GraphicsComponentHandle> graphicsComponent; Nz::LuaClass<GraphicsComponentHandle> graphicsComponent;
#endif #endif
@ -117,7 +126,7 @@ namespace Ndk
Nz::String name; Nz::String name;
}; };
ComponentBinding* QueryComponentIndex(Nz::LuaInstance& lua, int argIndex = 1); ComponentBinding* QueryComponentIndex(Nz::LuaInstance& lua, int argIndex = 2);
std::vector<ComponentBinding> m_componentBinding; std::vector<ComponentBinding> m_componentBinding;
std::unordered_map<Nz::String, ComponentIndex> m_componentBindingByName; std::unordered_map<Nz::String, ComponentIndex> m_componentBindingByName;

View File

@ -29,7 +29,7 @@
// 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

@ -1,4 +1,4 @@
// This file was automatically generated on 30 Jul 2016 at 15:29:16 // This file was automatically generated
#pragma once #pragma once

View File

@ -98,9 +98,7 @@ namespace Ndk
++it; ++it;
} }
#endif
#ifndef NDK_SERVER
if (m_exitOnClosedWindows && !hasAtLeastOneActiveWindow) if (m_exitOnClosedWindows && !hasAtLeastOneActiveWindow)
return false; return false;
#endif #endif

View File

@ -1,6 +1,7 @@
// This file was automatically generated on 26 May 2014 at 01:05:31 // This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/LuaAPI.hpp> #include <NDK/LuaAPI.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <NDK/LuaBinding.hpp> #include <NDK/LuaBinding.hpp>
namespace Ndk namespace Ndk
@ -11,6 +12,21 @@ namespace Ndk
* \brief NDK class that represents the api used for Lua * \brief NDK class that represents the api used for Lua
*/ */
/*!
* \brief Gets the internal binding for Lua
* \return A pointer to the binding
*/
LuaBinding* LuaAPI::GetBinding()
{
if (!s_binding && !Initialize())
{
NazaraError("Failed to initialize binding");
return nullptr;
}
return s_binding;
}
/*! /*!
* \brief Initializes the LuaAPI module * \brief Initializes the LuaAPI module
* \return true if initialization is successful * \return true if initialization is successful
@ -30,13 +46,8 @@ namespace Ndk
void LuaAPI::RegisterClasses(Nz::LuaInstance& instance) void LuaAPI::RegisterClasses(Nz::LuaInstance& instance)
{ {
if (!s_binding && !Initialize()) Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true);
{ GetBinding()->RegisterClasses(instance);
NazaraError("Failed to initialize binding");
return;
}
s_binding->RegisterClasses(instance);
} }
/*! /*!

View File

@ -16,49 +16,58 @@ namespace Ndk
LuaBinding::LuaBinding() : LuaBinding::LuaBinding() :
// Core // Core
clockClass("Clock"), clock("Clock"),
directoryClass("Directory"), directory("Directory"),
fileClass("File"), file("File"),
streamClass("Stream"), stream("Stream"),
// Math // Math
eulerAnglesClass("EulerAngles"), eulerAngles("EulerAngles"),
quaternionClass("Quaternion"), matrix4d("Matrix4"),
rectClass("Rect"), quaternion("Quaternion"),
vector2dClass("Vector2"), rect("Rect"),
vector3dClass("Vector3"), vector2d("Vector2"),
vector3d("Vector3"),
// Network // Network
abstractSocketClass("AbstractSocket"), abstractSocket("AbstractSocket"),
ipAddressClass("IpAddress"), ipAddress("IpAddress"),
// Utility // Utility
abstractImage("AbstractImage"), abstractImage("AbstractImage"),
fontClass("Font"), font("Font"),
nodeClass("Node"), node("Node"),
// SDK // SDK
application("Application"), application("Application"),
entityClass("Entity"), entity("Entity"),
nodeComponent("NodeComponent"), nodeComponent("NodeComponent"),
velocityComponent("VelocityComponent"), velocityComponent("VelocityComponent"),
worldClass("World") world("World")
#ifndef NDK_SERVER #ifndef NDK_SERVER
, ,
// Audio // Audio
musicClass("Music"), music("Music"),
soundClass("Sound"), sound("Sound"),
soundBuffer("SoundBuffer"), soundBuffer("SoundBuffer"),
soundEmitter("SoundEmitter"), soundEmitter("SoundEmitter"),
// Graphics // Graphics
instancedRenderable("InstancedRenderable"), instancedRenderable("InstancedRenderable"),
modelClass("Model"), material("Material"),
model("Model"),
sprite("Sprite"),
spriteLibrary("SpriteLibrary"),
textureLibrary("TextureLibrary"),
textureManager("TextureManager"),
// Renderer
texture("Texture"),
// SDK // SDK
consoleClass("Console"), console("Console"),
graphicsComponent("GraphicsComponent") graphicsComponent("GraphicsComponent")
#endif #endif
{ {

View File

@ -13,67 +13,67 @@ namespace Ndk
void LuaBinding::BindAudio() void LuaBinding::BindAudio()
{ {
/*********************************** Nz::Music **********************************/ /*********************************** Nz::Music **********************************/
musicClass.Inherit(soundEmitter); music.Inherit(soundEmitter);
musicClass.BindDefaultConstructor(); music.BindDefaultConstructor();
//musicClass.SetMethod("Create", &Nz::Music::Create); //musicClass.SetMethod("Create", &Nz::Music::Create);
//musicClass.SetMethod("Destroy", &Nz::Music::Destroy); //musicClass.SetMethod("Destroy", &Nz::Music::Destroy);
musicClass.BindMethod("EnableLooping", &Nz::Music::EnableLooping); music.BindMethod("EnableLooping", &Nz::Music::EnableLooping);
musicClass.BindMethod("GetDuration", &Nz::Music::GetDuration); music.BindMethod("GetDuration", &Nz::Music::GetDuration);
musicClass.BindMethod("GetFormat", &Nz::Music::GetFormat); music.BindMethod("GetFormat", &Nz::Music::GetFormat);
musicClass.BindMethod("GetPlayingOffset", &Nz::Music::GetPlayingOffset); music.BindMethod("GetPlayingOffset", &Nz::Music::GetPlayingOffset);
musicClass.BindMethod("GetSampleCount", &Nz::Music::GetSampleCount); music.BindMethod("GetSampleCount", &Nz::Music::GetSampleCount);
musicClass.BindMethod("GetSampleRate", &Nz::Music::GetSampleRate); music.BindMethod("GetSampleRate", &Nz::Music::GetSampleRate);
musicClass.BindMethod("GetStatus", &Nz::Music::GetStatus); music.BindMethod("GetStatus", &Nz::Music::GetStatus);
musicClass.BindMethod("IsLooping", &Nz::Music::IsLooping); music.BindMethod("IsLooping", &Nz::Music::IsLooping);
musicClass.BindMethod("OpenFromFile", &Nz::Music::OpenFromFile, Nz::MusicParams()); music.BindMethod("OpenFromFile", &Nz::Music::OpenFromFile, Nz::MusicParams());
musicClass.BindMethod("Pause", &Nz::Music::Pause); music.BindMethod("Pause", &Nz::Music::Pause);
musicClass.BindMethod("Play", &Nz::Music::Play); music.BindMethod("Play", &Nz::Music::Play);
musicClass.BindMethod("SetPlayingOffset", &Nz::Music::SetPlayingOffset); music.BindMethod("SetPlayingOffset", &Nz::Music::SetPlayingOffset);
musicClass.BindMethod("Stop", &Nz::Music::Stop); music.BindMethod("Stop", &Nz::Music::Stop);
// Manual // Manual
musicClass.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Music& music) -> 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;
}); });
/*********************************** Nz::Sound **********************************/ /*********************************** Nz::Sound **********************************/
soundClass.Inherit(soundEmitter); sound.Inherit(soundEmitter);
soundClass.BindDefaultConstructor(); sound.BindDefaultConstructor();
soundClass.BindMethod("GetBuffer", &Nz::Sound::GetBuffer); sound.BindMethod("GetBuffer", &Nz::Sound::GetBuffer);
soundClass.BindMethod("IsPlayable", &Nz::Sound::IsPlayable); sound.BindMethod("IsPlayable", &Nz::Sound::IsPlayable);
soundClass.BindMethod("IsPlaying", &Nz::Sound::IsPlaying); sound.BindMethod("IsPlaying", &Nz::Sound::IsPlaying);
soundClass.BindMethod("LoadFromFile", &Nz::Sound::LoadFromFile, Nz::SoundBufferParams()); sound.BindMethod("LoadFromFile", &Nz::Sound::LoadFromFile, Nz::SoundBufferParams());
soundClass.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset); sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset);
// Manual // Manual
soundClass.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Sound& sound) -> 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;
}); });
@ -101,9 +101,9 @@ namespace Ndk
soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported); soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported);
// Manual // Manual
soundBuffer.BindMethod("Create", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance) -> int soundBuffer.BindMethod("Create", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{ {
int index = 1; int index = 2;
Nz::AudioFormat format = lua.Check<Nz::AudioFormat>(&index); Nz::AudioFormat format = lua.Check<Nz::AudioFormat>(&index);
unsigned int sampleCount = lua.Check<unsigned int>(&index); unsigned int sampleCount = lua.Check<unsigned int>(&index);
unsigned int sampleRate = lua.Check<unsigned int>(&index); unsigned int sampleRate = lua.Check<unsigned int>(&index);
@ -116,26 +116,26 @@ namespace Ndk
return 1; return 1;
}); });
soundBuffer.BindMethod("GetSamples", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance) -> int soundBuffer.BindMethod("GetSamples", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{ {
lua.PushString(reinterpret_cast<const char*>(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16)); lua.PushString(reinterpret_cast<const char*>(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16));
return 1; return 1;
}); });
soundBuffer.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::SoundBufferRef& instance) -> 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;
}); });
@ -177,8 +177,8 @@ namespace Ndk
void LuaBinding::RegisterAudio(Nz::LuaInstance& instance) void LuaBinding::RegisterAudio(Nz::LuaInstance& instance)
{ {
musicClass.Register(instance); music.Register(instance);
soundClass.Register(instance); sound.Register(instance);
soundBuffer.Register(instance); soundBuffer.Register(instance);
soundEmitter.Register(instance); soundEmitter.Register(instance);
} }

View File

@ -13,147 +13,147 @@ namespace Ndk
void LuaBinding::BindCore() void LuaBinding::BindCore()
{ {
/*********************************** Nz::Clock **********************************/ /*********************************** Nz::Clock **********************************/
clockClass.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 = 1; int argIndex = 2;
Nz::Int64 startingValue = lua.Check<Nz::Int64>(&argIndex, 0); Nz::Int64 startingValue = lua.Check<Nz::Int64>(&argIndex, 0);
bool paused = lua.Check<bool>(&argIndex, false); bool paused = lua.Check<bool>(&argIndex, false);
Nz::PlacementNew(clock, startingValue, paused); Nz::PlacementNew(instance, startingValue, paused);
return true; return true;
}); });
clockClass.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds); clock.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds);
clockClass.BindMethod("GetMilliseconds", &Nz::Clock::GetMilliseconds); clock.BindMethod("GetMilliseconds", &Nz::Clock::GetMilliseconds);
clockClass.BindMethod("GetSeconds", &Nz::Clock::GetSeconds); clock.BindMethod("GetSeconds", &Nz::Clock::GetSeconds);
clockClass.BindMethod("IsPaused", &Nz::Clock::IsPaused); clock.BindMethod("IsPaused", &Nz::Clock::IsPaused);
clockClass.BindMethod("Pause", &Nz::Clock::Pause); clock.BindMethod("Pause", &Nz::Clock::Pause);
clockClass.BindMethod("Restart", &Nz::Clock::Restart); clock.BindMethod("Restart", &Nz::Clock::Restart);
clockClass.BindMethod("Unpause", &Nz::Clock::Unpause); clock.BindMethod("Unpause", &Nz::Clock::Unpause);
// Manual // Manual
clockClass.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Clock& clock) -> 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 ********************************/
directoryClass.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);
int argIndex = 1; int argIndex = 2;
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;
} }
return false; return false;
}); });
directoryClass.BindMethod("Close", &Nz::Directory::Close); directory.BindMethod("Close", &Nz::Directory::Close);
directoryClass.BindMethod("Exists", &Nz::Directory::Exists); directory.BindMethod("Exists", &Nz::Directory::Exists);
directoryClass.BindMethod("GetPath", &Nz::Directory::GetPath); directory.BindMethod("GetPath", &Nz::Directory::GetPath);
directoryClass.BindMethod("GetPattern", &Nz::Directory::GetPattern); directory.BindMethod("GetPattern", &Nz::Directory::GetPattern);
directoryClass.BindMethod("GetResultName", &Nz::Directory::GetResultName); directory.BindMethod("GetResultName", &Nz::Directory::GetResultName);
directoryClass.BindMethod("GetResultPath", &Nz::Directory::GetResultPath); directory.BindMethod("GetResultPath", &Nz::Directory::GetResultPath);
directoryClass.BindMethod("GetResultSize", &Nz::Directory::GetResultSize); directory.BindMethod("GetResultSize", &Nz::Directory::GetResultSize);
directoryClass.BindMethod("IsOpen", &Nz::Directory::IsOpen); directory.BindMethod("IsOpen", &Nz::Directory::IsOpen);
directoryClass.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory); directory.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory);
directoryClass.BindMethod("NextResult", &Nz::Directory::NextResult, true); directory.BindMethod("NextResult", &Nz::Directory::NextResult, true);
directoryClass.BindMethod("Open", &Nz::Directory::Open); directory.BindMethod("Open", &Nz::Directory::Open);
directoryClass.BindMethod("SetPath", &Nz::Directory::SetPath); directory.BindMethod("SetPath", &Nz::Directory::SetPath);
directoryClass.BindMethod("SetPattern", &Nz::Directory::SetPattern); directory.BindMethod("SetPattern", &Nz::Directory::SetPattern);
directoryClass.BindStaticMethod("Copy", Nz::Directory::Copy); directory.BindStaticMethod("Copy", Nz::Directory::Copy);
directoryClass.BindStaticMethod("Create", Nz::Directory::Create); directory.BindStaticMethod("Create", Nz::Directory::Create);
directoryClass.BindStaticMethod("Exists", Nz::Directory::Exists); directory.BindStaticMethod("Exists", Nz::Directory::Exists);
directoryClass.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent); directory.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent);
directoryClass.BindStaticMethod("Remove", Nz::Directory::Remove); directory.BindStaticMethod("Remove", Nz::Directory::Remove);
directoryClass.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent);
// Manual // Manual
directoryClass.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::Directory& directory) -> 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;
}); });
/*********************************** Nz::Stream ***********************************/ /*********************************** Nz::Stream ***********************************/
streamClass.BindMethod("EnableTextMode", &Nz::Stream::EnableTextMode); stream.BindMethod("EnableTextMode", &Nz::Stream::EnableTextMode);
streamClass.BindMethod("Flush", &Nz::Stream::Flush); stream.BindMethod("Flush", &Nz::Stream::Flush);
streamClass.BindMethod("GetCursorPos", &Nz::Stream::GetCursorPos); stream.BindMethod("GetCursorPos", &Nz::Stream::GetCursorPos);
streamClass.BindMethod("GetDirectory", &Nz::Stream::GetDirectory); stream.BindMethod("GetDirectory", &Nz::Stream::GetDirectory);
streamClass.BindMethod("GetPath", &Nz::Stream::GetPath); stream.BindMethod("GetPath", &Nz::Stream::GetPath);
streamClass.BindMethod("GetOpenMode", &Nz::Stream::GetOpenMode); stream.BindMethod("GetOpenMode", &Nz::Stream::GetOpenMode);
streamClass.BindMethod("GetStreamOptions", &Nz::Stream::GetStreamOptions); stream.BindMethod("GetStreamOptions", &Nz::Stream::GetStreamOptions);
streamClass.BindMethod("GetSize", &Nz::Stream::GetSize); stream.BindMethod("GetSize", &Nz::Stream::GetSize);
streamClass.BindMethod("ReadLine", &Nz::Stream::ReadLine, 0U); stream.BindMethod("ReadLine", &Nz::Stream::ReadLine, 0U);
streamClass.BindMethod("IsReadable", &Nz::Stream::IsReadable); stream.BindMethod("IsReadable", &Nz::Stream::IsReadable);
streamClass.BindMethod("IsSequential", &Nz::Stream::IsSequential); stream.BindMethod("IsSequential", &Nz::Stream::IsSequential);
streamClass.BindMethod("IsTextModeEnabled", &Nz::Stream::IsTextModeEnabled); stream.BindMethod("IsTextModeEnabled", &Nz::Stream::IsTextModeEnabled);
streamClass.BindMethod("IsWritable", &Nz::Stream::IsWritable); stream.BindMethod("IsWritable", &Nz::Stream::IsWritable);
streamClass.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos); stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos);
streamClass.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& stream) -> int { stream.BindMethod("Read", [] (Nz::LuaInstance& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int {
int argIndex = 1; 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;
}); });
streamClass.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& stream) -> int { stream.BindMethod("Write", [] (Nz::LuaInstance& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int {
int argIndex = 1; 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 ***********************************/
fileClass.Inherit(streamClass); file.Inherit(stream);
fileClass.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);
int argIndex = 1; int argIndex = 2;
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 +162,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;
} }
} }
@ -171,52 +171,52 @@ namespace Ndk
return false; return false;
}); });
fileClass.BindMethod("Close", &Nz::File::Close); file.BindMethod("Close", &Nz::File::Close);
fileClass.BindMethod("Copy", &Nz::File::Copy); file.BindMethod("Copy", &Nz::File::Copy);
fileClass.BindMethod("Delete", &Nz::File::Delete); file.BindMethod("Delete", &Nz::File::Delete);
fileClass.BindMethod("EndOfFile", &Nz::File::EndOfFile); file.BindMethod("EndOfFile", &Nz::File::EndOfFile);
fileClass.BindMethod("Exists", &Nz::File::Exists); file.BindMethod("Exists", &Nz::File::Exists);
fileClass.BindMethod("GetCreationTime", &Nz::File::GetCreationTime); file.BindMethod("GetCreationTime", &Nz::File::GetCreationTime);
fileClass.BindMethod("GetFileName", &Nz::File::GetFileName); file.BindMethod("GetFileName", &Nz::File::GetFileName);
fileClass.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); file.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime);
fileClass.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
fileClass.BindMethod("IsOpen", &Nz::File::IsOpen); file.BindMethod("IsOpen", &Nz::File::IsOpen);
fileClass.BindMethod("Rename", &Nz::File::GetLastWriteTime); file.BindMethod("Rename", &Nz::File::GetLastWriteTime);
fileClass.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
fileClass.BindMethod("SetFile", &Nz::File::GetLastWriteTime); file.BindMethod("SetFile", &Nz::File::GetLastWriteTime);
fileClass.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath); file.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath);
fileClass.BindStaticMethod("ComputeHash", (Nz::ByteArray (*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash); file.BindStaticMethod("ComputeHash", (Nz::ByteArray (*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash);
fileClass.BindStaticMethod("Copy", &Nz::File::Copy); file.BindStaticMethod("Copy", &Nz::File::Copy);
fileClass.BindStaticMethod("Delete", &Nz::File::Delete); file.BindStaticMethod("Delete", &Nz::File::Delete);
fileClass.BindStaticMethod("Exists", &Nz::File::Exists); file.BindStaticMethod("Exists", &Nz::File::Exists);
//fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime); //fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime);
fileClass.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory); file.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory);
//fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); //fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime);
//fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); //fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
fileClass.BindStaticMethod("GetSize", &Nz::File::GetSize); file.BindStaticMethod("GetSize", &Nz::File::GetSize);
fileClass.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute); file.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute);
fileClass.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath); file.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath);
fileClass.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators); file.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators);
fileClass.BindStaticMethod("Rename", &Nz::File::Rename); file.BindStaticMethod("Rename", &Nz::File::Rename);
// Manual // Manual
fileClass.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& file) -> int file.BindMethod("Open", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int
{ {
unsigned int argCount = std::min(lua.GetStackTop(), 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 1; int argIndex = 2;
switch (argCount) switch (argCount)
{ {
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,21 +224,21 @@ namespace Ndk
return 0; return 0;
}); });
fileClass.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& file) -> int file.BindMethod("SetCursorPos", [] (Nz::LuaInstance& lua, Nz::File& instance, std::size_t argumentCount) -> int
{ {
unsigned int argCount = std::min(lua.GetStackTop(), 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 1; int argIndex = 2;
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 +246,14 @@ namespace Ndk
return 0; return 0;
}); });
fileClass.BindMethod("__tostring", [] (Nz::LuaInstance& lua, Nz::File& file) -> 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;
}); });
} }
@ -267,10 +267,10 @@ namespace Ndk
void LuaBinding::RegisterCore(Nz::LuaInstance& instance) void LuaBinding::RegisterCore(Nz::LuaInstance& instance)
{ {
// Classes // Classes
clockClass.Register(instance); clock.Register(instance);
directoryClass.Register(instance); directory.Register(instance);
fileClass.Register(instance); file.Register(instance);
streamClass.Register(instance); stream.Register(instance);
// Enums // Enums

View File

@ -14,34 +14,305 @@ namespace Ndk
{ {
/*********************************** Nz::InstancedRenderable ***********************************/ /*********************************** Nz::InstancedRenderable ***********************************/
/*********************************** Nz::Model ***********************************/ /*********************************** Nz::Material ***********************************/
modelClass.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::ModelRef* model) -> Nz::InstancedRenderableRef* material.SetConstructor([] (Nz::LuaInstance& lua, Nz::MaterialRef* instance, std::size_t argumentCount)
{ {
return reinterpret_cast<Nz::InstancedRenderableRef*>(model); //TODO: Make a ObjectRefCast switch (argumentCount)
{
case 0:
Nz::PlacementNew(instance, Nz::Material::New());
return true;
case 1:
{
int argIndex = 1;
if (lua.IsOfType(argIndex, "MaterialPipeline"))
{
Nz::PlacementNew(instance, Nz::Material::New(*static_cast<Nz::MaterialPipelineRef*>(lua.ToUserdata(argIndex))));
return true;
}
else if (lua.IsOfType(argIndex, "Material"))
{
Nz::PlacementNew(instance, Nz::Material::New(**static_cast<Nz::MaterialRef*>(lua.ToUserdata(argIndex))));
return true;
}
else
{
Nz::PlacementNew(instance, Nz::Material::New(lua.Check<Nz::String>(&argIndex)));
return true;
}
}
}
lua.Error("No matching overload for constructor");
return false;
}); });
modelClass.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* model, std::size_t /*argumentCount*/) material.BindMethod("Configure", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{ {
Nz::PlacementNew(model, Nz::Model::New()); int argIndex = 2;
if (lua.IsOfType(argIndex, "MaterialPipeline"))
{
instance->Configure(*static_cast<Nz::MaterialPipelineRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
{
lua.Push(instance->Configure(lua.Check<Nz::String>(&argIndex)));
return 1;
}
});
material.BindMethod("EnableAlphaTest", &Nz::Material::EnableAlphaTest);
material.BindMethod("EnableBlending", &Nz::Material::EnableBlending);
material.BindMethod("EnableColorWrite", &Nz::Material::EnableColorWrite);
material.BindMethod("EnableDepthBuffer", &Nz::Material::EnableDepthBuffer);
material.BindMethod("EnableDepthSorting", &Nz::Material::EnableDepthSorting);
material.BindMethod("EnableDepthWrite", &Nz::Material::EnableDepthWrite);
material.BindMethod("EnableFaceCulling", &Nz::Material::EnableFaceCulling);
material.BindMethod("EnableScissorTest", &Nz::Material::EnableScissorTest);
material.BindMethod("EnableShadowCasting", &Nz::Material::EnableShadowCasting);
material.BindMethod("EnableShadowReceive", &Nz::Material::EnableShadowReceive);
material.BindMethod("EnableStencilTest", &Nz::Material::EnableStencilTest);
material.BindMethod("EnsurePipelineUpdate", &Nz::Material::EnsurePipelineUpdate);
material.BindMethod("GetAlphaMap", &Nz::Material::GetAlphaMap);
material.BindMethod("GetAlphaThreshold", &Nz::Material::GetAlphaThreshold);
material.BindMethod("GetAmbientColor", &Nz::Material::GetAmbientColor);
material.BindMethod("GetDepthFunc", &Nz::Material::GetDepthFunc);
material.BindMethod("GetDepthMaterial", &Nz::Material::GetDepthMaterial);
material.BindMethod("GetDiffuseColor", &Nz::Material::GetDiffuseColor);
material.BindMethod("GetDiffuseMap", &Nz::Material::GetDiffuseMap);
//material.BindMethod("GetDiffuseSampler", &Nz::Material::GetDiffuseSampler);
material.BindMethod("GetDstBlend", &Nz::Material::GetDstBlend);
material.BindMethod("GetEmissiveMap", &Nz::Material::GetEmissiveMap);
material.BindMethod("GetFaceCulling", &Nz::Material::GetFaceCulling);
material.BindMethod("GetFaceFilling", &Nz::Material::GetFaceFilling);
material.BindMethod("GetHeightMap", &Nz::Material::GetHeightMap);
material.BindMethod("GetLineWidth", &Nz::Material::GetLineWidth);
material.BindMethod("GetNormalMap", &Nz::Material::GetNormalMap);
//material.BindMethod("GetPipeline", &Nz::Material::GetPipeline);
//material.BindMethod("GetPipelineInfo", &Nz::Material::GetPipelineInfo);
material.BindMethod("GetPointSize", &Nz::Material::GetPointSize);
//material.BindMethod("GetShader", &Nz::Material::GetShader);
material.BindMethod("GetShininess", &Nz::Material::GetShininess);
material.BindMethod("GetSpecularColor", &Nz::Material::GetSpecularColor);
material.BindMethod("GetSpecularMap", &Nz::Material::GetSpecularMap);
//material.BindMethod("GetSpecularSampler", &Nz::Material::GetSpecularSampler);
material.BindMethod("GetSrcBlend", &Nz::Material::GetSrcBlend);
material.BindMethod("HasAlphaMap", &Nz::Material::HasAlphaMap);
material.BindMethod("HasDepthMaterial", &Nz::Material::HasDepthMaterial);
material.BindMethod("HasDiffuseMap", &Nz::Material::HasDiffuseMap);
material.BindMethod("HasEmissiveMap", &Nz::Material::HasEmissiveMap);
material.BindMethod("HasHeightMap", &Nz::Material::HasHeightMap);
material.BindMethod("HasNormalMap", &Nz::Material::HasNormalMap);
material.BindMethod("HasSpecularMap", &Nz::Material::HasSpecularMap);
material.BindMethod("IsAlphaTestEnabled", &Nz::Material::IsAlphaTestEnabled);
material.BindMethod("IsBlendingEnabled", &Nz::Material::IsBlendingEnabled);
material.BindMethod("IsColorWriteEnabled", &Nz::Material::IsColorWriteEnabled);
material.BindMethod("IsDepthBufferEnabled", &Nz::Material::IsDepthBufferEnabled);
material.BindMethod("IsDepthSortingEnabled", &Nz::Material::IsDepthSortingEnabled);
material.BindMethod("IsDepthWriteEnabled", &Nz::Material::IsDepthWriteEnabled);
material.BindMethod("IsFaceCullingEnabled", &Nz::Material::IsFaceCullingEnabled);
material.BindMethod("IsScissorTestEnabled", &Nz::Material::IsScissorTestEnabled);
material.BindMethod("IsStencilTestEnabled", &Nz::Material::IsStencilTestEnabled);
material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled);
material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled);
material.BindMethod("LoadFromFile", &Nz::Material::LoadFromFile);
material.BindMethod("Reset", &Nz::Material::Reset);
material.BindMethod("SetAlphaThreshold", &Nz::Material::SetAlphaThreshold);
material.BindMethod("SetAmbientColor", &Nz::Material::SetAmbientColor);
material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc);
material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc);
material.BindMethod("SetDepthMaterial", &Nz::Material::SetDepthMaterial);
material.BindMethod("SetDiffuseColor", &Nz::Material::SetDiffuseColor);
//material.BindMethod("SetDiffuseSampler", &Nz::Material::SetDiffuseSampler);
material.BindMethod("SetDstBlend", &Nz::Material::SetDstBlend);
material.BindMethod("SetFaceCulling", &Nz::Material::SetFaceCulling);
material.BindMethod("SetFaceFilling", &Nz::Material::SetFaceFilling);
material.BindMethod("SetLineWidth", &Nz::Material::SetLineWidth);
material.BindMethod("SetPointSize", &Nz::Material::SetPointSize);
material.BindMethod("SetShininess", &Nz::Material::SetShininess);
material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor);
material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor);
//material.BindMethod("SetSpecularSampler", &Nz::Material::SetSpecularSampler);
material.BindMethod("SetSrcBlend", &Nz::Material::SetSrcBlend);
material.BindStaticMethod("GetDefault", &Nz::Material::GetDefault);
material.BindMethod("SetAlphaMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetAlphaMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetAlphaMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetDiffuseMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetDiffuseMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetDiffuseMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetEmissiveMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetEmissiveMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetEmissiveMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetHeightMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetHeightMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetHeightMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetNormalMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetNormalMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetNormalMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetShader", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "UberShader"))
{
instance->SetShader(*static_cast<Nz::UberShaderRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetShader(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetSpecularMap", [] (Nz::LuaInstance& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetSpecularMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetSpecularMap(lua.Check<Nz::String>(&argIndex)));
});
/*********************************** Nz::Model ***********************************/
model.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::ModelRef* modelRef) -> Nz::InstancedRenderableRef*
{
return reinterpret_cast<Nz::InstancedRenderableRef*>(modelRef); //TODO: Make a ObjectRefCast
});
model.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::ModelRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Model::New());
return true; return true;
}); });
//modelClass.SetMethod("GetMaterial", &Nz::Model::GetMaterial); //model.BindMethod("GetMaterial", &Nz::Model::GetMaterial);
modelClass.BindMethod("GetMaterialCount", &Nz::Model::GetMaterialCount); model.BindMethod("GetMaterialCount", &Nz::Model::GetMaterialCount);
//modelClass.SetMethod("GetMesh", &Nz::Model::GetMesh); //modelClass.SetMethod("GetMesh", &Nz::Model::GetMesh);
modelClass.BindMethod("GetSkin", &Nz::Model::GetSkin); model.BindMethod("GetSkin", &Nz::Model::GetSkin);
modelClass.BindMethod("GetSkinCount", &Nz::Model::GetSkinCount); model.BindMethod("GetSkinCount", &Nz::Model::GetSkinCount);
modelClass.BindMethod("IsAnimated", &Nz::Model::IsAnimated); model.BindMethod("IsAnimated", &Nz::Model::IsAnimated);
modelClass.BindMethod("LoadFromFile", &Nz::Model::LoadFromFile, Nz::ModelParameters()); model.BindMethod("LoadFromFile", &Nz::Model::LoadFromFile, Nz::ModelParameters());
modelClass.BindMethod("Reset", &Nz::Model::Reset); model.BindMethod("Reset", &Nz::Model::Reset);
//modelClass.SetMethod("SetMaterial", &Nz::Model::SetMaterial); //model.BindMethod("SetMaterial", &Nz::Model::SetMaterial);
//modelClass.SetMethod("SetMesh", &Nz::Model::SetMesh); //modelClass.SetMethod("SetMesh", &Nz::Model::SetMesh);
//modelClass.SetMethod("SetSequence", &Nz::Model::SetSequence); //modelClass.SetMethod("SetSequence", &Nz::Model::SetSequence);
modelClass.BindMethod("SetSkin", &Nz::Model::SetSkin); model.BindMethod("SetSkin", &Nz::Model::SetSkin);
modelClass.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount); model.BindMethod("SetSkinCount", &Nz::Model::SetSkinCount);
/*********************************** Nz::Sprite ***********************************/
sprite.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::SpriteRef* spriteRef) -> Nz::InstancedRenderableRef*
{
return reinterpret_cast<Nz::InstancedRenderableRef*>(spriteRef); //TODO: Make a ObjectRefCast
});
sprite.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::SpriteRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Sprite::New());
return true;
});
sprite.BindMethod("GetColor", &Nz::Sprite::GetColor);
sprite.BindMethod("GetCornerColor", &Nz::Sprite::GetCornerColor);
sprite.BindMethod("GetMaterial", &Nz::Sprite::GetMaterial);
sprite.BindMethod("GetOrigin", &Nz::Sprite::GetOrigin);
sprite.BindMethod("GetSize", &Nz::Sprite::GetSize);
sprite.BindMethod("GetTextureCoords", &Nz::Sprite::GetTextureCoords);
sprite.BindMethod("SetColor", &Nz::Sprite::SetColor);
sprite.BindMethod("SetCornerColor", &Nz::Sprite::SetCornerColor);
sprite.BindMethod("SetDefaultMaterial", &Nz::Sprite::SetDefaultMaterial);
sprite.BindMethod("SetMaterial", &Nz::Sprite::SetMaterial, true);
sprite.BindMethod("SetOrigin", &Nz::Sprite::SetOrigin);
sprite.BindMethod("SetSize", (void(Nz::Sprite::*)(const Nz::Vector2f&)) &Nz::Sprite::SetSize);
sprite.BindMethod("SetTexture", &Nz::Sprite::SetTexture, true);
sprite.BindMethod("SetTextureCoords", &Nz::Sprite::SetTextureCoords);
sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect);
/*********************************** Nz::SpriteLibrary ***********************************/
spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get);
spriteLibrary.BindStaticMethod("Has", &Nz::SpriteLibrary::Has);
spriteLibrary.BindStaticMethod("Register", &Nz::SpriteLibrary::Register);
spriteLibrary.BindStaticMethod("Query", &Nz::SpriteLibrary::Query);
spriteLibrary.BindStaticMethod("Unregister", &Nz::SpriteLibrary::Unregister);
/*********************************** Nz::TextureLibrary ***********************************/
textureLibrary.BindStaticMethod("Get", &Nz::TextureLibrary::Get);
textureLibrary.BindStaticMethod("Has", &Nz::TextureLibrary::Has);
textureLibrary.BindStaticMethod("Register", &Nz::TextureLibrary::Register);
textureLibrary.BindStaticMethod("Query", &Nz::TextureLibrary::Query);
textureLibrary.BindStaticMethod("Unregister", &Nz::TextureLibrary::Unregister);
/*********************************** Nz::TextureManager ***********************************/
textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear);
textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get);
textureManager.BindStaticMethod("GetDefaultParameters", &Nz::TextureManager::GetDefaultParameters);
textureManager.BindStaticMethod("Purge", &Nz::TextureManager::Purge);
textureManager.BindStaticMethod("Register", &Nz::TextureManager::Register);
textureManager.BindStaticMethod("SetDefaultParameters", &Nz::TextureManager::SetDefaultParameters);
textureManager.BindStaticMethod("Unregister", &Nz::TextureManager::Unregister);
} }
/*! /*!
@ -53,6 +324,11 @@ namespace Ndk
void LuaBinding::RegisterGraphics(Nz::LuaInstance& instance) void LuaBinding::RegisterGraphics(Nz::LuaInstance& instance)
{ {
instancedRenderable.Register(instance); instancedRenderable.Register(instance);
modelClass.Register(instance); material.Register(instance);
model.Register(instance);
sprite.Register(instance);
spriteLibrary.Register(instance);
textureLibrary.Register(instance);
textureManager.Register(instance);
} }
} }

View File

@ -14,22 +14,22 @@ namespace Ndk
void LuaBinding::BindMath() void LuaBinding::BindMath()
{ {
/*********************************** Nz::EulerAngles **********************************/ /*********************************** Nz::EulerAngles **********************************/
eulerAnglesClass.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,12 +37,12 @@ namespace Ndk
return false; return false;
}); });
eulerAnglesClass.BindMethod("__tostring", &Nz::EulerAnglesd::ToString); eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString);
eulerAnglesClass.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) eulerAngles.SetGetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance)
{ {
std::size_t length; std::size_t length;
const char* ypr = lua.CheckString(1, &length); const char* ypr = lua.CheckString(2, &length);
switch (length) switch (length)
{ {
@ -96,11 +96,11 @@ namespace Ndk
return false; return false;
}); });
eulerAnglesClass.SetSetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance) eulerAngles.SetSetter([] (Nz::LuaInstance& lua, Nz::EulerAnglesd& instance)
{ {
std::size_t length; std::size_t length;
const char* ypr = lua.CheckString(1, &length); const char* ypr = lua.CheckString(2, &length);
double value = lua.CheckNumber(2); double value = lua.CheckNumber(3);
switch (length) switch (length)
{ {
@ -154,8 +154,213 @@ namespace Ndk
return false; return false;
}); });
/*********************************** Nz::Matrix4 **********************************/
matrix4d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Matrix4d* matrix, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 0:
Nz::PlacementNew(matrix, Nz::Matrix4d::Zero());
return true;
case 1:
if (lua.IsOfType(1, "Matrix4"))
Nz::PlacementNew(matrix, *static_cast<Nz::Matrix4d*>(lua.ToUserdata(1)));
break;
case 16:
{
double values[16];
for (std::size_t i = 0; i < 16; ++i)
values[i] = lua.CheckNumber(i);
Nz::PlacementNew(matrix, values);
return true;
}
}
lua.Error("No matching overload for constructor");
return false;
});
matrix4d.BindMethod("ApplyRotation", &Nz::Matrix4d::ApplyRotation);
matrix4d.BindMethod("ApplyScale", &Nz::Matrix4d::ApplyScale);
matrix4d.BindMethod("ApplyTranslation", &Nz::Matrix4d::ApplyTranslation);
matrix4d.BindMethod("Concatenate", &Nz::Matrix4d::Concatenate);
matrix4d.BindMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine);
//matrix4d.BindMethod("GetColumn", &Nz::Matrix4d::GetColumn);
matrix4d.BindMethod("GetDeterminant", &Nz::Matrix4d::GetDeterminant);
matrix4d.BindMethod("GetDeterminantAffine", &Nz::Matrix4d::GetDeterminantAffine);
matrix4d.BindMethod("GetInverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
if (instance.GetInverse(&result))
return lua.Push(true, result);
else
return lua.Push(false);
});
matrix4d.BindMethod("GetInverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
if (instance.GetInverseAffine(&result))
return lua.Push(true, result);
else
return lua.Push(false);
});
matrix4d.BindMethod("GetRotation", &Nz::Matrix4d::GetRotation);
//matrix4d.BindMethod("GetRow", &Nz::Matrix4d::GetRow);
matrix4d.BindMethod("GetScale", &Nz::Matrix4d::GetScale);
matrix4d.BindMethod("GetSquaredScale", &Nz::Matrix4d::GetSquaredScale);
matrix4d.BindMethod("GetTranslation", &Nz::Matrix4d::GetTranslation);
matrix4d.BindMethod("GetTransposed", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
instance.GetTransposed(&result);
return lua.Push(result);
});
matrix4d.BindMethod("HasNegativeScale", &Nz::Matrix4d::HasNegativeScale);
matrix4d.BindMethod("HasScale", &Nz::Matrix4d::HasScale);
matrix4d.BindMethod("Inverse", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
bool succeeded;
instance.Inverse(&succeeded);
return lua.Push(succeeded);
});
matrix4d.BindMethod("InverseAffine", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
bool succeeded;
instance.InverseAffine(&succeeded);
return lua.Push(succeeded);
});
matrix4d.BindMethod("IsAffine", &Nz::Matrix4d::IsAffine);
matrix4d.BindMethod("IsIdentity", &Nz::Matrix4d::IsIdentity);
matrix4d.BindMethod("MakeIdentity", &Nz::Matrix4d::MakeIdentity);
matrix4d.BindMethod("MakeLookAt", &Nz::Matrix4d::MakeLookAt, Nz::Vector3d::Up());
matrix4d.BindMethod("MakeOrtho", &Nz::Matrix4d::MakeOrtho, -1.0, 1.0);
matrix4d.BindMethod("MakePerspective", &Nz::Matrix4d::MakePerspective);
matrix4d.BindMethod("MakeRotation", &Nz::Matrix4d::MakeRotation);
matrix4d.BindMethod("MakeScale", &Nz::Matrix4d::MakeScale);
matrix4d.BindMethod("MakeTranslation", &Nz::Matrix4d::MakeTranslation);
matrix4d.BindMethod("MakeTransform", (Nz::Matrix4d&(Nz::Matrix4d::*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::MakeTransform, Nz::Vector3d::Unit());
matrix4d.BindMethod("MakeViewMatrix", &Nz::Matrix4d::MakeViewMatrix);
matrix4d.BindMethod("MakeZero", &Nz::Matrix4d::MakeZero);
matrix4d.BindMethod("Set", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
int argIndex = 2;
switch (argCount)
{
case 1:
if (lua.IsOfType(argIndex, "Matrix4"))
instance.Set(*static_cast<Nz::Matrix4d*>(lua.ToUserdata(argIndex)));
break;
case 16:
{
double values[16];
for (std::size_t i = 0; i < 16; ++i)
values[i] = lua.CheckNumber(argIndex++);
instance.Set(values);
return 0;
}
}
lua.Error("No matching overload for method Set");
return 0;
});
matrix4d.BindMethod("SetRotation", &Nz::Matrix4d::SetRotation);
matrix4d.BindMethod("SetScale", &Nz::Matrix4d::SetScale);
matrix4d.BindMethod("SetTranslation", &Nz::Matrix4d::SetTranslation);
matrix4d.BindMethod("Transform", [] (Nz::LuaInstance& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Vector2"))
{
double z(lua.CheckNumber(argIndex+1, 0.0));
double w(lua.CheckNumber(argIndex+2, 1.0));
return lua.Push(instance.Transform(*static_cast<Nz::Vector2d*>(lua.ToUserdata(argIndex)), z, w));
}
else if (lua.IsOfType(argIndex, "Vector3"))
{
double w(lua.CheckNumber(argIndex+1, 1.0));
return lua.Push(instance.Transform(*static_cast<Nz::Vector3d*>(lua.ToUserdata(argIndex)), w));
}
//else if (lua.IsOfType(2, "Vector4"))
// return lua.Push(instance.Transform(*static_cast<Nz::Vector4d*>(lua.ToUserdata(1))));
lua.Error("No matching overload for method Transform");
return 0;
});
matrix4d.BindMethod("Transpose", &Nz::Matrix4d::Transpose);
matrix4d.BindMethod("__tostring", &Nz::Matrix4d::ToString);
matrix4d.BindStaticMethod("Concatenate", &Nz::Matrix4d::Concatenate);
matrix4d.BindStaticMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine);
matrix4d.BindStaticMethod("Identity", &Nz::Matrix4d::Identity);
matrix4d.BindStaticMethod("LookAt", &Nz::Matrix4d::LookAt, Nz::Vector3d::Up());
matrix4d.BindStaticMethod("Ortho", &Nz::Matrix4d::Ortho, -1.0, 1.0);
matrix4d.BindStaticMethod("Perspective", &Nz::Matrix4d::Perspective);
matrix4d.BindStaticMethod("Rotate", &Nz::Matrix4d::Rotate);
matrix4d.BindStaticMethod("Scale", &Nz::Matrix4d::Scale);
matrix4d.BindStaticMethod("Translate", &Nz::Matrix4d::Translate);
matrix4d.BindStaticMethod("Transform", (Nz::Matrix4d(*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::Transform, Nz::Vector3d::Unit());
matrix4d.BindStaticMethod("ViewMatrix", &Nz::Matrix4d::ViewMatrix);
matrix4d.BindStaticMethod("Zero", &Nz::Matrix4d::Zero);
matrix4d.SetGetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance)
{
bool succeeded = false;
std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded));
if (!succeeded || index < 1 || index > 16)
return false;
lua.Push(instance[index - 1]);
return true;
});
matrix4d.SetSetter([] (Nz::LuaInstance& lua, Nz::Matrix4d& instance)
{
bool succeeded = false;
std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded));
if (!succeeded || index < 1 || index > 16)
return false;
instance[index - 1] = lua.CheckNumber(3);
return true;
});
/*********************************** Nz::Rect **********************************/ /*********************************** Nz::Rect **********************************/
rectClass.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);
@ -163,23 +368,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;
@ -189,9 +394,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;
@ -203,15 +408,15 @@ namespace Ndk
return false; return false;
}); });
rectClass.BindMethod("__tostring", &Nz::Rectd::ToString); rect.BindMethod("__tostring", &Nz::Rectd::ToString);
rectClass.SetGetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) rect.SetGetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance)
{ {
switch (lua.GetType(1)) switch (lua.GetType(2))
{ {
case Nz::LuaType_Number: case Nz::LuaType_Number:
{ {
auto index = lua.CheckBoundInteger<std::size_t>(1); auto index = lua.CheckBoundInteger<std::size_t>(2);
if (index < 1 || index > 4) if (index < 1 || index > 4)
return false; return false;
@ -222,7 +427,7 @@ namespace Ndk
case Nz::LuaType_String: case Nz::LuaType_String:
{ {
std::size_t length; std::size_t length;
const char* xywh = lua.CheckString(1, &length); const char* xywh = lua.CheckString(2, &length);
if (length != 1) if (length != 1)
break; break;
@ -258,13 +463,13 @@ namespace Ndk
return false; return false;
}); });
rectClass.SetSetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance) rect.SetSetter([] (Nz::LuaInstance& lua, Nz::Rectd& instance)
{ {
switch (lua.GetType(1)) switch (lua.GetType(2))
{ {
case Nz::LuaType_Number: case Nz::LuaType_Number:
{ {
auto index = lua.CheckBoundInteger<std::size_t>(1); auto index = lua.CheckBoundInteger<std::size_t>(2);
if (index < 1 || index > 4) if (index < 1 || index > 4)
return false; return false;
@ -275,12 +480,12 @@ namespace Ndk
case Nz::LuaType_String: case Nz::LuaType_String:
{ {
std::size_t length; std::size_t length;
const char* xywh = lua.CheckString(1, &length); const char* xywh = lua.CheckString(2, &length);
if (length != 1) if (length != 1)
break; break;
double value = lua.CheckNumber(2); double value = lua.CheckNumber(3);
switch (xywh[0]) switch (xywh[0])
{ {
@ -311,22 +516,22 @@ namespace Ndk
}); });
/*********************************** Nz::Quaternion **********************************/ /*********************************** Nz::Quaternion **********************************/
quaternionClass.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;
@ -334,11 +539,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:
@ -349,12 +554,12 @@ namespace Ndk
return false; return false;
}); });
quaternionClass.BindMethod("__tostring", &Nz::Quaterniond::ToString); quaternion.BindMethod("__tostring", &Nz::Quaterniond::ToString);
quaternionClass.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) quaternion.SetGetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance)
{ {
std::size_t length; std::size_t length;
const char* wxyz = lua.CheckString(1, &length); const char* wxyz = lua.CheckString(2, &length);
if (length != 1) if (length != 1)
return false; return false;
@ -381,15 +586,15 @@ namespace Ndk
return false; return false;
}); });
quaternionClass.SetSetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance) quaternion.SetSetter([] (Nz::LuaInstance& lua, Nz::Quaterniond& instance)
{ {
std::size_t length; std::size_t length;
const char* wxyz = lua.CheckString(1, &length); const char* wxyz = lua.CheckString(2, &length);
if (length != 1) if (length != 1)
return false; return false;
double value = lua.CheckNumber(2); double value = lua.CheckNumber(3);
switch (wxyz[0]) switch (wxyz[0])
{ {
@ -417,7 +622,7 @@ namespace Ndk
}); });
/*********************************** Nz::Vector2 **********************************/ /*********************************** Nz::Vector2 **********************************/
vector2dClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector2d* vector, std::size_t argumentCount) vector2d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector2d* vector, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
@ -445,15 +650,15 @@ namespace Ndk
return false; return false;
}); });
vector2dClass.BindMethod("__tostring", &Nz::Vector2d::ToString); vector2d.BindMethod("__tostring", &Nz::Vector2d::ToString);
vector2dClass.SetGetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance) vector2d.SetGetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance)
{ {
switch (lua.GetType(1)) switch (lua.GetType(2))
{ {
case Nz::LuaType_Number: case Nz::LuaType_Number:
{ {
long long index = lua.CheckInteger(1); long long index = lua.CheckInteger(2);
if (index < 1 || index > 2) if (index < 1 || index > 2)
return false; return false;
@ -464,7 +669,7 @@ namespace Ndk
case Nz::LuaType_String: case Nz::LuaType_String:
{ {
std::size_t length; std::size_t length;
const char* xy = lua.CheckString(1, &length); const char* xy = lua.CheckString(2, &length);
if (length != 1) if (length != 1)
break; break;
@ -492,29 +697,29 @@ namespace Ndk
return false; return false;
}); });
vector2dClass.SetSetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance) vector2d.SetSetter([](Nz::LuaInstance& lua, Nz::Vector2d& instance)
{ {
switch (lua.GetType(1)) switch (lua.GetType(2))
{ {
case Nz::LuaType_Number: case Nz::LuaType_Number:
{ {
long long index = lua.CheckInteger(1); long long index = lua.CheckInteger(2);
if (index < 1 || index > 2) if (index < 1 || index > 2)
return false; return false;
instance[index - 1] = lua.CheckNumber(2); instance[index - 1] = lua.CheckNumber(3);
return true; return true;
} }
case Nz::LuaType_String: case Nz::LuaType_String:
{ {
std::size_t length; std::size_t length;
const char* xy = lua.CheckString(1, &length); const char* xy = lua.CheckString(2, &length);
if (length != 1) if (length != 1)
break; break;
double value = lua.CheckNumber(2); double value = lua.CheckNumber(3);
switch (xy[0]) switch (xy[0])
{ {
@ -540,7 +745,7 @@ namespace Ndk
}); });
/*********************************** Nz::Vector3 **********************************/ /*********************************** Nz::Vector3 **********************************/
vector3dClass.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector3d* vector, std::size_t argumentCount) vector3d.SetConstructor([] (Nz::LuaInstance& lua, Nz::Vector3d* vector, std::size_t argumentCount)
{ {
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U); std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
@ -582,15 +787,15 @@ namespace Ndk
return false; return false;
}); });
vector3dClass.BindMethod("__tostring", &Nz::Vector3d::ToString); vector3d.BindMethod("__tostring", &Nz::Vector3d::ToString);
vector3dClass.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) vector3d.SetGetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance)
{ {
switch (lua.GetType(1)) switch (lua.GetType(2))
{ {
case Nz::LuaType_Number: case Nz::LuaType_Number:
{ {
long long index = lua.CheckInteger(1); long long index = lua.CheckInteger(2);
if (index < 1 || index > 3) if (index < 1 || index > 3)
return false; return false;
@ -601,7 +806,7 @@ namespace Ndk
case Nz::LuaType_String: case Nz::LuaType_String:
{ {
std::size_t length; std::size_t length;
const char* xyz = lua.CheckString(1, &length); const char* xyz = lua.CheckString(2, &length);
if (length != 1) if (length != 1)
break; break;
@ -633,29 +838,29 @@ namespace Ndk
return false; return false;
}); });
vector3dClass.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance) vector3d.SetSetter([] (Nz::LuaInstance& lua, Nz::Vector3d& instance)
{ {
switch (lua.GetType(1)) switch (lua.GetType(2))
{ {
case Nz::LuaType_Number: case Nz::LuaType_Number:
{ {
long long index = lua.CheckInteger(1); long long index = lua.CheckInteger(2);
if (index < 1 || index > 3) if (index < 1 || index > 3)
return false; return false;
instance[index - 1] = lua.CheckNumber(2); instance[index - 1] = lua.CheckNumber(3);
return true; return true;
} }
case Nz::LuaType_String: case Nz::LuaType_String:
{ {
std::size_t length; std::size_t length;
const char* xyz = lua.CheckString(1, &length); const char* xyz = lua.CheckString(2, &length);
if (length != 1) if (length != 1)
break; break;
double value = lua.CheckNumber(2); double value = lua.CheckNumber(3);
switch (xyz[0]) switch (xyz[0])
{ {
@ -693,10 +898,11 @@ namespace Ndk
void LuaBinding::RegisterMath(Nz::LuaInstance& instance) void LuaBinding::RegisterMath(Nz::LuaInstance& instance)
{ {
eulerAnglesClass.Register(instance); eulerAngles.Register(instance);
quaternionClass.Register(instance); matrix4d.Register(instance);
rectClass.Register(instance); quaternion.Register(instance);
vector2dClass.Register(instance); rect.Register(instance);
vector3dClass.Register(instance); vector2d.Register(instance);
vector3d.Register(instance);
} }
} }

View File

@ -12,28 +12,28 @@ namespace Ndk
void LuaBinding::BindNetwork() void LuaBinding::BindNetwork()
{ {
/*********************************** Nz::AbstractSocket **********************************/ /*********************************** Nz::AbstractSocket **********************************/
abstractSocketClass.BindMethod("Close", &Nz::AbstractSocket::Close); abstractSocket.BindMethod("Close", &Nz::AbstractSocket::Close);
abstractSocketClass.BindMethod("EnableBlocking", &Nz::AbstractSocket::EnableBlocking); abstractSocket.BindMethod("EnableBlocking", &Nz::AbstractSocket::EnableBlocking);
abstractSocketClass.BindMethod("GetLastError", &Nz::AbstractSocket::GetLastError); abstractSocket.BindMethod("GetLastError", &Nz::AbstractSocket::GetLastError);
abstractSocketClass.BindMethod("GetState", &Nz::AbstractSocket::GetState); abstractSocket.BindMethod("GetState", &Nz::AbstractSocket::GetState);
abstractSocketClass.BindMethod("GetType", &Nz::AbstractSocket::GetType); abstractSocket.BindMethod("GetType", &Nz::AbstractSocket::GetType);
abstractSocketClass.BindMethod("IsBlockingEnabled", &Nz::AbstractSocket::IsBlockingEnabled); abstractSocket.BindMethod("IsBlockingEnabled", &Nz::AbstractSocket::IsBlockingEnabled);
abstractSocketClass.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes); abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes);
/*********************************** Nz::IpAddress **********************************/ /*********************************** Nz::IpAddress **********************************/
ipAddressClass.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);
int argIndex = 1; int argIndex = 2;
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;
} }
} }
@ -71,19 +71,19 @@ namespace Ndk
return false; return false;
}); });
ipAddressClass.BindMethod("GetPort", &Nz::IpAddress::GetPort); ipAddress.BindMethod("GetPort", &Nz::IpAddress::GetPort);
ipAddressClass.BindMethod("GetProtocol", &Nz::IpAddress::GetProtocol); ipAddress.BindMethod("GetProtocol", &Nz::IpAddress::GetProtocol);
ipAddressClass.BindMethod("IsLoopback", &Nz::IpAddress::IsLoopback); ipAddress.BindMethod("IsLoopback", &Nz::IpAddress::IsLoopback);
ipAddressClass.BindMethod("IsValid", &Nz::IpAddress::IsValid); ipAddress.BindMethod("IsValid", &Nz::IpAddress::IsValid);
ipAddressClass.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32); ipAddress.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32);
ipAddressClass.BindMethod("__tostring", &Nz::IpAddress::ToString); ipAddress.BindMethod("__tostring", &Nz::IpAddress::ToString);
ipAddressClass.BindStaticMethod("ResolveAddress", [] (Nz::LuaInstance& instance) -> int ipAddress.BindStaticMethod("ResolveAddress", [] (Nz::LuaInstance& instance) -> int
{ {
Nz::String service; Nz::String service;
Nz::ResolveError error = Nz::ResolveError_Unknown; Nz::ResolveError error = Nz::ResolveError_Unknown;
int argIndex = 1; int argIndex = 2;
Nz::String hostName = Nz::IpAddress::ResolveAddress(instance.Check<Nz::IpAddress>(&argIndex), &service, &error); Nz::String hostName = Nz::IpAddress::ResolveAddress(instance.Check<Nz::IpAddress>(&argIndex), &service, &error);
if (error == Nz::ResolveError_NoError) if (error == Nz::ResolveError_NoError)
@ -100,11 +100,11 @@ namespace Ndk
} }
}); });
ipAddressClass.BindStaticMethod("ResolveHostname", [] (Nz::LuaInstance& instance) -> int ipAddress.BindStaticMethod("ResolveHostname", [] (Nz::LuaInstance& instance) -> int
{ {
Nz::ResolveError error = Nz::ResolveError_Unknown; Nz::ResolveError error = Nz::ResolveError_Unknown;
int argIndex = 1; int argIndex = 2;
Nz::NetProtocol protocol = instance.Check<Nz::NetProtocol>(&argIndex); Nz::NetProtocol protocol = instance.Check<Nz::NetProtocol>(&argIndex);
Nz::String hostname = instance.Check<Nz::String>(&argIndex); Nz::String hostname = instance.Check<Nz::String>(&argIndex);
Nz::String service = instance.Check<Nz::String>(&argIndex, "http"); Nz::String service = instance.Check<Nz::String>(&argIndex, "http");
@ -145,8 +145,8 @@ namespace Ndk
void LuaBinding::RegisterNetwork(Nz::LuaInstance& instance) void LuaBinding::RegisterNetwork(Nz::LuaInstance& instance)
{ {
// Classes // Classes
abstractSocketClass.Register(instance); abstractSocket.Register(instance);
ipAddressClass.Register(instance); ipAddress.Register(instance);
// Enums // Enums

View File

@ -10,9 +10,58 @@ namespace Ndk
/*! /*!
* \brief Binds Renderer module to Lua * \brief Binds Renderer module to Lua
*/ */
void LuaBinding::BindRenderer() void LuaBinding::BindRenderer()
{ {
/*********************************** Nz::Texture ***********************************/
texture.Inherit<Nz::AbstractImageRef>(abstractImage, [] (Nz::TextureRef* textureRef) -> Nz::AbstractImageRef*
{
return reinterpret_cast<Nz::AbstractImageRef*>(textureRef); //TODO: Make a ObjectRefCast
});
texture.SetConstructor([] (Nz::LuaInstance& /*lua*/, Nz::TextureRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Texture::New());
return true;
});
texture.BindMethod("Create", &Nz::Texture::Create, static_cast<Nz::UInt8>(1), 1U);
texture.BindMethod("Destroy", &Nz::Texture::Destroy);
//texture.BindMethod("Download", &Nz::Texture::Download);
texture.BindMethod("EnableMipmapping", &Nz::Texture::EnableMipmapping);
texture.BindMethod("EnsureMipmapsUpdate", &Nz::Texture::EnsureMipmapsUpdate);
texture.BindMethod("HasMipmaps", &Nz::Texture::HasMipmaps);
texture.BindMethod("InvalidateMipmaps", &Nz::Texture::InvalidateMipmaps);
texture.BindMethod("IsValid", &Nz::Texture::IsValid);
texture.BindMethod("LoadFromFile", &Nz::Texture::LoadFromFile, true, Nz::ImageParams());
//bool LoadFromImage(const Image& image, bool generateMipmaps = true);
//bool LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
//bool LoadFromStream(Stream& stream, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
texture.BindMethod("LoadArrayFromFile", &Nz::Texture::LoadArrayFromFile, Nz::Vector2ui(2, 2), true, Nz::ImageParams());
//bool LoadArrayFromImage(const Image& image, bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//bool LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//bool LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//bool LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
//bool LoadCubemapFromImage(const Image& image, bool generateMipmaps = true, const CubemapParams& params = CubemapParams());
//bool LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
//bool LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
texture.BindMethod("LoadFaceFromFile", &Nz::Texture::LoadFaceFromFile, Nz::ImageParams());
//bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams());
//bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams());
texture.BindMethod("SaveToFile", &Nz::Texture::SaveToFile, Nz::ImageParams());
//bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams());
texture.BindMethod("SetMipmapRange", &Nz::Texture::SetMipmapRange);
texture.BindStaticMethod("IsFormatSupported", &Nz::Texture::IsFormatSupported);
texture.BindStaticMethod("IsMipmappingSupported", &Nz::Texture::IsMipmappingSupported);
texture.BindStaticMethod("IsTypeSupported", &Nz::Texture::IsTypeSupported);
} }
/*! /*!
@ -20,8 +69,8 @@ namespace Ndk
* *
* \param instance Lua instance that will interact with the Renderer classes * \param instance Lua instance that will interact with the Renderer classes
*/ */
void LuaBinding::RegisterRenderer(Nz::LuaInstance& instance) void LuaBinding::RegisterRenderer(Nz::LuaInstance& instance)
{ {
texture.Register(instance);
} }
} }

View File

@ -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) -> 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;
}); });
@ -36,58 +36,58 @@ namespace Ndk
/*********************************** Ndk::Console **********************************/ /*********************************** Ndk::Console **********************************/
#ifndef NDK_SERVER #ifndef NDK_SERVER
consoleClass.Inherit<Nz::Node>(nodeClass, [] (ConsoleHandle* handle) -> Nz::Node* console.Inherit<Nz::Node>(node, [] (ConsoleHandle* handle) -> Nz::Node*
{ {
return handle->GetObject(); return handle->GetObject();
}); });
consoleClass.BindMethod("AddLine", &Console::AddLine, Nz::Color::White); console.BindMethod("AddLine", &Console::AddLine, Nz::Color::White);
consoleClass.BindMethod("Clear", &Console::Clear); console.BindMethod("Clear", &Console::Clear);
consoleClass.BindMethod("GetCharacterSize", &Console::GetCharacterSize); console.BindMethod("GetCharacterSize", &Console::GetCharacterSize);
consoleClass.BindMethod("GetHistory", &Console::GetHistory); console.BindMethod("GetHistory", &Console::GetHistory);
consoleClass.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground); console.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground);
consoleClass.BindMethod("GetInput", &Console::GetInput); console.BindMethod("GetInput", &Console::GetInput);
consoleClass.BindMethod("GetInputBackground", &Console::GetInputBackground); console.BindMethod("GetInputBackground", &Console::GetInputBackground);
consoleClass.BindMethod("GetSize", &Console::GetSize); console.BindMethod("GetSize", &Console::GetSize);
consoleClass.BindMethod("GetTextFont", &Console::GetTextFont); console.BindMethod("GetTextFont", &Console::GetTextFont);
consoleClass.BindMethod("IsVisible", &Console::IsVisible); console.BindMethod("IsVisible", &Console::IsVisible);
consoleClass.BindMethod("SendCharacter", &Console::SendCharacter); console.BindMethod("SendCharacter", &Console::SendCharacter);
//consoleClass.SetMethod("SendEvent", &Console::SendEvent); //consoleClass.SetMethod("SendEvent", &Console::SendEvent);
consoleClass.BindMethod("SetCharacterSize", &Console::SetCharacterSize); console.BindMethod("SetCharacterSize", &Console::SetCharacterSize);
consoleClass.BindMethod("SetSize", &Console::SetSize); console.BindMethod("SetSize", &Console::SetSize);
consoleClass.BindMethod("SetTextFont", &Console::SetTextFont); console.BindMethod("SetTextFont", &Console::SetTextFont);
consoleClass.BindMethod("Show", &Console::Show, true); console.BindMethod("Show", &Console::Show, true);
#endif #endif
/*********************************** Ndk::Entity **********************************/ /*********************************** Ndk::Entity **********************************/
entityClass.BindMethod("Enable", &Entity::Enable, true); entity.BindMethod("Enable", &Entity::Enable, true);
entityClass.BindMethod("GetId", &Entity::GetId); entity.BindMethod("GetId", &Entity::GetId);
entityClass.BindMethod("GetWorld", &Entity::GetWorld); entity.BindMethod("GetWorld", &Entity::GetWorld);
entityClass.BindMethod("Kill", &Entity::Kill); entity.BindMethod("Kill", &Entity::Kill);
entityClass.BindMethod("IsEnabled", &Entity::IsEnabled); entity.BindMethod("IsEnabled", &Entity::IsEnabled);
entityClass.BindMethod("IsValid", &Entity::IsValid); entity.BindMethod("IsValid", &Entity::IsValid);
entityClass.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents);
entityClass.BindMethod("__tostring", &EntityHandle::ToString); entity.BindMethod("__tostring", &EntityHandle::ToString);
entityClass.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int entity.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{ {
ComponentBinding* binding = QueryComponentIndex(instance); ComponentBinding* binding = QueryComponentIndex(instance);
return binding->adder(instance, handle); return binding->adder(instance, handle);
}); });
entityClass.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int entity.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{ {
ComponentBinding* binding = QueryComponentIndex(instance); ComponentBinding* binding = QueryComponentIndex(instance);
return binding->getter(instance, handle->GetComponent(binding->index)); return binding->getter(instance, handle->GetComponent(binding->index));
}); });
entityClass.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int entity.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{ {
ComponentBinding* binding = QueryComponentIndex(instance); ComponentBinding* binding = QueryComponentIndex(instance);
@ -96,7 +96,7 @@ namespace Ndk
}); });
/*********************************** Ndk::NodeComponent **********************************/ /*********************************** Ndk::NodeComponent **********************************/
nodeComponent.Inherit<Nz::Node>(nodeClass, [] (NodeComponentHandle* handle) -> Nz::Node* nodeComponent.Inherit<Nz::Node>(node, [] (NodeComponentHandle* handle) -> Nz::Node*
{ {
return handle->GetObject(); return handle->GetObject();
}); });
@ -105,7 +105,7 @@ namespace Ndk
velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)
{ {
std::size_t length; std::size_t length;
const char* member = lua.CheckString(1, &length); const char* member = lua.CheckString(2, &length);
if (std::strcmp(member, "Linear") == 0) if (std::strcmp(member, "Linear") == 0)
{ {
@ -119,9 +119,9 @@ namespace Ndk
velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)
{ {
std::size_t length; std::size_t length;
const char* member = lua.CheckString(1, &length); const char* member = lua.CheckString(2, &length);
int argIndex = 2; int argIndex = 3;
if (std::strcmp(member, "Linear") == 0) if (std::strcmp(member, "Linear") == 0)
{ {
instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex); instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex);
@ -132,14 +132,69 @@ namespace Ndk
}); });
/*********************************** Ndk::World **********************************/ /*********************************** Ndk::World **********************************/
worldClass.BindMethod("CreateEntity", &World::CreateEntity); world.BindMethod("CreateEntity", &World::CreateEntity);
worldClass.BindMethod("CreateEntities", &World::CreateEntities); world.BindMethod("CreateEntities", &World::CreateEntities);
worldClass.BindMethod("Clear", &World::Clear); world.BindMethod("Clear", &World::Clear);
#ifndef NDK_SERVER #ifndef NDK_SERVER
/*********************************** Ndk::GraphicsComponent **********************************/ /*********************************** Ndk::GraphicsComponent **********************************/
graphicsComponent.BindMethod("Attach", (void(Ndk::GraphicsComponent::*)(Nz::InstancedRenderableRef, int)) &GraphicsComponent::Attach, 0); graphicsComponent.BindMethod("Attach", [] (Nz::LuaInstance& lua, Ndk::GraphicsComponent* instance, std::size_t argumentCount) -> int
{
/*
void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0);
void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0);
*/
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 1:
{
int argIndex = 2;
instance->Attach(lua.Check<Nz::InstancedRenderableRef>(&argIndex));
return 0;
}
case 2:
{
int argIndex = 2;
Nz::InstancedRenderableRef renderable = lua.Check<Nz::InstancedRenderableRef>(&argIndex);
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
int renderOrder = lua.Check<int>(&argIndex);
instance->Attach(renderable, renderOrder);
}
else if (lua.IsOfType(argIndex, "Matrix4"))
{
Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex);
instance->Attach(renderable, localMatrix);
}
else
break;
return 0;
}
case 3:
{
int argIndex = 2;
Nz::InstancedRenderableRef renderable = lua.Check<Nz::InstancedRenderableRef>(&argIndex);
Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex);
int renderOrder = lua.Check<int>(&argIndex);
instance->Attach(renderable, localMatrix, renderOrder);
return 0;
}
}
lua.Error("No matching overload for method GetMemoryUsage");
return 0;
});
#endif #endif
@ -164,13 +219,13 @@ namespace Ndk
{ {
// Classes // Classes
application.Register(instance); application.Register(instance);
entityClass.Register(instance); entity.Register(instance);
nodeComponent.Register(instance); nodeComponent.Register(instance);
velocityComponent.Register(instance); velocityComponent.Register(instance);
worldClass.Register(instance); world.Register(instance);
#ifndef NDK_SERVER #ifndef NDK_SERVER
consoleClass.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) -> int abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int
{ {
unsigned int argCount = std::min(lua.GetStackTop(), 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 index = 1; int argIndex = 2;
Nz::UInt8 level(lua.Check<Nz::UInt8>(&index)); Nz::UInt8 level(lua.Check<Nz::UInt8>(&argIndex));
return lua.Push(abstractImage->GetMemoryUsage(level)); return lua.Push(instance->GetMemoryUsage(level));
} }
} }
@ -46,10 +46,10 @@ namespace Ndk
return 0; return 0;
}); });
abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* abstractImage) -> int abstractImage.BindMethod("Update", [] (Nz::LuaInstance& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int
{ {
unsigned int argCount = std::min(lua.GetStackTop(), 6U); std::size_t argCount = std::min<std::size_t>(argumentCount, 6U);
int argIndex = 1; int argIndex = 2;
std::size_t bufferSize = 0; std::size_t bufferSize = 0;
const Nz::UInt8* pixels = reinterpret_cast<const Nz::UInt8*>(lua.CheckString(argIndex++, &bufferSize)); const Nz::UInt8* pixels = reinterpret_cast<const Nz::UInt8*>(lua.CheckString(argIndex++, &bufferSize));
@ -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,23 +93,23 @@ namespace Ndk
}); });
/*********************************** Nz::Font **********************************/ /*********************************** Nz::Font **********************************/
fontClass.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;
}); });
fontClass.BindMethod("ClearGlyphCache", &Nz::Font::ClearGlyphCache); font.BindMethod("ClearGlyphCache", &Nz::Font::ClearGlyphCache);
fontClass.BindMethod("ClearKerningCache", &Nz::Font::ClearKerningCache); font.BindMethod("ClearKerningCache", &Nz::Font::ClearKerningCache);
fontClass.BindMethod("ClearSizeInfoCache", &Nz::Font::ClearSizeInfoCache); font.BindMethod("ClearSizeInfoCache", &Nz::Font::ClearSizeInfoCache);
fontClass.BindMethod("Destroy", &Nz::Font::Destroy); font.BindMethod("Destroy", &Nz::Font::Destroy);
fontClass.BindMethod("GetCachedGlyphCount", [] (Nz::LuaInstance& lua, Nz::FontRef& instance) -> int font.BindMethod("GetCachedGlyphCount", [] (Nz::LuaInstance& lua, Nz::FontRef& instance, std::size_t argumentCount) -> int
{ {
unsigned int argCount = std::min(lua.GetStackTop(), 2U); std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 1; int argIndex = 2;
switch (argCount) switch (argCount)
{ {
case 0: case 0:
@ -130,116 +130,116 @@ namespace Ndk
return 0; return 0;
}); });
fontClass.BindMethod("GetFamilyName", &Nz::Font::GetFamilyName); font.BindMethod("GetFamilyName", &Nz::Font::GetFamilyName);
fontClass.BindMethod("GetKerning", &Nz::Font::GetKerning); font.BindMethod("GetKerning", &Nz::Font::GetKerning);
fontClass.BindMethod("GetGlyphBorder", &Nz::Font::GetGlyphBorder); font.BindMethod("GetGlyphBorder", &Nz::Font::GetGlyphBorder);
fontClass.BindMethod("GetMinimumStepSize", &Nz::Font::GetMinimumStepSize); font.BindMethod("GetMinimumStepSize", &Nz::Font::GetMinimumStepSize);
fontClass.BindMethod("GetSizeInfo", &Nz::Font::GetSizeInfo); font.BindMethod("GetSizeInfo", &Nz::Font::GetSizeInfo);
fontClass.BindMethod("GetStyleName", &Nz::Font::GetStyleName); font.BindMethod("GetStyleName", &Nz::Font::GetStyleName);
fontClass.BindMethod("IsValid", &Nz::Font::IsValid); font.BindMethod("IsValid", &Nz::Font::IsValid);
fontClass.BindMethod("Precache", (bool(Nz::Font::*)(unsigned int, Nz::UInt32, const Nz::String&) const) &Nz::Font::Precache); font.BindMethod("Precache", (bool(Nz::Font::*)(unsigned int, Nz::UInt32, const Nz::String&) const) &Nz::Font::Precache);
fontClass.BindMethod("OpenFromFile", &Nz::Font::OpenFromFile, Nz::FontParams()); font.BindMethod("OpenFromFile", &Nz::Font::OpenFromFile, Nz::FontParams());
fontClass.BindMethod("SetGlyphBorder", &Nz::Font::SetGlyphBorder); font.BindMethod("SetGlyphBorder", &Nz::Font::SetGlyphBorder);
fontClass.BindMethod("SetMinimumStepSize", &Nz::Font::SetMinimumStepSize); font.BindMethod("SetMinimumStepSize", &Nz::Font::SetMinimumStepSize);
fontClass.BindStaticMethod("GetDefault", &Nz::Font::GetDefault); font.BindStaticMethod("GetDefault", &Nz::Font::GetDefault);
fontClass.BindStaticMethod("GetDefaultGlyphBorder", &Nz::Font::GetDefaultGlyphBorder); font.BindStaticMethod("GetDefaultGlyphBorder", &Nz::Font::GetDefaultGlyphBorder);
fontClass.BindStaticMethod("GetDefaultMinimumStepSize", &Nz::Font::GetDefaultMinimumStepSize); font.BindStaticMethod("GetDefaultMinimumStepSize", &Nz::Font::GetDefaultMinimumStepSize);
fontClass.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder); font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder);
fontClass.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize); font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize);
/*********************************** Nz::Node **********************************/ /*********************************** Nz::Node **********************************/
nodeClass.BindMethod("GetBackward", &Nz::Node::GetBackward); node.BindMethod("GetBackward", &Nz::Node::GetBackward);
//nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds); //nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds);
nodeClass.BindMethod("GetDown", &Nz::Node::GetDown); node.BindMethod("GetDown", &Nz::Node::GetDown);
nodeClass.BindMethod("GetForward", &Nz::Node::GetForward); node.BindMethod("GetForward", &Nz::Node::GetForward);
nodeClass.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition);
nodeClass.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation);
nodeClass.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale);
nodeClass.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition);
//nodeClass.SetMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); //nodeClass.SetMethod("GetInitialRotation", &Nz::Node::GetInitialRotation);
nodeClass.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale);
nodeClass.BindMethod("GetLeft", &Nz::Node::GetLeft); node.BindMethod("GetLeft", &Nz::Node::GetLeft);
nodeClass.BindMethod("GetNodeType", &Nz::Node::GetNodeType); node.BindMethod("GetNodeType", &Nz::Node::GetNodeType);
//nodeClass.SetMethod("GetParent", &Nz::Node::GetParent); //nodeClass.SetMethod("GetParent", &Nz::Node::GetParent);
nodeClass.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global);
nodeClass.BindMethod("GetRight", &Nz::Node::GetRight); node.BindMethod("GetRight", &Nz::Node::GetRight);
//nodeClass.SetMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); //nodeClass.SetMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global);
nodeClass.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global);
//nodeClass.SetMethod("GetTransformMatrix", &Nz::Node::GetTransformMatrix); //nodeClass.SetMethod("GetTransformMatrix", &Nz::Node::GetTransformMatrix);
nodeClass.BindMethod("GetUp", &Nz::Node::GetUp); node.BindMethod("GetUp", &Nz::Node::GetUp);
nodeClass.BindMethod("HasChilds", &Nz::Node::HasChilds); node.BindMethod("HasChilds", &Nz::Node::HasChilds);
nodeClass.BindMethod("GetBackward", &Nz::Node::GetBackward); node.BindMethod("GetBackward", &Nz::Node::GetBackward);
nodeClass.BindMethod("GetDown", &Nz::Node::GetDown); node.BindMethod("GetDown", &Nz::Node::GetDown);
nodeClass.BindMethod("GetForward", &Nz::Node::GetForward); node.BindMethod("GetForward", &Nz::Node::GetForward);
nodeClass.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition);
nodeClass.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation);
nodeClass.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale);
nodeClass.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition);
nodeClass.BindMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); node.BindMethod("GetInitialRotation", &Nz::Node::GetInitialRotation);
nodeClass.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale);
nodeClass.BindMethod("GetLeft", &Nz::Node::GetLeft); node.BindMethod("GetLeft", &Nz::Node::GetLeft);
nodeClass.BindMethod("GetNodeType", &Nz::Node::GetNodeType); node.BindMethod("GetNodeType", &Nz::Node::GetNodeType);
nodeClass.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global);
nodeClass.BindMethod("GetRight", &Nz::Node::GetRight); node.BindMethod("GetRight", &Nz::Node::GetRight);
nodeClass.BindMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); node.BindMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global);
nodeClass.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global);
nodeClass.BindMethod("GetUp", &Nz::Node::GetUp); node.BindMethod("GetUp", &Nz::Node::GetUp);
nodeClass.BindMethod("SetInitialPosition", (void(Nz::Node::*)(const Nz::Vector3f&)) &Nz::Node::SetInitialPosition); node.BindMethod("SetInitialPosition", (void(Nz::Node::*)(const Nz::Vector3f&)) &Nz::Node::SetInitialPosition);
nodeClass.BindMethod("SetInitialRotation", (void(Nz::Node::*)(const Nz::Quaternionf&)) &Nz::Node::SetInitialRotation); node.BindMethod("SetInitialRotation", (void(Nz::Node::*)(const Nz::Quaternionf&)) &Nz::Node::SetInitialRotation);
nodeClass.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);
nodeClass.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);
nodeClass.BindMethod("Move", [] (Nz::LuaInstance& lua, Nz::Node& node) -> int node.BindMethod("Move", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 1; 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;
}); });
nodeClass.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& node) -> int node.BindMethod("Rotate", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int
{ {
int argIndex = 1; 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;
}); });
nodeClass.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& node) -> int node.BindMethod("Scale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{ {
unsigned int argCount = std::min(lua.GetStackTop(), 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 1; int argIndex = 2;
switch (argCount) switch (argCount)
{ {
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,11 +247,11 @@ namespace Ndk
return 0; return 0;
}); });
nodeClass.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& node) -> int node.BindMethod("SetScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{ {
unsigned int argCount = std::min(lua.GetStackTop(), 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 1; int argIndex = 2;
switch (argCount) switch (argCount)
{ {
case 1: case 1:
@ -261,10 +261,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 +275,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,26 +284,26 @@ namespace Ndk
return 0; return 0;
}); });
nodeClass.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& node) -> int node.BindMethod("SetInitialScale", [] (Nz::LuaInstance& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{ {
unsigned int argCount = std::min(lua.GetStackTop(), 4U); std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 1; int argIndex = 2;
switch (argCount) switch (argCount)
{ {
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;
} }
@ -321,7 +321,7 @@ namespace Ndk
void LuaBinding::RegisterUtility(Nz::LuaInstance& instance) void LuaBinding::RegisterUtility(Nz::LuaInstance& instance)
{ {
abstractImage.Register(instance); abstractImage.Register(instance);
fontClass.Register(instance); font.Register(instance);
nodeClass.Register(instance); node.Register(instance);
} }
} }

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

@ -67,7 +67,7 @@ ACTION.Function = function ()
error("Failed to create header file (" .. v.Target .. "): " .. err) error("Failed to create header file (" .. v.Target .. "): " .. err)
end end
header:write("// This file was automatically generated on " .. os.date("%d %b %Y at %X") .. "\n\n") header:write("// This file was automatically generated\n\n")
if (v.Header) then if (v.Header) then
header:write(v.Header) header:write(v.Header)
end 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,123 @@ function NazaraBuild:Process(infoTable)
return true return true
end end
function NazaraBuild:PrepareGeneric()
flags({
"C++14",
"MultiProcessorCompile",
"NoMinimalRebuild"
})
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")
rtti("Off")
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,4 +1,4 @@
// This file was automatically generated on 24 Jun 2015 at 13:55:50 // This file was automatically generated
/* /*
Nazara Engine - Audio module Nazara Engine - Audio module

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 09 May 2016 at 17:07:09 // This file was automatically generated
/* /*
Nazara Engine - Core module Nazara Engine - Core module

View File

@ -20,8 +20,8 @@ namespace Nz
class AbstractHash; class AbstractHash;
class ByteArray; class ByteArray;
template<typename F, typename Tuple> 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> 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> 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

@ -19,13 +19,13 @@ namespace Nz
{ {
// http://www.cppsamples.com/common-tasks/apply-tuple-to-function.html // http://www.cppsamples.com/common-tasks/apply-tuple-to-function.html
template<typename F, typename Tuple, size_t... S> template<typename F, typename Tuple, size_t... S>
auto ApplyImplFunc(F&& fn, Tuple&& t, std::index_sequence<S...>) decltype(auto) ApplyImplFunc(F&& fn, Tuple&& t, std::index_sequence<S...>)
{ {
return std::forward<F>(fn)(std::get<S>(std::forward<Tuple>(t))...); return std::forward<F>(fn)(std::get<S>(std::forward<Tuple>(t))...);
} }
template<typename O, typename F, typename Tuple, size_t... S> template<typename O, typename F, typename Tuple, size_t... S>
auto ApplyImplMethod(O& object, F&& fn, Tuple&& t, std::index_sequence<S...>) decltype(auto) ApplyImplMethod(O& object, F&& fn, Tuple&& t, std::index_sequence<S...>)
{ {
return (object .* std::forward<F>(fn))(std::get<S>(std::forward<Tuple>(t))...); return (object .* std::forward<F>(fn))(std::get<S>(std::forward<Tuple>(t))...);
} }
@ -44,7 +44,7 @@ namespace Nz
* \see Apply * \see Apply
*/ */
template<typename F, typename Tuple> template<typename F, typename Tuple>
auto Apply(F&& fn, Tuple&& t) decltype(auto) Apply(F&& fn, Tuple&& t)
{ {
constexpr std::size_t tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value; constexpr std::size_t tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value;
@ -63,7 +63,7 @@ namespace Nz
* \see Apply * \see Apply
*/ */
template<typename O, typename F, typename Tuple> template<typename O, typename F, typename Tuple>
auto Apply(O& object, F&& fn, Tuple&& t) decltype(auto) Apply(O& object, F&& fn, Tuple&& t)
{ {
constexpr std::size_t tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value; constexpr std::size_t tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value;

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

@ -56,7 +56,7 @@ namespace Nz
template<typename T> bool operator<(const T& lhs, const ObjectRef<T>& rhs); template<typename T> bool operator<(const T& lhs, const ObjectRef<T>& rhs);
template<typename T> bool operator<(const ObjectRef<T>& lhs, const T& rhs); template<typename T> bool operator<(const ObjectRef<T>& lhs, const T& rhs);
template<typename T> bool operator<=(const ObjectRef<T>, const ObjectRef<T>& rhs); template<typename T> bool operator<=(const ObjectRef<T>& lhs, const ObjectRef<T>& rhs);
template<typename T> bool operator<=(const T& lhs, const ObjectRef<T>& rhs); template<typename T> bool operator<=(const T& lhs, const ObjectRef<T>& rhs);
template<typename T> bool operator<=(const ObjectRef<T>& lhs, const T& rhs); template<typename T> bool operator<=(const ObjectRef<T>& lhs, const T& rhs);

View File

@ -78,7 +78,7 @@ namespace Nz
while (it != Type::s_managerMap.end()) while (it != Type::s_managerMap.end())
{ {
const ObjectRef<Type>& ref = it->second; const ObjectRef<Type>& ref = it->second;
if (ref.GetReferenceCount() == 1) // Are we the only ones to own the resource ? if (ref->GetReferenceCount() == 1) // Are we the only ones to own the resource ?
{ {
NazaraDebug("Purging resource from file " + ref->GetFilePath()); NazaraDebug("Purging resource from file " + ref->GetFilePath());
Type::s_managerMap.erase(it++); // Then we erase it Type::s_managerMap.erase(it++); // Then we erase it

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 15 Sep 2016 at 00:43:26 // This file was automatically generated
/* /*
Nazara Engine - Graphics module Nazara Engine - Graphics module

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

@ -1,4 +1,4 @@
// This file was automatically generated on 24 Jun 2015 at 13:55:50 // This file was automatically generated
/* /*
Nazara Engine - Lua scripting module Nazara Engine - Lua scripting module

View File

@ -26,7 +26,7 @@ namespace Nz
friend class LuaClass; friend class LuaClass;
public: public:
using ClassFunc = std::function<int(LuaInstance& lua, T& instance)>; using ClassFunc = std::function<int(LuaInstance& lua, T& instance, std::size_t argumentCount)>;
using ClassIndexFunc = std::function<bool(LuaInstance& lua, T& instance)>; using ClassIndexFunc = std::function<bool(LuaInstance& lua, T& instance)>;
using ConstructorFunc = std::function<bool(LuaInstance& lua, T* instance, std::size_t argumentCount)>; using ConstructorFunc = std::function<bool(LuaInstance& lua, T* instance, std::size_t argumentCount)>;
template<typename P> using ConvertToParent = std::function<P*(T*)>; template<typename P> using ConvertToParent = std::function<P*(T*)>;
@ -34,6 +34,7 @@ namespace Nz
using StaticIndexFunc = std::function<bool(LuaInstance& lua)>; using StaticIndexFunc = std::function<bool(LuaInstance& lua)>;
using StaticFunc = std::function<int(LuaInstance& lua)>; using StaticFunc = std::function<int(LuaInstance& lua)>;
LuaClass() = default;
LuaClass(const String& name); LuaClass(const String& name);
void BindDefaultConstructor(); void BindDefaultConstructor();
@ -50,6 +51,9 @@ namespace Nz
template<class P> void Inherit(LuaClass<P>& parent); template<class P> void Inherit(LuaClass<P>& parent);
template<class P> void Inherit(LuaClass<P>& parent, ConvertToParent<P> convertFunc); template<class P> void Inherit(LuaClass<P>& parent, ConvertToParent<P> convertFunc);
void Reset();
void Reset(const String& name);
void Register(LuaInstance& lua); void Register(LuaInstance& lua);
void PushGlobalTable(LuaInstance& lua); void PushGlobalTable(LuaInstance& lua);
@ -62,6 +66,19 @@ namespace Nz
void SetStaticSetter(StaticIndexFunc getter); void SetStaticSetter(StaticIndexFunc getter);
private: private:
template<typename U, bool HasDestructor>
friend struct LuaClassImplFinalizerSetupProxy;
void PushClassInfo(LuaInstance& lua);
void SetupConstructor(LuaInstance& lua);
void SetupDefaultToString(LuaInstance& lua);
void SetupFinalizer(LuaInstance& lua);
void SetupGetter(LuaInstance& lua, LuaCFunction proxy);
void SetupGlobalTable(LuaInstance& lua);
void SetupMetatable(LuaInstance& lua);
void SetupMethod(LuaInstance& lua, LuaCFunction proxy, const String& name, std::size_t methodIndex);
void SetupSetter(LuaInstance& lua, LuaCFunction proxy);
using ParentFunc = std::function<void(LuaInstance& lua, T* instance)>; using ParentFunc = std::function<void(LuaInstance& lua, T* instance)>;
using InstanceGetter = std::function<T*(LuaInstance& lua)>; using InstanceGetter = std::function<T*(LuaInstance& lua)>;

View File

@ -2,6 +2,7 @@
// This file is part of the "Nazara Engine - Lua scripting module" // This file is part of the "Nazara Engine - Lua scripting 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/Lua/LuaClass.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/MemoryHelper.hpp> #include <Nazara/Core/MemoryHelper.hpp>
#include <type_traits> #include <type_traits>
@ -10,10 +11,9 @@
namespace Nz namespace Nz
{ {
template<class T> template<class T>
LuaClass<T>::LuaClass(const String& name) : LuaClass<T>::LuaClass(const String& name)
m_info(new ClassInfo)
{ {
m_info->name = name; Reset(name);
} }
template<class T> template<class T>
@ -58,147 +58,37 @@ namespace Nz
}); });
} }
template<class T>
void LuaClass<T>::Reset()
{
m_info.reset();
}
template<class T>
void LuaClass<T>::Reset(const String& name)
{
m_info = std::make_shared<ClassInfo>();
m_info->name = name;
m_info->instanceGetters[m_info->name] = [info = m_info] (LuaInstance& instance)
{
return static_cast<T*>(instance.CheckUserdata(1, info->name));
};
}
template<class T> template<class T>
void LuaClass<T>::Register(LuaInstance& lua) void LuaClass<T>::Register(LuaInstance& lua)
{ {
// Le ClassInfo doit rester en vie jusqu'à la fin du script PushClassInfo(lua);
// Obliger l'instance de LuaClass à rester en vie dans cette fin serait contraignant pour l'utilisateur
// J'utilise donc une astuce, la stocker dans une UserData associée avec chaque fonction de la metatable du type,
// cette UserData disposera d'un finalizer qui libérera le ClassInfo
// Ainsi c'est Lua qui va s'occuper de la destruction pour nous :-)
// De même, l'utilisation d'un shared_ptr permet de garder la structure en vie même si l'instance est libérée avant le LuaClass
std::shared_ptr<ClassInfo>* info = static_cast<std::shared_ptr<ClassInfo>*>(lua.PushUserdata(sizeof(std::shared_ptr<ClassInfo>)));
PlacementNew(info, m_info);
// On créé la table qui contiendra une méthode (Le finalizer) pour libérer le ClassInfo // Let's create the metatable which will be associated with every instance.
lua.PushTable(0, 1); SetupMetatable(lua);
lua.PushLightUserdata(info);
lua.PushCFunction(InfoDestructor, 1);
lua.SetField("__gc");
lua.SetMetatable(-2); // La table devient la metatable de l'UserData
// Maintenant, nous allons associer l'UserData avec chaque fonction, de sorte qu'il reste en vie if (m_info->constructor || m_info->staticGetter || m_info->staticSetter || !m_staticMethods.empty())
// aussi longtemps que nécessaire, et que le pointeur soit transmis à chaque méthode SetupGlobalTable(lua);
if (!lua.NewMetatable(m_info->name)) lua.Pop(); // Pop our ClassInfo, which is now referenced by all our functions
NazaraWarning("Class \"" + m_info->name + "\" already registred in this instance");
{
// Set the type in a __type field
lua.PushString(m_info->name);
lua.SetField("__type");
// In case a __tostring method is missing, add a default implementation returning the type
if (m_methods.find("__tostring") == m_methods.end())
{
// Define the Finalizer
lua.PushValue(1); // shared_ptr on UserData
lua.PushCFunction(ToStringProxy, 1);
lua.SetField("__tostring");
}
// Define the Finalizer
lua.PushValue(1);
lua.PushCFunction(FinalizerProxy, 1);
lua.SetField("__gc");
if (m_info->getter || !m_info->parentGetters.empty())
{
lua.PushValue(1); // shared_ptr on UserData
lua.PushValue(-2); // Metatable
lua.PushCFunction(GetterProxy, 2);
}
else
// Optimisation, plutôt que de rediriger vers une fonction C qui ne fera rien d'autre que rechercher
// dans la table, nous envoyons directement la table, de sorte que Lua fasse directement la recherche
// Ceci n'est possible que si nous n'avons ni getter, ni parent
lua.PushValue(-1); // Metatable
lua.SetField("__index"); // Getter
if (m_info->setter)
{
lua.PushValue(1); // shared_ptr on UserData
lua.PushCFunction(SetterProxy, 1);
lua.SetField("__newindex"); // Setter
}
m_info->methods.reserve(m_methods.size());
for (auto& pair : m_methods)
{
std::size_t methodIndex = m_info->methods.size();
m_info->methods.push_back(pair.second);
lua.PushValue(1); // shared_ptr on UserData
lua.PushInteger(methodIndex);
lua.PushCFunction(MethodProxy, 2);
lua.SetField(pair.first); // Method name
}
m_info->instanceGetters[m_info->name] = [info = m_info] (LuaInstance& instance)
{
return static_cast<T*>(instance.CheckUserdata(1, info->name));
};
}
lua.Pop(); // On pop la metatable
if (m_info->constructor || m_info->staticGetter || m_info->staticSetter || !m_info->staticMethods.empty())
{
// Création de l'instance globale
lua.PushTable(); // Class = {}
// Création de la metatable associée à la table globale
lua.PushTable(); // ClassMeta = {}
if (m_info->constructor)
{
lua.PushValue(1); // ClassInfo
lua.PushCFunction(ConstructorProxy, 1);
lua.SetField("__call"); // ClassMeta.__call = ConstructorProxy
}
if (m_info->staticGetter)
{
lua.PushValue(1); // shared_ptr on UserData
lua.PushValue(-2); // ClassMeta
lua.PushCFunction(StaticGetterProxy, 2);
}
else
// Optimisation, plutôt que de rediriger vers une fonction C qui ne fera rien d'autre que rechercher
// dans la table, nous envoyons directement la table, de sorte que Lua fasse directement la recherche
// Ceci n'est possible que si nous n'avons ni getter, ni parent
lua.PushValue(-1); // ClassMeta
lua.SetField("__index"); // ClassMeta.__index = StaticGetterProxy/ClassMeta
if (m_info->staticSetter)
{
lua.PushValue(1); // shared_ptr on UserData
lua.PushCFunction(StaticSetterProxy, 1);
lua.SetField("__newindex"); // ClassMeta.__newindex = StaticSetterProxy
}
m_info->staticMethods.reserve(m_staticMethods.size());
for (auto& pair : m_staticMethods)
{
std::size_t methodIndex = m_info->staticMethods.size();
m_info->staticMethods.push_back(pair.second);
lua.PushValue(1); // shared_ptr on UserData
lua.PushInteger(methodIndex);
lua.PushCFunction(StaticMethodProxy, 2);
lua.SetField(pair.first); // ClassMeta.method = StaticMethodProxy
}
lua.SetMetatable(-2); // setmetatable(Class, ClassMeta)
lua.PushValue(-1); // Copie
lua.SetGlobal(m_info->name); // Class
m_info->globalTableRef = lua.CreateReference();
}
lua.Pop(); // On pop l'Userdata (contenant nos informations)
} }
template<class T> template<class T>
@ -237,9 +127,9 @@ namespace Nz
{ {
typename LuaImplMethodProxy<Args...>::template Impl<DefArgs...> handler(std::forward<DefArgs>(defArgs)...); typename LuaImplMethodProxy<Args...>::template Impl<DefArgs...> handler(std::forward<DefArgs>(defArgs)...);
BindMethod(name, [func, handler] (LuaInstance& lua, T& object) -> 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);
}); });
@ -251,9 +141,9 @@ namespace Nz
{ {
typename LuaImplMethodProxy<Args...>::template Impl<DefArgs...> handler(std::forward<DefArgs>(defArgs)...); typename LuaImplMethodProxy<Args...>::template Impl<DefArgs...> handler(std::forward<DefArgs>(defArgs)...);
BindMethod(name, [func, handler] (LuaInstance& lua, T& object) -> 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);
}); });
@ -265,9 +155,9 @@ namespace Nz
{ {
typename LuaImplMethodProxy<Args...>::template Impl<DefArgs...> handler(std::forward<DefArgs>(defArgs)...); typename LuaImplMethodProxy<Args...>::template Impl<DefArgs...> handler(std::forward<DefArgs>(defArgs)...);
BindMethod(name, [func, handler] (LuaInstance& lua, T& object) -> 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);
}); });
@ -279,9 +169,9 @@ namespace Nz
{ {
typename LuaImplMethodProxy<Args...>::template Impl<DefArgs...> handler(std::forward<DefArgs>(defArgs)...); typename LuaImplMethodProxy<Args...>::template Impl<DefArgs...> handler(std::forward<DefArgs>(defArgs)...);
BindMethod(name, [func, handler] (LuaInstance& lua, T& object) -> 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);
}); });
@ -313,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);
}); });
@ -325,6 +215,176 @@ namespace Nz
m_info->staticSetter = setter; m_info->staticSetter = setter;
} }
template<class T>
void LuaClass<T>::PushClassInfo(LuaInstance& lua)
{
// Our ClassInfo has to outlive the LuaClass, because we don't want to force the user to keep the LuaClass alive
// To do that, each Registration creates a tiny shared_ptr wrapper whose life is directly managed by Lua.
// This shared_ptr object gets pushed as a up-value for every proxy function set in the metatable.
// This way, there is no way our ClassInfo gets freed before any instance and the global class gets destroyed.
std::shared_ptr<ClassInfo>* info = static_cast<std::shared_ptr<ClassInfo>*>(lua.PushUserdata(sizeof(std::shared_ptr<ClassInfo>)));
PlacementNew(info, m_info);
// Setup a tiny metatable to let Lua know how to destroy our ClassInfo
lua.PushTable(0, 1);
lua.PushLightUserdata(info);
lua.PushCFunction(InfoDestructor, 1);
lua.SetField("__gc");
lua.SetMetatable(-2);
}
template<class T>
void LuaClass<T>::SetupConstructor(LuaInstance& lua)
{
lua.PushValue(1); // ClassInfo
lua.PushCFunction(ConstructorProxy, 1);
lua.SetField("__call"); // ClassMeta.__call = ConstructorProxy
}
template<class T>
void LuaClass<T>::SetupDefaultToString(LuaInstance& lua)
{
lua.PushValue(1); // shared_ptr on UserData
lua.PushCFunction(ToStringProxy, 1);
lua.SetField("__tostring");
}
template<typename T, bool HasDestructor>
struct LuaClassImplFinalizerSetupProxy;
template<typename T>
struct LuaClassImplFinalizerSetupProxy<T, true>
{
static void Setup(LuaInstance& lua)
{
lua.PushValue(1); // ClassInfo
lua.PushCFunction(LuaClass<T>::FinalizerProxy, 1);
lua.SetField("__gc");
}
};
template<typename T>
struct LuaClassImplFinalizerSetupProxy<T, false>
{
static void Setup(LuaInstance&)
{
}
};
template<class T>
void LuaClass<T>::SetupFinalizer(LuaInstance& lua)
{
LuaClassImplFinalizerSetupProxy<T, std::is_destructible<T>::value>::Setup(lua);
}
template<class T>
void LuaClass<T>::SetupGetter(LuaInstance& lua, LuaCFunction proxy)
{
lua.PushValue(1); // ClassInfo
lua.PushValue(-2); // Metatable
lua.PushCFunction(proxy, 2);
lua.SetField("__index"); // Getter
}
template<class T>
void LuaClass<T>::SetupGlobalTable(LuaInstance& lua)
{
// Create the global table
lua.PushTable(); // Class = {}
// Create a metatable which will be used for our global table
lua.PushTable(); // ClassMeta = {}
if (m_info->constructor)
SetupConstructor(lua);
if (m_info->staticGetter)
SetupGetter(lua, StaticGetterProxy);
else
{
// Optimize by assigning the metatable instead of a search function
lua.PushValue(-1); // Metatable
lua.SetField("__index");
}
if (m_info->staticSetter)
SetupSetter(lua, StaticSetterProxy);
m_info->staticMethods.reserve(m_staticMethods.size());
for (auto& pair : m_staticMethods)
{
std::size_t methodIndex = m_info->staticMethods.size();
m_info->staticMethods.push_back(pair.second);
SetupMethod(lua, StaticMethodProxy, pair.first, methodIndex);
}
lua.SetMetatable(-2); // setmetatable(Class, ClassMeta), pops ClassMeta
lua.PushValue(-1); // As CreateReference() pops the table, push a copy
m_info->globalTableRef = lua.CreateReference();
lua.SetGlobal(m_info->name); // _G["Class"] = Class
}
template<class T>
void LuaClass<T>::SetupMetatable(LuaInstance& lua)
{
if (!lua.NewMetatable(m_info->name))
NazaraWarning("Class \"" + m_info->name + "\" already registred in this instance");
{
SetupFinalizer(lua);
if (m_info->getter || !m_info->parentGetters.empty())
SetupGetter(lua, GetterProxy);
else
{
// Optimize by assigning the metatable instead of a search function
// This is only possible if we have no custom getter nor parent
lua.PushValue(-1); // Metatable
lua.SetField("__index");
}
if (m_info->setter)
SetupSetter(lua, SetterProxy);
// In case a __tostring method is missing, add a default implementation returning the class name
if (m_methods.find("__tostring") == m_methods.end())
SetupDefaultToString(lua);
m_info->methods.reserve(m_methods.size());
for (auto& pair : m_methods)
{
std::size_t methodIndex = m_info->methods.size();
m_info->methods.push_back(pair.second);
SetupMethod(lua, MethodProxy, pair.first, methodIndex);
}
}
lua.Pop(); //< Pops the metatable, it won't be collected before it's referenced by the Lua registry.
}
template<class T>
void LuaClass<T>::SetupMethod(LuaInstance& lua, LuaCFunction proxy, const String& name, std::size_t methodIndex)
{
lua.PushValue(1); // ClassInfo
lua.PushInteger(methodIndex);
lua.PushCFunction(proxy, 2);
lua.SetField(name); // Method name
}
template<class T>
void LuaClass<T>::SetupSetter(LuaInstance& lua, LuaCFunction proxy)
{
lua.PushValue(1); // ClassInfo
lua.PushCFunction(proxy, 1);
lua.SetField("__newindex"); // Setter
}
template<class T> template<class T>
int LuaClass<T>::ConstructorProxy(lua_State* state) int LuaClass<T>::ConstructorProxy(lua_State* state)
{ {
@ -389,7 +449,7 @@ namespace Nz
{ {
// Query from the metatable // Query from the metatable
lua.GetMetatable(info->name); //< Metatable lua.GetMetatable(info->name); //< Metatable
lua.PushValue(1); //< Field lua.PushValue(2); //< Field
lua.GetTable(); // Metatable[Field] lua.GetTable(); // Metatable[Field]
lua.Remove(-2); // Remove Metatable lua.Remove(-2); // Remove Metatable
@ -416,7 +476,6 @@ namespace Nz
std::shared_ptr<ClassInfo>& info = *static_cast<std::shared_ptr<ClassInfo>*>(lua.ToUserdata(lua.GetIndexOfUpValue(1))); std::shared_ptr<ClassInfo>& info = *static_cast<std::shared_ptr<ClassInfo>*>(lua.ToUserdata(lua.GetIndexOfUpValue(1)));
T* instance = static_cast<T*>(lua.CheckUserdata(1, info->name)); T* instance = static_cast<T*>(lua.CheckUserdata(1, info->name));
lua.Remove(1); //< Remove the instance from the Lua stack
Get(info, lua, instance); Get(info, lua, instance);
return 1; return 1;
@ -432,7 +491,7 @@ namespace Nz
T* instance = nullptr; T* instance = nullptr;
if (lua.GetMetatable(1)) if (lua.GetMetatable(1))
{ {
LuaType type = lua.GetField("__type"); LuaType type = lua.GetField("__name");
if (type == LuaType_String) if (type == LuaType_String)
{ {
String name = lua.ToString(-1); String name = lua.ToString(-1);
@ -441,8 +500,6 @@ namespace Nz
instance = it->second(lua); instance = it->second(lua);
} }
lua.Pop(2); lua.Pop(2);
lua.Remove(1); //< Remove the instance from the Lua stack
} }
if (!instance) if (!instance)
@ -451,9 +508,11 @@ namespace Nz
return 0; return 0;
} }
std::size_t argCount = lua.GetStackTop() - 1U;
unsigned int index = static_cast<unsigned int>(lua.ToInteger(lua.GetIndexOfUpValue(2))); unsigned int index = static_cast<unsigned int>(lua.ToInteger(lua.GetIndexOfUpValue(2)));
const ClassFunc& method = info->methods[index]; const ClassFunc& method = info->methods[index];
return method(lua, *instance); return method(lua, *instance, argCount);
} }
template<class T> template<class T>
@ -465,7 +524,6 @@ namespace Nz
const ClassIndexFunc& setter = info->setter; const ClassIndexFunc& setter = info->setter;
T& instance = *static_cast<T*>(lua.CheckUserdata(1, info->name)); T& instance = *static_cast<T*>(lua.CheckUserdata(1, info->name));
lua.Remove(1); //< Remove the instance from the Lua stack
if (!setter(lua, instance)) if (!setter(lua, instance))
{ {

View File

@ -34,10 +34,10 @@ namespace Nz
inline LuaInstance(LuaInstance&& instance) noexcept; inline LuaInstance(LuaInstance&& instance) noexcept;
~LuaInstance(); ~LuaInstance();
void ArgCheck(bool condition, unsigned int argNum, const char* error); void ArgCheck(bool condition, unsigned int argNum, const char* error) const;
void ArgCheck(bool condition, unsigned int argNum, const String& error); void ArgCheck(bool condition, unsigned int argNum, const String& error) const;
int ArgError(unsigned int argNum, const char* error); int ArgError(unsigned int argNum, const char* error) const;
int ArgError(unsigned int argNum, const String& error); int ArgError(unsigned int argNum, const String& error) const;
bool Call(unsigned int argCount); bool Call(unsigned int argCount);
bool Call(unsigned int argCount, unsigned int resultCount); bool Call(unsigned int argCount, unsigned int resultCount);
@ -123,6 +123,7 @@ namespace Nz
void Pop(unsigned int n = 1U) const; void Pop(unsigned int n = 1U) const;
template<typename T> int Push(T arg) const; template<typename T> int Push(T arg) const;
template<typename T, typename T2, typename... Args> int Push(T firstArg, T2 secondArg, Args... args) const;
void PushBoolean(bool value) const; void PushBoolean(bool value) const;
void PushCFunction(LuaCFunction func, unsigned int upvalueCount = 0) const; void PushCFunction(LuaCFunction func, unsigned int upvalueCount = 0) const;
template<typename T> void PushField(const char* name, T&& arg, int tableIndex = -2) const; template<typename T> void PushField(const char* name, T&& arg, int tableIndex = -2) const;

View File

@ -209,6 +209,24 @@ namespace Nz
return LuaImplReplyVal(instance, val, TypeTag<T>()); return LuaImplReplyVal(instance, val, TypeTag<T>());
} }
template<typename T>
std::enable_if_t<!std::is_arithmetic<T>::value && !std::is_enum<T>::value, int> LuaImplReplyVal(const LuaInstance& instance, T val, TypeTag<T&>)
{
return LuaImplReplyVal(instance, std::move(val), TypeTag<T>());
}
template<typename T>
std::enable_if_t<!std::is_arithmetic<T>::value && !std::is_enum<T>::value, int> LuaImplReplyVal(const LuaInstance& instance, T val, TypeTag<const T&>)
{
return LuaImplReplyVal(instance, std::move(val), TypeTag<T>());
}
template<typename T>
int LuaImplReplyVal(const LuaInstance& instance, T&& val, TypeTag<T&&>)
{
return LuaImplReplyVal(instance, std::forward<T>(val), TypeTag<T>());
}
inline int LuaImplReplyVal(const LuaInstance& instance, std::string&& val, TypeTag<std::string>) inline int LuaImplReplyVal(const LuaInstance& instance, std::string&& val, TypeTag<std::string>)
{ {
instance.PushString(val.c_str(), val.size()); instance.PushString(val.c_str(), val.size());
@ -266,7 +284,7 @@ namespace Nz
template<std::size_t N, std::size_t FirstDefArg, typename ArgType, typename ArgContainer, typename DefArgContainer> template<std::size_t N, std::size_t FirstDefArg, typename ArgType, typename ArgContainer, typename DefArgContainer>
static unsigned int Process(const LuaInstance& instance, unsigned int argIndex, ArgContainer& args, DefArgContainer& defArgs) static unsigned int Process(const LuaInstance& instance, unsigned int argIndex, ArgContainer& args, DefArgContainer& defArgs)
{ {
return LuaImplQueryArg(instance, argIndex, &std::get<N>(args), std::get<std::tuple_size<DefArgContainer>() - N + FirstDefArg - 1>(defArgs), TypeTag<ArgType>()); return LuaImplQueryArg(instance, argIndex, &std::get<N>(args), std::get<FirstDefArg + std::tuple_size<DefArgContainer>() - N - 1>(defArgs), TypeTag<ArgType>());
} }
}; };
@ -302,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);
@ -373,9 +391,9 @@ namespace Nz
{ {
} }
void ProcessArgs(const LuaInstance& instance) const void ProcessArguments(const LuaInstance& instance) const
{ {
m_index = 1; m_index = 2; //< 1 being the instance
ProcessArgs<0, Args...>(instance); ProcessArgs<0, Args...>(instance);
} }
@ -394,6 +412,19 @@ namespace Nz
return LuaImplReplyVal(instance, std::move(Apply(object, func, m_args)), TypeTag<decltype(Apply(object, func, m_args))>()); return LuaImplReplyVal(instance, std::move(Apply(object, func, m_args)), TypeTag<decltype(Apply(object, func, m_args))>());
} }
template<typename T, typename P>
std::enable_if_t<std::is_base_of<P, T>::value, int> Invoke(const LuaInstance& instance, T& object, T&(P::*func)(Args...)) const
{
T& r = Apply(object, func, m_args);
if (&r == &object)
{
instance.PushValue(1); //< Userdata
return 1;
}
else
return LuaImplReplyVal(instance, r, TypeTag<T&>());
}
template<typename T, typename P> template<typename T, typename P>
std::enable_if_t<std::is_base_of<P, T>::value, int> Invoke(const LuaInstance& instance, const T& object, void(P::*func)(Args...) const) const std::enable_if_t<std::is_base_of<P, T>::value, int> Invoke(const LuaInstance& instance, const T& object, void(P::*func)(Args...) const) const
{ {
@ -409,11 +440,22 @@ namespace Nz
return LuaImplReplyVal(instance, std::move(Apply(object, func, m_args)), TypeTag<decltype(Apply(object, func, m_args))>()); return LuaImplReplyVal(instance, std::move(Apply(object, func, m_args)), TypeTag<decltype(Apply(object, func, m_args))>());
} }
template<typename T, typename P>
std::enable_if_t<std::is_base_of<P, T>::value, int> Invoke(const LuaInstance& instance, const T& object, const T&(P::*func)(Args...) const) const
{
const T& r = Apply(object, func, m_args);
if (&r == &object)
{
instance.PushValue(1); //< Userdata
return 1;
}
else
return LuaImplReplyVal(instance, r, TypeTag<T&>());
}
template<typename T, typename P> template<typename T, typename P>
std::enable_if_t<std::is_base_of<P, typename PointedType<T>::type>::value, int> Invoke(const LuaInstance& instance, T& object, void(P::*func)(Args...)) const std::enable_if_t<std::is_base_of<P, typename PointedType<T>::type>::value, int> Invoke(const LuaInstance& instance, T& object, void(P::*func)(Args...)) const
{ {
NazaraUnused(instance);
if (!object) if (!object)
{ {
instance.Error("Invalid object"); instance.Error("Invalid object");
@ -436,11 +478,28 @@ namespace Nz
return LuaImplReplyVal(instance, std::move(Apply(*object, func, m_args)), TypeTag<decltype(Apply(*object, func, m_args))>()); return LuaImplReplyVal(instance, std::move(Apply(*object, func, m_args)), TypeTag<decltype(Apply(*object, func, m_args))>());
} }
template<typename T, typename P>
std::enable_if_t<std::is_base_of<P, typename PointedType<T>::type>::value, int> Invoke(const LuaInstance& instance, T& object, typename PointedType<T>::type&(P::*func)(Args...) const) const
{
if (!object)
{
instance.Error("Invalid object");
return 0;
}
const typename PointedType<T>::type& r = Apply(*object, func, m_args);
if (&r == &*object)
{
instance.PushValue(1); //< Userdata
return 1;
}
else
return LuaImplReplyVal(instance, r, TypeTag<T&>());
}
template<typename T, typename P> template<typename T, typename P>
std::enable_if_t<std::is_base_of<P, typename PointedType<T>::type>::value, int> Invoke(const LuaInstance& instance, const T& object, void(P::*func)(Args...) const) const std::enable_if_t<std::is_base_of<P, typename PointedType<T>::type>::value, int> Invoke(const LuaInstance& instance, const T& object, void(P::*func)(Args...) const) const
{ {
NazaraUnused(instance);
if (!object) if (!object)
{ {
instance.Error("Invalid object"); instance.Error("Invalid object");
@ -463,6 +522,25 @@ namespace Nz
return LuaImplReplyVal(instance, std::move(Apply(*object, func, m_args)), TypeTag<decltype(Apply(*object, func, m_args))>()); return LuaImplReplyVal(instance, std::move(Apply(*object, func, m_args)), TypeTag<decltype(Apply(*object, func, m_args))>());
} }
template<typename T, typename P>
std::enable_if_t<std::is_base_of<P, typename PointedType<T>::type>::value, int> Invoke(const LuaInstance& instance, const T& object, const typename PointedType<T>::type&(P::*func)(Args...) const) const
{
if (!object)
{
instance.Error("Invalid object");
return 0;
}
const typename PointedType<T>::type& r = Apply(*object, func, m_args);
if (&r == &*object)
{
instance.PushValue(1); //< Userdata
return 1;
}
else
return LuaImplReplyVal(instance, r, TypeTag<T&>());
}
private: private:
using ArgContainer = std::tuple<std::remove_cv_t<std::remove_reference_t<Args>>...>; using ArgContainer = std::tuple<std::remove_cv_t<std::remove_reference_t<Args>>...>;
using DefArgContainer = std::tuple<std::remove_cv_t<std::remove_reference_t<DefArgs>>...>; using DefArgContainer = std::tuple<std::remove_cv_t<std::remove_reference_t<DefArgs>>...>;
@ -606,6 +684,16 @@ namespace Nz
return LuaImplReplyVal(*this, std::move(arg), TypeTag<T>()); return LuaImplReplyVal(*this, std::move(arg), TypeTag<T>());
} }
template<typename T, typename T2, typename... Args>
int LuaInstance::Push(T firstArg, T2 secondArg, Args... args) const
{
int valCount = 0;
valCount += Push(std::move(firstArg));
valCount += Push(secondArg, std::forward<Args>(args)...);
return valCount;
}
template<typename T> template<typename T>
void LuaInstance::PushField(const char* name, T&& arg, int tableIndex) const void LuaInstance::PushField(const char* name, T&& arg, int tableIndex) const
{ {
@ -626,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);
}); });
@ -648,7 +736,7 @@ namespace Nz
template<typename T> template<typename T>
void LuaInstance::PushInstance(const char* tname, const T& instance) const void LuaInstance::PushInstance(const char* tname, const T& instance) const
{ {
T* userdata = static_cast<T*>(PushUserdata(sizeof(T*))); T* userdata = static_cast<T*>(PushUserdata(sizeof(T)));
PlacementNew(userdata, instance); PlacementNew(userdata, instance);
SetMetatable(tname); SetMetatable(tname);
@ -657,7 +745,7 @@ namespace Nz
template<typename T> template<typename T>
void LuaInstance::PushInstance(const char* tname, T&& instance) const void LuaInstance::PushInstance(const char* tname, T&& instance) const
{ {
T* userdata = static_cast<T*>(PushUserdata(sizeof(T*))); T* userdata = static_cast<T*>(PushUserdata(sizeof(T)));
PlacementNew(userdata, std::move(instance)); PlacementNew(userdata, std::move(instance));
SetMetatable(tname); SetMetatable(tname);
@ -666,7 +754,7 @@ namespace Nz
template<typename T, typename... Args> template<typename T, typename... Args>
void LuaInstance::PushInstance(const char* tname, Args&&... args) const void LuaInstance::PushInstance(const char* tname, Args&&... args) const
{ {
T* userdata = static_cast<T*>(PushUserdata(sizeof(T*))); T* userdata = static_cast<T*>(PushUserdata(sizeof(T)));
PlacementNew(userdata, std::forward<Args>(args)...); PlacementNew(userdata, std::forward<Args>(args)...);
SetMetatable(tname); SetMetatable(tname);

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 24 Jun 2015 at 13:55:50 // This file was automatically generated
/* /*
Nazara Engine - Mathematics module Nazara Engine - Mathematics module

View File

@ -242,7 +242,7 @@ namespace Nz
} }
#endif #endif
T* ptr = (&m11) + column*4; const T* ptr = (&m11) + column*4;
return Vector4<T>(ptr); return Vector4<T>(ptr);
} }
@ -636,7 +636,7 @@ namespace Nz
} }
#endif #endif
T* ptr = &m11; const T* ptr = &m11;
return Vector4<T>(ptr[row], ptr[row+4], ptr[row+8], ptr[row+12]); return Vector4<T>(ptr[row], ptr[row+4], ptr[row+8], ptr[row+12]);
} }
@ -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

@ -553,9 +553,9 @@ namespace Nz
template<typename T> template<typename T>
Vector3<T> Quaternion<T>::operator*(const Vector3<T>& vec) const Vector3<T> Quaternion<T>::operator*(const Vector3<T>& vec) const
{ {
Vector3f quatVec(x, y, z); Vector3<T> quatVec(x, y, z);
Vector3f uv = quatVec.CrossProduct(vec); Vector3<T> uv = quatVec.CrossProduct(vec);
Vector3f uuv = quatVec.CrossProduct(uv); Vector3<T> uuv = quatVec.CrossProduct(uv);
uv *= F(2.0) * w; uv *= F(2.0) * w;
uuv *= F(2.0); uuv *= F(2.0);

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

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

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 03 Feb 2016 at 00:06:56 // This file was automatically generated
/* /*
Nazara Engine - Network module Nazara Engine - Network module
@ -36,7 +36,10 @@
#include <Nazara/Network/IpAddress.hpp> #include <Nazara/Network/IpAddress.hpp>
#include <Nazara/Network/NetPacket.hpp> #include <Nazara/Network/NetPacket.hpp>
#include <Nazara/Network/Network.hpp> #include <Nazara/Network/Network.hpp>
#include <Nazara/Network/RUdpConnection.hpp>
#include <Nazara/Network/RUdpMessage.hpp>
#include <Nazara/Network/SocketHandle.hpp> #include <Nazara/Network/SocketHandle.hpp>
#include <Nazara/Network/SocketPoller.hpp>
#include <Nazara/Network/TcpClient.hpp> #include <Nazara/Network/TcpClient.hpp>
#include <Nazara/Network/TcpServer.hpp> #include <Nazara/Network/TcpServer.hpp>
#include <Nazara/Network/UdpSocket.hpp> #include <Nazara/Network/UdpSocket.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

@ -1,4 +1,4 @@
// This file was automatically generated on 12 Jul 2016 at 17:44:43 // This file was automatically generated
/* /*
Nazara Engine - Noise module Nazara Engine - Noise module

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 14 Oct 2016 at 18:58:18 // This file was automatically generated
/* /*
Nazara Engine - Physics 2D module Nazara Engine - Physics 2D module
@ -29,11 +29,11 @@
#ifndef NAZARA_GLOBAL_PHYSICS2D_HPP #ifndef NAZARA_GLOBAL_PHYSICS2D_HPP
#define NAZARA_GLOBAL_PHYSICS2D_HPP #define NAZARA_GLOBAL_PHYSICS2D_HPP
#include <Nazara/Physics2D/PhysWorld2D.hpp>
#include <Nazara/Physics2D/Physics2D.hpp>
#include <Nazara/Physics2D/Collider2D.hpp> #include <Nazara/Physics2D/Collider2D.hpp>
#include <Nazara/Physics2D/Enums.hpp>
#include <Nazara/Physics2D/Config.hpp> #include <Nazara/Physics2D/Config.hpp>
#include <Nazara/Physics2D/Enums.hpp>
#include <Nazara/Physics2D/Physics2D.hpp>
#include <Nazara/Physics2D/PhysWorld2D.hpp>
#include <Nazara/Physics2D/RigidBody2D.hpp> #include <Nazara/Physics2D/RigidBody2D.hpp>
#endif // NAZARA_GLOBAL_PHYSICS2D_HPP #endif // NAZARA_GLOBAL_PHYSICS2D_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

@ -1,4 +1,4 @@
// This file was automatically generated on 14 Oct 2016 at 18:58:18 // This file was automatically generated
/* /*
Nazara Engine - Physics 3D module Nazara Engine - Physics 3D module
@ -29,11 +29,11 @@
#ifndef NAZARA_GLOBAL_PHYSICS3D_HPP #ifndef NAZARA_GLOBAL_PHYSICS3D_HPP
#define NAZARA_GLOBAL_PHYSICS3D_HPP #define NAZARA_GLOBAL_PHYSICS3D_HPP
#include <Nazara/Physics3D/PhysWorld3D.hpp>
#include <Nazara/Physics3D/Physics3D.hpp>
#include <Nazara/Physics3D/RigidBody3D.hpp>
#include <Nazara/Physics3D/Enums.hpp>
#include <Nazara/Physics3D/Config.hpp>
#include <Nazara/Physics3D/Collider3D.hpp> #include <Nazara/Physics3D/Collider3D.hpp>
#include <Nazara/Physics3D/Config.hpp>
#include <Nazara/Physics3D/Enums.hpp>
#include <Nazara/Physics3D/Physics3D.hpp>
#include <Nazara/Physics3D/PhysWorld3D.hpp>
#include <Nazara/Physics3D/RigidBody3D.hpp>
#endif // NAZARA_GLOBAL_PHYSICS3D_HPP #endif // NAZARA_GLOBAL_PHYSICS3D_HPP

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

@ -1,4 +1,4 @@
// This file was automatically generated on 24 Jun 2015 at 13:55:50 // This file was automatically generated
/* /*
Nazara Engine - Renderer module Nazara Engine - Renderer module
@ -38,6 +38,7 @@
#include <Nazara/Renderer/OpenGL.hpp> #include <Nazara/Renderer/OpenGL.hpp>
#include <Nazara/Renderer/RenderBuffer.hpp> #include <Nazara/Renderer/RenderBuffer.hpp>
#include <Nazara/Renderer/Renderer.hpp> #include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Renderer/RenderPipeline.hpp>
#include <Nazara/Renderer/RenderStates.hpp> #include <Nazara/Renderer/RenderStates.hpp>
#include <Nazara/Renderer/RenderTarget.hpp> #include <Nazara/Renderer/RenderTarget.hpp>
#include <Nazara/Renderer/RenderTargetParameters.hpp> #include <Nazara/Renderer/RenderTargetParameters.hpp>

View File

@ -10,7 +10,6 @@
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/ObjectLibrary.hpp> #include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp> #include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Core/Resource.hpp> #include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceManager.hpp> #include <Nazara/Core/ResourceManager.hpp>
#include <Nazara/Core/Signal.hpp> #include <Nazara/Core/Signal.hpp>
@ -31,7 +30,7 @@ namespace Nz
struct TextureImpl; struct TextureImpl;
class NAZARA_RENDERER_API Texture : public AbstractImage, public RefCounted, public Resource class NAZARA_RENDERER_API Texture : public AbstractImage, public Resource
{ {
friend TextureLibrary; friend TextureLibrary;
friend TextureManager; friend TextureManager;
@ -54,16 +53,16 @@ namespace Nz
void EnsureMipmapsUpdate() const; void EnsureMipmapsUpdate() const;
unsigned int GetDepth(UInt8 level = 0) const; unsigned int GetDepth(UInt8 level = 0) const override;
PixelFormatType GetFormat() const; PixelFormatType GetFormat() const override;
unsigned int GetHeight(UInt8 level = 0) const; unsigned int GetHeight(UInt8 level = 0) const override;
UInt8 GetLevelCount() const; UInt8 GetLevelCount() const override;
UInt8 GetMaxLevel() const; UInt8 GetMaxLevel() const override;
std::size_t GetMemoryUsage() const; std::size_t GetMemoryUsage() const override;
std::size_t GetMemoryUsage(UInt8 level) const; std::size_t GetMemoryUsage(UInt8 level) const override;
Vector3ui GetSize(UInt8 level = 0) const; Vector3ui GetSize(UInt8 level = 0) const override;
ImageType GetType() const; ImageType GetType() const override;
unsigned int GetWidth(UInt8 level = 0) const; unsigned int GetWidth(UInt8 level = 0) const override;
bool HasMipmaps() const; bool HasMipmaps() const;
@ -102,9 +101,9 @@ namespace Nz
bool Update(const Image& image, UInt8 level = 0); bool Update(const Image& image, UInt8 level = 0);
bool Update(const Image& image, const Boxui& box, UInt8 level = 0); bool Update(const Image& image, const Boxui& box, UInt8 level = 0);
bool Update(const Image& image, const Rectui& rect, unsigned int z = 0, UInt8 level = 0); bool Update(const Image& image, const Rectui& rect, unsigned int z = 0, UInt8 level = 0);
bool Update(const UInt8* pixels, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0); bool Update(const UInt8* pixels, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) override;
bool Update(const UInt8* pixels, const Boxui& box, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0); bool Update(const UInt8* pixels, const Boxui& box, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) override;
bool Update(const UInt8* pixels, const Rectui& rect, unsigned int z = 0, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0); bool Update(const UInt8* pixels, const Rectui& rect, unsigned int z = 0, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) override;
// Fonctions OpenGL // Fonctions OpenGL
unsigned int GetOpenGLID() const; unsigned int GetOpenGLID() const;

View File

@ -1,4 +1,4 @@
// This file was automatically generated on 12 Jul 2016 at 17:44:43 // This file was automatically generated
/* /*
Nazara Engine - Utility module Nazara Engine - Utility module
@ -42,6 +42,7 @@
#include <Nazara/Utility/Cursor.hpp> #include <Nazara/Utility/Cursor.hpp>
#include <Nazara/Utility/Enums.hpp> #include <Nazara/Utility/Enums.hpp>
#include <Nazara/Utility/Event.hpp> #include <Nazara/Utility/Event.hpp>
#include <Nazara/Utility/EventHandler.hpp>
#include <Nazara/Utility/Font.hpp> #include <Nazara/Utility/Font.hpp>
#include <Nazara/Utility/FontData.hpp> #include <Nazara/Utility/FontData.hpp>
#include <Nazara/Utility/FontGlyph.hpp> #include <Nazara/Utility/FontGlyph.hpp>

View File

@ -8,6 +8,7 @@
#define NAZARA_ABSTRACTIMAGE_HPP #define NAZARA_ABSTRACTIMAGE_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Math/Box.hpp> #include <Nazara/Math/Box.hpp>
#include <Nazara/Math/Rect.hpp> #include <Nazara/Math/Rect.hpp>
#include <Nazara/Math/Vector3.hpp> #include <Nazara/Math/Vector3.hpp>
@ -16,10 +17,16 @@
namespace Nz namespace Nz
{ {
class NAZARA_UTILITY_API AbstractImage class AbstractImage;
using AbstractImageConstRef = ObjectRef<const AbstractImage>;
using AbstractImageRef = ObjectRef<AbstractImage>;
class NAZARA_UTILITY_API AbstractImage : public RefCounted
{ {
public: public:
AbstractImage() = default; AbstractImage() = default;
inline AbstractImage(const AbstractImage& image);
virtual ~AbstractImage(); virtual ~AbstractImage();
UInt8 GetBytesPerPixel() const; UInt8 GetBytesPerPixel() const;
@ -43,4 +50,6 @@ namespace Nz
}; };
} }
#include <Nazara/Utility/AbstractImage.inl>
#endif // NAZARA_IMAGE_HPP #endif // NAZARA_IMAGE_HPP

View File

@ -0,0 +1,16 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/AbstractImage.hpp>
#include <Nazara/Utility/Debug.hpp>
namespace Nz
{
inline AbstractImage::AbstractImage(const AbstractImage&) :
RefCounted()
{
}
}
#include <Nazara/Utility/DebugOff.hpp>

View File

@ -10,7 +10,6 @@
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Color.hpp> #include <Nazara/Core/Color.hpp>
#include <Nazara/Core/ObjectLibrary.hpp> #include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/RefCounted.hpp> #include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Core/Resource.hpp> #include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceLoader.hpp> #include <Nazara/Core/ResourceLoader.hpp>
@ -47,7 +46,7 @@ namespace Nz
using ImageRef = ObjectRef<Image>; using ImageRef = ObjectRef<Image>;
using ImageSaver = ResourceSaver<Image, ImageParams>; using ImageSaver = ResourceSaver<Image, ImageParams>;
class NAZARA_UTILITY_API Image : public AbstractImage, public RefCounted, public Resource class NAZARA_UTILITY_API Image : public AbstractImage, public Resource
{ {
friend ImageLibrary; friend ImageLibrary;
friend ImageLoader; friend ImageLoader;

View File

@ -1,7 +1,7 @@
Platform | Build Status Platform | Build Status
------------ | ------------- ------------ | -------------
Windows | [![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/dj5qx7axym4uakmy/branch/master?svg=true)](https://ci.appveyor.com/project/DPSLynix/nazaraengine/branch/master) Windows | [![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/dj5qx7axym4uakmy/branch/master?svg=true)](https://ci.appveyor.com/project/DPSLynix/nazaraengine/branch/master)
Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine) Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg?branch=master)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine)
# Nazara Engine # Nazara Engine

View File

@ -1,7 +1,7 @@
Platforme | Build Status Platforme | Build Status
------------ | ------------- ------------ | -------------
Windows | [![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/dj5qx7axym4uakmy/branch/master?svg=true)](https://ci.appveyor.com/project/DPSLynix/nazaraengine/branch/master) Windows | [![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/dj5qx7axym4uakmy/branch/master?svg=true)](https://ci.appveyor.com/project/DPSLynix/nazaraengine/branch/master)
Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine) Linux | [![Travis CI Build Status](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine.svg?branch=master)](https://travis-ci.org/DigitalPulseSoftware/NazaraEngine)
# Nazara Engine # Nazara Engine

View File

@ -906,5 +906,5 @@ namespace Nz
} }
return true; return true;
}; }
} }

View File

@ -94,6 +94,7 @@ namespace Nz
void InstancedRenderable::UpdateData(InstanceData* instanceData) const void InstancedRenderable::UpdateData(InstanceData* instanceData) const
{ {
NazaraAssert(instanceData, "Invalid instance data"); NazaraAssert(instanceData, "Invalid instance data");
NazaraUnused(instanceData);
} }
InstancedRenderableLibrary::LibraryMap InstancedRenderable::s_library; InstancedRenderableLibrary::LibraryMap InstancedRenderable::s_library;

View File

@ -149,22 +149,22 @@ namespace Nz
lua_close(m_state); lua_close(m_state);
} }
void LuaInstance::ArgCheck(bool condition, unsigned int argNum, const char* error) void LuaInstance::ArgCheck(bool condition, unsigned int argNum, const char* error) const
{ {
luaL_argcheck(m_state, condition, argNum, error); luaL_argcheck(m_state, condition, argNum, error);
} }
void LuaInstance::ArgCheck(bool condition, unsigned int argNum, const String& error) void LuaInstance::ArgCheck(bool condition, unsigned int argNum, const String& error) const
{ {
luaL_argcheck(m_state, condition, argNum, error.GetConstBuffer()); luaL_argcheck(m_state, condition, argNum, error.GetConstBuffer());
} }
int LuaInstance::ArgError(unsigned int argNum, const char* error) int LuaInstance::ArgError(unsigned int argNum, const char* error) const
{ {
return luaL_argerror(m_state, argNum, error); return luaL_argerror(m_state, argNum, error);
} }
int LuaInstance::ArgError(unsigned int argNum, const String& error) int LuaInstance::ArgError(unsigned int argNum, const String& error) const
{ {
return luaL_argerror(m_state, argNum, error.GetConstBuffer()); return luaL_argerror(m_state, argNum, error.GetConstBuffer());
} }

View File

@ -146,7 +146,7 @@ namespace Nz
if (!m_buffer) if (!m_buffer)
m_buffer = std::make_unique<ByteArray>(); m_buffer = std::make_unique<ByteArray>();
m_buffer->Resize(static_cast<std::size_t>(cursorPos)); m_buffer->Resize(minCapacity);
m_memoryStream.SetBuffer(m_buffer.get(), openMode); m_memoryStream.SetBuffer(m_buffer.get(), openMode);
m_memoryStream.SetCursorPos(cursorPos); m_memoryStream.SetCursorPos(cursorPos);

View File

@ -385,7 +385,7 @@ namespace Nz
* \remark Produces a NazaraError because it is a special stream * \remark Produces a NazaraError because it is a special stream
*/ */
bool TcpClient::SetCursorPos(UInt64 offset) bool TcpClient::SetCursorPos(UInt64 /*offset*/)
{ {
NazaraError("SetCursorPos() cannot be used on sequential streams"); NazaraError("SetCursorPos() cannot be used on sequential streams");
return false; return false;

View File

@ -437,6 +437,10 @@ namespace Nz
return result; return result;
#else #else
NazaraUnused(fdarray);
NazaraUnused(nfds);
NazaraUnused(timeout);
if (error) if (error)
*error = SocketError_NotSupported; *error = SocketError_NotSupported;

View File

@ -2,8 +2,8 @@
// 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/MemoryManager.hpp> #include <Nazara/Core/MemoryManager.hpp>
#include <new> // Nécessaire ? #include <new> // Nécessaire ?

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
#include <Nazara/Physics3D/Config.hpp> #include <Nazara/Physics3D/Config.hpp>
#if NAZARA_PHYSICS_MANAGE_MEMORY #if NAZARA_PHYSICS3D_MANAGE_MEMORY
#include <Nazara/Core/MemoryManager.hpp> #include <Nazara/Core/MemoryManager.hpp>
#include <new> // Nécessaire ? #include <new> // Nécessaire ?

View File

@ -795,6 +795,7 @@ namespace Nz
NazaraAssert(attachmentIndex < m_impl->attachments.size(), "Invalid attachment index"); NazaraAssert(attachmentIndex < m_impl->attachments.size(), "Invalid attachment index");
NazaraAssert(!m_impl->attachments[attachmentIndex].isBuffer, "Invalid attachment state"); NazaraAssert(!m_impl->attachments[attachmentIndex].isBuffer, "Invalid attachment state");
NazaraUnused(texture); NazaraUnused(texture);
NazaraUnused(attachmentIndex);
InvalidateTargets(); InvalidateTargets();
} }

View File

@ -331,19 +331,19 @@ namespace Nz
Emit(mat.specular.b / 255.f); Emit(mat.specular.b / 255.f);
EmitLine(); EmitLine();
if (mat.alpha != 1.f) if (!NumberEquals(mat.alpha, 1.f))
{ {
Emit("d "); Emit("d ");
EmitLine(mat.alpha); EmitLine(mat.alpha);
} }
if (mat.refractionIndex != 1.f) if (!NumberEquals(mat.refractionIndex, 1.f))
{ {
Emit("ni "); Emit("ni ");
EmitLine(mat.refractionIndex); EmitLine(mat.refractionIndex);
} }
if (mat.shininess != 1.f) if (!NumberEquals(mat.shininess, 1.f))
{ {
Emit("ns "); Emit("ns ");
EmitLine(mat.shininess); EmitLine(mat.shininess);

View File

@ -128,17 +128,17 @@ namespace Nz
UInt32 faceReserve = 0; UInt32 faceReserve = 0;
UInt32 vertexReserve = 0; UInt32 vertexReserve = 0;
unsigned int matCount = 0; unsigned int matCount = 0;
auto GetMaterial = [&] (const String& meshName, const String& matName) -> Mesh* auto GetMaterial = [&] (const String& mesh, const String& mat) -> Mesh*
{ {
auto& map = meshesByName[meshName]; auto& map = meshesByName[mesh];
auto it = map.find(matName); auto it = map.find(mat);
if (it == map.end()) if (it == map.end())
it = map.insert(std::make_pair(matName, MatPair(Mesh(), matCount++))).first; it = map.insert(std::make_pair(mat, MatPair(Mesh(), matCount++))).first;
Mesh& mesh = it->second.first; Mesh& meshData = it->second.first;
mesh.faces.reserve(faceReserve); meshData.faces.reserve(faceReserve);
mesh.vertices.reserve(vertexReserve); meshData.vertices.reserve(vertexReserve);
faceReserve = 0; faceReserve = 0;
vertexReserve = 0; vertexReserve = 0;
@ -550,9 +550,9 @@ namespace Nz
EmitLine(pair.second.size()); EmitLine(pair.second.size());
EmitLine(); EmitLine();
for (std::size_t meshIndex : pair.second) for (std::size_t index : pair.second)
{ {
const Mesh& mesh = m_meshes[meshIndex]; const Mesh& mesh = m_meshes[index];
Emit("g "); Emit("g ");
EmitLine(mesh.name); EmitLine(mesh.name);

View File

@ -52,7 +52,7 @@ namespace Nz
} }
Image::Image(const Image& image) : Image::Image(const Image& image) :
RefCounted(), AbstractImage(image),
Resource(), Resource(),
m_sharedImage(image.m_sharedImage) m_sharedImage(image.m_sharedImage)
{ {

View File

@ -75,6 +75,7 @@ namespace Nz
Font* SimpleTextDrawer::GetFont(std::size_t index) const Font* SimpleTextDrawer::GetFont(std::size_t index) const
{ {
NazaraAssert(index == 0, "Font index out of range"); NazaraAssert(index == 0, "Font index out of range");
NazaraUnused(index);
return m_font; return m_font;
} }

View File

@ -11,7 +11,7 @@
namespace Nz namespace Nz
{ {
SoftwareBuffer::SoftwareBuffer(Buffer* /*parent*/, BufferType type) SoftwareBuffer::SoftwareBuffer(Buffer* /*parent*/, BufferType /*type*/)
{ {
} }

View File

@ -154,7 +154,7 @@ namespace Nz
// On attend que la fenêtre soit créée // On attend que la fenêtre soit créée
mutex.Lock(); mutex.Lock();
m_thread = Thread(WindowThread, &m_handle, win32StyleEx, title.GetWideString().data(), win32Style, x, y, width, height, this, &mutex, &condition); m_thread = Thread(WindowThread, &m_handle, win32StyleEx, title, win32Style, x, y, width, height, this, &mutex, &condition);
condition.Wait(&mutex); condition.Wait(&mutex);
mutex.Unlock(); mutex.Unlock();
#else #else
@ -789,15 +789,25 @@ namespace Nz
case WM_MOVE: case WM_MOVE:
{ {
#if !NAZARA_UTILITY_THREADED_WINDOW
if (m_sizemove)
break;
#endif
RECT windowRect; RECT windowRect;
GetWindowRect(m_handle, &windowRect); GetWindowRect(m_handle, &windowRect);
WindowEvent event; Vector2i position(windowRect.left, windowRect.top);
event.type = WindowEventType_Moved; if (m_position != position)
event.position.x = windowRect.left; {
event.position.y = windowRect.top; m_position = position;
m_parent->PushEvent(event);
WindowEvent event;
event.type = WindowEventType_Moved;
event.position.x = position.x;
event.position.y = position.y;
m_parent->PushEvent(event);
}
break; break;
} }
@ -1178,10 +1188,10 @@ namespace Nz
} }
#if NAZARA_UTILITY_THREADED_WINDOW #if NAZARA_UTILITY_THREADED_WINDOW
void WindowImpl::WindowThread(HWND* handle, DWORD styleEx, const wchar_t* title, DWORD style, unsigned int x, unsigned int y, unsigned int width, unsigned int height, WindowImpl* window, Mutex* mutex, ConditionVariable* condition) void WindowImpl::WindowThread(HWND* handle, DWORD styleEx, const String& title, DWORD style, unsigned int x, unsigned int y, unsigned int width, unsigned int height, WindowImpl* window, Mutex* mutex, ConditionVariable* condition)
{ {
HWND& winHandle = *handle; HWND& winHandle = *handle;
winHandle = CreateWindowExW(styleEx, className, title, style, x, y, width, height, nullptr, nullptr, GetModuleHandle(nullptr), window); winHandle = CreateWindowExW(styleEx, className, title.GetWideString().data(), style, x, y, width, height, nullptr, nullptr, GetModuleHandle(nullptr), window);
mutex->Lock(); mutex->Lock();
condition->Signal(); condition->Signal();

View File

@ -89,7 +89,7 @@ namespace Nz
static LRESULT CALLBACK MessageHandler(HWND window, UINT message, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK MessageHandler(HWND window, UINT message, WPARAM wParam, LPARAM lParam);
static UInt32 RetrieveStyle(HWND window); static UInt32 RetrieveStyle(HWND window);
#if NAZARA_UTILITY_THREADED_WINDOW #if NAZARA_UTILITY_THREADED_WINDOW
static void WindowThread(HWND* handle, DWORD styleEx, const wchar_t* title, DWORD style, unsigned int x, unsigned int y, unsigned int width, unsigned int height, WindowImpl* window, Mutex* mutex, ConditionVariable* condition); static void WindowThread(HWND* handle, DWORD styleEx, const String& title, DWORD style, unsigned int x, unsigned int y, unsigned int width, unsigned int height, WindowImpl* window, Mutex* mutex, ConditionVariable* condition);
#endif #endif
HCURSOR m_cursor; HCURSOR m_cursor;

View File

@ -335,6 +335,7 @@ namespace Nz
void Window::ProcessEvents(bool block) void Window::ProcessEvents(bool block)
{ {
NazaraAssert(m_impl, "Window not created"); NazaraAssert(m_impl, "Window not created");
NazaraUnused(block);
#if !NAZARA_UTILITY_THREADED_WINDOW #if !NAZARA_UTILITY_THREADED_WINDOW
m_impl->ProcessEvents(block); m_impl->ProcessEvents(block);