BlockRegistry.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include <unordered_map>
  2. #include <vector>
  3. #include <fstream>
  4. #include <iostream>
  5. #include "BlockRegistry.h"
  6. static Block NULL_BLOCK(0, "null_block");
  7. static std::unordered_map<std::string, u16> registry;
  8. static std::vector<Block> idMap = {NULL_BLOCK};
  9. void BlockRegistry::loadFromFile(const std::string& path) {
  10. std::ifstream in;
  11. in.open(path);
  12. if(in.fail()) {
  13. std::cout << "cannot read blocks from file '" << path << "'" << std::endl;
  14. return;
  15. }
  16. std::string line;
  17. while(true) {
  18. std::getline(in, line, '\n');
  19. if(in.fail()) {
  20. break;
  21. }
  22. u16 id = idMap.size();
  23. idMap.emplace_back(id, line);
  24. registry[line] = id;
  25. }
  26. }
  27. const Block& BlockRegistry::getBlock(const std::string& name) {
  28. const std::unordered_map<std::string, u16>::const_iterator& iter = registry.find(name);
  29. if(iter == registry.end()) {
  30. return NULL_BLOCK;
  31. }
  32. return idMap[iter->second];
  33. }
  34. const Block& BlockRegistry::getBlock(u16 id) {
  35. if(id >= idMap.size()) {
  36. return NULL_BLOCK;
  37. }
  38. return idMap[id];
  39. }