From 7469a6271b4b1b9e3bfcc7bd81d817cfed0a88c2 Mon Sep 17 00:00:00 2001
From: Lactozilla <jp6781615@gmail.com>
Date: Thu, 14 Mar 2024 00:59:49 -0300
Subject: [PATCH] Fix #1219

---
 src/p_maputl.c | 24 ++++++++++++++++++------
 1 file changed, 18 insertions(+), 6 deletions(-)

diff --git a/src/p_maputl.c b/src/p_maputl.c
index 82b8647152..242bc559e8 100644
--- a/src/p_maputl.c
+++ b/src/p_maputl.c
@@ -1026,23 +1026,35 @@ boolean P_BlockLinesIterator(INT32 x, INT32 y, boolean (*func)(line_t *))
 //
 boolean P_BlockThingsIterator(INT32 x, INT32 y, boolean (*func)(mobj_t *))
 {
-	mobj_t *mobj;
-	blocknode_t *block;
+	mobj_t *bnext = NULL;
+	blocknode_t *block, *next = NULL;
 
 	if (x < 0 || y < 0 || x >= bmapwidth || y >= bmapheight)
 		return true;
 
 	// Check interaction with the objects in the blockmap.
-	for (block = blocklinks[y*bmapwidth + x]; block; block = block->mnext)
+	for (block = blocklinks[y*bmapwidth + x]; block; block = next)
 	{
-		mobj = block->mobj;
+		next = block->mnext;
+		if (next)
+			P_SetTarget(&bnext, next->mobj); // We want to note our reference to bnext here in case it is MF_NOTHINK and gets removed!
 
-		if (!func(mobj))
+		if (!func(block->mobj))
+		{
+			P_SetTarget(&bnext, NULL);
 			return false;
-		if (P_MobjWasRemoved(tmthing)) // func just broke blockmap chain, cannot continue.
+		}
+
+		if (P_MobjWasRemoved(tmthing) // func just popped our tmthing, cannot continue.
+		|| (bnext && P_MobjWasRemoved(bnext))) // func just broke blockmap chain, cannot continue.
+		{
+			P_SetTarget(&bnext, NULL);
 			return true;
+		}
 	}
 
+	P_SetTarget(&bnext, NULL);
+
 	return true;
 }
 
-- 
GitLab