Viewer.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. #include <igl/get_seconds.h>
  10. #ifdef _WIN32
  11. # include <windows.h>
  12. # undef max
  13. # undef min
  14. #endif
  15. // Todo: windows equivalent for `usleep`
  16. //#include <unistd.h>
  17. #include <chrono>
  18. #include <thread>
  19. #ifndef __APPLE__
  20. # define GLEW_STATIC
  21. # include <GL/glew.h>
  22. #endif
  23. #ifdef __APPLE__
  24. # include <OpenGL/gl3.h>
  25. # define __gl_h_ /* Prevent inclusion of the old gl.h */
  26. #else
  27. # ifdef _WIN32
  28. # include <windows.h>
  29. # endif
  30. # include <GL/gl.h>
  31. #endif
  32. #include <Eigen/LU>
  33. #define GLFW_INCLUDE_GLU
  34. #include <GLFW/glfw3.h>
  35. #include <cmath>
  36. #include <cstdio>
  37. #include <sstream>
  38. #include <iomanip>
  39. #include <iostream>
  40. #include <fstream>
  41. #include <algorithm>
  42. #include <igl/project.h>
  43. #include <limits>
  44. #include <cassert>
  45. #ifdef ENABLE_XML_SERIALIZATION
  46. #include "igl/xml/XMLSerializer.h"
  47. #endif
  48. #include <igl/readOBJ.h>
  49. #include <igl/readOFF.h>
  50. #include <igl/adjacency_list.h>
  51. #include <igl/writeOBJ.h>
  52. #include <igl/writeOFF.h>
  53. #include <igl/massmatrix.h>
  54. #include <igl/file_dialog_open.h>
  55. #include <igl/file_dialog_save.h>
  56. #include <igl/quat_mult.h>
  57. #include <igl/axis_angle_to_quat.h>
  58. #include <igl/trackball.h>
  59. #include <igl/snap_to_canonical_view_quat.h>
  60. #include <igl/unproject.h>
  61. #include <igl/viewer/TextRenderer.h>
  62. // Internal global variables used for glfw event handling
  63. static igl::Viewer * __viewer;
  64. static double highdpi = 1;
  65. static double scroll_x = 0;
  66. static double scroll_y = 0;
  67. static void glfw_mouse_press(GLFWwindow* window, int button, int action, int modifier)
  68. {
  69. bool tw_used = TwEventMouseButtonGLFW(button, action);
  70. igl::Viewer::MouseButton mb;
  71. if (button == GLFW_MOUSE_BUTTON_1)
  72. mb = igl::Viewer::IGL_LEFT;
  73. else if (button == GLFW_MOUSE_BUTTON_2)
  74. mb = igl::Viewer::IGL_RIGHT;
  75. else //if (button == GLFW_MOUSE_BUTTON_3)
  76. mb = igl::Viewer::IGL_MIDDLE;
  77. if (action == GLFW_PRESS)
  78. {
  79. if(!tw_used)
  80. {
  81. __viewer->mouse_down(mb,modifier);
  82. }
  83. } else
  84. {
  85. // Always call mouse_up on up
  86. __viewer->mouse_up(mb,modifier);
  87. }
  88. }
  89. static void glfw_error_callback(int error, const char* description)
  90. {
  91. fputs(description, stderr);
  92. }
  93. int global_KMod = 0;
  94. int TwEventKeyGLFW3(int glfwKey, int glfwAction)
  95. {
  96. int handled = 0;
  97. // Register of modifiers state
  98. if (glfwAction==GLFW_PRESS)
  99. {
  100. switch (glfwKey)
  101. {
  102. case GLFW_KEY_LEFT_SHIFT:
  103. case GLFW_KEY_RIGHT_SHIFT:
  104. global_KMod |= TW_KMOD_SHIFT;
  105. break;
  106. case GLFW_KEY_LEFT_CONTROL:
  107. case GLFW_KEY_RIGHT_CONTROL:
  108. global_KMod |= TW_KMOD_CTRL;
  109. break;
  110. case GLFW_KEY_LEFT_ALT:
  111. case GLFW_KEY_RIGHT_ALT:
  112. global_KMod |= TW_KMOD_ALT;
  113. break;
  114. }
  115. }
  116. else
  117. {
  118. switch (glfwKey)
  119. {
  120. case GLFW_KEY_LEFT_SHIFT:
  121. case GLFW_KEY_RIGHT_SHIFT:
  122. global_KMod &= ~TW_KMOD_SHIFT;
  123. break;
  124. case GLFW_KEY_LEFT_CONTROL:
  125. case GLFW_KEY_RIGHT_CONTROL:
  126. global_KMod &= ~TW_KMOD_CTRL;
  127. break;
  128. case GLFW_KEY_LEFT_ALT:
  129. case GLFW_KEY_RIGHT_ALT:
  130. global_KMod &= ~TW_KMOD_ALT;
  131. break;
  132. }
  133. }
  134. // Process key pressed
  135. if (glfwAction==GLFW_PRESS)
  136. {
  137. int mod = global_KMod;
  138. int testkp = ((mod&TW_KMOD_CTRL) || (mod&TW_KMOD_ALT)) ? 1 : 0;
  139. if ((mod&TW_KMOD_CTRL) && glfwKey>0 && glfwKey<GLFW_KEY_ESCAPE ) // CTRL cases
  140. handled = TwKeyPressed(glfwKey, mod);
  141. else if (glfwKey>=GLFW_KEY_ESCAPE )
  142. {
  143. int k = 0;
  144. if (glfwKey>=GLFW_KEY_F1 && glfwKey<=GLFW_KEY_F15)
  145. k = TW_KEY_F1 + (glfwKey-GLFW_KEY_F1);
  146. else if (testkp && glfwKey>=GLFW_KEY_KP_0 && glfwKey<=GLFW_KEY_KP_9)
  147. k = '0' + (glfwKey-GLFW_KEY_KP_0);
  148. else
  149. {
  150. switch (glfwKey)
  151. {
  152. case GLFW_KEY_ESCAPE :
  153. k = TW_KEY_ESCAPE;
  154. break;
  155. case GLFW_KEY_UP:
  156. k = TW_KEY_UP;
  157. break;
  158. case GLFW_KEY_DOWN:
  159. k = TW_KEY_DOWN;
  160. break;
  161. case GLFW_KEY_LEFT:
  162. k = TW_KEY_LEFT;
  163. break;
  164. case GLFW_KEY_RIGHT:
  165. k = TW_KEY_RIGHT;
  166. break;
  167. case GLFW_KEY_TAB:
  168. k = TW_KEY_TAB;
  169. break;
  170. case GLFW_KEY_ENTER:
  171. k = TW_KEY_RETURN;
  172. break;
  173. case GLFW_KEY_BACKSPACE:
  174. k = TW_KEY_BACKSPACE;
  175. break;
  176. case GLFW_KEY_INSERT:
  177. k = TW_KEY_INSERT;
  178. break;
  179. case GLFW_KEY_DELETE:
  180. k = TW_KEY_DELETE;
  181. break;
  182. case GLFW_KEY_PAGE_UP:
  183. k = TW_KEY_PAGE_UP;
  184. break;
  185. case GLFW_KEY_PAGE_DOWN:
  186. k = TW_KEY_PAGE_DOWN;
  187. break;
  188. case GLFW_KEY_HOME:
  189. k = TW_KEY_HOME;
  190. break;
  191. case GLFW_KEY_END:
  192. k = TW_KEY_END;
  193. break;
  194. case GLFW_KEY_KP_ENTER:
  195. k = TW_KEY_RETURN;
  196. break;
  197. case GLFW_KEY_KP_DIVIDE:
  198. if (testkp)
  199. k = '/';
  200. break;
  201. case GLFW_KEY_KP_MULTIPLY:
  202. if (testkp)
  203. k = '*';
  204. break;
  205. case GLFW_KEY_KP_SUBTRACT:
  206. if (testkp)
  207. k = '-';
  208. break;
  209. case GLFW_KEY_KP_ADD:
  210. if (testkp)
  211. k = '+';
  212. break;
  213. case GLFW_KEY_KP_DECIMAL:
  214. if (testkp)
  215. k = '.';
  216. break;
  217. case GLFW_KEY_KP_EQUAL:
  218. if (testkp)
  219. k = '=';
  220. break;
  221. }
  222. }
  223. if (k>0)
  224. handled = TwKeyPressed(k, mod);
  225. }
  226. }
  227. return handled;
  228. }
  229. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  230. {
  231. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  232. glfwSetWindowShouldClose(window, GL_TRUE);
  233. if (!TwEventKeyGLFW3(key,action))
  234. {
  235. if (action == GLFW_PRESS)
  236. __viewer->key_down(key, modifier);
  237. else
  238. __viewer->key_up(key, modifier);
  239. }
  240. }
  241. static void glfw_window_size(GLFWwindow* window, int width, int height)
  242. {
  243. int w = width*highdpi;
  244. int h = height*highdpi;
  245. __viewer->resize(w, h);
  246. TwWindowSize(w, h);
  247. const auto & bar = __viewer->bar;
  248. // Keep AntTweakBar on right side of screen and height == opengl height
  249. // get the current position of a bar
  250. int size[2];
  251. TwGetParam(bar, NULL, "size", TW_PARAM_INT32, 2, size);
  252. int pos[2];
  253. // Place bar on left side of opengl rect (padded by 10 pixels)
  254. pos[0] = 10;//max(10,(int)width - size[0] - 10);
  255. // place bar at top (padded by 10 pixels)
  256. pos[1] = 10;
  257. // Set height to new height of window (padded by 10 pixels on bottom)
  258. size[1] = highdpi*(height-pos[1]-10);
  259. TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, pos);
  260. TwSetParam(bar, NULL, "size", TW_PARAM_INT32, 2,size);
  261. }
  262. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  263. {
  264. if(!TwEventMousePosGLFW(x*highdpi,y*highdpi) || __viewer->down)
  265. {
  266. // Call if TwBar hasn't used or if down
  267. __viewer->mouse_move(x*highdpi, y*highdpi);
  268. }
  269. }
  270. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  271. {
  272. using namespace std;
  273. scroll_x += x;
  274. scroll_y += y;
  275. if (!TwEventMouseWheelGLFW(scroll_y))
  276. __viewer->mouse_scroll(y);
  277. }
  278. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  279. {
  280. if ((c & 0xff00)==0)
  281. TwKeyPressed(c, global_KMod);
  282. }
  283. namespace igl
  284. {
  285. void Viewer::init()
  286. {
  287. // Create a tweak bar
  288. bar = TwNewBar("libIGL-Viewer");
  289. TwDefine(" libIGL-Viewer help='This is a simple 3D mesh viewer.' "); // Message added to the help bar->
  290. TwDefine(" libIGL-Viewer size='200 685'"); // change default tweak bar size
  291. TwDefine(" libIGL-Viewer color='76 76 127' "); // change default tweak bar color
  292. TwDefine(" libIGL-Viewer refresh=0.5"); // change refresh rate
  293. // ---------------------- LOADING ----------------------
  294. #ifdef ENABLE_XML_SERIALIZATION
  295. TwAddButton(bar,"Load Scene", load_scene_cb, this, "group='Workspace'");
  296. TwAddButton(bar,"Save Scene", save_scene_cb, this, "group='Workspace'");
  297. #endif
  298. #ifdef ENABLE_IO
  299. TwAddButton(bar,"Load Mesh", open_dialog_mesh, this, "group='Mesh' key=o");
  300. #endif
  301. // ---------------------- SCENE ----------------------
  302. TwAddButton(bar,"Center object", align_camera_center_cb, this,
  303. " group='Viewing Options'"
  304. " label='Center object' key=A help='Set the center of the camera to the mesh center.'");
  305. TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &(core.camera_zoom),
  306. " min=0.05 max=50 step=0.1 keyIncr=+ keyDecr=- help='Scale the object (1=original size).' group='Scene'");
  307. TwAddButton(bar,"SnapView", snap_to_canonical_quaternion_cb, this,
  308. " group='Scene'"
  309. " label='Snap to canonical view' key=Z "
  310. " help='Snaps view to nearest canonical view.'");
  311. TwAddVarRW(bar,"LightDir", TW_TYPE_DIR3F, core.light_position.data(),
  312. " group='Scene'"
  313. " label='Light direction' open help='Change the light direction.' ");
  314. // ---------------------- DRAW OPTIONS ----------------------
  315. TwAddVarRW(bar, "ToggleOrthographic", TW_TYPE_BOOLCPP, &(core.orthographic),
  316. " group='Viewing Options'"
  317. " label='Orthographic view' "
  318. " help='Toggles orthographic / perspective view. Default: perspective.'");
  319. TwAddVarRW(bar, "Rotation", TW_TYPE_QUAT4F, &(core.trackball_angle),
  320. " group='Viewing Options'"
  321. " label='Rotation'"
  322. " help='Rotates view.'");
  323. TwAddVarCB(bar,"Face-based Normals/Colors", TW_TYPE_BOOLCPP, set_face_based_cb, get_face_based_cb, this,
  324. " group='Draw options'"
  325. " label='Face-based' key=T help='Toggle per face shading/colors.' ");
  326. TwAddVarRW(bar,"Show texture", TW_TYPE_BOOLCPP, &(core.show_texture),
  327. " group='Draw options'");
  328. TwAddVarCB(bar,"Invert Normals", TW_TYPE_BOOLCPP, set_invert_normals_cb, get_invert_normals_cb, this,
  329. " group='Draw options'"
  330. " label='Invert normals' key=i help='Invert normal directions for inside out meshes.' ");
  331. TwAddVarRW(bar,"ShowOverlay", TW_TYPE_BOOLCPP, &(core.show_overlay),
  332. " group='Draw options'"
  333. " label='Show overlay' key=o help='Show the overlay layers.' ");
  334. TwAddVarRW(bar,"ShowOverlayDepth", TW_TYPE_BOOLCPP, &(core.show_overlay_depth),
  335. " group='Draw options'"
  336. " label='Show overlay depth test' help='Enable the depth test for overlay layer.' ");
  337. TwAddVarRW(bar,"Background color", TW_TYPE_COLOR3F,
  338. core.background_color.data(),
  339. " help='Select a background color' colormode=hls group='Draw options'");
  340. TwAddVarRW(bar, "LineColor", TW_TYPE_COLOR3F,
  341. core.line_color.data(),
  342. " label='Line color' help='Select a outline color' group='Draw options'");
  343. TwAddVarRW(bar,"Shininess",TW_TYPE_FLOAT,&core.shininess," group='Draw options'"
  344. " min=1 max=128");
  345. // ---------------------- Overlays ----------------------
  346. TwAddVarRW(bar,"Wireframe", TW_TYPE_BOOLCPP, &(core.show_lines),
  347. " group='Overlays'"
  348. " label='Wireframe' key=l help='Toggle wire frame of mesh'");
  349. TwAddVarRW(bar,"Fill", TW_TYPE_BOOLCPP, &(core.show_faces),
  350. " group='Overlays'"
  351. " label='Fill' key=t help='Display filled polygons of mesh'");
  352. TwAddVarRW(bar,"ShowVertexId", TW_TYPE_BOOLCPP, &(core.show_vertid),
  353. " group='Overlays'"
  354. " label='Show Vertex Labels' key=';' help='Toggle vertex indices'");
  355. TwAddVarRW(bar,"ShowFaceId", TW_TYPE_BOOLCPP, &(core.show_faceid),
  356. " group='Overlays'"
  357. " label='Show Faces Labels' key='CTRL+;' help='Toggle face"
  358. " indices'");
  359. core.init();
  360. init_plugins();
  361. }
  362. Viewer::Viewer()
  363. {
  364. // Temporary variables initialization
  365. down = false;
  366. hack_never_moved = true;
  367. scroll_position = 0.0f;
  368. // Per face
  369. set_face_based(false);
  370. // C-style callbacks
  371. callback_pre_draw = 0;
  372. callback_post_draw = 0;
  373. callback_mouse_down = 0;
  374. callback_mouse_up = 0;
  375. callback_mouse_move = 0;
  376. callback_mouse_scroll = 0;
  377. callback_key_down = 0;
  378. callback_key_up = 0;
  379. callback_pre_draw_data = 0;
  380. callback_post_draw = 0;
  381. callback_mouse_down = 0;
  382. callback_mouse_up = 0;
  383. callback_mouse_move = 0;
  384. callback_mouse_scroll = 0;
  385. callback_key_down = 0;
  386. callback_key_up = 0;
  387. }
  388. void Viewer::init_plugins()
  389. {
  390. // Init all plugins
  391. for (unsigned int i = 0; i<plugins.size(); ++i)
  392. plugins[i]->init(this);
  393. }
  394. Viewer::~Viewer()
  395. {
  396. }
  397. void Viewer::shutdown_plugins()
  398. {
  399. for (unsigned int i = 0; i<plugins.size(); ++i)
  400. plugins[i]->shutdown();
  401. }
  402. bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  403. {
  404. std::string mesh_file_name_string = std::string(mesh_file_name);
  405. // first try to load it with a plugin
  406. for (unsigned int i = 0; i<plugins.size(); ++i)
  407. if (plugins[i]->load(mesh_file_name_string))
  408. return true;
  409. data.clear();
  410. size_t last_dot = mesh_file_name_string.rfind('.');
  411. if (last_dot == std::string::npos)
  412. {
  413. printf("Error: No file extension found in %s\n",mesh_file_name);
  414. return false;
  415. }
  416. std::string extension = mesh_file_name_string.substr(last_dot+1);
  417. if (extension == "off" || extension =="OFF")
  418. {
  419. if (!igl::readOFF(mesh_file_name_string, data.V, data.F))
  420. return false;
  421. }
  422. else if (extension == "obj" || extension =="OBJ")
  423. {
  424. Eigen::MatrixXd corner_normals;
  425. Eigen::MatrixXi fNormIndices;
  426. Eigen::MatrixXd UV_V;
  427. Eigen::MatrixXi UV_F;
  428. if (!(igl::readOBJ(mesh_file_name_string, data.V, data.F, corner_normals, fNormIndices, UV_V, UV_F)))
  429. return false;
  430. }
  431. else
  432. {
  433. // unrecognized file type
  434. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  435. return false;
  436. }
  437. data.compute_normals();
  438. data.uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  439. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  440. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  441. if (data.V_uv.rows() == 0)
  442. data.grid_texture();
  443. core.align_camera_center(data.V);
  444. for (unsigned int i = 0; i<plugins.size(); ++i)
  445. if (plugins[i]->post_load())
  446. return true;
  447. return true;
  448. }
  449. bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  450. {
  451. std::string mesh_file_name_string(mesh_file_name);
  452. // first try to load it with a plugin
  453. for (unsigned int i = 0; i<plugins.size(); ++i)
  454. if (plugins[i]->save(mesh_file_name_string))
  455. return true;
  456. size_t last_dot = mesh_file_name_string.rfind('.');
  457. if (last_dot == std::string::npos)
  458. {
  459. // No file type determined
  460. printf("Error: No file extension found in %s\n",mesh_file_name);
  461. return false;
  462. }
  463. std::string extension = mesh_file_name_string.substr(last_dot+1);
  464. if (extension == "off" || extension =="OFF")
  465. {
  466. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  467. }
  468. else if (extension == "obj" || extension =="OBJ")
  469. {
  470. Eigen::MatrixXd corner_normals;
  471. Eigen::MatrixXi fNormIndices;
  472. Eigen::MatrixXd UV_V;
  473. Eigen::MatrixXi UV_F;
  474. return igl::writeOBJ(mesh_file_name_string, data.V,
  475. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  476. }
  477. else
  478. {
  479. // unrecognized file type
  480. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  481. return false;
  482. }
  483. return true;
  484. }
  485. void Viewer::clear()
  486. {
  487. data.clear();
  488. }
  489. bool Viewer::key_down(unsigned char key, int modifiers)
  490. {
  491. if (callback_key_down)
  492. if (callback_key_down(*this,key,modifiers))
  493. return true;
  494. for (unsigned int i = 0; i<plugins.size(); ++i)
  495. if (plugins[i]->key_down(key, modifiers))
  496. return true;
  497. if (key == 'S')
  498. mouse_scroll(1);
  499. if (key == 'A')
  500. mouse_scroll(-1);
  501. // Why aren't these handled view AntTweakBar?
  502. if (key == 'z') // Don't use 'Z' because that clobbers snap_to_canonical_view_quat
  503. core.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  504. if (key == 'y')
  505. core.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  506. if (key == 'x')
  507. core.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  508. return false;
  509. }
  510. bool Viewer::key_up(unsigned char key, int modifiers)
  511. {
  512. if (callback_key_up)
  513. if (callback_key_up(*this,key,modifiers))
  514. return true;
  515. for (unsigned int i = 0; i<plugins.size(); ++i)
  516. if (plugins[i]->key_up(key, modifiers))
  517. return true;
  518. return false;
  519. }
  520. bool Viewer::mouse_down(MouseButton button, int modifier)
  521. {
  522. if (callback_mouse_down)
  523. if (callback_mouse_down(*this,button,modifier))
  524. return true;
  525. for (unsigned int i = 0; i<plugins.size(); ++i)
  526. if (plugins[i]->mouse_down(button,modifier))
  527. return true;
  528. down = true;
  529. down_mouse_x = current_mouse_x;
  530. down_mouse_y = current_mouse_y;
  531. down_translation = core.model_translation;
  532. // Initialization code for the trackball
  533. Eigen::RowVector3d center;
  534. if (data.V.rows() == 0)
  535. center << 0,0,0;
  536. else
  537. center = data.V.colwise().sum()/data.V.rows();
  538. Eigen::Vector3f coord = igl::project(Eigen::Vector3f(center(0),center(1),center(2)), core.view * core.model, core.proj, core.viewport);
  539. down_mouse_z = coord[2];
  540. down_rotation = core.trackball_angle;
  541. mouse_mode = ROTATION;
  542. switch (button)
  543. {
  544. case IGL_LEFT:
  545. mouse_mode = ROTATION;
  546. break;
  547. case IGL_RIGHT:
  548. mouse_mode = TRANSLATE;
  549. break;
  550. default:
  551. mouse_mode = NOTHING;
  552. break;
  553. }
  554. return true;
  555. }
  556. bool Viewer::mouse_up(MouseButton button, int modifier)
  557. {
  558. down = false;
  559. if (callback_mouse_up)
  560. if (callback_mouse_up(*this,button,modifier))
  561. return true;
  562. for (unsigned int i = 0; i<plugins.size(); ++i)
  563. if (plugins[i]->mouse_up(button,modifier))
  564. return true;
  565. mouse_mode = NOTHING;
  566. return true;
  567. }
  568. bool Viewer::mouse_move(int mouse_x, int mouse_y)
  569. {
  570. if(hack_never_moved)
  571. {
  572. down_mouse_x = mouse_x;
  573. down_mouse_y = mouse_y;
  574. hack_never_moved = false;
  575. }
  576. current_mouse_x = mouse_x;
  577. current_mouse_y = mouse_y;
  578. if (callback_mouse_move)
  579. if (callback_mouse_move(*this,mouse_x,mouse_y))
  580. return true;
  581. for (unsigned int i = 0; i<plugins.size(); ++i)
  582. if (plugins[i]->mouse_move(mouse_x, mouse_y))
  583. return true;
  584. if (down)
  585. {
  586. switch (mouse_mode)
  587. {
  588. case ROTATION :
  589. {
  590. igl::trackball(core.viewport(2),
  591. core.viewport(3),
  592. 2.0f,
  593. down_rotation.data(),
  594. down_mouse_x,
  595. down_mouse_y,
  596. mouse_x,
  597. mouse_y,
  598. core.trackball_angle.data());
  599. //Eigen::Vector4f snapq = core.trackball_angle;
  600. break;
  601. }
  602. case TRANSLATE:
  603. {
  604. //translation
  605. Eigen::Vector3f pos1 = igl::unproject(Eigen::Vector3f(mouse_x, core.viewport[3] - mouse_y, down_mouse_z), core.view * core.model, core.proj, core.viewport);
  606. Eigen::Vector3f pos0 = igl::unproject(Eigen::Vector3f(down_mouse_x, core.viewport[3] - down_mouse_y, down_mouse_z), core.view * core.model, core.proj, core.viewport);
  607. Eigen::Vector3f diff = pos1 - pos0;
  608. core.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  609. break;
  610. }
  611. case ZOOM:
  612. {
  613. //float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  614. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  615. core.camera_zoom *= 1 + delta;
  616. down_mouse_x = mouse_x;
  617. down_mouse_y = mouse_y;
  618. break;
  619. }
  620. default:
  621. break;
  622. }
  623. }
  624. return true;
  625. }
  626. bool Viewer::mouse_scroll(float delta_y)
  627. {
  628. scroll_position += delta_y;
  629. if (callback_mouse_scroll)
  630. if (callback_mouse_scroll(*this,delta_y))
  631. return true;
  632. for (unsigned int i = 0; i<plugins.size(); ++i)
  633. if (plugins[i]->mouse_scroll(delta_y))
  634. return true;
  635. // Only zoom if there's actually a change
  636. if(delta_y != 0)
  637. {
  638. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  639. const float min_zoom = 0.1f;
  640. core.camera_zoom = (core.camera_zoom * mult > min_zoom ? core.camera_zoom * mult : min_zoom);
  641. }
  642. return true;
  643. }
  644. void Viewer::draw()
  645. {
  646. using namespace std;
  647. using namespace Eigen;
  648. core.clear_framebuffers();
  649. if (callback_pre_draw)
  650. if (callback_pre_draw(*this))
  651. return;
  652. for (unsigned int i = 0; i<plugins.size(); ++i)
  653. if (plugins[i]->pre_draw())
  654. return;
  655. core.draw(data,opengl);
  656. if (callback_post_draw)
  657. if (callback_post_draw(*this))
  658. return;
  659. for (unsigned int i = 0; i<plugins.size(); ++i)
  660. if (plugins[i]->post_draw())
  661. break;
  662. TwDraw();
  663. }
  664. bool Viewer::save_scene()
  665. {
  666. #ifdef ENABLE_XML_SERIALIZATION
  667. string fname = igl::file_dialog_save();
  668. if (fname.length() == 0)
  669. return false;
  670. ::igl::XMLSerializer serializer("Viewer");
  671. serializer.Add(data,"Data");
  672. serializer.Add(options,"Options");
  673. if (plugin_manager)
  674. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  675. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  676. serializer.Save(fname.c_str(),true);
  677. #endif
  678. return true;
  679. }
  680. bool Viewer::load_scene()
  681. {
  682. #ifdef ENABLE_XML_SERIALIZATION
  683. string fname = igl::file_dialog_open();
  684. if (fname.length() == 0)
  685. return false;
  686. ::igl::XMLSerializer serializer("Viewer");
  687. serializer.Add(data,"Data");
  688. serializer.Add(options,"Options");
  689. if (plugin_manager)
  690. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  691. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  692. serializer.Load(fname.c_str());
  693. #endif
  694. return true;
  695. }
  696. void Viewer::resize(int w, int h)
  697. {
  698. core.viewport = Eigen::Vector4f(0,0,w,h);
  699. }
  700. void TW_CALL Viewer::snap_to_canonical_quaternion_cb(void *clientData)
  701. {
  702. Eigen::Vector4f snapq = static_cast<Viewer *>(clientData)->core.trackball_angle;
  703. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,static_cast<Viewer *>(clientData)->core.trackball_angle.data());
  704. }
  705. void TW_CALL Viewer::align_camera_center_cb(void *clientData)
  706. {
  707. static_cast<Viewer *>(clientData)->core.align_camera_center(static_cast<Viewer *>(clientData)->data.V);
  708. }
  709. void TW_CALL Viewer::save_scene_cb(void *clientData)
  710. {
  711. static_cast<Viewer *>(clientData)->save_scene();
  712. }
  713. void TW_CALL Viewer::load_scene_cb(void *clientData)
  714. {
  715. static_cast<Viewer *>(clientData)->load_scene();
  716. }
  717. void TW_CALL Viewer::set_invert_normals_cb(const void *param, void *clientData)
  718. {
  719. Viewer *viewer = static_cast<Viewer *>(clientData);
  720. viewer->data.dirty |= ViewerData::DIRTY_NORMAL;
  721. viewer->core.invert_normals = *((bool *) param);
  722. }
  723. void TW_CALL Viewer::get_invert_normals_cb(void *param, void *clientData)
  724. {
  725. *((bool *) param) = static_cast<Viewer *>(clientData)->core.invert_normals;
  726. }
  727. void TW_CALL Viewer::set_face_based_cb(const void *param, void *clientData)
  728. {
  729. Viewer *viewer = static_cast<Viewer *>(clientData);
  730. viewer->set_face_based(*((bool *) param));
  731. }
  732. void TW_CALL Viewer::get_face_based_cb(void *param, void *clientData)
  733. {
  734. *((bool *) param) = static_cast<Viewer *>(clientData)->data.face_based;
  735. }
  736. void TW_CALL Viewer::open_dialog_mesh(void *clientData)
  737. {
  738. std::string fname = igl::file_dialog_open();
  739. if (fname.length() == 0)
  740. return;
  741. static_cast<Viewer *>(clientData)->load_mesh_from_file(fname.c_str());
  742. }
  743. void Viewer::set_face_based(bool newvalue)
  744. {
  745. data.set_face_based(newvalue);
  746. }
  747. void Viewer::compute_normals()
  748. {
  749. data.compute_normals();
  750. }
  751. void Viewer::align_camera_center()
  752. {
  753. core.align_camera_center(data.V);
  754. }
  755. void Viewer::set_mesh(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F)
  756. {
  757. data.set_mesh(V,F);
  758. core.align_camera_center(V);
  759. }
  760. void Viewer::set_vertices(const Eigen::MatrixXd& V)
  761. {
  762. data.set_vertices(V);
  763. }
  764. void Viewer::set_normals(const Eigen::MatrixXd& N)
  765. {
  766. data.set_normals(N);
  767. }
  768. void Viewer::set_colors(const Eigen::MatrixXd &C)
  769. {
  770. data.set_colors(C);
  771. }
  772. void Viewer::set_uv(const Eigen::MatrixXd& UV)
  773. {
  774. data.set_uv(UV);
  775. }
  776. void Viewer::set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F)
  777. {
  778. data.set_uv(UV_V,UV_F);
  779. }
  780. void Viewer::set_texture(
  781. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& R,
  782. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& G,
  783. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& B)
  784. {
  785. data.set_texture(R,G,B);
  786. }
  787. void Viewer::add_points(const Eigen::MatrixXd& P, const Eigen::MatrixXd& C)
  788. {
  789. data.add_points(P,C);
  790. }
  791. void Viewer::set_edges(
  792. const Eigen::MatrixXd& P,
  793. const Eigen::MatrixXi& E,
  794. const Eigen::MatrixXd& C)
  795. {
  796. data.set_edges(P,E,C);
  797. }
  798. void Viewer::add_edges(const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C)
  799. {
  800. data.add_edges(P1,P2,C);
  801. }
  802. void Viewer::add_label(const Eigen::VectorXd& P, const std::string& str)
  803. {
  804. data.add_label(P,str);
  805. }
  806. int Viewer::launch(std::string filename)
  807. {
  808. GLFWwindow* window;
  809. glfwSetErrorCallback(glfw_error_callback);
  810. if (!glfwInit())
  811. return EXIT_FAILURE;
  812. glfwWindowHint(GLFW_SAMPLES, 16);
  813. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  814. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  815. #ifdef __APPLE__
  816. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  817. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  818. #endif
  819. window = glfwCreateWindow(1280, 800, "IGL Viewer", NULL, NULL);
  820. if (!window)
  821. {
  822. glfwTerminate();
  823. return EXIT_FAILURE;
  824. }
  825. glfwMakeContextCurrent(window);
  826. #ifndef __APPLE__
  827. glewExperimental = true;
  828. GLenum err = glewInit();
  829. if (GLEW_OK != err)
  830. {
  831. /* Problem: glewInit failed, something is seriously wrong. */
  832. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  833. }
  834. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  835. #endif
  836. #ifdef DEBUG
  837. int major, minor, rev;
  838. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  839. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  840. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  841. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  842. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  843. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  844. #endif
  845. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  846. // Initialize AntTweakBar
  847. TwInit(TW_OPENGL_CORE, NULL);
  848. // Initialize IGL viewer
  849. init();
  850. __viewer = this;
  851. // Register callbacks
  852. glfwSetKeyCallback(window, glfw_key_callback); glfwSetCursorPosCallback(window,glfw_mouse_move); glfwSetWindowSizeCallback(window,glfw_window_size); glfwSetMouseButtonCallback(window,glfw_mouse_press); glfwSetScrollCallback(window,glfw_mouse_scroll); glfwSetCharCallback(window, glfw_char_callback);
  853. // Handle retina displays (windows and mac)
  854. int width, height;
  855. glfwGetFramebufferSize(window, &width, &height);
  856. int width_window, height_window;
  857. glfwGetWindowSize(window, &width_window, &height_window);
  858. highdpi = width/width_window;
  859. glfw_window_size(window,width_window,height_window);
  860. opengl.init();
  861. // Load the mesh passed as input
  862. if (filename.size() > 0)
  863. load_mesh_from_file(filename.c_str());
  864. // Rendering loop
  865. while (!glfwWindowShouldClose(window))
  866. {
  867. double tic = get_seconds();
  868. draw();
  869. glfwSwapBuffers(window);
  870. if(core.is_animating)
  871. {
  872. glfwPollEvents();
  873. // In microseconds
  874. double duration = 1000000.*(get_seconds()-tic);
  875. const double min_duration = 1000000./core.animation_max_fps;
  876. if(duration<min_duration)
  877. {
  878. // TODO: windows equivalent
  879. //usleep(min_duration-duration);
  880. std::this_thread::sleep_for(std::chrono::microseconds((int)(min_duration-duration)));
  881. }
  882. }
  883. else
  884. {
  885. glfwWaitEvents();
  886. }
  887. }
  888. opengl.free();
  889. core.shut();
  890. shutdown_plugins();
  891. glfwDestroyWindow(window);
  892. glfwTerminate();
  893. return EXIT_SUCCESS;
  894. }
  895. } // end namespace