1 #ifndef MSP_GL_RESOURCEMANAGER_H_
2 #define MSP_GL_RESOURCEMANAGER_H_
4 #include <msp/core/inttypes.h>
5 #include <msp/core/mutex.h>
6 #include <msp/core/semaphore.h>
7 #include <msp/core/thread.h>
8 #include <msp/datafile/collection.h>
14 class ResourceObserver;
16 class resource_load_error: public std::runtime_error
19 resource_load_error(const std::string &, const std::string &);
20 resource_load_error(const std::string &, const std::exception &);
21 virtual ~resource_load_error() throw() { }
35 struct ResourceLocation
37 DataFile::Collection *collection;
41 ResourceLocation(DataFile::Collection &, const std::string &);
45 struct ManagedResource
58 ResourceLocation location;
61 Resource::AsyncLoader *loader;
65 std::vector<ResourceObserver *> observers;
67 ManagedResource(Resource &);
71 void finish_loading(bool);
72 void finish_loading();
75 void add_observer(ResourceObserver &);
76 void remove_observer(ResourceObserver &);
79 typedef std::list<ManagedResource *> LoadQueue;
81 class LoadingThread: public Thread
86 LoadQueue async_queue;
90 std::list<resource_load_error> error_queue;
91 Mutex data_size_mutex;
92 UInt64 loaded_data_size;
101 ManagedResource *front(LoadQueue &);
104 void add_resource(ManagedResource &);
105 void remove_resource(ManagedResource &);
107 bool try_remove_resource(ManagedResource &);
110 bool needs_work() const { return size<capacity; }
111 UInt64 get_and_reset_loaded_data_size();
116 typedef std::map<const Resource *, ManagedResource> ResourceMap;
118 LoadingPolicy policy;
120 mutable Mutex map_mutex;
121 ResourceMap resources;
123 UInt64 total_data_size;
126 unsigned min_retain_frames;
127 unsigned max_retain_frames;
128 unsigned next_unload;
129 LoadingThread thread;
135 void set_loading_policy(LoadingPolicy);
136 void set_async_loads(bool);
137 void set_size_limit(UInt64);
138 void set_min_retain_frames(unsigned);
139 void set_max_retain_frames(unsigned);
141 void add_resource(Resource &);
143 const ManagedResource &get_managed_resource(const Resource &) const;
144 ManagedResource &get_managed_resource(const Resource &);
146 void *get_data_for_resource(const Resource &r) { return &get_managed_resource(r); }
147 void set_resource_location(Resource &, DataFile::Collection &, const std::string &);
148 void set_resource_location(Resource &, const ResourceLocation &);
149 const ResourceLocation *get_resource_location(const Resource &) const;
150 void load_resource(Resource &);
151 bool is_resource_loaded(const Resource &) const;
152 void resource_used(const Resource &);
153 void remove_resource(Resource &);
155 void observe_resource(const Resource &, ResourceObserver &);
156 void unobserve_resource(const Resource &, ResourceObserver &);
160 void dispatch_work();
161 void unload_by_age();
162 void unload_by_size();
164 UInt64 get_total_data_size() const { return total_data_size; }
167 static bool age_order(ManagedResource *, ManagedResource *);