2

我有一些值是多维数组的偏移量,如下所示:

static const int TILE_SIZE = 32;
int Offset2D = (y * TILE_SIZE) + (x * TILE_SIZE);
int Offset3D = (y * TILE_SIZE) + (x * TILE_SIZE) + (z * TILE_SIZE);

现在我想做的是将偏移量转换为 x,y,z 对,如下所示:

void ConvertBack(int offset,int size,int& x,int& y,int& z)
{
    //What's wrong with this code ?
    x = offset / size;
    y = offset % size;
    z = ??; //How to get Z?
}

或者

//Get back offsets from any dimension ?

void ConvertBackComplex(unsigned int offset,int size,int* vector,int len)
{
    for (int i = 0;i < len;i++)
    {
        vector[i] = offset ?... ?
    }
}

......到目前为止,我所有的尝试都失败了......所以我真的很欢迎任何帮助!......

4

3 回答 3

5

首先,我认为您的索引系统有点偏离。排列不同的 x、y 和 z 值的方式可以给出相同的偏移量。因此,首先,假设 TILE_SIZE 是数组的多少个单元格存储给定点的数据:

myArray = new arr[xSize*ySize*zSize*TILESIZE]
int offset2D = (x*ySize*zSize + y*zSize)*TILE_SIZE;
int offset3D = (x*ySize*zSize + y*zSize + z)*TILE_SIZE;

要从偏移中返回 x,y,z,只需执行以下操作:

temp = offset/TILE_SIZE;
x = temp/(ySize*zSize);
y = (temp%(ySize*zSize))/zSize;
z = (temp%(ySize*zSize))%zSize;

对于多个维度:

temp = offset/TILE_SIZE;
sizeProduct = 1;
for(int k=1; k<numDims; ++k)
{
    sizeProduct*=size[k];
}
for(int i=0; i<numDims; ++i)
{
    vector[i]=temp/sizeProduct;
    temp = temp % sizeProduct;
    if((i+1)<numDims)
    {
        sizeProduct/=sizes[i+1];
    }
}

要计算多个维度的数组大小:

int arraySize = TILE_SIZE;
for(int i=0; i<numDims; ++i)
{
    arraySize*=sizes[i];
}

要计算多个维度的数组索引(假设向量是您的坐标数组):

int index =0;
sizeProduct = 1;
for(int k=1; k<numDims; ++k)
{
    sizeProduct*=size[k];
}
for(int i=0; i<numDims; ++i)
{
    index+=sizeProduct*vector[i];
    if((i+1)<numDims)
    {
        sizeProduct/=sizes[i+1];
    }
}
index*=TILE_SIZE;
于 2012-08-24T16:43:00.613 回答
1

假设所有尺寸都很TILE_SIZE长,那么您的偏移计算是错误的。假设我有一个数组a,它模拟了所有维度都TILE_SIZE长的 3d 数组:

int a[TILE_SIZE * TILE_SIZE * TILE_SIZE];

然后p带有坐标的点(x, y, z)会有这样的偏移:

int p_offset = z * (TILE_SIZE * TILE_SIZE)
             + y * (TILE_SIZE)
             + x;

然后逆向计算:

int p_z = p_offset / (TILE_SIZE * TILE_SIZE);
int p_y = (p_offset - p_z * (TILE_SIZE * TILE_SIZE)) / TILE_SIZE;
int p_x = p_offset % TILE_SIZE;

您可以选择不同的维度顺序,(x, y, z)但必须保持一致。

于 2012-08-24T16:40:01.683 回答
1

假设维度从 X 到 Y 到 Z(如 X 表示最低维度):

您不能使用单个函数将 2D 和 3D 偏移计算回坐标。

对于 2D:

void ConvertBack2D(int offset, int x_len, int &x, int &y)
{
    y = offset / x_len;
    x = offset % x_len;
}

对于 3D:

void ConvertBack3D(int offset, int x_len, int y_len, int &x, int &y, int &z)
{
    z = offset / (x_len * y_len);
    y = (offset - (x * x_len * y_len)) / y_len;
    x = (offset - (x * x_len * y_len)) % x_len;
}
于 2012-08-24T17:00:22.950 回答