307 lines
16 KiB
C++
307 lines
16 KiB
C++
#include "settlement/core/voxel_navigation.hpp"
|
|
#include <Void/Algorithms/Graph.hpp>
|
|
#include <Void/Math/Numeric.hpp>
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <cstdint>
|
|
#include <limits>
|
|
#include <new>
|
|
#include <stdexcept>
|
|
|
|
namespace settlement {
|
|
namespace {
|
|
using Status = VoxelNavigationStatus;
|
|
struct NavigationFailure { Status status; };
|
|
|
|
std::optional<VoxelPosition> offset(VoxelPosition p, int x, int y, int z) noexcept {
|
|
const auto nx = std::int64_t{p.x} + x, ny = std::int64_t{p.y} + y, nz = std::int64_t{p.z} + z;
|
|
constexpr auto low = std::numeric_limits<std::int32_t>::min();
|
|
constexpr auto high = std::numeric_limits<std::int32_t>::max();
|
|
if (nx < low || nx > high || ny < low || ny > high || nz < low || nz > high) return {};
|
|
return VoxelPosition{static_cast<std::int32_t>(nx), static_cast<std::int32_t>(ny), static_cast<std::int32_t>(nz)};
|
|
}
|
|
|
|
bool valid_bounds(const VoxelBounds& b, const VoxelBounds& region) noexcept {
|
|
return b.lower.x < b.upper.x && b.lower.y < b.upper.y && b.lower.z < b.upper.z &&
|
|
b.lower.x >= region.lower.x && b.lower.y >= region.lower.y && b.lower.z >= region.lower.z &&
|
|
b.upper.x <= region.upper.x && b.upper.y <= region.upper.y && b.upper.z <= region.upper.z;
|
|
}
|
|
|
|
class Queries {
|
|
public:
|
|
Queries(const VoxelRegion& world, const Void::Uuid::Uuid& session,
|
|
VoxelNavigationLimits limits, std::stop_token stop)
|
|
: world_(world), limits_(limits), stop_(stop), reads{world.descriptor().id, session, {}} {
|
|
if (session.is_nil()) throw NavigationFailure{Status::InvalidInput};
|
|
if (limits.max_dependencies > reads.chunks.max_size()) throw NavigationFailure{Status::LimitExceeded};
|
|
const auto bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp));
|
|
if (!bytes || *bytes > limits.max_scratch_bytes) throw NavigationFailure{Status::LimitExceeded};
|
|
reads.chunks.reserve(limits.max_dependencies);
|
|
}
|
|
|
|
VoxelSample sample(VoxelPosition p) {
|
|
if (stop_.stop_requested()) throw NavigationFailure{Status::Cancelled};
|
|
if (samples_ == limits_.max_samples) throw NavigationFailure{Status::LimitExceeded};
|
|
++samples_;
|
|
auto value = world_.sample(p);
|
|
auto at = std::lower_bound(reads.chunks.begin(), reads.chunks.end(), value.stamp.coordinate,
|
|
[](const auto& stamp, const auto& coordinate) { return stamp.coordinate < coordinate; });
|
|
if (at == reads.chunks.end() || at->coordinate != value.stamp.coordinate) {
|
|
if (reads.chunks.size() == limits_.max_dependencies) throw NavigationFailure{Status::LimitExceeded};
|
|
reads.chunks.insert(at, value.stamp);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
Status standing(VoxelPosition foot) {
|
|
const auto above = offset(foot, 0, 0, 1), below = offset(foot, 0, 0, -1);
|
|
if (!above || !below) return Status::Unreachable;
|
|
const auto body = sample(foot), head = sample(*above), support = sample(*below);
|
|
// A known obstruction is conclusive even if another cell is unavailable.
|
|
if (body.availability == VoxelAvailability::Outside || head.availability == VoxelAvailability::Outside ||
|
|
support.availability == VoxelAvailability::Outside ||
|
|
(body.availability == VoxelAvailability::Loaded && voxel_blocks_passage(body.material)) ||
|
|
(head.availability == VoxelAvailability::Loaded && voxel_blocks_passage(head.material)) ||
|
|
(support.availability == VoxelAvailability::Loaded && !voxel_provides_support(support.material))) return Status::Unreachable;
|
|
if (body.availability == VoxelAvailability::Unavailable || head.availability == VoxelAvailability::Unavailable ||
|
|
support.availability == VoxelAvailability::Unavailable) return Status::Unavailable;
|
|
return Status::Reachable;
|
|
}
|
|
|
|
Status transition(VoxelPosition from, VoxelPosition to) {
|
|
const auto dx = std::int64_t{to.x} - from.x, dy = std::int64_t{to.y} - from.y;
|
|
const auto dz = std::int64_t{to.z} - from.z;
|
|
if (!((dx == -1 || dx == 1) && dy == 0) && !((dy == -1 || dy == 1) && dx == 0)) return Status::Unreachable;
|
|
if (dz < -1 || dz > 1) return Status::Unreachable;
|
|
const auto first = standing(from), second = standing(to);
|
|
Status swept = Status::Reachable;
|
|
if (dz != 0) {
|
|
const auto upper = offset(dz > 0 ? from : to, 0, 0, 2);
|
|
if (!upper) return Status::Unreachable;
|
|
const auto cell = sample(*upper);
|
|
if (cell.availability == VoxelAvailability::Outside ||
|
|
(cell.availability == VoxelAvailability::Loaded && voxel_blocks_passage(cell.material))) swept = Status::Unreachable;
|
|
else if (cell.availability == VoxelAvailability::Unavailable) swept = Status::Unavailable;
|
|
}
|
|
if (first == Status::Unreachable || second == Status::Unreachable || swept == Status::Unreachable) return Status::Unreachable;
|
|
if (first == Status::Unavailable || second == Status::Unavailable || swept == Status::Unavailable) return Status::Unavailable;
|
|
return Status::Reachable;
|
|
}
|
|
|
|
const VoxelRegion& world_;
|
|
VoxelNavigationLimits limits_;
|
|
std::stop_token stop_;
|
|
VoxelReadSet reads;
|
|
private:
|
|
std::size_t samples_ = 0;
|
|
};
|
|
|
|
struct NeighborList {
|
|
std::array<std::size_t, 12> values{};
|
|
std::size_t size = 0;
|
|
auto begin() const { return values.begin(); }
|
|
auto end() const { return values.begin() + static_cast<std::ptrdiff_t>(size); }
|
|
};
|
|
|
|
class WalkingGraph {
|
|
public:
|
|
WalkingGraph(Queries& queries, VoxelBounds bounds, std::size_t sx, std::size_t sy, std::size_t count)
|
|
: queries_(queries), bounds_(bounds), sx_(sx), sy_(sy), count_(count) {}
|
|
std::size_t vertex_count() const noexcept { return count_; }
|
|
std::size_t index(VoxelPosition p) const noexcept {
|
|
return static_cast<std::size_t>(std::int64_t{p.x} - bounds_.lower.x) + sx_ *
|
|
(static_cast<std::size_t>(std::int64_t{p.y} - bounds_.lower.y) + sy_ *
|
|
static_cast<std::size_t>(std::int64_t{p.z} - bounds_.lower.z));
|
|
}
|
|
VoxelPosition position(std::size_t i) const noexcept {
|
|
return {static_cast<std::int32_t>(bounds_.lower.x + static_cast<std::int64_t>(i % sx_)),
|
|
static_cast<std::int32_t>(bounds_.lower.y + static_cast<std::int64_t>((i / sx_) % sy_)),
|
|
static_cast<std::int32_t>(bounds_.lower.z + static_cast<std::int64_t>(i / (sx_ * sy_)))};
|
|
}
|
|
NeighborList neighbors(std::size_t i) const {
|
|
NeighborList result;
|
|
const auto from = position(i);
|
|
// This is lexicographic VoxelPosition order, including all step heights.
|
|
constexpr std::array<std::array<int, 2>, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}};
|
|
for (auto direction : directions) for (int dz = -1; dz <= 1; ++dz) {
|
|
const auto to = offset(from, direction[0], direction[1], dz);
|
|
if (!to) continue;
|
|
const auto state = queries_.transition(from, *to);
|
|
// Only inconclusive edges out of reached vertices can extend the
|
|
// search into missing data. Raw reads may already have been ruled
|
|
// out by a known wall, floor or obstructed swept body volume.
|
|
if (state == Status::Unavailable) unavailable = true;
|
|
if (state != Status::Reachable) continue;
|
|
if (!bounds_.contains(*to)) { boundary = true; continue; }
|
|
result.values[result.size++] = index(*to);
|
|
}
|
|
return result;
|
|
}
|
|
mutable bool boundary = false;
|
|
mutable bool unavailable = false;
|
|
private:
|
|
Queries& queries_;
|
|
VoxelBounds bounds_;
|
|
std::size_t sx_, sy_, count_;
|
|
};
|
|
|
|
VoxelPathResult search(Queries& queries, const VoxelPathRequest& request,
|
|
std::span<const VoxelPosition> goals, std::span<const VoxelPosition> omitted = {}) {
|
|
VoxelPathResult result;
|
|
if (goals.empty() && omitted.empty()) return result;
|
|
const auto& limits = request.limits;
|
|
if (omitted.size() > limits.max_goals || goals.size() > limits.max_goals - omitted.size()) {
|
|
result.status = Status::LimitExceeded; return result;
|
|
}
|
|
for (auto goal : goals) if (!request.search_bounds.contains(goal)) return result;
|
|
const auto sx = static_cast<std::size_t>(request.search_bounds.upper.x - request.search_bounds.lower.x);
|
|
const auto sy = static_cast<std::size_t>(request.search_bounds.upper.y - request.search_bounds.lower.y);
|
|
const auto sz = static_cast<std::size_t>(request.search_bounds.upper.z - request.search_bounds.lower.z);
|
|
const auto count = Void::Numeric::checked_mul(sx, sy).and_then(
|
|
[sz](auto xy) { return Void::Numeric::checked_mul(xy, sz); });
|
|
// Void BFS retains four size_t vectors plus visited. Route construction and
|
|
// the read-set reserve coexist with them. No adjacency matrix is allocated.
|
|
const auto vertex_bytes = count.and_then([](auto size) {
|
|
return Void::Numeric::checked_mul(size, 4 * sizeof(std::size_t) + 1 + sizeof(VoxelPosition));
|
|
});
|
|
const auto read_bytes = Void::Numeric::checked_mul(limits.max_dependencies, sizeof(ChunkStamp));
|
|
if (!count || *count > limits.max_vertices || !vertex_bytes || !read_bytes ||
|
|
*count > std::vector<std::size_t>{}.max_size() ||
|
|
*count > std::vector<std::uint8_t>{}.max_size() ||
|
|
*count > std::vector<VoxelPosition>{}.max_size()) {
|
|
result.status = Status::LimitExceeded; return result;
|
|
}
|
|
const auto bytes = Void::Numeric::checked_add(*vertex_bytes, *read_bytes);
|
|
if (!bytes || *bytes > limits.max_scratch_bytes) {
|
|
result.status = Status::LimitExceeded; return result;
|
|
}
|
|
const auto start_state = queries.standing(request.start);
|
|
if (start_state != Status::Reachable) { result.status = start_state; return result; }
|
|
WalkingGraph graph(queries, request.search_bounds, sx, sy, *count);
|
|
const Void::Algorithms::WorkLimits work{
|
|
limits.max_vertices, limits.max_steps, limits.max_scratch_bytes - *read_bytes, 1};
|
|
auto traversal = Void::Algorithms::bfs(graph, graph.index(request.start), work, queries.stop_);
|
|
if (!traversal) {
|
|
result.status = traversal.error().code == Void::Algorithms::AlgorithmError::Code::cancelled ? Status::Cancelled : Status::LimitExceeded;
|
|
return result;
|
|
}
|
|
result.visited = traversal->order.size();
|
|
std::size_t distance = Void::Algorithms::TraversalResult::npos;
|
|
bool possible_goal = false;
|
|
for (auto goal : goals) {
|
|
// Explicit validation also covers the library's start==target fast path.
|
|
const auto standing = queries.standing(goal);
|
|
possible_goal = possible_goal || standing != Status::Unreachable;
|
|
if (standing != Status::Reachable) continue;
|
|
const auto cost = traversal->depth[graph.index(goal)];
|
|
if (cost < distance || (cost == distance && cost != Void::Algorithms::TraversalResult::npos &&
|
|
(!result.goal || goal < *result.goal))) { distance = cost; result.goal = goal; }
|
|
}
|
|
if (!result.goal) {
|
|
// Interaction contacts outside the selected window still matter to a
|
|
// global negative. Their feasibility cannot manufacture a frontier;
|
|
// BFS must also have reached a valid exit or an unresolved transition.
|
|
for (auto goal : omitted) {
|
|
const auto standing = queries.standing(goal);
|
|
possible_goal = possible_goal || standing != Status::Unreachable;
|
|
}
|
|
result.status = Status::Unreachable;
|
|
if (possible_goal) {
|
|
if (graph.unavailable) result.status = Status::Unavailable;
|
|
else if (graph.boundary) result.status = Status::SearchBoundary;
|
|
}
|
|
return result;
|
|
}
|
|
result.status = Status::Reachable;
|
|
result.cost = distance;
|
|
result.route.reserve(distance);
|
|
auto vertex = graph.index(*result.goal);
|
|
const auto start = graph.index(request.start);
|
|
while (vertex != start) {
|
|
result.route.push_back(graph.position(vertex));
|
|
vertex = traversal->parent[vertex];
|
|
}
|
|
std::reverse(result.route.begin(), result.route.end());
|
|
return result;
|
|
}
|
|
|
|
template<class Function>
|
|
VoxelTraversalResult check(const VoxelRegion& world, const Void::Uuid::Uuid& session,
|
|
VoxelNavigationLimits limits, std::stop_token stop, Function&& function) {
|
|
VoxelTraversalResult result;
|
|
result.consulted = {world.descriptor().id, session, {}};
|
|
try {
|
|
Queries queries(world, session, limits, stop);
|
|
try { result.status = function(queries); }
|
|
catch (const NavigationFailure& failure) { result.status = failure.status; }
|
|
result.consulted = std::move(queries.reads);
|
|
} catch (const NavigationFailure& failure) { result.status = failure.status; }
|
|
catch (const std::length_error&) { result.status = Status::LimitExceeded; }
|
|
catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; }
|
|
return result;
|
|
}
|
|
|
|
VoxelPathResult path(const VoxelRegion& world, const VoxelPathRequest& request,
|
|
std::optional<VoxelPosition> target, std::stop_token stop) {
|
|
VoxelPathResult result;
|
|
result.consulted = {world.descriptor().id, request.session, {}};
|
|
if (request.region != world.descriptor().id || request.session.is_nil() ||
|
|
!valid_bounds(request.search_bounds, world.descriptor().bounds) ||
|
|
!request.search_bounds.contains(request.start)) return result;
|
|
try {
|
|
Queries queries(world, request.session, request.limits, stop);
|
|
try {
|
|
if (target) {
|
|
const auto cell = queries.sample(*target);
|
|
if (cell.availability != VoxelAvailability::Loaded) {
|
|
result.status = cell.availability == VoxelAvailability::Unavailable ? Status::Unavailable : Status::InvalidInput;
|
|
} else {
|
|
std::array<VoxelPosition, 10> goals{};
|
|
std::array<VoxelPosition, 10> omitted{};
|
|
std::size_t size = 0, omitted_size = 0;
|
|
const auto add_goal = [&](std::optional<VoxelPosition> goal) {
|
|
if (!goal) return;
|
|
if (request.search_bounds.contains(*goal)) goals[size++] = *goal;
|
|
else omitted[omitted_size++] = *goal;
|
|
};
|
|
constexpr std::array<std::array<int, 2>, 4> directions{{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}};
|
|
for (auto direction : directions) for (int dz : {-1, 0}) {
|
|
add_goal(offset(*target, direction[0], direction[1], dz));
|
|
}
|
|
for (int dz : {-2, 1}) {
|
|
add_goal(offset(*target, 0, 0, dz));
|
|
}
|
|
result = search(queries, request, std::span(goals.data(), size),
|
|
std::span(omitted.data(), omitted_size));
|
|
}
|
|
} else result = search(queries, request, request.goals);
|
|
} catch (const NavigationFailure& failure) { result.status = failure.status; }
|
|
result.consulted = std::move(queries.reads);
|
|
} catch (const NavigationFailure& failure) { result.status = failure.status; }
|
|
catch (const std::length_error&) { result.status = Status::LimitExceeded; }
|
|
catch (const std::bad_alloc&) { result.status = Status::AllocationFailed; }
|
|
return result;
|
|
}
|
|
} // namespace
|
|
|
|
bool VoxelReadSet::current(const VoxelRegion& world, const Void::Uuid::Uuid& epoch) const noexcept {
|
|
return region == world.descriptor().id && !session.is_nil() && epoch == session &&
|
|
std::all_of(chunks.begin(), chunks.end(), [&](const auto& stamp) { return world.matches(stamp); });
|
|
}
|
|
VoxelTraversalResult voxel_standing(const VoxelRegion& world, const Void::Uuid::Uuid& session,
|
|
VoxelPosition foot, VoxelNavigationLimits limits, std::stop_token stop) {
|
|
return check(world, session, limits, stop, [&](Queries& queries) { return queries.standing(foot); });
|
|
}
|
|
VoxelTraversalResult voxel_transition(const VoxelRegion& world, const Void::Uuid::Uuid& session,
|
|
VoxelPosition from, VoxelPosition to, VoxelNavigationLimits limits, std::stop_token stop) {
|
|
return check(world, session, limits, stop, [&](Queries& queries) { return queries.transition(from, to); });
|
|
}
|
|
VoxelPathResult find_voxel_path(const VoxelRegion& world, const VoxelPathRequest& request, std::stop_token stop) {
|
|
return path(world, request, {}, stop);
|
|
}
|
|
VoxelPathResult find_voxel_interaction_path(const VoxelRegion& world, const VoxelPathRequest& request,
|
|
VoxelPosition target, std::stop_token stop) {
|
|
return path(world, request, target, stop);
|
|
}
|
|
} // namespace settlement
|