From 185cfdea0fa8e42681c12b36c6f233de502156a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 27 Sep 2021 23:05:48 +0300 Subject: [PATCH] Refactor GetSpatialIndexOffset and fix overflow --- src/openrct2/world/Sprite.cpp | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/openrct2/world/Sprite.cpp b/src/openrct2/world/Sprite.cpp index aefecb5ee3..b3363565e2 100644 --- a/src/openrct2/world/Sprite.cpp +++ b/src/openrct2/world/Sprite.cpp @@ -48,21 +48,18 @@ static void FreeEntity(EntityBase& entity); constexpr size_t GetSpatialIndexOffset(int32_t x, int32_t y) { - size_t index = SPATIAL_INDEX_LOCATION_NULL; - if (x != LOCATION_NULL) - { - x = std::clamp(x, 0, 0xFFFF); - y = std::clamp(y, 0, 0xFFFF); + if (x == LOCATION_NULL) + return SPATIAL_INDEX_LOCATION_NULL; - int16_t flooredX = floor2(x, 32); - uint8_t tileY = y >> 5; - index = (flooredX << 3) | tileY; - } + const auto tileX = std::clamp(x / COORDS_XY_STEP, 0, MAXIMUM_MAP_SIZE_TECHNICAL); + const auto tileY = std::clamp(y / COORDS_XY_STEP, 0, MAXIMUM_MAP_SIZE_TECHNICAL); + const auto index = tileX * MAXIMUM_MAP_SIZE_TECHNICAL + tileY; if (index >= sizeof(gSpriteSpatialIndex)) { return SPATIAL_INDEX_LOCATION_NULL; } + return index; }