From 4e402a77211b40a0d9b1ab62e42bd285d811d803 Mon Sep 17 00:00:00 2001
From: Tim Felgentreff <timfelgentreff@gmail.com>
Date: Mon, 14 Feb 2022 20:06:45 +0100
Subject: [PATCH] fix a crash in select script functions

---
 src/game/trigger.cpp            |  7 +++++++
 src/stratagus/script_player.cpp | 13 +++++++++++++
 src/unit/script_unit.cpp        |  6 ++++++
 3 files changed, 26 insertions(+)

diff --git a/src/game/trigger.cpp b/src/game/trigger.cpp
index 89cea89d4..53acc521b 100644
--- a/src/game/trigger.cpp
+++ b/src/game/trigger.cpp
@@ -178,6 +178,13 @@ static int CclGetNumUnitsAt(lua_State *l)
 	CclGetPos(l, &minPos.x, &minPos.y, 3);
 	CclGetPos(l, &maxPos.x, &maxPos.y, 4);
 
+	if (minPos.x > maxPos.x) {
+		std::swap(minPos.x, maxPos.x);
+	}
+	if (minPos.y > maxPos.y) {
+		std::swap(minPos.y, maxPos.y);
+	}
+
 	std::vector<CUnit *> units;
 
 	Select(minPos, maxPos, units);
diff --git a/src/stratagus/script_player.cpp b/src/stratagus/script_player.cpp
index 681f79aa6..20589a931 100644
--- a/src/stratagus/script_player.cpp
+++ b/src/stratagus/script_player.cpp
@@ -361,6 +361,13 @@ static int CclChangeUnitsOwner(lua_State *l)
     Vec2i pos2;
     CclGetPos(l, &pos1.x, &pos1.y, 1);
     CclGetPos(l, &pos2.x, &pos2.y, 2);
+	if (pos1.x > pos2.x) {
+		std::swap(pos1.x, pos2.x);
+	}
+	if (pos1.y > pos2.y) {
+		std::swap(pos1.y, pos2.y);
+	}
+
     const int oldp = LuaToNumber(l, 3);
     const int newp = LuaToNumber(l, 4);
     std::vector<CUnit *> table;
@@ -450,6 +457,12 @@ static int CclGiveUnitsToPlayer(lua_State *l)
 			Vec2i pos2;
 			CclGetPos(l, &pos1.x, &pos1.y, 3);
 			CclGetPos(l, &pos2.x, &pos2.y, 4);
+			if (pos1.x > pos2.x) {
+				std::swap(pos1.x, pos2.x);
+			}
+			if (pos1.y > pos2.y) {
+				std::swap(pos1.y, pos2.y);
+			}
 			if (any) {
 				Select(pos1, pos2, table, HasSamePlayerAs(Players[oldp]));
 			} else if (onlyUnits) {
diff --git a/src/unit/script_unit.cpp b/src/unit/script_unit.cpp
index 31cda4480..9d8d595dc 100644
--- a/src/unit/script_unit.cpp
+++ b/src/unit/script_unit.cpp
@@ -1024,6 +1024,12 @@ static int CclKillUnitAt(lua_State *l)
 	Vec2i pos2;
 	CclGetPos(l, &pos1.x, &pos1.y, 4);
 	CclGetPos(l, &pos2.x, &pos2.y, 5);
+	if (pos1.x > pos2.x) {
+		std::swap(pos1.x, pos2.x);
+	}
+	if (pos1.y > pos2.y) {
+		std::swap(pos1.y, pos2.y);
+	}
 
 	std::vector<CUnit *> table;