#include "voxel_scene.hpp" #include #include #include #include #include #include #include namespace settlement::viewer { namespace { constexpr std::array normals{{ {-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}}}; constexpr double elevation_pixels = 16; bool finite(VoxelPoint point) noexcept { return std::isfinite(point.x) && std::isfinite(point.y) && std::isfinite(point.z); } bool empty(VoxelBounds bounds) noexcept { return bounds.upper.z <= bounds.lower.z; } bool solid(const VoxelSample& sample) noexcept { return sample.availability == VoxelAvailability::Unavailable || (sample.availability == VoxelAvailability::Loaded && voxel_blocks_passage(sample.material)); } bool record(std::vector& reads, ChunkStamp stamp, std::size_t limit) { const auto at = std::lower_bound(reads.begin(), reads.end(), stamp.coordinate, [](const ChunkStamp& left, ChunkCoordinate right) { return left.coordinate < right; }); if (at != reads.end() && at->coordinate == stamp.coordinate) return true; if (reads.size() >= limit) return false; reads.insert(at, stamp); return true; } std::optional neighbor(VoxelPosition cell, VoxelPosition normal) noexcept { const auto x = Void::Numeric::checked_add(cell.x, normal.x); const auto y = Void::Numeric::checked_add(cell.y, normal.y); const auto z = Void::Numeric::checked_add(cell.z, normal.z); if (!x || !y || !z) return std::nullopt; return VoxelPosition{*x, *y, *z}; } bool within_budget(std::size_t faces, std::size_t reads, std::size_t limit) noexcept { // Include the eventual six expanded position/color vertices per quad, so // this budget covers a retained CPU scene plus its prepared D3D geometry. constexpr std::size_t face_bytes = sizeof(VoxelFace) + 6 * 6 * sizeof(float); const auto mesh_bytes = Void::Numeric::checked_mul(faces, face_bytes); // Account for geometric vector capacity growth in the read directory. const auto stamp_bytes = Void::Numeric::checked_mul(reads, 2 * sizeof(ChunkStamp)); if (!mesh_bytes || !stamp_bytes) return false; const auto total = Void::Numeric::checked_add(*mesh_bytes, *stamp_bytes); return total && *total <= limit; } std::array lower_array(VoxelBounds bounds) noexcept { return {bounds.lower.x, bounds.lower.y, bounds.lower.z}; } std::array extent_array(VoxelBounds bounds) noexcept { return {bounds.upper.x - bounds.lower.x, bounds.upper.y - bounds.lower.y, bounds.upper.z - bounds.lower.z}; } VoxelPosition normal_for(std::size_t axis, int sign) noexcept { if (axis == 0) return {sign, 0, 0}; if (axis == 1) return {0, sign, 0}; return {0, 0, sign}; } } // namespace VoxelScene::VoxelScene(VoxelRegion region, Void::Uuid::Uuid session, VoxelSceneOptions options, VoxelBounds visible) : region_(std::move(region)), session_(session), options_(options), visible_(visible) {} bool VoxelScene::current(const VoxelRegion& region, const Void::Uuid::Uuid& session) const noexcept { return session == session_ && region.descriptor() == region_.descriptor() && std::all_of(reads_.begin(), reads_.end(), [&](auto stamp) { return region.matches(stamp); }); } std::expected, VoxelSceneError> prepare_voxel_scene( const VoxelRegion& region, const Void::Uuid::Uuid& session, VoxelSceneOptions options) { const auto& bounds = options.bounds; const auto& region_bounds = region.descriptor().bounds; const auto& limits = options.limits; if (bounds.lower.x < region_bounds.lower.x || bounds.lower.y < region_bounds.lower.y || bounds.lower.z < region_bounds.lower.z || bounds.upper.x > region_bounds.upper.x || bounds.upper.y > region_bounds.upper.y || bounds.upper.z > region_bounds.upper.z || bounds.lower.x >= bounds.upper.x || bounds.lower.y >= bounds.upper.y || bounds.lower.z >= bounds.upper.z || limits.max_axis <= 0) { return std::unexpected(VoxelSceneError::InvalidInput); } const auto extents = extent_array(bounds); for (auto extent : extents) { // The shader uses float local vertices. Keep all cell corners exact, // including the upper endpoint, even if a caller raises its budget. if (extent > limits.max_axis || extent > 65536) return std::unexpected(VoxelSceneError::LimitExceeded); } auto visible = bounds; visible.upper.z = std::max(bounds.lower.z, std::min(bounds.upper.z, std::int64_t{options.slice} + 1)); auto cells = Void::Numeric::checked_mul(static_cast(extents[0]), static_cast(extents[1])); if (cells) cells = Void::Numeric::checked_mul(*cells, static_cast(visible.upper.z - visible.lower.z)); if (!cells || *cells > limits.max_cells) return std::unexpected(VoxelSceneError::LimitExceeded); try { auto scene = std::shared_ptr(new VoxelScene(region, session, options, visible)); std::size_t face_count = 0; const auto record_read = [&](ChunkStamp stamp) { const auto at = std::lower_bound(scene->reads_.begin(), scene->reads_.end(), stamp.coordinate, [](const ChunkStamp& left, ChunkCoordinate right) { return left.coordinate < right; }); if (at != scene->reads_.end() && at->coordinate == stamp.coordinate) return true; if (scene->reads_.size() >= limits.max_read_chunks || !within_budget(face_count, scene->reads_.size() + 1, limits.max_bytes)) return false; scene->reads_.insert(at, stamp); return true; }; // First pass counts and records dependencies before allocating faces. // Second pass reads the same held immutable pages and fills exact capacity. for (int pass = 0; pass < 2; ++pass) { for (auto z = visible.lower.z; z < visible.upper.z; ++z) { for (auto y = visible.lower.y; y < visible.upper.y; ++y) { for (auto x = visible.lower.x; x < visible.upper.x; ++x) { const VoxelPosition cell{static_cast(x), static_cast(y), static_cast(z)}; const auto sample = region.sample(cell); if (pass == 0 && !record_read(sample.stamp)) return std::unexpected(VoxelSceneError::LimitExceeded); if (!solid(sample)) continue; for (auto normal : normals) { const auto next = neighbor(cell, normal); if (next && visible.contains(*next)) { const auto beside = region.sample(*next); if (pass == 0 && !record_read(beside.stamp)) return std::unexpected(VoxelSceneError::LimitExceeded); if (solid(beside)) continue; } if (pass == 0) { if (face_count >= limits.max_faces) return std::unexpected(VoxelSceneError::LimitExceeded); ++face_count; if (!within_budget(face_count, scene->reads_.size(), limits.max_bytes)) return std::unexpected(VoxelSceneError::LimitExceeded); } else { scene->faces_.push_back({cell, normal, sample.material, sample.availability == VoxelAvailability::Unavailable}); } } } } } if (pass == 0) { if (!within_budget(face_count, scene->reads_.size(), limits.max_bytes)) return std::unexpected(VoxelSceneError::LimitExceeded); scene->faces_.reserve(face_count); } } return scene; } catch (const std::bad_alloc&) { return std::unexpected(VoxelSceneError::AllocationFailed); } catch (const std::length_error&) { return std::unexpected(VoxelSceneError::AllocationFailed); } } bool valid_voxel_camera(const VoxelCamera& camera) noexcept { // D3D11 maximum 2D resource dimension, with finite practical shader inputs. // Tiny/huge scales cannot identify a cell in a pixel and are refused. return camera.width > 0 && camera.width <= 16384 && camera.height > 0 && camera.height <= 16384 && std::isfinite(camera.origin_x) && std::abs(camera.origin_x) <= 1e7 && std::isfinite(camera.origin_y) && std::abs(camera.origin_y) <= 1e7 && std::isfinite(camera.scale) && camera.scale >= 0.01 && camera.scale <= 256 && std::isfinite(camera.tile_half_width) && camera.tile_half_width >= 1 && camera.tile_half_width <= 256 && std::isfinite(camera.tile_half_height) && camera.tile_half_height >= 1 && camera.tile_half_height <= 256; } std::optional project_voxel_point(const VoxelScene& scene, const VoxelCamera& camera, VoxelPoint point) noexcept { if (!valid_voxel_camera(camera) || !finite(point)) return std::nullopt; const auto lower = scene.options().bounds.lower; point = point - VoxelPoint{static_cast(lower.x), static_cast(lower.y), static_cast(lower.z)}; const ScreenPoint result{camera.origin_x + camera.scale * (point.x - point.y) * camera.tile_half_width, camera.origin_y + camera.scale * ((point.x + point.y) * camera.tile_half_height - point.z * elevation_pixels)}; if (!std::isfinite(result.x) || !std::isfinite(result.y)) return std::nullopt; return result; } std::uint32_t voxel_face_color(const VoxelFace& face) noexcept { std::array color{128, 132, 140}; if (!face.unavailable) { switch (face.material) { case MaterialId::Soil: color = {166, 119, 70}; break; case MaterialId::Stone: color = {130, 143, 157}; break; case MaterialId::DoorClosed: color = {184, 99, 46}; break; default: break; } } const std::uint32_t percent = face.normal.z > 0 ? 100u : face.normal.x != 0 ? 82u : face.normal.y != 0 ? 66u : 50u; for (auto& channel : color) channel = channel * percent / 100u; return (color[0] << 16u) | (color[1] << 8u) | color[2]; } bool VoxelPick::current(const VoxelRegion& world, const Void::Uuid::Uuid& current_session) const noexcept { return session == current_session && region == world.descriptor().id && std::all_of(reads.begin(), reads.end(), [&](auto stamp) { return world.matches(stamp); }); } std::expected trace_voxels( const VoxelScene& scene, VoxelRay ray, VoxelPickLimits limits) { if (!finite(ray.origin) || !finite(ray.direction) || !std::isfinite(ray.max_distance) || ray.max_distance < 0) return std::unexpected(VoxelSceneError::InvalidInput); const double magnitude = std::max({std::abs(ray.direction.x), std::abs(ray.direction.y), std::abs(ray.direction.z)}); if (magnitude == 0) return std::unexpected(VoxelSceneError::InvalidInput); // Power-of-two scaling preserves represented component ratios. Dividing by // a Euclidean norm first would turn a 1:3 exact corner tie into two steps. int exponent = 0; std::frexp(magnitude, &exponent); const std::array direction{std::scalbn(static_cast(ray.direction.x), -exponent), std::scalbn(static_cast(ray.direction.y), -exponent), std::scalbn(static_cast(ray.direction.z), -exponent)}; const auto length = std::hypot(direction[0], direction[1], direction[2]); VoxelPick result; result.region = scene.region().descriptor().id; result.session = scene.session(); const auto bounds = scene.visible_bounds(); if (empty(bounds)) return result; const auto lower = lower_array(bounds); const auto extent = extent_array(bounds); const std::array origin{static_cast(ray.origin.x) - lower[0], static_cast(ray.origin.y) - lower[1], static_cast(ray.origin.z) - lower[2]}; std::array step{}; std::array entry{}; long double start = 0, finish = ray.max_distance / length; for (std::size_t axis = 0; axis < 3; ++axis) { if (!std::isfinite(origin[axis])) return std::unexpected(VoxelSceneError::InvalidInput); step[axis] = direction[axis] > 0 ? 1 : direction[axis] < 0 ? -1 : 0; if (step[axis] == 0) { if (origin[axis] < 0 || origin[axis] >= extent[axis]) return result; entry[axis] = -std::numeric_limits::infinity(); continue; } const auto a = -origin[axis] / direction[axis]; const auto b = (extent[axis] - origin[axis]) / direction[axis]; entry[axis] = std::min(a, b); start = std::max(start, entry[axis]); finish = std::min(finish, std::max(a, b)); } if (start > finish || !std::isfinite(start)) return result; std::array cell{}; VoxelPosition normal{}; bool has_normal = false; for (std::size_t axis = 0; axis < 3; ++axis) { auto point = std::fma(direction[axis], start, origin[axis]); if (entry[axis] == start) point = step[axis] > 0 ? 0 : static_cast(extent[axis]); if (!std::isfinite(point) || point < 0 || point > extent[axis]) return std::unexpected(VoxelSceneError::InvalidInput); const auto floor = std::floor(point); cell[axis] = static_cast(floor) - (step[axis] < 0 && point == floor ? 1 : 0); if (cell[axis] < 0 || cell[axis] >= extent[axis]) return result; if (!has_normal && step[axis] != 0 && point == floor) { normal = normal_for(axis, -step[axis]); has_normal = true; } } try { auto distance = start; for (std::size_t walked = 0; ; ++walked) { if (walked >= limits.max_steps) return std::unexpected(VoxelSceneError::LimitExceeded); const VoxelPosition absolute{static_cast(lower[0] + cell[0]), static_cast(lower[1] + cell[1]), static_cast(lower[2] + cell[2])}; const auto sample = scene.region().sample(absolute); if (!record(result.reads, sample.stamp, limits.max_read_chunks)) return std::unexpected(VoxelSceneError::LimitExceeded); if (solid(sample)) { result.status = sample.availability == VoxelAvailability::Unavailable ? VoxelPickStatus::Unavailable : has_normal ? VoxelPickStatus::Hit : VoxelPickStatus::Inside; result.cell = absolute; result.normal = normal; if (has_normal) result.adjacent = neighbor(absolute, normal); result.material = sample.material; result.distance = static_cast(distance * length); return result; } std::array crossing{}; for (std::size_t axis = 0; axis < 3; ++axis) { crossing[axis] = step[axis] == 0 ? std::numeric_limits::infinity() : (static_cast(cell[axis] + (step[axis] > 0 ? 1 : 0)) - origin[axis]) / direction[axis]; } const auto next = *std::min_element(crossing.begin(), crossing.end()); if (next > finish || !std::isfinite(next)) return result; // A distance too large to represent successive voxel planes is not // safe for a selection. Refuse rather than returning an arbitrary cell. if (next <= distance) return std::unexpected(VoxelSceneError::InvalidInput); has_normal = false; for (std::size_t axis = 0; axis < 3; ++axis) { if (crossing[axis] != next) continue; cell[axis] += step[axis]; if (!has_normal) { normal = normal_for(axis, -step[axis]); has_normal = true; } if (cell[axis] < 0 || cell[axis] >= extent[axis]) return result; } distance = next; } } catch (const std::bad_alloc&) { return std::unexpected(VoxelSceneError::AllocationFailed); } catch (const std::length_error&) { return std::unexpected(VoxelSceneError::AllocationFailed); } } std::expected voxel_screen_ray( const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point) { if (!valid_voxel_camera(camera) || !std::isfinite(point.x) || !std::isfinite(point.y) || point.x < 0 || point.y < 0 || point.x >= camera.width || point.y >= camera.height) return std::unexpected(VoxelSceneError::InvalidInput); const auto bounds = scene.visible_bounds(); const double z = static_cast(bounds.upper.z - bounds.lower.z); const double u = (point.x - camera.origin_x) / (camera.scale * camera.tile_half_width); const double v = (point.y - camera.origin_y) / (camera.scale * camera.tile_half_height); const double elevated = v + z * elevation_pixels / camera.tile_half_height; VoxelRay ray{{(u + elevated) * 0.5 + static_cast(bounds.lower.x), (elevated - u) * 0.5 + static_cast(bounds.lower.y), static_cast(bounds.upper.z)}, {-1, -1, -2 * camera.tile_half_height / elevation_pixels}, 0}; ray.max_distance = z * std::hypot(ray.direction.x, ray.direction.y, ray.direction.z) / -ray.direction.z; return ray; } std::expected pick_voxel_screen( const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point, VoxelPickLimits limits) { const auto ray = voxel_screen_ray(scene, camera, point); if (!ray) return std::unexpected(ray.error()); return trace_voxels(scene, *ray, limits); } } // namespace settlement::viewer