Viewer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "Viewer.h"
  9. #ifdef _WIN32
  10. # include <windows.h>
  11. # undef max
  12. # undef min
  13. #endif
  14. #include <chrono>
  15. #include <thread>
  16. #ifndef __APPLE__
  17. # define GLEW_STATIC
  18. # include <GL/glew.h>
  19. #endif
  20. #ifdef __APPLE__
  21. # include <OpenGL/gl3.h>
  22. # define __gl_h_ /* Prevent inclusion of the old gl.h */
  23. #else
  24. # include <GL/gl.h>
  25. #endif
  26. #include <Eigen/LU>
  27. #define GLFW_INCLUDE_GLU
  28. #include <GLFW/glfw3.h>
  29. #include <cmath>
  30. #include <cstdio>
  31. #include <sstream>
  32. #include <iomanip>
  33. #include <iostream>
  34. #include <fstream>
  35. #include <algorithm>
  36. #include <limits>
  37. #include <cassert>
  38. #include <nanogui/nanoguicontrol.h>
  39. #include <igl/project.h>
  40. #include <igl/get_seconds.h>
  41. #include <igl/readOBJ.h>
  42. #include <igl/readOFF.h>
  43. #include <igl/adjacency_list.h>
  44. #include <igl/writeOBJ.h>
  45. #include <igl/writeOFF.h>
  46. #include <igl/massmatrix.h>
  47. #include <igl/file_dialog_open.h>
  48. #include <igl/file_dialog_save.h>
  49. #include <igl/quat_mult.h>
  50. #include <igl/axis_angle_to_quat.h>
  51. #include <igl/trackball.h>
  52. #include <igl/snap_to_canonical_view_quat.h>
  53. #include <igl/unproject.h>
  54. #include <igl/viewer/TextRenderer.h>
  55. #ifdef ENABLE_SERIALIZATION
  56. #include <igl/serialize.h>
  57. #endif
  58. // Internal global variables used for glfw event handling
  59. static igl::Viewer * __viewer;
  60. static double highdpi = 1;
  61. static double scroll_x = 0;
  62. static double scroll_y = 0;
  63. static int global_KMod = 0;
  64. static void glfw_mouse_press(GLFWwindow* window, int button, int action, int modifier)
  65. {
  66. bool tw_used = __viewer->ngui->mouseButtonEvent(window,button,action,modifier);
  67. igl::Viewer::MouseButton mb;
  68. if (button == GLFW_MOUSE_BUTTON_1)
  69. mb = igl::Viewer::MouseButton::Left;
  70. else if (button == GLFW_MOUSE_BUTTON_2)
  71. mb = igl::Viewer::MouseButton::Right;
  72. else //if (button == GLFW_MOUSE_BUTTON_3)
  73. mb = igl::Viewer::MouseButton::Middle;
  74. if (action == GLFW_PRESS)
  75. {
  76. if(!tw_used)
  77. {
  78. __viewer->mouse_down(mb,modifier);
  79. }
  80. } else
  81. {
  82. // Always call mouse_up on up
  83. __viewer->mouse_up(mb,modifier);
  84. }
  85. }
  86. static void glfw_error_callback(int error, const char* description)
  87. {
  88. fputs(description, stderr);
  89. }
  90. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  91. {
  92. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  93. glfwSetWindowShouldClose(window, GL_TRUE);
  94. if (__viewer->ngui->keyEvent(window,key,scancode,action,modifier) == false)
  95. {
  96. if (action == GLFW_PRESS)
  97. __viewer->key_down(key, modifier);
  98. else if(action == GLFW_RELEASE)
  99. __viewer->key_up(key, modifier);
  100. }
  101. }
  102. static void glfw_window_size(GLFWwindow* window, int width, int height)
  103. {
  104. int w = width*highdpi;
  105. int h = height*highdpi;
  106. __viewer->resize(w, h);
  107. // TODO: repositioning of the nanogui
  108. }
  109. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  110. {
  111. if(__viewer->ngui->cursorPosEvent(window,x,y) == false || __viewer->down)
  112. {
  113. __viewer->mouse_move(x*highdpi, y*highdpi);
  114. }
  115. }
  116. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  117. {
  118. using namespace std;
  119. scroll_x += x;
  120. scroll_y += y;
  121. if (__viewer->ngui->scrollEvent(window,x,y) == false)
  122. __viewer->mouse_scroll(y);
  123. }
  124. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  125. {
  126. __viewer->ngui->charEvent(window,c);
  127. }
  128. static void glfw_drop_callback(GLFWwindow *window,int count,const char **filenames)
  129. {
  130. __viewer->ngui->dropEvent(window,count,filenames);
  131. }
  132. namespace igl
  133. {
  134. IGL_INLINE void Viewer::init()
  135. {
  136. ngui->setInputCellSize(Eigen::Vector2i(60,20));
  137. // Create nanogui widgets
  138. ngui->addNewWindow(Eigen::Vector2i(10,10),"libIGL-Viewer");
  139. // ---------------------- LOADING ----------------------
  140. #ifdef ENABLE_SERIALIZATION
  141. ngui->addNewGroup("Workspace",NanoGui::Layout::Horizontal);
  142. ngui->addButton("Load",[&](){this->load_scene();});
  143. ngui->addButton("Save",[&](){this->save_scene();});
  144. #endif
  145. #ifdef ENABLE_IO
  146. ngui->addNewGroup("Mesh",NanoGui::Layout::Horizontal);
  147. ngui->addButton("Load",[&](){this->open_dialog_load_mesh();});
  148. ngui->addButton("Save",[&](){this->open_dialog_save_mesh();});
  149. #endif
  150. ngui->addNewGroup("Viewing Options",NanoGui::Layout::Vertical);
  151. ngui->addButton("Center object",[&](){this->core.align_camera_center(this->data.V,this->data.F);});
  152. ngui->addButton("Snap canonical view",[&]()
  153. {
  154. this->snap_to_canonical_quaternion();
  155. });
  156. ngui->addVariable(core.camera_zoom,"Zoom");
  157. ngui->addVariable(core.orthographic,"Orthographic view");
  158. ngui->addNewGroup("Draw options");
  159. ngui->addVariable([&](bool checked)
  160. {
  161. this->data.set_face_based(checked);
  162. },[&]()
  163. {
  164. return this->data.face_based;
  165. }, "Face-based",false);
  166. ngui->addVariable(core.show_texture,"Show texture");
  167. ngui->addVariable([&](bool checked)
  168. {
  169. this->data.dirty |= ViewerData::DIRTY_NORMAL;
  170. this->core.invert_normals = checked;
  171. },[&]()
  172. {
  173. return this->core.invert_normals;
  174. },
  175. "Invert normals",false);
  176. ngui->addVariable(core.show_overlay,"Show overlay");
  177. ngui->addVariable(core.show_overlay_depth,"Show overlay depth");
  178. ngui->addColorPicker(core.background_color,"Background");
  179. ngui->addColorPicker(core.line_color,"Line color");
  180. ngui->addVariable(core.shininess,"Shininess");
  181. ngui->addNewGroup("Overlays");
  182. ngui->addVariable(core.show_lines,"Wireframe");
  183. ngui->addVariable(core.show_faces,"Fill");
  184. ngui->addVariable(core.show_vertid,"Show vertex labels");
  185. ngui->addVariable(core.show_faceid,"Show faces labels");
  186. ngui->layout();
  187. // Create a tweak bar
  188. /*bar = TwNewBar("libIGL-Viewer");
  189. TwDefine(" libIGL-Viewer help='This is a simple 3D mesh viewer.' "); // Message added to the help bar->
  190. TwDefine(" libIGL-Viewer size='200 685'"); // change default tweak bar size
  191. TwDefine(" libIGL-Viewer color='76 76 127' "); // change default tweak bar color
  192. TwDefine(" libIGL-Viewer refresh=0.5"); // change refresh rate
  193. // ---------------------- LOADING ----------------------
  194. #ifdef ENABLE_SERIALIZATION
  195. TwAddButton(bar,"Load Scene", load_scene_cb, this, "group='Workspace'");
  196. TwAddButton(bar,"Save Scene", save_scene_cb, this, "group='Workspace'");
  197. #endif
  198. #ifdef ENABLE_IO
  199. TwAddButton(bar,"Load Mesh", open_dialog_mesh, this, "group='Mesh' key=o");
  200. #endif
  201. // ---------------------- SCENE ----------------------
  202. TwAddButton(bar,"Center object", align_camera_center_cb, this,
  203. " group='Viewing Options'"
  204. " label='Center object' key=A help='Set the center of the camera to the mesh center.'");
  205. TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &(core.camera_zoom),
  206. " min=0.05 max=50 step=0.1 keyIncr=+ keyDecr=- help='Scale the object (1=original size).' group='Scene'");
  207. TwAddButton(bar,"SnapView", snap_to_canonical_quaternion_cb, this,
  208. " group='Scene'"
  209. " label='Snap to canonical view' key=Z "
  210. " help='Snaps view to nearest canonical view.'");
  211. TwAddVarRW(bar,"LightDir", TW_TYPE_DIR3F, core.light_position.data(),
  212. " group='Scene'"
  213. " label='Light direction' open help='Change the light direction.' ");
  214. // ---------------------- DRAW OPTIONS ----------------------
  215. TwAddVarRW(bar, "ToggleOrthographic", TW_TYPE_BOOLCPP, &(core.orthographic),
  216. " group='Viewing Options'"
  217. " label='Orthographic view' "
  218. " help='Toggles orthographic / perspective view. Default: perspective.'");
  219. TwAddVarRW(bar, "Rotation", TW_TYPE_QUAT4F, &(core.trackball_angle),
  220. " group='Viewing Options'"
  221. " label='Rotation'"
  222. " help='Rotates view.'");
  223. TwAddVarCB(bar,"Face-based Normals/Colors", TW_TYPE_BOOLCPP, set_face_based_cb, get_face_based_cb, this,
  224. " group='Draw options'"
  225. " label='Face-based' key=T help='Toggle per face shading/colors.' ");
  226. TwAddVarRW(bar,"Show texture", TW_TYPE_BOOLCPP, &(core.show_texture),
  227. " group='Draw options'");
  228. TwAddVarCB(bar,"Invert Normals", TW_TYPE_BOOLCPP, set_invert_normals_cb, get_invert_normals_cb, this,
  229. " group='Draw options'"
  230. " label='Invert normals' key=i help='Invert normal directions for inside out meshes.' ");
  231. TwAddVarRW(bar,"ShowOverlay", TW_TYPE_BOOLCPP, &(core.show_overlay),
  232. " group='Draw options'"
  233. " label='Show overlay' key=o help='Show the overlay layers.' ");
  234. TwAddVarRW(bar,"ShowOverlayDepth", TW_TYPE_BOOLCPP, &(core.show_overlay_depth),
  235. " group='Draw options'"
  236. " label='Show overlay depth test' help='Enable the depth test for overlay layer.' ");
  237. TwAddVarRW(bar,"Background color", TW_TYPE_COLOR3F,
  238. core.background_color.data(),
  239. " help='Select a background color' colormode=hls group='Draw options'");
  240. TwAddVarRW(bar, "LineColor", TW_TYPE_COLOR3F,
  241. core.line_color.data(),
  242. " label='Line color' help='Select a outline color' group='Draw options'");
  243. TwAddVarRW(bar,"Shininess",TW_TYPE_FLOAT,&core.shininess," group='Draw options'"
  244. " min=1 max=128");
  245. // ---------------------- Overlays ----------------------
  246. TwAddVarRW(bar,"Wireframe", TW_TYPE_BOOLCPP, &(core.show_lines),
  247. " group='Overlays'"
  248. " label='Wireframe' key=l help='Toggle wire frame of mesh'");
  249. TwAddVarRW(bar,"Fill", TW_TYPE_BOOLCPP, &(core.show_faces),
  250. " group='Overlays'"
  251. " label='Fill' key=t help='Display filled polygons of mesh'");
  252. TwAddVarRW(bar,"ShowVertexId", TW_TYPE_BOOLCPP, &(core.show_vertid),
  253. " group='Overlays'"
  254. " label='Show Vertex Labels' key=';' help='Toggle vertex indices'");
  255. TwAddVarRW(bar,"ShowFaceId", TW_TYPE_BOOLCPP, &(core.show_faceid),
  256. " group='Overlays'"
  257. " label='Show Faces Labels' key='CTRL+;' help='Toggle face"
  258. " indices'");
  259. */
  260. core.init();
  261. if (callback_init)
  262. if (callback_init(*this))
  263. return;
  264. init_plugins();
  265. // Parse command line arguments
  266. bool isLoaded = false;
  267. for(int i=1;i<argc;i++)
  268. {
  269. if(strcmp(argv[i],"-s")==0) {
  270. std::cout << "load scene file: " << argv[i+1] << std::endl;
  271. isLoaded = load_scene(argv[i+1]);
  272. if(isLoaded == false)
  273. std::cout << "file not found: " << argv[i+1] << std::endl;
  274. }
  275. }
  276. }
  277. IGL_INLINE Viewer::Viewer()
  278. {
  279. ngui = nullptr;
  280. // Temporary variables initialization
  281. down = false;
  282. hack_never_moved = true;
  283. scroll_position = 0.0f;
  284. // Per face
  285. data.set_face_based(false);
  286. // C-style callbacks
  287. callback_init = nullptr;
  288. callback_pre_draw = nullptr;
  289. callback_post_draw = nullptr;
  290. callback_mouse_down = nullptr;
  291. callback_mouse_up = nullptr;
  292. callback_mouse_move = nullptr;
  293. callback_mouse_scroll = nullptr;
  294. callback_key_down = nullptr;
  295. callback_key_up = nullptr;
  296. callback_init_data = nullptr;
  297. callback_pre_draw_data = nullptr;
  298. callback_post_draw_data = nullptr;
  299. callback_mouse_down_data = nullptr;
  300. callback_mouse_up_data = nullptr;
  301. callback_mouse_move_data = nullptr;
  302. callback_mouse_scroll_data = nullptr;
  303. callback_key_down_data = nullptr;
  304. callback_key_up_data = nullptr;
  305. }
  306. IGL_INLINE void Viewer::init_plugins()
  307. {
  308. // Init all plugins
  309. for (unsigned int i = 0; i<plugins.size(); ++i)
  310. plugins[i]->init(this);
  311. }
  312. IGL_INLINE Viewer::~Viewer()
  313. {
  314. if(!ngui) delete ngui;
  315. }
  316. IGL_INLINE void Viewer::shutdown_plugins()
  317. {
  318. for (unsigned int i = 0; i<plugins.size(); ++i)
  319. plugins[i]->shutdown();
  320. }
  321. IGL_INLINE bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  322. {
  323. std::string mesh_file_name_string = std::string(mesh_file_name);
  324. // first try to load it with a plugin
  325. for (unsigned int i = 0; i<plugins.size(); ++i)
  326. {
  327. if (plugins[i]->load(mesh_file_name_string))
  328. {
  329. return true;
  330. }
  331. }
  332. data.clear();
  333. size_t last_dot = mesh_file_name_string.rfind('.');
  334. if (last_dot == std::string::npos)
  335. {
  336. printf("Error: No file extension found in %s\n",mesh_file_name);
  337. return false;
  338. }
  339. std::string extension = mesh_file_name_string.substr(last_dot+1);
  340. if (extension == "off" || extension =="OFF")
  341. {
  342. Eigen::MatrixXd V;
  343. Eigen::MatrixXi F;
  344. if (!igl::readOFF(mesh_file_name_string, V, F))
  345. return false;
  346. data.set_mesh(V,F);
  347. }
  348. else if (extension == "obj" || extension =="OBJ")
  349. {
  350. Eigen::MatrixXd corner_normals;
  351. Eigen::MatrixXi fNormIndices;
  352. Eigen::MatrixXd UV_V;
  353. Eigen::MatrixXi UV_F;
  354. Eigen::MatrixXd V;
  355. Eigen::MatrixXi F;
  356. if (!(igl::readOBJ(mesh_file_name_string, V, F, corner_normals, fNormIndices, UV_V, UV_F)))
  357. return false;
  358. data.set_mesh(V,F);
  359. data.set_uv(UV_V,UV_F);
  360. }
  361. else
  362. {
  363. // unrecognized file type
  364. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  365. return false;
  366. }
  367. data.compute_normals();
  368. data.uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  369. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  370. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  371. if (data.V_uv.rows() == 0)
  372. data.grid_texture();
  373. core.align_camera_center(data.V,data.F);
  374. for (unsigned int i = 0; i<plugins.size(); ++i)
  375. if (plugins[i]->post_load())
  376. return true;
  377. return true;
  378. }
  379. IGL_INLINE bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  380. {
  381. std::string mesh_file_name_string(mesh_file_name);
  382. // first try to load it with a plugin
  383. for (unsigned int i = 0; i<plugins.size(); ++i)
  384. if (plugins[i]->save(mesh_file_name_string))
  385. return true;
  386. size_t last_dot = mesh_file_name_string.rfind('.');
  387. if (last_dot == std::string::npos)
  388. {
  389. // No file type determined
  390. printf("Error: No file extension found in %s\n",mesh_file_name);
  391. return false;
  392. }
  393. std::string extension = mesh_file_name_string.substr(last_dot+1);
  394. if (extension == "off" || extension =="OFF")
  395. {
  396. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  397. }
  398. else if (extension == "obj" || extension =="OBJ")
  399. {
  400. Eigen::MatrixXd corner_normals;
  401. Eigen::MatrixXi fNormIndices;
  402. Eigen::MatrixXd UV_V;
  403. Eigen::MatrixXi UV_F;
  404. return igl::writeOBJ(mesh_file_name_string, data.V,
  405. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  406. }
  407. else
  408. {
  409. // unrecognized file type
  410. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  411. return false;
  412. }
  413. return true;
  414. }
  415. IGL_INLINE bool Viewer::key_down(int key,int modifiers)
  416. {
  417. if (callback_key_down)
  418. if (callback_key_down(*this,key,modifiers))
  419. return true;
  420. for (unsigned int i = 0; i<plugins.size(); ++i)
  421. if (plugins[i]->key_down(key, modifiers))
  422. return true;
  423. char k = key;
  424. if(key == GLFW_KEY_S && modifiers == GLFW_MOD_SHIFT)
  425. mouse_scroll(1);
  426. if(key == GLFW_KEY_A && modifiers == GLFW_MOD_SHIFT)
  427. mouse_scroll(-1);
  428. // Why aren't these handled via AntTweakBar?
  429. if(key == GLFW_KEY_Z) // Don't use 'Z' because that clobbers snap_to_canonical_view_quat
  430. core.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  431. if(key == GLFW_KEY_Y)
  432. core.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  433. if(key == GLFW_KEY_X)
  434. core.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  435. return false;
  436. }
  437. IGL_INLINE bool Viewer::key_up(int key,int modifiers)
  438. {
  439. if (callback_key_up)
  440. if (callback_key_up(*this,key,modifiers))
  441. return true;
  442. for (unsigned int i = 0; i<plugins.size(); ++i)
  443. if (plugins[i]->key_up(key, modifiers))
  444. return true;
  445. return false;
  446. }
  447. IGL_INLINE bool Viewer::mouse_down(MouseButton button,int modifier)
  448. {
  449. if (callback_mouse_down)
  450. if (callback_mouse_down(*this,static_cast<int>(button),modifier))
  451. return true;
  452. for (unsigned int i = 0; i<plugins.size(); ++i)
  453. if(plugins[i]->mouse_down(static_cast<int>(button),modifier))
  454. return true;
  455. down = true;
  456. down_mouse_x = current_mouse_x;
  457. down_mouse_y = current_mouse_y;
  458. down_translation = core.model_translation;
  459. // Initialization code for the trackball
  460. Eigen::RowVector3d center;
  461. if (data.V.rows() == 0)
  462. center << 0,0,0;
  463. else
  464. center = data.V.colwise().sum()/data.V.rows();
  465. Eigen::Vector3f coord = igl::project(Eigen::Vector3f(center(0),center(1),center(2)), (core.view * core.model).eval(), core.proj, core.viewport);
  466. down_mouse_z = coord[2];
  467. down_rotation = core.trackball_angle;
  468. mouse_mode = MouseMode::Rotation;
  469. switch (button)
  470. {
  471. case MouseButton::Left:
  472. mouse_mode = MouseMode::Rotation;
  473. break;
  474. case MouseButton::Right:
  475. mouse_mode = MouseMode::Translation;
  476. break;
  477. default:
  478. mouse_mode = MouseMode::None;
  479. break;
  480. }
  481. return true;
  482. }
  483. IGL_INLINE bool Viewer::mouse_up(MouseButton button,int modifier)
  484. {
  485. down = false;
  486. if (callback_mouse_up)
  487. if (callback_mouse_up(*this,static_cast<int>(button),modifier))
  488. return true;
  489. for (unsigned int i = 0; i<plugins.size(); ++i)
  490. if(plugins[i]->mouse_up(static_cast<int>(button),modifier))
  491. return true;
  492. mouse_mode = MouseMode::None;
  493. return true;
  494. }
  495. IGL_INLINE bool Viewer::mouse_move(int mouse_x,int mouse_y)
  496. {
  497. if(hack_never_moved)
  498. {
  499. down_mouse_x = mouse_x;
  500. down_mouse_y = mouse_y;
  501. hack_never_moved = false;
  502. }
  503. current_mouse_x = mouse_x;
  504. current_mouse_y = mouse_y;
  505. if (callback_mouse_move)
  506. if (callback_mouse_move(*this,mouse_x,mouse_y))
  507. return true;
  508. for (unsigned int i = 0; i<plugins.size(); ++i)
  509. if (plugins[i]->mouse_move(mouse_x, mouse_y))
  510. return true;
  511. if (down)
  512. {
  513. switch (mouse_mode)
  514. {
  515. case MouseMode::Rotation :
  516. {
  517. igl::trackball(core.viewport(2),
  518. core.viewport(3),
  519. 2.0f,
  520. down_rotation.data(),
  521. down_mouse_x,
  522. down_mouse_y,
  523. mouse_x,
  524. mouse_y,
  525. core.trackball_angle.data());
  526. //Eigen::Vector4f snapq = core.trackball_angle;
  527. break;
  528. }
  529. case MouseMode::Translation:
  530. {
  531. //translation
  532. Eigen::Vector3f pos1 = igl::unproject(Eigen::Vector3f(mouse_x, core.viewport[3] - mouse_y, down_mouse_z), (core.view * core.model).eval(), core.proj, core.viewport);
  533. Eigen::Vector3f pos0 = igl::unproject(Eigen::Vector3f(down_mouse_x, core.viewport[3] - down_mouse_y, down_mouse_z), (core.view * core.model).eval(), core.proj, core.viewport);
  534. Eigen::Vector3f diff = pos1 - pos0;
  535. core.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  536. break;
  537. }
  538. case MouseMode::Zoom:
  539. {
  540. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  541. core.camera_zoom *= 1 + delta;
  542. down_mouse_x = mouse_x;
  543. down_mouse_y = mouse_y;
  544. break;
  545. }
  546. default:
  547. break;
  548. }
  549. }
  550. return true;
  551. }
  552. IGL_INLINE bool Viewer::mouse_scroll(float delta_y)
  553. {
  554. scroll_position += delta_y;
  555. if (callback_mouse_scroll)
  556. if (callback_mouse_scroll(*this,delta_y))
  557. return true;
  558. for (unsigned int i = 0; i<plugins.size(); ++i)
  559. if (plugins[i]->mouse_scroll(delta_y))
  560. return true;
  561. // Only zoom if there's actually a change
  562. if(delta_y != 0)
  563. {
  564. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  565. const float min_zoom = 0.1f;
  566. core.camera_zoom = (core.camera_zoom * mult > min_zoom ? core.camera_zoom * mult : min_zoom);
  567. }
  568. return true;
  569. }
  570. IGL_INLINE void Viewer::draw()
  571. {
  572. using namespace std;
  573. using namespace Eigen;
  574. core.clear_framebuffers();
  575. if (callback_pre_draw)
  576. if (callback_pre_draw(*this))
  577. return;
  578. for (unsigned int i = 0; i<plugins.size(); ++i)
  579. if (plugins[i]->pre_draw())
  580. return;
  581. core.draw(data,opengl);
  582. if (callback_post_draw)
  583. if (callback_post_draw(*this))
  584. return;
  585. for (unsigned int i = 0; i<plugins.size(); ++i)
  586. if (plugins[i]->post_draw())
  587. break;
  588. ngui->draw();
  589. }
  590. IGL_INLINE bool Viewer::save_scene()
  591. {
  592. std::string fname = igl::file_dialog_save();
  593. if (fname.length() == 0)
  594. return false;
  595. #ifdef ENABLE_SERIALIZATION
  596. igl::serialize(core,"Core",fname.c_str(),true);
  597. #ifndef ENABLE_SERIALIZATION_DATA_SEPARATION
  598. igl::serialize(data,"Data",fname.c_str());
  599. #endif
  600. for(unsigned int i = 0; i <plugins.size(); ++i)
  601. igl::serialize(*plugins[i],plugins[i]->plugin_name,fname.c_str());
  602. #endif
  603. return true;
  604. }
  605. IGL_INLINE bool Viewer::load_scene()
  606. {
  607. std::string fname = igl::file_dialog_open();
  608. if(fname.length() == 0)
  609. return false;
  610. return load_scene(fname);
  611. }
  612. IGL_INLINE bool Viewer::load_scene(std::string fname)
  613. {
  614. #ifdef ENABLE_SERIALIZATION
  615. igl::deserialize(core,"Core",fname.c_str());
  616. #ifndef ENABLE_SERIALIZATION_DATA_SEPARATION
  617. igl::deserialize(data,"Data",fname.c_str());
  618. #endif
  619. for(unsigned int i = 0; i <plugins.size(); ++i)
  620. igl::deserialize(*plugins[i],plugins[i]->plugin_name,fname.c_str());
  621. #endif
  622. return true;
  623. }
  624. IGL_INLINE void Viewer::resize(int w,int h)
  625. {
  626. core.viewport = Eigen::Vector4f(0,0,w,h);
  627. }
  628. IGL_INLINE void Viewer::snap_to_canonical_quaternion()
  629. {
  630. Eigen::Vector4f snapq = this->core.trackball_angle;
  631. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,this->core.trackball_angle.data());
  632. }
  633. IGL_INLINE void Viewer::open_dialog_load_mesh()
  634. {
  635. std::string fname = igl::file_dialog_open();
  636. if (fname.length() == 0)
  637. return;
  638. this->load_mesh_from_file(fname.c_str());
  639. }
  640. IGL_INLINE void Viewer::open_dialog_save_mesh()
  641. {
  642. std::string fname = igl::file_dialog_save();
  643. if(fname.length() == 0)
  644. return;
  645. this->save_mesh_to_file(fname.c_str());
  646. }
  647. IGL_INLINE int Viewer::launch(std::string filename,bool resizable,bool fullscreen)
  648. {
  649. GLFWwindow* window;
  650. glfwSetErrorCallback(glfw_error_callback);
  651. if (!glfwInit())
  652. return EXIT_FAILURE;
  653. glfwWindowHint(GLFW_SAMPLES, 8);
  654. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  655. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  656. #ifdef __APPLE__
  657. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  658. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  659. #endif
  660. if(fullscreen)
  661. {
  662. GLFWmonitor *monitor = glfwGetPrimaryMonitor();
  663. const GLFWvidmode *mode = glfwGetVideoMode(monitor);
  664. window = glfwCreateWindow(mode->width,mode->height,"libigl viewer",monitor,nullptr);
  665. }
  666. else
  667. {
  668. window = glfwCreateWindow(1280,800,"libigl viewer",nullptr,nullptr);
  669. }
  670. if (!window)
  671. {
  672. glfwTerminate();
  673. return EXIT_FAILURE;
  674. }
  675. glfwMakeContextCurrent(window);
  676. #ifndef __APPLE__
  677. glewExperimental = true;
  678. GLenum err = glewInit();
  679. if(GLEW_OK != err)
  680. {
  681. /* Problem: glewInit failed, something is seriously wrong. */
  682. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  683. }
  684. glGetError(); // pull and savely ignonre unhandled errors like GL_INVALID_ENUM
  685. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  686. #endif
  687. #if defined(DEBUG) || defined(_DEBUG)
  688. int major, minor, rev;
  689. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  690. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  691. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  692. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  693. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  694. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  695. #endif
  696. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  697. // Initialize NanoGui
  698. ngui = new NanoGui();
  699. ngui->init(window);
  700. __viewer = this;
  701. // Register callbacks
  702. glfwSetKeyCallback(window, glfw_key_callback);
  703. glfwSetCursorPosCallback(window,glfw_mouse_move);
  704. glfwSetWindowSizeCallback(window,glfw_window_size);
  705. glfwSetMouseButtonCallback(window,glfw_mouse_press);
  706. glfwSetScrollCallback(window,glfw_mouse_scroll);
  707. glfwSetCharCallback(window,glfw_char_callback);
  708. glfwSetDropCallback(window,glfw_drop_callback);
  709. // Handle retina displays (windows and mac)
  710. int width, height;
  711. glfwGetFramebufferSize(window, &width, &height);
  712. int width_window, height_window;
  713. glfwGetWindowSize(window, &width_window, &height_window);
  714. highdpi = width/width_window;
  715. glfw_window_size(window,width_window,height_window);
  716. opengl.init();
  717. // Alec: It seems silly to overload launch to take a filename as an
  718. // argument. load_mesh_from_file has many side effects so it makes
  719. // debugging launch difficult.
  720. // Load the mesh passed as input
  721. if (filename.size() > 0)
  722. {
  723. load_mesh_from_file(filename.c_str());
  724. }
  725. core.align_camera_center(data.V,data.F);
  726. // Initialize IGL viewer
  727. init();
  728. // Rendering loop
  729. while (!glfwWindowShouldClose(window))
  730. {
  731. double tic = get_seconds();
  732. draw();
  733. glfwSwapBuffers(window);
  734. if(core.is_animating)
  735. {
  736. glfwPollEvents();
  737. // In microseconds
  738. double duration = 1000000.*(get_seconds()-tic);
  739. const double min_duration = 1000000./core.animation_max_fps;
  740. if(duration<min_duration)
  741. {
  742. std::this_thread::sleep_for(std::chrono::microseconds((int)(min_duration-duration)));
  743. }
  744. }
  745. else
  746. {
  747. glfwWaitEvents();
  748. }
  749. }
  750. opengl.free();
  751. core.shut();
  752. shutdown_plugins();
  753. glfwDestroyWindow(window);
  754. glfwTerminate();
  755. return EXIT_SUCCESS;
  756. }
  757. } // end namespace