Complete M6.4 atomic environmental transfers
This commit is contained in:
@@ -0,0 +1,184 @@
|
||||
#include "evo/world/transfers.hpp"
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
namespace evo::world {
|
||||
namespace {
|
||||
constexpr auto ceiling = std::numeric_limits<std::uint64_t>::max();
|
||||
constexpr std::array<std::size_t, 7> mass_channels{3, 1, 2, 0, 1, 2, 3};
|
||||
bool accumulate(accounting::Inventory& sum, std::size_t field, std::uint64_t amount) noexcept {
|
||||
auto& value = field < 7 ? sum.matter[mass_channels[field]].value : sum.energy.value;
|
||||
if (amount > ceiling - value)
|
||||
return false;
|
||||
value += amount;
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
std::expected<std::unique_ptr<EnvironmentalTransfers>, TransferError>
|
||||
EnvironmentalTransfers::create(WorldIdentity identity, std::unique_ptr<FieldStore> fields,
|
||||
std::unique_ptr<ChunkStore> terrain,
|
||||
std::span<const OrganismResources> organisms,
|
||||
std::size_t byte_budget) {
|
||||
if (!fields || !terrain || organisms.empty() || organisms.size() > max_organisms ||
|
||||
fields->sites().size() > max_sites)
|
||||
return std::unexpected{TransferError::config};
|
||||
if (identity.world == 0 || identity.frame == 0 || fields->identity() != identity)
|
||||
return std::unexpected{TransferError::identity};
|
||||
const auto resident =
|
||||
sizeof(EnvironmentalTransfers) + fields->accounted_bytes() + terrain->accounted_bytes();
|
||||
if (resident > byte_budget || scratch_bytes > byte_budget - resident)
|
||||
return std::unexpected{TransferError::budget};
|
||||
accounting::Inventory sum{};
|
||||
for (std::size_t i = 0; i < fields->sites().size(); ++i) {
|
||||
const auto& site = fields->sites()[i];
|
||||
const auto location = split(site.voxel, base_chunk_edge);
|
||||
const auto view = terrain->view(location->chunk);
|
||||
if (!view)
|
||||
return std::unexpected{TransferError::terrain_binding};
|
||||
const auto cell = terrain->read(*view, location->local);
|
||||
if (!cell || cell->material() != site.substrate)
|
||||
return std::unexpected{TransferError::terrain_binding};
|
||||
for (std::size_t k = 0; k < field_count; ++k) {
|
||||
const auto value = fields->read(i, static_cast<Field>(k));
|
||||
if (value && !accumulate(sum, k, *value))
|
||||
return std::unexpected{TransferError::overflow};
|
||||
}
|
||||
}
|
||||
for (std::size_t i = 0; i < organisms.size(); ++i) {
|
||||
const auto& organism = organisms[i];
|
||||
if (organism.id.value == 0 || (i != 0 && organisms[i - 1].id >= organism.id))
|
||||
return std::unexpected{TransferError::config};
|
||||
for (std::size_t k = 0; k < field_count; ++k) {
|
||||
if (organism.balances[k] > organism.capacities[k])
|
||||
return std::unexpected{TransferError::capacity};
|
||||
if (!accumulate(sum, k, organism.balances[k]))
|
||||
return std::unexpected{TransferError::overflow};
|
||||
}
|
||||
}
|
||||
auto owner = std::unique_ptr<EnvironmentalTransfers>(new EnvironmentalTransfers);
|
||||
owner->fields_ = std::move(fields);
|
||||
owner->terrain_ = std::move(terrain);
|
||||
std::copy(organisms.begin(), organisms.end(), owner->organisms_.begin());
|
||||
owner->count_ = organisms.size();
|
||||
owner->budget_ = byte_budget;
|
||||
return owner;
|
||||
}
|
||||
std::size_t EnvironmentalTransfers::accounted_bytes() const noexcept {
|
||||
return sizeof(EnvironmentalTransfers) + fields_->accounted_bytes() +
|
||||
terrain_->accounted_bytes();
|
||||
}
|
||||
accounting::Inventory EnvironmentalTransfers::totals() const noexcept {
|
||||
accounting::Inventory sum{};
|
||||
for (std::size_t k = 0; k < field_count; ++k) {
|
||||
for (std::size_t i = 0; i < fields_->sites().size(); ++i) {
|
||||
const auto value = fields_->read(i, static_cast<Field>(k));
|
||||
if (value)
|
||||
(void)accumulate(sum, k, *value);
|
||||
}
|
||||
for (const auto& organism : organisms())
|
||||
(void)accumulate(sum, k, organism.balances[k]);
|
||||
}
|
||||
return sum; // Admission bounds totals; same-channel transfers preserve them.
|
||||
}
|
||||
std::expected<EnvironmentalReceipt, TransferError>
|
||||
EnvironmentalTransfers::commit(const EnvironmentalBatch& batch, const EnvironmentView& view,
|
||||
std::uint64_t current_tick) {
|
||||
if (batch.command == 0 || batch.legs.empty() || batch.legs.size() > max_legs)
|
||||
return std::unexpected{TransferError::invalid_request};
|
||||
if (view.fields_ != fields_.get() || view.terrain_ != terrain_.get() || view.samples_.empty())
|
||||
return std::unexpected{TransferError::wrong_owner};
|
||||
if (batch.command <= fields_->command_) {
|
||||
for (const auto& h : history_) {
|
||||
if (h.receipt.command != batch.command)
|
||||
continue;
|
||||
if (h.receipt.tick != batch.tick || h.receipt.legs != batch.legs.size() ||
|
||||
!std::equal(batch.legs.begin(), batch.legs.end(), h.legs.begin()))
|
||||
return std::unexpected{TransferError::conflict};
|
||||
return h.receipt;
|
||||
}
|
||||
return std::unexpected{TransferError::stale_command};
|
||||
}
|
||||
if (batch.tick != current_tick ||
|
||||
!validate_environment(view, *fields_, *terrain_, current_tick))
|
||||
return std::unexpected{TransferError::stale_view};
|
||||
std::array<std::array<std::uint64_t, max_sites>, field_count> staged{};
|
||||
std::array<bool, field_count> touched{};
|
||||
auto accounts = organisms_;
|
||||
const auto sites = fields_->sites();
|
||||
for (const auto& leg : batch.legs) {
|
||||
const auto k = static_cast<std::size_t>(leg.field);
|
||||
if (k >= field_count || leg.amount == 0 ||
|
||||
(leg.direction != ResourceDirection::to_organism &&
|
||||
leg.direction != ResourceDirection::to_environment))
|
||||
return std::unexpected{TransferError::invalid_request};
|
||||
const auto sample = std::lower_bound(
|
||||
view.samples_.begin(), view.samples_.end(), leg.voxel,
|
||||
[](const EnvironmentSample& s, VoxelAddress a) { return s.voxel < a; });
|
||||
if (sample == view.samples_.end() || sample->voxel != leg.voxel ||
|
||||
(view.mask_ & (1U << k)) == 0)
|
||||
return std::unexpected{TransferError::uncovered};
|
||||
if (!sample->fields[k])
|
||||
return std::unexpected{TransferError::missing};
|
||||
const auto site =
|
||||
std::lower_bound(sites.begin(), sites.end(), leg.voxel,
|
||||
[](const FieldSite& s, VoxelAddress a) { return s.voxel < a; });
|
||||
const auto i = static_cast<std::size_t>(site - sites.begin());
|
||||
const auto account = std::lower_bound(
|
||||
accounts.begin(), accounts.begin() + static_cast<std::ptrdiff_t>(count_), leg.organism,
|
||||
[](const OrganismResources& a, OrganismResourceId id) { return a.id < id; });
|
||||
if (account == accounts.begin() + static_cast<std::ptrdiff_t>(count_) ||
|
||||
account->id != leg.organism)
|
||||
return std::unexpected{TransferError::unknown_organism};
|
||||
if (!touched[k]) {
|
||||
for (std::size_t j = 0; j < sites.size(); ++j)
|
||||
staged[k][j] = fields_->fields_[k].get(j);
|
||||
touched[k] = true;
|
||||
}
|
||||
auto& environment = staged[k][i];
|
||||
auto& organism = account->balances[k];
|
||||
const bool uptake = leg.direction == ResourceDirection::to_organism;
|
||||
auto& source = uptake ? environment : organism;
|
||||
auto& destination = uptake ? organism : environment;
|
||||
const auto capacity =
|
||||
uptake ? account->capacities[k]
|
||||
: (leg.field == Field::water ? fields_->water_capacity(i)->value : ceiling);
|
||||
if (leg.amount > source)
|
||||
return std::unexpected{TransferError::insufficient};
|
||||
if (leg.amount > ceiling - destination)
|
||||
return std::unexpected{TransferError::overflow};
|
||||
if (destination + leg.amount > capacity)
|
||||
return std::unexpected{TransferError::capacity};
|
||||
source -= leg.amount;
|
||||
destination += leg.amount;
|
||||
}
|
||||
std::size_t new_bytes{};
|
||||
for (std::size_t k = 0; k < field_count; ++k)
|
||||
if (touched[k])
|
||||
new_bytes += FieldStore::page_bytes(std::span{staged[k]}.first(sites.size()));
|
||||
const auto resident = accounted_bytes();
|
||||
if (new_bytes > budget_ - resident - scratch_bytes ||
|
||||
new_bytes > fields_->budget_ - fields_->bytes_ - FieldStore::scratch_bytes)
|
||||
return std::unexpected{TransferError::budget};
|
||||
std::array<FieldStore::Channel, field_count> replacements;
|
||||
for (std::size_t k = 0; k < field_count; ++k)
|
||||
if (touched[k])
|
||||
replacements[k] = FieldStore::encode(std::span{staged[k]}.first(sites.size()));
|
||||
static_assert(std::is_nothrow_move_assignable_v<FieldStore::Channel>);
|
||||
// All checks and allocations complete. Single-owner, nonthrowing publication.
|
||||
for (std::size_t k = 0; k < field_count; ++k)
|
||||
if (touched[k]) {
|
||||
fields_->bytes_ -= fields_->fields_[k].bytes();
|
||||
fields_->bytes_ += replacements[k].bytes();
|
||||
fields_->fields_[k] = std::move(replacements[k]);
|
||||
}
|
||||
organisms_ = accounts;
|
||||
fields_->command_ = batch.command;
|
||||
auto& history = history_[next_history_];
|
||||
history.receipt = {batch.command, batch.tick, batch.legs.size()};
|
||||
std::copy(batch.legs.begin(), batch.legs.end(), history.legs.begin());
|
||||
next_history_ = (next_history_ + 1) % retained_commands;
|
||||
return history.receipt;
|
||||
}
|
||||
} // namespace evo::world
|
||||
Reference in New Issue
Block a user