From 433b012715fcc216ce4dc9b73aea9f631ce856be Mon Sep 17 00:00:00 2001 From: Klemen Plestenjak Date: Wed, 22 Nov 2023 08:47:29 +0100 Subject: [PATCH] Fix iteration --- engine/breeze/utils/spatial_grid.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/engine/breeze/utils/spatial_grid.c b/engine/breeze/utils/spatial_grid.c index 3342344..2a8230e 100644 --- a/engine/breeze/utils/spatial_grid.c +++ b/engine/breeze/utils/spatial_grid.c @@ -94,12 +94,17 @@ static BzSpatialGridIndex calculateGridIndex(BzSpatialGrid *grid, f32 posX, f32 i32 minY = (i32) floorf(posY); i32 maxX = (i32) ceilf(posX + sizeX); i32 maxY = (i32) ceilf(posY + sizeY); - return (BzSpatialGridIndex) { + BzSpatialGridIndex index = { (i16) (minX / grid->cellWidth), (i16) (minY / grid->cellHeight), (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; + return index; } BzSpatialGridID bzSpatialGridInsert(BzSpatialGrid *grid, void *data, f32 posX, f32 posY, f32 sizeX, f32 sizeY) { @@ -188,16 +193,17 @@ BzSpatialGridIter bzSpatialGridIter(BzSpatialGrid *grid, f32 posX, f32 posY, f32 } bool bzSpatialGridQueryNext(BzSpatialGridIter *it) { BzSpatialGridID **cell = getCell(it->_grid, it->_x, it->_y); - if (it->_cellIdx >= bzArraySize(*cell)) { + while (it->_cellIdx >= bzArraySize(*cell)) { it->_cellIdx = 0; it->_x++; if (it->_x > it->index.maxX) { - if (it->_y > it->index.maxX) { - it->_y++; - if (it->_y > it->index.maxY) - return false; + it->_x = it->index.minX; + it->_y++; + if (it->_y > it->index.maxY) { + return false; } } + cell = getCell(it->_grid, it->_x, it->_y); } BzSpatialGridID id = bzArrayGet(*cell, it->_cellIdx);