Viewer.cpp 29 KB

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