Game Development Reference
In-Depth Information
Ignoring the silly y axis, we can see that, due to the discrete nature of our coordinates, the
origin is coincident with the top-left pixel in the grid, which is located at (0,0). The pixel to the
right of the origin pixel is located at (1,0), the pixel beneath the origin pixel is at (0,1), and so on
(see the left side of Figure 3-21 ). The display's raster grid is finite, so there's a limited number of
meaningful coordinates. Negative coordinates are outside the screen. Coordinates greater than
or equal to the width or height of the raster are also outside the screen. Note that the biggest
x coordinate is the raster's width minus 1, and the biggest y coordinate is the raster's height
minus 1. That's due to the origin being coincident with the top-left pixel. Off-by-one errors are a
common source of frustration in graphics programming.
Figure 3-21. Display raster grid and VRAM, oversimplified
The display receives a constant stream of information from the graphics processor. It encodes
the color of each pixel in the display's raster, as specified by the program or operating system in
control of drawing to the screen. The display will refresh its state a few dozen times per second.
The exact rate is called the refresh rate . It is expressed in hertz. Liquid-crystal display (LCD)
monitors usually have a refresh rate of 60Hz per second; cathode ray tube (CRT) monitors and
plasma monitors often have higher refresh rates.
The graphics processor has access to a special memory area known as video random access
memory, or VRAM. Within VRAM there's a reserved area for storing each pixel to be displayed
on the screen. This area is usually called the framebuffer . A complete screen image is therefore
called a frame. For each pixel in the display's raster grid, there's a corresponding memory
address in the framebuffer that holds the pixel's color. When we want to change what's
displayed on the screen, we simply change the color values of the pixels in that memory area
in VRAM.
Now it's time to explain why the y axis in the display's coordinate system is pointing downward.
Memory, be it VRAM or normal RAM, is linear and one dimensional. Think of it as a one-dimensional
array. So how do we map the two-dimensional pixel coordinates to one-dimensional memory
addresses? Figure 3-21 shows a rather small display raster grid of three-by-two pixels, as well
as its representation in VRAM. (We assume VRAM only consists of the framebuffer memory.)
From this, we can easily derive the following formula to calculate the memory address of a pixel
at (x,y):
int address = x + y * rasterWidth;
We can also go the other way around, from an address to the x and y coordinates of a pixel:
int x = address % rasterWidth;
int y = address / rasterWidth;
 
Search WWH ::




Custom Search