Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderFramePlanar.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#include "RenderFrame.hpp"
8#include "../../core/Log.hpp"
9#include <glm/gtc/type_ptr.hpp>
10#include <string>
11
12namespace esengine {
13void RenderFrame::setPlanarQuality(f32 scale, u32 maxSize, f32 rate, bool capAuthored) {
14 planar_scale_ = std::isfinite(scale) ? std::clamp(scale, 0.125f, 1.0f) : 0.5f;
15 planar_max_size_ = std::clamp(maxSize, 64u, 4096u);
16 planar_rate_ = std::isfinite(rate) ? std::clamp(rate, 0.0f, 120.0f) : 0.0f;
17 planar_capped_ = capAuthored;
18}
19
20void RenderFrame::releasePlanarCaptures() {
21 for (auto& [view, capture] : planar_captures_) {
22 if (capture.frameUbo != BufferHandle::Invalid) device_.deleteBuffer(capture.frameUbo);
23 }
24 planar_captures_.clear();
25 planar_receiver_ = INVALID_ENTITY;
26 planar_texture_ = 0;
27 planar_resource_ = rg::kNoResource;
28}
29
30void RenderFrame::declarePlanarReflection(ecs::Registry& registry) {
31 planar_receiver_ = INVALID_ENTITY;
32 planar_texture_ = 0;
33 planar_resource_ = rg::kNoResource;
34 if (scene_resource_ == rg::kNoResource) return;
35 auto surfaces = registry.activeView<ecs::Transform, ecs::MeshRenderer, ecs::PlanarReflection>();
36 Entity selected = INVALID_ENTITY;
37 PlanarReflectionCamera camera;
38 u32 eligible = 0;
39 for (const Entity entity : surfaces) {
40 if (screen_domain_ && screen_domain_->count(entity.id()) != 0) continue;
41 const auto& surface = surfaces.get<ecs::PlanarReflection>(entity);
42 const auto& mesh = surfaces.get<ecs::MeshRenderer>(entity);
43 if (!surface.enabled || !mesh.enabled || !mesh.mesh.isValid()
44 || !draw_list_.layerVisible(DrawList::layerBit(mesh.layer))) continue;
45 const Mesh* geometry = resource_manager_.getMesh(mesh.mesh);
46 if (!geometry || !geometry->isDrawable()) continue;
47 auto& transform = surfaces.get<ecs::Transform>(entity);
48 transform.ensureDecomposed();
49 glm::vec3 centre, half;
50 orientedWorldAabb(rebased(transform.worldPosition), transform.worldRotation, transform.worldScale,
51 geometry->localMin, geometry->localMax, centre, half);
52 if (!frustum_.intersectsAABB(centre, half)) continue;
53 const u32 axis = static_cast<u32>(surface.axis);
54 if (axis > 2 || std::abs(transform.worldScale[axis]) < 1e-6f) continue;
55 glm::vec3 normal(0.0f); normal[axis] = 1.0f;
56 PlanarReflectionCamera candidate;
57 if (!planarReflectionCamera(view_projection_, rebased(transform.worldPosition),
58 transform.worldRotation * normal, surface.clipOffset, candidate)) continue;
59 ++eligible;
60 // A stable winner, independent of sparse-set iteration and camera movement.
61 if (selected != INVALID_ENTITY && selected.id() < entity.id()) continue;
62 selected = entity;
63 camera = candidate;
64 }
65 if (selected == INVALID_ENTITY) {
66 const auto previous = planar_captures_.find(view_id_);
67 if (previous != planar_captures_.end()) {
68 if (previous->second.frameUbo != BufferHandle::Invalid) device_.deleteBuffer(previous->second.frameUbo);
69 planar_captures_.erase(previous);
70 }
71 return;
72 }
73 const auto& surface = registry.get<ecs::PlanarReflection>(selected);
74 auto& capture = planar_captures_[view_id_];
75 capture.lastSeen = planar_frame_;
76 capture.rejected = eligible - 1;
77 const bool project = surface.quality == ecs::ReflectionQuality::Project;
78 const bool capped = planar_capped_ && !project;
79 const f32 requestedScale = project ? planar_scale_ : surface.resolutionScale;
80 const f32 authoredScale = std::isfinite(requestedScale) ? std::clamp(requestedScale, 0.125f, 1.0f) : 0.5f;
81 const f32 scale = capped ? std::min(authoredScale, planar_scale_) : authoredScale;
82 const u32 authoredLimit = std::clamp(project ? planar_max_size_ : surface.maxSize, 64u, 4096u);
83 const u32 limit = capped ? std::min(authoredLimit, planar_max_size_) : authoredLimit;
84 u32 sourceW = scene_viewport_.w ? scene_viewport_.w : width_;
85 u32 sourceH = scene_viewport_.h ? scene_viewport_.h : height_;
86 if (auto* target = target_manager_.get(current_target_); target && !scene_viewport_.w) {
87 sourceW = target->getWidth(); sourceH = target->getHeight();
88 }
89 const f32 ratio = std::min(scale, static_cast<f32>(limit) / std::max({sourceW, sourceH, 1u}));
90 const u32 w = std::max(1u, static_cast<u32>(std::round(sourceW * ratio)));
91 const u32 h = std::max(1u, static_cast<u32>(std::round(sourceH * ratio)));
92 GfxPixelFormat format = linear_color_ && device_.supportsFloatTargets()
94 // A driver can claim float targets and still refuse this one; remember that and stay with 8 bits.
95 if (planar_float_refused_) format = GfxPixelFormat::RGBA8;
96 const bool generationChanged = capture.generation != device_.deviceGeneration();
97 if (!capture.target || capture.target->getWidth() != w || capture.target->getHeight() != h
98 || capture.target->getSpecification().colorFormat != format) {
99 FramebufferSpec spec;
100 spec.width = w; spec.height = h; spec.linearFilter = true;
101 spec.depthStencil = true; spec.colorFormat = format;
102 capture.target = Framebuffer::create(device_, spec);
103 if (!capture.target && format == GfxPixelFormat::RGBA16F) {
104 ES_LOG_WARN("Planar reflection: a {}x{} float capture target was refused, falling back to RGBA8", w, h);
105 planar_float_refused_ = true;
106 format = GfxPixelFormat::RGBA8;
107 spec.colorFormat = format;
108 capture.target = Framebuffer::create(device_, spec);
109 }
110 capture.valid = false;
111 }
112 if (!capture.target) return;
113 const bool rateCapped = capped && planar_rate_ > 0 && surface.update != ecs::ReflectionUpdate::OnDemand;
114 const auto policy = project || rateCapped ? (planar_rate_ > 0 ? ecs::ReflectionUpdate::FixedRate : ecs::ReflectionUpdate::EveryFrame) : surface.update;
115 const f32 requestedRate = project ? planar_rate_ : surface.updatesPerSecond;
116 const f32 authoredRate = std::isfinite(requestedRate) ? std::clamp(requestedRate, 1.0f, 120.0f) : 30.0f;
117 const f32 rate = rateCapped ? (surface.update == ecs::ReflectionUpdate::FixedRate ? std::min(authoredRate, planar_rate_) : planar_rate_)
118 : authoredRate;
119 const bool due = !capture.valid || generationChanged || capture.receiver != selected
120 || capture.revision != surface.revision || capture.mask != surface.cullingMask
122 || (policy == ecs::ReflectionUpdate::FixedRate && (planar_elapsed_ < capture.lastTime
123 || planar_elapsed_ - capture.lastTime >= 1.0f / rate));
124 const auto resource = graph_.importTarget(capture.target->handle(), w, h, /*output=*/false);
125 if (due) {
126 capture.receiver = selected;
127 capture.camera = camera;
128 capture.mask = surface.cullingMask;
129 capture.revision = surface.revision;
130 capture.generation = device_.deviceGeneration();
131 rg::PassDesc pass;
132 pass.name = "planar-reflection";
133 pass.write = resource;
134 pass.clear = pass.clearDepth = true;
135 for (u32 i = 0; i < 4; ++i) pass.clearColor[i] = scene_clear_[i];
136 if (shadow_resource_ != rg::kNoResource) pass.dependencies.push_back(shadow_resource_);
137 const u32 view = view_id_;
138 collectPlanarReflection(registry, view);
139 pass.execute = [this, view](const rg::PassContext&) { executePlanarReflection(view); };
140 graph_.addPass(std::move(pass));
141 }
142 // Imported targets do not publish a texture until explicitly named.
143 planar_resource_ = resource;
144 planar_receiver_ = selected;
145 planar_texture_ = static_cast<u32>(capture.target->getColorAttachment());
146 planar_constants_.projection = capture.camera.samplingProjection;
147 // y: the rows' direction, 1 on every backend now that WebGPU lays a target's rows bottom-up as GL does.
148 planar_constants_.params = {1.0f, 1.0f, 1.0f / w, 1.0f / h};
149}
150
151void RenderFrame::collectPlanarReflection(ecs::Registry& registry, u32 view) {
152 auto& capture = planar_captures_.at(view);
153 planar_pool_.beginFrame();
154 planar_list_.clear();
155 planar_list_.setCullingMask(capture.mask);
156 planar_list_.setDepthMask(draw_list_.depthMask());
157 planar_list_.setYSortMask(draw_list_.ySortMask());
158 auto ctx = makeContext();
159 ctx.view_projection = capture.camera.projection;
160 Frustum frustum;
161 frustum.extractFromMatrix(ctx.view_projection);
162 RenderCollectContext collect{registry, frustum, clip_state_, planar_pool_, planar_list_, ctx,
163 computeCameraView(ctx.view_projection)};
164 collect.screen_ui = screen_domain_;
165 collect.ui_tree_layers = ui_tree_layers_;
166 collect.excluded = capture.receiver;
167 collectSky(collect);
168 // No recursive frame/scene collect, post-processing, host overlays or HUD.
169 for (auto& plugin : plugins_) plugin->collect(collect);
170}
171
172void RenderFrame::executePlanarReflection(u32 view) {
173 auto& capture = planar_captures_.at(view);
174 if (capture.frameUbo == BufferHandle::Invalid) {
175 capture.frameUbo = device_.createBuffer({GfxBufferUsage::Uniform, RenderContext::frameConstantsSize(), true}, GfxContent::transient(), nullptr);
176 }
177 if (capture.frameUbo == BufferHandle::Invalid) return;
178 planar_list_.finalize(planar_pool_);
179 planar_pool_.upload();
180 context_.useFrameConstants(capture.frameUbo,
181 toClipDepthRange(capture.camera.projection, device_.clipDepthRange()));
182 auto& lights = context_.lights();
183 lights.setTiledView(capture.camera.projection);
184 lights.uploadAndBind();
185 submitColorList(planar_list_, planar_pool_, nullptr, DrawList::Phase::All, "render.planar.prepass.draws");
186 lights.setTiledView(view_projection_);
187 ES_PROFILE_COUNTER("render.planar.tiledLights", lights.tiledCount());
188 capture.valid = true;
189 capture.lastTime = planar_elapsed_;
190 capture.draws = planar_list_.mergedDrawCallCount();
191 accumulateStats(planar_list_);
192 tallyPass(planar_list_);
193 ES_PROFILE_COUNTER("render.planar.draws", capture.draws);
194 ES_PROFILE_COUNTER("render.planar.rejected", capture.rejected);
195 device_.invalidatePipelineCache();
196}
197
198std::string RenderFrame::planarStatus(u32 view, u32 entity) const {
199 const auto found = planar_captures_.find(view);
200 if (found == planar_captures_.end()) return "{\"state\":\"inactive\"}";
201 const auto& c = found->second;
202 if (c.receiver.id() != entity) return "{\"state\":\"budget-excluded\"}";
203 if (!c.valid || !c.target) return "{\"state\":\"unavailable\"}";
204 const auto& spec = c.target->getSpecification();
205 const u64 bytes = static_cast<u64>(spec.width) * spec.height * (spec.colorFormat == GfxPixelFormat::RGBA16F ? 12u : 8u);
206 return "{\"state\":\"ready\",\"width\":" + std::to_string(spec.width) + ",\"height\":" + std::to_string(spec.height)
207 + ",\"draws\":" + std::to_string(c.draws) + ",\"bytes\":" + std::to_string(bytes)
208 + ",\"rejected\":" + std::to_string(c.rejected) + ",\"updated\":" + (c.lastTime == planar_elapsed_ ? "true" : "false") + "}";
209}
210} // 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_WARN(...)
Logs a warning message.
Definition Log.hpp:294
Arbitrary-geometry 2D mesh renderable (deformed sprites, polygons, water surfaces,...
Geometry that lives on the GPU rather than in a frame.
Frame resources and the shared scene rendering contract.
static u32 layerBit(i32 layer)
The mask bit of a sorting layer, or 0 when it has none (outside 0..31).
Definition DrawList.hpp:227
static Unique< Framebuffer > create(GfxDevice &device, const FramebufferSpec &spec)
Creates a framebuffer from specification.
static constexpr GfxContent transient()
void deleteBuffer(BufferHandle buffer)
Deletes a buffer.
static u32 frameConstantsSize()
Bytes a buffer passed to useFrameConstants must hold.
void setPlanarQuality(f32 scale, u32 maxSize, f32 updatesPerSecond, bool capAuthored)
std::string planarStatus(u32 view, u32 entity) const
Central container for all entities and components.
Definition Registry.hpp:73
void update(Instance *instance, float dt)
constexpr ResourceId kNoResource
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
glm::mat4 toClipDepthRange(const glm::mat4 &p, ClipDepthRange range)
The projection p as a device keeping range wants it.
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)
void orientedWorldAabb(const glm::vec3 &position, const glm::quat &rotation, const glm::vec3 &scale, const glm::vec3 &localMin, const glm::vec3 &localMax, glm::vec3 &outCentre, glm::vec3 &outHalf)
The world AABB of a turned box: its centre and half-extents, from a local box and the position,...
bool planarReflectionCamera(const glm::mat4 &source, const glm::vec3 &origin, glm::vec3 normal, f32 offset, PlanarReflectionCamera &out)
static EstellaContext & ctx()
float f32
32-bit floating point
Definition Types.hpp:59
constexpr u32 id() const
Returns the raw packed value for FFI serialization.
Definition Types.hpp:159