2014-12-06 44 views
1

我有一個展平的3D數組,代表我試圖優化的程序網格的頂點索引。我創建數組,像這樣:展平的3D陣列內部值

int* vertIndices = new int[WIDTH * HEIGHT * DEPTH]; 

,並添加到陣列

vertIndices[x + WIDTH * (y + HEIGHT * z)] = vertIndex; 

的問題是,我只需要跟蹤頂點的網格的表面上。內部頂點不會被創建。

因此,我創建了許多浪費的整數,永遠不會使用。

這裏是通過與WIDTH網眼的vertIndices陣列的環:7,高度:7和深淺度:7

enter image description here

所有這些-1163005939值是將位於內部頂點的網格,但不會被創建。

我的問題是如何提高公式

x + WIDTH * (y + HEIGHT * z) 

忽略內在價值。

謝謝!

回答

1

我想你不會在公式中引入某種條件。類似這樣的:

int getIndex(int x, int y, int z) { 
    //First get the amount of points in all layers before this z layer. 
    int beforeZ = (z) ? WIDTH*HEIGHT + (z - 1)*2*(WIDTH + HEIGHT - 2) : 0; 

    //Then get the amount of points within this layer before this line. 
    int beforeY = (y) ? WIDTH + 2*(y - 1) : 0; 
    if(z == 0 || z == DEPTH - 1) beforeY = y*WIDTH; 

    //And finally the amount of points within this line before this point. 
    int beforeX = (x) ? 1 : 0; 
    if(z == 0 || z == DEPTH - 1 || y == 0 || y == HEIGHT - 1) beforeX = x; 

    //Return the amount of points before this one. 
    return beforeZ + beforeY + beforeX; 
} 

我承認這有點難看,但我認爲它相當接近你能得到的最好結果。至少如果你不想創建某種匹配座標到索引的查找表,反之亦然。當然,這樣的查找表將是可處理任何情況的真正的大型槍,具有相當顯着的內存使用和可能較慢的操作的缺點。