FontRenderer.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include "rendering/FontRenderer.h"
  2. #include "gaming-core/wrapper/Attributes.h"
  3. #include "gaming-core/utils/List.h"
  4. FontRenderer::FontRenderer() : tex1("resources/font8x8.png"), tex2("resources/font16x16.png"),
  5. tex3("resources/font24x24.png"), activeTex(&tex1), scale(1) {
  6. vertexBuffer.setAttributes(Attributes().addFloat(2).addFloat(2).addFloat(4));
  7. vertexBuffer.setStreamData(256 * 4 * sizeof (float) * 8);
  8. }
  9. float FontRenderer::drawString(float x, float y, const char* text) {
  10. const int maxIndex = 256;
  11. List<float, maxIndex * 4 * 8> buffer;
  12. int index = 0;
  13. float r = 1.0f;
  14. float g = 1.0f;
  15. float b = 1.0f;
  16. float addX = 6.0f * scale;
  17. float addY = 8.0f * scale;
  18. while(text[index] != '\0' && index < maxIndex) {
  19. char32_t c = text[index];
  20. if(c > 128 && index + 1 < maxIndex && text[index + 1] != '\0') {
  21. index++;
  22. c = (text[index] & 0x3F) | ((c & 0x1F) << 6);
  23. }
  24. if(c == '&') {
  25. if(text[index + 1] == '\0' || text[index + 2] == '\0' || text[index + 3] == '\0') {
  26. break;
  27. }
  28. r = (text[index + 1] - '0') * (1.0f / 9.0f);
  29. g = (text[index + 2] - '0') * (1.0f / 9.0f);
  30. b = (text[index + 3] - '0') * (1.0f / 9.0f);
  31. index += 4;
  32. continue;
  33. }
  34. float minX = (c & 0xF) * (1.0f / 16.0f) + 1.0f / 128.0f;
  35. float minY = (c >> 4) * (1.0f / 16.0f);
  36. float maxX = minX + (1.0f / 16.0f) - 2.0f / 128.0f;
  37. float maxY = minY + (1.0f / 16.0f);
  38. buffer.add(x);
  39. buffer.add(y);
  40. buffer.add(minX);
  41. buffer.add(minY);
  42. buffer.add(r);
  43. buffer.add(g);
  44. buffer.add(b);
  45. buffer.add(1.0f);
  46. buffer.add(x);
  47. buffer.add(y + addY);
  48. buffer.add(minX);
  49. buffer.add(maxY);
  50. buffer.add(r);
  51. buffer.add(g);
  52. buffer.add(b);
  53. buffer.add(1.0f);
  54. buffer.add(x + addX);
  55. buffer.add(y);
  56. buffer.add(maxX);
  57. buffer.add(minY);
  58. buffer.add(r);
  59. buffer.add(g);
  60. buffer.add(b);
  61. buffer.add(1.0f);
  62. buffer.add(x + addX);
  63. buffer.add(y + addY);
  64. buffer.add(maxX);
  65. buffer.add(maxY);
  66. buffer.add(r);
  67. buffer.add(g);
  68. buffer.add(b);
  69. buffer.add(1.0f);
  70. x += addX;
  71. index++;
  72. }
  73. activeTex->bind();
  74. vertexBuffer.updateData(0, buffer.getLength() * sizeof(float), buffer.begin());
  75. vertexBuffer.drawStrip(buffer.getLength() / 8);
  76. return y + addY;
  77. }
  78. void FontRenderer::setSize(int size) {
  79. if(size == 1) {
  80. activeTex = &tex2;
  81. scale = 2;
  82. } else if(size == 2) {
  83. activeTex = &tex3;
  84. scale = 3;
  85. } else {
  86. activeTex = &tex1;
  87. scale = 1;
  88. }
  89. }