载入中...
搜索中...
未找到
ClimbingECS.h
浏览该文件的文档.
1#pragma once
2#include "common/Export.h"
3
4
10#include "climbing/Climbing.h"
12#include "common/ECS.h"
13#include "physics/Body3D.h"
14#include "physics/PhysicsLink.h"
15#include "physics/World3D.h"
16
17#include <array>
18#include <algorithm>
19#include <chrono>
20#include <cmath>
21#include <cstddef>
22#include <cstdint>
23#include <span>
24#include <string>
25#include <string_view>
26#include <utility>
27
28namespace eve::climbing {
29
50
64
67public:
68 static constexpr std::size_t Capacity = ClimbingCandidateSet::Capacity;
69
71 [[nodiscard]] eve::Result<void> replace(std::span<const ClimbingCandidate> candidates,
74 [[nodiscard]] eve::Result<void> probe(ClimbingRuntime& runtime, physics::World3D& world,
77 [[nodiscard]] std::span<const ClimbingCandidate> values() const noexcept {
78 return values_.values();
79 }
81 void clear() noexcept { values_.clear(); }
83 [[nodiscard]] eve::SimulationTick tick() const noexcept { return tick_; }
84
85private:
88};
89
106
124
127public:
128 static constexpr std::size_t Capacity = ClimbingRuntime::PendingEventCapacity;
129
131 [[nodiscard]] eve::Result<void> replace(std::span<const ClimbingEvent> events,
134 [[nodiscard]] std::span<const ClimbingEvent> values() const noexcept { return {values_.data(), size_}; }
136 [[nodiscard]] eve::SimulationTick tick() const noexcept { return tick_; }
137
138private:
139 std::array<ClimbingEvent, Capacity> values_{};
140 std::size_t size_ = 0;
142};
143
146 std::string_view name;
147 std::string_view entityScope;
148 std::string_view view;
149 std::string_view readSet;
150 std::string_view writeSet;
151 std::string_view structuralChanges;
152 std::string_view events;
153 std::string_view services;
154 std::string_view phase;
155 std::string_view determinism;
156};
157
159[[nodiscard]] EVENGINE_API_DOMAINS std::span<const ClimbingSystemContract> climbingSystemContracts() noexcept;
160
161namespace detail {
162
168} // namespace detail
169
172public:
182 template <class EntityRoot>
184 [[nodiscard]] static eve::Result<std::size_t> step(physics::World3D& world,
186 std::size_t processed = 0;
187 auto view = ecs::View<EntityRoot, ClimbingBody, ClimbingIntent, ClimbingState,
189 for (auto it = view.begin(); it != view.end(); ++it) {
190 auto [body, intent, state, links, buffer] = *it;
191 (void)intent;
192 auto runtime = Climbing::resolve(state->runtime);
193 if (!runtime.isBound())
196 "climbing runtime link is stale",
197 "state.runtime", {}, "climbing.ecs"));
198 auto linkedBody = links->physicsBody.resolve(world);
199 if (!linkedBody)
201 return eve::Result<std::size_t>::failure(linkedBody.status());
202 const bool hasEligibleIntent = std::any_of(intent->commands.begin(), intent->commands.end(),
203 [&](const BufferedClimbingCommand& command) {
204 return command.consumedExecutionId.isZero() &&
205 command.pressedTick <= tick && tick <= command.expiryTick;
206 });
207 if (!hasEligibleIntent) {
208 buffer->clear();
209 ++processed;
210 continue;
211 }
212 const ClimbingPose pose{body->feet, body->forward,
214 std::sqrt(body->velocity.x * body->velocity.x +
215 body->velocity.z * body->velocity.z),
216 linkedBody.value()->getId(), body->velocity.y, body->grounded,
217 intent->move, intent->look, intent->mode};
218 auto probed = buffer->probe(*runtime, world, pose, tick);
219 if (!probed) return eve::Result<std::size_t>::failure(probed.status());
220 ++processed;
221 }
223 return eve::Result<std::size_t>::success(processed);
224 }
225};
226
229public:
234 template <class EntityRoot>
236 [[nodiscard]] static eve::Result<std::size_t> step(physics::World3D& world,
237 ClimbingCommand command,
239 std::size_t started = 0;
240 auto view = ecs::View<EntityRoot, ClimbingBody, ClimbingIntent, ClimbingState, ClimbingLinks>();
241 for (auto it = view.begin(); it != view.end(); ++it) {
242 auto [body, intent, state, links] = *it;
243 if (!ClimbingInputSystem::peek(*intent, command, tick)) continue;
244 auto runtime = Climbing::resolve(state->runtime);
245 if (!runtime.isBound())
248 "climbing runtime link is stale",
249 "state.runtime", {}, "climbing.ecs"));
250 auto linkedBody = links->physicsBody.resolve(world);
251 if (!linkedBody) return eve::Result<std::size_t>::failure(linkedBody.status());
252 const ClimbingPose pose{body->feet, body->forward,
254 std::sqrt(body->velocity.x * body->velocity.x +
255 body->velocity.z * body->velocity.z),
256 linkedBody.value()->getId(), body->velocity.y, body->grounded,
257 intent->move, intent->look, intent->mode};
258 auto selected = ClimbingSelectionSystem::tryStart(*runtime, world, pose, *intent, command,
259 tick, body->lastGroundedTick);
261 ++started;
262 }
265 }
266};
267
270public:
275 template <class EntityRoot>
277 [[nodiscard]] static eve::Result<std::size_t> step(physics::World3D& world,
279 const ClimbingMotionInput& motion = {}) {
280 if (step.delta.nanoseconds() <= 0)
283 "climbing motion delta must be positive",
284 "step.delta", {}, "climbing.ecs"));
285 std::size_t processed = 0;
286 auto view = ecs::View<EntityRoot, ClimbingBody, ClimbingIntent, ClimbingState, ClimbingLinks>();
287 for (auto it = view.begin(); it != view.end(); ++it) {
288 auto [body, intent, state, links] = *it;
289 auto runtime = Climbing::resolve(state->runtime);
290 if (!runtime.isBound())
293 "climbing runtime link is stale",
294 "state.runtime", {}, "climbing.ecs"));
295 auto linkedBody = links->physicsBody.resolve(world);
296 if (!linkedBody) return eve::Result<std::size_t>::failure(linkedBody.status());
297 if (!detail::activeClimbingPhase(runtime->phase())) {
298 const auto ordinaryStart = std::chrono::steady_clock::now();
299 if (!(body->capsuleRadius > 0.f) ||
300 !(body->capsuleHeight > body->capsuleRadius * 2.f) || body->skin < 0.f ||
301 body->groundSnap < 0.f || body->stepHeight < 0.f ||
302 !std::isfinite(body->maxSlopeRadians) || body->maxSlopeRadians < 0.f ||
303 body->maxSlopeRadians >= 1.57079633f)
306 eve::DiagnosticCode::InvalidArgument, "ordinary locomotion capsule is invalid", "body.capsule",
307 {}, "climbing.ecs"));
308 const ClimbingLocomotionPolicy policy = runtime->locomotionPolicy();
309 const float deltaSeconds = static_cast<float>(step.delta.seconds());
310 const float moveLength = std::sqrt(intent->move.x * intent->move.x +
311 intent->move.z * intent->move.z);
312 const Vec3 desiredVelocity{intent->move.x, 0.f, intent->move.z};
313 const float acceleration = body->grounded
314 ? (moveLength > 1e-6f ? policy.groundAcceleration
315 : policy.groundBraking)
316 : policy.groundAcceleration * policy.airControl;
317 const float maxVelocityChange = acceleration * deltaSeconds;
318 const Vec3 horizontalError{desiredVelocity.x - body->velocity.x, 0.f,
319 desiredVelocity.z - body->velocity.z};
320 const float errorLength = std::sqrt(horizontalError.x * horizontalError.x +
321 horizontalError.z * horizontalError.z);
322 if (errorLength > maxVelocityChange && errorLength > 1e-6f) {
323 const float scale = maxVelocityChange / errorLength;
324 body->velocity.x += horizontalError.x * scale;
325 body->velocity.z += horizontalError.z * scale;
326 } else {
327 body->velocity.x = desiredVelocity.x;
328 body->velocity.z = desiredVelocity.z;
329 }
330
331 const auto jump = ClimbingInputSystem::peek(*intent, ClimbingCommand::Jump, step.tick);
332 const bool freshJump = jump && (!body->hasOrdinaryJump ||
333 jump->pressedTick != body->lastOrdinaryJumpPressedTick);
334 if (freshJump &&
335 (body->grounded ||
337 ClimbingInputSystem::coyoteWindowState(step.tick, body->lastGroundedTick,
338 policy.coyoteTicks) == ClimbingCoyoteState::Eligible)) {
339 body->velocity.y = policy.jumpSpeed;
340 body->grounded = false;
341 body->lastOrdinaryJumpPressedTick = jump->pressedTick;
342 body->hasOrdinaryJump = true;
343 } else if (!body->grounded) {
344 body->velocity.y -= policy.gravity * deltaSeconds;
345 } else {
346 body->velocity.y = 0.f;
347 }
348
349 physics::QueryFilter3D filter = policy.queryFilter;
350 filter.ignoredBodyId = linkedBody.value()->getId();
351 const physics::CapsuleMovePolicy3D moverPolicy{
352 body->up.x, body->up.y, body->up.z, body->maxSlopeRadians};
353 const float lowerY = body->feet.y + body->capsuleRadius + body->skin;
354 const float upperY = body->feet.y + body->capsuleHeight - body->capsuleRadius + body->skin;
355 const float snap = body->grounded && !freshJump ? body->groundSnap : 0.f;
356 auto moved = world.moveCapsuleOwned(
357 body->feet.x, lowerY, body->feet.z, body->feet.x, upperY, body->feet.z,
358 body->capsuleRadius, body->velocity.x * deltaSeconds,
359 body->velocity.y * deltaSeconds - snap, body->velocity.z * deltaSeconds,
360 filter, moverPolicy);
361 if (!moved) return eve::Result<std::size_t>::failure(moved.status());
362 physics::CapsuleMove3D movement = std::move(moved).takeValue();
363 std::uint32_t queryCount = 1;
364 std::uint32_t moverIterations = static_cast<std::uint32_t>(movement.iterations);
365 const float desiredX = body->velocity.x * deltaSeconds;
366 const float desiredZ = body->velocity.z * deltaSeconds;
367 const float desiredHorizontal = std::sqrt(desiredX * desiredX + desiredZ * desiredZ);
368 const float directHorizontal = std::sqrt(movement.deltaX * movement.deltaX +
369 movement.deltaZ * movement.deltaZ);
370 if (body->grounded && !freshJump && body->stepHeight > 0.f &&
371 desiredHorizontal > 1e-6f && directHorizontal + body->skin < desiredHorizontal) {
372 auto raised = world.moveCapsuleOwned(
373 body->feet.x, lowerY, body->feet.z, body->feet.x, upperY, body->feet.z,
374 body->capsuleRadius, 0.f, body->stepHeight, 0.f, filter, moverPolicy);
375 if (!raised) return eve::Result<std::size_t>::failure(raised.status());
376 ++queryCount;
377 const physics::CapsuleMove3D rise = std::move(raised).takeValue();
378 moverIterations += static_cast<std::uint32_t>(rise.iterations);
379 if (rise.deltaY + body->skin >= body->stepHeight) {
380 auto crossed = world.moveCapsuleOwned(
381 body->feet.x, lowerY + rise.deltaY, body->feet.z,
382 body->feet.x, upperY + rise.deltaY, body->feet.z,
383 body->capsuleRadius, desiredX, 0.f, desiredZ, filter, moverPolicy);
384 if (!crossed) return eve::Result<std::size_t>::failure(crossed.status());
385 ++queryCount;
386 const physics::CapsuleMove3D across = std::move(crossed).takeValue();
387 moverIterations += static_cast<std::uint32_t>(across.iterations);
388 const float steppedHorizontal = std::sqrt(across.deltaX * across.deltaX +
389 across.deltaZ * across.deltaZ);
390 auto lowered = world.moveCapsuleOwned(
391 body->feet.x + across.deltaX, lowerY + rise.deltaY,
392 body->feet.z + across.deltaZ, body->feet.x + across.deltaX,
393 upperY + rise.deltaY, body->feet.z + across.deltaZ,
394 body->capsuleRadius, 0.f,
395 -(rise.deltaY + body->groundSnap + body->skin), 0.f, filter, moverPolicy);
396 if (!lowered) return eve::Result<std::size_t>::failure(lowered.status());
397 ++queryCount;
398 const physics::CapsuleMove3D down = std::move(lowered).takeValue();
399 moverIterations += static_cast<std::uint32_t>(down.iterations);
400 if (down.grounded && steppedHorizontal > directHorizontal + body->skin) {
401 movement.constrained = rise.constrained || across.constrained || down.constrained;
402 movement.grounded = true;
403 movement.deltaX = across.deltaX;
404 movement.deltaY = rise.deltaY + down.deltaY;
405 movement.deltaZ = across.deltaZ;
406 movement.normalX = down.normalX;
407 movement.normalY = down.normalY;
408 movement.normalZ = down.normalZ;
409 movement.planeCount = rise.planeCount + across.planeCount + down.planeCount;
410 movement.iterations = rise.iterations + across.iterations + down.iterations;
411 }
412 }
413 }
414 body->feet = {body->feet.x + movement.deltaX, body->feet.y + movement.deltaY,
415 body->feet.z + movement.deltaZ};
416 body->grounded = movement.grounded && body->velocity.y <= 0.f;
417 body->mode = body->grounded ? ClimbingMovementMode::Grounded
419 body->velocity.x = movement.deltaX / deltaSeconds;
420 body->velocity.z = movement.deltaZ / deltaSeconds;
421 body->velocity.y = body->grounded ? 0.f : movement.deltaY / deltaSeconds;
422 if (body->grounded) {
423 body->groundNormal = {movement.normalX, movement.normalY, movement.normalZ};
424 body->lastStableFeet = body->feet;
425 body->lastGroundedTick = step.tick;
426 }
427 if (moveLength > 1e-6f)
428 body->forward = {intent->move.x / moveLength, 0.f, intent->move.z / moveLength};
429 linkedBody.value()->setPosition(body->feet.x,
430 body->feet.y + body->capsuleHeight * 0.5f,
431 body->feet.z);
432 const auto ordinaryElapsed = std::chrono::steady_clock::now() - ordinaryStart;
433 runtime->recordOrdinaryTick(
434 step.tick, queryCount, moverIterations,
435 static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
436 ordinaryElapsed)
437 .count()));
438 ++processed;
439 continue;
440 }
441 const Vec3 previous = body->feet;
442 auto advanced = runtime->advance(world, step, motion);
443 if (!advanced) return eve::Result<std::size_t>::failure(advanced.status());
444 state->lastAdvance = std::move(advanced).takeValue();
445 state->lastAdvanceTick = step.tick;
446 body->feet = state->lastAdvance.feet;
447 const float inverseDelta = static_cast<float>(1.0 / step.delta.seconds());
448 body->velocity = {(body->feet.x - previous.x) * inverseDelta,
449 (body->feet.y - previous.y) * inverseDelta,
450 (body->feet.z - previous.z) * inverseDelta};
451 if (state->lastAdvance.hasTerminalVelocity)
452 body->velocity = state->lastAdvance.terminalVelocity;
453 body->grounded = state->lastAdvance.grounded;
454 body->mode = detail::activeClimbingPhase(state->lastAdvance.phase)
458 if (body->grounded) {
459 body->lastStableFeet = body->feet;
460 body->lastGroundedTick = step.tick;
461 }
462 linkedBody.value()->setPosition(body->feet.x, body->feet.y + body->capsuleHeight * 0.5f,
463 body->feet.z);
464 ++processed;
465 }
467 return eve::Result<std::size_t>::success(processed);
468 }
469};
470
473public:
478 template <class EntityRoot>
481 std::size_t processed = 0;
482 auto view = ecs::View<EntityRoot, ClimbingState, ClimbingPoseProjection, ClimbingEventBatch>();
483 for (auto it = view.begin(); it != view.end(); ++it) {
484 auto [state, pose, events] = *it;
485 auto runtime = Climbing::resolve(state->runtime);
486 if (!runtime.isBound())
489 "climbing runtime link is stale",
490 "state.runtime", {}, "climbing.ecs"));
491 pose->executionId = state->lastAdvance.executionId;
492 pose->leftHandAnchor = state->lastAdvance.leftHandAnchor;
493 pose->rightHandAnchor = state->lastAdvance.rightHandAnchor;
494 pose->leftHandWeight = state->lastAdvance.leftHandWeight;
495 pose->rightHandWeight = state->lastAdvance.rightHandWeight;
496 pose->leftFootAnchor = state->lastAdvance.leftFootAnchor;
497 pose->rightFootAnchor = state->lastAdvance.rightFootAnchor;
498 pose->hasLeftFootAnchor = state->lastAdvance.hasLeftFootAnchor;
499 pose->hasRightFootAnchor = state->lastAdvance.hasRightFootAnchor;
500 pose->leftFootWeight = state->lastAdvance.leftFootWeight;
501 pose->rightFootWeight = state->lastAdvance.rightFootWeight;
502 pose->pelvisWeight = state->lastAdvance.pelvisWeight;
503 pose->compactCollision = state->lastAdvance.compactCollisionActive;
504 auto drained = runtime->drainEvents();
505 if (!drained) return eve::Result<std::size_t>::failure(drained.status());
506 auto replaced = events->replace(drained.value(), tick);
507 if (!replaced) return eve::Result<std::size_t>::failure(replaced.status());
508 ++processed;
509 }
511 return eve::Result<std::size_t>::success(processed);
512 }
513};
514
515} // namespace eve::climbing
std::string selected
eve::EntitySpatialPose pose
Tick-addressed command buffering for deterministic climbing input.
Deterministic climbing/parkour planning and capsule-constrained execution.
#define EVENGINE_API_DOMAINS
Definition Export.h:110
ScriptForceVector acceleration
HexVec3 across
std::array< float, 3 > scale
OceanSprayView view
std::shared_ptr< const OceanSprayFrame > previous
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::vector< particles::ParticleRecordEvent > events
std::string body
std::string filter
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
float phase
SimulationTick tick
float step
Definition TreeMesh.cpp:451
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
Fixed-capacity owning candidate projection written once per PrePhysics probe phase.
Definition ClimbingECS.h:66
void clear() noexcept
Clear derived candidates without affecting runtime state.
Definition ClimbingECS.h:81
eve::SimulationTick tick() const noexcept
Tick that produced the current projection.
Definition ClimbingECS.h:83
std::span< const ClimbingCandidate > values() const noexcept
Return an immutable synchronous view invalidated by the next replace/clear.
Definition ClimbingECS.h:77
Fixed-capacity owning candidate set used by the production probe hot path.
Definition Climbing.h:329
PrePhysics selection/commit consumer over caller-selected domain entities.
static eve::Result< std::size_t > step(physics::World3D &world, ClimbingCommand command, eve::SimulationTick tick)
Consume at most one buffered command and commit one execution per visible entity.
Bounded owning post-simulation event batch safe to dispatch after the ECS View closes.
eve::SimulationTick tick() const noexcept
Simulation tick at which the runtime queue was drained.
std::span< const ClimbingEvent > values() const noexcept
Immutable synchronous event view.
static ClimbingCoyoteState coyoteWindowState(eve::SimulationTick currentTick, eve::SimulationTick lastGroundedTick, std::uint64_t coyoteTicks) noexcept
Evaluate a grounded grace window without reading wall clock.
static std::optional< BufferedClimbingCommand > peek(const ClimbingIntent &intent, ClimbingCommand command, eve::SimulationTick currentTick) noexcept
Observe the oldest eligible command without consuming or pruning intent.
Physics-phase authoritative capsule motion consumer.
static eve::Result< std::size_t > step(physics::World3D &world, const eve::SimulationStep &step, const ClimbingMotionInput &motion={})
Advance active executions and publish the corrected feet transform to Body and linked Physics body.
PostPhysics derived pose and owning event-drain producer.
static eve::Result< std::size_t > step(eve::SimulationTick tick)
Project pose constraints and drain runtime events without invoking external consumers inside the View...
PrePhysics candidate producer over a caller-selected existing domain root.
static eve::Result< std::size_t > step(physics::World3D &world, eve::SimulationTick tick)
Probe every entity in View<EntityRoot, Body, Intent, State, Links, CandidateBuffer>.
Owner-thread climbing planner and executor for one character.
Definition Climbing.h:659
static eve::Result< ClimbingStart > tryStart(ClimbingRuntime &runtime, physics::World3D &world, const ClimbingPose &pose, ClimbingIntent &intent, ClimbingCommand command, eve::SimulationTick tick, eve::SimulationTick lastGroundedTick)
Start the best candidate and consume its input edge exactly once.
static eve::script::Borrowed< ClimbingRuntime > resolve(ClimbingRuntimeHandleRef reference) noexcept
Resolves a live runtime as a non-owning observation.
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
bool activeClimbingPhase(ClimbingPhase phase) noexcept
Active climbing phase.
std::span< const ClimbingSystemContract > climbingSystemContracts() noexcept
Return immutable process-lifetime contracts for the four climbing ECS phases.
ClimbingPhase
Execution lifecycle visible to gameplay and animation adapters.
Definition Climbing.h:470
ClimbingMovementMode
Movement mode used by action source-mode hard validation.
Definition Climbing.h:67
ClimbingCommand
Edge and held commands understood by the climbing input phase.
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
One owning edge command with deterministic lifetime and consumption evidence.
Owning output of one execution tick.
Definition Climbing.h:553
Hot authoritative transient motor component; replicated by value for prediction.
Definition ClimbingECS.h:31
eve::SimulationTick lastOrdinaryJumpPressedTick
Definition ClimbingECS.h:47
ClimbingMovementMode mode
Definition ClimbingECS.h:45
eve::SimulationTick lastGroundedTick
Definition ClimbingECS.h:46
Hot authoritative intent component; contains no device or callback pointers.
Per-tick authored animation motion supplied before climbing warp and collision.
Definition Climbing.h:540
Derived PostPhysics pose projection; gameplay validity never depends on these weights.
Vec3 leftFootAnchor
Transient world-space supported targets copied from the current advance.
Input pose used for one deterministic candidate probe.
Definition Climbing.h:275
Hot authoritative execution component holding the module-owned runtime identity.
Definition ClimbingECS.h:96
ClimbingRuntimeHandleRef runtime
Definition ClimbingECS.h:97
ClimbingAdvance lastAdvance
Definition ClimbingECS.h:98
Static review/tooling description of one concrete climbing ECS phase.
Small owning world-space vector used at climbing module boundaries.
bool started
Definition Graphics.cpp:200