载入中...
搜索中...
未找到
PixelWorldReplay.cpp
浏览该文件的文档.
2
3#include <utility>
4
5#include <algorithm>
6#include <charconv>
7#include <cstddef>
8#include <limits>
9#include <set>
10#include <type_traits>
11
13namespace {
14
15constexpr std::string_view kReplayType = "pixelworld.replay-log";
16constexpr std::uint64_t kReplaySchemaVersion = 2;
17constexpr std::size_t kMaximumReplayEntries = 1'000'000;
18constexpr std::size_t kMaximumReplayCheckpoints = 100'000;
19constexpr std::size_t kMaximumReplayChunkDigests = 1'000'000;
20
21eve::LogicalId replaySchema() {
22 const auto parsed = eve::LogicalId::parse("pixelworld:replay-log");
23 if (!parsed) std::terminate();
24 return *parsed;
25}
26
28 std::initializer_list<std::string_view> fields) {
29 const auto* result = value.getIf<eve::Value::Object>();
30 if (!result || result->size() != fields.size())
32 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "replay object has unknown or missing fields",
33 path, {}, "pixelworld.replay"));
34 for (const auto field : fields)
35 if (!result->contains(std::string(field)))
37 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "replay object has unknown or missing fields",
38 path, {}, "pixelworld.replay"));
40}
41
42eve::Result<std::uint64_t> decimal(const eve::Value& value, std::string path) {
43 const auto* text = value.getIf<std::string>();
44 if (!text)
46 eve::DiagnosticCode::ParseError, "expected decimal string", path, {}, "pixelworld.replay"));
47 std::uint64_t result = 0;
48 const auto [end, error] = std::from_chars(text->data(), text->data() + text->size(), result);
49 if (error != std::errc{} || end != text->data() + text->size())
51 eve::DiagnosticCode::ParseError, "invalid decimal string", path, {}, "pixelworld.replay"));
53}
54
55eve::Result<int> integer(const eve::Value& value, std::string path) {
56 const auto* number = value.getIf<std::int64_t>();
57 if (!number || *number < std::numeric_limits<int>::min() || *number > std::numeric_limits<int>::max())
59 eve::DiagnosticCode::ParseError, "expected in-range integer", std::move(path), {}, "pixelworld.replay"));
60 return eve::Result<int>::success(static_cast<int>(*number));
61}
62
63eve::Value commandValue(const eve::pixelworld::PixelEditCommand& command) {
65 {"centerX", eve::Value(command.centerX)},
66 {"centerY", eve::Value(command.centerY)},
67 {"kind", eve::Value(static_cast<int>(command.kind))},
68 {"material", eve::Value(static_cast<int>(command.material))},
69 {"radius", eve::Value(command.radius)},
70 {"sequence", eve::Value(std::to_string(command.sequence))},
71 {"strength", eve::Value(command.strength)},
72 {"temperatureDelta", eve::Value(int(command.temperatureDelta))},
73 });
74}
75
76eve::Result<eve::pixelworld::PixelEditCommand> parseCommand(const eve::Value& value, const std::string& path) {
77 auto record = object(value, path, {"centerX", "centerY", "kind", "material", "radius", "sequence",
78 "strength", "temperatureDelta"});
81 auto centerX = integer(record.value()->at("centerX"), path + ".centerX");
82 auto centerY = integer(record.value()->at("centerY"), path + ".centerY");
83 auto kind = integer(record.value()->at("kind"), path + ".kind");
84 auto material = integer(record.value()->at("material"), path + ".material");
85 auto radius = integer(record.value()->at("radius"), path + ".radius");
86 auto sequence = decimal(record.value()->at("sequence"), path + ".sequence");
87 auto strength = integer(record.value()->at("strength"), path + ".strength");
88 auto temperature = integer(record.value()->at("temperatureDelta"), path + ".temperatureDelta");
89 if (!centerX || !centerY || !kind || !material || !radius || !sequence || !strength || !temperature)
91 eve::DiagnosticCode::ParseError, "invalid replay command", path, {}, "pixelworld.replay"));
92 if (kind.value() < 0 || kind.value() > static_cast<int>(eve::pixelworld::PixelEditKind::Explosion) ||
93 material.value() < 0 || material.value() > std::numeric_limits<std::uint16_t>::max() ||
94 temperature.value() < std::numeric_limits<std::int16_t>::min() ||
95 temperature.value() > std::numeric_limits<std::int16_t>::max())
97 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "replay command enum or scalar is out of range",
98 path, {}, "pixelworld.replay"));
99 command.sequence = sequence.value();
100 command.kind = static_cast<eve::pixelworld::PixelEditKind>(kind.value());
101 command.centerX = centerX.value();
102 command.centerY = centerY.value();
103 command.radius = radius.value();
104 command.material = static_cast<eve::pixelworld::MaterialId>(material.value());
105 command.strength = strength.value();
106 command.temperatureDelta = static_cast<std::int16_t>(temperature.value());
108}
109
110std::uint64_t hashBytes(std::span<const std::byte> bytes) noexcept {
111 std::uint64_t hash = 1469598103934665603ULL;
112 for (const std::byte value : bytes) {
113 hash ^= std::uint64_t(std::to_integer<std::uint8_t>(value));
114 hash *= 1099511628211ULL;
115 }
116 return hash;
117}
118
119template <class T>
120void hashValue(std::uint64_t& hash, T value) noexcept {
121 static_assert(std::is_integral_v<T>);
122 using Unsigned = std::make_unsigned_t<T>;
123 static_assert(sizeof(Unsigned) <= sizeof(std::uint64_t));
124 std::uint64_t encoded = static_cast<std::uint64_t>(static_cast<Unsigned>(value));
125 for (std::size_t index = 0; index < sizeof(T); ++index) {
126 hash ^= encoded & 0xffULL;
127 hash *= 1099511628211ULL;
128 encoded >>= 8;
129 }
130}
131
132std::uint64_t hashChunk(const eve::pixelworld::PixelChunkSnapshot& chunk) noexcept {
133 std::uint64_t hash = 1469598103934665603ULL;
134 hashValue(hash, std::int32_t(chunk.x));
135 hashValue(hash, std::int32_t(chunk.y));
136 for (const auto cell : chunk.cells) {
137 hashValue(hash, std::uint16_t(cell.material));
138 hashValue(hash, cell.temperature);
139 hashValue(hash, cell.lifetime);
140 hashValue(hash, cell.thermalRemainder);
141 }
142 return hash;
143}
144
146 auto snapshot = world.saveSnapshot();
148 PixelReplayCheckpoint checkpoint;
149 checkpoint.tick = eve::SimulationTick(world.tickValue());
150 checkpoint.revision = world.revision();
151 checkpoint.worldDigest = hashBytes(snapshot.value());
152 for (const auto& chunk : world.snapshotChangedChunks(0))
153 if (!chunk.removed)
154 checkpoint.chunks.push_back({chunk.x, chunk.y, hashChunk(chunk)});
155 return eve::Result<PixelReplayCheckpoint>::success(std::move(checkpoint));
156}
157
158eve::Value replayPayload(const std::vector<PixelReplayEntry>& entries,
159 const std::vector<PixelReplayCheckpoint>& checkpoints) {
160 eve::Value::Array encodedEntries;
161 encodedEntries.reserve(entries.size());
162 for (const auto& entry : entries)
163 encodedEntries.emplace_back(eve::Value::Object{
164 {"command", commandValue(entry.command)},
165 {"tick", eve::Value(std::to_string(entry.tick.value()))},
166 });
167
168 eve::Value::Array encodedCheckpoints;
169 encodedCheckpoints.reserve(checkpoints.size());
170 for (const auto& checkpoint : checkpoints) {
171 eve::Value::Array chunks;
172 chunks.reserve(checkpoint.chunks.size());
173 for (const auto& chunk : checkpoint.chunks)
174 chunks.emplace_back(eve::Value::Object{
175 {"digest", eve::Value(std::to_string(chunk.digest))},
176 {"x", eve::Value(chunk.x)},
177 {"y", eve::Value(chunk.y)},
178 });
179 encodedCheckpoints.emplace_back(eve::Value::Object{
180 {"chunks", eve::Value(std::move(chunks))},
181 {"revision", eve::Value(std::to_string(checkpoint.revision))},
182 {"tick", eve::Value(std::to_string(checkpoint.tick.value()))},
183 {"worldDigest", eve::Value(std::to_string(checkpoint.worldDigest))},
184 });
185 }
187 {"checkpoints", eve::Value(std::move(encodedCheckpoints))},
188 {"entries", eve::Value(std::move(encodedEntries))},
189 });
190}
191
192PixelReplayDivergence compare(const PixelReplayCheckpoint& expected,
193 const PixelReplayCheckpoint& actual) {
194 PixelReplayDivergence divergence;
195 divergence.tick = expected.tick;
196 divergence.expectedRevision = expected.revision;
197 divergence.actualRevision = actual.revision;
198 const std::size_t count = std::max(expected.chunks.size(), actual.chunks.size());
199 for (std::size_t index = 0; index < count; ++index) {
200 const bool expectedPresent = index < expected.chunks.size();
201 const bool actualPresent = index < actual.chunks.size();
202 if (expectedPresent && actualPresent && expected.chunks[index] == actual.chunks[index]) continue;
203 if (expectedPresent) divergence.expectedChunk = expected.chunks[index];
204 if (actualPresent) divergence.actualChunk = actual.chunks[index];
205 break;
206 }
207 return divergence;
208}
209
210} // namespace
211
212eve::Result<void> PixelReplayLog::append(PixelReplayEntry entry) {
213 if (entry.tick.value() == 0)
215 eve::DiagnosticCode::InvalidArgument, "replay command Tick must be positive",
216 "tick", {}, "pixelworld.replay"));
217 if (!entries_.empty() && entry.tick.value() < entries_.back().tick.value())
219 eve::DiagnosticCode::PreconditionViolation, "replay command Ticks must be nondecreasing",
220 "tick", {}, "pixelworld.replay"));
221 const std::uint64_t expectedSequence = entries_.empty() ? 1 : entries_.back().command.sequence + 1;
222 if (entry.command.sequence != expectedSequence)
224 eve::DiagnosticCode::PreconditionViolation, "replay edit sequence must be contiguous",
225 "command.sequence", {}, "pixelworld.replay"));
226 entries_.push_back(std::move(entry));
228}
229
230eve::Result<void> PixelReplayLog::captureCheckpoint(const eve::pixelworld::PixelWorld& world) {
231 if (!checkpoints_.empty() && world.tickValue() <= checkpoints_.back().tick.value())
233 eve::DiagnosticCode::PreconditionViolation, "checkpoint Tick must increase",
234 "tick", {}, "pixelworld.replay"));
235 auto checkpoint = checkpointFor(world);
236 if (!checkpoint.ok()) return eve::Result<void>::failure(checkpoint.status());
237 checkpoints_.push_back(std::move(checkpoint).value());
239}
240
241eve::Result<PixelReplayReceipt> PixelReplayLog::replay(
243 if (throughTick.value() == 0 || target.tickValue() != 0 || target.chunkCount() != 0 ||
244 target.lastEditSequence() != 0)
247 "replay requires a positive target Tick and an empty target world",
248 "target", {}, "pixelworld.replay"));
249 if ((!entries_.empty() && entries_.back().tick.value() > throughTick.value()) ||
250 (!checkpoints_.empty() && checkpoints_.back().tick.value() > throughTick.value()))
252 eve::DiagnosticCode::InvalidArgument, "throughTick does not cover the complete log",
253 "throughTick", {}, "pixelworld.replay"));
254
255 PixelReplayReceipt receipt;
256 std::size_t entryIndex = 0;
257 std::size_t checkpointIndex = 0;
258 for (std::uint64_t tick = 1; tick <= throughTick.value(); ++tick) {
259 while (entryIndex < entries_.size() && entries_[entryIndex].tick.value() == tick) {
260 auto applied = target.applyEdit(entries_[entryIndex].command);
261 if (!applied.ok()) return eve::Result<PixelReplayReceipt>::failure(applied.status());
262 ++entryIndex;
263 ++receipt.commandsApplied;
264 }
265 auto advanced = target.advance(eve::SimulationTick(tick));
266 if (!advanced.ok()) return eve::Result<PixelReplayReceipt>::failure(advanced.status());
268 if (checkpointIndex < checkpoints_.size() && checkpoints_[checkpointIndex].tick.value() == tick) {
269 auto actual = checkpointFor(target);
270 if (!actual.ok()) return eve::Result<PixelReplayReceipt>::failure(actual.status());
271 const auto& expected = checkpoints_[checkpointIndex];
272 if (actual.value().worldDigest != expected.worldDigest) {
273 receipt.match = PixelReplayMatch::Diverged;
274 receipt.firstDivergence = compare(expected, actual.value());
275 return eve::Result<PixelReplayReceipt>::success(std::move(receipt));
276 }
277 ++checkpointIndex;
278 }
279 }
280 return eve::Result<PixelReplayReceipt>::success(std::move(receipt));
281}
282
283eve::Result<eve::SnapshotEnvelope> PixelReplayLog::snapshot(
284 eve::PersistentId instanceId, const eve::SnapshotHashProvider& hashProvider) const {
285 const std::uint64_t entryTick = entries_.empty() ? 0 : entries_.back().tick.value();
286 const std::uint64_t checkpointTick = checkpoints_.empty() ? 0 : checkpoints_.back().tick.value();
288 std::string(kReplayType), replaySchema(), eve::SchemaVersion(kReplaySchemaVersion), instanceId,
289 eve::Revision(entries_.size() + checkpoints_.size()),
290 eve::SimulationTick(std::max(entryTick, checkpointTick)), replayPayload(entries_, checkpoints_),
291 hashProvider);
292}
293
294eve::Result<void> PixelReplayLog::restoreSnapshot(
295 const eve::SnapshotEnvelope& snapshot, const eve::SnapshotHashProvider& hashProvider) {
296 auto verified = eve::verifySnapshotEnvelope(snapshot, hashProvider);
297 if (!verified) return verified;
298 if (snapshot.type != kReplayType || snapshot.schema != replaySchema())
300 "replay snapshot type or schema does not match",
301 "schema", {}, "pixelworld.replay"));
302 if (snapshot.schemaVersion.value() < 1 || snapshot.schemaVersion.value() > kReplaySchemaVersion)
304 "unsupported replay snapshot schema version",
305 "schemaVersion", {}, "pixelworld.replay"));
306
307 auto root = object(snapshot.payload, "payload", {"checkpoints", "entries"});
308 if (!root) return eve::Result<void>::failure(root.status());
309 const auto* encodedEntries = root.value()->at("entries").getIf<eve::Value::Array>();
310 const auto* encodedCheckpoints = root.value()->at("checkpoints").getIf<eve::Value::Array>();
311 if (!encodedEntries || !encodedCheckpoints || encodedEntries->size() > kMaximumReplayEntries ||
312 encodedCheckpoints->size() > kMaximumReplayCheckpoints)
314 "replay arrays are invalid or exceed decode budget",
315 "payload", {}, "pixelworld.replay"));
316
317 PixelReplayLog candidate;
318 for (std::size_t index = 0; index < encodedEntries->size(); ++index) {
319 const std::string path = "payload.entries[" + std::to_string(index) + "]";
320 auto record = object((*encodedEntries)[index], path, {"command", "tick"});
321 if (!record) return eve::Result<void>::failure(record.status());
322 auto tick = decimal(record.value()->at("tick"), path + ".tick");
323 auto command = parseCommand(record.value()->at("command"), path + ".command");
324 if (!tick || !command)
326 eve::DiagnosticCode::ParseError, "invalid replay entry", path, {}, "pixelworld.replay"));
327 auto appended = candidate.append({eve::SimulationTick(tick.value()), std::move(command).value()});
328 if (!appended) return appended;
329 }
330
331 std::size_t totalChunks = 0;
332 std::uint64_t previousCheckpointTick = 0;
333 for (std::size_t index = 0; index < encodedCheckpoints->size(); ++index) {
334 const std::string path = "payload.checkpoints[" + std::to_string(index) + "]";
335 const bool versionOne = snapshot.schemaVersion.value() == 1;
336 auto record = versionOne
337 ? object((*encodedCheckpoints)[index], path, {"revision", "tick", "worldDigest"})
338 : object((*encodedCheckpoints)[index], path,
339 {"chunks", "revision", "tick", "worldDigest"});
340 if (!record) return eve::Result<void>::failure(record.status());
341 auto tick = decimal(record.value()->at("tick"), path + ".tick");
342 auto revision = decimal(record.value()->at("revision"), path + ".revision");
343 auto worldDigest = decimal(record.value()->at("worldDigest"), path + ".worldDigest");
344 if (!tick || !revision || !worldDigest || tick.value() == 0 || tick.value() <= previousCheckpointTick)
346 eve::DiagnosticCode::ParseError, "invalid replay checkpoint", path, {}, "pixelworld.replay"));
347 PixelReplayCheckpoint checkpoint;
348 checkpoint.tick = eve::SimulationTick(tick.value());
349 checkpoint.revision = revision.value();
350 checkpoint.worldDigest = worldDigest.value();
351
352 if (!versionOne) {
353 const auto* chunks = record.value()->at("chunks").getIf<eve::Value::Array>();
354 if (!chunks || chunks->size() > kMaximumReplayChunkDigests - totalChunks)
356 "replay Chunk digests exceed decode budget",
357 path + ".chunks", {}, "pixelworld.replay"));
358 totalChunks += chunks->size();
359 for (std::size_t chunkIndex = 0; chunkIndex < chunks->size(); ++chunkIndex) {
360 const std::string chunkPath = path + ".chunks[" + std::to_string(chunkIndex) + "]";
361 auto chunk = object((*chunks)[chunkIndex], chunkPath, {"digest", "x", "y"});
362 if (!chunk) return eve::Result<void>::failure(chunk.status());
363 auto x = integer(chunk.value()->at("x"), chunkPath + ".x");
364 auto y = integer(chunk.value()->at("y"), chunkPath + ".y");
365 auto digest = decimal(chunk.value()->at("digest"), chunkPath + ".digest");
366 if (!x || !y || !digest)
368 "invalid replay Chunk digest", chunkPath,
369 {}, "pixelworld.replay"));
370 PixelChunkDigest decoded{x.value(), y.value(), digest.value()};
371 if (!checkpoint.chunks.empty()) {
372 const auto& prior = checkpoint.chunks.back();
373 if (decoded.y < prior.y || (decoded.y == prior.y && decoded.x <= prior.x))
375 eve::DiagnosticCode::ParseError, "replay Chunk digests must be unique canonical order",
376 chunkPath, {}, "pixelworld.replay"));
377 }
378 checkpoint.chunks.push_back(decoded);
379 }
380 }
381 previousCheckpointTick = tick.value();
382 candidate.checkpoints_.push_back(std::move(checkpoint));
383 }
384
385 const std::uint64_t entryTick = candidate.entries_.empty() ? 0 : candidate.entries_.back().tick.value();
386 const std::uint64_t checkpointTick = candidate.checkpoints_.empty()
387 ? 0
388 : candidate.checkpoints_.back().tick.value();
389 if (snapshot.revision.value() != candidate.entries_.size() + candidate.checkpoints_.size() ||
390 snapshot.tick.value() != std::max(entryTick, checkpointTick))
392 eve::DiagnosticCode::Conflict, "replay payload count or Tick disagrees with envelope metadata", "payload",
393 {}, "pixelworld.replay"));
394
395 entries_ = std::move(candidate.entries_);
396 checkpoints_ = std::move(candidate.checkpoints_);
398}
399
400} // namespace eve::pixelworld_replay
double y
double x
LogicalId target
int root
Definition AnimSmr.cpp:119
std::uint64_t revision
std::unordered_map< std::string, QuestRuntime > entries
bool applied
ScriptComponentRecord record
Definition ECS.cpp:228
std::vector< std::string > fields
Definition ECS.cpp:42
int instanceId
float strength
float temperature
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::uint64_t bytes
double radius
Definition MeleeHit.cpp:42
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
std::string error
Definition Package.cpp:174
std::array< uint32_t, 16 > material
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
std::string hash
double number
std::string text
size_t end
std::string kind
std::string digest
int count
Cell cell
SimulationTick tick
Json object
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
Id128 public API.
Definition Identity.h:111
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
Sparse, chunked, deterministic 2D falling-material world.
Definition PixelWorld.h:224
Owning command log and periodic checkpoint projection for PixelWorld.
eve::Result< void > append(PixelReplayEntry entry)
Append the next sequenced command; Tick order must be nondecreasing.
MaterialId
Compact stable material identifier stored in each authoritative cell.
PixelEditKind
Canonical deterministic edit operation admitted at a Tick boundary.
Definition PixelWorld.h:148
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
Result< SnapshotEnvelope > makeSnapshotEnvelope(std::string type, LogicalId schema, SchemaVersion schemaVersion, PersistentId instanceId, Revision revision, SimulationTick tick, Value payload, const SnapshotHashProvider &hashProvider)
Construct and seal a snapshot envelope.
Definition Snapshot.cpp:103
Result< void > verifySnapshotEnvelope(const SnapshotEnvelope &snapshot, const SnapshotHashProvider &hashProvider)
Verify an envelope's content hash without modifying it.
Definition Snapshot.cpp:63
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
Owning, immutable projection of one authoritative simulation chunk.
Definition PixelWorld.h:77
std::vector< PixelCell > cells
Definition PixelWorld.h:82
Owning replayable edit command. Sequence must be exactly previous + 1.
Definition PixelWorld.h:155
Canonical content digest for one authoritative PixelWorld Chunk.
Periodic replay checkpoint containing world and per-Chunk diagnostics.
One deterministic edit admitted immediately before its simulation Tick.
eve::pixelworld::PixelEditCommand command
Receipt from deterministic replay through an exact target Tick.
std::optional< PixelReplayDivergence > firstDivergence