载入中...
搜索中...
未找到
ClimbingExecution.cpp
浏览该文件的文档.
1// eve-hot-path
2#include "climbing/Climbing.h"
5#include "physics/Body3D.h"
6#include "physics/World3D.h"
7namespace eve::climbing {
8using namespace runtime_detail;
12
14 const ClimbingMotionInput& motion) {
15 lastDebugQueries_.clear();
16 lastQueryCount_ = 0;
17 lastCounters_ = {};
18 lastCounters_.workload = ClimbingWorkload::Active;
20 RuntimeTelemetryScope telemetryScope(telemetry_, lastCounters_, step.tick);
21 if (!isActivePhase(phase_) || !execution_)
23 "no climbing execution is active",
24 "runtime.phase", {}, "climbing"));
25 Execution& execution = *execution_;
26 lastCounters_.selectedCost = execution.candidate.score;
27 if (world.runtimeHandle() != execution.candidate.world)
30 "execution belongs to another or stale physics world", "world", {}, "climbing"));
31 if (step.tick <= execution.lastTick)
33 eve::DiagnosticCode::Conflict, "simulation tick must increase exactly once per update", "step.tick", {},
34 "climbing"));
35 if (step.delta.nanoseconds() <= 0)
37 eve::DiagnosticCode::InvalidArgument, "simulation delta must be positive", "step.delta", {}, "climbing"));
45 eve::DiagnosticCode::InvalidArgument, "motion policies require valid enum values and authored root motion",
46 "motion.policy", {}, "climbing"));
47 if (!isFinite(motion.rootTranslation) || !isFinite(motion.facing) || !isFinite(motion.pelvisOffset) ||
51 "authored motion must be finite and pelvis deviation must remain inside the profile limit", "motion", {},
52 "climbing"));
54 !world.findShape(execution.candidate.obstacleShape))
56 eve::DiagnosticCode::StaleHandle, "traversed shape is stale; collision exclusion was not applied",
57 "motion.obstacleCollision", {}, "climbing"));
58 auto eventCapacity = requireEventCapacity(4, step.tick);
59 if (!eventCapacity) return eve::Result<ClimbingAdvance>::failure(eventCapacity.status());
60
61 std::optional<ResolvedClimbingAnchorNode> sourceAnchor;
62 const bool graphBound = execution.anchorGraph.isValid() && !execution.anchorReservation.id.isZero();
63 float graphPointSpeed = -1.f;
64 Vec3 leftFootAnchor;
65 Vec3 rightFootAnchor;
66 Vec3 authoredFeetCenter;
67 bool hasAuthoredFootAnchors = false;
68 bool hasLeftFootAnchor = false;
69 bool hasRightFootAnchor = false;
70 if (graphBound) {
71 auto graph = Climbing::resolveAnchorGraph(execution.anchorGraph);
72 auto resolved = graph.isBound() ? graph->resolveNodeKinematics(world, execution.anchorNode)
74 eve::DiagnosticCode::StaleHandle, "anchor graph instance handle is stale",
75 "execution.anchorGraph", {}, "climbing"));
76 auto reservation = graph.isBound()
77 ? graph->validateReservation(execution.anchorReservation)
79 eve::DiagnosticCode::StaleHandle, "anchor graph instance handle is stale",
80 "execution.anchorGraph", {}, "climbing"));
81 if (!resolved || !reservation) {
82 enqueueEvent(
83 {ClimbingEventKind::Cancelled, execution.candidate.actionId, step.tick, execution.executionId});
85 terminalCode_ = "climbing.anchor.stale";
86 if (graph.isBound() && reservation) {
87 auto released = graph->release(execution.anchorReservation);
88 released.ignore("stale graph anchor resolution releases live occupancy");
89 }
90 execution_.reset();
92 eve::DiagnosticCode::StaleHandle, "graph anchor or occupancy reservation is stale", "execution.anchor",
93 {}, "climbing"));
94 }
95 if (execution.sourceAnchorNode) {
96 auto source = graph->resolveNodeKinematics(world, *execution.sourceAnchorNode);
98 sourceAnchor = std::move(source).takeValue();
99 }
100 execution.candidate.obstacleBody = resolved.value().body;
101 execution.candidate.topPoint = resolved.value().position;
102 execution.candidate.frontPoint = resolved.value().position;
103 execution.candidate.surfaceNormal = resolved.value().normal;
104 execution.candidate.surfaceTangent = resolved.value().tangent;
105 execution.candidate.leftHandAnchor = resolved.value().leftHandSocket;
106 execution.candidate.rightHandAnchor = resolved.value().rightHandSocket;
107 if (execution.action.kind == ClimbingActionKind::LadderDismount ||
108 execution.action.kind == ClimbingActionKind::BeamBalance) {
109 execution.candidate.landingFeet = resolved.value().position;
110 } else {
111 execution.candidate.landingFeet =
112 resolved.value().position +
113 resolved.value().normal * (profile_.capsuleRadius + profile_.skin + execution.action.hangBodyOffset);
114 execution.candidate.landingFeet.y = resolved.value().position.y - execution.action.hangFeetBelowLedge;
115 }
116 authoredFeetCenter = resolved.value().feetSocket;
117 // A rung supplies an authored support center in body-local space. Resolve
118 // it every tick, just like hand sockets, including moving-platform rotation.
119 if (resolved.value().kind == ClimbingAnchorKind::LadderRung) {
120 const Vec3 halfStance = resolved.value().tangent * (profile_.capsuleRadius * 0.5f);
121 leftFootAnchor = resolved.value().feetSocket - halfStance;
122 rightFootAnchor = resolved.value().feetSocket + halfStance;
123 hasAuthoredFootAnchors = true;
124 }
125 graphPointSpeed = length(resolved.value().pointVelocity);
126 }
127
128 physics::Body3D* obstacle = world.findBody(execution.candidate.obstacleBody);
129 if (!obstacle) {
130 enqueueEvent({ClimbingEventKind::Cancelled, execution.candidate.actionId, step.tick, execution.executionId});
132 terminalCode_ = "climbing.anchor.stale";
133 if (graphBound) {
134 auto released = releaseAnchorReservation();
135 released.ignore("destroyed anchor body releases graph occupancy");
136 }
137 execution_.reset();
139 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "climbing target handle is stale",
140 "execution.candidate.obstacleBody", {}, "climbing"));
141 }
142 const float platformSpeed = graphPointSpeed >= 0.f
143 ? graphPointSpeed
144 : std::sqrt(obstacle->getLinearVelocityX() * obstacle->getLinearVelocityX() +
145 obstacle->getLinearVelocityY() * obstacle->getLinearVelocityY() +
146 obstacle->getLinearVelocityZ() * obstacle->getLinearVelocityZ());
147 if (platformSpeed > profile_.maxPlatformSpeed + epsilon) {
148 enqueueEvent({ClimbingEventKind::Cancelled, execution.candidate.actionId, step.tick, execution.executionId});
150 terminalCode_ = "climbing.anchor.platform_speed";
151 if (graphBound) {
152 auto released = releaseAnchorReservation();
153 released.ignore("unsafe anchor platform speed releases graph occupancy");
154 }
155 execution_.reset();
157 eve::DiagnosticCode::PreconditionViolation, "climbing target exceeded the platform speed limit",
158 "execution.candidate.obstacleBody", {}, "climbing"));
159 }
160 if (!graphBound) {
161 auto worldTop = obstacle->localToWorldPointOwned(
162 execution.candidate.bodyLocalTop.x, execution.candidate.bodyLocalTop.y, execution.candidate.bodyLocalTop.z);
163 if (!worldTop) return eve::Result<ClimbingAdvance>::failure(worldTop.status());
164 auto worldLanding = obstacle->localToWorldPointOwned(execution.candidate.bodyLocalLanding.x,
165 execution.candidate.bodyLocalLanding.y,
166 execution.candidate.bodyLocalLanding.z);
167 if (!worldLanding) return eve::Result<ClimbingAdvance>::failure(worldLanding.status());
168 execution.candidate.topPoint = {worldTop.value().x, worldTop.value().y, worldTop.value().z};
169 if (execution.candidate.kind == ClimbingActionKind::ClimbUp) {
170 execution.candidate.landingFeet =
171 execution.candidate.topPoint - execution.candidate.surfaceNormal * execution.action.landingForward;
172 } else {
173 execution.candidate.landingFeet = {worldLanding.value().x, worldLanding.value().y, worldLanding.value().z};
174 }
175 execution.candidate.leftHandAnchor =
176 execution.candidate.topPoint - execution.candidate.surfaceTangent * (execution.action.handSpacing * 0.5f);
177 execution.candidate.rightHandAnchor =
178 execution.candidate.topPoint + execution.candidate.surfaceTangent * (execution.action.handSpacing * 0.5f);
179 }
180
181 const bool holding =
183 eve::Duration nextElapsed = execution.elapsed;
184 if (!holding && phase_ != ClimbingPhase::Dropping) {
185 auto elapsed = execution.elapsed.tryAdd(step.delta);
186 if (!elapsed) return eve::Result<ClimbingAdvance>::failure(elapsed.status());
187 nextElapsed = std::move(elapsed).takeValue();
188 }
189 const float contactTime =
190 holding ? 1.f : static_cast<float>(std::clamp(nextElapsed.seconds() / execution.duration.seconds(), 0.0, 1.0));
191 const bool feetReleased = execution.landContactReleased || phase_ == ClimbingPhase::Dropping;
192 const bool wantsLeftFoot =
193 !feetReleased && activeContactWeight(execution.action, ClimbingContactTarget::LeftFoot, contactTime) > 0.f;
194 const bool wantsRightFoot =
195 !feetReleased && activeContactWeight(execution.action, ClimbingContactTarget::RightFoot, contactTime) > 0.f;
196 if (hasAuthoredFootAnchors) {
197 hasLeftFootAnchor = wantsLeftFoot;
198 hasRightFootAnchor = wantsRightFoot;
199 } else if (wantsLeftFoot || wantsRightFoot) {
200 // Probe each foot independently. A narrow ledge may support only one side;
201 // an overhead ledge can support the hands while both feet hang freely.
202 Vec3 center = authoredFeetCenter;
203 if (!graphBound) {
204 center = execution.candidate.topPoint;
205 center.y += profile_.capsuleRadius - execution.action.hangFeetBelowLedge;
206 }
207 const Vec3 normal = execution.candidate.surfaceNormal;
208 const Vec3 halfStance = execution.candidate.surfaceTangent * (profile_.capsuleRadius * 0.5f);
209 physics::QueryFilter3D footFilter = profile_.queryFilter;
210 footFilter.ignoredBodyId = execution.candidate.ignoredBodyId;
211 for (int side = 0; side < 2; ++side) {
212 if (!(side == 0 ? wantsLeftFoot : wantsRightFoot)) continue;
213 const Vec3 target = center + halfStance * (side == 0 ? -1.f : 1.f);
214 const Vec3 start =
215 target + normal * (profile_.capsuleRadius + profile_.skin + execution.action.hangBodyOffset);
216 const Vec3 end = target - normal * (profile_.capsuleRadius + profile_.skin);
217 auto hit = world.rayCastOwned(start.x, start.y, start.z, end.x, end.y, end.z, footFilter);
218 ++lastQueryCount_;
219 lastCounters_.queryCount = lastQueryCount_;
220 if (!hit) return eve::Result<ClimbingAdvance>::failure(hit.status());
221 const auto& contact = hit.value();
222 const bool supported =
223 contact.hit && contact.body == execution.candidate.obstacleBody &&
224 contact.normalX * normal.x + contact.normalY * normal.y + contact.normalZ * normal.z > 0.5f;
225 if (debugCapture_ == ClimbingDebugCapture::Enabled)
227 lastDebugQueries_,
229 execution.candidate.actionId,
230 side == 0
231 ? (supported ? "climbing.contact.left_foot.hit" : "climbing.contact.left_foot.miss")
232 : (supported ? "climbing.contact.right_foot.hit" : "climbing.contact.right_foot.miss"),
233 start, end, 0.f, 0.f});
234 if (side == 0) {
235 hasLeftFootAnchor = supported;
236 if (supported) leftFootAnchor = {contact.x, contact.y, contact.z};
237 } else {
238 hasRightFootAnchor = supported;
239 if (supported) rightFootAnchor = {contact.x, contact.y, contact.z};
240 }
241 }
242 }
243
245 filter.ignoredBodyId = execution.candidate.ignoredBodyId;
247 filter.ignoredShapeId = execution.candidate.obstacleShapeId;
248 if (phase_ == ClimbingPhase::Hanging || phase_ == ClimbingPhase::Balanced || phase_ == ClimbingPhase::Swinging) {
249 const float lowerY = execution.currentFeet.y + profile_.capsuleRadius + profile_.skin;
250 const float upperY = execution.currentFeet.y + profile_.capsuleHeight - profile_.capsuleRadius + profile_.skin;
251 auto overlap =
252 world.queryCapsuleOwned(execution.currentFeet.x, lowerY, execution.currentFeet.z, execution.currentFeet.x,
253 upperY, execution.currentFeet.z, profile_.capsuleRadius, filter);
254 if (!overlap) return eve::Result<ClimbingAdvance>::failure(overlap.status());
255 ++lastQueryCount_;
256 lastCounters_.queryCount = lastQueryCount_;
257 if (debugCapture_ == ClimbingDebugCapture::Enabled)
258 boundedDebugPush(lastDebugQueries_,
259 ClimbingDebugQuery{execution.candidate.actionId,
260 "climbing.hang.clearance",
261 {execution.currentFeet.x, lowerY, execution.currentFeet.z},
262 {execution.currentFeet.x, upperY, execution.currentFeet.z},
263 profile_.capsuleRadius,
264 profile_.capsuleHeight});
265 if (overlap.value().bodyCount != 0) {
266 enqueueEvent({ClimbingEventKind::Failed, execution.candidate.actionId, step.tick, execution.executionId});
267 phase_ = ClimbingPhase::Failed;
268 terminalCode_ = "climbing.candidate.clearance_blocked";
269 if (graphBound) {
270 auto released = releaseAnchorReservation();
271 released.ignore("blocked hanging clearance releases graph occupancy");
272 }
273 execution_.reset();
275 eve::DiagnosticCode::PreconditionViolation, "hanging capsule clearance became blocked",
276 "execution.clearance", {}, "climbing"));
277 }
278 execution.lastTick = step.tick;
279 ClimbingAdvance output{phase_, execution.candidate.actionId, execution.currentFeet, {}, {}, {}, 1.f, false,
280 false, execution.candidate.support};
281 output.leftFootAnchor = leftFootAnchor;
282 output.rightFootAnchor = rightFootAnchor;
283 output.hasLeftFootAnchor = hasLeftFootAnchor;
284 output.hasRightFootAnchor = hasRightFootAnchor;
285 output.leftHandAnchor = execution.candidate.leftHandAnchor;
286 output.rightHandAnchor = execution.candidate.rightHandAnchor;
287 const bool handHold = phase_ != ClimbingPhase::Balanced;
288 const bool authoredContacts = !execution.action.contactConstraints.empty();
289 output.leftHandWeight = authoredContacts
291 : (handHold ? 1.f : 0.f);
292 output.rightHandWeight = authoredContacts
294 : (handHold ? 1.f : 0.f);
295 output.leftFootWeight = activeContactWeight(execution.action, ClimbingContactTarget::LeftFoot, 1.f);
296 output.rightFootWeight = activeContactWeight(execution.action, ClimbingContactTarget::RightFoot, 1.f);
297 output.pelvisWeight = activeContactWeight(execution.action, ClimbingContactTarget::Pelvis, 1.f);
298 output.contactWeight = std::max({output.leftHandWeight, output.rightHandWeight, output.leftFootWeight,
299 output.rightFootWeight, output.pelvisWeight});
300 output.executionId = execution.executionId;
301 output.compactCollisionActive = execution.compactCollisionActive;
302 output.branchWindowOpen = execution.branchWindowOpen;
303 output.cameraCueProfile = profile_.cameraCueProfile;
304 output.cameraCue = execution.action.cameraCue;
305 output.animationClipId = execution.action.animation.clipId;
306 output.animationGraphNodeId = execution.action.animation.graphNodeId;
307 output.animationMirrored = execution.action.animation.mirrored;
309 }
310
311 if (phase_ == ClimbingPhase::Dropping) {
312 const float dt = static_cast<float>(step.delta.seconds());
313 execution.velocity.x += world.getGravityX() * dt;
314 execution.velocity.y += world.getGravityY() * dt;
315 execution.velocity.z += world.getGravityZ() * dt;
316 const Vec3 desired = execution.velocity * dt;
317 const float lowerY = execution.currentFeet.y + profile_.capsuleRadius;
318 const float upperY = execution.currentFeet.y + profile_.capsuleHeight - profile_.capsuleRadius;
319 auto moved = world.moveCapsuleOwned(execution.currentFeet.x, lowerY, execution.currentFeet.z,
320 execution.currentFeet.x, upperY, execution.currentFeet.z,
321 profile_.capsuleRadius, desired.x, desired.y, desired.z, filter);
322 if (!moved) return eve::Result<ClimbingAdvance>::failure(moved.status());
323 ++lastQueryCount_;
324 lastCounters_.queryCount = lastQueryCount_;
325 const physics::CapsuleMove3D movement = std::move(moved).takeValue();
326 lastCounters_.moverIterations = static_cast<std::uint32_t>(std::max(0, movement.iterations));
327 const Vec3 actual{movement.deltaX, movement.deltaY, movement.deltaZ};
328 lastCounters_.warpResidual = desired - actual;
329 execution.currentFeet = execution.currentFeet + actual;
330 execution.lastTick = step.tick;
332 execution.candidate.actionId,
333 execution.currentFeet,
334 desired,
335 actual,
336 desired - actual,
337 1.f,
338 movement.constrained,
339 movement.grounded,
341 output.executionId = execution.executionId;
342 output.cameraCueProfile = profile_.cameraCueProfile;
343 output.cameraCue = execution.action.cameraCue;
344 output.animationClipId = execution.action.animation.clipId;
345 output.animationGraphNodeId = execution.action.animation.graphNodeId;
346 output.animationMirrored = execution.action.animation.mirrored;
347 if (movement.grounded) {
349 terminalCode_ = "climbing.completed";
350 output.phase = phase_;
351 enqueueEvent({ClimbingEventKind::Landed, output.actionId, step.tick, execution.executionId});
352 enqueueEvent({ClimbingEventKind::Completed, output.actionId, step.tick, execution.executionId});
353 output.terminalVelocity = terminalVelocityFor(execution.action, actual, 1.f / dt);
354 output.hasTerminalVelocity = true;
355 execution_.reset();
356 }
358 }
359
360 execution.elapsed = nextElapsed;
361 execution.lastTick = step.tick;
362 const double durationSeconds = execution.duration.seconds();
363 const float t = static_cast<float>(std::clamp(execution.elapsed.seconds() / durationSeconds, 0.0, 1.0));
364 const Vec3 planned = detail::trajectoryPoint(execution.startFeet, execution.candidate, execution.action, profile_,
365 t, sourceAnchor ? sourceAnchor->normal : Vec3{});
366 const Vec3 proceduralDelta = planned - execution.currentFeet;
367 Vec3 baseDelta = proceduralDelta;
369 baseDelta = motion.rootTranslation;
370 } else if (motion.hasRootMotion) {
371 const float authoredLength = length(motion.rootTranslation);
372 const float targetLength = length(proceduralDelta);
373 const float scale = authoredLength > epsilon
374 ? std::clamp(targetLength / authoredLength, execution.action.rootMotionScaleMin,
375 execution.action.rootMotionScaleMax)
376 : execution.action.rootMotionScaleMin;
377 baseDelta = motion.rootTranslation * scale;
378 }
379
381 ? WarpChannels{}
382 : activeWarpChannels(execution.action, t);
383 const Vec3 warpError = planned - (execution.currentFeet + baseDelta);
384 Vec3 appliedWarp;
385 if (channels.horizontal) {
386 Vec3 horizontal{warpError.x, 0.f, warpError.z};
387 const float remaining = std::max(0.f, execution.action.horizontalWarpBudget - execution.horizontalWarpUsed);
388 horizontal = clampMagnitude(horizontal, std::min(execution.action.maxTranslationWarpPerTick, remaining));
389 appliedWarp.x = horizontal.x;
390 appliedWarp.z = horizontal.z;
391 }
392 if (channels.vertical) {
393 const float remaining = std::max(0.f, execution.action.verticalWarpBudget - execution.verticalWarpUsed);
394 appliedWarp.y = std::clamp(warpError.y, -std::min(execution.action.maxTranslationWarpPerTick, remaining),
395 std::min(execution.action.maxTranslationWarpPerTick, remaining));
396 }
397 const float remainingTotalWarp =
398 std::max(0.f, profile_.maxTotalWarpBudget - execution.horizontalWarpUsed - execution.verticalWarpUsed);
399 appliedWarp = clampMagnitude(appliedWarp, std::min(execution.action.maxTranslationWarpPerTick, remainingTotalWarp));
400 execution.horizontalWarpUsed += length({appliedWarp.x, 0.f, appliedWarp.z});
401 execution.verticalWarpUsed += std::fabs(appliedWarp.y);
402 const Vec3 desired = baseDelta + appliedWarp;
403
404 float desiredYawDelta = motion.rootYawRadians;
405 if (channels.facing) {
406 const Vec3 targetFacing = execution.candidate.surfaceNormal * -1.f;
407 const float yawError = signedHorizontalAngle(motion.facing, targetFacing) - motion.rootYawRadians;
408 const float remaining = std::max(0.f, execution.action.facingWarpBudgetRadians - execution.facingWarpUsed);
409 const float correction = std::clamp(yawError, -std::min(execution.action.maxYawWarpRadiansPerTick, remaining),
410 std::min(execution.action.maxYawWarpRadiansPerTick, remaining));
411 execution.facingWarpUsed += std::fabs(correction);
412 desiredYawDelta += correction;
413 }
414 const float authoredLeftHand = activeContactWeight(execution.action, ClimbingContactTarget::LeftHand, t);
415 const float authoredRightHand = activeContactWeight(execution.action, ClimbingContactTarget::RightHand, t);
416 bool leftContact = authoredLeftHand > epsilon;
417 bool rightContact = authoredRightHand > epsilon;
418 bool landContact = false;
419 bool compactRequested = false;
420 bool compactForTick = execution.compactCollisionActive;
421 bool branchForTick =
422 execution.action.branchWindows.empty() ? execution.branchWindowOpen : activeBranchWindow(execution.action, t);
423 for (ClimbingNotifyKind notify : motion.notifies) {
424 switch (notify) {
425 case ClimbingNotifyKind::ContactLeftHand: leftContact = true; break;
426 case ClimbingNotifyKind::ContactRightHand: rightContact = true; break;
428 compactRequested = true;
429 compactForTick = true;
430 break;
431 case ClimbingNotifyKind::BranchOpen: branchForTick = true; break;
432 case ClimbingNotifyKind::BranchClose: branchForTick = false; break;
434 landContact = true;
435 compactForTick = false;
436 branchForTick = false;
437 break;
438 }
439 }
440 const float collisionHeight = compactForTick ? profile_.compactCapsuleHeight : profile_.capsuleHeight;
441 const float lowerY = execution.currentFeet.y + profile_.capsuleRadius;
442 const float upperY = execution.currentFeet.y + collisionHeight - profile_.capsuleRadius;
443 auto moved = world.moveCapsuleOwned(execution.currentFeet.x, lowerY, execution.currentFeet.z,
444 execution.currentFeet.x, upperY, execution.currentFeet.z,
445 profile_.capsuleRadius, desired.x, desired.y, desired.z, filter);
446 if (!moved) return eve::Result<ClimbingAdvance>::failure(moved.status());
447 ++lastQueryCount_;
448 lastCounters_.queryCount = lastQueryCount_;
449 const physics::CapsuleMove3D movement = std::move(moved).takeValue();
450 lastCounters_.moverIterations = static_cast<std::uint32_t>(std::max(0, movement.iterations));
451 const Vec3 actual{movement.deltaX, movement.deltaY, movement.deltaZ};
452 if (debugCapture_ == ClimbingDebugCapture::Enabled)
453 boundedDebugPush(lastDebugQueries_,
454 ClimbingDebugQuery{execution.candidate.actionId, "climbing.active.move", execution.currentFeet,
455 execution.currentFeet + desired, profile_.capsuleRadius, collisionHeight});
456 execution.currentFeet = execution.currentFeet + actual;
457 execution.lastPlannedFeet = planned;
458 const Vec3 residual = desired - actual;
459 lastCounters_.warpResidual = residual;
460 execution.accumulatedResidual = execution.accumulatedResidual + residual;
461 execution.compactCollisionActive = compactForTick;
462 execution.branchWindowOpen = branchForTick;
463 if (debugCapture_ == ClimbingDebugCapture::Enabled)
464 boundedDebugPush(motionEvidence_, ClimbingMotionEvidence{step.tick, planned, execution.currentFeet, residual,
465 collisionHeight, movement.constrained});
467 execution.candidate.actionId,
468 execution.currentFeet,
469 desired,
470 actual,
471 residual,
472 t,
473 movement.constrained,
474 movement.grounded,
475 execution.candidate.support};
476 output.executionId = execution.executionId;
477 output.appliedWarp = appliedWarp;
478 output.desiredYawDelta = desiredYawDelta;
479 output.cameraCueProfile = profile_.cameraCueProfile;
480 output.cameraCue = execution.action.cameraCue;
481 output.animationClipId = execution.action.animation.clipId;
482 output.animationGraphNodeId = execution.action.animation.graphNodeId;
483 output.animationMirrored = execution.action.animation.mirrored;
484 output.leftFootAnchor = leftFootAnchor;
485 output.rightFootAnchor = rightFootAnchor;
486 output.hasLeftFootAnchor = hasLeftFootAnchor;
487 output.hasRightFootAnchor = hasRightFootAnchor;
488 output.leftHandAnchor = execution.candidate.leftHandAnchor;
489 output.rightHandAnchor = execution.candidate.rightHandAnchor;
490 if (sourceAnchor) {
491 const auto transfer = [&](ClimbingContactTarget hand, Vec3 source, Vec3 target) {
492 float begin = 0.f;
493 float end = 1.f;
494 bool found = false;
495 for (const auto& window : execution.action.contactConstraints) {
496 if (window.target != hand || window.maxWeight <= 0.f) continue;
497 if (!found || window.start < begin) {
498 begin = window.start;
499 end = window.end;
500 found = true;
501 }
502 }
503 const float linear =
504 end > begin ? std::clamp((t - begin) / (end - begin), 0.f, 1.f) : (t >= end ? 1.f : 0.f);
505 const float blend = linear * linear * (3.f - 2.f * linear);
506 if (execution.action.kind == ClimbingActionKind::CornerInner ||
507 execution.action.kind == ClimbingActionKind::CornerOuter)
508 return detail::cornerPathPoint(source, target, sourceAnchor->normal, execution.candidate.surfaceNormal,
509 linear);
510 return source + (target - source) * blend;
511 };
512 output.leftHandAnchor =
513 transfer(ClimbingContactTarget::LeftHand, sourceAnchor->leftHandSocket, output.leftHandAnchor);
514 output.rightHandAnchor =
515 transfer(ClimbingContactTarget::RightHand, sourceAnchor->rightHandSocket, output.rightHandAnchor);
516 }
517
518 if (leftContact && !execution.leftContactEmitted) {
519 execution.leftContactEmitted = true;
520 enqueueEvent({ClimbingEventKind::ContactLeftHand, output.actionId, step.tick, execution.executionId});
521 }
522 if (rightContact && !execution.rightContactEmitted) {
523 execution.rightContactEmitted = true;
524 enqueueEvent({ClimbingEventKind::ContactRightHand, output.actionId, step.tick, execution.executionId});
525 }
526 if (landContact) execution.landContactReleased = true;
527 if (execution.action.contactConstraints.empty()) {
528 output.leftHandWeight = execution.leftContactEmitted && !execution.landContactReleased ? 1.f : 0.f;
529 output.rightHandWeight = execution.rightContactEmitted && !execution.landContactReleased ? 1.f : 0.f;
530 } else if (!execution.landContactReleased) {
531 output.leftHandWeight = authoredLeftHand;
532 output.rightHandWeight = authoredRightHand;
533 output.leftFootWeight = activeContactWeight(execution.action, ClimbingContactTarget::LeftFoot, t);
534 output.rightFootWeight = activeContactWeight(execution.action, ClimbingContactTarget::RightFoot, t);
535 output.pelvisWeight = activeContactWeight(execution.action, ClimbingContactTarget::Pelvis, t);
536 }
537 output.contactWeight = std::max({output.leftHandWeight, output.rightHandWeight, output.leftFootWeight,
538 output.rightFootWeight, output.pelvisWeight});
539 output.compactCollisionRequested = compactRequested;
540 output.compactCollisionActive = execution.compactCollisionActive;
541 output.branchWindowOpen = execution.branchWindowOpen;
542 if (const std::string* comboTag = activeBranchComboTag(execution.action, t)) output.branchComboTag = *comboTag;
543 if (t < 0.1f)
545 else if (t < 0.2f)
547 else if (t < 0.8f)
549 else if (t < 0.95f)
550 phase_ = ClimbingPhase::Landing;
551 else
553 output.phase = phase_;
554 const Vec3 remainingTargetError = planned - execution.currentFeet;
555 const bool authoredWarpMissed = motion.hasRootMotion &&
557 t + epsilon >= finalWarpWindowEnd(execution.action) &&
558 length(remainingTargetError) > profile_.maxWarpResidual + epsilon;
559 if (length(execution.accumulatedResidual) > profile_.maxWarpResidual + epsilon || authoredWarpMissed) {
560 phase_ = ClimbingPhase::Failed;
561 terminalCode_ = "climbing.warp.budget_exceeded";
562 output.phase = phase_;
563 enqueueEvent({ClimbingEventKind::Failed, output.actionId, step.tick, execution.executionId});
564 if (graphBound) {
565 auto released = releaseAnchorReservation();
566 released.ignore("failed anchor motion releases graph occupancy");
567 }
568 execution_.reset();
569 } else if (t >= 1.f - epsilon) {
570 execution.sourceAnchorNode.reset();
571 if (graphBound && isAnchorHangEnd(execution.candidate.kind)) {
572 if (execution.candidate.kind == ClimbingActionKind::BeamBalance)
574 else if (execution.candidate.kind == ClimbingActionKind::PoleSwing ||
575 execution.candidate.kind == ClimbingActionKind::BarSwing)
577 else
578 phase_ = ClimbingPhase::Hanging;
579 execution.branchWindowOpen = true;
580 output.branchWindowOpen = true;
581 enqueueEvent({execution.candidate.kind == ClimbingActionKind::LedgeGrab ? ClimbingEventKind::Hanging
583 output.actionId, step.tick, execution.executionId});
584 } else if (execution.candidate.kind == ClimbingActionKind::LedgeGrab) {
585 phase_ = ClimbingPhase::Hanging;
586 execution.branchWindowOpen = true;
587 output.branchWindowOpen = true;
588 enqueueEvent({ClimbingEventKind::Hanging, output.actionId, step.tick, execution.executionId});
589 } else {
591 terminalCode_ = "climbing.completed";
592 if (execution.candidate.kind != ClimbingActionKind::WallRun)
593 enqueueEvent({ClimbingEventKind::Landed, output.actionId, step.tick, execution.executionId});
594 enqueueEvent({ClimbingEventKind::Completed, output.actionId, step.tick, execution.executionId});
595 if (graphBound) {
596 auto released = releaseAnchorReservation();
597 released.ignore("completed graph dismount releases occupancy");
598 }
599 }
600 output.phase = phase_;
601 if (phase_ == ClimbingPhase::Completed) {
602 output.terminalVelocity =
603 terminalVelocityFor(execution.action, actual, static_cast<float>(1.0 / step.delta.seconds()));
604 output.hasTerminalVelocity = true;
605 execution_.reset();
606 }
607 }
609}
610
611
612} // namespace eve::climbing
LogicalId target
Duration start
std::map< std::string, std::vector< Key >, std::less<> > channels
std::string output
Deterministic climbing/parkour planning and capsule-constrained execution.
float linear
float blend
float length
std::array< float, 3 > scale
Texture * normal
glm::dvec2 center
double dt
std::map< std::string, std::vector< std::string > > graph
Definition Package.cpp:173
bool hit
float t
RoadNetwork resolved
bool found
std::string filter
std::string_view source
size_t begin
size_t end
float step
Definition TreeMesh.cpp:451
Contact contact
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Signed, fixed-resolution simulation duration in nanoseconds.
Definition Time.h:43
Result< Duration > tryAdd(Duration other) const
Add two durations with overflow validation.
Definition Time.cpp:31
double seconds() const noexcept
Return this duration as seconds for legacy/presentation APIs.
Definition Time.cpp:29
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
eve::Result< ClimbingAdvance > advance(physics::World3D &world, eve::SimulationStep step)
Advances the active trajectory through the world's capsule mover.
static eve::script::Borrowed< ClimbingAnchorGraphInstance > resolveAnchorGraph(ClimbingAnchorGraphHandleRef reference) noexcept
Resolves a live graph instance as a synchronous non-owning observation.
Backend-neutral 3D rigid body in meter-space coordinates (+Y up by convention). Owned by a World3D; c...
Definition Body3D.h:31
float getLinearVelocityY() const
Returns the linear velocity y.
Definition Body3D.cpp:137
eve::Result< PhysicsVector3D > localToWorldPointOwned(float x, float y, float z) const
Converts a local point to an allocation-free owning value with structured stale/input failure.
Definition Body3D.cpp:169
float getLinearVelocityZ() const
Returns the linear velocity z.
Definition Body3D.cpp:141
float getLinearVelocityX() const
Returns the linear velocity x.
Definition Body3D.cpp:133
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
Vec3 trajectoryPoint(Vec3 start, const ClimbingCandidate &candidate, const ClimbingActionDefinition &action, const ClimbingProfileDefinition &profile, float normalizedTime, Vec3 sourceNormal={}) noexcept
Vec3 cornerPathPoint(Vec3 start, Vec3 end, Vec3 sourceNormal, Vec3 targetNormal, float normalizedTime) noexcept
WarpChannels activeWarpChannels(const ClimbingActionDefinition &action, float normalizedTime)
Active warp channels.
float activeContactWeight(const ClimbingActionDefinition &action, ClimbingContactTarget target, float normalizedTime)
Active contact weight.
const std::string * activeBranchComboTag(const ClimbingActionDefinition &action, float normalizedTime)
Optional combo tag. @borrowed From action; lifetime ends when the caller-owned action changes or is d...
float finalWarpWindowEnd(const ClimbingActionDefinition &action)
Final warp window end.
Vec3 clampMagnitude(Vec3 value, float maximum)
Clamp magnitude.
bool isFinite(float value)
True when finite.
void boundedDebugPush(std::vector< T > &values, T value)
Bounded debug push.
bool isActivePhase(ClimbingPhase phase)
True when active phase.
bool activeBranchWindow(const ClimbingActionDefinition &action, float normalizedTime)
Active branch window.
float signedHorizontalAngle(Vec3 from, Vec3 to)
Signed horizontal angle.
Vec3 terminalVelocityFor(const ClimbingActionDefinition &action, Vec3 actualDelta, float inverseDelta)
Terminal velocity for.
bool isAnchorHangEnd(ClimbingActionKind kind)
True when anchor hang end.
ClimbingContactTarget
Contact target used by animation/IK adapters.
Definition Climbing.h:115
ClimbingNotifyKind
Stable animation notify semantics accepted from a validated climbing clip.
Definition Climbing.h:503
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Owning output of one execution tick.
Definition Climbing.h:553
Geometry-query evidence suitable for an engine debug-draw adapter.
Definition Climbing.h:609
One planned-versus-actual capsule sample from an authoritative execution tick.
Definition Climbing.h:629
Per-tick authored animation motion supplied before climbing warp and collision.
Definition Climbing.h:540
ClimbingObstacleCollision obstacleCollision
Definition Climbing.h:549
std::vector< ClimbingNotifyKind > notifies
Owning semantic notifies crossed by the animation player during this exact simulation step.
Definition Climbing.h:547
ClimbingRootMotionPolicy rootMotionPolicy
Definition Climbing.h:548
physics::QueryFilter3D queryFilter
Definition Climbing.h:254
static constexpr std::uint32_t Active
Small owning world-space vector used at climbing module boundaries.
Owning result of continuous capsule movement.
Query filter applied atomically for one owning query operation.