Viewer.cpp 71 KB

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