Debian Codegraph @

libs/opengl/src/CMesh.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/img/color_maps.h>
15 #include <mrpt/math/ops_containers.h>
16 #include <mrpt/opengl/CMesh.h>
17 #include <mrpt/opengl/CSetOfTriangles.h>
18 #include <mrpt/opengl/opengl_api.h>
19 #include <mrpt/poses/CPose3D.h>
20 #include <mrpt/serialization/CArchive.h>
21
22 using namespace mrpt;
23 using namespace mrpt::opengl;
24 using namespace mrpt::poses;
25 using namespace mrpt::math;
26 using namespace std;
27 using mrpt::img::CImage;
28
29 IMPLEMENTS_SERIALIZABLE(CMesh, CRenderizable, mrpt::opengl)
30
31 CMesh::CMesh(
32 bool enableTransparency, float m_xMin_p, float m_xMax_p, float m_yMin_p, float m_yMax_p) :
33 m_enableTransparency(enableTransparency),
34 Z(0, 0),
35 mask(0, 0),
36 C(0, 0),
37 C_r(0, 0),
38 C_g(0, 0),
39 C_b(0, 0),
40 m_xMin(m_xMin_p),
41 m_xMax(m_xMax_p),
42 m_yMin(m_yMin_p),
43 m_yMax(m_yMax_p)
44 {
45 enableTextureLinearInterpolation(true);
46 enableLight(true);
47
48 setColor_u8(0, 0, 150);
49 }
50
51 CMesh::~CMesh() = default;
52
53 void CMesh::updateTriangles() const
54 {
55 using mrpt::img::colormap;
56
57 CRenderizable::notifyChange();
58
59 std::unique_lock<std::shared_mutex> lckWrite(m_meshDataMtx.data);
60
61 // Remember:
62 /** List of triangles in the mesh */
63 // mutable
64 // std::vector<std::pair<mrpt::opengl::TTriangle,TTriangleVertexIndices>
65 // > actualMesh;
66
67 /** The accumulated normals & counts for each vertex, so normals can be
68 * averaged. */
69 // mutable std::vector<std::pair<mrpt::math::TPoint3D,size_t> >
70 // vertex_normals;
71
72 const auto cols = Z.cols();
73 const auto rows = Z.rows();
74
75 m_zMin = m_zMax = 0;
76
77 actualMesh.clear();
78 if (cols == 0 && rows == 0) return; // empty mesh
79
80 ASSERT_(cols > 0 && rows > 0);
81 ASSERT_NOT_EQUAL_(m_xMax, m_xMin);
82 ASSERT_NOT_EQUAL_(m_yMax, m_yMin);
83
84 float normalSign = 1.0f;
85 if (m_xMax < m_xMin) normalSign *= -1.0f;
86 if (m_yMax < m_yMin) normalSign *= -1.0f;
87
88 // we have 1 more row & col of vertices than of triangles:
89 vertex_normals.assign((1 + cols) * (1 + rows), std::pair<TPoint3D, size_t>(TPoint3D(0, 0, 0), 0));
90
91 if (m_colorFromZ || m_isImage) updateColorsMatrix();
92
93 bool useMask = false;
94 if (mask.cols() != 0 && mask.rows() != 0)
95 {
96 ASSERT_(mask.cols() == cols && mask.rows() == rows);
97 useMask = true;
98 }
99 const float sCellX = (m_xMax - m_xMin) / (rows - 1);
100 const float sCellY = (m_yMax - m_yMin) / (cols - 1);
101
102 const auto myColor = getColor_u8();
103
104 mrpt::opengl::TTriangle tri;
105
106 m_zMin = std::numeric_limits<float>::max();
107 m_zMax = -std::numeric_limits<float>::max();
108
109 for (int iX = 0; iX < rows - 1; iX++)
110 for (int iY = 0; iY < cols - 1; iY++)
111 {
112 if (useMask && (!mask(iX, iY) || !mask(iX + 1, iY + 1))) continue;
113 tri.x(0) = m_xMin + iX * sCellX;
114 tri.y(0) = m_yMin + iY * sCellY;
115 tri.z(0) = Z(iX, iY);
116 tri.x(2) = tri.x(0) + sCellX;
117 tri.y(2) = tri.y(0) + sCellY;
118 tri.z(2) = Z(iX + 1, iY + 1);
119
120 // Vertex indices:
121 TTriangleVertexIndices tvi;
122 tvi.vind[0] = iX + rows * iY;
123 tvi.vind[2] = (iX + 1) + rows * (iY + 1);
124
125 // Each quadrangle has up to 2 triangles:
126 // [0]
127 // |
128 // |
129 // [1]--[2]
130 // Order: 0,1,2
131 if (!useMask || mask(iX + 1, iY))
132 {
133 tri.x(1) = tri.x(2);
134 tri.y(1) = tri.y(0);
135 tri.z(1) = Z(iX + 1, iY);
136 // Assign alpha channel
137 for (int i = 0; i < 3; i++) tri.a(i) = myColor.A;
138
139 if (m_colorFromZ)
140 {
141 mrpt::img::TColorf col(0, 0, 0, 1);
142 colormap(m_colorMap, C(iX, iY), col.R, col.G, col.B);
143 tri.r(0) = f2u8(col.R);
144 tri.g(0) = f2u8(col.G);
145 tri.b(0) = f2u8(col.B);
146 colormap(m_colorMap, C(iX + 1, iY), col.R, col.G, col.B);
147 tri.r(1) = f2u8(col.R);
148 tri.g(1) = f2u8(col.G);
149 tri.b(1) = f2u8(col.B);
150 colormap(m_colorMap, C(iX + 1, iY + 1), col.R, col.G, col.B);
151 tri.r(2) = f2u8(col.R);
152 tri.g(2) = f2u8(col.G);
153 tri.b(2) = f2u8(col.B);
154 }
155 else if (m_isImage)
156 {
157 if (getTextureImage().isColor())
158 {
159 tri.r(0) = tri.r(1) = tri.r(2) = C_r(iX, iY);
160 tri.g(0) = tri.g(1) = tri.g(2) = C_g(iX, iY);
161 tri.b(0) = tri.b(1) = tri.b(2) = C_b(iX, iY);
162 }
163 else
164 {
165 tri.r(0) = tri.r(1) = tri.r(2) = C(iX, iY);
166 tri.g(0) = tri.g(1) = tri.g(2) = C(iX, iY);
167 tri.b(0) = tri.b(1) = tri.b(2) = C(iX, iY);
168 }
169 }
170 else
171 {
172 tri.r(0) = tri.r(1) = tri.r(2) = u8tof(myColor.R);
173 tri.g(0) = tri.g(1) = tri.g(2) = u8tof(myColor.G);
174 tri.b(0) = tri.b(1) = tri.b(2) = u8tof(myColor.B);
175 }
176
177 // Compute normal of this triangle, and add it up to the 3
178 // neighboring vertices:
179 // A = P1 - P0, B = P2 - P0
180 float ax = tri.x(1) - tri.x(0);
181 float bx = tri.x(2) - tri.x(0);
182 float ay = tri.y(1) - tri.y(0);
183 float by = tri.y(2) - tri.y(0);
184 float az = tri.z(1) - tri.z(0);
185 float bz = tri.z(2) - tri.z(0);
186 const TPoint3D this_normal(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx);
187
188 // Vertex indices:
189 tvi.vind[1] = iX + 1 + rows * iY;
190
191 // Add triangle:
192 actualMesh.emplace_back(tri, tvi);
193
194 // ... and update z bbox:
195 for (int i = 0; i < 3; i++)
196 {
197 mrpt::keep_min(m_zMin, tri.z(i));
198 mrpt::keep_max(m_zMax, tri.z(i));
199 }
200
201 // For averaging normals:
202 for (unsigned long k : tvi.vind)
203 {
204 vertex_normals[k].first += this_normal * normalSign;
205 vertex_normals[k].second++;
206 }
207 }
208 // 2:
209 // [0]--[1->2]
210 // \ |
211 // \|
212 // [2->1]
213 // Order: 0,2,1
214 if (!useMask || mask(iX, iY + 1))
215 {
216 tri.x(1) = tri.x(2);
217 tri.y(1) = tri.y(2);
218 tri.z(1) = tri.z(2);
219
220 tri.x(2) = tri.x(0);
221 // tri.y(2)=tri.y(1);
222 tri.z(2) = Z(iX, iY + 1);
223 if (m_colorFromZ)
224 {
225 mrpt::img::TColorf col(0, 0, 0, 1);
226
227 colormap(m_colorMap, C(iX, iY), col.R, col.G, col.B);
228 tri.r(0) = f2u8(col.R);
229 tri.g(0) = f2u8(col.G);
230 tri.b(0) = f2u8(col.B);
231 colormap(m_colorMap, C(iX + 1, iY + 1), col.R, col.G, col.B);
232 tri.r(1) = f2u8(col.R);
233 tri.g(1) = f2u8(col.G);
234 tri.b(1) = f2u8(col.B);
235 colormap(m_colorMap, C(iX, iY + 1), col.R, col.G, col.B);
236 tri.r(2) = f2u8(col.R);
237 tri.g(2) = f2u8(col.G);
238 tri.b(2) = f2u8(col.B);
239 }
240 else if (m_isImage)
241 {
242 if (getTextureImage().isColor())
243 {
244 tri.r(0) = tri.r(1) = tri.r(2) = C_r(iX, iY);
245 tri.g(0) = tri.g(1) = tri.g(2) = C_g(iX, iY);
246 tri.b(0) = tri.b(1) = tri.b(2) = C_b(iX, iY);
247 }
248 else
249 {
250 tri.r(0) = tri.r(1) = tri.r(2) = C(iX, iY);
251 tri.g(0) = tri.g(1) = tri.g(2) = C(iX, iY);
252 tri.b(0) = tri.b(1) = tri.b(2) = C(iX, iY);
253 }
254 }
255 else
256 {
257 tri.r(0) = tri.r(1) = tri.r(2) = u8tof(myColor.R);
258 tri.g(0) = tri.g(1) = tri.g(2) = u8tof(myColor.G);
259 tri.b(0) = tri.b(1) = tri.b(2) = u8tof(myColor.B);
260 }
261
262 // Compute normal of this triangle, and add it up to the 3
263 // neighboring vertices:
264 // A = P1 - P0, B = P2 - P0
265 float ax = tri.x(1) - tri.x(0);
266 float bx = tri.x(2) - tri.x(0);
267 float ay = tri.y(1) - tri.y(0);
268 float by = tri.y(2) - tri.y(0);
269 float az = tri.z(1) - tri.z(0);
270 float bz = tri.z(2) - tri.z(0);
271 const TPoint3D this_normal(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx);
272
273 // Vertex indices:
274 tvi.vind[1] = tvi.vind[2];
275 tvi.vind[2] = iX + rows * (iY + 1);
276
277 // Add triangle:
278 actualMesh.emplace_back(tri, tvi);
279
280 // ... and update z bbox:
281 for (int i = 0; i < 3; i++)
282 {
283 mrpt::keep_min(m_zMin, tri.z(i));
284 mrpt::keep_max(m_zMax, tri.z(i));
285 }
286
287 // For averaging normals:
288 for (unsigned long k : tvi.vind)
289 {
290 vertex_normals[k].first += this_normal * normalSign;
291 vertex_normals[k].second++;
292 }
293 }
294 }
295
296 // Average normals:
297 for (auto& vertex_normal : vertex_normals)
298 {
299 const size_t N = vertex_normal.second;
300 if (N > 0)
301 {
302 vertex_normal.first *= 1.0 / N;
303 vertex_normal.first = vertex_normal.first.unitarize();
304 }
305 }
306
307 m_trianglesUpToDate = true;
308 m_polygonsUpToDate = false;
309 }
310
311 void CMesh::render(const RenderContext& rc) const
312 {
313 switch (rc.shader_id)
314 {
315 case DefaultShaderID::TEXTURED_TRIANGLES_LIGHT:
316 if (!m_isWireFrame) CRenderizableShaderTexturedTriangles::render(rc);
317 break;
318 case DefaultShaderID::WIREFRAME:
319 if (m_isWireFrame) CRenderizableShaderWireFrame::render(rc);
320 break;
321 };
322 }
323 void CMesh::renderUpdateBuffers() const
324 {
325 if (!m_trianglesUpToDate) updateTriangles();
326
327 CRenderizableShaderTexturedTriangles::renderUpdateBuffers();
328 CRenderizableShaderWireFrame::renderUpdateBuffers();
329 }
330
331 void CMesh::onUpdateBuffers_Wireframe()
332 {
333 auto& vbd = CRenderizableShaderWireFrame::m_vertex_buffer_data;
334 auto& cbd = CRenderizableShaderWireFrame::m_color_buffer_data;
335 std::unique_lock<std::shared_mutex> wfWriteLock(
336 CRenderizableShaderWireFrame::m_wireframeMtx.data);
337
338 vbd.clear();
339 cbd.clear();
340
341 std::shared_lock<std::shared_mutex> lckRead(m_meshDataMtx.data);
342
343 for (auto& i : actualMesh)
344 {
345 const mrpt::opengl::TTriangle& t = i.first;
346
347 for (int kk = 0; kk <= 3; kk++)
348 {
349 int k = kk % 3;
350 int k1 = (kk + 1) % 3;
351
352 vbd.emplace_back(t.x(k), t.y(k), t.z(k));
353 cbd.emplace_back(t.r(k), t.g(k), t.b(k), t.a(k));
354
355 vbd.emplace_back(t.x(k1), t.y(k1), t.z(k1));
356 cbd.emplace_back(t.r(k1), t.g(k1), t.b(k1), t.a(k1));
357 }
358 }
359
360 notifyBBoxChange();
361 }
362
363 void CMesh::onUpdateBuffers_TexturedTriangles()
364 {
365 auto& tris = CRenderizableShaderTexturedTriangles::m_triangles;
366 std::unique_lock<std::shared_mutex> writeLock(m_trianglesMtx.data);
367
368 tris.clear();
369
370 std::shared_lock<std::shared_mutex> lckRead(m_meshDataMtx.data);
371
372 // Default: texture over the whole extension.
373 const float textureSizeX = (m_textureSize_x != 0) ? m_textureSize_x : (m_xMax - m_xMin);
374 const float textureSizeY = (m_textureSize_y != 0) ? m_textureSize_y : (m_yMax - m_yMin);
375
376 for (auto& i : actualMesh)
377 {
378 mrpt::opengl::TTriangle& tri = i.first;
379 const TTriangleVertexIndices& tvi = i.second;
380
381 const auto& n0 = vertex_normals.at(tvi.vind[0]).first;
382 const auto& n1 = vertex_normals.at(tvi.vind[1]).first;
383 const auto& n2 = vertex_normals.at(tvi.vind[2]).first;
384
385 tri.vertices[0].normal = n0;
386 tri.vertices[1].normal = n1;
387 tri.vertices[2].normal = n2;
388
389 for (int k = 0; k < 3; k++)
390 {
391 // NOTE: These texture coordinates assume the use of WRAPPED texture
392 // (U,V) in the shader. This is GL_REPEAT, the default.
393 tri.vertices[k].uv.y = (tri.vertices[k].xyzrgba.pt.x - m_xMin) / textureSizeX;
394 tri.vertices[k].uv.x = (tri.vertices[k].xyzrgba.pt.y - m_yMin) / textureSizeY;
395 }
396
397 tris.emplace_back(tri);
398 }
399
400 notifyBBoxChange();
401 }
402
403 /*---------------------------------------------------------------
404 assignImage
405 ---------------------------------------------------------------*/
406 void CMesh::assignImage(const CImage& img)
407 {
408 MRPT_START
409
410 // Make a copy:
411 CRenderizableShaderTexturedTriangles::assignImage(img);
412
413 // Delete content in Z
414 Z.setZero(img.getHeight(), img.getWidth());
415
416 m_modified_Image = true;
417 m_enableTransparency = false;
418 m_colorFromZ = false;
419 m_isImage = true;
420 m_trianglesUpToDate = false;
421
422 CRenderizable::notifyChange();
423
424 MRPT_END
425 }
426
427 void CMesh::assignImageAndZ(const CImage& img, const mrpt::math::CMatrixDynamic<float>& in_Z)
428 {
429 MRPT_START
430
431 // In MRPT<2.7.0, img size must be = to in_z size.
432 // This condition was removed, and custom texture coordinates added.
433
434 Z = in_Z;
435
436 // Load the texture:
437 CRenderizableShaderTexturedTriangles::assignImage(img);
438
439 m_modified_Image = true;
440 m_enableTransparency = false;
441 m_colorFromZ = false;
442 m_isImage = true;
443 m_trianglesUpToDate = false;
444
445 CRenderizable::notifyChange();
446
447 MRPT_END
448 }
449
450 uint8_t CMesh::serializeGetVersion() const { return 1; }
451 void CMesh::serializeTo(mrpt::serialization::CArchive& out) const
452 {
453 writeToStreamRender(out);
454 writeToStreamTexturedObject(out);
455
456 // Version 0:
457 out << m_xMin << m_xMax << m_yMin << m_yMax;
458 out << Z << mask; // We don't need to serialize C, it's computed
459 out << m_enableTransparency;
460 out << m_colorFromZ;
461 // new in v1
462 out << m_isWireFrame;
463 out << int16_t(m_colorMap);
464 }
465
466 void CMesh::serializeFrom(mrpt::serialization::CArchive& in, uint8_t version)
467 {
468 switch (version)
469 {
470 case 0:
471 case 1:
472 {
473 readFromStreamRender(in);
474 readFromStreamTexturedObject(in);
475
476 in >> m_xMin;
477 in >> m_xMax;
478 in >> m_yMin;
479 in >> m_yMax;
480
481 in >> Z >> mask;
482 in >> m_enableTransparency;
483 in >> m_colorFromZ;
484
485 if (version >= 1)
486 {
487 in >> m_isWireFrame;
488 int16_t i;
489 in >> i;
490 m_colorMap = mrpt::img::TColormap(i);
491 }
492 else
493 m_isWireFrame = false;
494
495 m_modified_Z = true;
496 }
497 m_trianglesUpToDate = false;
498 break;
499 default:
500 MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);
501 };
502 m_trianglesUpToDate = false;
503 CRenderizable::notifyChange();
504 }
505
506 void CMesh::updateColorsMatrix() const
507 {
508 if ((!m_modified_Z) && (!m_modified_Image)) return;
509
510 CRenderizable::notifyChange();
511
512 if (m_isImage)
513 {
514 const int cols = getTextureImage().getWidth();
515 const int rows = getTextureImage().getHeight();
516
517 if ((cols != Z.cols()) || (rows != Z.rows()))
518 {
519 // Texture image and Z matrix have different sizes.
520 // Don't create color matrices.
521 }
522 else if (getTextureImage().isColor())
523 {
524 C_r.setSize(rows, cols);
525 C_g.setSize(rows, cols);
526 C_b.setSize(rows, cols);
527 getTextureImage().getAsRGBMatrices(C_r, C_g, C_b);
528 }
529 else
530 {
531 C.setSize(rows, cols);
532 getTextureImage().getAsMatrix(C);
533 }
534 }
535 else
536 {
537 const size_t cols = Z.cols();
538 const size_t rows = Z.rows();
539 C.setSize(rows, cols);
540
541 // Color is proportional to height:
542 C = Z;
543
544 // If mask is empty -> Normalize the whole mesh
545 if (mask.empty()) mrpt::math::normalize(C, 0.01f, 0.99f);
546
547 // Else -> Normalize color ignoring masked-out cells:
548 else
549 {
550 float val_max = -std::numeric_limits<float>::max(),
551 val_min = std::numeric_limits<float>::max();
552 bool any_valid = false;
553
554 for (size_t c = 0; c < cols; c++)
555 for (size_t r = 0; r < rows; r++)
556 {
557 if (!mask(r, c)) continue;
558 any_valid = true;
559 const float val = C(r, c);
560 mrpt::keep_max(val_max, val);
561 mrpt::keep_min(val_min, val);
562 }
563
564 if (any_valid)
565 {
566 float minMaxDelta = val_max - val_min;
567 if (minMaxDelta == 0) minMaxDelta = 1;
568 const float minMaxDelta_ = 1.0f / minMaxDelta;
569 C.array() = (C.array() - val_min) * minMaxDelta_;
570 }
571 }
572 }
573
574 m_modified_Image = false;
575 m_modified_Z = false;
576 m_trianglesUpToDate = false;
577 }
578
579 void CMesh::setZ(const mrpt::math::CMatrixDynamic<float>& in_Z)
580 {
581 Z = in_Z;
582 m_modified_Z = true;
583 m_trianglesUpToDate = false;
584
585 // Delete previously loaded images
586 m_isImage = false;
587
588 CRenderizable::notifyChange();
589 }
590
591 void CMesh::setMask(const mrpt::math::CMatrixDynamic<float>& in_mask)
592 {
593 mask = in_mask;
594 m_trianglesUpToDate = false;
595 CRenderizable::notifyChange();
596 }
597
598 bool CMesh::traceRay(const mrpt::poses::CPose3D& o, double& dist) const
599 {
600 if (!m_trianglesUpToDate || !m_polygonsUpToDate) updatePolygons();
601 return mrpt::math::traceRay(tmpPolys, (o - getCPose()).asTPose(), dist);
602 }
603
604 static math::TPolygon3D tmpPoly(3);
605 mrpt::math::TPolygonWithPlane createPolygonFromTriangle(
606 const std::pair<mrpt::opengl::TTriangle, CMesh::TTriangleVertexIndices>& p)
607 {
608 const mrpt::opengl::TTriangle& t = p.first;
609 for (size_t i = 0; i < 3; i++) tmpPoly[i] = t.vertex(i);
610 return mrpt::math::TPolygonWithPlane(tmpPoly);
611 }
612
613 void CMesh::updatePolygons() const
614 {
615 if (!m_trianglesUpToDate) updateTriangles();
616
617 std::shared_lock<std::shared_mutex> lckRead(m_meshDataMtx.data);
618 size_t N = actualMesh.size();
619 tmpPolys.resize(N);
620 transform(actualMesh.begin(), actualMesh.end(), tmpPolys.begin(), createPolygonFromTriangle);
621 m_polygonsUpToDate = true;
622 CRenderizable::notifyChange();
623 }
624
625 auto CMesh::internalBoundingBoxLocal() const -> mrpt::math::TBoundingBoxf
626 {
627 return mrpt::math::TBoundingBoxf::FromUnsortedPoints(
628 {m_xMin, m_yMin, m_zMin}, {m_xMax, m_yMax, m_zMax});
629 }
630
631 void CMesh::adjustGridToImageAR()
632 {
633 ASSERT_(m_isImage);
634 const float ycenter = 0.5f * (m_yMin + m_yMax);
635 const float xwidth = m_xMax - m_xMin;
636 const float newratio = float(getTextureImage().getWidth()) / float(getTextureImage().getHeight());
637 m_yMax = ycenter + 0.5f * newratio * xwidth;
638 m_yMin = ycenter - 0.5f * newratio * xwidth;
639 CRenderizable::notifyChange();
640 }