Merge branch 'master' into NDK-ShadowMapping

Former-commit-id: 83435ab51753299b30a102871fbcd5558d2ac4f1
This commit is contained in:
Lynix 2015-12-09 00:59:07 +01:00
commit 9cf5e4b68c
751 changed files with 79400 additions and 71735 deletions

3
.gitignore vendored
View File

@ -5,6 +5,9 @@ lib/*
# Feature page # Feature page
build/scripts/features/index.html build/scripts/features/index.html
# Documentation
doc
# Codeblocks # Codeblocks
build/**/*.cbp build/**/*.cbp
build/**/*.cbp build/**/*.cbp

2458
Doxyfile Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,33 +0,0 @@
if (not _OPTIONS["united"]) then
project "NazaraModuleName"
end
files
{
"../include/Nazara/ModuleName/**.hpp",
"../include/Nazara/ModuleName/**.inl",
"../src/Nazara/ModuleName/**.hpp",
"../src/Nazara/ModuleName/**.cpp"
}
if (os.is("windows")) then
excludes { "../src/Nazara/ModuleName/Posix/*.hpp", "../src/Nazara/ModuleName/Posix/*.cpp" }
else
excludes { "../src/Nazara/ModuleName/Win32/*.hpp", "../src/Nazara/ModuleName/Win32/*.cpp" }
end
if (_OPTIONS["united"]) then
excludes "../src/Nazara/ModuleName/Debug/NewOverload.cpp"
else
configuration "DebugStatic"
links "NazaraCore-s-d"
configuration "ReleaseStatic"
links "NazaraCore-s"
configuration "DebugDLL"
links "NazaraCore-d"
configuration "ReleaseDLL"
links "NazaraCore"
end

View File

@ -0,0 +1,15 @@
MODULE.Name = "ModuleName"
MODULE.Libraries = {
"NazaraCore"
}
MODULE.OsFiles.Windows = {
"../src/Nazara/ModuleName/Win32/**.hpp",
"../src/Nazara/ModuleName/Win32/**.cpp"
}
MODULE.OsFiles.Posix = {
"../src/Nazara/ModuleName/Posix/**.hpp",
"../src/Nazara/ModuleName/Posix/**.cpp"
}

View File

@ -7,19 +7,22 @@
#ifndef NAZARA_CLASSNAME_HPP #ifndef NAZARA_CLASSNAME_HPP
#define NAZARA_CLASSNAME_HPP #define NAZARA_CLASSNAME_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/ModuleName/Config.hpp>
class NAZARA_API NzClassName namespace Nz
{ {
public: class NAZARA_MODULENAME_API ClassName
NzClassName(); {
public:
ClassName();
int GetAttribute() const; int GetAttribute() const;
void SetAttribute(int attribute); void SetAttribute(int attribute);
private: private:
int m_attribute; int m_attribute;
}; };
}
#endif // NAZARA_CLASSNAME_HPP #endif // NAZARA_CLASSNAME_HPP

View File

@ -40,4 +40,14 @@
/// Vérification des valeurs et types de certaines constantes /// Vérification des valeurs et types de certaines constantes
#include <Nazara/ModuleName/ConfigCheck.hpp> #include <Nazara/ModuleName/ConfigCheck.hpp>
#if !defined(NAZARA_STATIC)
#ifdef NAZARA_MODULENAME_BUILD
#define NAZARA_MODULENAME_API NAZARA_EXPORT
#else
#define NAZARA_MODULENAME_API NAZARA_IMPORT
#endif
#else
#define NAZARA_MODULENAME_API
#endif
#endif // NAZARA_CONFIG_MODULENAME_HPP #endif // NAZARA_CONFIG_MODULENAME_HPP

View File

@ -16,7 +16,7 @@
// 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_MODULENAME_MANAGE_MEMORY #if defined(NAZARA_DEBUG) && !NAZARA_MODULENAME_MANAGE_MEMORY
#undef NAZARA_MODULENAME_MANAGE_MEMORY #undef NAZARA_MODULENAME_MANAGE_MEMORY
#define NAZARA_MODULENAME_MANAGE_MEMORY 1 #define NAZARA_MODULENAME_MANAGE_MEMORY 0
#endif #endif
#endif // NAZARA_CONFIG_CHECK_MODULENAME_HPP #endif // NAZARA_CONFIG_CHECK_MODULENAME_HPP

View File

@ -1,9 +1,9 @@
// Copyright (C) 2014 AUTHORS // Copyright (C) YEAR AUTHORS
// This file is part of the "Nazara Engine - Module name" // This file is part of the "Nazara Engine - Module name"
// 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_MODULENAME_HPP #if NAZARA_MODULENAME_MANAGE_MEMORY
#undef delete #undef delete
#undef new #undef new
#endif #endif

View File

@ -9,21 +9,25 @@
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Initializer.hpp> #include <Nazara/Core/Initializer.hpp>
#include <Nazara/ModuleName/Config.hpp>
class NAZARA_API NzModuleName namespace Nz
{ {
public: class NAZARA_MODULENAME_API ModuleName
NzModuleName() = delete; {
~NzModuleName() = delete; public:
ModuleName() = delete;
~ModuleName() = delete;
static bool Initialize(); static bool Initialize();
static bool IsInitialized(); static bool IsInitialized();
static void Uninitialize(); static void Uninitialize();
private: private:
static unsigned int s_moduleReferenceCounter; static unsigned int s_moduleReferenceCounter;
}; };
}
#endif // NAZARA_MODULENAME_HPP #endif // NAZARA_MODULENAME_HPP

View File

@ -5,17 +5,21 @@
#include <Nazara/ModuleName/ClassName.hpp> #include <Nazara/ModuleName/ClassName.hpp>
#include <Nazara/ModuleName/Debug.hpp> #include <Nazara/ModuleName/Debug.hpp>
NzClassName::NzClassName() : namespace Nz
m_attribute(42)
{ {
ClassName::ClassName() :
m_attribute(42)
{
}
int ClassName::GetAttribute() const
{
return m_attribute;
}
void ClassName::SetAttribute(int attribute)
{
m_attribute = attribute;
}
} }
int NzClassName::GetAttribute() const
{
return m_attribute;
}
void NzClassName::SetAttribute(int attribute)
{
m_attribute = attribute;
}

View File

@ -10,22 +10,22 @@
void* operator new(std::size_t size) void* operator new(std::size_t size)
{ {
return NzMemoryManager::Allocate(size, false); return Nz::MemoryManager::Allocate(size, false);
} }
void* operator new[](std::size_t size) void* operator new[](std::size_t size)
{ {
return NzMemoryManager::Allocate(size, true); return Nz::MemoryManager::Allocate(size, true);
} }
void operator delete(void* pointer) noexcept void operator delete(void* pointer) noexcept
{ {
NzMemoryManager::Free(pointer, false); Nz::MemoryManager::Free(pointer, false);
} }
void operator delete[](void* pointer) noexcept void operator delete[](void* pointer) noexcept
{ {
NzMemoryManager::Free(pointer, true); Nz::MemoryManager::Free(pointer, true);
} }
#endif // NAZARA_MODULENAME_MANAGE_MEMORY #endif // NAZARA_MODULENAME_MANAGE_MEMORY

View File

@ -10,55 +10,61 @@
#include <Nazara/ModuleName/Config.hpp> #include <Nazara/ModuleName/Config.hpp>
#include <Nazara/ModuleName/Debug.hpp> #include <Nazara/ModuleName/Debug.hpp>
bool NzModuleName::Initialize() namespace Nz
{ {
if (s_moduleReferenceCounter > 0) bool ModuleName::Initialize()
{ {
if (s_moduleReferenceCounter > 0)
{
s_moduleReferenceCounter++;
return true; // Already initialized
}
// Initialize module dependencies
if (!Core::Initialize())
{
NazaraError("Failed to initialize core module");
return false;
}
s_moduleReferenceCounter++; s_moduleReferenceCounter++;
return true; // Déjà initialisé
CallOnExit onExit(ModuleName::Uninitialize);
// Initialize module here
onExit.Reset();
NazaraNotice("Initialized: ModuleName module");
return true;
} }
// Initialisation des dépendances bool ModuleName::IsInitialized()
if (!NzCore::Initialize())
{ {
NazaraError("Failed to initialize core module"); return s_moduleReferenceCounter != 0;
return false;
} }
s_moduleReferenceCounter++; void ModuleName::Uninitialize()
// Initialisation du module
NzCallOnExit onExit(NzModuleName::Uninitialize);
onExit.Reset();
NazaraNotice("Initialized: ModuleName module");
return true;
}
bool NzModuleName::IsInitialized()
{
return s_moduleReferenceCounter != 0;
}
void NzModuleName::Uninitialize()
{
if (s_moduleReferenceCounter != 1)
{ {
// Le module est soit encore utilisé, soit pas initialisé if (s_moduleReferenceCounter != 1)
if (s_moduleReferenceCounter > 1) {
s_moduleReferenceCounter--; // Either the module is not initialized, either it was initialized multiple times
if (s_moduleReferenceCounter > 1)
s_moduleReferenceCounter--;
return; return;
}
s_moduleReferenceCounter = 0;
// Uninitialize module here
NazaraNotice("Uninitialized: ModuleName module");
// Free module dependencies
Core::Uninitialize();
} }
// Libération du module unsigned int ModuleName::s_moduleReferenceCounter = 0;
s_moduleReferenceCounter = 0;
NazaraNotice("Uninitialized: ModuleName module");
// Libération des dépendances
NzCore::Uninitialize();
} }
unsigned int NzModuleName::s_moduleReferenceCounter = 0;

View File

@ -9,7 +9,7 @@ namespace Ndk
{ {
inline Application::Application() inline Application::Application()
{ {
NzErrorFlags errFlags(nzErrorFlag_ThrowException, true); Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true);
// Initialisation du SDK // Initialisation du SDK
Sdk::Initialize(); Sdk::Initialize();

View File

@ -24,7 +24,7 @@ namespace Ndk
BaseComponent(ComponentIndex componentIndex); BaseComponent(ComponentIndex componentIndex);
BaseComponent(const BaseComponent&) = default; BaseComponent(const BaseComponent&) = default;
BaseComponent(BaseComponent&&) noexcept = default; BaseComponent(BaseComponent&&) = default;
virtual ~BaseComponent(); virtual ~BaseComponent();
virtual BaseComponent* Clone() const = 0; virtual BaseComponent* Clone() const = 0;
@ -32,7 +32,7 @@ namespace Ndk
ComponentIndex GetIndex() const; ComponentIndex GetIndex() const;
BaseComponent& operator=(const BaseComponent&) = default; BaseComponent& operator=(const BaseComponent&) = default;
BaseComponent& operator=(BaseComponent&&) noexcept = default; BaseComponent& operator=(BaseComponent&&) = default;
protected: protected:
ComponentIndex m_componentIndex; ComponentIndex m_componentIndex;

View File

@ -79,11 +79,11 @@ namespace Ndk
static inline void Uninitialize(); static inline void Uninitialize();
std::vector<EntityHandle> m_entities; std::vector<EntityHandle> m_entities;
NzBitset<nzUInt64> m_entityBits; Nz::Bitset<Nz::UInt64> m_entityBits;
NzBitset<> m_excludedComponents; Nz::Bitset<> m_excludedComponents;
mutable NzBitset<> m_filterResult; mutable Nz::Bitset<> m_filterResult;
NzBitset<> m_requiredAnyComponents; Nz::Bitset<> m_requiredAnyComponents;
NzBitset<> m_requiredComponents; Nz::Bitset<> m_requiredComponents;
SystemIndex m_systemIndex; SystemIndex m_systemIndex;
World* m_world; World* m_world;
float m_updateCounter; float m_updateCounter;

View File

@ -19,7 +19,7 @@ namespace Ndk
{ {
class Entity; class Entity;
class NDK_API CameraComponent : public Component<CameraComponent>, public NzAbstractViewer class NDK_API CameraComponent : public Component<CameraComponent>, public Nz::AbstractViewer
{ {
public: public:
inline CameraComponent(); inline CameraComponent();
@ -34,26 +34,26 @@ namespace Ndk
inline void EnsureViewportUpdate() const; inline void EnsureViewportUpdate() const;
inline float GetAspectRatio() const; inline float GetAspectRatio() const;
inline NzVector3f GetEyePosition() const; inline Nz::Vector3f GetEyePosition() const;
inline NzVector3f GetForward() const; inline Nz::Vector3f GetForward() const;
inline float GetFOV() const; inline float GetFOV() const;
inline const NzFrustumf& GetFrustum() const; inline const Nz::Frustumf& GetFrustum() const;
inline unsigned int GetLayer() const; inline unsigned int GetLayer() const;
inline const NzMatrix4f& GetProjectionMatrix() const; inline const Nz::Matrix4f& GetProjectionMatrix() const;
inline nzProjectionType GetProjectionType() const; inline Nz::ProjectionType GetProjectionType() const;
inline const NzRenderTarget* GetTarget() const; inline const Nz::RenderTarget* GetTarget() const;
inline const NzRectf& GetTargetRegion() const; inline const Nz::Rectf& GetTargetRegion() const;
inline const NzMatrix4f& GetViewMatrix() const; inline const Nz::Matrix4f& GetViewMatrix() const;
inline const NzRecti& GetViewport() const; inline const Nz::Recti& GetViewport() const;
inline float GetZFar() const; inline float GetZFar() const;
inline float GetZNear() const; inline float GetZNear() const;
inline void SetFOV(float fov); inline void SetFOV(float fov);
inline void SetLayer(unsigned int layer); inline void SetLayer(unsigned int layer);
inline void SetProjectionType(nzProjectionType projection); inline void SetProjectionType(Nz::ProjectionType projection);
inline void SetTarget(const NzRenderTarget* renderTarget); inline void SetTarget(const Nz::RenderTarget* renderTarget);
inline void SetTargetRegion(const NzRectf& region); inline void SetTargetRegion(const Nz::Rectf& region);
inline void SetViewport(const NzRecti& viewport); inline void SetViewport(const Nz::Recti& viewport);
inline void SetZFar(float zFar); inline void SetZFar(float zFar);
inline void SetZNear(float zNear); inline void SetZNear(float zNear);
@ -69,26 +69,26 @@ namespace Ndk
void OnComponentAttached(BaseComponent& component) override; void OnComponentAttached(BaseComponent& component) override;
void OnComponentDetached(BaseComponent& component) override; void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override; void OnDetached() override;
void OnNodeInvalidated(const NzNode* node); void OnNodeInvalidated(const Nz::Node* node);
void OnRenderTargetRelease(const NzRenderTarget* renderTarget); void OnRenderTargetRelease(const Nz::RenderTarget* renderTarget);
void OnRenderTargetSizeChange(const NzRenderTarget* renderTarget); void OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget);
void UpdateFrustum() const; void UpdateFrustum() const;
void UpdateProjectionMatrix() const; void UpdateProjectionMatrix() const;
void UpdateViewMatrix() const; void UpdateViewMatrix() const;
void UpdateViewport() const; void UpdateViewport() const;
NazaraSlot(NzNode, OnNodeInvalidation, m_nodeInvalidationSlot); NazaraSlot(Nz::Node, OnNodeInvalidation, m_nodeInvalidationSlot);
NazaraSlot(NzRenderTarget, OnRenderTargetRelease, m_targetReleaseSlot); NazaraSlot(Nz::RenderTarget, OnRenderTargetRelease, m_targetReleaseSlot);
NazaraSlot(NzRenderTarget, OnRenderTargetSizeChange, m_targetResizeSlot); NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_targetResizeSlot);
nzProjectionType m_projectionType; Nz::ProjectionType m_projectionType;
mutable NzFrustumf m_frustum; mutable Nz::Frustumf m_frustum;
mutable NzMatrix4f m_projectionMatrix; mutable Nz::Matrix4f m_projectionMatrix;
mutable NzMatrix4f m_viewMatrix; mutable Nz::Matrix4f m_viewMatrix;
NzRectf m_targetRegion; Nz::Rectf m_targetRegion;
mutable NzRecti m_viewport; mutable Nz::Recti m_viewport;
const NzRenderTarget* m_target; const Nz::RenderTarget* m_target;
mutable bool m_frustumUpdated; mutable bool m_frustumUpdated;
mutable bool m_projectionMatrixUpdated; mutable bool m_projectionMatrixUpdated;
mutable bool m_viewMatrixUpdated; mutable bool m_viewMatrixUpdated;

View File

@ -8,7 +8,7 @@
namespace Ndk namespace Ndk
{ {
inline CameraComponent::CameraComponent() : inline CameraComponent::CameraComponent() :
m_projectionType(nzProjectionType_Perspective), m_projectionType(Nz::ProjectionType_Perspective),
m_targetRegion(0.f, 0.f, 1.f, 1.f), m_targetRegion(0.f, 0.f, 1.f, 1.f),
m_target(nullptr), m_target(nullptr),
m_frustumUpdated(false), m_frustumUpdated(false),
@ -25,7 +25,7 @@ namespace Ndk
inline CameraComponent::CameraComponent(const CameraComponent& camera) : inline CameraComponent::CameraComponent(const CameraComponent& camera) :
Component(camera), Component(camera),
NzAbstractViewer(camera), AbstractViewer(camera),
m_projectionType(camera.m_projectionType), m_projectionType(camera.m_projectionType),
m_targetRegion(camera.m_targetRegion), m_targetRegion(camera.m_targetRegion),
m_target(nullptr), m_target(nullptr),
@ -78,7 +78,7 @@ namespace Ndk
return m_fov; return m_fov;
} }
inline const NzFrustumf& CameraComponent::GetFrustum() const inline const Nz::Frustumf& CameraComponent::GetFrustum() const
{ {
EnsureFrustumUpdate(); EnsureFrustumUpdate();
@ -90,36 +90,36 @@ namespace Ndk
return m_layer; return m_layer;
} }
inline const NzMatrix4f& CameraComponent::GetProjectionMatrix() const inline const Nz::Matrix4f& CameraComponent::GetProjectionMatrix() const
{ {
EnsureProjectionMatrixUpdate(); EnsureProjectionMatrixUpdate();
return m_projectionMatrix; return m_projectionMatrix;
} }
inline nzProjectionType CameraComponent::GetProjectionType() const inline Nz::ProjectionType CameraComponent::GetProjectionType() const
{ {
return m_projectionType; return m_projectionType;
} }
inline const NzRenderTarget* CameraComponent::GetTarget() const inline const Nz::RenderTarget* CameraComponent::GetTarget() const
{ {
return m_target; return m_target;
} }
inline const NzRectf& CameraComponent::GetTargetRegion() const inline const Nz::Rectf& CameraComponent::GetTargetRegion() const
{ {
return m_targetRegion; return m_targetRegion;
} }
inline const NzMatrix4f& CameraComponent::GetViewMatrix() const inline const Nz::Matrix4f& CameraComponent::GetViewMatrix() const
{ {
EnsureViewMatrixUpdate(); EnsureViewMatrixUpdate();
return m_viewMatrix; return m_viewMatrix;
} }
inline const NzRecti& CameraComponent::GetViewport() const inline const Nz::Recti& CameraComponent::GetViewport() const
{ {
EnsureViewportUpdate(); EnsureViewportUpdate();
@ -138,36 +138,42 @@ namespace Ndk
inline void CameraComponent::SetFOV(float fov) inline void CameraComponent::SetFOV(float fov)
{ {
NazaraAssert(!NzNumberEquals(fov, 0.f), "FOV must be different from zero"); NazaraAssert(!Nz::NumberEquals(fov, 0.f), "FOV must be different from zero");
m_fov = fov; m_fov = fov;
InvalidateProjectionMatrix(); InvalidateProjectionMatrix();
} }
inline void CameraComponent::SetProjectionType(nzProjectionType projectionType) inline void CameraComponent::SetProjectionType(Nz::ProjectionType projectionType)
{ {
m_projectionType = projectionType; m_projectionType = projectionType;
InvalidateProjectionMatrix(); InvalidateProjectionMatrix();
} }
inline void CameraComponent::SetTarget(const NzRenderTarget* renderTarget) inline void CameraComponent::SetTarget(const Nz::RenderTarget* renderTarget)
{ {
m_target = renderTarget; m_target = renderTarget;
if (m_target) if (m_target)
{
m_targetResizeSlot.Connect(m_target->OnRenderTargetSizeChange, this, &CameraComponent::OnRenderTargetSizeChange);
m_targetReleaseSlot.Connect(m_target->OnRenderTargetRelease, this, &CameraComponent::OnRenderTargetRelease); m_targetReleaseSlot.Connect(m_target->OnRenderTargetRelease, this, &CameraComponent::OnRenderTargetRelease);
}
else else
{
m_targetResizeSlot.Disconnect();
m_targetReleaseSlot.Disconnect(); m_targetReleaseSlot.Disconnect();
}
} }
inline void CameraComponent::SetTargetRegion(const NzRectf& region) inline void CameraComponent::SetTargetRegion(const Nz::Rectf& region)
{ {
m_targetRegion = region; m_targetRegion = region;
InvalidateViewport(); InvalidateViewport();
} }
inline void CameraComponent::SetViewport(const NzRecti& viewport) inline void CameraComponent::SetViewport(const Nz::Recti& viewport)
{ {
NazaraAssert(m_target, "Component has no render target"); NazaraAssert(m_target, "Component has no render target");
@ -175,7 +181,7 @@ namespace Ndk
float invWidth = 1.f/m_target->GetWidth(); float invWidth = 1.f/m_target->GetWidth();
float invHeight = 1.f/m_target->GetHeight(); float invHeight = 1.f/m_target->GetHeight();
SetTargetRegion(NzRectf(invWidth * viewport.x, invHeight * viewport.y, invWidth * viewport.width, invHeight * viewport.height)); SetTargetRegion(Nz::Rectf(invWidth * viewport.x, invHeight * viewport.y, invWidth * viewport.width, invHeight * viewport.height));
} }
inline void CameraComponent::SetZFar(float zFar) inline void CameraComponent::SetZFar(float zFar)
@ -187,7 +193,7 @@ namespace Ndk
inline void CameraComponent::SetZNear(float zNear) inline void CameraComponent::SetZNear(float zNear)
{ {
NazaraAssert(!NzNumberEquals(zNear, 0.f), "zNear cannot be zero"); NazaraAssert(!Nz::NumberEquals(zNear, 0.f), "zNear cannot be zero");
m_zNear = zNear; m_zNear = zNear;
InvalidateProjectionMatrix(); InvalidateProjectionMatrix();

View File

@ -11,7 +11,10 @@
#include <NDK/Component.hpp> #include <NDK/Component.hpp>
#include <memory> #include <memory>
class NzPhysObject; namespace Nz
{
class PhysObject;
}
namespace Ndk namespace Ndk
{ {
@ -23,30 +26,30 @@ namespace Ndk
friend class StaticCollisionSystem; friend class StaticCollisionSystem;
public: public:
CollisionComponent(NzPhysGeomRef geom = NzPhysGeomRef()); CollisionComponent(Nz::PhysGeomRef geom = Nz::PhysGeomRef());
CollisionComponent(const CollisionComponent& collision); CollisionComponent(const CollisionComponent& collision);
~CollisionComponent() = default; ~CollisionComponent() = default;
const NzPhysGeomRef& GetGeom() const; const Nz::PhysGeomRef& GetGeom() const;
void SetGeom(NzPhysGeomRef geom); void SetGeom(Nz::PhysGeomRef geom);
CollisionComponent& operator=(NzPhysGeomRef geom); CollisionComponent& operator=(Nz::PhysGeomRef geom);
CollisionComponent& operator=(CollisionComponent&& collision) = default; CollisionComponent& operator=(CollisionComponent&& collision) = default;
static ComponentIndex componentIndex; static ComponentIndex componentIndex;
private: private:
void InitializeStaticBody(); void InitializeStaticBody();
NzPhysObject* GetStaticBody(); Nz::PhysObject* GetStaticBody();
void OnAttached() override; void OnAttached() override;
void OnComponentAttached(BaseComponent& component) override; void OnComponentAttached(BaseComponent& component) override;
void OnComponentDetached(BaseComponent& component) override; void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override; void OnDetached() override;
std::unique_ptr<NzPhysObject> m_staticBody; std::unique_ptr<Nz::PhysObject> m_staticBody;
NzPhysGeomRef m_geom; Nz::PhysGeomRef m_geom;
bool m_bodyUpdated; bool m_bodyUpdated;
}; };
} }

View File

@ -9,7 +9,7 @@
namespace Ndk namespace Ndk
{ {
inline CollisionComponent::CollisionComponent(NzPhysGeomRef geom) : inline CollisionComponent::CollisionComponent(Nz::PhysGeomRef geom) :
m_geom(std::move(geom)), m_geom(std::move(geom)),
m_bodyUpdated(false) m_bodyUpdated(false)
{ {
@ -21,19 +21,19 @@ namespace Ndk
{ {
} }
inline const NzPhysGeomRef& CollisionComponent::GetGeom() const inline const Nz::PhysGeomRef& CollisionComponent::GetGeom() const
{ {
return m_geom; return m_geom;
} }
inline CollisionComponent& CollisionComponent::operator=(NzPhysGeomRef geom) inline CollisionComponent& CollisionComponent::operator=(Nz::PhysGeomRef geom)
{ {
SetGeom(geom); SetGeom(geom);
return *this; return *this;
} }
inline NzPhysObject* CollisionComponent::GetStaticBody() inline Nz::PhysObject* CollisionComponent::GetStaticBody()
{ {
return m_staticBody.get(); return m_staticBody.get();
} }

View File

@ -22,16 +22,16 @@ namespace Ndk
inline GraphicsComponent(const GraphicsComponent& graphicsComponent); inline GraphicsComponent(const GraphicsComponent& graphicsComponent);
~GraphicsComponent() = default; ~GraphicsComponent() = default;
inline void AddToRenderQueue(NzAbstractRenderQueue* renderQueue) const; inline void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const;
inline void Attach(NzInstancedRenderableRef renderable); inline void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0);
inline void EnsureTransformMatrixUpdate() const; inline void EnsureTransformMatrixUpdate() const;
static ComponentIndex componentIndex; static ComponentIndex componentIndex;
private: private:
void InvalidateRenderableData(const NzInstancedRenderable* renderable, nzUInt32 flags, unsigned int index); void InvalidateRenderableData(const Nz::InstancedRenderable* renderable, Nz::UInt32 flags, unsigned int index);
inline void InvalidateRenderables(); inline void InvalidateRenderables();
inline void InvalidateTransformMatrix(); inline void InvalidateTransformMatrix();
@ -39,29 +39,29 @@ namespace Ndk
void OnComponentAttached(BaseComponent& component) override; void OnComponentAttached(BaseComponent& component) override;
void OnComponentDetached(BaseComponent& component) override; void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override; void OnDetached() override;
void OnNodeInvalidated(const NzNode* node); void OnNodeInvalidated(const Nz::Node* node);
void UpdateTransformMatrix() const; void UpdateTransformMatrix() const;
NazaraSlot(NzNode, OnNodeInvalidation, m_nodeInvalidationSlot); NazaraSlot(Nz::Node, OnNodeInvalidation, m_nodeInvalidationSlot);
struct Renderable struct Renderable
{ {
Renderable(NzMatrix4f& transformMatrix) : Renderable(Nz::Matrix4f& transformMatrix) :
data(transformMatrix), data(transformMatrix),
dataUpdated(false) dataUpdated(false)
{ {
} }
NazaraSlot(NzInstancedRenderable, OnInstancedRenderableInvalidateData, renderableInvalidationSlot); NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateData, renderableInvalidationSlot);
mutable NzInstancedRenderable::InstanceData data; mutable Nz::InstancedRenderable::InstanceData data;
NzInstancedRenderableRef renderable; Nz::InstancedRenderableRef renderable;
mutable bool dataUpdated; mutable bool dataUpdated;
}; };
std::vector<Renderable> m_renderables; std::vector<Renderable> m_renderables;
mutable NzMatrix4f m_transformMatrix; mutable Nz::Matrix4f m_transformMatrix;
mutable bool m_transformMatrixUpdated; mutable bool m_transformMatrixUpdated;
}; };
} }

View File

@ -13,10 +13,10 @@ namespace Ndk
{ {
m_renderables.reserve(graphicsComponent.m_renderables.size()); m_renderables.reserve(graphicsComponent.m_renderables.size());
for (const Renderable& r : graphicsComponent.m_renderables) for (const Renderable& r : graphicsComponent.m_renderables)
Attach(r.renderable); Attach(r.renderable, r.data.renderOrder);
} }
inline void GraphicsComponent::AddToRenderQueue(NzAbstractRenderQueue* renderQueue) const inline void GraphicsComponent::AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const
{ {
EnsureTransformMatrixUpdate(); EnsureTransformMatrixUpdate();
@ -32,10 +32,11 @@ namespace Ndk
} }
} }
inline void GraphicsComponent::Attach(NzInstancedRenderableRef renderable) inline void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, int renderOrder)
{ {
m_renderables.emplace_back(m_transformMatrix); m_renderables.emplace_back(m_transformMatrix);
Renderable& r = m_renderables.back(); Renderable& r = m_renderables.back();
r.data.renderOrder = renderOrder;
r.renderable = std::move(renderable); r.renderable = std::move(renderable);
r.renderableInvalidationSlot.Connect(r.renderable->OnInstancedRenderableInvalidateData, std::bind(&GraphicsComponent::InvalidateRenderableData, this, std::placeholders::_1, std::placeholders::_2, m_renderables.size()-1)); r.renderableInvalidationSlot.Connect(r.renderable->OnInstancedRenderableInvalidateData, std::bind(&GraphicsComponent::InvalidateRenderableData, this, std::placeholders::_1, std::placeholders::_2, m_renderables.size()-1));
} }

View File

@ -12,10 +12,10 @@
namespace Ndk namespace Ndk
{ {
class NDK_API LightComponent : public Component<LightComponent>, public NzLight class NDK_API LightComponent : public Component<LightComponent>, public Nz::Light
{ {
public: public:
inline LightComponent(nzLightType lightType = nzLightType_Point); inline LightComponent(Nz::LightType lightType = Nz::LightType_Point);
LightComponent(const LightComponent& light) = default; LightComponent(const LightComponent& light) = default;
~LightComponent() = default; ~LightComponent() = default;

View File

@ -4,8 +4,8 @@
namespace Ndk namespace Ndk
{ {
inline LightComponent::LightComponent(nzLightType lightType) : inline LightComponent::LightComponent(Nz::LightType lightType) :
NzLight(lightType) Nz::Light(lightType)
{ {
} }
} }

View File

@ -14,14 +14,14 @@ namespace Ndk
{ {
class Entity; class Entity;
class NDK_API NodeComponent : public Component<NodeComponent>, public NzNode class NDK_API NodeComponent : public Component<NodeComponent>, public Nz::Node
{ {
public: public:
NodeComponent() = default; NodeComponent() = default;
~NodeComponent() = default; ~NodeComponent() = default;
void SetParent(Entity* entity, bool keepDerived = false); void SetParent(Entity* entity, bool keepDerived = false);
using NzNode::SetParent; using Nz::Node::SetParent;
static ComponentIndex componentIndex; static ComponentIndex componentIndex;
}; };

View File

@ -13,9 +13,9 @@ namespace Ndk
{ {
NazaraAssert(entity->HasComponent<NodeComponent>(), "Entity must have a NodeComponent"); NazaraAssert(entity->HasComponent<NodeComponent>(), "Entity must have a NodeComponent");
NzNode::SetParent(entity->GetComponent<NodeComponent>(), keepDerived); Nz::Node::SetParent(entity->GetComponent<NodeComponent>(), keepDerived);
} }
else else
NzNode::SetParent(nullptr, keepDerived); Nz::Node::SetParent(nullptr, keepDerived);
} }
} }

View File

@ -25,45 +25,45 @@ namespace Ndk
PhysicsComponent(const PhysicsComponent& physics); PhysicsComponent(const PhysicsComponent& physics);
~PhysicsComponent() = default; ~PhysicsComponent() = default;
void AddForce(const NzVector3f& force, nzCoordSys coordSys = nzCoordSys_Global); void AddForce(const Nz::Vector3f& force, Nz::CoordSys coordSys = Nz::CoordSys_Global);
void AddForce(const NzVector3f& force, const NzVector3f& point, nzCoordSys coordSys = nzCoordSys_Global); void AddForce(const Nz::Vector3f& force, const Nz::Vector3f& point, Nz::CoordSys coordSys = Nz::CoordSys_Global);
void AddTorque(const NzVector3f& torque, nzCoordSys coordSys = nzCoordSys_Global); void AddTorque(const Nz::Vector3f& torque, Nz::CoordSys coordSys = Nz::CoordSys_Global);
void EnableAutoSleep(bool autoSleep); void EnableAutoSleep(bool autoSleep);
NzBoxf GetAABB() const; Nz::Boxf GetAABB() const;
NzVector3f GetAngularVelocity() const; Nz::Vector3f GetAngularVelocity() const;
float GetGravityFactor() const; float GetGravityFactor() const;
float GetMass() const; float GetMass() const;
NzVector3f GetMassCenter(nzCoordSys coordSys = nzCoordSys_Local) const; Nz::Vector3f GetMassCenter(Nz::CoordSys coordSys = Nz::CoordSys_Local) const;
const NzMatrix4f& GetMatrix() const; const Nz::Matrix4f& GetMatrix() const;
NzVector3f GetPosition() const; Nz::Vector3f GetPosition() const;
NzQuaternionf GetRotation() const; Nz::Quaternionf GetRotation() const;
NzVector3f GetVelocity() const; Nz::Vector3f GetVelocity() const;
bool IsAutoSleepEnabled() const; bool IsAutoSleepEnabled() const;
bool IsMoveable() const; bool IsMoveable() const;
bool IsSleeping() const; bool IsSleeping() const;
void SetAngularVelocity(const NzVector3f& angularVelocity); void SetAngularVelocity(const Nz::Vector3f& angularVelocity);
void SetGravityFactor(float gravityFactor); void SetGravityFactor(float gravityFactor);
void SetMass(float mass); void SetMass(float mass);
void SetMassCenter(const NzVector3f& center); void SetMassCenter(const Nz::Vector3f& center);
void SetPosition(const NzVector3f& position); void SetPosition(const Nz::Vector3f& position);
void SetRotation(const NzQuaternionf& rotation); void SetRotation(const Nz::Quaternionf& rotation);
void SetVelocity(const NzVector3f& velocity); void SetVelocity(const Nz::Vector3f& velocity);
static ComponentIndex componentIndex; static ComponentIndex componentIndex;
private: private:
NzPhysObject& GetPhysObject(); Nz::PhysObject& GetPhysObject();
void OnAttached() override; void OnAttached() override;
void OnComponentAttached(BaseComponent& component) override; void OnComponentAttached(BaseComponent& component) override;
void OnComponentDetached(BaseComponent& component) override; void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override; void OnDetached() override;
std::unique_ptr<NzPhysObject> m_object; std::unique_ptr<Nz::PhysObject> m_object;
}; };
} }

View File

@ -12,21 +12,21 @@ namespace Ndk
NazaraUnused(physics); NazaraUnused(physics);
} }
inline void PhysicsComponent::AddForce(const NzVector3f& force, nzCoordSys coordSys) inline void PhysicsComponent::AddForce(const Nz::Vector3f& force, Nz::CoordSys coordSys)
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
m_object->AddForce(force, coordSys); m_object->AddForce(force, coordSys);
} }
inline void PhysicsComponent::AddForce(const NzVector3f& force, const NzVector3f& point, nzCoordSys coordSys) inline void PhysicsComponent::AddForce(const Nz::Vector3f& force, const Nz::Vector3f& point, Nz::CoordSys coordSys)
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
m_object->AddForce(force, point, coordSys); m_object->AddForce(force, point, coordSys);
} }
inline void PhysicsComponent::AddTorque(const NzVector3f& torque, nzCoordSys coordSys) inline void PhysicsComponent::AddTorque(const Nz::Vector3f& torque, Nz::CoordSys coordSys)
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
@ -40,14 +40,14 @@ namespace Ndk
m_object->EnableAutoSleep(autoSleep); m_object->EnableAutoSleep(autoSleep);
} }
inline NzBoxf PhysicsComponent::GetAABB() const inline Nz::Boxf PhysicsComponent::GetAABB() const
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
return m_object->GetAABB(); return m_object->GetAABB();
} }
inline NzVector3f PhysicsComponent::GetAngularVelocity() const inline Nz::Vector3f PhysicsComponent::GetAngularVelocity() const
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
@ -68,35 +68,35 @@ namespace Ndk
return m_object->GetMass(); return m_object->GetMass();
} }
inline NzVector3f PhysicsComponent::GetMassCenter(nzCoordSys coordSys) const inline Nz::Vector3f PhysicsComponent::GetMassCenter(Nz::CoordSys coordSys) const
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
return m_object->GetMassCenter(coordSys); return m_object->GetMassCenter(coordSys);
} }
inline const NzMatrix4f& PhysicsComponent::GetMatrix() const inline const Nz::Matrix4f& PhysicsComponent::GetMatrix() const
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
return m_object->GetMatrix(); return m_object->GetMatrix();
} }
inline NzVector3f PhysicsComponent::GetPosition() const inline Nz::Vector3f PhysicsComponent::GetPosition() const
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
return m_object->GetPosition(); return m_object->GetPosition();
} }
inline NzQuaternionf PhysicsComponent::GetRotation() const inline Nz::Quaternionf PhysicsComponent::GetRotation() const
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
return m_object->GetRotation(); return m_object->GetRotation();
} }
inline NzVector3f PhysicsComponent::GetVelocity() const inline Nz::Vector3f PhysicsComponent::GetVelocity() const
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
@ -117,7 +117,7 @@ namespace Ndk
return m_object->IsSleeping(); return m_object->IsSleeping();
} }
inline void PhysicsComponent::SetAngularVelocity(const NzVector3f& angularVelocity) inline void PhysicsComponent::SetAngularVelocity(const Nz::Vector3f& angularVelocity)
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
@ -139,35 +139,35 @@ namespace Ndk
m_object->SetMass(mass); m_object->SetMass(mass);
} }
inline void PhysicsComponent::SetMassCenter(const NzVector3f& center) inline void PhysicsComponent::SetMassCenter(const Nz::Vector3f& center)
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
m_object->SetMassCenter(center); m_object->SetMassCenter(center);
} }
inline void PhysicsComponent::SetPosition(const NzVector3f& position) inline void PhysicsComponent::SetPosition(const Nz::Vector3f& position)
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
m_object->SetPosition(position); m_object->SetPosition(position);
} }
inline void PhysicsComponent::SetRotation(const NzQuaternionf& rotation) inline void PhysicsComponent::SetRotation(const Nz::Quaternionf& rotation)
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
m_object->SetRotation(rotation); m_object->SetRotation(rotation);
} }
inline void PhysicsComponent::SetVelocity(const NzVector3f& velocity) inline void PhysicsComponent::SetVelocity(const Nz::Vector3f& velocity)
{ {
NazaraAssert(m_object, "Invalid physics object"); NazaraAssert(m_object, "Invalid physics object");
m_object->SetVelocity(velocity); m_object->SetVelocity(velocity);
} }
inline NzPhysObject& PhysicsComponent::GetPhysObject() inline Nz::PhysObject& PhysicsComponent::GetPhysObject()
{ {
return *m_object.get(); return *m_object.get();
} }

View File

@ -17,12 +17,12 @@ namespace Ndk
class NDK_API VelocityComponent : public Component<VelocityComponent> class NDK_API VelocityComponent : public Component<VelocityComponent>
{ {
public: public:
VelocityComponent(const NzVector3f& velocity = NzVector3f::Zero()); VelocityComponent(const Nz::Vector3f& velocity = Nz::Vector3f::Zero());
~VelocityComponent() = default; ~VelocityComponent() = default;
NzVector3f linearVelocity; Nz::Vector3f linearVelocity;
VelocityComponent& operator=(const NzVector3f& vel); VelocityComponent& operator=(const Nz::Vector3f& vel);
static ComponentIndex componentIndex; static ComponentIndex componentIndex;
}; };

View File

@ -7,12 +7,12 @@
namespace Ndk namespace Ndk
{ {
inline VelocityComponent::VelocityComponent(const NzVector3f& velocity) : inline VelocityComponent::VelocityComponent(const Nz::Vector3f& velocity) :
linearVelocity(velocity) linearVelocity(velocity)
{ {
} }
inline VelocityComponent& VelocityComponent::operator=(const NzVector3f& vel) inline VelocityComponent& VelocityComponent::operator=(const Nz::Vector3f& vel)
{ {
linearVelocity = vel; linearVelocity = vel;
return *this; return *this;

View File

@ -36,9 +36,9 @@ namespace Ndk
inline BaseComponent& GetComponent(ComponentIndex index); inline BaseComponent& GetComponent(ComponentIndex index);
template<typename ComponentType> ComponentType& GetComponent(); template<typename ComponentType> ComponentType& GetComponent();
inline const NzBitset<>& GetComponentBits() const; inline const Nz::Bitset<>& GetComponentBits() const;
inline EntityId GetId() const; inline EntityId GetId() const;
inline const NzBitset<>& GetSystemBits() const; inline const Nz::Bitset<>& GetSystemBits() const;
inline World* GetWorld() const; inline World* GetWorld() const;
inline bool HasComponent(ComponentIndex index) const; inline bool HasComponent(ComponentIndex index) const;
@ -69,9 +69,9 @@ namespace Ndk
std::vector<std::unique_ptr<BaseComponent>> m_components; std::vector<std::unique_ptr<BaseComponent>> m_components;
std::vector<EntityHandle*> m_handles; std::vector<EntityHandle*> m_handles;
Nz::Bitset<> m_componentBits;
Nz::Bitset<> m_systemBits;
EntityId m_id; EntityId m_id;
NzBitset<> m_componentBits;
NzBitset<> m_systemBits;
World* m_world; World* m_world;
bool m_valid; bool m_valid;
}; };

View File

@ -40,7 +40,7 @@ namespace Ndk
return static_cast<ComponentType&>(GetComponent(index)); return static_cast<ComponentType&>(GetComponent(index));
} }
inline const NzBitset<>& Entity::GetComponentBits() const inline const Nz::Bitset<>& Entity::GetComponentBits() const
{ {
return m_componentBits; return m_componentBits;
} }
@ -50,7 +50,7 @@ namespace Ndk
return m_id; return m_id;
} }
inline const NzBitset<>& Entity::GetSystemBits() const inline const Nz::Bitset<>& Entity::GetSystemBits() const
{ {
return m_systemBits; return m_systemBits;
} }

View File

@ -33,7 +33,7 @@ namespace Ndk
EntityHandle& Swap(EntityHandle& handle); EntityHandle& Swap(EntityHandle& handle);
NzString ToString() const; Nz::String ToString() const;
operator bool() const; operator bool() const;
operator Entity*() const; operator Entity*() const;

View File

@ -90,9 +90,9 @@ namespace Ndk
return *this; return *this;
} }
inline NzString EntityHandle::ToString() const inline Nz::String EntityHandle::ToString() const
{ {
NzStringStream ss; Nz::StringStream ss;
ss << "EntityHandle("; ss << "EntityHandle(";
if (IsValid()) if (IsValid())
ss << "Entity(" << m_entity->GetId() << ')'; ss << "Entity(" << m_entity->GetId() << ')';
@ -260,9 +260,9 @@ namespace Ndk
namespace std namespace std
{ {
template<> template<>
struct hash<Ndk::EntityHandle> struct hash<Ndk::EntityHandle>
{ {
size_t operator()(const Ndk::EntityHandle& handle) const size_t operator()(const Ndk::EntityHandle& handle) const
{ {
// Hasher le pointeur fonctionnerait jusqu'à ce que l'entité soit mise à jour et déplacée // Hasher le pointeur fonctionnerait jusqu'à ce que l'entité soit mise à jour et déplacée
@ -271,9 +271,9 @@ namespace std
return hash<Ndk::EntityId>()(id); return hash<Ndk::EntityId>()(id);
} }
}; };
inline void swap(Ndk::EntityHandle& lhs, Ndk::EntityHandle& rhs) inline void swap(Ndk::EntityHandle& lhs, Ndk::EntityHandle& rhs)
{ {
lhs.Swap(rhs); lhs.Swap(rhs);
} }

View File

@ -54,7 +54,7 @@ namespace Ndk
private: private:
std::vector<EntityHandle> m_entities; std::vector<EntityHandle> m_entities;
NzBitset<nzUInt64> m_entityBits; Nz::Bitset<Nz::UInt64> m_entityBits;
}; };
} }

View File

@ -44,7 +44,7 @@ namespace Ndk
} }
} }
// Interface STD // Nz::Interface STD
inline EntityList::Container::iterator EntityList::begin() inline EntityList::Container::iterator EntityList::begin()
{ {
return m_entities.begin(); return m_entities.begin();

View File

@ -57,10 +57,10 @@
namespace Ndk namespace Ndk
{ {
using ComponentId = nzUInt64; using ComponentId = Nz::UInt64;
using ComponentIndex = nzUInt32; using ComponentIndex = Nz::UInt32;
using EntityId = nzUInt32; using EntityId = Nz::UInt32;
using SystemIndex = nzUInt32; using SystemIndex = Nz::UInt32;
} }
#endif // NDK_PREREQUESITES_HPP #endif // NDK_PREREQUESITES_HPP

View File

@ -20,8 +20,8 @@ namespace Ndk
PhysicsSystem(const PhysicsSystem& system); PhysicsSystem(const PhysicsSystem& system);
~PhysicsSystem() = default; ~PhysicsSystem() = default;
NzPhysWorld& GetWorld(); Nz::PhysWorld& GetWorld();
const NzPhysWorld& GetWorld() const; const Nz::PhysWorld& GetWorld() const;
static SystemIndex systemIndex; static SystemIndex systemIndex;
@ -31,7 +31,7 @@ namespace Ndk
EntityList m_dynamicObjects; EntityList m_dynamicObjects;
EntityList m_staticObjects; EntityList m_staticObjects;
NzPhysWorld m_world; Nz::PhysWorld m_world;
}; };
} }

View File

@ -4,12 +4,12 @@
namespace Ndk namespace Ndk
{ {
inline NzPhysWorld& PhysicsSystem::GetWorld() inline Nz::PhysWorld& PhysicsSystem::GetWorld()
{ {
return m_world; return m_world;
} }
inline const NzPhysWorld& PhysicsSystem::GetWorld() const inline const Nz::PhysWorld& PhysicsSystem::GetWorld() const
{ {
return m_world; return m_world;
} }

View File

@ -27,16 +27,16 @@ namespace Ndk
inline RenderSystem(const RenderSystem& renderSystem); inline RenderSystem(const RenderSystem& renderSystem);
~RenderSystem() = default; ~RenderSystem() = default;
inline const NzBackgroundRef& GetDefaultBackground() const; inline const Nz::BackgroundRef& GetDefaultBackground() const;
inline const NzMatrix4f& GetCoordinateSystemMatrix() const; inline const Nz::Matrix4f& GetCoordinateSystemMatrix() const;
inline NzVector3f GetGlobalForward() const; inline Nz::Vector3f GetGlobalForward() const;
inline NzVector3f GetGlobalRight() const; inline Nz::Vector3f GetGlobalRight() const;
inline NzVector3f GetGlobalUp() const; inline Nz::Vector3f GetGlobalUp() const;
inline void SetDefaultBackground(NzBackgroundRef background); inline void SetDefaultBackground(Nz::BackgroundRef background);
inline void SetGlobalForward(const NzVector3f& direction); inline void SetGlobalForward(const Nz::Vector3f& direction);
inline void SetGlobalRight(const NzVector3f& direction); inline void SetGlobalRight(const Nz::Vector3f& direction);
inline void SetGlobalUp(const NzVector3f& direction); inline void SetGlobalUp(const Nz::Vector3f& direction);
static SystemIndex systemIndex; static SystemIndex systemIndex;
@ -46,7 +46,7 @@ namespace Ndk
void OnEntityRemoved(Entity* entity) override; void OnEntityRemoved(Entity* entity) override;
void OnEntityValidation(Entity* entity, bool justAdded) override; void OnEntityValidation(Entity* entity, bool justAdded) override;
void OnUpdate(float elapsedTime) override; void OnUpdate(float elapsedTime) override;
void UpdateDirectionalShadowMaps(const NzAbstractViewer& viewer); void UpdateDirectionalShadowMaps(const Nz::AbstractViewer& viewer);
void UpdatePointSpotShadowMaps(); void UpdatePointSpotShadowMaps();
EntityList m_cameras; EntityList m_cameras;
@ -54,11 +54,11 @@ namespace Ndk
EntityList m_directionalLights; EntityList m_directionalLights;
EntityList m_lights; EntityList m_lights;
EntityList m_pointSpotLights; EntityList m_pointSpotLights;
NzBackgroundRef m_background; Nz::BackgroundRef m_background;
NzDepthRenderTechnique m_shadowTechnique; Nz::DepthRenderTechnique m_shadowTechnique;
NzForwardRenderTechnique m_renderTechnique; Nz::ForwardRenderTechnique m_renderTechnique;
NzMatrix4f m_coordinateSystemMatrix; Nz::Matrix4f m_coordinateSystemMatrix;
NzRenderTexture m_shadowRT; Nz::RenderTexture m_shadowRT;
bool m_coordinateSystemInvalidated; bool m_coordinateSystemInvalidated;
}; };
} }

View File

@ -9,37 +9,37 @@ namespace Ndk
{ {
} }
inline const NzBackgroundRef& RenderSystem::GetDefaultBackground() const inline const Nz::BackgroundRef& RenderSystem::GetDefaultBackground() const
{ {
return m_background; return m_background;
} }
inline const NzMatrix4f& RenderSystem::GetCoordinateSystemMatrix() const inline const Nz::Matrix4f& RenderSystem::GetCoordinateSystemMatrix() const
{ {
return m_coordinateSystemMatrix; return m_coordinateSystemMatrix;
} }
inline NzVector3f RenderSystem::GetGlobalForward() const inline Nz::Vector3f RenderSystem::GetGlobalForward() const
{ {
return NzVector3f(-m_coordinateSystemMatrix.m13, -m_coordinateSystemMatrix.m23, -m_coordinateSystemMatrix.m33); return Nz::Vector3f(-m_coordinateSystemMatrix.m13, -m_coordinateSystemMatrix.m23, -m_coordinateSystemMatrix.m33);
} }
inline NzVector3f RenderSystem::GetGlobalRight() const inline Nz::Vector3f RenderSystem::GetGlobalRight() const
{ {
return NzVector3f(m_coordinateSystemMatrix.m11, m_coordinateSystemMatrix.m21, m_coordinateSystemMatrix.m31); return Nz::Vector3f(m_coordinateSystemMatrix.m11, m_coordinateSystemMatrix.m21, m_coordinateSystemMatrix.m31);
} }
inline NzVector3f RenderSystem::GetGlobalUp() const inline Nz::Vector3f RenderSystem::GetGlobalUp() const
{ {
return NzVector3f(m_coordinateSystemMatrix.m12, m_coordinateSystemMatrix.m22, m_coordinateSystemMatrix.m32); return Nz::Vector3f(m_coordinateSystemMatrix.m12, m_coordinateSystemMatrix.m22, m_coordinateSystemMatrix.m32);
} }
inline void RenderSystem::SetDefaultBackground(NzBackgroundRef background) inline void RenderSystem::SetDefaultBackground(Nz::BackgroundRef background)
{ {
m_background = std::move(background); m_background = std::move(background);
} }
inline void RenderSystem::SetGlobalForward(const NzVector3f& direction) inline void RenderSystem::SetGlobalForward(const Nz::Vector3f& direction)
{ {
m_coordinateSystemMatrix.m13 = -direction.x; m_coordinateSystemMatrix.m13 = -direction.x;
m_coordinateSystemMatrix.m23 = -direction.y; m_coordinateSystemMatrix.m23 = -direction.y;
@ -48,7 +48,7 @@ namespace Ndk
InvalidateCoordinateSystem(); InvalidateCoordinateSystem();
} }
inline void RenderSystem::SetGlobalRight(const NzVector3f& direction) inline void RenderSystem::SetGlobalRight(const Nz::Vector3f& direction)
{ {
m_coordinateSystemMatrix.m11 = direction.x; m_coordinateSystemMatrix.m11 = direction.x;
m_coordinateSystemMatrix.m21 = direction.y; m_coordinateSystemMatrix.m21 = direction.y;
@ -57,7 +57,7 @@ namespace Ndk
InvalidateCoordinateSystem(); InvalidateCoordinateSystem();
} }
inline void RenderSystem::SetGlobalUp(const NzVector3f& direction) inline void RenderSystem::SetGlobalUp(const Nz::Vector3f& direction)
{ {
m_coordinateSystemMatrix.m12 = direction.x; m_coordinateSystemMatrix.m12 = direction.x;
m_coordinateSystemMatrix.m22 = direction.y; m_coordinateSystemMatrix.m22 = direction.y;

View File

@ -8,7 +8,6 @@
#define NDK_WORLD_HPP #define NDK_WORLD_HPP
#include <Nazara/Core/Bitset.hpp> #include <Nazara/Core/Bitset.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <NDK/Entity.hpp> #include <NDK/Entity.hpp>
#include <NDK/EntityHandle.hpp> #include <NDK/EntityHandle.hpp>
#include <NDK/System.hpp> #include <NDK/System.hpp>
@ -19,7 +18,7 @@
namespace Ndk namespace Ndk
{ {
class NDK_API World : NzNonCopyable class NDK_API World
{ {
friend Entity; friend Entity;
@ -27,6 +26,8 @@ namespace Ndk
using EntityList = std::vector<EntityHandle>; using EntityList = std::vector<EntityHandle>;
inline World(bool addDefaultSystems = true); inline World(bool addDefaultSystems = true);
World(const World&) = delete;
World(World&&) = delete; ///TODO
~World(); ~World();
void AddDefaultSystems(); void AddDefaultSystems();
@ -60,6 +61,9 @@ namespace Ndk
void Update(); void Update();
inline void Update(float elapsedTime); inline void Update(float elapsedTime);
World& operator=(const World&) = delete;
World& operator=(World&&) = delete; ///TODO
private: private:
inline void Invalidate(); inline void Invalidate();
inline void Invalidate(EntityId id); inline void Invalidate(EntityId id);
@ -81,8 +85,8 @@ namespace Ndk
std::vector<EntityBlock> m_entities; std::vector<EntityBlock> m_entities;
std::vector<EntityId> m_freeIdList; std::vector<EntityId> m_freeIdList;
EntityList m_aliveEntities; EntityList m_aliveEntities;
NzBitset<nzUInt64> m_dirtyEntities; Nz::Bitset<Nz::UInt64> m_dirtyEntities;
NzBitset<nzUInt64> m_killedEntities; Nz::Bitset<Nz::UInt64> m_killedEntities;
}; };
} }

View File

@ -136,7 +136,10 @@ namespace Ndk
// And then update systems // And then update systems
for (auto& systemPtr : m_systems) for (auto& systemPtr : m_systems)
systemPtr->Update(elapsedTime); {
if (systemPtr)
systemPtr->Update(elapsedTime);
}
} }
inline void World::Invalidate() inline void World::Invalidate()

View File

@ -17,15 +17,15 @@ namespace Ndk
if (!entity) if (!entity)
return false; return false;
const NzBitset<>& components = entity->GetComponentBits(); const Nz::Bitset<>& components = entity->GetComponentBits();
m_filterResult.PerformsAND(m_requiredComponents, components); m_filterResult.PerformsAND(m_requiredComponents, components);
if (m_filterResult != m_requiredComponents) if (m_filterResult != m_requiredComponents)
return false; // Au moins un component requis n'est pas présent return false; // Au moins un component requis n'est pas présent
m_filterResult.PerformsAND(m_excludedComponents, components); m_filterResult.PerformsAND(m_excludedComponents, components);
if (m_filterResult.TestAny()) if (m_filterResult.TestAny())
return false; // Au moins un component exclu est présent return false; // Au moins un component exclu est présent
// Si nous avons une liste de composants nécessaires // Si nous avons une liste de composants nécessaires
if (m_requiredAnyComponents.TestAny()) if (m_requiredAnyComponents.TestAny())
@ -34,7 +34,7 @@ namespace Ndk
return false; return false;
} }
return true; return true;
} }
void BaseSystem::OnEntityAdded(Entity* entity) void BaseSystem::OnEntityAdded(Entity* entity)

View File

@ -17,20 +17,20 @@ namespace Ndk
EnsureViewMatrixUpdate(); EnsureViewMatrixUpdate();
EnsureViewportUpdate(); EnsureViewportUpdate();
NzRenderer::SetMatrix(nzMatrixType_Projection, m_projectionMatrix); Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, m_projectionMatrix);
NzRenderer::SetMatrix(nzMatrixType_View, m_viewMatrix); Nz::Renderer::SetMatrix(Nz::MatrixType_View, m_viewMatrix);
NzRenderer::SetTarget(m_target); Nz::Renderer::SetTarget(m_target);
NzRenderer::SetViewport(m_viewport); Nz::Renderer::SetViewport(m_viewport);
} }
NzVector3f CameraComponent::GetEyePosition() const Nz::Vector3f CameraComponent::GetEyePosition() const
{ {
NazaraAssert(m_entity && m_entity->HasComponent<NodeComponent>(), "CameraComponent requires NodeComponent"); NazaraAssert(m_entity && m_entity->HasComponent<NodeComponent>(), "CameraComponent requires NodeComponent");
return m_entity->GetComponent<NodeComponent>().GetPosition(); return m_entity->GetComponent<NodeComponent>().GetPosition();
} }
NzVector3f CameraComponent::GetForward() const Nz::Vector3f CameraComponent::GetForward() const
{ {
NazaraAssert(m_entity && m_entity->HasComponent<NodeComponent>(), "CameraComponent requires NodeComponent"); NazaraAssert(m_entity && m_entity->HasComponent<NodeComponent>(), "CameraComponent requires NodeComponent");
@ -80,7 +80,7 @@ namespace Ndk
InvalidateViewMatrix(); InvalidateViewMatrix();
} }
void CameraComponent::OnNodeInvalidated(const NzNode* node) void CameraComponent::OnNodeInvalidated(const Nz::Node* node)
{ {
NazaraUnused(node); NazaraUnused(node);
@ -88,20 +88,20 @@ namespace Ndk
InvalidateViewMatrix(); InvalidateViewMatrix();
} }
void CameraComponent::OnRenderTargetRelease(const NzRenderTarget* renderTarget) void CameraComponent::OnRenderTargetRelease(const Nz::RenderTarget* renderTarget)
{ {
if (renderTarget == m_target) if (renderTarget == m_target)
m_target = nullptr; m_target = nullptr;
else else
NazaraInternalError("Not listening to " + NzString::Pointer(renderTarget)); NazaraInternalError("Not listening to " + Nz::String::Pointer(renderTarget));
} }
void CameraComponent::OnRenderTargetSizeChange(const NzRenderTarget* renderTarget) void CameraComponent::OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget)
{ {
if (renderTarget == m_target) if (renderTarget == m_target)
InvalidateViewport(); InvalidateViewport();
else else
NazaraInternalError("Not listening to " + NzString::Pointer(renderTarget)); NazaraInternalError("Not listening to " + Nz::String::Pointer(renderTarget));
} }
void CameraComponent::UpdateFrustum() const void CameraComponent::UpdateFrustum() const
@ -118,13 +118,13 @@ namespace Ndk
{ {
switch (m_projectionType) switch (m_projectionType)
{ {
case nzProjectionType_Orthogonal: case Nz::ProjectionType_Orthogonal:
EnsureViewportUpdate(); EnsureViewportUpdate();
m_projectionMatrix.MakeOrtho(0.f, static_cast<float>(m_viewport.width), 0.f, static_cast<float>(m_viewport.height), m_zNear, m_zFar); m_projectionMatrix.MakeOrtho(0.f, static_cast<float>(m_viewport.width), 0.f, static_cast<float>(m_viewport.height), m_zNear, m_zFar);
break; break;
case nzProjectionType_Perspective: case Nz::ProjectionType_Perspective:
EnsureViewportUpdate(); // Can affect aspect ratio EnsureViewportUpdate(); // Can affect aspect ratio
m_projectionMatrix.MakePerspective(m_fov, m_aspectRatio, m_zNear, m_zFar); m_projectionMatrix.MakePerspective(m_fov, m_aspectRatio, m_zNear, m_zFar);
@ -141,7 +141,7 @@ namespace Ndk
NodeComponent& nodeComponent = m_entity->GetComponent<NodeComponent>(); NodeComponent& nodeComponent = m_entity->GetComponent<NodeComponent>();
// Build the view matrix using the NodeComponent position/rotation // Build the view matrix using the NodeComponent position/rotation
m_viewMatrix.MakeViewMatrix(nodeComponent.GetPosition(nzCoordSys_Global), nodeComponent.GetRotation(nzCoordSys_Global)); m_viewMatrix.MakeViewMatrix(nodeComponent.GetPosition(Nz::CoordSys_Global), nodeComponent.GetRotation(Nz::CoordSys_Global));
m_viewMatrixUpdated = true; m_viewMatrixUpdated = true;
} }
@ -153,7 +153,7 @@ namespace Ndk
unsigned int targetHeight = std::max(m_target->GetHeight(), 1U); // Let's make sure we won't divide by zero unsigned int targetHeight = std::max(m_target->GetHeight(), 1U); // Let's make sure we won't divide by zero
// Our target region is expressed as % of the viewport dimensions, let's compute it in pixels // Our target region is expressed as % of the viewport dimensions, let's compute it in pixels
NzRectf fViewport(m_targetRegion); Nz::Rectf fViewport(m_targetRegion);
fViewport.x *= targetWidth; fViewport.x *= targetWidth;
fViewport.y *= targetHeight; fViewport.y *= targetHeight;
fViewport.width *= targetWidth; fViewport.width *= targetWidth;
@ -161,11 +161,11 @@ namespace Ndk
// Compute the new aspect ratio, if it's different we need to invalidate the projection matrix // Compute the new aspect ratio, if it's different we need to invalidate the projection matrix
float aspectRatio = fViewport.width/fViewport.height; float aspectRatio = fViewport.width/fViewport.height;
if (!NzNumberEquals(m_aspectRatio, aspectRatio, 0.001f)) if (!Nz::NumberEquals(m_aspectRatio, aspectRatio, 0.001f))
{ {
m_aspectRatio = aspectRatio; m_aspectRatio = aspectRatio;
if (m_projectionType == nzProjectionType_Perspective) if (m_projectionType == Nz::ProjectionType_Perspective)
InvalidateProjectionMatrix(); InvalidateProjectionMatrix();
} }

View File

@ -11,7 +11,7 @@
namespace Ndk namespace Ndk
{ {
void CollisionComponent::SetGeom(NzPhysGeomRef geom) void CollisionComponent::SetGeom(Nz::PhysGeomRef geom)
{ {
m_geom = std::move(geom); m_geom = std::move(geom);
@ -35,9 +35,9 @@ namespace Ndk
NazaraAssert(entityWorld, "Entity must have world"); NazaraAssert(entityWorld, "Entity must have world");
NazaraAssert(entityWorld->HasSystem<PhysicsSystem>(), "World must have a physics system"); NazaraAssert(entityWorld->HasSystem<PhysicsSystem>(), "World must have a physics system");
NzPhysWorld& physWorld = entityWorld->GetSystem<PhysicsSystem>().GetWorld(); Nz::PhysWorld& physWorld = entityWorld->GetSystem<PhysicsSystem>().GetWorld();
m_staticBody.reset(new NzPhysObject(&physWorld, m_geom)); m_staticBody.reset(new Nz::PhysObject(&physWorld, m_geom));
m_staticBody->EnableAutoSleep(false); m_staticBody->EnableAutoSleep(false);
} }

View File

@ -9,7 +9,7 @@
namespace Ndk namespace Ndk
{ {
void GraphicsComponent::InvalidateRenderableData(const NzInstancedRenderable* renderable, nzUInt32 flags, unsigned int index) void GraphicsComponent::InvalidateRenderableData(const Nz::InstancedRenderable* renderable, Nz::UInt32 flags, unsigned int index)
{ {
NazaraAssert(index < m_renderables.size(), "Invalid renderable index"); NazaraAssert(index < m_renderables.size(), "Invalid renderable index");
NazaraUnused(renderable); NazaraUnused(renderable);
@ -55,7 +55,7 @@ namespace Ndk
InvalidateTransformMatrix(); InvalidateTransformMatrix();
} }
void GraphicsComponent::OnNodeInvalidated(const NzNode* node) void GraphicsComponent::OnNodeInvalidated(const Nz::Node* node)
{ {
NazaraUnused(node); NazaraUnused(node);
@ -69,7 +69,7 @@ namespace Ndk
Ndk::RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem<Ndk::RenderSystem>(); Ndk::RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem<Ndk::RenderSystem>();
m_transformMatrix = NzMatrix4f::ConcatenateAffine(renderSystem.GetCoordinateSystemMatrix(), m_entity->GetComponent<NodeComponent>().GetTransformMatrix()); m_transformMatrix = Nz::Matrix4f::ConcatenateAffine(renderSystem.GetCoordinateSystemMatrix(), m_entity->GetComponent<NodeComponent>().GetTransformMatrix());
m_transformMatrixUpdated = true; m_transformMatrixUpdated = true;
} }

View File

@ -17,19 +17,19 @@ namespace Ndk
World* entityWorld = m_entity->GetWorld(); World* entityWorld = m_entity->GetWorld();
NazaraAssert(entityWorld->HasSystem<PhysicsSystem>(), "World must have a physics system"); NazaraAssert(entityWorld->HasSystem<PhysicsSystem>(), "World must have a physics system");
NzPhysWorld& world = entityWorld->GetSystem<PhysicsSystem>().GetWorld(); Nz::PhysWorld& world = entityWorld->GetSystem<PhysicsSystem>().GetWorld();
NzPhysGeomRef geom; Nz::PhysGeomRef geom;
if (m_entity->HasComponent<CollisionComponent>()) if (m_entity->HasComponent<CollisionComponent>())
geom = m_entity->GetComponent<CollisionComponent>().GetGeom(); geom = m_entity->GetComponent<CollisionComponent>().GetGeom();
NzMatrix4f matrix; Nz::Matrix4f matrix;
if (m_entity->HasComponent<NodeComponent>()) if (m_entity->HasComponent<NodeComponent>())
matrix = m_entity->GetComponent<NodeComponent>().GetTransformMatrix(); matrix = m_entity->GetComponent<NodeComponent>().GetTransformMatrix();
else else
matrix.MakeIdentity(); matrix.MakeIdentity();
m_object.reset(new NzPhysObject(&world, geom, matrix)); m_object.reset(new Nz::PhysObject(&world, geom, matrix));
m_object->SetMass(1.f); m_object->SetMass(1.f);
} }
@ -47,7 +47,7 @@ namespace Ndk
if (IsComponent<CollisionComponent>(component)) if (IsComponent<CollisionComponent>(component))
{ {
NazaraAssert(m_object, "Invalid object"); NazaraAssert(m_object, "Invalid object");
m_object->SetGeom(NzNullGeom::New()); m_object->SetGeom(Nz::NullGeom::New());
} }
} }

View File

@ -12,9 +12,9 @@ namespace Ndk
Entity::Entity(Entity&& entity) : Entity::Entity(Entity&& entity) :
m_components(std::move(entity.m_components)), m_components(std::move(entity.m_components)),
m_handles(std::move(entity.m_handles)), m_handles(std::move(entity.m_handles)),
m_id(entity.m_id),
m_componentBits(std::move(entity.m_componentBits)), m_componentBits(std::move(entity.m_componentBits)),
m_systemBits(std::move(entity.m_systemBits)), m_systemBits(std::move(entity.m_systemBits)),
m_id(entity.m_id),
m_world(entity.m_world), m_world(entity.m_world),
m_valid(entity.m_valid) m_valid(entity.m_valid)
{ {

View File

@ -35,19 +35,19 @@ namespace Ndk
try try
{ {
NzErrorFlags errFlags(nzErrorFlag_ThrowException, true); Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true);
// Initialisation du moteur // Initialisation du moteur
// Modules clients // Modules clients
NzAudio::Initialize(); Nz::Audio::Initialize();
NzGraphics::Initialize(); Nz::Graphics::Initialize();
// Modules serveurs // Modules serveurs
NzLua::Initialize(); Nz::Lua::Initialize();
NzNoise::Initialize(); Nz::Noise::Initialize();
NzPhysics::Initialize(); Nz::Physics::Initialize();
NzUtility::Initialize(); Nz::Utility::Initialize();
// Initialisation du SDK // Initialisation du SDK
@ -76,7 +76,7 @@ namespace Ndk
} }
catch (const std::exception& e) catch (const std::exception& e)
{ {
NazaraError("Failed to initialize NDK: " + NzString(e.what())); NazaraError("Failed to initialize NDK: " + Nz::String(e.what()));
return false; return false;
} }
@ -99,14 +99,14 @@ namespace Ndk
// Libération du moteur // Libération du moteur
// Modules clients // Modules clients
NzAudio::Uninitialize(); Nz::Audio::Uninitialize();
NzGraphics::Uninitialize(); Nz::Graphics::Uninitialize();
// Modules serveurs // Modules serveurs
NzLua::Uninitialize(); Nz::Lua::Uninitialize();
NzNoise::Uninitialize(); Nz::Noise::Uninitialize();
NzPhysics::Uninitialize(); Nz::Physics::Uninitialize();
NzUtility::Uninitialize(); Nz::Utility::Uninitialize();
NazaraNotice("Uninitialized: SDK"); NazaraNotice("Uninitialized: SDK");
} }

View File

@ -30,22 +30,22 @@ namespace Ndk
// On récupère la position et la rotation pour les affecter au listener // On récupère la position et la rotation pour les affecter au listener
const NodeComponent& node = entity->GetComponent<NodeComponent>(); const NodeComponent& node = entity->GetComponent<NodeComponent>();
NzAudio::SetListenerPosition(node.GetPosition(nzCoordSys_Global)); Nz::Audio::SetListenerPosition(node.GetPosition(Nz::CoordSys_Global));
NzAudio::SetListenerRotation(node.GetRotation(nzCoordSys_Global)); Nz::Audio::SetListenerRotation(node.GetRotation(Nz::CoordSys_Global));
// On vérifie la présence d'une donnée de vitesse, et on l'affecte // On vérifie la présence d'une donnée de vitesse, et on l'affecte
// (La vitesse du listener Audio ne le fait pas se déplacer, mais affecte par exemple l'effet Doppler) // (La vitesse du listener Audio ne le fait pas se déplacer, mais affecte par exemple l'effet Doppler)
if (entity->HasComponent<VelocityComponent>()) if (entity->HasComponent<VelocityComponent>())
{ {
const VelocityComponent& velocity = entity->GetComponent<VelocityComponent>(); const VelocityComponent& velocity = entity->GetComponent<VelocityComponent>();
NzAudio::SetListenerVelocity(velocity.linearVelocity); Nz::Audio::SetListenerVelocity(velocity.linearVelocity);
} }
activeListenerCount++; activeListenerCount++;
} }
if (activeListenerCount > 1) if (activeListenerCount > 1)
NazaraWarning(NzString::Number(activeListenerCount) + " listeners were active in the same update loop"); NazaraWarning(Nz::String::Number(activeListenerCount) + " listeners were active in the same update loop");
} }
SystemIndex ListenerSystem::systemIndex; SystemIndex ListenerSystem::systemIndex;

View File

@ -45,9 +45,9 @@ namespace Ndk
NodeComponent& node = entity->GetComponent<NodeComponent>(); NodeComponent& node = entity->GetComponent<NodeComponent>();
PhysicsComponent& phys = entity->GetComponent<PhysicsComponent>(); PhysicsComponent& phys = entity->GetComponent<PhysicsComponent>();
NzPhysObject& physObj = phys.GetPhysObject(); Nz::PhysObject& physObj = phys.GetPhysObject();
node.SetRotation(physObj.GetRotation(), nzCoordSys_Global); node.SetRotation(physObj.GetRotation(), Nz::CoordSys_Global);
node.SetPosition(physObj.GetPosition(), nzCoordSys_Global); node.SetPosition(physObj.GetPosition(), Nz::CoordSys_Global);
} }
float invElapsedTime = 1.f / elapsedTime; float invElapsedTime = 1.f / elapsedTime;
@ -56,12 +56,12 @@ namespace Ndk
CollisionComponent& collision = entity->GetComponent<CollisionComponent>(); CollisionComponent& collision = entity->GetComponent<CollisionComponent>();
NodeComponent& node = entity->GetComponent<NodeComponent>(); NodeComponent& node = entity->GetComponent<NodeComponent>();
NzPhysObject* physObj = collision.GetStaticBody(); Nz::PhysObject* physObj = collision.GetStaticBody();
NzQuaternionf oldRotation = physObj->GetRotation(); Nz::Quaternionf oldRotation = physObj->GetRotation();
NzVector3f oldPosition = physObj->GetPosition(); Nz::Vector3f oldPosition = physObj->GetPosition();
NzQuaternionf newRotation = node.GetRotation(nzCoordSys_Global); Nz::Quaternionf newRotation = node.GetRotation(Nz::CoordSys_Global);
NzVector3f newPosition = node.GetPosition(nzCoordSys_Global); Nz::Vector3f newPosition = node.GetPosition(Nz::CoordSys_Global);
// Pour déplacer des objets statiques et assurer les collisions, il faut leur définir une vitesse // Pour déplacer des objets statiques et assurer les collisions, il faut leur définir une vitesse
// (note importante: le moteur physique n'applique pas la vitesse sur les objets statiques) // (note importante: le moteur physique n'applique pas la vitesse sur les objets statiques)
@ -71,21 +71,21 @@ namespace Ndk
physObj->SetVelocity((newPosition - oldPosition) * invElapsedTime); physObj->SetVelocity((newPosition - oldPosition) * invElapsedTime);
} }
else else
physObj->SetVelocity(NzVector3f::Zero()); physObj->SetVelocity(Nz::Vector3f::Zero());
if (newRotation != oldRotation) if (newRotation != oldRotation)
{ {
NzQuaternionf transition = newRotation * oldRotation.GetConjugate(); Nz::Quaternionf transition = newRotation * oldRotation.GetConjugate();
NzEulerAnglesf angles = transition.ToEulerAngles(); Nz::EulerAnglesf angles = transition.ToEulerAngles();
NzVector3f angularVelocity(NzToRadians(angles.pitch * invElapsedTime), Nz::Vector3f angularVelocity(Nz::ToRadians(angles.pitch * invElapsedTime),
NzToRadians(angles.yaw * invElapsedTime), Nz::ToRadians(angles.yaw * invElapsedTime),
NzToRadians(angles.roll * invElapsedTime)); Nz::ToRadians(angles.roll * invElapsedTime));
physObj->SetRotation(oldRotation); physObj->SetRotation(oldRotation);
physObj->SetAngularVelocity(angularVelocity); physObj->SetAngularVelocity(angularVelocity);
} }
else else
physObj->SetAngularVelocity(NzVector3f::Zero()); physObj->SetAngularVelocity(Nz::Vector3f::Zero());
} }
} }

View File

@ -13,10 +13,10 @@
namespace Ndk namespace Ndk
{ {
RenderSystem::RenderSystem() : RenderSystem::RenderSystem() :
m_coordinateSystemMatrix(NzMatrix4f::Identity()), m_coordinateSystemMatrix(Nz::Matrix4f::Identity()),
m_coordinateSystemInvalidated(true) m_coordinateSystemInvalidated(true)
{ {
SetDefaultBackground(NzColorBackground::New()); SetDefaultBackground(Nz::ColorBackground::New());
SetUpdateRate(0.f); SetUpdateRate(0.f);
} }
@ -50,7 +50,7 @@ namespace Ndk
if (entity->HasComponent<LightComponent>() && entity->HasComponent<NodeComponent>()) if (entity->HasComponent<LightComponent>() && entity->HasComponent<NodeComponent>())
{ {
LightComponent& lightComponent = entity->GetComponent<LightComponent>(); LightComponent& lightComponent = entity->GetComponent<LightComponent>();
if (lightComponent.GetLightType() == nzLightType_Directional) if (lightComponent.GetLightType() == Nz::LightType_Directional)
{ {
m_directionalLights.Insert(entity); m_directionalLights.Insert(entity);
m_pointSpotLights.Remove(entity); m_pointSpotLights.Remove(entity);
@ -95,7 +95,7 @@ namespace Ndk
//UpdateDirectionalShadowMaps(camComponent); //UpdateDirectionalShadowMaps(camComponent);
NzAbstractRenderQueue* renderQueue = m_renderTechnique.GetRenderQueue(); Nz::AbstractRenderQueue* renderQueue = m_renderTechnique.GetRenderQueue();
renderQueue->Clear(); renderQueue->Clear();
//TODO: Culling //TODO: Culling
@ -113,13 +113,13 @@ namespace Ndk
NodeComponent& lightNode = light->GetComponent<NodeComponent>(); NodeComponent& lightNode = light->GetComponent<NodeComponent>();
///TODO: Cache somehow? ///TODO: Cache somehow?
lightComponent.AddToRenderQueue(renderQueue, NzMatrix4f::ConcatenateAffine(m_coordinateSystemMatrix, lightNode.GetTransformMatrix())); lightComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::ConcatenateAffine(m_coordinateSystemMatrix, lightNode.GetTransformMatrix()));
} }
camComponent.ApplyView(); camComponent.ApplyView();
NzSceneData sceneData; Nz::SceneData sceneData;
sceneData.ambientColor = NzColor(25, 25, 25); sceneData.ambientColor = Nz::Color(25, 25, 25);
sceneData.background = m_background; sceneData.background = m_background;
sceneData.viewer = &camComponent; sceneData.viewer = &camComponent;
@ -127,13 +127,13 @@ namespace Ndk
} }
} }
void RenderSystem::UpdateDirectionalShadowMaps(const NzAbstractViewer& viewer) void RenderSystem::UpdateDirectionalShadowMaps(const Nz::AbstractViewer& viewer)
{ {
if (!m_shadowRT.IsValid()) if (!m_shadowRT.IsValid())
m_shadowRT.Create(); m_shadowRT.Create();
NzSceneData dummySceneData; Nz::SceneData dummySceneData;
dummySceneData.ambientColor = NzColor(0, 0, 0); dummySceneData.ambientColor = Nz::Color(0, 0, 0);
dummySceneData.background = nullptr; dummySceneData.background = nullptr;
dummySceneData.viewer = nullptr; //< Depth technique doesn't require any viewer dummySceneData.viewer = nullptr; //< Depth technique doesn't require any viewer
@ -145,13 +145,13 @@ namespace Ndk
if (!lightComponent.IsShadowCastingEnabled()) if (!lightComponent.IsShadowCastingEnabled())
continue; continue;
NzVector2ui shadowMapSize(lightComponent.GetShadowMap()->GetSize()); Nz::Vector2ui shadowMapSize(lightComponent.GetShadowMap()->GetSize());
m_shadowRT.AttachTexture(nzAttachmentPoint_Depth, 0, lightComponent.GetShadowMap()); m_shadowRT.AttachTexture(Nz::AttachmentPoint_Depth, 0, lightComponent.GetShadowMap());
NzRenderer::SetTarget(&m_shadowRT); Nz::Renderer::SetTarget(&m_shadowRT);
NzRenderer::SetViewport(NzRecti(0, 0, shadowMapSize.x, shadowMapSize.y)); Nz::Renderer::SetViewport(Nz::Recti(0, 0, shadowMapSize.x, shadowMapSize.y));
NzAbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue(); Nz::AbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue();
renderQueue->Clear(); renderQueue->Clear();
///TODO: Culling ///TODO: Culling
@ -164,8 +164,8 @@ namespace Ndk
} }
///TODO: Cache the matrices in the light? ///TODO: Cache the matrices in the light?
NzRenderer::SetMatrix(nzMatrixType_Projection, NzMatrix4f::Ortho(0.f, 100.f, 100.f, 0.f, 1.f, 100.f)); Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, Nz::Matrix4f::Ortho(0.f, 100.f, 100.f, 0.f, 1.f, 100.f));
NzRenderer::SetMatrix(nzMatrixType_View, NzMatrix4f::ViewMatrix(lightNode.GetRotation() * NzVector3f::Forward() * 100.f, lightNode.GetRotation())); Nz::Renderer::SetMatrix(Nz::MatrixType_View, Nz::Matrix4f::ViewMatrix(lightNode.GetRotation() * Nz::Vector3f::Forward() * 100.f, lightNode.GetRotation()));
m_shadowTechnique.Draw(dummySceneData); m_shadowTechnique.Draw(dummySceneData);
} }
@ -176,8 +176,8 @@ namespace Ndk
if (!m_shadowRT.IsValid()) if (!m_shadowRT.IsValid())
m_shadowRT.Create(); m_shadowRT.Create();
NzSceneData dummySceneData; Nz::SceneData dummySceneData;
dummySceneData.ambientColor = NzColor(0, 0, 0); dummySceneData.ambientColor = Nz::Color(0, 0, 0);
dummySceneData.background = nullptr; dummySceneData.background = nullptr;
dummySceneData.viewer = nullptr; //< Depth technique doesn't require any viewer dummySceneData.viewer = nullptr; //< Depth technique doesn't require any viewer
@ -189,37 +189,37 @@ namespace Ndk
if (!lightComponent.IsShadowCastingEnabled()) if (!lightComponent.IsShadowCastingEnabled())
continue; continue;
NzVector2ui shadowMapSize(lightComponent.GetShadowMap()->GetSize()); Nz::Vector2ui shadowMapSize(lightComponent.GetShadowMap()->GetSize());
switch (lightComponent.GetLightType()) switch (lightComponent.GetLightType())
{ {
case nzLightType_Directional: case Nz::LightType_Directional:
NazaraInternalError("Directional lights included in point/spot light list"); NazaraInternalError("Directional lights included in point/spot light list");
break; break;
case nzLightType_Point: case Nz::LightType_Point:
{ {
static NzQuaternionf rotations[6] = static Nz::Quaternionf rotations[6] =
{ {
NzQuaternionf::RotationBetween(NzVector3f::Forward(), NzVector3f::UnitX()), // nzCubemapFace_PositiveX Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), Nz::Vector3f::UnitX()), // nzCubemapFace_PositiveX
NzQuaternionf::RotationBetween(NzVector3f::Forward(), -NzVector3f::UnitX()), // nzCubemapFace_NegativeX Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), -Nz::Vector3f::UnitX()), // nzCubemapFace_NegativeX
NzQuaternionf::RotationBetween(NzVector3f::Forward(), -NzVector3f::UnitY()), // nzCubemapFace_PositiveY Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), -Nz::Vector3f::UnitY()), // nzCubemapFace_PositiveY
NzQuaternionf::RotationBetween(NzVector3f::Forward(), NzVector3f::UnitY()), // nzCubemapFace_NegativeY Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), Nz::Vector3f::UnitY()), // nzCubemapFace_NegativeY
NzQuaternionf::RotationBetween(NzVector3f::Forward(), -NzVector3f::UnitZ()), // nzCubemapFace_PositiveZ Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), -Nz::Vector3f::UnitZ()), // nzCubemapFace_PositiveZ
NzQuaternionf::RotationBetween(NzVector3f::Forward(), NzVector3f::UnitZ()) // nzCubemapFace_NegativeZ Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), Nz::Vector3f::UnitZ()) // nzCubemapFace_NegativeZ
}; };
for (unsigned int face = 0; face < 6; ++face) for (unsigned int face = 0; face < 6; ++face)
{ {
m_shadowRT.AttachTexture(nzAttachmentPoint_Depth, 0, lightComponent.GetShadowMap(), face); m_shadowRT.AttachTexture(Nz::AttachmentPoint_Depth, 0, lightComponent.GetShadowMap(), face);
NzRenderer::SetTarget(&m_shadowRT); Nz::Renderer::SetTarget(&m_shadowRT);
NzRenderer::SetViewport(NzRecti(0, 0, shadowMapSize.x, shadowMapSize.y)); Nz::Renderer::SetViewport(Nz::Recti(0, 0, shadowMapSize.x, shadowMapSize.y));
///TODO: Cache the matrices in the light? ///TODO: Cache the matrices in the light?
NzRenderer::SetMatrix(nzMatrixType_Projection, NzMatrix4f::Perspective(NzFromDegrees(90.f), 1.f, 0.1f, lightComponent.GetRadius())); Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, Nz::Matrix4f::Perspective(Nz::FromDegrees(90.f), 1.f, 0.1f, lightComponent.GetRadius()));
NzRenderer::SetMatrix(nzMatrixType_View, NzMatrix4f::ViewMatrix(lightNode.GetPosition(), rotations[face])); Nz::Renderer::SetMatrix(Nz::MatrixType_View, Nz::Matrix4f::ViewMatrix(lightNode.GetPosition(), rotations[face]));
NzAbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue(); Nz::AbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue();
renderQueue->Clear(); renderQueue->Clear();
///TODO: Culling ///TODO: Culling
@ -236,16 +236,17 @@ namespace Ndk
break; break;
} }
case nzLightType_Spot: case Nz::LightType_Spot:
m_shadowRT.AttachTexture(nzAttachmentPoint_Depth, 0, lightComponent.GetShadowMap()); {
NzRenderer::SetTarget(&m_shadowRT); m_shadowRT.AttachTexture(Nz::AttachmentPoint_Depth, 0, lightComponent.GetShadowMap());
NzRenderer::SetViewport(NzRecti(0, 0, shadowMapSize.x, shadowMapSize.y)); Nz::Renderer::SetTarget(&m_shadowRT);
Nz::Renderer::SetViewport(Nz::Recti(0, 0, shadowMapSize.x, shadowMapSize.y));
///TODO: Cache the matrices in the light? ///TODO: Cache the matrices in the light?
NzRenderer::SetMatrix(nzMatrixType_Projection, NzMatrix4f::Perspective(lightComponent.GetOuterAngle()*2.f, 1.f, 0.1f, lightComponent.GetRadius())); Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, Nz::Matrix4f::Perspective(lightComponent.GetOuterAngle()*2.f, 1.f, 0.1f, lightComponent.GetRadius()));
NzRenderer::SetMatrix(nzMatrixType_View, NzMatrix4f::ViewMatrix(lightNode.GetPosition(), lightNode.GetRotation())); Nz::Renderer::SetMatrix(Nz::MatrixType_View, Nz::Matrix4f::ViewMatrix(lightNode.GetPosition(), lightNode.GetRotation()));
NzAbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue(); Nz::AbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue();
renderQueue->Clear(); renderQueue->Clear();
///TODO: Culling ///TODO: Culling
@ -259,6 +260,7 @@ namespace Ndk
m_shadowTechnique.Draw(dummySceneData); m_shadowTechnique.Draw(dummySceneData);
break; break;
}
} }
} }
} }

View File

@ -132,6 +132,10 @@ namespace Ndk
{ {
for (auto& system : m_systems) for (auto& system : m_systems)
{ {
// Ignore non-existent systems
if (!system)
continue;
// L'entité est-elle enregistrée comme faisant partie du système ? // L'entité est-elle enregistrée comme faisant partie du système ?
bool partOfSystem = system->HasEntity(entity); bool partOfSystem = system->HasEntity(entity);

View File

@ -6,6 +6,8 @@ function NazaraBuild:Execute()
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.OrderedExtLibs > 0) then if (#self.OrderedExtLibs > 0) then
solution("NazaraExtlibs") solution("NazaraExtlibs")
platforms({"x32", "x64"}) platforms({"x32", "x64"})
@ -28,12 +30,12 @@ function NazaraBuild:Execute()
libdirs("../extlibs/lib/common/x64") libdirs("../extlibs/lib/common/x64")
configuration({"codeblocks or codelite or gmake", "x32"}) configuration({"codeblocks or codelite or gmake", "x32"})
libdirs("../extlibs/lib/mingw/x86") libdirs("../extlibs/lib/" .. makeLibDir .. "/x86")
targetdir("../extlibs/lib/mingw/x86") targetdir("../extlibs/lib/" .. makeLibDir .. "/x86")
configuration({"codeblocks or codelite or gmake", "x64"}) configuration({"codeblocks or codelite or gmake", "x64"})
libdirs("../extlibs/lib/mingw/x64") libdirs("../extlibs/lib/" .. makeLibDir .. "/x64")
targetdir("../extlibs/lib/mingw/x64") targetdir("../extlibs/lib/" .. makeLibDir .. "/x64")
configuration("vs*") configuration("vs*")
buildoptions("/MP") buildoptions("/MP")
@ -71,7 +73,7 @@ function NazaraBuild:Execute()
targetsuffix("-s") targetsuffix("-s")
configuration("codeblocks or codelite or gmake or xcode3 or xcode4") configuration("codeblocks or codelite or gmake or xcode3 or xcode4")
buildoptions("-std=c++14") buildoptions({"-fPIC", "-std=c++14"})
for k, libTable in ipairs(self.OrderedExtLibs) do for k, libTable in ipairs(self.OrderedExtLibs) do
project(libTable.Name) project(libTable.Name)
@ -171,14 +173,14 @@ function NazaraBuild:Execute()
libdirs("../extlibs/lib/common/x64") libdirs("../extlibs/lib/common/x64")
configuration({"codeblocks or codelite or gmake", "x32"}) configuration({"codeblocks or codelite or gmake", "x32"})
libdirs("../extlibs/lib/mingw/x86") libdirs("../extlibs/lib/" .. makeLibDir .. "/x86")
libdirs("../lib/mingw/x86") libdirs("../lib/" .. makeLibDir .. "/x86")
targetdir("../lib/mingw/x86") targetdir("../lib/" .. makeLibDir .. "/x86")
configuration({"codeblocks or codelite or gmake", "x64"}) configuration({"codeblocks or codelite or gmake", "x64"})
libdirs("../extlibs/lib/mingw/x64") libdirs("../extlibs/lib/" .. makeLibDir .. "/x64")
libdirs("../lib/mingw/x64") libdirs("../lib/" .. makeLibDir .. "/x64")
targetdir("../lib/mingw/x64") targetdir("../lib/" .. makeLibDir .. "/x64")
configuration({"vs*", "x32"}) configuration({"vs*", "x32"})
libdirs("../extlibs/lib/msvc/x86") libdirs("../extlibs/lib/msvc/x86")
@ -268,17 +270,17 @@ function NazaraBuild:Execute()
libdirs("../extlibs/lib/common/x64") libdirs("../extlibs/lib/common/x64")
configuration({"codeblocks or codelite or gmake", "x32"}) configuration({"codeblocks or codelite or gmake", "x32"})
libdirs("../extlibs/lib/mingw/x86") libdirs("../extlibs/lib/" .. makeLibDir .. "/x86")
libdirs("../lib/mingw/x86") libdirs("../lib/" .. makeLibDir .. "/x86")
if (toolTable.Kind == "library") then if (toolTable.Kind == "library") then
targetdir("../lib/mingw/x86") targetdir("../lib/" .. makeLibDir .. "/x86")
end end
configuration({"codeblocks or codelite or gmake", "x64"}) configuration({"codeblocks or codelite or gmake", "x64"})
libdirs("../extlibs/lib/mingw/x64") libdirs("../extlibs/lib/" .. makeLibDir .. "/x64")
libdirs("../lib/mingw/x64") libdirs("../lib/" .. makeLibDir .. "/x64")
if (toolTable.Kind == "library") then if (toolTable.Kind == "library") then
targetdir("../lib/mingw/x64") targetdir("../lib/" .. makeLibDir .. "/x64")
end end
configuration({"vs*", "x32"}) configuration({"vs*", "x32"})
@ -379,10 +381,10 @@ function NazaraBuild:Execute()
libdirs("../extlibs/lib/common/x64") libdirs("../extlibs/lib/common/x64")
configuration({"codeblocks or codelite or gmake", "x32"}) configuration({"codeblocks or codelite or gmake", "x32"})
libdirs("../lib/mingw/x86") libdirs("../lib/" .. makeLibDir .. "/x86")
configuration({"codeblocks or codelite or gmake", "x64"}) configuration({"codeblocks or codelite or gmake", "x64"})
libdirs("../lib/mingw/x64") libdirs("../lib/" .. makeLibDir .. "/x64")
configuration({"vs*", "x32"}) configuration({"vs*", "x32"})
libdirs("../lib/msvc/x86") libdirs("../lib/msvc/x86")

View File

@ -15,3 +15,8 @@ MODULE.OsFiles.Posix = {
"../src/Nazara/Core/Posix/**.hpp", "../src/Nazara/Core/Posix/**.hpp",
"../src/Nazara/Core/Posix/**.cpp" "../src/Nazara/Core/Posix/**.cpp"
} }
MODULE.OsLibraries.Posix = {
"dl",
"pthread"
}

View File

@ -0,0 +1,19 @@
MODULE.Name = "Network"
MODULE.Libraries = {
"NazaraCore"
}
MODULE.OsFiles.Windows = {
"../src/Nazara/Network/Win32/**.hpp",
"../src/Nazara/Network/Win32/**.cpp"
}
MODULE.OsFiles.Posix = {
"../src/Nazara/Network/Posix/**.hpp",
"../src/Nazara/Network/Posix/**.cpp"
}
MODULE.OsLibraries.Windows = {
"ws2_32"
}

View File

@ -24,3 +24,8 @@ MODULE.OsLibraries.Windows = {
"opengl32", "opengl32",
"winmm" "winmm"
} }
MODULE.OsLibraries.Posix = {
"GL",
"X11"
}

View File

@ -20,3 +20,13 @@ MODULE.OsLibraries.Windows = {
"gdi32" "gdi32"
} }
MODULE.OsLibraries.Posix = {
"X11",
"xcb",
"xcb-cursor",
"xcb-ewmh",
"xcb-icccm",
"xcb-keysyms",
"xcb-randr"
}

View File

@ -18,7 +18,7 @@
int main() int main()
{ {
// NzKeyboard ne nécessite pas l'initialisation du module Utilitaire // NzKeyboard ne nécessite pas l'initialisation du module Utilitaire
NzInitializer<NzAudio> audio; Nz::Initializer<Nz::Audio> audio;
if (!audio) if (!audio)
{ {
std::cout << "Failed to initialize audio module" << std::endl; std::cout << "Failed to initialize audio module" << std::endl;
@ -26,7 +26,7 @@ int main()
return 1; return 1;
} }
NzSound sound; Nz::Sound sound;
if (!sound.LoadFromFile("resources/siren.wav")) if (!sound.LoadFromFile("resources/siren.wav"))
{ {
std::cout << "Failed to load sound" << std::endl; std::cout << "Failed to load sound" << std::endl;
@ -44,32 +44,32 @@ int main()
sound.EnableLooping(true); sound.EnableLooping(true);
// La source du son se situe vers la gauche (Et un peu en avant) // La source du son se situe vers la gauche (Et un peu en avant)
sound.SetPosition(NzVector3f::Left()*50.f + NzVector3f::Forward()*5.f); sound.SetPosition(Nz::Vector3f::Left()*50.f + Nz::Vector3f::Forward()*5.f);
// Et possède une vitesse de 10 par seconde vers la droite // Et possède une vitesse de 10 par seconde vers la droite
sound.SetVelocity(NzVector3f::Left()*-10.f); sound.SetVelocity(Nz::Vector3f::Left()*-10.f);
// On joue le son // On joue le son
sound.Play(); sound.Play();
// La boucle du programme (Pour déplacer le son) // La boucle du programme (Pour déplacer le son)
NzClock clock; Nz::Clock clock;
while (sound.GetStatus() == nzSoundStatus_Playing) while (sound.GetStatus() == Nz::SoundStatus_Playing)
{ {
// Comme le son se joue dans un thread séparé, on peut mettre en pause le principal régulièrement // Comme le son se joue dans un thread séparé, on peut mettre en pause le principal régulièrement
int sleepTime = int(1000/60 - clock.GetMilliseconds()); // 60 FPS int sleepTime = int(1000/60 - clock.GetMilliseconds()); // 60 FPS
if (sleepTime > 0) if (sleepTime > 0)
NzThread::Sleep(sleepTime); Nz::Thread::Sleep(sleepTime);
// On bouge la source du son en fonction du temps depuis chaque mise à jour // On bouge la source du son en fonction du temps depuis chaque mise à jour
NzVector3f pos = sound.GetPosition() + sound.GetVelocity()*clock.GetSeconds(); Nz::Vector3f pos = sound.GetPosition() + sound.GetVelocity()*clock.GetSeconds();
sound.SetPosition(pos); sound.SetPosition(pos);
std::cout << "Sound position: " << pos << std::endl; std::cout << "Sound position: " << pos << std::endl;
// Si la position de la source atteint une certaine position, ou si l'utilisateur appuie sur echap // Si la position de la source atteint une certaine position, ou si l'utilisateur appuie sur echap
if (pos.x > NzVector3f::Left().x*-50.f || NzKeyboard::IsKeyPressed(NzKeyboard::Escape)) if (pos.x > Nz::Vector3f::Left().x*-50.f || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Escape))
sound.Stop(); // On arrête le son (Stoppant également la boucle) sound.Stop(); // On arrête le son (Stoppant également la boucle)
clock.Restart(); clock.Restart();

View File

@ -10,5 +10,6 @@ EXAMPLE.Libraries = {
"NazaraCore", "NazaraCore",
"NazaraGraphics", "NazaraGraphics",
"NazaraRenderer", "NazaraRenderer",
"NazaraUtility" "NazaraUtility",
"NazaraSDK"
} }

View File

@ -15,18 +15,25 @@
#include <Nazara/Graphics.hpp> // Module graphique #include <Nazara/Graphics.hpp> // Module graphique
#include <Nazara/Renderer.hpp> // Module de rendu #include <Nazara/Renderer.hpp> // Module de rendu
#include <Nazara/Utility.hpp> // Module utilitaire #include <Nazara/Utility.hpp> // Module utilitaire
#include <NDK/Components/CameraComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/LightComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Systems/RenderSystem.hpp>
#include <NDK/Sdk.hpp>
#include <NDK/World.hpp>
#include <iostream> #include <iostream>
// Petite fonction permettant de rendre le déplacement de la caméra moins ridige // Petite fonction permettant de rendre le déplacement de la caméra moins ridige
NzVector3f DampedString(const NzVector3f& currentPos, const NzVector3f& targetPos, float frametime, float springStrength = 3.f); Nz::Vector3f DampedString(const Nz::Vector3f& currentPos, const Nz::Vector3f& targetPos, float frametime, float springStrength = 3.f);
int main() int main()
{ {
// Pour commencer, nous initialisons le module Graphique, celui-ci va provoquer l'initialisation (dans l'ordre), // Pour commencer, nous initialisons le SDK de Nazara, celui-ci va préparer le terrain en initialisant le moteur,
// du noyau (Core), Utility, Renderer. // les composants, systèmes, etc.
// NzInitializer est une classe RAII appelant Initialize dans son constructeur et Uninitialize dans son destructeur. // NzInitializer est une classe RAII appelant Initialize dans son constructeur et Uninitialize dans son destructeur.
// Autrement dit, une fois ceci fait nous n'avons plus à nous soucier de la libération du moteur. // Autrement dit, une fois ceci fait nous n'avons plus à nous soucier de la libération du moteur.
NzInitializer<NzGraphics> nazara; Nz::Initializer<Ndk::Sdk> nazara;
if (!nazara) if (!nazara)
{ {
// Une erreur s'est produite dans l'initialisation d'un des modules // Une erreur s'est produite dans l'initialisation d'un des modules
@ -36,17 +43,16 @@ int main()
return EXIT_FAILURE; return EXIT_FAILURE;
} }
// Nazara étant initialisé, nous pouvons créer la scène // Nazara étant initialisé, nous pouvons créer le monde pour contenir notre scène.
// Une scène représente tout ce qui est visible par une ou plusieurs caméras. // Dans un ECS, le monde représente bien ce que son nom indique, c'est l'ensemble de ce qui existe au niveau de l'application.
// La plupart du temps vous n'aurez pas besoin de plus d'une scène, mais cela peut se révéler utile pour mieux // Il contient les systèmes et les entités, ces dernières contiennent les composants.
// organiser et optimiser le rendu. // Il est possible d'utiliser plusieurs mondes au sein d'une même application, par exemple pour gérer un mélange de 2D et de 3D,
// Par exemple, une pièce contenant une télévision, laquelle affichant des images provenant d'une Camera // mais nous verrons cela dans un prochain exemple.
// Le rendu sera alors plus efficace en créant deux scènes, une pour la pièce et l'autre pour les images de la télé. Ndk::World world;
// Cela diminuera le nombre de SceneNode à gérer pour chaque scène, et vous permettra même de ne pas afficher la scène
// affichée dans la télé si cette dernière n'est pas visible dans la première scène.
NzScene scene;
// La première chose que nous faisons est d'ajouter un background (fond) à la scène. // Nous pouvons maintenant ajouter des systèmes, mais dans cet exemple nous nous contenterons de ceux de base.
// La première chose que nous faisons est d'ajouter un background (fond) à notre scène.
// Il en existe plusieurs types, le moteur inclut pour l'instant trois d'entre eux: // Il en existe plusieurs types, le moteur inclut pour l'instant trois d'entre eux:
// -ColorBackground: Une couleur unie en fond // -ColorBackground: Une couleur unie en fond
// -SkyboxBackground: Une skybox en fond, un cube à six faces rendu autour de la caméra (En perdant la notion de distance) // -SkyboxBackground: Une skybox en fond, un cube à six faces rendu autour de la caméra (En perdant la notion de distance)
@ -56,53 +62,59 @@ int main()
// Pour commencer il faut charger une texture de type cubemap, certaines images sont assemblées de cette façon, // Pour commencer il faut charger une texture de type cubemap, certaines images sont assemblées de cette façon,
// comme celle que nous allons utiliser. // comme celle que nous allons utiliser.
// En réalité les textures "cubemap" regroupent six faces en une, pour faciliter leur utilisation. // En réalité les textures "cubemap" regroupent six faces en une, pour faciliter leur utilisation.
NzTexture* texture = new NzTexture;
// Nous créons une nouvelle texture et prenons une référence sur celle-ci (à la manière des pointeurs intelligents)
Nz::TextureRef texture = Nz::Texture::New();
if (texture->LoadCubemapFromFile("resources/skybox-space.png")) if (texture->LoadCubemapFromFile("resources/skybox-space.png"))
{ {
// Si la création du cubemap a fonctionné // Si la création du cubemap a fonctionné
// Nous indiquons que la texture est "non-persistente", autrement dit elle sera libérée automatiquement par le moteur // Nous créons alors le background à partir de notre texture (celui-ci va référencer notre texture, notre pointeur ne sert alors plus à rien).
// à l'instant précis où elle ne sera plus utilisée, dans ce cas-ci, ce sera à la libération de l'objet skybox, Nz::SkyboxBackgroundRef skybox = Nz::SkyboxBackground::New(std::move(texture));
// ceci arrivant lorsqu'un autre background est affecté à la scène, ou lorsque la scène sera libérée
texture->SetPersistent(false);
// Nous créons le background en lui affectant la texture // Accédons maintenant au système de rendu faisant partie du monde
NzSkyboxBackground* background = new NzSkyboxBackground(texture); Ndk::RenderSystem& renderSystem = world.GetSystem<Ndk::RenderSystem>(); // Une assertion valide la précondition "le système doit faire partie du monde"
// Nous pouvons en profiter pour paramétrer le background. // Nous assignons ensuite notre skybox comme "fond par défaut" du système
// Cependant, nous n'avons rien de spécial à faire ici, nous pouvons donc l'envoyer à la scène. // La notion "par défaut" existe parce qu'une caméra pourrait utiliser son propre fond lors du rendu,
scene.SetBackground(background); // le fond par défaut est utilisé lorsque la caméra n'a pas de fond propre assigné
renderSystem.SetDefaultBackground(std::move(skybox));
// Comme indiqué plus haut, la scène s'occupera automatiquement de la libération de notre background // Notre skybox est maintenant référencée par le système, lui-même appartenant au monde, aucune libération explicite n'est nécessaire
} }
else else
{ // Le chargement a échoué
delete texture; // Le chargement a échoué, nous libérons la texture
std::cout << "Failed to load skybox" << std::endl; std::cout << "Failed to load skybox" << std::endl;
}
// Ensuite, nous allons rajouter un modèle à notre scène. // Ensuite, nous allons rajouter un modèle à notre scène.
// Les modèles représentent, globalement, tout ce qui est visible en trois dimensions. // Les modèles représentent, globalement, tout ce qui est visible en trois dimensions.
// Nous choisirons ici un vaisseau spatial (Quoi de mieux pour une scène spatiale ?) // Nous choisirons ici un vaisseau spatial (Quoi de mieux pour une scène spatiale ?)
NzModel* spaceship = scene.CreateNode<NzModel>(); // Création depuis la scène
// Une structure permettant de paramétrer le chargement des modèles // Encore une fois, nous récupérons une référence plutôt que l'objet lui-même (cela va être très utile par la suite)
NzModelParameters params; Nz::ModelRef spaceshipModel = Nz::Model::New();
// Le format OBJ ne précise aucune échelle pour ses données, contrairement à Nazara (une unité = un mètre). // Nous allons charger notre modèle depuis un fichier, mais nous pouvons ajuster le modèle lors du chargement via
// Comme le vaisseau est très grand (Des centaines de mètres de long), nous allons le rendre plus petit // une structure permettant de paramétrer le chargement des modèles
// pour les besoins de la démo. Nz::ModelParameters params;
// Le format OBJ ne précise aucune échelle pour ses données, contrairement à Nazara (une unité = un mètre en 3D).
// Comme le vaisseau est très grand (Des centaines de mètres de long), nous allons le rendre plus petit pour les besoins de la démo.
// Ce paramètre sert à indiquer la mise à l'échelle désirée lors du chargement du modèle. // Ce paramètre sert à indiquer la mise à l'échelle désirée lors du chargement du modèle.
params.mesh.scale.Set(0.01f); // Un centième de la taille originelle params.mesh.scale.Set(0.01f); // Un centième de la taille originelle
// Les UVs de ce fichier sont retournées (repère OpenGL, origine coin bas-gauche) par rapport à ce que le moteur attend // Les UVs de ce fichier sont retournées (repère OpenGL, origine coin bas-gauche) par rapport à ce que le moteur attend (haut-gauche)
// Nous devons dire au moteur de les retourner lors du chargement // Nous devons donc indiquer au moteur de les retourner lors du chargement
params.mesh.flipUVs = true; params.mesh.flipUVs = true;
// Nazara va par défaut optimiser les modèles pour un rendu plus rapide, cela peut prendre du temps et n'est pas nécessaire ici
params.mesh.optimizeIndexBuffers = false;
// On charge ensuite le modèle depuis son fichier // On charge ensuite le modèle depuis son fichier
// Le moteur va charger le fichier et essayer de retrouver les fichiers associés (comme les matériaux, textures, ...) // Le moteur va charger le fichier et essayer de retrouver les fichiers associés (comme les matériaux, textures, ...)
if (!spaceship->LoadFromFile("resources/Spaceship/spaceship.obj", params)) if (!spaceshipModel->LoadFromFile("resources/Spaceship/spaceship.obj", params))
{ {
// Si le chargement a échoué (fichier inexistant/invalide), il ne sert à rien de continuer
std::cout << "Failed to load spaceship" << std::endl; std::cout << "Failed to load spaceship" << std::endl;
std::getchar(); std::getchar();
@ -111,15 +123,18 @@ int main()
// Nous voulons afficher quelques statistiques relatives au modèle, comme le nombre de sommets et de triangles // Nous voulons afficher quelques statistiques relatives au modèle, comme le nombre de sommets et de triangles
// Pour cela, nous devons accéder au mesh (maillage 3D) // Pour cela, nous devons accéder au mesh (maillage 3D)
NzMesh* mesh = spaceship->GetMesh();
// Note: Si nous voulions stocker le mesh pour nous en servir après, nous devrions alors récupérer une référence pour nous assurer
// qu'il ne sera pas supprimé tant que nous l'utilisons, mais ici nous faisons un accès direct et ne nous servons plus du pointeur par la suite
// Il est donc acceptable d'utiliser un pointeur nu ici.
Nz::Mesh* mesh = spaceshipModel->GetMesh();
std::cout << mesh->GetVertexCount() << " sommets" << std::endl; std::cout << mesh->GetVertexCount() << " sommets" << std::endl;
std::cout << mesh->GetTriangleCount() << " triangles" << std::endl; std::cout << mesh->GetTriangleCount() << " triangles" << std::endl;
// En revanche, le format OBJ ne précise pas l'utilisation d'une normal map, nous devons donc la charger manuellement // En revanche, le format OBJ ne précise pas l'utilisation d'une normal map, nous devons donc la charger manuellement
// Pour commencer on récupère le matériau du mesh, celui-ci en possède plusieurs mais celui qui nous intéresse, // Pour commencer on récupère le matériau du mesh, celui-ci en possède plusieurs mais celui qui nous intéresse,
// celui de la coque, est le second (Cela est bien entendu lié au modèle en lui-même) // celui de la coque, est le second (Cela est bien entendu lié au modèle en lui-même)
NzMaterial* material = spaceship->GetMaterial(1); Nz::Material* material = spaceshipModel->GetMaterial(1); // Encore une fois nous ne faisons qu'un accès direct.
// On lui indique ensuite le chemin vers la normal map // On lui indique ensuite le chemin vers la normal map
if (!material->SetNormalMap("resources/Spaceship/Texture/normal.png")) if (!material->SetNormalMap("resources/Spaceship/Texture/normal.png"))
@ -129,27 +144,58 @@ int main()
std::cout << "Failed to load normal map" << std::endl; std::cout << "Failed to load normal map" << std::endl;
} }
// Nous avons besoin également d'une caméra, pour des raisons évidentes, celle-ci sera à l'écart du modèle // Bien, nous avons un modèle valide, mais celui-ci ne consiste qu'en des informations de rendu, de matériaux et de textures.
// Commençons donc par créer une entité vide, cela se fait en demandant au monde de générer une nouvelle entité.
Ndk::EntityHandle spaceship = world.CreateEntity();
// Note: Nous ne récupérons pas l'entité directement mais un "handle" vers elle, ce dernier est un pointeur intelligent non-propriétaire.
// Pour des raisons techniques, le pointeur de l'entité peut venir à changer, ou l'entité être simplement détruite pour n'importe quelle raison.
// Le Handle nous permet de maintenir un pointeur valide vers notre entité, et invalidé automatiquement à sa mort.
// Nous avons désormais une entité, mais celle-ci ne contient rien et n'a d'autre propriété qu'un identifiant
// Nous devons donc lui rajouter les composants que nous voulons.
// Un NodeComponent donne à notre entité une position, rotation, échelle, et nous permet de l'attacher à d'autres entités (ce que nous ne ferons pas ici).
// Étant donné que par défaut, un NodeComponent se place en (0,0,0) sans rotation et avec une échelle de 1,1,1 et que cela nous convient,
// nous n'avons pas besoin d'agir sur le composant créé.
spaceship->AddComponent<Ndk::NodeComponent>();
// Bien, notre entité nouvellement créé dispose maintenant d'une position dans la scène, mais est toujours invisible
// Nous lui ajoutons donc un GraphicsComponent
Ndk::GraphicsComponent& spaceshipGraphics = spaceship->AddComponent<Ndk::GraphicsComponent>();
// Ce composant sert de point d'attache pour tous les renderables instanciés (tels que les modèles, les sprites, le texte, etc.)
// Cela signifie également qu'un modèle peut être attaché à autant d'entités que nécessaire.
// Note: Afin de maximiser les performances, essayez d'avoir le moins de renderables instanciés/matériaux et autres ressources possible
// le moteur fonctionne selon le batching et regroupera par exemple tous les modèles identiques ensembles lors du rendu.
spaceshipGraphics.Attach(spaceshipModel);
// Nous avons besoin également d'une caméra pour servir de point de vue à notre scène, celle-ci sera à l'écart du modèle
// regardant dans sa direction. // regardant dans sa direction.
// On conserve la rotation à part via des angles d'eulers pour la caméra free-fly // On conserve la rotation à part via des angles d'eulers pour la caméra free-fly
NzEulerAnglesf camAngles(0.f, -20.f, 0.f); Nz::EulerAnglesf camAngles(0.f, -20.f, 0.f);
NzCamera camera; // Nous créons donc une seconde entité
camera.SetPosition(0.f, 0.25f, 2.f); // On place la caméra à l'écart // Note: La création d'entité est une opération légère au sein du moteur, mais plus vous aurez d'entités et plus le processeur devra travailler.
camera.SetRotation(camAngles); Ndk::EntityHandle camera = world.CreateEntity();
// Notre caméra a elle aussi besoin d'être positionnée dans la scène
Ndk::NodeComponent& cameraNode = camera->AddComponent<Ndk::NodeComponent>();
cameraNode.SetPosition(0.f, 0.25f, 2.f); // On place la caméra à l'écart
cameraNode.SetRotation(camAngles);
// Et dispose d'un composant pour chaque point de vue de la scène, le CameraComponent
Ndk::CameraComponent& cameraComp = camera->AddComponent<Ndk::CameraComponent>();
// Et on n'oublie pas de définir les plans délimitant le champs de vision // Et on n'oublie pas de définir les plans délimitant le champs de vision
// (Seul ce qui se trouvera entre les deux plans sera rendu) // (Seul ce qui se trouvera entre les deux plans sera rendu)
// La distance entre l'oeil et le plan éloigné // La distance entre l'oeil et le plan éloigné
camera.SetZFar(5000.f); cameraComp.SetZFar(5000.f);
// La distance entre l'oeil et le plan rapproché (0 est une valeur interdite car la division par zéro l'est également) // La distance entre l'oeil et le plan rapproché (0 est une valeur interdite car la division par zéro l'est également)
camera.SetZNear(0.1f); cameraComp.SetZNear(0.1f);
// On indique à la scène que le viewer (Le point de vue) sera la caméra
scene.SetViewer(camera);
// Attention que le ratio entre les deux (zFar/zNear) doit rester raisonnable, dans le cas contraire vous risquez un phénomène // Attention que le ratio entre les deux (zFar/zNear) doit rester raisonnable, dans le cas contraire vous risquez un phénomène
// de "Z-Fighting" (Impossibilité de déduire quelle surface devrait apparaître en premier) sur les surfaces éloignées. // de "Z-Fighting" (Impossibilité de déduire quelle surface devrait apparaître en premier) sur les surfaces éloignées.
@ -160,40 +206,47 @@ int main()
// -PointLight: Lumière située à un endroit précis, envoyant de la lumière finie dans toutes les directions // -PointLight: Lumière située à un endroit précis, envoyant de la lumière finie dans toutes les directions
// -SpotLight: Lumière située à un endroit précis, envoyant de la lumière vers un endroit donné, avec un angle de diffusion // -SpotLight: Lumière située à un endroit précis, envoyant de la lumière vers un endroit donné, avec un angle de diffusion
// Nous créons une lumière directionnelle pour représenter la nébuleuse de notre skybox // Nous allons créer une lumière directionnelle pour représenter la nébuleuse de notre skybox
NzLight* nebulaLight = scene.CreateNode<NzLight>(nzLightType_Directional); // Encore une fois, nous créons notre entité
Ndk::EntityHandle nebulaLight = world.CreateEntity();
// Lui ajoutons une position dans la scène
Ndk::NodeComponent& nebulaLightNode = nebulaLight->AddComponent<Ndk::NodeComponent>();
// Et ensuite le composant principal, le LightComponent
Ndk::LightComponent& nebulaLightComp = nebulaLight->AddComponent<Ndk::LightComponent>(Nz::LightType_Directional);
// Il nous faut ensuite configurer la lumière // Il nous faut ensuite configurer la lumière
// Pour commencer, sa couleur, la nébuleuse étant d'une couleur jaune, j'ai choisi ces valeurs // Pour commencer, sa couleur, la nébuleuse étant d'une couleur jaune, j'ai choisi ces valeurs
nebulaLight->SetColor(NzColor(255, 182, 90)); nebulaLightComp.SetColor(Nz::Color(255, 182, 90));
// Nous appliquons ensuite une rotation de sorte que la lumière dans la même direction que la nébuleuse // Nous appliquons ensuite une rotation de sorte que la lumière dans la même direction que la nébuleuse
nebulaLight->SetRotation(NzEulerAnglesf(0.f, 102.f, 0.f)); nebulaLightNode.SetRotation(Nz::EulerAnglesf(0.f, 102.f, 0.f));
// Nous allons maintenant créer la fenêtre, dans laquelle nous ferons nos rendus // Nous allons maintenant créer la fenêtre, dans laquelle nous ferons nos rendus
// Celle-ci demande des paramètres plus complexes // Celle-ci demande des paramètres plus complexes
// Pour commencer le mode vidéo, celui-ci va définir la taille de la zone de rendu et le nombre de bits par pixels // Pour commencer le mode vidéo, celui-ci va définir la taille de la zone de rendu et le nombre de bits par pixels
NzVideoMode mode = NzVideoMode::GetDesktopMode(); // Nous récupérons le mode vidéo du bureau Nz::VideoMode mode = Nz::VideoMode::GetDesktopMode(); // Nous récupérons le mode vidéo du bureau
// Nous allons prendre les trois quarts de la résolution du bureau pour notre fenêtre // Nous allons prendre les trois quarts de la résolution du bureau pour notre fenêtre
mode.width *= 3.f/4.f; mode.width = 3 * mode.width / 4;
mode.height *= 3.f/4.f; mode.height = 3 * mode.height / 4;
// Maintenant le titre, rien de plus simple... // Maintenant le titre, rien de plus simple...
NzString windowTitle = "Nazara Demo - First scene"; Nz::String windowTitle = "Nazara Demo - First scene";
// Ensuite, le "style" de la fenêtre, possède-t-elle des bordures, peut-on cliquer sur la croix de fermeture, // Ensuite, le "style" de la fenêtre, possède-t-elle des bordures, peut-on cliquer sur la croix de fermeture,
// peut-on la redimensionner, ... // peut-on la redimensionner, ...
nzWindowStyleFlags style = nzWindowStyle_Default; // Nous prenons le style par défaut, autorisant tout ce que je viens de citer Nz::WindowStyleFlags style = Nz::WindowStyle_Default; // Nous prenons le style par défaut, autorisant tout ce que je viens de citer
// Ensuite, les paramètres du contexte de rendu // Ensuite, les paramètres du contexte de rendu
// On peut configurer le niveau d'antialiasing, le nombre de bits du depth buffer et le nombre de bits du stencil buffer // On peut configurer le niveau d'antialiasing, le nombre de bits du depth buffer et le nombre de bits du stencil buffer
// Nous désirons avoir un peu d'antialiasing (4x), les valeurs par défaut pour le reste nous conviendrons très bien // Nous désirons avoir un peu d'antialiasing (4x), les valeurs par défaut pour le reste nous conviendrons très bien
NzRenderTargetParameters parameters; Nz::RenderTargetParameters parameters;
parameters.antialiasingLevel = 4; parameters.antialiasingLevel = 4;
NzRenderWindow window(mode, windowTitle, style, parameters); Nz::RenderWindow window(mode, windowTitle, style, parameters);
if (!window.IsValid()) if (!window.IsValid())
{ {
std::cout << "Failed to create render window" << std::endl; std::cout << "Failed to create render window" << std::endl;
@ -203,62 +256,63 @@ int main()
} }
// On fait disparaître le curseur de la souris // On fait disparaître le curseur de la souris
window.SetCursor(nzWindowCursor_None); window.SetCursor(Nz::WindowCursor_None);
// On lie la caméra à la fenêtre // On lie la caméra à la fenêtre
camera.SetTarget(window); cameraComp.SetTarget(&window);
// Et on créé deux horloges pour gérer le temps // Et on créé deux horloges pour gérer le temps
NzClock secondClock, updateClock; Nz::Clock secondClock, updateClock;
Nz::UInt64 updateAccumulator = 0;
// Ainsi qu'un compteur de FPS improvisé // Ainsi qu'un compteur de FPS improvisé
unsigned int fps = 0; unsigned int fps = 0;
// Quelques variables de plus pour notre caméra // Quelques variables de plus pour notre caméra
bool smoothMovement = true; bool smoothMovement = true;
NzVector3f targetPos = camera.GetPosition(); Nz::Vector3f targetPos = cameraNode.GetPosition();
// Début de la boucle de rendu du programme // Début de la boucle de rendu du programme
while (window.IsOpen()) while (window.IsOpen())
{ {
// Ensuite nous allons traiter les évènements (Étape indispensable pour la fenêtre) // Ensuite nous allons traiter les évènements (Étape indispensable pour la fenêtre)
NzEvent event; Nz::WindowEvent event;
while (window.PollEvent(&event)) while (window.PollEvent(&event))
{ {
switch (event.type) switch (event.type)
{ {
case nzEventType_MouseMoved: // La souris a bougé case Nz::WindowEventType_MouseMoved: // La souris a bougé
{ {
// Gestion de la caméra free-fly (Rotation) // Gestion de la caméra free-fly (Rotation)
float sensitivity = 0.3f; // Sensibilité de la souris float sensitivity = 0.3f; // Sensibilité de la souris
// On modifie l'angle de la caméra grâce au déplacement relatif sur X de la souris // On modifie l'angle de la caméra grâce au déplacement relatif sur X de la souris
camAngles.yaw = NzNormalizeAngle(camAngles.yaw - event.mouseMove.deltaX*sensitivity); camAngles.yaw = Nz::NormalizeAngle(camAngles.yaw - event.mouseMove.deltaX*sensitivity);
// Idem, mais pour éviter les problèmes de calcul de la matrice de vue, on restreint les angles // Idem, mais pour éviter les problèmes de calcul de la matrice de vue, on restreint les angles
camAngles.pitch = NzClamp(camAngles.pitch - event.mouseMove.deltaY*sensitivity, -89.f, 89.f); camAngles.pitch = Nz::Clamp(camAngles.pitch - event.mouseMove.deltaY*sensitivity, -89.f, 89.f);
// On applique les angles d'Euler à notre caméra // On applique les angles d'Euler à notre caméra
camera.SetRotation(camAngles); cameraNode.SetRotation(camAngles);
// Pour éviter que le curseur ne sorte de l'écran, nous le renvoyons au centre de la fenêtre // Pour éviter que le curseur ne sorte de l'écran, nous le renvoyons au centre de la fenêtre
// Cette fonction est codée de sorte à ne pas provoquer d'évènement MouseMoved // Cette fonction est codée de sorte à ne pas provoquer d'évènement MouseMoved
NzMouse::SetPosition(window.GetWidth()/2, window.GetHeight()/2, window); Nz::Mouse::SetPosition(window.GetWidth()/2, window.GetHeight()/2, window);
break; break;
} }
case nzEventType_Quit: // L'utilisateur a cliqué sur la croix, ou l'OS veut terminer notre programme case Nz::WindowEventType_Quit: // L'utilisateur a cliqué sur la croix, ou l'OS veut terminer notre programme
window.Close(); // On demande la fermeture de la fenêtre (Qui aura lieu au prochain tour de boucle) window.Close(); // On demande la fermeture de la fenêtre (Qui aura lieu au prochain tour de boucle)
break; break;
case nzEventType_KeyPressed: // Une touche a été pressée ! case Nz::WindowEventType_KeyPressed: // Une touche a été pressée !
if (event.key.code == NzKeyboard::Key::Escape) if (event.key.code == Nz::Keyboard::Key::Escape)
window.Close(); window.Close();
else if (event.key.code == NzKeyboard::F1) else if (event.key.code == Nz::Keyboard::F1)
{ {
if (smoothMovement) if (smoothMovement)
{ {
targetPos = camera.GetPosition(); targetPos = cameraNode.GetPosition();
smoothMovement = false; smoothMovement = false;
} }
else else
@ -271,68 +325,63 @@ int main()
} }
} }
Nz::UInt64 elapsedUS = updateClock.GetMicroseconds();
// On relance l'horloge
updateClock.Restart();
// Mise à jour (Caméra) // Mise à jour (Caméra)
if (updateClock.GetMilliseconds() >= 1000/60) // 60 fois par seconde const Nz::UInt64 updateRate = 1000000 / 60; // 60 fois par seconde
updateAccumulator += elapsedUS;
if (updateAccumulator >= updateRate)
{ {
// Le temps écoulé depuis la dernière fois que ce bloc a été exécuté // Le temps écoulé en seconde depuis la dernière fois que ce bloc a été exécuté
float elapsedTime = updateClock.GetSeconds(); float elapsedTime = updateAccumulator / 1000000.f;
std::cout << elapsedTime << std::endl;
// Vitesse de déplacement de la caméra // Vitesse de déplacement de la caméra
float cameraSpeed = 3.f * elapsedTime; // Trois mètres par seconde float cameraSpeed = 3.f * elapsedTime; // Trois mètres par seconde
// Si la touche espace est enfoncée, notre vitesse de déplacement est multipliée par deux // Si la touche espace est enfoncée, notre vitesse de déplacement est multipliée par deux
if (NzKeyboard::IsKeyPressed(NzKeyboard::Space)) if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Space))
cameraSpeed *= 2.f; cameraSpeed *= 2.f;
// Pour que nos déplacement soient liés à la rotation de la caméra, nous allons utiliser // Pour que nos déplacement soient liés à la rotation de la caméra, nous allons utiliser
// les directions locales de la caméra // les directions locales de la caméra
// Si la flèche du haut ou la touche Z (vive ZQSD) est pressée, on avance // Si la flèche du haut ou la touche Z (vive ZQSD) est pressée, on avance
if (NzKeyboard::IsKeyPressed(NzKeyboard::Up) || NzKeyboard::IsKeyPressed(NzKeyboard::Z)) if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Up) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Z))
targetPos += camera.GetForward() * cameraSpeed; targetPos += cameraNode.GetForward() * cameraSpeed;
// Si la flèche du bas ou la touche S est pressée, on recule // Si la flèche du bas ou la touche S est pressée, on recule
if (NzKeyboard::IsKeyPressed(NzKeyboard::Down) || NzKeyboard::IsKeyPressed(NzKeyboard::S)) if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Down) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::S))
targetPos += camera.GetBackward() * cameraSpeed; targetPos += cameraNode.GetBackward() * cameraSpeed;
// Etc... // Etc...
if (NzKeyboard::IsKeyPressed(NzKeyboard::Left) || NzKeyboard::IsKeyPressed(NzKeyboard::Q)) if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Left) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Q))
targetPos += camera.GetLeft() * cameraSpeed; targetPos += cameraNode.GetLeft() * cameraSpeed;
// Etc... // Etc...
if (NzKeyboard::IsKeyPressed(NzKeyboard::Right) || NzKeyboard::IsKeyPressed(NzKeyboard::D)) if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::Right) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::D))
targetPos += camera.GetRight() * cameraSpeed; targetPos += cameraNode.GetRight() * cameraSpeed;
// Majuscule pour monter, notez l'utilisation d'une direction globale (Non-affectée par la rotation) // Majuscule pour monter, notez l'utilisation d'une direction globale (Non-affectée par la rotation)
if (NzKeyboard::IsKeyPressed(NzKeyboard::LShift) || NzKeyboard::IsKeyPressed(NzKeyboard::RShift)) if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::RShift))
targetPos += NzVector3f::Up() * cameraSpeed; targetPos += Nz::Vector3f::Up() * cameraSpeed;
// Contrôle (Gauche ou droite) pour descendre dans l'espace global, etc... // Contrôle (Gauche ou droite) pour descendre dans l'espace global, etc...
if (NzKeyboard::IsKeyPressed(NzKeyboard::LControl) || NzKeyboard::IsKeyPressed(NzKeyboard::RControl)) if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::RControl))
targetPos += NzVector3f::Down() * cameraSpeed; targetPos += Nz::Vector3f::Down() * cameraSpeed;
camera.SetPosition((smoothMovement) ? DampedString(camera.GetPosition(), targetPos, elapsedTime) : targetPos, nzCoordSys_Global); cameraNode.SetPosition((smoothMovement) ? DampedString(cameraNode.GetPosition(), targetPos, elapsedTime) : targetPos, Nz::CoordSys_Global);
// On relance l'horloge updateAccumulator = 0;
updateClock.Restart();
} }
// Rendu de la scène: // Et maintenant pour rendre la scène, il nous suffit de mettre à jour le monde en lui envoyant le temps depuis la dernière mise à jour
// On procède maintenant au rendu de la scène en elle-même, celui-ci se décompose en quatre étapes distinctes // Note: La plupart des systèmes, à l'exception de celui de rendu, ont une fréquence de mise à jour fixe (modifiable)
// Il n'est donc pas nécessaire de limiter vous-même les mises à jour du monde
// Pour commencer, on met à jour la scène, ceci appelle la méthode Update de tous les SceneNode enregistrés world.Update(elapsedUS / 1000000.f);
// pour la mise à jour globale (Scene::RegisterForUpdate)
scene.Update();
// Ensuite il y a le calcul de visibilité, la scène se sert de la caméra active pour effectuer un test de visibilité
// afin de faire une liste des SceneNode visibles (Ex: Frustum culling)
scene.Cull();
// Ensuite il y a la mise à jour des SceneNode enregistrés pour la mise à jour visible (Exemple: Terrain)
scene.UpdateVisible();
// Pour terminer, il y a l'affichage en lui-même, de façon organisée et optimisée (Batching)
scene.Draw();
// Après avoir dessiné sur la fenêtre, il faut s'assurer qu'elle affiche cela // Après avoir dessiné sur la fenêtre, il faut s'assurer qu'elle affiche cela
// Cet appel ne fait rien d'autre qu'échanger les buffers de rendu (Double Buffering) // Cet appel ne fait rien d'autre qu'échanger les buffers de rendu (Double Buffering)
@ -344,7 +393,7 @@ int main()
if (secondClock.GetMilliseconds() >= 1000) // Toutes les secondes if (secondClock.GetMilliseconds() >= 1000) // Toutes les secondes
{ {
// Et on insère ces données dans le titre de la fenêtre // Et on insère ces données dans le titre de la fenêtre
window.SetTitle(windowTitle + " - " + NzString::Number(fps) + " FPS"); window.SetTitle(windowTitle + " - " + Nz::String::Number(fps) + " FPS");
/* /*
Note: En C++11 il est possible d'insérer de l'Unicode de façon standard, quel que soit l'encodage du fichier, Note: En C++11 il est possible d'insérer de l'Unicode de façon standard, quel que soit l'encodage du fichier,
@ -364,7 +413,7 @@ int main()
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
NzVector3f DampedString(const NzVector3f& currentPos, const NzVector3f& targetPos, float frametime, float springStrength) Nz::Vector3f DampedString(const Nz::Vector3f& currentPos, const Nz::Vector3f& targetPos, float frametime, float springStrength)
{ {
// Je ne suis pas l'auteur de cette fonction // Je ne suis pas l'auteur de cette fonction
// Je l'ai reprise du programme "Floaty Camera Example" et adaptée au C++ // Je l'ai reprise du programme "Floaty Camera Example" et adaptée au C++
@ -372,13 +421,13 @@ NzVector3f DampedString(const NzVector3f& currentPos, const NzVector3f& targetPo
// Tout le mérite revient à l'auteur (Qui me permettra ainsi d'améliorer les démos, voire même le moteur) // Tout le mérite revient à l'auteur (Qui me permettra ainsi d'améliorer les démos, voire même le moteur)
// calculate the displacement between the target and the current position // calculate the displacement between the target and the current position
NzVector3f displacement = targetPos - currentPos; Nz::Vector3f displacement = targetPos - currentPos;
// whats the distance between them? // whats the distance between them?
float displacementLength = displacement.GetLength(); float displacementLength = displacement.GetLength();
// Stops small position fluctuations (integration errors probably - since only using euler) // Stops small position fluctuations (integration errors probably - since only using euler)
if (NzNumberEquals(displacementLength, 0.f)) if (Nz::NumberEquals(displacementLength, 0.f))
return currentPos; return currentPos;
float invDisplacementLength = 1.f/displacementLength; float invDisplacementLength = 1.f/displacementLength;

View File

@ -1,5 +1,5 @@
/* /*
** HardwareInfo - Récupération des caractéristiques de l'ordinateur ** Nz::HardwareInfo - Récupération des caractéristiques de l'ordinateur
** Prérequis: Aucun ** Prérequis: Aucun
** Utilisation du noyau et du module de rendu ** Utilisation du noyau et du module de rendu
** Présente: ** Présente:
@ -15,7 +15,7 @@
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
void printCap(std::ostream& o, const NzString& cap, bool b); void printCap(std::ostream& o, const Nz::String& cap, bool b);
int main() int main()
{ {
@ -28,68 +28,63 @@ int main()
// Plutôt que d'initialiser le Renderer de Nazara, nous initialisons les deux classes utilisées ici // Plutôt que d'initialiser le Renderer de Nazara, nous initialisons les deux classes utilisées ici
// Elles sont compatibles avec NzInitialiser et seront donc libérées automatiquement // Elles sont compatibles avec NzInitialiser et seront donc libérées automatiquement
// Cela permet d'avoir une initialisation plus rapide et un coût en mémoire moindre // Cela permet d'avoir une initialisation plus rapide et un coût en mémoire moindre
NzInitializer<NzHardwareInfo> hardwareInfo; Nz::Initializer<Nz::HardwareInfo> hardwareInfo;
if (hardwareInfo) if (hardwareInfo)
{ {
// On commence par les informations sur le processeur, Nazara en récupère trois caractéristiques: // On commence par les informations sur le processeur, Nazara en récupère trois caractéristiques:
// 1) La "brand string", qui est une chaîne de 48 caractères identifiant le processeur // 1) La "brand string", qui est une chaîne de 48 caractères identifiant le processeur
// 2) Le concepteur du processeur, accessible via une énumération (GetProcessorVendor) ou une chaîne de caractère (GetProcessorVendorName) // 2) Le concepteur du processeur, accessible via une énumération (GetProcessorVendor) ou une chaîne de caractère (GetProcessorVendorName)
// 3) Le nombre de processeurs logique, alias bien souvent le nombre de coeurs (logiques), cette valeur est renvoyée par l'OS (Le SMT multiplie donc la valeur réelle) // 3) Le nombre de processeurs logique, alias bien souvent le nombre de coeurs (logiques), cette valeur est renvoyée par l'OS (Le SMT multiplie donc la valeur réelle)
oss << "Identification: " << NzHardwareInfo::GetProcessorBrandString() << std::endl; oss << "Identification: " << Nz::HardwareInfo::GetProcessorBrandString() << std::endl;
oss << "Concepteur: " << NzHardwareInfo::GetProcessorVendorName() << std::endl; oss << "Concepteur: " << Nz::HardwareInfo::GetProcessorVendorName() << std::endl;
oss << "Nombre de coeurs logiques: " << NzHardwareInfo::GetProcessorCount() << std::endl; oss << "Nombre de coeurs logiques: " << Nz::HardwareInfo::GetProcessorCount() << std::endl;
oss << std::endl; oss << std::endl;
// Ensuite, Nazara récupère les capacités du processeur, dont des jeux d'extensions supplémentaires // Ensuite, Nazara récupère les capacités du processeur, dont des jeux d'extensions supplémentaires
oss << "Rapport des capacites: " << std::endl;// Pas d'accent car écriture dans un fichier (et on ne va pas s'embêter avec ça) oss << "Rapport des capacites: " << std::endl;// Pas d'accent car écriture dans un fichier (et on ne va pas s'embêter avec ça)
printCap(oss, "-64bits", NzHardwareInfo::HasCapability(nzProcessorCap_x64)); printCap(oss, "-64bits", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_x64));
printCap(oss, "-AVX", NzHardwareInfo::HasCapability(nzProcessorCap_AVX)); printCap(oss, "-AVX", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_AVX));
printCap(oss, "-FMA3", NzHardwareInfo::HasCapability(nzProcessorCap_FMA3)); printCap(oss, "-FMA3", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_FMA3));
printCap(oss, "-FMA4", NzHardwareInfo::HasCapability(nzProcessorCap_FMA4)); printCap(oss, "-FMA4", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_FMA4));
printCap(oss, "-MMX", NzHardwareInfo::HasCapability(nzProcessorCap_MMX)); printCap(oss, "-MMX", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_MMX));
printCap(oss, "-SSE", NzHardwareInfo::HasCapability(nzProcessorCap_SSE)); printCap(oss, "-SSE", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_SSE));
printCap(oss, "-SSE2", NzHardwareInfo::HasCapability(nzProcessorCap_SSE2)); printCap(oss, "-SSE2", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_SSE2));
printCap(oss, "-SSE3", NzHardwareInfo::HasCapability(nzProcessorCap_SSE3)); printCap(oss, "-SSE3", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_SSE3));
printCap(oss, "-SSSE3", NzHardwareInfo::HasCapability(nzProcessorCap_SSSE3)); printCap(oss, "-SSSE3", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_SSSE3));
printCap(oss, "-SSE4.1", NzHardwareInfo::HasCapability(nzProcessorCap_SSE41)); printCap(oss, "-SSE4.1", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_SSE41));
printCap(oss, "-SSE4.2", NzHardwareInfo::HasCapability(nzProcessorCap_SSE42)); printCap(oss, "-SSE4.2", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_SSE42));
printCap(oss, "-SSE4.a", NzHardwareInfo::HasCapability(nzProcessorCap_SSE4a)); printCap(oss, "-SSE4.a", Nz::HardwareInfo::HasCapability(Nz::ProcessorCap_SSE4a));
} }
else else
oss << "Impossible de retrouver les informations du processeur" << std::endl; oss << "Impossible de retrouver les informations du processeur" << std::endl;
oss << std::endl << "--Carte graphique--" << std::endl; oss << std::endl << "--Carte graphique--" << std::endl;
// La classe NzOpenGL nous donne accès à des informations sur la carte graphique // La classe OpenGL nous donne accès à des informations sur la carte graphique
// Cependant celle-ci n'est accessible que si le projet est compilé avec NAZARA_RENDERER_OPENGL // Cependant celle-ci n'est accessible que si le projet est compilé avec NAZARA_RENDERER_OPENGL
// et que les répertoires d'inclusions donnent accès aux includes d'OpenGL (Cette démo utilisent ceux de Nazara) // et que les répertoires d'inclusions donnent accès aux includes d'OpenGL (Cette démo utilisent ceux de Nazara)
NzInitializer<NzOpenGL> openGL; Nz::Initializer<Nz::OpenGL> openGL;
if (openGL) if (openGL)
{ {
// Nous récupérons ensuite la version d'OpenGL sous forme d'entier (ex: OpenGL 3.3 donnera 330) // Nous récupérons ensuite la version d'OpenGL sous forme d'entier (ex: OpenGL 3.3 donnera 330)
unsigned int openglVersion = NzOpenGL::GetVersion(); unsigned int openglVersion = Nz::OpenGL::GetVersion();
// NzOpenGL nous donne accès à trois informations principales: // OpenGL nous donne accès à trois informations principales:
// 1) La chaîne d'identification du driver ("Renderer name") // 1) La chaîne d'identification du driver ("Renderer name")
// 2) La chaîne d'identification du concepteur ("Vendor name") // 2) La chaîne d'identification du concepteur ("Vendor name")
// 3) La version d'OpenGL // 3) La version d'OpenGL
oss << "Identification: " << NzOpenGL::GetRendererName() << std::endl; oss << "Identification: " << Nz::OpenGL::GetRendererName() << std::endl;
oss << "Concepteur: " << NzOpenGL::GetVendorName() << std::endl; oss << "Concepteur: " << Nz::OpenGL::GetVendorName() << std::endl;
oss << "Version d'OpenGL: " << openglVersion/100 << '.' << openglVersion%100 << std::endl; oss << "Version d'OpenGL: " << openglVersion/100 << '.' << openglVersion%100 << std::endl;
oss << std::endl; oss << std::endl;
// Ainsi qu'un report des capacités de la carte graphique (avec le driver actuel) // Ainsi qu'un report des capacités de la carte graphique (avec le driver actuel)
oss << "Rapport des capacites: " << std::endl; // Pas d'accent car écriture dans un fichier (et on ne va pas s'embêter avec ça) oss << "Rapport des capacites: " << std::endl; // Pas d'accent car écriture dans un fichier (et on ne va pas s'embêter avec ça)
printCap(oss, "-Calculs 64bits", NzOpenGL::IsSupported(nzOpenGLExtension_FP64)); printCap(oss, "-Calculs 64bits", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_FP64));
printCap(oss, "-Compression de textures (s3tc)", NzOpenGL::IsSupported(nzOpenGLExtension_TextureCompression_s3tc)); printCap(oss, "-Compression de textures (s3tc)", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_TextureCompression_s3tc));
printCap(oss, "-Filtrage anisotrope", NzOpenGL::IsSupported(nzOpenGLExtension_AnisotropicFilter)); printCap(oss, "-Filtrage anisotrope", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_AnisotropicFilter));
printCap(oss, "-Framebuffer Object", NzOpenGL::IsSupported(nzOpenGLExtension_FrameBufferObject)); printCap(oss, "-Mode debug", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_DebugOutput));
printCap(oss, "-Mode debug", NzOpenGL::IsSupported(nzOpenGLExtension_DebugOutput)); printCap(oss, "-Separate shader objects", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_SeparateShaderObjects));
printCap(oss, "-Pixelbuffer Object", NzOpenGL::IsSupported(nzOpenGLExtension_PixelBufferObject)); printCap(oss, "-Texture storage", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_TextureStorage));
printCap(oss, "-Samplers Object", NzOpenGL::IsSupported(nzOpenGLExtension_SamplerObjects));
printCap(oss, "-Separate shader objects", NzOpenGL::IsSupported(nzOpenGLExtension_SeparateShaderObjects));
printCap(oss, "-Texture array", NzOpenGL::IsSupported(nzOpenGLExtension_TextureArray));
printCap(oss, "-Texture storage", NzOpenGL::IsSupported(nzOpenGLExtension_TextureStorage));
printCap(oss, "-Vertex array objects", NzOpenGL::IsSupported(nzOpenGLExtension_VertexArrayObjects));
} }
else else
oss << "Impossible de retrouver les informations de la carte graphique" << std::endl; oss << "Impossible de retrouver les informations de la carte graphique" << std::endl;
@ -99,14 +94,14 @@ int main()
std::cout << oss.str() << std::endl; std::cout << oss.str() << std::endl;
NzFile reportFile("RapportHardwareInfo.txt"); Nz::File reportFile("RapportNz::HardwareInfo.txt");
if (reportFile.Open(nzOpenMode_Text | nzOpenMode_Truncate | nzOpenMode_WriteOnly)) if (reportFile.Open(Nz::OpenMode_Text | Nz::OpenMode_Truncate | Nz::OpenMode_WriteOnly))
{ {
reportFile.Write(oss.str()); // Conversion implicite en NzString reportFile.Write(oss.str()); // Conversion implicite en Nz::String
reportFile.Close(); reportFile.Close();
char accentAigu = static_cast<char>(130); // C'est crade, mais ça marche chez 95% des Windowsiens char accentAigu = static_cast<char>(130); // C'est crade, mais ça marche chez 95% des Windowsiens
std::cout << "Un fichier (RapportHardwareInfo.txt) contenant le rapport a " << accentAigu << 't' << accentAigu << " cr" << accentAigu << accentAigu << std::endl; std::cout << "Un fichier (RapportNz::HardwareInfo.txt) contenant le rapport a " << accentAigu << 't' << accentAigu << " cr" << accentAigu << accentAigu << std::endl;
} }
else else
std::cout << "Impossible de sauvegarder le rapport" << std::endl; std::cout << "Impossible de sauvegarder le rapport" << std::endl;
@ -116,7 +111,7 @@ int main()
return 0; return 0;
} }
void printCap(std::ostream& o, const NzString& cap, bool b) void printCap(std::ostream& o, const Nz::String& cap, bool b)
{ {
if (b) if (b)
o << cap << ": Oui" << std::endl; o << cap << ": Oui" << std::endl;

View File

@ -11,7 +11,7 @@
int main() int main()
{ {
// Pour charger des ressources, il est impératif d'initialiser le module utilitaire // Pour charger des ressources, il est impératif d'initialiser le module utilitaire
NzInitializer<NzUtility> utility; Nz::Initializer<Nz::Utility> utility;
if (!utility) if (!utility)
{ {
// Ça n'a pas fonctionné, le pourquoi se trouve dans le fichier NazaraLog.log // Ça n'a pas fonctionné, le pourquoi se trouve dans le fichier NazaraLog.log
@ -22,7 +22,7 @@ int main()
for (;;) for (;;)
{ {
NzDirectory resourceDirectory("resources/"); Nz::Directory resourceDirectory("resources/");
if (!resourceDirectory.Open()) if (!resourceDirectory.Open())
{ {
std::cerr << "Failed to open resource directory" << std::endl; std::cerr << "Failed to open resource directory" << std::endl;
@ -30,12 +30,12 @@ int main()
return EXIT_FAILURE; return EXIT_FAILURE;
} }
std::vector<NzString> models; std::vector<Nz::String> models;
while (resourceDirectory.NextResult()) while (resourceDirectory.NextResult())
{ {
NzString path = resourceDirectory.GetResultName(); Nz::String path = resourceDirectory.GetResultName();
NzString ext = path.SubStringFrom('.', -1, true); // Tout ce qui vient après le dernier '.' de la chaîne Nz::String ext = path.SubStringFrom('.', -1, true); // Tout ce qui vient après le dernier '.' de la chaîne
if (NzMeshLoader::IsExtensionSupported(ext)) // L'extension est-elle supportée par le MeshLoader ? if (Nz::MeshLoader::IsExtensionSupported(ext)) // L'extension est-elle supportée par le MeshLoader ?
models.push_back(path); models.push_back(path);
} }
@ -67,7 +67,7 @@ int main()
if (iChoice == 0) if (iChoice == 0)
break; break;
NzMesh mesh; Nz::Mesh mesh;
if (!mesh.LoadFromFile("resources/" + models[iChoice-1])) if (!mesh.LoadFromFile("resources/" + models[iChoice-1]))
{ {
std::cout << "Failed to load mesh" << std::endl; std::cout << "Failed to load mesh" << std::endl;
@ -77,11 +77,11 @@ int main()
switch (mesh.GetAnimationType()) switch (mesh.GetAnimationType())
{ {
case nzAnimationType_Skeletal: case Nz::AnimationType_Skeletal:
std::cout << "This is a skeletal-animated mesh" << std::endl; std::cout << "This is a skeletal-animated mesh" << std::endl;
break; break;
case nzAnimationType_Static: case Nz::AnimationType_Static:
std::cout << "This is a static mesh" << std::endl; std::cout << "This is a static mesh" << std::endl;
break; break;
@ -92,9 +92,9 @@ int main()
if (mesh.IsAnimable()) if (mesh.IsAnimable())
{ {
if (mesh.GetAnimationType() == nzAnimationType_Skeletal) if (mesh.GetAnimationType() == Nz::AnimationType_Skeletal)
{ {
const NzSkeleton* skeleton = mesh.GetSkeleton(); const Nz::Skeleton* skeleton = mesh.GetSkeleton();
unsigned int jointCount = skeleton->GetJointCount(); unsigned int jointCount = skeleton->GetJointCount();
std::cout << "It has a skeleton made of " << skeleton->GetJointCount() << " joint(s)." << std::endl; std::cout << "It has a skeleton made of " << skeleton->GetJointCount() << " joint(s)." << std::endl;
std::cout << "Print joints ? (Y/N) "; std::cout << "Print joints ? (Y/N) ";
@ -107,10 +107,10 @@ int main()
{ {
for (unsigned int i = 0; i < jointCount; ++i) for (unsigned int i = 0; i < jointCount; ++i)
{ {
const NzJoint* joint = skeleton->GetJoint(i); const Nz::Joint* joint = skeleton->GetJoint(i);
std::cout << "\t" << (i+1) << ": " << joint->GetName(); std::cout << "\t" << (i+1) << ": " << joint->GetName();
const NzJoint* parent = static_cast<const NzJoint*>(joint->GetParent()); const Nz::Joint* parent = static_cast<const Nz::Joint*>(joint->GetParent());
if (parent) if (parent)
std::cout << " (Parent: " << parent->GetName() << ')'; std::cout << " (Parent: " << parent->GetName() << ')';
@ -119,10 +119,10 @@ int main()
} }
} }
NzString animationPath = mesh.GetAnimation(); Nz::String animationPath = mesh.GetAnimation();
if (!animationPath.IsEmpty()) if (!animationPath.IsEmpty())
{ {
NzAnimation animation; Nz::Animation animation;
if (animation.LoadFromFile(animationPath)) if (animation.LoadFromFile(animationPath))
{ {
unsigned int sequenceCount = animation.GetSequenceCount(); unsigned int sequenceCount = animation.GetSequenceCount();
@ -137,7 +137,7 @@ int main()
{ {
for (unsigned int i = 0; i < sequenceCount; ++i) for (unsigned int i = 0; i < sequenceCount; ++i)
{ {
const NzSequence* sequence = animation.GetSequence(i); const Nz::Sequence* sequence = animation.GetSequence(i);
std::cout << "\t" << (i+1) << ": " << sequence->name << std::endl; std::cout << "\t" << (i+1) << ": " << sequence->name << std::endl;
std::cout << "\t\tStart frame: " << sequence->firstFrame << std::endl; std::cout << "\t\tStart frame: " << sequence->firstFrame << std::endl;
std::cout << "\t\tFrame count: " << sequence->frameCount << std::endl; std::cout << "\t\tFrame count: " << sequence->frameCount << std::endl;
@ -153,7 +153,7 @@ int main()
std::cout << "It's animable but has no animation information" << std::endl; std::cout << "It's animable but has no animation information" << std::endl;
} }
NzBoxf cube = mesh.GetAABB(); Nz::Boxf cube = mesh.GetAABB();
std::cout << "Mesh is " << cube.width << " units wide, " << cube.height << " units height and " << cube.depth << " units depth" << std::endl; std::cout << "Mesh is " << cube.width << " units wide, " << cube.height << " units height and " << cube.depth << " units depth" << std::endl;
unsigned int materialCount = mesh.GetMaterialCount(); unsigned int materialCount = mesh.GetMaterialCount();

View File

@ -9,7 +9,10 @@
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
template<typename T> void NzMixToMono(T* input, T* output, unsigned int channelCount, unsigned int frameCount); namespace Nz
{
template<typename T> void MixToMono(T* input, T* output, unsigned int channelCount, unsigned int frameCount);
}
#include <Nazara/Audio/Algorithm.inl> #include <Nazara/Audio/Algorithm.inl>

View File

@ -5,21 +5,24 @@
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Audio/Debug.hpp> #include <Nazara/Audio/Debug.hpp>
template<typename T> namespace Nz
void NzMixToMono(T* input, T* output, unsigned int channelCount, unsigned int frameCount)
{ {
///DOC: Le buffer d'entrée peut être le même que le buffer de sortie template<typename T>
// Pour éviter l'overflow, on utilise comme accumulateur un type assez grand, (u)int 64 bits pour les entiers, double pour les flottants void MixToMono(T* input, T* output, unsigned int channelCount, unsigned int frameCount)
typedef typename std::conditional<std::is_unsigned<T>::value, nzUInt64, nzInt64>::type BiggestInt;
typedef typename std::conditional<std::is_integral<T>::value, BiggestInt, double>::type Biggest;
for (unsigned int i = 0; i < frameCount; ++i)
{ {
Biggest acc = Biggest(0); ///DOC: Le buffer d'entrée peut être le même que le buffer de sortie
for (unsigned int j = 0; j < channelCount; ++j) // Pour éviter l'overflow, on utilise comme accumulateur un type assez grand, (u)int 64 bits pour les entiers, double pour les flottants
acc += input[i*channelCount + j]; typedef typename std::conditional<std::is_unsigned<T>::value, UInt64, Int64>::type BiggestInt;
typedef typename std::conditional<std::is_integral<T>::value, BiggestInt, double>::type Biggest;
output[i] = static_cast<T>(acc/channelCount); for (unsigned int i = 0; i < frameCount; ++i)
{
Biggest acc = Biggest(0);
for (unsigned int j = 0; j < channelCount; ++j)
acc += input[i*channelCount + j];
output[i] = static_cast<T>(acc / channelCount);
}
} }
} }

View File

@ -14,41 +14,44 @@
#include <Nazara/Math/Quaternion.hpp> #include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Vector3.hpp> #include <Nazara/Math/Vector3.hpp>
class NAZARA_AUDIO_API NzAudio namespace Nz
{ {
public: class NAZARA_AUDIO_API Audio
NzAudio() = delete; {
~NzAudio() = delete; public:
Audio() = delete;
~Audio() = delete;
static nzAudioFormat GetAudioFormat(unsigned int channelCount); static AudioFormat GetAudioFormat(unsigned int channelCount);
static float GetDopplerFactor(); static float GetDopplerFactor();
static float GetGlobalVolume(); static float GetGlobalVolume();
static NzVector3f GetListenerDirection(); static Vector3f GetListenerDirection();
static NzVector3f GetListenerPosition(); static Vector3f GetListenerPosition();
static NzQuaternionf GetListenerRotation(); static Quaternionf GetListenerRotation();
static NzVector3f GetListenerVelocity(); static Vector3f GetListenerVelocity();
static float GetSpeedOfSound(); static float GetSpeedOfSound();
static bool Initialize(); static bool Initialize();
static bool IsFormatSupported(nzAudioFormat format); static bool IsFormatSupported(AudioFormat format);
static bool IsInitialized(); static bool IsInitialized();
static void SetDopplerFactor(float dopplerFactor); static void SetDopplerFactor(float dopplerFactor);
static void SetGlobalVolume(float volume); static void SetGlobalVolume(float volume);
static void SetListenerDirection(const NzVector3f& direction); static void SetListenerDirection(const Vector3f& direction);
static void SetListenerDirection(float dirX, float dirY, float dirZ); static void SetListenerDirection(float dirX, float dirY, float dirZ);
static void SetListenerPosition(const NzVector3f& position); static void SetListenerPosition(const Vector3f& position);
static void SetListenerPosition(float x, float y, float z); static void SetListenerPosition(float x, float y, float z);
static void SetListenerRotation(const NzQuaternionf& rotation); static void SetListenerRotation(const Quaternionf& rotation);
static void SetListenerVelocity(const NzVector3f& velocity); static void SetListenerVelocity(const Vector3f& velocity);
static void SetListenerVelocity(float velX, float velY, float velZ); static void SetListenerVelocity(float velX, float velY, float velZ);
static void SetSpeedOfSound(float speed); static void SetSpeedOfSound(float speed);
static void Uninitialize(); static void Uninitialize();
private: private:
static unsigned int s_moduleReferenceCounter; static unsigned int s_moduleReferenceCounter;
}; };
}
#endif // NAZARA_AUDIO_HPP #endif // NAZARA_AUDIO_HPP

View File

@ -15,7 +15,7 @@
// 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_AUDIO_MANAGE_MEMORY #if defined(NAZARA_DEBUG) && !NAZARA_AUDIO_MANAGE_MEMORY
#undef NAZARA_AUDIO_MANAGE_MEMORY #undef NAZARA_AUDIO_MANAGE_MEMORY
#define NAZARA_AUDIO_MANAGE_MEMORY 1 #define NAZARA_AUDIO_MANAGE_MEMORY 0
#endif #endif
NazaraCheckTypeAndVal(NAZARA_AUDIO_STREAMED_BUFFER_COUNT, integral, >, 0, " shall be a strictly positive integer"); NazaraCheckTypeAndVal(NAZARA_AUDIO_STREAMED_BUFFER_COUNT, integral, >, 0, " shall be a strictly positive integer");

View File

@ -4,29 +4,32 @@
#pragma once #pragma once
#ifndef NAZARA_ENUMS_HPP #ifndef NAZARA_ENUMS_AUDIO_HPP
#define NAZARA_ENUMS_HPP #define NAZARA_ENUMS_AUDIO_HPP
enum nzAudioFormat namespace Nz
{ {
nzAudioFormat_Unknown = -1, enum AudioFormat
{
AudioFormat_Unknown = -1,
// La valeur entière est le nombre de canaux possédés par ce format // La valeur entière est le nombre de canaux possédés par ce format
nzAudioFormat_Mono = 1, AudioFormat_Mono = 1,
nzAudioFormat_Stereo = 2, AudioFormat_Stereo = 2,
nzAudioFormat_Quad = 4, AudioFormat_Quad = 4,
nzAudioFormat_5_1 = 6, AudioFormat_5_1 = 6,
nzAudioFormat_6_1 = 7, AudioFormat_6_1 = 7,
nzAudioFormat_7_1 = 8, AudioFormat_7_1 = 8,
nzAudioFormat_Max = nzAudioFormat_7_1 AudioFormat_Max = AudioFormat_7_1
}; };
enum nzSoundStatus enum SoundStatus
{ {
nzSoundStatus_Playing, SoundStatus_Playing,
nzSoundStatus_Paused, SoundStatus_Paused,
nzSoundStatus_Stopped SoundStatus_Stopped
}; };
}
#endif // NAZARA_ENUMS_HPP #endif // NAZARA_ENUMS_AUDIO_HPP

View File

@ -13,60 +13,68 @@
#include <Nazara/Core/Resource.hpp> #include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceLoader.hpp> #include <Nazara/Core/ResourceLoader.hpp>
struct NzMusicParams namespace Nz
{ {
bool forceMono = false; struct MusicParams
{
bool forceMono = false;
bool IsValid() const; bool IsValid() const;
}; };
class NzMusic; class Music;
class NzSoundStream; class SoundStream;
using NzMusicLoader = NzResourceLoader<NzMusic, NzMusicParams>; using MusicLoader = ResourceLoader<Music, MusicParams>;
struct NzMusicImpl; struct MusicImpl;
class NAZARA_AUDIO_API NzMusic : public NzResource, public NzSoundEmitter, NzNonCopyable class NAZARA_AUDIO_API Music : public Resource, public SoundEmitter
{ {
friend NzMusicLoader; friend MusicLoader;
public: public:
NzMusic() = default; Music() = default;
~NzMusic(); Music(const Music&) = delete;
Music(Music&&) = delete; ///TODO
~Music();
bool Create(NzSoundStream* soundStream); bool Create(SoundStream* soundStream);
void Destroy(); void Destroy();
void EnableLooping(bool loop); void EnableLooping(bool loop);
nzUInt32 GetDuration() const; UInt32 GetDuration() const;
nzAudioFormat GetFormat() const; AudioFormat GetFormat() const;
nzUInt32 GetPlayingOffset() const; UInt32 GetPlayingOffset() const;
unsigned int GetSampleCount() const; UInt32 GetSampleCount() const;
unsigned int GetSampleRate() const; UInt32 GetSampleRate() const;
nzSoundStatus GetStatus() const; SoundStatus GetStatus() const;
bool IsLooping() const; bool IsLooping() const;
bool OpenFromFile(const NzString& filePath, const NzMusicParams& params = NzMusicParams()); bool OpenFromFile(const String& filePath, const MusicParams& params = MusicParams());
bool OpenFromMemory(const void* data, std::size_t size, const NzMusicParams& params = NzMusicParams()); bool OpenFromMemory(const void* data, std::size_t size, const MusicParams& params = MusicParams());
bool OpenFromStream(NzInputStream& stream, const NzMusicParams& params = NzMusicParams()); bool OpenFromStream(Stream& stream, const MusicParams& params = MusicParams());
void Pause(); void Pause();
void Play(); void Play();
void SetPlayingOffset(nzUInt32 offset); void SetPlayingOffset(UInt32 offset);
void Stop(); void Stop();
private: Music& operator=(const Music&) = delete;
NzMusicImpl* m_impl = nullptr; Music& operator=(Music&&) = delete; ///TODO
bool FillAndQueueBuffer(unsigned int buffer); private:
void MusicThread(); MusicImpl* m_impl = nullptr;
static NzMusicLoader::LoaderList s_loaders; bool FillAndQueueBuffer(unsigned int buffer);
}; void MusicThread();
static MusicLoader::LoaderList s_loaders;
};
}
#endif // NAZARA_MUSIC_HPP #endif // NAZARA_MUSIC_HPP

View File

@ -20,168 +20,171 @@
// Étant donné que les headers OpenAL ne nous permettent pas de n'avoir que les signatures sans les pointeurs de fonctions // Étant donné que les headers OpenAL ne nous permettent pas de n'avoir que les signatures sans les pointeurs de fonctions
// Et que je ne souhaite pas les modifier, je suis contraint de les placer dans un espace de nom différent pour ensuite // Et que je ne souhaite pas les modifier, je suis contraint de les placer dans un espace de nom différent pour ensuite
// remettre dans l'espace global les choses intéressantes (les typedef notamment) // remettre dans l'espace global les choses intéressantes (les typedef notamment)
namespace NzOpenALDetail namespace OpenALDetail
{ {
#include <AL/al.h> #include <AL/al.h>
#include <AL/alc.h> #include <AL/alc.h>
} }
// Si quelqu'un a une meilleure idée ... // Si quelqu'un a une meilleure idée ...
using NzOpenALDetail::ALboolean; using OpenALDetail::ALboolean;
using NzOpenALDetail::ALbyte; using OpenALDetail::ALbyte;
using NzOpenALDetail::ALchar; using OpenALDetail::ALchar;
using NzOpenALDetail::ALdouble; using OpenALDetail::ALdouble;
using NzOpenALDetail::ALenum; using OpenALDetail::ALenum;
using NzOpenALDetail::ALfloat; using OpenALDetail::ALfloat;
using NzOpenALDetail::ALint; using OpenALDetail::ALint;
using NzOpenALDetail::ALshort; using OpenALDetail::ALshort;
using NzOpenALDetail::ALsizei; using OpenALDetail::ALsizei;
using NzOpenALDetail::ALubyte; using OpenALDetail::ALubyte;
using NzOpenALDetail::ALuint; using OpenALDetail::ALuint;
using NzOpenALDetail::ALushort; using OpenALDetail::ALushort;
using NzOpenALDetail::ALvoid; using OpenALDetail::ALvoid;
using NzOpenALDetail::ALCboolean; using OpenALDetail::ALCboolean;
using NzOpenALDetail::ALCbyte; using OpenALDetail::ALCbyte;
using NzOpenALDetail::ALCchar; using OpenALDetail::ALCchar;
using NzOpenALDetail::ALCcontext; using OpenALDetail::ALCcontext;
using NzOpenALDetail::ALCdevice; using OpenALDetail::ALCdevice;
using NzOpenALDetail::ALCdouble; using OpenALDetail::ALCdouble;
using NzOpenALDetail::ALCenum; using OpenALDetail::ALCenum;
using NzOpenALDetail::ALCfloat; using OpenALDetail::ALCfloat;
using NzOpenALDetail::ALCint; using OpenALDetail::ALCint;
using NzOpenALDetail::ALCshort; using OpenALDetail::ALCshort;
using NzOpenALDetail::ALCsizei; using OpenALDetail::ALCsizei;
using NzOpenALDetail::ALCubyte; using OpenALDetail::ALCubyte;
using NzOpenALDetail::ALCuint; using OpenALDetail::ALCuint;
using NzOpenALDetail::ALCushort; using OpenALDetail::ALCushort;
using NzOpenALDetail::ALCvoid; using OpenALDetail::ALCvoid;
using NzOpenALFunc = void (*)(); namespace Nz
class NAZARA_AUDIO_API NzOpenAL
{ {
public: using OpenALFunc = void(*)();
static NzOpenALFunc GetEntry(const NzString& entryPoint);
static NzString GetRendererName();
static NzString GetVendorName();
static unsigned int GetVersion();
static bool Initialize(bool openDevice = true); class NAZARA_AUDIO_API OpenAL
{
public:
static OpenALFunc GetEntry(const String& entryPoint);
static String GetRendererName();
static String GetVendorName();
static unsigned int GetVersion();
static bool IsInitialized(); static bool Initialize(bool openDevice = true);
static unsigned int QueryInputDevices(std::vector<NzString>& devices); static bool IsInitialized();
static unsigned int QueryOutputDevices(std::vector<NzString>& devices);
static bool SetDevice(const NzString& deviceName); static unsigned int QueryInputDevices(std::vector<String>& devices);
static unsigned int QueryOutputDevices(std::vector<String>& devices);
static void Uninitialize(); static bool SetDevice(const String& deviceName);
static ALenum AudioFormat[nzAudioFormat_Max+1]; static void Uninitialize();
private: static ALenum AudioFormat[AudioFormat_Max + 1];
static void CloseDevice();
static bool OpenDevice(); private:
static NzOpenALFunc LoadEntry(const char* name, bool throwException = false); static void CloseDevice();
}; static bool OpenDevice();
static OpenALFunc LoadEntry(const char* name, bool throwException = false);
};
}
// al // al
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFER3F alBuffer3f; NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFER3F alBuffer3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFER3I alBuffer3i; NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFER3I alBuffer3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFERDATA alBufferData; NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERDATA alBufferData;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFERF alBufferf; NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERF alBufferf;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFERFV alBufferfv; NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERFV alBufferfv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFERI alBufferi; NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERI alBufferi;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFERIV alBufferiv; NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERIV alBufferiv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDELETEBUFFERS alDeleteBuffers; NAZARA_AUDIO_API extern OpenALDetail::LPALDELETEBUFFERS alDeleteBuffers;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDELETESOURCES alDeleteSources; NAZARA_AUDIO_API extern OpenALDetail::LPALDELETESOURCES alDeleteSources;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDISABLE alDisable; NAZARA_AUDIO_API extern OpenALDetail::LPALDISABLE alDisable;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDISTANCEMODEL alDistanceModel; NAZARA_AUDIO_API extern OpenALDetail::LPALDISTANCEMODEL alDistanceModel;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDOPPLERFACTOR alDopplerFactor; NAZARA_AUDIO_API extern OpenALDetail::LPALDOPPLERFACTOR alDopplerFactor;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDOPPLERVELOCITY alDopplerVelocity; NAZARA_AUDIO_API extern OpenALDetail::LPALDOPPLERVELOCITY alDopplerVelocity;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALENABLE alEnable; NAZARA_AUDIO_API extern OpenALDetail::LPALENABLE alEnable;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGENBUFFERS alGenBuffers; NAZARA_AUDIO_API extern OpenALDetail::LPALGENBUFFERS alGenBuffers;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGENSOURCES alGenSources; NAZARA_AUDIO_API extern OpenALDetail::LPALGENSOURCES alGenSources;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBOOLEAN alGetBoolean; NAZARA_AUDIO_API extern OpenALDetail::LPALGETBOOLEAN alGetBoolean;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBOOLEANV alGetBooleanv; NAZARA_AUDIO_API extern OpenALDetail::LPALGETBOOLEANV alGetBooleanv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFER3F alGetBuffer3f; NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFER3F alGetBuffer3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFER3I alGetBuffer3i; NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFER3I alGetBuffer3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFERF alGetBufferf; NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERF alGetBufferf;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFERFV alGetBufferfv; NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERFV alGetBufferfv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFERI alGetBufferi; NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERI alGetBufferi;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFERIV alGetBufferiv; NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERIV alGetBufferiv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETDOUBLE alGetDouble; NAZARA_AUDIO_API extern OpenALDetail::LPALGETDOUBLE alGetDouble;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETDOUBLEV alGetDoublev; NAZARA_AUDIO_API extern OpenALDetail::LPALGETDOUBLEV alGetDoublev;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETENUMVALUE alGetEnumValue; NAZARA_AUDIO_API extern OpenALDetail::LPALGETENUMVALUE alGetEnumValue;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETERROR alGetError; NAZARA_AUDIO_API extern OpenALDetail::LPALGETERROR alGetError;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETFLOAT alGetFloat; NAZARA_AUDIO_API extern OpenALDetail::LPALGETFLOAT alGetFloat;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETFLOATV alGetFloatv; NAZARA_AUDIO_API extern OpenALDetail::LPALGETFLOATV alGetFloatv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETINTEGER alGetInteger; NAZARA_AUDIO_API extern OpenALDetail::LPALGETINTEGER alGetInteger;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETINTEGERV alGetIntegerv; NAZARA_AUDIO_API extern OpenALDetail::LPALGETINTEGERV alGetIntegerv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENER3F alGetListener3f; NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENER3F alGetListener3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENER3I alGetListener3i; NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENER3I alGetListener3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENERF alGetListenerf; NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERF alGetListenerf;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENERFV alGetListenerfv; NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERFV alGetListenerfv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENERI alGetListeneri; NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERI alGetListeneri;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENERIV alGetListeneriv; NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERIV alGetListeneriv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETPROCADDRESS alGetProcAddress; NAZARA_AUDIO_API extern OpenALDetail::LPALGETPROCADDRESS alGetProcAddress;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCE3F alGetSource3f; NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCE3F alGetSource3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCE3I alGetSource3i; NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCE3I alGetSource3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCEF alGetSourcef; NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEF alGetSourcef;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCEFV alGetSourcefv; NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEFV alGetSourcefv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCEI alGetSourcei; NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEI alGetSourcei;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCEIV alGetSourceiv; NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEIV alGetSourceiv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSTRING alGetString; NAZARA_AUDIO_API extern OpenALDetail::LPALGETSTRING alGetString;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALISBUFFER alIsBuffer; NAZARA_AUDIO_API extern OpenALDetail::LPALISBUFFER alIsBuffer;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALISENABLED alIsEnabled; NAZARA_AUDIO_API extern OpenALDetail::LPALISENABLED alIsEnabled;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALISEXTENSIONPRESENT alIsExtensionPresent; NAZARA_AUDIO_API extern OpenALDetail::LPALISEXTENSIONPRESENT alIsExtensionPresent;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALISSOURCE alIsSource; NAZARA_AUDIO_API extern OpenALDetail::LPALISSOURCE alIsSource;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENER3F alListener3f; NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENER3F alListener3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENER3I alListener3i; NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENER3I alListener3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENERF alListenerf; NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERF alListenerf;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENERFV alListenerfv; NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERFV alListenerfv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENERI alListeneri; NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERI alListeneri;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENERIV alListeneriv; NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERIV alListeneriv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCE3F alSource3f; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCE3F alSource3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCE3I alSource3i; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCE3I alSource3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEF alSourcef; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEF alSourcef;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEFV alSourcefv; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEFV alSourcefv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEI alSourcei; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEI alSourcei;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEIV alSourceiv; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEIV alSourceiv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEPAUSE alSourcePause; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPAUSE alSourcePause;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEPAUSEV alSourcePausev; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPAUSEV alSourcePausev;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEPLAY alSourcePlay; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPLAY alSourcePlay;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEPLAYV alSourcePlayv; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPLAYV alSourcePlayv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEQUEUEBUFFERS alSourceQueueBuffers; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEQUEUEBUFFERS alSourceQueueBuffers;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEREWIND alSourceRewind; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEREWIND alSourceRewind;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEREWINDV alSourceRewindv; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEREWINDV alSourceRewindv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCESTOP alSourceStop; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCESTOP alSourceStop;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCESTOPV alSourceStopv; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCESTOPV alSourceStopv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEUNQUEUEBUFFERS alSourceUnqueueBuffers; NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEUNQUEUEBUFFERS alSourceUnqueueBuffers;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSPEEDOFSOUND alSpeedOfSound; NAZARA_AUDIO_API extern OpenALDetail::LPALSPEEDOFSOUND alSpeedOfSound;
// alc // alc
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCAPTURECLOSEDEVICE alcCaptureCloseDevice; NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURECLOSEDEVICE alcCaptureCloseDevice;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCAPTUREOPENDEVICE alcCaptureOpenDevice; NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTUREOPENDEVICE alcCaptureOpenDevice;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCAPTURESAMPLES alcCaptureSamples; NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURESAMPLES alcCaptureSamples;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCAPTURESTART alcCaptureStart; NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURESTART alcCaptureStart;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCAPTURESTOP alcCaptureStop; NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURESTOP alcCaptureStop;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCLOSEDEVICE alcCloseDevice; NAZARA_AUDIO_API extern OpenALDetail::LPALCCLOSEDEVICE alcCloseDevice;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCREATECONTEXT alcCreateContext; NAZARA_AUDIO_API extern OpenALDetail::LPALCCREATECONTEXT alcCreateContext;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCDESTROYCONTEXT alcDestroyContext; NAZARA_AUDIO_API extern OpenALDetail::LPALCDESTROYCONTEXT alcDestroyContext;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETCONTEXTSDEVICE alcGetContextsDevice; NAZARA_AUDIO_API extern OpenALDetail::LPALCGETCONTEXTSDEVICE alcGetContextsDevice;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETCURRENTCONTEXT alcGetCurrentContext; NAZARA_AUDIO_API extern OpenALDetail::LPALCGETCURRENTCONTEXT alcGetCurrentContext;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETENUMVALUE alcGetEnumValue; NAZARA_AUDIO_API extern OpenALDetail::LPALCGETENUMVALUE alcGetEnumValue;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETERROR alcGetError; NAZARA_AUDIO_API extern OpenALDetail::LPALCGETERROR alcGetError;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETINTEGERV alcGetIntegerv; NAZARA_AUDIO_API extern OpenALDetail::LPALCGETINTEGERV alcGetIntegerv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETPROCADDRESS alcGetProcAddress; NAZARA_AUDIO_API extern OpenALDetail::LPALCGETPROCADDRESS alcGetProcAddress;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETSTRING alcGetString; NAZARA_AUDIO_API extern OpenALDetail::LPALCGETSTRING alcGetString;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCISEXTENSIONPRESENT alcIsExtensionPresent; NAZARA_AUDIO_API extern OpenALDetail::LPALCISEXTENSIONPRESENT alcIsExtensionPresent;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCMAKECONTEXTCURRENT alcMakeContextCurrent; NAZARA_AUDIO_API extern OpenALDetail::LPALCMAKECONTEXTCURRENT alcMakeContextCurrent;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCOPENDEVICE alcOpenDevice; NAZARA_AUDIO_API extern OpenALDetail::LPALCOPENDEVICE alcOpenDevice;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCPROCESSCONTEXT alcProcessContext; NAZARA_AUDIO_API extern OpenALDetail::LPALCPROCESSCONTEXT alcProcessContext;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCSUSPENDCONTEXT alcSuspendContext; NAZARA_AUDIO_API extern OpenALDetail::LPALCSUSPENDCONTEXT alcSuspendContext;
#endif // NAZARA_AUDIO_OPENAL #endif // NAZARA_AUDIO_OPENAL

View File

@ -12,39 +12,46 @@
#include <Nazara/Audio/SoundBuffer.hpp> #include <Nazara/Audio/SoundBuffer.hpp>
#include <Nazara/Audio/SoundEmitter.hpp> #include <Nazara/Audio/SoundEmitter.hpp>
class NAZARA_AUDIO_API NzSound : public NzSoundEmitter namespace Nz
{ {
public: class NAZARA_AUDIO_API Sound : public SoundEmitter
NzSound() = default; {
NzSound(const NzSoundBuffer* soundBuffer); public:
NzSound(const NzSound& sound); Sound() = default;
~NzSound(); Sound(const SoundBuffer* soundBuffer);
Sound(const Sound& sound);
Sound(Sound&&) = default;
~Sound();
void EnableLooping(bool loop); void EnableLooping(bool loop);
const NzSoundBuffer* GetBuffer() const; const SoundBuffer* GetBuffer() const;
nzUInt32 GetDuration() const; UInt32 GetDuration() const;
nzUInt32 GetPlayingOffset() const; UInt32 GetPlayingOffset() const;
nzSoundStatus GetStatus() const; SoundStatus GetStatus() const;
bool IsLooping() const; bool IsLooping() const;
bool IsPlayable() const; bool IsPlayable() const;
bool IsPlaying() const; bool IsPlaying() const;
bool LoadFromFile(const NzString& filePath, const NzSoundBufferParams& params = NzSoundBufferParams()); bool LoadFromFile(const String& filePath, const SoundBufferParams& params = SoundBufferParams());
bool LoadFromMemory(const void* data, std::size_t size, const NzSoundBufferParams& params = NzSoundBufferParams()); bool LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params = SoundBufferParams());
bool LoadFromStream(NzInputStream& stream, const NzSoundBufferParams& params = NzSoundBufferParams()); bool LoadFromStream(Stream& stream, const SoundBufferParams& params = SoundBufferParams());
void Pause(); void Pause();
void Play(); void Play();
void SetBuffer(const NzSoundBuffer* buffer); void SetBuffer(const SoundBuffer* buffer);
void SetPlayingOffset(nzUInt32 offset); void SetPlayingOffset(UInt32 offset);
void Stop(); void Stop();
private: Sound& operator=(const Sound&) = delete; ///TODO?
NzSoundBufferConstRef m_buffer; Sound& operator=(Sound&&) = default;
};
private:
SoundBufferConstRef m_buffer;
};
}
#endif // NAZARA_SOUND_HPP #endif // NAZARA_SOUND_HPP

View File

@ -10,8 +10,6 @@
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Audio/Config.hpp> #include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/Enums.hpp> #include <Nazara/Audio/Enums.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/ObjectRef.hpp> #include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/ObjectLibrary.hpp> #include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/RefCounted.hpp> #include <Nazara/Core/RefCounted.hpp>
@ -19,73 +17,82 @@
#include <Nazara/Core/ResourceLoader.hpp> #include <Nazara/Core/ResourceLoader.hpp>
#include <Nazara/Core/ResourceManager.hpp> #include <Nazara/Core/ResourceManager.hpp>
#include <Nazara/Core/Signal.hpp> #include <Nazara/Core/Signal.hpp>
#include <Nazara/Core/Stream.hpp>
struct NzSoundBufferParams namespace Nz
{ {
bool forceMono = false; struct SoundBufferParams
{
bool IsValid() const; bool forceMono = false;
};
class NzSound;
class NzSoundBuffer;
using NzSoundBufferConstRef = NzObjectRef<const NzSoundBuffer>;
using NzSoundBufferLibrary = NzObjectLibrary<NzSoundBuffer>;
using NzSoundBufferLoader = NzResourceLoader<NzSoundBuffer, NzSoundBufferParams>;
using NzSoundBufferManager = NzResourceManager<NzSoundBuffer, NzSoundBufferParams>;
using NzSoundBufferRef = NzObjectRef<NzSoundBuffer>;
struct NzSoundBufferImpl;
class NAZARA_AUDIO_API NzSoundBuffer : public NzRefCounted, public NzResource, NzNonCopyable
{
friend NzSound;
friend NzSoundBufferLibrary;
friend NzSoundBufferLoader;
friend NzSoundBufferManager;
friend class NzAudio;
public:
NzSoundBuffer() = default;
NzSoundBuffer(nzAudioFormat format, unsigned int sampleCount, unsigned int sampleRate, const nzInt16* samples);
~NzSoundBuffer();
bool Create(nzAudioFormat format, unsigned int sampleCount, unsigned int sampleRate, const nzInt16* samples);
void Destroy();
nzUInt32 GetDuration() const;
nzAudioFormat GetFormat() const;
const nzInt16* GetSamples() const;
unsigned int GetSampleCount() const;
unsigned int GetSampleRate() const;
bool IsValid() const; bool IsValid() const;
};
bool LoadFromFile(const NzString& filePath, const NzSoundBufferParams& params = NzSoundBufferParams()); class Sound;
bool LoadFromMemory(const void* data, std::size_t size, const NzSoundBufferParams& params = NzSoundBufferParams()); class SoundBuffer;
bool LoadFromStream(NzInputStream& stream, const NzSoundBufferParams& params = NzSoundBufferParams());
static bool IsFormatSupported(nzAudioFormat format); using SoundBufferConstRef = ObjectRef<const SoundBuffer>;
template<typename... Args> static NzSoundBufferRef New(Args&&... args); using SoundBufferLibrary = ObjectLibrary<SoundBuffer>;
using SoundBufferLoader = ResourceLoader<SoundBuffer, SoundBufferParams>;
using SoundBufferManager = ResourceManager<SoundBuffer, SoundBufferParams>;
using SoundBufferRef = ObjectRef<SoundBuffer>;
// Signals: struct SoundBufferImpl;
NazaraSignal(OnSoundBufferDestroy, const NzSoundBuffer* /*soundBuffer*/);
NazaraSignal(OnSoundBufferRelease, const NzSoundBuffer* /*soundBuffer*/);
private: class NAZARA_AUDIO_API SoundBuffer : public RefCounted, public Resource
unsigned int GetOpenALBuffer() const; {
friend Sound;
friend SoundBufferLibrary;
friend SoundBufferLoader;
friend SoundBufferManager;
friend class Audio;
static bool Initialize(); public:
static void Uninitialize(); SoundBuffer() = default;
SoundBuffer(AudioFormat format, unsigned int sampleCount, unsigned int sampleRate, const Int16* samples);
SoundBuffer(const SoundBuffer&) = delete;
SoundBuffer(SoundBuffer&&) = delete;
~SoundBuffer();
NzSoundBufferImpl* m_impl = nullptr; bool Create(AudioFormat format, unsigned int sampleCount, unsigned int sampleRate, const Int16* samples);
void Destroy();
static NzSoundBufferLibrary::LibraryMap s_library; UInt32 GetDuration() const;
static NzSoundBufferLoader::LoaderList s_loaders; AudioFormat GetFormat() const;
static NzSoundBufferManager::ManagerMap s_managerMap; const Int16* GetSamples() const;
static NzSoundBufferManager::ManagerParams s_managerParameters; UInt32 GetSampleCount() const;
}; UInt32 GetSampleRate() const;
bool IsValid() const;
bool LoadFromFile(const String& filePath, const SoundBufferParams& params = SoundBufferParams());
bool LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params = SoundBufferParams());
bool LoadFromStream(Stream& stream, const SoundBufferParams& params = SoundBufferParams());
static bool IsFormatSupported(AudioFormat format);
template<typename... Args> static SoundBufferRef New(Args&&... args);
SoundBuffer& operator=(const SoundBuffer&) = delete;
SoundBuffer& operator=(SoundBuffer&&) = delete; ///TODO
// Signals:
NazaraSignal(OnSoundBufferDestroy, const SoundBuffer* /*soundBuffer*/);
NazaraSignal(OnSoundBufferRelease, const SoundBuffer* /*soundBuffer*/);
private:
unsigned int GetOpenALBuffer() const;
static bool Initialize();
static void Uninitialize();
SoundBufferImpl* m_impl = nullptr;
static SoundBufferLibrary::LibraryMap s_library;
static SoundBufferLoader::LoaderList s_loaders;
static SoundBufferManager::ManagerMap s_managerMap;
static SoundBufferManager::ManagerParams s_managerParameters;
};
}
#include <Nazara/Audio/SoundBuffer.inl> #include <Nazara/Audio/SoundBuffer.inl>

View File

@ -5,13 +5,16 @@
#include <memory> #include <memory>
#include <Nazara/Audio/Debug.hpp> #include <Nazara/Audio/Debug.hpp>
template<typename... Args> namespace Nz
NzSoundBufferRef NzSoundBuffer::New(Args&&... args)
{ {
std::unique_ptr<NzSoundBuffer> object(new NzSoundBuffer(std::forward<Args>(args)...)); template<typename... Args>
object->SetPersistent(false); SoundBufferRef SoundBuffer::New(Args&&... args)
{
std::unique_ptr<SoundBuffer> object(new SoundBuffer(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release(); return object.release();
}
} }
#include <Nazara/Audio/DebugOff.hpp> #include <Nazara/Audio/DebugOff.hpp>

View File

@ -10,54 +10,58 @@
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Audio/Config.hpp> #include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/Enums.hpp> #include <Nazara/Audio/Enums.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Math/Vector3.hpp> #include <Nazara/Math/Vector3.hpp>
///TODO: Faire hériter SoundEmitter de Node ///TODO: Faire hériter SoundEmitter de Node
class NAZARA_AUDIO_API NzSoundEmitter namespace Nz
{ {
public: class NAZARA_AUDIO_API SoundEmitter
virtual ~NzSoundEmitter(); {
public:
virtual ~SoundEmitter();
virtual void EnableLooping(bool loop) = 0; virtual void EnableLooping(bool loop) = 0;
void EnableSpatialization(bool spatialization); void EnableSpatialization(bool spatialization);
float GetAttenuation() const; float GetAttenuation() const;
virtual nzUInt32 GetDuration() const = 0; virtual UInt32 GetDuration() const = 0;
float GetMinDistance() const; float GetMinDistance() const;
float GetPitch() const; float GetPitch() const;
virtual nzUInt32 GetPlayingOffset() const = 0; virtual UInt32 GetPlayingOffset() const = 0;
NzVector3f GetPosition() const; Vector3f GetPosition() const;
NzVector3f GetVelocity() const; Vector3f GetVelocity() const;
virtual nzSoundStatus GetStatus() const = 0; virtual SoundStatus GetStatus() const = 0;
float GetVolume() const; float GetVolume() const;
virtual bool IsLooping() const = 0; virtual bool IsLooping() const = 0;
bool IsSpatialized() const; bool IsSpatialized() const;
virtual void Pause() = 0; virtual void Pause() = 0;
virtual void Play() = 0; virtual void Play() = 0;
void SetAttenuation(float attenuation); void SetAttenuation(float attenuation);
void SetMinDistance(float minDistance); void SetMinDistance(float minDistance);
void SetPitch(float pitch); void SetPitch(float pitch);
void SetPosition(const NzVector3f& position); void SetPosition(const Vector3f& position);
void SetPosition(float x, float y, float z); void SetPosition(float x, float y, float z);
void SetVelocity(const NzVector3f& velocity); void SetVelocity(const Vector3f& velocity);
void SetVelocity(float velX, float velY, float velZ); void SetVelocity(float velX, float velY, float velZ);
void SetVolume(float volume); void SetVolume(float volume);
virtual void Stop() = 0; virtual void Stop() = 0;
protected: SoundEmitter& operator=(const SoundEmitter&) = delete; ///TODO
NzSoundEmitter(); SoundEmitter& operator=(SoundEmitter&&) = delete; ///TODO
NzSoundEmitter(const NzSoundEmitter& emitter);
nzSoundStatus GetInternalStatus() const; protected:
SoundEmitter();
SoundEmitter(const SoundEmitter& emitter);
SoundEmitter(SoundEmitter&&) = delete; ///TODO
unsigned int m_source; SoundStatus GetInternalStatus() const;
};
unsigned int m_source;
};
}
#endif // NAZARA_SOUNDEMITTER_HPP #endif // NAZARA_SOUNDEMITTER_HPP

View File

@ -11,19 +11,22 @@
#include <Nazara/Audio/Config.hpp> #include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/Enums.hpp> #include <Nazara/Audio/Enums.hpp>
class NAZARA_AUDIO_API NzSoundStream namespace Nz
{ {
public: class NAZARA_AUDIO_API SoundStream
NzSoundStream() = default; {
virtual ~NzSoundStream(); public:
SoundStream() = default;
virtual ~SoundStream();
virtual nzUInt32 GetDuration() const = 0; virtual UInt32 GetDuration() const = 0;
virtual nzAudioFormat GetFormat() const = 0; virtual AudioFormat GetFormat() const = 0;
virtual nzUInt64 GetSampleCount() const = 0; virtual UInt32 GetSampleCount() const = 0;
virtual nzUInt32 GetSampleRate() const = 0; virtual UInt32 GetSampleRate() const = 0;
virtual unsigned int Read(void* buffer, unsigned int sampleCount) = 0; virtual unsigned int Read(void* buffer, unsigned int sampleCount) = 0;
virtual void Seek(nzUInt32 offset) = 0; virtual void Seek(UInt32 offset) = 0;
}; };
}
#endif // NAZARA_SOUNDSTREAM_HPP #endif // NAZARA_SOUNDSTREAM_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 on 20 Nov 2015 at 14:22:32
/* /*
Nazara Engine - Core module Nazara Engine - Core module
@ -49,19 +49,14 @@
#include <Nazara/Core/Functor.hpp> #include <Nazara/Core/Functor.hpp>
#include <Nazara/Core/GuillotineBinPack.hpp> #include <Nazara/Core/GuillotineBinPack.hpp>
#include <Nazara/Core/HardwareInfo.hpp> #include <Nazara/Core/HardwareInfo.hpp>
#include <Nazara/Core/Hash.hpp>
#include <Nazara/Core/Hashable.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/Initializer.hpp> #include <Nazara/Core/Initializer.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/LockGuard.hpp> #include <Nazara/Core/LockGuard.hpp>
#include <Nazara/Core/Log.hpp> #include <Nazara/Core/Log.hpp>
#include <Nazara/Core/MemoryHelper.hpp> #include <Nazara/Core/MemoryHelper.hpp>
#include <Nazara/Core/MemoryManager.hpp> #include <Nazara/Core/MemoryManager.hpp>
#include <Nazara/Core/MemoryPool.hpp> #include <Nazara/Core/MemoryPool.hpp>
#include <Nazara/Core/MemoryStream.hpp> #include <Nazara/Core/MemoryView.hpp>
#include <Nazara/Core/Mutex.hpp> #include <Nazara/Core/Mutex.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/ObjectLibrary.hpp> #include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp> #include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/OffsetOf.hpp> #include <Nazara/Core/OffsetOf.hpp>
@ -74,6 +69,8 @@
#include <Nazara/Core/ResourceLoader.hpp> #include <Nazara/Core/ResourceLoader.hpp>
#include <Nazara/Core/ResourceManager.hpp> #include <Nazara/Core/ResourceManager.hpp>
#include <Nazara/Core/Semaphore.hpp> #include <Nazara/Core/Semaphore.hpp>
#include <Nazara/Core/Serialization.hpp>
#include <Nazara/Core/Serializer.hpp>
#include <Nazara/Core/Signal.hpp> #include <Nazara/Core/Signal.hpp>
#include <Nazara/Core/SparsePtr.hpp> #include <Nazara/Core/SparsePtr.hpp>
#include <Nazara/Core/Stream.hpp> #include <Nazara/Core/Stream.hpp>
@ -82,6 +79,7 @@
#include <Nazara/Core/TaskScheduler.hpp> #include <Nazara/Core/TaskScheduler.hpp>
#include <Nazara/Core/Thread.hpp> #include <Nazara/Core/Thread.hpp>
#include <Nazara/Core/Unicode.hpp> #include <Nazara/Core/Unicode.hpp>
#include <Nazara/Core/Unserializer.hpp>
#include <Nazara/Core/Updatable.hpp> #include <Nazara/Core/Updatable.hpp>
#endif // NAZARA_GLOBAL_CORE_HPP #endif // NAZARA_GLOBAL_CORE_HPP

View File

@ -8,19 +8,33 @@
#define NAZARA_ABSTRACTHASH_HPP #define NAZARA_ABSTRACTHASH_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp> #include <Nazara/Core/Enums.hpp>
#include <memory>
class NzHashDigest; namespace Nz
class NAZARA_CORE_API NzAbstractHash : NzNonCopyable
{ {
public: class ByteArray;
NzAbstractHash() = default;
virtual ~NzAbstractHash();
virtual void Append(const nzUInt8* data, unsigned int len) = 0; class NAZARA_CORE_API AbstractHash
virtual void Begin() = 0; {
virtual NzHashDigest End() = 0; public:
}; AbstractHash() = default;
AbstractHash(const AbstractHash&) = delete;
AbstractHash(AbstractHash&&) = default;
virtual ~AbstractHash();
virtual void Append(const UInt8* data, std::size_t len) = 0;
virtual void Begin() = 0;
virtual ByteArray End() = 0;
virtual std::size_t GetDigestLength() const = 0;
virtual const char* GetHashName() const = 0;
AbstractHash& operator=(const AbstractHash&) = delete;
AbstractHash& operator=(AbstractHash&&) = default;
static std::unique_ptr<AbstractHash> Get(HashType hash);
};
}
#endif // NAZARA_ABSTRACTHASH_HPP #endif // NAZARA_ABSTRACTHASH_HPP

View File

@ -0,0 +1,9 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
/*!
* \class Nz::AbstractLogger
* \brief Logger interface
*/

View File

@ -0,0 +1,31 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_ABSTRACTLOGGER_HPP
#define NAZARA_ABSTRACTLOGGER_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Enums.hpp>
#include <Nazara/Core/String.hpp>
namespace Nz
{
class NAZARA_CORE_API AbstractLogger
{
public:
AbstractLogger() = default;
virtual ~AbstractLogger();
virtual void EnableStdReplication(bool enable) = 0;
virtual bool IsStdReplicationEnabled() = 0;
virtual void Write(const String& string) = 0;
virtual void WriteError(ErrorType type, const String& error, unsigned int line = 0, const char* file = nullptr, const char* function = nullptr);
};
}
#endif // NAZARA_ABSTRACTLOGGER_HPP

View File

@ -8,15 +8,36 @@
#define NAZARA_ALGORITHM_CORE_HPP #define NAZARA_ALGORITHM_CORE_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Enums.hpp>
#include <Nazara/Core/Serialization.hpp>
#include <functional> #include <functional>
#include <tuple> #include <tuple>
#include <type_traits>
template<typename F, typename Tuple> auto NzApply(F&& fn, Tuple&& t); namespace Nz
template<typename O, typename F, typename Tuple> auto NzApply(O& object, F&& fn, Tuple&& t); {
template<typename T> void NzHashCombine(std::size_t& seed, const T& v); class AbstractHash;
class ByteArray;
template<typename T> template<typename F, typename Tuple> auto Apply(F&& fn, Tuple&& t);
struct NzTypeTag {}; template<typename O, typename F, typename Tuple> auto Apply(O& object, F&& fn, Tuple&& t);
template<typename T> ByteArray ComputeHash(HashType hash, const T& v);
template<typename T> ByteArray ComputeHash(AbstractHash* hash, const T& v);
template<typename T> void HashCombine(std::size_t& seed, const T& v);
template<typename T>
struct TypeTag {};
inline bool Serialize(SerializationContext& context, bool value);
template<typename T>
std::enable_if_t<std::is_arithmetic<T>::value, bool> Serialize(SerializationContext& context, T value);
inline bool Unserialize(UnserializationContext& context, bool* value);
template<typename T>
std::enable_if_t<std::is_arithmetic<T>::value, bool> Unserialize(UnserializationContext& context, T* value);
}
#include <Nazara/Core/Algorithm.inl> #include <Nazara/Core/Algorithm.inl>

View File

@ -6,51 +6,152 @@
// Merci à Ryan "FullMetal Alchemist" Lahfa // Merci à Ryan "FullMetal Alchemist" Lahfa
// Merci aussi à Freedom de siteduzero.com // Merci aussi à Freedom de siteduzero.com
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/ByteArray.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Stream.hpp>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
// http://www.cppsamples.com/common-tasks/apply-tuple-to-function.html namespace Nz
template<typename F, typename Tuple, size_t... S>
auto NzApplyImplFunc(F&& fn, Tuple&& t, std::index_sequence<S...>)
{ {
return std::forward<F>(fn)(std::get<S>(std::forward<Tuple>(t))...); namespace Detail
} {
// http://www.cppsamples.com/common-tasks/apply-tuple-to-function.html
template<typename F, typename Tuple, size_t... S>
auto ApplyImplFunc(F&& fn, Tuple&& t, std::index_sequence<S...>)
{
return std::forward<F>(fn)(std::get<S>(std::forward<Tuple>(t))...);
}
template<typename F, typename Tuple> template<typename O, typename F, typename Tuple, size_t... S>
auto NzApply(F&& fn, Tuple&& t) auto ApplyImplMethod(O& object, F&& fn, Tuple&& t, std::index_sequence<S...>)
{ {
constexpr std::size_t tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value; return (object .* std::forward<F>(fn))(std::get<S>(std::forward<Tuple>(t))...);
}
}
return NzApplyImplFunc(std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>()); template<typename F, typename Tuple>
} auto Apply(F&& fn, Tuple&& t)
{
constexpr std::size_t tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value;
template<typename O, typename F, typename Tuple, size_t... S> return Detail::ApplyImplFunc(std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>());
auto NzApplyImplMethod(O& object, F&& fn, Tuple&& t, std::index_sequence<S...>) }
{
return (object .* std::forward<F>(fn))(std::get<S>(std::forward<Tuple>(t))...);
}
template<typename O, typename F, typename Tuple> template<typename O, typename F, typename Tuple>
auto NzApply(O& object, F&& fn, Tuple&& t) 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;
return NzApplyImplMethod(object, std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>()); return Detail::ApplyImplMethod(object, std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>());
} }
// Algorithme venant de CityHash par Google
// http://stackoverflow.com/questions/8513911/how-to-create-a-good-hash-combine-with-64-bit-output-inspired-by-boosthash-co
template<typename T>
void NzHashCombine(std::size_t& seed, const T& v)
{
const nzUInt64 kMul = 0x9ddfea08eb382d69ULL;
std::hash<T> hasher; template<typename T>
nzUInt64 a = (hasher(v) ^ seed) * kMul; ByteArray ComputeHash(HashType hash, const T& v)
a ^= (a >> 47); {
return ComputeHash(AbstractHash::Get(hash).get(), v);
}
nzUInt64 b = (seed ^ a) * kMul; template<typename T>
b ^= (b >> 47); ByteArray ComputeHash(AbstractHash* hash, const T& v)
{
hash->Begin();
seed = static_cast<std::size_t>(b * kMul); HashAppend(hash, v);
return hash->End();
}
// Algorithme venant de CityHash par Google
// http://stackoverflow.com/questions/8513911/how-to-create-a-good-hash-combine-with-64-bit-output-inspired-by-boosthash-co
template<typename T>
void HashCombine(std::size_t& seed, const T& v)
{
const UInt64 kMul = 0x9ddfea08eb382d69ULL;
std::hash<T> hasher;
UInt64 a = (hasher(v) ^ seed) * kMul;
a ^= (a >> 47);
UInt64 b = (seed ^ a) * kMul;
b ^= (b >> 47);
seed = static_cast<std::size_t>(b * kMul);
}
inline bool Serialize(SerializationContext& context, bool value)
{
if (context.currentBitPos == 8)
{
context.currentBitPos = 0;
context.currentByte = 0;
}
if (value)
context.currentByte |= 1 << context.currentBitPos;
if (++context.currentBitPos >= 8)
return Serialize<UInt8>(context, context.currentByte);
else
return true;
}
template<typename T>
std::enable_if_t<std::is_arithmetic<T>::value, bool> Serialize(SerializationContext& context, T value)
{
// Flush bits if a writing is in progress
if (context.currentBitPos != 8)
{
context.currentBitPos = 8;
if (!Serialize<UInt8>(context, context.currentByte))
NazaraWarning("Failed to flush bits");
}
if (context.endianness != Endianness_Unknown && context.endianness != GetPlatformEndianness())
SwapBytes(&value, sizeof(T));
return context.stream->Write(&value, sizeof(T)) == sizeof(T);
}
inline bool Unserialize(UnserializationContext& context, bool* value)
{
NazaraAssert(value, "Invalid data pointer");
if (context.currentBitPos == 8)
{
if (!Unserialize(context, &context.currentByte))
return false;
context.currentBitPos = 0;
}
if (value)
*value = (context.currentByte & (1 << context.currentBitPos)) != 0;
context.currentBitPos++;
return true;
}
template<typename T>
std::enable_if_t<std::is_arithmetic<T>::value, bool> Unserialize(UnserializationContext& context, T* value)
{
NazaraAssert(value, "Invalid data pointer");
// Reset bit position
context.currentBitPos = 8;
if (context.stream->Read(value, sizeof(T)) == sizeof(T))
{
if (context.endianness != Endianness_Unknown && context.endianness != GetPlatformEndianness())
SwapBytes(value, sizeof(T));
return true;
}
else
return false;
}
} }
#include <Nazara/Core/DebugOff.hpp> #include <Nazara/Core/DebugOff.hpp>

View File

@ -12,165 +12,168 @@
#include <memory> #include <memory>
#include <type_traits> #include <type_traits>
class NzAbstractHash; namespace Nz
template<typename Block = nzUInt32, class Allocator = std::allocator<Block>>
class NzBitset
{ {
static_assert(std::is_integral<Block>::value && std::is_unsigned<Block>::value, "Block must be a unsigned integral type"); class AbstractHash;
public: template<typename Block = UInt32, class Allocator = std::allocator<Block>>
class Bit; class Bitset
{
static_assert(std::is_integral<Block>::value && std::is_unsigned<Block>::value, "Block must be a unsigned integral type");
NzBitset(); public:
explicit NzBitset(unsigned int bitCount, bool val = false); class Bit;
explicit NzBitset(const char* bits);
NzBitset(const char* bits, unsigned int bitCount);
NzBitset(const NzBitset& bitset) = default;
explicit NzBitset(const NzString& bits);
NzBitset(NzBitset&& bitset) noexcept = default;
~NzBitset() = default;
void Clear(); Bitset();
unsigned int Count() const; explicit Bitset(unsigned int bitCount, bool val = false);
void Flip(); explicit Bitset(const char* bits);
Bitset(const char* bits, unsigned int bitCount);
Bitset(const Bitset& bitset) = default;
explicit Bitset(const String& bits);
Bitset(Bitset&& bitset) noexcept = default;
~Bitset() = default;
unsigned int FindFirst() const; void Clear();
unsigned int FindNext(unsigned int bit) const; unsigned int Count() const;
void Flip();
Block GetBlock(unsigned int i) const; unsigned int FindFirst() const;
unsigned int GetBlockCount() const; unsigned int FindNext(unsigned int bit) const;
unsigned int GetCapacity() const;
unsigned int GetSize() const;
void PerformsAND(const NzBitset& a, const NzBitset& b); Block GetBlock(unsigned int i) const;
void PerformsNOT(const NzBitset& a); unsigned int GetBlockCount() const;
void PerformsOR(const NzBitset& a, const NzBitset& b); unsigned int GetCapacity() const;
void PerformsXOR(const NzBitset& a, const NzBitset& b); unsigned int GetSize() const;
bool Intersects(const NzBitset& bitset) const; void PerformsAND(const Bitset& a, const Bitset& b);
void PerformsNOT(const Bitset& a);
void PerformsOR(const Bitset& a, const Bitset& b);
void PerformsXOR(const Bitset& a, const Bitset& b);
void Reserve(unsigned int bitCount); bool Intersects(const Bitset& bitset) const;
void Resize(unsigned int bitCount, bool defaultVal = false);
void Reset(); void Reserve(unsigned int bitCount);
void Reset(unsigned int bit); void Resize(unsigned int bitCount, bool defaultVal = false);
void Set(bool val = true); void Reset();
void Set(unsigned int bit, bool val = true); void Reset(unsigned int bit);
void SetBlock(unsigned int i, Block block);
void Swap(NzBitset& bitset); void Set(bool val = true);
void Set(unsigned int bit, bool val = true);
void SetBlock(unsigned int i, Block block);
bool Test(unsigned int bit) const; void Swap(Bitset& bitset);
bool TestAll() const;
bool TestAny() const;
bool TestNone() const;
template<typename T> T To() const; bool Test(unsigned int bit) const;
NzString ToString() const; bool TestAll() const;
bool TestAny() const;
bool TestNone() const;
void UnboundedReset(unsigned int bit); template<typename T> T To() const;
void UnboundedSet(unsigned int bit, bool val = true); String ToString() const;
bool UnboundedTest(unsigned int bit) const;
Bit operator[](int index); void UnboundedReset(unsigned int bit);
bool operator[](int index) const; void UnboundedSet(unsigned int bit, bool val = true);
bool UnboundedTest(unsigned int bit) const;
NzBitset operator~() const; Bit operator[](int index);
bool operator[](int index) const;
NzBitset& operator=(const NzBitset& bitset) = default; Bitset operator~() const;
NzBitset& operator=(const NzString& bits);
NzBitset& operator=(NzBitset&& bitset) noexcept = default;
NzBitset& operator&=(const NzBitset& bitset); Bitset& operator=(const Bitset& bitset) = default;
NzBitset& operator|=(const NzBitset& bitset); Bitset& operator=(const String& bits);
NzBitset& operator^=(const NzBitset& bitset); Bitset& operator=(Bitset&& bitset) noexcept = default;
static Block fullBitMask; Bitset& operator&=(const Bitset& bitset);
static unsigned int bitsPerBlock; Bitset& operator|=(const Bitset& bitset);
static unsigned int npos; Bitset& operator^=(const Bitset& bitset);
private: static Block fullBitMask;
unsigned int FindFirstFrom(unsigned int blockIndex) const; static unsigned int bitsPerBlock;
Block GetLastBlockMask() const; static unsigned int npos;
void ResetExtraBits();
static unsigned int ComputeBlockCount(unsigned int bitCount); private:
static unsigned int GetBitIndex(unsigned int bit); unsigned int FindFirstFrom(unsigned int blockIndex) const;
static unsigned int GetBlockIndex(unsigned int bit); Block GetLastBlockMask() const;
void ResetExtraBits();
std::vector<Block, Allocator> m_blocks; static unsigned int ComputeBlockCount(unsigned int bitCount);
unsigned int m_bitCount; static unsigned int GetBitIndex(unsigned int bit);
}; static unsigned int GetBlockIndex(unsigned int bit);
template<typename Block, class Allocator> std::vector<Block, Allocator> m_blocks;
bool operator==(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs); unsigned int m_bitCount;
};
template<typename Block, class Allocator> template<typename Block, class Allocator>
bool operator!=(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs); class Bitset<Block, Allocator>::Bit
{
friend Bitset<Block, Allocator>;
template<typename Block, class Allocator> public:
bool operator<(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs); Bit(const Bit& bit) = default;
template<typename Block, class Allocator> Bit& Flip();
bool operator<=(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs); Bit& Reset();
Bit& Set(bool val = true);
bool Test() const;
template<typename Block, class Allocator> template<bool BadCall = true>
bool operator>(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs); void* operator&() const;
template<typename Block, class Allocator> operator bool() const;
bool operator>=(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs); Bit& operator=(bool val);
Bit& operator=(const Bit& bit);
template<typename Block, class Allocator> Bit& operator|=(bool val);
NzBitset<Block, Allocator> operator&(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs); Bit& operator&=(bool val);
Bit& operator^=(bool val);
Bit& operator-=(bool val);
template<typename Block, class Allocator> private:
NzBitset<Block, Allocator> operator|(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs); Bit(Block& block, Block mask) :
m_block(block),
m_mask(mask)
{
}
template<typename Block, class Allocator> Block& m_block;
NzBitset<Block, Allocator> operator^(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs); Block m_mask;
};
template<typename Block, class Allocator> template<typename Block, class Allocator>
class NzBitset<Block, Allocator>::Bit bool operator==(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
{
friend NzBitset<Block, Allocator>;
public: template<typename Block, class Allocator>
Bit(const Bit& bit) = default; bool operator!=(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
Bit& Flip(); template<typename Block, class Allocator>
Bit& Reset(); bool operator<(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
Bit& Set(bool val = true);
bool Test() const;
template<bool BadCall = true> template<typename Block, class Allocator>
void* operator&() const; bool operator<=(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
operator bool() const; template<typename Block, class Allocator>
Bit& operator=(bool val); bool operator>(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
Bit& operator=(const Bit& bit);
Bit& operator|=(bool val); template<typename Block, class Allocator>
Bit& operator&=(bool val); bool operator>=(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
Bit& operator^=(bool val);
Bit& operator-=(bool val);
private: template<typename Block, class Allocator>
Bit(Block& block, Block mask) : Bitset<Block, Allocator> operator&(const Bitset<Block, Allocator>& lhs, const Bitset<Block, Allocator>& rhs);
m_block(block),
m_mask(mask)
{
}
Block& m_block; template<typename Block, class Allocator>
Block m_mask; Bitset<Block, Allocator> operator|(const Bitset<Block, Allocator>& lhs, const Bitset<Block, Allocator>& rhs);
};
template<typename Block, class Allocator>
Bitset<Block, Allocator> operator^(const Bitset<Block, Allocator>& lhs, const Bitset<Block, Allocator>& rhs);
}
namespace std namespace std
{ {
template<typename Block, class Allocator> template<typename Block, class Allocator>
void swap(NzBitset<Block, Allocator>& lhs, NzBitset<Block, Allocator>& rhs); void swap(Nz::Bitset<Block, Allocator>& lhs, Nz::Bitset<Block, Allocator>& rhs);
} }
#include <Nazara/Core/Bitset.inl> #include <Nazara/Core/Bitset.inl>

File diff suppressed because it is too large Load Diff

View File

@ -8,130 +8,132 @@
#define NAZARA_BYTEARRAY_HPP #define NAZARA_BYTEARRAY_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Hashable.hpp>
#include <Nazara/Core/String.hpp> #include <Nazara/Core/String.hpp>
#include <vector> #include <vector>
class NzAbstractHash; namespace Nz
class NAZARA_CORE_API NzByteArray : public NzHashable
{ {
using Container = std::vector<nzUInt8>; class AbstractHash;
public: class NAZARA_CORE_API ByteArray
// types: {
using allocator_type = Container::allocator_type; using Container = std::vector<UInt8>;
using const_iterator = Container::const_iterator;
using const_reference = Container::const_reference;
using const_pointer = Container::const_pointer;
using const_reverse_iterator = Container::const_reverse_iterator;
using difference_type = Container::difference_type;
using pointer = Container::pointer;
using iterator = Container::iterator;
using reference = Container::reference;
using reverse_iterator = Container::reverse_iterator;
using size_type = Container::size_type;
using value_type = Container::value_type;
// construct/destroy: public:
inline NzByteArray() = default; // types:
inline explicit NzByteArray(size_type n); using allocator_type = Container::allocator_type;
inline NzByteArray(const void* buffer, size_type n); using const_iterator = Container::const_iterator;
inline NzByteArray(size_type n, value_type value); using const_reference = Container::const_reference;
template <class InputIterator> NzByteArray(InputIterator first, InputIterator last); using const_pointer = Container::const_pointer;
NzByteArray(const NzByteArray& other) = default; using const_reverse_iterator = Container::const_reverse_iterator;
NzByteArray(NzByteArray&& other) = default; using difference_type = Container::difference_type;
~NzByteArray() = default; using pointer = Container::pointer;
using iterator = Container::iterator;
using reference = Container::reference;
using reverse_iterator = Container::reverse_iterator;
using size_type = Container::size_type;
using value_type = Container::value_type;
inline iterator Append(const void* buffer, size_type size); // construct/destroy:
inline iterator Append(const NzByteArray& other); inline ByteArray() = default;
template <class InputIterator> void Assign(InputIterator first, InputIterator last); inline explicit ByteArray(size_type n);
inline void Assign(size_type n, value_type value); inline ByteArray(const void* buffer, size_type n);
inline ByteArray(size_type n, value_type value);
template <class InputIterator> ByteArray(InputIterator first, InputIterator last);
ByteArray(const ByteArray& other) = default;
ByteArray(ByteArray&& other) = default;
~ByteArray() = default;
inline reference Back(); inline iterator Append(const void* buffer, size_type size);
inline const_reference Back() const; inline iterator Append(const ByteArray& other);
template <class InputIterator> void Assign(InputIterator first, InputIterator last);
inline void Assign(size_type n, value_type value);
inline void Clear(bool keepBuffer = false); inline reference Back();
inline const_reference Back() const;
inline iterator Erase(const_iterator pos); inline void Clear(bool keepBuffer = false);
inline iterator Erase(const_iterator first, const_iterator last);
inline reference Front(); inline iterator Erase(const_iterator pos);
inline const_reference Front() const; inline iterator Erase(const_iterator first, const_iterator last);
inline allocator_type GetAllocator() const; inline reference Front();
inline pointer GetBuffer(); inline const_reference Front() const;
inline size_type GetCapacity() const noexcept;
inline const_pointer GetConstBuffer() const;
inline size_type GetMaxSize() const noexcept;
inline size_type GetSize() const noexcept;
inline NzByteArray GetSubArray(const_iterator startPos, const_iterator endPos) const;
inline iterator Insert(const_iterator pos, const void* buffer, size_type n); inline allocator_type GetAllocator() const;
inline iterator Insert(const_iterator pos, const NzByteArray& other); inline pointer GetBuffer();
inline iterator Insert(const_iterator pos, size_type n, value_type byte); inline size_type GetCapacity() const noexcept;
template <class InputIterator> iterator Insert(const_iterator pos, InputIterator first, InputIterator last); inline const_pointer GetConstBuffer() const;
inline bool IsEmpty() const noexcept; inline size_type GetMaxSize() const noexcept;
inline size_type GetSize() const noexcept;
inline ByteArray GetSubArray(const_iterator startPos, const_iterator endPos) const;
inline void PopBack(); inline iterator Insert(const_iterator pos, const void* buffer, size_type n);
inline void PopFront(); inline iterator Insert(const_iterator pos, const ByteArray& other);
inline iterator Prepend(const void* buffer, size_type size); inline iterator Insert(const_iterator pos, size_type n, value_type byte);
inline iterator Prepend(const NzByteArray& other); template <class InputIterator> iterator Insert(const_iterator pos, InputIterator first, InputIterator last);
inline void PushBack(value_type byte); inline bool IsEmpty() const noexcept;
inline void PushFront(value_type byte);
inline void Reserve(size_type bufferSize); inline void PopBack();
inline void Resize(size_type newSize); inline void PopFront();
inline void Resize(size_type newSize, value_type byte); inline iterator Prepend(const void* buffer, size_type size);
inline iterator Prepend(const ByteArray& other);
inline void PushBack(value_type byte);
inline void PushFront(value_type byte);
inline void ShrinkToFit(); inline void Reserve(size_type bufferSize);
inline void Swap(NzByteArray& other); inline void Resize(size_type newSize);
inline void Resize(size_type newSize, value_type byte);
inline NzString ToString() const; inline void ShrinkToFit();
inline void Swap(ByteArray& other);
// STL interface inline String ToHex() const;
inline iterator begin() noexcept; inline String ToString() const;
inline const_iterator begin() const noexcept;
inline bool empty() const noexcept;
inline iterator end() noexcept;
inline const_iterator end() const noexcept;
inline reverse_iterator rbegin() noexcept;
inline const_reverse_iterator rbegin() const noexcept;
inline reverse_iterator rend() noexcept;
inline const_reverse_iterator rend() const noexcept;
inline const_iterator cbegin() const noexcept;
inline const_iterator cend() const noexcept;
inline const_reverse_iterator crbegin() const noexcept;
inline const_reverse_iterator crend() const noexcept;
inline size_type size() const noexcept;
// Operators // STL interface
inline reference operator[](size_type pos); inline iterator begin() noexcept;
inline const_reference operator[](size_type pos) const; inline const_iterator begin() const noexcept;
inline NzByteArray& operator=(const NzByteArray& array) = default; inline bool empty() const noexcept;
inline NzByteArray& operator=(NzByteArray&& array) = default; inline iterator end() noexcept;
inline NzByteArray operator+(const NzByteArray& array) const; inline const_iterator end() const noexcept;
inline NzByteArray& operator+=(const NzByteArray& array); inline reverse_iterator rbegin() noexcept;
inline const_reverse_iterator rbegin() const noexcept;
inline reverse_iterator rend() noexcept;
inline const_reverse_iterator rend() const noexcept;
inline const_iterator cbegin() const noexcept;
inline const_iterator cend() const noexcept;
inline const_reverse_iterator crbegin() const noexcept;
inline const_reverse_iterator crend() const noexcept;
inline size_type size() const noexcept;
inline bool operator==(const NzByteArray& rhs) const; // Operators
inline bool operator!=(const NzByteArray& rhs) const; NAZARA_CORE_API friend std::ostream& operator<<(std::ostream& out, const Nz::ByteArray& byteArray);
inline bool operator<(const NzByteArray& rhs) const;
inline bool operator<=(const NzByteArray& rhs) const;
inline bool operator>(const NzByteArray& rhs) const;
inline bool operator>=(const NzByteArray& rhs) const;
private: inline reference operator[](size_type pos);
bool FillHash(NzAbstractHash* hash) const; inline const_reference operator[](size_type pos) const;
inline ByteArray& operator=(const ByteArray& array) = default;
inline ByteArray& operator=(ByteArray&& array) = default;
inline ByteArray operator+(const ByteArray& array) const;
inline ByteArray& operator+=(const ByteArray& array);
Container m_array; inline bool operator==(const ByteArray& rhs) const;
}; inline bool operator!=(const ByteArray& rhs) const;
inline bool operator<(const ByteArray& rhs) const;
inline bool operator<=(const ByteArray& rhs) const;
inline bool operator>(const ByteArray& rhs) const;
inline bool operator>=(const ByteArray& rhs) const;
NAZARA_CORE_API std::ostream& operator<<(std::ostream& out, const NzByteArray& byteArray); private:
Container m_array;
};
inline bool HashAppend(AbstractHash* hash, const ByteArray& byteArray);
}
namespace std namespace std
{ {
void swap(NzByteArray& lhs, NzByteArray& rhs); void swap(Nz::ByteArray& lhs, Nz::ByteArray& rhs);
} }
#include <Nazara/Core/ByteArray.inl> #include <Nazara/Core/ByteArray.inl>

View File

@ -2,327 +2,356 @@
// This file is part of the "Nazara Engine - Core module" // This file is part of the "Nazara Engine - Core 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
inline NzByteArray::NzByteArray(size_type n) : #include <Nazara/Core/Error.hpp>
m_array()
namespace Nz
{ {
m_array.reserve(n); inline ByteArray::ByteArray(size_type n) :
} m_array()
{
m_array.reserve(n);
}
inline NzByteArray::NzByteArray(const void* buffer, size_type n) : inline ByteArray::ByteArray(const void* buffer, size_type n) :
m_array(static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n) m_array(static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n)
{ {
} }
inline NzByteArray::NzByteArray(size_type n, const value_type value) : inline ByteArray::ByteArray(size_type n, const value_type value) :
m_array(n, value) m_array(n, value)
{ {
} }
template <class InputIterator> template <class InputIterator>
NzByteArray::NzByteArray(InputIterator first, InputIterator last) : ByteArray::ByteArray(InputIterator first, InputIterator last) :
m_array(first, last) m_array(first, last)
{ {
} }
inline NzByteArray::iterator NzByteArray::Append(const void* buffer, size_type n) inline ByteArray::iterator ByteArray::Append(const void* buffer, size_type n)
{ {
return Insert(end(), static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n); return Insert(end(), static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n);
} }
inline NzByteArray::iterator NzByteArray::Append(const NzByteArray& other) inline ByteArray::iterator ByteArray::Append(const ByteArray& other)
{ {
return Insert(end(), other.begin(), other.end()); return Insert(end(), other.begin(), other.end());
} }
inline void NzByteArray::Assign(size_type n, value_type value) inline void ByteArray::Assign(size_type n, value_type value)
{ {
m_array.assign(n, value); m_array.assign(n, value);
} }
template <class InputIterator> template <class InputIterator>
void NzByteArray::Assign(InputIterator first, InputIterator last) void ByteArray::Assign(InputIterator first, InputIterator last)
{ {
m_array.assign(first, last); m_array.assign(first, last);
} }
inline NzByteArray::reference NzByteArray::Back() inline ByteArray::reference ByteArray::Back()
{ {
return m_array.back(); return m_array.back();
} }
inline NzByteArray::const_reference NzByteArray::Back() const inline ByteArray::const_reference ByteArray::Back() const
{ {
return m_array.back(); return m_array.back();
} }
inline NzByteArray::iterator NzByteArray::Erase(const_iterator pos) inline void ByteArray::Clear(bool keepBuffer)
{ {
return m_array.erase(pos); m_array.clear();
} if (!keepBuffer)
m_array.shrink_to_fit();
}
inline NzByteArray::iterator NzByteArray::Erase(const_iterator first, const_iterator last) inline ByteArray::iterator ByteArray::Erase(const_iterator pos)
{ {
return m_array.erase(first, last); return m_array.erase(pos);
} }
inline NzByteArray::reference NzByteArray::Front() inline ByteArray::iterator ByteArray::Erase(const_iterator first, const_iterator last)
{ {
return m_array.front(); return m_array.erase(first, last);
} }
inline NzByteArray::const_reference NzByteArray::Front() const inline ByteArray::reference ByteArray::Front()
{ {
return m_array.front(); return m_array.front();
} }
inline NzByteArray::allocator_type NzByteArray::GetAllocator() const inline ByteArray::const_reference ByteArray::Front() const
{ {
return m_array.get_allocator(); return m_array.front();
} }
inline NzByteArray::pointer NzByteArray::GetBuffer() inline ByteArray::allocator_type ByteArray::GetAllocator() const
{ {
return m_array.data(); return m_array.get_allocator();
} }
inline NzByteArray::size_type NzByteArray::GetCapacity() const noexcept inline ByteArray::pointer ByteArray::GetBuffer()
{ {
return m_array.capacity(); return m_array.data();
} }
inline NzByteArray::const_pointer NzByteArray::GetConstBuffer() const inline ByteArray::size_type ByteArray::GetCapacity() const noexcept
{ {
return m_array.data(); return m_array.capacity();
} }
inline NzByteArray::size_type NzByteArray::GetMaxSize() const noexcept inline ByteArray::const_pointer ByteArray::GetConstBuffer() const
{ {
return m_array.max_size(); return m_array.data();
} }
inline NzByteArray::size_type NzByteArray::GetSize() const noexcept inline ByteArray::size_type ByteArray::GetMaxSize() const noexcept
{ {
return m_array.size(); return m_array.max_size();
} }
inline NzByteArray NzByteArray::GetSubArray(const_iterator startPos, const_iterator endPos) const inline ByteArray::size_type ByteArray::GetSize() const noexcept
{ {
return NzByteArray(startPos, endPos); return m_array.size();
} }
inline NzByteArray::iterator NzByteArray::Insert(const_iterator pos, const void* buffer, size_type n) inline ByteArray ByteArray::GetSubArray(const_iterator startPos, const_iterator endPos) const
{ {
return m_array.insert(pos, static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n); return ByteArray(startPos, endPos);
} }
inline NzByteArray::iterator NzByteArray::Insert(const_iterator pos, const NzByteArray& other) inline ByteArray::iterator ByteArray::Insert(const_iterator pos, const void* buffer, size_type n)
{ {
return m_array.insert(pos, other.begin(), other.end()); return m_array.insert(pos, static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n);
} }
inline NzByteArray::iterator NzByteArray::Insert(const_iterator pos, size_type n, value_type byte) inline ByteArray::iterator ByteArray::Insert(const_iterator pos, const ByteArray& other)
{ {
return m_array.insert(pos, n, byte); return m_array.insert(pos, other.begin(), other.end());
} }
template <class InputIterator> inline ByteArray::iterator ByteArray::Insert(const_iterator pos, size_type n, value_type byte)
NzByteArray::iterator NzByteArray::Insert(const_iterator pos, InputIterator first, InputIterator last) {
{ return m_array.insert(pos, n, byte);
return m_array.insert(pos, first, last); }
}
inline bool NzByteArray::IsEmpty() const noexcept template <class InputIterator>
{ ByteArray::iterator ByteArray::Insert(const_iterator pos, InputIterator first, InputIterator last)
return m_array.empty(); {
} return m_array.insert(pos, first, last);
}
inline void NzByteArray::PopBack() inline bool ByteArray::IsEmpty() const noexcept
{ {
Erase(end() - 1); return m_array.empty();
} }
inline void NzByteArray::PopFront() inline void ByteArray::PopBack()
{ {
Erase(begin()); Erase(end() - 1);
} }
inline NzByteArray::iterator NzByteArray::Prepend(const void* buffer, size_type n) inline void ByteArray::PopFront()
{ {
return Insert(begin(), buffer, n); Erase(begin());
} }
inline NzByteArray::iterator NzByteArray::Prepend(const NzByteArray& other) inline ByteArray::iterator ByteArray::Prepend(const void* buffer, size_type n)
{ {
return Insert(begin(), other); return Insert(begin(), buffer, n);
} }
inline void NzByteArray::PushBack(const value_type byte) inline ByteArray::iterator ByteArray::Prepend(const ByteArray& other)
{ {
m_array.push_back(byte); return Insert(begin(), other);
} }
inline void NzByteArray::PushFront(const value_type byte) inline void ByteArray::PushBack(const value_type byte)
{ {
m_array.insert(begin(), 1, byte); m_array.push_back(byte);
} }
inline void NzByteArray::Reserve(size_type bufferSize) inline void ByteArray::PushFront(const value_type byte)
{ {
m_array.reserve(bufferSize); m_array.insert(begin(), 1, byte);
} }
inline void NzByteArray::Resize(size_type newSize) inline void ByteArray::Reserve(size_type bufferSize)
{ {
m_array.resize(newSize); m_array.reserve(bufferSize);
} }
inline void NzByteArray::Resize(size_type newSize, const value_type byte) inline void ByteArray::Resize(size_type newSize)
{ {
m_array.resize(newSize, byte); m_array.resize(newSize);
} }
inline void NzByteArray::ShrinkToFit() inline void ByteArray::Resize(size_type newSize, const value_type byte)
{ {
m_array.shrink_to_fit(); m_array.resize(newSize, byte);
} }
inline void NzByteArray::Swap(NzByteArray& other) inline void ByteArray::ShrinkToFit()
{ {
m_array.swap(other.m_array); m_array.shrink_to_fit();
} }
inline NzString NzByteArray::ToString() const inline void ByteArray::Swap(ByteArray& other)
{ {
return NzString(reinterpret_cast<const char*>(GetConstBuffer()), GetSize()); m_array.swap(other.m_array);
} }
inline NzByteArray::iterator NzByteArray::begin() noexcept inline String ByteArray::ToHex() const
{ {
return m_array.begin(); std::size_t length = m_array.size() * 2;
}
inline NzByteArray::const_iterator NzByteArray::begin() const noexcept String hexOutput(length, '\0');
{ for (std::size_t i = 0; i < m_array.size(); ++i)
return m_array.begin(); std::sprintf(&hexOutput[i * 2], "%02x", m_array[i]);
}
inline NzByteArray::const_iterator NzByteArray::cbegin() const noexcept return hexOutput;
{ }
return m_array.cbegin();
}
inline NzByteArray::const_iterator NzByteArray::cend() const noexcept inline String ByteArray::ToString() const
{ {
return m_array.cend(); return String(reinterpret_cast<const char*>(GetConstBuffer()), GetSize());
} }
inline NzByteArray::const_reverse_iterator NzByteArray::crbegin() const noexcept inline ByteArray::iterator ByteArray::begin() noexcept
{ {
return m_array.crbegin(); return m_array.begin();
} }
inline NzByteArray::const_reverse_iterator NzByteArray::crend() const noexcept inline ByteArray::const_iterator ByteArray::begin() const noexcept
{ {
return m_array.crend(); return m_array.begin();
} }
inline bool NzByteArray::empty() const noexcept inline ByteArray::const_iterator ByteArray::cbegin() const noexcept
{ {
return m_array.empty(); return m_array.cbegin();
} }
inline NzByteArray::iterator NzByteArray::end() noexcept inline ByteArray::const_iterator ByteArray::cend() const noexcept
{ {
return m_array.end(); return m_array.cend();
} }
inline NzByteArray::const_iterator NzByteArray::end() const noexcept inline ByteArray::const_reverse_iterator ByteArray::crbegin() const noexcept
{ {
return m_array.end(); return m_array.crbegin();
} }
inline NzByteArray::reverse_iterator NzByteArray::rbegin() noexcept inline ByteArray::const_reverse_iterator ByteArray::crend() const noexcept
{ {
return m_array.rbegin(); return m_array.crend();
} }
inline NzByteArray::const_reverse_iterator NzByteArray::rbegin() const noexcept inline bool ByteArray::empty() const noexcept
{ {
return m_array.rbegin(); return m_array.empty();
} }
inline NzByteArray::reverse_iterator NzByteArray::rend() noexcept inline ByteArray::iterator ByteArray::end() noexcept
{ {
return m_array.rend(); return m_array.end();
} }
inline NzByteArray::size_type NzByteArray::size() const noexcept inline ByteArray::const_iterator ByteArray::end() const noexcept
{ {
return GetSize(); return m_array.end();
} }
inline NzByteArray::reference NzByteArray::operator[](size_type pos) inline ByteArray::reverse_iterator ByteArray::rbegin() noexcept
{ {
NazaraAssert(pos < GetSize(), "Index out of range"); return m_array.rbegin();
}
return m_array[pos]; inline ByteArray::const_reverse_iterator ByteArray::rbegin() const noexcept
} {
return m_array.rbegin();
}
inline NzByteArray::const_reference NzByteArray::operator[](size_type pos) const inline ByteArray::reverse_iterator ByteArray::rend() noexcept
{ {
NazaraAssert(pos < GetSize(), "Index out of range"); return m_array.rend();
}
return m_array[pos]; inline ByteArray::size_type ByteArray::size() const noexcept
} {
return GetSize();
}
inline NzByteArray NzByteArray::operator+(const NzByteArray& other) const inline ByteArray::reference ByteArray::operator[](size_type pos)
{ {
NzByteArray tmp(*this); NazaraAssert(pos < GetSize(), "Index out of range");
tmp += other;
return tmp; return m_array[pos];
} }
inline NzByteArray& NzByteArray::operator+=(const NzByteArray& other) inline ByteArray::const_reference ByteArray::operator[](size_type pos) const
{ {
Append(other); NazaraAssert(pos < GetSize(), "Index out of range");
return *this; return m_array[pos];
} }
inline bool NzByteArray::operator==(const NzByteArray& rhs) const inline ByteArray ByteArray::operator+(const ByteArray& other) const
{ {
return m_array == rhs.m_array; ByteArray tmp(*this);
} tmp += other;
inline bool NzByteArray::operator!=(const NzByteArray& rhs) const return tmp;
{ }
return !operator==(rhs);
}
inline bool NzByteArray::operator<(const NzByteArray& rhs) const inline ByteArray& ByteArray::operator+=(const ByteArray& other)
{ {
return m_array < rhs.m_array; Append(other);
}
inline bool NzByteArray::operator<=(const NzByteArray& rhs) const return *this;
{ }
return m_array <= rhs.m_array;
}
inline bool NzByteArray::operator>(const NzByteArray& rhs) const inline bool ByteArray::operator==(const ByteArray& rhs) const
{ {
return m_array > rhs.m_array; return m_array == rhs.m_array;
} }
inline bool NzByteArray::operator>=(const NzByteArray& rhs) const inline bool ByteArray::operator!=(const ByteArray& rhs) const
{ {
return m_array >= rhs.m_array; return !operator==(rhs);
}
inline bool ByteArray::operator<(const ByteArray& rhs) const
{
return m_array < rhs.m_array;
}
inline bool ByteArray::operator<=(const ByteArray& rhs) const
{
return m_array <= rhs.m_array;
}
inline bool ByteArray::operator>(const ByteArray& rhs) const
{
return m_array > rhs.m_array;
}
inline bool ByteArray::operator>=(const ByteArray& rhs) const
{
return m_array >= rhs.m_array;
}
inline bool HashAppend(AbstractHash* hash, const ByteArray& byteArray)
{
hash->Append(byteArray.GetConstBuffer(), byteArray.GetSize());
return true;
}
} }
namespace std namespace std
{ {
inline void swap(NzByteArray& lhs, NzByteArray& rhs) inline void swap(Nz::ByteArray& lhs, Nz::ByteArray& rhs)
{ {
lhs.Swap(rhs); lhs.Swap(rhs);
} }

View File

@ -8,23 +8,30 @@
#define NAZARA_CALLONEXIT_HPP #define NAZARA_CALLONEXIT_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <functional> #include <functional>
class NzCallOnExit : NzNonCopyable namespace Nz
{ {
using Func = std::function<void()>; class CallOnExit
{
using Func = std::function<void()>;
public: public:
NzCallOnExit(Func func = nullptr); CallOnExit(Func func = nullptr);
~NzCallOnExit(); CallOnExit(const CallOnExit&) = delete;
CallOnExit(CallOnExit&&) = delete;
~CallOnExit();
void CallAndReset(Func func = nullptr); void CallAndReset(Func func = nullptr);
void Reset(Func func = nullptr); void Reset(Func func = nullptr);
private: CallOnExit& operator=(const CallOnExit&) = delete;
Func m_func; CallOnExit& operator=(CallOnExit&&) = default;
};
private:
Func m_func;
};
}
#include <Nazara/Core/CallOnExit.inl> #include <Nazara/Core/CallOnExit.inl>

View File

@ -5,28 +5,31 @@
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
inline NzCallOnExit::NzCallOnExit(Func func) : namespace Nz
m_func(func)
{ {
} inline CallOnExit::CallOnExit(Func func) :
m_func(func)
{
}
inline NzCallOnExit::~NzCallOnExit() inline CallOnExit::~CallOnExit()
{ {
if (m_func) if (m_func)
m_func(); m_func();
} }
inline void NzCallOnExit::CallAndReset(Func func) inline void CallOnExit::CallAndReset(Func func)
{ {
if (m_func) if (m_func)
m_func(); m_func();
Reset(func); Reset(func);
} }
inline void NzCallOnExit::Reset(Func func) inline void CallOnExit::Reset(Func func)
{ {
m_func = func; m_func = func;
}
} }
#include <Nazara/Core/DebugOff.hpp> #include <Nazara/Core/DebugOff.hpp>

View File

@ -15,35 +15,41 @@
#include <Nazara/Core/ThreadSafetyOff.hpp> #include <Nazara/Core/ThreadSafetyOff.hpp>
#endif #endif
class NAZARA_CORE_API NzClock namespace Nz
{ {
public: class NAZARA_CORE_API Clock
NzClock(nzUInt64 startingValue = 0, bool paused = false); {
NzClock(const NzClock& clock) = default; public:
Clock(UInt64 startingValue = 0, bool paused = false);
Clock(const Clock& clock) = default;
Clock(Clock&& clock) = default;
~Clock() = default;
float GetSeconds() const; float GetSeconds() const;
nzUInt64 GetMicroseconds() const; UInt64 GetMicroseconds() const;
nzUInt64 GetMilliseconds() const; UInt64 GetMilliseconds() const;
bool IsPaused() const; bool IsPaused() const;
void Pause(); void Pause();
void Restart(); void Restart();
void Unpause(); void Unpause();
NzClock& operator=(const NzClock& clock) = default; Clock& operator=(const Clock& clock) = default;
Clock& operator=(Clock&& clock) = default;
private: private:
NazaraMutexAttrib(m_mutex, mutable) NazaraMutexAttrib(m_mutex, mutable)
nzUInt64 m_elapsedTime; UInt64 m_elapsedTime;
nzUInt64 m_refTime; UInt64 m_refTime;
bool m_paused; bool m_paused;
}; };
typedef nzUInt64 (*NzClockFunction)(); typedef UInt64 (*ClockFunction)();
extern NAZARA_CORE_API NzClockFunction NzGetMicroseconds; extern NAZARA_CORE_API ClockFunction GetElapsedMicroseconds;
extern NAZARA_CORE_API NzClockFunction NzGetMilliseconds; extern NAZARA_CORE_API ClockFunction GetElapsedMilliseconds;
}
#endif // NAZARA_CLOCK_HPP #endif // NAZARA_CLOCK_HPP

View File

@ -11,57 +11,60 @@
#include <Nazara/Core/String.hpp> #include <Nazara/Core/String.hpp>
#include <Nazara/Math/Vector3.hpp> #include <Nazara/Math/Vector3.hpp>
class NzColor namespace Nz
{ {
public: class Color
inline NzColor(); {
inline NzColor(nzUInt8 red, nzUInt8 green, nzUInt8 blue, nzUInt8 alpha = 255); public:
inline explicit NzColor(nzUInt8 lightness); inline Color();
inline NzColor(nzUInt8 color[3], nzUInt8 alpha = 255); inline Color(UInt8 red, UInt8 green, UInt8 blue, UInt8 alpha = 255);
inline NzColor(const NzColor& color) = default; inline explicit Color(UInt8 lightness);
inline ~NzColor() = default; inline Color(UInt8 color[3], UInt8 alpha = 255);
inline Color(const Color& color) = default;
inline ~Color() = default;
inline NzString ToString() const; inline String ToString() const;
inline NzColor operator+(const NzColor& angles) const; inline Color operator+(const Color& angles) const;
inline NzColor operator*(const NzColor& angles) const; inline Color operator*(const Color& angles) const;
inline NzColor operator+=(const NzColor& angles); inline Color operator+=(const Color& angles);
inline NzColor operator*=(const NzColor& angles); inline Color operator*=(const Color& angles);
inline bool operator==(const NzColor& angles) const; inline bool operator==(const Color& angles) const;
inline bool operator!=(const NzColor& angles) const; inline bool operator!=(const Color& angles) const;
static inline NzColor FromCMY(float cyan, float magenta, float yellow); static inline Color FromCMY(float cyan, float magenta, float yellow);
static inline NzColor FromCMYK(float cyan, float magenta, float yellow, float black); static inline Color FromCMYK(float cyan, float magenta, float yellow, float black);
static inline NzColor FromHSL(nzUInt8 hue, nzUInt8 saturation, nzUInt8 lightness); static inline Color FromHSL(UInt8 hue, UInt8 saturation, UInt8 lightness);
static inline NzColor FromHSV(float hue, float saturation, float value); static inline Color FromHSV(float hue, float saturation, float value);
static inline NzColor FromXYZ(const NzVector3f& vec); static inline Color FromXYZ(const Vector3f& vec);
static inline NzColor FromXYZ(float x, float y, float z); static inline Color FromXYZ(float x, float y, float z);
static inline void ToCMY(const NzColor& color, float* cyan, float* magenta, float* yellow); static inline void ToCMY(const Color& color, float* cyan, float* magenta, float* yellow);
static inline void ToCMYK(const NzColor& color, float* cyan, float* magenta, float* yellow, float* black); static inline void ToCMYK(const Color& color, float* cyan, float* magenta, float* yellow, float* black);
static inline void ToHSL(const NzColor& color, nzUInt8* hue, nzUInt8* saturation, nzUInt8* lightness); static inline void ToHSL(const Color& color, UInt8* hue, UInt8* saturation, UInt8* lightness);
static inline void ToHSV(const NzColor& color, float* hue, float* saturation, float* value); static inline void ToHSV(const Color& color, float* hue, float* saturation, float* value);
static inline void ToXYZ(const NzColor& color, NzVector3f* vec); static inline void ToXYZ(const Color& color, Vector3f* vec);
static inline void ToXYZ(const NzColor& color, float* x, float* y, float* z); static inline void ToXYZ(const Color& color, float* x, float* y, float* z);
nzUInt8 r, g, b, a; UInt8 r, g, b, a;
static NAZARA_CORE_API const NzColor Black; static NAZARA_CORE_API const Color Black;
static NAZARA_CORE_API const NzColor Blue; static NAZARA_CORE_API const Color Blue;
static NAZARA_CORE_API const NzColor Cyan; static NAZARA_CORE_API const Color Cyan;
static NAZARA_CORE_API const NzColor Green; static NAZARA_CORE_API const Color Green;
static NAZARA_CORE_API const NzColor Magenta; static NAZARA_CORE_API const Color Magenta;
static NAZARA_CORE_API const NzColor Orange; static NAZARA_CORE_API const Color Orange;
static NAZARA_CORE_API const NzColor Red; static NAZARA_CORE_API const Color Red;
static NAZARA_CORE_API const NzColor Yellow; static NAZARA_CORE_API const Color Yellow;
static NAZARA_CORE_API const NzColor White; static NAZARA_CORE_API const Color White;
private: private:
static float Hue2RGB(float v1, float v2, float vH); static float Hue2RGB(float v1, float v2, float vH);
}; };
}
std::ostream& operator<<(std::ostream& out, const NzColor& color); std::ostream& operator<<(std::ostream& out, const Nz::Color& color);
#include <Nazara/Core/Color.inl> #include <Nazara/Core/Color.inl>

View File

@ -9,411 +9,416 @@
#include <stdexcept> #include <stdexcept>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
inline NzColor::NzColor() namespace Nz
{ {
} inline Color::Color()
inline NzColor::NzColor(nzUInt8 red, nzUInt8 green, nzUInt8 blue, nzUInt8 alpha) :
r(red),
g(green),
b(blue),
a(alpha)
{
}
inline NzColor::NzColor(nzUInt8 lightness) :
r(lightness),
g(lightness),
b(lightness),
a(255)
{
}
inline NzColor::NzColor(nzUInt8 vec[3], nzUInt8 alpha) :
r(vec[0]),
g(vec[1]),
b(vec[2]),
a(alpha)
{
}
inline NzString NzColor::ToString() const
{
NzStringStream ss;
ss << "Color(" << static_cast<int>(r) << ", " << static_cast<int>(g) << ", " << static_cast<int>(b);
if (a != 255)
ss << ", " << static_cast<int>(a);
ss << ')';
return ss;
}
inline NzColor NzColor::operator+(const NzColor& color) const
{
NzColor c;
c.r = std::min(static_cast<unsigned int>(r) + static_cast<unsigned int>(color.r), 255U);
c.g = std::min(static_cast<unsigned int>(g) + static_cast<unsigned int>(color.g), 255U);
c.b = std::min(static_cast<unsigned int>(b) + static_cast<unsigned int>(color.b), 255U);
c.a = std::min(static_cast<unsigned int>(a) + static_cast<unsigned int>(color.a), 255U);
return c;
}
inline NzColor NzColor::operator*(const NzColor& color) const
{
NzColor c;
c.r = (static_cast<unsigned int>(r) * static_cast<unsigned int>(color.r)) / 255U;
c.g = (static_cast<unsigned int>(g) * static_cast<unsigned int>(color.g)) / 255U;
c.b = (static_cast<unsigned int>(b) * static_cast<unsigned int>(color.b)) / 255U;
c.a = (static_cast<unsigned int>(a) * static_cast<unsigned int>(color.a)) / 255U;
return c;
}
inline NzColor NzColor::operator+=(const NzColor& color)
{
return operator=(operator+(color));
}
inline NzColor NzColor::operator*=(const NzColor& color)
{
return operator=(operator*(color));
}
inline bool NzColor::operator==(const NzColor& color) const
{
return r == color.r && g == color.g && b == color.b && a == color.a;
}
inline bool NzColor::operator!=(const NzColor& color) const
{
return !operator==(color);
}
// Algorithmes venant de http://www.easyrgb.com/index.php?X=MATH
inline NzColor NzColor::FromCMY(float cyan, float magenta, float yellow)
{
return NzColor(static_cast<nzUInt8>((1.f-cyan)*255.f), static_cast<nzUInt8>((1.f-magenta)*255.f), static_cast<nzUInt8>((1.f-yellow)*255.f));
}
inline NzColor NzColor::FromCMYK(float cyan, float magenta, float yellow, float black)
{
return FromCMY(cyan * (1.f - black) + black,
magenta * (1.f - black) + black,
yellow * (1.f - black) + black);
}
inline NzColor NzColor::FromHSL(nzUInt8 hue, nzUInt8 saturation, nzUInt8 lightness)
{
if (saturation == 0)
{ {
// RGB results from 0 to 255
return NzColor(lightness * 255,
lightness * 255,
lightness * 255);
} }
else
inline Color::Color(UInt8 red, UInt8 green, UInt8 blue, UInt8 alpha) :
r(red),
g(green),
b(blue),
a(alpha)
{ {
// Norme Windows
float l = lightness/240.f;
float h = hue/240.f;
float s = saturation/240.f;
float v2;
if (l < 0.5f)
v2 = l * (1.f + s);
else
v2 = (l + s) - (s*l);
float v1 = 2.f * l - v2;
return NzColor(static_cast<nzUInt8>(255.f * Hue2RGB(v1, v2, h + (1.f/3.f))),
static_cast<nzUInt8>(255.f * Hue2RGB(v1, v2, h)),
static_cast<nzUInt8>(255.f * Hue2RGB(v1, v2, h - (1.f/3.f))));
} }
}
inline NzColor NzColor::FromHSV(float hue, float saturation, float value) inline Color::Color(UInt8 lightness) :
{ r(lightness),
if (NzNumberEquals(saturation, 0.f)) g(lightness),
return NzColor(static_cast<nzUInt8>(value * 255.f)); b(lightness),
else a(255)
{ {
float h = hue/360.f * 6.f; }
float s = saturation/360.f;
if (NzNumberEquals(h, 6.f)) inline Color::Color(UInt8 vec[3], UInt8 alpha) :
h = 0; // hue must be < 1 r(vec[0]),
g(vec[1]),
b(vec[2]),
a(alpha)
{
}
int i = static_cast<unsigned int>(h); inline String Color::ToString() const
float v1 = value * (1.f - s); {
float v2 = value * (1.f - s * (h - i)); StringStream ss;
float v3 = value * (1.f - s * (1.f - (h - i))); ss << "Color(" << static_cast<int>(r) << ", " << static_cast<int>(g) << ", " << static_cast<int>(b);
float r, g, b; if (a != 255)
switch (i) ss << ", " << static_cast<int>(a);
ss << ')';
return ss;
}
inline Color Color::operator+(const Color& color) const
{
///TODO: Improve this shit
Color c;
c.r = static_cast<UInt8>(std::min(static_cast<unsigned int>(r) + static_cast<unsigned int>(color.r), 255U));
c.g = static_cast<UInt8>(std::min(static_cast<unsigned int>(g) + static_cast<unsigned int>(color.g), 255U));
c.b = static_cast<UInt8>(std::min(static_cast<unsigned int>(b) + static_cast<unsigned int>(color.b), 255U));
c.a = static_cast<UInt8>(std::min(static_cast<unsigned int>(a) + static_cast<unsigned int>(color.a), 255U));
return c;
}
inline Color Color::operator*(const Color& color) const
{
///TODO: Improve this shit
Color c;
c.r = static_cast<UInt8>((static_cast<unsigned int>(r) * static_cast<unsigned int>(color.r)) / 255U);
c.g = static_cast<UInt8>((static_cast<unsigned int>(g) * static_cast<unsigned int>(color.g)) / 255U);
c.b = static_cast<UInt8>((static_cast<unsigned int>(b) * static_cast<unsigned int>(color.b)) / 255U);
c.a = static_cast<UInt8>((static_cast<unsigned int>(a) * static_cast<unsigned int>(color.a)) / 255U);
return c;
}
inline Color Color::operator+=(const Color& color)
{
return operator=(operator+(color));
}
inline Color Color::operator*=(const Color& color)
{
return operator=(operator*(color));
}
inline bool Color::operator==(const Color& color) const
{
return r == color.r && g == color.g && b == color.b && a == color.a;
}
inline bool Color::operator!=(const Color& color) const
{
return !operator==(color);
}
// Algorithmes venant de http://www.easyrgb.com/index.php?X=MATH
inline Color Color::FromCMY(float cyan, float magenta, float yellow)
{
return Color(static_cast<UInt8>((1.f-cyan)*255.f), static_cast<UInt8>((1.f-magenta)*255.f), static_cast<UInt8>((1.f-yellow)*255.f));
}
inline Color Color::FromCMYK(float cyan, float magenta, float yellow, float black)
{
return FromCMY(cyan * (1.f - black) + black,
magenta * (1.f - black) + black,
yellow * (1.f - black) + black);
}
inline Color Color::FromHSL(UInt8 hue, UInt8 saturation, UInt8 lightness)
{
if (saturation == 0)
{ {
case 0: // RGB results from 0 to 255
r = value; return Color(lightness * 255,
g = v3; lightness * 255,
b = v1; lightness * 255);
break; }
else
{
// Norme Windows
float l = lightness/240.f;
float h = hue/240.f;
float s = saturation/240.f;
case 1: float v2;
r = v2; if (l < 0.5f)
g = value; v2 = l * (1.f + s);
b = v1; else
break; v2 = (l + s) - (s*l);
case 2: float v1 = 2.f * l - v2;
r = v1;
g = value;
b = v3;
break;
case 3: return Color(static_cast<UInt8>(255.f * Hue2RGB(v1, v2, h + (1.f/3.f))),
r = v1; static_cast<UInt8>(255.f * Hue2RGB(v1, v2, h)),
g = v2; static_cast<UInt8>(255.f * Hue2RGB(v1, v2, h - (1.f/3.f))));
b = value; }
break; }
case 4: inline Color Color::FromHSV(float hue, float saturation, float value)
r = v3; {
g = v1; if (NumberEquals(saturation, 0.f))
b = value; return Color(static_cast<UInt8>(value * 255.f));
break; else
{
float h = hue/360.f * 6.f;
float s = saturation/360.f;
default: if (NumberEquals(h, 6.f))
r = value; h = 0; // hue must be < 1
g = v1;
b = v2; int i = static_cast<unsigned int>(h);
break; float v1 = value * (1.f - s);
float v2 = value * (1.f - s * (h - i));
float v3 = value * (1.f - s * (1.f - (h - i)));
float r, g, b;
switch (i)
{
case 0:
r = value;
g = v3;
b = v1;
break;
case 1:
r = v2;
g = value;
b = v1;
break;
case 2:
r = v1;
g = value;
b = v3;
break;
case 3:
r = v1;
g = v2;
b = value;
break;
case 4:
r = v3;
g = v1;
b = value;
break;
default:
r = value;
g = v1;
b = v2;
break;
}
// RGB results from 0 to 255
return Color(static_cast<UInt8>(r*255.f), static_cast<UInt8>(g*255.f), static_cast<UInt8>(b*255.f));
}
}
inline Color Color::FromXYZ(const Vector3f& vec)
{
return FromXYZ(vec.x, vec.y, vec.z);
}
inline Color Color::FromXYZ(float x, float y, float z)
{
x /= 100.f; // X from 0 to 95.047
y /= 100.f; // Y from 0 to 100.000
z /= 100.f; // Z from 0 to 108.883
float r = x * 3.2406f + y * -1.5372f + z * -0.4986f;
float g = x * -0.9689f + y * 1.8758f + z * 0.0415f;
float b = x * 0.0557f + y * -0.2040f + z * 1.0570f;
if (r > 0.0031308f)
r = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
r *= 12.92f;
if (g > 0.0031308f)
g = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
g *= 12.92f;
if (b > 0.0031308f)
b = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
b *= 12.92f;
return Color(static_cast<UInt8>(r * 255.f), static_cast<UInt8>(g * 255.f), static_cast<UInt8>(b * 255.f));
}
inline void Color::ToCMY(const Color& color, float* cyan, float* magenta, float* yellow)
{
*cyan = 1.f - color.r/255.f;
*magenta = 1.f - color.g/255.f;
*yellow = 1.f - color.b/255.f;
}
inline void Color::ToCMYK(const Color& color, float* cyan, float* magenta, float* yellow, float* black)
{
float c, m, y;
ToCMY(color, &c, &m, &y);
float k = std::min({1.f, c, m, y});
if (NumberEquals(k, 1.f))
{
//Black
*cyan = 0.f;
*magenta = 0.f;
*yellow = 0.f;
}
else
{
*cyan = (c-k)/(1.f-k);
*magenta = (m-k)/(1.f-k);
*yellow = (y-k)/(1.f-k);
} }
// RGB results from 0 to 255 *black = k;
return NzColor(static_cast<nzUInt8>(r*255.f), static_cast<nzUInt8>(g*255.f), static_cast<nzUInt8>(b*255.f));
}
}
inline NzColor NzColor::FromXYZ(const NzVector3f& vec)
{
return FromXYZ(vec.x, vec.y, vec.z);
}
inline NzColor NzColor::FromXYZ(float x, float y, float z)
{
x /= 100.f; // X from 0 to 95.047
y /= 100.f; // Y from 0 to 100.000
z /= 100.f; // Z from 0 to 108.883
float r = x * 3.2406f + y * -1.5372f + z * -0.4986f;
float g = x * -0.9689f + y * 1.8758f + z * 0.0415f;
float b = x * 0.0557f + y * -0.2040f + z * 1.0570f;
if (r > 0.0031308f)
r = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
r *= 12.92f;
if (g > 0.0031308f)
g = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
g *= 12.92f;
if (b > 0.0031308f)
b = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
b *= 12.92f;
return NzColor(static_cast<nzUInt8>(r * 255.f), static_cast<nzUInt8>(g * 255.f), static_cast<nzUInt8>(b * 255.f));
}
inline void NzColor::ToCMY(const NzColor& color, float* cyan, float* magenta, float* yellow)
{
*cyan = 1.f - color.r/255.f;
*magenta = 1.f - color.g/255.f;
*yellow = 1.f - color.b/255.f;
}
inline void NzColor::ToCMYK(const NzColor& color, float* cyan, float* magenta, float* yellow, float* black)
{
float c, m, y;
ToCMY(color, &c, &m, &y);
float k = std::min({1.f, c, m, y});
if (NzNumberEquals(k, 1.f))
{
//Black
*cyan = 0.f;
*magenta = 0.f;
*yellow = 0.f;
}
else
{
*cyan = (c-k)/(1.f-k);
*magenta = (m-k)/(1.f-k);
*yellow = (y-k)/(1.f-k);
} }
*black = k; inline void Color::ToHSL(const Color& color, UInt8* hue, UInt8* saturation, UInt8* lightness)
}
inline void NzColor::ToHSL(const NzColor& color, nzUInt8* hue, nzUInt8* saturation, nzUInt8* lightness)
{
float r = color.r / 255.f;
float g = color.g / 255.f;
float b = color.b / 255.f;
float min = std::min({r, g, b}); // Min. value of RGB
float max = std::max({r, g, b}); // Max. value of RGB
float deltaMax = max - min; //Delta RGB value
float l = (max + min)/2.f;
if (NzNumberEquals(deltaMax, 0.f))
{ {
//This is a gray, no chroma... float r = color.r / 255.f;
*hue = 0; //HSL results from 0 to 1 float g = color.g / 255.f;
*saturation = 0; float b = color.b / 255.f;
}
else float min = std::min({r, g, b}); // Min. value of RGB
{ float max = std::max({r, g, b}); // Max. value of RGB
//Chromatic data...
if (l < 0.5f) float deltaMax = max - min; //Delta RGB value
*saturation = static_cast<nzUInt8>(deltaMax/(max+min)*240.f);
float l = (max + min)/2.f;
if (NumberEquals(deltaMax, 0.f))
{
//This is a gray, no chroma...
*hue = 0; //HSL results from 0 to 1
*saturation = 0;
}
else else
*saturation = static_cast<nzUInt8>(deltaMax/(2.f-max-min)*240.f); {
//Chromatic data...
if (l < 0.5f)
*saturation = static_cast<UInt8>(deltaMax/(max+min)*240.f);
else
*saturation = static_cast<UInt8>(deltaMax/(2.f-max-min)*240.f);
*lightness = static_cast<nzUInt8>(l*240.f); *lightness = static_cast<UInt8>(l*240.f);
float deltaR = ((max - r)/6.f + deltaMax/2.f)/deltaMax; float deltaR = ((max - r)/6.f + deltaMax/2.f)/deltaMax;
float deltaG = ((max - g)/6.f + deltaMax/2.f)/deltaMax; float deltaG = ((max - g)/6.f + deltaMax/2.f)/deltaMax;
float deltaB = ((max - b)/6.f + deltaMax/2.f)/deltaMax; float deltaB = ((max - b)/6.f + deltaMax/2.f)/deltaMax;
float h; float h;
if (NzNumberEquals(r, max)) if (NumberEquals(r, max))
h = deltaB - deltaG; h = deltaB - deltaG;
else if (NzNumberEquals(g, max)) else if (NumberEquals(g, max))
h = (1.f/3.f) + deltaR - deltaB; h = (1.f/3.f) + deltaR - deltaB;
else else
h = (2.f/3.f) + deltaG - deltaR; h = (2.f/3.f) + deltaG - deltaR;
if (h < 0.f) if (h < 0.f)
h += 1.f; h += 1.f;
else if (h > 1.f) else if (h > 1.f)
h -= 1.f; h -= 1.f;
*hue = static_cast<nzUInt8>(h*240.f); *hue = static_cast<UInt8>(h*240.f);
}
} }
}
inline void NzColor::ToHSV(const NzColor& color, float* hue, float* saturation, float* value) inline void Color::ToHSV(const Color& color, float* hue, float* saturation, float* value)
{
float r = color.r / 255.f;
float g = color.g / 255.f;
float b = color.b / 255.f;
float min = std::min({r, g, b}); //Min. value of RGB
float max = std::max({r, g, b}); //Max. value of RGB
float deltaMax = max - min; //Delta RGB value
*value = max;
if (NzNumberEquals(deltaMax, 0.f))
{ {
//This is a gray, no chroma... float r = color.r / 255.f;
*hue = 0; //HSV results from 0 to 1 float g = color.g / 255.f;
*saturation = 0; float b = color.b / 255.f;
}
else
{
//Chromatic data...
*saturation = deltaMax/max*360.f;
float deltaR = ((max - r)/6.f + deltaMax/2.f)/deltaMax; float min = std::min({r, g, b}); //Min. value of RGB
float deltaG = ((max - g)/6.f + deltaMax/2.f)/deltaMax; float max = std::max({r, g, b}); //Max. value of RGB
float deltaB = ((max - b)/6.f + deltaMax/2.f)/deltaMax;
float h; float deltaMax = max - min; //Delta RGB value
if (NzNumberEquals(r, max)) *value = max;
h = deltaB - deltaG;
else if (NzNumberEquals(g, max)) if (NumberEquals(deltaMax, 0.f))
h = (1.f/3.f) + deltaR - deltaB; {
//This is a gray, no chroma...
*hue = 0; //HSV results from 0 to 1
*saturation = 0;
}
else else
h = (2.f/3.f) + deltaG - deltaR; {
//Chromatic data...
*saturation = deltaMax/max*360.f;
if (h < 0.f) float deltaR = ((max - r)/6.f + deltaMax/2.f)/deltaMax;
h += 1.f; float deltaG = ((max - g)/6.f + deltaMax/2.f)/deltaMax;
else if (h > 1.f) float deltaB = ((max - b)/6.f + deltaMax/2.f)/deltaMax;
h -= 1.f;
*hue = h*360.f; float h;
if (NumberEquals(r, max))
h = deltaB - deltaG;
else if (NumberEquals(g, max))
h = (1.f/3.f) + deltaR - deltaB;
else
h = (2.f/3.f) + deltaG - deltaR;
if (h < 0.f)
h += 1.f;
else if (h > 1.f)
h -= 1.f;
*hue = h*360.f;
}
} }
inline void Color::ToXYZ(const Color& color, Vector3f* vec)
{
return ToXYZ(color, &vec->x, &vec->y, &vec->z);
}
inline void Color::ToXYZ(const Color& color, float* x, float* y, float* z)
{
float r = color.r/255.f; //R from 0 to 255
float g = color.g/255.f; //G from 0 to 255
float b = color.b/255.f; //B from 0 to 255
if (r > 0.04045f)
r = std::pow((r + 0.055f)/1.055f, 2.4f);
else
r /= 12.92f;
if (g > 0.04045f)
g = std::pow((g + 0.055f)/1.055f, 2.4f);
else
g /= 12.92f;
if (b > 0.04045f)
b = std::pow((b + 0.055f)/1.055f, 2.4f);
else
b /= 12.92f;
r *= 100.f;
g *= 100.f;
b *= 100.f;
//Observer. = 2°, Illuminant = D65
*x = r*0.4124f + g*0.3576f + b*0.1805f;
*y = r*0.2126f + g*0.7152f + b*0.0722f;
*z = r*0.0193f + g*0.1192f + b*0.9505f;
}
inline float Color::Hue2RGB(float v1, float v2, float vH)
{
if (vH < 0.f)
vH += 1;
if (vH > 1.f)
vH -= 1;
if ((6.f * vH) < 1.f)
return v1 + (v2-v1)*6*vH;
if ((2.f * vH) < 1.f)
return v2;
if ((3.f * vH) < 2.f)
return v1 + (v2 - v1)*(2.f/3.f - vH)*6;
return v1;
}
} }
inline void NzColor::ToXYZ(const NzColor& color, NzVector3f* vec) inline std::ostream& operator<<(std::ostream& out, const Nz::Color& color)
{
return ToXYZ(color, &vec->x, &vec->y, &vec->z);
}
inline void NzColor::ToXYZ(const NzColor& color, float* x, float* y, float* z)
{
float r = color.r/255.f; //R from 0 to 255
float g = color.g/255.f; //G from 0 to 255
float b = color.b/255.f; //B from 0 to 255
if (r > 0.04045f)
r = std::pow((r + 0.055f)/1.055f, 2.4f);
else
r /= 12.92f;
if (g > 0.04045f)
g = std::pow((g + 0.055f)/1.055f, 2.4f);
else
g /= 12.92f;
if (b > 0.04045f)
b = std::pow((b + 0.055f)/1.055f, 2.4f);
else
b /= 12.92f;
r *= 100.f;
g *= 100.f;
b *= 100.f;
//Observer. = 2°, Illuminant = D65
*x = r*0.4124f + g*0.3576f + b*0.1805f;
*y = r*0.2126f + g*0.7152f + b*0.0722f;
*z = r*0.0193f + g*0.1192f + b*0.9505f;
}
inline float NzColor::Hue2RGB(float v1, float v2, float vH)
{
if (vH < 0.f)
vH += 1;
if (vH > 1.f)
vH -= 1;
if ((6.f * vH) < 1.f)
return v1 + (v2-v1)*6*vH;
if ((2.f * vH) < 1.f)
return v2;
if ((3.f * vH) < 2.f)
return v1 + (v2 - v1)*(2.f/3.f - vH)*6;
return v1;
}
inline std::ostream& operator<<(std::ostream& out, const NzColor& color)
{ {
return out << color.ToString(); return out << color.ToString();
} }

View File

@ -8,25 +8,32 @@
#define NAZARA_CONDITIONVARIABLE_HPP #define NAZARA_CONDITIONVARIABLE_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
class NzConditionVariableImpl; namespace Nz
class NzMutex;
class NAZARA_CORE_API NzConditionVariable : NzNonCopyable
{ {
public: class ConditionVariableImpl;
NzConditionVariable(); class Mutex;
~NzConditionVariable();
void Signal(); class NAZARA_CORE_API ConditionVariable
void SignalAll(); {
public:
ConditionVariable();
ConditionVariable(const ConditionVariable&) = delete;
ConditionVariable(ConditionVariable&&) = delete; ///TODO
~ConditionVariable();
void Wait(NzMutex* mutex); void Signal();
bool Wait(NzMutex* mutex, nzUInt32 timeout); void SignalAll();
private: void Wait(Mutex* mutex);
NzConditionVariableImpl* m_impl; bool Wait(Mutex* mutex, UInt32 timeout);
};
ConditionVariable& operator=(const ConditionVariable&) = delete;
ConditionVariable& operator=(ConditionVariable&&) = delete; ///TODO
private:
ConditionVariableImpl* m_impl;
};
}
#endif // NAZARA_CONDITIONVARIABLE_HPP #endif // NAZARA_CONDITIONVARIABLE_HPP

View File

@ -44,7 +44,7 @@
// Taille du buffer lors d'une lecture complète d'un fichier (ex: Hash) // Taille du buffer lors d'une lecture complète d'un fichier (ex: Hash)
#define NAZARA_CORE_FILE_BUFFERSIZE 4096 #define NAZARA_CORE_FILE_BUFFERSIZE 4096
// Incorpore la table Unicode Character Data (Nécessaires pour faire fonctionner le flag NzString::HandleUTF8) // Incorpore la table Unicode Character Data (Nécessaires pour faire fonctionner le flag String::HandleUTF8)
#define NAZARA_CORE_INCLUDE_UNICODEDATA 0 #define NAZARA_CORE_INCLUDE_UNICODEDATA 0
// Utilise le MemoryManager pour gérer les allocations dynamiques (détecte les leaks au prix d'allocations/libérations dynamiques plus lentes) // Utilise le MemoryManager pour gérer les allocations dynamiques (détecte les leaks au prix d'allocations/libérations dynamiques plus lentes)
@ -57,12 +57,12 @@
#define NAZARA_CORE_THREADSAFE 1 #define NAZARA_CORE_THREADSAFE 1
// Les classes à protéger des accès concurrentiels // Les classes à protéger des accès concurrentiels
#define NAZARA_THREADSAFETY_CLOCK 0 // NzClock #define NAZARA_THREADSAFETY_CLOCK 0 // Clock
#define NAZARA_THREADSAFETY_DIRECTORY 1 // NzDirectory #define NAZARA_THREADSAFETY_DIRECTORY 1 // Directory
#define NAZARA_THREADSAFETY_DYNLIB 1 // NzDynLib #define NAZARA_THREADSAFETY_DYNLIB 1 // DynLib
#define NAZARA_THREADSAFETY_FILE 1 // NzFile #define NAZARA_THREADSAFETY_FILE 1 // File
#define NAZARA_THREADSAFETY_LOG 1 // NzLog #define NAZARA_THREADSAFETY_LOG 1 // Log
#define NAZARA_THREADSAFETY_REFCOUNTED 1 // NzRefCounted #define NAZARA_THREADSAFETY_REFCOUNTED 1 // RefCounted
// Le nombre de spinlocks à utiliser avec les sections critiques de Windows (0 pour désactiver) // Le nombre de spinlocks à utiliser avec les sections critiques de Windows (0 pour désactiver)
#define NAZARA_CORE_WINDOWS_CS_SPINLOCKS 4096 #define NAZARA_CORE_WINDOWS_CS_SPINLOCKS 4096

View File

@ -10,20 +10,23 @@
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Initializer.hpp> #include <Nazara/Core/Initializer.hpp>
class NAZARA_CORE_API NzCore namespace Nz
{ {
public: class NAZARA_CORE_API Core
NzCore() = delete; {
~NzCore() = delete; public:
Core() = delete;
~Core() = delete;
static bool Initialize(); static bool Initialize();
static bool IsInitialized(); static bool IsInitialized();
static void Uninitialize(); static void Uninitialize();
private: private:
static unsigned int s_moduleReferenceCounter; static unsigned int s_moduleReferenceCounter;
}; };
}
#endif // NAZARA_CORE_HPP #endif // NAZARA_CORE_HPP

View File

@ -21,7 +21,7 @@ NAZARA_CORE_API void operator delete[](void* ptr, const char* file, unsigned int
#endif // NAZARA_DEBUG_NEWREDEFINITION_HPP #endif // NAZARA_DEBUG_NEWREDEFINITION_HPP
#ifndef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION #ifndef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION
#define delete NzMemoryManager::NextFree(__FILE__, __LINE__), delete #define delete MemoryManager::NextFree(__FILE__, __LINE__), delete
#define new new(__FILE__, __LINE__) #define new new(__FILE__, __LINE__)
#endif #endif

View File

@ -8,7 +8,6 @@
#define NAZARA_DIRECTORY_HPP #define NAZARA_DIRECTORY_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/String.hpp> #include <Nazara/Core/String.hpp>
#if defined(NAZARA_PLATFORM_WINDOWS) #if defined(NAZARA_PLATFORM_WINDOWS)
@ -26,49 +25,57 @@
#include <Nazara/Core/ThreadSafetyOff.hpp> #include <Nazara/Core/ThreadSafetyOff.hpp>
#endif #endif
class NzDirectoryImpl; namespace Nz
class NAZARA_CORE_API NzDirectory : NzNonCopyable
{ {
public: class DirectoryImpl;
NzDirectory();
NzDirectory(const NzString& dirPath);
~NzDirectory();
void Close(); class NAZARA_CORE_API Directory
{
public:
Directory();
Directory(const String& dirPath);
Directory(const Directory&) = delete;
Directory(Directory&&) = delete; ///TODO
~Directory();
bool Exists() const; void Close();
NzString GetPath() const; bool Exists() const;
NzString GetPattern() const;
NzString GetResultName() const;
NzString GetResultPath() const;
nzUInt64 GetResultSize() const;
bool IsOpen() const; String GetPath() const;
bool IsResultDirectory() const; String GetPattern() const;
String GetResultName() const;
String GetResultPath() const;
UInt64 GetResultSize() const;
bool NextResult(bool skipDots = true); bool IsOpen() const;
bool IsResultDirectory() const;
bool Open(); bool NextResult(bool skipDots = true);
void SetPath(const NzString& dirPath); bool Open();
void SetPattern(const NzString& pattern);
static bool Copy(const NzString& sourcePath, const NzString& destPath); void SetPath(const String& dirPath);
static bool Create(const NzString& dirPath, bool recursive = false); void SetPattern(const String& pattern);
static bool Exists(const NzString& dirPath);
static NzString GetCurrent();
static const char* GetCurrentFileRelativeToEngine(const char* currentFile);
static bool Remove(const NzString& dirPath, bool emptyDirectory = false);
static bool SetCurrent(const NzString& dirPath);
private: static bool Copy(const String& sourcePath, const String& destPath);
NazaraMutexAttrib(m_mutex, mutable) static bool Create(const String& dirPath, bool recursive = false);
static bool Exists(const String& dirPath);
static String GetCurrent();
static const char* GetCurrentFileRelativeToEngine(const char* currentFile);
static bool Remove(const String& dirPath, bool emptyDirectory = false);
static bool SetCurrent(const String& dirPath);
NzString m_dirPath; Directory& operator=(const Directory&) = delete;
NzString m_pattern; Directory& operator=(Directory&&) = delete; ///TODO
NzDirectoryImpl* m_impl;
}; private:
NazaraMutexAttrib(m_mutex, mutable)
String m_dirPath;
String m_pattern;
DirectoryImpl* m_impl;
};
}
#endif // NAZARA_DIRECTORY_HPP #endif // NAZARA_DIRECTORY_HPP

View File

@ -8,7 +8,6 @@
#define NAZARA_DYNLIB_HPP #define NAZARA_DYNLIB_HPP
#include <Nazara/Prerequesites.hpp> #include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/String.hpp> #include <Nazara/Core/String.hpp>
#if defined(NAZARA_PLATFORM_WINDOWS) #if defined(NAZARA_PLATFORM_WINDOWS)
@ -27,32 +26,37 @@
#include <Nazara/Core/ThreadSafetyOff.hpp> #include <Nazara/Core/ThreadSafetyOff.hpp>
#endif #endif
using NzDynLibFunc = int (*)(); // Type "générique" de pointeur sur fonction namespace Nz
class NzDynLibImpl;
class NAZARA_CORE_API NzDynLib : NzNonCopyable
{ {
public: using DynLibFunc = int (*)(); // Type "générique" de pointeur sur fonction
NzDynLib();
NzDynLib(NzDynLib&& lib);
~NzDynLib();
NzString GetLastError() const; class DynLibImpl;
NzDynLibFunc GetSymbol(const NzString& symbol) const;
bool IsLoaded() const; class NAZARA_CORE_API DynLib
{
public:
DynLib();
DynLib(const DynLib&) = delete;
DynLib(DynLib&& lib);
~DynLib();
bool Load(const NzString& libraryPath); String GetLastError() const;
void Unload(); DynLibFunc GetSymbol(const String& symbol) const;
NzDynLib& operator=(NzDynLib&& lib); bool IsLoaded() const;
private: bool Load(const String& libraryPath);
NazaraMutexAttrib(m_mutex, mutable) void Unload();
mutable NzString m_lastError; DynLib& operator=(const DynLib&) = delete;
NzDynLibImpl* m_impl; DynLib& operator=(DynLib&& lib);
private:
NazaraMutexAttrib(m_mutex, mutable)
mutable String m_lastError;
DynLibImpl* m_impl;
}; };
}
#endif // NAZARA_DYNLIB_HPP #endif // NAZARA_DYNLIB_HPP

View File

@ -25,8 +25,11 @@
#error You cannot define both NAZARA_BIG_ENDIAN and NAZARA_LITTLE_ENDIAN #error You cannot define both NAZARA_BIG_ENDIAN and NAZARA_LITTLE_ENDIAN
#endif #endif
inline void NzByteSwap(void* buffer, unsigned int size); namespace Nz
inline nzEndianness NzGetPlatformEndianness(); {
inline constexpr Endianness GetPlatformEndianness();
inline void SwapBytes(void* buffer, unsigned int size);
}
#include <Nazara/Core/Endianness.inl> #include <Nazara/Core/Endianness.inl>

View File

@ -5,23 +5,26 @@
#include <algorithm> #include <algorithm>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
inline void NzByteSwap(void* buffer, unsigned int size) namespace Nz
{ {
nzUInt8* bytes = reinterpret_cast<nzUInt8*>(buffer); inline constexpr Endianness GetPlatformEndianness()
unsigned int i = 0; {
unsigned int j = size-1; #if defined(NAZARA_BIG_ENDIAN)
return Endianness_BigEndian;
#elif defined(NAZARA_LITTLE_ENDIAN)
return Endianness_LittleEndian;
#endif
}
while (i < j) inline void SwapBytes(void* buffer, unsigned int size)
std::swap(bytes[i++], bytes[j--]); {
} UInt8* bytes = reinterpret_cast<UInt8*>(buffer);
unsigned int i = 0;
unsigned int j = size-1;
inline nzEndianness NzGetPlatformEndianness() while (i < j)
{ std::swap(bytes[i++], bytes[j--]);
#if defined(NAZARA_BIG_ENDIAN) }
return nzEndianness_BigEndian;
#elif defined(NAZARA_LITTLE_ENDIAN)
return nzEndianness_LittleEndian;
#endif
} }
#include <Nazara/Core/DebugOff.hpp> #include <Nazara/Core/DebugOff.hpp>

View File

@ -7,182 +7,187 @@
#ifndef NAZARA_ENUMS_CORE_HPP #ifndef NAZARA_ENUMS_CORE_HPP
#define NAZARA_ENUMS_CORE_HPP #define NAZARA_ENUMS_CORE_HPP
enum nzCoordSys namespace Nz
{ {
nzCoordSys_Global, enum CoordSys
nzCoordSys_Local, {
CoordSys_Global,
CoordSys_Local,
nzCoordSys_Max = nzCoordSys_Local CoordSys_Max = CoordSys_Local
}; };
enum nzCursorPosition enum CursorPosition
{ {
nzCursorPosition_AtBegin, // Début du fichier CursorPosition_AtBegin, // Début du fichier
nzCursorPosition_AtCurrent, // Position du pointeur CursorPosition_AtCurrent, // Position du pointeur
nzCursorPosition_AtEnd, // Fin du fichier CursorPosition_AtEnd, // Fin du fichier
nzCursorPosition_Max = nzCursorPosition_AtEnd CursorPosition_Max = CursorPosition_AtEnd
}; };
enum nzEndianness enum Endianness
{ {
nzEndianness_Unknown = -1, Endianness_Unknown = -1,
nzEndianness_BigEndian, Endianness_BigEndian,
nzEndianness_LittleEndian, Endianness_LittleEndian,
nzEndianness_Max = nzEndianness_LittleEndian Endianness_Max = Endianness_LittleEndian
}; };
enum nzErrorFlag enum ErrorFlag
{ {
nzErrorFlag_None = 0, ErrorFlag_None = 0,
nzErrorFlag_Silent = 0x1, ErrorFlag_Silent = 0x1,
nzErrorFlag_SilentDisabled = 0x2, ErrorFlag_SilentDisabled = 0x2,
nzErrorFlag_ThrowException = 0x4, ErrorFlag_ThrowException = 0x4,
nzErrorFlag_ThrowExceptionDisabled = 0x8, ErrorFlag_ThrowExceptionDisabled = 0x8,
nzErrorFlag_Max = nzErrorFlag_ThrowExceptionDisabled*2-1 ErrorFlag_Max = ErrorFlag_ThrowExceptionDisabled*2-1
}; };
enum nzErrorType enum ErrorType
{ {
nzErrorType_AssertFailed, ErrorType_AssertFailed,
nzErrorType_Internal, ErrorType_Internal,
nzErrorType_Normal, ErrorType_Normal,
nzErrorType_Warning, ErrorType_Warning,
nzErrorType_Max = nzErrorType_Warning ErrorType_Max = ErrorType_Warning
}; };
enum nzHash enum HashType
{ {
nzHash_CRC32, HashType_CRC32,
nzHash_Fletcher16, HashType_Fletcher16,
nzHash_MD5, HashType_MD5,
nzHash_SHA1, HashType_SHA1,
nzHash_SHA224, HashType_SHA224,
nzHash_SHA256, HashType_SHA256,
nzHash_SHA384, HashType_SHA384,
nzHash_SHA512, HashType_SHA512,
nzHash_Whirlpool, HashType_Whirlpool,
nzHash_Max = nzHash_Whirlpool HashType_Max = HashType_Whirlpool
}; };
enum nzOpenModeFlags enum OpenModeFlags
{ {
nzOpenMode_Current = 0x00, // Utilise le mode d'ouverture actuel OpenMode_NotOpen = 0x00, // Utilise le mode d'ouverture actuel
nzOpenMode_Append = 0x01, // Empêche l'écriture sur la partie déjà existante et met le curseur à la fin OpenMode_Append = 0x01, // Empêche l'écriture sur la partie déjà existante et met le curseur à la fin
nzOpenMode_Lock = 0x02, // Empêche le fichier d'être modifié tant qu'il est ouvert OpenMode_Lock = 0x02, // Empêche le fichier d'être modifié tant qu'il est ouvert
nzOpenMode_ReadOnly = 0x04, // Ouvre uniquement en lecture OpenMode_ReadOnly = 0x04, // Ouvre uniquement en lecture
nzOpenMode_ReadWrite = 0x08, // Ouvre en lecture/écriture OpenMode_Text = 0x10, // Ouvre en mode texte
nzOpenMode_Text = 0x10, // Ouvre en mode texte OpenMode_Truncate = 0x20, // Créé le fichier s'il n'existe pas et le vide s'il existe
nzOpenMode_Truncate = 0x20, // Créé le fichier s'il n'existe pas et le vide s'il existe OpenMode_WriteOnly = 0x40, // Ouvre uniquement en écriture, créé le fichier s'il n'existe pas
nzOpenMode_WriteOnly = 0x40, // Ouvre uniquement en écriture, créé le fichier s'il n'existe pas
nzOpenMode_Max = nzOpenMode_WriteOnly OpenMode_ReadWrite = OpenMode_ReadOnly | OpenMode_WriteOnly, // Ouvre en lecture/écriture
};
enum nzParameterType OpenMode_Max = OpenMode_WriteOnly
{ };
nzParameterType_Boolean,
nzParameterType_Float,
nzParameterType_Integer,
nzParameterType_None,
nzParameterType_Pointer,
nzParameterType_String,
nzParameterType_Userdata,
nzParameterType_Max = nzParameterType_Userdata enum ParameterType
}; {
ParameterType_Boolean,
ParameterType_Float,
ParameterType_Integer,
ParameterType_None,
ParameterType_Pointer,
ParameterType_String,
ParameterType_Userdata,
enum nzPlugin ParameterType_Max = ParameterType_Userdata
{ };
nzPlugin_Assimp,
nzPlugin_FreeType
};
enum nzPrimitiveType enum Plugin
{ {
nzPrimitiveType_Box, Plugin_Assimp,
nzPrimitiveType_Cone, Plugin_FreeType
nzPrimitiveType_Plane, };
nzPrimitiveType_Sphere,
nzPrimitiveType_Max = nzPrimitiveType_Sphere enum PrimitiveType
}; {
PrimitiveType_Box,
PrimitiveType_Cone,
PrimitiveType_Plane,
PrimitiveType_Sphere,
enum nzProcessorCap PrimitiveType_Max = PrimitiveType_Sphere
{ };
nzProcessorCap_x64,
nzProcessorCap_AVX,
nzProcessorCap_FMA3,
nzProcessorCap_FMA4,
nzProcessorCap_MMX,
nzProcessorCap_XOP,
nzProcessorCap_SSE,
nzProcessorCap_SSE2,
nzProcessorCap_SSE3,
nzProcessorCap_SSSE3,
nzProcessorCap_SSE41,
nzProcessorCap_SSE42,
nzProcessorCap_SSE4a,
nzProcessorCap_Max = nzProcessorCap_SSE4a enum ProcessorCap
}; {
ProcessorCap_x64,
ProcessorCap_AVX,
ProcessorCap_FMA3,
ProcessorCap_FMA4,
ProcessorCap_MMX,
ProcessorCap_XOP,
ProcessorCap_SSE,
ProcessorCap_SSE2,
ProcessorCap_SSE3,
ProcessorCap_SSSE3,
ProcessorCap_SSE41,
ProcessorCap_SSE42,
ProcessorCap_SSE4a,
enum nzProcessorVendor ProcessorCap_Max = ProcessorCap_SSE4a
{ };
nzProcessorVendor_Unknown = -1,
nzProcessorVendor_AMD, enum ProcessorVendor
nzProcessorVendor_Centaur, {
nzProcessorVendor_Cyrix, ProcessorVendor_Unknown = -1,
nzProcessorVendor_Intel,
nzProcessorVendor_KVM,
nzProcessorVendor_HyperV,
nzProcessorVendor_NSC,
nzProcessorVendor_NexGen,
nzProcessorVendor_Rise,
nzProcessorVendor_SIS,
nzProcessorVendor_Transmeta,
nzProcessorVendor_UMC,
nzProcessorVendor_VIA,
nzProcessorVendor_VMware,
nzProcessorVendor_Vortex,
nzProcessorVendor_XenHVM,
nzProcessorVendor_Max = nzProcessorVendor_XenHVM ProcessorVendor_AMD,
}; ProcessorVendor_Centaur,
ProcessorVendor_Cyrix,
ProcessorVendor_Intel,
ProcessorVendor_KVM,
ProcessorVendor_HyperV,
ProcessorVendor_NSC,
ProcessorVendor_NexGen,
ProcessorVendor_Rise,
ProcessorVendor_SIS,
ProcessorVendor_Transmeta,
ProcessorVendor_UMC,
ProcessorVendor_VIA,
ProcessorVendor_VMware,
ProcessorVendor_Vortex,
ProcessorVendor_XenHVM,
enum nzSphereType ProcessorVendor_Max = ProcessorVendor_XenHVM
{ };
nzSphereType_Cubic,
nzSphereType_Ico,
nzSphereType_UV,
nzSphereType_Max = nzSphereType_UV enum SphereType
}; {
SphereType_Cubic,
SphereType_Ico,
SphereType_UV,
enum nzStreamOptionFlags SphereType_Max = SphereType_UV
{ };
nzStreamOption_None = 0,
nzStreamOption_Text = 0x1, enum StreamOptionFlags
{
StreamOption_None = 0,
nzStreamOption_Max = nzStreamOption_Text*2-1 StreamOption_Sequential = 0x1,
}; StreamOption_Text = 0x2,
enum nzTernary StreamOption_Max = StreamOption_Text*2-1
{ };
nzTernary_False,
nzTernary_True,
nzTernary_Unknown,
nzTernary_Max = nzTernary_Unknown enum Ternary
}; {
Ternary_False,
Ternary_True,
Ternary_Unknown,
Ternary_Max = Ternary_Unknown
};
}
#endif // NAZARA_ENUMS_CORE_HPP #endif // NAZARA_ENUMS_CORE_HPP

View File

@ -14,37 +14,40 @@
#include <Nazara/Core/String.hpp> #include <Nazara/Core/String.hpp>
#if NAZARA_CORE_ENABLE_ASSERTS || defined(NAZARA_DEBUG) #if NAZARA_CORE_ENABLE_ASSERTS || defined(NAZARA_DEBUG)
#define NazaraAssert(a, err) if (!(a)) NzError::Error(nzErrorType_AssertFailed, err, __LINE__, NzDirectory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION) #define NazaraAssert(a, err) if (!(a)) Nz::Error::Trigger(Nz::ErrorType_AssertFailed, err, __LINE__, Nz::Directory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
#else #else
#define NazaraAssert(a, err) #define NazaraAssert(a, err) for (;;) break
#endif #endif
#define NazaraError(err) NzError::Error(nzErrorType_Normal, err, __LINE__, NzDirectory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION) #define NazaraError(err) Nz::Error::Trigger(Nz::ErrorType_Normal, err, __LINE__, Nz::Directory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
#define NazaraInternalError(err) NzError::Error(nzErrorType_Internal, err, __LINE__, NzDirectory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION) #define NazaraInternalError(err) Nz::Error::Trigger(Nz::ErrorType_Internal, err, __LINE__, Nz::Directory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
#define NazaraWarning(err) NzError::Error(nzErrorType_Warning, err, __LINE__, NzDirectory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION) #define NazaraWarning(err) Nz::Error::Trigger(Nz::ErrorType_Warning, err, __LINE__, Nz::Directory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
class NAZARA_CORE_API NzError namespace Nz
{ {
public: class NAZARA_CORE_API Error
NzError() = delete; {
~NzError() = delete; public:
Error() = delete;
~Error() = delete;
static void Error(nzErrorType type, const NzString& error); static UInt32 GetFlags();
static void Error(nzErrorType type, const NzString& error, unsigned int line, const char* file, const char* function); static String GetLastError(const char** file = nullptr, unsigned int* line = nullptr, const char** function = nullptr);
static unsigned int GetLastSystemErrorCode();
static String GetLastSystemError(unsigned int code = GetLastSystemErrorCode());
static nzUInt32 GetFlags(); static void SetFlags(UInt32 flags);
static NzString GetLastError(const char** file = nullptr, unsigned int* line = nullptr, const char** function = nullptr);
static unsigned int GetLastSystemErrorCode();
static NzString GetLastSystemError(unsigned int code = GetLastSystemErrorCode());
static void SetFlags(nzUInt32 flags); static void Trigger(ErrorType type, const String& error);
static void Trigger(ErrorType type, const String& error, unsigned int line, const char* file, const char* function);
private: private:
static nzUInt32 s_flags; static UInt32 s_flags;
static NzString s_lastError; static String s_lastError;
static const char* s_lastErrorFunction; static const char* s_lastErrorFunction;
static const char* s_lastErrorFile; static const char* s_lastErrorFile;
static unsigned int s_lastErrorLine; static unsigned int s_lastErrorLine;
}; };
}
#endif // NAZARA_ERROR_HPP #endif // NAZARA_ERROR_HPP

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