载入中...
搜索中...
未找到
Lightning.cpp
浏览该文件的文档.
1// eve-hot-path
2#include "weather/Lightning.h"
3#include <algorithm>
4#include <cmath>
5#include <exception>
7#include "graphics/Graphics.h"
8#include "graphics/Material.h"
9#include "graphics/Mesh.h"
11#include "graphics/Shader.h"
13#include "weather/shaders/bolt_frag_spv.inc"
14#include "weather/shaders/bolt_vert_spv.inc"
15namespace eve::weather {
16namespace {
18 return Result<void>::failure(Diagnostic::error(code, message, "weather.lightning"));
19}
20} // namespace
23 std::weak_ptr<const void> lifetime;
25 ecs::EntityHandle entity;
26 std::unique_ptr<graphics::Material> material;
28 std::vector<graphics::Mesh*> meshes;
30 double age = 0;
31 float flash = 0;
32 unsigned variant = 0;
33 bool playing = false;
35 return lifetime.expired() ? nullptr : static_cast<graphics::Renderable3D*>(ecs::try_get(entity));
36 }
37 void cleanup() {
38 if (auto* e = ecs::try_get(entity)) ecs::DestroyEntity(e);
39 entity = {};
40 playing = false;
41 flash = 0;
42 if (!lifetime.expired()) {
43 for (auto* mesh : meshes)
44 if (graphics->releaseMesh(mesh)) delete mesh;
45 if (shader && graphics->releaseShader(shader)) delete shader;
46 }
47 meshes.clear();
48 shader = nullptr;
49 material.reset();
50 }
51 ~Impl() { cleanup(); }
52};
53Lightning::Lightning(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
54Lightning::~Lightning() = default;
57 if (!valid) return Result<std::unique_ptr<Lightning>>::failure(valid.status());
58 auto impl = std::make_unique<Impl>();
59 impl->graphics = &graphics;
60 impl->lifetime = graphics.resourceLifetime();
61 impl->settings = settings;
62 auto subscription = graphics.onResourcesRetiring([state = impl.get()] { state->cleanup(); });
63 if (!subscription) return Result<std::unique_ptr<Lightning>>::failure(subscription.status());
64 impl->retiring = std::move(subscription).takeValue();
65 try {
66 impl->meshes.reserve(static_cast<size_t>(settings.variants));
67 if (graphics.getBackendName() == "webgpu")
68 impl->shader = graphics.newMeshShaderFromWgsl(shaders::kBoltVertWgsl, shaders::kBoltFragWgsl);
69 else
70 impl->shader = graphics.newMeshShaderFromSpv({bolt_vert_spv, bolt_vert_spv + bolt_vert_spv_count},
71 {bolt_frag_spv, bolt_frag_spv + bolt_frag_spv_count});
72 if (!impl->shader)
74 DiagnosticCode::InvalidArgument, "Lightning shader unavailable", "weather.lightning"));
75 impl->material = std::make_unique<graphics::Material>();
76 auto& m = *impl->material;
77 m.setShader(impl->shader);
78 m.setShadingModel("unlit");
79 m.setReceiveLight(false);
80 m.setReceiveShadow(false);
81 m.setCastShadow(false);
82 m.setCastOcclusion(false);
83 m.setTint(1, 1, 1, 1);
84 impl->shader->setPushConstantBlock({});
85 for (int i = 0; i < settings.variants; ++i) {
86 auto geometry = buildLightningGeometry(settings, static_cast<unsigned>(i));
87 if (!geometry) return Result<std::unique_ptr<Lightning>>::failure(geometry.status());
88 auto& g = geometry.value();
89 auto* mesh = graphics.newMeshFromArrays(g.positions.data(), g.normals.data(), g.uv.data(),
90 static_cast<int>(g.positions.size() / 3), g.indices.data(),
91 static_cast<int>(g.indices.size()));
92 if (!mesh)
94 DiagnosticCode::InvalidArgument, "Lightning mesh unavailable", "weather.lightning"));
95 impl->meshes.push_back(mesh);
96 }
97 auto* entity = graphics::Renderable3D::create();
98 impl->entity = ecs::handle_of(entity);
99 entity->setMesh(impl->meshes.front());
100 entity->setMaterial(impl->material.get());
101 entity->setVisible(false);
102 } catch (const std::exception& e) {
103 return Result<std::unique_ptr<Lightning>>::failure(
104 Diagnostic::error(DiagnosticCode::InvalidArgument, e.what(), "weather.lightning"));
105 }
106 return Result<std::unique_ptr<Lightning>>::success(std::unique_ptr<Lightning>(new Lightning(std::move(impl))));
107}
108Result<void> Lightning::setEndpoints(float ax, float ay, float az, float bx, float by, float bz) {
109 auto* e = impl_->renderable();
110 if (!e) return invalid("Lightning renderer retired", DiagnosticCode::StaleHandle);
111 const float dx = bx - ax, dy = by - ay, dz = bz - az;
112 const float length = std::hypot(dx, dy, dz);
113 if (!std::isfinite(ax) || !std::isfinite(ay) || !std::isfinite(az) || !std::isfinite(length) || length < .0001f ||
114 length > 1e6f)
115 return invalid("Lightning endpoints must be finite and distinct, length <= 1e6");
116 e->setPosition(ax, ay, az);
117 e->setRotation(std::atan2(dx, dz), std::acos(std::clamp(dy / length, -1.f, 1.f)), 0);
118 e->setScale(1, length, 1);
119 return Result<void>::success();
120}
121Result<void> Lightning::setColor(float r, float g, float b) {
122 if (!impl_->renderable()) return invalid("Lightning renderer retired", DiagnosticCode::StaleHandle);
123 if (!std::isfinite(r) || !std::isfinite(g) || !std::isfinite(b) || r < 0 || g < 0 || b < 0 || r > 16 || g > 16 ||
124 b > 16)
125 return invalid("Lightning RGB must be finite in [0,16]");
126 impl_->material->setTint(r, g, b, 1);
127 return Result<void>::success();
128}
130 auto* e = impl_->renderable();
131 if (!e) return invalid("Lightning renderer retired", DiagnosticCode::StaleHandle);
132 e->setMesh(impl_->meshes[impl_->variant++ % impl_->meshes.size()]);
133 impl_->playing = true;
134 impl_->age = 0;
135 impl_->flash = 1;
136 std::array<float, graphics::Shader::kMaxFloats> block{};
137 block[11] = 1;
138 impl_->shader->setPushConstantBlock(block);
139 e->setVisible(true);
140 return Result<void>::success();
141}
143 if (!std::isfinite(dt) || dt < 0) return invalid("Lightning dt must be finite and nonnegative");
144 auto* e = impl_->renderable();
145 if (!e) return invalid("Lightning renderer retired", DiagnosticCode::StaleHandle);
146 if (!impl_->playing) return Result<void>::success();
147 impl_->age = std::min(impl_->age + dt, static_cast<double>(impl_->settings.duration));
148 impl_->flash = lightningEnvelope(static_cast<float>(impl_->age / impl_->settings.duration));
149 std::array<float, graphics::Shader::kMaxFloats> block{};
150 block[11] = impl_->flash;
151 impl_->shader->setPushConstantBlock(block);
152 e->setVisible(impl_->flash > .02f);
153 if (impl_->age >= impl_->settings.duration) impl_->playing = false;
154 return Result<void>::success();
155}
157 impl_->playing = false;
158 impl_->flash = 0;
159 if (auto* e = impl_->renderable()) e->setVisible(false);
160}
161float Lightning::amplitude() const { return impl_->renderable() ? impl_->flash : 0; }
162} // namespace eve::weather
double m[16]
void * impl
std::string message
DiagnosticCode code
tensor::Graph g
Definition GpuGraph.cpp:7
double r
float length
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
OceanWakeSettings settings
OceanMeshSettings mesh
glm::dvec3 dx
glm::dvec3 dz
double dt
const EntityFact * entity
std::string geometry
Graphics * graphics
float dy
Definition Shadow.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
Move-only RAII token that owns one observer registration.
virtual bool releaseMesh(Mesh *mesh)
Eagerly releases a mesh created by this Graphics.
Definition Graphics.h:935
virtual bool releaseShader(Shader *shader)
Eagerly releases a shader created by this Graphics.
Definition Graphics.h:1976
EVENGINE_API_BACKENDS public API.
Custom GPU program.
Definition Shader.h:41
Independently owned, pooled visual effect; main/render thread only, no callbacks or gameplay damage....
Definition Lightning.h:44
Result< void > trigger()
Restart the pulse, selecting the next prebuilt variant; no allocation.
Result< void > update(float dt)
Advance with caller-supplied seconds before render3D; finite nonnegative dt required.
float amplitude() const
Current visual amplitude; zero after stop or retirement.
Result< void > setEndpoints(float ax, float ay, float az, float bx, float by, float bz)
Copy finite, distinct world endpoints; cheap transform update, width stays constant....
Lightning(const Lightning &)=delete
void stop()
Hide immediately; safe after provider/entity retirement.
~Lightning()
Release the internal entity and meshes on the main thread.
static Result< std::unique_ptr< Lightning > > prepare(graphics::Graphics &graphics, const LightningSettings &settings)
Validate and prepare hidden geometry; Graphics must be live during this call.
Definition Lightning.cpp:55
Result< void > setColor(float r, float g, float b)
Set nonnegative finite RGB tint; cheap material update, no environment mutation.
Status invalid(const char *message)
constexpr const char * kBoltFragWgsl
Definition WeatherWgsl.h:86
constexpr const char * kBoltVertWgsl
Definition WeatherWgsl.h:82
EVENGINE_API_ORCHESTRATION float lightningEnvelope(float age)
Weather return-stroke envelope, normalized age [0,1]; side-effect free.
EVENGINE_API_ORCHESTRATION Result< void > validateLightning(const LightningSettings &settings)
Validate bounded finite settings without modifying live instances.
EVENGINE_API_ORCHESTRATION Result< LightningGeometry > buildLightningGeometry(const LightningSettings &settings, unsigned variant)
Deterministic CPU preparation, explicit variant stream; identical inputs give identical geometry on o...
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Copied preparation settings. Width and displacement are world units, independent of endpoint distance...
Definition Lightning.h:16
LightningSettings settings
Definition Lightning.cpp:29
std::vector< graphics::Mesh * > meshes
Definition Lightning.cpp:28
graphics::Renderable3D * renderable() const
Definition Lightning.cpp:34
std::unique_ptr< graphics::Material > material
Definition Lightning.cpp:26
graphics::Graphics * graphics
Definition Lightning.cpp:22
graphics::Shader * shader
Definition Lightning.cpp:27
std::weak_ptr< const void > lifetime
Definition Lightning.cpp:23