Visual Computing Library  devel
Loading...
Searching...
No Matches
curvature.h
1/*****************************************************************************
2 * VCLib *
3 * Visual Computing Library *
4 * *
5 * Copyright(C) 2021-2025 *
6 * Visual Computing Lab *
7 * ISTI - Italian National Research Council *
8 * *
9 * All rights reserved. *
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the Mozilla Public License Version 2.0 as published *
13 * by the Mozilla Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 * This program is distributed in the hope that it will be useful, *
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
19 * Mozilla Public License Version 2.0 *
20 * (https://www.mozilla.org/en-US/MPL/2.0/) for more details. *
21 ****************************************************************************/
22
23#ifndef VCL_ALGORITHMS_MESH_UPDATE_CURVATURE_H
24#define VCL_ALGORITHMS_MESH_UPDATE_CURVATURE_H
25
26#include <vclib/algorithms/mesh/intersection.h>
27#include <vclib/algorithms/mesh/point_sampling.h>
28#include <vclib/algorithms/mesh/stat.h>
29#include <vclib/algorithms/mesh/update/normal.h>
30
31#include <vclib/algorithms/core.h>
32#include <vclib/mesh.h>
33#include <vclib/space/complex.h>
34#include <vclib/space/core.h>
35
36#include <mutex>
37
38namespace vcl {
39
40enum class PrincipalCurvatureAlgorithm { TAUBIN95, PCA };
41
42template<FaceMeshConcept MeshType, LoggerConcept LogType = NullLogger>
43void updatePrincipalCurvatureTaubin95(MeshType& m, LogType& log = nullLogger)
44{
45 requirePerVertexPrincipalCurvature(m);
46 requirePerVertexAdjacentFaces(m);
48
49 using VertexType = MeshType::VertexType;
50 using PositionType = VertexType::PositionType;
51 using NormalType = VertexType::NormalType;
52 using ScalarType = PositionType::ScalarType;
53 using FaceType = MeshType::FaceType;
54
55 // Auxiliary data structure
56 struct AdjVertex
57 {
58 const VertexType* vert;
59 double doubleArea;
60 bool isBorder;
61 };
62
63 log.log(0, "Updating per vertex normals...");
64
65 updatePerVertexNormalsAngleWeighted(m);
66 normalizePerVertexNormals(m);
67
68 log.log(5, "Computing per vertex curvature...");
69 // log every 5%, starting from 5% to 100%
70 log.startProgress("", m.vertexNumber(), 5, 5, 100);
71
72 for (VertexType& v : m.vertices()) {
73 std::vector<ScalarType> weights;
74 std::vector<AdjVertex> vertices;
75
76 MeshPos<FaceType> pos(v.adjFace(0), &v);
77 const VertexType* firstVertex = pos.adjVertex();
78 const VertexType* tmpVertex;
79 float totalDoubleAreaSize = 0;
80
81 // compute the area of each triangle around the central vertex as well
82 // as their total area
83 do {
84 pos.nextEdgeAdjacentToV();
85 tmpVertex = pos.adjVertex();
86 AdjVertex adjV;
87 adjV.isBorder = pos.isEdgeOnBorder();
88 adjV.vert = tmpVertex;
89 adjV.doubleArea = faceArea(*pos.face()) * 2;
90 totalDoubleAreaSize += adjV.doubleArea;
91 vertices.push_back(adjV);
92 } while (tmpVertex != firstVertex);
93
94 weights.reserve(vertices.size());
95
96 for (int i = 0; i < vertices.size(); ++i) {
97 if (vertices[i].isBorder) {
98 weights.push_back(vertices[i].doubleArea / totalDoubleAreaSize);
99 }
100 else {
101 weights.push_back(
102 0.5f *
103 (vertices[i].doubleArea +
104 vertices[(i - 1) % vertices.size()].doubleArea) /
105 totalDoubleAreaSize);
106 }
107 assert(weights.back() < 1.0f);
108 }
109
110 // compute I-NN^t to be used for computing the T_i's
111 Matrix33<ScalarType> Tp;
112
113 NormalType n = v.normal();
114 for (int i = 0; i < 3; ++i)
115 Tp(i, i) = 1.0f - std::pow(n[i], 2);
116 Tp(0, 1) = Tp(1, 0) = -1.0f * (n[0] * n[1]);
117 Tp(1, 2) = Tp(2, 1) = -1.0f * (n[1] * n[2]);
118 Tp(0, 2) = Tp(2, 0) = -1.0f * (n[0] * n[2]);
119
120 // for all neighbors vi compute the directional curvatures k_i and the
121 // T_i compute M by summing all w_i k_i T_i T_i^t
122 Matrix33<ScalarType> tempMatrix;
123 Matrix33<ScalarType> M = Matrix33<ScalarType>::Zero();
124 for (size_t i = 0; i < vertices.size(); ++i) {
125 PositionType edge = (v.position() - vertices[i].vert->position());
126 float curvature =
127 (2.0f * (v.normal().dot(edge))) / edge.squaredNorm();
128 PositionType t = Tp * edge;
129 t.normalize();
130 tempMatrix = t.outerProduct(t);
131 M += tempMatrix * weights[i] * curvature;
132 }
133
134 // compute vector W for the Householder matrix
135 PositionType w;
136 PositionType e1(1.0f, 0.0f, 0.0f);
137 if ((e1 - v.normal()).squaredNorm() > (e1 + v.normal()).squaredNorm())
138 w = e1 - v.normal();
139 else
140 w = e1 + v.normal();
141 w.normalize();
142
143 // compute the Householder matrix I - 2WW^t
144 Matrix33<ScalarType> Q = Matrix33<ScalarType>::Identity();
145 tempMatrix = w.outerProduct(w);
146 Q -= tempMatrix * 2.0f;
147
148 // compute matrix Q^t M Q
149 Matrix33<ScalarType> QtMQ = (Q.transpose() * M * Q);
150
151 Eigen::Matrix<ScalarType, 1, 3> T1 = Q.col(1);
152 Eigen::Matrix<ScalarType, 1, 3> T2 = Q.col(2);
153
154 // find sin and cos for the Givens rotation
155 ScalarType s, c;
156 // Gabriel Taubin hint and Valentino Fiorin impementation
157 ScalarType alpha = QtMQ(1, 1) - QtMQ(2, 2);
158 ScalarType beta = QtMQ(2, 1);
159
160 ScalarType h[2];
161 ScalarType delta =
162 std::sqrt(4.0f * std::pow(alpha, 2) + 16.0f * std::pow(beta, 2));
163 h[0] = (2.0f * alpha + delta) / (2.0f * beta);
164 h[1] = (2.0f * alpha - delta) / (2.0f * beta);
165
166 ScalarType t[2];
167 ScalarType bestC, bestS;
168 ScalarType minError = std::numeric_limits<ScalarType>::infinity();
169 for (uint i = 0; i < 2; i++) {
170 delta = std::sqrt(std::pow(h[i], 2) + 4.0f);
171 t[0] = (h[i] + delta) / 2.0f;
172 t[1] = (h[i] - delta) / 2.0f;
173
174 for (uint j = 0; j < 2; j++) {
175 ScalarType squaredT = std::pow(t[j], 2);
176 ScalarType denominator = 1.0f + squaredT;
177
178 s = (2.0f * t[j]) / denominator;
179 c = (1 - squaredT) / denominator;
180
181 ScalarType approximation =
182 c * s * alpha + (std::pow(c, 2) - std::pow(s, 2)) * beta;
183 ScalarType angleSimilarity =
184 std::abs(std::acos(c) / std::asin(s));
185 ScalarType error =
186 std::abs(1.0f - angleSimilarity) + std::abs(approximation);
187 if (error < minError) {
188 minError = error;
189 bestC = c;
190 bestS = s;
191 }
192 }
193 }
194 c = bestC;
195 s = bestS;
196
197 Eigen::Matrix2f minor2x2;
198 Eigen::Matrix2f S;
199
200 // diagonalize M
201 minor2x2(0, 0) = QtMQ(1, 1);
202 minor2x2(0, 1) = QtMQ(1, 2);
203 minor2x2(1, 0) = QtMQ(2, 1);
204 minor2x2(1, 1) = QtMQ(2, 2);
205
206 S(0, 0) = S(1, 1) = c;
207 S(0, 1) = s;
208 S(1, 0) = -1.0f * s;
209
210 Eigen::Matrix2f StMS = S.transpose() * minor2x2 * S;
211
212 // compute curvatures and curvature directions
213 ScalarType principalCurv1 = (3.0f * StMS(0, 0)) - StMS(1, 1);
214 ScalarType principalCurv2 = (3.0f * StMS(1, 1)) - StMS(0, 0);
215
216 Eigen::Matrix<ScalarType, 1, 3> principalDir1 = T1 * c - T2 * s;
217 Eigen::Matrix<ScalarType, 1, 3> principalDir2 = T1 * s + T2 * c;
218
219 v.principalCurvature().maxDir() = principalDir1;
220 v.principalCurvature().minDir() = principalDir2;
221 v.principalCurvature().maxValue() = principalCurv1;
222 v.principalCurvature().minValue() = principalCurv2;
223
224 log.progress(m.index(v));
225 }
226
227 log.endProgress();
228 log.log(100, "Per vertex curvature computed.");
229}
230
243template<FaceMeshConcept MeshType, LoggerConcept LogType = NullLogger>
244void updatePrincipalCurvaturePCA(
245 MeshType& m,
246 typename MeshType::VertexType::PositionType::ScalarType radius,
247 bool montecarloSampling = true,
248 LogType& log = nullLogger)
249{
250 using VertexType = MeshType::VertexType;
251 using PositionType = VertexType::PositionType;
252 using ScalarType = PositionType::ScalarType;
253 using NormalType = VertexType::NormalType;
254 using FaceType = MeshType::FaceType;
255
256 using VGrid = StaticGrid3<VertexType*, ScalarType>;
257 using VGridIterator = VGrid::ConstIterator;
258
259 VGrid pGrid;
260 ScalarType area;
261
262 log.log(0, "Updating per vertex normals...");
263
264 updatePerVertexNormalsAngleWeighted(m);
265 normalizePerVertexNormals(m);
266
267 log.log(0, "Computing per vertex curvature...");
268 log.startProgress("", m.vertexNumber());
269
270 if (montecarloSampling) {
271 area = surfaceArea(m);
272 pGrid = VGrid(m.vertices() | views::addrOf);
273 pGrid.build();
274 }
275
276 parallelFor(m.vertices(), [&](VertexType& v) {
277 // for (VertexType& v : m.vertices()) {
278 Matrix33<ScalarType> A, eigenvectors;
279 PositionType bp, eigenvalues;
280 if (montecarloSampling) {
281 Sphere s(v.position(), radius);
282 std::vector<VGridIterator> vec = pGrid.valuesInSphere(s);
283 std::vector<PositionType> points;
284 points.reserve(vec.size());
285 for (const auto& it : vec) {
286 points.push_back(it->second->position());
287 }
288 A = covarianceMatrixOfPointCloud(points);
289 A *= area * area / 1000;
290 }
291 else {
292 Sphere<ScalarType> sph(v.position(), radius);
293 MeshType tmpMesh = intersection(m, sph);
294
295 A = covarianceMatrixOfMesh(tmpMesh);
296 }
297
298 Eigen::SelfAdjointEigenSolver<Eigen::Matrix<ScalarType, 3, 3>> eig(A);
299 eigenvalues = PositionType(eig.eigenvalues());
300 eigenvectors = eig.eigenvectors(); // eigenvector are stored as columns.
301 // get the estimate of curvatures from eigenvalues and eigenvectors
302 // find the 2 most tangent eigenvectors (by finding the one closest to
303 // the normal)
304 uint best = 0;
305 ScalarType bestv = std::abs(
306 v.normal().dot(PositionType(eigenvectors.col(0).normalized())));
307 for (uint i = 1; i < 3; ++i) {
308 ScalarType prod = std::abs(
309 v.normal().dot(PositionType(eigenvectors.col(i).normalized())));
310 if (prod > bestv) {
311 bestv = prod;
312 best = i;
313 }
314 }
315 v.principalCurvature().maxDir() =
316 (eigenvectors.col((best + 1) % 3).normalized());
317 v.principalCurvature().minDir() =
318 (eigenvectors.col((best + 2) % 3).normalized());
319
320 Matrix33<ScalarType> rot;
321 ScalarType angle;
322 angle = acos(v.principalCurvature().maxDir().dot(v.normal()));
323
324 rot = rotationMatrix<Matrix33<ScalarType>>(
325 PositionType(v.principalCurvature().maxDir().cross(v.normal())),
326 -(M_PI * 0.5 - angle));
327
328 v.principalCurvature().maxDir() = rot * v.principalCurvature().maxDir();
329
330 angle = acos(v.principalCurvature().minDir().dot(v.normal()));
331
332 rot = rotationMatrix<Matrix33<ScalarType>>(
333 PositionType(v.principalCurvature().minDir().cross(v.normal())),
334 -(M_PI * 0.5 - angle));
335
336 v.principalCurvature().minDir() = rot * v.principalCurvature().minDir();
337
338 // computes the curvature values
339 const ScalarType r5 = std::pow(radius, 5);
340 const ScalarType r6 = r5 * radius;
341 v.principalCurvature().maxValue() =
342 (2.0 / 5.0) *
343 (4.0 * M_PI * r5 + 15 * eigenvalues[(best + 2) % 3] -
344 45.0 * eigenvalues[(best + 1) % 3]) /
345 (M_PI * r6);
346 v.principalCurvature().minValue() =
347 (2.0 / 5.0) *
348 (4.0 * M_PI * r5 + 15 * eigenvalues[(best + 1) % 3] -
349 45.0 * eigenvalues[(best + 2) % 3]) /
350 (M_PI * r6);
351 if (v.principalCurvature().maxValue() <
352 v.principalCurvature().minValue()) {
353 std::swap(
354 v.principalCurvature().minValue(),
355 v.principalCurvature().maxValue());
356 std::swap(
357 v.principalCurvature().minDir(),
358 v.principalCurvature().maxDir());
359 }
360
361 log.progress(m.index(v));
362 //}
363 });
364
365 log.endProgress();
366 log.log(100, "Per vertex curvature computed.");
367}
368
369template<FaceMeshConcept MeshType, LoggerConcept LogType = NullLogger>
370void updatePrincipalCurvature(MeshType& m, LogType& log = nullLogger)
371{
372 requirePerVertexPrincipalCurvature(m);
373
374 updatePrincipalCurvatureTaubin95(m, log);
375}
376
377template<FaceMeshConcept MeshType, LoggerConcept LogType = NullLogger>
378void updatePrincipalCurvature(
379 MeshType& m,
380 PrincipalCurvatureAlgorithm alg = PrincipalCurvatureAlgorithm::TAUBIN95,
381 LogType& log = nullLogger)
382{
383 using enum PrincipalCurvatureAlgorithm;
384 requirePerVertexPrincipalCurvature(m);
385
386 double radius;
387 switch (alg) {
388 case TAUBIN95: updatePrincipalCurvatureTaubin95(m, log); break;
389 case PCA:
390 radius = boundingBox(m).diagonal() * 0.1;
391 updatePrincipalCurvaturePCA(m, radius, true, log);
392 }
393}
394
395} // namespace vcl
396
397#endif // VCL_ALGORITHMS_MESH_UPDATE_CURVATURE_H
auto diagonal() const
Calculates the diagonal length of the box.
Definition box.h:246
Box()
The Empty constructor of a box, initializes a null box.
Definition box.h:65
PointT size() const
Computes the size of the box.
Definition box.h:267
NullLogger nullLogger
The nullLogger object is an object of type NullLogger that is used as default argument in the functio...
Definition null_logger.h:123
auto boundingBox(const PointType &p)
Compute the bounding box of a single point.
Definition bounding_box.h:59
auto faceArea(const FaceType &f)
Computes the area of a face. Works both for triangle and polygonal faces, and it is optimized in case...
Definition geometry.h:108
void requirePerFaceAdjacentFaces(const MeshType &m)
This function asserts that a Mesh has a FaceContainer, the Face has a AdjacentFaces Component,...
Definition face_requirements.h:1037
constexpr detail::VerticesView vertices
A view that allows to iterate over the Vertex elements of an object.
Definition vertex.h:92
constexpr detail::AddressOfView addrOf
The addrOf view applies the address-of operator & on the input view.
Definition pointers.h:120