BlockRegistry.cpp 1.3 KB

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