OpenTTD Source 15.0-beta2
sdl2_v.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#include "../stdafx.h"
11#include "../openttd.h"
12#include "../gfx_func.h"
13#include "../blitter/factory.hpp"
14#include "../thread.h"
15#include "../progress.h"
16#include "../core/random_func.hpp"
17#include "../core/math_func.hpp"
18#include "../core/mem_func.hpp"
19#include "../core/geometry_func.hpp"
20#include "../core/utf8.hpp"
21#include "../fileio_func.h"
22#include "../framerate_type.h"
23#include "../window_func.h"
24#include "sdl2_v.h"
25#include <SDL.h>
26#ifdef __EMSCRIPTEN__
27# include <emscripten.h>
28# include <emscripten/html5.h>
29#endif
30
31#include "../safeguards.h"
32
33void VideoDriver_SDL_Base::MakeDirty(int left, int top, int width, int height)
34{
35 Rect r = {left, top, left + width, top + height};
36 this->dirty_rect = BoundingRect(this->dirty_rect, r);
37}
38
40{
41 if (!CopyPalette(this->local_palette)) return;
42 this->MakeDirty(0, 0, _screen.width, _screen.height);
43}
44
45static const Dimension default_resolutions[] = {
46 { 640, 480 },
47 { 800, 600 },
48 { 1024, 768 },
49 { 1152, 864 },
50 { 1280, 800 },
51 { 1280, 960 },
52 { 1280, 1024 },
53 { 1400, 1050 },
54 { 1600, 1200 },
55 { 1680, 1050 },
56 { 1920, 1200 }
57};
58
59static void FindResolutions()
60{
61 _resolutions.clear();
62
63 for (int display = 0; display < SDL_GetNumVideoDisplays(); display++) {
64 for (int i = 0; i < SDL_GetNumDisplayModes(display); i++) {
65 SDL_DisplayMode mode;
66 SDL_GetDisplayMode(display, i, &mode);
67
68 if (mode.w < 640 || mode.h < 480) continue;
69 if (std::ranges::find(_resolutions, Dimension(mode.w, mode.h)) != _resolutions.end()) continue;
70 _resolutions.emplace_back(mode.w, mode.h);
71 }
72 }
73
74 /* We have found no resolutions, show the default list */
75 if (_resolutions.empty()) {
76 _resolutions.assign(std::begin(default_resolutions), std::end(default_resolutions));
77 }
78
79 SortResolutions();
80}
81
82static void GetAvailableVideoMode(uint *w, uint *h)
83{
84 /* All modes available? */
85 if (!_fullscreen || _resolutions.empty()) return;
86
87 /* Is the wanted mode among the available modes? */
88 if (std::ranges::find(_resolutions, Dimension(*w, *h)) != _resolutions.end()) return;
89
90 /* Use the closest possible resolution */
91 uint best = 0;
92 uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
93 for (uint i = 1; i != _resolutions.size(); ++i) {
94 uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
95 if (newdelta < delta) {
96 best = i;
97 delta = newdelta;
98 }
99 }
100 *w = _resolutions[best].width;
101 *h = _resolutions[best].height;
102}
103
104static uint FindStartupDisplay(uint startup_display)
105{
106 int num_displays = SDL_GetNumVideoDisplays();
107
108 /* If the user indicated a valid monitor, use that. */
109 if (IsInsideBS(startup_display, 0, num_displays)) return startup_display;
110
111 /* Mouse position decides which display to use. */
112 int mx, my;
113 SDL_GetGlobalMouseState(&mx, &my);
114 for (int display = 0; display < num_displays; ++display) {
115 SDL_Rect r;
116 if (SDL_GetDisplayBounds(display, &r) == 0 && IsInsideBS(mx, r.x, r.w) && IsInsideBS(my, r.y, r.h)) {
117 Debug(driver, 1, "SDL2: Mouse is at ({}, {}), use display {} ({}, {}, {}, {})", mx, my, display, r.x, r.y, r.w, r.h);
118 return display;
119 }
120 }
121
122 return 0;
123}
124
125void VideoDriver_SDL_Base::ClientSizeChanged(int w, int h, bool force)
126{
127 /* Allocate backing store of the new size. */
128 if (this->AllocateBackingStore(w, h, force)) {
129 CopyPalette(this->local_palette, true);
130
132
134 }
135}
136
137bool VideoDriver_SDL_Base::CreateMainWindow(uint w, uint h, uint flags)
138{
139 if (this->sdl_window != nullptr) return true;
140
141 flags |= SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE;
142
143 if (_fullscreen) {
144 flags |= SDL_WINDOW_FULLSCREEN;
145 }
146
147 int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED;
148 SDL_Rect r;
149 if (SDL_GetDisplayBounds(this->startup_display, &r) == 0) {
150 x = r.x + std::max(0, r.w - static_cast<int>(w)) / 2;
151 y = r.y + std::max(0, r.h - static_cast<int>(h)) / 4; // decent desktops have taskbars at the bottom
152 }
153
154 std::string caption = VideoDriver::GetCaption();
155 this->sdl_window = SDL_CreateWindow(
156 caption.c_str(),
157 x, y,
158 w, h,
159 flags);
160
161 if (this->sdl_window == nullptr) {
162 Debug(driver, 0, "SDL2: Couldn't allocate a window to draw on: {}", SDL_GetError());
163 return false;
164 }
165
166 std::string icon_path = FioFindFullPath(BASESET_DIR, "openttd.32.bmp");
167 if (!icon_path.empty()) {
168 /* Give the application an icon */
169 SDL_Surface *icon = SDL_LoadBMP(icon_path.c_str());
170 if (icon != nullptr) {
171 /* Get the colourkey, which will be magenta */
172 uint32_t rgbmap = SDL_MapRGB(icon->format, 255, 0, 255);
173
174 SDL_SetColorKey(icon, SDL_TRUE, rgbmap);
175 SDL_SetWindowIcon(this->sdl_window, icon);
176 SDL_FreeSurface(icon);
177 }
178 }
179
180 return true;
181}
182
183bool VideoDriver_SDL_Base::CreateMainSurface(uint w, uint h, bool resize)
184{
185 GetAvailableVideoMode(&w, &h);
186 Debug(driver, 1, "SDL2: using mode {}x{}", w, h);
187
188 if (!this->CreateMainWindow(w, h)) return false;
189 if (resize) SDL_SetWindowSize(this->sdl_window, w, h);
190 this->ClientSizeChanged(w, h, true);
191
192 /* When in full screen, we will always have the mouse cursor
193 * within the window, even though SDL does not give us the
194 * appropriate event to know this. */
195 if (_fullscreen) _cursor.in_window = true;
196
197 return true;
198}
199
200bool VideoDriver_SDL_Base::ClaimMousePointer()
201{
202 /* Emscripten never claims the pointer, so we do not need to change the cursor visibility. */
203#ifndef __EMSCRIPTEN__
204 SDL_ShowCursor(0);
205#endif
206 return true;
207}
208
213{
214 if (!this->edit_box_focused) {
215 SDL_StartTextInput();
216 this->edit_box_focused = true;
217 }
218}
219
224{
225 if (this->edit_box_focused) {
226 SDL_StopTextInput();
227 this->edit_box_focused = false;
228 }
229}
230
232{
233 std::vector<int> rates = {};
234 for (int i = 0; i < SDL_GetNumVideoDisplays(); i++) {
235 SDL_DisplayMode mode = {};
236 if (SDL_GetDisplayMode(i, 0, &mode) != 0) continue;
237 if (mode.refresh_rate != 0) rates.push_back(mode.refresh_rate);
238 }
239 return rates;
240}
241
242
244 const SDL_Keycode vk_from;
245 const uint8_t vk_count;
246 const uint8_t map_to;
247 const bool unprintable;
248
249 constexpr SDLVkMapping(SDL_Keycode vk_first, SDL_Keycode vk_last, uint8_t map_first, [[maybe_unused]] uint8_t map_last, bool unprintable)
250 : vk_from(vk_first), vk_count(vk_last - vk_first + 1), map_to(map_first), unprintable(unprintable)
251 {
252 assert((vk_last - vk_first) == (map_last - map_first));
253 }
254};
255
256#define AS(x, z) {x, x, z, z, false}
257#define AM(x, y, z, w) {x, y, z, w, false}
258#define AS_UP(x, z) {x, x, z, z, true}
259#define AM_UP(x, y, z, w) {x, y, z, w, true}
260
261static constexpr SDLVkMapping _vk_mapping[] = {
262 /* Pageup stuff + up/down */
263 AS_UP(SDLK_PAGEUP, WKC_PAGEUP),
264 AS_UP(SDLK_PAGEDOWN, WKC_PAGEDOWN),
265 AS_UP(SDLK_UP, WKC_UP),
266 AS_UP(SDLK_DOWN, WKC_DOWN),
267 AS_UP(SDLK_LEFT, WKC_LEFT),
268 AS_UP(SDLK_RIGHT, WKC_RIGHT),
269
270 AS_UP(SDLK_HOME, WKC_HOME),
271 AS_UP(SDLK_END, WKC_END),
272
273 AS_UP(SDLK_INSERT, WKC_INSERT),
274 AS_UP(SDLK_DELETE, WKC_DELETE),
275
276 /* Map letters & digits */
277 AM(SDLK_a, SDLK_z, 'A', 'Z'),
278 AM(SDLK_0, SDLK_9, '0', '9'),
279
280 AS_UP(SDLK_ESCAPE, WKC_ESC),
281 AS_UP(SDLK_PAUSE, WKC_PAUSE),
282 AS_UP(SDLK_BACKSPACE, WKC_BACKSPACE),
283
284 AS(SDLK_SPACE, WKC_SPACE),
285 AS(SDLK_RETURN, WKC_RETURN),
286 AS(SDLK_TAB, WKC_TAB),
287
288 /* Function keys */
289 AM_UP(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
290
291 /* Numeric part. */
292 AS(SDLK_KP_1, '1'),
293 AS(SDLK_KP_2, '2'),
294 AS(SDLK_KP_3, '3'),
295 AS(SDLK_KP_4, '4'),
296 AS(SDLK_KP_5, '5'),
297 AS(SDLK_KP_6, '6'),
298 AS(SDLK_KP_7, '7'),
299 AS(SDLK_KP_8, '8'),
300 AS(SDLK_KP_9, '9'),
301 AS(SDLK_KP_0, '0'),
302 AS(SDLK_KP_DIVIDE, WKC_NUM_DIV),
303 AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
304 AS(SDLK_KP_MINUS, WKC_NUM_MINUS),
305 AS(SDLK_KP_PLUS, WKC_NUM_PLUS),
306 AS(SDLK_KP_ENTER, WKC_NUM_ENTER),
307 AS(SDLK_KP_PERIOD, WKC_NUM_DECIMAL),
308
309 /* Other non-letter keys */
310 AS(SDLK_SLASH, WKC_SLASH),
311 AS(SDLK_SEMICOLON, WKC_SEMICOLON),
312 AS(SDLK_EQUALS, WKC_EQUALS),
313 AS(SDLK_LEFTBRACKET, WKC_L_BRACKET),
314 AS(SDLK_BACKSLASH, WKC_BACKSLASH),
315 AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
316
317 AS(SDLK_QUOTE, WKC_SINGLEQUOTE),
318 AS(SDLK_COMMA, WKC_COMMA),
319 AS(SDLK_MINUS, WKC_MINUS),
320 AS(SDLK_PERIOD, WKC_PERIOD)
321};
322
323static uint ConvertSdlKeyIntoMy(SDL_Keysym *sym, char32_t *character)
324{
325 uint key = 0;
326 bool unprintable = false;
327
328 for (const auto &map : _vk_mapping) {
329 if (IsInsideBS(sym->sym, map.vk_from, map.vk_count)) {
330 key = sym->sym - map.vk_from + map.map_to;
331 unprintable = map.unprintable;
332 break;
333 }
334 }
335
336 /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
337 if (sym->scancode == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
338
339 /* META are the command keys on mac */
340 if (sym->mod & KMOD_GUI) key |= WKC_META;
341 if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
342 if (sym->mod & KMOD_CTRL) key |= WKC_CTRL;
343 if (sym->mod & KMOD_ALT) key |= WKC_ALT;
344
345 /* The mod keys have no character. Prevent '?' */
346 if (sym->mod & KMOD_GUI ||
347 sym->mod & KMOD_CTRL ||
348 sym->mod & KMOD_ALT ||
349 unprintable) {
350 *character = WKC_NONE;
351 } else {
352 *character = sym->sym;
353 }
354
355 return key;
356}
357
362static uint ConvertSdlKeycodeIntoMy(SDL_Keycode kc)
363{
364 uint key = 0;
365
366 for (const auto &map : _vk_mapping) {
367 if (IsInsideBS(kc, map.vk_from, map.vk_count)) {
368 key = kc - map.vk_from + map.map_to;
369 break;
370 }
371 }
372
373 /* check scancode for BACKQUOTE key, because we want the key left
374 * of "1", not anything else (on non-US keyboards) */
375 SDL_Scancode sc = SDL_GetScancodeFromKey(kc);
376 if (sc == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
377
378 return key;
379}
380
382{
383 SDL_Event ev;
384
385 if (!SDL_PollEvent(&ev)) return false;
386
387 switch (ev.type) {
388 case SDL_MOUSEMOTION: {
389 int32_t x = ev.motion.x;
390 int32_t y = ev.motion.y;
391
392 if (_cursor.fix_at) {
393 /* Get all queued mouse events now in case we have to warp the cursor. In the
394 * end, we only care about the current mouse position and not bygone events. */
395 while (SDL_PeepEvents(&ev, 1, SDL_GETEVENT, SDL_MOUSEMOTION, SDL_MOUSEMOTION)) {
396 x = ev.motion.x;
397 y = ev.motion.y;
398 }
399 }
400
401 if (_cursor.UpdateCursorPosition(x, y)) {
402 SDL_WarpMouseInWindow(this->sdl_window, _cursor.pos.x, _cursor.pos.y);
403 }
405 break;
406 }
407
408 case SDL_MOUSEWHEEL: {
409 if (ev.wheel.y > 0) {
410 _cursor.wheel--;
411 } else if (ev.wheel.y < 0) {
412 _cursor.wheel++;
413 }
414
415 /* Handle 2D scrolling. */
416 const float SCROLL_BUILTIN_MULTIPLIER = 14.0f;
417#if SDL_VERSION_ATLEAST(2, 18, 0)
418 _cursor.v_wheel -= ev.wheel.preciseY * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
419 _cursor.h_wheel += ev.wheel.preciseX * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
420#else
421 _cursor.v_wheel -= static_cast<float>(ev.wheel.y * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier);
422 _cursor.h_wheel += static_cast<float>(ev.wheel.x * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier);
423#endif
424 _cursor.wheel_moved = true;
425 break;
426 }
427
428 case SDL_MOUSEBUTTONDOWN:
429 if (_rightclick_emulate && SDL_GetModState() & KMOD_CTRL) {
430 ev.button.button = SDL_BUTTON_RIGHT;
431 }
432
433 switch (ev.button.button) {
434 case SDL_BUTTON_LEFT:
435 _left_button_down = true;
436 break;
437
438 case SDL_BUTTON_RIGHT:
439 _right_button_down = true;
441 break;
442
443 default: break;
444 }
446 break;
447
448 case SDL_MOUSEBUTTONUP:
450 _right_button_down = false;
451 _left_button_down = false;
452 _left_button_clicked = false;
453 } else if (ev.button.button == SDL_BUTTON_LEFT) {
454 _left_button_down = false;
455 _left_button_clicked = false;
456 } else if (ev.button.button == SDL_BUTTON_RIGHT) {
457 _right_button_down = false;
458 }
460 break;
461
462 case SDL_QUIT:
463 HandleExitGameRequest();
464 break;
465
466 case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
467 if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_GUI)) &&
468 (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
469 if (ev.key.repeat == 0) ToggleFullScreen(!_fullscreen);
470 } else {
471 char32_t character;
472
473 uint keycode = ConvertSdlKeyIntoMy(&ev.key.keysym, &character);
474 // Only handle non-text keys here. Text is handled in
475 // SDL_TEXTINPUT below.
476 if (!this->edit_box_focused ||
477 keycode == WKC_DELETE ||
478 keycode == WKC_NUM_ENTER ||
479 keycode == WKC_LEFT ||
480 keycode == WKC_RIGHT ||
481 keycode == WKC_UP ||
482 keycode == WKC_DOWN ||
483 keycode == WKC_HOME ||
484 keycode == WKC_END ||
485 keycode & WKC_META ||
486 keycode & WKC_CTRL ||
487 keycode & WKC_ALT ||
488 (keycode >= WKC_F1 && keycode <= WKC_F12) ||
489 !IsValidChar(character, CS_ALPHANUMERAL)) {
490 HandleKeypress(keycode, character);
491 }
492 }
493 break;
494
495 case SDL_TEXTINPUT: {
496 if (!this->edit_box_focused) break;
497 SDL_Keycode kc = SDL_GetKeyFromName(ev.text.text);
498 uint keycode = ConvertSdlKeycodeIntoMy(kc);
499
500 if (keycode == WKC_BACKQUOTE && FocusedWindowIsConsole()) {
501 auto [len, c] = DecodeUtf8(ev.text.text);
502 if (len > 0) HandleKeypress(keycode, c);
503 } else {
504 HandleTextInput(ev.text.text);
505 }
506 break;
507 }
508 case SDL_WINDOWEVENT: {
509 if (ev.window.event == SDL_WINDOWEVENT_EXPOSED) {
510 // Force a redraw of the entire screen.
511 this->MakeDirty(0, 0, _screen.width, _screen.height);
512 } else if (ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
513 int w = std::max(ev.window.data1, 64);
514 int h = std::max(ev.window.data2, 64);
515 CreateMainSurface(w, h, w != ev.window.data1 || h != ev.window.data2);
516 } else if (ev.window.event == SDL_WINDOWEVENT_ENTER) {
517 // mouse entered the window, enable cursor
518 _cursor.in_window = true;
519 /* Ensure pointer lock will not occur. */
520 SDL_SetRelativeMouseMode(SDL_FALSE);
521 } else if (ev.window.event == SDL_WINDOWEVENT_LEAVE) {
522 // mouse left the window, undraw cursor
523 UndrawMouseCursor();
524 _cursor.in_window = false;
525 }
526 break;
527 }
528 }
529
530 return true;
531}
532
533static std::optional<std::string_view> InitializeSDL()
534{
535 /* Check if the video-driver is already initialized. */
536 if (SDL_WasInit(SDL_INIT_VIDEO) != 0) return std::nullopt;
537
538#ifdef SDL_HINT_APP_NAME
539 SDL_SetHint(SDL_HINT_APP_NAME, "OpenTTD");
540#endif
541
542 if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) return SDL_GetError();
543 return std::nullopt;
544}
545
546std::optional<std::string_view> VideoDriver_SDL_Base::Initialize()
547{
548 this->UpdateAutoResolution();
549
550 auto error = InitializeSDL();
551 if (error) return error;
552
553 FindResolutions();
554 Debug(driver, 2, "Resolution for display: {}x{}", _cur_resolution.width, _cur_resolution.height);
555
556 return std::nullopt;
557}
558
559std::optional<std::string_view> VideoDriver_SDL_Base::Start(const StringList &param)
560{
561 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
562
563 auto error = this->Initialize();
564 if (error) return error;
565
566#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
567 if (GetDriverParamBool(param, "no_mouse_capture")) {
568 /* By default SDL captures the mouse, while a button is pressed.
569 * This is annoying during debugging, when OpenTTD is suspended while the button was pressed.
570 */
571 if (!SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0")) return SDL_GetError();
572 }
573#endif
574
575 this->startup_display = FindStartupDisplay(GetDriverParamInt(param, "display", -1));
576
577 if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height, false)) {
578 return SDL_GetError();
579 }
580
581 const char *dname = SDL_GetCurrentVideoDriver();
582 Debug(driver, 1, "SDL2: using driver '{}'", dname);
583
584 this->driver_info = this->GetName();
585 this->driver_info += " (";
586 this->driver_info += dname;
587 this->driver_info += ")";
588
590
591 SDL_StopTextInput();
592 this->edit_box_focused = false;
593
594#ifdef __EMSCRIPTEN__
595 this->is_game_threaded = false;
596#else
597 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
598#endif
599
600 return std::nullopt;
601}
602
604{
605 SDL_QuitSubSystem(SDL_INIT_VIDEO);
606 if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
607 SDL_Quit(); // If there's nothing left, quit SDL
608 }
609}
610
612{
613 uint32_t mod = SDL_GetModState();
614 const Uint8 *keys = SDL_GetKeyboardState(nullptr);
615
616 bool old_ctrl_pressed = _ctrl_pressed;
617
618 _ctrl_pressed = !!(mod & KMOD_CTRL);
619 _shift_pressed = !!(mod & KMOD_SHIFT);
620
621 /* Speedup when pressing tab, except when using ALT+TAB
622 * to switch to another application. */
623 this->fast_forward_key_pressed = keys[SDL_SCANCODE_TAB] && (mod & KMOD_ALT) == 0;
624
625 /* Determine which directional keys are down. */
626 _dirkeys =
627 (keys[SDL_SCANCODE_LEFT] ? 1 : 0) |
628 (keys[SDL_SCANCODE_UP] ? 2 : 0) |
629 (keys[SDL_SCANCODE_RIGHT] ? 4 : 0) |
630 (keys[SDL_SCANCODE_DOWN] ? 8 : 0);
631
632 if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
633}
634
635void VideoDriver_SDL_Base::LoopOnce()
636{
637 if (_exit_game) {
638#ifdef __EMSCRIPTEN__
639 /* Emscripten is event-driven, and as such the main loop is inside
640 * the browser. So if _exit_game goes true, the main loop ends (the
641 * cancel call), but we still have to call the cleanup that is
642 * normally done at the end of the main loop for non-Emscripten.
643 * After that, Emscripten just halts, and the HTML shows a nice
644 * "bye, see you next time" message. */
645 extern void PostMainLoop();
646 PostMainLoop();
647
648 emscripten_cancel_main_loop();
649 emscripten_exit_pointerlock();
650 /* In effect, the game ends here. As emscripten_set_main_loop() caused
651 * the stack to be unwound, the code after MainLoop() in
652 * openttd_main() is never executed. */
653 if (_game_mode == GM_BOOTSTRAP) {
654 EM_ASM(if (window["openttd_bootstrap_reload"]) openttd_bootstrap_reload());
655 } else {
656 EM_ASM(if (window["openttd_exit"]) openttd_exit());
657 }
658#endif
659 return;
660 }
661
662 this->Tick();
663
664/* Emscripten is running an event-based mainloop; there is already some
665 * downtime between each iteration, so no need to sleep. */
666#ifndef __EMSCRIPTEN__
667 this->SleepTillNextTick();
668#endif
669}
670
672{
673#ifdef __EMSCRIPTEN__
674 /* Run the main loop event-driven, based on RequestAnimationFrame. */
675 emscripten_set_main_loop_arg(&this->EmscriptenLoop, this, 0, 1);
676#else
677 this->StartGameThread();
678
679 while (!_exit_game) {
680 LoopOnce();
681 }
682
683 this->StopGameThread();
684#endif
685}
686
688{
689 return CreateMainSurface(w, h, true);
690}
691
693{
694 /* Remember current window size */
695 int w, h;
696 SDL_GetWindowSize(this->sdl_window, &w, &h);
697
698 if (fullscreen) {
699 /* Find fullscreen window size */
700 SDL_DisplayMode dm;
701 if (SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(this->sdl_window), &dm) < 0) {
702 Debug(driver, 0, "SDL_GetCurrentDisplayMode() failed: {}", SDL_GetError());
703 } else {
704 SDL_SetWindowSize(this->sdl_window, dm.w, dm.h);
705 }
706 }
707
708 Debug(driver, 1, "SDL2: Setting {}", fullscreen ? "fullscreen" : "windowed");
709 int ret = SDL_SetWindowFullscreen(this->sdl_window, fullscreen ? SDL_WINDOW_FULLSCREEN : 0);
710 if (ret == 0) {
711 /* Switching resolution succeeded, set fullscreen value of window. */
712 _fullscreen = fullscreen;
713 if (!fullscreen) SDL_SetWindowSize(this->sdl_window, w, h);
714 } else {
715 Debug(driver, 0, "SDL_SetWindowFullscreen() failed: {}", SDL_GetError());
716 }
717
719 return ret == 0;
720}
721
723{
724 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
725 int w, h;
726 SDL_GetWindowSize(this->sdl_window, &w, &h);
727 return CreateMainSurface(w, h, false);
728}
729
731{
732 SDL_DisplayMode mode;
733 if (SDL_GetCurrentDisplayMode(this->startup_display, &mode) != 0) return VideoDriver::GetScreenSize();
734
735 return { static_cast<uint>(mode.w), static_cast<uint>(mode.h) };
736}
737
739{
740 if (this->buffer_locked) return false;
741 this->buffer_locked = true;
742
743 _screen.dst_ptr = this->GetVideoPointer();
744 assert(_screen.dst_ptr != nullptr);
745
746 return true;
747}
748
750{
751 if (_screen.dst_ptr != nullptr) {
752 /* Hand video buffer back to the drawing backend. */
753 this->ReleaseVideoPointer();
754 _screen.dst_ptr = nullptr;
755 }
756
757 this->buffer_locked = false;
758}
#define AS(ap_name, size_x, size_y, min_year, max_year, catchment, noise, maint_cost, ttdpatch_type, class_id, name, preview)
AirportSpec definition for airports with at least one depot.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:136
virtual void PostResize()
Post resize event.
Definition base.hpp:205
virtual std::string_view GetName() const =0
Get the name of this driver.
std::optional< std::string_view > Start(const StringList &param) override
Start this driver.
Definition sdl2_v.cpp:559
bool buffer_locked
Video buffer was locked by the main thread.
Definition sdl2_v.h:49
Dimension GetScreenSize() const override
Get the resolution of the main screen.
Definition sdl2_v.cpp:730
bool PollEvent() override
Process a single system event.
Definition sdl2_v.cpp:381
void EditBoxLostFocus() override
This is called to indicate that an edit box has lost focus, text input mode should be disabled.
Definition sdl2_v.cpp:223
virtual void ReleaseVideoPointer()=0
Hand video buffer back to the painting backend.
virtual void * GetVideoPointer()=0
Get a pointer to the video buffer.
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
Definition sdl2_v.cpp:722
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.
Definition sdl2_v.cpp:611
Palette local_palette
Current palette to use for drawing.
Definition sdl2_v.h:48
void MainLoop() override
Perform the actual drawing.
Definition sdl2_v.cpp:671
std::string driver_info
Information string about selected driver.
Definition sdl2_v.h:51
void UnlockVideoBuffer() override
Unlock a previously locked video buffer.
Definition sdl2_v.cpp:749
void ClientSizeChanged(int w, int h, bool force)
Indicate to the driver the client-side might have changed.
Definition sdl2_v.cpp:125
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
Definition sdl2_v.cpp:33
virtual bool CreateMainWindow(uint w, uint h, uint flags=0)
Create the main window.
Definition sdl2_v.cpp:137
std::vector< int > GetListOfMonitorRefreshRates() override
Get a list of refresh rates of each available monitor.
Definition sdl2_v.cpp:231
bool edit_box_focused
This is true to indicate that keyboard input is in text input mode, and SDL_TEXTINPUT events are enab...
Definition sdl2_v.h:86
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition sdl2_v.cpp:687
void Stop() override
Stop this driver.
Definition sdl2_v.cpp:603
bool LockVideoBuffer() override
Make sure the video buffer is ready for drawing.
Definition sdl2_v.cpp:738
void EditBoxGainedFocus() override
This is called to indicate that an edit box has gained focus, text input mode should be enabled.
Definition sdl2_v.cpp:212
Rect dirty_rect
Rectangle encompassing the dirty area of the video buffer.
Definition sdl2_v.h:50
void CheckPaletteAnim() override
Process any pending palette animation.
Definition sdl2_v.cpp:39
struct SDL_Window * sdl_window
Main SDL window.
Definition sdl2_v.h:47
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition sdl2_v.cpp:692
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.
std::pair< size_t, char32_t > DecodeUtf8(std::string_view buf)
Decode a character from UTF-8.
Definition utf8.cpp:48
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
int GetDriverParamInt(const StringList &parm, const char *name, int def)
Get an integer parameter the list of parameters.
Definition driver.cpp:77
std::vector< Dimension > _resolutions
List of resolutions.
Definition driver.cpp:26
Dimension _cur_resolution
The current resolution.
Definition driver.cpp:27
bool _rightclick_emulate
Whether right clicking is emulated.
Definition driver.cpp:28
bool GetDriverParamBool(const StringList &parm, const char *name)
Get a boolean parameter the list of parameters.
Definition driver.cpp:65
std::string FioFindFullPath(Subdirectory subdir, const std::string &filename)
Find a path to the filename in one of the search directories.
Definition fileio.cpp:144
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
Rect BoundingRect(const Rect &r1, const Rect &r2)
Compute the bounding rectangle around two rectangles.
bool _shift_pressed
Is Shift pressed?
Definition gfx.cpp:39
bool _left_button_down
Is left mouse button pressed?
Definition gfx.cpp:41
bool _ctrl_pressed
Is Ctrl pressed?
Definition gfx.cpp:38
uint8_t _dirkeys
1 = left, 2 = up, 4 = right, 8 = down
Definition gfx.cpp:34
bool _left_button_clicked
Is left mouse button clicked?
Definition gfx.cpp:42
bool _right_button_clicked
Is right mouse button clicked?
Definition gfx.cpp:44
bool _right_button_down
Is right mouse button pressed?
Definition gfx.cpp:43
void HandleCtrlChanged()
State of CONTROL key has changed.
Definition window.cpp:2629
void GameSizeChanged()
Size of the application screen changed.
Definition main_gui.cpp:592
void HandleMouseEvents()
Handle a mouse event from the video driver.
Definition window.cpp:2890
void HandleKeypress(uint keycode, char32_t key)
Handle keyboard input.
Definition window.cpp:2573
void HandleTextInput(const char *str, bool marked=false, const char *caret=nullptr, const char *insert_location=nullptr, const char *replacement_end=nullptr)
Handle text input.
Definition window.cpp:2659
@ WKC_BACKSLASH
\ Backslash
Definition gfx_type.h:101
@ WKC_MINUS
Definition gfx_type.h:106
@ WKC_COMMA
, Comma
Definition gfx_type.h:104
@ WKC_PERIOD
. Period
Definition gfx_type.h:105
@ WKC_EQUALS
= Equals
Definition gfx_type.h:99
@ WKC_SLASH
/ Forward slash
Definition gfx_type.h:97
@ WKC_SINGLEQUOTE
' Single quote
Definition gfx_type.h:103
@ WKC_R_BRACKET
] Right square bracket
Definition gfx_type.h:102
@ WKC_L_BRACKET
[ Left square bracket
Definition gfx_type.h:100
@ WKC_SEMICOLON
; Semicolon
Definition gfx_type.h:98
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1500
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.
bool CopyPalette(Palette &local_palette, bool force_copy)
Copy the current palette if the palette was updated.
Definition palette.cpp:225
static uint ConvertSdlKeycodeIntoMy(SDL_Keycode kc)
Like ConvertSdlKeyIntoMy(), but takes an SDL_Keycode as input instead of an SDL_Keysym.
Definition sdl2_v.cpp:362
Base of the SDL2 video driver.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:58
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
Definition string.cpp:418
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
std::vector< std::string > StringList
Type for a list of strings.
Definition string_type.h:60
GUISettings gui
settings related to the GUI
bool UpdateCursorPosition(int x, int y)
Update cursor position on mouse movement.
Definition gfx.cpp:1699
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
Definition gfx_type.h:129
Point pos
logical mouse position
Definition gfx_type.h:126
bool in_window
mouse inside this window, determines drawing logic
Definition gfx_type.h:148
int wheel
mouse wheel movement
Definition gfx_type.h:128
Dimensions (a width and height) of a rectangle in 2D.
uint8_t scrollwheel_multiplier
how much 'wheel' per incoming event from the OS?
Specification of a rectangle with absolute coordinates of all edges.
bool FocusedWindowIsConsole()
Check if a console is focused.
Definition window.cpp:461
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...
Definition window.cpp:3241
@ WC_GAME_OPTIONS
Game options window; Window numbers: