Viewer.cpp 28 KB

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