#include "JsonRepository.h" #include #include #include #include #include #include #include #include #include using json = nlohmann::json; namespace kurator { namespace universe { template void maybe_to(const json& item, const char* member, Type& output) { if (item.contains(member)) item.at(member).get_to(output); } void from_json(const json& item, ShipType& ship) { item.at("name").get_to(ship.name); item.at("base_structure_points").get_to(ship.base_structure_points); item.at("base_armour_points").get_to(ship.base_armour_points); item.at("base_shield_points").get_to(ship.base_shield_points); item.at("max_speed").get_to(ship.max_speed); maybe_to(item, "base_structure_resists", ship.base_structure_resists); maybe_to(item, "base_armour_resists", ship.base_armour_resists); maybe_to(item, "base_shield_resists", ship.base_shield_resists); } void from_json(const json& item, TurretType& turret) { item.at("name").get_to(turret.name); maybe_to(item, "base_damage", turret.base_damage); maybe_to(item, "rounds", turret.rounds); maybe_to(item, "rate_of_fire", turret.rate_of_fire); maybe_to(item, "reload", turret.reload); maybe_to(item, "optimal_range", turret.optimal_range); maybe_to(item, "falloff_modifier", turret.falloff_modifier); maybe_to(item, "falloff_intensity", turret.falloff_intensity); } template std::map parse(const std::string& path) try { std::fstream file{path, file.binary | file.in}; // std::filesystem? if (!file.is_open()) throw "could not load universe part"; // FIXME: proper errors and handling above std::map map; const auto root = json::parse(file); for (const auto& item : root) { auto def = item.get(); map[def.name] = def; } return map; } catch (const json::parse_error&) { throw; } JsonRepository::JsonRepository(const std::string& path) { ships = parse(path + "/ship_types.json"); turrets = parse(path + "/turret_types.json"); } ShipType JsonRepository::ship_type() const { const auto it = ships.begin(); if (it == ships.end()) throw NotFound("any/default"); return it->second; } ShipType JsonRepository::ship_type(const std::string& id) const try { return ships.at(id); } catch (const std::out_of_range&) { throw NotFound(id); } TurretType JsonRepository::turret_type() const { const auto it = turrets.begin(); if (it == turrets.end()) throw NotFound("any/default"); return it->second; } TurretType JsonRepository::turret_type(const std::string& id) const try { return turrets.at(id); } catch (const std::out_of_range&) { throw NotFound(id); } void JsonRepository::for_ship_types(std::function func) const { for (const auto& [_, type] : ships) func(type); } void JsonRepository::for_turret_types(std::function func) const { for (const auto& [_, type] : turrets) func(type); } } // namespace universe } // namespace kurator