Tag Archives: SDL2

Handling Keyboard and Mouse Events in SDL2

This article was originally posted as “SDL2: Keyboard and Mouse Movement (Events)” at Programmer’s Ranch on 12th February 2014. It is slightly updated here. The source code and spaceship bitmap are available at the Gigi Labs BitBucket repository.

Hi there! ūüôā

In this article, we’ll learn how to handle keyboard and mouse events, and we’ll use them to move an object around the window. Hooray! ūüôā

We’ll start with an image. I made this 64×64 bitmap:

spaceship

As you can see, I can’t draw to save my life. But since this is a bitmap, we don’t need the SDL_image extension.

Once you have an image, you’ll want to create a new Visual Studio project, wire it up to work with SDL2, and then add some code to display a window and the spaceship in it. If you don’t remember how, these past articles should help:

  1. Setting up SDL2 with Visual Studio 2015
  2. Showing an Empty Window in SDL2
  3. Displaying an Image in an SDL2 Window

You should end up with code that looks something like this:

#include <SDL.h>

int main(int argc, char ** argv)
{
    // variables

    bool quit = false;
    SDL_Event event;
    int x = 288;
    int y = 208;

    // init SDL

    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window * window = SDL_CreateWindow("SDL2 Keyboard/Mouse events",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);

    SDL_Surface * image = SDL_LoadBMP("spaceship.bmp");
    SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer,
        image);
    SDL_FreeSurface(image);

    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);

    // handle events

    while (!quit)
    {
        SDL_WaitEvent(&event);

        switch (event.type)
        {
        case SDL_QUIT:
            quit = true;
            break;
        }

        SDL_Rect dstrect = { x, y, 64, 64 };

        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, texture, NULL, &dstrect);
        SDL_RenderPresent(renderer);
    }

    // cleanup SDL

    SDL_DestroyTexture(texture);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}

You’ll also want to place spaceship.bmp¬†into your Debug folder (along with SDL2.dll) so that the program can find the files it needs..

Once you actually run the program, you should see this:

sdl2-kbd-kickoff

I set the window’s background to white to match the spaceship’s white background by setting the clear colour using¬†SDL_SetRenderDrawColor(), and then calling¬†SDL_RenderClear()¬†to clear the window to that colour.

In order to handle keyboard and mouse events, we need an¬†SDL_Event. Well, what do you know: we have been using one all along, in order to take action when the window is closed. What we need now is to handle a different event type. So let’s add a new case¬†statement after the one that handles SDL_QUIT:

            case SDL_KEYDOWN:

                break;

Within this case statement, let us now determine which key was actually pressed, and move the spaceship accordingly:

            case SDL_KEYDOWN:
                switch (event.key.keysym.sym)
                {
                    case SDLK_LEFT:  x--; break;
                    case SDLK_RIGHT: x++; break;
                    case SDLK_UP:    y--; break;
                    case SDLK_DOWN:  y++; break;
                }
                break;

If you now run the program, you’ll find that you can move the spaceship using the arrow keys:

sdl2-kbd-moving-slow

You’ll notice that it seems to move pretty slowly, and you have to keep pressing for quite a while to make any significant movement. Now, in your code, replace¬†SDL_WaitEvent¬†with¬†SDL_PollEvent:

        SDL_PollEvent(&event);

Now, try running it again:

sdl2-kbd-moving-fast

Swoosh! In less than half a second, the spaceship hits the edge of the window. It’s actually too fast. To get this down to something manageable, add a small delay at the beginning of your while¬†loop:

        SDL_Delay(20);

SDL_PollEvent()¬†is better than¬†SDL_WaitEvent()¬†when you want to continuously check (i.e. poll) for events, but it consumes more CPU power (you can see this if you open Task Manager).¬†SDL_WaitEvent()¬†is okay when your window is mostly sitting idle so you don’t need to check for events that often.

Handling mouse events is also very easy. All you need to do is handle the appropriate event. Let’s see how to handle a mouse click:

            case SDL_MOUSEBUTTONDOWN:
                switch (event.button.button)
                {
                    case SDL_BUTTON_LEFT:
                        SDL_ShowSimpleMessageBox(0, "Mouse", "Left button was pressed!", window);
                        break;
                    case SDL_BUTTON_RIGHT:
                        SDL_ShowSimpleMessageBox(0, "Mouse", "Right button was pressed!", window);
                        break;
                    default:
                        SDL_ShowSimpleMessageBox(0, "Mouse", "Some other button was pressed!", window);
                        break;
                }
                break;

And this is what happens when you run it, and click somewhere in the window:

sdl2-kbd-left-click

You can also track mouse motion and obtain the current coordinates of the mouse pointer. This is useful when moving things with the mouse (e.g. moving an object by mouse-dragging it). The following code obtains the mouse coordinates and displays them in the window title:

            case SDL_MOUSEMOTION:
                int mouseX = event.motion.x;
                int mouseY = event.motion.y;

                std::stringstream ss;
                ss << "X: " << mouseX << " Y: " << mouseY;

                SDL_SetWindowTitle(window, ss.str().c_str());
                break;

Note that you’ll need to add the following at the top of your main.cpp¬†to make the above code work:

#include <sstream>

You will now notice the mouse coordinates in the window title:

sdl2-kbd-mouse-coords

Wonderful! You should now have an idea of how to capture and handle keyboard and mouse events in SDL2. We will see more of these in an upcoming article dealing with drawing pixels in the window, so stay tuned to learn more! ūüôā

Loading Images in SDL2 with SDL_image

This article was originally posted as “SDL2: Loading Images with SDL_image” on 25th November 2013 at Programmer’s Ranch, and has been updated before being reposted here. The source code for this article is available at the Gigi Labs BitBucket repository.

In “SDL2: Displaying an Image in the Window“, we saw how we could load bitmaps using the¬†SDL_LoadBMP()¬†function. Unfortunately, working with bitmaps is very limiting, and the core SDL2 library does not provide the means to work with other image formats. However, such functionality is provided by an extension library called¬†SDL_image. In this article, we will learn how to set up SDL_image and also how to use it to load other image formats.

Setting up SDL_image is not very different from setting up SDL 2.0 itself. You need to go to the SDL_image homepage and download the development libraries:

sdl_image-downloads2

Extract the include and lib folders inside the zip file over the ones you have in your sdl2 folder. You should get an SDL_image.h file in your include folder, and in your lib\x86 and lib\x64 folders you should get SDL2_image.lib and a whole bunch of DLLs including SDL2_image.dll.

We’ll start off with the same code we had in “Displaying an Image in an SDL2 Window” (you can just grab the source code if you’re lazy). I’ve modified the code so that the image fills the window:

#include <SDL.h>        

int main(int argc, char ** argv)
{
	bool quit = false;
	SDL_Event event;

	SDL_Init(SDL_INIT_VIDEO);

	SDL_Window * window = SDL_CreateWindow("SDL2 Displaying Image",
		SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);

	SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
	SDL_Surface * image = SDL_LoadBMP("image.bmp");
	SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, image);

	while (!quit)
	{
		SDL_WaitEvent(&event);

		switch (event.type)
		{
			case SDL_QUIT:
				quit = true;
				break;
		}

		//SDL_Rect dstrect = { 5, 5, 320, 240 };
		//SDL_RenderCopy(renderer, texture, NULL, &dstrect);
		SDL_RenderCopy(renderer, texture, NULL, NULL);
		SDL_RenderPresent(renderer);
	}

	SDL_DestroyTexture(texture);
	SDL_FreeSurface(image);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);

	SDL_Quit();

	return 0;
}

Now since we’ve introduced a new statically-linked library (i.e. SDL2_image.lib), the first thing we need to do is add it to the Linker -> Input in the project properties:

sdl_image-linker

The entry there should now look like this:

SDL2.lib;SDL2main.lib;SDL2_image.lib

Now, we’re going to load this nice photo (.jpg format) taken in Gardaland in 2006:

sdl_image-pict3159

Doing this is quite simple. First, we need to include the appropriate header:

#include <SDL_image.h>

Then, we initialise SDL_image by calling IMG_Init() right after the call to SDL_Init():

IMG_Init(IMG_INIT_JPG);

…and before the call to SDL_Quit(), we shut down SDL_Image using¬†IMG_Quit():

IMG_Quit();

All we have left to do now is replace the line calling SDL_LoadBMP() with one that uses IMG_Load() instead:

SDL_Surface * image = IMG_Load("PICT3159.JPG");

You should now be able to build this program (Ctrl+Shift+B). Before you run it, though, make sure that SDL2.dll is in the same folder as your executable. You’ll also need to toss in all the DLLs from the appropriate lib folder (most likely the x86 one is what you’ll be using by default) – that includes SDL2_image.dll along with format-specific files such as libjpeg-9.dll, libpng16-16.dll, etc. And your image file will need to be there too.

And voilà:

sdl_image-result

Isn’t that sweet? The SDL_image library allows you to load a large variety of image formats, by just replacing SDL_LoadBMP() with IMG_Load(). You’ll need to initialise and cleanup the library (although it seems to work even without this) and remember to link the library and include the appropriate header file. But as you can see, it’s pretty straightforward.

Displaying an Image in an SDL2 Window

This article was originally posted as “SDL2: Displaying an Image in the Window” on 17th November 2013 at Programmer’s Ranch. It has been updated, and the part about detecting and displaying errors has been removed as it is better addressed by configuring the project’s working directory. The source code for this article is available at the Gigi Labs BitBucket repository.

In this article we’re going to learn how to load a bitmap image from disk and display it in an SDL2 window. In order to follow along, you’ll need to set up a project to work with SDL2 (see Setting up SDL2 with Visual Studio 2015), and start off with the following basic empty window code, which is practically the same as what we did in¬†Showing an Empty Window in SDL2:

#include <SDL.h>        

int main(int argc, char ** argv)
{
	bool quit = false;
	SDL_Event event;

	SDL_Init(SDL_INIT_VIDEO);

	SDL_Window * window = SDL_CreateWindow("SDL2 Displaying Image",
		SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);

	while (!quit)
	{
		SDL_WaitEvent(&event);

		switch (event.type)
		{
		case SDL_QUIT:
			quit = true;
			break;
		}
	}

	SDL_Quit();

	return 0;
}

OK, we can now create an SDL_Renderer:

SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);

We use¬†SDL_CreateRenderer()¬†to get an instance of SDL_Renderer. This renderer represents the output device (usually your graphics card) to which your code will be drawing. In fact it’s the final destination of our image, because we’ll be following the steps below:

sdl2-displayimage-workflow

SDL_CreateRenderer()¬†takes three parameters. The first is the window where we are drawing. The second allows us to select different rendering drivers; in our case we don’t care, and we can set it to -1 and get the default one. The last parameter allows us to set SDL_RendererFlags¬†to control how the rendering occurs. We can set it to zero to¬†default to hardware rendering. If any of this sounds confusing, don’t worry about it and just use SDL_CreateRenderer() as it is here.

We can now load the image from disk using the SDL_LoadBMP() function, which takes a path to a bitmap and loads it into an SDL_Surface:

SDL_Surface * image = SDL_LoadBMP("image.bmp");

I’m using the following photo of the Grand Harbour in Valletta, Malta, which I took back in 2005, and which has a width of 320 pixels and a height of 240 pixels:

sdl2-displayimage-image

Place the image in your Debug folder, where your executable is located.

Next, we need to create a texture.

SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, image);

A texture is memory close to the graphics card (see image below), and we use SDL_CreateTextureFromSurface() to directly map our surface (which contains the image we loaded) to a texture.

sdl2-displayimage-surface-textures

Now that we have a texture, let’s display it in the window. At the end of the while¬†loop, just after the switch¬†statement, add the following:

		SDL_RenderCopy(renderer, texture, NULL, NULL);
		SDL_RenderPresent(renderer);

We use¬†SDL_RenderCopy()¬†to copy the texture to the output device. There are also a couple of other parameters that we’re setting to NULL – more on these in a minute. Finally,¬†SDL_RenderPresent()¬†is what commits the texture to the video memory, displaying the image.

Before we run the program, we must always remember to clean up every resource that we initialise. In our case, that means adding the following just before the call to SDL_Quit():

	SDL_DestroyTexture(texture);
	SDL_FreeSurface(image);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);

If you now run the program from within Visual Studio, you should see the image in your window:

sdl2-displayimage-stretched

Fantastic! The image is right there in the window! But… can you see what happened? The image, which has dimensions 320×240, has been stretched to fill the window, which has dimensions 640×480. That’s sometimes convenient, because we get scaling for free. However, it makes photos look messy. Let’s change our call to SDL_RenderCopy() to fix this:

		SDL_Rect dstrect = { 5, 5, 320, 240 };
		SDL_RenderCopy(renderer, texture, NULL, &dstrect);

Remember those two parameters at the end of SDL_RenderCopy() that we were setting to NULL? If you look at the¬†documentation for SDL_RenderCopy(), you’ll see that the last one defines a destination region (which part of the texture will the image be copied to). If it’s set to NULL, then the image is stretched to fill the texture – which is what happened above.

By setting dstrect (the last parameter), we can render to only a portion of the window. We set it to an SDL_Rect, with x and y set to 5, and width and height corresponding to the dimensions of the image. When we run the program, we get this:

sdl2-displayimage-original-size

Excellent! ūüôā In this article we looked at how to create renderers, surfaces and textures. We used these to load bitmaps and display them on the screen. We also saw the difference between copying the image to a region of the window, and making it fill the entire window.

Showing an Empty Window in SDL2

This article was originally posted as “SDL2: Empty Window” on 31st August 2013 at Programmer’s Ranch. It has been slightly updated and now enjoys syntax highlighting. The source code for this article is available at the Gigi Labs BitBucket repository.

Yesterday’s article dealt with¬†setting up SDL2 in Visual Studio. Today we’re going to continue what we did there by showing an empty window and allowing the user to exit by pressing the X at the top-right of the window.

It takes very little to show an empty window. Use the following code:

#include <SDL.h>

int main(int argc, char ** argv)
{
	SDL_Init(SDL_INIT_VIDEO);

	SDL_Window * screen = SDL_CreateWindow("My SDL Empty Window",
		SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);

	SDL_Quit();

	return 0;
}

We use SDL_Init() to initialise SDL, and tell it which subsystems we need Рin this case video is enough. At the end, we use SDL_Quit() to clean up. It is possible to set up SDL_Quit() with atexit(), as the SDL_Quit() documentation shows.

We create a window using SDL_CreateWindow(). This is quite different from how we used to do it in SDL 1.2.x. We pass it the window caption, initial coordinates where to put the window (not important in our case), window width and height, and flags (e.g. fullscreen).

If you try and run the code, it will work, but the window will flash for half a second and then disappear. You can put a call to SDL_Delay() to make it persist for a certain number of milliseconds:

SDL_Delay(3000);

Now, let’s make the window actually remain until it is closed. Use the following code:

#include <SDL.h>

int main(int argc, char ** argv)
{
	bool quit = false;
	SDL_Event event;

	SDL_Init(SDL_INIT_VIDEO);

	SDL_Window * screen = SDL_CreateWindow("My SDL Empty Window",
		SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);

	while (!quit)
	{
		SDL_WaitEvent(&event);

		switch (event.type)
		{
			case SDL_QUIT:
				quit = true;
				break;
		}
	}

	SDL_Quit();

	return 0;
}

The while (!quit) part is very typical in games and is in fact called a game loop. We basically loop forever, until the conditions necessary for quitting occur.

We use¬†SDL_WaitEvent()¬†to wait for an event (e.g. keypress) to happen, and we pass a reference to an¬†SDL_Event¬†structure. Another possibility is to use¬†SDL_PollEvent(), which checks continuously for events and consumes a lot of CPU cycles (SDL_WaitEvent() basically just sleeps until an event occurs, so it’s much more lightweight).

The event type gives you an idea of what happened. It could be a key press, mouse wheel movement, touch interaction, etc. In our case we’re interested in the SDL_QUIT event type, which means the user clicked the window’s top-right X button to close it.

We can now run this code, and the window remains until you close it:

sdl2-empty-window

Wasn’t that easy? You can use this as a starting point to start drawing stuff in your window. Have fun, and come back again for more tutorials! ūüôā

Setting up SDL2 with Visual Studio 2015

This article is based on “SDL2: Setting up SDL2 in Visual Studio (2013 or any other)“, which was published at Programmer’s Ranch on 10th February 2014. This article uses Visual Studio 2015 Community, and although the steps should mostly apply to any version of Visual Studio, I’ve included steps specific to VS2015 because of issues encountered. It also uses a more recent version of the SDL2 library. Finally, it adds a configuration step originally found in “SDL2: Displaying text with SDL_ttf” (Programmer’s Ranch, 29th March 2014). The source code for this article is available here at the Gigi Labs BitBucket repository

SDL2 is a great low-level library for developing games in C/C++ (other language bindings exist). It’s a little bit tedious to set up in Visual Studio the first time, so I’m going to guide you through the process.

For starters you’re going to want to head to the SDL2 download page and grab the latest Visual C++ Development Libraries (at the time of writing, that would be¬†SDL2-devel-2.0.3-VC.zip):

sdl2-vs-devlib

Create a folder for your SDL2 libraries in a convenient location, say C:\sdl2. Extract the include and lib folders in the zip file here.

We can now create an empty Visual C++ project:

sdl2-vs-newproj

We now need to configure our project (via the project’s properties) so that it can¬†work with SDL2.

First, we’ll tell Visual Studio where to look for the SDL2 header files, by adding the SDL2 include folder to the¬†Include Directories in¬†VC++ Directories:

sdl2-vs-include

In Linker -> General, set Additional Library Directories to the path to the SDL2 library Рeither x86 or x64:

sdl2-vs-library

Then in Linker -> Input, replace the value of¬†Additional Dependencies with “SDL2.lib; SDL2main.lib“:

sdl2-vs-dependencies

Finally, in Linker -> System, set SubSystem to Windows (/SUBSYSTEM:WINDOWS):

sdl2-vs-subsystem

That should be all the configuration you need to get started.

Now, let’s add a new main.cpp file under¬†Source Files, and add some code just to see whether it works:

#include <SDL.h>

int main(int argc, char ** argv)
{
    SDL_Init(SDL_INIT_VIDEO);

    // game code eventually goes here

    SDL_Quit();

    return 0;
}

Press Ctrl+Shift+B to build, and lo and behold…

sdl2-vs-failed

Crap.

Well, until VS2013, these steps used to work, as you can see from the Programmer’s Ranch article “SDL2: Setting up SDL2 in Visual Studio (2013 or any other)“.

Some insights as to the nature of the problem can be found in this StackOverflow thread and this gamedev.net thread. Quoting the latter:

VS2015 contains a completely rewritten CRT with many bug and conformance fixes. It’s not surprising that this kind of breakage happened; it’s not clear if this is a temporary bug with the CRT being incompatible or if all static libraries (like SDL2main) will have to be recompiled for VS2015’s runtime.

So basically, until this is resolved, throw out your C:\sdl2 folder, and instead make a new one from the latest SDL2 build for Visual Studio. Be sure to rename your lib\win32 folder to lib\x86 so that the earlier settings will apply (or change the path in the settings). Sorry, you can’t use this method for x64 just yet.

Try building again, and it should now succeed.

Press F5 to run the program, and you should get a nice runtime error message:

sdl2-vs-nosdldll

Fortunately, the error is pretty clear. Grab SDL.dll from C:\sdl2\lib\x86 and put it in your project’s Debug folder, where the executable is being generated:

sdl2-vs-copydll

You should now be able to run the program without errors. It doesn’t do anything, but you can use it as a basis for any SDL2 code you’ll write. You can find this empty project here at the Gigi Labs BitBucket repository, or else follow the steps in TwinklebearDev’s tutorial to export a Visual Studio template from the project.

Finally, there’s an additional configuration setting that you’ll find handy if you’re going to be loading resources from files (e.g. images, fonts, etc). In your project’s properties, go to the Debugging section and change the value of Working Directory from $(ProjectDir) to $(SolutionDir)$(Configuration)\:

sdl2-vs-wd

Why are we doing this? By default, the program will use a different working directory depending on whether you run it from Visual Studio or directly from the executable. So if it has to look for a particular file in the current directory, this won’t work in both scenarios unless you copy the same file into both the project folder and the output folder. With the above setting, we are telling Visual Studio to run the program with its working directory as the Debug folder, thus aligning the two scenarios.

How to set up SDL2 on Linux

This article explains how to get started with SDL2 in Linux. For other SDL2 tutorials (including setting up on Windows), check out my SDL2 Tutorials at Programmer’s Ranch.

Using apt-get

If you’re on a Debian-based Linux distribution, you can use the APT package manager to easily install the SDL2 development libraries. From a terminal, install the libsdl2-dev package:

sudo apt-get install libsdl2-dev

Installing from source

If for whatever reason you can’t use a package manager, you’ll have to compile SDL2 from the source code. To do this, you first have to download SDL2:

sdl2linux-download

After extracting the archive to a folder, cd to that folder and run:

./configure

When it’s done, run:

make all

Finally, run:

sudo make install

Testing it out

To verify that you can compile an SDL2 program, use the following code (it’s the same used in my “SDL2: Setting up SDL2 in Visual Studio 2010” article at Programmer’s Ranch):

#include <SDL2/SDL.h>

int main(int argc, char ** argv)
{
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Quit();

    return 0;
}

You can use vi or your favourite editor to create the source code:

sdl2linux-minimal

To compile this (assuming it’s called sdl2minimal.c), use the following command:

gcc sdl2minimal.c -lSDL2 -lSDL2main -o sdl2minimal

We need to link in the SDL2 libraries, which is why we add the -lSDL2 -lSDL2main. Be aware that those start with a lowercase L, not a 1. The program should compile. It won’t show you anything if you run it, but now you know that you’re all set up to write SDL2 programs on Linux.

sdl2linux-run