Changeset - r25014:e1f1bf3a062e
[Not reviewed]
master
0 17 0
Patric Stout - 3 years ago 2021-02-24 14:22:23
truebrain@openttd.org
Add: [Video] move GameLoop into its own thread

This allows drawing to happen while the GameLoop is doing an
iteration too.

Sadly, not much drawing currently can be done while the GameLoop
is running, as for example PollEvent() or UpdateWindows() can
influence the game-state. As such, they first need to acquire a
lock on the game-state before they can be called.

Currently, the main advantage is the time spend in Paint(), which
for non-OpenGL drivers can be a few milliseconds. For OpenGL this
is more like 0.05 milliseconds; in these instances this change
doesn't add any benefits for now.

This is an alternative to the former "draw-thread", which moved
the drawing in a thread for some OSes. It has similar performance
gain as this does, although this implementation allows for more
finer control over what suffers when the GameLoop takes too
long: drawing or the next GameLoop. For now they both suffer
equally.
17 files changed with 206 insertions and 51 deletions:
0 comments (0 inline, 0 general)
src/video/allegro_v.cpp
Show inline comments
 
@@ -403,25 +403,25 @@ bool VideoDriver_Allegro::PollEvent()
 
		HandleKeypress(keycode, character);
 
	}
 

	
 
	return false;
 
}
 

	
 
/**
 
 * There are multiple modules that might be using Allegro and
 
 * Allegro can only be initiated once.
 
 */
 
int _allegro_instance_count = 0;
 

	
 
const char *VideoDriver_Allegro::Start(const StringList &parm)
 
const char *VideoDriver_Allegro::Start(const StringList &param)
 
{
 
	if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, nullptr)) {
 
		DEBUG(driver, 0, "allegro: install_allegro failed '%s'", allegro_error);
 
		return "Failed to set up Allegro";
 
	}
 
	_allegro_instance_count++;
 

	
 
	this->UpdateAutoResolution();
 

	
 
	install_timer();
 
	install_mouse();
 
	install_keyboard();
 
@@ -431,24 +431,26 @@ const char *VideoDriver_Allegro::Start(c
 
 * be triggered, so rereplace the signals and make the debugger useful. */
 
	signal(SIGABRT, nullptr);
 
	signal(SIGSEGV, nullptr);
 
#endif
 

	
 
	GetVideoModes();
 
	if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
 
		return "Failed to set up Allegro video";
 
	}
 
	MarkWholeScreenDirty();
 
	set_close_button_callback(HandleExitGameRequest);
 

	
 
	this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
 

	
 
	return nullptr;
 
}
 

	
 
void VideoDriver_Allegro::Stop()
 
{
 
	if (--_allegro_instance_count == 0) allegro_exit();
 
}
 

	
 
void VideoDriver_Allegro::InputLoop()
 
{
 
	bool old_ctrl_pressed = _ctrl_pressed;
 

	
 
@@ -466,30 +468,34 @@ void VideoDriver_Allegro::InputLoop()
 
	/* Determine which directional keys are down. */
 
	_dirkeys =
 
		(key[KEY_LEFT]  ? 1 : 0) |
 
		(key[KEY_UP]    ? 2 : 0) |
 
		(key[KEY_RIGHT] ? 4 : 0) |
 
		(key[KEY_DOWN]  ? 8 : 0);
 

	
 
	if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
 
}
 

	
 
void VideoDriver_Allegro::MainLoop()
 
{
 
	this->StartGameThread();
 

	
 
	for (;;) {
 
		if (_exit_game) return;
 
		if (_exit_game) break;
 

	
 
		this->Tick();
 
		this->SleepTillNextTick();
 
	}
 

	
 
	this->StopGameThread();
 
}
 

	
 
bool VideoDriver_Allegro::ChangeResolution(int w, int h)
 
{
 
	return CreateMainSurface(w, h);
 
}
 

	
 
bool VideoDriver_Allegro::ToggleFullscreen(bool fullscreen)
 
{
 
	_fullscreen = fullscreen;
 
	GetVideoModes(); // get the list of available video modes
 
	if (_resolutions.empty() || !this->ChangeResolution(_cur_resolution.width, _cur_resolution.height)) {
src/video/cocoa/cocoa_ogl.h
Show inline comments
 
@@ -24,24 +24,26 @@ class VideoDriver_CocoaOpenGL : public V
 
public:
 
	VideoDriver_CocoaOpenGL() : gl_context(nullptr), anim_buffer(nullptr) {}
 

	
 
	const char *Start(const StringList &param) override;
 
	void Stop() override;
 

	
 
	bool HasEfficient8Bpp() const override { return true; }
 

	
 
	bool UseSystemCursor() override { return true; }
 

	
 
	void ClearSystemSprites() override;
 

	
 
	void PopulateSystemSprites() override;
 

	
 
	bool HasAnimBuffer() override { return true; }
 
	uint8 *GetAnimBuffer() override { return this->anim_buffer; }
 

	
 
	/** Return driver name */
 
	const char *GetName() const override { return "cocoa-opengl"; }
 

	
 
	void AllocateBackingStore(bool force = false) override;
 

	
 
protected:
 
	void Paint() override;
 

	
 
	void *GetVideoPointer() override;
src/video/cocoa/cocoa_ogl.mm
Show inline comments
 
@@ -205,37 +205,44 @@ const char *VideoDriver_CocoaOpenGL::Sta
 
		this->Stop();
 
		return "Could not create window";
 
	}
 

	
 
	this->AllocateBackingStore(true);
 

	
 
	if (fullscreen) this->ToggleFullscreen(fullscreen);
 

	
 
	this->GameSizeChanged();
 
	this->UpdateVideoModes();
 
	MarkWholeScreenDirty();
 

	
 
	this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
 

	
 
	return nullptr;
 

	
 
}
 

	
 
void VideoDriver_CocoaOpenGL::Stop()
 
{
 
	this->VideoDriver_Cocoa::Stop();
 

	
 
	CGLSetCurrentContext(this->gl_context);
 
	OpenGLBackend::Destroy();
 
	CGLReleaseContext(this->gl_context);
 
}
 

	
 
void VideoDriver_CocoaOpenGL::PopulateSystemSprites()
 
{
 
	OpenGLBackend::Get()->PopulateCursorCache();
 
}
 

	
 
void VideoDriver_CocoaOpenGL::ClearSystemSprites()
 
{
 
	CGLSetCurrentContext(this->gl_context);
 
	OpenGLBackend::Get()->ClearCursorCache();
 
}
 

	
 
const char *VideoDriver_CocoaOpenGL::AllocateContext(bool allow_software)
 
{
 
	[ OTTD_CGLLayer setAllowSoftware:allow_software ];
 

	
 
	CGLPixelFormatObj pxfmt = [ OTTD_CGLLayer defaultPixelFormat ];
 
	if (pxfmt == nullptr) return "No suitable pixel format found";
src/video/cocoa/cocoa_v.mm
Show inline comments
 
@@ -426,36 +426,40 @@ void VideoDriver_Cocoa::InputLoop()
 
#if defined(_DEBUG)
 
	this->fast_forward_key_pressed = _shift_pressed;
 
#else
 
	this->fast_forward_key_pressed = _tab_is_down;
 
#endif
 

	
 
	if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
 
}
 

	
 
/** Main game loop. */
 
void VideoDriver_Cocoa::MainLoopReal()
 
{
 
	this->StartGameThread();
 

	
 
	for (;;) {
 
		@autoreleasepool {
 
			if (_exit_game) {
 
				/* Restore saved resolution if in fullscreen mode. */
 
				if (this->IsFullscreen()) _cur_resolution = this->orig_res;
 
				break;
 
			}
 

	
 
			this->Tick();
 
			this->SleepTillNextTick();
 
		}
 
	}
 

	
 
	this->StopGameThread();
 
}
 

	
 

	
 
/* Subclass of OTTD_CocoaView to fix Quartz rendering */
 
@interface OTTD_QuartzView : NSView {
 
	VideoDriver_CocoaQuartz *driver;
 
}
 
- (instancetype)initWithFrame:(NSRect)frameRect andDriver:(VideoDriver_CocoaQuartz *)drv;
 
@end
 

	
 
@implementation OTTD_QuartzView
 

	
 
@@ -549,24 +553,26 @@ const char *VideoDriver_CocoaQuartz::Sta
 
	if (!this->MakeWindow(_cur_resolution.width, _cur_resolution.height)) {
 
		Stop();
 
		return "Could not create window";
 
	}
 

	
 
	this->AllocateBackingStore(true);
 

	
 
	if (fullscreen) this->ToggleFullscreen(fullscreen);
 

	
 
	this->GameSizeChanged();
 
	this->UpdateVideoModes();
 

	
 
	this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
 

	
 
	return nullptr;
 

	
 
}
 

	
 
void VideoDriver_CocoaQuartz::Stop()
 
{
 
	this->VideoDriver_Cocoa::Stop();
 

	
 
	CGContextRelease(this->cgcontext);
 

	
 
	free(this->window_buffer);
 
	free(this->pixel_buffer);
src/video/dedicated_v.cpp
Show inline comments
 
@@ -258,24 +258,26 @@ void VideoDriver_Dedicated::MainLoop()
 
		/* First we need to test if the savegame can be loaded, else we will end up playing the
 
		 *  intro game... */
 
		if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, BASE_DIR)) {
 
			/* Loading failed, pop out.. */
 
			DEBUG(net, 0, "Loading requested map failed, aborting");
 
			_networking = false;
 
		} else {
 
			/* We can load this game, so go ahead */
 
			SwitchToMode(SM_LOAD_GAME);
 
		}
 
	}
 

	
 
	this->is_game_threaded = false;
 

	
 
	/* Done loading, start game! */
 

	
 
	if (!_networking) {
 
		DEBUG(net, 0, "Dedicated server could not be started, aborting");
 
		return;
 
	}
 

	
 
	while (!_exit_game) {
 
		if (!_dedicated_forks) DedicatedHandleKeyInput();
 

	
 
		ChangeGameSpeed(_ddc_fastforward);
 
		this->Tick();
src/video/null_v.cpp
Show inline comments
 
@@ -39,21 +39,21 @@ const char *VideoDriver_Null::Start(cons
 
	return nullptr;
 
}
 

	
 
void VideoDriver_Null::Stop() { }
 

	
 
void VideoDriver_Null::MakeDirty(int left, int top, int width, int height) {}
 

	
 
void VideoDriver_Null::MainLoop()
 
{
 
	uint i;
 

	
 
	for (i = 0; i < this->ticks; i++) {
 
		GameLoop();
 
		InputLoop();
 
		UpdateWindows();
 
		::GameLoop();
 
		::InputLoop();
 
		::UpdateWindows();
 
	}
 
}
 

	
 
bool VideoDriver_Null::ChangeResolution(int w, int h) { return false; }
 

	
 
bool VideoDriver_Null::ToggleFullscreen(bool fs) { return false; }
src/video/opengl.cpp
Show inline comments
 
@@ -1027,39 +1027,50 @@ void OpenGLBackend::Paint()
 
	_glEnable(GL_BLEND);
 
}
 

	
 
/**
 
 * Draw mouse cursor on screen.
 
 */
 
void OpenGLBackend::DrawMouseCursor()
 
{
 
	/* Draw cursor on screen */
 
	_cur_dpi = &_screen;
 
	for (uint i = 0; i < _cursor.sprite_count; ++i) {
 
		SpriteID sprite = _cursor.sprite_seq[i].sprite;
 
		const Sprite *spr = GetSprite(sprite, ST_NORMAL);
 

	
 
		/* Sprites are cached by PopulateCursorCache(). */
 
		if (this->cursor_cache.Contains(sprite)) {
 
			const Sprite *spr = GetSprite(sprite, ST_NORMAL);
 

	
 
			this->RenderOglSprite((OpenGLSprite *)this->cursor_cache.Get(sprite)->data, _cursor.sprite_seq[i].pal,
 
					_cursor.pos.x + _cursor.sprite_pos[i].x + UnScaleByZoom(spr->x_offs, ZOOM_LVL_GUI),
 
					_cursor.pos.y + _cursor.sprite_pos[i].y + UnScaleByZoom(spr->y_offs, ZOOM_LVL_GUI),
 
					ZOOM_LVL_GUI);
 
		}
 
	}
 
}
 

	
 
void OpenGLBackend::PopulateCursorCache()
 
{
 
	for (uint i = 0; i < _cursor.sprite_count; ++i) {
 
		SpriteID sprite = _cursor.sprite_seq[i].sprite;
 

	
 
		if (!this->cursor_cache.Contains(sprite)) {
 
			Sprite *old = this->cursor_cache.Insert(sprite, (Sprite *)GetRawSprite(sprite, ST_NORMAL, &SimpleSpriteAlloc, this));
 
			if (old != nullptr) {
 
				OpenGLSprite *sprite = (OpenGLSprite *)old->data;
 
				sprite->~OpenGLSprite();
 
				free(old);
 
			}
 
		}
 

	
 
		this->RenderOglSprite((OpenGLSprite *)this->cursor_cache.Get(sprite)->data, _cursor.sprite_seq[i].pal,
 
				_cursor.pos.x + _cursor.sprite_pos[i].x + UnScaleByZoom(spr->x_offs, ZOOM_LVL_GUI),
 
				_cursor.pos.y + _cursor.sprite_pos[i].y + UnScaleByZoom(spr->y_offs, ZOOM_LVL_GUI),
 
				ZOOM_LVL_GUI);
 
	}
 
}
 

	
 
/**
 
 * Clear all cached cursor sprites.
 
 */
 
void OpenGLBackend::ClearCursorCache()
 
{
 
	this->last_sprite_pal = (PaletteID)-1;
 

	
 
	Sprite *sp;
 
	while ((sp = this->cursor_cache.Pop()) != nullptr) {
src/video/opengl.h
Show inline comments
 
@@ -79,24 +79,25 @@ public:
 
		return OpenGLBackend::instance;
 
	}
 
	static const char *Create(GetOGLProcAddressProc get_proc);
 
	static void Destroy();
 

	
 
	void PrepareContext();
 

	
 
	void UpdatePalette(const Colour *pal, uint first, uint length);
 
	bool Resize(int w, int h, bool force = false);
 
	void Paint();
 

	
 
	void DrawMouseCursor();
 
	void PopulateCursorCache();
 
	void ClearCursorCache();
 

	
 
	void *GetVideoBuffer();
 
	uint8 *GetAnimBuffer();
 
	void ReleaseVideoBuffer(const Rect &update_rect);
 
	void ReleaseAnimBuffer(const Rect &update_rect);
 

	
 
	/* SpriteEncoder */
 

	
 
	bool Is32BppSupported() override { return true; }
 
	uint GetSpriteAlignment() override { return 1u << (ZOOM_LVL_COUNT - 1); }
 
	Sprite *Encode(const SpriteLoader::Sprite *sprite, AllocatorProc *allocator) override;
src/video/sdl2_default_v.cpp
Show inline comments
 
@@ -98,31 +98,25 @@ void VideoDriver_SDL_Default::Paint()
 

	
 
	if (IsEmptyRect(this->dirty_rect) && _cur_palette.count_dirty == 0) return;
 

	
 
	if (_cur_palette.count_dirty != 0) {
 
		Blitter *blitter = BlitterFactory::GetCurrentBlitter();
 

	
 
		switch (blitter->UsePaletteAnimation()) {
 
			case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
 
				this->UpdatePalette();
 
				break;
 

	
 
			case Blitter::PALETTE_ANIMATION_BLITTER: {
 
				bool need_buf = _screen.dst_ptr == nullptr;
 
				if (need_buf) _screen.dst_ptr = this->GetVideoPointer();
 
				blitter->PaletteAnimate(this->local_palette);
 
				if (need_buf) {
 
					this->ReleaseVideoPointer();
 
					_screen.dst_ptr = nullptr;
 
				}
 
				break;
 
			}
 

	
 
			case Blitter::PALETTE_ANIMATION_NONE:
 
				break;
 

	
 
			default:
 
				NOT_REACHED();
 
		}
 
		_cur_palette.count_dirty = 0;
 
	}
 

	
src/video/sdl2_opengl_v.cpp
Show inline comments
 
@@ -101,24 +101,29 @@ const char *VideoDriver_SDL_OpenGL::Allo
 
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
 

	
 
	if (_debug_driver_level >= 8) {
 
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
 
	}
 

	
 
	this->gl_context = SDL_GL_CreateContext(this->sdl_window);
 
	if (this->gl_context == nullptr) return "SDL2: Can't active GL context";
 

	
 
	return OpenGLBackend::Create(&GetOGLProcAddressCallback);
 
}
 

	
 
void VideoDriver_SDL_OpenGL::PopulateSystemSprites()
 
{
 
	OpenGLBackend::Get()->PopulateCursorCache();
 
}
 

	
 
void VideoDriver_SDL_OpenGL::ClearSystemSprites()
 
{
 
	OpenGLBackend::Get()->ClearCursorCache();
 
}
 

	
 
bool VideoDriver_SDL_OpenGL::AllocateBackingStore(int w, int h, bool force)
 
{
 
	if (this->gl_context == nullptr) return false;
 

	
 
	if (_screen.dst_ptr != nullptr) this->ReleaseVideoPointer();
 

	
 
	w = std::max(w, 64);
src/video/sdl2_opengl_v.h
Show inline comments
 
@@ -15,24 +15,26 @@ public:
 
	VideoDriver_SDL_OpenGL() : gl_context(nullptr), anim_buffer(nullptr) {}
 

	
 
	const char *Start(const StringList &param) override;
 

	
 
	void Stop() override;
 

	
 
	bool HasEfficient8Bpp() const override { return true; }
 

	
 
	bool UseSystemCursor() override { return true; }
 

	
 
	void ClearSystemSprites() override;
 

	
 
	void PopulateSystemSprites() override;
 

	
 
	bool HasAnimBuffer() override { return true; }
 
	uint8 *GetAnimBuffer() override { return this->anim_buffer; }
 

	
 
	const char *GetName() const override { return "sdl-opengl"; }
 

	
 
protected:
 
	bool AllocateBackingStore(int w, int h, bool force = false) override;
 
	void *GetVideoPointer() override;
 
	void ReleaseVideoPointer() override;
 
	void Paint() override;
 
	bool CreateMainWindow(uint w, uint h, uint flags) override;
 

	
src/video/sdl2_v.cpp
Show inline comments
 
@@ -532,45 +532,51 @@ const char *VideoDriver_SDL_Base::Initia
 
{
 
	this->UpdateAutoResolution();
 

	
 
	const char *error = InitializeSDL();
 
	if (error != nullptr) return error;
 

	
 
	FindResolutions();
 
	DEBUG(driver, 2, "Resolution for display: %ux%u", _cur_resolution.width, _cur_resolution.height);
 

	
 
	return nullptr;
 
}
 

	
 
const char *VideoDriver_SDL_Base::Start(const StringList &parm)
 
const char *VideoDriver_SDL_Base::Start(const StringList &param)
 
{
 
	if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
 

	
 
	const char *error = this->Initialize();
 
	if (error != nullptr) return error;
 

	
 
	this->startup_display = FindStartupDisplay(GetDriverParamInt(parm, "display", -1));
 
	this->startup_display = FindStartupDisplay(GetDriverParamInt(param, "display", -1));
 

	
 
	if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height, false)) {
 
		return SDL_GetError();
 
	}
 

	
 
	const char *dname = SDL_GetCurrentVideoDriver();
 
	DEBUG(driver, 1, "SDL2: using driver '%s'", dname);
 

	
 
	MarkWholeScreenDirty();
 

	
 
	SDL_StopTextInput();
 
	this->edit_box_focused = false;
 

	
 
#ifdef __EMSCRIPTEN__
 
	this->is_game_threaded = false;
 
#else
 
	this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
 
#endif
 

	
 
	return nullptr;
 
}
 

	
 
void VideoDriver_SDL_Base::Stop()
 
{
 
	SDL_QuitSubSystem(SDL_INIT_VIDEO);
 
	if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
 
		SDL_Quit(); // If there's nothing left, quit SDL
 
	}
 
}
 

	
 
void VideoDriver_SDL_Base::InputLoop()
 
@@ -628,27 +634,31 @@ void VideoDriver_SDL_Base::LoopOnce()
 
 * downtime between each iteration, so no need to sleep. */
 
#ifndef __EMSCRIPTEN__
 
	this->SleepTillNextTick();
 
#endif
 
}
 

	
 
void VideoDriver_SDL_Base::MainLoop()
 
{
 
#ifdef __EMSCRIPTEN__
 
	/* Run the main loop event-driven, based on RequestAnimationFrame. */
 
	emscripten_set_main_loop_arg(&this->EmscriptenLoop, this, 0, 1);
 
#else
 
	this->StartGameThread();
 

	
 
	while (!_exit_game) {
 
		LoopOnce();
 
	}
 

	
 
	this->StopGameThread();
 
#endif
 
}
 

	
 
bool VideoDriver_SDL_Base::ChangeResolution(int w, int h)
 
{
 
	return CreateMainSurface(w, h, true);
 
}
 

	
 
bool VideoDriver_SDL_Base::ToggleFullscreen(bool fullscreen)
 
{
 
	int w, h;
 

	
src/video/sdl_v.cpp
Show inline comments
 
@@ -561,28 +561,28 @@ bool VideoDriver_SDL::PollEvent()
 
		case SDL_VIDEOEXPOSE: {
 
			/* Force a redraw of the entire screen. Note
 
			 * that SDL 1.2 seems to do this automatically
 
			 * in most cases, but 1.3 / 2.0 does not. */
 
		        _num_dirty_rects = MAX_DIRTY_RECTS + 1;
 
			break;
 
		}
 
	}
 

	
 
	return true;
 
}
 

	
 
const char *VideoDriver_SDL::Start(const StringList &parm)
 
const char *VideoDriver_SDL::Start(const StringList &param)
 
{
 
	char buf[30];
 
	_use_hwpalette = GetDriverParamInt(parm, "hw_palette", 2);
 
	_use_hwpalette = GetDriverParamInt(param, "hw_palette", 2);
 

	
 
	/* Just on the offchance the audio subsystem started before the video system,
 
	 * check whether any part of SDL has been initialised before getting here.
 
	 * Slightly duplicated with sound/sdl_s.cpp */
 
	int ret_code = 0;
 
	if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
 
		ret_code = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);
 
	} else if (SDL_WasInit(SDL_INIT_VIDEO) == 0) {
 
		ret_code = SDL_InitSubSystem(SDL_INIT_VIDEO);
 
	}
 
	if (ret_code < 0) return SDL_GetError();
 

	
 
@@ -590,24 +590,26 @@ const char *VideoDriver_SDL::Start(const
 

	
 
	GetVideoModes();
 
	if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
 
		return SDL_GetError();
 
	}
 

	
 
	SDL_VideoDriverName(buf, sizeof buf);
 
	DEBUG(driver, 1, "SDL: using driver '%s'", buf);
 

	
 
	MarkWholeScreenDirty();
 
	SetupKeyboard();
 

	
 
	this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
 

	
 
	return nullptr;
 
}
 

	
 
void VideoDriver_SDL::SetupKeyboard()
 
{
 
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
 
	SDL_EnableUNICODE(1);
 
}
 

	
 
void VideoDriver_SDL::Stop()
 
{
 
	SDL_QuitSubSystem(SDL_INIT_VIDEO);
 
@@ -638,30 +640,34 @@ void VideoDriver_SDL::InputLoop()
 
	/* Determine which directional keys are down. */
 
	_dirkeys =
 
		(keys[SDLK_LEFT]  ? 1 : 0) |
 
		(keys[SDLK_UP]    ? 2 : 0) |
 
		(keys[SDLK_RIGHT] ? 4 : 0) |
 
		(keys[SDLK_DOWN]  ? 8 : 0);
 

	
 
	if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
 
}
 

	
 
void VideoDriver_SDL::MainLoop()
 
{
 
	this->StartGameThread();
 

	
 
	for (;;) {
 
		if (_exit_game) break;
 

	
 
		this->Tick();
 
		this->SleepTillNextTick();
 
	}
 

	
 
	this->StopGameThread();
 
}
 

	
 
bool VideoDriver_SDL::ChangeResolution(int w, int h)
 
{
 
	return CreateMainSurface(w, h);
 
}
 

	
 
bool VideoDriver_SDL::ToggleFullscreen(bool fullscreen)
 
{
 
	_fullscreen = fullscreen;
 
	GetVideoModes(); // get the list of available video modes
 
	bool ret = !_resolutions.empty() && CreateMainSurface(_cur_resolution.width, _cur_resolution.height);
src/video/video_driver.cpp
Show inline comments
 
/*
 
 * This file is part of OpenTTD.
 
 * 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.
 
 * 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.
 
 * 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/>.
 
 */
 

	
 
/** @file video_driver.cpp Common code between video driver implementations. */
 

	
 
#include "../stdafx.h"
 
#include "../debug.h"
 
#include "../core/random_func.hpp"
 
#include "../network/network.h"
 
#include "../debug.h"
 
#include "../gfx_func.h"
 
#include "../progress.h"
 
#include "../thread.h"
 
#include "../window_func.h"
 
#include "video_driver.hpp"
 

	
 
bool _video_hw_accel; ///< Whether to consider hardware accelerated video drivers.
 

	
 
void VideoDriver::GameLoop()
 
{
 
	this->next_game_tick += this->GetGameInterval();
 

	
 
	/* Avoid next_game_tick getting behind more and more if it cannot keep up. */
 
	auto now = std::chrono::steady_clock::now();
 
	if (this->next_game_tick < now - ALLOWED_DRIFT * this->GetGameInterval()) this->next_game_tick = now;
 

	
 
	{
 
		std::lock_guard<std::mutex> lock(this->game_state_mutex);
 

	
 
		::GameLoop();
 
	}
 
}
 

	
 
void VideoDriver::GameThread()
 
{
 
	while (!_exit_game) {
 
		this->GameLoop();
 

	
 
		auto now = std::chrono::steady_clock::now();
 
		if (this->next_game_tick > now) {
 
			std::this_thread::sleep_for(this->next_game_tick - now);
 
		} else {
 
			/* Ensure we yield this thread if drawings wants to take a lock on
 
			 * the game state. This is mainly because most OSes have an
 
			 * optimization that if you unlock/lock a mutex in the same thread
 
			 * quickly, it will never context switch even if there is another
 
			 * thread waiting to take the lock on the same mutex. */
 
			std::lock_guard<std::mutex> lock(this->game_thread_wait_mutex);
 
		}
 
	}
 
}
 

	
 
/* static */ void VideoDriver::GameThreadThunk(VideoDriver *drv)
 
{
 
	drv->GameThread();
 
}
 

	
 
void VideoDriver::StartGameThread()
 
{
 
	if (this->is_game_threaded) {
 
		this->is_game_threaded = StartNewThread(&this->game_thread, "ottd:game", &VideoDriver::GameThreadThunk, this);
 
	}
 

	
 
	DEBUG(driver, 1, "using %sthread for game-loop", this->is_game_threaded ? "" : "no ");
 
}
 

	
 
void VideoDriver::StopGameThread()
 
{
 
	if (!this->is_game_threaded) return;
 

	
 
	this->game_thread.join();
 
}
 

	
 
void VideoDriver::Tick()
 
{
 
	auto cur_ticks = std::chrono::steady_clock::now();
 

	
 
	if (cur_ticks >= this->next_game_tick) {
 
		this->next_game_tick += this->GetGameInterval();
 
		/* Avoid next_game_tick getting behind more and more if it cannot keep up. */
 
		if (this->next_game_tick < cur_ticks - ALLOWED_DRIFT * this->GetGameInterval()) this->next_game_tick = cur_ticks;
 

	
 
		/* The game loop is the part that can run asynchronously.
 
		 * The rest except sleeping can't. */
 
		this->UnlockVideoBuffer();
 
		::GameLoop();
 
		this->LockVideoBuffer();
 
	if (!this->is_game_threaded && std::chrono::steady_clock::now() >= this->next_game_tick) {
 
		this->GameLoop();
 

	
 
		/* For things like dedicated server, don't run a separate draw-tick. */
 
		if (!this->HasGUI()) {
 
			::InputLoop();
 
			UpdateWindows();
 
			::UpdateWindows();
 
			this->next_draw_tick = this->next_game_tick;
 
		}
 
	}
 

	
 
	/* Prevent drawing when switching mode, as windows can be removed when they should still appear. */
 
	if (this->HasGUI() && cur_ticks >= this->next_draw_tick && (_switch_mode == SM_NONE || _game_mode == GM_BOOTSTRAP || HasModalProgress())) {
 
	auto now = std::chrono::steady_clock::now();
 
	if (this->HasGUI() && now >= this->next_draw_tick) {
 
		this->next_draw_tick += this->GetDrawInterval();
 
		/* Avoid next_draw_tick getting behind more and more if it cannot keep up. */
 
		if (this->next_draw_tick < cur_ticks - ALLOWED_DRIFT * this->GetDrawInterval()) this->next_draw_tick = cur_ticks;
 
		if (this->next_draw_tick < now - ALLOWED_DRIFT * this->GetDrawInterval()) this->next_draw_tick = now;
 

	
 
		/* Keep the interactive randomizer a bit more random by requesting
 
		 * new values when-ever we can. */
 
		InteractiveRandom();
 

	
 
		while (this->PollEvent()) {}
 
		this->InputLoop();
 

	
 
		/* Check if the fast-forward button is still pressed. */
 
		if (fast_forward_key_pressed && !_networking && _game_mode != GM_MENU) {
 
			ChangeGameSpeed(true);
 
			this->fast_forward_via_key = true;
 
		} else if (this->fast_forward_via_key) {
 
			ChangeGameSpeed(false);
 
			this->fast_forward_via_key = false;
 
		}
 

	
 
		::InputLoop();
 
		UpdateWindows();
 
		{
 
			/* Tell the game-thread to stop so we can have a go. */
 
			std::lock_guard<std::mutex> lock_wait(this->game_thread_wait_mutex);
 
			std::lock_guard<std::mutex> lock_state(this->game_state_mutex);
 

	
 
			this->LockVideoBuffer();
 

	
 
			while (this->PollEvent()) {}
 
			::InputLoop();
 

	
 
			/* Prevent drawing when switching mode, as windows can be removed when they should still appear. */
 
			if (_game_mode == GM_BOOTSTRAP || _switch_mode == SM_NONE || HasModalProgress()) {
 
				::UpdateWindows();
 
			}
 

	
 
			this->PopulateSystemSprites();
 
		}
 

	
 
		this->CheckPaletteAnim();
 
		this->Paint();
 

	
 
		this->UnlockVideoBuffer();
 
	}
 
}
 

	
 
void VideoDriver::SleepTillNextTick()
 
{
 
	/* See how much time there is till we have to process the next event, and try to hit that as close as possible. */
 
	auto next_tick = std::min(this->next_draw_tick, this->next_game_tick);
 
	auto next_tick = this->next_draw_tick;
 
	auto now = std::chrono::steady_clock::now();
 

	
 
	if (!this->is_game_threaded) {
 
		next_tick = min(next_tick, this->next_game_tick);
 
	}
 

	
 
	if (next_tick > now) {
 
		this->UnlockVideoBuffer();
 
		std::this_thread::sleep_for(next_tick - now);
 
		this->LockVideoBuffer();
 
	}
 
}
src/video/video_driver.hpp
Show inline comments
 
@@ -7,39 +7,45 @@
 

	
 
/** @file video_driver.hpp Base of all video drivers. */
 

	
 
#ifndef VIDEO_VIDEO_DRIVER_HPP
 
#define VIDEO_VIDEO_DRIVER_HPP
 

	
 
#include "../driver.h"
 
#include "../core/geometry_type.hpp"
 
#include "../core/math_func.hpp"
 
#include "../gfx_func.h"
 
#include "../settings_type.h"
 
#include "../zoom_type.h"
 
#include <atomic>
 
#include <chrono>
 
#include <condition_variable>
 
#include <mutex>
 
#include <thread>
 
#include <vector>
 

	
 
extern std::string _ini_videodriver;
 
extern std::vector<Dimension> _resolutions;
 
extern Dimension _cur_resolution;
 
extern bool _rightclick_emulate;
 
extern bool _video_hw_accel;
 

	
 
/** The base of all video drivers. */
 
class VideoDriver : public Driver {
 
	const uint DEFAULT_WINDOW_WIDTH = 640u;  ///< Default window width.
 
	const uint DEFAULT_WINDOW_HEIGHT = 480u; ///< Default window height.
 

	
 
public:
 
	VideoDriver() : is_game_threaded(true) {}
 

	
 
	/**
 
	 * Mark a particular area dirty.
 
	 * @param left   The left most line of the dirty area.
 
	 * @param top    The top most line of the dirty area.
 
	 * @param width  The width of the dirty area.
 
	 * @param height The height of the dirty area.
 
	 */
 
	virtual void MakeDirty(int left, int top, int width, int height) = 0;
 

	
 
	/**
 
	 * Perform the actual drawing.
 
	 */
 
@@ -75,24 +81,29 @@ public:
 
	}
 

	
 
	/**
 
	 * Get whether the mouse cursor is drawn by the video driver.
 
	 * @return True if cursor drawing is done by the video driver.
 
	 */
 
	virtual bool UseSystemCursor()
 
	{
 
		return false;
 
	}
 

	
 
	/**
 
	 * Populate all sprites in cache.
 
	 */
 
	virtual void PopulateSystemSprites() {}
 

	
 
	/**
 
	 * Clear all cached sprites.
 
	 */
 
	virtual void ClearSystemSprites() {}
 

	
 
	/**
 
	 * Whether the driver has a graphical user interface with the end user.
 
	 * Or in other words, whether we should spawn a thread for world generation
 
	 * and NewGRF scanning so the graphical updates can keep coming. Otherwise
 
	 * progress has to be shown on the console, which uses by definition another
 
	 * thread/process for display purposes.
 
	 * @return True for all drivers except null and dedicated.
 
	 */
 
@@ -231,24 +242,34 @@ protected:
 
	/**
 
	 * Process any pending palette animation.
 
	 */
 
	virtual void CheckPaletteAnim() {}
 

	
 
	/**
 
	 * Process a single system event.
 
	 * @returns False if there are no more events to process.
 
	 */
 
	virtual bool PollEvent() { return false; };
 

	
 
	/**
 
	 * Start the loop for game-tick.
 
	 */
 
	void StartGameThread();
 

	
 
	/**
 
	 * Stop the loop for the game-tick. This can still tick at most one time before truly shutting down.
 
	 */
 
	void StopGameThread();
 

	
 
	/**
 
	 * Give the video-driver a tick.
 
	 * It will process any potential game-tick and/or draw-tick, and/or any
 
	 * other video-driver related event.
 
	 */
 
	void Tick();
 

	
 
	/**
 
	 * Sleep till the next tick is about to happen.
 
	 */
 
	void SleepTillNextTick();
 

	
 
	std::chrono::steady_clock::duration GetGameInterval()
 
@@ -262,15 +283,26 @@ protected:
 
	}
 

	
 
	std::chrono::steady_clock::duration GetDrawInterval()
 
	{
 
		return std::chrono::microseconds(1000000 / _settings_client.gui.refresh_rate);
 
	}
 

	
 
	std::chrono::steady_clock::time_point next_game_tick;
 
	std::chrono::steady_clock::time_point next_draw_tick;
 

	
 
	bool fast_forward_key_pressed; ///< The fast-forward key is being pressed.
 
	bool fast_forward_via_key; ///< The fast-forward was enabled by key press.
 

	
 
	bool is_game_threaded;
 
	std::thread game_thread;
 
	std::mutex game_state_mutex;
 
	std::mutex game_thread_wait_mutex;
 

	
 
	static void GameThreadThunk(VideoDriver *drv);
 

	
 
private:
 
	void GameLoop();
 
	void GameThread();
 
};
 

	
 
#endif /* VIDEO_VIDEO_DRIVER_HPP */
src/video/win32_v.cpp
Show inline comments
 
@@ -855,30 +855,34 @@ bool VideoDriver_Win32Base::PollEvent()
 

	
 
	if (!PeekMessage(&mesg, nullptr, 0, 0, PM_REMOVE)) return false;
 

	
 
	/* Convert key messages to char messages if we want text input. */
 
	if (EditBoxInGlobalFocus()) TranslateMessage(&mesg);
 
	DispatchMessage(&mesg);
 

	
 
	return true;
 
}
 

	
 
void VideoDriver_Win32Base::MainLoop()
 
{
 
	this->StartGameThread();
 

	
 
	for (;;) {
 
		if (_exit_game) break;
 

	
 
		this->Tick();
 
		this->SleepTillNextTick();
 
	}
 

	
 
	this->StopGameThread();
 
}
 

	
 
void VideoDriver_Win32Base::ClientSizeChanged(int w, int h, bool force)
 
{
 
	/* Allocate backing store of the new size. */
 
	if (this->AllocateBackingStore(w, h, force)) {
 
		/* Mark all palette colours dirty. */
 
		_cur_palette.first_dirty = 0;
 
		_cur_palette.count_dirty = 256;
 
		_local_palette = _cur_palette;
 

	
 
		BlitterFactory::GetCurrentBlitter()->PostResize();
 
@@ -986,24 +990,26 @@ static FVideoDriver_Win32GDI iFVideoDriv
 
const char *VideoDriver_Win32GDI::Start(const StringList &param)
 
{
 
	if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
 

	
 
	this->Initialize();
 

	
 
	this->MakePalette();
 
	this->AllocateBackingStore(_cur_resolution.width, _cur_resolution.height);
 
	this->MakeWindow(_fullscreen);
 

	
 
	MarkWholeScreenDirty();
 

	
 
	this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
 

	
 
	return nullptr;
 
}
 

	
 
void VideoDriver_Win32GDI::Stop()
 
{
 
	DeleteObject(this->gdi_palette);
 
	DeleteObject(this->dib_sect);
 

	
 
	this->VideoDriver_Win32Base::Stop();
 
}
 

	
 
bool VideoDriver_Win32GDI::AllocateBackingStore(int w, int h, bool force)
 
@@ -1106,31 +1112,25 @@ void VideoDriver_Win32GDI::Paint()
 
	HBITMAP old_bmp = (HBITMAP)SelectObject(dc2, this->dib_sect);
 
	HPALETTE old_palette = SelectPalette(dc, this->gdi_palette, FALSE);
 

	
 
	if (_cur_palette.count_dirty != 0) {
 
		Blitter *blitter = BlitterFactory::GetCurrentBlitter();
 

	
 
		switch (blitter->UsePaletteAnimation()) {
 
			case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
 
				this->UpdatePalette(dc2, _local_palette.first_dirty, _local_palette.count_dirty);
 
				break;
 

	
 
			case Blitter::PALETTE_ANIMATION_BLITTER: {
 
				bool need_buf = _screen.dst_ptr == nullptr;
 
				if (need_buf) _screen.dst_ptr = this->GetVideoPointer();
 
				blitter->PaletteAnimate(_local_palette);
 
				if (need_buf) {
 
					this->ReleaseVideoPointer();
 
					_screen.dst_ptr = nullptr;
 
				}
 
				break;
 
			}
 

	
 
			case Blitter::PALETTE_ANIMATION_NONE:
 
				break;
 

	
 
			default:
 
				NOT_REACHED();
 
		}
 
		_cur_palette.count_dirty = 0;
 
	}
 

	
 
@@ -1282,24 +1282,26 @@ const char *VideoDriver_Win32OpenGL::Sta
 
	/* Create and initialize OpenGL context. */
 
	const char *err = this->AllocateContext();
 
	if (err != nullptr) {
 
		this->Stop();
 
		_cur_resolution = old_res;
 
		return err;
 
	}
 

	
 
	this->ClientSizeChanged(this->width, this->height, true);
 

	
 
	MarkWholeScreenDirty();
 

	
 
	this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
 

	
 
	return nullptr;
 
}
 

	
 
void VideoDriver_Win32OpenGL::Stop()
 
{
 
	this->DestroyContext();
 
	this->VideoDriver_Win32Base::Stop();
 
}
 

	
 
void VideoDriver_Win32OpenGL::DestroyContext()
 
{
 
	OpenGLBackend::Destroy();
 
@@ -1362,24 +1364,29 @@ bool VideoDriver_Win32OpenGL::ToggleFull
 
	res &= this->AllocateContext() == nullptr;
 
	this->ClientSizeChanged(this->width, this->height, true);
 
	return res;
 
}
 

	
 
bool VideoDriver_Win32OpenGL::AfterBlitterChange()
 
{
 
	assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
 
	this->ClientSizeChanged(this->width, this->height, true);
 
	return true;
 
}
 

	
 
void VideoDriver_Win32OpenGL::PopulateSystemSprites()
 
{
 
	OpenGLBackend::Get()->PopulateCursorCache();
 
}
 

	
 
void VideoDriver_Win32OpenGL::ClearSystemSprites()
 
{
 
	OpenGLBackend::Get()->ClearCursorCache();
 
}
 

	
 
bool VideoDriver_Win32OpenGL::AllocateBackingStore(int w, int h, bool force)
 
{
 
	if (!force && w == _screen.width && h == _screen.height) return false;
 

	
 
	this->width = w = std::max(w, 64);
 
	this->height = h = std::max(h, 64);
 

	
src/video/win32_v.h
Show inline comments
 
@@ -120,24 +120,26 @@ public:
 
	const char *Start(const StringList &param) override;
 

	
 
	void Stop() override;
 

	
 
	bool ToggleFullscreen(bool fullscreen) override;
 

	
 
	bool AfterBlitterChange() override;
 

	
 
	bool HasEfficient8Bpp() const override { return true; }
 

	
 
	bool UseSystemCursor() override { return true; }
 

	
 
	void PopulateSystemSprites() override;
 

	
 
	void ClearSystemSprites() override;
 

	
 
	bool HasAnimBuffer() override { return true; }
 
	uint8 *GetAnimBuffer() override { return this->anim_buffer; }
 

	
 
	const char *GetName() const override { return "win32-opengl"; }
 

	
 
protected:
 
	HDC    dc;          ///< Window device context.
 
	HGLRC  gl_rc;       ///< OpenGL context.
 
	bool   vsync;       ///< Enable VSync?
 
	uint8 *anim_buffer; ///< Animation buffer from OpenGL back-end.
0 comments (0 inline, 0 general)