载入中...
搜索中...
未找到
WarshipSystem.cpp
浏览该文件的文档.
2
3#include "common/Diagnostic.h"
4#include "common/Value.h"
5#include "common/ValueRead.h"
7
8#include <algorithm>
9#include <cmath>
10#include <memory>
11#include <unordered_map>
12#include <utility>
13
14namespace eve::warship {
15namespace {
16
17constexpr float kPi = 3.14159265358979323846f;
18
19std::unordered_map<std::string, std::unique_ptr<IWarshipMobility>>& mobilityTable() {
20 static std::unordered_map<std::string, std::unique_ptr<IWarshipMobility>> table;
21 return table;
22}
23
24float normalizeHeading(float deg) {
25 deg = std::fmod(deg, 360.f);
26 if (deg < 0.f) deg += 360.f;
27 return deg;
28}
29
30float shortestAngleDelta(float fromDeg, float toDeg) {
31 float delta = toDeg - fromDeg;
32 while (delta > 180.f) delta -= 360.f;
33 while (delta < -180.f) delta += 360.f;
34 return delta;
35}
36
37void integrateHelm(WarshipEntity& ship, float dt, float speedScale, float turnScale) {
38 const WarshipDefinition* def = ship.definition()->def;
39 if (def == nullptr) return;
40 auto input = ship.input();
41 auto motion = ship.motion();
42 auto caps = ship.capabilities();
43
44 float thrustMul = caps->values.thrustMul;
45 if (caps->values.underpowered) thrustMul *= 0.55f;
46
47 float maxSpeed = def->maxSpeed * speedScale * thrustMul;
48 if (maxSpeed < 0.f) maxSpeed = 0.f;
49
50 if (motion->hasMove) {
51 const float dx = motion->targetX - motion->x;
52 const float dy = motion->targetY - motion->y;
53 const float dist = std::sqrt(dx * dx + dy * dy);
54 if (dist <= motion->arriveRadius) {
55 motion->hasMove = false;
56 motion->arrived = true;
57 input->throttle = 0.f;
58 input->steer = 0.f;
59 motion->speed = 0.f;
60 WarshipEvent event;
61 event.type = WarshipEventType::Arrived;
62 event.warshipId = ship.identity()->id;
63 event.defId = ship.identity()->defId;
64 event.x = motion->x;
65 event.y = motion->y;
66 WarshipSystem::pushEvent(std::move(event));
67 } else {
68 const float desired = normalizeHeading(std::atan2(dy, dx) * 180.f / kPi);
69 const float delta = shortestAngleDelta(motion->heading, desired);
70 input->steer = std::clamp(delta / 45.f, -1.f, 1.f);
71 input->throttle = dist < motion->arriveRadius * 3.f ? 0.45f : 1.f;
72 motion->arrived = false;
73 }
74 }
75
76 const float turn = def->turnRate * turnScale * input->steer * dt;
77 motion->heading = normalizeHeading(motion->heading + turn);
78
79 float targetSpeed = maxSpeed * std::clamp(input->throttle, -1.f, 1.f);
80 const float accel = def->accel * speedScale * (targetSpeed >= motion->speed ? 1.f : 1.5f);
81 if (motion->speed < targetSpeed)
82 motion->speed = std::min(motion->speed + accel * dt, targetSpeed);
83 else
84 motion->speed = std::max(motion->speed - accel * dt, targetSpeed);
85
86 const float rad = motion->heading * kPi / 180.f;
87 motion->x += std::cos(rad) * motion->speed * dt;
88 motion->y += std::sin(rad) * motion->speed * dt;
89}
90
91class SurfaceMobility final : public IWarshipMobility {
92public:
93 const char* name() const override { return kMobilitySurface; }
94 void update(WarshipEntity& ship, float dt) override { integrateHelm(ship, dt, 1.f, 1.f); }
95};
96
97class SailMobility final : public IWarshipMobility {
98public:
99 const char* name() const override { return kMobilitySail; }
100 void update(WarshipEntity& ship, float dt) override {
101 float sailScale = 0.7f;
102 sailScale += std::clamp(ship.capabilities()->values.sailPower, 0.f, 1.5f) * 0.4f;
103 integrateHelm(ship, dt, sailScale, 0.85f);
104 }
105};
106
107class CarrierMobility final : public IWarshipMobility {
108public:
109 const char* name() const override { return kMobilityCarrier; }
110 void update(WarshipEntity& ship, float dt) override { integrateHelm(ship, dt, 0.75f, 0.55f); }
111};
112
113class SpaceMobility final : public IWarshipMobility {
114public:
115 const char* name() const override { return kMobilitySpace; }
116 void update(WarshipEntity& ship, float dt) override { integrateHelm(ship, dt, 1.35f, 1.1f); }
117};
118
119Result<void> validateCell(WarshipEntity& ship, int deck, int row, int col, int& outIndex) {
120 auto layout = ship.layout();
121 outIndex = layout->grid.indexOf(deck, row, col);
122 if (outIndex < 0 || outIndex >= static_cast<int>(layout->cells.size())) {
124 Diagnostic::error(DiagnosticCode::InvalidArgument, "compartment cell out of range", "warship.layout"));
125 }
126 return Result<void>::success();
127}
128
129} // namespace
130
132 switch (type) {
133 case WarshipEventType::Arrived: return "arrived";
134 case WarshipEventType::LayoutChanged: return "layout_changed";
135 case WarshipEventType::Damaged: return "damaged";
136 case WarshipEventType::Destroyed: return "destroyed";
137 case WarshipEventType::Underpowered: return "underpowered";
138 }
139 return "unknown";
140}
141
143 WarshipEntity* ship = WarshipEntity::create();
144 ship->identity();
145 ship->definition();
146 ship->input();
147 ship->motion();
148 ship->health();
149 ship->hull();
150 ship->layout();
151 ship->capabilities();
152 ship->stateFlags();
153 return ship;
154}
155
157 if (mobility == nullptr) return;
158 mobilityTable()[mobility->name()] = std::unique_ptr<IWarshipMobility>(mobility);
159}
160
163 return static_cast<int>(mobilityTable().size());
164}
165
167 auto& table = mobilityTable();
168 if (table.count(kMobilitySurface) == 0) table[kMobilitySurface] = std::make_unique<SurfaceMobility>();
169 if (table.count(kMobilitySail) == 0) table[kMobilitySail] = std::make_unique<SailMobility>();
170 if (table.count(kMobilityCarrier) == 0) table[kMobilityCarrier] = std::make_unique<CarrierMobility>();
171 if (table.count(kMobilitySpace) == 0) table[kMobilitySpace] = std::make_unique<SpaceMobility>();
172}
173
175 auto layout = ship.layout();
176 auto caps = ship.capabilities();
177
179 values.thrustMul = 1.f;
180 const bool hadUnderpowered = caps->values.underpowered;
181
182 for (const CompartmentCell& cell : layout->cells) {
183 if (cell.functionId.empty()) continue;
185 if (fn == nullptr) continue;
186 values.powerNet += fn->powerProvide - fn->powerDraw;
187 values.thrustMul += fn->thrustBonus;
188 values.hangarCapacity += fn->hangarCapacity;
189 values.weaponBayCount += fn->weaponBayCount;
190 values.crewCapacity += fn->crewCapacity;
191 values.sailPower += fn->sailPower;
192 }
193 if (values.thrustMul < 0.05f) values.thrustMul = 0.05f;
194 values.underpowered = values.powerNet < 0.f;
195 caps->values = values;
196 ++caps->revision;
197
198 if (values.underpowered && !hadUnderpowered) {
199 WarshipEvent event;
201 event.warshipId = ship.identity()->id;
202 event.defId = ship.identity()->defId;
203 event.detail = "power_deficit";
204 pushEvent(std::move(event));
205 }
206}
207
209 const std::string& functionId) {
210 if (functionId.empty() || !WarshipRegistry::hasFunction(functionId)) {
212 Diagnostic::error(DiagnosticCode::InvalidArgument, "unknown compartment function", "warship.layout"));
213 }
214 int index = 0;
215 if (auto ok = validateCell(ship, deck, row, col, index); !ok) return ok;
216 ship.layout()->cells[static_cast<std::size_t>(index)].functionId = functionId;
218 WarshipEvent event;
220 event.warshipId = ship.identity()->id;
221 event.defId = ship.identity()->defId;
222 event.detail = functionId;
223 pushEvent(std::move(event));
224 return Result<void>::success();
225}
226
228 int index = 0;
229 if (auto ok = validateCell(ship, deck, row, col, index); !ok) return ok;
230 ship.layout()->cells[static_cast<std::size_t>(index)].functionId.clear();
232 WarshipEvent event;
234 event.warshipId = ship.identity()->id;
235 event.defId = ship.identity()->defId;
236 event.detail = "cleared";
237 pushEvent(std::move(event));
238 return Result<void>::success();
239}
240
241Result<void> WarshipSystem::swapCompartments(WarshipEntity& ship, int deckA, int rowA, int colA, int deckB, int rowB,
242 int colB) {
243 int indexA = 0;
244 int indexB = 0;
245 if (auto ok = validateCell(ship, deckA, rowA, colA, indexA); !ok) return ok;
246 if (auto ok = validateCell(ship, deckB, rowB, colB, indexB); !ok) return ok;
247 auto& cells = ship.layout()->cells;
248 std::swap(cells[static_cast<std::size_t>(indexA)].functionId, cells[static_cast<std::size_t>(indexB)].functionId);
250 WarshipEvent event;
252 event.warshipId = ship.identity()->id;
253 event.defId = ship.identity()->defId;
254 event.detail = "swapped";
255 pushEvent(std::move(event));
256 return Result<void>::success();
257}
258
260 auto layout = ship.layout();
261 auto parsed = Value::fromJson(json);
262 if (!parsed) return Result<void>::failure(parsed.status());
263 const auto* array = parsed.value().getIf<Value::Array>();
264 if (array == nullptr) {
266 Diagnostic::error(DiagnosticCode::InvalidArgument, "layout JSON must be an array", "warship.layout"));
267 }
268
269 std::vector<CompartmentCell> next(layout->cells.size());
270 for (const Value& entry : *array) {
271 const auto* object = entry.getIf<Value::Object>();
272 if (object == nullptr) {
274 Diagnostic::error(DiagnosticCode::InvalidArgument, "layout entries must be objects", "warship.layout"));
275 }
276 auto readCoord = [&](const char* key) -> Result<int> {
277 auto it = object->find(key);
278 if (it == object->end()) {
280 "layout entry missing coordinate", "warship.layout"));
281 }
282 return readIntValue(it->second);
283 };
284 auto deckR = readCoord("deck");
285 if (!deckR) return Result<void>::failure(deckR.status());
286 auto rowR = readCoord("row");
287 if (!rowR) return Result<void>::failure(rowR.status());
288 auto colR = readCoord("col");
289 if (!colR) return Result<void>::failure(colR.status());
290
291 std::string functionKey = "function";
292 if (object->find("function") == object->end()) functionKey = "functionId";
293 auto functionId = readStringMember(*object, functionKey);
294 if (!functionId) return Result<void>::failure(functionId.status());
295 if (functionId.value().empty() || !WarshipRegistry::hasFunction(functionId.value())) {
297 Diagnostic::error(DiagnosticCode::InvalidArgument, "unknown compartment function", "warship.layout"));
298 }
299 const int index = layout->grid.indexOf(deckR.value(), rowR.value(), colR.value());
300 if (index < 0 || index >= static_cast<int>(next.size())) {
302 Diagnostic::error(DiagnosticCode::InvalidArgument, "layout cell out of range", "warship.layout"));
303 }
304 if (!next[static_cast<std::size_t>(index)].functionId.empty()) {
306 Diagnostic::error(DiagnosticCode::InvalidArgument, "duplicate layout cell", "warship.layout"));
307 }
308 next[static_cast<std::size_t>(index)].functionId = std::move(functionId).takeValue();
309 }
310
311 layout->cells = std::move(next);
313 WarshipEvent event;
315 event.warshipId = ship.identity()->id;
316 event.defId = ship.identity()->defId;
317 event.detail = "rearranged";
318 pushEvent(std::move(event));
319 return Result<void>::success();
320}
321
322void WarshipSystem::moveTo(WarshipEntity& ship, float x, float y, float arriveRadius) {
323 auto motion = ship.motion();
324 motion->targetX = x;
325 motion->targetY = y;
326 motion->arriveRadius = arriveRadius > 0.f ? arriveRadius : 24.f;
327 motion->hasMove = true;
328 motion->arrived = false;
329}
330
332 auto motion = ship.motion();
333 motion->hasMove = false;
334 motion->arrived = true;
335 motion->speed = 0.f;
336 auto input = ship.input();
337 input->throttle = 0.f;
338 input->steer = 0.f;
339}
340
341void WarshipSystem::applyDamage(WarshipEntity& ship, float amount, const std::string& /*sourceId*/) {
342 auto health = ship.health();
343 auto flags = ship.stateFlags();
344 if (flags->destroyed) return;
345 if (amount < 0.f) amount = 0.f;
346 health->hp = std::max(0.f, health->hp - amount);
347 WarshipEvent damaged;
349 damaged.warshipId = ship.identity()->id;
350 damaged.defId = ship.identity()->defId;
351 pushEvent(std::move(damaged));
352 if (health->hp <= 0.f) {
353 flags->destroyed = true;
354 stop(ship);
355 WarshipEvent destroyed;
357 destroyed.warshipId = ship.identity()->id;
358 destroyed.defId = ship.identity()->defId;
359 pushEvent(std::move(destroyed));
360 }
361}
362
364 if (!std::isfinite(dt) || dt < 0.f) return;
366 ecs::Table* table = ecs::current();
367 if (table == nullptr) return;
368
369 ecs::IComponentManager& cm = table->getOrCreateManager<WarshipEntity>();
370 auto* reg = cm.getOrCreateRegistryComponentBuffer<WarshipEntity>();
371 std::vector<ecs::IComponentBuffer*> stack;
372 stack.push_back(reg);
373 while (!stack.empty()) {
374 ecs::IComponentBuffer* buf = stack.back();
375 stack.pop_back();
376 auto* r = dynamic_cast<ecs::IRegistryComponentBuffer*>(buf);
377 if (r != nullptr) {
378 for (uint32_t i = 0; i < r->entity_count(); ++i) {
379 ecs::Entity* ent = r->entity_at(i);
380 if (ent == nullptr || !ecs::is_entity_visible(ent)) continue;
381 auto* ship = static_cast<WarshipEntity*>(ent);
382 if (ship->stateFlags()->destroyed) continue;
383 const WarshipDefinition* def = ship->definition()->def;
384 if (def == nullptr) continue;
385 auto it = mobilityTable().find(def->mobility);
386 if (it == mobilityTable().end() || !it->second) {
387 it = mobilityTable().find(kMobilitySurface);
388 }
389 if (it != mobilityTable().end() && it->second) it->second->update(*ship, dt);
390 }
391 }
392 if (buf->children != nullptr) stack.push_back(buf->children);
393 if (buf->next != nullptr) stack.push_back(buf->next);
394 }
395}
396
397std::vector<WarshipEvent>& WarshipSystem::events() {
398 static std::vector<WarshipEvent> queue;
399 return queue;
400}
401
402void WarshipSystem::clearEvents() { events().clear(); }
403
404int WarshipSystem::eventCount() { return static_cast<int>(events().size()); }
405
407 if (index < 0 || index >= eventCount()) return nullptr;
408 return &events()[static_cast<std::size_t>(index)];
409}
410
411void WarshipSystem::pushEvent(WarshipEvent event) { events().push_back(std::move(event)); }
412
413} // namespace eve::warship
double y
double x
Stable, structured diagnostics shared by engine modules.
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
std::string layout
double r
glm::dvec3 dx
double dt
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::set< std::string > values
size_t end
float dy
Definition Shadow.cpp:151
Cell cell
TacticalUnit::TurnResources turn
Json object
int caps
Definition TreeMesh.cpp:164
uint32_t index
Owning, renderer-independent dynamic values.
uint32_t flags
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
Pluggable hull mobility (surface / sail / carrier / space / custom).
virtual const char * name() const =0
Registry key matching WarshipDefinition::mobility.
Warship short-root entity: huge hull + rearrangeable compartments.
static WarshipEntity * createWarship()
Allocate a WarshipEntity with every component installed. @ownership ECS table owns the entity; caller...
static const CompartmentFunctionDef * findFunction(const std::string &id)
Lookup a compartment function. @ownership Borrowed; valid until the next clear / replace of that id....
static bool hasFunction(const std::string &id)
static int mobilityCount()
Number of registered mobility implementations (includes builtins).
static void stop(WarshipEntity &ship)
Cancel move order and zero helm input.
static Result< void > clearCompartment(WarshipEntity &ship, int deck, int row, int col)
Vacate one cell.
static void applyDamage(WarshipEntity &ship, float amount, const std::string &sourceId={})
Apply damage; may mark destroyed and push events.
static Result< void > swapCompartments(WarshipEntity &ship, int deckA, int rowA, int colA, int deckB, int rowB, int colB)
Swap two cells atomically.
static void recomputeCapabilities(WarshipEntity &ship)
Recompute Capabilities from Layout + function catalogue. @cost Linear in cell count; amortize across ...
static Result< void > rearrangeFromJson(WarshipEntity &ship, const std::string &json)
Replace the entire layout from a JSON array of {deck,row,col,function}.
static void update(float dt)
Advance all warships one step.
static void ensureBuiltinMobility()
Ensure built-in surface/sail/carrier/space models are registered.
static void moveTo(WarshipEntity &ship, float x, float y, float arriveRadius=24.f)
Issue a move order toward (x, y).
static void registerMobility(IWarshipMobility *mobility)
Register a mobility plugin (same name replaces). Takes ownership.
static const WarshipEvent * eventAt(int index)
Borrow one buffered event by index.
static void pushEvent(WarshipEvent event)
static Result< void > placeCompartment(WarshipEntity &ship, int deck, int row, int col, const std::string &functionId)
Place or replace a function in one cell. @cost One cell write + full capability recompute.
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
Warship module entry (eve.Warship): hull/function catalogues, spawn, compartment remodel,...
Definition Warship.cpp:17
constexpr const char * kMobilitySpace
constexpr const char * kMobilityCarrier
constexpr const char * kMobilitySail
constexpr const char * kMobilitySurface
Built-in mobility model names used by hull definitions.
const char * warshipEventTypeName(WarshipEventType type)
Stable event type protocol name.
WarshipEventType
Frame-buffered warship events for script polling.
Result< int > readIntValue(const Value &value)
Read an Int64 value as a range-checked native int without numeric coercion.
Definition Value.cpp:41
Result< std::string > readStringMember(const Value::Object &object, std::string_view name)
Read a required string field, including an empty string, as an owning value.
Definition Value.cpp:25
SettlementPipeline::Stage fn
One cell of a hull's compartment grid.
Compartment function catalogue entry.
Aggregated capabilities projected from the live compartment layout.
Hull template registered through Warship::registerHullsFromJson.
std::string mobility
IWarshipMobility registry name; default surface.
One warship event (frame cache).