29#include <glm/gtc/matrix_transform.hpp>
38#include <unordered_map>
39#include <unordered_set>
45constexpr float kPi = 3.14159265358979323846f;
47float degToRad(
float d) {
return d * kPi / 180.f; }
49std::string jsonEscape(
const std::string &
s) {
51 out.reserve(
s.size() + 8);
54 case '"':
out +=
"\\\"";
break;
55 case '\\':
out +=
"\\\\";
break;
56 case '\n':
out +=
"\\n";
break;
57 case '\r':
out +=
"\\r";
break;
58 case '\t':
out +=
"\\t";
break;
65std::string num(
float v) {
67 std::snprintf(buf,
sizeof(buf),
"%g",
static_cast<double>(
v));
71std::string vec3Json(
const glm::vec3 &
v) {
72 return "[" + num(
v.x) +
"," + num(
v.y) +
"," + num(
v.z) +
"]";
77 Graphics *gfx() {
return eve::ModuleManager::getInstance<Graphics>(
"Graphics"); }
80 if (ecs::current()->getManager<Camera3D>() !=
nullptr) {
81 auto view = ecs::View<Camera3D, Camera3D::Data>();
82 for (
auto it =
view.begin(); it !=
view.end(); ++it) {
84 if (data->active && data->entity)
return data->entity;
92 if (
auto *
g =
const_cast<RenderCaptureImpl *
>(
this)->gfx()) {
94 info.height =
g->getHeight();
95 info.pixelWidth =
g->getPixelWidth();
96 info.pixelHeight =
g->getPixelHeight();
97 info.had3DThisFrame =
g->had3DThisFrame();
98 info.readbackEnabled =
g->isScreenReadbackEnabled();
99 info.backend =
g->getBackendName();
104 void setReadbackEnabled(
bool enabled)
override {
105 if (
auto *
g = gfx())
g->setScreenReadbackEnabled(
enabled);
114 g->setScreenReadbackEnabled(
true);
115 image::ImageData *
frame =
nullptr;
117 frame =
g->newImageData();
121 "no presented frame yet: readback was just enabled and the "
122 "copy lands on the next present — call again after one frame "
123 "(screenshots need a running, presented game loop)",
129 "no presented frame (enable readback and render a frame first)",
"capture"));
131 filesystem::FileData *png =
nullptr;
133 png =
frame->encode(image::ImageData::FormatHandler::ENCODED_PNG,
"frame.png",
false);
145 std::filesystem::create_directories(std::filesystem::path(
path).parent_path(), ec);
146 std::ofstream
out(
path, std::ios::binary);
153 out.write(
static_cast<const char *
>(png->getData()),
154 static_cast<std::streamsize
>(png->getSize()));
155 const bool ok =
out.good();
164 info.height =
g->getPixelHeight();
168 std::string capturePngDataUrl()
override {
171 g->setScreenReadbackEnabled(
true);
172 image::ImageData *
frame =
nullptr;
174 frame =
g->newImageData();
178 if (!
frame)
return {};
179 filesystem::FileData *png =
nullptr;
181 png =
frame->encode(image::ImageData::FormatHandler::ENCODED_PNG,
"frame.png",
false);
191 char *b64 =
eve::b64_encode(
static_cast<const char *
>(png->getData()), png->getSize(), 0, len);
192 std::string url =
"data:image/png;base64," + std::string(b64 ? b64 :
"", len);
199 bool ensureCamera()
override {
return camera() !=
nullptr; }
201 bool setCameraPose(
float ex,
float ey,
float ez,
float tx,
float ty,
float tz,
202 float fovYDeg)
override {
204 if (!cam)
return false;
205 cam->setActive(
true);
206 cam->setEye(ex, ey, ez);
207 cam->setTarget(tx, ty, tz);
208 if (fovYDeg > 0.f) cam->setFov(fovYDeg);
212 bool setCameraPoseYawPitch(
float ex,
float ey,
float ez,
float yawDeg,
float pitchDeg,
213 float fovYDeg)
override {
215 if (!cam)
return false;
216 cam->setActive(
true);
217 const float yaw = degToRad(yawDeg);
218 const float pitch = degToRad(pitchDeg);
221 cam->setEye(ex, ey, ez);
222 cam->setTarget(ex +
dir.x * 100.f, ey +
dir.y * 100.f, ez +
dir.z * 100.f);
223 if (fovYDeg > 0.f) cam->setFov(fovYDeg);
227 std::string cameraPoseJson()
override {
229 if (!cam)
return "{\"error\":\"no camera\"}";
230 auto d = cam->data();
231 std::string
out =
"{\"eye\":" + vec3Json(glm::vec3(
d->eyeX,
d->eyeY,
d->eyeZ));
232 out +=
",\"target\":" + vec3Json(glm::vec3(
d->targetX,
d->targetY,
d->targetZ));
233 out +=
",\"up\":" + vec3Json(glm::vec3(
d->upX,
d->upY,
d->upZ));
234 out +=
",\"fov\":" + num(
d->fovYDeg);
235 out +=
",\"near\":" + num(
d->nearZ);
236 out +=
",\"far\":" + num(
d->farZ);
237 if (
auto *
g = gfx()) {
238 out +=
",\"viewportWidth\":" + std::to_string(
g->getPixelWidth());
239 out +=
",\"viewportHeight\":" + std::to_string(
g->getPixelHeight());
246 std::uint32_t entityId, std::uint32_t
generation)
override {
247 ecs::EntityHandle
handle{ecs::current(), std::type_index(
typeid(Renderable3D)),
249 auto* renderable =
dynamic_cast<Renderable3D*
>(ecs::try_get(
handle));
253 "Renderable3D handle is missing or stale",
"entity"));
254 auto transform = renderable->transform();
255 auto renderer = renderable->meshRenderer();
258 info.generation = renderable->generation;
259 info.x = transform->x;
260 info.y = transform->y;
261 info.z = transform->z;
280 std::string visibleEntitiesJson(
float fovYDeg,
bool *
ok)
override {
281 return visibleAt(
nullptr,
nullptr, fovYDeg,
ok);
284 std::string visibleEntitiesJsonAt(
float ex,
float ey,
float ez,
float tx,
float ty,
float tz,
285 float fovYDeg,
bool *
ok)
override {
286 const glm::vec3
eye(ex, ey, ez);
287 const glm::vec3
target(tx, ty, tz);
291 std::string entityIdMaskJson(
int *outWidth,
int *outHeight,
bool *
ok)
override {
294 if (!
g)
return "{\"error\":\"Graphics module not available\"}";
296 if (!cam)
return "{\"error\":\"no camera\"}";
297 auto d = cam->data();
298 const glm::vec3
eye(
d->eyeX,
d->eyeY,
d->eyeZ);
299 const glm::vec3
target(
d->targetX,
d->targetY,
d->targetZ);
300 const glm::vec3
up(
d->upX,
d->upY,
d->upZ);
301 const int vw =
g->getPixelWidth() > 0 ?
g->getPixelWidth() :
g->getWidth();
302 const int vh =
g->getPixelHeight() > 0 ?
g->getPixelHeight() :
g->getHeight();
303 if (outWidth) *outWidth = vw;
304 if (outHeight) *outHeight = vh;
305 if (vw <= 0 || vh <= 0)
return "{\"error\":\"empty viewport\"}";
306 const glm::mat4 viewM = glm::lookAtRH(
eye,
target,
up);
308 d->orthographic, degToRad(
d->fovYDeg),
d->orthoHeight,
309 float(vw) /
float(vh),
d->nearZ,
d->farZ);
310 const glm::mat4
viewProj = projM * viewM;
312 std::vector<EntityIdDraw> draws;
316 if (ecs::current()->getManager<scene::SceneHost>() !=
nullptr) {
317 auto hostView = ecs::View<scene::SceneHost, scene::SceneHost::Meta,
318 scene::SceneHost::Tree>();
319 for (
auto it = hostView.begin(); it != hostView.end(); ++it) {
320 auto [meta, tree] = *it;
321 if (!meta || !meta->entity || !tree)
continue;
322 auto *
host = meta->entity;
323 host->walkDepthFirst([&](scene::SceneHost *,
int, scene::SceneNode &
node) {
324 if (!
node.visible ||
node.space !=
"3d")
return;
326 if (!l || !l->target)
return;
327 auto *
r =
static_cast<Renderable3D *
>(l->target);
328 auto mr =
r->meshRenderer();
330 if (!
mesh || !
mesh->gpuHandle)
return;
334 const uint32_t packed = uint32_t(
id);
335 draw.idColor = glm::vec4((packed & 255u) / 255.f,
336 ((packed >> 8) & 255u) / 255.f,
337 ((packed >> 16) & 255u) / 255.f, 1.f);
338 draws.push_back(
draw);
340 entities +=
"{\"id\":" + std::to_string(
id) +
347 auto* capture =
g->visibilityCapture();
348 if (!capture)
return {};
349 image::ImageData* img = capture->renderEntityIdMask(draws,
viewProj, vw, vh);
350 if (!img)
return "{\"error\":\"id mask unsupported\"}";
353 return "{\"camera\":" + vec3Json(
eye) +
",\"viewportWidth\":" + std::to_string(vw) +
354 ",\"viewportHeight\":" + std::to_string(vh) +
",\"entities\":[" +
entities +
355 "],\"count\":" + std::to_string(
id - 1) +
"}";
369 auto d = cam->data();
370 const glm::vec3
eye(
d->eyeX,
d->eyeY,
d->eyeZ);
371 const glm::vec3
target(
d->targetX,
d->targetY,
d->targetZ);
372 const glm::vec3
up(
d->upX,
d->upY,
d->upZ);
373 const int vw =
g->getPixelWidth() > 0 ?
g->getPixelWidth() :
g->getWidth();
374 const int vh =
g->getPixelHeight() > 0 ?
g->getPixelHeight() :
g->getHeight();
375 if (vw <= 0 || vh <= 0) {
379 const glm::mat4 viewM = glm::lookAtRH(
eye,
target,
up);
381 d->orthographic, degToRad(
d->fovYDeg),
d->orthoHeight,
382 float(vw) /
float(vh),
d->nearZ,
d->farZ);
383 const glm::mat4
viewProj = projM * viewM;
384 std::vector<EntityIdDraw> draws;
387 if (ecs::current()->getManager<scene::SceneHost>() !=
nullptr) {
388 auto hostView = ecs::View<scene::SceneHost, scene::SceneHost::Meta,
389 scene::SceneHost::Tree>();
390 for (
auto it = hostView.begin(); it != hostView.end(); ++it) {
391 auto [meta, tree] = *it;
392 if (!meta || !meta->entity || !tree)
continue;
393 auto *
host = meta->entity;
394 host->walkDepthFirst([&](scene::SceneHost *,
int, scene::SceneNode &
node) {
395 if (!
node.visible ||
node.space !=
"3d")
return;
397 if (!l || !l->target)
return;
398 auto *
r =
static_cast<Renderable3D *
>(l->target);
399 auto mr =
r->meshRenderer();
401 if (!
mesh || !
mesh->gpuHandle)
return;
405 const uint32_t packed = uint32_t(
id);
406 draw.idColor = glm::vec4((packed & 255u) / 255.f,
407 ((packed >> 8) & 255u) / 255.f,
408 ((packed >> 16) & 255u) / 255.f, 1.f);
409 draws.push_back(
draw);
414 auto* capture =
g->visibilityCapture();
419 image::ImageData* img = capture->renderEntityIdMask(draws,
viewProj, vw, vh);
424 filesystem::FileData *png =
nullptr;
426 png = img->encode(image::ImageData::FormatHandler::ENCODED_PNG,
"id.png",
false);
435 std::filesystem::create_directories(std::filesystem::path(
path).parent_path(), ec);
436 std::ofstream
out(
path, std::ios::binary);
438 out.write(
static_cast<const char *
>(png->getData()),
439 static_cast<std::streamsize
>(png->getSize()));
458 image::ImageData *img =
g->readGBufferToImageData(
name);
463 filesystem::FileData *png =
nullptr;
465 png = img->encode(image::ImageData::FormatHandler::ENCODED_PNG,
"buf.png",
false);
477 std::filesystem::create_directories(std::filesystem::path(
path).parent_path(), ec);
478 std::ofstream
out(
path, std::ios::binary);
481 out.write(
static_cast<const char *
>(png->getData()),
static_cast<std::streamsize
>(png->getSize()));
494 std::string visibleAt(
const glm::vec3 *
eye,
const glm::vec3 *
target,
float fovYDeg,
500 glm::vec3 camEye(0.f, 1.8f, 3.f);
501 glm::vec3 camTarget(0.f, 1.2f, 0.f);
503 float camNear = 0.1f, camFar = 100.f;
505 auto d = cam->data();
506 camEye = glm::vec3(
d->eyeX,
d->eyeY,
d->eyeZ);
507 camTarget = glm::vec3(
d->targetX,
d->targetY,
d->targetZ);
516 if (fovYDeg > 0.f) camFov = fovYDeg;
518 const int vw =
g ?
g->getPixelWidth() : 1280;
519 const int vh =
g ?
g->getPixelHeight() : 720;
520 const glm::vec3
up(0.f, 1.f, 0.f);
521 const glm::mat4
view = glm::lookAtRH(camEye, camTarget,
up);
526 static const glm::vec3 kLocalCorners[8] = {
527 {-0.5f, -0.5f, -0.5f}, {0.5f, -0.5f, -0.5f}, {-0.5f, 0.5f, -0.5f},
528 {-0.5f, -0.5f, 0.5f}, {0.5f, 0.5f, -0.5f}, {0.5f, -0.5f, 0.5f},
529 {-0.5f, 0.5f, 0.5f}, {0.5f, 0.5f, 0.5f}};
534 if (ecs::current()->getManager<scene::SceneHost>() !=
nullptr) {
535 auto hostView = ecs::View<scene::SceneHost, scene::SceneHost::Meta,
536 scene::SceneHost::Tree>();
537 for (
auto it = hostView.begin(); it != hostView.end(); ++it) {
538 auto [meta, tree] = *it;
539 if (!meta || !meta->entity || !tree)
continue;
540 auto *
host = meta->entity;
541 host->walkDepthFirst([&](scene::SceneHost *,
int, scene::SceneNode &
node) {
542 if (!
node.visible ||
node.space !=
"3d")
return;
543 float minX = 1e30f, minY = 1e30f, minZ = 1e30f;
544 float maxX = -1e30f, maxY = -1e30f, maxZ = -1e30f;
545 float scMinX = 1e30f, scMinY = 1e30f;
546 float scMaxX = -1e30f, scMaxY = -1e30f;
547 bool anyInFront =
false;
548 for (
const auto &
c : kLocalCorners) {
549 const glm::vec4
w =
node.world * glm::vec4(
c, 1.f);
550 minX = std::min(minX,
w.x);
551 minY = std::min(minY,
w.y);
552 minZ = std::min(minZ,
w.z);
553 maxX = std::max(maxX,
w.x);
554 maxY = std::max(maxY,
w.y);
555 maxZ = std::max(maxZ,
w.z);
557 if (
clip.w <= 1e-6f)
continue;
561 const float sx = (ndcX * 0.5f + 0.5f) *
float(vw);
562 const float sy = (ndcY * 0.5f + 0.5f) *
float(vh);
563 scMinX = std::min(scMinX,
sx);
564 scMinY = std::min(scMinY,
sy);
565 scMaxX = std::max(scMaxX,
sx);
566 scMaxY = std::max(scMaxY,
sy);
568 if (!anyInFront)
return;
569 if (scMaxX < 0.f || scMinX >
float(vw) || scMaxY < 0.f ||
576 "\",\"world_aabb\":{\"min\":" + vec3Json(glm::vec3(minX, minY, minZ)) +
577 ",\"max\":" + vec3Json(glm::vec3(maxX, maxY, maxZ)) +
578 "},\"screen_bbox\":{\"x\":" + num(scMinX) +
",\"y\":" + num(scMinY) +
579 ",\"w\":" + num(scMaxX - scMinX) +
",\"h\":" + num(scMaxY - scMinY) +
586 return "{\"camera\":" + vec3Json(camEye) +
",\"cameraTarget\":" + vec3Json(camTarget) +
587 ",\"fov\":" + num(camFov) +
",\"viewportWidth\":" + std::to_string(vw) +
588 ",\"viewportHeight\":" + std::to_string(vh) +
",\"entities\":[" +
entities +
589 "],\"count\":" + std::to_string(
count) +
"}";
597 std::vector<eve::ProcgenProbeDesc>
lights;
600 Result<int> replaceProbeBatch(
const std::string& batchId,
601 const std::vector<eve::ProcgenProbeDesc>& probes)
override {
605 "procedural probe publication requires a batch id and graphics provider"));
608 for (
const auto& probe : probes) {
609 if (!probe.sourcePointId || !
identities.insert(probe.sourcePointId).second ||
610 probe.resource.empty() || (probe.type != 0 && probe.type != 1) ||
611 !std::isfinite(probe.x) || !std::isfinite(probe.y) || !std::isfinite(probe.z) ||
612 !std::isfinite(probe.extentX) || !std::isfinite(probe.extentY) || !std::isfinite(probe.extentZ) ||
613 probe.extentX <= 0 || probe.extentY <= 0 || probe.extentZ <= 0 ||
614 probe.resolution < 16 || probe.resolution > 2048 ||
615 !std::isfinite(probe.clipDistance) || probe.clipDistance <= 0 ||
616 !std::isfinite(probe.irradianceR) || !std::isfinite(probe.irradianceG) ||
617 !std::isfinite(probe.irradianceB) || probe.irradianceR < 0 || probe.irradianceG < 0 ||
618 probe.irradianceB < 0)
620 "procedural probe publication requires valid unique probe descriptors"));
621 if (probe.hasSphericalHarmonics &&
622 !std::all_of(probe.sphericalHarmonics.begin(), probe.sphericalHarmonics.end(),
623 [](
float coefficient) { return std::isfinite(coefficient); }))
625 "procedural light probe spherical harmonics must be finite"));
626 if (probe.type == 1) {
627 candidate.lights.push_back(probe);
630 auto capture = std::make_unique<ReflectionProbeCapture>(
graphics);
631 capture->configure(probe.x, probe.y, probe.z, probe.resolution, 0.1F, probe.clipDistance);
632 capture->configureInfluence(probe.extentX, probe.extentY, probe.extentZ, 1, 1, 0);
633 capture->requestCapture();
634 candidate.reflections.push_back(std::move(capture));
637 for (
auto& probe : candidate.
reflections) registry_->
add(probe.get());
638 auto found = batches_.find(batchId);
639 if (
found != batches_.end())
642 batches_.insert_or_assign(batchId, std::move(candidate));
646 Result<int> removeProbeBatch(
const std::string& batchId)
override {
647 auto found = batches_.find(batchId);
648 if (
found == batches_.end())
650 "procedural probe batch was not published", batchId));
651 const int count =
static_cast<int>(
found->second.reflections.size() +
found->second.lights.size());
655 batches_.erase(
found);
659 Result<int> tickProbeBatches(
int faceBudget,
int filterBudget,
int filterSamples)
override {
660 if (faceBudget < 0 || filterBudget < 0 || filterSamples < 8 || filterSamples > 512)
662 "procedural probe tick requires nonnegative budgets and 8..512 filter samples"));
666 int probeCount(
const std::string& batchId)
const override {
667 auto found = batches_.find(batchId);
668 return found == batches_.end() ? 0 :
static_cast<int>(
found->second.reflections.size() +
found->second.lights.size());
670 int reflectionProbeCount(
const std::string& batchId)
const override {
671 auto found = batches_.find(batchId);
672 return found == batches_.end() ? 0 :
static_cast<int>(
found->second.reflections.size());
674 int lightProbeCount(
const std::string& batchId)
const override {
675 auto found = batches_.find(batchId);
676 return found == batches_.end() ? 0 :
static_cast<int>(
found->second.lights.size());
679 void ensureRegistry() {
680 if (!registry_) registry_ = std::make_unique<ReflectionProbeRegistry>();
682 std::unique_ptr<ReflectionProbeRegistry> registry_;
683 std::unordered_map<std::string, Batch> batches_;
689 static RenderCaptureImpl
impl;
690 static ProcgenProbeSinkImpl probeSink;
691 eve::cap::provide<eve::IRenderCapture>(&
impl);
692 eve::cap::provide<eve::IProcgenProbeSink>(&probeSink);
std::vector< eve::ProcgenProbeDesc > lights
std::vector< std::unique_ptr< ReflectionProbeCapture > > reflections
wgpu::PopErrorScopeStatus status
Entity-ID / isolated visibility capture kept off Graphics.h.
std::shared_ptr< OceanRenderer > renderer
std::vector< ecs::EntityHandle > entities
std::set< std::string > identities
Renderable3D::MeshRenderer * mr
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Optional graphics consumer for complete generated probe batches. Implementations own all runtime reso...
Frame capture + camera + visible-entity inspection (graphics).
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
static Camera3D * createCamera(ecs::Table &table= *ecs::current())
Create an active camera in the current ECS table.
void removeBatch(const std::string &batchId)
Remove every diffuse probe owned by one generated batch.
void replaceBatch(const std::string &batchId, const std::vector< eve::ProcgenProbeDesc > &probes)
Atomically replace the diffuse probes owned by one generated batch.
static DiffuseLightProbeRegistry & instance()
Return the process-wide graphics-owned registry.
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
glm::mat4 cameraProjectionVulkanRH_ZO(bool orthographic, float fovyRad, float orthoHeight, float aspect, float zNear, float zFar)
Camera projection shared by rendering, picking, and diagnostic passes.
glm::mat4 perspectiveVulkanRH_ZO(float fovyRad, float aspect, float zNear, float zFar)
Right-handed, zero-to-one depth perspective for Vulkan swapchains.
void registerGraphicsCapabilities()
Registers graphics capabilities.
ForceVector add(ForceVector a, ForceVector b)
int findLinkKind(const char *kind)
Finds link kind.
char * b64_encode(const char *src, size_t srclen, size_t linelen, size_t &dstlen)
Base64-encode data.
Pixel size reported by a successful frame/image capture.
Render surface / frame state snapshot (value type).
Generation-qualified snapshot of one live field-backed Renderable3D.