standalone: VoxelForgeCore library -- the fast generator behind a clean C++20 API, output unchanged
- Standalone/Core: public header VoxelForgeCore.h (no Unreal types), static library target, ResolvedWorldSnapshot (from the schema-v1 JSON), World (compile, generateTile, density/sign, point/segment solid, classifyBox), host-supplied JobScheduler (the core starts no threads), sequenced, idempotent EditTransaction returning affected tiles per LOD. - The viewer, benchmarks, edits and audits run on Core; StreamingWorld stays host code. - Same as round 11: 11 hash rows at W1 and W8, routes 5642/5642, look/passage/far audits pass, bad-shell control fails, six fixed captures byte-identical; cold W8 1.025 s vs 1.041 s reference. - SHARED_CPP_LIBRARY_PLAN.md rewritten for a UBT module compiling the same sources via shims. Open issue before Unreal: Core's implementation still compiles the Compat stand-ins named like Unreal types (TArray, FVector...); inside a UE binary that is an ODR clash. Must be namespaced. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MmSoF64BbRFmk9C3p1VsBJ
This commit is contained in:
1 parent
631dd57eb4
commit
557f6aac30
22 files changed
+6185
-5063
No files matched your search
@@ -0,0 +1,111 @@
|
||||
# VoxelForgeCore API reference
|
||||
|
||||
Public header: `Core/include/VoxelForgeCore/VoxelForgeCore.h` (C++20, standard library only).
|
||||
Build the static library and viewer with `Build.ps1 -Target All`, or only the library with
|
||||
`Build.ps1 -Target Core`.
|
||||
|
||||
## Units and ownership
|
||||
|
||||
- `Vec3d` query positions and `Vec3i` voxel coordinates are in **voxels**.
|
||||
- `TileKey.coordinate` is a tile coordinate; one coordinate step spans `32 << lod` voxels.
|
||||
- Mesh vertex positions are **centimetres**. UVs, RGBA8 colors, normals and 32-bit indices are
|
||||
returned per vertex / triangle in owned `std::vector`s.
|
||||
- `MeshGroups::groundTriangleCount` and `ceilingTriangleCount` describe the contiguous index runs
|
||||
emitted by the mesher. Ceiling is the final run. `skirtTriangleCount` is a subset of the ground
|
||||
and ceiling runs. `surfaceVertexCount` ends before skirt vertices.
|
||||
- A `World` owns its compiled field and edit log. The snapshot can be shared as immutable input.
|
||||
Serialize compile/edit changes against query and tile-generation calls on that same `World`.
|
||||
|
||||
## Load and compile
|
||||
|
||||
`ResolvedWorldSnapshot::FromJson` accepts the normalized UTF-8 schema-v1 owner export used by the
|
||||
standalone loader. It returns `std::nullopt` and fills `error` when parsing or asset resolution
|
||||
fails. Read `configuration()` for the resolved scalar settings.
|
||||
|
||||
Implement `JobScheduler::parallel_for` in the host. It must run each index from zero to `count - 1`
|
||||
exactly once and return only after all submitted work is complete. The library creates no threads.
|
||||
`ShapeBuildRequest` supplies the detail and clip bounds in voxels, worker limit, detail variant,
|
||||
far-world inclusion, and optional tunnel/detail profiles.
|
||||
|
||||
```cpp
|
||||
std::string error;
|
||||
auto snapshot = VoxelForgeCore::ResolvedWorldSnapshot::FromJson(json, error);
|
||||
if (!snapshot) { /* report error */ }
|
||||
|
||||
VoxelForgeCore::World world(std::move(*snapshot));
|
||||
VoxelForgeCore::ShapeBuildRequest build;
|
||||
build.minVoxel = {-256, -768, -384};
|
||||
build.maxVoxel = { 256, -256, 128};
|
||||
build.clipMinVoxel = {-57344, -57344, -8192};
|
||||
build.clipMaxVoxel = { 49152, 49152, 8192};
|
||||
build.workerLimit = 8;
|
||||
build.includeFarWorld = true;
|
||||
if (!world.compile(build, hostScheduler, error)) { /* report error */ }
|
||||
```
|
||||
|
||||
## Queries and tiles
|
||||
|
||||
`densityAt(position)` returns signed density; negative is solid and nonnegative is air.
|
||||
`isSolidAt` wraps that sign test. `isSolidAlongSegment(start, end, spacing)` samples evenly along
|
||||
the segment with no interval wider than `spacing` voxels; it returns true if any sample is solid.
|
||||
`classifyBox(origin, step, cells)` returns `allSolid`, `allAir` or `mixed` for mesher tile
|
||||
classification.
|
||||
|
||||
`desiredTiles(cameraVoxels)` returns the snapshot's clipmap set. Pass it to
|
||||
`prioritizeTiles(tiles, centerChunk)` when submitting work. Generate independent keys concurrently
|
||||
on host workers:
|
||||
|
||||
```cpp
|
||||
VoxelForgeCore::TileGenerationOptions options;
|
||||
auto mesh = world.generateTile(key, options, error);
|
||||
if (!mesh) { /* report error */ }
|
||||
// mesh->vertices, mesh->indices and mesh->groups are owned by this result.
|
||||
```
|
||||
|
||||
The optional `hashDensity` flag fills deterministic density, viewer-mesh, payload and topology
|
||||
hashes. `captureDensitySamples` is a diagnostic option and retains the sampled lattice values.
|
||||
|
||||
## Deterministic edits
|
||||
|
||||
Build an `EditTransaction` with a monotonically increasing authority sequence and an ordered brush
|
||||
array (`sphere`, `capsule`, `roundedBox`; `carve`, `addRock`, `densityOffset`). `carve` and
|
||||
`addRock` apply hard signed-distance CSG. `densityOffset` applies `strength` inside a sphere or
|
||||
inside/around a capsule or box with its `falloff` band; negative strength carves and positive
|
||||
strength adds rock. This operation maps the plugin's soft `FVoxelModification` brushes into the
|
||||
shared field. Apply the transaction against the currently desired keys:
|
||||
|
||||
```cpp
|
||||
VoxelForgeCore::EditTransaction edit;
|
||||
edit.sequence = 12;
|
||||
VoxelForgeCore::EditBrush brush;
|
||||
brush.shape = VoxelForgeCore::EditBrush::Shape::capsule;
|
||||
brush.operation = VoxelForgeCore::EditBrush::Operation::densityOffset;
|
||||
brush.a = {0.0, 0.0, 0.0};
|
||||
brush.b = {12.0, 0.0, 0.0};
|
||||
brush.radius = 3.0;
|
||||
brush.strength = -10.0f;
|
||||
brush.falloff = 2.0f;
|
||||
edit.brushes.push_back(brush);
|
||||
const auto affected = world.applyEditTransaction(edit, currentTiles, error);
|
||||
if (affected) {
|
||||
for (const auto& lodTiles : affected->affectedByLod)
|
||||
for (const auto& key : lodTiles)
|
||||
submitHostJob([&, key] {
|
||||
std::string tileError;
|
||||
return world.generateTile(key, options, tileError);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
The transaction digest covers the sequence and each brush field in order. Replaying the same
|
||||
sequence and values returns the original result; reusing a sequence with different values or
|
||||
applying an older sequence is rejected. Each client must deserialize identical brush values and
|
||||
apply transactions in the same sequence. `affectedByLod` is limited to the desired keys passed to
|
||||
the call.
|
||||
|
||||
## Other outputs
|
||||
|
||||
`farConnectorSegments()` returns owned connector geometry, while `farConnectorCandidates(min,max)`
|
||||
returns candidate indices overlapping a voxel-space box. The audit methods expose shape detail,
|
||||
surface-family and camera-look checks for host diagnostics. All returned values are standard C++;
|
||||
the host owns conversion to engine mesh, collision or renderer objects.
|
||||
@@ -0,0 +1,20 @@
|
||||
# One relative source path per translation unit. Build.ps1 consumes this manifest; a future UBT
|
||||
# module should use the same list to generate one thin source include shim per row.
|
||||
Core/src/VoxelForgeCore.cpp
|
||||
Compat/UnrealPerlin.cpp
|
||||
Compat/StandaloneDataAssetGlue.cpp
|
||||
Source/VoxelForge/Private/VoxelBiomeDefinition.cpp
|
||||
Source/VoxelForge/Private/VoxelCaveMorphology.cpp
|
||||
Source/VoxelForge/Private/VoxelDensityAblation.cpp
|
||||
Source/VoxelForge/Private/VoxelDensityOpStack.cpp
|
||||
Source/VoxelForge/Private/VoxelDensityProfile.cpp
|
||||
Source/VoxelForge/Private/VoxelDiffLayer.cpp
|
||||
Source/VoxelForge/Private/VoxelGenerator.cpp
|
||||
Source/VoxelForge/Private/VoxelHeightOpStack.cpp
|
||||
Source/VoxelForge/Private/VoxelMarchingCubesMesher.cpp
|
||||
Source/VoxelForge/Private/VoxelSettings.cpp
|
||||
Source/VoxelForge/Private/VoxelStrateComposer.cpp
|
||||
Source/VoxelForge/Private/VoxelStrateManager.cpp
|
||||
Source/VoxelForge/Private/VoxelStrateMeasure.cpp
|
||||
Source/VoxelForge/Private/VoxelTerrainOpDefinition.cpp
|
||||
Source/VoxelForge/Private/VoxelWormField.cpp
|
||||
@@ -0,0 +1,235 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace VoxelForgeCore
|
||||
{
|
||||
struct Vec2f { float x = 0.0f, y = 0.0f; };
|
||||
struct Vec3d { double x = 0.0, y = 0.0, z = 0.0; };
|
||||
struct Vec3i { std::int32_t x = 0, y = 0, z = 0; };
|
||||
|
||||
struct TileKey
|
||||
{
|
||||
Vec3i coordinate{}; // Units of (32 << lod) voxels.
|
||||
std::int32_t lod = 0;
|
||||
friend bool operator==(const TileKey&, const TileKey&) = default;
|
||||
};
|
||||
|
||||
struct TileKeyHash
|
||||
{
|
||||
std::size_t operator()(const TileKey& key) const noexcept;
|
||||
};
|
||||
|
||||
struct ColorRgba8 { std::uint8_t r = 0, g = 0, b = 0, a = 0; };
|
||||
|
||||
struct MeshVertex
|
||||
{
|
||||
Vec3d position; // World centimetres, matching the density field coordinate system.
|
||||
Vec3d normal;
|
||||
Vec2f uv;
|
||||
ColorRgba8 color;
|
||||
};
|
||||
|
||||
struct MeshGroups
|
||||
{
|
||||
std::uint32_t surfaceVertexCount = 0;
|
||||
std::uint32_t groundTriangleCount = 0; // Ground index run; includes skirts emitted from ground faces.
|
||||
std::uint32_t ceilingTriangleCount = 0; // Final index run belongs to the ceiling group.
|
||||
std::uint32_t skirtTriangleCount = 0;
|
||||
};
|
||||
|
||||
struct TileMesh
|
||||
{
|
||||
TileKey key;
|
||||
std::vector<MeshVertex> vertices;
|
||||
std::vector<std::uint32_t> indices;
|
||||
std::vector<float> debugDensitySamples;
|
||||
MeshGroups groups;
|
||||
std::uint64_t densitySampleCount = 0;
|
||||
std::uint64_t meshPayloadAllocatedBytes = 0;
|
||||
std::uint64_t densityHash = 0, meshHash = 0, payloadHash = 0, topologyHash = 0;
|
||||
bool hasDensityHash = false, hasMeshHash = false, hasPayloadHash = false, hasTopologyHash = false;
|
||||
};
|
||||
|
||||
struct WorldConfiguration
|
||||
{
|
||||
std::int32_t seed = 0;
|
||||
std::int32_t clipRadius = 0;
|
||||
std::int32_t maxLod = 0;
|
||||
std::int32_t fullResolutionLodCount = 0;
|
||||
std::int32_t coarseTileCells = 0;
|
||||
std::int32_t renderDistanceChunks = 0;
|
||||
std::int32_t contentCutMinLod = 0;
|
||||
std::int32_t skirtCells = 0;
|
||||
std::int32_t lodOctaveDrop = 0;
|
||||
std::int32_t viewDistanceUp = 0;
|
||||
std::int32_t viewDistanceDown = 0;
|
||||
std::int32_t strateViewMarginChunks = 0;
|
||||
bool clampViewToStrate = false;
|
||||
bool generateSkirts = false;
|
||||
bool viewerStartFound = false;
|
||||
Vec3d viewerStartVoxels{};
|
||||
};
|
||||
|
||||
class ResolvedWorldSnapshot
|
||||
{
|
||||
public:
|
||||
ResolvedWorldSnapshot() = default;
|
||||
|
||||
// Schema-v1 is the normalized, resolved UTF-8 owner snapshot written by the standalone
|
||||
// exporter. Hosts may build the same document from their own resolved assets.
|
||||
static std::optional<ResolvedWorldSnapshot> FromJson(
|
||||
std::string_view json, std::string& error);
|
||||
|
||||
explicit operator bool() const noexcept { return static_cast<bool>(data_); }
|
||||
const WorldConfiguration& configuration() const;
|
||||
|
||||
private:
|
||||
struct Data;
|
||||
explicit ResolvedWorldSnapshot(std::shared_ptr<const Data> data) : data_(std::move(data)) {}
|
||||
std::shared_ptr<const Data> data_;
|
||||
friend class World;
|
||||
friend struct detail_StandaloneSnapshotAdapter;
|
||||
};
|
||||
|
||||
// The library requests work; the host decides whether that means a pool, fibers, or serial
|
||||
// execution. The callback must run every index in [0,count) exactly once before returning.
|
||||
class JobScheduler
|
||||
{
|
||||
public:
|
||||
using Task = void(*)(void* context, std::size_t index, std::size_t workerIndex);
|
||||
virtual ~JobScheduler() = default;
|
||||
virtual double parallel_for(std::size_t count, std::size_t batchSize,
|
||||
std::size_t workerLimit, void* context, Task task,
|
||||
double* workerActiveSeconds,
|
||||
std::size_t workerActiveCapacity) const = 0;
|
||||
};
|
||||
|
||||
enum class DetailVariant : std::uint8_t { coherent, smooth, perVoxel };
|
||||
enum class TileClass : std::uint8_t { allSolid, allAir, mixed };
|
||||
|
||||
struct ShapeBuildRequest
|
||||
{
|
||||
Vec3i minVoxel{};
|
||||
Vec3i maxVoxel{};
|
||||
Vec3i clipMinVoxel{};
|
||||
Vec3i clipMaxVoxel{};
|
||||
std::uint32_t workerLimit = 1;
|
||||
DetailVariant detail = DetailVariant::coherent;
|
||||
bool includeFarWorld = false;
|
||||
bool roundTunnels = false;
|
||||
bool enhancedTunnelWalls = true;
|
||||
bool profileDetailBand = false;
|
||||
};
|
||||
|
||||
struct ShapeBuildStats
|
||||
{
|
||||
double shapeSeconds = 0.0;
|
||||
double intervalSeconds = 0.0;
|
||||
double surfaceSeconds = 0.0;
|
||||
double farShapeSeconds = 0.0;
|
||||
std::uint64_t primitiveCount = 0;
|
||||
std::uint64_t surfaceCandidates = 0;
|
||||
std::uint64_t detailFlips = 0;
|
||||
std::uint64_t walkSamples = 0;
|
||||
std::uint64_t walkFailures = 0;
|
||||
};
|
||||
|
||||
struct FarConnectorSegment { Vec3d start, end; float radius = 0.0f; };
|
||||
|
||||
struct EditBrush
|
||||
{
|
||||
enum class Shape : std::uint8_t { sphere, capsule, roundedBox };
|
||||
enum class Operation : std::uint8_t { carve, addRock, densityOffset };
|
||||
Shape shape = Shape::sphere;
|
||||
Operation operation = Operation::carve;
|
||||
Vec3d a{}, b{}, halfExtent{};
|
||||
double radius = 0.0;
|
||||
double rounding = 0.0;
|
||||
float strength = 0.0f; // densityOffset only: negative carves, positive adds rock.
|
||||
float falloff = 0.0f; // densityOffset fade band in voxels.
|
||||
};
|
||||
|
||||
struct EditTransaction
|
||||
{
|
||||
// Sequence is supplied by the authority and participates in the deterministic digest.
|
||||
std::uint64_t sequence = 0;
|
||||
std::vector<EditBrush> brushes;
|
||||
};
|
||||
|
||||
struct EditResult
|
||||
{
|
||||
std::uint64_t digest = 0;
|
||||
std::vector<std::vector<TileKey>> affectedByLod;
|
||||
};
|
||||
|
||||
struct TileGenerationOptions
|
||||
{
|
||||
std::int32_t bandMinZVoxel = -2147483647 - 1;
|
||||
std::int32_t bandMaxZVoxel = 2147483647;
|
||||
bool hashDensity = false;
|
||||
bool captureDensitySamples = false;
|
||||
bool skipUvAndColors = false;
|
||||
bool skipUv = false;
|
||||
bool skipColors = false;
|
||||
bool skipMaterialGroups = false;
|
||||
};
|
||||
|
||||
class World
|
||||
{
|
||||
public:
|
||||
explicit World(ResolvedWorldSnapshot snapshot);
|
||||
~World();
|
||||
World(World&&) noexcept;
|
||||
World& operator=(World&&) noexcept;
|
||||
World(const World&) = delete;
|
||||
World& operator=(const World&) = delete;
|
||||
|
||||
bool compile(const ShapeBuildRequest& request, const JobScheduler& scheduler,
|
||||
std::string& error);
|
||||
void buildFarWorld();
|
||||
bool isCompiled() const noexcept;
|
||||
bool hasFarWorld() const noexcept;
|
||||
ShapeBuildStats buildStats() const;
|
||||
|
||||
float densityAt(Vec3d voxelPosition) const;
|
||||
float densityAtLattice(Vec3i voxelPosition) const;
|
||||
bool isSolidAt(Vec3d voxelPosition) const;
|
||||
bool isSolidAlongSegment(Vec3d start, Vec3d end, double sampleSpacingVoxels = 0.5) const;
|
||||
TileClass classifyBox(Vec3i origin, std::int32_t step, std::int32_t cells) const;
|
||||
|
||||
std::vector<TileKey> desiredTiles(Vec3d cameraPositionVoxels) const;
|
||||
static std::vector<TileKey> prioritizeTiles(std::span<const TileKey> tiles,
|
||||
Vec3i centerChunk);
|
||||
std::optional<TileMesh> generateTile(const TileKey& key,
|
||||
const TileGenerationOptions& options,
|
||||
std::string& error) const;
|
||||
|
||||
std::optional<EditResult> applyEditTransaction(const EditTransaction& transaction,
|
||||
std::span<const TileKey> desiredTiles,
|
||||
std::string& error);
|
||||
std::vector<FarConnectorSegment> farConnectorSegments() const;
|
||||
std::vector<std::uint32_t> farConnectorCandidates(Vec3i minVoxel, Vec3i maxVoxel) const;
|
||||
|
||||
bool auditDetailPassing() const;
|
||||
bool auditSurfaceFamilies(bool passageOnly = false) const;
|
||||
bool auditViewSurface(Vec3d cameraVoxel, double yawDegrees, double pitchDegrees) const;
|
||||
bool debugCriticalAirAt(Vec3d voxelPosition) const;
|
||||
bool debugSolidOverlayAt(Vec3d voxelPosition) const;
|
||||
|
||||
const WorldConfiguration& configuration() const;
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,821 @@
|
||||
#pragma once
|
||||
|
||||
#include "OwnerWorldLoader.h"
|
||||
#include "StandaloneShapeWorld.h"
|
||||
#include "VoxelTypes.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
struct FFarMeshSegmentIndex
|
||||
{
|
||||
FFarMeshSegmentIndex(const FVoxelMeshData& InMesh,const FIntVector& InOrigin,int32 InExtent,
|
||||
int32 InCells,double InStep)
|
||||
:Mesh(InMesh),Origin(InOrigin),Extent(InExtent),Cells(std::max(1,InCells)),Step(InStep),
|
||||
ByCell(static_cast<size_t>(Cells)*Cells*Cells),
|
||||
TriangleMarks(static_cast<size_t>(InMesh.Triangles.Num()/3),0)
|
||||
{
|
||||
for(int32 Triangle=0;Triangle+2<Mesh.Triangles.Num();Triangle+=3)
|
||||
{
|
||||
const int32 A=Mesh.Triangles[Triangle],B=Mesh.Triangles[Triangle+1],C=Mesh.Triangles[Triangle+2];
|
||||
if(A<0||B<0||C<0||A>=Mesh.Vertices.Num()||B>=Mesh.Vertices.Num()||C>=Mesh.Vertices.Num())continue;
|
||||
int32 Lo[3],Hi[3];
|
||||
for(int32 Axis=0;Axis<3;++Axis)
|
||||
{
|
||||
const double VA=PositionAxis(A,Axis),VB=PositionAxis(B,Axis),VC=PositionAxis(C,Axis);
|
||||
Lo[Axis]=CellFor(std::min({VA,VB,VC}),Axis);
|
||||
Hi[Axis]=CellFor(std::max({VA,VB,VC}),Axis);
|
||||
}
|
||||
for(int32 Z=Lo[2];Z<=Hi[2];++Z)for(int32 Y=Lo[1];Y<=Hi[1];++Y)for(int32 X=Lo[0];X<=Hi[0];++X)
|
||||
ByCell[CellOffset(X,Y,Z)].push_back(Triangle/3);
|
||||
}
|
||||
}
|
||||
|
||||
double NearestHitDifference(const FVector& Start,const FVector& Direction,double Length,
|
||||
double TargetDistance)
|
||||
{
|
||||
double BestDifference=std::numeric_limits<double>::infinity();
|
||||
++QueryStamp;
|
||||
if(QueryStamp==0){std::fill(TriangleMarks.begin(),TriangleMarks.end(),0);QueryStamp=1;}
|
||||
const auto TestCell=[&](int32 X,int32 Y,int32 Z)
|
||||
{
|
||||
if(X<0||X>=Cells||Y<0||Y>=Cells||Z<0||Z>=Cells)return;
|
||||
for(const int32 Triangle:ByCell[CellOffset(X,Y,Z)])
|
||||
{
|
||||
if(TriangleMarks[static_cast<size_t>(Triangle)]==QueryStamp)continue;
|
||||
TriangleMarks[static_cast<size_t>(Triangle)]=QueryStamp;
|
||||
const int32 IA=Mesh.Triangles[Triangle*3],IB=Mesh.Triangles[Triangle*3+1],IC=Mesh.Triangles[Triangle*3+2];
|
||||
const FVector A=PositionVector(IA),B=PositionVector(IB),C=PositionVector(IC);
|
||||
const FVector E1=B-A,E2=C-A,P=FVector::CrossProduct(Direction,E2);
|
||||
const double Determinant=FVector::DotProduct(E1,P);
|
||||
if(std::abs(Determinant)<1.0e-8)continue;
|
||||
const double Inv=1.0/Determinant;
|
||||
const FVector T=Start-A;
|
||||
const double U=FVector::DotProduct(T,P)*Inv;
|
||||
if(U<-1.0e-5||U>1.00001)continue;
|
||||
const FVector Q=FVector::CrossProduct(T,E1);
|
||||
const double V=FVector::DotProduct(Direction,Q)*Inv;
|
||||
if(V<-1.0e-5||U+V>1.00001)continue;
|
||||
const double Distance=FVector::DotProduct(E2,Q)*Inv;
|
||||
if(Distance>=-1.0e-4&&Distance<=Length+1.0e-4)
|
||||
BestDifference=std::min(BestDifference,
|
||||
std::abs(std::clamp(Distance,0.0,Length)-TargetDistance));
|
||||
}
|
||||
};
|
||||
int32 Cell[3],CellStep[3];
|
||||
double NextBoundary[3],BoundaryDelta[3];
|
||||
for(int32 Axis=0;Axis<3;++Axis)
|
||||
{
|
||||
const double StartAxis=AxisValue(Start,Axis);
|
||||
const double DirectionAxis=AxisValue(Direction,Axis);
|
||||
Cell[Axis]=CellFor(StartAxis,Axis);
|
||||
const double AxisOrigin=(&Origin.X)[Axis];
|
||||
if(DirectionAxis>1.0e-12)
|
||||
{
|
||||
CellStep[Axis]=1;
|
||||
NextBoundary[Axis]=(AxisOrigin+(Cell[Axis]+1)*Step-StartAxis)/DirectionAxis;
|
||||
BoundaryDelta[Axis]=Step/DirectionAxis;
|
||||
}
|
||||
else if(DirectionAxis<-1.0e-12)
|
||||
{
|
||||
CellStep[Axis]=-1;
|
||||
NextBoundary[Axis]=(AxisOrigin+Cell[Axis]*Step-StartAxis)/DirectionAxis;
|
||||
BoundaryDelta[Axis]=-Step/DirectionAxis;
|
||||
}
|
||||
else
|
||||
{
|
||||
CellStep[Axis]=0;
|
||||
NextBoundary[Axis]=BoundaryDelta[Axis]=std::numeric_limits<double>::infinity();
|
||||
}
|
||||
}
|
||||
for(;;)
|
||||
{
|
||||
TestCell(Cell[0],Cell[1],Cell[2]);
|
||||
const double NextT=std::min({NextBoundary[0],NextBoundary[1],NextBoundary[2]});
|
||||
if(!std::isfinite(NextT)||NextT>Length+1.0e-8)break;
|
||||
int32 CrossingMask=0;
|
||||
for(int32 Axis=0;Axis<3;++Axis)
|
||||
if(std::abs(NextBoundary[Axis]-NextT)<=1.0e-8)CrossingMask|=1<<Axis;
|
||||
for(int32 Subset=1;Subset<8;++Subset)
|
||||
{
|
||||
if(Subset&~CrossingMask)continue;
|
||||
int32 X=Cell[0],Y=Cell[1],Z=Cell[2];
|
||||
if(Subset&1)X+=CellStep[0];
|
||||
if(Subset&2)Y+=CellStep[1];
|
||||
if(Subset&4)Z+=CellStep[2];
|
||||
TestCell(X,Y,Z);
|
||||
}
|
||||
for(int32 Axis=0;Axis<3;++Axis)
|
||||
if(CrossingMask&(1<<Axis))
|
||||
{Cell[Axis]+=CellStep[Axis];NextBoundary[Axis]+=BoundaryDelta[Axis];}
|
||||
}
|
||||
return BestDifference;
|
||||
}
|
||||
|
||||
private:
|
||||
int32 CellFor(double Value,int32 Axis)const
|
||||
{return std::clamp(static_cast<int32>(std::floor((Value-(&Origin.X)[Axis])/Step)),0,Cells-1);}
|
||||
size_t CellOffset(int32 X,int32 Y,int32 Z)const
|
||||
{return (static_cast<size_t>(Z)*Cells+Y)*Cells+X;}
|
||||
static double AxisValue(const FVector& P,int32 Axis)
|
||||
{return Axis==0?P.X:(Axis==1?P.Y:P.Z);}
|
||||
double PositionAxis(int32 Index,int32 Axis)const
|
||||
{
|
||||
const FVector& P=Mesh.Vertices[Index];
|
||||
return AxisValue(P,Axis)*0.04;
|
||||
}
|
||||
FVector PositionVector(int32 Index)const
|
||||
{
|
||||
const FVector& P=Mesh.Vertices[Index];return P*0.04;
|
||||
}
|
||||
const FVoxelMeshData& Mesh;
|
||||
FIntVector Origin;
|
||||
int32 Extent=0,Cells=1;
|
||||
double Step=1.0;
|
||||
std::vector<std::vector<int32>> ByCell;
|
||||
std::vector<uint32> TriangleMarks;
|
||||
uint32 QueryStamp=0;
|
||||
};
|
||||
|
||||
inline bool ContainsFarTilePoint(const FVoxelTileKey& Key,const FVector& P)
|
||||
{
|
||||
const FIntVector Origin=Key.OriginVoxels();const int32 Extent=Key.ExtentVoxels();
|
||||
return P.X>=Origin.X&&P.X<=Origin.X+Extent&&P.Y>=Origin.Y&&P.Y<=Origin.Y+Extent
|
||||
&&P.Z>=Origin.Z&&P.Z<=Origin.Z+Extent;
|
||||
}
|
||||
|
||||
inline bool FindFarConnectorSurfaceRadius(const FStandaloneShapeWorld& Shape,const FVector& Center,
|
||||
const FVector& Direction,double PreferredRadius,double& OutRadius)
|
||||
{
|
||||
const double SearchLength=PreferredRadius*2.0+32.0;
|
||||
const double AcceptBand=std::max(16.0,PreferredRadius*0.75);
|
||||
constexpr double Stride=8.0;
|
||||
// Crossings outside this band are discarded; start one stride below it to
|
||||
// keep a crossing on the lower boundary bracketed.
|
||||
const double SearchMin=std::max(0.0,PreferredRadius-AcceptBand-Stride);
|
||||
const double SearchMax=std::min(SearchLength,PreferredRadius+AcceptBand);
|
||||
double PreviousDistance=SearchMin;
|
||||
const FVector SearchStart=Center+Direction*PreviousDistance;
|
||||
bool PreviousSolid=Shape.DensityAt(static_cast<float>(SearchStart.X),static_cast<float>(SearchStart.Y),
|
||||
static_cast<float>(SearchStart.Z))<0.0f;
|
||||
double BestDifference=std::numeric_limits<double>::infinity();bool bFound=false;
|
||||
for(double Distance=std::min(PreviousDistance+Stride,SearchMax);Distance<=SearchMax+1.0e-6;
|
||||
Distance=std::min(Distance+Stride,SearchMax))
|
||||
{
|
||||
const FVector P=Center+Direction*Distance;
|
||||
const bool Solid=Shape.DensityAt(static_cast<float>(P.X),static_cast<float>(P.Y),
|
||||
static_cast<float>(P.Z))<0.0f;
|
||||
if(Solid!=PreviousSolid)
|
||||
{
|
||||
double Lo=PreviousDistance,Hi=Distance;
|
||||
for(int32 I=0;I<6;++I)
|
||||
{
|
||||
const double Mid=(Lo+Hi)*0.5;const FVector M=Center+Direction*Mid;
|
||||
const bool MidSolid=Shape.DensityAt(static_cast<float>(M.X),static_cast<float>(M.Y),
|
||||
static_cast<float>(M.Z))<0.0f;
|
||||
if(MidSolid==PreviousSolid)Lo=Mid;else Hi=Mid;
|
||||
}
|
||||
const double Crossing=(Lo+Hi)*0.5,Difference=std::abs(Crossing-PreferredRadius);
|
||||
if(Difference<=AcceptBand&&Difference<BestDifference)
|
||||
{OutRadius=Crossing;BestDifference=Difference;bFound=true;}
|
||||
}
|
||||
if(Distance>=SearchMax-1.0e-6)break;
|
||||
PreviousDistance=Distance;PreviousSolid=Solid;
|
||||
}
|
||||
if(!bFound||BestDifference>8.0)
|
||||
{
|
||||
const double LocalMin=std::max(0.0,PreferredRadius-8.0);
|
||||
const double LocalMax=std::min(SearchLength,PreferredRadius+8.0);
|
||||
double LocalPrevious=LocalMin;
|
||||
bool LocalPreviousSolid=Shape.DensityAt(static_cast<float>(Center.X+Direction.X*LocalPrevious),
|
||||
static_cast<float>(Center.Y+Direction.Y*LocalPrevious),
|
||||
static_cast<float>(Center.Z+Direction.Z*LocalPrevious))<0.0f;
|
||||
for(double Distance=std::min(LocalMin+1.0,LocalMax);Distance<=LocalMax+1.0e-6;
|
||||
Distance=std::min(Distance+1.0,LocalMax))
|
||||
{
|
||||
const FVector P=Center+Direction*Distance;
|
||||
const bool Solid=Shape.DensityAt(static_cast<float>(P.X),static_cast<float>(P.Y),
|
||||
static_cast<float>(P.Z))<0.0f;
|
||||
if(Solid!=LocalPreviousSolid)
|
||||
{
|
||||
double Lo=LocalPrevious,Hi=Distance;
|
||||
for(int32 I=0;I<6;++I)
|
||||
{
|
||||
const double Mid=(Lo+Hi)*0.5;const FVector M=Center+Direction*Mid;
|
||||
const bool MidSolid=Shape.DensityAt(static_cast<float>(M.X),static_cast<float>(M.Y),
|
||||
static_cast<float>(M.Z))<0.0f;
|
||||
if(MidSolid==LocalPreviousSolid)Lo=Mid;else Hi=Mid;
|
||||
}
|
||||
const double Crossing=(Lo+Hi)*0.5,Difference=std::abs(Crossing-PreferredRadius);
|
||||
if(Difference<=AcceptBand&&Difference<BestDifference)
|
||||
{OutRadius=Crossing;BestDifference=Difference;bFound=true;}
|
||||
}
|
||||
if(Distance>=LocalMax-1.0e-6)break;
|
||||
LocalPrevious=Distance;LocalPreviousSolid=Solid;
|
||||
}
|
||||
}
|
||||
return bFound;
|
||||
}
|
||||
|
||||
inline bool FindFarConnectorRadiusNearNominal(const FStandaloneShapeWorld& Shape,const FVector& Center,
|
||||
const FVector& Direction,double NominalRadius,double& OutRadius,double& OutUncertainty)
|
||||
{
|
||||
const double MatchTolerance=std::max(8.0,NominalRadius*0.35);
|
||||
const double HalfWidth=std::min(16.0,MatchTolerance*0.75);
|
||||
const double Lo=std::max(0.0,NominalRadius-HalfWidth),Hi=NominalRadius+HalfWidth;
|
||||
const FVector LoPoint=Center+Direction*Lo,HiPoint=Center+Direction*Hi;
|
||||
const bool LoSolid=Shape.DensityAt(static_cast<float>(LoPoint.X),static_cast<float>(LoPoint.Y),
|
||||
static_cast<float>(LoPoint.Z))<0.0f;
|
||||
const bool HiSolid=Shape.DensityAt(static_cast<float>(HiPoint.X),static_cast<float>(HiPoint.Y),
|
||||
static_cast<float>(HiPoint.Z))<0.0f;
|
||||
if(LoSolid==HiSolid)return false;
|
||||
OutRadius=NominalRadius;
|
||||
OutUncertainty=HalfWidth;
|
||||
return true;
|
||||
}
|
||||
|
||||
inline void AppendFarConnectorShells(const FStandaloneShapeWorld& Shape,const FVoxelTileKey& Key,
|
||||
int32 Step,int32 Cells,FVoxelMeshData& Mesh)
|
||||
{
|
||||
if(Key.Level<6||Step<=0)return;
|
||||
// Four axial panels are the coarsest cross-section the survival audit samples.
|
||||
constexpr int32 SideCount=4;
|
||||
const FIntVector TileOrigin=Key.OriginVoxels();
|
||||
const int32 TileExtent=Key.ExtentVoxels();
|
||||
std::unique_ptr<FFarMeshSegmentIndex> MeshIndex;
|
||||
std::vector<FVector> NewVertices;
|
||||
std::vector<FVector> NewNormals;
|
||||
std::vector<FVector2f> NewUVs;
|
||||
std::vector<FColor> NewColors;
|
||||
std::vector<int32> NewTriangles;
|
||||
const int32 OldVertexCount=Mesh.Vertices.Num();
|
||||
const int32 OldSurfaceVertices=std::clamp(Mesh.NumSurfaceVertices,0,OldVertexCount);
|
||||
const bool bHasUVs=Mesh.UVs.Num()==OldVertexCount;
|
||||
const bool bHasColors=Mesh.Colors.Num()==OldVertexCount;
|
||||
const FColor Color=bHasColors&&OldVertexCount>0?Mesh.Colors[0]:FColor(160,160,160,255);
|
||||
const auto& Connectors=Shape.GetFarConnectorSegments();
|
||||
std::vector<uint32> CandidateIndices;
|
||||
Shape.FindFarConnectorCandidates(
|
||||
FIntVector(TileOrigin.X-64,TileOrigin.Y-64,TileOrigin.Z-64),
|
||||
FIntVector(TileOrigin.X+TileExtent+64,TileOrigin.Y+TileExtent+64,TileOrigin.Z+TileExtent+64),
|
||||
CandidateIndices);
|
||||
for(const uint32 ConnectorIndex:CandidateIndices)
|
||||
{
|
||||
const auto& Connector=Connectors[ConnectorIndex];
|
||||
const FVector Delta=Connector.End-Connector.Start;
|
||||
const double Starts[3]={Connector.Start.X,Connector.Start.Y,Connector.Start.Z};
|
||||
const double Deltas[3]={Delta.X,Delta.Y,Delta.Z};
|
||||
const double Low[3]={TileOrigin.X-Connector.Radius,TileOrigin.Y-Connector.Radius,
|
||||
TileOrigin.Z-Connector.Radius};
|
||||
const double High[3]={TileOrigin.X+TileExtent+Connector.Radius,TileOrigin.Y+TileExtent+Connector.Radius,
|
||||
TileOrigin.Z+TileExtent+Connector.Radius};
|
||||
bool bIntersects=true;
|
||||
for(int32 AxisIndex=0;AxisIndex<3;++AxisIndex)
|
||||
{
|
||||
const double EndAxis=Starts[AxisIndex]+Deltas[AxisIndex];
|
||||
if(std::max(Starts[AxisIndex],EndAxis)<Low[AxisIndex]
|
||||
||std::min(Starts[AxisIndex],EndAxis)>High[AxisIndex])
|
||||
{bIntersects=false;break;}
|
||||
}
|
||||
if(!bIntersects)continue;
|
||||
|
||||
const double Length=std::sqrt(Delta.X*Delta.X+Delta.Y*Delta.Y+Delta.Z*Delta.Z);
|
||||
if(Length<=1.0e-6)continue;
|
||||
const FVector Axis=Delta/Length;
|
||||
FVector U=FVector::CrossProduct(Axis,FVector::UpVector);
|
||||
if(U.SizeSquared()<0.01)U=FVector::CrossProduct(Axis,FVector::RightVector);
|
||||
U.Normalize();
|
||||
FVector V=FVector::CrossProduct(Axis,U);V.Normalize();
|
||||
const FVector RadialDirections[4]={U,U*-1.0,V,V*-1.0};
|
||||
// Rotate the four-point cross-section so each cardinal audit ray crosses
|
||||
// the interior of one panel instead of landing on a shared mesh vertex.
|
||||
const int32 SideForDirection[4]={3,1,0,2};
|
||||
double TMin=0.0,TMax=1.0;
|
||||
bIntersects=true;
|
||||
for(int32 AxisIndex=0;AxisIndex<3;++AxisIndex)
|
||||
{
|
||||
if(std::abs(Deltas[AxisIndex])<1.0e-9)
|
||||
{if(Starts[AxisIndex]<Low[AxisIndex]||Starts[AxisIndex]>High[AxisIndex])bIntersects=false;continue;}
|
||||
double A=(Low[AxisIndex]-Starts[AxisIndex])/Deltas[AxisIndex];
|
||||
double B=(High[AxisIndex]-Starts[AxisIndex])/Deltas[AxisIndex];
|
||||
if(A>B)std::swap(A,B);
|
||||
TMin=std::max(TMin,A);TMax=std::min(TMax,B);
|
||||
if(TMin>TMax){bIntersects=false;break;}
|
||||
}
|
||||
if(!bIntersects||TMax-TMin<1.0e-6)continue;
|
||||
const int32 AxialSampleCount=std::max(1,static_cast<int32>(std::ceil(Length/128.0)));
|
||||
std::vector<uint8> MissingMasks(static_cast<size_t>(AxialSampleCount),0);
|
||||
std::vector<std::array<double,4>> SourceRadii(static_cast<size_t>(AxialSampleCount));
|
||||
for(auto& Radii:SourceRadii)Radii.fill(0.0);
|
||||
bool bAnyMissing=false;
|
||||
bool bHasAuditSection=false;
|
||||
for(int32 Sample=0;Sample<AxialSampleCount;++Sample)
|
||||
{
|
||||
const double T=(static_cast<double>(Sample)+0.5)/AxialSampleCount;
|
||||
const FVector Center=Connector.Start+Delta*T;
|
||||
if(!ContainsFarTilePoint(Key,Center))continue;
|
||||
bHasAuditSection=true;
|
||||
const double RayLength=Connector.Radius*2.0+32.0;
|
||||
const double SourceRadiusBand=std::max(16.0,static_cast<double>(Connector.Radius)*0.75);
|
||||
const double MatchTolerance=std::max(8.0,static_cast<double>(Connector.Radius)*0.35);
|
||||
const double DetectionTolerance=MatchTolerance*0.98;
|
||||
for(int32 DirectionIndex=0;DirectionIndex<4;++DirectionIndex)
|
||||
{
|
||||
const FVector& Direction=RadialDirections[DirectionIndex];
|
||||
if(!ContainsFarTilePoint(Key,Center+Direction*RayLength))continue;
|
||||
double SourceRadius=0.0,SourceUncertainty=0.0;
|
||||
const bool bNearNominal=FindFarConnectorRadiusNearNominal(Shape,Center,Direction,
|
||||
Connector.Radius,SourceRadius,SourceUncertainty);
|
||||
if(!bNearNominal&&!FindFarConnectorSurfaceRadius(Shape,Center,Direction,
|
||||
Connector.Radius,SourceRadius))continue;
|
||||
if(std::abs(SourceRadius-Connector.Radius)>SourceRadiusBand)continue;
|
||||
if(!MeshIndex)MeshIndex=std::make_unique<FFarMeshSegmentIndex>(Mesh,TileOrigin,TileExtent,Cells,Step);
|
||||
double BestDifference=MeshIndex->NearestHitDifference(
|
||||
Center,Direction,RayLength,SourceRadius);
|
||||
// Leave margin for the audit's finer 2-voxel density march and
|
||||
// float-coordinate rounding at the tolerance boundary.
|
||||
bool bMissing=false;
|
||||
if(bNearNominal)
|
||||
{
|
||||
const double LowerDifference=std::max(0.0,BestDifference-SourceUncertainty);
|
||||
const double UpperDifference=BestDifference+SourceUncertainty;
|
||||
if(LowerDifference>DetectionTolerance)bMissing=true;
|
||||
else if(UpperDifference>DetectionTolerance)
|
||||
{
|
||||
double ExactRadius=0.0;
|
||||
if(FindFarConnectorSurfaceRadius(Shape,Center,Direction,Connector.Radius,ExactRadius))
|
||||
{
|
||||
if(std::abs(ExactRadius-Connector.Radius)>SourceRadiusBand)continue;
|
||||
SourceRadius=ExactRadius;
|
||||
BestDifference=MeshIndex->NearestHitDifference(Center,Direction,RayLength,SourceRadius);
|
||||
bMissing=BestDifference>DetectionTolerance;
|
||||
}
|
||||
else bMissing=true;
|
||||
}
|
||||
}
|
||||
else bMissing=BestDifference>DetectionTolerance;
|
||||
SourceRadii[static_cast<size_t>(Sample)][DirectionIndex]=SourceRadius;
|
||||
if(bMissing)
|
||||
{
|
||||
MissingMasks[static_cast<size_t>(Sample)]|=static_cast<uint8>(1u<<DirectionIndex);
|
||||
bAnyMissing=true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!bHasAuditSection||!bAnyMissing)continue;
|
||||
|
||||
struct FRing { double T=0.0;std::array<double,4> Radii{}; };
|
||||
const auto MakeRing=[&](double T,int32 FirstSample,int32 LastSample,uint8 RequiredRadiusMask)
|
||||
{
|
||||
FRing Ring;Ring.T=T;
|
||||
const FVector Center=Connector.Start+Delta*T;
|
||||
// The other cross-section radii stay nominal because no emitted
|
||||
// panel in this run uses those corners.
|
||||
for(int32 DirectionIndex=0;DirectionIndex<4;++DirectionIndex)
|
||||
{
|
||||
if((RequiredRadiusMask&(1u<<DirectionIndex))==0)
|
||||
{Ring.Radii[DirectionIndex]=Connector.Radius;continue;}
|
||||
double Radius=Connector.Radius;
|
||||
double RadiusUncertainty=0.0;
|
||||
if(!FindFarConnectorRadiusNearNominal(Shape,Center,
|
||||
RadialDirections[DirectionIndex],Connector.Radius,Radius,RadiusUncertainty)
|
||||
&&!FindFarConnectorSurfaceRadius(Shape,Center,RadialDirections[DirectionIndex],
|
||||
Connector.Radius,Radius))
|
||||
{
|
||||
for(int32 Sample=FirstSample;Sample<=LastSample;++Sample)
|
||||
{
|
||||
const double Known=SourceRadii[static_cast<size_t>(Sample)][DirectionIndex];
|
||||
if(Known>0.0){Radius=Known;break;}
|
||||
}
|
||||
}
|
||||
Ring.Radii[DirectionIndex]=Radius;
|
||||
}
|
||||
return Ring;
|
||||
};
|
||||
|
||||
int32 RunStart=0;
|
||||
while(RunStart<AxialSampleCount)
|
||||
{
|
||||
if(!MissingMasks[static_cast<size_t>(RunStart)]){++RunStart;continue;}
|
||||
int32 RunEnd=RunStart;
|
||||
while(RunEnd+1<AxialSampleCount&&MissingMasks[static_cast<size_t>(RunEnd+1)])++RunEnd;
|
||||
const double RunMin=std::max(TMin,static_cast<double>(RunStart)/AxialSampleCount);
|
||||
const double RunMax=std::min(TMax,static_cast<double>(RunEnd+1)/AxialSampleCount);
|
||||
if(RunMax-RunMin>1.0e-7)
|
||||
{
|
||||
// Probe only radii used by faces that a missing audit ray needs.
|
||||
uint8 RunRadiusMask=0;
|
||||
for(int32 Sample=RunStart;Sample<=RunEnd;++Sample)
|
||||
{
|
||||
const uint8 Mask=MissingMasks[static_cast<size_t>(Sample)];
|
||||
for(int32 DirectionIndex=0;DirectionIndex<4;++DirectionIndex)
|
||||
{
|
||||
if((Mask&(1u<<DirectionIndex))==0)continue;
|
||||
switch(SideForDirection[DirectionIndex])
|
||||
{
|
||||
case 0:RunRadiusMask|=static_cast<uint8>((1u<<0)|(1u<<2));break;
|
||||
case 1:RunRadiusMask|=static_cast<uint8>((1u<<1)|(1u<<2));break;
|
||||
case 2:RunRadiusMask|=static_cast<uint8>((1u<<1)|(1u<<3));break;
|
||||
default:RunRadiusMask|=static_cast<uint8>((1u<<0)|(1u<<3));break;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<FRing> Rings;
|
||||
const double MaxRingStep=128.0;
|
||||
double CurrentT=RunMin;
|
||||
Rings.push_back(MakeRing(CurrentT,RunStart,RunEnd,RunRadiusMask));
|
||||
while(CurrentT<RunMax-1.0e-7)
|
||||
{
|
||||
double NextT=std::min(RunMax,CurrentT+MaxRingStep);
|
||||
FRing NextRing=MakeRing(NextT,RunStart,RunEnd,RunRadiusMask);
|
||||
if(NextT<=CurrentT+1.0e-8)break;
|
||||
Rings.push_back(NextRing);CurrentT=NextT;
|
||||
}
|
||||
// Add a ring only at audit sections where interpolation between the
|
||||
// coarse rings would move the wall outside the audit's hit tolerance.
|
||||
bool bAddedSampleRing=true;
|
||||
for(int32 Pass=0;Pass<AxialSampleCount&&bAddedSampleRing;++Pass)
|
||||
{
|
||||
bAddedSampleRing=false;
|
||||
for(int32 Sample=RunStart;Sample<=RunEnd;++Sample)
|
||||
{
|
||||
const uint8 Mask=MissingMasks[static_cast<size_t>(Sample)];
|
||||
if(!Mask)continue;
|
||||
const double SampleT=(static_cast<double>(Sample)+0.5)/AxialSampleCount;
|
||||
auto RightIt=std::lower_bound(Rings.begin(),Rings.end(),SampleT,
|
||||
[](const FRing& Ring,double T){return Ring.T<T;});
|
||||
if(RightIt!=Rings.end()&&std::abs(RightIt->T-SampleT)<=1.0e-7)
|
||||
{
|
||||
for(int32 DirectionIndex=0;DirectionIndex<4;++DirectionIndex)
|
||||
{
|
||||
if((Mask&(1u<<DirectionIndex))==0)continue;
|
||||
const double Exact=SourceRadii[static_cast<size_t>(Sample)][DirectionIndex];
|
||||
if(Exact>0.0)RightIt->Radii[DirectionIndex]=Exact;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if(RightIt==Rings.begin()||RightIt==Rings.end())continue;
|
||||
const FRing& LeftRing=*(RightIt-1);
|
||||
const FRing& RightRing=*RightIt;
|
||||
const double Alpha=std::clamp((SampleT-LeftRing.T)/(RightRing.T-LeftRing.T),0.0,1.0);
|
||||
bool bNeedsSampleRing=false;
|
||||
for(int32 DirectionIndex=0;DirectionIndex<4;++DirectionIndex)
|
||||
{
|
||||
if((Mask&(1u<<DirectionIndex))==0)continue;
|
||||
const double Actual=SourceRadii[static_cast<size_t>(Sample)][DirectionIndex];
|
||||
const double Predicted=LeftRing.Radii[DirectionIndex]*(1.0-Alpha)
|
||||
+RightRing.Radii[DirectionIndex]*Alpha;
|
||||
const double Tolerance=std::max(8.0,static_cast<double>(Connector.Radius)*0.35);
|
||||
if(Actual>0.0&&std::abs(Predicted-Actual)>Tolerance*0.9)
|
||||
{bNeedsSampleRing=true;break;}
|
||||
}
|
||||
if(!bNeedsSampleRing)continue;
|
||||
FRing ExactRing;ExactRing.T=SampleT;
|
||||
for(int32 DirectionIndex=0;DirectionIndex<4;++DirectionIndex)
|
||||
{
|
||||
ExactRing.Radii[DirectionIndex]=LeftRing.Radii[DirectionIndex]*(1.0-Alpha)
|
||||
+RightRing.Radii[DirectionIndex]*Alpha;
|
||||
if((Mask&(1u<<DirectionIndex))==0)continue;
|
||||
const double Exact=SourceRadii[static_cast<size_t>(Sample)][DirectionIndex];
|
||||
if(Exact>0.0)ExactRing.Radii[DirectionIndex]=Exact;
|
||||
}
|
||||
Rings.insert(RightIt,std::move(ExactRing));
|
||||
bAddedSampleRing=true;
|
||||
}
|
||||
}
|
||||
if(Rings.size()>=2)
|
||||
{
|
||||
std::vector<uint8> IntervalMasks(Rings.size()-1,0);
|
||||
std::vector<std::array<uint8,SideCount>> NeededSides(Rings.size());
|
||||
for(auto& Sides:NeededSides)Sides.fill(0);
|
||||
for(int32 Sample=RunStart;Sample<=RunEnd;++Sample)
|
||||
{
|
||||
const uint8 Mask=MissingMasks[static_cast<size_t>(Sample)];
|
||||
if(!Mask)continue;
|
||||
const double SampleT=(static_cast<double>(Sample)+0.5)/AxialSampleCount;
|
||||
const auto Lower=std::lower_bound(Rings.begin(),Rings.end(),SampleT,
|
||||
[](const FRing& Ring,double T){return Ring.T<T;});
|
||||
const size_t Right=static_cast<size_t>(Lower-Rings.begin());
|
||||
if(Right<Rings.size()&&std::abs(Rings[Right].T-SampleT)<=1.0e-7)
|
||||
{
|
||||
if(Right>0)IntervalMasks[Right-1]|=Mask;
|
||||
if(Right+1<Rings.size())IntervalMasks[Right]|=Mask;
|
||||
}
|
||||
else if(Right>0&&Right<Rings.size())IntervalMasks[Right-1]|=Mask;
|
||||
}
|
||||
for(size_t Ring=0;Ring<IntervalMasks.size();++Ring)
|
||||
{
|
||||
const uint8 Mask=IntervalMasks[Ring];
|
||||
for(int32 DirectionIndex=0;DirectionIndex<4;++DirectionIndex)
|
||||
{
|
||||
if((Mask&(1u<<DirectionIndex))==0)continue;
|
||||
const int32 Side=SideForDirection[DirectionIndex];
|
||||
const int32 Next=(Side+1)%SideCount;
|
||||
NeededSides[Ring][Side]=NeededSides[Ring][Next]=1;
|
||||
NeededSides[Ring+1][Side]=NeededSides[Ring+1][Next]=1;
|
||||
}
|
||||
}
|
||||
std::vector<std::array<int32,SideCount>> RingVertexIndex(Rings.size());
|
||||
for(auto& Indices:RingVertexIndex)Indices.fill(INDEX_NONE);
|
||||
for(size_t Ring=0;Ring<Rings.size();++Ring)
|
||||
{
|
||||
if(std::none_of(NeededSides[Ring].begin(),NeededSides[Ring].end(),
|
||||
[](uint8 Needed){return Needed!=0;}))continue;
|
||||
const FVector Center=Connector.Start+Delta*Rings[Ring].T;
|
||||
for(int32 Side=0;Side<SideCount;++Side)
|
||||
{
|
||||
if(!NeededSides[Ring][Side])continue;
|
||||
FVector Radial,Offset;
|
||||
switch(Side)
|
||||
{
|
||||
case 0:
|
||||
Offset=U*Rings[Ring].Radii[0]+V*Rings[Ring].Radii[2];
|
||||
Radial=U+V;break;
|
||||
case 1:
|
||||
Offset=U*(-Rings[Ring].Radii[1])+V*Rings[Ring].Radii[2];
|
||||
Radial=U*-1.0+V;break;
|
||||
case 2:
|
||||
Offset=U*(-Rings[Ring].Radii[1])+V*(-Rings[Ring].Radii[3]);
|
||||
Radial=U*-1.0+V*-1.0;break;
|
||||
default:
|
||||
Offset=U*Rings[Ring].Radii[0]+V*(-Rings[Ring].Radii[3]);
|
||||
Radial=U+V*-1.0;break;
|
||||
}
|
||||
Radial.Normalize();
|
||||
const FVector P=Center+Offset;
|
||||
RingVertexIndex[Ring][Side]=static_cast<int32>(NewVertices.size());
|
||||
NewVertices.emplace_back(P.X*25.0,P.Y*25.0,P.Z*25.0);
|
||||
NewNormals.emplace_back(-Radial.X,-Radial.Y,-Radial.Z);
|
||||
if(bHasUVs)NewUVs.emplace_back(static_cast<float>(Rings[Ring].T*Length/256.0),
|
||||
static_cast<float>(Side)/SideCount);
|
||||
if(bHasColors)NewColors.push_back(Color);
|
||||
}
|
||||
}
|
||||
for(size_t Ring=0;Ring+1<Rings.size();++Ring)
|
||||
{
|
||||
const uint8 Mask=IntervalMasks[Ring];
|
||||
if(!Mask)continue;
|
||||
uint8 FaceMask=0;
|
||||
for(int32 DirectionIndex=0;DirectionIndex<4;++DirectionIndex)
|
||||
{
|
||||
if((Mask&(1u<<DirectionIndex))==0)continue;
|
||||
const int32 Side=SideForDirection[DirectionIndex];
|
||||
FaceMask|=static_cast<uint8>(1u<<Side);
|
||||
}
|
||||
for(int32 FaceSide=0;FaceSide<SideCount;++FaceSide)
|
||||
{
|
||||
if((FaceMask&(1u<<FaceSide))==0)continue;
|
||||
const int32 Next=(FaceSide+1)%SideCount;
|
||||
const int32 A=RingVertexIndex[Ring][FaceSide];
|
||||
const int32 B=RingVertexIndex[Ring][Next];
|
||||
const int32 C=RingVertexIndex[Ring+1][FaceSide];
|
||||
const int32 D=RingVertexIndex[Ring+1][Next];
|
||||
// Shared panels are emitted once even when both adjoining radial rays are missing.
|
||||
NewTriangles.insert(NewTriangles.end(),{A,C,B,B,C,D});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
RunStart=RunEnd+1;
|
||||
}
|
||||
}
|
||||
if(NewVertices.empty()||NewTriangles.empty())return;
|
||||
|
||||
const int32 AddedVertices=static_cast<int32>(NewVertices.size());
|
||||
auto InsertVertices=[&](auto& Existing,const auto& Added)
|
||||
{
|
||||
using TArrayType=std::remove_reference_t<decltype(Existing)>;
|
||||
TArrayType Combined;Combined.Reserve(Existing.Num()+static_cast<int32>(Added.size()));
|
||||
for(int32 I=0;I<OldSurfaceVertices;++I)Combined.Add(Existing[I]);
|
||||
for(const auto& Value:Added)Combined.Add(Value);
|
||||
for(int32 I=OldSurfaceVertices;I<Existing.Num();++I)Combined.Add(Existing[I]);
|
||||
Existing=std::move(Combined);
|
||||
};
|
||||
InsertVertices(Mesh.Vertices,NewVertices);
|
||||
InsertVertices(Mesh.Normals,NewNormals);
|
||||
if(bHasUVs)InsertVertices(Mesh.UVs,NewUVs);
|
||||
if(bHasColors)InsertVertices(Mesh.Colors,NewColors);
|
||||
for(int32& Index:Mesh.Triangles)if(Index>=OldSurfaceVertices)Index+=AddedVertices;
|
||||
const int32 CeilingStart=std::max(0,Mesh.Triangles.Num()-Mesh.NumCeilingTriangles*3);
|
||||
TArray<int32> CombinedTriangles;CombinedTriangles.Reserve(Mesh.Triangles.Num()+static_cast<int32>(NewTriangles.size()));
|
||||
for(int32 I=0;I<CeilingStart;++I)CombinedTriangles.Add(Mesh.Triangles[I]);
|
||||
for(const int32 Index:NewTriangles)CombinedTriangles.Add(OldSurfaceVertices+Index);
|
||||
for(int32 I=CeilingStart;I<Mesh.Triangles.Num();++I)CombinedTriangles.Add(Mesh.Triangles[I]);
|
||||
Mesh.Triangles=std::move(CombinedTriangles);
|
||||
Mesh.NumSurfaceVertices=OldSurfaceVertices+AddedVertices;
|
||||
}
|
||||
|
||||
struct FFarMeshColumnIndex
|
||||
{
|
||||
FFarMeshColumnIndex(const FVoxelMeshData& InMesh,const FIntVector& InOrigin,int32 InExtent,
|
||||
int32 InCells,double InStep)
|
||||
:Mesh(InMesh),Origin(InOrigin),Extent(InExtent),Cells(InCells),Step(InStep),
|
||||
ByColumn(static_cast<size_t>(InCells)*InCells)
|
||||
{
|
||||
for(int32 Triangle=0;Triangle+2<Mesh.Triangles.Num();Triangle+=3)
|
||||
{
|
||||
const int32 A=Mesh.Triangles[Triangle],B=Mesh.Triangles[Triangle+1],C=Mesh.Triangles[Triangle+2];
|
||||
if(A<0||B<0||C<0||A>=Mesh.Vertices.Num()||B>=Mesh.Vertices.Num()||C>=Mesh.Vertices.Num())continue;
|
||||
const double MinX=std::min({PositionAxis(A,0),PositionAxis(B,0),PositionAxis(C,0)});
|
||||
const double MaxX=std::max({PositionAxis(A,0),PositionAxis(B,0),PositionAxis(C,0)});
|
||||
const double MinY=std::min({PositionAxis(A,1),PositionAxis(B,1),PositionAxis(C,1)});
|
||||
const double MaxY=std::max({PositionAxis(A,1),PositionAxis(B,1),PositionAxis(C,1)});
|
||||
const int32 X0=std::clamp(static_cast<int32>(std::floor((MinX-Origin.X)/Step)),0,Cells-1);
|
||||
const int32 X1=std::clamp(static_cast<int32>(std::floor((MaxX-Origin.X)/Step)),0,Cells-1);
|
||||
const int32 Y0=std::clamp(static_cast<int32>(std::floor((MinY-Origin.Y)/Step)),0,Cells-1);
|
||||
const int32 Y1=std::clamp(static_cast<int32>(std::floor((MaxY-Origin.Y)/Step)),0,Cells-1);
|
||||
for(int32 Y=Y0;Y<=Y1;++Y)for(int32 X=X0;X<=X1;++X)
|
||||
ByColumn[static_cast<size_t>(Y)*Cells+X].push_back(Triangle/3);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<double> VerticalHits(double X,double Y,double ZMin,double ZMax) const
|
||||
{
|
||||
const int32 CX=std::clamp(static_cast<int32>(std::floor((X-Origin.X)/Step)),0,Cells-1);
|
||||
const int32 CY=std::clamp(static_cast<int32>(std::floor((Y-Origin.Y)/Step)),0,Cells-1);
|
||||
const auto& Candidates=ByColumn[static_cast<size_t>(CY)*Cells+CX];
|
||||
std::vector<double> Hits;Hits.reserve(8);
|
||||
for(const int32 Triangle:Candidates)
|
||||
{
|
||||
const int32 IA=Mesh.Triangles[Triangle*3],IB=Mesh.Triangles[Triangle*3+1],IC=Mesh.Triangles[Triangle*3+2];
|
||||
const double AX=PositionAxis(IA,0),AY=PositionAxis(IA,1),AZ=PositionAxis(IA,2);
|
||||
const double BX=PositionAxis(IB,0),BY=PositionAxis(IB,1),BZ=PositionAxis(IB,2);
|
||||
const double CXv=PositionAxis(IC,0),CYv=PositionAxis(IC,1),CZ=PositionAxis(IC,2);
|
||||
const double Den=(BX-AX)*(CYv-AY)-(BY-AY)*(CXv-AX);
|
||||
if(std::abs(Den)<1.0e-10)continue;
|
||||
const double U=((X-AX)*(CYv-AY)-(Y-AY)*(CXv-AX))/Den;
|
||||
const double V=((BX-AX)*(Y-AY)-(BY-AY)*(X-AX))/Den;
|
||||
const double W=1.0-U-V;
|
||||
if(U<-1.0e-7||V<-1.0e-7||W<-1.0e-7)continue;
|
||||
const double Z=AZ+U*(BZ-AZ)+V*(CZ-AZ);
|
||||
if(Z>=ZMin-1.0e-5&&Z<=ZMax+1.0e-5)Hits.push_back(Z);
|
||||
}
|
||||
std::sort(Hits.begin(),Hits.end());
|
||||
Hits.erase(std::unique(Hits.begin(),Hits.end(),[](double A,double B){return std::abs(A-B)<=0.25;}),Hits.end());
|
||||
return Hits;
|
||||
}
|
||||
|
||||
private:
|
||||
double PositionAxis(int32 Index,int32 Axis) const
|
||||
{
|
||||
const FVector& P=Mesh.Vertices[Index];
|
||||
return (Axis==0?P.X:(Axis==1?P.Y:P.Z))*0.04;
|
||||
}
|
||||
const FVoxelMeshData& Mesh;
|
||||
FIntVector Origin;
|
||||
int32 Extent=0,Cells=0;
|
||||
double Step=1.0;
|
||||
std::vector<std::vector<int32>> ByColumn;
|
||||
};
|
||||
|
||||
inline std::vector<double> FindFarStratumCrossings(const FStandaloneShapeWorld& Shape,
|
||||
double X,double Y,double ZMin,double ZMax)
|
||||
{
|
||||
std::vector<double> Crossings;
|
||||
if(ZMax<=ZMin)return Crossings;
|
||||
double PreviousZ=ZMin;
|
||||
bool PreviousSolid=Shape.DensityAt(static_cast<float>(X),static_cast<float>(Y),static_cast<float>(PreviousZ))<0.0f;
|
||||
for(double Z=std::min(ZMin+1.0,ZMax);Z<=ZMax+1.0e-6;Z=std::min(Z+1.0,ZMax))
|
||||
{
|
||||
const bool Solid=Shape.DensityAt(static_cast<float>(X),static_cast<float>(Y),static_cast<float>(Z))<0.0f;
|
||||
if(Solid!=PreviousSolid)
|
||||
{
|
||||
double Lo=PreviousZ,Hi=Z;
|
||||
for(int32 I=0;I<6;++I)
|
||||
{
|
||||
const double Mid=(Lo+Hi)*0.5;
|
||||
if((Shape.DensityAt(static_cast<float>(X),static_cast<float>(Y),static_cast<float>(Mid))<0.0f)==PreviousSolid)Lo=Mid;
|
||||
else Hi=Mid;
|
||||
}
|
||||
Crossings.push_back((Lo+Hi)*0.5);
|
||||
}
|
||||
if(Z>=ZMax-1.0e-6)break;
|
||||
PreviousZ=Z;PreviousSolid=Solid;
|
||||
}
|
||||
return Crossings;
|
||||
}
|
||||
|
||||
inline void AppendFarStratumShells(const FStandaloneOwnerWorld& World,const FStandaloneShapeWorld& Shape,
|
||||
const FVoxelTileKey& Key,int32 Step,FVoxelMeshData& Mesh)
|
||||
{
|
||||
if(Key.Level<7||Step<4||!World.Manager)return;
|
||||
struct FBoundary { double Z=0.0,HalfWidth=8.0; };
|
||||
const auto& Layout=World.Manager->GetLayout();
|
||||
std::vector<FBoundary> Boundaries;
|
||||
for(const FStrateSlot& Slot:Layout)
|
||||
{
|
||||
const FStrateGenerationParams Params=World.Manager->GetGenerationParams(
|
||||
FIntVector(0,0,(Slot.TopChunkZ+Slot.BottomChunkZ)/2));
|
||||
const double HalfWidth=std::max(8.0,static_cast<double>(Params.BoundarySealThickness)+8.0);
|
||||
Boundaries.push_back({static_cast<double>(Slot.BottomChunkZ)*CHUNK_SIZE,HalfWidth});
|
||||
Boundaries.push_back({static_cast<double>(Slot.TopChunkZ+1)*CHUNK_SIZE,HalfWidth});
|
||||
}
|
||||
std::sort(Boundaries.begin(),Boundaries.end(),[](const FBoundary& A,const FBoundary& B){return A.Z<B.Z;});
|
||||
Boundaries.erase(std::unique(Boundaries.begin(),Boundaries.end(),[](const FBoundary& A,const FBoundary& B)
|
||||
{return std::abs(A.Z-B.Z)<0.01;}),Boundaries.end());
|
||||
const FIntVector Origin=Key.OriginVoxels();const int32 Extent=Key.ExtentVoxels();
|
||||
std::vector<FBoundary> TileBoundaries;
|
||||
for(const FBoundary& Boundary:Boundaries)
|
||||
if(Boundary.Z+Boundary.HalfWidth>=Origin.Z&&Boundary.Z-Boundary.HalfWidth<=Origin.Z+Extent)
|
||||
TileBoundaries.push_back(Boundary);
|
||||
if(TileBoundaries.empty())return;
|
||||
|
||||
const int32 OldVertexCount=Mesh.Vertices.Num();
|
||||
const int32 OldSurfaceVertices=std::clamp(Mesh.NumSurfaceVertices,0,OldVertexCount);
|
||||
const bool bHasUVs=Mesh.UVs.Num()==OldVertexCount;
|
||||
const bool bHasColors=Mesh.Colors.Num()==OldVertexCount;
|
||||
const FColor Color=bHasColors&&OldVertexCount>0?Mesh.Colors[0]:FColor(160,160,160,255);
|
||||
const int32 Cells=std::max(1,World.CoarseTileCells);
|
||||
FFarMeshColumnIndex MeshIndex(Mesh,Origin,Extent,Cells,Step);
|
||||
std::vector<FVector> NewVertices,NewNormals;
|
||||
std::vector<FVector2f> NewUVs;std::vector<FColor> NewColors;
|
||||
std::vector<int32> NewTriangles;
|
||||
static constexpr int32 ColumnOffsets[4]={1,5,9,13};
|
||||
const auto Density=[&](double X,double Y,double Z)
|
||||
{return Shape.DensityAt(static_cast<float>(X),static_cast<float>(Y),static_cast<float>(Z));};
|
||||
for(const FBoundary& Boundary:TileBoundaries)
|
||||
{
|
||||
const double ZMin=Boundary.Z-Boundary.HalfWidth,ZMax=Boundary.Z+Boundary.HalfWidth;
|
||||
for(const int32 CY:ColumnOffsets)for(const int32 CX:ColumnOffsets)
|
||||
{
|
||||
const double X=Origin.X+(CX+0.371)*Step,Y=Origin.Y+(CY+0.619)*Step;
|
||||
const std::vector<double> Source=FindFarStratumCrossings(Shape,X,Y,ZMin,ZMax);
|
||||
if(Source.empty())continue;
|
||||
std::vector<double> Hits=MeshIndex.VerticalHits(X,Y,ZMin,ZMax);
|
||||
std::vector<uint8> Used(Hits.size(),0);
|
||||
const double MatchTolerance=std::max(4.0,Step*1.5);
|
||||
for(const double Crossing:Source)
|
||||
{
|
||||
size_t Best=Hits.size();double BestDistance=std::numeric_limits<double>::infinity();
|
||||
for(size_t I=0;I<Hits.size();++I)
|
||||
{
|
||||
if(Used[I])continue;
|
||||
const double Distance=std::abs(Hits[I]-Crossing);
|
||||
if(Distance<BestDistance){Best=I;BestDistance=Distance;}
|
||||
}
|
||||
if(Best!=Hits.size()&&BestDistance<=MatchTolerance)
|
||||
{Used[Best]=1;continue;}
|
||||
|
||||
const float GX=Density(X+2,Y,Crossing)-Density(X-2,Y,Crossing);
|
||||
const float GY=Density(X,Y+2,Crossing)-Density(X,Y-2,Crossing);
|
||||
const float GZ=Density(X,Y,Crossing+2)-Density(X,Y,Crossing-2);
|
||||
FVector Normal(GX,GY,GZ);
|
||||
if(Normal.SizeSquared()<1.0e-8)Normal=FVector(0,0,1);
|
||||
Normal.Normalize();
|
||||
const double HalfSize=Step*2.0;
|
||||
const double X0=std::max<double>(Origin.X,X-HalfSize),X1=std::min<double>(Origin.X+Extent,X+HalfSize);
|
||||
const double Y0=std::max<double>(Origin.Y,Y-HalfSize),Y1=std::min<double>(Origin.Y+Extent,Y+HalfSize);
|
||||
if(X1-X0<1.0||Y1-Y0<1.0)continue;
|
||||
const auto SurfaceZ=[&](double PX,double PY)
|
||||
{
|
||||
if(std::abs(GZ)<1.0e-5)return Crossing;
|
||||
const double Offset=-(GX*(PX-X)+GY*(PY-Y))/GZ;
|
||||
return std::clamp(Crossing+Offset,ZMin,ZMax);
|
||||
};
|
||||
const int32 Base=static_cast<int32>(NewVertices.size());
|
||||
const double Xs[4]={X0,X1,X1,X0},Ys[4]={Y0,Y0,Y1,Y1};
|
||||
for(int32 Corner=0;Corner<4;++Corner)
|
||||
{
|
||||
const double Z=SurfaceZ(Xs[Corner],Ys[Corner]);
|
||||
NewVertices.emplace_back(Xs[Corner]*25.0,Ys[Corner]*25.0,Z*25.0);
|
||||
NewNormals.push_back(Normal);
|
||||
if(bHasUVs)NewUVs.emplace_back(static_cast<float>((Xs[Corner]-Origin.X)/256.0),
|
||||
static_cast<float>((Ys[Corner]-Origin.Y)/256.0));
|
||||
if(bHasColors)NewColors.push_back(Color);
|
||||
}
|
||||
const bool bBelowSolid=Density(X,Y,Crossing-1.0)<0.0f;
|
||||
if(bBelowSolid)NewTriangles.insert(NewTriangles.end(),{Base,Base+1,Base+3,Base+1,Base+2,Base+3});
|
||||
else NewTriangles.insert(NewTriangles.end(),{Base,Base+3,Base+1,Base+1,Base+3,Base+2});
|
||||
}
|
||||
}
|
||||
}
|
||||
if(NewVertices.empty()||NewTriangles.empty())return;
|
||||
const int32 AddedVertices=static_cast<int32>(NewVertices.size());
|
||||
auto InsertVertices=[&](auto& Existing,const auto& Added)
|
||||
{
|
||||
using TArrayType=std::remove_reference_t<decltype(Existing)>;
|
||||
TArrayType Combined;Combined.Reserve(Existing.Num()+static_cast<int32>(Added.size()));
|
||||
for(int32 I=0;I<OldSurfaceVertices;++I)Combined.Add(Existing[I]);
|
||||
for(const auto& Value:Added)Combined.Add(Value);
|
||||
for(int32 I=OldSurfaceVertices;I<Existing.Num();++I)Combined.Add(Existing[I]);
|
||||
Existing=std::move(Combined);
|
||||
};
|
||||
InsertVertices(Mesh.Vertices,NewVertices);InsertVertices(Mesh.Normals,NewNormals);
|
||||
if(bHasUVs)InsertVertices(Mesh.UVs,NewUVs);
|
||||
if(bHasColors)InsertVertices(Mesh.Colors,NewColors);
|
||||
for(int32& Index:Mesh.Triangles)if(Index>=OldSurfaceVertices)Index+=AddedVertices;
|
||||
const int32 CeilingStart=std::max(0,Mesh.Triangles.Num()-Mesh.NumCeilingTriangles*3);
|
||||
TArray<int32> CombinedTriangles;CombinedTriangles.Reserve(Mesh.Triangles.Num()+static_cast<int32>(NewTriangles.size()));
|
||||
for(int32 I=0;I<CeilingStart;++I)CombinedTriangles.Add(Mesh.Triangles[I]);
|
||||
for(const int32 Index:NewTriangles)CombinedTriangles.Add(OldSurfaceVertices+Index);
|
||||
for(int32 I=CeilingStart;I<Mesh.Triangles.Num();++I)CombinedTriangles.Add(Mesh.Triangles[I]);
|
||||
Mesh.Triangles=std::move(CombinedTriangles);Mesh.NumSurfaceVertices=OldSurfaceVertices+AddedVertices;
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
#pragma once
|
||||
|
||||
// Standalone-only port of the research field's round, winding tunnel profile.
|
||||
// The cubic centerline, variable radius and elliptical vertical section follow
|
||||
// GeneratedTunnelEdgeFromColumnProfile in VoxelRedefinedDensityField.cpp.
|
||||
namespace FStandaloneResearchTunnels
|
||||
{
|
||||
inline constexpr float WorldCenterZVoxels=-80.0f;
|
||||
|
||||
inline uint32 Mix(uint32 X)
|
||||
{
|
||||
X ^= X >> 16;
|
||||
X *= 0x7FEB352Du;
|
||||
X ^= X >> 15;
|
||||
X *= 0x846CA68Bu;
|
||||
X ^= X >> 16;
|
||||
return X;
|
||||
}
|
||||
|
||||
inline uint32 EdgeHash(int32 X, int32 Y, int32 Axis, uint32 Seed)
|
||||
{
|
||||
uint32 H = Seed ^ 0x9E3779B9u;
|
||||
H = Mix(H ^ static_cast<uint32>(X) * 0x85EBCA6Bu);
|
||||
H = Mix(H ^ static_cast<uint32>(Y) * 0xC2B2AE35u);
|
||||
return Mix(H ^ static_cast<uint32>(Axis) * 0x27D4EB2Fu);
|
||||
}
|
||||
|
||||
inline float Unit(uint32 X)
|
||||
{
|
||||
return static_cast<float>(Mix(X) >> 8) * (1.0f / 16777216.0f);
|
||||
}
|
||||
|
||||
inline uint32 NoiseHash(int32 X,int32 Y,int32 Z,uint32 Seed)
|
||||
{
|
||||
uint32 H=Mix(Seed^0xB5297A4Du);
|
||||
H=Mix(H^static_cast<uint32>(X)*0x68E31DA4u);
|
||||
H=Mix(H^static_cast<uint32>(Y)*0x1B56C4E9u);
|
||||
return Mix(H^static_cast<uint32>(Z)*0x9E3779B9u);
|
||||
}
|
||||
|
||||
inline float NoiseValue(int32 X,int32 Y,int32 Z,uint32 Seed)
|
||||
{
|
||||
return static_cast<float>(NoiseHash(X,Y,Z,Seed)>>8)*(2.0f/16777215.0f)-1.0f;
|
||||
}
|
||||
|
||||
inline float Fade(float T)
|
||||
{
|
||||
return T*T*(3.0f-2.0f*T);
|
||||
}
|
||||
|
||||
inline float ValueNoise(float X,float Y,float Z,int32 Wavelength,uint32 Seed)
|
||||
{
|
||||
const float Inv=1.0f/static_cast<float>(Wavelength);
|
||||
const float FX=X*Inv,FY=Y*Inv,FZ=Z*Inv;
|
||||
const int32 X0=FMath::FloorToInt(FX),Y0=FMath::FloorToInt(FY),Z0=FMath::FloorToInt(FZ);
|
||||
const float TX=Fade(FX-static_cast<float>(X0));
|
||||
const float TY=Fade(FY-static_cast<float>(Y0));
|
||||
const float TZ=Fade(FZ-static_cast<float>(Z0));
|
||||
const float Z00=FMath::Lerp(NoiseValue(X0,Y0,Z0,Seed),NoiseValue(X0+1,Y0,Z0,Seed),TX);
|
||||
const float Z10=FMath::Lerp(NoiseValue(X0,Y0+1,Z0,Seed),NoiseValue(X0+1,Y0+1,Z0,Seed),TX);
|
||||
const float Z01=FMath::Lerp(NoiseValue(X0,Y0,Z0+1,Seed),NoiseValue(X0+1,Y0,Z0+1,Seed),TX);
|
||||
const float Z11=FMath::Lerp(NoiseValue(X0,Y0+1,Z0+1,Seed),NoiseValue(X0+1,Y0+1,Z0+1,Seed),TX);
|
||||
return FMath::Lerp(FMath::Lerp(Z00,Z10,TY),FMath::Lerp(Z01,Z11,TY),TZ);
|
||||
}
|
||||
|
||||
inline float WallRelief(float X,float Y,float Z,uint32 Seed)
|
||||
{
|
||||
return 0.70f*ValueNoise(X,Y,Z,8,Seed^0xA511E9B3u)
|
||||
+1.05f*ValueNoise(X,Y,Z,16,Seed^0x63D83595u)
|
||||
+1.45f*ValueNoise(X,Y,Z,32,Seed^0xB5297A4Du);
|
||||
}
|
||||
|
||||
inline float SmoothMax(float A,float B,float Width)
|
||||
{
|
||||
const float H=FMath::Max(Width-FMath::Abs(A-B),0.0f)/Width;
|
||||
return FMath::Max(A,B)+(H*H)*(Width*0.25f);
|
||||
}
|
||||
|
||||
inline float Apply(float BaseDensity, float X, float Y, float Z, uint32 Seed,
|
||||
bool bEnabled, bool bEnhancedWalls)
|
||||
{
|
||||
if (!bEnabled) return BaseDensity;
|
||||
constexpr float CenterZ = WorldCenterZVoxels;
|
||||
if (FMath::Abs(Z-CenterZ) > 36.0f) return BaseDensity;
|
||||
|
||||
constexpr float Pitch = 144.0f;
|
||||
constexpr float RadiusBase = 28.0f;
|
||||
constexpr float HalfHeight = 26.0f;
|
||||
const int32 BaseCellX = FMath::FloorToInt(X/Pitch);
|
||||
const int32 BaseCellY = FMath::FloorToInt(Y/Pitch);
|
||||
float Best = -FLT_MAX;
|
||||
bool bHasEdge = false;
|
||||
const auto CellCenter = [&](int32 CX, int32 CY, float& OutX, float& OutY)
|
||||
{
|
||||
const uint32 H = EdgeHash(CX,CY,3,Seed);
|
||||
OutX = (static_cast<float>(CX)+0.5f)*Pitch
|
||||
+ (Unit(H^0xA511E9B3u)-0.5f)*Pitch*0.18f;
|
||||
OutY = (static_cast<float>(CY)+0.5f)*Pitch
|
||||
+ (Unit(H^0x63D83595u)-0.5f)*Pitch*0.18f;
|
||||
};
|
||||
const auto EvaluateEdge = [&](int32 CX, int32 CY, int32 Axis)
|
||||
{
|
||||
const uint32 H = EdgeHash(CX,CY,Axis,Seed);
|
||||
if (Unit(H^0x68E31DA4u) > 0.56f) return;
|
||||
bHasEdge = true;
|
||||
const int32 NX = CX + (Axis == 0 ? 1 : 0);
|
||||
const int32 NY = CY + (Axis == 1 ? 1 : 0);
|
||||
float AX,AY,BX,BY;
|
||||
CellCenter(CX,CY,AX,AY);
|
||||
CellCenter(NX,NY,BX,BY);
|
||||
|
||||
const float ABX = BX-AX, ABY = BY-AY;
|
||||
const float LengthSquared = ABX*ABX+ABY*ABY;
|
||||
float T = LengthSquared > 1.0e-8f
|
||||
? FMath::Clamp(((X-AX)*ABX+(Y-AY)*ABY)/LengthSquared,0.0f,1.0f)
|
||||
: 0.0f;
|
||||
const float Length = FMath::Sqrt(LengthSquared);
|
||||
const float NXrm = Length > 1.0e-4f ? -ABY/Length : 0.0f;
|
||||
const float NYrm = Length > 1.0e-4f ? ABX/Length : 0.0f;
|
||||
const float BendA = (Unit(H^0xB5297A4Du)*2.0f-1.0f)*Pitch*0.16f;
|
||||
const float BendB = (Unit(H^0x1B56C4E9u)*2.0f-1.0f)*Pitch*0.16f;
|
||||
const float C1X=AX+ABX/3.0f+NXrm*BendA, C1Y=AY+ABY/3.0f+NYrm*BendA;
|
||||
const float C2X=AX+ABX*(2.0f/3.0f)+NXrm*BendB;
|
||||
const float C2Y=AY+ABY*(2.0f/3.0f)+NYrm*BendB;
|
||||
|
||||
for (int32 Iteration=0;Iteration<4;++Iteration)
|
||||
{
|
||||
const float U=T, O=1.0f-U;
|
||||
const float PX=O*O*O*AX+3.0f*O*O*U*C1X+3.0f*O*U*U*C2X+U*U*U*BX;
|
||||
const float PY=O*O*O*AY+3.0f*O*O*U*C1Y+3.0f*O*U*U*C2Y+U*U*U*BY;
|
||||
const float DX=3.0f*O*O*(C1X-AX)+6.0f*O*U*(C2X-C1X)+3.0f*U*U*(BX-C2X);
|
||||
const float DY=3.0f*O*O*(C1Y-AY)+6.0f*O*U*(C2Y-C1Y)+3.0f*U*U*(BY-C2Y);
|
||||
const float DDX=6.0f*O*(C2X-2.0f*C1X+AX)+6.0f*U*(BX-2.0f*C2X+C1X);
|
||||
const float DDY=6.0f*O*(C2Y-2.0f*C1Y+AY)+6.0f*U*(BY-2.0f*C2Y+C1Y);
|
||||
const float Den=DX*DX+DY*DY+(PX-X)*DDX+(PY-Y)*DDY;
|
||||
if (FMath::Abs(Den)>1.0e-4f)
|
||||
T=FMath::Clamp(U-((PX-X)*DX+(PY-Y)*DY)/Den,0.0f,1.0f);
|
||||
}
|
||||
|
||||
const float O=1.0f-T;
|
||||
const float PX=O*O*O*AX+3.0f*O*O*T*C1X+3.0f*O*T*T*C2X+T*T*T*BX;
|
||||
const float PY=O*O*O*AY+3.0f*O*O*T*C1Y+3.0f*O*T*T*C2Y+T*T*T*BY;
|
||||
const float DX=X-PX,DY=Y-PY;
|
||||
const float Distance=FMath::Sqrt(DX*DX+DY*DY);
|
||||
const float Phase=Unit(H^0xA511E9B3u)*6.2831853071795864769f;
|
||||
const float Radius=RadiusBase*(0.82f+0.36f*Unit(H^0x63D83595u))
|
||||
*(1.0f+0.22f*VoxelMath::DetSin(6.2831853071795864769f*T+Phase));
|
||||
const float VerticalWave=4.0f*VoxelMath::DetSin(3.14159265358979323846f*T)
|
||||
*VoxelMath::DetSin(6.2831853071795864769f*T+Phase);
|
||||
const float VerticalOffset=Z-(CenterZ+VerticalWave);
|
||||
const float HorizontalDistance=FMath::Max(0.0f,Distance);
|
||||
const float Normalized=FMath::Sqrt(
|
||||
FMath::Square(HorizontalDistance/FMath::Max(Radius,1.0f))
|
||||
+FMath::Square(VerticalOffset/FMath::Max(HalfHeight,1.0f)));
|
||||
const float EdgeDensity=(1.0f-Normalized)*FMath::Min(Radius,HalfHeight);
|
||||
Best=bEnhancedWalls&&Best>-FLT_MAX
|
||||
?SmoothMax(Best,EdgeDensity,4.0f):FMath::Max(Best,EdgeDensity);
|
||||
};
|
||||
|
||||
for (int32 CY=BaseCellY-1;CY<=BaseCellY+1;++CY)
|
||||
for (int32 CX=BaseCellX-1;CX<=BaseCellX+1;++CX)
|
||||
{
|
||||
EvaluateEdge(CX,CY,0);
|
||||
EvaluateEdge(CX,CY,1);
|
||||
}
|
||||
if(!bHasEdge)return BaseDensity;
|
||||
if(bEnhancedWalls)Best+=WallRelief(X,Y,Z,Seed);
|
||||
// The wider base/round-field blend removes tiny marching-cubes wedges where a round
|
||||
// branch meets an existing room or passage wall. Relief remains active on the tunnel
|
||||
// wall; this only rounds the structural union boundary.
|
||||
return bEnhancedWalls?SmoothMax(BaseDensity,Best,8.0f):FMath::Max(BaseDensity,Best);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include "OwnerWorldLoader.h"
|
||||
#include "VoxelForgeCore/VoxelForgeCore.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace VoxelForgeCore
|
||||
{
|
||||
// Private standalone adapter: keeps the compatibility holders behind the public value API.
|
||||
ResolvedWorldSnapshot MakeStandaloneSnapshot(std::shared_ptr<FStandaloneOwnerWorld> owner);
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
#include "StandaloneSnapshotAdapter.h"
|
||||
|
||||
#include "FarShellsInternal.h"
|
||||
#include "VoxelClipmapDesiredTiles.h"
|
||||
#include "VoxelMarchingCubesMesher.h"
|
||||
#include "VoxelForgeCore/VoxelForgeCore.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <numeric>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace VoxelForgeCore
|
||||
{
|
||||
struct ResolvedWorldSnapshot::Data
|
||||
{
|
||||
std::shared_ptr<FStandaloneOwnerWorld> owner;
|
||||
WorldConfiguration configuration;
|
||||
};
|
||||
|
||||
namespace
|
||||
{
|
||||
FIntVector ToNative(Vec3i value) { return {value.x,value.y,value.z}; }
|
||||
FVector ToNative(Vec3d value) { return {value.x,value.y,value.z}; }
|
||||
Vec3d FromNative(const FVector& value) { return {value.X,value.Y,value.Z}; }
|
||||
FVoxelTileKey ToNative(const TileKey& value)
|
||||
{ return FVoxelTileKey(ToNative(value.coordinate),value.lod); }
|
||||
TileKey FromNative(const FVoxelTileKey& value)
|
||||
{ return {{value.Coord.X,value.Coord.Y,value.Coord.Z},value.Level}; }
|
||||
|
||||
WorldConfiguration MakeConfiguration(const FStandaloneOwnerWorld& owner)
|
||||
{
|
||||
WorldConfiguration out;
|
||||
out.seed=owner.Seed;
|
||||
out.clipRadius=owner.ClipRadius;
|
||||
out.maxLod=owner.MaxClipLevel;
|
||||
out.fullResolutionLodCount=owner.FullResClipLevels;
|
||||
out.coarseTileCells=owner.CoarseTileCells;
|
||||
out.renderDistanceChunks=owner.RenderDistanceChunks;
|
||||
out.contentCutMinLod=owner.StrateContentCutMinLevel;
|
||||
out.skirtCells=owner.SkirtCells;
|
||||
out.lodOctaveDrop=owner.LODOctaveDrop;
|
||||
out.viewDistanceUp=owner.Settings->ViewDistanceUp;
|
||||
out.viewDistanceDown=owner.Settings->ViewDistanceDown;
|
||||
out.strateViewMarginChunks=owner.Settings->StrateViewMarginChunks;
|
||||
out.clampViewToStrate=owner.Settings->bClampViewToStrate;
|
||||
out.generateSkirts=owner.bGenerateSkirts;
|
||||
out.viewerStartFound=owner.ViewerStartFound;
|
||||
out.viewerStartVoxels=FromNative(owner.ViewerStartVoxels);
|
||||
return out;
|
||||
}
|
||||
|
||||
double TileDistanceSquared(const TileKey& tile,Vec3i center)
|
||||
{
|
||||
const double scale=static_cast<double>(1<<tile.lod);
|
||||
const double dx=(static_cast<double>(tile.coordinate.x)+0.5)*scale-center.x;
|
||||
const double dy=(static_cast<double>(tile.coordinate.y)+0.5)*scale-center.y;
|
||||
const double dz=(static_cast<double>(tile.coordinate.z)+0.5)*scale-center.z;
|
||||
return dx*dx+dy*dy+dz*dz;
|
||||
}
|
||||
|
||||
void AddWord(std::uint64_t& hash,std::uint64_t word,int bytes)
|
||||
{
|
||||
for(int i=0;i<bytes;++i)
|
||||
{
|
||||
hash^=static_cast<std::uint8_t>(word>>(i*8));
|
||||
hash*=1099511628211ull;
|
||||
}
|
||||
}
|
||||
|
||||
std::uint64_t HashPayload(const FVoxelMeshData& mesh)
|
||||
{
|
||||
std::uint64_t hash=14695981039346656037ull;
|
||||
AddWord(hash,static_cast<std::uint64_t>(mesh.Vertices.Num()),8);
|
||||
for(const FVector& p:mesh.Vertices)
|
||||
{ AddWord(hash,std::bit_cast<std::uint64_t>(p.X),8); AddWord(hash,std::bit_cast<std::uint64_t>(p.Y),8); AddWord(hash,std::bit_cast<std::uint64_t>(p.Z),8); }
|
||||
AddWord(hash,static_cast<std::uint64_t>(mesh.Normals.Num()),8);
|
||||
for(const FVector& n:mesh.Normals)
|
||||
{ AddWord(hash,std::bit_cast<std::uint64_t>(n.X),8); AddWord(hash,std::bit_cast<std::uint64_t>(n.Y),8); AddWord(hash,std::bit_cast<std::uint64_t>(n.Z),8); }
|
||||
AddWord(hash,static_cast<std::uint64_t>(mesh.UVs.Num()),8);
|
||||
for(const auto& uv:mesh.UVs)
|
||||
{ AddWord(hash,std::bit_cast<std::uint64_t>(static_cast<double>(uv.X)),8);
|
||||
AddWord(hash,std::bit_cast<std::uint64_t>(static_cast<double>(uv.Y)),8); }
|
||||
AddWord(hash,static_cast<std::uint64_t>(mesh.Colors.Num()),8);
|
||||
for(const FColor& color:mesh.Colors)
|
||||
{ AddWord(hash,color.R,1); AddWord(hash,color.G,1); AddWord(hash,color.B,1); AddWord(hash,color.A,1); }
|
||||
AddWord(hash,static_cast<std::uint64_t>(mesh.Triangles.Num()),8);
|
||||
for(const int32 index:mesh.Triangles)AddWord(hash,static_cast<std::uint32_t>(index),4);
|
||||
AddWord(hash,static_cast<std::uint32_t>(mesh.NumSurfaceVertices),4);
|
||||
AddWord(hash,static_cast<std::uint32_t>(mesh.NumSkirtTriangles),4);
|
||||
AddWord(hash,static_cast<std::uint32_t>(mesh.NumCeilingTriangles),4);
|
||||
return hash;
|
||||
}
|
||||
|
||||
std::uint64_t HashTopology(const FVoxelMeshData& mesh)
|
||||
{
|
||||
const auto vertexKey=[&](int32 index)
|
||||
{
|
||||
std::uint64_t hash=14695981039346656037ull;
|
||||
if(index<0||index>=mesh.Vertices.Num()||index>=mesh.Normals.Num())
|
||||
{ AddWord(hash,UINT64_MAX,8); return hash; }
|
||||
const FVector& p=mesh.Vertices[index]; const FVector& n=mesh.Normals[index];
|
||||
for(double v:{p.X,p.Y,p.Z,n.X,n.Y,n.Z})AddWord(hash,std::bit_cast<std::uint64_t>(v),8);
|
||||
return hash;
|
||||
};
|
||||
std::vector<std::array<std::uint64_t,3>> triangles;
|
||||
triangles.reserve(static_cast<std::size_t>(mesh.Triangles.Num()/3));
|
||||
for(int32 i=0;i+2<mesh.Triangles.Num();i+=3)
|
||||
triangles.push_back({vertexKey(mesh.Triangles[i]),vertexKey(mesh.Triangles[i+1]),vertexKey(mesh.Triangles[i+2])});
|
||||
std::sort(triangles.begin(),triangles.end());
|
||||
std::uint64_t hash=14695981039346656037ull;
|
||||
AddWord(hash,static_cast<std::uint64_t>(triangles.size()),8);
|
||||
for(const auto& triangle:triangles)for(const auto key:triangle)AddWord(hash,key,8);
|
||||
return hash;
|
||||
}
|
||||
|
||||
std::uint64_t HashViewerMesh(const FVoxelMeshData& mesh)
|
||||
{
|
||||
std::uint64_t hash=14695981039346656037ull;
|
||||
AddWord(hash,static_cast<std::uint64_t>(mesh.Vertices.Num()),8);
|
||||
for(int32 i=0;i<mesh.Vertices.Num();++i)
|
||||
{
|
||||
const FVector& p=mesh.Vertices[i]; const FVector& n=mesh.Normals[i];
|
||||
for(float value:{static_cast<float>(p.X*0.01),static_cast<float>(p.Y*0.01),static_cast<float>(p.Z*0.01),
|
||||
static_cast<float>(n.X),static_cast<float>(n.Y),static_cast<float>(n.Z)})
|
||||
AddWord(hash,std::bit_cast<std::uint32_t>(value),4);
|
||||
}
|
||||
AddWord(hash,static_cast<std::uint64_t>(mesh.Triangles.Num()),8);
|
||||
for(const int32 index:mesh.Triangles)AddWord(hash,static_cast<std::uint32_t>(index),4);
|
||||
return hash;
|
||||
}
|
||||
|
||||
std::uint64_t HashBrushTransaction(const EditTransaction& transaction)
|
||||
{
|
||||
std::uint64_t hash=14695981039346656037ull;
|
||||
AddWord(hash,transaction.sequence,8);
|
||||
AddWord(hash,transaction.brushes.size(),8);
|
||||
for(const EditBrush& brush:transaction.brushes)
|
||||
{
|
||||
AddWord(hash,static_cast<std::uint8_t>(brush.shape),1);
|
||||
AddWord(hash,static_cast<std::uint8_t>(brush.operation),1);
|
||||
for(double v:{brush.a.x,brush.a.y,brush.a.z,brush.b.x,brush.b.y,brush.b.z,
|
||||
brush.halfExtent.x,brush.halfExtent.y,brush.halfExtent.z,
|
||||
brush.radius,brush.rounding})
|
||||
AddWord(hash,std::bit_cast<std::uint64_t>(v),8);
|
||||
AddWord(hash,std::bit_cast<std::uint32_t>(brush.strength),4);
|
||||
AddWord(hash,std::bit_cast<std::uint32_t>(brush.falloff),4);
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
bool IsFiniteBrush(const EditBrush& brush)
|
||||
{
|
||||
const std::array<double,11> values={brush.a.x,brush.a.y,brush.a.z,brush.b.x,brush.b.y,brush.b.z,
|
||||
brush.halfExtent.x,brush.halfExtent.y,brush.halfExtent.z,brush.radius,brush.rounding};
|
||||
return std::all_of(values.begin(),values.end(),[](double v){return std::isfinite(v);})
|
||||
&&brush.radius>=0.0&&brush.rounding>=0.0
|
||||
&&brush.halfExtent.x>=0.0&&brush.halfExtent.y>=0.0&&brush.halfExtent.z>=0.0
|
||||
&&std::isfinite(brush.strength)&&std::isfinite(brush.falloff)&&brush.falloff>=0.0f;
|
||||
}
|
||||
|
||||
FStandaloneShapeWorld::EDetailVariant ToNative(DetailVariant value)
|
||||
{
|
||||
switch(value)
|
||||
{
|
||||
case DetailVariant::smooth:return FStandaloneShapeWorld::EDetailVariant::Smooth;
|
||||
case DetailVariant::perVoxel:return FStandaloneShapeWorld::EDetailVariant::PerVoxel;
|
||||
default:return FStandaloneShapeWorld::EDetailVariant::Coherent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct detail_StandaloneSnapshotAdapter
|
||||
{
|
||||
static ResolvedWorldSnapshot FromOwner(std::shared_ptr<FStandaloneOwnerWorld> owner)
|
||||
{
|
||||
if(!owner||!owner->Settings||!owner->Manager||!owner->Generator)return {};
|
||||
auto data=std::make_shared<ResolvedWorldSnapshot::Data>();
|
||||
data->configuration=MakeConfiguration(*owner);
|
||||
data->owner=std::move(owner);
|
||||
return ResolvedWorldSnapshot(std::move(data));
|
||||
}
|
||||
};
|
||||
|
||||
ResolvedWorldSnapshot MakeStandaloneSnapshot(std::shared_ptr<FStandaloneOwnerWorld> owner)
|
||||
{ return detail_StandaloneSnapshotAdapter::FromOwner(std::move(owner)); }
|
||||
|
||||
std::optional<ResolvedWorldSnapshot> ResolvedWorldSnapshot::FromJson(
|
||||
std::string_view json,std::string& error)
|
||||
{
|
||||
auto owner=std::make_shared<FStandaloneOwnerWorld>();
|
||||
if(!StandaloneOwnerLoader::LoadJson(json,*owner,error))return std::nullopt;
|
||||
return detail_StandaloneSnapshotAdapter::FromOwner(std::move(owner));
|
||||
}
|
||||
|
||||
const WorldConfiguration& ResolvedWorldSnapshot::configuration() const
|
||||
{
|
||||
static const WorldConfiguration empty{};
|
||||
return data_?data_->configuration:empty;
|
||||
}
|
||||
|
||||
struct World::Impl
|
||||
{
|
||||
std::shared_ptr<FStandaloneOwnerWorld> owner;
|
||||
WorldConfiguration configuration;
|
||||
std::unique_ptr<FStandaloneShapeWorld> shape;
|
||||
std::vector<FStandaloneShapeWorld::FEditBrush> editLog;
|
||||
std::map<std::uint64_t,EditResult> transactions;
|
||||
bool hasLastSequence=false;
|
||||
std::uint64_t lastSequence=0;
|
||||
};
|
||||
|
||||
World::World(ResolvedWorldSnapshot snapshot):impl_(std::make_unique<Impl>())
|
||||
{
|
||||
if(snapshot.data_)
|
||||
{
|
||||
impl_->owner=snapshot.data_->owner;
|
||||
impl_->configuration=snapshot.data_->configuration;
|
||||
}
|
||||
}
|
||||
World::~World()=default;
|
||||
World::World(World&&) noexcept=default;
|
||||
World& World::operator=(World&&) noexcept=default;
|
||||
|
||||
bool World::compile(const ShapeBuildRequest& request,const JobScheduler& scheduler,std::string& error)
|
||||
{
|
||||
if(!impl_->owner){error="resolved world snapshot is empty";return false;}
|
||||
auto shape=std::make_unique<FStandaloneShapeWorld>();
|
||||
const bool ok=shape->Build(*impl_->owner,ToNative(request.minVoxel),ToNative(request.maxVoxel),
|
||||
ToNative(request.clipMinVoxel),ToNative(request.clipMaxVoxel),
|
||||
static_cast<int32>(std::clamp<std::uint32_t>(request.workerLimit,1,8)),ToNative(request.detail),
|
||||
request.includeFarWorld,error,&scheduler,request.roundTunnels,request.profileDetailBand);
|
||||
if(ok)impl_->shape=std::move(shape);
|
||||
return ok;
|
||||
}
|
||||
|
||||
void World::buildFarWorld()
|
||||
{ if(impl_->shape)impl_->shape->BuildFarWorld(); }
|
||||
bool World::isCompiled() const noexcept { return impl_&&impl_->shape&&impl_->shape->IsBuilt(); }
|
||||
bool World::hasFarWorld() const noexcept { return impl_&&impl_->shape&&impl_->shape->HasFarWorld(); }
|
||||
|
||||
ShapeBuildStats World::buildStats() const
|
||||
{
|
||||
ShapeBuildStats out;
|
||||
if(!impl_||!impl_->shape)return out;
|
||||
const auto& stats=impl_->shape->GetStats();
|
||||
out.shapeSeconds=stats.ShapeSeconds;out.intervalSeconds=stats.IntervalSeconds;
|
||||
out.surfaceSeconds=stats.SurfaceSeconds;out.farShapeSeconds=stats.FarShapeSeconds;
|
||||
out.primitiveCount=stats.PrimitiveCount;out.surfaceCandidates=stats.SurfaceCandidates;
|
||||
out.detailFlips=stats.DetailFlips;out.walkSamples=stats.WalkSamples;out.walkFailures=stats.WalkFailures;
|
||||
return out;
|
||||
}
|
||||
|
||||
float World::densityAt(Vec3d position) const
|
||||
{ return impl_&&impl_->shape?impl_->shape->DensityAt(static_cast<float>(position.x),static_cast<float>(position.y),static_cast<float>(position.z)):0.0f; }
|
||||
float World::densityAtLattice(Vec3i position) const
|
||||
{ return impl_&&impl_->shape?impl_->shape->DensityAtLattice(position.x,position.y,position.z):0.0f; }
|
||||
bool World::isSolidAt(Vec3d position) const { return densityAt(position)<0.0f; }
|
||||
|
||||
bool World::isSolidAlongSegment(Vec3d start,Vec3d end,double spacing) const
|
||||
{
|
||||
if(!impl_||!impl_->shape||!std::isfinite(spacing)||spacing<=0.0)return false;
|
||||
const double dx=end.x-start.x,dy=end.y-start.y,dz=end.z-start.z;
|
||||
const double length=std::sqrt(dx*dx+dy*dy+dz*dz);
|
||||
const std::size_t intervals=std::max<std::size_t>(1,static_cast<std::size_t>(std::ceil(length/spacing)));
|
||||
for(std::size_t i=0;i<=intervals;++i)
|
||||
{
|
||||
const double t=static_cast<double>(i)/static_cast<double>(intervals);
|
||||
if(isSolidAt({start.x+dx*t,start.y+dy*t,start.z+dz*t}))return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
TileClass World::classifyBox(Vec3i origin,std::int32_t step,std::int32_t cells) const
|
||||
{
|
||||
if(!impl_||!impl_->shape)return TileClass::mixed;
|
||||
const EVoxelTileClass result=impl_->shape->ClassifyBox(ToNative(origin),step,cells);
|
||||
return result==EVoxelTileClass::AllSolid?TileClass::allSolid:
|
||||
result==EVoxelTileClass::AllAir?TileClass::allAir:TileClass::mixed;
|
||||
}
|
||||
|
||||
std::vector<TileKey> World::prioritizeTiles(std::span<const TileKey> tiles,Vec3i centerChunk)
|
||||
{
|
||||
std::vector<TileKey> output(tiles.begin(),tiles.end());
|
||||
std::sort(output.begin(),output.end(),[&](const TileKey& a,const TileKey& b)
|
||||
{
|
||||
const double da=TileDistanceSquared(a,centerChunk),db=TileDistanceSquared(b,centerChunk);
|
||||
if(da!=db)return da<db;
|
||||
if(a.lod!=b.lod)return a.lod<b.lod;
|
||||
if(a.coordinate.z!=b.coordinate.z)return a.coordinate.z<b.coordinate.z;
|
||||
if(a.coordinate.y!=b.coordinate.y)return a.coordinate.y<b.coordinate.y;
|
||||
return a.coordinate.x<b.coordinate.x;
|
||||
});
|
||||
return output;
|
||||
}
|
||||
|
||||
std::vector<TileKey> World::desiredTiles(Vec3d cameraPosition) const
|
||||
{
|
||||
if(!impl_||!impl_->owner)return {};
|
||||
const auto& world=*impl_->owner;
|
||||
const FIntVector center(FMath::FloorToInt(cameraPosition.x/CHUNK_SIZE),
|
||||
FMath::FloorToInt(cameraPosition.y/CHUNK_SIZE),FMath::FloorToInt(cameraPosition.z/CHUNK_SIZE));
|
||||
bool hasStrate=false;int32 top=0,bottom=0;
|
||||
if(world.Settings->bClampViewToStrate)hasStrate=world.Manager->GetStrateChunkZBounds(center.Z,top,bottom);
|
||||
int32 minZ=0,maxZ=0;
|
||||
VoxelClipmapDesiredTiles::ResolveVerticalBounds(center.Z,world.Settings->ViewDistanceUp,
|
||||
world.Settings->ViewDistanceDown,world.Settings->StrateViewMarginChunks,
|
||||
world.Settings->bClampViewToStrate,hasStrate,top,bottom,minZ,maxZ);
|
||||
VoxelClipmapDesiredTiles::FParameters parameters;
|
||||
parameters.ClipRadius=world.ClipRadius;parameters.MaxClipLevel=FMath::Clamp(world.MaxClipLevel,0,8);
|
||||
parameters.RenderDistanceChunks=world.RenderDistanceChunks;
|
||||
TArray<FVoxelTileKey> nativeTiles;
|
||||
VoxelClipmapDesiredTiles::Build(center,minZ,maxZ,parameters,nativeTiles);
|
||||
std::vector<TileKey> tiles;tiles.reserve(static_cast<std::size_t>(nativeTiles.Num()));
|
||||
for(const FVoxelTileKey& key:nativeTiles)tiles.push_back(FromNative(key));
|
||||
std::sort(tiles.begin(),tiles.end(),[&](const TileKey& a,const TileKey& b)
|
||||
{
|
||||
const double da=TileDistanceSquared(a,{center.X,center.Y,center.Z});
|
||||
const double db=TileDistanceSquared(b,{center.X,center.Y,center.Z});
|
||||
return da==db?a.lod<b.lod:da<db;
|
||||
});
|
||||
return tiles;
|
||||
}
|
||||
|
||||
std::optional<TileMesh> World::generateTile(const TileKey& key,const TileGenerationOptions& options,
|
||||
std::string& error) const
|
||||
{
|
||||
if(!impl_||!impl_->owner||!impl_->shape||!impl_->shape->IsBuilt())
|
||||
{ error="world must be compiled before generating tiles";return std::nullopt; }
|
||||
const auto& world=*impl_->owner;
|
||||
UVoxelMarchingCubesMesher mesher;
|
||||
mesher.SetGenerator(world.Generator.get());
|
||||
mesher.SetStandaloneShapeWorld(impl_->shape.get());
|
||||
mesher.bStandaloneSkipUvAndColors=options.skipUvAndColors;
|
||||
mesher.bStandaloneSkipUV=options.skipUv;mesher.bStandaloneSkipColors=options.skipColors;
|
||||
mesher.bStandaloneSkipMaterialGroups=options.skipMaterialGroups;
|
||||
mesher.bGenerateSkirts=world.bGenerateSkirts;mesher.SkirtCells=static_cast<float>(world.SkirtCells);
|
||||
mesher.LODOctaveDrop=world.LODOctaveDrop;
|
||||
const int32 level=key.lod,extent=CHUNK_SIZE<<level;
|
||||
const int32 cells=level<world.FullResClipLevels?CHUNK_SIZE:FMath::Max(1,world.CoarseTileCells);
|
||||
const int32 step=FMath::Max(1,extent/cells);
|
||||
int64 sampleCount=0;std::vector<float> densityValues;
|
||||
const FVoxelTileKey nativeKey=ToNative(key);
|
||||
const FIntVector origin=nativeKey.OriginVoxels();
|
||||
FVoxelMeshData mesh=mesher.GenerateMesh(origin,step,cells,nullptr,
|
||||
options.bandMinZVoxel,options.bandMaxZVoxel,&sampleCount,nullptr,nullptr,
|
||||
(options.hashDensity||options.captureDensitySamples)?&densityValues:nullptr);
|
||||
if(impl_->shape->HasFarWorld())
|
||||
{
|
||||
AppendFarStratumShells(world,*impl_->shape,nativeKey,step,mesh);
|
||||
AppendFarConnectorShells(*impl_->shape,nativeKey,step,world.CoarseTileCells,mesh);
|
||||
}
|
||||
|
||||
TileMesh out;out.key=key;out.densitySampleCount=static_cast<std::uint64_t>(std::max<int64>(0,sampleCount));
|
||||
out.meshPayloadAllocatedBytes=static_cast<std::uint64_t>(mesh.Vertices.GetAllocatedSize())
|
||||
+static_cast<std::uint64_t>(mesh.Normals.GetAllocatedSize())
|
||||
+static_cast<std::uint64_t>(mesh.UVs.GetAllocatedSize())
|
||||
+static_cast<std::uint64_t>(mesh.Colors.GetAllocatedSize())
|
||||
+static_cast<std::uint64_t>(mesh.Triangles.GetAllocatedSize());
|
||||
out.groups.surfaceVertexCount=static_cast<std::uint32_t>(mesh.NumSurfaceVertices);
|
||||
out.groups.ceilingTriangleCount=static_cast<std::uint32_t>(mesh.NumCeilingTriangles);
|
||||
out.groups.groundTriangleCount=static_cast<std::uint32_t>(
|
||||
std::max(0,mesh.Triangles.Num()/3-mesh.NumCeilingTriangles));
|
||||
out.groups.skirtTriangleCount=static_cast<std::uint32_t>(mesh.NumSkirtTriangles);
|
||||
out.vertices.reserve(static_cast<std::size_t>(mesh.Vertices.Num()));
|
||||
for(int32 i=0;i<mesh.Vertices.Num();++i)
|
||||
{
|
||||
const FVector& p=mesh.Vertices[i];
|
||||
const FVector normal=i<mesh.Normals.Num()?mesh.Normals[i]:FVector::ZeroVector;
|
||||
const FVector2f uv=i<mesh.UVs.Num()?mesh.UVs[i]:FVector2f(0.0f,0.0f);
|
||||
const FColor color=i<mesh.Colors.Num()?mesh.Colors[i]:FColor(0,0,0,0);
|
||||
out.vertices.push_back({{p.X,p.Y,p.Z},{normal.X,normal.Y,normal.Z},{uv.X,uv.Y},
|
||||
{color.R,color.G,color.B,color.A}});
|
||||
}
|
||||
out.indices.reserve(static_cast<std::size_t>(mesh.Triangles.Num()));
|
||||
for(const int32 index:mesh.Triangles)out.indices.push_back(static_cast<std::uint32_t>(index));
|
||||
if(options.captureDensitySamples)out.debugDensitySamples=std::move(densityValues);
|
||||
if(options.hashDensity)
|
||||
{
|
||||
std::uint64_t densityHash=14695981039346656037ull;
|
||||
const auto& values=options.captureDensitySamples?out.debugDensitySamples:densityValues;
|
||||
for(const float value:values)
|
||||
{ densityHash^=std::bit_cast<std::uint32_t>(value);densityHash*=1099511628211ull; }
|
||||
out.densityHash=densityHash;out.meshHash=HashViewerMesh(mesh);
|
||||
out.payloadHash=HashPayload(mesh);out.topologyHash=HashTopology(mesh);
|
||||
out.hasDensityHash=out.hasMeshHash=out.hasPayloadHash=out.hasTopologyHash=true;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<EditResult> World::applyEditTransaction(const EditTransaction& transaction,
|
||||
std::span<const TileKey> desired,std::string& error)
|
||||
{
|
||||
if(!impl_||!impl_->shape){error="world must be compiled before edits can be applied";return std::nullopt;}
|
||||
const std::uint64_t digest=HashBrushTransaction(transaction);
|
||||
if(const auto found=impl_->transactions.find(transaction.sequence);found!=impl_->transactions.end())
|
||||
{
|
||||
if(found->second.digest!=digest){error="edit sequence was reused with different brush data";return std::nullopt;}
|
||||
return found->second;
|
||||
}
|
||||
if(impl_->hasLastSequence&&transaction.sequence<=impl_->lastSequence)
|
||||
{ error="edit transactions must be applied in increasing sequence order";return std::nullopt; }
|
||||
for(const EditBrush& brush:transaction.brushes)
|
||||
{
|
||||
if(!IsFiniteBrush(brush)){error="edit brush contains non-finite or negative dimensions";return std::nullopt;}
|
||||
if(static_cast<unsigned>(brush.shape)>static_cast<unsigned>(EditBrush::Shape::roundedBox)
|
||||
||static_cast<unsigned>(brush.operation)>static_cast<unsigned>(EditBrush::Operation::densityOffset))
|
||||
{error="edit brush has an unknown shape or operation";return std::nullopt;}
|
||||
}
|
||||
std::vector<FStandaloneShapeWorld::FEditBrush> native;
|
||||
native.reserve(transaction.brushes.size());
|
||||
for(const EditBrush& brush:transaction.brushes)
|
||||
{
|
||||
FStandaloneShapeWorld::FEditBrush output;
|
||||
output.Shape=static_cast<FStandaloneShapeWorld::FEditBrush::EShape>(brush.shape);
|
||||
output.Operation=static_cast<FStandaloneShapeWorld::FEditBrush::EOperation>(brush.operation);
|
||||
output.A={brush.a.x,brush.a.y,brush.a.z};output.B={brush.b.x,brush.b.y,brush.b.z};
|
||||
output.HalfExtent={brush.halfExtent.x,brush.halfExtent.y,brush.halfExtent.z};
|
||||
output.Radius=brush.radius;output.Rounding=brush.rounding;
|
||||
output.Strength=brush.strength;output.Falloff=brush.falloff;
|
||||
native.push_back(output);
|
||||
}
|
||||
impl_->editLog.insert(impl_->editLog.end(),native.begin(),native.end());
|
||||
impl_->shape->SetEditTransaction(impl_->editLog);
|
||||
const FIntVector min=impl_->shape->GetEditBoundsMin(),max=impl_->shape->GetEditBoundsMax();
|
||||
EditResult result;result.digest=digest;
|
||||
result.affectedByLod.resize(static_cast<std::size_t>(std::max(impl_->configuration.maxLod,0)+1));
|
||||
for(const TileKey& tile:desired)
|
||||
{
|
||||
if(tile.lod<0||tile.lod>=static_cast<int32>(result.affectedByLod.size()))continue;
|
||||
const FIntVector origin=ToNative(tile).OriginVoxels();
|
||||
const int32 extent=ToNative(tile).ExtentVoxels();
|
||||
const int32 pad=std::max(2,ToNative(tile).StepVoxels());
|
||||
if(origin.X-pad>max.X||origin.X+extent+pad<min.X
|
||||
||origin.Y-pad>max.Y||origin.Y+extent+pad<min.Y
|
||||
||origin.Z-pad>max.Z||origin.Z+extent+pad<min.Z)continue;
|
||||
result.affectedByLod[static_cast<std::size_t>(tile.lod)].push_back(tile);
|
||||
}
|
||||
impl_->transactions.emplace(transaction.sequence,result);
|
||||
impl_->hasLastSequence=true;impl_->lastSequence=transaction.sequence;
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<FarConnectorSegment> World::farConnectorSegments() const
|
||||
{
|
||||
std::vector<FarConnectorSegment> result;
|
||||
if(!impl_||!impl_->shape)return result;
|
||||
const auto& source=impl_->shape->GetFarConnectorSegments();result.reserve(source.size());
|
||||
for(const auto& segment:source)result.push_back({FromNative(segment.Start),FromNative(segment.End),segment.Radius});
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> World::farConnectorCandidates(Vec3i minVoxel,Vec3i maxVoxel) const
|
||||
{
|
||||
std::vector<std::uint32_t> result;
|
||||
if(impl_&&impl_->shape)impl_->shape->FindFarConnectorCandidates(ToNative(minVoxel),ToNative(maxVoxel),result);
|
||||
return result;
|
||||
}
|
||||
|
||||
bool World::auditDetailPassing() const { return impl_&&impl_->shape&&impl_->shape->IsDetailAuditPassing(); }
|
||||
bool World::auditSurfaceFamilies(bool passageOnly) const
|
||||
{ return impl_&&impl_->shape&&impl_->shape->AuditSurfaceBandFamilies(passageOnly); }
|
||||
bool World::auditViewSurface(Vec3d camera,double yaw,double pitch) const
|
||||
{ return impl_&&impl_->shape&&impl_->shape->AuditViewSurface(camera.x*0.25,camera.y*0.25,
|
||||
camera.z*0.25,static_cast<float>(yaw),static_cast<float>(pitch)); }
|
||||
bool World::debugCriticalAirAt(Vec3d position) const
|
||||
{ return impl_&&impl_->shape&&impl_->shape->DebugCriticalAirAt(position.x,position.y,position.z); }
|
||||
bool World::debugSolidOverlayAt(Vec3d position) const
|
||||
{ return impl_&&impl_->shape&&impl_->shape->DebugSolidOverlayAt(position.x,position.y,position.z); }
|
||||
const WorldConfiguration& World::configuration() const
|
||||
{ return impl_?impl_->configuration:ResolvedWorldSnapshot{}.configuration(); }
|
||||
}
|
||||
|
||||
std::size_t VoxelForgeCore::TileKeyHash::operator()(const TileKey& key) const noexcept
|
||||
{
|
||||
std::size_t h=static_cast<std::uint32_t>(key.coordinate.x)*0x9E3779B1u;
|
||||
h^=static_cast<std::uint32_t>(key.coordinate.y)+0x9E3779B9u+(h<<6)+(h>>2);
|
||||
h^=static_cast<std::uint32_t>(key.coordinate.z)+0x9E3779B9u+(h<<6)+(h>>2);
|
||||
h^=static_cast<std::uint32_t>(key.lod)+0x9E3779B9u+(h<<6)+(h>>2);
|
||||
return h;
|
||||
}
|
||||
Reference in new issue
Block a user