Files
aevolution/src/world/transfer_codec.cpp
T

226 lines
10 KiB
C++

#include "evo/world/transfers.hpp"
#include <algorithm>
#include <bit>
#include <limits>
namespace evo::world {
namespace {
constexpr std::uint64_t magic = 0x31504c43564f4541ULL;
void put(WorldBytes& b, std::size_t& at, std::uint64_t v, unsigned n) {
for (unsigned i = 0; i < n; ++i) {
b.at(at++) = static_cast<std::uint8_t>(v & 255U);
v >>= 8U;
}
}
std::uint64_t hash(std::span<const std::uint8_t> b) {
std::uint64_t h = 14695981039346656037ULL;
for (auto v : b)
h = (h ^ v) * 1099511628211ULL;
return h;
}
struct Reader {
std::span<const std::uint8_t> bytes;
std::size_t at{};
bool ok{true};
std::uint64_t get(unsigned n) {
if (n > bytes.size() - at) {
ok = false;
return 0;
}
std::uint64_t v{};
for (unsigned i = 0; i < n; ++i)
v |= std::uint64_t{bytes[at++]} << (8U * i);
return v;
}
auto take(std::size_t n) {
if (n > bytes.size() - at) {
ok = false;
return std::span<const std::uint8_t>{};
}
auto s = bytes.subspan(at, n);
at += n;
return s;
}
};
} // namespace
std::expected<WorldBytes, TransferError> EnvironmentalTransfers::snapshot() const {
auto terrain = terrain_->snapshot(fields_->identity());
if (!terrain)
return std::unexpected{TransferError::format};
const auto fields = fields_->snapshot();
std::array<const History*, retained_commands> ordered{};
std::size_t count{};
for (const auto& h : history_)
if (h.receipt.command != 0)
ordered[count++] = &h;
std::sort(ordered.begin(), ordered.begin() + static_cast<std::ptrdiff_t>(count),
[](const auto* a, const auto* b) { return a->receipt.command < b->receipt.command; });
std::size_t length = 64 + terrain->size() + fields.size() + count_ * 168;
for (std::size_t i = 0; i < count; ++i)
length += 20 + 42 * ordered[i]->receipt.legs;
if (length > max_snapshot_bytes)
return std::unexpected{TransferError::budget};
WorldBytes out(length);
std::size_t at{};
put(out, at, magic, 8);
put(out, at, 1, 4);
put(out, at, length, 4);
put(out, at, fields_->identity().world, 8);
put(out, at, fields_->identity().frame, 8);
put(out, at, adoption_command_, 8);
put(out, at, count_, 4);
put(out, at, count, 4);
put(out, at, terrain->size(), 4);
put(out, at, fields.size(), 4);
std::copy(terrain->begin(), terrain->end(), out.begin() + static_cast<std::ptrdiff_t>(at));
at += terrain->size();
std::copy(fields.begin(), fields.end(), out.begin() + static_cast<std::ptrdiff_t>(at));
at += fields.size();
for (const auto& a : organisms()) {
put(out, at, a.id.value, 8);
for (auto v : a.balances)
put(out, at, v, 8);
for (auto v : a.capacities)
put(out, at, v, 8);
}
for (std::size_t i = 0; i < count; ++i) {
const auto& h = *ordered[i];
put(out, at, h.receipt.command, 8);
put(out, at, h.receipt.tick, 8);
put(out, at, h.receipt.legs, 4);
for (const auto& l : std::span{h.legs}.first(h.receipt.legs)) {
put(out, at, std::bit_cast<std::uint64_t>(l.voxel.x), 8);
put(out, at, std::bit_cast<std::uint64_t>(l.voxel.y), 8);
put(out, at, std::bit_cast<std::uint64_t>(l.voxel.z), 8);
put(out, at, l.organism.value, 8);
put(out, at, static_cast<std::uint8_t>(l.field), 1);
put(out, at, static_cast<std::uint8_t>(l.direction), 1);
put(out, at, l.amount, 8);
}
}
put(out, at, hash(std::span{out}.first(length - 8)), 8);
if (at != length)
return std::unexpected{TransferError::format};
return out;
}
std::expected<std::unique_ptr<EnvironmentalTransfers>, TransferError>
EnvironmentalTransfers::restore(std::span<const std::uint8_t> bytes, WorldIdentity identity,
std::size_t budget, std::size_t field_budget,
std::size_t terrain_budget) {
if (bytes.size() < 64 || bytes.size() > max_snapshot_bytes)
return std::unexpected{TransferError::format};
Reader r{bytes.first(bytes.size() - 8)}, tail{bytes.last(8)};
if (r.get(8) != magic)
return std::unexpected{TransferError::format};
if (r.get(4) != 1)
return std::unexpected{TransferError::version};
if (r.get(4) != bytes.size())
return std::unexpected{TransferError::format};
if (hash(r.bytes) != tail.get(8))
return std::unexpected{TransferError::checksum};
if (WorldIdentity{r.get(8), r.get(8)} != identity || identity.world == 0 || identity.frame == 0)
return std::unexpected{TransferError::identity};
const auto adoption = r.get(8), count = r.get(4), records = r.get(4), terrain_length = r.get(4),
field_length = r.get(4);
if (count == 0 || count > max_organisms || records > retained_commands ||
terrain_length > max_world_snapshot_bytes || field_length > FieldStore::max_snapshot_bytes)
return std::unexpected{TransferError::format};
const auto terrain_bytes = r.take(static_cast<std::size_t>(terrain_length));
const auto field_bytes = r.take(static_cast<std::size_t>(field_length));
if (!r.ok || count * 168 + records * 62 > r.bytes.size() - r.at)
return std::unexpected{TransferError::format};
if (budget < sizeof(EnvironmentalTransfers) + scratch_bytes)
return std::unexpected{TransferError::budget};
const auto available = budget - sizeof(EnvironmentalTransfers) - scratch_bytes;
auto fields = FieldStore::restore(field_bytes, identity, std::min(field_budget, available));
if (!fields)
return std::unexpected{fields.error() == FieldError::budget ? TransferError::budget
: TransferError::format};
if ((*fields)->sites().size() > max_sites)
return std::unexpected{TransferError::config};
auto terrain =
ChunkStore::restore(terrain_bytes, identity,
std::min(terrain_budget, available - (*fields)->accounted_bytes()));
if (!terrain)
return std::unexpected{terrain.error() == WorldCodecError::budget ? TransferError::budget
: TransferError::format};
std::array<OrganismResources, max_organisms> accounts{};
for (auto& a : std::span{accounts}.first(static_cast<std::size_t>(count))) {
a.id = {r.get(8)};
for (auto& v : a.balances)
v = r.get(8);
for (auto& v : a.capacities)
v = r.get(8);
}
auto out = create(identity, std::move(*fields), std::move(*terrain),
std::span{accounts}.first(static_cast<std::size_t>(count)), budget);
if (!out)
return out;
auto& o = **out;
o.adoption_command_ = adoption;
std::uint64_t previous = adoption;
for (std::size_t i = 0; i < records; ++i) {
auto& h = o.history_[i];
h.receipt = {r.get(8), r.get(8), static_cast<std::size_t>(r.get(4))};
if (!r.ok || h.receipt.command <= previous || h.receipt.legs == 0 ||
h.receipt.legs > max_legs)
return std::unexpected{TransferError::format};
previous = h.receipt.command;
for (auto& l : std::span{h.legs}.first(h.receipt.legs)) {
l.voxel = {std::bit_cast<std::int64_t>(r.get(8)), std::bit_cast<std::int64_t>(r.get(8)),
std::bit_cast<std::int64_t>(r.get(8))};
l.organism = {r.get(8)};
const auto field = r.get(1), direction = r.get(1);
l.amount = r.get(8);
if (!r.ok || field >= field_count || direction > 1 || l.amount == 0)
return std::unexpected{TransferError::format};
l.field = static_cast<Field>(field);
l.direction = static_cast<ResourceDirection>(direction);
}
}
if (!r.ok || r.at != r.bytes.size() || previous != o.fields_->last_command())
return std::unexpected{TransferError::format};
// Reverse retained history against current state: every predecessor must be possible.
std::array<std::array<std::uint64_t, max_sites>, field_count> values{};
const auto sites = o.fields_->sites();
for (std::size_t k = 0; k < field_count; ++k)
for (std::size_t j = 0; j < sites.size(); ++j) {
auto v = o.fields_->read(j, static_cast<Field>(k));
if (v)
values[k][j] = *v;
}
for (std::size_t n = static_cast<std::size_t>(records); n > 0; --n) {
const auto& h = o.history_[n - 1];
for (std::size_t m = h.receipt.legs; m > 0; --m) {
const auto& l = h.legs[m - 1];
const auto site =
std::lower_bound(sites.begin(), sites.end(), l.voxel,
[](const FieldSite& s, VoxelAddress v) { return s.voxel < v; });
const auto end = accounts.begin() + static_cast<std::ptrdiff_t>(count);
const auto a = std::lower_bound(
accounts.begin(), end, l.organism,
[](const OrganismResources& x, OrganismResourceId v) { return x.id < v; });
if (site == sites.end() || site->voxel != l.voxel || a == end || a->id != l.organism)
return std::unexpected{TransferError::format};
const auto j = static_cast<std::size_t>(site - sites.begin()),
k = static_cast<std::size_t>(l.field);
if (!o.fields_->read(j, l.field))
return std::unexpected{TransferError::format};
const bool uptake = l.direction == ResourceDirection::to_organism;
auto& source = uptake ? a->balances[k] : values[k][j];
auto& destination = uptake ? values[k][j] : a->balances[k];
const auto cap =
uptake ? (l.field == Field::water ? o.fields_->water_capacity(j)->value
: std::numeric_limits<std::uint64_t>::max())
: a->capacities[k];
if (source < l.amount || l.amount > cap - destination)
return std::unexpected{TransferError::format};
source -= l.amount;
destination += l.amount;
}
}
o.next_history_ = static_cast<std::size_t>(records) % retained_commands;
return out;
}
} // namespace evo::world