SDL2 vs SDL3 Relative Mode
How does relative mode work differently in SDL2 vs. SDL3?
SDL3 introduces several important changes to relative mouse mode handling. Here's a comprehensive comparison of the differences:
// SDL2 Version
#include <SDL.h>
#include "Window.h"
class SDL2MouseHandler {
public:
bool Initialize(SDL_Window* Window) {
// SDL2: Global relative mode
return SDL_SetRelativeMouseMode(SDL_TRUE) == 0;
}
};
// SDL3 Version
#include <SDL3/SDL.h>
#include "Window.h"
class SDL3MouseHandler {
public:
bool Initialize(SDL_Window* Window) {
// SDL3: Window-specific relative mode
return SDL_SetWindowRelativeMouseMode(
Window, SDL_TRUE) == 0;
}
};
Key differences include:
- SDL3 uses window-specific relative mode instead of global
- SDL3 provides better multi-window support
- SDL3 adds new configuration options
- SDL3 improves error handling and reporting
Here's a more detailed example showing how to write code that works with both versions:
#include <SDL.h>
#include <iostream>
#ifdef SDL_MAJOR_VERSION
#if SDL_MAJOR_VERSION >= 3
#define SDL3_MODE
#endif
#endif
class PortableMouseHandler {
public:
bool Initialize(SDL_Window* Window) {
#ifdef SDL3_MODE
if (SDL_SetWindowRelativeMouseMode(
Window, SDL_TRUE) < 0
) {
std::cout << "SDL3: Failed to enable "
<< "relative mode\n";
return false;
}
#else
if (SDL_SetRelativeMouseMode(SDL_TRUE)
< 0) {
std::cout << "SDL2: Failed to enable "
<< "relative mode\n";
return false;
}
#endif
return true;
}
void Cleanup(SDL_Window* Window) {
#ifdef SDL3_MODE
SDL_SetWindowRelativeMouseMode(
Window, SDL_FALSE);
#else
SDL_SetRelativeMouseMode(SDL_FALSE);
#endif
}
};
The main considerations when migrating from SDL2 to SDL3 are:
- Update function calls to use window-specific variants
- Review error handling as error codes may differ
- Test multi-window scenarios if applicable
- Update any custom relative mode management code
- Review documentation for new SDL3 features and hints
Relative Mouse Mode
Learn how to restrict cursor movement to a window whilst capturing mouse motion continuously.