canvas.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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(const Canvas &b)
  21. {
  22. this->width = b.width;
  23. this->height = b.height;
  24. this->stride = b.stride;
  25. this->bitmap = (uint8_t *)calloc(4, b.width * b.height);
  26. memcpy(this->bitmap, b.bitmap, 4 * b.width * b.height);
  27. }
  28. Canvas::Canvas(const Canvas *b)
  29. {
  30. this->width = b->width;
  31. this->height = b->height;
  32. this->stride = b->stride;
  33. this->bitmap = (uint8_t *)calloc(4, b->width * b->height);
  34. memcpy(this->bitmap, b->bitmap, 4 * b->width * b->height);
  35. }
  36. Canvas::~Canvas()
  37. {
  38. if (this->bitmap != nullptr)
  39. {
  40. free(this->bitmap);
  41. }
  42. }
  43. void Canvas::putPixel(uint32_t x, uint32_t y, Tuple colour)
  44. {
  45. uint32_t offset = y * this->stride + x * BytePP;
  46. this->bitmap[offset + 0] = MAX(MIN(colour.x * 255, 255), 0);
  47. this->bitmap[offset + 1] = MAX(MIN(colour.y * 255, 255), 0);
  48. this->bitmap[offset + 2] = MAX(MIN(colour.z * 255, 255), 0);
  49. }
  50. Colour Canvas::getPixel(uint32_t x, uint32_t y)
  51. {
  52. uint32_t offset = y * this->stride + x * BytePP;
  53. return Colour(this->bitmap[offset + 0] / 255.0, this->bitmap[offset + 1] / 255.0, this->bitmap[offset + 2] / 255.0);
  54. }
  55. bool Canvas::SaveAsPNG(const char *filename)
  56. {
  57. uint32_t ret = lodepng_encode24_file(filename, this->bitmap, this->width, this->height);
  58. return ret == 0;
  59. }