Real-time collision detection between two meshes, with intersecting faces highlighted.
This tutorial loads two meshes (a bunny and a mannequin), animates the bunny, and continuously reports which faces of the two meshes intersect, painting them red. Pausing the animation lets the user drag the bunny around (as in Tutorial_404_ObjectManipulation) and watch the contact regions update in real time. Unlike the other 4xx tutorials, all scene setup happens in the viewer's constructor, so main() only creates the viewer and runs it.
Testing every face of one mesh against every face of the other is O(n*m) — far too slow for interactive rates on large meshes. The standard solution is a bounding volume hierarchy (BVH): each mesh is preprocessed once into a tree of axis-aligned bounding boxes (AABBs), with the actual triangles at the leaves. A collision query then walks both trees simultaneously, discarding whole branches whose boxes do not overlap, and only performs exact triangle-triangle intersection tests on the few leaf pairs that survive. Easy3D's Collider wraps the Opcode library (Pierre Terdiman), which achieves real-time performance even for large meshes. Crucially, the trees are built in each mesh's local space and the current transformation matrices are passed to every detect() call — so moving or rotating a mesh never requires rebuilding the trees. The demo visualizes the result by storing a per-face color property: all faces start in the mesh's base color, and every reported intersecting face pair is painted red.
On start, an animation rotates the bunny and highlights intersecting faces in red. Press 'space' (or F2) to pause/resume. While paused, Alt + left-drag rotates the bunny and Alt + right-drag translates it; collisions are recomputed during every drag.
31#include <easy3d/renderer/drawable_triangles.h>
32#include <easy3d/renderer/manipulator.h>
33#include <easy3d/renderer/manipulated_frame.h>
34#include <easy3d/renderer/renderer.h>
35#include <easy3d/util/resource.h>
36#include <easy3d/algo/collider.h>
42TutorialCollisionDetection::TutorialCollisionDetection(
const std::string &title)
43 :
Viewer(title), model0_color_(.8f, 1, .8f), model1_color_(.8f, .8f, 1) {
45 "--------------------- Collision Viewer usage ----------------------\n"
46 "On start, you will see an animation with highlighted intersecting \n"
47 "faces. Press 'space' to pause/resume the animation. \n"
48 "When the animation is paused, you can manipulate the bunny model \n"
49 "(using your mouse) to perform real-time collection detection: \n"
50 " - Alt + left button: rotate bunny model \n"
51 " - Alt + right button: translate bunny model \n"
52 "------------------------------------------------------------------ \n";
54 "Press 'space' to pause/resume animation\n"
56 " - Alt + left button: rotate bunny model\n"
57 " - Alt + right button: translate bunny model";
58 add_model(resource::directory() +
"/data/bunny.ply");
59 add_model(resource::directory() +
"/data/mannequin.ply");
60 animation_func_ = [
this](
Viewer *) {
64 initialize_collision();
66TutorialCollisionDetection::~TutorialCollisionDetection() {
72bool TutorialCollisionDetection::collision_models_valid()
const {
73 if (!collider_ || models().size() != 2)
75 for (
unsigned i = 0; i < 2; ++i) {
76 const auto model = collision_models_[i].lock();
77 if (!model || !model->renderer() || !model->manipulator() ||
78 std::find(models().begin(), models().end(), model) == models().end())
83void TutorialCollisionDetection::initialize_collision() {
85 if (models().size() != 2)
86 throw std::invalid_argument(
"collision example requires two triangle meshes");
87 auto first = std::dynamic_pointer_cast<SurfaceMesh>(models()[0]);
88 auto second = std::dynamic_pointer_cast<SurfaceMesh>(models()[1]);
89 if (!first || !second || first->n_faces() == 0 || second->n_faces() == 0 || !first->is_triangle_mesh() ||
90 !second->is_triangle_mesh())
91 throw std::invalid_argument(
"collision example requires two nonempty triangle meshes");
92 for (
const auto &mesh : {first, second})
93 if (!mesh->manipulator())
94 mesh->set_manipulator(std::make_shared<Manipulator>(mesh.get()));
95 first->add_face_property<
vec3>(
"face_color", model0_color_);
96 second->add_face_property<
vec3>(
"face_color", model1_color_);
97 for (
const auto &mesh : {first, second})
98 mesh->renderer()->get_triangles_drawable(
"faces")->set_coloring(State::COLOR_PROPERTY, State::FACE,
100 collider_.reset(
new Collider(first.get(), second.get()));
101 collision_models_[0] = first;
102 collision_models_[1] = second;
105 next_tick_ = std::chrono::steady_clock::now() + std::chrono::milliseconds(50);
108void TutorialCollisionDetection::end_model_drag() {
109 if (
auto model = drag_model_.lock())
110 if (model->manipulator())
111 model->manipulator()->frame()->action_end();
114void TutorialCollisionDetection::retire_collision() {
115 set_animation(
false);
118 for (
unsigned i = 0; i < 2; ++i)
119 if (
const auto mesh = collision_models_[i].lock()) {
120 auto colors = mesh->get_face_property<
vec3>(
"face_color");
122 colors.vector().assign(mesh->n_faces(), i == 0 ? model0_color_ : model1_color_);
123 if (mesh->renderer())
124 mesh->renderer()->update();
128 collision_models_[0].reset();
129 collision_models_[1].reset();
131void TutorialCollisionDetection::advance() {
132 if (!collision_models_valid()) {
136 const auto now = std::chrono::steady_clock::now();
137 if (now < next_tick_)
139 next_tick_ = now + std::chrono::milliseconds(50);
140 const auto mesh = collision_models_[0].lock();
142 const auto pose = mat4::rotation(
vec3(0, 0, 1), angle_) * mesh->manipulator()->frame()->matrix();
143 mesh->manipulator()->frame()->set_from_matrix(pose);
146void TutorialCollisionDetection::detect() {
147 if (!collision_models_valid()) {
151 const auto first = collision_models_[0].lock();
152 const auto second = collision_models_[1].lock();
153 const auto pairs = collider_->detect(first->manipulator()->matrix(), second->manipulator()->matrix());
154 auto colors0 = first->get_face_property<
vec3>(
"face_color");
155 auto colors1 = second->get_face_property<
vec3>(
"face_color");
156 colors0.vector().assign(first->n_faces(), model0_color_);
157 colors1.vector().assign(second->n_faces(), model1_color_);
158 for (
const auto &pair : pairs) {
159 colors0[pair.first] =
vec3(1, 0, 0);
160 colors1[pair.second] =
vec3(1, 0, 0);
162 first->renderer()->update();
163 second->renderer()->update();
166bool TutorialCollisionDetection::key_press_event(
int key,
int modifiers) {
167 if ((key == KEY_SPACE || key == KEY_F2) && modifiers == 0) {
170 set_animation(
false);
171 else if (collision_models_valid()) {
172 next_tick_ = std::chrono::steady_clock::now() + std::chrono::milliseconds(50);
177 return Viewer::key_press_event(key, modifiers);
179bool TutorialCollisionDetection::mouse_press_event(
int x,
int y,
int button,
int modifiers) {
181 if (modifiers == MODIF_ALT && !is_animating() && collision_models_valid() &&
182 (button == BUTTON_LEFT || button == BUTTON_RIGHT)) {
183 const auto mesh = collision_models_[0].lock();
184 mesh->manipulator()->frame()->action_start();
188 return Viewer::mouse_press_event(x, y, button, modifiers);
190bool TutorialCollisionDetection::mouse_drag_event(
int x,
int y,
int dx,
int dy,
int button,
int modifiers) {
191 const auto mesh = drag_model_.lock();
192 if (modifiers == MODIF_ALT && !is_animating() && collision_models_valid() && mesh) {
193 if (button == BUTTON_LEFT)
194 mesh->manipulator()->frame()->action_rotate(x, y, dx, dy, camera(), ManipulatedFrame::NONE);
195 else if (button == BUTTON_RIGHT)
196 mesh->manipulator()->frame()->action_translate(x, y, dx, dy, camera(), ManipulatedFrame::NONE);
202 return Viewer::mouse_drag_event(x, y, dx, dy, button, modifiers);
204bool TutorialCollisionDetection::mouse_release_event(
int x,
int y,
int button,
int modifiers) {
206 return Viewer::mouse_release_event(x, y, button, modifiers);
208bool TutorialCollisionDetection::focus_event(
bool focused) {
213void TutorialCollisionDetection::post_resize(
int,
int) {
216bool TutorialCollisionDetection::delete_model(
Model *model) {
217 if (collision_models_[0].lock().get() == model || collision_models_[1].lock().get() == model) {
220 return Viewer::delete_model(model);
222void TutorialCollisionDetection::clear_scene() {
224 Viewer::clear_scene();
Efficient collision detection.
Definition collider.h:51