Files
aevolution/src/world/generation.cpp
T

80 lines
3.0 KiB
C++

#include "evo/world/generation.hpp"
namespace evo::world {
namespace {
std::expected<void, GenerationError> validate(BaseDescriptor d) noexcept {
if (d.coordinate_version != coordinate_contract_version) {
return std::unexpected{GenerationError::unsupported_coordinates};
}
if (d.generator_version != 1) {
return std::unexpected{GenerationError::unsupported_generator};
}
if (d.material_version != 1) {
return std::unexpected{GenerationError::unsupported_materials};
}
if (d.edge != base_chunk_edge) {
return std::unexpected{GenerationError::unsupported_edge};
}
return {};
}
std::uint64_t mix(std::uint64_t value) noexcept {
value = (value ^ (value >> 30U)) * 0xbf58476d1ce4e5b9ULL;
value = (value ^ (value >> 27U)) * 0x94d049bb133111ebULL;
return value ^ (value >> 31U);
}
CellSample sample(std::uint64_t seed, VoxelAddress a) noexcept {
auto hash = mix(mix(seed ^ 0x4145564f47454e31ULL) ^ static_cast<std::uint64_t>(a.x));
hash = mix(hash ^ static_cast<std::uint64_t>(a.y));
const auto surface = static_cast<std::int64_t>(hash % 16U) - 8;
const std::uint16_t material = a.z >= surface ? 0 : (a.z >= surface - 3 ? 2 : 1);
// All constructed pairs obey CellSample's invariant by construction.
return *CellSample::create({material}, material == 0 ? 0 : fill_scale);
}
} // namespace
std::expected<std::string_view, GenerationError> material_name(std::uint32_t version,
MaterialId id) noexcept {
if (version != 1) {
return std::unexpected{GenerationError::unsupported_materials};
}
switch (id.value) {
case 0:
return "void";
case 1:
return "rock";
case 2:
return "regolith";
default:
return std::unexpected{GenerationError::unknown_material};
}
}
std::expected<CellSample, GenerationError> base_sample(BaseDescriptor d, VoxelAddress a) noexcept {
if (const auto valid = validate(d); !valid) {
return std::unexpected{valid.error()};
}
if (!lower_corner_mm(a)) {
return std::unexpected{GenerationError::invalid_voxel};
}
return sample(d.seed, a);
}
std::expected<std::vector<CellSample>, GenerationError> generate_base_chunk(BaseDescriptor d,
ChunkAddress a) {
if (const auto valid = validate(d); !valid) {
return std::unexpected{valid.error()};
}
const auto origin = join({a, {}}, base_chunk_edge);
if (!origin) {
return std::unexpected{GenerationError::invalid_chunk};
}
std::vector<CellSample> result;
result.reserve(base_chunk_cells);
for (std::int64_t z = 0; z < base_chunk_edge; ++z) {
for (std::int64_t y = 0; y < base_chunk_edge; ++y) {
for (std::int64_t x = 0; x < base_chunk_edge; ++x) {
result.push_back(sample(d.seed, {origin->x + x, origin->y + y, origin->z + z}));
}
}
}
return result;
}
} // namespace evo::world