From 8655e39fba09d2c0a0ab3d5f1545814d737a8089 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9ophile=20Bastian?= Date: Tue, 6 Feb 2018 20:45:23 +0100 Subject: [PATCH] Add center to a mesh to allow easy translation --- Mesh.cpp | 27 +++++++++++++++++++++++++++ Mesh.hpp | 13 +++++++++++++ common_structures.hpp | 24 ++++++++++++++++++++++++ 3 files changed, 64 insertions(+) diff --git a/Mesh.cpp b/Mesh.cpp index 815aad2..7fd709d 100644 --- a/Mesh.cpp +++ b/Mesh.cpp @@ -1,6 +1,7 @@ #include "Mesh.hpp" Mesh::Mesh() + : center(Point(.0, .0, .0)) { } @@ -16,6 +17,32 @@ void Mesh::add_face(size_t f1, size_t f2, size_t f3) { add_face(Face(f1, f2, f3)); } +const Point& Mesh::get_center() const { + return center; +} + +void Mesh::set_center(const Point& pt) { + center = pt; +} +void Mesh::translate(const Point& tr) { + center += tr; +} + +void Mesh::normalize_center(bool keep_position) { + Point bary(0., 0., 0.); + for(const Point& vert: vertices) + bary += vert; + bary = (1. / ((double)vertices.size())) * bary; + + for(Point& vert: vertices) + vert -= bary; + + if(keep_position) + translate(bary); + else + set_center(Point(0, 0, 0)); +} + const std::vector& Mesh::get_vertices() const { return vertices; } diff --git a/Mesh.hpp b/Mesh.hpp index e46c127..43d668f 100644 --- a/Mesh.hpp +++ b/Mesh.hpp @@ -20,6 +20,17 @@ class Mesh { void add_face(const Face& face); void add_face(size_t f1, size_t f2, size_t f3); + /// Center manipulation + const Point& get_center() const; + void set_center(const Point& pt); + void translate(const Point& tr); ///< Translate by the vector `tr` + + /** Translates the vertices to make (0, 0, 0) the mesh's barycenter. + * If `keep_position == true`, this also sets the center to the + * previous barycenter. + */ + void normalize_center(bool keep_position=false); + /// Gets the various vertices const std::vector& get_vertices() const; @@ -29,4 +40,6 @@ class Mesh { private: std::vector vertices; std::vector faces; + + Point center; }; diff --git a/common_structures.hpp b/common_structures.hpp index 8c88a13..adf9d9f 100644 --- a/common_structures.hpp +++ b/common_structures.hpp @@ -21,6 +21,30 @@ struct Point { default: return 0; } } + + Point operator+(const Point& pt) const { + return Point( + x + pt.x, + y + pt.y, + z + pt.z); + } + Point& operator+=(const Point& pt) { + x += pt.x; + y += pt.y; + z += pt.z; + return *this; + } + + Point& operator-=(const Point& pt) { + return (*this += Point(-pt.x, -pt.y, -pt.z)); + } + + friend Point operator*(double scalar, const Point& pt) { + return Point( + scalar * pt.x, + scalar * pt.y, + scalar * pt.z); + } }; struct Face {