5c4ca51905d4813040c777edfaad40460213ae68
[laserbrain_demo] / src / dataset.h
1 /** DataSet is a generic resource database with fast O(logn) lookups by name
2  * it can be used for texture managers, mesh managers, sound effect managers etc
3  *
4  * The constructor takes a load function and a destructor function to be called
5  * when a nonexistent resource is requested and needs to be loaded, and when
6  * the DataSet is destroyed. The destructor is optional and can be set to null
7  * if not needed.
8  *
9  * Requesting a resource works by simply calling get, example:
10  * ----------------------------------------------------------
11  * \code
12  * Texture *load_texture(const char *fname);
13  * void free_texture(Texture *tex);
14  *
15  * DataSet<Texture*> texman(load_texture, free_texture);
16  * Texture *foo = texman.get("foo.png");
17  * \endcode
18  */
19 #ifndef DATASET_H_
20 #define DATASET_H_
21
22 #include <vector>
23 #include <string>
24 #include <map>
25 #include <resman.h>
26
27 template <typename T>
28 class DataSet {
29 public:
30         typedef void (*LoadedCallbackFunc)(T, void*);
31
32 protected:
33         mutable std::map<std::string, T> data;
34         mutable struct resman *rman;
35
36         std::vector<std::pair<LoadedCallbackFunc, void*> > loaded_cb;
37
38         T (*create)();
39         bool (*load)(T, const char*);
40         bool (*done)(T);
41         void (*destroy)(T);
42
43         static int dataset_load_func(const char *fname, int id, void *cls);
44         static int dataset_done_func(int id, void *cls);
45         static void dataset_destroy_func(int id, void *cls);
46
47 public:
48         DataSet(T (*create_func)(), bool (*load_func)(T, const char*), bool (*done_func)(T) = 0, void (*destr_func)(T) = 0);
49         ~DataSet();
50
51         void clear();
52         void update();
53
54         T get(const char *name) const;
55
56         void add_loaded_callback(LoadedCallbackFunc func, void *cls = 0);
57         bool remove_loaded_callback(LoadedCallbackFunc func);
58 };
59
60 #include "dataset.inl"
61
62 #endif  // DATASET_H_