Upgrade Utility

This commit is contained in:
Jérôme Leclercq 2021-05-24 19:10:53 +02:00
parent b936946154
commit cce32a64d4
120 changed files with 2328 additions and 2971 deletions

View File

@ -28,25 +28,38 @@ namespace Nz
friend Type; friend Type;
public: public:
using ExtensionGetter = bool (*)(const std::string& extension); struct Entry;
using FormatQuerier = bool (*)(const std::string& format); using FormatSupport = std::function<bool(const std::string_view& format)>;
using FileSaver = bool (*)(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters); using FileSaver = std::function<bool(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters)>;
using StreamSaver = bool (*)(const Type& resource, const std::string& format, Stream& stream, const Parameters& parameters); using StreamSaver = std::function<bool(const Type& resource, const std::string& format, Stream& stream, const Parameters& parameters)>;
ResourceSaver() = delete; ResourceSaver() = default;
~ResourceSaver() = delete; ResourceSaver(const ResourceSaver&) = delete;
ResourceSaver(ResourceSaver&&) noexcept = default;
~ResourceSaver() = default;
static bool IsFormatSupported(const std::string& extension); void Clear();
static bool SaveToFile(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters = Parameters()); bool IsExtensionSupported(const std::string_view& extension) const;
static bool SaveToStream(const Type& resource, Stream& stream, const std::string& format, const Parameters& parameters = Parameters());
static void RegisterSaver(FormatQuerier formatQuerier, StreamSaver streamSaver, FileSaver fileSaver = nullptr); bool SaveToFile(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters = Parameters()) const;
static void UnregisterSaver(FormatQuerier formatQuerier, StreamSaver streamSaver, FileSaver fileSaver = nullptr); bool SaveToStream(const Type& resource, Stream& stream, const std::string& format, const Parameters& parameters = Parameters()) const;
const Entry* RegisterSaver(Entry saver);
void UnregisterSaver(const Entry* saver);
ResourceSaver& operator=(const ResourceSaver&) = delete;
ResourceSaver& operator=(ResourceSaver&&) noexcept = default;
struct Entry
{
FormatSupport formatSupport;
FileSaver fileSaver;
StreamSaver streamSaver;
};
private: private:
using Saver = std::tuple<FormatQuerier, StreamSaver, FileSaver>; std::vector<std::unique_ptr<Entry>> m_savers;
using SaverList = std::list<Saver>;
}; };
} }

View File

@ -18,6 +18,15 @@ namespace Nz
* \brief Core class that represents a list of saver functions for a specific resource type * \brief Core class that represents a list of saver functions for a specific resource type
*/ */
/*!
* \brief Unregister every saver registered
*/
template<typename Type, typename Parameters>
void ResourceSaver<Type, Parameters>::Clear()
{
m_savers.clear();
}
/*! /*!
* \brief Checks whether the extension of the file is supported * \brief Checks whether the extension of the file is supported
* \return true if supported * \return true if supported
@ -25,13 +34,12 @@ namespace Nz
* \param extension Extension of the file * \param extension Extension of the file
*/ */
template<typename Type, typename Parameters> template<typename Type, typename Parameters>
bool ResourceSaver<Type, Parameters>::IsFormatSupported(const std::string& extension) bool ResourceSaver<Type, Parameters>::IsExtensionSupported(const std::string_view& extension) const
{ {
for (Saver& saver : Type::s_savers) for (const auto& saverPtr : m_savers)
{ {
ExtensionGetter isExtensionSupported = std::get<0>(saver); const Entry& saver = *saverPtr;
if (saver.formatSupport(extension))
if (isExtensionSupported && isExtensionSupported(extension))
return true; return true;
} }
@ -52,45 +60,42 @@ namespace Nz
* \see SaveToStream * \see SaveToStream
*/ */
template<typename Type, typename Parameters> template<typename Type, typename Parameters>
bool ResourceSaver<Type, Parameters>::SaveToFile(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters) bool ResourceSaver<Type, Parameters>::SaveToFile(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters) const
{ {
NazaraAssert(parameters.IsValid(), "Invalid parameters"); NazaraAssert(parameters.IsValid(), "Invalid parameters");
std::string ext = ToLower(filePath.extension().generic_u8string()); std::string extension = ToLower(filePath.extension().generic_u8string());
if (ext.empty()) if (extension.empty())
{ {
NazaraError("Failed to get file extension from \"" + filePath.generic_u8string() + '"'); NazaraError("Failed to get file extension from \"" + filePath.generic_u8string() + '"');
return false; return false;
} }
File file(filePath.generic_u8string()); // Opened only is required
bool found = false; bool found = false;
for (Saver& saver : Type::s_savers) for (const auto& saverPtr : m_savers)
{ {
FormatQuerier formatQuerier = std::get<0>(saver); const Entry& saver = *saverPtr;
if (!formatQuerier || !formatQuerier(ext)) if (!saver.formatSupport(extension))
continue; continue;
found = true; found = true;
StreamSaver streamSeaver = std::get<1>(saver); if (saver.fileSaver)
FileSaver fileSaver = std::get<2>(saver);
if (fileSaver)
{ {
if (fileSaver(resource, filePath, parameters)) if (saver.fileSaver(resource, filePath, parameters))
return true; return true;
} }
else else
{ {
File file(filePath.generic_u8string());
if (!file.Open(OpenMode_WriteOnly | OpenMode_Truncate)) if (!file.Open(OpenMode_WriteOnly | OpenMode_Truncate))
{ {
NazaraError("Failed to save to file: unable to open \"" + filePath.generic_u8string() + "\" in write mode"); NazaraError("Failed to save to file: unable to open \"" + filePath.generic_u8string() + "\" in write mode");
return false; return false;
} }
if (streamSeaver(resource, ext, file, parameters)) if (saver.streamSaver(resource, extension, file, parameters))
return true; return true;
} }
@ -100,7 +105,7 @@ namespace Nz
if (found) if (found)
NazaraError("Failed to save resource: all savers failed"); NazaraError("Failed to save resource: all savers failed");
else else
NazaraError("Failed to save resource: no saver found for extension \"" + ext + '"'); NazaraError("Failed to save resource: no saver found for extension \"" + extension + '"');
return false; return false;
} }
@ -117,28 +122,26 @@ namespace Nz
* \see SaveToFile * \see SaveToFile
*/ */
template<typename Type, typename Parameters> template<typename Type, typename Parameters>
bool ResourceSaver<Type, Parameters>::SaveToStream(const Type& resource, Stream& stream, const std::string& format, const Parameters& parameters) bool ResourceSaver<Type, Parameters>::SaveToStream(const Type& resource, Stream& stream, const std::string& format, const Parameters& parameters) const
{ {
NazaraAssert(stream.IsWritable(), "Stream is not writable"); NazaraAssert(stream.IsWritable(), "Stream is not writable");
NazaraAssert(parameters.IsValid(), "Invalid parameters"); NazaraAssert(parameters.IsValid(), "Invalid parameters");
UInt64 streamPos = stream.GetCursorPos(); UInt64 streamPos = stream.GetCursorPos();
bool found = false; bool found = false;
for (Saver& saver : Type::s_savers) for (const auto& saverPtr : m_savers)
{ {
FormatQuerier formatQuerier = std::get<0>(saver); const Entry& saver = *saverPtr;
if (!formatQuerier || !formatQuerier(format)) if (!saver.formatSupport(format))
continue; continue;
found = true; found = true;
StreamSaver streamSeaver = std::get<1>(saver);
// We move the stream to its old position // We move the stream to its old position
stream.SetCursorPos(streamPos); stream.SetCursorPos(streamPos);
// Load of the resource // Load of the resource
if (streamSeaver(resource, format, stream, parameters)) if (saver.streamSaver(resource, format, stream, parameters))
return true; return true;
NazaraWarning("Saver failed"); NazaraWarning("Saver failed");
@ -154,36 +157,35 @@ namespace Nz
/*! /*!
* \brief Registers a saver * \brief Registers a saver
* \return A pointer to the registered Entry which can be unsed to unregister it later
* *
* \param formatQuerier A function to test whether the format (as a string) is supported by this saver * \param loader A collection of saver callbacks that will be registered
* \param streamSaver A function which saves the resource to a stream
* \param fileSaver Optional function which saves the resource directly to a file given a file path
* *
* \remark The fileSaver argument is only present for compatibility with external savers which cannot be interfaced with streams * \see UnregisterLoader
* \remark At least one saver is required
*/ */
template<typename Type, typename Parameters> template<typename Type, typename Parameters>
void ResourceSaver<Type, Parameters>::RegisterSaver(FormatQuerier formatQuerier, StreamSaver streamSaver, FileSaver fileSaver) auto ResourceSaver<Type, Parameters>::RegisterSaver(Entry saver) -> const Entry*
{ {
NazaraAssert(formatQuerier, "A format querier is mandaroty"); NazaraAssert(saver.formatSupport, "A format support callback is mandatory");
NazaraAssert(streamSaver || fileSaver, "A saver function is mandaroty"); NazaraAssert(saver.streamSaver || saver.fileSaver, "A saver function is mandatory");
Type::s_savers.push_front(std::make_tuple(formatQuerier, streamSaver, fileSaver)); auto it = m_savers.emplace(m_savers.begin(), std::make_unique<Entry>(std::move(saver)));
return it->get();
} }
/*! /*!
* \brief Unregisters a saver * \brief Unregisters a saver
* *
* \param formatQuerier A function to test whether the format (as a string) is supported by this saver * \param saver A pointer to a loader returned by RegisterSaver
* \param streamSaver A function which saves the resource to a stream
* \param fileSaver A function function which saves the resource directly to a file given a file path
* *
* \remark The saver will only be unregistered if the function pointers are exactly the same * \see RegisterSaver
*/ */
template<typename Type, typename Parameters> template<typename Type, typename Parameters>
void ResourceSaver<Type, Parameters>::UnregisterSaver(FormatQuerier formatQuerier, StreamSaver streamSaver, FileSaver fileSaver) void ResourceSaver<Type, Parameters>::UnregisterSaver(const Entry* saver)
{ {
Type::s_savers.remove(std::make_tuple(formatQuerier, streamSaver, fileSaver)); auto it = std::find_if(m_savers.begin(), m_savers.end(), [&](const std::unique_ptr<Entry>& saverPtr) { return saverPtr.get() == saver; });
if (it != m_savers.end())
m_savers.erase(it);
} }
} }

View File

@ -18,7 +18,7 @@ namespace Nz
class NAZARA_GRAPHICS_API GraphicalMesh class NAZARA_GRAPHICS_API GraphicalMesh
{ {
public: public:
GraphicalMesh(const Mesh* mesh); GraphicalMesh(const Mesh& mesh);
GraphicalMesh(const GraphicalMesh&) = delete; GraphicalMesh(const GraphicalMesh&) = delete;
GraphicalMesh(GraphicalMesh&&) noexcept = default; GraphicalMesh(GraphicalMesh&&) noexcept = default;
~GraphicalMesh() = default; ~GraphicalMesh() = default;
@ -26,7 +26,7 @@ namespace Nz
inline const std::shared_ptr<AbstractBuffer>& GetIndexBuffer(std::size_t subMesh) const; inline const std::shared_ptr<AbstractBuffer>& GetIndexBuffer(std::size_t subMesh) const;
inline std::size_t GetIndexCount(std::size_t subMesh) const; inline std::size_t GetIndexCount(std::size_t subMesh) const;
inline const std::shared_ptr<AbstractBuffer>& GetVertexBuffer(std::size_t subMesh) const; inline const std::shared_ptr<AbstractBuffer>& GetVertexBuffer(std::size_t subMesh) const;
inline const VertexDeclarationConstRef& GetVertexDeclaration(std::size_t subMesh) const; inline const std::shared_ptr<const VertexDeclaration>& GetVertexDeclaration(std::size_t subMesh) const;
inline std::size_t GetSubMeshCount() const; inline std::size_t GetSubMeshCount() const;
GraphicalMesh& operator=(const GraphicalMesh&) = delete; GraphicalMesh& operator=(const GraphicalMesh&) = delete;
@ -38,7 +38,7 @@ namespace Nz
std::shared_ptr<AbstractBuffer> indexBuffer; std::shared_ptr<AbstractBuffer> indexBuffer;
std::shared_ptr<AbstractBuffer> vertexBuffer; std::shared_ptr<AbstractBuffer> vertexBuffer;
std::size_t indexCount; std::size_t indexCount;
VertexDeclarationConstRef vertexDeclaration; std::shared_ptr<const VertexDeclaration> vertexDeclaration;
}; };
std::vector<GraphicalSubMesh> m_subMeshes; std::vector<GraphicalSubMesh> m_subMeshes;

View File

@ -26,7 +26,7 @@ namespace Nz
return m_subMeshes[subMesh].vertexBuffer; return m_subMeshes[subMesh].vertexBuffer;
} }
inline const VertexDeclarationConstRef& GraphicalMesh::GetVertexDeclaration(std::size_t subMesh) const inline const std::shared_ptr<const VertexDeclaration>& GraphicalMesh::GetVertexDeclaration(std::size_t subMesh) const
{ {
assert(subMesh < m_subMeshes.size()); assert(subMesh < m_subMeshes.size());
return m_subMeshes[subMesh].vertexDeclaration; return m_subMeshes[subMesh].vertexDeclaration;

View File

@ -10,8 +10,6 @@
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Color.hpp> #include <Nazara/Core/Color.hpp>
#include <Nazara/Core/ObjectLibrary.hpp> #include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Core/Resource.hpp> #include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceLoader.hpp> #include <Nazara/Core/ResourceLoader.hpp>
#include <Nazara/Core/ResourceManager.hpp> #include <Nazara/Core/ResourceManager.hpp>
@ -32,7 +30,7 @@ namespace Nz
class CommandBufferBuilder; class CommandBufferBuilder;
class UploadPool; class UploadPool;
class NAZARA_GRAPHICS_API Material : public RefCounted, public Resource class NAZARA_GRAPHICS_API Material : public Resource
{ {
public: public:
Material(std::shared_ptr<const MaterialSettings> settings); Material(std::shared_ptr<const MaterialSettings> settings);

View File

@ -107,7 +107,7 @@ namespace Nz
* *
* This parameter is required for depth writing. * This parameter is required for depth writing.
* *
* In order to enable depth writing without enabling depth test, set the depth comparison function to RendererComparison_Never * In order to enable depth writing without enabling depth test, set the depth comparison function to RendererComparison::Never
* *
* \param depthBuffer Defines if this material will use depth buffer * \param depthBuffer Defines if this material will use depth buffer
* *

View File

@ -17,13 +17,13 @@ namespace Nz
{ {
switch (imageType) switch (imageType)
{ {
case ImageType_2D: return GL::TextureTarget::Target2D; case ImageType::E2D: return GL::TextureTarget::Target2D;
case ImageType_2D_Array: return GL::TextureTarget::Target2D_Array; case ImageType::E2D_Array: return GL::TextureTarget::Target2D_Array;
case ImageType_3D: return GL::TextureTarget::Target3D; case ImageType::E3D: return GL::TextureTarget::Target3D;
case ImageType_Cubemap: return GL::TextureTarget::Cubemap; case ImageType::Cubemap: return GL::TextureTarget::Cubemap;
case ImageType_1D: case ImageType::E1D:
case ImageType_1D_Array: case ImageType::E1D_Array:
default: default:
throw std::runtime_error("unsupported texture type"); throw std::runtime_error("unsupported texture type");
} }

View File

@ -15,17 +15,17 @@ namespace Nz
// TODO: Fill this switch // TODO: Fill this switch
switch (pixelFormat) switch (pixelFormat)
{ {
case PixelFormat_A8: return GLTextureFormat{ GL_R8, GL_RED, GL_UNSIGNED_BYTE, GL_ZERO, GL_ZERO, GL_ZERO, GL_RED }; case PixelFormat::A8: return GLTextureFormat{ GL_R8, GL_RED, GL_UNSIGNED_BYTE, GL_ZERO, GL_ZERO, GL_ZERO, GL_RED };
case PixelFormat_BGR8: return GLTextureFormat{ GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, GL_BLUE, GL_GREEN, GL_RED, GL_ONE }; case PixelFormat::BGR8: return GLTextureFormat{ GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, GL_BLUE, GL_GREEN, GL_RED, GL_ONE };
case PixelFormat_BGR8_SRGB: return GLTextureFormat{ GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE, GL_BLUE, GL_GREEN, GL_RED, GL_ONE }; case PixelFormat::BGR8_SRGB: return GLTextureFormat{ GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE, GL_BLUE, GL_GREEN, GL_RED, GL_ONE };
case PixelFormat_BGRA8: return GLTextureFormat{ GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA }; case PixelFormat::BGRA8: return GLTextureFormat{ GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
case PixelFormat_BGRA8_SRGB: return GLTextureFormat{ GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA }; case PixelFormat::BGRA8_SRGB: return GLTextureFormat{ GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
case PixelFormat_Depth24Stencil8: return GLTextureFormat{ GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, GL_RED, GL_GREEN, GL_ZERO, GL_ZERO }; case PixelFormat::Depth24Stencil8: return GLTextureFormat{ GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, GL_RED, GL_GREEN, GL_ZERO, GL_ZERO };
case PixelFormat_RGB8: return GLTextureFormat{ GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, GL_RED, GL_GREEN, GL_BLUE, GL_ONE }; case PixelFormat::RGB8: return GLTextureFormat{ GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, GL_RED, GL_GREEN, GL_BLUE, GL_ONE };
case PixelFormat_RGB8_SRGB: return GLTextureFormat{ GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE, GL_RED, GL_GREEN, GL_BLUE, GL_ONE }; case PixelFormat::RGB8_SRGB: return GLTextureFormat{ GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE, GL_RED, GL_GREEN, GL_BLUE, GL_ONE };
case PixelFormat_RGBA8: return GLTextureFormat{ GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA }; case PixelFormat::RGBA8: return GLTextureFormat{ GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA };
case PixelFormat_RGBA8_SRGB: return GLTextureFormat{ GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA }; case PixelFormat::RGBA8_SRGB: return GLTextureFormat{ GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA };
case PixelFormat_RGBA32F: return GLTextureFormat{ GL_RGBA32F, GL_RGBA, GL_FLOAT, GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA }; case PixelFormat::RGBA32F: return GLTextureFormat{ GL_RGBA32F, GL_RGBA, GL_FLOAT, GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA };
default: break; default: break;
} }
@ -76,12 +76,12 @@ namespace Nz
{ {
switch (filter) switch (filter)
{ {
case FaceSide_None: case FaceSide::None:
break; break;
case FaceSide_Back: return GL_BACK; case FaceSide::Back: return GL_BACK;
case FaceSide_Front: return GL_FRONT; case FaceSide::Front: return GL_FRONT;
case FaceSide_FrontAndBack: return GL_FRONT_AND_BACK; case FaceSide::FrontAndBack: return GL_FRONT_AND_BACK;
} }
NazaraError("Unhandled FaceSide 0x" + NumberToString(UnderlyingCast(filter), 16)); NazaraError("Unhandled FaceSide 0x" + NumberToString(UnderlyingCast(filter), 16));
@ -92,12 +92,12 @@ namespace Nz
{ {
switch (primitiveMode) switch (primitiveMode)
{ {
case PrimitiveMode_LineList: return GL_LINES; case PrimitiveMode::LineList: return GL_LINES;
case PrimitiveMode_LineStrip: return GL_LINE_STRIP; case PrimitiveMode::LineStrip: return GL_LINE_STRIP;
case PrimitiveMode_PointList: return GL_POINTS; case PrimitiveMode::PointList: return GL_POINTS;
case PrimitiveMode_TriangleList: return GL_TRIANGLES; case PrimitiveMode::TriangleList: return GL_TRIANGLES;
case PrimitiveMode_TriangleStrip: return GL_TRIANGLE_STRIP; case PrimitiveMode::TriangleStrip: return GL_TRIANGLE_STRIP;
case PrimitiveMode_TriangleFan: return GL_TRIANGLE_FAN; case PrimitiveMode::TriangleFan: return GL_TRIANGLE_FAN;
} }
NazaraError("Unhandled PrimitiveMode 0x" + NumberToString(UnderlyingCast(primitiveMode), 16)); NazaraError("Unhandled PrimitiveMode 0x" + NumberToString(UnderlyingCast(primitiveMode), 16));
@ -108,14 +108,14 @@ namespace Nz
{ {
switch (comparison) switch (comparison)
{ {
case RendererComparison_Always: return GL_ALWAYS; case RendererComparison::Always: return GL_ALWAYS;
case RendererComparison_Equal: return GL_EQUAL; case RendererComparison::Equal: return GL_EQUAL;
case RendererComparison_Greater: return GL_GREATER; case RendererComparison::Greater: return GL_GREATER;
case RendererComparison_GreaterOrEqual: return GL_GEQUAL; case RendererComparison::GreaterOrEqual: return GL_GEQUAL;
case RendererComparison_Less: return GL_LESS; case RendererComparison::Less: return GL_LESS;
case RendererComparison_LessOrEqual: return GL_LEQUAL; case RendererComparison::LessOrEqual: return GL_LEQUAL;
case RendererComparison_Never: return GL_NEVER; case RendererComparison::Never: return GL_NEVER;
case RendererComparison_NotEqual: return GL_NOTEQUAL; case RendererComparison::NotEqual: return GL_NOTEQUAL;
} }
NazaraError("Unhandled RendererComparison 0x" + NumberToString(UnderlyingCast(comparison), 16)); NazaraError("Unhandled RendererComparison 0x" + NumberToString(UnderlyingCast(comparison), 16));
@ -126,8 +126,8 @@ namespace Nz
{ {
switch (filter) switch (filter)
{ {
case SamplerFilter::SamplerFilter_Linear: return GL_LINEAR; case SamplerFilter::Linear: return GL_LINEAR;
case SamplerFilter::SamplerFilter_Nearest: return GL_NEAREST; case SamplerFilter::Nearest: return GL_NEAREST;
} }
NazaraError("Unhandled SamplerFilter 0x" + NumberToString(UnderlyingCast(filter), 16)); NazaraError("Unhandled SamplerFilter 0x" + NumberToString(UnderlyingCast(filter), 16));
@ -138,24 +138,24 @@ namespace Nz
{ {
switch (minFilter) switch (minFilter)
{ {
case SamplerFilter::SamplerFilter_Linear: case SamplerFilter::Linear:
{ {
switch (mipmapFilter) switch (mipmapFilter)
{ {
case SamplerMipmapMode_Linear: return GL_LINEAR_MIPMAP_LINEAR; case SamplerMipmapMode::Linear: return GL_LINEAR_MIPMAP_LINEAR;
case SamplerMipmapMode_Nearest: return GL_LINEAR_MIPMAP_NEAREST; case SamplerMipmapMode::Nearest: return GL_LINEAR_MIPMAP_NEAREST;
} }
NazaraError("Unhandled SamplerFilter 0x" + NumberToString(UnderlyingCast(mipmapFilter), 16)); NazaraError("Unhandled SamplerFilter 0x" + NumberToString(UnderlyingCast(mipmapFilter), 16));
return {}; return {};
} }
case SamplerFilter::SamplerFilter_Nearest: case SamplerFilter::Nearest:
{ {
switch (mipmapFilter) switch (mipmapFilter)
{ {
case SamplerMipmapMode_Linear: return GL_NEAREST_MIPMAP_LINEAR; case SamplerMipmapMode::Linear: return GL_NEAREST_MIPMAP_LINEAR;
case SamplerMipmapMode_Nearest: return GL_NEAREST_MIPMAP_NEAREST; case SamplerMipmapMode::Nearest: return GL_NEAREST_MIPMAP_NEAREST;
} }
NazaraError("Unhandled SamplerFilter 0x" + NumberToString(UnderlyingCast(mipmapFilter), 16)); NazaraError("Unhandled SamplerFilter 0x" + NumberToString(UnderlyingCast(mipmapFilter), 16));
@ -171,9 +171,9 @@ namespace Nz
{ {
switch (wrapMode) switch (wrapMode)
{ {
case SamplerWrap::SamplerWrap_Clamp: return GL_CLAMP_TO_EDGE; case SamplerWrap::Clamp: return GL_CLAMP_TO_EDGE;
case SamplerWrap::SamplerWrap_MirroredRepeat: return GL_MIRRORED_REPEAT; case SamplerWrap::MirroredRepeat: return GL_MIRRORED_REPEAT;
case SamplerWrap::SamplerWrap_Repeat: return GL_REPEAT; case SamplerWrap::Repeat: return GL_REPEAT;
} }
NazaraError("Unhandled SamplerWrap 0x" + NumberToString(UnderlyingCast(wrapMode), 16)); NazaraError("Unhandled SamplerWrap 0x" + NumberToString(UnderlyingCast(wrapMode), 16));
@ -196,14 +196,14 @@ namespace Nz
{ {
switch (stencilOp) switch (stencilOp)
{ {
case StencilOperation_Decrement: return GL_DECR; case StencilOperation::Decrement: return GL_DECR;
case StencilOperation_DecrementNoClamp: return GL_DECR_WRAP; case StencilOperation::DecrementNoClamp: return GL_DECR_WRAP;
case StencilOperation_Increment: return GL_INCR; case StencilOperation::Increment: return GL_INCR;
case StencilOperation_IncrementNoClamp: return GL_INCR_WRAP; case StencilOperation::IncrementNoClamp: return GL_INCR_WRAP;
case StencilOperation_Invert: return GL_INVERT; case StencilOperation::Invert: return GL_INVERT;
case StencilOperation_Keep: return GL_KEEP; case StencilOperation::Keep: return GL_KEEP;
case StencilOperation_Replace: return GL_REPLACE; case StencilOperation::Replace: return GL_REPLACE;
case StencilOperation_Zero: return GL_ZERO; case StencilOperation::Zero: return GL_ZERO;
} }
NazaraError("Unhandled StencilOperation 0x" + NumberToString(UnderlyingCast(stencilOp), 16)); NazaraError("Unhandled StencilOperation 0x" + NumberToString(UnderlyingCast(stencilOp), 16));

View File

@ -8,7 +8,6 @@
#define NAZARA_ABSTRACTIMAGE_HPP #define NAZARA_ABSTRACTIMAGE_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Math/Box.hpp> #include <Nazara/Math/Box.hpp>
#include <Nazara/Math/Rect.hpp> #include <Nazara/Math/Rect.hpp>
#include <Nazara/Math/Vector3.hpp> #include <Nazara/Math/Vector3.hpp>
@ -19,14 +18,12 @@ namespace Nz
{ {
class AbstractImage; class AbstractImage;
using AbstractImageConstRef = ObjectRef<const AbstractImage>; class NAZARA_UTILITY_API AbstractImage
using AbstractImageRef = ObjectRef<AbstractImage>;
class NAZARA_UTILITY_API AbstractImage : public RefCounted
{ {
public: public:
AbstractImage() = default; AbstractImage() = default;
inline AbstractImage(const AbstractImage& image); AbstractImage(const AbstractImage&) = default;
AbstractImage(AbstractImage&&) noexcept = default;
virtual ~AbstractImage(); virtual ~AbstractImage();
UInt8 GetBytesPerPixel() const; UInt8 GetBytesPerPixel() const;
@ -47,6 +44,9 @@ namespace Nz
virtual bool Update(const UInt8* pixels, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) = 0; virtual bool Update(const UInt8* pixels, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) = 0;
virtual bool Update(const UInt8* pixels, const Boxui& box, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) = 0; virtual bool Update(const UInt8* pixels, const Boxui& box, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) = 0;
virtual bool Update(const UInt8* pixels, const Rectui& rect, unsigned int z = 0, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) = 0; virtual bool Update(const UInt8* pixels, const Rectui& rect, unsigned int z = 0, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) = 0;
AbstractImage& operator=(const AbstractImage&) = default;
AbstractImage& operator=(AbstractImage&&) noexcept = default;
}; };
} }

View File

@ -6,10 +6,6 @@
namespace Nz namespace Nz
{ {
inline AbstractImage::AbstractImage(const AbstractImage&) :
RefCounted()
{
}
} }
#include <Nazara/Utility/DebugOff.hpp> #include <Nazara/Utility/DebugOff.hpp>

View File

@ -12,6 +12,7 @@
#include <Nazara/Math/Rect.hpp> #include <Nazara/Math/Rect.hpp>
#include <Nazara/Math/Vector2.hpp> #include <Nazara/Math/Vector2.hpp>
#include <Nazara/Utility/Config.hpp> #include <Nazara/Utility/Config.hpp>
#include <memory>
namespace Nz namespace Nz
{ {
@ -30,7 +31,7 @@ namespace Nz
virtual void Clear() = 0; virtual void Clear() = 0;
virtual const Rectf& GetBounds() const = 0; virtual const Rectf& GetBounds() const = 0;
virtual Font* GetFont(std::size_t index) const = 0; virtual const std::shared_ptr<Font>& GetFont(std::size_t index) const = 0;
virtual std::size_t GetFontCount() const = 0; virtual std::size_t GetFontCount() const = 0;
virtual const Glyph& GetGlyph(std::size_t index) const = 0; virtual const Glyph& GetGlyph(std::size_t index) const = 0;
virtual std::size_t GetGlyphCount() const = 0; virtual std::size_t GetGlyphCount() const = 0;

View File

@ -14,20 +14,20 @@ namespace Nz
return ComponentType{}; return ComponentType{};
} }
template<> constexpr ComponentType ComponentTypeId<Color>() { return ComponentType_Color; } template<> constexpr ComponentType ComponentTypeId<Color>() { return ComponentType::Color; }
template<> constexpr ComponentType ComponentTypeId<double>() { return ComponentType_Double1; } template<> constexpr ComponentType ComponentTypeId<double>() { return ComponentType::Double1; }
template<> constexpr ComponentType ComponentTypeId<Vector2d>() { return ComponentType_Double2; } template<> constexpr ComponentType ComponentTypeId<Vector2d>() { return ComponentType::Double2; }
template<> constexpr ComponentType ComponentTypeId<Vector3d>() { return ComponentType_Double3; } template<> constexpr ComponentType ComponentTypeId<Vector3d>() { return ComponentType::Double3; }
template<> constexpr ComponentType ComponentTypeId<Vector4d>() { return ComponentType_Double4; } template<> constexpr ComponentType ComponentTypeId<Vector4d>() { return ComponentType::Double4; }
template<> constexpr ComponentType ComponentTypeId<float>() { return ComponentType_Float1; } template<> constexpr ComponentType ComponentTypeId<float>() { return ComponentType::Float1; }
template<> constexpr ComponentType ComponentTypeId<Vector2f>() { return ComponentType_Float2; } template<> constexpr ComponentType ComponentTypeId<Vector2f>() { return ComponentType::Float2; }
template<> constexpr ComponentType ComponentTypeId<Vector3f>() { return ComponentType_Float3; } template<> constexpr ComponentType ComponentTypeId<Vector3f>() { return ComponentType::Float3; }
template<> constexpr ComponentType ComponentTypeId<Vector4f>() { return ComponentType_Float4; } template<> constexpr ComponentType ComponentTypeId<Vector4f>() { return ComponentType::Float4; }
template<> constexpr ComponentType ComponentTypeId<int>() { return ComponentType_Int1; } template<> constexpr ComponentType ComponentTypeId<int>() { return ComponentType::Int1; }
template<> constexpr ComponentType ComponentTypeId<Vector2i>() { return ComponentType_Int2; } template<> constexpr ComponentType ComponentTypeId<Vector2i>() { return ComponentType::Int2; }
template<> constexpr ComponentType ComponentTypeId<Vector3i>() { return ComponentType_Int3; } template<> constexpr ComponentType ComponentTypeId<Vector3i>() { return ComponentType::Int3; }
template<> constexpr ComponentType ComponentTypeId<Vector4i>() { return ComponentType_Int4; } template<> constexpr ComponentType ComponentTypeId<Vector4i>() { return ComponentType::Int4; }
template<> constexpr ComponentType ComponentTypeId<Quaternionf>() { return ComponentType_Quaternion; } template<> constexpr ComponentType ComponentTypeId<Quaternionf>() { return ComponentType::Quaternion; }
template<typename T> template<typename T>
constexpr ComponentType GetComponentTypeOf() constexpr ComponentType GetComponentTypeOf()

View File

@ -10,8 +10,6 @@
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/MovablePtr.hpp> #include <Nazara/Core/MovablePtr.hpp>
#include <Nazara/Core/ObjectLibrary.hpp> #include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Core/Resource.hpp> #include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceLoader.hpp> #include <Nazara/Core/ResourceLoader.hpp>
#include <Nazara/Core/ResourceManager.hpp> #include <Nazara/Core/ResourceManager.hpp>
@ -38,23 +36,18 @@ namespace Nz
struct SequenceJoint; struct SequenceJoint;
class Skeleton; class Skeleton;
using AnimationConstRef = ObjectRef<const Animation>;
using AnimationLibrary = ObjectLibrary<Animation>; using AnimationLibrary = ObjectLibrary<Animation>;
using AnimationLoader = ResourceLoader<Animation, AnimationParams>; using AnimationLoader = ResourceLoader<Animation, AnimationParams>;
using AnimationManager = ResourceManager<Animation, AnimationParams>; using AnimationManager = ResourceManager<Animation, AnimationParams>;
using AnimationRef = ObjectRef<Animation>;
struct AnimationImpl; struct AnimationImpl;
class NAZARA_UTILITY_API Animation : public RefCounted, public Resource class NAZARA_UTILITY_API Animation : public Resource
{ {
friend AnimationLibrary;
friend AnimationLoader;
friend AnimationManager;
friend class Utility;
public: public:
Animation() = default; Animation();
Animation(const Animation&) = delete;
Animation(Animation&&) noexcept;
~Animation(); ~Animation();
bool AddSequence(const Sequence& sequence); bool AddSequence(const Sequence& sequence);
@ -86,26 +79,15 @@ namespace Nz
void RemoveSequence(const std::string& sequenceName); void RemoveSequence(const std::string& sequenceName);
void RemoveSequence(std::size_t index); void RemoveSequence(std::size_t index);
template<typename... Args> static AnimationRef New(Args&&... args); Animation& operator=(const Animation&) = delete;
Animation& operator=(Animation&&) noexcept;
static AnimationRef LoadFromFile(const std::filesystem::path& filePath, const AnimationParams& params = AnimationParams()); static std::shared_ptr<Animation> LoadFromFile(const std::filesystem::path& filePath, const AnimationParams& params = AnimationParams());
static AnimationRef LoadFromMemory(const void* data, std::size_t size, const AnimationParams& params = AnimationParams()); static std::shared_ptr<Animation> LoadFromMemory(const void* data, std::size_t size, const AnimationParams& params = AnimationParams());
static AnimationRef LoadFromStream(Stream& stream, const AnimationParams& params = AnimationParams()); static std::shared_ptr<Animation> LoadFromStream(Stream& stream, const AnimationParams& params = AnimationParams());
// Signals:
NazaraSignal(OnAnimationDestroy, const Animation* /*animation*/);
NazaraSignal(OnAnimationRelease, const Animation* /*animation*/);
private: private:
static bool Initialize(); std::unique_ptr<AnimationImpl> m_impl;
static void Uninitialize();
MovablePtr<AnimationImpl> m_impl = nullptr;
static AnimationLibrary::LibraryMap s_library;
static AnimationLoader::LoaderList s_loaders;
static AnimationManager::ManagerMap s_managerMap;
static AnimationManager::ManagerParams s_managerParameters;
}; };
} }

View File

@ -2,19 +2,12 @@
// This file is part of the "Nazara Engine - Utility module" // This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Animation.hpp>
#include <memory> #include <memory>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
namespace Nz namespace Nz
{ {
template<typename... Args>
AnimationRef Animation::New(Args&&... args)
{
std::unique_ptr<Animation> object(new Animation(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
}
} }
#include <Nazara/Utility/DebugOff.hpp> #include <Nazara/Utility/DebugOff.hpp>

View File

@ -8,37 +8,30 @@
#define NAZARA_BUFFER_HPP #define NAZARA_BUFFER_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Utility/AbstractBuffer.hpp> #include <Nazara/Utility/AbstractBuffer.hpp>
#include <Nazara/Utility/Config.hpp> #include <Nazara/Utility/Config.hpp>
#include <Nazara/Utility/Enums.hpp> #include <Nazara/Utility/Enums.hpp>
#include <array> #include <array>
#include <functional>
namespace Nz namespace Nz
{ {
class Buffer; class NAZARA_UTILITY_API Buffer
using BufferConstRef = ObjectRef<const Buffer>;
using BufferRef = ObjectRef<Buffer>;
class NAZARA_UTILITY_API Buffer : public RefCounted
{ {
friend class Utility; friend class Utility;
public: public:
using BufferFactory = AbstractBuffer* (*)(Buffer* parent, BufferType type); using BufferFactory = std::function<std::unique_ptr<AbstractBuffer>(Buffer* parent, BufferType type)>;
Buffer(BufferType type); Buffer(BufferType type);
Buffer(BufferType type, UInt32 size, DataStorage storage = DataStorage_Software, BufferUsageFlags usage = 0); Buffer(BufferType type, UInt32 size, DataStorage storage = DataStorage::Software, BufferUsageFlags usage = 0);
Buffer(const Buffer&) = delete; Buffer(const Buffer&) = delete;
Buffer(Buffer&&) = delete; Buffer(Buffer&&) = delete;
~Buffer(); ~Buffer() = default;
bool CopyContent(const BufferRef& buffer); bool CopyContent(const Buffer& buffer);
bool Create(UInt32 size, DataStorage storage = DataStorage_Software, BufferUsageFlags usage = 0); bool Create(UInt32 size, DataStorage storage = DataStorage::Software, BufferUsageFlags usage = 0);
void Destroy(); void Destroy();
bool Fill(const void* data, UInt32 offset, UInt32 size); bool Fill(const void* data, UInt32 offset, UInt32 size);
@ -64,13 +57,8 @@ namespace Nz
Buffer& operator=(Buffer&&) = delete; Buffer& operator=(Buffer&&) = delete;
static bool IsStorageSupported(DataStorage storage); static bool IsStorageSupported(DataStorage storage);
template<typename... Args> static BufferRef New(Args&&... args);
static void SetBufferFactory(DataStorage storage, BufferFactory func); static void SetBufferFactory(DataStorage storage, BufferFactory func);
// Signals:
NazaraSignal(OnBufferDestroy, const Buffer* /*buffer*/);
NazaraSignal(OnBufferRelease, const Buffer* /*buffer*/);
private: private:
static bool Initialize(); static bool Initialize();
static void Uninitialize(); static void Uninitialize();
@ -80,7 +68,7 @@ namespace Nz
BufferUsageFlags m_usage; BufferUsageFlags m_usage;
UInt32 m_size; UInt32 m_size;
static std::array<BufferFactory, DataStorage_Max + 1> s_bufferFactories; static std::array<BufferFactory, DataStorageCount> s_bufferFactories;
}; };
} }

View File

@ -41,15 +41,6 @@ namespace Nz
{ {
return m_impl != nullptr; return m_impl != nullptr;
} }
template<typename... Args>
BufferRef Buffer::New(Args&&... args)
{
std::unique_ptr<Buffer> object(new Buffer(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
}
} }
#include <Nazara/Utility/DebugOff.hpp> #include <Nazara/Utility/DebugOff.hpp>

View File

@ -11,12 +11,12 @@
namespace Nz namespace Nz
{ {
enum AnimationType enum class AnimationType
{ {
AnimationType_Skeletal, Skeletal,
AnimationType_Static, Static,
AnimationType_Max = AnimationType_Static Max = Static
}; };
enum class BlendEquation enum class BlendEquation
@ -46,286 +46,281 @@ namespace Nz
Zero Zero
}; };
enum BufferAccess enum class BufferAccess
{ {
BufferAccess_DiscardAndWrite, DiscardAndWrite,
BufferAccess_ReadOnly, ReadOnly,
BufferAccess_ReadWrite, ReadWrite,
BufferAccess_WriteOnly, WriteOnly,
BufferAccess_Max = BufferAccess_WriteOnly Max = WriteOnly
}; };
enum BufferType enum class BufferType
{ {
BufferType_Index, Index,
BufferType_Vertex, Vertex,
BufferType_Uniform, Uniform,
BufferType_Max = BufferType_Uniform Max = Uniform
}; };
enum BufferUsage enum class BufferUsage
{ {
BufferUsage_DeviceLocal, DeviceLocal,
BufferUsage_DirectMapping, DirectMapping,
BufferUsage_Dynamic, Dynamic,
BufferUsage_PersistentMapping, PersistentMapping,
BufferUsage_Max = BufferUsage_DirectMapping Max = DirectMapping
}; };
template<> template<>
struct EnumAsFlags<BufferUsage> struct EnumAsFlags<BufferUsage>
{ {
static constexpr BufferUsage max = BufferUsage_Max; static constexpr BufferUsage max = BufferUsage::Max;
}; };
using BufferUsageFlags = Flags<BufferUsage>; using BufferUsageFlags = Flags<BufferUsage>;
enum ComponentType enum class ComponentType
{ {
ComponentType_Color, Color,
ComponentType_Double1, Double1,
ComponentType_Double2, Double2,
ComponentType_Double3, Double3,
ComponentType_Double4, Double4,
ComponentType_Float1, Float1,
ComponentType_Float2, Float2,
ComponentType_Float3, Float3,
ComponentType_Float4, Float4,
ComponentType_Int1, Int1,
ComponentType_Int2, Int2,
ComponentType_Int3, Int3,
ComponentType_Int4, Int4,
ComponentType_Quaternion, Quaternion,
ComponentType_Max = ComponentType_Quaternion Max = Quaternion
}; };
enum CubemapFace constexpr std::size_t ComponentTypeCount = static_cast<std::size_t>(ComponentType::Max) + 1;
enum class CubemapFace
{ {
// This enumeration is intended to replace the "z" argument of Image's methods containing cubemap // This enumeration is intended to replace the "z" argument of Image's methods containing cubemap
// The order is X, -X, Y, -Y, Z, -Z // The order is X, -X, Y, -Y, Z, -Z
CubemapFace_PositiveX = 0, PositiveX = 0,
CubemapFace_PositiveY = 2, PositiveY = 2,
CubemapFace_PositiveZ = 4, PositiveZ = 4,
CubemapFace_NegativeX = 1, NegativeX = 1,
CubemapFace_NegativeY = 3, NegativeY = 3,
CubemapFace_NegativeZ = 5, NegativeZ = 5,
CubemapFace_Max = CubemapFace_NegativeZ Max = NegativeZ
}; };
enum DataStorage enum class DataStorage
{ {
DataStorage_Hardware, Hardware,
DataStorage_Software, Software,
DataStorage_Max = DataStorage_Software Max = Software
}; };
enum FaceFilling constexpr std::size_t DataStorageCount = static_cast<std::size_t>(DataStorage::Max) + 1;
{
FaceFilling_Fill,
FaceFilling_Line,
FaceFilling_Point,
FaceFilling_Max = FaceFilling_Point enum class FaceFilling
{
Fill,
Line,
Point,
Max = Point
}; };
enum FaceSide enum class FaceSide
{ {
FaceSide_None, None,
FaceSide_Back, Back,
FaceSide_Front, Front,
FaceSide_FrontAndBack, FrontAndBack,
FaceSide_Max = FaceSide_FrontAndBack Max = FrontAndBack
}; };
enum ImageType enum class ImageType
{ {
ImageType_1D, E1D,
ImageType_1D_Array, E1D_Array,
ImageType_2D, E2D,
ImageType_2D_Array, E2D_Array,
ImageType_3D, E3D,
ImageType_Cubemap, Cubemap,
ImageType_Max = ImageType_Cubemap Max = Cubemap
}; };
constexpr std::size_t ImageTypeCount = static_cast<std::size_t>(ImageType_Max) + 1; constexpr std::size_t ImageTypeCount = static_cast<std::size_t>(ImageType::Max) + 1;
enum NodeType enum class NodeType
{ {
NodeType_Default, // Node Default, // Node
NodeType_Scene, // SceneNode (Graphics) Scene, // SceneNode (Graphics)
NodeType_Skeletal, ///TODO Skeletal, ///TODO
NodeType_Max = NodeType_Skeletal Max = Skeletal
}; };
enum PixelFormatContent enum class PixelFormatContent
{ {
PixelFormatContent_Undefined = -1, Undefined = -1,
PixelFormatContent_ColorRGBA, ColorRGBA,
PixelFormatContent_Depth, Depth,
PixelFormatContent_DepthStencil, DepthStencil,
PixelFormatContent_Stencil, Stencil,
PixelFormatContent_Max = PixelFormatContent_Stencil Max = Stencil
}; };
enum PixelFormat enum class PixelFormat
{ {
PixelFormat_Undefined = -1, Undefined = -1,
PixelFormat_A8, // 1*uint8 A8, // 1*uint8
PixelFormat_BGR8, // 3*uint8 BGR8, // 3*uint8
PixelFormat_BGR8_SRGB, // 3*uint8 BGR8_SRGB, // 3*uint8
PixelFormat_BGRA8, // 4*uint8 BGRA8, // 4*uint8
PixelFormat_BGRA8_SRGB, // 4*uint8 BGRA8_SRGB, // 4*uint8
PixelFormat_DXT1, DXT1,
PixelFormat_DXT3, DXT3,
PixelFormat_DXT5, DXT5,
PixelFormat_L8, // 1*uint8 L8, // 1*uint8
PixelFormat_LA8, // 2*uint8 LA8, // 2*uint8
PixelFormat_R8, // 1*uint8 R8, // 1*uint8
PixelFormat_R8I, // 1*int8 R8I, // 1*int8
PixelFormat_R8UI, // 1*uint8 R8UI, // 1*uint8
PixelFormat_R16, // 1*uint16 R16, // 1*uint16
PixelFormat_R16F, // 1*half R16F, // 1*half
PixelFormat_R16I, // 1*int16 R16I, // 1*int16
PixelFormat_R16UI, // 1*uint16 R16UI, // 1*uint16
PixelFormat_R32F, // 1*float R32F, // 1*float
PixelFormat_R32I, // 1*uint16 R32I, // 1*uint16
PixelFormat_R32UI, // 1*uint32 R32UI, // 1*uint32
PixelFormat_RG8, // 2*int8 RG8, // 2*int8
PixelFormat_RG8I, // 2*int8 RG8I, // 2*int8
PixelFormat_RG8UI, // 2*uint8 RG8UI, // 2*uint8
PixelFormat_RG16, // 2*uint16 RG16, // 2*uint16
PixelFormat_RG16F, // 2*half RG16F, // 2*half
PixelFormat_RG16I, // 2*int16 RG16I, // 2*int16
PixelFormat_RG16UI, // 2*uint16 RG16UI, // 2*uint16
PixelFormat_RG32F, // 2*float RG32F, // 2*float
PixelFormat_RG32I, // 2*uint16 RG32I, // 2*uint16
PixelFormat_RG32UI, // 2*uint32 RG32UI, // 2*uint32
PixelFormat_RGB5A1, // 3*uint5 + alpha bit RGB5A1, // 3*uint5 + alpha bit
PixelFormat_RGB8, // 3*uint8 RGB8, // 3*uint8
PixelFormat_RGB8_SRGB, // 3*uint8 RGB8_SRGB, // 3*uint8
PixelFormat_RGB16F, // 3*half RGB16F, // 3*half
PixelFormat_RGB16I, // 4*int16 RGB16I, // 4*int16
PixelFormat_RGB16UI, // 4*uint16 RGB16UI, // 4*uint16
PixelFormat_RGB32F, // 3*float RGB32F, // 3*float
PixelFormat_RGB32I, // 4*int32 RGB32I, // 4*int32
PixelFormat_RGB32UI, // 4*uint32 RGB32UI, // 4*uint32
PixelFormat_RGBA4, // 4*uint4 RGBA4, // 4*uint4
PixelFormat_RGBA8, // 4*uint8 RGBA8, // 4*uint8
PixelFormat_RGBA8_SRGB, // 4*uint8 RGBA8_SRGB, // 4*uint8
PixelFormat_RGBA16F, // 4*half RGBA16F, // 4*half
PixelFormat_RGBA16I, // 4*int16 RGBA16I, // 4*int16
PixelFormat_RGBA16UI, // 4*uint16 RGBA16UI, // 4*uint16
PixelFormat_RGBA32F, // 4*float RGBA32F, // 4*float
PixelFormat_RGBA32I, // 4*int32 RGBA32I, // 4*int32
PixelFormat_RGBA32UI, // 4*uint32 RGBA32UI, // 4*uint32
PixelFormat_Depth16, Depth16,
PixelFormat_Depth24, Depth24,
PixelFormat_Depth24Stencil8, Depth24Stencil8,
PixelFormat_Depth32, Depth32,
PixelFormat_Stencil1, Stencil1,
PixelFormat_Stencil4, Stencil4,
PixelFormat_Stencil8, Stencil8,
PixelFormat_Stencil16, Stencil16,
PixelFormat_Max = PixelFormat_Stencil16 Max = Stencil16
}; };
enum PixelFormatSubType constexpr std::size_t PixelFormatCount = static_cast<std::size_t>(PixelFormat::Max) + 1;
{
PixelFormatSubType_Compressed, // Opaque
PixelFormatSubType_Double, // F64
PixelFormatSubType_Float, // F32
PixelFormatSubType_Half, // F16
PixelFormatSubType_Int, // Signed integer
PixelFormatSubType_Unsigned, // Unsigned integer
PixelFormatSubType_Max = PixelFormatSubType_Unsigned enum class PixelFormatSubType
{
Compressed, // Opaque
Double, // F64
Float, // F32
Half, // F16
Int, // Signed integer
Unsigned, // Unsigned integer
Max = Unsigned
}; };
enum PixelFlipping enum class PixelFlipping
{ {
PixelFlipping_Horizontally, Horizontally,
PixelFlipping_Vertically, Vertically,
PixelFlipping_Max = PixelFlipping_Vertically Max = Vertically
}; };
enum PrimitiveMode constexpr std::size_t PixelFlippingCount = static_cast<std::size_t>(PixelFlipping::Max) + 1;
{
PrimitiveMode_LineList,
PrimitiveMode_LineStrip,
PrimitiveMode_PointList,
PrimitiveMode_TriangleList,
PrimitiveMode_TriangleStrip,
PrimitiveMode_TriangleFan,
PrimitiveMode_Max = PrimitiveMode_TriangleFan enum class PrimitiveMode
{
LineList,
LineStrip,
PointList,
TriangleList,
TriangleStrip,
TriangleFan,
Max = TriangleFan
}; };
enum RendererComparison enum class RendererComparison
{ {
RendererComparison_Always, Always,
RendererComparison_Equal, Equal,
RendererComparison_Greater, Greater,
RendererComparison_GreaterOrEqual, GreaterOrEqual,
RendererComparison_Less, Less,
RendererComparison_LessOrEqual, LessOrEqual,
RendererComparison_Never, Never,
RendererComparison_NotEqual, NotEqual,
RendererComparison_Max = RendererComparison_NotEqual Max = NotEqual
}; };
enum RendererParameter enum class SamplerFilter
{ {
RendererParameter_Blend, Linear,
RendererParameter_ColorWrite, Nearest,
RendererParameter_DepthBuffer,
RendererParameter_DepthWrite,
RendererParameter_FaceCulling,
RendererParameter_ScissorTest,
RendererParameter_StencilTest,
RendererParameter_Max = RendererParameter_StencilTest Max = Nearest
}; };
enum SamplerFilter enum class SamplerMipmapMode
{ {
SamplerFilter_Linear, Linear,
SamplerFilter_Nearest, Nearest,
SamplerFilter_Max = SamplerFilter_Nearest Max = Nearest
}; };
enum SamplerMipmapMode enum class SamplerWrap
{ {
SamplerMipmapMode_Linear, Clamp,
SamplerMipmapMode_Nearest, MirroredRepeat,
Repeat,
SamplerMipmapMode_Max = SamplerMipmapMode_Nearest Max = Repeat
};
enum SamplerWrap
{
SamplerWrap_Clamp,
SamplerWrap_MirroredRepeat,
SamplerWrap_Repeat,
SamplerWrap_Max = SamplerWrap_Repeat
}; };
enum class ShaderStageType enum class ShaderStageType
@ -348,95 +343,95 @@ namespace Nz
constexpr ShaderStageTypeFlags ShaderStageType_All = ShaderStageType::Fragment | ShaderStageType::Vertex; constexpr ShaderStageTypeFlags ShaderStageType_All = ShaderStageType::Fragment | ShaderStageType::Vertex;
enum StructFieldType enum class StructFieldType
{ {
StructFieldType_Bool1, Bool1,
StructFieldType_Bool2, Bool2,
StructFieldType_Bool3, Bool3,
StructFieldType_Bool4, Bool4,
StructFieldType_Float1, Float1,
StructFieldType_Float2, Float2,
StructFieldType_Float3, Float3,
StructFieldType_Float4, Float4,
StructFieldType_Double1, Double1,
StructFieldType_Double2, Double2,
StructFieldType_Double3, Double3,
StructFieldType_Double4, Double4,
StructFieldType_Int1, Int1,
StructFieldType_Int2, Int2,
StructFieldType_Int3, Int3,
StructFieldType_Int4, Int4,
StructFieldType_UInt1, UInt1,
StructFieldType_UInt2, UInt2,
StructFieldType_UInt3, UInt3,
StructFieldType_UInt4, UInt4,
StructFieldType_Max = StructFieldType_UInt4 Max = UInt4
}; };
enum StructLayout enum class StructLayout
{ {
StructLayout_Packed, Packed,
StructLayout_Std140, Std140,
StructLayout_Max = StructLayout_Std140 Max = Std140
}; };
enum StencilOperation enum class StencilOperation
{ {
StencilOperation_Decrement, Decrement,
StencilOperation_DecrementNoClamp, DecrementNoClamp,
StencilOperation_Increment, Increment,
StencilOperation_IncrementNoClamp, IncrementNoClamp,
StencilOperation_Invert, Invert,
StencilOperation_Keep, Keep,
StencilOperation_Replace, Replace,
StencilOperation_Zero, Zero,
StencilOperation_Max = StencilOperation_Zero Max = Zero
}; };
enum TextAlign enum class TextAlign
{ {
TextAlign_Left, Left,
TextAlign_Middle, Middle,
TextAlign_Right, Right,
TextAlign_Max = TextAlign_Right Max = Right
}; };
enum TextStyle enum class TextStyle
{ {
TextStyle_Bold, Bold,
TextStyle_Italic, Italic,
TextStyle_StrikeThrough, StrikeThrough,
TextStyle_Underlined, Underlined,
TextStyle_Max = TextStyle_Underlined Max = Underlined
}; };
template<> template<>
struct EnumAsFlags<TextStyle> struct EnumAsFlags<TextStyle>
{ {
static constexpr TextStyle max = TextStyle_Max; static constexpr TextStyle max = TextStyle::Max;
}; };
using TextStyleFlags = Flags<TextStyle>; using TextStyleFlags = Flags<TextStyle>;
constexpr TextStyleFlags TextStyle_Regular = 0; constexpr TextStyleFlags TextStyle_Regular = 0;
enum VertexComponent enum class VertexComponent
{ {
VertexComponent_Unused = -1, Unused = -1,
VertexComponent_Color, Color,
VertexComponent_Normal, Normal,
VertexComponent_Position, Position,
VertexComponent_Tangent, Tangent,
VertexComponent_TexCoord, TexCoord,
VertexComponent_Userdata, Userdata,
VertexComponent_Max = VertexComponent_Userdata Max = Userdata
}; };
enum class VertexInputRate enum class VertexInputRate
@ -445,26 +440,28 @@ namespace Nz
Vertex Vertex
}; };
enum VertexLayout enum class VertexLayout
{ {
// Predefined declarations for rendering // Predefined declarations for rendering
VertexLayout_XY, XY,
VertexLayout_XY_Color, XY_Color,
VertexLayout_XY_UV, XY_UV,
VertexLayout_XYZ, XYZ,
VertexLayout_XYZ_Color, XYZ_Color,
VertexLayout_XYZ_Color_UV, XYZ_Color_UV,
VertexLayout_XYZ_Normal, XYZ_Normal,
VertexLayout_XYZ_Normal_UV, XYZ_Normal_UV,
VertexLayout_XYZ_Normal_UV_Tangent, XYZ_Normal_UV_Tangent,
VertexLayout_XYZ_Normal_UV_Tangent_Skinning, XYZ_Normal_UV_Tangent_Skinning,
VertexLayout_XYZ_UV, XYZ_UV,
// Predefined declarations for instancing // Predefined declarations for instancing
VertexLayout_Matrix4, Matrix4,
VertexLayout_Max = VertexLayout_Matrix4 Max = Matrix4
}; };
constexpr std::size_t VertexLayoutCount = static_cast<std::size_t>(VertexLayout::Max) + 1;
} }
#endif // NAZARA_ENUMS_UTILITY_HPP #endif // NAZARA_ENUMS_UTILITY_HPP

View File

@ -25,7 +25,7 @@ namespace Nz
inline std::size_t FieldOffsets::GetAlignedSize() const inline std::size_t FieldOffsets::GetAlignedSize() const
{ {
if (m_layout == StructLayout_Std140) if (m_layout == StructLayout::Std140)
return Align(m_size, m_largestFieldAlignment); return Align(m_size, m_largestFieldAlignment);
else else
return m_size; return m_size;
@ -40,43 +40,43 @@ namespace Nz
{ {
switch (layout) switch (layout)
{ {
case StructLayout_Packed: case StructLayout::Packed:
return 1; return 1;
case StructLayout_Std140: case StructLayout::Std140:
{ {
switch (fieldType) switch (fieldType)
{ {
case StructFieldType_Bool1: case StructFieldType::Bool1:
case StructFieldType_Float1: case StructFieldType::Float1:
case StructFieldType_Int1: case StructFieldType::Int1:
case StructFieldType_UInt1: case StructFieldType::UInt1:
return 4; return 4;
case StructFieldType_Bool2: case StructFieldType::Bool2:
case StructFieldType_Float2: case StructFieldType::Float2:
case StructFieldType_Int2: case StructFieldType::Int2:
case StructFieldType_UInt2: case StructFieldType::UInt2:
return 2 * 4; return 2 * 4;
case StructFieldType_Bool3: case StructFieldType::Bool3:
case StructFieldType_Float3: case StructFieldType::Float3:
case StructFieldType_Int3: case StructFieldType::Int3:
case StructFieldType_UInt3: case StructFieldType::UInt3:
case StructFieldType_Bool4: case StructFieldType::Bool4:
case StructFieldType_Float4: case StructFieldType::Float4:
case StructFieldType_Int4: case StructFieldType::Int4:
case StructFieldType_UInt4: case StructFieldType::UInt4:
return 4 * 4; return 4 * 4;
case StructFieldType_Double1: case StructFieldType::Double1:
return 8; return 8;
case StructFieldType_Double2: case StructFieldType::Double2:
return 2 * 8; return 2 * 8;
case StructFieldType_Double3: case StructFieldType::Double3:
case StructFieldType_Double4: case StructFieldType::Double4:
return 4 * 8; return 4 * 8;
} }
} }
@ -89,32 +89,32 @@ namespace Nz
{ {
switch (fieldType) switch (fieldType)
{ {
case StructFieldType_Bool1: case StructFieldType::Bool1:
case StructFieldType_Double1: case StructFieldType::Double1:
case StructFieldType_Float1: case StructFieldType::Float1:
case StructFieldType_Int1: case StructFieldType::Int1:
case StructFieldType_UInt1: case StructFieldType::UInt1:
return 1; return 1;
case StructFieldType_Bool2: case StructFieldType::Bool2:
case StructFieldType_Double2: case StructFieldType::Double2:
case StructFieldType_Float2: case StructFieldType::Float2:
case StructFieldType_Int2: case StructFieldType::Int2:
case StructFieldType_UInt2: case StructFieldType::UInt2:
return 2; return 2;
case StructFieldType_Bool3: case StructFieldType::Bool3:
case StructFieldType_Double3: case StructFieldType::Double3:
case StructFieldType_Float3: case StructFieldType::Float3:
case StructFieldType_Int3: case StructFieldType::Int3:
case StructFieldType_UInt3: case StructFieldType::UInt3:
return 3; return 3;
case StructFieldType_Bool4: case StructFieldType::Bool4:
case StructFieldType_Double4: case StructFieldType::Double4:
case StructFieldType_Float4: case StructFieldType::Float4:
case StructFieldType_Int4: case StructFieldType::Int4:
case StructFieldType_UInt4: case StructFieldType::UInt4:
return 4; return 4;
} }
@ -125,40 +125,40 @@ namespace Nz
{ {
switch (fieldType) switch (fieldType)
{ {
case StructFieldType_Bool1: case StructFieldType::Bool1:
case StructFieldType_Float1: case StructFieldType::Float1:
case StructFieldType_Int1: case StructFieldType::Int1:
case StructFieldType_UInt1: case StructFieldType::UInt1:
return 4; return 4;
case StructFieldType_Bool2: case StructFieldType::Bool2:
case StructFieldType_Float2: case StructFieldType::Float2:
case StructFieldType_Int2: case StructFieldType::Int2:
case StructFieldType_UInt2: case StructFieldType::UInt2:
return 2 * 4; return 2 * 4;
case StructFieldType_Bool3: case StructFieldType::Bool3:
case StructFieldType_Float3: case StructFieldType::Float3:
case StructFieldType_Int3: case StructFieldType::Int3:
case StructFieldType_UInt3: case StructFieldType::UInt3:
return 3 * 4; return 3 * 4;
case StructFieldType_Bool4: case StructFieldType::Bool4:
case StructFieldType_Float4: case StructFieldType::Float4:
case StructFieldType_Int4: case StructFieldType::Int4:
case StructFieldType_UInt4: case StructFieldType::UInt4:
return 4 * 4; return 4 * 4;
case StructFieldType_Double1: case StructFieldType::Double1:
return 8; return 8;
case StructFieldType_Double2: case StructFieldType::Double2:
return 2 * 8; return 2 * 8;
case StructFieldType_Double3: case StructFieldType::Double3:
return 3 * 8; return 3 * 8;
case StructFieldType_Double4: case StructFieldType::Double4:
return 4 * 8; return 4 * 8;
} }

View File

@ -11,7 +11,6 @@
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectLibrary.hpp> #include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/Resource.hpp> #include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceLoader.hpp> #include <Nazara/Core/ResourceLoader.hpp>
#include <Nazara/Core/ResourceParameters.hpp> #include <Nazara/Core/ResourceParameters.hpp>
@ -32,12 +31,10 @@ namespace Nz
struct FontGlyph; struct FontGlyph;
using FontConstRef = ObjectRef<const Font>;
using FontLibrary = ObjectLibrary<Font>; using FontLibrary = ObjectLibrary<Font>;
using FontLoader = ResourceLoader<Font, FontParams>; using FontLoader = ResourceLoader<Font, FontParams>;
using FontRef = ObjectRef<Font>;
class NAZARA_UTILITY_API Font : public RefCounted, public Resource class NAZARA_UTILITY_API Font : public Resource
{ {
friend FontLibrary; friend FontLibrary;
friend FontLoader; friend FontLoader;
@ -85,15 +82,13 @@ namespace Nz
Font& operator=(Font&&) = delete; Font& operator=(Font&&) = delete;
static std::shared_ptr<AbstractAtlas> GetDefaultAtlas(); static std::shared_ptr<AbstractAtlas> GetDefaultAtlas();
static const FontRef& GetDefault(); static const std::shared_ptr<Font>& GetDefault();
static unsigned int GetDefaultGlyphBorder(); static unsigned int GetDefaultGlyphBorder();
static unsigned int GetDefaultMinimumStepSize(); static unsigned int GetDefaultMinimumStepSize();
static FontRef OpenFromFile(const std::filesystem::path& filePath, const FontParams& params = FontParams()); static std::shared_ptr<Font> OpenFromFile(const std::filesystem::path& filePath, const FontParams& params = FontParams());
static FontRef OpenFromMemory(const void* data, std::size_t size, const FontParams& params = FontParams()); static std::shared_ptr<Font> OpenFromMemory(const void* data, std::size_t size, const FontParams& params = FontParams());
static FontRef OpenFromStream(Stream& stream, const FontParams& params = FontParams()); static std::shared_ptr<Font> OpenFromStream(Stream& stream, const FontParams& params = FontParams());
template<typename... Args> static FontRef New(Args&&... args);
static void SetDefaultAtlas(const std::shared_ptr<AbstractAtlas>& atlas); static void SetDefaultAtlas(const std::shared_ptr<AbstractAtlas>& atlas);
static void SetDefaultGlyphBorder(unsigned int borderSize); static void SetDefaultGlyphBorder(unsigned int borderSize);
@ -154,9 +149,7 @@ namespace Nz
unsigned int m_minimumStepSize; unsigned int m_minimumStepSize;
static std::shared_ptr<AbstractAtlas> s_defaultAtlas; static std::shared_ptr<AbstractAtlas> s_defaultAtlas;
static FontRef s_defaultFont; static std::shared_ptr<Font> s_defaultFont;
static FontLibrary::LibraryMap s_library;
static FontLoader::LoaderList s_loaders;
static unsigned int s_defaultGlyphBorder; static unsigned int s_defaultGlyphBorder;
static unsigned int s_defaultMinimumStepSize; static unsigned int s_defaultMinimumStepSize;
}; };

View File

@ -2,19 +2,12 @@
// This file is part of the "Nazara Engine - Utility module" // This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Font.hpp>
#include <memory> #include <memory>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
namespace Nz namespace Nz
{ {
template<typename... Args>
FontRef Font::New(Args&&... args)
{
std::unique_ptr<Font> object(new Font(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
}
} }
#include <Nazara/Utility/DebugOff.hpp> #include <Nazara/Utility/DebugOff.hpp>

View File

@ -27,7 +27,7 @@ namespace Nz
struct NAZARA_UTILITY_API ImageParams : ResourceParameters struct NAZARA_UTILITY_API ImageParams : ResourceParameters
{ {
// Le format dans lequel l'image doit être chargée (Undefined pour le format le plus proche de l'original) // Le format dans lequel l'image doit être chargée (Undefined pour le format le plus proche de l'original)
PixelFormat loadFormat = PixelFormat_Undefined; PixelFormat loadFormat = PixelFormat::Undefined;
// Le nombre de niveaux de mipmaps maximum devant être créé // Le nombre de niveaux de mipmaps maximum devant être créé
UInt8 levelCount = 0; UInt8 levelCount = 0;
@ -37,21 +37,13 @@ namespace Nz
class Image; class Image;
using ImageConstRef = ObjectRef<const Image>;
using ImageLibrary = ObjectLibrary<Image>; using ImageLibrary = ObjectLibrary<Image>;
using ImageLoader = ResourceLoader<Image, ImageParams>; using ImageLoader = ResourceLoader<Image, ImageParams>;
using ImageManager = ResourceManager<Image, ImageParams>; using ImageManager = ResourceManager<Image, ImageParams>;
using ImageRef = ObjectRef<Image>;
using ImageSaver = ResourceSaver<Image, ImageParams>; using ImageSaver = ResourceSaver<Image, ImageParams>;
class NAZARA_UTILITY_API Image : public AbstractImage, public Resource class NAZARA_UTILITY_API Image : public AbstractImage, public Resource
{ {
friend ImageLibrary;
friend ImageLoader;
friend ImageManager;
friend ImageSaver;
friend class Utility;
public: public:
struct SharedImage; struct SharedImage;
@ -63,7 +55,7 @@ namespace Nz
bool Convert(PixelFormat format); bool Convert(PixelFormat format);
void Copy(const Image* source, const Boxui& srcBox, const Vector3ui& dstPos); void Copy(const Image& source, const Boxui& srcBox, const Vector3ui& dstPos);
bool Create(ImageType type, PixelFormat format, unsigned int width, unsigned int height, unsigned int depth = 1, UInt8 levelCount = 1); bool Create(ImageType type, PixelFormat format, unsigned int width, unsigned int height, unsigned int depth = 1, UInt8 levelCount = 1);
void Destroy(); void Destroy();
@ -118,23 +110,21 @@ namespace Nz
static UInt8 GetMaxLevel(ImageType type, unsigned int width, unsigned int height, unsigned int depth = 1); static UInt8 GetMaxLevel(ImageType type, unsigned int width, unsigned int height, unsigned int depth = 1);
// Load // Load
static ImageRef LoadFromFile(const std::filesystem::path& filePath, const ImageParams& params = ImageParams()); static std::shared_ptr<Image> LoadFromFile(const std::filesystem::path& filePath, const ImageParams& params = ImageParams());
static ImageRef LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams()); static std::shared_ptr<Image> LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams());
static ImageRef LoadFromStream(Stream& stream, const ImageParams& params = ImageParams()); static std::shared_ptr<Image> LoadFromStream(Stream& stream, const ImageParams& params = ImageParams());
// LoadArray // LoadArray
static ImageRef LoadArrayFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2)); static std::shared_ptr<Image> LoadArrayFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2));
static ImageRef LoadArrayFromImage(const Image* image, const Vector2ui& atlasSize = Vector2ui(2, 2)); static std::shared_ptr<Image> LoadArrayFromImage(const Image& image, const Vector2ui& atlasSize = Vector2ui(2, 2));
static ImageRef LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2)); static std::shared_ptr<Image> LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2));
static ImageRef LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2)); static std::shared_ptr<Image> LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2));
// LoadCubemap // LoadCubemap
static ImageRef LoadCubemapFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams()); static std::shared_ptr<Image> LoadCubemapFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams());
static ImageRef LoadCubemapFromImage(const Image* image, const CubemapParams& params = CubemapParams()); static std::shared_ptr<Image> LoadCubemapFromImage(const Image& image, const CubemapParams& params = CubemapParams());
static ImageRef LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams()); static std::shared_ptr<Image> LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams());
static ImageRef LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams()); static std::shared_ptr<Image> LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams());
template<typename... Args> static ImageRef New(Args&&... args);
struct SharedImage struct SharedImage
{ {
@ -163,24 +153,11 @@ namespace Nz
static SharedImage emptyImage; static SharedImage emptyImage;
// Signals:
NazaraSignal(OnImageDestroy, const Image* /*image*/);
NazaraSignal(OnImageRelease, const Image* /*image*/);
private: private:
void EnsureOwnership(); void EnsureOwnership();
void ReleaseImage(); void ReleaseImage();
static bool Initialize();
static void Uninitialize();
SharedImage* m_sharedImage; SharedImage* m_sharedImage;
static ImageLibrary::LibraryMap s_library;
static ImageLoader::LoaderList s_loaders;
static ImageManager::ManagerMap s_managerMap;
static ImageManager::ManagerParams s_managerParameters;
static ImageSaver::SaverList s_savers;
}; };
} }

View File

@ -2,19 +2,12 @@
// This file is part of the "Nazara Engine - Utility module" // This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Image.hpp>
#include <memory> #include <memory>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
namespace Nz namespace Nz
{ {
template<typename... Args>
ImageRef Image::New(Args&&... args)
{
std::unique_ptr<Image> object(new Image(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
}
} }
#include <Nazara/Utility/DebugOff.hpp> #include <Nazara/Utility/DebugOff.hpp>

View File

@ -8,34 +8,27 @@
#define NAZARA_INDEXBUFFER_HPP #define NAZARA_INDEXBUFFER_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Utility/Buffer.hpp> #include <Nazara/Utility/Buffer.hpp>
namespace Nz namespace Nz
{ {
class IndexBuffer; class NAZARA_UTILITY_API IndexBuffer
using IndexBufferConstRef = ObjectRef<const IndexBuffer>;
using IndexBufferRef = ObjectRef<IndexBuffer>;
class NAZARA_UTILITY_API IndexBuffer : public RefCounted
{ {
public: public:
IndexBuffer() = default; IndexBuffer() = default;
IndexBuffer(bool largeIndices, BufferRef buffer); IndexBuffer(bool largeIndices, std::shared_ptr<Buffer> buffer);
IndexBuffer(bool largeIndices, BufferRef buffer, std::size_t offset, std::size_t size); IndexBuffer(bool largeIndices, std::shared_ptr<Buffer> buffer, std::size_t offset, std::size_t size);
IndexBuffer(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage); IndexBuffer(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage);
IndexBuffer(const IndexBuffer& indexBuffer); IndexBuffer(const IndexBuffer&) = default;
IndexBuffer(IndexBuffer&&) = delete; IndexBuffer(IndexBuffer&&) noexcept = default;
~IndexBuffer(); ~IndexBuffer() = default;
unsigned int ComputeCacheMissCount() const; unsigned int ComputeCacheMissCount() const;
bool Fill(const void* data, std::size_t startIndex, std::size_t length); bool Fill(const void* data, std::size_t startIndex, std::size_t length);
bool FillRaw(const void* data, std::size_t offset, std::size_t size); bool FillRaw(const void* data, std::size_t offset, std::size_t size);
inline const BufferRef& GetBuffer() const; inline const std::shared_ptr<Buffer>& GetBuffer() const;
inline std::size_t GetEndOffset() const; inline std::size_t GetEndOffset() const;
inline std::size_t GetIndexCount() const; inline std::size_t GetIndexCount() const;
inline std::size_t GetStride() const; inline std::size_t GetStride() const;
@ -53,23 +46,18 @@ namespace Nz
void Optimize(); void Optimize();
void Reset(); void Reset();
void Reset(bool largeIndices, BufferRef buffer); void Reset(bool largeIndices, std::shared_ptr<Buffer> buffer);
void Reset(bool largeIndices, BufferRef buffer, std::size_t offset, std::size_t size); void Reset(bool largeIndices, std::shared_ptr<Buffer> buffer, std::size_t offset, std::size_t size);
void Reset(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage); void Reset(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage);
void Reset(const IndexBuffer& indexBuffer); void Reset(const IndexBuffer& indexBuffer);
void Unmap() const; void Unmap() const;
IndexBuffer& operator=(const IndexBuffer& indexBuffer); IndexBuffer& operator=(const IndexBuffer&) = default;
IndexBuffer& operator=(IndexBuffer&&) = delete; IndexBuffer& operator=(IndexBuffer&&) noexcept = default;
template<typename... Args> static IndexBufferRef New(Args&&... args);
// Signals:
NazaraSignal(OnIndexBufferRelease, const IndexBuffer* /*indexBuffer*/);
private: private:
BufferRef m_buffer; std::shared_ptr<Buffer> m_buffer;
std::size_t m_endOffset; std::size_t m_endOffset;
std::size_t m_indexCount; std::size_t m_indexCount;
std::size_t m_startOffset; std::size_t m_startOffset;

View File

@ -7,7 +7,7 @@
namespace Nz namespace Nz
{ {
inline const BufferRef& IndexBuffer::GetBuffer() const inline const std::shared_ptr<Buffer>& IndexBuffer::GetBuffer() const
{ {
return m_buffer; return m_buffer;
} }
@ -39,7 +39,7 @@ namespace Nz
inline bool IndexBuffer::IsValid() const inline bool IndexBuffer::IsValid() const
{ {
return m_buffer.IsValid(); return m_buffer != nullptr;
} }
inline void* IndexBuffer::Map(BufferAccess access, std::size_t startIndex, std::size_t length) inline void* IndexBuffer::Map(BufferAccess access, std::size_t startIndex, std::size_t length)
@ -53,15 +53,6 @@ namespace Nz
std::size_t stride = GetStride(); std::size_t stride = GetStride();
return MapRaw(access, startIndex*stride, length*stride); return MapRaw(access, startIndex*stride, length*stride);
} }
template<typename... Args>
IndexBufferRef IndexBuffer::New(Args&&... args)
{
std::unique_ptr<IndexBuffer> object(new IndexBuffer(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
}
} }
#include <Nazara/Utility/DebugOff.hpp> #include <Nazara/Utility/DebugOff.hpp>

View File

@ -19,10 +19,10 @@ namespace Nz
class NAZARA_UTILITY_API IndexMapper class NAZARA_UTILITY_API IndexMapper
{ {
public: public:
IndexMapper(IndexBuffer* indexBuffer, BufferAccess access = BufferAccess_ReadWrite, std::size_t indexCount = 0); IndexMapper(IndexBuffer& indexBuffer, BufferAccess access = BufferAccess::ReadWrite, std::size_t indexCount = 0);
IndexMapper(SubMesh* subMesh, BufferAccess access = BufferAccess_ReadWrite); IndexMapper(SubMesh& subMesh, BufferAccess access = BufferAccess::ReadWrite);
IndexMapper(const IndexBuffer* indexBuffer, BufferAccess access = BufferAccess_ReadOnly, std::size_t indexCount = 0); IndexMapper(const IndexBuffer& indexBuffer, BufferAccess access = BufferAccess::ReadOnly, std::size_t indexCount = 0);
IndexMapper(const SubMesh* subMesh, BufferAccess access = BufferAccess_ReadOnly); IndexMapper(const SubMesh& subMesh, BufferAccess access = BufferAccess::ReadOnly);
~IndexMapper() = default; ~IndexMapper() = default;
UInt32 Get(std::size_t i) const; UInt32 Get(std::size_t i) const;

View File

@ -9,8 +9,6 @@
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectLibrary.hpp> #include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Core/Resource.hpp> #include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceLoader.hpp> #include <Nazara/Core/ResourceLoader.hpp>
#include <Nazara/Core/ResourceManager.hpp> #include <Nazara/Core/ResourceManager.hpp>
@ -35,7 +33,7 @@ namespace Nz
BufferUsageFlags indexBufferFlags = 0; ///< Buffer usage flags used to build the index buffers BufferUsageFlags indexBufferFlags = 0; ///< Buffer usage flags used to build the index buffers
BufferUsageFlags vertexBufferFlags = 0; ///< Buffer usage flags used to build the vertex buffers BufferUsageFlags vertexBufferFlags = 0; ///< Buffer usage flags used to build the vertex buffers
Matrix4f matrix = Matrix4f::Identity(); ///< A matrix which will transform every vertex position Matrix4f matrix = Matrix4f::Identity(); ///< A matrix which will transform every vertex position
DataStorage storage = DataStorage_Hardware; ///< The place where the buffers will be allocated DataStorage storage = DataStorage::Hardware; ///< The place where the buffers will be allocated
Vector2f texCoordOffset = {0.f, 0.f}; ///< Offset to apply on the texture coordinates (not scaled) Vector2f texCoordOffset = {0.f, 0.f}; ///< Offset to apply on the texture coordinates (not scaled)
Vector2f texCoordScale = {1.f, 1.f}; ///< Scale to apply on the texture coordinates Vector2f texCoordScale = {1.f, 1.f}; ///< Scale to apply on the texture coordinates
bool animated = true; ///< If true, will load an animated version of the model if possible bool animated = true; ///< If true, will load an animated version of the model if possible
@ -51,7 +49,7 @@ namespace Nz
* If the declaration has a Vector3f Normals component enabled, Normals are generated. * If the declaration has a Vector3f Normals component enabled, Normals are generated.
* If the declaration has a Vector3f Tangents component enabled, Tangents are generated. * If the declaration has a Vector3f Tangents component enabled, Tangents are generated.
*/ */
VertexDeclaration* vertexDeclaration = VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent); std::shared_ptr<VertexDeclaration> vertexDeclaration = VertexDeclaration::Get(VertexLayout::XYZ_Normal_UV_Tangent);
bool IsValid() const; bool IsValid() const;
}; };
@ -64,33 +62,25 @@ namespace Nz
using MeshVertex = VertexStruct_XYZ_Normal_UV_Tangent; using MeshVertex = VertexStruct_XYZ_Normal_UV_Tangent;
using SkeletalMeshVertex = VertexStruct_XYZ_Normal_UV_Tangent_Skinning; using SkeletalMeshVertex = VertexStruct_XYZ_Normal_UV_Tangent_Skinning;
using MeshConstRef = ObjectRef<const Mesh>;
using MeshLibrary = ObjectLibrary<Mesh>; using MeshLibrary = ObjectLibrary<Mesh>;
using MeshLoader = ResourceLoader<Mesh, MeshParams>; using MeshLoader = ResourceLoader<Mesh, MeshParams>;
using MeshManager = ResourceManager<Mesh, MeshParams>; using MeshManager = ResourceManager<Mesh, MeshParams>;
using MeshRef = ObjectRef<Mesh>;
using MeshSaver = ResourceSaver<Mesh, MeshParams>; using MeshSaver = ResourceSaver<Mesh, MeshParams>;
struct MeshImpl; struct MeshImpl;
class NAZARA_UTILITY_API Mesh : public RefCounted, public Resource class NAZARA_UTILITY_API Mesh : public Resource
{ {
friend MeshLibrary;
friend MeshLoader;
friend MeshManager;
friend MeshSaver;
friend class Utility;
public: public:
inline Mesh(); inline Mesh();
Mesh(const Mesh&) = delete; Mesh(const Mesh&) = delete;
Mesh(Mesh&&) = delete; Mesh(Mesh&&) = delete;
inline ~Mesh(); ~Mesh() = default;
void AddSubMesh(SubMesh* subMesh); void AddSubMesh(std::shared_ptr<SubMesh> subMesh);
void AddSubMesh(const std::string& identifier, SubMesh* subMesh); void AddSubMesh(const std::string& identifier, std::shared_ptr<SubMesh> subMesh);
SubMesh* BuildSubMesh(const Primitive& primitive, const MeshParams& params = MeshParams()); std::shared_ptr<SubMesh> BuildSubMesh(const Primitive& primitive, const MeshParams& params = MeshParams());
void BuildSubMeshes(const PrimitiveList& list, const MeshParams& params = MeshParams()); void BuildSubMeshes(const PrimitiveList& list, const MeshParams& params = MeshParams());
bool CreateSkeletal(std::size_t jointCount); bool CreateSkeletal(std::size_t jointCount);
@ -110,10 +100,8 @@ namespace Nz
std::size_t GetMaterialCount() const; std::size_t GetMaterialCount() const;
Skeleton* GetSkeleton(); Skeleton* GetSkeleton();
const Skeleton* GetSkeleton() const; const Skeleton* GetSkeleton() const;
SubMesh* GetSubMesh(const std::string& identifier); const std::shared_ptr<SubMesh>& GetSubMesh(const std::string& identifier) const;
SubMesh* GetSubMesh(std::size_t index); const std::shared_ptr<SubMesh>& GetSubMesh(std::size_t index) const;
const SubMesh* GetSubMesh(const std::string& identifier) const;
const SubMesh* GetSubMesh(std::size_t index) const;
std::size_t GetSubMeshCount() const; std::size_t GetSubMeshCount() const;
std::size_t GetSubMeshIndex(const std::string& identifier) const; std::size_t GetSubMeshIndex(const std::string& identifier) const;
std::size_t GetTriangleCount() const; std::size_t GetTriangleCount() const;
@ -144,25 +132,22 @@ namespace Nz
Mesh& operator=(const Mesh&) = delete; Mesh& operator=(const Mesh&) = delete;
Mesh& operator=(Mesh&&) = delete; Mesh& operator=(Mesh&&) = delete;
static MeshRef LoadFromFile(const std::filesystem::path& filePath, const MeshParams& params = MeshParams()); static std::shared_ptr<Mesh> LoadFromFile(const std::filesystem::path& filePath, const MeshParams& params = MeshParams());
static MeshRef LoadFromMemory(const void* data, std::size_t size, const MeshParams& params = MeshParams()); static std::shared_ptr<Mesh> LoadFromMemory(const void* data, std::size_t size, const MeshParams& params = MeshParams());
static MeshRef LoadFromStream(Stream& stream, const MeshParams& params = MeshParams()); static std::shared_ptr<Mesh> LoadFromStream(Stream& stream, const MeshParams& params = MeshParams());
template<typename... Args> static MeshRef New(Args&&... args);
// Signals: // Signals:
NazaraSignal(OnMeshDestroy, const Mesh* /*mesh*/);
NazaraSignal(OnMeshInvalidateAABB, const Mesh* /*mesh*/); NazaraSignal(OnMeshInvalidateAABB, const Mesh* /*mesh*/);
NazaraSignal(OnMeshRelease, const Mesh* /*mesh*/);
private: private:
struct SubMeshData struct SubMeshData
{ {
SubMeshRef subMesh; std::shared_ptr<SubMesh> subMesh;
NazaraSlot(SubMesh, OnSubMeshInvalidateAABB, onSubMeshInvalidated); NazaraSlot(SubMesh, OnSubMeshInvalidateAABB, onSubMeshInvalidated);
}; };
std::size_t m_jointCount; // Only used by skeletal meshes
std::unordered_map<std::string, std::size_t> m_subMeshMap; std::unordered_map<std::string, std::size_t> m_subMeshMap;
std::vector<ParameterList> m_materialData; std::vector<ParameterList> m_materialData;
std::vector<SubMeshData> m_subMeshes; std::vector<SubMeshData> m_subMeshes;
@ -172,16 +157,6 @@ namespace Nz
std::filesystem::path m_animationPath; std::filesystem::path m_animationPath;
mutable bool m_aabbUpdated; mutable bool m_aabbUpdated;
bool m_isValid; bool m_isValid;
std::size_t m_jointCount; // Only used by skeletal meshes
static bool Initialize();
static void Uninitialize();
static MeshLibrary::LibraryMap s_library;
static MeshLoader::LoaderList s_loaders;
static MeshManager::ManagerMap s_managerMap;
static MeshManager::ManagerParams s_managerParameters;
static MeshSaver::SaverList s_savers;
}; };
} }

View File

@ -14,22 +14,6 @@ namespace Nz
m_isValid(false) m_isValid(false)
{ {
} }
Mesh::~Mesh()
{
OnMeshRelease(this);
Destroy();
}
template<typename... Args>
MeshRef Mesh::New(Args&&... args)
{
std::unique_ptr<Mesh> object(new Mesh(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
}
} }
#include <Nazara/Utility/DebugOff.hpp> #include <Nazara/Utility/DebugOff.hpp>

View File

@ -87,9 +87,9 @@ namespace Nz
static bool Initialize(); static bool Initialize();
static void Uninitialize(); static void Uninitialize();
static PixelFormatDescription s_pixelFormatInfos[PixelFormat_Max + 1]; static PixelFormatDescription s_pixelFormatInfos[PixelFormatCount];
static ConvertFunction s_convertFunctions[PixelFormat_Max+1][PixelFormat_Max+1]; static ConvertFunction s_convertFunctions[PixelFormatCount][PixelFormatCount];
static std::map<PixelFormat, FlipFunction> s_flipFunctions[PixelFlipping_Max+1]; static std::map<PixelFormat, FlipFunction> s_flipFunctions[PixelFlippingCount];
}; };
} }

View File

@ -2,7 +2,9 @@
// This file is part of the "Nazara Engine - Utility module" // This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/PixelFormat.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <array> #include <array>
#include <cstring> #include <cstring>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
@ -10,7 +12,7 @@
namespace Nz namespace Nz
{ {
inline PixelFormatDescription::PixelFormatDescription() : inline PixelFormatDescription::PixelFormatDescription() :
content(PixelFormatContent_Undefined), content(PixelFormatContent::Undefined),
bitsPerPixel(0) bitsPerPixel(0)
{ {
} }
@ -74,10 +76,10 @@ namespace Nz
inline bool PixelFormatDescription::IsCompressed() const inline bool PixelFormatDescription::IsCompressed() const
{ {
return redType == PixelFormatSubType_Compressed || return redType == PixelFormatSubType::Compressed ||
greenType == PixelFormatSubType_Compressed || greenType == PixelFormatSubType::Compressed ||
blueType == PixelFormatSubType_Compressed || blueType == PixelFormatSubType::Compressed ||
alphaType == PixelFormatSubType_Compressed; alphaType == PixelFormatSubType::Compressed;
} }
inline bool PixelFormatDescription::IsValid() const inline bool PixelFormatDescription::IsValid() const
@ -101,7 +103,7 @@ namespace Nz
if (!IsValid()) if (!IsValid())
return false; return false;
if (content <= PixelFormatContent_Undefined || content > PixelFormatContent_Max) if (content <= PixelFormatContent::Undefined || content > PixelFormatContent::Max)
return false; return false;
std::array<const Nz::Bitset<>*, 4> masks = { {&redMask, &greenMask, &blueMask, &alphaMask} }; std::array<const Nz::Bitset<>*, 4> masks = { {&redMask, &greenMask, &blueMask, &alphaMask} };
@ -121,13 +123,13 @@ namespace Nz
switch (types[i]) switch (types[i])
{ {
case PixelFormatSubType_Half: case PixelFormatSubType::Half:
if (usedBits != 16) if (usedBits != 16)
return false; return false;
break; break;
case PixelFormatSubType_Float: case PixelFormatSubType::Float:
if (usedBits != 32) if (usedBits != 32)
return false; return false;
@ -149,10 +151,10 @@ namespace Nz
{ {
switch (format) switch (format)
{ {
case PixelFormat_DXT1: case PixelFormat::DXT1:
case PixelFormat_DXT3: case PixelFormat::DXT3:
case PixelFormat_DXT5: case PixelFormat::DXT5:
return (((width + 3) / 4) * ((height + 3) / 4) * ((format == PixelFormat_DXT1) ? 8 : 16)) * depth; return (((width + 3) / 4) * ((height + 3) / 4) * ((format == PixelFormat::DXT1) ? 8 : 16)) * depth;
default: default:
NazaraError("Unsupported format"); NazaraError("Unsupported format");
@ -196,7 +198,7 @@ namespace Nz
return true; return true;
} }
ConvertFunction func = s_convertFunctions[srcFormat][dstFormat]; ConvertFunction func = s_convertFunctions[UnderlyingCast(srcFormat)][UnderlyingCast(dstFormat)];
if (!func) if (!func)
{ {
NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported"); NazaraError("Pixel format conversion from " + GetName(srcFormat) + " to " + GetName(dstFormat) + " is not supported");
@ -214,7 +216,7 @@ namespace Nz
inline UInt8 PixelFormatInfo::GetBitsPerPixel(PixelFormat format) inline UInt8 PixelFormatInfo::GetBitsPerPixel(PixelFormat format)
{ {
return s_pixelFormatInfos[format].bitsPerPixel; return s_pixelFormatInfos[UnderlyingCast(format)].bitsPerPixel;
} }
inline UInt8 PixelFormatInfo::GetBytesPerPixel(PixelFormat format) inline UInt8 PixelFormatInfo::GetBytesPerPixel(PixelFormat format)
@ -224,27 +226,27 @@ namespace Nz
inline PixelFormatContent PixelFormatInfo::GetContent(PixelFormat format) inline PixelFormatContent PixelFormatInfo::GetContent(PixelFormat format)
{ {
return s_pixelFormatInfos[format].content; return s_pixelFormatInfos[UnderlyingCast(format)].content;
} }
inline const PixelFormatDescription& PixelFormatInfo::GetInfo(PixelFormat format) inline const PixelFormatDescription& PixelFormatInfo::GetInfo(PixelFormat format)
{ {
return s_pixelFormatInfos[format]; return s_pixelFormatInfos[UnderlyingCast(format)];
} }
inline const std::string& PixelFormatInfo::GetName(PixelFormat format) inline const std::string& PixelFormatInfo::GetName(PixelFormat format)
{ {
return s_pixelFormatInfos[format].name; return s_pixelFormatInfos[UnderlyingCast(format)].name;
} }
inline bool PixelFormatInfo::HasAlpha(PixelFormat format) inline bool PixelFormatInfo::HasAlpha(PixelFormat format)
{ {
return s_pixelFormatInfos[format].alphaMask.TestAny(); return s_pixelFormatInfos[UnderlyingCast(format)].alphaMask.TestAny();
} }
inline bool PixelFormatInfo::IsCompressed(PixelFormat format) inline bool PixelFormatInfo::IsCompressed(PixelFormat format)
{ {
return s_pixelFormatInfos[format].IsCompressed(); return s_pixelFormatInfos[UnderlyingCast(format)].IsCompressed();
} }
inline bool PixelFormatInfo::IsConversionSupported(PixelFormat srcFormat, PixelFormat dstFormat) inline bool PixelFormatInfo::IsConversionSupported(PixelFormat srcFormat, PixelFormat dstFormat)
@ -252,22 +254,22 @@ namespace Nz
if (srcFormat == dstFormat) if (srcFormat == dstFormat)
return true; return true;
return s_convertFunctions[srcFormat][dstFormat] != nullptr; return s_convertFunctions[UnderlyingCast(srcFormat)][UnderlyingCast(dstFormat)] != nullptr;
} }
inline bool PixelFormatInfo::IsValid(PixelFormat format) inline bool PixelFormatInfo::IsValid(PixelFormat format)
{ {
return format != PixelFormat_Undefined; return format != PixelFormat::Undefined;
} }
inline void PixelFormatInfo::SetConvertFunction(PixelFormat srcFormat, PixelFormat dstFormat, ConvertFunction func) inline void PixelFormatInfo::SetConvertFunction(PixelFormat srcFormat, PixelFormat dstFormat, ConvertFunction func)
{ {
s_convertFunctions[srcFormat][dstFormat] = func; s_convertFunctions[UnderlyingCast(srcFormat)][UnderlyingCast(dstFormat)] = func;
} }
inline void PixelFormatInfo::SetFlipFunction(PixelFlipping flipping, PixelFormat format, FlipFunction func) inline void PixelFormatInfo::SetFlipFunction(PixelFlipping flipping, PixelFormat format, FlipFunction func)
{ {
s_flipFunctions[flipping][format] = func; s_flipFunctions[UnderlyingCast(flipping)][format] = func;
} }
} }

View File

@ -37,7 +37,7 @@ namespace Nz
inline const Color& GetBlockColor(std::size_t index) const; inline const Color& GetBlockColor(std::size_t index) const;
inline std::size_t GetBlockCount() const; inline std::size_t GetBlockCount() const;
inline std::size_t GetBlockFirstGlyphIndex(std::size_t index) const; inline std::size_t GetBlockFirstGlyphIndex(std::size_t index) const;
inline const FontRef& GetBlockFont(std::size_t index) const; inline const std::shared_ptr<Font>& GetBlockFont(std::size_t index) const;
inline float GetBlockLineHeight(std::size_t index) const; inline float GetBlockLineHeight(std::size_t index) const;
inline float GetBlockLineSpacingOffset(std::size_t index) const; inline float GetBlockLineSpacingOffset(std::size_t index) const;
inline const Color& GetBlockOutlineColor(std::size_t index) const; inline const Color& GetBlockOutlineColor(std::size_t index) const;
@ -50,12 +50,12 @@ namespace Nz
inline unsigned int GetDefaultCharacterSize() const; inline unsigned int GetDefaultCharacterSize() const;
inline float GetDefaultCharacterSpacingOffset() const; inline float GetDefaultCharacterSpacingOffset() const;
inline const Color& GetDefaultColor() const; inline const Color& GetDefaultColor() const;
inline const FontRef& GetDefaultFont() const; inline const std::shared_ptr<Font>& GetDefaultFont() const;
inline float GetDefaultLineSpacingOffset() const; inline float GetDefaultLineSpacingOffset() const;
inline const Color& GetDefaultOutlineColor() const; inline const Color& GetDefaultOutlineColor() const;
inline float GetDefaultOutlineThickness() const; inline float GetDefaultOutlineThickness() const;
inline TextStyleFlags GetDefaultStyle() const; inline TextStyleFlags GetDefaultStyle() const;
Font* GetFont(std::size_t index) const override; const std::shared_ptr<Font>& GetFont(std::size_t index) const override;
std::size_t GetFontCount() const override; std::size_t GetFontCount() const override;
const Glyph& GetGlyph(std::size_t index) const override; const Glyph& GetGlyph(std::size_t index) const override;
std::size_t GetGlyphCount() const override; std::size_t GetGlyphCount() const override;
@ -72,7 +72,7 @@ namespace Nz
inline void SetBlockCharacterSize(std::size_t index, unsigned int characterSize); inline void SetBlockCharacterSize(std::size_t index, unsigned int characterSize);
inline void SetBlockCharacterSpacingOffset(std::size_t index, float offset); inline void SetBlockCharacterSpacingOffset(std::size_t index, float offset);
inline void SetBlockColor(std::size_t index, const Color& color); inline void SetBlockColor(std::size_t index, const Color& color);
inline void SetBlockFont(std::size_t index, FontRef font); inline void SetBlockFont(std::size_t index, std::shared_ptr<Font> font);
inline void SetBlockLineSpacingOffset(std::size_t index, float offset); inline void SetBlockLineSpacingOffset(std::size_t index, float offset);
inline void SetBlockOutlineColor(std::size_t index, const Color& color); inline void SetBlockOutlineColor(std::size_t index, const Color& color);
inline void SetBlockOutlineThickness(std::size_t index, float thickness); inline void SetBlockOutlineThickness(std::size_t index, float thickness);
@ -82,7 +82,7 @@ namespace Nz
inline void SetDefaultCharacterSize(unsigned int characterSize); inline void SetDefaultCharacterSize(unsigned int characterSize);
inline void SetDefaultCharacterSpacingOffset(float offset); inline void SetDefaultCharacterSpacingOffset(float offset);
inline void SetDefaultColor(const Color& color); inline void SetDefaultColor(const Color& color);
inline void SetDefaultFont(const FontRef& font); inline void SetDefaultFont(const std::shared_ptr<Font>& font);
inline void SetDefaultLineSpacingOffset(float offset); inline void SetDefaultLineSpacingOffset(float offset);
inline void SetDefaultOutlineColor(const Color& color); inline void SetDefaultOutlineColor(const Color& color);
inline void SetDefaultOutlineThickness(float thickness); inline void SetDefaultOutlineThickness(float thickness);
@ -98,16 +98,16 @@ namespace Nz
private: private:
struct Block; struct Block;
inline void AppendNewLine(const Font* font, unsigned int characterSize, float lineSpacingOffset) const; inline void AppendNewLine(const Font& font, unsigned int characterSize, float lineSpacingOffset) const;
void AppendNewLine(const Font* font, unsigned int characterSize, float lineSpacingOffset, std::size_t glyphIndex, float glyphPosition) const; void AppendNewLine(const Font& font, unsigned int characterSize, float lineSpacingOffset, std::size_t glyphIndex, float glyphPosition) const;
inline void ClearGlyphs() const; inline void ClearGlyphs() const;
inline void ConnectFontSlots(); inline void ConnectFontSlots();
inline void DisconnectFontSlots(); inline void DisconnectFontSlots();
bool GenerateGlyph(Glyph& glyph, char32_t character, float outlineThickness, bool lineWrap, const Font* font, const Color& color, TextStyleFlags style, float lineSpacingOffset, unsigned int characterSize, int renderOrder, int* advance) const; bool GenerateGlyph(Glyph& glyph, char32_t character, float outlineThickness, bool lineWrap, const Font& font, const Color& color, TextStyleFlags style, float lineSpacingOffset, unsigned int characterSize, int renderOrder, int* advance) const;
void GenerateGlyphs(const Font* font, const Color& color, TextStyleFlags style, unsigned int characterSize, const Color& outlineColor, float characterSpacingOffset, float lineSpacingOffset, float outlineThickness, const std::string& text) const; void GenerateGlyphs(const Font& font, const Color& color, TextStyleFlags style, unsigned int characterSize, const Color& outlineColor, float characterSpacingOffset, float lineSpacingOffset, float outlineThickness, const std::string& text) const;
inline float GetLineHeight(const Block& block) const; inline float GetLineHeight(const Block& block) const;
inline float GetLineHeight(float lineSpacingOffset, const Font::SizeInfo& sizeInfo) const; inline float GetLineHeight(float lineSpacingOffset, const Font::SizeInfo& sizeInfo) const;
inline std::size_t HandleFontAddition(const FontRef& font); inline std::size_t HandleFontAddition(const std::shared_ptr<Font>& font);
inline void InvalidateGlyphs(); inline void InvalidateGlyphs();
inline void ReleaseFont(std::size_t fontIndex); inline void ReleaseFont(std::size_t fontIndex);
inline bool ShouldLineWrap(float size) const; inline bool ShouldLineWrap(float size) const;
@ -136,7 +136,7 @@ namespace Nz
struct FontData struct FontData
{ {
FontRef font; std::shared_ptr<Font> font;
std::size_t useCount = 0; std::size_t useCount = 0;
NazaraSlot(Font, OnFontAtlasChanged, atlasChangedSlot); NazaraSlot(Font, OnFontAtlasChanged, atlasChangedSlot);
@ -148,9 +148,9 @@ namespace Nz
Color m_defaultColor; Color m_defaultColor;
Color m_defaultOutlineColor; Color m_defaultOutlineColor;
TextStyleFlags m_defaultStyle; TextStyleFlags m_defaultStyle;
FontRef m_defaultFont; std::shared_ptr<Font> m_defaultFont;
mutable std::size_t m_lastSeparatorGlyph; mutable std::size_t m_lastSeparatorGlyph;
std::unordered_map<FontRef, std::size_t> m_fontIndexes; std::unordered_map<std::shared_ptr<Font>, std::size_t> m_fontIndexes;
std::vector<Block> m_blocks; std::vector<Block> m_blocks;
std::vector<FontData> m_fonts; std::vector<FontData> m_fonts;
mutable std::vector<Glyph> m_glyphs; mutable std::vector<Glyph> m_glyphs;
@ -179,7 +179,7 @@ namespace Nz
inline unsigned int GetCharacterSize() const; inline unsigned int GetCharacterSize() const;
inline Color GetColor() const; inline Color GetColor() const;
inline std::size_t GetFirstGlyphIndex() const; inline std::size_t GetFirstGlyphIndex() const;
inline const FontRef& GetFont() const; inline const std::shared_ptr<Font>& GetFont() const;
inline float GetLineSpacingOffset() const; inline float GetLineSpacingOffset() const;
inline Color GetOutlineColor() const; inline Color GetOutlineColor() const;
inline float GetOutlineThickness() const; inline float GetOutlineThickness() const;
@ -189,7 +189,7 @@ namespace Nz
inline void SetCharacterSpacingOffset(float offset); inline void SetCharacterSpacingOffset(float offset);
inline void SetCharacterSize(unsigned int size); inline void SetCharacterSize(unsigned int size);
inline void SetColor(Color color); inline void SetColor(Color color);
inline void SetFont(FontRef font); inline void SetFont(std::shared_ptr<Font> font);
inline void SetLineSpacingOffset(float offset); inline void SetLineSpacingOffset(float offset);
inline void SetOutlineColor(Color color); inline void SetOutlineColor(Color color);
inline void SetOutlineThickness(float thickness); inline void SetOutlineThickness(float thickness);

View File

@ -80,7 +80,7 @@ namespace Nz
return m_blocks[index].glyphIndex; return m_blocks[index].glyphIndex;
} }
inline const FontRef& RichTextDrawer::GetBlockFont(std::size_t index) const inline const std::shared_ptr<Font>& RichTextDrawer::GetBlockFont(std::size_t index) const
{ {
NazaraAssert(index < m_blocks.size(), "Invalid block index"); NazaraAssert(index < m_blocks.size(), "Invalid block index");
std::size_t fontIndex = m_blocks[index].fontIndex; std::size_t fontIndex = m_blocks[index].fontIndex;
@ -139,7 +139,7 @@ namespace Nz
return m_defaultColor; return m_defaultColor;
} }
inline const FontRef& RichTextDrawer::GetDefaultFont() const inline const std::shared_ptr<Font>& RichTextDrawer::GetDefaultFont() const
{ {
return m_defaultFont; return m_defaultFont;
} }
@ -164,7 +164,7 @@ namespace Nz
return m_defaultStyle; return m_defaultStyle;
} }
inline void RichTextDrawer::AppendNewLine(const Font* font, unsigned int characterSize, float lineSpacingOffset) const inline void RichTextDrawer::AppendNewLine(const Font& font, unsigned int characterSize, float lineSpacingOffset) const
{ {
AppendNewLine(font, characterSize, lineSpacingOffset, InvalidGlyph, 0); AppendNewLine(font, characterSize, lineSpacingOffset, InvalidGlyph, 0);
} }
@ -214,7 +214,7 @@ namespace Nz
return float(sizeInfo.lineHeight) + lineSpacingOffset; return float(sizeInfo.lineHeight) + lineSpacingOffset;
} }
inline std::size_t RichTextDrawer::HandleFontAddition(const FontRef& font) inline std::size_t RichTextDrawer::HandleFontAddition(const std::shared_ptr<Font>& font)
{ {
auto it = m_fontIndexes.find(font); auto it = m_fontIndexes.find(font);
if (it == m_fontIndexes.end()) if (it == m_fontIndexes.end())
@ -292,7 +292,7 @@ namespace Nz
InvalidateGlyphs(); InvalidateGlyphs();
} }
inline void RichTextDrawer::SetBlockFont(std::size_t index, FontRef font) inline void RichTextDrawer::SetBlockFont(std::size_t index, std::shared_ptr<Font> font)
{ {
NazaraAssert(index < m_blocks.size(), "Invalid block index"); NazaraAssert(index < m_blocks.size(), "Invalid block index");
std::size_t fontIndex = HandleFontAddition(font); std::size_t fontIndex = HandleFontAddition(font);
@ -375,7 +375,7 @@ namespace Nz
m_defaultColor = color; m_defaultColor = color;
} }
inline void RichTextDrawer::SetDefaultFont(const FontRef& font) inline void RichTextDrawer::SetDefaultFont(const std::shared_ptr<Font>& font)
{ {
m_defaultFont = font; m_defaultFont = font;
} }
@ -457,7 +457,7 @@ namespace Nz
* *
* \see GetCharacterSize, GetColor, GetStyle, GetText, SetFont * \see GetCharacterSize, GetColor, GetStyle, GetText, SetFont
*/ */
inline const FontRef& RichTextDrawer::BlockRef::GetFont() const inline const std::shared_ptr<Font>& RichTextDrawer::BlockRef::GetFont() const
{ {
return m_drawer.GetBlockFont(m_blockIndex); return m_drawer.GetBlockFont(m_blockIndex);
} }
@ -567,7 +567,7 @@ namespace Nz
* *
* \see GetCharacterSize, SetCharacterSize, SetColor, SetStyle, SetText * \see GetCharacterSize, SetCharacterSize, SetColor, SetStyle, SetText
*/ */
inline void RichTextDrawer::BlockRef::SetFont(FontRef font) inline void RichTextDrawer::BlockRef::SetFont(std::shared_ptr<Font> font)
{ {
m_drawer.SetBlockFont(m_blockIndex, std::move(font)); m_drawer.SetBlockFont(m_blockIndex, std::move(font));
} }

View File

@ -31,8 +31,8 @@ namespace Nz
inline float GetCharacterSpacingOffset() const; inline float GetCharacterSpacingOffset() const;
inline unsigned int GetCharacterSize() const; inline unsigned int GetCharacterSize() const;
inline const Color& GetColor() const; inline const Color& GetColor() const;
inline Font* GetFont() const; inline const std::shared_ptr<Font>& GetFont() const;
Font* GetFont(std::size_t index) const override; const std::shared_ptr<Font>& GetFont(std::size_t index) const override;
std::size_t GetFontCount() const override; std::size_t GetFontCount() const override;
const Glyph& GetGlyph(std::size_t index) const override; const Glyph& GetGlyph(std::size_t index) const override;
std::size_t GetGlyphCount() const override; std::size_t GetGlyphCount() const override;
@ -49,7 +49,7 @@ namespace Nz
inline void SetCharacterSpacingOffset(float offset); inline void SetCharacterSpacingOffset(float offset);
inline void SetCharacterSize(unsigned int characterSize); inline void SetCharacterSize(unsigned int characterSize);
inline void SetColor(const Color& color); inline void SetColor(const Color& color);
inline void SetFont(Font* font); inline void SetFont(std::shared_ptr<Font> font);
inline void SetLineSpacingOffset(float offset); inline void SetLineSpacingOffset(float offset);
inline void SetMaxLineWidth(float lineWidth) override; inline void SetMaxLineWidth(float lineWidth) override;
inline void SetOutlineColor(const Color& color); inline void SetOutlineColor(const Color& color);
@ -62,8 +62,8 @@ namespace Nz
static inline SimpleTextDrawer Draw(const std::string& str, unsigned int characterSize, TextStyleFlags style = TextStyle_Regular, const Color& color = Color::White); static inline SimpleTextDrawer Draw(const std::string& str, unsigned int characterSize, TextStyleFlags style = TextStyle_Regular, const Color& color = Color::White);
static inline SimpleTextDrawer Draw(const std::string& str, unsigned int characterSize, TextStyleFlags style, const Color& color, float outlineThickness, const Color& outlineColor); static inline SimpleTextDrawer Draw(const std::string& str, unsigned int characterSize, TextStyleFlags style, const Color& color, float outlineThickness, const Color& outlineColor);
static inline SimpleTextDrawer Draw(Font* font, const std::string& str, unsigned int characterSize, TextStyleFlags style = TextStyle_Regular, const Color& color = Color::White); static inline SimpleTextDrawer Draw(const std::shared_ptr<Font>& font, const std::string& str, unsigned int characterSize, TextStyleFlags style = TextStyle_Regular, const Color& color = Color::White);
static inline SimpleTextDrawer Draw(Font* font, const std::string& str, unsigned int characterSize, TextStyleFlags style, const Color& color, float outlineThickness, const Color& outlineColor); static inline SimpleTextDrawer Draw(const std::shared_ptr<Font>& font, const std::string& str, unsigned int characterSize, TextStyleFlags style, const Color& color, float outlineThickness, const Color& outlineColor);
private: private:
inline void AppendNewLine() const; inline void AppendNewLine() const;
@ -104,7 +104,7 @@ namespace Nz
std::string m_text; std::string m_text;
Color m_color; Color m_color;
Color m_outlineColor; Color m_outlineColor;
FontRef m_font; std::shared_ptr<Font> m_font;
mutable Rectf m_bounds; mutable Rectf m_bounds;
TextStyleFlags m_style; TextStyleFlags m_style;
mutable UInt32 m_previousCharacter; mutable UInt32 m_previousCharacter;

View File

@ -65,7 +65,7 @@ namespace Nz
return m_color; return m_color;
} }
inline Font* SimpleTextDrawer::GetFont() const inline const std::shared_ptr<Font>& SimpleTextDrawer::GetFont() const
{ {
return m_font; return m_font;
} }
@ -131,11 +131,11 @@ namespace Nz
} }
} }
inline void SimpleTextDrawer::SetFont(Font* font) inline void SimpleTextDrawer::SetFont(std::shared_ptr<Font> font)
{ {
if (m_font != font) if (m_font != font)
{ {
m_font = font; m_font = std::move(font);
if (m_font) if (m_font)
ConnectFontSlots(); ConnectFontSlots();
@ -281,7 +281,7 @@ namespace Nz
return drawer; return drawer;
} }
inline SimpleTextDrawer SimpleTextDrawer::Draw(Font* font, const std::string& str, unsigned int characterSize, TextStyleFlags style, const Color& color) inline SimpleTextDrawer SimpleTextDrawer::Draw(const std::shared_ptr<Font>& font, const std::string& str, unsigned int characterSize, TextStyleFlags style, const Color& color)
{ {
SimpleTextDrawer drawer; SimpleTextDrawer drawer;
drawer.SetCharacterSize(characterSize); drawer.SetCharacterSize(characterSize);
@ -293,7 +293,7 @@ namespace Nz
return drawer; return drawer;
} }
inline SimpleTextDrawer SimpleTextDrawer::Draw(Font* font, const std::string& str, unsigned int characterSize, TextStyleFlags style, const Color& color, float outlineThickness, const Color& outlineColor) inline SimpleTextDrawer SimpleTextDrawer::Draw(const std::shared_ptr<Font>& font, const std::string& str, unsigned int characterSize, TextStyleFlags style, const Color& color, float outlineThickness, const Color& outlineColor)
{ {
SimpleTextDrawer drawer; SimpleTextDrawer drawer;
drawer.SetCharacterSize(characterSize); drawer.SetCharacterSize(characterSize);

View File

@ -8,56 +8,34 @@
#define NAZARA_SKELETALMESH_HPP #define NAZARA_SKELETALMESH_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Utility/IndexBuffer.hpp> #include <Nazara/Utility/IndexBuffer.hpp>
#include <Nazara/Utility/SubMesh.hpp> #include <Nazara/Utility/SubMesh.hpp>
#include <Nazara/Utility/VertexBuffer.hpp> #include <Nazara/Utility/VertexBuffer.hpp>
namespace Nz namespace Nz
{ {
class SkeletalMesh;
using SkeletalMeshConstRef = ObjectRef<const SkeletalMesh>;
using SkeletalMeshRef = ObjectRef<SkeletalMesh>;
class NAZARA_UTILITY_API SkeletalMesh final : public SubMesh class NAZARA_UTILITY_API SkeletalMesh final : public SubMesh
{ {
public: public:
SkeletalMesh(VertexBuffer* vertexBuffer, const IndexBuffer* indexBuffer); SkeletalMesh(std::shared_ptr<VertexBuffer> vertexBuffer, std::shared_ptr<const IndexBuffer> indexBuffer);
~SkeletalMesh() = default;
NAZARA_DEPRECATED("SkeletalMesh constructor taking a mesh is deprecated, submeshes no longer require to be part of a single mesh")
SkeletalMesh(const Mesh* parent);
~SkeletalMesh();
NAZARA_DEPRECATED("SkeletalMesh create/destroy functions are deprecated, please use constructor")
bool Create(VertexBuffer* vertexBuffer);
void Destroy();
const Boxf& GetAABB() const override; const Boxf& GetAABB() const override;
AnimationType GetAnimationType() const final; AnimationType GetAnimationType() const final;
const IndexBuffer* GetIndexBuffer() const override; const std::shared_ptr<const IndexBuffer>& GetIndexBuffer() const override;
VertexBuffer* GetVertexBuffer(); const std::shared_ptr<VertexBuffer>& GetVertexBuffer() const;
const VertexBuffer* GetVertexBuffer() const;
std::size_t GetVertexCount() const override; std::size_t GetVertexCount() const override;
bool IsAnimated() const final; bool IsAnimated() const final;
bool IsValid() const; bool IsValid() const;
void SetAABB(const Boxf& aabb); void SetAABB(const Boxf& aabb);
void SetIndexBuffer(const IndexBuffer* indexBuffer); void SetIndexBuffer(std::shared_ptr<const IndexBuffer> indexBuffer);
template<typename... Args> static SkeletalMeshRef New(Args&&... args);
// Signals:
NazaraSignal(OnSkeletalMeshDestroy, const SkeletalMesh* /*skeletalMesh*/);
NazaraSignal(OnSkeletalMeshRelease, const SkeletalMesh* /*skeletalMesh*/);
private: private:
Boxf m_aabb; Boxf m_aabb;
IndexBufferConstRef m_indexBuffer; std::shared_ptr<const IndexBuffer> m_indexBuffer;
VertexBufferRef m_vertexBuffer; std::shared_ptr<VertexBuffer> m_vertexBuffer;
}; };
} }

View File

@ -2,19 +2,12 @@
// This file is part of the "Nazara Engine - Utility module" // This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/SkeletalMesh.hpp>
#include <memory> #include <memory>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
namespace Nz namespace Nz
{ {
template<typename... Args>
SkeletalMeshRef SkeletalMesh::New(Args&&... args)
{
std::unique_ptr<SkeletalMesh> object(new SkeletalMesh(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
}
} }
#include <Nazara/Utility/DebugOff.hpp> #include <Nazara/Utility/DebugOff.hpp>

View File

@ -9,8 +9,6 @@
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectLibrary.hpp> #include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Core/Signal.hpp> #include <Nazara/Core/Signal.hpp>
#include <Nazara/Math/Box.hpp> #include <Nazara/Math/Box.hpp>
#include <Nazara/Utility/Config.hpp> #include <Nazara/Utility/Config.hpp>
@ -21,21 +19,18 @@ namespace Nz
class Joint; class Joint;
class Skeleton; class Skeleton;
using SkeletonConstRef = ObjectRef<const Skeleton>;
using SkeletonLibrary = ObjectLibrary<Skeleton>; using SkeletonLibrary = ObjectLibrary<Skeleton>;
using SkeletonRef = ObjectRef<Skeleton>;
struct SkeletonImpl; struct SkeletonImpl;
class NAZARA_UTILITY_API Skeleton : public RefCounted class NAZARA_UTILITY_API Skeleton
{ {
friend Joint; friend Joint;
friend SkeletonLibrary;
friend class Utility;
public: public:
Skeleton() = default; Skeleton();
Skeleton(const Skeleton& skeleton); Skeleton(const Skeleton& skeleton);
Skeleton(Skeleton&&) noexcept;
~Skeleton(); ~Skeleton();
bool Create(std::size_t jointCount); bool Create(std::size_t jointCount);
@ -49,33 +44,25 @@ namespace Nz
Joint* GetJoints(); Joint* GetJoints();
const Joint* GetJoints() const; const Joint* GetJoints() const;
std::size_t GetJointCount() const; std::size_t GetJointCount() const;
int GetJointIndex(const std::string& jointName) const; std::size_t GetJointIndex(const std::string& jointName) const;
void Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation); void Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation);
void Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation, std::size_t* indices, std::size_t indiceCount); void Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation, const std::size_t* indices, std::size_t indiceCount);
bool IsValid() const; bool IsValid() const;
Skeleton& operator=(const Skeleton& skeleton); Skeleton& operator=(const Skeleton& skeleton);
Skeleton& operator=(Skeleton&&) noexcept;
template<typename... Args> static SkeletonRef New(Args&&... args);
// Signals: // Signals:
NazaraSignal(OnSkeletonDestroy, const Skeleton* /*skeleton*/);
NazaraSignal(OnSkeletonJointsInvalidated, const Skeleton* /*skeleton*/); NazaraSignal(OnSkeletonJointsInvalidated, const Skeleton* /*skeleton*/);
NazaraSignal(OnSkeletonRelease, const Skeleton* /*skeleton*/);
private: private:
void InvalidateJoints(); void InvalidateJoints();
void InvalidateJointMap(); void InvalidateJointMap();
void UpdateJointMap() const; void UpdateJointMap() const;
static bool Initialize(); std::unique_ptr<SkeletonImpl> m_impl;
static void Uninitialize();
SkeletonImpl* m_impl = nullptr;
static SkeletonLibrary::LibraryMap s_library;
}; };
} }

View File

@ -7,14 +7,6 @@
namespace Nz namespace Nz
{ {
template<typename... Args>
SkeletonRef Skeleton::New(Args&&... args)
{
std::unique_ptr<Skeleton> object(new Skeleton(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
}
} }
#include <Nazara/Utility/DebugOff.hpp> #include <Nazara/Utility/DebugOff.hpp>

View File

@ -8,57 +8,36 @@
#define NAZARA_STATICMESH_HPP #define NAZARA_STATICMESH_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Utility/SubMesh.hpp> #include <Nazara/Utility/SubMesh.hpp>
namespace Nz namespace Nz
{ {
class StaticMesh;
using StaticMeshConstRef = ObjectRef<const StaticMesh>;
using StaticMeshRef = ObjectRef<StaticMesh>;
class NAZARA_UTILITY_API StaticMesh final : public SubMesh class NAZARA_UTILITY_API StaticMesh final : public SubMesh
{ {
public: public:
StaticMesh(VertexBuffer* vertexBuffer, const IndexBuffer* indexBuffer); StaticMesh(std::shared_ptr<VertexBuffer> vertexBuffer, std::shared_ptr<const IndexBuffer> indexBuffer);
~StaticMesh() = default;
NAZARA_DEPRECATED("StaticMesh constructor taking a mesh is deprecated, submeshes no longer require to be part of a single mesh")
StaticMesh(const Mesh* parent);
~StaticMesh();
void Center(); void Center();
NAZARA_DEPRECATED("StaticMesh create/destroy functions are deprecated, please use constructor")
bool Create(VertexBuffer* vertexBuffer);
void Destroy();
bool GenerateAABB(); bool GenerateAABB();
const Boxf& GetAABB() const override; const Boxf& GetAABB() const override;
AnimationType GetAnimationType() const final; AnimationType GetAnimationType() const final;
const IndexBuffer* GetIndexBuffer() const override; const std::shared_ptr<const IndexBuffer>& GetIndexBuffer() const override;
VertexBuffer* GetVertexBuffer(); const std::shared_ptr<VertexBuffer>& GetVertexBuffer() const;
const VertexBuffer* GetVertexBuffer() const;
std::size_t GetVertexCount() const override; std::size_t GetVertexCount() const override;
bool IsAnimated() const final; bool IsAnimated() const final;
bool IsValid() const; bool IsValid() const;
void SetAABB(const Boxf& aabb); void SetAABB(const Boxf& aabb);
void SetIndexBuffer(const IndexBuffer* indexBuffer); void SetIndexBuffer(std::shared_ptr<const IndexBuffer> indexBuffer);
template<typename... Args> static StaticMeshRef New(Args&&... args);
// Signals:
NazaraSignal(OnStaticMeshDestroy, const StaticMesh* /*staticMesh*/);
NazaraSignal(OnStaticMeshRelease, const StaticMesh* /*staticMesh*/);
private: private:
Boxf m_aabb; Boxf m_aabb;
IndexBufferConstRef m_indexBuffer; std::shared_ptr<const IndexBuffer> m_indexBuffer;
VertexBufferRef m_vertexBuffer; std::shared_ptr<VertexBuffer> m_vertexBuffer;
}; };
} }

View File

@ -7,14 +7,6 @@
namespace Nz namespace Nz
{ {
template<typename... Args>
StaticMeshRef StaticMesh::New(Args&&... args)
{
std::unique_ptr<StaticMesh> object(new StaticMesh(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
}
} }
#include <Nazara/Utility/DebugOff.hpp> #include <Nazara/Utility/DebugOff.hpp>

View File

@ -8,8 +8,7 @@
#define NAZARA_SUBMESH_HPP #define NAZARA_SUBMESH_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectRef.hpp> #include <Nazara/Core/Signal.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Math/Box.hpp> #include <Nazara/Math/Box.hpp>
#include <Nazara/Utility/Enums.hpp> #include <Nazara/Utility/Enums.hpp>
#include <Nazara/Utility/IndexBuffer.hpp> #include <Nazara/Utility/IndexBuffer.hpp>
@ -18,21 +17,13 @@
namespace Nz namespace Nz
{ {
class Mesh; class Mesh;
class SubMesh;
using SubMeshConstRef = ObjectRef<const SubMesh>; class NAZARA_UTILITY_API SubMesh
using SubMeshRef = ObjectRef<SubMesh>;
class NAZARA_UTILITY_API SubMesh : public RefCounted
{ {
friend Mesh; friend Mesh;
public: public:
SubMesh(); SubMesh();
NAZARA_DEPRECATED("Submesh constructor taking a mesh is deprecated, submeshes no longer require to be part of a single mesh")
SubMesh(const Mesh* parent);
SubMesh(const SubMesh&) = delete; SubMesh(const SubMesh&) = delete;
SubMesh(SubMesh&&) = delete; SubMesh(SubMesh&&) = delete;
virtual ~SubMesh(); virtual ~SubMesh();
@ -43,7 +34,7 @@ namespace Nz
virtual const Boxf& GetAABB() const = 0; virtual const Boxf& GetAABB() const = 0;
virtual AnimationType GetAnimationType() const = 0; virtual AnimationType GetAnimationType() const = 0;
virtual const IndexBuffer* GetIndexBuffer() const = 0; virtual const std::shared_ptr<const IndexBuffer>& GetIndexBuffer() const = 0;
std::size_t GetMaterialIndex() const; std::size_t GetMaterialIndex() const;
PrimitiveMode GetPrimitiveMode() const; PrimitiveMode GetPrimitiveMode() const;
std::size_t GetTriangleCount() const; std::size_t GetTriangleCount() const;
@ -59,7 +50,6 @@ namespace Nz
// Signals: // Signals:
NazaraSignal(OnSubMeshInvalidateAABB, const SubMesh* /*subMesh*/); NazaraSignal(OnSubMeshInvalidateAABB, const SubMesh* /*subMesh*/);
NazaraSignal(OnSubMeshRelease, const SubMesh* /*subMesh*/);
protected: protected:
PrimitiveMode m_primitiveMode; PrimitiveMode m_primitiveMode;

View File

@ -18,8 +18,8 @@ namespace Nz
class NAZARA_UTILITY_API TriangleIterator class NAZARA_UTILITY_API TriangleIterator
{ {
public: public:
TriangleIterator(PrimitiveMode primitiveMode, const IndexBuffer* indexBuffer); TriangleIterator(PrimitiveMode primitiveMode, const IndexBuffer& indexBuffer);
TriangleIterator(const SubMesh* subMesh); TriangleIterator(const SubMesh& subMesh);
~TriangleIterator() = default; ~TriangleIterator() = default;
bool Advance(); bool Advance();

View File

@ -8,31 +8,24 @@
#define NAZARA_UNIFORMBUFFER_HPP #define NAZARA_UNIFORMBUFFER_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Utility/Buffer.hpp> #include <Nazara/Utility/Buffer.hpp>
namespace Nz namespace Nz
{ {
class UniformBuffer; class NAZARA_UTILITY_API UniformBuffer
using UniformBufferConstRef = ObjectRef<const UniformBuffer>;
using UniformBufferRef = ObjectRef<UniformBuffer>;
class NAZARA_UTILITY_API UniformBuffer : public RefCounted
{ {
public: public:
UniformBuffer() = default; UniformBuffer() = default;
UniformBuffer(BufferRef buffer); UniformBuffer(std::shared_ptr<Buffer> buffer);
UniformBuffer(BufferRef buffer, UInt32 offset, UInt32 size); UniformBuffer(std::shared_ptr<Buffer> buffer, UInt32 offset, UInt32 size);
UniformBuffer(UInt32 length, DataStorage storage, BufferUsageFlags usage); UniformBuffer(UInt32 length, DataStorage storage, BufferUsageFlags usage);
UniformBuffer(const UniformBuffer& uniformBuffer); UniformBuffer(const UniformBuffer&) = default;
UniformBuffer(UniformBuffer&&) = delete; UniformBuffer(UniformBuffer&&) noexcept = default;
~UniformBuffer(); ~UniformBuffer() = default;
bool Fill(const void* data, UInt32 offset, UInt32 size); bool Fill(const void* data, UInt32 offset, UInt32 size);
inline const BufferRef& GetBuffer() const; inline const std::shared_ptr<Buffer>& GetBuffer() const;
inline UInt32 GetEndOffset() const; inline UInt32 GetEndOffset() const;
inline UInt32 GetStartOffset() const; inline UInt32 GetStartOffset() const;
@ -42,23 +35,18 @@ namespace Nz
void* Map(BufferAccess access, UInt32 offset = 0, UInt32 size = 0) const; void* Map(BufferAccess access, UInt32 offset = 0, UInt32 size = 0) const;
void Reset(); void Reset();
void Reset(BufferRef buffer); void Reset(std::shared_ptr<Buffer> buffer);
void Reset(BufferRef buffer, UInt32 offset, UInt32 size); void Reset(std::shared_ptr<Buffer> buffer, UInt32 offset, UInt32 size);
void Reset(UInt32 size, DataStorage storage, BufferUsageFlags usage); void Reset(UInt32 size, DataStorage storage, BufferUsageFlags usage);
void Reset(const UniformBuffer& uniformBuffer); void Reset(const UniformBuffer& uniformBuffer);
void Unmap() const; void Unmap() const;
UniformBuffer& operator=(const UniformBuffer& uniformBuffer); UniformBuffer& operator=(const UniformBuffer&) = default;
UniformBuffer& operator=(UniformBuffer&&) = delete; UniformBuffer& operator=(UniformBuffer&&) noexcept = default;
template<typename... Args> static UniformBufferRef New(Args&&... args);
// Signals:
NazaraSignal(OnUniformBufferRelease, const UniformBuffer* /*UniformBuffer*/);
private: private:
BufferRef m_buffer; std::shared_ptr<Buffer> m_buffer;
UInt32 m_endOffset; UInt32 m_endOffset;
UInt32 m_startOffset; UInt32 m_startOffset;
}; };

View File

@ -8,7 +8,7 @@
namespace Nz namespace Nz
{ {
inline const BufferRef& UniformBuffer::GetBuffer() const inline const std::shared_ptr<Buffer>& UniformBuffer::GetBuffer() const
{ {
return m_buffer; return m_buffer;
} }
@ -25,16 +25,7 @@ namespace Nz
inline bool UniformBuffer::IsValid() const inline bool UniformBuffer::IsValid() const
{ {
return m_buffer.IsValid(); return m_buffer != nullptr;
}
template<typename... Args>
UniformBufferRef UniformBuffer::New(Args&&... args)
{
std::unique_ptr<UniformBuffer> object(new UniformBuffer(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
} }
} }

View File

@ -9,7 +9,11 @@
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Core.hpp> #include <Nazara/Core/Core.hpp>
#include <Nazara/Utility/Animation.hpp>
#include <Nazara/Utility/Config.hpp> #include <Nazara/Utility/Config.hpp>
#include <Nazara/Utility/Font.hpp>
#include <Nazara/Utility/Image.hpp>
#include <Nazara/Utility/Mesh.hpp>
namespace Nz namespace Nz
{ {
@ -23,9 +27,34 @@ namespace Nz
struct Config {}; struct Config {};
Utility(Config /*config*/); Utility(Config /*config*/);
Utility(const Utility&) = delete;
Utility(Utility&&) = delete;
~Utility(); ~Utility();
AnimationLoader& GetAnimationLoader();
const AnimationLoader& GetAnimationLoader() const;
FontLoader& GetFontLoader();
const FontLoader& GetFontLoader() const;
ImageLoader& GetImageLoader();
const ImageLoader& GetImageLoader() const;
ImageSaver& GetImageSaver();
const ImageSaver& GetImageSaver() const;
MeshLoader& GetMeshLoader();
const MeshLoader& GetMeshLoader() const;
MeshSaver& GetMeshSaver();
const MeshSaver& GetMeshSaver() const;
Utility& operator=(const Utility&) = delete;
Utility& operator=(Utility&&) = delete;
private: private:
AnimationLoader m_animationLoader;
FontLoader m_fontLoader;
ImageLoader m_imageLoader;
ImageSaver m_imageSaver;
MeshLoader m_meshLoader;
MeshSaver m_meshSaver;
static Utility* s_instance; static Utility* s_instance;
}; };
} }

View File

@ -8,39 +8,31 @@
#define NAZARA_VERTEXBUFFER_HPP #define NAZARA_VERTEXBUFFER_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Utility/Buffer.hpp> #include <Nazara/Utility/Buffer.hpp>
#include <Nazara/Utility/VertexDeclaration.hpp> #include <Nazara/Utility/VertexDeclaration.hpp>
namespace Nz namespace Nz
{ {
class VertexBuffer; class NAZARA_UTILITY_API VertexBuffer
using VertexBufferConstRef = ObjectRef<VertexBuffer>;
using VertexBufferRef = ObjectRef<VertexBuffer>;
class NAZARA_UTILITY_API VertexBuffer : public RefCounted
{ {
public: public:
VertexBuffer() = default; VertexBuffer() = default;
VertexBuffer(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer); VertexBuffer(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::shared_ptr<Buffer> buffer);
VertexBuffer(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, std::size_t offset, std::size_t size); VertexBuffer(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::shared_ptr<Buffer> buffer, std::size_t offset, std::size_t size);
VertexBuffer(VertexDeclarationConstRef vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage); VertexBuffer(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage);
VertexBuffer(const VertexBuffer& vertexBuffer); VertexBuffer(const VertexBuffer&) = default;
VertexBuffer(VertexBuffer&&) = delete; VertexBuffer(VertexBuffer&&) noexcept = default;
~VertexBuffer(); ~VertexBuffer() = default;
bool Fill(const void* data, std::size_t startVertex, std::size_t length); bool Fill(const void* data, std::size_t startVertex, std::size_t length);
bool FillRaw(const void* data, std::size_t offset, std::size_t size); bool FillRaw(const void* data, std::size_t offset, std::size_t size);
inline const BufferRef& GetBuffer() const; inline const std::shared_ptr<Buffer>& GetBuffer() const;
inline std::size_t GetEndOffset() const; inline std::size_t GetEndOffset() const;
inline std::size_t GetStartOffset() const; inline std::size_t GetStartOffset() const;
inline std::size_t GetStride() const; inline std::size_t GetStride() const;
inline std::size_t GetVertexCount() const; inline std::size_t GetVertexCount() const;
inline const VertexDeclarationConstRef& GetVertexDeclaration() const; inline const std::shared_ptr<const VertexDeclaration>& GetVertexDeclaration() const;
inline bool IsValid() const; inline bool IsValid() const;
@ -50,29 +42,24 @@ namespace Nz
void* MapRaw(BufferAccess access, std::size_t offset = 0, std::size_t size = 0) const; void* MapRaw(BufferAccess access, std::size_t offset = 0, std::size_t size = 0) const;
void Reset(); void Reset();
void Reset(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer); void Reset(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::shared_ptr<Buffer> buffer);
void Reset(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, std::size_t offset, std::size_t size); void Reset(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::shared_ptr<Buffer> buffer, std::size_t offset, std::size_t size);
void Reset(VertexDeclarationConstRef vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage); void Reset(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage);
void Reset(const VertexBuffer& vertexBuffer); void Reset(const VertexBuffer& vertexBuffer);
void SetVertexDeclaration(VertexDeclarationConstRef vertexDeclaration); void SetVertexDeclaration(std::shared_ptr<const VertexDeclaration> vertexDeclaration);
void Unmap() const; void Unmap() const;
VertexBuffer& operator=(const VertexBuffer& vertexBuffer); VertexBuffer& operator=(const VertexBuffer&) = default;
VertexBuffer& operator=(VertexBuffer&&) = delete; VertexBuffer& operator=(VertexBuffer&&) noexcept = default;
template<typename... Args> static VertexBufferRef New(Args&&... args);
// Signals:
NazaraSignal(OnVertexBufferRelease, const VertexBuffer* /*vertexBuffer*/);
private: private:
BufferRef m_buffer; std::shared_ptr<Buffer> m_buffer;
std::shared_ptr<const VertexDeclaration> m_vertexDeclaration;
std::size_t m_endOffset; std::size_t m_endOffset;
std::size_t m_startOffset; std::size_t m_startOffset;
std::size_t m_vertexCount; std::size_t m_vertexCount;
VertexDeclarationConstRef m_vertexDeclaration;
}; };
} }

View File

@ -2,12 +2,13 @@
// This file is part of the "Nazara Engine - Utility module" // This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/VertexBuffer.hpp>
#include <memory> #include <memory>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
namespace Nz namespace Nz
{ {
inline const BufferRef& VertexBuffer::GetBuffer() const inline const std::shared_ptr<Buffer>& VertexBuffer::GetBuffer() const
{ {
return m_buffer; return m_buffer;
} }
@ -32,23 +33,14 @@ namespace Nz
return m_vertexCount; return m_vertexCount;
} }
inline const VertexDeclarationConstRef& VertexBuffer::GetVertexDeclaration() const inline const std::shared_ptr<const VertexDeclaration>& VertexBuffer::GetVertexDeclaration() const
{ {
return m_vertexDeclaration; return m_vertexDeclaration;
} }
inline bool VertexBuffer::IsValid() const inline bool VertexBuffer::IsValid() const
{ {
return m_buffer.IsValid() && m_vertexDeclaration.IsValid(); return m_buffer && m_vertexDeclaration;
}
template<typename... Args>
VertexBufferRef VertexBuffer::New(Args&&... args)
{
std::unique_ptr<VertexBuffer> object(new VertexBuffer(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
} }
} }

View File

@ -9,8 +9,6 @@
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ObjectLibrary.hpp> #include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Core/SparsePtr.hpp> #include <Nazara/Core/SparsePtr.hpp>
#include <Nazara/Utility/Config.hpp> #include <Nazara/Utility/Config.hpp>
#include <Nazara/Utility/Enums.hpp> #include <Nazara/Utility/Enums.hpp>
@ -20,11 +18,9 @@ namespace Nz
{ {
class VertexDeclaration; class VertexDeclaration;
using VertexDeclarationConstRef = ObjectRef<const VertexDeclaration>;
using VertexDeclarationLibrary = ObjectLibrary<VertexDeclaration>; using VertexDeclarationLibrary = ObjectLibrary<VertexDeclaration>;
using VertexDeclarationRef = ObjectRef<VertexDeclaration>;
class NAZARA_UTILITY_API VertexDeclaration : public RefCounted class NAZARA_UTILITY_API VertexDeclaration
{ {
friend VertexDeclarationLibrary; friend VertexDeclarationLibrary;
friend class Utility; friend class Utility;
@ -54,9 +50,8 @@ namespace Nz
VertexDeclaration& operator=(const VertexDeclaration&) = delete; VertexDeclaration& operator=(const VertexDeclaration&) = delete;
VertexDeclaration& operator=(VertexDeclaration&&) = delete; VertexDeclaration& operator=(VertexDeclaration&&) = delete;
static inline const VertexDeclarationRef& Get(VertexLayout layout); static inline const std::shared_ptr<VertexDeclaration>& Get(VertexLayout layout);
static bool IsTypeSupported(ComponentType type); static bool IsTypeSupported(ComponentType type);
template<typename... Args> static VertexDeclarationRef New(Args&&... args);
struct Component struct Component
{ {
@ -81,8 +76,7 @@ namespace Nz
std::size_t m_stride; std::size_t m_stride;
VertexInputRate m_inputRate; VertexInputRate m_inputRate;
static std::array<VertexDeclarationRef, VertexLayout_Max + 1> s_declarations; static std::array<std::shared_ptr<VertexDeclaration>, VertexLayoutCount> s_declarations;
static VertexDeclarationLibrary::LibraryMap s_library;
}; };
} }

View File

@ -12,7 +12,7 @@ namespace Nz
{ {
inline auto VertexDeclaration::FindComponent(VertexComponent vertexComponent, std::size_t componentIndex) const -> const Component* inline auto VertexDeclaration::FindComponent(VertexComponent vertexComponent, std::size_t componentIndex) const -> const Component*
{ {
assert(componentIndex == 0 || vertexComponent == VertexComponent_Userdata); assert(componentIndex == 0 || vertexComponent == VertexComponent::Userdata);
for (const Component& component : m_components) for (const Component& component : m_components)
{ {
@ -56,7 +56,7 @@ namespace Nz
template<typename T> template<typename T>
auto VertexDeclaration::GetComponentByType(VertexComponent vertexComponent, std::size_t componentIndex) const -> const Component* auto VertexDeclaration::GetComponentByType(VertexComponent vertexComponent, std::size_t componentIndex) const -> const Component*
{ {
NazaraAssert(componentIndex == 0 || vertexComponent == VertexComponent_Userdata, "Only userdata vertex component can have component indexes"); NazaraAssert(componentIndex == 0 || vertexComponent == VertexComponent::Userdata, "Only userdata vertex component can have component indexes");
if (const Component* component = FindComponent(vertexComponent, componentIndex)) if (const Component* component = FindComponent(vertexComponent, componentIndex))
{ {
if (GetComponentTypeOf<T>() == component->type) if (GetComponentTypeOf<T>() == component->type)
@ -72,20 +72,11 @@ namespace Nz
return GetComponentByType<T>(vertexComponent, componentIndex) != nullptr; return GetComponentByType<T>(vertexComponent, componentIndex) != nullptr;
} }
inline const VertexDeclarationRef& VertexDeclaration::Get(VertexLayout layout) inline const std::shared_ptr<VertexDeclaration>& VertexDeclaration::Get(VertexLayout layout)
{ {
NazaraAssert(layout <= VertexLayout_Max, "Vertex layout out of enum"); NazaraAssert(layout <= VertexLayout::Max, "Vertex layout out of enum");
return s_declarations[layout]; return s_declarations[UnderlyingCast(layout)];
}
template<typename... Args>
VertexDeclarationRef VertexDeclaration::New(Args&&... args)
{
std::unique_ptr<VertexDeclaration> object = std::make_unique<VertexDeclaration>(std::forward<Args>(args)...);
object->SetPersistent(false);
return object.release();
} }
} }

View File

@ -20,10 +20,10 @@ namespace Nz
class NAZARA_UTILITY_API VertexMapper class NAZARA_UTILITY_API VertexMapper
{ {
public: public:
VertexMapper(SubMesh* subMesh, BufferAccess access = BufferAccess_ReadWrite); VertexMapper(SubMesh& subMesh, BufferAccess access = BufferAccess::ReadWrite);
VertexMapper(VertexBuffer* vertexBuffer, BufferAccess access = BufferAccess_ReadWrite); VertexMapper(VertexBuffer& vertexBuffer, BufferAccess access = BufferAccess::ReadWrite);
VertexMapper(const SubMesh* subMesh, BufferAccess access = BufferAccess_ReadOnly); VertexMapper(const SubMesh& subMesh, BufferAccess access = BufferAccess::ReadOnly);
VertexMapper(const VertexBuffer* vertexBuffer, BufferAccess access = BufferAccess_ReadOnly); VertexMapper(const VertexBuffer& vertexBuffer, BufferAccess access = BufferAccess::ReadOnly);
~VertexMapper(); ~VertexMapper();
template<typename T> SparsePtr<T> GetComponentPtr(VertexComponent component, std::size_t componentIndex = 0); template<typename T> SparsePtr<T> GetComponentPtr(VertexComponent component, std::size_t componentIndex = 0);

View File

@ -13,7 +13,7 @@ namespace Nz
SparsePtr<T> VertexMapper::GetComponentPtr(VertexComponent component, std::size_t componentIndex) SparsePtr<T> VertexMapper::GetComponentPtr(VertexComponent component, std::size_t componentIndex)
{ {
// On récupère la déclaration depuis le buffer // On récupère la déclaration depuis le buffer
const VertexDeclaration* declaration = m_mapper.GetBuffer()->GetVertexDeclaration(); const std::shared_ptr<const VertexDeclaration>& declaration = m_mapper.GetBuffer()->GetVertexDeclaration();
if (const auto* componentData = declaration->GetComponentByType<T>(component, componentIndex)) if (const auto* componentData = declaration->GetComponentByType<T>(component, componentIndex))
return SparsePtr<T>(static_cast<UInt8*>(m_mapper.GetPointer()) + componentData->offset, declaration->GetStride()); return SparsePtr<T>(static_cast<UInt8*>(m_mapper.GetPointer()) + componentData->offset, declaration->GetStride());

View File

@ -14,12 +14,12 @@ namespace Nz
{ {
switch (format) switch (format)
{ {
case VK_FORMAT_B8G8R8A8_UNORM: return PixelFormat::PixelFormat_BGRA8; case VK_FORMAT_B8G8R8A8_UNORM: return PixelFormat::BGRA8;
case VK_FORMAT_B8G8R8A8_SRGB: return PixelFormat::PixelFormat_BGRA8_SRGB; case VK_FORMAT_B8G8R8A8_SRGB: return PixelFormat::BGRA8_SRGB;
case VK_FORMAT_D24_UNORM_S8_UINT: return PixelFormat::PixelFormat_Depth24Stencil8; case VK_FORMAT_D24_UNORM_S8_UINT: return PixelFormat::Depth24Stencil8;
case VK_FORMAT_D32_SFLOAT: return PixelFormat::PixelFormat_Depth32; case VK_FORMAT_D32_SFLOAT: return PixelFormat::Depth32;
case VK_FORMAT_R8G8B8A8_UNORM: return PixelFormat::PixelFormat_RGBA8; case VK_FORMAT_R8G8B8A8_UNORM: return PixelFormat::RGBA8;
case VK_FORMAT_R8G8B8A8_SRGB: return PixelFormat::PixelFormat_RGBA8_SRGB; case VK_FORMAT_R8G8B8A8_SRGB: return PixelFormat::RGBA8_SRGB;
default: break; default: break;
} }
@ -94,12 +94,12 @@ namespace Nz
{ {
switch (bufferType) switch (bufferType)
{ {
case BufferType_Index: return VK_BUFFER_USAGE_INDEX_BUFFER_BIT; case BufferType::Index: return VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
case BufferType_Vertex: return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; case BufferType::Vertex: return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
case BufferType_Uniform: return VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; case BufferType::Uniform: return VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
} }
NazaraError("Unhandled BufferType 0x" + NumberToString(bufferType, 16)); NazaraError("Unhandled BufferType 0x" + NumberToString(UnderlyingCast(bufferType), 16));
return 0; return 0;
} }
@ -107,23 +107,23 @@ namespace Nz
{ {
switch (componentType) switch (componentType)
{ {
case ComponentType_Color: return VK_FORMAT_R8G8B8A8_UINT; case ComponentType::Color: return VK_FORMAT_R8G8B8A8_UINT;
case ComponentType_Double1: return VK_FORMAT_R64_SFLOAT; case ComponentType::Double1: return VK_FORMAT_R64_SFLOAT;
case ComponentType_Double2: return VK_FORMAT_R64G64_SFLOAT; case ComponentType::Double2: return VK_FORMAT_R64G64_SFLOAT;
case ComponentType_Double3: return VK_FORMAT_R64G64B64_SFLOAT; case ComponentType::Double3: return VK_FORMAT_R64G64B64_SFLOAT;
case ComponentType_Double4: return VK_FORMAT_R64G64B64A64_SFLOAT; case ComponentType::Double4: return VK_FORMAT_R64G64B64A64_SFLOAT;
case ComponentType_Float1: return VK_FORMAT_R32_SFLOAT; case ComponentType::Float1: return VK_FORMAT_R32_SFLOAT;
case ComponentType_Float2: return VK_FORMAT_R32G32_SFLOAT; case ComponentType::Float2: return VK_FORMAT_R32G32_SFLOAT;
case ComponentType_Float3: return VK_FORMAT_R32G32B32_SFLOAT; case ComponentType::Float3: return VK_FORMAT_R32G32B32_SFLOAT;
case ComponentType_Float4: return VK_FORMAT_R32G32B32A32_SFLOAT; case ComponentType::Float4: return VK_FORMAT_R32G32B32A32_SFLOAT;
case ComponentType_Int1: return VK_FORMAT_R32_SINT; case ComponentType::Int1: return VK_FORMAT_R32_SINT;
case ComponentType_Int2: return VK_FORMAT_R32G32_SINT; case ComponentType::Int2: return VK_FORMAT_R32G32_SINT;
case ComponentType_Int3: return VK_FORMAT_R32G32B32_SINT; case ComponentType::Int3: return VK_FORMAT_R32G32B32_SINT;
case ComponentType_Int4: return VK_FORMAT_R32G32B32A32_SINT; case ComponentType::Int4: return VK_FORMAT_R32G32B32A32_SINT;
case ComponentType_Quaternion: return VK_FORMAT_R32G32B32A32_SFLOAT; case ComponentType::Quaternion: return VK_FORMAT_R32G32B32A32_SFLOAT;
} }
NazaraError("Unhandled ComponentType 0x" + NumberToString(componentType, 16)); NazaraError("Unhandled ComponentType 0x" + NumberToString(UnderlyingCast(componentType), 16));
return VK_FORMAT_UNDEFINED; return VK_FORMAT_UNDEFINED;
} }
@ -131,13 +131,13 @@ namespace Nz
{ {
switch (faceSide) switch (faceSide)
{ {
case FaceSide_None: return VK_CULL_MODE_NONE; case FaceSide::None: return VK_CULL_MODE_NONE;
case FaceSide_Back: return VK_CULL_MODE_BACK_BIT; case FaceSide::Back: return VK_CULL_MODE_BACK_BIT;
case FaceSide_Front: return VK_CULL_MODE_FRONT_BIT; case FaceSide::Front: return VK_CULL_MODE_FRONT_BIT;
case FaceSide_FrontAndBack: return VK_CULL_MODE_FRONT_AND_BACK; case FaceSide::FrontAndBack: return VK_CULL_MODE_FRONT_AND_BACK;
} }
NazaraError("Unhandled FaceSide 0x" + NumberToString(faceSide, 16)); NazaraError("Unhandled FaceSide 0x" + NumberToString(UnderlyingCast(faceSide), 16));
return VK_CULL_MODE_BACK_BIT; return VK_CULL_MODE_BACK_BIT;
} }
@ -145,12 +145,12 @@ namespace Nz
{ {
switch (faceFilling) switch (faceFilling)
{ {
case FaceFilling_Fill: return VK_POLYGON_MODE_FILL; case FaceFilling::Fill: return VK_POLYGON_MODE_FILL;
case FaceFilling_Line: return VK_POLYGON_MODE_LINE; case FaceFilling::Line: return VK_POLYGON_MODE_LINE;
case FaceFilling_Point: return VK_POLYGON_MODE_POINT; case FaceFilling::Point: return VK_POLYGON_MODE_POINT;
} }
NazaraError("Unhandled FaceFilling 0x" + NumberToString(faceFilling, 16)); NazaraError("Unhandled FaceFilling 0x" + NumberToString(UnderlyingCast(faceFilling), 16));
return VK_POLYGON_MODE_FILL; return VK_POLYGON_MODE_FILL;
} }
@ -234,17 +234,17 @@ namespace Nz
{ {
switch (pixelFormat) switch (pixelFormat)
{ {
case PixelFormat::PixelFormat_BGRA8: return VK_FORMAT_B8G8R8A8_UNORM; case PixelFormat::BGRA8: return VK_FORMAT_B8G8R8A8_UNORM;
case PixelFormat::PixelFormat_BGRA8_SRGB: return VK_FORMAT_B8G8R8A8_SRGB; case PixelFormat::BGRA8_SRGB: return VK_FORMAT_B8G8R8A8_SRGB;
case PixelFormat::PixelFormat_Depth24Stencil8: return VK_FORMAT_D24_UNORM_S8_UINT; case PixelFormat::Depth24Stencil8: return VK_FORMAT_D24_UNORM_S8_UINT;
case PixelFormat::PixelFormat_Depth32: return VK_FORMAT_D32_SFLOAT; case PixelFormat::Depth32: return VK_FORMAT_D32_SFLOAT;
case PixelFormat::PixelFormat_RGBA8: return VK_FORMAT_R8G8B8A8_UNORM; case PixelFormat::RGBA8: return VK_FORMAT_R8G8B8A8_UNORM;
case PixelFormat::PixelFormat_RGBA8_SRGB: return VK_FORMAT_R8G8B8A8_SRGB; case PixelFormat::RGBA8_SRGB: return VK_FORMAT_R8G8B8A8_SRGB;
case PixelFormat::PixelFormat_RGBA32F: return VK_FORMAT_R32G32B32A32_SFLOAT; case PixelFormat::RGBA32F: return VK_FORMAT_R32G32B32A32_SFLOAT;
default: break; default: break;
} }
NazaraError("Unhandled PixelFormat 0x" + NumberToString(pixelFormat, 16)); NazaraError("Unhandled PixelFormat 0x" + NumberToString(UnderlyingCast(pixelFormat), 16));
return {}; return {};
} }
@ -252,15 +252,15 @@ namespace Nz
{ {
switch (primitiveMode) switch (primitiveMode)
{ {
case PrimitiveMode_LineList: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST; case PrimitiveMode::LineList: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
case PrimitiveMode_LineStrip: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; case PrimitiveMode::LineStrip: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
case PrimitiveMode_PointList: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST; case PrimitiveMode::PointList: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
case PrimitiveMode_TriangleList: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; case PrimitiveMode::TriangleList: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
case PrimitiveMode_TriangleStrip: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; case PrimitiveMode::TriangleStrip: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
case PrimitiveMode_TriangleFan: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; case PrimitiveMode::TriangleFan: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN;
} }
NazaraError("Unhandled FaceFilling 0x" + NumberToString(primitiveMode, 16)); NazaraError("Unhandled FaceFilling 0x" + NumberToString(UnderlyingCast(primitiveMode), 16));
return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
} }
@ -268,17 +268,17 @@ namespace Nz
{ {
switch (comparison) switch (comparison)
{ {
case RendererComparison_Never: return VK_COMPARE_OP_NEVER; case RendererComparison::Never: return VK_COMPARE_OP_NEVER;
case RendererComparison_Less: return VK_COMPARE_OP_LESS; case RendererComparison::Less: return VK_COMPARE_OP_LESS;
case RendererComparison_Equal: return VK_COMPARE_OP_EQUAL; case RendererComparison::Equal: return VK_COMPARE_OP_EQUAL;
case RendererComparison_LessOrEqual: return VK_COMPARE_OP_LESS_OR_EQUAL; case RendererComparison::LessOrEqual: return VK_COMPARE_OP_LESS_OR_EQUAL;
case RendererComparison_Greater: return VK_COMPARE_OP_GREATER; case RendererComparison::Greater: return VK_COMPARE_OP_GREATER;
case RendererComparison_NotEqual: return VK_COMPARE_OP_NOT_EQUAL; case RendererComparison::NotEqual: return VK_COMPARE_OP_NOT_EQUAL;
case RendererComparison_GreaterOrEqual: return VK_COMPARE_OP_GREATER_OR_EQUAL; case RendererComparison::GreaterOrEqual: return VK_COMPARE_OP_GREATER_OR_EQUAL;
case RendererComparison_Always: return VK_COMPARE_OP_ALWAYS; case RendererComparison::Always: return VK_COMPARE_OP_ALWAYS;
} }
NazaraError("Unhandled RendererComparison 0x" + NumberToString(comparison, 16)); NazaraError("Unhandled RendererComparison 0x" + NumberToString(UnderlyingCast(comparison), 16));
return VK_COMPARE_OP_NEVER; return VK_COMPARE_OP_NEVER;
} }
@ -286,8 +286,8 @@ namespace Nz
{ {
switch (samplerFilter) switch (samplerFilter)
{ {
case SamplerFilter_Linear: return VK_FILTER_LINEAR; case SamplerFilter::Linear: return VK_FILTER_LINEAR;
case SamplerFilter_Nearest: return VK_FILTER_NEAREST; case SamplerFilter::Nearest: return VK_FILTER_NEAREST;
} }
NazaraError("Unhandled SamplerFilter 0x" + NumberToString(UnderlyingCast(samplerFilter), 16)); NazaraError("Unhandled SamplerFilter 0x" + NumberToString(UnderlyingCast(samplerFilter), 16));
@ -298,8 +298,8 @@ namespace Nz
{ {
switch (samplerMipmap) switch (samplerMipmap)
{ {
case SamplerMipmapMode_Linear: return VK_SAMPLER_MIPMAP_MODE_LINEAR; case SamplerMipmapMode::Linear: return VK_SAMPLER_MIPMAP_MODE_LINEAR;
case SamplerMipmapMode_Nearest: return VK_SAMPLER_MIPMAP_MODE_NEAREST; case SamplerMipmapMode::Nearest: return VK_SAMPLER_MIPMAP_MODE_NEAREST;
} }
NazaraError("Unhandled SamplerMipmapMode 0x" + NumberToString(UnderlyingCast(samplerMipmap), 16)); NazaraError("Unhandled SamplerMipmapMode 0x" + NumberToString(UnderlyingCast(samplerMipmap), 16));
@ -310,9 +310,9 @@ namespace Nz
{ {
switch (samplerWrap) switch (samplerWrap)
{ {
case SamplerWrap_Clamp: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; case SamplerWrap::Clamp: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
case SamplerWrap_MirroredRepeat: return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; case SamplerWrap::MirroredRepeat: return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
case SamplerWrap_Repeat: return VK_SAMPLER_ADDRESS_MODE_REPEAT; case SamplerWrap::Repeat: return VK_SAMPLER_ADDRESS_MODE_REPEAT;
} }
NazaraError("Unhandled SamplerWrap 0x" + NumberToString(UnderlyingCast(samplerWrap), 16)); NazaraError("Unhandled SamplerWrap 0x" + NumberToString(UnderlyingCast(samplerWrap), 16));
@ -360,17 +360,17 @@ namespace Nz
{ {
switch (stencilOp) switch (stencilOp)
{ {
case StencilOperation_Decrement: return VK_STENCIL_OP_DECREMENT_AND_CLAMP; case StencilOperation::Decrement: return VK_STENCIL_OP_DECREMENT_AND_CLAMP;
case StencilOperation_DecrementNoClamp: return VK_STENCIL_OP_DECREMENT_AND_WRAP; case StencilOperation::DecrementNoClamp: return VK_STENCIL_OP_DECREMENT_AND_WRAP;
case StencilOperation_Increment: return VK_STENCIL_OP_INCREMENT_AND_CLAMP; case StencilOperation::Increment: return VK_STENCIL_OP_INCREMENT_AND_CLAMP;
case StencilOperation_IncrementNoClamp: return VK_STENCIL_OP_INCREMENT_AND_WRAP; case StencilOperation::IncrementNoClamp: return VK_STENCIL_OP_INCREMENT_AND_WRAP;
case StencilOperation_Invert: return VK_STENCIL_OP_INVERT; case StencilOperation::Invert: return VK_STENCIL_OP_INVERT;
case StencilOperation_Keep: return VK_STENCIL_OP_KEEP; case StencilOperation::Keep: return VK_STENCIL_OP_KEEP;
case StencilOperation_Replace: return VK_STENCIL_OP_REPLACE; case StencilOperation::Replace: return VK_STENCIL_OP_REPLACE;
case StencilOperation_Zero: return VK_STENCIL_OP_ZERO; case StencilOperation::Zero: return VK_STENCIL_OP_ZERO;
} }
NazaraError("Unhandled StencilOperation 0x" + NumberToString(stencilOp, 16)); NazaraError("Unhandled StencilOperation 0x" + NumberToString(UnderlyingCast(stencilOp), 16));
return {}; return {};
} }

View File

@ -36,6 +36,7 @@ SOFTWARE.
#include <Nazara/Utility/Skeleton.hpp> #include <Nazara/Utility/Skeleton.hpp>
#include <Nazara/Utility/StaticMesh.hpp> #include <Nazara/Utility/StaticMesh.hpp>
#include <Nazara/Utility/VertexMapper.hpp> #include <Nazara/Utility/VertexMapper.hpp>
#include <Nazara/Utility/Utility.hpp>
#include <assimp/cfileio.h> #include <assimp/cfileio.h>
#include <assimp/cimport.h> #include <assimp/cimport.h>
#include <assimp/config.h> #include <assimp/config.h>
@ -74,9 +75,13 @@ void ProcessJoints(aiNode* node, Skeleton* skeleton, const std::set<std::string>
ProcessJoints(node->mChildren[i], skeleton, joints); ProcessJoints(node->mChildren[i], skeleton, joints);
} }
bool IsSupported(const std::string& extension) bool IsSupported(const std::string_view& extension)
{ {
std::string dotExt = '.' + extension; std::string dotExt;
dotExt.reserve(extension.size() + 1);
dotExt += '.';
dotExt += extension;
return (aiIsExtensionSupported(dotExt.data()) == AI_TRUE); return (aiIsExtensionSupported(dotExt.data()) == AI_TRUE);
} }
@ -89,7 +94,7 @@ Ternary CheckAnimation(Stream& /*stream*/, const AnimationParams& parameters)
return Ternary::Unknown; return Ternary::Unknown;
} }
AnimationRef LoadAnimation(Stream& stream, const AnimationParams& parameters) std::shared_ptr<Animation> LoadAnimation(Stream& stream, const AnimationParams& parameters)
{ {
std::string streamPath = stream.GetPath().generic_u8string(); std::string streamPath = stream.GetPath().generic_u8string();
@ -141,7 +146,7 @@ AnimationRef LoadAnimation(Stream& stream, const AnimationParams& parameters)
maxFrameCount = std::max({ maxFrameCount, nodeAnim->mNumPositionKeys, nodeAnim->mNumRotationKeys, nodeAnim->mNumScalingKeys }); maxFrameCount = std::max({ maxFrameCount, nodeAnim->mNumPositionKeys, nodeAnim->mNumRotationKeys, nodeAnim->mNumScalingKeys });
} }
AnimationRef anim = Animation::New(); std::shared_ptr<Animation> anim = std::make_shared<Animation>();
anim->CreateSkeletal(maxFrameCount, animation->mNumChannels); anim->CreateSkeletal(maxFrameCount, animation->mNumChannels);
@ -184,7 +189,7 @@ Ternary CheckMesh(Stream& /*stream*/, const MeshParams& parameters)
return Ternary::Unknown; return Ternary::Unknown;
} }
MeshRef LoadMesh(Stream& stream, const MeshParams& parameters) std::shared_ptr<Mesh> LoadMesh(Stream& stream, const MeshParams& parameters)
{ {
std::string streamPath = stream.GetPath().generic_u8string(); std::string streamPath = stream.GetPath().generic_u8string();
@ -221,16 +226,16 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
int excludedComponents = 0; int excludedComponents = 0;
if (!parameters.vertexDeclaration->HasComponent(VertexComponent_Color)) if (!parameters.vertexDeclaration->HasComponent(VertexComponent::Color))
excludedComponents |= aiComponent_COLORS; excludedComponents |= aiComponent_COLORS;
if (!parameters.vertexDeclaration->HasComponent(VertexComponent_Normal)) if (!parameters.vertexDeclaration->HasComponent(VertexComponent::Normal))
excludedComponents |= aiComponent_NORMALS; excludedComponents |= aiComponent_NORMALS;
if (!parameters.vertexDeclaration->HasComponent(VertexComponent_Tangent)) if (!parameters.vertexDeclaration->HasComponent(VertexComponent::Tangent))
excludedComponents |= aiComponent_TANGENTS_AND_BITANGENTS; excludedComponents |= aiComponent_TANGENTS_AND_BITANGENTS;
if (!parameters.vertexDeclaration->HasComponent(VertexComponent_TexCoord)) if (!parameters.vertexDeclaration->HasComponent(VertexComponent::TexCoord))
excludedComponents |= aiComponent_TEXCOORDS; excludedComponents |= aiComponent_TEXCOORDS;
aiPropertyStore* properties = aiCreatePropertyStore(); aiPropertyStore* properties = aiCreatePropertyStore();
@ -271,7 +276,7 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
} }
} }
MeshRef mesh = Mesh::New(); std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
if (animatedMesh) if (animatedMesh)
{ {
mesh->CreateSkeletal(UInt32(joints.size())); mesh->CreateSkeletal(UInt32(joints.size()));
@ -302,9 +307,9 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
// Index buffer // Index buffer
bool largeIndices = (vertexCount > std::numeric_limits<UInt16>::max()); bool largeIndices = (vertexCount > std::numeric_limits<UInt16>::max());
IndexBufferRef indexBuffer = IndexBuffer::New(largeIndices, indexCount, parameters.storage, parameters.indexBufferFlags); std::shared_ptr<IndexBuffer> indexBuffer = std::make_shared<IndexBuffer>(largeIndices, indexCount, parameters.storage, parameters.indexBufferFlags);
IndexMapper indexMapper(indexBuffer, BufferAccess_DiscardAndWrite); IndexMapper indexMapper(*indexBuffer, BufferAccess::DiscardAndWrite);
IndexIterator index = indexMapper.begin(); IndexIterator index = indexMapper.begin();
for (unsigned int faceIdx = 0; faceIdx < iMesh->mNumFaces; ++faceIdx) for (unsigned int faceIdx = 0; faceIdx < iMesh->mNumFaces; ++faceIdx)
@ -324,8 +329,8 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
if (normalTangentMatrix.HasScale()) if (normalTangentMatrix.HasScale())
normalTangentMatrix.ApplyScale(1.f / normalTangentMatrix.GetScale()); normalTangentMatrix.ApplyScale(1.f / normalTangentMatrix.GetScale());
VertexBufferRef vertexBuffer = VertexBuffer::New(VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent_Skinning), vertexCount, parameters.storage, parameters.vertexBufferFlags); std::shared_ptr<VertexBuffer> vertexBuffer = std::make_shared<VertexBuffer>(VertexDeclaration::Get(VertexLayout::XYZ_Normal_UV_Tangent_Skinning), vertexCount, parameters.storage, parameters.vertexBufferFlags);
BufferMapper<VertexBuffer> vertexMapper(vertexBuffer, BufferAccess_ReadWrite); BufferMapper<VertexBuffer> vertexMapper(*vertexBuffer, BufferAccess::ReadWrite);
SkeletalMeshVertex* vertices = static_cast<SkeletalMeshVertex*>(vertexMapper.GetPointer()); SkeletalMeshVertex* vertices = static_cast<SkeletalMeshVertex*>(vertexMapper.GetPointer());
for (std::size_t vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx) for (std::size_t vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx)
@ -357,7 +362,7 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
} }
// Submesh // Submesh
SkeletalMeshRef subMesh = SkeletalMesh::New(vertexBuffer, indexBuffer); std::shared_ptr<SkeletalMesh> subMesh = std::make_shared<SkeletalMesh>(vertexBuffer, indexBuffer);
subMesh->SetMaterialIndex(iMesh->mMaterialIndex); subMesh->SetMaterialIndex(iMesh->mMaterialIndex);
auto matIt = materials.find(iMesh->mMaterialIndex); auto matIt = materials.find(iMesh->mMaterialIndex);
@ -385,20 +390,20 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
if (wrapKey) if (wrapKey)
{ {
SamplerWrap wrap = SamplerWrap_Clamp; SamplerWrap wrap = SamplerWrap::Clamp;
switch (mapMode[0]) switch (mapMode[0])
{ {
case aiTextureMapMode_Clamp: case aiTextureMapMode_Clamp:
case aiTextureMapMode_Decal: case aiTextureMapMode_Decal:
wrap = SamplerWrap_Clamp; wrap = SamplerWrap::Clamp;
break; break;
case aiTextureMapMode_Mirror: case aiTextureMapMode_Mirror:
wrap = SamplerWrap_MirroredRepeat; wrap = SamplerWrap::MirroredRepeat;
break; break;
case aiTextureMapMode_Wrap: case aiTextureMapMode_Wrap:
wrap = SamplerWrap_Repeat; wrap = SamplerWrap::Repeat;
break; break;
default: default:
@ -460,9 +465,9 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
// Index buffer // Index buffer
bool largeIndices = (vertexCount > std::numeric_limits<UInt16>::max()); bool largeIndices = (vertexCount > std::numeric_limits<UInt16>::max());
IndexBufferRef indexBuffer = IndexBuffer::New(largeIndices, indexCount, parameters.storage, parameters.indexBufferFlags); std::shared_ptr<IndexBuffer> indexBuffer = std::make_shared<IndexBuffer>(largeIndices, indexCount, parameters.storage, parameters.indexBufferFlags);
IndexMapper indexMapper(indexBuffer, BufferAccess_DiscardAndWrite); IndexMapper indexMapper(*indexBuffer, BufferAccess::DiscardAndWrite);
IndexIterator index = indexMapper.begin(); IndexIterator index = indexMapper.begin();
for (unsigned int faceIdx = 0; faceIdx < iMesh->mNumFaces; ++faceIdx) for (unsigned int faceIdx = 0; faceIdx < iMesh->mNumFaces; ++faceIdx)
@ -484,18 +489,18 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
if (normalTangentMatrix.HasScale()) if (normalTangentMatrix.HasScale())
normalTangentMatrix.ApplyScale(1.f / normalTangentMatrix.GetScale()); normalTangentMatrix.ApplyScale(1.f / normalTangentMatrix.GetScale());
VertexBufferRef vertexBuffer = VertexBuffer::New(parameters.vertexDeclaration, vertexCount, parameters.storage, parameters.vertexBufferFlags); std::shared_ptr<VertexBuffer> vertexBuffer = std::make_shared<VertexBuffer>(parameters.vertexDeclaration, vertexCount, parameters.storage, parameters.vertexBufferFlags);
VertexMapper vertexMapper(vertexBuffer, BufferAccess_DiscardAndWrite); VertexMapper vertexMapper(*vertexBuffer, BufferAccess::DiscardAndWrite);
auto posPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); auto posPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
for (unsigned int vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx) for (unsigned int vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx)
{ {
aiVector3D position = iMesh->mVertices[vertexIdx]; aiVector3D position = iMesh->mVertices[vertexIdx];
*posPtr++ = parameters.matrix * Vector3f(position.x, position.y, position.z); *posPtr++ = parameters.matrix * Vector3f(position.x, position.y, position.z);
} }
if (auto normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Normal)) if (auto normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Normal))
{ {
for (unsigned int vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx) for (unsigned int vertexIdx = 0; vertexIdx < vertexCount; ++vertexIdx)
{ {
@ -505,7 +510,7 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
} }
bool generateTangents = false; bool generateTangents = false;
if (auto tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Tangent)) if (auto tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Tangent))
{ {
if (iMesh->HasTangentsAndBitangents()) if (iMesh->HasTangentsAndBitangents())
{ {
@ -519,7 +524,7 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
generateTangents = true; generateTangents = true;
} }
if (auto uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord)) if (auto uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord))
{ {
if (iMesh->HasTextureCoords(0)) if (iMesh->HasTextureCoords(0))
{ {
@ -539,7 +544,7 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
vertexMapper.Unmap(); vertexMapper.Unmap();
// Submesh // Submesh
StaticMeshRef subMesh = StaticMesh::New(vertexBuffer, indexBuffer); std::shared_ptr<StaticMesh> subMesh = std::make_shared<StaticMesh>(vertexBuffer, indexBuffer);
subMesh->GenerateAABB(); subMesh->GenerateAABB();
subMesh->SetMaterialIndex(iMesh->mMaterialIndex); subMesh->SetMaterialIndex(iMesh->mMaterialIndex);
@ -571,20 +576,20 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
if (wrapKey) if (wrapKey)
{ {
SamplerWrap wrap = SamplerWrap_Clamp; SamplerWrap wrap = SamplerWrap::Clamp;
switch (mapMode[0]) switch (mapMode[0])
{ {
case aiTextureMapMode_Clamp: case aiTextureMapMode_Clamp:
case aiTextureMapMode_Decal: case aiTextureMapMode_Decal:
wrap = SamplerWrap_Clamp; wrap = SamplerWrap::Clamp;
break; break;
case aiTextureMapMode_Mirror: case aiTextureMapMode_Mirror:
wrap = SamplerWrap_MirroredRepeat; wrap = SamplerWrap::MirroredRepeat;
break; break;
case aiTextureMapMode_Wrap: case aiTextureMapMode_Wrap:
wrap = SamplerWrap_Repeat; wrap = SamplerWrap::Repeat;
break; break;
default: default:
@ -636,18 +641,51 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
return mesh; return mesh;
} }
namespace
{
const Nz::AnimationLoader::Entry* animationLoaderEntry = nullptr;
const Nz::MeshLoader::Entry* meshLoaderEntry = nullptr;
}
extern "C" extern "C"
{ {
NAZARA_EXPORT int PluginLoad() NAZARA_EXPORT int PluginLoad()
{ {
Nz::AnimationLoader::RegisterLoader(IsSupported, CheckAnimation, LoadAnimation); Nz::Utility* utility = Nz::Utility::Instance();
Nz::MeshLoader::RegisterLoader(IsSupported, CheckMesh, LoadMesh); NazaraAssert(utility, "utility module is not instancied");
Nz::AnimationLoader& animationLoader = utility->GetAnimationLoader();
animationLoaderEntry = animationLoader.RegisterLoader({
IsSupported,
nullptr,
nullptr,
CheckAnimation,
LoadAnimation
});
Nz::MeshLoader& meshLoader = utility->GetMeshLoader();
meshLoaderEntry = meshLoader.RegisterLoader({
IsSupported,
nullptr,
nullptr,
CheckMesh,
LoadMesh
});
return 1; return 1;
} }
NAZARA_EXPORT void PluginUnload() NAZARA_EXPORT void PluginUnload()
{ {
Nz::AnimationLoader::RegisterLoader(IsSupported, CheckAnimation, LoadAnimation); Nz::Utility* utility = Nz::Utility::Instance();
Nz::MeshLoader::UnregisterLoader(IsSupported, CheckMesh, LoadMesh); NazaraAssert(utility, "utility module is not instancied");
Nz::AnimationLoader& animationLoader = utility->GetAnimationLoader();
animationLoader.UnregisterLoader(animationLoaderEntry);
animationLoaderEntry = nullptr;
Nz::MeshLoader& meshLoader = utility->GetMeshLoader();
meshLoader.UnregisterLoader(meshLoaderEntry);
meshLoaderEntry = nullptr;
} }
} }

View File

@ -130,7 +130,7 @@ namespace Nz
for (auto& textureData : m_textures) for (auto& textureData : m_textures)
{ {
TextureInfo textureCreationParams; TextureInfo textureCreationParams;
textureCreationParams.type = ImageType_2D; textureCreationParams.type = ImageType::E2D;
textureCreationParams.width = textureData.width * width / 100'000; textureCreationParams.width = textureData.width * width / 100'000;
textureCreationParams.height = textureData.height * height / 100'000; textureCreationParams.height = textureData.height * height / 100'000;
textureCreationParams.usageFlags = textureData.usage; textureCreationParams.usageFlags = textureData.usage;

View File

@ -98,10 +98,10 @@ namespace Nz
bool BasicMaterial::Initialize() bool BasicMaterial::Initialize()
{ {
FieldOffsets fieldOffsets(StructLayout_Std140); FieldOffsets fieldOffsets(StructLayout::Std140);
s_uniformOffsets.alphaThreshold = fieldOffsets.AddField(StructFieldType_Float1); s_uniformOffsets.alphaThreshold = fieldOffsets.AddField(StructFieldType::Float1);
s_uniformOffsets.diffuseColor = fieldOffsets.AddField(StructFieldType_Float4); s_uniformOffsets.diffuseColor = fieldOffsets.AddField(StructFieldType::Float4);
s_uniformOffsets.totalSize = fieldOffsets.GetSize(); s_uniformOffsets.totalSize = fieldOffsets.GetSize();
MaterialSettings::Builder settings; MaterialSettings::Builder settings;
@ -129,21 +129,21 @@ namespace Nz
settings.textures.push_back({ settings.textures.push_back({
"MaterialAlphaMap", "MaterialAlphaMap",
"Alpha", "Alpha",
ImageType_2D ImageType::E2D
}); });
s_textureIndexes.diffuse = settings.textures.size(); s_textureIndexes.diffuse = settings.textures.size();
settings.textures.push_back({ settings.textures.push_back({
"MaterialDiffuseMap", "MaterialDiffuseMap",
"Diffuse", "Diffuse",
ImageType_2D ImageType::E2D
}); });
settings.predefinedBinding[UnderlyingCast(PredefinedShaderBinding::TexOverlay)] = settings.textures.size(); settings.predefinedBinding[UnderlyingCast(PredefinedShaderBinding::TexOverlay)] = settings.textures.size();
settings.textures.push_back({ settings.textures.push_back({
"TextureOverlay", "TextureOverlay",
"Overlay", "Overlay",
ImageType_2D ImageType::E2D
}); });
s_uniformBlockIndex = settings.uniformBlocks.size(); s_uniformBlockIndex = settings.uniformBlocks.size();

View File

@ -429,7 +429,7 @@ namespace Nz
{ {
auto& depthStencilAttachment = renderPassAttachments[colorAttachmentCount]; auto& depthStencilAttachment = renderPassAttachments[colorAttachmentCount];
if (PixelFormatInfo::GetContent(depthStencilAttachment.format) == PixelFormatContent_DepthStencil) if (PixelFormatInfo::GetContent(depthStencilAttachment.format) == PixelFormatContent::DepthStencil)
{ {
depthStencilAttachment.stencilLoadOp = depthStencilAttachment.loadOp; depthStencilAttachment.stencilLoadOp = depthStencilAttachment.loadOp;
depthStencilAttachment.stencilStoreOp = depthStencilAttachment.storeOp; depthStencilAttachment.stencilStoreOp = depthStencilAttachment.storeOp;

View File

@ -11,31 +11,31 @@
namespace Nz namespace Nz
{ {
GraphicalMesh::GraphicalMesh(const Mesh* mesh) GraphicalMesh::GraphicalMesh(const Mesh& mesh)
{ {
assert(mesh->GetAnimationType() == AnimationType_Static); assert(mesh.GetAnimationType() == AnimationType::Static);
const std::shared_ptr<RenderDevice>& renderDevice = Graphics::Instance()->GetRenderDevice(); const std::shared_ptr<RenderDevice>& renderDevice = Graphics::Instance()->GetRenderDevice();
m_subMeshes.reserve(mesh->GetSubMeshCount()); m_subMeshes.reserve(mesh.GetSubMeshCount());
for (std::size_t i = 0; i < mesh->GetSubMeshCount(); ++i) for (std::size_t i = 0; i < mesh.GetSubMeshCount(); ++i)
{ {
const SubMesh* subMesh = mesh->GetSubMesh(i); const SubMesh& subMesh = *mesh.GetSubMesh(i);
const StaticMesh* staticMesh = static_cast<const StaticMesh*>(subMesh); const StaticMesh& staticMesh = static_cast<const StaticMesh&>(subMesh);
const IndexBuffer* indexBuffer = staticMesh->GetIndexBuffer(); const std::shared_ptr<const IndexBuffer>& indexBuffer = staticMesh.GetIndexBuffer();
const VertexBuffer* vertexBuffer = staticMesh->GetVertexBuffer(); const std::shared_ptr<VertexBuffer>& vertexBuffer = staticMesh.GetVertexBuffer();
assert(indexBuffer->GetBuffer()->GetStorage() == DataStorage_Software); assert(indexBuffer->GetBuffer()->GetStorage() == DataStorage::Software);
const SoftwareBuffer* indexBufferContent = static_cast<const SoftwareBuffer*>(indexBuffer->GetBuffer()->GetImpl()); const SoftwareBuffer* indexBufferContent = static_cast<const SoftwareBuffer*>(indexBuffer->GetBuffer()->GetImpl());
assert(vertexBuffer->GetBuffer()->GetStorage() == DataStorage_Software); assert(vertexBuffer->GetBuffer()->GetStorage() == DataStorage::Software);
const SoftwareBuffer* vertexBufferContent = static_cast<const SoftwareBuffer*>(vertexBuffer->GetBuffer()->GetImpl()); const SoftwareBuffer* vertexBufferContent = static_cast<const SoftwareBuffer*>(vertexBuffer->GetBuffer()->GetImpl());
auto& submeshData = m_subMeshes.emplace_back(); auto& submeshData = m_subMeshes.emplace_back();
submeshData.indexBuffer = renderDevice->InstantiateBuffer(BufferType_Index); submeshData.indexBuffer = renderDevice->InstantiateBuffer(BufferType::Index);
if (!submeshData.indexBuffer->Initialize(indexBuffer->GetStride() * indexBuffer->GetIndexCount(), BufferUsage_DeviceLocal)) if (!submeshData.indexBuffer->Initialize(indexBuffer->GetStride() * indexBuffer->GetIndexCount(), BufferUsage::DeviceLocal))
throw std::runtime_error("failed to create index buffer"); throw std::runtime_error("failed to create index buffer");
if (!submeshData.indexBuffer->Fill(indexBufferContent->GetData() + indexBuffer->GetStartOffset(), 0, indexBuffer->GetEndOffset() - indexBuffer->GetStartOffset())) if (!submeshData.indexBuffer->Fill(indexBufferContent->GetData() + indexBuffer->GetStartOffset(), 0, indexBuffer->GetEndOffset() - indexBuffer->GetStartOffset()))
@ -43,8 +43,8 @@ namespace Nz
submeshData.indexCount = indexBuffer->GetIndexCount(); submeshData.indexCount = indexBuffer->GetIndexCount();
submeshData.vertexBuffer = renderDevice->InstantiateBuffer(BufferType_Vertex); submeshData.vertexBuffer = renderDevice->InstantiateBuffer(BufferType::Vertex);
if (!submeshData.vertexBuffer->Initialize(vertexBuffer->GetStride() * vertexBuffer->GetVertexCount(), BufferUsage_DeviceLocal)) if (!submeshData.vertexBuffer->Initialize(vertexBuffer->GetStride() * vertexBuffer->GetVertexCount(), BufferUsage::DeviceLocal))
throw std::runtime_error("failed to create vertex buffer"); throw std::runtime_error("failed to create vertex buffer");
if (!submeshData.vertexBuffer->Fill(vertexBufferContent->GetData() + vertexBuffer->GetStartOffset(), 0, vertexBuffer->GetEndOffset() - vertexBuffer->GetStartOffset())) if (!submeshData.vertexBuffer->Fill(vertexBufferContent->GetData() + vertexBuffer->GetStartOffset(), 0, vertexBuffer->GetEndOffset() - vertexBuffer->GetStartOffset()))

View File

@ -50,8 +50,8 @@ namespace Nz
Nz::PredefinedViewerData viewerUboOffsets = Nz::PredefinedViewerData::GetOffsets(); Nz::PredefinedViewerData viewerUboOffsets = Nz::PredefinedViewerData::GetOffsets();
m_viewerDataUBO = m_renderDevice->InstantiateBuffer(Nz::BufferType_Uniform); m_viewerDataUBO = m_renderDevice->InstantiateBuffer(Nz::BufferType::Uniform);
if (!m_viewerDataUBO->Initialize(viewerUboOffsets.totalSize, Nz::BufferUsage_DeviceLocal | Nz::BufferUsage_Dynamic)) if (!m_viewerDataUBO->Initialize(viewerUboOffsets.totalSize, Nz::BufferUsage::DeviceLocal | Nz::BufferUsage::Dynamic))
throw std::runtime_error("failed to initialize viewer data UBO"); throw std::runtime_error("failed to initialize viewer data UBO");
} }

View File

@ -43,8 +43,8 @@ namespace Nz
{ {
auto& uniformBuffer = m_uniformBuffers.emplace_back(); auto& uniformBuffer = m_uniformBuffers.emplace_back();
uniformBuffer.buffer = Graphics::Instance()->GetRenderDevice()->InstantiateBuffer(Nz::BufferType_Uniform); uniformBuffer.buffer = Graphics::Instance()->GetRenderDevice()->InstantiateBuffer(Nz::BufferType::Uniform);
if (!uniformBuffer.buffer->Initialize(uniformBufferInfo.blockSize, BufferUsage_Dynamic)) if (!uniformBuffer.buffer->Initialize(uniformBufferInfo.blockSize, BufferUsage::Dynamic))
throw std::runtime_error("failed to initialize UBO memory"); throw std::runtime_error("failed to initialize UBO memory");
assert(uniformBufferInfo.defaultValues.size() <= uniformBufferInfo.blockSize); assert(uniformBufferInfo.defaultValues.size() <= uniformBufferInfo.blockSize);

View File

@ -15,8 +15,8 @@ namespace Nz
{ {
Nz::PredefinedInstanceData instanceUboOffsets = Nz::PredefinedInstanceData::GetOffsets(); Nz::PredefinedInstanceData instanceUboOffsets = Nz::PredefinedInstanceData::GetOffsets();
m_instanceDataBuffer = Graphics::Instance()->GetRenderDevice()->InstantiateBuffer(BufferType_Uniform); m_instanceDataBuffer = Graphics::Instance()->GetRenderDevice()->InstantiateBuffer(BufferType::Uniform);
if (!m_instanceDataBuffer->Initialize(instanceUboOffsets.totalSize, Nz::BufferUsage_DeviceLocal | Nz::BufferUsage_Dynamic)) if (!m_instanceDataBuffer->Initialize(instanceUboOffsets.totalSize, Nz::BufferUsage::DeviceLocal | Nz::BufferUsage::Dynamic))
throw std::runtime_error("failed to initialize viewer data UBO"); throw std::runtime_error("failed to initialize viewer data UBO");
m_shaderBinding = settings->GetRenderPipelineLayout()->AllocateShaderBinding(); m_shaderBinding = settings->GetRenderPipelineLayout()->AllocateShaderBinding();

View File

@ -143,13 +143,13 @@ namespace Nz
bool PhongLightingMaterial::Initialize() bool PhongLightingMaterial::Initialize()
{ {
// MaterialPhongSettings // MaterialPhongSettings
FieldOffsets phongUniformStruct(StructLayout_Std140); FieldOffsets phongUniformStruct(StructLayout::Std140);
s_phongUniformOffsets.alphaThreshold = phongUniformStruct.AddField(StructFieldType_Float1); s_phongUniformOffsets.alphaThreshold = phongUniformStruct.AddField(StructFieldType::Float1);
s_phongUniformOffsets.shininess = phongUniformStruct.AddField(StructFieldType_Float1); s_phongUniformOffsets.shininess = phongUniformStruct.AddField(StructFieldType::Float1);
s_phongUniformOffsets.ambientColor = phongUniformStruct.AddField(StructFieldType_Float4); s_phongUniformOffsets.ambientColor = phongUniformStruct.AddField(StructFieldType::Float4);
s_phongUniformOffsets.diffuseColor = phongUniformStruct.AddField(StructFieldType_Float4); s_phongUniformOffsets.diffuseColor = phongUniformStruct.AddField(StructFieldType::Float4);
s_phongUniformOffsets.specularColor = phongUniformStruct.AddField(StructFieldType_Float4); s_phongUniformOffsets.specularColor = phongUniformStruct.AddField(StructFieldType::Float4);
MaterialSettings::Builder settings; MaterialSettings::Builder settings;
settings.predefinedBinding.fill(MaterialSettings::InvalidIndex); settings.predefinedBinding.fill(MaterialSettings::InvalidIndex);
@ -207,49 +207,49 @@ namespace Nz
settings.textures.push_back({ settings.textures.push_back({
"MaterialAlphaMap", "MaterialAlphaMap",
"Alpha", "Alpha",
ImageType_2D ImageType::E2D
}); });
s_textureIndexes.diffuse = settings.textures.size(); s_textureIndexes.diffuse = settings.textures.size();
settings.textures.push_back({ settings.textures.push_back({
"MaterialDiffuseMap", "MaterialDiffuseMap",
"Diffuse", "Diffuse",
ImageType_2D ImageType::E2D
}); });
s_textureIndexes.emissive = settings.textures.size(); s_textureIndexes.emissive = settings.textures.size();
settings.textures.push_back({ settings.textures.push_back({
"MaterialEmissiveMap", "MaterialEmissiveMap",
"Emissive", "Emissive",
ImageType_2D ImageType::E2D
}); });
s_textureIndexes.height = settings.textures.size(); s_textureIndexes.height = settings.textures.size();
settings.textures.push_back({ settings.textures.push_back({
"MaterialHeightMap", "MaterialHeightMap",
"Height", "Height",
ImageType_2D ImageType::E2D
}); });
s_textureIndexes.normal = settings.textures.size(); s_textureIndexes.normal = settings.textures.size();
settings.textures.push_back({ settings.textures.push_back({
"MaterialNormalMap", "MaterialNormalMap",
"Normal", "Normal",
ImageType_2D ImageType::E2D
}); });
s_textureIndexes.specular = settings.textures.size(); s_textureIndexes.specular = settings.textures.size();
settings.textures.push_back({ settings.textures.push_back({
"MaterialSpecularMap", "MaterialSpecularMap",
"Specular", "Specular",
ImageType_2D ImageType::E2D
}); });
settings.predefinedBinding[UnderlyingCast(PredefinedShaderBinding::TexOverlay)] = settings.textures.size(); settings.predefinedBinding[UnderlyingCast(PredefinedShaderBinding::TexOverlay)] = settings.textures.size();
settings.textures.push_back({ settings.textures.push_back({
"TextureOverlay", "TextureOverlay",
"Overlay", "Overlay",
ImageType_2D, ImageType::E2D,
}); });
s_materialSettings = std::make_shared<MaterialSettings>(std::move(settings)); s_materialSettings = std::make_shared<MaterialSettings>(std::move(settings));

View File

@ -12,18 +12,18 @@ namespace Nz
{ {
PredefinedLightData lightData; PredefinedLightData lightData;
FieldOffsets lightStruct(StructLayout_Std140); FieldOffsets lightStruct(StructLayout::Std140);
lightData.innerOffsets.type = lightStruct.AddField(StructFieldType_Int1); lightData.innerOffsets.type = lightStruct.AddField(StructFieldType::Int1);
lightData.innerOffsets.color = lightStruct.AddField(StructFieldType_Float4); lightData.innerOffsets.color = lightStruct.AddField(StructFieldType::Float4);
lightData.innerOffsets.factor = lightStruct.AddField(StructFieldType_Float2); lightData.innerOffsets.factor = lightStruct.AddField(StructFieldType::Float2);
lightData.innerOffsets.parameter1 = lightStruct.AddField(StructFieldType_Float4); lightData.innerOffsets.parameter1 = lightStruct.AddField(StructFieldType::Float4);
lightData.innerOffsets.parameter2 = lightStruct.AddField(StructFieldType_Float4); lightData.innerOffsets.parameter2 = lightStruct.AddField(StructFieldType::Float4);
lightData.innerOffsets.parameter3 = lightStruct.AddField(StructFieldType_Float2); lightData.innerOffsets.parameter3 = lightStruct.AddField(StructFieldType::Float2);
lightData.innerOffsets.shadowMappingFlag = lightStruct.AddField(StructFieldType_Bool1); lightData.innerOffsets.shadowMappingFlag = lightStruct.AddField(StructFieldType::Bool1);
lightData.innerOffsets.totalSize = lightStruct.GetAlignedSize(); lightData.innerOffsets.totalSize = lightStruct.GetAlignedSize();
FieldOffsets lightDataStruct(StructLayout_Std140); FieldOffsets lightDataStruct(StructLayout::Std140);
for (std::size_t& lightOffset : lightData.lightArray) for (std::size_t& lightOffset : lightData.lightArray)
lightOffset = lightDataStruct.AddStruct(lightStruct); lightOffset = lightDataStruct.AddStruct(lightStruct);
@ -56,11 +56,11 @@ namespace Nz
PredefinedInstanceData PredefinedInstanceData::GetOffsets() PredefinedInstanceData PredefinedInstanceData::GetOffsets()
{ {
FieldOffsets viewerStruct(StructLayout_Std140); FieldOffsets viewerStruct(StructLayout::Std140);
PredefinedInstanceData instanceData; PredefinedInstanceData instanceData;
instanceData.worldMatrixOffset = viewerStruct.AddMatrix(StructFieldType_Float1, 4, 4, true); instanceData.worldMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true);
instanceData.invWorldMatrixOffset = viewerStruct.AddMatrix(StructFieldType_Float1, 4, 4, true); instanceData.invWorldMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true);
instanceData.totalSize = viewerStruct.GetAlignedSize(); instanceData.totalSize = viewerStruct.GetAlignedSize();
@ -94,18 +94,18 @@ namespace Nz
PredefinedViewerData PredefinedViewerData::GetOffsets() PredefinedViewerData PredefinedViewerData::GetOffsets()
{ {
FieldOffsets viewerStruct(StructLayout_Std140); FieldOffsets viewerStruct(StructLayout::Std140);
PredefinedViewerData viewerData; PredefinedViewerData viewerData;
viewerData.projMatrixOffset = viewerStruct.AddMatrix(StructFieldType_Float1, 4, 4, true); viewerData.projMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true);
viewerData.invProjMatrixOffset = viewerStruct.AddMatrix(StructFieldType_Float1, 4, 4, true); viewerData.invProjMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true);
viewerData.viewMatrixOffset = viewerStruct.AddMatrix(StructFieldType_Float1, 4, 4, true); viewerData.viewMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true);
viewerData.invViewMatrixOffset = viewerStruct.AddMatrix(StructFieldType_Float1, 4, 4, true); viewerData.invViewMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true);
viewerData.viewProjMatrixOffset = viewerStruct.AddMatrix(StructFieldType_Float1, 4, 4, true); viewerData.viewProjMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true);
viewerData.invViewProjMatrixOffset = viewerStruct.AddMatrix(StructFieldType_Float1, 4, 4, true); viewerData.invViewProjMatrixOffset = viewerStruct.AddMatrix(StructFieldType::Float1, 4, 4, true);
viewerData.targetSizeOffset = viewerStruct.AddField(StructFieldType_Float2); viewerData.targetSizeOffset = viewerStruct.AddField(StructFieldType::Float2);
viewerData.invTargetSizeOffset = viewerStruct.AddField(StructFieldType_Float2); viewerData.invTargetSizeOffset = viewerStruct.AddField(StructFieldType::Float2);
viewerData.eyePositionOffset = viewerStruct.AddField(StructFieldType_Float3); viewerData.eyePositionOffset = viewerStruct.AddField(StructFieldType::Float3);
viewerData.totalSize = viewerStruct.GetAlignedSize(); viewerData.totalSize = viewerStruct.GetAlignedSize();

View File

@ -31,9 +31,9 @@ namespace Nz
GL::BufferTarget target; GL::BufferTarget target;
switch (m_type) switch (m_type)
{ {
case BufferType_Index: target = GL::BufferTarget::ElementArray; break; case BufferType::Index: target = GL::BufferTarget::ElementArray; break;
case BufferType_Uniform: target = GL::BufferTarget::Uniform; break; case BufferType::Uniform: target = GL::BufferTarget::Uniform; break;
case BufferType_Vertex: target = GL::BufferTarget::Array; break; case BufferType::Vertex: target = GL::BufferTarget::Array; break;
default: default:
throw std::runtime_error("unknown buffer type 0x" + NumberToString(UnderlyingCast(m_type), 16)); throw std::runtime_error("unknown buffer type 0x" + NumberToString(UnderlyingCast(m_type), 16));
@ -41,12 +41,12 @@ namespace Nz
GLenum hint = GL_STREAM_COPY; GLenum hint = GL_STREAM_COPY;
if (usage & BufferUsage_Dynamic) if (usage & BufferUsage::Dynamic)
hint = GL_DYNAMIC_DRAW; hint = GL_DYNAMIC_DRAW;
else if (usage & BufferUsage_DeviceLocal) else if (usage & BufferUsage::DeviceLocal)
hint = GL_STATIC_DRAW; hint = GL_STATIC_DRAW;
if (usage & BufferUsage_DirectMapping) if (usage & BufferUsage::DirectMapping)
hint = GL_DYNAMIC_COPY; hint = GL_DYNAMIC_COPY;
m_buffer.Reset(target, size, nullptr, hint); m_buffer.Reset(target, size, nullptr, hint);
@ -60,7 +60,7 @@ namespace Nz
DataStorage OpenGLBuffer::GetStorage() const DataStorage OpenGLBuffer::GetStorage() const
{ {
return DataStorage_Hardware; return DataStorage::Hardware;
} }
void* OpenGLBuffer::Map(BufferAccess access, UInt64 offset, UInt64 size) void* OpenGLBuffer::Map(BufferAccess access, UInt64 offset, UInt64 size)
@ -68,7 +68,7 @@ namespace Nz
GLbitfield accessBit = 0; GLbitfield accessBit = 0;
switch (access) switch (access)
{ {
case BufferAccess_DiscardAndWrite: case BufferAccess::DiscardAndWrite:
accessBit |= GL_MAP_WRITE_BIT; accessBit |= GL_MAP_WRITE_BIT;
if (offset == 0 && size == m_size) if (offset == 0 && size == m_size)
accessBit |= GL_MAP_INVALIDATE_BUFFER_BIT; accessBit |= GL_MAP_INVALIDATE_BUFFER_BIT;
@ -77,15 +77,15 @@ namespace Nz
break; break;
case BufferAccess_ReadOnly: case BufferAccess::ReadOnly:
accessBit |= GL_MAP_READ_BIT; accessBit |= GL_MAP_READ_BIT;
break; break;
case BufferAccess_ReadWrite: case BufferAccess::ReadWrite:
accessBit |= GL_MAP_READ_BIT | GL_MAP_WRITE_BIT; accessBit |= GL_MAP_READ_BIT | GL_MAP_WRITE_BIT;
break; break;
case BufferAccess_WriteOnly: case BufferAccess::WriteOnly:
accessBit |= GL_MAP_WRITE_BIT; accessBit |= GL_MAP_WRITE_BIT;
break; break;

View File

@ -18,39 +18,39 @@ namespace Nz
{ {
switch (component) switch (component)
{ {
case ComponentType_Color: case ComponentType::Color:
attrib.normalized = GL_TRUE; attrib.normalized = GL_TRUE;
attrib.size = 4; attrib.size = 4;
attrib.type = GL_UNSIGNED_BYTE; attrib.type = GL_UNSIGNED_BYTE;
return; return;
case ComponentType_Float1: case ComponentType::Float1:
case ComponentType_Float2: case ComponentType::Float2:
case ComponentType_Float3: case ComponentType::Float3:
case ComponentType_Float4: case ComponentType::Float4:
attrib.normalized = GL_FALSE; attrib.normalized = GL_FALSE;
attrib.size = (component - ComponentType_Float1 + 1); attrib.size = (UnderlyingCast(component) - UnderlyingCast(ComponentType::Float1) + 1);
attrib.type = GL_FLOAT; attrib.type = GL_FLOAT;
return; return;
case ComponentType_Int1: case ComponentType::Int1:
case ComponentType_Int2: case ComponentType::Int2:
case ComponentType_Int3: case ComponentType::Int3:
case ComponentType_Int4: case ComponentType::Int4:
attrib.normalized = GL_FALSE; attrib.normalized = GL_FALSE;
attrib.size = (component - ComponentType_Int1 + 1); attrib.size = (UnderlyingCast(component) - UnderlyingCast(ComponentType::Int1) + 1);
attrib.type = GL_INT; attrib.type = GL_INT;
return; return;
case ComponentType_Double1: case ComponentType::Double1:
case ComponentType_Double2: case ComponentType::Double2:
case ComponentType_Double3: case ComponentType::Double3:
case ComponentType_Double4: case ComponentType::Double4:
case ComponentType_Quaternion: case ComponentType::Quaternion:
break; break;
} }
throw std::runtime_error("component type 0x" + NumberToString(component, 16) + " is not handled"); throw std::runtime_error("component type 0x" + NumberToString(UnderlyingCast(component), 16) + " is not handled");
} }
} }

View File

@ -30,12 +30,12 @@ namespace Nz
GLenum attachment; GLenum attachment;
switch (PixelFormatInfo::GetContent(textureFormat)) switch (PixelFormatInfo::GetContent(textureFormat))
{ {
case PixelFormatContent_ColorRGBA: case PixelFormatContent::ColorRGBA:
attachment = static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + colorAttachmentCount); attachment = static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + colorAttachmentCount);
colorAttachmentCount++; colorAttachmentCount++;
break; break;
case PixelFormatContent_Depth: case PixelFormatContent::Depth:
if (hasDepth) if (hasDepth)
throw std::runtime_error("a framebuffer can only have one depth attachment"); throw std::runtime_error("a framebuffer can only have one depth attachment");
@ -43,7 +43,7 @@ namespace Nz
hasDepth = true; hasDepth = true;
break; break;
case PixelFormatContent_DepthStencil: case PixelFormatContent::DepthStencil:
if (hasDepth) if (hasDepth)
throw std::runtime_error("a framebuffer can only have one depth attachment"); throw std::runtime_error("a framebuffer can only have one depth attachment");
@ -55,7 +55,7 @@ namespace Nz
hasStencil = true; hasStencil = true;
break; break;
case PixelFormatContent_Stencil: case PixelFormatContent::Stencil:
if (hasStencil) if (hasStencil)
throw std::runtime_error("a framebuffer can only have one stencil attachment"); throw std::runtime_error("a framebuffer can only have one stencil attachment");
@ -63,7 +63,7 @@ namespace Nz
hasStencil = true; hasStencil = true;
break; break;
case PixelFormatContent_Undefined: case PixelFormatContent::Undefined:
default: default:
throw std::runtime_error("unhandled pixel format " + PixelFormatInfo::GetName(textureFormat)); throw std::runtime_error("unhandled pixel format " + PixelFormatInfo::GetName(textureFormat));
} }

View File

@ -105,7 +105,7 @@ namespace Nz
if (OpenGLBuffer* glBuffer = static_cast<OpenGLBuffer*>(uboBinding.buffer)) if (OpenGLBuffer* glBuffer = static_cast<OpenGLBuffer*>(uboBinding.buffer))
{ {
if (glBuffer->GetType() != BufferType_Uniform) if (glBuffer->GetType() != BufferType::Uniform)
throw std::runtime_error("expected uniform buffer"); throw std::runtime_error("expected uniform buffer");
uboDescriptor.buffer = glBuffer->GetBuffer().GetObjectId(); uboDescriptor.buffer = glBuffer->GetBuffer().GetObjectId();

View File

@ -22,23 +22,23 @@ namespace Nz
switch (params.type) switch (params.type)
{ {
case ImageType_1D: case ImageType::E1D:
break; break;
case ImageType_1D_Array: case ImageType::E1D_Array:
break; break;
case ImageType_2D: case ImageType::E2D:
m_texture.TexStorage2D(params.mipmapLevel, format->internalFormat, params.width, params.height); m_texture.TexStorage2D(params.mipmapLevel, format->internalFormat, params.width, params.height);
break; break;
case ImageType_2D_Array: case ImageType::E2D_Array:
break; break;
case ImageType_3D: case ImageType::E3D:
break; break;
case ImageType_Cubemap: case ImageType::Cubemap:
break; break;
default: default:
@ -79,23 +79,23 @@ namespace Nz
switch (m_params.type) switch (m_params.type)
{ {
case ImageType_1D: case ImageType::E1D:
break; break;
case ImageType_1D_Array: case ImageType::E1D_Array:
break; break;
case ImageType_2D: case ImageType::E2D:
m_texture.TexSubImage2D(0, 0, 0, m_params.width, m_params.height, format->format, format->type, ptr); m_texture.TexSubImage2D(0, 0, 0, m_params.width, m_params.height, format->format, format->type, ptr);
break; break;
case ImageType_2D_Array: case ImageType::E2D_Array:
break; break;
case ImageType_3D: case ImageType::E3D:
break; break;
case ImageType_Cubemap: case ImageType::Cubemap:
break; break;
default: default:

View File

@ -236,12 +236,12 @@ namespace Nz
switch (samplerType.dim) switch (samplerType.dim)
{ {
case ImageType_1D: Append("1D"); break; case ImageType::E1D: Append("1D"); break;
case ImageType_1D_Array: Append("1DArray"); break; case ImageType::E1D_Array: Append("1DArray"); break;
case ImageType_2D: Append("2D"); break; case ImageType::E2D: Append("2D"); break;
case ImageType_2D_Array: Append("2DArray"); break; case ImageType::E2D_Array: Append("2DArray"); break;
case ImageType_3D: Append("3D"); break; case ImageType::E3D: Append("3D"); break;
case ImageType_Cubemap: Append("Cube"); break; case ImageType::Cubemap: Append("Cube"); break;
} }
} }
@ -795,7 +795,7 @@ namespace Nz
std::size_t structIndex = std::get<ShaderAst::StructType>(uniform.containedType).structIndex; std::size_t structIndex = std::get<ShaderAst::StructType>(uniform.containedType).structIndex;
auto& structInfo = Retrieve(m_currentState->structs, structIndex); auto& structInfo = Retrieve(m_currentState->structs, structIndex);
isStd140 = structInfo.layout == StructLayout_Std140; isStd140 = structInfo.layout == StructLayout::Std140;
} }
if (externalVar.bindingIndex) if (externalVar.bindingIndex)

View File

@ -147,12 +147,12 @@ namespace Nz
switch (samplerType.dim) switch (samplerType.dim)
{ {
case ImageType_1D: Append("1D"); break; case ImageType::E1D: Append("1D"); break;
case ImageType_1D_Array: Append("1DArray"); break; case ImageType::E1D_Array: Append("1DArray"); break;
case ImageType_2D: Append("2D"); break; case ImageType::E2D: Append("2D"); break;
case ImageType_2D_Array: Append("2DArray"); break; case ImageType::E2D_Array: Append("2DArray"); break;
case ImageType_3D: Append("3D"); break; case ImageType::E3D: Append("3D"); break;
case ImageType_Cubemap: Append("Cube"); break; case ImageType::Cubemap: Append("Cube"); break;
} }
Append("<", samplerType.sampledType, ">"); Append("<", samplerType.sampledType, ">");
@ -261,7 +261,7 @@ namespace Nz
switch (*entry.layout) switch (*entry.layout)
{ {
case StructLayout_Std140: case StructLayout::Std140:
Append("layout(std140)"); Append("layout(std140)");
break; break;
} }

View File

@ -38,7 +38,7 @@ namespace Nz::ShaderLang
}; };
std::unordered_map<std::string, StructLayout> s_layoutMapping = { std::unordered_map<std::string, StructLayout> s_layoutMapping = {
{ "std140", StructLayout_Std140 } { "std140", StructLayout::Std140 }
}; };
template<typename T, typename U> template<typename T, typename U>
@ -157,7 +157,7 @@ namespace Nz::ShaderLang
Consume(); Consume();
ShaderAst::SamplerType samplerType; ShaderAst::SamplerType samplerType;
samplerType.dim = ImageType_2D; samplerType.dim = ImageType::E2D;
Expect(Advance(), TokenType::LessThan); //< '<' Expect(Advance(), TokenType::LessThan); //< '<'
samplerType.sampledType = ParsePrimitiveType(); samplerType.sampledType = ParsePrimitiveType();

View File

@ -846,7 +846,7 @@ namespace Nz
annotations.Append(SpirvOp::OpDecorate, resultId, SpirvDecoration::Block); annotations.Append(SpirvOp::OpDecorate, resultId, SpirvDecoration::Block);
FieldOffsets structOffsets(StructLayout_Std140); FieldOffsets structOffsets(StructLayout::Std140);
for (std::size_t memberIndex = 0; memberIndex < structData.members.size(); ++memberIndex) for (std::size_t memberIndex = 0; memberIndex < structData.members.size(); ++memberIndex)
{ {
@ -858,18 +858,18 @@ namespace Nz
using T = std::decay_t<decltype(arg)>; using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, Bool>) if constexpr (std::is_same_v<T, Bool>)
return structOffsets.AddField(StructFieldType_Bool1); return structOffsets.AddField(StructFieldType::Bool1);
else if constexpr (std::is_same_v<T, Float>) else if constexpr (std::is_same_v<T, Float>)
{ {
switch (arg.width) switch (arg.width)
{ {
case 32: return structOffsets.AddField(StructFieldType_Float1); case 32: return structOffsets.AddField(StructFieldType::Float1);
case 64: return structOffsets.AddField(StructFieldType_Double1); case 64: return structOffsets.AddField(StructFieldType::Double1);
default: throw std::runtime_error("unexpected float width " + std::to_string(arg.width)); default: throw std::runtime_error("unexpected float width " + std::to_string(arg.width));
} }
} }
else if constexpr (std::is_same_v<T, Integer>) else if constexpr (std::is_same_v<T, Integer>)
return structOffsets.AddField((arg.signedness) ? StructFieldType_Int1 : StructFieldType_UInt1); return structOffsets.AddField((arg.signedness) ? StructFieldType::Int1 : StructFieldType::UInt1);
else if constexpr (std::is_same_v<T, Matrix>) else if constexpr (std::is_same_v<T, Matrix>)
{ {
assert(std::holds_alternative<Vector>(arg.columnType->type)); assert(std::holds_alternative<Vector>(arg.columnType->type));
@ -883,8 +883,8 @@ namespace Nz
StructFieldType columnType; StructFieldType columnType;
switch (vecType.width) switch (vecType.width)
{ {
case 32: columnType = StructFieldType_Float1; break; case 32: columnType = StructFieldType::Float1; break;
case 64: columnType = StructFieldType_Double1; break; case 64: columnType = StructFieldType::Double1; break;
default: throw std::runtime_error("unexpected float width " + std::to_string(vecType.width)); default: throw std::runtime_error("unexpected float width " + std::to_string(vecType.width));
} }
@ -905,14 +905,14 @@ namespace Nz
else if constexpr (std::is_same_v<T, Vector>) else if constexpr (std::is_same_v<T, Vector>)
{ {
if (std::holds_alternative<Bool>(arg.componentType->type)) if (std::holds_alternative<Bool>(arg.componentType->type))
return structOffsets.AddField(static_cast<StructFieldType>(StructFieldType_Bool1 + arg.componentCount - 1)); return structOffsets.AddField(static_cast<StructFieldType>(UnderlyingCast(StructFieldType::Bool1) + arg.componentCount - 1));
else if (std::holds_alternative<Float>(arg.componentType->type)) else if (std::holds_alternative<Float>(arg.componentType->type))
{ {
Float& floatData = std::get<Float>(arg.componentType->type); Float& floatData = std::get<Float>(arg.componentType->type);
switch (floatData.width) switch (floatData.width)
{ {
case 32: return structOffsets.AddField(static_cast<StructFieldType>(StructFieldType_Float1 + arg.componentCount - 1)); case 32: return structOffsets.AddField(static_cast<StructFieldType>(UnderlyingCast(StructFieldType::Float1) + arg.componentCount - 1));
case 64: return structOffsets.AddField(static_cast<StructFieldType>(StructFieldType_Double1 + arg.componentCount - 1)); case 64: return structOffsets.AddField(static_cast<StructFieldType>(UnderlyingCast(StructFieldType::Double1) + arg.componentCount - 1));
default: throw std::runtime_error("unexpected float width " + std::to_string(floatData.width)); default: throw std::runtime_error("unexpected float width " + std::to_string(floatData.width));
} }
} }
@ -923,9 +923,9 @@ namespace Nz
throw std::runtime_error("unexpected integer width " + std::to_string(intData.width)); throw std::runtime_error("unexpected integer width " + std::to_string(intData.width));
if (intData.signedness) if (intData.signedness)
return structOffsets.AddField(static_cast<StructFieldType>(StructFieldType_Int1 + arg.componentCount - 1)); return structOffsets.AddField(static_cast<StructFieldType>(UnderlyingCast(StructFieldType::Int1) + arg.componentCount - 1));
else else
return structOffsets.AddField(static_cast<StructFieldType>(StructFieldType_UInt1 + arg.componentCount - 1)); return structOffsets.AddField(static_cast<StructFieldType>(UnderlyingCast(StructFieldType::UInt1) + arg.componentCount - 1));
} }
else else
throw std::runtime_error("unexpected type for vector"); throw std::runtime_error("unexpected type for vector");

View File

@ -22,6 +22,6 @@ namespace Nz
bool AbstractImage::IsCubemap() const bool AbstractImage::IsCubemap() const
{ {
return GetType() == ImageType_Cubemap; return GetType() == ImageType::Cubemap;
} }
} }

View File

@ -8,6 +8,7 @@
#include <Nazara/Utility/Joint.hpp> #include <Nazara/Utility/Joint.hpp>
#include <Nazara/Utility/Sequence.hpp> #include <Nazara/Utility/Sequence.hpp>
#include <Nazara/Utility/Skeleton.hpp> #include <Nazara/Utility/Skeleton.hpp>
#include <Nazara/Utility/Utility.hpp>
#include <vector> #include <vector>
#include <unordered_map> #include <unordered_map>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
@ -36,19 +37,16 @@ namespace Nz
return true; return true;
} }
Animation::~Animation() Animation::Animation() = default;
{ Animation::Animation(Animation&&) noexcept = default;
OnAnimationRelease(this); Animation::~Animation() = default;
Destroy();
}
bool Animation::AddSequence(const Sequence& sequence) bool Animation::AddSequence(const Sequence& sequence)
{ {
NazaraAssert(m_impl, "Animation not created"); NazaraAssert(m_impl, "Animation not created");
NazaraAssert(sequence.frameCount > 0, "Sequence frame count must be over zero"); NazaraAssert(sequence.frameCount > 0, "Sequence frame count must be over zero");
if (m_impl->type == AnimationType_Skeletal) if (m_impl->type == AnimationType::Skeletal)
{ {
std::size_t endFrame = sequence.firstFrame + sequence.frameCount - 1; std::size_t endFrame = sequence.firstFrame + sequence.frameCount - 1;
if (endFrame >= m_impl->frameCount) if (endFrame >= m_impl->frameCount)
@ -80,7 +78,7 @@ namespace Nz
void Animation::AnimateSkeleton(Skeleton* targetSkeleton, std::size_t frameA, std::size_t frameB, float interpolation) const void Animation::AnimateSkeleton(Skeleton* targetSkeleton, std::size_t frameA, std::size_t frameB, float interpolation) const
{ {
NazaraAssert(m_impl, "Animation not created"); NazaraAssert(m_impl, "Animation not created");
NazaraAssert(m_impl->type == AnimationType_Skeletal, "Animation is not skeletal"); NazaraAssert(m_impl->type == AnimationType::Skeletal, "Animation is not skeletal");
NazaraAssert(targetSkeleton && targetSkeleton->IsValid(), "Invalid skeleton"); NazaraAssert(targetSkeleton && targetSkeleton->IsValid(), "Invalid skeleton");
NazaraAssert(targetSkeleton->GetJointCount() == m_impl->jointCount, "Skeleton joint does not match animation joint count"); NazaraAssert(targetSkeleton->GetJointCount() == m_impl->jointCount, "Skeleton joint does not match animation joint count");
NazaraAssert(frameA < m_impl->frameCount, "FrameA is out of range"); NazaraAssert(frameA < m_impl->frameCount, "FrameA is out of range");
@ -106,24 +104,18 @@ namespace Nz
Destroy(); Destroy();
m_impl = new AnimationImpl; m_impl = std::make_unique<AnimationImpl>();
m_impl->frameCount = frameCount; m_impl->frameCount = frameCount;
m_impl->jointCount = jointCount; m_impl->jointCount = jointCount;
m_impl->sequenceJoints.resize(frameCount*jointCount); m_impl->sequenceJoints.resize(frameCount*jointCount);
m_impl->type = AnimationType_Skeletal; m_impl->type = AnimationType::Skeletal;
return true; return true;
} }
void Animation::Destroy() void Animation::Destroy()
{ {
if (m_impl) m_impl.reset();
{
OnAnimationDestroy(this);
delete m_impl;
m_impl = nullptr;
}
} }
void Animation::EnableLoopPointInterpolation(bool loopPointInterpolation) void Animation::EnableLoopPointInterpolation(bool loopPointInterpolation)
@ -215,7 +207,7 @@ namespace Nz
SequenceJoint* Animation::GetSequenceJoints(std::size_t frameIndex) SequenceJoint* Animation::GetSequenceJoints(std::size_t frameIndex)
{ {
NazaraAssert(m_impl, "Animation not created"); NazaraAssert(m_impl, "Animation not created");
NazaraAssert(m_impl->type == AnimationType_Skeletal, "Animation is not skeletal"); NazaraAssert(m_impl->type == AnimationType::Skeletal, "Animation is not skeletal");
return &m_impl->sequenceJoints[frameIndex*m_impl->jointCount]; return &m_impl->sequenceJoints[frameIndex*m_impl->jointCount];
} }
@ -223,7 +215,7 @@ namespace Nz
const SequenceJoint* Animation::GetSequenceJoints(std::size_t frameIndex) const const SequenceJoint* Animation::GetSequenceJoints(std::size_t frameIndex) const
{ {
NazaraAssert(m_impl, "Animation not created"); NazaraAssert(m_impl, "Animation not created");
NazaraAssert(m_impl->type == AnimationType_Skeletal, "Animation is not skeletal"); NazaraAssert(m_impl->type == AnimationType::Skeletal, "Animation is not skeletal");
return &m_impl->sequenceJoints[frameIndex*m_impl->jointCount]; return &m_impl->sequenceJoints[frameIndex*m_impl->jointCount];
} }
@ -289,46 +281,29 @@ namespace Nz
m_impl->sequences.erase(it); m_impl->sequences.erase(it);
} }
AnimationRef Animation::LoadFromFile(const std::filesystem::path& filePath, const AnimationParams& params) Animation& Animation::operator=(Animation&&) noexcept = default;
std::shared_ptr<Animation> Animation::LoadFromFile(const std::filesystem::path& filePath, const AnimationParams& params)
{ {
return AnimationLoader::LoadFromFile(filePath, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetAnimationLoader().LoadFromFile(filePath, params);
} }
AnimationRef Animation::LoadFromMemory(const void* data, std::size_t size, const AnimationParams& params) std::shared_ptr<Animation> Animation::LoadFromMemory(const void* data, std::size_t size, const AnimationParams& params)
{ {
return AnimationLoader::LoadFromMemory(data, size, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetAnimationLoader().LoadFromMemory(data, size, params);
} }
AnimationRef Animation::LoadFromStream(Stream& stream, const AnimationParams& params) std::shared_ptr<Animation> Animation::LoadFromStream(Stream& stream, const AnimationParams& params)
{ {
return AnimationLoader::LoadFromStream(stream, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetAnimationLoader().LoadFromStream(stream, params);
} }
bool Animation::Initialize()
{
if (!AnimationLibrary::Initialize())
{
NazaraError("Failed to initialise library");
return false;
}
if (!AnimationManager::Initialize())
{
NazaraError("Failed to initialise manager");
return false;
}
return true;
}
void Animation::Uninitialize()
{
AnimationManager::Uninitialize();
AnimationLibrary::Uninitialize();
}
AnimationLibrary::LibraryMap Animation::s_library;
AnimationLoader::LoaderList Animation::s_loaders;
AnimationManager::ManagerMap Animation::s_managerMap;
AnimationManager::ManagerParams Animation::s_managerParameters;
} }

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Buffer.hpp> #include <Nazara/Utility/Buffer.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/CallOnExit.hpp> #include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/Core/ErrorFlags.hpp>
@ -29,20 +30,13 @@ namespace Nz
Create(size, storage, usage); Create(size, storage, usage);
} }
Buffer::~Buffer() bool Buffer::CopyContent(const Buffer& buffer)
{
OnBufferRelease(this);
Destroy();
}
bool Buffer::CopyContent(const BufferRef& buffer)
{ {
NazaraAssert(m_impl, "Invalid buffer"); NazaraAssert(m_impl, "Invalid buffer");
NazaraAssert(!buffer && !buffer->IsValid(), "Invalid source buffer"); NazaraAssert(buffer.IsValid(), "Invalid source buffer");
BufferMapper<Buffer> mapper(*buffer, BufferAccess_ReadOnly); BufferMapper<Buffer> mapper(buffer, BufferAccess::ReadOnly);
return Fill(mapper.GetPointer(), 0, buffer->GetSize()); return Fill(mapper.GetPointer(), 0, buffer.GetSize());
} }
bool Buffer::Create(UInt32 size, DataStorage storage, BufferUsageFlags usage) bool Buffer::Create(UInt32 size, DataStorage storage, BufferUsageFlags usage)
@ -56,7 +50,7 @@ namespace Nz
return false; return false;
} }
std::unique_ptr<AbstractBuffer> impl(s_bufferFactories[storage](this, m_type)); std::unique_ptr<AbstractBuffer> impl = s_bufferFactories[UnderlyingCast(storage)](this, m_type);
if (!impl->Initialize(size, usage)) if (!impl->Initialize(size, usage))
{ {
NazaraError("Failed to create buffer"); NazaraError("Failed to create buffer");
@ -72,12 +66,7 @@ namespace Nz
void Buffer::Destroy() void Buffer::Destroy()
{ {
if (m_impl) m_impl.reset();
{
OnBufferDestroy(this);
m_impl.reset();
}
} }
bool Buffer::Fill(const void* data, UInt32 offset, UInt32 size) bool Buffer::Fill(const void* data, UInt32 offset, UInt32 size)
@ -99,7 +88,7 @@ namespace Nz
void* Buffer::Map(BufferAccess access, UInt32 offset, UInt32 size) const void* Buffer::Map(BufferAccess access, UInt32 offset, UInt32 size) const
{ {
NazaraAssert(m_impl, "Invalid buffer"); NazaraAssert(m_impl, "Invalid buffer");
NazaraAssert(access == BufferAccess_ReadOnly, "Buffer access must be read-only when used const"); NazaraAssert(access == BufferAccess::ReadOnly, "Buffer access must be read-only when used const");
NazaraAssert(offset + size <= m_size, "Exceeding buffer size"); NazaraAssert(offset + size <= m_size, "Exceeding buffer size");
return m_impl->Map(access, offset, (size == 0) ? m_size - offset : size); return m_impl->Map(access, offset, (size == 0) ? m_size - offset : size);
@ -118,7 +107,7 @@ namespace Nz
return false; return false;
} }
void* ptr = m_impl->Map(BufferAccess_ReadOnly, 0, m_size); void* ptr = m_impl->Map(BufferAccess::ReadOnly, 0, m_size);
if (!ptr) if (!ptr)
{ {
NazaraError("Failed to map buffer"); NazaraError("Failed to map buffer");
@ -130,7 +119,7 @@ namespace Nz
m_impl->Unmap(); m_impl->Unmap();
}); });
std::unique_ptr<AbstractBuffer> impl(s_bufferFactories[storage](this, m_type)); std::unique_ptr<AbstractBuffer> impl(s_bufferFactories[UnderlyingCast(storage)](this, m_type));
if (!impl->Initialize(m_size, m_usage)) if (!impl->Initialize(m_size, m_usage))
{ {
NazaraError("Failed to create buffer"); NazaraError("Failed to create buffer");
@ -160,19 +149,19 @@ namespace Nz
bool Buffer::IsStorageSupported(DataStorage storage) bool Buffer::IsStorageSupported(DataStorage storage)
{ {
return s_bufferFactories[storage] != nullptr; return s_bufferFactories[UnderlyingCast(storage)] != nullptr;
} }
void Buffer::SetBufferFactory(DataStorage storage, BufferFactory func) void Buffer::SetBufferFactory(DataStorage storage, BufferFactory func)
{ {
s_bufferFactories[storage] = func; s_bufferFactories[UnderlyingCast(storage)] = func;
} }
bool Buffer::Initialize() bool Buffer::Initialize()
{ {
SetBufferFactory(DataStorage_Software, [](Buffer* parent, BufferType type) -> AbstractBuffer* SetBufferFactory(DataStorage::Software, [](Buffer* parent, BufferType type) -> std::unique_ptr<AbstractBuffer>
{ {
return new SoftwareBuffer(parent, type); return std::make_unique<SoftwareBuffer>(parent, type);
}); });
return true; return true;
@ -183,5 +172,5 @@ namespace Nz
std::fill(s_bufferFactories.begin(), s_bufferFactories.end(), nullptr); std::fill(s_bufferFactories.begin(), s_bufferFactories.end(), nullptr);
} }
std::array<Buffer::BufferFactory, DataStorage_Max + 1> Buffer::s_bufferFactories; std::array<Buffer::BufferFactory, DataStorageCount> Buffer::s_bufferFactories;
} }

View File

@ -26,8 +26,8 @@ namespace Nz
std::size_t FieldOffsets::AddFieldArray(StructFieldType type, std::size_t arraySize) std::size_t FieldOffsets::AddFieldArray(StructFieldType type, std::size_t arraySize)
{ {
std::size_t fieldAlignement = GetAlignement(m_layout, type); std::size_t fieldAlignement = GetAlignement(m_layout, type);
if (m_layout == StructLayout_Std140) if (m_layout == StructLayout::Std140)
fieldAlignement = Align(fieldAlignement, GetAlignement(StructLayout_Std140, StructFieldType_Float4)); fieldAlignement = Align(fieldAlignement, GetAlignement(StructLayout::Std140, StructFieldType::Float4));
m_largestFieldAlignment = std::max(fieldAlignement, m_largestFieldAlignment); m_largestFieldAlignment = std::max(fieldAlignement, m_largestFieldAlignment);
@ -46,9 +46,9 @@ namespace Nz
assert(rows >= 2 && rows <= 4); assert(rows >= 2 && rows <= 4);
if (columnMajor) if (columnMajor)
return AddFieldArray(static_cast<StructFieldType>(cellType + rows - 1), columns); return AddFieldArray(static_cast<StructFieldType>(UnderlyingCast(cellType) + rows - 1), columns);
else else
return AddFieldArray(static_cast<StructFieldType>(cellType + columns - 1), rows); return AddFieldArray(static_cast<StructFieldType>(UnderlyingCast(cellType) + columns - 1), rows);
} }
std::size_t FieldOffsets::AddMatrixArray(StructFieldType cellType, unsigned int columns, unsigned int rows, bool columnMajor, std::size_t arraySize) std::size_t FieldOffsets::AddMatrixArray(StructFieldType cellType, unsigned int columns, unsigned int rows, bool columnMajor, std::size_t arraySize)
@ -58,16 +58,16 @@ namespace Nz
assert(rows >= 2 && rows <= 4); assert(rows >= 2 && rows <= 4);
if (columnMajor) if (columnMajor)
return AddFieldArray(static_cast<StructFieldType>(cellType + rows - 1), columns * arraySize); return AddFieldArray(static_cast<StructFieldType>(UnderlyingCast(cellType) + rows - 1), columns * arraySize);
else else
return AddFieldArray(static_cast<StructFieldType>(cellType + columns - 1), rows * arraySize); return AddFieldArray(static_cast<StructFieldType>(UnderlyingCast(cellType) + columns - 1), rows * arraySize);
} }
std::size_t FieldOffsets::AddStruct(const FieldOffsets& fieldStruct) std::size_t FieldOffsets::AddStruct(const FieldOffsets& fieldStruct)
{ {
std::size_t fieldAlignement = fieldStruct.GetLargestFieldAlignement(); std::size_t fieldAlignement = fieldStruct.GetLargestFieldAlignement();
if (m_layout == StructLayout_Std140) if (m_layout == StructLayout::Std140)
fieldAlignement = Align(fieldAlignement, GetAlignement(StructLayout_Std140, StructFieldType_Float4)); fieldAlignement = Align(fieldAlignement, GetAlignement(StructLayout::Std140, StructFieldType::Float4));
m_largestFieldAlignment = std::max(m_largestFieldAlignment, fieldAlignement); m_largestFieldAlignment = std::max(m_largestFieldAlignment, fieldAlignement);
@ -84,8 +84,8 @@ namespace Nz
assert(arraySize > 0); assert(arraySize > 0);
std::size_t fieldAlignement = fieldStruct.GetLargestFieldAlignement(); std::size_t fieldAlignement = fieldStruct.GetLargestFieldAlignement();
if (m_layout == StructLayout_Std140) if (m_layout == StructLayout::Std140)
fieldAlignement = Align(fieldAlignement, GetAlignement(StructLayout_Std140, StructFieldType_Float4)); fieldAlignement = Align(fieldAlignement, GetAlignement(StructLayout::Std140, StructFieldType::Float4));
m_largestFieldAlignment = std::max(m_largestFieldAlignment, fieldAlignement); m_largestFieldAlignment = std::max(m_largestFieldAlignment, fieldAlignement);

View File

@ -8,6 +8,7 @@
#include <Nazara/Utility/FontData.hpp> #include <Nazara/Utility/FontData.hpp>
#include <Nazara/Utility/FontGlyph.hpp> #include <Nazara/Utility/FontGlyph.hpp>
#include <Nazara/Utility/GuillotineImageAtlas.hpp> #include <Nazara/Utility/GuillotineImageAtlas.hpp>
#include <Nazara/Utility/Utility.hpp>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
namespace Nz namespace Nz
@ -329,7 +330,7 @@ namespace Nz
return s_defaultAtlas; return s_defaultAtlas;
} }
const FontRef& Font::GetDefault() const std::shared_ptr<Font>& Font::GetDefault()
{ {
// Nous n'initialisons la police par défaut qu'à la demande pour qu'elle prenne // Nous n'initialisons la police par défaut qu'à la demande pour qu'elle prenne
// les paramètres par défaut (qui peuvent avoir étés changés par l'utilisateur), // les paramètres par défaut (qui peuvent avoir étés changés par l'utilisateur),
@ -355,19 +356,28 @@ namespace Nz
return s_defaultMinimumStepSize; return s_defaultMinimumStepSize;
} }
FontRef Font::OpenFromFile(const std::filesystem::path& filePath, const FontParams& params) std::shared_ptr<Font> Font::OpenFromFile(const std::filesystem::path& filePath, const FontParams& params)
{ {
return FontLoader::LoadFromFile(filePath, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetFontLoader().LoadFromFile(filePath, params);
} }
FontRef Font::OpenFromMemory(const void* data, std::size_t size, const FontParams& params) std::shared_ptr<Font> Font::OpenFromMemory(const void* data, std::size_t size, const FontParams& params)
{ {
return FontLoader::LoadFromMemory(data, size, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetFontLoader().LoadFromMemory(data, size, params);
} }
FontRef Font::OpenFromStream(Stream& stream, const FontParams& params) std::shared_ptr<Font> Font::OpenFromStream(Stream& stream, const FontParams& params)
{ {
return FontLoader::LoadFromStream(stream, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetFontLoader().LoadFromStream(stream, params);
} }
void Font::SetDefaultAtlas(const std::shared_ptr<AbstractAtlas>& atlas) void Font::SetDefaultAtlas(const std::shared_ptr<AbstractAtlas>& atlas)
@ -401,10 +411,10 @@ namespace Nz
sizeStylePart <<= 2; sizeStylePart <<= 2;
// Store bold and italic flags (other style are handled directly by a TextDrawer) // Store bold and italic flags (other style are handled directly by a TextDrawer)
if (style & TextStyle_Bold) if (style & TextStyle::Bold)
sizeStylePart |= 1 << 0; sizeStylePart |= 1 << 0;
if (style & TextStyle_Italic) if (style & TextStyle::Italic)
sizeStylePart |= 1 << 1; sizeStylePart |= 1 << 1;
return (sizeStylePart << 32) | reinterpret_cast<Nz::UInt32&>(outlineThickness); return (sizeStylePart << 32) | reinterpret_cast<Nz::UInt32&>(outlineThickness);
@ -488,16 +498,16 @@ namespace Nz
glyph.requireFauxItalic = false; glyph.requireFauxItalic = false;
TextStyleFlags supportedStyle = style; TextStyleFlags supportedStyle = style;
if (style & TextStyle_Bold && !m_data->SupportsStyle(TextStyle_Bold)) if (style & TextStyle::Bold && !m_data->SupportsStyle(TextStyle::Bold))
{ {
glyph.requireFauxBold = true; glyph.requireFauxBold = true;
supportedStyle &= ~TextStyle_Bold; supportedStyle &= ~TextStyle::Bold;
} }
if (style & TextStyle_Italic && !m_data->SupportsStyle(TextStyle_Italic)) if (style & TextStyle::Italic && !m_data->SupportsStyle(TextStyle::Italic))
{ {
glyph.requireFauxItalic = true; glyph.requireFauxItalic = true;
supportedStyle &= ~TextStyle_Italic; supportedStyle &= ~TextStyle::Italic;
} }
float supportedOutlineThickness = outlineThickness; float supportedOutlineThickness = outlineThickness;
@ -572,13 +582,7 @@ namespace Nz
bool Font::Initialize() bool Font::Initialize()
{ {
if (!FontLibrary::Initialize()) s_defaultAtlas = std::make_shared<GuillotineImageAtlas>();
{
NazaraError("Failed to initialise library");
return false;
}
s_defaultAtlas.reset(new GuillotineImageAtlas);
s_defaultGlyphBorder = 1; s_defaultGlyphBorder = 1;
s_defaultMinimumStepSize = 1; s_defaultMinimumStepSize = 1;
@ -588,14 +592,11 @@ namespace Nz
void Font::Uninitialize() void Font::Uninitialize()
{ {
s_defaultAtlas.reset(); s_defaultAtlas.reset();
s_defaultFont.Reset(); s_defaultFont.reset();
FontLibrary::Uninitialize();
} }
std::shared_ptr<AbstractAtlas> Font::s_defaultAtlas; std::shared_ptr<AbstractAtlas> Font::s_defaultAtlas;
FontRef Font::s_defaultFont; std::shared_ptr<Font> Font::s_defaultFont;
FontLibrary::LibraryMap Font::s_library;
FontLoader::LoaderList Font::s_loaders;
unsigned int Font::s_defaultGlyphBorder; unsigned int Font::s_defaultGlyphBorder;
unsigned int Font::s_defaultMinimumStepSize; unsigned int Font::s_defaultMinimumStepSize;
} }

View File

@ -18,7 +18,7 @@ namespace Nz
DDSLoader() = delete; DDSLoader() = delete;
~DDSLoader() = delete; ~DDSLoader() = delete;
static bool IsSupported(const std::string& extension) static bool IsSupported(const std::string_view& extension)
{ {
return (extension == "dds"); return (extension == "dds");
} }
@ -38,7 +38,7 @@ namespace Nz
return (magic == DDS_Magic) ? Ternary::True : Ternary::False; return (magic == DDS_Magic) ? Ternary::True : Ternary::False;
} }
static ImageRef Load(Stream& stream, const ImageParams& parameters) static std::shared_ptr<Image> Load(Stream& stream, const ImageParams& parameters)
{ {
NazaraUnused(parameters); NazaraUnused(parameters);
@ -88,7 +88,7 @@ namespace Nz
if (!IdentifyPixelFormat(header, headerDX10, &format)) if (!IdentifyPixelFormat(header, headerDX10, &format))
return nullptr; return nullptr;
ImageRef image = Image::New(type, format, width, height, depth, levelCount); std::shared_ptr<Image> image = std::make_shared<Image>(type, format, width, height, depth, levelCount);
// Read all mipmap levels // Read all mipmap levels
for (unsigned int i = 0; i < image->GetLevelCount(); i++) for (unsigned int i = 0; i < image->GetLevelCount(); i++)
@ -114,7 +114,7 @@ namespace Nz
} }
if (parameters.loadFormat != PixelFormat_Undefined) if (parameters.loadFormat != PixelFormat::Undefined)
image->Convert(parameters.loadFormat); image->Convert(parameters.loadFormat);
return image; return image;
@ -131,9 +131,9 @@ namespace Nz
return false; return false;
} }
else if (header.flags & DDSD_HEIGHT) else if (header.flags & DDSD_HEIGHT)
*type = ImageType_2D_Array; *type = ImageType::E2D_Array;
else else
*type = ImageType_1D_Array; *type = ImageType::E1D_Array;
} }
else else
{ {
@ -145,7 +145,7 @@ namespace Nz
return false; return false;
} }
*type = ImageType_Cubemap; *type = ImageType::Cubemap;
} }
else if (headerExt.resourceDimension == D3D10_RESOURCE_DIMENSION_BUFFER) else if (headerExt.resourceDimension == D3D10_RESOURCE_DIMENSION_BUFFER)
{ {
@ -153,11 +153,11 @@ namespace Nz
return false; return false;
} }
else if (headerExt.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE1D) else if (headerExt.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE1D)
*type = ImageType_1D; *type = ImageType::E1D;
else if (header.ddsCaps[1] & DDSCAPS2_VOLUME || header.flags & DDSD_DEPTH || headerExt.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE3D) else if (header.ddsCaps[1] & DDSCAPS2_VOLUME || header.flags & DDSD_DEPTH || headerExt.resourceDimension == D3D10_RESOURCE_DIMENSION_TEXTURE3D)
*type = ImageType_3D; *type = ImageType::E3D;
else else
*type = ImageType_2D; *type = ImageType::E2D;
} }
return true; return true;
@ -167,7 +167,7 @@ namespace Nz
{ {
if (header.format.flags & (DDPF_RGB | DDPF_ALPHA | DDPF_ALPHAPIXELS | DDPF_LUMINANCE)) if (header.format.flags & (DDPF_RGB | DDPF_ALPHA | DDPF_ALPHAPIXELS | DDPF_LUMINANCE))
{ {
PixelFormatDescription info(PixelFormatContent_ColorRGBA, header.format.bpp, PixelFormatSubType_Unsigned); PixelFormatDescription info(PixelFormatContent::ColorRGBA, header.format.bpp, PixelFormatSubType::Unsigned);
if (header.format.flags & DDPF_RGB) if (header.format.flags & DDPF_RGB)
{ {
@ -191,15 +191,15 @@ namespace Nz
switch (header.format.fourCC) switch (header.format.fourCC)
{ {
case D3DFMT_DXT1: case D3DFMT_DXT1:
*format = PixelFormat_DXT1; *format = PixelFormat::DXT1;
break; break;
case D3DFMT_DXT3: case D3DFMT_DXT3:
*format = PixelFormat_DXT3; *format = PixelFormat::DXT3;
break; break;
case D3DFMT_DXT5: case D3DFMT_DXT5:
*format = PixelFormat_DXT3; *format = PixelFormat::DXT3;
break; break;
case D3DFMT_DX10: case D3DFMT_DX10:
@ -207,30 +207,35 @@ namespace Nz
switch (headerExt.dxgiFormat) switch (headerExt.dxgiFormat)
{ {
case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32A32_FLOAT:
*format = PixelFormat_RGBA32F; *format = PixelFormat::RGBA32F;
break; break;
case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_UINT:
*format = PixelFormat_RGBA32UI; *format = PixelFormat::RGBA32UI;
break; break;
case DXGI_FORMAT_R32G32B32A32_SINT: case DXGI_FORMAT_R32G32B32A32_SINT:
*format = PixelFormat_RGBA32I; *format = PixelFormat::RGBA32I;
break; break;
case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R32G32B32_FLOAT:
*format = PixelFormat_RGB32F; *format = PixelFormat::RGB32F;
break; break;
case DXGI_FORMAT_R32G32B32_UINT: case DXGI_FORMAT_R32G32B32_UINT:
//*format = PixelFormat_RGB32U; //*format = PixelFormat::RGB32U;
return false; return false;
case DXGI_FORMAT_R32G32B32_SINT: case DXGI_FORMAT_R32G32B32_SINT:
*format = PixelFormat_RGB32I; *format = PixelFormat::RGB32I;
break; break;
case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R16G16B16A16_SNORM:
case DXGI_FORMAT_R16G16B16A16_SINT: case DXGI_FORMAT_R16G16B16A16_SINT:
case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_UINT:
*format = PixelFormat_RGBA16I; *format = PixelFormat::RGBA16I;
break; break;
case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_UNORM:
*format = PixelFormat_RGBA16UI; *format = PixelFormat::RGBA16UI;
break;
default:
//TODO
NazaraError("TODO");
break; break;
} }
break; break;
@ -262,14 +267,14 @@ namespace Nz
namespace Loaders namespace Loaders
{ {
void RegisterDDSLoader() ImageLoader::Entry GetImageLoader_DDS()
{ {
ImageLoader::RegisterLoader(DDSLoader::IsSupported, DDSLoader::Check, DDSLoader::Load); ImageLoader::Entry loaderEntry;
} loaderEntry.extensionSupport = DDSLoader::IsSupported;
loaderEntry.streamChecker = DDSLoader::Check;
loaderEntry.streamLoader = DDSLoader::Load;
void UnregisterDDSLoader() return loaderEntry;
{
ImageLoader::UnregisterLoader(DDSLoader::IsSupported, DDSLoader::Check, DDSLoader::Load);
} }
} }
} }

View File

@ -8,14 +8,11 @@
#define NAZARA_LOADERS_DDS_HPP #define NAZARA_LOADERS_DDS_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Image.hpp>
namespace Nz namespace Nz::Loaders
{ {
namespace Loaders ImageLoader::Entry GetImageLoader_DDS();
{
void RegisterDDSLoader();
void UnregisterDDSLoader();
}
} }
#endif // NAZARA_LOADERS_DDS_HPP #endif // NAZARA_LOADERS_DDS_HPP

View File

@ -145,7 +145,7 @@ namespace Nz
const FT_Pos boldStrength = 2 << 6; const FT_Pos boldStrength = 2 << 6;
bool embolden = (style & TextStyle_Bold) != 0; bool embolden = (style & TextStyle::Bold) != 0;
bool hasOutlineFormat = (glyph->format == FT_GLYPH_FORMAT_OUTLINE); bool hasOutlineFormat = (glyph->format == FT_GLYPH_FORMAT_OUTLINE);
dst->advance = (embolden) ? boldStrength >> 6 : 0; dst->advance = (embolden) ? boldStrength >> 6 : 0;
@ -202,7 +202,7 @@ namespace Nz
if (width > 0 && height > 0) if (width > 0 && height > 0)
{ {
dst->image.Create(ImageType_2D, PixelFormat_A8, width, height); dst->image.Create(ImageType::E2D, PixelFormat::A8, width, height);
UInt8* pixels = dst->image.GetPixels(); UInt8* pixels = dst->image.GetPixels();
const UInt8* data = bitmap.buffer; const UInt8* data = bitmap.buffer;
@ -363,7 +363,7 @@ namespace Nz
bool SupportsStyle(TextStyleFlags style) const override bool SupportsStyle(TextStyleFlags style) const override
{ {
///TODO ///TODO
return style == TextStyle_Regular || style == TextStyle_Bold; return style == TextStyle_Regular || style == TextStyle::Bold;
} }
private: private:
@ -384,10 +384,10 @@ namespace Nz
mutable unsigned int m_characterSize; mutable unsigned int m_characterSize;
}; };
bool IsSupported(const std::string& extension) bool IsSupported(const std::string_view& extension)
{ {
///FIXME: Je suppose qu'il en manque quelques unes.. ///FIXME: Je suppose qu'il en manque quelques unes..
static std::set<std::string> supportedExtensions = { static std::set<std::string_view> supportedExtensions = {
"afm", "bdf", "cff", "cid", "dfont", "fnt", "fon", "otf", "pfa", "pfb", "pfm", "pfr", "sfnt", "ttc", "tte", "ttf" "afm", "bdf", "cff", "cid", "dfont", "fnt", "fon", "otf", "pfa", "pfb", "pfm", "pfr", "sfnt", "ttc", "tte", "ttf"
}; };
@ -409,7 +409,7 @@ namespace Nz
return Ternary::False; return Ternary::False;
} }
FontRef LoadFile(const std::filesystem::path& filePath, const FontParams& parameters) std::shared_ptr<Font> LoadFile(const std::filesystem::path& filePath, const FontParams& parameters)
{ {
NazaraUnused(parameters); NazaraUnused(parameters);
@ -426,7 +426,7 @@ namespace Nz
return nullptr; return nullptr;
} }
FontRef font = Font::New(); std::shared_ptr<Font> font = std::make_shared<Font>();
if (font->Create(face.get())) if (font->Create(face.get()))
{ {
face.release(); face.release();
@ -436,7 +436,7 @@ namespace Nz
return nullptr; return nullptr;
} }
FontRef LoadMemory(const void* data, std::size_t size, const FontParams& parameters) std::shared_ptr<Font> LoadMemory(const void* data, std::size_t size, const FontParams& parameters)
{ {
NazaraUnused(parameters); NazaraUnused(parameters);
@ -449,7 +449,7 @@ namespace Nz
return nullptr; return nullptr;
} }
FontRef font = Font::New(); std::shared_ptr<Font> font = std::make_shared<Font>();
if (font->Create(face.get())) if (font->Create(face.get()))
{ {
face.release(); face.release();
@ -459,7 +459,7 @@ namespace Nz
return nullptr; return nullptr;
} }
FontRef LoadStream(Stream& stream, const FontParams& parameters) std::shared_ptr<Font> LoadStream(Stream& stream, const FontParams& parameters)
{ {
NazaraUnused(parameters); NazaraUnused(parameters);
@ -472,7 +472,7 @@ namespace Nz
return nullptr; return nullptr;
} }
FontRef font = Font::New(); std::shared_ptr<Font> font = std::make_shared<Font>();
if (font->Create(face.get())) if (font->Create(face.get()))
{ {
face.release(); face.release();
@ -485,27 +485,36 @@ namespace Nz
namespace Loaders namespace Loaders
{ {
void RegisterFreeType() bool InitializeFreeType()
{ {
if (FT_Init_FreeType(&s_library) == 0) NazaraAssert(!s_libraryOwner, "double initialization for FreeType");
if (FT_Init_FreeType(&s_library) != 0)
{ {
s_libraryOwner = std::make_shared<FreeTypeLibrary>(); NazaraWarning("failed to initialize FreeType library");
FontLoader::RegisterLoader(IsSupported, Check, LoadStream, LoadFile, LoadMemory); return false;
}
else
{
s_library = nullptr; // On s'assure que le pointeur ne pointe pas sur n'importe quoi
NazaraWarning("Failed to initialize FreeType library");
} }
s_libraryOwner = std::make_shared<FreeTypeLibrary>();
return true;
} }
void UnregisterFreeType() FontLoader::Entry GetFontLoader_FreeType()
{ {
if (s_library) NazaraAssert(s_libraryOwner, "FreeType has not been initialized");
{
FontLoader::UnregisterLoader(IsSupported, Check, LoadStream, LoadFile, LoadMemory); FontLoader::Entry entry;
s_libraryOwner.reset(); entry.extensionSupport = IsSupported;
} entry.fileLoader = LoadFile;
entry.memoryLoader = LoadMemory;
entry.streamChecker = Check;
entry.streamLoader = LoadStream;
return entry;
}
void UninitializeFreeType()
{
s_libraryOwner.reset();
} }
} }
} }

View File

@ -8,14 +8,13 @@
#define NAZARA_LOADERS_FREETYPE_HPP #define NAZARA_LOADERS_FREETYPE_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Font.hpp>
namespace Nz namespace Nz::Loaders
{ {
namespace Loaders bool InitializeFreeType();
{ FontLoader::Entry GetFontLoader_FreeType();
void RegisterFreeType(); void UninitializeFreeType();
void UnregisterFreeType();
}
} }
#endif // NAZARA_LOADERS_FREETYPE_HPP #endif // NAZARA_LOADERS_FREETYPE_HPP

View File

@ -20,7 +20,7 @@ namespace Nz
{ {
namespace namespace
{ {
bool IsSupported(const std::string& extension) bool IsSupported(const std::string_view& extension)
{ {
return (extension == "md2"); return (extension == "md2");
} }
@ -46,7 +46,7 @@ namespace Nz
return Ternary::False; return Ternary::False;
} }
MeshRef Load(Stream& stream, const MeshParams& parameters) std::shared_ptr<Mesh> Load(Stream& stream, const MeshParams& parameters)
{ {
MD2_Header header; MD2_Header header;
if (stream.Read(&header, sizeof(MD2_Header)) != sizeof(MD2_Header)) if (stream.Read(&header, sizeof(MD2_Header)) != sizeof(MD2_Header))
@ -80,7 +80,7 @@ namespace Nz
} }
// Since the engine no longer supports keyframe animations, let's make a static mesh // Since the engine no longer supports keyframe animations, let's make a static mesh
MeshRef mesh = Nz::Mesh::New(); std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
if (!mesh->CreateStatic()) if (!mesh->CreateStatic())
{ {
NazaraInternalError("Failed to create mesh"); NazaraInternalError("Failed to create mesh");
@ -107,7 +107,7 @@ namespace Nz
} }
} }
IndexBufferRef indexBuffer = IndexBuffer::New(false, header.num_tris*3, parameters.storage, parameters.indexBufferFlags); std::shared_ptr<IndexBuffer> indexBuffer = std::make_shared<IndexBuffer>(false, header.num_tris*3, parameters.storage, parameters.indexBufferFlags);
// Extract triangles data // Extract triangles data
std::vector<MD2_Triangle> triangles(header.num_tris); std::vector<MD2_Triangle> triangles(header.num_tris);
@ -116,7 +116,7 @@ namespace Nz
stream.Read(&triangles[0], header.num_tris*sizeof(MD2_Triangle)); stream.Read(&triangles[0], header.num_tris*sizeof(MD2_Triangle));
// And convert them into an index buffer // And convert them into an index buffer
BufferMapper<IndexBuffer> indexMapper(indexBuffer, BufferAccess_DiscardAndWrite); BufferMapper<IndexBuffer> indexMapper(*indexBuffer, BufferAccess::DiscardAndWrite);
UInt16* index = static_cast<UInt16*>(indexMapper.GetPointer()); UInt16* index = static_cast<UInt16*>(indexMapper.GetPointer());
for (unsigned int i = 0; i < header.num_tris; ++i) for (unsigned int i = 0; i < header.num_tris; ++i)
@ -158,8 +158,8 @@ namespace Nz
} }
#endif #endif
VertexBufferRef vertexBuffer = VertexBuffer::New(parameters.vertexDeclaration, header.num_vertices, parameters.storage, parameters.vertexBufferFlags); std::shared_ptr<VertexBuffer> vertexBuffer = std::make_shared<VertexBuffer>(parameters.vertexDeclaration, header.num_vertices, parameters.storage, parameters.vertexBufferFlags);
StaticMeshRef subMesh = StaticMesh::New(vertexBuffer, indexBuffer); std::shared_ptr<StaticMesh> subMesh = std::make_shared<StaticMesh>(vertexBuffer, indexBuffer);
// Extracting vertices // Extracting vertices
stream.SetCursorPos(header.offset_frames); stream.SetCursorPos(header.offset_frames);
@ -186,10 +186,10 @@ namespace Nz
scale *= ScaleAdjust; scale *= ScaleAdjust;
translate *= ScaleAdjust; translate *= ScaleAdjust;
VertexMapper vertexMapper(vertexBuffer, BufferAccess_DiscardAndWrite); VertexMapper vertexMapper(*vertexBuffer, BufferAccess::DiscardAndWrite);
// Loading texture coordinates // Loading texture coordinates
if (auto uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord)) if (auto uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord))
{ {
const unsigned int indexFix[3] = {0, 2, 1}; const unsigned int indexFix[3] = {0, 2, 1};
@ -214,7 +214,7 @@ namespace Nz
Nz::Matrix4f matrix = Matrix4f::Transform(translate, rotationQuat, scale); Nz::Matrix4f matrix = Matrix4f::Transform(translate, rotationQuat, scale);
matrix *= parameters.matrix; matrix *= parameters.matrix;
if (auto normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Normal)) if (auto normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Normal))
{ {
Nz::Matrix4f normalMatrix = Matrix4f::Rotate(rotationQuat); Nz::Matrix4f normalMatrix = Matrix4f::Rotate(rotationQuat);
normalMatrix *= parameters.matrix; normalMatrix *= parameters.matrix;
@ -227,7 +227,7 @@ namespace Nz
} }
} }
auto posPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); auto posPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
assert(posPtr); assert(posPtr);
for (unsigned int v = 0; v < header.num_vertices; ++v) for (unsigned int v = 0; v < header.num_vertices; ++v)
@ -244,7 +244,7 @@ namespace Nz
subMesh->GenerateAABB(); subMesh->GenerateAABB();
if (parameters.vertexDeclaration->HasComponentOfType<Vector3f>(VertexComponent_Tangent)) if (parameters.vertexDeclaration->HasComponentOfType<Vector3f>(VertexComponent::Tangent))
subMesh->GenerateTangents(); subMesh->GenerateTangents();
mesh->AddSubMesh(subMesh); mesh->AddSubMesh(subMesh);
@ -258,14 +258,14 @@ namespace Nz
namespace Loaders namespace Loaders
{ {
void RegisterMD2() MeshLoader::Entry GetMeshLoader_MD2()
{ {
MeshLoader::RegisterLoader(IsSupported, Check, Load); MeshLoader::Entry loader;
} loader.extensionSupport = IsSupported;
loader.streamChecker = Check;
loader.streamLoader = Load;
void UnregisterMD2() return loader;
{
MeshLoader::UnregisterLoader(IsSupported, Check, Load);
} }
} }
} }

View File

@ -8,14 +8,11 @@
#define NAZARA_LOADERS_MD2_HPP #define NAZARA_LOADERS_MD2_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Mesh.hpp>
namespace Nz namespace Nz::Loaders
{ {
namespace Loaders MeshLoader::Entry GetMeshLoader_MD2();
{
void RegisterMD2();
void UnregisterMD2();
}
} }
#endif // NAZARA_LOADERS_MD2_HPP #endif // NAZARA_LOADERS_MD2_HPP

View File

@ -12,7 +12,7 @@ namespace Nz
{ {
namespace namespace
{ {
bool IsSupported(const std::string& extension) bool IsSupported(const std::string_view& extension)
{ {
return (extension == "md5anim"); return (extension == "md5anim");
} }
@ -27,7 +27,7 @@ namespace Nz
return parser.Check(); return parser.Check();
} }
AnimationRef Load(Stream& stream, const AnimationParams& /*parameters*/) std::shared_ptr<Animation> Load(Stream& stream, const AnimationParams& /*parameters*/)
{ {
///TODO: Utiliser les paramètres ///TODO: Utiliser les paramètres
MD5AnimParser parser(stream); MD5AnimParser parser(stream);
@ -45,7 +45,7 @@ namespace Nz
std::size_t jointCount = parser.GetJointCount(); std::size_t jointCount = parser.GetJointCount();
// À ce stade, nous sommes censés avoir assez d'informations pour créer l'animation // À ce stade, nous sommes censés avoir assez d'informations pour créer l'animation
AnimationRef animation = Animation::New(); std::shared_ptr<Animation> animation = std::make_shared<Animation>();
animation->CreateSkeletal(frameCount, jointCount); animation->CreateSkeletal(frameCount, jointCount);
Sequence sequence; Sequence sequence;
@ -90,14 +90,14 @@ namespace Nz
namespace Loaders namespace Loaders
{ {
void RegisterMD5Anim() AnimationLoader::Entry GetAnimationLoader_MD5Anim()
{ {
AnimationLoader::RegisterLoader(IsSupported, Check, Load); AnimationLoader::Entry loader;
} loader.extensionSupport = IsSupported;
loader.streamChecker = Check;
loader.streamLoader = Load;
void UnregisterMD5Anim() return loader;
{
AnimationLoader::UnregisterLoader(IsSupported, Check, Load);
} }
} }
} }

View File

@ -8,14 +8,11 @@
#define NAZARA_LOADERS_MD5ANIM_HPP #define NAZARA_LOADERS_MD5ANIM_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Animation.hpp>
namespace Nz namespace Nz::Loaders
{ {
namespace Loaders AnimationLoader::Entry GetAnimationLoader_MD5Anim();
{
void RegisterMD5Anim();
void UnregisterMD5Anim();
}
} }
#endif // NAZARA_LOADERS_MD5ANIM_HPP #endif // NAZARA_LOADERS_MD5ANIM_HPP

View File

@ -20,7 +20,7 @@ namespace Nz
{ {
namespace namespace
{ {
bool IsSupported(const std::string& extension) bool IsSupported(const std::string_view& extension)
{ {
return (extension == "md5mesh"); return (extension == "md5mesh");
} }
@ -35,7 +35,7 @@ namespace Nz
return parser.Check(); return parser.Check();
} }
MeshRef Load(Stream& stream, const MeshParams& parameters) std::shared_ptr<Mesh> Load(Stream& stream, const MeshParams& parameters)
{ {
MD5MeshParser parser(stream); MD5MeshParser parser(stream);
if (!parser.Parse()) if (!parser.Parse())
@ -62,7 +62,7 @@ namespace Nz
if (parameters.animated) if (parameters.animated)
{ {
MeshRef mesh = Mesh::New(); std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
mesh->CreateSkeletal(jointCount); mesh->CreateSkeletal(jointCount);
Skeleton* skeleton = mesh->GetSkeleton(); Skeleton* skeleton = mesh->GetSkeleton();
@ -96,11 +96,11 @@ namespace Nz
bool largeIndices = (vertexCount > std::numeric_limits<UInt16>::max()); bool largeIndices = (vertexCount > std::numeric_limits<UInt16>::max());
IndexBufferRef indexBuffer = IndexBuffer::New(largeIndices, UInt32(indexCount), parameters.storage, parameters.indexBufferFlags); std::shared_ptr<IndexBuffer> indexBuffer = std::make_shared<IndexBuffer>(largeIndices, UInt32(indexCount), parameters.storage, parameters.indexBufferFlags);
VertexBufferRef vertexBuffer = VertexBuffer::New(VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent_Skinning), UInt32(vertexCount), parameters.storage, parameters.vertexBufferFlags); std::shared_ptr<VertexBuffer> vertexBuffer = std::make_shared<VertexBuffer>(VertexDeclaration::Get(VertexLayout::XYZ_Normal_UV_Tangent_Skinning), UInt32(vertexCount), parameters.storage, parameters.vertexBufferFlags);
// Index buffer // Index buffer
IndexMapper indexMapper(indexBuffer, BufferAccess_DiscardAndWrite); IndexMapper indexMapper(*indexBuffer, BufferAccess::DiscardAndWrite);
// Le format définit un set de triangles nous permettant de retrouver facilement les indices // Le format définit un set de triangles nous permettant de retrouver facilement les indices
// Cependant les sommets des triangles ne sont pas spécifiés dans le même ordre que ceux du moteur // Cependant les sommets des triangles ne sont pas spécifiés dans le même ordre que ceux du moteur
@ -128,7 +128,7 @@ namespace Nz
std::vector<Weight> tempWeights; std::vector<Weight> tempWeights;
BufferMapper<VertexBuffer> vertexMapper(vertexBuffer, BufferAccess_WriteOnly); BufferMapper<VertexBuffer> vertexMapper(*vertexBuffer, BufferAccess::WriteOnly);
SkeletalMeshVertex* vertices = static_cast<SkeletalMeshVertex*>(vertexMapper.GetPointer()); SkeletalMeshVertex* vertices = static_cast<SkeletalMeshVertex*>(vertexMapper.GetPointer());
for (const MD5MeshParser::Vertex& vertex : md5Mesh.vertices) for (const MD5MeshParser::Vertex& vertex : md5Mesh.vertices)
@ -203,7 +203,7 @@ namespace Nz
mesh->SetMaterialData(i, std::move(matData)); mesh->SetMaterialData(i, std::move(matData));
// Submesh // Submesh
SkeletalMeshRef subMesh = SkeletalMesh::New(vertexBuffer, indexBuffer); std::shared_ptr<SkeletalMesh> subMesh = std::make_shared<SkeletalMesh>(vertexBuffer, indexBuffer);
subMesh->GenerateNormalsAndTangents(); subMesh->GenerateNormalsAndTangents();
subMesh->SetMaterialIndex(i); subMesh->SetMaterialIndex(i);
@ -224,7 +224,7 @@ namespace Nz
} }
else else
{ {
MeshRef mesh = Mesh::New(); std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
if (!mesh->CreateStatic()) // Ne devrait jamais échouer if (!mesh->CreateStatic()) // Ne devrait jamais échouer
{ {
NazaraInternalError("Failed to create mesh"); NazaraInternalError("Failed to create mesh");
@ -241,9 +241,9 @@ namespace Nz
// Index buffer // Index buffer
bool largeIndices = (vertexCount > std::numeric_limits<UInt16>::max()); bool largeIndices = (vertexCount > std::numeric_limits<UInt16>::max());
IndexBufferRef indexBuffer = IndexBuffer::New(largeIndices, UInt32(indexCount), parameters.storage, parameters.indexBufferFlags); std::shared_ptr<IndexBuffer> indexBuffer = std::make_shared<IndexBuffer>(largeIndices, UInt32(indexCount), parameters.storage, parameters.indexBufferFlags);
IndexMapper indexMapper(indexBuffer, BufferAccess_DiscardAndWrite); IndexMapper indexMapper(*indexBuffer, BufferAccess::DiscardAndWrite);
IndexIterator index = indexMapper.begin(); IndexIterator index = indexMapper.begin();
for (const MD5MeshParser::Triangle& triangle : md5Mesh.triangles) for (const MD5MeshParser::Triangle& triangle : md5Mesh.triangles)
@ -259,11 +259,11 @@ namespace Nz
indexBuffer->Optimize(); indexBuffer->Optimize();
// Vertex buffer // Vertex buffer
VertexBufferRef vertexBuffer = VertexBuffer::New(parameters.vertexDeclaration, UInt32(vertexCount), parameters.storage, parameters.vertexBufferFlags); std::shared_ptr<VertexBuffer> vertexBuffer = std::make_shared<VertexBuffer>(parameters.vertexDeclaration, UInt32(vertexCount), parameters.storage, parameters.vertexBufferFlags);
VertexMapper vertexMapper(vertexBuffer, BufferAccess_DiscardAndWrite); VertexMapper vertexMapper(*vertexBuffer, BufferAccess::DiscardAndWrite);
auto posPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); auto posPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
for (const MD5MeshParser::Vertex& md5Vertex : md5Mesh.vertices) for (const MD5MeshParser::Vertex& md5Vertex : md5Mesh.vertices)
{ {
@ -281,7 +281,7 @@ namespace Nz
*posPtr++ = matrix * finalPos; *posPtr++ = matrix * finalPos;
} }
if (auto uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord)) if (auto uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord))
{ {
for (const MD5MeshParser::Vertex& md5Vertex : md5Mesh.vertices) for (const MD5MeshParser::Vertex& md5Vertex : md5Mesh.vertices)
*uvPtr++ = parameters.texCoordOffset + md5Vertex.uv * parameters.texCoordScale; *uvPtr++ = parameters.texCoordOffset + md5Vertex.uv * parameters.texCoordScale;
@ -290,13 +290,13 @@ namespace Nz
vertexMapper.Unmap(); vertexMapper.Unmap();
// Submesh // Submesh
StaticMeshRef subMesh = StaticMesh::New(vertexBuffer, indexBuffer); std::shared_ptr<StaticMesh> subMesh = std::make_shared<StaticMesh>(vertexBuffer, indexBuffer);
subMesh->GenerateAABB(); subMesh->GenerateAABB();
subMesh->SetMaterialIndex(i); subMesh->SetMaterialIndex(i);
if (parameters.vertexDeclaration->HasComponentOfType<Vector3f>(VertexComponent_Normal)) if (parameters.vertexDeclaration->HasComponentOfType<Vector3f>(VertexComponent::Normal))
{ {
if (parameters.vertexDeclaration->HasComponentOfType<Vector3f>(VertexComponent_Tangent)) if (parameters.vertexDeclaration->HasComponentOfType<Vector3f>(VertexComponent::Tangent))
subMesh->GenerateNormalsAndTangents(); subMesh->GenerateNormalsAndTangents();
else else
subMesh->GenerateNormals(); subMesh->GenerateNormals();
@ -321,14 +321,14 @@ namespace Nz
namespace Loaders namespace Loaders
{ {
void RegisterMD5Mesh() MeshLoader::Entry GetMeshLoader_MD5Mesh()
{ {
MeshLoader::RegisterLoader(IsSupported, Check, Load); MeshLoader::Entry loader;
} loader.extensionSupport = IsSupported;
loader.streamChecker = Check;
loader.streamLoader = Load;
void UnregisterMD5Mesh() return loader;
{
MeshLoader::UnregisterLoader(IsSupported, Check, Load);
} }
} }
} }

View File

@ -8,14 +8,11 @@
#define NAZARA_LOADERS_MD5MESH_HPP #define NAZARA_LOADERS_MD5MESH_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Mesh.hpp>
namespace Nz namespace Nz::Loaders
{ {
namespace Loaders MeshLoader::Entry GetMeshLoader_MD5Mesh();
{
void RegisterMD5Mesh();
void UnregisterMD5Mesh();
}
} }
#endif // NAZARA_LOADERS_MD5MESH_HPP #endif // NAZARA_LOADERS_MD5MESH_HPP

View File

@ -22,7 +22,7 @@ namespace Nz
{ {
namespace namespace
{ {
bool IsSupported(const std::string& extension) bool IsSupported(const std::string_view& extension)
{ {
return (extension == "obj"); return (extension == "obj");
} }
@ -42,7 +42,7 @@ namespace Nz
return Ternary::Unknown; return Ternary::Unknown;
} }
bool ParseMTL(Mesh* mesh, const std::filesystem::path& filePath, const std::string* materials, const OBJParser::Mesh* meshes, std::size_t meshCount) bool ParseMTL(Mesh& mesh, const std::filesystem::path& filePath, const std::string* materials, const OBJParser::Mesh* meshes, std::size_t meshCount)
{ {
File file(filePath); File file(filePath);
if (!file.Open(OpenMode_ReadOnly | OpenMode_Text)) if (!file.Open(OpenMode_ReadOnly | OpenMode_Text))
@ -151,13 +151,13 @@ namespace Nz
it = materialCache.emplace(matName, std::move(data)).first; it = materialCache.emplace(matName, std::move(data)).first;
} }
mesh->SetMaterialData(meshes[i].material, it->second); mesh.SetMaterialData(meshes[i].material, it->second);
} }
return true; return true;
} }
MeshRef Load(Stream& stream, const MeshParams& parameters) std::shared_ptr<Mesh> Load(Stream& stream, const MeshParams& parameters)
{ {
long long reservedVertexCount; long long reservedVertexCount;
if (!parameters.custom.GetIntegerParameter("NativeOBJLoader_VertexCount", &reservedVertexCount)) if (!parameters.custom.GetIntegerParameter("NativeOBJLoader_VertexCount", &reservedVertexCount))
@ -170,7 +170,7 @@ namespace Nz
return nullptr; return nullptr;
} }
MeshRef mesh = Mesh::New(); std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
mesh->CreateStatic(); mesh->CreateStatic();
const std::string* materials = parser.GetMaterials(); const std::string* materials = parser.GetMaterials();
@ -254,11 +254,11 @@ namespace Nz
} }
// Création des buffers // Création des buffers
IndexBufferRef indexBuffer = IndexBuffer::New(vertexCount > std::numeric_limits<UInt16>::max(), std::size_t(indices.size()), parameters.storage, parameters.indexBufferFlags); std::shared_ptr<IndexBuffer> indexBuffer = std::make_shared<IndexBuffer>(vertexCount > std::numeric_limits<UInt16>::max(), std::size_t(indices.size()), parameters.storage, parameters.indexBufferFlags);
VertexBufferRef vertexBuffer = VertexBuffer::New(parameters.vertexDeclaration, std::size_t(vertexCount), parameters.storage, parameters.vertexBufferFlags); std::shared_ptr<VertexBuffer> vertexBuffer = std::make_shared<VertexBuffer>(parameters.vertexDeclaration, std::size_t(vertexCount), parameters.storage, parameters.vertexBufferFlags);
// Remplissage des indices // Remplissage des indices
IndexMapper indexMapper(indexBuffer, BufferAccess_WriteOnly); IndexMapper indexMapper(*indexBuffer, BufferAccess::WriteOnly);
for (std::size_t j = 0; j < indices.size(); ++j) for (std::size_t j = 0; j < indices.size(); ++j)
indexMapper.Set(j, UInt32(indices[j])); indexMapper.Set(j, UInt32(indices[j]));
@ -277,11 +277,11 @@ namespace Nz
bool hasNormals = true; bool hasNormals = true;
bool hasTexCoords = true; bool hasTexCoords = true;
VertexMapper vertexMapper(vertexBuffer, BufferAccess_DiscardAndWrite); VertexMapper vertexMapper(*vertexBuffer, BufferAccess::DiscardAndWrite);
auto normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Normal); auto normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Normal);
auto posPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); auto posPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
auto uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord); auto uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord);
if (!normalPtr) if (!normalPtr)
hasNormals = false; hasNormals = false;
@ -321,7 +321,7 @@ namespace Nz
vertexMapper.Unmap(); vertexMapper.Unmap();
StaticMeshRef subMesh = StaticMesh::New(vertexBuffer, indexBuffer); std::shared_ptr<StaticMesh> subMesh = std::make_shared<StaticMesh>(std::move(vertexBuffer), indexBuffer);
subMesh->GenerateAABB(); subMesh->GenerateAABB();
subMesh->SetMaterialIndex(meshes[i].material); subMesh->SetMaterialIndex(meshes[i].material);
@ -345,7 +345,7 @@ namespace Nz
if (!mtlLib.empty()) if (!mtlLib.empty())
{ {
ErrorFlags flags(ErrorFlag_ThrowExceptionDisabled); ErrorFlags flags(ErrorFlag_ThrowExceptionDisabled);
ParseMTL(mesh, stream.GetDirectory() / mtlLib, materials, meshes, meshCount); ParseMTL(*mesh, stream.GetDirectory() / mtlLib, materials, meshes, meshCount);
} }
return mesh; return mesh;
@ -354,14 +354,14 @@ namespace Nz
namespace Loaders namespace Loaders
{ {
void RegisterOBJLoader() MeshLoader::Entry GetMeshLoader_OBJ()
{ {
MeshLoader::RegisterLoader(IsSupported, Check, Load); MeshLoader::Entry loader;
} loader.extensionSupport = IsSupported;
loader.streamChecker = Check;
loader.streamLoader = Load;
void UnregisterOBJLoader() return loader;
{
MeshLoader::UnregisterLoader(IsSupported, Check, Load);
} }
} }
} }

View File

@ -8,14 +8,11 @@
#define NAZARA_LOADERS_OBJ_HPP #define NAZARA_LOADERS_OBJ_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Mesh.hpp>
namespace Nz namespace Nz::Loaders
{ {
namespace Loaders MeshLoader::Entry GetMeshLoader_OBJ();
{
void RegisterOBJLoader();
void UnregisterOBJLoader();
}
} }
#endif // NAZARA_LOADERS_OBJ_HPP #endif // NAZARA_LOADERS_OBJ_HPP

View File

@ -51,7 +51,7 @@ namespace Nz
T* m_buffer; T* m_buffer;
}; };
bool IsSupported(const std::string& extension) bool IsSupported(const std::string_view& extension)
{ {
return (extension == "obj"); return (extension == "obj");
} }
@ -142,21 +142,21 @@ namespace Nz
OBJParser::Mesh* meshes = objFormat.SetMeshCount(meshCount); OBJParser::Mesh* meshes = objFormat.SetMeshCount(meshCount);
for (std::size_t i = 0; i < meshCount; ++i) for (std::size_t i = 0; i < meshCount; ++i)
{ {
const StaticMesh* staticMesh = static_cast<const StaticMesh*>(mesh.GetSubMesh(i)); const StaticMesh& staticMesh = static_cast<const StaticMesh&>(*mesh.GetSubMesh(i));
std::size_t triangleCount = staticMesh->GetTriangleCount(); std::size_t triangleCount = staticMesh.GetTriangleCount();
meshes[i].faces.resize(triangleCount); meshes[i].faces.resize(triangleCount);
meshes[i].material = staticMesh->GetMaterialIndex(); meshes[i].material = staticMesh.GetMaterialIndex();
meshes[i].name = "mesh_" + std::to_string(i); meshes[i].name = "mesh_" + std::to_string(i);
meshes[i].vertices.resize(triangleCount * 3); meshes[i].vertices.resize(triangleCount * 3);
{ {
VertexMapper vertexMapper(staticMesh); VertexMapper vertexMapper(staticMesh);
SparsePtr<Vector3f> normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Normal); SparsePtr<Vector3f> normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Normal);
SparsePtr<Vector3f> positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); SparsePtr<Vector3f> positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
SparsePtr<Vector2f> texCoordsPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord); SparsePtr<Vector2f> texCoordsPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord);
std::size_t faceIndex = 0; std::size_t faceIndex = 0;
TriangleIterator triangle(staticMesh); TriangleIterator triangle(staticMesh);
@ -201,14 +201,13 @@ namespace Nz
namespace Loaders namespace Loaders
{ {
void RegisterOBJSaver() MeshSaver::Entry GetMeshSaver_OBJ()
{ {
MeshSaver::RegisterSaver(IsSupported, SaveToStream); MeshSaver::Entry entry;
} entry.formatSupport = IsSupported;
entry.streamSaver = SaveToStream;
void UnregisterOBJSaver() return entry;
{
MeshSaver::UnregisterSaver(IsSupported, SaveToStream);
} }
} }
} }

View File

@ -8,14 +8,11 @@
#define NAZARA_FORMATS_OBJSAVER_HPP #define NAZARA_FORMATS_OBJSAVER_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Mesh.hpp>
namespace Nz namespace Nz::Loaders
{ {
namespace Loaders MeshSaver::Entry GetMeshSaver_OBJ();
{
void RegisterOBJSaver();
void UnregisterOBJSaver();
}
} }
#endif // NAZARA_FORMATS_OBJSAVER_HPP #endif // NAZARA_FORMATS_OBJSAVER_HPP

View File

@ -40,7 +40,7 @@ namespace Nz
static_assert(sizeof(pcx_header) == (6+48+54)*sizeof(UInt8) + 10*sizeof(UInt16), "pcx_header struct must be packed"); static_assert(sizeof(pcx_header) == (6+48+54)*sizeof(UInt8) + 10*sizeof(UInt16), "pcx_header struct must be packed");
bool IsSupported(const std::string& extension) bool IsSupported(const std::string_view& extension)
{ {
return (extension == "pcx"); return (extension == "pcx");
} }
@ -61,7 +61,7 @@ namespace Nz
return Ternary::False; return Ternary::False;
} }
ImageRef Load(Stream& stream, const ImageParams& parameters) std::shared_ptr<Image> Load(Stream& stream, const ImageParams& parameters)
{ {
NazaraUnused(parameters); NazaraUnused(parameters);
@ -91,8 +91,8 @@ namespace Nz
unsigned int width = header.xmax - header.xmin+1; unsigned int width = header.xmax - header.xmin+1;
unsigned int height = header.ymax - header.ymin+1; unsigned int height = header.ymax - header.ymin+1;
ImageRef image = Image::New(); std::shared_ptr<Image> image = std::make_shared<Image>();
if (!image->Create(ImageType_2D, PixelFormat_RGB8, width, height, 1, (parameters.levelCount > 0) ? parameters.levelCount : 1)) if (!image->Create(ImageType::E2D, PixelFormat::RGB8, width, height, 1, (parameters.levelCount > 0) ? parameters.levelCount : 1))
{ {
NazaraError("Failed to create image"); NazaraError("Failed to create image");
return nullptr; return nullptr;
@ -333,7 +333,7 @@ namespace Nz
return nullptr; return nullptr;
} }
if (parameters.loadFormat != PixelFormat_Undefined) if (parameters.loadFormat != PixelFormat::Undefined)
image->Convert(parameters.loadFormat); image->Convert(parameters.loadFormat);
return image; return image;
@ -342,14 +342,14 @@ namespace Nz
namespace Loaders namespace Loaders
{ {
void RegisterPCX() ImageLoader::Entry GetImageLoader_PCX()
{ {
ImageLoader::RegisterLoader(IsSupported, Check, Load); ImageLoader::Entry loaderEntry;
} loaderEntry.extensionSupport = IsSupported;
loaderEntry.streamChecker = Check;
loaderEntry.streamLoader = Load;
void UnregisterPCX() return loaderEntry;
{
ImageLoader::UnregisterLoader(IsSupported, Check, Load);
} }
} }
} }

View File

@ -8,14 +8,11 @@
#define NAZARA_LOADERS_PCX_HPP #define NAZARA_LOADERS_PCX_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Image.hpp>
namespace Nz namespace Nz::Loaders
{ {
namespace Loaders ImageLoader::Entry GetImageLoader_PCX();
{
void RegisterPCX();
void UnregisterPCX();
}
} }
#endif // NAZARA_LOADERS_PCX_HPP #endif // NAZARA_LOADERS_PCX_HPP

View File

@ -36,9 +36,9 @@ namespace Nz
static stbi_io_callbacks callbacks = {Read, Skip, Eof}; static stbi_io_callbacks callbacks = {Read, Skip, Eof};
bool IsSupported(const std::string& extension) bool IsSupported(const std::string_view& extension)
{ {
static std::unordered_set<std::string> supportedExtensions = {"bmp", "gif", "hdr", "jpg", "jpeg", "pic", "png", "ppm", "pgm", "psd", "tga"}; static std::unordered_set<std::string_view> supportedExtensions = {"bmp", "gif", "hdr", "jpg", "jpeg", "pic", "png", "ppm", "pgm", "psd", "tga"};
return supportedExtensions.find(extension) != supportedExtensions.end(); return supportedExtensions.find(extension) != supportedExtensions.end();
} }
@ -55,7 +55,7 @@ namespace Nz
return Ternary::False; return Ternary::False;
} }
ImageRef Load(Stream& stream, const ImageParams& parameters) std::shared_ptr<Image> Load(Stream& stream, const ImageParams& parameters)
{ {
// Je charge tout en RGBA8 et je converti ensuite via la méthode Convert // Je charge tout en RGBA8 et je converti ensuite via la méthode Convert
// Ceci à cause d'un bug de STB lorsqu'il s'agit de charger certaines images (ex: JPG) en "default" // Ceci à cause d'un bug de STB lorsqu'il s'agit de charger certaines images (ex: JPG) en "default"
@ -65,7 +65,7 @@ namespace Nz
if (!ptr) if (!ptr)
{ {
NazaraError("Failed to load image: " + std::string(stbi_failure_reason())); NazaraError("Failed to load image: " + std::string(stbi_failure_reason()));
return nullptr; return {};
} }
CallOnExit freeStbiImage([ptr]() CallOnExit freeStbiImage([ptr]()
@ -73,19 +73,25 @@ namespace Nz
stbi_image_free(ptr); stbi_image_free(ptr);
}); });
ImageRef image = Image::New(); std::shared_ptr<Image> image = std::make_shared<Image>();
if (!image->Create(ImageType_2D, PixelFormat_RGBA8, width, height, 1, (parameters.levelCount > 0) ? parameters.levelCount : 1)) if (!image->Create(ImageType::E2D, PixelFormat::RGBA8, width, height, 1, (parameters.levelCount > 0) ? parameters.levelCount : 1))
{ {
NazaraError("Failed to create image"); NazaraError("Failed to create image");
return nullptr; return {};
} }
image->Update(ptr); image->Update(ptr);
freeStbiImage.CallAndReset(); freeStbiImage.CallAndReset();
if (parameters.loadFormat != PixelFormat_Undefined) if (parameters.loadFormat != PixelFormat::Undefined)
image->Convert(parameters.loadFormat); {
if (!image->Convert(parameters.loadFormat))
{
NazaraError("Failed to convert image to required format");
return {};
}
}
return image; return image;
} }
@ -93,14 +99,14 @@ namespace Nz
namespace Loaders namespace Loaders
{ {
void RegisterSTBLoader() ImageLoader::Entry GetImageLoader_STB()
{ {
ImageLoader::RegisterLoader(IsSupported, Check, Load); ImageLoader::Entry loaderEntry;
} loaderEntry.extensionSupport = IsSupported;
loaderEntry.streamChecker = Check;
loaderEntry.streamLoader = Load;
void UnregisterSTBLoader() return loaderEntry;
{
ImageLoader::UnregisterLoader(IsSupported, Check, Load);
} }
} }
} }

View File

@ -8,14 +8,11 @@
#define NAZARA_FORMATS_STBLOADER_HPP #define NAZARA_FORMATS_STBLOADER_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Image.hpp>
namespace Nz namespace Nz::Loaders
{ {
namespace Loaders ImageLoader::Entry GetImageLoader_STB();
{
void RegisterSTBLoader();
void UnregisterSTBLoader();
}
} }
#endif // NAZARA_FORMATS_STBLOADER_HPP #endif // NAZARA_FORMATS_STBLOADER_HPP

View File

@ -15,36 +15,36 @@ namespace Nz
{ {
using FormatHandler = bool(*)(const Image& image, const ImageParams& parameters, Stream& stream); using FormatHandler = bool(*)(const Image& image, const ImageParams& parameters, Stream& stream);
std::map<std::string, FormatHandler> s_formatHandlers; std::map<std::string_view, FormatHandler> s_formatHandlers;
int ConvertToFloatFormat(Image& image) int ConvertToFloatFormat(Image& image)
{ {
switch (image.GetFormat()) switch (image.GetFormat())
{ {
case PixelFormat_R32F: case PixelFormat::R32F:
return 1; return 1;
case PixelFormat_RG32F: case PixelFormat::RG32F:
return 2; return 2;
case PixelFormat_RGB32F: case PixelFormat::RGB32F:
return 3; return 3;
case PixelFormat_RGBA32F: case PixelFormat::RGBA32F:
return 4; return 4;
default: default:
{ {
if (PixelFormatInfo::HasAlpha(image.GetFormat())) if (PixelFormatInfo::HasAlpha(image.GetFormat()))
{ {
if (!image.Convert(PixelFormat_RGBA32F)) if (!image.Convert(PixelFormat::RGBA32F))
break; break;
return 4; return 4;
} }
else else
{ {
if (!image.Convert(PixelFormat_RGB32F)) if (!image.Convert(PixelFormat::RGB32F))
break; break;
return 3; return 3;
@ -59,32 +59,32 @@ namespace Nz
{ {
switch (image.GetFormat()) switch (image.GetFormat())
{ {
case PixelFormat_L8: case PixelFormat::L8:
case PixelFormat_R8: case PixelFormat::R8:
return 1; return 1;
case PixelFormat_LA8: case PixelFormat::LA8:
case PixelFormat_RG8: case PixelFormat::RG8:
return 2; return 2;
case PixelFormat_RGB8: case PixelFormat::RGB8:
return 3; return 3;
case PixelFormat_RGBA8: case PixelFormat::RGBA8:
return 4; return 4;
default: default:
{ {
if (PixelFormatInfo::HasAlpha(image.GetFormat())) if (PixelFormatInfo::HasAlpha(image.GetFormat()))
{ {
if (!image.Convert(PixelFormat_RGBA8)) if (!image.Convert(PixelFormat::RGBA8))
break; break;
return 4; return 4;
} }
else else
{ {
if (!image.Convert(PixelFormat_RGB8)) if (!image.Convert(PixelFormat::RGB8))
break; break;
return 3; return 3;
@ -102,7 +102,7 @@ namespace Nz
throw std::runtime_error("Failed to write to stream"); throw std::runtime_error("Failed to write to stream");
} }
bool FormatQuerier(const std::string& extension) bool FormatQuerier(const std::string_view& extension)
{ {
return s_formatHandlers.find(extension) != s_formatHandlers.end(); return s_formatHandlers.find(extension) != s_formatHandlers.end();
} }
@ -118,9 +118,9 @@ namespace Nz
} }
ImageType type = image.GetType(); ImageType type = image.GetType();
if (type != ImageType_1D && type != ImageType_2D) if (type != ImageType::E1D && type != ImageType::E2D)
{ {
NazaraError("Image type 0x" + NumberToString(type, 16) + " is not in a supported format"); NazaraError("Image type 0x" + NumberToString(UnderlyingCast(type), 16) + " is not in a supported format");
return false; return false;
} }
@ -262,22 +262,20 @@ namespace Nz
namespace Loaders namespace Loaders
{ {
void RegisterSTBSaver() ImageSaver::Entry GetImageSaver_STB()
{ {
s_formatHandlers["bmp"] = &SaveBMP; s_formatHandlers["bmp"] = &SaveBMP;
s_formatHandlers["hdr"] = &SaveHDR; s_formatHandlers["hdr"] = &SaveHDR;
s_formatHandlers["jpg"] = &SaveJPEG; s_formatHandlers["jpg"] = &SaveJPEG;
s_formatHandlers["jpeg"] = &SaveJPEG; s_formatHandlers["jpeg"] = &SaveJPEG;
s_formatHandlers["png"] = &SavePNG; s_formatHandlers["png"] = &SavePNG;
s_formatHandlers["tga"] = &SaveTGA; s_formatHandlers["tga"] = &SaveTGA;
ImageSaver::RegisterSaver(FormatQuerier, SaveToStream); ImageSaver::Entry entry;
} entry.formatSupport = FormatQuerier;
entry.streamSaver = SaveToStream;
void UnregisterSTBSaver() return entry;
{
ImageSaver::UnregisterSaver(FormatQuerier, SaveToStream);
s_formatHandlers.clear();
} }
} }
} }

View File

@ -8,14 +8,11 @@
#define NAZARA_FORMATS_STBSAVER_HPP #define NAZARA_FORMATS_STBSAVER_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Utility/Image.hpp>
namespace Nz namespace Nz::Loaders
{ {
namespace Loaders ImageSaver::Entry GetImageSaver_STB();
{
void RegisterSTBSaver();
void UnregisterSTBSaver();
}
} }
#endif // NAZARA_FORMATS_STBSAVER_HPP #endif // NAZARA_FORMATS_STBSAVER_HPP

View File

@ -75,7 +75,7 @@ namespace Nz
UInt32 GuillotineImageAtlas::GetStorage() const UInt32 GuillotineImageAtlas::GetStorage() const
{ {
return DataStorage_Software; return static_cast<UInt32>(DataStorage::Software);
} }
bool GuillotineImageAtlas::Insert(const Image& image, Rectui* rect, bool* flipped, unsigned int* layerIndex) bool GuillotineImageAtlas::Insert(const Image& image, Rectui* rect, bool* flipped, unsigned int* layerIndex)
@ -161,10 +161,10 @@ namespace Nz
AbstractImage* GuillotineImageAtlas::ResizeImage(AbstractImage* oldImage, const Vector2ui& size) const AbstractImage* GuillotineImageAtlas::ResizeImage(AbstractImage* oldImage, const Vector2ui& size) const
{ {
std::unique_ptr<Image> newImage(new Image(ImageType_2D, PixelFormat_A8, size.x, size.y)); std::unique_ptr<Image> newImage(new Image(ImageType::E2D, PixelFormat::A8, size.x, size.y));
if (oldImage) if (oldImage)
{ {
newImage->Copy(static_cast<Image*>(oldImage), Rectui(size), Vector2ui(0, 0)); // Copie des anciennes données newImage->Copy(static_cast<Image&>(*oldImage), Rectui(size), Vector2ui(0, 0)); // Copie des anciennes données
} }
return newImage.release(); return newImage.release();

View File

@ -8,6 +8,7 @@
#include <Nazara/Core/StringExt.hpp> #include <Nazara/Core/StringExt.hpp>
#include <Nazara/Utility/Config.hpp> #include <Nazara/Utility/Config.hpp>
#include <Nazara/Utility/PixelFormat.hpp> #include <Nazara/Utility/PixelFormat.hpp>
#include <Nazara/Utility/Utility.hpp>
#include <memory> #include <memory>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
@ -66,8 +67,6 @@ namespace Nz
Image::~Image() Image::~Image()
{ {
OnImageRelease(this);
Destroy(); Destroy();
} }
@ -102,7 +101,7 @@ namespace Nz
unsigned int height = m_sharedImage->height; unsigned int height = m_sharedImage->height;
// Les images 3D et cubemaps sont stockés de la même façon // Les images 3D et cubemaps sont stockés de la même façon
unsigned int depth = (m_sharedImage->type == ImageType_Cubemap) ? 6 : m_sharedImage->depth; unsigned int depth = (m_sharedImage->type == ImageType::Cubemap) ? 6 : m_sharedImage->depth;
for (unsigned int i = 0; i < levels.size(); ++i) for (unsigned int i = 0; i < levels.size(); ++i)
{ {
@ -132,7 +131,7 @@ namespace Nz
if (height > 1) if (height > 1)
height >>= 1; height >>= 1;
if (depth > 1 && m_sharedImage->type != ImageType_Cubemap) if (depth > 1 && m_sharedImage->type != ImageType::Cubemap)
depth >>= 1; depth >>= 1;
} }
@ -144,13 +143,13 @@ namespace Nz
return true; return true;
} }
void Image::Copy(const Image* source, const Boxui& srcBox, const Vector3ui& dstPos) void Image::Copy(const Image& source, const Boxui& srcBox, const Vector3ui& dstPos)
{ {
NazaraAssert(IsValid(), "Invalid image"); NazaraAssert(IsValid(), "invalid image");
NazaraAssert(source && source->IsValid(), "Invalid source image"); NazaraAssert(source.IsValid(), "invalid source image");
NazaraAssert(source->GetFormat() == m_sharedImage->format, "Image formats don't match"); NazaraAssert(source.GetFormat() == m_sharedImage->format, "image formats don't match");
const UInt8* srcPtr = source->GetConstPixels(srcBox.x, srcBox.y, srcBox.z); const UInt8* srcPtr = source.GetConstPixels(srcBox.x, srcBox.y, srcBox.z);
#if NAZARA_UTILITY_SAFE #if NAZARA_UTILITY_SAFE
if (!srcPtr) if (!srcPtr)
{ {
@ -162,7 +161,7 @@ namespace Nz
UInt8 bpp = PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format); UInt8 bpp = PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format);
UInt8* dstPtr = GetPixelPtr(m_sharedImage->levels[0].get(), bpp, dstPos.x, dstPos.y, dstPos.z, m_sharedImage->width, m_sharedImage->height); UInt8* dstPtr = GetPixelPtr(m_sharedImage->levels[0].get(), bpp, dstPos.x, dstPos.y, dstPos.z, m_sharedImage->width, m_sharedImage->height);
Copy(dstPtr, srcPtr, m_sharedImage->format, srcBox.width, srcBox.height, srcBox.depth, m_sharedImage->width, m_sharedImage->height, source->GetWidth(), source->GetHeight()); Copy(dstPtr, srcPtr, m_sharedImage->format, srcBox.width, srcBox.height, srcBox.depth, m_sharedImage->width, m_sharedImage->height, source.GetWidth(), source.GetHeight());
} }
bool Image::Create(ImageType type, PixelFormat format, unsigned int width, unsigned int height, unsigned int depth, UInt8 levelCount) bool Image::Create(ImageType type, PixelFormat format, unsigned int width, unsigned int height, unsigned int depth, UInt8 levelCount)
@ -196,7 +195,7 @@ namespace Nz
switch (type) switch (type)
{ {
case ImageType_1D: case ImageType::E1D:
if (height > 1) if (height > 1)
{ {
NazaraError("1D textures must be 1 tall"); NazaraError("1D textures must be 1 tall");
@ -210,8 +209,8 @@ namespace Nz
} }
break; break;
case ImageType_1D_Array: case ImageType::E1D_Array:
case ImageType_2D: case ImageType::E2D:
if (depth > 1) if (depth > 1)
{ {
NazaraError("2D textures must be 1 deep"); NazaraError("2D textures must be 1 deep");
@ -219,11 +218,11 @@ namespace Nz
} }
break; break;
case ImageType_2D_Array: case ImageType::E2D_Array:
case ImageType_3D: case ImageType::E3D:
break; break;
case ImageType_Cubemap: case ImageType::Cubemap:
if (depth > 1) if (depth > 1)
{ {
NazaraError("Cubemaps must be 1 deep"); NazaraError("Cubemaps must be 1 deep");
@ -249,7 +248,7 @@ namespace Nz
unsigned int w = width; unsigned int w = width;
unsigned int h = height; unsigned int h = height;
unsigned int d = (type == ImageType_Cubemap) ? 6 : depth; unsigned int d = (type == ImageType::Cubemap) ? 6 : depth;
for (unsigned int i = 0; i < levelCount; ++i) for (unsigned int i = 0; i < levelCount; ++i)
{ {
@ -264,7 +263,7 @@ namespace Nz
if (h > 1) if (h > 1)
h >>= 1; h >>= 1;
if (d > 1 && type != ImageType_Cubemap) if (d > 1 && type != ImageType::Cubemap)
d >>= 1; d >>= 1;
} }
catch (const std::exception& e) catch (const std::exception& e)
@ -282,10 +281,7 @@ namespace Nz
void Image::Destroy() void Image::Destroy()
{ {
if (m_sharedImage != &emptyImage) if (m_sharedImage != &emptyImage)
{
OnImageDestroy(this);
ReleaseImage(); ReleaseImage();
}
} }
bool Image::Fill(const Color& color) bool Image::Fill(const Color& color)
@ -308,7 +304,7 @@ namespace Nz
UInt8 bpp = PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format); UInt8 bpp = PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format);
std::unique_ptr<UInt8[]> colorBuffer(new UInt8[bpp]); std::unique_ptr<UInt8[]> colorBuffer(new UInt8[bpp]);
if (!PixelFormatInfo::Convert(PixelFormat_RGBA8, m_sharedImage->format, &color.r, colorBuffer.get())) if (!PixelFormatInfo::Convert(PixelFormat::RGBA8, m_sharedImage->format, &color.r, colorBuffer.get()))
{ {
NazaraError("Failed to convert RGBA8 to " + PixelFormatInfo::GetName(m_sharedImage->format)); NazaraError("Failed to convert RGBA8 to " + PixelFormatInfo::GetName(m_sharedImage->format));
return false; return false;
@ -320,7 +316,7 @@ namespace Nz
unsigned int height = m_sharedImage->height; unsigned int height = m_sharedImage->height;
// Les images 3D et cubemaps sont stockés de la même façon // Les images 3D et cubemaps sont stockés de la même façon
unsigned int depth = (m_sharedImage->type == ImageType_Cubemap) ? 6 : m_sharedImage->depth; unsigned int depth = (m_sharedImage->type == ImageType::Cubemap) ? 6 : m_sharedImage->depth;
for (auto & level : levels) for (auto & level : levels)
{ {
@ -342,7 +338,7 @@ namespace Nz
if (height > 1U) if (height > 1U)
height >>= 1; height >>= 1;
if (depth > 1U && m_sharedImage->type != ImageType_Cubemap) if (depth > 1U && m_sharedImage->type != ImageType::Cubemap)
depth >>= 1; depth >>= 1;
} }
@ -386,7 +382,7 @@ namespace Nz
UInt8 bpp = PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format); UInt8 bpp = PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format);
std::unique_ptr<UInt8[]> colorBuffer(new UInt8[bpp]); std::unique_ptr<UInt8[]> colorBuffer(new UInt8[bpp]);
if (!PixelFormatInfo::Convert(PixelFormat_RGBA8, m_sharedImage->format, &color.r, colorBuffer.get())) if (!PixelFormatInfo::Convert(PixelFormat::RGBA8, m_sharedImage->format, &color.r, colorBuffer.get()))
{ {
NazaraError("Failed to convert RGBA8 to " + PixelFormatInfo::GetName(m_sharedImage->format)); NazaraError("Failed to convert RGBA8 to " + PixelFormatInfo::GetName(m_sharedImage->format));
return false; return false;
@ -446,7 +442,7 @@ namespace Nz
return false; return false;
} }
unsigned int depth = (m_sharedImage->type == ImageType_Cubemap) ? 6 : m_sharedImage->depth; unsigned int depth = (m_sharedImage->type == ImageType::Cubemap) ? 6 : m_sharedImage->depth;
if (z >= depth) if (z >= depth)
{ {
NazaraError("Z value exceeds depth (" + NumberToString(z) + " >= " + NumberToString(depth) + ')'); NazaraError("Z value exceeds depth (" + NumberToString(z) + " >= " + NumberToString(depth) + ')');
@ -458,7 +454,7 @@ namespace Nz
UInt8 bpp = PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format); UInt8 bpp = PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format);
std::unique_ptr<UInt8[]> colorBuffer(new UInt8[bpp]); std::unique_ptr<UInt8[]> colorBuffer(new UInt8[bpp]);
if (!PixelFormatInfo::Convert(PixelFormat_RGBA8, m_sharedImage->format, &color.r, colorBuffer.get())) if (!PixelFormatInfo::Convert(PixelFormat::RGBA8, m_sharedImage->format, &color.r, colorBuffer.get()))
{ {
NazaraError("Failed to convert RGBA8 to " + PixelFormatInfo::GetName(m_sharedImage->format)); NazaraError("Failed to convert RGBA8 to " + PixelFormatInfo::GetName(m_sharedImage->format));
return false; return false;
@ -498,11 +494,11 @@ namespace Nz
unsigned int width = m_sharedImage->width; unsigned int width = m_sharedImage->width;
unsigned int height = m_sharedImage->height; unsigned int height = m_sharedImage->height;
unsigned int depth = (m_sharedImage->type == ImageType_Cubemap) ? 6 : m_sharedImage->depth; unsigned int depth = (m_sharedImage->type == ImageType::Cubemap) ? 6 : m_sharedImage->depth;
for (auto& level : m_sharedImage->levels) for (auto& level : m_sharedImage->levels)
{ {
UInt8* ptr = level.get(); UInt8* ptr = level.get();
if (!PixelFormatInfo::Flip(PixelFlipping_Horizontally, m_sharedImage->format, width, height, depth, ptr, ptr)) if (!PixelFormatInfo::Flip(PixelFlipping::Horizontally, m_sharedImage->format, width, height, depth, ptr, ptr))
{ {
NazaraError("Failed to flip image"); NazaraError("Failed to flip image");
return false; return false;
@ -514,7 +510,7 @@ namespace Nz
if (height > 1U) if (height > 1U)
height >>= 1; height >>= 1;
if (depth > 1U && m_sharedImage->type != ImageType_Cubemap) if (depth > 1U && m_sharedImage->type != ImageType::Cubemap)
depth >>= 1; depth >>= 1;
} }
@ -541,11 +537,11 @@ namespace Nz
unsigned int width = m_sharedImage->width; unsigned int width = m_sharedImage->width;
unsigned int height = m_sharedImage->height; unsigned int height = m_sharedImage->height;
unsigned int depth = (m_sharedImage->type == ImageType_Cubemap) ? 6 : m_sharedImage->depth; unsigned int depth = (m_sharedImage->type == ImageType::Cubemap) ? 6 : m_sharedImage->depth;
for (auto& level : m_sharedImage->levels) for (auto& level : m_sharedImage->levels)
{ {
UInt8* ptr = level.get(); UInt8* ptr = level.get();
if (!PixelFormatInfo::Flip(PixelFlipping_Vertically, m_sharedImage->format, width, height, depth, ptr, ptr)) if (!PixelFormatInfo::Flip(PixelFlipping::Vertically, m_sharedImage->format, width, height, depth, ptr, ptr))
{ {
NazaraError("Failed to flip image"); NazaraError("Failed to flip image");
return false; return false;
@ -557,7 +553,7 @@ namespace Nz
if (height > 1U) if (height > 1U)
height >>= 1; height >>= 1;
if (depth > 1U && m_sharedImage->type != ImageType_Cubemap) if (depth > 1U && m_sharedImage->type != ImageType::Cubemap)
depth >>= 1; depth >>= 1;
} }
@ -597,7 +593,7 @@ namespace Nz
return nullptr; return nullptr;
} }
unsigned int depth = (m_sharedImage->type == ImageType_Cubemap) ? 6 : GetLevelSize(m_sharedImage->depth, level); unsigned int depth = (m_sharedImage->type == ImageType::Cubemap) ? 6 : GetLevelSize(m_sharedImage->depth, level);
if (z >= depth) if (z >= depth)
{ {
NazaraError("Z value exceeds depth (" + NumberToString(z) + " >= " + NumberToString(depth) + ')'); NazaraError("Z value exceeds depth (" + NumberToString(z) + " >= " + NumberToString(depth) + ')');
@ -670,7 +666,7 @@ namespace Nz
depth >>= 1; depth >>= 1;
} }
if (m_sharedImage->type == ImageType_Cubemap) if (m_sharedImage->type == ImageType::Cubemap)
size *= 6; size *= 6;
return size * PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format); return size * PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format);
@ -678,7 +674,7 @@ namespace Nz
std::size_t Image::GetMemoryUsage(UInt8 level) const std::size_t Image::GetMemoryUsage(UInt8 level) const
{ {
return PixelFormatInfo::ComputeSize(m_sharedImage->format, GetLevelSize(m_sharedImage->width, level), GetLevelSize(m_sharedImage->height, level), ((m_sharedImage->type == ImageType_Cubemap) ? 6 : GetLevelSize(m_sharedImage->depth, level))); return PixelFormatInfo::ComputeSize(m_sharedImage->format, GetLevelSize(m_sharedImage->width, level), GetLevelSize(m_sharedImage->height, level), ((m_sharedImage->type == ImageType::Cubemap) ? 6 : GetLevelSize(m_sharedImage->depth, level)));
} }
Color Image::GetPixelColor(unsigned int x, unsigned int y, unsigned int z) const Color Image::GetPixelColor(unsigned int x, unsigned int y, unsigned int z) const
@ -708,7 +704,7 @@ namespace Nz
return Color(); return Color();
} }
unsigned int depth = (m_sharedImage->type == ImageType_Cubemap) ? 6 : m_sharedImage->depth; unsigned int depth = (m_sharedImage->type == ImageType::Cubemap) ? 6 : m_sharedImage->depth;
if (z >= depth) if (z >= depth)
{ {
NazaraError("Z value exceeds depth (" + NumberToString(z) + " >= " + NumberToString(depth) + ')'); NazaraError("Z value exceeds depth (" + NumberToString(z) + " >= " + NumberToString(depth) + ')');
@ -719,7 +715,7 @@ namespace Nz
const UInt8* pixel = GetPixelPtr(m_sharedImage->levels[0].get(), PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format), x, y, z, m_sharedImage->width, m_sharedImage->height); const UInt8* pixel = GetPixelPtr(m_sharedImage->levels[0].get(), PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format), x, y, z, m_sharedImage->width, m_sharedImage->height);
Color color; Color color;
if (!PixelFormatInfo::Convert(m_sharedImage->format, PixelFormat_RGBA8, pixel, &color.r)) if (!PixelFormatInfo::Convert(m_sharedImage->format, PixelFormat::RGBA8, pixel, &color.r))
NazaraError("Failed to convert image's format to RGBA8"); NazaraError("Failed to convert image's format to RGBA8");
return color; return color;
@ -758,7 +754,7 @@ namespace Nz
return nullptr; return nullptr;
} }
unsigned int depth = (m_sharedImage->type == ImageType_Cubemap) ? 6 : GetLevelSize(m_sharedImage->depth, level); unsigned int depth = (m_sharedImage->type == ImageType::Cubemap) ? 6 : GetLevelSize(m_sharedImage->depth, level);
if (z >= depth) if (z >= depth)
{ {
NazaraError("Z value exceeds depth (" + NumberToString(z) + " >= " + NumberToString(depth) + ')'); NazaraError("Z value exceeds depth (" + NumberToString(z) + " >= " + NumberToString(depth) + ')');
@ -820,7 +816,7 @@ namespace Nz
const PixelFormatDescription& info = PixelFormatInfo::GetInfo(m_sharedImage->format); const PixelFormatDescription& info = PixelFormatInfo::GetInfo(m_sharedImage->format);
Bitset<> workingBitset; Bitset<> workingBitset;
std::size_t pixelCount = m_sharedImage->width * m_sharedImage->height * ((m_sharedImage->type == ImageType_Cubemap) ? 6 : m_sharedImage->depth); std::size_t pixelCount = m_sharedImage->width * m_sharedImage->height * ((m_sharedImage->type == ImageType::Cubemap) ? 6 : m_sharedImage->depth);
if (pixelCount == 0) if (pixelCount == 0)
return false; return false;
@ -851,21 +847,21 @@ namespace Nz
} }
// LoadArray // LoadArray
ImageRef Image::LoadArrayFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams, const Vector2ui& atlasSize) std::shared_ptr<Image> Image::LoadArrayFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams, const Vector2ui& atlasSize)
{ {
ImageRef image = Image::LoadFromFile(filePath, imageParams); std::shared_ptr<Image> image = Image::LoadFromFile(filePath, imageParams);
if (!image) if (!image)
{ {
NazaraError("Failed to load image"); NazaraError("Failed to load image");
return nullptr; return nullptr;
} }
return LoadArrayFromImage(image, atlasSize); return LoadArrayFromImage(*image, atlasSize);
} }
ImageRef Image::LoadArrayFromImage(const Image* image, const Vector2ui& atlasSize) std::shared_ptr<Image> Image::LoadArrayFromImage(const Image& image, const Vector2ui& atlasSize)
{ {
NazaraAssert(image && image->IsValid(), "Invalid image"); NazaraAssert(image.IsValid(), "Invalid image");
#if NAZARA_UTILITY_SAFE #if NAZARA_UTILITY_SAFE
if (atlasSize.x == 0) if (atlasSize.x == 0)
@ -881,17 +877,17 @@ namespace Nz
} }
#endif #endif
ImageType type = image->GetType(); ImageType type = image.GetType();
#if NAZARA_UTILITY_SAFE #if NAZARA_UTILITY_SAFE
if (type != ImageType_1D && type != ImageType_2D) if (type != ImageType::E1D && type != ImageType::E2D)
{ {
NazaraError("Image type not handled (0x" + NumberToString(type, 16) + ')'); NazaraError("Image type not handled (0x" + NumberToString(UnderlyingCast(type), 16) + ')');
return nullptr; return nullptr;
} }
#endif #endif
Vector2ui imageSize(image->GetWidth(), image->GetHeight()); Vector2ui imageSize(image.GetWidth(), image.GetHeight());
if (imageSize.x % atlasSize.x != 0) if (imageSize.x % atlasSize.x != 0)
{ {
@ -907,12 +903,12 @@ namespace Nz
unsigned int layerCount = atlasSize.x*atlasSize.y; unsigned int layerCount = atlasSize.x*atlasSize.y;
ImageRef arrayImage = New(); std::shared_ptr<Image> arrayImage = std::make_shared<Image>();
// Selon le type de l'image de base, on va créer un array d'images 2D ou 1D // Selon le type de l'image de base, on va créer un array d'images 2D ou 1D
if (type == ImageType_2D) if (type == ImageType::E2D)
arrayImage->Create(ImageType_2D_Array, image->GetFormat(), faceSize.x, faceSize.y, layerCount); arrayImage->Create(ImageType::E2D_Array, image.GetFormat(), faceSize.x, faceSize.y, layerCount);
else else
arrayImage->Create(ImageType_1D_Array, image->GetFormat(), faceSize.x, layerCount); arrayImage->Create(ImageType::E1D_Array, image.GetFormat(), faceSize.x, layerCount);
if (!arrayImage->IsValid()) if (!arrayImage->IsValid())
{ {
@ -928,57 +924,57 @@ namespace Nz
return arrayImage; return arrayImage;
} }
ImageRef Image::LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams, const Vector2ui& atlasSize) std::shared_ptr<Image> Image::LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams, const Vector2ui& atlasSize)
{ {
ImageRef image = Image::LoadFromMemory(data, size, imageParams); std::shared_ptr<Image> image = Image::LoadFromMemory(data, size, imageParams);
if (!image) if (!image)
{ {
NazaraError("Failed to load image"); NazaraError("Failed to load image");
return nullptr; return nullptr;
} }
return LoadArrayFromImage(image, atlasSize); return LoadArrayFromImage(*image, atlasSize);
} }
ImageRef Image::LoadArrayFromStream(Stream& stream, const ImageParams& imageParams, const Vector2ui& atlasSize) std::shared_ptr<Image> Image::LoadArrayFromStream(Stream& stream, const ImageParams& imageParams, const Vector2ui& atlasSize)
{ {
ImageRef image = Image::LoadFromStream(stream, imageParams); std::shared_ptr<Image> image = Image::LoadFromStream(stream, imageParams);
if (!image) if (!image)
{ {
NazaraError("Failed to load image"); NazaraError("Failed to load image");
return nullptr; return nullptr;
} }
return LoadArrayFromImage(image, atlasSize); return LoadArrayFromImage(*image, atlasSize);
} }
ImageRef Image::LoadCubemapFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams, const CubemapParams& cubemapParams) std::shared_ptr<Image> Image::LoadCubemapFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams, const CubemapParams& cubemapParams)
{ {
ImageRef image = Image::LoadFromFile(filePath, imageParams); std::shared_ptr<Image> image = Image::LoadFromFile(filePath, imageParams);
if (!image) if (!image)
{ {
NazaraError("Failed to load image"); NazaraError("Failed to load image");
return nullptr; return nullptr;
} }
return LoadCubemapFromImage(image, cubemapParams); return LoadCubemapFromImage(*image, cubemapParams);
} }
ImageRef Image::LoadCubemapFromImage(const Image* image, const CubemapParams& params) std::shared_ptr<Image> Image::LoadCubemapFromImage(const Image& image, const CubemapParams& params)
{ {
NazaraAssert(image && image->IsValid(), "Invalid image"); NazaraAssert(image.IsValid(), "Invalid image");
#if NAZARA_UTILITY_SAFE #if NAZARA_UTILITY_SAFE
ImageType type = image->GetType(); ImageType type = image.GetType();
if (type != ImageType_2D) if (type != ImageType::E2D)
{ {
NazaraError("Image type not handled (0x" + NumberToString(type, 16) + ')'); NazaraError("Image type not handled (0x" + NumberToString(UnderlyingCast(type), 16) + ')');
return nullptr; return nullptr;
} }
#endif #endif
unsigned int width = image->GetWidth(); unsigned int width = image.GetWidth();
unsigned int height = image->GetHeight(); unsigned int height = image.GetHeight();
unsigned int faceSize = (params.faceSize == 0) ? std::max(width, height)/4 : params.faceSize; unsigned int faceSize = (params.faceSize == 0) ? std::max(width, height)/4 : params.faceSize;
// Sans cette vérification, celles des rectangles pourrait réussir via un overflow // Sans cette vérification, celles des rectangles pourrait réussir via un overflow
@ -1034,52 +1030,52 @@ namespace Nz
return nullptr; return nullptr;
} }
ImageRef cubemap = New(); std::shared_ptr<Image> cubemap = std::make_shared<Image>();
if (!cubemap->Create(ImageType_Cubemap, image->GetFormat(), faceSize, faceSize)) if (!cubemap->Create(ImageType::Cubemap, image.GetFormat(), faceSize, faceSize))
{ {
NazaraError("Failed to create cubemap"); NazaraError("Failed to create cubemap");
return nullptr; return nullptr;
} }
cubemap->Copy(image, Rectui(backPos.x, backPos.y, faceSize, faceSize), Vector3ui(0, 0, CubemapFace_NegativeZ)); cubemap->Copy(image, Rectui(backPos.x, backPos.y, faceSize, faceSize), Vector3ui(0, 0, UnderlyingCast(CubemapFace::NegativeZ)));
cubemap->Copy(image, Rectui(downPos.x, downPos.y, faceSize, faceSize), Vector3ui(0, 0, CubemapFace_NegativeY)); cubemap->Copy(image, Rectui(downPos.x, downPos.y, faceSize, faceSize), Vector3ui(0, 0, UnderlyingCast(CubemapFace::NegativeY)));
cubemap->Copy(image, Rectui(forwardPos.x, forwardPos.y, faceSize, faceSize), Vector3ui(0, 0, CubemapFace_PositiveZ)); cubemap->Copy(image, Rectui(forwardPos.x, forwardPos.y, faceSize, faceSize), Vector3ui(0, 0, UnderlyingCast(CubemapFace::PositiveZ)));
cubemap->Copy(image, Rectui(leftPos.x, leftPos.y, faceSize, faceSize), Vector3ui(0, 0, CubemapFace_NegativeX)); cubemap->Copy(image, Rectui(leftPos.x, leftPos.y, faceSize, faceSize), Vector3ui(0, 0, UnderlyingCast(CubemapFace::NegativeX)));
cubemap->Copy(image, Rectui(rightPos.x, rightPos.y, faceSize, faceSize), Vector3ui(0, 0, CubemapFace_PositiveX)); cubemap->Copy(image, Rectui(rightPos.x, rightPos.y, faceSize, faceSize), Vector3ui(0, 0, UnderlyingCast(CubemapFace::PositiveX)));
cubemap->Copy(image, Rectui(upPos.x, upPos.y, faceSize, faceSize), Vector3ui(0, 0, CubemapFace_PositiveY)); cubemap->Copy(image, Rectui(upPos.x, upPos.y, faceSize, faceSize), Vector3ui(0, 0, UnderlyingCast(CubemapFace::PositiveY)));
return cubemap; return cubemap;
} }
ImageRef Image::LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams, const CubemapParams& cubemapParams) std::shared_ptr<Image> Image::LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams, const CubemapParams& cubemapParams)
{ {
ImageRef image = Image::LoadFromMemory(data, size, imageParams); std::shared_ptr<Image> image = Image::LoadFromMemory(data, size, imageParams);
if (!image) if (!image)
{ {
NazaraError("Failed to load image"); NazaraError("Failed to load image");
return nullptr; return nullptr;
} }
return LoadCubemapFromImage(image, cubemapParams); return LoadCubemapFromImage(*image, cubemapParams);
} }
ImageRef Image::LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams, const CubemapParams& cubemapParams) std::shared_ptr<Image> Image::LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams, const CubemapParams& cubemapParams)
{ {
ImageRef image = Image::LoadFromStream(stream, imageParams); std::shared_ptr<Image> image = Image::LoadFromStream(stream, imageParams);
if (!image) if (!image)
{ {
NazaraError("Failed to load image"); NazaraError("Failed to load image");
return nullptr; return nullptr;
} }
return LoadCubemapFromImage(image, cubemapParams); return LoadCubemapFromImage(*image, cubemapParams);
} }
bool Image::LoadFaceFromFile(CubemapFace face, const std::filesystem::path& filePath, const ImageParams& params) bool Image::LoadFaceFromFile(CubemapFace face, const std::filesystem::path& filePath, const ImageParams& params)
{ {
NazaraAssert(IsValid() && IsCubemap(), "Texture must be a valid cubemap"); NazaraAssert(IsValid() && IsCubemap(), "Texture must be a valid cubemap");
ImageRef image = Image::LoadFromFile(filePath, params); std::shared_ptr<Image> image = Image::LoadFromFile(filePath, params);
if (!image) if (!image)
{ {
NazaraError("Failed to load image"); NazaraError("Failed to load image");
@ -1099,7 +1095,7 @@ namespace Nz
return false; return false;
} }
Copy(image, Rectui(0, 0, faceSize, faceSize), Vector3ui(0, 0, face)); Copy(*image, Rectui(0, 0, faceSize, faceSize), Vector3ui(0, 0, UnderlyingCast(face)));
return true; return true;
} }
@ -1107,7 +1103,7 @@ namespace Nz
{ {
NazaraAssert(IsValid() && IsCubemap(), "Texture must be a valid cubemap"); NazaraAssert(IsValid() && IsCubemap(), "Texture must be a valid cubemap");
ImageRef image = Image::LoadFromMemory(data, size, params); std::shared_ptr<Image> image = Image::LoadFromMemory(data, size, params);
if (!image) if (!image)
{ {
NazaraError("Failed to load image"); NazaraError("Failed to load image");
@ -1127,7 +1123,7 @@ namespace Nz
return false; return false;
} }
Copy(image, Rectui(0, 0, faceSize, faceSize), Vector3ui(0, 0, face)); Copy(*image, Rectui(0, 0, faceSize, faceSize), Vector3ui(0, 0, UnderlyingCast(face)));
return true; return true;
} }
@ -1135,7 +1131,7 @@ namespace Nz
{ {
NazaraAssert(IsValid() && IsCubemap(), "Texture must be a valid cubemap"); NazaraAssert(IsValid() && IsCubemap(), "Texture must be a valid cubemap");
ImageRef image = Image::LoadFromStream(stream, params); std::shared_ptr<Image> image = Image::LoadFromStream(stream, params);
if (!image) if (!image)
{ {
NazaraError("Failed to load image"); NazaraError("Failed to load image");
@ -1155,18 +1151,24 @@ namespace Nz
return false; return false;
} }
Copy(image, Rectui(0, 0, faceSize, faceSize), Vector3ui(0, 0, face)); Copy(*image, Rectui(0, 0, faceSize, faceSize), Vector3ui(0, 0, UnderlyingCast(face)));
return true; return true;
} }
bool Image::SaveToFile(const std::filesystem::path& filePath, const ImageParams& params) bool Image::SaveToFile(const std::filesystem::path& filePath, const ImageParams& params)
{ {
return ImageSaver::SaveToFile(*this, filePath, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetImageSaver().SaveToFile(*this, filePath, params);
} }
bool Image::SaveToStream(Stream& stream, const std::string& format, const ImageParams& params) bool Image::SaveToStream(Stream& stream, const std::string& format, const ImageParams& params)
{ {
return ImageSaver::SaveToStream(*this, stream, format, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetImageSaver().SaveToStream(*this, stream, format, params);
} }
void Image::SetLevelCount(UInt8 levelCount) void Image::SetLevelCount(UInt8 levelCount)
@ -1227,7 +1229,7 @@ namespace Nz
return false; return false;
} }
unsigned int depth = (m_sharedImage->type == ImageType_Cubemap) ? 6 : m_sharedImage->depth; unsigned int depth = (m_sharedImage->type == ImageType::Cubemap) ? 6 : m_sharedImage->depth;
if (z >= depth) if (z >= depth)
{ {
NazaraError("Z value exceeds depth (" + NumberToString(z) + " >= " + NumberToString(depth) + ')'); NazaraError("Z value exceeds depth (" + NumberToString(z) + " >= " + NumberToString(depth) + ')');
@ -1237,7 +1239,7 @@ namespace Nz
UInt8* pixel = GetPixelPtr(m_sharedImage->levels[0].get(), PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format), x, y, z, m_sharedImage->width, m_sharedImage->height); UInt8* pixel = GetPixelPtr(m_sharedImage->levels[0].get(), PixelFormatInfo::GetBytesPerPixel(m_sharedImage->format), x, y, z, m_sharedImage->width, m_sharedImage->height);
if (!PixelFormatInfo::Convert(PixelFormat_RGBA8, m_sharedImage->format, &color.r, pixel)) if (!PixelFormatInfo::Convert(PixelFormat::RGBA8, m_sharedImage->format, &color.r, pixel))
{ {
NazaraError("Failed to convert RGBA8 to image's format"); NazaraError("Failed to convert RGBA8 to image's format");
return false; return false;
@ -1312,9 +1314,9 @@ namespace Nz
return false; return false;
} }
unsigned int depth = (m_sharedImage->type == ImageType_Cubemap) ? 6 : GetLevelSize(m_sharedImage->depth, level); unsigned int depth = (m_sharedImage->type == ImageType::Cubemap) ? 6 : GetLevelSize(m_sharedImage->depth, level);
if (box.x+box.width > width || box.y+box.height > height || box.z+box.depth > depth || if (box.x+box.width > width || box.y+box.height > height || box.z+box.depth > depth ||
(m_sharedImage->type == ImageType_Cubemap && box.depth > 1)) // Nous n'autorisons pas de modifier plus d'une face du cubemap à la fois (m_sharedImage->type == ImageType::Cubemap && box.depth > 1)) // Nous n'autorisons pas de modifier plus d'une face du cubemap à la fois
{ {
NazaraError("Box dimensions are out of bounds"); NazaraError("Box dimensions are out of bounds");
return false; return false;
@ -1413,36 +1415,45 @@ namespace Nz
// Pour éviter que la profondeur ne soit comptée dans le calcul des niveaux // Pour éviter que la profondeur ne soit comptée dans le calcul des niveaux
switch (type) switch (type)
{ {
case ImageType_1D: case ImageType::E1D:
case ImageType_1D_Array: case ImageType::E1D_Array:
return GetMaxLevel(width, 1U, 1U); return GetMaxLevel(width, 1U, 1U);
case ImageType_2D: case ImageType::E2D:
case ImageType_2D_Array: case ImageType::E2D_Array:
case ImageType_Cubemap: case ImageType::Cubemap:
return GetMaxLevel(width, height, 1U); return GetMaxLevel(width, height, 1U);
case ImageType_3D: case ImageType::E3D:
return GetMaxLevel(width, height, depth); return GetMaxLevel(width, height, depth);
} }
NazaraError("Image type not handled (0x" + NumberToString(type, 16) + ')'); NazaraError("Image type not handled (0x" + NumberToString(UnderlyingCast(type), 16) + ')');
return 0; return 0;
} }
ImageRef Image::LoadFromFile(const std::filesystem::path& filePath, const ImageParams& params) std::shared_ptr<Image> Image::LoadFromFile(const std::filesystem::path& filePath, const ImageParams& params)
{ {
return ImageLoader::LoadFromFile(filePath, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetImageLoader().LoadFromFile(filePath, params);
} }
ImageRef Image::LoadFromMemory(const void* data, std::size_t size, const ImageParams& params) std::shared_ptr<Image> Image::LoadFromMemory(const void* data, std::size_t size, const ImageParams& params)
{ {
return ImageLoader::LoadFromMemory(data, size, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetImageLoader().LoadFromMemory(data, size, params);
} }
ImageRef Image::LoadFromStream(Stream& stream, const ImageParams& params) std::shared_ptr<Image> Image::LoadFromStream(Stream& stream, const ImageParams& params)
{ {
return ImageLoader::LoadFromStream(stream, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetImageLoader().LoadFromStream(stream, params);
} }
void Image::EnsureOwnership() void Image::EnsureOwnership()
@ -1476,33 +1487,5 @@ namespace Nz
m_sharedImage = &emptyImage; m_sharedImage = &emptyImage;
} }
bool Image::Initialize() Image::SharedImage Image::emptyImage(0, ImageType::E2D, PixelFormat::Undefined, Image::SharedImage::PixelContainer(), 0, 0, 0);
{
if (!ImageLibrary::Initialize())
{
NazaraError("Failed to initialise library");
return false;
}
if (!ImageManager::Initialize())
{
NazaraError("Failed to initialise manager");
return false;
}
return true;
}
void Image::Uninitialize()
{
ImageManager::Uninitialize();
ImageLibrary::Uninitialize();
}
Image::SharedImage Image::emptyImage(0, ImageType_2D, PixelFormat_Undefined, Image::SharedImage::PixelContainer(), 0, 0, 0);
ImageLibrary::LibraryMap Image::s_library;
ImageLoader::LoaderList Image::s_loaders;
ImageManager::ManagerMap Image::s_managerMap;
ImageManager::ManagerParams Image::s_managerParameters;
ImageSaver::SaverList Image::s_savers;
} }

View File

@ -13,13 +13,13 @@
namespace Nz namespace Nz
{ {
IndexBuffer::IndexBuffer(bool largeIndices, BufferRef buffer) IndexBuffer::IndexBuffer(bool largeIndices, std::shared_ptr<Buffer> buffer)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorFlag_ThrowException, true);
Reset(largeIndices, std::move(buffer)); Reset(largeIndices, std::move(buffer));
} }
IndexBuffer::IndexBuffer(bool largeIndices, BufferRef buffer, std::size_t offset, std::size_t size) IndexBuffer::IndexBuffer(bool largeIndices, std::shared_ptr<Buffer> buffer, std::size_t offset, std::size_t size)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorFlag_ThrowException, true);
Reset(largeIndices, std::move(buffer), offset, size); Reset(largeIndices, std::move(buffer), offset, size);
@ -31,24 +31,9 @@ namespace Nz
Reset(largeIndices, length, storage, usage); Reset(largeIndices, length, storage, usage);
} }
IndexBuffer::IndexBuffer(const IndexBuffer& indexBuffer) :
RefCounted(),
m_buffer(indexBuffer.m_buffer),
m_endOffset(indexBuffer.m_endOffset),
m_indexCount(indexBuffer.m_indexCount),
m_startOffset(indexBuffer.m_startOffset),
m_largeIndices(indexBuffer.m_largeIndices)
{
}
IndexBuffer::~IndexBuffer()
{
OnIndexBufferRelease(this);
}
unsigned int IndexBuffer::ComputeCacheMissCount() const unsigned int IndexBuffer::ComputeCacheMissCount() const
{ {
IndexMapper mapper(this); IndexMapper mapper(*this);
return Nz::ComputeCacheMissCount(mapper.begin(), m_indexCount); return Nz::ComputeCacheMissCount(mapper.begin(), m_indexCount);
} }
@ -86,27 +71,27 @@ namespace Nz
void IndexBuffer::Optimize() void IndexBuffer::Optimize()
{ {
IndexMapper mapper(this); IndexMapper mapper(*this);
OptimizeIndices(mapper.begin(), m_indexCount); OptimizeIndices(mapper.begin(), m_indexCount);
} }
void IndexBuffer::Reset() void IndexBuffer::Reset()
{ {
m_buffer.Reset(); m_buffer.reset();
} }
void IndexBuffer::Reset(bool largeIndices, BufferRef buffer) void IndexBuffer::Reset(bool largeIndices, std::shared_ptr<Buffer> buffer)
{ {
NazaraAssert(buffer && buffer->IsValid(), "Invalid buffer"); NazaraAssert(buffer && buffer->IsValid(), "Invalid buffer");
Reset(largeIndices, buffer, 0, buffer->GetSize()); Reset(largeIndices, buffer, 0, buffer->GetSize());
} }
void IndexBuffer::Reset(bool largeIndices, BufferRef buffer, std::size_t offset, std::size_t size) void IndexBuffer::Reset(bool largeIndices, std::shared_ptr<Buffer> buffer, std::size_t offset, std::size_t size)
{ {
NazaraAssert(buffer && buffer->IsValid(), "Invalid buffer"); NazaraAssert(buffer && buffer->IsValid(), "Invalid buffer");
NazaraAssert(buffer->GetType() == BufferType_Index, "Buffer must be an index buffer"); NazaraAssert(buffer->GetType() == BufferType::Index, "Buffer must be an index buffer");
NazaraAssert(size > 0, "Invalid size"); NazaraAssert(size > 0, "Invalid size");
NazaraAssert(offset + size > buffer->GetSize(), "Virtual buffer exceed buffer bounds"); NazaraAssert(offset + size > buffer->GetSize(), "Virtual buffer exceed buffer bounds");
@ -128,7 +113,7 @@ namespace Nz
m_largeIndices = largeIndices; m_largeIndices = largeIndices;
m_startOffset = 0; m_startOffset = 0;
m_buffer = Buffer::New(BufferType_Index, m_endOffset, storage, usage); m_buffer = std::make_shared<Buffer>(BufferType::Index, m_endOffset, storage, usage);
} }
void IndexBuffer::Reset(const IndexBuffer& indexBuffer) void IndexBuffer::Reset(const IndexBuffer& indexBuffer)
@ -144,11 +129,4 @@ namespace Nz
{ {
m_buffer->Unmap(); m_buffer->Unmap();
} }
IndexBuffer& IndexBuffer::operator=(const IndexBuffer& indexBuffer)
{
Reset(indexBuffer);
return *this;
}
} }

View File

@ -49,67 +49,50 @@ namespace Nz
} }
} }
IndexMapper::IndexMapper(IndexBuffer* indexBuffer, BufferAccess access, std::size_t indexCount) : IndexMapper::IndexMapper(IndexBuffer& indexBuffer, BufferAccess access, std::size_t indexCount) :
m_indexCount((indexCount != 0) ? indexCount : indexBuffer->GetIndexCount()) m_indexCount((indexCount != 0) ? indexCount : indexBuffer.GetIndexCount())
{ {
NazaraAssert(indexCount != 0 || indexBuffer, "Invalid index count with invalid index buffer"); if (!m_mapper.Map(indexBuffer, access))
NazaraError("Failed to map buffer"); ///TODO: Unexcepted
if (indexBuffer) if (indexBuffer.HasLargeIndices())
{ {
if (!m_mapper.Map(indexBuffer, access)) m_getter = Getter32;
NazaraError("Failed to map buffer"); ///TODO: Unexcepted if (access != BufferAccess::ReadOnly)
m_setter = Setter32;
if (indexBuffer->HasLargeIndices())
{
m_getter = Getter32;
if (access != BufferAccess_ReadOnly)
m_setter = Setter32;
else
m_setter = SetterError;
}
else else
{ m_setter = SetterError;
m_getter = Getter16;
if (access != BufferAccess_ReadOnly)
m_setter = Setter16;
else
m_setter = SetterError;
}
} }
else else
{ {
m_getter = GetterSequential; m_getter = Getter16;
m_setter = SetterError; if (access != BufferAccess::ReadOnly)
m_setter = Setter16;
else
m_setter = SetterError;
} }
} }
IndexMapper::IndexMapper(SubMesh* subMesh, BufferAccess access) : IndexMapper::IndexMapper(SubMesh& subMesh, BufferAccess access) :
IndexMapper(subMesh->GetIndexBuffer(), access, (subMesh->GetIndexBuffer()) ? 0 : subMesh->GetVertexCount()) IndexMapper(*subMesh.GetIndexBuffer(), access, (subMesh.GetIndexBuffer()) ? 0 : subMesh.GetVertexCount())
{ {
} }
IndexMapper::IndexMapper(const IndexBuffer* indexBuffer, BufferAccess access, std::size_t indexCount) : IndexMapper::IndexMapper(const IndexBuffer& indexBuffer, BufferAccess access, std::size_t indexCount) :
m_setter(SetterError), m_setter(SetterError),
m_indexCount((indexCount != 0) ? indexCount : indexBuffer->GetIndexCount()) m_indexCount((indexCount != 0) ? indexCount : indexBuffer.GetIndexCount())
{ {
NazaraAssert(indexCount != 0 || indexBuffer, "Invalid index count with invalid index buffer"); if (!m_mapper.Map(indexBuffer, access))
NazaraError("Failed to map buffer"); ///TODO: Unexcepted
if (indexBuffer) if (indexBuffer.HasLargeIndices())
{ m_getter = Getter32;
if (!m_mapper.Map(indexBuffer, access))
NazaraError("Failed to map buffer"); ///TODO: Unexcepted
if (indexBuffer->HasLargeIndices())
m_getter = Getter32;
else
m_getter = Getter16;
}
else else
m_getter = GetterSequential; m_getter = Getter16;
} }
IndexMapper::IndexMapper(const SubMesh* subMesh, BufferAccess access) : IndexMapper::IndexMapper(const SubMesh& subMesh, BufferAccess access) :
IndexMapper(subMesh->GetIndexBuffer(), access, (subMesh->GetIndexBuffer()) ? 0 : subMesh->GetVertexCount()) IndexMapper(*subMesh.GetIndexBuffer(), access, (subMesh.GetIndexBuffer()) ? 0 : subMesh.GetVertexCount())
{ {
} }

View File

@ -14,6 +14,7 @@
#include <Nazara/Utility/Skeleton.hpp> #include <Nazara/Utility/Skeleton.hpp>
#include <Nazara/Utility/StaticMesh.hpp> #include <Nazara/Utility/StaticMesh.hpp>
#include <Nazara/Utility/SubMesh.hpp> #include <Nazara/Utility/SubMesh.hpp>
#include <Nazara/Utility/Utility.hpp>
#include <Nazara/Utility/VertexMapper.hpp> #include <Nazara/Utility/VertexMapper.hpp>
#include <limits> #include <limits>
#include <memory> #include <memory>
@ -25,7 +26,7 @@ namespace Nz
MeshParams::MeshParams() MeshParams::MeshParams()
{ {
if (!Buffer::IsStorageSupported(storage)) if (!Buffer::IsStorageSupported(storage))
storage = DataStorage_Software; storage = DataStorage::Software;
} }
bool MeshParams::IsValid() const bool MeshParams::IsValid() const
@ -48,7 +49,7 @@ namespace Nz
return false; return false;
} }
if (!vertexDeclaration->HasComponent(VertexComponent_Position)) if (!vertexDeclaration->HasComponent(VertexComponent::Position))
{ {
NazaraError("Vertex declaration must contains a vertex position"); NazaraError("Vertex declaration must contains a vertex position");
return false; return false;
@ -58,7 +59,7 @@ namespace Nz
} }
void Mesh::AddSubMesh(SubMesh* subMesh) void Mesh::AddSubMesh(std::shared_ptr<SubMesh> subMesh)
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
NazaraAssert(subMesh, "Invalid submesh"); NazaraAssert(subMesh, "Invalid submesh");
@ -66,13 +67,13 @@ namespace Nz
m_subMeshes.emplace_back(); m_subMeshes.emplace_back();
SubMeshData& subMeshData = m_subMeshes.back(); SubMeshData& subMeshData = m_subMeshes.back();
subMeshData.subMesh = subMesh; subMeshData.subMesh = std::move(subMesh);
subMeshData.onSubMeshInvalidated.Connect(subMesh->OnSubMeshInvalidateAABB, [this](const SubMesh* /*subMesh*/) { InvalidateAABB(); }); subMeshData.onSubMeshInvalidated.Connect(subMeshData.subMesh->OnSubMeshInvalidateAABB, [this](const SubMesh* /*subMesh*/) { InvalidateAABB(); });
InvalidateAABB(); InvalidateAABB();
} }
void Mesh::AddSubMesh(const std::string& identifier, SubMesh* subMesh) void Mesh::AddSubMesh(const std::string& identifier, std::shared_ptr<SubMesh> subMesh)
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
NazaraAssert(!identifier.empty(), "Identifier is empty"); NazaraAssert(!identifier.empty(), "Identifier is empty");
@ -82,26 +83,26 @@ namespace Nz
std::size_t index = m_subMeshes.size(); std::size_t index = m_subMeshes.size();
AddSubMesh(subMesh); AddSubMesh(std::move(subMesh));
m_subMeshMap[identifier] = static_cast<std::size_t>(index); m_subMeshMap[identifier] = static_cast<std::size_t>(index);
} }
SubMesh* Mesh::BuildSubMesh(const Primitive& primitive, const MeshParams& params) std::shared_ptr<SubMesh> Mesh::BuildSubMesh(const Primitive& primitive, const MeshParams& params)
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
NazaraAssert(m_animationType == AnimationType_Static, "Submesh building only works for static meshes"); NazaraAssert(m_animationType == AnimationType::Static, "Submesh building only works for static meshes");
NazaraAssert(params.IsValid(), "Invalid parameters"); NazaraAssert(params.IsValid(), "Invalid parameters");
NazaraAssert(params.vertexDeclaration->HasComponentOfType<Vector3f>(VertexComponent_Position), "The vertex declaration doesn't have a Vector3 position component"); NazaraAssert(params.vertexDeclaration->HasComponentOfType<Vector3f>(VertexComponent::Position), "The vertex declaration doesn't have a Vector3 position component");
Boxf aabb; Boxf aabb;
IndexBufferRef indexBuffer; std::shared_ptr<IndexBuffer> indexBuffer;
VertexBufferRef vertexBuffer; std::shared_ptr<VertexBuffer> vertexBuffer;
Matrix4f matrix(primitive.matrix); Matrix4f matrix(primitive.matrix);
matrix *= params.matrix; matrix *= params.matrix;
VertexDeclaration* declaration = params.vertexDeclaration; const std::shared_ptr<VertexDeclaration>& declaration = params.vertexDeclaration;
switch (primitive.type) switch (primitive.type)
{ {
@ -111,18 +112,18 @@ namespace Nz
unsigned int vertexCount; unsigned int vertexCount;
ComputeBoxIndexVertexCount(primitive.box.subdivision, &indexCount, &vertexCount); ComputeBoxIndexVertexCount(primitive.box.subdivision, &indexCount, &vertexCount);
indexBuffer = IndexBuffer::New(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags); indexBuffer = std::make_shared<IndexBuffer>(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags);
vertexBuffer = VertexBuffer::New(declaration, vertexCount, params.storage, params.vertexBufferFlags); vertexBuffer = std::make_shared<VertexBuffer>(declaration, vertexCount, params.storage, params.vertexBufferFlags);
VertexMapper vertexMapper(vertexBuffer, BufferAccess_WriteOnly); VertexMapper vertexMapper(*vertexBuffer, BufferAccess::WriteOnly);
VertexPointers pointers; VertexPointers pointers;
pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Normal); pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Normal);
pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Tangent); pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Tangent);
pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord); pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord);
IndexMapper indexMapper(indexBuffer, BufferAccess_WriteOnly); IndexMapper indexMapper(*indexBuffer, BufferAccess::WriteOnly);
GenerateBox(primitive.box.lengths, primitive.box.subdivision, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb); GenerateBox(primitive.box.lengths, primitive.box.subdivision, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb);
break; break;
} }
@ -133,18 +134,18 @@ namespace Nz
unsigned int vertexCount; unsigned int vertexCount;
ComputeConeIndexVertexCount(primitive.cone.subdivision, &indexCount, &vertexCount); ComputeConeIndexVertexCount(primitive.cone.subdivision, &indexCount, &vertexCount);
indexBuffer = IndexBuffer::New(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags); indexBuffer = std::make_shared<IndexBuffer>(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags);
vertexBuffer = VertexBuffer::New(declaration, vertexCount, params.storage, params.vertexBufferFlags); vertexBuffer = std::make_shared<VertexBuffer>(declaration, vertexCount, params.storage, params.vertexBufferFlags);
VertexMapper vertexMapper(vertexBuffer, BufferAccess_WriteOnly); VertexMapper vertexMapper(*vertexBuffer, BufferAccess::WriteOnly);
VertexPointers pointers; VertexPointers pointers;
pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Normal); pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Normal);
pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Tangent); pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Tangent);
pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord); pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord);
IndexMapper indexMapper(indexBuffer, BufferAccess_WriteOnly); IndexMapper indexMapper(*indexBuffer, BufferAccess::WriteOnly);
GenerateCone(primitive.cone.length, primitive.cone.radius, primitive.cone.subdivision, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb); GenerateCone(primitive.cone.length, primitive.cone.radius, primitive.cone.subdivision, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb);
break; break;
} }
@ -155,18 +156,18 @@ namespace Nz
unsigned int vertexCount; unsigned int vertexCount;
ComputePlaneIndexVertexCount(primitive.plane.subdivision, &indexCount, &vertexCount); ComputePlaneIndexVertexCount(primitive.plane.subdivision, &indexCount, &vertexCount);
indexBuffer = IndexBuffer::New(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags); indexBuffer = std::make_shared<IndexBuffer>(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags);
vertexBuffer = VertexBuffer::New(declaration, vertexCount, params.storage, params.vertexBufferFlags); vertexBuffer = std::make_shared<VertexBuffer>(declaration, vertexCount, params.storage, params.vertexBufferFlags);
VertexMapper vertexMapper(vertexBuffer, BufferAccess_WriteOnly); VertexMapper vertexMapper(*vertexBuffer, BufferAccess::WriteOnly);
VertexPointers pointers; VertexPointers pointers;
pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Normal); pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Normal);
pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Tangent); pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Tangent);
pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord); pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord);
IndexMapper indexMapper(indexBuffer, BufferAccess_WriteOnly); IndexMapper indexMapper(*indexBuffer, BufferAccess::WriteOnly);
GeneratePlane(primitive.plane.subdivision, primitive.plane.size, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb); GeneratePlane(primitive.plane.subdivision, primitive.plane.size, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb);
break; break;
} }
@ -181,18 +182,18 @@ namespace Nz
unsigned int vertexCount; unsigned int vertexCount;
ComputeCubicSphereIndexVertexCount(primitive.sphere.cubic.subdivision, &indexCount, &vertexCount); ComputeCubicSphereIndexVertexCount(primitive.sphere.cubic.subdivision, &indexCount, &vertexCount);
indexBuffer = IndexBuffer::New(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags); indexBuffer = std::make_shared<IndexBuffer>(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags);
vertexBuffer = VertexBuffer::New(declaration, vertexCount, params.storage, params.vertexBufferFlags); vertexBuffer = std::make_shared<VertexBuffer>(declaration, vertexCount, params.storage, params.vertexBufferFlags);
VertexMapper vertexMapper(vertexBuffer, BufferAccess_ReadWrite); VertexMapper vertexMapper(*vertexBuffer, BufferAccess::ReadWrite);
VertexPointers pointers; VertexPointers pointers;
pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Normal); pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Normal);
pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Tangent); pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Tangent);
pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord); pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord);
IndexMapper indexMapper(indexBuffer, BufferAccess_WriteOnly); IndexMapper indexMapper(*indexBuffer, BufferAccess::WriteOnly);
GenerateCubicSphere(primitive.sphere.size, primitive.sphere.cubic.subdivision, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb); GenerateCubicSphere(primitive.sphere.size, primitive.sphere.cubic.subdivision, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb);
break; break;
} }
@ -203,18 +204,18 @@ namespace Nz
unsigned int vertexCount; unsigned int vertexCount;
ComputeIcoSphereIndexVertexCount(primitive.sphere.ico.recursionLevel, &indexCount, &vertexCount); ComputeIcoSphereIndexVertexCount(primitive.sphere.ico.recursionLevel, &indexCount, &vertexCount);
indexBuffer = IndexBuffer::New(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags); indexBuffer = std::make_shared<IndexBuffer>(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags);
vertexBuffer = VertexBuffer::New(declaration, vertexCount, params.storage, params.vertexBufferFlags); vertexBuffer = std::make_shared<VertexBuffer>(declaration, vertexCount, params.storage, params.vertexBufferFlags);
VertexMapper vertexMapper(vertexBuffer, BufferAccess_WriteOnly); VertexMapper vertexMapper(*vertexBuffer, BufferAccess::WriteOnly);
VertexPointers pointers; VertexPointers pointers;
pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Normal); pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Normal);
pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Tangent); pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Tangent);
pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord); pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord);
IndexMapper indexMapper(indexBuffer, BufferAccess_WriteOnly); IndexMapper indexMapper(*indexBuffer, BufferAccess::WriteOnly);
GenerateIcoSphere(primitive.sphere.size, primitive.sphere.ico.recursionLevel, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb); GenerateIcoSphere(primitive.sphere.size, primitive.sphere.ico.recursionLevel, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb);
break; break;
} }
@ -225,18 +226,18 @@ namespace Nz
unsigned int vertexCount; unsigned int vertexCount;
ComputeUvSphereIndexVertexCount(primitive.sphere.uv.sliceCount, primitive.sphere.uv.stackCount, &indexCount, &vertexCount); ComputeUvSphereIndexVertexCount(primitive.sphere.uv.sliceCount, primitive.sphere.uv.stackCount, &indexCount, &vertexCount);
indexBuffer = IndexBuffer::New(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags); indexBuffer = std::make_shared<IndexBuffer>(vertexCount > std::numeric_limits<UInt16>::max(), indexCount, params.storage, params.indexBufferFlags);
vertexBuffer = VertexBuffer::New(declaration, vertexCount, params.storage, params.vertexBufferFlags); vertexBuffer = std::make_shared<VertexBuffer>(declaration, vertexCount, params.storage, params.vertexBufferFlags);
VertexMapper vertexMapper(vertexBuffer, BufferAccess_WriteOnly); VertexMapper vertexMapper(*vertexBuffer, BufferAccess::WriteOnly);
VertexPointers pointers; VertexPointers pointers;
pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Normal); pointers.normalPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Normal);
pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Position); pointers.positionPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Position);
pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent_Tangent); pointers.tangentPtr = vertexMapper.GetComponentPtr<Vector3f>(VertexComponent::Tangent);
pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent_TexCoord); pointers.uvPtr = vertexMapper.GetComponentPtr<Vector2f>(VertexComponent::TexCoord);
IndexMapper indexMapper(indexBuffer, BufferAccess_WriteOnly); IndexMapper indexMapper(*indexBuffer, BufferAccess::WriteOnly);
GenerateUvSphere(primitive.sphere.size, primitive.sphere.uv.sliceCount, primitive.sphere.uv.stackCount, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb); GenerateUvSphere(primitive.sphere.size, primitive.sphere.uv.sliceCount, primitive.sphere.uv.stackCount, matrix, primitive.textureCoords, pointers, indexMapper.begin(), &aabb);
break; break;
} }
@ -248,7 +249,7 @@ namespace Nz
if (params.optimizeIndexBuffers) if (params.optimizeIndexBuffers)
indexBuffer->Optimize(); indexBuffer->Optimize();
StaticMeshRef subMesh = StaticMesh::New(vertexBuffer, indexBuffer); std::shared_ptr<StaticMesh> subMesh = std::make_shared<StaticMesh>(vertexBuffer, indexBuffer);
subMesh->SetAABB(aabb); subMesh->SetAABB(aabb);
AddSubMesh(subMesh); AddSubMesh(subMesh);
@ -265,7 +266,7 @@ namespace Nz
{ {
Destroy(); Destroy();
m_animationType = AnimationType_Skeletal; m_animationType = AnimationType::Skeletal;
m_jointCount = jointCount; m_jointCount = jointCount;
if (!m_skeleton.Create(jointCount)) if (!m_skeleton.Create(jointCount))
{ {
@ -282,7 +283,7 @@ namespace Nz
{ {
Destroy(); Destroy();
m_animationType = AnimationType_Static; m_animationType = AnimationType::Static;
m_isValid = true; m_isValid = true;
return true; return true;
@ -292,8 +293,6 @@ namespace Nz
{ {
if (m_isValid) if (m_isValid)
{ {
OnMeshDestroy(this);
m_animationPath.clear(); m_animationPath.clear();
m_materialData.clear(); m_materialData.clear();
m_materialData.resize(1); m_materialData.resize(1);
@ -368,7 +367,7 @@ namespace Nz
std::size_t Mesh::GetJointCount() const std::size_t Mesh::GetJointCount() const
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
NazaraAssert(m_animationType == AnimationType_Skeletal, "Mesh is not skeletal"); NazaraAssert(m_animationType == AnimationType::Skeletal, "Mesh is not skeletal");
return m_jointCount; return m_jointCount;
} }
@ -399,7 +398,7 @@ namespace Nz
Skeleton* Mesh::GetSkeleton() Skeleton* Mesh::GetSkeleton()
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
NazaraAssert(m_animationType == AnimationType_Skeletal, "Mesh is not skeletal"); NazaraAssert(m_animationType == AnimationType::Skeletal, "Mesh is not skeletal");
return &m_skeleton; return &m_skeleton;
} }
@ -407,12 +406,12 @@ namespace Nz
const Skeleton* Mesh::GetSkeleton() const const Skeleton* Mesh::GetSkeleton() const
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
NazaraAssert(m_animationType == AnimationType_Skeletal, "Mesh is not skeletal"); NazaraAssert(m_animationType == AnimationType::Skeletal, "Mesh is not skeletal");
return &m_skeleton; return &m_skeleton;
} }
SubMesh* Mesh::GetSubMesh(const std::string& identifier) const std::shared_ptr<SubMesh>& Mesh::GetSubMesh(const std::string& identifier) const
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
@ -422,25 +421,7 @@ namespace Nz
return m_subMeshes[it->second].subMesh; return m_subMeshes[it->second].subMesh;
} }
SubMesh* Mesh::GetSubMesh(std::size_t index) const std::shared_ptr<SubMesh>& Mesh::GetSubMesh(std::size_t index) const
{
NazaraAssert(m_isValid, "Mesh should be created first");
NazaraAssert(index < m_subMeshes.size(), "Submesh index out of range");
return m_subMeshes[index].subMesh;
}
const SubMesh* Mesh::GetSubMesh(const std::string& identifier) const
{
NazaraAssert(m_isValid, "Mesh should be created first");
auto it = m_subMeshMap.find(identifier);
NazaraAssert(it != m_subMeshMap.end(), "SubMesh " + identifier + " not found");
return m_subMeshes[it->second].subMesh;
}
const SubMesh* Mesh::GetSubMesh(std::size_t index) const
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
NazaraAssert(index < m_subMeshes.size(), "Submesh index out of range"); NazaraAssert(index < m_subMeshes.size(), "Submesh index out of range");
@ -514,7 +495,7 @@ namespace Nz
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
return m_animationType != AnimationType_Static; return m_animationType != AnimationType::Static;
} }
bool Mesh::IsValid() const bool Mesh::IsValid() const
@ -525,7 +506,7 @@ namespace Nz
void Mesh::Recenter() void Mesh::Recenter()
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
NazaraAssert(m_animationType == AnimationType_Static, "Mesh is not static"); NazaraAssert(m_animationType == AnimationType::Static, "Mesh is not static");
// The center of our mesh is the center of our *global* AABB // The center of our mesh is the center of our *global* AABB
Vector3f center = GetAABB().GetCenter(); Vector3f center = GetAABB().GetCenter();
@ -534,7 +515,7 @@ namespace Nz
{ {
StaticMesh& staticMesh = static_cast<StaticMesh&>(*data.subMesh); StaticMesh& staticMesh = static_cast<StaticMesh&>(*data.subMesh);
BufferMapper<VertexBuffer> mapper(staticMesh.GetVertexBuffer(), BufferAccess_ReadWrite); BufferMapper<VertexBuffer> mapper(*staticMesh.GetVertexBuffer(), BufferAccess::ReadWrite);
MeshVertex* vertices = static_cast<MeshVertex*>(mapper.GetPointer()); MeshVertex* vertices = static_cast<MeshVertex*>(mapper.GetPointer());
std::size_t vertexCount = staticMesh.GetVertexCount(); std::size_t vertexCount = staticMesh.GetVertexCount();
@ -577,12 +558,18 @@ namespace Nz
bool Mesh::SaveToFile(const std::filesystem::path& filePath, const MeshParams& params) bool Mesh::SaveToFile(const std::filesystem::path& filePath, const MeshParams& params)
{ {
return MeshSaver::SaveToFile(*this, filePath, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetMeshSaver().SaveToFile(*this, filePath, params);
} }
bool Mesh::SaveToStream(Stream& stream, const std::string& format, const MeshParams& params) bool Mesh::SaveToStream(Stream& stream, const std::string& format, const MeshParams& params)
{ {
return MeshSaver::SaveToStream(*this, stream, format, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetMeshSaver().SaveToStream(*this, stream, format, params);
} }
void Mesh::SetAnimation(const std::filesystem::path& animationPath) void Mesh::SetAnimation(const std::filesystem::path& animationPath)
@ -614,7 +601,7 @@ namespace Nz
if (matIndex >= matCount) if (matIndex >= matCount)
{ {
data.subMesh->SetMaterialIndex(0); // To prevent a crash data.subMesh->SetMaterialIndex(0); // To prevent a crash
NazaraWarning("SubMesh " + PointerToString(data.subMesh) + " material index is over mesh new material count (" + NumberToString(matIndex) + " >= " + NumberToString(matCount) + "), setting it to first material"); NazaraWarning("SubMesh " + PointerToString(data.subMesh.get()) + " material index is over mesh new material count (" + NumberToString(matIndex) + " >= " + NumberToString(matCount) + "), setting it to first material");
} }
} }
#endif #endif
@ -623,13 +610,13 @@ namespace Nz
void Mesh::Transform(const Matrix4f& matrix) void Mesh::Transform(const Matrix4f& matrix)
{ {
NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_isValid, "Mesh should be created first");
NazaraAssert(m_animationType == AnimationType_Static, "Mesh is not static"); NazaraAssert(m_animationType == AnimationType::Static, "Mesh is not static");
for (SubMeshData& data : m_subMeshes) for (SubMeshData& data : m_subMeshes)
{ {
StaticMesh& staticMesh = static_cast<StaticMesh&>(*data.subMesh); StaticMesh& staticMesh = static_cast<StaticMesh&>(*data.subMesh);
BufferMapper<VertexBuffer> mapper(staticMesh.GetVertexBuffer(), BufferAccess_ReadWrite); BufferMapper<VertexBuffer> mapper(*staticMesh.GetVertexBuffer(), BufferAccess::ReadWrite);
MeshVertex* vertices = static_cast<MeshVertex*>(mapper.GetPointer()); MeshVertex* vertices = static_cast<MeshVertex*>(mapper.GetPointer());
Boxf aabb(vertices->position.x, vertices->position.y, vertices->position.z, 0.f, 0.f, 0.f); Boxf aabb(vertices->position.x, vertices->position.y, vertices->position.z, 0.f, 0.f, 0.f);
@ -647,47 +634,27 @@ namespace Nz
} }
} }
MeshRef Mesh::LoadFromFile(const std::filesystem::path& filePath, const MeshParams& params) std::shared_ptr<Mesh> Mesh::LoadFromFile(const std::filesystem::path& filePath, const MeshParams& params)
{ {
return MeshLoader::LoadFromFile(filePath, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetMeshLoader().LoadFromFile(filePath, params);
} }
MeshRef Mesh::LoadFromMemory(const void* data, std::size_t size, const MeshParams& params) std::shared_ptr<Mesh> Mesh::LoadFromMemory(const void* data, std::size_t size, const MeshParams& params)
{ {
return MeshLoader::LoadFromMemory(data, size, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetMeshLoader().LoadFromMemory(data, size, params);
} }
MeshRef Mesh::LoadFromStream(Stream& stream, const MeshParams& params) std::shared_ptr<Mesh> Mesh::LoadFromStream(Stream& stream, const MeshParams& params)
{ {
return MeshLoader::LoadFromStream(stream, params); Utility* utility = Utility::Instance();
NazaraAssert(utility, "Utility module has not been initialized");
return utility->GetMeshLoader().LoadFromStream(stream, params);
} }
bool Mesh::Initialize()
{
if (!MeshLibrary::Initialize())
{
NazaraError("Failed to initialise library");
return false;
}
if (!MeshManager::Initialize())
{
NazaraError("Failed to initialise manager");
return false;
}
return true;
}
void Mesh::Uninitialize()
{
MeshManager::Uninitialize();
MeshLibrary::Uninitialize();
}
MeshLibrary::LibraryMap Mesh::s_library;
MeshLoader::LoaderList Mesh::s_loaders;
MeshManager::ManagerMap Mesh::s_managerMap;
MeshManager::ManagerParams Mesh::s_managerParameters;
MeshSaver::SaverList Mesh::s_savers;
} }

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