From 504b5b5f9bec2ec6d06df4f10c5a06c4c30b43d4 Mon Sep 17 00:00:00 2001 From: Klemen Plestenjak Date: Sat, 10 Feb 2024 11:06:41 +0100 Subject: [PATCH] Clamp spatial index to grid size --- engine/breeze/util/spatial_grid.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/engine/breeze/util/spatial_grid.c b/engine/breeze/util/spatial_grid.c index f5de1df..1081de7 100644 --- a/engine/breeze/util/spatial_grid.c +++ b/engine/breeze/util/spatial_grid.c @@ -68,6 +68,7 @@ void *bzSpatialGridGetData(const BzSpatialGrid *grid, BzSpatialGridID id) { static BzSpatialGridID **getCell(const BzSpatialGrid *grid, i32 x, i32 y) { + BZ_ASSERT(x >= 0 && y >= 0 && x < grid->width && y < grid->height); return grid->cells + y * grid->width + x; } @@ -100,10 +101,6 @@ static BzSpatialGridIndex calculateGridIndex(BzSpatialGrid *grid, f32 posX, f32 (i16) (maxX / grid->cellWidth), (i16) (maxY / grid->cellHeight), }; - if (index.minX < 0) index.minX = 0; - if (index.minY < 0) index.minY = 0; - if (index.maxX >= grid->width) index.maxX = grid->width - 1; - if (index.maxY >= grid->height) index.maxY = grid->height - 1; if (index.minX > index.maxX) { i32 tmp = index.minX; @@ -115,6 +112,12 @@ static BzSpatialGridIndex calculateGridIndex(BzSpatialGrid *grid, f32 posX, f32 index.minY = index.maxY; index.maxX = tmp; } + + if (index.minX < 0) index.minX = 0; + if (index.minY < 0) index.minY = 0; + if (index.maxX >= grid->width) index.maxX = grid->width - 1; + if (index.maxY >= grid->height) index.maxY = grid->height - 1; + return index; }