载入中...
搜索中...
未找到
Time.cpp
浏览该文件的文档.
1#include "common/Time.h"
2#include "common/Assert.h"
3
4#include <cmath>
5#include <limits>
6#include <utility>
7
8namespace eve {
9namespace {
10
11Diagnostic invalidTime(std::string message) {
13}
14
15} // namespace
16
18 if (!std::isfinite(seconds)) return Result<Duration>::failure(invalidTime("duration seconds must be finite"));
19
20 const long double nanoseconds = static_cast<long double>(seconds) * 1000000000.0L;
21 constexpr long double minimum = static_cast<long double>(std::numeric_limits<std::int64_t>::min());
22 constexpr long double maximum = static_cast<long double>(std::numeric_limits<std::int64_t>::max());
23 if (nanoseconds < minimum || nanoseconds > maximum)
24 return Result<Duration>::failure(invalidTime("duration seconds are out of range"));
25
26 return Result<Duration>::success(Duration(static_cast<std::int64_t>(std::round(nanoseconds))));
27}
28
29double Duration::seconds() const noexcept { return static_cast<double>(nanoseconds_) / 1000000000.0; }
30
32 if ((other.nanoseconds_ > 0 && nanoseconds_ > std::numeric_limits<std::int64_t>::max() - other.nanoseconds_) ||
33 (other.nanoseconds_ < 0 && nanoseconds_ < std::numeric_limits<std::int64_t>::min() - other.nanoseconds_))
34 return Result<Duration>::failure(invalidTime("duration addition overflow"));
35 return Result<Duration>::success(Duration(nanoseconds_ + other.nanoseconds_));
36}
37
39 if (!std::isfinite(rate) || rate < 0.0)
40 return Result<Duration>::failure(invalidTime("duration rate must be finite and non-negative"));
41 const long double nanoseconds = static_cast<long double>(nanoseconds_) * static_cast<long double>(rate);
42 constexpr long double minimum = static_cast<long double>(std::numeric_limits<std::int64_t>::min());
43 constexpr long double maximum = static_cast<long double>(std::numeric_limits<std::int64_t>::max());
44 if (nanoseconds < minimum || nanoseconds > maximum)
45 return Result<Duration>::failure(invalidTime("scaled duration is out of range"));
46 return Result<Duration>::success(Duration(static_cast<std::int64_t>(std::round(nanoseconds))));
47}
48
50 if (nanoseconds_ < earlier.nanoseconds_)
52 Diagnostic::error(DiagnosticCode::PreconditionViolation, "monotonic source moved backwards"));
53
54 // Subtract in the unsigned domain after the ordering check. The modulo
55 // subtraction is the exact distance for two ordered int64 values, while
56 // the explicit bound check prevents converting a distance larger than the
57 // Duration domain back to int64_t.
58 const std::uint64_t distance =
59 static_cast<std::uint64_t>(nanoseconds_) - static_cast<std::uint64_t>(earlier.nanoseconds_);
60 if (distance > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))
62 "monotonic timestamp distance exceeds Duration range"));
63 return Result<Duration>::success(Duration(static_cast<std::int64_t>(distance)));
64}
65
66SimulationClock::SimulationClock(ITimeSource& source, Duration fixedStep) : source_(source), fixedStep_(fixedStep) {
67 EV_ASSERT(fixedStep_.nanoseconds() > 0, "SimulationClock fixed step must be positive");
68 if (fixedStep_.nanoseconds() <= 0) fixedStep_ = Duration::fromNanoseconds(16666667);
69}
70
72 if (fixedStep.nanoseconds() <= 0)
73 return Result<void>::failure(invalidTime("fixed simulation step must be positive"));
74 fixedStep_ = fixedStep;
75 return Result<void>::success();
76}
77
79 if (!std::isfinite(rate) || rate < 0.0)
80 return Result<void>::failure(invalidTime("simulation rate must be finite and non-negative"));
81 rate_ = rate;
82 return Result<void>::success();
83}
84
86 if (realDelta.nanoseconds() < 0)
88 invalidTime("simulation frame duration must be non-negative"));
89
90 auto nextFrame = frame_.incremented();
91 if (!nextFrame)
93 Diagnostic::error(DiagnosticCode::InvariantViolation, "simulation frame index overflow"));
94
95 auto scaled = realDelta.scaled(rate_);
96 if (!scaled) return Result<std::vector<SimulationStep>>::failure(scaled.status());
97 const Duration scaledDelta = std::move(scaled).takeValue();
98
99 if (paused_) {
100 frame_ = *nextFrame;
101 lastFrameDelta_ = realDelta;
102 return Result<std::vector<SimulationStep>>::success({});
103 }
104
105 auto total = accumulator_.tryAdd(scaledDelta);
106 if (!total) return Result<std::vector<SimulationStep>>::failure(total.status());
107 const std::int64_t accumulated = std::move(total).takeValue().nanoseconds();
108 const std::uint64_t accumulatedUnsigned = static_cast<std::uint64_t>(accumulated);
109 const std::uint64_t fixedStepUnsigned = static_cast<std::uint64_t>(fixedStep_.nanoseconds());
110 const std::uint64_t stepCount = accumulatedUnsigned / fixedStepUnsigned;
111 if (stepCount > std::numeric_limits<std::size_t>::max() ||
112 stepCount > std::numeric_limits<std::uint64_t>::max() - tick_.value())
113 return Result<std::vector<SimulationStep>>::failure(
114 Diagnostic::error(DiagnosticCode::InvariantViolation, "simulation step count overflow"));
115
116 // Avoid an unbounded allocation when a stalled frame or a malicious
117 // replay requests more catch-up steps than one result can safely own.
118 constexpr std::uint64_t maxStepsPerAdvance = 1000000;
119 if (stepCount > maxStepsPerAdvance)
120 return Result<std::vector<SimulationStep>>::failure(
121 Diagnostic::error(DiagnosticCode::InvariantViolation, "simulation catch-up step limit exceeded"));
122 if (stepCount > std::numeric_limits<std::uint64_t>::max() / fixedStepUnsigned)
123 return Result<std::vector<SimulationStep>>::failure(
124 Diagnostic::error(DiagnosticCode::InvariantViolation, "simulation duration multiplication overflow"));
125 const std::uint64_t consumedUnsigned = stepCount * fixedStepUnsigned;
126 const std::uint64_t remainderUnsigned = accumulatedUnsigned - consumedUnsigned;
127 if (remainderUnsigned > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))
128 return Result<std::vector<SimulationStep>>::failure(
129 Diagnostic::error(DiagnosticCode::InvariantViolation, "simulation remainder exceeds Duration range"));
130
131 std::vector<SimulationStep> steps;
132 steps.reserve(static_cast<std::size_t>(stepCount));
133 for (std::uint64_t i = 0; i < stepCount; ++i) steps.push_back({SimulationTick(tick_.value() + i + 1), fixedStep_});
134
135 tick_ = SimulationTick(tick_.value() + stepCount);
136 accumulator_ = Duration(static_cast<std::int64_t>(remainderUnsigned));
137 frame_ = *nextFrame;
138 lastFrameDelta_ = realDelta;
139 return Result<std::vector<SimulationStep>>::success(std::move(steps));
140}
141
143 const MonotonicTimestamp now = source_.monotonicNow();
144 if (!previousSourceTime_) {
145 auto first = advance(Duration::zero());
146 if (!first) return first;
147 previousSourceTime_ = now;
148 return first;
149 }
150
151 auto elapsed = now.since(*previousSourceTime_);
152 if (!elapsed) return Result<std::vector<SimulationStep>>::failure(elapsed.status());
153 Duration delta = std::move(elapsed).takeValue();
154 auto result = advance(delta);
155 if (!result) return result;
156 previousSourceTime_ = now;
157 return result;
158}
159
161 tick_ = tick;
162 frame_ = FrameIndex::zero();
163 accumulator_ = Duration::zero();
164 lastFrameDelta_ = Duration::zero();
165 previousSourceTime_.reset();
166}
167
168} // namespace eve
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
std::string message
float maximum[3]
float minimum[3]
std::int32_t first
Poco::JSON::Object::Ptr result
float distance
int steps
std::string_view source
SimulationTick tick
Common time values and an injectable deterministic simulation clock.
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
constexpr std::int64_t nanoseconds() const noexcept
Return the exact signed nanosecond representation.
Definition Time.h:69
Result< Duration > tryAdd(Duration other) const
Add two durations with overflow validation.
Definition Time.cpp:31
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
static constexpr Duration fromNanoseconds(std::int64_t nanoseconds) noexcept
Construct an exact duration from nanoseconds.
Definition Time.h:55
constexpr Duration() noexcept=default
Construct a zero duration.
static constexpr Duration zero() noexcept
Return zero duration.
Definition Time.h:60
double seconds() const noexcept
Return this duration as seconds for legacy/presentation APIs.
Definition Time.cpp:29
Result< Duration > scaled(double rate) const
Scale a duration by a finite non-negative rate.
Definition Time.cpp:38
Injectable source for elapsed and metadata time.
Definition Time.h:173
virtual MonotonicTimestamp monotonicNow() const =0
Read the non-decreasing source-relative timestamp.
Timestamp from a monotonic source.
Definition Time.h:104
Result< Duration > since(MonotonicTimestamp earlier) const
Compute elapsed duration from an earlier timestamp.
Definition Time.cpp:49
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
double rate() const noexcept
Current slow-motion rate.
Definition Time.h:237
Result< void > setRate(double rate)
Set a finite non-negative simulation rate (1 is normal speed).
Definition Time.cpp:78
void reset(SimulationTick tick=SimulationTick::zero()) noexcept
Reset deterministic state to a supplied tick without reading a clock.
Definition Time.cpp:160
Duration fixedStep() const noexcept
Fixed duration of emitted simulation steps.
Definition Time.h:235
Result< std::vector< SimulationStep > > advance(Duration realDelta)
Advance from supplied monotonic elapsed duration without reading a clock.
Definition Time.cpp:85
Result< std::vector< SimulationStep > > sample()
Read the source and emit deterministic steps for one frame.
Definition Time.cpp:142
SimulationClock(ITimeSource &source, Duration fixedStep=Duration::fromNanoseconds(16666667))
Construct a fixed-step clock without reading the source.
Definition Time.cpp:66
Result< void > setFixedStep(Duration fixedStep)
Set the positive fixed-step duration; accumulated time is preserved.
Definition Time.cpp:71
constexpr std::optional< StrongUint64 > incremented() const noexcept
Returns the next value, or empty instead of unsigned wraparound.
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.
eve::Diagnostic Diagnostic
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31