1 #ifndef slic3r_TriangleMesh_hpp_
2 #define slic3r_TriangleMesh_hpp_
3 
4 #include "libslic3r.h"
5 #include <admesh/stl.h>
6 #include <functional>
7 #include <vector>
8 #include <boost/thread.hpp>
9 #include "BoundingBox.hpp"
10 #include "Line.hpp"
11 #include "Point.hpp"
12 #include "Polygon.hpp"
13 #include "ExPolygon.hpp"
14 
15 namespace Slic3r {
16 
17 class TriangleMesh;
18 class TriangleMeshSlicer;
19 typedef std::vector<TriangleMesh*> TriangleMeshPtrs;
20 
21 class TriangleMesh
22 {
23 public:
TriangleMesh()24     TriangleMesh() : repaired(false) {}
25     TriangleMesh(const Pointf3s &points, const std::vector<Vec3i> &facets);
26     explicit TriangleMesh(const indexed_triangle_set &M);
clear()27 	void clear() { this->stl.clear(); this->its.clear(); this->repaired = false; }
ReadSTLFile(const char * input_file)28     bool ReadSTLFile(const char* input_file) { return stl_open(&stl, input_file); }
write_ascii(const char * output_file)29     bool write_ascii(const char* output_file) { return stl_write_ascii(&this->stl, output_file, ""); }
write_binary(const char * output_file)30     bool write_binary(const char* output_file) { return stl_write_binary(&this->stl, output_file, ""); }
31     void repair(bool update_shared_vertices = true);
32     float volume();
33     void check_topology();
is_manifold() const34     bool is_manifold() const { return this->stl.stats.connected_facets_3_edge == (int)this->stl.stats.number_of_facets; }
35     void WriteOBJFile(const char* output_file) const;
36     void scale(float factor);
37     void scale(const Vec3d &versor);
38     void translate(float x, float y, float z);
39     void translate(const Vec3f &displacement);
40     void rotate(float angle, const Axis &axis);
41     void rotate(float angle, const Vec3d& axis);
rotate_x(float angle)42     void rotate_x(float angle) { this->rotate(angle, X); }
rotate_y(float angle)43     void rotate_y(float angle) { this->rotate(angle, Y); }
rotate_z(float angle)44     void rotate_z(float angle) { this->rotate(angle, Z); }
45     void mirror(const Axis &axis);
mirror_x()46     void mirror_x() { this->mirror(X); }
mirror_y()47     void mirror_y() { this->mirror(Y); }
mirror_z()48     void mirror_z() { this->mirror(Z); }
49     void transform(const Transform3d& t, bool fix_left_handed = false);
50 	void transform(const Matrix3d& t, bool fix_left_handed = false);
51     void align_to_origin();
52     void rotate(double angle, Point* center);
53     TriangleMeshPtrs split() const;
54     void merge(const TriangleMesh &mesh);
55     ExPolygons horizontal_projection() const;
first_vertex() const56     const float* first_vertex() const { return this->stl.facet_start.empty() ? nullptr : &this->stl.facet_start.front().vertex[0](0); }
57     // 2D convex hull of a 3D mesh projected into the Z=0 plane.
58     Polygon convex_hull();
59     BoundingBoxf3 bounding_box() const;
60     // Returns the bbox of this TriangleMesh transformed by the given transformation
61     BoundingBoxf3 transformed_bounding_box(const Transform3d &trafo) const;
62     // Return the size of the mesh in coordinates.
size() const63     Vec3d size() const { return stl.stats.size.cast<double>(); }
64     /// Return the center of the related bounding box.
center() const65 	Vec3d center() const { return this->bounding_box().center(); }
66     // Returns the convex hull of this TriangleMesh
67     TriangleMesh convex_hull_3d() const;
68     // Slice this mesh at the provided Z levels and return the vector
69     std::vector<ExPolygons> slice(const std::vector<double>& z);
70     void reset_repair_stats();
71     bool needed_repair() const;
72     void require_shared_vertices();
has_shared_vertices() const73     bool   has_shared_vertices() const { return ! this->its.vertices.empty(); }
facets_count() const74     size_t facets_count() const { return this->stl.stats.number_of_facets; }
empty() const75     bool   empty() const { return this->facets_count() == 0; }
76     bool is_splittable() const;
77     // Estimate of the memory occupied by this structure, important for keeping an eye on the Undo / Redo stack allocation.
78     size_t memsize() const;
79     // Release optional data from the mesh if the object is on the Undo / Redo stack only. Returns the amount of memory released.
80     size_t release_optional();
81 	// Restore optional data possibly released by release_optional().
82 	void restore_optional();
83 
84     stl_file stl;
85     indexed_triangle_set its;
86     bool repaired;
87 
88 private:
89     std::deque<uint32_t> find_unvisited_neighbors(std::vector<unsigned char> &facet_visited) const;
90 };
91 
92 enum FacetEdgeType {
93     // A general case, the cutting plane intersect a face at two different edges.
94     feGeneral,
95     // Two vertices are aligned with the cutting plane, the third vertex is below the cutting plane.
96     feTop,
97     // Two vertices are aligned with the cutting plane, the third vertex is above the cutting plane.
98     feBottom,
99     // All three vertices of a face are aligned with the cutting plane.
100     feHorizontal
101 };
102 
103 class IntersectionReference
104 {
105 public:
IntersectionReference()106     IntersectionReference() : point_id(-1), edge_id(-1) {};
IntersectionReference(int point_id,int edge_id)107     IntersectionReference(int point_id, int edge_id) : point_id(point_id), edge_id(edge_id) {}
108     // Where is this intersection point located? On mesh vertex or mesh edge?
109     // Only one of the following will be set, the other will remain set to -1.
110     // Index of the mesh vertex.
111     int point_id;
112     // Index of the mesh edge.
113     int edge_id;
114 };
115 
116 class IntersectionPoint : public Point, public IntersectionReference
117 {
118 public:
IntersectionPoint()119     IntersectionPoint() {};
IntersectionPoint(int point_id,int edge_id,const Point & pt)120     IntersectionPoint(int point_id, int edge_id, const Point &pt) : IntersectionReference(point_id, edge_id), Point(pt) {}
IntersectionPoint(const IntersectionReference & ir,const Point & pt)121     IntersectionPoint(const IntersectionReference &ir, const Point &pt) : IntersectionReference(ir), Point(pt) {}
122     // Inherits coord_t x, y
123 };
124 
125 class IntersectionLine : public Line
126 {
127 public:
IntersectionLine()128     IntersectionLine() : a_id(-1), b_id(-1), edge_a_id(-1), edge_b_id(-1), edge_type(feGeneral), flags(0) {}
129 
skip() const130     bool skip() const { return (this->flags & SKIP) != 0; }
set_skip()131     void set_skip() { this->flags |= SKIP; }
132 
is_seed_candidate() const133     bool is_seed_candidate() const { return (this->flags & NO_SEED) == 0 && ! this->skip(); }
set_no_seed(bool set)134     void set_no_seed(bool set) { if (set) this->flags |= NO_SEED; else this->flags &= ~NO_SEED; }
135 
136     // Inherits Point a, b
137     // For each line end point, either {a,b}_id or {a,b}edge_a_id is set, the other is left to -1.
138     // Vertex indices of the line end points.
139     int             a_id;
140     int             b_id;
141     // Source mesh edges of the line end points.
142     int             edge_a_id;
143     int             edge_b_id;
144     // feGeneral, feTop, feBottom, feHorizontal
145     FacetEdgeType   edge_type;
146     // Used by TriangleMeshSlicer::slice() to skip duplicate edges.
147     enum {
148         // Triangle edge added, because it has no neighbor.
149         EDGE0_NO_NEIGHBOR   = 0x001,
150         EDGE1_NO_NEIGHBOR   = 0x002,
151         EDGE2_NO_NEIGHBOR   = 0x004,
152         // Triangle edge added, because it makes a fold with another horizontal edge.
153         EDGE0_FOLD          = 0x010,
154         EDGE1_FOLD          = 0x020,
155         EDGE2_FOLD          = 0x040,
156         // The edge cannot be a seed of a greedy loop extraction (folds are not safe to become seeds).
157         NO_SEED             = 0x100,
158         SKIP                = 0x200,
159     };
160     uint32_t        flags;
161 };
162 typedef std::vector<IntersectionLine> IntersectionLines;
163 typedef std::vector<IntersectionLine*> IntersectionLinePtrs;
164 
165 enum class SlicingMode : uint32_t {
166 	// Regular slicing, maintain all contours and their orientation.
167 	Regular,
168 	// Maintain all contours, orient all contours CCW, therefore all holes are being closed.
169 	Positive,
170 	// Orient all contours CCW and keep only the contour with the largest area.
171 	// This mode is useful for slicing complex objects in vase mode.
172 	PositiveLargestContour,
173 };
174 
175 class TriangleMeshSlicer
176 {
177 public:
178     typedef std::function<void()> throw_on_cancel_callback_type;
TriangleMeshSlicer()179     TriangleMeshSlicer() : mesh(nullptr) {}
TriangleMeshSlicer(const TriangleMesh * mesh)180 	TriangleMeshSlicer(const TriangleMesh* mesh) { this->init(mesh, [](){}); }
181     void init(const TriangleMesh *mesh, throw_on_cancel_callback_type throw_on_cancel);
182     void slice(
183         const std::vector<float> &z, SlicingMode mode, size_t alternate_mode_first_n_layers, SlicingMode alternate_mode,
184         std::vector<Polygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const;
slice(const std::vector<float> & z,SlicingMode mode,std::vector<Polygons> * layers,throw_on_cancel_callback_type throw_on_cancel) const185     void slice(const std::vector<float> &z, SlicingMode mode, std::vector<Polygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const
186         { return this->slice(z, mode, 0, mode, layers, throw_on_cancel); }
187     void slice(
188         const std::vector<float> &z, SlicingMode mode, size_t alternate_mode_first_n_layers, SlicingMode alternate_mode, const float closing_radius,
189         std::vector<ExPolygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const;
slice(const std::vector<float> & z,SlicingMode mode,const float closing_radius,std::vector<ExPolygons> * layers,throw_on_cancel_callback_type throw_on_cancel) const190     void slice(const std::vector<float> &z, SlicingMode mode, const float closing_radius,
191         std::vector<ExPolygons>* layers, throw_on_cancel_callback_type throw_on_cancel) const
192         { this->slice(z, mode, 0, mode, closing_radius, layers, throw_on_cancel); }
193     enum FacetSliceType {
194         NoSlice = 0,
195         Slicing = 1,
196         Cutting = 2
197     };
198     FacetSliceType slice_facet(float slice_z, const stl_facet &facet, const int facet_idx,
199         const float min_z, const float max_z, IntersectionLine *line_out) const;
200     void cut(float z, TriangleMesh* upper, TriangleMesh* lower) const;
201     void set_up_direction(const Vec3f& up);
202 
203 private:
204     const TriangleMesh      *mesh;
205     // Map from a facet to an edge index.
206     std::vector<int>         facets_edges;
207     // Scaled copy of this->mesh->stl.v_shared
208     std::vector<stl_vertex>  v_scaled_shared;
209     // Quaternion that will be used to rotate every facet before the slicing
210     Eigen::Quaternion<float, Eigen::DontAlign> m_quaternion;
211     // Whether or not the above quaterion should be used
212     bool                     m_use_quaternion = false;
213 
214     void _slice_do(size_t facet_idx, std::vector<IntersectionLines>* lines, boost::mutex* lines_mutex, const std::vector<float> &z) const;
215     void make_loops(std::vector<IntersectionLine> &lines, Polygons* loops) const;
216     void make_expolygons(const Polygons &loops, const float closing_radius, ExPolygons* slices) const;
217     void make_expolygons_simple(std::vector<IntersectionLine> &lines, ExPolygons* slices) const;
218     void make_expolygons(std::vector<IntersectionLine> &lines, const float closing_radius, ExPolygons* slices) const;
219 };
220 
slice_mesh(const TriangleMesh & mesh,const std::vector<float> & z,std::vector<Polygons> & layers,TriangleMeshSlicer::throw_on_cancel_callback_type thr=nullptr)221 inline void slice_mesh(
222     const TriangleMesh &                              mesh,
223     const std::vector<float> &                        z,
224     std::vector<Polygons> &                           layers,
225     TriangleMeshSlicer::throw_on_cancel_callback_type thr = nullptr)
226 {
227     if (mesh.empty()) return;
228     TriangleMeshSlicer slicer(&mesh);
229     slicer.slice(z, SlicingMode::Regular, &layers, thr);
230 }
231 
slice_mesh(const TriangleMesh & mesh,const std::vector<float> & z,std::vector<ExPolygons> & layers,float closing_radius,TriangleMeshSlicer::throw_on_cancel_callback_type thr=nullptr)232 inline void slice_mesh(
233     const TriangleMesh &                              mesh,
234     const std::vector<float> &                        z,
235     std::vector<ExPolygons> &                         layers,
236     float                                             closing_radius,
237     TriangleMeshSlicer::throw_on_cancel_callback_type thr = nullptr)
238 {
239     if (mesh.empty()) return;
240     TriangleMeshSlicer slicer(&mesh);
241     slicer.slice(z, SlicingMode::Regular, closing_radius, &layers, thr);
242 }
243 
244 TriangleMesh make_cube(double x, double y, double z);
245 
246 // Generate a TriangleMesh of a cylinder
247 TriangleMesh make_cylinder(double r, double h, double fa=(2*PI/360));
248 
249 TriangleMesh make_sphere(double rho, double fa=(2*PI/360));
250 
251 }
252 
253 // Serialization through the Cereal library
254 #include <cereal/access.hpp>
255 namespace cereal {
256 	template <class Archive> struct specialize<Archive, Slic3r::TriangleMesh, cereal::specialization::non_member_load_save> {};
load(Archive & archive,Slic3r::TriangleMesh & mesh)257 	template<class Archive> void load(Archive &archive, Slic3r::TriangleMesh &mesh) {
258         stl_file &stl = mesh.stl;
259         stl.stats.type = inmemory;
260 		archive(stl.stats.number_of_facets, stl.stats.original_num_facets);
261         stl_allocate(&stl);
262 		archive.loadBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50);
263         stl_get_size(&stl);
264         mesh.repair();
265 	}
save(Archive & archive,const Slic3r::TriangleMesh & mesh)266 	template<class Archive> void save(Archive &archive, const Slic3r::TriangleMesh &mesh) {
267 		const stl_file& stl = mesh.stl;
268 		archive(stl.stats.number_of_facets, stl.stats.original_num_facets);
269 		archive.saveBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50);
270 	}
271 }
272 
273 #endif
274