From fe5976c4250b42a9b139ed2b347f54e152e96492 Mon Sep 17 00:00:00 2001 From: John McCardle Date: Sun, 6 Jul 2025 00:45:01 -0400 Subject: [PATCH] feat: Add Entity.die() method for lifecycle management closes #30 - Remove entity from its grid's entity list - Clear grid reference after removal - Safe to call multiple times (no-op if not on grid) - Works with shared_ptr entity management --- src/UIEntity.cpp | 28 ++++++++++++++++++++++++++++ src/UIEntity.h | 1 + 2 files changed, 29 insertions(+) diff --git a/src/UIEntity.cpp b/src/UIEntity.cpp index 172dded..8f825dd 100644 --- a/src/UIEntity.cpp +++ b/src/UIEntity.cpp @@ -1,6 +1,7 @@ #include "UIEntity.h" #include "UIGrid.h" #include "McRFPy_API.h" +#include #include "PyObjectUtils.h" #include "PyVector.h" @@ -323,9 +324,36 @@ int UIEntity::set_float_member(PyUIEntityObject* self, PyObject* value, void* cl return 0; } +PyObject* UIEntity::die(PyUIEntityObject* self, PyObject* Py_UNUSED(ignored)) +{ + // Check if entity has a grid + if (!self->data || !self->data->grid) { + Py_RETURN_NONE; // Entity not on a grid, nothing to do + } + + // Remove entity from grid's entity list + auto grid = self->data->grid; + auto& entities = grid->entities; + + // Find and remove this entity from the list + auto it = std::find_if(entities->begin(), entities->end(), + [self](const std::shared_ptr& e) { + return e.get() == self->data.get(); + }); + + if (it != entities->end()) { + entities->erase(it); + // Clear the grid reference + self->data->grid.reset(); + } + + Py_RETURN_NONE; +} + PyMethodDef UIEntity::methods[] = { {"at", (PyCFunction)UIEntity::at, METH_O}, {"index", (PyCFunction)UIEntity::index, METH_NOARGS, "Return the index of this entity in its grid's entity collection"}, + {"die", (PyCFunction)UIEntity::die, METH_NOARGS, "Remove this entity from its grid"}, {NULL, NULL, 0, NULL} }; diff --git a/src/UIEntity.h b/src/UIEntity.h index 9d605f2..5531390 100644 --- a/src/UIEntity.h +++ b/src/UIEntity.h @@ -53,6 +53,7 @@ public: static PyObject* at(PyUIEntityObject* self, PyObject* o); static PyObject* index(PyUIEntityObject* self, PyObject* Py_UNUSED(ignored)); + static PyObject* die(PyUIEntityObject* self, PyObject* Py_UNUSED(ignored)); static int init(PyUIEntityObject* self, PyObject* args, PyObject* kwds); static PyObject* get_position(PyUIEntityObject* self, void* closure);