I'm trying to find an efficient way to update a spatial grid which contains information about which object is on which grid cell. The objects move. For example:
···AAA···
···AAA···
···AAA···
·········
The object A occupies 9 cells in the grid. Now it moves down and to the right one position:
·········
····AAA··
····AAA··
····AAA··
The "brute force" approach would remove object A from all cells and then it would add A to the new cells. This however is very inefficient because 4 of the cells involved already contain A. What I would like to do instead is only to operate on the "diff":
···---···
···-··+··
···-··+··
····+++··
This is, adding "A" to the cells with a + and remove it from the cells with a -. Leaving the rest as they are.
A can be considered to be defined by its left,right,top and bottom coordinates:
- Before: l0,r0,t0,b0
- After: l1,r1,t1,b1
The movement can occur in any direction, not just always left and bottom. The object can change in size as it moves, so the "After" could become bigger or smaller than the "Before". "Before" and "After" don't always overlap, the objects can "teleport" around.
I would like to avoid even iterating over cells that are not part of the diff, it at all possible.
I'm implementing this in Lua, but I would appreciate an efficient algorithm in any language that I can translate.