Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_601_Tessellator

Triangulating general polygonal faces (concave, self-intersecting, and with holes) using the Tessellator.

Overview

This tutorial builds a tiny SurfaceMesh whose three faces are deliberately "hard" to triangulate — a concave quad, a self-intersecting star, and a quad with a rectangular hole — and then converts the whole mesh into triangles with the Tessellator. It shows the general recipe for turning arbitrary planar contours into a triangle soup that a GPU can actually rasterize.

The technique

Graphics hardware renders triangles, so any polygon that is not already a triangle must be decomposed. Simple convex polygons are easy (a fan from one vertex), but concave polygons, polygons with holes, and self-intersecting contours break naive fans and ear-clipping. The robust solution, used by the OpenGL Utility (GLU) tessellator and by Easy3D's Tessellator, is a sweep-line algorithm: the contour edges are intersected to form a planar subdivision, and each resulting face is classified as interior or exterior using a winding rule. The winding number of a point counts how many times the contour loops around it; WINDING_NONZERO fills every region with a non-zero count (so a self-intersecting star becomes a solid pentagram), while WINDING_ODD fills only regions encircled an odd number of times (which is how a hole — a contour nested inside the outer boundary — is carved out). All input is first projected onto the plane perpendicular to a supplied normal, and the output triangles are oriented counter-clockwise with respect to that normal. See the OpenGL Programming Guide (the "Red Book"), chapter 11, for the classic description of winding rules and the GLU tessellator.

Easy3D API

Running it

A window opens showing the three tessellated shapes side by side, with spheres at the vertices and the triangle edges and borders drawn. The star is filled solid (non-zero rule) and the third quad has a rectangular hole (odd rule). For general rendering you can also let the tessellator build a DrawableTriangles directly, without explicitly rewriting the mesh.

1
27#include <easy3d/viewer/viewer.h>
28#include <easy3d/renderer/camera.h>
29#include <easy3d/core/surface_mesh.h>
30#include <easy3d/renderer/drawable_points.h>
31#include <easy3d/renderer/drawable_lines.h>
32#include <easy3d/renderer/renderer.h>
33#include <easy3d/algo/tessellator.h>
34#include <easy3d/util/initializer.h>
35
85using namespace easy3d;
86
87// A hole is stored as an extra closed contour (a list of 3D points) attached to a face.
88typedef std::vector<vec3> Hole;
89
90// Convert every face of the mesh into triangles using the tessellator, then rebuild the mesh
91// from the tessellator's output vertices and triangle indices.
92void triangulate(SurfaceMesh *mesh) {
93 if (!mesh)
94 return;
95
96 // The tessellator projects each face onto a plane, so it needs a reliable per-face normal.
97 mesh->update_face_normals();
98 auto normals = mesh->face_property<vec3>("f:normal");
99 // Optional property: faces may carry hole contours (absent for most meshes).
100 auto holes = mesh->get_face_property<Hole>("f:holes");
101
102 Tessellator tessellator;
103 for (auto f : mesh->faces()) {
104 // Start a new complex polygon lying in the plane with this normal. Output triangles
105 // will be oriented counter-clockwise with respect to it.
106 tessellator.begin_polygon(normals[f]);
107
108 // The outer boundary: fill every region with non-zero winding number. This also fills
109 // self-intersecting contours (e.g. the star below) into a solid shape.
110 tessellator.set_winding_rule(Tessellator::WINDING_NONZERO);
111 tessellator.begin_contour();
112 for (auto h : mesh->halfedges(f)) {
113 SurfaceMesh::Vertex v = mesh->target(h);
114 // Passing v.idx() lets us map tessellator output vertices back to the original mesh
115 // vertices; vertices created at edge intersections get index -1 instead.
116 tessellator.add_vertex(mesh->position(v), v.idx());
117 }
118 tessellator.end_contour();
119
120 if (holes && holes[f].size() >= 3) { // has a valid hole
121 // A hole is just another contour of the same complex polygon. With the odd winding
122 // rule, the region inside the hole is encircled twice (even) and stays unfilled.
123 tessellator.set_winding_rule(Tessellator::WINDING_ODD);
124 tessellator.begin_contour();
125 for (const auto &p : holes[f])
126 tessellator.add_vertex(p);
127 tessellator.end_contour();
128 }
129
130 // Run the sweep-line tessellation for this face.
131 tessellator.end_polygon();
132 }
133
134 // now the tessellation is done. We can clear the old mesh and
135 // fill it will the new set of triangles
136
137 mesh->clear();
138
139 const auto &triangles = tessellator.elements();
140 if (triangles.empty())
141 return; // in degenerate cases num can be zero
142
143 // The tessellator welds duplicate positions into unique vertices, so the element (index)
144 // buffer can reference them without sending repeated coordinates to the GPU.
145 const auto &vts = tessellator.vertices();
146 for (auto v : vts)
147 mesh->add_vertex(vec3(v->data()));
148
149 // Each element is a triple of indices into the vertex list above.
150 for (const auto &t : triangles) {
151 mesh->add_triangle(SurfaceMesh::Vertex(static_cast<int>(t[0])), SurfaceMesh::Vertex(static_cast<int>(t[1])),
152 SurfaceMesh::Vertex(static_cast<int>(t[2])));
153 }
154}
155
156std::shared_ptr<SurfaceMesh> create_tessellation_mesh() {
157 //-------- create a simple mesh with 3 complex faces ---------
158 // All geometry lies in the z = 0 plane so the tessellator works in a well-defined 2D plane.
159
160 auto mesh = std::make_shared<SurfaceMesh>();
161
162 { // face 1: a concave quad
163 // v3 dents inward, so a naive triangle fan would produce triangles outside the face.
164 auto v0 = mesh->add_vertex(vec3(0, 0, 0));
165 auto v1 = mesh->add_vertex(vec3(800, 0, 0));
166 auto v2 = mesh->add_vertex(vec3(800, 800, 0));
167 auto v3 = mesh->add_vertex(vec3(600, 300, 0));
168 mesh->add_quad(v0, v1, v2, v3);
169 }
170
171 { // face 2: a self-intersecting face representing a star
172 // The vertex order makes the boundary cross itself (a pentagram). The non-zero winding
173 // rule fills the whole star, including the central pentagon.
174 auto vertices = {mesh->add_vertex(vec3(1500, 0, 0)), mesh->add_vertex(vec3(1300, 800, 0)),
175 mesh->add_vertex(vec3(1100, 0, 0)), mesh->add_vertex(vec3(1700, 500, 0)),
176 mesh->add_vertex(vec3(900, 500, 0))};
177 mesh->add_face(vertices);
178 }
179
180 { // face 3: a quad face with a hole
181 auto vertices = {mesh->add_vertex(vec3(1800, 0, 0)), mesh->add_vertex(vec3(2200, 0, 0)),
182 mesh->add_vertex(vec3(2200, 700, 0)), mesh->add_vertex(vec3(1800, 700, 0))};
183 auto f = mesh->add_face(vertices);
184
185 // let's create a hole (also a quad shape) in this face
186 // SurfaceMesh has no native hole representation, so we attach the hole contour as a
187 // custom face property; triangulate() feeds it to the tessellator as a second contour.
188 auto holes = mesh->add_face_property<Hole>("f:holes");
189 holes[f] = {vec3(1900, 100, 0), vec3(2100, 100, 0), vec3(2100, 600, 0), vec3(1900, 600, 0)};
190 }
191
192 //-------- triangulate the mesh using the tessellator ---------
193
194 triangulate(mesh.get());
195
196 // ------------------------------------------------------------
197
198 return mesh;
199}
200
201int main(int argc, char **argv) {
202 // Bootstrap Easy3D (logging, resource directory, ...). Must come first.
203 initialize();
204 Viewer viewer(EXAMPLE_TITLE);
205
206 // Look straight down onto the XY plane: y is up on screen, the camera looks along -z.
207 viewer.camera()->set_up_vector(vec3(0, 1, 0));
208 viewer.camera()->set_view_direction(vec3(0, 0, -1));
209 auto mesh = create_tessellation_mesh();
210 if (!mesh || mesh->empty())
211 return EXIT_FAILURE;
212 // add the model to the viewer (true: center and scale it to fit the scene).
213 viewer.add_model(mesh, true);
214
215 // show the vertices (as sphere impostors, so they stay round at any zoom level)
216 mesh->renderer()->get_points_drawable("vertices")->set_visible(true);
217 mesh->renderer()->get_points_drawable("vertices")->set_impostor_type(easy3d::PointsDrawable::SPHERE);
218 mesh->renderer()->get_points_drawable("vertices")->set_point_size(8);
219 // show the edges (the triangulation produced by the tessellator)
220 mesh->renderer()->get_lines_drawable("edges")->set_visible(true);
221 // also show the borders (the outer silhouette, including the hole boundary)
222 mesh->renderer()->get_lines_drawable("borders")->set_visible(true);
223
224 // Enter the interactive loop (returns when the window is closed).
225 return viewer.run();
226}
@ SPHERE
The points will be drawn as spheres.
Definition drawable_points.h:62
int idx() const
Get the underlying index of this handle.
Definition surface_mesh.h:72
A halfedge data structure for polygonal meshes of 2-manifold topology.
Definition surface_mesh.h:51
Tessellator subdivides concave planar polygons, polygons with holes, or polygons with intersecting ed...
Definition tessellator.h:55
void begin_polygon(const vec3 &normal)
Begin the tessellation of a complex polygon.
Definition tessellator.cpp:145
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143
Definition collider.cpp:182
void initialize(bool info_to_stdout, bool use_log_file, bool use_setting_file, const std::string &resource_dir)
Initialization of Easy3D.
Definition initializer.cpp:39
This type represents a vertex (internally it is basically an index).
Definition surface_mesh.h:135
See also
Tessellator, SurfaceMesh, Viewer, Tutorial_602_ConvexPartition, Tutorial_603_CSG