Viewer.cpp 75 KB

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