【发布时间】:2012-12-22 07:31:24
【问题描述】:
我正在尝试将 (x,y,z) 坐标的 3 维数组展平为展平数组。
所以here 它基本上说解决方案是;
elements[x][y][z] = Tiles[x + y*WIDTH + Z*WIDTH*DEPTH]
这对我来说都很好,除了上面那个在迭代时优先考虑 x 坐标。
问题是,当我迭代数组时,我主要是线性访问 y 值。给出一个想法,我所有的迭代都像
for (int x = -someXVal; x <= someXVal; x++)
{
for (int z = -someZVal; z <= someZVal; z++)
{
for (int y = -someYVal; y < someYVal; y++ )
{
所以我想在扁平化列表中优先考虑 y 坐标,以便我的线性 y 坐标读/写性能更好。
我在这里进一步发现了一些有趣的read,他基本上使用圆形扁平数组(是的,我还需要我的数组是圆形的)。
为了计算指向 x,y,z 坐标的指针,他使用以下函数;
Public Shared Function GetPTR(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer) As Integer
Dim bx, bz As Integer
bx = x Mod BlockBuffWidth
If bx < 0 Then
bx += BlockBuffWidth
End If
bz = z Mod BlockBuffWidth
If bz < 0 Then
bz += BlockBuffWidth
End If
Return bx * BMX + bz * BMZ + y
End Function
我真的不确定他是如何计算 BlockBuffWidth、BMX 和 BMZ 的。
以下代码是我想出的;
/// <summary>
/// Flatten offset x step to advance next block in x direction.
/// </summary>
public static readonly int XStep = CacheLenghtInBlocks*Chunk.HeightInBlocks;
/// <summary>
/// Flatten offset z step to advance next block in z direction.
/// </summary>
public static readonly int ZStep = Chunk.HeightInBlocks;
public static int BlockIndexByWorldPosition(int x, byte y, int z)
{
var wrapX = x%CacheWidthInBlocks;
if (wrapX < 0)
wrapX += CacheWidthInBlocks;
var wrapZ = z%CacheLenghtInBlocks;
if (wrapZ < 0)
wrapZ += CacheLenghtInBlocks;
var flattenIndex = wrapX * XStep + wrapZ * ZStep + y;
return flattenIndex;
}
显然我的代码没有按预期工作。欢迎任何想法。
【问题讨论】:
-
obviously my code doesn't work as expected请详解。
标签: c# arrays flatten circular-buffer