在原始N*M的数组A中(该数组可以理解为规则格子,各维度的增量均为常数)内部构建一个比其小的数组B,要求数组B与A格子点重合,如图所示:
对于三维空间的数组来讲,也可以用该方法来做
首先建立grid_x *grid_y *grid_z的数组,为了减少循环我们使用一维数组存储三维信息
for (int grid_z = 0; grid_z < grid[2]; grid_z++)//Z-方向
{
for (int grid_y = 0; grid_y < grid[1]; grid_y++)//Y-方向
{
for (int grid_x = 0; grid_x < grid[0]; grid_x++)//X-方向
{
//grid_x + grid[0] * grid_y + grid[0] * grid[1] * grid_z为三维坐标点在一维数组中的索引值
grid_point[grid_x + grid[0] * grid_y + grid[0] * grid[1] * grid_z] = vec( grid_x*SampleSpacing + topleft[0], grid_y*SampleSpacing + topleft[1], grid_z*SampleSpacing + topleft[2] );
}
}
}
//三维空间中数组B的最小单元的位置(grid_id_xmin,grid_id_ymin,grid_id_zmin)
vector<vector<vec>>Save_B_arr;
int grid_id_xmin, grid_id_ymin, grid_id_zmin;
int grid_id_xmax, grid_id_ymax, grid_id_zmax;
//grid_id_add 相应的一维数组遍历的起始格子ID
int grid_id_add = grid_id_xmin + grid[0] * grid_id_ymin + grid[0] * grid[1] * grid_id_zmin;
//x_cube_num x方向格子数量
//y_cube_num y方向格子数量
//z_cube_num z方向格子数量
x_cube_num = grid_id_xmax - grid_id_xmin;
y_cube_num = grid_id_ymax - grid_id_ymin;
z_cube_num = grid_id_zmax - grid_id_zmin;
//B数组总共的格子数量
int sizenum = x_cube_num*y_cube_num*z_cube_num;
//遍历每一个B的格子点,从0开始,但是内部位置应该从B在一维数组的最小格子点位置算起
for (int gi = 0; gi < /*grid_point.size()*/sizenum; ++gi)
{
//gi % (x_cube_num*y_cube_num)的目的是如果gi不是从第0层开始,应该先对其取余,让其算在第0层,然后再/x_cube_num,计算第y行;
int ynum = gi % (x_cube_num*y_cube_num) / x_cube_num;
//计算在第z层
int znum = gi / x_cube_num/y_cube_num;
//grid_id 为一维格子点ID,前面的那两步实际上是在数组B上计算的,这边需要再转换为一维数组具体讲解如图:
int grid_id = gi + ynum* (grid[0] - x_cube_num) + znum*((grid[0]) * (grid[1]) - x_cube_num*y_cube_num) + grid_id_add;
Save_B_arr.push_back(grid_point[grid_id]);
}
解释下这块内容;
int grid_id = gi + ynum* (grid[0] - x_cube_num) + znum*((grid[0]) *
(grid[1]) - x_cube_num*y_cube_num) + grid_id_add;
当gi从0增加到5时走完图中红色的格子,gi++应该要跳一层跳到橙色位置,如果直接让grid_id++很显然是不对的,因为grid_id++所对应的点应该为蓝色格子点,那应该怎么做呢?所以这边考虑到应该让格子跳一层,综合考虑为ynum* (grid[0] - x_cube_num)
那如果遍历完一层怎么跳上一层呢?这边需要考虑z值。本身这边浅蓝色格子为需要增加的格子,即:
znum*((grid[0]) * (grid[1]) - (grid[0])((y_cube_num-1) )
怎么和之前写的不一致呢
znum((grid[0]) (grid[1]) - x_cube_numy_cube_num)
这是因为在y那边 ynum* (grid[0] - x_cube_num) 多加了深蓝色部分,那我们这边再减去就没问题了刚好抵消,白色那一行是因为本来应该有蓝色的但是没有绿的所以刚好也抵消了