feat(rendering): draw and pick immutable voxel height slices through D3D11
This commit is contained in:
1 parent
13dc673088
commit
37a08d4d48
8 files changed
+1049
-11
No files matched your search
+14
-3
@@ -95,17 +95,22 @@ enable_language(RC)
|
||||
add_library(settlement_client STATIC app/viewer_session.cpp)
|
||||
target_include_directories(settlement_client PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
|
||||
target_link_libraries(settlement_client PUBLIC settlement_core)
|
||||
add_library(settlement_voxel_scene STATIC app/voxel_scene.cpp)
|
||||
target_include_directories(settlement_voxel_scene PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/app)
|
||||
target_link_libraries(settlement_voxel_scene PUBLIC settlement_core Void::Math)
|
||||
add_executable(settlement_viewer WIN32
|
||||
app/d3d_scene_win32.cpp
|
||||
app/viewer_win32.cpp
|
||||
app/house_icons.rc
|
||||
)
|
||||
target_link_libraries(settlement_viewer PRIVATE settlement_client settlement_lan user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
target_link_libraries(settlement_viewer PRIVATE settlement_client settlement_lan settlement_voxel_scene user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
if(MSVC)
|
||||
target_compile_options(settlement_voxel_scene PRIVATE /W4 /permissive-)
|
||||
target_compile_options(settlement_client PRIVATE /W4 /permissive-)
|
||||
target_compile_options(settlement_lan PRIVATE /W4 /permissive-)
|
||||
target_compile_options(settlement_viewer PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/W4;/permissive->)
|
||||
else()
|
||||
target_compile_options(settlement_voxel_scene PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
target_compile_options(settlement_client PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
target_compile_options(settlement_lan PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow)
|
||||
target_link_options(settlement_viewer PRIVATE -municode)
|
||||
@@ -150,7 +155,7 @@ if(BUILD_TESTING)
|
||||
|
||||
add_executable(settlement_viewer_frame_smoke
|
||||
tests/viewer_frame_smoke.cpp app/d3d_scene_win32.cpp app/house_icons.rc)
|
||||
target_link_libraries(settlement_viewer_frame_smoke PRIVATE settlement_client settlement_lan
|
||||
target_link_libraries(settlement_viewer_frame_smoke PRIVATE settlement_client settlement_lan settlement_voxel_scene
|
||||
user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
add_test(NAME settlement_viewer_frame_smoke COMMAND settlement_viewer_frame_smoke)
|
||||
set_tests_properties(settlement_viewer_frame_smoke PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77)
|
||||
@@ -161,8 +166,14 @@ if(BUILD_TESTING)
|
||||
|
||||
add_executable(settlement_production_controls_tests
|
||||
tests/production_controls_tests.cpp tests/test_main.cpp app/d3d_scene_win32.cpp app/house_icons.rc)
|
||||
target_link_libraries(settlement_production_controls_tests PRIVATE settlement_client settlement_lan
|
||||
target_link_libraries(settlement_production_controls_tests PRIVATE settlement_client settlement_lan settlement_voxel_scene
|
||||
Void::Testing user32 gdi32 comctl32 comdlg32 d3d11 d3dcompiler)
|
||||
add_test(NAME settlement_production_controls_tests COMMAND settlement_production_controls_tests)
|
||||
set_tests_properties(settlement_production_controls_tests PROPERTIES RUN_SERIAL TRUE TIMEOUT 60)
|
||||
|
||||
add_executable(settlement_voxel_scene_tests
|
||||
tests/voxel_scene_tests.cpp tests/test_main.cpp app/d3d_scene_win32.cpp)
|
||||
target_link_libraries(settlement_voxel_scene_tests PRIVATE settlement_voxel_scene Void::Testing d3d11 d3dcompiler)
|
||||
add_test(NAME settlement_voxel_scene_tests COMMAND settlement_voxel_scene_tests)
|
||||
set_tests_properties(settlement_voxel_scene_tests PROPERTIES TIMEOUT 90)
|
||||
endif()
|
||||
+78
-7
@@ -11,6 +11,8 @@
|
||||
#include <cstring>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace settlement::viewer {
|
||||
@@ -468,6 +470,8 @@ cbuffer Camera : register(b0) {
|
||||
float2 screen;
|
||||
float scale;
|
||||
float padding;
|
||||
float2 depthParameters;
|
||||
float2 depthPadding;
|
||||
};
|
||||
struct Input { float3 position : POSITION; float3 color : COLOR; };
|
||||
struct Pixel { float4 position : SV_Position; float3 color : COLOR; };
|
||||
@@ -477,7 +481,8 @@ Pixel project(Input input) {
|
||||
(p.x + p.y) * halfTile.y - p.z * 16.0);
|
||||
Pixel result;
|
||||
result.position = float4(screenPoint.x * 2.0 / screen.x - 1.0,
|
||||
1.0 - screenPoint.y * 2.0 / screen.y, 0.96 - (p.x + p.y + p.z * 1.5) * 0.009, 1.0);
|
||||
1.0 - screenPoint.y * 2.0 / screen.y,
|
||||
depthParameters.x - (p.x + p.y + p.z * 1.5) * depthParameters.y, 1.0);
|
||||
result.color = input.color;
|
||||
return result;
|
||||
}
|
||||
@@ -489,6 +494,8 @@ float4 paint(Pixel input) : SV_Target { return float4(input.color, 1.0); }
|
||||
class PreparedGeometry {
|
||||
public:
|
||||
Mesh mesh;
|
||||
std::shared_ptr<const VoxelScene> voxel_scene;
|
||||
float depth_bias = .96f, depth_scale = .009f;
|
||||
};
|
||||
|
||||
struct D3DScene::Backend {
|
||||
@@ -539,21 +546,28 @@ struct D3DScene::Backend {
|
||||
}
|
||||
|
||||
bool upload_geometry(const Mesh& mesh) {
|
||||
if (mesh.vertices.empty()) return true;
|
||||
const auto bytes = mesh.vertices.size() * sizeof(Vertex);
|
||||
if (bytes > std::numeric_limits<UINT>::max()) return false;
|
||||
ComPtr<ID3D11Buffer> replacement;
|
||||
auto* destination = geometry.Get();
|
||||
if (bytes > buffer_bytes) {
|
||||
D3D11_BUFFER_DESC desc{};
|
||||
desc.ByteWidth = static_cast<UINT>(bytes);
|
||||
desc.Usage = D3D11_USAGE_DYNAMIC;
|
||||
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
|
||||
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
|
||||
if (FAILED(device->CreateBuffer(&desc, nullptr, geometry.ReleaseAndGetAddressOf()))) return false;
|
||||
buffer_bytes = desc.ByteWidth;
|
||||
if (FAILED(device->CreateBuffer(&desc, nullptr, &replacement))) return false;
|
||||
destination = replacement.Get();
|
||||
}
|
||||
D3D11_MAPPED_SUBRESOURCE mapped{};
|
||||
if (FAILED(context->Map(geometry.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
|
||||
if (FAILED(context->Map(destination, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return false;
|
||||
std::memcpy(mapped.pData, mesh.vertices.data(), bytes);
|
||||
context->Unmap(geometry.Get(), 0);
|
||||
context->Unmap(destination, 0);
|
||||
if (replacement) {
|
||||
geometry = std::move(replacement);
|
||||
buffer_bytes = static_cast<UINT>(bytes);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -621,7 +635,7 @@ bool D3DScene::initialize(HWND target, bool software) {
|
||||
raster.CullMode = D3D11_CULL_NONE;
|
||||
raster.DepthClipEnable = TRUE;
|
||||
D3D11_BUFFER_DESC constants{};
|
||||
constants.ByteWidth = 32;
|
||||
constants.ByteWidth = 48;
|
||||
constants.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
|
||||
if (FAILED(graphics->device->CreateInputLayout(elements, std::size(elements), vertex->GetBufferPointer(),
|
||||
vertex->GetBufferSize(), &graphics->layout)) ||
|
||||
@@ -656,6 +670,62 @@ bool D3DScene::render(const World& world, const SceneView& view, std::vector<std
|
||||
return render(prepare(world, view), view, capture);
|
||||
}
|
||||
|
||||
std::expected<std::shared_ptr<const PreparedGeometry>, VoxelSceneError>
|
||||
D3DScene::prepare_voxels(std::shared_ptr<const VoxelScene> scene) {
|
||||
if (!scene) return std::unexpected(VoxelSceneError::InvalidInput);
|
||||
if (scene->faces().size() > std::numeric_limits<UINT>::max() / (6 * sizeof(Vertex)))
|
||||
return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
try {
|
||||
auto prepared = std::make_shared<PreparedGeometry>();
|
||||
prepared->voxel_scene = std::move(scene);
|
||||
const auto bounds = prepared->voxel_scene->visible_bounds();
|
||||
const double depth_extent = static_cast<double>(bounds.upper.x - bounds.lower.x) +
|
||||
static_cast<double>(bounds.upper.y - bounds.lower.y) +
|
||||
static_cast<double>(bounds.upper.z - bounds.lower.z) * 1.5;
|
||||
prepared->depth_bias = .95f;
|
||||
prepared->depth_scale = static_cast<float>(.9 / depth_extent);
|
||||
auto& mesh = prepared->mesh;
|
||||
mesh.vertices.reserve(prepared->voxel_scene->faces().size() * 6);
|
||||
for (const auto& face : prepared->voxel_scene->faces()) {
|
||||
const float x = static_cast<float>(std::int64_t{face.cell.x} - bounds.lower.x);
|
||||
const float y = static_cast<float>(std::int64_t{face.cell.y} - bounds.lower.y);
|
||||
const float z = static_cast<float>(std::int64_t{face.cell.z} - bounds.lower.z);
|
||||
const auto packed = voxel_face_color(face);
|
||||
const auto color = rgb(static_cast<int>((packed >> 16u) & 255u),
|
||||
static_cast<int>((packed >> 8u) & 255u), static_cast<int>(packed & 255u));
|
||||
if (face.normal.x != 0) {
|
||||
const float a = x + (face.normal.x > 0 ? 1.f : 0.f);
|
||||
mesh.quad({a, y, z}, {a, y + 1, z}, {a, y + 1, z + 1}, {a, y, z + 1}, color);
|
||||
} else if (face.normal.y != 0) {
|
||||
const float a = y + (face.normal.y > 0 ? 1.f : 0.f);
|
||||
mesh.quad({x, a, z}, {x + 1, a, z}, {x + 1, a, z + 1}, {x, a, z + 1}, color);
|
||||
} else {
|
||||
const float a = z + (face.normal.z > 0 ? 1.f : 0.f);
|
||||
mesh.quad({x, y, a}, {x + 1, y, a}, {x + 1, y + 1, a}, {x, y + 1, a}, color);
|
||||
}
|
||||
}
|
||||
return prepared;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return std::unexpected(VoxelSceneError::AllocationFailed);
|
||||
} catch (const std::length_error&) {
|
||||
return std::unexpected(VoxelSceneError::AllocationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const VoxelCamera& camera,
|
||||
std::vector<std::uint32_t>* capture) {
|
||||
if (!geometry || !geometry->voxel_scene || !valid_voxel_camera(camera)) return false;
|
||||
SceneView view{};
|
||||
view.width = camera.width;
|
||||
view.height = camera.height;
|
||||
view.origin_x = static_cast<float>(camera.origin_x);
|
||||
view.origin_y = static_cast<float>(camera.origin_y);
|
||||
view.scale = static_cast<float>(camera.scale);
|
||||
view.tile_half_width = static_cast<float>(camera.tile_half_width);
|
||||
view.tile_half_height = static_cast<float>(camera.tile_half_height);
|
||||
return render(std::move(geometry), view, capture);
|
||||
}
|
||||
|
||||
bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const SceneView& view,
|
||||
std::vector<std::uint32_t>* capture) {
|
||||
// Present may dispatch window messages, including destruction. Keep this
|
||||
@@ -679,7 +749,8 @@ bool D3DScene::render(std::shared_ptr<const PreparedGeometry> geometry, const Sc
|
||||
ctx->RSSetViewports(1, &viewport);
|
||||
ctx->RSSetState(graphics.rasterizer.Get());
|
||||
const float constants[] = {view.origin_x, view.origin_y, view.tile_half_width, view.tile_half_height,
|
||||
viewport.Width, viewport.Height, view.scale, 0};
|
||||
viewport.Width, viewport.Height, view.scale, 0,
|
||||
geometry->depth_bias, geometry->depth_scale, 0, 0};
|
||||
ctx->UpdateSubresource(graphics.camera.Get(), 0, nullptr, constants, 0, 0);
|
||||
constexpr UINT stride = sizeof(Vertex);
|
||||
constexpr UINT offset = 0;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
#include "voxel_scene.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
@@ -55,6 +56,10 @@ public:
|
||||
[[nodiscard]] static std::shared_ptr<const PreparedGeometry> prepare(const World& world, const SceneView& view);
|
||||
bool render(std::shared_ptr<const PreparedGeometry> geometry, const SceneView& view,
|
||||
std::vector<std::uint32_t>* capture = nullptr);
|
||||
[[nodiscard]] static std::expected<std::shared_ptr<const PreparedGeometry>, VoxelSceneError>
|
||||
prepare_voxels(std::shared_ptr<const VoxelScene> scene);
|
||||
bool render(std::shared_ptr<const PreparedGeometry> geometry, const VoxelCamera& view,
|
||||
std::vector<std::uint32_t>* capture = nullptr);
|
||||
[[nodiscard]] std::uint64_t uploads() const noexcept { return uploads_; }
|
||||
[[nodiscard]] std::uint64_t frames() const noexcept { return frames_; }
|
||||
void reset() noexcept;
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
#include "voxel_scene.hpp"
|
||||
|
||||
#include <Void/Math/Numeric.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace settlement::viewer {
|
||||
namespace {
|
||||
|
||||
constexpr std::array<VoxelPosition, 6> 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<ChunkStamp>& 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<VoxelPosition> 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<std::int64_t, 3> lower_array(VoxelBounds bounds) noexcept {
|
||||
return {bounds.lower.x, bounds.lower.y, bounds.lower.z};
|
||||
}
|
||||
std::array<std::int64_t, 3> 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<std::shared_ptr<const VoxelScene>, 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<std::size_t>(extents[0]),
|
||||
static_cast<std::size_t>(extents[1]));
|
||||
if (cells) cells = Void::Numeric::checked_mul(*cells,
|
||||
static_cast<std::size_t>(visible.upper.z - visible.lower.z));
|
||||
if (!cells || *cells > limits.max_cells) return std::unexpected(VoxelSceneError::LimitExceeded);
|
||||
|
||||
try {
|
||||
auto scene = std::shared_ptr<VoxelScene>(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<std::int32_t>(x),
|
||||
static_cast<std::int32_t>(y), static_cast<std::int32_t>(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<ScreenPoint> 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<double>(lower.x), static_cast<double>(lower.y), static_cast<double>(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<std::uint32_t, 3> 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<VoxelPick, VoxelSceneError> 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<long double, 3> direction{std::scalbn(static_cast<long double>(ray.direction.x), -exponent),
|
||||
std::scalbn(static_cast<long double>(ray.direction.y), -exponent),
|
||||
std::scalbn(static_cast<long double>(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<long double, 3> origin{static_cast<long double>(ray.origin.x) - lower[0],
|
||||
static_cast<long double>(ray.origin.y) - lower[1], static_cast<long double>(ray.origin.z) - lower[2]};
|
||||
std::array<int, 3> step{};
|
||||
std::array<long double, 3> 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<long double>::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<std::int64_t, 3> 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<long double>(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<std::int64_t>(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<std::int32_t>(lower[0] + cell[0]),
|
||||
static_cast<std::int32_t>(lower[1] + cell[1]), static_cast<std::int32_t>(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<double>(distance * length);
|
||||
return result;
|
||||
}
|
||||
std::array<long double, 3> crossing{};
|
||||
for (std::size_t axis = 0; axis < 3; ++axis) {
|
||||
crossing[axis] = step[axis] == 0 ? std::numeric_limits<long double>::infinity() :
|
||||
(static_cast<long double>(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<VoxelRay, VoxelSceneError> 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<double>(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<double>(bounds.lower.x),
|
||||
(elevated - u) * 0.5 + static_cast<double>(bounds.lower.y), static_cast<double>(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<VoxelPick, VoxelSceneError> 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
|
||||
@@ -0,0 +1,113 @@
|
||||
#pragma once
|
||||
|
||||
#include "map_camera.hpp"
|
||||
#include "settlement/core/voxel_region.hpp"
|
||||
#include <Void/Core/Uuid.hpp>
|
||||
#include <Void/Math/Vec.hpp>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace settlement::viewer {
|
||||
|
||||
using VoxelPoint = Void::Math::Vec3<double>;
|
||||
|
||||
struct VoxelCamera {
|
||||
int width = 0, height = 0;
|
||||
// Screen position of the lower corner of the prepared display bounds.
|
||||
double origin_x = 0, origin_y = 0;
|
||||
double scale = 1;
|
||||
double tile_half_width = 12, tile_half_height = 7;
|
||||
};
|
||||
struct VoxelSceneLimits {
|
||||
std::size_t max_cells = 2 * 1024 * 1024;
|
||||
std::size_t max_faces = 262144;
|
||||
std::size_t max_read_chunks = 1024;
|
||||
// Faces, read directory capacity and expanded CPU vertices. Shared source
|
||||
// pages, allocator overhead, retained older scenes and GPU memory are separate.
|
||||
std::size_t max_bytes = 64 * 1024 * 1024;
|
||||
std::int64_t max_axis = 4096;
|
||||
};
|
||||
struct VoxelSceneOptions {
|
||||
// An explicit display volume bounds work even in an enormous sparse region.
|
||||
VoxelBounds bounds;
|
||||
std::int32_t slice = 0; // Highest displayed cell, inclusive.
|
||||
VoxelSceneLimits limits;
|
||||
};
|
||||
enum class VoxelSceneError {
|
||||
InvalidInput, LimitExceeded, AllocationFailed
|
||||
};
|
||||
struct VoxelFace {
|
||||
VoxelPosition cell;
|
||||
VoxelPosition normal;
|
||||
MaterialId material = MaterialId::Air;
|
||||
bool unavailable = false;
|
||||
bool operator==(const VoxelFace&) const = default;
|
||||
};
|
||||
|
||||
class VoxelScene {
|
||||
public:
|
||||
[[nodiscard]] const VoxelRegion& region() const noexcept { return region_; }
|
||||
[[nodiscard]] const Void::Uuid::Uuid& session() const noexcept { return session_; }
|
||||
[[nodiscard]] const VoxelSceneOptions& options() const noexcept { return options_; }
|
||||
[[nodiscard]] const VoxelBounds& visible_bounds() const noexcept { return visible_; }
|
||||
[[nodiscard]] std::span<const VoxelFace> faces() const noexcept { return faces_; }
|
||||
[[nodiscard]] std::span<const ChunkStamp> reads() const noexcept { return reads_; }
|
||||
[[nodiscard]] bool current(const VoxelRegion& region, const Void::Uuid::Uuid& session) const noexcept;
|
||||
private:
|
||||
friend std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError>
|
||||
prepare_voxel_scene(const VoxelRegion&, const Void::Uuid::Uuid&, VoxelSceneOptions);
|
||||
VoxelScene(VoxelRegion region, Void::Uuid::Uuid session, VoxelSceneOptions options, VoxelBounds visible);
|
||||
VoxelRegion region_;
|
||||
Void::Uuid::Uuid session_;
|
||||
VoxelSceneOptions options_;
|
||||
VoxelBounds visible_;
|
||||
std::vector<VoxelFace> faces_;
|
||||
std::vector<ChunkStamp> reads_;
|
||||
};
|
||||
|
||||
// Missing cells are opaque gray terrain boundaries. Picks stop there with
|
||||
// Unavailable so loaded geometry cannot be selected through unknown space.
|
||||
[[nodiscard]] std::expected<std::shared_ptr<const VoxelScene>, VoxelSceneError>
|
||||
prepare_voxel_scene(const VoxelRegion& region, const Void::Uuid::Uuid& session, VoxelSceneOptions options);
|
||||
[[nodiscard]] bool valid_voxel_camera(const VoxelCamera& camera) noexcept;
|
||||
[[nodiscard]] std::optional<ScreenPoint> project_voxel_point(
|
||||
const VoxelScene& scene, const VoxelCamera& camera, VoxelPoint point) noexcept;
|
||||
[[nodiscard]] std::uint32_t voxel_face_color(const VoxelFace& face) noexcept;
|
||||
|
||||
struct VoxelRay {
|
||||
VoxelPoint origin;
|
||||
VoxelPoint direction;
|
||||
double max_distance = 0;
|
||||
};
|
||||
struct VoxelPickLimits {
|
||||
std::size_t max_steps = 16384;
|
||||
std::size_t max_read_chunks = 1024;
|
||||
};
|
||||
enum class VoxelPickStatus { Miss, Hit, Inside, Unavailable };
|
||||
struct VoxelPick {
|
||||
RegionId region = 0;
|
||||
Void::Uuid::Uuid session;
|
||||
VoxelPickStatus status = VoxelPickStatus::Miss;
|
||||
VoxelPosition cell;
|
||||
VoxelPosition normal; // Zero for an initial occupied cell with no crossed face.
|
||||
std::optional<VoxelPosition> adjacent; // May be outside the region. Validate before placement.
|
||||
MaterialId material = MaterialId::Air;
|
||||
double distance = 0;
|
||||
std::vector<ChunkStamp> reads;
|
||||
[[nodiscard]] bool current(const VoxelRegion& world, const Void::Uuid::Uuid& current_session) const noexcept;
|
||||
};
|
||||
|
||||
// Cells are [x,x+1). At an exact plane the direction selects the forward cell.
|
||||
// A zero component stays in the half-open cell owning that coordinate.
|
||||
// Simultaneous plane crossings advance all tied axes, selecting normal X/Y/Z
|
||||
// in that priority order. Cells touched only along an edge are skipped.
|
||||
[[nodiscard]] std::expected<VoxelPick, VoxelSceneError> trace_voxels(
|
||||
const VoxelScene& scene, VoxelRay ray, VoxelPickLimits limits = {});
|
||||
[[nodiscard]] std::expected<VoxelRay, VoxelSceneError> voxel_screen_ray(
|
||||
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point);
|
||||
[[nodiscard]] std::expected<VoxelPick, VoxelSceneError> pick_voxel_screen(
|
||||
const VoxelScene& scene, const VoxelCamera& camera, ScreenPoint point, VoxelPickLimits limits = {});
|
||||
|
||||
} // namespace settlement::viewer
|
||||
@@ -0,0 +1,48 @@
|
||||
# Draw and pick the same sliced voxel terrain through Direct3D
|
||||
|
||||
Task ID: S17-02
|
||||
Role: astra_implementer
|
||||
Status: READY
|
||||
|
||||
## 1. Context and baseline
|
||||
Isolated detached staging worktree s17-voxel at 13dc673 contains both M01 immutable D3D frame changes and accepted S02 1ca481b (including MaterialId DoorClosed/DoorOpen). Later root integrates this work to the existing system/s17-rendering. M02-P1/F1 define shared z-up projection, frozen bounds/32³ S02 sampling/availability, finite edit scenario. Actual shader uses (x−y)*halfTile.x and (x+y)*halfTile.y−16*z, existing flat pick is z=0. Void pin 7b0fea6 Math::Vec/Numeric present, general bounded 3D grid-ray traversal absent under issue #12; mesh neighbor revision issue #13.
|
||||
|
||||
## 2. Objective and deliverables
|
||||
Implement a usable terrain geometry and height-slice picking API, real D3D11 renderer entry point and offscreen WARP test proving projected visible surfaces agree with mouse hit cells/faces for edited signed voxel regions. Provide frozen interface early for normal S18+World frame hookup. Root/next worker wires actual authored game when its World factory exists.
|
||||
|
||||
## 3. Scope and non-goals
|
||||
M02 terrain presentation/picking/CPU prepared geometry and actual D3D draw only; do not edit mutable World, simulation, new-game menu, viewer_win32.cpp, existing legacy protocol/codec or actor motion. Existing 2D rendering and immutable prepare/render interface are relied upon; cover regressions. Use game generated terrain and material colors, no borrowed graphics.
|
||||
|
||||
## 4. Files to inspect
|
||||
Read real S02 voxel_region.hpp/cpp/test, S17-01 frame contract and S17 docs, M02 F1/P1, dependency matrix M02 and pin Math Vec/Numeric. Read app/{d3d_scene_win32,map_camera}.hpp, d3d_scene_win32.cpp Mesh/PreparedGeometry/shader/camera constant buffer/D3DScene::render, viewer_win32 map_cell/scene_view/camera/timers, tests/viewer_frame_smoke.cpp CMake graphics targets. Share public anchors with S18 owner; M02 normal World integration upcoming.
|
||||
|
||||
## 5. Write ownership and coordination
|
||||
Write scope: app/d3d_scene_win32.hpp; app/d3d_scene_win32.cpp; app/voxel_scene.hpp; app/voxel_scene.cpp; tests/voxel_scene_tests.cpp; CMakeLists.txt; docs/plan/systems/S17.md
|
||||
New dedicated voxel_scene files plus tested D3D terrain overload; CMake only own source/test entries/libraries. Other agents own separate WTs. No external actions, Git writes/checkout changes, shared Serena activation, children or other source edits. Temporary controlled probes in your own /tmp build OK.
|
||||
|
||||
## 6. Implementation or investigation approach
|
||||
Use actual existing shader isometric basis, z-up. Expose one view/projection/slice model for both rendering and hit query; support real camera origin/pan/scale/viewport and integer slice inclusive maximum visible z. Render material faces exposed to air/open door/slice/outside, avoid duplicate internal faces across adjacent loaded pages. Decide display for unavailable neighboring pages consistently; picking must return unresolved when an unloaded visible cell can precede a farther surface. Open doorway permits seeing and picking through its aperture, closed door blocks, rendering/picking same shape. Bound drawable cells/faces/time, support signed absolute/extreme coordinates via region-local origin and double checked ray/cell transforms, no huge implicit dense region allocation. Clip to actual bounds + slice and dynamic depth or comparable ordering so unusual signed positions are not clipped by the legacy flattened shader constants. Keep old renderer unchanged for old 2D. Use real immutable prepared CPU data and actual D3D upload/render, camera-pan reuse and retained meshes across mutation.
|
||||
|
||||
## 7. Interfaces and data contracts
|
||||
NEW public terrain APIs for building immutable surface mesh/packet (a shared pointer accepted by D3DScene::render over existing PreparedGeometry or equivalent) and constrained screen/world ray picking. Return region/epoch or caller-held snapshot plus stable voxel, signed face normal, adjacent placement/work cell when representable, consulted chunk stamps incl neighbor/missing for stale check. GPU resources owned by UI as existing; do not expose mutable resident pointers. NEW generic DDA local to receiver if no pin primitive: deterministic exact boundary negative coordinate convention, finite distance/step budget, zero components/no-hit/inside/start exactly on plane/edge/corner ties with declared single face, outside/unavailable distinct. Avoid epsilon that scales poorly across world; one documented voxel cell convention shared between meshing and picking. Bound face budget before/while preparing and refuse atomically without replacing old displayed geometry.
|
||||
|
||||
## 8. Dependencies and integration
|
||||
Committed S02 actual region ready. No new World getter needed in this package; S18 will call terrain prepare and pick on the exact held published region after M02 owner. Expose next-point integration callback/document only if needed. Root will sign off and ff/merge existing S17 branch after publication of M01. Preceding user branches/MRs preserved.
|
||||
|
||||
## 9. Edge cases security and performance
|
||||
Negative floors/near int extrema/partial chunk boundaries, clipping slice (below/above whole region), camera pan/zoom/viewport, equal edge/corner traversal, unknown and unloaded neighbor occlusion, triangles orientation/cull/depth, overflows at INT_MIN/INT_MAX adjacency, WARP device reset/upload of older immutable packet. Respect real outcome with WARP, no physical 1080p60 claims. Keep CMake test registrations independent of running interactive controls, use offscreen captures where possible.
|
||||
|
||||
## 10. Acceptance criteria
|
||||
1. Build real signed two-page sample incl cutaway cave/passage, opendoor/closed, compare expected emitted faces and frozen old vs updated CPU buffers & distinct markers incl neighbor stamps. 2. Test/measure real offscreen WARP draws at controlled pixel samples and projected hit face/adjacent cell including slice and camera transforms, consistent crossing from both directions through x31/32 and negatives. 3. Ties/start-inside/zero direction/limits/unloaded/extremes explicit, refusal leaves displayed packet usable, camera-only no regeneration or upload when previous mesh valid. 4. Legacy viewer/frame tests pass, actual link and diagnostic output/issue links #12/#13 in docs. 5. Show bounded per world/page costs (prepared counts), no placeholder flat map geometry presented as voxel mode.
|
||||
|
||||
## 11. Verification commands and evidence
|
||||
Source /tmp/stoneheart-verify.KoZwE4o8/env.sh. From YOUR worktree configure cmake -S . -B /tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-build -G Ninja --toolchain "$SETTLEMENT_VERIFY/cross.cmake" -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_VOID_LIBRARY:PATH="$SETTLEMENT_VERIFY/candidate/_deps/void_library-src". Build with cmake --build <that dir> --parallel 6, run ctest --test-dir <that dir> --output-on-failure and your targeted tests. Evidence required. Run new registered voxel scene target showing real offscreen WARP output and full ctest -V; coordinate interactive keyboard control tests with root before running. Write s17-voxel-*.log and git diff --check. Non-Windows host does not establish native hardware perf.
|
||||
|
||||
## 12. Constraints and stop conditions
|
||||
Do not silently fallback to flat map for unsupported 3D or ray through unloaded cells. If dependency/API or D3D transform must change beyond local scope, notify root with targeted counterexample. No new upstream ticket without pin/duplicate research; user mandated genuine gaps, #12/#13 already cover this. No remote, children or claims of normal S18 integration until actual world is wired.
|
||||
|
||||
## 13. Authorization and decisions
|
||||
User authorized all milestones and system branches. Planner/F1 accepted 3D render/pick and actual shader basis. Reversible drawing/Face data layout choices delegated, root accepts final integration and posts remote work.
|
||||
|
||||
## 14. Return format
|
||||
Return S17-02 READY or PARTIAL, early stable public interface, verified real D3D pixel/pick behavior, touched paths, tests/limits/CPU-GPU retention and exact upcoming normal-viewer options.
|
||||
@@ -1,6 +1,6 @@
|
||||
# S17. D3D11-рендеринг, камера и визуальное состояние
|
||||
|
||||
Статус — S17-W01 реализован и проверен в Windows x64/Wine; ожидает независимой приёмки. Остальные этапы — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
Статус — S17-W01 и ограниченный объёмный API S17-02 реализованы и проверены в Windows x64/Wine, ожидают независимой приёмки. Подключение объёмного API к обычному игровому кадру выполняется отдельной задачей S18/World. Остальные этапы — план реализации. Клиент должен показывать редактируемый объёмный мир, позволять выбрать нужный этаж и сохранять отзывчивость во время симуляции, сохранения и сетевого обмена. Рендер развивается с [M01](../milestones/M01.md) до приёмки [M11](../milestones/M11.md). Главная ранняя сцена — [дом на склоне M03](../milestones/M03.md). [Мастер-план](../../../PLAN.md) · [Реестр паритета](../parity.md)
|
||||
|
||||
## Исходное состояние
|
||||
|
||||
@@ -29,6 +29,30 @@ S17-W01 сохраняет существующую плоскую карту и
|
||||
|
||||
Общий примитив публикации остаётся связан с [Void/Library #5](https://git.faumaray.com/Void/Library/issues/5). При его появлении заменить локальное владение только после тех же проверок старого пакета, вложенной установки и срока жизни геометрии. `PreparedFrame` и игровые правила формирования HUD остаются клиентскими данными.
|
||||
|
||||
## Объёмная сцена S17-02
|
||||
|
||||
[`prepare_voxel_scene`](../../../app/voxel_scene.hpp) принимает настоящий `VoxelRegion` S02, UUID экземпляра сессии, конечный объём показа внутри региона и включительный верхний слой `slice`. Результат совместно владеет неизменяемым снимком страниц, открытыми гранями и отсортированными `ChunkStamp` всех прочитанных страниц, включая отсутствующие и соседние. `current(region, session)` проверяет описание региона, экземпляр сессии и прочитанные ревизии. Изменение непрочитанной страницы оставляет геометрию пригодной. При замене мира вызывающая сторона меняет UUID.
|
||||
|
||||
Клетка занимает `[x,x+1) × [y,y+1) × [z,z+1)`. Почва, камень и закрытая дверь образуют непрозрачный куб. Воздух и открытая дверь дают видимый проход. Внутренние грани смежных занятых клеток не выпускаются, в том числе через границы страниц −32, 0 и 32. Отсечение объёмом показа и слоем открывает соответствующие граничные поверхности. Отсутствующие страницы показываются непрозрачными серыми гранями, а выбор останавливается с `Unavailable`, поэтому загруженный объект за неизвестной областью нельзя выбрать насквозь.
|
||||
|
||||
`D3DScene::prepare_voxels(scene)` создаёт настоящий CPU-пакет `PreparedGeometry`. `render(packet, VoxelCamera, capture)` загружает его в D3D11 и рисует треугольники. Координаты вершин отсчитываются от нижнего угла объёма показа, что сохраняет точность клеток рядом с `INT32_MIN` и `INT32_MAX`. Позиция этого угла на экране задаётся `origin_x/y`. Проекция сохраняет базис `(x-y)*halfTile.x, (x+y)*halfTile.y-z*16`, масштаб и смещение камеры. Глубина нормируется по объёму сцены. Прежний плоский пакет сохраняет прежние коэффициенты глубины `.96/.009`.
|
||||
|
||||
`pick_voxel_screen` использует тот же удержанный `VoxelScene` и ту же `VoxelCamera`, что и показанный пакет. Результат содержит регион, UUID сессии, клетку, одну нормаль грани, материал, расстояние и прочитанные ревизии. Соседняя клетка возвращается только при представимых координатах и может оказаться за границами региона, поэтому её допустимость для действия проверяет симуляция. `trace_voxels` также принимает произвольный конечный луч. Нулевое направление и нечисловые входы отвергаются. Начало внутри занятой клетки даёт `Inside` без грани. На точной плоскости знак направления выбирает следующую клетку, нулевой компонент оставляет луч в клетке, владеющей полуоткрытой границей. При одновременном переходе по нескольким осям меняются все эти координаты, а нормаль выбирается в порядке X, Y, Z. Клетки, которых луч касается только ребром, пропускаются. Масштабирование направления степенью двойки сохраняет точные отношения компонентов, включая проверенный случай 1:3.
|
||||
|
||||
По умолчанию подготовка ограничена 2 097 152 просматриваемыми клетками, 262 144 гранями, 1 024 прочитанными страницами, 4 096 клетками по каждой оси и 64 МиБ для граней, ёмкости каталога ревизий и развёрнутых CPU-вершин. Независимый предел оси 65 536 сохраняет представимость локальных координат даже при повышении бюджета. Грани сначала подсчитываются и проверяются, затем заполняется выделенный массив. Луч ограничен 16 384 посещёнными клетками и 1 024 страницами. Ошибка лимита или выделения памяти возвращается до публикации замены. Источник страниц, старые удержанные пакеты, накладные расходы аллокатора и GPU-память учитываются вызывающей стороной отдельно. Один квадрат разворачивается в шесть вершин по 24 байта.
|
||||
|
||||
Камера не входит в CPU-геометрию. Сдвиг и масштаб используют тот же пакет без повторной загрузки. Возврат к удержанному старому пакету и восстановление устройства загружают его вновь. Рост GPU-буфера сначала создаёт и заполняет замену, сохраняя прежний буфер при отказе. Пустой срез рисует только фон. Асинхронный диспетчер перестроения отдельных чанков, вращение камеры, обычное управление срезом через S18 и физический профиль производительности остаются последующими работами.
|
||||
|
||||
### Проверка S17-02
|
||||
|
||||
[`settlement_voxel_scene_tests`](../../../tests/voxel_scene_tests.cpp) содержит 15 проверок CPU-контрактов и настоящего offscreen D3D11/WARP. Пиксели известных верхних и боковых граней сверяются с результатом выбора, включая масштаб, сдвиг, срез крыши, открытый дверной проём, пропуск, лимит, неизвестную страницу и крайние знаковые координаты. Отдельная сцена использует генератор S02 на 16 страницах и 6 528 клетках, выдаёт 1 998 граней и 11 988 вершин. Отказ меньшего бюджета сохраняет отображаемый пакет и счётчик GPU-загрузок. Проверки удерживают старую геометрию после изменения материалов и пересоздания устройства.
|
||||
|
||||
Проверка из изолированного `s17-voxel` на базе `13dc673`, GCC 16.2.0, Windows x64/Wine 11.0, Release и закреплённой VoidLibrary `7b0fea6095f603f9e1904f66dfdc7752f4be4792` выполняется командами `cmake --build /tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-build --parallel 6`, `flock /tmp/stoneheart-milestones.xprJ2SVp/interactive-test.lock ctest --test-dir /tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-build -V` и `git diff --check`. Конфигурация использует согласованные `env.sh` и cross-toolchain из `/tmp/stoneheart-verify.KoZwE4o8`, `BUILD_TESTING=ON`. Журналы находятся в `/tmp/stoneheart-milestones.xprJ2SVp/s17-voxel-*.log`. Этот прогон не устанавливает физическую производительность 1080p60 или поведение драйвера на нативной Windows.
|
||||
|
||||
Наблюдаемый итог 2026-12-03 — сборка без предупреждений, 6/6 CTest за 17,60 с. Прошли 196 core, 17 LAN, 15 viewer session, 6 production controls, 15 voxel scene и отдельный настоящий frame smoke. Полный журнал — `s17-voxel-final-ctest.log`, сборка — `s17-voxel-final-build.log`. Native Windows, физическая GPU и искусственное исчерпание памяти драйвера не проверялись.
|
||||
|
||||
Публичные `Void::Math::Vec3` и `Void::Numeric::checked_*` используются из закреплённой версии. Локальный ограниченный 3D-обход связан с [Void/Library #12](https://git.faumaray.com/Void/Library/issues/12), каталог прочитанных ревизий — с [#13](https://git.faumaray.com/Void/Library/issues/13). Замена библиотечным API требует сохранить проверенные правила границ, неопределённости, лимитов, UUID сессии и инвалидирования соседних страниц. Форма клеток, материалы, дверной проём и включительный срез остаются игровыми правилами.
|
||||
|
||||
## Границы данных и потоков
|
||||
|
||||
Предлагаемый новый `PresentationSnapshot` содержит номер завершённого такта, экземпляр мира, постоянные идентификаторы видимых объектов, их позы и необходимые визуальные признаки. Геометрия чанка передаётся по идентификатору и ревизии. Каждый снимок неизменяем на всём сроке чтения. Ссылка рендера на изменяемый `World` заменяется чтением снимка.
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
#define NOMINMAX
|
||||
#include "d3d_scene_win32.hpp"
|
||||
#include "voxel_scene.hpp"
|
||||
|
||||
#include <Void/Testing/Suite.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace settlement;
|
||||
using namespace settlement::viewer;
|
||||
using Void::Testing::Test;
|
||||
using Mark = std::pair<VoxelPosition, MaterialId>;
|
||||
constexpr auto smallest = std::numeric_limits<std::int32_t>::min();
|
||||
constexpr auto largest = std::numeric_limits<std::int32_t>::max();
|
||||
|
||||
void require(bool condition, const char* message = "voxel scene invariant failed") {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
Void::Uuid::Uuid epoch(std::uint8_t value = 1) {
|
||||
Void::Uuid::Uuid result;
|
||||
result.bytes.back() = value;
|
||||
return result;
|
||||
}
|
||||
void load_page(VoxelRegion& region, ChunkCoordinate coordinate, std::span<const Mark> marks = {}) {
|
||||
std::vector<MaterialId> cells(voxel_chunk_cells, MaterialId::Air);
|
||||
for (const auto& [position, material] : marks) {
|
||||
const auto address = split_voxel(position);
|
||||
if (address.chunk == coordinate) cells[*voxel_index(address.local)] = material;
|
||||
}
|
||||
const auto candidate = region.prepare_restored(coordinate, 1, cells);
|
||||
require(candidate.has_value(), "restored fixture page refused");
|
||||
require(region.activate(std::span(&*candidate, 1)).has_value(), "fixture activation refused");
|
||||
}
|
||||
VoxelRegion loaded(VoxelBounds bounds, std::initializer_list<Mark> marks = {}) {
|
||||
VoxelRegion region({7, 42, voxel_generator_version, bounds});
|
||||
const auto first = split_voxel({static_cast<std::int32_t>(bounds.lower.x),
|
||||
static_cast<std::int32_t>(bounds.lower.y), static_cast<std::int32_t>(bounds.lower.z)}).chunk;
|
||||
const auto last = split_voxel({static_cast<std::int32_t>(bounds.upper.x - 1),
|
||||
static_cast<std::int32_t>(bounds.upper.y - 1), static_cast<std::int32_t>(bounds.upper.z - 1)}).chunk;
|
||||
for (auto z = first.z; z <= last.z; ++z) for (auto y = first.y; y <= last.y; ++y) {
|
||||
for (auto x = first.x; x <= last.x; ++x) load_page(region, {x, y, z}, {marks.begin(), marks.size()});
|
||||
}
|
||||
return region;
|
||||
}
|
||||
std::shared_ptr<const VoxelScene> prepare(const VoxelRegion& region, std::int32_t slice = largest) {
|
||||
auto result = prepare_voxel_scene(region, epoch(), {region.descriptor().bounds, slice});
|
||||
require(result.has_value(), "scene preparation refused");
|
||||
return *result;
|
||||
}
|
||||
void edit(VoxelRegion& region, VoxelPosition cell, MaterialId material) {
|
||||
const VoxelEdit change{cell, material, region.sample(cell).stamp.revision};
|
||||
require(region.edit(std::span(&change, 1)).has_value(), "fixture edit refused");
|
||||
}
|
||||
bool has_face(const VoxelScene& scene, VoxelPosition cell, VoxelPosition normal) {
|
||||
return std::ranges::any_of(scene.faces(), [&](const auto& face) { return face.cell == cell && face.normal == normal; });
|
||||
}
|
||||
VoxelPick trace(const VoxelScene& scene, VoxelPoint origin, VoxelPoint direction, double distance = 100) {
|
||||
auto result = trace_voxels(scene, {origin, direction, distance});
|
||||
require(result.has_value(), "valid ray refused");
|
||||
return *result;
|
||||
}
|
||||
void hit(const VoxelPick& pick, VoxelPosition cell, VoxelPosition normal) {
|
||||
require(pick.status == VoxelPickStatus::Hit, "ray did not hit");
|
||||
require(pick.cell == cell, "ray selected wrong cell");
|
||||
require(pick.normal == normal, "ray selected wrong face");
|
||||
}
|
||||
template<class T> void error(const std::expected<T, VoxelSceneError>& result, VoxelSceneError expected) {
|
||||
require(!result && result.error() == expected, "wrong error or successful refusal");
|
||||
}
|
||||
VoxelPick pixel_probe(D3DScene& renderer, std::shared_ptr<const PreparedGeometry> geometry,
|
||||
const VoxelScene& scene, VoxelCamera camera, VoxelPoint point, VoxelPosition cell, VoxelPosition normal) {
|
||||
const auto projected = project_voxel_point(scene, camera, point);
|
||||
require(projected.has_value(), "projection refused");
|
||||
const auto x = static_cast<int>(std::floor(projected->x));
|
||||
const auto y = static_cast<int>(std::floor(projected->y));
|
||||
require(x >= 0 && x < camera.width && y >= 0 && y < camera.height, "test point outside viewport");
|
||||
const auto pick = pick_voxel_screen(scene, camera, {x + .5, y + .5});
|
||||
require(pick.has_value(), "pixel ray refused");
|
||||
hit(*pick, cell, normal);
|
||||
std::vector<std::uint32_t> pixels;
|
||||
require(renderer.render(std::move(geometry), camera, &pixels), "offscreen D3D11 draw failed");
|
||||
const auto expected = voxel_face_color({pick->cell, pick->normal, pick->material,
|
||||
pick->status == VoxelPickStatus::Unavailable});
|
||||
const auto actual = pixels[static_cast<std::size_t>(y) * camera.width + x] & 0x00ffffffu;
|
||||
if (actual != expected) {
|
||||
std::cerr << "pixel " << x << ',' << y << " color " << std::hex << actual << " expected " << expected << std::dec << '\n';
|
||||
throw std::runtime_error("D3D pixel does not show the picked face");
|
||||
}
|
||||
return *pick;
|
||||
}
|
||||
|
||||
struct [[= Void::Testing::name("VoxelSceneTests")]] VoxelSceneTests : Void::Testing::Suite<VoxelSceneTests> {
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test exposed_faces_cross_signed_chunk_boundaries();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test slice_is_inclusive_and_snapshots_survive_edits();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test read_stamps_include_missing_and_neighbors_with_session_guard();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test unrelated_pages_do_not_invalidate_bounded_scene();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test closed_door_blocks_open_door_reveals_farther_surface();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test exact_plane_edge_and_corner_ties_are_directional();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test axis_rays_inside_parallel_and_misses();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test bounded_rays_and_nonfinite_inputs_are_refused();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test signed_extremes_use_checked_adjacent_cells();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test generation_budgets_fail_before_publishing_replacement();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test projection_and_pick_share_camera_and_slice();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test generated_signed_terrain_is_meshed_and_drawn();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test warp_pixels_match_faces_pan_zoom_and_retained_geometry();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test warp_slice_and_open_door_match_picks();
|
||||
[[= Void::Testing::tag("voxel-scene")]] Test warp_extreme_coordinates_missing_and_empty_scenes();
|
||||
};
|
||||
|
||||
Test VoxelSceneTests::exposed_faces_cross_signed_chunk_boundaries() {
|
||||
for (int seam : {-32, 0, 32}) {
|
||||
const auto region = loaded({{seam - 2, -1, 0}, {seam + 2, 1, 2}},
|
||||
{{{seam - 1, -1, 0}, MaterialId::Soil}, {{seam, -1, 0}, MaterialId::Stone}});
|
||||
const auto scene = prepare(region);
|
||||
require(scene->faces().size() == 10, "adjacent pages emitted duplicate internal faces");
|
||||
require(!has_face(*scene, {seam - 1, -1, 0}, {1, 0, 0}));
|
||||
require(!has_face(*scene, {seam, -1, 0}, {-1, 0, 0}));
|
||||
hit(trace(*scene, {seam - 3., -.5, .5}, {1, 0, 0}), {seam - 1, -1, 0}, {-1, 0, 0});
|
||||
hit(trace(*scene, {seam + 3., -.5, .5}, {-1, 0, 0}), {seam, -1, 0}, {1, 0, 0});
|
||||
require(scene->reads().size() == 4, "signed display pages absent from read set");
|
||||
}
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::slice_is_inclusive_and_snapshots_survive_edits() {
|
||||
auto region = loaded({{-1, -1, -1}, {2, 2, 3}},
|
||||
{{{0, 0, 0}, MaterialId::Stone}, {{0, 0, 1}, MaterialId::Soil}});
|
||||
const auto complete = prepare(region), cut = prepare(region, 0);
|
||||
require(complete->faces().size() == 10 && cut->faces().size() == 6);
|
||||
require(has_face(*cut, {0, 0, 0}, {0, 0, 1}) && !has_face(*complete, {0, 0, 0}, {0, 0, 1}));
|
||||
hit(trace(*complete, {.5, .5, 5}, {0, 0, -1}), {0, 0, 1}, {0, 0, 1});
|
||||
hit(trace(*cut, {.5, .5, 5}, {0, 0, -1}), {0, 0, 0}, {0, 0, 1});
|
||||
edit(region, {0, 0, 1}, MaterialId::Air);
|
||||
const auto changed = prepare(region);
|
||||
require(changed->faces().size() == 6 && complete->faces().size() == 10);
|
||||
require(!complete->current(region, epoch()) && changed->current(region, epoch()));
|
||||
hit(trace(*complete, {.5, .5, 5}, {0, 0, -1}), {0, 0, 1}, {0, 0, 1});
|
||||
require(prepare(region, -2)->faces().empty());
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::read_stamps_include_missing_and_neighbors_with_session_guard() {
|
||||
VoxelRegion region({7, 42, voxel_generator_version, {{30, 0, 0}, {34, 1, 1}}});
|
||||
const std::array marks{Mark{{31, 0, 0}, MaterialId::Stone}};
|
||||
load_page(region, {0, 0, 0}, marks);
|
||||
const auto before = prepare(region);
|
||||
require(before->reads().size() == 2 && before->reads()[1].availability == VoxelAvailability::Unavailable);
|
||||
require(!has_face(*before, {31, 0, 0}, {1, 0, 0}), "unknown adjacent page must occlude the shared face");
|
||||
const auto unresolved = trace(*before, {35, .5, .5}, {-1, 0, 0});
|
||||
require(unresolved.status == VoxelPickStatus::Unavailable && unresolved.cell == VoxelPosition{33, 0, 0});
|
||||
require(unresolved.current(region, epoch()) && !unresolved.current(region, epoch(2)));
|
||||
load_page(region, {1, 0, 0});
|
||||
require(!before->current(region, epoch()) && !unresolved.current(region, epoch()));
|
||||
const auto after = prepare(region);
|
||||
require(after->faces().size() == 6 && has_face(*after, {31, 0, 0}, {1, 0, 0}));
|
||||
require(!after->current(region, epoch(2)));
|
||||
hit(trace(*after, {35, .5, .5}, {-1, 0, 0}), {31, 0, 0}, {1, 0, 0});
|
||||
require(trace(*before, {35, .5, .5}, {-1, 0, 0}).status == VoxelPickStatus::Unavailable);
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::unrelated_pages_do_not_invalidate_bounded_scene() {
|
||||
auto region = loaded({{0, 0, 0}, {65, 1, 1}}, {{{0, 0, 0}, MaterialId::Stone}});
|
||||
const auto scene = prepare_voxel_scene(region, epoch(), {{{0, 0, 0}, {2, 1, 1}}, 0});
|
||||
require(scene.has_value() && (*scene)->reads().size() == 1);
|
||||
edit(region, {64, 0, 0}, MaterialId::Stone);
|
||||
require((*scene)->current(region, epoch()), "unconsulted page invalidated geometry");
|
||||
edit(region, {1, 0, 0}, MaterialId::Stone);
|
||||
require(!(*scene)->current(region, epoch()));
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::closed_door_blocks_open_door_reveals_farther_surface() {
|
||||
auto region = loaded({{30, -1, 0}, {34, 2, 3}},
|
||||
{{{32, 0, 1}, MaterialId::DoorClosed}, {{30, 0, 1}, MaterialId::Stone}});
|
||||
const auto closed = prepare(region);
|
||||
hit(trace(*closed, {34, .5, 1.5}, {-1, 0, 0}), {32, 0, 1}, {1, 0, 0});
|
||||
edit(region, {32, 0, 1}, MaterialId::DoorOpen);
|
||||
const auto open = prepare(region);
|
||||
require(closed->faces().size() == 12 && open->faces().size() == 6);
|
||||
hit(trace(*open, {34, .5, 1.5}, {-1, 0, 0}), {30, 0, 1}, {1, 0, 0});
|
||||
hit(trace(*closed, {34, .5, 1.5}, {-1, 0, 0}), {32, 0, 1}, {1, 0, 0});
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::exact_plane_edge_and_corner_ties_are_directional() {
|
||||
const auto region = loaded({{-2, -2, -2}, {2, 2, 2}},
|
||||
{{{0, 0, 0}, MaterialId::Stone}, {{-1, -1, -1}, MaterialId::Soil},
|
||||
{{-1, -1, 0}, MaterialId::Stone}});
|
||||
const auto scene = prepare(region);
|
||||
hit(trace(*scene, {0, .5, .5}, {1, 0, 0}), {0, 0, 0}, {-1, 0, 0});
|
||||
require(trace(*scene, {0, .5, .5}, {-1, 0, 0}).status == VoxelPickStatus::Miss);
|
||||
hit(trace(*scene, {0, 0, 0}, {1, 1, 1}), {0, 0, 0}, {-1, 0, 0});
|
||||
hit(trace(*scene, {0, 0, 0}, {-1, -1, -1}), {-1, -1, -1}, {1, 0, 0});
|
||||
hit(trace(*scene, {1.5, 1.5, 1.5}, {-1, -1, -1}), {0, 0, 0}, {1, 0, 0});
|
||||
hit(trace(*scene, {1.5, 1.5, .5}, {-1, -1, 0}), {0, 0, 0}, {1, 0, 0});
|
||||
const auto edge_only = prepare(loaded({{-2, -2, 0}, {2, 2, 1}},
|
||||
{{{-1, 0, 0}, MaterialId::Stone}, {{0, -1, 0}, MaterialId::Stone}}));
|
||||
require(trace(*edge_only, {1.5, 1.5, .5}, {-1, -1, 0}).status == VoxelPickStatus::Miss,
|
||||
"diagonal ray hit a voxel touched only along an edge");
|
||||
require(trace(*edge_only, {-.5, -1.5, .5}, {1, 3, 0}).status == VoxelPickStatus::Miss,
|
||||
"normalizing a 1:3 ray split an exact corner crossing");
|
||||
hit(trace(*scene, {-.5, -1.5, .5}, {1, 3, 0}), {-1, -1, 0}, {0, -1, 0});
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::axis_rays_inside_parallel_and_misses() {
|
||||
const auto scene = prepare(loaded({{-2, -2, -2}, {3, 3, 3}}, {{{0, 0, 0}, MaterialId::Stone}}));
|
||||
const std::array origins{VoxelPoint{-3, .5, .5}, VoxelPoint{4, .5, .5}, VoxelPoint{.5, -3, .5},
|
||||
VoxelPoint{.5, 4, .5}, VoxelPoint{.5, .5, -3}, VoxelPoint{.5, .5, 4}};
|
||||
const std::array directions{VoxelPoint{1, 0, 0}, VoxelPoint{-1, 0, 0}, VoxelPoint{0, 1, 0},
|
||||
VoxelPoint{0, -1, 0}, VoxelPoint{0, 0, 1}, VoxelPoint{0, 0, -1}};
|
||||
const std::array normals{VoxelPosition{-1, 0, 0}, VoxelPosition{1, 0, 0}, VoxelPosition{0, -1, 0},
|
||||
VoxelPosition{0, 1, 0}, VoxelPosition{0, 0, -1}, VoxelPosition{0, 0, 1}};
|
||||
for (std::size_t i = 0; i < origins.size(); ++i) {
|
||||
const auto picked = trace(*scene, origins[i], directions[i]);
|
||||
hit(picked, {0, 0, 0}, normals[i]);
|
||||
require(picked.adjacent == normals[i] && picked.distance == 3);
|
||||
}
|
||||
const auto inside = trace(*scene, {.5, .5, .5}, {1, 0, 0});
|
||||
require(inside.status == VoxelPickStatus::Inside && inside.distance == 0 &&
|
||||
inside.normal == VoxelPosition{} && !inside.adjacent);
|
||||
require(trace(*scene, {-3, 3, .5}, {1, 0, 0}).status == VoxelPickStatus::Miss);
|
||||
require(trace(*scene, {-3, .5, .5}, {1, 0, 0}, 2.9).status == VoxelPickStatus::Miss);
|
||||
hit(trace(*scene, {-3, .5, .5}, {1, 0, 0}, 3), {0, 0, 0}, {-1, 0, 0});
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::bounded_rays_and_nonfinite_inputs_are_refused() {
|
||||
const auto scene = prepare(loaded({{-2, 0, 0}, {4, 1, 1}}, {{{3, 0, 0}, MaterialId::Stone}}));
|
||||
error(trace_voxels(*scene, {{-3, .5, .5}, {1, 0, 0}, 20}, {2, 10}), VoxelSceneError::LimitExceeded);
|
||||
error(trace_voxels(*scene, {{-3, .5, .5}, {1, 0, 0}, 20}, {20, 1}), VoxelSceneError::LimitExceeded);
|
||||
error(trace_voxels(*scene, {{0, .5, .5}, {}, 20}), VoxelSceneError::InvalidInput);
|
||||
error(trace_voxels(*scene, {{0, .5, .5}, {1, 0, 0}, -1}), VoxelSceneError::InvalidInput);
|
||||
const auto nan = std::numeric_limits<double>::quiet_NaN(), inf = std::numeric_limits<double>::infinity();
|
||||
error(trace_voxels(*scene, {{nan, 0, 0}, {1, 0, 0}, 20}), VoxelSceneError::InvalidInput);
|
||||
error(trace_voxels(*scene, {{0, 0, 0}, {inf, 0, 0}, 20}), VoxelSceneError::InvalidInput);
|
||||
error(trace_voxels(*scene, {{0, 0, 0}, {1, 0, 0}, inf}), VoxelSceneError::InvalidInput);
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::signed_extremes_use_checked_adjacent_cells() {
|
||||
for (auto value : {smallest, largest}) {
|
||||
const std::int64_t first = value == smallest ? value : std::int64_t{value} - 1;
|
||||
const auto scene = prepare(loaded({{first, first, first}, {first + 2, first + 2, first + 2}},
|
||||
{{{value, value, value}, MaterialId::Stone}}));
|
||||
const double v = value;
|
||||
const auto origin = value == smallest ? VoxelPoint{v - 1, v + .5, v + .5} : VoxelPoint{v + 2, v + .5, v + .5};
|
||||
const auto direction = value == smallest ? VoxelPoint{1, 0, 0} : VoxelPoint{-1, 0, 0};
|
||||
const VoxelPosition normal{value == smallest ? -1 : 1, 0, 0};
|
||||
const auto pick = trace(*scene, origin, direction);
|
||||
hit(pick, {value, value, value}, normal);
|
||||
require(!pick.adjacent, "adjacent cell overflowed a signed coordinate");
|
||||
require(scene->faces().size() == 6);
|
||||
}
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::generation_budgets_fail_before_publishing_replacement() {
|
||||
const auto region = loaded({{0, 0, 0}, {2, 2, 2}}, {{{0, 0, 0}, MaterialId::Stone}});
|
||||
const auto held = prepare(region);
|
||||
auto options = held->options();
|
||||
options.limits.max_cells = 7;
|
||||
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::LimitExceeded);
|
||||
options = held->options(); options.limits.max_faces = 5;
|
||||
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::LimitExceeded);
|
||||
options = held->options(); options.limits.max_read_chunks = 0;
|
||||
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::LimitExceeded);
|
||||
options = held->options(); options.limits.max_bytes = 1;
|
||||
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::LimitExceeded);
|
||||
options = held->options(); options.limits.max_axis = 1;
|
||||
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::LimitExceeded);
|
||||
options = held->options(); options.bounds.lower.x = -1;
|
||||
error(prepare_voxel_scene(region, epoch(), options), VoxelSceneError::InvalidInput);
|
||||
require(held->current(region, epoch()) && held->faces().size() == 6);
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::projection_and_pick_share_camera_and_slice() {
|
||||
const auto scene = prepare(loaded({{-3, -3, -2}, {4, 4, 4}},
|
||||
{{{0, 0, 0}, MaterialId::Stone}, {{0, 0, 1}, MaterialId::Soil}}), 0);
|
||||
for (double scale : {.65, 1., 2.5, 4.}) {
|
||||
const VoxelCamera camera{800, 600, 400.25, 300.75, scale};
|
||||
const auto point = project_voxel_point(*scene, camera, {.5, .5, 1});
|
||||
require(point.has_value());
|
||||
const auto pick = pick_voxel_screen(*scene, camera, *point);
|
||||
require(pick.has_value());
|
||||
hit(*pick, {0, 0, 0}, {0, 0, 1});
|
||||
}
|
||||
VoxelCamera camera{800, 600, 400, 300, 1};
|
||||
error(pick_voxel_screen(*scene, camera, {800, 0}), VoxelSceneError::InvalidInput);
|
||||
error(pick_voxel_screen(*scene, camera, {0, -1}), VoxelSceneError::InvalidInput);
|
||||
camera.scale = 0;
|
||||
require(!valid_voxel_camera(camera) && !project_voxel_point(*scene, camera, {.5, .5, 1}));
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::generated_signed_terrain_is_meshed_and_drawn() {
|
||||
const VoxelBounds bounds{{-34, -2, -12}, {34, 2, 12}};
|
||||
VoxelRegion region({7, 42, voxel_generator_version, bounds});
|
||||
std::vector<PreparedVoxelChunk> pages;
|
||||
for (int z = -1; z <= 0; ++z) for (int y = -1; y <= 0; ++y) {
|
||||
for (int x = -2; x <= 1; ++x) {
|
||||
const auto candidate = region.prepare_generated({x, y, z});
|
||||
require(candidate.has_value());
|
||||
pages.push_back(*candidate);
|
||||
}
|
||||
}
|
||||
require(region.activate(pages).has_value());
|
||||
const auto scene = prepare(region);
|
||||
require(scene->reads().size() == 16 && !scene->faces().empty());
|
||||
const auto top = [&](int x, int y) {
|
||||
for (int z = 11; z >= -12; --z) {
|
||||
if (voxel_blocks_passage(region.sample({x, y, z}).material)) return z;
|
||||
}
|
||||
throw std::runtime_error("generated column lacks solid terrain");
|
||||
};
|
||||
for (int x : {-33, -32, -1, 0, 31, 32, 33}) {
|
||||
const int z = top(x, 1);
|
||||
hit(trace(*scene, {x + .5, 1.5, 13}, {0, 0, -1}), {x, 1, z}, {0, 0, 1});
|
||||
require(has_face(*scene, {x, 1, z}, {0, 0, 1}));
|
||||
}
|
||||
const auto geometry = D3DScene::prepare_voxels(scene);
|
||||
require(geometry.has_value());
|
||||
D3DScene renderer;
|
||||
require(renderer.initialize(nullptr, true));
|
||||
const VoxelCamera camera{1280, 800, 200, 200, 1};
|
||||
const int z = top(33, 1);
|
||||
pixel_probe(renderer, *geometry, *scene, camera, {33.5, 1.5, z + 1.}, {33, 1, z}, {0, 0, 1});
|
||||
const auto missed = pick_voxel_screen(*scene, camera, {20.5, 20.5});
|
||||
require(missed && missed->status == VoxelPickStatus::Miss);
|
||||
std::vector<std::uint32_t> pixels;
|
||||
require(renderer.render(*geometry, camera, &pixels));
|
||||
require(pixels[20 * camera.width + 20] == pixels.front(), "missed ray has terrain pixels");
|
||||
const auto point = project_voxel_point(*scene, camera, {33.5, 1.5, z + 1.});
|
||||
require(point.has_value());
|
||||
error(pick_voxel_screen(*scene, camera, *point, {0, 1024}), VoxelSceneError::LimitExceeded);
|
||||
auto refused = scene->options();
|
||||
refused.limits.max_faces = scene->faces().size() - 1;
|
||||
error(prepare_voxel_scene(region, epoch(), refused), VoxelSceneError::LimitExceeded);
|
||||
pixel_probe(renderer, *geometry, *scene, camera, {33.5, 1.5, z + 1.}, {33, 1, z}, {0, 0, 1});
|
||||
require(renderer.uploads() == 1, "refusal replaced the retained GPU geometry");
|
||||
std::cout << "WARP generated signed terrain: 6528 cells, 16 consulted pages, " << scene->faces().size()
|
||||
<< " faces, " << scene->faces().size() * 6 << " vertices; miss and budget refusal preserve displayed packet\n";
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::warp_pixels_match_faces_pan_zoom_and_retained_geometry() {
|
||||
auto region = loaded({{-2, -2, -2}, {3, 3, 3}}, {{{0, 0, 0}, MaterialId::Stone}});
|
||||
const auto scene = prepare(region);
|
||||
const auto geometry = D3DScene::prepare_voxels(scene);
|
||||
require(geometry.has_value());
|
||||
D3DScene renderer;
|
||||
require(renderer.initialize(nullptr, true), "WARP device unavailable");
|
||||
VoxelCamera camera{640, 480, 320, 230, 3};
|
||||
pixel_probe(renderer, *geometry, *scene, camera, {.5, .5, 1}, {0, 0, 0}, {0, 0, 1});
|
||||
pixel_probe(renderer, *geometry, *scene, camera, {1, .5, .5}, {0, 0, 0}, {1, 0, 0});
|
||||
pixel_probe(renderer, *geometry, *scene, camera, {.5, 1, .5}, {0, 0, 0}, {0, 1, 0});
|
||||
camera.origin_x += 31; camera.origin_y -= 17; camera.scale = 2;
|
||||
pixel_probe(renderer, *geometry, *scene, camera, {.5, .5, 1}, {0, 0, 0}, {0, 0, 1});
|
||||
require(renderer.uploads() == 1, "camera-only render uploaded geometry again");
|
||||
edit(region, {0, 0, 0}, MaterialId::Soil);
|
||||
const auto changed = prepare(region);
|
||||
const auto next_geometry = D3DScene::prepare_voxels(changed);
|
||||
require(next_geometry.has_value());
|
||||
pixel_probe(renderer, *next_geometry, *changed, camera, {.5, .5, 1}, {0, 0, 0}, {0, 0, 1});
|
||||
pixel_probe(renderer, *geometry, *scene, camera, {.5, .5, 1}, {0, 0, 0}, {0, 0, 1});
|
||||
require(renderer.uploads() == 3, "return to immutable old packet did not upload it");
|
||||
renderer.reset();
|
||||
require(renderer.initialize(nullptr, true));
|
||||
pixel_probe(renderer, *geometry, *scene, camera, {.5, .5, 1}, {0, 0, 0}, {0, 0, 1});
|
||||
require(renderer.uploads() == 4);
|
||||
std::cout << "WARP terrain: 6 faces, 36 vertices; top/+X/+Y pixel probes, pan/zoom, old packet and reset passed\n";
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::warp_slice_and_open_door_match_picks() {
|
||||
auto region = loaded({{-2, -2, -1}, {3, 3, 4}},
|
||||
{{{0, 0, 0}, MaterialId::Stone}, {{0, 0, 1}, MaterialId::DoorClosed},
|
||||
{{0, 0, 2}, MaterialId::Soil}, {{-1, -1, 0}, MaterialId::Stone}});
|
||||
const auto complete = prepare(region), cut = prepare(region, 1);
|
||||
const auto complete_geometry = D3DScene::prepare_voxels(complete), cut_geometry = D3DScene::prepare_voxels(cut);
|
||||
require(complete_geometry.has_value() && cut_geometry.has_value());
|
||||
D3DScene renderer;
|
||||
require(renderer.initialize(nullptr, true));
|
||||
const VoxelCamera camera{640, 480, 320, 280, 4};
|
||||
pixel_probe(renderer, *complete_geometry, *complete, camera, {.5, .5, 3}, {0, 0, 2}, {0, 0, 1});
|
||||
pixel_probe(renderer, *cut_geometry, *cut, camera, {.5, .5, 2}, {0, 0, 1}, {0, 0, 1});
|
||||
pixel_probe(renderer, *cut_geometry, *cut, camera, {1, .5, 1.5}, {0, 0, 1}, {1, 0, 0});
|
||||
edit(region, {0, 0, 1}, MaterialId::DoorOpen);
|
||||
const auto open = prepare(region, 1);
|
||||
const auto open_geometry = D3DScene::prepare_voxels(open);
|
||||
require(open_geometry.has_value());
|
||||
pixel_probe(renderer, *open_geometry, *open, camera, {1, .5, 1.5}, {-1, -1, 0}, {1, 0, 0});
|
||||
pixel_probe(renderer, *cut_geometry, *cut, camera, {1, .5, 1.5}, {0, 0, 1}, {1, 0, 0});
|
||||
std::cout << "WARP cutaway: inclusive roof/door slices and open aperture select the actual farther stone pixel\n";
|
||||
}
|
||||
|
||||
Test VoxelSceneTests::warp_extreme_coordinates_missing_and_empty_scenes() {
|
||||
D3DScene renderer;
|
||||
require(renderer.initialize(nullptr, true));
|
||||
const VoxelCamera camera{640, 480, 320, 280, 4};
|
||||
for (auto value : {smallest, largest}) {
|
||||
const std::int64_t first = value == smallest ? value : std::int64_t{value} - 1;
|
||||
const auto scene = prepare(loaded({{first, first, first}, {first + 2, first + 2, first + 2}},
|
||||
{{{value, value, value}, MaterialId::Stone}}));
|
||||
const auto geometry = D3DScene::prepare_voxels(scene);
|
||||
require(geometry.has_value());
|
||||
const double v = value;
|
||||
pixel_probe(renderer, *geometry, *scene, camera, {v + .5, v + .5, v + 1}, {value, value, value}, {0, 0, 1});
|
||||
}
|
||||
VoxelRegion unknown({7, 42, voxel_generator_version, {{0, 0, 0}, {1, 1, 1}}});
|
||||
const auto scene = prepare(unknown);
|
||||
const auto geometry = D3DScene::prepare_voxels(scene);
|
||||
require(geometry.has_value());
|
||||
const auto point = project_voxel_point(*scene, camera, {.5, .5, 1});
|
||||
require(point.has_value());
|
||||
const auto pick = pick_voxel_screen(*scene, camera, *point);
|
||||
require(pick && pick->status == VoxelPickStatus::Unavailable);
|
||||
std::vector<std::uint32_t> pixels;
|
||||
require(renderer.render(*geometry, camera, &pixels));
|
||||
const auto index = static_cast<std::size_t>(std::floor(point->y)) * camera.width + static_cast<std::size_t>(std::floor(point->x));
|
||||
require((pixels[index] & 0xffffffu) == voxel_face_color({{0, 0, 0}, {0, 0, 1}, MaterialId::Air, true}));
|
||||
const auto empty_scene = prepare(unknown, -1);
|
||||
const auto empty_geometry = D3DScene::prepare_voxels(empty_scene);
|
||||
require(empty_geometry.has_value());
|
||||
require(renderer.render(*empty_geometry, camera, &pixels), "empty terrain draw failed");
|
||||
require(std::ranges::all_of(pixels, [&](auto pixel) { return pixel == pixels.front(); }));
|
||||
const auto miss = pick_voxel_screen(*empty_scene, camera, *point);
|
||||
require(miss && miss->status == VoxelPickStatus::Miss);
|
||||
require(renderer.render(*geometry, camera));
|
||||
std::cout << "WARP terrain: INT32_MIN/INT32_MAX local coordinates, unknown occlusion, empty slice passed\n";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
Reference in new issue
Block a user