dungeon_crawler
annotate prototype/src/dataset.h @ 75:b05ab29cd17d
color grading done
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Mon, 22 Oct 2012 03:55:00 +0300 |
parents | 7f52d6310317 |
children |
rev | line source |
---|---|
nuclear@48 | 1 #ifndef DATASET_H_ |
nuclear@48 | 2 #define DATASET_H_ |
nuclear@48 | 3 |
nuclear@48 | 4 #include <string.h> |
nuclear@48 | 5 #include <string> |
nuclear@48 | 6 #include <map> |
nuclear@48 | 7 #include <functional> |
nuclear@48 | 8 #include "datapath.h" |
nuclear@48 | 9 |
nuclear@48 | 10 template <typename T> |
nuclear@48 | 11 class DataSet { |
nuclear@48 | 12 private: |
nuclear@48 | 13 mutable std::map<std::string, T> data; |
nuclear@48 | 14 |
nuclear@48 | 15 std::function<T(const char*)> load; |
nuclear@48 | 16 std::function<void(T)> destroy; |
nuclear@48 | 17 |
nuclear@48 | 18 public: |
nuclear@48 | 19 DataSet(std::function<T(const char*)> load_func, std::function<void(T)> destr_func); |
nuclear@48 | 20 ~DataSet(); |
nuclear@48 | 21 |
nuclear@48 | 22 T get(const char *name) const; |
nuclear@48 | 23 }; |
nuclear@48 | 24 |
nuclear@48 | 25 template <typename T> |
nuclear@48 | 26 DataSet<T>::DataSet(std::function<T(const char*)> load_func, std::function<void(T)> destr_func) |
nuclear@48 | 27 { |
nuclear@48 | 28 load = load_func; |
nuclear@48 | 29 destroy = destr_func; |
nuclear@48 | 30 } |
nuclear@48 | 31 |
nuclear@48 | 32 template <typename T> |
nuclear@48 | 33 DataSet<T>::~DataSet() |
nuclear@48 | 34 { |
nuclear@48 | 35 if(destroy) { |
nuclear@48 | 36 for(auto it : data) { |
nuclear@48 | 37 destroy(it.second); |
nuclear@48 | 38 } |
nuclear@48 | 39 } |
nuclear@48 | 40 } |
nuclear@48 | 41 |
nuclear@48 | 42 template <typename T> |
nuclear@48 | 43 T DataSet<T>::get(const char *name) const |
nuclear@48 | 44 { |
nuclear@48 | 45 auto iter = data.find(name); |
nuclear@48 | 46 if(iter != data.end()) { |
nuclear@48 | 47 return iter->second; |
nuclear@48 | 48 } |
nuclear@48 | 49 |
nuclear@64 | 50 const char *fname, *slash; |
nuclear@48 | 51 if((slash = strrchr(name, '/'))) { |
nuclear@64 | 52 fname = slash + 1; |
nuclear@48 | 53 } else { |
nuclear@64 | 54 fname = name; |
nuclear@48 | 55 } |
nuclear@64 | 56 |
nuclear@64 | 57 std::string path = datafile_path(fname); |
nuclear@64 | 58 if(path.empty()) { |
nuclear@48 | 59 fprintf(stderr, "can't find data file: %s\n", name); |
nuclear@48 | 60 return 0; |
nuclear@48 | 61 } |
nuclear@48 | 62 |
nuclear@64 | 63 T res = load(path.c_str()); |
nuclear@48 | 64 if(res) { |
nuclear@48 | 65 data[name] = res; |
nuclear@48 | 66 } |
nuclear@48 | 67 return res; |
nuclear@48 | 68 } |
nuclear@48 | 69 |
nuclear@48 | 70 #endif // DATASET_H_ |