Lagrange
compute_triangle_normal.h
1/*
2 * Copyright 2017 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12#pragma once
13
14#include <exception>
15
16#include <lagrange/Mesh.h>
17#include <lagrange/MeshTrait.h>
18#include <lagrange/legacy/inline.h>
19
20namespace lagrange {
21LAGRANGE_LEGACY_INLINE
22namespace legacy {
23
24template <typename MeshType>
25auto compute_triangle_normal_const(const MeshType& mesh) -> typename MeshType::AttributeArray
26{
27 static_assert(MeshTrait<MeshType>::is_mesh(), "Input type is not Mesh");
28 using Index = IndexOf<MeshType>;
29 using Scalar = ScalarOf<MeshType>;
30 using AttributeArray = typename MeshType::AttributeArray;
31 using RowVector3s = Eigen::Matrix<Scalar, 1, 3>;
32
33 if (mesh.get_vertex_per_facet() != 3) {
34 throw std::runtime_error("Input mesh is not triangle mesh.");
35 }
36 if (mesh.get_dim() != 3) {
37 throw std::runtime_error("Input mesh vertices should have dimension 3.");
38 }
39
40 const auto& vertices = mesh.get_vertices();
41 const auto& facets = mesh.get_facets();
42 AttributeArray normals(facets.rows(), 3);
43
44 // Iterate over facets in parallel
45 tbb::parallel_for(Index(0), mesh.get_num_facets(), [&](Index f) {
46 const RowVector3s p0 = vertices.row(facets(f, 0));
47 const RowVector3s p1 = vertices.row(facets(f, 1));
48 const RowVector3s p2 = vertices.row(facets(f, 2));
49 normals.row(f) = (p1 - p0).cross(p2 - p0).stableNormalized();
50 });
51
52 return normals;
53}
54
55template <typename MeshType>
56void compute_triangle_normal(MeshType& mesh)
57{
58 mesh.add_facet_attribute("normal");
59 mesh.import_facet_attribute("normal", compute_triangle_normal_const(mesh));
60}
61
62} // namespace legacy
63} // namespace lagrange
Definition: Mesh.h:48
Main namespace for Lagrange.
Definition: AABBIGL.h:30