From 3d223211090a00177d613f1f6d411b2131b1f3d5 Mon Sep 17 00:00:00 2001 From: Lynix Date: Sun, 23 Feb 2020 00:42:22 +0100 Subject: [PATCH] Big f***ing cleanup part 1 --- SDK/include/NDK/Lua/LuaBinding_Core.hpp | 2 - SDK/include/NDK/LuaAPI.inl | 2 +- SDK/src/NDK/Lua/LuaBinding_Audio.cpp | 8 +- SDK/src/NDK/Lua/LuaBinding_Core.cpp | 84 +-- SDK/src/NDK/Lua/LuaBinding_Graphics.cpp | 26 +- examples/DopplerEffect/main.cpp | 4 +- examples/MeshInfos/main.cpp | 29 +- examples/Particles/main.cpp | 2 +- include/Nazara/Audio/Music.hpp | 2 +- include/Nazara/Audio/Sound.hpp | 2 +- include/Nazara/Audio/SoundBuffer.hpp | 2 +- include/Nazara/Audio/SoundStream.hpp | 5 +- include/Nazara/Core.hpp | 9 +- include/Nazara/Core/Algorithm.hpp | 27 + include/Nazara/Core/Clock.hpp | 8 - include/Nazara/Core/ConditionVariable.hpp | 42 -- include/Nazara/Core/ConditionVariable.inl | 14 - include/Nazara/Core/Config.hpp | 11 - include/Nazara/Core/Directory.hpp | 82 -- include/Nazara/Core/DynLib.hpp | 24 +- include/Nazara/Core/Error.hpp | 4 +- include/Nazara/Core/File.hpp | 58 +- include/Nazara/Core/File.inl | 4 +- include/Nazara/Core/FileLogger.hpp | 6 +- include/Nazara/Core/LockGuard.hpp | 34 - include/Nazara/Core/LockGuard.inl | 83 --- include/Nazara/Core/Log.hpp | 6 - include/Nazara/Core/Mutex.hpp | 41 - include/Nazara/Core/Mutex.inl | 17 - include/Nazara/Core/PluginManager.hpp | 23 +- include/Nazara/Core/RefCounted.hpp | 6 - include/Nazara/Core/Resource.hpp | 8 +- include/Nazara/Core/ResourceLoader.hpp | 10 +- include/Nazara/Core/ResourceLoader.inl | 19 +- include/Nazara/Core/ResourceManager.hpp | 17 +- include/Nazara/Core/ResourceManager.inl | 18 +- include/Nazara/Core/ResourceSaver.hpp | 15 +- include/Nazara/Core/ResourceSaver.inl | 18 +- include/Nazara/Core/Semaphore.hpp | 40 - include/Nazara/Core/SparsePtr.hpp | 2 +- include/Nazara/Core/SparsePtr.inl | 2 +- include/Nazara/Core/Stream.hpp | 9 +- include/Nazara/Core/StringExt.hpp | 61 ++ include/Nazara/Core/StringExt.inl | 82 ++ include/Nazara/Core/Thread.hpp | 75 -- include/Nazara/Core/Thread.inl | 55 -- include/Nazara/Core/ThreadSafety.hpp | 23 - include/Nazara/Core/ThreadSafetyOff.hpp | 21 - include/Nazara/Graphics/Material.hpp | 23 +- include/Nazara/Graphics/Material.inl | 20 +- include/Nazara/Graphics/Model.hpp | 10 +- include/Nazara/Graphics/Sprite.hpp | 8 +- include/Nazara/Lua/LuaState.hpp | 5 +- include/Nazara/Lua/LuaState.inl | 15 + include/Nazara/Network/NetPacket.hpp | 4 +- include/Nazara/Platform/Window.hpp | 10 +- include/Nazara/Platform/Window.inl | 8 +- include/Nazara/Renderer/Shader.hpp | 3 +- include/Nazara/Renderer/ShaderStage.hpp | 3 +- include/Nazara/Renderer/Texture.hpp | 12 +- .../Renderer/UberShaderPreprocessor.hpp | 2 +- include/Nazara/Utility/Animation.hpp | 30 +- include/Nazara/Utility/Font.hpp | 2 +- .../Nazara/Utility/Formats/MD5MeshParser.hpp | 8 +- include/Nazara/Utility/Formats/MTLParser.hpp | 37 +- include/Nazara/Utility/Formats/MTLParser.inl | 16 +- include/Nazara/Utility/Formats/OBJParser.hpp | 55 +- include/Nazara/Utility/Formats/OBJParser.inl | 48 +- include/Nazara/Utility/Image.hpp | 12 +- include/Nazara/Utility/IndexBuffer.hpp | 34 +- include/Nazara/Utility/IndexBuffer.inl | 18 +- include/Nazara/Utility/Mesh.hpp | 56 +- include/Nazara/Utility/SkeletalMesh.hpp | 6 +- include/Nazara/Utility/Skeleton.hpp | 10 +- include/Nazara/Utility/StaticMesh.hpp | 6 +- include/Nazara/Utility/SubMesh.hpp | 10 +- include/Nazara/Utility/VertexBuffer.hpp | 34 +- include/Nazara/Utility/VertexBuffer.inl | 10 +- include/Nazara/Utility/VertexMapper.hpp | 4 +- include/Nazara/Utility/VertexMapper.inl | 4 +- plugins/Assimp/Plugin.cpp | 18 +- src/Nazara/Audio/Formats/sndfileLoader.cpp | 18 +- src/Nazara/Audio/Music.cpp | 90 ++- src/Nazara/Audio/OpenAL.cpp | 6 +- src/Nazara/Audio/Sound.cpp | 4 +- src/Nazara/Audio/SoundBuffer.cpp | 2 +- src/Nazara/Audio/SoundStream.cpp | 2 +- src/Nazara/Core/Clock.cpp | 16 - src/Nazara/Core/ConditionVariable.cpp | 105 --- src/Nazara/Core/Directory.cpp | 535 -------------- src/Nazara/Core/DynLib.cpp | 61 +- src/Nazara/Core/Error.cpp | 38 +- src/Nazara/Core/File.cpp | 475 +----------- src/Nazara/Core/FileLogger.cpp | 15 +- src/Nazara/Core/Mutex.cpp | 80 -- src/Nazara/Core/PluginManager.cpp | 62 +- .../Core/Posix/ConditionVariableImpl.cpp | 52 -- .../Core/Posix/ConditionVariableImpl.hpp | 36 - src/Nazara/Core/Posix/DirectoryImpl.cpp | 120 --- src/Nazara/Core/Posix/DirectoryImpl.hpp | 52 -- src/Nazara/Core/Posix/FileImpl.cpp | 126 +--- src/Nazara/Core/Posix/FileImpl.hpp | 13 +- src/Nazara/Core/Posix/MutexImpl.cpp | 38 - src/Nazara/Core/Posix/MutexImpl.hpp | 31 - src/Nazara/Core/Posix/SemaphoreImpl.cpp | 73 -- src/Nazara/Core/Posix/SemaphoreImpl.hpp | 31 - src/Nazara/Core/Posix/ThreadImpl.cpp | 78 -- src/Nazara/Core/Posix/ThreadImpl.hpp | 42 -- src/Nazara/Core/Resource.cpp | 4 +- src/Nazara/Core/Semaphore.cpp | 86 --- src/Nazara/Core/Stream.cpp | 28 +- src/Nazara/Core/StringExt.cpp | 226 ++++++ src/Nazara/Core/Thread.cpp | 280 ------- .../Core/Win32/ConditionVariableImpl.cpp | 84 --- .../Core/Win32/ConditionVariableImpl.hpp | 53 -- src/Nazara/Core/Win32/DirectoryImpl.cpp | 122 --- src/Nazara/Core/Win32/DirectoryImpl.hpp | 52 -- src/Nazara/Core/Win32/DynLibImpl.cpp | 31 +- src/Nazara/Core/Win32/DynLibImpl.hpp | 10 +- src/Nazara/Core/Win32/FileImpl.cpp | 124 +--- src/Nazara/Core/Win32/FileImpl.hpp | 14 +- src/Nazara/Core/Win32/MutexImpl.cpp | 38 - src/Nazara/Core/Win32/MutexImpl.hpp | 32 - src/Nazara/Core/Win32/SemaphoreImpl.cpp | 67 -- src/Nazara/Core/Win32/SemaphoreImpl.hpp | 31 - src/Nazara/Core/Win32/ThreadImpl.cpp | 122 --- src/Nazara/Core/Win32/ThreadImpl.hpp | 42 -- src/Nazara/Graphics/Formats/MeshLoader.cpp | 9 +- src/Nazara/Graphics/Material.cpp | 50 +- src/Nazara/Graphics/MaterialPipeline.cpp | 5 +- src/Nazara/Graphics/Model.cpp | 10 +- src/Nazara/Graphics/Sprite.cpp | 8 +- src/Nazara/Lua/LuaState.cpp | 4 +- src/Nazara/Network/NetPacket.cpp | 9 +- src/Nazara/Platform/Win32/WindowImpl.cpp | 37 +- src/Nazara/Platform/Win32/WindowImpl.hpp | 10 +- src/Nazara/Platform/Window.cpp | 24 +- src/Nazara/Renderer/RenderWindow.cpp | 4 +- src/Nazara/Renderer/Shader.cpp | 2 +- src/Nazara/Renderer/ShaderStage.cpp | 4 +- src/Nazara/Renderer/Texture.cpp | 12 +- .../Renderer/UberShaderPreprocessor.cpp | 4 +- src/Nazara/Renderer/Win32/ContextImpl.cpp | 7 +- src/Nazara/Utility/Animation.cpp | 40 +- src/Nazara/Utility/Font.cpp | 2 +- src/Nazara/Utility/Formats/DDSLoader.cpp | 2 +- src/Nazara/Utility/Formats/FreeTypeLoader.cpp | 19 +- src/Nazara/Utility/Formats/MD2Loader.cpp | 10 +- src/Nazara/Utility/Formats/MD5AnimLoader.cpp | 15 +- src/Nazara/Utility/Formats/MD5MeshLoader.cpp | 16 +- src/Nazara/Utility/Formats/MD5MeshParser.cpp | 93 ++- src/Nazara/Utility/Formats/MTLParser.cpp | 698 +++++++++++------- src/Nazara/Utility/Formats/OBJLoader.cpp | 92 +-- src/Nazara/Utility/Formats/OBJParser.cpp | 163 ++-- src/Nazara/Utility/Formats/OBJSaver.cpp | 64 +- src/Nazara/Utility/Formats/PCXLoader.cpp | 2 +- src/Nazara/Utility/Formats/STBLoader.cpp | 2 +- src/Nazara/Utility/Formats/STBSaver.cpp | 6 +- src/Nazara/Utility/Image.cpp | 12 +- src/Nazara/Utility/IndexBuffer.cpp | 22 +- src/Nazara/Utility/Mesh.cpp | 98 ++- src/Nazara/Utility/SkeletalMesh.cpp | 2 +- src/Nazara/Utility/Skeleton.cpp | 22 +- src/Nazara/Utility/StaticMesh.cpp | 2 +- src/Nazara/Utility/SubMesh.cpp | 18 +- src/Nazara/Utility/VertexBuffer.cpp | 34 +- tests/Engine/Audio/Music.cpp | 10 +- tests/Engine/Audio/Sound.cpp | 12 +- tests/Engine/Audio/SoundEmitter.cpp | 2 - tests/Engine/Core/Clock.cpp | 5 +- tests/Engine/Core/Directory.cpp | 34 - tests/Engine/Core/File.cpp | 25 +- tests/Engine/Network/TCP.cpp | 5 +- thirdparty/include/Utfcpp/utf8.h | 4 + thirdparty/include/Utfcpp/utf8/checked.h | 43 +- thirdparty/include/Utfcpp/utf8/core.h | 26 +- thirdparty/include/Utfcpp/utf8/cpp11.h | 103 +++ thirdparty/include/Utfcpp/utf8/unchecked.h | 71 +- 178 files changed, 2190 insertions(+), 5113 deletions(-) delete mode 100644 include/Nazara/Core/ConditionVariable.hpp delete mode 100644 include/Nazara/Core/ConditionVariable.inl delete mode 100644 include/Nazara/Core/Directory.hpp delete mode 100644 include/Nazara/Core/LockGuard.hpp delete mode 100644 include/Nazara/Core/LockGuard.inl delete mode 100644 include/Nazara/Core/Mutex.hpp delete mode 100644 include/Nazara/Core/Mutex.inl delete mode 100644 include/Nazara/Core/Semaphore.hpp create mode 100644 include/Nazara/Core/StringExt.hpp create mode 100644 include/Nazara/Core/StringExt.inl delete mode 100644 include/Nazara/Core/Thread.hpp delete mode 100644 include/Nazara/Core/Thread.inl delete mode 100644 include/Nazara/Core/ThreadSafety.hpp delete mode 100644 include/Nazara/Core/ThreadSafetyOff.hpp delete mode 100644 src/Nazara/Core/ConditionVariable.cpp delete mode 100644 src/Nazara/Core/Directory.cpp delete mode 100644 src/Nazara/Core/Mutex.cpp delete mode 100644 src/Nazara/Core/Posix/ConditionVariableImpl.cpp delete mode 100644 src/Nazara/Core/Posix/ConditionVariableImpl.hpp delete mode 100644 src/Nazara/Core/Posix/DirectoryImpl.cpp delete mode 100644 src/Nazara/Core/Posix/DirectoryImpl.hpp delete mode 100644 src/Nazara/Core/Posix/MutexImpl.cpp delete mode 100644 src/Nazara/Core/Posix/MutexImpl.hpp delete mode 100644 src/Nazara/Core/Posix/SemaphoreImpl.cpp delete mode 100644 src/Nazara/Core/Posix/SemaphoreImpl.hpp delete mode 100644 src/Nazara/Core/Posix/ThreadImpl.cpp delete mode 100644 src/Nazara/Core/Posix/ThreadImpl.hpp delete mode 100644 src/Nazara/Core/Semaphore.cpp create mode 100644 src/Nazara/Core/StringExt.cpp delete mode 100644 src/Nazara/Core/Thread.cpp delete mode 100644 src/Nazara/Core/Win32/ConditionVariableImpl.cpp delete mode 100644 src/Nazara/Core/Win32/ConditionVariableImpl.hpp delete mode 100644 src/Nazara/Core/Win32/DirectoryImpl.cpp delete mode 100644 src/Nazara/Core/Win32/DirectoryImpl.hpp delete mode 100644 src/Nazara/Core/Win32/MutexImpl.cpp delete mode 100644 src/Nazara/Core/Win32/MutexImpl.hpp delete mode 100644 src/Nazara/Core/Win32/SemaphoreImpl.cpp delete mode 100644 src/Nazara/Core/Win32/SemaphoreImpl.hpp delete mode 100644 src/Nazara/Core/Win32/ThreadImpl.cpp delete mode 100644 src/Nazara/Core/Win32/ThreadImpl.hpp delete mode 100644 tests/Engine/Core/Directory.cpp create mode 100644 thirdparty/include/Utfcpp/utf8/cpp11.h diff --git a/SDK/include/NDK/Lua/LuaBinding_Core.hpp b/SDK/include/NDK/Lua/LuaBinding_Core.hpp index 3149fdcc8..4277936e0 100644 --- a/SDK/include/NDK/Lua/LuaBinding_Core.hpp +++ b/SDK/include/NDK/Lua/LuaBinding_Core.hpp @@ -8,7 +8,6 @@ #define NDK_LUABINDING_CORE_HPP #include -#include #include #include #include @@ -24,7 +23,6 @@ namespace Ndk void Register(Nz::LuaState& state) override; Nz::LuaClass clock; - Nz::LuaClass directory; Nz::LuaClass file; Nz::LuaClass stream; }; diff --git a/SDK/include/NDK/LuaAPI.inl b/SDK/include/NDK/LuaAPI.inl index 01c797e89..b867e90fe 100644 --- a/SDK/include/NDK/LuaAPI.inl +++ b/SDK/include/NDK/LuaAPI.inl @@ -385,7 +385,7 @@ namespace Nz params->loadHeightMap = state.CheckField("LoadHeightMap", params->loadHeightMap); params->loadNormalMap = state.CheckField("LoadNormalMap", params->loadNormalMap); params->loadSpecularMap = state.CheckField("LoadSpecularMap", params->loadSpecularMap); - params->shaderName = state.CheckField("ShaderName", params->shaderName); + params->shaderName = state.CheckField("ShaderName", params->shaderName); return 1; } diff --git a/SDK/src/NDK/Lua/LuaBinding_Audio.cpp b/SDK/src/NDK/Lua/LuaBinding_Audio.cpp index c95b5d0ce..df97a7d38 100644 --- a/SDK/src/NDK/Lua/LuaBinding_Audio.cpp +++ b/SDK/src/NDK/Lua/LuaBinding_Audio.cpp @@ -80,7 +80,7 @@ namespace Ndk music.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Music& instance, std::size_t /*argumentCount*/) -> int { Nz::StringStream ss("Music("); - ss << instance.GetFilePath() << ')'; + ss << instance.GetFilePath().generic_u8string() << ')'; lua.PushString(ss); return 1; @@ -169,9 +169,9 @@ namespace Ndk Nz::StringStream ss("SoundBuffer("); if (instance->IsValid()) { - Nz::String filePath = instance->GetFilePath(); - if (!filePath.IsEmpty()) - ss << "File: " << filePath << ", "; + std::filesystem::path filePath = instance->GetFilePath(); + if (!filePath.empty()) + ss << "File: " << filePath.generic_u8string() << ", "; ss << "Duration: " << instance->GetDuration() / 1000.f << "s"; } diff --git a/SDK/src/NDK/Lua/LuaBinding_Core.cpp b/SDK/src/NDK/Lua/LuaBinding_Core.cpp index 6091c88e2..49a7642f4 100644 --- a/SDK/src/NDK/Lua/LuaBinding_Core.cpp +++ b/SDK/src/NDK/Lua/LuaBinding_Core.cpp @@ -115,60 +115,6 @@ namespace Ndk }); } - /********************************* Nz::Directory ********************************/ - directory.Reset("Directory"); - { - directory.SetConstructor([] (Nz::LuaState& lua, Nz::Directory* instance, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 1U); - - int argIndex = 2; - switch (argCount) - { - case 0: - Nz::PlacementNew(instance); - return true; - - case 1: - Nz::PlacementNew(instance, lua.Check(&argIndex)); - return true; - } - - return false; - }); - - directory.BindMethod("Close", &Nz::Directory::Close); - directory.BindMethod("Exists", &Nz::Directory::Exists); - directory.BindMethod("GetPath", &Nz::Directory::GetPath); - directory.BindMethod("GetPattern", &Nz::Directory::GetPattern); - directory.BindMethod("GetResultName", &Nz::Directory::GetResultName); - directory.BindMethod("GetResultPath", &Nz::Directory::GetResultPath); - directory.BindMethod("GetResultSize", &Nz::Directory::GetResultSize); - directory.BindMethod("IsOpen", &Nz::Directory::IsOpen); - directory.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory); - directory.BindMethod("NextResult", &Nz::Directory::NextResult, true); - directory.BindMethod("Open", &Nz::Directory::Open); - directory.BindMethod("SetPath", &Nz::Directory::SetPath); - directory.BindMethod("SetPattern", &Nz::Directory::SetPattern); - - directory.BindStaticMethod("Copy", Nz::Directory::Copy); - directory.BindStaticMethod("Create", Nz::Directory::Create); - directory.BindStaticMethod("Exists", Nz::Directory::Exists); - directory.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent); - directory.BindStaticMethod("Remove", Nz::Directory::Remove); - directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); - - // Manual - directory.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Directory& instance, std::size_t /*argumentCount*/) -> int { - Nz::StringStream ss("Directory("); - ss << instance.GetPath(); - ss << ')'; - - lua.PushString(ss); - return 1; - }); - } - /*********************************** Nz::File ***********************************/ file.Reset("File"); { @@ -187,7 +133,7 @@ namespace Ndk case 1: { - Nz::String filePath = lua.Check(&argIndex); + std::string filePath = lua.Check(&argIndex); Nz::PlacementNew(instance, filePath); return true; @@ -195,7 +141,7 @@ namespace Ndk case 2: { - Nz::String filePath = lua.Check(&argIndex); + std::string filePath = lua.Check(&argIndex); Nz::UInt32 openMode = lua.Check(&argIndex); Nz::PlacementNew(instance, filePath, openMode); @@ -212,29 +158,8 @@ namespace Ndk file.BindMethod("Delete", &Nz::File::Delete); file.BindMethod("EndOfFile", &Nz::File::EndOfFile); file.BindMethod("Exists", &Nz::File::Exists); - file.BindMethod("GetCreationTime", &Nz::File::GetCreationTime); file.BindMethod("GetFileName", &Nz::File::GetFileName); - file.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); - file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); file.BindMethod("IsOpen", &Nz::File::IsOpen); - file.BindMethod("Rename", &Nz::File::GetLastWriteTime); - file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - file.BindMethod("SetFile", &Nz::File::GetLastWriteTime); - - file.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath); - file.BindStaticMethod("ComputeHash", (Nz::ByteArray(*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash); - file.BindStaticMethod("Copy", &Nz::File::Copy); - file.BindStaticMethod("Delete", &Nz::File::Delete); - file.BindStaticMethod("Exists", &Nz::File::Exists); - //fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime); - file.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory); - //fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); - //fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - file.BindStaticMethod("GetSize", &Nz::File::GetSize); - file.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute); - file.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath); - file.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators); - file.BindStaticMethod("Rename", &Nz::File::Rename); // Manual file.BindMethod("Open", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t argumentCount) -> int @@ -250,7 +175,7 @@ namespace Ndk case 2: { - Nz::String filePath = lua.Check(&argIndex); + std::string filePath = lua.Check(&argIndex); Nz::UInt32 openMode = lua.Check(&argIndex, Nz::OpenMode_NotOpen); return lua.Push(instance.Open(filePath, openMode)); } @@ -285,7 +210,7 @@ namespace Ndk file.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t /*argumentCount*/) -> int { Nz::StringStream ss("File("); if (instance.IsOpen()) - ss << "Path: " << instance.GetPath(); + ss << "Path: " << instance.GetPath().generic_u8string(); ss << ')'; @@ -304,7 +229,6 @@ namespace Ndk { // Classes clock.Register(state); - directory.Register(state); file.Register(state); stream.Register(state); diff --git a/SDK/src/NDK/Lua/LuaBinding_Graphics.cpp b/SDK/src/NDK/Lua/LuaBinding_Graphics.cpp index fc764866a..5ed660089 100644 --- a/SDK/src/NDK/Lua/LuaBinding_Graphics.cpp +++ b/SDK/src/NDK/Lua/LuaBinding_Graphics.cpp @@ -94,7 +94,7 @@ namespace Ndk } else { - Nz::PlacementNew(instance, Nz::Material::New(lua.Check(&argIndex))); + Nz::PlacementNew(instance, Nz::Material::New(lua.Check(&argIndex))); return true; } } @@ -114,7 +114,7 @@ namespace Ndk } else { - lua.Push(instance->Configure(lua.Check(&argIndex))); + lua.Push(instance->Configure(lua.Check(&argIndex))); return 1; } }); @@ -214,7 +214,7 @@ namespace Ndk return 0; } else - return lua.Push(instance->SetAlphaMap(lua.Check(&argIndex))); + return lua.Push(instance->SetAlphaMap(lua.Check(&argIndex))); }); material.BindMethod("SetDiffuseMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int @@ -226,7 +226,7 @@ namespace Ndk return 0; } else - return lua.Push(instance->SetDiffuseMap(lua.Check(&argIndex))); + return lua.Push(instance->SetDiffuseMap(lua.Check(&argIndex))); }); material.BindMethod("SetEmissiveMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int @@ -238,7 +238,7 @@ namespace Ndk return 0; } else - return lua.Push(instance->SetEmissiveMap(lua.Check(&argIndex))); + return lua.Push(instance->SetEmissiveMap(lua.Check(&argIndex))); }); material.BindMethod("SetHeightMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int @@ -250,7 +250,7 @@ namespace Ndk return 0; } else - return lua.Push(instance->SetHeightMap(lua.Check(&argIndex))); + return lua.Push(instance->SetHeightMap(lua.Check(&argIndex))); }); material.BindMethod("SetNormalMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int @@ -262,7 +262,7 @@ namespace Ndk return 0; } else - return lua.Push(instance->SetNormalMap(lua.Check(&argIndex))); + return lua.Push(instance->SetNormalMap(lua.Check(&argIndex))); }); material.BindMethod("SetShader", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int @@ -274,7 +274,7 @@ namespace Ndk return 0; } else - return lua.Push(instance->SetShader(lua.Check(&argIndex))); + return lua.Push(instance->SetShader(lua.Check(&argIndex))); }); material.BindMethod("SetSpecularMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int @@ -286,7 +286,7 @@ namespace Ndk return 0; } else - return lua.Push(instance->SetSpecularMap(lua.Check(&argIndex))); + return lua.Push(instance->SetSpecularMap(lua.Check(&argIndex))); }); } @@ -326,7 +326,7 @@ namespace Ndk } else if (lua.IsOfType(argIndex, Nz::LuaType_String)) { - Nz::String subMesh(lua.Check(&argIndex)); + std::string subMesh(lua.Check(&argIndex)); Nz::MaterialRef mat(lua.Check(&argIndex)); instance->SetMaterial(subMesh, std::move(mat)); @@ -351,7 +351,7 @@ namespace Ndk else if (lua.IsOfType(argIndex, Nz::LuaType_String)) { std::size_t skinIndex(lua.Check(&argIndex)); - Nz::String subMesh(lua.Check(&argIndex)); + std::string subMesh(lua.Check(&argIndex)); Nz::MaterialRef materialRef(lua.Check(&argIndex)); instance->SetMaterial(skinIndex, subMesh, std::move(materialRef)); @@ -423,7 +423,7 @@ namespace Ndk if (lua.IsOfType(argIndex, "Material")) instance->SetMaterial(skinIndex, *static_cast(lua.ToUserdata(argIndex)), resizeSprite); else - instance->SetMaterial(skinIndex, lua.Check(&argIndex), resizeSprite); + instance->SetMaterial(skinIndex, lua.Check(&argIndex), resizeSprite); } return 0; @@ -452,7 +452,7 @@ namespace Ndk if (lua.IsOfType(argIndex, "Texture")) instance->SetTexture(skinIndex, *static_cast(lua.ToUserdata(argIndex)), resizeSprite); else - instance->SetTexture(skinIndex, lua.Check(&argIndex), resizeSprite); + instance->SetTexture(skinIndex, lua.Check(&argIndex), resizeSprite); } return 0; diff --git a/examples/DopplerEffect/main.cpp b/examples/DopplerEffect/main.cpp index 24120a2f5..b0c7a8f62 100644 --- a/examples/DopplerEffect/main.cpp +++ b/examples/DopplerEffect/main.cpp @@ -10,10 +10,10 @@ #include #include -#include // Thread::Sleep #include #include #include +#include #include int main() @@ -61,7 +61,7 @@ int main() int sleepTime = int(1000/60 - clock.GetMilliseconds()); // 60 FPS if (sleepTime > 0) - Nz::Thread::Sleep(sleepTime); + std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); // On bouge la source du son en fonction du temps depuis chaque mise à jour Nz::Vector3f pos = sound.GetPosition() + sound.GetVelocity()*clock.GetSeconds(); diff --git a/examples/MeshInfos/main.cpp b/examples/MeshInfos/main.cpp index e7b3feaeb..8d7d25adb 100644 --- a/examples/MeshInfos/main.cpp +++ b/examples/MeshInfos/main.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -26,25 +25,17 @@ int main() for (;;) { - Nz::Directory resourceDirectory("resources"); - if (!resourceDirectory.Open()) + std::vector models; + for (auto& p : std::filesystem::directory_iterator("resources")) { - std::cerr << "Failed to open resource directory" << std::endl; - std::getchar(); - return EXIT_FAILURE; - } + if (!p.is_regular_file()) + continue; - std::vector models; - while (resourceDirectory.NextResult()) - { - Nz::String path = resourceDirectory.GetResultName(); - Nz::String ext = path.SubStringFrom('.', -1, true); // Tout ce qui vient après le dernier '.' de la chaîne - if (Nz::MeshLoader::IsExtensionSupported(ext)) // L'extension est-elle supportée par le MeshLoader ? - models.push_back(path); + const std::filesystem::path& filePath = p.path(); + if (Nz::MeshLoader::IsExtensionSupported(filePath.extension().generic_u8string())) // L'extension est-elle supportée par le MeshLoader ? + models.push_back(filePath); } - resourceDirectory.Close(); - if (models.empty()) { std::cout << "No loadable mesh found in resource directory" << std::endl; @@ -71,7 +62,7 @@ int main() if (iChoice == 0) break; - Nz::MeshRef mesh = Nz::Mesh::LoadFromFile(resourceDirectory.GetPath() + '/' + models[iChoice-1]); + Nz::MeshRef mesh = Nz::Mesh::LoadFromFile(models[iChoice-1]); if (!mesh) { std::cout << "Failed to load mesh" << std::endl; @@ -123,8 +114,8 @@ int main() } } - Nz::String animationPath = mesh->GetAnimation(); - if (!animationPath.IsEmpty()) + std::filesystem::path animationPath = mesh->GetAnimation(); + if (!animationPath.empty()) { Nz::AnimationRef animation = Nz::Animation::LoadFromFile(animationPath); if (animation) diff --git a/examples/Particles/main.cpp b/examples/Particles/main.cpp index e4940c63d..7f1571989 100644 --- a/examples/Particles/main.cpp +++ b/examples/Particles/main.cpp @@ -173,7 +173,7 @@ int main() window.CopyToImage(&screenshot); static unsigned int counter = 1; - screenshot.SaveToFile("screenshot_" + Nz::String::Number(counter++) + ".png"); + screenshot.SaveToFile("screenshot_" + std::to_string(counter++) + ".png"); break; } diff --git a/include/Nazara/Audio/Music.hpp b/include/Nazara/Audio/Music.hpp index 331624a8d..0f0acc1b7 100644 --- a/include/Nazara/Audio/Music.hpp +++ b/include/Nazara/Audio/Music.hpp @@ -39,7 +39,7 @@ namespace Nz bool IsLooping() const override; - bool OpenFromFile(const String& filePath, const SoundStreamParams& params = SoundStreamParams()); + bool OpenFromFile(const std::filesystem::path& filePath, const SoundStreamParams& params = SoundStreamParams()); bool OpenFromMemory(const void* data, std::size_t size, const SoundStreamParams& params = SoundStreamParams()); bool OpenFromStream(Stream& stream, const SoundStreamParams& params = SoundStreamParams()); diff --git a/include/Nazara/Audio/Sound.hpp b/include/Nazara/Audio/Sound.hpp index 55cc2f97a..1c1415dc8 100644 --- a/include/Nazara/Audio/Sound.hpp +++ b/include/Nazara/Audio/Sound.hpp @@ -34,7 +34,7 @@ namespace Nz bool IsPlayable() const; bool IsPlaying() const; - bool LoadFromFile(const String& filePath, const SoundBufferParams& params = SoundBufferParams()); + bool LoadFromFile(const std::filesystem::path& filePath, const SoundBufferParams& params = SoundBufferParams()); bool LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params = SoundBufferParams()); bool LoadFromStream(Stream& stream, const SoundBufferParams& params = SoundBufferParams()); diff --git a/include/Nazara/Audio/SoundBuffer.hpp b/include/Nazara/Audio/SoundBuffer.hpp index 4cf5e50df..0a7ab4f63 100644 --- a/include/Nazara/Audio/SoundBuffer.hpp +++ b/include/Nazara/Audio/SoundBuffer.hpp @@ -71,7 +71,7 @@ namespace Nz static bool IsFormatSupported(AudioFormat format); - static SoundBufferRef LoadFromFile(const String& filePath, const SoundBufferParams& params = SoundBufferParams()); + static SoundBufferRef LoadFromFile(const std::filesystem::path& filePath, const SoundBufferParams& params = SoundBufferParams()); static SoundBufferRef LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params = SoundBufferParams()); static SoundBufferRef LoadFromStream(Stream& stream, const SoundBufferParams& params = SoundBufferParams()); diff --git a/include/Nazara/Audio/SoundStream.hpp b/include/Nazara/Audio/SoundStream.hpp index d33997d26..89b229317 100644 --- a/include/Nazara/Audio/SoundStream.hpp +++ b/include/Nazara/Audio/SoundStream.hpp @@ -14,6 +14,7 @@ #include #include #include +#include namespace Nz { @@ -40,7 +41,7 @@ namespace Nz virtual UInt32 GetDuration() const = 0; virtual AudioFormat GetFormat() const = 0; - virtual Mutex& GetMutex() = 0; + virtual std::mutex& GetMutex() = 0; virtual UInt64 GetSampleCount() const = 0; virtual UInt32 GetSampleRate() const = 0; @@ -48,7 +49,7 @@ namespace Nz virtual void Seek(UInt64 offset) = 0; virtual UInt64 Tell() = 0; - static SoundStreamRef OpenFromFile(const String& filePath, const SoundStreamParams& params = SoundStreamParams()); + static SoundStreamRef OpenFromFile(const std::filesystem::path& filePath, const SoundStreamParams& params = SoundStreamParams()); static SoundStreamRef OpenFromMemory(const void* data, std::size_t size, const SoundStreamParams& params = SoundStreamParams()); static SoundStreamRef OpenFromStream(Stream& stream, const SoundStreamParams& params = SoundStreamParams()); diff --git a/include/Nazara/Core.hpp b/include/Nazara/Core.hpp index bb5e6e682..579a0c267 100644 --- a/include/Nazara/Core.hpp +++ b/include/Nazara/Core.hpp @@ -34,14 +34,13 @@ #include #include #include +#include #include #include #include #include -#include #include #include -#include #include #include #include @@ -56,7 +55,6 @@ #include #include #include -#include #include #include #include @@ -64,13 +62,13 @@ #include #include #include -#include #include #include #include #include #include #include +#include #include #include #include @@ -79,7 +77,6 @@ #include #include #include -#include #include #include #include @@ -88,9 +85,9 @@ #include #include #include +#include #include #include -#include #include #include #include diff --git a/include/Nazara/Core/Algorithm.hpp b/include/Nazara/Core/Algorithm.hpp index faf80e6cb..f42fefd27 100644 --- a/include/Nazara/Core/Algorithm.hpp +++ b/include/Nazara/Core/Algorithm.hpp @@ -31,6 +31,33 @@ namespace Nz template void HashCombine(std::size_t& seed, const T& v); template T ReverseBits(T integer); + template + struct AlwaysFalse : std::false_type {}; + + template + struct OverloadResolver + { + template + constexpr auto operator()(R(T::* ptr)(Args...)) const noexcept + { + return ptr; + } + + template + constexpr auto operator()(R(T::* ptr)(Args...) const) const noexcept + { + return ptr; + } + + template + constexpr auto operator()(R(*ptr)(Args...)) const noexcept + { + return ptr; + } + }; + + template constexpr OverloadResolver Overload = {}; + template struct PointedType { diff --git a/include/Nazara/Core/Clock.hpp b/include/Nazara/Core/Clock.hpp index a6b464db6..f37f78a52 100644 --- a/include/Nazara/Core/Clock.hpp +++ b/include/Nazara/Core/Clock.hpp @@ -9,12 +9,6 @@ #include -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_CLOCK -#include -#else -#include -#endif - namespace Nz { class NAZARA_CORE_API Clock @@ -39,8 +33,6 @@ namespace Nz Clock& operator=(Clock&& clock) = default; private: - NazaraMutexAttrib(m_mutex, mutable) - UInt64 m_elapsedTime; UInt64 m_refTime; bool m_paused; diff --git a/include/Nazara/Core/ConditionVariable.hpp b/include/Nazara/Core/ConditionVariable.hpp deleted file mode 100644 index 4b69926d3..000000000 --- a/include/Nazara/Core/ConditionVariable.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CONDITIONVARIABLE_HPP -#define NAZARA_CONDITIONVARIABLE_HPP - -#include -#include - -namespace Nz -{ - class ConditionVariableImpl; - class Mutex; - - class NAZARA_CORE_API ConditionVariable - { - public: - ConditionVariable(); - ConditionVariable(const ConditionVariable&) = delete; - ConditionVariable(ConditionVariable&& condition) noexcept = default; - ~ConditionVariable(); - - void Signal(); - void SignalAll(); - - void Wait(Mutex* mutex); - bool Wait(Mutex* mutex, UInt32 timeout); - - ConditionVariable& operator=(const ConditionVariable&) = delete; - ConditionVariable& operator=(ConditionVariable&& condition) noexcept = default; - - private: - MovablePtr m_impl; - }; -} - -#include - -#endif // NAZARA_CONDITIONVARIABLE_HPP diff --git a/include/Nazara/Core/ConditionVariable.inl b/include/Nazara/Core/ConditionVariable.inl deleted file mode 100644 index 71866b880..000000000 --- a/include/Nazara/Core/ConditionVariable.inl +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include - -namespace Nz -{ - /*! - * \class Nz::ConditionVariable - */ -} - -#include diff --git a/include/Nazara/Core/Config.hpp b/include/Nazara/Core/Config.hpp index 976db4512..e4362f80a 100644 --- a/include/Nazara/Core/Config.hpp +++ b/include/Nazara/Core/Config.hpp @@ -58,17 +58,6 @@ // Activate the security tests based on the code (Advised for development) #define NAZARA_CORE_SAFE 1 -// Protect the classes against data race -#define NAZARA_CORE_THREADSAFE 1 - -// Classes to protect against data race -#define NAZARA_THREADSAFETY_CLOCK 0 // Clock -#define NAZARA_THREADSAFETY_DIRECTORY 1 // Directory -#define NAZARA_THREADSAFETY_DYNLIB 1 // DynLib -#define NAZARA_THREADSAFETY_FILE 1 // File -#define NAZARA_THREADSAFETY_LOG 1 // Log -#define NAZARA_THREADSAFETY_REFCOUNTED 1 // RefCounted - // Number of spinlocks to use with the Windows critical sections (0 to disable) #define NAZARA_CORE_WINDOWS_CS_SPINLOCKS 4096 diff --git a/include/Nazara/Core/Directory.hpp b/include/Nazara/Core/Directory.hpp deleted file mode 100644 index 1ac3af76b..000000000 --- a/include/Nazara/Core/Directory.hpp +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_DIRECTORY_HPP -#define NAZARA_DIRECTORY_HPP - -#include -#include -#include - -#if defined(NAZARA_PLATFORM_WINDOWS) - #define NAZARA_DIRECTORY_SEPARATOR '\\' -#elif defined(NAZARA_PLATFORM_LINUX) - #define NAZARA_DIRECTORY_SEPARATOR '/' -#else - #error OS not handled - #define NAZARA_DIRECTORY_SEPARATOR '/' -#endif - -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_DIRECTORY - #include -#else - #include -#endif - -namespace Nz -{ - class DirectoryImpl; - - class NAZARA_CORE_API Directory - { - public: - Directory(); - Directory(const String& dirPath); - Directory(const Directory&) = delete; - Directory(Directory&&) noexcept = default; - ~Directory(); - - void Close(); - - bool Exists() const; - - String GetPath() const; - String GetPattern() const; - String GetResultName() const; - String GetResultPath() const; - UInt64 GetResultSize() const; - - bool IsOpen() const; - bool IsResultDirectory() const; - - bool NextResult(bool skipDots = true); - - bool Open(); - - void SetPath(const String& dirPath); - void SetPattern(const String& pattern); - - static bool Copy(const String& sourcePath, const String& destPath); - static bool Create(const String& dirPath, bool recursive = false); - static bool Exists(const String& dirPath); - static String GetCurrent(); - static const char* GetCurrentFileRelativeToEngine(const char* currentFile); - static bool Remove(const String& dirPath, bool emptyDirectory = false); - static bool SetCurrent(const String& dirPath); - - Directory& operator=(const Directory&) = delete; - Directory& operator=(Directory&&) noexcept = delete; - - private: - NazaraMutexAttrib(m_mutex, mutable) - - String m_dirPath; - String m_pattern; - MovablePtr m_impl; - }; -} - -#endif // NAZARA_DIRECTORY_HPP diff --git a/include/Nazara/Core/DynLib.hpp b/include/Nazara/Core/DynLib.hpp index 266334b3e..71730d6e1 100644 --- a/include/Nazara/Core/DynLib.hpp +++ b/include/Nazara/Core/DynLib.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #if defined(NAZARA_PLATFORM_WINDOWS) #define NAZARA_DYNLIB_EXTENSION ".dll" @@ -21,12 +21,6 @@ #error OS not handled #endif -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_DYNLIB - #include -#else - #include -#endif - namespace Nz { using DynLibFunc = int (*)(); // "Generic" type of pointer to function @@ -38,25 +32,23 @@ namespace Nz public: DynLib(); DynLib(const DynLib&) = delete; - DynLib(DynLib&&) noexcept = default; + DynLib(DynLib&&) noexcept; ~DynLib(); - String GetLastError() const; - DynLibFunc GetSymbol(const String& symbol) const; + std::string GetLastError() const; + DynLibFunc GetSymbol(const char* symbol) const; bool IsLoaded() const; - bool Load(const String& libraryPath); + bool Load(const std::filesystem::path& libraryPath); void Unload(); DynLib& operator=(const DynLib&) = delete; - DynLib& operator=(DynLib&& lib) noexcept = default; + DynLib& operator=(DynLib&& lib) noexcept; private: - NazaraMutexAttrib(m_mutex, mutable) - - mutable String m_lastError; - MovablePtr m_impl; + mutable std::string m_lastError; + std::unique_ptr m_impl; }; } diff --git a/include/Nazara/Core/Error.hpp b/include/Nazara/Core/Error.hpp index 8081340f7..16c7d6ca7 100644 --- a/include/Nazara/Core/Error.hpp +++ b/include/Nazara/Core/Error.hpp @@ -33,7 +33,7 @@ namespace Nz static UInt32 GetFlags(); static String GetLastError(const char** file = nullptr, unsigned int* line = nullptr, const char** function = nullptr); static unsigned int GetLastSystemErrorCode(); - static String GetLastSystemError(unsigned int code = GetLastSystemErrorCode()); + static std::string GetLastSystemError(unsigned int code = GetLastSystemErrorCode()); static void SetFlags(UInt32 flags); @@ -41,6 +41,8 @@ namespace Nz static void Trigger(ErrorType type, const String& error, unsigned int line, const char* file, const char* function); private: + static const char* GetCurrentFileRelativeToEngine(const char* file); + static UInt32 s_flags; static String s_lastError; static const char* s_lastErrorFunction; diff --git a/include/Nazara/Core/File.hpp b/include/Nazara/Core/File.hpp index ce3025ca5..10e37a31b 100644 --- a/include/Nazara/Core/File.hpp +++ b/include/Nazara/Core/File.hpp @@ -13,14 +13,9 @@ #include #include #include - -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_FILE - #include -#else - #include -#endif - #include +#include +#include namespace Nz { @@ -30,13 +25,13 @@ namespace Nz { public: File(); - File(const String& filePath); - File(const String& filePath, OpenModeFlags openMode); + File(const std::filesystem::path& filePath); + File(const std::filesystem::path& filePath, OpenModeFlags openMode); File(const File&) = delete; - File(File&& file) noexcept = default; + File(File&& file) noexcept; ~File(); - bool Copy(const String& newFilePath); + void Copy(const std::filesystem::path& newFilePath); void Close(); bool Delete(); @@ -46,56 +41,35 @@ namespace Nz bool Exists() const; - time_t GetCreationTime() const; UInt64 GetCursorPos() const override; - String GetDirectory() const override; - String GetFileName() const; - time_t GetLastAccessTime() const; - time_t GetLastWriteTime() const; - String GetPath() const override; + std::filesystem::path GetDirectory() const override; + std::filesystem::path GetFileName() const; + std::filesystem::path GetPath() const override; UInt64 GetSize() const override; bool IsOpen() const; bool Open(OpenModeFlags openMode = OpenMode_NotOpen); - bool Open(const String& filePath, OpenModeFlags openMode = OpenMode_NotOpen); - - bool Rename(const String& newFilePath); + bool Open(const std::filesystem::path& filePath, OpenModeFlags openMode = OpenMode_NotOpen); bool SetCursorPos(CursorPosition pos, Int64 offset = 0); bool SetCursorPos(UInt64 offset) override; - bool SetFile(const String& filePath); + bool SetFile(const std::filesystem::path& filePath); bool SetSize(UInt64 size); - File& operator=(const String& filePath); File& operator=(const File&) = delete; - File& operator=(File&& file) noexcept = default; + File& operator=(File&& file) noexcept; - static String AbsolutePath(const String& filePath); - static inline ByteArray ComputeHash(HashType hash, const String& filePath); - static inline ByteArray ComputeHash(AbstractHash* hash, const String& filePath); - static bool Copy(const String& sourcePath, const String& targetPath); - static bool Delete(const String& filePath); - static bool Exists(const String& filePath); - static time_t GetCreationTime(const String& filePath); - static String GetDirectory(const String& filePath); - static time_t GetLastAccessTime(const String& filePath); - static time_t GetLastWriteTime(const String& filePath); - static UInt64 GetSize(const String& filePath); - static bool IsAbsolute(const String& filePath); - static String NormalizePath(const String& filePath); - static String NormalizeSeparators(const String& filePath); - static bool Rename(const String& sourcePath, const String& targetPath); + static inline ByteArray ComputeHash(HashType hash, const std::filesystem::path& filePath); + static inline ByteArray ComputeHash(AbstractHash* hash, const std::filesystem::path& filePath); private: - NazaraMutexAttrib(m_mutex, mutable) - void FlushStream() override; std::size_t ReadBlock(void* buffer, std::size_t size) override; std::size_t WriteBlock(const void* buffer, std::size_t size) override; - String m_filePath; - MovablePtr m_impl; + std::filesystem::path m_filePath; + std::unique_ptr m_impl; }; NAZARA_CORE_API bool HashAppend(AbstractHash* hash, const File& originalFile); diff --git a/include/Nazara/Core/File.inl b/include/Nazara/Core/File.inl index 8a93fbc28..d23daf953 100644 --- a/include/Nazara/Core/File.inl +++ b/include/Nazara/Core/File.inl @@ -15,7 +15,7 @@ namespace Nz * \param filePath Path for the file */ - inline ByteArray File::ComputeHash(HashType hash, const String& filePath) + inline ByteArray File::ComputeHash(HashType hash, const std::filesystem::path& filePath) { return ComputeHash(AbstractHash::Get(hash).get(), filePath); } @@ -28,7 +28,7 @@ namespace Nz * \param filePath Path for the file */ - inline ByteArray File::ComputeHash(AbstractHash* hash, const String& filePath) + inline ByteArray File::ComputeHash(AbstractHash* hash, const std::filesystem::path& filePath) { return Nz::ComputeHash(hash, File(filePath)); } diff --git a/include/Nazara/Core/FileLogger.hpp b/include/Nazara/Core/FileLogger.hpp index c722b3290..f61ba8046 100644 --- a/include/Nazara/Core/FileLogger.hpp +++ b/include/Nazara/Core/FileLogger.hpp @@ -9,8 +9,9 @@ #include #include -#include #include +#include +#include namespace Nz { @@ -35,7 +36,8 @@ namespace Nz FileLogger& operator=(FileLogger&&) noexcept = default; private: - File m_outputFile; + std::fstream m_outputFile; + std::filesystem::path m_outputPath; StdLogger m_stdLogger; bool m_forceStdOutput; bool m_stdReplicationEnabled; diff --git a/include/Nazara/Core/LockGuard.hpp b/include/Nazara/Core/LockGuard.hpp deleted file mode 100644 index 59ece007c..000000000 --- a/include/Nazara/Core/LockGuard.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_LOCKGUARD_HPP -#define NAZARA_LOCKGUARD_HPP - -#include - -namespace Nz -{ - class Mutex; - - class LockGuard - { - public: - inline LockGuard(Mutex& mutex, bool lock = true); - inline ~LockGuard(); - - inline void Lock(); - inline bool TryLock(); - inline void Unlock(); - - private: - Mutex& m_mutex; - bool m_locked; - }; -} - -#include - -#endif // NAZARA_LOCKGUARD_HPP diff --git a/include/Nazara/Core/LockGuard.inl b/include/Nazara/Core/LockGuard.inl deleted file mode 100644 index 4fa95884f..000000000 --- a/include/Nazara/Core/LockGuard.inl +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::LockGuard - * \brief Core class that represents a mutex wrapper that provides a convenient RAII-style mechanism - */ - - /*! - * \brief Constructs a LockGuard object with a mutex - * - * \param mutex Mutex to lock - * \param lock Should the mutex be locked by the constructor - */ - inline LockGuard::LockGuard(Mutex& mutex, bool lock) : - m_mutex(mutex), - m_locked(false) - { - if (lock) - { - m_mutex.Lock(); - m_locked = true; - } - } - - /*! - * \brief Destructs a LockGuard object and unlocks the mutex if it was previously locked - */ - inline LockGuard::~LockGuard() - { - if (m_locked) - m_mutex.Unlock(); - } - - /*! - * \brief Locks the underlying mutex - * - * \see Mutex::Lock - */ - inline void LockGuard::Lock() - { - NazaraAssert(!m_locked, "Mutex is already locked"); - - m_mutex.Lock(); - } - - /*! - * \brief Tries to lock the underlying mutex - * - * \see Mutex::TryLock - * - * \return true if the lock was acquired successfully - */ - inline bool LockGuard::TryLock() - { - NazaraAssert(!m_locked, "Mutex is already locked"); - - return m_mutex.TryLock(); - } - - /*! - * \brief Unlocks the underlying mutex - * - * \see Mutex::Unlock - */ - inline void LockGuard::Unlock() - { - NazaraAssert(m_locked, "Mutex is not locked"); - - m_mutex.Unlock(); - } -} - -#include diff --git a/include/Nazara/Core/Log.hpp b/include/Nazara/Core/Log.hpp index edb8f7947..c398b76a7 100644 --- a/include/Nazara/Core/Log.hpp +++ b/include/Nazara/Core/Log.hpp @@ -11,12 +11,6 @@ #include #include -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_LOG - #include -#else - #include -#endif - #ifdef NAZARA_DEBUG #define NazaraDebug(txt) NazaraNotice(txt) #else diff --git a/include/Nazara/Core/Mutex.hpp b/include/Nazara/Core/Mutex.hpp deleted file mode 100644 index d5d5180bb..000000000 --- a/include/Nazara/Core/Mutex.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_MUTEX_HPP -#define NAZARA_MUTEX_HPP - -#include -#include - -namespace Nz -{ - class MutexImpl; - - class NAZARA_CORE_API Mutex - { - friend class ConditionVariable; - - public: - Mutex(); - Mutex(const Mutex&) = delete; - Mutex(Mutex&&) noexcept = default; - ~Mutex(); - - void Lock(); - bool TryLock(); - void Unlock(); - - Mutex& operator=(const Mutex&) = delete; - Mutex& operator=(Mutex&&) noexcept = default; - - private: - MovablePtr m_impl; - }; -} - -#include - -#endif // NAZARA_MUTEX_HPP diff --git a/include/Nazara/Core/Mutex.inl b/include/Nazara/Core/Mutex.inl deleted file mode 100644 index ca9e5ec2f..000000000 --- a/include/Nazara/Core/Mutex.inl +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::Mutex - */ -} - -#include diff --git a/include/Nazara/Core/PluginManager.hpp b/include/Nazara/Core/PluginManager.hpp index 13b384109..a13f1f0b0 100644 --- a/include/Nazara/Core/PluginManager.hpp +++ b/include/Nazara/Core/PluginManager.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include @@ -24,23 +24,32 @@ namespace Nz PluginManager() = delete; ~PluginManager() = delete; - static void AddDirectory(const String& directoryPath); + static void AddDirectory(const std::filesystem::path& directoryPath); static bool Initialize(); static bool Mount(Plugin plugin); - static bool Mount(const String& pluginPath, bool appendExtension = true); + static bool Mount(const std::filesystem::path& pluginPath, bool appendExtension = true); - static void RemoveDirectory(const String& directoryPath); + static void RemoveDirectory(const std::filesystem::path& directoryPath); static void Unmount(Plugin plugin); - static void Unmount(const String& pluginPath); + static void Unmount(const std::filesystem::path& pluginPath); static void Uninitialize(); private: - static std::set s_directories; - static std::unordered_map s_plugins; + // https://stackoverflow.com/questions/51065244/is-there-no-standard-hash-for-stdfilesystempath + struct PathHash + { + std::size_t operator()(const std::filesystem::path& p) const + { + return hash_value(p); + } + }; + + static std::set s_directories; + static std::unordered_map, PathHash> s_plugins; static bool s_initialized; }; } diff --git a/include/Nazara/Core/RefCounted.hpp b/include/Nazara/Core/RefCounted.hpp index d348d9280..a108653f7 100644 --- a/include/Nazara/Core/RefCounted.hpp +++ b/include/Nazara/Core/RefCounted.hpp @@ -10,12 +10,6 @@ #include #include -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_REFCOUNTED - #include -#else - #include -#endif - namespace Nz { class NAZARA_CORE_API RefCounted diff --git a/include/Nazara/Core/Resource.hpp b/include/Nazara/Core/Resource.hpp index 6f651ecf8..d1cc1bc2e 100644 --- a/include/Nazara/Core/Resource.hpp +++ b/include/Nazara/Core/Resource.hpp @@ -8,7 +8,7 @@ #define NAZARA_RESOURCE_HPP #include -#include +#include namespace Nz { @@ -20,15 +20,15 @@ namespace Nz Resource(Resource&&) noexcept = default; virtual ~Resource(); - const String& GetFilePath() const; + const std::filesystem::path& GetFilePath() const; - void SetFilePath(const String& filePath); + void SetFilePath(const std::filesystem::path& filePath); Resource& operator=(const Resource&) = default; Resource& operator=(Resource&&) noexcept = default; private: - String m_filePath; + std::filesystem::path m_filePath; }; } diff --git a/include/Nazara/Core/ResourceLoader.hpp b/include/Nazara/Core/ResourceLoader.hpp index 1bee093ee..c3a0918a9 100644 --- a/include/Nazara/Core/ResourceLoader.hpp +++ b/include/Nazara/Core/ResourceLoader.hpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include #include @@ -29,8 +29,8 @@ namespace Nz friend Type; public: - using ExtensionGetter = bool (*)(const String& extension); - using FileLoader = ObjectRef (*)(const String& filePath, const Parameters& parameters); + using ExtensionGetter = bool (*)(const std::string& extension); + using FileLoader = ObjectRef (*)(const std::filesystem::path& filePath, const Parameters& parameters); using MemoryLoader = ObjectRef (*)(const void* data, std::size_t size, const Parameters& parameters); using StreamChecker = Ternary (*)(Stream& stream, const Parameters& parameters); using StreamLoader = ObjectRef (*)(Stream& stream, const Parameters& parameters); @@ -38,9 +38,9 @@ namespace Nz ResourceLoader() = delete; ~ResourceLoader() = delete; - static bool IsExtensionSupported(const String& extension); + static bool IsExtensionSupported(const std::string& extension); - static ObjectRef LoadFromFile(const String& filePath, const Parameters& parameters = Parameters()); + static ObjectRef LoadFromFile(const std::filesystem::path& filePath, const Parameters& parameters = Parameters()); static ObjectRef LoadFromMemory(const void* data, std::size_t size, const Parameters& parameters = Parameters()); static ObjectRef LoadFromStream(Stream& stream, const Parameters& parameters = Parameters()); diff --git a/include/Nazara/Core/ResourceLoader.inl b/include/Nazara/Core/ResourceLoader.inl index db143c3b0..65ae38803 100644 --- a/include/Nazara/Core/ResourceLoader.inl +++ b/include/Nazara/Core/ResourceLoader.inl @@ -7,6 +7,7 @@ #include #include #include +#include #include namespace Nz @@ -24,7 +25,7 @@ namespace Nz * \param extension Extension of the file */ template - bool ResourceLoader::IsExtensionSupported(const String& extension) + bool ResourceLoader::IsExtensionSupported(const std::string& extension) { for (Loader& loader : Type::s_loaders) { @@ -53,19 +54,21 @@ namespace Nz * \remark Produces a NazaraError if all loaders failed or no loader was found */ template - ObjectRef ResourceLoader::LoadFromFile(const String& filePath, const Parameters& parameters) + ObjectRef ResourceLoader::LoadFromFile(const std::filesystem::path& filePath, const Parameters& parameters) { NazaraAssert(parameters.IsValid(), "Invalid parameters"); - String path = File::NormalizePath(filePath); - String ext = path.SubStringFrom('.', -1, true).ToLower(); - if (ext.IsEmpty()) + std::string ext = ToLower(filePath.extension().generic_u8string()); + if (ext.empty()) { - NazaraError("Failed to get file extension from \"" + filePath + '"'); + NazaraError("Failed to get file extension from \"" + filePath.generic_u8string() + '"'); return nullptr; } - File file(path); // Open only if needed + if (ext[0] == '.') + ext.erase(ext.begin()); + + File file(filePath.generic_u8string()); // Open only if needed bool found = false; for (Loader& loader : Type::s_loaders) @@ -82,7 +85,7 @@ namespace Nz { if (!file.Open(OpenMode_ReadOnly)) { - NazaraError("Failed to load file: unable to open \"" + filePath + '"'); + NazaraError("Failed to load file: unable to open \"" + filePath.generic_u8string() + '"'); return nullptr; } } diff --git a/include/Nazara/Core/ResourceManager.hpp b/include/Nazara/Core/ResourceManager.hpp index c99e84f78..c8b5f8f68 100644 --- a/include/Nazara/Core/ResourceManager.hpp +++ b/include/Nazara/Core/ResourceManager.hpp @@ -25,19 +25,28 @@ namespace Nz static void Clear(); - static ObjectRef Get(const String& filePath); + static ObjectRef Get(const std::filesystem::path& filePath); static const Parameters& GetDefaultParameters(); static void Purge(); - static void Register(const String& filePath, ObjectRef resource); + static void Register(const std::filesystem::path& filePath, ObjectRef resource); static void SetDefaultParameters(const Parameters& params); - static void Unregister(const String& filePath); + static void Unregister(const std::filesystem::path& filePath); private: static bool Initialize(); static void Uninitialize(); - using ManagerMap = std::unordered_map>; + // https://stackoverflow.com/questions/51065244/is-there-no-standard-hash-for-stdfilesystempath + struct PathHash + { + std::size_t operator()(const std::filesystem::path& p) const + { + return hash_value(p); + } + }; + + using ManagerMap = std::unordered_map, PathHash>; using ManagerParams = Parameters; }; } diff --git a/include/Nazara/Core/ResourceManager.inl b/include/Nazara/Core/ResourceManager.inl index ca381fce7..8da2c138e 100644 --- a/include/Nazara/Core/ResourceManager.inl +++ b/include/Nazara/Core/ResourceManager.inl @@ -31,20 +31,20 @@ namespace Nz * \param filePath Path to the asset that will be loaded */ template - ObjectRef ResourceManager::Get(const String& filePath) + ObjectRef ResourceManager::Get(const std::filesystem::path& filePath) { - String absolutePath = File::AbsolutePath(filePath); + std::filesystem::path absolutePath = std::filesystem::canonical(filePath); auto it = Type::s_managerMap.find(absolutePath); if (it == Type::s_managerMap.end()) { ObjectRef resource = Type::LoadFromFile(absolutePath, GetDefaultParameters()); if (!resource) { - NazaraError("Failed to load resource from file: " + absolutePath); + NazaraError("Failed to load resource from file: " + absolutePath.generic_u8string()); return ObjectRef(); } - NazaraDebug("Loaded resource from file " + absolutePath); + NazaraDebug("Loaded resource from file " + absolutePath.generic_u8string()); it = Type::s_managerMap.insert(std::make_pair(absolutePath, resource)).first; } @@ -74,7 +74,7 @@ namespace Nz const ObjectRef& ref = it->second; if (ref->GetReferenceCount() == 1) // Are we the only ones to own the resource ? { - NazaraDebug("Purging resource from file " + ref->GetFilePath()); + NazaraDebug("Purging resource from file " + ref->GetFilePath().generic_u8string()); Type::s_managerMap.erase(it++); // Then we erase it } else @@ -89,9 +89,9 @@ namespace Nz * \param resource Object to associate with */ template - void ResourceManager::Register(const String& filePath, ObjectRef resource) + void ResourceManager::Register(const std::filesystem::path& filePath, ObjectRef resource) { - String absolutePath = File::AbsolutePath(filePath); + std::filesystem::path absolutePath = std::filesystem::canonical(filePath); Type::s_managerMap[absolutePath] = resource; } @@ -113,9 +113,9 @@ namespace Nz * \param filePath Path for the resource */ template - void ResourceManager::Unregister(const String& filePath) + void ResourceManager::Unregister(const std::filesystem::path& filePath) { - String absolutePath = File::AbsolutePath(filePath); + std::filesystem::path absolutePath = std::filesystem::canonical(filePath); Type::s_managerMap.erase(absolutePath); } diff --git a/include/Nazara/Core/ResourceSaver.hpp b/include/Nazara/Core/ResourceSaver.hpp index 08e7ae745..3a122013f 100644 --- a/include/Nazara/Core/ResourceSaver.hpp +++ b/include/Nazara/Core/ResourceSaver.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -27,18 +28,18 @@ namespace Nz friend Type; public: - using ExtensionGetter = bool (*)(const String& extension); - using FormatQuerier = bool (*)(const String& format); - using FileSaver = bool (*)(const Type& resource, const String& filePath, const Parameters& parameters); - using StreamSaver = bool (*)(const Type& resource, const String& format, Stream& stream, const Parameters& parameters); + using ExtensionGetter = bool (*)(const std::string& extension); + using FormatQuerier = bool (*)(const std::string& format); + using FileSaver = 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); ResourceSaver() = delete; ~ResourceSaver() = delete; - static bool IsFormatSupported(const String& extension); + static bool IsFormatSupported(const std::string& extension); - static bool SaveToFile(const Type& resource, const String& filePath, const Parameters& parameters = Parameters()); - static bool SaveToStream(const Type& resource, Stream& stream, const String& format, const Parameters& parameters = Parameters()); + static bool SaveToFile(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters = Parameters()); + 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); static void UnregisterSaver(FormatQuerier formatQuerier, StreamSaver streamSaver, FileSaver fileSaver = nullptr); diff --git a/include/Nazara/Core/ResourceSaver.inl b/include/Nazara/Core/ResourceSaver.inl index 007f4cc75..57d038843 100644 --- a/include/Nazara/Core/ResourceSaver.inl +++ b/include/Nazara/Core/ResourceSaver.inl @@ -7,6 +7,7 @@ #include #include #include +#include #include namespace Nz @@ -24,7 +25,7 @@ namespace Nz * \param extension Extension of the file */ template - bool ResourceSaver::IsFormatSupported(const String& extension) + bool ResourceSaver::IsFormatSupported(const std::string& extension) { for (Saver& saver : Type::s_savers) { @@ -51,19 +52,18 @@ namespace Nz * \see SaveToStream */ template - bool ResourceSaver::SaveToFile(const Type& resource, const String& filePath, const Parameters& parameters) + bool ResourceSaver::SaveToFile(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters) { NazaraAssert(parameters.IsValid(), "Invalid parameters"); - String path = File::NormalizePath(filePath); - String ext = path.SubStringFrom('.', -1, true).ToLower(); - if (ext.IsEmpty()) + std::string ext = ToLower(filePath.extension().generic_u8string()); + if (ext.empty()) { - NazaraError("Failed to get file extension from \"" + filePath + '"'); + NazaraError("Failed to get file extension from \"" + filePath.generic_u8string() + '"'); return false; } - File file(path); // Opened only is required + File file(filePath.generic_u8string()); // Opened only is required bool found = false; for (Saver& saver : Type::s_savers) @@ -86,7 +86,7 @@ namespace Nz { if (!file.Open(OpenMode_WriteOnly | OpenMode_Truncate)) { - NazaraError("Failed to save to file: unable to open \"" + filePath + "\" in write mode"); + NazaraError("Failed to save to file: unable to open \"" + filePath.generic_u8string() + "\" in write mode"); return false; } @@ -117,7 +117,7 @@ namespace Nz * \see SaveToFile */ template - bool ResourceSaver::SaveToStream(const Type& resource, Stream& stream, const String& format, const Parameters& parameters) + bool ResourceSaver::SaveToStream(const Type& resource, Stream& stream, const std::string& format, const Parameters& parameters) { NazaraAssert(stream.IsWritable(), "Stream is not writable"); NazaraAssert(parameters.IsValid(), "Invalid parameters"); diff --git a/include/Nazara/Core/Semaphore.hpp b/include/Nazara/Core/Semaphore.hpp deleted file mode 100644 index cb7fdbe56..000000000 --- a/include/Nazara/Core/Semaphore.hpp +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SEMAPHORE_HPP -#define NAZARA_SEMAPHORE_HPP - -#include -#include - -namespace Nz -{ - class SemaphoreImpl; - - class NAZARA_CORE_API Semaphore - { - public: - Semaphore(unsigned int count); - Semaphore(const Semaphore&) = delete; - Semaphore(Semaphore&&) noexcept = default; - ~Semaphore(); - - unsigned int GetCount() const; - - void Post(); - - void Wait(); - bool Wait(UInt32 timeout); - - Semaphore& operator=(const Semaphore&) = delete; - Semaphore& operator=(Semaphore&&) noexcept = default; - - private: - MovablePtr m_impl; - }; -} - -#endif // NAZARA_SEMAPHORE_HPP diff --git a/include/Nazara/Core/SparsePtr.hpp b/include/Nazara/Core/SparsePtr.hpp index 862ddba4c..aad0e453e 100644 --- a/include/Nazara/Core/SparsePtr.hpp +++ b/include/Nazara/Core/SparsePtr.hpp @@ -46,7 +46,7 @@ namespace Nz operator T*() const; T& operator*() const; T* operator->() const; - T& operator[](int index) const; + T& operator[](std::size_t index) const; SparsePtr& operator=(const SparsePtr& ptr) = default; diff --git a/include/Nazara/Core/SparsePtr.inl b/include/Nazara/Core/SparsePtr.inl index ba9400188..db3a60c33 100644 --- a/include/Nazara/Core/SparsePtr.inl +++ b/include/Nazara/Core/SparsePtr.inl @@ -247,7 +247,7 @@ namespace Nz */ template - T& SparsePtr::operator[](int index) const + T& SparsePtr::operator[](std::size_t index) const { return *reinterpret_cast(m_ptr + index * m_stride); } diff --git a/include/Nazara/Core/Stream.hpp b/include/Nazara/Core/Stream.hpp index a1f86e12e..128ccf099 100644 --- a/include/Nazara/Core/Stream.hpp +++ b/include/Nazara/Core/Stream.hpp @@ -10,11 +10,12 @@ #include #include #include +#include +#include namespace Nz { class ByteArray; - class String; //< Do not include String.hpp in this file class NAZARA_CORE_API Stream { @@ -30,15 +31,15 @@ namespace Nz inline void Flush(); virtual UInt64 GetCursorPos() const = 0; - virtual String GetDirectory() const; - virtual String GetPath() const; + virtual std::filesystem::path GetDirectory() const; + virtual std::filesystem::path GetPath() const; inline OpenModeFlags GetOpenMode() const; inline StreamOptionFlags GetStreamOptions() const; virtual UInt64 GetSize() const = 0; inline std::size_t Read(void* buffer, std::size_t size); - virtual String ReadLine(unsigned int lineSize = 0); + virtual std::string ReadLine(unsigned int lineSize = 0); inline bool IsReadable() const; inline bool IsSequential() const; diff --git a/include/Nazara/Core/StringExt.hpp b/include/Nazara/Core/StringExt.hpp new file mode 100644 index 000000000..4d38014e7 --- /dev/null +++ b/include/Nazara/Core/StringExt.hpp @@ -0,0 +1,61 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Core module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#pragma once + +#ifndef NAZARA_CORE_STRING_EXT_HPP +#define NAZARA_CORE_STRING_EXT_HPP + +#include +#include +#include + +namespace Nz +{ + struct CaseIndependent {}; + struct UnicodeAware {}; + + // std::string is assumed to contains UTF-8 + NAZARA_CORE_API std::string FromUtf16String(const char16_t* u16str); + NAZARA_CORE_API std::string FromUtf16String(const std::u16string_view& u16str); + + NAZARA_CORE_API std::string FromUtf32String(const char32_t* u32str); + NAZARA_CORE_API std::string FromUtf32String(const std::u32string_view& u32str); + + NAZARA_CORE_API std::string FromWideString(const wchar_t* wstr); + NAZARA_CORE_API std::string FromWideString(const std::wstring_view& str); + + inline bool IsNumber(const char* str); + inline bool IsNumber(const std::string_view& str); + + template bool StartsWith(const std::string_view& str, const char* s, Args&&... args); + inline bool StartsWith(const std::string_view& str, const std::string_view& s); + NAZARA_CORE_API bool StartsWith(const std::string_view& str, const std::string_view& s, CaseIndependent); + NAZARA_CORE_API bool StartsWith(const std::string_view& str, const std::string_view& s, CaseIndependent, UnicodeAware); + + inline std::string ToLower(const char* str); + NAZARA_CORE_API std::string ToLower(const std::string_view& str); + + inline std::string ToLower(const char* str, UnicodeAware); + NAZARA_CORE_API std::string ToLower(const std::string_view& str, UnicodeAware); + + inline std::string ToUpper(const char* str); + NAZARA_CORE_API std::string ToUpper(const std::string_view& str); + + inline std::string ToUpper(const char* str, UnicodeAware); + NAZARA_CORE_API std::string ToUpper(const std::string_view& str, UnicodeAware); + + inline std::u16string ToUtf16String(const char* str); + NAZARA_CORE_API std::u16string ToUtf16String(const std::string_view& str); + + inline std::u32string ToUtf32String(const char* str); + NAZARA_CORE_API std::u32string ToUtf32String(const std::string_view& str); + + inline std::wstring ToWideString(const char* str); + NAZARA_CORE_API std::wstring ToWideString(const std::string_view& str); +} + +#include + +#endif // NAZARA_ALGORITHM_CORE_HPP diff --git a/include/Nazara/Core/StringExt.inl b/include/Nazara/Core/StringExt.inl new file mode 100644 index 000000000..064ca8be6 --- /dev/null +++ b/include/Nazara/Core/StringExt.inl @@ -0,0 +1,82 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Core module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include + +namespace Nz +{ + bool IsNumber(const char* str) + { + std::size_t size = std::strlen(str); + return IsNumber(std::string_view(str, size)); + } + + bool IsNumber(const std::string_view& str) + { + return !str.empty() && std::find_if(str.begin(), str.end(), [](unsigned char c) { return !std::isdigit(c); }) == str.end(); + } + + template bool StartsWith(const std::string_view& str, const char* s, Args&&... args) + { + std::size_t size = std::strlen(s); + return StartsWith(str, std::string_view(s, size), std::forward(args)...); + } + + bool StartsWith(const std::string_view& str, const std::string_view& s) + { + //FIXME: Replace with proper C++20 value once it's available +#if __cplusplus > 201703L + // C++20 + return str.starts_with(s); +#else + return str.compare(0, s.size(), s.data()) == 0; +#endif + } + + inline std::string ToLower(const char* str) + { + std::size_t size = std::strlen(str); + return ToLower(std::string_view(str, size)); + } + + inline std::string ToLower(const char* str, UnicodeAware) + { + std::size_t size = std::strlen(str); + return ToLower(std::string_view(str, size), UnicodeAware{}); + } + + inline std::string ToUpper(const char* str) + { + std::size_t size = std::strlen(str); + return ToUpper(std::string_view(str, size)); + } + + inline std::string ToUpper(const char* str, UnicodeAware) + { + std::size_t size = std::strlen(str); + return ToUpper(std::string_view(str, size), UnicodeAware{}); + } + + inline std::u16string ToUtf16String(const char* str) + { + std::size_t size = std::strlen(str); + return ToUtf16String(std::string_view(str, size)); + } + + inline std::u32string ToUtf32String(const char* str) + { + std::size_t size = std::strlen(str); + return ToUtf32String(std::string_view(str, size)); + } + + inline std::wstring ToWideString(const char* str) + { + std::size_t size = std::strlen(str); + return ToWideString(std::string_view(str, size)); + } + +} + +#include diff --git a/include/Nazara/Core/Thread.hpp b/include/Nazara/Core/Thread.hpp deleted file mode 100644 index 7143a881f..000000000 --- a/include/Nazara/Core/Thread.hpp +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_THREAD_HPP -#define NAZARA_THREAD_HPP - -#include -#include -#include -#include - -namespace Nz -{ - class String; - class ThreadImpl; - - class NAZARA_CORE_API Thread - { - public: - class Id; - - Thread(); - template Thread(F function); - template Thread(F function, Args&&... args); - template Thread(void (C::*function)(), C* object); - Thread(const Thread&) = delete; - Thread(Thread&& other) noexcept = default; - ~Thread(); - - void Detach(); - Id GetId() const; - bool IsJoinable() const; - void Join(); - void SetName(const String& name); - - Thread& operator=(const Thread&) = delete; - Thread& operator=(Thread&& thread) noexcept = default; - - static unsigned int HardwareConcurrency(); - static void SetCurrentThreadName(const String& name); - static void Sleep(UInt32 milliseconds); - - private: - void CreateImpl(Functor* functor); - - MovablePtr m_impl; - }; - - class NAZARA_CORE_API Thread::Id - { - friend Thread; - - public: - NAZARA_CORE_API friend bool operator==(const Id& lhs, const Id& rhs); - NAZARA_CORE_API friend bool operator!=(const Id& lhs, const Id& rhs); - NAZARA_CORE_API friend bool operator<(const Id& lhs, const Id& rhs); - NAZARA_CORE_API friend bool operator<=(const Id& lhs, const Id& rhs); - NAZARA_CORE_API friend bool operator>(const Id& lhs, const Id& rhs); - NAZARA_CORE_API friend bool operator>=(const Id& lhs, const Id& rhs); - - NAZARA_CORE_API friend std::ostream& operator<<(std::ostream& o, const Id& id); - - private: - explicit Id(ThreadImpl* thread); - - ThreadImpl* m_id = nullptr; - }; -} - -#include - -#endif // NAZARA_THREAD_HPP diff --git a/include/Nazara/Core/Thread.inl b/include/Nazara/Core/Thread.inl deleted file mode 100644 index f2065adfa..000000000 --- a/include/Nazara/Core/Thread.inl +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::Thread - * \brief Core class that represents a thread - */ - - /*! - * \brief Constructs a Thread object with a function - * - * \param function Task the thread will execute in parallel - */ - - template - Thread::Thread(F function) - { - CreateImpl(new FunctorWithoutArgs(function)); - } - - /*! - * \brief Constructs a Thread object with a function and its parameters - * - * \param function Task the thread will execute in parallel - * \param args Arguments of the function - */ - - template - Thread::Thread(F function, Args&&... args) - { - CreateImpl(new FunctorWithArgs(function, std::forward(args)...)); - } - - /*! - * \brief Constructs a Thread object with a member function and its object - * - * \param function Task the thread will execute in parallel - * \param object Object on which the method will be called - */ - - template - Thread::Thread(void (C::*function)(), C* object) - { - CreateImpl(new MemberWithoutArgs(function, object)); - } -} - -#include diff --git a/include/Nazara/Core/ThreadSafety.hpp b/include/Nazara/Core/ThreadSafety.hpp deleted file mode 100644 index 271d6c474..000000000 --- a/include/Nazara/Core/ThreadSafety.hpp +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// No header guard - -#include -#include - -// These macroes can change for any file which uses it in the same unit of compilation -#undef NazaraLock -#undef NazaraMutex -#undef NazaraMutexAttrib -#undef NazaraMutexLock -#undef NazaraMutexUnlock -#undef NazaraNamedLock - -#define NazaraLock(mutex) Nz::LockGuard lock_mutex(mutex); -#define NazaraMutex(name) Nz::Mutex name; -#define NazaraMutexAttrib(name, attribute) attribute Mutex name; -#define NazaraMutexLock(mutex) mutex.Lock(); -#define NazaraMutexUnlock(mutex) mutex.Unlock(); -#define NazaraNamedLock(mutex, name) Nz::LockGuard lock_##name(mutex); diff --git a/include/Nazara/Core/ThreadSafetyOff.hpp b/include/Nazara/Core/ThreadSafetyOff.hpp deleted file mode 100644 index 196ef7d07..000000000 --- a/include/Nazara/Core/ThreadSafetyOff.hpp +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// No header guard - -// These macroes can change for any file which uses it in the same unit of compilation -#undef NazaraLock -#undef NazaraMutex -#undef NazaraMutexAttrib -#undef NazaraMutexLock -#undef NazaraMutexUnlock -#undef NazaraNamedLock - -#define NazaraLock(mutex) -#define NazaraMutex(name) -#define NazaraMutexAttrib(name, attribute) -#define NazaraMutexLock(mutex) -#define NazaraMutexUnlock(mutex) -#define NazaraNamedLock(mutex, name) - diff --git a/include/Nazara/Graphics/Material.hpp b/include/Nazara/Graphics/Material.hpp index 00cbbcbdb..71aff5332 100644 --- a/include/Nazara/Graphics/Material.hpp +++ b/include/Nazara/Graphics/Material.hpp @@ -17,7 +17,6 @@ #include #include #include -#include #include #include #include @@ -35,7 +34,7 @@ namespace Nz bool loadHeightMap = true; bool loadNormalMap = true; bool loadSpecularMap = true; - String shaderName = "Basic"; + std::string shaderName = "Basic"; bool IsValid() const; }; @@ -59,7 +58,7 @@ namespace Nz inline Material(); inline Material(const MaterialPipeline* pipeline); inline Material(const MaterialPipelineInfo& pipelineInfo); - inline Material(const String& pipelineName); + inline Material(const std::string& pipelineName); inline Material(const Material& material); inline ~Material(); @@ -69,7 +68,7 @@ namespace Nz inline void Configure(const MaterialPipeline* pipeline); inline void Configure(const MaterialPipelineInfo& pipelineInfo); - inline bool Configure(const String& pipelineName); + inline bool Configure(const std::string& pipelineName); inline void EnableAlphaTest(bool alphaTest); inline void EnableBlending(bool blending); @@ -141,33 +140,33 @@ namespace Nz void SaveToParameters(ParameterList* matData); - inline bool SetAlphaMap(const String& textureName); + inline bool SetAlphaMap(const std::string& textureName); inline void SetAlphaMap(TextureRef alphaMap); inline void SetAlphaThreshold(float alphaThreshold); inline void SetAmbientColor(const Color& ambient); inline void SetDepthFunc(RendererComparison depthFunc); inline void SetDepthMaterial(MaterialRef depthMaterial); inline void SetDiffuseColor(const Color& diffuse); - inline bool SetDiffuseMap(const String& textureName); + inline bool SetDiffuseMap(const std::string& textureName); inline void SetDiffuseMap(TextureRef diffuseMap); inline void SetDiffuseSampler(const TextureSampler& sampler); inline void SetDstBlend(BlendFunc func); - inline bool SetEmissiveMap(const String& textureName); + inline bool SetEmissiveMap(const std::string& textureName); inline void SetEmissiveMap(TextureRef textureName); inline void SetFaceCulling(FaceSide faceSide); inline void SetFaceFilling(FaceFilling filling); - inline bool SetHeightMap(const String& textureName); + inline bool SetHeightMap(const std::string& textureName); inline void SetHeightMap(TextureRef textureName); inline void SetLineWidth(float lineWidth); - inline bool SetNormalMap(const String& textureName); + inline bool SetNormalMap(const std::string& textureName); inline void SetNormalMap(TextureRef textureName); inline void SetPointSize(float pointSize); inline void SetReflectionMode(ReflectionMode reflectionMode); inline void SetShader(UberShaderConstRef uberShader); - inline bool SetShader(const String& uberShaderName); + inline bool SetShader(const std::string& uberShaderName); inline void SetShininess(float shininess); inline void SetSpecularColor(const Color& specular); - inline bool SetSpecularMap(const String& textureName); + inline bool SetSpecularMap(const std::string& textureName); inline void SetSpecularMap(TextureRef specularMap); inline void SetSpecularSampler(const TextureSampler& sampler); inline void SetSrcBlend(BlendFunc func); @@ -177,7 +176,7 @@ namespace Nz inline static MaterialRef GetDefault(); inline static int GetTextureUnit(TextureMap textureMap); - static inline MaterialRef LoadFromFile(const String& filePath, const MaterialParams& params = MaterialParams()); + static inline MaterialRef LoadFromFile(const std::filesystem::path& filePath, const MaterialParams& params = MaterialParams()); static inline MaterialRef LoadFromMemory(const void* data, std::size_t size, const MaterialParams& params = MaterialParams()); static inline MaterialRef LoadFromStream(Stream& stream, const MaterialParams& params = MaterialParams()); diff --git a/include/Nazara/Graphics/Material.inl b/include/Nazara/Graphics/Material.inl index 66c34e19c..ac22ea266 100644 --- a/include/Nazara/Graphics/Material.inl +++ b/include/Nazara/Graphics/Material.inl @@ -57,7 +57,7 @@ namespace Nz * * \see Configure */ - inline Material::Material(const String& pipelineName) + inline Material::Material(const std::string& pipelineName) { ErrorFlags errFlags(ErrorFlag_ThrowException, true); @@ -139,7 +139,7 @@ namespace Nz * * \see Configure */ - inline bool Material::Configure(const String& pipelineName) + inline bool Material::Configure(const std::string& pipelineName) { MaterialPipelineRef pipeline = MaterialPipelineLibrary::Query(pipelineName); if (!pipeline) @@ -909,7 +909,7 @@ namespace Nz * * \param textureName Named texture */ - inline bool Material::SetAlphaMap(const String& textureName) + inline bool Material::SetAlphaMap(const std::string& textureName) { TextureRef texture = TextureLibrary::Query(textureName); if (!texture) @@ -1005,7 +1005,7 @@ namespace Nz * * \remark Invalidates the pipeline */ - inline bool Material::SetDiffuseMap(const String& textureName) + inline bool Material::SetDiffuseMap(const std::string& textureName) { TextureRef texture = TextureLibrary::Query(textureName); if (!texture) @@ -1071,7 +1071,7 @@ namespace Nz * * \see GetEmissiveMap */ - inline bool Material::SetEmissiveMap(const String& textureName) + inline bool Material::SetEmissiveMap(const std::string& textureName) { TextureRef texture = TextureLibrary::Query(textureName); if (!texture) @@ -1140,7 +1140,7 @@ namespace Nz * * \see GetHeightMap */ - inline bool Material::SetHeightMap(const String& textureName) + inline bool Material::SetHeightMap(const std::string& textureName) { TextureRef texture = TextureLibrary::Query(textureName); if (!texture) @@ -1202,7 +1202,7 @@ namespace Nz * * \see GetNormalMap */ - inline bool Material::SetNormalMap(const String& textureName) + inline bool Material::SetNormalMap(const std::string& textureName) { TextureRef texture = TextureLibrary::Query(textureName); if (!texture) @@ -1305,7 +1305,7 @@ namespace Nz * * \param uberShaderName Named shader */ - inline bool Material::SetShader(const String& uberShaderName) + inline bool Material::SetShader(const std::string& uberShaderName) { UberShaderConstRef uberShader = UberShaderLibrary::Get(uberShaderName); if (!uberShader) @@ -1343,7 +1343,7 @@ namespace Nz * * \remark Invalidates the pipeline */ - inline bool Material::SetSpecularMap(const String& textureName) + inline bool Material::SetSpecularMap(const std::string& textureName) { TextureRef texture = TextureLibrary::Query(textureName); if (!texture) @@ -1444,7 +1444,7 @@ namespace Nz * \param filePath Path to the file * \param params Parameters for the material */ - inline MaterialRef Material::LoadFromFile(const String& filePath, const MaterialParams& params) + inline MaterialRef Material::LoadFromFile(const std::filesystem::path& filePath, const MaterialParams& params) { return MaterialLoader::LoadFromFile(filePath, params); } diff --git a/include/Nazara/Graphics/Model.hpp b/include/Nazara/Graphics/Model.hpp index db73d4f98..70be0d70c 100644 --- a/include/Nazara/Graphics/Model.hpp +++ b/include/Nazara/Graphics/Model.hpp @@ -59,22 +59,22 @@ namespace Nz std::unique_ptr Clone() const override; using InstancedRenderable::GetMaterial; - const MaterialRef& GetMaterial(const String& subMeshName) const; - const MaterialRef& GetMaterial(std::size_t skinIndex, const String& subMeshName) const; + const MaterialRef& GetMaterial(const std::string& subMeshName) const; + const MaterialRef& GetMaterial(std::size_t skinIndex, const std::string& subMeshName) const; Mesh* GetMesh() const; virtual bool IsAnimated() const; using InstancedRenderable::SetMaterial; - bool SetMaterial(const String& subMeshName, MaterialRef material); - bool SetMaterial(std::size_t skinIndex, const String& subMeshName, MaterialRef material); + bool SetMaterial(const std::string& subMeshName, MaterialRef material); + bool SetMaterial(std::size_t skinIndex, const std::string& subMeshName, MaterialRef material); virtual void SetMesh(Mesh* mesh); Model& operator=(const Model& node) = default; Model& operator=(Model&& node) = delete; - static ModelRef LoadFromFile(const String& filePath, const ModelParameters& params = ModelParameters()); + static ModelRef LoadFromFile(const std::filesystem::path& filePath, const ModelParameters& params = ModelParameters()); static ModelRef LoadFromMemory(const void* data, std::size_t size, const ModelParameters& params = ModelParameters()); static ModelRef LoadFromStream(Stream& stream, const ModelParameters& params = ModelParameters()); diff --git a/include/Nazara/Graphics/Sprite.hpp b/include/Nazara/Graphics/Sprite.hpp index 587060467..cba7195df 100644 --- a/include/Nazara/Graphics/Sprite.hpp +++ b/include/Nazara/Graphics/Sprite.hpp @@ -47,15 +47,15 @@ namespace Nz inline void SetCornerColor(RectCorner corner, const Color& color); inline void SetDefaultMaterial(); inline void SetMaterial(MaterialRef material, bool resizeSprite = true); - bool SetMaterial(String materialName, bool resizeSprite = true); + bool SetMaterial(std::string materialName, bool resizeSprite = true); inline void SetMaterial(std::size_t skinIndex, MaterialRef material, bool resizeSprite = true); - bool SetMaterial(std::size_t skinIndex, String materialName, bool resizeSprite = true); + bool SetMaterial(std::size_t skinIndex, std::string materialName, bool resizeSprite = true); inline void SetOrigin(const Vector3f& origin); inline void SetSize(const Vector2f& size); inline void SetSize(float sizeX, float sizeY); - bool SetTexture(String textureName, bool resizeSprite = true); + bool SetTexture(std::string textureName, bool resizeSprite = true); inline void SetTexture(TextureRef texture, bool resizeSprite = true); - bool SetTexture(std::size_t skinIndex, String textureName, bool resizeSprite = true); + bool SetTexture(std::size_t skinIndex, std::string textureName, bool resizeSprite = true); inline void SetTexture(std::size_t skinIndex, TextureRef texture, bool resizeSprite = true); inline void SetTextureCoords(const Rectf& coords); inline void SetTextureRect(const Rectui& rect); diff --git a/include/Nazara/Lua/LuaState.hpp b/include/Nazara/Lua/LuaState.hpp index 4890eae30..8f401a6c3 100644 --- a/include/Nazara/Lua/LuaState.hpp +++ b/include/Nazara/Lua/LuaState.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -87,7 +88,7 @@ namespace Nz void Error(const String& message) const; bool Execute(const String& code, int errorHandler = 0); - bool ExecuteFromFile(const String& filePath, int errorHandler = 0); + bool ExecuteFromFile(const std::filesystem::path& filePath, int errorHandler = 0); bool ExecuteFromMemory(const void* data, std::size_t size, int errorHandler = 0); bool ExecuteFromStream(Stream& stream, int errorHandler = 0); @@ -115,7 +116,7 @@ namespace Nz bool IsValid(int index) const; bool Load(const String& code); - bool LoadFromFile(const String& filePath); + bool LoadFromFile(const std::filesystem::path& filePath); bool LoadFromMemory(const void* data, std::size_t size); bool LoadFromStream(Stream& stream); diff --git a/include/Nazara/Lua/LuaState.inl b/include/Nazara/Lua/LuaState.inl index 97a0827b0..a3a71ef65 100644 --- a/include/Nazara/Lua/LuaState.inl +++ b/include/Nazara/Lua/LuaState.inl @@ -43,6 +43,16 @@ namespace Nz return 1; } + inline unsigned int LuaImplQueryArg(const LuaState& instance, int index, std::filesystem::path* arg, TypeTag) + { + std::size_t strLength = 0; + const char* str = instance.CheckString(index, &strLength); + + arg->assign(std::string_view(str, strLength)); + + return 1; + } + inline unsigned int LuaImplQueryArg(const LuaState& instance, int index, std::string* arg, TypeTag) { std::size_t strLength = 0; @@ -272,6 +282,11 @@ namespace Nz return 1; } + inline int LuaImplReplyVal(const LuaState& instance, std::filesystem::path&& val, TypeTag) + { + return LuaImplReplyVal(instance, val.generic_u8string(), TypeTag()); + } + template inline int LuaImplReplyVal(const LuaState& instance, std::vector&& valContainer, TypeTag>) { diff --git a/include/Nazara/Network/NetPacket.hpp b/include/Nazara/Network/NetPacket.hpp index 37003e14c..be515b81a 100644 --- a/include/Nazara/Network/NetPacket.hpp +++ b/include/Nazara/Network/NetPacket.hpp @@ -10,8 +10,8 @@ #include #include #include -#include #include +#include namespace Nz { @@ -64,7 +64,7 @@ namespace Nz MemoryStream m_memoryStream; UInt16 m_netCode; - static std::unique_ptr s_availableBuffersMutex; + static std::mutex s_availableBuffersMutex; static std::vector>> s_availableBuffers; }; } diff --git a/include/Nazara/Platform/Window.hpp b/include/Nazara/Platform/Window.hpp index 47d416930..4cfff0bed 100644 --- a/include/Nazara/Platform/Window.hpp +++ b/include/Nazara/Platform/Window.hpp @@ -10,9 +10,7 @@ #define NAZARA_WINDOW_HPP #include -#include #include -#include #include #include #include @@ -23,6 +21,8 @@ #include #include #include +#include +#include #include namespace Nz @@ -126,13 +126,13 @@ namespace Nz std::queue m_events; std::vector m_pendingEvents; - ConditionVariable m_eventCondition; + std::condition_variable m_eventCondition; CursorController m_cursorController; CursorRef m_cursor; EventHandler m_eventHandler; IconRef m_icon; - Mutex m_eventMutex; - Mutex m_eventConditionMutex; + std::mutex m_eventMutex; + std::mutex m_eventConditionMutex; bool m_asyncWindow; bool m_closed; bool m_closeOnQuit; diff --git a/include/Nazara/Platform/Window.inl b/include/Nazara/Platform/Window.inl index 1be1a773f..c18ebd26e 100644 --- a/include/Nazara/Platform/Window.inl +++ b/include/Nazara/Platform/Window.inl @@ -4,7 +4,6 @@ #include #include -#include #include namespace Nz @@ -98,16 +97,15 @@ namespace Nz else { { - LockGuard eventLock(m_eventMutex); + std::lock_guard eventLock(m_eventMutex); m_pendingEvents.push_back(event); } if (m_waitForEvent) { - m_eventConditionMutex.Lock(); - m_eventCondition.Signal(); - m_eventConditionMutex.Unlock(); + std::lock_guard lock(m_eventConditionMutex); + m_eventCondition.notify_all(); } } } diff --git a/include/Nazara/Renderer/Shader.hpp b/include/Nazara/Renderer/Shader.hpp index 42e8ba26e..b169f32fc 100644 --- a/include/Nazara/Renderer/Shader.hpp +++ b/include/Nazara/Renderer/Shader.hpp @@ -20,6 +20,7 @@ #include #include #include +#include namespace Nz { @@ -43,7 +44,7 @@ namespace Nz ~Shader(); void AttachStage(ShaderStageType stage, const ShaderStage& shaderStage); - bool AttachStageFromFile(ShaderStageType stage, const String& filePath); + bool AttachStageFromFile(ShaderStageType stage, const std::filesystem::path& filePath); bool AttachStageFromSource(ShaderStageType stage, const char* source, unsigned int length); bool AttachStageFromSource(ShaderStageType stage, const String& source); diff --git a/include/Nazara/Renderer/ShaderStage.hpp b/include/Nazara/Renderer/ShaderStage.hpp index dea80d611..c0ec6d824 100644 --- a/include/Nazara/Renderer/ShaderStage.hpp +++ b/include/Nazara/Renderer/ShaderStage.hpp @@ -11,6 +11,7 @@ #include #include #include +#include namespace Nz { @@ -36,7 +37,7 @@ namespace Nz void SetSource(const char* source, unsigned int length); void SetSource(const String& source); - bool SetSourceFromFile(const String& filePath); + bool SetSourceFromFile(const std::filesystem::path& filePath); ShaderStage& operator=(const ShaderStage&) = delete; ShaderStage& operator=(ShaderStage&& shader); diff --git a/include/Nazara/Renderer/Texture.hpp b/include/Nazara/Renderer/Texture.hpp index b4108f357..69b88f3bf 100644 --- a/include/Nazara/Renderer/Texture.hpp +++ b/include/Nazara/Renderer/Texture.hpp @@ -68,13 +68,13 @@ namespace Nz bool IsValid() const; // LoadFace - bool LoadFaceFromFile(CubemapFace face, const String& filePath, const ImageParams& params = ImageParams()); + bool LoadFaceFromFile(CubemapFace face, const std::filesystem::path& filePath, const ImageParams& params = ImageParams()); bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams()); bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams()); // Save - bool SaveToFile(const String& filePath, const ImageParams& params = ImageParams()); - bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams()); + bool SaveToFile(const std::filesystem::path& filePath, const ImageParams& params = ImageParams()); + bool SaveToStream(Stream& stream, const std::string& format, const ImageParams& params = ImageParams()); bool SetMipmapRange(UInt8 minLevel, UInt8 maxLevel); @@ -96,19 +96,19 @@ namespace Nz static bool IsTypeSupported(ImageType type); // Load - static TextureRef LoadFromFile(const String& filePath, const ImageParams& params = ImageParams(), bool generateMipmaps = true); + static TextureRef LoadFromFile(const std::filesystem::path& filePath, const ImageParams& params = ImageParams(), bool generateMipmaps = true); static TextureRef LoadFromImage(const Image* image, bool generateMipmaps = true); static TextureRef LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams(), bool generateMipmaps = true); static TextureRef LoadFromStream(Stream& stream, const ImageParams& params = ImageParams(), bool generateMipmaps = true); // LoadArray - static TextureRef LoadArrayFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); + static TextureRef LoadArrayFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); static TextureRef LoadArrayFromImage(const Image* image, bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); static TextureRef LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); static TextureRef LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); // LoadCubemap - static TextureRef LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); + static TextureRef LoadCubemapFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); static TextureRef LoadCubemapFromImage(const Image* image, bool generateMipmaps = true, const CubemapParams& params = CubemapParams()); static TextureRef LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); static TextureRef LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); diff --git a/include/Nazara/Renderer/UberShaderPreprocessor.hpp b/include/Nazara/Renderer/UberShaderPreprocessor.hpp index 2c45f9d00..924135290 100644 --- a/include/Nazara/Renderer/UberShaderPreprocessor.hpp +++ b/include/Nazara/Renderer/UberShaderPreprocessor.hpp @@ -32,7 +32,7 @@ namespace Nz UberShaderInstance* Get(const ParameterList& parameters) const override; void SetShader(ShaderStageType stage, const String& source, const String& shaderFlags, const String& requiredFlags = String()); - bool SetShaderFromFile(ShaderStageType stage, const String& filePath, const String& shaderFlags, const String& requiredFlags = String()); + bool SetShaderFromFile(ShaderStageType stage, const std::filesystem::path& filePath, const String& shaderFlags, const String& requiredFlags = String()); static bool IsSupported(); template static UberShaderPreprocessorRef New(Args&&... args); diff --git a/include/Nazara/Utility/Animation.hpp b/include/Nazara/Utility/Animation.hpp index 85f3f3bc8..a1f8f7ffe 100644 --- a/include/Nazara/Utility/Animation.hpp +++ b/include/Nazara/Utility/Animation.hpp @@ -26,9 +26,9 @@ namespace Nz struct NAZARA_UTILITY_API AnimationParams : ResourceParameters { // La frame de fin à charger - UInt32 endFrame = 0xFFFFFFFF; + std::size_t endFrame = 0xFFFFFFFF; // La frame de début à charger - UInt32 startFrame = 0; + std::size_t startFrame = 0; bool IsValid() const; }; @@ -58,37 +58,37 @@ namespace Nz ~Animation(); bool AddSequence(const Sequence& sequence); - void AnimateSkeleton(Skeleton* targetSkeleton, UInt32 frameA, UInt32 frameB, float interpolation) const; + void AnimateSkeleton(Skeleton* targetSkeleton, std::size_t frameA, std::size_t frameB, float interpolation) const; - bool CreateSkeletal(UInt32 frameCount, UInt32 jointCount); + bool CreateSkeletal(std::size_t frameCount, std::size_t jointCount); void Destroy(); void EnableLoopPointInterpolation(bool loopPointInterpolation); - UInt32 GetFrameCount() const; - UInt32 GetJointCount() const; + std::size_t GetFrameCount() const; + std::size_t GetJointCount() const; Sequence* GetSequence(const String& sequenceName); - Sequence* GetSequence(UInt32 index); + Sequence* GetSequence(std::size_t index); const Sequence* GetSequence(const String& sequenceName) const; - const Sequence* GetSequence(UInt32 index) const; - UInt32 GetSequenceCount() const; - UInt32 GetSequenceIndex(const String& sequenceName) const; - SequenceJoint* GetSequenceJoints(UInt32 frameIndex = 0); - const SequenceJoint* GetSequenceJoints(UInt32 frameIndex = 0) const; + const Sequence* GetSequence(std::size_t index) const; + std::size_t GetSequenceCount() const; + std::size_t GetSequenceIndex(const String& sequenceName) const; + SequenceJoint* GetSequenceJoints(std::size_t frameIndex = 0); + const SequenceJoint* GetSequenceJoints(std::size_t frameIndex = 0) const; AnimationType GetType() const; bool HasSequence(const String& sequenceName) const; - bool HasSequence(UInt32 index = 0) const; + bool HasSequence(std::size_t index = 0) const; bool IsLoopPointInterpolationEnabled() const; bool IsValid() const; void RemoveSequence(const String& sequenceName); - void RemoveSequence(UInt32 index); + void RemoveSequence(std::size_t index); template static AnimationRef New(Args&&... args); - static AnimationRef LoadFromFile(const String& filePath, const AnimationParams& params = AnimationParams()); + static AnimationRef 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 AnimationRef LoadFromStream(Stream& stream, const AnimationParams& params = AnimationParams()); diff --git a/include/Nazara/Utility/Font.hpp b/include/Nazara/Utility/Font.hpp index 70cbf6150..bf2561201 100644 --- a/include/Nazara/Utility/Font.hpp +++ b/include/Nazara/Utility/Font.hpp @@ -89,7 +89,7 @@ namespace Nz static unsigned int GetDefaultGlyphBorder(); static unsigned int GetDefaultMinimumStepSize(); - static FontRef OpenFromFile(const String& filePath, const FontParams& params = FontParams()); + static FontRef 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 FontRef OpenFromStream(Stream& stream, const FontParams& params = FontParams()); diff --git a/include/Nazara/Utility/Formats/MD5MeshParser.hpp b/include/Nazara/Utility/Formats/MD5MeshParser.hpp index f5cdb8637..ce8df1630 100644 --- a/include/Nazara/Utility/Formats/MD5MeshParser.hpp +++ b/include/Nazara/Utility/Formats/MD5MeshParser.hpp @@ -49,7 +49,7 @@ namespace Nz std::vector triangles; std::vector vertices; std::vector weights; - String shader; + std::string shader; }; MD5MeshParser(Stream& stream); @@ -66,17 +66,17 @@ namespace Nz private: bool Advance(bool required = true); - void Error(const String& message); + void Error(const std::string& message); bool ParseJoints(); bool ParseMesh(); - void Warning(const String& message); + void Warning(const std::string& message); void UnrecognizedLine(bool error = false); std::vector m_joints; std::vector m_meshes; Stream& m_stream; StreamOptionFlags m_streamFlags; - String m_currentLine; + std::string m_currentLine; bool m_keepLastLine; unsigned int m_lineCount; unsigned int m_meshIndex; diff --git a/include/Nazara/Utility/Formats/MTLParser.hpp b/include/Nazara/Utility/Formats/MTLParser.hpp index 7eb10aaa9..fcc9ec7fb 100644 --- a/include/Nazara/Utility/Formats/MTLParser.hpp +++ b/include/Nazara/Utility/Formats/MTLParser.hpp @@ -9,7 +9,6 @@ #include #include -#include #include #include @@ -23,12 +22,12 @@ namespace Nz MTLParser() = default; ~MTLParser() = default; - inline Material* AddMaterial(const String& matName); + inline Material* AddMaterial(const std::string& matName); inline void Clear(); - inline const Material* GetMaterial(const String& materialName) const; - inline const std::unordered_map& GetMaterials() const; + inline const Material* GetMaterial(const std::string& materialName) const; + inline const std::unordered_map& GetMaterials() const; bool Parse(Stream& stream); @@ -39,17 +38,17 @@ namespace Nz Color ambient = Color::White; Color diffuse = Color::White; Color specular = Color::White; - String alphaMap; - String ambientMap; - String bumpMap; - String decalMap; - String diffuseMap; - String displacementMap; - String emissiveMap; //< Custom addition: not present in MTL - String normalMap; //< Custom addition: not present in MTL - String reflectionMap; - String shininessMap; - String specularMap; + std::string alphaMap; + std::string ambientMap; + std::string bumpMap; + std::string decalMap; + std::string diffuseMap; + std::string displacementMap; + std::string emissiveMap; //< Custom addition: not present in MTL + std::string normalMap; //< Custom addition: not present in MTL + std::string reflectionMap; + std::string shininessMap; + std::string specularMap; float alpha = 1.f; float refractionIndex = 1.f; float shininess = 1.f; @@ -61,14 +60,14 @@ namespace Nz template void Emit(const T& text) const; inline void EmitLine() const; template void EmitLine(const T& line) const; - inline void Error(const String& message); + inline void Error(const std::string& message); inline void Flush() const; - inline void Warning(const String& message); + inline void Warning(const std::string& message); inline void UnrecognizedLine(bool error = false); - std::unordered_map m_materials; + std::unordered_map m_materials; mutable Stream* m_currentStream; - String m_currentLine; + std::string m_currentLine; mutable StringStream m_outputStream; bool m_keepLastLine; unsigned int m_lineCount; diff --git a/include/Nazara/Utility/Formats/MTLParser.inl b/include/Nazara/Utility/Formats/MTLParser.inl index cde870fee..20c95dc9c 100644 --- a/include/Nazara/Utility/Formats/MTLParser.inl +++ b/include/Nazara/Utility/Formats/MTLParser.inl @@ -7,7 +7,7 @@ namespace Nz { - inline MTLParser::Material* MTLParser::AddMaterial(const String& matName) + inline MTLParser::Material* MTLParser::AddMaterial(const std::string& matName) { return &m_materials[matName]; } @@ -17,7 +17,7 @@ namespace Nz m_materials.clear(); } - inline const MTLParser::Material* MTLParser::GetMaterial(const String& materialName) const + inline const MTLParser::Material* MTLParser::GetMaterial(const std::string& materialName) const { auto it = m_materials.find(materialName); if (it != m_materials.end()) @@ -26,7 +26,7 @@ namespace Nz return nullptr; } - inline const std::unordered_map& MTLParser::GetMaterials() const + inline const std::unordered_map& MTLParser::GetMaterials() const { return m_materials; } @@ -51,9 +51,9 @@ namespace Nz Emit('\n'); } - inline void MTLParser::Error(const String& message) + inline void MTLParser::Error(const std::string& message) { - NazaraError(message + " at line #" + String::Number(m_lineCount)); + NazaraError(message + " at line #" + std::to_string(m_lineCount)); } inline void MTLParser::Flush() const @@ -62,14 +62,14 @@ namespace Nz m_outputStream.Clear(); } - inline void MTLParser::Warning(const String& message) + inline void MTLParser::Warning(const std::string& message) { - NazaraWarning(message + " at line #" + String::Number(m_lineCount)); + NazaraWarning(message + " at line #" + std::to_string(m_lineCount)); } inline void MTLParser::UnrecognizedLine(bool error) { - String message = "Unrecognized \"" + m_currentLine + '"'; + std::string message = "Unrecognized \"" + m_currentLine + '"'; if (error) Error(message); diff --git a/include/Nazara/Utility/Formats/OBJParser.hpp b/include/Nazara/Utility/Formats/OBJParser.hpp index 91c82e4d9..4a7a7d50a 100644 --- a/include/Nazara/Utility/Formats/OBJParser.hpp +++ b/include/Nazara/Utility/Formats/OBJParser.hpp @@ -8,7 +8,6 @@ #define NAZARA_FORMATS_OBJPARSER_HPP #include -#include #include #include #include @@ -28,53 +27,53 @@ namespace Nz bool Check(Stream& stream); - inline String* GetMaterials(); - inline const String* GetMaterials() const; - inline UInt32 GetMaterialCount() const; + inline std::string* GetMaterials(); + inline const std::string* GetMaterials() const; + inline std::size_t GetMaterialCount() const; inline Mesh* GetMeshes(); inline const Mesh* GetMeshes() const; - inline UInt32 GetMeshCount() const; - inline const String& GetMtlLib() const; + inline std::size_t GetMeshCount() const; + inline const std::filesystem::path& GetMtlLib() const; inline Vector3f* GetNormals(); inline const Vector3f* GetNormals() const; - inline UInt32 GetNormalCount() const; + inline std::size_t GetNormalCount() const; inline Vector4f* GetPositions(); inline const Vector4f* GetPositions() const; - inline UInt32 GetPositionCount() const; + inline std::size_t GetPositionCount() const; inline Vector3f* GetTexCoords(); inline const Vector3f* GetTexCoords() const; - inline UInt32 GetTexCoordCount() const; + inline std::size_t GetTexCoordCount() const; - bool Parse(Stream& stream, UInt32 reservedVertexCount = 100); + bool Parse(Stream& stream, std::size_t reservedVertexCount = 100); bool Save(Stream& stream) const; - inline String* SetMaterialCount(UInt32 materialCount); - inline Mesh* SetMeshCount(UInt32 meshCount); - inline void SetMtlLib(const String& mtlLib); - inline Vector3f* SetNormalCount(UInt32 normalCount); - inline Vector4f* SetPositionCount(UInt32 positionCount); - inline Vector3f* SetTexCoordCount(UInt32 texCoordCount); + inline std::string* SetMaterialCount(std::size_t materialCount); + inline Mesh* SetMeshCount(std::size_t meshCount); + inline void SetMtlLib(const std::filesystem::path& mtlLib); + inline Vector3f* SetNormalCount(std::size_t normalCount); + inline Vector4f* SetPositionCount(std::size_t positionCount); + inline Vector3f* SetTexCoordCount(std::size_t texCoordCount); struct Face { - UInt32 firstVertex; - UInt32 vertexCount; + std::size_t firstVertex; + std::size_t vertexCount; }; struct FaceVertex { - UInt32 normal; - UInt32 position; - UInt32 texCoord; + std::size_t normal; + std::size_t position; + std::size_t texCoord; }; struct Mesh { std::vector faces; std::vector vertices; - String name; - UInt32 material; + std::string name; + std::size_t material; }; private: @@ -82,19 +81,19 @@ namespace Nz template void Emit(const T& text) const; inline void EmitLine() const; template void EmitLine(const T& line) const; - inline void Error(const String& message); + inline void Error(const std::string& message); inline void Flush() const; - inline void Warning(const String& message); + inline void Warning(const std::string& message); inline bool UnrecognizedLine(bool error = false); std::vector m_meshes; - std::vector m_materials; + std::vector m_materials; std::vector m_normals; std::vector m_positions; std::vector m_texCoords; mutable Stream* m_currentStream; - String m_currentLine; - String m_mtlLib; + std::string m_currentLine; + std::filesystem::path m_mtlLib; mutable StringStream m_outputStream; bool m_keepLastLine; unsigned int m_lineCount; diff --git a/include/Nazara/Utility/Formats/OBJParser.inl b/include/Nazara/Utility/Formats/OBJParser.inl index e1d821a44..af36929a2 100644 --- a/include/Nazara/Utility/Formats/OBJParser.inl +++ b/include/Nazara/Utility/Formats/OBJParser.inl @@ -16,19 +16,19 @@ namespace Nz m_texCoords.clear(); } - inline String* OBJParser::GetMaterials() + inline std::string* OBJParser::GetMaterials() { return m_materials.data(); } - inline const String* OBJParser::GetMaterials() const + inline const std::string* OBJParser::GetMaterials() const { return m_materials.data(); } - inline UInt32 OBJParser::GetMaterialCount() const + inline std::size_t OBJParser::GetMaterialCount() const { - return static_cast(m_materials.size()); + return m_materials.size(); } inline OBJParser::Mesh* OBJParser::GetMeshes() @@ -41,12 +41,12 @@ namespace Nz return m_meshes.data(); } - inline UInt32 OBJParser::GetMeshCount() const + inline std::size_t OBJParser::GetMeshCount() const { - return static_cast(m_meshes.size()); + return m_meshes.size(); } - inline const String& OBJParser::GetMtlLib() const + inline const std::filesystem::path& OBJParser::GetMtlLib() const { return m_mtlLib; } @@ -61,9 +61,9 @@ namespace Nz return m_normals.data(); } - inline UInt32 OBJParser::GetNormalCount() const + inline std::size_t OBJParser::GetNormalCount() const { - return static_cast(m_normals.size()); + return m_normals.size(); } inline Vector4f* OBJParser::GetPositions() @@ -76,9 +76,9 @@ namespace Nz return m_positions.data(); } - inline UInt32 OBJParser::GetPositionCount() const + inline std::size_t OBJParser::GetPositionCount() const { - return static_cast(m_positions.size()); + return m_positions.size(); } inline Vector3f* OBJParser::GetTexCoords() @@ -91,41 +91,41 @@ namespace Nz return m_texCoords.data(); } - inline UInt32 OBJParser::GetTexCoordCount() const + inline std::size_t OBJParser::GetTexCoordCount() const { - return static_cast(m_texCoords.size()); + return m_texCoords.size(); } - inline String* OBJParser::SetMaterialCount(UInt32 materialCount) + inline std::string* OBJParser::SetMaterialCount(std::size_t materialCount) { m_materials.resize(materialCount); return m_materials.data(); } - inline OBJParser::Mesh* OBJParser::SetMeshCount(UInt32 meshCount) + inline OBJParser::Mesh* OBJParser::SetMeshCount(std::size_t meshCount) { m_meshes.resize(meshCount); return m_meshes.data(); } - inline void OBJParser::SetMtlLib(const String& mtlLib) + inline void OBJParser::SetMtlLib(const std::filesystem::path& mtlLib) { m_mtlLib = mtlLib; } - inline Vector3f* OBJParser::SetNormalCount(UInt32 normalCount) + inline Vector3f* OBJParser::SetNormalCount(std::size_t normalCount) { m_normals.resize(normalCount); return m_normals.data(); } - inline Vector4f* OBJParser::SetPositionCount(UInt32 positionCount) + inline Vector4f* OBJParser::SetPositionCount(std::size_t positionCount) { m_positions.resize(positionCount); return m_positions.data(); } - inline Vector3f* OBJParser::SetTexCoordCount(UInt32 texCoordCount) + inline Vector3f* OBJParser::SetTexCoordCount(std::size_t texCoordCount) { m_texCoords.resize(texCoordCount); return m_texCoords.data(); @@ -151,9 +151,9 @@ namespace Nz Emit('\n'); } - inline void OBJParser::Error(const String& message) + inline void OBJParser::Error(const std::string& message) { - NazaraError(message + " at line #" + String::Number(m_lineCount)); + NazaraError(message + " at line #" + std::to_string(m_lineCount)); } inline void OBJParser::Flush() const @@ -162,14 +162,14 @@ namespace Nz m_outputStream.Clear(); } - inline void OBJParser::Warning(const String& message) + inline void OBJParser::Warning(const std::string& message) { - NazaraWarning(message + " at line #" + String::Number(m_lineCount)); + NazaraWarning(message + " at line #" + std::to_string(m_lineCount)); } inline bool OBJParser::UnrecognizedLine(bool error) { - String message = "Unrecognized \"" + m_currentLine + '"'; + std::string message = "Unrecognized \"" + m_currentLine + '"'; if (error) Error(message); diff --git a/include/Nazara/Utility/Image.hpp b/include/Nazara/Utility/Image.hpp index 3c3427b88..1ee0011dc 100644 --- a/include/Nazara/Utility/Image.hpp +++ b/include/Nazara/Utility/Image.hpp @@ -94,13 +94,13 @@ namespace Nz bool IsValid() const; // LoadFace - bool LoadFaceFromFile(CubemapFace face, const String& filePath, const ImageParams& params = ImageParams()); + bool LoadFaceFromFile(CubemapFace face, const std::filesystem::path& filePath, const ImageParams& params = ImageParams()); bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams()); bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams()); // Save - bool SaveToFile(const String& filePath, const ImageParams& params = ImageParams()); - bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams()); + bool SaveToFile(const std::filesystem::path& filePath, const ImageParams& params = ImageParams()); + bool SaveToStream(Stream& stream, const std::string& format, const ImageParams& params = ImageParams()); //TODO: SaveArray, SaveCubemap, SaveFace @@ -118,18 +118,18 @@ namespace Nz static UInt8 GetMaxLevel(ImageType type, unsigned int width, unsigned int height, unsigned int depth = 1); // Load - static ImageRef LoadFromFile(const String& filePath, const ImageParams& params = ImageParams()); + static ImageRef 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 ImageRef LoadFromStream(Stream& stream, const ImageParams& params = ImageParams()); // LoadArray - static ImageRef LoadArrayFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2)); + static ImageRef 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 ImageRef 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)); // LoadCubemap - static ImageRef LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams()); + static ImageRef 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 ImageRef 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()); diff --git a/include/Nazara/Utility/IndexBuffer.hpp b/include/Nazara/Utility/IndexBuffer.hpp index 7feee06e8..fb229f124 100644 --- a/include/Nazara/Utility/IndexBuffer.hpp +++ b/include/Nazara/Utility/IndexBuffer.hpp @@ -24,39 +24,39 @@ namespace Nz public: IndexBuffer() = default; IndexBuffer(bool largeIndices, BufferRef buffer); - IndexBuffer(bool largeIndices, BufferRef buffer, UInt32 offset, UInt32 size); - IndexBuffer(bool largeIndices, UInt32 length, DataStorage storage, BufferUsageFlags usage); + IndexBuffer(bool largeIndices, BufferRef buffer, std::size_t offset, std::size_t size); + IndexBuffer(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage); IndexBuffer(const IndexBuffer& indexBuffer); IndexBuffer(IndexBuffer&&) = delete; ~IndexBuffer(); unsigned int ComputeCacheMissCount() const; - bool Fill(const void* data, UInt32 startIndex, UInt32 length); - bool FillRaw(const void* data, UInt32 offset, UInt32 size); + 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); inline const BufferRef& GetBuffer() const; - inline UInt32 GetEndOffset() const; - inline UInt32 GetIndexCount() const; + inline std::size_t GetEndOffset() const; + inline std::size_t GetIndexCount() const; inline DataStorage GetStorage() const; - inline UInt32 GetStride() const; - inline UInt32 GetStartOffset() const; + inline std::size_t GetStride() const; + inline std::size_t GetStartOffset() const; inline bool HasLargeIndices() const; inline bool IsValid() const; - inline void* Map(BufferAccess access, UInt32 startVertex = 0, UInt32 length = 0); - inline void* Map(BufferAccess access, UInt32 startVertex = 0, UInt32 length = 0) const; - void* MapRaw(BufferAccess access, UInt32 offset = 0, UInt32 size = 0); - void* MapRaw(BufferAccess access, UInt32 offset = 0, UInt32 size = 0) const; + inline void* Map(BufferAccess access, std::size_t startVertex = 0, std::size_t length = 0); + inline void* Map(BufferAccess access, std::size_t startVertex = 0, std::size_t length = 0) const; + void* MapRaw(BufferAccess access, std::size_t offset = 0, std::size_t size = 0); + void* MapRaw(BufferAccess access, std::size_t offset = 0, std::size_t size = 0) const; void Optimize(); void Reset(); void Reset(bool largeIndices, BufferRef buffer); - void Reset(bool largeIndices, BufferRef buffer, UInt32 offset, UInt32 size); - void Reset(bool largeIndices, UInt32 length, DataStorage storage, BufferUsageFlags usage); + void Reset(bool largeIndices, BufferRef buffer, std::size_t offset, std::size_t size); + void Reset(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage); void Reset(const IndexBuffer& indexBuffer); void Unmap() const; @@ -71,9 +71,9 @@ namespace Nz private: BufferRef m_buffer; - UInt32 m_endOffset; - UInt32 m_indexCount; - UInt32 m_startOffset; + std::size_t m_endOffset; + std::size_t m_indexCount; + std::size_t m_startOffset; bool m_largeIndices; }; } diff --git a/include/Nazara/Utility/IndexBuffer.inl b/include/Nazara/Utility/IndexBuffer.inl index 1bcf60b26..8c09ae706 100644 --- a/include/Nazara/Utility/IndexBuffer.inl +++ b/include/Nazara/Utility/IndexBuffer.inl @@ -12,12 +12,12 @@ namespace Nz return m_buffer; } - inline UInt32 IndexBuffer::GetEndOffset() const + inline std::size_t IndexBuffer::GetEndOffset() const { return m_endOffset; } - inline UInt32 IndexBuffer::GetIndexCount() const + inline std::size_t IndexBuffer::GetIndexCount() const { return m_indexCount; } @@ -27,12 +27,12 @@ namespace Nz return DataStorage(); } - inline UInt32 IndexBuffer::GetStride() const + inline std::size_t IndexBuffer::GetStride() const { - return static_cast((m_largeIndices) ? sizeof(UInt32) : sizeof(UInt16)); + return static_cast((m_largeIndices) ? sizeof(std::size_t) : sizeof(UInt16)); } - inline UInt32 IndexBuffer::GetStartOffset() const + inline std::size_t IndexBuffer::GetStartOffset() const { return m_startOffset; } @@ -47,15 +47,15 @@ namespace Nz return m_buffer.IsValid(); } - inline void* IndexBuffer::Map(BufferAccess access, UInt32 startIndex, UInt32 length) + inline void* IndexBuffer::Map(BufferAccess access, std::size_t startIndex, std::size_t length) { - UInt32 stride = GetStride(); + std::size_t stride = GetStride(); return MapRaw(access, startIndex*stride, length*stride); } - inline void* IndexBuffer::Map(BufferAccess access, UInt32 startIndex, UInt32 length) const + inline void* IndexBuffer::Map(BufferAccess access, std::size_t startIndex, std::size_t length) const { - UInt32 stride = GetStride(); + std::size_t stride = GetStride(); return MapRaw(access, startIndex*stride, length*stride); } diff --git a/include/Nazara/Utility/Mesh.hpp b/include/Nazara/Utility/Mesh.hpp index 3c1169bfc..634a66629 100644 --- a/include/Nazara/Utility/Mesh.hpp +++ b/include/Nazara/Utility/Mesh.hpp @@ -89,12 +89,12 @@ namespace Nz inline ~Mesh(); void AddSubMesh(SubMesh* subMesh); - void AddSubMesh(const String& identifier, SubMesh* subMesh); + void AddSubMesh(const std::string& identifier, SubMesh* subMesh); SubMesh* BuildSubMesh(const Primitive& primitive, const MeshParams& params = MeshParams()); void BuildSubMeshes(const PrimitiveList& list, const MeshParams& params = MeshParams()); - bool CreateSkeletal(UInt32 jointCount); + bool CreateSkeletal(std::size_t jointCount); bool CreateStatic(); void Destroy(); @@ -103,25 +103,25 @@ namespace Nz void GenerateTangents(); const Boxf& GetAABB() const; - String GetAnimation() const; + std::filesystem::path GetAnimation() const; AnimationType GetAnimationType() const; - UInt32 GetJointCount() const; - ParameterList& GetMaterialData(UInt32 index); - const ParameterList& GetMaterialData(UInt32 index) const; - UInt32 GetMaterialCount() const; + std::size_t GetJointCount() const; + ParameterList& GetMaterialData(std::size_t index); + const ParameterList& GetMaterialData(std::size_t index) const; + std::size_t GetMaterialCount() const; Skeleton* GetSkeleton(); const Skeleton* GetSkeleton() const; - SubMesh* GetSubMesh(const String& identifier); - SubMesh* GetSubMesh(UInt32 index); - const SubMesh* GetSubMesh(const String& identifier) const; - const SubMesh* GetSubMesh(UInt32 index) const; - UInt32 GetSubMeshCount() const; - UInt32 GetSubMeshIndex(const String& identifier) const; - UInt32 GetTriangleCount() const; - UInt32 GetVertexCount() const; + SubMesh* GetSubMesh(const std::string& identifier); + SubMesh* GetSubMesh(std::size_t index); + const SubMesh* GetSubMesh(const std::string& identifier) const; + const SubMesh* GetSubMesh(std::size_t index) const; + std::size_t GetSubMeshCount() const; + std::size_t GetSubMeshIndex(const std::string& identifier) const; + std::size_t GetTriangleCount() const; + std::size_t GetVertexCount() const; - bool HasSubMesh(const String& identifier) const; - bool HasSubMesh(UInt32 index = 0) const; + bool HasSubMesh(const std::string& identifier) const; + bool HasSubMesh(std::size_t index = 0) const; void InvalidateAABB() const; @@ -130,22 +130,22 @@ namespace Nz void Recenter(); - void RemoveSubMesh(const String& identifier); - void RemoveSubMesh(UInt32 index); + void RemoveSubMesh(const std::string& identifier); + void RemoveSubMesh(std::size_t index); - bool SaveToFile(const String& filePath, const MeshParams& params = MeshParams()); - bool SaveToStream(Stream& stream, const String& format, const MeshParams& params = MeshParams()); + bool SaveToFile(const std::filesystem::path& filePath, const MeshParams& params = MeshParams()); + bool SaveToStream(Stream& stream, const std::string& format, const MeshParams& params = MeshParams()); - void SetAnimation(const String& animationPath); - void SetMaterialCount(UInt32 matCount); - void SetMaterialData(UInt32 matIndex, ParameterList data); + void SetAnimation(const std::filesystem::path& animationPath); + void SetMaterialCount(std::size_t matCount); + void SetMaterialData(std::size_t matIndex, ParameterList data); void Transform(const Matrix4f& matrix); Mesh& operator=(const Mesh&) = delete; Mesh& operator=(Mesh&&) = delete; - static MeshRef LoadFromFile(const String& filePath, const MeshParams& params = MeshParams()); + static MeshRef 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 MeshRef LoadFromStream(Stream& stream, const MeshParams& params = MeshParams()); @@ -164,16 +164,16 @@ namespace Nz NazaraSlot(SubMesh, OnSubMeshInvalidateAABB, onSubMeshInvalidated); }; - std::unordered_map m_subMeshMap; + std::unordered_map m_subMeshMap; std::vector m_materialData; std::vector m_subMeshes; AnimationType m_animationType; mutable Boxf m_aabb; Skeleton m_skeleton; // Only used by skeletal meshes - String m_animationPath; + std::filesystem::path m_animationPath; mutable bool m_aabbUpdated; bool m_isValid; - UInt32 m_jointCount; // Only used by skeletal meshes + std::size_t m_jointCount; // Only used by skeletal meshes static bool Initialize(); static void Uninitialize(); diff --git a/include/Nazara/Utility/SkeletalMesh.hpp b/include/Nazara/Utility/SkeletalMesh.hpp index ebba1cfb5..051e87a8b 100644 --- a/include/Nazara/Utility/SkeletalMesh.hpp +++ b/include/Nazara/Utility/SkeletalMesh.hpp @@ -36,13 +36,13 @@ namespace Nz void Destroy(); const Boxf& GetAABB() const override; - AnimationType GetAnimationType() const final override; + AnimationType GetAnimationType() const final; const IndexBuffer* GetIndexBuffer() const override; VertexBuffer* GetVertexBuffer(); const VertexBuffer* GetVertexBuffer() const; - unsigned int GetVertexCount() const override; + std::size_t GetVertexCount() const override; - bool IsAnimated() const final override; + bool IsAnimated() const final; bool IsValid() const; void SetAABB(const Boxf& aabb); diff --git a/include/Nazara/Utility/Skeleton.hpp b/include/Nazara/Utility/Skeleton.hpp index 75341b9d7..eab57a02b 100644 --- a/include/Nazara/Utility/Skeleton.hpp +++ b/include/Nazara/Utility/Skeleton.hpp @@ -37,21 +37,21 @@ namespace Nz Skeleton(const Skeleton& skeleton); ~Skeleton(); - bool Create(UInt32 jointCount); + bool Create(std::size_t jointCount); void Destroy(); const Boxf& GetAABB() const; Joint* GetJoint(const String& jointName); - Joint* GetJoint(UInt32 index); + Joint* GetJoint(std::size_t index); const Joint* GetJoint(const String& jointName) const; - const Joint* GetJoint(UInt32 index) const; + const Joint* GetJoint(std::size_t index) const; Joint* GetJoints(); const Joint* GetJoints() const; - UInt32 GetJointCount() const; + std::size_t GetJointCount() const; int GetJointIndex(const String& jointName) const; void Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation); - void Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation, UInt32* indices, UInt32 indiceCount); + void Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation, std::size_t* indices, std::size_t indiceCount); bool IsValid() const; diff --git a/include/Nazara/Utility/StaticMesh.hpp b/include/Nazara/Utility/StaticMesh.hpp index 534157fb6..a1b7c5020 100644 --- a/include/Nazara/Utility/StaticMesh.hpp +++ b/include/Nazara/Utility/StaticMesh.hpp @@ -37,13 +37,13 @@ namespace Nz bool GenerateAABB(); const Boxf& GetAABB() const override; - AnimationType GetAnimationType() const final override; + AnimationType GetAnimationType() const final; const IndexBuffer* GetIndexBuffer() const override; VertexBuffer* GetVertexBuffer(); const VertexBuffer* GetVertexBuffer() const; - unsigned int GetVertexCount() const override; + std::size_t GetVertexCount() const override; - bool IsAnimated() const final override; + bool IsAnimated() const final; bool IsValid() const; void SetAABB(const Boxf& aabb); diff --git a/include/Nazara/Utility/SubMesh.hpp b/include/Nazara/Utility/SubMesh.hpp index cfbde074c..19a8aedc5 100644 --- a/include/Nazara/Utility/SubMesh.hpp +++ b/include/Nazara/Utility/SubMesh.hpp @@ -44,14 +44,14 @@ namespace Nz virtual const Boxf& GetAABB() const = 0; virtual AnimationType GetAnimationType() const = 0; virtual const IndexBuffer* GetIndexBuffer() const = 0; - UInt32 GetMaterialIndex() const; + std::size_t GetMaterialIndex() const; PrimitiveMode GetPrimitiveMode() const; - UInt32 GetTriangleCount() const; - virtual UInt32 GetVertexCount() const = 0; + std::size_t GetTriangleCount() const; + virtual std::size_t GetVertexCount() const = 0; virtual bool IsAnimated() const = 0; - void SetMaterialIndex(UInt32 matIndex); + void SetMaterialIndex(std::size_t matIndex); void SetPrimitiveMode(PrimitiveMode mode); SubMesh& operator=(const SubMesh&) = delete; @@ -63,7 +63,7 @@ namespace Nz protected: PrimitiveMode m_primitiveMode; - UInt32 m_matIndex; + std::size_t m_matIndex; }; } diff --git a/include/Nazara/Utility/VertexBuffer.hpp b/include/Nazara/Utility/VertexBuffer.hpp index ca9a20a10..481327a40 100644 --- a/include/Nazara/Utility/VertexBuffer.hpp +++ b/include/Nazara/Utility/VertexBuffer.hpp @@ -26,33 +26,33 @@ namespace Nz public: VertexBuffer() = default; VertexBuffer(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer); - VertexBuffer(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, UInt32 offset, UInt32 size); - VertexBuffer(VertexDeclarationConstRef vertexDeclaration, UInt32 length, DataStorage storage, BufferUsageFlags usage); + VertexBuffer(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, std::size_t offset, std::size_t size); + VertexBuffer(VertexDeclarationConstRef vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage); VertexBuffer(const VertexBuffer& vertexBuffer); VertexBuffer(VertexBuffer&&) = delete; ~VertexBuffer(); - bool Fill(const void* data, UInt32 startVertex, UInt32 length); - bool FillRaw(const void* data, UInt32 offset, UInt32 size); + 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); inline const BufferRef& GetBuffer() const; - inline UInt32 GetEndOffset() const; - inline UInt32 GetStartOffset() const; - inline UInt32 GetStride() const; - inline UInt32 GetVertexCount() const; + inline std::size_t GetEndOffset() const; + inline std::size_t GetStartOffset() const; + inline std::size_t GetStride() const; + inline std::size_t GetVertexCount() const; inline const VertexDeclarationConstRef& GetVertexDeclaration() const; inline bool IsValid() const; - void* Map(BufferAccess access, UInt32 startVertex = 0, UInt32 length = 0); - void* Map(BufferAccess access, UInt32 startVertex = 0, UInt32 length = 0) const; - void* MapRaw(BufferAccess access, UInt32 offset = 0, UInt32 size = 0); - void* MapRaw(BufferAccess access, UInt32 offset = 0, UInt32 size = 0) const; + void* Map(BufferAccess access, std::size_t startVertex = 0, std::size_t length = 0); + void* Map(BufferAccess access, std::size_t startVertex = 0, std::size_t length = 0) const; + void* MapRaw(BufferAccess access, std::size_t offset = 0, std::size_t size = 0); + void* MapRaw(BufferAccess access, std::size_t offset = 0, std::size_t size = 0) const; void Reset(); void Reset(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer); - void Reset(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, UInt32 offset, UInt32 size); - void Reset(VertexDeclarationConstRef vertexDeclaration, UInt32 length, DataStorage storage, BufferUsageFlags usage); + void Reset(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, std::size_t offset, std::size_t size); + void Reset(VertexDeclarationConstRef vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage); void Reset(const VertexBuffer& vertexBuffer); void SetVertexDeclaration(VertexDeclarationConstRef vertexDeclaration); @@ -69,9 +69,9 @@ namespace Nz private: BufferRef m_buffer; - UInt32 m_endOffset; - UInt32 m_startOffset; - UInt32 m_vertexCount; + std::size_t m_endOffset; + std::size_t m_startOffset; + std::size_t m_vertexCount; VertexDeclarationConstRef m_vertexDeclaration; }; } diff --git a/include/Nazara/Utility/VertexBuffer.inl b/include/Nazara/Utility/VertexBuffer.inl index 09f701d12..f7091752e 100644 --- a/include/Nazara/Utility/VertexBuffer.inl +++ b/include/Nazara/Utility/VertexBuffer.inl @@ -12,22 +12,22 @@ namespace Nz return m_buffer; } - inline UInt32 VertexBuffer::GetEndOffset() const + inline std::size_t VertexBuffer::GetEndOffset() const { return m_endOffset; } - inline UInt32 VertexBuffer::GetStride() const + inline std::size_t VertexBuffer::GetStride() const { - return static_cast(m_vertexDeclaration->GetStride()); + return static_cast(m_vertexDeclaration->GetStride()); } - inline UInt32 VertexBuffer::GetStartOffset() const + inline std::size_t VertexBuffer::GetStartOffset() const { return m_startOffset; } - inline UInt32 VertexBuffer::GetVertexCount() const + inline std::size_t VertexBuffer::GetVertexCount() const { return m_vertexCount; } diff --git a/include/Nazara/Utility/VertexMapper.hpp b/include/Nazara/Utility/VertexMapper.hpp index 1b0bfbf3a..d76d830a6 100644 --- a/include/Nazara/Utility/VertexMapper.hpp +++ b/include/Nazara/Utility/VertexMapper.hpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -28,7 +28,7 @@ namespace Nz template SparsePtr GetComponentPtr(VertexComponent component); inline const VertexBuffer* GetVertexBuffer() const; - inline UInt32 GetVertexCount() const; + inline std::size_t GetVertexCount() const; template bool HasComponentOfType(VertexComponent component) const; diff --git a/include/Nazara/Utility/VertexMapper.inl b/include/Nazara/Utility/VertexMapper.inl index f3861541c..bdb1edfc2 100644 --- a/include/Nazara/Utility/VertexMapper.inl +++ b/include/Nazara/Utility/VertexMapper.inl @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -32,7 +32,7 @@ namespace Nz return m_mapper.GetBuffer(); } - inline UInt32 VertexMapper::GetVertexCount() const + inline std::size_t VertexMapper::GetVertexCount() const { return GetVertexBuffer()->GetVertexCount(); } diff --git a/plugins/Assimp/Plugin.cpp b/plugins/Assimp/Plugin.cpp index 3f1e5200a..79efd69f0 100644 --- a/plugins/Assimp/Plugin.cpp +++ b/plugins/Assimp/Plugin.cpp @@ -74,10 +74,10 @@ void ProcessJoints(aiNode* node, Skeleton* skeleton, const std::set& ProcessJoints(node->mChildren[i], skeleton, joints); } -bool IsSupported(const String& extension) +bool IsSupported(const std::string& extension) { - String dotExt = '.' + extension; - return (aiIsExtensionSupported(dotExt.GetConstBuffer()) == AI_TRUE); + std::string dotExt = '.' + extension; + return (aiIsExtensionSupported(dotExt.data()) == AI_TRUE); } Ternary CheckAnimation(Stream& /*stream*/, const AnimationParams& parameters) @@ -91,10 +91,10 @@ Ternary CheckAnimation(Stream& /*stream*/, const AnimationParams& parameters) AnimationRef LoadAnimation(Stream& stream, const AnimationParams& parameters) { - Nz::String streamPath = stream.GetPath(); + std::string streamPath = stream.GetPath().generic_u8string(); FileIOUserdata userdata; - userdata.originalFilePath = (!streamPath.IsEmpty()) ? streamPath.GetConstBuffer() : StreamPath; + userdata.originalFilePath = (!streamPath.empty()) ? streamPath.data() : StreamPath; userdata.originalStream = &stream; aiFileIO fileIO; @@ -186,10 +186,10 @@ Ternary CheckMesh(Stream& /*stream*/, const MeshParams& parameters) MeshRef LoadMesh(Stream& stream, const MeshParams& parameters) { - Nz::String streamPath = stream.GetPath(); + std::string streamPath = stream.GetPath().generic_u8string(); FileIOUserdata userdata; - userdata.originalFilePath = (!streamPath.IsEmpty()) ? streamPath.GetConstBuffer() : StreamPath; + userdata.originalFilePath = (!streamPath.empty()) ? streamPath.data() : StreamPath; userdata.originalStream = &stream; aiFileIO fileIO; @@ -377,7 +377,7 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters) aiTextureMapMode mapMode[3]; if (aiGetMaterialTexture(aiMat, aiType, 0, &path, nullptr, nullptr, nullptr, nullptr, &mapMode[0], nullptr) == aiReturn_SUCCESS) { - matData.SetParameter(textureKey, stream.GetDirectory() + String(path.data, path.length)); + matData.SetParameter(textureKey, (stream.GetDirectory() / std::string_view(path.data, path.length)).generic_u8string()); if (wrapKey) { @@ -563,7 +563,7 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters) aiTextureMapMode mapMode[3]; if (aiGetMaterialTexture(aiMat, aiType, 0, &path, nullptr, nullptr, nullptr, nullptr, &mapMode[0], nullptr) == aiReturn_SUCCESS) { - matData.SetParameter(textureKey, stream.GetDirectory() + String(path.data, path.length)); + matData.SetParameter(textureKey, (stream.GetDirectory() / std::string_view(path.data, path.length)).generic_u8string()); if (wrapKey) { diff --git a/src/Nazara/Audio/Formats/sndfileLoader.cpp b/src/Nazara/Audio/Formats/sndfileLoader.cpp index 75bb3e62f..5d297fc4f 100644 --- a/src/Nazara/Audio/Formats/sndfileLoader.cpp +++ b/src/Nazara/Audio/Formats/sndfileLoader.cpp @@ -14,9 +14,7 @@ #include #include #include -#include #include -#include #include #include #include @@ -99,7 +97,7 @@ namespace Nz return m_format; } - Mutex& GetMutex() override + std::mutex& GetMutex() override { return m_mutex; } @@ -114,11 +112,11 @@ namespace Nz return m_sampleRate; } - bool Open(const String& filePath, bool forceMono) + bool Open(const std::filesystem::path& filePath, bool forceMono) { // Nous devons gérer nous-même le flux car il doit rester ouvert après le passage du loader // (les flux automatiquement ouverts par le ResourceLoader étant fermés après celui-ci) - std::unique_ptr file(new File); + std::unique_ptr file = std::make_unique(); if (!file->Open(filePath, OpenMode_ReadOnly)) { NazaraError("Failed to open stream from file: " + Error::GetLastError()); @@ -219,15 +217,15 @@ namespace Nz AudioFormat m_format; SNDFILE* m_handle; bool m_mixToMono; - Mutex m_mutex; + std::mutex m_mutex; UInt32 m_duration; UInt32 m_sampleRate; UInt64 m_sampleCount; }; - bool IsSupported(const String& extension) + bool IsSupported(const std::string& extension) { - static std::set supportedExtensions = { + static std::set supportedExtensions = { "aiff", "au", "avr", "caf", "flac", "htk", "ircam", "mat4", "mat5", "mpc2k", "nist","ogg", "pvf", "raw", "rf64", "sd2", "sds", "svx", "voc", "w64", "wav", "wve" }; @@ -253,9 +251,9 @@ namespace Nz return Ternary_False; } - SoundStreamRef LoadSoundStreamFile(const String& filePath, const SoundStreamParams& parameters) + SoundStreamRef LoadSoundStreamFile(const std::filesystem::path& filePath, const SoundStreamParams& parameters) { - std::unique_ptr soundStream(new sndfileStream); + std::unique_ptr soundStream = std::make_unique(); if (!soundStream->Open(filePath, parameters.forceMono)) { NazaraError("Failed to open sound stream"); diff --git a/src/Nazara/Audio/Music.cpp b/src/Nazara/Audio/Music.cpp index 356b1b51a..85bdc764e 100644 --- a/src/Nazara/Audio/Music.cpp +++ b/src/Nazara/Audio/Music.cpp @@ -5,12 +5,11 @@ #include #include #include -#include -#include -#include #include +#include #include -#include +#include +#include #include #include @@ -29,9 +28,9 @@ namespace Nz ALenum audioFormat; std::atomic processedSamples; std::vector chunkSamples; - Mutex bufferLock; + std::mutex bufferLock; SoundStreamRef stream; - Thread thread; + std::thread thread; UInt64 playingOffset; bool loop = false; bool streaming = false; @@ -142,7 +141,7 @@ namespace Nz NazaraAssert(m_impl, "Music not created"); // Prevent music thread from enqueing new buffers while we're getting the count - Nz::LockGuard lock(m_impl->bufferLock); + std::lock_guard lock(m_impl->bufferLock); ALint samples = 0; alGetSourcei(m_source, AL_SAMPLE_OFFSET, &samples); @@ -215,7 +214,7 @@ namespace Nz * \param filePath Path to the file * \param params Parameters for the music */ - bool Music::OpenFromFile(const String& filePath, const SoundStreamParams& params) + bool Music::OpenFromFile(const std::filesystem::path& filePath, const SoundStreamParams& params) { if (SoundStreamRef soundStream = SoundStream::OpenFromFile(filePath, params)) return Create(soundStream); @@ -305,7 +304,7 @@ namespace Nz { // Starting streaming's thread m_impl->streaming = true; - m_impl->thread = Thread(&Music::MusicThread, this); + m_impl->thread = std::thread(&Music::MusicThread, this); } } @@ -351,30 +350,29 @@ namespace Nz { std::size_t sampleCount = m_impl->chunkSamples.size(); std::size_t sampleRead = 0; - - Nz::LockGuard lock(m_impl->stream->GetMutex()); - - m_impl->stream->Seek(m_impl->playingOffset); - - // Fill the buffer by reading from the stream - for (;;) { - sampleRead += m_impl->stream->Read(&m_impl->chunkSamples[sampleRead], sampleCount - sampleRead); - if (sampleRead < sampleCount && m_impl->loop) + std::lock_guard lock(m_impl->stream->GetMutex()); + + m_impl->stream->Seek(m_impl->playingOffset); + + // Fill the buffer by reading from the stream + for (;;) { - // In case we read less than expected, assume we reached the end of the stream and seek back to the beginning - m_impl->stream->Seek(0); - continue; + sampleRead += m_impl->stream->Read(&m_impl->chunkSamples[sampleRead], sampleCount - sampleRead); + if (sampleRead < sampleCount && m_impl->loop) + { + // In case we read less than expected, assume we reached the end of the stream and seek back to the beginning + m_impl->stream->Seek(0); + continue; + } + + // Either we read the size we wanted, either we're not looping + break; } - // Either we read the size we wanted, either we're not looping - break; + m_impl->playingOffset = m_impl->stream->Tell(); } - m_impl->playingOffset = m_impl->stream->Tell(); - - lock.Unlock(); - // Update the buffer (send it to OpenAL) and queue it if we got any data if (sampleRead > 0) { @@ -410,31 +408,31 @@ namespace Nz break; } - Nz::LockGuard lock(m_impl->bufferLock); - - // We treat read buffers - ALint processedCount = 0; - alGetSourcei(m_source, AL_BUFFERS_PROCESSED, &processedCount); - while (processedCount--) { - ALuint buffer; - alSourceUnqueueBuffers(m_source, 1, &buffer); + std::lock_guard lock(m_impl->bufferLock); - ALint bits, size; - alGetBufferi(buffer, AL_BITS, &bits); - alGetBufferi(buffer, AL_SIZE, &size); + // We treat read buffers + ALint processedCount = 0; + alGetSourcei(m_source, AL_BUFFERS_PROCESSED, &processedCount); + while (processedCount--) + { + ALuint buffer; + alSourceUnqueueBuffers(m_source, 1, &buffer); - if (bits != 0) - m_impl->processedSamples += (8 * size) / bits; + ALint bits, size; + alGetBufferi(buffer, AL_BITS, &bits); + alGetBufferi(buffer, AL_SIZE, &size); - if (FillAndQueueBuffer(buffer)) - break; + if (bits != 0) + m_impl->processedSamples += (8 * size) / bits; + + if (FillAndQueueBuffer(buffer)) + break; + } } - lock.Unlock(); - // We go back to sleep - Thread::Sleep(50); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); } // Stop playing of the sound (in the case where it has not been already done) @@ -456,7 +454,7 @@ namespace Nz if (m_impl->streaming) { m_impl->streaming = false; - m_impl->thread.Join(); + m_impl->thread.join(); } } } diff --git a/src/Nazara/Audio/OpenAL.cpp b/src/Nazara/Audio/OpenAL.cpp index 755a68a0b..f9e5b346b 100644 --- a/src/Nazara/Audio/OpenAL.cpp +++ b/src/Nazara/Audio/OpenAL.cpp @@ -41,7 +41,7 @@ namespace Nz std::size_t length; while ((length = std::strlen(deviceString)) > 0) { - devices.push_back(String(deviceString, length)); + devices.emplace_back(deviceString, length); deviceString += length + 1; } @@ -140,7 +140,7 @@ namespace Nz bool succeeded = false; for (const char* path : libs) { - String libPath(path); + std::filesystem::path libPath(path); if (!s_library.Load(libPath)) continue; @@ -248,7 +248,7 @@ namespace Nz } catch (const std::exception& e) { - NazaraWarning(libPath + " loading failed: " + String(e.what())); + NazaraWarning(libPath.generic_u8string() + " loading failed: " + std::string(e.what())); continue; } } diff --git a/src/Nazara/Audio/Sound.cpp b/src/Nazara/Audio/Sound.cpp index d4a9e8e06..707ed3a21 100644 --- a/src/Nazara/Audio/Sound.cpp +++ b/src/Nazara/Audio/Sound.cpp @@ -149,12 +149,12 @@ namespace Nz * * \remark Produces a NazaraError if loading failed */ - bool Sound::LoadFromFile(const String& filePath, const SoundBufferParams& params) + bool Sound::LoadFromFile(const std::filesystem::path& filePath, const SoundBufferParams& params) { SoundBufferRef buffer = SoundBuffer::LoadFromFile(filePath, params); if (!buffer) { - NazaraError("Failed to load buffer from file (" + filePath + ')'); + NazaraError("Failed to load buffer from file (" + filePath.generic_u8string() + ')'); return false; } diff --git a/src/Nazara/Audio/SoundBuffer.cpp b/src/Nazara/Audio/SoundBuffer.cpp index e1570b36e..5641e3e57 100644 --- a/src/Nazara/Audio/SoundBuffer.cpp +++ b/src/Nazara/Audio/SoundBuffer.cpp @@ -269,7 +269,7 @@ namespace Nz * \param filePath Path to the file * \param params Parameters for the sound buffer */ - SoundBufferRef SoundBuffer::LoadFromFile(const String& filePath, const SoundBufferParams& params) + SoundBufferRef SoundBuffer::LoadFromFile(const std::filesystem::path& filePath, const SoundBufferParams& params) { return SoundBufferLoader::LoadFromFile(filePath, params); } diff --git a/src/Nazara/Audio/SoundStream.cpp b/src/Nazara/Audio/SoundStream.cpp index 0051b5596..6bfdaafbe 100644 --- a/src/Nazara/Audio/SoundStream.cpp +++ b/src/Nazara/Audio/SoundStream.cpp @@ -21,7 +21,7 @@ namespace Nz SoundStream::~SoundStream() = default; - SoundStreamRef SoundStream::OpenFromFile(const String& filePath, const SoundStreamParams& params) + SoundStreamRef SoundStream::OpenFromFile(const std::filesystem::path& filePath, const SoundStreamParams& params) { return SoundStreamLoader::LoadFromFile(filePath, params); } diff --git a/src/Nazara/Core/Clock.cpp b/src/Nazara/Core/Clock.cpp index 13554a1fa..ee7e32acb 100644 --- a/src/Nazara/Core/Clock.cpp +++ b/src/Nazara/Core/Clock.cpp @@ -12,12 +12,6 @@ #error OS not handled #endif -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_CLOCK - #include -#else - #include -#endif - #include namespace Nz @@ -78,8 +72,6 @@ namespace Nz */ UInt64 Clock::GetMicroseconds() const { - NazaraLock(m_mutex); - UInt64 elapsedMicroseconds = m_elapsedTime; if (!m_paused) elapsedMicroseconds += (GetElapsedMicroseconds() - m_refTime); @@ -106,8 +98,6 @@ namespace Nz */ bool Clock::IsPaused() const { - NazaraLock(m_mutex); - return m_paused; } @@ -121,8 +111,6 @@ namespace Nz */ void Clock::Pause() { - NazaraLock(m_mutex); - if (!m_paused) { m_elapsedTime += GetElapsedMicroseconds() - m_refTime; @@ -139,8 +127,6 @@ namespace Nz */ UInt64 Clock::Restart() { - NazaraLock(m_mutex); - Nz::UInt64 now = GetElapsedMicroseconds(); Nz::UInt64 elapsedTime = m_elapsedTime; @@ -164,8 +150,6 @@ namespace Nz */ void Clock::Unpause() { - NazaraLock(m_mutex); - if (m_paused) { m_refTime = GetElapsedMicroseconds(); diff --git a/src/Nazara/Core/ConditionVariable.cpp b/src/Nazara/Core/ConditionVariable.cpp deleted file mode 100644 index f4314870c..000000000 --- a/src/Nazara/Core/ConditionVariable.cpp +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include - -#if defined(NAZARA_PLATFORM_WINDOWS) - #include -#elif defined(NAZARA_PLATFORM_POSIX) - #include -#else - #error Condition variable has no implementation -#endif - -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::ConditionVariable - * \brief Core class that represents a condition variable - * - * The ConditionVariable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the ConditionVariable - */ - - /*! - * \brief Constructs a ConditionVariable object by default - */ - - ConditionVariable::ConditionVariable() - { - m_impl = new ConditionVariableImpl; - } - - /*! - * \brief Destructs the object - */ - - ConditionVariable::~ConditionVariable() - { - delete m_impl; - } - - /*! - * \brief Sends a signal to one thread waiting on the condition - * - * If any threads are waiting on *this, calling Signal unblocks one of the waiting threads - * - * \see SignalAll - */ - - void ConditionVariable::Signal() - { - m_impl->Signal(); - } - - /*! - * \brief Sends a signal to every threads waiting on the condition - * - * Unblocks all threads currently waiting for *this - * - * \see Signal - */ - - void ConditionVariable::SignalAll() - { - m_impl->SignalAll(); - } - - /*! - * \brief Makes the thread wait on the condition - * - * Wait causes the current thread to block until the condition variable is notified or a spurious wakeup occurs - * - * \param mutex Mutex for the condition - * - * \remark Produces a NazaraAssert if mutex is invalid - */ - - void ConditionVariable::Wait(Mutex* mutex) - { - NazaraAssert(mutex != nullptr, "Mutex must be valid"); - m_impl->Wait(mutex->m_impl); - } - - /*! - * \brief Makes the thread wait on the condition for a certain amount of time - * - * Wait causes the current thread to block until the condition variable is notified, a specific time is reached, or a spurious wakeup occurs - * - * \param mutex Mutex for the condition - * \param timeout Time before expiration of the waiting - * - * \remark Produces a NazaraAssert if mutex is invalid - */ - - bool ConditionVariable::Wait(Mutex* mutex, UInt32 timeout) - { - NazaraAssert(mutex != nullptr, "Mutex must be valid"); - return m_impl->Wait(mutex->m_impl, timeout); - } -} diff --git a/src/Nazara/Core/Directory.cpp b/src/Nazara/Core/Directory.cpp deleted file mode 100644 index 04a2eeb94..000000000 --- a/src/Nazara/Core/Directory.cpp +++ /dev/null @@ -1,535 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include - -#if defined(NAZARA_PLATFORM_WINDOWS) - #include -#elif defined(NAZARA_PLATFORM_POSIX) - #include -#else - #error OS not handled -#endif - -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_DIRECTORY - #include -#else - #include -#endif - -#include - -namespace Nz -{ - namespace - { - //FIXME: MinGW seems to dislike thread_local shared_ptr.. (using a std::string is a working hackfix) - thread_local std::string currentPath(DirectoryImpl::GetCurrent().ToStdString()); - } - - /*! - * \ingroup core - * \class Nz::Directory - * \brief Core class that represents a directory - */ - - /*! - * \brief Constructs a Directory object by default - */ - - Directory::Directory() : - m_pattern('*'), - m_impl(nullptr) - { - } - - /*! - * \brief Constructs a Directory object with a path - * - * \param dirPath Path to the directory - */ - - Directory::Directory(const String& dirPath) : - m_dirPath(dirPath), - m_pattern('*'), - m_impl(nullptr) - { - } - - /*! - * \brief Destructs the object and calls Close - * - * \see Close - */ - - Directory::~Directory() - { - Close(); - } - - /*! - * \brief Closes the directory - */ - - void Directory::Close() - { - NazaraLock(m_mutex); - - if (m_impl) - { - m_impl->Close(); - delete m_impl; - m_impl = nullptr; - } - } - - /*! - * \brief Checks whether the directory exists - * \return true if directory exists - */ - - bool Directory::Exists() const - { - NazaraLock(m_mutex); - - if (IsOpen()) - return true; // If directory is open, then it exists - else - return Exists(m_dirPath); - } - - /*! - * \brief Gets the path of the directory - * \return Path of the directory - */ - - String Directory::GetPath() const - { - NazaraLock(m_mutex); - - return m_dirPath; - } - - /*! - * \brief Gets the pattern for the path of the directory - * \return Pattern for the path of the directory - */ - - String Directory::GetPattern() const - { - NazaraLock(m_mutex); - - return m_pattern; - } - - /*! - * \brief Gets the result name of the directory - * \return Resulting name - * - * \remark Produces a NazaraError if directory is not open with NAZARA_CORE_SAFE defined - */ - - String Directory::GetResultName() const - { - NazaraLock(m_mutex); - - #if NAZARA_CORE_SAFE - if (!IsOpen()) - { - NazaraError("Directory not opened"); - return String(); - } - #endif - - return m_impl->GetResultName(); - } - - /*! - * \brief Gets the result path of the directory - * \return Resulting path - * - * \remark Produces a NazaraError if directory is not open with NAZARA_CORE_SAFE defined - */ - - String Directory::GetResultPath() const - { - NazaraLock(m_mutex); - - #if NAZARA_CORE_SAFE - if (!IsOpen()) - { - NazaraError("Directory not opened"); - return String(); - } - #endif - - return m_dirPath + NAZARA_DIRECTORY_SEPARATOR + m_impl->GetResultName(); - } - - /*! - * \brief Gets the resulting size of the directory - * \return Size of the directory - * - * \remark Produces a NazaraError if directory is not open with NAZARA_CORE_SAFE defined - */ - - UInt64 Directory::GetResultSize() const - { - NazaraLock(m_mutex); - - #if NAZARA_CORE_SAFE - if (!IsOpen()) - { - NazaraError("Directory not opened"); - return 0; - } - #endif - - return m_impl->GetResultSize(); - } - - /*! - * \brief Checks whether the directory is open - * \return true if open - */ - - bool Directory::IsOpen() const - { - NazaraLock(m_mutex); - - return m_impl != nullptr; - } - - /*! - * \brief Checks whether the directory is result - * \return true if result - * - * \remark Produces a NazaraError if directory is not open with NAZARA_CORE_SAFE defined - */ - - bool Directory::IsResultDirectory() const - { - NazaraLock(m_mutex); - - #if NAZARA_CORE_SAFE - if (!IsOpen()) - { - NazaraError("Directory not opened"); - return false; - } - #endif - - return m_impl->IsResultDirectory(); - } - - /*! - * \brief Sets the next result in the directory - * \return true if directory has a next result - * - * \param skipDots Skips the dots in the path - * - * \remark Produces a NazaraError if directory is not open with NAZARA_CORE_SAFE defined - */ - - bool Directory::NextResult(bool skipDots) - { - NazaraLock(m_mutex); - - #if NAZARA_CORE_SAFE - if (!IsOpen()) - { - NazaraError("Directory not opened"); - return false; - } - #endif - - String name; - for (;;) - { - if (!m_impl->NextResult()) - return false; - - name = m_impl->GetResultName(); - - if (skipDots && (name == '.' || name == "..")) - continue; - - if (name.Match(m_pattern)) - break; - } - - return true; - } - - /*! - * \brief Opens the directory - * \return true if opening is successful - */ - - bool Directory::Open() - { - NazaraLock(m_mutex); - - Close(); - - if (!Exists(m_dirPath)) - return false; - - m_impl = new DirectoryImpl(this); - if (!m_impl->Open(m_dirPath)) - { - delete m_impl; - m_impl = nullptr; - - return false; - } - - return true; - } - - /*! - * \brief Sets the path of the directory - * - * \param dirPath Path of the directory - */ - - void Directory::SetPath(const String& dirPath) - { - NazaraLock(m_mutex); - - Close(); - - m_dirPath = File::AbsolutePath(dirPath); - } - - /*! - * \brief Sets the pattern of the directory - * - * \param pattern Pattern of the directory - */ - - void Directory::SetPattern(const String& pattern) - { - NazaraLock(m_mutex); - - m_pattern = pattern; - } - - /*! - * \brief Copies the first directory to a new directory path - * \return true if copy is successful - * - * \param sourcePath Path of the original directory - * \param destPath Path of the copied directory - * - * \remark Produces a NazaraError if could not create destination directory - * \remark Produces a NazaraError if could not open origin directory - * \remark Produces a NazaraError if could not copy a file - */ - - bool Directory::Copy(const String& sourcePath, const String& destPath) - { - if (sourcePath.IsEmpty() || destPath.IsEmpty()) - return false; - - String dirPath(sourcePath); - String dest(File::NormalizePath(destPath)); - - if (!Create(destPath, true)) - { - NazaraError("Unable to create \"" + destPath + '"'); - return false; - } - - Directory dir(dirPath); - if (!dir.Open()) - { - NazaraError("Unable to open \"" + destPath + '"'); - return false; - } - - while (dir.NextResult(true)) - { - if (dir.IsResultDirectory()) - { - if (!Copy(dir.GetResultPath(), dest + NAZARA_DIRECTORY_SEPARATOR + dir.GetResultName())) - return false; - } - else if (!File::Copy(dir.GetResultPath(), dest + NAZARA_DIRECTORY_SEPARATOR + dir.GetResultName())) - { - NazaraError("Failed to copy \"" + dir.GetResultPath() + "\" to \"" + dest + NAZARA_DIRECTORY_SEPARATOR + dir.GetResultName() + '"'); - return false; - } - } - - dir.Close(); - - return true; - } - - /*! - * \brief Creates a directory from a path - * \return true if creation is successful - * - * \param dirPath Path of the directory - * \param recursive Creates subdirectories - */ - - bool Directory::Create(const String& dirPath, bool recursive) - { - if (dirPath.IsEmpty()) - return false; - - if (recursive) - { - String path = File::NormalizePath(dirPath); - std::size_t foundPos = path.Find(NAZARA_DIRECTORY_SEPARATOR); - if (foundPos == String::npos) - return false; - - #ifdef NAZARA_PLATFORM_WINDOWS - // Unlike to disk (Ex: "C:"), the network path is not considered as a directory (Ex: "\\Laptop") - if (path.Match("\\\\*")) - { - foundPos = path.Find('\\', 2); - if (foundPos == String::npos) - return false; - - foundPos = path.Find('\\', foundPos + 1); - if (foundPos == String::npos) - return false; - } - #endif - - for (;;) - { - String p = path.SubString(0, foundPos); - if (p.EndsWith(NAZARA_DIRECTORY_SEPARATOR)) - p = p.SubString(0, -2); - - if (!p.IsEmpty()) - { - if (!DirectoryImpl::Exists(p) && !DirectoryImpl::Create(p)) - return false; - - if (foundPos == String::npos) - break; - } - - foundPos = path.Find(NAZARA_DIRECTORY_SEPARATOR, foundPos + 1); - } - - return true; - } - else - return DirectoryImpl::Create(File::NormalizePath(dirPath)); - } - - /*! - * \brief Checks whether the directory exists - * \return true if directory exists - * - * \param dirPath Path of the directory - */ - - bool Directory::Exists(const String& dirPath) - { - if (dirPath.IsEmpty()) - return false; - - return DirectoryImpl::Exists(File::NormalizePath(dirPath)); - } - - /*! - * \brief Gets the current path of this directory - * \return Current path - */ - - String Directory::GetCurrent() - { - return currentPath; - } - - /*! - * \brief Gets this current file relative to the engine - * \return Path to this file - */ - - const char* Directory::GetCurrentFileRelativeToEngine(const char* currentFile) - { - ///FIXME: Is this method in the right place ? - const char* ptr = std::strstr(currentFile, "NazaraEngine/"); - if (!ptr) - ptr = std::strstr(currentFile, "NazaraEngine\\"); - - if (!ptr) - ptr = currentFile; - - return ptr; - } - - /*! - * \brief Removes the directory - * \return true if remove is successful - * - * \param dirPath Path of the directory - * \param emptyDirectory Remove recursively - */ - - bool Directory::Remove(const String& dirPath, bool emptyDirectory) - { - if (dirPath.IsEmpty()) - return false; - - if (emptyDirectory) - { - Directory dir(dirPath); - if (!dir.Open()) - return DirectoryImpl::Remove(dirPath); // If we can't open the directory, we try to delete it - - while (dir.NextResult(true)) - { - if (dir.IsResultDirectory()) - { - if (!Remove(dir.GetResultPath(), true)) - return false; - } - else if (!File::Delete(dir.GetResultPath())) - { - NazaraError(dir.GetResultPath()); - return false; - } - } - - dir.Close(); - } - - return DirectoryImpl::Remove(File::NormalizePath(dirPath)); - } - - /*! - * \brief Sets the current directory - * \return true if directory path exists - * - * \param dirPath Path of the directory - */ - - bool Directory::SetCurrent(const String& dirPath) - { - String path = File::AbsolutePath(dirPath); - if (DirectoryImpl::Exists(path)) - { - currentPath = path.ToStdString(); - return true; - } - else - return false; - } -} diff --git a/src/Nazara/Core/DynLib.cpp b/src/Nazara/Core/DynLib.cpp index 1558f5a37..486d628b8 100644 --- a/src/Nazara/Core/DynLib.cpp +++ b/src/Nazara/Core/DynLib.cpp @@ -15,12 +15,6 @@ #error No implementation for this platform #endif -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_DYNLIB - #include -#else - #include -#endif - #include namespace Nz @@ -31,35 +25,16 @@ namespace Nz * \brief Core class that represents a dynamic library loader */ - /*! - * \brief Constructs a DynLib object by default - */ - - DynLib::DynLib() : - m_impl(nullptr) - { - } - - /*! - * \brief Destructs the object and calls Unload - * - * \see Unload - */ - - DynLib::~DynLib() - { - Unload(); - } + DynLib::DynLib() = default; + DynLib::DynLib(DynLib&&) noexcept = default; + DynLib::~DynLib() = default; /*! * \brief Gets the last error * \return Last error */ - - String DynLib::GetLastError() const + std::string DynLib::GetLastError() const { - NazaraLock(m_mutex) - return m_lastError; } @@ -69,11 +44,8 @@ namespace Nz * * \remark Produces a NazaraError if library is not loaded with NAZARA_CORE_SAFE defined */ - - DynLibFunc DynLib::GetSymbol(const String& symbol) const + DynLibFunc DynLib::GetSymbol(const char* symbol) const { - NazaraLock(m_mutex) - #if NAZARA_CORE_SAFE if (!IsLoaded()) { @@ -89,7 +61,6 @@ namespace Nz * \brief Checks whether the library is loaded * \return true if loaded */ - bool DynLib::IsLoaded() const { return m_impl != nullptr; @@ -103,38 +74,28 @@ namespace Nz * * \remark Produces a NazaraError if library is could not be loaded */ - - bool DynLib::Load(const String& libraryPath) + bool DynLib::Load(const std::filesystem::path& libraryPath) { - NazaraLock(m_mutex) - Unload(); - std::unique_ptr impl(new DynLibImpl(this)); + auto impl = std::make_unique(this); if (!impl->Load(libraryPath, &m_lastError)) { NazaraError("Failed to load library: " + m_lastError); return false; } - m_impl = impl.release(); - + m_impl = std::move(impl); return true; } /*! * \brief Unloads the library */ - void DynLib::Unload() { - NazaraLock(m_mutex) - - if (IsLoaded()) - { - m_impl->Unload(); - delete m_impl; - m_impl = nullptr; - } + m_impl.reset(); } + + DynLib& DynLib::operator=(DynLib&&) noexcept = default; } diff --git a/src/Nazara/Core/Error.cpp b/src/Nazara/Core/Error.cpp index b5c689971..424a898d0 100644 --- a/src/Nazara/Core/Error.cpp +++ b/src/Nazara/Core/Error.cpp @@ -3,8 +3,9 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include +#include #include +#include #include #include @@ -82,25 +83,21 @@ namespace Nz * \param code Code of the error */ - String Error::GetLastSystemError(unsigned int code) + std::string Error::GetLastSystemError(unsigned int code) { #if defined(NAZARA_PLATFORM_WINDOWS) wchar_t* buffer = nullptr; FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, - code, - 0, - reinterpret_cast(&buffer), - 0, - nullptr); + nullptr, + code, + 0, + reinterpret_cast(&buffer), + 0, + nullptr); - String error(String::Unicode(buffer)); - LocalFree(buffer); - - error.Trim(); // For an unknown reason, Windows put two-three line return after the message - - return error; + CallOnExit freeOnExit([buffer] { LocalFree(buffer); }); + return FromWideString(buffer); #elif defined(NAZARA_PLATFORM_POSIX) return std::strerror(code); #else @@ -166,7 +163,7 @@ namespace Nz void Error::Trigger(ErrorType type, const String& error, unsigned int line, const char* file, const char* function) { - file = Nz::Directory::GetCurrentFileRelativeToEngine(file); + file = GetCurrentFileRelativeToEngine(file); if (type == ErrorType_AssertFailed || (s_flags & ErrorFlag_Silent) == 0 || (s_flags & ErrorFlag_SilentDisabled) != 0) Log::WriteError(type, error, line, file, function); @@ -186,6 +183,17 @@ namespace Nz throw std::runtime_error(error.ToStdString()); } + const char* Error::GetCurrentFileRelativeToEngine(const char* file) + { + if (const char* ptr = std::strstr(file, "NazaraEngine/")) + return ptr; + + if (const char* ptr = std::strstr(file, "NazaraEngine\\")) + return ptr; + + return file; + } + UInt32 Error::s_flags = ErrorFlag_None; String Error::s_lastError; const char* Error::s_lastErrorFunction = ""; diff --git a/src/Nazara/Core/File.cpp b/src/Nazara/Core/File.cpp index 6181f7d1b..c11b92c1f 100644 --- a/src/Nazara/Core/File.cpp +++ b/src/Nazara/Core/File.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -19,12 +18,6 @@ #error OS not handled #endif -#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_FILE - #include -#else - #include -#endif - #include namespace Nz @@ -39,10 +32,7 @@ namespace Nz * \brief Constructs a File object by default */ - File::File() : - m_impl(nullptr) - { - } + File::File() = default; /*! * \brief Constructs a File object with a file path @@ -50,7 +40,7 @@ namespace Nz * \param filePath Path to the file */ - File::File(const String& filePath) : + File::File(const std::filesystem::path& filePath) : File() { SetFile(filePath); @@ -63,7 +53,7 @@ namespace Nz * \param openMode Flag of the file */ - File::File(const String& filePath, OpenModeFlags openMode) : + File::File(const std::filesystem::path& filePath, OpenModeFlags openMode) : File() { Open(filePath, openMode); @@ -75,6 +65,8 @@ namespace Nz * \see Close */ + File::File(File&& file) noexcept = default; + File::~File() { Close(); @@ -82,14 +74,12 @@ namespace Nz /*! * \brief Copies this file to a new file path - * \return true if copy is successful * * \param newFilePath Path of the new file */ - - bool File::Copy(const String& newFilePath) + void File::Copy(const std::filesystem::path& newFilePath) { - return Copy(m_filePath, newFilePath); + std::filesystem::copy(m_filePath, newFilePath); } /*! @@ -98,13 +88,9 @@ namespace Nz void File::Close() { - NazaraLock(m_mutex) - if (m_impl) { - m_impl->Close(); - delete m_impl; - m_impl = nullptr; + m_impl.reset(); m_openMode = OpenMode_NotOpen; } @@ -117,11 +103,9 @@ namespace Nz bool File::Delete() { - NazaraLock(m_mutex) - Close(); - return Delete(m_filePath); + return std::filesystem::remove(m_filePath); } /*! @@ -133,8 +117,6 @@ namespace Nz bool File::EndOfFile() const { - NazaraLock(m_mutex) - #if NAZARA_CORE_SAFE if (!IsOpen()) { @@ -167,24 +149,10 @@ namespace Nz bool File::Exists() const { - NazaraLock(m_mutex) - if (IsOpen()) return true; // Le fichier est ouvert, donc il existe else - return Exists(m_filePath); - } - - /*! - * \brief Gets the creation time of the file - * \return Information about the creation time - */ - - time_t File::GetCreationTime() const - { - NazaraLock(m_mutex) - - return GetCreationTime(m_filePath); + return std::filesystem::exists(m_filePath); } /*! @@ -196,8 +164,6 @@ namespace Nz UInt64 File::GetCursorPos() const { - NazaraLock(m_mutex) - NazaraAssert(IsOpen(), "File is not open"); return m_impl->GetCursorPos(); @@ -207,72 +173,32 @@ namespace Nz * \brief Gets the directory of the file * \return Directory of the file */ - - String File::GetDirectory() const + std::filesystem::path File::GetDirectory() const { - NazaraLock(m_mutex) - - return m_filePath.SubStringTo(NAZARA_DIRECTORY_SEPARATOR, -1, true, true); + return m_filePath.parent_path(); } /*! * \brief Gets the name of the file * \return Name of the file */ - - String File::GetFileName() const + std::filesystem::path File::GetFileName() const { - NazaraLock(m_mutex) - - return m_filePath.SubStringFrom(NAZARA_DIRECTORY_SEPARATOR, -1, true); - } - - /*! - * \brief Gets the last time the file was accessed - * \return Information about the last access time - */ - - time_t File::GetLastAccessTime() const - { - NazaraLock(m_mutex) - - return GetLastAccessTime(m_filePath); - } - - /*! - * \brief Gets the last time the file was written - * \return Information about the last writing time - */ - - time_t File::GetLastWriteTime() const - { - NazaraLock(m_mutex) - - return GetLastWriteTime(m_filePath); + return m_filePath.filename(); } /*! * \brief Gets the path of the file * \return Path of the file */ - - String File::GetPath() const + std::filesystem::path File::GetPath() const { - NazaraLock(m_mutex) - return m_filePath; } - /*! - * \brief Gets the size of the file - * \return Size of the file - */ - UInt64 File::GetSize() const { - NazaraLock(m_mutex) - - return GetSize(m_filePath); + return std::filesystem::file_size(m_filePath); } /*! @@ -282,8 +208,6 @@ namespace Nz bool File::IsOpen() const { - NazaraLock(m_mutex) - return m_impl != nullptr; } @@ -298,26 +222,24 @@ namespace Nz bool File::Open(OpenModeFlags openMode) { - NazaraLock(m_mutex) - Close(); - if (m_filePath.IsEmpty()) + if (m_filePath.empty()) return false; if (openMode == OpenMode_NotOpen) return false; - std::unique_ptr impl(new FileImpl(this)); + std::unique_ptr impl = std::make_unique(this); if (!impl->Open(m_filePath, openMode)) { ErrorFlags flags(ErrorFlag_Silent); // Silent by default - NazaraError("Failed to open \"" + m_filePath + "\": " + Error::GetLastSystemError()); + NazaraError("Failed to open \"" + m_filePath.generic_u8string() + "\": " + Error::GetLastSystemError()); return false; } m_openMode = openMode; - m_impl = impl.release(); + m_impl = std::move(impl); if (m_openMode & OpenMode_Text) m_streamOptions |= StreamOption_Text; @@ -337,38 +259,14 @@ namespace Nz * \remark Produces a NazaraError if OS error to open a file */ - bool File::Open(const String& filePath, OpenModeFlags openMode) + bool File::Open(const std::filesystem::path& filePath, OpenModeFlags openMode) { - NazaraLock(m_mutex) - Close(); SetFile(filePath); return Open(openMode); } - /*! - * \brief Renames the file with a new name - * \return true if rename is successful - */ - - bool File::Rename(const String& newFilePath) - { - NazaraLock(m_mutex) - - bool open = IsOpen(); - Close(); - - bool success = Rename(m_filePath, newFilePath); - if (success) - m_filePath = NormalizePath(newFilePath); - - if (open) - Open(); - - return success; - } - /*! * \brief Sets the position of the cursor * \return true if cursor is successfully positioned @@ -381,8 +279,6 @@ namespace Nz bool File::SetCursorPos(CursorPosition pos, Int64 offset) { - NazaraLock(m_mutex) - NazaraAssert(IsOpen(), "File is not open"); return m_impl->SetCursorPos(pos, offset); @@ -399,8 +295,6 @@ namespace Nz bool File::SetCursorPos(UInt64 offset) { - NazaraLock(m_mutex) - NazaraAssert(IsOpen(), "File is not open"); return m_impl->SetCursorPos(CursorPosition_AtBegin, offset); @@ -413,29 +307,24 @@ namespace Nz * \remark Produces a NazaraError if file path can not be open */ - bool File::SetFile(const String& filePath) + bool File::SetFile(const std::filesystem::path& filePath) { - NazaraLock(m_mutex) - if (IsOpen()) { - if (filePath.IsEmpty()) + if (filePath.empty()) return false; - std::unique_ptr impl(new FileImpl(this)); + std::unique_ptr impl = std::make_unique(this); if (!impl->Open(filePath, m_openMode)) { NazaraError("Failed to open new file; " + Error::GetLastSystemError()); return false; } - m_impl->Close(); - delete m_impl; - - m_impl = impl.release(); + m_impl = std::move(impl); } - m_filePath = AbsolutePath(filePath); + m_filePath = std::filesystem::absolute(filePath); return true; } @@ -450,317 +339,13 @@ namespace Nz */ bool File::SetSize(UInt64 size) { - NazaraLock(m_mutex) - NazaraAssert(IsOpen(), "File is not open"); NazaraAssert(IsWritable(), "File is not writable"); return m_impl->SetSize(size); } - /*! - * \brief Sets the file path - * \return A reference to this - * - * \remark Produces a NazaraError if file path can not be open - */ - - File& File::operator=(const String& filePath) - { - SetFile(filePath); - - return *this; - } - - /*! - * \brief Gets the absolute path of the file - * \return Absolute path of the file - * - * \param filePath Path of the file - * - * \remark Produces a NazaraError if filePath is weird with NAZARA_PLATFORM_WINDOWS defined - */ - - String File::AbsolutePath(const String& filePath) - { - // We don't use OS functions because they only work for existing path - String path = NormalizePath(filePath); - if (path.IsEmpty()) - return String(); - - String base; - unsigned int start; - #ifdef NAZARA_PLATFORM_WINDOWS - if (path.Match("?:*")) - start = 1; - else if (path.Match("\\\\*")) - { - base = "\\\\"; - start = 2; - } - else if (path.StartsWith('\\')) // Special : '\' refering to root - { - String drive = Directory::GetCurrent().SubStringTo('\\'); - String end = path.SubString(1, -1); - if (end.IsEmpty()) - path = drive; - else - path = drive + '\\' + end; - - start = 1; - } - else - { - NazaraError("Path unrecognized"); - return path; - } - #elif defined(NAZARA_PLATFORM_POSIX) - base = '/'; - start = 0; - #else - #error OS case not implemented - #endif - - static String upDir = NAZARA_DIRECTORY_SEPARATOR + String('.'); - - if (path.Find(upDir) == String::npos) - return path; - - std::vector sep; - if (path.Split(sep, NAZARA_DIRECTORY_SEPARATOR) <= 1) - return path; - - // We have the absolute path, but we need to clean it up - for (unsigned int i = 0; i < sep.size(); ++i) - { - if (sep[i] == '.') - sep.erase(sep.begin() + i--); - else if (sep[i] == "..") - { - if (i > start) // If we are not in the protected area - sep.erase(sep.begin() + i--); - - sep.erase(sep.begin() + i--); - } - } - - StringStream stream(base); - for (unsigned int i = 0; i < sep.size(); ++i) - { - if (i != sep.size()-1) - stream << sep[i] << NAZARA_DIRECTORY_SEPARATOR; - else - stream << sep[i]; - } - - return stream; - } - - /*! - * \brief Copies the first file to a new file path - * \return true if copy is successful - * - * \param sourcePath Path of the original file - * \param targetPath Path of the copied file - */ - - bool File::Copy(const String& sourcePath, const String& targetPath) - { - if (sourcePath.IsEmpty() || targetPath.IsEmpty()) - return false; - - return FileImpl::Copy(NormalizePath(sourcePath), NormalizePath(targetPath)); - } - - /*! - * \brief Deletes the file - * \return true if delete is successful - * - * \param filePath Path of the file - */ - - bool File::Delete(const String& filePath) - { - if (filePath.IsEmpty()) - return false; - - return FileImpl::Delete(NormalizePath(filePath)); - } - - /*! - * \brief Checks whether the file exists - * \return true if file exists - * - * \param filePath Path of the file - */ - - bool File::Exists(const String& filePath) - { - if (filePath.IsEmpty()) - return false; - - return FileImpl::Exists(NormalizePath(filePath)); - } - - /*! - * \brief Gets the creation time of the file - * \return Information about the creation time - * - * \param filePath Path of the file - */ - - time_t File::GetCreationTime(const String& filePath) - { - if (filePath.IsEmpty()) - return 0; - - return FileImpl::GetCreationTime(NormalizePath(filePath)); - } - - /*! - * \brief Gets the directory of the file - * \return Directory of the file - * - * \param filePath Path of the file - */ - - String File::GetDirectory(const String& filePath) - { - return filePath.SubStringTo(NAZARA_DIRECTORY_SEPARATOR, -1, true, true); - } - /*! - * \brief Gets the last time the file was accessed - * \return Information about the last access time - * - * \param filePath Path of the file - */ - - time_t File::GetLastAccessTime(const String& filePath) - { - if (filePath.IsEmpty()) - return 0; - - return FileImpl::GetLastAccessTime(NormalizePath(filePath)); - } - - /*! - * \brief Gets the last time the file was written - * \return Information about the last writing time - * - * \param filePath Path of the file - */ - - time_t File::GetLastWriteTime(const String& filePath) - { - if (filePath.IsEmpty()) - return 0; - - return FileImpl::GetLastWriteTime(NormalizePath(filePath)); - } - - /*! - * \brief Gets the size of the file - * \return Size of the file - * - * \param filePath Path of the file - */ - - UInt64 File::GetSize(const String& filePath) - { - if (filePath.IsEmpty()) - return 0; - - return FileImpl::GetSize(NormalizePath(filePath)); - } - - /*! - * \brief Checks whether the file path is absolute - * \return true if path is absolute - * - * \param filePath Path to test - */ - - bool File::IsAbsolute(const String& filePath) - { - String path(filePath.Trimmed()); - if (path.IsEmpty()) - return false; - - path = NormalizeSeparators(path); - - #ifdef NAZARA_PLATFORM_WINDOWS - if (path.Match("?:*")) // Ex: C:\Hello - return true; - else if (path.Match("\\\\*")) // Ex: \\Laptop - return true; - else if (path.StartsWith('\\')) // Special : '\' referring to the root - return true; - else - return false; - #elif defined(NAZARA_PLATFORM_POSIX) - return path.StartsWith('/'); - #else - #error OS case not implemented - #endif - } - - /*! - * \brief Normalizes the file path - * \return Path normalized (replacing '/' with '\\' on Windows, ...) - * - * \param filePath Path to normalize - */ - - String File::NormalizePath(const String& filePath) - { - String path = NormalizeSeparators(filePath.Trimmed()); - - if (!IsAbsolute(path)) - path = Directory::GetCurrent() + NAZARA_DIRECTORY_SEPARATOR + path; - - while (path.EndsWith(NAZARA_DIRECTORY_SEPARATOR)) - path.Resize(-1); - - return path; - } - - /*! - * \brief Normalizes the path separator - * \return Path normalized (replacing '/' with '\\' on Windows, ...) - * - * \param filePath Path to normalize - */ - - String File::NormalizeSeparators(const String& filePath) - { - String path(filePath); - - #if defined(NAZARA_PLATFORM_WINDOWS) - path.Replace('/', '\\'); - #elif defined(NAZARA_PLATFORM_LINUX) - path.Replace('\\', '/'); - #else - #error OS case not implemented - #endif - - return path; - } - - /*! - * \brief Renames the file with a new name - * \return true if rename is successful - * - * \param sourcePath Path of the original file - * \param targetPath Path of the renamed file - */ - - bool File::Rename(const String& sourcePath, const String& targetPath) - { - if (sourcePath.IsEmpty() || targetPath.IsEmpty()) - return false; - - return FileImpl::Rename(NormalizePath(sourcePath), NormalizePath(targetPath)); - } + File& File::operator=(File&& file) noexcept = default; /*! * \brief Flushes the stream @@ -770,8 +355,6 @@ namespace Nz void File::FlushStream() { - NazaraLock(m_mutex) - NazaraAssert(IsOpen(), "File is not open"); m_impl->Flush(); @@ -789,8 +372,6 @@ namespace Nz std::size_t File::ReadBlock(void* buffer, std::size_t size) { - NazaraLock(m_mutex) - NazaraAssert(IsOpen(), "File is not open"); if (size == 0) @@ -822,8 +403,6 @@ namespace Nz std::size_t File::WriteBlock(const void* buffer, std::size_t size) { - NazaraLock(m_mutex) - NazaraAssert(IsOpen(), "File is not open"); if (size == 0) diff --git a/src/Nazara/Core/FileLogger.cpp b/src/Nazara/Core/FileLogger.cpp index 6dadfdcf1..3d4b4a0f9 100644 --- a/src/Nazara/Core/FileLogger.cpp +++ b/src/Nazara/Core/FileLogger.cpp @@ -8,6 +8,8 @@ #include #include #include +#include +#include #include namespace Nz @@ -25,7 +27,7 @@ namespace Nz */ FileLogger::FileLogger(const String& logPath) : - m_outputFile(logPath), + m_outputPath(logPath.ToStdString()), m_forceStdOutput(false), m_stdReplicationEnabled(true), m_timeLoggingEnabled(true) @@ -107,9 +109,10 @@ namespace Nz m_forceStdOutput = false; }); - if (!m_outputFile.IsOpen()) + if (!m_outputFile.is_open()) { - if (!m_outputFile.Open(OpenMode_Text | OpenMode_Truncate | OpenMode_WriteOnly)) + m_outputFile.open(m_outputPath, std::ios_base::trunc | std::ios_base::out); + if (!m_outputFile.is_open()) { NazaraError("Failed to open output file"); return; @@ -117,7 +120,7 @@ namespace Nz } // Apply some processing before writing - StringStream stream; + std::ostringstream stream; if (m_timeLoggingEnabled) { std::array buffer; @@ -130,7 +133,7 @@ namespace Nz stream << string << '\n'; - m_outputFile.Write(stream); + m_outputFile << stream.str(); } /*! @@ -148,6 +151,6 @@ namespace Nz void FileLogger::WriteError(ErrorType type, const String& error, unsigned int line, const char* file, const char* function) { AbstractLogger::WriteError(type, error, line, file, function); - m_outputFile.Flush(); + m_outputFile.flush(); } } diff --git a/src/Nazara/Core/Mutex.cpp b/src/Nazara/Core/Mutex.cpp deleted file mode 100644 index 473ee233e..000000000 --- a/src/Nazara/Core/Mutex.cpp +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -#if defined(NAZARA_PLATFORM_WINDOWS) - #include -#elif defined(NAZARA_PLATFORM_POSIX) - #include -#else - #error Lack of implementation: Mutex -#endif - -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::Mutex - * \brief Core class that represents a binary semaphore, a mutex - * - * \remark The mutex is recursive, it means that a thread who owns the mutex can call the same function which needs the same mutex - */ - - /*! - * \brief Constructs a Mutex object by default - */ - - Mutex::Mutex() - { - m_impl = new MutexImpl; - } - - /*! - * \brief Destructs the object - */ - - Mutex::~Mutex() - { - delete m_impl; - } - - /*! - * \brief Locks the mutex - * - * If another thread has already locked the mutex, a call to lock will block execution until the lock is acquired. A thread may call lock on a recursive mutex repeatedly. Ownership will only be released after the thread makes a matching number of calls to unlock - */ - - void Mutex::Lock() - { - NazaraAssert(m_impl, "Cannot lock a moved mutex"); - m_impl->Lock(); - } - - /*! - * \brief Tries to lock the mutex - * \return true if the lock was acquired successfully - */ - - bool Mutex::TryLock() - { - NazaraAssert(m_impl, "Cannot lock a moved mutex"); - return m_impl->TryLock(); - } - - /*! - * \brief Unlocks the mutex - * - * Unlocks the mutex if its level of ownership is 1 (there was exactly one more call to Lock() than there were calls to Unlock() made by this thread), reduces the level of ownership by 1 otherwise - */ - - void Mutex::Unlock() - { - NazaraAssert(m_impl, "Cannot unlock a moved mutex"); - m_impl->Unlock(); - } -} diff --git a/src/Nazara/Core/PluginManager.cpp b/src/Nazara/Core/PluginManager.cpp index 14bc6744e..8d0769c5e 100644 --- a/src/Nazara/Core/PluginManager.cpp +++ b/src/Nazara/Core/PluginManager.cpp @@ -3,10 +3,8 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include -#include #include #include @@ -17,7 +15,7 @@ namespace Nz using PluginLoad = int (*)(); using PluginUnload = void (*)(); - String s_pluginFiles[] = + std::filesystem::path s_pluginFiles[] = { "PluginAssimp", // Plugin_Assimp }; @@ -37,7 +35,7 @@ namespace Nz * \remark Produces a NazaraError if not initialized */ - void PluginManager::AddDirectory(const String& directoryPath) + void PluginManager::AddDirectory(const std::filesystem::path& directoryPath) { if (!Initialize()) { @@ -45,7 +43,7 @@ namespace Nz return; } - s_directories.insert(File::AbsolutePath(directoryPath)); + s_directories.insert(std::filesystem::absolute(directoryPath)); } /*! @@ -79,9 +77,13 @@ namespace Nz bool PluginManager::Mount(Plugin plugin) { - Nz::String pluginName = s_pluginFiles[plugin]; + std::filesystem::path pluginName = s_pluginFiles[plugin]; + #ifdef NAZARA_DEBUG - if (Mount(pluginName + "-d", true)) + std::filesystem::path debugPath = pluginName; + debugPath += "-d"; + + if (Mount(debugPath, true)) return true; #endif @@ -102,7 +104,7 @@ namespace Nz * \remark Produces a NazaraError if fail to initialize the plugin with PluginLoad */ - bool PluginManager::Mount(const String& pluginPath, bool appendExtension) + bool PluginManager::Mount(const std::filesystem::path& pluginPath, bool appendExtension) { if (!Initialize()) { @@ -110,23 +112,17 @@ namespace Nz return false; } - String path = pluginPath; - if (appendExtension && !path.EndsWith(NAZARA_DYNLIB_EXTENSION)) + std::filesystem::path path = pluginPath; + if (appendExtension && path.extension() == NAZARA_DYNLIB_EXTENSION) path += NAZARA_DYNLIB_EXTENSION; bool exists = false; - if (!File::IsAbsolute(path)) + if (!path.is_absolute()) { - for (const String& dir : s_directories) + for (const std::filesystem::path& dir : s_directories) { - String testPath; - testPath.Reserve(dir.GetSize() + path.GetSize() + 10); - - testPath = dir; - testPath += NAZARA_DIRECTORY_SEPARATOR; - testPath += path; - - if (File::Exists(testPath)) + std::filesystem::path testPath = dir / path; + if (std::filesystem::exists(testPath)) { path = testPath; exists = true; @@ -134,7 +130,7 @@ namespace Nz } } } - else if (File::Exists(path)) + else if (std::filesystem::exists(path)) exists = true; if (!exists) @@ -143,7 +139,7 @@ namespace Nz return false; } - std::unique_ptr library(new DynLib); + std::unique_ptr library = std::make_unique(); if (!library->Load(path)) { NazaraError("Failed to load plugin"); @@ -163,7 +159,8 @@ namespace Nz return false; } - s_plugins[pluginPath] = library.release(); + std::filesystem::path canonicalPath = std::filesystem::canonical(pluginPath); + s_plugins[canonicalPath] = std::move(library); return true; } @@ -176,7 +173,7 @@ namespace Nz * \remark Produces a NazaraError if not initialized */ - void PluginManager::RemoveDirectory(const String& directoryPath) + void PluginManager::RemoveDirectory(const std::filesystem::path& directoryPath) { if (!Initialize()) { @@ -184,7 +181,7 @@ namespace Nz return; } - s_directories.erase(File::AbsolutePath(directoryPath)); + s_directories.erase(std::filesystem::canonical(directoryPath)); } /*! @@ -210,7 +207,7 @@ namespace Nz * \remark Produces a NazaraError if plugin is not loaded */ - void PluginManager::Unmount(const String& pluginPath) + void PluginManager::Unmount(const std::filesystem::path& pluginPath) { if (!Initialize()) { @@ -218,7 +215,8 @@ namespace Nz return; } - auto it = s_plugins.find(pluginPath); + std::filesystem::path canonicalPath = std::filesystem::canonical(pluginPath); + auto it = s_plugins.find(canonicalPath); if (it == s_plugins.end()) { NazaraError("Plugin not loaded"); @@ -229,9 +227,6 @@ namespace Nz if (func) func(); - it->second->Unload(); - delete it->second; - s_plugins.erase(it); } @@ -253,15 +248,12 @@ namespace Nz PluginUnload func = reinterpret_cast(pair.second->GetSymbol("PluginUnload")); if (func) func(); - - pair.second->Unload(); - delete pair.second; } s_plugins.clear(); } - std::set PluginManager::s_directories; - std::unordered_map PluginManager::s_plugins; + std::set PluginManager::s_directories; + std::unordered_map, PluginManager::PathHash> PluginManager::s_plugins; bool PluginManager::s_initialized = false; } diff --git a/src/Nazara/Core/Posix/ConditionVariableImpl.cpp b/src/Nazara/Core/Posix/ConditionVariableImpl.cpp deleted file mode 100644 index 69eb691fa..000000000 --- a/src/Nazara/Core/Posix/ConditionVariableImpl.cpp +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (C) 2015 Alexandre Janniaux -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include - -namespace Nz -{ - ConditionVariableImpl::ConditionVariableImpl() - { - pthread_cond_init(&m_cv, nullptr); - } - - ConditionVariableImpl::~ConditionVariableImpl() - { - pthread_cond_destroy(&m_cv); - } - - void ConditionVariableImpl::Signal() - { - pthread_cond_signal(&m_cv); - } - - void ConditionVariableImpl::SignalAll() - { - pthread_cond_broadcast(&m_cv); - } - - void ConditionVariableImpl::Wait(MutexImpl* mutex) - { - pthread_cond_wait(&m_cv, &mutex->m_handle); - } - - bool ConditionVariableImpl::Wait(MutexImpl* mutex, UInt32 timeout) - { - // get the current time - timeval tv; - gettimeofday(&tv, nullptr); - - // construct the time limit (current time + time to wait) - timespec ti; - ti.tv_nsec = (tv.tv_usec + (timeout % 1000)) * 1000000; - ti.tv_sec = tv.tv_sec + (timeout / 1000) + (ti.tv_nsec / 1000000000); - ti.tv_nsec %= 1000000000; - - return pthread_cond_timedwait(&m_cv,&mutex->m_handle, &ti) != 0; - } -} diff --git a/src/Nazara/Core/Posix/ConditionVariableImpl.hpp b/src/Nazara/Core/Posix/ConditionVariableImpl.hpp deleted file mode 100644 index e5da2d984..000000000 --- a/src/Nazara/Core/Posix/ConditionVariableImpl.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (C) 2015 Alexandre Janniaux -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html - -#pragma once - -#ifndef NAZARA_CONDITIONVARIABLEIMPL_HPP -#define NAZARA_CONDITIONVARIABLEIMPL_HPP - -#include -#include - -namespace Nz -{ - class MutexImpl; - - class ConditionVariableImpl - { - public: - ConditionVariableImpl(); - ~ConditionVariableImpl(); - - void Signal(); - void SignalAll(); - - void Wait(MutexImpl* mutex); - bool Wait(MutexImpl* mutex, UInt32 timeout); - - private: - pthread_cond_t m_cv; - }; -} - -#endif // NAZARA_CONDITIONVARIABLEIMPL_HPP diff --git a/src/Nazara/Core/Posix/DirectoryImpl.cpp b/src/Nazara/Core/Posix/DirectoryImpl.cpp deleted file mode 100644 index e0a7968f0..000000000 --- a/src/Nazara/Core/Posix/DirectoryImpl.cpp +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (C) 2015 Alexandre Janniaux -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - DirectoryImpl::DirectoryImpl(const Directory* parent) : - m_parent(parent) - { - } - - void DirectoryImpl::Close() - { - closedir(m_handle); - } - - String DirectoryImpl::GetResultName() const - { - return m_result->d_name; - } - - UInt64 DirectoryImpl::GetResultSize() const - { - String path = m_parent->GetPath(); - std::size_t pathSize = path.GetSize(); - - std::size_t resultNameSize = std::strlen(m_result->d_name); - - std::size_t fullNameSize = pathSize + 1 + resultNameSize; - StackArray fullName = NazaraStackArrayNoInit(char, fullNameSize + 1); - std::memcpy(&fullName[0], path.GetConstBuffer(), pathSize * sizeof(char)); - fullName[pathSize] = '/'; - std::memcpy(&fullName[pathSize + 1], m_result->d_name, resultNameSize * sizeof(char)); - fullName[fullNameSize] = '\0'; - - struct stat64 results; - stat64(fullName.data(), &results); - - return results.st_size; - } - - bool DirectoryImpl::IsResultDirectory() const - { - //TODO: Fix d_type handling (field can be missing or be a symbolic link, both cases which must be handled by calling stat) - - return m_result->d_type == DT_DIR; - } - - bool DirectoryImpl::NextResult() - { - if ((m_result = readdir64(m_handle))) - return true; - else - { - if (errno == EBADF || errno == EOVERFLOW) - NazaraError("Unable to get next result: " + Error::GetLastSystemError()); - - return false; - } - } - - bool DirectoryImpl::Open(const String& dirPath) - { - m_handle = opendir(dirPath.GetConstBuffer()); - if (!m_handle) - { - NazaraError("Unable to open directory: " + Error::GetLastSystemError()); - return false; - } - - return true; - } - - bool DirectoryImpl::Create(const String& dirPath) - { - mode_t permissions = S_IRWXU | S_IRWXG | S_IRWXO; // 777 - return mkdir(dirPath.GetConstBuffer(), permissions) != -1; - } - - bool DirectoryImpl::Exists(const String& dirPath) - { - struct stat64 filestats; - if (stat64(dirPath.GetConstBuffer(), &filestats) == -1) // error - return false; - - return S_ISDIR(filestats.st_mode) || S_ISREG(filestats.st_mode); - } - - String DirectoryImpl::GetCurrent() - { - String currentPath; - - char path[MAXPATHLEN]; - if (getcwd(path, MAXPATHLEN)) - currentPath = path; - else - NazaraError("Unable to get current directory: " + Error::GetLastSystemError()); // Bug: initialisation -> if no path for log ! - - return currentPath; - } - - bool DirectoryImpl::Remove(const String& dirPath) - { - bool success = rmdir(dirPath.GetConstBuffer()) != -1; - - return success; - } -} diff --git a/src/Nazara/Core/Posix/DirectoryImpl.hpp b/src/Nazara/Core/Posix/DirectoryImpl.hpp deleted file mode 100644 index 907947371..000000000 --- a/src/Nazara/Core/Posix/DirectoryImpl.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (C) 2015 Alexandre Janniaux -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_DIRECTORYIMPL_HPP -#define NAZARA_DIRECTORYIMPL_HPP - -#include -#include - -namespace Nz -{ - class Directory; - class String; - - class DirectoryImpl - { - public: - DirectoryImpl(const Directory* parent); - DirectoryImpl(const DirectoryImpl&) = delete; - DirectoryImpl(DirectoryImpl&&) = delete; ///TODO - ~DirectoryImpl() = default; - - void Close(); - - String GetResultName() const; - UInt64 GetResultSize() const; - - bool IsResultDirectory() const; - - bool NextResult(); - - bool Open(const String& dirPath); - - DirectoryImpl& operator=(const DirectoryImpl&) = delete; - DirectoryImpl& operator=(DirectoryImpl&&) = delete; ///TODO - - static bool Create(const String& dirPath); - static bool Exists(const String& dirPath); - static String GetCurrent(); - static bool Remove(const String& dirPath); - - private: - const Directory* m_parent; - DIR* m_handle; - dirent64* m_result; - }; -} - -#endif // NAZARA_DIRECTORYIMPL_HPP diff --git a/src/Nazara/Core/Posix/FileImpl.cpp b/src/Nazara/Core/Posix/FileImpl.cpp index 5e2cbc200..c08a8c383 100644 --- a/src/Nazara/Core/Posix/FileImpl.cpp +++ b/src/Nazara/Core/Posix/FileImpl.cpp @@ -13,13 +13,14 @@ namespace Nz { FileImpl::FileImpl(const File* parent) : + m_fileDescriptor(-1), m_endOfFile(false), m_endOfFileUpdated(true) { NazaraUnused(parent); } - void FileImpl::Close() + FileImpl::~FileImpl() { if (m_fileDescriptor != -1) close(m_fileDescriptor); @@ -52,7 +53,7 @@ namespace Nz return static_cast(position); } - bool FileImpl::Open(const String& filePath, OpenModeFlags mode) + bool FileImpl::Open(const std::filesystem::path& filePath, OpenModeFlags mode) { int flags; mode_t permissions = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; @@ -75,10 +76,10 @@ namespace Nz if (mode & OpenMode_Truncate) flags |= O_TRUNC; - m_fileDescriptor = open64(filePath.GetConstBuffer(), flags, permissions); + m_fileDescriptor = open64(filePath.generic_u8string().data(), flags, permissions); if (m_fileDescriptor == -1) { - NazaraError("Failed to open \"" + filePath + "\" : " + Error::GetLastSystemError()); + NazaraError("Failed to open \"" + filePath.generic_u8string() + "\" : " + Error::GetLastSystemError()); return false; } @@ -177,121 +178,4 @@ namespace Nz return written; } - - bool FileImpl::Copy(const String& sourcePath, const String& targetPath) - { - int fd1 = open64(sourcePath.GetConstBuffer(), O_RDONLY); - if (fd1 == -1) - { - NazaraError("Fail to open input file (" + sourcePath + "): " + Error::GetLastSystemError()); - return false; - } - - mode_t permissions; - struct stat sb; - if (fstat(fd1, &sb) == -1) // get permission from first file - { - NazaraWarning("Could not get permissions of source file"); - permissions = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; - } - else - { - permissions = sb.st_mode & ~S_IFMT; // S_IFMT: bit mask for the file type bit field -> ~S_IFMT: general permissions - } - - int fd2 = open64(targetPath.GetConstBuffer(), O_WRONLY | O_TRUNC, permissions); - if (fd2 == -1) - { - NazaraError("Fail to open output file (" + targetPath + "): " + Error::GetLastSystemError()); // TODO: more info ? - close(fd1); - return false; - } - - char buffer[512]; - ssize_t bytes; - do - { - bytes = read(fd1,buffer,512); - if (bytes == -1) - { - close(fd1); - close(fd2); - NazaraError("An error occured from copy : " + Error::GetLastSystemError()); - return false; - } - write(fd2,buffer,bytes); - } - while (bytes == 512); - - close(fd1); - close(fd2); - return true; - } - - bool FileImpl::Delete(const String& filePath) - { - bool success = unlink(filePath.GetConstBuffer()) != -1; - - if (success) - return true; - else - { - NazaraError("Failed to delete file (" + filePath + "): " + Error::GetLastSystemError()); - return false; - } - } - - bool FileImpl::Exists(const String& filePath) - { - const char* path = filePath.GetConstBuffer(); - if (access(path, F_OK) != -1) - return true; - - return false; - } - - time_t FileImpl::GetCreationTime(const String& filePath) - { - NazaraUnused(filePath); - - NazaraWarning("Posix has no creation time information"); - return 0; - } - - time_t FileImpl::GetLastAccessTime(const String& filePath) - { - struct stat64 stats; - stat64(filePath.GetConstBuffer(), &stats); - - return stats.st_atime; - } - - time_t FileImpl::GetLastWriteTime(const String& filePath) - { - struct stat64 stats; - stat64(filePath.GetConstBuffer(), &stats); - - return stats.st_mtime; - } - - UInt64 FileImpl::GetSize(const String& filePath) - { - struct stat64 stats; - stat64(filePath.GetConstBuffer(), &stats); - - return static_cast(stats.st_size); - } - - bool FileImpl::Rename(const String& sourcePath, const String& targetPath) - { - bool success = std::rename(sourcePath.GetConstBuffer(), targetPath.GetConstBuffer()) != -1; - - if (success) - return true; - else - { - NazaraError("Unable to rename file: " + Error::GetLastSystemError()); - return false; - } - } } diff --git a/src/Nazara/Core/Posix/FileImpl.hpp b/src/Nazara/Core/Posix/FileImpl.hpp index ef519eda0..d74ae4f3e 100644 --- a/src/Nazara/Core/Posix/FileImpl.hpp +++ b/src/Nazara/Core/Posix/FileImpl.hpp @@ -14,6 +14,7 @@ #include #include #include +#include namespace Nz { @@ -28,11 +29,10 @@ namespace Nz FileImpl(FileImpl&&) = delete; ///TODO ~FileImpl() = default; - void Close(); bool EndOfFile() const; void Flush(); UInt64 GetCursorPos() const; - bool Open(const String& filePath, OpenModeFlags mode); + bool Open(const std::filesystem::path& filePath, OpenModeFlags mode); std::size_t Read(void* buffer, std::size_t size); bool SetCursorPos(CursorPosition pos, Int64 offset); bool SetSize(UInt64 size); @@ -41,15 +41,6 @@ namespace Nz FileImpl& operator=(const FileImpl&) = delete; FileImpl& operator=(FileImpl&&) = delete; ///TODO - static bool Copy(const String& sourcePath, const String& targetPath); - static bool Delete(const String& filePath); - static bool Exists(const String& filePath); - static time_t GetCreationTime(const String& filePath); - static time_t GetLastAccessTime(const String& filePath); - static time_t GetLastWriteTime(const String& filePath); - static UInt64 GetSize(const String& filePath); - static bool Rename(const String& sourcePath, const String& targetPath); - private: int m_fileDescriptor; mutable bool m_endOfFile; diff --git a/src/Nazara/Core/Posix/MutexImpl.cpp b/src/Nazara/Core/Posix/MutexImpl.cpp deleted file mode 100644 index a19720000..000000000 --- a/src/Nazara/Core/Posix/MutexImpl.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2015 Alexandre Janniaux -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - MutexImpl::MutexImpl() - { - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - - pthread_mutex_init(&m_handle, &attr); - } - - MutexImpl::~MutexImpl() - { - pthread_mutex_destroy(&m_handle); - } - - void MutexImpl::Lock() - { - pthread_mutex_lock(&m_handle); - } - - bool MutexImpl::TryLock() - { - return pthread_mutex_trylock(&m_handle) == 0; - } - - void MutexImpl::Unlock() - { - pthread_mutex_unlock(&m_handle); - } -} diff --git a/src/Nazara/Core/Posix/MutexImpl.hpp b/src/Nazara/Core/Posix/MutexImpl.hpp deleted file mode 100644 index 5437ce043..000000000 --- a/src/Nazara/Core/Posix/MutexImpl.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015 Alexandre Janniaux -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_MUTEXIMPL_HPP -#define NAZARA_MUTEXIMPL_HPP - -#include - -namespace Nz -{ - class MutexImpl - { - friend class ConditionVariableImpl; - - public: - MutexImpl(); - ~MutexImpl(); - - void Lock(); - bool TryLock(); - void Unlock(); - - private: - pthread_mutex_t m_handle; - }; -} - -#endif // NAZARA_MUTEXIMPL_HPP diff --git a/src/Nazara/Core/Posix/SemaphoreImpl.cpp b/src/Nazara/Core/Posix/SemaphoreImpl.cpp deleted file mode 100644 index c53928407..000000000 --- a/src/Nazara/Core/Posix/SemaphoreImpl.cpp +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (C) 2015 Alexandre Janniaux -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include - -namespace Nz -{ - SemaphoreImpl::SemaphoreImpl(unsigned int count) - { - if (sem_init(&m_semaphore, 0, count) != 0) - NazaraError("Failed to create semaphore: " + Error::GetLastSystemError()); - } - - SemaphoreImpl::~SemaphoreImpl() - { - sem_destroy(&m_semaphore); - } - - unsigned int SemaphoreImpl::GetCount() const - { - int count=0; - sem_getvalue(const_cast(&m_semaphore), &count); - return static_cast(count); - } - - void SemaphoreImpl::Post() - { - #if NAZARA_CORE_SAFE - if (sem_post(&m_semaphore)==-1) - NazaraError("Failed to release semaphore: " + Error::GetLastSystemError()); - #else - sem_post(&m_semaphore); - #endif - } - - void SemaphoreImpl::Wait() - { - #if NAZARA_CORE_SAFE - if (sem_wait(&m_semaphore) == -1 ) - NazaraError("Failed to wait for semaphore: " + Error::GetLastSystemError()); - #else - sem_wait(&m_semaphore); - #endif - } - - bool SemaphoreImpl::Wait(UInt32 timeout) - { - timeval tv; - gettimeofday(&tv, nullptr); - - timespec ti; - ti.tv_nsec = (tv.tv_usec + (timeout % 1000)) * 1000000; - ti.tv_sec = tv.tv_sec + (timeout / 1000) + (ti.tv_nsec / 1000000000); - ti.tv_nsec %= 1000000000; - - #if NAZARA_CORE_SAFE - if (sem_timedwait(&m_semaphore, &ti) != 0) - { - NazaraError("Failed to wait for semaphore: " + Error::GetLastSystemError()); - return false; - } - - return true; - #else - return sem_timedwait(&m_semaphore, &ti) != 0; - #endif - } -} diff --git a/src/Nazara/Core/Posix/SemaphoreImpl.hpp b/src/Nazara/Core/Posix/SemaphoreImpl.hpp deleted file mode 100644 index 367d35811..000000000 --- a/src/Nazara/Core/Posix/SemaphoreImpl.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015 Alexandre Janniaux -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SEMAPHOREIMPL_HPP -#define NAZARA_SEMAPHOREIMPL_HPP - -#include -#include - -namespace Nz -{ - class SemaphoreImpl - { - public: - SemaphoreImpl(unsigned int count); - ~SemaphoreImpl(); - - unsigned int GetCount() const; - void Post(); - void Wait(); - bool Wait(UInt32 timeout); - - private: - sem_t m_semaphore; - }; -} - -#endif // NAZARA_SEMAPHOREIMPL_HPP diff --git a/src/Nazara/Core/Posix/ThreadImpl.cpp b/src/Nazara/Core/Posix/ThreadImpl.cpp deleted file mode 100644 index 3793ddcf5..000000000 --- a/src/Nazara/Core/Posix/ThreadImpl.cpp +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (C) 2015 Alexandre Janniaux -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - ThreadImpl::ThreadImpl(Functor* functor) - { - int error = pthread_create(&m_handle, nullptr, &ThreadImpl::ThreadProc, functor); - if (error != 0) - NazaraInternalError("Failed to create thread: " + Error::GetLastSystemError()); - } - - void ThreadImpl::Detach() - { - pthread_detach(m_handle); - } - - void ThreadImpl::Join() - { - pthread_join(m_handle, nullptr); - } - - void ThreadImpl::SetName(const Nz::String& name) - { -#ifdef __GNUC__ - pthread_setname_np(m_handle, name.GetConstBuffer()); -#else - NazaraWarning("Setting thread name is not supported on this platform"); -#endif - } - - void ThreadImpl::SetCurrentName(const Nz::String& name) - { -#ifdef __GNUC__ - pthread_setname_np(pthread_self(), name.GetConstBuffer()); -#else - NazaraWarning("Setting current thread name is not supported on this platform"); -#endif - } - - void ThreadImpl::Sleep(UInt32 time) - { - if (time == 0) - sched_yield(); - else - { - struct timespec ts; - ts.tv_sec = time / 1000; - ts.tv_nsec = (time - ts.tv_sec * 1000) * 1'000'000; - - int r; - do - { - r = nanosleep(&ts, &ts); - } - while (r == -1 && errno == EINTR); - } - } - - void* ThreadImpl::ThreadProc(void* userdata) - { - Functor* func = static_cast(userdata); - func->Run(); - delete func; - - return nullptr; - } -} diff --git a/src/Nazara/Core/Posix/ThreadImpl.hpp b/src/Nazara/Core/Posix/ThreadImpl.hpp deleted file mode 100644 index f8c024cb5..000000000 --- a/src/Nazara/Core/Posix/ThreadImpl.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2015 Alexandre Janniaux -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_THREADIMPL_HPP -#define NAZARA_THREADIMPL_HPP - -#include - -#if defined(__GNUC__) && !defined(_GNU_SOURCE) -#define _GNU_SOURCE -#endif - -#include - -namespace Nz -{ - struct Functor; - class String; - - class ThreadImpl - { - public: - ThreadImpl(Functor* threadFunc); - - void Detach(); - void Join(); - void SetName(const Nz::String& name); - - static void SetCurrentName(const Nz::String& name); - static void Sleep(UInt32 time); - - private: - static void* ThreadProc(void* userdata); - - pthread_t m_handle; - }; -} - -#endif // NAZARA_THREADIMPL_HPP diff --git a/src/Nazara/Core/Resource.cpp b/src/Nazara/Core/Resource.cpp index efd8a4eb6..d409d15cc 100644 --- a/src/Nazara/Core/Resource.cpp +++ b/src/Nazara/Core/Resource.cpp @@ -20,7 +20,7 @@ namespace Nz * \return A reference to the path */ - const String& Resource::GetFilePath() const + const std::filesystem::path& Resource::GetFilePath() const { return m_filePath; } @@ -31,7 +31,7 @@ namespace Nz * \param filePath Path to the resource */ - void Resource::SetFilePath(const String& filePath) + void Resource::SetFilePath(const std::filesystem::path& filePath) { m_filePath = filePath; } diff --git a/src/Nazara/Core/Semaphore.cpp b/src/Nazara/Core/Semaphore.cpp deleted file mode 100644 index e4a52b43f..000000000 --- a/src/Nazara/Core/Semaphore.cpp +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include - -#if defined(NAZARA_PLATFORM_WINDOWS) - #include -#elif defined(NAZARA_PLATFORM_POSIX) - #include -#else - #error Lack of implementation: Semaphore -#endif - -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::Semaphore - * \brief Core class that represents a counting semaphore - */ - - /*! - * \brief Constructs a semaphore object with a count - */ - - Semaphore::Semaphore(unsigned int count) - { - m_impl = new SemaphoreImpl(count); - } - - /*! - * \brief Destructs the object - */ - - Semaphore::~Semaphore() - { - delete m_impl; - } - - /*! - * \brief Gets the number of count that can handle the semaphore - * \return Number of count associated with the semaphore - */ - - unsigned int Semaphore::GetCount() const - { - return m_impl->GetCount(); - } - - /*! - * \brief Increments the count of the semaphore and wait if count equals zero - * - * Increments the value of semaphore variable by 1. After the increment, if the pre-increment value was negative (meaning there are processes waiting for a resource), it transfers a blocked process from the semaphore's waiting queue to the ready queue - */ - - void Semaphore::Post() - { - m_impl->Post(); - } - - /*! - * \brief Decrements the count of the semaphore and wait if count equals zero - * - * If the value of semaphore variable is not negative, decrements it by 1. If the semaphore variable is now negative, the process executing Wait is blocked (i.e., added to the semaphore's queue) until the value is greater or equal to 1. Otherwise, the process continues execution, having used a unit of the resource - */ - - void Semaphore::Wait() - { - m_impl->Wait(); - } - - /*! - * \brief Decrements the count of the semaphore and wait if count equals zero - * \return true if the semaphore successfully decrements before timeout - * - * If the value of semaphore variable is not negative, decrements it by 1. If the semaphore variable is now negative, the process executing Wait is blocked (i.e., added to the semaphore's queue) until the value is greater or equal to 1. Otherwise, the process continues execution, having used a unit of the resource - */ - - bool Semaphore::Wait(UInt32 timeout) - { - return m_impl->Wait(timeout); - } -} diff --git a/src/Nazara/Core/Stream.cpp b/src/Nazara/Core/Stream.cpp index 7ae91ed93..c607ff313 100644 --- a/src/Nazara/Core/Stream.cpp +++ b/src/Nazara/Core/Stream.cpp @@ -28,9 +28,9 @@ namespace Nz * \return Empty string (meant to be virtual) */ - String Stream::GetDirectory() const + std::filesystem::path Stream::GetDirectory() const { - return String(); + return std::filesystem::path(); } /*! @@ -38,9 +38,9 @@ namespace Nz * \return Empty string (meant to be virtual) */ - String Stream::GetPath() const + std::filesystem::path Stream::GetPath() const { - return String(); + return std::filesystem::path(); } /*! @@ -57,9 +57,9 @@ namespace Nz * \remark With the text stream option, "\r\n" is treated as "\n" * \remark The line separator character is not returned as part of the string */ - String Stream::ReadLine(unsigned int lineSize) + std::string Stream::ReadLine(unsigned int lineSize) { - String line; + std::string line; if (lineSize == 0) // Maximal size undefined { const unsigned int bufferSize = 64; @@ -79,9 +79,9 @@ namespace Nz if (ptr != buffer) { if (m_streamOptions & StreamOption_Text && buffer[pos - 1] == '\r') - line.Append(buffer, pos - 1); + line.append(buffer, pos - 1); else - line.Append(buffer, pos); + line.append(buffer, pos); } if (!SetCursorPos(GetCursorPos() - readSize + pos + 1)) @@ -100,28 +100,28 @@ namespace Nz length--; } - line.Append(buffer, length); + line.append(buffer, length); } } while (readSize == bufferSize); } else { - line.Set(lineSize, '\0'); + line.resize(lineSize, '\0'); std::size_t readSize = Read(&line[0], lineSize); - std::size_t pos = line.Find('\n'); + std::size_t pos = line.find('\n'); if (pos <= readSize) // False only if the character is not available (npos being the biggest integer) { if (m_streamOptions & StreamOption_Text && pos > 0 && line[pos - 1] == '\r') - line.Resize(pos); + line.resize(pos); else - line.Resize(pos + 1); + line.resize(pos + 1); if (!SetCursorPos(GetCursorPos() - readSize + pos + 1)) NazaraWarning("Failed to reset cursos pos"); } else - line.Resize(readSize); + line.resize(readSize); } return line; diff --git a/src/Nazara/Core/StringExt.cpp b/src/Nazara/Core/StringExt.cpp new file mode 100644 index 000000000..52f4e90cc --- /dev/null +++ b/src/Nazara/Core/StringExt.cpp @@ -0,0 +1,226 @@ +// Copyright (C) 2017 Jérôme Leclercq +// This file is part of the "Nazara Engine - Core module" +// For conditions of distribution and use, see copyright notice in Config.hpp + +#include +#include +#include +#include + +namespace Nz +{ + namespace + { + bool IsSpace(char32_t character) + { + return character == '\t' || Unicode::GetCategory(character) & Unicode::Category_Separator; + } + + char ToLower(char character) + { + if (character >= 'A' && character <= 'Z') + return character + ('a' - 'A'); + else + return character; + } + + char ToUpper(char character) + { + if (character >= 'a' && character <= 'z') + return character + ('A' - 'a'); + else + return character; + } + + template + struct WideConverter + { + static std::string From(const wchar_t* wstr, std::size_t size) + { + if constexpr (S == 2) + { + // UTF-16 (Windows) + return FromUtf16String(std::u16string_view(reinterpret_cast(wstr), size)); + } + else if constexpr (S == 4) + { + // UTF-32 (Linux) + return FromUtf32String(std::u32string_view(reinterpret_cast(wstr), size)); + } + else + { + static_assert(AlwaysFalse, "Unsupported platform"); + return std::string(""); + } + } + + static std::wstring To(const std::string_view& str) + { + if constexpr (S == 2) + { + std::wstring result; + utf8::utf8to16(str.begin(), str.end(), std::back_inserter(result)); + + return result; + } + else if constexpr (S == 4) + { + std::wstring result; + utf8::utf8to32(str.begin(), str.end(), std::back_inserter(result)); + + return result; + } + else + { + static_assert(AlwaysFalse, "Unsupported platform"); + return std::string(""); + } + } + }; + } + + std::string FromUtf16String(const char16_t* u16str) + { + std::size_t size = std::char_traits::length(u16str); + return FromUtf16String(std::u16string_view(u16str, size)); + } + + std::string FromUtf16String(const std::u16string_view& u16str) + { + std::string result; + utf8::utf16to8(u16str.begin(), u16str.end(), std::back_inserter(result)); + + return result; + } + + std::string FromUtf32String(const char32_t* u32str) + { + std::size_t size = std::char_traits::length(u32str); + return FromUtf32String(std::u32string_view(u32str, size)); + } + + std::string FromUtf32String(const std::u32string_view& u32str) + { + std::string result; + utf8::utf32to8(u32str.begin(), u32str.end(), std::back_inserter(result)); + + return result; + } + + std::string FromWideString(const wchar_t* wstr) + { + std::size_t size = std::char_traits::length(wstr); + return WideConverter::From(wstr, size); + } + + std::string FromWideString(const std::wstring_view& wstr) + { + return WideConverter::From(wstr.data(), wstr.size()); + } + + bool StartsWith(const std::string_view& str, const std::string_view& s, CaseIndependent) + { + if (s.size() > str.size()) + return false; + + return std::equal(str.begin(), str.begin() + s.size(), s.begin(), s.end(), [](char c1, char c2) + { + return ToLower(c1) == ToLower(c2); + }); + } + + bool StartsWith(const std::string_view& str, const std::string_view& s, CaseIndependent, UnicodeAware) + { + if (str.empty() || s.empty()) + return str == s; + + utf8::iterator it(str.data(), str.data(), str.data() + str.size()); + utf8::iterator it2(s.data(), s.data(), s.data() + s.size()); + do + { + if (it2.base() >= s.data() + s.size()) + return true; + + if (Unicode::GetLowercase(*it) != Unicode::GetLowercase(*it2)) + return false; + + ++it2; + } + while (*it++); + + return true; + } + + std::string ToLower(const std::string_view& str) + { + std::string result; + result.reserve(str.size()); + std::transform(str.begin(), str.end(), std::back_inserter(result), Overload(ToLower)); + + return result; + } + + std::string ToLower(const std::string_view& str, UnicodeAware) + { + if (str.empty()) + return std::string(); + + std::string result; + result.reserve(str.size()); + + utf8::unchecked::iterator it(str.data()); + do + utf8::append(Unicode::GetLowercase(*it), std::back_inserter(result)); + while (*++it); + + return result; + } + + std::string ToUpper(const std::string_view& str) + { + std::string result; + result.reserve(str.size()); + std::transform(str.begin(), str.end(), std::back_inserter(result), Overload(ToUpper)); + + return result; + } + + std::string ToUpper(const std::string_view& str, UnicodeAware) + { + if (str.empty()) + return std::string(); + + std::string result; + result.reserve(str.size()); + + utf8::iterator it(str.data(), str.data(), str.data() + str.size()); + do + utf8::append(Unicode::GetUppercase(*it), std::back_inserter(result)); + while (*++it); + + return result; + } + + std::u16string ToUtf16String(const std::string_view& str) + { + std::u16string result; + utf8::utf8to16(str.begin(), str.end(), std::back_inserter(result)); + + return result; + } + + std::u32string ToUtf32String(const std::string_view& str) + { + std::u32string result; + utf8::utf8to32(str.begin(), str.end(), std::back_inserter(result)); + + return result; + } + + std::wstring ToWideString(const std::string_view& str) + { + return WideConverter::To(str); + } +} + +#include diff --git a/src/Nazara/Core/Thread.cpp b/src/Nazara/Core/Thread.cpp deleted file mode 100644 index 5380188d1..000000000 --- a/src/Nazara/Core/Thread.cpp +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include - -#if defined(NAZARA_PLATFORM_WINDOWS) - #include -#elif defined(NAZARA_PLATFORM_POSIX) - #include -#else - #error Thread has no implementation -#endif - -#include - -namespace Nz -{ - /*! - * \ingroup core - * \class Nz::Thread - * \brief Core class that represents a thread - */ - - /*! - * \brief Constructs a Thread object by default - */ - - Thread::Thread() : - m_impl(nullptr) - { - } - - /*! - * \brief Waits that the thread ends and then destroys this - */ - - Thread::~Thread() - { - if (m_impl) - { - m_impl->Join(); - delete m_impl; - m_impl = nullptr; - } - } - - /*! - * \brief Detaches the thread - */ - - void Thread::Detach() - { - if (m_impl) - { - m_impl->Detach(); - delete m_impl; - m_impl = nullptr; - } - } - - /*! - * \brief Gets the id of the thread - * \return The identifiant of the thread (PID) - */ - - Thread::Id Thread::GetId() const - { - return Thread::Id(m_impl); - } - - /*! - * \brief Checks whether the thread can be joined - * \return true if well formed and not detached - */ - - bool Thread::IsJoinable() const - { - return m_impl != nullptr; - } - - /*! - * \brief Waits that the thread ends - * - * \remark Produce a NazaraError if no functor was assigned and NAZARA_CORE_SAFE is defined - */ - - void Thread::Join() - { - #if NAZARA_CORE_SAFE - if (!m_impl) - { - NazaraError("This thread is not joinable"); - return; - } - #endif - - m_impl->Join(); - delete m_impl; - m_impl = nullptr; - } - - /*! - * \brief Changes the debugging name associated to a thread - * - * Changes the debugging name associated with a particular thread, and may helps with debugging tools. - * - * \param name The new name of the thread - * - * \remark Due to system limitations, thread name cannot exceed 15 characters (excluding null-terminator) - * - * \see SetCurrentThreadName - */ - void Thread::SetName(const String& name) - { - NazaraAssert(m_impl, "Invalid thread"); - NazaraAssert(name.GetSize() < 16, "Thread name is too long"); - - m_impl->SetName(name); - } - - /*! - * \brief Gets the number of simulatenous threads that can run on the same cpu - * \return The number of simulatenous threads - */ - unsigned int Thread::HardwareConcurrency() - { - return HardwareInfo::GetProcessorCount(); - } - - - /*! - * \brief Changes the debugging name associated to the calling thread - * - * Changes the debugging name associated with the calling thread, and may helps with debugging tools. - * - * \param name The new name associated with this thread - * - * \remark Due to system limitations, thread name cannot exceed 15 characters (excluding null-terminator) - * - * \see SetName - */ - void Thread::SetCurrentThreadName(const String& name) - { - NazaraAssert(name.GetSize() < 16, "Thread name is too long"); - - ThreadImpl::SetCurrentName(name); - } - - /*! - * \brief Makes sleep this thread - * - * \param milliseconds The number of milliseconds to sleep - */ - void Thread::Sleep(UInt32 milliseconds) - { - ThreadImpl::Sleep(milliseconds); - } - - /*! - * \brief Creates the implementation of this thread - * - * \param functor The task the thread will represent - */ - - void Thread::CreateImpl(Functor* functor) - { - m_impl = new ThreadImpl(functor); - } - - /*********************************Thread::Id********************************/ - - /*! - * \brief Constructs a Thread object with a thread implementation - * - * \param thread Thread implementation assigned to the thread - */ - - Thread::Id::Id(ThreadImpl* thread) : - m_id(thread) - { - } - - /*! - * \brief Compares two Thread::Id - * \return true if the two thread ids are the same - * - * \param lhs First id - * \param rhs Second id - */ - - bool operator==(const Thread::Id& lhs, const Thread::Id& rhs) - { - return lhs.m_id == rhs.m_id; - } - - /*! - * \brief Compares two Thread::Id - * \return false if the two thread ids are the same - * - * \param lhs First id - * \param rhs Second id - */ - - bool operator!=(const Thread::Id& lhs, const Thread::Id& rhs) - { - return lhs.m_id != rhs.m_id; - } - - /*! - * \brief Compares two Thread::Id - * \return true if the first thread id is inferior to the second one - * - * \param lhs First id - * \param rhs Second id - */ - - bool operator<(const Thread::Id& lhs, const Thread::Id& rhs) - { - return lhs.m_id < rhs.m_id; - } - - /*! - * \brief Compares two Thread::Id - * \return true if the first thread id is inferior or equal to the second one - * - * \param lhs First id - * \param rhs Second id - */ - - bool operator<=(const Thread::Id& lhs, const Thread::Id& rhs) - { - return lhs.m_id <= rhs.m_id; - } - - /*! - * \brief Compares two Thread::Id - * \return true if the first thread id is superior to the second one - * - * \param lhs First id - * \param rhs Second id - */ - - bool operator>(const Thread::Id& lhs, const Thread::Id& rhs) - { - return lhs.m_id > rhs.m_id; - } - - /*! - * \brief Compares two Thread::Id - * \return true if the first thread id is superior or equal to the second one - * - * \param lhs First id - * \param rhs Second id - */ - - bool operator>=(const Thread::Id& lhs, const Thread::Id& rhs) - { - return lhs.m_id >= rhs.m_id; - } - - /*! - * \brief Output operator - * \return The stream - * - * \param out The stream - * \param id The thread id to output - */ - - std::ostream& operator<<(std::ostream& o, const Nz::Thread::Id& id) - { - o << id.m_id; - return o; - } -} diff --git a/src/Nazara/Core/Win32/ConditionVariableImpl.cpp b/src/Nazara/Core/Win32/ConditionVariableImpl.cpp deleted file mode 100644 index 7cd5416a8..000000000 --- a/src/Nazara/Core/Win32/ConditionVariableImpl.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// Source: http://www.cs.wustl.edu/~schmidt/win32-cv-1.html - -#include -#include -#include - -namespace Nz -{ - ConditionVariableImpl::ConditionVariableImpl() - { - #if NAZARA_CORE_WINDOWS_NT6 - InitializeConditionVariable(&m_cv); - #else - m_count = 0; - m_events[BROADCAST] = CreateEvent(nullptr, true, false, nullptr); // manual-reset event - m_events[SIGNAL] = CreateEvent(nullptr, false, false, nullptr); // auto-reset event - #endif - } - - #if !NAZARA_CORE_WINDOWS_NT6 - ConditionVariableImpl::~ConditionVariableImpl() - { - CloseHandle(m_events[BROADCAST]); - CloseHandle(m_events[SIGNAL]); - } - #endif - - void ConditionVariableImpl::Signal() - { - #if NAZARA_CORE_WINDOWS_NT6 - WakeConditionVariable(&m_cv); - #else - if (m_count > 0) - SetEvent(m_events[SIGNAL]); - #endif - } - - void ConditionVariableImpl::SignalAll() - { - #if NAZARA_CORE_WINDOWS_NT6 - WakeAllConditionVariable(&m_cv); - #else - if (m_count > 0) - SetEvent(m_events[BROADCAST]); - #endif - } - - void ConditionVariableImpl::Wait(MutexImpl* mutex) - { - Wait(mutex, INFINITE); - } - - bool ConditionVariableImpl::Wait(MutexImpl* mutex, UInt32 timeout) - { - #if NAZARA_CORE_WINDOWS_NT6 - return SleepConditionVariableCS(&m_cv, &mutex->m_criticalSection, timeout) == TRUE; - #else - m_count++; - - // It's ok to release the mutex here since Win32 - // manual-reset events maintain state when used with SetEvent. - // This avoids the "lost wakeup" bug... - LeaveCriticalSection(&mutex->m_criticalSection); - - // Wait for either event to become signaled due to Signal being called or SignalAll being called. - int result = WaitForMultipleObjects(2, m_events, false, timeout); - - // Some thread called SignalAll - if (--m_count == 0 && result == WAIT_OBJECT_0 + BROADCAST) - // We're the last waiter to be notified or to stop waiting, so reset the manual event. - ResetEvent(m_events[BROADCAST]); - - // Reacquire the mutex. - EnterCriticalSection(&mutex->m_criticalSection); - - return result != WAIT_TIMEOUT; - #endif - } - -} diff --git a/src/Nazara/Core/Win32/ConditionVariableImpl.hpp b/src/Nazara/Core/Win32/ConditionVariableImpl.hpp deleted file mode 100644 index 852241ae3..000000000 --- a/src/Nazara/Core/Win32/ConditionVariableImpl.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html - -#pragma once - -#ifndef NAZARA_CONDITIONVARIABLEIMPL_HPP -#define NAZARA_CONDITIONVARIABLEIMPL_HPP - -#include -#include -#include - -namespace Nz -{ - class MutexImpl; - - class ConditionVariableImpl - { - public: - ConditionVariableImpl(); - #if NAZARA_CORE_WINDOWS_NT6 - ~ConditionVariableImpl() = default; - #else - ~ConditionVariableImpl(); - #endif - - void Signal(); - void SignalAll(); - - void Wait(MutexImpl* mutex); - bool Wait(MutexImpl* mutex, UInt32 timeout); - - private: - #if NAZARA_CORE_WINDOWS_NT6 - CONDITION_VARIABLE m_cv; - #else - enum - { - SIGNAL, - BROADCAST, - MAX_EVENTS - }; - - std::atomic_uint m_count; - HANDLE m_events[MAX_EVENTS]; - #endif - }; -} - -#endif // NAZARA_CONDITIONVARIABLEIMPL_HPP diff --git a/src/Nazara/Core/Win32/DirectoryImpl.cpp b/src/Nazara/Core/Win32/DirectoryImpl.cpp deleted file mode 100644 index 824d81746..000000000 --- a/src/Nazara/Core/Win32/DirectoryImpl.cpp +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include - -namespace Nz -{ - DirectoryImpl::DirectoryImpl(const Directory* parent) - { - NazaraUnused(parent); - } - - void DirectoryImpl::Close() - { - FindClose(m_handle); - } - - String DirectoryImpl::GetResultName() const - { - return String::Unicode(m_result.cFileName); - } - - UInt64 DirectoryImpl::GetResultSize() const - { - LARGE_INTEGER size; - size.HighPart = m_result.nFileSizeHigh; - size.LowPart = m_result.nFileSizeLow; - - return size.QuadPart; - } - - bool DirectoryImpl::IsResultDirectory() const - { - if (m_result.dwFileAttributes != INVALID_FILE_ATTRIBUTES) - return (m_result.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; - else - return false; - } - - bool DirectoryImpl::NextResult() - { - if (m_firstCall) // Nous devons ignorer le premier appel car FindFirstFile nous a déjà renvoyé des résultats - { - m_firstCall = false; - return true; - } - - if (FindNextFileW(m_handle, &m_result)) - return true; - else - { - if (GetLastError() != ERROR_NO_MORE_FILES) - NazaraError("Unable to get next result: " + Error::GetLastSystemError()); - - return false; - } - } - - bool DirectoryImpl::Open(const String& dirPath) - { - String searchPath = dirPath + "\\*"; - - m_handle = FindFirstFileW(searchPath.GetWideString().data(), &m_result); - if (m_handle == INVALID_HANDLE_VALUE) - { - NazaraError("Unable to open directory: " + Error::GetLastSystemError()); - return false; - } - - m_firstCall = true; - - return true; - } - - bool DirectoryImpl::Create(const String& dirPath) - { - return (CreateDirectoryW(dirPath.GetWideString().data(), nullptr) != 0) || GetLastError() == ERROR_ALREADY_EXISTS; - } - - bool DirectoryImpl::Exists(const String& dirPath) - { - DWORD attributes = GetFileAttributesW(dirPath.GetWideString().data()); - if (attributes != INVALID_FILE_ATTRIBUTES) - return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; - else - return false; - } - - String DirectoryImpl::GetCurrent() - { - String currentPath; - std::unique_ptr path(new wchar_t[MAX_PATH]); - - unsigned int size = GetCurrentDirectoryW(MAX_PATH, path.get()); - if (size > MAX_PATH) // La taille prends en compte le caractère nul - { - path.reset(new wchar_t[size]); - if (GetCurrentDirectoryW(size, path.get()) != 0) - currentPath = String::Unicode(path.get()); - else - NazaraError("Unable to get current directory: " + Error::GetLastSystemError()); - } - else if (size == 0) - NazaraError("Unable to get current directory: " + Error::GetLastSystemError()); - else - currentPath = String::Unicode(path.get()); - - return currentPath; - } - - bool DirectoryImpl::Remove(const String& dirPath) - { - bool success = RemoveDirectoryW(dirPath.GetWideString().data()) != 0; - - DWORD error = GetLastError(); - return success || error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND; - } -} diff --git a/src/Nazara/Core/Win32/DirectoryImpl.hpp b/src/Nazara/Core/Win32/DirectoryImpl.hpp deleted file mode 100644 index 358910be4..000000000 --- a/src/Nazara/Core/Win32/DirectoryImpl.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_DIRECTORYIMPL_HPP -#define NAZARA_DIRECTORYIMPL_HPP - -#include -#include - -namespace Nz -{ - class Directory; - class String; - - class DirectoryImpl - { - public: - DirectoryImpl(const Directory* parent); - DirectoryImpl(const DirectoryImpl&) = delete; - DirectoryImpl(DirectoryImpl&&) = delete; ///TODO - ~DirectoryImpl() = default; - - void Close(); - - String GetResultName() const; - UInt64 GetResultSize() const; - - bool IsResultDirectory() const; - - bool NextResult(); - - bool Open(const String& dirPath); - - DirectoryImpl& operator=(const DirectoryImpl&) = delete; - DirectoryImpl& operator=(DirectoryImpl&&) = delete; ///TODO - - static bool Create(const String& dirPath); - static bool Exists(const String& dirPath); - static String GetCurrent(); - static bool Remove(const String& dirPath); - - private: - HANDLE m_handle; - WIN32_FIND_DATAW m_result; - bool m_firstCall; - }; -} - -#endif // NAZARA_DIRECTORYIMPL_HPP diff --git a/src/Nazara/Core/Win32/DynLibImpl.cpp b/src/Nazara/Core/Win32/DynLibImpl.cpp index aa42fda18..d2cbecb7d 100644 --- a/src/Nazara/Core/Win32/DynLibImpl.cpp +++ b/src/Nazara/Core/Win32/DynLibImpl.cpp @@ -5,34 +5,39 @@ #include #include #include -#include -#include +#include #include #include namespace Nz { - DynLibImpl::DynLibImpl(DynLib* parent) + DynLibImpl::DynLibImpl(DynLib*) : + m_handle(nullptr) { - NazaraUnused(parent); } - DynLibFunc DynLibImpl::GetSymbol(const String& symbol, String* errorMessage) const + DynLibImpl::~DynLibImpl() { - DynLibFunc sym = reinterpret_cast(GetProcAddress(m_handle, symbol.GetConstBuffer())); + if (m_handle) + FreeLibrary(m_handle); + } + + DynLibFunc DynLibImpl::GetSymbol(const char* symbol, std::string* errorMessage) const + { + DynLibFunc sym = reinterpret_cast(GetProcAddress(m_handle, symbol)); if (!sym) *errorMessage = Error::GetLastSystemError(); return sym; } - bool DynLibImpl::Load(const String& libraryPath, String* errorMessage) + bool DynLibImpl::Load(const std::filesystem::path& libraryPath, std::string* errorMessage) { - String path = libraryPath; - if (!path.EndsWith(".dll")) + std::filesystem::path path = libraryPath; + if (path.extension() != ".dll") path += ".dll"; - m_handle = LoadLibraryExW(path.GetWideString().data(), nullptr, (File::IsAbsolute(path)) ? LOAD_WITH_ALTERED_SEARCH_PATH : 0); + m_handle = LoadLibraryExW(ToWideString(path.generic_u8string()).data(), nullptr, (path.is_absolute()) ? LOAD_WITH_ALTERED_SEARCH_PATH : 0); if (m_handle) return true; else @@ -41,10 +46,4 @@ namespace Nz return false; } } - - void DynLibImpl::Unload() - { - FreeLibrary(m_handle); - } - } diff --git a/src/Nazara/Core/Win32/DynLibImpl.hpp b/src/Nazara/Core/Win32/DynLibImpl.hpp index c9d88d57d..31a279103 100644 --- a/src/Nazara/Core/Win32/DynLibImpl.hpp +++ b/src/Nazara/Core/Win32/DynLibImpl.hpp @@ -9,23 +9,21 @@ #include #include +#include #include namespace Nz { - class String; - class DynLibImpl { public: DynLibImpl(DynLib* m_parent); DynLibImpl(const DynLibImpl&) = delete; DynLibImpl(DynLibImpl&&) = delete; ///TODO? - ~DynLibImpl() = default; + ~DynLibImpl(); - DynLibFunc GetSymbol(const String& symbol, String* errorMessage) const; - bool Load(const String& libraryPath, String* errorMessage); - void Unload(); + DynLibFunc GetSymbol(const char* symbol, std::string* errorMessage) const; + bool Load(const std::filesystem::path& libraryPath, std::string* errorMessage); DynLibImpl& operator=(const DynLibImpl&) = delete; DynLibImpl& operator=(DynLibImpl&&) = delete; ///TODO? diff --git a/src/Nazara/Core/Win32/FileImpl.cpp b/src/Nazara/Core/Win32/FileImpl.cpp index 4e5d75c6c..5b1fe952b 100644 --- a/src/Nazara/Core/Win32/FileImpl.cpp +++ b/src/Nazara/Core/Win32/FileImpl.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -18,9 +19,10 @@ namespace Nz NazaraUnused(parent); } - void FileImpl::Close() + FileImpl::~FileImpl() { - CloseHandle(m_handle); + if (m_handle) + CloseHandle(m_handle); } bool FileImpl::EndOfFile() const @@ -55,7 +57,7 @@ namespace Nz return position.QuadPart; } - bool FileImpl::Open(const String& filePath, OpenModeFlags mode) + bool FileImpl::Open(const std::filesystem::path& filePath, OpenModeFlags mode) { DWORD access = 0; DWORD shareMode = FILE_SHARE_READ; @@ -87,7 +89,7 @@ namespace Nz if ((mode & OpenMode_Lock) == 0) shareMode |= FILE_SHARE_WRITE; - m_handle = CreateFileW(filePath.GetWideString().data(), access, shareMode, nullptr, openMode, 0, nullptr); + m_handle = CreateFileW(ToWideString(filePath.generic_u8string()).data(), access, shareMode, nullptr, openMode, 0, nullptr); return m_handle != INVALID_HANDLE_VALUE; } @@ -197,118 +199,4 @@ namespace Nz return written; } - - bool FileImpl::Copy(const String& sourcePath, const String& targetPath) - { - if (CopyFileW(sourcePath.GetWideString().data(), targetPath.GetWideString().data(), false)) - return true; - else - { - NazaraError("Failed to copy file: " + Error::GetLastSystemError()); - return false; - } - } - - bool FileImpl::Delete(const String& filePath) - { - if (DeleteFileW(filePath.GetWideString().data())) - return true; - else - { - NazaraError("Failed to delete file (" + filePath + "): " + Error::GetLastSystemError()); - return false; - } - } - - bool FileImpl::Exists(const String& filePath) - { - HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); - if (handle == INVALID_HANDLE_VALUE) - return false; - - CloseHandle(handle); - return true; - } - - time_t FileImpl::GetCreationTime(const String& filePath) - { - HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); - if (handle == INVALID_HANDLE_VALUE) - return 0; - - FILETIME creationTime; - if (!GetFileTime(handle, &creationTime, nullptr, nullptr)) - { - CloseHandle(handle); - - NazaraError("Unable to get creation time: " + Error::GetLastSystemError()); - return 0; - } - - CloseHandle(handle); - return FileTimeToTime(&creationTime); - } - - time_t FileImpl::GetLastAccessTime(const String& filePath) - { - HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); - if (handle == INVALID_HANDLE_VALUE) - return 0; - - FILETIME accessTime; - if (!GetFileTime(handle, nullptr, &accessTime, nullptr)) - { - CloseHandle(handle); - - NazaraError("Unable to get last access time: " + Error::GetLastSystemError()); - return 0; - } - - CloseHandle(handle); - return FileTimeToTime(&accessTime); - } - - time_t FileImpl::GetLastWriteTime(const String& filePath) - { - HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); - if (handle == INVALID_HANDLE_VALUE) - return 0; - - FILETIME writeTime; - if (!GetFileTime(handle, nullptr, nullptr, &writeTime)) - { - CloseHandle(handle); - - NazaraError("Unable to get last write time: " + Error::GetLastSystemError()); - return 0; - } - - CloseHandle(handle); - return FileTimeToTime(&writeTime); - } - - UInt64 FileImpl::GetSize(const String& filePath) - { - HANDLE handle = CreateFileW(filePath.GetWideString().data(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); - if (handle == INVALID_HANDLE_VALUE) - return 0; - - LARGE_INTEGER fileSize; - if (!GetFileSizeEx(handle, &fileSize)) - fileSize.QuadPart = 0; - - CloseHandle(handle); - return fileSize.QuadPart; - } - - bool FileImpl::Rename(const String& sourcePath, const String& targetPath) - { - if (MoveFileExW(sourcePath.GetWideString().data(), targetPath.GetWideString().data(), MOVEFILE_COPY_ALLOWED)) - return true; - else - { - NazaraError("Unable to rename file: " + Error::GetLastSystemError()); - return false; - } - } } diff --git a/src/Nazara/Core/Win32/FileImpl.hpp b/src/Nazara/Core/Win32/FileImpl.hpp index 6595c58b2..3380a71e4 100644 --- a/src/Nazara/Core/Win32/FileImpl.hpp +++ b/src/Nazara/Core/Win32/FileImpl.hpp @@ -23,13 +23,12 @@ namespace Nz FileImpl(const File* parent); FileImpl(const FileImpl&) = delete; FileImpl(FileImpl&&) = delete; ///TODO - ~FileImpl() = default; + ~FileImpl(); - void Close(); bool EndOfFile() const; void Flush(); UInt64 GetCursorPos() const; - bool Open(const String& filePath, OpenModeFlags mode); + bool Open(const std::filesystem::path& filePath, OpenModeFlags mode); std::size_t Read(void* buffer, std::size_t size); bool SetCursorPos(CursorPosition pos, Int64 offset); bool SetSize(UInt64 size); @@ -38,15 +37,6 @@ namespace Nz FileImpl& operator=(const FileImpl&) = delete; FileImpl& operator=(FileImpl&&) = delete; ///TODO - static bool Copy(const String& sourcePath, const String& targetPath); - static bool Delete(const String& filePath); - static bool Exists(const String& filePath); - static time_t GetCreationTime(const String& filePath); - static time_t GetLastAccessTime(const String& filePath); - static time_t GetLastWriteTime(const String& filePath); - static UInt64 GetSize(const String& filePath); - static bool Rename(const String& sourcePath, const String& targetPath); - private: HANDLE m_handle; mutable bool m_endOfFile; diff --git a/src/Nazara/Core/Win32/MutexImpl.cpp b/src/Nazara/Core/Win32/MutexImpl.cpp deleted file mode 100644 index 7c4e18f34..000000000 --- a/src/Nazara/Core/Win32/MutexImpl.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - MutexImpl::MutexImpl() - { - #if NAZARA_CORE_WINDOWS_CS_SPINLOCKS > 0 - InitializeCriticalSectionAndSpinCount(&m_criticalSection, NAZARA_CORE_WINDOWS_CS_SPINLOCKS); - #else - InitializeCriticalSection(&m_criticalSection); - #endif - } - - MutexImpl::~MutexImpl() - { - DeleteCriticalSection(&m_criticalSection); - } - - void MutexImpl::Lock() - { - EnterCriticalSection(&m_criticalSection); - } - - bool MutexImpl::TryLock() - { - return TryEnterCriticalSection(&m_criticalSection) != 0; - } - - void MutexImpl::Unlock() - { - LeaveCriticalSection(&m_criticalSection); - } -} diff --git a/src/Nazara/Core/Win32/MutexImpl.hpp b/src/Nazara/Core/Win32/MutexImpl.hpp deleted file mode 100644 index e411d4fa2..000000000 --- a/src/Nazara/Core/Win32/MutexImpl.hpp +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_MUTEXIMPL_HPP -#define NAZARA_MUTEXIMPL_HPP - -#include -#include - -namespace Nz -{ - class MutexImpl - { - friend class ConditionVariableImpl; - - public: - MutexImpl(); - ~MutexImpl(); - - void Lock(); - bool TryLock(); - void Unlock(); - - private: - CRITICAL_SECTION m_criticalSection; - }; -} - -#endif // NAZARA_MUTEXIMPL_HPP diff --git a/src/Nazara/Core/Win32/SemaphoreImpl.cpp b/src/Nazara/Core/Win32/SemaphoreImpl.cpp deleted file mode 100644 index 19bc17c74..000000000 --- a/src/Nazara/Core/Win32/SemaphoreImpl.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include - -namespace Nz -{ - SemaphoreImpl::SemaphoreImpl(unsigned int count) - { - m_semaphore = CreateSemaphoreW(nullptr, count, std::numeric_limits::max(), nullptr); - if (!m_semaphore) - NazaraError("Failed to create semaphore: " + Error::GetLastSystemError()); - } - - SemaphoreImpl::~SemaphoreImpl() - { - CloseHandle(m_semaphore); - } - - unsigned int SemaphoreImpl::GetCount() const - { - LONG count; - ReleaseSemaphore(m_semaphore, 0, &count); - return count; - } - - void SemaphoreImpl::Post() - { - #if NAZARA_CORE_SAFE - if (!ReleaseSemaphore(m_semaphore, 1, nullptr)) - NazaraError("Failed to release semaphore: " + Error::GetLastSystemError()); - #else - ReleaseSemaphore(m_semaphore, 1, nullptr); - #endif - } - - void SemaphoreImpl::Wait() - { - #if NAZARA_CORE_SAFE - if (WaitForSingleObject(m_semaphore, INFINITE) == WAIT_FAILED) - NazaraError("Failed to wait for semaphore: " + Error::GetLastSystemError()); - #else - WaitForSingleObject(m_semaphore, INFINITE); - #endif - } - - bool SemaphoreImpl::Wait(UInt32 timeout) - { - #if NAZARA_CORE_SAFE - DWORD result = WaitForSingleObject(m_semaphore, timeout); - if (result == WAIT_FAILED) - { - NazaraError("Failed to wait for semaphore: " + Error::GetLastSystemError()); - return false; - } - else - return result == WAIT_OBJECT_0; - #else - return WaitForSingleObject(m_semaphore, timeout) == WAIT_OBJECT_0; - #endif - } -} diff --git a/src/Nazara/Core/Win32/SemaphoreImpl.hpp b/src/Nazara/Core/Win32/SemaphoreImpl.hpp deleted file mode 100644 index 3dad0d9a3..000000000 --- a/src/Nazara/Core/Win32/SemaphoreImpl.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_SEMAPHOREIMPL_HPP -#define NAZARA_SEMAPHOREIMPL_HPP - -#include -#include - -namespace Nz -{ - class SemaphoreImpl - { - public: - SemaphoreImpl(unsigned int count); - ~SemaphoreImpl(); - - unsigned int GetCount() const; - void Post(); - void Wait(); - bool Wait(UInt32 timeout); - - private: - HANDLE m_semaphore; - }; -} - -#endif // NAZARA_SEMAPHOREIMPL_HPP diff --git a/src/Nazara/Core/Win32/ThreadImpl.cpp b/src/Nazara/Core/Win32/ThreadImpl.cpp deleted file mode 100644 index 0ad2293cc..000000000 --- a/src/Nazara/Core/Win32/ThreadImpl.cpp +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - // Windows 10, version 1607 brought SetThreadDescription in order to name a thread - using SetThreadDescriptionFunc = HRESULT(WINAPI*)(HANDLE hThread, PCWSTR lpThreadDescription); - -#ifdef NAZARA_COMPILER_MSVC - namespace - { -#pragma pack(push,8) - struct THREADNAME_INFO - { - DWORD dwType; - LPCSTR szName; - DWORD dwThreadID; - DWORD dwFlags; - }; -#pragma pack(pop) - } -#endif - - ThreadImpl::ThreadImpl(Functor* functor) - { - unsigned int threadId; - m_handle = reinterpret_cast(_beginthreadex(nullptr, 0, &ThreadImpl::ThreadProc, functor, 0, &threadId)); - if (!m_handle) - NazaraInternalError("Failed to create thread: " + Error::GetLastSystemError()); - - m_threadId = threadId; - } - - void ThreadImpl::Detach() - { - // http://stackoverflow.com/questions/418742/is-it-reasonable-to-call-closehandle-on-a-thread-before-it-terminates - CloseHandle(m_handle); - } - - void ThreadImpl::Join() - { - WaitForSingleObject(m_handle, INFINITE); - CloseHandle(m_handle); - } - - void ThreadImpl::SetName(const Nz::String& name) - { - SetThreadName(m_handle, name); - } - - void ThreadImpl::SetCurrentName(const Nz::String& name) - { - SetThreadName(::GetCurrentThread(), name); - } - - void ThreadImpl::Sleep(UInt32 time) - { - ::Sleep(time); - } - - void ThreadImpl::RaiseThreadNameException(DWORD threadId, const char* threadName) - { -#ifdef NAZARA_COMPILER_MSVC - if (!::IsDebuggerPresent()) - return; - - // https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx - constexpr DWORD MS_VC_EXCEPTION = 0x406D1388; - - THREADNAME_INFO info; - info.dwType = 0x1000; - info.szName = threadName; - info.dwThreadID = threadId; - info.dwFlags = 0; - -#pragma warning(push) -#pragma warning(disable: 6320 6322) - __try - { - RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), reinterpret_cast(&info)); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - } -#pragma warning(pop) -#else - NazaraWarning("SetThreadDescription is not supported and threadname exception is only supported with MSVC"); -#endif - } - - void ThreadImpl::SetThreadName(HANDLE threadHandle, const Nz::String& name) - { - // Try to use SetThreadDescription if available - static SetThreadDescriptionFunc SetThreadDescription = reinterpret_cast(::GetProcAddress(::GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription")); - if (SetThreadDescription) - SetThreadDescription(threadHandle, name.GetWideString().data()); - else - RaiseThreadNameException(::GetThreadId(threadHandle), name.GetConstBuffer()); - } - - unsigned int __stdcall ThreadImpl::ThreadProc(void* userdata) - { - Functor* func = static_cast(userdata); - func->Run(); - delete func; - - /* - En C++, il vaut mieux retourner depuis la fonction que de quitter le thread explicitement - Source : http://msdn.microsoft.com/en-us/library/windows/desktop/ms682659(v=vs.85).aspx - */ - - return 0; - } -} diff --git a/src/Nazara/Core/Win32/ThreadImpl.hpp b/src/Nazara/Core/Win32/ThreadImpl.hpp deleted file mode 100644 index c12697611..000000000 --- a/src/Nazara/Core/Win32/ThreadImpl.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Engine - Core module" -// For conditions of distribution and use, see copyright notice in Config.hpp - -// Inspiré du code de la SFML par Laurent Gomila - -#pragma once - -#ifndef NAZARA_THREADIMPL_HPP -#define NAZARA_THREADIMPL_HPP - -#include -#include -#include - -namespace Nz -{ - struct Functor; - - class ThreadImpl - { - public: - ThreadImpl(Functor* threadFunc); - - void Detach(); - void Join(); - void SetName(const Nz::String& name); - - static void SetCurrentName(const Nz::String& name); - static void Sleep(UInt32 time); - - private: - static void RaiseThreadNameException(DWORD threadId, const char* threadName); - static void SetThreadName(HANDLE threadHandle, const Nz::String& name); - static unsigned int __stdcall ThreadProc(void* userdata); - - DWORD m_threadId; - HANDLE m_handle; - }; -} - -#endif // NAZARA_THREADIMPL_HPP diff --git a/src/Nazara/Graphics/Formats/MeshLoader.cpp b/src/Nazara/Graphics/Formats/MeshLoader.cpp index d21ed58c1..5b8df3932 100644 --- a/src/Nazara/Graphics/Formats/MeshLoader.cpp +++ b/src/Nazara/Graphics/Formats/MeshLoader.cpp @@ -22,13 +22,14 @@ namespace Nz { const ParameterList& matData = model->GetMesh()->GetMaterialData(i); - String filePath; - if (matData.GetStringParameter(MaterialData::FilePath, &filePath)) + String path; + if (matData.GetStringParameter(MaterialData::FilePath, &path)) { - if (!File::Exists(filePath)) + std::filesystem::path filePath = path.ToStdString(); + if (!std::filesystem::exists(filePath)) { NazaraWarning("Shader name does not refer to an existing file, \".tga\" is used by default"); - filePath += ".tga"; + filePath.replace_extension(".tga"); } if (MaterialRef material = Material::LoadFromFile(filePath, parameters.material)) diff --git a/src/Nazara/Graphics/Material.cpp b/src/Nazara/Graphics/Material.cpp index 81c50ab85..08b769c1a 100644 --- a/src/Nazara/Graphics/Material.cpp +++ b/src/Nazara/Graphics/Material.cpp @@ -115,7 +115,7 @@ namespace Nz bool isEnabled; double dValue; long long iValue; - String path; + Nz::String path; ErrorFlags errFlags(ErrorFlag_Silent | ErrorFlag_ThrowExceptionDisabled, true); @@ -247,22 +247,22 @@ namespace Nz // Textures if (matParams.loadAlphaMap && matData.GetStringParameter(MaterialData::AlphaTexturePath, &path)) - SetAlphaMap(path); + SetAlphaMap(path.ToStdString()); if (matParams.loadDiffuseMap && matData.GetStringParameter(MaterialData::DiffuseTexturePath, &path)) - SetDiffuseMap(path); + SetDiffuseMap(path.ToStdString()); if (matParams.loadEmissiveMap && matData.GetStringParameter(MaterialData::EmissiveTexturePath, &path)) - SetEmissiveMap(path); + SetEmissiveMap(path.ToStdString()); if (matParams.loadHeightMap && matData.GetStringParameter(MaterialData::HeightTexturePath, &path)) - SetHeightMap(path); + SetHeightMap(path.ToStdString()); if (matParams.loadNormalMap && matData.GetStringParameter(MaterialData::NormalTexturePath, &path)) - SetNormalMap(path); + SetNormalMap(path.ToStdString()); if (matParams.loadSpecularMap && matData.GetStringParameter(MaterialData::SpecularTexturePath, &path)) - SetSpecularMap(path); + SetSpecularMap(path.ToStdString()); SetShader(matParams.shaderName); } @@ -329,44 +329,44 @@ namespace Nz // Textures if (HasAlphaMap()) { - const String& path = GetAlphaMap()->GetFilePath(); - if (!path.IsEmpty()) - matData->SetParameter(MaterialData::AlphaTexturePath, path); + const std::filesystem::path& path = GetAlphaMap()->GetFilePath(); + if (!path.empty()) + matData->SetParameter(MaterialData::AlphaTexturePath, path.generic_u8string()); } if (HasDiffuseMap()) { - const String& path = GetDiffuseMap()->GetFilePath(); - if (!path.IsEmpty()) - matData->SetParameter(MaterialData::DiffuseTexturePath, path); + const std::filesystem::path& path = GetDiffuseMap()->GetFilePath(); + if (!path.empty()) + matData->SetParameter(MaterialData::DiffuseTexturePath, path.generic_u8string()); } if (HasEmissiveMap()) { - const String& path = GetEmissiveMap()->GetFilePath(); - if (!path.IsEmpty()) - matData->SetParameter(MaterialData::EmissiveTexturePath, path); + const std::filesystem::path& path = GetEmissiveMap()->GetFilePath(); + if (!path.empty()) + matData->SetParameter(MaterialData::EmissiveTexturePath, path.generic_u8string()); } if (HasHeightMap()) { - const String& path = GetHeightMap()->GetFilePath(); - if (!path.IsEmpty()) - matData->SetParameter(MaterialData::HeightTexturePath, path); + const std::filesystem::path& path = GetHeightMap()->GetFilePath(); + if (!path.empty()) + matData->SetParameter(MaterialData::HeightTexturePath, path.generic_u8string()); } if (HasNormalMap()) { - const String& path = GetNormalMap()->GetFilePath(); - if (!path.IsEmpty()) - matData->SetParameter(MaterialData::NormalTexturePath, path); + const std::filesystem::path& path = GetNormalMap()->GetFilePath(); + if (!path.empty()) + matData->SetParameter(MaterialData::NormalTexturePath, path.generic_u8string()); } if (HasSpecularMap()) { - const String& path = GetSpecularMap()->GetFilePath(); - if (!path.IsEmpty()) - matData->SetParameter(MaterialData::SpecularTexturePath, path); + const std::filesystem::path& path = GetSpecularMap()->GetFilePath(); + if (!path.empty()) + matData->SetParameter(MaterialData::SpecularTexturePath, path.generic_u8string()); } } diff --git a/src/Nazara/Graphics/MaterialPipeline.cpp b/src/Nazara/Graphics/MaterialPipeline.cpp index 743984783..37e5f8ca0 100644 --- a/src/Nazara/Graphics/MaterialPipeline.cpp +++ b/src/Nazara/Graphics/MaterialPipeline.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include namespace Nz @@ -29,7 +30,7 @@ namespace Nz #include }; - void OverrideShader(const String& path, String* source) + void OverrideShader(const std::filesystem::path& path, String* source) { ErrorFlags errFlags(ErrorFlag_Silent | ErrorFlag_ThrowExceptionDisabled); @@ -46,7 +47,7 @@ namespace Nz *source = shaderSource; - NazaraNotice(path + " will be used to override built-in shader"); + NazaraNotice(path.generic_u8string() + " will be used to override built-in shader"); } } } diff --git a/src/Nazara/Graphics/Model.cpp b/src/Nazara/Graphics/Model.cpp index 5a6b1cfca..31187023b 100644 --- a/src/Nazara/Graphics/Model.cpp +++ b/src/Nazara/Graphics/Model.cpp @@ -86,7 +86,7 @@ namespace Nz * \remark Produces a NazaraError if there is no subMesh with that name * \remark Produces a NazaraError if material is invalid */ - const MaterialRef& Model::GetMaterial(const String& subMeshName) const + const MaterialRef& Model::GetMaterial(const std::string& subMeshName) const { NazaraAssert(m_mesh, "Model has no mesh"); @@ -113,7 +113,7 @@ namespace Nz * \remark Produces a NazaraError if there is no subMesh with that name * \remark Produces a NazaraError if material index is invalid */ - const MaterialRef& Model::GetMaterial(std::size_t skinIndex, const String& subMeshName) const + const MaterialRef& Model::GetMaterial(std::size_t skinIndex, const std::string& subMeshName) const { NazaraAssert(m_mesh, "Model has no mesh"); @@ -160,7 +160,7 @@ namespace Nz * \remark Produces a NazaraError if material index is invalid */ - bool Model::SetMaterial(const String& subMeshName, MaterialRef material) + bool Model::SetMaterial(const std::string& subMeshName, MaterialRef material) { SubMesh* subMesh = m_mesh->GetSubMesh(subMeshName); if (!subMesh) @@ -185,7 +185,7 @@ namespace Nz * \remark Produces a NazaraError if there is no subMesh with that name * \remark Produces a NazaraError if material index is invalid */ - bool Model::SetMaterial(std::size_t skinIndex, const String& subMeshName, MaterialRef material) + bool Model::SetMaterial(std::size_t skinIndex, const std::string& subMeshName, MaterialRef material) { SubMesh* subMesh = m_mesh->GetSubMesh(subMeshName); if (!subMesh) @@ -239,7 +239,7 @@ namespace Nz * \param filePath Path to the file * \param params Parameters for the model */ - ModelRef Model::LoadFromFile(const String& filePath, const ModelParameters& params) + ModelRef Model::LoadFromFile(const std::filesystem::path& filePath, const ModelParameters& params) { return ModelLoader::LoadFromFile(filePath, params); } diff --git a/src/Nazara/Graphics/Sprite.cpp b/src/Nazara/Graphics/Sprite.cpp index 0c16de174..6a01fd5d2 100644 --- a/src/Nazara/Graphics/Sprite.cpp +++ b/src/Nazara/Graphics/Sprite.cpp @@ -56,7 +56,7 @@ namespace Nz * * \return True if the material was found or loaded from its name/path, false if it couldn't */ - bool Sprite::SetMaterial(String materialName, bool resizeSprite) + bool Sprite::SetMaterial(std::string materialName, bool resizeSprite) { MaterialRef material = MaterialLibrary::Query(materialName); if (!material) @@ -85,7 +85,7 @@ namespace Nz * * \return True if the material was found or loaded from its name/path, false if it couldn't */ - bool Sprite::SetMaterial(std::size_t skinIndex, String materialName, bool resizeSprite) + bool Sprite::SetMaterial(std::size_t skinIndex, std::string materialName, bool resizeSprite) { MaterialRef material = MaterialLibrary::Query(materialName); if (!material) @@ -114,7 +114,7 @@ namespace Nz * * \remark The sprite material gets copied to prevent accidentally changing other drawable materials */ - bool Sprite::SetTexture(String textureName, bool resizeSprite) + bool Sprite::SetTexture(std::string textureName, bool resizeSprite) { TextureRef texture = TextureLibrary::Query(textureName); if (!texture) @@ -144,7 +144,7 @@ namespace Nz * * \remark The sprite material gets copied to prevent accidentally changing other drawable materials */ - bool Sprite::SetTexture(std::size_t skinIndex, String textureName, bool resizeSprite) + bool Sprite::SetTexture(std::size_t skinIndex, std::string textureName, bool resizeSprite) { TextureRef texture = TextureLibrary::Query(textureName); if (!texture) diff --git a/src/Nazara/Lua/LuaState.cpp b/src/Nazara/Lua/LuaState.cpp index 6065087d6..c18367c30 100644 --- a/src/Nazara/Lua/LuaState.cpp +++ b/src/Nazara/Lua/LuaState.cpp @@ -371,7 +371,7 @@ namespace Nz return CallWithHandler(errorHandler, 0); } - bool LuaState::ExecuteFromFile(const String& filePath, int errorHandler) + bool LuaState::ExecuteFromFile(const std::filesystem::path& filePath, int errorHandler) { if (!LoadFromFile(filePath)) return false; @@ -539,7 +539,7 @@ namespace Nz return true; } - bool LuaState::LoadFromFile(const String& filePath) + bool LuaState::LoadFromFile(const std::filesystem::path& filePath) { File file(filePath); if (!file.Open(OpenMode_ReadOnly | OpenMode_Text)) diff --git a/src/Nazara/Network/NetPacket.cpp b/src/Nazara/Network/NetPacket.cpp index 4df6e0cae..0887e7d3f 100644 --- a/src/Nazara/Network/NetPacket.cpp +++ b/src/Nazara/Network/NetPacket.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include @@ -113,7 +112,7 @@ namespace Nz std::size_t size = m_buffer->GetSize(); - Nz::LockGuard lock(*s_availableBuffersMutex); + std::lock_guard lock(s_availableBuffersMutex); s_availableBuffers.emplace_back(std::make_pair(size, std::move(m_buffer))); } @@ -132,7 +131,7 @@ namespace Nz NazaraAssert(minCapacity >= cursorPos, "Cannot init stream with a smaller capacity than wanted cursor pos"); { - Nz::LockGuard lock(*s_availableBuffersMutex); + std::lock_guard lock(s_availableBuffersMutex); FreeStream(); //< In case it wasn't released yet @@ -160,7 +159,6 @@ namespace Nz bool NetPacket::Initialize() { - s_availableBuffersMutex = std::make_unique(); return true; } @@ -171,9 +169,8 @@ namespace Nz void NetPacket::Uninitialize() { s_availableBuffers.clear(); - s_availableBuffersMutex.reset(); } - std::unique_ptr NetPacket::s_availableBuffersMutex; + std::mutex NetPacket::s_availableBuffersMutex; std::vector>> NetPacket::s_availableBuffers; } diff --git a/src/Nazara/Platform/Win32/WindowImpl.cpp b/src/Nazara/Platform/Win32/WindowImpl.cpp index 6ee3365ac..edc5dd1d6 100644 --- a/src/Nazara/Platform/Win32/WindowImpl.cpp +++ b/src/Nazara/Platform/Win32/WindowImpl.cpp @@ -5,10 +5,7 @@ // Un grand merci à Laurent Gomila pour la SFML qui m'aura bien aidé à réaliser cette implémentation #include -#include #include -#include -#include #include #include #include @@ -130,15 +127,15 @@ namespace Nz if (async) { - Mutex mutex; - ConditionVariable condition; + std::mutex mutex; + std::condition_variable condition; m_threadActive = true; // On attend que la fenêtre soit créée - mutex.Lock(); - m_thread = Thread(WindowThread, &m_handle, win32StyleEx, title, win32Style, fullscreen, Rectui(x, y, width, height), this, &mutex, &condition); - condition.Wait(&mutex); - mutex.Unlock(); + std::unique_lock lock(mutex); + m_thread = std::thread(WindowThread, std::ref(m_handle), win32StyleEx, title, win32Style, fullscreen, Rectui(x, y, width, height), this, std::ref(mutex), std::ref(condition)); + + condition.wait(lock); } else m_handle = CreateWindowExW(win32StyleEx, className, title.GetWideString().data(), win32Style, x, y, width, height, nullptr, nullptr, GetModuleHandle(nullptr), this); @@ -186,12 +183,12 @@ namespace Nz { if (m_style & WindowStyle_Threaded) { - if (m_thread.IsJoinable()) + if (m_thread.joinable()) { m_threadActive = false; PostMessageW(m_handle, WM_NULL, 0, 0); // Wake up our thread - m_thread.Join(); + m_thread.join(); } } else @@ -1151,24 +1148,24 @@ namespace Nz return style; } - void WindowImpl::WindowThread(HWND* handle, DWORD styleEx, const String& title, DWORD style, bool fullscreen, const Rectui& dimensions, WindowImpl* window, Mutex* mutex, ConditionVariable* condition) + void WindowImpl::WindowThread(HWND& handle, DWORD styleEx, const String& title, DWORD style, bool fullscreen, const Rectui& dimensions, WindowImpl* window, std::mutex& mutex, std::condition_variable& condition) { - HWND& winHandle = *handle; - winHandle = CreateWindowExW(styleEx, className, title.GetWideString().data(), style, dimensions.x, dimensions.y, dimensions.width, dimensions.height, nullptr, nullptr, GetModuleHandle(nullptr), window); + handle = CreateWindowExW(styleEx, className, title.GetWideString().data(), style, dimensions.x, dimensions.y, dimensions.width, dimensions.height, nullptr, nullptr, GetModuleHandle(nullptr), window); - if (winHandle) + if (handle) window->PrepareWindow(fullscreen); - mutex->Lock(); - condition->Signal(); - mutex->Unlock(); // mutex and condition may be destroyed after this line + { + std::lock_guard lock(mutex); + condition.notify_all(); + } - if (!winHandle) + if (!handle) return; while (window->m_threadActive) window->ProcessEvents(true); - DestroyWindow(winHandle); + DestroyWindow(handle); } } diff --git a/src/Nazara/Platform/Win32/WindowImpl.hpp b/src/Nazara/Platform/Win32/WindowImpl.hpp index e05a86fdf..8165ae8c5 100644 --- a/src/Nazara/Platform/Win32/WindowImpl.hpp +++ b/src/Nazara/Platform/Win32/WindowImpl.hpp @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -19,12 +18,13 @@ #include #include #include +#include +#include +#include #include namespace Nz { - class ConditionVariable; - class Mutex; class Window; #undef IsMinimized // Conflits with windows.h redefinition @@ -87,7 +87,7 @@ namespace Nz static Keyboard::Key ConvertVirtualKey(WPARAM key, LPARAM flags); static LRESULT CALLBACK MessageHandler(HWND window, UINT message, WPARAM wParam, LPARAM lParam); static UInt32 RetrieveStyle(HWND window); - static void WindowThread(HWND* handle, DWORD styleEx, const String& title, DWORD style, bool fullscreen, const Rectui& dimensions, WindowImpl* window, Mutex* mutex, ConditionVariable* condition); + static void WindowThread(HWND& handle, DWORD styleEx, const String& title, DWORD style, bool fullscreen, const Rectui& dimensions, WindowImpl* window, std::mutex& mutex, std::condition_variable& condition); HCURSOR m_cursor; HWND m_handle; @@ -98,7 +98,7 @@ namespace Nz Vector2i m_mousePos; Vector2i m_position; Vector2ui m_size; - Thread m_thread; + std::thread m_thread; Window* m_parent; bool m_eventListener; bool m_keyRepeat; diff --git a/src/Nazara/Platform/Window.cpp b/src/Nazara/Platform/Window.cpp index 9ce743ad4..90b6556a2 100644 --- a/src/Nazara/Platform/Window.cpp +++ b/src/Nazara/Platform/Window.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include @@ -39,13 +38,10 @@ namespace Nz Window::Window(Window&& window) : m_events(std::move(window.m_events)), m_pendingEvents(std::move(window.m_pendingEvents)), - m_eventCondition(std::move(window.m_eventCondition)), m_cursorController(std::move(window.m_cursorController)), m_cursor(std::move(window.m_cursor)), m_eventHandler(std::move(window.m_eventHandler)), m_icon(std::move(window.m_icon)), - m_eventMutex(std::move(window.m_eventMutex)), - m_eventConditionMutex(std::move(window.m_eventConditionMutex)), m_asyncWindow(window.m_asyncWindow), m_closed(window.m_asyncWindow), m_closeOnQuit(window.m_closeOnQuit), @@ -344,7 +340,7 @@ namespace Nz m_impl->ProcessEvents(block); else { - LockGuard eventLock(m_eventMutex); + std::lock_guard eventLock(m_eventMutex); for (const WindowEvent& event : m_pendingEvents) HandleEvent(event); @@ -570,16 +566,19 @@ namespace Nz } else { - LockGuard lock(m_eventMutex); + std::lock_guard lock(m_eventMutex); if (m_events.empty()) { m_waitForEvent = true; - m_eventConditionMutex.Lock(); - m_eventMutex.Unlock(); - m_eventCondition.Wait(&m_eventConditionMutex); - m_eventMutex.Lock(); - m_eventConditionMutex.Unlock(); + { + m_eventMutex.unlock(); + + std::unique_lock eventConditionLock(m_eventConditionMutex); + m_eventCondition.wait(eventConditionLock); + + m_eventMutex.lock(); + } m_waitForEvent = false; } @@ -601,13 +600,10 @@ namespace Nz { m_events = std::move(window.m_events); m_pendingEvents = std::move(window.m_pendingEvents); - m_eventCondition = std::move(window.m_eventCondition); m_cursorController = std::move(window.m_cursorController); m_cursor = std::move(window.m_cursor); m_eventHandler = std::move(window.m_eventHandler); m_icon = std::move(window.m_icon); - m_eventMutex = std::move(window.m_eventMutex); - m_eventConditionMutex = std::move(window.m_eventConditionMutex); m_asyncWindow = window.m_asyncWindow; m_closed = window.m_asyncWindow; m_closeOnQuit = window.m_closeOnQuit; diff --git a/src/Nazara/Renderer/RenderWindow.cpp b/src/Nazara/Renderer/RenderWindow.cpp index b1ade1d95..b4d4f259b 100644 --- a/src/Nazara/Renderer/RenderWindow.cpp +++ b/src/Nazara/Renderer/RenderWindow.cpp @@ -5,10 +5,10 @@ #include #include #include -#include #include #include #include +#include #include namespace Nz @@ -137,7 +137,7 @@ namespace Nz { int remainingTime = 1000/static_cast(m_framerateLimit) - static_cast(m_clock.GetMilliseconds()); if (remainingTime > 0) - Thread::Sleep(remainingTime); + std::this_thread::sleep_for(std::chrono::milliseconds(remainingTime)); m_clock.Restart(); } diff --git a/src/Nazara/Renderer/Shader.cpp b/src/Nazara/Renderer/Shader.cpp index bfef4c12d..a3e5662ce 100644 --- a/src/Nazara/Renderer/Shader.cpp +++ b/src/Nazara/Renderer/Shader.cpp @@ -62,7 +62,7 @@ namespace Nz m_attachedShaders[stage].push_back(shader); } - bool Shader::AttachStageFromFile(ShaderStageType stage, const String& filePath) + bool Shader::AttachStageFromFile(ShaderStageType stage, const std::filesystem::path& filePath) { ShaderStage shaderStage(stage); if (!shaderStage.IsValid()) diff --git a/src/Nazara/Renderer/ShaderStage.cpp b/src/Nazara/Renderer/ShaderStage.cpp index 29f434091..bf88c4a06 100644 --- a/src/Nazara/Renderer/ShaderStage.cpp +++ b/src/Nazara/Renderer/ShaderStage.cpp @@ -165,7 +165,7 @@ namespace Nz glShaderSource(m_id, 1, &tmp, &length); } - bool ShaderStage::SetSourceFromFile(const String& filePath) + bool ShaderStage::SetSourceFromFile(const std::filesystem::path& filePath) { #if NAZARA_RENDERER_SAFE if (!m_id) @@ -178,7 +178,7 @@ namespace Nz File file(filePath); if (!file.Open(OpenMode_ReadOnly | OpenMode_Text)) { - NazaraError("Failed to open \"" + filePath + '"'); + NazaraError("Failed to open \"" + filePath.generic_u8string() + '"'); return false; } diff --git a/src/Nazara/Renderer/Texture.cpp b/src/Nazara/Renderer/Texture.cpp index a03dc558a..7ade50291 100644 --- a/src/Nazara/Renderer/Texture.cpp +++ b/src/Nazara/Renderer/Texture.cpp @@ -483,7 +483,7 @@ namespace Nz return m_impl != nullptr; } - bool Texture::LoadFaceFromFile(CubemapFace face, const String& filePath, const ImageParams& params) + bool Texture::LoadFaceFromFile(CubemapFace face, const std::filesystem::path& filePath, const ImageParams& params) { #if NAZARA_RENDERER_SAFE if (!m_impl) @@ -601,7 +601,7 @@ namespace Nz return Update(image, Rectui(0, 0, faceSize, faceSize), face); } - bool Texture::SaveToFile(const String& filePath, const ImageParams& params) + bool Texture::SaveToFile(const std::filesystem::path& filePath, const ImageParams& params) { Image image; if (!Download(&image)) @@ -613,7 +613,7 @@ namespace Nz return image.SaveToFile(filePath, params); } - bool Texture::SaveToStream(Stream& stream, const String& format, const ImageParams& params) + bool Texture::SaveToStream(Stream& stream, const std::string& format, const ImageParams& params) { Image image; if (!Download(&image)) @@ -935,7 +935,7 @@ namespace Nz return false; } - TextureRef Texture::LoadFromFile(const String& filePath, const ImageParams& params, bool generateMipmaps) + TextureRef Texture::LoadFromFile(const std::filesystem::path& filePath, const ImageParams& params, bool generateMipmaps) { ImageRef image = Image::LoadFromFile(filePath, params); if (!image) @@ -1047,7 +1047,7 @@ namespace Nz return LoadFromImage(image, generateMipmaps); } - TextureRef Texture::LoadArrayFromFile(const String& filePath, const ImageParams& imageParams, bool generateMipmaps, const Vector2ui& atlasSize) + TextureRef Texture::LoadArrayFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams, bool generateMipmaps, const Vector2ui& atlasSize) { ImageRef cubemap = Image::LoadArrayFromFile(filePath, imageParams, atlasSize); if (!cubemap) @@ -1095,7 +1095,7 @@ namespace Nz return LoadFromImage(cubemap, generateMipmaps); } - TextureRef Texture::LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams, bool generateMipmaps, const CubemapParams& cubemapParams) + TextureRef Texture::LoadCubemapFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams, bool generateMipmaps, const CubemapParams& cubemapParams) { ImageRef cubemap = Image::LoadCubemapFromFile(filePath, imageParams, cubemapParams); if (!cubemap) diff --git a/src/Nazara/Renderer/UberShaderPreprocessor.cpp b/src/Nazara/Renderer/UberShaderPreprocessor.cpp index 50eed66ac..aec846a09 100644 --- a/src/Nazara/Renderer/UberShaderPreprocessor.cpp +++ b/src/Nazara/Renderer/UberShaderPreprocessor.cpp @@ -166,12 +166,12 @@ namespace Nz } } - bool UberShaderPreprocessor::SetShaderFromFile(ShaderStageType stage, const String& filePath, const String& shaderFlags, const String& requiredFlags) + bool UberShaderPreprocessor::SetShaderFromFile(ShaderStageType stage, const std::filesystem::path& filePath, const String& shaderFlags, const String& requiredFlags) { File file(filePath); if (!file.Open(OpenMode_ReadOnly | OpenMode_Text)) { - NazaraError("Failed to open \"" + filePath + '"'); + NazaraError("Failed to open \"" + filePath.generic_u8string() + '"'); return false; } diff --git a/src/Nazara/Renderer/Win32/ContextImpl.cpp b/src/Nazara/Renderer/Win32/ContextImpl.cpp index fa975747d..d221e3d86 100644 --- a/src/Nazara/Renderer/Win32/ContextImpl.cpp +++ b/src/Nazara/Renderer/Win32/ContextImpl.cpp @@ -7,11 +7,10 @@ #include #include #include -#include -#include #include #include #include +#include #include namespace Nz @@ -185,8 +184,8 @@ namespace Nz if (shareContext) { // wglShareLists n'est pas thread-safe (source: SFML) - static Mutex mutex; - LockGuard lock(mutex); + static std::mutex mutex; + std::lock_guard lock(mutex); if (!wglShareLists(shareContext, m_context)) NazaraWarning("Failed to share the context: " + Error::GetLastSystemError()); diff --git a/src/Nazara/Utility/Animation.cpp b/src/Nazara/Utility/Animation.cpp index d60e095ee..1a05ef423 100644 --- a/src/Nazara/Utility/Animation.cpp +++ b/src/Nazara/Utility/Animation.cpp @@ -16,13 +16,13 @@ namespace Nz { struct AnimationImpl { - std::unordered_map sequenceMap; + std::unordered_map sequenceMap; std::vector sequences; std::vector sequenceJoints; // Uniquement pour les animations squelettiques AnimationType type; bool loopPointInterpolation = false; - UInt32 frameCount; - UInt32 jointCount; // Uniquement pour les animations squelettiques + std::size_t frameCount; + std::size_t jointCount; // Uniquement pour les animations squelettiques }; bool AnimationParams::IsValid() const @@ -50,7 +50,7 @@ namespace Nz if (m_impl->type == AnimationType_Skeletal) { - UInt32 endFrame = sequence.firstFrame + sequence.frameCount - 1; + std::size_t endFrame = sequence.firstFrame + sequence.frameCount - 1; if (endFrame >= m_impl->frameCount) { m_impl->frameCount = endFrame+1; @@ -69,7 +69,7 @@ namespace Nz } #endif - m_impl->sequenceMap[sequence.name] = static_cast(m_impl->sequences.size()); + m_impl->sequenceMap[sequence.name] = static_cast(m_impl->sequences.size()); } m_impl->sequences.push_back(sequence); @@ -77,7 +77,7 @@ namespace Nz return true; } - void Animation::AnimateSkeleton(Skeleton* targetSkeleton, UInt32 frameA, UInt32 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->type == AnimationType_Skeletal, "Animation is not skeletal"); @@ -86,7 +86,7 @@ namespace Nz NazaraAssert(frameA < m_impl->frameCount, "FrameA is out of range"); NazaraAssert(frameB < m_impl->frameCount, "FrameB is out of range"); - for (UInt32 i = 0; i < m_impl->jointCount; ++i) + for (std::size_t i = 0; i < m_impl->jointCount; ++i) { Joint* joint = targetSkeleton->GetJoint(i); @@ -99,7 +99,7 @@ namespace Nz } } - bool Animation::CreateSkeletal(UInt32 frameCount, UInt32 jointCount) + bool Animation::CreateSkeletal(std::size_t frameCount, std::size_t jointCount) { NazaraAssert(frameCount > 0, "Frame count must be over zero"); NazaraAssert(jointCount > 0, "Frame count must be over zero"); @@ -133,14 +133,14 @@ namespace Nz m_impl->loopPointInterpolation = loopPointInterpolation; } - UInt32 Animation::GetFrameCount() const + std::size_t Animation::GetFrameCount() const { NazaraAssert(m_impl, "Animation not created"); return m_impl->frameCount; } - UInt32 Animation::GetJointCount() const + std::size_t Animation::GetJointCount() const { NazaraAssert(m_impl, "Animation not created"); @@ -161,7 +161,7 @@ namespace Nz return &m_impl->sequences[it->second]; } - Sequence* Animation::GetSequence(UInt32 index) + Sequence* Animation::GetSequence(std::size_t index) { NazaraAssert(m_impl, "Animation not created"); NazaraAssert(index < m_impl->sequences.size(), "Sequence index out of range"); @@ -183,7 +183,7 @@ namespace Nz return &m_impl->sequences[it->second]; } - const Sequence* Animation::GetSequence(UInt32 index) const + const Sequence* Animation::GetSequence(std::size_t index) const { NazaraAssert(m_impl, "Animation not created"); NazaraAssert(index < m_impl->sequences.size(), "Sequence index out of range"); @@ -191,14 +191,14 @@ namespace Nz return &m_impl->sequences[index]; } - UInt32 Animation::GetSequenceCount() const + std::size_t Animation::GetSequenceCount() const { NazaraAssert(m_impl, "Animation not created"); - return static_cast(m_impl->sequences.size()); + return static_cast(m_impl->sequences.size()); } - UInt32 Animation::GetSequenceIndex(const String& sequenceName) const + std::size_t Animation::GetSequenceIndex(const String& sequenceName) const { NazaraAssert(m_impl, "Animation not created"); @@ -212,7 +212,7 @@ namespace Nz return it->second; } - SequenceJoint* Animation::GetSequenceJoints(UInt32 frameIndex) + SequenceJoint* Animation::GetSequenceJoints(std::size_t frameIndex) { NazaraAssert(m_impl, "Animation not created"); NazaraAssert(m_impl->type == AnimationType_Skeletal, "Animation is not skeletal"); @@ -220,7 +220,7 @@ namespace Nz return &m_impl->sequenceJoints[frameIndex*m_impl->jointCount]; } - const SequenceJoint* Animation::GetSequenceJoints(UInt32 frameIndex) const + const SequenceJoint* Animation::GetSequenceJoints(std::size_t frameIndex) const { NazaraAssert(m_impl, "Animation not created"); NazaraAssert(m_impl->type == AnimationType_Skeletal, "Animation is not skeletal"); @@ -242,7 +242,7 @@ namespace Nz return m_impl->sequenceMap.find(sequenceName) != m_impl->sequenceMap.end(); } - bool Animation::HasSequence(UInt32 index) const + bool Animation::HasSequence(std::size_t index) const { NazaraAssert(m_impl, "Animation not created"); @@ -278,7 +278,7 @@ namespace Nz m_impl->sequences.erase(sequenceIt); } - void Animation::RemoveSequence(UInt32 index) + void Animation::RemoveSequence(std::size_t index) { NazaraAssert(m_impl, "Animation not created"); NazaraAssert(index < m_impl->sequences.size(), "Sequence index out of range"); @@ -289,7 +289,7 @@ namespace Nz m_impl->sequences.erase(it); } - AnimationRef Animation::LoadFromFile(const String& filePath, const AnimationParams& params) + AnimationRef Animation::LoadFromFile(const std::filesystem::path& filePath, const AnimationParams& params) { return AnimationLoader::LoadFromFile(filePath, params); } diff --git a/src/Nazara/Utility/Font.cpp b/src/Nazara/Utility/Font.cpp index a61311fb0..7bbd80ad2 100644 --- a/src/Nazara/Utility/Font.cpp +++ b/src/Nazara/Utility/Font.cpp @@ -354,7 +354,7 @@ namespace Nz return s_defaultMinimumStepSize; } - FontRef Font::OpenFromFile(const String& filePath, const FontParams& params) + FontRef Font::OpenFromFile(const std::filesystem::path& filePath, const FontParams& params) { return FontLoader::LoadFromFile(filePath, params); } diff --git a/src/Nazara/Utility/Formats/DDSLoader.cpp b/src/Nazara/Utility/Formats/DDSLoader.cpp index e4c6f2d57..9fb93cc6e 100644 --- a/src/Nazara/Utility/Formats/DDSLoader.cpp +++ b/src/Nazara/Utility/Formats/DDSLoader.cpp @@ -18,7 +18,7 @@ namespace Nz DDSLoader() = delete; ~DDSLoader() = delete; - static bool IsSupported(const String& extension) + static bool IsSupported(const std::string& extension) { return (extension == "dds"); } diff --git a/src/Nazara/Utility/Formats/FreeTypeLoader.cpp b/src/Nazara/Utility/Formats/FreeTypeLoader.cpp index 05814a903..37ca659fe 100644 --- a/src/Nazara/Utility/Formats/FreeTypeLoader.cpp +++ b/src/Nazara/Utility/Formats/FreeTypeLoader.cpp @@ -320,9 +320,9 @@ namespace Nz return characterSize/15.f; // Joker ? } - bool SetFile(const String& filePath) + bool SetFile(const std::filesystem::path& filePath) { - std::unique_ptr file(new File); + std::unique_ptr file = std::make_unique(); if (!file->Open(filePath, OpenMode_ReadOnly)) { NazaraError("Failed to open stream from file: " + Error::GetLastError()); @@ -336,7 +336,7 @@ namespace Nz void SetMemory(const void* data, std::size_t size) { - m_ownedStream.reset(new MemoryView(data, size)); + m_ownedStream = std::make_unique(data, size); SetStream(*m_ownedStream); } @@ -349,14 +349,14 @@ namespace Nz m_stream.pos = 0; m_stream.size = static_cast(stream.GetSize()); - m_args.driver = 0; + m_args.driver = nullptr; m_args.flags = FT_OPEN_STREAM; m_args.stream = &m_stream; } bool SupportsOutline(float /*outlineThickness*/) const override { - return s_stroker != 0; + return s_stroker != nullptr; } bool SupportsStyle(TextStyleFlags style) const override @@ -383,10 +383,10 @@ namespace Nz mutable unsigned int m_characterSize; }; - bool IsSupported(const String& extension) + bool IsSupported(const std::string& extension) { ///FIXME: Je suppose qu'il en manque quelques unes.. - static std::set supportedExtensions = { + static std::set supportedExtensions = { "afm", "bdf", "cff", "cid", "dfont", "fnt", "fon", "otf", "pfa", "pfb", "pfm", "pfr", "sfnt", "ttc", "tte", "ttf" }; @@ -408,12 +408,11 @@ namespace Nz return Ternary_False; } - FontRef LoadFile(const String& filePath, const FontParams& parameters) + FontRef LoadFile(const std::filesystem::path& filePath, const FontParams& parameters) { NazaraUnused(parameters); - std::unique_ptr face(new FreeTypeStream); - + std::unique_ptr face = std::make_unique(); if (!face->SetFile(filePath)) { NazaraError("Failed to open file"); diff --git a/src/Nazara/Utility/Formats/MD2Loader.cpp b/src/Nazara/Utility/Formats/MD2Loader.cpp index b58799978..d5fb90270 100644 --- a/src/Nazara/Utility/Formats/MD2Loader.cpp +++ b/src/Nazara/Utility/Formats/MD2Loader.cpp @@ -20,7 +20,7 @@ namespace Nz { namespace { - bool IsSupported(const String& extension) + bool IsSupported(const std::string& extension) { return (extension == "md2"); } @@ -93,14 +93,14 @@ namespace Nz mesh->SetMaterialCount(header.num_skins); stream.SetCursorPos(header.offset_skins); { - String baseDir = stream.GetDirectory(); + std::filesystem::path baseDir = stream.GetDirectory(); char skin[68]; for (unsigned int i = 0; i < header.num_skins; ++i) { stream.Read(skin, 68*sizeof(char)); ParameterList matData; - matData.SetParameter(MaterialData::DiffuseTexturePath, baseDir + skin); + matData.SetParameter(MaterialData::DiffuseTexturePath, (baseDir / skin).generic_u8string()); mesh->SetMaterialData(i, std::move(matData)); } @@ -196,10 +196,8 @@ namespace Nz Vector2f invSkinSize(1.f / header.skinwidth, 1.f / header.skinheight); for (unsigned int i = 0; i < header.num_tris; ++i) { - for (unsigned int j = 0; j < 3; ++j) + for (unsigned int fixedIndex : indexFix) //< Reverse winding order { - const unsigned int fixedIndex = indexFix[j]; //< Reverse winding order - const MD2_TexCoord& texC = texCoords[triangles[i].texCoords[fixedIndex]]; Vector2f uv(texC.u, texC.v); uv *= invSkinSize; diff --git a/src/Nazara/Utility/Formats/MD5AnimLoader.cpp b/src/Nazara/Utility/Formats/MD5AnimLoader.cpp index 84f0baeaf..e93299d1a 100644 --- a/src/Nazara/Utility/Formats/MD5AnimLoader.cpp +++ b/src/Nazara/Utility/Formats/MD5AnimLoader.cpp @@ -3,7 +3,6 @@ // For conditions of distribution and use, see copyright notice in Config.hpp #include -#include #include #include #include @@ -13,7 +12,7 @@ namespace Nz { namespace { - bool IsSupported(const String& extension) + bool IsSupported(const std::string& extension) { return (extension == "md5anim"); } @@ -40,10 +39,10 @@ namespace Nz } const MD5AnimParser::Frame* frames = parser.GetFrames(); - UInt32 frameCount = parser.GetFrameCount(); - UInt32 frameRate = parser.GetFrameRate(); + std::size_t frameCount = parser.GetFrameCount(); + std::size_t frameRate = parser.GetFrameRate(); const MD5AnimParser::Joint* joints = parser.GetJoints(); - UInt32 jointCount = parser.GetJointCount(); + std::size_t jointCount = parser.GetJointCount(); // À ce stade, nous sommes censés avoir assez d'informations pour créer l'animation AnimationRef animation = Animation::New(); @@ -53,7 +52,7 @@ namespace Nz sequence.firstFrame = 0; sequence.frameCount = frameCount; sequence.frameRate = frameRate; - sequence.name = stream.GetPath().SubStringFrom(NAZARA_DIRECTORY_SEPARATOR, -1, true); + sequence.name = stream.GetPath().filename().generic_u8string(); animation->AddSequence(sequence); @@ -63,10 +62,10 @@ namespace Nz Quaternionf rotationQuat = Quaternionf::RotationBetween(Vector3f::UnitX(), Vector3f::Forward()) * Quaternionf::RotationBetween(Vector3f::UnitZ(), Vector3f::Up()); - for (UInt32 i = 0; i < jointCount; ++i) + for (std::size_t i = 0; i < jointCount; ++i) { int parent = joints[i].parent; - for (UInt32 j = 0; j < frameCount; ++j) + for (std::size_t j = 0; j < frameCount; ++j) { SequenceJoint& sequenceJoint = sequenceJoints[j*jointCount + i]; diff --git a/src/Nazara/Utility/Formats/MD5MeshLoader.cpp b/src/Nazara/Utility/Formats/MD5MeshLoader.cpp index 31b3a64a7..69ffcad36 100644 --- a/src/Nazara/Utility/Formats/MD5MeshLoader.cpp +++ b/src/Nazara/Utility/Formats/MD5MeshLoader.cpp @@ -20,7 +20,7 @@ namespace Nz { namespace { - bool IsSupported(const String& extension) + bool IsSupported(const std::string& extension) { return (extension == "md5mesh"); } @@ -48,7 +48,7 @@ namespace Nz Quaternionf rotationQuat = Quaternionf::RotationBetween(Vector3f::UnitX(), Vector3f::Forward()) * Quaternionf::RotationBetween(Vector3f::UnitZ(), Vector3f::Up()); - String baseDir = stream.GetDirectory(); + std::filesystem::path baseDir = stream.GetDirectory(); // Le hellknight de Doom 3 fait ~120 unités, et il est dit qu'il fait trois mètres // Nous réduisons donc la taille générale des fichiers MD5 de 1/40 @@ -198,7 +198,7 @@ namespace Nz // Material ParameterList matData; - matData.SetParameter(MaterialData::FilePath, baseDir + md5Mesh.shader); + matData.SetParameter(MaterialData::FilePath, (baseDir / md5Mesh.shader).generic_u8string()); mesh->SetMaterialData(i, std::move(matData)); @@ -211,11 +211,11 @@ namespace Nz // Animation // Il est peut-être éventuellement possible que la probabilité que l'animation ait le même nom soit non-nulle. - String path = stream.GetPath(); - if (!path.IsEmpty()) + std::filesystem::path path = stream.GetPath(); + if (!path.empty()) { - path.Replace(".md5mesh", ".md5anim", -8, String::CaseInsensitive); - if (File::Exists(path)) + path.replace_extension(".md5anim"); + if (std::filesystem::exists(path)) mesh->SetAnimation(path); } } @@ -306,7 +306,7 @@ namespace Nz // Material ParameterList matData; - matData.SetParameter(MaterialData::FilePath, baseDir + md5Mesh.shader); + matData.SetParameter(MaterialData::FilePath, (baseDir / md5Mesh.shader).generic_u8string()); mesh->SetMaterialData(i, std::move(matData)); } diff --git a/src/Nazara/Utility/Formats/MD5MeshParser.cpp b/src/Nazara/Utility/Formats/MD5MeshParser.cpp index c6af0ed96..fc5f30f6d 100644 --- a/src/Nazara/Utility/Formats/MD5MeshParser.cpp +++ b/src/Nazara/Utility/Formats/MD5MeshParser.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -71,19 +72,19 @@ namespace Nz { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING case 'M': // MD5Version - if (m_currentLine.GetWord(0) != "MD5Version") + if (!StartsWith(m_currentLine, "MD5Version ")) UnrecognizedLine(); break; case 'c': // commandline - if (m_currentLine.GetWord(0) != "commandline") + if (!StartsWith(m_currentLine, "commandline ")) UnrecognizedLine(); break; #endif case 'j': // joints #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - if (!m_currentLine.StartsWith("joints {")) + if (!StartsWith(m_currentLine, "joints {")) { UnrecognizedLine(); break; @@ -100,7 +101,7 @@ namespace Nz case 'm': // mesh { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - if (m_currentLine != "mesh {") + if (!StartsWith(m_currentLine, "mesh {")) { UnrecognizedLine(); break; @@ -113,7 +114,7 @@ namespace Nz Warning("More meshes than registred"); #endif - m_meshes.push_back(Mesh()); + m_meshes.emplace_back(); } if (!ParseMesh()) @@ -182,14 +183,25 @@ namespace Nz m_lineCount++; m_currentLine = m_stream.ReadLine(); - if (m_currentLine.IsEmpty()) - continue; - m_currentLine = m_currentLine.SubStringTo("//"); // On ignore les commentaires - m_currentLine.Simplify(); // Pour un traitement plus simple - m_currentLine.Trim(); + if (std::size_t p = m_currentLine.find("//"); p != m_currentLine.npos) + { + if (p > 0) + m_currentLine = m_currentLine.substr(0, p - 1); + else + m_currentLine.clear(); + } + + // Trim left + m_currentLine.erase(m_currentLine.begin(), std::find_if(m_currentLine.begin(), m_currentLine.end(), [](char c) + { + return !std::isspace(c); + })); + + if (m_currentLine.empty()) + continue; } - while (m_currentLine.IsEmpty()); + while (m_currentLine.empty()); } else m_keepLastLine = false; @@ -197,9 +209,9 @@ namespace Nz return true; } - void MD5MeshParser::Error(const String& message) + void MD5MeshParser::Error(const std::string& message) { - NazaraError(message + " at line #" + String::Number(m_lineCount)); + NazaraError(message + " at line #" + std::to_string(m_lineCount)); } bool MD5MeshParser::ParseJoints() @@ -216,7 +228,7 @@ namespace Nz if (!Advance()) return false; - std::size_t pos = m_currentLine.Find(' '); + std::size_t pos = m_currentLine.find(' '); if (pos == String::npos) { UnrecognizedLine(true); @@ -231,8 +243,8 @@ namespace Nz char name[64]; if (std::sscanf(&m_currentLine[0], "%63s %d ( %f %f %f ) ( %f %f %f )", &name[0], &m_joints[i].parent, - &m_joints[i].bindPos.x, &m_joints[i].bindPos.y, &m_joints[i].bindPos.z, - &m_joints[i].bindOrient.x, &m_joints[i].bindOrient.y, &m_joints[i].bindOrient.z) != 8) + &m_joints[i].bindPos.x, &m_joints[i].bindPos.y, &m_joints[i].bindPos.z, + &m_joints[i].bindOrient.x, &m_joints[i].bindOrient.y, &m_joints[i].bindOrient.z) != 8) { UnrecognizedLine(true); return false; @@ -246,7 +258,7 @@ namespace Nz { if (static_cast(parent) >= jointCount) { - Error("Joint's parent is out of bounds (" + String::Number(parent) + " >= " + String::Number(jointCount) + ')'); + Error("Joint's parent is out of bounds (" + std::to_string(parent) + " >= " + std::to_string(jointCount) + ')'); return false; } } @@ -257,7 +269,7 @@ namespace Nz if (!Advance()) return false; - if (m_currentLine != '}') + if (m_currentLine != "}") { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING Warning("Hierarchy braces closing not found"); @@ -282,17 +294,42 @@ namespace Nz break; case 's': // shader + { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - if (!m_currentLine.StartsWith("shader ")) + if (!StartsWith(m_currentLine, "shader ")) { UnrecognizedLine(); break; } #endif - m_meshes[m_meshIndex].shader = m_currentLine.SubString(7); - m_meshes[m_meshIndex].shader.Trim('"'); + std::string_view shader = m_currentLine; + shader = shader.substr(7); + if (shader.empty()) + { +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + UnrecognizedLine(); +#endif + break; + } + + if (shader.front() == '"') + shader.remove_prefix(1); + + if (shader.empty()) + { +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + UnrecognizedLine(); +#endif + break; + } + + if (shader.back() == '"') + shader.remove_prefix(1); + + m_meshes[m_meshIndex].shader = shader; break; + } case 'n': // num[tris/verts] { @@ -315,7 +352,7 @@ namespace Nz if (index != i) { - Error("Unexpected triangle index (expected " + String::Number(i) + ", got " + String::Number(index) + ')'); + Error("Unexpected triangle index (expected " + std::to_string(i) + ", got " + std::to_string(index) + ')'); return false; } } @@ -338,7 +375,7 @@ namespace Nz if (index != i) { - Error("Unexpected vertex index (expected " + String::Number(i) + ", got " + String::Number(index) + ')'); + Error("Unexpected vertex index (expected " + std::to_string(i) + ", got " + std::to_string(index) + ')'); return false; } } @@ -354,7 +391,7 @@ namespace Nz Weight& weight = m_meshes[m_meshIndex].weights[i]; unsigned int index; if (std::sscanf(&m_currentLine[0], "weight %u %u %f ( %f %f %f )", &index, &weight.joint, &weight.bias, - &weight.pos.x, &weight.pos.y, &weight.pos.z) != 6) + &weight.pos.x, &weight.pos.y, &weight.pos.z) != 6) { UnrecognizedLine(true); return false; @@ -362,7 +399,7 @@ namespace Nz if (index != i) { - Error("Unexpected weight index (expected " + String::Number(i) + ", got " + String::Number(index) + ')'); + Error("Unexpected weight index (expected " + std::to_string(i) + ", got " + std::to_string(index) + ')'); return false; } } @@ -408,14 +445,14 @@ namespace Nz return true; } - void MD5MeshParser::Warning(const String& message) + void MD5MeshParser::Warning(const std::string& message) { - NazaraWarning(message + " at line #" + String::Number(m_lineCount)); + NazaraWarning(message + " at line #" + std::to_string(m_lineCount)); } void MD5MeshParser::UnrecognizedLine(bool error) { - String message = "Unrecognized \"" + m_currentLine + '"'; + std::string message = "Unrecognized \"" + m_currentLine + '"'; if (error) Error(message); diff --git a/src/Nazara/Utility/Formats/MTLParser.cpp b/src/Nazara/Utility/Formats/MTLParser.cpp index 31a377e38..743622f0c 100644 --- a/src/Nazara/Utility/Formats/MTLParser.cpp +++ b/src/Nazara/Utility/Formats/MTLParser.cpp @@ -4,12 +4,31 @@ #include #include +#include #include #include #include namespace Nz { + namespace + { + template + bool TestKeyword(const std::string& currentLine, const char(&keyword)[N], std::size_t& offset) + { + if (currentLine.size() > N && StartsWith(currentLine, keyword, CaseIndependent{}) && std::isspace(currentLine[N - 1])) + { + offset = N; + while (offset < currentLine.size() && std::isspace(currentLine[offset])) + offset++; + + return offset < currentLine.size(); + } + else + return false; + } + } + bool MTLParser::Parse(Stream& stream) { m_currentStream = &stream; @@ -31,266 +50,434 @@ namespace Nz m_materials.clear(); Material* currentMaterial = nullptr; + std::size_t offset; while (Advance(false)) { - String keyword = m_currentLine.GetWord(0).ToLower(); - if (keyword == "ka") + switch (std::tolower(m_currentLine[0])) { - float r, g, b; - if (std::sscanf(&m_currentLine[3], "%f %f %f", &r, &g, &b) == 3) + case 'b': { - if (!currentMaterial) - currentMaterial = AddMaterial("default"); + if (TestKeyword(m_currentLine, "bump", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); - currentMaterial->ambient = Color(static_cast(r*255.f), static_cast(g*255.f), static_cast(b*255.f)); + currentMaterial->bumpMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } } - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - else - UnrecognizedLine(); - #endif - } - else if (keyword == "kd") - { - float r, g, b; - if (std::sscanf(&m_currentLine[3], "%f %f %f", &r, &g, &b) == 3) + + case 'd': { - if (!currentMaterial) - currentMaterial = AddMaterial("default"); + if (TestKeyword(m_currentLine, "d", offset)) + { + float alpha; + if (std::sscanf(&m_currentLine[2], "%f", &alpha) == 1) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); - currentMaterial->diffuse = Color(static_cast(r*255.f), static_cast(g*255.f), static_cast(b*255.f)); + currentMaterial->alpha = alpha; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "decal", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->decalMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "disp", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->displacementMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + break; } - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - else - UnrecognizedLine(); - #endif - } - else if (keyword == "ks") - { - float r, g, b; - if (std::sscanf(&m_currentLine[3], "%f %f %f", &r, &g, &b) == 3) + + case 'e': { - if (!currentMaterial) - currentMaterial = AddMaterial("default"); + if (TestKeyword(m_currentLine, "emissive", offset)) + { + // This is a custom keyword + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); - currentMaterial->specular = Color(static_cast(r*255.f), static_cast(g*255.f), static_cast(b*255.f)); + currentMaterial->emissiveMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + break; } - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - else - UnrecognizedLine(); - #endif - } - else if (keyword == "ni") - { - float density; - if (std::sscanf(&m_currentLine[3], "%f", &density) == 1) + + case 'k': { - if (!currentMaterial) - currentMaterial = AddMaterial("default"); + if (TestKeyword(m_currentLine, "ka", offset)) + { + float r, g, b; + if (std::sscanf(&m_currentLine[offset], "%f %f %f", &r, &g, &b) == 3) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); - currentMaterial->refractionIndex = density; + currentMaterial->ambient = Color(static_cast(r * 255.f), static_cast(g * 255.f), static_cast(b * 255.f)); + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "kd", offset)) + { + float r, g, b; + if (std::sscanf(&m_currentLine[offset], "%f %f %f", &r, &g, &b) == 3) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->diffuse = Color(static_cast(r * 255.f), static_cast(g * 255.f), static_cast(b * 255.f)); + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "ks", offset)) + { + float r, g, b; + if (std::sscanf(&m_currentLine[offset], "%f %f %f", &r, &g, &b) == 3) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->specular = Color(static_cast(r * 255.f), static_cast(g * 255.f), static_cast(b * 255.f)); + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + + break; } - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - else - UnrecognizedLine(); - #endif - } - else if (keyword == "ns") - { - float coef; - if (std::sscanf(&m_currentLine[3], "%f", &coef) == 1) + + case 'i': { - if (!currentMaterial) - currentMaterial = AddMaterial("default"); + if (TestKeyword(m_currentLine, "illum", offset)) + { + unsigned int model; + if (std::sscanf(&m_currentLine[offset], "%u", &model) == 1) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); - currentMaterial->shininess = coef; - } - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - else - UnrecognizedLine(); - #endif - } - else if (keyword == 'd') - { - float alpha; - if (std::sscanf(&m_currentLine[(keyword[0] == 'd') ? 2 : 3], "%f", &alpha) == 1) - { - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->alpha = alpha; - } - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - else - UnrecognizedLine(); - #endif - } - else if (keyword == "tr") - { - float alpha; - if (std::sscanf(&m_currentLine[(keyword[0] == 'd') ? 2 : 3], "%f", &alpha) == 1) - { - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->alpha = 1.f - alpha; // tr vaut pour la "valeur de transparence", 0 = opaque - } - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - else - UnrecognizedLine(); - #endif - } - else if (keyword == "illum") - { - unsigned int model; - if (std::sscanf(&m_currentLine[6], "%u", &model) == 1) - { - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->illumModel = model; - } - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - else - UnrecognizedLine(); - #endif - } - else if (keyword == "map_ka") - { - std::size_t mapPos = m_currentLine.GetWordPosition(1); - if (mapPos != String::npos) - { - String map = m_currentLine.SubString(mapPos); - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->ambientMap = map; - } - } - else if (keyword == "map_kd") - { - std::size_t mapPos = m_currentLine.GetWordPosition(1); - if (mapPos != String::npos) - { - String map = m_currentLine.SubString(mapPos); - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->diffuseMap = map; - } - } - else if (keyword == "map_ks") - { - std::size_t mapPos = m_currentLine.GetWordPosition(1); - if (mapPos != String::npos) - { - String map = m_currentLine.SubString(mapPos); - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->specularMap = map; - } - } - else if (keyword == "map_bump" || keyword == "bump") - { - std::size_t mapPos = m_currentLine.GetWordPosition(1); - if (mapPos != String::npos) - { - String map = m_currentLine.SubString(mapPos); - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->bumpMap = map; - } - } - else if (keyword == "map_d") - { - std::size_t mapPos = m_currentLine.GetWordPosition(1); - if (mapPos != String::npos) - { - String map = m_currentLine.SubString(mapPos); - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->alphaMap = map; - } - } - else if (keyword == "map_decal" || keyword == "decal") - { - std::size_t mapPos = m_currentLine.GetWordPosition(1); - if (mapPos != String::npos) - { - String map = m_currentLine.SubString(mapPos); - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->decalMap = map; - } - } - else if (keyword == "map_disp" || keyword == "disp") - { - std::size_t mapPos = m_currentLine.GetWordPosition(1); - if (mapPos != String::npos) - { - String map = m_currentLine.SubString(mapPos); - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->displacementMap = map; - } - } - else if (keyword == "map_refl" || keyword == "refl") - { - std::size_t mapPos = m_currentLine.GetWordPosition(1); - if (mapPos != String::npos) - { - String map = m_currentLine.SubString(mapPos); - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->reflectionMap = map; - } - } - else if (keyword == "map_normal" || keyword == "normal") - { - // This is a custom keyword - std::size_t mapPos = m_currentLine.GetWordPosition(1); - if (mapPos != String::npos) - { - String map = m_currentLine.SubString(mapPos); - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->normalMap = map; - } - } - else if (keyword == "map_emissive" || keyword == "emissive") - { - // This is a custom keyword - std::size_t mapPos = m_currentLine.GetWordPosition(1); - if (mapPos != String::npos) - { - String map = m_currentLine.SubString(mapPos); - if (!currentMaterial) - currentMaterial = AddMaterial("default"); - - currentMaterial->emissiveMap = map; - } - } - else if (keyword == "newmtl") - { - String materialName = m_currentLine.SubString(m_currentLine.GetWordPosition(1)); - if (!materialName.IsEmpty()) - currentMaterial = AddMaterial(materialName); - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - else - UnrecognizedLine(); - #endif - } + currentMaterial->illumModel = model; + } #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - else - UnrecognizedLine(); + else + UnrecognizedLine(); #endif + } + break; + } + + case 'm': + { + if (TestKeyword(m_currentLine, "map_ka", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->ambientMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "map_kd", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->diffuseMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "map_ks", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->specularMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "map_bump", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->bumpMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "map_d", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->alphaMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "map_decal", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->decalMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "map_disp", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->displacementMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "map_refl", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->reflectionMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "map_normal", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->normalMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "map_emissive", offset)) + { + // This is a custom keyword + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->emissiveMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + break; + } + + case 'n': + { + if (TestKeyword(m_currentLine, "ni", offset)) + { + float density; + if (std::sscanf(&m_currentLine[offset], "%f", &density) == 1) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->refractionIndex = density; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "ns", offset)) + { + float coef; + if (std::sscanf(&m_currentLine[offset], "%f", &coef) == 1) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->shininess = coef; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "normal", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->normalMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + else if (TestKeyword(m_currentLine, "newmtl", offset)) + { + std::string materialName = m_currentLine.substr(offset); + if (!materialName.empty()) + currentMaterial = AddMaterial(materialName); +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + break; + } + + case 'r': + { + if (TestKeyword(m_currentLine, "refl", offset)) + { + std::string map = m_currentLine.substr(offset); + if (!map.empty()) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->reflectionMap = map; + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + break; + } + + case 't': + { + if (TestKeyword(m_currentLine, "tr", offset)) + { + float alpha; + if (std::sscanf(&m_currentLine[offset], "%f", &alpha) == 1) + { + if (!currentMaterial) + currentMaterial = AddMaterial("default"); + + currentMaterial->alpha = 1.f - alpha; // tr vaut pour la "valeur de transparence", 0 = opaque + } +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + else + UnrecognizedLine(); +#endif + } + } + + default: +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + UnrecognizedLine(); +#endif + break; + } } return true; @@ -378,49 +565,49 @@ namespace Nz EmitLine(mat.illumModel); } - if (!mat.ambientMap.IsEmpty()) + if (!mat.ambientMap.empty()) { Emit("map_Ka "); EmitLine(mat.ambientMap); } - if (!mat.diffuseMap.IsEmpty()) + if (!mat.diffuseMap.empty()) { Emit("map_Kd "); EmitLine(mat.diffuseMap); } - if (!mat.specularMap.IsEmpty()) + if (!mat.specularMap.empty()) { Emit("map_Ks "); EmitLine(mat.specularMap); } - if (!mat.bumpMap.IsEmpty()) + if (!mat.bumpMap.empty()) { Emit("map_bump "); EmitLine(mat.bumpMap); } - if (!mat.alphaMap.IsEmpty()) + if (!mat.alphaMap.empty()) { Emit("map_d "); EmitLine(mat.alphaMap); } - if (!mat.decalMap.IsEmpty()) + if (!mat.decalMap.empty()) { Emit("map_decal "); EmitLine(mat.decalMap); } - if (!mat.displacementMap.IsEmpty()) + if (!mat.displacementMap.empty()) { Emit("map_disp "); EmitLine(mat.displacementMap); } - if (!mat.reflectionMap.IsEmpty()) + if (!mat.reflectionMap.empty()) { Emit("map_refl "); EmitLine(mat.reflectionMap); @@ -450,13 +637,18 @@ namespace Nz m_lineCount++; m_currentLine = m_currentStream->ReadLine(); - if (m_currentLine.IsEmpty()) - continue; + if (std::size_t p = m_currentLine.find('#'); p != m_currentLine.npos) + { + if (p > 0) + m_currentLine = m_currentLine.substr(0, p - 1); + else + m_currentLine.clear(); + } - m_currentLine = m_currentLine.SubStringTo("#"); // On ignore les commentaires - m_currentLine.Simplify(); // Pour un traitement plus simple + if (m_currentLine.empty()) + continue; } - while (m_currentLine.IsEmpty()); + while (m_currentLine.empty()); } else m_keepLastLine = false; diff --git a/src/Nazara/Utility/Formats/OBJLoader.cpp b/src/Nazara/Utility/Formats/OBJLoader.cpp index 58b2d8e0a..819bbe256 100644 --- a/src/Nazara/Utility/Formats/OBJLoader.cpp +++ b/src/Nazara/Utility/Formats/OBJLoader.cpp @@ -22,7 +22,7 @@ namespace Nz { namespace { - bool IsSupported(const String& extension) + bool IsSupported(const std::string& extension) { return (extension == "obj"); } @@ -42,12 +42,12 @@ namespace Nz return Ternary_Unknown; } - bool ParseMTL(Mesh* mesh, const String& filePath, const String* materials, const OBJParser::Mesh* meshes, UInt32 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); if (!file.Open(OpenMode_ReadOnly | OpenMode_Text)) { - NazaraError("Failed to open MTL file (" + file.GetPath() + ')'); + NazaraError("Failed to open MTL file (" + file.GetPath().generic_u8string() + ')'); return false; } @@ -59,10 +59,10 @@ namespace Nz } std::unordered_map materialCache; - String baseDir = file.GetDirectory(); - for (UInt32 i = 0; i < meshCount; ++i) + std::filesystem::path baseDir = file.GetDirectory(); + for (std::size_t i = 0; i < meshCount; ++i) { - const String& matName = materials[meshes[i].material]; + const std::string& matName = materials[meshes[i].material]; const MTLParser::Material* mtlMat = materialParser.GetMaterial(matName); if (!mtlMat) { @@ -89,53 +89,53 @@ namespace Nz data.SetParameter(MaterialData::Shininess, mtlMat->shininess); data.SetParameter(MaterialData::SpecularColor, specularColor); - if (!mtlMat->alphaMap.IsEmpty()) + if (!mtlMat->alphaMap.empty()) { - String fullPath = mtlMat->alphaMap; - if (!Nz::File::IsAbsolute(fullPath)) - fullPath.Prepend(baseDir); + std::filesystem::path fullPath = mtlMat->alphaMap; + if (!fullPath.is_absolute()) + fullPath = baseDir / fullPath; - data.SetParameter(MaterialData::AlphaTexturePath, fullPath); + data.SetParameter(MaterialData::AlphaTexturePath, fullPath.generic_u8string()); } - if (!mtlMat->diffuseMap.IsEmpty()) + if (!mtlMat->diffuseMap.empty()) { - String fullPath = mtlMat->diffuseMap; - if (!Nz::File::IsAbsolute(fullPath)) - fullPath.Prepend(baseDir); + std::filesystem::path fullPath = mtlMat->diffuseMap; + if (!fullPath.is_absolute()) + fullPath = baseDir / fullPath; - data.SetParameter(MaterialData::DiffuseTexturePath, fullPath); + data.SetParameter(MaterialData::DiffuseTexturePath, fullPath.generic_u8string()); } - if (!mtlMat->emissiveMap.IsEmpty()) + if (!mtlMat->emissiveMap.empty()) { - String fullPath = mtlMat->emissiveMap; - if (!Nz::File::IsAbsolute(fullPath)) - fullPath.Prepend(baseDir); + std::filesystem::path fullPath = mtlMat->emissiveMap; + if (!fullPath.is_absolute()) + fullPath = baseDir / fullPath; - data.SetParameter(MaterialData::EmissiveTexturePath, fullPath); + data.SetParameter(MaterialData::EmissiveTexturePath, fullPath.generic_u8string()); } - if (!mtlMat->normalMap.IsEmpty()) + if (!mtlMat->normalMap.empty()) { - String fullPath = mtlMat->normalMap; - if (!Nz::File::IsAbsolute(fullPath)) - fullPath.Prepend(baseDir); + std::filesystem::path fullPath = mtlMat->normalMap; + if (!fullPath.is_absolute()) + fullPath = baseDir / fullPath; - data.SetParameter(MaterialData::NormalTexturePath, fullPath); + data.SetParameter(MaterialData::NormalTexturePath, fullPath.generic_u8string()); } - if (!mtlMat->specularMap.IsEmpty()) + if (!mtlMat->specularMap.empty()) { - String fullPath = mtlMat->specularMap; - if (!Nz::File::IsAbsolute(fullPath)) - fullPath.Prepend(baseDir); + std::filesystem::path fullPath = mtlMat->specularMap; + if (!fullPath.is_absolute()) + fullPath = baseDir / fullPath; - data.SetParameter(MaterialData::SpecularTexturePath, fullPath); + data.SetParameter(MaterialData::SpecularTexturePath, fullPath.generic_u8string()); } // If we either have an alpha value or an alpha map, let's configure the material for transparency - if (alphaValue != 255 || !mtlMat->alphaMap.IsEmpty()) + if (alphaValue != 255 || !mtlMat->alphaMap.empty()) { // Some default settings data.SetParameter(MaterialData::Blending, true); @@ -169,27 +169,27 @@ namespace Nz MeshRef mesh = Mesh::New(); mesh->CreateStatic(); - const String* materials = parser.GetMaterials(); + const std::string* materials = parser.GetMaterials(); const Vector4f* positions = parser.GetPositions(); const Vector3f* normals = parser.GetNormals(); const Vector3f* texCoords = parser.GetTexCoords(); const OBJParser::Mesh* meshes = parser.GetMeshes(); - UInt32 meshCount = parser.GetMeshCount(); + std::size_t meshCount = parser.GetMeshCount(); NazaraAssert(materials != nullptr && positions != nullptr && normals != nullptr && texCoords != nullptr && meshes != nullptr && meshCount > 0, "Invalid OBJParser output"); // Un conteneur temporaire pour contenir les indices de face avant triangulation - std::vector faceIndices(3); // Comme il y aura au moins trois sommets - for (UInt32 i = 0; i < meshCount; ++i) + std::vector faceIndices(3); // Comme il y aura au moins trois sommets + for (std::size_t i = 0; i < meshCount; ++i) { std::size_t faceCount = meshes[i].faces.size(); if (faceCount == 0) continue; - std::vector indices; + std::vector indices; indices.reserve(faceCount*3); // Pire cas si les faces sont des triangles // Afin d'utiliser OBJParser::FaceVertex comme clé dans un unordered_map, @@ -226,10 +226,10 @@ namespace Nz unsigned int vertexCount = 0; for (unsigned int j = 0; j < faceCount; ++j) { - UInt32 faceVertexCount = meshes[i].faces[j].vertexCount; + std::size_t faceVertexCount = meshes[i].faces[j].vertexCount; faceIndices.resize(faceVertexCount); - for (UInt32 k = 0; k < faceVertexCount; ++k) + for (std::size_t k = 0; k < faceVertexCount; ++k) { const OBJParser::FaceVertex& vertex = meshes[i].vertices[meshes[i].faces[j].firstVertex + k]; @@ -241,7 +241,7 @@ namespace Nz } // Triangulation - for (UInt32 k = 1; k < faceVertexCount-1; ++k) + for (std::size_t k = 1; k < faceVertexCount-1; ++k) { indices.push_back(faceIndices[0]); indices.push_back(faceIndices[k]); @@ -250,13 +250,13 @@ namespace Nz } // Création des buffers - IndexBufferRef indexBuffer = IndexBuffer::New(vertexCount > std::numeric_limits::max(), UInt32(indices.size()), parameters.storage, parameters.indexBufferFlags); - VertexBufferRef vertexBuffer = VertexBuffer::New(parameters.vertexDeclaration, UInt32(vertexCount), parameters.storage, parameters.vertexBufferFlags); + IndexBufferRef indexBuffer = IndexBuffer::New(vertexCount > std::numeric_limits::max(), std::size_t(indices.size()), parameters.storage, parameters.indexBufferFlags); + VertexBufferRef vertexBuffer = VertexBuffer::New(parameters.vertexDeclaration, std::size_t(vertexCount), parameters.storage, parameters.vertexBufferFlags); // Remplissage des indices IndexMapper indexMapper(indexBuffer, BufferAccess_WriteOnly); for (std::size_t j = 0; j < indices.size(); ++j) - indexMapper.Set(j, indices[j]); + indexMapper.Set(j, UInt32(indices[j])); indexMapper.Unmap(); // Pour laisser les autres tâches affecter l'index buffer @@ -337,11 +337,11 @@ namespace Nz mesh->Recenter(); // On charge les matériaux si demandé - String mtlLib = parser.GetMtlLib(); - if (!mtlLib.IsEmpty()) + std::filesystem::path mtlLib = parser.GetMtlLib(); + if (!mtlLib.empty()) { ErrorFlags flags(ErrorFlag_ThrowExceptionDisabled); - ParseMTL(mesh, stream.GetDirectory() + mtlLib, materials, meshes, meshCount); + ParseMTL(mesh, stream.GetDirectory() / mtlLib, materials, meshes, meshCount); } return mesh; diff --git a/src/Nazara/Utility/Formats/OBJParser.cpp b/src/Nazara/Utility/Formats/OBJParser.cpp index b4766fc56..03cf494fa 100644 --- a/src/Nazara/Utility/Formats/OBJParser.cpp +++ b/src/Nazara/Utility/Formats/OBJParser.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -45,32 +46,29 @@ namespace Nz case 'o': //< Object (defines a mesh) case 's': //< Smooth { - if (m_currentLine.GetSize() > 1 && m_currentLine[1] == ' ') + if (m_currentLine.size() > 1 && m_currentLine[1] == ' ') return true; break; } case 'm': //< MTLLib - if (m_currentLine.GetWord(0).ToLower() == "mtllib") + if (StartsWith(m_currentLine, "mtllib ")) return true; break; case 'u': //< Usemtl - if (m_currentLine.GetWord(0).ToLower() == "usemtl") + if (StartsWith(m_currentLine, "usemtl ")) return true; break; case 'v': //< Position/Normal/Texcoords { - String word = m_currentLine.GetWord(0).ToLower(); - if (word == 'v') - return true; - else if (word == "vn") - return true; - else if (word == "vt") + if (StartsWith(m_currentLine, "v ") || + StartsWith(m_currentLine, "vn ") || + StartsWith(m_currentLine, "vt ")) return true; break; @@ -87,7 +85,7 @@ namespace Nz return false; } - bool OBJParser::Parse(Nz::Stream& stream, UInt32 reservedVertexCount) + bool OBJParser::Parse(Nz::Stream& stream, std::size_t reservedVertexCount) { m_currentStream = &stream; m_errorCount = 0; @@ -106,10 +104,10 @@ namespace Nz }); } - String matName, meshName; + std::string matName, meshName; matName = meshName = "default"; m_meshes.clear(); - m_mtlLib.Clear(); + m_mtlLib.clear(); m_normals.clear(); m_positions.clear(); @@ -122,12 +120,12 @@ namespace Nz // Sort meshes by material and group using MatPair = std::pair; - std::unordered_map> meshesByName; + std::unordered_map> meshesByName; UInt32 faceReserve = 0; UInt32 vertexReserve = 0; unsigned int matCount = 0; - auto GetMaterial = [&] (const String& mesh, const String& mat) -> Mesh* + auto GetMaterial = [&] (const std::string& mesh, const std::string& mat) -> Mesh* { auto& map = meshesByName[mesh]; auto it = map.find(mat); @@ -154,22 +152,22 @@ namespace Nz case '#': //< Comment // Some softwares write comments to gives the number of vertex/faces an importer can expect unsigned int data; - if (std::sscanf(m_currentLine.GetConstBuffer(), "# position count: %u", &data) == 1) + if (std::sscanf(m_currentLine.data(), "# position count: %u", &data) == 1) m_positions.reserve(data); - else if (std::sscanf(m_currentLine.GetConstBuffer(), "# normal count: %u", &data) == 1) + else if (std::sscanf(m_currentLine.data(), "# normal count: %u", &data) == 1) m_normals.reserve(data); - else if (std::sscanf(m_currentLine.GetConstBuffer(), "# texcoords count: %u", &data) == 1) + else if (std::sscanf(m_currentLine.data(), "# texcoords count: %u", &data) == 1) m_texCoords.reserve(data); - else if (std::sscanf(m_currentLine.GetConstBuffer(), "# face count: %u", &data) == 1) + else if (std::sscanf(m_currentLine.data(), "# face count: %u", &data) == 1) faceReserve = data; - else if (std::sscanf(m_currentLine.GetConstBuffer(), "# vertex count: %u", &data) == 1) + else if (std::sscanf(m_currentLine.data(), "# vertex count: %u", &data) == 1) vertexReserve = data; break; case 'f': //< Face { - if (m_currentLine.GetSize() < 7) // Since we only treat triangles, this is the minimum length of a face line (f 1 2 3) + if (m_currentLine.size() < 7) // Since we only treat triangles, this is the minimum length of a face line (f 1 2 3) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!UnrecognizedLine()) @@ -178,7 +176,7 @@ namespace Nz break; } - unsigned int vertexCount = m_currentLine.Count(' '); + std::size_t vertexCount = std::count(m_currentLine.begin(), m_currentLine.end(), ' '); if (vertexCount < 3) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING @@ -192,8 +190,8 @@ namespace Nz currentMesh = GetMaterial(meshName, matName); Face face; - face.firstVertex = static_cast(currentMesh->vertices.size()); - face.vertexCount = static_cast(vertexCount); + face.firstVertex = currentMesh->vertices.size(); + face.vertexCount = vertexCount; currentMesh->vertices.resize(face.firstVertex + vertexCount, FaceVertex{0, 0, 0}); @@ -230,7 +228,7 @@ namespace Nz p += static_cast(m_positions.size()); if (p < 0) { - Error("Vertex index out of range (" + String::Number(p) + " < 0"); + Error("Vertex index out of range (" + std::to_string(p) + " < 0"); error = true; break; } @@ -243,7 +241,7 @@ namespace Nz n += static_cast(m_normals.size()); if (n < 0) { - Error("Normal index out of range (" + String::Number(n) + " < 0"); + Error("Normal index out of range (" + std::to_string(n) + " < 0"); error = true; break; } @@ -256,7 +254,7 @@ namespace Nz t += static_cast(m_texCoords.size()); if (t < 0) { - Error("Texture coordinates index out of range (" + String::Number(t) + " < 0"); + Error("Texture coordinates index out of range (" + std::to_string(t) + " < 0"); error = true; break; } @@ -266,19 +264,19 @@ namespace Nz if (static_cast(p) > m_positions.size()) { - Error("Vertex index out of range (" + String::Number(p) + " >= " + String::Number(m_positions.size()) + ')'); + Error("Vertex index out of range (" + std::to_string(p) + " >= " + std::to_string(m_positions.size()) + ')'); error = true; break; } else if (n != 0 && static_cast(n) > m_normals.size()) { - Error("Normal index out of range (" + String::Number(n) + " >= " + String::Number(m_normals.size()) + ')'); + Error("Normal index out of range (" + std::to_string(n) + " >= " + std::to_string(m_normals.size()) + ')'); error = true; break; } else if (t != 0 && static_cast(t) > m_texCoords.size()) { - Error("TexCoord index out of range (" + String::Number(t) + " >= " + String::Number(m_texCoords.size()) + ')'); + Error("TexCoord index out of range (" + std::to_string(t) + " >= " + std::to_string(m_texCoords.size()) + ')'); error = true; break; } @@ -299,29 +297,36 @@ namespace Nz } case 'm': //< MTLLib - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - if (m_currentLine.GetWord(0).ToLower() != "mtllib") + { + const char prefix[] = "mtllib "; + if (!StartsWith(m_currentLine, prefix)) + { +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!UnrecognizedLine()) return false; - #endif +#endif - m_mtlLib = m_currentLine.SubString(m_currentLine.GetWordPosition(1)); + break; + } + + m_mtlLib = m_currentLine.substr(sizeof(prefix) - 1); break; + } case 'g': //< Group (inside a mesh) case 'o': //< Object (defines a mesh) { - if (m_currentLine.GetSize() <= 2 || m_currentLine[1] != ' ') + if (m_currentLine.size() <= 2 || m_currentLine[1] != ' ') { - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!UnrecognizedLine()) return false; - #endif +#endif break; } - String objectName = m_currentLine.SubString(m_currentLine.GetWordPosition(1)); - if (objectName.IsEmpty()) + std::string objectName = m_currentLine.substr(2); + if (objectName.empty()) { #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!UnrecognizedLine()) @@ -335,12 +340,12 @@ namespace Nz break; } - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING case 's': //< Smooth - if (m_currentLine.GetSize() <= 2 || m_currentLine[1] == ' ') + if (m_currentLine.size() <= 2 || m_currentLine[1] == ' ') { - String param = m_currentLine.SubString(2); - if (param != "all" && param != "on" && param != "off" && !param.IsNumber()) + std::string param = m_currentLine.substr(2); + if (param != "all" && param != "on" && param != "off" && !IsNumber(param)) { if (!UnrecognizedLine()) return false; @@ -349,33 +354,51 @@ namespace Nz else if (!UnrecognizedLine()) return false; break; - #endif +#endif case 'u': //< Usemtl - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING - if (m_currentLine.GetWord(0) != "usemtl" && !UnrecognizedLine()) - return false; - #endif - - matName = m_currentLine.SubString(m_currentLine.GetWordPosition(1)); - currentMesh = nullptr; - if (matName.IsEmpty()) + { + const char prefix[] = "usemtl "; + if (!StartsWith(m_currentLine, prefix)) { - #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING if (!UnrecognizedLine()) return false; - #endif +#endif + break; } + + std::string newMatName = m_currentLine.substr(sizeof(prefix) - 1); + if (newMatName.empty()) + { +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + if (!UnrecognizedLine()) + return false; +#endif + break; + } + + matName = std::move(newMatName); + currentMesh = nullptr; break; + } case 'v': //< Position/Normal/Texcoords { - String word = m_currentLine.GetWord(0).ToLower(); - if (word == 'v') + if (m_currentLine.size() < 7) + { +#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING + if (!UnrecognizedLine()) + return false; +#endif + break; + } + + if (std::isspace(m_currentLine[1])) { Vector4f vertex(Vector3f::Zero(), 1.f); - unsigned int paramCount = std::sscanf(&m_currentLine[2], "%f %f %f %f", &vertex.x, &vertex.y, &vertex.z, &vertex.w); + unsigned int paramCount = std::sscanf(&m_currentLine[2], " %f %f %f %f", &vertex.x, &vertex.y, &vertex.z, &vertex.w); if (paramCount >= 1) m_positions.push_back(vertex); #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING @@ -383,10 +406,10 @@ namespace Nz return false; #endif } - else if (word == "vn") + else if (m_currentLine[1] == 'n' && std::isspace(m_currentLine[2])) { Vector3f normal(Vector3f::Zero()); - unsigned int paramCount = std::sscanf(&m_currentLine[3], "%f %f %f", &normal.x, &normal.y, &normal.z); + unsigned int paramCount = std::sscanf(&m_currentLine[3], " %f %f %f", &normal.x, &normal.y, &normal.z); if (paramCount == 3) m_normals.push_back(normal); #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING @@ -394,10 +417,10 @@ namespace Nz return false; #endif } - else if (word == "vt") + else if (m_currentLine[1] == 't' && std::isspace(m_currentLine[2])) { Vector3f uvw(Vector3f::Zero()); - unsigned int paramCount = std::sscanf(&m_currentLine[3], "%f %f %f", &uvw.x, &uvw.y, &uvw.z); + unsigned int paramCount = std::sscanf(&m_currentLine[3], " %f %f %f", &uvw.x, &uvw.y, &uvw.z); if (paramCount >= 2) m_texCoords.push_back(uvw); #if NAZARA_UTILITY_STRICT_RESOURCE_PARSING @@ -422,7 +445,7 @@ namespace Nz } } - std::unordered_map materials; + std::unordered_map materials; m_materials.resize(matCount); for (auto& meshPair : meshesByName) @@ -480,10 +503,10 @@ namespace Nz EmitLine("# Exported by Nazara Engine"); EmitLine(); - if (!m_mtlLib.IsEmpty()) + if (!m_mtlLib.empty()) { Emit("mtllib "); - EmitLine(m_mtlLib); + EmitLine(m_mtlLib.generic_u8string()); EmitLine(); } @@ -617,12 +640,18 @@ namespace Nz m_lineCount++; m_currentLine = m_currentStream->ReadLine(); - if (m_currentLine.IsEmpty()) - continue; + if (std::size_t p = m_currentLine.find('#'); p != m_currentLine.npos) + { + if (p > 0) + m_currentLine = m_currentLine.substr(0, p - 1); + else + m_currentLine.clear(); + } - m_currentLine.Simplify(); // Simplify lines (convert multiple blanks into a single space and trims) + if (m_currentLine.empty()) + continue; } - while (m_currentLine.IsEmpty()); + while (m_currentLine.empty()); } else m_keepLastLine = false; diff --git a/src/Nazara/Utility/Formats/OBJSaver.cpp b/src/Nazara/Utility/Formats/OBJSaver.cpp index 74585971d..d363bbe67 100644 --- a/src/Nazara/Utility/Formats/OBJSaver.cpp +++ b/src/Nazara/Utility/Formats/OBJSaver.cpp @@ -2,7 +2,6 @@ // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp -#include #include #include #include @@ -28,12 +27,12 @@ namespace Nz { } - UInt32 GetCount() const + std::size_t GetCount() const { return m_count; } - UInt32 Insert(const T& data) + std::size_t Insert(const T& data) { auto it = m_cache.find(data); if (it == m_cache.end()) @@ -47,17 +46,17 @@ namespace Nz } private: - UInt32 m_count; - std::map m_cache; + std::size_t m_count; + std::map m_cache; T* m_buffer; }; - bool IsSupported(const String& extension) + bool IsSupported(const std::string& extension) { return (extension == "obj"); } - bool SaveToStream(const Mesh& mesh, const String& format, Stream& stream, const MeshParams& parameters) + bool SaveToStream(const Mesh& mesh, const std::string& format, Stream& stream, const MeshParams& parameters) { NazaraUnused(parameters); @@ -73,18 +72,18 @@ namespace Nz return false; } - UInt32 worstCacheVertexCount = mesh.GetVertexCount(); + std::size_t worstCacheVertexCount = mesh.GetVertexCount(); OBJParser objFormat; objFormat.SetNormalCount(worstCacheVertexCount); objFormat.SetPositionCount(worstCacheVertexCount); objFormat.SetTexCoordCount(worstCacheVertexCount); - String mtlPath = stream.GetPath(); - if (!mtlPath.IsEmpty()) + std::filesystem::path mtlPath = stream.GetPath(); + if (!mtlPath.empty()) { - mtlPath.Replace(".obj", ".mtl"); - String fileName = mtlPath.SubStringFrom(NAZARA_DIRECTORY_SEPARATOR, -1, true); - if (!fileName.IsEmpty()) + mtlPath.replace_extension(".mtl"); + std::filesystem::path fileName = mtlPath.filename(); + if (!fileName.empty()) objFormat.SetMtlLib(fileName); } @@ -94,17 +93,20 @@ namespace Nz // Materials MTLParser mtlFormat; - std::unordered_set registredMaterials; + std::unordered_set registredMaterials; - UInt32 matCount = mesh.GetMaterialCount(); - String* materialNames = objFormat.SetMaterialCount(matCount); - for (UInt32 i = 0; i < matCount; ++i) + std::size_t matCount = mesh.GetMaterialCount(); + std::string* materialNames = objFormat.SetMaterialCount(matCount); + for (std::size_t i = 0; i < matCount; ++i) { const ParameterList& matData = mesh.GetMaterialData(i); - String name; - if (!matData.GetStringParameter(MaterialData::Name, &name)) - name = "material_" + String::Number(i); + String nzname; + std::string name; + if (matData.GetStringParameter(MaterialData::Name, &nzname)) + name = nzname.ToStdString(); + else + name = "material_" + std::to_string(i); // Makes sure we only have one material of that name while (registredMaterials.find(name) != registredMaterials.end()) @@ -117,7 +119,7 @@ namespace Nz String strVal; if (matData.GetStringParameter(MaterialData::FilePath, &strVal)) - material->diffuseMap = strVal; + material->diffuseMap = strVal.ToStdString(); else { Color colorVal; @@ -136,28 +138,28 @@ namespace Nz material->shininess = float(dValue); if (matData.GetStringParameter(MaterialData::AlphaTexturePath, &strVal)) - material->alphaMap = strVal; + material->alphaMap = strVal.ToStdString(); if (matData.GetStringParameter(MaterialData::DiffuseTexturePath, &strVal)) - material->diffuseMap = strVal; + material->diffuseMap = strVal.ToStdString(); if (matData.GetStringParameter(MaterialData::SpecularTexturePath, &strVal)) - material->specularMap = strVal; + material->specularMap = strVal.ToStdString(); } } // Meshes - UInt32 meshCount = mesh.GetSubMeshCount(); + std::size_t meshCount = mesh.GetSubMeshCount(); OBJParser::Mesh* meshes = objFormat.SetMeshCount(meshCount); - for (UInt32 i = 0; i < meshCount; ++i) + for (std::size_t i = 0; i < meshCount; ++i) { const StaticMesh* staticMesh = static_cast(mesh.GetSubMesh(i)); - UInt32 triangleCount = staticMesh->GetTriangleCount(); + std::size_t triangleCount = staticMesh->GetTriangleCount(); meshes[i].faces.resize(triangleCount); meshes[i].material = staticMesh->GetMaterialIndex(); - meshes[i].name = "mesh_" + String::Number(i); + meshes[i].name = "mesh_" + std::to_string(i); meshes[i].vertices.resize(triangleCount * 3); { @@ -167,7 +169,7 @@ namespace Nz SparsePtr positionPtr = vertexMapper.GetComponentPtr(VertexComponent_Position); SparsePtr texCoordsPtr = vertexMapper.GetComponentPtr(VertexComponent_TexCoord); - UInt32 faceIndex = 0; + std::size_t faceIndex = 0; TriangleIterator triangle(staticMesh); do { @@ -179,7 +181,7 @@ namespace Nz { OBJParser::FaceVertex& vertexIndices = meshes[i].vertices[face.firstVertex + j]; - UInt32 index = triangle[j]; + std::size_t index = triangle[j]; vertexIndices.normal = normalCache.Insert(normalPtr[index]); vertexIndices.position = positionCache.Insert(positionPtr[index]); vertexIndices.texCoord = texCoordsCache.Insert(texCoordsPtr[index]); @@ -197,7 +199,7 @@ namespace Nz objFormat.Save(stream); - if (!mtlPath.IsEmpty()) + if (!mtlPath.empty()) { File mtlFile(mtlPath, OpenMode_WriteOnly | OpenMode_Truncate); if (mtlFile.IsOpen()) diff --git a/src/Nazara/Utility/Formats/PCXLoader.cpp b/src/Nazara/Utility/Formats/PCXLoader.cpp index 5de1aa29d..75016cd2c 100644 --- a/src/Nazara/Utility/Formats/PCXLoader.cpp +++ b/src/Nazara/Utility/Formats/PCXLoader.cpp @@ -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"); - bool IsSupported(const String& extension) + bool IsSupported(const std::string& extension) { return (extension == "pcx"); } diff --git a/src/Nazara/Utility/Formats/STBLoader.cpp b/src/Nazara/Utility/Formats/STBLoader.cpp index 132886175..26836c057 100644 --- a/src/Nazara/Utility/Formats/STBLoader.cpp +++ b/src/Nazara/Utility/Formats/STBLoader.cpp @@ -36,7 +36,7 @@ namespace Nz static stbi_io_callbacks callbacks = {Read, Skip, Eof}; - bool IsSupported(const String& extension) + bool IsSupported(const std::string& extension) { static std::set supportedExtensions = {"bmp", "gif", "hdr", "jpg", "jpeg", "pic", "png", "ppm", "pgm", "psd", "tga"}; return supportedExtensions.find(extension) != supportedExtensions.end(); diff --git a/src/Nazara/Utility/Formats/STBSaver.cpp b/src/Nazara/Utility/Formats/STBSaver.cpp index bc8d7d7ac..effb8b921 100644 --- a/src/Nazara/Utility/Formats/STBSaver.cpp +++ b/src/Nazara/Utility/Formats/STBSaver.cpp @@ -15,7 +15,7 @@ namespace Nz { using FormatHandler = bool(*)(const Image& image, const ImageParams& parameters, Stream& stream); - std::map s_formatHandlers; + std::map s_formatHandlers; int ConvertToFloatFormat(Image& image) { @@ -102,12 +102,12 @@ namespace Nz throw std::runtime_error("Failed to write to stream"); } - bool FormatQuerier(const String& extension) + bool FormatQuerier(const std::string& extension) { return s_formatHandlers.find(extension) != s_formatHandlers.end(); } - bool SaveToStream(const Image& image, const String& format, Stream& stream, const ImageParams& parameters) + bool SaveToStream(const Image& image, const std::string& format, Stream& stream, const ImageParams& parameters) { NazaraUnused(parameters); diff --git a/src/Nazara/Utility/Image.cpp b/src/Nazara/Utility/Image.cpp index da5ec120c..51443667a 100644 --- a/src/Nazara/Utility/Image.cpp +++ b/src/Nazara/Utility/Image.cpp @@ -850,7 +850,7 @@ namespace Nz } // LoadArray - ImageRef Image::LoadArrayFromFile(const String& filePath, const ImageParams& imageParams, const Vector2ui& atlasSize) + ImageRef Image::LoadArrayFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams, const Vector2ui& atlasSize) { ImageRef image = Image::LoadFromFile(filePath, imageParams); if (!image) @@ -951,7 +951,7 @@ namespace Nz return LoadArrayFromImage(image, atlasSize); } - ImageRef Image::LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams, const CubemapParams& cubemapParams) + ImageRef Image::LoadCubemapFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams, const CubemapParams& cubemapParams) { ImageRef image = Image::LoadFromFile(filePath, imageParams); if (!image) @@ -1074,7 +1074,7 @@ namespace Nz return LoadCubemapFromImage(image, cubemapParams); } - bool Image::LoadFaceFromFile(CubemapFace face, const String& 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"); @@ -1158,12 +1158,12 @@ namespace Nz return true; } - bool Image::SaveToFile(const String& filePath, const ImageParams& params) + bool Image::SaveToFile(const std::filesystem::path& filePath, const ImageParams& params) { return ImageSaver::SaveToFile(*this, filePath, params); } - bool Image::SaveToStream(Stream& stream, const String& format, const ImageParams& params) + bool Image::SaveToStream(Stream& stream, const std::string& format, const ImageParams& params) { return ImageSaver::SaveToStream(*this, stream, format, params); } @@ -1429,7 +1429,7 @@ namespace Nz return 0; } - ImageRef Image::LoadFromFile(const String& filePath, const ImageParams& params) + ImageRef Image::LoadFromFile(const std::filesystem::path& filePath, const ImageParams& params) { return ImageLoader::LoadFromFile(filePath, params); } diff --git a/src/Nazara/Utility/IndexBuffer.cpp b/src/Nazara/Utility/IndexBuffer.cpp index 4455a2f0c..21d1997f0 100644 --- a/src/Nazara/Utility/IndexBuffer.cpp +++ b/src/Nazara/Utility/IndexBuffer.cpp @@ -19,13 +19,13 @@ namespace Nz Reset(largeIndices, std::move(buffer)); } - IndexBuffer::IndexBuffer(bool largeIndices, BufferRef buffer, UInt32 offset, UInt32 size) + IndexBuffer::IndexBuffer(bool largeIndices, BufferRef buffer, std::size_t offset, std::size_t size) { ErrorFlags(ErrorFlag_ThrowException, true); Reset(largeIndices, std::move(buffer), offset, size); } - IndexBuffer::IndexBuffer(bool largeIndices, UInt32 length, DataStorage storage, BufferUsageFlags usage) + IndexBuffer::IndexBuffer(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage) { ErrorFlags(ErrorFlag_ThrowException, true); Reset(largeIndices, length, storage, usage); @@ -53,14 +53,14 @@ namespace Nz return Nz::ComputeCacheMissCount(mapper.begin(), m_indexCount); } - bool IndexBuffer::Fill(const void* data, UInt32 startIndex, UInt32 length) + bool IndexBuffer::Fill(const void* data, std::size_t startIndex, std::size_t length) { - UInt32 stride = GetStride(); + std::size_t stride = GetStride(); return FillRaw(data, startIndex*stride, length*stride); } - bool IndexBuffer::FillRaw(const void* data, UInt32 offset, UInt32 size) + bool IndexBuffer::FillRaw(const void* data, std::size_t offset, std::size_t size) { NazaraAssert(m_buffer && m_buffer->IsValid(), "Invalid buffer"); NazaraAssert(m_startOffset + offset + size <= m_endOffset, "Exceeding virtual buffer size"); @@ -68,7 +68,7 @@ namespace Nz return m_buffer->Fill(data, m_startOffset+offset, size); } - void* IndexBuffer::MapRaw(BufferAccess access, UInt32 offset, UInt32 size) + void* IndexBuffer::MapRaw(BufferAccess access, std::size_t offset, std::size_t size) { NazaraAssert(m_buffer && m_buffer->IsValid(), "Invalid buffer"); NazaraAssert(m_startOffset + offset + size <= m_endOffset, "Exceeding virtual buffer size"); @@ -76,7 +76,7 @@ namespace Nz return m_buffer->Map(access, offset, size); } - void* IndexBuffer::MapRaw(BufferAccess access, UInt32 offset, UInt32 size) const + void* IndexBuffer::MapRaw(BufferAccess access, std::size_t offset, std::size_t size) const { NazaraAssert(m_buffer && m_buffer->IsValid(), "Invalid buffer"); NazaraAssert(m_startOffset + offset + size <= m_endOffset, "Exceeding virtual buffer size"); @@ -103,13 +103,13 @@ namespace Nz Reset(largeIndices, buffer, 0, buffer->GetSize()); } - void IndexBuffer::Reset(bool largeIndices, BufferRef buffer, UInt32 offset, UInt32 size) + void IndexBuffer::Reset(bool largeIndices, BufferRef buffer, std::size_t offset, std::size_t size) { NazaraAssert(buffer && buffer->IsValid(), "Invalid buffer"); NazaraAssert(size > 0, "Invalid size"); NazaraAssert(offset + size > buffer->GetSize(), "Virtual buffer exceed buffer bounds"); - UInt32 stride = static_cast((largeIndices) ? sizeof(UInt32) : sizeof(UInt16)); + std::size_t stride = static_cast((largeIndices) ? sizeof(std::size_t) : sizeof(UInt16)); m_buffer = buffer; m_endOffset = offset + size; @@ -118,9 +118,9 @@ namespace Nz m_startOffset = offset; } - void IndexBuffer::Reset(bool largeIndices, UInt32 length, DataStorage storage, BufferUsageFlags usage) + void IndexBuffer::Reset(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage) { - UInt32 stride = static_cast((largeIndices) ? sizeof(UInt32) : sizeof(UInt16)); + std::size_t stride = static_cast((largeIndices) ? sizeof(std::size_t) : sizeof(UInt16)); m_endOffset = length * stride; m_indexCount = length; diff --git a/src/Nazara/Utility/Mesh.cpp b/src/Nazara/Utility/Mesh.cpp index 890577de4..d2ed17353 100644 --- a/src/Nazara/Utility/Mesh.cpp +++ b/src/Nazara/Utility/Mesh.cpp @@ -71,10 +71,10 @@ namespace Nz InvalidateAABB(); } - void Mesh::AddSubMesh(const String& identifier, SubMesh* subMesh) + void Mesh::AddSubMesh(const std::string& identifier, SubMesh* subMesh) { NazaraAssert(m_isValid, "Mesh should be created first"); - NazaraAssert(!identifier.IsEmpty(), "Identifier is empty"); + NazaraAssert(!identifier.empty(), "Identifier is empty"); NazaraAssert(m_subMeshMap.find(identifier) == m_subMeshMap.end(), "SubMesh identifier \"" + identifier + "\" is already in use"); NazaraAssert(subMesh, "Invalid submesh"); NazaraAssert(subMesh->GetAnimationType() == m_animationType, "Submesh animation type doesn't match mesh animation type"); @@ -83,7 +83,7 @@ namespace Nz AddSubMesh(subMesh); - m_subMeshMap[identifier] = static_cast(index); + m_subMeshMap[identifier] = static_cast(index); } SubMesh* Mesh::BuildSubMesh(const Primitive& primitive, const MeshParams& params) @@ -256,11 +256,11 @@ namespace Nz void Mesh::BuildSubMeshes(const PrimitiveList& list, const MeshParams& params) { - for (UInt32 i = 0; i < list.GetSize(); ++i) + for (std::size_t i = 0; i < list.GetSize(); ++i) BuildSubMesh(list.GetPrimitive(i), params); } - bool Mesh::CreateSkeletal(UInt32 jointCount) + bool Mesh::CreateSkeletal(std::size_t jointCount) { Destroy(); @@ -293,7 +293,7 @@ namespace Nz { OnMeshDestroy(this); - m_animationPath.Clear(); + m_animationPath.clear(); m_materialData.clear(); m_materialData.resize(1); m_skeleton.Destroy(); @@ -350,7 +350,7 @@ namespace Nz return m_aabb; } - String Mesh::GetAnimation() const + std::filesystem::path Mesh::GetAnimation() const { NazaraAssert(m_isValid, "Mesh should be created first"); @@ -364,7 +364,7 @@ namespace Nz return m_animationType; } - UInt32 Mesh::GetJointCount() const + std::size_t Mesh::GetJointCount() const { NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(m_animationType == AnimationType_Skeletal, "Mesh is not skeletal"); @@ -372,7 +372,7 @@ namespace Nz return m_jointCount; } - ParameterList& Mesh::GetMaterialData(UInt32 index) + ParameterList& Mesh::GetMaterialData(std::size_t index) { NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(index < m_materialData.size(), "Material index out of range"); @@ -380,7 +380,7 @@ namespace Nz return m_materialData[index]; } - const ParameterList& Mesh::GetMaterialData(UInt32 index) const + const ParameterList& Mesh::GetMaterialData(std::size_t index) const { NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(index < m_materialData.size(), "Material index out of range"); @@ -388,11 +388,11 @@ namespace Nz return m_materialData[index]; } - UInt32 Mesh::GetMaterialCount() const + std::size_t Mesh::GetMaterialCount() const { NazaraAssert(m_isValid, "Mesh should be created first"); - return static_cast(m_materialData.size()); + return static_cast(m_materialData.size()); } Skeleton* Mesh::GetSkeleton() @@ -411,7 +411,7 @@ namespace Nz return &m_skeleton; } - SubMesh* Mesh::GetSubMesh(const String& identifier) + SubMesh* Mesh::GetSubMesh(const std::string& identifier) { NazaraAssert(m_isValid, "Mesh should be created first"); @@ -421,7 +421,7 @@ namespace Nz return m_subMeshes[it->second].subMesh; } - SubMesh* Mesh::GetSubMesh(UInt32 index) + SubMesh* Mesh::GetSubMesh(std::size_t index) { NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(index < m_subMeshes.size(), "Submesh index out of range"); @@ -429,7 +429,7 @@ namespace Nz return m_subMeshes[index].subMesh; } - const SubMesh* Mesh::GetSubMesh(const String& identifier) const + const SubMesh* Mesh::GetSubMesh(const std::string& identifier) const { NazaraAssert(m_isValid, "Mesh should be created first"); @@ -439,7 +439,7 @@ namespace Nz return m_subMeshes[it->second].subMesh; } - const SubMesh* Mesh::GetSubMesh(UInt32 index) const + const 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"); @@ -447,14 +447,14 @@ namespace Nz return m_subMeshes[index].subMesh; } - UInt32 Mesh::GetSubMeshCount() const + std::size_t Mesh::GetSubMeshCount() const { NazaraAssert(m_isValid, "Mesh should be created first"); - return static_cast(m_subMeshes.size()); + return static_cast(m_subMeshes.size()); } - UInt32 Mesh::GetSubMeshIndex(const String& identifier) const + std::size_t Mesh::GetSubMeshIndex(const std::string& identifier) const { NazaraAssert(m_isValid, "Mesh should be created first"); @@ -464,22 +464,22 @@ namespace Nz return it->second; } - UInt32 Mesh::GetTriangleCount() const + std::size_t Mesh::GetTriangleCount() const { NazaraAssert(m_isValid, "Mesh should be created first"); - UInt32 triangleCount = 0; + std::size_t triangleCount = 0; for (const SubMeshData& data : m_subMeshes) triangleCount += data.subMesh->GetTriangleCount(); return triangleCount; } - UInt32 Mesh::GetVertexCount() const + std::size_t Mesh::GetVertexCount() const { NazaraAssert(m_isValid, "Mesh should be created first"); - UInt32 vertexCount = 0; + std::size_t vertexCount = 0; for (const SubMeshData& data : m_subMeshes) vertexCount += data.subMesh->GetVertexCount(); @@ -495,14 +495,14 @@ namespace Nz OnMeshInvalidateAABB(this); } - bool Mesh::HasSubMesh(const String& identifier) const + bool Mesh::HasSubMesh(const std::string& identifier) const { NazaraAssert(m_isValid, "Mesh should be created first"); return m_subMeshMap.find(identifier) != m_subMeshMap.end(); } - bool Mesh::HasSubMesh(UInt32 index) const + bool Mesh::HasSubMesh(std::size_t index) const { NazaraAssert(m_isValid, "Mesh should be created first"); @@ -536,8 +536,8 @@ namespace Nz BufferMapper mapper(staticMesh.GetVertexBuffer(), BufferAccess_ReadWrite); MeshVertex* vertices = static_cast(mapper.GetPointer()); - UInt32 vertexCount = staticMesh.GetVertexCount(); - for (UInt32 i = 0; i < vertexCount; ++i) + std::size_t vertexCount = staticMesh.GetVertexCount(); + for (std::size_t i = 0; i < vertexCount; ++i) { vertices->position -= center; vertices++; @@ -551,49 +551,47 @@ namespace Nz } } - void Mesh::RemoveSubMesh(const String& identifier) + void Mesh::RemoveSubMesh(const std::string& identifier) { - UInt32 index = GetSubMeshIndex(identifier); - - // On déplace l'itérateur du début d'une distance de x - auto it2 = m_subMeshes.begin(); - std::advance(it2, index); - m_subMeshes.erase(it2); - - InvalidateAABB(); + std::size_t index = GetSubMeshIndex(identifier); + RemoveSubMesh(index); } - void Mesh::RemoveSubMesh(UInt32 index) + void Mesh::RemoveSubMesh(std::size_t index) { NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(index < m_subMeshes.size(), "Submesh index out of range"); - // On déplace l'itérateur du début de x - auto it = m_subMeshes.begin(); - std::advance(it, index); - m_subMeshes.erase(it); + m_subMeshes.erase(m_subMeshes.begin() + index); + + // Shift indices + for (auto& it : m_subMeshMap) + { + if (it.second > index) + it.second--; + } InvalidateAABB(); } - bool Mesh::SaveToFile(const String& filePath, const MeshParams& params) + bool Mesh::SaveToFile(const std::filesystem::path& filePath, const MeshParams& params) { return MeshSaver::SaveToFile(*this, filePath, params); } - bool Mesh::SaveToStream(Stream& stream, const String& format, const MeshParams& params) + bool Mesh::SaveToStream(Stream& stream, const std::string& format, const MeshParams& params) { return MeshSaver::SaveToStream(*this, stream, format, params); } - void Mesh::SetAnimation(const String& animationPath) + void Mesh::SetAnimation(const std::filesystem::path& animationPath) { NazaraAssert(m_isValid, "Mesh should be created first"); m_animationPath = animationPath; } - void Mesh::SetMaterialData(UInt32 matIndex, ParameterList data) + void Mesh::SetMaterialData(std::size_t matIndex, ParameterList data) { NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(matIndex < m_materialData.size(), "Material index out of range"); @@ -601,7 +599,7 @@ namespace Nz m_materialData[matIndex] = std::move(data); } - void Mesh::SetMaterialCount(UInt32 matCount) + void Mesh::SetMaterialCount(std::size_t matCount) { NazaraAssert(m_isValid, "Mesh should be created first"); NazaraAssert(matCount > 0, "A mesh should have at least a material"); @@ -611,7 +609,7 @@ namespace Nz #ifdef NAZARA_DEBUG for (SubMeshData& data : m_subMeshes) { - UInt32 matIndex = data.subMesh->GetMaterialIndex(); + std::size_t matIndex = data.subMesh->GetMaterialIndex(); if (matIndex >= matCount) { data.subMesh->SetMaterialIndex(0); // To prevent a crash @@ -635,8 +633,8 @@ namespace Nz Boxf aabb(vertices->position.x, vertices->position.y, vertices->position.z, 0.f, 0.f, 0.f); - UInt32 vertexCount = staticMesh.GetVertexCount(); - for (UInt32 i = 0; i < vertexCount; ++i) + std::size_t vertexCount = staticMesh.GetVertexCount(); + for (std::size_t i = 0; i < vertexCount; ++i) { vertices->position = matrix.Transform(vertices->position); aabb.ExtendTo(vertices->position); @@ -648,7 +646,7 @@ namespace Nz } } - MeshRef Mesh::LoadFromFile(const String& filePath, const MeshParams& params) + MeshRef Mesh::LoadFromFile(const std::filesystem::path& filePath, const MeshParams& params) { return MeshLoader::LoadFromFile(filePath, params); } diff --git a/src/Nazara/Utility/SkeletalMesh.cpp b/src/Nazara/Utility/SkeletalMesh.cpp index e5a3a3268..7b8bc6a78 100644 --- a/src/Nazara/Utility/SkeletalMesh.cpp +++ b/src/Nazara/Utility/SkeletalMesh.cpp @@ -80,7 +80,7 @@ namespace Nz return m_vertexBuffer; } - unsigned int SkeletalMesh::GetVertexCount() const + std::size_t SkeletalMesh::GetVertexCount() const { return m_vertexBuffer->GetVertexCount(); } diff --git a/src/Nazara/Utility/Skeleton.cpp b/src/Nazara/Utility/Skeleton.cpp index 45958980f..21e0596b7 100644 --- a/src/Nazara/Utility/Skeleton.cpp +++ b/src/Nazara/Utility/Skeleton.cpp @@ -11,7 +11,7 @@ namespace Nz { struct SkeletonImpl { - std::unordered_map jointMap; + std::unordered_map jointMap; std::vector joints; Boxf aabb; bool aabbUpdated = false; @@ -32,7 +32,7 @@ namespace Nz Destroy(); } - bool Skeleton::Create(UInt32 jointCount) + bool Skeleton::Create(std::size_t jointCount) { #if NAZARA_UTILITY_SAFE if (jointCount == 0) @@ -118,7 +118,7 @@ namespace Nz return &m_impl->joints[it->second]; } - Joint* Skeleton::GetJoint(UInt32 index) + Joint* Skeleton::GetJoint(std::size_t index) { #if NAZARA_UTILITY_SAFE if (!m_impl) @@ -165,7 +165,7 @@ namespace Nz return &m_impl->joints[it->second]; } - const Joint* Skeleton::GetJoint(UInt32 index) const + const Joint* Skeleton::GetJoint(std::size_t index) const { #if NAZARA_UTILITY_SAFE if (!m_impl) @@ -210,7 +210,7 @@ namespace Nz return &m_impl->joints[0]; } - UInt32 Skeleton::GetJointCount() const + std::size_t Skeleton::GetJointCount() const { #if NAZARA_UTILITY_SAFE if (!m_impl) @@ -220,7 +220,7 @@ namespace Nz } #endif - return static_cast(m_impl->joints.size()); + return static_cast(m_impl->joints.size()); } int Skeleton::GetJointIndex(const String& jointName) const @@ -285,7 +285,7 @@ namespace Nz InvalidateJoints(); } - void Skeleton::Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation, UInt32* indices, UInt32 indiceCount) + void Skeleton::Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation, std::size_t* indices, std::size_t indiceCount) { #if NAZARA_UTILITY_SAFE if (!m_impl) @@ -315,9 +315,9 @@ namespace Nz const Joint* jointsA = &skeletonA.m_impl->joints[0]; const Joint* jointsB = &skeletonB.m_impl->joints[0]; - for (UInt32 i = 0; i < indiceCount; ++i) + for (std::size_t i = 0; i < indiceCount; ++i) { - UInt32 index = indices[i]; + std::size_t index = indices[i]; #if NAZARA_UTILITY_SAFE if (index >= m_impl->joints.size()) @@ -352,7 +352,7 @@ namespace Nz m_impl->jointMapUpdated = skeleton.m_impl->jointMapUpdated; m_impl->joints = skeleton.m_impl->joints; - // Code crade mais son optimisation demanderait de stocker jointCount*sizeof(UInt32) en plus + // Code crade mais son optimisation demanderait de stocker jointCount*sizeof(std::size_t) en plus // Ce qui, pour juste une copie qui ne se fera que rarement, ne vaut pas le coup // L'éternel trade-off mémoire/calculs .. std::size_t jointCount = skeleton.m_impl->joints.size(); @@ -414,7 +414,7 @@ namespace Nz { NazaraAssert(m_impl->jointMap.find(name) == m_impl->jointMap.end(), "Joint name \"" + name + "\" is already present in joint map"); - m_impl->jointMap[name] = static_cast(i); + m_impl->jointMap[name] = static_cast(i); } } diff --git a/src/Nazara/Utility/StaticMesh.cpp b/src/Nazara/Utility/StaticMesh.cpp index b363736f7..38de3c033 100644 --- a/src/Nazara/Utility/StaticMesh.cpp +++ b/src/Nazara/Utility/StaticMesh.cpp @@ -107,7 +107,7 @@ namespace Nz return m_vertexBuffer; } - unsigned int StaticMesh::GetVertexCount() const + std::size_t StaticMesh::GetVertexCount() const { return m_vertexBuffer->GetVertexCount(); } diff --git a/src/Nazara/Utility/SubMesh.cpp b/src/Nazara/Utility/SubMesh.cpp index 0b7a95b31..b10c42992 100644 --- a/src/Nazara/Utility/SubMesh.cpp +++ b/src/Nazara/Utility/SubMesh.cpp @@ -32,14 +32,14 @@ namespace Nz void SubMesh::GenerateNormals() { VertexMapper mapper(this); - UInt32 vertexCount = mapper.GetVertexCount(); + std::size_t vertexCount = mapper.GetVertexCount(); SparsePtr normals = mapper.GetComponentPtr(VertexComponent_Normal); SparsePtr positions = mapper.GetComponentPtr(VertexComponent_Position); if (!normals || !positions) return; - for (UInt32 i = 0; i < vertexCount; ++i) + for (std::size_t i = 0; i < vertexCount; ++i) normals[i].MakeZero(); TriangleIterator iterator(this); @@ -58,14 +58,14 @@ namespace Nz } while (iterator.Advance()); - for (UInt32 i = 0; i < vertexCount; ++i) + for (std::size_t i = 0; i < vertexCount; ++i) normals[i].Normalize(); } void SubMesh::GenerateNormalsAndTangents() { VertexMapper mapper(this); - UInt32 vertexCount = mapper.GetVertexCount(); + std::size_t vertexCount = mapper.GetVertexCount(); SparsePtr normals = mapper.GetComponentPtr(VertexComponent_Normal); SparsePtr positions = mapper.GetComponentPtr(VertexComponent_Position); @@ -74,7 +74,7 @@ namespace Nz if (!normals || !positions || !tangents || !texCoords) return; - for (UInt32 i = 0; i < vertexCount; ++i) + for (std::size_t i = 0; i < vertexCount; ++i) { normals[i].MakeZero(); tangents[i].MakeZero(); @@ -169,10 +169,10 @@ namespace Nz return m_primitiveMode; } - unsigned int SubMesh::GetTriangleCount() const + std::size_t SubMesh::GetTriangleCount() const { const IndexBuffer* indexBuffer = GetIndexBuffer(); - unsigned int indexCount; + std::size_t indexCount; if (indexBuffer) indexCount = indexBuffer->GetIndexCount(); else @@ -199,7 +199,7 @@ namespace Nz return 0; } - UInt32 SubMesh::GetMaterialIndex() const + std::size_t SubMesh::GetMaterialIndex() const { return m_matIndex; } @@ -209,7 +209,7 @@ namespace Nz m_primitiveMode = mode; } - void SubMesh::SetMaterialIndex(UInt32 matIndex) + void SubMesh::SetMaterialIndex(std::size_t matIndex) { m_matIndex = matIndex; } diff --git a/src/Nazara/Utility/VertexBuffer.cpp b/src/Nazara/Utility/VertexBuffer.cpp index e072c4aa1..2e2e22e21 100644 --- a/src/Nazara/Utility/VertexBuffer.cpp +++ b/src/Nazara/Utility/VertexBuffer.cpp @@ -15,13 +15,13 @@ namespace Nz Reset(std::move(vertexDeclaration), std::move(buffer)); } - VertexBuffer::VertexBuffer(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, UInt32 offset, UInt32 size) + VertexBuffer::VertexBuffer(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, std::size_t offset, std::size_t size) { ErrorFlags(ErrorFlag_ThrowException, true); Reset(std::move(vertexDeclaration), std::move(buffer), offset, size); } - VertexBuffer::VertexBuffer(VertexDeclarationConstRef vertexDeclaration, UInt32 length, DataStorage storage, BufferUsageFlags usage) + VertexBuffer::VertexBuffer(VertexDeclarationConstRef vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage) { ErrorFlags(ErrorFlag_ThrowException, true); Reset(std::move(vertexDeclaration), length, storage, usage); @@ -42,13 +42,13 @@ namespace Nz OnVertexBufferRelease(this); } - bool VertexBuffer::Fill(const void* data, UInt32 startVertex, UInt32 length) + bool VertexBuffer::Fill(const void* data, std::size_t startVertex, std::size_t length) { - UInt32 stride = static_cast(m_vertexDeclaration->GetStride()); + std::size_t stride = static_cast(m_vertexDeclaration->GetStride()); return FillRaw(data, startVertex*stride, length*stride); } - bool VertexBuffer::FillRaw(const void* data, UInt32 offset, UInt32 size) + bool VertexBuffer::FillRaw(const void* data, std::size_t offset, std::size_t size) { NazaraAssert(m_buffer && m_buffer->IsValid(), "Invalid buffer"); NazaraAssert(m_startOffset + offset + size <= m_endOffset, "Exceeding virtual buffer size"); @@ -56,24 +56,24 @@ namespace Nz return m_buffer->Fill(data, m_startOffset + offset, size); } - void* VertexBuffer::Map(BufferAccess access, UInt32 startVertex, UInt32 length) + void* VertexBuffer::Map(BufferAccess access, std::size_t startVertex, std::size_t length) { - UInt32 stride = static_cast(m_vertexDeclaration->GetStride()); + std::size_t stride = static_cast(m_vertexDeclaration->GetStride()); return MapRaw(access, startVertex*stride, length*stride); } - void* VertexBuffer::Map(BufferAccess access, UInt32 startVertex, UInt32 length) const + void* VertexBuffer::Map(BufferAccess access, std::size_t startVertex, std::size_t length) const { NazaraAssert(m_buffer && m_buffer->IsValid(), "Invalid buffer"); NazaraAssert(m_vertexDeclaration, "Invalid vertex declaration"); - UInt32 stride = static_cast(m_vertexDeclaration->GetStride()); + std::size_t stride = static_cast(m_vertexDeclaration->GetStride()); return MapRaw(access, startVertex*stride, length*stride); } - void* VertexBuffer::MapRaw(BufferAccess access, UInt32 offset, UInt32 size) + void* VertexBuffer::MapRaw(BufferAccess access, std::size_t offset, std::size_t size) { NazaraAssert(m_buffer && m_buffer->IsValid(), "Invalid buffer"); NazaraAssert(m_startOffset + offset + size <= m_endOffset, "Exceeding virtual buffer size"); @@ -81,7 +81,7 @@ namespace Nz return m_buffer->Map(access, offset, size); } - void* VertexBuffer::MapRaw(BufferAccess access, UInt32 offset, UInt32 size) const + void* VertexBuffer::MapRaw(BufferAccess access, std::size_t offset, std::size_t size) const { NazaraAssert(m_buffer && m_buffer->IsValid(), "Invalid buffer"); NazaraAssert(m_startOffset + offset + size <= m_endOffset, "Exceeding virtual buffer size"); @@ -99,11 +99,11 @@ namespace Nz { NazaraAssert(buffer && buffer->IsValid(), "Invalid buffer"); - UInt32 size = buffer->GetSize(); + std::size_t size = buffer->GetSize(); Reset(std::move(vertexDeclaration), std::move(buffer), 0, size); } - void VertexBuffer::Reset(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, UInt32 offset, UInt32 size) + void VertexBuffer::Reset(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, std::size_t offset, std::size_t size) { NazaraAssert(buffer && buffer->IsValid(), "Invalid buffer"); NazaraAssert(size > 0, "Invalid size"); @@ -112,13 +112,13 @@ namespace Nz m_buffer = buffer; m_endOffset = offset + size; m_startOffset = offset; - m_vertexCount = (vertexDeclaration) ? (size / static_cast(vertexDeclaration->GetStride())) : 0; + m_vertexCount = (vertexDeclaration) ? (size / static_cast(vertexDeclaration->GetStride())) : 0; m_vertexDeclaration = vertexDeclaration; } - void VertexBuffer::Reset(VertexDeclarationConstRef vertexDeclaration, UInt32 length, DataStorage storage, BufferUsageFlags usage) + void VertexBuffer::Reset(VertexDeclarationConstRef vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage) { - m_endOffset = length * ((vertexDeclaration) ? static_cast(vertexDeclaration->GetStride()) : 1); + m_endOffset = length * ((vertexDeclaration) ? static_cast(vertexDeclaration->GetStride()) : 1); m_startOffset = 0; m_vertexCount = length; m_vertexDeclaration = std::move(vertexDeclaration); @@ -139,7 +139,7 @@ namespace Nz { NazaraAssert(vertexDeclaration, "Invalid vertex declaration"); - m_vertexCount = (m_endOffset - m_startOffset) / static_cast(vertexDeclaration->GetStride()); + m_vertexCount = (m_endOffset - m_startOffset) / static_cast(vertexDeclaration->GetStride()); m_vertexDeclaration = std::move(vertexDeclaration); } diff --git a/tests/Engine/Audio/Music.cpp b/tests/Engine/Audio/Music.cpp index 2e0edd8c3..262e87bc6 100644 --- a/tests/Engine/Audio/Music.cpp +++ b/tests/Engine/Audio/Music.cpp @@ -1,8 +1,8 @@ +#include #include #include - -#include -#include +#include +#include SCENARIO("Music", "[AUDIO][MUSIC]") { @@ -32,9 +32,9 @@ SCENARIO("Music", "[AUDIO][MUSIC]") Nz::Audio::SetGlobalVolume(0.f); music.Play(); - Nz::Thread::Sleep(1000); + std::this_thread::sleep_for(std::chrono::seconds(1)); REQUIRE(music.GetPlayingOffset() >= 950); - Nz::Thread::Sleep(200); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); REQUIRE(music.GetPlayingOffset() <= 1300); music.Pause(); REQUIRE(music.GetStatus() == Nz::SoundStatus_Paused); diff --git a/tests/Engine/Audio/Sound.cpp b/tests/Engine/Audio/Sound.cpp index 684138ccd..aa58bd537 100644 --- a/tests/Engine/Audio/Sound.cpp +++ b/tests/Engine/Audio/Sound.cpp @@ -1,8 +1,8 @@ +#include #include #include - -#include -#include +#include +#include SCENARIO("Sound", "[AUDIO][SOUND]") { @@ -26,10 +26,10 @@ SCENARIO("Sound", "[AUDIO][SOUND]") { Nz::Audio::SetGlobalVolume(0.f); - sound.Play(); - Nz::Thread::Sleep(1000); + sound.Play(); + std::this_thread::sleep_for(std::chrono::seconds(1)); REQUIRE(sound.GetPlayingOffset() >= 950); - Nz::Thread::Sleep(200); + std::this_thread::sleep_for(std::chrono::milliseconds(200)); REQUIRE(sound.GetPlayingOffset() <= 1300); sound.Pause(); REQUIRE(sound.GetStatus() == Nz::SoundStatus_Paused); diff --git a/tests/Engine/Audio/SoundEmitter.cpp b/tests/Engine/Audio/SoundEmitter.cpp index baac41eb3..c2cf4f318 100644 --- a/tests/Engine/Audio/SoundEmitter.cpp +++ b/tests/Engine/Audio/SoundEmitter.cpp @@ -1,8 +1,6 @@ #include #include -#include - SCENARIO("SoundEmitter", "[AUDIO][SOUNDEMITTER]") { GIVEN("A sound emitter") diff --git a/tests/Engine/Core/Clock.cpp b/tests/Engine/Core/Clock.cpp index 0bd579163..4e62996f1 100644 --- a/tests/Engine/Core/Clock.cpp +++ b/tests/Engine/Core/Clock.cpp @@ -1,6 +1,7 @@ #include -#include #include +#include +#include SCENARIO("Clock", "[CORE][CLOCK]") { @@ -25,7 +26,7 @@ SCENARIO("Clock", "[CORE][CLOCK]") THEN("Time must not be the initialTime") { - Nz::Thread::Sleep(1); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); Nz::UInt64 microSeconds = clock.GetMicroseconds(); CHECK(microSeconds != initialTime); CHECK(microSeconds / 1000 <= clock.GetMilliseconds()); diff --git a/tests/Engine/Core/Directory.cpp b/tests/Engine/Core/Directory.cpp deleted file mode 100644 index 5e60ed0ca..000000000 --- a/tests/Engine/Core/Directory.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include - -SCENARIO("Directory", "[CORE][DIRECTORY]") -{ - GIVEN("The current directory") - { - Nz::Directory currentDirectory(Nz::Directory::GetCurrent()); - CHECK(currentDirectory.Exists()); - currentDirectory.Open(); - - WHEN("We create a new directory Test Directory") - { - Nz::Directory::Create("Test Directory"); - - THEN("A new directory has been created") - { - CHECK(Nz::Directory::Exists(currentDirectory.GetCurrent() + "/Test Directory")); - CHECK(currentDirectory.IsOpen()); - } - } - - AND_WHEN("We delete it") - { - Nz::Directory::Remove(currentDirectory.GetCurrent() + "/Test Directory", true); - - THEN("It doesn't exist anymore") - { - CHECK(!Nz::Directory::Exists(currentDirectory.GetCurrent() + "/Test Directory")); - } - } - } -} - diff --git a/tests/Engine/Core/File.cpp b/tests/Engine/Core/File.cpp index 60b5bcc40..e78a812d1 100644 --- a/tests/Engine/Core/File.cpp +++ b/tests/Engine/Core/File.cpp @@ -1,5 +1,4 @@ #include -#include #include SCENARIO("File", "[CORE][FILE]") @@ -9,7 +8,7 @@ SCENARIO("File", "[CORE][FILE]") WHEN("We create a new file") { Nz::File file("Test File.txt", Nz::OpenMode_ReadWrite); - REQUIRE(file.GetDirectory() == Nz::Directory::GetCurrent() + NAZARA_DIRECTORY_SEPARATOR); + REQUIRE(file.GetDirectory() == std::filesystem::current_path()); REQUIRE(file.IsOpen()); THEN("We are allowed to write 3 times 'Test String'") @@ -53,18 +52,18 @@ SCENARIO("File", "[CORE][FILE]") WHEN("We delete this file") { - Nz::File::Delete("Test File.txt"); + std::filesystem::remove("Test File.txt"); THEN("It doesn't exist anymore") { - CHECK(!Nz::File::Exists("Test File.txt")); + CHECK(!std::filesystem::exists("Test File.txt")); } } } GIVEN("The test file") { - REQUIRE(Nz::File::Exists("resources/Engine/Core/FileTest.txt")); + REQUIRE(std::filesystem::exists("resources/Engine/Core/FileTest.txt")); Nz::File fileTest("resources/Engine/Core/FileTest.txt", Nz::OpenMode_ReadOnly | Nz::OpenMode_Text); @@ -79,20 +78,4 @@ SCENARIO("File", "[CORE][FILE]") } } } - - GIVEN("Nothing") - { - WHEN("We get the absolute path of something containing relative path") - { - Nz::String containingDot = "/resources/Spaceship/./spaceship.mtl"; - Nz::String containingDoubleDot = "/resources/Spaceship/../Spaceship/spaceship.mtl"; - - THEN("The relative positioning should disappear") - { - Nz::String containingNoMoreDot = Nz::File::NormalizePath("/resources/Spaceship/spaceship.mtl"); - REQUIRE(Nz::File::AbsolutePath(containingDot).EndsWith(containingNoMoreDot)); - REQUIRE(Nz::File::AbsolutePath(containingDoubleDot).EndsWith(containingNoMoreDot)); - } - } - } } diff --git a/tests/Engine/Network/TCP.cpp b/tests/Engine/Network/TCP.cpp index 2c34e0b0b..0bc90483c 100644 --- a/tests/Engine/Network/TCP.cpp +++ b/tests/Engine/Network/TCP.cpp @@ -1,10 +1,11 @@ -#include #include #include #include #include #include +#include #include +#include SCENARIO("TCP", "[NETWORK][TCP]") { @@ -29,7 +30,7 @@ SCENARIO("TCP", "[NETWORK][TCP]") Nz::IpAddress clientIP = client.GetRemoteAddress(); CHECK(clientIP.IsValid()); - Nz::Thread::Sleep(100); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); Nz::TcpClient serverToClient; REQUIRE(server.AcceptClient(&serverToClient)); diff --git a/thirdparty/include/Utfcpp/utf8.h b/thirdparty/include/Utfcpp/utf8.h index 82b13f59f..c2c85d6d0 100644 --- a/thirdparty/include/Utfcpp/utf8.h +++ b/thirdparty/include/Utfcpp/utf8.h @@ -31,4 +31,8 @@ DEALINGS IN THE SOFTWARE. #include "utf8/checked.h" #include "utf8/unchecked.h" +#if __cplusplus >= 201103L // C++ 11 or later +#include "utf8/cpp11.h" +#endif // C++ 11 or later + #endif // header guard diff --git a/thirdparty/include/Utfcpp/utf8/checked.h b/thirdparty/include/Utfcpp/utf8/checked.h index 23a5e473d..c31861e0a 100644 --- a/thirdparty/include/Utfcpp/utf8/checked.h +++ b/thirdparty/include/Utfcpp/utf8/checked.h @@ -1,4 +1,4 @@ -// Copyright 2006 Nemanja Trifunovic +// Copyright 2006-2016 Nemanja Trifunovic /* Permission is hereby granted, free of charge, to any person or organization @@ -41,7 +41,7 @@ namespace utf8 class invalid_code_point : public exception { uint32_t cp; public: - invalid_code_point(uint32_t Cp) : cp(Cp) {} // @Lynix: -Wshadow + invalid_code_point(uint32_t codepoint) : cp(codepoint) {} virtual const char* what() const throw() { return "Invalid code point"; } uint32_t code_point() const {return cp;} }; @@ -107,7 +107,9 @@ namespace utf8 *out++ = *it; break; case internal::NOT_ENOUGH_ROOM: - throw not_enough_room(); + out = utf8::append (replacement, out); + start = end; + break; case internal::INVALID_LEAD: out = utf8::append (replacement, out); ++start; @@ -174,23 +176,19 @@ namespace utf8 return utf8::peek_next(it, end); } - /// Deprecated in versions that include "prior" - template - uint32_t previous(octet_iterator& it, octet_iterator pass_start) - { - octet_iterator end = it; - while (utf8::internal::is_trail(*(--it))) - if (it == pass_start) - throw invalid_utf8(*it); // error - no lead byte in the sequence - octet_iterator temp = it; - return utf8::next(temp, end); - } - template void advance (octet_iterator& it, distance_type n, octet_iterator end) { - for (distance_type i = 0; i < n; ++i) - utf8::next(it, end); + const distance_type zero(0); + if (n < zero) { + // backward + for (distance_type i = n; i < zero; ++i) + utf8::prior(it, end); + } else { + // forward + for (distance_type i = zero; i < n; ++i) + utf8::next(it, end); + } } template @@ -233,7 +231,7 @@ namespace utf8 template u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) { - while (start != end) { + while (start < end) { uint32_t cp = utf8::next(start, end); if (cp > 0xffff) { //make a surrogate pair *result++ = static_cast((cp >> 10) + internal::LEAD_OFFSET); @@ -257,7 +255,7 @@ namespace utf8 template u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) { - while (start != end) + while (start < end) (*result++) = utf8::next(start, end); return result; @@ -272,9 +270,9 @@ namespace utf8 public: iterator () {} explicit iterator (const octet_iterator& octet_it, - const octet_iterator& Range_start, // @Lynix: -Wshadow - const octet_iterator& Range_end) : // @Lynix: -Wshadow - it(octet_it), range_start(Range_start), range_end(Range_end) // @Lynix: -Wshadow + const octet_iterator& rangestart, + const octet_iterator& rangeend) : + it(octet_it), range_start(rangestart), range_end(rangeend) { if (it < range_start || it > range_end) throw std::out_of_range("Invalid utf-8 iterator position"); @@ -324,4 +322,3 @@ namespace utf8 #endif //header guard - diff --git a/thirdparty/include/Utfcpp/utf8/core.h b/thirdparty/include/Utfcpp/utf8/core.h index 636795143..01e061b0a 100644 --- a/thirdparty/include/Utfcpp/utf8/core.h +++ b/thirdparty/include/Utfcpp/utf8/core.h @@ -50,8 +50,8 @@ namespace internal const uint16_t LEAD_SURROGATE_MAX = 0xdbffu; const uint16_t TRAIL_SURROGATE_MIN = 0xdc00u; const uint16_t TRAIL_SURROGATE_MAX = 0xdfffu; - const uint16_t LEAD_OFFSET = LEAD_SURROGATE_MIN - (0x10000 >> 10); - const uint32_t SURROGATE_OFFSET = 0x10000u - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN; + const uint16_t LEAD_OFFSET = 0xd7c0u; // LEAD_SURROGATE_MIN - (0x10000 >> 10) + const uint32_t SURROGATE_OFFSET = 0xfca02400u; // 0x10000u - (LEAD_SURROGATE_MIN << 10) - TRAIL_SURROGATE_MIN // Maximum valid value for a Unicode code point const uint32_t CODE_POINT_MAX = 0x0010ffffu; @@ -143,7 +143,7 @@ namespace internal if (!utf8::internal::is_trail(*it)) return INCOMPLETE_SEQUENCE; - + return UTF8_OK; } @@ -166,7 +166,7 @@ namespace internal { if (it == end) return NOT_ENOUGH_ROOM; - + code_point = utf8::internal::mask8(*it); UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) @@ -223,6 +223,9 @@ namespace internal template utf_error validate_next(octet_iterator& it, octet_iterator end, uint32_t& code_point) { + if (it == end) + return NOT_ENOUGH_ROOM; + // Save the original value of it so we can go back in case of failure // Of course, it does not make much sense with i.e. stream iterators octet_iterator original_it = it; @@ -235,7 +238,7 @@ namespace internal // Get trail octets and calculate the code point utf_error err = UTF8_OK; switch (length) { - case 0: + case 0: return INVALID_LEAD; case 1: err = utf8::internal::get_sequence_1(it, end, cp); @@ -311,18 +314,7 @@ namespace internal ((it != end) && (utf8::internal::mask8(*it++)) == bom[1]) && ((it != end) && (utf8::internal::mask8(*it)) == bom[2]) ); - } - - //Deprecated in release 2.3 - template - inline bool is_bom (octet_iterator it) - { - return ( - (utf8::internal::mask8(*it++)) == bom[0] && - (utf8::internal::mask8(*it++)) == bom[1] && - (utf8::internal::mask8(*it)) == bom[2] - ); - } + } } // namespace utf8 #endif // header guard diff --git a/thirdparty/include/Utfcpp/utf8/cpp11.h b/thirdparty/include/Utfcpp/utf8/cpp11.h new file mode 100644 index 000000000..d93961b04 --- /dev/null +++ b/thirdparty/include/Utfcpp/utf8/cpp11.h @@ -0,0 +1,103 @@ +// Copyright 2018 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef UTF8_FOR_CPP_a184c22c_d012_11e8_a8d5_f2801f1b9fd1 +#define UTF8_FOR_CPP_a184c22c_d012_11e8_a8d5_f2801f1b9fd1 + +#include "checked.h" +#include + +namespace utf8 +{ + + inline void append(char32_t cp, std::string& s) + { + append(uint32_t(cp), std::back_inserter(s)); + } + + inline std::string utf16to8(const std::u16string& s) + { + std::string result; + utf16to8(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u16string utf8to16(const std::string& s) + { + std::u16string result; + utf8to16(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::string utf32to8(const std::u32string& s) + { + std::string result; + utf32to8(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::u32string utf8to32(const std::string& s) + { + std::u32string result; + utf8to32(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline std::size_t find_invalid(const std::string& s) + { + std::string::const_iterator invalid = find_invalid(s.begin(), s.end()); + return (invalid == s.end()) ? std::string::npos : (invalid - s.begin()); + } + + inline bool is_valid(const std::string& s) + { + return is_valid(s.begin(), s.end()); + } + + inline std::string replace_invalid(const std::string& s, char32_t replacement) + { + std::string result; + replace_invalid(s.begin(), s.end(), std::back_inserter(result), replacement); + return result; + } + + inline std::string replace_invalid(const std::string& s) + { + std::string result; + replace_invalid(s.begin(), s.end(), std::back_inserter(result)); + return result; + } + + inline bool starts_with_bom(const std::string& s) + { + return starts_with_bom(s.begin(), s.end()); + } + +} // namespace utf8 + +#endif // header guard + diff --git a/thirdparty/include/Utfcpp/utf8/unchecked.h b/thirdparty/include/Utfcpp/utf8/unchecked.h index cb2427166..def000997 100644 --- a/thirdparty/include/Utfcpp/utf8/unchecked.h +++ b/thirdparty/include/Utfcpp/utf8/unchecked.h @@ -32,13 +32,13 @@ DEALINGS IN THE SOFTWARE. namespace utf8 { - namespace unchecked + namespace unchecked { template octet_iterator append(uint32_t cp, octet_iterator result) { if (cp < 0x80) // one octet - *(result++) = static_cast(cp); + *(result++) = static_cast(cp); else if (cp < 0x800) { // two octets *(result++) = static_cast((cp >> 6) | 0xc0); *(result++) = static_cast((cp & 0x3f) | 0x80); @@ -57,6 +57,46 @@ namespace utf8 return result; } + template + output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement) + { + while (start != end) { + octet_iterator sequence_start = start; + internal::utf_error err_code = utf8::internal::validate_next(start, end); + switch (err_code) { + case internal::UTF8_OK : + for (octet_iterator it = sequence_start; it != start; ++it) + *out++ = *it; + break; + case internal::NOT_ENOUGH_ROOM: + out = utf8::unchecked::append (replacement, out); + start = end; + break; + case internal::INVALID_LEAD: + out = utf8::unchecked::append (replacement, out); + ++start; + break; + case internal::INCOMPLETE_SEQUENCE: + case internal::OVERLONG_SEQUENCE: + case internal::INVALID_CODE_POINT: + out = utf8::unchecked::append (replacement, out); + ++start; + // just one replacement mark for the sequence + while (start != end && utf8::internal::is_trail(*start)) + ++start; + break; + } + } + return out; + } + + template + inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) + { + static const uint32_t replacement_marker = utf8::internal::mask16(0xfffd); + return utf8::unchecked::replace_invalid(start, end, out, replacement_marker); + } + template uint32_t next(octet_iterator& it) { @@ -85,13 +125,13 @@ namespace utf8 break; } ++it; - return cp; + return cp; } template uint32_t peek_next(octet_iterator it) { - return utf8::unchecked::next(it); + return utf8::unchecked::next(it); } template @@ -102,18 +142,19 @@ namespace utf8 return utf8::unchecked::next(temp); } - // Deprecated in versions that include prior, but only for the sake of consistency (see utf8::previous) - template - inline uint32_t previous(octet_iterator& it) - { - return utf8::unchecked::prior(it); - } - template void advance (octet_iterator& it, distance_type n) { - for (distance_type i = 0; i < n; ++i) - utf8::unchecked::next(it); + const distance_type zero(0); + if (n < zero) { + // backward + for (distance_type i = n; i < zero; ++i) + utf8::unchecked::prior(it); + } else { + // forward + for (distance_type i = zero; i < n; ++i) + utf8::unchecked::next(it); + } } template @@ -128,7 +169,7 @@ namespace utf8 template octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) - { + { while (start != end) { uint32_t cp = utf8::internal::mask16(*start++); // Take care of surrogate pairs first @@ -138,7 +179,7 @@ namespace utf8 } result = utf8::unchecked::append(cp, result); } - return result; + return result; } template