载入中...
搜索中...
未找到
ClimbingSnapshot.cpp
浏览该文件的文档.
1#include "climbing/Climbing.h"
2#include "common/ValueRead.h"
3
6#include "physics/World3D.h"
7
8#include <charconv>
9#include <cmath>
10#include <limits>
11#include <optional>
12#include <utility>
13
14namespace eve::climbing {
15namespace {
16
17const eve::Value* field(const eve::Value::Object& object, std::string_view name) {
18 const auto found = object.find(std::string(name));
19 return found == object.end() ? nullptr : &found->second;
20}
21
22bool readString(const eve::Value::Object& object, std::string_view name, std::string& output) {
23 auto text = eve::readStringMember(object, name);
24 if (!text) return false;
25 output = std::move(text.value());
26 return true;
27}
28
29bool readInt64(const eve::Value::Object& object, std::string_view name, std::int64_t& output) {
30 const auto* value = field(object, name);
31 if (!value) return false;
32 auto parsed = eve::readInt64Value(*value);
33 if (!parsed) return false;
34 output = parsed.value();
35 return true;
36}
37
38bool readBool(const eve::Value::Object& object, std::string_view name, bool& output, bool defaultValue, bool required) {
39 const auto* value = field(object, name);
40 if (!value) {
42 return !required;
43 }
44 auto parsed = eve::readBoolValue(*value);
45 if (!parsed) return false;
46 output = parsed.value();
47 return true;
48}
49
50bool readUint64String(const eve::Value::Object& object, std::string_view name, std::uint64_t& output) {
51 auto parsed = eve::scanUnsignedStringMember(object, name);
52 if (!parsed) return false;
53 output = parsed.value().value;
54 return parsed.value().consumed == parsed.value().size;
55}
56
57eve::Value vecValue(Vec3 value) {
59}
60
61bool numericFloat(const eve::Value& value, float& output) {
62 auto parsed = eve::readFiniteFloatValue(value);
63 if (!parsed) return false;
64 output = parsed.value();
65 return true;
66}
67
68bool readVec(const eve::Value::Object& object, std::string_view name, Vec3& output) {
69 const eve::Value* value = field(object, name);
70 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
71 return array && array->size() == 3 && numericFloat((*array)[0], output.x) && numericFloat((*array)[1], output.y) &&
72 numericFloat((*array)[2], output.z);
73}
74
75bool readOptionalFloat(const eve::Value::Object& object, std::string_view name, float& output) {
76 const eve::Value* value = field(object, name);
77 return !value || numericFloat(*value, output);
78}
79
80std::string_view phaseName(ClimbingPhase phase) {
81 switch (phase) {
82 case ClimbingPhase::Idle: return "idle";
83 case ClimbingPhase::Requested: return "requested";
84 case ClimbingPhase::Aligning: return "aligning";
85 case ClimbingPhase::Launching: return "launching";
86 case ClimbingPhase::Climbing: return "climbing";
87 case ClimbingPhase::Landing: return "landing";
88 case ClimbingPhase::Recovering: return "recovering";
89 case ClimbingPhase::Hanging: return "hanging";
90 case ClimbingPhase::Dropping: return "dropping";
91 case ClimbingPhase::Completed: return "completed";
92 case ClimbingPhase::Cancelled: return "cancelled";
93 case ClimbingPhase::Failed: return "failed";
94 case ClimbingPhase::Balanced: return "balanced";
95 case ClimbingPhase::Swinging: return "swinging";
96 }
97 return "unknown";
98}
99
100bool readPhase(std::string_view value, ClimbingPhase& output) {
101 if (value == "idle")
103 else if (value == "requested")
105 else if (value == "aligning")
107 else if (value == "launching")
109 else if (value == "climbing" || value == "traversing")
110 // "traversing" is accepted only to migrate snapshots emitted before the
111 // public climbing terminology was finalized.
113 else if (value == "landing")
115 else if (value == "recovering")
117 else if (value == "hanging")
119 else if (value == "dropping")
121 else if (value == "completed")
123 else if (value == "cancelled")
125 else if (value == "failed")
127 else if (value == "balanced")
129 else if (value == "swinging")
131 else
132 return false;
133 return true;
134}
135
136eve::Value eventArrayValue(const std::vector<ClimbingEvent>& events) { return climbingEventArrayValue(events); }
137
138eve::Result<std::vector<ClimbingEvent>> readEvents(const eve::Value& value, std::uint64_t nextExecutionId) {
139 const auto* array = value.getIf<eve::Value::Array>();
140 if (!array || array->size() > ClimbingRuntime::PendingEventCapacity)
141 return eve::Result<std::vector<ClimbingEvent>>::failure(
142 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "pending climbing events must be a bounded array",
143 "pendingEvents", {}, "climbing.snapshot"));
144 std::vector<ClimbingEvent> events;
145 events.reserve(array->size());
147 bool first = true;
148 for (std::size_t index = 0; index < array->size(); ++index) {
149 const auto* object = (*array)[index].getIf<eve::Value::Object>();
150 ClimbingEvent event;
151 std::string kind;
152 std::uint64_t tick = 0;
153 std::uint64_t executionId = 0;
154 if (!object || !readString(*object, "kind", kind) ||
156 !readString(*object, "actionId", event.actionId) || event.actionId.empty() ||
157 !readUint64String(*object, "tick", tick) || !readUint64String(*object, "executionId", executionId) ||
158 executionId == 0 || executionId >= nextExecutionId)
159 return eve::Result<std::vector<ClimbingEvent>>::failure(eve::Diagnostic::error(
160 eve::DiagnosticCode::ParseError, "pending climbing event is missing or inconsistent",
161 "pendingEvents." + std::to_string(index), {}, "climbing.snapshot"));
162 if (const eve::Value* metadataValue = field(*object, "metadata")) {
163 const auto* metadata = metadataValue->getIf<eve::Value::Array>();
164 if (!metadata)
166 eve::DiagnosticCode::ParseError, "climbing event metadata must be an array",
167 "pendingEvents." + std::to_string(index) + ".metadata", {}, "climbing.snapshot"));
168 event.metadata.reserve(metadata->size());
169 for (const eve::Value& item : *metadata) {
170 const auto* text = item.getIf<std::string>();
171 if (!text || text->empty())
172 return eve::Result<std::vector<ClimbingEvent>>::failure(eve::Diagnostic::error(
173 eve::DiagnosticCode::ParseError, "climbing event metadata must contain non-empty strings",
174 "pendingEvents." + std::to_string(index) + ".metadata", {}, "climbing.snapshot"));
175 event.metadata.push_back(*text);
176 }
177 }
178 event.tick = eve::SimulationTick(tick);
179 event.executionId = ClimbingExecutionId(executionId);
180 if (!first && event.tick < previousTick)
182 eve::DiagnosticCode::InvariantViolation, "pending climbing events must be ordered by tick",
183 "pendingEvents." + std::to_string(index) + ".tick", {}, "climbing.snapshot"));
184 first = false;
185 previousTick = event.tick;
186 events.push_back(std::move(event));
187 }
188 return eve::Result<std::vector<ClimbingEvent>>::success(std::move(events));
189}
190
191eve::Value candidateValue(const ClimbingCandidate& value) {
192 return eve::Value::object({
193 {"actionId", value.actionId},
194 {"definitionGeneration", std::to_string(value.definitionGeneration)},
195 {"world", std::to_string(value.world.packed())},
196 {"obstacleBody", std::to_string(value.obstacleBody.packed())},
197 {"obstacleShape", std::to_string(value.obstacleShape.packed())},
198 {"obstacleBodyId", value.obstacleBodyId},
199 {"obstacleShapeId", value.obstacleShapeId},
200 {"ignoredBodyId", value.ignoredBodyId},
201 {"frontPoint", vecValue(value.frontPoint)},
202 {"topPoint", vecValue(value.topPoint)},
203 {"landingFeet", vecValue(value.landingFeet)},
204 {"surfaceNormal", vecValue(value.surfaceNormal)},
205 {"surfaceTangent", vecValue(value.surfaceTangent)},
206 {"leftHandAnchor", vecValue(value.leftHandAnchor)},
207 {"rightHandAnchor", vecValue(value.rightHandAnchor)},
208 {"bodyLocalTop", vecValue(value.bodyLocalTop)},
209 {"bodyLocalLanding", vecValue(value.bodyLocalLanding)},
210 {"obstacleHeight", value.obstacleHeight},
211 {"obstacleDepth", value.obstacleDepth},
212 {"gapDistance", value.gapDistance},
213 {"clearanceHeight", value.clearanceHeight},
214 {"slopeRadians", value.slopeRadians},
215 {"curvature", value.curvature},
216 {"supportShapeTag", value.supportShapeTag},
217 {"supportMaterialId", value.supportMaterialId},
218 {"probeRecipe", static_cast<std::int64_t>(value.probeRecipe)},
219 {"score", value.score},
220 {"kind", static_cast<std::int64_t>(value.kind)},
221 {"support", static_cast<std::int64_t>(value.support)},
222 });
223}
224
225eve::Value anchorValue(ClimbingAnchorGraphHandleRef graph, const ClimbingAnchorNodeRef& node,
226 const ClimbingAnchorReservation& reservation) {
227 if (!graph.isValid() || reservation.id.isZero()) return eve::Value();
228 return eve::Value::object({
229 {"graphHandle", std::to_string(graph.packed())},
230 {"graphOwnerEpoch", std::to_string(graph.ownerEpoch)},
231 {"graphId", node.graphId},
232 {"nodeId", node.nodeId},
233 {"nodeGraphGeneration", std::to_string(node.graphGeneration)},
234 {"reservationId", std::to_string(reservation.id.value())},
235 {"reservationGraphGeneration", std::to_string(reservation.graphGeneration)},
236 {"claimGeneration", std::to_string(reservation.claimGeneration)},
237 {"slot", static_cast<std::int64_t>(reservation.slot)},
238 {"agentId", std::to_string(reservation.occupant.agentId.value())},
239 {"executionId", std::to_string(reservation.occupant.executionId.value())},
240 });
241}
242
243eve::Result<ClimbingCandidate> readCandidate(const eve::Value& value, std::int64_t snapshotVersion) {
244 const auto* object = value.getIf<eve::Value::Object>();
245 if (!object)
247 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "runtime candidate must be an object",
248 "execution.candidate", {}, "climbing.snapshot"));
249 ClimbingCandidate result;
250 std::uint64_t world = 0, body = 0, shape = 0, definitionGeneration = 1;
251 std::int64_t bodyId = 0, shapeId = 0, ignoredBodyId = 0, score = 0, kind = 0, support = 0;
252 std::int64_t supportShapeTag = 0, supportMaterialId = 0, probeRecipe = 0;
253 const eve::Value* heightValue = field(*object, "obstacleHeight");
254 const eve::Value* depthValue = field(*object, "obstacleDepth");
255 const eve::Value* gapValue = field(*object, "gapDistance");
256 const eve::Value* clearanceValue = field(*object, "clearanceHeight");
257 const eve::Value* slopeValue = field(*object, "slopeRadians");
258 const eve::Value* curvatureValue = field(*object, "curvature");
259 if (!readString(*object, "actionId", result.actionId) ||
260 (field(*object, "definitionGeneration") &&
261 !readUint64String(*object, "definitionGeneration", definitionGeneration)) ||
262 definitionGeneration == 0 || !readUint64String(*object, "world", world) ||
263 !readUint64String(*object, "obstacleBody", body) || !readUint64String(*object, "obstacleShape", shape) ||
264 !readInt64(*object, "obstacleBodyId", bodyId) || bodyId < std::numeric_limits<int>::min() ||
265 bodyId > std::numeric_limits<int>::max() || !readInt64(*object, "obstacleShapeId", shapeId) ||
266 shapeId < std::numeric_limits<int>::min() || shapeId > std::numeric_limits<int>::max() ||
267 !readInt64(*object, "ignoredBodyId", ignoredBodyId) || ignoredBodyId < std::numeric_limits<int>::min() ||
268 ignoredBodyId > std::numeric_limits<int>::max() || !readVec(*object, "frontPoint", result.frontPoint) ||
269 !readVec(*object, "topPoint", result.topPoint) || !readVec(*object, "landingFeet", result.landingFeet) ||
270 !readVec(*object, "surfaceNormal", result.surfaceNormal) ||
271 !readVec(*object, "surfaceTangent", result.surfaceTangent) ||
272 !readVec(*object, "leftHandAnchor", result.leftHandAnchor) ||
273 !readVec(*object, "rightHandAnchor", result.rightHandAnchor) ||
274 !readVec(*object, "bodyLocalTop", result.bodyLocalTop) ||
275 !readVec(*object, "bodyLocalLanding", result.bodyLocalLanding) || !heightValue ||
276 !numericFloat(*heightValue, result.obstacleHeight) || !readInt64(*object, "score", score) ||
277 !readInt64(*object, "kind", kind) || kind < 0 ||
278 kind > static_cast<std::int64_t>(ClimbingActionKind::BarSwing) ||
279 !readInt64(*object, "support", support) ||
280 support < 0 || support > static_cast<std::int64_t>(HangSupport::Free))
282 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "runtime candidate has missing or invalid fields",
283 "execution.candidate", {}, "climbing.snapshot"));
284 if ((snapshotVersion >= 4 && (!depthValue || !gapValue || !clearanceValue || !slopeValue || !curvatureValue ||
285 !field(*object, "supportShapeTag") || !field(*object, "supportMaterialId") ||
286 !field(*object, "probeRecipe"))) ||
287 (depthValue && !numericFloat(*depthValue, result.obstacleDepth)) ||
288 (gapValue && !numericFloat(*gapValue, result.gapDistance)) ||
289 (clearanceValue && !numericFloat(*clearanceValue, result.clearanceHeight)) ||
290 (slopeValue && !numericFloat(*slopeValue, result.slopeRadians)) ||
291 (curvatureValue && !numericFloat(*curvatureValue, result.curvature)) ||
292 (field(*object, "supportShapeTag") && !readInt64(*object, "supportShapeTag", supportShapeTag)) ||
293 supportShapeTag < std::numeric_limits<int>::min() || supportShapeTag > std::numeric_limits<int>::max() ||
294 (field(*object, "supportMaterialId") && !readInt64(*object, "supportMaterialId", supportMaterialId)) ||
295 supportMaterialId < std::numeric_limits<int>::min() ||
296 supportMaterialId > std::numeric_limits<int>::max() ||
297 (field(*object, "probeRecipe") && !readInt64(*object, "probeRecipe", probeRecipe)) || probeRecipe < 0 ||
298 probeRecipe > static_cast<std::int64_t>(ClimbingProbeRecipe::AnchorGraph))
300 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "runtime candidate metrics are missing or invalid",
301 "execution.candidate", {}, "climbing.snapshot"));
302 result.definitionGeneration = definitionGeneration;
306 result.obstacleBodyId = static_cast<int>(bodyId);
307 result.obstacleShapeId = static_cast<int>(shapeId);
308 result.ignoredBodyId = static_cast<int>(ignoredBodyId);
309 result.score = score;
310 result.kind = static_cast<ClimbingActionKind>(kind);
311 result.supportShapeTag = static_cast<int>(supportShapeTag);
312 result.supportMaterialId = static_cast<int>(supportMaterialId);
313 result.probeRecipe = static_cast<ClimbingProbeRecipe>(probeRecipe);
314 result.support = static_cast<HangSupport>(support);
316}
317
318bool activePhase(ClimbingPhase phase) {
321}
322
323} // namespace
324
326 auto profile = encodeClimbingProfileDefinition(profile_);
327 if (!profile) return eve::Result<eve::Value>::failure(profile.status());
328 eve::Value::Object root{{"schemaId", eve::Value(std::string(SnapshotSchemaId))},
329 {"schemaVersion", eve::Value(SnapshotSchemaVersion)},
330 {"phase", eve::Value(std::string(phaseName(phase_)))},
331 {"terminalCode", eve::Value(terminalCode_)},
332 {"definitionGeneration", eve::Value(std::to_string(definitionGeneration_))},
333 {"profile", std::move(profile).takeValue()},
334 {"previousActionId", eve::Value(previousActionId_)},
335 {"nextExecutionId", eve::Value(std::to_string(nextExecutionId_))},
336 {"pendingEvents", eventArrayValue(pendingEvents_)}};
337 if (!execution_) {
338 root.emplace("execution", eve::Value());
340 }
341 auto action = encodeClimbingActionDefinition(execution_->action);
342 if (!action) return eve::Result<eve::Value>::failure(action.status());
344 {"executionId", std::to_string(execution_->executionId.value())},
345 {"definitionGeneration", std::to_string(execution_->definitionGeneration)},
346 {"action", std::move(action).takeValue()},
347 {"candidate", candidateValue(execution_->candidate)},
348 {"startFeet", vecValue(execution_->startFeet)},
349 {"currentFeet", vecValue(execution_->currentFeet)},
350 {"lastPlannedFeet", vecValue(execution_->lastPlannedFeet)},
351 {"elapsedNs", execution_->elapsed.nanoseconds()},
352 {"durationNs", execution_->duration.nanoseconds()},
353 {"lastTick", std::to_string(execution_->lastTick.value())},
354 {"velocity", vecValue(execution_->velocity)},
355 {"accumulatedResidual", vecValue(execution_->accumulatedResidual)},
356 {"horizontalWarpUsed", execution_->horizontalWarpUsed},
357 {"verticalWarpUsed", execution_->verticalWarpUsed},
358 {"facingWarpUsed", execution_->facingWarpUsed},
359 {"leftContactEmitted", execution_->leftContactEmitted},
360 {"rightContactEmitted", execution_->rightContactEmitted},
361 {"landContactReleased", execution_->landContactReleased},
362 {"compactCollisionActive", execution_->compactCollisionActive},
363 {"branchWindowOpen", execution_->branchWindowOpen},
364 {"anchor", anchorValue(execution_->anchorGraph, execution_->anchorNode,
365 execution_->anchorReservation)},
366 };
367 state.emplace(
368 "sourceAnchor",
369 execution_->sourceAnchorNode
370 ? eve::Value::object({{"graphId", execution_->sourceAnchorNode->graphId},
371 {"nodeId", execution_->sourceAnchorNode->nodeId},
372 {"generation", std::to_string(execution_->sourceAnchorNode->graphGeneration)}})
373 : eve::Value());
374 root.emplace("execution", eve::Value(std::move(state)));
376}
377
378eve::Result<void> ClimbingRuntime::restore(const eve::Value& value, physics::World3D& world) {
379 const auto* root = value.getIf<eve::Value::Object>();
380 if (!root)
382 eve::DiagnosticCode::ParseError, "runtime snapshot must be an object", {}, {}, "climbing.snapshot"));
383 std::string schemaId;
384 std::int64_t version = -1;
385 std::string phaseText;
386 std::string terminalCode;
387 std::string candidatePreviousActionId;
388 std::uint64_t candidateNextExecutionId = 1;
389 std::uint64_t candidateDefinitionGeneration = definitionGeneration_;
390 if (!readString(*root, "schemaId", schemaId) || schemaId != SnapshotSchemaId ||
391 !readInt64(*root, "schemaVersion", version) || version < 0 || version > SnapshotSchemaVersion ||
392 !readString(*root, "phase", phaseText) ||
393 (version >= 1 && !readString(*root, "terminalCode", terminalCode))) {
394 if (version > SnapshotSchemaVersion)
396 "climbing.restore.version_unsupported",
397 "schemaVersion", {}, "climbing.snapshot"));
399 "invalid climbing runtime snapshot envelope", {}, {},
400 "climbing.snapshot"));
401 }
402 if (version >= 4 && !readString(*root, "previousActionId", candidatePreviousActionId))
404 "invalid previous climbing action id",
405 "previousActionId", {}, "climbing.snapshot"));
406 if (field(*root, "nextExecutionId") && !readUint64String(*root, "nextExecutionId", candidateNextExecutionId))
408 "invalid next climbing execution id",
409 "nextExecutionId", {}, "climbing.snapshot"));
410 if (field(*root, "definitionGeneration") &&
411 (!readUint64String(*root, "definitionGeneration", candidateDefinitionGeneration) ||
412 candidateDefinitionGeneration == 0))
414 "invalid climbing definition generation",
415 "definitionGeneration", {}, "climbing.snapshot"));
416 ClimbingProfile candidateProfile = profile_;
417 if (const eve::Value* profileValue = field(*root, "profile")) {
418 auto decodedProfile = decodeClimbingProfileDefinition(*profileValue);
419 if (!decodedProfile) return eve::Result<void>::failure(decodedProfile.status());
420 candidateProfile = std::move(decodedProfile).takeValue();
421 }
422 ClimbingPhase candidatePhase;
423 if (!readPhase(phaseText, candidatePhase))
425 eve::DiagnosticCode::ParseError, "invalid climbing runtime phase", "phase", {}, "climbing.snapshot"));
426 const eve::Value* executionValue = field(*root, "execution");
427 if (!executionValue)
429 "runtime snapshot execution field is required",
430 "execution", {}, "climbing.snapshot"));
431 std::optional<Execution> candidateExecution;
432 if (!executionValue->isNull()) {
433 const auto* state = executionValue->getIf<eve::Value::Object>();
434 const eve::Value* actionValue = state ? field(*state, "action") : nullptr;
435 const eve::Value* candidateValueField = state ? field(*state, "candidate") : nullptr;
436 if (!state || !actionValue || !candidateValueField)
438 "invalid climbing execution object", "execution",
439 {}, "climbing.snapshot"));
440 auto action = decodeClimbingActionDefinition(*actionValue);
441 if (!action) return eve::Result<void>::failure(action.status());
442 auto candidate = readCandidate(*candidateValueField, version);
443 if (!candidate) return eve::Result<void>::failure(candidate.status());
444 Execution parsed;
445 std::uint64_t executionId = 1;
446 std::uint64_t executionDefinitionGeneration = candidateDefinitionGeneration;
447 if (field(*state, "executionId") && !readUint64String(*state, "executionId", executionId))
449 "invalid climbing execution id",
450 "execution.executionId", {}, "climbing.snapshot"));
451 parsed.executionId = ClimbingExecutionId(executionId);
452 if (field(*state, "definitionGeneration") &&
453 (!readUint64String(*state, "definitionGeneration", executionDefinitionGeneration) ||
454 executionDefinitionGeneration == 0))
456 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "invalid execution definition generation",
457 "execution.definitionGeneration", {}, "climbing.snapshot"));
458 parsed.definitionGeneration = executionDefinitionGeneration;
459 parsed.action = std::move(action).takeValue();
460 parsed.candidate = std::move(candidate).takeValue();
461 std::int64_t elapsedNs = 0, durationNs = 0;
462 std::uint64_t lastTick = 0;
463 if (parsed.action.id != parsed.candidate.actionId ||
464 (field(*state, "definitionGeneration") &&
465 parsed.candidate.definitionGeneration != parsed.definitionGeneration) ||
466 !readVec(*state, "startFeet", parsed.startFeet) ||
467 !readVec(*state, "currentFeet", parsed.currentFeet) ||
468 !readVec(*state, "lastPlannedFeet", parsed.lastPlannedFeet) || !readInt64(*state, "elapsedNs", elapsedNs) ||
469 elapsedNs < 0 || !readInt64(*state, "durationNs", durationNs) || durationNs <= 0 ||
470 !readUint64String(*state, "lastTick", lastTick) || !readVec(*state, "velocity", parsed.velocity) ||
471 !readVec(*state, "accumulatedResidual", parsed.accumulatedResidual) ||
472 !readOptionalFloat(*state, "horizontalWarpUsed", parsed.horizontalWarpUsed) ||
473 !readOptionalFloat(*state, "verticalWarpUsed", parsed.verticalWarpUsed) ||
474 !readOptionalFloat(*state, "facingWarpUsed", parsed.facingWarpUsed) || parsed.horizontalWarpUsed < 0.f ||
475 parsed.verticalWarpUsed < 0.f || parsed.facingWarpUsed < 0.f ||
476 !readBool(*state, "leftContactEmitted", parsed.leftContactEmitted, false, version != 0) ||
477 !readBool(*state, "rightContactEmitted", parsed.rightContactEmitted, false, version != 0) ||
478 !readBool(*state, "landContactReleased", parsed.landContactReleased, false, false) ||
479 !readBool(*state, "compactCollisionActive", parsed.compactCollisionActive, false, false) ||
480 !readBool(*state, "branchWindowOpen", parsed.branchWindowOpen, false, false))
482 eve::DiagnosticCode::ParseError, "climbing execution has missing or inconsistent fields", "execution",
483 {}, "climbing.snapshot"));
484 const eve::Value* anchorField = field(*state, "anchor");
485 if (version >= 3 && !anchorField)
487 "runtime snapshot anchor field is required",
488 "execution.anchor", {}, "climbing.snapshot"));
489 if (anchorField && !anchorField->isNull()) {
490 if (version < 3)
492 eve::DiagnosticCode::ParseError, "legacy runtime snapshot cannot contain an anchor claim",
493 "execution.anchor", {}, "climbing.snapshot"));
494 const auto* anchor = anchorField->getIf<eve::Value::Object>();
495 std::uint64_t graphHandle = 0, graphOwnerEpoch = 0, nodeGraphGeneration = 0;
496 std::uint64_t reservationId = 0, reservationGraphGeneration = 0, claimGeneration = 0;
497 std::uint64_t agentId = 0, occupantExecutionId = 0;
498 std::int64_t slot = -1;
499 std::string graphId, nodeId;
500 if (!anchor || !readUint64String(*anchor, "graphHandle", graphHandle) ||
501 !readUint64String(*anchor, "graphOwnerEpoch", graphOwnerEpoch) || graphOwnerEpoch == 0 ||
502 !readString(*anchor, "graphId", graphId) || graphId.empty() ||
503 !readString(*anchor, "nodeId", nodeId) || nodeId.empty() ||
504 !readUint64String(*anchor, "nodeGraphGeneration", nodeGraphGeneration) ||
505 nodeGraphGeneration == 0 || !readUint64String(*anchor, "reservationId", reservationId) ||
506 reservationId == 0 ||
507 !readUint64String(*anchor, "reservationGraphGeneration", reservationGraphGeneration) ||
508 reservationGraphGeneration == 0 ||
509 !readUint64String(*anchor, "claimGeneration", claimGeneration) || claimGeneration == 0 ||
510 !readInt64(*anchor, "slot", slot) || slot < 0 ||
511 slot > static_cast<std::int64_t>(std::numeric_limits<std::uint32_t>::max()) ||
512 !readUint64String(*anchor, "agentId", agentId) || agentId == 0 ||
513 !readUint64String(*anchor, "executionId", occupantExecutionId) || occupantExecutionId == 0)
515 eve::DiagnosticCode::ParseError, "runtime anchor claim has missing or invalid fields",
516 "execution.anchor", {}, "climbing.snapshot"));
517 parsed.anchorGraph.handle = eve::RuntimeHandle<ClimbingAnchorGraphHandleTag>::fromPacked(graphHandle);
518 parsed.anchorGraph.ownerEpoch = graphOwnerEpoch;
519 parsed.anchorNode = {std::move(graphId), std::move(nodeId), nodeGraphGeneration};
520 parsed.anchorReservation = {ClimbingAnchorReservationId(reservationId), reservationGraphGeneration,
521 claimGeneration, parsed.anchorNode.nodeId, static_cast<std::uint32_t>(slot),
522 {ClimbingAnchorAgentId(agentId), ClimbingExecutionId(occupantExecutionId)}};
523 if (!parsed.anchorGraph.isValid() || nodeGraphGeneration != reservationGraphGeneration ||
524 parsed.executionId != parsed.anchorReservation.occupant.executionId)
526 "runtime anchor identities are inconsistent",
527 "execution.anchor", {}, "climbing.snapshot"));
528 }
529 const eve::Value* sourceField = field(*state, "sourceAnchor");
530 if (version >= 5 && !sourceField)
532 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "transition source field is required",
533 "execution.sourceAnchor", {}, "climbing.snapshot"));
534 if (sourceField && !sourceField->isNull()) {
536 const auto* object = sourceField->getIf<eve::Value::Object>();
537 if (version < 5 || !object || !parsed.anchorGraph.isValid() ||
538 !readString(*object, "graphId", source.graphId) || !readString(*object, "nodeId", source.nodeId) ||
539 source.nodeId.empty() || !readUint64String(*object, "generation", source.graphGeneration) ||
540 source.graphId != parsed.anchorNode.graphId ||
541 source.graphGeneration != parsed.anchorNode.graphGeneration)
543 eve::DiagnosticCode::ParseError, "transition source must belong to the target graph generation",
544 "execution.sourceAnchor", {}, "climbing.snapshot"));
545 parsed.sourceAnchorNode = std::move(source);
546 }
547 parsed.elapsed = eve::Duration::fromNanoseconds(elapsedNs);
548 parsed.duration = eve::Duration::fromNanoseconds(durationNs);
549 parsed.lastTick = eve::SimulationTick(lastTick);
550 if (parsed.duration != parsed.action.duration || parsed.elapsed > parsed.duration)
552 "execution timing disagrees with pinned action",
553 "execution.durationNs", {}, "climbing.snapshot"));
554 const bool graphBound = parsed.anchorGraph.isValid();
555 if (world.runtimeHandle() != parsed.candidate.world || !world.findBody(parsed.candidate.obstacleBody) ||
556 (!graphBound && !world.findShape(parsed.candidate.obstacleShape)))
558 "climbing restore target link is stale",
559 "execution.candidate", {}, "climbing.snapshot"));
560 if (graphBound) {
561 auto graph = Climbing::resolveAnchorGraph(parsed.anchorGraph);
562 if (!graph.isBound() || graph->body() != parsed.candidate.obstacleBody)
564 eve::DiagnosticCode::StaleHandle, "climbing restore anchor graph link is stale",
565 "execution.anchor.graph", {}, "climbing.snapshot"));
566 auto resolved = graph->resolveNode(world, parsed.anchorNode);
567 if (!resolved)
568 return eve::Result<void>::failure(resolved.status());
569 if (parsed.sourceAnchorNode) {
570 auto source = graph->resolveNode(world, *parsed.sourceAnchorNode);
571 if (!source) return eve::Result<void>::failure(source.status());
572 }
573 auto reservation = graph->validateReservation(parsed.anchorReservation);
574 if (!reservation && (!reservation.error() || reservation.error()->code() != eve::DiagnosticCode::NotFound))
575 return eve::Result<void>::failure(reservation.status());
576 }
577 candidateExecution = std::move(parsed);
578 }
579 if (activePhase(candidatePhase) != candidateExecution.has_value())
581 "active phase and execution presence disagree",
582 "execution", {}, "climbing.snapshot"));
583 if (!field(*root, "nextExecutionId")) {
584 candidateNextExecutionId = candidateExecution ? candidateExecution->executionId.value() + 1 : 1;
585 }
586 if (candidateNextExecutionId == 0 ||
587 (candidateExecution && (candidateExecution->executionId.isZero() ||
588 candidateNextExecutionId <= candidateExecution->executionId.value())))
590 "next execution id must follow the restored execution",
591 "nextExecutionId", {}, "climbing.snapshot"));
592 std::vector<ClimbingEvent> candidateEvents;
593 if (const eve::Value* eventValue = field(*root, "pendingEvents")) {
594 auto parsedEvents = readEvents(*eventValue, candidateNextExecutionId);
595 if (!parsedEvents) return eve::Result<void>::failure(parsedEvents.status());
596 candidateEvents = std::move(parsedEvents).takeValue();
597 } else if (version >= 2) {
599 "runtime snapshot pendingEvents field is required",
600 "pendingEvents", {}, "climbing.snapshot"));
601 }
602
603 if (execution_ && execution_->anchorGraph.isValid() &&
604 (!candidateExecution || execution_->anchorGraph != candidateExecution->anchorGraph ||
605 execution_->anchorReservation.id != candidateExecution->anchorReservation.id ||
606 execution_->anchorReservation.claimGeneration != candidateExecution->anchorReservation.claimGeneration))
608 eve::DiagnosticCode::Conflict, "restore cannot overwrite a different live anchor claim", "execution.anchor",
609 {}, "climbing.snapshot"));
610 if (candidateExecution && candidateExecution->anchorGraph.isValid()) {
611 const bool alreadyOwned = execution_ && execution_->anchorGraph == candidateExecution->anchorGraph &&
612 execution_->anchorReservation.id == candidateExecution->anchorReservation.id &&
613 execution_->anchorReservation.claimGeneration ==
614 candidateExecution->anchorReservation.claimGeneration;
615 if (!alreadyOwned) {
616 auto graph = Climbing::resolveAnchorGraph(candidateExecution->anchorGraph);
617 if (!graph.isBound())
619 eve::DiagnosticCode::StaleHandle, "climbing restore anchor graph link became stale",
620 "execution.anchor.graph", {}, "climbing.snapshot"));
621 auto claimed = graph->restoreReservation(candidateExecution->anchorReservation);
622 if (!claimed) return eve::Result<void>::failure(claimed.status());
623 candidateExecution->anchorReservation = std::move(claimed).takeValue();
624 }
625 }
626
627 // Publish only after the whole owning candidate and all cross-domain links have passed validation.
628 phase_ = candidatePhase;
629 profile_ = std::move(candidateProfile);
630 terminalCode_ = std::move(terminalCode);
631 execution_ = std::move(candidateExecution);
632 previousActionId_ = std::move(candidatePreviousActionId);
633 nextExecutionId_ = candidateNextExecutionId;
634 definitionGeneration_ = candidateDefinitionGeneration;
635 validatedProfileGeneration_.reset();
636 pendingEvents_ = std::move(candidateEvents);
637 validatedAnimationActions_.clear();
638 lastCandidates_.clear();
639 lastDebugQueries_.clear();
640 lastEvidence_.clear();
641 motionEvidence_.clear();
642 lastQueryCount_ = 0;
644}
645
646} // namespace eve::climbing
double score
Definition Agent.cpp:51
int root
Definition AnimSmr.cpp:119
std::string output
eve::action::ActionExecutionId executionId
Versioned, lossless codecs for climbing definitions.
攀爬事件 ↔ eve::Value 的**唯一**映射。
Deterministic climbing/parkour planning and capsule-constrained execution.
std::string nodeId
std::string name
Definition ECS.cpp:154
ShaderImageInput shape
std::int32_t first
bool required
Poco::JSON::Object::Ptr result
double defaultValue
std::map< std::string, std::vector< std::string > > graph
Definition Package.cpp:173
std::vector< particles::ParticleRecordEvent > events
std::string action
Definition PlayHost.cpp:118
std::string body
Object::Ptr value
std::string slot
RoadNetwork resolved
const RoadNode * node
bool found
std::string text
std::string_view source
std::string kind
float phase
SimulationTick tick
uint32_t index
int shapeId
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static constexpr Duration fromNanoseconds(std::int64_t nanoseconds) noexcept
Construct an exact duration from nanoseconds.
Definition Time.h:55
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 constexpr RuntimeHandle fromPacked(std::uint64_t value) noexcept
Reconstructs a handle from an explicit packed boundary value.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
static Value array(Array value)
Compatibility factory for an array value.
Definition Value.cpp:128
bool isNull() const noexcept
Return true when this value is null.
Definition Value.h:98
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
static constexpr std::int64_t SnapshotSchemaVersion
Current runtime snapshot version; v3 is N-1 and historical v2/v1/v0 remain migratable.
Definition Climbing.h:664
eve::Result< eve::Value > snapshot() const
Captures deterministic runtime state; debug candidates and final bone poses are excluded.
static constexpr std::string_view SnapshotSchemaId
Stable schema id for owning runtime snapshots.
Definition Climbing.h:662
static constexpr std::size_t PendingEventCapacity
Hard bound for undelivered post-simulation events owned by one runtime.
Definition Climbing.h:666
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
eve::detail::StrongUint64< detail::ClimbingExecutionIdTag > ClimbingExecutionId
Stable non-zero identity assigned when a climbing selection transaction commits.
Value climbingEventArrayValue(std::span< const ClimbingEvent > events)
一批事件 → Value 数组,顺序与传入一致。
eve::Result< ClimbingActionDefinition > decodeClimbingActionDefinition(const eve::Value &value)
Decode and validate one action without partially mutating a registry.
eve::Result< eve::Value > encodeClimbingProfileDefinition(const ClimbingProfileDefinition &profile)
Encode one validated profile and all nested actions into canonical schema v4 data.
eve::Result< ClimbingProfileDefinition > decodeClimbingProfileDefinition(const eve::Value &value)
Decode and validate an owning profile candidate transactionally.
ClimbingPhase
Execution lifecycle visible to gameplay and animation adapters.
Definition Climbing.h:470
@ Parsed
name 认识,out 已写入。
EventKindParse parseClimbingEventKind(std::string_view name, ClimbingEventKind &out)
名字 → ClimbingEventKind(climbingEventKindName 的严格逆)。
eve::Result< eve::Value > encodeClimbingActionDefinition(const ClimbingActionDefinition &action)
Encode one validated action into canonical schema v4 data.
HangSupport
Evidence describing whether a hanging pose has foot support.
Definition Climbing.h:137
eve::script::RuntimeHandleRef< ClimbingAnchorGraphHandleTag > ClimbingAnchorGraphHandleRef
Generation- and module-epoch-qualified anchor graph instance reference.
ClimbingActionKind
Data-driven action family; stable action identity remains the definition id.
Definition Climbing.h:46
ClimbingProbeRecipe
Semantic query family used to produce action candidates.
Definition Climbing.h:82
bool readString(const eve::Value::Object &object, const char *name, std::string &output)
Result< std::int64_t > readInt64(const Value::Object &object, std::string_view name)
Reads a required signed decimal integer string.
Result< bool > readBool(const Value::Object &object, std::string_view name)
Reads a required boolean.
bool readUint64String(const eve::Value::Object &object, const char *name, std::uint64_t &output)
std::string_view phaseName(BattlePhase phase) noexcept
Return the stable protocol spelling of a battle phase.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
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< bool > readBoolValue(const Value &value)
Read a Bool without coercing integers, strings or other kinds.
Definition Value.cpp:50
Result< json::UnsignedIntegerScan > scanUnsignedStringMember(const Value::Object &object, std::string_view name)
Scan a required nonempty decimal-string field using from_chars semantics.
Definition Value.cpp:104
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
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::int64_t > readInt64Value(const Value &value)
Read an Int64 without narrowing or numeric coercion.
Definition Value.cpp:57
Generation-qualified reference to an authored anchor node.
Runtime profile controlling capsule geometry and probe limits.
Definition Climbing.h:218