载入中...
搜索中...
未找到
ShallowWaterField.cpp
浏览该文件的文档.
2
3#include "common/Diagnostic.h"
6#include "gpgpu/Gpgpu.h"
7#include "gpgpu/GpuBuffer.h"
8#include "gpgpu/Sequence.h"
9#include "image/ImageData.h"
10
11#include <algorithm>
12#include <cmath>
13#include <cstring>
14#include <glm/glm.hpp>
15#include <limits>
16#include <string>
17#include <utility>
18
19namespace eve::fluids {
20namespace {
21
22constexpr int kPushResX = 0;
23constexpr int kPushResZ = 1;
24constexpr int kPushCell = 2;
25constexpr int kPushDt = 3;
26constexpr int kPushGravity = 4;
27constexpr int kPushViscosity = 5;
28constexpr int kPushFriction = 6;
29constexpr int kPushMinDepth = 7;
30constexpr int kPushMaxDepth = 8;
31constexpr int kPushColliderCount = 9;
32constexpr int kPushOriginX = 10;
33constexpr int kPushOriginY = 11;
34constexpr int kPushOriginZ = 12;
35
36[[nodiscard]] bool finite3(const glm::vec3& v) noexcept {
37 return std::isfinite(v.x) && std::isfinite(v.y) && std::isfinite(v.z);
38}
39
40[[nodiscard]] Result<void> fail(const char* message) {
43}
44
45[[nodiscard]] glm::vec3 fluxX(float h, float hu, float hv, float g, float minH) noexcept {
46 if (h <= minH) return {0.f, 0.f, 0.f};
47 const float u = hu / h;
48 const float v = hv / h;
49 return {hu, hu * u + 0.5f * g * h * h, hu * v};
50}
51
52[[nodiscard]] glm::vec3 fluxZ(float h, float hu, float hv, float g, float minH) noexcept {
53 if (h <= minH) return {0.f, 0.f, 0.f};
54 const float u = hu / h;
55 const float v = hv / h;
56 return {hv, hv * u, hv * v + 0.5f * g * h * h};
57}
58
59// Hydrostatic reconstruction (Audusse et al., 2004), including the pressure
60// correction on the receiving cell. A constant free surface remains at rest.
61[[nodiscard]] glm::vec3 bedFlux(glm::vec3 a, glm::vec3 b, float ba, float bb, float gravity, float minDepth, bool axisZ,
62 bool receiveA) noexcept {
63 const float top = std::max(ba, bb);
64 const float ha = std::max(0.f, a.x + ba - top);
65 const float hb = std::max(0.f, b.x + bb - top);
66 const glm::vec3 qa{ha, a.x > minDepth ? a.y * ha / a.x : 0.f, a.x > minDepth ? a.z * ha / a.x : 0.f};
67 const glm::vec3 qb{hb, b.x > minDepth ? b.y * hb / b.x : 0.f, b.x > minDepth ? b.z * hb / b.x : 0.f};
68 const int axis = axisZ ? 2 : 1;
69 const float va = ha > minDepth ? std::abs(qa[axis] / ha) : 0.f;
70 const float vb = hb > minDepth ? std::abs(qb[axis] / hb) : 0.f;
71 const float alpha = std::max(va + std::sqrt(gravity * ha), vb + std::sqrt(gravity * hb));
72 glm::vec3 f =
73 0.5f * ((axisZ ? fluxZ(qa.x, qa.y, qa.z, gravity, minDepth) : fluxX(qa.x, qa.y, qa.z, gravity, minDepth)) +
74 (axisZ ? fluxZ(qb.x, qb.y, qb.z, gravity, minDepth) : fluxX(qb.x, qb.y, qb.z, gravity, minDepth))) -
75 0.5f * alpha * (qb - qa);
76 const float original = receiveA ? a.x : b.x;
77 const float reconstructed = receiveA ? ha : hb;
78 f[axis] += 0.5f * gravity * (original * original - reconstructed * reconstructed);
79 return f;
80}
81
82[[nodiscard]] float colliderFootprintDistance(const ShallowWaterCollider& c, float worldX, float worldZ) noexcept {
83 const float dx = worldX - c.center.x;
84 const float dz = worldZ - c.center.z;
85 if (c.shape == ShallowWaterColliderShape::Box) {
86 const float ox = std::abs(dx) - c.halfExtent.x;
87 const float oz = std::abs(dz) - c.halfExtent.z;
88 const float outside = std::sqrt(std::max(ox, 0.f) * std::max(ox, 0.f) + std::max(oz, 0.f) * std::max(oz, 0.f));
89 return outside + std::min(std::max(ox, oz), 0.f);
90 }
91 return std::sqrt(dx * dx + dz * dz) - c.radius;
92}
93
94[[nodiscard]] float colliderImmersion(const ShallowWaterCollider& c, float surfaceY) noexcept {
96 return std::clamp(surfaceY - (c.center.y - c.radius), 0.f, 2.f * c.radius);
97 }
99 const float top = c.center.y + c.halfExtent.y + c.radius;
100 const float bottom = c.center.y - c.halfExtent.y - c.radius;
101 return std::clamp(surfaceY - bottom, 0.f, top - bottom);
102 }
103 return std::clamp(surfaceY - (c.center.y - c.halfExtent.y), 0.f, 2.f * c.halfExtent.y);
104}
105
106} // namespace
107
109 auto field = std::unique_ptr<ShallowWaterField>(new ShallowWaterField(settings));
110 if (auto valid = field->validateSettings(settings); !valid) return Result<std::unique_ptr<ShallowWaterField>>::failure(valid.status());
111 const int cells = field->cellCount();
112 field->heights_.assign(size_t(cells), settings.initialDepth);
113 field->restDepths_ = field->heights_;
114 field->momentumX_.assign(size_t(cells), 0.f);
115 field->momentumZ_.assign(size_t(cells), 0.f);
116 field->beds_.assign(size_t(cells), settings.bedHeight);
117 field->srcH_.assign(size_t(cells), 0.f);
118 field->srcHu_.assign(size_t(cells), 0.f);
119 field->srcHv_.assign(size_t(cells), 0.f);
120 field->scratchH_.assign(size_t(cells), 0.f);
121 field->scratchHu_.assign(size_t(cells), 0.f);
122 field->scratchHv_.assign(size_t(cells), 0.f);
123 return Result<std::unique_ptr<ShallowWaterField>>::success(std::move(field));
124}
125
127 : resX_(settings.resolutionX),
128 resZ_(settings.resolutionZ),
129 cellSize_(settings.cellSize),
130 origin_(settings.origin),
131 gravity_(settings.gravity),
132 viscosity_(settings.viscosity),
133 friction_(settings.friction),
134 minDepth_(settings.minDepth),
135 maxDepth_(settings.maxDepth),
136 cfl_(settings.cfl),
137 maxSubsteps_(settings.maxSubsteps),
138 preferGpu_(settings.preferGpu) {}
139
141 // gpgpu_ comes from Gpgpu::create() (module registry ownership), same as FluidSimulator.
142 delete seq_;
143 delete stageState_;
144 delete bufColliders_;
145 delete bufSources_;
146 delete bufBed_;
147 delete bufStateB_;
148 delete bufStateA_;
149 delete shIntegrate_;
150 delete shRaster_;
151 delete shClear_;
152}
153
154Result<void> ShallowWaterField::validateSettings(const ShallowWaterSettings& settings) const {
156 return fail("resolutionX/Z must be in [8, 512]");
157 if (!(settings.cellSize > 0.f) || settings.cellSize > 10.f || !std::isfinite(settings.cellSize))
158 return fail("cellSize must be in (0, 10]");
159 if (!finite3(settings.origin)) return fail("origin must be finite");
160 if (!(settings.gravity > 0.f) || settings.gravity > 100.f || !std::isfinite(settings.gravity))
161 return fail("gravity must be in (0, 100]");
162 if (!(settings.viscosity >= 0.f) || settings.viscosity > 1.f || !std::isfinite(settings.viscosity))
163 return fail("viscosity must be in [0, 1]");
164 if (!(settings.friction >= 0.f) || settings.friction > 8.f || !std::isfinite(settings.friction))
165 return fail("friction must be in [0, 8]");
166 if (!(settings.minDepth > 0.f) || settings.minDepth > 1.f || !std::isfinite(settings.minDepth))
167 return fail("minDepth must be in (0, 1]");
168 if (!(settings.maxDepth > settings.minDepth) || settings.maxDepth > 100.f || !std::isfinite(settings.maxDepth))
169 return fail("maxDepth must be in (minDepth, 100]");
170 if (!(settings.cfl > 0.f) || settings.cfl > 1.f || !std::isfinite(settings.cfl)) return fail("cfl must be in (0, 1]");
171 if (settings.maxSubsteps < 1 || settings.maxSubsteps > 64) return fail("maxSubsteps must be in [1, 64]");
172 if (!(settings.initialDepth >= 0.f) || settings.initialDepth > settings.maxDepth || !std::isfinite(settings.initialDepth))
173 return fail("initialDepth must be in [0, maxDepth]");
174 if (!std::isfinite(settings.bedHeight)) return fail("bedHeight must be finite");
176 if (cells > 512ull * 512ull) return fail("cell count exceeds 512^2 budget");
177 return Result<void>::success();
178}
179
182 s.resolutionX = resX_;
183 s.resolutionZ = resZ_;
184 s.cellSize = cellSize_;
185 s.origin = origin_;
186 s.gravity = gravity_;
187 s.viscosity = viscosity_;
188 s.friction = friction_;
189 s.minDepth = minDepth_;
190 s.maxDepth = maxDepth_;
191 s.cfl = cfl_;
192 s.maxSubsteps = maxSubsteps_;
193 s.preferGpu = preferGpu_;
194 s.initialDepth = heights_.empty() ? 0.f : heights_[0];
195 s.bedHeight = beds_.empty() ? 0.f : beds_[0];
196 return s;
197}
198
199Result<void> ShallowWaterField::setColliders(std::span<const ShallowWaterCollider> colliders) {
200 if (colliders.size() > 64) return fail("at most 64 shallow-water colliders");
201 for (size_t i = 0; i < colliders.size(); ++i) {
202 const auto& c = colliders[i];
203 if (!finite3(c.center) || !finite3(c.halfExtent) || !finite3(c.velocity) || !std::isfinite(c.radius) ||
204 !std::isfinite(c.displacementScale) || !std::isfinite(c.dragScale) || c.radius < 0.001f || c.radius > 100.f ||
205 c.displacementScale < 0.f || c.displacementScale > 10.f || c.dragScale < 0.f || c.dragScale > 10.f ||
206 glm::length(c.velocity) > 100.f ||
209 return fail("invalid shallow-water collider sample");
210 if (c.shape == ShallowWaterColliderShape::Box &&
211 (c.halfExtent.x <= 0.f || c.halfExtent.y <= 0.f || c.halfExtent.z <= 0.f))
212 return fail("box collider halfExtent must be positive");
213 if (c.shape == ShallowWaterColliderShape::Capsule && c.halfExtent.y <= 0.f)
214 return fail("capsule halfExtent.y must be positive");
215 for (size_t j = 0; j < i; ++j)
216 if (colliders[j].label == c.label) return fail("duplicate shallow-water collider label");
217 }
218 colliders_.assign(colliders.begin(), colliders.end());
219 return Result<void>::success();
220}
221
222Result<void> ShallowWaterField::setBed(std::span<const float> beds) {
223 if (int(beds.size()) != cellCount()) return fail("bed buffer size must equal cellCount()");
224 for (float v : beds)
225 if (!std::isfinite(v)) return fail("bed heights must be finite");
226 beds_.assign(beds.begin(), beds.end());
227 stateOnGpu_ = false;
228 if (gpuOk_ && bufBed_) bufBed_->writeFloat32s(beds_.data(), int(beds_.size()));
229 return Result<void>::success();
230}
231
233 if (!std::isfinite(depth) || depth < 0.f || depth > maxDepth_) return fail("fillDepth out of range");
234 std::fill(heights_.begin(), heights_.end(), depth);
235 restDepths_ = heights_;
236 std::fill(momentumX_.begin(), momentumX_.end(), 0.f);
237 std::fill(momentumZ_.begin(), momentumZ_.end(), 0.f);
238 stateOnGpu_ = false;
239 return Result<void>::success();
240}
241
243 if (!std::isfinite(surfaceY)) return fail("surfaceY must be finite");
244 for (float bed : beds_)
245 if (surfaceY - bed > maxDepth_) return fail("surface depth exceeds maxDepth");
246 for (size_t i = 0; i < heights_.size(); ++i) heights_[i] = std::max(0.f, surfaceY - beds_[i]);
247 restDepths_ = heights_;
248 std::fill(momentumX_.begin(), momentumX_.end(), 0.f);
249 std::fill(momentumZ_.begin(), momentumZ_.end(), 0.f);
250 stateOnGpu_ = false;
251 return Result<void>::success();
252}
253
254void ShallowWaterField::worldToCell(float worldX, float worldZ, float& fx, float& fz) const noexcept {
255 fx = (worldX - origin_.x) / cellSize_ - 0.5f;
256 fz = (worldZ - origin_.z) / cellSize_ - 0.5f;
257}
258
259Result<void> ShallowWaterField::disturbAt(float worldX, float worldZ, float radius, float heightDelta,
260 float radialSpeed) {
261 if (!std::isfinite(worldX) || !std::isfinite(worldZ) || !std::isfinite(radius) || !std::isfinite(heightDelta) ||
262 !std::isfinite(radialSpeed) || radius <= 0.f || radius > 50.f || std::abs(heightDelta) > maxDepth_ ||
263 std::abs(radialSpeed) > 50.f)
264 return fail("invalid disturbAt arguments");
265 stateOnGpu_ = false;
266 const float r2 = radius * radius;
267 for (int z = 0; z < resZ_; ++z) {
268 for (int x = 0; x < resX_; ++x) {
269 const float wx = origin_.x + (float(x) + 0.5f) * cellSize_;
270 const float wz = origin_.z + (float(z) + 0.5f) * cellSize_;
271 const float dx = wx - worldX;
272 const float dz = wz - worldZ;
273 const float d2 = dx * dx + dz * dz;
274 if (d2 > r2) continue;
275 const float w = 1.f - std::sqrt(d2) / radius;
276 const int i = index(x, z);
277 heights_[size_t(i)] = std::clamp(heights_[size_t(i)] + heightDelta * w, 0.f, maxDepth_);
278 if (std::abs(radialSpeed) > 1e-6f && d2 > 1e-8f) {
279 const float inv = 1.f / std::sqrt(d2);
280 const float h = std::max(heights_[size_t(i)], minDepth_);
281 momentumX_[size_t(i)] += dx * inv * radialSpeed * w * h;
282 momentumZ_[size_t(i)] += dz * inv * radialSpeed * w * h;
283 }
284 }
285 }
286 return Result<void>::success();
287}
288
289Result<void> ShallowWaterField::addImpulse(float worldX, float worldZ, float radius, float strength) {
290 const float radial = std::abs(strength) * 1.5f;
291 return disturbAt(worldX, worldZ, radius, strength, strength >= 0.f ? radial : -radial);
292}
293
294float ShallowWaterField::surfaceHeightAt(float worldX, float worldZ) const noexcept {
295 float fx = 0.f, fz = 0.f;
296 worldToCell(worldX, worldZ, fx, fz);
297 const int x0 = int(std::floor(fx));
298 const int z0 = int(std::floor(fz));
299 const float tx = fx - float(x0);
300 const float tz = fz - float(z0);
301 auto sample = [&](int x, int z) -> float {
302 if (!inside(x, z)) return origin_.y;
303 const int i = index(x, z);
304 return beds_[size_t(i)] + heights_[size_t(i)];
305 };
306 const float s00 = sample(x0, z0);
307 const float s10 = sample(x0 + 1, z0);
308 const float s01 = sample(x0, z0 + 1);
309 const float s11 = sample(x0 + 1, z0 + 1);
310 const float a = s00 * (1.f - tx) + s10 * tx;
311 const float b = s01 * (1.f - tx) + s11 * tx;
312 return a * (1.f - tz) + b * tz;
313}
314
315float ShallowWaterField::depthAt(float worldX, float worldZ) const noexcept {
316 float fx = 0.f, fz = 0.f;
317 worldToCell(worldX, worldZ, fx, fz);
318 const int x0 = int(std::floor(fx));
319 const int z0 = int(std::floor(fz));
320 const float tx = fx - float(x0);
321 const float tz = fz - float(z0);
322 auto sample = [&](int x, int z) -> float {
323 if (!inside(x, z)) return 0.f;
324 return heights_[size_t(index(x, z))];
325 };
326 const float a = sample(x0, z0) * (1.f - tx) + sample(x0 + 1, z0) * tx;
327 const float b = sample(x0, z0 + 1) * (1.f - tx) + sample(x0 + 1, z0 + 1) * tx;
328 return a * (1.f - tz) + b * tz;
329}
330
331glm::vec2 ShallowWaterField::velocityAt(float worldX, float worldZ) const noexcept {
332 float fx = 0.f, fz = 0.f;
333 worldToCell(worldX, worldZ, fx, fz);
334 const int x0 = int(std::floor(fx));
335 const int z0 = int(std::floor(fz));
336 const float tx = fx - float(x0);
337 const float tz = fz - float(z0);
338 auto sample = [&](int x, int z) -> glm::vec2 {
339 if (!inside(x, z)) return {0.f, 0.f};
340 const int i = index(x, z);
341 const float h = std::max(heights_[size_t(i)], minDepth_);
342 return {momentumX_[size_t(i)] / h, momentumZ_[size_t(i)] / h};
343 };
344 const glm::vec2 a = sample(x0, z0) * (1.f - tx) + sample(x0 + 1, z0) * tx;
345 const glm::vec2 b = sample(x0, z0 + 1) * (1.f - tx) + sample(x0 + 1, z0 + 1) * tx;
346 return a * (1.f - tz) + b * tz;
347}
348
350 std::vector<float>& uvsST, std::vector<uint32_t>& indices,
351 float visualHeightGain, std::vector<float>* colorsRGBA) const {
352 if (!(visualHeightGain > 0.f) || visualHeightGain > 32.f || !std::isfinite(visualHeightGain))
353 return fail("visualHeightGain must be in (0, 32]");
354
355 const int vx = resX_;
356 const int vz = resZ_;
357 positionsXYZ.resize(size_t(vx * vz) * 3u);
358 normalsXYZ.resize(size_t(vx * vz) * 3u);
359 uvsST.resize(size_t(vx * vz) * 2u);
360 if (colorsRGBA) colorsRGBA->assign(size_t(vx * vz) * 4u, 1.f);
361 indices.clear();
362 indices.reserve(size_t((vx - 1) * (vz - 1) * 6));
363
364 // Rest depth ≈ mean filled depth; used only for display exaggeration / vertex tint.
365 float restDepth = 0.f;
366 for (float h : heights_) restDepth += h;
367 restDepth /= float(std::max(cellCount(), 1));
368
369 for (int z = 0; z < vz; ++z) {
370 for (int x = 0; x < vx; ++x) {
371 const int i = index(x, z);
372 const size_t p = size_t(i) * 3u;
373 const size_t u = size_t(i) * 2u;
374 const float h = heights_[size_t(i)];
375 const float reference = restDepths_[size_t(i)];
376 const float y = beds_[size_t(i)] + std::max(0.f, reference + (h - reference) * visualHeightGain);
377 positionsXYZ[p] = origin_.x + (float(x) + 0.5f) * cellSize_;
378 positionsXYZ[p + 1] = y;
379 positionsXYZ[p + 2] = origin_.z + (float(z) + 0.5f) * cellSize_;
380 uvsST[u] = float(x) / float(std::max(vx - 1, 1));
381 uvsST[u + 1] = float(z) / float(std::max(vz - 1, 1));
382
383 if (colorsRGBA) {
384 // Match copyFieldToImage crest-heat packing so vertex colours carry depth/velocity.
385 constexpr float kVelScale = 1.5f;
386 const float depthContrast =
387 std::max(0.12f * std::max(restDepth, 1e-3f), 1e-3f);
388 const float invH = 1.f / std::max(h, minDepth_);
389 const float vxCell = momentumX_[size_t(i)] * invH;
390 const float vzCell = momentumZ_[size_t(i)] * invH;
391 const float speed = std::sqrt(vxCell * vxCell + vzCell * vzCell);
392 const size_t c = size_t(i) * 4u;
393 (*colorsRGBA)[c] = std::clamp((h - restDepth) / depthContrast, 0.f, 1.f);
394 (*colorsRGBA)[c + 1] = 0.5f + 0.5f * std::clamp(vxCell / kVelScale, -1.f, 1.f);
395 (*colorsRGBA)[c + 2] = 0.5f + 0.5f * std::clamp(vzCell / kVelScale, -1.f, 1.f);
396 (*colorsRGBA)[c + 3] = std::clamp(speed / kVelScale, 0.f, 1.f);
397 }
398 }
399 }
400 for (int z = 0; z < vz; ++z) {
401 for (int x = 0; x < vx; ++x) {
402 const auto pos = [&](int cx, int cz) -> glm::vec3 {
403 cx = std::clamp(cx, 0, vx - 1);
404 cz = std::clamp(cz, 0, vz - 1);
405 const size_t p = size_t(index(cx, cz)) * 3u;
406 return {positionsXYZ[p], positionsXYZ[p + 1], positionsXYZ[p + 2]};
407 };
408 const glm::vec3 dx = pos(x + 1, z) - pos(x - 1, z);
409 const glm::vec3 dz = pos(x, z + 1) - pos(x, z - 1);
410 glm::vec3 n = glm::normalize(glm::cross(dz, dx));
411 if (!std::isfinite(n.x) || !std::isfinite(n.y) || !std::isfinite(n.z)) n = {0.f, 1.f, 0.f};
412 const size_t p = size_t(index(x, z)) * 3u;
413 normalsXYZ[p] = n.x;
414 normalsXYZ[p + 1] = n.y;
415 normalsXYZ[p + 2] = n.z;
416 }
417 }
418 for (int z = 0; z < vz - 1; ++z) {
419 for (int x = 0; x < vx - 1; ++x) {
420 const uint32_t i00 = uint32_t(index(x, z));
421 const uint32_t i10 = uint32_t(index(x + 1, z));
422 const uint32_t i01 = uint32_t(index(x, z + 1));
423 const uint32_t i11 = uint32_t(index(x + 1, z + 1));
424 indices.push_back(i00);
425 indices.push_back(i01);
426 indices.push_back(i10);
427 indices.push_back(i10);
428 indices.push_back(i01);
429 indices.push_back(i11);
430 }
431 }
432 return Result<void>::success();
433}
434
435namespace {
436
437[[nodiscard]] uint8_t toU8(float v) noexcept {
438 return uint8_t(std::lround(std::clamp(v, 0.f, 1.f) * 255.f));
439}
440
442 if (image.getFormat() != "RGBA8" || image.getWidth() != resX || image.getHeight() != resZ || !image.getData())
443 return fail("field image must be RGBA8 with width=resolutionX and height=resolutionZ");
444 return Result<void>::success();
445}
446
447} // namespace
448
450 float depthContrast) const {
451 if (auto shape = requireRgbaGrid(image, resX_, resZ_); !shape) return shape;
452 if (!(velocityScale > 0.f) || velocityScale > 50.f || !std::isfinite(velocityScale))
453 return fail("velocityScale must be in (0, 50]");
454 if (!std::isfinite(depthContrast) || depthContrast > maxDepth_)
455 return fail("depthContrast must be finite and <= maxDepth");
456
457 float meanH = 0.f;
458 if (depthContrast > 0.f) {
459 for (float h : heights_) meanH += h;
460 meanH /= float(std::max(cellCount(), 1));
461 }
462
463 auto* pixels = static_cast<uint8_t*>(image.getData());
464 for (int z = 0; z < resZ_; ++z) {
465 for (int x = 0; x < resX_; ++x) {
466 const int i = index(x, z);
467 const float h = heights_[size_t(i)];
468 const float invH = 1.f / std::max(h, minDepth_);
469 const float vx = momentumX_[size_t(i)] * invH;
470 const float vz = momentumZ_[size_t(i)] * invH;
471 const float speed = std::sqrt(vx * vx + vz * vz);
472 const size_t p = size_t(z * resX_ + x) * 4u;
473 // Crest heat (not mid-gray bipolar): rest stays near black in R so G/B flow
474 // reads as teal, and raised water lights up red.
475 if (depthContrast > 0.f)
476 pixels[p + 0] = toU8(std::clamp((h - meanH) / depthContrast, 0.f, 1.f));
477 else
478 pixels[p + 0] = toU8(h / std::max(maxDepth_, 1e-4f));
479 pixels[p + 1] = toU8(0.5f + 0.5f * std::clamp(vx / velocityScale, -1.f, 1.f));
480 pixels[p + 2] = toU8(0.5f + 0.5f * std::clamp(vz / velocityScale, -1.f, 1.f));
481 pixels[p + 3] = toU8(std::clamp(speed / velocityScale, 0.f, 1.f));
482 }
483 }
484 return Result<void>::success();
485}
486
488 float velocityScale) const {
489 if (auto shape = requireRgbaGrid(image, resX_, resZ_); !shape) return shape;
490 if (!(restDepth > 0.f) || restDepth > maxDepth_ || !std::isfinite(restDepth))
491 return fail("restDepth must be in (0, maxDepth]");
492 if (!(velocityScale > 0.f) || velocityScale > 50.f || !std::isfinite(velocityScale))
493 return fail("velocityScale must be in (0, 50]");
494
495 auto* pixels = static_cast<uint8_t*>(image.getData());
496 const float invRest = 1.f / restDepth;
497 for (int z = 0; z < resZ_; ++z) {
498 for (int x = 0; x < resX_; ++x) {
499 const int i = index(x, z);
500 const float h = heights_[size_t(i)];
501 const float invH = 1.f / std::max(h, minDepth_);
502 const float vx = momentumX_[size_t(i)] * invH;
503 const float vz = momentumZ_[size_t(i)] * invH;
504 const float speed = std::sqrt(vx * vx + vz * vz);
505 // Strong gain so centimetre-scale waves still read as clear crests/troughs.
506 const float anomaly = std::clamp((h - restDepth) * invRest * 14.f, -1.f, 1.f);
507 const float foam = std::clamp(speed / (velocityScale * 0.45f), 0.f, 1.f);
508 const float flowX = std::clamp(vx / velocityScale, -1.f, 1.f);
509 const float flowZ = std::clamp(vz / velocityScale, -1.f, 1.f);
510 const float crest = 0.5f + 0.5f * anomaly;
511
512 // Deep navy → bright turquoise with magenta/lime flow tint + white foam.
513 float r = 0.02f + 0.55f * crest + 0.35f * std::max(0.f, flowX);
514 float g = 0.12f + 0.70f * crest + 0.30f * std::max(0.f, flowZ);
515 float b = 0.28f + 0.65f * crest + 0.20f * std::max(0.f, -flowX);
516 r = r * (1.f - foam) + foam;
517 g = g * (1.f - foam) + foam;
518 b = b * (1.f - 0.75f * foam) + 0.75f * foam;
519
520 const size_t p = size_t(z * resX_ + x) * 4u;
521 pixels[p + 0] = toU8(r);
522 pixels[p + 1] = toU8(g);
523 pixels[p + 2] = toU8(b);
524 pixels[p + 3] = toU8(0.78f + 0.22f * foam);
525 }
526 }
527 return Result<void>::success();
528}
529
531 if (auto shape = requireRgbaGrid(image, resX_, resZ_); !shape) return shape;
532 if (!(normalStrength > 0.f) || normalStrength > 64.f || !std::isfinite(normalStrength))
533 return fail("normalStrength must be in (0, 64]");
534
535 auto* pixels = static_cast<uint8_t*>(image.getData());
536 for (int z = 0; z < resZ_; ++z) {
537 for (int x = 0; x < resX_; ++x) {
538 const auto sampleH = [&](int cx, int cz) -> float {
539 cx = std::clamp(cx, 0, resX_ - 1);
540 cz = std::clamp(cz, 0, resZ_ - 1);
541 const int i = index(cx, cz);
542 return beds_[size_t(i)] + heights_[size_t(i)];
543 };
544 const float dHx = (sampleH(x + 1, z) - sampleH(x - 1, z)) / (2.f * cellSize_);
545 const float dHz = (sampleH(x, z + 1) - sampleH(x, z - 1)) / (2.f * cellSize_);
546 // Tangent-space normal with Z-up (OpenGL-style normal maps).
547 glm::vec3 n{-dHx * normalStrength, -dHz * normalStrength, 1.f};
548 n = glm::normalize(n);
549 if (!std::isfinite(n.x) || !std::isfinite(n.y) || !std::isfinite(n.z)) n = {0.f, 0.f, 1.f};
550
551 const size_t p = size_t(z * resX_ + x) * 4u;
552 pixels[p + 0] = toU8(0.5f + 0.5f * n.x);
553 pixels[p + 1] = toU8(0.5f + 0.5f * n.y);
554 pixels[p + 2] = toU8(0.5f + 0.5f * n.z);
555 pixels[p + 3] = 255;
556 }
557 }
558 return Result<void>::success();
559}
560
561void ShallowWaterField::rasterizeCollidersCpu(float dt) {
562 std::fill(srcH_.begin(), srcH_.end(), 0.f);
563 std::fill(srcHu_.begin(), srcHu_.end(), 0.f);
564 std::fill(srcHv_.begin(), srcHv_.end(), 0.f);
565 if (colliders_.empty() || !(dt > 0.f)) return;
566
567 const float coverRadius = cellSize_ * 0.75f;
568 const float maxSrcH = maxDepth_ * 0.15f;
569 for (int z = 0; z < resZ_; ++z) {
570 for (int x = 0; x < resX_; ++x) {
571 const int i = index(x, z);
572 const float wx = origin_.x + (float(x) + 0.5f) * cellSize_;
573 const float wz = origin_.z + (float(z) + 0.5f) * cellSize_;
574 if (heights_[size_t(i)] <= minDepth_) continue;
575 const float surfaceY = beds_[size_t(i)] + heights_[size_t(i)];
576 for (const auto& c : colliders_) {
577 const float dist = colliderFootprintDistance(c, wx, wz);
578 if (dist >= coverRadius) continue;
579 const float immersion = colliderImmersion(c, surfaceY);
580 if (immersion <= 1e-4f) continue;
581 const float cover = std::clamp(1.f - dist / coverRadius, 0.f, 1.f);
582 // Rates × substep dt — absolute sources stacked with CFL substeps
583 // previously grew into multi-meter height spikes.
584 const float push = immersion * cover * c.displacementScale * dt;
585 float dx = wx - c.center.x;
586 float dz = wz - c.center.z;
587 const float olen = std::sqrt(dx * dx + dz * dz);
588 if (olen > 1e-5f) {
589 dx /= olen;
590 dz /= olen;
591 } else {
592 dx = 0.f;
593 dz = 1.f;
594 }
595 const float radial = push * 1.f;
596 const float h = std::max(heights_[size_t(i)], minDepth_);
597 srcH_[size_t(i)] -= push * 0.35f;
598 srcHu_[size_t(i)] += (dx * radial + c.velocity.x * c.dragScale * dt) * h;
599 srcHv_[size_t(i)] += (dz * radial + c.velocity.z * c.dragScale * dt) * h;
600 srcH_[size_t(i)] += std::max(0.f, -c.velocity.y) * cover * 0.15f * c.displacementScale * dt;
601 }
602 srcH_[size_t(i)] = std::clamp(srcH_[size_t(i)], -maxSrcH, maxSrcH);
603 }
604 }
605}
606
607void ShallowWaterField::integrateCpu(float dt) {
608 auto sample = [&](int x, int z, float& h, float& hu, float& hv) {
609 x = std::clamp(x, 0, resX_ - 1);
610 z = std::clamp(z, 0, resZ_ - 1);
611 const int i = index(x, z);
612 h = std::max(heights_[size_t(i)] + srcH_[size_t(i)], 0.f);
613 hu = momentumX_[size_t(i)] + srcHu_[size_t(i)];
614 hv = momentumZ_[size_t(i)] + srcHv_[size_t(i)];
615 if (!std::isfinite(h)) h = 0.f;
616 if (!std::isfinite(hu)) hu = 0.f;
617 if (!std::isfinite(hv)) hv = 0.f;
618 };
619 auto sampleBed = [&](int x, int z) {
620 x = std::clamp(x, 0, resX_ - 1);
621 z = std::clamp(z, 0, resZ_ - 1);
622 return beds_[size_t(index(x, z))];
623 };
624
625 for (int z = 0; z < resZ_; ++z) {
626 for (int x = 0; x < resX_; ++x) {
627 float h = 0, hu = 0, hv = 0;
628 float hL = 0, huL = 0, hvL = 0;
629 float hR = 0, huR = 0, hvR = 0;
630 float hD = 0, huD = 0, hvD = 0;
631 float hU = 0, huU = 0, hvU = 0;
632 sample(x, z, h, hu, hv);
633 sample(x - 1, z, hL, huL, hvL);
634 sample(x + 1, z, hR, huR, hvR);
635 sample(x, z - 1, hD, huD, hvD);
636 sample(x, z + 1, hU, huU, hvU);
637
638 const glm::vec3 q{h, hu, hv};
639 const glm::vec3 qL{hL, huL, hvL};
640 const glm::vec3 qR{hR, huR, hvR};
641 const glm::vec3 qD{hD, huD, hvD};
642 const glm::vec3 qU{hU, huU, hvU};
643
644 const float bed = sampleBed(x, z);
645 const glm::vec3 fR = bedFlux(q, qR, bed, sampleBed(x + 1, z), gravity_, minDepth_, false, true);
646 const glm::vec3 fL = bedFlux(qL, q, sampleBed(x - 1, z), bed, gravity_, minDepth_, false, false);
647 const glm::vec3 fU = bedFlux(q, qU, bed, sampleBed(x, z + 1), gravity_, minDepth_, true, true);
648 const glm::vec3 fD = bedFlux(qD, q, sampleBed(x, z - 1), bed, gravity_, minDepth_, true, false);
649 glm::vec3 qn = q - (dt / cellSize_) * (fR - fL + fU - fD);
650 // dt-scaled Laplacian viscosity (was previously unscaled and blew up).
651 qn.y += viscosity_ * dt * (huL + huR + huD + huU - 4.f * hu);
652 qn.z += viscosity_ * dt * (hvL + hvR + hvD + hvU - 4.f * hv);
653 qn.y *= std::max(0.f, 1.f - friction_ * dt);
654 qn.z *= std::max(0.f, 1.f - friction_ * dt);
655 qn.x = std::clamp(qn.x, 0.f, maxDepth_);
656 if (!std::isfinite(qn.x)) qn.x = 0.f;
657 if (!std::isfinite(qn.y)) qn.y = 0.f;
658 if (!std::isfinite(qn.z)) qn.z = 0.f;
659 if (qn.x <= minDepth_) {
660 qn.y = 0.f;
661 qn.z = 0.f;
662 } else {
663 // Cap horizontal speed so a single splash cannot break CFL next step.
664 const float speed = std::sqrt(qn.y * qn.y + qn.z * qn.z) / std::max(qn.x, minDepth_);
665 const float maxSpeed = 8.f;
666 if (speed > maxSpeed) {
667 const float s = maxSpeed / speed;
668 qn.y *= s;
669 qn.z *= s;
670 }
671 }
672 if (x == 0 || x == resX_ - 1) qn.y = 0.f;
673 if (z == 0 || z == resZ_ - 1) qn.z = 0.f;
674
675 const int i = index(x, z);
676 scratchH_[size_t(i)] = qn.x;
677 scratchHu_[size_t(i)] = qn.y;
678 scratchHv_[size_t(i)] = qn.z;
679 }
680 }
681 heights_.swap(scratchH_);
682 momentumX_.swap(scratchHu_);
683 momentumZ_.swap(scratchHv_);
684}
685
686void ShallowWaterField::stepCpu(float dt) {
687 rasterizeCollidersCpu(dt);
688 integrateCpu(dt);
689}
690
692 if (!std::isfinite(dt) || dt < 0.f) return fail("dt must be finite and >= 0");
693 if (dt == 0.f) return Result<void>::success();
694 // Long first frames after engine startup commonly exceed 1s; advance in
695 // capped chunks instead of rejecting the call.
696 float remaining = std::min(dt, 5.f);
697 while (remaining > 1e-6f) {
698 const float chunk = std::min(remaining, 1.f / 20.f); // <= 50 ms chunks
699 float maxH = minDepth_;
700 float maxVel = 0.f;
701 for (int i = 0; i < cellCount(); ++i) {
702 maxH = std::max(maxH, heights_[size_t(i)]);
703 const float h = std::max(heights_[size_t(i)], minDepth_);
704 const float u = momentumX_[size_t(i)] / h;
705 const float v = momentumZ_[size_t(i)] / h;
706 maxVel = std::max(maxVel, std::sqrt(u * u + v * v));
707 }
708 const float waveSpeed = std::sqrt(gravity_ * maxH) + maxVel + 1.f;
709 const float safeDt = 0.5f * cfl_ * cellSize_ / std::max(waveSpeed, 1e-3f);
710 int substeps = std::clamp(int(std::ceil(chunk / safeDt)), 1, maxSubsteps_);
711 const float subDt = chunk / float(substeps);
712
713 bool advanced = false;
714 if (preferGpu_) {
715 if (ensureGpu()) {
716 auto gpu = stepGpu(chunk);
717 if (gpu) {
718 advanced = true;
719 } else {
720 backendFallback_ = true;
721 gpuOk_ = false;
722 }
723 } else {
724 backendFallback_ = true;
725 }
726 }
727 if (!advanced) {
728 for (int i = 0; i < substeps; ++i) stepCpu(subDt);
729 stateOnGpu_ = false;
730 }
731 remaining -= chunk;
732 }
733 return Result<void>::success();
734}
735
736bool ShallowWaterField::ensureGpu() {
737 if (gpuOk_) return true;
738 gpgpu_ = eve::gpgpu::Gpgpu::create();
739 if (!gpgpu_ || !gpgpu_->isAvailable()) return false;
740 const int cells = cellCount();
741 try {
742 shClear_ = gpgpu_->newShader(kShallowWaterClearSources);
743 shRaster_ = gpgpu_->newShader(kShallowWaterRasterizeColliders);
744 shIntegrate_ = gpgpu_->newShader(kShallowWaterIntegrate);
745 bufStateA_ = gpgpu_->newBuffer(cells * 4 * int(sizeof(float)), "storage");
746 bufStateB_ = gpgpu_->newBuffer(cells * 4 * int(sizeof(float)), "storage");
747 bufBed_ = gpgpu_->newBuffer(cells * int(sizeof(float)), "storage");
748 bufSources_ = gpgpu_->newBuffer(cells * 4 * int(sizeof(float)), "storage");
749 bufColliders_ = gpgpu_->newBuffer(64 * 16 * int(sizeof(float)), "storage");
750 stageState_ = gpgpu_->newBuffer(cells * 4 * int(sizeof(float)), "staging");
751 seq_ = gpgpu_->newSequence();
752 } catch (...) {
753 return false;
754 }
755 if (!seq_ || !seq_->isAvailable() || !shClear_ || !shRaster_ || !shIntegrate_) return false;
756
757 shClear_->bindBuffer(3, bufSources_);
758 shRaster_->bindBuffer(0, bufStateA_);
759 shRaster_->bindBuffer(2, bufBed_);
760 shRaster_->bindBuffer(3, bufSources_);
761 shRaster_->bindBuffer(4, bufColliders_);
762 shIntegrate_->bindBuffer(0, bufStateA_);
763 shIntegrate_->bindBuffer(1, bufStateB_);
764 shIntegrate_->bindBuffer(2, bufBed_);
765 shIntegrate_->bindBuffer(3, bufSources_);
766 bufBed_->writeFloat32s(beds_.data(), int(beds_.size()));
767 gpuOk_ = true;
768 stateOnGpu_ = false;
769 pingA_ = true;
770 return true;
771}
772
773void ShallowWaterField::setPushConstants(gpgpu::ComputeShader* shader, float dt) const {
774 if (!shader) return;
775 shader->setFloat(kPushResX, float(resX_));
776 shader->setFloat(kPushResZ, float(resZ_));
777 shader->setFloat(kPushCell, cellSize_);
778 shader->setFloat(kPushDt, dt);
779 shader->setFloat(kPushGravity, gravity_);
780 shader->setFloat(kPushViscosity, viscosity_);
781 shader->setFloat(kPushFriction, friction_);
782 shader->setFloat(kPushMinDepth, minDepth_);
783 shader->setFloat(kPushMaxDepth, maxDepth_);
784 shader->setFloat(kPushColliderCount, float(colliders_.size()));
785 shader->setFloat(kPushOriginX, origin_.x);
786 shader->setFloat(kPushOriginY, origin_.y);
787 shader->setFloat(kPushOriginZ, origin_.z);
788}
789
790void ShallowWaterField::uploadState() {
791 std::vector<float> packed(size_t(cellCount()) * 4u, 0.f);
792 for (int i = 0; i < cellCount(); ++i) {
793 const size_t b = size_t(i) * 4u;
794 packed[b] = heights_[size_t(i)];
795 packed[b + 1] = momentumX_[size_t(i)];
796 packed[b + 2] = momentumZ_[size_t(i)];
797 }
798 auto* dst = pingA_ ? bufStateA_ : bufStateB_;
799 seq_->recordUpload(dst, packed.data(), uint64_t(packed.size()) * sizeof(float));
800}
801
802void ShallowWaterField::downloadState() {
803 auto* src = pingA_ ? bufStateA_ : bufStateB_;
804 seq_->recordDownload(src, stageState_, uint64_t(cellCount()) * 4u * sizeof(float));
805}
806
807void ShallowWaterField::uploadColliders() {
808 std::vector<float> packed(64u * 16u, 0.f);
809 for (size_t i = 0; i < colliders_.size(); ++i) {
810 const auto& c = colliders_[i];
811 float* d = packed.data() + i * 16u;
812 d[0] = c.center.x;
813 d[1] = c.center.y;
814 d[2] = c.center.z;
815 d[3] = c.radius;
816 d[4] = c.halfExtent.x;
817 d[5] = c.halfExtent.y;
818 d[6] = c.halfExtent.z;
819 d[7] = float(c.shape);
820 d[8] = c.velocity.x;
821 d[9] = c.velocity.y;
822 d[10] = c.velocity.z;
823 d[11] = c.displacementScale;
824 d[12] = c.dragScale;
825 }
826 seq_->recordUpload(bufColliders_, packed.data(), uint64_t(packed.size()) * sizeof(float));
827}
828
829Result<void> ShallowWaterField::stepGpu(float dt) {
830 float maxH = minDepth_, maxVel = 0.f;
831 for (size_t i = 0; i < heights_.size(); ++i) {
832 maxH = std::max(maxH, heights_[i]);
833 const float h = std::max(heights_[i], minDepth_);
834 maxVel = std::max(maxVel, std::hypot(momentumX_[i], momentumZ_[i]) / h);
835 }
836 const float waveSpeed = std::sqrt(gravity_ * maxH) + maxVel + 1.f;
837 const float safeDt = 0.5f * cfl_ * cellSize_ / std::max(waveSpeed, 1e-3f);
838 const int substeps = std::clamp(int(std::ceil(dt / safeDt)), 1, maxSubsteps_);
839 const float subDt = dt / float(substeps);
840 const int groupsX = (resX_ + 7) / 8;
841 const int groupsZ = (resZ_ + 7) / 8;
842
843 try {
844 seq_->begin();
845 if (!stateOnGpu_) uploadState();
846 uploadColliders();
847 for (int s = 0; s < substeps; ++s) {
848 auto* src = pingA_ ? bufStateA_ : bufStateB_;
849 auto* dst = pingA_ ? bufStateB_ : bufStateA_;
850 shClear_->bindBuffer(3, bufSources_);
851 setPushConstants(shClear_, subDt);
852 seq_->recordDispatch(shClear_, groupsX, groupsZ);
853
854 shRaster_->bindBuffer(0, src);
855 shRaster_->bindBuffer(2, bufBed_);
856 shRaster_->bindBuffer(3, bufSources_);
857 shRaster_->bindBuffer(4, bufColliders_);
858 setPushConstants(shRaster_, subDt);
859 seq_->recordDispatch(shRaster_, groupsX, groupsZ);
860
861 shIntegrate_->bindBuffer(0, src);
862 shIntegrate_->bindBuffer(1, dst);
863 shIntegrate_->bindBuffer(2, bufBed_);
864 shIntegrate_->bindBuffer(3, bufSources_);
865 setPushConstants(shIntegrate_, subDt);
866 seq_->recordDispatch(shIntegrate_, groupsX, groupsZ);
867 pingA_ = !pingA_;
868 }
869 downloadState();
870 seq_->submit();
871 std::vector<float> packed(size_t(cellCount()) * 4u, 0.f);
872 stageState_->downloadBytes(packed.data(), uint64_t(packed.size()) * sizeof(float));
873 for (int i = 0; i < cellCount(); ++i) {
874 const size_t b = size_t(i) * 4u;
875 heights_[size_t(i)] = packed[b];
876 momentumX_[size_t(i)] = packed[b + 1];
877 momentumZ_[size_t(i)] = packed[b + 2];
878 }
879 stateOnGpu_ = true;
880 return Result<void>::success();
881 } catch (const std::exception& error) {
883 std::string("Shallow-water GPU step failed: ") + error.what(),
884 "fluids.shallowWater.gpu"));
885 } catch (...) {
887 Diagnostic::error(DiagnosticCode::Failed, "Shallow-water GPU step failed", "fluids.shallowWater.gpu"));
888 }
889}
890
891} // namespace eve::fluids
double z
double y
double x
float w
Definition AnimClip.cpp:738
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
const std::string & s
float normalStrength
float cx
Definition CardTypes.cpp:36
glm::vec4 p[6]
Stable, structured diagnostics shared by engine modules.
float strength
ScriptForceVector gravity
float friction
std::string message
tensor::Graph g
Definition GpuGraph.cpp:7
ShaderImageInput shape
vk::UniqueImage image
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
double r
std::vector< std::uint32_t > indices
float v
std::int32_t c
int h
JointPoint2D axis
std::string label
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanWakeSettings settings
std::shared_ptr< OceanGpuSpectrum > gpu
glm::dvec3 origin
glm::dvec3 dx
glm::dvec3 dz
double dt
std::string error
Definition Package.cpp:174
float f
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
float d
uint8_t * pixels
Shader * shader
float axisZ
Definition RockMesh.cpp:22
std::uint32_t depth
uint32_t index
std::vector< char > inside
double ox
float bottom
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
GPU-first shallow-water (2D Saint-Venant) free-surface solver.
float depthAt(float worldX, float worldZ) const noexcept
Bilinear water depth at a world XZ point.
Result< void > fillSurface(float surfaceY)
Fill to a world-space free-surface elevation, leaving high terrain dry.
Result< void > fillDepth(float depth)
Fill every cell with a uniform water depth (momentum cleared).
std::span< const float > beds() const noexcept
Result< void > setBed(std::span< const float > beds)
Replace bed heights; call fillSurface afterwards to initialize a level lake.
Result< void > step(float dt)
Advance the free surface by dt seconds (CFL substeps).
Result< void > copyNormalToImage(image::ImageData &image, float normalStrength=6.f) const
Write tangent-space normals from free-surface slopes (RGBA8, same grid size).
Result< void > addImpulse(float worldX, float worldZ, float radius, float strength)
Convenience splash: positive strength raises water, negative digs.
Result< void > disturbAt(float worldX, float worldZ, float radius, float heightDelta, float radialSpeed=0.f)
Inject a localized height bump and radial outflow (mouse / splash).
Result< void > buildSurfaceMesh(std::vector< float > &positionsXYZ, std::vector< float > &normalsXYZ, std::vector< float > &uvsST, std::vector< uint32_t > &indices, float visualHeightGain=1.f, std::vector< float > *colorsRGBA=nullptr) const
Build a Y-up triangle mesh of the free surface for Graphics upload.
Result< void > copyFieldToImage(image::ImageData &image, float velocityScale=2.f, float depthContrast=0.f) const
Pack per-cell depth / velocity into an RGBA8 image (resolutionX × resolutionZ).
static Result< std::unique_ptr< ShallowWaterField > > create(const ShallowWaterSettings &settings)
Validate settings and allocate a filled lake.
glm::vec2 velocityAt(float worldX, float worldZ) const noexcept
Bilinear horizontal velocity at a world XZ point.
float surfaceHeightAt(float worldX, float worldZ) const noexcept
Bilinear free-surface height b + h at a world XZ point.
Result< void > copyShadedAlbedoToImage(image::ImageData &image, float restDepth, float velocityScale=2.f) const
Write a shaded water albedo (RGBA8, same size as the grid) for Material upload.
Result< void > setColliders(std::span< const ShallowWaterCollider > colliders)
Replace analytic interactors atomically.
ShallowWaterField(const ShallowWaterField &)=delete
std::span< const ShallowWaterCollider > colliders() const noexcept
ShallowWaterSettings settings() const noexcept
virtual void bindBuffer(int binding, GpuBuffer *buffer)=0
Bind a storage buffer to set=0 binding. binding in [0, kMaxBindings).
ComputeShader * newShader(const std::string &source)
Compatibility-only raw-owning shader factory (Vulkan: GLSL; WebGPU: WGSL). Vulkan delegates to the ch...
Definition Gpgpu.cpp:324
bool isAvailable() const
True when the active Graphics backend can run compute (device initialized).
Definition Gpgpu.cpp:284
GpuBuffer * newBuffer(int byteSize, const std::string &usage="storage")
Allocate a GPU buffer. usage: "storage" (SSBO) | "staging" (host transfer) | "storage_vertex" (Vulkan...
Definition Gpgpu.cpp:372
Sequence * newSequence()
Create a Kompute-style command Sequence: record buffer transfers and compute dispatches into one comm...
Definition Gpgpu.cpp:384
virtual void writeFloat32s(const float *data, int count, int startIndex=0)=0
Bulk float upload/download (one transfer). startIndex is in floats.
virtual void downloadBytes(void *dst, uint64_t nbytes, uint64_t srcOffset=0) const =0
Downloads bytes.
void recordUpload(GpuBuffer *dst, const void *src, uint64_t nbytes, uint64_t dstOffset=0)
Record upload.
Definition Sequence.cpp:77
void recordDownload(GpuBuffer *src, GpuBuffer *staging, uint64_t nbytes, uint64_t srcOffset=0)
Record download.
Definition Sequence.cpp:82
void submit()
Submit.
Definition Sequence.cpp:92
void recordDispatch(ComputeShader *shader, int groupsX, int groupsY=1, int groupsZ=1)
Record dispatch.
Definition Sequence.cpp:87
void begin()
Begins begin.
Definition Sequence.cpp:75
bool isAvailable() const
True when available.
Definition Sequence.cpp:66
Represents raw pixel data.
Definition ImageData.h:38
SQInteger top
Definition Snapshot.cpp:115
Result< T > fail(std::string message, DiagnosticCode code=DiagnosticCode::InvalidArgument)
const Value & field(const Value &value, const char *name)
Borrow a required child of value; throws on a missing field.
GLSL compute kernels for the GPU surface-flow solver.
Definition FluidTarget.h:12
const char * kShallowWaterClearSources
Zero the per-cell impulse source buffer. @lifetime The returned pointer remains valid for the process...
const char * kShallowWaterIntegrate
Apply source impulses then advance one Lax-Friedrichs shallow-water step. @lifetime The returned poin...
const char * kShallowWaterRasterizeColliders
Rasterize sphere/capsule/box colliders into height/momentum sources. @lifetime The returned pointer r...
double sample(const Heightmap &map, double u, double v)
Sample.
Authoritative settings for a shallow-water heightfield.
float initialDepth
Initial water depth filled on create.
int resolutionZ
Grid resolution along world Z, in [8, 512].
glm::vec3 origin
World-space origin of cell (0,0) corner (Y is bed baseline).
float cellSize
Cell edge length in meters, in (0, 10].
float cfl
Courant number used to pick substeps.
int resolutionX
Grid resolution along world X, in [8, 512].
float viscosity
Artificial viscosity for Lax-Friedrichs stability, in [0, 1].
float minDepth
Depth treated as dry.
float gravity
Gravity magnitude used by Saint-Venant fluxes.
int maxSubsteps
Upper bound on substeps per step call.
float maxDepth
Hard clamp on water column height.
float friction
Linear momentum friction per second, in [0, 8].
float bedHeight
Flat bed height filled on create.