list.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /*
  2. * DoRayMe - a quick and dirty Raytracer
  3. * List header
  4. *
  5. * Created by Manoël Trapier
  6. * Copyright (c) 2020 986-Studio.
  7. *
  8. */
  9. #ifndef DORAYME_LIST_H
  10. #define DORAYME_LIST_H
  11. #include <shape.h>
  12. struct ChainList
  13. {
  14. Shape *shape;
  15. ChainList *next;
  16. };
  17. class List
  18. {
  19. private:
  20. ChainList *head;
  21. ChainList *tail;
  22. uint32_t count;
  23. public:
  24. List() : head(nullptr), tail(nullptr), count(0) { };
  25. ~List()
  26. {
  27. ChainList *p = this->head;
  28. if (p == nullptr) { return; }
  29. /* clear up the list */
  30. do
  31. {
  32. ChainList *next = p->next;
  33. free(p);
  34. p = next;
  35. }
  36. while(p != nullptr);
  37. }
  38. Shape *last()
  39. {
  40. ChainList *p = this->tail;
  41. if (p == nullptr) { return nullptr; }
  42. return p->shape;
  43. }
  44. void remove(Shape *s)
  45. {
  46. ChainList *p = this->head;
  47. if (p == nullptr) { return; }
  48. if ((p->next == nullptr) && (p->shape == s))
  49. {
  50. /* First element */
  51. this->tail = nullptr;
  52. free(this->head);
  53. this->head = nullptr;
  54. this->count = 0;
  55. return;
  56. }
  57. while(p->next != nullptr)
  58. {
  59. if (p->next->shape == s)
  60. {
  61. ChainList *found = p->next;
  62. p->next = p->next->next;
  63. free(found);
  64. if (p->next == NULL) { this->tail = p; }
  65. this->count --;
  66. return;
  67. }
  68. p = p->next;
  69. }
  70. }
  71. void append(Shape *s)
  72. {
  73. ChainList *theNew = (ChainList *)calloc(1, sizeof(ChainList));
  74. theNew->shape = s;
  75. ChainList *p = this->tail;
  76. this->tail = theNew;
  77. if (p != nullptr) { p->next = theNew; }
  78. else { this->head = theNew; } /* If the tail is empty, it mean the list IS empty. */
  79. this->count ++;
  80. }
  81. bool isEmpty()
  82. {
  83. return (this->count == 0);
  84. }
  85. bool doesInclude(Shape *s)
  86. {
  87. ChainList *p = this->head;
  88. while(p != nullptr)
  89. {
  90. if (p->shape == s) { return true; }
  91. p = p->next;
  92. }
  93. return false;
  94. }
  95. };
  96. #endif //DORAYME_LIST_H