载入中...
搜索中...
未找到
VehicleDefinitionRuntime.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <cstdint>
5#include <limits>
6#include <set>
7#include <stdexcept>
8#include <unordered_map>
9#include <utility>
10#include "common/Value.h"
11#include "common/ValueRead.h"
12#include "orders/CommandQueue.h"
13#include "vehicle/Vehicle.h"
16
17// VehicleDefinitionRuntime.cpp
18namespace eve::vehicle {
19namespace {
20
21eve::LogicalId vehicleSchema() {
22 static const eve::LogicalId value = [] {
23 const auto parsed = eve::LogicalId::parse("vehicle:runtime");
24 if (!parsed) throw std::logic_error("invalid built-in vehicle snapshot schema");
25 return *parsed;
26 }();
27 return value;
28}
29
32 const auto& logical = reference.id();
33 return registry.handle(std::string(logical.namespaceName()), std::string(logical.name()));
34}
35
36const eve::Value* field(const eve::Value::Object& object, std::string_view name) {
37 const auto it = object.find(std::string(name));
38 return it == object.end() ? nullptr : &it->second;
39}
40
41bool readString(const eve::Value::Object& object, std::string_view name, std::string& result, bool required = false) {
42 if (!field(object, name)) return !required;
44 if (!parsed) return false;
45 result = std::move(parsed.value());
46 return true;
47}
48
49bool readNumber(const eve::Value::Object& object, std::string_view name, float& result, float fallback) {
50 const auto* value = field(object, name);
51 if (value == nullptr) {
52 result = fallback;
53 return true;
54 }
55 double number = 0.0;
56 if (const auto* real = value->getIf<double>())
57 number = *real;
58 else if (const auto* integer = value->getIf<std::int64_t>())
59 number = static_cast<double>(*integer);
60 else
61 return false;
62 if (!std::isfinite(number) || number < 0.0 || number > std::numeric_limits<float>::max()) return false;
63 result = static_cast<float>(number);
64 return true;
65}
66
67bool readSignedNumber(const eve::Value::Object& object, std::string_view name, float& result, float fallback) {
68 const auto* value = field(object, name);
69 if (!value) {
70 result = fallback;
71 return true;
72 }
73 auto parsed = eve::readFiniteFloatValue(*value);
74 if (!parsed) return false;
75 result = parsed.value();
76 return true;
77}
78
79bool readBool(const eve::Value::Object& object, std::string_view name, bool& result, bool fallback) {
80 const auto* value = field(object, name);
81 if (!value) {
82 result = fallback;
83 return true;
84 }
85 auto parsed = eve::readBoolValue(*value);
86 if (!parsed) return false;
87 result = parsed.value();
88 return true;
89}
90
91} // namespace
92
94 auto parsed = eve::Value::fromJson(source.json);
95 if (!parsed) return eve::Result<VehicleDefinition>::failure(parsed.status());
96 const auto* object = parsed.value().getIf<eve::Value::Object>();
97 if (object == nullptr)
99 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle definition must be an object", "json",
100 {}, "vehicle.definition_runtime"));
101
103 result.id = source.id;
104 if (!readString(*object, "category", result.category) || !readString(*object, "mobility", result.mobility))
106 eve::DiagnosticCode::InvalidArgument, "vehicle category and mobility must be strings", "definition", {},
107 "vehicle.definition_runtime"));
108 if (!readNumber(*object, "maxSpeed", result.maxSpeed, result.maxSpeed) ||
109 !readNumber(*object, "accel", result.accel, result.accel) ||
110 !readNumber(*object, "turnRate", result.turnRate, result.turnRate) ||
111 !readNumber(*object, "radius", result.radius, result.radius) ||
112 !readNumber(*object, "maxHealth", result.maxHealth, result.maxHealth) || result.radius <= 0.f ||
113 result.maxHealth < 0.f)
115 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle numeric definition field is invalid",
116 "definition", {}, "vehicle.definition_runtime"));
117
118 if (const auto* physics = field(*object, "physics")) {
119 const auto* physicsObject = physics->getIf<eve::Value::Object>();
120 if (physicsObject == nullptr)
122 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle physics must be an object",
123 "physics", {}, "vehicle.definition_runtime"));
124 if (!readNumber(*physicsObject, "maxSpeed", result.maxSpeed, result.maxSpeed) ||
125 !readNumber(*physicsObject, "accel", result.accel, result.accel) ||
126 !readNumber(*physicsObject, "turnRate", result.turnRate, result.turnRate) ||
127 !readNumber(*physicsObject, "radius", result.radius, result.radius))
129 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle physics numeric field is invalid",
130 "physics", {}, "vehicle.definition_runtime"));
131 }
132
133 if (const auto* zones = field(*object, "armorZones")) {
134 const auto* array = zones->getIf<eve::Value::Array>();
135 if (array == nullptr)
138 "armorZones", {}, "vehicle.definition_runtime"));
139 for (std::size_t index = 0; index < array->size(); ++index) {
140 const auto* item = (*array)[index].getIf<eve::Value::Object>();
141 if (item == nullptr)
143 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "armor zone must be an object",
144 "armorZones", {}, "vehicle.definition_runtime"));
145 ArmorZone zone;
146 if (!readString(*item, "name", zone.name) || !readString(*item, "node", zone.node) ||
147 !readNumber(*item, "mult", zone.mult, zone.mult) || zone.name.empty())
149 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "armor zone fields are invalid",
150 "armorZones", {}, "vehicle.definition_runtime"));
151 result.armorZones.push_back(std::move(zone));
152 }
153 }
154
155 if (const auto* mounts = field(*object, "mounts")) {
156 const auto* array = mounts->getIf<eve::Value::Array>();
157 if (array == nullptr)
159 "mounts must be an array", "mounts",
160 {}, "vehicle.definition_runtime"));
161 for (std::size_t index = 0; index < array->size(); ++index) {
162 const auto* item = (*array)[index].getIf<eve::Value::Object>();
163 if (item == nullptr)
165 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "mount must be an object", "mounts",
166 {}, "vehicle.definition_runtime"));
167 MountDef mount;
168 mount.name = "mount" + std::to_string(index);
169 if (!readString(*item, "name", mount.name) || !readString(*item, "weapon", mount.weapon) ||
170 !readString(*item, "type", mount.type) || !readString(*item, "aimMode", mount.aimMode) ||
171 !readSignedNumber(*item, "yawMin", mount.yawMin, mount.yawMin) ||
172 !readSignedNumber(*item, "yawMax", mount.yawMax, mount.yawMax) ||
173 !readSignedNumber(*item, "pitchMin", mount.pitchMin, mount.pitchMin) ||
174 !readSignedNumber(*item, "pitchMax", mount.pitchMax, mount.pitchMax) ||
175 !readNumber(*item, "rotSpeed", mount.rotSpeed, mount.rotSpeed) ||
176 !readNumber(*item, "firingArc", mount.firingArc, mount.firingArc))
178 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "mount definition field is invalid",
179 "mounts", {}, "vehicle.definition_runtime"));
180 if (const auto* limits = field(*item, "limits")) {
181 const auto* values = limits->getIf<eve::Value::Array>();
182 if (values == nullptr || values->size() < 4)
184 eve::DiagnosticCode::InvalidArgument, "mount limits must contain four numbers", "mounts.limits",
185 {}, "vehicle.definition_runtime"));
186 float* output[] = {&mount.yawMin, &mount.yawMax, &mount.pitchMin, &mount.pitchMax};
187 for (std::size_t limit = 0; limit < 4; ++limit) {
188 const auto* real = (*values)[limit].getIf<double>();
189 const auto* integer = (*values)[limit].getIf<std::int64_t>();
190 const double number = real ? *real
191 : integer ? static_cast<double>(*integer)
192 : std::numeric_limits<double>::quiet_NaN();
193 if (!std::isfinite(number) || number < -std::numeric_limits<float>::max() ||
194 number > std::numeric_limits<float>::max())
197 "mounts.limits", {}, "vehicle.definition_runtime"));
198 *output[limit] = static_cast<float>(number);
199 }
200 }
201 result.mounts.push_back(std::move(mount));
202 }
203 }
204
205 if (const auto* suspension = field(*object, "suspension")) {
206 const auto* value = suspension->getIf<eve::Value::Object>();
207 if (value == nullptr)
209 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "suspension must be an object",
210 "suspension", {}, "vehicle.definition_runtime"));
211 if (!readNumber(*value, "maxTravel", result.suspension.maxTravel, result.suspension.maxTravel) ||
212 !readNumber(*value, "driveForce", result.suspension.driveForce, result.suspension.driveForce) ||
213 !readNumber(*value, "lateralGrip", result.suspension.lateralGrip, result.suspension.lateralGrip) ||
214 !readNumber(*value, "wheelInertia", result.suspension.wheelInertia, result.suspension.wheelInertia) ||
215 !readNumber(*value, "tireFriction", result.suspension.tireFriction, result.suspension.tireFriction) ||
216 !readNumber(*value, "longitudinalStiffness", result.suspension.longitudinalStiffness,
217 result.suspension.longitudinalStiffness) ||
218 !readNumber(*value, "corneringStiffness", result.suspension.corneringStiffness,
219 result.suspension.corneringStiffness) ||
220 !readNumber(*value, "rollingResistance", result.suspension.rollingResistance,
221 result.suspension.rollingResistance) ||
222 !readNumber(*value, "brakeTorque", result.suspension.brakeTorque, result.suspension.brakeTorque) ||
223 !readNumber(*value, "maxSteerAngle", result.suspension.maxSteerAngle, result.suspension.maxSteerAngle) ||
224 !readNumber(*value, "supportAcceleration2D", result.suspension.supportAcceleration2D,
225 result.suspension.supportAcceleration2D) ||
226 result.suspension.wheelInertia <= 0 || result.suspension.maxSteerAngle > 1.4f)
228 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "suspension numeric field is invalid",
229 "suspension", {}, "vehicle.definition_runtime"));
230 if (const auto* wheels = field(*value, "wheels")) {
231 const auto* array = wheels->getIf<eve::Value::Array>();
232 if (array == nullptr)
234 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "suspension wheels must be an array",
235 "suspension.wheels", {}, "vehicle.definition_runtime"));
236 for (std::size_t index = 0; index < array->size(); ++index) {
237 const auto* item = (*array)[index].getIf<eve::Value::Object>();
238 if (item == nullptr)
241 "suspension.wheels", {}, "vehicle.definition_runtime"));
242 SuspensionWheel wheel;
243 if (!readSignedNumber(*item, "x", wheel.x, wheel.x) ||
244 !readSignedNumber(*item, "y", wheel.y, wheel.y) ||
245 !readSignedNumber(*item, "z", wheel.z, wheel.z) ||
246 !readNumber(*item, "radius", wheel.radius, wheel.radius) ||
247 !readNumber(*item, "rest", wheel.restLength, wheel.restLength) ||
248 !readNumber(*item, "stiffness", wheel.stiffness, wheel.stiffness) ||
249 !readNumber(*item, "damping", wheel.damping, wheel.damping) ||
250 !readBool(*item, "drive", wheel.drive, wheel.drive) ||
251 !readBool(*item, "steer", wheel.steer, wheel.steer))
253 eve::DiagnosticCode::InvalidArgument, "wheel definition field is invalid", "suspension.wheels",
254 {}, "vehicle.definition_runtime"));
255 result.suspension.wheels.push_back(wheel);
256 }
257 }
258 }
259
260 if (const auto* seats = field(*object, "seats")) {
261 const auto* array = seats->getIf<eve::Value::Array>();
262 if (array == nullptr)
264 "seats must be an array", "seats", {},
265 "vehicle.definition_runtime"));
266 for (std::size_t index = 0; index < array->size(); ++index) {
267 const auto* item = (*array)[index].getIf<eve::Value::Object>();
268 if (item == nullptr)
270 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "seat must be an object", "seats", {},
271 "vehicle.definition_runtime"));
272 SeatDef seat;
273 seat.name = "passenger" + std::to_string(index);
274 if (!readString(*item, "name", seat.name) || !readString(*item, "driver", seat.driver) ||
275 !readString(*item, "cameraMode", seat.cameraMode))
277 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "seat definition field is invalid",
278 "seats", {}, "vehicle.definition_runtime"));
279 if (const auto* mount = field(*item, "mountIndex")) {
280 const auto* integer = mount->getIf<std::int64_t>();
281 if (integer == nullptr || *integer < std::numeric_limits<int>::min() ||
282 *integer > std::numeric_limits<int>::max())
285 "seats.mountIndex", {}, "vehicle.definition_runtime"));
286 seat.mountIndex = static_cast<int>(*integer);
287 }
288 result.seats.push_back(std::move(seat));
289 }
290 }
291 if (const auto* tags = field(*object, "tags")) {
292 const auto* array = tags->getIf<eve::Value::Array>();
293 if (array == nullptr)
295 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle tags must be an array", "tags",
296 {}, "vehicle.definition_runtime"));
297 for (const auto& item : *array) {
298 const auto* text = item.getIf<std::string>();
299 if (text == nullptr || text->empty())
301 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle tag is invalid", "tags", {},
302 "vehicle.definition_runtime"));
303 result.tags.push_back(*text);
304 }
305 }
307}
308
309namespace {
310
311eve::Value encodeState(const VehicleRuntimeState& state) {
313 {"destroyed", eve::Value(state.destroyed)},
314 {"faction", eve::Value(state.faction)},
315 {"heading", eve::Value(static_cast<double>(state.heading))},
316 {"health", eve::Value(static_cast<double>(state.health))},
317 {"speed", eve::Value(static_cast<double>(state.speed))},
318 {"x", eve::Value(static_cast<double>(state.x))},
319 {"y", eve::Value(static_cast<double>(state.y))},
320 });
321}
322
324 const auto* object = value.getIf<eve::Value::Object>();
325 if (object == nullptr)
327 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle runtime state must be an object",
328 "state", {}, "vehicle.definition_runtime"));
329 static const std::set<std::string> fields = {"destroyed", "faction", "heading", "health", "speed", "x", "y"};
330 for (const auto& [name, unused] : *object) {
331 (void)unused;
332 if (!fields.contains(name))
334 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "unknown vehicle runtime state field",
335 "state." + name, {}, "vehicle.definition_runtime"));
336 }
337 for (const auto& name : fields)
338 if (!object->contains(name))
339 return eve::Result<VehicleRuntimeState>::failure(
340 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle runtime state is missing a field",
341 "state." + name, {}, "vehicle.definition_runtime"));
342 auto number = [&](std::string_view name, float& output, bool allowNegative) -> bool {
343 const auto* real = object->at(std::string(name)).getIf<double>();
344 if (real == nullptr || !std::isfinite(*real) || (!allowNegative && *real < 0.0) ||
345 *real < -std::numeric_limits<float>::max() || *real > std::numeric_limits<float>::max())
346 return false;
347 output = static_cast<float>(*real);
348 return true;
349 };
350 const auto* destroyed = object->at("destroyed").getIf<bool>();
351 const auto* faction = object->at("faction").getIf<std::string>();
352 VehicleRuntimeState result;
353 if (destroyed == nullptr || faction == nullptr || !number("heading", result.heading, false) ||
354 !number("health", result.health, false) || !number("speed", result.speed, false) ||
355 !number("x", result.x, true) || !number("y", result.y, true))
357 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle runtime state field is invalid",
358 "state", {}, "vehicle.definition_runtime"));
359 result.destroyed = *destroyed;
360 result.faction = *faction;
362}
363
364} // namespace
365
367 eve::DefinitionRef definition,
370 if (!definition.id().isValid() || definition.id().namespaceName() != "vehicle")
372 eve::DiagnosticCode::InvalidArgument, "vehicle definition reference must use vehicle namespace",
373 "definition", {}, "vehicle.definition_runtime"));
374 auto handle = currentHandle(registry, definition);
376 auto resolved = registry.resolveHandle(handle.value());
378 auto typed = parseVehicleDefinition(resolved.value().get());
379 if (!typed) return eve::Result<VehicleDefinitionRuntime>::failure(typed.status());
381 defaults.health = typed.value().maxHealth;
383 handle.value().generation, defaults);
384 if (!runtime) return eve::Result<VehicleDefinitionRuntime>::failure(runtime.status());
386 VehicleDefinitionRuntime(registry, std::move(runtime).takeValue(), policy));
387}
388
390 std::string_view definitionId,
393 auto logical = eve::LogicalId::fromParts("vehicle", definitionId);
394 if (!logical)
396 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle id is not a valid logical name",
397 "definitionId", {}, "vehicle.definition_runtime"));
398 auto reference = eve::DefinitionRef::fromId(*logical);
400 return create(registry, std::move(reference).takeValue(), instanceId, policy);
401}
402
406 return create(module.definitionRegistry(), definitionId, instanceId, policy);
407}
408
410 return runtime_.identity();
411}
412
413const VehicleRuntimeState& VehicleDefinitionRuntime::state() const noexcept { return runtime_.state(); }
414
415VehicleRuntimeState& VehicleDefinitionRuntime::state() noexcept { return runtime_.state(); }
416
418 return runtime_.identity().definitionHandle();
419}
420
422 if (registry_ == nullptr)
424 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle definition registry is not bound",
425 "registry", {}, "vehicle.definition_runtime"));
426 auto resolved = registry_->resolveHandle(definitionHandle());
428 return parseVehicleDefinition(resolved.value().get());
429}
430
431void VehicleDefinitionRuntime::setActive(bool active) noexcept { runtime_.setActive(active); }
432
433bool VehicleDefinitionRuntime::isActive() const noexcept { return runtime_.isActive(); }
434
436 if (entity == nullptr)
438 eve::DiagnosticCode::InvalidArgument, "vehicle runtime cannot project to a null VehicleEntity", "entity",
439 {}, "vehicle.definition_runtime"));
440 auto typed = definition();
441 if (!typed) return eve::Result<void>::failure(typed.status());
442 try {
443 auto definitionOwner = std::make_shared<const VehicleDefinition>(typed.value());
444 auto identity = *entity->identity();
445 auto definition = *entity->definition();
446 auto binding = *entity->definitionBinding();
447 auto motion = *entity->motion();
448 auto health = *entity->health();
449 auto flags = *entity->stateFlags();
450
451 identity.id = this->identity().instanceId.format();
452 identity.defId = this->identity().definition.id().name();
453 identity.faction = state().faction;
454 definition.owned = std::move(definitionOwner);
455 definition.def = definition.owned.get();
456 binding.identity = this->identity();
457 binding.reloadPolicy = policy_;
458 binding.active = isActive();
459 motion.x = state().x;
460 motion.y = state().y;
461 motion.heading = state().heading;
462 motion.speed = state().speed;
463 motion.arrived = false;
464 health.maxHp = typed.value().maxHealth;
465 health.hp = std::clamp(state().health, 0.f, health.maxHp);
466 flags.destroyed = state().destroyed;
467
468 using std::swap;
469 swap(*entity->identity(), identity);
470 swap(*entity->definition(), definition);
471 swap(*entity->definitionBinding(), binding);
472 swap(*entity->motion(), motion);
473 swap(*entity->health(), health);
474 swap(*entity->stateFlags(), flags);
476 } catch (const std::exception&) {
478 "vehicle runtime projection allocation failed",
479 "entity", {}, "vehicle.definition_runtime"));
480 }
481}
482
484 if (registry_ == nullptr)
486 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "vehicle definition registry is not bound",
487 "registry", {}, "vehicle.definition_runtime"));
488 auto next = currentHandle(*registry_, identity().definition);
489 if (!next) return eve::Result<eve::definition::ReloadOutcome>::failure(next.status());
490 auto resolved = registry_->resolveHandle(next.value());
492 auto typed = parseVehicleDefinition(resolved.value().get());
493 if (!typed) return eve::Result<eve::definition::ReloadOutcome>::failure(typed.status());
495 defaults.health = typed.value().maxHealth;
496 const float maxHealth = typed.value().maxHealth;
497 auto rebuild = [maxHealth](const VehicleRuntimeState& oldState, const eve::definition::InstanceIdentity&,
499 VehicleRuntimeState rebuilt = oldState;
500 rebuilt.health = std::clamp(oldState.health, 0.f, maxHealth);
501 return eve::Result<VehicleRuntimeState>::success(std::move(rebuilt));
502 };
503 auto result = runtime_.reload(next.value(), policy, defaults, std::move(rebuild));
504 if (result.ok()) policy_ = policy;
505 return result;
506}
507
516
524
526 const eve::SnapshotHashProvider& hashProvider) {
527 if (registry_ == nullptr)
529 "vehicle definition registry is not bound", "registry",
530 {}, "vehicle.definition_runtime"));
531 auto current = currentHandle(*registry_, identity().definition);
532 if (!current) return eve::Result<void>::failure(current.status());
533 if (current.value() != definitionHandle())
535 eve::DiagnosticCode::StaleHandle, "vehicle snapshot cannot restore against a replaced definition",
536 "definitionGeneration", {}, "vehicle.definition_runtime"));
538 return eve::definition::restoreRuntimeInstance(runtime_, snapshotValue, "vehicle.runtime", vehicleSchema(),
539 eve::SchemaVersion(1), hashProvider, decoder);
540}
541
542} // namespace eve::vehicle
543
544// VehicleEffects.cpp
545namespace eve::vehicle {
546namespace {
547
548const char* kindTag(VehicleEffectKind kind) {
549 switch (kind) {
550 case VehicleEffectKind::Damage: return "vehicle:damage";
551 case VehicleEffectKind::Repair: return "vehicle:repair";
552 case VehicleEffectKind::Disable: return "vehicle:disable";
553 }
554 return "vehicle:unknown";
555}
556
557double zoneMultiplier(const VehicleEffectTarget& target, const std::vector<std::string>& tags) {
558 const auto has = [&tags](const std::string& tag) { return std::find(tags.begin(), tags.end(), tag) != tags.end(); };
559 if (has("vehicle:zone:front")) return target.frontArmorMultiplier;
560 if (has("vehicle:zone:rear")) return target.rearArmorMultiplier;
561 return target.sideArmorMultiplier;
562}
563
564} // namespace
565
567 if (!std::isfinite(target.hull) || !std::isfinite(target.maxHull) || target.maxHull <= 0.0 || target.hull < 0.0 ||
568 target.hull > target.maxHull || target.frontArmorMultiplier < 0.0 || target.sideArmorMultiplier < 0.0 ||
569 target.rearArmorMultiplier < 0.0)
571 "vehicle effect target state is invalid", "target"));
573}
574
582
584 effects::EffectUpdateSummary lifecycle) const {
585 auto valid = validate(target);
588 result.lifecycle = std::move(lifecycle);
589 for (const auto& tick : result.lifecycle.periodicTicks) {
590 if (tick.stackCount == 0 || tick.magnitude < 0.0 || !std::isfinite(tick.magnitude))
592 eve::DiagnosticCode::InvalidArgument, "vehicle periodic effect value is invalid", "periodic"));
593 const double amount = tick.magnitude * static_cast<double>(tick.stackCount);
594 if (!std::isfinite(amount))
596 eve::DiagnosticCode::InvalidArgument, "vehicle periodic settlement overflows", "periodic"));
597 const auto has = [&tick](const char* tag) {
598 return std::find(tick.tags.begin(), tick.tags.end(), tag) != tick.tags.end();
599 };
600 if (has("vehicle:repair")) {
601 target.hull = std::min(target.maxHull, target.hull + amount);
602 } else if (has("vehicle:disable")) {
603 target.disabled = true;
604 } else {
605 const double damage = amount * zoneMultiplier(target, tick.tags);
606 if (!std::isfinite(damage))
608 eve::DiagnosticCode::InvalidArgument, "vehicle armor settlement overflows", "periodic"));
609 target.hull = std::max(0.0, target.hull - damage);
610 if (damage >= target.maxHull * 0.5) {
611 ++target.criticalHits;
612 ++result.criticalHits;
613 }
614 }
615 ++result.settled;
616 }
618}
619
622 if (definition.id.empty() || !subject.isValid() || definition.armorZone.empty())
624 eve::DiagnosticCode::InvalidArgument, "vehicle effect requires id, zone and valid subject", "effect"));
626 common.id = definition.id;
627 common.stackKey = definition.id;
628 common.duration = definition.duration;
629 common.period = definition.period;
630 common.magnitude = definition.magnitude;
631 common.policy = definition.policy;
632 common.tags = definition.tags;
633 common.tags.push_back(kindTag(definition.kind));
634 common.tags.push_back("vehicle:zone:" + definition.armorZone);
635 auto valid = common.validate();
637 auto candidate = container_.clone();
638 auto applied = candidate.apply(common, subject.format(), definition.source);
640 const std::string id = std::move(applied).takeValue();
641 const auto* instance = candidate.find(id);
642 if (!instance)
644 eve::DiagnosticCode::InvariantViolation, "vehicle effect candidate disappeared", "effect"));
645 auto targetCandidate = target_;
646 auto immediate = executor_.applyImmediate(targetCandidate, *instance);
647 if (!immediate) return eve::Result<effects::EffectHandle>::failure(immediate.status());
648 auto handle = candidate.handleFor(id);
650 target_ = std::move(targetCandidate);
651 container_ = std::move(candidate);
652 return eve::Result<effects::EffectHandle>::success(std::move(handle).takeValue(),
654}
655
657 auto resolved = container_.resolve(handle);
658 if (!resolved) return eve::Result<void>::failure(resolved.status());
659 return container_.remove(handle.instanceId);
660}
661
663 auto candidate = container_.clone();
664 auto lifecycle = effects::EffectExecutor{}.advance(candidate, step);
665 if (!lifecycle) return eve::Result<VehicleEffectUpdate>::failure(lifecycle.status());
666 auto targetCandidate = target_;
667 auto settled = executor_.settle(targetCandidate, std::move(lifecycle).takeValue());
668 if (!settled) return settled;
669 auto result = std::move(settled).takeValue();
670 target_ = std::move(targetCandidate);
671 container_ = std::move(candidate);
673}
674
675VehicleEffectSnapshot VehicleEffectAdapter::snapshot() const { return {container_.snapshot(), target_}; }
676
678 auto valid = executor_.validate(snapshotValue.target);
679 if (!valid) return valid;
680 auto restored = container_.restore(snapshotValue.effects);
681 if (!restored) return restored;
682 target_ = snapshotValue.target;
684}
685
689
690} // namespace eve::vehicle
691
692// VehicleOrderQueueAdapter.cpp
693namespace eve::vehicle {
694
695namespace {} // namespace
696
699 std::unordered_map<std::string, VehicleOrder> payloads;
700};
701
702void VehicleOrderQueueAdapter::pruneTerminalPayloads() {
703 for (auto it = impl_->payloads.begin(); it != impl_->payloads.end();) {
704 auto recordRef = impl_->queue.find(it->first);
705 const orders::Order* record = recordRef ? &recordRef->get() : nullptr;
706 if (record == nullptr ||
708 it = impl_->payloads.erase(it);
709 } else {
710 ++it;
711 }
712 }
713}
714
716
718
720 : impl_(std::make_unique<Impl>(*other.impl_)) {}
721
723 if (this != &other) *impl_ = *other.impl_;
724 return *this;
725}
726
728
730
732 double timeoutSeconds) {
733 auto id = impl_->queue.append(vehicleOrderTypeName(order.type), priority, timeoutSeconds);
734 if (!id) return id;
735 std::string key = std::move(id).takeValue();
736 impl_->payloads.emplace(key, order);
738}
739
741 double timeoutSeconds) {
742 auto id = impl_->queue.replace(vehicleOrderTypeName(order.type), priority, timeoutSeconds);
743 if (!id) return id;
744 std::string key = std::move(id).takeValue();
745 pruneTerminalPayloads();
746 impl_->payloads.emplace(key, order);
748}
749
751 double timeoutSeconds) {
752 auto id = impl_->queue.interrupt(vehicleOrderTypeName(order.type), priority, timeoutSeconds);
753 if (!id) return id;
754 std::string key = std::move(id).takeValue();
755 pruneTerminalPayloads();
756 impl_->payloads.emplace(key, order);
758}
759
761 auto currentRef = impl_->queue.current();
762 orders::Order* current = currentRef ? &currentRef->get() : nullptr;
763 if (current == nullptr)
765 eve::DiagnosticCode::Conflict, "vehicle order queue has no active order", "order", {}, "vehicle.orders"));
766 auto completed = impl_->queue.complete(current->id);
767 if (completed) pruneTerminalPayloads();
768 return completed;
769}
770
772 auto currentRef = impl_->queue.current();
773 orders::Order* current = currentRef ? &currentRef->get() : nullptr;
774 if (current == nullptr)
776 eve::DiagnosticCode::Conflict, "vehicle order queue has no active order", "order", {}, "vehicle.orders"));
777 auto failed = impl_->queue.fail(current->id, reason);
778 if (failed) pruneTerminalPayloads();
779 return failed;
780}
781
782eve::Result<void> VehicleOrderQueueAdapter::cancel(const std::string& id, const std::string& reason) {
783 auto cancelled = impl_->queue.cancel(id, reason);
784 if (cancelled) pruneTerminalPayloads();
785 return cancelled;
786}
787
788void VehicleOrderQueueAdapter::update(double dtSeconds) {
789 auto updated = impl_->queue.update(dtSeconds);
790 updated.ignore("VehicleOrderQueueAdapter exposes a legacy void update boundary");
791 pruneTerminalPayloads();
792}
793
795 impl_->queue.clear();
796 impl_->payloads.clear();
797}
798
800 auto recordRef = impl_->queue.current();
801 const orders::Order* record = recordRef ? &recordRef->get() : nullptr;
802 if (record == nullptr) return nullptr;
803 const auto it = impl_->payloads.find(record->id);
804 return it == impl_->payloads.end() ? nullptr : &it->second;
805}
806
808 int count = 0;
809 for (int i = 0; i < impl_->queue.orderCount(); ++i) {
810 auto recordRef = impl_->queue.orderAt(i);
811 const orders::Order* record = recordRef ? &recordRef->get() : nullptr;
812 if (record != nullptr &&
814 ++count;
815 }
816 }
817 return count;
818}
819
821 legacy.queue.clear();
822 legacy.current = -1;
823 for (int i = 0; i < impl_->queue.orderCount(); ++i) {
824 auto recordRef = impl_->queue.orderAt(i);
825 const orders::Order* record = recordRef ? &recordRef->get() : nullptr;
826 if (record == nullptr ||
828 continue;
829 }
830 const auto it = impl_->payloads.find(record->id);
831 if (it == impl_->payloads.end()) continue;
832 if (record->state == orders::OrderState::Active) legacy.current = static_cast<int>(legacy.queue.size());
833 legacy.queue.push_back(it->second);
834 }
835}
836
838
840
842 : queue(other.queue),
843 current(other.current),
844 adapter(other.adapter == nullptr ? std::make_unique<VehicleOrderQueueAdapter>()
845 : std::make_unique<VehicleOrderQueueAdapter>(*other.adapter)) {}
846
848 if (this == &other) return *this;
849 queue = other.queue;
850 current = other.current;
851 if (other.adapter == nullptr) {
852 adapter = std::make_unique<VehicleOrderQueueAdapter>();
853 } else if (adapter == nullptr) {
854 adapter = std::make_unique<VehicleOrderQueueAdapter>(*other.adapter);
855 } else {
856 *adapter = *other.adapter;
857 }
858 return *this;
859}
860
861VehicleEntity::Orders::Orders(Orders&&) noexcept = default;
862
863VehicleEntity::Orders& VehicleEntity::Orders::operator=(Orders&&) noexcept = default;
864
865} // namespace eve::vehicle
LogicalId target
bool & active
int subject
Definition AnimSmr.cpp:163
std::string output
std::uint64_t revision
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
int priority
bool applied
std::vector< Value > defaults
Definition ECS.cpp:49
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
int instanceId
bool required
std::string id
std::shared_ptr< std::atomic< bool > > cancelled
Poco::JSON::Object::Ptr result
bool valid
std::unordered_set< std::string > tags
std::vector< std::int32_t > order
const std::string * tag
std::string error
Definition Package.cpp:174
std::unique_ptr< ParticleEffect > effect
eve::action::ActionVfxBinding binding
std::array< std::uint64_t, kPixelChunkSize *kPixelChunkSize > updated
PrimitiveHandle handle
std::set< std::string > values
const eve::script::BindingContractRegistry & registry
Object::Ptr value
const EntityFact * entity
RoadNetwork resolved
double number
std::string text
std::string_view source
std::string kind
double current
int count
std::string_view adapter
SimulationTick tick
Json object
int limit
Definition TreeMesh.cpp:166
float step
Definition TreeMesh.cpp:451
const AssetImportLimits & limits
uint32_t index
Owning, renderer-independent dynamic values.
Strongly typed Vehicle definition/entity runtime adapter.
Vehicle-domain effect adapter and armor-zone executor.
uint32_t flags
Stable definition reference backed by LogicalId.
Definition ResourceRef.h:85
static Result< DefinitionRef > fromId(LogicalId id)
Build a definition reference from a valid LogicalId.
const LogicalId & id() const noexcept
Return the stable logical definition identity.
Definition ResourceRef.h:97
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
static std::optional< LogicalId > fromParts(std::string_view namespaceName, std::string_view name)
Builds a logical ID from separate namespace and name components.
Definition Identity.cpp:49
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
std::string_view name() const noexcept
Returns the name component as a view into this object.
Definition Identity.cpp:64
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 Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
Strong, domain-neutral reference to a runtime subject.
Definition SubjectRef.h:26
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
static eve::Result< RuntimeInstance > create(eve::PersistentId instanceId, eve::DefinitionRef definition, eve::Generation definitionGeneration, State state, bool active=true)
Construct a runtime instance after validating its identity.
Deterministic registry of topic-neutral, versioned JSON definitions.
Definition Definitions.h:58
eve::ResultRef< const Definition > resolveHandle(const DefinitionHandle &handle) const
Resolves a generation-qualified handle and reports stale identities.
Id128 public API.
Definition Identity.h:111
std::string format() const
Formats the ID in lower-case canonical UUID text.
Definition Identity.h:172
EffectContainer snapshot() const
Capture an independent lifecycle snapshot for staging/restore.
eve::Result< const EffectInstance * > resolve(EffectHandle handle) const
Resolve a generation-qualified handle for this call.
eve::Result< void > remove(const std::string &id, const std::string &reason="removed")
Removes one active instance and emits a Removed event.
EffectContainer clone() const
Create an independent deep copy suitable for ECS staging.
eve::Result< std::string > apply(const EffectDefinition &definition, const std::string &subject, const std::string &source={})
Applies a definition and returns the stable instance identifier.
eve::Result< void > restore(const EffectContainer &snapshot)
Restore a previously captured snapshot as one observable commit.
Executes lifecycle time progression for an EffectContainer.
eve::Result< EffectUpdateSummary > advance(EffectContainer &container, double dtSeconds) const
Advances one container by a legacy seconds delta.
Generic priority order queue with no gameplay or entity semantics.
Binds a VehicleDefinition to a VehicleEntity without a new root type.
eve::Result< std::string > snapshotJson(eve::Revision revision, eve::SimulationTick tick, const eve::SnapshotHashProvider &hashProvider) const
Serialize snapshot() as canonical deterministic JSON.
eve::Result< void > restore(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider)
Verify and restore a same-generation vehicle snapshot atomically.
bool isActive() const noexcept
Return the active guard state.
void setActive(bool active) noexcept
Set the active guard used by RejectWhileActive.
eve::Result< eve::SnapshotEnvelope > snapshot(eve::Revision revision, eve::SimulationTick tick, const eve::SnapshotHashProvider &hashProvider) const
Capture mutable entity state in a common SnapshotEnvelope.
eve::definition::DefinitionHandle definitionHandle() const noexcept
Return the generation-qualified definition handle.
const eve::definition::InstanceIdentity & identity() const noexcept
Borrow common instance identity and exact definition generation.
static eve::Result< VehicleDefinitionRuntime > create(eve::definitions::DefinitionRegistry &registry, eve::DefinitionRef definition, eve::PersistentId instanceId, eve::definition::ReloadPolicy policy=eve::definition::ReloadPolicy::RebuildInstance)
Create from a common vehicle:<name> definition.
const VehicleRuntimeState & state() const noexcept
Borrow mutable vehicle entity state.
eve::Result< void > applyTo(VehicleEntity *entity) const
Project typed state and identity into a borrowed VehicleEntity.
eve::Result< VehicleDefinition > definition() const
Resolve and parse the current strongly typed VehicleDefinition.
eve::Result< eve::definition::ReloadOutcome > reload(eve::definition::ReloadPolicy policy)
Reload the registry's current generation using a typed policy.
VehicleEffectSnapshot snapshot() const
Capture effects and target state.
eve::Result< void > restore(const VehicleEffectSnapshot &snapshot)
Restore a snapshot and invalidate prior handles.
eve::Result< const effects::EffectInstance * > resolve(effects::EffectHandle handle) const
Resolve a live handle as a borrowed observation.
eve::Result< VehicleEffectUpdate > advance(const eve::SimulationStep &step)
Advance and settle vehicle effects atomically.
eve::Result< effects::EffectHandle > apply(const VehicleEffectDefinition &definition, eve::SubjectRef subject)
Apply one typed vehicle effect to a stable subject.
eve::Result< void > remove(effects::EffectHandle handle)
Remove one generation-qualified effect handle.
eve::Result< VehicleEffectUpdate > settle(VehicleEffectTarget &target, effects::EffectUpdateSummary lifecycle) const
Settle common periodic triggers through vehicle armor policy.
eve::Result< void > validate(const VehicleEffectTarget &target) const
Validate hull and armor invariants.
eve::Result< void > applyImmediate(VehicleEffectTarget &target, const effects::EffectInstance &effect) const
Apply an immediate disable strategy to a staged target.
载具实体:数据全部在组件里,行为在 VehicleSystem。
Maps VehicleOrder domain payloads onto an orders::CommandQueue.
void syncCompatibility(VehicleEntity::Orders &legacy) const
Refreshes the legacy component projection.
const VehicleOrder * current() const
Returns the Vehicle payload for the active generic order, or null.
eve::Result< std::string > replace(const VehicleOrder &order, int priority=0, double timeoutSeconds=0.0)
Cancels unfinished orders and starts a replacement.
eve::Result< std::string > interrupt(const VehicleOrder &order, int priority=0, double timeoutSeconds=0.0)
Interrupts the active order when the generic priority permits.
int activeOrQueuedCount() const
Returns the number of active and queued Vehicle orders.
~VehicleOrderQueueAdapter()
Releases the owned generic queue and domain payloads.
void update(double dtSeconds)
Advances generic timeout handling.
eve::Result< void > failCurrent(const std::string &reason)
Fails the current generic order and activates the next one.
VehicleOrderQueueAdapter & operator=(const VehicleOrderQueueAdapter &)
Deep-copies generic lifecycle state and Vehicle payloads.
VehicleOrderQueueAdapter()
Creates an empty adapter with an owned generic queue.
eve::Result< void > cancel(const std::string &id, const std::string &reason="cancelled")
Cancels an active or queued generic order by stable id.
eve::Result< std::string > append(const VehicleOrder &order, int priority=0, double timeoutSeconds=0.0)
Appends a Vehicle domain order to the generic queue.
eve::Result< void > completeCurrent()
Completes the current generic order and activates the next one.
void clear()
Clears generic queue history and Vehicle domain payloads.
载具模块(eve.Vehicle)。
Definition Vehicle.h:33
eve::definitions::DefinitionRegistry & definitionRegistry() noexcept
Return the canonical common registry for vehicle definitions.
Definition Vehicle.h:59
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
ReloadPolicy
Policy used when a live definition is replaced.
eve::Result< eve::SnapshotEnvelope > snapshotRuntimeInstance(const RuntimeInstance< State > &runtime, std::string type, eve::LogicalId schema, eve::SchemaVersion schemaVersion, eve::Revision revision, eve::SimulationTick tick, const eve::SnapshotHashProvider &hashProvider, const RuntimeStateEncoder< State > &encode)
Capture a typed runtime instance in the common snapshot envelope.
eve::Result< void > restoreRuntimeInstance(RuntimeInstance< State > &runtime, const eve::SnapshotEnvelope &snapshot, std::string_view expectedType, const eve::LogicalId &expectedSchema, eve::SchemaVersion expectedVersion, const eve::SnapshotHashProvider &hashProvider, const RuntimeStateDecoder< State > &decode)
Verify and atomically restore a typed runtime instance.
std::function< eve::Result< State >(const eve::Value &)> RuntimeStateDecoder
Decodes one domain-owned runtime state from an owning Value.
std::function< eve::Result< eve::Value >(const State &)> RuntimeStateEncoder
Converts one domain-owned runtime state into an owning Value.
eve::Diagnostic Diagnostic
eve::Result< T > Result
bool has(const std::vector< std::reference_wrapper< const HouseComponent > > &values)
bool readString(const eve::Value::Object &object, const char *name, std::string &output)
Result< bool > readBool(const Value::Object &object, std::string_view name)
Reads a required boolean.
eve::Result< double > readNumber(const eve::Value::Object &object, std::string_view name)
Reads a required finite number.
驾驶者接口与玩家控制状态。
const char * vehicleOrderTypeName(VehicleOrderType type)
命令类型的字符串名("move" | "attack_move" | ...)。
Definition Vehicle.cpp:85
VehicleEffectKind
Vehicle-specific effect strategy.
eve::Result< VehicleDefinition > parseVehicleDefinition(const eve::definitions::Definition &source)
Parse one canonical registry definition into a short-lived typed projection.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Result< float > readFiniteFloatValue(const Value &value)
Convert an Integer or Double to a finite Float after validating its source range.
Definition Value.cpp:81
Result< std::string > serializeSnapshotEnvelope(const SnapshotEnvelope &snapshot)
Serialize an envelope as deterministic compact JSON.
Definition Snapshot.cpp:184
Result< bool > readBoolValue(const Value &value)
Read a Bool without coercing integers, strings or other kinds.
Definition Value.cpp:50
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
Result< std::string > readNonEmptyStringMember(const Value::Object &object, std::string_view name)
Read a required nonempty string field as an independent owning value.
Definition Value.cpp:33
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
A generation-qualified reference to one definition incarnation.
Canonical identity carried by every typed runtime instance.
One immutable view of a registered versioned JSON definition.
Definition Definitions.h:31
Immutable-by-convention template used to create effect instances.
std::vector< std::string > tags
double period
Period in seconds for domain executor settlement; zero disables periodic ticks.
eve::Result< void > validate() const
Validates definition fields without changing any state.
Generation-qualified local reference to a canonical effect instance.
One owned runtime effect fact.
Summary returned by the lifecycle executor after one simulation step.
One entity-agnostic command and its lifecycle metadata.
装甲区(Phase 4 伤害管线使用;Phase 2 仅作为定义数据保留)。
武器挂点声明(载具模板的一部分)。
座位声明(载具模板的一部分,FPS 面)。
Wheel mount for 3D ray suspension or 2D top-down tire contact.
float x
Local mount in meters: 3D uses +Y up; top-down 2D uses XY with z = 0.
载具模板(registerVehiclesFromJson 注册,进程级注册表)。
Strong vehicle definition projected into the common lifecycle.
In-memory vehicle effect snapshot.
effects::EffectContainer effects
Mutable vehicle state changed by the effect executor.
Result of one vehicle lifecycle step and armor settlement.
effects::EffectUpdateSummary lifecycle
Vehicle order lifecycle adapter and compatibility projection.
std::unique_ptr< VehicleOrderQueueAdapter > adapter
Orders & operator=(const Orders &other)
Deep-copies the queue and domain payload projection for ECS staging.
Orders()
Creates an empty adapter-backed order component.
std::vector< VehicleOrder > queue
~Orders()
Releases the adapter-owned generic queue.
std::unordered_map< std::string, VehicleOrder > payloads
一条 Vehicle 领域命令(生命周期由 Vehicle order adapter 执行)。
Mutable state owned by one typed vehicle runtime instance.