Find corner points of a cube that has a random point in a 3D grid
-
07-06-2021 - |
Question
I have coordinates (x,y,z) for a evenly spaced 3D grid. Given a random 3D point (x,y,z) somewhere on the grid, how to find which cube has the point. I need to know the 8 corners of the cube.
I have the grid point data in a list of vectors in c++.
Thanks.
Solution
Assuming equal length for the grid cubes in all dimentions, you can get the coordinate closest to ohe origo by calculating
gx = x - x%l;
gy = y - y%l;
gz = z - z%l;
Where gx
, gy
, gz
are the grid cube coordinates closest to the origo (I'm assuming x
,y
,z
>=0 here), %
is the modulus operator and l
is the length of the grid cubes.
Note: You can perform the calculations this way as well: gx = static_cast<int>(x)/l*l;
(static_cast<>
to account for non-integer x
)
Then the 8 corners of the grid cube (x, y, z)
falls into are:
(gx, gy, gz)
(gx+l, gy, gz)
(gx, gy+l, gz)
(gx, gy, gz+l)
(gx+l, gy+l, gz)
(gx+l, gy, gz+l)
(gx, gy+l, gz+l)
(gx+l, gy+l, gz+l)
OTHER TIPS
Assuming the origin of the grid is at (0,0,0)
, you should divide (x,y,z)
by the grid's size.
Then you should round the result and multiply it by the grid's size, that is:
(nx, ny, nz) = [(x,y,z) / grid_size] * grid_size
where [x]
is the greatest integer n
, so that n<=x
(in practice, you should just cast the result of floating-point operation to an int
). The points you're searching for are:
(nx, ny, nz)
(nx+grid_size, ny, nz)
(nx, ny+grid_size, nz)
(nx, ny, nz+grid_size)
(nx+grid_size, ny+grid_size, nz)
(nx+grid_size, ny, nz+grid_size)
(nx, ny+grid_size, nz+grid_size)
(nx+grid_size, ny+grid_size, nz+grid_size)