Sign in to follow this  

2D - "Tileset" index to sub-rectangular position calculation

Recommended Posts

PureSnowX    275
Hey forum of!
I'm stopping by for a quick question regarding how to calculate the sub-rectangle position for a tileset?
Say I have a tileset of 512x512 ( 256 worth of 32x32 tiles ) and that in my "map class" I have an array of integers that defines the array index of each tile in each cell.

Having a 1D Tileset is quite easy to work with, it's basically: tile_index * tile_width to get what the part of the whole tileset I should display. Once moving into a tileset of 2D I'm not sure how to go on about it.

I have found this snippet of code that works ( I have integrated it )
( Pseudo-Code )
int frame_col = tile_index % ( texture_width / tile_width );
int frame_row = tile_index / ( texture_width / tile_width );
subRect.setPos( frame_col * tile_width, frame_row * tile_height);

Could someone explain this to me a bit better, why does it work? and possible ( mostly because I'm very interested ) present another way to calculate it?

Share this post

Link to post
Share on other sites
TheUnbeliever    963
You can index a linear array as if it were multidimensional by using a formula like x + y * width. i.e. Skip y rows of width elements, then x elements preceding the one you want on the row you want. Your code just reverses this. Where width is the number of tiles in the texture, and x < width: integer division truncates so (x + y * width) / width = y; % is the modulo operation, which effectively gives you the remainer: (x + y * width) % width = x.

Share this post

Link to post
Share on other sites
PureSnowX    275
I'm not sure I follow, could someone please explain the concept a bit further? I feel that implementing a 2D tileset is somewhat complex? ( Not complex but I'm not sure how "new" people would approach this without that snippet of code ).

I'm having a hard time understanding the math behind it maybe?

Share this post

Link to post
Share on other sites
It's not complex - I'm not very good with math, but I find it easy once I understood it.

To convert a TileX and TileY to an 'index' into your array, you use this:
[CODE]int index = (TileY * TilesetWidth) + TileX;[/CODE]

Let's pretend your tileset is 5 tiles wide and 7 tiles high, and you want to access the 2nd tile on the third row:



To reverse it (to go from the index to X,Y), we divide instead of multiply:
[CODE]int TileX = (index % TilesetWidth);
int TileY = (index / TilesetWidth);[/CODE]

The numbers I'm using (x and y) are in tiles, not pixels. If you want the pixel location of a tile within your tileset, you have to multiply the x,y by the width and height of the tile.

[CODE]int pixelX = (TileX * TileWidth);
int pixelY = (TileY * TileHeight);[/CODE]

Share this post

Link to post
Share on other sites
To further confuse the second image with more scribblings:


The reason we are starting to count at zero is because we are saying "How many cells beyond the first cell", If we are already on the first cell, then we are 0 cells beyond the first cell, so the first cell is cell 0.
This is why we start at zero for things like positions, but we don't start at zero for the widths and the heights. We already [i]are[/i] at the first cell, and we need to know how many cells to move to go to where we want. When we actually [i]want[/i] to first cell, we move 'zero' spaces. Edited by Servant of the Lord

Share this post

Link to post
Share on other sites
PureSnowX    275
int TileX = (index % TilesetWidth);
int TileY = (index / TilesetWidth);
This line, I'm a bit confused, I get that it works, just the %-operator confuses me, how am I supposed to visualize this to myself how it works inside my head?

Also for a system that begins at 0, the formula ( Y * WIDTH ) + X works ( And I can see WHY it works ) but how would it work ( and bare with me since this is a bit important for me to actually understand why it works for the programming-0-first-style ) when everything starts at 1 and not 0?

The formula ( Y * WIDTH ) * X will no longer work for that kind of system, right? ( 0-first = 1,2 and 1-first = 2, 3 which will result in the 1-first to have a single index of 17? ( 3 * 5 ) + 2 = 17 )

Share this post

Link to post
Share on other sites
If for you, everything starts at one, then just subtract 1 before mutliplying.

If x and y start at 1 instead of zero, then you use:
[code]int index = ((TileY-1) * TilesetWidth) + (TileX - 1);[/code]

The x and y we are wanting is, "Assuming you start at the first cell, how many steps do you need to [b]move [/b]to get to where you want?".

If you want to think of the first cell as cell 1 instead of cell 0, you can think of it like this:
"I'm at cell 1, and I want to be at cell 4, so the [b]difference [/b]between cell 1 and 4 is (4 - 1) which is 3, so I need to [b]move [/b]3 steps to get to cell 4"

The % operator is modulus. Think of it like this:
[code]int TileY = (index / TilesetWidth); //Divide index by the width of the tileset. The result is Y, but save the remainder of the division!
int TileX = remainder;[/code]

If it helps you, you could mentally calculate it like this:
[code]int TileY = (index / TilesetWidth);
int TileX = (index - TileY); //Whatever is left from the index, after TileY was calculated.[/code]

In the examples in the earlier posts, if the index is 11, we divide by the TilesetWidth (which is 5), so Y = (11 / 5) which is 2. But it's not an even division! There is still a remainder of 1, and that remainder goes to X. Edited by Servant of the Lord

Share this post

Link to post
Share on other sites
It's the [b]difference[/b] between the place of origin (the cell), and the place you want to be (Third row, second column).

The difference between the second column and the first column is one column (2 - 1 = 1), so you need to move one column.
The difference between the third row and the first row is two rows (3 - 1 = 2), so you need to move two rows.

The reason we start counting at zero alot of times in programming, is because we are always [u][b]at[/b][/u] some location in memory, wanting to [u][b]move to[/b][/u] another location in memory. If the place where we are [u][b]at[/b][/u] is also the place we want to be, then we just move "zero" places. Once you understand this, so you know [i]why[/i] it makes sense, then you can just keep that information in the back of your head, and take the much much easier mental shortcut of saying, "We start counting at zero", and cut out the "we're [i][u]here[/u][/i], we want to be [u][i]there[/i][/u], the difference is [i][u]thus[/u][/i].", because the end result always just to subtract one from the "[u][i]there[/i][/u]" location anyway. We work with [i]relative[/i] positions, not absolute positions, so our "[u][i]here[/i][/u]" is [i]always[/i] 1, so we can just shortcut by always subtracting 1 from our "[u][i]there[/i][/u]".

We always work with relative positions instead of absolute positions because we never can be sure about what actual physical location of memory we're at. Our memory address might be 0x45FF34A4 at one run, or 0x33C63A3D the next run - but it doesn't matter, because we know we have a tileset at [[i]whatever location in memory[/i]], and whatever that location is, it doesn't effect us, because we know that 4 steps beyond that location is the specific tile we want. So, (absolute location of memory) + 4 steps = Our tile.
Instead of complicating math unnecessarily and saying "0x45FF34A4 + 4", we move the problem domain to be relative to zero (for ease of mental problem solving), and say, "0 + 4", and then add 0x45FF34A4 to the final result. (Note that '4' is moving '4' steps to get to the 5th tile, because the first tile is located at location 0x45FF34A4 itself, but since we moved the problem domain to be relative to zero, then the first tile is located at position zero. Unnecessarily large numbers that are our location in memory can be shortcutted out of our math since it's irrelevant to our final result.

That was really confusing. If I'm doing a crappy job of explaining this, just let me know. If someone more skilled in explanations is reading this, you are most welcome to step in any time you want to undo any damage I may be causing! [img][/img]

If you are just born, you are in your first year of life. You aren't 1 year old (1 year old = you are in your second year of life).
If I'm 5 years old, that means I've already [i]moved[/i] 5 years from my place of origin (my birth at zero years old). It means I am now in my sixth year of life.
If it is 12:05 am, you are 5 minutes into the first hour of the day. The first hour is hour 'zero', it hasn't yet reached hour '1' which is the second hour of the day.

Taking the age thing further: If I was born in 2010, nobody stops and thinks that "Your age is now at time-location 2012 minus 2". They say, "You are now 2". Everyone understands that my birth was in 2010, so my "2" is relative to 2010. Even though I was born in 2010, that year doesn't tell anyone information that they want, but my age [i]relative[/i] to that year is what is important.
It doesn't matter that the tileset starts at memory location 0x45FF34A4 in a piece of RAM somewhere. But the location of the tile in the tileset [i]relative[/i] to the origin is the information we want. If we want the tile, we can just eliminate the '0x45FF34A4 ' information entirely, and work from a problem domain of 'zero' (memory location 0x00). Edited by Servant of the Lord

Share this post

Link to post
Share on other sites
nickem    210
More confusion!
[source lang="csharp"]int sy = ((tile_index - 1) / tileset_width);
int sx = ((tile_index - 1) - (sy * tileset_width)) * tile_width;
sy = sy * tile_height;[/source]

Tile index to source rect [img][/img]

Share this post

Link to post
Share on other sites
The code is trying to do two things at once, and instead of doing them in order, are mixing the two together in what looks like a poor programmer's attempt at "optimizing code" (and are instead obfuscating code, making it harder to maintain).

1) They are converting from a tile index, to the tile location in tiles.
2) They are converting from the tile location in tiles, to the tile location in pixels.
...But they are intermingling the two at one time, which is what is causes the confusion.

If you do things neatly, it might look like this:
[code]//Step one: Go from index to tile location in tiles.
int tileX = (tileIndex % TilesetWidthInTiles);
int tileY = (tileIndex / TilesetWidthInTiles);

//Step two: Go from location in tiles, to location in pixels.
int tilePixelX = (tileX * TileWidth);
int tilePixelY = (tileY * TileHeight);[/code]

If you want to mix them together in one line that's also fine:
[code]int tilePixelX = (tileIndex % TilesetWidthInTiles) * TileWidth;
int tilePixelY = (tileIndex / TilesetWidthInTiles) * TileHeight;
It's still broken into two logical steps (step 1: within the parenthesis, step 2: the multiplication), even if you have it on one line, and is easier to understand.

The other one intermingles the two steps, I'm not sure why, probably to save the cost of using the modulus operator or something. [img][/img]
But (since it's just a tiny snippet of code) it's really not as bad as I'm making it sound - I'm just an idealist when it comes to clean code. [img][/img]
Though even in my own projects, clean code isn't always possible, it's still one of the top goals to shoot for (Much more important than running fast, but I digress).

[b]Here's how it works:[/b]
[hr]We'll start by assigning some test values, to help us walk through it. It'll work for any sane values you choose, but for figuring out what a piece of code does, it's always good to pick some test values and walk through the code mentally in the same way the computer will walk through it.
[code]int tile_index = 12;
int tileset_width = 5; //The tileset is 5 _tiles_ wide.
int tile_width = 32; //Our tiles are 32 _pixels_ wide and high.[/code]

[b]Line one:[/b]
[code]int sy = ((tile_index - 1) / tileset_width);
int sy = ((12 - 1) / 5);
int sy = ((11) / 5);
int sy = (2);[/code]

[b]Line two:[/b]
[code]int sx = ((tile_index - 1) - (sy * tileset_width)) * tile_width;
int sx = ((12 - 1) - (2 * 5)) * 32;
int sx = ((11) - (10)) * 32;
int sx = (1) * 32;
int sx = 32;[/code]

[b]Line three:[/b]
[code]sy = sy * tile_height;
sy = 2 * 32;
sy = 64;[/code]

[code]sx = 32 pixels
sy = 64 pixels[/code] Edited by Servant of the Lord

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this