FontRenderer.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "rendering/FontRenderer.h"
  2. #include "gaming-core/utils/Buffer.h"
  3. #include "gaming-core/utils/Color.h"
  4. #include "gaming-core/wrapper/Attributes.h"
  5. FontRenderer::FontRenderer() : activeTex(0), scale(1) {
  6. tex.add("resources/font8x8.png");
  7. tex.add("resources/font16x16.png");
  8. tex.add("resources/font24x24.png");
  9. vertexBuffer.setAttributes(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' || text[index + 3] == '\0') {
  27. break;
  28. }
  29. color[0] = ((text[index + 1] - '0') * 255) / 9;
  30. color[1] = ((text[index + 2] - '0') * 255) / 9;
  31. color[2] = ((text[index + 3] - '0') * 255) / 9;
  32. index += 4;
  33. continue;
  34. }
  35. float minX = (c & 0xF) * (1.0f / 16.0f) + 1.0f / 128.0f;
  36. float minY = (c >> 4) * (1.0f / 16.0f);
  37. float maxX = minX + (1.0f / 16.0f) - 2.0f / 128.0f;
  38. float maxY = minY + (1.0f / 16.0f);
  39. buffer.add(x).add(y).add(minX).add(minY).add(color);
  40. buffer.add(x).add(y + addY).add(minX).add(maxY).add(color);
  41. buffer.add(x + addX).add(y).add(maxX).add(minY).add(color);
  42. buffer.add(x + addX).add(y + addY).add(maxX).add(maxY).add(color);
  43. x += addX;
  44. index++;
  45. }
  46. tex[activeTex].bindTo(0);
  47. vertexBuffer.updateData(0, buffer.getLength(), buffer);
  48. vertexBuffer.drawStrip(buffer.getLength() / (4 * sizeof(float) + sizeof(Color4)));
  49. return y + addY;
  50. }
  51. void FontRenderer::setSize(int size) {
  52. if(size == 1 || size == 2) {
  53. activeTex = size;
  54. scale = size + 1;
  55. } else {
  56. activeTex = 0;
  57. scale = 1;
  58. }
  59. }