FontRenderer.cpp 2.3 KB

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