载入中...
搜索中...
未找到
VolumeFluidFoamSurface.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cmath>
3#include <exception>
4#include <glm/glm.hpp>
5#include <glm/gtc/matrix_transform.hpp>
6#include <glm/gtc/quaternion.hpp>
7#include <limits>
13#include "graphics/Graphics.h"
14#include "graphics/Mesh.h"
16
17// VolumeFluidFoamSurface.cpp
18namespace eve::fluids {
22 DiagnosticCode::InvalidArgument, "Foam downsample must be in [1,4]", "fluids.surface.configureFoam"));
23 foamEnabled_ = enabled;
24 foamDownsample_ = downsample;
25 return Result<void>::success();
26}
27
29 float fadeSeconds) {
30 const auto fail = [](const char* message) {
33 };
34 if (!std::isfinite(radius) || radius <= 0.f || radius > 1.f || !std::isfinite(opacity) || opacity < 0.f ||
35 opacity > 1.f || !std::isfinite(fadeSeconds) || fadeSeconds <= 0.f || fadeSeconds > 86400.f)
36 return fail("Invalid diffuse rendering settings");
37 if (!foamEnabled_ || pool.particleCount() == 0 || opacity == 0.f) return Result<void>::success();
38 const int width = params_.width, height = params_.height;
39 if (width <= 0 || height <= 0 || depth_.size() != size_t(width) * size_t(height) ||
40 color_.size() != depth_.size() * 4)
41 return fail("Invalid reconstructed frame size");
42 const int renderWidth = std::max(1, (width + foamDownsample_ - 1) / foamDownsample_);
43 const int renderHeight = std::max(1, (height + foamDownsample_ - 1) / foamDownsample_);
44 const float tangent = std::tan(glm::radians(params_.fovYDeg) * .5f);
45 if (!std::isfinite(tangent) || tangent <= 0.f) return fail("Invalid diffuse camera projection");
46 const auto view = glm::lookAtRH(params_.eye, params_.target, params_.up);
47 pool.copyRenderData(diffuseParticles_);
48 diffuseSplats_.clear();
49 diffuseSplats_.reserve(diffuseParticles_.size());
50 uint64_t visits = 0;
51 for (const auto p : diffuseParticles_) {
52 const auto v = view * glm::vec4(glm::vec3(p), 1.f);
53 if (!std::isfinite(v.x) || !std::isfinite(v.y) || !std::isfinite(v.z))
54 return fail("Invalid diffuse camera transform");
55 DiffuseSplat s;
56 s.z = -v.z;
57 if (s.z <= params_.nearZ || s.z >= params_.farZ) continue;
58 s.r = std::max(1.f, radius * float(renderHeight) / (2.f * s.z * tangent));
59 s.x = (.5f + .5f * v.x / (s.z * tangent * float(renderWidth) / float(renderHeight))) * float(renderWidth);
60 s.y = (.5f - .5f * v.y / (s.z * tangent)) * float(renderHeight);
61 if (!std::isfinite(s.r) || !std::isfinite(s.x) || !std::isfinite(s.y))
62 return fail("Invalid diffuse projection");
63 if (s.x + s.r < 0.f || s.y + s.r < 0.f || s.x - s.r >= float(renderWidth) || s.y - s.r >= float(renderHeight))
64 continue;
65 // Clamp in floating point before converting extreme off-screen coordinates.
66 s.x0 = int(std::floor(std::clamp(s.x - s.r, 0.f, float(renderWidth - 1))));
67 s.x1 = int(std::ceil(std::clamp(s.x + s.r, 0.f, float(renderWidth - 1))));
68 s.y0 = int(std::floor(std::clamp(s.y - s.r, 0.f, float(renderHeight - 1))));
69 s.y1 = int(std::ceil(std::clamp(s.y + s.r, 0.f, float(renderHeight - 1))));
70 s.alpha = opacity * std::min(1.f, p.w / fadeSeconds);
71 visits += uint64_t(s.x1 - s.x0 + 1) * uint64_t(s.y1 - s.y0 + 1);
72 if (visits > 4000000) return fail("Diffuse rendering exceeds 4M pixel visits");
73 diffuseSplats_.push_back(s);
74 }
75 if (foamDownsample_ > 1) foamCoverageScratch_.assign(size_t(renderWidth) * size_t(renderHeight), 0.f);
76 for (const auto& s : diffuseSplats_) {
77 for (int y = s.y0; y <= s.y1; ++y)
78 for (int x = s.x0; x <= s.x1; ++x) {
79 const float dx = (float(x) + .5f - s.x) / s.r, dy = (float(y) + .5f - s.y) / s.r;
80 const float q = 1.f - dx * dx - dy * dy;
81 if (q <= 0.f) continue;
82 const size_t reducedAt = size_t(y) * size_t(renderWidth) + size_t(x);
83 const int fullX = std::min(width - 1, x * width / renderWidth);
84 const int fullY = std::min(height - 1, y * height / renderHeight);
85 const size_t at = size_t(fullY) * size_t(width) + size_t(fullX);
86 const float front = s.z - radius * std::sqrt(q);
87 const float visibility = std::clamp(1.f + (depth_[at] - front) / radius, 0.f, 1.f);
88 const float alpha = s.alpha * q * q * visibility;
89 if (alpha <= 0.f) continue;
90 if (foamDownsample_ > 1) {
91 foamCoverageScratch_[reducedAt] = alpha + foamCoverageScratch_[reducedAt] * (1.f - alpha);
92 continue;
93 }
94 const float oldAlpha = float(color_[at * 4 + 3]) / 255.f;
95 const float retained = oldAlpha * (1.f - alpha), combined = alpha + retained;
96 for (size_t c = 0; c < 3; ++c) {
97 const float color = (alpha + float(color_[at * 4 + c]) / 255.f * retained) / combined;
98 color_[at * 4 + c] = uint8_t(std::clamp(color, 0.f, 1.f) * 255.f + .5f);
99 }
100 color_[at * 4 + 3] = uint8_t(std::clamp(combined, 0.f, 1.f) * 255.f + .5f);
101 }
102 }
103 if (foamDownsample_ > 1) {
104 for (int y = 0; y < height; ++y)
105 for (int x = 0; x < width; ++x) {
106 const int sx = std::min(renderWidth - 1, x * renderWidth / width);
107 const int sy = std::min(renderHeight - 1, y * renderHeight / height);
108 const float alpha = foamCoverageScratch_[size_t(sy) * size_t(renderWidth) + size_t(sx)];
109 if (alpha <= 0.f) continue;
110 const size_t at = size_t(y) * size_t(width) + size_t(x);
111 const float oldAlpha = float(color_[at * 4u + 3u]) / 255.f;
112 const float retained = oldAlpha * (1.f - alpha), combined = alpha + retained;
113 for (size_t c = 0; c < 3; ++c) {
114 const float value = (alpha + float(color_[at * 4u + c]) / 255.f * retained) / combined;
115 color_[at * 4u + c] = uint8_t(std::clamp(value, 0.f, 1.f) * 255.f + .5f);
116 }
117 color_[at * 4u + 3u] = uint8_t(std::clamp(combined, 0.f, 1.f) * 255.f + .5f);
118 }
119 }
120 residentColorCurrent_ = false;
121 return Result<void>::success();
122}
123} // namespace eve::fluids
124
125// VolumeFluidMeshEmitter.cpp
126namespace eve::fluids {
127namespace {
128bool finiteMeshVector(glm::vec3 p) { return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z); }
129bool intersects(glm::dvec3 a, glm::dvec3 b, glm::dvec3 c, glm::dvec3 center, double half) {
130 a -= center;
131 b -= center;
132 c -= center;
133 const glm::dvec3 edges[] = {b - a, c - b, a - c};
134 const glm::dvec3 basis[] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
135 const auto separated = [&](glm::dvec3 axis) {
136 const double radius = half * (std::abs(axis.x) + std::abs(axis.y) + std::abs(axis.z));
137 const double pa = glm::dot(a, axis), pb = glm::dot(b, axis), pc = glm::dot(c, axis);
138 return std::min({pa, pb, pc}) > radius + 1e-12 || std::max({pa, pb, pc}) < -radius - 1e-12;
139 };
140 for (const auto axis : basis)
142 if (separated(glm::cross(edges[0], edges[1]))) return false;
143 for (const auto edge : edges)
146 return true;
147}
148} // namespace
150 std::span<const uint32_t> indices,
151 glm::vec3 scale, float spacing) {
153 const auto fail = [](const char* text) {
154 return Output::failure(
155 Diagnostic::error(DiagnosticCode::InvalidArgument, text, "fluids.volume.meshDistribution"));
156 };
157 if (vertices.empty() || vertices.size() > 1000000 || indices.empty() || indices.size() % 3 != 0 ||
158 indices.size() / 3 > 65536 || !finiteMeshVector(scale) || scale.x == 0 || scale.y == 0 || scale.z == 0 ||
159 !std::isfinite(spacing) || spacing < .001f || spacing > 10000.f)
160 return fail("Invalid mesh dimensions or spacing");
161 std::vector<glm::dvec3> points;
162 points.reserve(vertices.size());
163 glm::dvec3 minimum(std::numeric_limits<double>::max()), maximum(-std::numeric_limits<double>::max());
164 for (const auto vertex : vertices) {
165 if (!finiteMeshVector(vertex)) return fail("Nonfinite mesh vertex");
166 const auto p = glm::dvec3(vertex) * glm::dvec3(scale);
167 if (glm::any(glm::greaterThan(glm::abs(p), glm::dvec3(10000.0))))
168 return fail("Scaled mesh exceeds world-size limit");
169 minimum = glm::min(minimum, p);
170 maximum = glm::max(maximum, p);
171 points.push_back(p);
172 }
173 for (const auto index : indices)
174 if (index >= points.size()) return fail("Mesh index out of range");
175 const auto extent = maximum - minimum;
176 const double size = std::max(double(spacing), std::max({extent.x, extent.y, extent.z}) / 32.0);
177 const glm::ivec3 dimensions = glm::ivec3(glm::ceil(extent / size)) + glm::ivec3(4);
178 const auto origin = minimum - glm::dvec3(1.5 * size);
179 const auto index = [&](glm::ivec3 p) {
180 return size_t(p.x) + size_t(dimensions.x) * (size_t(p.y) + size_t(dimensions.y) * size_t(p.z));
181 };
182 std::vector<uint8_t> cells(size_t(dimensions.x) * size_t(dimensions.y) * size_t(dimensions.z), 0);
183 uint64_t work = 0;
184 for (size_t t = 0; t < indices.size(); t += 3) {
185 const auto a = points[indices[t]], b = points[indices[t + 1]], c = points[indices[t + 2]];
186 if (glm::length(glm::cross(b - a, c - a)) < 1e-12) return fail("Degenerate mesh triangle");
187 const auto lo = glm::ivec3(glm::floor((glm::min(a, glm::min(b, c)) - origin) / size));
188 const auto hi = glm::ivec3(glm::floor((glm::max(a, glm::max(b, c)) - origin) / size));
189 for (int z = lo.z; z <= hi.z; ++z)
190 for (int y = lo.y; y <= hi.y; ++y)
191 for (int x = lo.x; x <= hi.x; ++x) {
192 if (++work > 4000000) return fail("Mesh voxelization exceeds 4M intersection checks");
193 const glm::ivec3 p(x, y, z);
194 if (cells[index(p)] == 1) continue;
195 const auto center = origin + (glm::dvec3(p) + .5) * size;
196 if (intersects(a, b, c, center, size * .5)) cells[index(p)] = 1;
197 }
198 }
199 std::vector<glm::ivec3> queue;
200 queue.reserve(cells.size());
201 queue.emplace_back(0);
202 cells[0] = 2;
203 const glm::ivec3 directions[] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
204 for (size_t i = 0; i < queue.size(); ++i)
205 for (const auto direction : directions) {
206 const auto p = queue[i] + direction;
207 if (glm::any(glm::lessThan(p, glm::ivec3(0))) || glm::any(glm::greaterThanEqual(p, dimensions))) continue;
208 if (cells[index(p)] == 0) {
209 cells[index(p)] = 2;
210 queue.push_back(p);
211 }
212 }
213 std::vector<VolumeFluidDistributionPoint> result;
214 for (int z = 0; z < dimensions.z; ++z)
215 for (int y = 0; y < dimensions.y; ++y)
216 for (int x = 0; x < dimensions.x; ++x) {
217 const glm::ivec3 p(x, y, z);
218 if (cells[index(p)] == 2) continue;
219 if (result.size() == 4096) return fail("Mesh distribution exceeds 4096 points; increase spacing");
220 result.push_back({glm::vec3(origin + (glm::dvec3(p) + .5) * size), glm::vec4(1.f)});
221 }
222 return Output::success(std::move(result));
223}
224} // namespace eve::fluids
225
226// VolumeFluidShadowCaster.cpp
227namespace eve::fluids {
228namespace {
229Status failure(const char* message) {
230 return Status::failure(Diagnostic::error(DiagnosticCode::Failed, message, "fluids.volume.shadowCaster"));
231}
232} // namespace
233
235
238 if (graphics_ && mesh_ && graphics_->releaseMesh(mesh_)) delete mesh_;
239}
240
241Result<void> VolumeFluidShadowCaster::update(const VolumeFluid& fluid, unsigned actorGroup, float radiusScale,
242 float alpha, unsigned maxParticles) {
243 std::vector<VolumeFluidParticleInstance> candidate;
244 candidate.swap(instances_);
245 auto copied = fluid.copyParticleImpostors(actorGroup, radiusScale, glm::vec4(1.f), alpha, maxParticles, candidate);
246 if (!copied) {
247 candidate.swap(instances_);
248 return Result<void>::failure(copied.status());
249 }
250 const size_t count = candidate.size();
251 positions_.resize(count * 18u);
252 normals_.resize(count * 18u);
253 indices_.resize(count * 24u);
254 static constexpr glm::vec3 directions[6] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
255 static constexpr uint32_t faces[24] = {0, 2, 4, 2, 1, 4, 1, 3, 4, 3, 0, 4, 2, 0, 5, 1, 2, 5, 3, 1, 5, 0, 3, 5};
256 for (size_t i = 0; i < count; ++i) {
257 const auto q = glm::quat(candidate[i].orientation.w, candidate[i].orientation.x, candidate[i].orientation.y,
258 candidate[i].orientation.z);
259 for (size_t v = 0; v < 6; ++v) {
260 const glm::vec3 local = directions[v] * candidate[i].scale;
261 const glm::vec3 normal = q * directions[v];
262 const glm::vec3 point = candidate[i].position + q * local;
263 for (size_t c = 0; c < 3; ++c) {
264 const auto component = static_cast<glm::vec3::length_type>(c);
265 positions_[(i * 6 + v) * 3 + c] = point[component];
266 normals_[(i * 6 + v) * 3 + c] = normal[component];
267 }
268 }
269 for (size_t k = 0; k < 24; ++k) indices_[i * 24 + k] = uint32_t(i * 6 + faces[k]);
270 }
271 try {
272 if (count != 0 && !mesh_)
273 mesh_ = graphics_->newMeshFromArrays(positions_.data(), normals_.data(), nullptr, int(count * 6),
274 indices_.data(), int(count * 24));
275 else if (count != 0 && !graphics_->updateMeshVertices(mesh_, positions_.data(), normals_.data(), nullptr,
276 int(count * 6), indices_.data(), int(count * 24)))
277 return Result<void>::failure(failure("Particle shadow mesh update failed"));
278 } catch (const std::exception&) {
279 return Result<void>::failure(failure("Particle shadow mesh creation failed"));
280 }
281 if (mesh_ && drawerToken_ == 0)
283 [this](graphics::Graphics& gfx, const glm::mat4& lightVP, const auto&) {
284 if (particleCount_ != 0) gfx.drawMeshShadow(mesh_, lightVP);
285 });
286 instances_.swap(candidate);
287 particleCount_ = unsigned(count);
288 return Result<void>::success();
289}
290
291} // namespace eve::fluids
292
293// VolumeFluidSimplexQuery.cpp
295namespace {
296bool finite(glm::vec3 v) { return std::isfinite(v.x) && std::isfinite(v.y) && std::isfinite(v.z); }
297bool finite(glm::vec4 v) { return finite(glm::vec3(v)) && std::isfinite(v.w); }
298bool inRange(float v, float lo, float hi) { return std::isfinite(v) && v >= lo && v <= hi; }
299bool validFilter(unsigned filter) { return (filter & 0xffffu) != 0 && (filter >> 16u) != 0; }
300bool filtersMatch(unsigned a, unsigned b) {
301 return ((a & 0xffffu) & (b >> 16u)) != 0 && ((b & 0xffffu) & (a >> 16u)) != 0;
302}
303struct SimplexPoint {
304 glm::vec3 point{0.f};
305 glm::vec4 bary{1.f, 0.f, 0.f, 0.f};
306};
307
308SimplexPoint closestEdge(glm::vec3 a, glm::vec3 b, glm::vec3 p) {
309 const auto edge = b - a;
310 const float denominator = glm::dot(edge, edge);
311 const float t = denominator > 1e-12f ? std::clamp(glm::dot(p - a, edge) / denominator, 0.f, 1.f) : 0.f;
312 return {a + edge * t, {1.f - t, t, 0.f, 0.f}};
313}
314SimplexPoint closestTriangle(glm::vec3 a, glm::vec3 b, glm::vec3 c, glm::vec3 p) {
315 const auto ab = b - a, ac = c - a, ap = p - a;
316 const float d1 = glm::dot(ab, ap), d2 = glm::dot(ac, ap);
317 if (d1 <= 0.f && d2 <= 0.f) return {a, {1, 0, 0, 0}};
318 const auto bp = p - b;
319 const float d3 = glm::dot(ab, bp), d4 = glm::dot(ac, bp);
320 if (d3 >= 0.f && d4 <= d3) return {b, {0, 1, 0, 0}};
321 const float vc = d1 * d4 - d3 * d2;
322 if (vc <= 0.f && d1 >= 0.f && d3 <= 0.f) {
323 const float v = d1 / (d1 - d3);
324 return {a + ab * v, {1 - v, v, 0, 0}};
325 }
326 const auto cp = p - c;
327 const float d5 = glm::dot(ab, cp), d6 = glm::dot(ac, cp);
328 if (d6 >= 0.f && d5 <= d6) return {c, {0, 0, 1, 0}};
329 const float vb = d5 * d2 - d1 * d6;
330 if (vb <= 0.f && d2 >= 0.f && d6 <= 0.f) {
331 const float w = d2 / (d2 - d6);
332 return {a + ac * w, {1 - w, 0, w, 0}};
333 }
334 const float va = d3 * d6 - d5 * d4;
335 if (va <= 0.f && (d4 - d3) >= 0.f && (d5 - d6) >= 0.f) {
336 const float w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
337 return {b + (c - b) * w, {0, 1 - w, w, 0}};
338 }
339 const float sum = va + vb + vc;
340 if (std::abs(sum) <= 1e-12f) {
341 auto first = closestEdge(a, b, p), second = closestEdge(b, c, p), third = closestEdge(c, a, p);
342 const float da = glm::dot(first.point - p, first.point - p), db = glm::dot(second.point - p, second.point - p),
343 dc = glm::dot(third.point - p, third.point - p);
344 if (da <= db && da <= dc) return first;
345 if (db <= dc) return {second.point, {0, second.bary.x, second.bary.y, 0}};
346 return {third.point, {third.bary.y, 0, third.bary.x, 0}};
347 }
348 const float inverse = 1.f / sum, v = vb * inverse, w = vc * inverse;
349 return {a + ab * v + ac * w, {1.f - v - w, v, w, 0}};
350}
351SimplexPoint closestSimplex(const VolumeFluidSimplex& simplex, std::span<const VolumeFluidParticle> particles,
352 glm::vec3 point) {
353 const auto a = particles[simplex.particleIndices[0]].position;
354 if (simplex.size == 1) return {a, {1, 0, 0, 0}};
355 const auto b = particles[simplex.particleIndices[1]].position;
356 if (simplex.size == 2) return closestEdge(a, b, point);
357 return closestTriangle(a, b, particles[simplex.particleIndices[2]].position, point);
358}
359float radiusAlong(const VolumeFluidSimplex& simplex, std::span<const VolumeFluidParticle> particles, glm::vec4 bary,
360 glm::vec3 normal) {
361 float radius = 0.f;
362 for (unsigned i = 0; i < simplex.size; ++i) {
363 const auto& particle = particles[simplex.particleIndices[i]];
364 const auto q =
365 glm::quat(particle.orientation.w, particle.orientation.x, particle.orientation.y, particle.orientation.z);
366 radius += bary[i] / glm::length((glm::conjugate(q) * normal) / particle.radii);
367 }
368 return radius;
369}
370glm::vec3 boxPoint(const VolumeFluidQueryShape& query, glm::vec3 world, glm::vec3& normal) {
371 const auto q = glm::normalize(glm::quat(query.rotation.w, query.rotation.x, query.rotation.y, query.rotation.z));
372 const auto half = query.size * .5f + glm::vec3(query.contactOffset),
373 local = glm::conjugate(q) * (world - query.center);
374 auto projected = glm::clamp(local, -half, half);
375 const auto outside = glm::abs(local) - half;
376 if (glm::all(glm::lessThanEqual(outside, glm::vec3(0.f)))) {
377 const auto gap = half - glm::abs(local);
378 int axis = 0;
379 if (gap.y < gap.x) axis = 1;
380 if (gap.z < gap[axis]) axis = 2;
381 projected[axis] = local[axis] >= 0.f ? half[axis] : -half[axis];
382 }
383 const auto point = query.center + q * projected, delta = world - point;
384 const float length = glm::length(delta);
385 normal = length > 1e-7f ? delta / length : q * glm::vec3(0, 1, 0);
386 return point;
387}
388VolumeFluidSimplex implicitPoint(unsigned index) { return {{index, 0, 0}, 1}; }
389bool selected(const VolumeFluidSimplex& simplex, std::span<const VolumeFluidParticle> particles,
390 const VolumeFluidQueryShape& query) {
391 for (unsigned i = 0; i < simplex.size; ++i) {
392 const auto& p = particles[simplex.particleIndices[i]];
393 if ((query.phaseMask & (1u << unsigned(p.material.phase))) != 0 &&
394 filtersMatch(query.collisionFilter, p.collisionFilter))
395 return true;
396 }
397 return false;
398}
399VolumeFluidSimplexHit evaluate(const VolumeFluidSimplex& simplex, unsigned simplexIndex, unsigned queryIndex,
400 std::span<const VolumeFluidParticle> particles, const VolumeFluidQueryShape& query) {
401 SimplexPoint convex;
402 glm::vec3 queryPoint, normal;
404 convex = closestSimplex(simplex, particles, query.center);
405 const auto delta = convex.point - query.center;
406 const float length = glm::length(delta);
407 normal = length > 1e-7f ? delta / length : glm::vec3(0, 1, 0);
408 queryPoint = query.center + normal * (query.size.x + query.contactOffset);
409 } else if (query.type == VolumeFluidQueryType::Box) {
410 convex.bary = glm::vec4(1.f / float(simplex.size));
411 convex.point = glm::vec3(0.f);
412 for (unsigned i = 0; i < simplex.size; ++i)
413 convex.point += particles[simplex.particleIndices[i]].position * convex.bary[i];
414 for (int iteration = 0; iteration < 8; ++iteration) {
415 queryPoint = boxPoint(query, convex.point, normal);
416 convex = closestSimplex(simplex, particles, queryPoint);
417 }
418 queryPoint = boxPoint(query, convex.point, normal);
419 } else {
420 const auto segment = query.size - query.center;
421 const float length = glm::length(segment);
422 const auto direction = segment / length;
423 float along = .5f * length;
424 queryPoint = query.center + direction * along;
425 for (int iteration = 0; iteration < 8; ++iteration) {
426 convex = closestSimplex(simplex, particles, queryPoint);
427 along = std::clamp(glm::dot(convex.point - query.center, direction), 0.f, length);
428 queryPoint = query.center + direction * along;
429 }
430 const auto delta = convex.point - queryPoint;
431 const float separation = glm::length(delta);
432 normal = separation > 1e-7f ? delta / separation : -direction;
433 queryPoint += normal * query.contactOffset;
434 }
435 const float centerDistance = glm::dot(convex.point - queryPoint, normal);
436 return {convex.bary, queryPoint, normal, centerDistance - radiusAlong(simplex, particles, convex.bary, normal),
437 simplexIndex, queryIndex};
438}
439} // namespace
440
441Result<std::vector<VolumeFluidSimplexHit>> querySimplexes(std::span<const VolumeFluidParticle> particles,
442 std::span<const VolumeFluidSimplex> simplexes,
443 std::span<const VolumeFluidQueryShape> queries,
444 unsigned maxHitsPerQuery) {
446 const auto fail = [](const char* message) {
447 return Output::failure(
448 Diagnostic::error(DiagnosticCode::InvalidArgument, message, "fluids.volume.querySimplexes"));
449 };
450 const size_t simplexCount = simplexes.empty() ? particles.size() : simplexes.size();
451 if (queries.size() > 256 || maxHitsPerQuery == 0 || maxHitsPerQuery > 4096)
452 return fail("Invalid query count or hit limit");
453 if (simplexCount > 65536 || (!queries.empty() && simplexCount > 4000000u / queries.size()))
454 return fail("Simplex query exceeds candidate budget");
455 for (const auto& query : queries) {
456 if (unsigned(query.type) > unsigned(VolumeFluidQueryType::Ray) || !finite(query.center) ||
457 !finite(query.size) || !inRange(query.contactOffset, 0.f, 10000.f) ||
458 !inRange(query.maxDistance, 0.f, 10000.f) || query.phaseMask == 0 || (query.phaseMask & ~0x0fu) != 0 ||
459 !validFilter(query.collisionFilter))
460 return fail("Invalid simplex query");
461 if (query.type == VolumeFluidQueryType::Sphere &&
462 (!inRange(query.size.x, 0.f, 10000.f) || query.size.y != 0 || query.size.z != 0))
463 return fail("Invalid sphere query");
464 if (query.type == VolumeFluidQueryType::Box &&
465 (glm::any(glm::lessThan(query.size, glm::vec3(0))) ||
466 glm::any(glm::greaterThan(query.size, glm::vec3(20000))) || !finite(query.rotation) ||
467 std::abs(glm::dot(query.rotation, query.rotation) - 1.f) > .001f))
468 return fail("Invalid box query");
469 if (query.type == VolumeFluidQueryType::Ray && glm::length(query.size - query.center) <= 1e-7f)
470 return fail("Invalid ray query");
471 }
472 struct Farther {
473 bool operator()(const VolumeFluidSimplexHit& a, const VolumeFluidSimplexHit& b) const {
474 return a.distance != b.distance ? a.distance < b.distance : a.simplexIndex < b.simplexIndex;
475 }
476 };
477 std::vector<VolumeFluidSimplexHit> output;
478 output.reserve(std::min<size_t>(queries.size() * size_t(maxHitsPerQuery), 4000000));
479 std::vector<VolumeFluidSimplexHit> heap;
480 heap.reserve(maxHitsPerQuery);
481 const Farther farther;
482 for (size_t qi = 0; qi < queries.size(); ++qi) {
483 heap.clear();
484 for (size_t si = 0; si < simplexCount; ++si) {
485 const auto implicit = implicitPoint(unsigned(si));
486 const auto& simplex = simplexes.empty() ? implicit : simplexes[si];
487 if (!selected(simplex, particles, queries[qi])) continue;
488 auto hit = evaluate(simplex, unsigned(si), unsigned(qi), particles, queries[qi]);
489 if (hit.distance > queries[qi].maxDistance) continue;
490 if (heap.size() < maxHitsPerQuery) {
491 heap.push_back(hit);
492 std::push_heap(heap.begin(), heap.end(), farther);
493 } else if (hit.distance < heap.front().distance ||
494 (hit.distance == heap.front().distance && si < heap.front().simplexIndex)) {
495 std::pop_heap(heap.begin(), heap.end(), farther);
496 heap.back() = hit;
497 std::push_heap(heap.begin(), heap.end(), farther);
498 }
499 }
500 std::sort_heap(heap.begin(), heap.end(), farther);
501 output.insert(output.end(), heap.begin(), heap.end());
502 }
503 return Output::success(std::move(output));
504}
505} // namespace eve::fluids::detail
double z
double y
double x
float w
Definition AnimClip.cpp:738
std::string selected
std::string output
const std::string & s
float gap
glm::vec4 p[6]
std::string message
float maximum[3]
float minimum[3]
std::array< double, 10 > q
std::uint32_t ab
std::uint32_t ac
std::vector< std::uint32_t > indices
float v
std::int32_t second
std::int32_t c
std::int32_t first
std::uint32_t height
std::uint32_t width
float length
JointPoint2D axis
std::string local
std::array< float, 3 > scale
std::vector< Edge > edges
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
glm::dvec3 origin
glm::dvec2 center
glm::dvec3 dx
OceanSprayView view
size_t directions
bool finite
std::vector< BakedParticleSample > particles
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::shared_ptr< const std::vector< glm::vec2 > > points
bool hit
Object::Ptr value
float t
RoadLaneDirection direction
std::string filter
Graphics * graphics
std::string text
std::uint16_t third
glm::mat4 lightVP
Definition Shadow.cpp:148
float dy
Definition Shadow.cpp:151
int count
std::array< double, 2 > vertices[3]
int spacing
float opacity
float separation
Definition TreeMesh.cpp:161
float size
Definition TreeMesh.cpp:158
std::size_t at
uint32_t index
glm::vec3 point
glm::vec4 bary
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
Definition Status.cpp:28
Result< void > configureFoam(bool enabled, int downsample=1)
Configures Fluid3D-compatible foam generation visibility and render-target downsampling.
const std::vector< uint8_t > & color() const
RGBA8 shaded output.
Result< void > compositeDiffuse(const VolumeFluidDiffuse &pool, float radius, float opacity, float fadeSeconds)
Composites white secondary particles over the last reconstructed frame.
Bounded, one-way fluid-advected secondary particle pool. @ownership Owns particles and capacity; no f...
unsigned particleCount() const
Returns live count without copying particle data.
void copyRenderData(std::vector< glm::vec4 > &positionLife) const
Reuses caller storage to copy XY Z position and remaining life for rendering.
Result< void > update(const VolumeFluid &fluid, unsigned actorGroup, float radiusScale, float alpha=1.f, unsigned maxParticles=4096)
Rebuild one actor's bounded octahedral shadow batch.
VolumeFluidShadowCaster(graphics::Graphics &graphics)
Constructs a VolumeFluidShadowCaster.
~VolumeFluidShadowCaster()
Releases VolumeFluidShadowCaster resources.
CPU position-based free-volume fluid with a bounded spatial grid. @ownership Owns all particle state;...
Result< void > copyParticleImpostors(unsigned actorGroup, float radiusScale, glm::vec4 tint, float alpha, unsigned maxInstances, std::vector< VolumeFluidParticleInstance > &instances) const
Writes Fluid3DParticleRenderer-style instances into caller-owned reusable storage.
virtual bool releaseMesh(Mesh *mesh)
Eagerly releases a mesh created by this Graphics.
Definition Graphics.h:935
virtual void drawMeshShadow(Mesh *mesh, const glm::mat4 &lightMVP, bool doubleSided=true)=0
Queue an opaque shadow caster.
virtual bool updateMeshVertices(Mesh *mesh, const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
In-place update of a mesh's vertex/index data (CPU -> host-visible VBO). Only call when content chang...
virtual Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh from packed CPU arrays. Owned by Graphics. posXYZ required (vertexCount*3)....
static void removeShadowExtraDrawer(uint64_t token)
Remove one shadow callback before destroying its captured state.
static uint64_t addShadowExtraDrawer(ShadowExtraDrawer drawer)
Adds shadow extra drawer.
I * query()
Queries .
Definition Capability.h:88
Result< std::vector< VolumeFluidSimplexHit > > querySimplexes(std::span< const VolumeFluidParticle > particles, std::span< const VolumeFluidSimplex > simplexes, std::span< const VolumeFluidQueryShape > queries, unsigned maxHitsPerQuery)
Queries simplexes.
GLSL compute kernels for the GPU surface-flow solver.
Definition FluidTarget.h:12
EVENGINE_API_DOMAINS Result< std::vector< VolumeFluidDistributionPoint > > buildVolumeFluidMeshDistribution(std::span< const glm::vec3 > vertices, std::span< const uint32_t > indices, glm::vec3 scale, float spacing)
Voxelizes indexed triangles, returning surface and enclosed interior cell centers.
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29
std::vector< OnnxNamedTensor > evaluate(const ModelData &, std::span< const OnnxNamedTensor >, const std::vector< std::string > &, OnnxCompute *, OnnxRunOptions options)
Evaluate.
bool enabled
Owning Fluid3D-compatible nearest result for one simplex and query pair.