载入中...
搜索中...
未找到
CaveSurfaceReactivity.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <array>
4#include <cmath>
5#include <cstddef>
6#include <cstdint>
7#include <string>
8#include <vector>
9#include "procgen/MeshBuild.h"
12
13// CaveSurfaceReactivity.cpp
14namespace eve::procgen {
15namespace {
16
17struct Normal {
18 float x = 0.f;
19 float y = 0.f;
20 float z = 0.f;
21 bool valid = false;
22};
23
24size_t voxelIndex(int x, int y, int z, int nx, int ny) {
25 return size_t(x) + size_t(y) * size_t(nx) + size_t(z) * size_t(nx) * size_t(ny);
26}
27
28Normal densityNormal(const std::vector<float>& density, int x, int y, int z, int nx, int ny, float hx, float hy,
29 float hz) {
30 const float gx = (density[voxelIndex(x + 1, y, z, nx, ny)] - density[voxelIndex(x - 1, y, z, nx, ny)]) / (2.f * hx);
31 const float gy = (density[voxelIndex(x, y + 1, z, nx, ny)] - density[voxelIndex(x, y - 1, z, nx, ny)]) / (2.f * hy);
32 const float gz = (density[voxelIndex(x, y, z + 1, nx, ny)] - density[voxelIndex(x, y, z - 1, nx, ny)]) / (2.f * hz);
33 const float length = std::sqrt(gx * gx + gy * gy + gz * gz);
34 if (length <= 1e-6f) return {};
35 return {gx / length, gy / length, gz / length, true};
36}
37
38} // namespace
39
41 const std::vector<float>& rateField, int nx, int ny, int nz,
42 float strength, int iterations) {
44 if (strength <= 0.f || iterations <= 0 || nx < 5 || ny < 5 || nz < 5 || density.size() != rateField.size() ||
45 density.size() != size_t(nx) * size_t(ny) * size_t(nz))
46 return result;
47
48 const float hx = 2.f / float(nx - 1), hy = 2.f / float(ny - 1), hz = 2.f / float(nz - 1);
49 const float cellScale = std::min({hx, hy, hz});
50 const float band = cellScale * 2.5f;
51 const std::array<std::array<int, 3>, 6> offsets = {
52 {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}};
53 std::vector<float> source(density.size());
54 std::vector<uint8_t> affected(density.size(), uint8_t(0));
55
56 for (int iteration = 0; iteration < iterations; ++iteration) {
58 for (int z = 2; z < nz - 2; ++z) {
59 for (int y = 2; y < ny - 2; ++y) {
60 for (int x = 2; x < nx - 2; ++x) {
61 const size_t center = voxelIndex(x, y, z, nx, ny);
62 const float value = source[center];
63 if (std::fabs(value) > band) continue;
64 const Normal centerNormal = densityNormal(source, x, y, z, nx, ny, hx, hy, hz);
65 if (!centerNormal.valid) continue;
66
67 float dispersion = 0.f;
68 int samples = 0;
69 for (const auto& offset : offsets) {
70 const int sx = x + offset[0], sy = y + offset[1], sz = z + offset[2];
71 if (std::fabs(source[voxelIndex(sx, sy, sz, nx, ny)]) > band * 1.5f) continue;
72 const Normal neighbor = densityNormal(source, sx, sy, sz, nx, ny, hx, hy, hz);
73 if (!neighbor.valid) continue;
74 const float alignment = std::fabs(centerNormal.x * neighbor.x + centerNormal.y * neighbor.y +
75 centerNormal.z * neighbor.z);
76 dispersion += 1.f - std::clamp(alignment, 0.f, 1.f);
77 ++samples;
78 }
79 if (samples < 2) continue;
80 const float normalDispersion = std::clamp(std::sqrt(dispersion / float(samples)) * 1.8f, 0.f, 1.f);
81 if (normalDispersion <= 1e-4f) continue;
82
83 const float surfaceWeight = 1.f - std::clamp(std::fabs(value) / band, 0.f, 1.f);
84 const float rateMultiplier = std::clamp(rateField[center], 0.25f, 2.5f);
85 const float retreat = strength * cellScale * 0.045f * surfaceWeight * normalDispersion *
86 rateMultiplier / float(iterations);
87 density[center] -= retreat;
88 if (affected[center] == 0) {
89 affected[center] = 1;
90 ++result.affectedVoxels;
91 }
92 result.maximumRetreat = std::max(result.maximumRetreat, retreat);
93 result.totalRetreat += retreat;
94 result.maximumNormalDispersion = std::max(result.maximumNormalDispersion, normalDispersion);
95 result.minimumRateMultiplier = std::min(result.minimumRateMultiplier, rateMultiplier);
96 result.maximumRateMultiplier = std::max(result.maximumRateMultiplier, rateMultiplier);
97 }
98 }
99 }
100 }
101 return result;
102}
103
104} // namespace eve::procgen
105
106// CaveWaterTable.cpp
107namespace eve::procgen {
108namespace {
109
110float smoothstep(float lo, float hi, float value) {
111 const float t = std::clamp((value - lo) / std::max(hi - lo, 1e-6f), 0.f, 1.f);
112 return t * t * (3.f - 2.f * t);
113}
114
115} // namespace
116
119 // passageAngle is zero at the crown and +/- pi/2 at the walls. Restricting
120 // retreat to sidewalls prevents a horizontal density slice from cutting floors.
121 result.sidewallMask = std::pow(std::fabs(std::sin(input.passageAngle)), 1.45f);
122 const float seedPhase = float(input.seed % 1009u) * 0.006227141f;
123 const float halfThickness = 0.022f + input.fluctuation * 0.035f;
124 for (int stage = 0; stage < input.stages; ++stage) {
125 const float nominalLevel = input.level - float(stage) * input.stageDrop;
126 // Long-wavelength variation retains a recognizably level belt without making
127 // it an artificial perfectly planar cut through every chamber.
128 const float localLevel =
129 nominalLevel + std::sin(input.along * 1.7f + seedPhase + float(stage) * 1.91f) * halfThickness * 0.22f;
130 const float verticalDistance = std::fabs(input.y - localLevel);
131 const float band = 1.f - smoothstep(halfThickness, halfThickness * 2.6f, verticalDistance);
132 const float preservation = std::pow(0.78f, float(stage));
133 const float erosion = band * preservation * result.sidewallMask;
134 if (erosion > result.erosion) {
135 result.erosion = erosion;
136 result.dominantStage = stage;
137 result.dominantLevel = nominalLevel;
138 }
139 }
140 return result;
141}
142
143} // namespace eve::procgen
144
145// CaveWetness.cpp
146namespace eve::procgen {
147namespace {
148
149struct WetVertex {
150 float px = 0.f, py = 0.f, pz = 0.f;
151 float nx = 0.f, ny = 0.f, nz = 0.f;
152 float u = 0.f, v = 0.f;
153 float wetness = 0.f;
154};
155
156uint32_t hash(uint32_t value) {
157 value ^= value >> 16u;
158 value *= 0x7feb352du;
159 value ^= value >> 15u;
160 value *= 0x846ca68bu;
161 return value ^ (value >> 16u);
162}
163
164float latticeNoise(float x, float y, float z, uint32_t seed) {
165 const int ix = int(std::floor(x)), iy = int(std::floor(y)), iz = int(std::floor(z));
166 const float fx = x - float(ix), fy = y - float(iy), fz = z - float(iz);
167 auto smooth = [](float t) { return t * t * (3.f - 2.f * t); };
168 auto sample = [seed](int sx, int sy, int sz) {
169 const uint32_t h = hash(uint32_t(sx) * 73856093u ^ uint32_t(sy) * 19349663u ^ uint32_t(sz) * 83492791u ^ seed);
170 return float(h & 0xffffu) / 32767.5f - 1.f;
171 };
172 auto lerp = [](float a, float b, float t) { return a + (b - a) * t; };
173 const float ux = smooth(fx), uy = smooth(fy), uz = smooth(fz);
174 const float x00 = lerp(sample(ix, iy, iz), sample(ix + 1, iy, iz), ux);
175 const float x10 = lerp(sample(ix, iy + 1, iz), sample(ix + 1, iy + 1, iz), ux);
176 const float x01 = lerp(sample(ix, iy, iz + 1), sample(ix + 1, iy, iz + 1), ux);
177 const float x11 = lerp(sample(ix, iy + 1, iz + 1), sample(ix + 1, iy + 1, iz + 1), ux);
178 return lerp(lerp(x00, x10, uy), lerp(x01, x11, uy), uz);
179}
180
181WetVertex interpolate(WetVertex a, WetVertex b) {
182 const float denominator = a.wetness - b.wetness;
183 const float t = std::fabs(denominator) > 1e-12f ? std::clamp(a.wetness / denominator, 0.f, 1.f) : 0.5f;
184 auto lerp = [t](float from, float to) { return from + (to - from) * t; };
185 return {lerp(a.px, b.px), lerp(a.py, b.py), lerp(a.pz, b.pz),
186 lerp(a.nx, b.nx), lerp(a.ny, b.ny), lerp(a.nz, b.nz),
187 lerp(a.u, b.u), lerp(a.v, b.v), 0.f};
188}
189
190std::vector<WetVertex> clip(const WetVertex (&triangle)[3], bool keepWet) {
191 std::vector<WetVertex> input{triangle, triangle + 3};
192 std::vector<WetVertex> output;
193 output.reserve(4);
194 for (size_t i = 0; i < input.size(); ++i) {
195 const WetVertex current = input[i];
196 const WetVertex next = input[(i + 1) % input.size()];
197 const bool currentInside = keepWet ? current.wetness >= 0.f : current.wetness <= 0.f;
198 const bool nextInside = keepWet ? next.wetness >= 0.f : next.wetness <= 0.f;
199 if (currentInside) output.push_back(current);
200 if (currentInside != nextInside) output.push_back(interpolate(current, next));
201 }
202 return output;
203}
204
205void emitPolygon(MeshBuild& mesh, const std::vector<WetVertex>& polygon, const std::string& group) {
206 if (polygon.size() < 3) return;
207 mesh.setActiveGroup(group);
208 for (size_t corner = 1; corner + 1 < polygon.size(); ++corner) {
209 const uint32_t base = uint32_t(mesh.getVertexCount());
210 for (const WetVertex& vertex : {polygon[0], polygon[corner], polygon[corner + 1]})
211 mesh.addVertex(vertex.px, vertex.py, vertex.pz, vertex.nx, vertex.ny, vertex.nz, vertex.u, vertex.v);
212 mesh.addTriangle(base, base + 1, base + 2);
213 }
214}
215
216} // namespace
217
218float caveWetnessField(CaveHydrologyVec3 point, const std::vector<CaveHydrologyPoint>& drainageSpine,
219 float fallbackRadius, uint32_t seed) {
220 float nearestDistance2 = 1e9f;
221 float nearestY = 0.f;
222 float nearestRadius = fallbackRadius;
223 for (size_t i = 1; i < drainageSpine.size(); ++i) {
224 const CaveHydrologyVec3 start = drainageSpine[i - 1].position;
225 const CaveHydrologyVec3 end = drainageSpine[i].position;
226 const CaveHydrologyVec3 segment{end.x - start.x, end.y - start.y, end.z - start.z};
227 const float length2 = segment.x * segment.x + segment.y * segment.y + segment.z * segment.z;
228 const CaveHydrologyVec3 relative{point.x - start.x, point.y - start.y, point.z - start.z};
229 const float t =
230 length2 > 1e-8f
231 ? std::clamp((relative.x * segment.x + relative.y * segment.y + relative.z * segment.z) / length2, 0.f,
232 1.f)
233 : 0.f;
234 const CaveHydrologyVec3 nearest{start.x + segment.x * t, start.y + segment.y * t, start.z + segment.z * t};
235 const float dx = point.x - nearest.x, dy = point.y - nearest.y, dz = point.z - nearest.z;
236 const float distance2 = dx * dx + dy * dy + dz * dz;
237 if (distance2 < nearestDistance2) {
238 nearestDistance2 = distance2;
239 nearestY = nearest.y;
240 nearestRadius = drainageSpine[i - 1].radius + (drainageSpine[i].radius - drainageSpine[i - 1].radius) * t;
241 }
242 }
243 const float radius2 = std::max(nearestRadius * nearestRadius, 1e-8f);
244 const float drainage = (radius2 * 6.25f - nearestDistance2) / (radius2 * 6.25f);
245 const float gravity = (nearestY - nearestRadius * 0.22f - point.y) / std::max(nearestRadius, 1e-4f);
246 const float surfaceAccess = latticeNoise(point.x * 4.f, point.y * 2.f, point.z * 4.f, seed ^ 0x68e31da4u) + 0.32f;
247 return std::min({drainage, gravity, surfaceAccess});
248}
249
250CaveWetnessRefinement refineCaveWetnessBoundary(MeshBuild& mesh, const std::vector<CaveHydrologyPoint>& drainageSpine,
251 float fallbackRadius, uint32_t seed, bool splitBoundary) {
252 MeshBuild refined;
253 refined.reserve(mesh.getVertexCount() * 2, mesh.getIndexCount() * 2);
254 refined.setActiveGroup("caveWalls");
255 refined.setActiveGroup("speleothems");
256 refined.setActiveGroup("wetWalls");
257 for (int group = 0; group < mesh.getGroupCount(); ++group) {
258 const std::string name = mesh.getGroupName(group);
259 if (name != "caveWalls" && name != "wetWalls" && name != "speleothems") refined.setActiveGroup(name);
260 }
262 for (int triangleIndex = 0; triangleIndex < mesh.getIndexCount() / 3; ++triangleIndex) {
263 WetVertex triangle[3];
264 for (int corner = 0; corner < 3; ++corner) {
265 const int vertex = mesh.getIndex(triangleIndex * 3 + corner);
266 const CaveHydrologyVec3 point{mesh.getPositionX(vertex) * 2.f, mesh.getPositionY(vertex) * 2.f,
267 mesh.getPositionZ(vertex) * 2.f};
268 triangle[corner] = {mesh.getPositionX(vertex),
269 mesh.getPositionY(vertex),
270 mesh.getPositionZ(vertex),
271 mesh.getNormalX(vertex),
272 mesh.getNormalY(vertex),
273 mesh.getNormalZ(vertex),
274 mesh.getUvU(vertex),
275 mesh.getUvV(vertex),
276 caveWetnessField(point, drainageSpine, fallbackRadius, seed)};
277 }
278 const std::string sourceGroup = mesh.getGroupName(mesh.getTriangleGroup(triangleIndex));
279 if (sourceGroup != "caveWalls" && sourceGroup != "wetWalls") {
280 emitPolygon(refined, {triangle[0], triangle[1], triangle[2]}, sourceGroup);
281 continue;
282 }
283 const bool anyWet = triangle[0].wetness >= 0.f || triangle[1].wetness >= 0.f || triangle[2].wetness >= 0.f;
284 const bool anyDry = triangle[0].wetness < 0.f || triangle[1].wetness < 0.f || triangle[2].wetness < 0.f;
285 if (!splitBoundary || !anyWet || !anyDry) {
286 const CaveHydrologyVec3 center{(triangle[0].px + triangle[1].px + triangle[2].px) * (2.f / 3.f),
287 (triangle[0].py + triangle[1].py + triangle[2].py) * (2.f / 3.f),
288 (triangle[0].pz + triangle[1].pz + triangle[2].pz) * (2.f / 3.f)};
289 const bool wet = caveWetnessField(center, drainageSpine, fallbackRadius, seed) > 0.f;
290 emitPolygon(refined, {triangle[0], triangle[1], triangle[2]}, wet ? "wetWalls" : "caveWalls");
291 continue;
292 }
293 ++result.boundaryTriangles;
294 const std::vector<WetVertex> wet = clip(triangle, true);
295 const std::vector<WetVertex> dry = clip(triangle, false);
296 const int emitted = int(wet.size() >= 3 ? wet.size() - 2 : 0) + int(dry.size() >= 3 ? dry.size() - 2 : 0);
297 result.addedTriangles += emitted - 1;
298 emitPolygon(refined, wet, "wetWalls");
299 emitPolygon(refined, dry, "caveWalls");
300 }
301 mesh = std::move(refined);
302 return result;
303}
304
305} // namespace eve::procgen
double z
double y
double x
Duration start
Vec3 relative
Definition AnimSmr.cpp:164
std::string output
float wetness
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
int triangle
Definition FluidSdf.cpp:554
float strength
ScriptForceVector gravity
float density
glm::vec4 clip
float u
Definition Grass.cpp:233
float v
int h
std::vector< Colorf > px
float length
size_t offset
std::string to
std::string from
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanMeshSettings mesh
glm::dvec2 center
glm::dvec3 dx
glm::dvec3 dz
Object::Ptr value
std::string hash
float t
std::string_view source
size_t end
double current
float dy
Definition Shadow.cpp:151
AbilityActivationGroup group
int iterations
Definition TreeMesh.cpp:448
uint32_t seed
Definition TreeMesh.cpp:276
glm::vec3 point
int neighbor
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Definition MeshBuild.h:20
void reserve(int vertexCount, int indexCount)
Reserve.
Definition MeshBuild.cpp:22
int setActiveGroup(const std::string &name)
Select/create the named group assigned to subsequently added triangles.
Definition MeshBuild.cpp:55
Vec3 interpolate(Vec3 start, Vec3 end, float amount) noexcept
Interpolate.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
constexpr HexVec3 lerp(HexVec3 a, HexVec3 b, float t) noexcept
Linear interpolation between two positions.
Definition HexMetrics.h:51
float latticeNoise(float x, float y, float z, uint32_t seed)
double sample(const Heightmap &map, double u, double v)
Sample.
CaveSurfaceReactivityResult evolveCaveSurfaceByReactivity(std::vector< float > &density, const std::vector< float > &rateField, int nx, int ny, int nz, float strength, int iterations)
Retreat rough, highly reactive surface sites using rotation-invariant normal dispersion.
CaveWaterTableSample sampleCaveWaterTableCorrosion(const CaveWaterTableInput &input)
Sample laterally continuous corrosion belts left by one or more water-table stages.
CaveWetnessRefinement refineCaveWetnessBoundary(MeshBuild &mesh, const std::vector< CaveHydrologyPoint > &drainageSpine, float fallbackRadius, uint32_t seed, bool splitBoundary)
Refine cave wetness boundary.
float caveWetnessField(CaveHydrologyVec3 point, const std::vector< CaveHydrologyPoint > &drainageSpine, float fallbackRadius, uint32_t seed)
Cave wetness field.
CaveHydrologyVec3 public API.
Diagnostics from geometry-controlled cave-surface dissolution.
Inputs for a staged epiphreatic water-table corrosion belt.
Local staged water-table corrosion and the dominant historical level.
CaveWetnessRefinement public API.
Definition CaveWetness.h:13