载入中...
搜索中...
未找到
RoadFacilityPrefab.cpp
浏览该文件的文档.
3
4#include <algorithm>
5#include <array>
6#include <cmath>
7#include <map>
8#include <utility>
9
11namespace {
12Result<void> invalidPrefab(std::string message) {
13 return bakeFail<void>(DiagnosticCode::InvalidArgument, std::move(message), "facility.prefab");
14}
15RoadPrefabVertex mix(const RoadPrefabVertex& a, const RoadPrefabVertex& b, float t) {
16 return {std::lerp(a.x, b.x, t), std::lerp(a.y, b.y, t), std::lerp(a.z, b.z, t), std::lerp(a.nx, b.nx, t),
17 std::lerp(a.ny, b.ny, t), std::lerp(a.nz, b.nz, t), std::lerp(a.u, b.u, t), std::lerp(a.v, b.v, t)};
18}
19std::vector<RoadPrefabVertex> clip(const std::vector<RoadPrefabVertex>& polygon, float plane, bool above) {
20 std::vector<RoadPrefabVertex> out;
21 if (polygon.empty()) return out;
22 auto previous = polygon.back();
23 bool wasInside = above ? previous.z >= plane : previous.z <= plane;
24 for (const auto& current : polygon) {
25 const bool inside = above ? current.z >= plane : current.z <= plane;
26 if (inside != wasInside) out.push_back(mix(previous, current, (plane - previous.z) / (current.z - previous.z)));
27 if (inside) out.push_back(current);
29 wasInside = inside;
30 }
31 return out;
32}
33V3 position(const SplineFrameSample& a, const SplineFrameSample& b, const RoadPrefabVertex& v, float t) {
34 const V3 side =
35 normalize(V3{std::lerp(a.sideX, b.sideX, t), std::lerp(a.sideY, b.sideY, t), std::lerp(a.sideZ, b.sideZ, t)});
36 const V3 up = normalize(V3{std::lerp(a.upX, b.upX, t), std::lerp(a.upY, b.upY, t), std::lerp(a.upZ, b.upZ, t)});
37 return V3{std::lerp(a.sample.x, b.sample.x, t), std::lerp(a.sample.y, b.sample.y, t),
38 std::lerp(a.sample.z, b.sample.z, t)} +
39 side * v.x + up * v.y;
40}
41} // namespace
43 if (!std::isfinite(p.repeatSourceLength) || p.repeatSourceLength < 0.f || p.repeatSourceLength > 10000000.f)
44 return invalidPrefab("invalid prefab repetition span");
45 if (!std::isfinite(p.length) || p.length <= 1e-4f || p.length > 10000.f || !std::isfinite(p.sourceStart) ||
46 !std::isfinite(p.sourceEnd) || p.sourceStart < 0.f || p.sourceEnd > 1.f || p.sourceStart >= p.sourceEnd)
47 return invalidPrefab("invalid prefab source mapping");
48 if (p.vertices.empty()) {
49 if (!p.triangles.empty() || !p.assetId.empty() || !p.startMesh.vertices.empty() ||
50 !p.endMesh.vertices.empty() || !p.startMesh.triangles.empty() || !p.endMesh.triangles.empty() ||
51 !p.startMesh.assetId.empty() || !p.endMesh.assetId.empty() || p.middleCopies != 1 ||
52 p.weldCompatibleVertices || p.automaticSpacing || !p.averageSpacing || p.reverseRepeatSequence ||
53 p.repeatSourceLength != 0.f)
54 return invalidPrefab("empty prefab carries mesh or identity");
55 return Result<void>::success();
56 }
57 if (p.middleCopies < 1 || p.middleCopies > 4096 || p.assetId.empty() || p.assetId.size() > 256u ||
58 p.vertices.size() > 65536u || p.triangles.empty() || p.triangles.size() > 131072u || !std::isfinite(p.length) ||
59 p.length <= 1e-4f || p.length > 10000.f || !std::isfinite(p.sourceStart) || !std::isfinite(p.sourceEnd) ||
60 p.sourceStart < 0.f || p.sourceEnd > 1.f || p.sourceEnd - p.sourceStart <= 1e-5f)
61 return invalidPrefab("invalid prefab identity, budget or source interval");
62 for (const auto& v : p.vertices) {
63 if (!std::isfinite(v.x) || !std::isfinite(v.y) || !std::isfinite(v.z) || std::fabs(v.x) > 10000.f ||
64 std::fabs(v.y) > 10000.f || v.z < 0.f || v.z > p.length || !std::isfinite(v.nx) || !std::isfinite(v.ny) ||
65 !std::isfinite(v.nz) || std::fabs(length(V3{v.nx, v.ny, v.nz}) - 1.f) > 1e-3f || !std::isfinite(v.u) ||
66 !std::isfinite(v.v))
67 return invalidPrefab("invalid prefab vertex");
68 }
69 for (const auto& t : p.triangles) {
70 if (t.a >= p.vertices.size() || t.b >= p.vertices.size() || t.c >= p.vertices.size() ||
71 t.material > RoadMaterial::TunnelPortalAsphalt || t.smoothingGroup > 65535u)
72 return invalidPrefab("invalid prefab triangle");
73 const auto &a = p.vertices[t.a], &b = p.vertices[t.b], &c = p.vertices[t.c];
74 const V3 normal = cross(V3{b.x - a.x, b.y - a.y, b.z - a.z}, V3{c.x - a.x, c.y - a.y, c.z - a.z});
75 if (length(normal) < 1e-7f ||
76 dot(normal, V3{a.nx + b.nx + c.nx, a.ny + b.ny + c.ny, a.nz + b.nz + c.nz}) <= 0.f)
77 return invalidPrefab("degenerate or reversed prefab triangle");
78 }
79 for (const auto* part : {&p.startMesh, &p.endMesh}) {
81 source.assetId = part->assetId;
82 source.length = part->length;
83 source.vertices = part->vertices;
84 source.triangles = part->triangles;
85 // Default empty segments stop recursion; only nonempty segment meshes need validation.
86 if (!part->vertices.empty() || !part->triangles.empty() || !part->assetId.empty()) {
88 if (!valid.ok()) return valid;
89 }
90 }
91 return Result<void>::success();
92}
94 const std::vector<SplineFrameSample>& frames, float sourceLow, float sourceHigh,
95 float fullSourceLength, std::size_t budget) {
97 if (!valid.ok()) return valid;
98 if (frames.size() < 2 || sourceHigh - sourceLow <= 1e-5f) return invalidPrefab("degenerate deformation interval");
99 int copies = prefab.middleCopies;
100 float middleLength = prefab.length, remainder = prefab.length;
101 if (prefab.automaticSpacing) {
102 const float span = prefab.repeatSourceLength > 0.f ? prefab.repeatSourceLength : fullSourceLength;
103 const float caps = (prefab.startMesh.vertices.empty() ? 0.f : prefab.startMesh.length) +
104 (prefab.endMesh.vertices.empty() ? 0.f : prefab.endMesh.length);
105 if (!std::isfinite(span) || span <= caps + 1e-5f)
106 return invalidPrefab("automatic spacing requires arc room for start, middle and end");
107 const double ratio = static_cast<double>(span - caps) / prefab.length;
108 const double count = std::max(1.0, prefab.averageSpacing ? std::round(ratio) : std::ceil(ratio));
109 if (count > 4096.0) return invalidPrefab("automatic spacing exceeds 4096 middle segments");
110 copies = static_cast<int>(count);
111 if (prefab.averageSpacing) middleLength = (span - caps) / static_cast<float>(copies);
112 remainder = (span - caps) - static_cast<float>(copies - 1) * middleLength;
113 }
114 const auto triangleCount = prefab.triangles.size() * static_cast<std::size_t>(copies) +
115 prefab.startMesh.triangles.size() + prefab.endMesh.triangles.size();
116 if (triangleCount > (budget / 12u) / (frames.size() - 1u))
117 return bakeFail<void>(DiagnosticCode::PreconditionViolation, "prefab tessellation exceeds work budget",
118 "prefab");
119 const float begin = frames.front().sample.normalizedDistance, end = frames.back().sample.normalizedDistance;
120 struct Part {
121 const std::vector<RoadPrefabVertex>* vertices;
122 const std::vector<RoadPrefabTriangle>* triangles;
123 float offset, length, sourceLength, sourceOffset;
124 };
125 std::vector<Part> parts;
126 float total = 0.f;
127 if (!prefab.startMesh.vertices.empty()) {
128 parts.push_back({&prefab.startMesh.vertices, &prefab.startMesh.triangles, total, prefab.startMesh.length,
129 prefab.startMesh.length, 0.f});
130 total += prefab.startMesh.length;
131 }
132 for (int i = 0; i < copies; ++i) {
133 const bool partial = prefab.automaticSpacing && !prefab.averageSpacing &&
134 (prefab.reverseRepeatSequence ? i == 0 : i == copies - 1);
135 const float span = partial ? remainder : middleLength;
136 parts.push_back({&prefab.vertices, &prefab.triangles, total, span,
137 prefab.automaticSpacing && prefab.averageSpacing ? prefab.length : span,
138 partial && prefab.reverseRepeatSequence ? prefab.length - remainder : 0.f});
139 total += span;
140 }
141 if (!prefab.endMesh.vertices.empty()) {
142 parts.push_back({&prefab.endMesh.vertices, &prefab.endMesh.triangles, total, prefab.endMesh.length,
143 prefab.endMesh.length, 0.f});
144 total += prefab.endMesh.length;
145 }
146 using SmoothKey = std::array<float, 4>;
147 struct Smooth {
148 V3 sum{};
149 std::vector<std::uint32_t> vertices;
150 };
151 std::map<SmoothKey, Smooth> smoothing;
152 std::map<std::array<float, 9>, std::uint32_t> welded;
153 for (std::size_t slab = 1; slab < frames.size(); ++slab) {
154 const auto &a = frames[slab - 1], &b = frames[slab];
155 if (length(V3{b.sample.x - a.sample.x, b.sample.y - a.sample.y, b.sample.z - a.sample.z}) <= 1e-5f) continue;
156 const float low =
157 std::lerp(sourceLow, sourceHigh, (a.sample.normalizedDistance - begin) / (end - begin)) * total;
158 const float high =
159 std::lerp(sourceLow, sourceHigh, (b.sample.normalizedDistance - begin) / (end - begin)) * total;
160 if (high - low <= 1e-6f) continue;
161 for (const auto& part : parts) {
162 if (part.offset + part.length < low || part.offset > high) continue;
163 for (const auto& triangle : *part.triangles) {
164 auto mapped = [&](std::uint32_t index) {
165 auto v = (*part.vertices)[index];
166 const float scale = part.length / part.sourceLength;
167 v.z = (v.z - part.sourceOffset) * scale;
168 const auto normal = normalize(V3{v.nx, v.ny, v.nz / scale});
169 v.nx = normal.x;
170 v.ny = normal.y;
171 v.nz = normal.z;
172 return v;
173 };
174 auto polygon = clip(clip({mapped(triangle.a), mapped(triangle.b), mapped(triangle.c)},
175 std::max(0.f, low - part.offset), true),
176 std::min(part.length, high - part.offset), false);
177 if (polygon.size() < 3) continue;
178 for (std::size_t i = 2; i < polygon.size(); ++i) {
179 const RoadPrefabVertex vertices[]{polygon[0], polygon[i - 1], polygon[i]};
180 if (static_cast<std::size_t>(mesh.getVertexCount()) +
181 static_cast<std::size_t>(mesh.getIndexCount()) + 6u >
182 budget)
183 return bakeFail<void>(DiagnosticCode::PreconditionViolation, "prefab exceeds output budget",
184 "mesh");
185 V3 positions[3], normals[3];
186 for (int k = 0; k < 3; ++k) {
187 const auto& v = vertices[k];
188 const float t = std::clamp((v.z + part.offset - low) / (high - low), 0.f, 1.f);
189 positions[k] = position(a, b, v, t);
190 const V3 side = normalize(V3{std::lerp(a.sideX, b.sideX, t), std::lerp(a.sideY, b.sideY, t),
191 std::lerp(a.sideZ, b.sideZ, t)});
192 const V3 up = normalize(
193 V3{std::lerp(a.upX, b.upX, t), std::lerp(a.upY, b.upY, t), std::lerp(a.upZ, b.upZ, t)});
194 const float t0 = std::max(0.f, t - .001f), t1 = std::min(1.f, t + .001f);
195 const V3 longitudinal =
196 (position(a, b, v, t1) - position(a, b, v, t0)) * (1.f / ((t1 - t0) * (high - low)));
197 const float determinant = dot(side, cross(up, longitudinal));
198 if (!std::isfinite(determinant) || determinant <= 1e-6f)
199 return invalidPrefab("prefab deformation folds or collapses; slab=" + std::to_string(slab) +
200 " determinant=" + std::to_string(determinant) +
201 " t=" + std::to_string(t) + " x0=" + std::to_string(a.sample.x) +
202 " x1=" + std::to_string(b.sample.x));
203 normals[k] = normalize((cross(up, longitudinal) * v.nx + cross(longitudinal, side) * v.ny +
204 cross(side, up) * v.nz) *
205 (1.f / determinant));
206 }
207 const V3 face = cross(positions[1] - positions[0], positions[2] - positions[0]);
208 if (length(face) < 1e-7f) continue;
209 mesh.setActiveGroup(roadMaterialGroup(triangle.material));
210 std::uint32_t indices[3]{};
211 for (int k = 0; k < 3; ++k) {
212 std::array<float, 9> key{
213 positions[k].x, positions[k].y, positions[k].z,
214 normals[k].x, normals[k].y, normals[k].z,
215 vertices[k].u, vertices[k].v, static_cast<float>(triangle.smoothingGroup)};
216 for (float& v : key)
217 v = static_cast<float>(std::round(static_cast<double>(v) * 100000.0) / 100000.0);
218 const auto found = welded.find(key);
219 if (triangle.smoothingGroup != 0u) {
220 auto& smooth = smoothing[SmoothKey{key[0], key[1], key[2], key[8]}];
221 smooth.sum = smooth.sum + face;
222 smooth.vertices.push_back(prefab.weldCompatibleVertices && found != welded.end()
223 ? found->second
224 : static_cast<std::uint32_t>(mesh.getVertexCount()));
225 }
226 if (prefab.weldCompatibleVertices && found != welded.end()) {
227 indices[k] = found->second;
228 continue;
229 }
230 indices[k] = static_cast<std::uint32_t>(mesh.getVertexCount());
231 mesh.addVertex(positions[k].x, positions[k].y, positions[k].z, normals[k].x, normals[k].y,
232 normals[k].z, vertices[k].u, vertices[k].v);
233 if (prefab.weldCompatibleVertices) welded.emplace(key, indices[k]);
234 }
235 mesh.addTriangle(indices[0], indices[1], indices[2]);
236 }
237 }
238 }
239 }
240 for (const auto& [key, smooth] : smoothing) {
241 (void)key;
242 if (length(smooth.sum) <= 1e-7f) return invalidPrefab("smoothing group has cancelling face normals");
243 const auto normal = normalize(smooth.sum);
244 for (auto index : smooth.vertices) {
245 mesh.normals()[index * 3u] = normal.x;
246 mesh.normals()[index * 3u + 1u] = normal.y;
247 mesh.normals()[index * 3u + 2u] = normal.z;
248 }
249 }
250 return Result<void>::success();
251}
252} // namespace eve::procgen::road::detail
double z
double y
double x
std::vector< eve::artifact::PartView > parts
std::string prefab
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
int triangle
Definition FluidSdf.cpp:554
std::string message
glm::vec4 clip
float u
Definition Grass.cpp:233
std::vector< std::uint32_t > indices
std::vector< float > normals
std::vector< float > positions
float v
HexVec3 up
std::int32_t c
float ratio
float length
size_t offset
std::array< float, 3 > position
std::array< float, 3 > scale
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< TriangleRef > triangles
Texture * normal
OceanMeshSettings mesh
std::shared_ptr< const OceanSprayFrame > previous
float t
bool found
ScriptStructure out
std::string_view source
size_t begin
size_t end
double current
int count
std::array< double, 2 > vertices[3]
int caps
Definition TreeMesh.cpp:164
uint32_t index
std::vector< char > inside
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Definition MeshBuild.h:20
Result< void > bakeFacilityPrefab(MeshBuild &mesh, const RoadFacilityPrefab &prefab, const std::vector< SplineFrameSample > &frames, float sourceLow, float sourceHigh, float fullSourceLength, std::size_t budget)
Clip source triangles into frame slabs and deform their positions and inverse-transpose normals.
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29
Result< void > validateFacilityPrefab(const RoadFacilityPrefab &prefab)
Validate finite source mesh topology and bounded source ranges.
float dot(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:28
V3 normalize(V3 a)
Module-private road bake implementation helper.
Definition RoadBake.cpp:31
const char * roadMaterialGroup(RoadMaterial material) noexcept
Map a material tag to the MeshBuild group name used by the baker. @ownership borrowed — returns a poi...
@ TunnelPortalAsphalt
Driving surface inside an authored tunnel portal footprint.
Owned prefab mesh; local Z in [0,length] deforms along the facility arc. Source range preserves cut g...
Definition RoadTypes.h:94
Owned source vertex in prefab-local (side, up, forward) axes, with normal and UV.
Definition RoadTypes.h:72