Viewer.cpp 73 KB

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