blob: 84b275dfe1779a0000d342e01acb1cbc50fde0bc (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
#pragma once
#include <memory>
#include <unordered_map>
#include "../Resource.h"
#include "../api/Asset.h"
#include "Manager.h"
namespace crepe {
/**
* \brief Owner of concrete Resource instances
*
* ResourceManager caches concrete Resource instances per Asset. Concrete resources are
* destroyed at the end of scenes by default, unless the game programmer marks them as
* persistent.
*/
class ResourceManager : public Manager {
public:
ResourceManager(Mediator & mediator);
virtual ~ResourceManager(); // dbg_trace
private:
//! Cache entry
struct CacheEntry {
//! Concrete resource instance
std::unique_ptr<Resource> resource = nullptr;
//! Prevent ResourceManager::clear from removing this entry
bool persistent = false;
};
//! Internal cache
std::unordered_map<const Asset, CacheEntry> resources;
/**
* \brief Ensure a cache entry exists for this asset and return a mutable reference to it
*
* \param asset Asset the concrete resource is instantiated from
*
* \returns Mutable reference to cache entry
*/
CacheEntry & get_entry(const Asset & asset);
public:
/**
* \brief Mark a resource as persistent (i.e. used across multiple scenes)
*
* \param asset Asset the concrete resource is instantiated from
* \param persistent Whether this resource is persistent (true=keep, false=destroy)
*/
void set_persistent(const Asset & asset, bool persistent);
/**
* \brief Retrieve reference to concrete Resource by Asset
*
* \param asset Asset the concrete resource is instantiated from
* \tparam Resource Concrete derivative of Resource
*
* This class instantiates the concrete resource if it is not yet stored in the internal
* cache, or returns a reference to the cached resource if it already exists.
*
* \returns Reference to concrete resource
*
* \throws std::runtime_error if the \c Resource parameter does not match with the actual
* type of the resource stored in the cache for this Asset
*/
template <typename Resource>
Resource & get(const Asset & asset);
//! Clear non-persistent resources from cache
void clear();
//! Clear all resources from cache regardless of persistence
void clear_all();
};
} // namespace crepe
#include "ResourceManager.hpp"
|