Renderer.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <cassert>
  2. #include "rendering/Renderer.h"
  3. static void setFloatAttribute(uint index, uint length, uint offset, uint step) {
  4. glVertexAttribPointer(index, length, GL_FLOAT, false, sizeof (float) * step, static_cast<float*> (0) + offset);
  5. glEnableVertexAttribArray(index);
  6. }
  7. Renderer::Renderer() : vertexArray(0), vertexBuffer(0), bufferSize(8 * 1024 * 1024), offset(bufferSize), index(0),
  8. buffer(nullptr) {
  9. glGenVertexArrays(1, &vertexArray);
  10. glGenBuffers(1, &vertexBuffer);
  11. bind();
  12. setFloatAttribute(0, 2, 0, 5);
  13. setFloatAttribute(1, 3, 2, 5);
  14. }
  15. Renderer::~Renderer() {
  16. glDeleteBuffers(1, &vertexBuffer);
  17. glDeleteVertexArrays(1, &vertexArray);
  18. }
  19. void Renderer::setPointSize(float size) {
  20. glPointSize(size);
  21. }
  22. void Renderer::drawPoint(float x, float y, uint color) {
  23. bind();
  24. reset(sizeof (float) * 5);
  25. add(x).add(y).add(getColorChannel(color, 16)).add(getColorChannel(color, 8)).add(getColorChannel(color, 0));
  26. draw(GL_POINTS);
  27. }
  28. void Renderer::drawLine(float x, float y, float x2, float y2, uint color) {
  29. bind();
  30. reset(sizeof (float) * 10);
  31. add(x).add(y).add(getColorChannel(color, 16)).add(getColorChannel(color, 8)).add(getColorChannel(color, 0));
  32. add(x2).add(y2).add(getColorChannel(color, 16)).add(getColorChannel(color, 8)).add(getColorChannel(color, 0));
  33. draw(GL_LINES);
  34. }
  35. void Renderer::bind() {
  36. glBindVertexArray(vertexArray);
  37. glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
  38. }
  39. void Renderer::reset(u64 size) {
  40. if(offset + size >= bufferSize) {
  41. offset = 0;
  42. glBufferData(GL_ARRAY_BUFFER, bufferSize, nullptr, GL_STREAM_DRAW);
  43. }
  44. constexpr uint bits = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT;
  45. buffer = static_cast<float*> (glMapBufferRange(GL_ARRAY_BUFFER, offset, size, bits));
  46. assert(buffer != nullptr);
  47. index = 0;
  48. }
  49. Renderer& Renderer::add(float f) {
  50. buffer[index++] = f;
  51. return *this;
  52. }
  53. void Renderer::draw(uint type) {
  54. glUnmapBuffer(GL_ARRAY_BUFFER);
  55. glDrawArrays(type, offset / (sizeof (float) * 5), index / 5);
  56. offset += index * sizeof (float);
  57. }
  58. float Renderer::getColorChannel(uint color, uint shifts) const {
  59. return ((color >> shifts) & 0xFF) * (1.0f / 255.0f);
  60. }