Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderFrameProbeCapture.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
13#include "RenderFrame.hpp"
14#ifdef ES_ENABLE_POSTPROCESS
16#endif
18#include "../../core/Log.hpp"
19
20#include <glm/gtc/constants.hpp>
21#include <glm/gtc/matrix_transform.hpp>
22
23namespace esengine {
24
25namespace {
26
27// Toward each face, and its up: the SDK's probeCapture.ts builds the same bases to read the faces back.
28constexpr glm::vec3 kFaceDir[6] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
29constexpr glm::vec3 kFaceUp[6] = {{0, 1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}, {0, 1, 0}, {0, 1, 0}};
30
31} // namespace
32
33void RenderFrame::requestProbeCapture(const glm::vec3& position, u32 face) {
34 ProbeCapture& c = probe_capture_;
35 c.position = position;
36 c.face = std::clamp(face, 8u, 128u);
37 c.next = 0;
38 c.state = ProbeCapture::State::Capturing;
39 c.readback = ReadbackHandle::Invalid;
40}
41
43 ProbeCapture& c = probe_capture_;
44 switch (c.state) {
45 case ProbeCapture::State::Idle: return 2;
46 case ProbeCapture::State::Capturing: return 0;
47 case ProbeCapture::State::Drawn:
48 c.readback = c.atlas ? device_.requestReadback(c.atlas->handle(), c.face * 6, c.face) : ReadbackHandle::Invalid;
49 if (c.readback == ReadbackHandle::Invalid) { c.state = ProbeCapture::State::Idle; return 2; }
50 c.state = ProbeCapture::State::Reading;
51 [[fallthrough]];
52 case ProbeCapture::State::Reading: {
53 const GfxReadbackStatus status = device_.pollReadback(c.readback);
54 if (status == GfxReadbackStatus::Pending) return 0;
55 c.state = ProbeCapture::State::Idle;
56 if (status != GfxReadbackStatus::Ready) return 2;
57 c.pixels.resize(static_cast<usize>(c.face) * 6 * c.face * 4);
58 return device_.takeReadback(c.readback, c.pixels.data(), c.pixels.size()) ? 1 : 2;
59 }
60 }
61 return 2;
62}
63
64void RenderFrame::declareProbeCapture(ecs::Registry& registry) {
65#ifdef ES_ENABLE_POSTPROCESS
66 ProbeCapture& c = probe_capture_;
67 // One face a frame, whichever camera's collect comes first.
68 if (c.state != ProbeCapture::State::Capturing || c.frame == planar_frame_ || !post_process_) return;
69 c.frame = planar_frame_;
70 const u32 n = c.face;
71 const GfxPixelFormat format = linear_color_ && device_.supportsFloatTargets() && !planar_float_refused_
73 const u32 f = std::min(c.next, 5u);
74 auto& target = c.faces[f];
75 if (!target || target->getWidth() != n || target->getSpecification().colorFormat != format) {
76 FramebufferSpec spec;
77 spec.width = n; spec.height = n; spec.linearFilter = false;
78 spec.depthStencil = true; spec.colorFormat = format;
79 target = Framebuffer::create(device_, spec);
80 }
81 if (!c.atlas || c.atlas->getWidth() != n * 6 || c.atlas->getHeight() != n) {
82 FramebufferSpec spec;
83 spec.width = n * 6; spec.height = n; spec.linearFilter = false;
84 spec.depthStencil = false; spec.colorFormat = GfxPixelFormat::RGBA8;
85 c.atlas = Framebuffer::create(device_, spec);
86 }
87 if (!target || !c.atlas) {
88 ES_LOG_ERROR("Probe capture: could not make its {}x{} targets", n, n);
89 c.state = ProbeCapture::State::Idle;
90 return;
91 }
92
93 const f32 metre = world_units_per_meter_;
94 const glm::vec3 at = rebased(c.position);
95 c.viewProjection = glm::perspective(glm::half_pi<f32>(), 1.0f, 0.05f * metre, 4000.0f * metre)
96 * glm::lookAt(at, at + kFaceDir[f], kFaceUp[f]);
97
98 rg::PassDesc face;
99 face.name = "probe-capture-face";
100 face.write = graph_.importTarget(target->handle(), n, n, /*output=*/false, target->getColorAttachment());
101 face.clear = face.clearDepth = true;
102 for (u32 i = 0; i < 4; ++i) face.clearColor[i] = 0.0f;
103 face.keep = true;
104 if (shadow_resource_ != rg::kNoResource) face.dependencies.push_back(shadow_resource_);
105 collectProbeFace(registry);
106 face.execute = [this](const rg::PassContext&) { executeProbeFace(); };
107 const rg::ResourceId faceResource = face.write;
108 graph_.addPass(std::move(face));
109
110 rg::PassDesc pack;
111 pack.name = "probe-capture-pack";
112 pack.reads = {faceResource};
113 pack.write = graph_.importTarget(c.atlas->handle(), n * 6, n, /*output=*/false, c.atlas->getColorAttachment());
114 pack.keep = true;
115 pack.viewportX = f * n;
116 pack.viewportY = 0;
117 pack.viewportW = n;
118 pack.viewportH = n;
119 // The face counts as done when it is DRAWN, not when it is declared: a frame whose graph is built and not run would
120 // otherwise skip it for good, and the last one would leave the capture waiting for ever.
121 pack.execute = [this, f](const rg::PassContext&) {
122 post_process_->encodeRgbm();
123 ProbeCapture& done = probe_capture_;
124 if (done.state != ProbeCapture::State::Capturing || done.next != f) return;
125 done.next = f + 1;
126 if (f == 5) done.state = ProbeCapture::State::Drawn;
127 };
128 graph_.addPass(std::move(pack));
129#else
130 (void)registry;
131#endif
132}
133
134void RenderFrame::collectProbeFace(ecs::Registry& registry) {
135 auto& c = probe_capture_;
136 probe_pool_.beginFrame();
137 probe_list_.clear();
138 probe_list_.setCullingMask(0xFFFFFFFFu);
139 probe_list_.setDepthMask(draw_list_.depthMask());
140 probe_list_.setYSortMask(draw_list_.ySortMask());
141 auto ctx = makeContext();
142 ctx.view_projection = c.viewProjection;
143 Frustum frustum;
144 frustum.extractFromMatrix(ctx.view_projection);
145 RenderCollectContext collect{registry, frustum, clip_state_, probe_pool_, probe_list_, ctx,
146 computeCameraView(ctx.view_projection)};
147 collect.screen_ui = screen_domain_;
148 collect.ui_tree_layers = ui_tree_layers_;
149 collectSky(collect);
150 // The scene as lit, and nothing after it: no post-processing, overlays or HUD.
151 for (auto& plugin : plugins_) plugin->collect(collect);
152}
153
154void RenderFrame::executeProbeFace() {
155 ProbeCapture& c = probe_capture_;
156 if (c.frameUbo == BufferHandle::Invalid) {
157 c.frameUbo = device_.createBuffer({GfxBufferUsage::Uniform, RenderContext::frameConstantsSize(), true},
158 GfxContent::transient(), nullptr);
159 }
160 if (c.frameUbo == BufferHandle::Invalid) return;
161 probe_list_.finalize(probe_pool_);
162 probe_pool_.upload();
163 context_.useFrameConstants(c.frameUbo, toClipDepthRange(c.viewProjection, device_.clipDepthRange()));
164 // The lights as the frame packed them; a light past the sixteen direct slots keeps the main view's tiles.
165 context_.lights().uploadAndBind();
166 submitColorList(probe_list_, probe_pool_, nullptr, DrawList::Phase::All, "render.probe.draws");
167 ES_PROFILE_COUNTER("render.probe.draws", probe_list_.mergedDrawCallCount());
168 device_.invalidatePipelineCache();
169}
170
172 if (grid.isValid()) probe_overrides_[entity] = grid;
173 else probe_overrides_.erase(entity);
174}
175
176} // namespace esengine
Per-frame CPU scope timing (ES_PROFILE_SCOPE) read by the editor profiler.
#define ES_PROFILE_COUNTER(name, value)
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
Post-processing effects pipeline.
Frame resources and the shared scene rendering contract.
static Unique< Framebuffer > create(GfxDevice &device, const FramebufferSpec &spec)
Creates a framebuffer from specification.
static constexpr GfxContent transient()
virtual bool supportsFloatTargets()=0
Whether RGBA16F color attachments are renderable.
static u32 frameConstantsSize()
Bytes a buffer passed to useFrameConstants must hold.
void requestProbeCapture(const glm::vec3 &position, u32 face)
Capture the scene around position (world) into six face-pixel faces, one a frame, and read them back:...
void setProbeVolumeOverride(u32 entity, resource::ProbeVolumeHandle grid)
The grid a volume reads instead of its own probes (a capture's), or an invalid handle to stop.
i32 pollProbeCapture()
0 = not yet, 1 = ready (probeCapturePixels), 2 = none asked for or it failed. Between frames only.
Central container for all entities and components.
Definition Registry.hpp:73
bool isValid() const
Checks if the handle references a valid resource.
Definition Handle.hpp:82
Handle< esengine::ProbeVolume > ProbeVolumeHandle
Handle to a grid of baked irradiance.
Definition Handle.hpp:232
constexpr ResourceId kNoResource
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
glm::mat4 toClipDepthRange(const glm::mat4 &p, ClipDepthRange range)
The projection p as a device keeping range wants it.
GfxReadbackStatus
State of an in-flight readback. GL completes at request time (first poll reports Ready); WebGPU resol...
Definition GfxEnums.hpp:47
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
glm::vec3 rebased(const glm::vec3 &world)
A world position as the frame draws it: from the origin.
CameraView computeCameraView(const glm::mat4 &viewProjection)
static EstellaContext & ctx()
float f32
32-bit floating point
Definition Types.hpp:59
Framebuffer creation parameters.
GfxPixelFormat colorFormat
Color attachment format. RGBA16F needs GfxDevice::supportsFloatTargets.
bool depthStencil
Whether to create depth/stencil attachment.
bool linearFilter
Texture filter mode: false=GL_NEAREST, true=GL_LINEAR.
u32 height
Framebuffer height in pixels.
u32 width
Framebuffer width in pixels.