载入中...
搜索中...
未找到
GraphicsFrameCapture.cpp
浏览该文件的文档.
3
4#include <algorithm>
5#include <cstring>
6#include <glm/gtc/matrix_inverse.hpp>
7#include <glm/gtc/type_ptr.hpp>
8#include <stdexcept>
9
10namespace eve::graphics::vulkan {
11
12void Graphics::recordFrameCapture(vk::CommandBuffer cb) {
13 ++captureFrameId_;
14 if (!captureToken_.empty()) return;
15 auto queued = frameCaptures().queued();
16 if (!queued) return;
17 const auto& [token, request] = *queued;
18 std::vector<CaptureCopy> copies;
19 size_t total = 0;
20 auto* gb = currentGBufferSlot();
21 for (auto attachment : request.attachments) {
22 CaptureCopy copy;
23 copy.metadata.attachment = attachment;
24 copy.metadata.producerFrameId = captureFrameId_;
25 copy.metadata.format = FramePixelFormat::Rgba8;
26 copy.metadata.colorSpace = "data-unorm-storage";
27 copy.metadata.encoding = "unorm8";
28 copy.layout = vk::ImageLayout::eShaderReadOnlyOptimal;
29 copy.aspect = vk::ImageAspectFlagBits::eColor;
30 vkb::GenericImage* source = nullptr;
31 if (attachment == FrameAttachment::Final) {
32 const auto format = swapchain.image_format;
33 const bool bgra = format == vk::Format::eB8G8R8A8Unorm || format == vk::Format::eB8G8R8A8Srgb;
34 const bool rgba = format == vk::Format::eR8G8B8A8Unorm || format == vk::Format::eR8G8B8A8Srgb;
35 if (!bgra && !rgba) copy.metadata.unavailableReason = "UnsupportedFormat";
36 if (presentModel.has_acquired_image && (bgra || rgba)) {
37 copy.source = swapchain.get_images()[presentModel.acquired_image_index];
38 copy.metadata.width = static_cast<uint32_t>(pixelWidth);
39 copy.metadata.height = static_cast<uint32_t>(pixelHeight);
40 copy.metadata.format = bgra ? FramePixelFormat::Bgra8 : FramePixelFormat::Rgba8;
41 copy.metadata.colorSpace = (format == vk::Format::eB8G8R8A8Srgb || format == vk::Format::eR8G8B8A8Srgb)
42 ? "srgb"
43 : "swapchain-unorm";
44 copy.metadata.encoding = "presented-including-overlay";
45 copy.layout = vk::ImageLayout::ePresentSrcKHR;
46 }
47 } else if (attachment >= FrameAttachment::Shadow0) {
48 // Do not present a previous slot's cached shadow as this frame's producer.
49 if (deferredGraphRecorded_ && deferredGraphRecordedSlot_ == currentFrameSlot() && !shadowMaps.empty()) {
50 source = &currentShadowMap().image;
51 copy.layer = static_cast<uint32_t>(attachment) - static_cast<uint32_t>(FrameAttachment::Shadow0);
52 copy.aspect = vk::ImageAspectFlagBits::eDepth;
53 copy.metadata.format = FramePixelFormat::Depth32Float;
54 copy.metadata.encoding = "device-depth-0-to-1";
55 std::copy_n(glm::value_ptr(mesh3dShadows.ubo.lightVP[copy.layer]), 16,
56 copy.metadata.producerMatrix.begin());
57 }
58 } else if (gb && deferredGraphRecorded_ && deferredGraphRecordedSlot_ == currentFrameSlot()) {
59 switch (attachment) {
61 case FrameAttachment::Velocity: source = &gb->depthColor; break;
62 case FrameAttachment::HwDepth: source = &gb->depth; break;
63 case FrameAttachment::Normal: source = &gb->normal; break;
64 case FrameAttachment::Albedo: source = &gb->albedo; break;
65 case FrameAttachment::PbrParams: source = &gb->pbrParams; break;
66 case FrameAttachment::Emissive: source = &gb->emissive; break;
67 default: break;
68 }
69 if (attachment == FrameAttachment::HwDepth) {
70 copy.aspect = vk::ImageAspectFlagBits::eDepth;
71 copy.metadata.format = FramePixelFormat::Depth32Float;
72 copy.metadata.encoding = "device-depth-0-to-1";
73 } else if (attachment == FrameAttachment::Depth || attachment == FrameAttachment::Velocity) {
74 copy.metadata.encoding = "r-linear01-gb-motion-ndc-times-half-plus-half";
75 } else if (attachment == FrameAttachment::Normal) {
76 copy.metadata.encoding = "rgb-world-normal-times-half-plus-half-a-legacy-pbr";
77 } else if (attachment == FrameAttachment::Albedo) {
78 copy.metadata.encoding = "rgb-albedo-times-tint-a-linear01-depth";
79 } else if (attachment == FrameAttachment::Emissive) {
80 copy.metadata.format = FramePixelFormat::Rgba16Float;
81 copy.metadata.colorSpace = "linear";
82 copy.metadata.encoding = "rgb-linear-hdr-emission";
83 } else if (attachment == FrameAttachment::PbrParams) {
84 copy.metadata.encoding = "metallic-roughness-occlusion-specular";
85 }
86 }
87 if (source) {
88 const auto& info = source->info();
89 const bool depth = copy.metadata.format == FramePixelFormat::Depth32Float;
90 const bool supportedFormat = depth ? info.format == vk::Format::eD32Sfloat
91 : copy.metadata.format == FramePixelFormat::Rgba16Float
92 ? info.format == vk::Format::eR16G16B16A16Sfloat
93 : info.format == vk::Format::eR8G8B8A8Unorm;
94 if ((info.usage & vk::ImageUsageFlagBits::eTransferSrc) && supportedFormat &&
95 info.samples == vk::SampleCountFlagBits::e1 && copy.layer < info.arrayLayers) {
96 copy.source = source->image();
97 copy.metadata.width = info.extent.width;
98 copy.metadata.height = info.extent.height;
99 } else
100 copy.metadata.unavailableReason =
101 !supportedFormat ? "UnsupportedFormat"
102 : info.samples != vk::SampleCountFlagBits::e1 ? "UnsupportedSampleCount"
103 : !(info.usage & vk::ImageUsageFlagBits::eTransferSrc) ? "TransferSourceUsageMissing"
104 : "InvalidArrayLayer";
105 }
106 if (!copy.source) {
107 if (copy.metadata.unavailableReason.empty()) copy.metadata.unavailableReason = "NotProducedInTargetFrame";
108 if (!request.reportUnavailable) {
109 auto failed = frameCaptures().fail(
110 token, copy.metadata.unavailableReason + ":" + std::string(frameAttachmentName(attachment)));
111 failed.ignore();
112 return;
113 }
114 }
115 copy.storageIndex = copies.size();
116 for (size_t i = 0; i < copies.size(); ++i) {
117 if (copy.source && copies[i].source == copy.source && copies[i].layer == copy.layer) {
118 copy.storageIndex = i;
119 break;
120 }
121 }
122 if (copy.source && copy.storageIndex == copies.size())
123 total += size_t(copy.metadata.width) * copy.metadata.height * framePixelBytes(copy.metadata.format);
124 copies.push_back(std::move(copy));
125 }
126 auto begin = frameCaptures().begin(token, captureFrameId_, total);
127 if (!begin) {
128 auto failed = frameCaptures().fail(token, "BudgetExceeded");
129 failed.ignore();
130 return;
131 }
132 // Allocate the entire batch before modifying any command buffer.
133 try {
134 for (size_t i = 0; i < copies.size(); ++i) {
135 auto& copy = copies[i];
136 if (copy.source && copy.storageIndex == i)
137 copy.staging = vkb::GenericBuffer(
138 device, vk::BufferUsageFlagBits::eTransferDst,
139 vk::DeviceSize(copy.metadata.width) * copy.metadata.height * framePixelBytes(copy.metadata.format),
140 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
141 }
142 } catch (const std::exception& e) {
143 auto failed = frameCaptures().fail(token, std::string("ReadbackAllocationFailed: ") + e.what());
144 failed.ignore();
146 return;
147 }
148 captureToken_ = token;
149 captureCopies_ = std::move(copies);
150 captureSnapshot_ = {};
151 captureSnapshot_.targetGeneration = captureTargetGeneration_;
152 captureSnapshot_.depthConvention = "Vulkan-NDC-0-to-1-positive-viewport-y";
153 const glm::mat4 inverseProjection = mesh3dFrameUbo.view * glm::inverse(mesh3dFrameUbo.mvp);
154 std::copy_n(glm::value_ptr(inverseProjection), 16, captureSnapshot_.inverseProjection.begin());
155 const glm::mat4 projection = glm::inverse(inverseProjection);
156 std::copy_n(glm::value_ptr(projection), 16, captureSnapshot_.projectionMatrix.begin());
157 std::copy_n(glm::value_ptr(mesh3dFrameUbo.view), 16, captureSnapshot_.viewMatrix.begin());
158 for (size_t i = 0; i < captureCopies_.size(); ++i) {
159 auto& copy = captureCopies_[i];
160 if (!copy.source || copy.storageIndex != i) continue;
161 detail::recordFrameReadback(cb, copy.source, copy.staging.buffer,
162 vk::Extent2D{copy.metadata.width, copy.metadata.height}, copy.aspect, copy.layer,
163 copy.layout);
164 }
165 captureFence_ = presentModel.in_flight_fences[presentRecording.slot().index];
166 for (auto& copy : captureCopies_) copy.source = nullptr;
167}
168
169void Graphics::markFrameCaptureSubmitted() {
170 if (captureToken_.empty() || captureSubmitted_) return;
171 auto submitted = frameCaptures().submitted(captureToken_);
172 submitted.ignore();
173 captureSubmitted_ = true;
174}
175
176void Graphics::pollFrameCapture() {
177 pollEntityInspection();
178 pollGuideCapture();
180 if (!captureToken_.empty() && !captureSubmitted_ && device.instance) {
181 // A new main-thread poll before submission means present threw. Drain
182 // this exceptional path rather than publish unsubmitted staging bytes.
183 try {
184 device->waitIdle();
185 } catch (const vk::SystemError&) {
186 }
187 auto failed = frameCaptures().fail(captureToken_, "CaptureSubmitFailed");
188 failed.ignore();
189 destroyFrameCapture();
190 return;
191 }
192 if (!captureSubmitted_ || !captureFence_ || !device.instance) return;
193 vk::Result status;
194 try {
195 status = device->getFenceStatus(captureFence_);
196 } catch (const vk::SystemError&) {
197 status = vk::Result::eErrorDeviceLost;
198 }
199 if (status == vk::Result::eNotReady) return;
200 if (status != vk::Result::eSuccess) {
201 auto failed = frameCaptures().fail(captureToken_, "DeviceLost");
202 failed.ignore();
203 } else {
204 auto state = frameCaptures().snapshot(captureToken_);
205 if (state && state.value().phase == FrameCapturePhase::ReadbackPending) {
206 try {
207 std::vector<std::shared_ptr<const std::vector<uint8_t>>> storage(captureCopies_.size());
208 for (size_t i = 0; i < captureCopies_.size(); ++i) {
209 auto& copy = captureCopies_[i];
210 if (copy.staging.buffer && copy.storageIndex == i) {
211 auto bytes = std::make_shared<std::vector<uint8_t>>(
212 size_t(copy.metadata.width) * copy.metadata.height * framePixelBytes(copy.metadata.format));
213 const void* mapped = copy.staging.map();
214 if (!mapped) throw std::runtime_error("ReadbackMapFailed");
215 std::memcpy(bytes->data(), mapped, bytes->size());
216 copy.staging.unmap();
217 storage[i] = std::move(bytes);
218 }
219 copy.metadata.bytes = storage[copy.storageIndex];
220 captureSnapshot_.buffers.push_back(copy.metadata);
221 }
222 auto done = frameCaptures().complete(captureToken_, std::move(captureSnapshot_));
223 if (!done) {
224 auto failed = frameCaptures().fail(captureToken_, "CapturePublicationFailed");
225 failed.ignore();
226 }
227 } catch (const std::exception& e) {
228 auto failed = frameCaptures().fail(captureToken_, std::string("ReadbackFailed: ") + e.what());
229 failed.ignore();
230 }
231 }
232 }
233 frameCaptures().retire(captureToken_);
234 captureCopies_.clear();
235 captureSnapshot_ = {};
236 captureToken_.clear();
237 captureFence_ = nullptr;
238 captureSubmitted_ = false;
239}
240
241void Graphics::destroyFrameCapture() {
242 destroyEntityInspection();
243 destroyGuideCapture();
244 ++captureTargetGeneration_;
245 // Existing caller has retired the swapchain/device before destroying readback resources.
246 if (!captureToken_.empty()) {
247 auto failed = frameCaptures().fail(captureToken_, "TargetRecreated");
248 failed.ignore();
249 frameCaptures().retire(captureToken_);
250 }
251 captureCopies_.clear();
252 captureSnapshot_ = {};
253 captureToken_.clear();
254 captureFence_ = nullptr;
255 captureSubmitted_ = false;
256}
257} // namespace eve::graphics::vulkan
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
bool done
std::uint64_t bytes
OceanGpuFrameToken token
size_t queued
Definition OnnxGpgpu.cpp:60
std::string_view source
size_t begin
std::uint32_t depth
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.
Result< void > complete(std::string_view token, FrameCaptureSnapshot snapshot)
Atomically publish all copied attachments; no partial ready result.
void retire(std::string_view token)
Release staging reservations after GPU completion, including cancelled work.
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.
Result< FrameCaptureSnapshot > snapshot(std::string_view token) override
Return immutable owning metadata without GPU access.
void collect()
Expire queued and ready entries; also called by tool operations.
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
FrameCaptureStore & frameCaptures()
Graphics-owned frame capture authority. @thread Engine main thread only. @lifetime Borrowed until Gra...
Definition Graphics.cpp:202
Result< T > failed(Status status, eve::DiagnosticCode code, RuleId rule, std::string message)
Construct a failed editing result with explicit status and diagnostic categories.
void recordFrameReadback(vk::CommandBuffer cb, vk::Image source, vk::Buffer destination, vk::Extent2D extent, vk::ImageAspectFlags aspect, uint32_t layer, vk::ImageLayout originalLayout)
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.
std::array< float, 16 > projectionMatrix
std::array< float, 16 > inverseProjection
std::vector< FrameCaptureBuffer > buffers
std::array< float, 16 > viewMatrix
glm::mat4 lightVP[ShadowConfig::kCascades]
Definition Shadow.h:37
glm::uvec4 info