载入中...
搜索中...
未找到
AnalyticalVolLight.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <glm/common.hpp>
5#include <glm/geometric.hpp>
6#include "common/Diagnostic.h"
8
9// AnalyticalVolLight.cpp
11
12std::optional<FogRayInterval> AnalyticalVolLight::intersectBeam(const glm::vec3& origin, const glm::vec3& direction,
13 const AnalyticBeam& beam) {
14 const float dirLen = glm::length(direction);
15 const float beamLen = glm::length(beam.direction);
16 if (!(dirLen > 1e-8f) || !(beamLen > 1e-8f)) return std::nullopt;
17 if (!(beam.farDistance > beam.nearDistance) || beam.nearRadius < 0.f || beam.farRadius < 0.f) return std::nullopt;
18
19 const glm::vec3 d = direction / dirLen;
20 const glm::vec3 axis = beam.direction / beamLen;
21
22 // Project the ray onto the beam axis and keep the capped interval, then
23 // reject samples that leave the linearly interpolated radius.
24 float tEnter = 1e9f;
25 float tExit = -1e9f;
26 constexpr int kProbe = 32;
27 for (int i = 0; i <= kProbe; ++i) {
28 const float u = static_cast<float>(i) / static_cast<float>(kProbe);
29 const float along = beam.nearDistance + u * (beam.farDistance - beam.nearDistance);
30 const glm::vec3 center = beam.apex + axis * along;
31 const float radius = beam.nearRadius + u * (beam.farRadius - beam.nearRadius);
32 // Solve |o + t d - center|^2 = radius^2 for the nearest positive hit.
33 const glm::vec3 oc = origin - center;
34 const float b = glm::dot(oc, d);
35 const float c = glm::dot(oc, oc) - radius * radius;
36 const float disc = b * b - c;
37 if (disc < 0.f) continue;
38 const float s = std::sqrt(disc);
39 for (float t : {-b - s, -b + s}) {
40 if (t < 0.f) continue;
41 const glm::vec3 p = origin + d * t;
42 const float axial = glm::dot(p - beam.apex, axis);
43 if (axial < beam.nearDistance || axial > beam.farDistance) continue;
44 tEnter = std::min(tEnter, t);
45 tExit = std::max(tExit, t);
46 }
47 // Also accept the sample if the ray point at axial distance is inside.
48 const float tAxis = glm::dot(center - origin, d);
49 if (tAxis > 0.f) {
50 const glm::vec3 p = origin + d * tAxis;
51 if (glm::length(p - center) <= radius) {
52 tEnter = std::min(tEnter, tAxis);
53 tExit = std::max(tExit, tAxis);
54 }
55 }
56 }
57 if (tExit <= tEnter || tEnter > 1e8f) return std::nullopt;
58 return FogRayInterval{tEnter, tExit};
59}
60
62 const glm::vec3& origin, const glm::vec3& direction,
63 float sceneDepth, int segments, float mediumDensity) const {
64 if (segments != 2 && segments != 4 && segments != 8) {
66 DiagnosticCode::InvalidArgument, "segments must be 2, 4, or 8", "segments", {}, "graphics.fog"));
67 }
68 if (!std::isfinite(mediumDensity) || mediumDensity < 0.f) {
70 "mediumDensity must be finite and >= 0", "mediumDensity",
71 {}, "graphics.fog"));
72 }
73
74 auto interval = intersectBeam(origin, direction, beam);
76 if (!interval) return Result<FogRayResult>::success(result);
77 if (sceneDepth > 0.f) interval->tExit = std::min(interval->tExit, sceneDepth);
78 if (!interval->valid()) return Result<FogRayResult>::success(result);
79
80 const glm::vec3 dir = glm::normalize(direction);
81 const glm::vec3 axis = glm::normalize(beam.direction);
82 const float sigmaT = profile.extinctionAt(mediumDensity);
83 const glm::vec3 sigmaS = profile.scatteringAt(mediumDensity);
84 const float phase = profile.phase(glm::dot(-dir, -axis));
85
86 float T = 1.f;
87 const float seg = interval->length() / static_cast<float>(segments);
88 for (int i = 0; i < segments && T > 1e-4f; ++i) {
89 const float t = interval->tEnter + (static_cast<float>(i) + 0.5f) * seg;
90 const glm::vec3 p = origin + dir * t;
91 const float axial = glm::dot(p - beam.apex, axis);
92 const float u =
93 std::clamp((axial - beam.nearDistance) / std::max(beam.farDistance - beam.nearDistance, 1e-4f), 0.f, 1.f);
94 const float radius = beam.nearRadius + u * (beam.farRadius - beam.nearRadius);
95 const glm::vec3 center = beam.apex + axis * axial;
96 const float radial = glm::length(p - center) / std::max(radius, 1e-4f);
97 const float mask = std::clamp(1.f - radial * radial, 0.f, 1.f);
98 const float stepT = std::exp(-sigmaT * seg);
99 const glm::vec3 Li = beam.color * beam.intensity * mask * phase;
100 result.inScatter += T * sigmaS * Li * ((1.f - stepT) / std::max(sigmaT, 1e-6f));
101 T *= stepT;
102 result.opticalDepth += sigmaT * seg;
103 ++result.samplesUsed;
104 }
105 result.transmittance = T;
107}
108
109} // namespace eve::graphics::fog
110
111// BeerLightCache.cpp
112namespace eve::graphics::fog {
113
115 valid_ = false;
116 ++key_.version;
117}
118
119bool BeerLightCache::matches(std::uint64_t densityRevision, const glm::vec3& lightDir, float intensity) const noexcept {
120 if (!valid_) return false;
121 if (key_.densityRevision != densityRevision) return false;
122 if (std::fabs(key_.intensity - intensity) > 1e-5f) return false;
123 const glm::vec3 d = key_.direction - lightDir;
124 return glm::dot(d, d) < 1e-6f;
125}
126
127Result<void> BeerLightCache::rebuild(const FogDensityField& field, const FogProfile& profile, const glm::vec3& lightDir,
128 const glm::vec3& lightColor, float intensity, int samplesPerCell) {
129 if (field.width() < 2) {
131 Diagnostic::error(DiagnosticCode::Failed, "density field is empty", "rebuild", {}, "graphics.fog"));
132 }
133 if (!std::isfinite(intensity) || intensity < 0.f || samplesPerCell < 1 || samplesPerCell > 64) {
135 DiagnosticCode::InvalidArgument, "intensity/samples out of range", "rebuild", {}, "graphics.fog"));
136 }
137 const float len = glm::length(lightDir);
138 if (!(len > 1e-6f) || !std::isfinite(len)) {
140 "light direction must be non-zero and finite", "lightDir", {},
141 "graphics.fog"));
142 }
143 const glm::vec3 dir = lightDir / len;
144
145 width_ = field.width();
146 height_ = field.height();
147 depth_ = field.depth();
148 transmittance_.assign(static_cast<std::size_t>(width_) * height_ * depth_, 1.f);
149
150 const glm::vec3 cell = field.cellSize();
151 const float stepLen = 0.5f * std::min({cell.x, cell.y, cell.z});
152 const FogWorldBounds& bounds = field.bounds();
153
154 for (int z = 0; z < depth_; ++z) {
155 for (int y = 0; y < height_; ++y) {
156 for (int x = 0; x < width_; ++x) {
157 glm::vec3 p = bounds.minimum + glm::vec3((x + 0.5f) * cell.x, (y + 0.5f) * cell.y, (z + 0.5f) * cell.z);
158 float optical = 0.f;
159 for (int s = 0; s < samplesPerCell; ++s) {
160 // March toward the light (opposite the "direction toward the surface").
161 p -= dir * stepLen;
162 if (!bounds.contains(p)) break;
163 optical += profile.extinctionAt(field.sampleDensity(p)) * stepLen;
164 }
165 const std::size_t idx =
166 (static_cast<std::size_t>(z) * height_ + y) * width_ + static_cast<std::size_t>(x);
167 transmittance_[idx] = std::exp(-optical);
168 }
169 }
170 }
171
172 key_.direction = dir;
173 key_.color = lightColor;
174 key_.intensity = intensity;
175 key_.densityRevision = field.revision();
176 ++key_.version;
177 valid_ = true;
178 return Result<void>::success();
179}
180
181float BeerLightCache::sampleTransmittance(const FogDensityField& field, const glm::vec3& world) const noexcept {
182 if (!valid_ || transmittance_.empty()) return 1.f;
183 const FogWorldBounds& bounds = field.bounds();
184 const glm::vec3 cell = field.cellSize();
185 const glm::vec3 local = (world - bounds.minimum) / cell;
186 const int x = std::clamp(static_cast<int>(local.x), 0, width_ - 1);
187 const int y = std::clamp(static_cast<int>(local.y), 0, height_ - 1);
188 const int z = std::clamp(static_cast<int>(local.z), 0, depth_ - 1);
189 const std::size_t idx = (static_cast<std::size_t>(z) * height_ + y) * width_ + static_cast<std::size_t>(x);
190 return transmittance_[idx];
191}
192
193} // namespace eve::graphics::fog
double z
double y
double x
const std::string & s
int mask
glm::vec4 p[6]
Stable, structured diagnostics shared by engine modules.
float u
Definition Grass.cpp:233
std::int32_t c
JointPoint2D axis
std::string local
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
glm::dvec3 origin
glm::dvec2 center
int idx
float d
float t
RoadLaneDirection direction
float phase
Cell cell
int segments
Definition TreeMesh.cpp:281
V3 dir
Definition TreeMesh.cpp:151
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 std::optional< FogRayInterval > intersectBeam(const glm::vec3 &origin, const glm::vec3 &direction, const AnalyticBeam &beam)
Intersect a view ray with a capped beam; empty on miss.
Result< FogRayResult > integrate(const AnalyticBeam &beam, const FogProfile &profile, const glm::vec3 &origin, const glm::vec3 &direction, float sceneDepth, int segments, float mediumDensity) const
Integrate the beam contribution along a view ray.
Result< void > rebuild(const FogDensityField &field, const FogProfile &profile, const glm::vec3 &lightDir, const glm::vec3 &lightColor, float intensity, int samplesPerCell=6)
Rebuild transmittance along the primary light for each density cell.
bool matches(std::uint64_t densityRevision, const glm::vec3 &lightDir, float intensity) const noexcept
True when the cache matches the supplied state.
void invalidate()
Mark cache stale (quality change, light cut, etc.).
float sampleTransmittance(const FogDensityField &field, const glm::vec3 &world) const noexcept
Sample cached transmittance at a world position (1 = fully lit).
World-space density bands, curl assist velocity, and lighting helpers.
Unit-density optical profile for participating media.
Definition FogProfile.h:16
float extinctionAt(float density) const noexcept
Extinction for a sampled density value.
float phase(float cosTheta) const noexcept
Dual-lobe Henyey–Greenstein phase evaluated for cosθ.
glm::vec3 scatteringAt(float density) const noexcept
Scattering coefficient σ_s = albedo * σ_t.
Analytic beam volume: capped cone frustum or pyramidal spot.
Interval along a ray where media is present (t in world units).
Definition FogTypes.h:112
Optical result of integrating one view ray through fog.
Definition FogTypes.h:122
Axis-aligned world bounds for a fog simulation domain.
Definition FogTypes.h:96
glm::vec4 lightColor
glm::vec4 lightDir
glm::vec4 bounds