intersect.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #define MIN_ALLOC (2)
  14. Intersect::Intersect()
  15. {
  16. this->allocated = MIN_ALLOC;
  17. this->list = (Intersection **)calloc(sizeof(Intersection *), MIN_ALLOC);
  18. this->num = 0;
  19. }
  20. Intersect::~Intersect()
  21. {
  22. /* Free stuff */
  23. }
  24. void Intersect::add(Intersection i)
  25. {
  26. Intersection *x;
  27. int j, k;
  28. if ((this->num + 1) > this->allocated)
  29. {
  30. this->allocated *= 2;
  31. this->list = (Intersection **)realloc(this->list, sizeof(Intersection *) * this->allocated);
  32. }
  33. this->list[this->num++] = new Intersection(i.t, i.object);
  34. /* Now sort.. */
  35. for(j = 1; j < (this->num); j++)
  36. {
  37. x = this->list[j];
  38. k = j;
  39. while( (k > 0) && (this->list[k - 1]->t) > x->t )
  40. {
  41. this->list[k] = this->list[k - 1];
  42. k--;
  43. }
  44. this->list[k] = x;
  45. }
  46. }
  47. Intersection Intersect::hit()
  48. {
  49. int i;
  50. double minHit = DBL_MAX;
  51. uint32_t curHit = -1;
  52. for(i = 0; i < this->num; i++)
  53. {
  54. if ((this->list[i]->t >= 0) && (this->list[i]->t < minHit))
  55. {
  56. curHit = i;
  57. minHit = this->list[i]->t;
  58. }
  59. }
  60. if (curHit == -1)
  61. {
  62. return Intersection(0, nullptr);
  63. }
  64. return *this->list[curHit];
  65. }