Viewer.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "Viewer.h"
  9. #include <igl/get_seconds.h>
  10. #ifdef _WIN32
  11. # include <windows.h>
  12. # undef max
  13. # undef min
  14. #endif
  15. #include <chrono>
  16. #include <thread>
  17. #ifndef __APPLE__
  18. # define GLEW_STATIC
  19. # include <GL/glew.h>
  20. #endif
  21. #ifdef __APPLE__
  22. # include <OpenGL/gl3.h>
  23. # define __gl_h_ /* Prevent inclusion of the old gl.h */
  24. #else
  25. # ifdef _WIN32
  26. # include <windows.h>
  27. # endif
  28. # include <GL/gl.h>
  29. #endif
  30. #include <Eigen/LU>
  31. #define GLFW_INCLUDE_GLU
  32. #include <GLFW/glfw3.h>
  33. #include <cmath>
  34. #include <cstdio>
  35. #include <sstream>
  36. #include <iomanip>
  37. #include <iostream>
  38. #include <fstream>
  39. #include <algorithm>
  40. #include <igl/project.h>
  41. #include <limits>
  42. #include <cassert>
  43. #ifdef ENABLE_XML_SERIALIZATION
  44. #include "igl/xml/XMLSerializer.h"
  45. #endif
  46. #include <igl/readOBJ.h>
  47. #include <igl/readOFF.h>
  48. #include <igl/adjacency_list.h>
  49. #include <igl/writeOBJ.h>
  50. #include <igl/writeOFF.h>
  51. #include <igl/massmatrix.h>
  52. #include <igl/file_dialog_open.h>
  53. #include <igl/file_dialog_save.h>
  54. #include <igl/quat_mult.h>
  55. #include <igl/axis_angle_to_quat.h>
  56. #include <igl/trackball.h>
  57. #include <igl/snap_to_canonical_view_quat.h>
  58. #include <igl/unproject.h>
  59. #include <igl/viewer/TextRenderer.h>
  60. // Internal global variables used for glfw event handling
  61. static igl::Viewer * __viewer;
  62. static double highdpi = 1;
  63. static double scroll_x = 0;
  64. static double scroll_y = 0;
  65. namespace {
  66. void TW_CALL copy_str(std::string& dst, const std::string& src)
  67. {
  68. dst = src;
  69. }
  70. }
  71. static void glfw_mouse_press(GLFWwindow* window, int button, int action, int modifier)
  72. {
  73. bool tw_used = TwEventMouseButtonGLFW(button, action);
  74. igl::Viewer::MouseButton mb;
  75. if (button == GLFW_MOUSE_BUTTON_1)
  76. mb = igl::Viewer::IGL_LEFT;
  77. else if (button == GLFW_MOUSE_BUTTON_2)
  78. mb = igl::Viewer::IGL_RIGHT;
  79. else //if (button == GLFW_MOUSE_BUTTON_3)
  80. mb = igl::Viewer::IGL_MIDDLE;
  81. if (action == GLFW_PRESS)
  82. {
  83. if(!tw_used)
  84. {
  85. __viewer->mouse_down(mb,modifier);
  86. }
  87. } else
  88. {
  89. // Always call mouse_up on up
  90. __viewer->mouse_up(mb,modifier);
  91. }
  92. }
  93. static void glfw_error_callback(int error, const char* description)
  94. {
  95. fputs(description, stderr);
  96. }
  97. int global_KMod = 0;
  98. int TwEventKeyGLFW3(int glfwKey, int glfwAction)
  99. {
  100. int handled = 0;
  101. // Register of modifiers state
  102. if (glfwAction==GLFW_PRESS)
  103. {
  104. switch (glfwKey)
  105. {
  106. case GLFW_KEY_LEFT_SHIFT:
  107. case GLFW_KEY_RIGHT_SHIFT:
  108. global_KMod |= TW_KMOD_SHIFT;
  109. break;
  110. case GLFW_KEY_LEFT_CONTROL:
  111. case GLFW_KEY_RIGHT_CONTROL:
  112. global_KMod |= TW_KMOD_CTRL;
  113. break;
  114. case GLFW_KEY_LEFT_ALT:
  115. case GLFW_KEY_RIGHT_ALT:
  116. global_KMod |= TW_KMOD_ALT;
  117. break;
  118. }
  119. }
  120. else
  121. {
  122. switch (glfwKey)
  123. {
  124. case GLFW_KEY_LEFT_SHIFT:
  125. case GLFW_KEY_RIGHT_SHIFT:
  126. global_KMod &= ~TW_KMOD_SHIFT;
  127. break;
  128. case GLFW_KEY_LEFT_CONTROL:
  129. case GLFW_KEY_RIGHT_CONTROL:
  130. global_KMod &= ~TW_KMOD_CTRL;
  131. break;
  132. case GLFW_KEY_LEFT_ALT:
  133. case GLFW_KEY_RIGHT_ALT:
  134. global_KMod &= ~TW_KMOD_ALT;
  135. break;
  136. }
  137. }
  138. // Process key pressed
  139. if (glfwAction==GLFW_PRESS)
  140. {
  141. int mod = global_KMod;
  142. int testkp = ((mod&TW_KMOD_CTRL) || (mod&TW_KMOD_ALT)) ? 1 : 0;
  143. if ((mod&TW_KMOD_CTRL) && glfwKey>0 && glfwKey<GLFW_KEY_ESCAPE ) // CTRL cases
  144. handled = TwKeyPressed(glfwKey, mod);
  145. else if (glfwKey>=GLFW_KEY_ESCAPE )
  146. {
  147. int k = 0;
  148. if (glfwKey>=GLFW_KEY_F1 && glfwKey<=GLFW_KEY_F15)
  149. k = TW_KEY_F1 + (glfwKey-GLFW_KEY_F1);
  150. else if (testkp && glfwKey>=GLFW_KEY_KP_0 && glfwKey<=GLFW_KEY_KP_9)
  151. k = '0' + (glfwKey-GLFW_KEY_KP_0);
  152. else
  153. {
  154. switch (glfwKey)
  155. {
  156. case GLFW_KEY_ESCAPE :
  157. k = TW_KEY_ESCAPE;
  158. break;
  159. case GLFW_KEY_UP:
  160. k = TW_KEY_UP;
  161. break;
  162. case GLFW_KEY_DOWN:
  163. k = TW_KEY_DOWN;
  164. break;
  165. case GLFW_KEY_LEFT:
  166. k = TW_KEY_LEFT;
  167. break;
  168. case GLFW_KEY_RIGHT:
  169. k = TW_KEY_RIGHT;
  170. break;
  171. case GLFW_KEY_TAB:
  172. k = TW_KEY_TAB;
  173. break;
  174. case GLFW_KEY_ENTER:
  175. k = TW_KEY_RETURN;
  176. break;
  177. case GLFW_KEY_BACKSPACE:
  178. k = TW_KEY_BACKSPACE;
  179. break;
  180. case GLFW_KEY_INSERT:
  181. k = TW_KEY_INSERT;
  182. break;
  183. case GLFW_KEY_DELETE:
  184. k = TW_KEY_DELETE;
  185. break;
  186. case GLFW_KEY_PAGE_UP:
  187. k = TW_KEY_PAGE_UP;
  188. break;
  189. case GLFW_KEY_PAGE_DOWN:
  190. k = TW_KEY_PAGE_DOWN;
  191. break;
  192. case GLFW_KEY_HOME:
  193. k = TW_KEY_HOME;
  194. break;
  195. case GLFW_KEY_END:
  196. k = TW_KEY_END;
  197. break;
  198. case GLFW_KEY_KP_ENTER:
  199. k = TW_KEY_RETURN;
  200. break;
  201. case GLFW_KEY_KP_DIVIDE:
  202. if (testkp)
  203. k = '/';
  204. break;
  205. case GLFW_KEY_KP_MULTIPLY:
  206. if (testkp)
  207. k = '*';
  208. break;
  209. case GLFW_KEY_KP_SUBTRACT:
  210. if (testkp)
  211. k = '-';
  212. break;
  213. case GLFW_KEY_KP_ADD:
  214. if (testkp)
  215. k = '+';
  216. break;
  217. case GLFW_KEY_KP_DECIMAL:
  218. if (testkp)
  219. k = '.';
  220. break;
  221. case GLFW_KEY_KP_EQUAL:
  222. if (testkp)
  223. k = '=';
  224. break;
  225. }
  226. }
  227. if (k>0)
  228. handled = TwKeyPressed(k, mod);
  229. }
  230. }
  231. return handled;
  232. }
  233. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  234. {
  235. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  236. glfwSetWindowShouldClose(window, GL_TRUE);
  237. if (!TwEventKeyGLFW3(key,action))
  238. {
  239. if (action == GLFW_PRESS)
  240. __viewer->key_down(key, modifier);
  241. else
  242. __viewer->key_up(key, modifier);
  243. }
  244. }
  245. static void glfw_window_size(GLFWwindow* window, int width, int height)
  246. {
  247. int w = width*highdpi;
  248. int h = height*highdpi;
  249. __viewer->resize(w, h);
  250. TwWindowSize(w, h);
  251. const auto & bar = __viewer->bar;
  252. // Keep AntTweakBar on right side of screen and height == opengl height
  253. // get the current position of a bar
  254. int size[2];
  255. TwGetParam(bar, NULL, "size", TW_PARAM_INT32, 2, size);
  256. int pos[2];
  257. // Place bar on left side of opengl rect (padded by 10 pixels)
  258. pos[0] = 10;//max(10,(int)width - size[0] - 10);
  259. // place bar at top (padded by 10 pixels)
  260. pos[1] = 10;
  261. // Set height to new height of window (padded by 10 pixels on bottom)
  262. size[1] = highdpi*(height-pos[1]-10);
  263. TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, pos);
  264. TwSetParam(bar, NULL, "size", TW_PARAM_INT32, 2,size);
  265. }
  266. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  267. {
  268. if(!TwEventMousePosGLFW(x*highdpi,y*highdpi) || __viewer->down)
  269. {
  270. // Call if TwBar hasn't used or if down
  271. __viewer->mouse_move(x*highdpi, y*highdpi);
  272. }
  273. }
  274. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  275. {
  276. using namespace std;
  277. scroll_x += x;
  278. scroll_y += y;
  279. if (!TwEventMouseWheelGLFW(scroll_y))
  280. __viewer->mouse_scroll(y);
  281. }
  282. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  283. {
  284. if ((c & 0xff00)==0)
  285. TwKeyPressed(c, global_KMod);
  286. }
  287. namespace igl
  288. {
  289. void Viewer::init()
  290. {
  291. // Create a tweak bar
  292. bar = TwNewBar("libIGL-Viewer");
  293. TwDefine(" libIGL-Viewer help='This is a simple 3D mesh viewer.' "); // Message added to the help bar->
  294. TwDefine(" libIGL-Viewer size='200 685'"); // change default tweak bar size
  295. TwDefine(" libIGL-Viewer color='76 76 127' "); // change default tweak bar color
  296. TwDefine(" libIGL-Viewer refresh=0.5"); // change refresh rate
  297. // ---------------------- LOADING ----------------------
  298. #ifdef ENABLE_XML_SERIALIZATION
  299. TwAddButton(bar,"Load Scene", load_scene_cb, this, "group='Workspace'");
  300. TwAddButton(bar,"Save Scene", save_scene_cb, this, "group='Workspace'");
  301. #endif
  302. #ifdef ENABLE_IO
  303. TwAddButton(bar,"Load Mesh", open_dialog_mesh, this, "group='Mesh' key=o");
  304. #endif
  305. // ---------------------- SCENE ----------------------
  306. TwAddButton(bar,"Center object", align_camera_center_cb, this,
  307. " group='Viewing Options'"
  308. " label='Center object' key=A help='Set the center of the camera to the mesh center.'");
  309. TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &(core.camera_zoom),
  310. " min=0.05 max=50 step=0.1 keyIncr=+ keyDecr=- help='Scale the object (1=original size).' group='Scene'");
  311. TwAddButton(bar,"SnapView", snap_to_canonical_quaternion_cb, this,
  312. " group='Scene'"
  313. " label='Snap to canonical view' key=Z "
  314. " help='Snaps view to nearest canonical view.'");
  315. TwAddVarRW(bar,"LightDir", TW_TYPE_DIR3F, core.light_position.data(),
  316. " group='Scene'"
  317. " label='Light direction' open help='Change the light direction.' ");
  318. // ---------------------- DRAW OPTIONS ----------------------
  319. TwAddVarRW(bar, "ToggleOrthographic", TW_TYPE_BOOLCPP, &(core.orthographic),
  320. " group='Viewing Options'"
  321. " label='Orthographic view' "
  322. " help='Toggles orthographic / perspective view. Default: perspective.'");
  323. TwAddVarRW(bar, "Rotation", TW_TYPE_QUAT4F, &(core.trackball_angle),
  324. " group='Viewing Options'"
  325. " label='Rotation'"
  326. " help='Rotates view.'");
  327. TwAddVarCB(bar,"Face-based Normals/Colors", TW_TYPE_BOOLCPP, set_face_based_cb, get_face_based_cb, this,
  328. " group='Draw options'"
  329. " label='Face-based' key=T help='Toggle per face shading/colors.' ");
  330. TwAddVarRW(bar,"Show texture", TW_TYPE_BOOLCPP, &(core.show_texture),
  331. " group='Draw options'");
  332. TwAddVarCB(bar,"Invert Normals", TW_TYPE_BOOLCPP, set_invert_normals_cb, get_invert_normals_cb, this,
  333. " group='Draw options'"
  334. " label='Invert normals' key=i help='Invert normal directions for inside out meshes.' ");
  335. TwAddVarRW(bar,"ShowOverlay", TW_TYPE_BOOLCPP, &(core.show_overlay),
  336. " group='Draw options'"
  337. " label='Show overlay' key=o help='Show the overlay layers.' ");
  338. TwAddVarRW(bar,"ShowOverlayDepth", TW_TYPE_BOOLCPP, &(core.show_overlay_depth),
  339. " group='Draw options'"
  340. " label='Show overlay depth test' help='Enable the depth test for overlay layer.' ");
  341. TwAddVarRW(bar,"Background color", TW_TYPE_COLOR3F,
  342. core.background_color.data(),
  343. " help='Select a background color' colormode=hls group='Draw options'");
  344. TwAddVarRW(bar, "LineColor", TW_TYPE_COLOR3F,
  345. core.line_color.data(),
  346. " label='Line color' help='Select a outline color' group='Draw options'");
  347. TwAddVarRW(bar,"Shininess",TW_TYPE_FLOAT,&core.shininess," group='Draw options'"
  348. " min=1 max=128");
  349. // ---------------------- Overlays ----------------------
  350. TwAddVarRW(bar,"Wireframe", TW_TYPE_BOOLCPP, &(core.show_lines),
  351. " group='Overlays'"
  352. " label='Wireframe' key=l help='Toggle wire frame of mesh'");
  353. TwAddVarRW(bar,"Fill", TW_TYPE_BOOLCPP, &(core.show_faces),
  354. " group='Overlays'"
  355. " label='Fill' key=t help='Display filled polygons of mesh'");
  356. TwAddVarRW(bar,"ShowVertexId", TW_TYPE_BOOLCPP, &(core.show_vertid),
  357. " group='Overlays'"
  358. " label='Show Vertex Labels' key=';' help='Toggle vertex indices'");
  359. TwAddVarRW(bar,"ShowFaceId", TW_TYPE_BOOLCPP, &(core.show_faceid),
  360. " group='Overlays'"
  361. " label='Show Faces Labels' key='CTRL+;' help='Toggle face"
  362. " indices'");
  363. core.init();
  364. if (callback_init)
  365. if (callback_init(*this))
  366. return;
  367. init_plugins();
  368. }
  369. Viewer::Viewer()
  370. {
  371. // Temporary variables initialization
  372. down = false;
  373. hack_never_moved = true;
  374. scroll_position = 0.0f;
  375. // Per face
  376. data.set_face_based(false);
  377. // C-style callbacks
  378. callback_init = 0;
  379. callback_pre_draw = 0;
  380. callback_post_draw = 0;
  381. callback_mouse_down = 0;
  382. callback_mouse_up = 0;
  383. callback_mouse_move = 0;
  384. callback_mouse_scroll = 0;
  385. callback_key_down = 0;
  386. callback_key_up = 0;
  387. callback_init_data = 0;
  388. callback_pre_draw_data = 0;
  389. callback_post_draw_data = 0;
  390. callback_mouse_down_data = 0;
  391. callback_mouse_up_data = 0;
  392. callback_mouse_move_data = 0;
  393. callback_mouse_scroll_data = 0;
  394. callback_key_down_data = 0;
  395. callback_key_up_data = 0;
  396. }
  397. void Viewer::init_plugins()
  398. {
  399. // Init all plugins
  400. for (unsigned int i = 0; i<plugins.size(); ++i)
  401. plugins[i]->init(this);
  402. }
  403. Viewer::~Viewer()
  404. {
  405. }
  406. void Viewer::shutdown_plugins()
  407. {
  408. for (unsigned int i = 0; i<plugins.size(); ++i)
  409. plugins[i]->shutdown();
  410. }
  411. bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  412. {
  413. std::string mesh_file_name_string = std::string(mesh_file_name);
  414. // first try to load it with a plugin
  415. for (unsigned int i = 0; i<plugins.size(); ++i)
  416. {
  417. if (plugins[i]->load(mesh_file_name_string))
  418. {
  419. return true;
  420. }
  421. }
  422. data.clear();
  423. size_t last_dot = mesh_file_name_string.rfind('.');
  424. if (last_dot == std::string::npos)
  425. {
  426. printf("Error: No file extension found in %s\n",mesh_file_name);
  427. return false;
  428. }
  429. std::string extension = mesh_file_name_string.substr(last_dot+1);
  430. if (extension == "off" || extension =="OFF")
  431. {
  432. if (!igl::readOFF(mesh_file_name_string, data.V, data.F))
  433. {
  434. return false;
  435. }
  436. }
  437. else if (extension == "obj" || extension =="OBJ")
  438. {
  439. Eigen::MatrixXd corner_normals;
  440. Eigen::MatrixXi fNormIndices;
  441. Eigen::MatrixXd UV_V;
  442. Eigen::MatrixXi UV_F;
  443. if (!(igl::readOBJ(mesh_file_name_string, data.V, data.F, corner_normals, fNormIndices, UV_V, UV_F)))
  444. {
  445. return false;
  446. }
  447. }
  448. else
  449. {
  450. // unrecognized file type
  451. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  452. return false;
  453. }
  454. data.compute_normals();
  455. data.uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  456. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  457. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  458. if (data.V_uv.rows() == 0)
  459. data.grid_texture();
  460. core.align_camera_center(data.V,data.F);
  461. for (unsigned int i = 0; i<plugins.size(); ++i)
  462. if (plugins[i]->post_load())
  463. return true;
  464. return true;
  465. }
  466. bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  467. {
  468. std::string mesh_file_name_string(mesh_file_name);
  469. // first try to load it with a plugin
  470. for (unsigned int i = 0; i<plugins.size(); ++i)
  471. if (plugins[i]->save(mesh_file_name_string))
  472. return true;
  473. size_t last_dot = mesh_file_name_string.rfind('.');
  474. if (last_dot == std::string::npos)
  475. {
  476. // No file type determined
  477. printf("Error: No file extension found in %s\n",mesh_file_name);
  478. return false;
  479. }
  480. std::string extension = mesh_file_name_string.substr(last_dot+1);
  481. if (extension == "off" || extension =="OFF")
  482. {
  483. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  484. }
  485. else if (extension == "obj" || extension =="OBJ")
  486. {
  487. Eigen::MatrixXd corner_normals;
  488. Eigen::MatrixXi fNormIndices;
  489. Eigen::MatrixXd UV_V;
  490. Eigen::MatrixXi UV_F;
  491. return igl::writeOBJ(mesh_file_name_string, data.V,
  492. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  493. }
  494. else
  495. {
  496. // unrecognized file type
  497. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  498. return false;
  499. }
  500. return true;
  501. }
  502. bool Viewer::key_down(unsigned char key, int modifiers)
  503. {
  504. if (callback_key_down)
  505. if (callback_key_down(*this,key,modifiers))
  506. return true;
  507. for (unsigned int i = 0; i<plugins.size(); ++i)
  508. if (plugins[i]->key_down(key, modifiers))
  509. return true;
  510. if (key == 'S')
  511. mouse_scroll(1);
  512. if (key == 'A')
  513. mouse_scroll(-1);
  514. // Why aren't these handled via AntTweakBar?
  515. if (key == 'z') // Don't use 'Z' because that clobbers snap_to_canonical_view_quat
  516. core.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  517. if (key == 'y')
  518. core.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  519. if (key == 'x')
  520. core.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  521. return false;
  522. }
  523. bool Viewer::key_up(unsigned char key, int modifiers)
  524. {
  525. if (callback_key_up)
  526. if (callback_key_up(*this,key,modifiers))
  527. return true;
  528. for (unsigned int i = 0; i<plugins.size(); ++i)
  529. if (plugins[i]->key_up(key, modifiers))
  530. return true;
  531. return false;
  532. }
  533. bool Viewer::mouse_down(MouseButton button, int modifier)
  534. {
  535. if (callback_mouse_down)
  536. if (callback_mouse_down(*this,button,modifier))
  537. return true;
  538. for (unsigned int i = 0; i<plugins.size(); ++i)
  539. if (plugins[i]->mouse_down(button,modifier))
  540. return true;
  541. down = true;
  542. down_mouse_x = current_mouse_x;
  543. down_mouse_y = current_mouse_y;
  544. down_translation = core.model_translation;
  545. // Initialization code for the trackball
  546. Eigen::RowVector3d center;
  547. if (data.V.rows() == 0)
  548. center << 0,0,0;
  549. else
  550. center = data.V.colwise().sum()/data.V.rows();
  551. Eigen::Vector3f coord = igl::project(Eigen::Vector3f(center(0),center(1),center(2)), core.view * core.model, core.proj, core.viewport);
  552. down_mouse_z = coord[2];
  553. down_rotation = core.trackball_angle;
  554. mouse_mode = ROTATION;
  555. switch (button)
  556. {
  557. case IGL_LEFT:
  558. mouse_mode = ROTATION;
  559. break;
  560. case IGL_RIGHT:
  561. mouse_mode = TRANSLATE;
  562. break;
  563. default:
  564. mouse_mode = NOTHING;
  565. break;
  566. }
  567. return true;
  568. }
  569. bool Viewer::mouse_up(MouseButton button, int modifier)
  570. {
  571. down = false;
  572. if (callback_mouse_up)
  573. if (callback_mouse_up(*this,button,modifier))
  574. return true;
  575. for (unsigned int i = 0; i<plugins.size(); ++i)
  576. if (plugins[i]->mouse_up(button,modifier))
  577. return true;
  578. mouse_mode = NOTHING;
  579. return true;
  580. }
  581. bool Viewer::mouse_move(int mouse_x, int mouse_y)
  582. {
  583. if(hack_never_moved)
  584. {
  585. down_mouse_x = mouse_x;
  586. down_mouse_y = mouse_y;
  587. hack_never_moved = false;
  588. }
  589. current_mouse_x = mouse_x;
  590. current_mouse_y = mouse_y;
  591. if (callback_mouse_move)
  592. if (callback_mouse_move(*this,mouse_x,mouse_y))
  593. return true;
  594. for (unsigned int i = 0; i<plugins.size(); ++i)
  595. if (plugins[i]->mouse_move(mouse_x, mouse_y))
  596. return true;
  597. if (down)
  598. {
  599. switch (mouse_mode)
  600. {
  601. case ROTATION :
  602. {
  603. igl::trackball(core.viewport(2),
  604. core.viewport(3),
  605. 2.0f,
  606. down_rotation.data(),
  607. down_mouse_x,
  608. down_mouse_y,
  609. mouse_x,
  610. mouse_y,
  611. core.trackball_angle.data());
  612. //Eigen::Vector4f snapq = core.trackball_angle;
  613. break;
  614. }
  615. case TRANSLATE:
  616. {
  617. //translation
  618. 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);
  619. 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);
  620. Eigen::Vector3f diff = pos1 - pos0;
  621. core.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  622. break;
  623. }
  624. case ZOOM:
  625. {
  626. //float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  627. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  628. core.camera_zoom *= 1 + delta;
  629. down_mouse_x = mouse_x;
  630. down_mouse_y = mouse_y;
  631. break;
  632. }
  633. default:
  634. break;
  635. }
  636. }
  637. return true;
  638. }
  639. bool Viewer::mouse_scroll(float delta_y)
  640. {
  641. scroll_position += delta_y;
  642. if (callback_mouse_scroll)
  643. if (callback_mouse_scroll(*this,delta_y))
  644. return true;
  645. for (unsigned int i = 0; i<plugins.size(); ++i)
  646. if (plugins[i]->mouse_scroll(delta_y))
  647. return true;
  648. // Only zoom if there's actually a change
  649. if(delta_y != 0)
  650. {
  651. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  652. const float min_zoom = 0.1f;
  653. core.camera_zoom = (core.camera_zoom * mult > min_zoom ? core.camera_zoom * mult : min_zoom);
  654. }
  655. return true;
  656. }
  657. void Viewer::draw()
  658. {
  659. using namespace std;
  660. using namespace Eigen;
  661. core.clear_framebuffers();
  662. if (callback_pre_draw)
  663. if (callback_pre_draw(*this))
  664. return;
  665. for (unsigned int i = 0; i<plugins.size(); ++i)
  666. if (plugins[i]->pre_draw())
  667. return;
  668. core.draw(data,opengl);
  669. if (callback_post_draw)
  670. if (callback_post_draw(*this))
  671. return;
  672. for (unsigned int i = 0; i<plugins.size(); ++i)
  673. if (plugins[i]->post_draw())
  674. break;
  675. TwDraw();
  676. }
  677. bool Viewer::save_scene()
  678. {
  679. #ifdef ENABLE_XML_SERIALIZATION
  680. string fname = igl::file_dialog_save();
  681. if (fname.length() == 0)
  682. return false;
  683. ::igl::XMLSerializer serializer("Viewer");
  684. serializer.Add(data,"Data");
  685. serializer.Add(options,"Options");
  686. if (plugin_manager)
  687. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  688. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  689. serializer.Save(fname.c_str(),true);
  690. #endif
  691. return true;
  692. }
  693. bool Viewer::load_scene()
  694. {
  695. #ifdef ENABLE_XML_SERIALIZATION
  696. string fname = igl::file_dialog_open();
  697. if (fname.length() == 0)
  698. return false;
  699. ::igl::XMLSerializer serializer("Viewer");
  700. serializer.Add(data,"Data");
  701. serializer.Add(options,"Options");
  702. if (plugin_manager)
  703. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  704. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  705. serializer.Load(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, 16);
  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