fix: objects being parented to themselves/descendents of themselves

This commit is contained in:
maelstrom 2025-02-01 14:18:53 +01:00
parent f9683a69be
commit 211e667351
2 changed files with 17 additions and 2 deletions

View file

@ -38,7 +38,19 @@ Instance::Instance(InstanceType* type) {
Instance::~Instance () {
}
void Instance::SetParent(std::optional<std::shared_ptr<Instance>> newParent) {
// TODO: Test this
bool Instance::ancestryContinuityCheck(std::optional<std::shared_ptr<Instance>> newParent) {
for (std::optional<std::shared_ptr<Instance>> currentParent = newParent; currentParent.has_value(); currentParent = currentParent.value()->GetParent()) {
if (currentParent.value() == this->shared_from_this())
return false;
}
return true;
}
bool Instance::SetParent(std::optional<std::shared_ptr<Instance>> newParent) {
if (!ancestryContinuityCheck(newParent))
return false;
auto lastParent = GetParent();
if (hierarchyPreUpdateHandler.has_value()) hierarchyPreUpdateHandler.value()(this->shared_from_this(), lastParent, newParent);
// If we currently have a parent, remove ourselves from it before adding ourselves to the new one
@ -56,6 +68,7 @@ void Instance::SetParent(std::optional<std::shared_ptr<Instance>> newParent) {
if (hierarchyPostUpdateHandler.has_value()) hierarchyPostUpdateHandler.value()(this->shared_from_this(), lastParent, newParent);
this->OnParentUpdated(lastParent, newParent);
return true;
}
std::optional<std::shared_ptr<Instance>> Instance::GetParent() {

View file

@ -35,6 +35,8 @@ private:
std::vector<std::shared_ptr<Instance>> children;
std::optional<std::vector<std::string>> cachedMemberList;
bool ancestryContinuityCheck(std::optional<std::shared_ptr<Instance>> newParent);
protected:
std::unique_ptr<MemberMap> memberMap;
@ -48,7 +50,7 @@ public:
// Instance is abstract, so it should not implement GetClass directly
virtual InstanceType* GetClass() = 0;
void SetParent(std::optional<std::shared_ptr<Instance>> newParent);
bool SetParent(std::optional<std::shared_ptr<Instance>> newParent);
std::optional<std::shared_ptr<Instance>> GetParent();
inline const std::vector<std::shared_ptr<Instance>> GetChildren() { return children; }