24#include <SDL3/SDL_events.h>
25#include <SDL3/SDL_init.h>
26#include <SDL3/SDL_video.h>
28# include <emscripten.h>
29# include <emscripten/html5.h>
36 Rect r = {left, top, left + width, top + height};
43 this->
MakeDirty(0, 0, _screen.width, _screen.height);
61 template <
typename Func,
typename ... Args>
62 SDLRange(Func func, Args... args) { this->data = func(args..., &this->count); }
73 constexpr T*
begin()
const {
return this->data; }
79 constexpr T*
end()
const {
return this->data +
count; }
85 constexpr size_t size()
const {
return this->count; }
110 if (mode->w < 640 || mode->h < 480)
continue;
142 if (newdelta < delta) {
161 if (
IsInsideBS(startup_display, 0, displays.
size()))
return startup_display;
165 SDL_GetGlobalMouseState(&mx, &my);
166 for (SDL_DisplayID display : displays) {
168 if (SDL_GetDisplayBounds(display, &r) == 0 &&
IsInsideBS(mx, r.x, r.w) &&
IsInsideBS(my, r.y, r.h)) {
169 Debug(
Facility::Driver,
Severity::Error,
"SDL3: Mouse is at ({}, {}), use display {} ({}, {}, {}, {})", mx, my, display, r.x, r.y, r.w, r.h);
199 flags |= SDL_WINDOW_RESIZABLE;
202 flags |= SDL_WINDOW_FULLSCREEN;
206 this->
sdl_window = SDL_CreateWindow(caption.c_str(), w, h, flags);
214 if (!icon_path.empty()) {
216 SDL_Surface *icon = SDL_LoadBMP(icon_path.c_str());
217 if (icon !=
nullptr) {
219 uint32_t rgbmap = SDL_MapSurfaceRGB(icon, 255, 0, 255);
220 if (!SDL_SetSurfaceColorKey(icon,
true, rgbmap)) {
225 SDL_DestroySurface(icon);
245 if (resize) SDL_SetWindowSize(this->
sdl_window, w, h);
251 if (_fullscreen) _cursor.in_window =
true;
259#ifndef __EMSCRIPTEN__
288 std::vector<int> rates = {};
291 if (mode->refresh_rate != 0) rates.push_back(mode->refresh_rate);
316 assert(vk_first < vk_last);
317 assert(map_first < map_last);
318 assert(this->count ==
static_cast<uint
>(map_last - map_first + 1));
334 { SDLK_PAGEUP, WKC_PAGEUP,
true },
335 { SDLK_PAGEDOWN, WKC_PAGEDOWN,
true },
336 { SDLK_UP, WKC_UP,
true },
337 { SDLK_DOWN, WKC_DOWN,
true },
338 { SDLK_LEFT, WKC_LEFT,
true },
339 { SDLK_RIGHT, WKC_RIGHT,
true },
341 { SDLK_HOME, WKC_HOME,
true },
342 { SDLK_END, WKC_END,
true },
344 { SDLK_INSERT, WKC_INSERT,
true },
345 { SDLK_DELETE, WKC_DELETE,
true },
347 { SDLK_ESCAPE, WKC_ESC,
true },
348 { SDLK_PAUSE, WKC_PAUSE,
true },
349 { SDLK_BACKSPACE, WKC_BACKSPACE,
true },
351 { SDLK_F1, SDLK_F12, WKC_F1, WKC_F12,
true },
357 { SDLK_SPACE, WKC_SPACE,
false },
358 { SDLK_RETURN, WKC_RETURN,
false },
359 { SDLK_TAB, WKC_TAB,
false },
364 { SDLK_KP_DIVIDE, WKC_NUM_DIV,
false },
365 { SDLK_KP_MULTIPLY, WKC_NUM_MUL,
false },
366 { SDLK_KP_MINUS, WKC_NUM_MINUS,
false },
367 { SDLK_KP_PLUS, WKC_NUM_PLUS,
false },
368 { SDLK_KP_ENTER, WKC_NUM_ENTER,
false },
369 { SDLK_KP_PERIOD, WKC_NUM_DECIMAL,
false },
394 bool unprintable =
false;
396 for (
const auto &map : _vk_mapping) {
397 if (
IsInsideBS(key_event->key, map.vk_from, map.count)) {
398 key = key_event->key - map.vk_from + map.map_to;
399 unprintable = map.unprintable;
405 if (key_event->scancode == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
408 if (key_event->mod & SDL_KMOD_GUI) key |= WKC_META;
409 if (key_event->mod & SDL_KMOD_SHIFT) key |= WKC_SHIFT;
410 if (key_event->mod & SDL_KMOD_CTRL) key |= WKC_CTRL;
411 if (key_event->mod & SDL_KMOD_ALT) key |= WKC_ALT;
414 if (key_event->mod & SDL_KMOD_GUI ||
415 key_event->mod & SDL_KMOD_CTRL ||
416 key_event->mod & SDL_KMOD_ALT ||
420 *character = key_event->key;
435 for (
const auto &map : _vk_mapping) {
437 key = kc - map.vk_from + map.map_to;
444 SDL_Scancode sc = SDL_GetScancodeFromKey(kc,
nullptr);
445 if (sc == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
454 if (!SDL_PollEvent(&ev))
return false;
457 case SDL_EVENT_MOUSE_MOTION: {
458 int32_t x = ev.motion.x;
459 int32_t y = ev.motion.y;
461 if (_cursor.fix_at) {
464 while (SDL_PeepEvents(&ev, 1, SDL_GETEVENT, SDL_EVENT_MOUSE_MOTION, SDL_EVENT_MOUSE_MOTION)) {
470 if (_cursor.UpdateCursorPosition(x, y)) {
471 SDL_WarpMouseInWindow(this->
sdl_window, _cursor.pos.x, _cursor.pos.y);
477 case SDL_EVENT_MOUSE_WHEEL: {
478 if (ev.wheel.y > 0) {
480 }
else if (ev.wheel.y < 0) {
485 const float SCROLL_BUILTIN_MULTIPLIER = 14.0f;
486 _cursor.v_wheel -= ev.wheel.y * SCROLL_BUILTIN_MULTIPLIER *
_settings_client.gui.scrollwheel_multiplier;
487 _cursor.h_wheel += ev.wheel.x * SCROLL_BUILTIN_MULTIPLIER *
_settings_client.gui.scrollwheel_multiplier;
488 _cursor.wheel_moved =
true;
492 case SDL_EVENT_MOUSE_BUTTON_DOWN:
494 ev.button.button = SDL_BUTTON_RIGHT;
497 switch (ev.button.button) {
498 case SDL_BUTTON_LEFT:
502 case SDL_BUTTON_RIGHT:
507 case SDL_BUTTON_MIDDLE:
527 case SDL_EVENT_MOUSE_BUTTON_UP:
531 }
else if (ev.button.button == SDL_BUTTON_LEFT) {
534 }
else if (ev.button.button == SDL_BUTTON_RIGHT) {
536 }
else if (ev.button.button == SDL_BUTTON_MIDDLE) {
538 }
else if (ev.button.button == SDL_BUTTON_X1) {
540 }
else if (ev.button.button == SDL_BUTTON_X2) {
547 HandleExitGameRequest();
550 case SDL_EVENT_KEY_DOWN:
551 if ((ev.key.mod & (SDL_KMOD_ALT | SDL_KMOD_GUI)) &&
552 (ev.key.key == SDLK_RETURN || ev.key.key == SDLK_F)) {
553 if (ev.key.repeat == 0) ToggleFullScreen(!_fullscreen);
561 keycode == WKC_DELETE ||
562 keycode == WKC_NUM_ENTER ||
563 keycode == WKC_LEFT ||
564 keycode == WKC_RIGHT ||
566 keycode == WKC_DOWN ||
567 keycode == WKC_HOME ||
568 keycode == WKC_END ||
569 keycode & WKC_META ||
570 keycode & WKC_CTRL ||
572 (keycode >= WKC_F1 && keycode <= WKC_F12) ||
579 case SDL_EVENT_TEXT_INPUT: {
581 SDL_Keycode kc = SDL_GetKeyFromName(ev.text.text);
593 case SDL_EVENT_WINDOW_EXPOSED:
595 this->
MakeDirty(0, 0, _screen.width, _screen.height);
598 case SDL_EVENT_WINDOW_RESIZED:
599 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED: {
600 int w = std::max(ev.window.data1, 64);
601 int h = std::max(ev.window.data2, 64);
606 case SDL_EVENT_WINDOW_MOUSE_ENTER:
608 _cursor.in_window =
true;
610 SDL_SetWindowRelativeMouseMode(this->
sdl_window,
false);
613 case SDL_EVENT_WINDOW_MOUSE_LEAVE:
616 _cursor.in_window =
false;
630 if (SDL_WasInit(SDL_INIT_VIDEO))
return std::nullopt;
632#ifdef SDL_HINT_APP_NAME
633 SDL_SetHint(SDL_HINT_APP_NAME,
"OpenTTD");
636 if (!SDL_InitSubSystem(SDL_INIT_VIDEO))
return SDL_GetError();
649 if (error)
return error;
662 if (error)
return error;
664#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
669 if (!SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE,
"0"))
return SDL_GetError();
676 return SDL_GetError();
679 const char *dname = SDL_GetCurrentVideoDriver();
703 SDL_QuitSubSystem(SDL_INIT_VIDEO);
704 if (!SDL_WasInit(SDL_INIT_AUDIO)) {
711 uint32_t mod = SDL_GetModState();
712 const bool *key_states = SDL_GetKeyboardState(
nullptr);
743 extern void PostMainLoop();
746 emscripten_cancel_main_loop();
747 emscripten_exit_pointerlock();
752 EM_ASM(
if (window[
"openttd_bootstrap_reload"]) openttd_bootstrap_reload());
754 EM_ASM(
if (window[
"openttd_exit"]) openttd_exit());
764#ifndef __EMSCRIPTEN__
773 emscripten_set_main_loop_arg(&this->EmscriptenLoop,
this, 0, 1);
777 while (!_exit_game) {
798 const SDL_DisplayMode *dm = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(this->
sdl_window));
802 SDL_SetWindowSize(this->
sdl_window, dm->w, dm->h);
807 bool success = SDL_SetWindowFullscreen(this->
sdl_window, fullscreen);
810 _fullscreen = fullscreen;
811 if (!fullscreen) SDL_SetWindowSize(this->
sdl_window, w, h);
830 const SDL_DisplayMode *mode = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(this->
sdl_window));
833 return {
static_cast<uint
>(mode->w),
static_cast<uint
>(mode->h) };
842 assert(_screen.dst_ptr !=
nullptr);
849 if (_screen.dst_ptr !=
nullptr) {
852 _screen.dst_ptr =
nullptr;
861 SDL_DisableScreenSaver();
863 SDL_EnableScreenSaver();
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
virtual void PostResize()
Post resize event.
virtual std::string_view GetName() const =0
Get the name of this driver.
Helper to map some SDL functions to behave like a std::range.
~SDLRange()
Free the data.
constexpr T * begin() const
Iterator to the begin of the data.
SDLRange & operator=(const SDLRange &)=delete
Do not assign.
SDLRange(Func func, Args... args)
Create the range.
constexpr T * end() const
Iterator to the end of the data.
int count
The number of elements.
T * data
The base pointer of the array.
SDLRange(SDLRange &)=delete
Do not copy.
constexpr size_t size() const
The number of elements in this range.
std::optional< std::string_view > Start(const StringList ¶m) override
Start this driver.
bool buffer_locked
Video buffer was locked by the main thread.
Dimension GetScreenSize() const override
Get the resolution of the main screen.
bool PollEvent() override
Process a single system event.
void EditBoxLostFocus() override
This is called to indicate that an edit box has lost focus, text input mode should be disabled.
virtual void ReleaseVideoPointer()=0
Hand video buffer back to the painting backend.
void ClaimMousePointer() override
Claim the exclusive rights for the mouse pointer.
virtual void * GetVideoPointer()=0
Get a pointer to the video buffer.
void LoopOnce()
Run a single tick of the game/main loop.
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
virtual bool AllocateBackingStore(int w, int h, bool force=false)=0
(Re-)create the backing store.
void InputLoop() override
Handle input logic, is CTRL pressed, should we fast-forward, etc.
Palette local_palette
Current palette to use for drawing.
void MainLoop() override
Perform the actual drawing.
std::optional< std::string_view > Initialize()
Initialize the driver.
std::string driver_info
Information string about selected driver.
void UnlockVideoBuffer() override
Unlock a previously locked video buffer.
void ClientSizeChanged(int w, int h, bool force)
Indicate to the driver the client-size might have changed.
int startup_display
The display to show OpenTTD on when starting.
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
virtual bool CreateMainWindow(uint w, uint h, uint flags=0)
Create the main window.
std::vector< int > GetListOfMonitorRefreshRates() override
Get a list of refresh rates of each available monitor.
void SetScreensaverInhibited(bool inhibited) override
Prevents the system from going to sleep.
bool edit_box_focused
This is true to indicate that keyboard input is in text input mode, and SDL_TEXTINPUT events are enab...
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
void Stop() override
Stop this driver.
bool CreateMainSurface(uint w, uint h, bool resize)
Create/update the surfaces to draw OpenTTD on.
bool LockVideoBuffer() override
Make sure the video buffer is ready for drawing.
void EditBoxGainedFocus() override
This is called to indicate that an edit box has gained focus, text input mode should be enabled.
Rect dirty_rect
Rectangle encompassing the dirty area of the video buffer.
void CheckPaletteAnim() override
Process any pending palette animation.
struct SDL_Window * sdl_window
Main SDL window.
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
virtual Dimension GetScreenSize() const
Get the resolution of the main screen.
bool fast_forward_key_pressed
The fast-forward key is being pressed.
void Tick()
Give the video-driver a tick.
void SleepTillNextTick()
Sleep till the next tick is about to happen.
void StartGameThread()
Start the loop for game-tick.
static std::string GetCaption()
Get the caption to use for the game's title bar.
void StopGameThread()
Stop the loop for the game-tick.
void UpdateAutoResolution()
Apply resolution auto-detection and clamp to sensible defaults.
bool is_game_threaded
Whether the game is allowed to use threads; cleared in the driver implementation constructors if requ...
static const Dimension _default_resolutions[]
List of common display/window sizes.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
@ Driver
Driver message facility.
@ Warning
Warning, wrong but okay if you don't know.
@ Critical
Critical, user should know about this.
@ Error
Error, but we are recovering.
int GetDriverParamInt(const StringList &parm, std::string_view name, int def)
Get an integer parameter the list of parameters.
bool GetDriverParamBool(const StringList &parm, std::string_view name)
Get a boolean parameter the list of parameters.
std::vector< Dimension > _resolutions
List of resolutions.
Dimension _cur_resolution
The current resolution.
bool _rightclick_emulate
Whether right clicking is emulated.
#define T
Climate temperate.
Factory to 'query' all available blitters.
std::string FioFindFullPath(Subdirectory subdir, std::string_view filename)
Find a path to the filename in one of the search directories.
Functions for standard in/out file operations.
@ Baseset
Subdirectory for all base data (base sets, intro game).
Types for recording game performance data.
Rect BoundingRect(const Rect &r1, const Rect &r2)
Compute the bounding rectangle around two rectangles.
ControlInputs _input_pressed
Control inputs that are currently pressed.
ControlInputs _input_clicked
Control inputs that have been actioned.
DirectionKeys _dirkeys
Pressed direction keys.
Functions related to the gfx engine.
void HandleCtrlChanged()
State of CONTROL key has changed.
void GameSizeChanged()
Size of the application screen changed.
void HandleMouseEvents()
Handle a mouse event from the video driver.
bool IsCtrlPressed()
Test if the ctrl key is pressed.
void HandleKeypress(uint keycode, char32_t key)
Handle keyboard input.
void HandleTextInput(std::string_view str, bool marked=false, std::optional< size_t > caret=std::nullopt, std::optional< size_t > insert_location=std::nullopt, std::optional< size_t > replacement_end=std::nullopt)
Handle text input.
@ Ctrl
Ctrl modifier is pressed.
@ X2
X2 mouse button is pressed.
@ Shift
Shift modifier is pressed.
@ Right
Right mouse button is pressed.
@ Left
Left mouse button is pressed.
@ Middle
Middle mouse button is pressed.
@ X1
X1 mouse button is pressed.
@ WKC_BACKSLASH
\ Backslash
@ WKC_SLASH
/ Forward slash
@ WKC_SINGLEQUOTE
' Single quote
@ WKC_R_BRACKET
] Right square bracket
@ WKC_L_BRACKET
[ Left square bracket
@ WKC_SEMICOLON
; Semicolon
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr T Delta(const T a, const T b)
Returns the (absolute) difference between two (scalar) variables.
@ Bootstrap
In the content bootstrap process.
bool CopyPalette(Palette &local_palette, bool force_copy)
Copy the current palette if the palette was updated.
Functions related to modal progress.
A number of safeguards to prevent using unsafe methods.
static void GetAvailableVideoMode(uint *w, uint *h)
Get the best resolution given the requested width and height.
static uint ConvertSdlKeyIntoMy(SDL_KeyboardEvent *key_event, char32_t *character)
Convert the SDL key into our WindowKeyCode and the printable character (if any).
static void FindResolutions()
Find and store all possible resolutions into _resolutions.
static std::optional< std::string_view > InitializeSDL()
Initialize the SDL backend if needed.
static uint ConvertSdlKeycodeIntoMy(SDL_Keycode kc)
Convert a SDL_Keycode into our own key codes.
static uint FindStartupDisplay(uint startup_display)
Find the display we want to start OpenTTD on.
Base of the SDL3 video driver.
ClientSettings _settings_client
The current settings for this game.
Definition of base types and functions in a cross-platform compatible way.
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
std::vector< std::string > StringList
Type for a list of strings.
Dimensions (a width and height) of a rectangle in 2D.
Specification of a rectangle with absolute coordinates of all edges.
Mapping from keycodes in the SDL world to OpenTTD's world.
const uint8_t count
The number of keycodes that are to be mapped.
const WindowKeyCodes map_to
The first of the OpenTTD keycodes of this mapping.
const bool unprintable
Whether this keycode is unprintable.
constexpr SDLVkMapping(SDL_Keycode vk_from, WindowKeyCodes map_to, bool unprintable)
Create a mapping for a single keycode.
const SDL_Keycode vk_from
The first of the SDL keycodes of this mapping.
constexpr SDLVkMapping(SDL_Keycode vk_first, SDL_Keycode vk_last, WindowKeyCodes map_first, WindowKeyCodes map_last, bool unprintable)
Create a mapping for several consecutive keycodes.
std::pair< size_t, char32_t > DecodeUtf8(std::string_view buf)
Decode a character from UTF-8.
Handling of UTF-8 encoded data.
bool FocusedWindowIsConsole()
Check if a console is focused.
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Window functions not directly related to making/drawing windows.