osb/source/game/StarVehicleDatabase.cpp

67 lines
2.0 KiB
C++
Raw Normal View History

2023-06-20 04:33:09 +00:00
#include "StarVehicleDatabase.hpp"
#include "StarVehicle.hpp"
#include "StarJsonExtra.hpp"
#include "StarRoot.hpp"
#include "StarAssets.hpp"
namespace Star {
VehicleDatabase::VehicleDatabase() {
auto assets = Root::singleton().assets();
2024-03-15 10:28:11 +00:00
auto& files = assets->scanExtension("vehicle");
2023-06-20 04:33:09 +00:00
assets->queueJsons(files);
2024-03-15 10:28:11 +00:00
for (auto& file : files) {
2023-06-20 04:33:09 +00:00
try {
auto config = assets->json(file);
String name = config.getString("name");
if (m_vehicles.contains(name))
2023-06-27 10:23:44 +00:00
throw VehicleDatabaseException::format("Repeat vehicle name '{}'", name);
2023-06-20 04:33:09 +00:00
m_vehicles.add(std::move(name), make_pair(std::move(file), std::move(config)));
2023-06-20 04:33:09 +00:00
} catch (StarException const& e) {
2023-06-27 10:23:44 +00:00
throw VehicleDatabaseException(strf("Error loading vehicle '{}'", file), e);
2023-06-20 04:33:09 +00:00
}
}
}
VehiclePtr VehicleDatabase::create(String const& vehicleName, Json const& extraConfig) const {
auto configPair = m_vehicles.ptr(vehicleName);
if (!configPair)
2023-06-27 10:23:44 +00:00
throw VehicleDatabaseException::format("No such vehicle named '{}'", vehicleName);
2023-06-20 04:33:09 +00:00
return make_shared<Vehicle>(configPair->second, configPair->first, extraConfig);
}
ByteArray VehicleDatabase::netStore(VehiclePtr const& vehicle) const {
DataStreamBuffer ds;
ds.write(vehicle->baseConfig().getString("name"));
ds.write(vehicle->dynamicConfig());
return ds.takeData();
}
VehiclePtr VehicleDatabase::netLoad(ByteArray const& netStore) const {
DataStreamBuffer ds(netStore);
String name = ds.read<String>();
auto dynamicConfig = ds.read<Json>();
auto vehicle = create(name, dynamicConfig);
return vehicle;
}
Json VehicleDatabase::diskStore(VehiclePtr const& vehicle) const {
return JsonObject{
{"name", vehicle->baseConfig().getString("name")},
{"dynamicConfig", vehicle->dynamicConfig()},
{"state", vehicle->diskStore()}
};
}
VehiclePtr VehicleDatabase::diskLoad(Json const& diskStore) const {
auto vehicle = create(diskStore.getString("name"), diskStore.get("dynamicConfig"));
vehicle->diskLoad(diskStore.get("state"));
return vehicle;
}
}