#include "settlement/core/voxel_region.hpp" #include #include #include #include #include #include #include #include namespace settlement { namespace { constexpr auto coordinate_min = std::int64_t{std::numeric_limits::min()}; constexpr auto coordinate_end = std::int64_t{std::numeric_limits::max()} + 1; bool valid_interval(std::int64_t lower, std::int64_t upper) noexcept { return lower >= coordinate_min && upper <= coordinate_end && lower < upper; } std::pair split_axis(std::int32_t value) noexcept { auto chunk = value / voxel_chunk_side; auto local = value % voxel_chunk_side; if (local < 0) { --chunk; local += voxel_chunk_side; } return {chunk, static_cast(local)}; } VoxelEndpoint chunk_origin(ChunkCoordinate coordinate) noexcept { return {std::int64_t{coordinate.x} * voxel_chunk_side, std::int64_t{coordinate.y} * voxel_chunk_side, std::int64_t{coordinate.z} * voxel_chunk_side}; } bool overlapping_axis(std::int64_t origin, std::int64_t lower, std::int64_t upper) noexcept { return origin < upper && origin + voxel_chunk_side > lower; } auto find_chunk(const VoxelDirectory& directory, ChunkCoordinate coordinate) noexcept { return std::lower_bound(directory.begin(), directory.end(), coordinate, [](const auto& entry, auto key) { return entry.coordinate < key; }); } class PayloadBudget { public: explicit PayloadBudget(std::size_t limit) : remaining_(limit) {} bool take(std::size_t count, std::size_t size) noexcept { const auto bytes = Void::Numeric::checked_mul(count, size); if (!bytes || *bytes > remaining_) return false; remaining_ -= *bytes; return true; } private: std::size_t remaining_; }; std::uint64_t terrain_hash(std::uint64_t seed, std::int64_t x, std::int64_t y) { std::array bytes{}; Void::Binary::Writer writer(bytes); if (!writer.writeLittle(seed) || !writer.writeLittle(voxel_generator_version) || !writer.writeLittle(std::uint32_t{1}) || !writer.writeLittle(x) || !writer.writeLittle(y) || !writer.writeLittle(std::int64_t{0})) { throw std::logic_error("voxel generator field layout exceeds its fixed buffer"); } return Void::Hash::fnv1a64(writer.written()); } std::int64_t surface_height(std::uint64_t seed, std::int32_t x, std::int32_t y) { // Interpolate absolute lattice columns to keep adjacent heights within one // voxel. Widened lattice endpoints also cover the final int32 column. const auto lattice = [](std::int32_t value) { std::int64_t quotient = value / 16; if (value % 16 < 0) --quotient; return quotient * 16; }; const auto x0 = lattice(x), y0 = lattice(y); const auto dx = std::int64_t{x} - x0, dy = std::int64_t{y} - y0; const auto height = [seed](std::int64_t a, std::int64_t b) { return static_cast(terrain_hash(seed, a, b) % 17) - 8; }; const auto numerator = height(x0, y0) * (16 - dx) * (16 - dy) + height(x0 + 16, y0) * dx * (16 - dy) + height(x0, y0 + 16) * (16 - dx) * dy + height(x0 + 16, y0 + 16) * dx * dy; auto result = numerator / 256; if (numerator % 256 < 0) --result; return result; } void add_neighbor(const VoxelRegion& region, std::vector& dirty, ChunkCoordinate coordinate, int axis, int delta) { std::array values{coordinate.x, coordinate.y, coordinate.z}; values[static_cast(axis)] += delta; if (values[static_cast(axis)] < coordinate_min || values[static_cast(axis)] >= coordinate_end) return; const ChunkCoordinate neighbor{static_cast(values[0]), static_cast(values[1]), static_cast(values[2])}; if (region.intersects(neighbor)) dirty.push_back(neighbor); } void canonicalize(std::vector& coordinates) { std::sort(coordinates.begin(), coordinates.end()); coordinates.erase(std::unique(coordinates.begin(), coordinates.end()), coordinates.end()); } } // namespace bool VoxelBounds::contains(VoxelPosition position) const noexcept { return position.x >= lower.x && position.x < upper.x && position.y >= lower.y && position.y < upper.y && position.z >= lower.z && position.z < upper.z; } VoxelAddress split_voxel(VoxelPosition position) noexcept { const auto [cx, lx] = split_axis(position.x); const auto [cy, ly] = split_axis(position.y); const auto [cz, lz] = split_axis(position.z); return {{cx, cy, cz}, {lx, ly, lz}}; } std::optional voxel_index(LocalVoxel local) noexcept { if (local.x >= voxel_chunk_side || local.y >= voxel_chunk_side || local.z >= voxel_chunk_side) return {}; return std::size_t{local.x} + 32 * (std::size_t{local.y} + 32 * std::size_t{local.z}); } std::optional join_voxel(ChunkCoordinate chunk, LocalVoxel local) noexcept { if (!voxel_index(local)) return {}; const auto origin = chunk_origin(chunk); const auto x = origin.x + local.x, y = origin.y + local.y, z = origin.z + local.z; if (x < coordinate_min || x >= coordinate_end || y < coordinate_min || y >= coordinate_end || z < coordinate_min || z >= coordinate_end) return {}; return VoxelPosition{static_cast(x), static_cast(y), static_cast(z)}; } bool valid_voxel_material(MaterialId material) noexcept { return material >= MaterialId::Air && material <= MaterialId::DoorOpen; } bool voxel_blocks_passage(MaterialId material) noexcept { return material == MaterialId::Soil || material == MaterialId::Stone || material == MaterialId::DoorClosed; } bool voxel_provides_support(MaterialId material) noexcept { return material == MaterialId::Soil || material == MaterialId::Stone; } VoxelChunk::VoxelChunk(std::uint64_t revision, std::span cells) : revision_(revision) { std::copy(cells.begin(), cells.end(), cells_.begin()); } PreparedVoxelChunk::PreparedVoxelChunk(VoxelRegionDescriptor descriptor, ChunkCoordinate coordinate, std::shared_ptr chunk) : descriptor_(descriptor), coordinate_(coordinate), chunk_(std::move(chunk)) {} VoxelRegion::VoxelRegion(VoxelRegionDescriptor descriptor, VoxelLimits limits) : descriptor_(descriptor), limits_(limits) { const auto& bounds = descriptor.bounds; if (!descriptor.id || descriptor.generator_version != voxel_generator_version || !valid_interval(bounds.lower.x, bounds.upper.x) || !valid_interval(bounds.lower.y, bounds.upper.y) || !valid_interval(bounds.lower.z, bounds.upper.z) || !limits.max_resident_chunks || !limits.max_edit_cells || limits.max_resident_bytes < sizeof(VoxelDirectory) || !limits.max_transaction_bytes) { throw std::invalid_argument("invalid voxel region descriptor or limits"); } directory_ = std::make_shared(); } std::size_t VoxelRegion::resident_bytes() const noexcept { return sizeof(VoxelDirectory) + directory_->size() * (sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)); } bool VoxelRegion::intersects(ChunkCoordinate coordinate) const noexcept { const auto origin = chunk_origin(coordinate); const auto& bounds = descriptor_.bounds; return overlapping_axis(origin.x, bounds.lower.x, bounds.upper.x) && overlapping_axis(origin.y, bounds.lower.y, bounds.upper.y) && overlapping_axis(origin.z, bounds.lower.z, bounds.upper.z); } ChunkStamp VoxelRegion::chunk_stamp(ChunkCoordinate coordinate) const noexcept { ChunkStamp result{descriptor_.id, coordinate, VoxelAvailability::Outside, 0}; if (!intersects(coordinate)) return result; const auto entry = find_chunk(*directory_, coordinate); result.availability = VoxelAvailability::Unavailable; if (entry != directory_->end() && entry->coordinate == coordinate) { result.availability = VoxelAvailability::Loaded; result.revision = entry->chunk->revision(); } return result; } bool VoxelRegion::matches(const ChunkStamp& stamp) const noexcept { return chunk_stamp(stamp.coordinate) == stamp; } VoxelSample VoxelRegion::sample(VoxelPosition position) const noexcept { const auto address = split_voxel(position); VoxelSample result{VoxelAvailability::Outside, MaterialId::Air, chunk_stamp(address.chunk)}; if (!descriptor_.bounds.contains(position)) return result; result.availability = result.stamp.availability; if (result.availability == VoxelAvailability::Loaded) { result.material = find_chunk(*directory_, address.chunk)->chunk->cells()[*voxel_index(address.local)]; } return result; } std::expected VoxelRegion::prepare_generated(ChunkCoordinate coordinate) const { if (!intersects(coordinate)) return std::unexpected(VoxelError::InvalidCoordinate); PayloadBudget budget(limits_.max_transaction_bytes); if (!budget.take(1, sizeof(VoxelChunk)) || !budget.take(voxel_chunk_cells, sizeof(MaterialId))) { return std::unexpected(VoxelError::LimitExceeded); } try { std::array cells{}; const auto origin = chunk_origin(coordinate); for (std::int32_t y = 0; y < voxel_chunk_side; ++y) { for (std::int32_t x = 0; x < voxel_chunk_side; ++x) { const auto px = static_cast(origin.x + x); const auto py = static_cast(origin.y + y); const auto height = surface_height(descriptor_.seed, px, py); for (std::int32_t z = 0; z < voxel_chunk_side; ++z) { const VoxelPosition position{px, py, static_cast(origin.z + z)}; if (!descriptor_.bounds.contains(position) || position.z > height) continue; const auto material = position.z > height - 3 ? MaterialId::Soil : MaterialId::Stone; const auto index = static_cast(x + 32 * (y + 32 * z)); cells[index] = material; } } } auto chunk = std::shared_ptr(new const VoxelChunk(1, cells)); return PreparedVoxelChunk(descriptor_, coordinate, std::move(chunk)); } catch (const std::bad_alloc&) { return std::unexpected(VoxelError::AllocationFailed); } } std::expected VoxelRegion::prepare_restored( ChunkCoordinate coordinate, std::uint64_t revision, std::span cells) const { if (!intersects(coordinate)) return std::unexpected(VoxelError::InvalidCoordinate); if (!revision) return std::unexpected(VoxelError::InvalidRevision); if (cells.size() != voxel_chunk_cells) return std::unexpected(VoxelError::InvalidSource); if (limits_.max_transaction_bytes < sizeof(VoxelChunk)) return std::unexpected(VoxelError::LimitExceeded); for (std::size_t i = 0; i < cells.size(); ++i) { if (!valid_voxel_material(cells[i])) return std::unexpected(VoxelError::InvalidMaterial); const auto position = join_voxel(coordinate, {static_cast(i % 32), static_cast((i / 32) % 32), static_cast(i / 1024)}); if (!position || (!descriptor_.bounds.contains(*position) && cells[i] != MaterialId::Air)) { return std::unexpected(VoxelError::InvalidCoordinate); } } try { const std::span fixed(cells.data(), voxel_chunk_cells); auto chunk = std::shared_ptr(new const VoxelChunk(revision, fixed)); return PreparedVoxelChunk(descriptor_, coordinate, std::move(chunk)); } catch (const std::bad_alloc&) { return std::unexpected(VoxelError::AllocationFailed); } } std::expected VoxelRegion::activate(std::span candidates) { if (candidates.empty()) return VoxelCommit{}; if (candidates.size() > limits_.max_resident_chunks - directory_->size()) { return std::unexpected(VoxelError::LimitExceeded); } const auto count = directory_->size() + candidates.size(); PayloadBudget resident(limits_.max_resident_bytes); PayloadBudget staging(limits_.max_transaction_bytes); const auto dirty_count = Void::Numeric::checked_mul(candidates.size(), std::size_t{7}); if (!dirty_count || !resident.take(1, sizeof(VoxelDirectory)) || !resident.take(count, sizeof(VoxelChunkEntry) + sizeof(VoxelChunk)) || !staging.take(1, sizeof(VoxelDirectory)) || !staging.take(count, sizeof(VoxelChunkEntry)) || !staging.take(candidates.size(), sizeof(VoxelChunk) + sizeof(ChunkStamp)) || !staging.take(*dirty_count, sizeof(ChunkCoordinate))) { return std::unexpected(VoxelError::LimitExceeded); } try { auto next = std::make_shared(); next->reserve(count); next->insert(next->end(), directory_->begin(), directory_->end()); VoxelCommit result; result.changed_chunks.reserve(candidates.size()); result.dirty_chunks.reserve(*dirty_count); for (const auto& candidate : candidates) { if (candidate.descriptor_ != descriptor_ || !candidate.chunk_ || !intersects(candidate.coordinate_)) { return std::unexpected(VoxelError::InvalidSource); } if (chunk_stamp(candidate.coordinate_).availability != VoxelAvailability::Unavailable) { return std::unexpected(VoxelError::Stale); } next->push_back({candidate.coordinate_, candidate.chunk_}); result.changed_chunks.push_back({descriptor_.id, candidate.coordinate_, VoxelAvailability::Loaded, candidate.chunk_->revision()}); result.dirty_chunks.push_back(candidate.coordinate_); for (int axis = 0; axis < 3; ++axis) { add_neighbor(*this, result.dirty_chunks, candidate.coordinate_, axis, -1); add_neighbor(*this, result.dirty_chunks, candidate.coordinate_, axis, 1); } } std::sort(next->begin(), next->end(), [](const auto& a, const auto& b) { return a.coordinate < b.coordinate; }); for (std::size_t i = 1; i < next->size(); ++i) { if ((*next)[i - 1].coordinate == (*next)[i].coordinate) return std::unexpected(VoxelError::Duplicate); } std::sort(result.changed_chunks.begin(), result.changed_chunks.end(), [](const auto& a, const auto& b) { return a.coordinate < b.coordinate; }); canonicalize(result.dirty_chunks); std::shared_ptr publication(std::move(next)); directory_.swap(publication); return result; } catch (const std::bad_alloc&) { return std::unexpected(VoxelError::AllocationFailed); } } std::expected VoxelRegion::edit(std::span edits) { if (edits.empty()) return VoxelCommit{}; if (edits.size() > limits_.max_edit_cells) return std::unexpected(VoxelError::LimitExceeded); PayloadBudget staging(limits_.max_transaction_bytes); if (!staging.take(edits.size(), sizeof(VoxelEdit))) return std::unexpected(VoxelError::LimitExceeded); try { std::vector ordered(edits.begin(), edits.end()); std::sort(ordered.begin(), ordered.end(), [](const auto& a, const auto& b) { const auto ca = split_voxel(a.position).chunk, cb = split_voxel(b.position).chunk; return ca == cb ? a.position < b.position : ca < cb; }); std::size_t changed_pages = 0, changed_cells = 0; std::optional last_changed; for (std::size_t i = 0; i < ordered.size(); ++i) { const auto& change = ordered[i]; if (i && ordered[i - 1].position == change.position) return std::unexpected(VoxelError::Duplicate); if (!valid_voxel_material(change.material)) return std::unexpected(VoxelError::InvalidMaterial); const auto current = sample(change.position); if (current.availability == VoxelAvailability::Outside) return std::unexpected(VoxelError::InvalidCoordinate); if (current.availability == VoxelAvailability::Unavailable) return std::unexpected(VoxelError::Unavailable); if (current.stamp.revision != change.expected_revision) return std::unexpected(VoxelError::Stale); if (current.material == change.material) continue; if (current.stamp.revision == std::numeric_limits::max()) { return std::unexpected(VoxelError::RevisionExhausted); } ++changed_cells; if (!last_changed || *last_changed != current.stamp.coordinate) { ++changed_pages; last_changed = current.stamp.coordinate; } } if (!changed_cells) return VoxelCommit{}; const auto dirty_count = Void::Numeric::checked_mul(changed_cells, std::size_t{4}); if (!dirty_count || !staging.take(1, sizeof(VoxelDirectory)) || !staging.take(directory_->size(), sizeof(VoxelChunkEntry)) || !staging.take(changed_pages, sizeof(VoxelChunk) + sizeof(ChunkStamp)) || !staging.take(voxel_chunk_cells, sizeof(MaterialId)) || !staging.take(changed_cells, sizeof(VoxelChange)) || !staging.take(*dirty_count, sizeof(ChunkCoordinate))) { return std::unexpected(VoxelError::LimitExceeded); } auto next = std::make_shared(*directory_); VoxelCommit result; result.changed_cells.reserve(changed_cells); result.changed_chunks.reserve(changed_pages); result.dirty_chunks.reserve(*dirty_count); for (std::size_t first = 0; first < ordered.size();) { const auto coordinate = split_voxel(ordered[first].position).chunk; auto last = first + 1; while (last < ordered.size() && split_voxel(ordered[last].position).chunk == coordinate) ++last; const auto old = find_chunk(*directory_, coordinate); std::array cells; std::copy(old->chunk->cells().begin(), old->chunk->cells().end(), cells.begin()); const auto count_before = result.changed_cells.size(); for (auto i = first; i < last; ++i) { const auto& change = ordered[i]; const auto local = split_voxel(change.position).local; auto& material = cells[*voxel_index(local)]; if (material == change.material) continue; result.changed_cells.push_back({change.position, material, change.material}); material = change.material; result.dirty_chunks.push_back(coordinate); const std::array axes{local.x, local.y, local.z}; for (int axis = 0; axis < 3; ++axis) { if (axes[static_cast(axis)] == 0) add_neighbor(*this, result.dirty_chunks, coordinate, axis, -1); if (axes[static_cast(axis)] == 31) add_neighbor(*this, result.dirty_chunks, coordinate, axis, 1); } } if (result.changed_cells.size() != count_before) { const auto revision = old->chunk->revision() + 1; auto chunk = std::shared_ptr(new const VoxelChunk(revision, cells)); const auto index = static_cast(old - directory_->begin()); (*next)[index].chunk = std::move(chunk); result.changed_chunks.push_back({descriptor_.id, coordinate, VoxelAvailability::Loaded, revision}); } first = last; } std::sort(result.changed_cells.begin(), result.changed_cells.end(), [](const auto& a, const auto& b) { return a.position < b.position; }); canonicalize(result.dirty_chunks); std::shared_ptr publication(std::move(next)); directory_.swap(publication); return result; } catch (const std::bad_alloc&) { return std::unexpected(VoxelError::AllocationFailed); } } } // namespace settlement