Viewer.cpp 28 KB

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