From 5a92a6817378f69785b77bb9993c9c950d6e0eb9 Mon Sep 17 00:00:00 2001
From: mekolat <mekolat@users.noreply.github.com>
Date: Sat, 23 Apr 2016 14:59:48 -0400
Subject: dispose orphan puppet if the parent is gone

---
 src/map/npc.cpp | 34 +++++++++++++++++++++++++++++++++-
 1 file changed, 33 insertions(+), 1 deletion(-)

diff --git a/src/map/npc.cpp b/src/map/npc.cpp
index 47bf820..3eb13b3 100644
--- a/src/map/npc.cpp
+++ b/src/map/npc.cpp
@@ -366,6 +366,12 @@ void npc_eventtimer(TimerData *, tick_t, BlockId id, NpcEvent data)
         return;
     }
 
+    if (nd->scr.parent && map_id2bl(nd->scr.parent) == nullptr)
+    {
+        npc_free(nd);
+        return;
+    }
+
     if (nd->scr.event_needs_map)
     {
         int xs = nd->scr.xs;
@@ -436,6 +442,12 @@ void npc_timerevent(TimerData *, tick_t tick, BlockId id, interval_t data)
     assert (nd->npc_subtype == NpcSubtype::SCRIPT);
     assert (nd->scr.next_event != nd->scr.timer_eventv.end());
 
+    if (nd->scr.parent && map_id2bl(nd->scr.parent) == nullptr)
+    {
+        npc_free(nd);
+        return;
+    }
+
     nd->scr.timertick = tick;
     const auto te = nd->scr.next_event;
     // nd->scr.timerid = nullptr;
@@ -606,6 +618,13 @@ int npc_event(dumb_ptr<map_session_data> sd, NpcEvent eventname,
                     eventname);
         return 0;
     }
+
+    if (nd->scr.parent && map_id2bl(nd->scr.parent) == nullptr)
+    {
+        npc_free(nd);
+        return 0;
+    }
+
     if (sd)
     {
         if (nd->scr.event_needs_map)
@@ -774,7 +793,13 @@ int npc_click(dumb_ptr<map_session_data> sd, BlockId id)
             npc_event_dequeue(sd);
             break;
         case NpcSubtype::SCRIPT:
-            sd->npc_pos = run_script(ScriptPointer(script_or_parent(nd->is_script()), 0), sd->bl_id, id);
+            dumb_ptr<npc_data_script> nds = nd->is_script();
+            if (nds->scr.parent && map_id2bl(nds->scr.parent) == nullptr)
+            {
+                npc_free(nds);
+                return 1;
+            }
+            sd->npc_pos = run_script(ScriptPointer(script_or_parent(nds), 0), sd->bl_id, id);
             break;
     }
 
@@ -808,6 +833,13 @@ int npc_scriptcont(dumb_ptr<map_session_data> sd, BlockId id)
         return 0;
     }
 
+    if (nd->is_script()->scr.parent &&
+        map_id2bl(nd->is_script()->scr.parent) == nullptr)
+    {
+        npc_free(nd);
+        return 0;
+    }
+
     sd->npc_pos = run_script(ScriptPointer(script_or_parent(nd->is_script()), sd->npc_pos), sd->bl_id, id);
 
     return 0;
-- 
cgit v1.2.3-70-g09d2