Viewer.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398
  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. //OK NV
  34. Eigen::Vector3f project(const Eigen::Vector3f& obj,
  35. const Eigen::Matrix4f& model,
  36. const Eigen::Matrix4f& proj,
  37. const Eigen::Vector4f& viewport)
  38. {
  39. Eigen::Vector4f tmp;
  40. tmp << obj,1;
  41. tmp = model * tmp;
  42. tmp = proj * tmp;
  43. tmp = tmp.array() / tmp(3);
  44. tmp = tmp.array() * 0.5f + 0.5f;
  45. tmp(0) = tmp(0) * viewport(2) + viewport(0);
  46. tmp(1) = tmp(1) * viewport(3) + viewport(1);
  47. return tmp.head(3);
  48. }
  49. Eigen::Matrix4f lookAt (
  50. const Eigen::Vector3f& eye,
  51. const Eigen::Vector3f& center,
  52. const Eigen::Vector3f& up)
  53. {
  54. Eigen::Vector3f f = (center - eye).normalized();
  55. Eigen::Vector3f s = f.cross(up).normalized();
  56. Eigen::Vector3f u = s.cross(f);
  57. Eigen::Matrix4f Result = Eigen::Matrix4f::Identity();
  58. Result(0,0) = s(0);
  59. Result(0,1) = s(1);
  60. Result(0,2) = s(2);
  61. Result(1,0) = u(0);
  62. Result(1,1) = u(1);
  63. Result(1,2) = u(2);
  64. Result(2,0) =-f(0);
  65. Result(2,1) =-f(1);
  66. Result(2,2) =-f(2);
  67. Result(0,3) =-s.transpose() * eye;
  68. Result(1,3) =-u.transpose() * eye;
  69. Result(2,3) = f.transpose() * eye;
  70. return Result;
  71. }
  72. Eigen::Matrix4f ortho (
  73. const float left,
  74. const float right,
  75. const float bottom,
  76. const float top,
  77. const float zNear,
  78. const float zFar
  79. )
  80. {
  81. Eigen::Matrix4f Result = Eigen::Matrix4f::Identity();
  82. Result(0,0) = 2.0f / (right - left);
  83. Result(1,1) = 2.0f / (top - bottom);
  84. Result(2,2) = - 2.0f / (zFar - zNear);
  85. Result(0,3) = - (right + left) / (right - left);
  86. Result(1,3) = - (top + bottom) / (top - bottom);
  87. Result(2,3) = - (zFar + zNear) / (zFar - zNear);
  88. return Result;
  89. }
  90. Eigen::Matrix4f frustum (
  91. const float left,
  92. const float right,
  93. const float bottom,
  94. const float top,
  95. const float nearVal,
  96. const float farVal)
  97. {
  98. Eigen::Matrix4f Result = Eigen::Matrix4f::Zero();
  99. Result(0,0) = (2.0f * nearVal) / (right - left);
  100. Result(1,1) = (2.0f * nearVal) / (top - bottom);
  101. Result(0,2) = (right + left) / (right - left);
  102. Result(1,2) = (top + bottom) / (top - bottom);
  103. Result(2,2) = -(farVal + nearVal) / (farVal - nearVal);
  104. Result(3,2) = -1.0f;
  105. Result(2,3) = -(2.0f * farVal * nearVal) / (farVal - nearVal);
  106. return Result;
  107. }
  108. Eigen::Matrix4f scale (const Eigen::Matrix4f& m,
  109. const Eigen::Vector3f& v)
  110. {
  111. Eigen::Matrix4f Result;
  112. Result.col(0) = m.col(0).array() * v(0);
  113. Result.col(1) = m.col(1).array() * v(1);
  114. Result.col(2) = m.col(2).array() * v(2);
  115. Result.col(3) = m.col(3);
  116. return Result;
  117. }
  118. Eigen::Matrix4f translate(
  119. const Eigen::Matrix4f& m,
  120. const Eigen::Vector3f& v)
  121. {
  122. Eigen::Matrix4f Result = m;
  123. 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();
  124. return Result;
  125. }
  126. #include <limits>
  127. #include <cassert>
  128. #ifdef ENABLE_XML_SERIALIZATION
  129. #include "igl/xml/XMLSerializer.h"
  130. #endif
  131. #include <igl/readOBJ.h>
  132. #include <igl/readOFF.h>
  133. #include <igl/per_face_normals.h>
  134. #include <igl/per_vertex_normals.h>
  135. #include <igl/per_corner_normals.h>
  136. #include <igl/adjacency_list.h>
  137. #include <igl/writeOBJ.h>
  138. #include <igl/writeOFF.h>
  139. #include <igl/massmatrix.h>
  140. #include <igl/file_dialog_open.h>
  141. #include <igl/file_dialog_save.h>
  142. #include <igl/quat_to_mat.h>
  143. #include <igl/quat_mult.h>
  144. #include <igl/axis_angle_to_quat.h>
  145. #include <igl/trackball.h>
  146. #include <igl/snap_to_canonical_view_quat.h>
  147. #include <igl/unproject.h>
  148. #include <TwOpenGLCore.h>
  149. #include <igl/viewer/TextRenderer.h>
  150. // Plugin manager (exported to other compilation units)
  151. igl::Plugin_manager igl_viewer_plugin_manager;
  152. // Internal global variables used for glfw event handling
  153. static igl::Viewer * __viewer;
  154. static double highdpi = 1;
  155. static double scroll_x = 0;
  156. static double scroll_y = 0;
  157. static igl::TextRenderer __font_renderer;
  158. static void glfw_mouse_press(GLFWwindow* window, int button, int action, int modifier)
  159. {
  160. bool tw_used = TwEventMouseButtonGLFW(button, action);
  161. igl::Viewer::MouseButton mb;
  162. if (button == GLFW_MOUSE_BUTTON_1)
  163. mb = igl::Viewer::IGL_LEFT;
  164. else if (button == GLFW_MOUSE_BUTTON_2)
  165. mb = igl::Viewer::IGL_RIGHT;
  166. else //if (button == GLFW_MOUSE_BUTTON_3)
  167. mb = igl::Viewer::IGL_MIDDLE;
  168. if (action == GLFW_PRESS)
  169. {
  170. if(!tw_used)
  171. {
  172. __viewer->mouse_down(mb,modifier);
  173. }
  174. } else
  175. {
  176. // Always call mouse_up on up
  177. __viewer->mouse_up(mb,modifier);
  178. }
  179. }
  180. static void glfw_error_callback(int error, const char* description)
  181. {
  182. fputs(description, stderr);
  183. }
  184. int global_KMod = 0;
  185. int TwEventKeyGLFW3(int glfwKey, int glfwAction)
  186. {
  187. int handled = 0;
  188. // Register of modifiers state
  189. if (glfwAction==GLFW_PRESS)
  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. else
  208. {
  209. switch (glfwKey)
  210. {
  211. case GLFW_KEY_LEFT_SHIFT:
  212. case GLFW_KEY_RIGHT_SHIFT:
  213. global_KMod &= ~TW_KMOD_SHIFT;
  214. break;
  215. case GLFW_KEY_LEFT_CONTROL:
  216. case GLFW_KEY_RIGHT_CONTROL:
  217. global_KMod &= ~TW_KMOD_CTRL;
  218. break;
  219. case GLFW_KEY_LEFT_ALT:
  220. case GLFW_KEY_RIGHT_ALT:
  221. global_KMod &= ~TW_KMOD_ALT;
  222. break;
  223. }
  224. }
  225. // Process key pressed
  226. if (glfwAction==GLFW_PRESS)
  227. {
  228. int mod = global_KMod;
  229. int testkp = ((mod&TW_KMOD_CTRL) || (mod&TW_KMOD_ALT)) ? 1 : 0;
  230. if ((mod&TW_KMOD_CTRL) && glfwKey>0 && glfwKey<GLFW_KEY_ESCAPE ) // CTRL cases
  231. handled = TwKeyPressed(glfwKey, mod);
  232. else if (glfwKey>=GLFW_KEY_ESCAPE )
  233. {
  234. int k = 0;
  235. if (glfwKey>=GLFW_KEY_F1 && glfwKey<=GLFW_KEY_F15)
  236. k = TW_KEY_F1 + (glfwKey-GLFW_KEY_F1);
  237. else if (testkp && glfwKey>=GLFW_KEY_KP_0 && glfwKey<=GLFW_KEY_KP_9)
  238. k = '0' + (glfwKey-GLFW_KEY_KP_0);
  239. else
  240. {
  241. switch (glfwKey)
  242. {
  243. case GLFW_KEY_ESCAPE :
  244. k = TW_KEY_ESCAPE;
  245. break;
  246. case GLFW_KEY_UP:
  247. k = TW_KEY_UP;
  248. break;
  249. case GLFW_KEY_DOWN:
  250. k = TW_KEY_DOWN;
  251. break;
  252. case GLFW_KEY_LEFT:
  253. k = TW_KEY_LEFT;
  254. break;
  255. case GLFW_KEY_RIGHT:
  256. k = TW_KEY_RIGHT;
  257. break;
  258. case GLFW_KEY_TAB:
  259. k = TW_KEY_TAB;
  260. break;
  261. case GLFW_KEY_ENTER:
  262. k = TW_KEY_RETURN;
  263. break;
  264. case GLFW_KEY_BACKSPACE:
  265. k = TW_KEY_BACKSPACE;
  266. break;
  267. case GLFW_KEY_INSERT:
  268. k = TW_KEY_INSERT;
  269. break;
  270. case GLFW_KEY_DELETE:
  271. k = TW_KEY_DELETE;
  272. break;
  273. case GLFW_KEY_PAGE_UP:
  274. k = TW_KEY_PAGE_UP;
  275. break;
  276. case GLFW_KEY_PAGE_DOWN:
  277. k = TW_KEY_PAGE_DOWN;
  278. break;
  279. case GLFW_KEY_HOME:
  280. k = TW_KEY_HOME;
  281. break;
  282. case GLFW_KEY_END:
  283. k = TW_KEY_END;
  284. break;
  285. case GLFW_KEY_KP_ENTER:
  286. k = TW_KEY_RETURN;
  287. break;
  288. case GLFW_KEY_KP_DIVIDE:
  289. if (testkp)
  290. k = '/';
  291. break;
  292. case GLFW_KEY_KP_MULTIPLY:
  293. if (testkp)
  294. k = '*';
  295. break;
  296. case GLFW_KEY_KP_SUBTRACT:
  297. if (testkp)
  298. k = '-';
  299. break;
  300. case GLFW_KEY_KP_ADD:
  301. if (testkp)
  302. k = '+';
  303. break;
  304. case GLFW_KEY_KP_DECIMAL:
  305. if (testkp)
  306. k = '.';
  307. break;
  308. case GLFW_KEY_KP_EQUAL:
  309. if (testkp)
  310. k = '=';
  311. break;
  312. }
  313. }
  314. if (k>0)
  315. handled = TwKeyPressed(k, mod);
  316. }
  317. }
  318. return handled;
  319. }
  320. static void glfw_key_callback(GLFWwindow* window, int key, int scancode, int action, int modifier)
  321. {
  322. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
  323. glfwSetWindowShouldClose(window, GL_TRUE);
  324. if (!TwEventKeyGLFW3(key,action))
  325. {
  326. if (action == GLFW_PRESS)
  327. __viewer->key_down(key, modifier);
  328. else
  329. __viewer->key_up(key, modifier);
  330. }
  331. }
  332. static void glfw_window_size(GLFWwindow* window, int width, int height)
  333. {
  334. int w = width*highdpi;
  335. int h = height*highdpi;
  336. __viewer->resize(w, h);
  337. TwWindowSize(w, h);
  338. const auto & bar = __viewer->bar;
  339. // Keep AntTweakBar on right side of screen and height == opengl height
  340. // get the current position of a bar
  341. int size[2];
  342. TwGetParam(bar, NULL, "size", TW_PARAM_INT32, 2, size);
  343. int pos[2];
  344. // Place bar on left side of opengl rect (padded by 10 pixels)
  345. pos[0] = 10;//max(10,(int)width - size[0] - 10);
  346. // place bar at top (padded by 10 pixels)
  347. pos[1] = 10;
  348. // Set height to new height of window (padded by 10 pixels on bottom)
  349. size[1] = highdpi*(height-pos[1]-10);
  350. TwSetParam(bar, NULL, "position", TW_PARAM_INT32, 2, pos);
  351. TwSetParam(bar, NULL, "size", TW_PARAM_INT32, 2,size);
  352. }
  353. static void glfw_mouse_move(GLFWwindow* window, double x, double y)
  354. {
  355. if(!TwEventMousePosGLFW(x*highdpi,y*highdpi) || __viewer->down)
  356. {
  357. // Call if TwBar hasn't used or if down
  358. __viewer->mouse_move(x*highdpi, y*highdpi);
  359. }
  360. }
  361. static void glfw_mouse_scroll(GLFWwindow* window, double x, double y)
  362. {
  363. using namespace std;
  364. scroll_x += x;
  365. scroll_y += y;
  366. if (!TwEventMouseWheelGLFW(scroll_y))
  367. __viewer->mouse_scroll(y);
  368. }
  369. static void glfw_char_callback(GLFWwindow* window, unsigned int c)
  370. {
  371. if ((c & 0xff00)==0)
  372. TwKeyPressed(c, global_KMod);
  373. }
  374. namespace igl
  375. {
  376. void Viewer::init(Plugin_manager* pm)
  377. {
  378. plugin_manager = pm;
  379. // Create a tweak bar
  380. bar = TwNewBar("libIGL-Viewer");
  381. TwDefine(" libIGL-Viewer help='This is a simple 3D mesh viewer.' "); // Message added to the help bar->
  382. TwDefine(" libIGL-Viewer size='200 685'"); // change default tweak bar size
  383. TwDefine(" libIGL-Viewer color='76 76 127' "); // change default tweak bar color
  384. TwDefine(" libIGL-Viewer refresh=0.5"); // change refresh rate
  385. // ---------------------- LOADING ----------------------
  386. #ifdef ENABLE_XML_SERIALIZATION
  387. TwAddButton(bar,"Load Scene", load_scene_cb, this, "group='Workspace'");
  388. TwAddButton(bar,"Save Scene", save_scene_cb, this, "group='Workspace'");
  389. #endif
  390. #ifdef ENABLE_IO
  391. TwAddButton(bar,"Load Mesh", open_dialog_mesh, this, "group='Mesh' key=o");
  392. #endif
  393. // ---------------------- SCENE ----------------------
  394. TwAddButton(bar,"Center object", align_camera_center_cb, this,
  395. " group='Viewing Options'"
  396. " label='Center object' key=A help='Set the center of the camera to the mesh center.'");
  397. TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &(options.camera_zoom),
  398. " min=0.05 max=50 step=0.1 keyIncr=+ keyDecr=- help='Scale the object (1=original size).' group='Scene'");
  399. TwAddButton(bar,"SnapView", snap_to_canonical_quaternion_cb, this,
  400. " group='Scene'"
  401. " label='Snap to canonical view' key=Z "
  402. " help='Snaps view to nearest canonical view.'");
  403. TwAddVarRW(bar,"LightDir", TW_TYPE_DIR3F, options.light_position.data(),
  404. " group='Scene'"
  405. " label='Light direction' open help='Change the light direction.' ");
  406. // ---------------------- DRAW OPTIONS ----------------------
  407. TwAddVarRW(bar, "ToggleOrthographic", TW_TYPE_BOOLCPP, &(options.orthographic),
  408. " group='Viewing Options'"
  409. " label='Orthographic view' "
  410. " help='Toggles orthographic / perspective view. Default: perspective.'");
  411. TwAddVarRW(bar, "Rotation", TW_TYPE_QUAT4F, &(options.trackball_angle),
  412. " group='Viewing Options'"
  413. " label='Rotation'"
  414. " help='Rotates view.'");
  415. TwAddVarCB(bar,"Face-based Normals/Colors", TW_TYPE_BOOLCPP, set_face_based_cb, get_face_based_cb, this,
  416. " group='Draw options'"
  417. " label='Face-based' key=T help='Toggle per face shading/colors.' ");
  418. TwAddVarRW(bar,"Show texture", TW_TYPE_BOOLCPP, &(options.show_texture),
  419. " group='Draw options'");
  420. TwAddVarCB(bar,"Invert Normals", TW_TYPE_BOOLCPP, set_invert_normals_cb, get_invert_normals_cb, this,
  421. " group='Draw options'"
  422. " label='Invert normals' key=i help='Invert normal directions for inside out meshes.' ");
  423. TwAddVarRW(bar,"ShowOverlay", TW_TYPE_BOOLCPP, &(options.show_overlay),
  424. " group='Draw options'"
  425. " label='Show overlay' key=o help='Show the overlay layers.' ");
  426. TwAddVarRW(bar,"ShowOverlayDepth", TW_TYPE_BOOLCPP, &(options.show_overlay_depth),
  427. " group='Draw options'"
  428. " label='Show overlay depth test' help='Enable the depth test for overlay layer.' ");
  429. TwAddVarRW(bar,"Background color", TW_TYPE_COLOR3F,
  430. options.background_color.data(),
  431. " help='Select a background color' colormode=hls group='Draw options'");
  432. TwAddVarRW(bar, "LineColor", TW_TYPE_COLOR3F,
  433. options.line_color.data(),
  434. " label='Line color' help='Select a outline color' group='Draw options'");
  435. TwAddVarRW(bar,"Shininess",TW_TYPE_FLOAT,&options.shininess," group='Draw options'"
  436. " min=1 max=128");
  437. // ---------------------- Overlays ----------------------
  438. TwAddVarRW(bar,"Wireframe", TW_TYPE_BOOLCPP, &(options.show_lines),
  439. " group='Overlays'"
  440. " label='Wireframe' key=l help='Toggle wire frame of mesh'");
  441. TwAddVarRW(bar,"Fill", TW_TYPE_BOOLCPP, &(options.show_faces),
  442. " group='Overlays'"
  443. " label='Fill' key=t help='Display filled polygons of mesh'");
  444. TwAddVarRW(bar,"ShowVertexId", TW_TYPE_BOOLCPP, &(options.show_vertid),
  445. " group='Overlays'"
  446. " label='Show Vertex Labels' key=';' help='Toggle vertex indices'");
  447. TwAddVarRW(bar,"ShowFaceId", TW_TYPE_BOOLCPP, &(options.show_faceid),
  448. " group='Overlays'"
  449. " label='Show Faces Labels' key='CTRL+;' help='Toggle face"
  450. " indices'");
  451. __font_renderer.Init();
  452. init_plugins();
  453. }
  454. Viewer::Viewer()
  455. {
  456. plugin_manager = 0;
  457. // Default shininess
  458. options.shininess = 35.0f;
  459. // Default colors
  460. options.background_color << 0.3f, 0.3f, 0.5f;
  461. options.line_color << 0.0f, 0.0f, 0.0f;
  462. // Default lights settings
  463. options.light_position << 0.0f, -0.30f, -5.0f;
  464. options.lighting_factor = 1.0f; //on
  465. // Default trackball
  466. options.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  467. // Defalut model viewing parameters
  468. options.model_zoom = 1.0f;
  469. options.model_translation << 0,0,0;
  470. // Camera parameters
  471. options.camera_zoom = 1.0f;
  472. options.orthographic = false;
  473. options.camera_view_angle = 45.0;
  474. options.camera_dnear = 1.0;
  475. options.camera_dfar = 100.0;
  476. options.camera_eye << 0, 0, 5;
  477. options.camera_center << 0, 0, 0;
  478. options.camera_up << 0, 1, 0;
  479. // Default visualization options
  480. options.show_faces = true;
  481. options.show_lines = true;
  482. options.invert_normals = false;
  483. options.show_overlay = true;
  484. options.show_overlay_depth = true;
  485. options.show_vertid = false;
  486. options.show_faceid = false;
  487. options.show_texture = false;
  488. // Default point size / line width
  489. options.point_size = 15;
  490. options.line_width = 0.5f;
  491. options.face_based = false;
  492. options.is_animating = false;
  493. options.animation_max_fps = 30.;
  494. // Temporary variables initialization
  495. down = false;
  496. hack_never_moved = true;
  497. scroll_position = 0.0f;
  498. // Per face
  499. set_face_based(false);
  500. // C-style callbacks
  501. callback_pre_draw = 0;
  502. callback_post_draw = 0;
  503. callback_mouse_down = 0;
  504. callback_mouse_up = 0;
  505. callback_mouse_move = 0;
  506. callback_mouse_scroll = 0;
  507. callback_key_down = 0;
  508. callback_key_up = 0;
  509. callback_pre_draw_data = 0;
  510. callback_post_draw = 0;
  511. callback_mouse_down = 0;
  512. callback_mouse_up = 0;
  513. callback_mouse_move = 0;
  514. callback_mouse_scroll = 0;
  515. callback_key_down = 0;
  516. callback_key_up = 0;
  517. }
  518. void Viewer::init_plugins()
  519. {
  520. // Init all plugins
  521. if (plugin_manager)
  522. for (unsigned int i = 0; i<plugin_manager->plugin_list.size(); ++i)
  523. plugin_manager->plugin_list[i]->init(this);
  524. }
  525. Viewer::~Viewer()
  526. {
  527. }
  528. void Viewer::shutdown_plugins()
  529. {
  530. if (plugin_manager)
  531. for (unsigned int i = 0; i<plugin_manager->plugin_list.size(); ++i)
  532. plugin_manager->plugin_list[i]->shutdown();
  533. }
  534. bool Viewer::load_mesh_from_file(const char* mesh_file_name)
  535. {
  536. std::string mesh_file_name_string = std::string(mesh_file_name);
  537. // first try to load it with a plugin
  538. if (plugin_manager)
  539. for (unsigned int i = 0; i<plugin_manager->plugin_list.size(); ++i)
  540. if (plugin_manager->plugin_list[i]->load(mesh_file_name_string))
  541. return true;
  542. clear_mesh();
  543. size_t last_dot = mesh_file_name_string.rfind('.');
  544. if (last_dot == std::string::npos)
  545. {
  546. printf("Error: No file extension found in %s\n",mesh_file_name);
  547. return false;
  548. }
  549. std::string extension = mesh_file_name_string.substr(last_dot+1);
  550. if (extension == "off" || extension =="OFF")
  551. {
  552. if (!igl::readOFF(mesh_file_name_string, data.V, data.F))
  553. return false;
  554. }
  555. else if (extension == "obj" || extension =="OBJ")
  556. {
  557. Eigen::MatrixXd corner_normals;
  558. Eigen::MatrixXi fNormIndices;
  559. Eigen::MatrixXd UV_V;
  560. Eigen::MatrixXi UV_F;
  561. if (!(igl::readOBJ(mesh_file_name_string, data.V, data.F, corner_normals, fNormIndices, UV_V, UV_F)))
  562. return false;
  563. }
  564. else
  565. {
  566. // unrecognized file type
  567. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  568. return false;
  569. }
  570. compute_normals();
  571. uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  572. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  573. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  574. if (data.V_uv.rows() == 0)
  575. grid_texture();
  576. align_camera_center();
  577. if (plugin_manager)
  578. for (unsigned int i = 0; i<plugin_manager->plugin_list.size(); ++i)
  579. if (plugin_manager->plugin_list[i]->post_load())
  580. return true;
  581. return true;
  582. }
  583. void Viewer::compute_normals()
  584. {
  585. igl::per_face_normals(data.V, data.F, data.F_normals);
  586. igl::per_vertex_normals(data.V, data.F, data.F_normals, data.V_normals);
  587. data.dirty |= DIRTY_NORMAL;
  588. }
  589. void Viewer::uniform_colors(Eigen::Vector3d ambient, Eigen::Vector3d diffuse, Eigen::Vector3d specular)
  590. {
  591. data.V_material_ambient.resize(data.V.rows(),3);
  592. data.V_material_diffuse.resize(data.V.rows(),3);
  593. data.V_material_specular.resize(data.V.rows(),3);
  594. for (unsigned i=0; i<data.V.rows();++i)
  595. {
  596. data.V_material_ambient.row(i) = ambient;
  597. data.V_material_diffuse.row(i) = diffuse;
  598. data.V_material_specular.row(i) = specular;
  599. }
  600. data.F_material_ambient.resize(data.F.rows(),3);
  601. data.F_material_diffuse.resize(data.F.rows(),3);
  602. data.F_material_specular.resize(data.F.rows(),3);
  603. for (unsigned i=0; i<data.F.rows();++i)
  604. {
  605. data.F_material_ambient.row(i) = ambient;
  606. data.F_material_diffuse.row(i) = diffuse;
  607. data.F_material_specular.row(i) = specular;
  608. }
  609. data.dirty |= DIRTY_SPECULAR | DIRTY_DIFFUSE | DIRTY_AMBIENT;
  610. }
  611. void Viewer::grid_texture()
  612. {
  613. if (data.V_uv.rows() == 0)
  614. {
  615. data.V_uv = data.V.block(0, 0, data.V.rows(), 2);
  616. data.V_uv.col(0) = data.V_uv.col(0).array() - data.V_uv.col(0).minCoeff();
  617. data.V_uv.col(0) = data.V_uv.col(0).array() / data.V_uv.col(0).maxCoeff();
  618. data.V_uv.col(1) = data.V_uv.col(1).array() - data.V_uv.col(1).minCoeff();
  619. data.V_uv.col(1) = data.V_uv.col(1).array() / data.V_uv.col(1).maxCoeff();
  620. data.V_uv = data.V_uv.array() * 10;
  621. data.dirty |= DIRTY_TEXTURE;
  622. }
  623. unsigned size = 128;
  624. unsigned size2 = size/2;
  625. data.texture_R.resize(size, size);
  626. for (unsigned i=0; i<size; ++i)
  627. {
  628. for (unsigned j=0; j<size; ++j)
  629. {
  630. data.texture_R(i,j) = 0;
  631. if ((i<size2 && j<size2) || (i>=size2 && j>=size2))
  632. data.texture_R(i,j) = 255;
  633. }
  634. }
  635. data.texture_G = data.texture_R;
  636. data.texture_B = data.texture_R;
  637. data.dirty |= DIRTY_TEXTURE;
  638. }
  639. bool Viewer::save_mesh_to_file(const char* mesh_file_name)
  640. {
  641. std::string mesh_file_name_string(mesh_file_name);
  642. // first try to load it with a plugin
  643. if (plugin_manager)
  644. for (unsigned int i = 0; i<plugin_manager->plugin_list.size(); ++i)
  645. if (plugin_manager->plugin_list[i]->save(mesh_file_name_string))
  646. return true;
  647. size_t last_dot = mesh_file_name_string.rfind('.');
  648. if (last_dot == std::string::npos)
  649. {
  650. // No file type determined
  651. printf("Error: No file extension found in %s\n",mesh_file_name);
  652. return false;
  653. }
  654. std::string extension = mesh_file_name_string.substr(last_dot+1);
  655. if (extension == "off" || extension =="OFF")
  656. {
  657. return igl::writeOFF(mesh_file_name_string,data.V,data.F);
  658. }
  659. else if (extension == "obj" || extension =="OBJ")
  660. {
  661. Eigen::MatrixXd corner_normals;
  662. Eigen::MatrixXi fNormIndices;
  663. Eigen::MatrixXd UV_V;
  664. Eigen::MatrixXi UV_F;
  665. return igl::writeOBJ(mesh_file_name_string, data.V,
  666. data.F, corner_normals, fNormIndices, UV_V, UV_F);
  667. }
  668. else
  669. {
  670. // unrecognized file type
  671. printf("Error: %s is not a recognized file type.\n",extension.c_str());
  672. return false;
  673. }
  674. return true;
  675. }
  676. void Viewer::clear_mesh()
  677. {
  678. data.V = Eigen::MatrixXd (0,3);
  679. data.F = Eigen::MatrixXi (0,3);
  680. data.F_material_ambient = Eigen::MatrixXd (0,3);
  681. data.F_material_diffuse = Eigen::MatrixXd (0,3);
  682. data.F_material_specular = Eigen::MatrixXd (0,3);
  683. data.V_material_ambient = Eigen::MatrixXd (0,3);
  684. data.V_material_diffuse = Eigen::MatrixXd (0,3);
  685. data.V_material_specular = Eigen::MatrixXd (0,3);
  686. data.F_normals = Eigen::MatrixXd (0,3);
  687. data.V_normals = Eigen::MatrixXd (0,3);
  688. data.V_uv = Eigen::MatrixXd (0,2);
  689. data.F_uv = Eigen::MatrixXi (0,3);
  690. data.lines = Eigen::MatrixXd (0,9);
  691. data.points = Eigen::MatrixXd (0,6);
  692. data.labels_positions = Eigen::MatrixXd (0,3);
  693. data.labels_strings.clear();
  694. }
  695. bool Viewer::key_down(unsigned char key, int modifiers)
  696. {
  697. if (callback_key_down)
  698. if (callback_key_down(*this,key,modifiers))
  699. return true;
  700. if (plugin_manager)
  701. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  702. if (plugin_manager->plugin_list[i]->key_down(key, modifiers))
  703. return true;
  704. if (key == 'S')
  705. mouse_scroll(1);
  706. if (key == 'A')
  707. mouse_scroll(-1);
  708. // Why aren't these handled view AntTweakBar?
  709. if (key == 'z') // Don't use 'Z' because that clobbers snap_to_canonical_view_quat
  710. options.trackball_angle << 0.0f, 0.0f, 0.0f, 1.0f;
  711. if (key == 'y')
  712. options.trackball_angle << -sqrt(2.0f)/2.0f, 0.0f, 0.0f, sqrt(2.0f)/2.0f;
  713. if (key == 'x')
  714. options.trackball_angle << -0.5f, -0.5f, -0.5f, 0.5f;
  715. return false;
  716. }
  717. bool Viewer::key_up(unsigned char key, int modifiers)
  718. {
  719. if (callback_key_up)
  720. if (callback_key_up(*this,key,modifiers))
  721. return true;
  722. if (plugin_manager)
  723. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  724. if (plugin_manager->plugin_list[i]->key_up(key, modifiers))
  725. return true;
  726. return false;
  727. }
  728. bool Viewer::mouse_down(MouseButton button, int modifier)
  729. {
  730. if (callback_mouse_down)
  731. if (callback_mouse_down(*this,button,modifier))
  732. return true;
  733. if (plugin_manager)
  734. for (unsigned int i = 0; i < plugin_manager->plugin_list.size(); ++i)
  735. if (plugin_manager->plugin_list[i]->mouse_down(button,modifier))
  736. return true;
  737. down = true;
  738. down_mouse_x = current_mouse_x;
  739. down_mouse_y = current_mouse_y;
  740. down_translation = options.model_translation;
  741. // Initialization code for the trackball
  742. Eigen::RowVector3d center;
  743. if (data.V.rows() == 0)
  744. center << 0,0,0;
  745. else
  746. center = data.V.colwise().sum()/data.V.rows();
  747. Eigen::Vector3f coord = project(Eigen::Vector3f(center(0),center(1),center(2)), view * model, proj, viewport);
  748. down_mouse_z = coord[2];
  749. down_rotation = options.trackball_angle;
  750. mouse_mode = ROTATION;
  751. switch (button)
  752. {
  753. case IGL_LEFT:
  754. mouse_mode = ROTATION;
  755. break;
  756. case IGL_RIGHT:
  757. mouse_mode = TRANSLATE;
  758. break;
  759. default:
  760. mouse_mode = NOTHING;
  761. break;
  762. }
  763. return true;
  764. }
  765. bool Viewer::mouse_up(MouseButton button, int modifier)
  766. {
  767. down = false;
  768. if (callback_mouse_up)
  769. if (callback_mouse_up(*this,button,modifier))
  770. return true;
  771. if (plugin_manager)
  772. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  773. if (plugin_manager->plugin_list[i]->mouse_up(button,modifier))
  774. return true;
  775. mouse_mode = NOTHING;
  776. return true;
  777. }
  778. bool Viewer::mouse_move(int mouse_x, int mouse_y)
  779. {
  780. if(hack_never_moved)
  781. {
  782. down_mouse_x = mouse_x;
  783. down_mouse_y = mouse_y;
  784. hack_never_moved = false;
  785. }
  786. current_mouse_x = mouse_x;
  787. current_mouse_y = mouse_y;
  788. if (callback_mouse_move)
  789. if (callback_mouse_move(*this,mouse_x,mouse_y))
  790. return true;
  791. if (plugin_manager)
  792. for (unsigned int i = 0; i < plugin_manager->plugin_list.size(); ++i)
  793. if (plugin_manager->plugin_list[i]->mouse_move(mouse_x, mouse_y))
  794. return true;
  795. if (down)
  796. {
  797. switch (mouse_mode)
  798. {
  799. case ROTATION :
  800. {
  801. igl::trackball(width,
  802. height,
  803. 2.0f,
  804. down_rotation.data(),
  805. down_mouse_x,
  806. down_mouse_y,
  807. mouse_x,
  808. mouse_y,
  809. options.trackball_angle.data());
  810. //Eigen::Vector4f snapq = options.trackball_angle;
  811. break;
  812. }
  813. case TRANSLATE:
  814. {
  815. //translation
  816. Eigen::Vector3f pos1 = igl::unproject(Eigen::Vector3f(mouse_x, viewport[3] - mouse_y, down_mouse_z), view * model, proj, viewport);
  817. Eigen::Vector3f pos0 = igl::unproject(Eigen::Vector3f(down_mouse_x, viewport[3] - down_mouse_y, down_mouse_z), view * model, proj, viewport);
  818. Eigen::Vector3f diff = pos1 - pos0;
  819. options.model_translation = down_translation + Eigen::Vector3f(diff[0],diff[1],diff[2]);
  820. break;
  821. }
  822. case ZOOM:
  823. {
  824. //float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  825. float delta = 0.001f * (mouse_x - down_mouse_x + mouse_y - down_mouse_y);
  826. options.camera_zoom *= 1 + delta;
  827. down_mouse_x = mouse_x;
  828. down_mouse_y = mouse_y;
  829. break;
  830. }
  831. default:
  832. break;
  833. }
  834. }
  835. return true;
  836. }
  837. bool Viewer::mouse_scroll(float delta_y)
  838. {
  839. scroll_position += delta_y;
  840. if (callback_mouse_scroll)
  841. if (callback_mouse_scroll(*this,delta_y))
  842. return true;
  843. if (plugin_manager)
  844. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  845. if (plugin_manager->plugin_list[i]->mouse_scroll(delta_y))
  846. return true;
  847. // Only zoom if there's actually a change
  848. if(delta_y != 0)
  849. {
  850. float mult = (1.0+((delta_y>0)?1.:-1.)*0.05);
  851. const float min_zoom = 0.1f;
  852. options.camera_zoom = (options.camera_zoom * mult > min_zoom ? options.camera_zoom * mult : min_zoom);
  853. }
  854. return true;
  855. }
  856. static GLuint create_shader_helper(GLint type, const std::string &shader_string)
  857. {
  858. using namespace std;
  859. if (shader_string.empty())
  860. return (GLuint) 0;
  861. GLuint id = glCreateShader(type);
  862. const char *shader_string_const = shader_string.c_str();
  863. glShaderSource(id, 1, &shader_string_const, NULL);
  864. glCompileShader(id);
  865. GLint status;
  866. glGetShaderiv(id, GL_COMPILE_STATUS, &status);
  867. if (status != GL_TRUE)
  868. {
  869. char buffer[512];
  870. if (type == GL_VERTEX_SHADER)
  871. cerr << "Vertex shader:" << endl;
  872. else if (type == GL_FRAGMENT_SHADER)
  873. cerr << "Fragment shader:" << endl;
  874. else if (type == GL_GEOMETRY_SHADER)
  875. cerr << "Geometry shader:" << endl;
  876. cerr << shader_string << endl << endl;
  877. glGetShaderInfoLog(id, 512, NULL, buffer);
  878. cerr << "Error: " << endl << buffer << endl;
  879. return (GLuint) 0;
  880. }
  881. return id;
  882. }
  883. bool Viewer::OpenGL_shader::init_from_files(
  884. const std::string &vertex_shader_filename,
  885. const std::string &fragment_shader_filename,
  886. const std::string &fragment_data_name,
  887. const std::string &geometry_shader_filename,
  888. int geometry_shader_max_vertices)
  889. {
  890. auto file_to_string = [](const std::string &filename)
  891. {
  892. std::ifstream t(filename);
  893. return std::string((std::istreambuf_iterator<char>(t)),
  894. std::istreambuf_iterator<char>());
  895. };
  896. return init(
  897. file_to_string(vertex_shader_filename),
  898. file_to_string(fragment_shader_filename),
  899. fragment_data_name,
  900. file_to_string(geometry_shader_filename),
  901. geometry_shader_max_vertices
  902. );
  903. }
  904. bool Viewer::OpenGL_shader::init(
  905. const std::string &vertex_shader_string,
  906. const std::string &fragment_shader_string,
  907. const std::string &fragment_data_name,
  908. const std::string &geometry_shader_string,
  909. int geometry_shader_max_vertices)
  910. {
  911. using namespace std;
  912. vertex_shader = create_shader_helper(GL_VERTEX_SHADER, vertex_shader_string);
  913. geometry_shader = create_shader_helper(GL_GEOMETRY_SHADER, geometry_shader_string);
  914. fragment_shader = create_shader_helper(GL_FRAGMENT_SHADER, fragment_shader_string);
  915. if (!vertex_shader || !fragment_shader)
  916. return false;
  917. program_shader = glCreateProgram();
  918. glAttachShader(program_shader, vertex_shader);
  919. glAttachShader(program_shader, fragment_shader);
  920. if (geometry_shader)
  921. {
  922. glAttachShader(program_shader, geometry_shader);
  923. /* This covers only basic cases and may need to be modified */
  924. glProgramParameteri(program_shader, GL_GEOMETRY_INPUT_TYPE, GL_TRIANGLES);
  925. glProgramParameteri(program_shader, GL_GEOMETRY_OUTPUT_TYPE, GL_TRIANGLES);
  926. glProgramParameteri(program_shader, GL_GEOMETRY_VERTICES_OUT, geometry_shader_max_vertices);
  927. }
  928. glBindFragDataLocation(program_shader, 0, fragment_data_name.c_str());
  929. glLinkProgram(program_shader);
  930. GLint status;
  931. glGetProgramiv(program_shader, GL_LINK_STATUS, &status);
  932. if (status != GL_TRUE)
  933. {
  934. char buffer[512];
  935. glGetProgramInfoLog(program_shader, 512, NULL, buffer);
  936. cerr << "Linker error: " << endl << buffer << endl;
  937. program_shader = 0;
  938. return false;
  939. }
  940. return true;
  941. }
  942. void Viewer::OpenGL_shader::bind()
  943. {
  944. glUseProgram(program_shader);
  945. }
  946. GLint Viewer::OpenGL_shader::attrib(const std::string &name) const
  947. {
  948. return glGetAttribLocation(program_shader, name.c_str());
  949. }
  950. GLint Viewer::OpenGL_shader::uniform(const std::string &name) const
  951. {
  952. return glGetUniformLocation(program_shader, name.c_str());
  953. }
  954. GLint Viewer::OpenGL_shader::bindVertexAttribArray(
  955. const std::string &name, GLuint bufferID, const Eigen::MatrixXf &M, bool refresh) const
  956. {
  957. GLint id = attrib(name);
  958. if (id < 0)
  959. return id;
  960. if (M.size() == 0)
  961. {
  962. glDisableVertexAttribArray(id);
  963. return id;
  964. }
  965. glBindBuffer(GL_ARRAY_BUFFER, bufferID);
  966. if (refresh)
  967. glBufferData(GL_ARRAY_BUFFER, sizeof(float)*M.size(), M.data(), GL_DYNAMIC_DRAW);
  968. glVertexAttribPointer(id, M.rows(), GL_FLOAT, GL_FALSE, 0, 0);
  969. glEnableVertexAttribArray(id);
  970. return id;
  971. }
  972. void Viewer::OpenGL_shader::free()
  973. {
  974. if (program_shader)
  975. {
  976. glDeleteProgram(program_shader);
  977. program_shader = 0;
  978. }
  979. if (vertex_shader)
  980. {
  981. glDeleteShader(vertex_shader);
  982. vertex_shader = 0;
  983. }
  984. if (fragment_shader)
  985. {
  986. glDeleteShader(fragment_shader);
  987. fragment_shader = 0;
  988. }
  989. if (geometry_shader)
  990. {
  991. glDeleteShader(geometry_shader);
  992. geometry_shader = 0;
  993. }
  994. }
  995. void Viewer::OpenGL_state::init()
  996. {
  997. // Mesh: Vertex Array Object & Buffer objects
  998. glGenVertexArrays(1, &vao_mesh);
  999. glBindVertexArray(vao_mesh);
  1000. glGenBuffers(1, &vbo_V);
  1001. glGenBuffers(1, &vbo_V_normals);
  1002. glGenBuffers(1, &vbo_V_ambient);
  1003. glGenBuffers(1, &vbo_V_diffuse);
  1004. glGenBuffers(1, &vbo_V_specular);
  1005. glGenBuffers(1, &vbo_V_uv);
  1006. glGenBuffers(1, &vbo_F);
  1007. glGenTextures(1, &vbo_tex);
  1008. // Line overlay
  1009. glGenVertexArrays(1, &vao_overlay_lines);
  1010. glBindVertexArray(vao_overlay_lines);
  1011. glGenBuffers(1, &vbo_lines_F);
  1012. glGenBuffers(1, &vbo_lines_V);
  1013. glGenBuffers(1, &vbo_lines_V_colors);
  1014. // Point overlay
  1015. glGenVertexArrays(1, &vao_overlay_points);
  1016. glBindVertexArray(vao_overlay_points);
  1017. glGenBuffers(1, &vbo_points_F);
  1018. glGenBuffers(1, &vbo_points_V);
  1019. glGenBuffers(1, &vbo_points_V_colors);
  1020. dirty = DIRTY_ALL;
  1021. }
  1022. void Viewer::OpenGL_state::free()
  1023. {
  1024. glDeleteVertexArrays(1, &vao_mesh);
  1025. glDeleteVertexArrays(1, &vao_overlay_lines);
  1026. glDeleteVertexArrays(1, &vao_overlay_points);
  1027. glDeleteBuffers(1, &vbo_V);
  1028. glDeleteBuffers(1, &vbo_V_normals);
  1029. glDeleteBuffers(1, &vbo_V_ambient);
  1030. glDeleteBuffers(1, &vbo_V_diffuse);
  1031. glDeleteBuffers(1, &vbo_V_specular);
  1032. glDeleteBuffers(1, &vbo_V_uv);
  1033. glDeleteBuffers(1, &vbo_F);
  1034. glDeleteBuffers(1, &vbo_lines_F);
  1035. glDeleteBuffers(1, &vbo_lines_V);
  1036. glDeleteBuffers(1, &vbo_lines_V_colors);
  1037. glDeleteBuffers(1, &vbo_points_F);
  1038. glDeleteBuffers(1, &vbo_points_V);
  1039. glDeleteBuffers(1, &vbo_points_V_colors);
  1040. glDeleteTextures(1, &vbo_tex);
  1041. }
  1042. void Viewer::OpenGL_state::set_data(const Data &data, bool face_based, bool invert_normals)
  1043. {
  1044. bool per_corner_uv = (data.F_uv.rows() == data.F.rows());
  1045. bool per_corner_normals = (data.F_normals.rows() == 3 * data.F.rows());
  1046. dirty |= data.dirty;
  1047. if (!face_based)
  1048. {
  1049. if (!per_corner_uv)
  1050. {
  1051. // Vertex positions
  1052. if (dirty & DIRTY_POSITION)
  1053. V_vbo = (data.V.transpose()).cast<float>();
  1054. // Vertex normals
  1055. if (dirty & DIRTY_NORMAL)
  1056. {
  1057. V_normals_vbo = (data.V_normals.transpose()).cast<float>();
  1058. if (invert_normals)
  1059. V_normals_vbo = -V_normals_vbo;
  1060. }
  1061. // Per-vertex material settings
  1062. if (dirty & DIRTY_AMBIENT)
  1063. V_ambient_vbo = (data.V_material_ambient.transpose()).cast<float>();
  1064. if (dirty & DIRTY_DIFFUSE)
  1065. V_diffuse_vbo = (data.V_material_diffuse.transpose()).cast<float>();
  1066. if (dirty & DIRTY_SPECULAR)
  1067. V_specular_vbo = (data.V_material_specular.transpose()).cast<float>();
  1068. // Face indices
  1069. if (dirty & DIRTY_FACE)
  1070. F_vbo = (data.F.transpose()).cast<unsigned>();
  1071. // Texture coordinates
  1072. if (dirty & DIRTY_UV)
  1073. V_uv_vbo = (data.V_uv.transpose()).cast<float>();
  1074. }
  1075. else
  1076. {
  1077. // Per vertex properties with per corner UVs
  1078. if (dirty & DIRTY_POSITION)
  1079. {
  1080. V_vbo.resize(3,data.F.rows()*3);
  1081. for (unsigned i=0; i<data.F.rows();++i)
  1082. for (unsigned j=0;j<3;++j)
  1083. V_vbo.col(i*3+j) = data.V.row(data.F(i,j)).transpose().cast<float>();
  1084. }
  1085. if (dirty & DIRTY_AMBIENT)
  1086. {
  1087. V_ambient_vbo.resize(3,data.F.rows()*3);
  1088. for (unsigned i=0; i<data.F.rows();++i)
  1089. for (unsigned j=0;j<3;++j)
  1090. V_ambient_vbo.col (i*3+j) = data.V_material_ambient.row(data.F(i,j)).transpose().cast<float>();
  1091. }
  1092. if (dirty & DIRTY_DIFFUSE)
  1093. {
  1094. V_diffuse_vbo.resize(3,data.F.rows()*3);
  1095. for (unsigned i=0; i<data.F.rows();++i)
  1096. for (unsigned j=0;j<3;++j)
  1097. V_diffuse_vbo.col (i*3+j) = data.V_material_diffuse.row(data.F(i,j)).transpose().cast<float>();
  1098. }
  1099. if (dirty & DIRTY_SPECULAR)
  1100. {
  1101. V_specular_vbo.resize(3,data.F.rows()*3);
  1102. for (unsigned i=0; i<data.F.rows();++i)
  1103. for (unsigned j=0;j<3;++j)
  1104. V_specular_vbo.col(i*3+j) = data.V_material_specular.row(data.F(i,j)).transpose().cast<float>();
  1105. }
  1106. if (dirty & DIRTY_NORMAL)
  1107. {
  1108. V_normals_vbo.resize(3,data.F.rows()*3);
  1109. for (unsigned i=0; i<data.F.rows();++i)
  1110. for (unsigned j=0;j<3;++j)
  1111. V_normals_vbo.col (i*3+j) = data.V_normals.row(data.F(i,j)).transpose().cast<float>();
  1112. if (invert_normals)
  1113. V_normals_vbo = -V_normals_vbo;
  1114. }
  1115. if (dirty & DIRTY_FACE)
  1116. {
  1117. F_vbo.resize(3,data.F.rows());
  1118. for (unsigned i=0; i<data.F.rows();++i)
  1119. F_vbo.col(i) << i*3+0, i*3+1, i*3+2;
  1120. }
  1121. if (dirty & DIRTY_UV)
  1122. {
  1123. V_uv_vbo.resize(2,data.F.rows()*3);
  1124. for (unsigned i=0; i<data.F.rows();++i)
  1125. for (unsigned j=0;j<3;++j)
  1126. V_uv_vbo.col(i*3+j) = data.V_uv.row(data.F(i,j)).transpose().cast<float>();
  1127. }
  1128. }
  1129. }
  1130. else
  1131. {
  1132. if (dirty & DIRTY_POSITION)
  1133. {
  1134. V_vbo.resize(3,data.F.rows()*3);
  1135. for (unsigned i=0; i<data.F.rows();++i)
  1136. for (unsigned j=0;j<3;++j)
  1137. V_vbo.col(i*3+j) = data.V.row(data.F(i,j)).transpose().cast<float>();
  1138. }
  1139. if (dirty & DIRTY_AMBIENT)
  1140. {
  1141. V_ambient_vbo.resize(3,data.F.rows()*3);
  1142. for (unsigned i=0; i<data.F.rows();++i)
  1143. for (unsigned j=0;j<3;++j)
  1144. V_ambient_vbo.col (i*3+j) = data.F_material_ambient.row(i).transpose().cast<float>();
  1145. }
  1146. if (dirty & DIRTY_DIFFUSE)
  1147. {
  1148. V_diffuse_vbo.resize(3,data.F.rows()*3);
  1149. for (unsigned i=0; i<data.F.rows();++i)
  1150. for (unsigned j=0;j<3;++j)
  1151. V_diffuse_vbo.col (i*3+j) = data.F_material_diffuse.row(i).transpose().cast<float>();
  1152. }
  1153. if (dirty & DIRTY_SPECULAR)
  1154. {
  1155. V_specular_vbo.resize(3,data.F.rows()*3);
  1156. for (unsigned i=0; i<data.F.rows();++i)
  1157. for (unsigned j=0;j<3;++j)
  1158. V_specular_vbo.col(i*3+j) = data.F_material_specular.row(i).transpose().cast<float>();
  1159. }
  1160. if (dirty & DIRTY_NORMAL)
  1161. {
  1162. V_normals_vbo.resize(3,data.F.rows()*3);
  1163. for (unsigned i=0; i<data.F.rows();++i)
  1164. for (unsigned j=0;j<3;++j)
  1165. V_normals_vbo.col (i*3+j) =
  1166. per_corner_normals ?
  1167. data.F_normals.row(i*3+j).transpose().cast<float>() :
  1168. data.F_normals.row(i).transpose().cast<float>();
  1169. if (invert_normals)
  1170. V_normals_vbo = -V_normals_vbo;
  1171. }
  1172. if (dirty & DIRTY_FACE)
  1173. {
  1174. F_vbo.resize(3,data.F.rows());
  1175. for (unsigned i=0; i<data.F.rows();++i)
  1176. F_vbo.col(i) << i*3+0, i*3+1, i*3+2;
  1177. }
  1178. if (dirty & DIRTY_UV)
  1179. {
  1180. V_uv_vbo.resize(2,data.F.rows()*3);
  1181. for (unsigned i=0; i<data.F.rows();++i)
  1182. for (unsigned j=0;j<3;++j)
  1183. V_uv_vbo.col(i*3+j) = data.V_uv.row(per_corner_uv ? data.F_uv(i,j) : data.F(i,j)).transpose().cast<float>();
  1184. }
  1185. }
  1186. if (dirty & DIRTY_TEXTURE)
  1187. {
  1188. tex_u = data.texture_R.rows();
  1189. tex_v = data.texture_R.cols();
  1190. tex.resize(data.texture_R.size()*3);
  1191. for (unsigned i=0;i<data.texture_R.size();++i)
  1192. {
  1193. tex(i*3+0) = data.texture_R(i);
  1194. tex(i*3+1) = data.texture_G(i);
  1195. tex(i*3+2) = data.texture_B(i);
  1196. }
  1197. }
  1198. if (dirty & DIRTY_OVERLAY_LINES)
  1199. {
  1200. lines_V_vbo.resize(3, data.lines.rows()*2);
  1201. lines_V_colors_vbo.resize(3, data.lines.rows()*2);
  1202. lines_F_vbo.resize(1, data.lines.rows()*2);
  1203. for (unsigned i=0; i<data.lines.rows();++i)
  1204. {
  1205. lines_V_vbo.col(2*i+0) = data.lines.block<1, 3>(i, 0).transpose().cast<float>();
  1206. lines_V_vbo.col(2*i+1) = data.lines.block<1, 3>(i, 3).transpose().cast<float>();
  1207. lines_V_colors_vbo.col(2*i+0) = data.lines.block<1, 3>(i, 6).transpose().cast<float>();
  1208. lines_V_colors_vbo.col(2*i+1) = data.lines.block<1, 3>(i, 6).transpose().cast<float>();
  1209. lines_F_vbo(2*i+0) = 2*i+0;
  1210. lines_F_vbo(2*i+1) = 2*i+1;
  1211. }
  1212. }
  1213. if (dirty & DIRTY_OVERLAY_POINTS)
  1214. {
  1215. points_V_vbo.resize(3, data.points.rows());
  1216. points_V_colors_vbo.resize(3, data.points.rows());
  1217. points_F_vbo.resize(1, data.points.rows());
  1218. for (unsigned i=0; i<data.points.rows();++i)
  1219. {
  1220. points_V_vbo.col(i) = data.points.block<1, 3>(i, 0).transpose().cast<float>();
  1221. points_V_colors_vbo.col(i) = data.points.block<1, 3>(i, 3).transpose().cast<float>();
  1222. points_F_vbo(i) = i;
  1223. }
  1224. }
  1225. }
  1226. void Viewer::OpenGL_state::bind_mesh()
  1227. {
  1228. glBindVertexArray(vao_mesh);
  1229. shader_mesh.bind();
  1230. shader_mesh.bindVertexAttribArray("position", vbo_V, V_vbo, dirty & DIRTY_POSITION);
  1231. shader_mesh.bindVertexAttribArray("normal", vbo_V_normals, V_normals_vbo, dirty & DIRTY_NORMAL);
  1232. shader_mesh.bindVertexAttribArray("Ka", vbo_V_ambient, V_ambient_vbo, dirty & DIRTY_AMBIENT);
  1233. shader_mesh.bindVertexAttribArray("Kd", vbo_V_diffuse, V_diffuse_vbo, dirty & DIRTY_DIFFUSE);
  1234. shader_mesh.bindVertexAttribArray("Ks", vbo_V_specular, V_specular_vbo, dirty & DIRTY_SPECULAR);
  1235. shader_mesh.bindVertexAttribArray("texcoord", vbo_V_uv, V_uv_vbo, dirty & DIRTY_UV);
  1236. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_F);
  1237. if (dirty & DIRTY_FACE)
  1238. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*F_vbo.size(), F_vbo.data(), GL_DYNAMIC_DRAW);
  1239. glActiveTexture(GL_TEXTURE0);
  1240. glBindTexture(GL_TEXTURE_2D, vbo_tex);
  1241. if (dirty & DIRTY_TEXTURE)
  1242. {
  1243. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  1244. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  1245. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1246. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1247. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_u, tex_v, 0, GL_RGB, GL_UNSIGNED_BYTE, tex.data());
  1248. }
  1249. glUniform1i(shader_mesh.uniform("tex"), 0);
  1250. dirty &= ~DIRTY_MESH;
  1251. }
  1252. void Viewer::OpenGL_state::bind_overlay_lines()
  1253. {
  1254. bool is_dirty = dirty & DIRTY_OVERLAY_LINES;
  1255. glBindVertexArray(vao_overlay_lines);
  1256. shader_overlay_lines.bind();
  1257. shader_overlay_lines.bindVertexAttribArray("position", vbo_lines_V, lines_V_vbo, is_dirty);
  1258. shader_overlay_lines.bindVertexAttribArray("color", vbo_lines_V_colors, lines_V_colors_vbo, is_dirty);
  1259. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_lines_F);
  1260. if (is_dirty)
  1261. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*lines_F_vbo.size(), lines_F_vbo.data(), GL_DYNAMIC_DRAW);
  1262. dirty &= ~DIRTY_OVERLAY_LINES;
  1263. }
  1264. void Viewer::OpenGL_state::bind_overlay_points()
  1265. {
  1266. bool is_dirty = dirty & DIRTY_OVERLAY_POINTS;
  1267. glBindVertexArray(vao_overlay_points);
  1268. shader_overlay_points.bind();
  1269. shader_overlay_points.bindVertexAttribArray("position", vbo_points_V, points_V_vbo, is_dirty);
  1270. shader_overlay_points.bindVertexAttribArray("color", vbo_points_V_colors, points_V_colors_vbo, is_dirty);
  1271. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_points_F);
  1272. if (is_dirty)
  1273. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned)*points_F_vbo.size(), points_F_vbo.data(), GL_DYNAMIC_DRAW);
  1274. dirty &= ~DIRTY_OVERLAY_POINTS;
  1275. }
  1276. void Viewer::OpenGL_state::draw_mesh(bool solid)
  1277. {
  1278. glPolygonMode(GL_FRONT_AND_BACK, solid ? GL_FILL : GL_LINE);
  1279. /* Avoid Z-buffer fighting between filled triangles & wireframe lines */
  1280. if (solid)
  1281. {
  1282. glEnable(GL_POLYGON_OFFSET_FILL);
  1283. glPolygonOffset(1.0, 1.0);
  1284. }
  1285. glDrawElements(GL_TRIANGLES, 3*F_vbo.cols(), GL_UNSIGNED_INT, 0);
  1286. glDisable(GL_POLYGON_OFFSET_FILL);
  1287. glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  1288. }
  1289. void Viewer::OpenGL_state::draw_overlay_lines()
  1290. {
  1291. glDrawElements(GL_LINES, lines_F_vbo.cols(), GL_UNSIGNED_INT, 0);
  1292. }
  1293. void Viewer::OpenGL_state::draw_overlay_points()
  1294. {
  1295. glDrawElements(GL_POINTS, points_F_vbo.cols(), GL_UNSIGNED_INT, 0);
  1296. }
  1297. void Viewer::init_opengl()
  1298. {
  1299. std::string mesh_vertex_shader_string =
  1300. "#version 150\n"
  1301. "uniform mat4 model;"
  1302. "uniform mat4 view;"
  1303. "uniform mat4 proj;"
  1304. "in vec3 position;"
  1305. "in vec3 normal;"
  1306. "out vec3 position_eye;"
  1307. "out vec3 normal_eye;"
  1308. "in vec3 Ka;"
  1309. "in vec3 Kd;"
  1310. "in vec3 Ks;"
  1311. "in vec2 texcoord;"
  1312. "out vec2 texcoordi;"
  1313. "out vec3 Kai;"
  1314. "out vec3 Kdi;"
  1315. "out vec3 Ksi;"
  1316. "void main()"
  1317. "{"
  1318. " position_eye = vec3 (view * model * vec4 (position, 1.0));"
  1319. " normal_eye = vec3 (view * model * vec4 (normal, 0.0));"
  1320. " normal_eye = normalize(normal_eye);"
  1321. " gl_Position = proj * vec4 (position_eye, 1.0);" //proj * view * model * vec4(position, 1.0);"
  1322. " Kai = Ka;"
  1323. " Kdi = Kd;"
  1324. " Ksi = Ks;"
  1325. " texcoordi = texcoord;"
  1326. "}";
  1327. std::string mesh_fragment_shader_string =
  1328. "#version 150\n"
  1329. "uniform mat4 model;"
  1330. "uniform mat4 view;"
  1331. "uniform mat4 proj;"
  1332. "uniform vec4 fixed_color;"
  1333. "in vec3 position_eye;"
  1334. "in vec3 normal_eye;"
  1335. "uniform vec3 light_position_world;"
  1336. "vec3 Ls = vec3 (1, 1, 1);"
  1337. "vec3 Ld = vec3 (1, 1, 1);"
  1338. "vec3 La = vec3 (1, 1, 1);"
  1339. "in vec3 Ksi;"
  1340. "in vec3 Kdi;"
  1341. "in vec3 Kai;"
  1342. "in vec2 texcoordi;"
  1343. "uniform sampler2D tex;"
  1344. "uniform float specular_exponent;"
  1345. "uniform float lighting_factor;"
  1346. "uniform float texture_factor;"
  1347. "out vec4 outColor;"
  1348. "void main()"
  1349. "{"
  1350. "vec3 Ia = La * Kai;" // ambient intensity
  1351. "vec3 light_position_eye = vec3 (view * vec4 (light_position_world, 1.0));"
  1352. "vec3 distance_to_light_eye = light_position_eye - position_eye;"
  1353. "vec3 direction_to_light_eye = normalize (distance_to_light_eye);"
  1354. "float dot_prod = dot (direction_to_light_eye, normal_eye);"
  1355. "dot_prod = max (dot_prod, 0.0);"
  1356. "vec3 Id = Ld * Kdi * dot_prod;" // Diffuse intensity
  1357. "vec3 reflection_eye = reflect (-direction_to_light_eye, normal_eye);"
  1358. "vec3 surface_to_viewer_eye = normalize (-position_eye);"
  1359. "float dot_prod_specular = dot (reflection_eye, surface_to_viewer_eye);"
  1360. "dot_prod_specular = max (dot_prod_specular, 0.0);"
  1361. "float specular_factor = pow (dot_prod_specular, specular_exponent);"
  1362. "vec3 Is = Ls * Ksi * specular_factor;" // specular intensity
  1363. "vec4 color = vec4(lighting_factor * (Is + Id) + Ia, 1.0) + vec4((1.0-lighting_factor) * Kdi,1.0);"
  1364. "outColor = mix(vec4(1,1,1,1), texture(tex, texcoordi), texture_factor) * color;"
  1365. "if (fixed_color != vec4(0.0)) outColor = fixed_color;"
  1366. "}";
  1367. std::string overlay_vertex_shader_string =
  1368. "#version 150\n"
  1369. "uniform mat4 model;"
  1370. "uniform mat4 view;"
  1371. "uniform mat4 proj;"
  1372. "in vec3 position;"
  1373. "in vec3 color;"
  1374. "out vec3 color_frag;"
  1375. "void main()"
  1376. "{"
  1377. " gl_Position = proj * view * model * vec4 (position, 1.0);"
  1378. " color_frag = color;"
  1379. "}";
  1380. std::string overlay_fragment_shader_string =
  1381. "#version 150\n"
  1382. "in vec3 color_frag;"
  1383. "out vec4 outColor;"
  1384. "void main()"
  1385. "{"
  1386. " outColor = vec4(color_frag, 1.0);"
  1387. "}";
  1388. std::string overlay_point_fragment_shader_string =
  1389. "#version 150\n"
  1390. "in vec3 color_frag;"
  1391. "out vec4 outColor;"
  1392. "void main()"
  1393. "{"
  1394. " if (length(gl_PointCoord - vec2(0.5)) > 0.5)"
  1395. " discard;"
  1396. " outColor = vec4(color_frag, 1.0);"
  1397. "}";
  1398. opengl.init();
  1399. opengl.shader_mesh.init(mesh_vertex_shader_string,
  1400. mesh_fragment_shader_string, "outColor");
  1401. opengl.shader_overlay_lines.init(overlay_vertex_shader_string,
  1402. overlay_fragment_shader_string, "outColor");
  1403. opengl.shader_overlay_points.init(overlay_vertex_shader_string,
  1404. overlay_point_fragment_shader_string, "outColor");
  1405. }
  1406. void Viewer::free_opengl()
  1407. {
  1408. opengl.shader_mesh.free();
  1409. opengl.shader_overlay_lines.free();
  1410. opengl.shader_overlay_points.free();
  1411. opengl.free();
  1412. __font_renderer.Shut();
  1413. }
  1414. void Viewer::draw()
  1415. {
  1416. using namespace std;
  1417. using namespace Eigen;
  1418. glClearColor(options.background_color[0],
  1419. options.background_color[1],
  1420. options.background_color[2],
  1421. 1.0f);
  1422. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  1423. glEnable(GL_DEPTH_TEST);
  1424. if (callback_pre_draw)
  1425. if (callback_pre_draw(*this))
  1426. return;
  1427. if (plugin_manager)
  1428. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1429. if (plugin_manager->plugin_list[i]->pre_draw())
  1430. return;
  1431. /* Bind and potentially refresh mesh/line/point data */
  1432. if (data.dirty)
  1433. {
  1434. opengl.set_data(data, options.face_based, options.invert_normals);
  1435. data.dirty = DIRTY_NONE;
  1436. }
  1437. opengl.bind_mesh();
  1438. // Initialize uniform
  1439. glViewport(0, 0, width, height);
  1440. model = Eigen::Matrix4f::Identity();
  1441. view = Eigen::Matrix4f::Identity();
  1442. proj = Eigen::Matrix4f::Identity();
  1443. // Set view
  1444. view = lookAt(Eigen::Vector3f(options.camera_eye[0], options.camera_eye[1], options.camera_eye[2]),
  1445. Eigen::Vector3f(options.camera_center[0], options.camera_center[1], options.camera_center[2]),
  1446. Eigen::Vector3f(options.camera_up[0], options.camera_up[1], options.camera_up[2]));
  1447. // Set projection
  1448. if (options.orthographic)
  1449. {
  1450. float length = (options.camera_eye - options.camera_center).norm();
  1451. float h = tan(options.camera_view_angle/360.0 * M_PI) * (length);
  1452. proj = ortho(-h*width/height, h*width/height, -h, h, options.camera_dnear, options.camera_dfar);
  1453. }
  1454. else
  1455. {
  1456. float fH = tan(options.camera_view_angle / 360.0 * M_PI) * options.camera_dnear;
  1457. float fW = fH * (double)width/(double)height;
  1458. proj = frustum(-fW, fW, -fH, fH, options.camera_dnear, options.camera_dfar);
  1459. }
  1460. // end projection
  1461. // Set model transformation
  1462. float mat[16];
  1463. igl::quat_to_mat(options.trackball_angle.data(), mat);
  1464. for (unsigned i=0;i<4;++i)
  1465. for (unsigned j=0;j<4;++j)
  1466. model(i,j) = mat[i+4*j];
  1467. model = scale(model, Eigen::Vector3f(options.camera_zoom,options.camera_zoom,options.camera_zoom));
  1468. model = scale(model, Eigen::Vector3f(options.model_zoom,options.model_zoom,options.model_zoom));
  1469. model = translate(model, Eigen::Vector3f(options.model_translation[0],options.model_translation[1],options.model_translation[2]));
  1470. // Send transformations to the GPU
  1471. GLint modeli = opengl.shader_mesh.uniform("model");
  1472. GLint viewi = opengl.shader_mesh.uniform("view");
  1473. GLint proji = opengl.shader_mesh.uniform("proj");
  1474. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  1475. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  1476. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  1477. // Light parameters
  1478. GLint specular_exponenti = opengl.shader_mesh.uniform("specular_exponent");
  1479. GLint light_position_worldi = opengl.shader_mesh.uniform("light_position_world");
  1480. GLint lighting_factori = opengl.shader_mesh.uniform("lighting_factor");
  1481. GLint fixed_colori = opengl.shader_mesh.uniform("fixed_color");
  1482. GLint texture_factori = opengl.shader_mesh.uniform("texture_factor");
  1483. glUniform1f(specular_exponenti, options.shininess);
  1484. Vector3f rev_light = -1.*options.light_position;
  1485. glUniform3fv(light_position_worldi, 1, rev_light.data());
  1486. glUniform1f(lighting_factori, options.lighting_factor); // enables lighting
  1487. glUniform4f(fixed_colori, 0.0, 0.0, 0.0, 0.0);
  1488. if (data.V.rows()>0)
  1489. {
  1490. // Render fill
  1491. if (options.show_faces)
  1492. {
  1493. // Texture
  1494. glUniform1f(texture_factori, options.show_texture ? 1.0f : 0.0f);
  1495. opengl.draw_mesh(true);
  1496. glUniform1f(texture_factori, 0.0f);
  1497. }
  1498. // Render wireframe
  1499. if (options.show_lines)
  1500. {
  1501. glLineWidth(options.line_width);
  1502. glUniform4f(fixed_colori, options.line_color[0], options.line_color[1],
  1503. options.line_color[2], 1.0f);
  1504. opengl.draw_mesh(false);
  1505. glUniform4f(fixed_colori, 0.0f, 0.0f, 0.0f, 0.0f);
  1506. }
  1507. if (options.show_vertid)
  1508. {
  1509. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  1510. for (int i=0; i<data.V.rows(); ++i)
  1511. __font_renderer.DrawText(data.V.row(i), data.V_normals.row(i), to_string(i));
  1512. __font_renderer.EndDraw();
  1513. }
  1514. if (options.show_faceid)
  1515. {
  1516. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  1517. for (int i=0; i<data.F.rows(); ++i)
  1518. {
  1519. Eigen::RowVector3d p = Eigen::RowVector3d::Zero();
  1520. for (int j=0;j<data.F.cols();++j)
  1521. p += data.V.row(data.F(i,j));
  1522. p /= data.F.cols();
  1523. __font_renderer.DrawText(p, data.F_normals.row(i), to_string(i));
  1524. }
  1525. __font_renderer.EndDraw();
  1526. }
  1527. }
  1528. if (options.show_overlay)
  1529. {
  1530. if (options.show_overlay_depth)
  1531. glEnable(GL_DEPTH_TEST);
  1532. else
  1533. glDisable(GL_DEPTH_TEST);
  1534. if (data.lines.rows() > 0)
  1535. {
  1536. opengl.bind_overlay_lines();
  1537. modeli = opengl.shader_overlay_lines.uniform("model");
  1538. viewi = opengl.shader_overlay_lines.uniform("view");
  1539. proji = opengl.shader_overlay_lines.uniform("proj");
  1540. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  1541. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  1542. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  1543. // This must be enabled, otherwise glLineWidth has no effect
  1544. glEnable(GL_LINE_SMOOTH);
  1545. glLineWidth(options.line_width);
  1546. opengl.draw_overlay_lines();
  1547. }
  1548. if (data.points.rows() > 0)
  1549. {
  1550. opengl.bind_overlay_points();
  1551. modeli = opengl.shader_overlay_points.uniform("model");
  1552. viewi = opengl.shader_overlay_points.uniform("view");
  1553. proji = opengl.shader_overlay_points.uniform("proj");
  1554. glUniformMatrix4fv(modeli, 1, GL_FALSE, model.data());
  1555. glUniformMatrix4fv(viewi, 1, GL_FALSE, view.data());
  1556. glUniformMatrix4fv(proji, 1, GL_FALSE, proj.data());
  1557. glPointSize(options.point_size);
  1558. opengl.draw_overlay_points();
  1559. }
  1560. if (data.labels_positions.rows() > 0)
  1561. {
  1562. __font_renderer.BeginDraw(view*model, proj, viewport, data.object_scale);
  1563. for (int i=0; i<data.labels_positions.rows(); ++i)
  1564. __font_renderer.DrawText(data.labels_positions.row(i), Eigen::Vector3d(0.0,0.0,0.0),
  1565. data.labels_strings[i]);
  1566. __font_renderer.EndDraw();
  1567. }
  1568. glEnable(GL_DEPTH_TEST);
  1569. }
  1570. if (callback_post_draw)
  1571. if (callback_post_draw(*this))
  1572. return;
  1573. if (plugin_manager)
  1574. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1575. if (plugin_manager->plugin_list[i]->post_draw())
  1576. break;
  1577. TwDraw();
  1578. }
  1579. bool Viewer::save_scene()
  1580. {
  1581. #ifdef ENABLE_XML_SERIALIZATION
  1582. string fname = igl::file_dialog_save();
  1583. if (fname.length() == 0)
  1584. return false;
  1585. ::igl::XMLSerializer serializer("Viewer");
  1586. serializer.Add(data,"Data");
  1587. serializer.Add(options,"Options");
  1588. if (plugin_manager)
  1589. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1590. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  1591. serializer.Save(fname.c_str(),true);
  1592. #endif
  1593. return true;
  1594. }
  1595. bool Viewer::load_scene()
  1596. {
  1597. #ifdef ENABLE_XML_SERIALIZATION
  1598. string fname = igl::file_dialog_open();
  1599. if (fname.length() == 0)
  1600. return false;
  1601. ::igl::XMLSerializer serializer("Viewer");
  1602. serializer.Add(data,"Data");
  1603. serializer.Add(options,"Options");
  1604. if (plugin_manager)
  1605. for (unsigned int i = 0; i <plugin_manager->plugin_list.size(); ++i)
  1606. serializer.Add(*(plugin_manager->plugin_list[i]),plugin_manager->plugin_list[i]->plugin_name);
  1607. serializer.Load(fname.c_str());
  1608. #endif
  1609. return true;
  1610. }
  1611. void Viewer::align_camera_center()
  1612. {
  1613. get_scale_and_shift_to_fit_mesh(data.V,data.F,options.model_zoom,options.model_translation);
  1614. data.object_scale = (data.V.colwise().maxCoeff() - data.V.colwise().minCoeff()).norm();
  1615. }
  1616. void Viewer::resize(int w, int h)
  1617. {
  1618. width = w;
  1619. height = h;
  1620. viewport = Eigen::Vector4f(0,0,width,height);
  1621. }
  1622. void Viewer::get_scale_and_shift_to_fit_mesh(
  1623. const Eigen::MatrixXd& V,
  1624. const Eigen::MatrixXi& F,
  1625. float& zoom,
  1626. Eigen::Vector3f& shift)
  1627. {
  1628. if (V.rows() == 0)
  1629. return;
  1630. //Compute mesh centroid
  1631. Eigen::SparseMatrix<double> M;
  1632. igl::massmatrix(V,F,igl::MASSMATRIX_TYPE_VORONOI,M);
  1633. const auto & MV = M*V;
  1634. Eigen::RowVector3d centroid = MV.colwise().sum()/M.diagonal().sum();
  1635. Eigen::RowVector3d min_point = V.colwise().minCoeff();
  1636. Eigen::RowVector3d max_point = V.colwise().maxCoeff();
  1637. shift = -centroid.cast<float>();
  1638. double x_scale = fabs(max_point[0] - min_point[0]);
  1639. double y_scale = fabs(max_point[1] - min_point[1]);
  1640. double z_scale = fabs(max_point[2] - min_point[2]);
  1641. zoom = 2.0/ std::max(z_scale,std::max(x_scale,y_scale));
  1642. }
  1643. void TW_CALL Viewer::snap_to_canonical_quaternion_cb(void *clientData)
  1644. {
  1645. Eigen::Vector4f snapq = static_cast<Viewer *>(clientData)->options.trackball_angle;
  1646. igl::snap_to_canonical_view_quat<float>(snapq.data(),1,static_cast<Viewer *>(clientData)->options.trackball_angle.data());
  1647. }
  1648. void TW_CALL Viewer::align_camera_center_cb(void *clientData)
  1649. {
  1650. static_cast<Viewer *>(clientData)->align_camera_center();
  1651. }
  1652. void TW_CALL Viewer::save_scene_cb(void *clientData)
  1653. {
  1654. static_cast<Viewer *>(clientData)->save_scene();
  1655. }
  1656. void TW_CALL Viewer::load_scene_cb(void *clientData)
  1657. {
  1658. static_cast<Viewer *>(clientData)->load_scene();
  1659. }
  1660. void TW_CALL Viewer::set_invert_normals_cb(const void *param, void *clientData)
  1661. {
  1662. Viewer *viewer = static_cast<Viewer *>(clientData);
  1663. viewer->data.dirty |= Viewer::DIRTY_NORMAL;
  1664. viewer->options.invert_normals = *((bool *) param);
  1665. }
  1666. void TW_CALL Viewer::get_invert_normals_cb(void *param, void *clientData)
  1667. {
  1668. *((bool *) param) = static_cast<Viewer *>(clientData)->options.invert_normals;
  1669. }
  1670. void TW_CALL Viewer::set_face_based_cb(const void *param, void *clientData)
  1671. {
  1672. Viewer *viewer = static_cast<Viewer *>(clientData);
  1673. viewer->set_face_based(*((bool *) param));
  1674. }
  1675. void TW_CALL Viewer::get_face_based_cb(void *param, void *clientData)
  1676. {
  1677. *((bool *) param) = static_cast<Viewer *>(clientData)->options.face_based;
  1678. }
  1679. void TW_CALL Viewer::open_dialog_mesh(void *clientData)
  1680. {
  1681. std::string fname = igl::file_dialog_open();
  1682. if (fname.length() == 0)
  1683. return;
  1684. static_cast<Viewer *>(clientData)->load_mesh_from_file(fname.c_str());
  1685. }
  1686. // Serialization
  1687. void Viewer::Options::InitSerialization()
  1688. {
  1689. #ifdef ENABLE_XML_SERIALIZATION
  1690. xmlSerializer->Add(shininess, "shininess");
  1691. xmlSerializer->Add(background_color, "background_color");
  1692. xmlSerializer->Add(line_color, "line_color");
  1693. xmlSerializer->Add(light_position, "light_position");
  1694. xmlSerializer->Add(lighting_factor, "lighting_factor");
  1695. xmlSerializer->Add(trackball_angle, "trackball_angle");
  1696. xmlSerializer->Add(model_zoom, "model_zoom");
  1697. xmlSerializer->Add(model_translation, "model_translation");
  1698. xmlSerializer->Add(model_zoom_uv, "model_zoom_uv");
  1699. xmlSerializer->Add(model_translation_uv, "model_translation_uv");
  1700. xmlSerializer->Add(camera_zoom, "camera_zoom");
  1701. xmlSerializer->Add(orthographic, "orthographic");
  1702. xmlSerializer->Add(camera_eye, "camera_eye");
  1703. xmlSerializer->Add(camera_up, "camera_up");
  1704. xmlSerializer->Add(camera_center, "camera_center");
  1705. xmlSerializer->Add(camera_view_angle, "camera_view_angle");
  1706. xmlSerializer->Add(camera_dnear, "camera_dnear");
  1707. xmlSerializer->Add(camera_dfar, "camera_dfar");
  1708. xmlSerializer->Add(show_overlay, "show_overlay");
  1709. xmlSerializer->Add(show_overlay_depth, "show_overlay_depth");
  1710. xmlSerializer->Add(show_texture, "show_texture");
  1711. xmlSerializer->Add(show_faces, "show_faces");
  1712. xmlSerializer->Add(show_lines, "show_lines");
  1713. xmlSerializer->Add(show_vertid, "show_vertid");
  1714. xmlSerializer->Add(show_faceid, "show_faceid");
  1715. xmlSerializer->Add(point_size, "point_size");
  1716. xmlSerializer->Add(line_width, "line_width");
  1717. xmlSerializer->Add(invert_normals, "invert_normals");
  1718. xmlSerializer->Add(face_based, "face_based");
  1719. #endif
  1720. }
  1721. void Viewer::Data::InitSerialization()
  1722. {
  1723. #ifdef ENABLE_XML_SERIALIZATION
  1724. xmlSerializer->Add(V,"V");
  1725. xmlSerializer->Add(F,"F");
  1726. xmlSerializer->Add(F_normals,"F_normals");
  1727. xmlSerializer->Add(F_material_ambient,"F_material_ambient");
  1728. xmlSerializer->Add(F_material_diffuse,"F_material_diffuse");
  1729. xmlSerializer->Add(F_material_specular,"F_material_specular");
  1730. xmlSerializer->Add(V_normals,"V_normals");
  1731. xmlSerializer->Add(V_material_ambient,"V_material_ambient");
  1732. xmlSerializer->Add(V_material_diffuse,"V_material_diffuse");
  1733. xmlSerializer->Add(V_material_specular,"V_material_specular");
  1734. xmlSerializer->Add(V_uv,"V_uv");
  1735. xmlSerializer->Add(F_uv,"F_uv");
  1736. xmlSerializer->Add(texture_R,"texture_R");
  1737. xmlSerializer->Add(texture_G,"texture_G");
  1738. xmlSerializer->Add(texture_B,"texture_B");
  1739. xmlSerializer->Add(lines,"lines");
  1740. xmlSerializer->Add(points,"points");
  1741. xmlSerializer->Add(labels_positions,"labels_positions");
  1742. xmlSerializer->Add(labels_strings,"labels_strings");
  1743. #endif
  1744. }
  1745. void Viewer::set_face_based(bool newvalue)
  1746. {
  1747. if (options.face_based != newvalue)
  1748. {
  1749. options.face_based = newvalue;
  1750. data.dirty = DIRTY_ALL;
  1751. }
  1752. }
  1753. // Helpers that draws the most common meshes
  1754. void Viewer::set_mesh(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F)
  1755. {
  1756. using namespace std;
  1757. Eigen::MatrixXd V_temp;
  1758. // If V only has two columns, pad with a column of zeros
  1759. if (V.cols() == 2)
  1760. {
  1761. V_temp = Eigen::MatrixXd::Zero(V.rows(),3);
  1762. V_temp.block(0,0,V.rows(),2) = V;
  1763. }
  1764. else
  1765. V_temp = V;
  1766. if (data.V.rows() == 0 && data.F.rows() == 0)
  1767. {
  1768. clear_mesh();
  1769. data.V = V_temp;
  1770. data.F = F;
  1771. compute_normals();
  1772. uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
  1773. Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
  1774. Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));
  1775. grid_texture();
  1776. align_camera_center();
  1777. }
  1778. else
  1779. {
  1780. if (data.V.rows() == V.rows() && data.F.rows() == F.rows())
  1781. {
  1782. data.V = V_temp;
  1783. data.F = F;
  1784. align_camera_center();
  1785. }
  1786. else
  1787. cerr << "ERROR (set_mesh): The new mesh has a different number of vertices/faces. Please clear the mesh before plotting.";
  1788. }
  1789. data.dirty |= DIRTY_FACE | DIRTY_POSITION;
  1790. }
  1791. void Viewer::set_vertices(const Eigen::MatrixXd& V)
  1792. {
  1793. data.V = V;
  1794. assert(data.F.size() == 0 || data.F.maxCoeff() < data.V.rows());
  1795. data.dirty |= DIRTY_POSITION;
  1796. }
  1797. void Viewer::set_normals(const Eigen::MatrixXd& N)
  1798. {
  1799. using namespace std;
  1800. if (N.rows() == data.V.rows())
  1801. {
  1802. set_face_based(false);
  1803. data.V_normals = N;
  1804. }
  1805. else if (N.rows() == data.F.rows() || N.rows() == data.F.rows()*3)
  1806. {
  1807. set_face_based(true);
  1808. data.F_normals = N;
  1809. }
  1810. else
  1811. cerr << "ERROR (set_normals): Please provide a normal per face, per corner or per vertex.";
  1812. data.dirty |= DIRTY_NORMAL;
  1813. }
  1814. void Viewer::set_colors(const Eigen::MatrixXd &C)
  1815. {
  1816. using namespace std;
  1817. using namespace Eigen;
  1818. // Ambient color should be darker color
  1819. const auto ambient = [](const MatrixXd & C)->MatrixXd
  1820. {
  1821. return 0.1*C;
  1822. };
  1823. // Specular color should be a less saturated and darker color: dampened
  1824. // highlights
  1825. const auto specular = [](const MatrixXd & C)->MatrixXd
  1826. {
  1827. const double grey = 0.3;
  1828. return grey+0.1*(C.array()-grey);
  1829. };
  1830. if (C.rows() == 1)
  1831. {
  1832. for (unsigned i=0;i<data.V_material_diffuse.rows();++i)
  1833. {
  1834. data.V_material_diffuse.row(i) = C.row(0);
  1835. }
  1836. data.V_material_ambient = ambient(data.V_material_diffuse);
  1837. data.V_material_specular = specular(data.V_material_diffuse);
  1838. for (unsigned i=0;i<data.F_material_diffuse.rows();++i)
  1839. {
  1840. data.F_material_diffuse.row(i) = C.row(0);
  1841. }
  1842. data.F_material_ambient = ambient(data.F_material_diffuse);
  1843. data.F_material_specular = specular(data.F_material_diffuse);
  1844. }
  1845. else if (C.rows() == data.V.rows())
  1846. {
  1847. set_face_based(false);
  1848. data.V_material_diffuse = C;
  1849. data.V_material_ambient = ambient(data.V_material_diffuse);
  1850. data.V_material_specular = specular(data.V_material_diffuse);
  1851. }
  1852. else if (C.rows() == data.F.rows())
  1853. {
  1854. set_face_based(true);
  1855. data.F_material_diffuse = C;
  1856. data.F_material_ambient = ambient(data.F_material_diffuse);
  1857. data.F_material_specular = specular(data.F_material_diffuse);
  1858. }
  1859. else
  1860. cerr << "ERROR (set_colors): Please provide a single color, or a color per face or per vertex.";
  1861. data.dirty |= DIRTY_DIFFUSE;
  1862. }
  1863. void Viewer::set_uv(const Eigen::MatrixXd& UV)
  1864. {
  1865. using namespace std;
  1866. if (UV.rows() == data.V.rows())
  1867. {
  1868. set_face_based(false);
  1869. data.V_uv = UV;
  1870. }
  1871. else
  1872. cerr << "ERROR (set_UV): Please provide uv per vertex.";
  1873. data.dirty |= DIRTY_UV;
  1874. }
  1875. void Viewer::set_uv(const Eigen::MatrixXd& UV_V, const Eigen::MatrixXi& UV_F)
  1876. {
  1877. set_face_based(true);
  1878. data.V_uv = UV_V;
  1879. data.F_uv = UV_F;
  1880. data.dirty |= DIRTY_UV;
  1881. }
  1882. void Viewer::set_texture(
  1883. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& R,
  1884. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& G,
  1885. const Eigen::Matrix<char,Eigen::Dynamic,Eigen::Dynamic>& B)
  1886. {
  1887. data.texture_R = R;
  1888. data.texture_G = G;
  1889. data.texture_B = B;
  1890. data.dirty |= DIRTY_TEXTURE;
  1891. }
  1892. void Viewer::add_points(const Eigen::MatrixXd& P, const Eigen::MatrixXd& C)
  1893. {
  1894. Eigen::MatrixXd P_temp;
  1895. // If P only has two columns, pad with a column of zeros
  1896. if (P.cols() == 2)
  1897. {
  1898. P_temp = Eigen::MatrixXd::Zero(P.rows(),3);
  1899. P_temp.block(0,0,P.rows(),2) = P;
  1900. }
  1901. else
  1902. P_temp = P;
  1903. int lastid = data.points.rows();
  1904. data.points.conservativeResize(data.points.rows() + P_temp.rows(),6);
  1905. for (unsigned i=0; i<P_temp.rows(); ++i)
  1906. data.points.row(lastid+i) << P_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
  1907. data.dirty |= DIRTY_OVERLAY_POINTS;
  1908. }
  1909. void Viewer::set_edges(
  1910. const Eigen::MatrixXd& P,
  1911. const Eigen::MatrixXi& E,
  1912. const Eigen::MatrixXd& C)
  1913. {
  1914. using namespace Eigen;
  1915. data.lines.resize(E.rows(),9);
  1916. assert(C.cols() == 3);
  1917. for(int e = 0;e<E.rows();e++)
  1918. {
  1919. RowVector3d color;
  1920. if(C.size() == 3)
  1921. {
  1922. color<<C;
  1923. }else if(C.rows() == E.rows())
  1924. {
  1925. color<<C.row(e);
  1926. }
  1927. data.lines.row(e)<< P.row(E(e,0)), P.row(E(e,1)), color;
  1928. }
  1929. data.dirty |= DIRTY_OVERLAY_LINES;
  1930. }
  1931. void Viewer::add_edges(const Eigen::MatrixXd& P1, const Eigen::MatrixXd& P2, const Eigen::MatrixXd& C)
  1932. {
  1933. Eigen::MatrixXd P1_temp,P2_temp;
  1934. // If P1 only has two columns, pad with a column of zeros
  1935. if (P1.cols() == 2)
  1936. {
  1937. P1_temp = Eigen::MatrixXd::Zero(P1.rows(),3);
  1938. P1_temp.block(0,0,P1.rows(),2) = P1;
  1939. P2_temp = Eigen::MatrixXd::Zero(P2.rows(),3);
  1940. P2_temp.block(0,0,P2.rows(),2) = P2;
  1941. }
  1942. else
  1943. {
  1944. P1_temp = P1;
  1945. P2_temp = P2;
  1946. }
  1947. int lastid = data.lines.rows();
  1948. data.lines.conservativeResize(data.lines.rows() + P1_temp.rows(),9);
  1949. for (unsigned i=0; i<P1_temp.rows(); ++i)
  1950. data.lines.row(lastid+i) << P1_temp.row(i), P2_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);
  1951. data.dirty |= DIRTY_OVERLAY_LINES;
  1952. }
  1953. void Viewer::add_label(const Eigen::VectorXd& P, const std::string& str)
  1954. {
  1955. Eigen::RowVectorXd P_temp;
  1956. // If P only has two columns, pad with a column of zeros
  1957. if (P.size() == 2)
  1958. {
  1959. P_temp = Eigen::RowVectorXd::Zero(3);
  1960. P_temp << P, 0;
  1961. }
  1962. else
  1963. P_temp = P;
  1964. int lastid = data.labels_positions.rows();
  1965. data.labels_positions.conservativeResize(lastid+1, 3);
  1966. data.labels_positions.row(lastid) = P_temp;
  1967. data.labels_strings.push_back(str);
  1968. }
  1969. int Viewer::launch(std::string filename)
  1970. {
  1971. GLFWwindow* window;
  1972. glfwSetErrorCallback(glfw_error_callback);
  1973. if (!glfwInit())
  1974. return EXIT_FAILURE;
  1975. glfwWindowHint(GLFW_SAMPLES, 16);
  1976. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  1977. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  1978. #ifdef __APPLE__
  1979. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  1980. glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  1981. #endif
  1982. window = glfwCreateWindow(1280, 800, "IGL Viewer", NULL, NULL);
  1983. if (!window)
  1984. {
  1985. glfwTerminate();
  1986. return EXIT_FAILURE;
  1987. }
  1988. glfwMakeContextCurrent(window);
  1989. #ifndef __APPLE__
  1990. glewExperimental = true;
  1991. GLenum err = glewInit();
  1992. if (GLEW_OK != err)
  1993. {
  1994. /* Problem: glewInit failed, something is seriously wrong. */
  1995. fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  1996. }
  1997. fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
  1998. #endif
  1999. #ifdef DEBUG
  2000. int major, minor, rev;
  2001. major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  2002. minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  2003. rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
  2004. printf("OpenGL version recieved: %d.%d.%d\n", major, minor, rev);
  2005. printf("Supported OpenGL is %s\n", (const char*)glGetString(GL_VERSION));
  2006. printf("Supported GLSL is %s\n", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
  2007. #endif
  2008. glfwSetInputMode(window,GLFW_CURSOR,GLFW_CURSOR_NORMAL);
  2009. // Initialize AntTweakBar
  2010. TwInit(TW_OPENGL_CORE, NULL);
  2011. // Initialize IGL viewer
  2012. init(&igl_viewer_plugin_manager);
  2013. __viewer = this;
  2014. // Register callbacks
  2015. 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);
  2016. // Handle retina displays (windows and mac)
  2017. int width, height;
  2018. glfwGetFramebufferSize(window, &width, &height);
  2019. int width_window, height_window;
  2020. glfwGetWindowSize(window, &width_window, &height_window);
  2021. highdpi = width/width_window;
  2022. glfw_window_size(window,width_window,height_window);
  2023. init_opengl();
  2024. // Load the mesh passed as input
  2025. if (filename.size() > 0)
  2026. load_mesh_from_file(filename.c_str());
  2027. // Rendering loop
  2028. while (!glfwWindowShouldClose(window))
  2029. {
  2030. double tic = get_seconds();
  2031. draw();
  2032. glfwSwapBuffers(window);
  2033. if(options.is_animating)
  2034. {
  2035. glfwPollEvents();
  2036. // In microseconds
  2037. double duration = 1000000.*(get_seconds()-tic);
  2038. const double min_duration = 1000000./options.animation_max_fps;
  2039. if(duration<min_duration)
  2040. {
  2041. // TODO: windows equivalent
  2042. usleep(min_duration-duration);
  2043. }
  2044. }else
  2045. {
  2046. glfwWaitEvents();
  2047. }
  2048. }
  2049. free_opengl();
  2050. shutdown_plugins();
  2051. glfwDestroyWindow(window);
  2052. glfwTerminate();
  2053. return EXIT_SUCCESS;
  2054. }
  2055. } // end namespace