Debian Codegraph @

libs/opengl/src/RenderQueue.cpp

raw
1 /* +------------------------------------------------------------------------+
2 | Mobile Robot Programming Toolkit (MRPT) |
3 | https://www.mrpt.org/ |
4 | |
5 | Copyright (c) 2005-2026, Individual contributors, see AUTHORS file |
6 | See: https://www.mrpt.org/Authors - All rights reserved. |
7 | Released under BSD License. See: https://www.mrpt.org/License |
8 +------------------------------------------------------------------------+ */
9
10 #include "opengl-precomp.h" // Precompiled header
11 //
12 #include <Eigen/Dense> // First! to avoid conflicts with X.h
13 //
14 #include <mrpt/opengl/CSetOfObjects.h>
15 #include <mrpt/opengl/CText.h>
16 #include <mrpt/opengl/RenderQueue.h>
17 #include <mrpt/opengl/opengl_api.h>
18 #include <mrpt/system/os.h>
19
20 #include <map>
21
22 using namespace std;
23 using namespace mrpt;
24 using namespace mrpt::math;
25 using namespace mrpt::poses;
26 using namespace mrpt::system;
27 using namespace mrpt::opengl;
28
29 // (U,V) normalized screen coordinates:
30 //
31 // +----------------------+
32 // |(-1,+1) (+1,+1)|
33 // | |
34 // | |
35 // | |
36 // |(-1,-1) (+1,-1)|
37 // +----------------------+
38 //
39 namespace
40 {
41 std::tuple<mrpt::math::TPoint2Df, float> projectToScreenCoordsAndDepth(
42 const mrpt::math::TPoint3Df& localPt, const mrpt::opengl::TRenderMatrices& objState)
43 {
44 const Eigen::Vector4f lrp_hm(localPt.x, localPt.y, localPt.z, 1.0f);
45
46 // Looking from the light (1st pass in a shadow mapping), or the camera
47 // (regular case):
48 const auto& pmv_matrix = objState.is1stShadowMapPass ? objState.light_pmv : objState.pmv_matrix;
49
50 const auto lrp_proj = (pmv_matrix.asEigen() * lrp_hm).eval();
51
52 const float depth = (lrp_proj(3) != 0) ? lrp_proj(2) / std::abs(lrp_proj(3)) : .001f;
53
54 auto uv = (lrp_proj(3) != 0)
55 ? mrpt::math::TPoint2Df(lrp_proj(0) / lrp_proj(3), lrp_proj(1) / lrp_proj(3))
56 : mrpt::math::TPoint2Df(.001f, .001f);
57
58 if (!objState.is1stShadowMapPass)
59 {
60 if (depth < -1.0f && objState.is_projective) uv *= -1.0;
61 }
62
63 return {uv, depth};
64 }
65 } // namespace
66
67 // See docs in .h
68 std::tuple<double, bool, bool> mrpt::opengl::depthAndVisibleInView(
69 const CRenderizable* obj,
70 const mrpt::opengl::TRenderMatrices& objState,
71 const bool skipCullChecks)
72 {
73 // This profiler has a too-high impact. Only for very low-level debugging.
74 /*#ifdef MRPT_OPENGL_PROFILER
75 mrpt::system::CTimeLoggerEntry tle(
76 opengl_profiler(), "depthAndVisibleInView");
77 #endif*/
78
79 const bool mustCheckWholeBbox = obj->isCompositeObject();
80
81 // Get a representative depth for this object (to sort objects from
82 // eye-distance):
83 const mrpt::math::TPoint3Df lrp = obj->getLocalRepresentativePoint();
84
85 const auto [lrpUV, lrpDepth] = projectToScreenCoordsAndDepth(lrp, objState);
86
87 if (skipCullChecks || !obj->cullElegible())
88 {
89 // direct return:
90 return {lrpDepth, true, true};
91 }
92
93 // If the object is outside of the camera frustrum, do not even send
94 // it for rendering:
95 // bbox is in local object frame of reference.
96
97 /*#ifdef MRPT_OPENGL_PROFILER
98 mrpt::system::CTimeLoggerEntry tle2(
99 opengl_profiler(), "depthAndVisibleInView.bbox");
100 #endif*/
101
102 mrpt::math::TBoundingBoxf bbox;
103 try
104 {
105 bbox = obj->getBoundingBoxLocalf();
106 }
107 catch (const std::exception&)
108 {
109 // use default (0,0,0) bbox
110 }
111
112 /*#ifdef MRPT_OPENGL_PROFILER
113 tle2.stop();
114 #endif*/
115
116 // for each of the 8 corners:
117 bool anyVisible = false, allVisible = true;
118 bool quadrants[9] = {false, false, false, false, false, false, false, false, false};
119
120 bool anyGoodDepth = false;
121
122 const auto lambdaProcessSample = [&anyVisible, &allVisible, &anyGoodDepth, &quadrants](
123 const mrpt::math::TPoint2Df& uv, const float sampleDepth)
124 {
125 // Do not check for "bboxDepth < 1.0f" since that may only mean
126 // the object is still visible, but farther away than the
127 // farPlane:
128 const bool goodDepth = sampleDepth > -1.0f;
129 anyGoodDepth = anyGoodDepth | goodDepth;
130
131 const bool inside = goodDepth && (uv.x >= -1 && uv.x <= 1 && uv.y >= -1 && uv.y < 1);
132
133 if (inside)
134 anyVisible = true;
135 else
136 allVisible = false;
137
138 // quadrants:
139 int qx = uv.x < -1 ? 0 : (uv.x > 1 ? 2 : 1);
140 int qy = uv.y < -1 ? 0 : (uv.y > 1 ? 2 : 1);
141 quadrants[qx + 3 * qy] = true;
142 };
143
144 // 1st) Process the local-representative-point (~body center) sample:
145 // -----------------------------------------------------------------------
146 lambdaProcessSample(lrpUV, lrpDepth);
147
148 // 2nd) then, the rest of 4 or 8 bbox corners:
149 // ------------------------------------------------
150 // dont go thru the (min,max) dimensions of one axis if it's negligible:
151 const auto diag = bbox.max - bbox.min;
152 const float maxLen = mrpt::max3(diag.x, diag.y, diag.z);
153 int numLayersX = 1, numLayersY = 1, numLayersZ = 1;
154 if (maxLen > 0)
155 {
156 numLayersX = (diag.x / maxLen) > 1e-3f ? 2 : 1;
157 numLayersY = (diag.y / maxLen) > 1e-3f ? 2 : 1;
158 numLayersZ = (diag.z / maxLen) > 1e-3f ? 2 : 1;
159 }
160 const mrpt::math::TPoint3Df ends[2] = {bbox.min, bbox.max};
161
162 for (int ix = 0; (mustCheckWholeBbox || !anyVisible) && ix < numLayersX; ix++)
163 {
164 const float x = ends[ix].x;
165 for (int iy = 0; (mustCheckWholeBbox || !anyVisible) && iy < numLayersY; iy++)
166 {
167 const float y = ends[iy].y;
168 for (int iz = 0; (mustCheckWholeBbox || !anyVisible) && iz < numLayersZ; iz++)
169 {
170 const float z = ends[iz].z;
171
172 const auto [uv, bboxDepth] = projectToScreenCoordsAndDepth({x, y, z}, objState);
173
174 lambdaProcessSample(uv, bboxDepth);
175 }
176 }
177 }
178
179 // if we already had *any* bbox corner inside the frustrum, it's visible.
180 // if not, *but* the corners are in opposed sides of the frustrum, then the
181 // (central part of the) object may be still visible:
182 if (!anyVisible)
183 {
184 using Bools3x3_bits = uint32_t;
185 constexpr Bools3x3_bits quadPairs[9] = {
186 // clang-format off
187 // 0:
188 (0b110 << 6) |
189 (0b110 << 3) |
190 (0b000 << 0), // 0b001 <= I'm here
191 // 1:
192 (0b111 << 6) |
193 (0b111 << 3) |
194 (0b000 << 0), // 0b010 <= I'm here
195 // 2:
196 (0b011 << 6) |
197 (0b011 << 3) |
198 (0b000 << 0), // 0b100 <= I'm here
199 // 3:
200 (0b110 << 6) |
201 (0b110 << 3) | // 0b001 <= I'm here
202 (0b110 << 0),
203 // 4:
204 (0b111 << 6) |
205 (0b101 << 3) | // 0b010 <= I'm here
206 (0b111 << 0),
207 // 5:
208 (0b011 << 6) |
209 (0b011 << 3) | // 0b100 <= I'm here
210 (0b011 << 0),
211 // 6:
212 (0b000 << 6) | // 0b001 <= I'm here
213 (0b110 << 3) |
214 (0b110 << 0),
215 // 7:
216 (0b000 << 6) | // 0b010 <= I'm here
217 (0b111 << 3) |
218 (0b111 << 0),
219 // 8:
220 (0b000 << 6) | // 0b100 <= I'm here
221 (0b011 << 3) |
222 (0b011 << 0),
223 // clang-format on
224 };
225
226 uint32_t q = 0;
227 for (int i = 0; i < 9; i++)
228 {
229 if (quadrants[i]) q = q | (1 << i);
230 }
231
232 for (int i = 0; i < 9 && !anyVisible; i++)
233 {
234 if (!quadrants[i]) continue;
235 if ((q & quadPairs[i]) != 0)
236 {
237 // at least one match for a potential edge crossing the visible
238 // area of the frustum:
239 anyVisible = true;
240 }
241 }
242 }
243 if (!anyGoodDepth)
244 {
245 anyVisible = false;
246 }
247
248 return {lrpDepth, anyVisible, allVisible};
249 }
250
251 // Render a set of objects
252 void mrpt::opengl::enqueueForRendering(
253 const mrpt::opengl::CListOpenGLObjects& objs,
254 const mrpt::opengl::TRenderMatrices& state,
255 RenderQueue& rq,
256 const bool skipCullChecks,
257 const bool is1stShadowMapPass,
258 RenderQueueStats* stats)
259 {
260 #if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL
261 using mrpt::math::CMatrixDouble44;
262
263 #ifdef MRPT_OPENGL_PROFILER
264 mrpt::system::CTimeLoggerEntry tle(opengl_profiler(), "enqueueForRendering");
265 #endif
266
267 const char* curClassName = nullptr;
268 try
269 {
270 for (const auto& objPtr : objs)
271 {
272 if (!objPtr) continue;
273
274 #ifdef MRPT_OPENGL_PROFILER
275 if (stats) stats->numObjTotal++;
276 #endif
277
278 // Use plain pointers, faster than smart pointers:
279 const CRenderizable* obj = objPtr.get();
280
281 // Quick check: if we are in a shadow generation pass where this
282 // object does not render, skip it:
283 const auto lst_shaders = obj->requiredShaders();
284 if (lst_shaders.size() == 1 && lst_shaders.at(0) == DefaultShaderID::NONE) continue;
285
286 // Save class name: just in case we have an exception, for error
287 // reporting:
288 curClassName = obj->GetRuntimeClass()->className;
289
290 if (!obj->isVisible()) continue;
291
292 // Skip objects that do not cast shadows, if we are in that first
293 // shadow map pass.
294 if (is1stShadowMapPass && !obj->castShadows()) continue;
295
296 // Regenerate opengl vertex buffers?
297 if (obj->hasToUpdateBuffers()) obj->updateBuffers();
298
299 const CPose3D thisPose = obj->getCPose();
300 CMatrixFloat44 HM = thisPose.getHomogeneousMatrixVal<CMatrixDouble44>().cast_float();
301
302 // Scaling:
303 if (obj->getScaleX() != 1 || obj->getScaleY() != 1 || obj->getScaleZ() != 1)
304 {
305 auto scale = CMatrixFloat44::Identity();
306 scale(0, 0) = obj->getScaleX();
307 scale(1, 1) = obj->getScaleY();
308 scale(2, 2) = obj->getScaleZ();
309 HM.asEigen() = HM.asEigen() * scale.asEigen();
310 }
311
312 // Make a copy of rendering state, so we always have the
313 // original version of my parent intact.
314 auto _ = state;
315
316 // Compose relative to my parent pose:
317 _.m_matrix.asEigen() = _.m_matrix.asEigen() * HM.asEigen();
318
319 // Precompute matrices to be used in shaders:
320 _.mv_matrix.asEigen() = _.v_matrix.asEigen() * _.m_matrix.asEigen();
321
322 // PMV = P*V*M (observe the weird notation order)
323 _.pmv_matrix.asEigen() = _.p_matrix.asEigen() * _.mv_matrix.asEigen();
324
325 // PMV for the light = P*V*M (observe the weird notation order)
326 _.light_pmv.asEigen() = _.light_pv.asEigen() * _.m_matrix.asEigen();
327
328 // Let the culling algorithm know whether we are looking from the
329 // camera or from the light:
330 _.is1stShadowMapPass = is1stShadowMapPass;
331
332 const auto [depth, withinView, wholeInView] = depthAndVisibleInView(obj, _, skipCullChecks);
333
334 if (withinView)
335 {
336 #ifdef MRPT_OPENGL_PROFILER
337 if (stats) stats->numObjRendered++;
338 #endif
339
340 // Enqueue this object...
341 for (const auto shader_id : lst_shaders)
342 {
343 // eye-to-object depth:
344 rq[shader_id].emplace(depth, RenderQueueElement(obj, _));
345 }
346
347 if (obj->isShowNameEnabled())
348 {
349 CText& label = obj->labelObject();
350
351 // Update the label, only if it changed:
352 if (label.getString() != obj->getName()) label.setString(obj->getName());
353
354 // Regenerate opengl vertex buffers, if first time or
355 // label changed:
356 if (label.hasToUpdateBuffers()) label.updateBuffers();
357
358 rq[DefaultShaderID::TEXT].emplace(depth, RenderQueueElement(&label, _));
359 }
360 }
361
362 // ...and its children:
363 obj->enqueueForRenderRecursive(_, rq, wholeInView, is1stShadowMapPass);
364
365 } // end foreach object
366 }
367 catch (const exception& e)
368 {
369 THROW_EXCEPTION_FMT(
370 "Exception while rendering class '%s':\n%s", curClassName ? curClassName : "(undefined)",
371 e.what());
372 }
373
374 #endif
375 }
376
377 void mrpt::opengl::processRenderQueue(
378 const RenderQueue& rq,
379 std::map<shader_id_t, mrpt::opengl::Program::Ptr>& shaders,
380 const mrpt::opengl::TLightParameters& lights,
381 const std::optional<unsigned int>& depthMapTextureId)
382 {
383 #if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL
384
385 #ifdef MRPT_OPENGL_PROFILER
386 mrpt::system::CTimeLoggerEntry tle(opengl_profiler(), "processRenderQueue");
387 #endif
388
389 for (const auto& rqSet : rq)
390 {
391 // bind the shader for this sequence of objects:
392 mrpt::opengl::Program& shader = *shaders.at(rqSet.first);
393
394 shader.use();
395
396 if (depthMapTextureId)
397 {
398 // We are in the 2nd pass of shadow rendering:
399 // bind depthmap texture
400 glActiveTexture(GL_TEXTURE0 + SHADOW_MAP_TEXTURE_UNIT);
401 glBindTexture(GL_TEXTURE_2D, *depthMapTextureId);
402 CHECK_OPENGL_ERROR_IN_DEBUG();
403 }
404
405 CRenderizable::RenderContext rc;
406 rc.shader = &shader;
407 rc.shader_id = rqSet.first;
408 rc.lights = &lights;
409
410 // Process all objects using this shader:
411 const auto& rqMap = rqSet.second;
412
413 // Render in reverse depth order:
414 for (auto it = rqMap.rbegin(); it != rqMap.rend(); ++it)
415 {
416 const RenderQueueElement& rqe = it->second;
417 ASSERT_(rqe.object != nullptr);
418
419 // Load matrices in shader:
420 const auto IS_TRANSPOSED = GL_TRUE;
421 if (shader.hasUniform("m_matrix"))
422 glUniformMatrix4fv(
423 shader.uniformId("m_matrix"), 1, IS_TRANSPOSED, rqe.renderState.m_matrix.data());
424
425 if (shader.hasUniform("p_matrix"))
426 glUniformMatrix4fv(
427 shader.uniformId("p_matrix"), 1, IS_TRANSPOSED, rqe.renderState.p_matrix.data());
428
429 if (shader.hasUniform("v_matrix"))
430 glUniformMatrix4fv(
431 shader.uniformId("v_matrix"), 1, IS_TRANSPOSED, rqe.renderState.v_matrix.data());
432
433 if (shader.hasUniform("v_matrix_no_translation"))
434 glUniformMatrix4fv(
435 shader.uniformId("v_matrix_no_translation"), 1, IS_TRANSPOSED,
436 rqe.renderState.v_matrix_no_translation.data());
437
438 if (shader.hasUniform("mv_matrix"))
439 glUniformMatrix4fv(
440 shader.uniformId("mv_matrix"), 1, IS_TRANSPOSED, rqe.renderState.mv_matrix.data());
441
442 if (shader.hasUniform("pmv_matrix"))
443 glUniformMatrix4fv(
444 shader.uniformId("pmv_matrix"), 1, IS_TRANSPOSED, rqe.renderState.pmv_matrix.data());
445
446 if (shader.hasUniform("cam_position"))
447 glUniform3f(
448 shader.uniformId("cam_position"), rqe.renderState.eye.x, rqe.renderState.eye.y,
449 rqe.renderState.eye.z);
450
451 if (shader.hasUniform("light_pv_matrix"))
452 glUniformMatrix4fv(
453 shader.uniformId("light_pv_matrix"), 1, IS_TRANSPOSED, rqe.renderState.light_pv.data());
454
455 if (shader.hasUniform("materialSpecular"))
456 glUniform1f(shader.uniformId("materialSpecular"), rqe.object->materialShininess());
457
458 rc.state = &rqe.renderState;
459
460 // Render object:
461 rqe.object->render(rc);
462 }
463 }
464
465 #endif
466 }
467
468 #if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL
469 void mrpt::opengl::checkOpenGLErr_impl(unsigned int glErrorCode, const char* filename, int lineno)
470 {
471 if (glErrorCode == GL_NO_ERROR) return;
472 #if MRPT_HAS_OPENGL_GLUT
473 const std::string sErr = mrpt::format(
474 "[%s:%i] OpenGL error: %s", filename, lineno,
475 reinterpret_cast<const char*>(gluErrorString(glErrorCode)));
476 #else
477 // w/o glu:
478 const std::string sErr = mrpt::format("[%s:%i] OpenGL error: %u", filename, lineno, glErrorCode);
479 #endif
480 std::cerr << "[gl_utils::checkOpenGLError] " << sErr << std::endl;
481 THROW_EXCEPTION(sErr);
482 }
483 #endif