Viewer.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. #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. # ifdef _WIN32
  26. # include <windows.h>
  27. # endif
  28. # include <GL/gl.h>
  29. #endif
  30. #include <Eigen/LU>
  31. #define GLFW_INCLUDE_GLU
  32. #include <GLFW/glfw3.h>
  33. #include <cmath>
  34. #include <cstdio>
  35. #include <sstream>
  36. #include <iomanip>
  37. #include <iostream>
  38. #include <fstream>
  39. #include <algorithm>
  40. #include <igl/project.h>
  41. #include <limits>
  42. #include <cassert>
  43. #ifdef ENABLE_XML_SERIALIZATION
  44. #include "igl/xml/XMLSerializer.h"
  45. #endif
  46. #include <igl/readOBJ.h>
  47. #include <igl/readOFF.h>
  48. #include <igl/adjacency_list.h>
  49. #include <igl/writeOBJ.h>
  50. #include <igl/writeOFF.h>
  51. #include <igl/massmatrix.h>
  52. #include <igl/file_dialog_open.h>
  53. #include <igl/file_dialog_save.h>
  54. #include <igl/quat_mult.h>
  55. #include <igl/axis_angle_to_quat.h>
  56. #include <igl/trackball.h>
  57. #include <igl/snap_to_canonical_view_quat.h>
  58. #include <igl/unproject.h>
  59. #include <igl/viewer/TextRenderer.h>
  60. // Internal global variables used for glfw event handling
  61. static igl::Viewer * __viewer;
  62. static double highdpi = 1;
  63. static double scroll_x = 0;
  64. static double scroll_y = 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. int global_KMod = 0;
  98. int TwEventKeyGLFW3(int glfwKey, int glfwAction)
  99. {
  100. int handled = 0;
  101. // Register of modifiers state
  102. if (glfwAction==GLFW_PRESS)
  103. {
  104. switch (glfwKey)
  105. {
  106. case GLFW_KEY_LEFT_SHIFT:
  107. case GLFW_KEY_RIGHT_SHIFT:
  108. global_KMod |= TW_KMOD_SHIFT;
  109. break;
  110. case GLFW_KEY_LEFT_CONTROL:
  111. case GLFW_KEY_RIGHT_CONTROL:
  112. global_KMod |= TW_KMOD_CTRL;
  113. break;
  114. case GLFW_KEY_LEFT_ALT:
  115. case GLFW_KEY_RIGHT_ALT:
  116. global_KMod |= TW_KMOD_ALT;
  117. break;
  118. }
  119. }
  120. else
  121. {
  122. switch (glfwKey)
  123. {
  124. case GLFW_KEY_LEFT_SHIFT:
  125. case GLFW_KEY_RIGHT_SHIFT:
  126. global_KMod &= ~TW_KMOD_SHIFT;
  127. break;
  128. case GLFW_KEY_LEFT_CONTROL:
  129. case GLFW_KEY_RIGHT_CONTROL:
  130. global_KMod &= ~TW_KMOD_CTRL;
  131. break;
  132. case GLFW_KEY_LEFT_ALT:
  133. case GLFW_KEY_RIGHT_ALT:
  134. global_KMod &= ~TW_KMOD_ALT;
  135. break;
  136. }
  137. }
  138. // Process key pressed
  139. if (glfwAction==GLFW_PRESS)
  140. {
  141. int mod = global_KMod;
  142. int testkp = ((mod&TW_KMOD_CTRL) || (mod&TW_KMOD_ALT)) ? 1 : 0;
  143. if ((mod&TW_KMOD_CTRL) && glfwKey>0 && glfwKey<GLFW_KEY_ESCAPE ) // CTRL cases
  144. handled = TwKeyPressed(glfwKey, mod);
  145. else if (glfwKey>=GLFW_KEY_ESCAPE )
  146. {
  147. int k = 0;
  148. if (glfwKey>=GLFW_KEY_F1 && glfwKey<=GLFW_KEY_F15)
  149. k = TW_KEY_F1 + (glfwKey-GLFW_KEY_F1);
  150. else if (testkp && glfwKey>=GLFW_KEY_KP_0 && glfwKey<=GLFW_KEY_KP_9)
  151. k = '0' + (glfwKey-GLFW_KEY_KP_0);
  152. else
  153. {
  154. switch (glfwKey)
  155. {
  156. case GLFW_KEY_ESCAPE :
  157. k = TW_KEY_ESCAPE;
  158. break;
  159. case GLFW_KEY_UP:
  160. k = TW_KEY_UP;
  161. break;
  162. case GLFW_KEY_DOWN:
  163. k = TW_KEY_DOWN;
  164. break;
  165. case GLFW_KEY_LEFT:
  166. k = TW_KEY_LEFT;
  167. break;
  168. case GLFW_KEY_RIGHT:
  169. k = TW_KEY_RIGHT;
  170. break;
  171. case GLFW_KEY_TAB:
  172. k = TW_KEY_TAB;
  173. break;
  174. case GLFW_KEY_ENTER:
  175. k = TW_KEY_RETURN;
  176. break;
  177. case GLFW_KEY_BACKSPACE:
  178. k = TW_KEY_BACKSPACE;
  179. break;
  180. case GLFW_KEY_INSERT:
  181. k = TW_KEY_INSERT;
  182. break;
  183. case GLFW_KEY_DELETE:
  184. k = TW_KEY_DELETE;
  185. break;
  186. case GLFW_KEY_PAGE_UP:
  187. k = TW_KEY_PAGE_UP;
  188. break;
  189. case GLFW_KEY_PAGE_DOWN:
  190. k = TW_KEY_PAGE_DOWN;
  191. break;
  192. case GLFW_KEY_HOME:
  193. k = TW_KEY_HOME;
  194. break;
  195. case GLFW_KEY_END:
  196. k = TW_KEY_END;
  197. break;
  198. case GLFW_KEY_KP_ENTER:
  199. k = TW_KEY_RETURN;
  200. break;
  201. case GLFW_KEY_KP_DIVIDE:
  202. if (testkp)
  203. k = '/';
  204. break;
  205. case GLFW_KEY_KP_MULTIPLY:
  206. if (testkp)
  207. k = '*';
  208. break;
  209. case GLFW_KEY_KP_SUBTRACT:
  210. if (testkp)
  211. k = '-';
  212. break;
  213. case GLFW_KEY_KP_ADD:
  214. if (testkp)
  215. k = '+';
  216. break;
  217. case GLFW_KEY_KP_DECIMAL:
  218. if (testkp)
  219. k = '.';
  220. break;
  221. case GLFW_KEY_KP_EQUAL:
  222. if (testkp)
  223. k = '=';
  224. break;
  225. }
  226. }
  227. if (k>0)
  228. handled = TwKeyPressed(k, mod);
  229. }
  230. }
  231. return handled;
  232. }
  233. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  234. {
  235. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  236. glfwSetWindowShouldClose(window, GL_TRUE);
  237. if (!TwEventKeyGLFW3(key,action))
  238. {
  239. if (action == GLFW_PRESS)
  240. __viewer->key_down(key, modifier);
  241. else
  242. __viewer->key_up(key, modifier);
  243. }
  244. }
  245. static void glfw_window_size(GLFWwindow* window, int width, int height)
  246. {
  247. int w = width*highdpi;
  248. int h = height*highdpi;
  249. __viewer->resize(w, h);
  250. TwWindowSize(w, h);
  251. const auto & bar = __viewer->bar;
  252. // Keep AntTweakBar on right side of screen and height == opengl height
  253. // get the current position of a bar
  254. int size[2];
  255. TwGetParam(bar, NULL, "size", TW_PARAM_INT32, 2, size);
  256. int pos[2];
  257. // Place bar on left side of opengl rect (padded by 10 pixels)
  258. pos[0] = 10;//max(10,(int)width - size[0] - 10);
  259. // place bar at top (padded by 10 pixels)
  260. pos[1] = 10;
  261. // Set height to new height of window (padded by 10 pixels on bottom)
  262. size[1] = highdpi*(height-pos[1]-10);
  263. TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, pos);
  264. TwSetParam(bar, NULL, "size", TW_PARAM_INT32, 2,size);
  265. }
  266. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  267. {
  268. if(!TwEventMousePosGLFW(x*highdpi,y*highdpi) || __viewer->down)
  269. {
  270. // Call if TwBar hasn't used or if down
  271. __viewer->mouse_move(x*highdpi, y*highdpi);
  272. }
  273. }
  274. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  275. {
  276. using namespace std;
  277. scroll_x += x;
  278. scroll_y += y;
  279. if (!TwEventMouseWheelGLFW(scroll_y))
  280. __viewer->mouse_scroll(y);
  281. }
  282. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  283. {
  284. if ((c & 0xff00)==0)
  285. TwKeyPressed(c, global_KMod);
  286. }
  287. namespace igl
  288. {
  289. 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_XML_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. init_plugins();
  365. }
  366. Viewer::Viewer()
  367. {
  368. // Temporary variables initialization
  369. down = false;
  370. hack_never_moved = true;
  371. scroll_position = 0.0f;
  372. // Per face
  373. data.set_face_based(false);
  374. // C-style callbacks
  375. callback_pre_draw = 0;
  376. callback_post_draw = 0;
  377. callback_mouse_down = 0;
  378. callback_mouse_up = 0;
  379. callback_mouse_move = 0;
  380. callback_mouse_scroll = 0;
  381. callback_key_down = 0;
  382. callback_key_up = 0;
  383. callback_pre_draw_data = 0;
  384. callback_post_draw = 0;
  385. callback_mouse_down = 0;
  386. callback_mouse_up = 0;
  387. callback_mouse_move = 0;
  388. callback_mouse_scroll = 0;
  389. callback_key_down = 0;
  390. callback_key_up = 0;
  391. }
  392. void Viewer::init_plugins()
  393. {
  394. // Init all plugins
  395. for (unsigned int i = 0; i<plugins.size(); ++i)
  396. plugins[i]->init(this);
  397. }
  398. Viewer::~Viewer()
  399. {
  400. }
  401. void Viewer::shutdown_plugins()
  402. {
  403. for (unsigned int i = 0; i<plugins.size(); ++i)
  404. plugins[i]->shutdown();
  405. }
  406. bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  407. {
  408. std::string mesh_file_name_string = std::string(mesh_file_name);
  409. // first try to load it with a plugin
  410. for (unsigned int i = 0; i<plugins.size(); ++i)
  411. if (plugins[i]->load(mesh_file_name_string))
  412. return true;
  413. data.clear();
  414. size_t last_dot = mesh_file_name_string.rfind('.');
  415. if (last_dot == std::string::npos)
  416. {
  417. printf("Error: No file extension found in %s\n",mesh_file_name);
  418. return false;
  419. }
  420. std::string extension = mesh_file_name_string.substr(last_dot+1);
  421. if (extension == "off" || extension =="OFF")
  422. {
  423. if (!igl::readOFF(mesh_file_name_string, data.V, data.F))
  424. return false;
  425. }
  426. else if (extension == "obj" || extension =="OBJ")
  427. {
  428. Eigen::MatrixXd corner_normals;
  429. Eigen::MatrixXi fNormIndices;
  430. Eigen::MatrixXd UV_V;
  431. Eigen::MatrixXi UV_F;
  432. if (!(igl::readOBJ(mesh_file_name_string, data.V, data.F, corner_normals, fNormIndices, UV_V, UV_F)))
  433. return false;
  434. }
  435. else
  436. {
  437. // unrecognized file type
  438. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  439. return false;
  440. }
  441. data.compute_normals();
  442. data.uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  443. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  444. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  445. if (data.V_uv.rows() == 0)
  446. data.grid_texture();
  447. core.align_camera_center(data.V,data.F);
  448. for (unsigned int i = 0; i<plugins.size(); ++i)
  449. if (plugins[i]->post_load())
  450. return true;
  451. return true;
  452. }
  453. bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  454. {
  455. std::string mesh_file_name_string(mesh_file_name);
  456. // first try to load it with a plugin
  457. for (unsigned int i = 0; i<plugins.size(); ++i)
  458. if (plugins[i]->save(mesh_file_name_string))
  459. return true;
  460. size_t last_dot = mesh_file_name_string.rfind('.');
  461. if (last_dot == std::string::npos)
  462. {
  463. // No file type determined
  464. printf("Error: No file extension found in %s\n",mesh_file_name);
  465. return false;
  466. }
  467. std::string extension = mesh_file_name_string.substr(last_dot+1);
  468. if (extension == "off" || extension =="OFF")
  469. {
  470. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  471. }
  472. else if (extension == "obj" || extension =="OBJ")
  473. {
  474. Eigen::MatrixXd corner_normals;
  475. Eigen::MatrixXi fNormIndices;
  476. Eigen::MatrixXd UV_V;
  477. Eigen::MatrixXi UV_F;
  478. return igl::writeOBJ(mesh_file_name_string, data.V,
  479. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  480. }
  481. else
  482. {
  483. // unrecognized file type
  484. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  485. return false;
  486. }
  487. return true;
  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(
  708. static_cast<Viewer *>(clientData)->data.V,
  709. static_cast<Viewer *>(clientData)->data.F);
  710. }
  711. void TW_CALL Viewer::save_scene_cb(void *clientData)
  712. {
  713. static_cast<Viewer *>(clientData)->save_scene();
  714. }
  715. void TW_CALL Viewer::load_scene_cb(void *clientData)
  716. {
  717. static_cast<Viewer *>(clientData)->load_scene();
  718. }
  719. 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. 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. 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. 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. 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. 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, 16);
  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, "IGL 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); 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);
  793. // Handle retina displays (windows and mac)
  794. int width, height;
  795. glfwGetFramebufferSize(window, &width, &height);
  796. int width_window, height_window;
  797. glfwGetWindowSize(window, &width_window, &height_window);
  798. highdpi = width/width_window;
  799. glfw_window_size(window,width_window,height_window);
  800. opengl.init();
  801. // Load the mesh passed as input
  802. if (filename.size() > 0)
  803. load_mesh_from_file(filename.c_str());
  804. core.align_camera_center(data.V,data.F);
  805. // Rendering loop
  806. while (!glfwWindowShouldClose(window))
  807. {
  808. double tic = get_seconds();
  809. draw();
  810. glfwSwapBuffers(window);
  811. if(core.is_animating)
  812. {
  813. glfwPollEvents();
  814. // In microseconds
  815. double duration = 1000000.*(get_seconds()-tic);
  816. const double min_duration = 1000000./core.animation_max_fps;
  817. if(duration<min_duration)
  818. {
  819. std::this_thread::sleep_for(std::chrono::microseconds((int)(min_duration-duration)));
  820. }
  821. }
  822. else
  823. {
  824. glfwWaitEvents();
  825. }
  826. }
  827. opengl.free();
  828. core.shut();
  829. shutdown_plugins();
  830. glfwDestroyWindow(window);
  831. glfwTerminate();
  832. return EXIT_SUCCESS;
  833. }
  834. } // end namespace