1
0
Fork 0

Compare commits

...

11 Commits

Author SHA1 Message Date
Michał Janiszewski 47850ffb8a
Merge 7b0028db03 into 9ce2aca949 2025-07-14 18:20:18 +00:00
Peter Nelson 9ce2aca949 Codechange: Get/pass ScriptStorage by reference instead of pointer. 2025-07-14 19:19:29 +01:00
Peter Nelson 55098a2f2e Codechange: Get/pass engine by reference instead of pointer. 2025-07-14 19:19:29 +01:00
Peter Nelson 7ff0c67f77 Codechange: Get/pass script controller by reference instead of pointer. 2025-07-14 19:19:29 +01:00
Peter Nelson b2de1ff66f
Fix #14433: Broken road stop drawing due to incorrect modes conversion. (#14434)
The mask was treated as a single RoadStopDrawMode instead of a RoadStopDrawModes bitset.
2025-07-14 17:25:53 +01:00
Loïc Guilloux fc924161ab
Fix 0455627d: Don't draw timetable panel if no orders (#14441) 2025-07-14 14:18:54 +00:00
Peter Nelson 61a299bc99
Codechange: Use SpriteID as GlyphID for SpriteFontCache. (#14439)
This reduces the amount of lookups in the character map as rendering a cached layout no longer needs to do so.
2025-07-14 13:28:10 +01:00
Michał Janiszewski 7b0028db03 Change: Limit gamepad scroll only to windows that don't follow vehicles 2025-06-29 11:09:52 +02:00
Michał Janiszewski 54767e0349 Add: Select viewport under the cursor for gamepad scrolling 2025-06-29 11:09:52 +02:00
Michał Janiszewski 1fc2481340 Feature: Win32 driver support for gamepad scrolling 2025-06-29 11:09:52 +02:00
Michał Janiszewski ebd2b45753 Feature: Add gamepad scrolling support (SDL2) 2025-06-29 11:09:52 +02:00
23 changed files with 513 additions and 78 deletions

View File

@ -449,6 +449,7 @@ if(WIN32)
psapi
winhttp
bcrypt
xinput
)
endif()

View File

@ -103,14 +103,14 @@ void SpriteFontCache::ClearFontCache()
const Sprite *SpriteFontCache::GetGlyph(GlyphID key)
{
SpriteID sprite = this->GetUnicodeGlyph(static_cast<char32_t>(key & ~SPRITE_GLYPH));
SpriteID sprite = static_cast<SpriteID>(key & ~SPRITE_GLYPH);
if (sprite == 0) sprite = this->GetUnicodeGlyph('?');
return GetSprite(sprite, SpriteType::Font);
}
uint SpriteFontCache::GetGlyphWidth(GlyphID key)
{
SpriteID sprite = this->GetUnicodeGlyph(static_cast<char32_t>(key & ~SPRITE_GLYPH));
SpriteID sprite = static_cast<SpriteID>(key & ~SPRITE_GLYPH);
if (sprite == 0) sprite = this->GetUnicodeGlyph('?');
return SpriteExists(sprite) ? GetSprite(sprite, SpriteType::Font)->width + ScaleFontTrad(this->fs != FS_NORMAL ? 1 : 0) : 0;
}
@ -120,7 +120,7 @@ GlyphID SpriteFontCache::MapCharToGlyph(char32_t key, [[maybe_unused]] bool allo
assert(IsPrintable(key));
SpriteID sprite = this->GetUnicodeGlyph(key);
if (sprite == 0) return 0;
return SPRITE_GLYPH | key;
return SPRITE_GLYPH | sprite;
}
bool SpriteFontCache::GetDrawGlyphShadow()

View File

@ -75,6 +75,7 @@ void HandleTextInput(std::string_view str, bool marked = false,
std::optional<size_t> insert_location = std::nullopt, std::optional<size_t> replacement_end = std::nullopt);
void HandleCtrlChanged();
void HandleMouseEvents();
void HandleGamepadScrolling(int stick_x, int stick_y, int max_axis_value);
void UpdateWindows();
void ChangeGameSpeed(bool enable_fast_forward);

View File

@ -1698,6 +1698,25 @@ STR_CONFIG_SETTING_SCROLLWHEEL_ZOOM :Zoom map
STR_CONFIG_SETTING_SCROLLWHEEL_SCROLL :Scroll map
STR_CONFIG_SETTING_SCROLLWHEEL_OFF :Off
STR_CONFIG_SETTING_GAMEPAD_STICK_SELECTION :Gamepad stick for scrolling: {STRING2}
STR_CONFIG_SETTING_GAMEPAD_STICK_SELECTION_HELPTEXT :Select which analog stick to use for map scrolling
###length 3
STR_CONFIG_SETTING_GAMEPAD_STICK_DISABLED :Disabled
STR_CONFIG_SETTING_GAMEPAD_STICK_LEFT :Left stick
STR_CONFIG_SETTING_GAMEPAD_STICK_RIGHT :Right stick
STR_CONFIG_SETTING_GAMEPAD_DEADZONE :Gamepad deadzone: {STRING2}%
STR_CONFIG_SETTING_GAMEPAD_DEADZONE_HELPTEXT :Minimum stick movement required before scrolling starts (0-100%)
STR_CONFIG_SETTING_GAMEPAD_SENSITIVITY :Gamepad sensitivity: {STRING2}
STR_CONFIG_SETTING_GAMEPAD_SENSITIVITY_HELPTEXT :Control the sensitivity of gamepad analog stick scrolling
STR_CONFIG_SETTING_GAMEPAD_INVERT_X :Invert gamepad X-axis: {STRING2}
STR_CONFIG_SETTING_GAMEPAD_INVERT_X_HELPTEXT :Invert the horizontal axis movement of the gamepad analog stick
STR_CONFIG_SETTING_GAMEPAD_INVERT_Y :Invert gamepad Y-axis: {STRING2}
STR_CONFIG_SETTING_GAMEPAD_INVERT_Y_HELPTEXT :Invert the vertical axis movement of the gamepad analog stick
STR_CONFIG_SETTING_OSK_ACTIVATION :On screen keyboard: {STRING2}
STR_CONFIG_SETTING_OSK_ACTIVATION_HELPTEXT :Select the method to open the on screen keyboard for entering text into editboxes only using the pointing device. This is meant for small devices without actual keyboard
###length 4

View File

@ -105,8 +105,8 @@ static ChangeInfoResult RoadStopChangeInfo(uint first, uint last, int prop, Byte
AddStringForMapping(GRFStringID{buf.ReadWord()}, [rs = rs.get()](StringID str) { RoadStopClass::Get(rs->class_index)->name = str; });
break;
case 0x0C: // The draw mode
rs->draw_mode = static_cast<RoadStopDrawMode>(buf.ReadByte());
case 0x0C: // The draw modes
rs->draw_mode = static_cast<RoadStopDrawModes>(buf.ReadByte());
break;
case 0x0D: // Cargo types for random triggers

View File

@ -298,7 +298,7 @@ void DrawRoadStopTile(int x, int y, RoadType roadtype, const RoadStopSpec *spec,
RoadStopDrawModes draw_mode;
if (spec->flags.Test(RoadStopSpecFlag::DrawModeRegister)) {
draw_mode = static_cast<RoadStopDrawMode>(object.GetRegister(0x100));
draw_mode = static_cast<RoadStopDrawModes>(object.GetRegister(0x100));
} else {
draw_mode = spec->draw_mode;
}

View File

@ -76,7 +76,7 @@ ScriptController::ScriptController(::CompanyID company) :
/* static */ uint ScriptController::GetTick()
{
return ScriptObject::GetActiveInstance().GetController()->ticks;
return ScriptObject::GetActiveInstance().GetController().ticks;
}
/* static */ int ScriptController::GetOpsTillSuspend()
@ -96,9 +96,9 @@ ScriptController::ScriptController(::CompanyID company) :
/* static */ HSQOBJECT ScriptController::Import(const std::string &library, const std::string &class_name, int version)
{
ScriptController *controller = ScriptObject::GetActiveInstance().GetController();
Squirrel *engine = ScriptObject::GetActiveInstance().engine;
HSQUIRRELVM vm = engine->GetVM();
ScriptController &controller = ScriptObject::GetActiveInstance().GetController();
Squirrel &engine = *ScriptObject::GetActiveInstance().engine;
HSQUIRRELVM vm = engine.GetVM();
ScriptInfo *lib = ScriptObject::GetActiveInstance().FindLibrary(library, version);
if (lib == nullptr) {
@ -114,11 +114,11 @@ ScriptController::ScriptController(::CompanyID company) :
std::string fake_class;
LoadedLibraryList::iterator it = controller->loaded_library.find(library_name);
if (it != controller->loaded_library.end()) {
LoadedLibraryList::iterator it = controller.loaded_library.find(library_name);
if (it != controller.loaded_library.end()) {
fake_class = (*it).second;
} else {
int next_number = ++controller->loaded_library_count;
int next_number = ++controller.loaded_library_count;
/* Create a new fake internal name */
fake_class = fmt::format("_internalNA{}", next_number);
@ -128,14 +128,14 @@ ScriptController::ScriptController(::CompanyID company) :
sq_pushstring(vm, fake_class);
sq_newclass(vm, SQFalse);
/* Load the library */
if (!engine->LoadScript(vm, lib->GetMainScript(), false)) {
if (!engine.LoadScript(vm, lib->GetMainScript(), false)) {
throw sq_throwerror(vm, fmt::format("there was a compile error when importing '{}' version {}", library, version));
}
/* Create the fake class */
sq_newslot(vm, -3, SQFalse);
sq_pop(vm, 1);
controller->loaded_library[library_name] = fake_class;
controller.loaded_library[library_name] = fake_class;
}
/* Find the real class inside the fake class (like 'sets.Vector') */

View File

@ -45,7 +45,7 @@ void SimpleCountedObject::Release()
* Get the storage associated with the current ScriptInstance.
* @return The storage.
*/
static ScriptStorage *GetStorage()
static ScriptStorage &GetStorage()
{
return ScriptObject::GetActiveInstance().GetStorage();
}
@ -65,7 +65,7 @@ ScriptObject::ActiveInstance::~ActiveInstance()
}
ScriptObject::DisableDoCommandScope::DisableDoCommandScope()
: AutoRestoreBackup(GetStorage()->allow_do_command, false)
: AutoRestoreBackup(GetStorage().allow_do_command, false)
{}
/* static */ ScriptInstance &ScriptObject::GetActiveInstance()
@ -78,181 +78,181 @@ ScriptObject::DisableDoCommandScope::DisableDoCommandScope()
/* static */ void ScriptObject::SetDoCommandDelay(uint ticks)
{
assert(ticks > 0);
GetStorage()->delay = ticks;
GetStorage().delay = ticks;
}
/* static */ uint ScriptObject::GetDoCommandDelay()
{
return GetStorage()->delay;
return GetStorage().delay;
}
/* static */ void ScriptObject::SetDoCommandMode(ScriptModeProc *proc, ScriptObject *instance)
{
GetStorage()->mode = proc;
GetStorage()->mode_instance = instance;
GetStorage().mode = proc;
GetStorage().mode_instance = instance;
}
/* static */ ScriptModeProc *ScriptObject::GetDoCommandMode()
{
return GetStorage()->mode;
return GetStorage().mode;
}
/* static */ ScriptObject *ScriptObject::GetDoCommandModeInstance()
{
return GetStorage()->mode_instance;
return GetStorage().mode_instance;
}
/* static */ void ScriptObject::SetDoCommandAsyncMode(ScriptAsyncModeProc *proc, ScriptObject *instance)
{
GetStorage()->async_mode = proc;
GetStorage()->async_mode_instance = instance;
GetStorage().async_mode = proc;
GetStorage().async_mode_instance = instance;
}
/* static */ ScriptAsyncModeProc *ScriptObject::GetDoCommandAsyncMode()
{
return GetStorage()->async_mode;
return GetStorage().async_mode;
}
/* static */ ScriptObject *ScriptObject::GetDoCommandAsyncModeInstance()
{
return GetStorage()->async_mode_instance;
return GetStorage().async_mode_instance;
}
/* static */ void ScriptObject::SetLastCommand(const CommandDataBuffer &data, Commands cmd)
{
ScriptStorage *s = GetStorage();
Debug(script, 6, "SetLastCommand company={:02d} cmd={} data={}", s->root_company, cmd, FormatArrayAsHex(data));
s->last_data = data;
s->last_cmd = cmd;
ScriptStorage &s = GetStorage();
Debug(script, 6, "SetLastCommand company={:02d} cmd={} data={}", s.root_company, cmd, FormatArrayAsHex(data));
s.last_data = data;
s.last_cmd = cmd;
}
/* static */ bool ScriptObject::CheckLastCommand(const CommandDataBuffer &data, Commands cmd)
{
ScriptStorage *s = GetStorage();
Debug(script, 6, "CheckLastCommand company={:02d} cmd={} data={}", s->root_company, cmd, FormatArrayAsHex(data));
if (s->last_cmd != cmd) return false;
if (s->last_data != data) return false;
ScriptStorage &s = GetStorage();
Debug(script, 6, "CheckLastCommand company={:02d} cmd={} data={}", s.root_company, cmd, FormatArrayAsHex(data));
if (s.last_cmd != cmd) return false;
if (s.last_data != data) return false;
return true;
}
/* static */ void ScriptObject::SetDoCommandCosts(Money value)
{
GetStorage()->costs = CommandCost(INVALID_EXPENSES, value); // Expense type is never read.
GetStorage().costs = CommandCost(INVALID_EXPENSES, value); // Expense type is never read.
}
/* static */ void ScriptObject::IncreaseDoCommandCosts(Money value)
{
GetStorage()->costs.AddCost(value);
GetStorage().costs.AddCost(value);
}
/* static */ Money ScriptObject::GetDoCommandCosts()
{
return GetStorage()->costs.GetCost();
return GetStorage().costs.GetCost();
}
/* static */ void ScriptObject::SetLastError(ScriptErrorType last_error)
{
GetStorage()->last_error = last_error;
GetStorage().last_error = last_error;
}
/* static */ ScriptErrorType ScriptObject::GetLastError()
{
return GetStorage()->last_error;
return GetStorage().last_error;
}
/* static */ void ScriptObject::SetLastCost(Money last_cost)
{
GetStorage()->last_cost = last_cost;
GetStorage().last_cost = last_cost;
}
/* static */ Money ScriptObject::GetLastCost()
{
return GetStorage()->last_cost;
return GetStorage().last_cost;
}
/* static */ void ScriptObject::SetRoadType(RoadType road_type)
{
GetStorage()->road_type = road_type;
GetStorage().road_type = road_type;
}
/* static */ RoadType ScriptObject::GetRoadType()
{
return GetStorage()->road_type;
return GetStorage().road_type;
}
/* static */ void ScriptObject::SetRailType(RailType rail_type)
{
GetStorage()->rail_type = rail_type;
GetStorage().rail_type = rail_type;
}
/* static */ RailType ScriptObject::GetRailType()
{
return GetStorage()->rail_type;
return GetStorage().rail_type;
}
/* static */ void ScriptObject::SetLastCommandRes(bool res)
{
GetStorage()->last_command_res = res;
GetStorage().last_command_res = res;
}
/* static */ bool ScriptObject::GetLastCommandRes()
{
return GetStorage()->last_command_res;
return GetStorage().last_command_res;
}
/* static */ void ScriptObject::SetLastCommandResData(CommandDataBuffer data)
{
GetStorage()->last_cmd_ret = std::move(data);
GetStorage().last_cmd_ret = std::move(data);
}
/* static */ const CommandDataBuffer &ScriptObject::GetLastCommandResData()
{
return GetStorage()->last_cmd_ret;
return GetStorage().last_cmd_ret;
}
/* static */ void ScriptObject::SetCompany(::CompanyID company)
{
if (GetStorage()->root_company == INVALID_OWNER) GetStorage()->root_company = company;
GetStorage()->company = company;
if (GetStorage().root_company == INVALID_OWNER) GetStorage().root_company = company;
GetStorage().company = company;
_current_company = company;
}
/* static */ ::CompanyID ScriptObject::GetCompany()
{
return GetStorage()->company;
return GetStorage().company;
}
/* static */ ::CompanyID ScriptObject::GetRootCompany()
{
return GetStorage()->root_company;
return GetStorage().root_company;
}
/* static */ bool ScriptObject::CanSuspend()
{
Squirrel *squirrel = ScriptObject::GetActiveInstance().engine;
return GetStorage()->allow_do_command && squirrel->CanSuspend();
return GetStorage().allow_do_command && squirrel->CanSuspend();
}
/* static */ ScriptEventQueue &ScriptObject::GetEventQueue()
{
return GetStorage()->event_queue;
return GetStorage().event_queue;
}
/* static */ ScriptLogTypes::LogData &ScriptObject::GetLogData()
{
return GetStorage()->log_data;
return GetStorage().log_data;
}
/* static */ void ScriptObject::SetCallbackVariable(int index, int value)
{
if (static_cast<size_t>(index) >= GetStorage()->callback_value.size()) GetStorage()->callback_value.resize(index + 1);
GetStorage()->callback_value[index] = value;
if (static_cast<size_t>(index) >= GetStorage().callback_value.size()) GetStorage().callback_value.resize(index + 1);
GetStorage().callback_value[index] = value;
}
/* static */ int ScriptObject::GetCallbackVariable(int index)
{
return GetStorage()->callback_value[index];
return GetStorage().callback_value[index];
}
/* static */ CommandCallbackData *ScriptObject::GetDoCommandCallback()
@ -310,8 +310,8 @@ ScriptObject::DisableDoCommandScope::DisableDoCommandScope()
IncreaseDoCommandCosts(res.GetCost());
if (!_generating_world) {
/* Charge a nominal fee for asynchronously executed commands */
Squirrel *engine = ScriptObject::GetActiveInstance().engine;
Squirrel::DecreaseOps(engine->GetVM(), 100);
Squirrel &engine = *ScriptObject::GetActiveInstance().engine;
Squirrel::DecreaseOps(engine.GetVM(), 100);
}
if (callback != nullptr) {
/* Insert return value into to stack and throw a control code that

View File

@ -100,7 +100,7 @@ void ScriptInstance::Initialize(const std::string &main_script, const std::strin
void ScriptInstance::RegisterAPI()
{
squirrel_register_std(this->engine);
squirrel_register_std(*this->engine);
}
bool ScriptInstance::LoadCompatibilityScript(std::string_view api_version, Subdirectory dir)
@ -318,9 +318,10 @@ void ScriptInstance::CollectGarbage()
}
ScriptStorage *ScriptInstance::GetStorage()
ScriptStorage &ScriptInstance::GetStorage()
{
return this->storage;
assert(this->storage != nullptr);
return *this->storage;
}
ScriptLogTypes::LogData &ScriptInstance::GetLogData()

View File

@ -91,7 +91,7 @@ public:
/**
* Get the storage of this script.
*/
class ScriptStorage *GetStorage();
class ScriptStorage &GetStorage();
/**
* Get the log pointer of this script.
@ -146,7 +146,11 @@ public:
/**
* Get the controller attached to the instance.
*/
class ScriptController *GetController() { return controller; }
class ScriptController &GetController()
{
assert(this->controller != nullptr);
return *this->controller;
}
/**
* Return the "this script died" value

View File

@ -536,7 +536,7 @@ void Squirrel::Initialize()
sq_setforeignptr(this->vm, this);
sq_pushroottable(this->vm);
squirrel_register_global_std(this);
squirrel_register_global_std(*this);
/* Set consts table as delegate of root table, so consts/enums defined via require() are accessible */
sq_pushconsttable(this->vm);

View File

@ -82,20 +82,20 @@ SQInteger SquirrelStd::notifyallexceptions(HSQUIRRELVM vm)
return SQ_ERROR;
}
void squirrel_register_global_std(Squirrel *engine)
void squirrel_register_global_std(Squirrel &engine)
{
/* We don't use squirrel_helper here, as we want to register to the global
* scope and not to a class. */
engine->AddMethod("require", &SquirrelStd::require, ".s");
engine->AddMethod("notifyallexceptions", &SquirrelStd::notifyallexceptions, ".b");
engine.AddMethod("require", &SquirrelStd::require, ".s");
engine.AddMethod("notifyallexceptions", &SquirrelStd::notifyallexceptions, ".b");
}
void squirrel_register_std(Squirrel *engine)
void squirrel_register_std(Squirrel &engine)
{
/* We don't use squirrel_helper here, as we want to register to the global
* scope and not to a class. */
engine->AddMethod("min", &SquirrelStd::min, ".ii");
engine->AddMethod("max", &SquirrelStd::max, ".ii");
engine.AddMethod("min", &SquirrelStd::min, ".ii");
engine.AddMethod("max", &SquirrelStd::max, ".ii");
sqstd_register_mathlib(engine->GetVM());
sqstd_register_mathlib(engine.GetVM());
}

View File

@ -52,12 +52,12 @@ public:
/**
* Register all standard functions we want to give to a script.
*/
void squirrel_register_std(Squirrel *engine);
void squirrel_register_std(Squirrel &engine);
/**
* Register all standard functions that are available on first startup.
* @note this set is very limited, and is only meant to load other scripts and things like that.
*/
void squirrel_register_global_std(Squirrel *engine);
void squirrel_register_global_std(Squirrel &engine);
#endif /* SQUIRREL_STD_HPP */

View File

@ -681,6 +681,11 @@ SettingsContainer &GetSettingsTree()
* Since it's also able to completely disable the scrollwheel will we display it on all platforms anyway */
viewports->Add(new SettingEntry("gui.scrollwheel_scrolling"));
viewports->Add(new SettingEntry("gui.scrollwheel_multiplier"));
viewports->Add(new SettingEntry("gui.gamepad_stick_selection"));
viewports->Add(new SettingEntry("gui.gamepad_deadzone"));
viewports->Add(new SettingEntry("gui.gamepad_sensitivity"));
viewports->Add(new SettingEntry("gui.gamepad_invert_x"));
viewports->Add(new SettingEntry("gui.gamepad_invert_y"));
#ifdef __APPLE__
/* We might need to emulate a right mouse button on mac */
viewports->Add(new SettingEntry("gui.right_mouse_btn_emulation"));

View File

@ -140,6 +140,13 @@ enum ScrollWheelScrollingSetting : uint8_t {
SWS_OFF = 2 ///< Scroll wheel has no effect.
};
/** Settings related to gamepad stick selection. */
enum GamepadStickSelection : uint8_t {
GSS_DISABLED = 0, ///< Gamepad scrolling disabled.
GSS_LEFT_STICK = 1, ///< Use left analog stick for scrolling.
GSS_RIGHT_STICK = 2, ///< Use right analog stick for scrolling.
};
/** Settings related to the GUI and other stuff that is not saved in the savegame. */
struct GUISettings {
bool sg_full_load_any; ///< new full load calculation, any cargo must be full read from pre v93 savegames
@ -183,6 +190,11 @@ struct GUISettings {
uint8_t right_mouse_btn_emulation; ///< should we emulate right mouse clicking?
uint8_t scrollwheel_scrolling; ///< scrolling using the scroll wheel?
uint8_t scrollwheel_multiplier; ///< how much 'wheel' per incoming event from the OS?
uint8_t gamepad_deadzone; ///< deadzone for gamepad analog sticks (0-100)
uint8_t gamepad_sensitivity; ///< sensitivity multiplier for gamepad scrolling
bool gamepad_invert_x; ///< invert X axis for gamepad scrolling?
bool gamepad_invert_y; ///< invert Y axis for gamepad scrolling?
uint8_t gamepad_stick_selection; ///< which stick to use for scrolling (left/right/disabled)
bool timetable_arrival_departure; ///< show arrivals and departures in vehicle timetables
RightClickClose right_click_wnd_close; ///< close window with right click
bool pause_on_newgame; ///< whether to start new games paused or not

View File

@ -3331,7 +3331,7 @@ draw_default_foundation:
auto result = GetRoadStopLayout(ti, stopspec, st, type, view, regs100);
if (result.has_value()) {
if (stopspec->flags.Test(RoadStopSpecFlag::DrawModeRegister)) {
stop_draw_mode = static_cast<RoadStopDrawMode>(regs100[0]);
stop_draw_mode = static_cast<RoadStopDrawModes>(regs100[0]);
}
if (type == StationType::RoadWaypoint && stop_draw_mode.Test(RoadStopDrawMode::WaypGround)) {
draw_ground = true;

View File

@ -912,3 +912,62 @@ post_cb = [](auto) { SetupWidgetDimensions(); ReInitAllWindows(true); }
cat = SC_BASIC
startup = true
[SDTC_VAR]
var = gui.gamepad_deadzone
type = SLE_UINT8
flags = SettingFlag::NotInSave, SettingFlag::NoNetworkSync
def = 10
min = 0
max = 100
interval = 5
str = STR_CONFIG_SETTING_GAMEPAD_DEADZONE
strhelp = STR_CONFIG_SETTING_GAMEPAD_DEADZONE_HELPTEXT
strval = STR_JUST_COMMA
cat = SC_BASIC
startup = true
[SDTC_VAR]
var = gui.gamepad_sensitivity
type = SLE_UINT8
flags = SettingFlag::NotInSave, SettingFlag::NoNetworkSync
def = 10
min = 1
max = 100
interval = 5
str = STR_CONFIG_SETTING_GAMEPAD_SENSITIVITY
strhelp = STR_CONFIG_SETTING_GAMEPAD_SENSITIVITY_HELPTEXT
strval = STR_JUST_COMMA
cat = SC_BASIC
startup = true
[SDTC_BOOL]
var = gui.gamepad_invert_x
flags = SettingFlag::NotInSave, SettingFlag::NoNetworkSync
def = false
str = STR_CONFIG_SETTING_GAMEPAD_INVERT_X
strhelp = STR_CONFIG_SETTING_GAMEPAD_INVERT_X_HELPTEXT
cat = SC_BASIC
startup = true
[SDTC_BOOL]
var = gui.gamepad_invert_y
flags = SettingFlag::NotInSave, SettingFlag::NoNetworkSync
def = false
str = STR_CONFIG_SETTING_GAMEPAD_INVERT_Y
strhelp = STR_CONFIG_SETTING_GAMEPAD_INVERT_Y_HELPTEXT
cat = SC_BASIC
startup = true
[SDTC_VAR]
var = gui.gamepad_stick_selection
type = SLE_UINT8
flags = SettingFlag::NotInSave, SettingFlag::NoNetworkSync, SettingFlag::GuiDropdown
def = GSS_LEFT_STICK
min = GSS_DISABLED
max = GSS_RIGHT_STICK
str = STR_CONFIG_SETTING_GAMEPAD_STICK_SELECTION
strhelp = STR_CONFIG_SETTING_GAMEPAD_STICK_SELECTION_HELPTEXT
strval = STR_CONFIG_SETTING_GAMEPAD_STICK_DISABLED
cat = SC_BASIC
startup = true

View File

@ -427,6 +427,7 @@ struct TimetableWindow : Window {
void DrawTimetablePanel(const Rect &r) const
{
const Vehicle *v = this->vehicle;
if (v->GetNumOrders() == 0) return;
Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
int i = this->vscroll->GetPosition();
VehicleOrderID order_id = (i + 1) / 2;

View File

@ -20,6 +20,7 @@
#include "../fileio_func.h"
#include "../framerate_type.h"
#include "../window_func.h"
#include "../zoom_func.h"
#include "sdl2_v.h"
#include <SDL.h>
#ifdef __EMSCRIPTEN__
@ -524,6 +525,27 @@ bool VideoDriver_SDL_Base::PollEvent()
}
break;
}
case SDL_CONTROLLERDEVICEADDED: {
Debug(driver, 1, "SDL2: Gamepad device added, index: {}", ev.cdevice.which);
/* Try to open the newly connected gamepad */
if (this->gamepad == nullptr) {
this->OpenGamepad();
}
break;
}
case SDL_CONTROLLERDEVICEREMOVED: {
Debug(driver, 1, "SDL2: Gamepad device removed, instance ID: {}", ev.cdevice.which);
/* Close gamepad if it was removed */
if (this->gamepad != nullptr && ev.cdevice.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(this->gamepad))) {
Debug(driver, 1, "SDL2: Current gamepad was removed, closing and reopening");
this->CloseGamepad();
/* Try to open another gamepad if available */
this->OpenGamepad();
}
break;
}
}
return true;
@ -539,6 +561,12 @@ static std::optional<std::string_view> InitializeSDL()
#endif
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) return SDL_GetError();
/* Initialize gamepad subsystem for gamepad scrolling support */
if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) < 0) {
Debug(driver, 1, "SDL2: Failed to initialize gamepad subsystem: {}", SDL_GetError());
}
return std::nullopt;
}
@ -590,6 +618,11 @@ std::optional<std::string_view> VideoDriver_SDL_Base::Start(const StringList &pa
SDL_StopTextInput();
this->edit_box_focused = false;
/* Initialize gamepad for scrolling */
Debug(driver, 1, "SDL2: Attempting to initialize gamepad support");
Debug(driver, 1, "SDL2: Gamepad stick selection setting: {}", _settings_client.gui.gamepad_stick_selection);
this->OpenGamepad();
#ifdef __EMSCRIPTEN__
this->is_game_threaded = false;
#else
@ -601,6 +634,8 @@ std::optional<std::string_view> VideoDriver_SDL_Base::Start(const StringList &pa
void VideoDriver_SDL_Base::Stop()
{
this->CloseGamepad();
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
SDL_QuitSubSystem(SDL_INIT_VIDEO);
if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
SDL_Quit(); // If there's nothing left, quit SDL
@ -629,6 +664,9 @@ void VideoDriver_SDL_Base::InputLoop()
(keys[SDL_SCANCODE_DOWN] ? 8 : 0);
if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
/* Process gamepad input for scrolling */
this->ProcessGamepadInput();
}
void VideoDriver_SDL_Base::LoopOnce()
@ -755,3 +793,84 @@ void VideoDriver_SDL_Base::UnlockVideoBuffer()
this->buffer_locked = false;
}
void VideoDriver_SDL_Base::OpenGamepad()
{
/* Don't open gamepad if already open or if gamepad scrolling is disabled */
if (this->gamepad != nullptr) {
Debug(driver, 1, "SDL2: Gamepad already open, skipping");
return;
}
if (_settings_client.gui.gamepad_stick_selection == GSS_DISABLED) {
Debug(driver, 1, "SDL2: Gamepad scrolling disabled, not opening gamepad");
return;
}
/* Check if any gamepads are available */
int num_gamepads = SDL_NumJoysticks();
Debug(driver, 1, "SDL2: Found {} joystick(s)", num_gamepads);
for (int i = 0; i < num_gamepads; i++) {
if (SDL_IsGameController(i)) {
Debug(driver, 1, "SDL2: Joystick {} is a gamepad, attempting to open", i);
this->gamepad = SDL_GameControllerOpen(i);
if (this->gamepad != nullptr) {
Debug(driver, 1, "SDL2: Opened gamepad: {}", SDL_GameControllerName(this->gamepad));
break;
} else {
Debug(driver, 1, "SDL2: Failed to open gamepad {}: {}", i, SDL_GetError());
}
} else {
Debug(driver, 1, "SDL2: Joystick {} is not a gamepad", i);
}
}
if (this->gamepad == nullptr) {
Debug(driver, 1, "SDL2: No gamepad opened");
}
}
void VideoDriver_SDL_Base::CloseGamepad()
{
if (this->gamepad != nullptr) {
SDL_GameControllerClose(this->gamepad);
this->gamepad = nullptr;
Debug(driver, 1, "SDL2: Closed gamepad");
}
}
void VideoDriver_SDL_Base::ProcessGamepadInput()
{
/* Skip if gamepad is not available */
if (this->gamepad == nullptr) {
static bool logged_no_gamepad = false;
if (!logged_no_gamepad) {
Debug(driver, 2, "SDL2: No gamepad available for input processing");
logged_no_gamepad = true;
}
return;
}
/* Check if gamepad is still connected */
if (!SDL_GameControllerGetAttached(this->gamepad)) {
Debug(driver, 1, "SDL2: Gamepad disconnected, closing and reopening");
this->CloseGamepad();
return;
}
/* Get analog stick values based on stick selection */
Sint16 stick_x = 0, stick_y = 0;
if (_settings_client.gui.gamepad_stick_selection == GSS_LEFT_STICK) {
stick_x = SDL_GameControllerGetAxis(this->gamepad, SDL_CONTROLLER_AXIS_LEFTX);
stick_y = SDL_GameControllerGetAxis(this->gamepad, SDL_CONTROLLER_AXIS_LEFTY);
Debug(driver, 3, "SDL2: Left stick raw values: x={}, y={}", stick_x, stick_y);
} else if (_settings_client.gui.gamepad_stick_selection == GSS_RIGHT_STICK) {
stick_x = SDL_GameControllerGetAxis(this->gamepad, SDL_CONTROLLER_AXIS_RIGHTX);
stick_y = SDL_GameControllerGetAxis(this->gamepad, SDL_CONTROLLER_AXIS_RIGHTY);
Debug(driver, 3, "SDL2: Right stick raw values: x={}, y={}", stick_x, stick_y);
}
/* Use the common gamepad handling function */
HandleGamepadScrolling(stick_x, stick_y, 32767);
}

View File

@ -14,6 +14,10 @@
#include "video_driver.hpp"
/* Forward declaration of SDL_GameController */
struct _SDL_GameController;
typedef struct _SDL_GameController SDL_GameController;
/** The SDL video driver. */
class VideoDriver_SDL_Base : public VideoDriver {
public:
@ -69,6 +73,13 @@ protected:
/** Create the main window. */
virtual bool CreateMainWindow(uint w, uint h, uint flags = 0);
protected:
/** Gamepad support for map scrolling */
SDL_GameController *gamepad = nullptr; ///< Currently opened gamepad.
void OpenGamepad();
void CloseGamepad();
void ProcessGamepadInput();
private:
void LoopOnce();
void MainLoopCleanup();

View File

@ -28,6 +28,7 @@
#include <windows.h>
#include <imm.h>
#include <versionhelpers.h>
#include <xinput.h>
#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
#include <winrt/Windows.UI.ViewManagement.h>
#endif
@ -984,6 +985,9 @@ void VideoDriver_Win32Base::InputLoop()
}
if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
/* Process gamepad input for scrolling */
this->ProcessGamepadInput();
}
bool VideoDriver_Win32Base::PollEvent()
@ -1143,6 +1147,106 @@ void VideoDriver_Win32Base::UnlockVideoBuffer()
this->buffer_locked = false;
}
void VideoDriver_Win32Base::OpenGamepad()
{
/* Don't open gamepad if already open or if gamepad scrolling is disabled */
if (this->gamepad_user_index != XUSER_MAX_COUNT) {
Debug(driver, 1, "Win32: Gamepad already open, skipping");
return;
}
if (_settings_client.gui.gamepad_stick_selection == GSS_DISABLED) {
Debug(driver, 1, "Win32: Gamepad scrolling disabled, not opening gamepad");
return;
}
/* Check for any connected gamepads */
for (DWORD i = 0; i < XUSER_MAX_COUNT; i++) {
XINPUT_STATE state = {};
if (XInputGetState(i, &state) == ERROR_SUCCESS) {
this->gamepad_user_index = i;
Debug(driver, 1, "Win32: Opened gamepad at index {}", i);
return;
}
}
}
void VideoDriver_Win32Base::CloseGamepad()
{
if (this->gamepad_user_index != XUSER_MAX_COUNT) {
this->gamepad_user_index = XUSER_MAX_COUNT;
Debug(driver, 1, "Win32: Closed gamepad");
}
}
void VideoDriver_Win32Base::ProcessGamepadInput()
{
/* Skip if gamepad scrolling is disabled */
if (_settings_client.gui.gamepad_stick_selection == GSS_DISABLED) {
return;
}
/* If no gamepad is currently open, try to reconnect periodically */
if (this->gamepad_user_index == XUSER_MAX_COUNT) {
static bool logged_no_gamepad = false;
/* Only try to reconnect every 60 frames (~1 second at 60 FPS) to avoid spam */
if (this->gamepad_reconnect_timer > 0) {
this->gamepad_reconnect_timer--;
if (!logged_no_gamepad) {
Debug(driver, 2, "Win32: No gamepad available for input processing");
logged_no_gamepad = true;
}
return;
}
/* Try to open gamepad */
this->OpenGamepad();
/* If still no gamepad, set timer for next retry */
if (this->gamepad_user_index == XUSER_MAX_COUNT) {
this->gamepad_reconnect_timer = 60; /* Retry in ~1 second */
if (!logged_no_gamepad) {
Debug(driver, 2, "Win32: No gamepad available for input processing");
logged_no_gamepad = true;
}
return;
} else {
/* Successfully reconnected */
logged_no_gamepad = false;
}
}
/* Get gamepad state */
XINPUT_STATE state = {};
if (XInputGetState(this->gamepad_user_index, &state) != ERROR_SUCCESS) {
Debug(driver, 1, "Win32: Gamepad disconnected, closing and will retry connection");
this->CloseGamepad();
this->gamepad_reconnect_timer = 60; /* Start retry timer */
return;
}
/* Get analog stick values based on stick selection
* Note: XInput uses SHORT values for stick positions, but we have to extend to INT
* to avoid overflow when inverting the Y-axis value */
INT stick_x = 0, stick_y = 0;
if (_settings_client.gui.gamepad_stick_selection == GSS_LEFT_STICK) {
stick_x = state.Gamepad.sThumbLX;
stick_y = state.Gamepad.sThumbLY;
Debug(driver, 3, "Win32: Left stick raw values: x={}, y={}", stick_x, stick_y);
} else if (_settings_client.gui.gamepad_stick_selection == GSS_RIGHT_STICK) {
stick_x = state.Gamepad.sThumbRX;
stick_y = state.Gamepad.sThumbRY;
Debug(driver, 3, "Win32: Right stick raw values: x={}, y={}", stick_x, stick_y);
}
stick_y = -stick_y; // Xinput Y-axis is inverted from other libraries
/* Use the common gamepad handling function */
HandleGamepadScrolling(stick_x, stick_y, 32767);
}
static FVideoDriver_Win32GDI iFVideoDriver_Win32GDI;
@ -1158,6 +1262,11 @@ std::optional<std::string_view> VideoDriver_Win32GDI::Start(const StringList &pa
MarkWholeScreenDirty();
/* Initialize gamepad for scrolling */
Debug(driver, 1, "Win32: Attempting to initialize gamepad support");
Debug(driver, 1, "Win32: Gamepad stick selection setting: {}", _settings_client.gui.gamepad_stick_selection);
this->OpenGamepad();
this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
return std::nullopt;
@ -1165,6 +1274,7 @@ std::optional<std::string_view> VideoDriver_Win32GDI::Start(const StringList &pa
void VideoDriver_Win32GDI::Stop()
{
this->CloseGamepad();
DeleteObject(this->gdi_palette);
DeleteObject(this->dib_sect);
@ -1472,6 +1582,11 @@ std::optional<std::string_view> VideoDriver_Win32OpenGL::Start(const StringList
MarkWholeScreenDirty();
/* Initialize gamepad for scrolling */
Debug(driver, 1, "Win32: Attempting to initialize gamepad support");
Debug(driver, 1, "Win32: Gamepad stick selection setting: {}", _settings_client.gui.gamepad_stick_selection);
this->OpenGamepad();
this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
return std::nullopt;
@ -1479,6 +1594,7 @@ std::optional<std::string_view> VideoDriver_Win32OpenGL::Start(const StringList
void VideoDriver_Win32OpenGL::Stop()
{
this->CloseGamepad();
this->DestroyContext();
this->VideoDriver_Win32Base::Stop();
}

View File

@ -14,6 +14,7 @@
#include <mutex>
#include <condition_variable>
#include <windows.h>
#include <xinput.h>
/** Base class for Windows video drivers. */
class VideoDriver_Win32Base : public VideoDriver {
@ -48,6 +49,13 @@ protected:
bool buffer_locked; ///< Video buffer was locked by the main thread.
/** Gamepad support for map scrolling */
DWORD gamepad_user_index = XUSER_MAX_COUNT; ///< Index of currently opened gamepad (XUSER_MAX_COUNT = no gamepad).
uint32_t gamepad_reconnect_timer = 0; ///< Timer for retrying gamepad connection after disconnect.
void OpenGamepad();
void CloseGamepad();
void ProcessGamepadInput();
Dimension GetScreenSize() const override;
float GetDPIScale() override;
void InputLoop() override;

View File

@ -3572,3 +3572,81 @@ void PickerWindowBase::Close([[maybe_unused]] int data)
ResetObjectToPlace();
this->Window::Close();
}
/**
* Process gamepad analog stick input for viewport scrolling.
* This is a common function that can be used by any video driver that supports gamepads.
* @param stick_x Raw analog stick X value (typically -32768 to 32767 range)
* @param stick_y Raw analog stick Y value (typically -32768 to 32767 range)
* @param max_axis_value Maximum value for the analog stick axes (e.g., 32767 for SDL2)
*/
void HandleGamepadScrolling(int stick_x, int stick_y, int max_axis_value)
{
/* Skip if gamepad stick selection is disabled */
if (_settings_client.gui.gamepad_stick_selection == GSS_DISABLED) {
return;
}
/* Apply deadzone (convert percentage to axis range) */
const int deadzone = (_settings_client.gui.gamepad_deadzone * max_axis_value) / 100;
if (abs(stick_x) < deadzone) stick_x = 0;
if (abs(stick_y) < deadzone) stick_y = 0;
/* Skip if no movement after deadzone */
if (stick_x == 0 && stick_y == 0) {
return;
}
/* Calculate scroll delta with sensitivity */
float sensitivity = _settings_client.gui.gamepad_sensitivity / 10.0f;
int delta_x = (int)(stick_x * sensitivity / (max_axis_value / 16)); // Scale down from axis range
int delta_y = (int)(stick_y * sensitivity / (max_axis_value / 16));
/* Apply axis inversion */
if (_settings_client.gui.gamepad_invert_x) delta_x = -delta_x;
if (_settings_client.gui.gamepad_invert_y) delta_y = -delta_y;
/* Skip if deltas are too small */
if (abs(delta_x) < 1 && abs(delta_y) < 1) {
return;
}
/* Apply scrolling based on cursor position */
if (_game_mode != GM_MENU && _game_mode != GM_BOOTSTRAP) {
Window *target_window = nullptr;
/* Check if cursor is over a window with a viewport */
Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
if (w != nullptr && w->viewport != nullptr) {
/* Check if cursor is actually over the viewport area within the window */
Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
if (pt.x >= w->viewport->left - w->left &&
pt.x < w->viewport->left - w->left + w->viewport->width &&
pt.y >= w->viewport->top - w->top &&
pt.y < w->viewport->top - w->top + w->viewport->height) {
target_window = w;
}
}
/* If no viewport under cursor, use main window */
if (target_window == nullptr) {
target_window = GetMainWindow();
}
/* Apply scrolling to the target viewport */
if (target_window != nullptr && target_window->viewport != nullptr) {
/* Check if the viewport is following a vehicle (similar to mouse scroll behavior) */
if (target_window == GetMainWindow() && target_window->viewport->follow_vehicle != VehicleID::Invalid()) {
/* If following a vehicle, center on it and stop following (like mouse scroll) */
const Vehicle *veh = Vehicle::Get(target_window->viewport->follow_vehicle);
ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
return; // Don't apply gamepad scroll, just like mouse scroll returns ES_NOT_HANDLED
}
/* Apply the scroll using the same method as keyboard scrolling */
target_window->viewport->dest_scrollpos_x += ScaleByZoom(delta_x, target_window->viewport->zoom);
target_window->viewport->dest_scrollpos_y += ScaleByZoom(delta_y, target_window->viewport->zoom);
}
}
}