From 982fdff528ddd4ffe744b8f5ab2d47b4d516bb30 Mon Sep 17 00:00:00 2001 From: jacob1 Date: Mon, 21 Feb 2022 23:20:43 -0500 Subject: [PATCH] Add safeguard to try_move to ensure we don't write to out of bounds pmap This is a follow up to this crash fix - 0ed8d0a0be2556f2337ec0acc2cf4f7e67bfb5b3 This may possibly fix other crashes users occasionally experience, especially in the case of high velocity particles with loop edge mode on. Even so, there are other bugs at play, as a crash here can't be triggered if pmap is in a correct state --- src/simulation/Simulation.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/simulation/Simulation.cpp b/src/simulation/Simulation.cpp index 8f5c50098..2bb286ff4 100644 --- a/src/simulation/Simulation.cpp +++ b/src/simulation/Simulation.cpp @@ -2863,9 +2863,14 @@ int Simulation::try_move(int i, int x, int y, int nx, int ny) if (ID(pmap[ny][nx]) == ri) pmap[ny][nx] = 0; - parts[ri].x += float(x-nx); - parts[ri].y += float(y-ny); - pmap[(int)(parts[ri].y+0.5f)][(int)(parts[ri].x+0.5f)] = PMAP(ri, parts[ri].type); + parts[ri].x += float(x - nx); + parts[ri].y += float(y - ny); + int rx = int(parts[ri].x + 0.5f); + int ry = int(parts[ri].y + 0.5f); + // This check will never fail unless the pmap array has already been corrupted via another bug + // In that case, r's position is inaccurate (not actually at nx/ny) and rx/ry may be out of bounds + if (InBounds(rx, ry)) + pmap[ry][rx] = PMAP(ri, parts[ri].type); } return 1; }