TextRenderer.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 <nanogui/opengl.h>
  12. #include <nanovg.h>
  13. #include <Eigen/Dense>
  14. #define NANOVG_GL3
  15. #include <nanovg_gl.h>
  16. using namespace std;
  17. IGL_INLINE igl::viewer::TextRenderer::TextRenderer(): ctx(nullptr) {}
  18. IGL_INLINE int igl::viewer::TextRenderer::Init()
  19. {
  20. #ifdef NDEBUG
  21. ctx = nvgCreateGL3(NVG_STENCIL_STROKES | NVG_ANTIALIAS);
  22. #else
  23. ctx = nvgCreateGL3(NVG_STENCIL_STROKES | NVG_ANTIALIAS | NVG_DEBUG);
  24. #endif
  25. nvgCreateFontMem(ctx, "sans", igl_roboto_regular_ttf,
  26. igl_roboto_regular_ttf_size, 0);
  27. return 0;
  28. }
  29. IGL_INLINE int igl::viewer::TextRenderer::Shut()
  30. {
  31. if(ctx)
  32. nvgDeleteGL3(ctx);
  33. return 0;
  34. }
  35. IGL_INLINE void igl::viewer::TextRenderer::BeginDraw(const Eigen::Matrix4f &view, const Eigen::Matrix4f &proj,
  36. const Eigen::Vector4f &_viewport, float _object_scale)
  37. {
  38. viewport = _viewport;
  39. proj_matrix = proj;
  40. view_matrix = view;
  41. object_scale = _object_scale;
  42. Eigen::Vector2i mFBSize;
  43. Eigen::Vector2i mSize;
  44. GLFWwindow* mGLFWWindow = glfwGetCurrentContext();
  45. glfwGetFramebufferSize(mGLFWWindow,&mFBSize[0],&mFBSize[1]);
  46. glfwGetWindowSize(mGLFWWindow,&mSize[0],&mSize[1]);
  47. glViewport(0,0,mFBSize[0],mFBSize[1]);
  48. glClear(GL_STENCIL_BUFFER_BIT);
  49. /* Calculate pixel ratio for hi-dpi devices. */
  50. mPixelRatio = (float)mFBSize[0] / (float)mSize[0];
  51. nvgBeginFrame(ctx,mSize[0],mSize[1],mPixelRatio);
  52. }
  53. IGL_INLINE void igl::viewer::TextRenderer::EndDraw()
  54. {
  55. nvgEndFrame(ctx);
  56. }
  57. IGL_INLINE void igl::viewer::TextRenderer::DrawText(Eigen::Vector3d pos, Eigen::Vector3d normal, const std::string &text)
  58. {
  59. pos += normal * 0.005f * object_scale;
  60. Eigen::Vector3f coord = igl::project(Eigen::Vector3f(pos(0), pos(1), pos(2)),
  61. view_matrix, proj_matrix, viewport);
  62. nvgFontSize(ctx, 16/mPixelRatio);
  63. nvgFontFace(ctx, "sans");
  64. nvgTextAlign(ctx, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE);
  65. nvgFillColor(ctx, nvgRGBA(10,10,250,255));
  66. nvgText(ctx, coord[0]/mPixelRatio, (viewport[3] - coord[1])/mPixelRatio, text.c_str(), NULL);
  67. }