Viewer.cpp 75 KB

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