Viewer.cpp 28 KB

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