载入中...
搜索中...
未找到
FrameCapture.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <atomic>
5#include <map>
6#include <set>
7
8namespace eve {
9namespace {
10constexpr std::array<std::string_view, 11> names{
11 "final", "gbuffer.depth", "gbuffer.hwDepth", "gbuffer.normal",
12 "gbuffer.albedo", "gbuffer.pbrParams", "gbuffer.emissive", "gbuffer.velocity",
13 "shadow.csm.0", "shadow.csm.1", "shadow.csm.2"};
14std::atomic<uint64_t> nextGeneration{1};
15template <class T>
16Result<T> failure(std::string message, DiagnosticCode code = DiagnosticCode::InvalidArgument) {
17 return Result<T>::failure(Diagnostic::error(code, std::move(message), "frame_capture"));
18}
19bool terminal(FrameCapturePhase p) {
22}
23} // namespace
24
26 const auto i = static_cast<size_t>(a);
27 return i < names.size() ? names[i] : "unknown";
28}
30 auto it = std::find(names.begin(), names.end(), name);
31 if (it == names.end()) return failure<FrameAttachment>("UnknownAttachment: " + std::string(name));
32 return Result<FrameAttachment>::success(static_cast<FrameAttachment>(it - names.begin()));
33}
35 constexpr std::array<std::string_view, 8> phases{"queued", "recording", "readbackPending", "ready",
36 "failed", "cancelled", "expired", "released"};
37 auto i = static_cast<size_t>(p);
38 return i < phases.size() ? phases[i] : "unknown";
39}
40
42 struct Entry {
45 std::chrono::steady_clock::time_point deadline;
46 size_t reserved = 0;
47 size_t cpuBytes = 0;
48 };
51 uint64_t nextToken = 1;
52 std::map<std::string, Entry, std::less<>> entries;
53 std::vector<std::pair<std::weak_ptr<const std::vector<uint8_t>>, size_t>> leases;
54 size_t used() const {
55 size_t bytes = 0;
56 for (const auto& [key, e] : entries) {
57 (void)key;
58 bytes += e.reserved;
59 }
60 for (const auto& [lease, size] : leases)
61 if (!lease.expired()) bytes += size;
62 return bytes;
63 }
64};
65
67FrameCaptureStore::FrameCaptureStore(Clock clock) : impl_(std::make_unique<Impl>()) {
68 impl_->clock = std::move(clock);
69 impl_->caps.generation = nextGeneration.fetch_add(1);
70}
73 caps.generation = impl_->caps.generation;
74 impl_->caps = std::move(caps);
75}
78 std::erase_if(impl_->leases, [](const auto& item) { return item.first.expired(); });
79 const auto now = impl_->clock();
80 for (auto& [key, e] : impl_->entries) {
81 (void)key;
82 if (!terminal(e.snapshot.phase) && now >= e.deadline) {
83 e.snapshot.phase = FrameCapturePhase::Expired;
84 e.snapshot.reason = "CaptureExpired";
85 e.snapshot.buffers.clear();
86 e.cpuBytes = 0;
87 }
88 }
89 // Bound diagnostic tombstones without invalidating live captures or GPU reservations.
90 while (impl_->entries.size() > 64) {
91 auto it = std::find_if(impl_->entries.begin(), impl_->entries.end(), [](const auto& item) {
92 return terminal(item.second.snapshot.phase) && item.second.reserved == 0;
93 });
94 if (it == impl_->entries.end()) break;
95 impl_->entries.erase(it);
96 }
97}
99 collect();
100 if (request.attachments.empty() || request.attachments.size() > names.size() || request.timeout.count() < 100 ||
101 request.timeout.count() > 30000 || request.requestKey.size() > 128)
102 return failure<std::string>("InvalidCaptureRequest");
103 std::set<FrameAttachment> unique;
104 for (auto a : request.attachments) {
105 if (frameAttachmentName(a) == "unknown" || !unique.insert(a).second)
106 return failure<std::string>("InvalidOrDuplicateAttachment");
107 if (std::find(impl_->caps.attachments.begin(), impl_->caps.attachments.end(), a) ==
108 impl_->caps.attachments.end())
109 return failure<std::string>("UnsupportedAttachment: " + std::string(frameAttachmentName(a)),
111 }
112 size_t live = 0;
113 for (const auto& [token, e] : impl_->entries) {
114 if (e.snapshot.generation == impl_->caps.generation && !request.requestKey.empty() &&
115 request.requestKey == e.request.requestKey) {
116 if (request.attachments != e.request.attachments || request.timeout != e.request.timeout ||
117 request.reportUnavailable != e.request.reportUnavailable)
118 return failure<std::string>("RequestConflict");
120 }
121 if (!terminal(e.snapshot.phase)) {
122 ++live;
123 if (e.snapshot.phase != FrameCapturePhase::Ready) return failure<std::string>("CaptureBusy");
124 }
125 }
126 // Retain a bounded sequence for inspection sheets; GPU acquisition remains single-flight.
127 if (live >= 16 || impl_->used() >= impl_->caps.maxBytes) return failure<std::string>("BudgetExceeded");
128 Impl::Entry e;
129 e.request = std::move(request);
130 e.snapshot.token = std::to_string(impl_->caps.generation) + ":" + std::to_string(impl_->nextToken++);
131 e.snapshot.generation = impl_->caps.generation;
132 e.snapshot.backend = impl_->caps.backend;
133 e.deadline = impl_->clock() + e.request.timeout;
134 auto token = e.snapshot.token;
135 impl_->entries.emplace(token, std::move(e));
136 return Result<std::string>::success(std::move(token));
137}
139 collect();
140 auto it = impl_->entries.find(token);
141 if (it == impl_->entries.end() || it->second.snapshot.generation != impl_->caps.generation)
142 return failure<FrameCaptureSnapshot>("StaleCapture", DiagnosticCode::NotFound);
143 return Result<FrameCaptureSnapshot>::success(it->second.snapshot);
144}
146 collect();
147 auto it = impl_->entries.find(token);
148 if (it == impl_->entries.end() || it->second.snapshot.generation != impl_->caps.generation)
149 return failure<FrameCapturePhase>("StaleCapture", DiagnosticCode::NotFound);
150 auto& e = it->second;
151 if (e.snapshot.phase == FrameCapturePhase::Released)
153 e.snapshot.phase =
155 e.snapshot.buffers.clear();
156 e.cpuBytes = 0;
157 return Result<FrameCapturePhase>::success(e.snapshot.phase);
158}
160 for (auto& [key, entry] : impl_->entries) {
161 (void)key;
162 entry.snapshot.phase = FrameCapturePhase::Cancelled;
163 entry.snapshot.buffers.clear();
164 entry.cpuBytes = 0;
165 }
166 impl_->caps.generation = nextGeneration.fetch_add(1);
167}
168std::optional<std::pair<std::string, FrameCaptureRequest>> FrameCaptureStore::queued() {
169 collect();
170 for (const auto& [token, e] : impl_->entries)
171 if (e.snapshot.phase == FrameCapturePhase::Queued) return std::make_pair(token, e.request);
172 return std::nullopt;
173}
174Result<void> FrameCaptureStore::begin(std::string_view token, uint64_t frameId, size_t bytes) {
175 collect();
176 auto it = impl_->entries.find(token);
177 if (it == impl_->entries.end() || it->second.snapshot.phase != FrameCapturePhase::Queued)
178 return failure<void>("InvalidCaptureTransition");
179 if (bytes > impl_->caps.maxBytes / 2 || impl_->used() > impl_->caps.maxBytes - bytes * 2)
180 return failure<void>("BudgetExceeded");
181 auto& e = it->second;
182 e.reserved = bytes * 2; // Reserve staging and peak CPU publication together.
183 e.snapshot.frameId = frameId;
184 e.snapshot.phase = FrameCapturePhase::Recording;
185 return Result<void>::success();
186}
188 auto it = impl_->entries.find(token);
189 if (it == impl_->entries.end() || it->second.snapshot.phase != FrameCapturePhase::Recording)
190 return failure<void>("InvalidCaptureTransition");
191 it->second.snapshot.phase = FrameCapturePhase::ReadbackPending;
192 return Result<void>::success();
193}
195 collect();
196 auto it = impl_->entries.find(token);
197 if (it == impl_->entries.end() || it->second.snapshot.phase != FrameCapturePhase::ReadbackPending)
198 return failure<void>("InvalidCaptureTransition");
199 auto& e = it->second;
200 std::set<FrameAttachment> seen;
201 std::set<const void*> storage;
202 size_t bytes = 0;
203 for (const auto& b : snapshot.buffers) {
204 if (!seen.insert(b.attachment).second) return failure<void>("DuplicateCaptureBuffer");
205 if (!b.bytes) {
206 if (!e.request.reportUnavailable || b.unavailableReason.empty())
207 return failure<void>("AttachmentUnavailable");
208 continue;
209 }
210 if (!framePixelBytes(b.format) || !b.width || !b.height ||
211 uint64_t(b.width) * b.height * framePixelBytes(b.format) != b.bytes->size())
212 return failure<void>("InvalidCaptureStorage");
213 if (storage.insert(b.bytes.get()).second) bytes += b.bytes->size();
214 }
215 if (seen != std::set<FrameAttachment>(e.request.attachments.begin(), e.request.attachments.end()) ||
216 bytes > e.reserved / 2)
217 return failure<void>("IncompleteCapture");
218 snapshot.token = e.snapshot.token;
219 snapshot.generation = e.snapshot.generation;
220 snapshot.backend = e.snapshot.backend;
221 snapshot.frameId = e.snapshot.frameId;
223 storage.clear();
224 for (const auto& b : snapshot.buffers)
225 if (b.bytes && storage.insert(b.bytes.get()).second) impl_->leases.emplace_back(b.bytes, b.bytes->size());
226 e.snapshot = std::move(snapshot);
227 e.cpuBytes = bytes;
228 e.reserved -= bytes; // Remaining reservation is retired with GPU staging.
229 e.deadline = impl_->clock() + std::chrono::seconds(60);
230 return Result<void>::success();
231}
232Result<void> FrameCaptureStore::fail(std::string_view token, std::string reason) {
233 auto it = impl_->entries.find(token);
234 if (it == impl_->entries.end()) return failure<void>("StaleCapture", DiagnosticCode::NotFound);
235 if (!terminal(it->second.snapshot.phase)) {
236 it->second.snapshot.phase = FrameCapturePhase::Failed;
237 it->second.snapshot.reason = std::move(reason);
238 it->second.snapshot.buffers.clear();
239 it->second.cpuBytes = 0;
240 }
241 return Result<void>::success();
242}
243void FrameCaptureStore::retire(std::string_view token) {
244 auto it = impl_->entries.find(token);
245 if (it != impl_->entries.end()) it->second.reserved = 0;
246}
247} // namespace eve
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::string message
DiagnosticCode code
const GltfImportRequest & request
Snapshot snapshot
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanGpuFrameToken token
PrefabLease lease
float size
Definition TreeMesh.cpp:158
int caps
Definition TreeMesh.cpp:164
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Graphics-owned state machine and immutable CPU snapshot authority. @thread Main-thread only; supplied...
std::optional< std::pair< std::string, FrameCaptureRequest > > queued()
Find pending work, or an empty value when idle.
Result< void > begin(std::string_view token, uint64_t frameId, size_t bytes)
Reserve CPU plus GPU storage before recording any commands.
FrameCaptureStore()
Construct a bounded store with an injectable monotonic clock.
Result< void > complete(std::string_view token, FrameCaptureSnapshot snapshot)
Atomically publish all copied attachments; no partial ready result.
std::function< std::chrono::steady_clock::time_point()> Clock
void retire(std::string_view token)
Release staging reservations after GPU completion, including cancelled work.
~FrameCaptureStore() override
Destroy CPU snapshots; backend must retire its GPU staging first.
Result< std::string > request(FrameCaptureRequest request) override
Reserve a request. @cost Selected attachments require per-pixel readback at recording.
void configure(FrameCaptureCapabilities capabilities)
Set backend support at provider initialization.
Result< void > fail(std::string_view token, std::string reason)
Publish a terminal diagnostic; retain reservation until retire().
Result< void > submitted(std::string_view token)
Mark a recorded batch submitted to the GPU.
void invalidate() override
Revoke all tokens and increment the generation.
FrameCaptureCapabilities capabilities() const override
Inspect supported attachment classes and memory budget.
Result< FrameCaptureSnapshot > snapshot(std::string_view token) override
Return immutable owning metadata without GPU access.
Result< FrameCapturePhase > release(std::string_view token) override
Release a snapshot or cancel an in-flight request.
void collect()
Expire queued and ready entries; also called by tool operations.
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
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
FrameCapturePhase
Capture progress; Ready is published only after all selected copies complete.
constexpr size_t framePixelBytes(FramePixelFormat format)
Packed CPU bytes per pixel; pure value query, callable on any thread.
std::string_view frameAttachmentName(FrameAttachment a)
Stable protocol spelling of an attachment.
Result< FrameAttachment > parseFrameAttachment(std::string_view name)
Validate a protocol attachment name without inventing a resource.
FrameAttachment
Stable logical render attachments; Depth and Velocity share storage.
std::string_view frameCapturePhaseName(FrameCapturePhase p)
Stable protocol spelling of a progress state.
Backend support is explicit; candidates need not be produced in every frame.
Owning request; timeout uses monotonic wall time, never gameplay time.
std::chrono::milliseconds timeout
Owning snapshot metadata; byte storage is immutable and lease-owned.
std::chrono::steady_clock::time_point deadline
std::map< std::string, Entry, std::less<> > entries
std::vector< std::pair< std::weak_ptr< const std::vector< uint8_t > >, size_t > > leases
FrameCaptureCapabilities caps