Skip to content

Commit 420fbe3

Browse files
positiveModulo
1 parent 20cd336 commit 420fbe3

1 file changed

Lines changed: 11 additions & 8 deletions

File tree

CMap.cpp

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -983,6 +983,14 @@ void CMap::setKeyboardData(const SDL_KeyboardEvent& key)
983983
}
984984
}
985985

986+
namespace {
987+
constexpr int positiveModulo(int value, int divisor)
988+
{
989+
// C++ % can be negative for negative inputs; this always returns [0, divisor-1]
990+
return ((value % divisor) + divisor) % divisor;
991+
}
992+
}
993+
986994
void CMap::storeVerticesFromMouse(Position mousePos, Uint8 /*MouseState*/)
987995
{
988996
// if user raises or reduces the height of a vertex, don't let the cursor jump to another vertex
@@ -995,16 +1003,11 @@ void CMap::storeVerticesFromMouse(Position mousePos, Uint8 /*MouseState*/)
9951003
// get X
9961004
// following out commented lines are the correct ones, but for tolerance (to prevent to early jumps of the cursor)
9971005
// we subtract "triangleWidth/2" Xeven = (mousePos.x + displayRect.left) / triangleWidth;
998-
Xeven = (mousePos.x + displayRect.left - triangleWidth / 2) / triangleWidth;
999-
Xeven = ((Xeven % map->width) + map->width) % map->width;
1006+
Xeven = positiveModulo((mousePos.x + displayRect.left - triangleWidth / 2) / triangleWidth, map->width);
10001007
// Add rows are already shifted by triangleWidth / 2
1001-
Xodd = (mousePos.x + displayRect.left) / triangleWidth;
1002-
// Xodd = (mousePos.x + displayRect.left) / triangleWidth;
1003-
Xodd = ((Xodd % (map->width - 1)) + (map->width - 1)) % (map->width - 1);
1008+
Xodd = positiveModulo((mousePos.x + displayRect.left) / triangleWidth, map->width - 1);
10041009

1005-
MousePosY = mousePos.y + displayRect.top;
1006-
// correct mouse position Y if displayRect is outside map edges
1007-
MousePosY = ((MousePosY % map->height_pixel) + map->height_pixel) % map->height_pixel;
1010+
MousePosY = positiveModulo(mousePos.y + displayRect.top, map->height_pixel);
10081011

10091012
// get Y
10101013
for(int j = 0; j < map->height; j++)

0 commit comments

Comments
 (0)