载入中...
搜索中...
未找到
McpFrameCapture.cpp
浏览该文件的文档.
2#include "common/Capability.h"
10
11#include <Poco/Base64Encoder.h>
12#include <Poco/JSON/Array.h>
13#include <algorithm>
14#include <atomic>
15#include <bit>
16#include <cmath>
17#include <filesystem>
18#include <fstream>
19#include <future>
20#include <map>
21#include <set>
22#include <sstream>
23
24namespace eve::dev {
25namespace {
26using Object = Poco::JSON::Object;
27using Array = Poco::JSON::Array;
28Object::Ptr object() { return new Object; }
29Array::Ptr array() { return new Array; }
30Object::Ptr envelope(std::string status) {
31 auto o = object();
32 o->set("schemaId", "eve.renderCapture");
33 o->set("schemaVersion", 1);
34 o->set("status", status);
35 return o;
36}
37std::string reply(Object::Ptr o) { return textContentResult(mcpStringify(Poco::Dynamic::Var(o))); }
38std::string error(std::string reason, bool retry = false) {
39 auto o = envelope("failed");
40 o->set("code", reason);
41 o->set("message", reason);
42 o->set("retryable", retry);
43 return textContentResult(mcpStringify(Poco::Dynamic::Var(o)), !retry);
44}
45std::string resultError(const Status& status) {
46 return error(status.diagnostics().empty() ? std::string(statusCodeName(status.code()))
47 : status.diagnostics().front().message());
48}
49Object::Ptr bufferJson(const FrameCaptureBuffer& b) {
50 auto o = object();
51 o->set("id", std::string(frameAttachmentName(b.attachment)));
52 o->set("width", b.width);
53 o->set("height", b.height);
54 o->set("producerFrameId", static_cast<Poco::UInt64>(b.producerFrameId));
55 o->set("format", b.format == FramePixelFormat::Depth32Float ? "D32_SFLOAT"
56 : b.format == FramePixelFormat::Rgba16Float ? "RGBA16_SFLOAT"
57 : b.format == FramePixelFormat::Bgra8 ? "BGRA8"
58 : "RGBA8");
59 o->set("encoding", b.encoding);
60 o->set("colorSpace", b.colorSpace);
61 o->set("status", b.bytes ? "available" : "unavailable");
62 o->set("reason", b.unavailableReason);
63 o->set("bytes", static_cast<Poco::UInt64>(b.bytes ? b.bytes->size() : 0));
64 o->set("samples", 1);
65 o->set("origin", "top-left");
66 const bool shadow = b.attachment >= FrameAttachment::Shadow0;
67 o->set("producerPass", b.attachment == FrameAttachment::Final ? "present" : shadow ? "csm" : "gbuffer");
68 o->set("viewId", shadow ? "primary-directional-csm" : "main");
69 o->set("storageGroup", b.attachment == FrameAttachment::Depth || b.attachment == FrameAttachment::Velocity
70 ? "gbuffer.depthColor"
71 : shadow ? "shadow.csm"
72 : std::string(frameAttachmentName(b.attachment)));
73 if (shadow)
74 o->set("arrayLayer", static_cast<unsigned>(b.attachment) - static_cast<unsigned>(FrameAttachment::Shadow0));
75 auto matrix = array();
76 for (float value : b.producerMatrix)
77 matrix->add(std::isfinite(value) ? Poco::Dynamic::Var(value) : Poco::Dynamic::Var("nonfinite"));
78 o->set("producerMatrixColumnMajor", matrix);
79 return o;
80}
81struct JobOutput {
82 std::string response;
83};
84struct Job {
85 uint64_t generation;
86 std::vector<std::string> captures;
87 std::string key;
88 std::future<JobOutput> future;
89 std::string response;
90 std::chrono::steady_clock::time_point deadline;
91 std::shared_ptr<std::atomic<bool>> cancelled;
92};
93std::map<std::string, Job> jobs;
94uint64_t nextJob = 1;
95struct ExportCleanup {
96 std::vector<std::filesystem::path> paths;
97 ~ExportCleanup() {
98 for (const auto& path : paths) {
99 std::error_code ignored;
100 std::filesystem::remove(path, ignored);
101 }
102 }
103};
104void writeExportFile(const std::filesystem::path& path, const char* data, size_t size) {
105 std::ofstream stream(path, std::ios::binary | std::ios::trunc);
106 stream.write(data, static_cast<std::streamsize>(size));
107 stream.close();
108 if (!stream) throw std::runtime_error("ExportWriteFailed");
109}
110std::string base64(const std::vector<uint8_t>& bytes) {
111 std::ostringstream out;
112 Poco::Base64Encoder encoder(out);
113 encoder.rdbuf()->setLineLength(0);
114 encoder.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
115 encoder.close();
116 return out.str();
117}
118std::string pending(std::string token) {
119 auto o = envelope("pending");
120 o->set("jobToken", token);
121 o->set("retryable", true);
122 return reply(o);
123}
124std::string pollJob(const std::string& token, uint64_t generation) {
125 auto it = jobs.find(token);
126 if (it == jobs.end() || it->second.generation != generation) return error("StaleJob");
127 auto& job = it->second;
128 if (job.cancelled->load()) return error("CancelledJob");
129 if (job.response.empty()) {
130 if (job.future.wait_for(std::chrono::seconds(0)) != std::future_status::ready) return pending(token);
131 try {
132 job.response = job.future.get().response;
133 } catch (const std::exception& e) {
134 job.response = error(std::string("WorkerFailed: ") + e.what());
135 }
136 }
137 return job.response;
138}
139bool validArguments(Object::Ptr args, const std::set<std::string>& allowed) {
140 if (!args) return true;
141 for (const auto& [key, value] : *args) {
142 if (!allowed.contains(key)) return false;
143 if (key == "buffers" || key == "tokens") {
144 if (value.type() != typeid(Array::Ptr)) return false;
145 } else if (key == "timeoutMs" || key == "x" || key == "y" || key == "channel" || key == "maxWidth" ||
146 key == "maxHeight" || key == "maxBytes" || key == "columns" || key == "cellWidth" ||
147 key == "cellHeight") {
148 if (!value.isInteger() || value.convert<double>() < -2147483648.0 || value.convert<double>() > 2147483647.0)
149 return false;
150 } else if (key == "rangeMin" || key == "rangeMax" || key == "exposure") {
151 if (!value.isNumeric()) return false;
152 } else if (!value.isString())
153 return false;
154 }
155 return true;
156}
157} // namespace
158
159bool isMcpFrameCaptureTool(std::string_view name) {
160 return name == "eve_frame_capture_capabilities" || name == "eve_frame_capture" ||
161 name == "eve_frame_capture_status" || name == "eve_frame_buffer_image" || name == "eve_frame_pixel" ||
162 name == "eve_frame_capture_export" || name == "eve_frame_capture_release" ||
163 name == "eve_frame_contact_sheet";
164}
165
167 for (auto& [token, job] : jobs) {
168 (void)token;
169 job.cancelled->store(true);
170 }
171 if (auto* capture = cap::query<IRenderFrameCapture>()) capture->invalidate();
172}
173
174std::string callMcpFrameCaptureTool(std::string_view name, Object::Ptr args) {
175 auto* service = cap::query<IRenderFrameCapture>();
176 if (!service) return error("ProviderAbsent");
177 const auto caps = service->capabilities();
178 for (auto it = jobs.begin(); it != jobs.end();) {
179 if (it->second.generation != caps.generation) it->second.cancelled->store(true);
180 const bool done = !it->second.response.empty() ||
181 it->second.future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
182 if (done &&
183 (it->second.generation != caps.generation || it->second.deadline < std::chrono::steady_clock::now()))
184 it = jobs.erase(it);
185 else
186 ++it;
187 }
188 if (name == "eve_frame_contact_sheet") {
189 if (!validArguments(args, {"tokens", "columns", "cellWidth", "cellHeight", "maxBytes"}) || !args ||
190 !args->has("tokens"))
191 return error("InvalidArguments");
192 const auto requested = args->getArray("tokens");
193 if (requested->size() == 0 || requested->size() > 16) return error("InvalidArguments");
195 options.columns = static_cast<uint32_t>(getArgInt(args, "columns", (std::min)(2, int(requested->size()))));
196 options.cellWidth = static_cast<uint32_t>(getArgInt(args, "cellWidth", 512));
197 options.cellHeight = static_cast<uint32_t>(getArgInt(args, "cellHeight", 512));
198 options.maxBytes = static_cast<size_t>(getArgInt(args, "maxBytes", 2097152));
199 if (!options.columns || options.columns > requested->size() || !options.cellWidth || !options.cellHeight ||
200 options.cellWidth > 2048 || options.cellHeight > 2048 || options.maxBytes < 1024 ||
201 options.maxBytes > 16777216 || options.columns * options.cellWidth > 2048 ||
202 ((requested->size() + options.columns - 1) / options.columns) * options.cellHeight > 2048)
203 return error("InvalidContactSheetOptions");
204 std::vector<std::string> tokens;
205 std::vector<FrameCaptureBuffer> frames;
206 auto cells = array();
207 for (unsigned i = 0; i < requested->size(); ++i) {
208 if (!requested->get(i).isString()) return error("InvalidArguments");
209 const auto token = requested->getElement<std::string>(i);
210 auto captured = service->snapshot(token);
211 if (!captured) return resultError(captured.status());
212 const auto& snapshot = captured.value();
214 return error("CaptureNotReady", snapshot.phase == FrameCapturePhase::Queued ||
217 const auto found = std::find_if(snapshot.buffers.begin(), snapshot.buffers.end(),
218 [](const auto& b) { return b.attachment == FrameAttachment::Final; });
219 if (found == snapshot.buffers.end() || !found->bytes) return error("AttachmentUnavailable");
220 frames.push_back(*found);
221 tokens.push_back(token);
222 auto cell = object();
223 cell->set("index", i);
224 cell->set("token", token);
225 cell->set("frameId", static_cast<Poco::UInt64>(snapshot.frameId));
226 cell->set("producerFrameId", static_cast<Poco::UInt64>(found->producerFrameId));
227 cell->set("sourceWidth", found->width);
228 cell->set("sourceHeight", found->height);
229 cell->set("backend", snapshot.backend);
230 cell->set("providerGeneration", static_cast<Poco::UInt64>(snapshot.generation));
231 cell->set("x", (i % options.columns) * options.cellWidth);
232 cell->set("y", (i / options.columns) * options.cellHeight);
233 cell->set("width", options.cellWidth);
234 cell->set("height", options.cellHeight);
235 cells->add(cell);
236 }
237 const auto key = std::string(name) + ":" + mcpStringify(Poco::Dynamic::Var(args));
238 for (const auto& [jobToken, job] : jobs)
239 if (job.generation == caps.generation && job.key == key) return pollJob(jobToken, caps.generation);
240 while (jobs.size() >= 2) {
241 const auto disposable = std::find_if(jobs.begin(), jobs.end(), [](const auto& pair) {
242 return !pair.second.response.empty() ||
243 pair.second.future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
244 });
245 if (disposable == jobs.end()) return error("WorkerBudgetExceeded");
246 jobs.erase(disposable);
247 }
248 const auto jobToken = "job:" + std::to_string(nextJob++);
249 auto cancelled = std::make_shared<std::atomic<bool>>(false);
250 auto future = std::async(std::launch::async,
251 [frames = std::move(frames), options, cells, cancelled, jobToken]() -> JobOutput {
252 try {
253 if (cancelled->load()) return {error("CancelledJob")};
254 auto sheet = frameContactSheet(frames, options);
255 if (!sheet) return {resultError(sheet.status())};
256 if (cancelled->load()) return {error("CancelledJob")};
257 auto metadata = envelope("ready");
258 metadata->set("jobToken", jobToken);
259 metadata->set("layout", "row-major");
260 metadata->set("cells", cells);
261 metadata->set("width", sheet.value().width);
262 metadata->set("height", sheet.value().height);
263 metadata->set("sameSimulationInstantVerified", false);
264 return {imageContentResult(base64(sheet.value().png), "image/png",
265 mcpStringify(Poco::Dynamic::Var(metadata)))};
266 } catch (const std::exception& exception) {
267 return {error(std::string("ContactSheetFailed: ") + exception.what())};
268 }
269 });
270 jobs.emplace(jobToken, Job{caps.generation,
271 std::move(tokens),
272 key,
273 std::move(future),
274 {},
275 std::chrono::steady_clock::now() + std::chrono::seconds(60),
276 std::move(cancelled)});
277 return pending(jobToken);
278 }
279 if (name == "eve_frame_capture_capabilities") {
280 if (!validArguments(args, {})) return error("InvalidArguments");
281 auto o = envelope("ready");
282 o->set("backend", caps.backend);
283 o->set("providerGeneration", static_cast<Poco::UInt64>(caps.generation));
284 o->set("maxBytes", static_cast<Poco::UInt64>(caps.maxBytes));
285 auto buffers = array();
286 for (auto a : caps.attachments) buffers->add(std::string(frameAttachmentName(a)));
287 o->set("buffers", buffers);
288 return reply(o);
289 }
290 if (name == "eve_frame_capture") {
291 if (!validArguments(args, {"buffers", "timeoutMs", "onUnavailable", "requestKey"}) || !args ||
292 !args->has("buffers"))
293 return error("InvalidArguments");
295 auto buffers = args->getArray("buffers");
296 if (buffers->size() > 11) return error("InvalidArguments");
297 for (size_t i = 0; i < buffers->size(); ++i) {
298 if (!buffers->get(static_cast<unsigned>(i)).isString()) return error("InvalidArguments");
299 auto parsed = parseFrameAttachment(buffers->getElement<std::string>(static_cast<unsigned>(i)));
300 if (!parsed) return resultError(parsed.status());
301 request.attachments.push_back(parsed.value());
302 }
303 const auto unavailable = getArgString(args, "onUnavailable", "fail");
304 if (unavailable != "fail" && unavailable != "report") return error("InvalidArguments");
305 request.reportUnavailable = unavailable == "report";
306 request.timeout = std::chrono::milliseconds(getArgInt(args, "timeoutMs", 5000));
307 request.requestKey = getArgString(args, "requestKey");
308 auto result = service->request(std::move(request));
309 if (!result) return resultError(result.status());
310 auto state = service->snapshot(result.value());
311 if (!state) return resultError(state.status());
312 auto o = envelope(std::string(frameCapturePhaseName(state.value().phase)));
313 o->set("token", result.value());
314 return reply(o);
315 }
316 const std::set<std::string> statusArgs{"token"};
317 const std::set<std::string> imageArgs{"token", "buffer", "view", "channel", "rangeMin",
318 "rangeMax", "exposure", "maxWidth", "maxHeight", "maxBytes"};
319 const std::set<std::string> pixelArgs{"token", "buffer", "x", "y"};
320 const std::set<std::string> exportArgs{"token", "buffer", "encoding", "path", "view", "channel",
321 "rangeMin", "rangeMax", "exposure", "maxWidth", "maxHeight", "maxBytes"};
322 if (!validArguments(args, name == "eve_frame_buffer_image" ? imageArgs
323 : name == "eve_frame_pixel" ? pixelArgs
324 : name == "eve_frame_capture_export" ? exportArgs
325 : statusArgs))
326 return error("InvalidArguments");
327 const auto token = getArgString(args, "token");
328 if (name == "eve_frame_capture_status" && token.starts_with("job:")) return pollJob(token, caps.generation);
329 if (name == "eve_frame_capture_release") {
330 auto result = service->release(token);
331 if (!result) return resultError(result.status());
332 for (auto& [jobToken, job] : jobs) {
333 (void)jobToken;
334 if (std::find(job.captures.begin(), job.captures.end(), token) != job.captures.end())
335 job.cancelled->store(true);
336 }
337 auto o = envelope(std::string(frameCapturePhaseName(result.value())));
338 o->set("token", token);
339 return reply(o);
340 }
341 auto result = service->snapshot(token);
342 if (!result) return resultError(result.status());
343 const auto& snapshot = result.value();
344 if (name == "eve_frame_capture_status") {
345 auto o = envelope(std::string(frameCapturePhaseName(snapshot.phase)));
346 o->set("token", token);
347 o->set("frameId", static_cast<Poco::UInt64>(snapshot.frameId));
348 o->set("providerGeneration", static_cast<Poco::UInt64>(snapshot.generation));
349 o->set("backend", snapshot.backend);
350 o->set("reason", snapshot.reason);
351 o->set("depthConvention", snapshot.depthConvention);
352 o->set("targetGeneration", static_cast<Poco::UInt64>(snapshot.targetGeneration));
353 o->set("viewId", "main");
354 auto inverseProjection = array();
355 auto projection = array();
356 auto view = array();
357 for (size_t i = 0; i < 16; ++i) {
358 auto finite = [](float f) {
359 return std::isfinite(f) ? Poco::Dynamic::Var(f) : Poco::Dynamic::Var("nonfinite");
360 };
361 inverseProjection->add(finite(snapshot.inverseProjection[i]));
362 projection->add(finite(snapshot.projectionMatrix[i]));
363 view->add(finite(snapshot.viewMatrix[i]));
364 }
365 o->set("inverseProjectionColumnMajor", inverseProjection);
366 o->set("projectionColumnMajor", projection);
367 o->set("viewColumnMajor", view);
368 auto buffers = array();
369 for (const auto& b : snapshot.buffers) buffers->add(bufferJson(b));
370 o->set("buffers", buffers);
371 return reply(o);
372 }
374 return error("CaptureNotReady", snapshot.phase == FrameCapturePhase::Queued ||
377 auto parsed = parseFrameAttachment(getArgString(args, "buffer"));
378 if (!parsed) return resultError(parsed.status());
379 const auto it = std::find_if(snapshot.buffers.begin(), snapshot.buffers.end(),
380 [&](const auto& b) { return b.attachment == parsed.value(); });
381 if (it == snapshot.buffers.end() || !it->bytes) return error("AttachmentUnavailable");
382 if (name == "eve_frame_pixel") {
383 if (!args || !args->has("x") || !args->has("y")) return error("InvalidArguments");
384 const int x = getArgInt(args, "x", -1), y = getArgInt(args, "y", -1);
385 if (x < 0 || y < 0) return error("PixelOutOfBounds");
386 auto pixel = frameCapturePixel(*it, static_cast<uint32_t>(x), static_cast<uint32_t>(y));
387 if (!pixel) return resultError(pixel.status());
388 auto o = envelope("ready");
389 o->set("token", token);
390 o->set("buffer", std::string(frameAttachmentName(it->attachment)));
391 o->set("frameId", static_cast<Poco::UInt64>(snapshot.frameId));
392 o->set("x", x);
393 o->set("y", y);
394 auto channels = array();
395 for (size_t c = 0; c < pixel.value().channels; ++c) {
396 auto channel = object();
397 channel->set("name", std::string(pixel.value().labels[c]));
398 const double decoded = pixel.value().decoded[c];
399 channel->set("stored", std::isfinite(pixel.value().stored[c]) ? Poco::Dynamic::Var(pixel.value().stored[c])
400 : Poco::Dynamic::Var("nonfinite"));
401 channel->set("decoded", std::isfinite(decoded) ? Poco::Dynamic::Var(decoded)
402 : Poco::Dynamic::Var(std::isnan(decoded) ? "NaN"
403 : decoded > 0 ? "+Inf"
404 : "-Inf"));
405 channels->add(channel);
406 }
407 o->set("channels", channels);
408 if (it->attachment == FrameAttachment::HwDepth) {
409 auto depth = frameCaptureLinearDepth(*it, static_cast<uint32_t>(x), static_cast<uint32_t>(y),
410 snapshot.inverseProjection);
411 if (depth)
412 o->set("linearViewDepth", depth.value());
413 else
414 o->set("linearViewDepthStatus", "InvalidDepthProjection");
415 }
416 return reply(o);
417 }
419 options.inverseProjection = snapshot.inverseProjection;
420 options.view = getArgString(args, "view", "auto");
421 options.channel = getArgInt(args, "channel", 0);
422 options.maxWidth = static_cast<uint32_t>(getArgInt(args, "maxWidth", 1024));
423 options.maxHeight = static_cast<uint32_t>(getArgInt(args, "maxHeight", 1024));
424 options.rangeMin = getArgFloat(args, "rangeMin", 0);
425 options.rangeMax = getArgFloat(args, "rangeMax", 1);
426 options.exposure = getArgFloat(args, "exposure", 0);
427 const int maxBytes = getArgInt(args, "maxBytes", 2 * 1024 * 1024);
428 if (maxBytes < 1024 || maxBytes > 16 * 1024 * 1024) return error("InvalidImageBudget");
429 options.maxBytes = static_cast<size_t>(maxBytes);
430 const auto encoding = getArgString(args, "encoding", "previewPng");
431 auto path = getArgString(args, "path");
432 const bool exporting = name == "eve_frame_capture_export";
433 if (exporting && (path.empty() || (encoding != "previewPng" && encoding != "nativeBinary")))
434 return error("InvalidExport");
435 if (exporting) {
436 if (path.find('\0') != std::string::npos) return error("InvalidExportPath");
437 try {
438 auto resolved = std::filesystem::path(path);
439 const auto root = McpServer::instance().gameRoot();
440 if (resolved.is_relative() && !root.empty()) resolved = std::filesystem::path(root) / resolved;
441 path = std::filesystem::absolute(resolved).lexically_normal().generic_string();
442 } catch (const std::exception&) {
443 return error("InvalidExportPath");
444 }
445 }
446 const auto key = std::string(name) + ":" + mcpStringify(Poco::Dynamic::Var(args));
447 for (const auto& [jobToken, job] : jobs)
448 if (job.generation == caps.generation && job.key == key) return pollJob(jobToken, caps.generation);
449 size_t running = 0;
450 for (const auto& [jobId, job] : jobs) {
451 (void)jobId;
452 if (job.response.empty() && job.future.wait_for(std::chrono::seconds(0)) != std::future_status::ready)
453 ++running;
454 }
455 if (running >= 2) return error("WorkerBudgetExceeded");
456 // Completed previews are disposable projections; capture snapshots retain their own TTL.
457 while (jobs.size() >= 2) {
458 auto disposable = std::find_if(jobs.begin(), jobs.end(), [](const auto& pair) {
459 return !pair.second.response.empty() ||
460 pair.second.future.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
461 });
462 if (disposable == jobs.end()) return error("WorkerBudgetExceeded");
463 jobs.erase(disposable);
464 }
465 const auto jobToken = "job:" + std::to_string(caps.generation) + ":" + std::to_string(nextJob++);
466 auto cancelled = std::make_shared<std::atomic<bool>>(false);
467 auto future = std::async(
468 std::launch::async,
469 [buffer = *it, options, token, snapshotFrame = snapshot.frameId, exporting, encoding, path, jobToken,
470 cancelled]() -> JobOutput {
471 try {
472 FramePreview preview;
473 if (!exporting || encoding == "previewPng") {
474 auto encoded = frameCapturePreview(buffer, options);
475 if (!encoded) return {resultError(encoded.status())};
476 preview = std::move(encoded.value());
477 }
478 auto o = envelope("ready");
479 o->set("token", token);
480 o->set("jobToken", jobToken);
481 if (cancelled->load()) return {error("CancelledJob")};
482 o->set("frameId", static_cast<Poco::UInt64>(snapshotFrame));
483 o->set("buffer", bufferJson(buffer));
484 if (!exporting) {
485 o->set("width", preview.width);
486 o->set("height", preview.height);
487 o->set("view", preview.view);
488 o->set("channel", options.channel);
489 o->set("rangeMin", options.rangeMin);
490 o->set("rangeMax", options.rangeMax);
491 o->set("exposure", options.exposure);
492 return {imageContentResult(base64(preview.png), "image/png", mcpStringify(Poco::Dynamic::Var(o)))};
493 }
494 const std::filesystem::path destination(path);
495 if (!destination.parent_path().empty()) std::filesystem::create_directories(destination.parent_path());
496 auto temporary = destination;
497 temporary += "." + std::to_string(snapshotFrame) + "." +
498 std::to_string(std::hash<std::string>{}(jobToken)) + ".tmp";
499 ExportCleanup cleanup;
500 cleanup.paths.push_back(temporary);
501 const auto& bytes = encoding == "nativeBinary" ? *buffer.bytes : preview.png;
502 writeExportFile(temporary, reinterpret_cast<const char*>(bytes.data()), bytes.size());
503 if (cancelled->load()) return {error("CancelledJob")};
504 if (encoding == "nativeBinary") {
505 if constexpr (std::endian::native != std::endian::little) return {error("UnsupportedByteOrder")};
506 o->set("byteOrder", "little-endian");
507 o->set("rowStride", static_cast<Poco::UInt64>(buffer.width) * 4);
508 o->set("path", path);
509 auto inverseProjection = array();
510 for (float value : options.inverseProjection)
511 inverseProjection->add(std::isfinite(value) ? Poco::Dynamic::Var(value)
512 : Poco::Dynamic::Var("nonfinite"));
513 o->set("inverseProjectionColumnMajor", inverseProjection);
514 const std::filesystem::path metadataPath(path + ".json");
515 auto metadataTemporary = temporary;
516 metadataTemporary += ".json";
517 cleanup.paths.push_back(metadataTemporary);
518 const auto metadata = mcpStringify(Poco::Dynamic::Var(o));
519 writeExportFile(metadataTemporary, metadata.data(), metadata.size());
520 // A same-filesystem hard link publishes without replacing an existing destination.
521 std::filesystem::create_hard_link(metadataTemporary, metadataPath);
522 cleanup.paths.push_back(metadataPath);
523 }
524 if (cancelled->load()) return {error("CancelledJob")};
525 std::filesystem::create_hard_link(temporary, destination);
526 // The binary/PNG is the commit marker; metadata is already complete when it appears.
527 if (encoding == "nativeBinary") cleanup.paths.pop_back();
528 o->set("path", path);
529 o->set("bytes", static_cast<Poco::UInt64>(bytes.size()));
530 return {reply(o)};
531 } catch (const std::exception& e) {
532 return {error(std::string("ExportOrPreviewFailed: ") + e.what())};
533 }
534 });
535 jobs.emplace(jobToken, Job{caps.generation,
536 {token},
537 key,
538 std::move(future),
539 {},
540 std::chrono::steady_clock::now() + std::chrono::seconds(60),
541 std::move(cancelled)});
542 return pending(jobToken);
543}
544
545std::string_view mcpFrameCaptureSchemas() {
546 static const std::string schemas = [] {
547 std::string out;
548 const std::array<std::string, 8> names{
549 "eve_frame_capture_capabilities", "eve_frame_capture", "eve_frame_capture_status",
550 "eve_frame_buffer_image", "eve_frame_pixel", "eve_frame_capture_export",
551 "eve_frame_capture_release", "eve_frame_contact_sheet"};
552 for (const auto& name : names) {
553 auto tool = object();
554 tool->set("name", name);
555 tool->set("description",
556 "Immutable same-frame render capture. Request queues the next normal frame; status polls "
557 "capture/job tokens. Image/export return jobToken; poll status until ready. Pixels use original "
558 "top-left coordinates. No implicit gameplay advance.");
559 auto schema = object();
560 schema->set("type", "object");
561 schema->set("additionalProperties", false);
562 auto props = object();
563 auto required = array();
564 auto property = [&](const std::string& key, const std::string& type, bool need = false) {
565 auto p = object();
566 p->set("type", type);
567 props->set(key, p);
568 if (need) required->add(key);
569 };
570 if (name == "eve_frame_contact_sheet") {
571 tool->set("description",
572 "Compose 1-16 ready final-color capture tokens into a row-major PNG image. "
573 "Preserves aspect ratio with black letterboxing; no camera or gameplay changes. "
574 "This does not acquire views or certify equal simulation time. Returns jobToken; "
575 "poll eve_frame_capture_status for the image and source-cell metadata.");
576 property("tokens", "array", true);
577 auto items = object();
578 items->set("type", "string");
579 props->getObject("tokens")->set("items", items);
580 props->getObject("tokens")->set("minItems", 1);
581 props->getObject("tokens")->set("maxItems", 16);
582 property("columns", "integer");
583 property("cellWidth", "integer");
584 property("cellHeight", "integer");
585 property("maxBytes", "integer");
586 } else if (name == "eve_frame_capture") {
587 property("buffers", "array", true);
588 auto items = object();
589 items->set("type", "string");
590 props->getObject("buffers")->set("items", items);
591 property("timeoutMs", "integer");
592 property("onUnavailable", "string");
593 property("requestKey", "string");
594 } else if (name != "eve_frame_capture_capabilities") {
595 property("token", "string", true);
596 if (name == "eve_frame_buffer_image" || name == "eve_frame_pixel" || name == "eve_frame_capture_export")
597 property("buffer", "string", true);
598 if (name == "eve_frame_pixel") {
599 property("x", "integer", true);
600 property("y", "integer", true);
601 }
602 if (name == "eve_frame_buffer_image" || name == "eve_frame_capture_export") {
603 property("view", "string");
604 property("channel", "integer");
605 property("rangeMin", "number");
606 property("rangeMax", "number");
607 property("exposure", "number");
608 property("maxWidth", "integer");
609 property("maxHeight", "integer");
610 property("maxBytes", "integer");
611 }
612 if (name == "eve_frame_capture_export") {
613 property("encoding", "string", true);
614 property("path", "string", true);
615 }
616 }
617 auto enumeration = [&](const std::string& key, std::initializer_list<const char*> values) {
618 if (!props->has(key)) return;
619 auto list = array();
620 for (const auto* value : values) list->add(value);
621 props->getObject(key)->set("enum", list);
622 };
623 auto bounds = [&](const std::string& key, int low, int high) {
624 if (!props->has(key)) return;
625 props->getObject(key)->set("minimum", low);
626 props->getObject(key)->set("maximum", high);
627 };
628 enumeration("view",
629 {"auto", "rawChannels", "normalWorld", "velocity", "scalar", "linearDepth", "hdrExposure"});
630 enumeration("encoding", {"previewPng", "nativeBinary"});
631 enumeration("onUnavailable", {"fail", "report"});
632 bounds("timeoutMs", 100, 30000);
633 bounds("channel", 0, 3);
634 bounds("maxWidth", 1, 2048);
635 bounds("maxHeight", 1, 2048);
636 bounds("maxBytes", 1024, 16777216);
637 bounds("columns", 1, 16);
638 bounds("cellWidth", 1, 2048);
639 bounds("cellHeight", 1, 2048);
640 bounds("x", 0, 2147483647);
641 bounds("y", 0, 2147483647);
642 schema->set("properties", props);
643 schema->set("required", required);
644 tool->set("inputSchema", schema);
645 if (!out.empty()) out += ',';
646 out += mcpStringify(Poco::Dynamic::Var(tool));
647 }
648 return out;
649 }();
650 return schemas;
651}
652} // namespace eve::dev
653
654namespace eve::dev {
656} // namespace eve::dev
double y
double x
std::map< std::string, std::vector< Key >, std::less<> > channels
int root
Definition AnimSmr.cpp:119
std::vector< QuestEvent > pending
void * service
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
Generation generation
Definition ECS.cpp:40
std::string name
Definition ECS.cpp:154
std::string message
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
std::int32_t c
std::string encoding
bool required
std::chrono::steady_clock::time_point deadline
std::vector< std::string > captures
std::shared_ptr< std::atomic< bool > > cancelled
std::vector< std::filesystem::path > paths
std::string key
std::string response
std::future< JobOutput > future
Poco::JSON::Object::Ptr result
bool done
Snapshot snapshot
std::uint64_t bytes
#define EVE_MCP_TOOL_FAMILY(Id, Schemas, Handler, Payload)
Declare one family beside its implementation; CMake derives composition from compiled sources.
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanGpuFrameToken token
OceanSprayView view
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
bool finite
std::string error
Definition Package.cpp:174
float f
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::string path
Definition PlayHost.cpp:111
std::set< std::string > values
Object::Ptr value
RoadNetwork resolved
bool found
glm::dmat4 matrix
ScriptStructure out
std::vector< Token > tokens
std::string string
const SquirrelValueOptions & options
Cell cell
Json object
float size
Definition TreeMesh.cpp:158
int caps
Definition TreeMesh.cpp:164
std::uint32_t depth
const std::string & gameRoot() const
Definition McpServer.hpp:67
static McpServer & instance()
float getArgFloat(Poco::JSON::Object::Ptr args, const char *key, float def=0.f)
Floating-point argument, or def when absent or not convertible.
Definition McpArgs.hpp:55
void resetMcpFrameCapture()
Main-thread disconnect cleanup; workers observe cancellation before publishing files.
std::string_view mcpFrameCaptureSchemas()
Comma-separated schemas for tools/list.
std::string mcpStringify(const Poco::Dynamic::Var &value)
Compact single-line JSON text for a newline-framed MCP payload.
Definition McpJson.hpp:24
std::string textContentResult(const std::string &text, bool isError=false)
MCP tools/call result object carrying one text content item.
Definition McpJson.hpp:84
std::string imageContentResult(const std::string &base64Png, const std::string &mimeType, const std::string &caption)
MCP tools/call result object carrying one image content item.
Definition McpJson.hpp:102
std::string callMcpFrameCaptureTool(std::string_view name, Object::Ptr args)
int getArgInt(Poco::JSON::Object::Ptr args, const char *key, int def=0)
Integer argument, or def when absent or not convertible.
Definition McpArgs.hpp:35
bool isMcpFrameCaptureTool(std::string_view name)
True for the frame snapshot MCP family.
Result< FramePreview > frameContactSheet(std::span< const FrameCaptureBuffer > frames, const FrameContactSheetOptions &options)
std::string getArgString(Poco::JSON::Object::Ptr args, const char *key, const std::string &def={})
String argument, or def when absent or not convertible.
Definition McpArgs.hpp:25
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
Result< double > frameCaptureLinearDepth(const FrameCaptureBuffer &b, uint32_t x, uint32_t y, const std::array< float, 16 > &matrix)
Reconstruct positive view depth using this snapshot's projection. @thread Any thread with CPU leases.
Result< FramePixel > frameCapturePixel(const FrameCaptureBuffer &b, uint32_t x, uint32_t y)
Read CPU snapshot only; no callback, rendering, or GPU wait. @thread Any thread with a snapshot lease...
std::string_view frameAttachmentName(FrameAttachment a)
Stable protocol spelling of an attachment.
constexpr std::string_view statusCodeName(StatusCode code) noexcept
Return the stable protocol spelling of a status code.
Definition Status.h:46
Result< FrameAttachment > parseFrameAttachment(std::string_view name)
Validate a protocol attachment name without inventing a resource.
FramePixelFormat
CPU storage encoding; no GPU object escapes the provider.
std::string_view frameCapturePhaseName(FrameCapturePhase p)
Stable protocol spelling of a progress state.
enum EVENGINE_API_FOUNDATION Array
OT_ARRAY (editable via Runtime array APIs / ReflectedPropertyModel).
Definition Runtime.h:120
Owning request; timeout uses monotonic wall time, never gameplay time.
Bounded, row-major contact sheet of immutable final-color captures.
Explicit CPU preview transformation, separate from costly GPU capture.
std::array< float, 16 > inverseProjection
glm::vec4 bounds