Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderContext.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
14#include "./RenderContext.hpp"
15#include "./RippleNormals.hpp"
16#include "../rhi/GfxDevice.hpp"
17#include "./FrameConstants.hpp"
18#include "../RenderOrigin.hpp"
24#include "../../core/Log.hpp"
25
26#include <cmath>
27#include <vector>
28
29#include <glm/gtc/type_ptr.hpp>
30
31namespace esengine {
32
34 : device_(device) {
35}
36
38 if (initialized_) {
39 shutdown();
40 }
41}
42
44 if (initialized_) {
45 ES_LOG_WARN("RenderContext already initialized");
46 return;
47 }
48
49 device_.init();
50 initDefaultTextures();
51 initFrameUbo();
52 materials_.setDevice(&device_);
53 materials_.setBuiltinDefaults(whiteTexture_, blackTexture_, flatNormalTexture_, ripplesTexture_);
54 materials_.setBuiltinDefaultArrays(whiteArrayTexture_, blackArrayTexture_, flatNormalArrayTexture_);
55 lights_.setDevice(&device_);
56
57 initialized_ = true;
58}
59
61 if (!initialized_) {
62 return;
63 }
64
65 for (TextureHandle* tex : {&whiteTexture_, &blackTexture_, &flatNormalTexture_, &ripplesTexture_, &whiteArrayTexture_,
66 &blackArrayTexture_, &flatNormalArrayTexture_}) {
67 if (*tex != TextureHandle::Invalid) {
68 device_.deleteTexture(*tex);
70 }
71 }
72
73 if (frameUbo_ != BufferHandle::Invalid) {
74 device_.deleteBuffer(frameUbo_);
75 frameUbo_ = BufferHandle::Invalid;
76 }
77 if (timeUbo_ != BufferHandle::Invalid) {
78 device_.deleteBuffer(timeUbo_);
79 timeUbo_ = BufferHandle::Invalid;
80 }
81 if (drawParamsFallback_ != BufferHandle::Invalid) {
82 device_.deleteBuffer(drawParamsFallback_);
83 drawParamsFallback_ = BufferHandle::Invalid;
84 }
85 skinBlocks_.shutdown();
86 probeBlocks_.shutdown();
87 instanceBlocks_.shutdown();
88 planarBlocks_.shutdown();
89
90 materials_.clear(); // free per-material UBOs while the device is still valid
91 materials_.setResourceManager(nullptr);
92 lights_.free(); // free the lighting UBO while the device is still valid
93
94 device_.shutdown();
95 initialized_ = false;
96 ES_LOG_INFO("RenderContext shutdown");
97}
98
99TextureHandle RenderContext::make1x1Texture(u32 rgba, u32 layers) {
100 TextureDesc desc;
101 desc.width = 1;
102 desc.height = 1;
103 desc.layers = layers;
106 const std::vector<u32> texels(layers, rgba);
107 return device_.createTexture(desc, GfxContent::retained(), texels.data());
108}
109
110namespace {
112constexpr u32 BUILTIN_CONTENT_PROVIDER = 0x4255494C;
113constexpr u32 BUILTIN_RIPPLES = 1;
114} // namespace
115
116TextureHandle RenderContext::makeRipplesTexture() {
117 TextureDesc desc;
119 desc.height = RIPPLE_NORMALS_SIZE;
120 desc.wrapS = TextureWrap::Repeat;
121 desc.wrapT = TextureWrap::Repeat;
122 desc.mipmaps = true;
123 const std::vector<u8> pixels = buildRippleNormals();
124 const TextureHandle texture =
125 device_.createTexture(desc, GfxContent::sourced(BUILTIN_CONTENT_PROVIDER, BUILTIN_RIPPLES), pixels.data());
126 if (texture != TextureHandle::Invalid) device_.generateMipmaps(texture);
127 return texture;
128}
129
131 for (const GfxOwedContent& owed : device_.owedContent()) {
132 if (owed.kind != GfxOwedContent::Kind::Texture || owed.provider != BUILTIN_CONTENT_PROVIDER) continue;
133 if (owed.key != BUILTIN_RIPPLES || ripplesTexture_ == TextureHandle::Invalid) {
134 device_.forgoContent(owed);
135 continue;
136 }
137 const std::vector<u8> pixels = buildRippleNormals();
138 device_.updateTexture(ripplesTexture_, 0, 0, RIPPLE_NORMALS_SIZE, RIPPLE_NORMALS_SIZE, pixels.data(), false);
139 device_.restoreContent(owed);
140 }
141}
142
143void RenderContext::initDefaultTextures() {
144 // Byte order in memory is R,G,B,A; these u32s are little-endian (so 0xAABBGGRR).
145 whiteTexture_ = make1x1Texture(0xFFFFFFFF); // RGBA(255,255,255,255)
146 blackTexture_ = make1x1Texture(0xFF000000); // RGBA(0,0,0,255)
147 flatNormalTexture_ = make1x1Texture(0xFFFF8080); // RGB(128,128,255) → normal (0,0,1)
148 whiteArrayTexture_ = make1x1Texture(0xFFFFFFFF, 2);
149 blackArrayTexture_ = make1x1Texture(0xFF000000, 2);
150 flatNormalArrayTexture_ = make1x1Texture(0xFFFF8080, 2);
151 ripplesTexture_ = makeRipplesTexture();
152 ES_LOG_DEBUG("Default textures created (white {}, black {}, flatNormal {})",
153 static_cast<u32>(whiteTexture_), static_cast<u32>(blackTexture_),
154 static_cast<u32>(flatNormalTexture_));
155}
156
157void RenderContext::initFrameUbo() {
158 FrameConstants initial{};
159 frameUbo_ = device_.createBuffer(
160 {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(FrameConstants)), /*dynamic=*/true},
161 GfxContent::retained(), &initial);
162
163 // The binding slot persists for the context lifetime; only the contents change
164 // per frame. Every engine shader's FrameConstants block is linked to this slot
165 // at compile time (Shader::compile).
166 device_.setUniformBuffer(FRAME_CONSTANTS_BINDING, frameUbo_);
167
168 TimeConstants time{};
169 timeUbo_ = device_.createBuffer(
170 {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(TimeConstants)), /*dynamic=*/true},
171 GfxContent::retained(), &time);
172 device_.setUniformBuffer(TIME_CONSTANTS_BINDING, timeUbo_);
173
174 // Zeroed fallback for the shared per-draw params slot: a shader whose loose
175 // uniforms were lifted into a DrawParams block but whose draw path never
176 // commits (e.g. a raw material shader drawn by the batch path) must still
177 // find a buffer covering its block there — members then read zero, exactly
178 // what their loose-uniform ancestors read.
179 const std::vector<u8> zeros(DRAW_PARAMS_FALLBACK_SIZE, 0);
180 drawParamsFallback_ = device_.createBuffer(
182 GfxContent::retained(), zeros.data());
183 device_.setUniformBuffer(DRAW_PARAMS_BINDING, drawParamsFallback_);
184
185 // A pose, the indirect light where a draw stands, and where its entry is. A POOL
186 // each and not one buffer each, because a block rewritten between two draws of
187 // one pass is read by both — see PerDrawBlocks. A draw's shapes are not one: they
188 // are texels of the record texture its entry names (InstanceConstants.hpp).
189 skinBlocks_.init(device_, static_cast<u32>(sizeof(SkinConstants)));
190 // A run per instance, not one for the draw: the block is what a merged draw
191 // says about every object in it, and GL wants the whole declared block bound.
192 probeBlocks_.init(device_, PROBE_BLOCK_BYTES);
193 // Where the draw's entry is, one texel of the record texture; a run's entries follow its head's, read by gl_DrawID.
194 instanceBlocks_.init(device_, static_cast<u32>(sizeof(InstanceConstants)));
195 planarBlocks_.init(device_, static_cast<u32>(sizeof(PlanarConstants)));
196 // What a draw with no volume reads. A pose has no zero: geometry
197 // without one is drawn by a shader that does not declare the block.
198 probeBlocks_.bindZero(PROBE_CONSTANTS_BINDING);
199 instanceBlocks_.bindZero(INSTANCE_CONSTANTS_BINDING);
200 planarBlocks_.bindZero(PLANAR_CONSTANTS_BINDING);
201
202 ES_LOG_DEBUG("FrameConstants UBO created (handle: {})", static_cast<u32>(frameUbo_));
203}
204
206 uploadFrameConstants(toClipDepthRange(viewProjection, device_.clipDepthRange()),
208}
209
210void RenderContext::updateCameraConstants(const glm::mat4& viewProjection, const glm::vec2& jitterNdc) {
211 // Added to clip xy in proportion to w, so it is the same shift in NDC under a
212 // perspective divide and under none: row 0 and 1 each gain a multiple of row 3.
213 glm::mat4 jittered = viewProjection;
214 for (int col = 0; col < 4; ++col) {
215 jittered[col][0] += jitterNdc.x * viewProjection[col][3];
216 jittered[col][1] += jitterNdc.y * viewProjection[col][3];
217 }
218 uploadFrameConstants(toClipDepthRange(jittered, device_.clipDepthRange()), viewProjection);
219}
220
222 uploadFrameConstants(viewProjection, viewProjection);
223}
224
226 return static_cast<u32>(sizeof(FrameConstants));
227}
228
230 if (ubo == BufferHandle::Invalid) return;
232 glm::inverse(viewProjection), glm::vec4(glm::vec3(renderOrigin()), 0.0f)};
233 device_.updateBuffer(ubo, 0, &frame, sizeof(FrameConstants));
234}
235
241
243 device_.setUniformBuffer(FRAME_CONSTANTS_BINDING, ubo);
244 // Same re-arm the frame's own upload does: a previous pass may have left a
245 // differently sized params buffer on the shared slot.
246 device_.setUniformBuffer(DRAW_PARAMS_BINDING, drawParamsFallback_);
247}
248
249// `engine` is the projection in the engine's own convention, which is what the
250// viewpoint is read from: the two agree on it, but only one of them is the answer
251// to "where is the eye" that the rest of the engine also holds.
252void RenderContext::uploadFrameConstants(const glm::mat4& upload, const glm::mat4& engine) {
253 viewProjection_ = engine;
254 // The viewpoint from `engine` and the un-projection from `upload`: the two
255 // agree about where the eye is, but only the uploaded one describes the clip
256 // space a shader will hand back.
257 const FrameConstants frame{upload, cameraFromViewProjection(engine), glm::inverse(upload), glm::vec4(glm::vec3(renderOrigin()), 0.0f)};
258 device_.updateBuffer(frameUbo_, 0, &frame, sizeof(FrameConstants));
259 // Take the binding back. A pass that draws several views points this slot at
260 // one buffer per view; without this the scene would keep reading whichever
261 // view was bound last, having uploaded its own camera to a buffer nothing reads.
262 device_.setUniformBuffer(FRAME_CONSTANTS_BINDING, frameUbo_);
263 // Re-arm the params fallback for this pass: a post-process or custom-draw
264 // commit from the previous pass left its own (differently sized) buffer on
265 // the shared slot.
266 device_.setUniformBuffer(DRAW_PARAMS_BINDING, drawParamsFallback_);
267}
268
269void RenderContext::setFrameTime(f32 elapsedSec, u32 viewportW, u32 viewportH) {
270 const f32 dt = (lastElapsed_ > 0.0f && elapsedSec > lastElapsed_) ? elapsedSec - lastElapsed_ : 0.0f;
271 lastElapsed_ = elapsedSec;
272 const f32 w = static_cast<f32>(viewportW);
273 const f32 h = static_cast<f32>(viewportH);
274 TimeConstants time{
275 glm::vec4(elapsedSec, dt, viewExposure_, 0.0f),
276 glm::vec4(w, h, w > 0.0f ? 1.0f / w : 0.0f, h > 0.0f ? 1.0f / h : 0.0f),
277 qualityConstants_,
278 };
279 device_.updateBuffer(timeUbo_, 0, &time, sizeof(TimeConstants));
280
281 // The backbuffer follows the viewport from the same size source the frame
282 // clock carries: GL tracks the canvas implicitly (no-op), WebGPU
283 // reconfigures its fixed-size swapchain when the size changes. Called at
284 // the top of the frame, before any pass opens.
285 device_.resizeBackbuffer(viewportW, viewportH);
286}
287
288} // namespace esengine
Per-draw shader parameter block — the UBO home for what used to be loose uniforms.
Per-frame shader constants shared via a single Uniform Buffer Object.
Abstract graphics device interface.
WHERE one draw's entry is in the frame's per-object record texture, and what an entry says.
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
#define ES_LOG_INFO(...)
Logs an info message.
Definition Log.hpp:292
#define ES_LOG_DEBUG(...)
Definition Log.hpp:282
The indirect light where ONE draw stands, when a grid was baked for it.
Rendering context containing all renderer state.
The point the frame is drawn relative to: a world far from zero loses precision in single floats,...
The pose one skinned draw is deformed by: a bone matrix per joint.
static constexpr GfxContent retained()
static constexpr GfxContent sourced(u32 provider, u32 key)
Abstract graphics device interface.
Definition GfxDevice.hpp:75
void setUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes=0, u32 sizeBytes=0)
Binds a buffer to a uniform binding slot (the block index shaders are linked to).
TextureHandle createTexture(const TextureDesc &desc, GfxContent content, const void *pixels)
Creates a 2D texture; uploads pixels (tightly packed, desc-sized) when non-null.
void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void *data, u32 sizeBytes)
Updates a sub-range of a buffer; must fit within its capacity.
static u32 frameConstantsSize()
Bytes a buffer passed to useFrameConstants must hold.
void prepareFrameConstants(BufferHandle ubo, const glm::mat4 &viewProjection)
Stage a light view before the render passes and switch to it without a mid-pass upload.
void restoreBuiltinContent()
Builds again what this context made from code alone and the device lost: call once the device is back...
void updateCameraConstants(const glm::mat4 &viewProjection)
Point the frame at what a CAMERA sees.
void bindFrameConstants(BufferHandle ubo)
void init()
Initializes rendering resources.
void setFrameTime(f32 elapsedSec, u32 viewportW, u32 viewportH)
Uploads the frame clock + canvas size into the injected TimeConstants UBO.
glm::mat4 & viewProjection()
Gets the current view-projection matrix.
void updateFrameConstants(const glm::mat4 &viewProjection)
Point the frame at a pass whose projection already suits the device.
void useFrameConstants(BufferHandle ubo, const glm::mat4 &viewProjection)
Frame constants for viewProjection in a buffer the CALLER owns, bound.
void shutdown()
Releases all rendering resources.
constexpr u32 FRAME_CONSTANTS_BINDING
Indexed uniform binding point the FrameConstants block is bound to.
constexpr u32 RIPPLE_NORMALS_SIZE
@ Repeat
Tile the texture.
Definition GfxEnums.hpp:63
constexpr u32 PROBE_CONSTANTS_BINDING
Indexed UBO binding point for the per-draw ProbeConstants block.
@ Nearest
No interpolation (pixelated look).
Definition GfxEnums.hpp:58
constexpr u32 DRAW_PARAMS_FALLBACK_SIZE
Size of the zeroed fallback UBO RenderContext binds at DRAW_PARAMS_BINDING each frame.
constexpr u32 TIME_CONSTANTS_BINDING
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
constexpr u32 DRAW_PARAMS_BINDING
Indexed UBO binding point for the per-draw DrawParams block. (0 = FrameConstants, 1 = MaterialConstan...
glm::dvec3 & renderOrigin()
The origin, in world units. A double, as the world positions it is taken from are far from zero.
constexpr u32 PLANAR_CONSTANTS_BINDING
std::vector< u8 > buildRippleNormals()
RGBA8, RIPPLE_NORMALS_SIZE square. A texel's rg (and ba) is the xy of a unit normal whose z is up: th...
constexpr u32 PROBE_BLOCK_BYTES
Bytes the block is declared with: every run, then one vec4 that is not data.
glm::vec4 cameraFromViewProjection(const glm::mat4 &viewProjection)
Where the frame is seen from, read out of the matrix that projects it.
constexpr u32 INSTANCE_CONSTANTS_BINDING
Indexed UBO binding point for the per-draw InstanceConstants block. Nine and not four: slot 4 is DRAW...
float f32
32-bit floating point
Definition Types.hpp:59
CPU mirror of the GLSL FrameConstants block (std140).
A Sourced object that has storage again and is waiting for its contents.
Immutable creation parameters of a 2D texture or 2D texture array.
Definition GfxEnums.hpp:414
TextureFilter minFilter
Definition GfxEnums.hpp:422
TextureFilter magFilter
Definition GfxEnums.hpp:423
CPU mirror of the injected TimeConstants block (std140).