Viewport

Viewports, in their most basic essence, are just containers that stores sprites. A viewport provides the rectangle in which a sprite can be shown, and provides a few modifiers that are used when displaying sprites.

A sprite cannot exist without a viewport. So far, we've always created created sprites without specifying the viewport the sprite belongs to, so it defaults to the first window's main viewport, which is a rectangle the exact same size as the window.

Viewports determine where sprites are drawn, and what area the sprite can be drawn in. If a sprite exceeds the boundaries of its viewport, it will be clipped (i.e. the area that exceeds the boundaries is not shown). Viewports and sprites both have a z index, which determines the order in which sprites and viewports are rendered. When the graphics are being rendered to the screen, it first sorts all the viewports from lowest z to highest z. Then it renders those viewports from lowest z to highest z. Then inside that viewport, it does the same with its sprites: render from lowest z to highest z.

triangle-exclamation

Viewports are linked to a Window. A window may have multiple viewports, but a viewport must have one window. When creating a viewport, you must specify the rectangle that that viewport will represent. For instance, let's create a viewport that starts at (x, y) = (10, 10), and stops 10 pixels before the width/height of the window.

Window w = new Window();
w.Initialize();

Viewport vp = new Viewport(10, 10, w.Width - 20, w.Height - 20);

Sprite s = new Sprite(vp);
s.Bitmap = new Bitmap(vp.Width, vp.Height);
s.Bitmap.Unlock();
s.Bitmap.FillRect(0, 0, s.Bitmap.Width, s.Bitmap.Height, Color.RED);
s.Bitmap.Lock();

w.Show();
circle-info

We're creating a viewport here without explicitly referencing the window we want it to be linked with. If you don't specify a window, it will always use the first window that was created. This because of the assumption that you will only use one window in your program - this is not necessary however.

So we've created a viewport that excludes a 10px border inside the window, and then create a sprite inside that viewport, create a bitmap the size of the viewport, and fill it with a red color. As you can see in the image below, the sprite's position is relative to the viewport's position. Although the sprite has an (x, y) position of (0, 0), the viewport's position is (x, y) = (10, 10), and as such that's where the sprite will be displayed.

However, we are not prohibited from creating bitmaps that exceed the viewport size, or from positioning sprites outside of the viewport boundaries. When we do, it will simply be clipped.

In this example, we've positioned the sprite at (-10, -10), and with the viewport's position being (10, 10), that would logically position the sprite at (0, 0) on-screen. And it does - but it clips those first 10 pixels, because it's outside of the viewport's boundaries.

Last updated