Viewer.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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. // Must defined this before including Viewer.h
  9. #define IGL_VIEWER_VIEWER_CPP
  10. #include "Viewer.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. #if defined(__APPLE__)
  31. #define GLFW_INCLUDE_GLCOREARB
  32. #else
  33. #define GL_GLEXT_PROTOTYPES
  34. #endif
  35. #include <GLFW/glfw3.h>
  36. #include <cmath>
  37. #include <cstdio>
  38. #include <sstream>
  39. #include <iomanip>
  40. #include <iostream>
  41. #include <fstream>
  42. #include <algorithm>
  43. #include <limits>
  44. #include <cassert>
  45. #ifdef IGL_VIEWER_WITH_NANOGUI
  46. # include <nanogui/formhelper.h>
  47. # include <nanogui/screen.h>
  48. #endif
  49. #include <igl/project.h>
  50. #include <igl/get_seconds.h>
  51. #include <igl/readOBJ.h>
  52. #include <igl/readOFF.h>
  53. #include <igl/adjacency_list.h>
  54. #include <igl/writeOBJ.h>
  55. #include <igl/writeOFF.h>
  56. #include <igl/massmatrix.h>
  57. #include <igl/file_dialog_open.h>
  58. #include <igl/file_dialog_save.h>
  59. #include <igl/quat_mult.h>
  60. #include <igl/axis_angle_to_quat.h>
  61. #include <igl/trackball.h>
  62. #include <igl/two_axis_valuator_fixed_up.h>
  63. #include <igl/snap_to_canonical_view_quat.h>
  64. #include <igl/unproject.h>
  65. #ifdef ENABLE_SERIALIZATION
  66. #include <igl/serialize.h>
  67. #endif
  68. // Internal global variables used for glfw event handling
  69. static igl::opengl::glfw::Viewer * __viewer;
  70. static double highdpi = 1;
  71. static double scroll_x = 0;
  72. static double scroll_y = 0;
  73. static void glfw_mouse_press(GLFWwindow* window, int button, int action, int modifier)
  74. {
  75. bool tw_used =
  76. #ifdef IGL_VIEWER_WITH_NANOGUI
  77. __viewer->screen->mouseButtonCallbackEvent(button,action,modifier);
  78. #else
  79. false;
  80. #endif
  81. igl::opengl::glfw::Viewer::MouseButton mb;
  82. if (button == GLFW_MOUSE_BUTTON_1)
  83. mb = igl::opengl::glfw::Viewer::MouseButton::Left;
  84. else if (button == GLFW_MOUSE_BUTTON_2)
  85. mb = igl::opengl::glfw::Viewer::MouseButton::Right;
  86. else //if (button == GLFW_MOUSE_BUTTON_3)
  87. mb = igl::opengl::glfw::Viewer::MouseButton::Middle;
  88. if (action == GLFW_PRESS)
  89. {
  90. if(!tw_used)
  91. {
  92. __viewer->mouse_down(mb,modifier);
  93. }
  94. } else
  95. {
  96. // Always call mouse_up on up
  97. __viewer->mouse_up(mb,modifier);
  98. }
  99. }
  100. static void glfw_error_callback(int error, const char* description)
  101. {
  102. fputs(description, stderr);
  103. }
  104. static void glfw_char_mods_callback(GLFWwindow* window, unsigned int codepoint, int modifier)
  105. {
  106. // TODO: pass to nanogui (although it's also using physical key down/up
  107. // rather than character codes...
  108. #ifdef IGL_VIEWER_WITH_NANOGUI
  109. if(! __viewer->screen->charCallbackEvent(codepoint) )
  110. #endif
  111. {
  112. __viewer->key_pressed(codepoint, modifier);
  113. }
  114. }
  115. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  116. {
  117. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  118. glfwSetWindowShouldClose(window, GL_TRUE);
  119. #ifdef IGL_VIEWER_WITH_NANOGUI
  120. if (__viewer->screen->keyCallbackEvent(key,scancode,action,modifier) == false)
  121. #endif
  122. {
  123. if (action == GLFW_PRESS)
  124. __viewer->key_down(key, modifier);
  125. else if(action == GLFW_RELEASE)
  126. __viewer->key_up(key, modifier);
  127. }
  128. }
  129. static void glfw_window_size(GLFWwindow* window, int width, int height)
  130. {
  131. int w = width*highdpi;
  132. int h = height*highdpi;
  133. __viewer->post_resize(w, h);
  134. // TODO: repositioning of the nanogui
  135. }
  136. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  137. {
  138. if(
  139. #ifdef IGL_VIEWER_WITH_NANOGUI
  140. __viewer->screen->cursorPosCallbackEvent(x,y) == false &&
  141. #endif
  142. true
  143. )
  144. {
  145. __viewer->mouse_move(x*highdpi, y*highdpi);
  146. }
  147. }
  148. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  149. {
  150. using namespace std;
  151. scroll_x += x;
  152. scroll_y += y;
  153. #ifdef IGL_VIEWER_WITH_NANOGUI
  154. if (__viewer->screen->scrollCallbackEvent(x,y) == false)
  155. #endif
  156. {
  157. __viewer->mouse_scroll(y);
  158. }
  159. }
  160. static void glfw_drop_callback(GLFWwindow *window,int count,const char **filenames)
  161. {
  162. #ifdef IGL_VIEWER_WITH_NANOGUI
  163. __viewer->screen->dropCallbackEvent(count,filenames);
  164. #endif
  165. }
  166. namespace igl
  167. {
  168. namespace opengl
  169. {
  170. namespace glfw
  171. {
  172. IGL_INLINE int Viewer::launch(bool resizable,bool fullscreen)
  173. {
  174. // TODO return values are being ignored...
  175. launch_init(resizable,fullscreen);
  176. launch_rendering(true);
  177. launch_shut();
  178. return EXIT_SUCCESS;
  179. }
  180. IGL_INLINE int Viewer::launch_init(bool resizable,bool fullscreen)
  181. {
  182. glfwSetErrorCallback(glfw_error_callback);
  183. if (!glfwInit())
  184. {
  185. return EXIT_FAILURE;
  186. }
  187. glfwWindowHint(GLFW_SAMPLES, 8);
  188. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  189. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  190. #ifdef __APPLE__
  191. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  192. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  193. #endif
  194. if(fullscreen)
  195. {
  196. GLFWmonitor *monitor = glfwGetPrimaryMonitor();
  197. const GLFWvidmode *mode = glfwGetVideoMode(monitor);
  198. window = glfwCreateWindow(mode->width,mode->height,"libigl viewer",monitor,nullptr);
  199. }
  200. else
  201. {
  202. if (core.viewport.tail<2>().any()) {
  203. window = glfwCreateWindow(core.viewport(2),core.viewport(3),"libigl viewer",nullptr,nullptr);
  204. } else {
  205. window = glfwCreateWindow(1280,800,"libigl viewer",nullptr,nullptr);
  206. }
  207. }
  208. if (!window)
  209. {
  210. glfwTerminate();
  211. return EXIT_FAILURE;
  212. }
  213. glfwMakeContextCurrent(window);
  214. #ifndef __APPLE__
  215. glewExperimental = true;
  216. GLenum err = glewInit();
  217. if(GLEW_OK != err)
  218. {
  219. /* Problem: glewInit failed, something is seriously wrong. */
  220. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  221. }
  222. glGetError(); // pull and savely ignonre unhandled errors like GL_INVALID_ENUM
  223. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  224. #endif
  225. #if defined(DEBUG) || defined(_DEBUG)
  226. int major, minor, rev;
  227. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  228. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  229. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  230. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  231. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  232. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  233. #endif
  234. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  235. // Initialize FormScreen
  236. #ifdef IGL_VIEWER_WITH_NANOGUI
  237. screen = new nanogui::Screen();
  238. screen->initialize(window, false);
  239. ngui = new nanogui::FormHelper(screen);
  240. #endif
  241. __viewer = this;
  242. // Register callbacks
  243. glfwSetKeyCallback(window, glfw_key_callback);
  244. glfwSetCursorPosCallback(window,glfw_mouse_move);
  245. glfwSetWindowSizeCallback(window,glfw_window_size);
  246. glfwSetMouseButtonCallback(window,glfw_mouse_press);
  247. glfwSetScrollCallback(window,glfw_mouse_scroll);
  248. glfwSetCharModsCallback(window,glfw_char_mods_callback);
  249. glfwSetDropCallback(window,glfw_drop_callback);
  250. // Handle retina displays (windows and mac)
  251. int width, height;
  252. glfwGetFramebufferSize(window, &width, &height);
  253. int width_window, height_window;
  254. glfwGetWindowSize(window, &width_window, &height_window);
  255. highdpi = width/width_window;
  256. glfw_window_size(window,width_window,height_window);
  257. //opengl.init();
  258. core.align_camera_center(data().V,data().F);
  259. // Initialize IGL viewer
  260. init();
  261. return EXIT_SUCCESS;
  262. }
  263. IGL_INLINE bool Viewer::launch_rendering(bool loop)
  264. {
  265. // glfwMakeContextCurrent(window);
  266. // Rendering loop
  267. while (!glfwWindowShouldClose(window))
  268. {
  269. double tic = get_seconds();
  270. draw();
  271. glfwSwapBuffers(window);
  272. if(core.is_animating)
  273. {
  274. glfwPollEvents();
  275. // In microseconds
  276. double duration = 1000000.*(get_seconds()-tic);
  277. const double min_duration = 1000000./core.animation_max_fps;
  278. if(duration<min_duration)
  279. {
  280. std::this_thread::sleep_for(std::chrono::microseconds((int)(min_duration-duration)));
  281. }
  282. }
  283. else
  284. {
  285. glfwWaitEvents();
  286. }
  287. if (!loop)
  288. return !glfwWindowShouldClose(window);
  289. }
  290. return EXIT_SUCCESS;
  291. }
  292. IGL_INLINE void Viewer::launch_shut()
  293. {
  294. for(auto & opengl : opengl_state_list)
  295. {
  296. opengl.free();
  297. }
  298. core.shut();
  299. shutdown_plugins();
  300. #ifdef IGL_VIEWER_WITH_NANOGUI
  301. delete ngui;
  302. //delete screen;
  303. screen = nullptr;
  304. ngui = nullptr;
  305. #endif
  306. glfwDestroyWindow(window);
  307. glfwTerminate();
  308. return;
  309. }
  310. IGL_INLINE void Viewer::init()
  311. {
  312. #ifdef IGL_VIEWER_WITH_NANOGUI
  313. using namespace nanogui;
  314. ngui->setFixedSize(Eigen::Vector2i(60,20));
  315. // Create nanogui widgets
  316. /* nanogui::Window *window = */ ngui->addWindow(Eigen::Vector2i(10,10),"libIGL-Viewer");
  317. // ---------------------- LOADING ----------------------
  318. #ifdef ENABLE_SERIALIZATION
  319. ngui->addGroup("Workspace");
  320. ngui->addButton("Load",[&](){this->load_scene();});
  321. ngui->addButton("Save",[&](){this->save_scene();});
  322. #endif
  323. #ifdef ENABLE_IO
  324. ngui->addGroup("Mesh");
  325. ngui->addButton("Load",[&](){this->open_dialog_load_mesh();});
  326. ngui->addButton("Save",[&](){this->open_dialog_save_mesh();});
  327. #endif
  328. ngui->addGroup("Viewing Options");
  329. ngui->addButton("Center object",[&](){this->core.align_camera_center(
  330. this->data().V,this->data().F);});
  331. ngui->addButton("Snap canonical view",[&]()
  332. {
  333. this->snap_to_canonical_quaternion();
  334. });
  335. ngui->addVariable("Zoom", core.camera_zoom);
  336. ngui->addVariable("Orthographic view", core.orthographic);
  337. ngui->addGroup("Draw options");
  338. ngui->addVariable<bool>("Face-based", [&](bool checked)
  339. {
  340. this->data().set_face_based(checked);
  341. },[&]()
  342. {
  343. return this->data().face_based;
  344. });
  345. ngui->addVariable("Show texture",this->data().show_texture);
  346. ngui->addVariable<bool>("Invert normals",[&](bool checked)
  347. {
  348. this->data().dirty |= ViewerData::DIRTY_NORMAL;
  349. this->data().invert_normals = checked;
  350. },[&]()
  351. {
  352. return this->data().invert_normals;
  353. });
  354. // Alec: This will probably just attach to the data() at the time
  355. // that addVariable is called. We probably need to use a callback here.
  356. ngui->addVariable("Show overlay", data().show_overlay);
  357. ngui->addVariable("Show overlay depth", data().show_overlay_depth);
  358. ngui->addVariable("Line color", (nanogui::Color &) data().line_color);
  359. ngui->addVariable("Background", (nanogui::Color &) core.background_color);
  360. ngui->addVariable("Shininess", data().shininess);
  361. ngui->addGroup("Overlays");
  362. ngui->addVariable("Wireframe", data().show_lines);
  363. ngui->addVariable("Fill", data().show_faces);
  364. ngui->addVariable("Show vertex labels", data().show_vertid);
  365. ngui->addVariable("Show faces labels", data().show_faceid);
  366. screen->setVisible(true);
  367. screen->performLayout();
  368. #endif
  369. core.init();
  370. if (callback_init)
  371. if (callback_init(*this))
  372. return;
  373. init_plugins();
  374. }
  375. IGL_INLINE void Viewer::init_plugins()
  376. {
  377. // Init all plugins
  378. for (unsigned int i = 0; i<plugins.size(); ++i)
  379. {
  380. plugins[i]->init(this);
  381. }
  382. }
  383. IGL_INLINE void Viewer::shutdown_plugins()
  384. {
  385. for (unsigned int i = 0; i<plugins.size(); ++i)
  386. {
  387. plugins[i]->shutdown();
  388. }
  389. }
  390. IGL_INLINE Viewer::Viewer():
  391. data_list(1),
  392. opengl_state_list(1),
  393. selected_data_index(0)
  394. {
  395. window = nullptr;
  396. #ifdef IGL_VIEWER_WITH_NANOGUI
  397. ngui = nullptr;
  398. screen = nullptr;
  399. #endif
  400. // Temporary variables initialization
  401. down = false;
  402. hack_never_moved = true;
  403. scroll_position = 0.0f;
  404. // Per face
  405. data().set_face_based(false);
  406. // C-style callbacks
  407. callback_init = nullptr;
  408. callback_pre_draw = nullptr;
  409. callback_post_draw = nullptr;
  410. callback_mouse_down = nullptr;
  411. callback_mouse_up = nullptr;
  412. callback_mouse_move = nullptr;
  413. callback_mouse_scroll = nullptr;
  414. callback_key_down = nullptr;
  415. callback_key_up = nullptr;
  416. callback_init_data = nullptr;
  417. callback_pre_draw_data = nullptr;
  418. callback_post_draw_data = nullptr;
  419. callback_mouse_down_data = nullptr;
  420. callback_mouse_up_data = nullptr;
  421. callback_mouse_move_data = nullptr;
  422. callback_mouse_scroll_data = nullptr;
  423. callback_key_down_data = nullptr;
  424. callback_key_up_data = nullptr;
  425. #ifndef IGL_VIEWER_VIEWER_QUIET
  426. const std::string usage(R"(igl::opengl::glfw::Viewer usage:
  427. [drag] Rotate scene
  428. A,a Toggle animation (tight draw loop)
  429. F,f Toggle face based
  430. I,i Toggle invert normals
  431. L,l Toggle wireframe
  432. O,o Toggle orthographic/perspective projection
  433. T,t Toggle filled faces
  434. Z Snap to canonical view
  435. [,] Toggle between rotation control types (trackball, two-axis
  436. valuator with fixed up, 2D mode with no rotation)
  437. <,> Toggle between models.)"
  438. #ifdef IGL_VIEWER_WITH_NANOGUI
  439. R"(
  440. ; Toggle vertex labels
  441. : Toggle face labels)"
  442. #endif
  443. );
  444. std::cout<<usage<<std::endl;
  445. #endif
  446. }
  447. IGL_INLINE Viewer::~Viewer()
  448. {
  449. }
  450. IGL_INLINE bool Viewer::load_mesh_from_file(
  451. const std::string & mesh_file_name_string)
  452. {
  453. // first try to load it with a plugin
  454. for (unsigned int i = 0; i<plugins.size(); ++i)
  455. {
  456. if (plugins[i]->load(mesh_file_name_string))
  457. {
  458. return true;
  459. }
  460. }
  461. // Create new data slot and set to selected
  462. if(!(data().F.rows() == 0 && data().V.rows() == 0))
  463. {
  464. append_mesh();
  465. }
  466. data().clear();
  467. size_t last_dot = mesh_file_name_string.rfind('.');
  468. if (last_dot == std::string::npos)
  469. {
  470. std::cerr<<"Error: No file extension found in "<<
  471. mesh_file_name_string<<std::endl;
  472. return false;
  473. }
  474. std::string extension = mesh_file_name_string.substr(last_dot+1);
  475. if (extension == "off" || extension =="OFF")
  476. {
  477. Eigen::MatrixXd V;
  478. Eigen::MatrixXi F;
  479. if (!igl::readOFF(mesh_file_name_string, V, F))
  480. return false;
  481. data().set_mesh(V,F);
  482. }
  483. else if (extension == "obj" || extension =="OBJ")
  484. {
  485. Eigen::MatrixXd corner_normals;
  486. Eigen::MatrixXi fNormIndices;
  487. Eigen::MatrixXd UV_V;
  488. Eigen::MatrixXi UV_F;
  489. Eigen::MatrixXd V;
  490. Eigen::MatrixXi F;
  491. if (!(
  492. igl::readOBJ(
  493. mesh_file_name_string,
  494. V, UV_V, corner_normals, F, UV_F, fNormIndices)))
  495. {
  496. return false;
  497. }
  498. data().set_mesh(V,F);
  499. data().set_uv(UV_V,UV_F);
  500. }
  501. else
  502. {
  503. // unrecognized file type
  504. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  505. return false;
  506. }
  507. data().compute_normals();
  508. data().uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  509. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  510. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  511. if (data().V_uv.rows() == 0)
  512. {
  513. data().grid_texture();
  514. }
  515. core.align_camera_center(data().V,data().F);
  516. for (unsigned int i = 0; i<plugins.size(); ++i)
  517. if (plugins[i]->post_load())
  518. return true;
  519. return true;
  520. }
  521. IGL_INLINE bool Viewer::save_mesh_to_file(
  522. const std::string & mesh_file_name_string)
  523. {
  524. // first try to load it with a plugin
  525. for (unsigned int i = 0; i<plugins.size(); ++i)
  526. if (plugins[i]->save(mesh_file_name_string))
  527. return true;
  528. size_t last_dot = mesh_file_name_string.rfind('.');
  529. if (last_dot == std::string::npos)
  530. {
  531. // No file type determined
  532. std::cerr<<"Error: No file extension found in "<<
  533. mesh_file_name_string<<std::endl;
  534. return false;
  535. }
  536. std::string extension = mesh_file_name_string.substr(last_dot+1);
  537. if (extension == "off" || extension =="OFF")
  538. {
  539. return igl::writeOFF(
  540. mesh_file_name_string,data().V,data().F);
  541. }
  542. else if (extension == "obj" || extension =="OBJ")
  543. {
  544. Eigen::MatrixXd corner_normals;
  545. Eigen::MatrixXi fNormIndices;
  546. Eigen::MatrixXd UV_V;
  547. Eigen::MatrixXi UV_F;
  548. return igl::writeOBJ(mesh_file_name_string,
  549. data().V,
  550. data().F,
  551. corner_normals, fNormIndices, UV_V, UV_F);
  552. }
  553. else
  554. {
  555. // unrecognized file type
  556. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  557. return false;
  558. }
  559. return true;
  560. }
  561. IGL_INLINE bool Viewer::key_pressed(unsigned int unicode_key,int modifiers)
  562. {
  563. if (callback_key_pressed)
  564. if (callback_key_pressed(*this,unicode_key,modifiers))
  565. return true;
  566. for (unsigned int i = 0; i<plugins.size(); ++i)
  567. {
  568. if (plugins[i]->key_pressed(unicode_key, modifiers))
  569. {
  570. return true;
  571. }
  572. }
  573. switch(unicode_key)
  574. {
  575. case 'A':
  576. case 'a':
  577. {
  578. core.is_animating = !core.is_animating;
  579. return true;
  580. }
  581. case 'F':
  582. case 'f':
  583. {
  584. data().set_face_based(!data().face_based);
  585. return true;
  586. }
  587. case 'I':
  588. case 'i':
  589. {
  590. data().dirty |= ViewerData::DIRTY_NORMAL;
  591. data().invert_normals = !data().invert_normals;
  592. return true;
  593. }
  594. case 'L':
  595. case 'l':
  596. {
  597. data().show_lines = !data().show_lines;
  598. return true;
  599. }
  600. case 'O':
  601. case 'o':
  602. {
  603. core.orthographic = !core.orthographic;
  604. return true;
  605. }
  606. case 'T':
  607. case 't':
  608. {
  609. data().show_faces = !data().show_faces;
  610. return true;
  611. }
  612. case 'Z':
  613. {
  614. snap_to_canonical_quaternion();
  615. return true;
  616. }
  617. case '[':
  618. case ']':
  619. {
  620. if(core.rotation_type == ViewerCore::ROTATION_TYPE_TRACKBALL)
  621. core.set_rotation_type(ViewerCore::ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP);
  622. else
  623. core.set_rotation_type(ViewerCore::ROTATION_TYPE_TRACKBALL);
  624. return true;
  625. }
  626. case '<':
  627. case '>':
  628. {
  629. selected_data_index =
  630. (selected_data_index + data_list.size() + (unicode_key=='>'?1:-1))%data_list.size();
  631. return true;
  632. }
  633. #ifdef IGL_VIEWER_WITH_NANOGUI
  634. case ';':
  635. data().show_vertid = !data().show_vertid;
  636. return true;
  637. case ':':
  638. data().show_faceid = !data().show_faceid;
  639. return true;
  640. #endif
  641. default: break;//do nothing
  642. }
  643. return false;
  644. }
  645. IGL_INLINE bool Viewer::key_down(int key,int modifiers)
  646. {
  647. if (callback_key_down)
  648. if (callback_key_down(*this,key,modifiers))
  649. return true;
  650. for (unsigned int i = 0; i<plugins.size(); ++i)
  651. if (plugins[i]->key_down(key, modifiers))
  652. return true;
  653. return false;
  654. }
  655. IGL_INLINE bool Viewer::key_up(int key,int modifiers)
  656. {
  657. if (callback_key_up)
  658. if (callback_key_up(*this,key,modifiers))
  659. return true;
  660. for (unsigned int i = 0; i<plugins.size(); ++i)
  661. if (plugins[i]->key_up(key, modifiers))
  662. return true;
  663. return false;
  664. }
  665. IGL_INLINE bool Viewer::mouse_down(MouseButton button,int modifier)
  666. {
  667. // Remember mouse location at down even if used by callback/plugin
  668. down_mouse_x = current_mouse_x;
  669. down_mouse_y = current_mouse_y;
  670. if (callback_mouse_down)
  671. if (callback_mouse_down(*this,static_cast<int>(button),modifier))
  672. return true;
  673. for (unsigned int i = 0; i<plugins.size(); ++i)
  674. if(plugins[i]->mouse_down(static_cast<int>(button),modifier))
  675. return true;
  676. down = true;
  677. down_translation = core.model_translation;
  678. // Initialization code for the trackball
  679. Eigen::RowVector3d center;
  680. if (data().V.rows() == 0)
  681. {
  682. center << 0,0,0;
  683. }else
  684. {
  685. center = data().V.colwise().sum()/data().V.rows();
  686. }
  687. Eigen::Vector3f coord =
  688. igl::project(
  689. Eigen::Vector3f(center(0),center(1),center(2)),
  690. (core.view * core.model).eval(),
  691. core.proj,
  692. core.viewport);
  693. down_mouse_z = coord[2];
  694. down_rotation = core.trackball_angle;
  695. mouse_mode = MouseMode::Rotation;
  696. switch (button)
  697. {
  698. case MouseButton::Left:
  699. if (core.rotation_type == ViewerCore::ROTATION_TYPE_NO_ROTATION) {
  700. mouse_mode = MouseMode::Translation;
  701. } else {
  702. mouse_mode = MouseMode::Rotation;
  703. }
  704. break;
  705. case MouseButton::Right:
  706. mouse_mode = MouseMode::Translation;
  707. break;
  708. default:
  709. mouse_mode = MouseMode::None;
  710. break;
  711. }
  712. return true;
  713. }
  714. IGL_INLINE bool Viewer::mouse_up(MouseButton button,int modifier)
  715. {
  716. down = false;
  717. if (callback_mouse_up)
  718. if (callback_mouse_up(*this,static_cast<int>(button),modifier))
  719. return true;
  720. for (unsigned int i = 0; i<plugins.size(); ++i)
  721. if(plugins[i]->mouse_up(static_cast<int>(button),modifier))
  722. return true;
  723. mouse_mode = MouseMode::None;
  724. return true;
  725. }
  726. IGL_INLINE bool Viewer::mouse_move(int mouse_x,int mouse_y)
  727. {
  728. if(hack_never_moved)
  729. {
  730. down_mouse_x = mouse_x;
  731. down_mouse_y = mouse_y;
  732. hack_never_moved = false;
  733. }
  734. current_mouse_x = mouse_x;
  735. current_mouse_y = mouse_y;
  736. if (callback_mouse_move)
  737. if (callback_mouse_move(*this,mouse_x,mouse_y))
  738. return true;
  739. for (unsigned int i = 0; i<plugins.size(); ++i)
  740. if (plugins[i]->mouse_move(mouse_x, mouse_y))
  741. return true;
  742. if (down)
  743. {
  744. switch (mouse_mode)
  745. {
  746. case MouseMode::Rotation:
  747. {
  748. switch(core.rotation_type)
  749. {
  750. default:
  751. assert(false && "Unknown rotation type");
  752. case ViewerCore::ROTATION_TYPE_NO_ROTATION:
  753. break;
  754. case ViewerCore::ROTATION_TYPE_TRACKBALL:
  755. igl::trackball(
  756. core.viewport(2),
  757. core.viewport(3),
  758. 2.0f,
  759. down_rotation,
  760. down_mouse_x,
  761. down_mouse_y,
  762. mouse_x,
  763. mouse_y,
  764. core.trackball_angle);
  765. break;
  766. case ViewerCore::ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP:
  767. igl::two_axis_valuator_fixed_up(
  768. core.viewport(2),core.viewport(3),
  769. 2.0,
  770. down_rotation,
  771. down_mouse_x, down_mouse_y, mouse_x, mouse_y,
  772. core.trackball_angle);
  773. break;
  774. }
  775. //Eigen::Vector4f snapq = core.trackball_angle;
  776. break;
  777. }
  778. case MouseMode::Translation:
  779. {
  780. //translation
  781. Eigen::Vector3f pos1 = igl::unproject(Eigen::Vector3f(mouse_x, core.viewport[3] - mouse_y, down_mouse_z), (core.view * core.model).eval(), core.proj, core.viewport);
  782. Eigen::Vector3f pos0 = igl::unproject(Eigen::Vector3f(down_mouse_x, core.viewport[3] - down_mouse_y, down_mouse_z), (core.view * core.model).eval(), core.proj, core.viewport);
  783. Eigen::Vector3f diff = pos1 - pos0;
  784. core.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  785. break;
  786. }
  787. case MouseMode::Zoom:
  788. {
  789. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  790. core.camera_zoom *= 1 + delta;
  791. down_mouse_x = mouse_x;
  792. down_mouse_y = mouse_y;
  793. break;
  794. }
  795. default:
  796. break;
  797. }
  798. }
  799. return true;
  800. }
  801. IGL_INLINE bool Viewer::mouse_scroll(float delta_y)
  802. {
  803. scroll_position += delta_y;
  804. if (callback_mouse_scroll)
  805. if (callback_mouse_scroll(*this,delta_y))
  806. return true;
  807. for (unsigned int i = 0; i<plugins.size(); ++i)
  808. if (plugins[i]->mouse_scroll(delta_y))
  809. return true;
  810. // Only zoom if there's actually a change
  811. if(delta_y != 0)
  812. {
  813. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  814. const float min_zoom = 0.1f;
  815. core.camera_zoom = (core.camera_zoom * mult > min_zoom ? core.camera_zoom * mult : min_zoom);
  816. }
  817. return true;
  818. }
  819. IGL_INLINE bool Viewer::load_scene()
  820. {
  821. std::string fname = igl::file_dialog_open();
  822. if(fname.length() == 0)
  823. {
  824. return false;
  825. }
  826. return load_scene(fname);
  827. }
  828. IGL_INLINE bool Viewer::load_scene(std::string fname)
  829. {
  830. #ifdef ENABLE_SERIALIZATION
  831. igl::deserialize(core,"Core",fname.c_str());
  832. #ifndef ENABLE_SERIALIZATION_CORE_ONLY
  833. igl::deserialize(data(),"Data",fname.c_str());
  834. for(unsigned int i = 0; i <plugins.size(); ++i)
  835. {
  836. igl::deserialize(*plugins[i],plugins[i]->plugin_name,fname.c_str());
  837. }
  838. #endif
  839. #endif
  840. return true;
  841. }
  842. IGL_INLINE bool Viewer::save_scene()
  843. {
  844. std::string fname = igl::file_dialog_save();
  845. if (fname.length() == 0)
  846. return false;
  847. #ifdef ENABLE_SERIALIZATION
  848. igl::serialize(core,"Core",fname.c_str(),true);
  849. #ifndef ENABLE_SERIALIZATION_CORE_ONLY
  850. igl::serialize(data(),"Data",fname.c_str());
  851. for(unsigned int i = 0; i <plugins.size(); ++i)
  852. igl::serialize(*plugins[i],plugins[i]->plugin_name,fname.c_str());
  853. #endif
  854. #endif
  855. return true;
  856. }
  857. IGL_INLINE void Viewer::draw()
  858. {
  859. using namespace std;
  860. using namespace Eigen;
  861. int width, height;
  862. glfwGetFramebufferSize(window, &width, &height);
  863. int width_window, height_window;
  864. glfwGetWindowSize(window, &width_window, &height_window);
  865. auto highdpi_tmp = width/width_window;
  866. if(fabs(highdpi_tmp-highdpi)>1e-8)
  867. {
  868. post_resize(width, height);
  869. highdpi=highdpi_tmp;
  870. }
  871. core.clear_framebuffers();
  872. if (callback_pre_draw)
  873. {
  874. if (callback_pre_draw(*this))
  875. {
  876. return;
  877. }
  878. }
  879. for (unsigned int i = 0; i<plugins.size(); ++i)
  880. {
  881. if (plugins[i]->pre_draw())
  882. {
  883. return;
  884. }
  885. }
  886. assert(data_list.size() == opengl_state_list.size());
  887. for(int i = 0;i<data_list.size();i++)
  888. {
  889. opengl_state_list[i].init();
  890. core.draw(data_list[i],opengl_state_list[i]);
  891. }
  892. if (callback_post_draw)
  893. {
  894. if (callback_post_draw(*this))
  895. {
  896. return;
  897. }
  898. }
  899. for (unsigned int i = 0; i<plugins.size(); ++i)
  900. {
  901. if (plugins[i]->post_draw())
  902. {
  903. break;
  904. }
  905. }
  906. #ifdef IGL_VIEWER_WITH_NANOGUI
  907. screen->drawContents();
  908. screen->drawWidgets();
  909. #endif
  910. }
  911. IGL_INLINE void Viewer::resize(int w,int h)
  912. {
  913. if (window) {
  914. glfwSetWindowSize(window, w/highdpi, h/highdpi);
  915. }
  916. post_resize(w, h);
  917. }
  918. IGL_INLINE void Viewer::post_resize(int w,int h)
  919. {
  920. core.viewport = Eigen::Vector4f(0,0,w,h);
  921. for (unsigned int i = 0; i<plugins.size(); ++i)
  922. {
  923. plugins[i]->post_resize(w, h);
  924. }
  925. }
  926. IGL_INLINE void Viewer::snap_to_canonical_quaternion()
  927. {
  928. Eigen::Quaternionf snapq = this->core.trackball_angle;
  929. igl::snap_to_canonical_view_quat(snapq,1.0f,this->core.trackball_angle);
  930. }
  931. IGL_INLINE void Viewer::open_dialog_load_mesh()
  932. {
  933. std::string fname = igl::file_dialog_open();
  934. if (fname.length() == 0)
  935. return;
  936. this->load_mesh_from_file(fname.c_str());
  937. }
  938. IGL_INLINE void Viewer::open_dialog_save_mesh()
  939. {
  940. std::string fname = igl::file_dialog_save();
  941. if(fname.length() == 0)
  942. return;
  943. this->save_mesh_to_file(fname.c_str());
  944. }
  945. IGL_INLINE ViewerData& Viewer::data()
  946. {
  947. assert(!data_list.empty() && "data_list should never be empty");
  948. assert(
  949. (selected_data_index >= 0 && selected_data_index < data_list.size()) &&
  950. "selected_data_index should be in bounds");
  951. return data_list[selected_data_index];
  952. }
  953. IGL_INLINE void Viewer::append_mesh()
  954. {
  955. assert(data_list.size() == opengl_state_list.size());
  956. assert(data_list.size() >= 1);
  957. data_list.emplace_back();
  958. opengl_state_list.emplace_back();
  959. selected_data_index = data_list.size()-1;
  960. }
  961. IGL_INLINE bool Viewer::erase_mesh(const size_t index)
  962. {
  963. assert(data_list.size() == opengl_state_list.size());
  964. assert(data_list.size() >= 1);
  965. if(data_list.size() == 1)
  966. {
  967. // Cannot remove last mesh
  968. return false;
  969. }
  970. data_list.erase(data_list.begin() + index);
  971. opengl_state_list.erase(opengl_state_list.begin() + index);
  972. if(selected_data_index >= index && selected_data_index>0)
  973. {
  974. selected_data_index--;
  975. }
  976. std::cout<<"data: "<<data_list.size()<<std::endl;
  977. std::cout<<"opengl_state: "<<opengl_state_list.size()<<std::endl;
  978. std::cout<<"selected_data_index: "<<selected_data_index<<std::endl;
  979. return true;
  980. }
  981. IGL_INLINE State& Viewer::selected_opengl_state()
  982. {
  983. assert(!opengl_state_list.empty() && "opengl_state_list should never be empty");
  984. assert(opengl_state_list.size() == data_list.size());
  985. assert(
  986. (selected_data_index >= 0 && selected_data_index < opengl_state_list.size()) &&
  987. "selected_data_index should be in bounds");
  988. return opengl_state_list[selected_data_index];
  989. }
  990. } // end namespace
  991. } // end namespace
  992. }