FontRenderer.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "rendering/FontRenderer.h"
  2. #include "utils/Buffer.h"
  3. #include "utils/Color.h"
  4. FontRenderer::FontRenderer() : activeTex(0), scale(1) {
  5. }
  6. void FontRenderer::init() {
  7. tex[0].load("resources/font8x8.png", 0);
  8. tex[1].load("resources/font16x16.png", 0);
  9. tex[2].load("resources/font24x24.png", 0);
  10. vertexBuffer.init(
  11. VertexBuffer::Attributes().addFloat(2).addFloat(2).addColor4());
  12. vertexBuffer.setData(256 * 4 * sizeof(float) * 8, nullptr, GL::STREAM_DRAW);
  13. }
  14. float FontRenderer::drawString(float x, float y, const char* text) {
  15. const int maxIndex = 256;
  16. Buffer buffer(sizeof(float) * maxIndex * 4 * 8);
  17. int index = 0;
  18. Color4 color(0xFF, 0xFF, 0xFF, 0xFF);
  19. float addX = 6.0f * scale;
  20. float addY = 8.0f * scale;
  21. while(text[index] != '\0' && index < maxIndex) {
  22. char32_t c = text[index];
  23. if(c > 128 && index + 1 < maxIndex && text[index + 1] != '\0') {
  24. index++;
  25. c = (text[index] & 0x3F) | ((c & 0x1F) << 6);
  26. }
  27. if(c == '&') {
  28. if(text[index + 1] == '\0' || text[index + 2] == '\0' ||
  29. text[index + 3] == '\0') {
  30. break;
  31. }
  32. color[0] = ((text[index + 1] - '0') * 255) / 9;
  33. color[1] = ((text[index + 2] - '0') * 255) / 9;
  34. color[2] = ((text[index + 3] - '0') * 255) / 9;
  35. index += 4;
  36. continue;
  37. }
  38. float minX = (c & 0xF) * (1.0f / 16.0f) + 1.0f / 128.0f;
  39. float minY = (c >> 4) * (1.0f / 16.0f);
  40. float maxX = minX + (1.0f / 16.0f) - 2.0f / 128.0f;
  41. float maxY = minY + (1.0f / 16.0f);
  42. buffer.add(x).add(y).add(minX).add(minY).add(color);
  43. buffer.add(x).add(y + addY).add(minX).add(maxY).add(color);
  44. buffer.add(x + addX).add(y).add(maxX).add(minY).add(color);
  45. buffer.add(x + addX).add(y + addY).add(maxX).add(maxY).add(color);
  46. x += addX;
  47. index++;
  48. }
  49. tex[activeTex].bindTo(0);
  50. vertexBuffer.updateData(0, buffer.getLength(), buffer);
  51. vertexBuffer.drawStrip(buffer.getLength() /
  52. (4 * sizeof(float) + sizeof(Color4)));
  53. return y + addY;
  54. }
  55. void FontRenderer::setSize(int size) {
  56. if(size == 1 || size == 2) {
  57. activeTex = size;
  58. scale = size + 1;
  59. } else {
  60. activeTex = 0;
  61. scale = 1;
  62. }
  63. }