intersect.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * Intersect implementation
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #include <stdlib.h>
  10. #include <math_helper.h>
  11. #include <intersect.h>
  12. #include <float.h>
  13. #include <renderstat.h>
  14. #define MIN_ALLOC (2)
  15. /* TODO: Memory allocation, even if using standard calloc/realloc have a huge impact on performances. need to find a way
  16. * to reuse the intersect object without reallocating from scratch all the time. We use a lot of Intersect objects as
  17. * there is at least 2 per ray (one for Ray intersect object, one object per light)
  18. */
  19. Intersect::Intersect()
  20. {
  21. this->allocated = MIN_ALLOC;
  22. this->list = (Intersection **)calloc(sizeof(Intersection *), MIN_ALLOC);
  23. if (this->list != nullptr)
  24. {
  25. stats.addMalloc();
  26. stats.addIntersect();
  27. this->num = 0;
  28. }
  29. else
  30. {
  31. printf("ABORT: Allocation error [%s]!\n", __FUNCTION__);
  32. exit(-1);
  33. }
  34. }
  35. Intersect::~Intersect()
  36. {
  37. int i;
  38. for(i = 0; i < this->num; i++)
  39. {
  40. if (this->list[i] != nullptr)
  41. {
  42. delete this->list[i];
  43. this->list[i] = nullptr;
  44. }
  45. }
  46. /* Free stuff */
  47. if (this->list != nullptr)
  48. {
  49. free(this->list);
  50. this->list = nullptr;
  51. }
  52. }
  53. void Intersect::reset()
  54. {
  55. this->num = 0;
  56. }
  57. void Intersect::add(Intersection i)
  58. {
  59. Intersection *x;
  60. int j, k;
  61. if ((this->num + 1) > this->allocated)
  62. {
  63. this->allocated *= 2;
  64. stats.addRealloc();
  65. this->list = (Intersection **)realloc(this->list, sizeof(Intersection *) * this->allocated);
  66. }
  67. this->list[this->num++] = new Intersection(i.t, i.object, i.u, i.v);
  68. stats.setMaxIntersect(this->num);
  69. /* Now sort.. */
  70. for(j = 1; j < (this->num); j++)
  71. {
  72. x = this->list[j];
  73. k = j;
  74. while( (k > 0) && (this->list[k - 1]->t) > x->t )
  75. {
  76. this->list[k] = this->list[k - 1];
  77. k--;
  78. }
  79. this->list[k] = x;
  80. }
  81. }
  82. Intersection Intersect::hit()
  83. {
  84. int i;
  85. for(i = 0; i < this->num; i++)
  86. {
  87. if (this->list[i]->t >= 0)
  88. return *this->list[i];
  89. }
  90. return Intersection(0, nullptr);
  91. }