Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_603_CSG

Computing 2D constructive solid geometry (union, intersection, difference) on polygons with the csg operators.

Overview

This tutorial computes the three classic 2D boolean operations on two overlapping squares using the csg operators provided in easy3d/algo/tessellator.h. The result is shown in a 2 x 2 MultiViewer so the inputs and the three operations can be compared side by side:

The technique

Constructive solid geometry builds complex shapes by combining simpler ones with set operations. In 2D these are exactly the boolean operations on regions: union (A | B) is the area covered by either, intersection (A & B) the area covered by both, and difference (A - B) the part of A not covered by B. The csg operators accept polygons of unknown structure (e.g., self-intersecting or overlapping contours) and return simple contours: counter-clockwise contours define the outer boundary and clockwise contours define holes. Internally they reuse the same sweep-line + winding-number machinery as the Tessellator (see Tutorial_601_Tessellator): each operation corresponds to a different winding rule for classifying the interior of the combined contours — union keeps regions with non-zero winding, intersection keeps regions covered by both inputs, and difference subtracts one region's winding from the other's. The returned simple contours are then filled into a triangle mesh with the Tessellator for display. See the OpenGL Programming Guide (the "Red Book"), chapter 11, for the winding-rule formulation of CSG.

Easy3D API

Running it

A 2 x 2 window opens comparing the inputs (top-left) with union (top-right), intersection (bottom-left), and difference (bottom-right). All views share navigation. See Tutorial_602_ConvexPartition for partitioning the resulting simple polygons into convex pieces.

1
27#include <easy3d/viewer/viewer.h>
28#include <easy3d/renderer/camera.h>
29#include <easy3d/core/surface_mesh.h>
30#include <easy3d/core/types.h>
31#include <easy3d/renderer/drawable_lines.h>
32#include <easy3d/renderer/drawable_triangles.h>
33#include <easy3d/renderer/renderer.h>
34#include <easy3d/algo/tessellator.h>
35#include <easy3d/util/initializer.h>
36
85using namespace easy3d;
86
87namespace {
88
89 // Two overlapping squares (both in counter-clockwise order).
90 const std::vector<vec2> square_a = {vec2(0, 0), vec2(400, 0), vec2(400, 400), vec2(0, 400)};
91 const std::vector<vec2> square_b = {vec2(200, 200), vec2(600, 200), vec2(600, 600), vec2(200, 600)};
92
93 enum Operation { CSG_UNION, CSG_INTERSECTION, CSG_DIFFERENCE };
94
95 // Run one boolean operation on the two squares and return the resulting simple contours.
96 std::vector<Polygon2> compute(Operation op) {
97 Polygon2 a(square_a.begin(), square_a.end());
98 Polygon2 b(square_b.begin(), square_b.end());
99 std::vector<Polygon2> result;
100 switch (op) {
101 case CSG_UNION:
102 // Union = tessellate all contours together with the non-zero winding rule:
103 // any region covered by at least one input polygon is kept.
104 result = {a, b};
105 csg::union_of(result);
106 break;
107 case CSG_INTERSECTION:
108 // Intersection = keep only regions covered by both inputs (winding number >= 2
109 // in absolute value, i.e. WINDING_ABS_GEQ_TWO).
110 csg::intersection_of(a, b, result);
111 break;
112 case CSG_DIFFERENCE:
113 // Difference = A with B subtracted: the operator reverses one contour's orientation
114 // and extracts the regions with positive winding number.
115 csg::difference_of(a, b, result);
116 break;
117 }
118 return result;
119 }
120
121 // Fill the resulting contours (CCW outer boundaries, CW holes) into a triangle mesh.
122 void build_mesh(const std::vector<Polygon2> &contours, SurfaceMesh *mesh) {
123 mesh->clear();
124
125 // All contours belong to one complex polygon in the z = 0 plane (normal +z). The CSG
126 // output is already simple, so the non-zero rule fills outer boundaries and leaves
127 // the clockwise hole contours empty.
128 Tessellator tessellator;
129 tessellator.begin_polygon(vec3(0, 0, 1));
130 tessellator.set_winding_rule(Tessellator::WINDING_NONZERO);
131 for (const auto &contour : contours) {
132 tessellator.begin_contour();
133 for (const auto &p : contour)
134 tessellator.add_vertex(vec3(p, 0.0));
135 tessellator.end_contour();
136 }
137 tessellator.end_polygon();
138
139 // Rebuild the mesh from the tessellator's unique vertices and triangle indices.
140 for (auto v : tessellator.vertices())
141 mesh->add_vertex(vec3(v->data()));
142 for (const auto &t : tessellator.elements()) {
143 mesh->add_triangle(SurfaceMesh::Vertex(static_cast<int>(t[0])), SurfaceMesh::Vertex(static_cast<int>(t[1])),
144 SurfaceMesh::Vertex(static_cast<int>(t[2])));
145 }
146 }
147
148 // Show the boundary of a CSG result so its shape is easy to read.
149 void set_boundary_visible(SurfaceMesh *mesh) {
150 auto borders = mesh->renderer()->get_lines_drawable("borders");
151 borders->set_line_width(2.0f);
152 borders->set_visible(true);
153 }
154
155} // namespace
156
157// The default (union) result, also used by the geometry tutorial test.
158std::shared_ptr<SurfaceMesh> create_csg_mesh() {
159 auto mesh = std::make_shared<SurfaceMesh>();
160 build_mesh(compute(CSG_UNION), mesh.get());
161 return mesh;
162}
163
164int main(int argc, char **argv) {
165 // Bootstrap Easy3D (logging, resource directory, ...). Must come first.
166 initialize();
167
168 // A 2 x 2 grid of views sharing one camera, so the inputs and the three boolean
169 // results can be compared side by side under identical navigation.
170 MultiViewer viewer(2, 2, EXAMPLE_TITLE);
171 // Look straight down onto the XY plane: y is up on screen, the camera looks along -z.
172 viewer.camera()->set_up_vector(vec3(0, 1, 0));
173 viewer.camera()->set_view_direction(vec3(0, 0, -1));
174
175 // -------------------------------------------------------------------------
176 // view (0, 0): the two input polygons, in distinct colors.
177 auto input_a = std::make_shared<SurfaceMesh>();
178 auto input_b = std::make_shared<SurfaceMesh>();
179 build_mesh({Polygon2(square_a.begin(), square_a.end())}, input_a.get());
180 build_mesh({Polygon2(square_b.begin(), square_b.end())}, input_b.get());
181 viewer.add_model(input_a);
182 viewer.add_model(input_b);
183 set_boundary_visible(input_a.get());
184 set_boundary_visible(input_b.get());
185
186 // Lift B slightly toward the camera so the overlapping region does not z-fight
187 // and B is drawn on top of A there (the intersection is shown explicitly below).
188 auto points_b = input_b->get_vertex_property<vec3>("v:point");
189 for (auto v : input_b->vertices())
190 points_b[v].z += 1.0f;
191
192 // Color A red and B blue so the two inputs are easy to tell apart in the top-left view.
193 input_a->renderer()->get_triangles_drawable("faces")->set_uniform_coloring(vec4(0.90f, 0.30f, 0.25f, 1.0f));
194 input_b->renderer()->get_triangles_drawable("faces")->set_uniform_coloring(vec4(0.25f, 0.45f, 0.90f, 1.0f));
195 // assign(row, col, model) pins a model to one cell of the grid; both inputs share cell (0, 0).
196 viewer.assign(0, 0, input_a.get());
197 viewer.assign(0, 0, input_b.get());
198
199 // -------------------------------------------------------------------------
200 // view (0, 1): union; view (1, 0): intersection; view (1, 1): difference (A - B).
201 auto union_mesh = create_csg_mesh();
202 auto intersection_mesh = std::make_shared<SurfaceMesh>();
203 build_mesh(compute(CSG_INTERSECTION), intersection_mesh.get());
204 auto difference_mesh = std::make_shared<SurfaceMesh>();
205 build_mesh(compute(CSG_DIFFERENCE), difference_mesh.get());
206 viewer.add_model(union_mesh);
207 viewer.add_model(intersection_mesh);
208 viewer.add_model(difference_mesh);
209 set_boundary_visible(union_mesh.get());
210 set_boundary_visible(intersection_mesh.get());
211 set_boundary_visible(difference_mesh.get());
212 // Each boolean result is pinned to its own cell for the side-by-side comparison.
213 viewer.assign(0, 1, union_mesh.get());
214 viewer.assign(1, 0, intersection_mesh.get());
215 viewer.assign(1, 1, difference_mesh.get());
216
217 // Explain the four cells in the viewer's on-screen help.
218 viewer.set_usage(
219 "default",
220 "Top-left: the two input polygons A (red) and B (blue)\n" "Top-right: union (A | B)\n" "Bottom-left: intersection (A & B)\n" "Bottom-right: difference (A - B)");
221
222 // Enter the interactive loop (returns when the window is closed).
223 return viewer.run();
224}
A polygon represented by an ordered sequence of 2D vertices.
Definition polygon.h:59
A viewer that displays assigned scene content in a grid of views.
Definition multi_viewer.h:55
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
void add_vertex(const Vertex &data)
Add a vertex of a contour to the tessellator.
Definition tessellator.cpp:163
void end_polygon()
Finish tessellating the current polygon and append its elements to the result.
Definition tessellator.cpp:233
void begin_contour()
Begin a contour of the current polygon.
Definition tessellator.cpp:158
const std::vector< Vertex * > & vertices() const
Get the unique vertices accumulated since the last reset().
Definition tessellator.cpp:238
const std::vector< std::vector< unsigned int > > & elements() const
Get elements accumulated since the last reset().
Definition tessellator.h:280
void set_winding_rule(WindingRule rule)
Set the winding rule. The new rule will be effective until being changed by calling this function aga...
Definition tessellator.cpp:140
void end_contour()
Finish the current contour.
Definition tessellator.cpp:228
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, MultiViewer, SurfaceMesh, Tutorial_601_Tessellator, Tutorial_602_ConvexPartition