Viewer.cpp 26 KB

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