Search code examples
c++3dgridcube

vertex of a 3d cube grid c++


i want to create a 3d cube grid in c++ but i have a problem: once specified the starting point (xs, ys, zs), the ending point (xe,ye,ze) and the number of elements along the three axis..i want to identify the eight corners of each cube.. Setting the origin in (0,0,0) and i,j,k the indexes moving along the three axis i know that:

1° corner is at (i,j,k) 2° corner is at (i+1,j,k) 3° corner is at (i,j+1,k)

and so on..

I don't have an idea on how to take this triples of value and identify one single point inside the three "for loops" on all the elements... Please help me :)


Solution

  • First define a simple struct point3D:

    typedef struct {
    
      float x;
      float y;
      float z;
    } point3D;
    

    I wrote this to generate the grid:

    //Compute edge sizes 
    float x_size = xe - xs;
    float y_size = ye - ys;
    float z_size = ze - zs;
    
    //Compute steps
    float x_step = x_size/n_step;
    float y_step = y_size/n_step;
    float z_step = z_size/n_step;
    
    //Points per edge (including ending point)
    int n = n_step + 1;
    
    //Alloc grid (you can use malloc if you prefer)
    point3D grid[n*n*n];
    
    for (int i = 0; i < n; i++) { //move on x axis
    
      for (int j = 0; j < n; j++) { //move on y axis
    
        for (int k = 0; k < n; k++) { //move on z axis
    
          point3D p;
          p.x = xs + x_step * i;
          p.y = ys + y_step * j;
          p.z = zs + z_step * k;
          grid[i+n*j+n*n*k] = point3D;
        } 
      }
    }
    

    To take the 8 corner points use:

    point3D corner = grid[n_step*x + n*n_step*y + n*n*n_step*z];
    

    with:

       (x, y, z)
    1: (0, 0, 0)
    2: (0, 0, 1)
    3: (0, 1, 0)
    4: (0, 1, 1)
    5: (1, 0, 0)
    6: (1, 0, 1)
    7: (1, 1, 0)
    8: (1, 1, 1)