Viewer.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. #include "Viewer.h"
  2. #include <igl/get_seconds.h>
  3. #ifdef _WIN32
  4. # include <windows.h>
  5. # undef max
  6. # undef min
  7. #endif
  8. // Todo: windows equivalent for `usleep`
  9. #include <unistd.h>
  10. #ifndef __APPLE__
  11. # define GLEW_STATIC
  12. # include <GL/glew.h>
  13. #endif
  14. #ifdef __APPLE__
  15. # include <OpenGL/gl3.h>
  16. # define __gl_h_ /* Prevent inclusion of the old gl.h */
  17. #else
  18. # ifdef _WIN32
  19. # include <windows.h>
  20. # endif
  21. # include <GL/gl.h>
  22. #endif
  23. #include <Eigen/LU>
  24. #define GLFW_INCLUDE_GLU
  25. #include <GLFW/glfw3.h>
  26. #include <cmath>
  27. #include <cstdio>
  28. #include <sstream>
  29. #include <iomanip>
  30. #include <iostream>
  31. #include <fstream>
  32. #include <algorithm>
  33. #include <igl/project.h>
  34. Eigen::Matrix4f lookAt (
  35. const Eigen::Vector3f& eye,
  36. const Eigen::Vector3f& center,
  37. const Eigen::Vector3f& up)
  38. {
  39. Eigen::Vector3f f = (center - eye).normalized();
  40. Eigen::Vector3f s = f.cross(up).normalized();
  41. Eigen::Vector3f u = s.cross(f);
  42. Eigen::Matrix4f Result = Eigen::Matrix4f::Identity();
  43. Result(0,0) = s(0);
  44. Result(0,1) = s(1);
  45. Result(0,2) = s(2);
  46. Result(1,0) = u(0);
  47. Result(1,1) = u(1);
  48. Result(1,2) = u(2);
  49. Result(2,0) =-f(0);
  50. Result(2,1) =-f(1);
  51. Result(2,2) =-f(2);
  52. Result(0,3) =-s.transpose() * eye;
  53. Result(1,3) =-u.transpose() * eye;
  54. Result(2,3) = f.transpose() * eye;
  55. return Result;
  56. }
  57. Eigen::Matrix4f ortho (
  58. const float left,
  59. const float right,
  60. const float bottom,
  61. const float top,
  62. const float zNear,
  63. const float zFar
  64. )
  65. {
  66. Eigen::Matrix4f Result = Eigen::Matrix4f::Identity();
  67. Result(0,0) = 2.0f / (right - left);
  68. Result(1,1) = 2.0f / (top - bottom);
  69. Result(2,2) = - 2.0f / (zFar - zNear);
  70. Result(0,3) = - (right + left) / (right - left);
  71. Result(1,3) = - (top + bottom) / (top - bottom);
  72. Result(2,3) = - (zFar + zNear) / (zFar - zNear);
  73. return Result;
  74. }
  75. Eigen::Matrix4f frustum (
  76. const float left,
  77. const float right,
  78. const float bottom,
  79. const float top,
  80. const float nearVal,
  81. const float farVal)
  82. {
  83. Eigen::Matrix4f Result = Eigen::Matrix4f::Zero();
  84. Result(0,0) = (2.0f * nearVal) / (right - left);
  85. Result(1,1) = (2.0f * nearVal) / (top - bottom);
  86. Result(0,2) = (right + left) / (right - left);
  87. Result(1,2) = (top + bottom) / (top - bottom);
  88. Result(2,2) = -(farVal + nearVal) / (farVal - nearVal);
  89. Result(3,2) = -1.0f;
  90. Result(2,3) = -(2.0f * farVal * nearVal) / (farVal - nearVal);
  91. return Result;
  92. }
  93. Eigen::Matrix4f scale (const Eigen::Matrix4f& m,
  94. const Eigen::Vector3f& v)
  95. {
  96. Eigen::Matrix4f Result;
  97. Result.col(0) = m.col(0).array() * v(0);
  98. Result.col(1) = m.col(1).array() * v(1);
  99. Result.col(2) = m.col(2).array() * v(2);
  100. Result.col(3) = m.col(3);
  101. return Result;
  102. }
  103. Eigen::Matrix4f translate(
  104. const Eigen::Matrix4f& m,
  105. const Eigen::Vector3f& v)
  106. {
  107. Eigen::Matrix4f Result = m;
  108. Result.col(3) = m.col(0).array() * v(0) + m.col(1).array() * v(1) + m.col(2).array() * v(2) + m.col(3).array();
  109. return Result;
  110. }
  111. #include <limits>
  112. #include <cassert>
  113. #ifdef ENABLE_XML_SERIALIZATION
  114. #include "igl/xml/XMLSerializer.h"
  115. #endif
  116. #include <igl/readOBJ.h>
  117. #include <igl/readOFF.h>
  118. #include <igl/per_face_normals.h>
  119. #include <igl/per_vertex_normals.h>
  120. #include <igl/per_corner_normals.h>
  121. #include <igl/adjacency_list.h>
  122. #include <igl/writeOBJ.h>
  123. #include <igl/writeOFF.h>
  124. #include <igl/massmatrix.h>
  125. #include <igl/file_dialog_open.h>
  126. #include <igl/file_dialog_save.h>
  127. #include <igl/quat_to_mat.h>
  128. #include <igl/quat_mult.h>
  129. #include <igl/axis_angle_to_quat.h>
  130. #include <igl/trackball.h>
  131. #include <igl/snap_to_canonical_view_quat.h>
  132. #include <igl/unproject.h>
  133. #include <igl/viewer/TextRenderer.h>
  134. // Internal global variables used for glfw event handling
  135. static igl::Viewer * __viewer;
  136. static double highdpi = 1;
  137. static double scroll_x = 0;
  138. static double scroll_y = 0;
  139. static igl::TextRenderer __font_renderer;
  140. static void glfw_mouse_press(GLFWwindow* window, int button, int action, int modifier)
  141. {
  142. bool tw_used = TwEventMouseButtonGLFW(button, action);
  143. igl::Viewer::MouseButton mb;
  144. if (button == GLFW_MOUSE_BUTTON_1)
  145. mb = igl::Viewer::IGL_LEFT;
  146. else if (button == GLFW_MOUSE_BUTTON_2)
  147. mb = igl::Viewer::IGL_RIGHT;
  148. else //if (button == GLFW_MOUSE_BUTTON_3)
  149. mb = igl::Viewer::IGL_MIDDLE;
  150. if (action == GLFW_PRESS)
  151. {
  152. if(!tw_used)
  153. {
  154. __viewer->mouse_down(mb,modifier);
  155. }
  156. } else
  157. {
  158. // Always call mouse_up on up
  159. __viewer->mouse_up(mb,modifier);
  160. }
  161. }
  162. static void glfw_error_callback(int error, const char* description)
  163. {
  164. fputs(description, stderr);
  165. }
  166. int global_KMod = 0;
  167. int TwEventKeyGLFW3(int glfwKey, int glfwAction)
  168. {
  169. int handled = 0;
  170. // Register of modifiers state
  171. if (glfwAction==GLFW_PRESS)
  172. {
  173. switch (glfwKey)
  174. {
  175. case GLFW_KEY_LEFT_SHIFT:
  176. case GLFW_KEY_RIGHT_SHIFT:
  177. global_KMod |= TW_KMOD_SHIFT;
  178. break;
  179. case GLFW_KEY_LEFT_CONTROL:
  180. case GLFW_KEY_RIGHT_CONTROL:
  181. global_KMod |= TW_KMOD_CTRL;
  182. break;
  183. case GLFW_KEY_LEFT_ALT:
  184. case GLFW_KEY_RIGHT_ALT:
  185. global_KMod |= TW_KMOD_ALT;
  186. break;
  187. }
  188. }
  189. else
  190. {
  191. switch (glfwKey)
  192. {
  193. case GLFW_KEY_LEFT_SHIFT:
  194. case GLFW_KEY_RIGHT_SHIFT:
  195. global_KMod &= ~TW_KMOD_SHIFT;
  196. break;
  197. case GLFW_KEY_LEFT_CONTROL:
  198. case GLFW_KEY_RIGHT_CONTROL:
  199. global_KMod &= ~TW_KMOD_CTRL;
  200. break;
  201. case GLFW_KEY_LEFT_ALT:
  202. case GLFW_KEY_RIGHT_ALT:
  203. global_KMod &= ~TW_KMOD_ALT;
  204. break;
  205. }
  206. }
  207. // Process key pressed
  208. if (glfwAction==GLFW_PRESS)
  209. {
  210. int mod = global_KMod;
  211. int testkp = ((mod&TW_KMOD_CTRL) || (mod&TW_KMOD_ALT)) ? 1 : 0;
  212. if ((mod&TW_KMOD_CTRL) && glfwKey>0 && glfwKey<GLFW_KEY_ESCAPE ) // CTRL cases
  213. handled = TwKeyPressed(glfwKey, mod);
  214. else if (glfwKey>=GLFW_KEY_ESCAPE )
  215. {
  216. int k = 0;
  217. if (glfwKey>=GLFW_KEY_F1 && glfwKey<=GLFW_KEY_F15)
  218. k = TW_KEY_F1 + (glfwKey-GLFW_KEY_F1);
  219. else if (testkp && glfwKey>=GLFW_KEY_KP_0 && glfwKey<=GLFW_KEY_KP_9)
  220. k = '0' + (glfwKey-GLFW_KEY_KP_0);
  221. else
  222. {
  223. switch (glfwKey)
  224. {
  225. case GLFW_KEY_ESCAPE :
  226. k = TW_KEY_ESCAPE;
  227. break;
  228. case GLFW_KEY_UP:
  229. k = TW_KEY_UP;
  230. break;
  231. case GLFW_KEY_DOWN:
  232. k = TW_KEY_DOWN;
  233. break;
  234. case GLFW_KEY_LEFT:
  235. k = TW_KEY_LEFT;
  236. break;
  237. case GLFW_KEY_RIGHT:
  238. k = TW_KEY_RIGHT;
  239. break;
  240. case GLFW_KEY_TAB:
  241. k = TW_KEY_TAB;
  242. break;
  243. case GLFW_KEY_ENTER:
  244. k = TW_KEY_RETURN;
  245. break;
  246. case GLFW_KEY_BACKSPACE:
  247. k = TW_KEY_BACKSPACE;
  248. break;
  249. case GLFW_KEY_INSERT:
  250. k = TW_KEY_INSERT;
  251. break;
  252. case GLFW_KEY_DELETE:
  253. k = TW_KEY_DELETE;
  254. break;
  255. case GLFW_KEY_PAGE_UP:
  256. k = TW_KEY_PAGE_UP;
  257. break;
  258. case GLFW_KEY_PAGE_DOWN:
  259. k = TW_KEY_PAGE_DOWN;
  260. break;
  261. case GLFW_KEY_HOME:
  262. k = TW_KEY_HOME;
  263. break;
  264. case GLFW_KEY_END:
  265. k = TW_KEY_END;
  266. break;
  267. case GLFW_KEY_KP_ENTER:
  268. k = TW_KEY_RETURN;
  269. break;
  270. case GLFW_KEY_KP_DIVIDE:
  271. if (testkp)
  272. k = '/';
  273. break;
  274. case GLFW_KEY_KP_MULTIPLY:
  275. if (testkp)
  276. k = '*';
  277. break;
  278. case GLFW_KEY_KP_SUBTRACT:
  279. if (testkp)
  280. k = '-';
  281. break;
  282. case GLFW_KEY_KP_ADD:
  283. if (testkp)
  284. k = '+';
  285. break;
  286. case GLFW_KEY_KP_DECIMAL:
  287. if (testkp)
  288. k = '.';
  289. break;
  290. case GLFW_KEY_KP_EQUAL:
  291. if (testkp)
  292. k = '=';
  293. break;
  294. }
  295. }
  296. if (k>0)
  297. handled = TwKeyPressed(k, mod);
  298. }
  299. }
  300. return handled;
  301. }
  302. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  303. {
  304. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  305. glfwSetWindowShouldClose(window, GL_TRUE);
  306. if (!TwEventKeyGLFW3(key,action))
  307. {
  308. if (action == GLFW_PRESS)
  309. __viewer->key_down(key, modifier);
  310. else
  311. __viewer->key_up(key, modifier);
  312. }
  313. }
  314. static void glfw_window_size(GLFWwindow* window, int width, int height)
  315. {
  316. int w = width*highdpi;
  317. int h = height*highdpi;
  318. __viewer->resize(w, h);
  319. TwWindowSize(w, h);
  320. const auto & bar = __viewer->bar;
  321. // Keep AntTweakBar on right side of screen and height == opengl height
  322. // get the current position of a bar
  323. int size[2];
  324. TwGetParam(bar, NULL, "size", TW_PARAM_INT32, 2, size);
  325. int pos[2];
  326. // Place bar on left side of opengl rect (padded by 10 pixels)
  327. pos[0] = 10;//max(10,(int)width - size[0] - 10);
  328. // place bar at top (padded by 10 pixels)
  329. pos[1] = 10;
  330. // Set height to new height of window (padded by 10 pixels on bottom)
  331. size[1] = highdpi*(height-pos[1]-10);
  332. TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, pos);
  333. TwSetParam(bar, NULL, "size", TW_PARAM_INT32, 2,size);
  334. }
  335. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  336. {
  337. if(!TwEventMousePosGLFW(x*highdpi,y*highdpi) || __viewer->down)
  338. {
  339. // Call if TwBar hasn't used or if down
  340. __viewer->mouse_move(x*highdpi, y*highdpi);
  341. }
  342. }
  343. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  344. {
  345. using namespace std;
  346. scroll_x += x;
  347. scroll_y += y;
  348. if (!TwEventMouseWheelGLFW(scroll_y))
  349. __viewer->mouse_scroll(y);
  350. }
  351. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  352. {
  353. if ((c & 0xff00)==0)
  354. TwKeyPressed(c, global_KMod);
  355. }
  356. namespace igl
  357. {
  358. void Viewer::init()
  359. {
  360. // Create a tweak bar
  361. bar = TwNewBar("libIGL-Viewer");
  362. TwDefine(" libIGL-Viewer help='This is a simple 3D mesh viewer.' "); // Message added to the help bar->
  363. TwDefine(" libIGL-Viewer size='200 685'"); // change default tweak bar size
  364. TwDefine(" libIGL-Viewer color='76 76 127' "); // change default tweak bar color
  365. TwDefine(" libIGL-Viewer refresh=0.5"); // change refresh rate
  366. // ---------------------- LOADING ----------------------
  367. #ifdef ENABLE_XML_SERIALIZATION
  368. TwAddButton(bar,"Load Scene", load_scene_cb, this, "group='Workspace'");
  369. TwAddButton(bar,"Save Scene", save_scene_cb, this, "group='Workspace'");
  370. #endif
  371. #ifdef ENABLE_IO
  372. TwAddButton(bar,"Load Mesh", open_dialog_mesh, this, "group='Mesh' key=o");
  373. #endif
  374. // ---------------------- SCENE ----------------------
  375. TwAddButton(bar,"Center object", align_camera_center_cb, this,
  376. " group='Viewing Options'"
  377. " label='Center object' key=A help='Set the center of the camera to the mesh center.'");
  378. TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &(options.camera_zoom),
  379. " min=0.05 max=50 step=0.1 keyIncr=+ keyDecr=- help='Scale the object (1=original size).' group='Scene'");
  380. TwAddButton(bar,"SnapView", snap_to_canonical_quaternion_cb, this,
  381. " group='Scene'"
  382. " label='Snap to canonical view' key=Z "
  383. " help='Snaps view to nearest canonical view.'");
  384. TwAddVarRW(bar,"LightDir", TW_TYPE_DIR3F, options.light_position.data(),
  385. " group='Scene'"
  386. " label='Light direction' open help='Change the light direction.' ");
  387. // ---------------------- DRAW OPTIONS ----------------------
  388. TwAddVarRW(bar, "ToggleOrthographic", TW_TYPE_BOOLCPP, &(options.orthographic),
  389. " group='Viewing Options'"
  390. " label='Orthographic view' "
  391. " help='Toggles orthographic / perspective view. Default: perspective.'");
  392. TwAddVarRW(bar, "Rotation", TW_TYPE_QUAT4F, &(options.trackball_angle),
  393. " group='Viewing Options'"
  394. " label='Rotation'"
  395. " help='Rotates view.'");
  396. TwAddVarCB(bar,"Face-based Normals/Colors", TW_TYPE_BOOLCPP, set_face_based_cb, get_face_based_cb, this,
  397. " group='Draw options'"
  398. " label='Face-based' key=T help='Toggle per face shading/colors.' ");
  399. TwAddVarRW(bar,"Show texture", TW_TYPE_BOOLCPP, &(options.show_texture),
  400. " group='Draw options'");
  401. TwAddVarCB(bar,"Invert Normals", TW_TYPE_BOOLCPP, set_invert_normals_cb, get_invert_normals_cb, this,
  402. " group='Draw options'"
  403. " label='Invert normals' key=i help='Invert normal directions for inside out meshes.' ");
  404. TwAddVarRW(bar,"ShowOverlay", TW_TYPE_BOOLCPP, &(options.show_overlay),
  405. " group='Draw options'"
  406. " label='Show overlay' key=o help='Show the overlay layers.' ");
  407. TwAddVarRW(bar,"ShowOverlayDepth", TW_TYPE_BOOLCPP, &(options.show_overlay_depth),
  408. " group='Draw options'"
  409. " label='Show overlay depth test' help='Enable the depth test for overlay layer.' ");
  410. TwAddVarRW(bar,"Background color", TW_TYPE_COLOR3F,
  411. options.background_color.data(),
  412. " help='Select a background color' colormode=hls group='Draw options'");
  413. TwAddVarRW(bar, "LineColor", TW_TYPE_COLOR3F,
  414. options.line_color.data(),
  415. " label='Line color' help='Select a outline color' group='Draw options'");
  416. TwAddVarRW(bar,"Shininess",TW_TYPE_FLOAT,&options.shininess," group='Draw options'"
  417. " min=1 max=128");
  418. // ---------------------- Overlays ----------------------
  419. TwAddVarRW(bar,"Wireframe", TW_TYPE_BOOLCPP, &(options.show_lines),
  420. " group='Overlays'"
  421. " label='Wireframe' key=l help='Toggle wire frame of mesh'");
  422. TwAddVarRW(bar,"Fill", TW_TYPE_BOOLCPP, &(options.show_faces),
  423. " group='Overlays'"
  424. " label='Fill' key=t help='Display filled polygons of mesh'");
  425. TwAddVarRW(bar,"ShowVertexId", TW_TYPE_BOOLCPP, &(options.show_vertid),
  426. " group='Overlays'"
  427. " label='Show Vertex Labels' key=';' help='Toggle vertex indices'");
  428. TwAddVarRW(bar,"ShowFaceId", TW_TYPE_BOOLCPP, &(options.show_faceid),
  429. " group='Overlays'"
  430. " label='Show Faces Labels' key='CTRL+;' help='Toggle face"
  431. " indices'");
  432. __font_renderer.Init();
  433. init_plugins();
  434. }
  435. Viewer::Viewer()
  436. {
  437. // Default shininess
  438. options.shininess = 35.0f;
  439. // Default colors
  440. options.background_color << 0.3f, 0.3f, 0.5f;
  441. options.line_color << 0.0f, 0.0f, 0.0f;
  442. // Default lights settings
  443. options.light_position << 0.0f, -0.30f, -5.0f;
  444. options.lighting_factor = 1.0f; //on
  445. // Default trackball
  446. options.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  447. // Defalut model viewing parameters
  448. options.model_zoom = 1.0f;
  449. options.model_translation << 0,0,0;
  450. // Camera parameters
  451. options.camera_zoom = 1.0f;
  452. options.orthographic = false;
  453. options.camera_view_angle = 45.0;
  454. options.camera_dnear = 1.0;
  455. options.camera_dfar = 100.0;
  456. options.camera_eye << 0, 0, 5;
  457. options.camera_center << 0, 0, 0;
  458. options.camera_up << 0, 1, 0;
  459. // Default visualization options
  460. options.show_faces = true;
  461. options.show_lines = true;
  462. options.invert_normals = false;
  463. options.show_overlay = true;
  464. options.show_overlay_depth = true;
  465. options.show_vertid = false;
  466. options.show_faceid = false;
  467. options.show_texture = false;
  468. // Default point size / line width
  469. options.point_size = 15;
  470. options.line_width = 0.5f;
  471. options.face_based = false;
  472. options.is_animating = false;
  473. options.animation_max_fps = 30.;
  474. // Temporary variables initialization
  475. down = false;
  476. hack_never_moved = true;
  477. scroll_position = 0.0f;
  478. // Per face
  479. set_face_based(false);
  480. // C-style callbacks
  481. callback_pre_draw = 0;
  482. callback_post_draw = 0;
  483. callback_mouse_down = 0;
  484. callback_mouse_up = 0;
  485. callback_mouse_move = 0;
  486. callback_mouse_scroll = 0;
  487. callback_key_down = 0;
  488. callback_key_up = 0;
  489. callback_pre_draw_data = 0;
  490. callback_post_draw = 0;
  491. callback_mouse_down = 0;
  492. callback_mouse_up = 0;
  493. callback_mouse_move = 0;
  494. callback_mouse_scroll = 0;
  495. callback_key_down = 0;
  496. callback_key_up = 0;
  497. }
  498. void Viewer::init_plugins()
  499. {
  500. // Init all plugins
  501. for (unsigned int i = 0; i<plugins.size(); ++i)
  502. plugins[i]->init(this);
  503. }
  504. Viewer::~Viewer()
  505. {
  506. }
  507. void Viewer::shutdown_plugins()
  508. {
  509. for (unsigned int i = 0; i<plugins.size(); ++i)
  510. plugins[i]->shutdown();
  511. }
  512. bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  513. {
  514. std::string mesh_file_name_string = std::string(mesh_file_name);
  515. // first try to load it with a plugin
  516. for (unsigned int i = 0; i<plugins.size(); ++i)
  517. if (plugins[i]->load(mesh_file_name_string))
  518. return true;
  519. clear_mesh();
  520. size_t last_dot = mesh_file_name_string.rfind('.');
  521. if (last_dot == std::string::npos)
  522. {
  523. printf("Error: No file extension found in %s\n",mesh_file_name);
  524. return false;
  525. }
  526. std::string extension = mesh_file_name_string.substr(last_dot+1);
  527. if (extension == "off" || extension =="OFF")
  528. {
  529. if (!igl::readOFF(mesh_file_name_string, data.V, data.F))
  530. return false;
  531. }
  532. else if (extension == "obj" || extension =="OBJ")
  533. {
  534. Eigen::MatrixXd corner_normals;
  535. Eigen::MatrixXi fNormIndices;
  536. Eigen::MatrixXd UV_V;
  537. Eigen::MatrixXi UV_F;
  538. if (!(igl::readOBJ(mesh_file_name_string, data.V, data.F, corner_normals, fNormIndices, UV_V, UV_F)))
  539. return false;
  540. }
  541. else
  542. {
  543. // unrecognized file type
  544. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  545. return false;
  546. }
  547. compute_normals();
  548. uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  549. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  550. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  551. if (data.V_uv.rows() == 0)
  552. grid_texture();
  553. align_camera_center();
  554. for (unsigned int i = 0; i<plugins.size(); ++i)
  555. if (plugins[i]->post_load())
  556. return true;
  557. return true;
  558. }
  559. void Viewer::compute_normals()
  560. {
  561. igl::per_face_normals(data.V, data.F, data.F_normals);
  562. igl::per_vertex_normals(data.V, data.F, data.F_normals, data.V_normals);
  563. data.dirty |= OpenGL_state::DIRTY_NORMAL;
  564. }
  565. void Viewer::uniform_colors(Eigen::Vector3d ambient, Eigen::Vector3d diffuse, Eigen::Vector3d specular)
  566. {
  567. data.V_material_ambient.resize(data.V.rows(),3);
  568. data.V_material_diffuse.resize(data.V.rows(),3);
  569. data.V_material_specular.resize(data.V.rows(),3);
  570. for (unsigned i=0; i<data.V.rows();++i)
  571. {
  572. data.V_material_ambient.row(i) = ambient;
  573. data.V_material_diffuse.row(i) = diffuse;
  574. data.V_material_specular.row(i) = specular;
  575. }
  576. data.F_material_ambient.resize(data.F.rows(),3);
  577. data.F_material_diffuse.resize(data.F.rows(),3);
  578. data.F_material_specular.resize(data.F.rows(),3);
  579. for (unsigned i=0; i<data.F.rows();++i)
  580. {
  581. data.F_material_ambient.row(i) = ambient;
  582. data.F_material_diffuse.row(i) = diffuse;
  583. data.F_material_specular.row(i) = specular;
  584. }
  585. data.dirty |= OpenGL_state::DIRTY_SPECULAR | OpenGL_state::DIRTY_DIFFUSE | OpenGL_state::DIRTY_AMBIENT;
  586. }
  587. void Viewer::grid_texture()
  588. {
  589. if (data.V_uv.rows() == 0)
  590. {
  591. data.V_uv = data.V.block(0, 0, data.V.rows(), 2);
  592. data.V_uv.col(0) = data.V_uv.col(0).array() - data.V_uv.col(0).minCoeff();
  593. data.V_uv.col(0) = data.V_uv.col(0).array() / data.V_uv.col(0).maxCoeff();
  594. data.V_uv.col(1) = data.V_uv.col(1).array() - data.V_uv.col(1).minCoeff();
  595. data.V_uv.col(1) = data.V_uv.col(1).array() / data.V_uv.col(1).maxCoeff();
  596. data.V_uv = data.V_uv.array() * 10;
  597. data.dirty |= OpenGL_state::DIRTY_TEXTURE;
  598. }
  599. unsigned size = 128;
  600. unsigned size2 = size/2;
  601. data.texture_R.resize(size, size);
  602. for (unsigned i=0; i<size; ++i)
  603. {
  604. for (unsigned j=0; j<size; ++j)
  605. {
  606. data.texture_R(i,j) = 0;
  607. if ((i<size2 && j<size2) || (i>=size2 && j>=size2))
  608. data.texture_R(i,j) = 255;
  609. }
  610. }
  611. data.texture_G = data.texture_R;
  612. data.texture_B = data.texture_R;
  613. data.dirty |= OpenGL_state::DIRTY_TEXTURE;
  614. }
  615. bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  616. {
  617. std::string mesh_file_name_string(mesh_file_name);
  618. // first try to load it with a plugin
  619. for (unsigned int i = 0; i<plugins.size(); ++i)
  620. if (plugins[i]->save(mesh_file_name_string))
  621. return true;
  622. size_t last_dot = mesh_file_name_string.rfind('.');
  623. if (last_dot == std::string::npos)
  624. {
  625. // No file type determined
  626. printf("Error: No file extension found in %s\n",mesh_file_name);
  627. return false;
  628. }
  629. std::string extension = mesh_file_name_string.substr(last_dot+1);
  630. if (extension == "off" || extension =="OFF")
  631. {
  632. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  633. }
  634. else if (extension == "obj" || extension =="OBJ")
  635. {
  636. Eigen::MatrixXd corner_normals;
  637. Eigen::MatrixXi fNormIndices;
  638. Eigen::MatrixXd UV_V;
  639. Eigen::MatrixXi UV_F;
  640. return igl::writeOBJ(mesh_file_name_string, data.V,
  641. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  642. }
  643. else
  644. {
  645. // unrecognized file type
  646. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  647. return false;
  648. }
  649. return true;
  650. }
  651. void Viewer::clear_mesh()
  652. {
  653. data.V = Eigen::MatrixXd (0,3);
  654. data.F = Eigen::MatrixXi (0,3);
  655. data.F_material_ambient = Eigen::MatrixXd (0,3);
  656. data.F_material_diffuse = Eigen::MatrixXd (0,3);
  657. data.F_material_specular = Eigen::MatrixXd (0,3);
  658. data.V_material_ambient = Eigen::MatrixXd (0,3);
  659. data.V_material_diffuse = Eigen::MatrixXd (0,3);
  660. data.V_material_specular = Eigen::MatrixXd (0,3);
  661. data.F_normals = Eigen::MatrixXd (0,3);
  662. data.V_normals = Eigen::MatrixXd (0,3);
  663. data.V_uv = Eigen::MatrixXd (0,2);
  664. data.F_uv = Eigen::MatrixXi (0,3);
  665. data.lines = Eigen::MatrixXd (0,9);
  666. data.points = Eigen::MatrixXd (0,6);
  667. data.labels_positions = Eigen::MatrixXd (0,3);
  668. data.labels_strings.clear();
  669. }
  670. bool Viewer::key_down(unsigned char key, int modifiers)
  671. {
  672. if (callback_key_down)
  673. if (callback_key_down(*this,key,modifiers))
  674. return true;
  675. for (unsigned int i = 0; i<plugins.size(); ++i)
  676. if (plugins[i]->key_down(key, modifiers))
  677. return true;
  678. if (key == 'S')
  679. mouse_scroll(1);
  680. if (key == 'A')
  681. mouse_scroll(-1);
  682. // Why aren't these handled view AntTweakBar?
  683. if (key == 'z') // Don't use 'Z' because that clobbers snap_to_canonical_view_quat
  684. options.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  685. if (key == 'y')
  686. options.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  687. if (key == 'x')
  688. options.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  689. return false;
  690. }
  691. bool Viewer::key_up(unsigned char key, int modifiers)
  692. {
  693. if (callback_key_up)
  694. if (callback_key_up(*this,key,modifiers))
  695. return true;
  696. for (unsigned int i = 0; i<plugins.size(); ++i)
  697. if (plugins[i]->key_up(key, modifiers))
  698. return true;
  699. return false;
  700. }
  701. bool Viewer::mouse_down(MouseButton button, int modifier)
  702. {
  703. if (callback_mouse_down)
  704. if (callback_mouse_down(*this,button,modifier))
  705. return true;
  706. for (unsigned int i = 0; i<plugins.size(); ++i)
  707. if (plugins[i]->mouse_down(button,modifier))
  708. return true;
  709. down = true;
  710. down_mouse_x = current_mouse_x;
  711. down_mouse_y = current_mouse_y;
  712. down_translation = options.model_translation;
  713. // Initialization code for the trackball
  714. Eigen::RowVector3d center;
  715. if (data.V.rows() == 0)
  716. center << 0,0,0;
  717. else
  718. center = data.V.colwise().sum()/data.V.rows();
  719. Eigen::Vector3f coord = igl::project(Eigen::Vector3f(center(0),center(1),center(2)), view * model, proj, viewport);
  720. down_mouse_z = coord[2];
  721. down_rotation = options.trackball_angle;
  722. mouse_mode = ROTATION;
  723. switch (button)
  724. {
  725. case IGL_LEFT:
  726. mouse_mode = ROTATION;
  727. break;
  728. case IGL_RIGHT:
  729. mouse_mode = TRANSLATE;
  730. break;
  731. default:
  732. mouse_mode = NOTHING;
  733. break;
  734. }
  735. return true;
  736. }
  737. bool Viewer::mouse_up(MouseButton button, int modifier)
  738. {
  739. down = false;
  740. if (callback_mouse_up)
  741. if (callback_mouse_up(*this,button,modifier))
  742. return true;
  743. for (unsigned int i = 0; i<plugins.size(); ++i)
  744. if (plugins[i]->mouse_up(button,modifier))
  745. return true;
  746. mouse_mode = NOTHING;
  747. return true;
  748. }
  749. bool Viewer::mouse_move(int mouse_x, int mouse_y)
  750. {
  751. if(hack_never_moved)
  752. {
  753. down_mouse_x = mouse_x;
  754. down_mouse_y = mouse_y;
  755. hack_never_moved = false;
  756. }
  757. current_mouse_x = mouse_x;
  758. current_mouse_y = mouse_y;
  759. if (callback_mouse_move)
  760. if (callback_mouse_move(*this,mouse_x,mouse_y))
  761. return true;
  762. for (unsigned int i = 0; i<plugins.size(); ++i)
  763. if (plugins[i]->mouse_move(mouse_x, mouse_y))
  764. return true;
  765. if (down)
  766. {
  767. switch (mouse_mode)
  768. {
  769. case ROTATION :
  770. {
  771. igl::trackball(width,
  772. height,
  773. 2.0f,
  774. down_rotation.data(),
  775. down_mouse_x,
  776. down_mouse_y,
  777. mouse_x,
  778. mouse_y,
  779. options.trackball_angle.data());
  780. //Eigen::Vector4f snapq = options.trackball_angle;
  781. break;
  782. }
  783. case TRANSLATE:
  784. {
  785. //translation
  786. Eigen::Vector3f pos1 = igl::unproject(Eigen::Vector3f(mouse_x, viewport[3] - mouse_y, down_mouse_z), view * model, proj, viewport);
  787. Eigen::Vector3f pos0 = igl::unproject(Eigen::Vector3f(down_mouse_x, viewport[3] - down_mouse_y, down_mouse_z), view * model, proj, viewport);
  788. Eigen::Vector3f diff = pos1 - pos0;
  789. options.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  790. break;
  791. }
  792. case ZOOM:
  793. {
  794. //float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  795. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  796. options.camera_zoom *= 1 + delta;
  797. down_mouse_x = mouse_x;
  798. down_mouse_y = mouse_y;
  799. break;
  800. }
  801. default:
  802. break;
  803. }
  804. }
  805. return true;
  806. }
  807. bool Viewer::mouse_scroll(float delta_y)
  808. {
  809. scroll_position += delta_y;
  810. if (callback_mouse_scroll)
  811. if (callback_mouse_scroll(*this,delta_y))
  812. return true;
  813. for (unsigned int i = 0; i<plugins.size(); ++i)
  814. if (plugins[i]->mouse_scroll(delta_y))
  815. return true;
  816. // Only zoom if there's actually a change
  817. if(delta_y != 0)
  818. {
  819. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  820. const float min_zoom = 0.1f;
  821. options.camera_zoom = (options.camera_zoom * mult > min_zoom ? options.camera_zoom * mult : min_zoom);
  822. }
  823. return true;
  824. }
  825. void Viewer::draw()
  826. {
  827. using namespace std;
  828. using namespace Eigen;
  829. glClearColor(options.background_color[0],
  830. options.background_color[1],
  831. options.background_color[2],
  832. 1.0f);
  833. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  834. glEnable(GL_DEPTH_TEST);
  835. if (callback_pre_draw)
  836. if (callback_pre_draw(*this))
  837. return;
  838. for (unsigned int i = 0; i<plugins.size(); ++i)
  839. if (plugins[i]->pre_draw())
  840. return;
  841. /* Bind and potentially refresh mesh/line/point data */
  842. if (data.dirty)
  843. {
  844. opengl.set_data(data, options.face_based, options.invert_normals);
  845. data.dirty = OpenGL_state::DIRTY_NONE;
  846. }
  847. opengl.bind_mesh();
  848. // Initialize uniform
  849. glViewport(0, 0, width, height);
  850. model = Eigen::Matrix4f::Identity();
  851. view = Eigen::Matrix4f::Identity();
  852. proj = Eigen::Matrix4f::Identity();
  853. // Set view
  854. view = lookAt(Eigen::Vector3f(options.camera_eye[0], options.camera_eye[1], options.camera_eye[2]),
  855. Eigen::Vector3f(options.camera_center[0], options.camera_center[1], options.camera_center[2]),
  856. Eigen::Vector3f(options.camera_up[0], options.camera_up[1], options.camera_up[2]));
  857. // Set projection
  858. if (options.orthographic)
  859. {
  860. float length = (options.camera_eye - options.camera_center).norm();
  861. float h = tan(options.camera_view_angle/360.0 * M_PI) * (length);
  862. proj = ortho(-h*width/height, h*width/height, -h, h, options.camera_dnear, options.camera_dfar);
  863. }
  864. else
  865. {
  866. float fH = tan(options.camera_view_angle / 360.0 * M_PI) * options.camera_dnear;
  867. float fW = fH * (double)width/(double)height;
  868. proj = frustum(-fW, fW, -fH, fH, options.camera_dnear, options.camera_dfar);
  869. }
  870. // end projection
  871. // Set model transformation
  872. float mat[16];
  873. igl::quat_to_mat(options.trackball_angle.data(), mat);
  874. for (unsigned i=0;i<4;++i)
  875. for (unsigned j=0;j<4;++j)
  876. model(i,j) = mat[i+4*j];
  877. model = scale(model, Eigen::Vector3f(options.camera_zoom,options.camera_zoom,options.camera_zoom));
  878. model = scale(model, Eigen::Vector3f(options.model_zoom,options.model_zoom,options.model_zoom));
  879. model = translate(model, Eigen::Vector3f(options.model_translation[0],options.model_translation[1],options.model_translation[2]));
  880. // Send transformations to the GPU
  881. GLint modeli = opengl.shader_mesh.uniform("model");
  882. GLint viewi = opengl.shader_mesh.uniform("view");
  883. GLint proji = opengl.shader_mesh.uniform("proj");
  884. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  885. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  886. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  887. // Light parameters
  888. GLint specular_exponenti = opengl.shader_mesh.uniform("specular_exponent");
  889. GLint light_position_worldi = opengl.shader_mesh.uniform("light_position_world");
  890. GLint lighting_factori = opengl.shader_mesh.uniform("lighting_factor");
  891. GLint fixed_colori = opengl.shader_mesh.uniform("fixed_color");
  892. GLint texture_factori = opengl.shader_mesh.uniform("texture_factor");
  893. glUniform1f(specular_exponenti, options.shininess);
  894. Vector3f rev_light = -1.*options.light_position;
  895. glUniform3fv(light_position_worldi, 1, rev_light.data());
  896. glUniform1f(lighting_factori, options.lighting_factor); // enables lighting
  897. glUniform4f(fixed_colori, 0.0, 0.0, 0.0, 0.0);
  898. if (data.V.rows()>0)
  899. {
  900. // Render fill
  901. if (options.show_faces)
  902. {
  903. // Texture
  904. glUniform1f(texture_factori, options.show_texture ? 1.0f : 0.0f);
  905. opengl.draw_mesh(true);
  906. glUniform1f(texture_factori, 0.0f);
  907. }
  908. // Render wireframe
  909. if (options.show_lines)
  910. {
  911. glLineWidth(options.line_width);
  912. glUniform4f(fixed_colori, options.line_color[0], options.line_color[1],
  913. options.line_color[2], 1.0f);
  914. opengl.draw_mesh(false);
  915. glUniform4f(fixed_colori, 0.0f, 0.0f, 0.0f, 0.0f);
  916. }
  917. if (options.show_vertid)
  918. {
  919. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  920. for (int i=0; i<data.V.rows(); ++i)
  921. __font_renderer.DrawText(data.V.row(i), data.V_normals.row(i), to_string(i));
  922. __font_renderer.EndDraw();
  923. }
  924. if (options.show_faceid)
  925. {
  926. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  927. for (int i=0; i<data.F.rows(); ++i)
  928. {
  929. Eigen::RowVector3d p = Eigen::RowVector3d::Zero();
  930. for (int j=0;j<data.F.cols();++j)
  931. p += data.V.row(data.F(i,j));
  932. p /= data.F.cols();
  933. __font_renderer.DrawText(p, data.F_normals.row(i), to_string(i));
  934. }
  935. __font_renderer.EndDraw();
  936. }
  937. }
  938. if (options.show_overlay)
  939. {
  940. if (options.show_overlay_depth)
  941. glEnable(GL_DEPTH_TEST);
  942. else
  943. glDisable(GL_DEPTH_TEST);
  944. if (data.lines.rows() > 0)
  945. {
  946. opengl.bind_overlay_lines();
  947. modeli = opengl.shader_overlay_lines.uniform("model");
  948. viewi = opengl.shader_overlay_lines.uniform("view");
  949. proji = opengl.shader_overlay_lines.uniform("proj");
  950. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  951. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  952. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  953. // This must be enabled, otherwise glLineWidth has no effect
  954. glEnable(GL_LINE_SMOOTH);
  955. glLineWidth(options.line_width);
  956. opengl.draw_overlay_lines();
  957. }
  958. if (data.points.rows() > 0)
  959. {
  960. opengl.bind_overlay_points();
  961. modeli = opengl.shader_overlay_points.uniform("model");
  962. viewi = opengl.shader_overlay_points.uniform("view");
  963. proji = opengl.shader_overlay_points.uniform("proj");
  964. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  965. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  966. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  967. glPointSize(options.point_size);
  968. opengl.draw_overlay_points();
  969. }
  970. if (data.labels_positions.rows() > 0)
  971. {
  972. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  973. for (int i=0; i<data.labels_positions.rows(); ++i)
  974. __font_renderer.DrawText(data.labels_positions.row(i), Eigen::Vector3d(0.0,0.0,0.0),
  975. data.labels_strings[i]);
  976. __font_renderer.EndDraw();
  977. }
  978. glEnable(GL_DEPTH_TEST);
  979. }
  980. if (callback_post_draw)
  981. if (callback_post_draw(*this))
  982. return;
  983. for (unsigned int i = 0; i<plugins.size(); ++i)
  984. if (plugins[i]->post_draw())
  985. break;
  986. TwDraw();
  987. }
  988. bool Viewer::save_scene()
  989. {
  990. #ifdef ENABLE_XML_SERIALIZATION
  991. string fname = igl::file_dialog_save();
  992. if (fname.length() == 0)
  993. return false;
  994. ::igl::XMLSerializer serializer("Viewer");
  995. serializer.Add(data,"Data");
  996. serializer.Add(options,"Options");
  997. if (plugin_manager)
  998. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  999. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  1000. serializer.Save(fname.c_str(),true);
  1001. #endif
  1002. return true;
  1003. }
  1004. bool Viewer::load_scene()
  1005. {
  1006. #ifdef ENABLE_XML_SERIALIZATION
  1007. string fname = igl::file_dialog_open();
  1008. if (fname.length() == 0)
  1009. return false;
  1010. ::igl::XMLSerializer serializer("Viewer");
  1011. serializer.Add(data,"Data");
  1012. serializer.Add(options,"Options");
  1013. if (plugin_manager)
  1014. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1015. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  1016. serializer.Load(fname.c_str());
  1017. #endif
  1018. return true;
  1019. }
  1020. void Viewer::align_camera_center()
  1021. {
  1022. get_scale_and_shift_to_fit_mesh(data.V,data.F,options.model_zoom,options.model_translation);
  1023. data.object_scale = (data.V.colwise().maxCoeff() - data.V.colwise().minCoeff()).norm();
  1024. }
  1025. void Viewer::resize(int w, int h)
  1026. {
  1027. width = w;
  1028. height = h;
  1029. viewport = Eigen::Vector4f(0,0,width,height);
  1030. }
  1031. void Viewer::get_scale_and_shift_to_fit_mesh(
  1032. const Eigen::MatrixXd& V,
  1033. const Eigen::MatrixXi& F,
  1034. float& zoom,
  1035. Eigen::Vector3f& shift)
  1036. {
  1037. if (V.rows() == 0)
  1038. return;
  1039. //Compute mesh centroid
  1040. Eigen::SparseMatrix<double> M;
  1041. igl::massmatrix(V,F,igl::MASSMATRIX_TYPE_VORONOI,M);
  1042. const auto & MV = M*V;
  1043. Eigen::RowVector3d centroid = MV.colwise().sum()/M.diagonal().sum();
  1044. Eigen::RowVector3d min_point = V.colwise().minCoeff();
  1045. Eigen::RowVector3d max_point = V.colwise().maxCoeff();
  1046. shift = -centroid.cast<float>();
  1047. double x_scale = fabs(max_point[0] - min_point[0]);
  1048. double y_scale = fabs(max_point[1] - min_point[1]);
  1049. double z_scale = fabs(max_point[2] - min_point[2]);
  1050. zoom = 2.0/ std::max(z_scale,std::max(x_scale,y_scale));
  1051. }
  1052. void TW_CALL Viewer::snap_to_canonical_quaternion_cb(void *clientData)
  1053. {
  1054. Eigen::Vector4f snapq = static_cast<Viewer *>(clientData)->options.trackball_angle;
  1055. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,static_cast<Viewer *>(clientData)->options.trackball_angle.data());
  1056. }
  1057. void TW_CALL Viewer::align_camera_center_cb(void *clientData)
  1058. {
  1059. static_cast<Viewer *>(clientData)->align_camera_center();
  1060. }
  1061. void TW_CALL Viewer::save_scene_cb(void *clientData)
  1062. {
  1063. static_cast<Viewer *>(clientData)->save_scene();
  1064. }
  1065. void TW_CALL Viewer::load_scene_cb(void *clientData)
  1066. {
  1067. static_cast<Viewer *>(clientData)->load_scene();
  1068. }
  1069. void TW_CALL Viewer::set_invert_normals_cb(const void *param, void *clientData)
  1070. {
  1071. Viewer *viewer = static_cast<Viewer *>(clientData);
  1072. viewer->data.dirty |= OpenGL_state::DIRTY_NORMAL;
  1073. viewer->options.invert_normals = *((bool *) param);
  1074. }
  1075. void TW_CALL Viewer::get_invert_normals_cb(void *param, void *clientData)
  1076. {
  1077. *((bool *) param) = static_cast<Viewer *>(clientData)->options.invert_normals;
  1078. }
  1079. void TW_CALL Viewer::set_face_based_cb(const void *param, void *clientData)
  1080. {
  1081. Viewer *viewer = static_cast<Viewer *>(clientData);
  1082. viewer->set_face_based(*((bool *) param));
  1083. }
  1084. void TW_CALL Viewer::get_face_based_cb(void *param, void *clientData)
  1085. {
  1086. *((bool *) param) = static_cast<Viewer *>(clientData)->options.face_based;
  1087. }
  1088. void TW_CALL Viewer::open_dialog_mesh(void *clientData)
  1089. {
  1090. std::string fname = igl::file_dialog_open();
  1091. if (fname.length() == 0)
  1092. return;
  1093. static_cast<Viewer *>(clientData)->load_mesh_from_file(fname.c_str());
  1094. }
  1095. // Serialization
  1096. void Viewer::Options::InitSerialization()
  1097. {
  1098. #ifdef ENABLE_XML_SERIALIZATION
  1099. xmlSerializer->Add(shininess, "shininess");
  1100. xmlSerializer->Add(background_color, "background_color");
  1101. xmlSerializer->Add(line_color, "line_color");
  1102. xmlSerializer->Add(light_position, "light_position");
  1103. xmlSerializer->Add(lighting_factor, "lighting_factor");
  1104. xmlSerializer->Add(trackball_angle, "trackball_angle");
  1105. xmlSerializer->Add(model_zoom, "model_zoom");
  1106. xmlSerializer->Add(model_translation, "model_translation");
  1107. xmlSerializer->Add(model_zoom_uv, "model_zoom_uv");
  1108. xmlSerializer->Add(model_translation_uv, "model_translation_uv");
  1109. xmlSerializer->Add(camera_zoom, "camera_zoom");
  1110. xmlSerializer->Add(orthographic, "orthographic");
  1111. xmlSerializer->Add(camera_eye, "camera_eye");
  1112. xmlSerializer->Add(camera_up, "camera_up");
  1113. xmlSerializer->Add(camera_center, "camera_center");
  1114. xmlSerializer->Add(camera_view_angle, "camera_view_angle");
  1115. xmlSerializer->Add(camera_dnear, "camera_dnear");
  1116. xmlSerializer->Add(camera_dfar, "camera_dfar");
  1117. xmlSerializer->Add(show_overlay, "show_overlay");
  1118. xmlSerializer->Add(show_overlay_depth, "show_overlay_depth");
  1119. xmlSerializer->Add(show_texture, "show_texture");
  1120. xmlSerializer->Add(show_faces, "show_faces");
  1121. xmlSerializer->Add(show_lines, "show_lines");
  1122. xmlSerializer->Add(show_vertid, "show_vertid");
  1123. xmlSerializer->Add(show_faceid, "show_faceid");
  1124. xmlSerializer->Add(point_size, "point_size");
  1125. xmlSerializer->Add(line_width, "line_width");
  1126. xmlSerializer->Add(invert_normals, "invert_normals");
  1127. xmlSerializer->Add(face_based, "face_based");
  1128. #endif
  1129. }
  1130. void Viewer::set_face_based(bool newvalue)
  1131. {
  1132. if (options.face_based != newvalue)
  1133. {
  1134. options.face_based = newvalue;
  1135. data.dirty = OpenGL_state::DIRTY_ALL;
  1136. }
  1137. }
  1138. // Helpers that draws the most common meshes
  1139. void Viewer::set_mesh(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F)
  1140. {
  1141. using namespace std;
  1142. Eigen::MatrixXd V_temp;
  1143. // If V only has two columns, pad with a column of zeros
  1144. if (V.cols() == 2)
  1145. {
  1146. V_temp = Eigen::MatrixXd::Zero(V.rows(),3);
  1147. V_temp.block(0,0,V.rows(),2) = V;
  1148. }
  1149. else
  1150. V_temp = V;
  1151. if (data.V.rows() == 0 && data.F.rows() == 0)
  1152. {
  1153. clear_mesh();
  1154. data.V = V_temp;
  1155. data.F = F;
  1156. compute_normals();
  1157. uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  1158. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  1159. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  1160. grid_texture();
  1161. align_camera_center();
  1162. }
  1163. else
  1164. {
  1165. if (data.V.rows() == V.rows() && data.F.rows() == F.rows())
  1166. {
  1167. data.V = V_temp;
  1168. data.F = F;
  1169. align_camera_center();
  1170. }
  1171. else
  1172. cerr << "ERROR (set_mesh): The new mesh has a different number of vertices/faces. Please clear the mesh before plotting.";
  1173. }
  1174. data.dirty |= OpenGL_state::DIRTY_FACE | OpenGL_state::DIRTY_POSITION;
  1175. }
  1176. void Viewer::set_vertices(const Eigen::MatrixXd& V)
  1177. {
  1178. data.V = V;
  1179. assert(data.F.size() == 0 || data.F.maxCoeff() < data.V.rows());
  1180. data.dirty |= OpenGL_state::DIRTY_POSITION;
  1181. }
  1182. void Viewer::set_normals(const Eigen::MatrixXd& N)
  1183. {
  1184. using namespace std;
  1185. if (N.rows() == data.V.rows())
  1186. {
  1187. set_face_based(false);
  1188. data.V_normals = N;
  1189. }
  1190. else if (N.rows() == data.F.rows() || N.rows() == data.F.rows()*3)
  1191. {
  1192. set_face_based(true);
  1193. data.F_normals = N;
  1194. }
  1195. else
  1196. cerr << "ERROR (set_normals): Please provide a normal per face, per corner or per vertex.";
  1197. data.dirty |= OpenGL_state::DIRTY_NORMAL;
  1198. }
  1199. void Viewer::set_colors(const Eigen::MatrixXd &C)
  1200. {
  1201. using namespace std;
  1202. using namespace Eigen;
  1203. // Ambient color should be darker color
  1204. const auto ambient = [](const MatrixXd & C)->MatrixXd
  1205. {
  1206. return 0.1*C;
  1207. };
  1208. // Specular color should be a less saturated and darker color: dampened
  1209. // highlights
  1210. const auto specular = [](const MatrixXd & C)->MatrixXd
  1211. {
  1212. const double grey = 0.3;
  1213. return grey+0.1*(C.array()-grey);
  1214. };
  1215. if (C.rows() == 1)
  1216. {
  1217. for (unsigned i=0;i<data.V_material_diffuse.rows();++i)
  1218. {
  1219. data.V_material_diffuse.row(i) = C.row(0);
  1220. }
  1221. data.V_material_ambient = ambient(data.V_material_diffuse);
  1222. data.V_material_specular = specular(data.V_material_diffuse);
  1223. for (unsigned i=0;i<data.F_material_diffuse.rows();++i)
  1224. {
  1225. data.F_material_diffuse.row(i) = C.row(0);
  1226. }
  1227. data.F_material_ambient = ambient(data.F_material_diffuse);
  1228. data.F_material_specular = specular(data.F_material_diffuse);
  1229. }
  1230. else if (C.rows() == data.V.rows())
  1231. {
  1232. set_face_based(false);
  1233. data.V_material_diffuse = C;
  1234. data.V_material_ambient = ambient(data.V_material_diffuse);
  1235. data.V_material_specular = specular(data.V_material_diffuse);
  1236. }
  1237. else if (C.rows() == data.F.rows())
  1238. {
  1239. set_face_based(true);
  1240. data.F_material_diffuse = C;
  1241. data.F_material_ambient = ambient(data.F_material_diffuse);
  1242. data.F_material_specular = specular(data.F_material_diffuse);
  1243. }
  1244. else
  1245. cerr << "ERROR (set_colors): Please provide a single color, or a color per face or per vertex.";
  1246. data.dirty |= OpenGL_state::DIRTY_DIFFUSE;
  1247. }
  1248. void Viewer::set_uv(const Eigen::MatrixXd& UV)
  1249. {
  1250. using namespace std;
  1251. if (UV.rows() == data.V.rows())
  1252. {
  1253. set_face_based(false);
  1254. data.V_uv = UV;
  1255. }
  1256. else
  1257. cerr << "ERROR (set_UV): Please provide uv per vertex.";
  1258. data.dirty |= OpenGL_state::DIRTY_UV;
  1259. }
  1260. void Viewer::set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F)
  1261. {
  1262. set_face_based(true);
  1263. data.V_uv = UV_V;
  1264. data.F_uv = UV_F;
  1265. data.dirty |= OpenGL_state::DIRTY_UV;
  1266. }
  1267. void Viewer::set_texture(
  1268. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& R,
  1269. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& G,
  1270. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& B)
  1271. {
  1272. data.texture_R = R;
  1273. data.texture_G = G;
  1274. data.texture_B = B;
  1275. data.dirty |= OpenGL_state::DIRTY_TEXTURE;
  1276. }
  1277. void Viewer::add_points(const Eigen::MatrixXd& P, const Eigen::MatrixXd& C)
  1278. {
  1279. Eigen::MatrixXd P_temp;
  1280. // If P only has two columns, pad with a column of zeros
  1281. if (P.cols() == 2)
  1282. {
  1283. P_temp = Eigen::MatrixXd::Zero(P.rows(),3);
  1284. P_temp.block(0,0,P.rows(),2) = P;
  1285. }
  1286. else
  1287. P_temp = P;
  1288. int lastid = data.points.rows();
  1289. data.points.conservativeResize(data.points.rows() + P_temp.rows(),6);
  1290. for (unsigned i=0; i<P_temp.rows(); ++i)
  1291. data.points.row(lastid+i) << P_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
  1292. data.dirty |= OpenGL_state::DIRTY_OVERLAY_POINTS;
  1293. }
  1294. void Viewer::set_edges(
  1295. const Eigen::MatrixXd& P,
  1296. const Eigen::MatrixXi& E,
  1297. const Eigen::MatrixXd& C)
  1298. {
  1299. using namespace Eigen;
  1300. data.lines.resize(E.rows(),9);
  1301. assert(C.cols() == 3);
  1302. for(int e = 0;e<E.rows();e++)
  1303. {
  1304. RowVector3d color;
  1305. if(C.size() == 3)
  1306. {
  1307. color<<C;
  1308. }else if(C.rows() == E.rows())
  1309. {
  1310. color<<C.row(e);
  1311. }
  1312. data.lines.row(e)<< P.row(E(e,0)), P.row(E(e,1)), color;
  1313. }
  1314. data.dirty |= OpenGL_state::DIRTY_OVERLAY_LINES;
  1315. }
  1316. void Viewer::add_edges(const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C)
  1317. {
  1318. Eigen::MatrixXd P1_temp,P2_temp;
  1319. // If P1 only has two columns, pad with a column of zeros
  1320. if (P1.cols() == 2)
  1321. {
  1322. P1_temp = Eigen::MatrixXd::Zero(P1.rows(),3);
  1323. P1_temp.block(0,0,P1.rows(),2) = P1;
  1324. P2_temp = Eigen::MatrixXd::Zero(P2.rows(),3);
  1325. P2_temp.block(0,0,P2.rows(),2) = P2;
  1326. }
  1327. else
  1328. {
  1329. P1_temp = P1;
  1330. P2_temp = P2;
  1331. }
  1332. int lastid = data.lines.rows();
  1333. data.lines.conservativeResize(data.lines.rows() + P1_temp.rows(),9);
  1334. for (unsigned i=0; i<P1_temp.rows(); ++i)
  1335. data.lines.row(lastid+i) << P1_temp.row(i), P2_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
  1336. data.dirty |= OpenGL_state::DIRTY_OVERLAY_LINES;
  1337. }
  1338. void Viewer::add_label(const Eigen::VectorXd& P, const std::string& str)
  1339. {
  1340. Eigen::RowVectorXd P_temp;
  1341. // If P only has two columns, pad with a column of zeros
  1342. if (P.size() == 2)
  1343. {
  1344. P_temp = Eigen::RowVectorXd::Zero(3);
  1345. P_temp << P, 0;
  1346. }
  1347. else
  1348. P_temp = P;
  1349. int lastid = data.labels_positions.rows();
  1350. data.labels_positions.conservativeResize(lastid+1, 3);
  1351. data.labels_positions.row(lastid) = P_temp;
  1352. data.labels_strings.push_back(str);
  1353. }
  1354. int Viewer::launch(std::string filename)
  1355. {
  1356. GLFWwindow* window;
  1357. glfwSetErrorCallback(glfw_error_callback);
  1358. if (!glfwInit())
  1359. return EXIT_FAILURE;
  1360. glfwWindowHint(GLFW_SAMPLES, 16);
  1361. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  1362. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  1363. #ifdef __APPLE__
  1364. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  1365. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  1366. #endif
  1367. window = glfwCreateWindow(1280, 800, "IGL Viewer", NULL, NULL);
  1368. if (!window)
  1369. {
  1370. glfwTerminate();
  1371. return EXIT_FAILURE;
  1372. }
  1373. glfwMakeContextCurrent(window);
  1374. #ifndef __APPLE__
  1375. glewExperimental = true;
  1376. GLenum err = glewInit();
  1377. if (GLEW_OK != err)
  1378. {
  1379. /* Problem: glewInit failed, something is seriously wrong. */
  1380. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  1381. }
  1382. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  1383. #endif
  1384. #ifdef DEBUG
  1385. int major, minor, rev;
  1386. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  1387. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  1388. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  1389. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  1390. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  1391. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  1392. #endif
  1393. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  1394. // Initialize AntTweakBar
  1395. TwInit(TW_OPENGL_CORE, NULL);
  1396. // Initialize IGL viewer
  1397. init();
  1398. __viewer = this;
  1399. // Register callbacks
  1400. 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);
  1401. // Handle retina displays (windows and mac)
  1402. int width, height;
  1403. glfwGetFramebufferSize(window, &width, &height);
  1404. int width_window, height_window;
  1405. glfwGetWindowSize(window, &width_window, &height_window);
  1406. highdpi = width/width_window;
  1407. glfw_window_size(window,width_window,height_window);
  1408. opengl.init();
  1409. // Load the mesh passed as input
  1410. if (filename.size() > 0)
  1411. load_mesh_from_file(filename.c_str());
  1412. // Rendering loop
  1413. while (!glfwWindowShouldClose(window))
  1414. {
  1415. double tic = get_seconds();
  1416. draw();
  1417. glfwSwapBuffers(window);
  1418. if(options.is_animating)
  1419. {
  1420. glfwPollEvents();
  1421. // In microseconds
  1422. double duration = 1000000.*(get_seconds()-tic);
  1423. const double min_duration = 1000000./options.animation_max_fps;
  1424. if(duration<min_duration)
  1425. {
  1426. // TODO: windows equivalent
  1427. usleep(min_duration-duration);
  1428. }
  1429. }
  1430. else
  1431. {
  1432. glfwWaitEvents();
  1433. }
  1434. }
  1435. opengl.free();
  1436. __font_renderer.Shut();
  1437. shutdown_plugins();
  1438. glfwDestroyWindow(window);
  1439. glfwTerminate();
  1440. return EXIT_SUCCESS;
  1441. }
  1442. } // end namespace