1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- #include <unordered_map>
- #include <vector>
- #include <fstream>
- #include <iostream>
- #include "BlockRegistry.h"
- static Block NULL_BLOCK(0, "null_block");
- static std::unordered_map<std::string, u16> registry;
- static std::vector<Block> idMap = {NULL_BLOCK};
- void BlockRegistry::loadFromFile(const std::string& path) {
- std::ifstream in;
- in.open(path);
- if(in.fail()) {
- std::cout << "cannot read blocks from file '" << path << "'" << std::endl;
- return;
- }
- std::string line;
- while(true) {
- std::getline(in, line, '\n');
- if(in.fail()) {
- break;
- }
- u16 id = idMap.size();
- idMap.emplace_back(id, line);
- registry[line] = id;
- }
- }
- const Block& BlockRegistry::getBlock(const std::string& name) {
- const std::unordered_map<std::string, u16>::const_iterator& iter = registry.find(name);
- if(iter == registry.end()) {
- return NULL_BLOCK;
- }
- return idMap[iter->second];
- }
- const Block& BlockRegistry::getBlock(u16 id) {
- if(id >= idMap.size()) {
- return NULL_BLOCK;
- }
- return idMap[id];
- }
|