载入中...
搜索中...
未找到
ClimbingInput.cpp
浏览该文件的文档.
1// eve-hot-path
3#include <algorithm>
4#include <charconv>
5#include <cmath>
6#include <limits>
7#include <string_view>
8#include <type_traits>
9#include <unordered_set>
10#include <utility>
12#include "animation/AnimPose.h"
14#include "climbing/Climbing.h"
17#include "common/ValueRead.h"
18#include "physics/World3D.h"
19
20// ClimbingInput.cpp
21namespace eve::climbing {
22namespace {
23
24bool commandLess(const BufferedClimbingCommand& lhs, const BufferedClimbingCommand& rhs) {
25 if (lhs.pressedTick != rhs.pressedTick) return lhs.pressedTick < rhs.pressedTick;
26 return static_cast<std::uint8_t>(lhs.command) < static_cast<std::uint8_t>(rhs.command);
27}
28
29} // namespace
30
32 eve::SimulationTick pressedTick, std::uint64_t bufferTicks) {
33 if (bufferTicks == 0)
35 "input buffer must contain at least one tick",
36 "bufferTicks", {}, "climbing.input"));
37 if (pressedTick.value() > std::numeric_limits<std::uint64_t>::max() - bufferTicks)
39 "input expiry tick would overflow", "pressedTick", {},
40 "climbing.input"));
41 (void)prune(intent, pressedTick);
42 if (std::any_of(intent.commands.begin(), intent.commands.end(),
43 [&](const auto& entry) { return entry.command == command && entry.pressedTick == pressedTick; }))
45 "duplicate edge command for the same tick", "command",
46 {}, "climbing.input"));
47 if (intent.commands.size() >= MaxBufferedCommands)
49 "climbing input buffer is full", "commands", {},
50 "climbing.input"));
51 intent.commands.push_back(
52 {command, pressedTick, eve::SimulationTick(pressedTick.value() + bufferTicks), ClimbingExecutionId::zero()});
53 std::stable_sort(intent.commands.begin(), intent.commands.end(), commandLess);
55}
56
58 eve::SimulationTick pressedTick,
59 const ClimbingProfileDefinition& profile) {
60 return submit(intent, command, pressedTick, profile.inputBufferTicks);
61}
62
63std::size_t ClimbingInputSystem::prune(ClimbingIntent& intent, eve::SimulationTick currentTick) noexcept {
64 const std::size_t before = intent.commands.size();
65 std::erase_if(intent.commands, [&](const BufferedClimbingCommand& entry) {
66 return !entry.consumedExecutionId.isZero() || entry.expiryTick < currentTick;
67 });
68 return before - intent.commands.size();
69}
70
72 ClimbingCommand command,
73 eve::SimulationTick currentTick,
75 if (executionId.isZero())
77 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "consuming execution id must be non-zero",
78 "executionId", {}, "climbing.input"));
79 (void)prune(intent, currentTick);
80 const auto found = std::find_if(intent.commands.begin(), intent.commands.end(), [&](const auto& entry) {
81 return entry.command == command && entry.pressedTick <= currentTick && currentTick <= entry.expiryTick &&
82 entry.consumedExecutionId.isZero();
83 });
84 if (found == intent.commands.end())
87 found->consumedExecutionId = executionId;
90}
91
92std::optional<BufferedClimbingCommand> ClimbingInputSystem::peek(const ClimbingIntent& intent, ClimbingCommand command,
93 eve::SimulationTick currentTick) noexcept {
94 const auto found = std::find_if(intent.commands.begin(), intent.commands.end(), [&](const auto& entry) {
95 return entry.command == command && entry.pressedTick <= currentTick && currentTick <= entry.expiryTick &&
96 entry.consumedExecutionId.isZero();
97 });
98 return found == intent.commands.end() ? std::nullopt : std::optional<BufferedClimbingCommand>(*found);
99}
100
102 eve::SimulationTick lastGroundedTick,
103 std::uint64_t coyoteTicks) noexcept {
104 if (currentTick < lastGroundedTick) return ClimbingCoyoteState::Outside;
105 return currentTick.value() - lastGroundedTick.value() <= coyoteTicks ? ClimbingCoyoteState::Eligible
107}
108
109} // namespace eve::climbing
110
111// ClimbingPersistence.cpp
112namespace eve::climbing {
113
115 return publishProfile(std::move(profile), true);
116}
117
119 auto value = eve::Value::fromJson(json);
120 if (!value) return eve::Result<void>::failure(value.status());
121 auto profile = decodeClimbingProfileDefinition(value.value());
122 if (!profile) return eve::Result<void>::failure(profile.status());
123 return setProfile(std::move(profile).takeValue());
124}
125
127 auto value = eve::Value::fromJson(json);
128 if (!value) return eve::Result<void>::failure(value.status());
129 auto profile = decodeClimbingProfileDefinition(value.value());
130 if (!profile) return eve::Result<void>::failure(profile.status());
131 return reloadProfile(std::move(profile).takeValue());
132}
133
135 auto value = snapshot();
136 if (!value) return eve::Result<std::string>::failure(value.status());
137 return value.value().toJson();
138}
139
141 auto value = eve::Value::fromJson(json);
142 if (!value) return eve::Result<void>::failure(value.status());
143 return restore(value.value(), world);
144}
145
146} // namespace eve::climbing
147
148// ClimbingPose.cpp
149namespace eve::climbing {
150namespace {
151
152eve::Result<ClimbingPoseResult> poseFailure(std::string message, std::string path) {
154 eve::DiagnosticCode::InvalidArgument, std::move(message), std::move(path), {}, "climbing"));
155}
156
157bool validChain(const ClimbingLimbChain& chain, const animation::AnimSkeleton& skeleton) {
158 const int boneCount = skeleton.getBoneCount();
159 return chain.root >= 0 && chain.mid >= 0 && chain.tip >= 0 && chain.root < boneCount && chain.mid < boneCount &&
160 chain.tip < boneCount && skeleton.getParent(chain.mid) == chain.root &&
161 skeleton.getParent(chain.tip) == chain.mid;
162}
163
164bool finite(Vec3 value) { return std::isfinite(value.x) && std::isfinite(value.y) && std::isfinite(value.z); }
165
166Vec3 toModelSpace(Vec3 world, const ClimbingPoseBinding& binding) {
167 const float x = world.x - binding.modelWorldOrigin.x;
168 const float y = world.y - binding.modelWorldOrigin.y;
169 const float z = world.z - binding.modelWorldOrigin.z;
170 const float cosine = std::cos(binding.modelYawRadians);
171 const float sine = std::sin(binding.modelYawRadians);
172 return {cosine * x - sine * z, y, sine * x + cosine * z};
173}
174
175} // namespace
176
178 const ClimbingAdvance& advance, const ClimbingPoseBinding& binding) {
179 if (!std::isfinite(binding.modelYawRadians))
180 return poseFailure("model yaw must be finite", "binding.modelYawRadians");
181 if (!finite(binding.modelWorldOrigin))
182 return poseFailure("model origin must be finite", "binding.modelWorldOrigin");
183 if (pose.getBoneCount() != skeleton.getBoneCount())
184 return poseFailure("pose and skeleton bone counts must match", "pose");
185 if (binding.enableLeftHand && !validChain(binding.leftArm, skeleton))
186 return poseFailure("left arm chain contains an invalid bone", "binding.leftArm");
187 if (binding.enableRightHand && !validChain(binding.rightArm, skeleton))
188 return poseFailure("right arm chain contains an invalid bone", "binding.rightArm");
189 if (binding.enableLeftFoot && !validChain(binding.leftLeg, skeleton))
190 return poseFailure("left leg chain contains an invalid bone", "binding.leftLeg");
191 if (binding.enableRightFoot && !validChain(binding.rightLeg, skeleton))
192 return poseFailure("right leg chain contains an invalid bone", "binding.rightLeg");
193 if (!std::isfinite(advance.contactWeight) || !std::isfinite(advance.leftHandWeight) ||
194 !std::isfinite(advance.rightHandWeight) || !std::isfinite(advance.leftFootWeight) ||
195 !std::isfinite(advance.rightFootWeight) || !std::isfinite(advance.pelvisWeight))
196 return poseFailure("contact weights must be finite", "advance.contactWeights");
197
199 const float legacyWeight = std::clamp(advance.contactWeight, 0.f, 1.f);
200 const float authoredLeft = std::clamp(advance.leftHandWeight, 0.f, 1.f);
201 const float authoredRight = std::clamp(advance.rightHandWeight, 0.f, 1.f);
202 // contactWeight summarizes all limbs, including feet and pelvis. Only old
203 // aggregate-only callers use it as a hand weight.
204 const bool hasLimbWeights = advance.leftHandWeight != 0.f || advance.rightHandWeight != 0.f ||
205 advance.leftFootWeight != 0.f || advance.rightFootWeight != 0.f ||
206 advance.pelvisWeight != 0.f;
207 const float leftWeight = binding.enableLeftHand ? (hasLimbWeights ? authoredLeft : legacyWeight) : 0.f;
208 const float rightWeight = binding.enableRightHand ? (hasLimbWeights ? authoredRight : legacyWeight) : 0.f;
209 const float leftFootWeight =
210 binding.enableLeftFoot && advance.hasLeftFootAnchor ? std::clamp(advance.leftFootWeight, 0.f, 1.f) : 0.f;
211 const float rightFootWeight =
212 binding.enableRightFoot && advance.hasRightFootAnchor ? std::clamp(advance.rightFootWeight, 0.f, 1.f) : 0.f;
213 result.weight = std::max({leftWeight, rightWeight, leftFootWeight, rightFootWeight});
214 if (result.weight <= 0.f)
216
217 // Validate every active target before applying any constraint.
218 const Vec3 leftTarget = toModelSpace(advance.leftHandAnchor, binding);
219 const Vec3 rightTarget = toModelSpace(advance.rightHandAnchor, binding);
220 if (leftWeight > 0.f && !finite(leftTarget))
221 return poseFailure("left hand target must be finite in model space", "advance.leftHandAnchor");
222 if (rightWeight > 0.f && !finite(rightTarget))
223 return poseFailure("right hand target must be finite in model space", "advance.rightHandAnchor");
224
225 const Vec3 leftFootTarget = toModelSpace(advance.leftFootAnchor, binding);
226 const Vec3 rightFootTarget = toModelSpace(advance.rightFootAnchor, binding);
227 if (leftFootWeight > 0.f && !finite(leftFootTarget))
228 return poseFailure("left foot target must be finite in model space", "advance.leftFootAnchor");
229 if (rightFootWeight > 0.f && !finite(rightFootTarget))
230 return poseFailure("right foot target must be finite in model space", "advance.rightFootAnchor");
231
232 animation::AnimConstraintStack constraints(&skeleton);
233 if (binding.enableLeftHand && leftWeight > 0.f) {
234 const Vec3 target = leftTarget;
235 constraints.addTwoBoneIK(binding.leftArm.root, binding.leftArm.mid, binding.leftArm.tip, target.x, target.y,
236 target.z, leftWeight);
237 result.leftHandApplied = true;
238 }
239 if (binding.enableRightHand && rightWeight > 0.f) {
240 const Vec3 target = rightTarget;
241 constraints.addTwoBoneIK(binding.rightArm.root, binding.rightArm.mid, binding.rightArm.tip, target.x, target.y,
242 target.z, rightWeight);
243 result.rightHandApplied = true;
244 }
245 if (leftFootWeight > 0.f) {
246 constraints.addTwoBoneIK(binding.leftLeg.root, binding.leftLeg.mid, binding.leftLeg.tip, leftFootTarget.x,
247 leftFootTarget.y, leftFootTarget.z, leftFootWeight);
248 result.leftFootApplied = true;
249 }
250 if (rightFootWeight > 0.f) {
251 constraints.addTwoBoneIK(binding.rightLeg.root, binding.rightLeg.mid, binding.rightLeg.tip, rightFootTarget.x,
252 rightFootTarget.y, rightFootTarget.z, rightFootWeight);
253 result.rightFootApplied = true;
254 }
255 constraints.apply(&pose);
257}
258
259} // namespace eve::climbing
260
261// ClimbingPrediction.cpp
262namespace eve::climbing {
263namespace {
264
265constexpr std::uint64_t fnvOffset = 14695981039346656037ull;
266constexpr std::uint64_t fnvPrime = 1099511628211ull;
267
268void appendByte(std::uint64_t& hash, std::uint8_t value) noexcept {
269 hash ^= value;
270 hash *= fnvPrime;
271}
272
273template <class T>
274void appendInteger(std::uint64_t& hash, T value) noexcept {
275 using Unsigned = std::make_unsigned_t<T>;
276 const Unsigned bits = static_cast<Unsigned>(value);
277 for (std::size_t index = 0; index < sizeof(T); ++index)
278 appendByte(hash, static_cast<std::uint8_t>((bits >> (index * 8)) & static_cast<Unsigned>(0xff)));
279}
280
281void appendString(std::uint64_t& hash, std::string_view value) noexcept {
282 appendInteger(hash, static_cast<std::uint64_t>(value.size()));
283 for (const unsigned char character : value) appendByte(hash, character);
284}
285
286std::int64_t quantize(float value) noexcept {
287 if (!std::isfinite(value)) return std::numeric_limits<std::int64_t>::min();
288 const double scaled = std::round(static_cast<double>(value) * 1000.0);
289 if (scaled <= static_cast<double>(std::numeric_limits<std::int64_t>::min()))
290 return std::numeric_limits<std::int64_t>::min();
291 if (scaled >= static_cast<double>(std::numeric_limits<std::int64_t>::max()))
292 return std::numeric_limits<std::int64_t>::max();
293 return static_cast<std::int64_t>(scaled);
294}
295
296void appendVec(std::uint64_t& hash, Vec3 value) noexcept {
297 appendInteger(hash, quantize(value.x));
298 appendInteger(hash, quantize(value.y));
299 appendInteger(hash, quantize(value.z));
300}
301
302const eve::Value* field(const eve::Value::Object& object, std::string_view name) {
303 const auto found = object.find(std::string(name));
304 return found == object.end() ? nullptr : &found->second;
305}
306
307bool readString(const eve::Value::Object& object, std::string_view name, std::string& output) {
308 auto text = eve::readStringMember(object, name);
309 if (!text) return false;
310 output = std::move(text.value());
311 return true;
312}
313
314bool parseUint64(std::string_view text, std::uint64_t& output, int base = 10) {
315 if (text.empty()) return false;
316 const char* first = text.data();
317 const char* last = first + text.size();
318 const auto parsed = std::from_chars(first, last, output, base);
319 return parsed.ec == std::errc{} && parsed.ptr == last;
320}
321
322bool readUint64String(const eve::Value::Object& object, std::string_view name, std::uint64_t& output, int base = 10) {
323 std::string text;
324 return readString(object, name, text) && parseUint64(text, output, base);
325}
326
327bool readInt64(const eve::Value::Object& object, std::string_view name, std::int64_t& output) {
328 const auto* value = field(object, name);
329 if (!value) return false;
330 auto parsed = eve::readInt64Value(*value);
331 if (!parsed) return false;
332 output = parsed.value();
333 return true;
334}
335
336eve::Value::Object unknownFields(const eve::Value::Object& object, std::initializer_list<std::string_view> known) {
337 const std::unordered_set<std::string_view> names(known.begin(), known.end());
339 for (const auto& [name, value] : object)
340 if (!names.contains(name)) result.emplace(name, value);
341 return result;
342}
343
344std::string_view dispositionName(ClimbingPredictionDisposition value) {
345 switch (value) {
346 case ClimbingPredictionDisposition::Accepted: return "accepted";
347 case ClimbingPredictionDisposition::Corrected: return "corrected";
348 case ClimbingPredictionDisposition::Rejected: return "rejected";
349 }
350 return "rejected";
351}
352
353bool readDisposition(std::string_view text, ClimbingPredictionDisposition& output) {
354 if (text == "accepted")
356 else if (text == "corrected")
358 else if (text == "rejected")
360 else
361 return false;
362 return true;
363}
364
365std::string_view reasonName(ClimbingPredictionReason value) {
366 switch (value) {
367 case ClimbingPredictionReason::None: return "none";
368 case ClimbingPredictionReason::CandidateMismatch: return "candidate_mismatch";
369 case ClimbingPredictionReason::NoCandidate: return "no_candidate";
370 case ClimbingPredictionReason::TickTooFarAhead: return "tick_too_far_ahead";
371 case ClimbingPredictionReason::RuntimeBusy: return "runtime_busy";
372 case ClimbingPredictionReason::InvalidRequest: return "invalid_request";
373 }
374 return "invalid_request";
375}
376
377bool readReason(std::string_view text, ClimbingPredictionReason& output) {
378 if (text == "none")
380 else if (text == "candidate_mismatch")
382 else if (text == "no_candidate")
384 else if (text == "tick_too_far_ahead")
386 else if (text == "runtime_busy")
388 else if (text == "invalid_request")
390 else
391 return false;
392 return true;
393}
394
395eve::Value encodeKey(const ClimbingCandidateKey& key) {
396 return eve::Value::object({
397 {"actionId", key.actionId},
398 {"kind", static_cast<std::int64_t>(key.kind)},
399 {"definitionGeneration", std::to_string(key.definitionGeneration)},
400 {"sortedRank", static_cast<std::int64_t>(key.sortedRank)},
401 {"fingerprintHex",
402 [&key] {
403 char buffer[17]{};
404 const auto converted = std::to_chars(buffer, buffer + 16, key.fingerprint, 16);
405 return std::string(buffer, converted.ptr);
406 }()},
407 });
408}
409
410bool decodeKey(const eve::Value& value, ClimbingCandidateKey& key) {
411 const auto* object = value.getIf<eve::Value::Object>();
412 std::int64_t kind = 0;
413 std::int64_t rank = 0;
414 if (!object || !readString(*object, "actionId", key.actionId) || !readInt64(*object, "kind", kind) || kind < 0 ||
415 kind > static_cast<std::int64_t>(ClimbingActionKind::BarSwing) ||
416 !readUint64String(*object, "definitionGeneration", key.definitionGeneration) ||
417 !readInt64(*object, "sortedRank", rank) || rank < 0 || rank > std::numeric_limits<std::uint32_t>::max() ||
418 !readUint64String(*object, "fingerprintHex", key.fingerprint, 16))
419 return false;
420 key.kind = static_cast<ClimbingActionKind>(kind);
421 key.sortedRank = static_cast<std::uint32_t>(rank);
422 return true;
423}
424
425bool validKey(const ClimbingCandidateKey& key) {
426 return !key.actionId.empty() && key.definitionGeneration != 0 && key.fingerprint != 0;
427}
428
429eve::Result<void> validateSnapshotEnvelope(const eve::Value& value) {
430 const auto* object = value.getIf<eve::Value::Object>();
431 std::string schemaId;
432 std::int64_t schemaVersion = -1;
433 if (!object || !readString(*object, "schemaId", schemaId) || schemaId != ClimbingRuntime::SnapshotSchemaId ||
434 !readInt64(*object, "schemaVersion", schemaVersion) || schemaVersion < 0)
436 eve::DiagnosticCode::ParseError, "authoritative snapshot has an invalid climbing runtime envelope",
437 "authoritativeSnapshot", {}, "climbing.prediction"));
438 if (schemaVersion > ClimbingRuntime::SnapshotSchemaVersion)
440 eve::DiagnosticCode::UnknownVersion, "authoritative snapshot version is newer than this runtime",
441 "authoritativeSnapshot.schemaVersion", {}, "climbing.prediction"));
443}
444
445bool consistentDecision(const ClimbingPredictionDecision& decision) {
446 if (decision.sequence.isZero()) return false;
447 if (decision.disposition == ClimbingPredictionDisposition::Accepted)
448 return validKey(decision.authoritativeCandidate) && decision.reason == ClimbingPredictionReason::None;
449 if (decision.reason == ClimbingPredictionReason::None) return false;
450 return decision.disposition != ClimbingPredictionDisposition::Corrected ||
451 validKey(decision.authoritativeCandidate);
452}
453
454eve::Result<eve::Value::Object> readEnvelope(const eve::Value& value, std::string_view schemaId) {
455 const auto* object = value.getIf<eve::Value::Object>();
456 if (!object)
458 eve::DiagnosticCode::ParseError, "prediction payload must be an object", {}, {}, "climbing.prediction"));
459 std::string actualSchema;
460 std::int64_t version = 0;
461 if (!readString(*object, "schemaId", actualSchema) || actualSchema != schemaId)
463 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "prediction schemaId is missing or mismatched",
464 "schemaId", {}, "climbing.prediction"));
465 if (!readInt64(*object, "schemaVersion", version))
467 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "prediction schemaVersion must be an integer",
468 "schemaVersion", {}, "climbing.prediction"));
469 if (version != 1)
471 eve::Diagnostic::error(eve::DiagnosticCode::UnknownVersion, "prediction schema version is unsupported",
472 "schemaVersion", {}, "climbing.prediction"));
474}
475
476bool activePhase(ClimbingPhase phase) {
479}
480
481} // namespace
482
483ClimbingCandidateKey makeClimbingCandidateKey(const ClimbingCandidate& candidate, std::uint32_t sortedRank) noexcept {
484 std::uint64_t hash = fnvOffset;
485 appendString(hash, candidate.actionId);
486 appendInteger(hash, static_cast<std::uint8_t>(candidate.kind));
487 appendInteger(hash, candidate.definitionGeneration);
488 appendInteger(hash, sortedRank);
489 appendInteger(hash, candidate.obstacleBodyId);
490 appendInteger(hash, candidate.obstacleShapeId);
491 appendVec(hash, candidate.frontPoint);
492 appendVec(hash, candidate.bodyLocalTop);
493 appendVec(hash, candidate.bodyLocalLanding);
494 appendVec(hash, candidate.surfaceNormal);
495 appendVec(hash, candidate.surfaceTangent);
496 appendInteger(hash, quantize(candidate.obstacleHeight));
497 appendInteger(hash, quantize(candidate.obstacleDepth));
498 appendInteger(hash, quantize(candidate.gapDistance));
499 appendInteger(hash, quantize(candidate.clearanceHeight));
500 appendInteger(hash, quantize(candidate.slopeRadians));
501 appendInteger(hash, quantize(candidate.curvature));
502 appendInteger(hash, candidate.supportShapeTag);
503 appendInteger(hash, candidate.supportMaterialId);
504 appendInteger(hash, static_cast<std::uint8_t>(candidate.probeRecipe));
505 appendInteger(hash, candidate.score);
506 appendInteger(hash, static_cast<std::uint8_t>(candidate.support));
507 if (hash == 0) hash = 1;
508 return {candidate.actionId, candidate.kind, candidate.definitionGeneration, sortedRank, hash};
509}
510
512 if (request.sequence.isZero() || !validKey(request.candidate))
514 eve::DiagnosticCode::InvalidArgument, "prediction request requires a non-zero sequence and candidate key",
515 "request", {}, "climbing.prediction"));
516 eve::Value::Object object = request.extensionMetadata;
517 object["schemaId"] = eve::Value(std::string(ClimbingPredictionRequest::SchemaId));
518 object["schemaVersion"] = eve::Value(ClimbingPredictionRequest::SchemaVersion);
519 object["sequence"] = eve::Value(std::to_string(request.sequence.value()));
520 object["clientTick"] = eve::Value(std::to_string(request.clientTick.value()));
521 object["candidate"] = encodeKey(request.candidate);
522 return eve::Result<eve::Value>::success(eve::Value(std::move(object)));
523}
524
526 auto root = readEnvelope(value, ClimbingPredictionRequest::SchemaId);
528 std::uint64_t sequence = 0;
529 std::uint64_t clientTick = 0;
531 const eve::Value* candidate = field(root.value(), "candidate");
532 if (!readUint64String(root.value(), "sequence", sequence) || sequence == 0 ||
533 !readUint64String(root.value(), "clientTick", clientTick) || !candidate ||
534 !decodeKey(*candidate, request.candidate) || !validKey(request.candidate))
536 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "prediction request has missing or invalid fields",
537 "request", {}, "climbing.prediction"));
539 request.clientTick = eve::SimulationTick(clientTick);
540 request.extensionMetadata =
541 unknownFields(root.value(), {"schemaId", "schemaVersion", "sequence", "clientTick", "candidate"});
543}
544
546 if (!consistentDecision(decision))
548 "prediction decision fields are inconsistent",
549 "decision", {}, "climbing.prediction"));
550 auto snapshotEnvelope = validateSnapshotEnvelope(decision.authoritativeSnapshot);
551 if (!snapshotEnvelope) return eve::Result<eve::Value>::failure(snapshotEnvelope.status());
552 eve::Value::Object object = decision.extensionMetadata;
553 object["schemaId"] = eve::Value(std::string(ClimbingPredictionDecision::SchemaId));
554 object["schemaVersion"] = eve::Value(ClimbingPredictionDecision::SchemaVersion);
555 object["sequence"] = eve::Value(std::to_string(decision.sequence.value()));
556 object["clientTick"] = eve::Value(std::to_string(decision.clientTick.value()));
557 object["serverTick"] = eve::Value(std::to_string(decision.serverTick.value()));
558 object["disposition"] = eve::Value(std::string(dispositionName(decision.disposition)));
559 object["reason"] = eve::Value(std::string(reasonName(decision.reason)));
560 object["authoritativeCandidate"] = encodeKey(decision.authoritativeCandidate);
561 object["authoritativeSnapshot"] = decision.authoritativeSnapshot;
562 return eve::Result<eve::Value>::success(eve::Value(std::move(object)));
563}
564
566 auto root = readEnvelope(value, ClimbingPredictionDecision::SchemaId);
568 std::uint64_t sequence = 0;
569 std::uint64_t clientTick = 0;
570 std::uint64_t serverTick = 0;
571 std::string disposition;
572 std::string reason;
574 const eve::Value* key = field(root.value(), "authoritativeCandidate");
575 const eve::Value* snapshot = field(root.value(), "authoritativeSnapshot");
576 if (!readUint64String(root.value(), "sequence", sequence) || sequence == 0 ||
577 !readUint64String(root.value(), "clientTick", clientTick) ||
578 !readUint64String(root.value(), "serverTick", serverTick) ||
579 !readString(root.value(), "disposition", disposition) || !readDisposition(disposition, decision.disposition) ||
580 !readString(root.value(), "reason", reason) || !readReason(reason, decision.reason) || !key ||
581 !decodeKey(*key, decision.authoritativeCandidate) || !snapshot)
583 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "prediction decision has missing or invalid fields",
584 "decision", {}, "climbing.prediction"));
586 decision.clientTick = eve::SimulationTick(clientTick);
587 decision.serverTick = eve::SimulationTick(serverTick);
588 if (!consistentDecision(decision))
590 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "prediction decision fields are inconsistent",
591 "decision", {}, "climbing.prediction"));
593 auto snapshotEnvelope = validateSnapshotEnvelope(decision.authoritativeSnapshot);
594 if (!snapshotEnvelope) return eve::Result<ClimbingPredictionDecision>::failure(snapshotEnvelope.status());
595 decision.extensionMetadata =
596 unknownFields(root.value(), {"schemaId", "schemaVersion", "sequence", "clientTick", "serverTick", "disposition",
597 "reason", "authoritativeCandidate", "authoritativeSnapshot"});
598 return eve::Result<ClimbingPredictionDecision>::success(std::move(decision));
599}
600
602 const ClimbingPose& pose,
604 eve::SimulationTick serverTick,
605 std::uint64_t maxClientTickLead) {
607 decision.sequence = request.sequence;
608 decision.clientTick = request.clientTick;
609 decision.serverTick = serverTick;
611 auto state = snapshot();
613 value.authoritativeSnapshot = std::move(state).takeValue();
615 };
616
617 if (request.sequence.isZero() || !validKey(request.candidate)) {
620 return finish(std::move(decision));
621 }
622 if (request.clientTick > serverTick && request.clientTick.value() - serverTick.value() > maxClientTickLead) {
625 return finish(std::move(decision));
626 }
627 if (activePhase(phase_)) {
630 return finish(std::move(decision));
631 }
632
633 auto candidates = probe(world, pose);
635 if (candidates.value().empty()) {
638 return finish(std::move(decision));
639 }
640 decision.authoritativeCandidate = makeClimbingCandidateKey(candidates.value().front(), 0);
641 std::size_t match = candidates.value().size();
642 for (std::size_t index = 0; index < candidates.value().size(); ++index) {
643 if (index > std::numeric_limits<std::uint32_t>::max()) break;
644 if (makeClimbingCandidateKey(candidates.value()[index], static_cast<std::uint32_t>(index)) ==
645 request.candidate) {
646 match = index;
647 break;
648 }
649 }
650 if (match == candidates.value().size()) {
653 return finish(std::move(decision));
654 }
655
656 decision.authoritativeCandidate = request.candidate;
657 auto prepared = prepareBeginCandidate(world, pose, serverTick, candidates.value()[match]);
658 if (!prepared) return eve::Result<ClimbingPredictionDecision>::failure(prepared.status());
659 auto committed = commitBegin(std::move(prepared).takeValue());
663 return finish(std::move(decision));
664}
665
666} // namespace eve::climbing
double z
double y
double x
LogicalId target
int root
Definition AnimSmr.cpp:119
std::string output
eve::action::ActionExecutionId executionId
eve::EntitySpatialPose pose
Versioned, lossless codecs for climbing definitions.
Tick-addressed command buffering for deterministic climbing input.
Synchronous Animation TwoBoneIK adapter for climbing contact anchors.
Deterministic climbing/parkour planning and capsule-constrained execution.
bool committed
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::string message
const GltfImportRequest & request
std::int32_t first
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
bool finite
eve::action::ActionVfxBinding binding
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
std::string hash
bool found
std::string text
std::string kind
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
float phase
Json object
float size
Definition TreeMesh.cpp:158
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static 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
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
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
Ordered main-thread post-process stack with aim, limb IK and foot planting.
void apply(AnimPose *pose) const
Apply constraints in insertion order and refresh world transforms. Main-thread only.
void addTwoBoneIK(int root, int mid, int tip, float targetX, float targetY, float targetZ, float weight=1.f)
Append a weighted two-bone IK constraint.
Evaluated local (and optional world) pose for an AnimSkeleton. Script type: AnimPose.
Definition AnimPose.h:17
3D bone hierarchy + bind-pose local TRS for skeletal animation. Independent of ik::Skeleton3D (FABRIK...
int getBoneCount() const
Returns the bone count.
static std::size_t prune(ClimbingIntent &intent, eve::SimulationTick currentTick) noexcept
Remove expired and already-consumed records; returns the number removed.
static constexpr std::size_t MaxBufferedCommands
Hard safety bound preventing an untrusted producer from growing intent indefinitely.
static ClimbingCoyoteState coyoteWindowState(eve::SimulationTick currentTick, eve::SimulationTick lastGroundedTick, std::uint64_t coyoteTicks) noexcept
Evaluate a grounded grace window without reading wall clock.
static eve::Result< void > submit(ClimbingIntent &intent, ClimbingCommand command, eve::SimulationTick pressedTick, std::uint64_t bufferTicks)
Queue one edge command with expiry derived from an exact tick budget.
static eve::Result< std::optional< BufferedClimbingCommand > > consume(ClimbingIntent &intent, ClimbingCommand command, eve::SimulationTick currentTick, ClimbingExecutionId executionId)
Atomically mark the oldest eligible command consumed by one committed execution.
static std::optional< BufferedClimbingCommand > peek(const ClimbingIntent &intent, ClimbingCommand command, eve::SimulationTick currentTick) noexcept
Observe the oldest eligible command without consuming or pruning intent.
eve::Result< std::string > snapshotJson() const
Serializes the canonical runtime snapshot as JSON.
eve::Result< void > reloadProfileJson(std::string_view json)
Parses and hot-reloads a canonical profile JSON document transactionally.
eve::Result< void > setProfile(ClimbingProfile profile)
Replaces the runtime profile after validating all dimensions and action definitions.
Definition Climbing.cpp:106
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< void > restoreJson(std::string_view json, physics::World3D &world)
Parses and atomically restores a canonical runtime snapshot JSON document.
eve::Result< eve::Value > snapshot() const
Captures deterministic runtime state; debug candidates and final bone poses are excluded.
eve::Result< void > setProfileJson(std::string_view json)
Parses and installs a canonical profile JSON document transactionally.
eve::Result< void > reloadProfile(ClimbingProfile profile)
Atomically publishes a validated profile while pinning any active execution to its old snapshot.
eve::Result< ClimbingCandidateSet > probe(physics::World3D &world, const ClimbingPose &pose) const
Probes, validates, and deterministically sorts all matching candidates.
Definition Climbing.cpp:179
eve::Result< void > restore(const eve::Value &value, physics::World3D &world)
Restores a fully parsed candidate atomically after revalidating all process-local Physics links.
eve::Result< ClimbingPredictionDecision > tryBeginPredicted(physics::World3D &world, const ClimbingPose &pose, const ClimbingPredictionRequest &request, eve::SimulationTick serverTick, std::uint64_t maxClientTickLead)
Re-probes authoritative state and commits only the exact server-matched predicted candidate.
static constexpr std::string_view SnapshotSchemaId
Stable schema id for owning runtime snapshots.
Definition Climbing.h:662
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.
constexpr bool isZero() const noexcept
Returns whether this value is zero.
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.
ClimbingCoyoteState
Named result of evaluating the deterministic grounded grace window.
EVENGINE_API_DOMAINS eve::Result< eve::Value > encodeClimbingPredictionRequest(const ClimbingPredictionRequest &request)
Encodes a validated prediction request to its canonical owning Value representation.
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
EVENGINE_API_DOMAINS eve::Result< eve::Value > encodeClimbingPredictionDecision(const ClimbingPredictionDecision &decision)
Encodes a validated authoritative decision to its canonical owning Value representation.
ClimbingPredictionReason
Stable reason for a non-accepted prediction decision.
Definition Climbing.h:421
ClimbingPredictionDisposition
Named server-authoritative outcome of one prediction request.
Definition Climbing.h:418
EVENGINE_API_DOMAINS eve::Result< ClimbingPredictionDecision > decodeClimbingPredictionDecision(const eve::Value &value)
Decodes a complete authoritative decision transactionally.
eve::detail::StrongUint64< detail::ClimbingPredictionSequenceTag > ClimbingPredictionSequence
Non-zero client command sequence used to pair one prediction decision.
Definition Climbing.h:380
ClimbingCommand
Edge and held commands understood by the climbing input phase.
ClimbingActionKind
Data-driven action family; stable action identity remains the definition id.
Definition Climbing.h:46
eve::Result< ClimbingPoseResult > applyClimbingPose(animation::AnimSkeleton &skeleton, animation::AnimPose &pose, const ClimbingAdvance &advance, const ClimbingPoseBinding &binding)
Applies contact anchors to an already evaluated animation pose.
EVENGINE_API_DOMAINS eve::Result< ClimbingPredictionRequest > decodeClimbingPredictionRequest(const eve::Value &value)
Decodes a complete request and rejects unknown schema versions transactionally.
EVENGINE_API_DOMAINS ClimbingCandidateKey makeClimbingCandidateKey(const ClimbingCandidate &candidate, std::uint32_t sortedRank) noexcept
Creates the opaque key for one candidate at its deterministic sorted rank.
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.
bool readUint64String(const eve::Value::Object &object, const char *name, std::uint64_t &output)
Result< std::vector< uint8_t > > quantize(std::span< const float > input, float scale, int zero, bool sign)
Affine quantization to int8/uint8 bytes, saturating and rounding ties to even.
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
One owning edge command with deterministic lifetime and consumption evidence.
Owning output of one execution tick.
Definition Climbing.h:553
float rightFootWeight
Right-foot constraint weight resolved from the immutable action contact windows.
Definition Climbing.h:590
float leftFootWeight
Left-foot constraint weight resolved from the immutable action contact windows.
Definition Climbing.h:588
Vec3 leftFootAnchor
Owning world-space foot targets, resolved for this tick only.
Definition Climbing.h:598
bool hasLeftFootAnchor
Whether a supported foot target exists; weights alone never imply a target.
Definition Climbing.h:601
float pelvisWeight
Pelvis constraint weight resolved from the immutable action contact windows.
Definition Climbing.h:592
Opaque deterministic identity of one sorted candidate; contains no client-authored position.
Definition Climbing.h:389
Owning, replayable climbing candidate; contains no borrowed query pointers.
Definition Climbing.h:290
Hot authoritative intent component; contains no device or callback pointers.
std::vector< BufferedClimbingCommand > commands
Borrowed-pose adapter inputs; no skeleton or pose pointer is retained.
Observable result of applying built-in hand and foot constraints.
Input pose used for one deterministic candidate probe.
Definition Climbing.h:275
Server-to-client decision carrying the authoritative runtime snapshot for reconciliation.
Definition Climbing.h:431
ClimbingPredictionSequence sequence
Definition Climbing.h:437
eve::Value authoritativeSnapshot
Canonical server runtime state after the decision, used for rollback/replay reconciliation.
Definition Climbing.h:445
static constexpr std::int64_t SchemaVersion
Current decision schema version.
Definition Climbing.h:435
ClimbingPredictionReason reason
Definition Climbing.h:441
eve::Value::Object extensionMetadata
Unknown schema fields retained across decode and encode.
Definition Climbing.h:447
ClimbingPredictionDisposition disposition
Definition Climbing.h:440
ClimbingCandidateKey authoritativeCandidate
Server-selected key; fingerprint zero means no authoritative candidate was available.
Definition Climbing.h:443
static constexpr std::string_view SchemaId
Canonical cross-process schema id.
Definition Climbing.h:433
Client-to-server request containing selection identity only, never a world-space target.
Definition Climbing.h:404
static constexpr std::int64_t SchemaVersion
Current request schema version.
Definition Climbing.h:408
static constexpr std::string_view SchemaId
Canonical cross-process schema id.
Definition Climbing.h:406
Runtime profile controlling capsule geometry and probe limits.
Definition Climbing.h:218
Small owning world-space vector used at climbing module boundaries.