载入中...
搜索中...
未找到
CollapseDust.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <bit>
4#include <chrono>
5#include <cmath>
6#include <cstdint>
7#include <cstdio>
8#include <filesystem>
9#include <fstream>
10#include <glm/gtc/matrix_transform.hpp>
11#include <glm/gtc/quaternion.hpp>
12#include <limits>
13#include <sstream>
14#include "fluids/VolumeFluid.h"
16#include "graphics/FogVolume.h"
17#include "graphics/Graphics.h"
19#include "graphics/Texture.h"
20#include "graphics/Volumetric.h"
24namespace eve::physics {
25namespace {
26Result<void> bad(const char* message) {
28}
29constexpr std::uint32_t MaxFrames = 2048, MaxParticles = 1024, MaxSamples = 524288;
30void put(std::ostream& out, std::uint32_t v) {
31 for (int i = 0; i < 4; ++i) out.put(static_cast<char>((v >> (i * 8)) & 255));
32}
33std::uint32_t get(std::istream& in) {
34 std::uint32_t v = 0;
35 for (int i = 0; i < 4; ++i) {
36 int c = in.get();
37 if (c < 0) throw std::runtime_error("truncated dust asset");
38 v |= static_cast<std::uint32_t>(c) << (i * 8);
39 }
40 return v;
41}
42void real(std::ostream& out, float v) { put(out, std::bit_cast<std::uint32_t>(v)); }
43float real(std::istream& in) { return std::bit_cast<float>(get(in)); }
44bool valid(const std::array<float, 7>& p) {
45 for (float f : p)
46 if (!std::isfinite(f)) return false;
47 for (int i = 0; i < 3; ++i)
48 if (std::abs(p[i]) > 10000.f) return false;
49 for (int i = 3; i < 7; ++i)
50 if (p[i] < 0.f || p[i] > 1.f) return false;
51 return true;
52}
53} // namespace
56 if (!future_.valid()) return;
57 try {
58 auto pending = future_.get();
59 if (!pending) std::fprintf(stderr, "collapse dust: unpublished worker failed during teardown\n");
60 } catch (const std::exception& error) {
61 std::fprintf(stderr, "collapse dust: worker teardown: %s\n", error.what());
62 }
63}
65 if (future_.valid()) return bad("collect fog worker before capture");
66 if (!std::isfinite(seconds) || seconds < 0.f || frames_.size() >= MaxFrames ||
67 (frames_.empty() ? seconds != 0.f : seconds <= frames_.back().seconds))
68 return bad("invalid capture time/count");
69 Frame frame{seconds, source.spacing(), {}};
70 for (const auto& p : source.particleView())
71 if (p.material.phase == fluids::VolumeFluidPhase::Gas) {
72 const float fade = p.life > 0.f ? std::min(1.f, p.life / 2.f) : 1.f;
73 std::array<float, 7> sample{p.position.x, p.position.y, p.position.z, p.color.r,
74 p.color.g, p.color.b, p.color.a * fade};
75 if (!valid(sample)) return bad("invalid gas sample");
76 frame.particles.push_back(sample);
77 }
78 std::size_t total = frame.particles.size();
79 for (const auto& f : frames_) total += f.particles.size();
80 if (frame.particles.size() > MaxParticles || total > MaxSamples) return bad("gas cache budget exceeded");
81 frames_.push_back(std::move(frame));
82 requestedSeconds_ = -1.f;
83 presented_ = false;
84 return Result<void>::success();
85}
87 if (frames_.empty() || !std::isfinite(seconds)) return bad("empty dust clip or invalid time");
88 auto it = std::upper_bound(frames_.begin(), frames_.end(), seconds,
89 [](float t, const Frame& f) { return t < f.seconds; });
90 if (it != frames_.begin()) --it;
92 state.settings = target.snapshot().settings;
93 state.settings.spacing = it->spacing;
94 for (const auto& s : it->particles) {
96 p.position = {s[0], s[1], s[2]};
97 p.color = {s[3], s[4], s[5], s[6]};
98 p.material.phase = fluids::VolumeFluidPhase::Gas;
99 state.particles.push_back(p);
100 }
101 return target.restore(state);
102}
103Result<void> CollapseDust::save(std::string_view path) const {
104 if (path.empty() || path.find('\0') != std::string_view::npos || frames_.empty())
105 return bad("nonempty path without NUL and frames required");
106 std::ostringstream out(std::ios::binary);
107 out.write("EVEDUST1", 8);
108 put(out, 2);
109 put(out, static_cast<std::uint32_t>(frames_.size()));
110 for (const auto& f : frames_) {
111 real(out, f.seconds);
112 real(out, f.spacing);
113 put(out, static_cast<std::uint32_t>(f.particles.size()));
114 for (const auto& p : f.particles)
115 for (float v : p) real(out, v);
116 }
117 if (!out) return bad("dust serialization failed");
118 auto bytes = out.str();
121}
123 if (future_.valid()) return bad("collect fog worker before load");
124 if (path.empty() || path.find('\0') != std::string_view::npos)
125 return bad("dust asset path is empty or contains NUL");
126 std::ifstream file(std::string(path), std::ios::binary | std::ios::ate);
127 if (!file) {
128 std::error_code error;
129 const auto status = std::filesystem::status(std::filesystem::path(path), error);
130 const bool missing =
131 error == std::errc::no_such_file_or_directory || (!error && !std::filesystem::exists(status));
133 missing ? "dust asset not found" : "dust asset cannot be opened",
134 "collapseDust"));
135 }
136 constexpr std::streamoff maxBytes = 16 + 12 * MaxFrames + 28 * MaxSamples + 32;
137 const auto size = file.tellg();
138 if (size < 16 || size > maxBytes) return bad("dust file size outside budget");
139 std::string bytes(static_cast<std::size_t>(size), '\0');
140 file.seekg(0);
141 file.read(bytes.data(), static_cast<std::streamsize>(bytes.size()));
142 if (!file) return bad("dust file read failed");
143 if (std::string_view(bytes).substr(0, 8) != "EVEDUST1") return bad("unsupported dust schema");
144 std::uint32_t version = 0;
145 for (unsigned i = 0; i < 4; ++i)
146 version |= static_cast<std::uint32_t>(static_cast<unsigned char>(bytes[8 + i])) << (8 * i);
147 if (version != 1 && version != 2) return bad("unsupported dust version");
148 if (version == 2) {
149 if (bytes.size() < 48) return bad("truncated dust checksum");
150 const auto payload = std::string_view(bytes).substr(0, bytes.size() - 32);
151 if (CollapseAnimation::contentKey(payload) != std::string_view(bytes).substr(bytes.size() - 32))
153 Diagnostic::error(DiagnosticCode::HashMismatch, "dust asset checksum mismatch", "collapseDust"));
154 bytes.resize(bytes.size() - 32);
155 }
156 std::istringstream in(std::move(bytes), std::ios::binary);
157 std::vector<Frame> candidate;
158 try {
159 char magic[8];
160 in.read(magic, 8);
161 if (!in || std::string_view(magic, 8) != "EVEDUST1" || get(in) != version)
162 return bad("unsupported dust schema/version");
163 const auto count = get(in);
164 if (!count || count > MaxFrames) return bad("dust frame budget exceeded");
165 std::size_t total = 0;
166 for (std::uint32_t i = 0; i < count; ++i) {
167 Frame f{real(in), real(in), {}};
168 auto n = get(in);
169 total += n;
170 if (n > MaxParticles || total > MaxSamples || !std::isfinite(f.seconds) || !std::isfinite(f.spacing) ||
171 f.spacing < 0.001f || f.spacing > 10.f ||
172 (i ? f.seconds <= candidate.back().seconds : f.seconds != 0.f))
173 return bad("invalid dust frame");
174 f.particles.resize(n);
175 for (auto& p : f.particles) {
176 for (float& v : p) v = real(in);
177 if (!valid(p)) return bad("invalid dust sample");
178 }
179 candidate.push_back(std::move(f));
180 }
181 if (in.peek() != std::char_traits<char>::eof()) return bad("trailing dust fields");
182 } catch (const std::exception&) {
183 return bad("truncated dust asset");
184 }
185 frames_ = std::move(candidate);
186 requestedSeconds_ = -1.f;
187 presented_ = false;
188 return Result<void>::success();
189}
191 if (future_.valid()) return bad("collect outstanding fog job before depth preparation");
192 if (width < 1 || height < 1 || width > 1024 || height > 1024) return bad("dust depth dimensions outside budget");
193 std::vector<float> candidate(static_cast<std::size_t>(width) * height, std::numeric_limits<float>::max());
194 depth_ = std::move(candidate);
195 depthPixels_.resize(depth_.size() * 4);
196 width_ = width;
197 height_ = height;
198 return Result<void>::success();
199}
200Result<void> CollapseDust::rasterizeDepth(const CollapseAnimation& clip, float seconds, graphics::Camera3D& camera) {
201 const auto c = camera.data();
203 view.view = glm::lookAtRH(glm::vec3(c->eyeX, c->eyeY, c->eyeZ), glm::vec3(c->targetX, c->targetY, c->targetZ),
204 glm::vec3(c->upX, c->upY, c->upZ));
205 view.fov = c->fovYDeg;
206 view.nearDistance = c->nearZ;
207 view.farDistance = c->farZ;
208 if (c->orthographic) return bad("dust needs a perspective camera");
209 return rasterizeDepthView(clip, seconds, view);
210}
211Result<void> CollapseDust::rasterizeDepthView(const CollapseAnimation& clip, float seconds, const DustFogView& camera) {
212 auto geometry = clip.fragmentGeometry();
213 if (!geometry || depth_.empty() || !std::isfinite(seconds) || camera.fov <= 1.f || camera.fov >= 179.f)
214 return bad("invalid depth camera/clip");
215 const auto& view = camera.view;
216 const float scale = std::tan(glm::radians(camera.fov) * 0.5f), aspect = static_cast<float>(width_) / height_;
217 std::fill(depth_.begin(), depth_.end(), std::numeric_limits<float>::max());
218 for (std::size_t bone = 0; bone < geometry->fragments.size(); ++bone) {
219 auto sample = clip.sample(seconds, static_cast<int>(bone));
220 if (!sample) return Result<void>::failure(sample.status());
221 const auto& b = sample.value();
222 const glm::quat q(b.rotW, b.rotX, b.rotY, b.rotZ);
223 const glm::vec3 origin(b.worldX, b.worldY, b.worldZ);
224 const auto& mesh = geometry->fragments[bone];
225 for (std::size_t t = 0; t < mesh.indices.size(); t += 3) {
226 glm::vec3 v[3];
227 bool clipped = false;
228 for (int k = 0; k < 3; ++k) {
229 const auto j = mesh.indices[t + k] * 3;
230 const auto p = view * glm::vec4(origin + q * glm::vec3(mesh.positions[j], mesh.positions[j + 1],
231 mesh.positions[j + 2]),
232 1.f);
233 const float z = -p.z;
234 if (z <= camera.nearDistance) {
235 clipped = true;
236 break;
237 }
238 v[k] = {width_ * (0.5f + 0.5f * p.x / (z * scale * aspect)),
239 height_ * (0.5f - 0.5f * p.y / (z * scale)), 1.f / z};
240 }
241 if (clipped) continue;
242 const auto edge = [](const glm::vec3& a, const glm::vec3& b, float x, float y) {
243 return (b.x - a.x) * (y - a.y) - (b.y - a.y) * (x - a.x);
244 };
245 const float area = edge(v[0], v[1], v[2].x, v[2].y);
246 if (std::abs(area) < 1e-5f) continue;
247 int x0 = std::clamp(static_cast<int>(std::floor(std::min({v[0].x, v[1].x, v[2].x}))), 0, width_ - 1);
248 int x1 = std::clamp(static_cast<int>(std::ceil(std::max({v[0].x, v[1].x, v[2].x}))), 0, width_ - 1);
249 int y0 = std::clamp(static_cast<int>(std::floor(std::min({v[0].y, v[1].y, v[2].y}))), 0, height_ - 1);
250 int y1 = std::clamp(static_cast<int>(std::ceil(std::max({v[0].y, v[1].y, v[2].y}))), 0, height_ - 1);
251 for (int y = y0; y <= y1; ++y)
252 for (int x = x0; x <= x1; ++x) {
253 float a = edge(v[1], v[2], x + 0.5f, y + 0.5f) / area,
254 bary = edge(v[2], v[0], x + 0.5f, y + 0.5f) / area, d = 1.f - a - bary;
255 if (a >= 0.f && bary >= 0.f && d >= 0.f) {
256 float z = 1.f / (a * v[0].z + bary * v[1].z + d * v[2].z);
257 auto& cell = depth_[static_cast<std::size_t>(y) * width_ + x];
258 cell = std::min(cell, z);
259 }
260 }
261 }
262 }
263 return Result<void>::success();
264}
266 const CollapseAnimation& clip, float seconds,
267 graphics::Camera3D& camera) {
268 if (texture.getWidth() != width_ || texture.getHeight() != height_) return bad("depth texture dimensions mismatch");
269 auto raster = rasterizeDepth(clip, seconds, camera);
270 if (!raster) return raster;
271 const float near = camera.getNearClip(), far = camera.getFarClip();
272 for (std::size_t i = 0; i < depth_.size(); ++i) {
273 const auto value =
274 static_cast<unsigned char>(std::lround(std::clamp((depth_[i] - near) / (far - near), 0.f, 1.f) * 255.f));
275 depthPixels_[i * 4] = value;
276 depthPixels_[i * 4 + 1] = value;
277 depthPixels_[i * 4 + 2] = value;
278 depthPixels_[i * 4 + 3] = 255;
279 }
280 if (!graphics.updateTexture(&texture, width_, height_, depthPixels_.data()))
281 return bad("depth texture upload failed");
282 return Result<void>::success();
283}
284Result<void> CollapseDust::injectFog(graphics::AtmosphereVolume& grid, const glm::mat4& inverse, float seconds,
285 float density, float radius) const {
286 if (frames_.empty() || !std::isfinite(seconds) || !std::isfinite(density) || density < 0.f || density > 10.f ||
287 !std::isfinite(radius) || radius < 0.1f || radius > 5.f || grid.getFroxelCount() == 0 ||
288 grid.getFroxelCount() > 4000000)
289 return bad("invalid fog injection parameters or grid");
290 for (int c = 0; c < 4; ++c)
291 for (int r = 0; r < 4; ++r)
292 if (!std::isfinite(inverse[c][r])) return bad("nonfinite fog camera");
293 if (std::abs(glm::determinant(inverse)) < 1e-12f) return bad("singular fog camera");
294 const auto projection = glm::inverse(inverse);
295 auto it = std::upper_bound(frames_.begin(), frames_.end(), seconds,
296 [](float t, const Frame& f) { return t < f.seconds; });
297 if (it != frames_.begin()) --it;
298 auto unproject = [&](float x, float y, float z) {
299 const auto p = inverse * glm::vec4(x, y, z, 1.f);
300 return glm::vec3(p) / p.w;
301 };
302 const int w = grid.getWidth(), h = grid.getHeight();
303 const float nearDistance = grid.getNearDistance(), farDistance = grid.getFarDistance();
304 std::vector<float> fractions(static_cast<std::size_t>(grid.getDepth()));
305 for (int z = 0; z < grid.getDepth(); ++z)
306 fractions[z] = (grid.sliceDistance(z) - nearDistance) / (farDistance - nearDistance);
307 std::vector<glm::vec3> nearRays(static_cast<std::size_t>(w) * h), farRays(nearRays.size());
308 for (int y = 0; y < h; ++y)
309 for (int x = 0; x < w; ++x) {
310 const float nx = (x + 0.5f) / w * 2.f - 1.f, ny = (y + 0.5f) / h * 2.f - 1.f;
311 const auto index = static_cast<std::size_t>(y) * w + x;
312 nearRays[index] = unproject(nx, ny, 0.f);
313 farRays[index] = unproject(nx, ny, 1.f);
314 }
315 for (const auto& p : it->particles) {
316 if (p[6] <= 0.f) continue;
318 fog.setShape("sphere");
319 fog.setPosition(p[0], p[1], p[2]);
320 fog.setSize(radius * 2.f, radius * 2.f, radius * 2.f);
321 fog.setAlbedo(p[3], p[4], p[5]);
322 fog.setExtinction(density * p[6]);
323 fog.setEdgeFalloff(0.9f);
324 fog.setNoise(0.72f, 1.4f, 42);
325 float xmin = 1.f, xmax = -1.f, ymin = 1.f, ymax = -1.f, zmin = grid.getFarDistance(), zmax = 0.f;
326 bool nearCrossing = false;
327 for (int corner = 0; corner < 8; ++corner) {
328 const glm::vec3 offset((corner & 1) ? radius : -radius, (corner & 2) ? radius : -radius,
329 (corner & 4) ? radius : -radius);
330 const auto projected = projection * glm::vec4(glm::vec3(p[0], p[1], p[2]) + offset, 1.f);
331 if (projected.w <= grid.getNearDistance()) {
332 nearCrossing = true;
333 continue;
334 }
335 xmin = std::min(xmin, projected.x / projected.w);
336 xmax = std::max(xmax, projected.x / projected.w);
337 ymin = std::min(ymin, projected.y / projected.w);
338 ymax = std::max(ymax, projected.y / projected.w);
339 zmin = std::min(zmin, projected.w);
340 zmax = std::max(zmax, projected.w);
341 }
342 if (nearCrossing) {
343 xmin = ymin = -1.f;
344 xmax = ymax = 1.f;
345 zmin = grid.getNearDistance();
346 }
347 if (xmax < -1.f || xmin > 1.f || ymax < -1.f || ymin > 1.f || zmax < grid.getNearDistance() ||
348 zmin > grid.getFarDistance())
349 continue;
350 const int x0 = std::clamp(static_cast<int>((xmin * 0.5f + 0.5f) * w) - 1, 0, w - 1),
351 x1 = std::clamp(static_cast<int>((xmax * 0.5f + 0.5f) * w) + 1, 0, w - 1);
352 const int y0 = std::clamp(static_cast<int>((ymin * 0.5f + 0.5f) * h) - 1, 0, h - 1),
353 y1 = std::clamp(static_cast<int>((ymax * 0.5f + 0.5f) * h) + 1, 0, h - 1);
354 const int z0 = std::max(0, grid.sliceForDistance(zmin) - 1),
355 z1 = std::min(grid.getDepth() - 1, grid.sliceForDistance(zmax) + 1);
356 for (int y = y0; y <= y1; ++y)
357 for (int x = x0; x <= x1; ++x) {
358 const auto index = static_cast<std::size_t>(y) * w + x;
359 const auto& a = nearRays[index];
360 const auto& b = farRays[index];
361 for (int z = z0; z <= z1; ++z) {
362 const float fraction = fractions[z];
363 const float extinction = fog.sampleExtinction(glm::mix(a, b, fraction));
364 if (extinction <= 0.f) continue;
365 auto& cell = grid.at(x, y, z);
366 cell.extinction += extinction;
367 cell.scattering += fog.getAlbedo() * extinction;
368 cell.anisotropy = 0.1f;
369 }
370 }
371 }
372 return Result<void>::success();
373}
374
375namespace {
376bool sameView(const DustFogView& a, const DustFogView& b) {
377 return a.view == b.view && a.inverseViewProjection == b.inverseViewProjection && a.fov == b.fov &&
378 a.nearDistance == b.nearDistance && a.farDistance == b.farDistance;
379}
380} // namespace
381Result<void> CollapseDust::prepareFog(const CollapseAnimation& clip, int dw, int dh, int gw, int gh, int gd) {
382 if (future_.valid()) return bad("collect outstanding fog job before preparation");
383 if (!clip.fragmentGeometry() || gw < 1 || gh < 1 || gd < 1 || gw > 256 || gh > 256 || gd > 256 ||
384 static_cast<std::size_t>(gw) * gh * gd > 4000000)
385 return bad("invalid fog preparation dimensions/clip");
386 auto candidate = std::make_shared<CollapseAnimation>(clip);
387 auto prepared = prepareDepth(dw, dh);
388 if (!prepared) return prepared;
389 fogClip_ = std::move(candidate);
390 gridWidth_ = gw;
391 gridHeight_ = gh;
392 gridDepth_ = gd;
393 requestedSeconds_ = -1.f;
394 presented_ = false;
395 return Result<void>::success();
396}
398 if (!fogClip_ || frames_.empty() || !std::isfinite(seconds) || !std::isfinite(density) || density < 0.f ||
399 density > 10.f || !std::isfinite(radius) || radius < 0.1f || radius > 5.f)
400 return Result<DustFogRequest>::failure(bad("invalid fog job parameters").status());
401 if (!std::isfinite(view.fov) || view.fov <= 1.f || view.fov >= 179.f || !std::isfinite(view.nearDistance) ||
402 !std::isfinite(view.farDistance) || view.nearDistance <= 0.f || view.farDistance <= view.nearDistance)
403 return Result<DustFogRequest>::failure(bad("invalid fog view range").status());
404 for (int c = 0; c < 4; ++c)
405 for (int r = 0; r < 4; ++r)
406 if (!std::isfinite(view.view[c][r]) || !std::isfinite(view.inverseViewProjection[c][r]))
407 return Result<DustFogRequest>::failure(bad("nonfinite fog view").status());
408 if (std::abs(glm::determinant(view.inverseViewProjection)) < 1e-12f)
409 return Result<DustFogRequest>::failure(bad("singular fog view").status());
410 if (future_.valid()) return Result<DustFogRequest>::success(DustFogRequest::Busy);
411 if (seconds == requestedSeconds_ && density == requestedDensity_ && radius == requestedRadius_ &&
412 sameView(view, requestedView_))
414 auto it = std::upper_bound(frames_.begin(), frames_.end(), seconds,
415 [](float t, const Frame& f) { return t < f.seconds; });
416 if (it != frames_.begin()) --it;
417 auto frame = *it;
418 frame.seconds = 0.f;
419 const auto clip = fogClip_;
420 const int dw = width_, dh = height_, gw = gridWidth_, gh = gridHeight_, gd = gridDepth_;
421 try {
422 future_ = std::async(
423 std::launch::async,
424 [frame = std::move(frame), clip, view, seconds, density, radius, dw, dh, gw, gh,
425 gd]() mutable -> Result<DustFogFrame> {
426 CollapseDust scratch;
427 scratch.frames_.push_back(std::move(frame));
428 auto prepared = scratch.prepareDepth(dw, dh);
429 if (!prepared) return Result<DustFogFrame>::failure(prepared.status());
431 grid.resize(gw, gh, gd);
432 grid.setDepthRange(view.nearDistance, view.farDistance);
433 auto injected = scratch.injectFog(grid, view.inverseViewProjection, 0.f, density, radius);
434 if (!injected) return Result<DustFogFrame>::failure(injected.status());
435 grid.integrate(glm::vec3(1.10f, 1.02f, 0.86f), 1.f);
437 output.view = view;
438 output.seconds = seconds;
439 output.depthWidth = dw;
440 output.depthHeight = dh;
441 const int cols = std::max(1, static_cast<int>(std::ceil(std::sqrt(static_cast<float>(gd))))),
442 rows = (gd + cols - 1) / cols;
443 output.atlasWidth = gw * cols;
444 output.atlasHeight = gh * rows;
445 output.atlas.resize(static_cast<std::size_t>(output.atlasWidth) * output.atlasHeight * 4);
446 for (int z = 0; z < gd; ++z)
447 for (int y = 0; y < gh; ++y)
448 for (int x = 0; x < gw; ++x) {
449 const auto& value = grid.integratedAt(x, y, z);
450 const auto mapped = glm::vec3(value) / (glm::vec3(1.f) + glm::vec3(value));
451 const auto at = (static_cast<std::size_t>((z / cols) * gh + y) * output.atlasWidth +
452 (z % cols) * gw + x) *
453 4;
454 for (int channel = 0; channel < 3; ++channel)
455 output.atlas[at + channel] = static_cast<unsigned char>(
456 std::lround(std::clamp(mapped[channel], 0.f, 1.f) * 255.f));
457 output.atlas[at + 3] =
458 static_cast<unsigned char>(std::lround(std::clamp(value.a, 0.f, 1.f) * 255.f));
459 }
460 // Reconstruct sparse media footprints before the existing fog
461 // compositor samples them. Clamp within each Z tile: neighbouring
462 // atlas tiles represent different depths and must never bleed.
463 std::vector<unsigned char> filtered(output.atlas.size());
464 for (int pass = 0; pass < 2; ++pass) {
465 for (int z = 0; z < gd; ++z)
466 for (int y = 0; y < gh; ++y)
467 for (int x = 0; x < gw; ++x) {
468 const auto at = (static_cast<std::size_t>((z / cols) * gh + y) * output.atlasWidth +
469 (z % cols) * gw + x) *
470 4;
471 for (int channel = 0; channel < 4; ++channel) {
472 unsigned total = 0;
473 constexpr unsigned weights[5] = {1, 4, 6, 4, 1};
474 for (int tap = -2; tap <= 2; ++tap) {
475 const int sx = std::clamp(x + (pass == 0 ? tap : 0), 0, gw - 1);
476 const int sy = std::clamp(y + (pass == 1 ? tap : 0), 0, gh - 1);
477 const auto from =
478 (static_cast<std::size_t>((z / cols) * gh + sy) * output.atlasWidth +
479 (z % cols) * gw + sx) *
480 4 +
481 channel;
482 total += weights[tap + 2] * output.atlas[from];
483 }
484 filtered[at + channel] = static_cast<unsigned char>((total + 8) / 16);
485 }
486 }
487 output.atlas.swap(filtered);
488 }
489 auto depth = scratch.rasterizeDepthView(*clip, seconds, view);
490 if (!depth) return Result<DustFogFrame>::failure(depth.status());
491 output.depth.resize(scratch.depth_.size() * 4);
492 for (std::size_t i = 0; i < scratch.depth_.size(); ++i) {
493 const auto d = static_cast<unsigned char>(std::lround(
494 std::clamp((scratch.depth_[i] - view.nearDistance) / (view.farDistance - view.nearDistance),
495 0.f, 1.f) *
496 255.f));
497 output.depth[i * 4] = d;
498 output.depth[i * 4 + 1] = d;
499 output.depth[i * 4 + 2] = d;
500 output.depth[i * 4 + 3] = 255;
501 }
502 return Result<DustFogFrame>::success(std::move(output));
503 });
504 } catch (const std::exception&) {
505 return Result<DustFogRequest>::failure(bad("fog worker admission failed").status());
506 }
507 requestedSeconds_ = seconds;
508 requestedDensity_ = density;
509 requestedRadius_ = radius;
510 requestedView_ = view;
512}
514 if (!future_.valid() || future_.wait_for(std::chrono::seconds(0)) != std::future_status::ready)
515 return Result<std::optional<DustFogFrame>>::success(std::nullopt);
516 try {
517 auto output = future_.get();
518 if (!output) {
519 requestedSeconds_ = -1.f;
520 return Result<std::optional<DustFogFrame>>::failure(output.status());
521 }
522 return Result<std::optional<DustFogFrame>>::success(std::move(output).takeValue());
523 } catch (const std::exception&) {
524 requestedSeconds_ = -1.f;
525 return Result<std::optional<DustFogFrame>>::failure(bad("fog worker failed").status());
526 }
527}
529 graphics::Camera3D& camera, float density, float radius) {
531 const auto c = camera.data();
532 if (c->orthographic) return Result<DustFogDisplay>::failure(bad("fog needs a perspective camera").status());
533 view.fov = c->fovYDeg;
534 view.nearDistance = c->nearZ;
535 view.farDistance = c->farZ;
536 view.view = glm::lookAtRH(glm::vec3(c->eyeX, c->eyeY, c->eyeZ), glm::vec3(c->targetX, c->targetY, c->targetZ),
537 glm::vec3(c->upX, c->upY, c->upZ));
538 view.inverseViewProjection = fog.getInvViewProj();
539 auto completed = takeFogFrame();
540 if (!completed) return Result<DustFogDisplay>::failure(completed.status());
541 if (completed.value() && sameView(completed.value()->view, view)) {
542 const auto& frame = *completed.value();
543 auto* atlas = fog.getFroxelAtlas();
544 if (!atlas || atlas->getWidth() != frame.atlasWidth || atlas->getHeight() != frame.atlasHeight)
545 return Result<DustFogDisplay>::failure(bad("prepare matching fog atlas before update").status());
546 if (!presented_) graphics.setTextureSampler(atlas, "linear", "none", 1.f, 0.f);
547 if (!graphics.updateTexture(atlas, frame.atlasWidth, frame.atlasHeight, frame.atlas.data()))
548 return Result<DustFogDisplay>::failure(bad("fog texture upload failed").status());
549 presented_ = true;
550 presentedView_ = view;
551 }
552 auto request = requestFog(seconds, view, density, radius);
553 if (!request) return Result<DustFogDisplay>::failure(request.status());
554 return Result<DustFogDisplay>::success(presented_ && sameView(presentedView_, view) ? DustFogDisplay::Ready
556}
557} // namespace eve::physics
double z
double y
double x
LogicalId target
Value::Object payload
float w
Definition AnimClip.cpp:738
std::string output
std::vector< QuestEvent > pending
const std::string & s
glm::vec4 p[6]
int rows
int cols
float density
std::string message
const GltfImportRequest & request
float camera[2]
wgpu::PopErrorScopeStatus status
glm::vec4 clip
float area
Definition Grass.cpp:62
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
double r
float v
std::int32_t c
int h
std::uint32_t height
std::uint32_t width
size_t offset
std::array< float, 3 > scale
std::uint32_t bone
std::string from
std::uint64_t bytes
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanMeshSettings mesh
glm::dvec3 origin
ssq::Object frame
OceanSprayView view
std::string error
Definition Package.cpp:174
Texture * texture
float f
std::string path
Definition PlayHost.cpp:111
std::string file
Object::Ptr value
float d
float t
std::string geometry
Graphics * graphics
ScriptStructure out
std::string_view source
Vec extinction
int count
Cell cell
float weights[3]
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
std::size_t at
uint32_t index
float fraction
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
CPU position-based free-volume fluid with a bounded spatial grid. @ownership Owns all particle state;...
Camera-frustum volume used by the volumetric fog passes and CPU references.
EVENGINE_API_BACKENDS public API.
Analytic local participating-media volume injected into atmospheric fog.
Definition FogVolume.h:12
const glm::vec3 & getAlbedo() const
Definition FogVolume.h:34
void setExtinction(float extinction)
Signed extinction; negative values carve fog but total density is clamped.
Definition FogVolume.h:30
float sampleExtinction(const glm::vec3 &worldPosition) const
Normalized analytic density at a world position, including signed extinction.
Definition FogVolume.cpp:82
void setShape(const std::string &shape)
Set shape using "sphere", "box" or "cylinder"; unknown selects box.
Definition FogVolume.cpp:41
void setAlbedo(float r, float g, float b)
Single-scattering albedo, clamped to [0,1].
Definition FogVolume.cpp:60
void setEdgeFalloff(float falloff)
Fraction of normalized radius used for a smooth edge, in [0,1].
Definition FogVolume.cpp:72
void setSize(float x, float y, float z)
Set full world-space dimensions; values are clamped positive.
Definition FogVolume.cpp:56
void setPosition(float x, float y, float z)
Set world-space center.
Definition FogVolume.h:23
void setNoise(float amount, float scale, int seed)
Configure deterministic world-space density variation.
Definition FogVolume.cpp:76
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
Volumetric light + fog.
Definition Volumetric.h:38
const glm::mat4 & getInvViewProj() const
Inverse view-projection last written by setCamera / setInvViewProj.
Definition Volumetric.h:215
Texture * getFroxelAtlas() const
Returns the froxel atlas.
Definition Volumetric.h:333
Owning, solver-independent baked rigid-fragment animation within Physics. @ownership Owns all samples...
static std::string contentKey(std::string_view source)
Stable noncryptographic cache identity over every source byte. Compatibility facade; canonical native...
Owning gas presentation cache, independent of the source solver. @ownership Owns frames and depth scr...
Result< void > updateDepthTexture(graphics::Graphics &graphics, graphics::Texture &texture, const CollapseAnimation &clip, float seconds, graphics::Camera3D &camera)
Upload exact animated-fragment depth for the existing fog compositor. @cost Linear in triangles and c...
Result< void > save(std::string_view path) const
Save a new asset through the shared atomic, non-replacing baked-asset publisher. @cost Linear in all ...
Result< std::optional< DustFogFrame > > takeFogFrame()
Nonblocking collection; an empty optional means the sole worker is still running.
Result< DustFogDisplay > updateFog(graphics::Volumetric &fog, graphics::Graphics &graphics, float seconds, graphics::Camera3D &camera, float density, float radius)
Poll/upload completed pixels and request the latest time without blocking rendering....
Result< void > injectFog(graphics::AtmosphereVolume &grid, const glm::mat4 &inverseViewProjection, float seconds, float density, float radius) const
Inject saved gas into the existing local-volume fog grid, without stepping a solver.
~CollapseDust()
Join and check an unpublished CPU job before releasing owned data.
Result< void > capture(const fluids::VolumeFluid &source, float seconds)
Capture gas particles, fading their final two seconds. @cost Linear in live particles,...
Result< DustFogRequest > requestFog(float seconds, const DustFogView &view, float density, float radius)
Submit at most one CPU-only worker; busy requests do not queue more work. @cost Copies one gas frame ...
Result< void > load(std::string_view path)
Validate and load an owning clip; failure preserves this clip. @cost Linear in file size,...
Result< void > present(fluids::VolumeFluid &target, float seconds) const
Restore nearest preceding frame into a dedicated presentation solver. @cost Linear in particles,...
Result< void > prepareDepth(int width, int height)
Allocate bounded CPU scene-depth scratch before rendering. @cost Linear in output pixels,...
Result< void > prepareFog(const CollapseAnimation &clip, int depthWidth, int depthHeight, int gridWidth, int gridHeight, int gridDepth)
Prepare independent clip ownership and bounded worker dimensions. @cost Copies all rigid samples once...
CollapseDust()
Construct an empty owning cache; no worker starts until requested.
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
Result< void > publishBakedAsset(std::string_view path, std::string_view bytes)
Publish complete baked asset bytes atomically without replacing an existing path. @ownership Borrows ...
Owning particle value with world position and velocity in SI units.
Definition VolumeFluid.h:96
Canonical version-20 owning state; older codecs migrate collider, attachment, stitch,...
Owning worker output; no GPU or source pointers. Graphics borrows pixels only for upload.
Owning camera snapshot; CPU workers never access an ECS camera.