Compare commits

...

15 Commits

Author SHA1 Message Date
SweetId
1846d42401 [Assets] Add example 2024-03-24 22:00:25 -04:00
SweetId
5c6ea6c485 [Assets] Add headers to single include 2024-03-24 22:00:11 -04:00
SweetId
92179df553 [Assets] Making AssetCatalog an AppComponent 2024-03-24 21:59:50 -04:00
SweetId
172d3ea720 Foreach can now be recursive 2024-03-24 21:58:55 -04:00
SweetId
2ccc5c364c fix ApplicationBase::TryGetComponent 2024-03-24 20:45:42 -04:00
SweetId
e306a66956 Make Sound FilesystemAppComponent-compliant 2024-03-11 19:37:35 -04:00
SweetId
4199582a52 [Serialization] Add SoundBufferParams serialization functions 2024-03-11 19:37:15 -04:00
SweetId
2784d62ec9 [Serialization] Fix SoundStreamParams Serialization functions 2024-03-11 19:36:51 -04:00
SweetId
d304c56898 [Assets] load Json through filesystem if available 2024-03-11 19:08:37 -04:00
SweetId
8cc1719d1b [Serialization] Make JsonSerializationContext FilesystemAppComponent-compatible 2024-03-11 19:08:10 -04:00
SweetId
cc2c36c75d Update Music to use correct Resource API 2024-03-11 17:15:27 -04:00
SweetId
cc91b8d3b9 [Assets] Handle streaming resources properly 2024-03-11 17:14:56 -04:00
SweetId
841778fe2f [Assets] Overload access operators to use underlying resource ptr 2024-03-11 17:14:39 -04:00
SweetId
467f471390 [Assets] add base classes and functionnalities 2024-03-10 17:05:54 -04:00
SweetId
6a6ffb6779 [Serialization] Add Json serializer 2024-03-10 17:04:35 -04:00
25 changed files with 624 additions and 45 deletions

39
examples/Assets/main.cpp Normal file
View File

@@ -0,0 +1,39 @@
#include <Nazara/Audio.hpp>
#include <Nazara/Core.hpp>
#include <Nazara/Platform.hpp>
int main(int argc, char* argv[])
{
std::filesystem::path resourceDir = "assets";
if (!std::filesystem::is_directory(resourceDir) && std::filesystem::is_directory("../.." / resourceDir))
resourceDir = "../.." / resourceDir;
Nz::Application<Nz::Audio> app(argc, argv);
auto& windowing = app.AddComponent<Nz::WindowingAppComponent>();
auto& fs = app.AddComponent<Nz::FilesystemAppComponent>();
fs.Mount("game:/", resourceDir);
auto& catalog = app.AddComponent<Nz::AssetCatalogAppComponent>();
catalog.AddFolder("game:/");
// Load an asset from its path
Nz::Asset<Nz::Music> music = Nz::Asset<Nz::Music>::LoadFromFile("game:/examples/Audio/file_example_MP3_700KB.nzasset");
// or by its name
music = catalog.Load<Nz::Music>("file_example_MP3_700KB");
music->Play();
Nz::Asset<Nz::Sound> sound = catalog.Load<Nz::Sound>("examples/Audio/siren");
sound->Play();
app.AddUpdaterFunc([&]
{
if (!music->IsPlaying())
app.Quit();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
});
return app.Run();
}

View File

@@ -0,0 +1,3 @@
target("Assets")
add_deps("NazaraGraphics", "NazaraAudio")
add_files("main.cpp")

View File

@@ -25,6 +25,8 @@ namespace Nz
class NAZARA_AUDIO_API Music final : public Resource, public SoundEmitter class NAZARA_AUDIO_API Music final : public Resource, public SoundEmitter
{ {
public: public:
using Params = SoundStreamParams;
Music(); Music();
Music(AudioDevice& device); Music(AudioDevice& device);
Music(const Music&) = delete; Music(const Music&) = delete;
@@ -46,9 +48,9 @@ namespace Nz
bool IsLooping() const override; bool IsLooping() const override;
bool OpenFromFile(const std::filesystem::path& filePath, const SoundStreamParams& params = SoundStreamParams()); static std::shared_ptr<Music> OpenFromFile(const std::filesystem::path& filePath, const Params& params = Params());
bool OpenFromMemory(const void* data, std::size_t size, const SoundStreamParams& params = SoundStreamParams()); static std::shared_ptr<Music> OpenFromMemory(const void* data, std::size_t size, const Params& params = Params());
bool OpenFromStream(Stream& stream, const SoundStreamParams& params = SoundStreamParams()); static std::shared_ptr<Music> OpenFromStream(Stream& stream, const Params& params = Params());
void Pause() override; void Pause() override;
void Play() override; void Play() override;

View File

@@ -17,6 +17,8 @@ namespace Nz
class NAZARA_AUDIO_API Sound final : public SoundEmitter class NAZARA_AUDIO_API Sound final : public SoundEmitter
{ {
public: public:
using Params = SoundBufferParams;
using SoundEmitter::SoundEmitter; using SoundEmitter::SoundEmitter;
Sound(); Sound();
Sound(AudioDevice& audioDevice, std::shared_ptr<SoundBuffer> soundBuffer); Sound(AudioDevice& audioDevice, std::shared_ptr<SoundBuffer> soundBuffer);
@@ -36,9 +38,9 @@ namespace Nz
bool IsLooping() const override; bool IsLooping() const override;
bool IsPlayable() const; bool IsPlayable() const;
bool LoadFromFile(const std::filesystem::path& filePath, const SoundBufferParams& params = SoundBufferParams()); static std::shared_ptr<Sound> LoadFromFile(const std::filesystem::path& filePath, const Params& params = {});
bool LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params = SoundBufferParams()); static std::shared_ptr<Sound> LoadFromMemory(const void* data, std::size_t size, const Params& params = {});
bool LoadFromStream(Stream& stream, const SoundBufferParams& params = SoundBufferParams()); static std::shared_ptr<Sound> LoadFromStream(Stream& stream, const Params& params = {});
void Pause() override; void Pause() override;
void Play() override; void Play() override;

View File

@@ -29,6 +29,9 @@ namespace Nz
bool IsValid() const; bool IsValid() const;
}; };
NAZARA_AUDIO_API bool Serialize(SerializationContext& context, SoundBufferParams& params, TypeTag<SoundBufferParams>);
NAZARA_AUDIO_API bool Unserialize(SerializationContext& context, SoundBufferParams* params, TypeTag<SoundBufferParams>);
class AudioBuffer; class AudioBuffer;
class AudioDevice; class AudioDevice;
class Sound; class Sound;

View File

@@ -25,8 +25,8 @@ namespace Nz
bool IsValid() const; bool IsValid() const;
}; };
NAZARA_CORE_API bool Serialize(SerializationContext& context, SoundStreamParams& params, TypeTag<SoundStreamParams>); NAZARA_AUDIO_API bool Serialize(SerializationContext& context, SoundStreamParams& params, TypeTag<SoundStreamParams>);
NAZARA_CORE_API bool Unserialize(SerializationContext& context, SoundStreamParams* params, TypeTag<SoundStreamParams>); NAZARA_AUDIO_API bool Unserialize(SerializationContext& context, SoundStreamParams* params, TypeTag<SoundStreamParams>);
class Mutex; class Mutex;
class SoundStream; class SoundStream;

View File

@@ -39,6 +39,9 @@
#include <Nazara/Core/ApplicationBase.hpp> #include <Nazara/Core/ApplicationBase.hpp>
#include <Nazara/Core/ApplicationComponent.hpp> #include <Nazara/Core/ApplicationComponent.hpp>
#include <Nazara/Core/ApplicationUpdater.hpp> #include <Nazara/Core/ApplicationUpdater.hpp>
#include <Nazara/Core/Asset.hpp>
#include <Nazara/Core/AssetDescriptor.hpp>
#include <Nazara/Core/AssetCatalogAppComponent.hpp>
#include <Nazara/Core/Buffer.hpp> #include <Nazara/Core/Buffer.hpp>
#include <Nazara/Core/BufferMapper.hpp> #include <Nazara/Core/BufferMapper.hpp>
#include <Nazara/Core/ByteArray.hpp> #include <Nazara/Core/ByteArray.hpp>

View File

@@ -97,7 +97,7 @@ namespace Nz
constexpr UInt64 typeHash = FNV1a64(TypeName<T>()); constexpr UInt64 typeHash = FNV1a64(TypeName<T>());
auto it = m_components.find(typeHash); auto it = m_components.find(typeHash);
if (it != m_components.end()) if (it == m_components.end())
return nullptr; return nullptr;
return static_cast<T*>(it->second.get()); return static_cast<T*>(it->second.get());
@@ -109,7 +109,7 @@ namespace Nz
constexpr UInt64 typeHash = FNV1a64(TypeName<T>()); constexpr UInt64 typeHash = FNV1a64(TypeName<T>());
auto it = m_components.find(typeHash); auto it = m_components.find(typeHash);
if (it != m_components.end()) if (it == m_components.end())
return nullptr; return nullptr;
return static_cast<const T*>(it->second.get()); return static_cast<const T*>(it->second.get());

View File

@@ -0,0 +1,29 @@
#pragma once
#include <Nazara/Core/AssetDescriptor.hpp>
namespace Nz
{
template <typename TResource>
class Asset final
{
public:
const std::shared_ptr<TResource>& Get() const { return m_resource; }
explicit operator bool() const noexcept { return !!m_resource; }
TResource& operator*() { return *m_resource.get(); }
const TResource& operator*() const { return *m_resource.get(); }
TResource* operator->() { return m_resource.get(); }
const TResource* operator->() const { return m_resource.get(); }
static Asset LoadFromFile(const std::filesystem::path& path);
protected:
AssetDescriptor<TResource> m_descriptor;
std::shared_ptr<TResource> m_resource;
friend class AssetCatalog;
};
}
#include <Nazara/Core/Asset.inl>

View File

@@ -0,0 +1,60 @@
#include <Nazara/Core/ApplicationBase.hpp>
#include <Nazara/Core/FilesystemAppComponent.hpp>
#include <Nazara/Core/JsonSerialization.hpp>
namespace Nz
{
template <typename TResource>
concept IsStreamingResource = requires(TResource)
{
{ TResource::OpenFromFile({}) } -> std::same_as<std::shared_ptr<TResource>>;
};
template <typename TResource>
Asset<TResource> Asset<TResource>::LoadFromFile(const std::filesystem::path& path)
{
Asset<TResource> asset;
FilesystemAppComponent* fs = ApplicationBase::Instance()->TryGetComponent<FilesystemAppComponent>();
if (fs) // first try using a FileSystem component to load the asset
{
auto json = fs->Load<JsonSerializationContext>(std::string_view(path.string()));
if (json)
{
if (!Unserialize(*json, "", &asset.m_descriptor))
return {};
std::string filepath = asset.m_descriptor.path.string();
if constexpr (IsStreamingResource<TResource>)
{
asset.m_resource = fs->Open<TResource>(std::string_view(filepath), asset.m_descriptor.parameters);
}
else
{
asset.m_resource = fs->Load<TResource>(std::string_view(filepath), asset.m_descriptor.parameters);
}
}
}
if (!asset) // if it fails, use the default loader
{
JsonSerializationContext json;
if (!json.Load(path))
return {};
if (!Unserialize(json, "", &asset.m_descriptor))
return {};
if constexpr (IsStreamingResource<TResource>)
{
asset.m_resource = TResource::OpenFromFile(asset.m_descriptor.path, asset.m_descriptor.parameters);
}
else
{
asset.m_resource = TResource::LoadFromFile(asset.m_descriptor.path, asset.m_descriptor.parameters);
}
}
return asset;
}
}

View File

@@ -0,0 +1,45 @@
#pragma once
#include <Nazara/Core/Asset.hpp>
#include <Nazara/Core/ApplicationComponent.hpp>
#include <Nazara/Core/Export.hpp>
#include <set>
namespace Nz
{
struct AssetHeaderLite
{
std::string name;
std::filesystem::path path;
friend auto operator<=>(const AssetHeaderLite& A, const AssetHeaderLite& B)
{
return A.name <=> B.name;
}
};
NAZARA_CORE_API bool Serialize(struct SerializationContext& context, const AssetHeaderLite& header, TypeTag<AssetHeaderLite>);
NAZARA_CORE_API bool Unserialize(struct SerializationContext& context, AssetHeaderLite* header, TypeTag<AssetHeaderLite>);
class NAZARA_CORE_API AssetCatalogAppComponent
: public ApplicationComponent
{
public:
inline AssetCatalogAppComponent(ApplicationBase& app);
AssetCatalogAppComponent(const AssetCatalogAppComponent&) = delete;
AssetCatalogAppComponent(AssetCatalogAppComponent&&) = delete;
~AssetCatalogAppComponent() = default;
void AddFolder(std::string_view folder);
template<typename TResource>
inline Asset<TResource> Load(std::string_view name) const;
protected:
std::set<AssetHeaderLite> m_assets;
};
}
#include <Nazara/Core/AssetCatalogAppComponent.inl>

View File

@@ -0,0 +1,19 @@
namespace Nz
{
inline AssetCatalogAppComponent::AssetCatalogAppComponent(ApplicationBase& app)
: ApplicationComponent(app)
{
}
template<typename TResource>
Asset<TResource> AssetCatalogAppComponent::Load(std::string_view name) const
{
AssetHeaderLite header{ std::string(name), "" };
auto it = m_assets.find(header);
if (it == m_assets.end())
return {};
return Asset<TResource>::LoadFromFile(it->path);
}
}

View File

@@ -0,0 +1,24 @@
#pragma once
#include <Nazara/Core/Serialization.hpp>
#include <NazaraUtils/TypeName.hpp>
namespace Nz
{
template <typename TResource>
struct AssetDescriptor
{
constexpr static std::string_view Type = TypeName<TResource>();
int version;
std::string type;
std::string name;
std::filesystem::path path;
TResource::Params parameters;
};
template <typename TResource> bool Serialize(SerializationContext& context, const AssetDescriptor<TResource>& descriptor, TypeTag<AssetDescriptor<TResource>>);
template <typename TResource> bool Unserialize(SerializationContext& context, AssetDescriptor<TResource>* descriptor, TypeTag<AssetDescriptor<TResource>>);
}
#include <Nazara/Core/AssetDescriptor.inl>

View File

@@ -0,0 +1,37 @@
namespace Nz
{
template <typename TResource>
bool Serialize(SerializationContext& context, const AssetDescriptor<TResource>& descriptor, TypeTag<AssetDescriptor<TResource>>)
{
Serialize(context, "version", descriptor.version);
Serialize(context, "type", descriptor.type);
Serialize(context, "name", descriptor.name);
Serialize(context, "path", descriptor.path);
Serialize(context, "parameters", descriptor.parameters);
return true;
}
template <typename TResource>
bool Unserialize(SerializationContext& context, AssetDescriptor<TResource>* descriptor, TypeTag<AssetDescriptor<TResource>>)
{
if (!Unserialize(context, "version", &descriptor->version))
return false;
if (!Unserialize(context, "type", &descriptor->type))
return false;
if (AssetDescriptor<TResource>::Type != descriptor->type)
return false;
if (!Unserialize(context, "name", &descriptor->name))
return false;
if (!Unserialize(context, "path", &descriptor->path))
return false;
if (!Unserialize(context, "parameters", &descriptor->parameters))
return false;
return true;
}
}

View File

@@ -0,0 +1,58 @@
#pragma once
#include <Nazara/Core/Export.hpp>
#include <Nazara/Core/Serialization.hpp>
namespace Nz
{
class NAZARA_CORE_API JsonSerializationContext
: public SerializationContext
{
public:
struct Params {};
JsonSerializationContext();
~JsonSerializationContext();
bool Load(const std::filesystem::path& path);
bool Load(Stream& stream);
EnumSerializationMode GetEnumSerializationMode() const override { return EnumSerializationMode::String; }
bool PushObject(std::string_view name) override;
bool PopObject() override;
bool PushArray(std::string_view name) override;
bool PopArray() override;
bool Write(std::string_view name, bool value) override;
bool Write(std::string_view name, Nz::Int8 value) override;
bool Write(std::string_view name, Nz::Int16 value) override;
bool Write(std::string_view name, Nz::Int32 value) override;
bool Write(std::string_view name, Nz::Int64 value) override;
bool Write(std::string_view name, Nz::UInt8 value) override;
bool Write(std::string_view name, Nz::UInt16 value) override;
bool Write(std::string_view name, Nz::UInt32 value) override;
bool Write(std::string_view name, Nz::UInt64 value) override;
bool Write(std::string_view name, float value) override;
bool Write(std::string_view name, double value) override;
bool Write(std::string_view name, const std::string& value) override;
bool Read(std::string_view name, bool* value) override;
bool Read(std::string_view name, Nz::Int8* value) override;
bool Read(std::string_view name, Nz::Int16* value) override;
bool Read(std::string_view name, Nz::Int32* value) override;
bool Read(std::string_view name, Nz::Int64* value) override;
bool Read(std::string_view name, Nz::UInt8* value) override;
bool Read(std::string_view name, Nz::UInt16* value) override;
bool Read(std::string_view name, Nz::UInt32* value) override;
bool Read(std::string_view name, Nz::UInt64* value) override;
bool Read(std::string_view name, float* value) override;
bool Read(std::string_view name, double* value) override;
bool Read(std::string_view name, std::string* value) override;
static std::shared_ptr<JsonSerializationContext> LoadFromStream(Stream& stream, const Params& params = {});
private:
std::unique_ptr<struct JsonImpl> m_impl;
};
}

View File

@@ -41,7 +41,7 @@ namespace Nz
inline bool Exists(std::string_view path); inline bool Exists(std::string_view path);
template<typename F> void Foreach(F&& callback, bool includeDots = false); template<typename F> bool Foreach(F&& callback, bool recursive = false, bool includeDots = false);
template<typename F> bool GetDirectoryEntry(std::string_view path, F&& callback); template<typename F> bool GetDirectoryEntry(std::string_view path, F&& callback);
template<typename F> bool GetEntry(std::string_view path, F&& callback); template<typename F> bool GetEntry(std::string_view path, F&& callback);

View File

@@ -36,7 +36,7 @@ namespace Nz
} }
template<typename F> template<typename F>
void VirtualDirectory::Foreach(F&& callback, bool includeDots) bool VirtualDirectory::Foreach(F&& callback, bool recursive, bool includeDots)
{ {
if (includeDots) if (includeDots)
{ {
@@ -46,16 +46,26 @@ namespace Nz
{ {
Entry parentEntry = DirectoryEntry{ { parent } }; Entry parentEntry = DirectoryEntry{ { parent } };
if (!CallbackReturn(callback, std::string_view(".."), parentEntry)) if (!CallbackReturn(callback, std::string_view(".."), parentEntry))
return; return false;
} }
else if (!CallbackReturn(callback, std::string_view(".."), ourselves)) else if (!CallbackReturn(callback, std::string_view(".."), ourselves))
return; return false;
} }
for (auto&& entry : m_content) for (auto&& entry : m_content)
{ {
if (!CallbackReturn(callback, std::string_view(entry.name), std::as_const(entry.entry))) if (!CallbackReturn(callback, std::string_view(entry.name), std::as_const(entry.entry)))
return; return false;
if (recursive)
{
if (std::holds_alternative<DirectoryEntry>(entry.entry))
{
DirectoryEntry& child = std::get<DirectoryEntry>(entry.entry);
if (!child.directory->Foreach(callback, recursive, includeDots))
return false;
}
}
} }
if (m_resolver) if (m_resolver)
@@ -70,9 +80,22 @@ namespace Nz
if (it != m_content.end() && it->name == filename) if (it != m_content.end() && it->name == filename)
return true; //< this was already returned return true; //< this was already returned
return CallbackReturn(callback, filename, std::move(entry)); if (!CallbackReturn(callback, filename, entry))
return false;
if (recursive)
{
if (std::holds_alternative<DirectoryEntry>(entry))
{
DirectoryEntry& child = std::get<DirectoryEntry>(entry);
if (!child.directory->Foreach(callback, recursive, includeDots))
return false;
}
}
return true;
}); });
} }
return true;
} }
template<typename F> template<typename F>

View File

@@ -240,12 +240,17 @@ namespace Nz
* \param filePath Path to the file * \param filePath Path to the file
* \param params Parameters for the music * \param params Parameters for the music
*/ */
bool Music::OpenFromFile(const std::filesystem::path& filePath, const SoundStreamParams& params) std::shared_ptr<Music> Music::OpenFromFile(const std::filesystem::path& filePath, const Params& params)
{ {
std::shared_ptr<Music> music = std::make_shared<Music>();
if (std::shared_ptr<SoundStream> soundStream = SoundStream::OpenFromFile(filePath, params)) if (std::shared_ptr<SoundStream> soundStream = SoundStream::OpenFromFile(filePath, params))
return Create(std::move(soundStream)); {
else std::shared_ptr<Music> music = std::make_shared<Music>();
return false; if (music->Create(std::move(soundStream)))
return music;
}
return {};
} }
/*! /*!
@@ -258,12 +263,16 @@ namespace Nz
* *
* \remark The memory pointer must stay valid (accessible) as long as the music is playing * \remark The memory pointer must stay valid (accessible) as long as the music is playing
*/ */
bool Music::OpenFromMemory(const void* data, std::size_t size, const SoundStreamParams& params) std::shared_ptr<Music> Music::OpenFromMemory(const void* data, std::size_t size, const Params& params)
{ {
if (std::shared_ptr<SoundStream> soundStream = SoundStream::OpenFromMemory(data, size, params)) if (std::shared_ptr<SoundStream> soundStream = SoundStream::OpenFromMemory(data, size, params))
return Create(std::move(soundStream)); {
else std::shared_ptr<Music> music = std::make_shared<Music>();
return false; if (music->Create(std::move(soundStream)))
return music;
}
return {};
} }
/*! /*!
@@ -275,12 +284,16 @@ namespace Nz
* *
* \remark The stream must stay valid as long as the music is playing * \remark The stream must stay valid as long as the music is playing
*/ */
bool Music::OpenFromStream(Stream& stream, const SoundStreamParams& params) std::shared_ptr<Music> Music::OpenFromStream(Stream& stream, const Params& params)
{ {
if (std::shared_ptr<SoundStream> soundStream = SoundStream::OpenFromStream(stream, params)) if (std::shared_ptr<SoundStream> soundStream = SoundStream::OpenFromStream(stream, params))
return Create(std::move(soundStream)); {
else std::shared_ptr<Music> music = std::make_shared<Music>();
return false; if (music->Create(std::move(soundStream)))
return music;
}
return {};
} }
/*! /*!
@@ -439,7 +452,7 @@ namespace Nz
break; // We have reached the end of the stream, there is no use to add new buffers break; // We have reached the end of the stream, there is no use to add new buffers
} }
} }
catch (const std::exception&) catch (const std::exception& e)
{ {
err = std::current_exception(); err = std::current_exception();

View File

@@ -141,17 +141,18 @@ namespace Nz
* *
* \remark Produces a NazaraError if loading failed * \remark Produces a NazaraError if loading failed
*/ */
bool Sound::LoadFromFile(const std::filesystem::path& filePath, const SoundBufferParams& params) std::shared_ptr<Sound> Sound::LoadFromFile(const std::filesystem::path& filePath, const Params& params)
{ {
std::shared_ptr<SoundBuffer> buffer = SoundBuffer::LoadFromFile(filePath, params); std::shared_ptr<SoundBuffer> buffer = SoundBuffer::LoadFromFile(filePath, params);
if (!buffer) if (!buffer)
{ {
NazaraErrorFmt("failed to load buffer from file ({0})", filePath); NazaraErrorFmt("failed to load buffer from file ({0})", filePath);
return false; return {};
} }
SetBuffer(std::move(buffer)); std::shared_ptr<Sound> sound = std::make_shared<Sound>();
return true; sound->SetBuffer(std::move(buffer));
return sound;
} }
/*! /*!
@@ -164,17 +165,18 @@ namespace Nz
* *
* \remark Produces a NazaraError if loading failed * \remark Produces a NazaraError if loading failed
*/ */
bool Sound::LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params) std::shared_ptr<Sound> Sound::LoadFromMemory(const void* data, std::size_t size, const Params& params)
{ {
std::shared_ptr<SoundBuffer> buffer = SoundBuffer::LoadFromMemory(data, size, params); std::shared_ptr<SoundBuffer> buffer = SoundBuffer::LoadFromMemory(data, size, params);
if (!buffer) if (!buffer)
{ {
NazaraErrorFmt("failed to load buffer from memory ({0})", PointerToString(data)); NazaraErrorFmt("failed to load buffer from memory ({0})", PointerToString(data));
return false; return {};
} }
SetBuffer(std::move(buffer)); std::shared_ptr<Sound> sound = std::make_shared<Sound>();
return true; sound->SetBuffer(std::move(buffer));
return sound;
} }
/*! /*!
@@ -186,17 +188,18 @@ namespace Nz
* *
* \remark Produces a NazaraError if loading failed * \remark Produces a NazaraError if loading failed
*/ */
bool Sound::LoadFromStream(Stream& stream, const SoundBufferParams& params) std::shared_ptr<Sound> Sound::LoadFromStream(Stream& stream, const Params& params)
{ {
std::shared_ptr<SoundBuffer> buffer = SoundBuffer::LoadFromStream(stream, params); std::shared_ptr<SoundBuffer> buffer = SoundBuffer::LoadFromStream(stream, params);
if (!buffer) if (!buffer)
{ {
NazaraError("failed to load buffer from stream"); NazaraError("failed to load buffer from stream");
return false; return {};
} }
SetBuffer(std::move(buffer)); std::shared_ptr<Sound> sound = std::make_shared<Sound>();
return true; sound->SetBuffer(std::move(buffer));
return sound;
} }
/*! /*!

View File

@@ -32,6 +32,20 @@ namespace Nz
return true; return true;
} }
bool Serialize(SerializationContext& context, SoundBufferParams& params, TypeTag<SoundBufferParams>)
{
Serialize(context, params, TypeTag<ResourceParameters>());
Serialize(context, "forceMono", params.forceMono);
return true;
}
bool Unserialize(SerializationContext& context, SoundBufferParams* params, TypeTag<SoundBufferParams>)
{
Unserialize(context, params, TypeTag<ResourceParameters>());
Unserialize(context, "forceMono", &params->forceMono);
return params->IsValid();
}
/*! /*!
* \brief Constructs a SoundBuffer object * \brief Constructs a SoundBuffer object
* *

View File

@@ -18,7 +18,7 @@ namespace Nz
{ {
Unserialize(context, params, TypeTag<ResourceParameters>()); Unserialize(context, params, TypeTag<ResourceParameters>());
Unserialize(context, "forceMono", &params->forceMono); Unserialize(context, "forceMono", &params->forceMono);
return true; return params->IsValid();
} }
bool SoundStreamParams::IsValid() const bool SoundStreamParams::IsValid() const

View File

@@ -0,0 +1,52 @@
#include <Nazara/Core/AssetCatalogAppComponent.hpp>
#include <Nazara/Core/Serialization.hpp>
namespace Nz
{
bool Serialize(SerializationContext& context, const AssetHeaderLite& header, TypeTag<AssetHeaderLite>)
{
Serialize(context, "name", header.name);
Serialize(context, "path", header.path);
return true;
}
bool Unserialize(SerializationContext& context, AssetHeaderLite* header, TypeTag<AssetHeaderLite>)
{
Unserialize(context, "name", &header->name);
Unserialize(context, "path", &header->path);
return true;
}
void AddFile(std::set<AssetHeaderLite>& container, Nz::Stream& stream)
{
AssetHeaderLite header;
auto json = JsonSerializationContext::LoadFromStream(stream);
if (!json)
return;
if (!Unserialize(*json, "", &header))
return;
header.path = stream.GetPath();
container.insert(header);
}
void AssetCatalogAppComponent::AddFolder(std::string_view folder)
{
auto& fs = GetApp().GetComponent<FilesystemAppComponent>();
auto directory = fs.GetDirectory(folder);
if (!directory)
return;
directory->Foreach([&](std::string_view, const VirtualDirectory::Entry& entry) {
if (std::holds_alternative<VirtualDirectory::FileEntry>(entry))
{
auto& file = std::get<VirtualDirectory::FileEntry>(entry);
if (file.stream->GetPath().extension() == ".nzasset")
AddFile(m_assets, *file.stream.get());
}
}, true);
}
}

View File

@@ -0,0 +1,149 @@
#include <Nazara/Core/JsonSerialization.hpp>
#include <Nazara/Core/FilesystemAppComponent.hpp>
#include <Nazara/Core/ApplicationBase.hpp>
#include <nlohmann/json.hpp>
#include <stack>
namespace Nz
{
struct JsonImpl
{
nlohmann::json& Top() { return *stack.top(); }
bool Pop()
{
if (stack.empty())
{
NazaraAssert(stack.empty(), "Stack is empty");
return false;
}
stack.pop();
return true;
}
nlohmann::json json;
std::stack<nlohmann::json*> stack;
};
JsonSerializationContext::JsonSerializationContext()
: m_impl(std::make_unique<JsonImpl>())
{}
JsonSerializationContext::~JsonSerializationContext() {}
bool JsonSerializationContext::Load(const std::filesystem::path& path)
{
Nz::File file(path, Nz::OpenMode::Read);
return Load(file);
}
bool JsonSerializationContext::Load(Stream& stream)
{
if (!stream.IsReadable())
return false;
auto size = stream.GetSize();
std::vector<char> content(size);
stream.Read(content.data(), content.size());
m_impl->json = nlohmann::json::parse(content.begin(), content.end());
m_impl->stack.push(&m_impl->json);
return true;
}
bool JsonSerializationContext::PushObject(std::string_view name)
{
if (name.empty()) // special case if name is empty, don't push
return true;
if (!m_impl->Top().contains(name))
return false;
if (!m_impl->Top()[name].is_object())
{
NazaraAssert(m_impl->Top()[name].is_object(), "Value is not an object");
return false;
}
m_impl->stack.push(&m_impl->Top()[name]);
return true;
}
bool JsonSerializationContext::PopObject()
{
return m_impl->Pop();
}
bool JsonSerializationContext::PushArray(std::string_view name)
{
if (!m_impl->Top()[name].is_array())
{
NazaraAssert(m_impl->Top()[name].is_array(), "Value is not an array");
return false;
}
m_impl->stack.push(&m_impl->Top()[name]);
return true;
}
bool JsonSerializationContext::PopArray()
{
return m_impl->Pop();
}
#define DEF_SERIALIZE(Type, cond) \
bool JsonSerializationContext::Write(std::string_view name, Type value) \
{ \
m_impl->Top()[name] = value; \
return true; \
} \
bool JsonSerializationContext::Read(std::string_view name, Type* value) \
{ \
if (!m_impl->Top()[name].cond()) \
{ \
/*NazaraAssert(m_impl->Top()[name].cond(), "Value failed check: " #cond "()");*/\
return false; \
} \
*value = m_impl->Top()[name].get<Type>(); \
return true; \
} \
DEF_SERIALIZE(bool, is_boolean);
DEF_SERIALIZE(Nz::Int8, is_number);
DEF_SERIALIZE(Nz::Int16, is_number);
DEF_SERIALIZE(Nz::Int32, is_number);
DEF_SERIALIZE(Nz::Int64, is_number);
DEF_SERIALIZE(Nz::UInt8, is_number);
DEF_SERIALIZE(Nz::UInt16, is_number);
DEF_SERIALIZE(Nz::UInt32, is_number);
DEF_SERIALIZE(Nz::UInt64, is_number);
DEF_SERIALIZE(float, is_number);
DEF_SERIALIZE(double, is_number);
#undef DEF_SERIALIZE
bool JsonSerializationContext::Write(std::string_view name, const std::string& value)
{
m_impl->Top()[name] = value;
return true;
}
bool JsonSerializationContext::Read(std::string_view name, std::string* value)
{
if (!m_impl->Top()[name].is_string())
{
NazaraAssert(m_impl->Top()[name].is_string(), "Value failed check: is_string()");
return false;
}
*value = m_impl->Top()[name].get<std::string>();
return true;
}
std::shared_ptr<JsonSerializationContext> JsonSerializationContext::LoadFromStream(Stream& stream, const JsonSerializationContext::Params&)
{
std::shared_ptr<JsonSerializationContext> context = std::make_shared<JsonSerializationContext>();
if (context->Load(stream))
return context;
return {};
}
}

View File

@@ -32,7 +32,7 @@ TEST_CASE("VirtualDirectory", "[Core][VirtualDirectory]")
} }
if (name != "." && name != "..") if (name != "." && name != "..")
FAIL("Got file " << name); FAIL("Got file " << name);
}, true); }, false, true);
CHECK(dot); CHECK(dot);
CHECK(dotDot); CHECK(dotDot);

View File

@@ -107,7 +107,7 @@ local modules = {
remove_files("src/Nazara/Core/Posix/TimeImpl.cpp") remove_files("src/Nazara/Core/Posix/TimeImpl.cpp")
end end
end, end,
Packages = { "concurrentqueue", "entt", "frozen", "ordered_map", "stb", "utfcpp" }, Packages = { "concurrentqueue", "entt", "frozen", "ordered_map", "stb", "utfcpp", "nlohmann_json" },
PublicPackages = { "nazarautils" } PublicPackages = { "nazarautils" }
}, },
Graphics = { Graphics = {
@@ -284,7 +284,8 @@ add_requires(
"ordered_map", "ordered_map",
"nazarautils >=2024.01.25", "nazarautils >=2024.01.25",
"stb", "stb",
"utfcpp" "utfcpp",
"nlohmann_json"
) )
-- Don't link with system-installed libs on CI -- Don't link with system-installed libs on CI