载入中...
搜索中...
未找到
PixelWorldArchive.cpp
浏览该文件的文档.
2
3#include <utility>
4
6
7#include <algorithm>
8#include <bit>
9#include <charconv>
10#include <limits>
11#include <string>
12#include <type_traits>
13
15namespace {
16
17constexpr std::string_view kArchiveType = "pixelworld.chunk-batch";
18constexpr std::uint64_t kArchiveVersion = 3;
19constexpr std::size_t kMaximumArchiveChunks = 65'536;
20constexpr std::uint64_t kMaximumDecodedBytes = 512ULL * 1024ULL * 1024ULL;
21constexpr std::size_t kLegacyDecodedChunkBytes =
23constexpr std::size_t kDecodedChunkBytes =
25
26eve::LogicalId archiveSchema() {
27 const auto parsed = eve::LogicalId::parse("pixelworld:chunk-batch");
28 if (!parsed) std::terminate();
29 return *parsed;
30}
31
35}
36
37std::string hex(std::span<const std::uint8_t> bytes) {
38 static constexpr char digits[] = "0123456789abcdef";
39 std::string result(bytes.size() * 2, '0');
40 for (std::size_t index = 0; index < bytes.size(); ++index) {
41 result[index * 2] = digits[bytes[index] >> 4];
42 result[index * 2 + 1] = digits[bytes[index] & 0xf];
43 }
44 return result;
45}
46
47eve::Result<std::vector<std::uint8_t>> unhex(const eve::Value& value, std::size_t maximumBytes,
48 std::string path) {
49 const auto* text = value.getIf<std::string>();
50 if (!text || text->size() % 2 != 0 || text->size() / 2 > maximumBytes)
51 return eve::Result<std::vector<std::uint8_t>>::failure(
52 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "invalid or oversized hexadecimal payload",
53 path, {}, "pixelworld.chunk-archive"));
54 const auto nibble = [](char value) -> int {
55 if (value >= '0' && value <= '9') return value - '0';
56 if (value >= 'a' && value <= 'f') return value - 'a' + 10;
57 return -1;
58 };
59 std::vector<std::uint8_t> result(text->size() / 2);
60 for (std::size_t index = 0; index < result.size(); ++index) {
61 const int high = nibble((*text)[index * 2]);
62 const int low = nibble((*text)[index * 2 + 1]);
63 if (high < 0 || low < 0)
66 {}, "pixelworld.chunk-archive"));
67 result[index] = std::uint8_t((high << 4) | low);
68 }
69 return eve::Result<std::vector<std::uint8_t>>::success(std::move(result));
70}
71
72template <class T>
73void put(std::vector<std::uint8_t>& bytes, T value) {
74 using Unsigned = std::make_unsigned_t<T>;
75 std::uint64_t encoded = static_cast<std::uint64_t>(static_cast<Unsigned>(value));
76 for (std::size_t index = 0; index < sizeof(T); ++index) {
77 bytes.push_back(std::uint8_t(encoded & 0xff));
78 encoded >>= 8;
79 }
80}
81
82template <class T>
83T take(std::span<const std::uint8_t> bytes, std::size_t& cursor) {
84 using Unsigned = std::make_unsigned_t<T>;
85 Unsigned encoded = 0;
86 for (std::size_t index = 0; index < sizeof(T); ++index)
87 encoded |= Unsigned(bytes[cursor++]) << (index * 8);
88 if constexpr (std::is_signed_v<T>) return std::bit_cast<T>(encoded);
89 return encoded;
90}
91
92std::vector<std::uint8_t> encodeCells(const eve::pixelworld::PixelChunkSnapshot& chunk) {
93 std::vector<std::uint8_t> result;
94 result.reserve(kDecodedChunkBytes);
95 for (const auto cell : chunk.cells) {
96 put(result, std::uint16_t(cell.material));
97 put(result, cell.temperature);
98 put(result, cell.lifetime);
99 put(result, cell.thermalRemainder);
100 }
101 return result;
102}
103
105 std::initializer_list<std::string_view> fields) {
106 const auto* result = value.getIf<eve::Value::Object>();
107 if (!result || result->size() != fields.size())
109 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "archive object has unknown or missing fields",
110 path, {}, "pixelworld.chunk-archive"));
111 for (const auto field : fields)
112 if (!result->contains(std::string(field)))
114 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "archive object has unknown or missing fields",
115 path, {}, "pixelworld.chunk-archive"));
117}
118
119eve::Result<std::uint64_t> decimal(const eve::Value& value, std::string path) {
120 const auto* text = value.getIf<std::string>();
121 if (!text)
123 eve::DiagnosticCode::ParseError, "expected decimal string", path, {}, "pixelworld.chunk-archive"));
124 std::uint64_t result = 0;
125 const auto [end, error] = std::from_chars(text->data(), text->data() + text->size(), result);
126 if (error != std::errc{} || end != text->data() + text->size())
128 "invalid decimal string", path, {},
129 "pixelworld.chunk-archive"));
131}
132
133eve::Result<int> integer(const eve::Value& value, std::string path) {
134 const auto* number = value.getIf<std::int64_t>();
135 if (!number || *number < std::numeric_limits<int>::min() || *number > std::numeric_limits<int>::max())
137 "expected in-range integer", std::move(path), {},
138 "pixelworld.chunk-archive"));
139 return eve::Result<int>::success(int(*number));
140}
141
142eve::Result<eve::ContentId> digest(const std::vector<std::uint8_t>& decoded,
143 const eve::SnapshotHashProvider& hashProvider) {
144 if (!hashProvider)
146 eve::DiagnosticCode::Unsupported, "archive hash provider is required", {}, {}, "pixelworld.chunk-archive"));
147 return hashProvider(hex(decoded));
148}
149
150} // namespace
151
154 PixelChunkArchiveCodec codec, const eve::SnapshotHashProvider& hashProvider) {
157 eve::DiagnosticCode::Unsupported, "unknown Chunk archive codec", {}, {}, "pixelworld.chunk-archive"));
158 if (batch.chunks.size() > kMaximumArchiveChunks)
160 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "Chunk archive exceeds record budget",
161 "chunks", {}, "pixelworld.chunk-archive"));
162 eve::Value::Array records;
163 std::optional<std::pair<int, int>> previous;
164 for (const auto& chunk : batch.chunks) {
165 const std::pair<int, int> key{chunk.y, chunk.x};
166 if (previous && !(previous.value() < key))
168 eve::DiagnosticCode::InvalidArgument, "Chunks must be unique canonical y/x order", "chunks", {},
169 "pixelworld.chunk-archive"));
170 previous = key;
171 if (chunk.revision == 0 || chunk.revision > batch.sourceRevision ||
172 (chunk.removed && !chunk.cells.empty()) ||
173 (!chunk.removed && chunk.cells.size() !=
176 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "invalid Chunk revision or cell shape",
177 "chunks", {}, "pixelworld.chunk-archive"));
178 const auto decoded = chunk.removed ? std::vector<std::uint8_t>{} : encodeCells(chunk);
179 auto contentHash = digest(decoded, hashProvider);
180 if (!contentHash) return eve::Result<eve::SnapshotEnvelope>::failure(contentHash.status());
181 const auto physical = chunk.removed ? PixelChunkArchiveCodec::None : codec;
182 auto stored = eve::asset::compressEvpackChunk(assetCodec(physical), decoded);
184 records.emplace_back(eve::Value::Object{
185 {"codec", eve::Value(int(physical))},
186 {"contentHash", eve::Value(contentHash.value().format())},
187 {"decodedSize", eve::Value(std::to_string(decoded.size()))},
188 {"removed", eve::Value(chunk.removed)},
189 {"revision", eve::Value(std::to_string(chunk.revision))},
190 {"stored", eve::Value(hex(stored.value()))},
191 {"x", eve::Value(chunk.x)},
192 {"y", eve::Value(chunk.y)},
193 });
194 }
196 {"catalogFingerprint", eve::Value(std::to_string(batch.catalogFingerprint))},
197 {"chunks", eve::Value(std::move(records))},
198 {"fullResync", eve::Value(batch.fullResync)},
199 {"sourceLastEditSequence", eve::Value(std::to_string(batch.sourceLastEditSequence))},
200 {"sourceSeed", eve::Value(std::to_string(batch.sourceSeed))},
201 });
202 return eve::makeSnapshotEnvelope(std::string(kArchiveType), archiveSchema(),
203 eve::SchemaVersion(kArchiveVersion), instanceId,
205 std::move(payload), hashProvider);
206}
207
209 const eve::SnapshotEnvelope& snapshot, const eve::SnapshotHashProvider& hashProvider) {
210 auto verified = eve::verifySnapshotEnvelope(snapshot, hashProvider);
211 if (!verified) return eve::Result<eve::pixelworld::PixelChunkBatch>::failure(verified.status());
212 if (snapshot.type != kArchiveType || snapshot.schema != archiveSchema())
214 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "Chunk archive type or schema does not match",
215 "schema", {}, "pixelworld.chunk-archive"));
216 if (snapshot.schemaVersion.value() < 1 || snapshot.schemaVersion.value() > kArchiveVersion)
218 eve::Diagnostic::error(eve::DiagnosticCode::UnknownVersion, "unsupported Chunk archive version",
219 "schemaVersion", {}, "pixelworld.chunk-archive"));
220 const bool versionOne = snapshot.schemaVersion.value() == 1;
221 const bool versionTwo = snapshot.schemaVersion.value() == 2;
222 auto root = versionOne
223 ? object(snapshot.payload, "payload", {"catalogFingerprint", "chunks", "sourceSeed"})
224 : versionTwo
225 ? object(snapshot.payload, "payload", {"catalogFingerprint", "chunks",
226 "sourceLastEditSequence", "sourceSeed"})
227 : object(snapshot.payload, "payload", {"catalogFingerprint", "chunks",
228 "fullResync", "sourceLastEditSequence",
229 "sourceSeed"});
231 auto catalog = decimal(root.value()->at("catalogFingerprint"), "payload.catalogFingerprint");
232 auto seed = decimal(root.value()->at("sourceSeed"), "payload.sourceSeed");
233 auto sequence = versionOne
235 : decimal(root.value()->at("sourceLastEditSequence"),
236 "payload.sourceLastEditSequence");
237 const auto* records = root.value()->at("chunks").getIf<eve::Value::Array>();
238 if (!catalog || !seed || !sequence || !records || records->size() > kMaximumArchiveChunks)
240 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "invalid Chunk archive payload", "payload", {},
241 "pixelworld.chunk-archive"));
242
244 batch.catalogFingerprint = catalog.value();
245 batch.sourceSeed = seed.value();
246 batch.sourceRevision = snapshot.revision.value();
247 batch.sourceTick = snapshot.tick;
248 batch.sourceLastEditSequence = sequence.value();
249 if (!versionOne && !versionTwo) {
250 const auto* fullResync = root.value()->at("fullResync").getIf<bool>();
251 if (!fullResync)
253 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "invalid fullResync flag", "payload.fullResync",
254 {}, "pixelworld.chunk-archive"));
255 batch.fullResync = *fullResync;
256 }
257 std::optional<std::pair<int, int>> previous;
258 std::uint64_t decodedTotal = 0;
259 for (std::size_t index = 0; index < records->size(); ++index) {
260 const std::string path = "payload.chunks[" + std::to_string(index) + "]";
261 auto record = object((*records)[index], path,
262 {"codec", "contentHash", "decodedSize", "removed", "revision",
263 "stored", "x", "y"});
265 auto x = integer(record.value()->at("x"), path + ".x");
266 auto y = integer(record.value()->at("y"), path + ".y");
267 auto revision = decimal(record.value()->at("revision"), path + ".revision");
268 auto decodedSize = decimal(record.value()->at("decodedSize"), path + ".decodedSize");
269 const auto* removed = record.value()->at("removed").getIf<bool>();
270 auto codecValue = integer(record.value()->at("codec"), path + ".codec");
271 const auto* hashText = record.value()->at("contentHash").getIf<std::string>();
272 if (!x || !y || !revision || !decodedSize || !removed || !codecValue || !hashText ||
273 revision.value() == 0 || revision.value() > batch.sourceRevision ||
274 codecValue.value() < 0 || codecValue.value() > int(PixelChunkArchiveCodec::Zstd))
276 eve::DiagnosticCode::ParseError, "invalid Chunk archive record", path, {}, "pixelworld.chunk-archive"));
277 const std::pair<int, int> key{y.value(), x.value()};
278 if (previous && !(previous.value() < key))
280 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "Chunk records are not canonical", path, {},
281 "pixelworld.chunk-archive"));
282 previous = key;
283 const bool currentCells = decodedSize.value() == kDecodedChunkBytes;
284 const bool legacyCells = decodedSize.value() == kLegacyDecodedChunkBytes;
285 const std::uint64_t expectedSize = *removed ? 0 : decodedSize.value();
286 if ((!*removed && !currentCells && !legacyCells) || (*removed && decodedSize.value() != 0) ||
287 decodedTotal > kMaximumDecodedBytes - expectedSize)
289 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "Chunk decoded size exceeds budget", path, {},
290 "pixelworld.chunk-archive"));
291 decodedTotal += expectedSize;
292 auto stored = unhex(record.value()->at("stored"), kDecodedChunkBytes + 1024, path + ".stored");
294 const auto codec = static_cast<PixelChunkArchiveCodec>(codecValue.value());
295 if (*removed && (codec != PixelChunkArchiveCodec::None || !stored.value().empty()))
297 eve::DiagnosticCode::ParseError, "removed Chunk must have empty uncompressed payload", path, {},
298 "pixelworld.chunk-archive"));
299 auto decoded = eve::asset::decompressEvpackChunk(assetCodec(codec), stored.value(),
300 expectedSize, kMaximumDecodedBytes);
301 if (!decoded) return eve::Result<eve::pixelworld::PixelChunkBatch>::failure(decoded.status());
302 const auto expectedHash = eve::ContentId::parse(*hashText);
303 auto actualHash = digest(decoded.value(), hashProvider);
304 if (!expectedHash || !actualHash || actualHash.value() != *expectedHash)
306 eve::Diagnostic::error(eve::DiagnosticCode::HashMismatch, "decoded Chunk content hash does not match",
307 path, {}, "pixelworld.chunk-archive"));
308
310 chunk.x = x.value();
311 chunk.y = y.value();
312 chunk.revision = revision.value();
313 chunk.removed = *removed;
314 if (!*removed) {
316 std::size_t cursor = 0;
317 for (auto& cell : chunk.cells) {
318 cell.material = eve::pixelworld::MaterialId(take<std::uint16_t>(decoded.value(), cursor));
319 cell.temperature = take<std::int16_t>(decoded.value(), cursor);
320 cell.lifetime = take<std::uint8_t>(decoded.value(), cursor);
321 if (currentCells)
322 cell.thermalRemainder = take<std::uint16_t>(decoded.value(), cursor);
323 }
324 }
325 batch.chunks.push_back(std::move(chunk));
326 }
328}
329
330} // namespace eve::pixelworld_streaming
double y
double x
Value::Object payload
int root
Definition AnimSmr.cpp:119
std::uint64_t revision
std::size_t cursor
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
std::vector< std::string > fields
Definition ECS.cpp:42
int instanceId
std::uint64_t decodedSize
Bounded deterministic compression used by the .evpack wire format.
std::vector< std::uint8_t > stored
Definition Evpack.cpp:171
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::uint64_t bytes
std::shared_ptr< const OceanSprayFrame > previous
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
double number
int removed
std::string text
size_t end
std::string digest
Cell cell
Json object
uint32_t seed
Definition TreeMesh.cpp:276
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
const T & value() const &
Borrow the value from a const lvalue after checking success.
Definition Result.h:339
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
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:150
EvpackCodec
Physical outer compression applied to one runtime chunk.
Definition Evpack.h:36
Result< std::vector< std::uint8_t > > compressEvpackChunk(EvpackCodec codec, std::span< const std::uint8_t > decoded)
Compress decoded chunk bytes using the selected stable wire codec.
Result< std::vector< std::uint8_t > > decompressEvpackChunk(EvpackCodec codec, std::span< const std::uint8_t > stored, std::uint64_t decodedSize, std::uint64_t maximumDecodedBytes)
Decode one chunk into its authenticated canonical bytes.
eve::Result< eve::SnapshotEnvelope > archiveChunkBatch(const eve::pixelworld::PixelChunkBatch &batch, eve::PersistentId instanceId, PixelChunkArchiveCodec codec, const eve::SnapshotHashProvider &hashProvider)
Encode one authoritative batch as pixelworld:chunk-batch SnapshotEnvelope version 3.
PixelChunkArchiveCodec
Stable physical codec for one independently stored PixelWorld Chunk.
eve::Result< eve::pixelworld::PixelChunkBatch > decodeChunkBatchArchive(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider)
Verify and decode a version 1, 2 or 3 Chunk-batch archive into an owning candidate.
MaterialId
Compact stable material identifier stored in each authoritative cell.
constexpr int kPixelChunkSize
Definition PixelWorld.h:20
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 authoritative Chunk correction with source world metadata.
Definition PixelWorld.h:89
bool fullResync
Replace the replica projection instead of applying an incremental correction.
Definition PixelWorld.h:96
std::vector< PixelChunkSnapshot > chunks
Definition PixelWorld.h:97
eve::SimulationTick sourceTick
Definition PixelWorld.h:93
Owning, immutable projection of one authoritative simulation chunk.
Definition PixelWorld.h:77
std::vector< PixelCell > cells
Definition PixelWorld.h:82