SDL Library - Overview

In this article I will try to give a brief overview of the very useful open-source SDL library (Simple DirectMedia Library) for writing cross-platform multimedia applications. On the habr, it was hardly mentioned, so I want to fill this "gap".
Intro
SDL is positioned as a tool that provides a platform-independent low-level API for access to hardware features such as 2D and 3D rendering, audio playback and processing of input devices (mouse, keyboard, joystick). Liba can be useful mainly for those involved in the development of cross-platform games, but with the same success it can be used, for example, in programs like video and audio players, emulators, etc. In addition to the above features, SDL has tools for working with multithreading, files, timers and a CD / DVD drive. This allows you to use the lib also in those projects that are not related to graphics and / or sound reproduction.
SDL has been ported to many platforms. In addition to Windows, Linux, and Mac OS (X), there are also ports on Solaris, IRIX, * BSD, etc. A complete list is on the main page of the project , it also lists the bindings to many programming languages, including scripted.
Distributed under the GNU LGPL license . The current version 1.2.14, according to the developers, was released to fix a number of bugs and is the last in the 1.2 branch, the next one will be 1.3.
A little bit about installation and API
For all platforms, the necessary files are available for download at the office. site, and for Linux you can also search for lib in turnips (at least under Ubuntu I found it in the libsdl-dev package). Sources are available in archives, or on svn.
SDL does not require installation as such. It is usually connected in the form of a dynamic library, for distribution with the program it is enough to attach a single .so file (.dll).
SDL is written in C. The interface consists of functions and macros, the list of which is not so large and not difficult to learn. On the API project wiki , functions and data types are grouped both alphabetically and by category, so you can find something you need almost without difficulty.
A small example
Below is a simple example of a program using SDL:
#include
int main()
{
// Инициализация подсистем SDL (видео, аудио и тайминг)
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) < 0)
return 1;
// Флаг центрирование окна на экране
SDL_putenv("SDL_VIDEO_CENTERED=true");
// Инициализация видео. В данном случае оконный режим, 800x600@16 с получением контекста OpenGL и двойной буферизацией
SDL_Surface *surface = SDL_SetVideoMode(800, 600, 16, SDL_DOUBLEBUF | SDL_OPENGL);
if (surface == NULL)
return 1;
// Цикл обработки сообщений и рендеринга
SDL_Event evt;
bool stop = false;
while (!stop)
{
// Извлекаем события из очереди
while (SDL_PollEvent(&evt))
{
switch (evt.type)
{
case SDL_KEYDOWN:
// Завершаемся при нажатии Esc...
if (evt.key.keysym.sym == SDLK_ESCAPE)
stop = true;
case SDL_QUIT:
// ... или при закрытии окна
stop = true;
default:;
}
}
// Здесь может быть код отрисовки
// ...
// Меняем местами GL фреймбуферы
SDL_GL_SwapBuffers();
}
// Завершаем работу всех подсистем SDL и освобождаем выделенную память
SDL_Quit();
return 0;
}
* This source code was highlighted with Source Code Highlighter.( it’s unusual for me to write comments in Russian, but since probably not everyone is good with English, just in case I leave it like that )
I ’ll go over the code. First of all, we initialize the subsystems we need. In this case, this is video, audio and timing. After that, we separately set the video mode with the SDL_SetVideoMode () function, which returns the created video context. She also part-time also creates a window in which the rendering will take place. There are a lot of initialization flags, a complete list is on the wiki.
After the preliminary settings, we proceed to the main working cycle of the program. At each iteration, it extracts information from the queue about the events that occurred, after which it swaps framebuffers (double buffering is enabled). Between these two actions, you can create something more meaningful, for example, draw another frame of animation. The loop is executed until the window is closed or the Esc key is pressed. Before shutting down, we call the SDL_Quit () function, which closes all SDL subsystems.
As you can see from the example, the SDL API is very simple, preparing the system for work takes only a couple of lines, and the event processing cycle is similar to the standard message processing cycle of Windows programs.
Outro
Finally, I want to note a few additional points:
- For development on OpenGL, SDL is a worthy alternative to GLUT. It can be integrated with various engines (I was able to get it to work together with OGRE).
- SDL is not intended to create any interface elements other than ordinary windows, and in this respect cannot compete with projects such as Qt or wxWidgets.
- The project has quite convenient documentation in several languages, including in offline version. In addition to the wiki, there is a detailed description of the features of the library and many lessons compiled by the community.
- The library has earned considerable popularity among igrodelov (mainly under Linux), and is used in projects such as Nexuiz and Civilization: Call To Power. I myself learned about the lib, delving into the Nexuiz files and stumbling upon the SDL abbreviation still incomprehensible to me at that time :).
- A list of APIs is available that the library itself uses on different platforms to output graphics and sound.
- Finally, the main developer of the library is Sam Lantinga, a software engineer from the notorious Blizzard Entertainment :)
That's all. The review turned out to be very superficial, although I hope it will be useful to those in whose area of interest is the development of multimedia applications, and who have not heard about this library.