Sruface width vs. Surface pitch

Started by
1 comment, last by VizOne 18 years, 7 months ago
I have just started learning the basics of Direct3D and I have gotten to the point where I am learning about surfaces. I understand that in order to draw a surface to the screen, you must first lock a rectangle, but what I am confused about is how the pitch of the locked rectangle is used to draw each line of the surface. I appreciate any help you can give me.
Advertisement
The width is how many pixels across. The pitch is the offset in bytes between the first pixel of a row, and the first pixel of the next bow. For example, a 30x30 8-bit surface will have a width of 30, but may have a pitch of 32 because the rows in surfaces often are padded to 4-byte boundaries. If the 30x30 surface was 32-bit the width would still be 30, but the pitch would be (atleast) 120 (30 pixels*4 bytes/pixel).
The pitch of a line is the number of bytes the line occupies in memory. Let's say your surface format uses 3 bytes per pixel (R8G8B8), the width is 340 pixels. Then the number of bytes per line that is needed to store the pixel-values is 340 * 3 = 1020. However, the driver might choose to add some fillbytes per line to have the memory layout pack nicely. E.g. the driver could find it more usefull to use 1024 byte per line - thus, 4 extra fill bytes per line. In this case, the pitch would be 1024, which tells you that you have to advance by 1024 bytes to reach the same pixel in the next line.

So, if you want to work with the locked data, one possible way of doing it might be something like this:

char * line = (char*)lockedRect.pBits; // points to first byte in linefor(int row = 0; row < RectHeight; ++row) {  // convert line-pointer (bytes) to pixel-pointer (e.g. 3-byte)  RGB * pixel = (RGB*)line; // imagine RGB is a 3-byte structure  for(int col = 0; col < RectWidth; ++col) {    // access pixel x,y (col, row):    pixel[col] = ....  }  // next line:  line += lockedRect.Pitch;}


Regards,
Andre
Andre Loker | Personal blog on .NET

This topic is closed to new replies.

Advertisement