Indexing an 3D array into 1D array ?

Monkey Forums/Monkey Programming/Indexing an 3D array into 1D array ?

Rushino(Posted 2012) [#1]
Hello,

I did some research but it seem that there many ways of doing this and ive also found some wierd indexing calculation. We all know that 2D indexing would result in doing x + y * WIDTH. Then i wonder what would be for 3D array (providing that you can change the width, height and depth of the 3d array when you actually create the array) ?

What i have so far is initializing the 1D array which seem the way to do this

Self.data = New T[width * height * depth]


1-Then for indexing ive found this. Can anyone confirm this is the correct way for indexing ? Im just wondering what mean 3+k. I can be wrong but does it actually get you right after the rows and col indexing so the k would be the depth ?


Self.data[(i*width+j)*3+k];  ' Equivalent to Self.data[i][j][k].


2-So if i am right 'i' is the rows, 'j' the cols and 'k' the depth.

3- What would be the equivalent to Self.data[k][j][i]. Can we just switch the variables ? or it require a new formulea ?

Thanks!


Rushino(Posted 2012) [#2]
After some tests.. i found that this is working :

Self.data[row + Self.width * (col + Self.height * layer)]


It is rather easy to understand too.


Gerry Quinn(Posted 2012) [#3]
I would do something like this:

Const XSIZE:Int = 60
Const YSIZE:Int = 40
Const ZSIZE:Int = 4
Const XDELTA:Int = 1
Const YDELTA:Int = XSIZE
Const ZDELTA:Int = XSIZE * YSIZE

' File arr:Tile[]
arr = New Tile[ XSIZE * YSIZE * ZSIZE ]

Method GetIndex:Int( x:Int, y:Int, z:Int )
	Return x + y * YDELTA + z * ZDELTA
End


It can be done in different ways depending on how your array is organised.

If you are not comfortable with this sort of arithmetic, though, I'd recommend the 3D array.


Edit: I see you aleady figured out something equivalent to the above.


Rushino(Posted 2012) [#4]
Well i made a Get and Set which i am using everywhere so actually i can change this anytime without a big cost at the maintenance. But i am rather confortable with it. :)

Thanks through for your exemple.


Gerry Quinn(Posted 2012) [#5]
Remember that the benefits of 1D arrays come from being able to rapidly access cells near (or in any fixed position in relation to) a particular cell. If you are calling GetValue( x, y, z ) on a 1D array it is probably no faster than arr[ x ][ y ][ z ]. The benefit of a 1D array is that if you have a cell at 'index', then the eight nearest cells are each at index plus a constant offset. And if you are saving the cell index you need only save one value instead of three. Unless you're using this kind of thing there's no speed-up.


Rushino(Posted 2012) [#6]
However, for saving and loading the map i find the 1D array useful because i don't have to create 3 loops but only one. I wonder if there any performance gain here but still make it easy.