TextRenderer.cpp 2.5 KB

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