I understand the concept but I am having trouble implementing the looping logic behind a 2D subdivide. I have a 2d array representing a grid with the corners seeded. I believe I need 3 loops. 1 to loop for the number of subdivide iterations. A second one for each column in the row, and a third for each row.
This is what I have. It shows the results of the top-left square subdivide. That is why the row and column loops only once. If i get the basic logic the rest should be cake. However the loop does not work on the third iteration. I pretty sure the loop needs to be more complex.
Iterations is a manually set variable.
// iterate though subdivision levels
for(i = 1; i <= iterations; i++) { // iteration
// iterate through each row
for(row = 1; row <= 1; row += size / i ) { // row
// iterate through each column and subdivide
for(col = 1; col <= 1; col += size / i) { // column
//*** ONLY SHOWING THE FIRST SUBDIVIDE OF EACH ITERATION ***//
// Math.pow(2, iterations) / 2 / i = 1
// i = 1, iteration = 1
heightmap[0][1] = (heightmap[0][0] + heightmap[0][2]) / 2;
// Math.pow(2, iterations) / 2 / i = 2
// i = 1, iterations = 2
heightmap[0][2] = (heightmap[0][0] + heightmap[0][4]) / 2;
// Math.pow(2, iterations) / 2 / i = 4
// i = 1, iterations = 3
heightmap[0][4] = (heightmap[0][0] + heightmap[0][8]) / 2;
// if iterations == 1, i != 2
// Math.pow(2, iterations) / 2 / i = 1
// i = 2, iterations = 2
heightmap[0][1] = (heightmap[0][0] + heightmap[0][2]) / 2;
// Math.pow(2, iterations) / 2 / i = 2
// i = 2, iterations = 3
heightmap[0][2] = (heightmap[0][0] + heightmap[0][4]) / 2;
// if iterations == 1 or 2, i != 3
// Math.pow(2, iterations) / 2 / i = 4/3 != 1
// i = 3, iterations = 3
heightmap[0][1] = (heightmap[0][0] + heightmap[0][2]) / 2;
}
}
}
If it helps this is what I used for a 1D subdivide.
// increase the number of segments
for(var i = 1; i < size; i *= 2){
// iterate through each segment calculating the center point
for(var j = (size / i) / 2; j < size; j += size / i){
points[j] = ((points[j - (size / i) / 2] + points[j + (size / i) / 2]) / 2);
}
}