engine/include/resource_manager.h

62 lines
1.7 KiB
C
Raw Permalink Normal View History

2024-03-31 10:11:22 +00:00
#pragma once
2022-09-02 11:06:59 +00:00
2022-12-01 15:54:28 +00:00
#include <memory>
#include <stdexcept>
2023-04-29 14:22:25 +00:00
#include <string>
#include <unordered_map>
#include <vector>
2023-08-29 21:10:05 +00:00
#include <typeinfo>
#include "log.h"
#include "resources/mesh.h"
2022-09-02 11:06:59 +00:00
2022-10-06 10:30:44 +00:00
namespace engine {
2022-09-02 11:06:59 +00:00
2023-04-29 14:22:25 +00:00
class IResourceManager {
2024-03-31 10:11:22 +00:00
public:
virtual ~IResourceManager(){};
2023-04-29 14:22:25 +00:00
};
template <class T>
class ResourceManager : public IResourceManager {
2024-03-31 10:11:22 +00:00
public:
~ResourceManager() override { LOG_DEBUG("Destroying resource manager... '{}'", typeid(T).name()); }
std::shared_ptr<T> Add(const std::string& name, std::unique_ptr<T>&& resource)
{
if (resources_.contains(name) == false) {
std::shared_ptr<T> resource_shared(std::move(resource));
resources_.emplace(name, resource_shared);
return resource_shared;
}
else {
throw std::runtime_error("Cannot add a resource which already exists");
}
2023-04-29 14:22:25 +00:00
}
2024-03-31 10:11:22 +00:00
void AddPersistent(const std::string& name, std::unique_ptr<T>&& resource) { persistent_resources_.push_back(Add(name, std::move(resource))); }
std::shared_ptr<T> Get(const std::string& name)
{
if (resources_.contains(name)) {
std::weak_ptr<T> ptr = resources_.at(name);
if (ptr.expired() == false) {
return ptr.lock();
}
else {
resources_.erase(name);
}
}
// resource doesn't exist:
throw std::runtime_error("Resource doesn't exist: " + name);
return {};
2023-04-29 14:22:25 +00:00
}
2024-03-31 10:11:22 +00:00
private:
std::unordered_map<std::string, std::weak_ptr<T>> resources_{};
// This array owns persistent resources
std::vector<std::shared_ptr<T>> persistent_resources_{};
2023-04-29 14:22:25 +00:00
};
2024-03-31 10:11:22 +00:00
} // namespace engine