Showing posts with label Game Programming. Show all posts
Showing posts with label Game Programming. Show all posts

SDL Tutorial Series - Part 3 - Your First Application

This tutorial will help you create your first SDL application using Microsoft Visual C++ Express 2008. You are going to learn how to initialize and shutdown the SDL and how to create a window. Also, you will see how the SDL handles events that are sent from the system. If you have not done so already, open up Microsoft Visual C++ Express so we may begin.

Once you have opened Visual C++, click on File and select New, then Project...


NewProject


In the 'New Project' dialog box, select Win32 Console Application. At the bottom of the dialog box enter a name for the project, 'SDLTutorial' should be fine. Also, select a location for the project. Important! Remember where you saved the project because this will be important later on.


NewProjectDialog


After you click 'OK', you will see a new dialog box labeled 'Win32 Application Wizard'. Click on the 'Next >' button and you should see this dialog box.


ApplicationSettings


Make sure that you select the 'Empty Project' check box. This should be the only change you need to make. Click on the 'Finish' button.

Now, click on 'Project' from the menu bar and select 'Add New Item...'. You should see a dialog box like this.


NewItem


Be sure to select C++ File (.cpp) and enter a name for the file. 'Main' will suffice for our purposes, so click on the 'Add' button to add it to your project.

Paste the following code into the source code file you just created:
#include <iostream>
#include "SDL.h"

using std::cerr;
using std::endl;

int main(int argc, char* args[])
{
    // Initialize the SDL
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
 {
  cerr << "SDL_Init() Failed: " << SDL_GetError() << endl;
  exit(1);
 }

 // Set the video mode
 SDL_Surface* display;
 display = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
 if (display == NULL)
 {
  cerr << "SDL_SetVideoMode() Failed: " << SDL_GetError() << endl;
  exit(1);
 }

 // Set the title bar
 SDL_WM_SetCaption("SDL Tutorial", "SDL Tutorial");

 // Main loop
 SDL_Event event;
 while(1)
 {
  // Check for messages
  if (SDL_PollEvent(&event))
  {
   // Check for the quit message
   if (event.type == SDL_QUIT)
   {
    // Quit the program
    break;
   }
  }
  // Game loop will go here...
 }

    // Tell the SDL to clean up and shut down
    SDL_Quit();
    
    return 0;    
}

In the menu bar, select 'Project' and then 'Properties' at the bottom of the menu.


SDLTutorialProperties


We need to modify some settings in order for the SDL program to run. Expand the 'C/C++' list and select 'Code Generation'. On the right, select 'Runtime Library' and set it to 'Multi-threaded DLL (/MD)'.

Go back to the list box on the left and expand the 'Linker' category. Select the 'Input' field and on the right select 'Additional Dependencies'. Type in the following:

SDL.lib SDLmain.lib

Note: This is case sensitive so be sure to type this exactly as shown.

Click on the 'OK' button. You should now be able to compile and run the program. Select 'Build' from the menu bar and click on 'Build Solution'. If everything worked as it should there should be no errors and no warnings. You need to copy SDL.dll to the same folder as the .exe file you just created. It should be in the 'Debug' sub-folder inside where you saved your project. Now, select 'Debug' from the menu bar and click on 'Start Without Debugging'. You should get a black window to popup and the title should be 'SDL Tutorial'.

Congratulations! You have just built and run your first SDL application. It does not do much of anything interesting but in future tutorials we will be adding elements to it. Let me explain some of the SDL functions to you.

The first function of interest is:
int SDL_Init(Uint32 flags)
This function initializes and loads the SDL library. All you need to know is if it was successful in loading the SDL library. If it was successful it will return 0. If there was an error, it will return -1. Information about the error can be obtained by the next function.

char* SDL_GetError(void)
This function will return a null terminated string that has information about the last internal error generated by the SDL library. This can be very useful in discovering errors in our program code.

The next function allows us to set our video mode.
SDL_Surface* SDL_SetVideoMode(int width, int height, int bitsperpixel, Uint32 flags)
With this function we can set the width and height of our window and the bits per pixel (16 or 32 are the most common). The flags parameter is of special note here. In this tutorial we set the flags to SDL_HWSURFACE and SDL_DOUBLEBUF by ORing them together. These will be most useful to us in future tutorials since we are interested in making games. We could have selected a software surface by specifying SDL_SWSURFACE instead of SDL_HWSURFACE but the hardware surface should be faster. Also, we selected double buffering for our application because this allows us to display one buffer to the user while we perform all drawing operations on the back buffer. Once we are finished drawing the current frame on the back buffer, we swap the buffers and display the one we just finished to the user. This allows us to provide the user with smooth animation and prevents him or her from seeing the frame being drawn which will break the immersion. Note: if you want a full screen window, you can pass SDL_FULLSCREEN to attempt full screen at the specified resolution.

void SDL_WM_SetCaption(const char *title, const char *icon);
This function sets the caption for our window. The first parameter is the string to display in the title bar of our window and the second parameter will be displayed when the window is minimized.

int SDL_PollEvent(SDL_Event *event)

This function will check to see if any events have been posted to the event queue. If there are events in the queue, the function pops the event off the queue and stores it in the SDL_Event data structure pointed to by event. It returns 1 if there is an event or 0 if there are none in the queue. The only event we care about for now is if the quit message has been posted. This will occur when the user clicks the 'x' button on the title bar. We will learn more about events that can occur in our SDL applications in a future tutorial. If you are not familiar with event driven programming I suggest you check out the tutorial on this site here.

void SDL_Quit(void);
This function should always be called if you are using the SDL before exiting your program. It shuts down all the subsystems, unloads all the dynamically linked libraries, and frees any allocated resources.

You have now successfully completed your first SDL application. You should have gained an understanding of the basic functions of the SDL and how they work together to create a functional application. The next tutorial will cover displaying graphics on the screen which will be fundamental in creating video games using the SDL.

Back to SDL Tutorial Index

Back to Main Page.

An introduction to Event-Driven Programming

Event-driven programming or Event-based programming refers to a computer programming technique that involves controlling the flow of a program by receiving signals (also called messages or events) from an outside source. The source of the message can be anything from another program, a thread, or it could be generated from within the program. There are two necessary data structures for the construction of an event-driven system: an event listener and an event handler.

An event listener will store messages that are passed to it from an outside source. This is usually implemented as a queue or stack. Messages are stored for later dispatching by the event handler. Observe the following diagram.


Event Driven Diagram


Messages A, B, and C get passed to the event listener which will then be retrieved by the event handler. These messages could be generated from a variety of sources and generated at different time intervals. It is important to note that until the event handler processes the messages, the event listener will store them.

Event Driven programming is heavily used in Graphical User Interfaces (GUIs). Imagine what happens when you move the mouse and press the left mouse button. First, a mouse move message would be sent to the window that has the focus. Maybe the window will want to know the new x and y coordinate of the mouse position. Second, a mouse click message will be sent to the window. If the mouse cursor is over a button then the left click would trigger another event that would get sent to the event listener. Imagine writing a program that had to check for each of the possible actions a user could perform in your program. You would waste CPU cycles checking for events that did not happen. Event driven programming solves this problem.

Event driven programming is a different way to think about the flow of your program. Usually when one sets out to learn programming, he or she thinks of the flow of the program as a linear progression from beginning to end. Using event driven programming, you can think in terms of events that happen to your program.

Back to Main Page

SDL Tutorial Series - Part 1 - What is the SDL?

SDL Logo
So what is the SDL? The SDL home page states that, "Simple DirectMedia Layer is a cross-platform multimedia library designed to provide low level access to audio, keyboard, mouse, joystick, 3D hardware via OpenGL, and 2D video framebuffer." The key-word in that description is cross-platform. SDL provides us with a platform independent way to access multimedia resources that we can use for making games. By using the SDL, we can share a common codebase across multiple platforms like Windows, Linux, and Mac OS X.

A fine example of a video game that uses the SDL is World of Goo. This critically acclaimed game was made by a small team of developers who used the SDL in their development process. Because they used the SDL, they were able to release the game for Windows, Mac OSX, and Linux with little modification to the underlying code base. Here is a short video trailer for the game.



Besides being cross-platform, the SDL is intuitive and very easy to use. It is written in the C programming language and has a function based syntax. The programmer controls the API by passing parameters to functions. Although written in the C programming language, SDL works with C++ and has bindings for many other languages including: C#, Python, Java, Objective C, D, and many others. The best part of the SDL is that it is FREE! As long a you link to the dynamic libraries you can use the SDL in your programs free of charge. For more information about the SDL, check out the SDL home page.

Back to SDL Tutorial Index

Back to Main Page

SDL Tutorial Series - Part 2 - Getting Started

In this tutorial, we will describe where to download the SDL libraries and how to set it up using Microsoft® Visual C++ 2008 Express Edition. If you are using Windows and have not yet installed Visual C++ 2008 Express Edition, it can be downloaded for free from here.

The first step to getting started using the SDL is to download the libraries. These libraries are required to building applications that use the SDL. The libraries can be downloaded from http://www.libsdl.org/download-1.2.php. At the bottom of the page, you should see this section.


SDL Libraries


Note: Since we are using Visual C++ 2008 Express Edition, download the Visual C++ 2005 Service Pack 1 zip file.

After you have downloaded the libraries, extract the contents to wherever you want on your computer. Just remember where because it will be very important.

Now we will set up Visual C++ Express Edition to use these libraries in our future SDL projects. Open up Visual C++ and click on Tools and then Options. It should look like this:


SDL tut 1


Expand the 'Projects and Solutions' category and select 'VC++ Directories'. Under the 'Show directories for:' drop down box, select 'Include files'.


SDL tut 2

Now, select the 'New Line' button (Highlighted with the red circle) and then the button with 3 dots (Highlighted with the green circle). This will let you browse the files on your computer. Select the 'include' folder in the SDL folder you extracted previously. It should be something like: SDL-1.2.14\include

Now, under the 'Show directories for:' drop down box, select 'Library files'. Do the same action you did in the previous step. Select the 'New Line' button and then the button with 3 dots to browse for the lib folder. Select the 'lib' folder in the same SDL folder that contained the 'include' folder. It should be SDL-1.2.14\lib.

Only one item remains in order for you to be using the SDL in your applications, the SDL.dll file. You can copy this .dll file to the folder containing the source code of your application (it will look like: application name\debug\sdl.dll). You can also copy the file to your Windows\System32 folder (or Windows\SysWOW64 if you are running a 64-bit version of Windows). The problem with this is that there are different versions of the SDL and if you have a conflicting version of the SDL.dll file in the Windows folder, version conflicts could arise. You will need to distribute a copy of the SDL.dll file with your applications anyways for it to run so I recommend not copying it to the Windows folder.

You are now ready to start using the SDL in your applications. Part 2 of this tutorial will begin to explain the basics of the SDL and how you can use it in your game applications.

Back to SDL Tutorial Index

Back to Main Page

Vectors - Part Two

In part one of this tutorial I explained what a vector is and described some of their basic operations. This tutorial will delve deeper into vectors and explain the more useful operations that vectors can be used for. First, lets see how we can find the length of a vector.
If you are not familiar with the Pythagorean theorem, please read this article. It is important that you are familiar with this theorem because finding the length of a vector is based on it.

Vector Length

This picture shows a 2-dimensional vector with red lines overlaid to show the x and y displacement. From this picture you should be able to infer how the length is obtained. You square the x and y term of the vector and then take the square root of their sum. In pseudo code it would look like this:

sqrt( x*x + y*y)

Or, in three dimensions:

sqrt (x*x + y*y + z*z)

The length of the vector is sometimes called the norm. If we have a vector A, you will often see the norm of vector A notated as ||A|| or just |A|.

There is a special class of vectors that will be VERY important to us. These are called unit length vectors and any vector that is unit length is said to be normalized. In order for a vector to qualify as unit length it must have a length of exactly 1. We can normalize any vector by first finding its length and dividing each component of the vector by the length (norm). In three dimensions it would look like this:

length = sqrt(x*x + y*y + z*z)

x = x / length
y = y / length
z = z / length

If the vector were only 2-dimensional you would take out the z component.

We will now discuss the most important and widely used operation on vectors in all of game programming - the dot product. Given two vectors A and B, we define the dot product of A and B as ||A||||B||cos theta. Theta is simply the angle between the two vectors. The dot product will return a scalar value between 1 and -1. We obtain the dot product by simply multiplying the two vectors' components. So, if we have vectors A and B that are 2-dimensional vectors, we find the dot product like so:

A.x*B.x + A.y*B.y

If the dot product of A and B is greater than zero, then we know the angle is less than 90 degrees. If the dot product is equal to zero then we know the two vectors are perpendicular or orthogonal to one another. If the scalar value returned is less than zero, we know the angle is greater than 90 degrees. If you need the actual angle between the two vectors, take the inverse cosine of the scalar value returned by the dot product.

We will now move on to the perpendicular product and the cross product; two similarly related concepts. For a vector A in 2-dimensions, there are two vectors that are exactly perpendicular to that vector. This picture will help demonstrate.

Perpendicular Product

The green vector is vector A. We say that the blue vector is the left hand normal of vector A and the red vector is the right hand normal of vector A. If we were to take the dot product of vector A and the left hand normal or the right hand normal, it would be exactly 0. For any 2-dimensional vector, to find the left hand normal switch the x and y components and negate the x component. In pseudo code it would look like this:

left_normal.x = vector.y
left_normal.y = -vector.x

The right hand normal is similar:

right_normal.x = -vector.y
right_normal.y = vector.x

The cross product is similar to the perpendicular product but it is used in 3-dimensions. Given three points: A, B, C, we can construct 2 vectors from these points. We will name the vectors V1 and V2. The following diagram will help in my explanation.

Cross Product

Vector V1 in constructed by taking the point B and subtracting it from A. Vector V2 is constructed the same way except by taking the point C and subtracting it from A. Similar to the perpendicular product, we can get two different normals that will be orthogonal to the plane constructed from the original 3 points. It is common to face the normal out of the plane. We calculate the normal vector like so:

normal.x = (V1.y * V2.z) - (V2.y * V1.z)
normal.y = (V1.z * V2.x) - (V2.z * V1.x)
normal.z = (V1.x * V2.y) - (V2.x * V1.y)

The normal vector is represented in the picture by the blue vector which is facing out. The cross product is usually written as normal = V1 x V2.

We now move onto our last topic which is vector projection. Have a look at this picture:

Vector Projection

Lets say the red vector is vector A and the green vector is vector B. We define the projection of A onto B as:

Projection = Dot(A, B) / (||B|| * ||B||) * B

The projection vector will be parallel to vector B. Notice the projection drops a
perpendicular onto B from A. If vector B is normalized we can reduce the projection vector calculation to:

Projection = Dot(A, B) * B

This is the end of this tutorial. If you have read over both tutorials you should have a good understanding of vectors and be able to start applying them to your game projects.

Back to Vectors - part 1

Back to Main Page

Vectors - Part One

Vectors are a very important part of any game. They are used primarily in graphics, collision detection, physics engines and ai. A vector can be represented graphically as follows:

Vector

Vectors have two properties that make them very useful; specifically, magnitude (length) and direction. You will see moving forward how these two properties of vectors make them invaluable in game programming.

We will represent 2-dimensional vectors as an [x,y] value pair and 3-dimensional vectors as an [x,y,z] value pair.

What can we do with vectors you ask? Well, for starters we can add them together. Given two vectors A and B, we can add them together to get a vector C. The following picture illustrates this concept.

Vector Addition

The green line represents vector A, the red line represents vector B, and the black line represents vector C. It is important to notice in this picture that the order in which we add the two vectors does not matter (A + B = B + A). This is called the commutative property.

Vectors can also be subtracted from one another:

Vector Subtraction

The green line represents vector A and the red line represents vector B and the black line represents the new vector C. Here we have B - A. It is important to notice that the vector is drawn from the tip of A to the tip of B. If we were to subtract vector B from A, vector C would face the opposite direction. We can then state that vector subtraction is non-commutative.

Vector Subtraction

A vector can be multiplied with a scalar value. For instance, say we have a 2-dimensional vector A = [3, 5] and we multiply it with the scalar value 2. Vector A is now twice as long and A = [6, 10]. If we wanted to reverse the direction of the vector we could multiply it with the scalar value -1. Two vectors can be multiplied together but I will save this for part two.

These are the most important basic properties of vectors. In the next tutorial I will explain the dot product, the cross product, vector length, and vector projection.

Continue to Vectors - part 2

Back to Main Page