[ SDL2 – Part 6 ] Using SDL_Textures

In this tutorial you will learn how to load images ( just .bmp for now, the next part will cover .png ). First of all, a little info about the two new structs we’ll be using

SDL_Surface

This is part of the old SDL ( before 2.0. ) It was used for just about everything related to rendering.

SDL_Surface is used for holding the raw texture data. Basically it says what the color for every pixels is. Sort of like this :

• pixel[ 0, 0 ] = 128, 64, 255, 255 ( 128 red, 64 green, 255 blue, 255 alpha )
• pixel[ 1, 0 ] = 255, 32, 128, 128 ( 255 red, 32 green, 128 blue, 128 alpha )
• ..etc

( This might not be 100% true for all cases, but it’s generally how SDL_Surface stores the pixels. )

The SDL_Surface structure also holds other data about the texture :

• width/height ( these are read-only )
• the pixel format, stores as an SDL_PixelFormat
• clip_rec, a SDL_Rect used for bliting ( similar to rendering )

These values are useful to know about if you want to create your own SDL_Surfaces using code or want to use the old form of rendering ( bliting ). I do, however, not recommend learning about it. Bliting is less intuitive and it uses only software rendering. This basically means that the CPU will be doing the rendering, something CPUs are really bad at. We want optimized hardware rendering on the GPU. And that’s where the second struct comes in.

SDL_Texture

Like SDL_Surface, SDL_Texture holds texture data. But unlike SDL_Surface, SDL_Texture holds an optimized, driver specific representation of the pixel data. This means rendering will be executed on the GPU, where it belongs. And THAT means it is really, really fast!

So what’s the point of SDL_Surfaces?

Well, as I said, the pixel data in SDL_Texture is optimized. And what’s more, it can be very different depending on your driver ( nVidia vs ATI. ) Basically this means that you can’t use the pixel data for anything other than rendering. A second reason will come up when we dive into another new part of SDL, namely image loading.

Loading a BMP image in SDL is very easy. It can be done using the following function

Parameters

• file – the file we want to load

Return value

The loaded image as a SDL_Surface. null if failed

Converting SDL_Surface to SDL_Texture

We’re not gonna use the SDL_Surface*, we want a SDL_Texture* instead. To get it, we need to use a second function :

Parameters

• renderer – our SDL_Renderer
• surface – the surface we want to make a SDL_Texture from

Return value

The resulting SDL_Texture. null if failed.

Since we won’t be using the SDL_Surface, we can delete it and free the memory :

Parameters

• surface – the SDL_Surface to delete

Now that all of this is in place, we can wrap it all up in a nice little function :

Getting the images on screen

Now that we have loaded the textures, we need to render then on screen. That means no more SDL_RenderFillRect() and THAT means no more rectangles and squares. Finally! To render them, we just need a simple function :

Parameters

• renderer – the SDL_Renderer we always use for rendering
• texture – the SDL_Texture we want to render
• srcrect – which part of the SDL_Texture to render. null for everything.
• dstrect – where to render it. Used exactly like in SDL_RenderFillRect)

Return value

0 on success

Even though this function has a few parameters, it’s really quite simple. We can use nullptr for srcrect and the SDL_Rects we used for SDL_RenderFillRect() as dstrect. And then we can remove the SDL_SetRenderDrawColor and end up with a shorter Render() function.

Putting it all together

I’m not gonna put the entire code on the blog anymore since this creates a whole wall of text to scroll through. And now there are images you’ll need too. But you can download the images and the source code here.

Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com

Collision detection

Collision detection is one of the key aspects of game programming. For all non-rectangular objects it gets harder and harder the more accurate you want it to be. But today we’re gonna continue just using rectangles. This part describes a simple algorithm to check for intersections.

After we’ve created a functions that does rectangle-rectangle collision detections, we’ll use all of what we’ve learned so far and make a simple game!

Rectangle – rectangle collisions

Instead of checking if two rectangles are inside or touching each other, we’re gonna check for the opposite; if they are outside of each other. The algorithm to do so consists of two steps.

1. Find the x coordinate of the left and right and the y coordinate for top and bottom.

Say we have two rectangles, rect1, and rect2.

Finding the x/y of left/right/top/bottom is very easy.

The process is exactly the same for the second SDL_Rect.

2. Use the 8 edges to check if they are not colliding

Take a look at the drawing below

As you can see, the red rectangle is farther to the right than the blue one. But how do can we easily check that? Simply by checking if redLeft is further to the right than blueRight. If it is ( like it is in our case ) there is no collision. Then it’s just a simple matter of repeating it for the other edges. So we end up with something like this :

This is the final function for you to copy and test out.

If you want to shorten the code, you can remove the comments and replace the variables with the rect. x / y / w / h values like so :

I chose to not do this as the longer version is a bit easier to read and understand.

Our first game!

Our first game is of the “lead the chicken safely across the road” kind of things. Or, as in our case, “lead the square from the rectangle, past all the other squares and to the other rectangle.” You control the square with the arrow keys. If you hit a red square, you’ll end up where you started. If you make it to the other side, you’ll also end up where you started, but at least you have that tiny sense of victory for helping our poor little square!

The code just uses the different things we’ve learned so far, so I won’t explain it other than in code comments and ( hopefully ) descriptive names.

So without further ado, here’s the code :

Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com

Make things happen!

Games without any input would be really boring. Actually it wouldn’t be a game at all, just a movie. So let’s look at how we can get input so that the player can actually play the game. But before we do that, we need to take a look at how we do the things updates every frame. ( A frame is a single image of the game, basically each SDL_RenderPresent(..) is the end of a frame. )

The game loop

In a game ( and many other applications ) things need to happen over and over again. So you need a big loop that does all of these things. A minimal game loop covers :

• Objects needs to be moved
• Input handling
• Collision detections
• ….

Today we’ll focus on the two first points, we’ll cover collision detection later.

The game loop itself is usually a form of infinite loop :

So in order to exit the loop, we need a way of setting the loop bool to yountrue inside the loop.This will make the loop condition ( if ( loop ) ) false and the loop will stop. We could just use a break; to quit the loop. But this won’t work when we start handling input. We’ll see why in a few moments. But first, we need to move on to the next SDL object :

Events in SDL2

All events in SDL2 is in the form of a SDL_Event struct. A SDL_Event is a huge structure with tons of member variable with names that generally don’t say a lot about what they’re for. It is used for just about everything ;

• Quit event
• Mouse events
• Keyboard events
• Window events( resize, minimize, move, focus, …  )
• Phone events ( touch, scale, flipping, … )
• …And the list goes on…

The type of the event is contained int the .event. This is an enum of the type SDL_EventType If you take a look at the documentation, you’ll see that it has a lot of fields. But to start out, we’ll only look at SDL_Quit and SDL_KeyDown.

Event polling

Now that we know about the SDL_Event, let’s see how we get the event from SDL. The method for doing this is :

As you can see, it’s pretty straight forward. Just pass it a pointer to a SDL_Event and it will populate the structure. If it returns 0, there are no more events. There will most likely be more than one SDL_Event in each iteration, so we’ll need to put this function in a loop.

SDL_Quit

The first SDL_EventType we’ll be handling is SDL_QUIT. Which occurs when the user quits our game. Either using the x on the top of the window or Alt + F4

And there we go! Now the user can exit the program. Which is rather important…

SDL_KeyDown

Let’s handle a more interesting event. Namely keyboard presses. These have the event type
SDL_KeyDown. All possible key presses is stored within the enum called SDL_KeyCode. If you want to see all possible values, you can look at the documentation. We won’t dive into the details of the where the SDL_KeyCode is stored right now because, as I said, it’s stored deep inside the SDL_Event. Instead we’ll just tell you were to find the SDL_KeyCode.

event.key.keysym.sym

Where the last sym is the actual SDL_KeyCode 

Moving things

And now we’ve come to the highpoint of this part, namely moving something based on user input. Doing this is fairly easy, we already have most code for it. All we need to do is to store the location ( SDL_Rect ) of what we are trying to move somewhere ( for now we’ll let it be a global variable along with SDL_Renderer and SDL_Window. )

We can render a rectangle normally like in the last part and move it around based on user input. We’ll use the following SDL_KeyCode values for movement

• SDLK_LEFT    – left arrow key
• SDLK_RIGHT – right arrow key
• SDLK_UP       – up arrow key
• SDLK_DOWN – down arrow key

As you can see, the names are very self-explanatory. And moving the item is as simple as incrementing the x and y of the SDL_Rect. So we get

This will handle arrow key presses and move the object accordingly.

Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com

Drawing rectangles

This part will teach you the basics of the coordinate system in SDL( it’s the same for the “old” SDL and SDL2 ). It will also teach you about a new and very important struct, SDL_Rect. You’ll be using it a lot! And finally we’ll draw something!

Note

This part assumes you have SDL2 up and running on your computer, and that you have read the previous part. If you haven’t, please scroll down to part1 and use it to install SDL2 before reading on.

The coordinate system

The SDL coordinate system is defined as ( 0, 0 ) being the ( top, left ). This means that a higher y value means further down.

This also means that if you tell SDL2 to draw a rectangle, you’ll specify the top-left position of the rectangle instead of the bottom left rectangle. More about this later

The basic rectangle

In order to draw something, be it textures or plain rectangles or text or anything, you need a rectangle to specify where to draw it and the size of what you are going to draw. And to hold the size and position we use an SDL_Rect

SDL_Rect

Data members :

• uint16 x – the x position of the rectangle
• uint16 y – the y position of the rectangle
• uint16 w – the width of the rectangle
• uint16 h – the height of the rectangle

And that’s it. It’s a really simple struct, but it’s very important in SDL2 rendering.

Drawing a rectangle

Now you have enough knowledge to draw some rectangles in SDL2. Let’s start off by looking at a the function for rendering a simple rectangle

Parameters

• SDL_Renderer* - the SDL_Renderer we created in the previous part
• SDL_Rect*  - the position and size of the rectangle we want to draw.

Return value

0 on success

Note that it also takes a pointer to the SDL_Rect, and not the SDL_Rect itself.

“But what about the color?” you might ask. Remember how in last function we look at
int SDL_SetRenderDrawColor()? Well, basically, the color you set with this function will also be the color you render your objects with. ( For simplicity, I will refer to this color as SDL_DrawColor from now on. )

And now the fun stuff

Let’s say you have just created and set up your window and renderer like so:

But wait! It’s just a red screen?! As you might have guessed, we forgot to change the color after calling SLD_RenderClear() So the rectangle was drawn with the same color as the background. To make the rectangle visible, we need to change SDL_DrawColor in between SDL_RenderClear() and SDL_RenderDrawRect()

This gives us something like this :

And now we have a nice little rectangle on our screen.

Filling it up…

The function I showed you earlier will only render the edges of the rectangle. What if you want to render the whole rectangle, and not just the edges? Well there is a nearly identical function for that :

Parameters

• SDL_Renderer* - the SDL_Renderer we created in the previous part
• SDL_Rect*  - the position and size of the rectangle we want to draw.

Return value

0 on success

As you can see, the only thing that separates the two us the name. If you switch SDL_RenderDrawRect() with SDL_RenderFillRect() in the example above, you will get the same rectangle with the same color, but this time it will be the whole rectangle and not just the edges.

Conclusion

That’s it for today! Feel free to experiment with two new functions. You can draw as many rectangles as you want, both filled and edges. You can also change the color as often as you want. The only thing you need to remember is to put it all between your SDL_RenderClear( renderer ); and SDL_RenderPresent( renderer );

Have fun! Below is a full working example to experiment with. I have taken the liberty of putting things in different functions to make it easier to read. =)

The comments in the code should explain most of what’s going on. But you need to run the program to really see what’s going on. The code will draw a single blue rectangle on a green background that you can move around on the screen. Don’t worry about the code for moving the player around ( RunGame() ), it’ll be explained in the next post.

Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com

[ SDL2 – Part 2 ] Your first SDL2 application

This part will teach you the basic parts of SDL2 namely SDL_Renderer and SDL_Window, what they do and how we use them in order to create a simple window.

SDL2 structures

The SDL2 library has a substantially improved rendering structure from the old SDL. The new structure is very simple and easy to understand. This is a short tutorial / reference guide that will teach you everything you need to know in order to start programming SDL2 applications.

The two major objects you need to know :

SDL_Window

This is the physical window you see on your screen. One SDL_Window represents one physical window on your screen. You can have as many SDL_Windows as you like. The structs holds info about the window like position, size, window state and window style.

SDL_Renderer

The SDL_Renderer is basically what you use to render to the screen. The renderer is usually tied to a window. One renderer can only render within one window. The SDL_Renderer also contains info about the rending itself like hardware acceleration and v-sync prevention.

This tutorial will focus on creating and setting up these so we can start drawing to our screen.

Setting up SDL2

Before you can use SDL2, you must set it up by initializing it and creating a SDL_Window and a SDL_Renderer This section will help you to just that.

Initializing SDL2

The first thing you need to do is to initialize SDL. This is done using the following function :

Parameters :

• flags – specifies what you want to initialize. Set it to SDL_INIT_EVERYTHING to initialize everything.

Return value

0 on success -1 oterwise

Since the function can fail ( though it probably won’t ) you should add code that handles this. I also recommend you print an error message with SLD_GetError() because it will tell you what went wrong. This tutorial will do this for the most important setup functions.

This makes our code so far look something like this :

Setting up the SDL_Window

Now that we have initialized SDL2, we can can start creating our window, this is done by using the following function :

Parameters :

• title -the window caption/title that appears on the top of the window
• posX – x position of the window.
• posY – y position of the window.
• sizeW – width of the window
• sizeH – height of the window
• flags – specifies window state or properties. More info here

The flags parameters has a few different possible values I will not go through all of them, but you can read about them here

Here are the flags that are most revelant to us now.

• SDL_WINDOW_FULLSCREEN -the window will start out in fullscreen mode
• SDL_WINDOW_FULLSCREEN_DESKTOP -the window will start out in fullscreen mode with the same resoltion as your desktop currently has
• SDL_WINDOW_OPENGL -for use with OpenGL, see my tutorial on OpenGL
• SDL_WINDOW_SHOWN -the window will start out being visible
• SDL_WINDOW_HIDDEN -the window will start out being invisible

The window will always start out visible, regardless of whether SDL_WINDOW_SHOWN is set. The only way to make a window start out as hidden is to pass SDL_WINDOW_HIDDEN. Because of this, the SDL_WINDOW_SHOWN flag is ignore by SDL_CreateWindow, and we can just pass 0 here.

Return value

A valid pointer on success. nullptr / NULL on oterwise

We’ll set the flag parameter to 0 for now. This simply means we’ll end up with a standard window that’s not maximized, minimized or fullscreen.

Remember to handle it if the function returns NULL. So we end up with something like this :

Creating the SDL_Renderer

Now for the last object we need to start rendering. This time it’s a little bit more work involved, but nothing too scary. We begin by creating the renderer. This is done using the following function :

Parameters :

• window – the SDL_Window this renderer will be attached to. In our case, this is the SDL_Window we just created.
• index - specifies which rendering driver to use. It sounds complicated, but we can just specify -1. This means we’ll use the first driver we can find.
• flags - species how the rendering should be done. For now, we’ll just use SDL_RENDERER_ACCELERATED which lets us use the graphics card to render quickly. You can read more here.

Return value :

Window a valid pointer on success. Otherwise nullptr / NULL.

As always ; remember to handle any return of 0.

Setting up the renderer

Now that we have created the SDL_Renderer we are technically ready to start rendering. But there are a few more things we should do first…

First of all we should set the resolution of the renderer :

Parameters :

• renderer – the SDL_Renderer we want to set the resolution on.
• width - the desired width in pixels
• height - the desired height in pixels

Return value

0 on success -1 oterwise

This is pretty straight forward, the first argument is the renderer on which to set the resolution on. The second and third is the width and height. Normally these are the same as the width and height of the SDL_Window.

And now the time has come to set the color. Here is the function for doing that :

Parameters :

• renderer – the SDL_Renderer on which to set render color
• red - specifies amount of red ( 0 – 255 )
• green - specifies amount of green ( 0 – 255 )
• blue - specifies amount of blue ( 0 – 255 )
• alpha - specifies amount of alpha ( 0 – 255 ) 0 = completely transparent

Return value

0 on success -1 oterwise

That’s it! We’re done with the setup. And now we can start using the renderer for fun stuff!

Rendering something

Now it’s time to get started on the renderng.
The first thing we need to do before drawing something, is to clear our window. This means we fill our window with the color we set using SDL_SetRenderDrawColor()

This is done by calling :

Parameters :

• renderer – the SDL_Renderer that we’ll clear

Return value

0 on success -1 oterwise

This function should be called at the beginning on every frame to clear the screen and make it ready for more stuff.

But… SDL_RenderClear ( and any other SDL_Render functions ) works behind the scenes. They don’t actually draw anything on the screen. So, in order for he drawing ( including SDL_RenderClear ) to take effect, we need to call another function.

Parameters :

• renderer – the SDL_Renderer on which to render

Return value

0 on success -1 oterwise

This function takes whatever you have drawn to the screen using SDL_Render* and actually puts it on the screen. So that after calling this, the screen will be all nice and red. And that’s it for now. In the next part I’ll go into rectangles and actually rendering something interesting ( yes, I assume red screens doesn’t catch your interest. )

Conclusion

That’s if for part 2. We now have a nice red window. Next time we’ll be rendering rects and other neat stuff.

Here is all the code so far. You should be able to just copy paste and compile.

Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com

Introduction

This tutorial will teach you how to program your own games using C++ and SDL2! This first part will just teach you how to set up SDL2. Don’t worry, it’s very easy. And when you’re done, you can jump ahead to part 2 where we will get something on screen.

This series is a little fast-paced and is mostly aimed at people who knows the basics of programming in C++, but I will try to explain everything. The series will also explain the various types and functions in SDL2, what they do, and what they are for. By the end of the series, you will have a good understanding of SDL2.

During the series we will be making several small games, but I recommend that you play around with the code and have fun. The best way of learning is to experiment.

So what is SDL2?

SDL2 is a cross-platform multimedia development library. You can use SDL2 to access your keyboard, for graphics, play sounds and for communication over Internet. SDl2 can also be used alongside with OpenGL. SDL2 can create the window for OpenGL and be used for text rendering, multiplayer and image loading.

SDL2 brings on a set of changes from SDL1.2. First of all, SDL2 has support for hardware acceleration, which means it’ll be very fast compared to SDL1.2. It also has an improved rendering structure with an object representing the window and an object for dealing with the rendering. I will cover these in more detail in the next post. For now, let’s just install it.

Installation

Installing SDL2 can be a bit tricky, especially on some operating systems where you might have to compile it yourself ( though this is becoming more rare. )

Linux

Linux comes in all shapes and sizes. Below are guides on how to install on most distributions of Linux.

Debian ( Ubuntu, Debian, Mint )

Depnding on your distro and version, you might be able to install SDL2 using the package manager. I.e :

sudo apt-get install libsdl2

If your package manager does have SDL2. it will be installed and you’re done. If not, you’ll have to compile SDL2 yourself Don’t worry, it’s easy. Just follow this excellent guide :

Arch

Probably the easiest. Simply use pacman :

sudo pacman -S sdl2

And that’s all, SDL2 is installed now.

Fedora

Just as easy as Arch :

sudo yum install sdl2

Note: Since I’m not running Fedora, I haven’t been able to test this. But it should work, and if it doesn’t, feel free to post a comment ( you’ll be the first, you lucky bastard! )

Other distros?

If you are using other distributions, there are three things you can try.

1. Simply use your package manager and see if it has SDL2/, libsdl2 or lSDL2 or something like that.
2. Try Google! Yes, I know it’s kinda obvious, but chances are someone else has had the same issue, it’s worth a shot.
3. If 1 and 2 doesn’t work, you could still try the guide for Debian. You will have to switch sudo apt-get install with the command for install packages on your distribution.

Windows

Setting up SDL2 in Windows is a littel bit more complicated, so I made a seperate post for it. You can find it here.

Mac

This will be the shortest guide and it will only cover homebrew since I don’t have the access to any computer running OS X.

In terminal simply type

brew install SDL2

Note: Since I haven’t actually tested this, I can’t guarantee that it will work.

Testing it

Now we come to the fun part, we get to actually use it and run or SDL2 application. Our end result isn’t terribly exiting this time, it just creates an empty window with a red background. But things will get better, I promise!

Compiling on Linux and Mac using terminal

To compile on Linux, simply add lSDL2 to your compilation string. To compile main.cpp you can do

clang++ main.cpp -lSDL2 -o SDLTest

If you are using GCC, the compilation string is

g++ main.cpp -lSDL2 -o SDLTest

Compiling on Linux and Mac without terminal

If you’re not using the terminal, you need to set up your IDE to use the SDL2 libraries. This should be a simple process, check the documentation for you IDE to find exactly how to do this. I do recommend using the terminal, though. It’s much simpler.

Compiling on Windows in VisualStudio

If you have followed my guide, you shouldn’t have to do anything in order to compile.

If you get any compile errors you need to check your include directory. Remember that you should add the folder that has the SDL2 folder, but not the SDL2 folder itself. This is because the example code uses #include

If you get linker errors, make sure you have added the folder with the SDL2.lib file.

If you get runtime errors, make sure you have all the .dll files in an appropriate directory.

Sample code

To test it, simply replace the content with your main.cpp with the following code snippet. If it displays a window, SDL2 is working properly on your window. Don’t worry about the code just now, I’ll explain it in the next part.

Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com

Introduction to the series

I thought I’d start of by talking about my favorite thing that’s new about C++11 standard. C++11 has a lot of useful new features : auto, initializer lists, lambda, shared_ptr, unique_ptr, move semantics, etc. Some of these are quite comprehensive and complicated, and I’m still working on understanding all of them. But this one is actually quite simple.

Enum classes are basically enumerations that can’t implicitly be converted to integer types. So basically you can’t write :

Why is this such a good thing?

First of all it helps code clarity. A simple question : Say you have an enum of card suits, which would you prefer?

Using and enforcing enum classes means you’ll instantly know what the value is, so you’ll never have to find the actual definition of the enum and look up what the different int values does.

So it helps code clairty. Is that all?

No! There are more serious issues. Say you have the following code

This might look okay, they both set the card to Suit::Clover. But here comes the big issue. Someone changes the order of the elements in Suit.

What’s the issue?

It might seem a very subtle change. But you let’s say you implemented reset method a long time ago. It’s been working fine ever since, and you’ve completely forgotten that it uses and integer value to set suit. It’ll now do something different from the constructor! So you end up with cards being different when you reset them from when you create them. And issues like this can be very confusing and hard to debug.

This is just a minimal example to showcase the issue. But this can happen just as easily in huge projects where the enum is used hundreds of places. Debugging such issues will waste a huge amount of time and cause a whole lot of pain and agony. All because of using an integer to assign an enum! Using enum class prevents these issues.

Conclusion

Use enum classes! It might be a bit annoying having to write the full enumeration name sometimes. But it’s a lot better than spending hours upon hours debugging when someone changes the order of the enumeration items or adds a new value in front of others!

Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com