canvas.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Canvas implementation
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #include <canvas.h>
  10. #include <lodepng.h>
  11. #define BPP (24)
  12. #define BytePP (BPP / 8)
  13. #define MIN(_a, _b) ((_a)<(_b)?(_a):(_b))
  14. #define MAX(_a, _b) ((_a)>(_b)?(_a):(_b))
  15. Canvas::Canvas(uint32_t width, uint32_t height) : width(width), height(height)
  16. {
  17. this->bitmap = (uint8_t *)calloc(4, width * height);
  18. this->stride = BytePP * width;
  19. }
  20. Canvas::~Canvas()
  21. {
  22. if (this->bitmap != nullptr)
  23. {
  24. free(this->bitmap);
  25. }
  26. }
  27. void Canvas::putPixel(uint32_t x, uint32_t y, Colour c)
  28. {
  29. uint32_t offset = y * this->stride + x * BytePP;
  30. this->bitmap[offset + 0] = MAX(MIN(c.red() * 255, 255), 0);
  31. this->bitmap[offset + 1] = MAX(MIN(c.green() * 255, 255), 0);
  32. this->bitmap[offset + 2] = MAX(MIN(c.blue() * 255, 255), 0);
  33. }
  34. Colour Canvas::getPixel(uint32_t x, uint32_t y)
  35. {
  36. uint32_t offset = y * this->stride + x * BytePP;
  37. return Colour(this->bitmap[offset + 0] / 255, this->bitmap[offset + 1] / 255, this->bitmap[offset + 2] / 255);
  38. }
  39. bool Canvas::SaveAsPNG(const char *filename)
  40. {
  41. uint32_t ret = lodepng_encode24_file(filename, this->bitmap, this->width, this->height);
  42. return ret == 0;
  43. }