OpenTTD Source 20261112-master-gbcbec5e63f
video_driver.hpp
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#ifndef VIDEO_VIDEO_DRIVER_HPP
11#define VIDEO_VIDEO_DRIVER_HPP
12
13#include "../debug.h"
14#include "../driver.h"
16#include "../core/math_func.hpp"
17#include "../gfx_func.h"
18#include "../settings_type.h"
19#include <chrono>
20#include <mutex>
21#include <thread>
22
23extern std::string _ini_videodriver;
24extern std::vector<Dimension> _resolutions;
26extern bool _rightclick_emulate;
27extern bool _video_hw_accel;
28extern bool _video_vsync;
29
31class VideoDriver : public Driver {
32 const uint DEFAULT_WINDOW_WIDTH = 640u;
33 const uint DEFAULT_WINDOW_HEIGHT = 480u;
34
35public:
43
51 virtual void MakeDirty(int left, int top, int width, int height) = 0;
52
56 virtual void MainLoop() = 0;
57
64 virtual bool ChangeResolution(int w, int h) = 0;
65
71 virtual bool ToggleFullscreen(bool fullscreen) = 0;
72
77 virtual void ToggleVsync([[maybe_unused]] bool vsync) {}
78
83 virtual bool AfterBlitterChange()
84 {
85 return true;
86 }
87
91 virtual void ClaimMousePointer() {}
92
97 virtual bool UseSystemCursor()
98 {
99 return false;
100 }
101
105 virtual void PopulateSystemSprites() {}
106
110 virtual void ClearSystemSprites() {}
111
120 virtual bool HasGUI() const
121 {
122 return true;
123 }
124
129 virtual bool HasEfficient8Bpp() const
130 {
131 return false;
132 }
133
138 constexpr bool SupportsAnimationBuffer() const
139 {
140 return this->supports_animation_buffer;
141 }
142
147 constexpr uint8_t *GetAnimBuffer() const
148 {
149 return this->anim_buffer;
150 }
151
156 constexpr int GetAnimBufferPitch() const
157 {
158 return anim_pitch;
159 }
160
164 virtual void EditBoxLostFocus() {}
165
169 virtual void EditBoxGainedFocus() {}
170
175 virtual std::vector<int> GetListOfMonitorRefreshRates()
176 {
177 return {};
178 }
179
184 virtual std::string_view GetInfoString() const
185 {
186 return this->GetName();
187 }
188
195 void QueueOnMainThread(std::function<void()> &&func)
196 {
197 std::lock_guard<std::mutex> lock(this->cmd_queue_mutex);
198
199 this->cmd_queue.emplace_back(std::forward<std::function<void()>>(func));
200 }
201
202 void GameLoopPause();
203
209 virtual void SetScreensaverInhibited([[maybe_unused]] bool inhibited) {}
210
216 {
218 }
219
220 static std::string GetCaption();
221
232
238
239 private:
240 bool unlock;
241 };
242
243protected:
244 const uint ALLOWED_DRIFT = 5;
245
251
256 {
257 if (_cur_resolution.width == 0 || _cur_resolution.height == 0) {
258 /* Auto-detect a good resolution. We aim for 75% of the screen size.
259 * Limit width times height times bytes per pixel to fit a 32 bit
260 * integer, This way all internal drawing routines work correctly. */
261 Dimension res = this->GetScreenSize();
262 _cur_resolution.width = ClampU(res.width * 3 / 4, DEFAULT_WINDOW_WIDTH, UINT16_MAX / 2);
263 _cur_resolution.height = ClampU(res.height * 3 / 4, DEFAULT_WINDOW_HEIGHT, UINT16_MAX / 2);
264 }
265 }
266
270 virtual void InputLoop() {}
271
276 virtual bool LockVideoBuffer()
277 {
278 return false;
279 }
280
284 virtual void UnlockVideoBuffer() {}
285
289 virtual void Paint() {}
290
294 virtual void CheckPaletteAnim() {}
295
300 virtual bool PollEvent() { return false; };
301
305 void StartGameThread();
306
310 void StopGameThread();
311
317 void Tick();
318
322 void SleepTillNextTick();
323
324 std::chrono::steady_clock::duration GetGameInterval()
325 {
326#ifdef DEBUG_DUMP_COMMANDS
327 /* When replaying, run as fast as we can. */
328 extern bool _ddc_fastforward;
329 if (_ddc_fastforward) return std::chrono::microseconds(0);
330#endif /* DEBUG_DUMP_COMMANDS */
331
332 TicToc::Tick("GameTick");
333
334 /* If we are paused, run on normal speed. */
335 if (_pause_mode.Any()) return std::chrono::milliseconds(MILLISECONDS_PER_TICK);
336 /* Infinite speed, as quickly as you can. */
337 if (_game_speed == 0) return std::chrono::microseconds(0);
338
339 return std::chrono::microseconds(MILLISECONDS_PER_TICK * 1000 * 100 / _game_speed);
340 }
341
342 std::chrono::steady_clock::duration GetDrawInterval()
343 {
344 TicToc::Tick("DrawTick");
345
346 /* If vsync, draw interval is decided by the display driver */
347 if (_video_vsync && this->uses_hardware_acceleration) return std::chrono::microseconds(0);
348 return std::chrono::microseconds(1000000 / _settings_client.gui.refresh_rate);
349 }
350
353 {
354 std::vector<std::function<void()>> cmds{};
355
356 {
357 /* Exchange queue with an empty one to limit the time we
358 * hold the mutex. This also ensures that queued functions can
359 * add new functions to the queue without everything blocking. */
360 std::lock_guard<std::mutex> lock(this->cmd_queue_mutex);
361 cmds.swap(this->cmd_queue);
362 }
363
364 for (auto &f : cmds) {
365 f();
366 }
367 }
368
369 std::chrono::steady_clock::time_point next_game_tick;
370 std::chrono::steady_clock::time_point next_draw_tick;
371
372 std::thread game_thread;
373 std::mutex game_state_mutex;
374 std::mutex game_thread_wait_mutex;
375
376 uint8_t *anim_buffer = nullptr;
377 int anim_pitch = 0;
378
382 bool fast_forward_via_key = false;
383 bool is_game_threaded = true;
384
385 static void GameThreadThunk(VideoDriver *drv);
386
387private:
388 std::mutex cmd_queue_mutex;
389 std::vector<std::function<void()>> cmd_queue;
390
391 void GameLoop();
392 void GameThread();
393};
394
395#endif /* VIDEO_VIDEO_DRIVER_HPP */
static std::unique_ptr< Driver > & GetActiveDriver(Driver::Type type)
Get the active driver for the given type.
Definition driver.h:83
A driver for communicating with the user.
Definition driver.h:21
virtual std::string_view GetName() const =0
Get the name of this driver.
@ Video
A video driver.
Definition driver.h:43
virtual void InputLoop()
Handle input logic, is CTRL pressed, should we fast-forward, etc.
virtual bool ToggleFullscreen(bool fullscreen)=0
Change the full screen setting.
int anim_pitch
Pitch of the animation buffer if supported/used.
virtual Dimension GetScreenSize() const
Get the resolution of the main screen.
virtual void PopulateSystemSprites()
Populate all sprites in cache.
void QueueOnMainThread(std::function< void()> &&func)
Queue a function to be called on the main thread with game state lock held and video buffer locked.
virtual std::string_view GetInfoString() const
Get some information about the selected driver/backend to be shown to the user.
const uint DEFAULT_WINDOW_WIDTH
Default window width.
bool fast_forward_key_pressed
The fast-forward key is being pressed.
virtual void ClearSystemSprites()
Clear all cached sprites.
virtual bool UseSystemCursor()
Get whether the mouse cursor is drawn by the video driver.
virtual void SetScreensaverInhibited(bool inhibited)
Prevents the system from going to sleep.
void Tick()
Give the video-driver a tick.
const uint DEFAULT_WINDOW_HEIGHT
Default window height.
const bool supports_animation_buffer
Whether this driver supports hardware accelerated animation.
virtual void MakeDirty(int left, int top, int width, int height)=0
Mark a particular area dirty.
void SleepTillNextTick()
Sleep till the next tick is about to happen.
void StartGameThread()
Start the loop for game-tick.
virtual void EditBoxLostFocus()
An edit box lost the input focus.
virtual bool ChangeResolution(int w, int h)=0
Change the resolution of the window.
virtual bool HasGUI() const
Whether the driver has a graphical user interface with the end user.
static std::string GetCaption()
Get the caption to use for the game's title bar.
virtual void ToggleVsync(bool vsync)
Change the vsync setting.
virtual bool AfterBlitterChange()
Callback invoked after the blitter was changed.
void StopGameThread()
Stop the loop for the game-tick.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
const uint ALLOWED_DRIFT
How many times videodriver can miss deadlines without it being overly compensated.
virtual void MainLoop()=0
Perform the actual drawing.
virtual void EditBoxGainedFocus()
An edit box gained the input focus.
virtual bool PollEvent()
Process a single system event.
VideoDriver(bool uses_hardware_acceleration=false, bool supports_animation_buffer=false)
Create the video driver.
virtual bool HasEfficient8Bpp() const
Has this video driver an efficient code path for palette animated 8-bpp sprites?
virtual void Paint()
Paint the window.
virtual void UnlockVideoBuffer()
Unlock a previously locked video buffer.
uint8_t * anim_buffer
The animation buffer if supported/used.
bool fast_forward_via_key
The fast-forward was enabled by key press.
constexpr bool SupportsAnimationBuffer() const
Does this video driver support a separate animation buffer in addition to the colour buffer?
virtual void ClaimMousePointer()
Claim the exclusive rights for the mouse pointer.
virtual std::vector< int > GetListOfMonitorRefreshRates()
Get a list of refresh rates of each available monitor.
constexpr uint8_t * GetAnimBuffer() const
Get a pointer to the animation buffer of the video back-end.
virtual void CheckPaletteAnim()
Process any pending palette animation.
virtual bool LockVideoBuffer()
Make sure the video buffer is ready for drawing.
void GameLoopPause()
Pause the game-loop for a bit, releasing the game-state lock.
void DrainCommandQueue()
Execute all queued commands.
void UpdateAutoResolution()
Apply resolution auto-detection and clamp to sensible defaults.
const bool uses_hardware_acceleration
Whether hardware acceleration is used or not.
bool is_game_threaded
Whether the game is allowed to use threads; cleared in the driver implementation constructors if requ...
constexpr int GetAnimBufferPitch() const
Get the animation buffer pitch in uint8_t elements per row.
Functions related to debugging.
std::string _ini_videodriver
The video driver a stored in the configuration file.
Definition driver.cpp:27
std::vector< Dimension > _resolutions
List of resolutions.
Definition driver.cpp:28
Dimension _cur_resolution
The current resolution.
Definition driver.cpp:29
bool _rightclick_emulate
Whether right clicking is emulated.
Definition driver.cpp:30
Base for all drivers (video, sound, music, etc).
All geometry types in OpenTTD.
uint16_t _game_speed
Current game-speed; 100 is 1x, 0 is infinite.
Definition gfx.cpp:40
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:46
Functions related to the gfx engine.
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition gfx_type.h:417
Integer math functions.
constexpr uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Types related to global configuration settings.
GUISettings gui
settings related to the GUI
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
uint16_t refresh_rate
How often we refresh the screen (time between draw-ticks).
bool unlock
Stores if the lock did anything that has to be undone.
VideoBufferLocker()
Lock the video buffer.
~VideoBufferLocker()
Release the video buffer.
bool _video_vsync
Whether we should use vsync (only if active video driver supports HW acceleration).
bool _video_hw_accel
Whether to consider hardware accelerated video drivers on startup.
bool _video_vsync
Whether we should use vsync (only if active video driver supports HW acceleration).
Dimension _cur_resolution
The current resolution.
Definition driver.cpp:29
std::mutex lock
synchronization for playback status fields
Definition win32_m.cpp:35