commit d184871cba902bde048ad1e56752ae451cafc2c3
parent 37e6ac5b19048e4bd2e0a220cce26fb1ab5da611
Author: Henry Wilson <henry@henryandlizzy.uk>
Date: Sun, 23 Jun 2024 10:21:41 +0100
sdl-gl: Object add and delete
Diffstat:
1 file changed, 24 insertions(+), 7 deletions(-)
diff --git a/src/sdl-gl.cpp b/src/sdl-gl.cpp
@@ -11,6 +11,7 @@
#include <algorithm>
#include <cassert>
#include <exception>
+#include <memory>
#include <numbers>
#include <print>
#include <vector>
@@ -177,10 +178,11 @@ struct object
{
point pos;
rgb col;
-} objs[] = {
- {{0, 0}, {.7,.2,.2}},
- {{4, 0}, {.2,.7,.2}},
- {{0, 5}, {.2,.2,.7}},
+};
+std::vector<std::shared_ptr<object>> objs = {
+ std::make_shared<object>(point{0, 0}, rgb{.7,.2,.2}),
+ std::make_shared<object>(point{4, 0}, rgb{.2,.7,.2}),
+ std::make_shared<object>(point{0, 5}, rgb{.2,.2,.7}),
};
std::vector<point> shape;
@@ -196,7 +198,8 @@ void presentScene(void)
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
circle mouse_area{mouse_pos, 1};
- for (auto& op : objs) {
+ for (auto& optr : objs) {
+ auto& op = *optr;
if (mouse_area.colliding(op.pos))
glColor3d(op.col.r + .25,op.col.g + .25,op.col.b + .25);
else
@@ -228,6 +231,19 @@ void key(SDL_KeyboardEvent& e)
exit(0);
break;
+ case SDLK_a:
+ if (e.state)
+ objs.push_back(std::make_shared<object>(mouse_pos, rgb{.5, .5, .2}));
+ break;
+
+ case SDLK_d:
+ if (e.state)
+ {
+ circle mouse_area{mouse_pos, 1};
+ std::erase_if(objs, [mouse_area](auto& o) { return mouse_area.colliding(o->pos); });
+ }
+ break;
+
case SDLK_ESCAPE:
exit(0);
}
@@ -276,9 +292,10 @@ coroutine_task mouse_task()
case SDL_BUTTON_LEFT:
{
circle mouse_area{mouse_pos, 1};
- auto obj = std::ranges::find_if(objs, [drag_pos, mouse_area](auto const& o){return mouse_area.colliding(o.pos);});
- if (obj == std::end(objs))
+ auto it = std::ranges::find_if(objs, [drag_pos, mouse_area](auto const& o){return mouse_area.colliding(o->pos);});
+ if (it == std::end(objs))
break;
+ auto obj = *it;
std::swap(obj->col.r, obj->col.g);
std::swap(obj->col.g, obj->col.b);
drag_pos = obj->pos - mouse_to_local(e.x, e.y);