TextRenderer.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Wenzel Jacob <wenzel@inf.ethz.ch>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "TextRenderer.h"
  9. #include "TextRenderer_fonts.h"
  10. #include <igl/project.h>
  11. #include <nanovg.h>
  12. #define NANOVG_GL3
  13. #include <nanovg_gl.h>
  14. using namespace std;
  15. IGL_INLINE igl::viewer::TextRenderer::TextRenderer() { }
  16. IGL_INLINE int igl::viewer::TextRenderer::Init()
  17. {
  18. #ifdef NDEBUG
  19. ctx = nvgCreateGL3(NVG_STENCIL_STROKES | NVG_ANTIALIAS);
  20. #else
  21. ctx = nvgCreateGL3(NVG_STENCIL_STROKES | NVG_ANTIALIAS | NVG_DEBUG);
  22. #endif
  23. nvgCreateFontMem(ctx, "sans", igl_roboto_regular_ttf,
  24. igl_roboto_regular_ttf_size, 0);
  25. return 0;
  26. }
  27. IGL_INLINE int igl::viewer::TextRenderer::Shut()
  28. {
  29. nvgDeleteGL3(ctx);
  30. return 0;
  31. }
  32. IGL_INLINE void igl::viewer::TextRenderer::BeginDraw(const Eigen::Matrix4f &view, const Eigen::Matrix4f &proj,
  33. const Eigen::Vector4f &_viewport, float _object_scale)
  34. {
  35. viewport = _viewport;
  36. proj_matrix = proj;
  37. view_matrix = view;
  38. object_scale = _object_scale;
  39. Eigen::Vector2i mFBSize;
  40. Eigen::Vector2i mSize;
  41. GLFWwindow* mGLFWWindow = glfwGetCurrentContext();
  42. glfwGetFramebufferSize(mGLFWWindow,&mFBSize[0],&mFBSize[1]);
  43. glfwGetWindowSize(mGLFWWindow,&mSize[0],&mSize[1]);
  44. glViewport(0,0,mFBSize[0],mFBSize[1]);
  45. glClear(GL_STENCIL_BUFFER_BIT);
  46. /* Calculate pixel ratio for hi-dpi devices. */
  47. mPixelRatio = (float)mFBSize[0] / (float)mSize[0];
  48. nvgBeginFrame(ctx,mSize[0],mSize[1],mPixelRatio);
  49. }
  50. IGL_INLINE void igl::viewer::TextRenderer::EndDraw()
  51. {
  52. nvgEndFrame(ctx);
  53. }
  54. IGL_INLINE void igl::viewer::TextRenderer::DrawText(Eigen::Vector3d pos, Eigen::Vector3d normal, const std::string &text)
  55. {
  56. pos += normal * 0.005f * object_scale;
  57. Eigen::Vector3f coord = igl::project(Eigen::Vector3f(pos(0), pos(1), pos(2)),
  58. view_matrix, proj_matrix, viewport);
  59. nvgFontSize(ctx, 16/mPixelRatio);
  60. nvgFontFace(ctx, "sans");
  61. nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE);
  62. nvgFillColor(ctx, nvgRGBA(10,10,250,255));
  63. nvgText(ctx, coord[0]/mPixelRatio, (viewport[3] - coord[1])/mPixelRatio, text.c_str(), NULL);
  64. }