Viewer.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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;
  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::MouseButton mb;
  74. if (button == GLFW_MOUSE_BUTTON_1)
  75. mb = igl::Viewer::IGL_LEFT;
  76. else if (button == GLFW_MOUSE_BUTTON_2)
  77. mb = igl::Viewer::IGL_RIGHT;
  78. else //if (button == GLFW_MOUSE_BUTTON_3)
  79. mb = igl::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. IGL_INLINE void Viewer::init()
  288. {
  289. // Create a tweak bar
  290. bar = TwNewBar("libIGL-Viewer");
  291. TwDefine(" libIGL-Viewer help='This is a simple 3D mesh viewer.' "); // Message added to the help bar->
  292. TwDefine(" libIGL-Viewer size='200 685'"); // change default tweak bar size
  293. TwDefine(" libIGL-Viewer color='76 76 127' "); // change default tweak bar color
  294. TwDefine(" libIGL-Viewer refresh=0.5"); // change refresh rate
  295. // ---------------------- LOADING ----------------------
  296. #ifdef ENABLE_SERIALIZATION
  297. TwAddButton(bar,"Load Scene", load_scene_cb, this, "group='Workspace'");
  298. TwAddButton(bar,"Save Scene", save_scene_cb, this, "group='Workspace'");
  299. #endif
  300. #ifdef ENABLE_IO
  301. TwAddButton(bar,"Load Mesh", open_dialog_mesh, this, "group='Mesh' key=o");
  302. #endif
  303. // ---------------------- SCENE ----------------------
  304. TwAddButton(bar,"Center object", align_camera_center_cb, this,
  305. " group='Viewing Options'"
  306. " label='Center object' key=A help='Set the center of the camera to the mesh center.'");
  307. TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &(core.camera_zoom),
  308. " min=0.05 max=50 step=0.1 keyIncr=+ keyDecr=- help='Scale the object (1=original size).' group='Scene'");
  309. TwAddButton(bar,"SnapView", snap_to_canonical_quaternion_cb, this,
  310. " group='Scene'"
  311. " label='Snap to canonical view' key=Z "
  312. " help='Snaps view to nearest canonical view.'");
  313. TwAddVarRW(bar,"LightDir", TW_TYPE_DIR3F, core.light_position.data(),
  314. " group='Scene'"
  315. " label='Light direction' open help='Change the light direction.' ");
  316. // ---------------------- DRAW OPTIONS ----------------------
  317. TwAddVarRW(bar, "ToggleOrthographic", TW_TYPE_BOOLCPP, &(core.orthographic),
  318. " group='Viewing Options'"
  319. " label='Orthographic view' "
  320. " help='Toggles orthographic / perspective view. Default: perspective.'");
  321. TwAddVarRW(bar, "Rotation", TW_TYPE_QUAT4F, &(core.trackball_angle),
  322. " group='Viewing Options'"
  323. " label='Rotation'"
  324. " help='Rotates view.'");
  325. TwAddVarCB(bar,"Face-based Normals/Colors", TW_TYPE_BOOLCPP, set_face_based_cb, get_face_based_cb, this,
  326. " group='Draw options'"
  327. " label='Face-based' key=T help='Toggle per face shading/colors.' ");
  328. TwAddVarRW(bar,"Show texture", TW_TYPE_BOOLCPP, &(core.show_texture),
  329. " group='Draw options'");
  330. TwAddVarCB(bar,"Invert Normals", TW_TYPE_BOOLCPP, set_invert_normals_cb, get_invert_normals_cb, this,
  331. " group='Draw options'"
  332. " label='Invert normals' key=i help='Invert normal directions for inside out meshes.' ");
  333. TwAddVarRW(bar,"ShowOverlay", TW_TYPE_BOOLCPP, &(core.show_overlay),
  334. " group='Draw options'"
  335. " label='Show overlay' key=o help='Show the overlay layers.' ");
  336. TwAddVarRW(bar,"ShowOverlayDepth", TW_TYPE_BOOLCPP, &(core.show_overlay_depth),
  337. " group='Draw options'"
  338. " label='Show overlay depth test' help='Enable the depth test for overlay layer.' ");
  339. TwAddVarRW(bar,"Background color", TW_TYPE_COLOR3F,
  340. core.background_color.data(),
  341. " help='Select a background color' colormode=hls group='Draw options'");
  342. TwAddVarRW(bar, "LineColor", TW_TYPE_COLOR3F,
  343. core.line_color.data(),
  344. " label='Line color' help='Select a outline color' group='Draw options'");
  345. TwAddVarRW(bar,"Shininess",TW_TYPE_FLOAT,&core.shininess," group='Draw options'"
  346. " min=1 max=128");
  347. // ---------------------- Overlays ----------------------
  348. TwAddVarRW(bar,"Wireframe", TW_TYPE_BOOLCPP, &(core.show_lines),
  349. " group='Overlays'"
  350. " label='Wireframe' key=l help='Toggle wire frame of mesh'");
  351. TwAddVarRW(bar,"Fill", TW_TYPE_BOOLCPP, &(core.show_faces),
  352. " group='Overlays'"
  353. " label='Fill' key=t help='Display filled polygons of mesh'");
  354. TwAddVarRW(bar,"ShowVertexId", TW_TYPE_BOOLCPP, &(core.show_vertid),
  355. " group='Overlays'"
  356. " label='Show Vertex Labels' key=';' help='Toggle vertex indices'");
  357. TwAddVarRW(bar,"ShowFaceId", TW_TYPE_BOOLCPP, &(core.show_faceid),
  358. " group='Overlays'"
  359. " label='Show Faces Labels' key='CTRL+;' help='Toggle face"
  360. " indices'");
  361. core.init();
  362. if (callback_init)
  363. if (callback_init(*this))
  364. return;
  365. init_plugins();
  366. }
  367. IGL_INLINE Viewer::Viewer()
  368. {
  369. // Temporary variables initialization
  370. down = false;
  371. hack_never_moved = true;
  372. scroll_position = 0.0f;
  373. // Per face
  374. data.set_face_based(false);
  375. // C-style callbacks
  376. callback_init = 0;
  377. callback_pre_draw = 0;
  378. callback_post_draw = 0;
  379. callback_mouse_down = 0;
  380. callback_mouse_up = 0;
  381. callback_mouse_move = 0;
  382. callback_mouse_scroll = 0;
  383. callback_key_down = 0;
  384. callback_key_up = 0;
  385. callback_init_data = 0;
  386. callback_pre_draw_data = 0;
  387. callback_post_draw_data = 0;
  388. callback_mouse_down_data = 0;
  389. callback_mouse_up_data = 0;
  390. callback_mouse_move_data = 0;
  391. callback_mouse_scroll_data = 0;
  392. callback_key_down_data = 0;
  393. callback_key_up_data = 0;
  394. }
  395. IGL_INLINE void Viewer::init_plugins()
  396. {
  397. // Init all plugins
  398. for (unsigned int i = 0; i<plugins.size(); ++i)
  399. plugins[i]->init(this);
  400. }
  401. IGL_INLINE Viewer::~Viewer()
  402. {
  403. }
  404. IGL_INLINE void Viewer::shutdown_plugins()
  405. {
  406. for (unsigned int i = 0; i<plugins.size(); ++i)
  407. plugins[i]->shutdown();
  408. }
  409. IGL_INLINE bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  410. {
  411. std::string mesh_file_name_string = std::string(mesh_file_name);
  412. // first try to load it with a plugin
  413. for (unsigned int i = 0; i<plugins.size(); ++i)
  414. {
  415. if (plugins[i]->load(mesh_file_name_string))
  416. {
  417. return true;
  418. }
  419. }
  420. data.clear();
  421. size_t last_dot = mesh_file_name_string.rfind('.');
  422. if (last_dot == std::string::npos)
  423. {
  424. printf("Error: No file extension found in %s\n",mesh_file_name);
  425. return false;
  426. }
  427. std::string extension = mesh_file_name_string.substr(last_dot+1);
  428. if (extension == "off" || extension =="OFF")
  429. {
  430. Eigen::MatrixXd V;
  431. Eigen::MatrixXi F;
  432. if (!igl::readOFF(mesh_file_name_string, V, F))
  433. return false;
  434. data.set_mesh(V,F);
  435. }
  436. else if (extension == "obj" || extension =="OBJ")
  437. {
  438. Eigen::MatrixXd corner_normals;
  439. Eigen::MatrixXi fNormIndices;
  440. Eigen::MatrixXd UV_V;
  441. Eigen::MatrixXi UV_F;
  442. Eigen::MatrixXd V;
  443. Eigen::MatrixXi F;
  444. if (!(igl::readOBJ(mesh_file_name_string, V, F, corner_normals, fNormIndices, UV_V, UV_F)))
  445. return false;
  446. data.set_mesh(V,F);
  447. data.set_uv(UV_V,UV_F);
  448. }
  449. else
  450. {
  451. // unrecognized file type
  452. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  453. return false;
  454. }
  455. data.compute_normals();
  456. data.uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  457. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  458. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  459. if (data.V_uv.rows() == 0)
  460. data.grid_texture();
  461. core.align_camera_center(data.V,data.F);
  462. for (unsigned int i = 0; i<plugins.size(); ++i)
  463. if (plugins[i]->post_load())
  464. return true;
  465. return true;
  466. }
  467. IGL_INLINE bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  468. {
  469. std::string mesh_file_name_string(mesh_file_name);
  470. // first try to load it with a plugin
  471. for (unsigned int i = 0; i<plugins.size(); ++i)
  472. if (plugins[i]->save(mesh_file_name_string))
  473. return true;
  474. size_t last_dot = mesh_file_name_string.rfind('.');
  475. if (last_dot == std::string::npos)
  476. {
  477. // No file type determined
  478. printf("Error: No file extension found in %s\n",mesh_file_name);
  479. return false;
  480. }
  481. std::string extension = mesh_file_name_string.substr(last_dot+1);
  482. if (extension == "off" || extension =="OFF")
  483. {
  484. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  485. }
  486. else if (extension == "obj" || extension =="OBJ")
  487. {
  488. Eigen::MatrixXd corner_normals;
  489. Eigen::MatrixXi fNormIndices;
  490. Eigen::MatrixXd UV_V;
  491. Eigen::MatrixXi UV_F;
  492. return igl::writeOBJ(mesh_file_name_string, data.V,
  493. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  494. }
  495. else
  496. {
  497. // unrecognized file type
  498. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  499. return false;
  500. }
  501. return true;
  502. }
  503. IGL_INLINE bool Viewer::key_down(int key,int modifiers)
  504. {
  505. if (callback_key_down)
  506. if (callback_key_down(*this,key,modifiers))
  507. return true;
  508. for (unsigned int i = 0; i<plugins.size(); ++i)
  509. if (plugins[i]->key_down(key, modifiers))
  510. return true;
  511. char k = key;
  512. if(key == GLFW_KEY_S && modifiers == GLFW_MOD_SHIFT)
  513. mouse_scroll(1);
  514. if(key == GLFW_KEY_A && modifiers == GLFW_MOD_SHIFT)
  515. mouse_scroll(-1);
  516. // Why aren't these handled via AntTweakBar?
  517. if(key == GLFW_KEY_Z) // Don't use 'Z' because that clobbers snap_to_canonical_view_quat
  518. core.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  519. if(key == GLFW_KEY_Y)
  520. core.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  521. if(key == GLFW_KEY_X)
  522. core.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  523. return false;
  524. }
  525. IGL_INLINE bool Viewer::key_up(int key,int modifiers)
  526. {
  527. if (callback_key_up)
  528. if (callback_key_up(*this,key,modifiers))
  529. return true;
  530. for (unsigned int i = 0; i<plugins.size(); ++i)
  531. if (plugins[i]->key_up(key, modifiers))
  532. return true;
  533. return false;
  534. }
  535. IGL_INLINE bool Viewer::mouse_down(MouseButton button,int modifier)
  536. {
  537. if (callback_mouse_down)
  538. if (callback_mouse_down(*this,button,modifier))
  539. return true;
  540. for (unsigned int i = 0; i<plugins.size(); ++i)
  541. if (plugins[i]->mouse_down(button,modifier))
  542. return true;
  543. down = true;
  544. down_mouse_x = current_mouse_x;
  545. down_mouse_y = current_mouse_y;
  546. down_translation = core.model_translation;
  547. // Initialization code for the trackball
  548. Eigen::RowVector3d center;
  549. if (data.V.rows() == 0)
  550. center << 0,0,0;
  551. else
  552. center = data.V.colwise().sum()/data.V.rows();
  553. Eigen::Vector3f coord = igl::project(Eigen::Vector3f(center(0),center(1),center(2)), (core.view * core.model).eval(), core.proj, core.viewport);
  554. down_mouse_z = coord[2];
  555. down_rotation = core.trackball_angle;
  556. mouse_mode = ROTATION;
  557. switch (button)
  558. {
  559. case IGL_LEFT:
  560. mouse_mode = ROTATION;
  561. break;
  562. case IGL_RIGHT:
  563. mouse_mode = TRANSLATE;
  564. break;
  565. default:
  566. mouse_mode = NOTHING;
  567. break;
  568. }
  569. return true;
  570. }
  571. IGL_INLINE bool Viewer::mouse_up(MouseButton button,int modifier)
  572. {
  573. down = false;
  574. if (callback_mouse_up)
  575. if (callback_mouse_up(*this,button,modifier))
  576. return true;
  577. for (unsigned int i = 0; i<plugins.size(); ++i)
  578. if (plugins[i]->mouse_up(button,modifier))
  579. return true;
  580. mouse_mode = NOTHING;
  581. return true;
  582. }
  583. IGL_INLINE bool Viewer::mouse_move(int mouse_x,int mouse_y)
  584. {
  585. if(hack_never_moved)
  586. {
  587. down_mouse_x = mouse_x;
  588. down_mouse_y = mouse_y;
  589. hack_never_moved = false;
  590. }
  591. current_mouse_x = mouse_x;
  592. current_mouse_y = mouse_y;
  593. if (callback_mouse_move)
  594. if (callback_mouse_move(*this,mouse_x,mouse_y))
  595. return true;
  596. for (unsigned int i = 0; i<plugins.size(); ++i)
  597. if (plugins[i]->mouse_move(mouse_x, mouse_y))
  598. return true;
  599. if (down)
  600. {
  601. switch (mouse_mode)
  602. {
  603. case ROTATION :
  604. {
  605. igl::trackball(core.viewport(2),
  606. core.viewport(3),
  607. 2.0f,
  608. down_rotation.data(),
  609. down_mouse_x,
  610. down_mouse_y,
  611. mouse_x,
  612. mouse_y,
  613. core.trackball_angle.data());
  614. //Eigen::Vector4f snapq = core.trackball_angle;
  615. break;
  616. }
  617. case TRANSLATE:
  618. {
  619. //translation
  620. 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);
  621. 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);
  622. Eigen::Vector3f diff = pos1 - pos0;
  623. core.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  624. break;
  625. }
  626. case ZOOM:
  627. {
  628. //float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  629. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  630. core.camera_zoom *= 1 + delta;
  631. down_mouse_x = mouse_x;
  632. down_mouse_y = mouse_y;
  633. break;
  634. }
  635. default:
  636. break;
  637. }
  638. }
  639. return true;
  640. }
  641. IGL_INLINE bool Viewer::mouse_scroll(float delta_y)
  642. {
  643. scroll_position += delta_y;
  644. if (callback_mouse_scroll)
  645. if (callback_mouse_scroll(*this,delta_y))
  646. return true;
  647. for (unsigned int i = 0; i<plugins.size(); ++i)
  648. if (plugins[i]->mouse_scroll(delta_y))
  649. return true;
  650. // Only zoom if there's actually a change
  651. if(delta_y != 0)
  652. {
  653. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  654. const float min_zoom = 0.1f;
  655. core.camera_zoom = (core.camera_zoom * mult > min_zoom ? core.camera_zoom * mult : min_zoom);
  656. }
  657. return true;
  658. }
  659. IGL_INLINE void Viewer::draw()
  660. {
  661. using namespace std;
  662. using namespace Eigen;
  663. core.clear_framebuffers();
  664. if (callback_pre_draw)
  665. if (callback_pre_draw(*this))
  666. return;
  667. for (unsigned int i = 0; i<plugins.size(); ++i)
  668. if (plugins[i]->pre_draw())
  669. return;
  670. core.draw(data,opengl);
  671. if (callback_post_draw)
  672. if (callback_post_draw(*this))
  673. return;
  674. for (unsigned int i = 0; i<plugins.size(); ++i)
  675. if (plugins[i]->post_draw())
  676. break;
  677. TwDraw();
  678. }
  679. IGL_INLINE bool Viewer::save_scene()
  680. {
  681. std::string fname = igl::file_dialog_save();
  682. if (fname.length() == 0)
  683. return false;
  684. #ifdef ENABLE_SERIALIZATION
  685. igl::serialize(core,"Core",fname.c_str(),true);
  686. igl::serialize(data,"Data",fname.c_str());
  687. for(unsigned int i = 0; i <plugins.size(); ++i)
  688. igl::serialize(*plugins[i],plugins[i]->plugin_name,fname.c_str());
  689. #endif
  690. return true;
  691. }
  692. IGL_INLINE bool Viewer::load_scene()
  693. {
  694. std::string fname = igl::file_dialog_open();
  695. if (fname.length() == 0)
  696. return false;
  697. #ifdef ENABLE_SERIALIZATION
  698. igl::deserialize(core,"Core",fname.c_str());
  699. igl::deserialize(data,"Data",fname.c_str());
  700. for(unsigned int i = 0; i <plugins.size(); ++i)
  701. igl::deserialize(*plugins[i],plugins[i]->plugin_name,fname.c_str());
  702. #endif
  703. return true;
  704. }
  705. IGL_INLINE void Viewer::resize(int w,int h)
  706. {
  707. core.viewport = Eigen::Vector4f(0,0,w,h);
  708. }
  709. IGL_INLINE void TW_CALL Viewer::snap_to_canonical_quaternion_cb(void *clientData)
  710. {
  711. Eigen::Vector4f snapq = static_cast<Viewer *>(clientData)->core.trackball_angle;
  712. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,static_cast<Viewer *>(clientData)->core.trackball_angle.data());
  713. }
  714. IGL_INLINE void TW_CALL Viewer::align_camera_center_cb(void *clientData)
  715. {
  716. static_cast<Viewer *>(clientData)->core.align_camera_center(
  717. static_cast<Viewer *>(clientData)->data.V,
  718. static_cast<Viewer *>(clientData)->data.F);
  719. }
  720. IGL_INLINE void TW_CALL Viewer::save_scene_cb(void *clientData)
  721. {
  722. static_cast<Viewer *>(clientData)->save_scene();
  723. }
  724. IGL_INLINE void TW_CALL Viewer::load_scene_cb(void *clientData)
  725. {
  726. static_cast<Viewer *>(clientData)->load_scene();
  727. }
  728. IGL_INLINE void TW_CALL Viewer::set_invert_normals_cb(const void *param,void *clientData)
  729. {
  730. Viewer *viewer = static_cast<Viewer *>(clientData);
  731. viewer->data.dirty |= ViewerData::DIRTY_NORMAL;
  732. viewer->core.invert_normals = *((bool *) param);
  733. }
  734. IGL_INLINE void TW_CALL Viewer::get_invert_normals_cb(void *param,void *clientData)
  735. {
  736. *((bool *) param) = static_cast<Viewer *>(clientData)->core.invert_normals;
  737. }
  738. IGL_INLINE void TW_CALL Viewer::set_face_based_cb(const void *param,void *clientData)
  739. {
  740. Viewer *viewer = static_cast<Viewer *>(clientData);
  741. viewer->data.set_face_based(*((bool *) param));
  742. }
  743. IGL_INLINE void TW_CALL Viewer::get_face_based_cb(void *param,void *clientData)
  744. {
  745. *((bool *) param) = static_cast<Viewer *>(clientData)->data.face_based;
  746. }
  747. IGL_INLINE void TW_CALL Viewer::open_dialog_mesh(void *clientData)
  748. {
  749. std::string fname = igl::file_dialog_open();
  750. if (fname.length() == 0)
  751. return;
  752. static_cast<Viewer *>(clientData)->load_mesh_from_file(fname.c_str());
  753. }
  754. IGL_INLINE int Viewer::launch(std::string filename)
  755. {
  756. GLFWwindow* window;
  757. glfwSetErrorCallback(glfw_error_callback);
  758. if (!glfwInit())
  759. return EXIT_FAILURE;
  760. glfwWindowHint(GLFW_SAMPLES, 4);
  761. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  762. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  763. #ifdef __APPLE__
  764. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  765. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  766. #endif
  767. window = glfwCreateWindow(1280, 800, "libigl viewer", NULL, NULL);
  768. if (!window)
  769. {
  770. glfwTerminate();
  771. return EXIT_FAILURE;
  772. }
  773. glfwMakeContextCurrent(window);
  774. #ifndef __APPLE__
  775. glewExperimental = true;
  776. GLenum err = glewInit();
  777. if (GLEW_OK != err)
  778. {
  779. /* Problem: glewInit failed, something is seriously wrong. */
  780. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  781. }
  782. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  783. #endif
  784. #ifdef DEBUG
  785. int major, minor, rev;
  786. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  787. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  788. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  789. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  790. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  791. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  792. #endif
  793. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  794. // Initialize AntTweakBar
  795. TwInit(TW_OPENGL_CORE, NULL);
  796. TwCopyStdStringToClientFunc(static_cast<TwCopyStdStringToClient>(::copy_str));
  797. // Initialize IGL viewer
  798. init();
  799. __viewer = this;
  800. // Register callbacks
  801. glfwSetKeyCallback(window, glfw_key_callback);
  802. glfwSetCursorPosCallback(window,glfw_mouse_move);
  803. glfwSetWindowSizeCallback(window,glfw_window_size);
  804. glfwSetMouseButtonCallback(window,glfw_mouse_press);
  805. glfwSetScrollCallback(window,glfw_mouse_scroll);
  806. glfwSetCharCallback(window, glfw_char_callback);
  807. // Handle retina displays (windows and mac)
  808. int width, height;
  809. glfwGetFramebufferSize(window, &width, &height);
  810. int width_window, height_window;
  811. glfwGetWindowSize(window, &width_window, &height_window);
  812. highdpi = width/width_window;
  813. glfw_window_size(window,width_window,height_window);
  814. opengl.init();
  815. // Alec: It seems silly to overload launch to take a filename as an
  816. // argument. load_mesh_from_file has many side effects so it makes
  817. // debugging launch difficult.
  818. // Load the mesh passed as input
  819. if (filename.size() > 0)
  820. {
  821. load_mesh_from_file(filename.c_str());
  822. }
  823. core.align_camera_center(data.V,data.F);
  824. // Rendering loop
  825. while (!glfwWindowShouldClose(window))
  826. {
  827. double tic = get_seconds();
  828. draw();
  829. glfwSwapBuffers(window);
  830. if(core.is_animating)
  831. {
  832. glfwPollEvents();
  833. // In microseconds
  834. double duration = 1000000.*(get_seconds()-tic);
  835. const double min_duration = 1000000./core.animation_max_fps;
  836. if(duration<min_duration)
  837. {
  838. std::this_thread::sleep_for(std::chrono::microseconds((int)(min_duration-duration)));
  839. }
  840. }
  841. else
  842. {
  843. glfwWaitEvents();
  844. }
  845. }
  846. opengl.free();
  847. core.shut();
  848. shutdown_plugins();
  849. glfwDestroyWindow(window);
  850. glfwTerminate();
  851. return EXIT_SUCCESS;
  852. }
  853. } // end namespace