diff --git a/source/include/group.h b/source/include/group.h index f4067a7..68ebc8c 100644 --- a/source/include/group.h +++ b/source/include/group.h @@ -37,7 +37,10 @@ public: bool isEmpty(); void addObject(Shape *s); - Shape *operator[](const int p) { return this->objectList[p]; } + void removeObject(Shape *s); + + Shape *operator[](const int p) { return this->objectList[p]; }; + Shape *getUnboxable(const int p) { return this->unboxableObjectList[p]; }; Intersect intersect(Ray r); BoundingBox getLocalBounds(); @@ -48,7 +51,8 @@ public: bool includes(Shape *b); - uint32_t getObjectCount() { return this->objectCount + this->unboxableObjectCount; }; + uint32_t getObjectCount() { return this->objectCount; }; + uint32_t getUnboxableCount() { return this->unboxableObjectCount; }; Group(const char *name = nullptr); diff --git a/source/shapes/group.cpp b/source/shapes/group.cpp index f3d7308..3da9e55 100644 --- a/source/shapes/group.cpp +++ b/source/shapes/group.cpp @@ -149,6 +149,37 @@ void Group::addObject(Shape *s) } } +void Group::removeObject(Shape *s) +{ + int i; + if (s->haveFiniteBounds()) + { + for (i = 0; i < this->objectCount; i++) + { + if (this->objectList[i] == s) + { + this->objectCount --; + this->objectList[i] = this->objectList[this->objectCount]; + this->objectList[this->objectCount] = nullptr; + break; + } + } + } + else + { + for (i = 0; i < this->unboxableObjectCount; i++) + { + if (this->unboxableObjectList[i] == s) + { + this->unboxableObjectCount --; + this->unboxableObjectList[i] = this->unboxableObjectList[this->unboxableObjectCount]; + this->unboxableObjectList[this->unboxableObjectCount] = nullptr; + break; + } + } + } +} + bool Group::isEmpty() { return (this->objectCount == 0) && (this->unboxableObjectCount == 0); diff --git a/tests/group_test.cpp b/tests/group_test.cpp index 0a817b6..9642939 100644 --- a/tests/group_test.cpp +++ b/tests/group_test.cpp @@ -97,4 +97,36 @@ TEST(GroupTest, Group_bounding_box) ASSERT_EQ(res.min, b.min); ASSERT_EQ(res.max, b.max); -} \ No newline at end of file +} + +TEST(GroupTest, Removing_an_object) +{ + Group g = Group(); + Sphere s1 = Sphere(); + Sphere s2 = Sphere(); + Sphere s3 = Sphere(); + + s1.setTransform(translation(-1, 0, 0)); + s2.setTransform(scaling(0.5, 0.5, 0.5)); + + g.addObject(&s1); + g.addObject(&s2); + + ASSERT_EQ(g.getObjectCount(), 2); + ASSERT_EQ(*(g[0]), s1); + ASSERT_EQ(*(g[1]), s2); + + g.removeObject(&s1); + + ASSERT_EQ(g.getObjectCount(), 1); + ASSERT_EQ(*(g[0]), s2); + ASSERT_EQ(g[1], nullptr); + + g.removeObject(&s3); + ASSERT_EQ(g.getObjectCount(), 1); + + g.removeObject(&s2); + ASSERT_EQ(g.getObjectCount(), 0); + ASSERT_EQ(g[0], nullptr); +} +