```{index} single: SDL2 ``` # SDL2 ```{pperl-module-badges} SDL2 ``` Perl bindings for SDL2 - windows, input, timers and hardware-accelerated 2D drawing. SDL2 is the library behind a large share of the cross-platform games and media applications written in the last decade. This module makes it available to Perl with no compiled binding to build: drawing and input go to the `libSDL2-2.0.so.0` installed on the machine, which is located the first time the module is used. If that library is absent, the first SDL call dies with a message naming the distribution package to install. ## Two layers There are two ways to use this module, and they interoperate freely. The **direct layer** mirrors SDL2's C API one-for-one - same function names, same argument order, same return values. Every prototype in SDL2's own documentation applies unchanged, which is what you want when you are following an SDL tutorial or porting C: ```perl use SDL2 qw(:all); SDL_Init(SDL_INIT_VIDEO); my $win = SDL_CreateWindow('hello', 100, 100, 640, 480, SDL_WINDOW_SHOWN); ``` The **object layer** wraps the same calls as Perl objects that free themselves, which is what you want when writing Perl rather than transcribing C: ```perl use SDL2; my $win = SDL2::Window->new(title => 'hello', w => 640, h => 480); my $ren = $win->renderer; ``` Handles pass between the layers in both directions: a direct-layer function accepts an object wherever it expects a handle, and `SDL2::Window->from_handle($h)` adopts a raw handle. ## Lifetime An object frees its SDL resource when the last Perl reference to it goes away, so nothing has to be destroyed by hand. Raw handles from the direct layer are yours to destroy, exactly as in C. Destroying a resource through the direct layer while an object also holds it is safe: the object is emptied at the same time, so it will not free it a second time. ## Errors The two layers report failure differently, each following its own convention. A direct-layer function returns what C returns - a negative integer or an undefined handle - and leaves the reason in `SDL_GetError()`. An object-layer method croaks with that text instead, so an error is an exception you can trap with `eval`. Because a failed object-layer call is an exception, a successful one returns the object itself. That means calls chain: ```perl $ren->set_draw_color(30, 30, 40, 255)->clear; $ren->fill_rect([10, 10, 40, 20]); $ren->present; ``` and it means **`or die` is for the object layer only**. On a direct-layer call it is always wrong, because C reports success with zero: ```perl $ren->clear or die; # correct: clear croaks, so this # never fires SDL_RenderClear($ren) or die; # WRONG: 0 IS success SDL_RenderClear($ren) == 0 or die "clear: " . SDL_GetError(); # right ``` The one object-layer method that returns nothing is `destroy`. It is the explicit finalizer, so there is nothing left to chain from. ## Exports and constants `use SDL2` exports nothing. Every direct-layer `SDL_*` function and every constant can be asked for by name, or by tag: `:init` (`SDL_INIT_*`), `:window` (`SDL_WINDOW_*`, `SDL_WINDOWPOS_*`), `:gl` (`SDL_GL_*` attributes), `:render` (renderer, flip, texture-access and blend-mode flags), `:events` (event types such as `SDL_QUIT` and `SDL_KEYDOWN`, window events, mouse buttons), `:keycode` (`SDLK_*`, `KMOD_*`), `:scancode` (`SDL_SCANCODE_*`), `:pixels` (`SDL_PIXELFORMAT_*`), `:syswm` (`SDL_SYSWM_*`), `:misc` (`IMG_INIT_*`, for `SDL2::Image`), and `:all` for everything. The values are those of SDL 2's own headers. The object-layer methods are reached through their objects and are never exported. ## Modules - [`SDL2::Events`](SDL2/Events) - Keyboard, mouse and window events. - [`SDL2::Image`](SDL2/Image) - `SDL2::Image` - loading and saving image files. - [`SDL2::Render`](SDL2/Render) - Hardware-accelerated 2D drawing: renderers and textures. - [`SDL2::Surface`](SDL2/Surface) - Surfaces - images in ordinary memory. - [`SDL2::Video`](SDL2/Video) - Windows and OpenGL contexts. ## Functions ### Lifecycle #### `SDL_Init` Initialise the SDL subsystems named by the OR of `SDL_INIT_*` flags. #### `SDL_InitSubSystem` Initialise one further subsystem after `SDL_Init` has run. #### `SDL_Quit` Shut SDL down and release everything it holds. #### `SDL_QuitSubSystem` Shut down just the subsystems named by the flags. #### `SDL_WasInit` Which of the subsystems named by the flags are currently initialised, as the OR of their `SDL_INIT_*` bits. Pass 0 to ask about all of them. #### `have_sdl` True when libSDL2 was found on this machine. ### Errors and version #### `SDL_GetError` The message describing the last SDL call that failed, or the empty string if none has. The direct layer leaves failures here rather than dying, so this is how you find out what went wrong. #### `SDL_ClearError` Forget the last error message. #### `SDL_GetVersion` The version of the SDL2 library actually loaded, as the list `($major, $minor, $patch)`. #### `version` The loaded SDL2 library's version as a string, `"2.30.1"`. #### `SDL_GetPlatform` The name SDL gives this platform, such as `"Linux"`. ### Timing #### `SDL_GetTicks` Milliseconds since SDL was initialised. #### `SDL_Delay` Sleep for the given number of milliseconds. ### Renderers #### [`SDL_CreateRenderer`](SDL2/SDL_CreateRenderer) Creates a renderer for a window and returns its handle, or undef. #### `SDL_DestroyRenderer` Frees a renderer. Accepts a raw handle or an `SDL2::Renderer`, emptying the object so it will not free the renderer again. #### `SDL_RenderPresent` Shows everything drawn since the last present. The last call of every frame; nothing appears on screen until you make it. #### `SDL_RenderSetLogicalSize` Fixes the coordinate system the renderer draws in, letting SDL scale to whatever size the window actually is. Draw against 320x240 and it stays correct when the user resizes. Returns 0 on success. #### `SDL_GetRendererOutputSize` The renderer's drawable size in pixels, as the list `($w, $h)`. #### `SDL_RenderReadPixels` Reads pixels back from the rendering target as a byte string, four bytes per pixel in RGBA order, row by row with no padding. #### `SDL_SetRenderTarget` Directs subsequent drawing into a texture instead of the window. Pass undef to go back to the window. The texture must have been created with `SDL_TEXTUREACCESS_TARGET`. Returns 0 on success. ### Drawing #### `SDL_RenderClear` Fills the whole rendering target with the current draw color. The first call of every frame. Returns 0 on success. #### `SDL_SetRenderDrawColor` Sets the color used by the drawing calls and by `SDL_RenderClear`. Components are 0 to 255; alpha defaults to 255 (opaque) and only has an effect when the blend mode is not `SDL_BLENDMODE_NONE`. #### `SDL_GetRenderDrawColor` The current draw color, as the list `($r, $g, $b, $a)`. #### `SDL_SetRenderDrawBlendMode` Chooses how drawing combines with what is already there. `SDL_BLENDMODE_NONE` overwrites; `SDL_BLENDMODE_BLEND` composites using the alpha channel, which is what you want for anything translucent. Returns 0 on success. #### `SDL_RenderDrawPoint` Draws one pixel in the current draw color. Returns 0 on success. #### `SDL_RenderDrawLine` Draws a line between two points in the current draw color. Returns 0 on success. #### `SDL_RenderDrawRect` Draws the outline of a rectangle. Pass undef for the whole target. Returns 0 on success. #### `SDL_RenderFillRect` Fills a rectangle with the current draw color. Pass undef for the whole target. Returns 0 on success. #### `SDL_RenderCopy` Draws a texture. `$src` selects part of the texture and `$dst` says where on the target it goes; undef means the whole of either. Returns 0 on success. #### `SDL_RenderCopyEx` Draws a texture rotated and/or mirrored. `$angle` is in degrees clockwise, `$center` is the pivot as `[x, y]` relative to `$dst` (undef for its middle), and `$flip` is the OR of `SDL_FLIP_*`. Returns 0 on success. ### Textures #### `SDL_CreateTexture` Creates an empty texture. `$access` is one of `SDL_TEXTUREACCESS_STATIC`, `STREAMING` or `TARGET`. Returns the handle, or undef on failure. #### `SDL_CreateTextureFromSurface` Uploads a surface to the GPU as a texture. Returns the handle, or undef. #### `SDL_DestroyTexture` Frees a texture. Accepts a raw handle or an `SDL2::Texture`. #### `SDL_QueryTexture` A texture's properties as the list `($format, $access, $w, $h)`. #### `SDL_SetTextureAlphaMod` Scales the texture's alpha when it is drawn, 0 to 255. Returns 0 on success. #### `SDL_SetTextureColorMod` Tints the texture when it is drawn: each channel is multiplied by the value you give divided by 255. Returns 0 on success. #### `SDL_SetTextureBlendMode` Chooses how the texture combines with what is under it. Returns 0 on success. ### Event queue #### `SDL_PollEvent` Takes the next event off the queue and returns it as a hash reference, or undef when there is nothing waiting. #### [`SDL_PushEvent`](SDL2/SDL_PushEvent) Puts an event on the queue, so a later `SDL_PollEvent` returns it. #### `SDL_WaitEvent` Waits for the next event and returns it as a hash reference, blocking until one arrives. Returns undef if the wait fails. #### `SDL_WaitEventTimeout` Waits up to `$ms` milliseconds for an event. Returns the event as a hash reference, or undef if the timeout passed with nothing to report. #### `SDL_PumpEvents` Collects pending input from the operating system into SDL's queue. #### `SDL_FlushEvents` Discards queued events whose type falls between `$min` and `$max` inclusive. Called with no arguments it discards everything. #### `SDL_HasEvents` True when the queue holds an event whose type is between `$min` and `$max` inclusive. ### Keyboard #### [`SDL_GetKeyboardState`](SDL2/SDL_GetKeyboardState) The whole keyboard as a string of bytes, one per scancode, each 1 when that key is down. Index it with a `SDL_SCANCODE_*` constant: #### `key_pressed` True when the physical key named by a `SDL_SCANCODE_*` constant is held down right now. #### `SDL_GetModState` The modifier keys held down right now, as the OR of the `KMOD_*` constants. #### `SDL_GetKeyName` The printable name of a key symbol, such as `"Left"` or `"A"`. The empty string if there is no such key. #### `SDL_GetScancodeName` The printable name of a physical key position, such as `"Left"`. #### `SDL_GetKeyFromName` The key symbol with the given name - the inverse of `SDL_GetKeyName`. Returns `SDLK_UNKNOWN` if the name is not one SDL knows. #### `SDL_GetKeyFromScancode` The key symbol a physical key currently produces, which depends on the user's keyboard layout. #### `SDL_GetScancodeFromKey` The physical key that currently produces a key symbol. ### Mouse #### `SDL_GetMouseState` The mouse as the list `($buttons, $x, $y)`. `$buttons` is a bitmask - test it against `SDL_BUTTON_LMASK` and its siblings - and the position is relative to the focused window. ### Surfaces #### `SDL_SaveBMP` Writes a surface as a BMP file. Returns 0 on success. #### `SDL_FreeSurface` Frees a surface. Accepts a raw handle or an `SDL2::Surface`. ### Windows #### [`SDL_CreateWindow`](SDL2/SDL_CreateWindow) Creates a window and returns its handle, or undef on failure. #### `SDL_DestroyWindow` Closes a window and frees it. Safe to pass either a raw handle or an `SDL2::Window`; passing the object also empties it, so its own cleanup will not free the window a second time. #### `SDL_SetWindowTitle` Sets the window's caption. #### `SDL_GetWindowTitle` The window's caption. #### `SDL_SetWindowSize` Resizes the window's client area to `$w` by `$h` pixels. #### `SDL_GetWindowSize` The window's client area as the list `($w, $h)`. #### `SDL_SetWindowPosition` Moves the window so its top-left corner is at `($x, $y)`. #### `SDL_GetWindowPosition` The window's top-left corner as the list `($x, $y)`. #### `SDL_ShowWindow` Makes a hidden window visible. #### `SDL_HideWindow` Hides the window without destroying it. #### `SDL_RaiseWindow` Brings the window to the front and gives it the input focus. #### `SDL_MaximizeWindow` Makes the window as large as the window manager allows. #### `SDL_MinimizeWindow` Iconifies the window. #### `SDL_RestoreWindow` Returns the window to its size and position from before it was minimized or maximized. #### `SDL_SetWindowFullscreen` Switches the window between windowed and full screen. Pass 0 for windowed, `SDL_WINDOW_FULLSCREEN` for a real video-mode change, or `SDL_WINDOW_FULLSCREEN_DESKTOP` for a borderless window filling the display - which is what most programs want. Returns 0 on success. #### `SDL_SetWindowResizable` Allows or forbids the user resizing the window. #### `SDL_SetWindowBordered` Shows or hides the window's border and title bar. #### `SDL_GetWindowFlags` The OR of the `SDL_WINDOW_*` bits describing the window's current state. #### `SDL_GetWindowID` The window's numeric id - what an event's `window_id` field holds, so this is how you tell which of several windows an event came from. #### `SDL_GetWindowFromID` The window handle for a numeric window id, or undef if there is no such window. This is how an event's `window_id` becomes the window it happened in, when a program has more than one. #### `SDL_UpdateWindowSurface` Copies the window's surface to the screen. Only for windows drawn through `SDL_GetWindowSurface`; a window with a renderer uses `SDL_RenderPresent` instead. Returns 0 on success. #### `SDL_GetCurrentVideoDriver` The name of the video driver SDL initialised, or undef when the video subsystem is not up. #### [`SDL_GetWindowWMInfo`](SDL2/SDL_GetWindowWMInfo) The window manager's own handles for this window, as a hash reference, or undef when SDL will not say. ### OpenGL #### `SDL_GL_SetAttribute` Requests an OpenGL context attribute BEFORE the window is created. Setting `SDL_GL_CONTEXT_MAJOR_VERSION`, `SDL_GL_CONTEXT_MINOR_VERSION` and `SDL_GL_CONTEXT_PROFILE_MASK` is how you ask for a specific OpenGL version. Returns 0 on success. #### `SDL_GL_GetAttribute` The value an OpenGL context attribute actually has - which can differ from what you asked for, since the driver may give you more than you requested. Returns the list `($result, $value)`, `$result` being 0 on success. #### `SDL_GL_CreateContext` Creates an OpenGL context for a window created with `SDL_WINDOW_OPENGL`, and makes it current. Returns the handle, or undef on failure. Free it with `SDL_GL_DeleteContext`. #### `SDL_GL_DeleteContext` Frees an OpenGL context. #### `SDL_GL_MakeCurrent` Makes a context current on a window, which is what you call when rendering to more than one window. Returns 0 on success. #### `SDL_GL_SwapWindow` Shows the frame OpenGL has just drawn - the OpenGL counterpart of `SDL_RenderPresent`. #### `SDL_GL_SetSwapInterval` Chooses how `SDL_GL_SwapWindow` waits: 0 for no wait, 1 to sync with the display's refresh, -1 for adaptive sync. Returns 0 on success, and -1 if the request is not supported. #### `SDL_GL_GetSwapInterval` The swap interval currently in effect. #### `SDL_GL_GetProcAddress` The address of an OpenGL function, as an integer, or undef if this driver does not have it. #### `SDL_GL_GetDrawableSize` The drawable size in pixels as the list `($w, $h)`. On a high-DPI display this is larger than the window size, which is in screen coordinates - use this one for `glViewport`. ```{toctree} :hidden: :maxdepth: 1 SDL2/Events SDL2/Image SDL2/Render SDL2/Surface SDL2/Video SDL2/SDL_CreateRenderer SDL2/SDL_PushEvent SDL2/SDL_GetKeyboardState SDL2/SDL_CreateWindow SDL2/SDL_GetWindowWMInfo ```