载入中...
搜索中...
未找到
PixelWorldStreaming.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <limits>
4#include <string>
5#include <vector>
7
8// PixelWorldStreaming.cpp
10namespace {
11
12using Coord = std::pair<int, int>;
13
14Coord coord(const eve::pixelworld::PixelChunkSnapshot& chunk) { return {chunk.y, chunk.x}; }
15
16bool contains(eve::pixelworld::PixelChunkRegion region, Coord value) noexcept {
17 const auto [y, x] = value;
18 return x >= region.minX && x <= region.maxX && y >= region.minY && y <= region.maxY;
19}
20
21} // namespace
22
25 auto all = source.snapshotChunksInRegion(interest, 0);
27
28 const auto link = source.worldLink();
29 const bool fullResync = source_.world == 0 || source_ != link;
30 std::set<Coord> nextKnown;
31 std::set<Coord> emitted;
32 std::vector<eve::pixelworld::PixelChunkSnapshot> output;
33 output.reserve(all.value().size() + known_.size());
35 update.fullResync = fullResync;
36
37 for (const auto& chunk : all.value()) {
38 const Coord key = coord(chunk);
39 if (chunk.removed) {
40 if (fullResync || known_.contains(key)) {
41 output.push_back(chunk);
42 emitted.insert(key);
43 }
44 continue;
45 }
46 nextKnown.insert(key);
47 if (fullResync || !known_.contains(key) || chunk.revision > revision_) {
48 output.push_back(chunk);
49 emitted.insert(key);
50 if (!known_.contains(key)) ++update.chunksEntered;
51 }
52 }
53
54 for (const Coord& key : known_) {
55 if (nextKnown.contains(key) || emitted.contains(key)) continue;
56 ++update.chunksEvicted;
57 if (fullResync || contains(interest, key)) continue;
58 const auto [y, x] = key;
59 output.push_back({x, y, source.revision(), true, {}});
60 }
61 std::sort(output.begin(), output.end(),
62 [](const auto& left, const auto& right) { return coord(left) < coord(right); });
63
64 update.batch.catalogFingerprint = source.materialCatalogFingerprint();
65 update.batch.sourceSeed = source.seed();
66 update.batch.sourceRevision = source.revision();
67 update.batch.sourceTick = eve::SimulationTick(source.tickValue());
68 update.batch.sourceLastEditSequence = source.lastEditSequence();
69 update.batch.fullResync = fullResync;
70 update.batch.chunks = std::move(output);
71
72 source_ = link;
73 revision_ = source.revision();
74 known_ = std::move(nextKnown);
75 return eve::Result<PixelChunkStreamUpdate>::success(std::move(update));
76}
77
79 source_ = {};
80 revision_ = 0;
81 known_.clear();
82}
83
84} // namespace eve::pixelworld_streaming
85
86// PixelWorldTransport.cpp
88namespace {
89
90bool valid(PixelChunkTransportConfig config) {
91 return config.maximumInFlightTransfers > 0 && config.maximumInFlightTransfers <= 1024 &&
92 config.maximumChunksPerPart > 0 && config.maximumChunksPerPart <= 1024 &&
93 config.maximumPartsPerTransfer > 0 && config.maximumPartsPerTransfer <= 65'536 &&
94 config.maximumBufferedTransfers > 0 && config.maximumBufferedTransfers <= 1024;
95}
96
97bool sameMetadata(const PixelChunkTransferPart& left, const PixelChunkTransferPart& right) {
98 return left.streamId == right.streamId && left.transferId == right.transferId &&
99 left.partCount == right.partCount && left.interest == right.interest &&
100 left.batch.catalogFingerprint == right.batch.catalogFingerprint &&
101 left.batch.sourceSeed == right.batch.sourceSeed && left.batch.sourceRevision == right.batch.sourceRevision &&
102 left.batch.sourceTick == right.batch.sourceTick &&
103 left.batch.sourceLastEditSequence == right.batch.sourceLastEditSequence &&
104 left.batch.fullResync == right.batch.fullResync;
105}
106
107} // namespace
108
109ReliablePixelChunkSender::ReliablePixelChunkSender(std::uint64_t streamId, PixelChunkTransportConfig config)
110 : streamId_(streamId), config_(config) {}
111
114 if (streamId == 0 || !valid(config))
116 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "stream id or transport policy is invalid",
117 "config", {}, "pixelworld.reliable-transport"));
119}
120
123 if (inFlight_.size() >= config_.maximumInFlightTransfers)
126 "maximumInFlightTransfers", {}, "pixelworld.reliable-transport"));
127 if (nextTransferId_ == std::numeric_limits<std::uint64_t>::max())
130 "transferId", {}, "pixelworld.reliable-transport"));
131 auto candidateCursor = cursor_;
132 auto captured = candidateCursor.capture(source, interest);
133 if (!captured.ok()) return eve::Result<std::vector<PixelChunkTransferPart>>::failure(captured.status());
134 auto update = std::move(captured).takeValue();
135 if (captured_ && !update.fullResync && update.batch.chunks.empty() &&
136 update.batch.sourceRevision == lastEnqueuedRevision_) {
137 cursor_ = std::move(candidateCursor);
139 }
140
141 const std::size_t chunkCount = update.batch.chunks.size();
142 const std::size_t partCount =
143 std::max<std::size_t>(1, (chunkCount + config_.maximumChunksPerPart - 1) / config_.maximumChunksPerPart);
144 if (partCount > config_.maximumPartsPerTransfer)
146 eve::Diagnostic::error(eve::DiagnosticCode::PreconditionViolation, "captured update exceeds part budget",
147 "maximumPartsPerTransfer", {}, "pixelworld.reliable-transport"));
148 std::vector<PixelChunkTransferPart> parts;
149 parts.reserve(partCount);
150 for (std::size_t index = 0; index < partCount; ++index) {
152 part.streamId = streamId_;
153 part.transferId = nextTransferId_;
154 part.partIndex = std::uint32_t(index);
155 part.partCount = std::uint32_t(partCount);
156 part.interest = interest;
157 part.batch.catalogFingerprint = update.batch.catalogFingerprint;
158 part.batch.sourceSeed = update.batch.sourceSeed;
159 part.batch.sourceRevision = update.batch.sourceRevision;
160 part.batch.sourceTick = update.batch.sourceTick;
161 part.batch.sourceLastEditSequence = update.batch.sourceLastEditSequence;
162 part.batch.fullResync = update.batch.fullResync;
163 const std::size_t begin = index * config_.maximumChunksPerPart;
164 const std::size_t end = std::min(chunkCount, begin + config_.maximumChunksPerPart);
165 if (begin < end)
166 part.batch.chunks.assign(update.batch.chunks.begin() + std::ptrdiff_t(begin),
167 update.batch.chunks.begin() + std::ptrdiff_t(end));
168 parts.push_back(std::move(part));
169 }
170 inFlight_.emplace(nextTransferId_, parts);
171 cursor_ = std::move(candidateCursor);
172 ++nextTransferId_;
173 captured_ = true;
174 lastEnqueuedRevision_ = update.batch.sourceRevision;
175 return eve::Result<std::vector<PixelChunkTransferPart>>::success(std::move(parts));
176}
177
178std::vector<PixelChunkTransferPart> ReliablePixelChunkSender::pendingParts() const {
179 std::vector<PixelChunkTransferPart> result;
180 for (const auto& [transfer, parts] : inFlight_) {
181 (void)transfer;
182 result.insert(result.end(), parts.begin(), parts.end());
183 }
184 return result;
185}
186
188 if (ack.streamId != streamId_)
190 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "ACK belongs to another stream", "streamId", {},
191 "pixelworld.reliable-transport"));
192 if (ack.acknowledgedThrough <= acknowledgedThrough_)
193 return eve::Result<PixelChunkAckReceipt>::success({0, 0, acknowledgedThrough_});
194 if (ack.acknowledgedThrough >= nextTransferId_)
196 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "ACK advances beyond the sent window",
197 "acknowledgedThrough", {}, "pixelworld.reliable-transport"));
198 const auto acknowledged = inFlight_.find(ack.acknowledgedThrough);
199 if (acknowledged == inFlight_.end() || acknowledged->second.empty() ||
200 acknowledged->second.front().batch.sourceRevision != ack.appliedRevision)
202 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "ACK revision does not match the transfer",
203 "appliedRevision", {}, "pixelworld.reliable-transport"));
204 PixelChunkAckReceipt receipt;
205 for (auto iterator = inFlight_.begin();
206 iterator != inFlight_.end() && iterator->first <= ack.acknowledgedThrough;) {
207 for (const auto& part : iterator->second)
208 receipt.tombstonesReleased += std::uint32_t(std::count_if(
209 part.batch.chunks.begin(), part.batch.chunks.end(), [](const auto& chunk) { return chunk.removed; }));
210 iterator = inFlight_.erase(iterator);
211 ++receipt.transfersReleased;
212 }
213 acknowledgedThrough_ = ack.acknowledgedThrough;
214 receipt.acknowledgedThrough = acknowledgedThrough_;
216}
217
218std::size_t ReliablePixelChunkSender::inFlightTransferCount() const noexcept { return inFlight_.size(); }
219
221 std::size_t count = 0;
222 for (const auto& [transfer, parts] : inFlight_) {
223 (void)transfer;
224 for (const auto& part : parts)
225 count += std::count_if(part.batch.chunks.begin(), part.batch.chunks.end(),
226 [](const auto& chunk) { return chunk.removed; });
227 }
228 return count;
229}
230
232 : streamId_(streamId), config_(config) {}
233
236 if (streamId == 0 || !valid(config))
238 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "stream id or transport policy is invalid",
239 "config", {}, "pixelworld.reliable-transport"));
241}
242
245 if (part.streamId != streamId_ || part.transferId == 0 || part.partCount == 0 ||
246 part.partCount > config_.maximumPartsPerTransfer || part.partIndex >= part.partCount ||
247 part.batch.chunks.size() > config_.maximumChunksPerPart)
249 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "transfer part metadata exceeds policy",
250 "part", {}, "pixelworld.reliable-transport"));
252 if (part.transferId < expectedTransferId_) {
253 receipt.duplicate = true;
254 receipt.ack = {streamId_, expectedTransferId_ - 1, replica.revision()};
255 receipt.partsBuffered = std::uint32_t(bufferedPartCount());
257 }
258 auto found = buffered_.find(part.transferId);
259 if (found == buffered_.end()) {
260 if (buffered_.size() >= config_.maximumBufferedTransfers)
262 eve::DiagnosticCode::PreconditionViolation, "out-of-order receive window is full",
263 "maximumBufferedTransfers", {}, "pixelworld.reliable-transport"));
264 Assembly assembly;
265 assembly.partCount = part.partCount;
266 assembly.parts.resize(part.partCount);
267 found = buffered_.emplace(part.transferId, std::move(assembly)).first;
268 }
269 Assembly& assembly = found->second;
270 if (assembly.partCount != part.partCount)
272 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "transfer part count changed", "partCount", {},
273 "pixelworld.reliable-transport"));
274 auto& slot = assembly.parts[part.partIndex];
275 if (slot) {
276 if (*slot != part)
278 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "duplicate part payload conflicts", "part", {},
279 "pixelworld.reliable-transport"));
280 receipt.duplicate = true;
281 } else {
282 slot = std::make_unique<PixelChunkTransferPart>(std::move(part));
283 }
284
285 while (true) {
286 auto next = buffered_.find(expectedTransferId_);
287 if (next == buffered_.end()) break;
288 const bool complete = std::all_of(next->second.parts.begin(), next->second.parts.end(),
289 [](const auto& value) { return bool(value); });
290 if (!complete) break;
291 const PixelChunkTransferPart& first = *next->second.parts.front();
293 combined.chunks.clear();
294 for (const auto& value : next->second.parts) {
295 if (!sameMetadata(first, *value))
297 eve::DiagnosticCode::Conflict, "transfer parts disagree on authority metadata", "part.batch", {},
298 "pixelworld.reliable-transport"));
299 combined.chunks.insert(combined.chunks.end(), value->batch.chunks.begin(), value->batch.chunks.end());
300 }
301 auto applied = replica.applyChunkBatch(combined, replica.revision());
302 if (!applied.ok()) {
303 buffered_.erase(next);
305 }
306 buffered_.erase(next);
307 ++expectedTransferId_;
308 ++receipt.transfersApplied;
309 }
310 receipt.ack = {streamId_, expectedTransferId_ - 1, replica.revision()};
311 receipt.partsBuffered = std::uint32_t(bufferedPartCount());
313}
314
316 std::size_t count = 0;
317 for (const auto& [transfer, assembly] : buffered_) {
318 (void)transfer;
319 count +=
320 std::count_if(assembly.parts.begin(), assembly.parts.end(), [](const auto& value) { return bool(value); });
321 }
322 return count;
323}
324
325} // namespace eve::pixelworld_streaming
double y
double x
std::vector< eve::artifact::PartView > parts
std::string output
bool applied
SQObjectPtr key
Definition ECS.cpp:155
ScriptFieldRegion region
HexVec3 left
HexVec3 right
std::int32_t first
PhysicsJointLink link
Poco::JSON::Object::Ptr result
bool valid
bool all
Object::Ptr value
std::string slot
bool found
std::string_view source
size_t begin
size_t end
int count
uint32_t index
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
Sparse, chunked, deterministic 2D falling-material world.
Definition PixelWorld.h:224
eve::Result< PixelChunkApplyReceipt > applyChunkBatch(const PixelChunkBatch &batch, std::uint64_t expectedRevision)
Transactionally apply a canonical authoritative Chunk correction batch.
std::uint64_t revision() const noexcept
Revision.
eve::Result< PixelChunkStreamUpdate > capture(const eve::pixelworld::PixelWorld &source, eve::pixelworld::PixelChunkRegion interest)
Capture changed/entered Chunks and eviction tombstones for an interest region.
void reset() noexcept
Forget consumer projection state so the next capture is a full resync.
Ordered atomic receiver with duplicate suppression and bounded out-of-order buffering.
eve::Result< PixelChunkReceiveReceipt > receive(PixelChunkTransferPart part, eve::pixelworld::PixelWorld &replica)
Buffer one part and atomically apply every newly contiguous complete transfer.
std::size_t bufferedPartCount() const noexcept
Count parts retained while waiting for gaps or completion.
static eve::Result< ReliablePixelChunkReceiver > create(std::uint64_t streamId, PixelChunkTransportConfig config={})
Validate policy and create a receiver for one nonzero stream session.
ReliablePixelChunkReceiver(const ReliablePixelChunkReceiver &)=delete
Reliable sender retaining owning transfer parts and tombstones until application ACK.
std::vector< PixelChunkTransferPart > pendingParts() const
Return every unacknowledged part in canonical transfer/part order for transmission.
static eve::Result< ReliablePixelChunkSender > create(std::uint64_t streamId, PixelChunkTransportConfig config={})
Validate policy and create a fresh nonzero stream session.
std::size_t retainedTombstoneCount() const noexcept
Number of tombstones retained specifically for possible retransmission.
eve::Result< std::vector< PixelChunkTransferPart > > capture(const eve::pixelworld::PixelWorld &source, eve::pixelworld::PixelChunkRegion interest)
Capture and enqueue one atomic revision transfer, split into bounded owning parts.
eve::Result< PixelChunkAckReceipt > acknowledge(PixelChunkTransferAck ack)
Release cumulatively acknowledged transfers and their retained tombstones.
std::size_t inFlightTransferCount() const noexcept
Number of unacknowledged atomic transfers.
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
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
Inclusive finite rectangle expressed in Chunk coordinates.
Definition PixelWorld.h:104
Owning, immutable projection of one authoritative simulation chunk.
Definition PixelWorld.h:77
Counters returned after accepting a cumulative ACK.
Receiver outcome after one possibly duplicate or out-of-order part.
One interest-stream update suitable for persistence or network transport.
bool fullResync
Mirrors batch.fullResync for capture diagnostics.
Cumulative application ACK proving transfers were committed to replica authority.
One independently retransmittable part of an atomic Chunk transfer.
Bounded application-level reliability policy layered over any byte transport.