Convolution filters are usually applied via image processing software, but we can use the same principles to change a grid's influence given a unit's value and its surroundings. In this recipe, we will explore a couple of algorithms to modify a grid using matrix filters.
It is important to have grasped the concept of influence maps before implementing this recipe, so that you can understand the context in which it is applied.
We will implement the Convolve
function:
Convolve
function:public static void Convolve( float[,] matrix, ref float[,] source, ref float[,] destination) { // next steps }
int matrixLength = matrix.GetLength(0); int size = (int)(matrixLength – 1) / 2; int height = source.GetLength(0); int width = source.GetLength(1); int I, j, k, m;
for (i = 0; i < width–- size; i++) { for (j = 0; j < height–- size; j++) { // next steps } }
destination[i, j] = 0f; for (k = 0; k < matrixLength; k++) { for (m = 0; m < matrixLength; m++) { int row = i + k–- size; int col = j + m–- size; float aux = source[row, col] * matrix[k,m]; destination[i, j] += aux; } }
We create a new grid to be swapped with the original source grid after the application of the matrix filter on each position. Then, we iterate over each position that is to be created as a destination grid and compute its result, taking the original grid's value and applying the matrix filter to it.
It is important to note that the matrix filter must be an odd-square array for the algorithm to work as expected.
The following ConvolveDriver
function helps us iterate using the Convolve
function implemented previously:
ConvolveDriver
function:public static void ConvolveDriver( float[,] matrix, ref float[,] source, ref float[,] destination, int iterations) { // next steps }
float[,] map1; float[,] map2; int i;
if (iterations % 2 == 0) { map1 = source; map2 = destination; } else { destination = source; map1 = destination; map2 = source; }
for (i = 0; i < iterations; i++) { Convolve(matrix, ref source, ref destination); float[,] aux = map1; map1 = map2; map2 = aux; }