Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_404_ObjectManipulation

Moving and rotating an individual model in 3D with the mouse, using the Manipulator class.

Overview

This tutorial combines picking (Tutorial_401_ModelPicker) with interactive object manipulation: click a letter of the "easy3d" logo to select it, then drag with Alt held to rotate or translate that model while the camera stays put. It is the standard "select and transform" interaction of 3D editors and games, and the same machinery drives the interactive collision demo in Tutorial_406_CollisionDetection.

The technique

The core idea is a manipulated frame: a local coordinate frame attached to the object (origin at the object center) whose rotation and translation accumulate the user's drag gestures. The frame's matrix becomes the model's transform, so the geometry itself is never edited — moving an object is just changing one 4x4 matrix. Mouse motion is converted to frame motion by the classic trackball technique (see e.g. Chen et al., "A Study in Interactive 3-D Rotation Using 2-D Control Devices", 1988): a 2D drag is mapped onto a virtual sphere surrounding the object, giving intuitive free rotation; translation drags the object in the screen-parallel plane. Holding 'X', 'Y', or 'O' during a drag constrains the motion to a horizontal, vertical, or view-orthogonal screen axis. The action_start() / action_end() pair brackets a drag so the frame can snapshot its state and apply incremental updates consistently. Which object receives the gestures is decided by GPU picking (Viewer::pick(), see Tutorial_401_ModelPicker), and a visual gizmo (the manipulated frame's axes) is drawn as a screen overlay so the user sees what is being manipulated.

Easy3D API

Running it

Left-click a model to select it (click again to deselect). With a model selected: Alt + left-drag rotates it, Alt + right-drag translates it; hold 'X'/'Y'/'O' during the drag to constrain the motion to a screen axis. Without Alt, the mouse controls the camera as usual.

1
27#include "viewer.h"
28#include <easy3d/util/resource.h>
29#include <easy3d/util/initializer.h>
30
85using namespace easy3d;
86
87int main(int argc, char **argv) {
88 // Bootstrap Easy3D (logging, resource directory, ...). Must come first.
89 initialize();
90
91 // Our custom viewer: a Viewer subclass that lets the user pick and then move a model.
92 TutorialObjectManipulation viewer(EXAMPLE_TITLE);
93
94 // Load the six letters of the "easy3d" logo; each becomes independently manipulable.
95 viewer.add_model(resource::directory() + "/data/easy3d/easy3d_e.ply");
96 viewer.add_model(resource::directory() + "/data/easy3d/easy3d_a.ply");
97 viewer.add_model(resource::directory() + "/data/easy3d/easy3d_s.ply");
98 viewer.add_model(resource::directory() + "/data/easy3d/easy3d_y.ply");
99 viewer.add_model(resource::directory() + "/data/easy3d/easy3d_3.ply");
100 viewer.add_model(resource::directory() + "/data/easy3d/easy3d_d.ply");
101
102 // add_model() returns nullptr on failure; if nothing loaded, there is nothing to manipulate.
103 if (viewer.models().empty()) {
104 std::cerr << "failed to load the model. Please make sure the file exists and format is correct" << std::endl;
105 return EXIT_FAILURE;
106 }
107
108 // Enter the interactive loop (returns when the window is closed).
109 return viewer.run();
110}
Definition collider.cpp:182

The header file of the viewer class:

1
27#ifndef EASY3D_TUTORIAL_OBJECT_MANIPULATION_VIEWER_H
28#define EASY3D_TUTORIAL_OBJECT_MANIPULATION_VIEWER_H
29
30#include <easy3d/viewer/viewer.h>
31
32// This class demonstrates how to manipulate an object in the 3D space using the mouse.
33
34// Forward declaration only: the header just needs the Model name for its signatures, so we
35// avoid pulling the full model header into every includer.
36namespace easy3d {
37 class Model;
38}
39
50class TutorialObjectManipulation : public easy3d::Viewer {
51public:
52 // Sets up a front view of the logo and installs the usage manual/hint.
53 explicit TutorialObjectManipulation(const std::string &title);
54
55protected:
56 // Plain left click picks a model; Alt + button starts a manipulation drag.
57 bool mouse_press_event(int x, int y, int button, int modifiers) override;
58 // Alt + drag rotates (left) or translates (right) the model being dragged.
59 bool mouse_drag_event(int x, int y, int dx, int dy, int button, int modifiers) override;
60 // Any release ends an in-flight manipulation drag.
61 bool mouse_release_event(int x, int y, int button, int modifiers) override;
62 // Losing focus aborts the drag (the release may arrive elsewhere).
63 bool focus_event(bool focused) override;
64 // A resize invalidates screen-space drag coordinates, so abort the drag.
65 void post_resize(int width, int height) override;
66 // Draws the selected model's manipulation gizmo (or clears the overlay).
67 void pre_draw() override;
68
69private:
70 // Selects/deselects the clicked model and attaches a Manipulator when selected.
71 void mark(easy3d::Model *model);
72
73 // Returns the selected model only if it is still alive, in the scene, and manipulable.
74 std::shared_ptr<easy3d::Model> selected_model() const;
75 // Ends the current drag (action_end on the frame) and forgets the dragged model.
76 void end_model_drag();
77 // Weak (non-owning) handles: the currently selected model and the one being dragged.
78 std::weak_ptr<easy3d::Model> selected_model_, drag_model_;
79};
80
81#endif // EASY3D_TUTORIAL_OBJECT_MANIPULATION_VIEWER_H
Base class for spatial models with optional rendering and manipulation state.
Definition model.h:53
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143

The source file of the viewer class:

1
27#include "viewer.h"
28#include <easy3d/renderer/camera.h>
29#include <easy3d/core/model.h>
30#include <easy3d/renderer/drawable_triangles.h>
31#include <easy3d/renderer/renderer.h>
32#include <easy3d/renderer/manipulator.h>
33#include <easy3d/renderer/manipulated_frame.h>
34
35using namespace easy3d;
36
37// The implementation is reproduced on the example page via \include in main.cpp, so we hide
38// it from Doxygen's separate symbol documentation to avoid documenting it twice.
39// \cond
40
41TutorialObjectManipulation::TutorialObjectManipulation(const std::string &title) : Viewer(title) {
42
43 // Look straight at the front of the logo so the letters are easy to click.
44 camera()->set_view_direction(vec3(0, 0, -1));
45 camera()->set_up_vector(vec3(0, 1, 0));
46
47 // manual_ is the full help text (shown on demand); hint_ is the short HUD reminder.
48 manual_ =
49 "-------------------- Manipulator Viewer usage ---------------------\n"
50 "Press the left button to pick/unpick a model. \n"
51 "When a model is picked, using the mouse to manipulate it: \n"
52 " - Alt + left button: rotate the model \n"
53 " - Alt + right button: translate the model \n"
54 "------------------------------------------------------------------ \n";
55 hint_ =
56 "Press left button to pick/unpick a model\n"
57 "When picked:\n"
58 " - Alt + left button: rotate the model\n"
59 " - Alt + right button: translate the model";
60}
61// Validates the weak selection handle: the model must still exist, still be part of the
62// scene, and have both a renderer and a manipulator before we act on it.
63std::shared_ptr<Model> TutorialObjectManipulation::selected_model() const {
64 auto model = selected_model_.lock();
65 return model && model->renderer() && model->manipulator() &&
66 std::find(models().begin(), models().end(), model) != models().end()
67 ? model
68 : nullptr;
69}
70// Closes an in-flight drag: action_end() lets the frame finalize the incremental motion.
71void TutorialObjectManipulation::end_model_drag() {
72 if (auto model = drag_model_.lock())
73 if (model->manipulator())
74 model->manipulator()->frame()->action_end();
75 drag_model_.reset();
76}
77// Two interaction modes: Alt + button manipulates the selected model; a plain left click
78// picks a model. Everything else is forwarded to the base Viewer (camera navigation).
79bool TutorialObjectManipulation::mouse_press_event(int x, int y, int button, int modifiers) {
80 end_model_drag();
81 if (modifiers == MODIF_ALT && (button == BUTTON_LEFT || button == BUTTON_RIGHT)) {
82 if (auto model = selected_model()) {
83 // Bracket the drag: the frame snapshots its state so subsequent motion events
84 // are applied incrementally and consistently.
85 model->manipulator()->frame()->action_start();
86 drag_model_ = model;
87 }
88 return true;
89 }
90 if (modifiers == 0 && button == BUTTON_LEFT) {
91 // GPU pick at the cursor. Mouse hooks and pick() both use logical window
92 // coordinates on both backends (DPI-independent). hit.model is null when the
93 // click landed on the background.
94 const auto hit = pick(x, y);
95 mark(hit.model.get());
96 }
97 return Viewer::mouse_press_event(x, y, button, modifiers);
98}
99// While Alt-dragging the selected model, mouse motion drives its manipulated frame instead
100// of the camera. Left button rotates (trackball), right button translates in the screen plane.
101bool TutorialObjectManipulation::mouse_drag_event(int x, int y, int dx, int dy, int button, int modifiers) {
102 const auto model = selected_model();
103 if (modifiers == MODIF_ALT && model && drag_model_.lock() == model) {
104 // Optional axis constraint: holding 'X', 'Y', or 'O' during the drag restricts the
105 // motion to a horizontal, vertical, or view-orthogonal screen axis.
106 auto axis = ManipulatedFrame::NONE;
107 if (input_.key == KEY_X)
108 axis = ManipulatedFrame::HORIZONTAL;
109 else if (input_.key == KEY_Y)
110 axis = ManipulatedFrame::VERTICAL;
111 else if (input_.key == KEY_O)
112 axis = ManipulatedFrame::ORTHOGONAL;
113 auto *frame = model->manipulator()->frame();
114 if (button == BUTTON_LEFT)
115 frame->action_rotate(x, y, dx, dy, camera(), axis);
116 else if (button == BUTTON_RIGHT)
117 frame->action_translate(x, y, dx, dy, camera(), axis);
118 update();
119 return true;
120 }
121 // The selection disappeared mid-drag (e.g. the model was deleted): abort cleanly.
122 if (!model)
123 end_model_drag();
124 return Viewer::mouse_drag_event(x, y, dx, dy, button, modifiers);
125}
126// Any button release finishes the drag; other release handling stays with the base Viewer.
127bool TutorialObjectManipulation::mouse_release_event(int x, int y, int button, int modifiers) {
128 end_model_drag();
129 return Viewer::mouse_release_event(x, y, button, modifiers);
130}
131// If focus is lost mid-drag, the release may arrive elsewhere; abort so the drag cannot stick.
132bool TutorialObjectManipulation::focus_event(bool focused) {
133 if (!focused)
134 end_model_drag();
135 return false;
136}
137// Screen-space drag coordinates become invalid after a resize; abort the drag.
138void TutorialObjectManipulation::post_resize(int, int) {
139 end_model_drag();
140}
141// Selects the clicked model (clicking the already-selected model deselects it). Selection is
142// exclusive: all other models are unmarked, and the newly selected one gets a Manipulator.
143void TutorialObjectManipulation::mark(Model *target) {
144 // Toggle: clicking the current selection clears it.
145 if (selected_model().get() == target)
146 target = nullptr;
147 end_model_drag();
148 selected_model_.reset();
149 for (const auto &model : models())
150 if (model->renderer()) {
151 const bool selected = model.get() == target;
152 model->renderer()->set_selected(selected);
153 if (selected) {
154 selected_model_ = model;
155 // Create the manipulator lazily, on first selection. Its frame origin sits
156 // at the object center, so rotations pivot around the object itself.
157 if (!model->manipulator())
158 model->set_manipulator(std::make_shared<Manipulator>(model.get()));
159 }
160 }
161 update();
162}
163// Every frame, show the manipulation gizmo (the frame's axes) of the selected model as a
164// depth-tested overlay, so the user sees the pivot and orientation being manipulated.
165void TutorialObjectManipulation::pre_draw() {
166 Viewer::pre_draw();
167 const auto model = selected_model();
168 if (model && model->renderer()->is_selected() && model->manipulator()) {
169 // draw_frame() returns an immutable draw command in framebuffer pixels, ready for
170 // set_overlays(); an empty command means there is nothing to draw.
171 int fw = 0, fh = 0;
172 framebuffer_size(fw, fh);
173 auto command = model->manipulator()->draw_frame(camera(), fw, fh);
174 set_overlays(command.geometry ? std::vector<graphics::DrawCommand>{command}
175 : std::vector<graphics::DrawCommand>{});
176 } else {
177 // No valid selection: drop any stale drag/selection state and clear the overlay.
178 end_model_drag();
179 selected_model_.reset();
180 set_overlays({});
181 }
182}
183
184// \endcond
See also
Manipulator, ManipulatedFrame, Viewer, Tutorial_401_ModelPicker, Tutorial_406_CollisionDetection