NazaraEngine/include/Nazara/Core/Asset.inl

61 lines
1.7 KiB
C++

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