C- Indexing x,y,z coordinates in a 1D byte array

谁说我不能喝 提交于 2019-12-01 06:51:52

问题


I want to evaluate the values of the surface to implement a marching tetrahedron algorithm, but I don't understand how to work with .raw unformatted data.

After loading a .raw file with a volume dataset into a 1D byte array, what arithmetic transformation should be applied to get the value associated to X,Y,Z from it? This is the only way I know to load .raw files, could I create a 3D byte array instead of this? How?

int XDIM=256, YDIM=256, ZDIM=256;
const int size = XDIM*YDIM*ZDIM;
bool LoadVolumeFromFile(const char* fileName) {

    FILE *pFile = fopen(fileName,"rb");
   if(NULL == pFile) {
    return false;
   }

   GLubyte* pVolume=new GLubyte[size]; //<- here pVolume is a 1D byte array 
   fread(pVolume,sizeof(GLubyte),size,pFile);
   fclose(pFile);

回答1:


The way you'd index the datum at (x, y, z) is:

pVolume[((x * 256) + y) * 256 + z]

Behind the scenes, this is what the C compiler does for you if you write:

GLuByte array[256][256][256];

array[x][y][z]

It only works that simply because C indexes from 0; if the language indexed from 1, you'd have to revise the calculation to achieve the net result obtained by subtracting one from each of x, y and z before doing the indexing.


Auxilliary Question

Can you generalize the formula for arbitrary dimensions?

Given (where the numeric values don't really matter):

DIMx = 256
DIMy = 128
DIMz =  64

the datum at (x, y, z) in 1D array pData is found at:

pData[((x * DIMx) + y) * DIMy + z]

The value of DIMz serves primarily for validation: 0 <= z < DIMz (using mathematical rather than C notation), and in parallel 0 <= x < DIMx; 0 <= y <= DIMy. The C notation for z is 0 <= z && z < DIMz; repeat mutatis mutandis for x and y.



来源:https://stackoverflow.com/questions/9371322/c-indexing-x-y-z-coordinates-in-a-1d-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!